diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 60dc3de49..b1fb70cc6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -118,7 +118,7 @@ jobs: mac-intel: name: Mac Intel - runs-on: macos-12 + runs-on: macos-13 steps: - name: Checkout sources uses: actions/checkout@v4 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7984e494b..3578feb21 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,14 +13,20 @@ jobs: repolinter: name: Repolinter runs-on: solang-ubuntu-latest + # spdx runs on python 3.10 but not any later versions + container: ubuntu:22.04 steps: + - name: Install Python and npm + run: | + apt-get update + apt-get install -y python3 git npm - name: Checkout sources uses: actions/checkout@v4 - name: Run repolinter run: npx repolinter --rulesetUrl https://raw.githubusercontent.com/hyperledger-labs/hyperledger-community-management-tools/master/repo_structure/repolint.json - uses: enarx/spdx@master with: - licenses: Apache-2.0 MIT + licenses: Apache-2.0 docs: name: Docs @@ -199,7 +205,7 @@ jobs: mac-intel: name: Mac Intel - runs-on: macos-12 + runs-on: macos-13 steps: - name: Checkout sources uses: actions/checkout@v4 @@ -223,7 +229,7 @@ jobs: mac-universal: name: Mac Universal Binary - runs-on: macos-12 + runs-on: macos-13 needs: [mac-arm, mac-intel] steps: - uses: actions/download-artifact@v4.1.8 @@ -319,6 +325,8 @@ jobs: with: node-version: '16' - uses: dtolnay/rust-toolchain@1.81.0 + with: + target: wasm32-unknown-unknown - uses: actions/download-artifact@v4.1.8 with: name: solang-linux-x86-64 @@ -329,7 +337,7 @@ jobs: echo "$(pwd)/bin" >> $GITHUB_PATH - name: Install Soroban - run: cargo install --locked soroban-cli --version 22.0.0 + run: cargo install --locked stellar-cli --version 22.0.0 - name: Add cargo install location to PATH run: echo "$HOME/.cargo/bin" >> $GITHUB_PATH - run: npm install @@ -337,6 +345,9 @@ jobs: - name: Build Solang contracts run: npm run build working-directory: ./integration/soroban + - name: Build rust contracts + run: soroban contract build --profile release-with-logs + working-directory: ./integration/soroban/rust/contracts - name: Setup Soroban enivronment run: npm run setup working-directory: ./integration/soroban diff --git a/.gitignore b/.gitignore index 9af78a6a2..43c419a5e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,8 +3,16 @@ Cargo.lock /target **/*.rs.bk *.ll -tests/.tmp* -tests/create_me/ +/tests/.tmp* +/tests/create_me/ +/test_snapshots/ .helix/ .vscode/ + +/test_snapshots + +# Exclude macOS system files +.DS_Store +# Recursively ignore all .DS_Store files +**/.DS_Store \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index fd8e411ef..c29534b18 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,34 +1,52 @@ [package] name = "solang" version = "0.3.3" -authors = ["Sean Young ", "Lucas Steuernagel ", "Cyrill Leutwiler "] +authors = [ + "Sean Young ", + "Lucas Steuernagel ", + "Cyrill Leutwiler ", +] repository = "https://github.com/hyperledger-solang/solang" documentation = "https://solang.readthedocs.io/" license = "Apache-2.0" build = "build.rs" description = "Solang Solidity Compiler" -keywords = [ "solidity", "compiler", "solana", "polkadot", "substrate" ] +keywords = ["solidity", "compiler", "solana", "polkadot", "substrate"] rust-version = "1.81.0" edition = "2021" -exclude = [ "/.*", "/docs", "/examples", "/solana-library", "/tests", "/integration", "/vscode", "/testdata" ] +exclude = [ + "/.*", + "/docs", + "/examples", + "/solana-library", + "/tests", + "/integration", + "/vscode", + "/testdata", +] [build-dependencies] cc = "1.0" [dependencies] +llvm-sys = "160.0" regex = "1" rand = "0.8" -num-bigint = { version = "0.4", features = ["rand"]} +num-bigint = { version = "0.4", features = ["rand"] } num-traits = "0.2" num-integer = "0.1" -clap = {version = "4.5", features = ["derive"]} +clap = { version = "4.5", features = ["derive"] } clap_complete = "4.5" hex = "0.4" tiny-keccak = { version = "2.0", features = ["keccak"] } serde_json = "1.0" serde = "1.0" serde_derive = { version = "1.0" } -inkwell = { version = "0.4.0", features = ["target-webassembly", "no-libffi-linking", "llvm16-0"], optional = true } +inkwell = { version = "0.4.0", features = [ + "target-webassembly", + "no-libffi-linking", + "llvm16-0", +], optional = true } blake2-rfc = "0.2.18" handlebars = "5.1" contract-metadata = "4.0.2" @@ -36,7 +54,11 @@ semver = { version = "1.0", features = ["serde"] } tempfile = "3.10" libc = { version = "0.2", optional = true } tower-lsp = { version = "0.20", optional = true } -tokio = { version = "1.27", features = ["rt", "io-std", "macros"], optional = true } +tokio = { version = "1.27", features = [ + "rt", + "io-std", + "macros", +], optional = true } base58 = "0.2.0" sha2 = "0.10" ripemd = "0.1" @@ -71,7 +93,10 @@ forge-fmt = { path = "fmt", optional = true } # We don't use ethers-core directly, but need the correct version for the # build to work. ethers-core = { version = "2.0.10", optional = true } -soroban-sdk = { version = "22.0.0-rc.3.2", features = ["testutils"], optional = true } +soroban-sdk = { version = "22.0.0-rc.3.2", features = [ + "testutils", +], optional = true } + [dev-dependencies] num-derive = "0.4" @@ -91,7 +116,7 @@ rayon = "1" walkdir = "2.4" ink_primitives = "5.0.0" wasm_host_attr = { path = "tests/wasm_host_attr" } -num-bigint = { version = "0.4", features = ["rand", "serde"]} +num-bigint = { version = "0.4", features = ["rand", "serde"] } [package.metadata.docs.rs] no-default-features = true @@ -104,7 +129,13 @@ soroban = ["soroban-sdk"] default = ["llvm", "wasm_opt", "language_server", "soroban"] llvm = ["inkwell", "libc"] wasm_opt = ["llvm", "wasm-opt", "contract-build"] -language_server = ["tower-lsp", "forge-fmt", "ethers-core", "tokio", "rust-lapper"] +language_server = [ + "tower-lsp", + "forge-fmt", + "ethers-core", + "tokio", + "rust-lapper", +] [workspace] members = ["solang-parser", "fmt", "tests/wasm_host_attr"] diff --git a/counter.abi b/counter.abi new file mode 100644 index 000000000..6e9148bc2 --- /dev/null +++ b/counter.abi @@ -0,0 +1 @@ +[{"name":"count","type":"function","inputs":[],"outputs":[{"name":"count","type":"uint64","internalType":"uint64"}],"stateMutability":"view"},{"name":"increment","type":"function","inputs":[],"outputs":[{"name":"","type":"uint64","internalType":"uint64"}],"stateMutability":"nonpayable"},{"name":"decrement","type":"function","inputs":[],"outputs":[{"name":"","type":"uint64","internalType":"uint64"}],"stateMutability":"nonpayable"},{"name":"additionu32","type":"function","inputs":[{"name":"a","type":"uint32","internalType":"uint32"},{"name":"b","type":"uint32","internalType":"uint32"}],"outputs":[{"name":"","type":"uint32","internalType":"uint32"}],"stateMutability":"nonpayable"}] \ No newline at end of file diff --git a/counter.wasm b/counter.wasm new file mode 100644 index 000000000..a8d193253 Binary files /dev/null and b/counter.wasm differ diff --git a/incrementer.abi b/incrementer.abi new file mode 100644 index 000000000..51f6914ab --- /dev/null +++ b/incrementer.abi @@ -0,0 +1 @@ +[{"type":"constructor","inputs":[{"name":"initvalue","type":"uint32","internalType":"uint32"}],"stateMutability":"nonpayable"},{"name":"inc","type":"function","inputs":[{"name":"by","type":"uint32","internalType":"uint32"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"add","type":"function","inputs":[{"name":"a","type":"uint32","internalType":"uint32"},{"name":"b","type":"uint32","internalType":"uint32"}],"outputs":[{"name":"","type":"uint32","internalType":"uint32"}],"stateMutability":"view"},{"name":"get","type":"function","inputs":[],"outputs":[{"name":"","type":"uint32","internalType":"uint32"}],"stateMutability":"view"}] \ No newline at end of file diff --git a/incrementer.wasm b/incrementer.wasm new file mode 100644 index 000000000..27a89da53 Binary files /dev/null and b/incrementer.wasm differ diff --git a/integration/.DS_Store b/integration/.DS_Store new file mode 100644 index 000000000..d037ded43 Binary files /dev/null and b/integration/.DS_Store differ diff --git a/integration/anchor/target/.rustc_info.json b/integration/anchor/target/.rustc_info.json new file mode 100644 index 000000000..b7a1f3ef6 --- /dev/null +++ b/integration/anchor/target/.rustc_info.json @@ -0,0 +1 @@ +{"rustc_fingerprint":13881514899064403785,"outputs":{"15729799797837862367":{"success":true,"status":"","code":0,"stdout":"___\nlib___.rlib\nlib___.dylib\nlib___.dylib\nlib___.a\nlib___.dylib\n/Users/ahmadsameh/.rustup/toolchains/stable-x86_64-apple-darwin\noff\npacked\nunpacked\n___\ndebug_assertions\npanic=\"unwind\"\nproc_macro\ntarget_abi=\"\"\ntarget_arch=\"x86_64\"\ntarget_endian=\"little\"\ntarget_env=\"\"\ntarget_family=\"unix\"\ntarget_feature=\"cmpxchg16b\"\ntarget_feature=\"fxsr\"\ntarget_feature=\"sse\"\ntarget_feature=\"sse2\"\ntarget_feature=\"sse3\"\ntarget_feature=\"sse4.1\"\ntarget_feature=\"ssse3\"\ntarget_has_atomic=\"128\"\ntarget_has_atomic=\"16\"\ntarget_has_atomic=\"32\"\ntarget_has_atomic=\"64\"\ntarget_has_atomic=\"8\"\ntarget_has_atomic=\"ptr\"\ntarget_os=\"macos\"\ntarget_pointer_width=\"64\"\ntarget_vendor=\"apple\"\nunix\n","stderr":""},"4614504638168534921":{"success":true,"status":"","code":0,"stdout":"rustc 1.83.0 (90b35a623 2024-11-26)\nbinary: rustc\ncommit-hash: 90b35a6239c3d8bdabc530a6a0816f7ff89a0aaf\ncommit-date: 2024-11-26\nhost: x86_64-apple-darwin\nrelease: 1.83.0\nLLVM version: 19.1.1\n","stderr":""}},"successes":{}} \ No newline at end of file diff --git a/integration/soroban/Error.abi b/integration/soroban/Error.abi new file mode 100644 index 000000000..8744a6e40 --- /dev/null +++ b/integration/soroban/Error.abi @@ -0,0 +1 @@ +[{"name":"decrement","type":"function","inputs":[],"outputs":[{"name":"","type":"uint64","internalType":"uint64"}],"stateMutability":"nonpayable"}] \ No newline at end of file diff --git a/integration/soroban/Error.wasm b/integration/soroban/Error.wasm new file mode 100644 index 000000000..def058356 Binary files /dev/null and b/integration/soroban/Error.wasm differ diff --git a/integration/soroban/counter.abi b/integration/soroban/counter.abi new file mode 100644 index 000000000..6e9148bc2 --- /dev/null +++ b/integration/soroban/counter.abi @@ -0,0 +1 @@ +[{"name":"count","type":"function","inputs":[],"outputs":[{"name":"count","type":"uint64","internalType":"uint64"}],"stateMutability":"view"},{"name":"increment","type":"function","inputs":[],"outputs":[{"name":"","type":"uint64","internalType":"uint64"}],"stateMutability":"nonpayable"},{"name":"decrement","type":"function","inputs":[],"outputs":[{"name":"","type":"uint64","internalType":"uint64"}],"stateMutability":"nonpayable"},{"name":"additionu32","type":"function","inputs":[{"name":"a","type":"uint32","internalType":"uint32"},{"name":"b","type":"uint32","internalType":"uint32"}],"outputs":[{"name":"","type":"uint32","internalType":"uint32"}],"stateMutability":"nonpayable"}] \ No newline at end of file diff --git a/integration/soroban/counter.sol b/integration/soroban/counter.sol index 3d289ba33..f881da0de 100644 --- a/integration/soroban/counter.sol +++ b/integration/soroban/counter.sol @@ -10,4 +10,9 @@ contract counter { count -= 1; return count; } + + function additionu32 (uint32 a , uint32 b) public returns (uint32){ + return a+b; + } + } diff --git a/integration/soroban/counter.spec.js b/integration/soroban/counter.spec.js index fce1d4b6a..033a4b52a 100644 --- a/integration/soroban/counter.spec.js +++ b/integration/soroban/counter.spec.js @@ -4,6 +4,7 @@ import { expect } from 'chai'; import path from 'path'; import { fileURLToPath } from 'url'; import { call_contract_function } from './test_helpers.js'; +import exp from 'constants'; const __filename = fileURLToPath(import.meta.url); const dirname = path.dirname(__filename); @@ -13,7 +14,7 @@ describe('Counter', () => { const server = new StellarSdk.SorobanRpc.Server( "https://soroban-testnet.stellar.org:443", ); - + console.log('server', server); let contractAddr; let contract; before(async () => { @@ -21,9 +22,10 @@ describe('Counter', () => { console.log('Setting up counter contract tests...'); // read secret from file - const secret = readFileSync('alice.txt', 'utf8').trim(); + const secret = readFileSync('/Users/ahmadsameh/Desktop/Work/salahswork/Soroban/solang/integration/soroban/alice.txt', 'utf8').trim(); keypair = StellarSdk.Keypair.fromSecret(secret); + let contractIdFile = path.join(dirname, '.soroban', 'contract-ids', 'counter.txt'); // read contract address from file contractAddr = readFileSync(contractIdFile, 'utf8').trim().toString(); @@ -35,6 +37,7 @@ describe('Counter', () => { it('get correct initial counter', async () => { // get the count let count = await call_contract_function("count", server, keypair, contract); + console.log(`initial counter is: ${count}`); expect(count.toString()).eq("10"); }); @@ -46,6 +49,18 @@ describe('Counter', () => { let count = await call_contract_function("count", server, keypair, contract); expect(count.toString()).eq("11"); }); + + it('adding two numbers', async () => { + // add two numbers + let args = [ + StellarSdk.xdr.ScVal.scvU32(30), + StellarSdk.xdr.ScVal.scvU32(40) + ]; + + let result = await call_contract_function("additionu32", server, keypair, contract, ...args); // let returnValue = result.returnValue().value().toString(); + console.log(`additionu32 output is: ${result}`); + expect(result.toString()).eq("70"); + }); }); diff --git a/integration/soroban/counter.wasm b/integration/soroban/counter.wasm new file mode 100644 index 000000000..e27209be9 Binary files /dev/null and b/integration/soroban/counter.wasm differ diff --git a/integration/soroban/package.json b/integration/soroban/package.json index d6d16f60a..a63e321be 100644 --- a/integration/soroban/package.json +++ b/integration/soroban/package.json @@ -1,23 +1,23 @@ { - "type": "module", - "dependencies": { - "@stellar/stellar-sdk": "^12.0.1", - "chai": "^5.1.1", - "dotenv": "^16.4.5", - "mocha": "^10.4.0" - }, - "scripts": { - "build": "solang compile *.sol --target soroban && solang compile storage_types.sol --target soroban --release", - "setup": "node setup.js", - "test": "mocha *.spec.js --timeout 100000" - }, - "devDependencies": { - "@eslint/js": "^9.4.0", - "@types/mocha": "^10.0.6", - "eslint": "^9.4.0", - "expect": "^29.7.0", - "globals": "^15.4.0", - "typescript": "^5.4.5" - } + "type": "module", + "dependencies": { + "@stellar/stellar-sdk": "^12.0.1", + "chai": "^5.1.1", + "dotenv": "^16.4.7", + "mocha": "^10.4.0" + }, + "scripts": { + "build": "solang compile *.sol --target soroban && solang compile counter.sol --target soroban --release", + "setup": "node setup.js", + "test": "mocha *.spec.js --timeout 100000", + "testcounter": "mocha counter.spec.js --timeout 100000" + }, + "devDependencies": { + "@eslint/js": "^9.4.0", + "@types/mocha": "^10.0.6", + "eslint": "^9.4.0", + "expect": "^29.7.0", + "globals": "^15.4.0", + "typescript": "^5.4.5" } - \ No newline at end of file +} \ No newline at end of file diff --git a/integration/soroban/storage_types.abi b/integration/soroban/storage_types.abi new file mode 100644 index 000000000..1488d7a99 --- /dev/null +++ b/integration/soroban/storage_types.abi @@ -0,0 +1 @@ +[{"name":"sesa","type":"function","inputs":[],"outputs":[{"name":"sesa","type":"uint64","internalType":"uint64"}],"stateMutability":"view"},{"name":"sesa1","type":"function","inputs":[],"outputs":[{"name":"sesa1","type":"uint64","internalType":"uint64"}],"stateMutability":"view"},{"name":"sesa2","type":"function","inputs":[],"outputs":[{"name":"sesa2","type":"uint64","internalType":"uint64"}],"stateMutability":"view"},{"name":"sesa3","type":"function","inputs":[],"outputs":[{"name":"sesa3","type":"uint64","internalType":"uint64"}],"stateMutability":"view"},{"name":"inc","type":"function","inputs":[],"outputs":[],"stateMutability":"nonpayable"},{"name":"dec","type":"function","inputs":[],"outputs":[],"stateMutability":"nonpayable"}] \ No newline at end of file diff --git a/integration/soroban/storage_types.wasm b/integration/soroban/storage_types.wasm new file mode 100644 index 000000000..b93f1a1de Binary files /dev/null and b/integration/soroban/storage_types.wasm differ diff --git a/integration/soroban/test_helpers.js b/integration/soroban/test_helpers.js index 1421a6add..7c08b1431 100644 --- a/integration/soroban/test_helpers.js +++ b/integration/soroban/test_helpers.js @@ -1,13 +1,13 @@ import * as StellarSdk from '@stellar/stellar-sdk'; -export async function call_contract_function(method, server, keypair, contract) { +export async function call_contract_function(method, server, keypair, contract, ...params) { let res = null; try { let builtTransaction = new StellarSdk.TransactionBuilder(await server.getAccount(keypair.publicKey()), { fee: StellarSdk.BASE_FEE, networkPassphrase: StellarSdk.Networks.TESTNET, - }).addOperation(contract.call(method)).setTimeout(30).build(); + }).addOperation(contract.call(method, ...params)).setTimeout(30).build(); let preparedTransaction = await server.prepareTransaction(builtTransaction); diff --git a/integration/subxt-tests/.DS_Store b/integration/subxt-tests/.DS_Store new file mode 100644 index 000000000..5e9e45c75 Binary files /dev/null and b/integration/subxt-tests/.DS_Store differ diff --git a/node_modules/.bin/node-gyp-build b/node_modules/.bin/node-gyp-build new file mode 120000 index 000000000..671c6ebce --- /dev/null +++ b/node_modules/.bin/node-gyp-build @@ -0,0 +1 @@ +../node-gyp-build/bin.js \ No newline at end of file diff --git a/node_modules/.bin/node-gyp-build-optional b/node_modules/.bin/node-gyp-build-optional new file mode 120000 index 000000000..46d347e6b --- /dev/null +++ b/node_modules/.bin/node-gyp-build-optional @@ -0,0 +1 @@ +../node-gyp-build/optional.js \ No newline at end of file diff --git a/node_modules/.bin/node-gyp-build-test b/node_modules/.bin/node-gyp-build-test new file mode 120000 index 000000000..d11de1bec --- /dev/null +++ b/node_modules/.bin/node-gyp-build-test @@ -0,0 +1 @@ +../node-gyp-build/build-test.js \ No newline at end of file diff --git a/node_modules/.bin/sha.js b/node_modules/.bin/sha.js new file mode 120000 index 000000000..3c761051a --- /dev/null +++ b/node_modules/.bin/sha.js @@ -0,0 +1 @@ +../sha.js/bin.js \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 000000000..e06412fcf --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,373 @@ +{ + "name": "solang", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@stellar/js-xdr": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@stellar/js-xdr/-/js-xdr-3.1.2.tgz", + "integrity": "sha512-VVolPL5goVEIsvuGqDc5uiKxV03lzfWdvYg1KikvwheDmTBO68CKDji3bAZ/kppZrx5iTA8z3Ld5yuytcvhvOQ==" + }, + "node_modules/@stellar/stellar-base": { + "version": "13.0.1", + "resolved": "https://registry.npmjs.org/@stellar/stellar-base/-/stellar-base-13.0.1.tgz", + "integrity": "sha512-Xbd12mc9Oj/130Tv0URmm3wXG77XMshZtZ2yNCjqX5ZbMD5IYpbBs3DVCteLU/4SLj/Fnmhh1dzhrQXnk4r+pQ==", + "dependencies": { + "@stellar/js-xdr": "^3.1.2", + "base32.js": "^0.1.0", + "bignumber.js": "^9.1.2", + "buffer": "^6.0.3", + "sha.js": "^2.3.6", + "tweetnacl": "^1.0.3" + }, + "optionalDependencies": { + "sodium-native": "^4.3.0" + } + }, + "node_modules/@stellar/stellar-sdk": { + "version": "13.1.0", + "resolved": "https://registry.npmjs.org/@stellar/stellar-sdk/-/stellar-sdk-13.1.0.tgz", + "integrity": "sha512-ARQkUdyGefXdTgwSF0eONkzv/geAqUfyfheJ9Nthz6GAr5b41fNwWW9UtE8JpXC4IpvE3t5elIUN5hKJzASN9w==", + "dependencies": { + "@stellar/stellar-base": "^13.0.1", + "axios": "^1.7.9", + "bignumber.js": "^9.1.2", + "eventsource": "^2.0.2", + "feaxios": "^0.0.23", + "randombytes": "^2.1.0", + "toml": "^3.0.0", + "urijs": "^1.19.1" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "engines": { + "node": ">=12" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/axios": { + "version": "1.7.9", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz", + "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/base32.js": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/base32.js/-/base32.js-0.1.0.tgz", + "integrity": "sha512-n3TkB02ixgBOhTvANakDb4xaMXnYUVkNoRFJjQflcqMQhyEKxEHdj3E6N8t8sUQ0mjH/3/JxzlXuz3ul/J90pQ==", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/bignumber.js": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.1.2.tgz", + "integrity": "sha512-2/mKyZH9K85bzOEfhXDBFZTGd1CTs+5IHpeFQo9luiBG7hghdC851Pj2WAhb6E3R6b9tZj/XKhbg4fum+Kepug==", + "engines": { + "node": "*" + } + }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/chai": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.1.2.tgz", + "integrity": "sha512-aGtmf24DW6MLHHG5gCx4zaI3uBq3KRtxeVs0DjFH6Z0rDNbsvTxFASFvdj79pxjxZ8/5u3PIiN3IwEIQkiiuPw==", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/check-error": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.1.tgz", + "integrity": "sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==", + "engines": { + "node": ">= 16" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "engines": { + "node": ">=6" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/eventsource": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-2.0.2.tgz", + "integrity": "sha512-IzUmBGPR3+oUG9dUeXynyNmf91/3zUSJg1lCktzKw47OXuhco54U3r9B7O4XX+Rb1Itm9OZ2b0RkTs10bICOxA==", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/feaxios": { + "version": "0.0.23", + "resolved": "https://registry.npmjs.org/feaxios/-/feaxios-0.0.23.tgz", + "integrity": "sha512-eghR0A21fvbkcQBgZuMfQhrXxJzC0GNUGC9fXhBge33D+mFDTwl0aJ35zoQQn575BhyjQitRc5N4f+L4cP708g==", + "dependencies": { + "is-retry-allowed": "^3.0.0" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz", + "integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/is-retry-allowed": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-3.0.0.tgz", + "integrity": "sha512-9xH0xvoggby+u0uGF7cZXdrutWiBiaFG8ZT4YFPXL8NzkyAwX3AKGLeFQLvzDpM430+nDFBZ1LHkie/8ocL06A==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/loupe": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.1.2.tgz", + "integrity": "sha512-23I4pFZHmAemUnz8WZXbYRSKYj801VDaNv9ETuMh7IrMc7VuVVSo+Z9iLE3ni30+U48iDWfi30d3twAXBYmnCg==" + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-gyp-build": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", + "optional": true, + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/pathval": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.0.tgz", + "integrity": "sha512-vE7JKRyES09KiunauX7nd2Q9/L7lhok4smP9RZTDeD4MVs72Dp2qNFVz39Nz5a0FVEW0BJR6C0DYrq6unoziZA==", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "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" + } + ] + }, + "node_modules/setup": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/setup/-/setup-0.0.3.tgz", + "integrity": "sha512-NcuGT1k9V3jdwcNdZzpnO6h2WtLMieaIVRMWeQvlSVRMB6b51T3jeUBSeBzP5Mmqy50viW5y7LRaMaTm/MZ4CA==" + }, + "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==", + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + }, + "bin": { + "sha.js": "bin.js" + } + }, + "node_modules/sodium-native": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/sodium-native/-/sodium-native-4.3.1.tgz", + "integrity": "sha512-YdP64gAdpIKHfL4ttuX4aIfjeunh9f+hNeQJpE9C8UMndB3zkgZ7YmmGT4J2+v6Ibyp6Wem8D1TcSrtdW0bqtg==", + "optional": true, + "dependencies": { + "node-gyp-build": "^4.8.0" + } + }, + "node_modules/toml": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/toml/-/toml-3.0.0.tgz", + "integrity": "sha512-y/mWCZinnvxjTKYhJ+pYxwD0mRLVvOtdS2Awbgxln6iEnt4rk0yBxeSBHkGJcPucRiG0e55mwWp+g/05rsrd6w==" + }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==" + }, + "node_modules/urijs": { + "version": "1.19.11", + "resolved": "https://registry.npmjs.org/urijs/-/urijs-1.19.11.tgz", + "integrity": "sha512-HXgFDgDommxn5/bIv0cnQZsPhHDA90NPHD6+c/v21U5+Sx5hoP8+dP9IZXBU1gIfvdRfhG8cel9QNPeionfcCQ==" + } + } +} diff --git a/node_modules/@stellar/js-xdr/.eslintrc.js b/node_modules/@stellar/js-xdr/.eslintrc.js new file mode 100644 index 000000000..b36e0aece --- /dev/null +++ b/node_modules/@stellar/js-xdr/.eslintrc.js @@ -0,0 +1,10 @@ +module.exports = { + env: { + node: true + }, + extends: ['eslint:recommended', 'plugin:node/recommended'], + rules: { + 'node/no-unpublished-require': 0, + indent: ['warn', 2] + } +}; diff --git a/node_modules/@stellar/js-xdr/.github/ISSUE_TEMPLATE/bug_report.md b/node_modules/@stellar/js-xdr/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..2990733d3 --- /dev/null +++ b/node_modules/@stellar/js-xdr/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,27 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**What version are you on?** +Check `yarn.lock` or `package-lock.json` to find out precisely what version of 'js-xdr' you're running. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Additional context** +Add any other context about the problem here. diff --git a/node_modules/@stellar/js-xdr/.github/ISSUE_TEMPLATE/feature_request.md b/node_modules/@stellar/js-xdr/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..bbcbbe7d6 --- /dev/null +++ b/node_modules/@stellar/js-xdr/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/node_modules/@stellar/js-xdr/.github/workflows/codeql.yml b/node_modules/@stellar/js-xdr/.github/workflows/codeql.yml new file mode 100644 index 000000000..11d7865b5 --- /dev/null +++ b/node_modules/@stellar/js-xdr/.github/workflows/codeql.yml @@ -0,0 +1,43 @@ +name: "CodeQL" + +on: + push: + branches: [ "master" ] + pull_request: + branches: [ "master" ] + schedule: + - cron: '35 22 * * 5' + +jobs: + analyze: + name: Analyze (${{ matrix.language }}) + runs-on: ubuntu-latest + timeout-minutes: 360 + permissions: + # required for all workflows + security-events: write + + strategy: + fail-fast: false + matrix: + include: + - language: javascript-typescript + build-mode: none + - language: ruby + build-mode: none + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.build-mode }} + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 + with: + category: "/language:${{matrix.language}}" diff --git a/node_modules/@stellar/js-xdr/.github/workflows/npm-publish.yml b/node_modules/@stellar/js-xdr/.github/workflows/npm-publish.yml new file mode 100644 index 000000000..9a6c9e49b --- /dev/null +++ b/node_modules/@stellar/js-xdr/.github/workflows/npm-publish.yml @@ -0,0 +1,40 @@ +name: npm publish +on: + release: + types: [published] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Install Node + uses: actions/setup-node@v3 + with: + node-version: '18.x' + registry-url: 'https://registry.npmjs.org' + always-auth: true + + - name: Install Dependencies + run: yarn + + - name: Build & Test + run: yarn build && yarn test + + - name: Publish npm packages + run: | + yarn publish --access public + sed -i -e 's#"@stellar/js-xdr"#"js-xdr"#' package.json + yarn publish + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + - name: Publish npm package under old scope + run: | + V=$(cat package.json | jq '.version' | sed -e 's/\"//g') + echo "Deprecating js-xdr@$V" + npm deprecate js-xdr@"<= $V" "⚠️ This package has moved to @stellar/js-xdr! 🚚" + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/node_modules/@stellar/js-xdr/.github/workflows/tests.yml b/node_modules/@stellar/js-xdr/.github/workflows/tests.yml new file mode 100644 index 000000000..b6b1cde41 --- /dev/null +++ b/node_modules/@stellar/js-xdr/.github/workflows/tests.yml @@ -0,0 +1,30 @@ +name: Tests + +on: + push: + branches: [ master ] + pull_request: + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Use Node.js 18 + uses: actions/setup-node@v3 + with: + node-version: 18 + + - name: Install Dependencies + run: yarn + + - name: Build All + run: yarn build + + - name: Run Tests + run: yarn test + + - name: Check Code Formatting + run: yarn fmt && (git diff-index --quiet HEAD; git diff) diff --git a/node_modules/@stellar/js-xdr/.prettierignore b/node_modules/@stellar/js-xdr/.prettierignore new file mode 100644 index 000000000..d5c6b6389 --- /dev/null +++ b/node_modules/@stellar/js-xdr/.prettierignore @@ -0,0 +1,4 @@ +/package.json +/node_modules +/lib +/dist diff --git a/node_modules/@stellar/js-xdr/.travis.yml b/node_modules/@stellar/js-xdr/.travis.yml new file mode 100644 index 000000000..980df79e4 --- /dev/null +++ b/node_modules/@stellar/js-xdr/.travis.yml @@ -0,0 +1,25 @@ +language: node_js +node_js: + - 10 + - 11 + - 12 +cache: + directories: + - node_modules +services: + - xvfb +script: yarn test +notifications: + slack: + secure: Bu3OZ0Cdy8eq0IMoLJmadDba8Yyb9ajobKocfp8V7/vfOjpIVXdFrGMqfckkZ22uiWxHCsYEX1ahQ77zTjbO3tNq1CTmSgEAWaqqMVz1iIVNhSoeHRfYDa9r1sKFpJv1KEz+j/8i2phcR5MDE6cGK+byJmjfjcnkP1XoNiupuck= +before_deploy: + - yarn build +deploy: + provider: npm + email: npm@stellar.org + api_key: $NPM_TOKEN + skip_cleanup: true + on: + tags: true + repo: stellar/js-xdr + branch: master diff --git a/node_modules/@stellar/js-xdr/CHANGELOG.md b/node_modules/@stellar/js-xdr/CHANGELOG.md new file mode 100644 index 000000000..9f8f79c19 --- /dev/null +++ b/node_modules/@stellar/js-xdr/CHANGELOG.md @@ -0,0 +1,130 @@ +# Changelog + +All notable changes to this project will be documented in this file. This +project adheres to [Semantic Versioning](http://semver.org/). + +## Unreleased + + +## [v3.1.2](https://github.com/stellar/js-xdr/compare/v3.1.1...v3.1.2) + +### Fixed +* Increase robustness of compatibility across multiple `js-xdr` instances in an environment ([#122](https://github.com/stellar/js-xdr/pull/122)). + + +## [v3.1.1](https://github.com/stellar/js-xdr/compare/v3.1.0...v3.1.1) + +### Fixed +* Add compatibility with pre-ES2016 environments (like some React Native JS compilers) by adding a custom `Buffer.subarray` polyfill ([#118](https://github.com/stellar/js-xdr/pull/118)). + + +## [v3.1.0](https://github.com/stellar/js-xdr/compare/v3.0.1...v3.1.0) + +### Added +* The raw, underlying `XdrReader` and `XdrWriter` types are now exposed by the library for reading without consuming the entire stream ([#116](https://github.com/stellar/js-xdr/pull/116)). + +### Fixed +* Added additional type checks for passing a bytearray-like object to `XdrReader`s and improves the error with details ([#116](https://github.com/stellar/js-xdr/pull/116)). + + +## [v3.0.1](https://github.com/stellar/js-xdr/compare/v3.0.0...v3.0.1) + +### Fixes +- This package is now being published to `@stellar/js-xdr` on NPM. +- The versions at `js-xdr` are now considered **deprecated** ([#111](https://github.com/stellar/js-xdr/pull/111)). +- Misc. dependencies have been upgraded ([#104](https://github.com/stellar/js-xdr/pull/104), [#106](https://github.com/stellar/js-xdr/pull/106), [#107](https://github.com/stellar/js-xdr/pull/107), [#108](https://github.com/stellar/js-xdr/pull/108), [#105](https://github.com/stellar/js-xdr/pull/105)). + + +## [v3.0.0](https://github.com/stellar/js-xdr/compare/v2.0.0...v3.0.0) + +### Breaking Change +- Add support for easily encoding integers larger than 32 bits ([#100](https://github.com/stellar/js-xdr/pull/100)). This (partially) breaks the API for creating `Hyper` and `UnsignedHyper` instances. Previously, you would pass `low` and `high` parts to represent the lower and upper 32 bits. Now, you can pass the entire 64-bit value directly as a `bigint` or `string` instance, or as a list of "chunks" like before, e.g.: + +```diff +-new Hyper({ low: 1, high: 1 }); // representing (1 << 32) + 1 = 4294967297n ++new Hyper(4294967297n); ++new Hyper("4294967297"); ++new Hyper(1, 1); +``` + + +## [v2.0.0](https://github.com/stellar/js-xdr/compare/v1.3.0...v2.0.0) + +- Refactor XDR serialization/deserialization logic ([#91](https://github.com/stellar/js-xdr/pull/91)). +- Replace `long` dependency with native `BigInt` arithmetics. +- Replace `lodash` dependency with built-in Array and Object methods, iterators. +- Add `buffer` dependency for WebPack browser polyfill. +- Update devDependencies to more recent versions, modernize bundler pipeline. +- Automatically grow underlying buffer on writes (#84 fixed). +- Always check that the entire read buffer is consumed (#32 fixed). +- Check actual byte size of the string on write (#33 fixed). +- Fix babel-polyfill build warnings (#34 fixed). +- Upgrade dependencies to their latest versions ([#92](https://github.com/stellar/js-xdr/pull/92)). + +## [v1.3.0](https://github.com/stellar/js-xdr/compare/v1.2.0...v1.3.0) + +- Inline and modernize the `cursor` dependency ([#](https://github.com/stellar/js-xdr/pull/63)). + +## [v1.2.0](https://github.com/stellar/js-xdr/compare/v1.1.4...v1.2.0) + +- Add method `validateXDR(input, format = 'raw')` which validates if a given XDR is valid or not. ([#56](https://github.com/stellar/js-xdr/pull/56)). + +## [v1.1.4](https://github.com/stellar/js-xdr/compare/v1.1.3...v1.1.4) + +- Remove `core-js` dependency ([#45](https://github.com/stellar/js-xdr/pull/45)). + +## [v1.1.3](https://github.com/stellar/js-xdr/compare/v1.1.2...v1.1.3) + +- Split out reference class to it's own file to avoid circular import ([#39](https://github.com/stellar/js-xdr/pull/39)). + +## [v1.1.2](https://github.com/stellar/js-xdr/compare/v1.1.1...v1.1.2) + +- Travis: Deploy to NPM with an env variable instead of an encrypted key +- Instruct Travis to cache node_modules + +## [v1.1.1](https://github.com/stellar/js-xdr/compare/v1.1.0...v1.1.1) + +- Updated some out-of-date dependencies + +## [v1.1.0](https://github.com/stellar/js-xdr/compare/v1.0.3...v1.1.0) + +### Changed + +- Added ESLint and Prettier to enforce code style +- Upgraded dependencies, including Babel to 6 +- Bump local node version to 6.14.0 + +## [v1.0.3](https://github.com/stellar/js-xdr/compare/v1.0.2...v1.0.3) + +### Changed + +- Updated dependencies +- Improved lodash imports (the browser build should be smaller) + +## [v1.0.2](https://github.com/stellar/js-xdr/compare/v1.0.1...v1.0.2) + +### Changed + +- bugfix: removed `runtime` flag from babel to make this package working in + React/Webpack environments + +## [v1.0.1](https://github.com/stellar/js-xdr/compare/v1.0.0...v1.0.1) + +### Changed + +- bugfix: padding bytes are now ensured to be zero when reading + +## [v1.0.0](https://github.com/stellar/js-xdr/compare/v0.0.12...v1.0.0) + +### Changed + +- Strings are now encoded/decoded as utf-8 + +## [v0.0.12](https://github.com/stellar/js-xdr/compare/v0.0.11...v0.0.12) + +### Changed + +- bugfix: Hyper.fromString() no longer silently accepts strings with decimal + points +- bugfix: UnsignedHyper.fromString() no longer silently accepts strings with + decimal points diff --git a/node_modules/@stellar/js-xdr/CONTRIBUTING.md b/node_modules/@stellar/js-xdr/CONTRIBUTING.md new file mode 100644 index 000000000..26ba4d1ad --- /dev/null +++ b/node_modules/@stellar/js-xdr/CONTRIBUTING.md @@ -0,0 +1,6 @@ +# How to contribute + +Please read the [Contribution Guide](https://github.com/stellar/docs/blob/master/CONTRIBUTING.md). + +Then please [sign the Contributor License Agreement](https://docs.google.com/forms/d/1g7EF6PERciwn7zfmfke5Sir2n10yddGGSXyZsq98tVY/viewform?usp=send_form). + diff --git a/node_modules/@stellar/js-xdr/Gemfile b/node_modules/@stellar/js-xdr/Gemfile new file mode 100644 index 000000000..59037c7ea --- /dev/null +++ b/node_modules/@stellar/js-xdr/Gemfile @@ -0,0 +1,8 @@ +source 'https://rubygems.org' + +group :development do + gem "xdrgen", git: "git@github.com:stellar/xdrgen.git" + # gem "xdrgen", path: "../xdrgen" + gem "pry" +end + diff --git a/node_modules/@stellar/js-xdr/Gemfile.lock b/node_modules/@stellar/js-xdr/Gemfile.lock new file mode 100644 index 000000000..17f2848f7 --- /dev/null +++ b/node_modules/@stellar/js-xdr/Gemfile.lock @@ -0,0 +1,46 @@ +GIT + remote: git@github.com:stellar/xdrgen.git + revision: 80e38ef2a96489f6b501d4db3a350406e5aa3bab + specs: + xdrgen (0.1.1) + activesupport (~> 6) + memoist (~> 0.11.0) + slop (~> 3.4) + treetop (~> 1.5.3) + +GEM + remote: https://rubygems.org/ + specs: + activesupport (6.1.7.6) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + zeitwerk (~> 2.3) + coderay (1.1.3) + concurrent-ruby (1.2.2) + i18n (1.14.1) + concurrent-ruby (~> 1.0) + memoist (0.11.0) + method_source (1.0.0) + minitest (5.19.0) + polyglot (0.3.5) + pry (0.14.2) + coderay (~> 1.1) + method_source (~> 1.0) + slop (3.6.0) + treetop (1.5.3) + polyglot (~> 0.3) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + zeitwerk (2.6.11) + +PLATFORMS + ruby + +DEPENDENCIES + pry + xdrgen! + +BUNDLED WITH + 2.4.6 diff --git a/node_modules/@stellar/js-xdr/LICENSE.md b/node_modules/@stellar/js-xdr/LICENSE.md new file mode 100644 index 000000000..e936ce3e0 --- /dev/null +++ b/node_modules/@stellar/js-xdr/LICENSE.md @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015 Stellar Development Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/node_modules/@stellar/js-xdr/README.md b/node_modules/@stellar/js-xdr/README.md new file mode 100644 index 000000000..974133230 --- /dev/null +++ b/node_modules/@stellar/js-xdr/README.md @@ -0,0 +1,140 @@ +# XDR, for Javascript + +Read/write XDR encoded data structures (RFC 4506) + +[![Build Status](https://travis-ci.com/stellar/js-xdr.svg?branch=master)](https://travis-ci.com/stellar/js-xdr) +[![Code Climate](https://codeclimate.com/github/stellar/js-xdr/badges/gpa.svg)](https://codeclimate.com/github/stellar/js-xdr) +[![Dependency Status](https://david-dm.org/stellar/js-xdr.svg)](https://david-dm.org/stellar/js-xdr) +[![devDependency Status](https://david-dm.org/stellar/js-xdr/dev-status.svg)](https://david-dm.org/stellar/js-xdr#info=devDependencies) + +XDR is an open data format, specified in +[RFC 4506](http://tools.ietf.org/html/rfc4506.html). This library provides a way +to read and write XDR data from javascript. It can read/write all of the +primitive XDR types and also provides facilities to define readers for the +compound XDR types (enums, structs and unions) + +## Installation + +via npm: + +```shell +npm install --save @stellar/js-xdr +``` + +## Usage + +You can find some [examples here](examples/). + +First, let's import the library: + +```javascript +var xdr = require('@stellar/js-xdr'); +// or +import xdr from '@stellar/js-xdr'; +``` + +Now, let's look at how to decode some primitive types: + +```javascript +// booleans +xdr.Bool.fromXDR([0, 0, 0, 0]); // returns false +xdr.Bool.fromXDR([0, 0, 0, 1]); // returns true + +// the inverse of `fromXDR` is `toXDR`, which returns a Buffer +xdr.Bool.toXDR(true); // returns Buffer.from([0,0,0,1]) + +// XDR ints and unsigned ints can be safely represented as +// a javascript number + +xdr.Int.fromXDR([0xff, 0xff, 0xff, 0xff]); // returns -1 +xdr.UnsignedInt.fromXDR([0xff, 0xff, 0xff, 0xff]); // returns 4294967295 + +// XDR Hypers, however, cannot be safely represented in the 53-bits +// of precision we get with a JavaScript `Number`, so we allow creation from big-endian arrays of numbers, strings, or bigints. +var result = xdr.Hyper.fromXDR([0, 0, 0, 0, 0, 0, 0, 0]); // returns an instance of xdr.Hyper +result = new xdr.Hyper(0); // equivalent + +// convert the hyper to a string +result.toString(); // return '0' + +// math! +var ten = result.toBigInt() + 10; +var minusone = result.toBigInt() - 1; + +// construct a number from a string +var big = xdr.Hyper.fromString('1099511627776'); + +// encode the hyper back into xdr +big.toXDR(); // +``` + +## Caveats + +There are a couple of caveats to be aware of with this library: + +1. We do not support quadruple precision floating point values. Attempting to + read or write these values will throw errors. +2. NaN is not handled perfectly for floats and doubles. There are several forms + of NaN as defined by IEEE754 and the browser polyfill for node's Buffer + class seems to handle them poorly. + +## Code generation + +`js-xdr` by itself does not have any ability to parse XDR IDL files and produce +a parser for your custom data types. Instead, that is the responsibility of +[`xdrgen`](http://github.com/stellar/xdrgen). xdrgen will take your .x files +and produce a javascript file that target this library to allow for your own +custom types. + +See [`stellar-base`](http://github.com/stellar/js-stellar-base) for an example +(check out the src/generated directory) + +## Contributing + +Please [see CONTRIBUTING.md for details](CONTRIBUTING.md). + +### To develop and test js-xdr itself + +1. Clone the repo + +```shell +git clone https://github.com/stellar/js-xdr.git +``` + +2. Install dependencies inside js-xdr folder + +```shell +cd js-xdr +npm i +``` + +3. Install Node 14 + +Because we support the oldest maintenance version of Node, please install and +develop on Node 14 so you don't get surprised when your code works locally but +breaks in CI. + +Here's out to install `nvm` if you haven't: https://github.com/creationix/nvm + +```shell +nvm install + +# if you've never installed 14.x before you'll want to re-install yarn +npm install -g yarn +``` + +If you work on several projects that use different Node versions, you might it +helpful to install this automatic version manager: +https://github.com/wbyoung/avn + +4. Observe the project's code style + +While you're making changes, make sure to run the linter periodically to catch any linting errors (in addition to making sure your text editor supports ESLint) + +```shell +yarn fmt +```` + +If you're working on a file not in `src`, limit your code to Node 14! See what's +supported here: https://node.green/ (The reason is that our npm library must +support earlier versions of Node, so the tests need to run on those versions.) diff --git a/node_modules/@stellar/js-xdr/babel.config.json b/node_modules/@stellar/js-xdr/babel.config.json new file mode 100644 index 000000000..e2b47eca4 --- /dev/null +++ b/node_modules/@stellar/js-xdr/babel.config.json @@ -0,0 +1,16 @@ +{ + "presets": [ + [ + "@babel/preset-env", + { + "targets": { + "browsers": [ + "> 2%", + "not ie 11", + "not op_mini all" + ] + } + } + ] + ] +} \ No newline at end of file diff --git a/node_modules/@stellar/js-xdr/bower.json b/node_modules/@stellar/js-xdr/bower.json new file mode 100644 index 000000000..774c4129f --- /dev/null +++ b/node_modules/@stellar/js-xdr/bower.json @@ -0,0 +1,9 @@ +{ + "name": "js-xdr", + "version": "0.0.1", + "private": false, + "main": "dist/xdr.js", + "dependencies": {}, + "devDependencies": {}, + "ignore": [] +} \ No newline at end of file diff --git a/node_modules/@stellar/js-xdr/buffer.js b/node_modules/@stellar/js-xdr/buffer.js new file mode 100644 index 000000000..86790bc74 --- /dev/null +++ b/node_modules/@stellar/js-xdr/buffer.js @@ -0,0 +1,12 @@ +// See https://github.com/stellar/js-xdr/issues/117 +import { Buffer } from 'buffer'; + +if (!(Buffer.alloc(1).subarray(0, 1) instanceof Buffer)) { + Buffer.prototype.subarray = function subarray(start, end) { + const result = Uint8Array.prototype.subarray.call(this, start, end); + Object.setPrototypeOf(result, Buffer.prototype); + return result; + }; +} + +export default Buffer; diff --git a/node_modules/@stellar/js-xdr/dist/xdr.js b/node_modules/@stellar/js-xdr/dist/xdr.js new file mode 100644 index 000000000..ee13e7844 --- /dev/null +++ b/node_modules/@stellar/js-xdr/dist/xdr.js @@ -0,0 +1,3 @@ +/*! For license information please see xdr.js.LICENSE.txt */ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.XDR=e():t.XDR=e()}(this,(()=>(()=>{var t={616:(t,e,r)=>{"use strict";r.d(e,{A:()=>i});var n=r(287);n.hp.alloc(1).subarray(0,1)instanceof n.hp||(n.hp.prototype.subarray=function(t,e){const r=Uint8Array.prototype.subarray.call(this,t,e);return Object.setPrototypeOf(r,n.hp.prototype),r});const i=n.hp},281:(t,e,r)=>{const n=r(164);t.exports=n},164:(t,e,r)=>{"use strict";r.r(e),r.d(e,{Array:()=>F,Bool:()=>S,Double:()=>L,Enum:()=>q,Float:()=>O,Hyper:()=>U,Int:()=>v,LargeInt:()=>x,Opaque:()=>D,Option:()=>X,Quadruple:()=>N,Reference:()=>G,String:()=>M,Struct:()=>Y,Union:()=>W,UnsignedHyper:()=>T,UnsignedInt:()=>R,VarArray:()=>P,VarOpaque:()=>z,Void:()=>k,XdrReader:()=>f,XdrWriter:()=>c,config:()=>it});class n extends TypeError{constructor(t){super(`XDR Write Error: ${t}`)}}class i extends TypeError{constructor(t){super(`XDR Read Error: ${t}`)}}class o extends TypeError{constructor(t){super(`XDR Type Definition Error: ${t}`)}}class s extends o{constructor(){super("method not implemented, it should be overloaded in the descendant class.")}}var u=r(616).A;class f{constructor(t){if(!u.isBuffer(t)){if(!(t instanceof Array||Array.isArray(t)||ArrayBuffer.isView(t)))throw new i(`source invalid: ${t}`);t=u.from(t)}this._buffer=t,this._length=t.length,this._index=0}_buffer;_length;_index;get eof(){return this._index===this._length}advance(t){const e=this._index;if(this._index+=t,this._length0){for(let t=0;t0){const t=this.alloc(r);this._buffer.fill(0,t,this._index)}}writeInt32BE(t){const e=this.alloc(4);this._buffer.writeInt32BE(t,e)}writeUInt32BE(t){const e=this.alloc(4);this._buffer.writeUInt32BE(t,e)}writeBigInt64BE(t){const e=this.alloc(8);this._buffer.writeBigInt64BE(t,e)}writeBigUInt64BE(t){const e=this.alloc(8);this._buffer.writeBigUInt64BE(t,e)}writeFloatBE(t){const e=this.alloc(4);this._buffer.writeFloatBE(t,e)}writeDoubleBE(t){const e=this.alloc(8);this._buffer.writeDoubleBE(t,e)}static bufferChunkSize=h}var l=r(616).A;class p{toXDR(t="raw"){if(!this.write)return this.constructor.toXDR(this,t);const e=new c;return this.write(this,e),w(e.finalize(),t)}fromXDR(t,e="raw"){if(!this.read)return this.constructor.fromXDR(t,e);const r=new f(m(t,e)),n=this.read(r);return r.ensureInputConsumed(),n}validateXDR(t,e="raw"){try{return this.fromXDR(t,e),!0}catch(t){return!1}}static toXDR(t,e="raw"){const r=new c;return this.write(t,r),w(r.finalize(),e)}static fromXDR(t,e="raw"){const r=new f(m(t,e)),n=this.read(r);return r.ensureInputConsumed(),n}static validateXDR(t,e="raw"){try{return this.fromXDR(t,e),!0}catch(t){return!1}}}class d extends p{static read(t){throw new s}static write(t,e){throw new s}static isValid(t){return!1}}class g extends p{isValid(t){return!1}}class y extends TypeError{constructor(t){super(`Invalid format ${t}, must be one of "raw", "hex", "base64"`)}}function w(t,e){switch(e){case"raw":return t;case"hex":return t.toString("hex");case"base64":return t.toString("base64");default:throw new y(e)}}function m(t,e){switch(e){case"raw":return t;case"hex":return l.from(t,"hex");case"base64":return l.from(t,"base64");default:throw new y(e)}}function b(t,e){return null!=t&&(t instanceof e||_(t,e)&&"function"==typeof t.constructor.read&&"function"==typeof t.constructor.write&&_(t,"XdrType"))}function _(t,e){do{if(t.constructor.name===e)return!0}while(t=Object.getPrototypeOf(t));return!1}const B=2147483647,E=-2147483648;class v extends d{static read(t){return t.readInt32BE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");if((0|t)!==t)throw new n("invalid i32 value");e.writeInt32BE(t)}static isValid(t){return"number"==typeof t&&(0|t)===t&&(t>=E&&t<=B)}}function A(t,e,r){if("bigint"!=typeof t)throw new TypeError("Expected bigint 'value', got "+typeof t);const n=e/r;if(1===n)return[t];if(r<32||r>128||2!==n&&4!==n&&8!==n)throw new TypeError(`invalid bigint (${t}) and slice size (${e} -> ${r}) combination`);const i=BigInt(r),o=new Array(n);for(let e=0;e>=i;return o}function I(t,e){if(e)return[0n,(1n<=o&&i<=s)return i;throw new TypeError(`bigint values [${t}] for ${function(t,e){return`${e?"u":"i"}${t}`}(e,r)} out of range [${o}, ${s}]: ${i}`)}(t,this.size,this.unsigned)}get unsigned(){throw new s}get size(){throw new s}slice(t){return A(this._value,this.size,t)}toString(){return this._value.toString()}toJSON(){return{_value:this._value.toString()}}toBigInt(){return BigInt(this._value)}static read(t){const{size:e}=this.prototype;return 64===e?new this(t.readBigUInt64BE()):new this(...Array.from({length:e/64},(()=>t.readBigUInt64BE())).reverse())}static write(t,e){if(t instanceof this)t=t._value;else if("bigint"!=typeof t||t>this.MAX_VALUE||t>32n)|0}get size(){return 64}get unsigned(){return!1}static fromBits(t,e){return new this(t,e)}}U.defineIntBoundaries();const $=4294967295;class R extends d{static read(t){return t.readUInt32BE()}static write(t,e){if("number"!=typeof t||!(t>=0&&t<=$)||t%1!=0)throw new n("invalid u32 value");e.writeUInt32BE(t)}static isValid(t){return"number"==typeof t&&t%1==0&&(t>=0&&t<=$)}}R.MAX_VALUE=$,R.MIN_VALUE=0;class T extends x{constructor(...t){super(t)}get low(){return Number(0xffffffffn&this._value)|0}get high(){return Number(this._value>>32n)|0}get size(){return 64}get unsigned(){return!0}static fromBits(t,e){return new this(t,e)}}T.defineIntBoundaries();class O extends d{static read(t){return t.readFloatBE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");e.writeFloatBE(t)}static isValid(t){return"number"==typeof t}}class L extends d{static read(t){return t.readDoubleBE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");e.writeDoubleBE(t)}static isValid(t){return"number"==typeof t}}class N extends d{static read(){throw new o("quadruple not supported")}static write(){throw new o("quadruple not supported")}static isValid(){return!1}}class S extends d{static read(t){const e=v.read(t);switch(e){case 0:return!1;case 1:return!0;default:throw new i(`got ${e} when trying to read a bool`)}}static write(t,e){const r=t?1:0;v.write(r,e)}static isValid(t){return"boolean"==typeof t}}var V=r(616).A;class M extends g{constructor(t=R.MAX_VALUE){super(),this._maxLength=t}read(t){const e=R.read(t);if(e>this._maxLength)throw new i(`saw ${e} length String, max allowed is ${this._maxLength}`);return t.read(e)}readString(t){return this.read(t).toString("utf8")}write(t,e){const r="string"==typeof t?V.byteLength(t,"utf8"):t.length;if(r>this._maxLength)throw new n(`got ${t.length} bytes, max allowed is ${this._maxLength}`);R.write(r,e),e.write(t,r)}isValid(t){return"string"==typeof t?V.byteLength(t,"utf8")<=this._maxLength:!!(t instanceof Array||V.isBuffer(t))&&t.length<=this._maxLength}}var C=r(616).A;class D extends g{constructor(t){super(),this._length=t}read(t){return t.read(this._length)}write(t,e){const{length:r}=t;if(r!==this._length)throw new n(`got ${t.length} bytes, expected ${this._length}`);e.write(t,r)}isValid(t){return C.isBuffer(t)&&t.length===this._length}}var j=r(616).A;class z extends g{constructor(t=R.MAX_VALUE){super(),this._maxLength=t}read(t){const e=R.read(t);if(e>this._maxLength)throw new i(`saw ${e} length VarOpaque, max allowed is ${this._maxLength}`);return t.read(e)}write(t,e){const{length:r}=t;if(t.length>this._maxLength)throw new n(`got ${t.length} bytes, max allowed is ${this._maxLength}`);R.write(r,e),e.write(t,r)}isValid(t){return j.isBuffer(t)&&t.length<=this._maxLength}}class F extends g{constructor(t,e){super(),this._childType=t,this._length=e}read(t){const e=new r.g.Array(this._length);for(let r=0;rthis._maxLength)throw new i(`saw ${e} length VarArray, max allowed is ${this._maxLength}`);const r=new Array(e);for(let n=0;nthis._maxLength)throw new n(`got array of size ${t.length}, max allowed is ${this._maxLength}`);R.write(t.length,e);for(const r of t)this._childType.write(r,e)}isValid(t){if(!(t instanceof Array)||t.length>this._maxLength)return!1;for(const e of t)if(!this._childType.isValid(e))return!1;return!0}}class X extends d{constructor(t){super(),this._childType=t}read(t){if(S.read(t))return this._childType.read(t)}write(t,e){const r=null!=t;S.write(r,e),r&&this._childType.write(t,e)}isValid(t){return null==t||this._childType.isValid(t)}}class k extends d{static read(){}static write(t){if(void 0!==t)throw new n("trying to write value to a void slot")}static isValid(t){return void 0===t}}class q extends d{constructor(t,e){super(),this.name=t,this.value=e}static read(t){const e=v.read(t),r=this._byValue[e];if(void 0===r)throw new i(`unknown ${this.enumName} member for value ${e}`);return r}static write(t,e){if(!this.isValid(t))throw new n(`${t} has enum name ${t?.enumName}, not ${this.enumName}: ${JSON.stringify(t)}`);v.write(t.value,e)}static isValid(t){return t?.constructor?.enumName===this.enumName||b(t,this)}static members(){return this._members}static values(){return Object.values(this._members)}static fromName(t){const e=this._members[t];if(!e)throw new TypeError(`${t} is not a member of ${this.enumName}`);return e}static fromValue(t){const e=this._byValue[t];if(void 0===e)throw new TypeError(`${t} is not a value of any member of ${this.enumName}`);return e}static create(t,e,r){const n=class extends q{};n.enumName=e,t.results[e]=n,n._members={},n._byValue={};for(const[t,e]of Object.entries(r)){const r=new n(t,e);n._members[t]=r,n._byValue[e]=r,n[t]=()=>r}return n}}class G extends d{resolve(){throw new o('"resolve" method should be implemented in the descendant class')}}class Y extends g{constructor(t){super(),this._attributes=t||{}}static read(t){const e={};for(const[r,n]of this._fields)e[r]=n.read(t);return new this(e)}static write(t,e){if(!this.isValid(t))throw new n(`${t} has struct name ${t?.constructor?.structName}, not ${this.structName}: ${JSON.stringify(t)}`);for(const[r,n]of this._fields){const i=t._attributes[r];n.write(i,e)}}static isValid(t){return t?.constructor?.structName===this.structName||b(t,this)}static create(t,e,r){const n=class extends Y{};n.structName=e,t.results[e]=n;const i=new Array(r.length);for(let e=0;e{"use strict";e.byteLength=function(t){var e=u(t),r=e[0],n=e[1];return 3*(r+n)/4-n},e.toByteArray=function(t){var e,r,o=u(t),s=o[0],f=o[1],a=new i(function(t,e,r){return 3*(e+r)/4-r}(0,s,f)),h=0,c=f>0?s-4:s;for(r=0;r>16&255,a[h++]=e>>8&255,a[h++]=255&e;2===f&&(e=n[t.charCodeAt(r)]<<2|n[t.charCodeAt(r+1)]>>4,a[h++]=255&e);1===f&&(e=n[t.charCodeAt(r)]<<10|n[t.charCodeAt(r+1)]<<4|n[t.charCodeAt(r+2)]>>2,a[h++]=e>>8&255,a[h++]=255&e);return a},e.fromByteArray=function(t){for(var e,n=t.length,i=n%3,o=[],s=16383,u=0,a=n-i;ua?a:u+s));1===i?(e=t[n-1],o.push(r[e>>2]+r[e<<4&63]+"==")):2===i&&(e=(t[n-2]<<8)+t[n-1],o.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"="));return o.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)r[s]=o[s],n[o.charCodeAt(s)]=s;function u(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function f(t,e,n){for(var i,o,s=[],u=e;u>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return s.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287:(t,e,r)=>{"use strict";const n=r(526),i=r(251),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.hp=f,e.IS=50;const s=2147483647;function u(t){if(t>s)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,f.prototype),e}function f(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return c(t)}return a(t,e,r)}function a(t,e,r){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!f.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|g(t,e);let n=u(r);const i=n.write(t,e);i!==r&&(n=n.slice(0,i));return n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(W(t,Uint8Array)){const e=new Uint8Array(t);return p(e.buffer,e.byteOffset,e.byteLength)}return l(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(W(t,ArrayBuffer)||t&&W(t.buffer,ArrayBuffer))return p(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(W(t,SharedArrayBuffer)||t&&W(t.buffer,SharedArrayBuffer)))return p(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return f.from(n,e,r);const i=function(t){if(f.isBuffer(t)){const e=0|d(t.length),r=u(e);return 0===r.length||t.copy(r,0,0,e),r}if(void 0!==t.length)return"number"!=typeof t.length||H(t.length)?u(0):l(t);if("Buffer"===t.type&&Array.isArray(t.data))return l(t.data)}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return f.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function h(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function c(t){return h(t),u(t<0?0:0|d(t))}function l(t){const e=t.length<0?0:0|d(t.length),r=u(e);for(let n=0;n=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|t}function g(t,e){if(f.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||W(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return G(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Y(t).length;default:if(i)return n?-1:G(t).length;e=(""+e).toLowerCase(),i=!0}}function y(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return x(this,e,r);case"ascii":return $(this,e,r);case"latin1":case"binary":return R(this,e,r);case"base64":return I(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function w(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function m(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),H(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=f.from(e,n)),f.isBuffer(e))return 0===e.length?-1:b(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):b(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(t,e,r,n,i){let o,s=1,u=t.length,f=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,f/=2,r/=2}function a(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){let n=-1;for(o=r;ou&&(r=u-f),o=r;o>=0;o--){let r=!0;for(let n=0;ni&&(n=i):n=i;const o=e.length;let s;for(n>o/2&&(n=o/2),s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function I(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function x(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+s<=r){let r,n,u,f;switch(s){case 1:e<128&&(o=e);break;case 2:r=t[i+1],128==(192&r)&&(f=(31&e)<<6|63&r,f>127&&(o=f));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(f=(15&e)<<12|(63&r)<<6|63&n,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:r=t[i+1],n=t[i+2],u=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&u)&&(f=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&u,f>65535&&f<1114112&&(o=f))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return function(t){const e=t.length;if(e<=U)return String.fromCharCode.apply(String,t);let r="",n=0;for(;nn.length?(f.isBuffer(e)||(e=f.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!f.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},f.byteLength=g,f.prototype._isBuffer=!0,f.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;er&&(t+=" ... "),""},o&&(f.prototype[o]=f.prototype.inspect),f.prototype.compare=function(t,e,r,n,i){if(W(t,Uint8Array)&&(t=f.from(t,t.offset,t.byteLength)),!f.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0);const u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r);for(let t=0;t>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return _(this,t,e,r);case"utf8":case"utf-8":return B(this,t,e,r);case"ascii":case"latin1":case"binary":return E(this,t,e,r);case"base64":return v(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},f.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const U=4096;function $(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;in)&&(r=n);let i="";for(let n=e;nr)throw new RangeError("Trying to access beyond buffer length")}function N(t,e,r,n,i,o){if(!f.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function S(t,e,r,n,i){P(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,r}function V(t,e,r,n,i){P(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r+7]=o,o>>=8,t[r+6]=o,o>>=8,t[r+5]=o,o>>=8,t[r+4]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=s,s>>=8,t[r+2]=s,s>>=8,t[r+1]=s,s>>=8,t[r]=s,r+8}function M(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function C(t,e,r,n,o){return e=+e,r>>>=0,o||M(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function D(t,e,r,n,o){return e=+e,r>>>=0,o||M(t,0,r,8),i.write(t,e,r,n,52,8),r+8}f.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t],i=1,o=0;for(;++o>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},f.prototype.readUint8=f.prototype.readUInt8=function(t,e){return t>>>=0,e||L(t,1,this.length),this[t]},f.prototype.readUint16LE=f.prototype.readUInt16LE=function(t,e){return t>>>=0,e||L(t,2,this.length),this[t]|this[t+1]<<8},f.prototype.readUint16BE=f.prototype.readUInt16BE=function(t,e){return t>>>=0,e||L(t,2,this.length),this[t]<<8|this[t+1]},f.prototype.readUint32LE=f.prototype.readUInt32LE=function(t,e){return t>>>=0,e||L(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},f.prototype.readUint32BE=f.prototype.readUInt32BE=function(t,e){return t>>>=0,e||L(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},f.prototype.readBigUInt64LE=Z((function(t){X(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t],i=1,o=0;for(;++o=i&&(n-=Math.pow(2,8*e)),n},f.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||L(t,e,this.length);let n=e,i=1,o=this[t+--n];for(;n>0&&(i*=256);)o+=this[t+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*e)),o},f.prototype.readInt8=function(t,e){return t>>>=0,e||L(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},f.prototype.readInt16LE=function(t,e){t>>>=0,e||L(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},f.prototype.readInt16BE=function(t,e){t>>>=0,e||L(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},f.prototype.readInt32LE=function(t,e){return t>>>=0,e||L(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},f.prototype.readInt32BE=function(t,e){return t>>>=0,e||L(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},f.prototype.readBigInt64LE=Z((function(t){X(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<>>=0,e||L(t,4,this.length),i.read(this,t,!0,23,4)},f.prototype.readFloatBE=function(t,e){return t>>>=0,e||L(t,4,this.length),i.read(this,t,!1,23,4)},f.prototype.readDoubleLE=function(t,e){return t>>>=0,e||L(t,8,this.length),i.read(this,t,!0,52,8)},f.prototype.readDoubleBE=function(t,e){return t>>>=0,e||L(t,8,this.length),i.read(this,t,!1,52,8)},f.prototype.writeUintLE=f.prototype.writeUIntLE=function(t,e,r,n){if(t=+t,e>>>=0,r>>>=0,!n){N(this,t,e,r,Math.pow(2,8*r)-1,0)}let i=1,o=0;for(this[e]=255&t;++o>>=0,r>>>=0,!n){N(this,t,e,r,Math.pow(2,8*r)-1,0)}let i=r-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+r},f.prototype.writeUint8=f.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,1,255,0),this[e]=255&t,e+1},f.prototype.writeUint16LE=f.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},f.prototype.writeUint16BE=f.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},f.prototype.writeUint32LE=f.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},f.prototype.writeUint32BE=f.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},f.prototype.writeBigUInt64LE=Z((function(t,e=0){return S(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),f.prototype.writeBigUInt64BE=Z((function(t,e=0){return V(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),f.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);N(this,t,e,r,n-1,-n)}let i=0,o=1,s=0;for(this[e]=255&t;++i>>=0,!n){const n=Math.pow(2,8*r-1);N(this,t,e,r,n-1,-n)}let i=r-1,o=1,s=0;for(this[e+i]=255&t;--i>=0&&(o*=256);)t<0&&0===s&&0!==this[e+i+1]&&(s=1),this[e+i]=(t/o|0)-s&255;return e+r},f.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},f.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},f.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},f.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},f.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},f.prototype.writeBigInt64LE=Z((function(t,e=0){return S(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),f.prototype.writeBigInt64BE=Z((function(t,e=0){return V(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),f.prototype.writeFloatLE=function(t,e,r){return C(this,t,e,!0,r)},f.prototype.writeFloatBE=function(t,e,r){return C(this,t,e,!1,r)},f.prototype.writeDoubleLE=function(t,e,r){return D(this,t,e,!0,r)},f.prototype.writeDoubleBE=function(t,e,r){return D(this,t,e,!1,r)},f.prototype.copy=function(t,e,r,n){if(!f.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function P(t,e,r,n,i,o){if(t>r||t3?0===e||e===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`:`>= ${e}${n} and <= ${r}${n}`,new j.ERR_OUT_OF_RANGE("value",i,t)}!function(t,e,r){X(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||k(e,t.length-(r+1))}(n,i,o)}function X(t,e){if("number"!=typeof t)throw new j.ERR_INVALID_ARG_TYPE(e,"number",t)}function k(t,e,r){if(Math.floor(t)!==t)throw X(t,r),new j.ERR_OUT_OF_RANGE(r||"offset","an integer",t);if(e<0)throw new j.ERR_BUFFER_OUT_OF_BOUNDS;throw new j.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}z("ERR_BUFFER_OUT_OF_BOUNDS",(function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),z("ERR_INVALID_ARG_TYPE",(function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`}),TypeError),z("ERR_OUT_OF_RANGE",(function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=F(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=F(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n}),RangeError);const q=/[^+/0-9A-Za-z-_]/g;function G(t,e){let r;e=e||1/0;const n=t.length;let i=null;const o=[];for(let s=0;s55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function Y(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(q,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function J(t,e,r,n){let i;for(i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function W(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function H(t){return t!=t}const Q=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function Z(t){return"undefined"==typeof BigInt?K:t}function K(){throw new Error("BigInt not supported")}},251:(t,e)=>{e.read=function(t,e,r,n,i){var o,s,u=8*i-n-1,f=(1<>1,h=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-h)-1,p>>=-h,h+=u;h>0;o=256*o+t[e+c],c+=l,h-=8);for(s=o&(1<<-h)-1,o>>=-h,h+=n;h>0;s=256*s+t[e+c],c+=l,h-=8);if(0===o)o=1-a;else{if(o===f)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=a}return(p?-1:1)*s*Math.pow(2,o-n)},e.write=function(t,e,r,n,i,o){var s,u,f,a=8*o-i-1,h=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=h):(s=Math.floor(Math.log(e)/Math.LN2),e*(f=Math.pow(2,-s))<1&&(s--,f*=2),(e+=s+c>=1?l/f:l*Math.pow(2,1-c))*f>=2&&(s++,f/=2),s+c>=h?(u=0,s=h):s+c>=1?(u=(e*f-1)*Math.pow(2,i),s+=c):(u=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,a-=8);t[r+p-d]|=128*g}}},e={};function r(n){var i=e[n];if(void 0!==i)return i.exports;var o=e[n]={exports:{}};return t[n](o,o.exports,r),o.exports}return r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r(281)})())); +//# sourceMappingURL=xdr.js.map \ No newline at end of file diff --git a/node_modules/@stellar/js-xdr/dist/xdr.js.LICENSE.txt b/node_modules/@stellar/js-xdr/dist/xdr.js.LICENSE.txt new file mode 100644 index 000000000..df537c532 --- /dev/null +++ b/node_modules/@stellar/js-xdr/dist/xdr.js.LICENSE.txt @@ -0,0 +1,8 @@ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ diff --git a/node_modules/@stellar/js-xdr/dist/xdr.js.map b/node_modules/@stellar/js-xdr/dist/xdr.js.map new file mode 100644 index 000000000..1f167f47c --- /dev/null +++ b/node_modules/@stellar/js-xdr/dist/xdr.js.map @@ -0,0 +1 @@ +{"version":3,"file":"xdr.js","mappings":";CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAa,IAAID,IAEjBD,EAAU,IAAIC,GACf,CATD,CASGK,MAAM,0ECNHC,EAAAA,GAAOC,MAAM,GAAGC,SAAS,EAAG,aAAcF,EAAAA,KAC9CA,EAAAA,GAAOG,UAAUD,SAAW,SAAkBE,EAAOC,GACnD,MAAMC,EAASC,WAAWJ,UAAUD,SAASM,KAAKT,KAAMK,EAAOC,GAE/D,OADAI,OAAOC,eAAeJ,EAAQN,EAAAA,GAAOG,WAC9BG,CACT,GAGF,QAAeN,EAAM,kBCVrB,MAAML,EAAUgB,EAAQ,KACxBf,EAAOD,QAAUA,4WCFV,MAAMiB,UAAuBC,UAClCC,WAAAA,CAAYC,GACVC,MAAM,oBAAoBD,IAC5B,EAGK,MAAME,UAAuBJ,UAClCC,WAAAA,CAAYC,GACVC,MAAM,mBAAmBD,IAC3B,EAGK,MAAMG,UAA2BL,UACtCC,WAAAA,CAAYC,GACVC,MAAM,8BAA8BD,IACtC,EAGK,MAAMI,UAAyCD,EACpDJ,WAAAA,GACEE,MACE,2EAEJ,iBClBK,MAAMI,EAKXN,WAAAA,CAAYO,GACV,IAAKrB,EAAOsB,SAASD,GAAS,CAC5B,KACEA,aAAkBE,OAClBA,MAAMC,QAAQH,IACdI,YAAYC,OAAOL,IAInB,MAAM,IAAIJ,EAAe,mBAAmBI,KAF5CA,EAASrB,EAAO2B,KAAKN,EAIzB,CAEAtB,KAAK6B,QAAUP,EACftB,KAAK8B,QAAUR,EAAOS,OACtB/B,KAAKgC,OAAS,CAChB,CAOAH,QAMAC,QAMAE,OAMA,OAAIC,GACF,OAAOjC,KAAKgC,SAAWhC,KAAK8B,OAC9B,CAQAI,OAAAA,CAAQC,GACN,MAAMP,EAAO5B,KAAKgC,OAIlB,GAFAhC,KAAKgC,QAAUG,EAEXnC,KAAK8B,QAAU9B,KAAKgC,OACtB,MAAM,IAAId,EACR,sDAGJ,MAAMkB,EAAU,GAAKD,EAAO,GAAK,GACjC,GAAIC,EAAU,EAAG,CACf,IAAK,IAAIC,EAAI,EAAGA,EAAID,EAASC,IAC3B,GAAsC,IAAlCrC,KAAK6B,QAAQ7B,KAAKgC,OAASK,GAE7B,MAAM,IAAInB,EAAe,mBAC7BlB,KAAKgC,QAAUI,CACjB,CACA,OAAOR,CACT,CAMAU,MAAAA,GACEtC,KAAKgC,OAAS,CAChB,CAOAO,IAAAA,CAAKJ,GACH,MAAMP,EAAO5B,KAAKkC,QAAQC,GAC1B,OAAOnC,KAAK6B,QAAQ1B,SAASyB,EAAMA,EAAOO,EAC5C,CAMAK,WAAAA,GACE,OAAOxC,KAAK6B,QAAQW,YAAYxC,KAAKkC,QAAQ,GAC/C,CAMAO,YAAAA,GACE,OAAOzC,KAAK6B,QAAQY,aAAazC,KAAKkC,QAAQ,GAChD,CAMAQ,cAAAA,GACE,OAAO1C,KAAK6B,QAAQa,eAAe1C,KAAKkC,QAAQ,GAClD,CAMAS,eAAAA,GACE,OAAO3C,KAAK6B,QAAQc,gBAAgB3C,KAAKkC,QAAQ,GACnD,CAMAU,WAAAA,GACE,OAAO5C,KAAK6B,QAAQe,YAAY5C,KAAKkC,QAAQ,GAC/C,CAMAW,YAAAA,GACE,OAAO7C,KAAK6B,QAAQgB,aAAa7C,KAAKkC,QAAQ,GAChD,CAOAY,mBAAAA,GACE,GAAI9C,KAAKgC,SAAWhC,KAAK8B,QACvB,MAAM,IAAIZ,EACR,sEAEN,iBC9JF,MAAM6B,EAAe,KAKd,MAAMC,EAIXjC,WAAAA,CAAYkC,GACY,iBAAXA,EACTA,EAAShD,EAAOiD,YAAYD,GACjBA,aAAkBhD,IAC7BgD,EAAShD,EAAOiD,YAAYH,IAE9B/C,KAAK6B,QAAUoB,EACfjD,KAAK8B,QAAUmB,EAAOlB,MACxB,CAOAF,QAMAC,QAMAE,OAAS,EAQT9B,KAAAA,CAAMiC,GACJ,MAAMP,EAAO5B,KAAKgC,OAOlB,OALAhC,KAAKgC,QAAUG,EAEXnC,KAAK8B,QAAU9B,KAAKgC,QACtBhC,KAAKmD,OAAOnD,KAAKgC,QAEZJ,CACT,CAQAuB,MAAAA,CAAOC,GAEL,MAAMC,EAAYC,KAAKC,KAAKH,EAAkBL,GAAgBA,EAExDS,EAAYvD,EAAOiD,YAAYG,GACrCrD,KAAK6B,QAAQ4B,KAAKD,EAAW,EAAG,EAAGxD,KAAK8B,SAExC9B,KAAK6B,QAAU2B,EACfxD,KAAK8B,QAAUuB,CACjB,CAMAK,QAAAA,GAEE,OAAO1D,KAAK6B,QAAQ1B,SAAS,EAAGH,KAAKgC,OACvC,CAMA2B,OAAAA,GACE,MAAO,IAAI3D,KAAK0D,WAClB,CAQAE,KAAAA,CAAMC,EAAO1B,GACX,GAAqB,iBAAV0B,EAAoB,CAE7B,MAAMC,EAAS9D,KAAKE,MAAMiC,GAC1BnC,KAAK6B,QAAQ+B,MAAMC,EAAOC,EAAQ,OACpC,KAAO,CAECD,aAAiB5D,IACrB4D,EAAQ5D,EAAO2B,KAAKiC,IAEtB,MAAMC,EAAS9D,KAAKE,MAAMiC,GAC1B0B,EAAMJ,KAAKzD,KAAK6B,QAASiC,EAAQ,EAAG3B,EACtC,CAGA,MAAMC,EAAU,GAAKD,EAAO,GAAK,GACjC,GAAIC,EAAU,EAAG,CACf,MAAM0B,EAAS9D,KAAKE,MAAMkC,GAC1BpC,KAAK6B,QAAQkC,KAAK,EAAGD,EAAQ9D,KAAKgC,OACpC,CACF,CAOAgC,YAAAA,CAAaH,GACX,MAAMC,EAAS9D,KAAKE,MAAM,GAC1BF,KAAK6B,QAAQmC,aAAaH,EAAOC,EACnC,CAOAG,aAAAA,CAAcJ,GACZ,MAAMC,EAAS9D,KAAKE,MAAM,GAC1BF,KAAK6B,QAAQoC,cAAcJ,EAAOC,EACpC,CAOAI,eAAAA,CAAgBL,GACd,MAAMC,EAAS9D,KAAKE,MAAM,GAC1BF,KAAK6B,QAAQqC,gBAAgBL,EAAOC,EACtC,CAOAK,gBAAAA,CAAiBN,GACf,MAAMC,EAAS9D,KAAKE,MAAM,GAC1BF,KAAK6B,QAAQsC,iBAAiBN,EAAOC,EACvC,CAOAM,YAAAA,CAAaP,GACX,MAAMC,EAAS9D,KAAKE,MAAM,GAC1BF,KAAK6B,QAAQuC,aAAaP,EAAOC,EACnC,CAOAO,aAAAA,CAAcR,GACZ,MAAMC,EAAS9D,KAAKE,MAAM,GAC1BF,KAAK6B,QAAQwC,cAAcR,EAAOC,EACpC,CAEAQ,uBAAyBvB,iBC7K3B,MAAMwB,EAMJC,KAAAA,CAAMC,EAAS,OACb,IAAKzE,KAAK4D,MAAO,OAAO5D,KAAKe,YAAYyD,MAAMxE,KAAMyE,GAErD,MAAMC,EAAS,IAAI1B,EAEnB,OADAhD,KAAK4D,MAAM5D,KAAM0E,GACVC,EAAaD,EAAOhB,WAAYe,EACzC,CAQAG,OAAAA,CAAQC,EAAOJ,EAAS,OACtB,IAAKzE,KAAKuC,KAAM,OAAOvC,KAAKe,YAAY6D,QAAQC,EAAOJ,GAEvD,MAAMK,EAAS,IAAIzD,EAAU0D,EAAYF,EAAOJ,IAC1ClE,EAASP,KAAKuC,KAAKuC,GAEzB,OADAA,EAAOhC,sBACAvC,CACT,CAQAyE,WAAAA,CAAYH,EAAOJ,EAAS,OAC1B,IAEE,OADAzE,KAAK4E,QAAQC,EAAOJ,IACb,CACT,CAAE,MAAOQ,GACP,OAAO,CACT,CACF,CAQA,YAAOT,CAAMX,EAAOY,EAAS,OAC3B,MAAMC,EAAS,IAAI1B,EAEnB,OADAhD,KAAK4D,MAAMC,EAAOa,GACXC,EAAaD,EAAOhB,WAAYe,EACzC,CAQA,cAAOG,CAAQC,EAAOJ,EAAS,OAC7B,MAAMK,EAAS,IAAIzD,EAAU0D,EAAYF,EAAOJ,IAC1ClE,EAASP,KAAKuC,KAAKuC,GAEzB,OADAA,EAAOhC,sBACAvC,CACT,CAQA,kBAAOyE,CAAYH,EAAOJ,EAAS,OACjC,IAEE,OADAzE,KAAK4E,QAAQC,EAAOJ,IACb,CACT,CAAE,MAAOQ,GACP,OAAO,CACT,CACF,EAGK,MAAMC,UAAyBX,EAQpC,WAAOhC,CAAKuC,GACV,MAAM,IAAI1D,CACZ,CAUA,YAAOwC,CAAMC,EAAOa,GAClB,MAAM,IAAItD,CACZ,CASA,cAAO+D,CAAQtB,GACb,OAAO,CACT,EAGK,MAAMuB,UAAyBb,EAUpCY,OAAAA,CAAQtB,GACN,OAAO,CACT,EAGF,MAAMwB,UAAsCvE,UAC1CC,WAAAA,CAAY0D,GACVxD,MAAM,kBAAkBwD,2CAC1B,EAGF,SAASE,EAAa1B,EAAQwB,GAC5B,OAAQA,GACN,IAAK,MACH,OAAOxB,EACT,IAAK,MACH,OAAOA,EAAOqC,SAAS,OACzB,IAAK,SACH,OAAOrC,EAAOqC,SAAS,UACzB,QACE,MAAM,IAAID,EAA8BZ,GAE9C,CAEA,SAASM,EAAYF,EAAOJ,GAC1B,OAAQA,GACN,IAAK,MACH,OAAOI,EACT,IAAK,MACH,OAAO5E,EAAO2B,KAAKiD,EAAO,OAC5B,IAAK,SACH,OAAO5E,EAAO2B,KAAKiD,EAAO,UAC5B,QACE,MAAM,IAAIQ,EAA8BZ,GAE9C,CAiBO,SAASc,EAAkB1B,EAAO2B,GACvC,OACE3B,UAECA,aAAiB2B,GAGfC,EAAe5B,EAAO2B,IAEa,mBAA3B3B,EAAM9C,YAAYwB,MACU,mBAA5BsB,EAAM9C,YAAY6C,OAEzB6B,EAAe5B,EAAO,WAE9B,CAGO,SAAS4B,EAAeC,EAAUF,GACvC,EAAG,CAED,GADaE,EAAS3E,YACb4E,OAASH,EAChB,OAAO,CAEX,OAAUE,EAAWhF,OAAOkF,eAAeF,IAC3C,OAAO,CACT,CCjNA,MAAMG,EAAY,WACZC,GAAa,WAEZ,MAAMC,UAAYb,EAIvB,WAAO3C,CAAKuC,GACV,OAAOA,EAAOtC,aAChB,CAKA,YAAOoB,CAAMC,EAAOa,GAClB,GAAqB,iBAAVb,EAAoB,MAAM,IAAIhD,EAAe,gBAExD,IAAa,EAARgD,KAAeA,EAAO,MAAM,IAAIhD,EAAe,qBAEpD6D,EAAOV,aAAaH,EACtB,CAKA,cAAOsB,CAAQtB,GACb,MAAqB,iBAAVA,IAA+B,EAARA,KAAeA,IAI1CA,GAASiC,GAAajC,GAASgC,EACxC,ECqDK,SAASG,EAAYnC,EAAOoC,EAAOC,GACxC,GAAqB,iBAAVrC,EACT,MAAM,IAAI/C,UAAU,uCAAuC+C,GAG7D,MAAMsC,EAAQF,EAAQC,EACtB,GAAc,IAAVC,EACF,MAAO,CAACtC,GAGV,GACEqC,EAAY,IACZA,EAAY,KACD,IAAVC,GAAyB,IAAVA,GAAyB,IAAVA,EAE/B,MAAM,IAAIrF,UACR,mBAAmB+C,sBAA0BoC,QAAYC,kBAI7D,MAAME,EAAQC,OAAOH,GAGf3F,EAAS,IAAIiB,MAAM2E,GACzB,IAAK,IAAI9D,EAAI,EAAGA,EAAI8D,EAAO9D,IAGzB9B,EAAO8B,GAAKgE,OAAOC,OAAOJ,EAAWrC,GAGrCA,IAAUuC,EAGZ,OAAO7F,CACT,CAYO,SAASgG,EAA0BpE,EAAMqE,GAC9C,GAAIA,EACF,MAAO,CAAC,IAAK,IAAMH,OAAOlE,IAAS,IAGrC,MAAMsE,EAAW,IAAMJ,OAAOlE,EAAO,GACrC,MAAO,CAAC,GAAKsE,EAAUA,EAAW,GACpC,CDvGAV,EAAIF,UAAYA,EAChBE,EAAID,UAAY,WE9BT,MAAMY,UAAiBxB,EAI5BnE,WAAAA,CAAY4F,GACV1F,QACAjB,KAAK4G,ODJF,SAA8BC,EAAO1E,EAAMqE,GAC1CK,aAAiBrF,MAGZqF,EAAM9E,QAAU8E,EAAM,aAAcrF,QAE7CqF,EAAQA,EAAM,IAHdA,EAAQ,CAACA,GAMX,MACMX,EAAY/D,EADJ0E,EAAM9E,OAEpB,OAAQmE,GACN,KAAK,GACL,KAAK,GACL,KAAK,IACL,KAAK,IACH,MAEF,QACE,MAAM,IAAIY,WACR,qDAAqDD,KAK3D,IACE,IAAK,IAAIxE,EAAI,EAAGA,EAAIwE,EAAM9E,OAAQM,IACR,iBAAbwE,EAAMxE,KACfwE,EAAMxE,GAAKgE,OAAOQ,EAAMxE,GAAG0E,WAGjC,CAAE,MAAO9B,GACP,MAAM,IAAInE,UAAU,qCAAqC+F,MAAU5B,KACrE,CAKA,GAAIuB,GAA6B,IAAjBK,EAAM9E,QAAgB8E,EAAM,GAAK,GAC/C,MAAM,IAAIC,WAAW,mCAAmCD,KAI1D,IAAItG,EAAS8F,OAAOW,QAAQd,EAAWW,EAAM,IAC7C,IAAK,IAAIxE,EAAI,EAAGA,EAAIwE,EAAM9E,OAAQM,IAChC9B,GAAU8F,OAAOW,QAAQd,EAAWW,EAAMxE,KAAOgE,OAAOhE,EAAI6D,GAIzDM,IACHjG,EAAS8F,OAAOC,OAAOnE,EAAM5B,IAI/B,MAAO0G,EAAKC,GAAOX,EAA0BpE,EAAMqE,GACnD,GAAIjG,GAAU0G,GAAO1G,GAAU2G,EAC7B,OAAO3G,EAIT,MAAM,IAAIO,UACR,kBAAkB+F,UAoDf,SAAuBM,EAAWX,GACvC,MAAO,GAAGA,EAAW,IAAM,MAAMW,GACnC,CAtDoCC,CAC9BjF,EACAqE,oBACiBS,MAAQC,OAAS3G,IAExC,CC9DkB8G,CAAqBV,EAAM3G,KAAKmC,KAAMnC,KAAKwG,SAC3D,CAOA,YAAIA,GACF,MAAM,IAAIpF,CACZ,CAOA,QAAIe,GACF,MAAM,IAAIf,CACZ,CAOAkG,KAAAA,CAAMpB,GACJ,OAAOF,EAAYhG,KAAK4G,OAAQ5G,KAAKmC,KAAM+D,EAC7C,CAEAZ,QAAAA,GACE,OAAOtF,KAAK4G,OAAOtB,UACrB,CAEAiC,MAAAA,GACE,MAAO,CAAEX,OAAQ5G,KAAK4G,OAAOtB,WAC/B,CAEAkC,QAAAA,GACE,OAAOnB,OAAOrG,KAAK4G,OACrB,CAKA,WAAOrE,CAAKuC,GACV,MAAM,KAAE3C,GAASnC,KAAKI,UACtB,OAAa,KAAT+B,EAAoB,IAAInC,KAAK8E,EAAOnC,mBACjC,IAAI3C,QACNwB,MAAMI,KAAK,CAAEG,OAAQI,EAAO,KAAM,IACnC2C,EAAOnC,oBACP8E,UAEN,CAKA,YAAO7D,CAAMC,EAAOa,GAClB,GAAIb,aAAiB7D,KACnB6D,EAAQA,EAAM+C,YACT,GACY,iBAAV/C,GACPA,EAAQ7D,KAAK6F,WACbhC,EAAQ7D,KAAK8F,UAEb,MAAM,IAAIjF,EAAe,GAAGgD,cAAkB7D,KAAK2F,QAErD,MAAM,SAAEa,EAAQ,KAAErE,GAASnC,KAAKI,UAChC,GAAa,KAAT+B,EACEqE,EACF9B,EAAOP,iBAAiBN,GAExBa,EAAOR,gBAAgBL,QAGzB,IAAK,MAAM6D,KAAQ1B,EAAYnC,EAAO1B,EAAM,IAAIsF,UAC1CjB,EACF9B,EAAOP,iBAAiBuD,GAExBhD,EAAOR,gBAAgBwD,EAI/B,CAKA,cAAOvC,CAAQtB,GACb,MAAwB,iBAAVA,GAAsBA,aAAiB7D,IACvD,CAOA,iBAAO2H,CAAWC,GAChB,OAAO,IAAI5H,KAAK4H,EAClB,CAEAtD,iBAAmB,GAEnBA,iBAAmB,GAMnB,0BAAOuD,GACL,MAAOZ,EAAKC,GAAOX,EACjBvG,KAAKI,UAAU+B,KACfnC,KAAKI,UAAUoG,UAEjBxG,KAAK8F,UAAYmB,EACjBjH,KAAK6F,UAAYqB,CACnB,ECjIK,MAAMY,UAAcpB,EAIzB3F,WAAAA,IAAe4F,GACb1F,MAAM0F,EACR,CAEA,OAAIoB,GACF,OAAOC,OAAqB,YAAdhI,KAAK4G,QAAyB,CAC9C,CAEA,QAAIqB,GACF,OAAOD,OAAOhI,KAAK4G,QAAU,KAAQ,CACvC,CAEA,QAAIzE,GACF,OAAO,EACT,CAEA,YAAIqE,GACF,OAAO,CACT,CAQA,eAAO0B,CAASH,EAAKE,GACnB,OAAO,IAAIjI,KAAK+H,EAAKE,EACvB,EAGFH,EAAMD,sBClCN,MAAMhC,EAAY,WAGX,MAAMsC,UAAoBjD,EAI/B,WAAO3C,CAAKuC,GACV,OAAOA,EAAOrC,cAChB,CAKA,YAAOmB,CAAMC,EAAOa,GAClB,GACmB,iBAAVb,KACLA,GAhBU,GAgBYA,GAASgC,IACjChC,EAAQ,GAAM,EAEd,MAAM,IAAIhD,EAAe,qBAE3B6D,EAAOT,cAAcJ,EACvB,CAKA,cAAOsB,CAAQtB,GACb,MAAqB,iBAAVA,GAAsBA,EAAQ,GAAM,IAIxCA,GAhCO,GAgCeA,GAASgC,EACxC,EAGFsC,EAAYtC,UAAYA,EACxBsC,EAAYrC,UArCM,ECFX,MAAMsC,UAAsB1B,EAIjC3F,WAAAA,IAAe4F,GACb1F,MAAM0F,EACR,CAEA,OAAIoB,GACF,OAAOC,OAAqB,YAAdhI,KAAK4G,QAAyB,CAC9C,CAEA,QAAIqB,GACF,OAAOD,OAAOhI,KAAK4G,QAAU,KAAQ,CACvC,CAEA,QAAIzE,GACF,OAAO,EACT,CAEA,YAAIqE,GACF,OAAO,CACT,CAQA,eAAO0B,CAASH,EAAKE,GACnB,OAAO,IAAIjI,KAAK+H,EAAKE,EACvB,EAGFG,EAAcP,sBClCP,MAAMQ,UAAcnD,EAIzB,WAAO3C,CAAKuC,GACV,OAAOA,EAAOlC,aAChB,CAKA,YAAOgB,CAAMC,EAAOa,GAClB,GAAqB,iBAAVb,EAAoB,MAAM,IAAIhD,EAAe,gBAExD6D,EAAON,aAAaP,EACtB,CAKA,cAAOsB,CAAQtB,GACb,MAAwB,iBAAVA,CAChB,ECtBK,MAAMyE,UAAepD,EAI1B,WAAO3C,CAAKuC,GACV,OAAOA,EAAOjC,cAChB,CAKA,YAAOe,CAAMC,EAAOa,GAClB,GAAqB,iBAAVb,EAAoB,MAAM,IAAIhD,EAAe,gBAExD6D,EAAOL,cAAcR,EACvB,CAKA,cAAOsB,CAAQtB,GACb,MAAwB,iBAAVA,CAChB,ECtBK,MAAM0E,UAAkBrD,EAC7B,WAAO3C,GACL,MAAM,IAAIpB,EAAmB,0BAC/B,CAEA,YAAOyC,GACL,MAAM,IAAIzC,EAAmB,0BAC/B,CAEA,cAAOgE,GACL,OAAO,CACT,ECVK,MAAMqD,UAAatD,EAIxB,WAAO3C,CAAKuC,GACV,MAAMjB,EAAQkC,EAAIxD,KAAKuC,GAEvB,OAAQjB,GACN,KAAK,EACH,OAAO,EACT,KAAK,EACH,OAAO,EACT,QACE,MAAM,IAAI3C,EAAe,OAAO2C,gCAEtC,CAKA,YAAOD,CAAMC,EAAOa,GAClB,MAAM+D,EAAS5E,EAAQ,EAAI,EAC3BkC,EAAInC,MAAM6E,EAAQ/D,EACpB,CAKA,cAAOS,CAAQtB,GACb,MAAwB,kBAAVA,CAChB,iBC9BK,MAAM6E,UAAetD,EAC1BrE,WAAAA,CAAY4H,EAAYR,EAAYtC,WAClC5E,QACAjB,KAAK4I,WAAaD,CACpB,CAKApG,IAAAA,CAAKuC,GACH,MAAM3C,EAAOgG,EAAY5F,KAAKuC,GAC9B,GAAI3C,EAAOnC,KAAK4I,WACd,MAAM,IAAI1H,EACR,OAAOiB,mCAAsCnC,KAAK4I,cAGtD,OAAO9D,EAAOvC,KAAKJ,EACrB,CAEA0G,UAAAA,CAAW/D,GACT,OAAO9E,KAAKuC,KAAKuC,GAAQQ,SAAS,OACpC,CAKA1B,KAAAA,CAAMC,EAAOa,GAEX,MAAMvC,EACa,iBAAV0B,EACH5D,EAAO6I,WAAWjF,EAAO,QACzBA,EAAM9B,OACZ,GAAII,EAAOnC,KAAK4I,WACd,MAAM,IAAI/H,EACR,OAAOgD,EAAM9B,gCAAgC/B,KAAK4I,cAGtDT,EAAYvE,MAAMzB,EAAMuC,GACxBA,EAAOd,MAAMC,EAAO1B,EACtB,CAKAgD,OAAAA,CAAQtB,GACN,MAAqB,iBAAVA,EACF5D,EAAO6I,WAAWjF,EAAO,SAAW7D,KAAK4I,cAE9C/E,aAAiBrC,OAASvB,EAAOsB,SAASsC,KACrCA,EAAM9B,QAAU/B,KAAK4I,UAGhC,iBCrDK,MAAMG,UAAe3D,EAC1BrE,WAAAA,CAAYgB,GACVd,QACAjB,KAAK8B,QAAUC,CACjB,CAKAQ,IAAAA,CAAKuC,GACH,OAAOA,EAAOvC,KAAKvC,KAAK8B,QAC1B,CAKA8B,KAAAA,CAAMC,EAAOa,GACX,MAAM,OAAE3C,GAAW8B,EACnB,GAAI9B,IAAW/B,KAAK8B,QAClB,MAAM,IAAIjB,EACR,OAAOgD,EAAM9B,0BAA0B/B,KAAK8B,WAEhD4C,EAAOd,MAAMC,EAAO9B,EACtB,CAKAoD,OAAAA,CAAQtB,GACN,OAAO5D,EAAOsB,SAASsC,IAAUA,EAAM9B,SAAW/B,KAAK8B,OACzD,iBC7BK,MAAMkH,UAAkB5D,EAC7BrE,WAAAA,CAAY4H,EAAYR,EAAYtC,WAClC5E,QACAjB,KAAK4I,WAAaD,CACpB,CAKApG,IAAAA,CAAKuC,GACH,MAAM3C,EAAOgG,EAAY5F,KAAKuC,GAC9B,GAAI3C,EAAOnC,KAAK4I,WACd,MAAM,IAAI1H,EACR,OAAOiB,sCAAyCnC,KAAK4I,cAEzD,OAAO9D,EAAOvC,KAAKJ,EACrB,CAKAyB,KAAAA,CAAMC,EAAOa,GACX,MAAM,OAAE3C,GAAW8B,EACnB,GAAIA,EAAM9B,OAAS/B,KAAK4I,WACtB,MAAM,IAAI/H,EACR,OAAOgD,EAAM9B,gCAAgC/B,KAAK4I,cAGtDT,EAAYvE,MAAM7B,EAAQ2C,GAC1BA,EAAOd,MAAMC,EAAO9B,EACtB,CAKAoD,OAAAA,CAAQtB,GACN,OAAO5D,EAAOsB,SAASsC,IAAUA,EAAM9B,QAAU/B,KAAK4I,UACxD,ECtCK,MAAMpH,UAAc4D,EACzBrE,WAAAA,CAAYkI,EAAWlH,GACrBd,QACAjB,KAAKkJ,WAAaD,EAClBjJ,KAAK8B,QAAUC,CACjB,CAKAQ,IAAAA,CAAKuC,GAEH,MAAMvE,EAAS,IAAI4I,EAAAA,EAAO3H,MAAMxB,KAAK8B,SAErC,IAAK,IAAIO,EAAI,EAAGA,EAAIrC,KAAK8B,QAASO,IAChC9B,EAAO8B,GAAKrC,KAAKkJ,WAAW3G,KAAKuC,GAEnC,OAAOvE,CACT,CAKAqD,KAAAA,CAAMC,EAAOa,GACX,IAAKyE,EAAAA,EAAO3H,MAAMC,QAAQoC,GACxB,MAAM,IAAIhD,EAAe,sBAE3B,GAAIgD,EAAM9B,SAAW/B,KAAK8B,QACxB,MAAM,IAAIjB,EACR,qBAAqBgD,EAAM9B,oBAAoB/B,KAAK8B,WAGxD,IAAK,MAAMsH,KAASvF,EAClB7D,KAAKkJ,WAAWtF,MAAMwF,EAAO1E,EAEjC,CAKAS,OAAAA,CAAQtB,GACN,KAAMA,aAAiBsF,EAAAA,EAAO3H,QAAUqC,EAAM9B,SAAW/B,KAAK8B,QAC5D,OAAO,EAGT,IAAK,MAAMsH,KAASvF,EAClB,IAAK7D,KAAKkJ,WAAW/D,QAAQiE,GAAQ,OAAO,EAE9C,OAAO,CACT,EChDK,MAAMC,UAAiBjE,EAC5BrE,WAAAA,CAAYkI,EAAWN,EAAYR,EAAYtC,WAC7C5E,QACAjB,KAAKkJ,WAAaD,EAClBjJ,KAAK4I,WAAaD,CACpB,CAKApG,IAAAA,CAAKuC,GACH,MAAM/C,EAASoG,EAAY5F,KAAKuC,GAChC,GAAI/C,EAAS/B,KAAK4I,WAChB,MAAM,IAAI1H,EACR,OAAOa,qCAA0C/B,KAAK4I,cAG1D,MAAMrI,EAAS,IAAIiB,MAAMO,GACzB,IAAK,IAAIM,EAAI,EAAGA,EAAIN,EAAQM,IAC1B9B,EAAO8B,GAAKrC,KAAKkJ,WAAW3G,KAAKuC,GAEnC,OAAOvE,CACT,CAKAqD,KAAAA,CAAMC,EAAOa,GACX,KAAMb,aAAiBrC,OACrB,MAAM,IAAIX,EAAe,sBAE3B,GAAIgD,EAAM9B,OAAS/B,KAAK4I,WACtB,MAAM,IAAI/H,EACR,qBAAqBgD,EAAM9B,0BAA0B/B,KAAK4I,cAG9DT,EAAYvE,MAAMC,EAAM9B,OAAQ2C,GAChC,IAAK,MAAM0E,KAASvF,EAClB7D,KAAKkJ,WAAWtF,MAAMwF,EAAO1E,EAEjC,CAKAS,OAAAA,CAAQtB,GACN,KAAMA,aAAiBrC,QAAUqC,EAAM9B,OAAS/B,KAAK4I,WACnD,OAAO,EAET,IAAK,MAAMQ,KAASvF,EAClB,IAAK7D,KAAKkJ,WAAW/D,QAAQiE,GAAQ,OAAO,EAE9C,OAAO,CACT,ECtDK,MAAME,UAAepE,EAC1BnE,WAAAA,CAAYkI,GACVhI,QACAjB,KAAKkJ,WAAaD,CACpB,CAKA1G,IAAAA,CAAKuC,GACH,GAAI0D,EAAKjG,KAAKuC,GACZ,OAAO9E,KAAKkJ,WAAW3G,KAAKuC,EAIhC,CAKAlB,KAAAA,CAAMC,EAAOa,GACX,MAAM6E,EAAY1F,QAElB2E,EAAK5E,MAAM2F,EAAW7E,GAElB6E,GACFvJ,KAAKkJ,WAAWtF,MAAMC,EAAOa,EAEjC,CAKAS,OAAAA,CAAQtB,GACN,OAAIA,SAGG7D,KAAKkJ,WAAW/D,QAAQtB,EACjC,ECtCK,MAAM2F,UAAatE,EAGxB,WAAO3C,GAEP,CAEA,YAAOqB,CAAMC,GACX,QAAc4F,IAAV5F,EACF,MAAM,IAAIhD,EAAe,uCAC7B,CAEA,cAAOsE,CAAQtB,GACb,YAAiB4F,IAAV5F,CACT,ECbK,MAAM6F,UAAaxE,EACxBnE,WAAAA,CAAY4E,EAAM9B,GAChB5C,QACAjB,KAAK2F,KAAOA,EACZ3F,KAAK6D,MAAQA,CACf,CAKA,WAAOtB,CAAKuC,GACV,MAAM2D,EAAS1C,EAAIxD,KAAKuC,GAClB6E,EAAM3J,KAAK4J,SAASnB,GAC1B,QAAYgB,IAARE,EACF,MAAM,IAAIzI,EACR,WAAWlB,KAAK6J,6BAA6BpB,KAEjD,OAAOkB,CACT,CAKA,YAAO/F,CAAMC,EAAOa,GAClB,IAAK1E,KAAKmF,QAAQtB,GAChB,MAAM,IAAIhD,EACR,GAAGgD,mBAAuBA,GAAOgG,iBAC/B7J,KAAK6J,aACFC,KAAKC,UAAUlG,MAIxBkC,EAAInC,MAAMC,EAAMA,MAAOa,EACzB,CAKA,cAAOS,CAAQtB,GACb,OACEA,GAAO9C,aAAa8I,WAAa7J,KAAK6J,UACtCtE,EAAkB1B,EAAO7D,KAE7B,CAEA,cAAOgK,GACL,OAAOhK,KAAKiK,QACd,CAEA,aAAOC,GACL,OAAOxJ,OAAOwJ,OAAOlK,KAAKiK,SAC5B,CAEA,eAAOE,CAASxE,GACd,MAAMpF,EAASP,KAAKiK,SAAStE,GAE7B,IAAKpF,EACH,MAAM,IAAIO,UAAU,GAAG6E,wBAA2B3F,KAAK6J,YAEzD,OAAOtJ,CACT,CAEA,gBAAO6J,CAAUvG,GACf,MAAMtD,EAASP,KAAK4J,SAAS/F,GAC7B,QAAe4F,IAAXlJ,EACF,MAAM,IAAIO,UACR,GAAG+C,qCAAyC7D,KAAK6J,YAErD,OAAOtJ,CACT,CAEA,aAAO8J,CAAOC,EAAS3E,EAAMqE,GAC3B,MAAMO,EAAY,cAAcb,IAEhCa,EAAUV,SAAWlE,EACrB2E,EAAQE,QAAQ7E,GAAQ4E,EAExBA,EAAUN,SAAW,CAAC,EACtBM,EAAUX,SAAW,CAAC,EAEtB,IAAK,MAAOa,EAAK5G,KAAUnD,OAAOgK,QAAQV,GAAU,CAClD,MAAMW,EAAO,IAAIJ,EAAUE,EAAK5G,GAChC0G,EAAUN,SAASQ,GAAOE,EAC1BJ,EAAUX,SAAS/F,GAAS8G,EAC5BJ,EAAUE,GAAO,IAAME,CACzB,CAEA,OAAOJ,CACT,ECzFK,MAAMK,UAAkB1F,EAE7B2F,OAAAA,GACE,MAAM,IAAI1J,EACR,iEAEJ,ECLK,MAAM2J,UAAe1F,EAC1BrE,WAAAA,CAAYgK,GACV9J,QACAjB,KAAKgL,YAAcD,GAAc,CAAC,CACpC,CAKA,WAAOxI,CAAKuC,GACV,MAAMiG,EAAa,CAAC,EACpB,IAAK,MAAOE,EAAWC,KAASlL,KAAKmL,QACnCJ,EAAWE,GAAaC,EAAK3I,KAAKuC,GAEpC,OAAO,IAAI9E,KAAK+K,EAClB,CAKA,YAAOnH,CAAMC,EAAOa,GAClB,IAAK1E,KAAKmF,QAAQtB,GAChB,MAAM,IAAIhD,EACR,GAAGgD,qBAAyBA,GAAO9C,aAAaqK,mBAC9CpL,KAAKoL,eACFtB,KAAKC,UAAUlG,MAIxB,IAAK,MAAOoH,EAAWC,KAASlL,KAAKmL,QAAS,CAC5C,MAAME,EAAYxH,EAAMmH,YAAYC,GACpCC,EAAKtH,MAAMyH,EAAW3G,EACxB,CACF,CAKA,cAAOS,CAAQtB,GACb,OACEA,GAAO9C,aAAaqK,aAAepL,KAAKoL,YACxC7F,EAAkB1B,EAAO7D,KAE7B,CAEA,aAAOqK,CAAOC,EAAS3E,EAAM2F,GAC3B,MAAMC,EAAc,cAAcT,IAElCS,EAAYH,WAAazF,EAEzB2E,EAAQE,QAAQ7E,GAAQ4F,EAExB,MAAMC,EAAe,IAAIhK,MAAM8J,EAAOvJ,QACtC,IAAK,IAAIM,EAAI,EAAGA,EAAIiJ,EAAOvJ,OAAQM,IAAK,CACtC,MAAMoJ,EAAkBH,EAAOjJ,GACzB4I,EAAYQ,EAAgB,GAClC,IAAIC,EAAQD,EAAgB,GACxBC,aAAiBd,IACnBc,EAAQA,EAAMb,QAAQP,IAExBkB,EAAanJ,GAAK,CAAC4I,EAAWS,GAE9BH,EAAYnL,UAAU6K,GAAaU,EAAqBV,EAC1D,CAIA,OAFAM,EAAYJ,QAAUK,EAEfD,CACT,EAGF,SAASI,EAAqBhG,GAC5B,OAAO,SAA8B9B,GAInC,YAHc4F,IAAV5F,IACF7D,KAAKgL,YAAYrF,GAAQ9B,GAEpB7D,KAAKgL,YAAYrF,EAC1B,CACF,CC7EO,MAAMiG,UAAcxG,EACzBrE,WAAAA,CAAY8K,EAAShI,GACnB5C,QACAjB,KAAK8L,IAAID,EAAShI,EACpB,CAEAiI,GAAAA,CAAID,EAAShI,GACY,iBAAZgI,IACTA,EAAU7L,KAAKe,YAAYgL,UAAU5B,SAAS0B,IAGhD7L,KAAKgM,QAAUH,EACf,MAAMI,EAAMjM,KAAKe,YAAYmL,aAAalM,KAAKgM,SAC/ChM,KAAKmM,KAAOF,EACZjM,KAAKoM,SAAWH,IAAQzC,EAAOA,EAAOxJ,KAAKe,YAAYsL,MAAMJ,GAC7DjM,KAAK4G,OAAS/C,CAChB,CAEAyI,GAAAA,CAAIC,EAAUvM,KAAKmM,MACjB,GAAInM,KAAKmM,OAAS3C,GAAQxJ,KAAKmM,OAASI,EACtC,MAAM,IAAIzL,UAAU,GAAGyL,aACzB,OAAOvM,KAAK4G,MACd,CAEA4F,SACE,OAAOxM,KAAKgM,OACd,CAEAC,GAAAA,GACE,OAAOjM,KAAKmM,IACd,CAEAM,OAAAA,GACE,OAAOzM,KAAKoM,QACd,CAEAvI,KAAAA,GACE,OAAO7D,KAAK4G,MACd,CAEA,mBAAOsF,CAAaL,GAClB,MAAMa,EAAS1M,KAAK2M,UAAUL,IAAIT,GAClC,QAAepC,IAAXiD,EACF,OAAOA,EAET,GAAI1M,KAAK4M,YACP,OAAO5M,KAAK4M,YAEd,MAAM,IAAI9L,UAAU,qBAAqB+K,IAC3C,CAEA,oBAAOgB,CAAcZ,GACnB,OAAIA,IAAQzC,EACHA,EAEFxJ,KAAKqM,MAAMJ,EACpB,CAKA,WAAO1J,CAAKuC,GACV,MAAM+G,EAAU7L,KAAK+L,UAAUxJ,KAAKuC,GAC9BmH,EAAMjM,KAAKkM,aAAaL,GACxBY,EAAUR,IAAQzC,EAAOA,EAAOxJ,KAAKqM,MAAMJ,GACjD,IAAIpI,EAMJ,OAJEA,OADc4F,IAAZgD,EACMA,EAAQlK,KAAKuC,GAEbmH,EAAI1J,KAAKuC,GAEZ,IAAI9E,KAAK6L,EAAShI,EAC3B,CAKA,YAAOD,CAAMC,EAAOa,GAClB,IAAK1E,KAAKmF,QAAQtB,GAChB,MAAM,IAAIhD,EACR,GAAGgD,oBAAwBA,GAAOiJ,kBAChC9M,KAAK8M,cACFhD,KAAKC,UAAUlG,MAIxB7D,KAAK+L,UAAUnI,MAAMC,EAAM2I,SAAU9H,GACrCb,EAAM4I,UAAU7I,MAAMC,EAAMA,QAASa,EACvC,CAKA,cAAOS,CAAQtB,GACb,OACEA,GAAO9C,aAAa+L,YAAc9M,KAAK8M,WACvCvH,EAAkB1B,EAAO7D,KAE7B,CAEA,aAAOqK,CAAOC,EAAS3E,EAAMoH,GAC3B,MAAMC,EAAa,cAAcpB,IAEjCoB,EAAWF,UAAYnH,EACvB2E,EAAQE,QAAQ7E,GAAQqH,EAEpBD,EAAOE,oBAAoBrC,EAC7BoC,EAAWjB,UAAYgB,EAAOE,SAASpC,QAAQP,GAE/C0C,EAAWjB,UAAYgB,EAAOE,SAGhCD,EAAWL,UAAY,IAAIO,IAC3BF,EAAWX,MAAQ,CAAC,EAGpB,IAAIc,EAAaJ,EAAOI,WACpBA,aAAsBvC,IACxBuC,EAAaA,EAAWtC,QAAQP,IAGlC0C,EAAWJ,YAAcO,EAEzB,IAAK,MAAOtB,EAASU,KAAYQ,EAAOK,SAAU,CAChD,MAAM3C,EACe,iBAAZoB,EACHmB,EAAWjB,UAAU5B,SAAS0B,GAC9BA,EAENmB,EAAWL,UAAUb,IAAIrB,EAAK8B,EAChC,CAMA,QAAoC9C,IAAhCuD,EAAWjB,UAAU7B,OACvB,IAAK,MAAM2B,KAAWmB,EAAWjB,UAAU7B,SAEzC8C,EAAWnB,EAAQlG,MAAQ,SAAa9B,GACtC,OAAO,IAAImJ,EAAWnB,EAAShI,EACjC,EAGAmJ,EAAW5M,UAAUyL,EAAQlG,MAAQ,SAAa9B,GAChD,OAAO7D,KAAK8L,IAAID,EAAShI,EAC3B,EAIJ,GAAIkJ,EAAOM,KACT,IAAK,MAAOC,EAAUzJ,KAAUnD,OAAOgK,QAAQqC,EAAOM,MACpDL,EAAWX,MAAMiB,GACfzJ,aAAiB+G,EAAY/G,EAAMgH,QAAQP,GAAWzG,EAEpDA,IAAU2F,IACZwD,EAAW5M,UAAUkN,GAAY,WAC/B,OAAOtN,KAAKsM,IAAIgB,EAClB,GAKN,OAAON,CACT,EClKF,MAAMO,UAAwB3C,EAC5B7J,WAAAA,CAAY4E,GACV1E,QACAjB,KAAK2F,KAAOA,CACd,CAEAkF,OAAAA,CAAQP,GAEN,OADaA,EAAQkD,YAAYxN,KAAK2F,MAC1BkF,QAAQP,EACtB,EAGF,MAAMmD,UAAuB7C,EAC3B7J,WAAAA,CAAY2M,EAAgB3L,EAAQ4L,GAAW,GAC7C1M,QACAjB,KAAK0N,eAAiBA,EACtB1N,KAAK+B,OAASA,EACd/B,KAAK2N,SAAWA,CAClB,CAEA9C,OAAAA,CAAQP,GACN,IAAIsD,EAAgB5N,KAAK0N,eACrB3L,EAAS/B,KAAK+B,OAUlB,OARI6L,aAAyBhD,IAC3BgD,EAAgBA,EAAc/C,QAAQP,IAGpCvI,aAAkB6I,IACpB7I,EAASA,EAAO8I,QAAQP,IAGtBtK,KAAK2N,SACA,IAAIE,EAAkBD,EAAe7L,GAEvC,IAAI8L,EAAeD,EAAe7L,EAC3C,EAGF,MAAM+L,UAAwBlD,EAC5B7J,WAAAA,CAAY2M,GACVzM,QACAjB,KAAK0N,eAAiBA,EACtB1N,KAAK2F,KAAO+H,EAAe/H,IAC7B,CAEAkF,OAAAA,CAAQP,GACN,IAAIsD,EAAgB5N,KAAK0N,eAMzB,OAJIE,aAAyBhD,IAC3BgD,EAAgBA,EAAc/C,QAAQP,IAGjC,IAAIuD,EAAgBD,EAC7B,EAGF,MAAMG,UAAuBnD,EAC3B7J,WAAAA,CAAYiN,EAAWjM,GACrBd,QACAjB,KAAKgO,UAAYA,EACjBhO,KAAK+B,OAASA,CAChB,CAEA8I,OAAAA,CAAQP,GACN,IAAIvI,EAAS/B,KAAK+B,OAMlB,OAJIA,aAAkB6I,IACpB7I,EAASA,EAAO8I,QAAQP,IAGnB,IAAItK,KAAKgO,UAAUjM,EAC5B,EAGF,MAAMkM,GACJlN,WAAAA,CAAYA,EAAa4E,EAAMuI,GAC7BlO,KAAKe,YAAcA,EACnBf,KAAK2F,KAAOA,EACZ3F,KAAK+M,OAASmB,CAChB,CAMArD,OAAAA,CAAQP,GACN,OAAItK,KAAK2F,QAAQ2E,EAAQE,QAChBF,EAAQE,QAAQxK,KAAK2F,MAGvB3F,KAAKe,YAAYuJ,EAAStK,KAAK2F,KAAM3F,KAAK+M,OACnD,EAKF,SAASoB,GAAc7D,EAAS8D,EAAUvK,GAKxC,OAJIA,aAAiB+G,IACnB/G,EAAQA,EAAMgH,QAAQP,IAExBA,EAAQE,QAAQ4D,GAAYvK,EACrBA,CACT,CAEA,SAASwK,GAAY/D,EAAS3E,EAAM9B,GAElC,OADAyG,EAAQE,QAAQ7E,GAAQ9B,EACjBA,CACT,CAEA,MAAMyK,GACJvN,WAAAA,CAAYwN,GACVvO,KAAKwO,aAAeD,EACpBvO,KAAKyO,aAAe,CAAC,CACvB,CAEAC,IAAAA,CAAK/I,EAAMqE,GACT,MAAMzJ,EAAS,IAAI0N,GAAWJ,EAAcxD,OAAQ1E,EAAMqE,GAC1DhK,KAAKF,OAAO6F,EAAMpF,EACpB,CAEAoO,MAAAA,CAAOhJ,EAAMqE,GACX,MAAMzJ,EAAS,IAAI0N,GAAWJ,EAAgBxD,OAAQ1E,EAAMqE,GAC5DhK,KAAKF,OAAO6F,EAAMpF,EACpB,CAEAqO,KAAAA,CAAMjJ,EAAMuI,GACV,MAAM3N,EAAS,IAAI0N,GAAWJ,EAAexD,OAAQ1E,EAAMuI,GAC3DlO,KAAKF,OAAO6F,EAAMpF,EACpB,CAEAsO,OAAAA,CAAQlJ,EAAMuI,GACZ,MAAM3N,EAAS,IAAI0N,GAAWE,GAAexI,EAAMuI,GACnDlO,KAAKF,OAAO6F,EAAMpF,EACpB,CAEAuO,MAAMnJ,EAAMuI,GACV,MAAM3N,EAAS,IAAI0N,GAAWI,GAAa1I,EAAMuI,GACjDlO,KAAKF,OAAO6F,EAAMpF,EACpB,CAEAwO,OACE,OAAOlB,CACT,CAEAmB,IAAAA,GACE,OAAOnB,CACT,CAEAoB,GAAAA,GACE,OAAOpB,CACT,CAEAqB,KAAAA,GACE,OAAOrB,CACT,CAEAsB,IAAAA,GACE,OAAOtB,CACT,CAEAuB,MAAAA,GACE,OAAOvB,CACT,CAEAwB,KAAAA,GACE,OAAOxB,CACT,CAEAyB,MAAAA,GACE,OAAOzB,CACT,CAEA0B,SAAAA,GACE,OAAO1B,CACT,CAEAjG,MAAAA,CAAO7F,GACL,OAAO,IAAIgM,EAAeF,EAAiB9L,EAC7C,CAEAyN,MAAAA,CAAOzN,GACL,OAAO,IAAIgM,EAAeF,EAAiB9L,EAC7C,CAEA0N,SAAAA,CAAU1N,GACR,OAAO,IAAIgM,EAAeF,EAAoB9L,EAChD,CAEA2N,KAAAA,CAAMzG,EAAWlH,GACf,OAAO,IAAI0L,EAAexE,EAAWlH,EACvC,CAEA4N,QAAAA,CAAS1G,EAAWN,GAClB,OAAO,IAAI8E,EAAexE,EAAWN,GAAW,EAClD,CAEAiH,MAAAA,CAAO3G,GACL,OAAO,IAAI6E,EAAgB7E,EAC7B,CAEAnJ,MAAAA,CAAO6F,EAAMkK,GACX,QAAgCpG,IAA5BzJ,KAAKwO,aAAa7I,GAGpB,MAAM,IAAIxE,EAAmB,GAAGwE,wBAFhC3F,KAAKyO,aAAa9I,GAAQkK,CAI9B,CAEAC,MAAAA,CAAOnK,GACL,OAAO,IAAI4H,EAAgB5H,EAC7B,CAEAkF,OAAAA,GACE,IAAK,MAAMkF,KAAQrP,OAAOwJ,OAAOlK,KAAKyO,cACpCsB,EAAKlF,QAAQ,CACX2C,YAAaxN,KAAKyO,aAClBjE,QAASxK,KAAKwO,cAGpB,EAGK,SAASzB,GAAOiD,EAAIC,EAAQ,CAAC,GAClC,GAAID,EAAI,CACN,MAAME,EAAU,IAAI5B,GAAY2B,GAChCD,EAAGE,GACHA,EAAQrF,SACV,CAEA,OAAOoF,CACT,4BC5OArQ,EAAQkJ,WAuCR,SAAqBqH,GACnB,IAAIC,EAAOC,EAAQF,GACfG,EAAWF,EAAK,GAChBG,EAAkBH,EAAK,GAC3B,OAAuC,GAA9BE,EAAWC,GAAuB,EAAKA,CAClD,EA3CA3Q,EAAQ4Q,YAiDR,SAAsBL,GACpB,IAAIM,EAcApO,EAbA+N,EAAOC,EAAQF,GACfG,EAAWF,EAAK,GAChBG,EAAkBH,EAAK,GAEvBM,EAAM,IAAIC,EAVhB,SAAsBR,EAAKG,EAAUC,GACnC,OAAuC,GAA9BD,EAAWC,GAAuB,EAAKA,CAClD,CAQoBK,CAAYT,EAAKG,EAAUC,IAEzCM,EAAU,EAGVC,EAAMP,EAAkB,EACxBD,EAAW,EACXA,EAGJ,IAAKjO,EAAI,EAAGA,EAAIyO,EAAKzO,GAAK,EACxBoO,EACGM,EAAUZ,EAAIa,WAAW3O,KAAO,GAChC0O,EAAUZ,EAAIa,WAAW3O,EAAI,KAAO,GACpC0O,EAAUZ,EAAIa,WAAW3O,EAAI,KAAO,EACrC0O,EAAUZ,EAAIa,WAAW3O,EAAI,IAC/BqO,EAAIG,KAAcJ,GAAO,GAAM,IAC/BC,EAAIG,KAAcJ,GAAO,EAAK,IAC9BC,EAAIG,KAAmB,IAANJ,EAGK,IAApBF,IACFE,EACGM,EAAUZ,EAAIa,WAAW3O,KAAO,EAChC0O,EAAUZ,EAAIa,WAAW3O,EAAI,KAAO,EACvCqO,EAAIG,KAAmB,IAANJ,GAGK,IAApBF,IACFE,EACGM,EAAUZ,EAAIa,WAAW3O,KAAO,GAChC0O,EAAUZ,EAAIa,WAAW3O,EAAI,KAAO,EACpC0O,EAAUZ,EAAIa,WAAW3O,EAAI,KAAO,EACvCqO,EAAIG,KAAcJ,GAAO,EAAK,IAC9BC,EAAIG,KAAmB,IAANJ,GAGnB,OAAOC,CACT,EA5FA9Q,EAAQqR,cAkHR,SAAwBC,GAQtB,IAPA,IAAIT,EACAK,EAAMI,EAAMnP,OACZoP,EAAaL,EAAM,EACnBjK,EAAQ,GACRuK,EAAiB,MAGZ/O,EAAI,EAAGgP,EAAOP,EAAMK,EAAY9O,EAAIgP,EAAMhP,GAAK+O,EACtDvK,EAAMyK,KAAKC,EAAYL,EAAO7O,EAAIA,EAAI+O,EAAkBC,EAAOA,EAAQhP,EAAI+O,IAI1D,IAAfD,GACFV,EAAMS,EAAMJ,EAAM,GAClBjK,EAAMyK,KACJxB,EAAOW,GAAO,GACdX,EAAQW,GAAO,EAAK,IACpB,OAEsB,IAAfU,IACTV,GAAOS,EAAMJ,EAAM,IAAM,GAAKI,EAAMJ,EAAM,GAC1CjK,EAAMyK,KACJxB,EAAOW,GAAO,IACdX,EAAQW,GAAO,EAAK,IACpBX,EAAQW,GAAO,EAAK,IACpB,MAIJ,OAAO5J,EAAM2K,KAAK,GACpB,EA1IA,IALA,IAAI1B,EAAS,GACTiB,EAAY,GACZJ,EAA4B,oBAAfnQ,WAA6BA,WAAagB,MAEvDiQ,EAAO,mEACFpP,EAAI,EAAsBA,EAAboP,KAAwBpP,EAC5CyN,EAAOzN,GAAKoP,EAAKpP,GACjB0O,EAAUU,EAAKT,WAAW3O,IAAMA,EAQlC,SAASgO,EAASF,GAChB,IAAIW,EAAMX,EAAIpO,OAEd,GAAI+O,EAAM,EAAI,EACZ,MAAM,IAAIY,MAAM,kDAKlB,IAAIpB,EAAWH,EAAIwB,QAAQ,KAO3B,OANkB,IAAdrB,IAAiBA,EAAWQ,GAMzB,CAACR,EAJcA,IAAaQ,EAC/B,EACA,EAAKR,EAAW,EAGtB,CAmEA,SAASiB,EAAaL,EAAO7Q,EAAOC,GAGlC,IAFA,IAAImQ,EARoBmB,EASpBC,EAAS,GACJxP,EAAIhC,EAAOgC,EAAI/B,EAAK+B,GAAK,EAChCoO,GACIS,EAAM7O,IAAM,GAAM,WAClB6O,EAAM7O,EAAI,IAAM,EAAK,QACP,IAAf6O,EAAM7O,EAAI,IACbwP,EAAOP,KAdFxB,GADiB8B,EAeMnB,IAdT,GAAK,IACxBX,EAAO8B,GAAO,GAAK,IACnB9B,EAAO8B,GAAO,EAAI,IAClB9B,EAAa,GAAN8B,IAaT,OAAOC,EAAOL,KAAK,GACrB,CAlGAT,EAAU,IAAIC,WAAW,IAAM,GAC/BD,EAAU,IAAIC,WAAW,IAAM,+BCT/B,MAAMc,EAAS,EAAQ,KACjBC,EAAU,EAAQ,KAClBC,EACe,mBAAXC,QAAkD,mBAAlBA,OAAY,IAChDA,OAAY,IAAE,8BACd,KAENrS,EAAQ,GAASK,EAEjBL,EAAQ,GAAoB,GAE5B,MAAMsS,EAAe,WAwDrB,SAASC,EAAcpQ,GACrB,GAAIA,EAASmQ,EACX,MAAM,IAAIpL,WAAW,cAAgB/E,EAAS,kCAGhD,MAAMqQ,EAAM,IAAI5R,WAAWuB,GAE3B,OADArB,OAAOC,eAAeyR,EAAKnS,EAAOG,WAC3BgS,CACT,CAYA,SAASnS,EAAQoS,EAAKC,EAAkBvQ,GAEtC,GAAmB,iBAARsQ,EAAkB,CAC3B,GAAgC,iBAArBC,EACT,MAAM,IAAIxR,UACR,sEAGJ,OAAOoC,EAAYmP,EACrB,CACA,OAAOzQ,EAAKyQ,EAAKC,EAAkBvQ,EACrC,CAIA,SAASH,EAAMiC,EAAOyO,EAAkBvQ,GACtC,GAAqB,iBAAV8B,EACT,OAqHJ,SAAqB+D,EAAQ2K,GACH,iBAAbA,GAAsC,KAAbA,IAClCA,EAAW,QAGb,IAAKtS,EAAOuS,WAAWD,GACrB,MAAM,IAAIzR,UAAU,qBAAuByR,GAG7C,MAAMxQ,EAAwC,EAA/B+G,EAAWlB,EAAQ2K,GAClC,IAAIH,EAAMD,EAAapQ,GAEvB,MAAM0Q,EAASL,EAAIxO,MAAMgE,EAAQ2K,GAE7BE,IAAW1Q,IAIbqQ,EAAMA,EAAI9K,MAAM,EAAGmL,IAGrB,OAAOL,CACT,CA3IWzK,CAAW9D,EAAOyO,GAG3B,GAAI5Q,YAAYC,OAAOkC,GACrB,OAkJJ,SAAwB6O,GACtB,GAAIC,EAAWD,EAAWlS,YAAa,CACrC,MAAMiD,EAAO,IAAIjD,WAAWkS,GAC5B,OAAOE,EAAgBnP,EAAKR,OAAQQ,EAAKoP,WAAYpP,EAAKqF,WAC5D,CACA,OAAOgK,EAAcJ,EACvB,CAxJWK,CAAclP,GAGvB,GAAa,MAATA,EACF,MAAM,IAAI/C,UACR,yHACiD+C,GAIrD,GAAI8O,EAAW9O,EAAOnC,cACjBmC,GAAS8O,EAAW9O,EAAMZ,OAAQvB,aACrC,OAAOkR,EAAgB/O,EAAOyO,EAAkBvQ,GAGlD,GAAiC,oBAAtBiR,oBACNL,EAAW9O,EAAOmP,oBAClBnP,GAAS8O,EAAW9O,EAAMZ,OAAQ+P,oBACrC,OAAOJ,EAAgB/O,EAAOyO,EAAkBvQ,GAGlD,GAAqB,iBAAV8B,EACT,MAAM,IAAI/C,UACR,yEAIJ,MAAMiG,EAAUlD,EAAMkD,SAAWlD,EAAMkD,UACvC,GAAe,MAAXA,GAAmBA,IAAYlD,EACjC,OAAO5D,EAAO2B,KAAKmF,EAASuL,EAAkBvQ,GAGhD,MAAMkR,EAkJR,SAAqBC,GACnB,GAAIjT,EAAOsB,SAAS2R,GAAM,CACxB,MAAMpC,EAA4B,EAAtBqC,EAAQD,EAAInR,QAClBqQ,EAAMD,EAAarB,GAEzB,OAAmB,IAAfsB,EAAIrQ,QAIRmR,EAAIzP,KAAK2O,EAAK,EAAG,EAAGtB,GAHXsB,CAKX,CAEA,QAAmB3I,IAAfyJ,EAAInR,OACN,MAA0B,iBAAfmR,EAAInR,QAAuBqR,EAAYF,EAAInR,QAC7CoQ,EAAa,GAEfW,EAAcI,GAGvB,GAAiB,WAAbA,EAAIhI,MAAqB1J,MAAMC,QAAQyR,EAAIG,MAC7C,OAAOP,EAAcI,EAAIG,KAE7B,CAzKYC,CAAWzP,GACrB,GAAIoP,EAAG,OAAOA,EAEd,GAAsB,oBAAXhB,QAAgD,MAAtBA,OAAOsB,aACH,mBAA9B1P,EAAMoO,OAAOsB,aACtB,OAAOtT,EAAO2B,KAAKiC,EAAMoO,OAAOsB,aAAa,UAAWjB,EAAkBvQ,GAG5E,MAAM,IAAIjB,UACR,yHACiD+C,EAErD,CAmBA,SAAS2P,EAAYrR,GACnB,GAAoB,iBAATA,EACT,MAAM,IAAIrB,UAAU,0CACf,GAAIqB,EAAO,EAChB,MAAM,IAAI2E,WAAW,cAAgB3E,EAAO,iCAEhD,CA0BA,SAASe,EAAaf,GAEpB,OADAqR,EAAWrR,GACJgQ,EAAahQ,EAAO,EAAI,EAAoB,EAAhBgR,EAAQhR,GAC7C,CAuCA,SAAS2Q,EAAepD,GACtB,MAAM3N,EAAS2N,EAAM3N,OAAS,EAAI,EAA4B,EAAxBoR,EAAQzD,EAAM3N,QAC9CqQ,EAAMD,EAAapQ,GACzB,IAAK,IAAIM,EAAI,EAAGA,EAAIN,EAAQM,GAAK,EAC/B+P,EAAI/P,GAAgB,IAAXqN,EAAMrN,GAEjB,OAAO+P,CACT,CAUA,SAASQ,EAAiBlD,EAAOmD,EAAY9Q,GAC3C,GAAI8Q,EAAa,GAAKnD,EAAM5G,WAAa+J,EACvC,MAAM,IAAI/L,WAAW,wCAGvB,GAAI4I,EAAM5G,WAAa+J,GAAc9Q,GAAU,GAC7C,MAAM,IAAI+E,WAAW,wCAGvB,IAAIsL,EAYJ,OAVEA,OADiB3I,IAAfoJ,QAAuCpJ,IAAX1H,EACxB,IAAIvB,WAAWkP,QACDjG,IAAX1H,EACH,IAAIvB,WAAWkP,EAAOmD,GAEtB,IAAIrS,WAAWkP,EAAOmD,EAAY9Q,GAI1CrB,OAAOC,eAAeyR,EAAKnS,EAAOG,WAE3BgS,CACT,CA2BA,SAASe,EAASpR,GAGhB,GAAIA,GAAUmQ,EACZ,MAAM,IAAIpL,WAAW,0DACaoL,EAAa5M,SAAS,IAAM,UAEhE,OAAgB,EAATvD,CACT,CAsGA,SAAS+G,EAAYlB,EAAQ2K,GAC3B,GAAItS,EAAOsB,SAASqG,GAClB,OAAOA,EAAO7F,OAEhB,GAAIL,YAAYC,OAAOiG,IAAW+K,EAAW/K,EAAQlG,aACnD,OAAOkG,EAAOkB,WAEhB,GAAsB,iBAAXlB,EACT,MAAM,IAAI9G,UACR,kGAC0B8G,GAI9B,MAAMkJ,EAAMlJ,EAAO7F,OACb0R,EAAaC,UAAU3R,OAAS,IAAsB,IAAjB2R,UAAU,GACrD,IAAKD,GAAqB,IAAR3C,EAAW,OAAO,EAGpC,IAAI6C,GAAc,EAClB,OACE,OAAQpB,GACN,IAAK,QACL,IAAK,SACL,IAAK,SACH,OAAOzB,EACT,IAAK,OACL,IAAK,QACH,OAAO8C,EAAYhM,GAAQ7F,OAC7B,IAAK,OACL,IAAK,QACL,IAAK,UACL,IAAK,WACH,OAAa,EAAN+O,EACT,IAAK,MACH,OAAOA,IAAQ,EACjB,IAAK,SACH,OAAO+C,EAAcjM,GAAQ7F,OAC/B,QACE,GAAI4R,EACF,OAAOF,GAAa,EAAIG,EAAYhM,GAAQ7F,OAE9CwQ,GAAY,GAAKA,GAAUuB,cAC3BH,GAAc,EAGtB,CAGA,SAASI,EAAcxB,EAAUlS,EAAOC,GACtC,IAAIqT,GAAc,EAclB,SALclK,IAAVpJ,GAAuBA,EAAQ,KACjCA,EAAQ,GAINA,EAAQL,KAAK+B,OACf,MAAO,GAOT,SAJY0H,IAARnJ,GAAqBA,EAAMN,KAAK+B,UAClCzB,EAAMN,KAAK+B,QAGTzB,GAAO,EACT,MAAO,GAOT,IAHAA,KAAS,KACTD,KAAW,GAGT,MAAO,GAKT,IAFKkS,IAAUA,EAAW,UAGxB,OAAQA,GACN,IAAK,MACH,OAAOyB,EAAShU,KAAMK,EAAOC,GAE/B,IAAK,OACL,IAAK,QACH,OAAO2T,EAAUjU,KAAMK,EAAOC,GAEhC,IAAK,QACH,OAAO4T,EAAWlU,KAAMK,EAAOC,GAEjC,IAAK,SACL,IAAK,SACH,OAAO6T,EAAYnU,KAAMK,EAAOC,GAElC,IAAK,SACH,OAAO8T,EAAYpU,KAAMK,EAAOC,GAElC,IAAK,OACL,IAAK,QACL,IAAK,UACL,IAAK,WACH,OAAO+T,EAAarU,KAAMK,EAAOC,GAEnC,QACE,GAAIqT,EAAa,MAAM,IAAI7S,UAAU,qBAAuByR,GAC5DA,GAAYA,EAAW,IAAIuB,cAC3BH,GAAc,EAGtB,CAUA,SAASW,EAAMrB,EAAGsB,EAAGC,GACnB,MAAMnS,EAAI4Q,EAAEsB,GACZtB,EAAEsB,GAAKtB,EAAEuB,GACTvB,EAAEuB,GAAKnS,CACT,CA2IA,SAASoS,EAAsBxR,EAAQyR,EAAK7B,EAAYN,EAAUoC,GAEhE,GAAsB,IAAlB1R,EAAOlB,OAAc,OAAQ,EAmBjC,GAhB0B,iBAAf8Q,GACTN,EAAWM,EACXA,EAAa,GACJA,EAAa,WACtBA,EAAa,WACJA,GAAc,aACvBA,GAAc,YAGZO,EADJP,GAAcA,KAGZA,EAAa8B,EAAM,EAAK1R,EAAOlB,OAAS,GAItC8Q,EAAa,IAAGA,EAAa5P,EAAOlB,OAAS8Q,GAC7CA,GAAc5P,EAAOlB,OAAQ,CAC/B,GAAI4S,EAAK,OAAQ,EACZ9B,EAAa5P,EAAOlB,OAAS,CACpC,MAAO,GAAI8Q,EAAa,EAAG,CACzB,IAAI8B,EACC,OAAQ,EADJ9B,EAAa,CAExB,CAQA,GALmB,iBAAR6B,IACTA,EAAMzU,EAAO2B,KAAK8S,EAAKnC,IAIrBtS,EAAOsB,SAASmT,GAElB,OAAmB,IAAfA,EAAI3S,QACE,EAEH6S,EAAa3R,EAAQyR,EAAK7B,EAAYN,EAAUoC,GAClD,GAAmB,iBAARD,EAEhB,OADAA,GAAY,IACgC,mBAAjClU,WAAWJ,UAAUuR,QAC1BgD,EACKnU,WAAWJ,UAAUuR,QAAQlR,KAAKwC,EAAQyR,EAAK7B,GAE/CrS,WAAWJ,UAAUyU,YAAYpU,KAAKwC,EAAQyR,EAAK7B,GAGvD+B,EAAa3R,EAAQ,CAACyR,GAAM7B,EAAYN,EAAUoC,GAG3D,MAAM,IAAI7T,UAAU,uCACtB,CAEA,SAAS8T,EAAclE,EAAKgE,EAAK7B,EAAYN,EAAUoC,GACrD,IA0BItS,EA1BAyS,EAAY,EACZC,EAAYrE,EAAI3O,OAChBiT,EAAYN,EAAI3S,OAEpB,QAAiB0H,IAAb8I,IAEe,UADjBA,EAAW7J,OAAO6J,GAAUuB,gBACY,UAAbvB,GACV,YAAbA,GAAuC,aAAbA,GAAyB,CACrD,GAAI7B,EAAI3O,OAAS,GAAK2S,EAAI3S,OAAS,EACjC,OAAQ,EAEV+S,EAAY,EACZC,GAAa,EACbC,GAAa,EACbnC,GAAc,CAChB,CAGF,SAAStQ,EAAM6P,EAAK/P,GAClB,OAAkB,IAAdyS,EACK1C,EAAI/P,GAEJ+P,EAAI6C,aAAa5S,EAAIyS,EAEhC,CAGA,GAAIH,EAAK,CACP,IAAIO,GAAc,EAClB,IAAK7S,EAAIwQ,EAAYxQ,EAAI0S,EAAW1S,IAClC,GAAIE,EAAKmO,EAAKrO,KAAOE,EAAKmS,GAAqB,IAAhBQ,EAAoB,EAAI7S,EAAI6S,IAEzD,IADoB,IAAhBA,IAAmBA,EAAa7S,GAChCA,EAAI6S,EAAa,IAAMF,EAAW,OAAOE,EAAaJ,OAEtC,IAAhBI,IAAmB7S,GAAKA,EAAI6S,GAChCA,GAAc,CAGpB,MAEE,IADIrC,EAAamC,EAAYD,IAAWlC,EAAakC,EAAYC,GAC5D3S,EAAIwQ,EAAYxQ,GAAK,EAAGA,IAAK,CAChC,IAAI8S,GAAQ,EACZ,IAAK,IAAIC,EAAI,EAAGA,EAAIJ,EAAWI,IAC7B,GAAI7S,EAAKmO,EAAKrO,EAAI+S,KAAO7S,EAAKmS,EAAKU,GAAI,CACrCD,GAAQ,EACR,KACF,CAEF,GAAIA,EAAO,OAAO9S,CACpB,CAGF,OAAQ,CACV,CAcA,SAASgT,EAAUjD,EAAKxK,EAAQ9D,EAAQ/B,GACtC+B,EAASkE,OAAOlE,IAAW,EAC3B,MAAMwR,EAAYlD,EAAIrQ,OAAS+B,EAC1B/B,GAGHA,EAASiG,OAAOjG,IACHuT,IACXvT,EAASuT,GAJXvT,EAASuT,EAQX,MAAMC,EAAS3N,EAAO7F,OAKtB,IAAIM,EACJ,IAJIN,EAASwT,EAAS,IACpBxT,EAASwT,EAAS,GAGflT,EAAI,EAAGA,EAAIN,IAAUM,EAAG,CAC3B,MAAMmT,EAASC,SAAS7N,EAAO8N,OAAW,EAAJrT,EAAO,GAAI,IACjD,GAAI+Q,EAAYoC,GAAS,OAAOnT,EAChC+P,EAAItO,EAASzB,GAAKmT,CACpB,CACA,OAAOnT,CACT,CAEA,SAASsT,EAAWvD,EAAKxK,EAAQ9D,EAAQ/B,GACvC,OAAO6T,EAAWhC,EAAYhM,EAAQwK,EAAIrQ,OAAS+B,GAASsO,EAAKtO,EAAQ/B,EAC3E,CAEA,SAAS8T,EAAYzD,EAAKxK,EAAQ9D,EAAQ/B,GACxC,OAAO6T,EAypCT,SAAuBE,GACrB,MAAMC,EAAY,GAClB,IAAK,IAAI1T,EAAI,EAAGA,EAAIyT,EAAI/T,SAAUM,EAEhC0T,EAAUzE,KAAyB,IAApBwE,EAAI9E,WAAW3O,IAEhC,OAAO0T,CACT,CAhqCoBC,CAAapO,GAASwK,EAAKtO,EAAQ/B,EACvD,CAEA,SAASkU,EAAa7D,EAAKxK,EAAQ9D,EAAQ/B,GACzC,OAAO6T,EAAW/B,EAAcjM,GAASwK,EAAKtO,EAAQ/B,EACxD,CAEA,SAASmU,EAAW9D,EAAKxK,EAAQ9D,EAAQ/B,GACvC,OAAO6T,EA0pCT,SAAyBE,EAAKK,GAC5B,IAAIC,EAAGC,EAAIC,EACX,MAAMP,EAAY,GAClB,IAAK,IAAI1T,EAAI,EAAGA,EAAIyT,EAAI/T,WACjBoU,GAAS,GAAK,KADa9T,EAGhC+T,EAAIN,EAAI9E,WAAW3O,GACnBgU,EAAKD,GAAK,EACVE,EAAKF,EAAI,IACTL,EAAUzE,KAAKgF,GACfP,EAAUzE,KAAK+E,GAGjB,OAAON,CACT,CAxqCoBQ,CAAe3O,EAAQwK,EAAIrQ,OAAS+B,GAASsO,EAAKtO,EAAQ/B,EAC9E,CA8EA,SAASqS,EAAahC,EAAK/R,EAAOC,GAChC,OAAc,IAAVD,GAAeC,IAAQ8R,EAAIrQ,OACtB+P,EAAOb,cAAcmB,GAErBN,EAAOb,cAAcmB,EAAI9K,MAAMjH,EAAOC,GAEjD,CAEA,SAAS2T,EAAW7B,EAAK/R,EAAOC,GAC9BA,EAAMgD,KAAK2D,IAAImL,EAAIrQ,OAAQzB,GAC3B,MAAMqJ,EAAM,GAEZ,IAAItH,EAAIhC,EACR,KAAOgC,EAAI/B,GAAK,CACd,MAAMkW,EAAYpE,EAAI/P,GACtB,IAAIoU,EAAY,KACZC,EAAoBF,EAAY,IAChC,EACCA,EAAY,IACT,EACCA,EAAY,IACT,EACA,EAEZ,GAAInU,EAAIqU,GAAoBpW,EAAK,CAC/B,IAAIqW,EAAYC,EAAWC,EAAYC,EAEvC,OAAQJ,GACN,KAAK,EACCF,EAAY,MACdC,EAAYD,GAEd,MACF,KAAK,EACHG,EAAavE,EAAI/P,EAAI,GACO,MAAV,IAAbsU,KACHG,GAA6B,GAAZN,IAAqB,EAAoB,GAAbG,EACzCG,EAAgB,MAClBL,EAAYK,IAGhB,MACF,KAAK,EACHH,EAAavE,EAAI/P,EAAI,GACrBuU,EAAYxE,EAAI/P,EAAI,GACQ,MAAV,IAAbsU,IAAsD,MAAV,IAAZC,KACnCE,GAA6B,GAAZN,IAAoB,IAAoB,GAAbG,IAAsB,EAAmB,GAAZC,EACrEE,EAAgB,OAAUA,EAAgB,OAAUA,EAAgB,SACtEL,EAAYK,IAGhB,MACF,KAAK,EACHH,EAAavE,EAAI/P,EAAI,GACrBuU,EAAYxE,EAAI/P,EAAI,GACpBwU,EAAazE,EAAI/P,EAAI,GACO,MAAV,IAAbsU,IAAsD,MAAV,IAAZC,IAAsD,MAAV,IAAbC,KAClEC,GAA6B,GAAZN,IAAoB,IAAqB,GAAbG,IAAsB,IAAmB,GAAZC,IAAqB,EAAoB,GAAbC,EAClGC,EAAgB,OAAUA,EAAgB,UAC5CL,EAAYK,IAItB,CAEkB,OAAdL,GAGFA,EAAY,MACZC,EAAmB,GACVD,EAAY,QAErBA,GAAa,MACb9M,EAAI2H,KAAKmF,IAAc,GAAK,KAAQ,OACpCA,EAAY,MAAqB,KAAZA,GAGvB9M,EAAI2H,KAAKmF,GACTpU,GAAKqU,CACP,CAEA,OAQF,SAAgCK,GAC9B,MAAMjG,EAAMiG,EAAWhV,OACvB,GAAI+O,GAAOkG,EACT,OAAOtO,OAAOuO,aAAaC,MAAMxO,OAAQqO,GAI3C,IAAIpN,EAAM,GACNtH,EAAI,EACR,KAAOA,EAAIyO,GACTnH,GAAOjB,OAAOuO,aAAaC,MACzBxO,OACAqO,EAAWzP,MAAMjF,EAAGA,GAAK2U,IAG7B,OAAOrN,CACT,CAxBSwN,CAAsBxN,EAC/B,CA39BA1J,EAAOmX,oBAUP,WAEE,IACE,MAAM1G,EAAM,IAAIlQ,WAAW,GACrB6W,EAAQ,CAAEC,IAAK,WAAc,OAAO,EAAG,GAG7C,OAFA5W,OAAOC,eAAe0W,EAAO7W,WAAWJ,WACxCM,OAAOC,eAAe+P,EAAK2G,GACN,KAAd3G,EAAI4G,KACb,CAAE,MAAOrS,GACP,OAAO,CACT,CACF,CArB6BsS,GAExBtX,EAAOmX,qBAA0C,oBAAZI,SACb,mBAAlBA,QAAQC,OACjBD,QAAQC,MACN,iJAkBJ/W,OAAOgX,eAAezX,EAAOG,UAAW,SAAU,CAChDuX,YAAY,EACZrL,IAAK,WACH,GAAKrM,EAAOsB,SAASvB,MACrB,OAAOA,KAAKiD,MACd,IAGFvC,OAAOgX,eAAezX,EAAOG,UAAW,SAAU,CAChDuX,YAAY,EACZrL,IAAK,WACH,GAAKrM,EAAOsB,SAASvB,MACrB,OAAOA,KAAK6S,UACd,IAoCF5S,EAAO2X,SAAW,KA8DlB3X,EAAO2B,KAAO,SAAUiC,EAAOyO,EAAkBvQ,GAC/C,OAAOH,EAAKiC,EAAOyO,EAAkBvQ,EACvC,EAIArB,OAAOC,eAAeV,EAAOG,UAAWI,WAAWJ,WACnDM,OAAOC,eAAeV,EAAQO,YA8B9BP,EAAOC,MAAQ,SAAUiC,EAAM4B,EAAMwO,GACnC,OArBF,SAAgBpQ,EAAM4B,EAAMwO,GAE1B,OADAiB,EAAWrR,GACPA,GAAQ,EACHgQ,EAAahQ,QAETsH,IAAT1F,EAIyB,iBAAbwO,EACVJ,EAAahQ,GAAM4B,KAAKA,EAAMwO,GAC9BJ,EAAahQ,GAAM4B,KAAKA,GAEvBoO,EAAahQ,EACtB,CAOSjC,CAAMiC,EAAM4B,EAAMwO,EAC3B,EAUAtS,EAAOiD,YAAc,SAAUf,GAC7B,OAAOe,EAAYf,EACrB,EAIAlC,EAAO4X,gBAAkB,SAAU1V,GACjC,OAAOe,EAAYf,EACrB,EA6GAlC,EAAOsB,SAAW,SAAmB0R,GACnC,OAAY,MAALA,IAA6B,IAAhBA,EAAE6E,WACpB7E,IAAMhT,EAAOG,SACjB,EAEAH,EAAO8X,QAAU,SAAkBC,EAAG/E,GAGpC,GAFIN,EAAWqF,EAAGxX,cAAawX,EAAI/X,EAAO2B,KAAKoW,EAAGA,EAAElU,OAAQkU,EAAElP,aAC1D6J,EAAWM,EAAGzS,cAAayS,EAAIhT,EAAO2B,KAAKqR,EAAGA,EAAEnP,OAAQmP,EAAEnK,cACzD7I,EAAOsB,SAASyW,KAAO/X,EAAOsB,SAAS0R,GAC1C,MAAM,IAAInS,UACR,yEAIJ,GAAIkX,IAAM/E,EAAG,OAAO,EAEpB,IAAIgF,EAAID,EAAEjW,OACNmW,EAAIjF,EAAElR,OAEV,IAAK,IAAIM,EAAI,EAAGyO,EAAMxN,KAAK2D,IAAIgR,EAAGC,GAAI7V,EAAIyO,IAAOzO,EAC/C,GAAI2V,EAAE3V,KAAO4Q,EAAE5Q,GAAI,CACjB4V,EAAID,EAAE3V,GACN6V,EAAIjF,EAAE5Q,GACN,KACF,CAGF,OAAI4V,EAAIC,GAAW,EACfA,EAAID,EAAU,EACX,CACT,EAEAhY,EAAOuS,WAAa,SAAqBD,GACvC,OAAQ7J,OAAO6J,GAAUuB,eACvB,IAAK,MACL,IAAK,OACL,IAAK,QACL,IAAK,QACL,IAAK,SACL,IAAK,SACL,IAAK,SACL,IAAK,OACL,IAAK,QACL,IAAK,UACL,IAAK,WACH,OAAO,EACT,QACE,OAAO,EAEb,EAEA7T,EAAOkY,OAAS,SAAiBC,EAAMrW,GACrC,IAAKP,MAAMC,QAAQ2W,GACjB,MAAM,IAAItX,UAAU,+CAGtB,GAAoB,IAAhBsX,EAAKrW,OACP,OAAO9B,EAAOC,MAAM,GAGtB,IAAImC,EACJ,QAAeoH,IAAX1H,EAEF,IADAA,EAAS,EACJM,EAAI,EAAGA,EAAI+V,EAAKrW,SAAUM,EAC7BN,GAAUqW,EAAK/V,GAAGN,OAItB,MAAMkB,EAAShD,EAAOiD,YAAYnB,GAClC,IAAIsW,EAAM,EACV,IAAKhW,EAAI,EAAGA,EAAI+V,EAAKrW,SAAUM,EAAG,CAChC,IAAI+P,EAAMgG,EAAK/V,GACf,GAAIsQ,EAAWP,EAAK5R,YACd6X,EAAMjG,EAAIrQ,OAASkB,EAAOlB,QACvB9B,EAAOsB,SAAS6Q,KAAMA,EAAMnS,EAAO2B,KAAKwQ,IAC7CA,EAAI3O,KAAKR,EAAQoV,IAEjB7X,WAAWJ,UAAU0L,IAAIrL,KACvBwC,EACAmP,EACAiG,OAGC,KAAKpY,EAAOsB,SAAS6Q,GAC1B,MAAM,IAAItR,UAAU,+CAEpBsR,EAAI3O,KAAKR,EAAQoV,EACnB,CACAA,GAAOjG,EAAIrQ,MACb,CACA,OAAOkB,CACT,EAiDAhD,EAAO6I,WAAaA,EA8EpB7I,EAAOG,UAAU0X,WAAY,EAQ7B7X,EAAOG,UAAUkY,OAAS,WACxB,MAAMxH,EAAM9Q,KAAK+B,OACjB,GAAI+O,EAAM,GAAM,EACd,MAAM,IAAIhK,WAAW,6CAEvB,IAAK,IAAIzE,EAAI,EAAGA,EAAIyO,EAAKzO,GAAK,EAC5BiS,EAAKtU,KAAMqC,EAAGA,EAAI,GAEpB,OAAOrC,IACT,EAEAC,EAAOG,UAAUmY,OAAS,WACxB,MAAMzH,EAAM9Q,KAAK+B,OACjB,GAAI+O,EAAM,GAAM,EACd,MAAM,IAAIhK,WAAW,6CAEvB,IAAK,IAAIzE,EAAI,EAAGA,EAAIyO,EAAKzO,GAAK,EAC5BiS,EAAKtU,KAAMqC,EAAGA,EAAI,GAClBiS,EAAKtU,KAAMqC,EAAI,EAAGA,EAAI,GAExB,OAAOrC,IACT,EAEAC,EAAOG,UAAUoY,OAAS,WACxB,MAAM1H,EAAM9Q,KAAK+B,OACjB,GAAI+O,EAAM,GAAM,EACd,MAAM,IAAIhK,WAAW,6CAEvB,IAAK,IAAIzE,EAAI,EAAGA,EAAIyO,EAAKzO,GAAK,EAC5BiS,EAAKtU,KAAMqC,EAAGA,EAAI,GAClBiS,EAAKtU,KAAMqC,EAAI,EAAGA,EAAI,GACtBiS,EAAKtU,KAAMqC,EAAI,EAAGA,EAAI,GACtBiS,EAAKtU,KAAMqC,EAAI,EAAGA,EAAI,GAExB,OAAOrC,IACT,EAEAC,EAAOG,UAAUkF,SAAW,WAC1B,MAAMvD,EAAS/B,KAAK+B,OACpB,OAAe,IAAXA,EAAqB,GACA,IAArB2R,UAAU3R,OAAqBkS,EAAUjU,KAAM,EAAG+B,GAC/CgS,EAAamD,MAAMlX,KAAM0T,UAClC,EAEAzT,EAAOG,UAAUqY,eAAiBxY,EAAOG,UAAUkF,SAEnDrF,EAAOG,UAAUsY,OAAS,SAAiBzF,GACzC,IAAKhT,EAAOsB,SAAS0R,GAAI,MAAM,IAAInS,UAAU,6BAC7C,OAAId,OAASiT,GACsB,IAA5BhT,EAAO8X,QAAQ/X,KAAMiT,EAC9B,EAEAhT,EAAOG,UAAUuY,QAAU,WACzB,IAAI7C,EAAM,GACV,MAAM5O,EAAMtH,EAAQ,GAGpB,OAFAkW,EAAM9V,KAAKsF,SAAS,MAAO,EAAG4B,GAAK0R,QAAQ,UAAW,OAAOC,OACzD7Y,KAAK+B,OAASmF,IAAK4O,GAAO,SACvB,WAAaA,EAAM,GAC5B,EACI9D,IACF/R,EAAOG,UAAU4R,GAAuB/R,EAAOG,UAAUuY,SAG3D1Y,EAAOG,UAAU2X,QAAU,SAAkBe,EAAQzY,EAAOC,EAAKyY,EAAWC,GAI1E,GAHIrG,EAAWmG,EAAQtY,cACrBsY,EAAS7Y,EAAO2B,KAAKkX,EAAQA,EAAOhV,OAAQgV,EAAOhQ,cAEhD7I,EAAOsB,SAASuX,GACnB,MAAM,IAAIhY,UACR,wFAC2BgY,GAiB/B,QAbcrP,IAAVpJ,IACFA,EAAQ,QAEEoJ,IAARnJ,IACFA,EAAMwY,EAASA,EAAO/W,OAAS,QAEf0H,IAAdsP,IACFA,EAAY,QAEEtP,IAAZuP,IACFA,EAAUhZ,KAAK+B,QAGb1B,EAAQ,GAAKC,EAAMwY,EAAO/W,QAAUgX,EAAY,GAAKC,EAAUhZ,KAAK+B,OACtE,MAAM,IAAI+E,WAAW,sBAGvB,GAAIiS,GAAaC,GAAW3Y,GAASC,EACnC,OAAO,EAET,GAAIyY,GAAaC,EACf,OAAQ,EAEV,GAAI3Y,GAASC,EACX,OAAO,EAQT,GAAIN,OAAS8Y,EAAQ,OAAO,EAE5B,IAAIb,GAJJe,KAAa,IADbD,KAAe,GAMXb,GAPJ5X,KAAS,IADTD,KAAW,GASX,MAAMyQ,EAAMxN,KAAK2D,IAAIgR,EAAGC,GAElBe,EAAWjZ,KAAKsH,MAAMyR,EAAWC,GACjCE,EAAaJ,EAAOxR,MAAMjH,EAAOC,GAEvC,IAAK,IAAI+B,EAAI,EAAGA,EAAIyO,IAAOzO,EACzB,GAAI4W,EAAS5W,KAAO6W,EAAW7W,GAAI,CACjC4V,EAAIgB,EAAS5W,GACb6V,EAAIgB,EAAW7W,GACf,KACF,CAGF,OAAI4V,EAAIC,GAAW,EACfA,EAAID,EAAU,EACX,CACT,EA2HAhY,EAAOG,UAAU+Y,SAAW,SAAmBzE,EAAK7B,EAAYN,GAC9D,OAAoD,IAA7CvS,KAAK2R,QAAQ+C,EAAK7B,EAAYN,EACvC,EAEAtS,EAAOG,UAAUuR,QAAU,SAAkB+C,EAAK7B,EAAYN,GAC5D,OAAOkC,EAAqBzU,KAAM0U,EAAK7B,EAAYN,GAAU,EAC/D,EAEAtS,EAAOG,UAAUyU,YAAc,SAAsBH,EAAK7B,EAAYN,GACpE,OAAOkC,EAAqBzU,KAAM0U,EAAK7B,EAAYN,GAAU,EAC/D,EA4CAtS,EAAOG,UAAUwD,MAAQ,SAAgBgE,EAAQ9D,EAAQ/B,EAAQwQ,GAE/D,QAAe9I,IAAX3F,EACFyO,EAAW,OACXxQ,EAAS/B,KAAK+B,OACd+B,EAAS,OAEJ,QAAe2F,IAAX1H,GAA0C,iBAAX+B,EACxCyO,EAAWzO,EACX/B,EAAS/B,KAAK+B,OACd+B,EAAS,MAEJ,KAAIsV,SAAStV,GAUlB,MAAM,IAAI4N,MACR,2EAVF5N,KAAoB,EAChBsV,SAASrX,IACXA,KAAoB,OACH0H,IAAb8I,IAAwBA,EAAW,UAEvCA,EAAWxQ,EACXA,OAAS0H,EAMb,CAEA,MAAM6L,EAAYtV,KAAK+B,OAAS+B,EAGhC,SAFe2F,IAAX1H,GAAwBA,EAASuT,KAAWvT,EAASuT,GAEpD1N,EAAO7F,OAAS,IAAMA,EAAS,GAAK+B,EAAS,IAAOA,EAAS9D,KAAK+B,OACrE,MAAM,IAAI+E,WAAW,0CAGlByL,IAAUA,EAAW,QAE1B,IAAIoB,GAAc,EAClB,OACE,OAAQpB,GACN,IAAK,MACH,OAAO8C,EAASrV,KAAM4H,EAAQ9D,EAAQ/B,GAExC,IAAK,OACL,IAAK,QACH,OAAO4T,EAAU3V,KAAM4H,EAAQ9D,EAAQ/B,GAEzC,IAAK,QACL,IAAK,SACL,IAAK,SACH,OAAO8T,EAAW7V,KAAM4H,EAAQ9D,EAAQ/B,GAE1C,IAAK,SAEH,OAAOkU,EAAYjW,KAAM4H,EAAQ9D,EAAQ/B,GAE3C,IAAK,OACL,IAAK,QACL,IAAK,UACL,IAAK,WACH,OAAOmU,EAAUlW,KAAM4H,EAAQ9D,EAAQ/B,GAEzC,QACE,GAAI4R,EAAa,MAAM,IAAI7S,UAAU,qBAAuByR,GAC5DA,GAAY,GAAKA,GAAUuB,cAC3BH,GAAc,EAGtB,EAEA1T,EAAOG,UAAUmH,OAAS,WACxB,MAAO,CACL2D,KAAM,SACNmI,KAAM7R,MAAMpB,UAAUkH,MAAM7G,KAAKT,KAAKqZ,MAAQrZ,KAAM,GAExD,EAyFA,MAAMgX,EAAuB,KAoB7B,SAAS9C,EAAY9B,EAAK/R,EAAOC,GAC/B,IAAIgZ,EAAM,GACVhZ,EAAMgD,KAAK2D,IAAImL,EAAIrQ,OAAQzB,GAE3B,IAAK,IAAI+B,EAAIhC,EAAOgC,EAAI/B,IAAO+B,EAC7BiX,GAAO5Q,OAAOuO,aAAsB,IAAT7E,EAAI/P,IAEjC,OAAOiX,CACT,CAEA,SAASnF,EAAa/B,EAAK/R,EAAOC,GAChC,IAAIgZ,EAAM,GACVhZ,EAAMgD,KAAK2D,IAAImL,EAAIrQ,OAAQzB,GAE3B,IAAK,IAAI+B,EAAIhC,EAAOgC,EAAI/B,IAAO+B,EAC7BiX,GAAO5Q,OAAOuO,aAAa7E,EAAI/P,IAEjC,OAAOiX,CACT,CAEA,SAAStF,EAAU5B,EAAK/R,EAAOC,GAC7B,MAAMwQ,EAAMsB,EAAIrQ,SAEX1B,GAASA,EAAQ,KAAGA,EAAQ,KAC5BC,GAAOA,EAAM,GAAKA,EAAMwQ,KAAKxQ,EAAMwQ,GAExC,IAAIyI,EAAM,GACV,IAAK,IAAIlX,EAAIhC,EAAOgC,EAAI/B,IAAO+B,EAC7BkX,GAAOC,EAAoBpH,EAAI/P,IAEjC,OAAOkX,CACT,CAEA,SAASlF,EAAcjC,EAAK/R,EAAOC,GACjC,MAAMmZ,EAAQrH,EAAI9K,MAAMjH,EAAOC,GAC/B,IAAIqJ,EAAM,GAEV,IAAK,IAAItH,EAAI,EAAGA,EAAIoX,EAAM1X,OAAS,EAAGM,GAAK,EACzCsH,GAAOjB,OAAOuO,aAAawC,EAAMpX,GAAqB,IAAfoX,EAAMpX,EAAI,IAEnD,OAAOsH,CACT,CAiCA,SAAS+P,EAAa5V,EAAQ6V,EAAK5X,GACjC,GAAK+B,EAAS,GAAO,GAAKA,EAAS,EAAG,MAAM,IAAIgD,WAAW,sBAC3D,GAAIhD,EAAS6V,EAAM5X,EAAQ,MAAM,IAAI+E,WAAW,wCAClD,CAyQA,SAAS8S,EAAUxH,EAAKvO,EAAOC,EAAQ6V,EAAKzS,EAAKD,GAC/C,IAAKhH,EAAOsB,SAAS6Q,GAAM,MAAM,IAAItR,UAAU,+CAC/C,GAAI+C,EAAQqD,GAAOrD,EAAQoD,EAAK,MAAM,IAAIH,WAAW,qCACrD,GAAIhD,EAAS6V,EAAMvH,EAAIrQ,OAAQ,MAAM,IAAI+E,WAAW,qBACtD,CA+FA,SAAS+S,EAAgBzH,EAAKvO,EAAOC,EAAQmD,EAAKC,GAChD4S,EAAWjW,EAAOoD,EAAKC,EAAKkL,EAAKtO,EAAQ,GAEzC,IAAIwS,EAAKtO,OAAOnE,EAAQwC,OAAO,aAC/B+L,EAAItO,KAAYwS,EAChBA,IAAW,EACXlE,EAAItO,KAAYwS,EAChBA,IAAW,EACXlE,EAAItO,KAAYwS,EAChBA,IAAW,EACXlE,EAAItO,KAAYwS,EAChB,IAAID,EAAKrO,OAAOnE,GAASwC,OAAO,IAAMA,OAAO,aAQ7C,OAPA+L,EAAItO,KAAYuS,EAChBA,IAAW,EACXjE,EAAItO,KAAYuS,EAChBA,IAAW,EACXjE,EAAItO,KAAYuS,EAChBA,IAAW,EACXjE,EAAItO,KAAYuS,EACTvS,CACT,CAEA,SAASiW,EAAgB3H,EAAKvO,EAAOC,EAAQmD,EAAKC,GAChD4S,EAAWjW,EAAOoD,EAAKC,EAAKkL,EAAKtO,EAAQ,GAEzC,IAAIwS,EAAKtO,OAAOnE,EAAQwC,OAAO,aAC/B+L,EAAItO,EAAS,GAAKwS,EAClBA,IAAW,EACXlE,EAAItO,EAAS,GAAKwS,EAClBA,IAAW,EACXlE,EAAItO,EAAS,GAAKwS,EAClBA,IAAW,EACXlE,EAAItO,EAAS,GAAKwS,EAClB,IAAID,EAAKrO,OAAOnE,GAASwC,OAAO,IAAMA,OAAO,aAQ7C,OAPA+L,EAAItO,EAAS,GAAKuS,EAClBA,IAAW,EACXjE,EAAItO,EAAS,GAAKuS,EAClBA,IAAW,EACXjE,EAAItO,EAAS,GAAKuS,EAClBA,IAAW,EACXjE,EAAItO,GAAUuS,EACPvS,EAAS,CAClB,CAkHA,SAASkW,EAAc5H,EAAKvO,EAAOC,EAAQ6V,EAAKzS,EAAKD,GACnD,GAAInD,EAAS6V,EAAMvH,EAAIrQ,OAAQ,MAAM,IAAI+E,WAAW,sBACpD,GAAIhD,EAAS,EAAG,MAAM,IAAIgD,WAAW,qBACvC,CAEA,SAASmT,EAAY7H,EAAKvO,EAAOC,EAAQoW,EAAcC,GAOrD,OANAtW,GAASA,EACTC,KAAoB,EACfqW,GACHH,EAAa5H,EAAKvO,EAAOC,EAAQ,GAEnCiO,EAAQnO,MAAMwO,EAAKvO,EAAOC,EAAQoW,EAAc,GAAI,GAC7CpW,EAAS,CAClB,CAUA,SAASsW,EAAahI,EAAKvO,EAAOC,EAAQoW,EAAcC,GAOtD,OANAtW,GAASA,EACTC,KAAoB,EACfqW,GACHH,EAAa5H,EAAKvO,EAAOC,EAAQ,GAEnCiO,EAAQnO,MAAMwO,EAAKvO,EAAOC,EAAQoW,EAAc,GAAI,GAC7CpW,EAAS,CAClB,CAzkBA7D,EAAOG,UAAUkH,MAAQ,SAAgBjH,EAAOC,GAC9C,MAAMwQ,EAAM9Q,KAAK+B,QACjB1B,IAAUA,GAGE,GACVA,GAASyQ,GACG,IAAGzQ,EAAQ,GACdA,EAAQyQ,IACjBzQ,EAAQyQ,IANVxQ,OAAcmJ,IAARnJ,EAAoBwQ,IAAQxQ,GASxB,GACRA,GAAOwQ,GACG,IAAGxQ,EAAM,GACVA,EAAMwQ,IACfxQ,EAAMwQ,GAGJxQ,EAAMD,IAAOC,EAAMD,GAEvB,MAAMga,EAASra,KAAKG,SAASE,EAAOC,GAIpC,OAFAI,OAAOC,eAAe0Z,EAAQpa,EAAOG,WAE9Bia,CACT,EAUApa,EAAOG,UAAUka,WACjBra,EAAOG,UAAUma,WAAa,SAAqBzW,EAAQgF,EAAYqR,GACrErW,KAAoB,EACpBgF,KAA4B,EACvBqR,GAAUT,EAAY5V,EAAQgF,EAAY9I,KAAK+B,QAEpD,IAAI2S,EAAM1U,KAAK8D,GACX0W,EAAM,EACNnY,EAAI,EACR,OAASA,EAAIyG,IAAe0R,GAAO,MACjC9F,GAAO1U,KAAK8D,EAASzB,GAAKmY,EAG5B,OAAO9F,CACT,EAEAzU,EAAOG,UAAUqa,WACjBxa,EAAOG,UAAUsa,WAAa,SAAqB5W,EAAQgF,EAAYqR,GACrErW,KAAoB,EACpBgF,KAA4B,EACvBqR,GACHT,EAAY5V,EAAQgF,EAAY9I,KAAK+B,QAGvC,IAAI2S,EAAM1U,KAAK8D,IAAWgF,GACtB0R,EAAM,EACV,KAAO1R,EAAa,IAAM0R,GAAO,MAC/B9F,GAAO1U,KAAK8D,IAAWgF,GAAc0R,EAGvC,OAAO9F,CACT,EAEAzU,EAAOG,UAAUua,UACjB1a,EAAOG,UAAUwa,UAAY,SAAoB9W,EAAQqW,GAGvD,OAFArW,KAAoB,EACfqW,GAAUT,EAAY5V,EAAQ,EAAG9D,KAAK+B,QACpC/B,KAAK8D,EACd,EAEA7D,EAAOG,UAAUya,aACjB5a,EAAOG,UAAU0a,aAAe,SAAuBhX,EAAQqW,GAG7D,OAFArW,KAAoB,EACfqW,GAAUT,EAAY5V,EAAQ,EAAG9D,KAAK+B,QACpC/B,KAAK8D,GAAW9D,KAAK8D,EAAS,IAAM,CAC7C,EAEA7D,EAAOG,UAAU2a,aACjB9a,EAAOG,UAAU6U,aAAe,SAAuBnR,EAAQqW,GAG7D,OAFArW,KAAoB,EACfqW,GAAUT,EAAY5V,EAAQ,EAAG9D,KAAK+B,QACnC/B,KAAK8D,IAAW,EAAK9D,KAAK8D,EAAS,EAC7C,EAEA7D,EAAOG,UAAU4a,aACjB/a,EAAOG,UAAU6a,aAAe,SAAuBnX,EAAQqW,GAI7D,OAHArW,KAAoB,EACfqW,GAAUT,EAAY5V,EAAQ,EAAG9D,KAAK+B,SAElC/B,KAAK8D,GACT9D,KAAK8D,EAAS,IAAM,EACpB9D,KAAK8D,EAAS,IAAM,IACD,SAAnB9D,KAAK8D,EAAS,EACrB,EAEA7D,EAAOG,UAAU8a,aACjBjb,EAAOG,UAAUqC,aAAe,SAAuBqB,EAAQqW,GAI7D,OAHArW,KAAoB,EACfqW,GAAUT,EAAY5V,EAAQ,EAAG9D,KAAK+B,QAEpB,SAAf/B,KAAK8D,IACT9D,KAAK8D,EAAS,IAAM,GACrB9D,KAAK8D,EAAS,IAAM,EACrB9D,KAAK8D,EAAS,GAClB,EAEA7D,EAAOG,UAAU+a,gBAAkBC,GAAmB,SAA0BtX,GAE9EuX,EADAvX,KAAoB,EACG,UACvB,MAAMwX,EAAQtb,KAAK8D,GACbyX,EAAOvb,KAAK8D,EAAS,QACb2F,IAAV6R,QAAgC7R,IAAT8R,GACzBC,EAAY1X,EAAQ9D,KAAK+B,OAAS,GAGpC,MAAMuU,EAAKgF,EACQ,IAAjBtb,OAAO8D,GACU,MAAjB9D,OAAO8D,GACP9D,OAAO8D,GAAU,GAAK,GAElBuS,EAAKrW,OAAO8D,GACC,IAAjB9D,OAAO8D,GACU,MAAjB9D,OAAO8D,GACPyX,EAAO,GAAK,GAEd,OAAOlV,OAAOiQ,IAAOjQ,OAAOgQ,IAAOhQ,OAAO,IAC5C,IAEApG,EAAOG,UAAUuC,gBAAkByY,GAAmB,SAA0BtX,GAE9EuX,EADAvX,KAAoB,EACG,UACvB,MAAMwX,EAAQtb,KAAK8D,GACbyX,EAAOvb,KAAK8D,EAAS,QACb2F,IAAV6R,QAAgC7R,IAAT8R,GACzBC,EAAY1X,EAAQ9D,KAAK+B,OAAS,GAGpC,MAAMsU,EAAKiF,EAAQ,GAAK,GACL,MAAjBtb,OAAO8D,GACU,IAAjB9D,OAAO8D,GACP9D,OAAO8D,GAEHwS,EAAKtW,OAAO8D,GAAU,GAAK,GACd,MAAjB9D,OAAO8D,GACU,IAAjB9D,OAAO8D,GACPyX,EAEF,OAAQlV,OAAOgQ,IAAOhQ,OAAO,KAAOA,OAAOiQ,EAC7C,IAEArW,EAAOG,UAAUqb,UAAY,SAAoB3X,EAAQgF,EAAYqR,GACnErW,KAAoB,EACpBgF,KAA4B,EACvBqR,GAAUT,EAAY5V,EAAQgF,EAAY9I,KAAK+B,QAEpD,IAAI2S,EAAM1U,KAAK8D,GACX0W,EAAM,EACNnY,EAAI,EACR,OAASA,EAAIyG,IAAe0R,GAAO,MACjC9F,GAAO1U,KAAK8D,EAASzB,GAAKmY,EAM5B,OAJAA,GAAO,IAEH9F,GAAO8F,IAAK9F,GAAOpR,KAAKoY,IAAI,EAAG,EAAI5S,IAEhC4L,CACT,EAEAzU,EAAOG,UAAUub,UAAY,SAAoB7X,EAAQgF,EAAYqR,GACnErW,KAAoB,EACpBgF,KAA4B,EACvBqR,GAAUT,EAAY5V,EAAQgF,EAAY9I,KAAK+B,QAEpD,IAAIM,EAAIyG,EACJ0R,EAAM,EACN9F,EAAM1U,KAAK8D,IAAWzB,GAC1B,KAAOA,EAAI,IAAMmY,GAAO,MACtB9F,GAAO1U,KAAK8D,IAAWzB,GAAKmY,EAM9B,OAJAA,GAAO,IAEH9F,GAAO8F,IAAK9F,GAAOpR,KAAKoY,IAAI,EAAG,EAAI5S,IAEhC4L,CACT,EAEAzU,EAAOG,UAAUwb,SAAW,SAAmB9X,EAAQqW,GAGrD,OAFArW,KAAoB,EACfqW,GAAUT,EAAY5V,EAAQ,EAAG9D,KAAK+B,QACtB,IAAf/B,KAAK8D,IAC0B,GAA5B,IAAO9D,KAAK8D,GAAU,GADK9D,KAAK8D,EAE3C,EAEA7D,EAAOG,UAAUyb,YAAc,SAAsB/X,EAAQqW,GAC3DrW,KAAoB,EACfqW,GAAUT,EAAY5V,EAAQ,EAAG9D,KAAK+B,QAC3C,MAAM2S,EAAM1U,KAAK8D,GAAW9D,KAAK8D,EAAS,IAAM,EAChD,OAAc,MAAN4Q,EAAsB,WAANA,EAAmBA,CAC7C,EAEAzU,EAAOG,UAAU0b,YAAc,SAAsBhY,EAAQqW,GAC3DrW,KAAoB,EACfqW,GAAUT,EAAY5V,EAAQ,EAAG9D,KAAK+B,QAC3C,MAAM2S,EAAM1U,KAAK8D,EAAS,GAAM9D,KAAK8D,IAAW,EAChD,OAAc,MAAN4Q,EAAsB,WAANA,EAAmBA,CAC7C,EAEAzU,EAAOG,UAAU2b,YAAc,SAAsBjY,EAAQqW,GAI3D,OAHArW,KAAoB,EACfqW,GAAUT,EAAY5V,EAAQ,EAAG9D,KAAK+B,QAEnC/B,KAAK8D,GACV9D,KAAK8D,EAAS,IAAM,EACpB9D,KAAK8D,EAAS,IAAM,GACpB9D,KAAK8D,EAAS,IAAM,EACzB,EAEA7D,EAAOG,UAAUoC,YAAc,SAAsBsB,EAAQqW,GAI3D,OAHArW,KAAoB,EACfqW,GAAUT,EAAY5V,EAAQ,EAAG9D,KAAK+B,QAEnC/B,KAAK8D,IAAW,GACrB9D,KAAK8D,EAAS,IAAM,GACpB9D,KAAK8D,EAAS,IAAM,EACpB9D,KAAK8D,EAAS,EACnB,EAEA7D,EAAOG,UAAU4b,eAAiBZ,GAAmB,SAAyBtX,GAE5EuX,EADAvX,KAAoB,EACG,UACvB,MAAMwX,EAAQtb,KAAK8D,GACbyX,EAAOvb,KAAK8D,EAAS,QACb2F,IAAV6R,QAAgC7R,IAAT8R,GACzBC,EAAY1X,EAAQ9D,KAAK+B,OAAS,GAGpC,MAAM2S,EAAM1U,KAAK8D,EAAS,GACL,IAAnB9D,KAAK8D,EAAS,GACK,MAAnB9D,KAAK8D,EAAS,IACbyX,GAAQ,IAEX,OAAQlV,OAAOqO,IAAQrO,OAAO,KAC5BA,OAAOiV,EACU,IAAjBtb,OAAO8D,GACU,MAAjB9D,OAAO8D,GACP9D,OAAO8D,GAAU,GAAK,GAC1B,IAEA7D,EAAOG,UAAUsC,eAAiB0Y,GAAmB,SAAyBtX,GAE5EuX,EADAvX,KAAoB,EACG,UACvB,MAAMwX,EAAQtb,KAAK8D,GACbyX,EAAOvb,KAAK8D,EAAS,QACb2F,IAAV6R,QAAgC7R,IAAT8R,GACzBC,EAAY1X,EAAQ9D,KAAK+B,OAAS,GAGpC,MAAM2S,GAAO4G,GAAS,IACH,MAAjBtb,OAAO8D,GACU,IAAjB9D,OAAO8D,GACP9D,OAAO8D,GAET,OAAQuC,OAAOqO,IAAQrO,OAAO,KAC5BA,OAAOrG,OAAO8D,GAAU,GAAK,GACZ,MAAjB9D,OAAO8D,GACU,IAAjB9D,OAAO8D,GACPyX,EACJ,IAEAtb,EAAOG,UAAU6b,YAAc,SAAsBnY,EAAQqW,GAG3D,OAFArW,KAAoB,EACfqW,GAAUT,EAAY5V,EAAQ,EAAG9D,KAAK+B,QACpCgQ,EAAQxP,KAAKvC,KAAM8D,GAAQ,EAAM,GAAI,EAC9C,EAEA7D,EAAOG,UAAUwC,YAAc,SAAsBkB,EAAQqW,GAG3D,OAFArW,KAAoB,EACfqW,GAAUT,EAAY5V,EAAQ,EAAG9D,KAAK+B,QACpCgQ,EAAQxP,KAAKvC,KAAM8D,GAAQ,EAAO,GAAI,EAC/C,EAEA7D,EAAOG,UAAU8b,aAAe,SAAuBpY,EAAQqW,GAG7D,OAFArW,KAAoB,EACfqW,GAAUT,EAAY5V,EAAQ,EAAG9D,KAAK+B,QACpCgQ,EAAQxP,KAAKvC,KAAM8D,GAAQ,EAAM,GAAI,EAC9C,EAEA7D,EAAOG,UAAUyC,aAAe,SAAuBiB,EAAQqW,GAG7D,OAFArW,KAAoB,EACfqW,GAAUT,EAAY5V,EAAQ,EAAG9D,KAAK+B,QACpCgQ,EAAQxP,KAAKvC,KAAM8D,GAAQ,EAAO,GAAI,EAC/C,EAQA7D,EAAOG,UAAU+b,YACjBlc,EAAOG,UAAUgc,YAAc,SAAsBvY,EAAOC,EAAQgF,EAAYqR,GAI9E,GAHAtW,GAASA,EACTC,KAAoB,EACpBgF,KAA4B,GACvBqR,EAAU,CAEbP,EAAS5Z,KAAM6D,EAAOC,EAAQgF,EADbxF,KAAKoY,IAAI,EAAG,EAAI5S,GAAc,EACK,EACtD,CAEA,IAAI0R,EAAM,EACNnY,EAAI,EAER,IADArC,KAAK8D,GAAkB,IAARD,IACNxB,EAAIyG,IAAe0R,GAAO,MACjCxa,KAAK8D,EAASzB,GAAMwB,EAAQ2W,EAAO,IAGrC,OAAO1W,EAASgF,CAClB,EAEA7I,EAAOG,UAAUic,YACjBpc,EAAOG,UAAUkc,YAAc,SAAsBzY,EAAOC,EAAQgF,EAAYqR,GAI9E,GAHAtW,GAASA,EACTC,KAAoB,EACpBgF,KAA4B,GACvBqR,EAAU,CAEbP,EAAS5Z,KAAM6D,EAAOC,EAAQgF,EADbxF,KAAKoY,IAAI,EAAG,EAAI5S,GAAc,EACK,EACtD,CAEA,IAAIzG,EAAIyG,EAAa,EACjB0R,EAAM,EAEV,IADAxa,KAAK8D,EAASzB,GAAa,IAARwB,IACVxB,GAAK,IAAMmY,GAAO,MACzBxa,KAAK8D,EAASzB,GAAMwB,EAAQ2W,EAAO,IAGrC,OAAO1W,EAASgF,CAClB,EAEA7I,EAAOG,UAAUmc,WACjBtc,EAAOG,UAAUoc,WAAa,SAAqB3Y,EAAOC,EAAQqW,GAKhE,OAJAtW,GAASA,EACTC,KAAoB,EACfqW,GAAUP,EAAS5Z,KAAM6D,EAAOC,EAAQ,EAAG,IAAM,GACtD9D,KAAK8D,GAAmB,IAARD,EACTC,EAAS,CAClB,EAEA7D,EAAOG,UAAUqc,cACjBxc,EAAOG,UAAUsc,cAAgB,SAAwB7Y,EAAOC,EAAQqW,GAMtE,OALAtW,GAASA,EACTC,KAAoB,EACfqW,GAAUP,EAAS5Z,KAAM6D,EAAOC,EAAQ,EAAG,MAAQ,GACxD9D,KAAK8D,GAAmB,IAARD,EAChB7D,KAAK8D,EAAS,GAAMD,IAAU,EACvBC,EAAS,CAClB,EAEA7D,EAAOG,UAAUuc,cACjB1c,EAAOG,UAAUwc,cAAgB,SAAwB/Y,EAAOC,EAAQqW,GAMtE,OALAtW,GAASA,EACTC,KAAoB,EACfqW,GAAUP,EAAS5Z,KAAM6D,EAAOC,EAAQ,EAAG,MAAQ,GACxD9D,KAAK8D,GAAWD,IAAU,EAC1B7D,KAAK8D,EAAS,GAAc,IAARD,EACbC,EAAS,CAClB,EAEA7D,EAAOG,UAAUyc,cACjB5c,EAAOG,UAAU0c,cAAgB,SAAwBjZ,EAAOC,EAAQqW,GAQtE,OAPAtW,GAASA,EACTC,KAAoB,EACfqW,GAAUP,EAAS5Z,KAAM6D,EAAOC,EAAQ,EAAG,WAAY,GAC5D9D,KAAK8D,EAAS,GAAMD,IAAU,GAC9B7D,KAAK8D,EAAS,GAAMD,IAAU,GAC9B7D,KAAK8D,EAAS,GAAMD,IAAU,EAC9B7D,KAAK8D,GAAmB,IAARD,EACTC,EAAS,CAClB,EAEA7D,EAAOG,UAAU2c,cACjB9c,EAAOG,UAAU6D,cAAgB,SAAwBJ,EAAOC,EAAQqW,GAQtE,OAPAtW,GAASA,EACTC,KAAoB,EACfqW,GAAUP,EAAS5Z,KAAM6D,EAAOC,EAAQ,EAAG,WAAY,GAC5D9D,KAAK8D,GAAWD,IAAU,GAC1B7D,KAAK8D,EAAS,GAAMD,IAAU,GAC9B7D,KAAK8D,EAAS,GAAMD,IAAU,EAC9B7D,KAAK8D,EAAS,GAAc,IAARD,EACbC,EAAS,CAClB,EA8CA7D,EAAOG,UAAU4c,iBAAmB5B,GAAmB,SAA2BvX,EAAOC,EAAS,GAChG,OAAO+V,EAAe7Z,KAAM6D,EAAOC,EAAQuC,OAAO,GAAIA,OAAO,sBAC/D,IAEApG,EAAOG,UAAU+D,iBAAmBiX,GAAmB,SAA2BvX,EAAOC,EAAS,GAChG,OAAOiW,EAAe/Z,KAAM6D,EAAOC,EAAQuC,OAAO,GAAIA,OAAO,sBAC/D,IAEApG,EAAOG,UAAU6c,WAAa,SAAqBpZ,EAAOC,EAAQgF,EAAYqR,GAG5E,GAFAtW,GAASA,EACTC,KAAoB,GACfqW,EAAU,CACb,MAAM+C,EAAQ5Z,KAAKoY,IAAI,EAAI,EAAI5S,EAAc,GAE7C8Q,EAAS5Z,KAAM6D,EAAOC,EAAQgF,EAAYoU,EAAQ,GAAIA,EACxD,CAEA,IAAI7a,EAAI,EACJmY,EAAM,EACN2C,EAAM,EAEV,IADAnd,KAAK8D,GAAkB,IAARD,IACNxB,EAAIyG,IAAe0R,GAAO,MAC7B3W,EAAQ,GAAa,IAARsZ,GAAsC,IAAzBnd,KAAK8D,EAASzB,EAAI,KAC9C8a,EAAM,GAERnd,KAAK8D,EAASzB,IAAOwB,EAAQ2W,EAAQ,GAAK2C,EAAM,IAGlD,OAAOrZ,EAASgF,CAClB,EAEA7I,EAAOG,UAAUgd,WAAa,SAAqBvZ,EAAOC,EAAQgF,EAAYqR,GAG5E,GAFAtW,GAASA,EACTC,KAAoB,GACfqW,EAAU,CACb,MAAM+C,EAAQ5Z,KAAKoY,IAAI,EAAI,EAAI5S,EAAc,GAE7C8Q,EAAS5Z,KAAM6D,EAAOC,EAAQgF,EAAYoU,EAAQ,GAAIA,EACxD,CAEA,IAAI7a,EAAIyG,EAAa,EACjB0R,EAAM,EACN2C,EAAM,EAEV,IADAnd,KAAK8D,EAASzB,GAAa,IAARwB,IACVxB,GAAK,IAAMmY,GAAO,MACrB3W,EAAQ,GAAa,IAARsZ,GAAsC,IAAzBnd,KAAK8D,EAASzB,EAAI,KAC9C8a,EAAM,GAERnd,KAAK8D,EAASzB,IAAOwB,EAAQ2W,EAAQ,GAAK2C,EAAM,IAGlD,OAAOrZ,EAASgF,CAClB,EAEA7I,EAAOG,UAAUid,UAAY,SAAoBxZ,EAAOC,EAAQqW,GAM9D,OALAtW,GAASA,EACTC,KAAoB,EACfqW,GAAUP,EAAS5Z,KAAM6D,EAAOC,EAAQ,EAAG,KAAO,KACnDD,EAAQ,IAAGA,EAAQ,IAAOA,EAAQ,GACtC7D,KAAK8D,GAAmB,IAARD,EACTC,EAAS,CAClB,EAEA7D,EAAOG,UAAUkd,aAAe,SAAuBzZ,EAAOC,EAAQqW,GAMpE,OALAtW,GAASA,EACTC,KAAoB,EACfqW,GAAUP,EAAS5Z,KAAM6D,EAAOC,EAAQ,EAAG,OAAS,OACzD9D,KAAK8D,GAAmB,IAARD,EAChB7D,KAAK8D,EAAS,GAAMD,IAAU,EACvBC,EAAS,CAClB,EAEA7D,EAAOG,UAAUmd,aAAe,SAAuB1Z,EAAOC,EAAQqW,GAMpE,OALAtW,GAASA,EACTC,KAAoB,EACfqW,GAAUP,EAAS5Z,KAAM6D,EAAOC,EAAQ,EAAG,OAAS,OACzD9D,KAAK8D,GAAWD,IAAU,EAC1B7D,KAAK8D,EAAS,GAAc,IAARD,EACbC,EAAS,CAClB,EAEA7D,EAAOG,UAAUod,aAAe,SAAuB3Z,EAAOC,EAAQqW,GAQpE,OAPAtW,GAASA,EACTC,KAAoB,EACfqW,GAAUP,EAAS5Z,KAAM6D,EAAOC,EAAQ,EAAG,YAAa,YAC7D9D,KAAK8D,GAAmB,IAARD,EAChB7D,KAAK8D,EAAS,GAAMD,IAAU,EAC9B7D,KAAK8D,EAAS,GAAMD,IAAU,GAC9B7D,KAAK8D,EAAS,GAAMD,IAAU,GACvBC,EAAS,CAClB,EAEA7D,EAAOG,UAAU4D,aAAe,SAAuBH,EAAOC,EAAQqW,GASpE,OARAtW,GAASA,EACTC,KAAoB,EACfqW,GAAUP,EAAS5Z,KAAM6D,EAAOC,EAAQ,EAAG,YAAa,YACzDD,EAAQ,IAAGA,EAAQ,WAAaA,EAAQ,GAC5C7D,KAAK8D,GAAWD,IAAU,GAC1B7D,KAAK8D,EAAS,GAAMD,IAAU,GAC9B7D,KAAK8D,EAAS,GAAMD,IAAU,EAC9B7D,KAAK8D,EAAS,GAAc,IAARD,EACbC,EAAS,CAClB,EAEA7D,EAAOG,UAAUqd,gBAAkBrC,GAAmB,SAA0BvX,EAAOC,EAAS,GAC9F,OAAO+V,EAAe7Z,KAAM6D,EAAOC,GAASuC,OAAO,sBAAuBA,OAAO,sBACnF,IAEApG,EAAOG,UAAU8D,gBAAkBkX,GAAmB,SAA0BvX,EAAOC,EAAS,GAC9F,OAAOiW,EAAe/Z,KAAM6D,EAAOC,GAASuC,OAAO,sBAAuBA,OAAO,sBACnF,IAiBApG,EAAOG,UAAUsd,aAAe,SAAuB7Z,EAAOC,EAAQqW,GACpE,OAAOF,EAAWja,KAAM6D,EAAOC,GAAQ,EAAMqW,EAC/C,EAEAla,EAAOG,UAAUgE,aAAe,SAAuBP,EAAOC,EAAQqW,GACpE,OAAOF,EAAWja,KAAM6D,EAAOC,GAAQ,EAAOqW,EAChD,EAYAla,EAAOG,UAAUud,cAAgB,SAAwB9Z,EAAOC,EAAQqW,GACtE,OAAOC,EAAYpa,KAAM6D,EAAOC,GAAQ,EAAMqW,EAChD,EAEAla,EAAOG,UAAUiE,cAAgB,SAAwBR,EAAOC,EAAQqW,GACtE,OAAOC,EAAYpa,KAAM6D,EAAOC,GAAQ,EAAOqW,EACjD,EAGAla,EAAOG,UAAUqD,KAAO,SAAeqV,EAAQ8E,EAAavd,EAAOC,GACjE,IAAKL,EAAOsB,SAASuX,GAAS,MAAM,IAAIhY,UAAU,+BAQlD,GAPKT,IAAOA,EAAQ,GACfC,GAAe,IAARA,IAAWA,EAAMN,KAAK+B,QAC9B6b,GAAe9E,EAAO/W,SAAQ6b,EAAc9E,EAAO/W,QAClD6b,IAAaA,EAAc,GAC5Btd,EAAM,GAAKA,EAAMD,IAAOC,EAAMD,GAG9BC,IAAQD,EAAO,OAAO,EAC1B,GAAsB,IAAlByY,EAAO/W,QAAgC,IAAhB/B,KAAK+B,OAAc,OAAO,EAGrD,GAAI6b,EAAc,EAChB,MAAM,IAAI9W,WAAW,6BAEvB,GAAIzG,EAAQ,GAAKA,GAASL,KAAK+B,OAAQ,MAAM,IAAI+E,WAAW,sBAC5D,GAAIxG,EAAM,EAAG,MAAM,IAAIwG,WAAW,2BAG9BxG,EAAMN,KAAK+B,SAAQzB,EAAMN,KAAK+B,QAC9B+W,EAAO/W,OAAS6b,EAActd,EAAMD,IACtCC,EAAMwY,EAAO/W,OAAS6b,EAAcvd,GAGtC,MAAMyQ,EAAMxQ,EAAMD,EAalB,OAXIL,OAAS8Y,GAAqD,mBAApCtY,WAAWJ,UAAUyd,WAEjD7d,KAAK6d,WAAWD,EAAavd,EAAOC,GAEpCE,WAAWJ,UAAU0L,IAAIrL,KACvBqY,EACA9Y,KAAKG,SAASE,EAAOC,GACrBsd,GAIG9M,CACT,EAMA7Q,EAAOG,UAAU2D,KAAO,SAAe2Q,EAAKrU,EAAOC,EAAKiS,GAEtD,GAAmB,iBAARmC,EAAkB,CAS3B,GARqB,iBAAVrU,GACTkS,EAAWlS,EACXA,EAAQ,EACRC,EAAMN,KAAK+B,QACa,iBAARzB,IAChBiS,EAAWjS,EACXA,EAAMN,KAAK+B,aAEI0H,IAAb8I,GAA8C,iBAAbA,EACnC,MAAM,IAAIzR,UAAU,6BAEtB,GAAwB,iBAAbyR,IAA0BtS,EAAOuS,WAAWD,GACrD,MAAM,IAAIzR,UAAU,qBAAuByR,GAE7C,GAAmB,IAAfmC,EAAI3S,OAAc,CACpB,MAAM0P,EAAOiD,EAAI1D,WAAW,IACV,SAAbuB,GAAuBd,EAAO,KAClB,WAAbc,KAEFmC,EAAMjD,EAEV,CACF,KAA0B,iBAARiD,EAChBA,GAAY,IACY,kBAARA,IAChBA,EAAM1M,OAAO0M,IAIf,GAAIrU,EAAQ,GAAKL,KAAK+B,OAAS1B,GAASL,KAAK+B,OAASzB,EACpD,MAAM,IAAIwG,WAAW,sBAGvB,GAAIxG,GAAOD,EACT,OAAOL,KAQT,IAAIqC,EACJ,GANAhC,KAAkB,EAClBC,OAAcmJ,IAARnJ,EAAoBN,KAAK+B,OAASzB,IAAQ,EAE3CoU,IAAKA,EAAM,GAGG,iBAARA,EACT,IAAKrS,EAAIhC,EAAOgC,EAAI/B,IAAO+B,EACzBrC,KAAKqC,GAAKqS,MAEP,CACL,MAAM+E,EAAQxZ,EAAOsB,SAASmT,GAC1BA,EACAzU,EAAO2B,KAAK8S,EAAKnC,GACfzB,EAAM2I,EAAM1X,OAClB,GAAY,IAAR+O,EACF,MAAM,IAAIhQ,UAAU,cAAgB4T,EAClC,qCAEJ,IAAKrS,EAAI,EAAGA,EAAI/B,EAAMD,IAASgC,EAC7BrC,KAAKqC,EAAIhC,GAASoZ,EAAMpX,EAAIyO,EAEhC,CAEA,OAAO9Q,IACT,EAMA,MAAM8d,EAAS,CAAC,EAChB,SAASC,EAAGC,EAAKC,EAAYC,GAC3BJ,EAAOE,GAAO,cAAwBE,EACpC,WAAAnd,GACEE,QAEAP,OAAOgX,eAAe1X,KAAM,UAAW,CACrC6D,MAAOoa,EAAW/G,MAAMlX,KAAM0T,WAC9ByK,UAAU,EACVC,cAAc,IAIhBpe,KAAK2F,KAAO,GAAG3F,KAAK2F,SAASqY,KAG7Bhe,KAAKqe,aAEEre,KAAK2F,IACd,CAEA,QAAI8L,GACF,OAAOuM,CACT,CAEA,QAAIvM,CAAM5N,GACRnD,OAAOgX,eAAe1X,KAAM,OAAQ,CAClCoe,cAAc,EACdzG,YAAY,EACZ9T,QACAsa,UAAU,GAEd,CAEA,QAAA7Y,GACE,MAAO,GAAGtF,KAAK2F,SAASqY,OAAShe,KAAKgB,SACxC,EAEJ,CA+BA,SAASsd,EAAuB5J,GAC9B,IAAI/K,EAAM,GACNtH,EAAIqS,EAAI3S,OACZ,MAAM1B,EAAmB,MAAXqU,EAAI,GAAa,EAAI,EACnC,KAAOrS,GAAKhC,EAAQ,EAAGgC,GAAK,EAC1BsH,EAAM,IAAI+K,EAAIpN,MAAMjF,EAAI,EAAGA,KAAKsH,IAElC,MAAO,GAAG+K,EAAIpN,MAAM,EAAGjF,KAAKsH,GAC9B,CAYA,SAASmQ,EAAYjW,EAAOoD,EAAKC,EAAKkL,EAAKtO,EAAQgF,GACjD,GAAIjF,EAAQqD,GAAOrD,EAAQoD,EAAK,CAC9B,MAAMsN,EAAmB,iBAARtN,EAAmB,IAAM,GAC1C,IAAIsX,EAWJ,MARIA,EAFAzV,EAAa,EACH,IAAR7B,GAAaA,IAAQZ,OAAO,GACtB,OAAOkO,YAAYA,QAA2B,GAAlBzL,EAAa,KAASyL,IAElD,SAASA,QAA2B,GAAlBzL,EAAa,GAAS,IAAIyL,iBACtB,GAAlBzL,EAAa,GAAS,IAAIyL,IAGhC,MAAMtN,IAAMsN,YAAYrN,IAAMqN,IAElC,IAAIuJ,EAAOU,iBAAiB,QAASD,EAAO1a,EACpD,EAtBF,SAAsBuO,EAAKtO,EAAQgF,GACjCuS,EAAevX,EAAQ,eACH2F,IAAhB2I,EAAItO,SAAsD2F,IAA7B2I,EAAItO,EAASgF,IAC5C0S,EAAY1X,EAAQsO,EAAIrQ,QAAU+G,EAAa,GAEnD,CAkBE2V,CAAYrM,EAAKtO,EAAQgF,EAC3B,CAEA,SAASuS,EAAgBxX,EAAO8B,GAC9B,GAAqB,iBAAV9B,EACT,MAAM,IAAIia,EAAOY,qBAAqB/Y,EAAM,SAAU9B,EAE1D,CAEA,SAAS2X,EAAa3X,EAAO9B,EAAQmJ,GACnC,GAAI5H,KAAKqb,MAAM9a,KAAWA,EAExB,MADAwX,EAAexX,EAAOqH,GAChB,IAAI4S,EAAOU,iBAAiBtT,GAAQ,SAAU,aAAcrH,GAGpE,GAAI9B,EAAS,EACX,MAAM,IAAI+b,EAAOc,yBAGnB,MAAM,IAAId,EAAOU,iBAAiBtT,GAAQ,SACR,MAAMA,EAAO,EAAI,YAAYnJ,IAC7B8B,EACpC,CAvFAka,EAAE,4BACA,SAAUpY,GACR,OAAIA,EACK,GAAGA,gCAGL,gDACT,GAAGmB,YACLiX,EAAE,wBACA,SAAUpY,EAAM8M,GACd,MAAO,QAAQ9M,4DAA+D8M,GAChF,GAAG3R,WACLid,EAAE,oBACA,SAAUjI,EAAKyI,EAAO1Z,GACpB,IAAIga,EAAM,iBAAiB/I,sBACvBgJ,EAAWja,EAWf,OAVImD,OAAO+W,UAAUla,IAAUvB,KAAK0b,IAAIna,GAAS,GAAK,GACpDia,EAAWR,EAAsB5V,OAAO7D,IACd,iBAAVA,IAChBia,EAAWpW,OAAO7D,IACdA,EAAQwB,OAAO,IAAMA,OAAO,KAAOxB,IAAUwB,OAAO,IAAMA,OAAO,QACnEyY,EAAWR,EAAsBQ,IAEnCA,GAAY,KAEdD,GAAO,eAAeN,eAAmBO,IAClCD,CACT,GAAG/X,YAiEL,MAAMmY,EAAoB,oBAgB1B,SAASrL,EAAahM,EAAQuO,GAE5B,IAAIM,EADJN,EAAQA,GAAS+I,IAEjB,MAAMnd,EAAS6F,EAAO7F,OACtB,IAAIod,EAAgB,KACpB,MAAM1F,EAAQ,GAEd,IAAK,IAAIpX,EAAI,EAAGA,EAAIN,IAAUM,EAAG,CAI/B,GAHAoU,EAAY7O,EAAOoJ,WAAW3O,GAG1BoU,EAAY,OAAUA,EAAY,MAAQ,CAE5C,IAAK0I,EAAe,CAElB,GAAI1I,EAAY,MAAQ,EAEjBN,GAAS,IAAM,GAAGsD,EAAMnI,KAAK,IAAM,IAAM,KAC9C,QACF,CAAO,GAAIjP,EAAI,IAAMN,EAAQ,EAEtBoU,GAAS,IAAM,GAAGsD,EAAMnI,KAAK,IAAM,IAAM,KAC9C,QACF,CAGA6N,EAAgB1I,EAEhB,QACF,CAGA,GAAIA,EAAY,MAAQ,EACjBN,GAAS,IAAM,GAAGsD,EAAMnI,KAAK,IAAM,IAAM,KAC9C6N,EAAgB1I,EAChB,QACF,CAGAA,EAAkE,OAArD0I,EAAgB,OAAU,GAAK1I,EAAY,MAC1D,MAAW0I,IAEJhJ,GAAS,IAAM,GAAGsD,EAAMnI,KAAK,IAAM,IAAM,KAMhD,GAHA6N,EAAgB,KAGZ1I,EAAY,IAAM,CACpB,IAAKN,GAAS,GAAK,EAAG,MACtBsD,EAAMnI,KAAKmF,EACb,MAAO,GAAIA,EAAY,KAAO,CAC5B,IAAKN,GAAS,GAAK,EAAG,MACtBsD,EAAMnI,KACJmF,GAAa,EAAM,IACP,GAAZA,EAAmB,IAEvB,MAAO,GAAIA,EAAY,MAAS,CAC9B,IAAKN,GAAS,GAAK,EAAG,MACtBsD,EAAMnI,KACJmF,GAAa,GAAM,IACnBA,GAAa,EAAM,GAAO,IACd,GAAZA,EAAmB,IAEvB,KAAO,MAAIA,EAAY,SASrB,MAAM,IAAI/E,MAAM,sBARhB,IAAKyE,GAAS,GAAK,EAAG,MACtBsD,EAAMnI,KACJmF,GAAa,GAAO,IACpBA,GAAa,GAAM,GAAO,IAC1BA,GAAa,EAAM,GAAO,IACd,GAAZA,EAAmB,IAIvB,CACF,CAEA,OAAOgD,CACT,CA2BA,SAAS5F,EAAeiC,GACtB,OAAOhE,EAAOtB,YAxHhB,SAAsBsF,GAMpB,IAFAA,GAFAA,EAAMA,EAAIsJ,MAAM,KAAK,IAEXvG,OAAOD,QAAQqG,EAAmB,KAEpCld,OAAS,EAAG,MAAO,GAE3B,KAAO+T,EAAI/T,OAAS,GAAM,GACxB+T,GAAY,IAEd,OAAOA,CACT,CA4G4BuJ,CAAYvJ,GACxC,CAEA,SAASF,EAAY0J,EAAKC,EAAKzb,EAAQ/B,GACrC,IAAIM,EACJ,IAAKA,EAAI,EAAGA,EAAIN,KACTM,EAAIyB,GAAUyb,EAAIxd,QAAYM,GAAKid,EAAIvd,UADpBM,EAExBkd,EAAIld,EAAIyB,GAAUwb,EAAIjd,GAExB,OAAOA,CACT,CAKA,SAASsQ,EAAYO,EAAKhI,GACxB,OAAOgI,aAAehI,GACZ,MAAPgI,GAAkC,MAAnBA,EAAInS,aAA+C,MAAxBmS,EAAInS,YAAY4E,MACzDuN,EAAInS,YAAY4E,OAASuF,EAAKvF,IACpC,CACA,SAASyN,EAAaF,GAEpB,OAAOA,GAAQA,CACjB,CAIA,MAAMsG,EAAsB,WAC1B,MAAMgG,EAAW,mBACXC,EAAQ,IAAIje,MAAM,KACxB,IAAK,IAAIa,EAAI,EAAGA,EAAI,KAAMA,EAAG,CAC3B,MAAMqd,EAAU,GAAJrd,EACZ,IAAK,IAAI+S,EAAI,EAAGA,EAAI,KAAMA,EACxBqK,EAAMC,EAAMtK,GAAKoK,EAASnd,GAAKmd,EAASpK,EAE5C,CACA,OAAOqK,CACR,CAV2B,GAa5B,SAASrE,EAAoBpL,GAC3B,MAAyB,oBAAX3J,OAAyBsZ,EAAyB3P,CAClE,CAEA,SAAS2P,IACP,MAAM,IAAIjO,MAAM,uBAClB,eCxjEA9R,EAAQ2C,KAAO,SAAUU,EAAQa,EAAQ8b,EAAMC,EAAMC,GACnD,IAAI7a,EAAGuP,EACHuL,EAAiB,EAATD,EAAcD,EAAO,EAC7BG,GAAQ,GAAKD,GAAQ,EACrBE,EAAQD,GAAQ,EAChBE,GAAS,EACT7d,EAAIud,EAAQE,EAAS,EAAK,EAC1BK,EAAIP,GAAQ,EAAI,EAChBQ,EAAInd,EAAOa,EAASzB,GAOxB,IALAA,GAAK8d,EAELlb,EAAImb,GAAM,IAAOF,GAAU,EAC3BE,KAAQF,EACRA,GAASH,EACFG,EAAQ,EAAGjb,EAAS,IAAJA,EAAWhC,EAAOa,EAASzB,GAAIA,GAAK8d,EAAGD,GAAS,GAKvE,IAHA1L,EAAIvP,GAAM,IAAOib,GAAU,EAC3Bjb,KAAQib,EACRA,GAASL,EACFK,EAAQ,EAAG1L,EAAS,IAAJA,EAAWvR,EAAOa,EAASzB,GAAIA,GAAK8d,EAAGD,GAAS,GAEvE,GAAU,IAANjb,EACFA,EAAI,EAAIgb,MACH,IAAIhb,IAAM+a,EACf,OAAOxL,EAAI6L,IAAsBnB,KAAdkB,GAAK,EAAI,GAE5B5L,GAAQlR,KAAKoY,IAAI,EAAGmE,GACpB5a,GAAQgb,CACV,CACA,OAAQG,GAAK,EAAI,GAAK5L,EAAIlR,KAAKoY,IAAI,EAAGzW,EAAI4a,EAC5C,EAEAjgB,EAAQgE,MAAQ,SAAUX,EAAQY,EAAOC,EAAQ8b,EAAMC,EAAMC,GAC3D,IAAI7a,EAAGuP,EAAG4B,EACN2J,EAAiB,EAATD,EAAcD,EAAO,EAC7BG,GAAQ,GAAKD,GAAQ,EACrBE,EAAQD,GAAQ,EAChBM,EAAe,KAATT,EAAcvc,KAAKoY,IAAI,GAAI,IAAMpY,KAAKoY,IAAI,GAAI,IAAM,EAC1DrZ,EAAIud,EAAO,EAAKE,EAAS,EACzBK,EAAIP,EAAO,GAAK,EAChBQ,EAAIvc,EAAQ,GAAgB,IAAVA,GAAe,EAAIA,EAAQ,EAAK,EAAI,EAmC1D,IAjCAA,EAAQP,KAAK0b,IAAInb,GAEb0c,MAAM1c,IAAUA,IAAUqb,KAC5B1K,EAAI+L,MAAM1c,GAAS,EAAI,EACvBoB,EAAI+a,IAEJ/a,EAAI3B,KAAKqb,MAAMrb,KAAKkd,IAAI3c,GAASP,KAAKmd,KAClC5c,GAASuS,EAAI9S,KAAKoY,IAAI,GAAIzW,IAAM,IAClCA,IACAmR,GAAK,IAGLvS,GADEoB,EAAIgb,GAAS,EACNK,EAAKlK,EAELkK,EAAKhd,KAAKoY,IAAI,EAAG,EAAIuE,IAEpB7J,GAAK,IACfnR,IACAmR,GAAK,GAGHnR,EAAIgb,GAASD,GACfxL,EAAI,EACJvP,EAAI+a,GACK/a,EAAIgb,GAAS,GACtBzL,GAAM3Q,EAAQuS,EAAK,GAAK9S,KAAKoY,IAAI,EAAGmE,GACpC5a,GAAQgb,IAERzL,EAAI3Q,EAAQP,KAAKoY,IAAI,EAAGuE,EAAQ,GAAK3c,KAAKoY,IAAI,EAAGmE,GACjD5a,EAAI,IAID4a,GAAQ,EAAG5c,EAAOa,EAASzB,GAAS,IAAJmS,EAAUnS,GAAK8d,EAAG3L,GAAK,IAAKqL,GAAQ,GAI3E,IAFA5a,EAAKA,GAAK4a,EAAQrL,EAClBuL,GAAQF,EACDE,EAAO,EAAG9c,EAAOa,EAASzB,GAAS,IAAJ4C,EAAU5C,GAAK8d,EAAGlb,GAAK,IAAK8a,GAAQ,GAE1E9c,EAAOa,EAASzB,EAAI8d,IAAU,IAAJC,CAC5B,ICnFIM,EAA2B,CAAC,EAGhC,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,QAAqBnX,IAAjBoX,EACH,OAAOA,EAAajhB,QAGrB,IAAIC,EAAS6gB,EAAyBE,GAAY,CAGjDhhB,QAAS,CAAC,GAOX,OAHAkhB,EAAoBF,GAAU/gB,EAAQA,EAAOD,QAAS+gB,GAG/C9gB,EAAOD,OACf,QCrBA+gB,EAAoBR,EAAI,CAACvgB,EAASiQ,KACjC,IAAI,IAAIpF,KAAOoF,EACX8Q,EAAoBI,EAAElR,EAAYpF,KAASkW,EAAoBI,EAAEnhB,EAAS6K,IAC5E/J,OAAOgX,eAAe9X,EAAS6K,EAAK,CAAEkN,YAAY,EAAMrL,IAAKuD,EAAWpF,IAE1E,ECNDkW,EAAoBK,EAAI,WACvB,GAA0B,iBAAfC,WAAyB,OAAOA,WAC3C,IACC,OAAOjhB,MAAQ,IAAIkhB,SAAS,cAAb,EAChB,CAAE,MAAOjc,GACR,GAAsB,iBAAXkc,OAAqB,OAAOA,MACxC,CACA,CAPuB,GCAxBR,EAAoBI,EAAI,CAAC7N,EAAKkO,IAAU1gB,OAAON,UAAUihB,eAAe5gB,KAAKyS,EAAKkO,GCClFT,EAAoBW,EAAK1hB,IACH,oBAAXqS,QAA0BA,OAAOsP,aAC1C7gB,OAAOgX,eAAe9X,EAASqS,OAAOsP,YAAa,CAAE1d,MAAO,WAE7DnD,OAAOgX,eAAe9X,EAAS,aAAc,CAAEiE,OAAO,GAAO,ECFpC8c,EAAoB","sources":["webpack://XDR/webpack/universalModuleDefinition","webpack://XDR/./buffer.js","webpack://XDR/./src/browser.js","webpack://XDR/./src/errors.js","webpack://XDR/./src/serialization/xdr-reader.js","webpack://XDR/./src/serialization/xdr-writer.js","webpack://XDR/./src/xdr-type.js","webpack://XDR/./src/int.js","webpack://XDR/./src/bigint-encoder.js","webpack://XDR/./src/large-int.js","webpack://XDR/./src/hyper.js","webpack://XDR/./src/unsigned-int.js","webpack://XDR/./src/unsigned-hyper.js","webpack://XDR/./src/float.js","webpack://XDR/./src/double.js","webpack://XDR/./src/quadruple.js","webpack://XDR/./src/bool.js","webpack://XDR/./src/string.js","webpack://XDR/./src/opaque.js","webpack://XDR/./src/var-opaque.js","webpack://XDR/./src/array.js","webpack://XDR/./src/var-array.js","webpack://XDR/./src/option.js","webpack://XDR/./src/void.js","webpack://XDR/./src/enum.js","webpack://XDR/./src/reference.js","webpack://XDR/./src/struct.js","webpack://XDR/./src/union.js","webpack://XDR/./src/config.js","webpack://XDR/./node_modules/base64-js/index.js","webpack://XDR/./node_modules/buffer/index.js","webpack://XDR/./node_modules/ieee754/index.js","webpack://XDR/webpack/bootstrap","webpack://XDR/webpack/runtime/define property getters","webpack://XDR/webpack/runtime/global","webpack://XDR/webpack/runtime/hasOwnProperty shorthand","webpack://XDR/webpack/runtime/make namespace object","webpack://XDR/webpack/startup"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"XDR\"] = factory();\n\telse\n\t\troot[\"XDR\"] = factory();\n})(this, () => {\nreturn ","// See https://github.com/stellar/js-xdr/issues/117\nimport { Buffer } from 'buffer';\n\nif (!(Buffer.alloc(1).subarray(0, 1) instanceof Buffer)) {\n Buffer.prototype.subarray = function subarray(start, end) {\n const result = Uint8Array.prototype.subarray.call(this, start, end);\n Object.setPrototypeOf(result, Buffer.prototype);\n return result;\n };\n}\n\nexport default Buffer;\n","// eslint-disable-next-line prefer-import/prefer-import-over-require\nconst exports = require('./index');\nmodule.exports = exports;\n","export class XdrWriterError extends TypeError {\n constructor(message) {\n super(`XDR Write Error: ${message}`);\n }\n}\n\nexport class XdrReaderError extends TypeError {\n constructor(message) {\n super(`XDR Read Error: ${message}`);\n }\n}\n\nexport class XdrDefinitionError extends TypeError {\n constructor(message) {\n super(`XDR Type Definition Error: ${message}`);\n }\n}\n\nexport class XdrNotImplementedDefinitionError extends XdrDefinitionError {\n constructor() {\n super(\n `method not implemented, it should be overloaded in the descendant class.`\n );\n }\n}\n","/**\n * @internal\n */\nimport { XdrReaderError } from '../errors';\n\nexport class XdrReader {\n /**\n * @constructor\n * @param {Buffer} source - Buffer containing serialized data\n */\n constructor(source) {\n if (!Buffer.isBuffer(source)) {\n if (\n source instanceof Array ||\n Array.isArray(source) ||\n ArrayBuffer.isView(source)\n ) {\n source = Buffer.from(source);\n } else {\n throw new XdrReaderError(`source invalid: ${source}`);\n }\n }\n\n this._buffer = source;\n this._length = source.length;\n this._index = 0;\n }\n\n /**\n * @type {Buffer}\n * @private\n * @readonly\n */\n _buffer;\n /**\n * @type {Number}\n * @private\n * @readonly\n */\n _length;\n /**\n * @type {Number}\n * @private\n * @readonly\n */\n _index;\n\n /**\n * Check if the reader reached the end of the input buffer\n * @return {Boolean}\n */\n get eof() {\n return this._index === this._length;\n }\n\n /**\n * Advance reader position, check padding and overflow\n * @param {Number} size - Bytes to read\n * @return {Number} Position to read from\n * @private\n */\n advance(size) {\n const from = this._index;\n // advance cursor position\n this._index += size;\n // check buffer boundaries\n if (this._length < this._index)\n throw new XdrReaderError(\n 'attempt to read outside the boundary of the buffer'\n );\n // check that padding is correct for Opaque and String\n const padding = 4 - (size % 4 || 4);\n if (padding > 0) {\n for (let i = 0; i < padding; i++)\n if (this._buffer[this._index + i] !== 0)\n // all bytes in the padding should be zeros\n throw new XdrReaderError('invalid padding');\n this._index += padding;\n }\n return from;\n }\n\n /**\n * Reset reader position\n * @return {void}\n */\n rewind() {\n this._index = 0;\n }\n\n /**\n * Read byte array from the buffer\n * @param {Number} size - Bytes to read\n * @return {Buffer} - Sliced portion of the underlying buffer\n */\n read(size) {\n const from = this.advance(size);\n return this._buffer.subarray(from, from + size);\n }\n\n /**\n * Read i32 from buffer\n * @return {Number}\n */\n readInt32BE() {\n return this._buffer.readInt32BE(this.advance(4));\n }\n\n /**\n * Read u32 from buffer\n * @return {Number}\n */\n readUInt32BE() {\n return this._buffer.readUInt32BE(this.advance(4));\n }\n\n /**\n * Read i64 from buffer\n * @return {BigInt}\n */\n readBigInt64BE() {\n return this._buffer.readBigInt64BE(this.advance(8));\n }\n\n /**\n * Read u64 from buffer\n * @return {BigInt}\n */\n readBigUInt64BE() {\n return this._buffer.readBigUInt64BE(this.advance(8));\n }\n\n /**\n * Read float from buffer\n * @return {Number}\n */\n readFloatBE() {\n return this._buffer.readFloatBE(this.advance(4));\n }\n\n /**\n * Read double from buffer\n * @return {Number}\n */\n readDoubleBE() {\n return this._buffer.readDoubleBE(this.advance(8));\n }\n\n /**\n * Ensure that input buffer has been consumed in full, otherwise it's a type mismatch\n * @return {void}\n * @throws {XdrReaderError}\n */\n ensureInputConsumed() {\n if (this._index !== this._length)\n throw new XdrReaderError(\n `invalid XDR contract typecast - source buffer not entirely consumed`\n );\n }\n}\n","const BUFFER_CHUNK = 8192; // 8 KB chunk size increment\n\n/**\n * @internal\n */\nexport class XdrWriter {\n /**\n * @param {Buffer|Number} [buffer] - Optional destination buffer\n */\n constructor(buffer) {\n if (typeof buffer === 'number') {\n buffer = Buffer.allocUnsafe(buffer);\n } else if (!(buffer instanceof Buffer)) {\n buffer = Buffer.allocUnsafe(BUFFER_CHUNK);\n }\n this._buffer = buffer;\n this._length = buffer.length;\n }\n\n /**\n * @type {Buffer}\n * @private\n * @readonly\n */\n _buffer;\n /**\n * @type {Number}\n * @private\n * @readonly\n */\n _length;\n /**\n * @type {Number}\n * @private\n * @readonly\n */\n _index = 0;\n\n /**\n * Advance writer position, write padding if needed, auto-resize the buffer\n * @param {Number} size - Bytes to write\n * @return {Number} Position to read from\n * @private\n */\n alloc(size) {\n const from = this._index;\n // advance cursor position\n this._index += size;\n // ensure sufficient buffer size\n if (this._length < this._index) {\n this.resize(this._index);\n }\n return from;\n }\n\n /**\n * Increase size of the underlying buffer\n * @param {Number} minRequiredSize - Minimum required buffer size\n * @return {void}\n * @private\n */\n resize(minRequiredSize) {\n // calculate new length, align new buffer length by chunk size\n const newLength = Math.ceil(minRequiredSize / BUFFER_CHUNK) * BUFFER_CHUNK;\n // create new buffer and copy previous data\n const newBuffer = Buffer.allocUnsafe(newLength);\n this._buffer.copy(newBuffer, 0, 0, this._length);\n // update references\n this._buffer = newBuffer;\n this._length = newLength;\n }\n\n /**\n * Return XDR-serialized value\n * @return {Buffer}\n */\n finalize() {\n // clip underlying buffer to the actually written value\n return this._buffer.subarray(0, this._index);\n }\n\n /**\n * Return XDR-serialized value as byte array\n * @return {Number[]}\n */\n toArray() {\n return [...this.finalize()];\n }\n\n /**\n * Write byte array from the buffer\n * @param {Buffer|String} value - Bytes/string to write\n * @param {Number} size - Size in bytes\n * @return {XdrReader} - XdrReader wrapper on top of a subarray\n */\n write(value, size) {\n if (typeof value === 'string') {\n // serialize string directly to the output buffer\n const offset = this.alloc(size);\n this._buffer.write(value, offset, 'utf8');\n } else {\n // copy data to the output buffer\n if (!(value instanceof Buffer)) {\n value = Buffer.from(value);\n }\n const offset = this.alloc(size);\n value.copy(this._buffer, offset, 0, size);\n }\n\n // add padding for 4-byte XDR alignment\n const padding = 4 - (size % 4 || 4);\n if (padding > 0) {\n const offset = this.alloc(padding);\n this._buffer.fill(0, offset, this._index);\n }\n }\n\n /**\n * Write i32 from buffer\n * @param {Number} value - Value to serialize\n * @return {void}\n */\n writeInt32BE(value) {\n const offset = this.alloc(4);\n this._buffer.writeInt32BE(value, offset);\n }\n\n /**\n * Write u32 from buffer\n * @param {Number} value - Value to serialize\n * @return {void}\n */\n writeUInt32BE(value) {\n const offset = this.alloc(4);\n this._buffer.writeUInt32BE(value, offset);\n }\n\n /**\n * Write i64 from buffer\n * @param {BigInt} value - Value to serialize\n * @return {void}\n */\n writeBigInt64BE(value) {\n const offset = this.alloc(8);\n this._buffer.writeBigInt64BE(value, offset);\n }\n\n /**\n * Write u64 from buffer\n * @param {BigInt} value - Value to serialize\n * @return {void}\n */\n writeBigUInt64BE(value) {\n const offset = this.alloc(8);\n this._buffer.writeBigUInt64BE(value, offset);\n }\n\n /**\n * Write float from buffer\n * @param {Number} value - Value to serialize\n * @return {void}\n */\n writeFloatBE(value) {\n const offset = this.alloc(4);\n this._buffer.writeFloatBE(value, offset);\n }\n\n /**\n * Write double from buffer\n * @param {Number} value - Value to serialize\n * @return {void}\n */\n writeDoubleBE(value) {\n const offset = this.alloc(8);\n this._buffer.writeDoubleBE(value, offset);\n }\n\n static bufferChunkSize = BUFFER_CHUNK;\n}\n","import { XdrReader } from './serialization/xdr-reader';\nimport { XdrWriter } from './serialization/xdr-writer';\nimport { XdrNotImplementedDefinitionError } from './errors';\n\nclass XdrType {\n /**\n * Encode value to XDR format\n * @param {XdrEncodingFormat} [format] - Encoding format (one of \"raw\", \"hex\", \"base64\")\n * @return {String|Buffer}\n */\n toXDR(format = 'raw') {\n if (!this.write) return this.constructor.toXDR(this, format);\n\n const writer = new XdrWriter();\n this.write(this, writer);\n return encodeResult(writer.finalize(), format);\n }\n\n /**\n * Decode XDR-encoded value\n * @param {Buffer|String} input - XDR-encoded input data\n * @param {XdrEncodingFormat} [format] - Encoding format (one of \"raw\", \"hex\", \"base64\")\n * @return {this}\n */\n fromXDR(input, format = 'raw') {\n if (!this.read) return this.constructor.fromXDR(input, format);\n\n const reader = new XdrReader(decodeInput(input, format));\n const result = this.read(reader);\n reader.ensureInputConsumed();\n return result;\n }\n\n /**\n * Check whether input contains a valid XDR-encoded value\n * @param {Buffer|String} input - XDR-encoded input data\n * @param {XdrEncodingFormat} [format] - Encoding format (one of \"raw\", \"hex\", \"base64\")\n * @return {Boolean}\n */\n validateXDR(input, format = 'raw') {\n try {\n this.fromXDR(input, format);\n return true;\n } catch (e) {\n return false;\n }\n }\n\n /**\n * Encode value to XDR format\n * @param {this} value - Value to serialize\n * @param {XdrEncodingFormat} [format] - Encoding format (one of \"raw\", \"hex\", \"base64\")\n * @return {Buffer}\n */\n static toXDR(value, format = 'raw') {\n const writer = new XdrWriter();\n this.write(value, writer);\n return encodeResult(writer.finalize(), format);\n }\n\n /**\n * Decode XDR-encoded value\n * @param {Buffer|String} input - XDR-encoded input data\n * @param {XdrEncodingFormat} [format] - Encoding format (one of \"raw\", \"hex\", \"base64\")\n * @return {this}\n */\n static fromXDR(input, format = 'raw') {\n const reader = new XdrReader(decodeInput(input, format));\n const result = this.read(reader);\n reader.ensureInputConsumed();\n return result;\n }\n\n /**\n * Check whether input contains a valid XDR-encoded value\n * @param {Buffer|String} input - XDR-encoded input data\n * @param {XdrEncodingFormat} [format] - Encoding format (one of \"raw\", \"hex\", \"base64\")\n * @return {Boolean}\n */\n static validateXDR(input, format = 'raw') {\n try {\n this.fromXDR(input, format);\n return true;\n } catch (e) {\n return false;\n }\n }\n}\n\nexport class XdrPrimitiveType extends XdrType {\n /**\n * Read value from the XDR-serialized input\n * @param {XdrReader} reader - XdrReader instance\n * @return {this}\n * @abstract\n */\n // eslint-disable-next-line no-unused-vars\n static read(reader) {\n throw new XdrNotImplementedDefinitionError();\n }\n\n /**\n * Write XDR value to the buffer\n * @param {this} value - Value to write\n * @param {XdrWriter} writer - XdrWriter instance\n * @return {void}\n * @abstract\n */\n // eslint-disable-next-line no-unused-vars\n static write(value, writer) {\n throw new XdrNotImplementedDefinitionError();\n }\n\n /**\n * Check whether XDR primitive value is valid\n * @param {this} value - Value to check\n * @return {Boolean}\n * @abstract\n */\n // eslint-disable-next-line no-unused-vars\n static isValid(value) {\n return false;\n }\n}\n\nexport class XdrCompositeType extends XdrType {\n // Every descendant should implement two methods: read(reader) and write(value, writer)\n\n /**\n * Check whether XDR primitive value is valid\n * @param {this} value - Value to check\n * @return {Boolean}\n * @abstract\n */\n // eslint-disable-next-line no-unused-vars\n isValid(value) {\n return false;\n }\n}\n\nclass InvalidXdrEncodingFormatError extends TypeError {\n constructor(format) {\n super(`Invalid format ${format}, must be one of \"raw\", \"hex\", \"base64\"`);\n }\n}\n\nfunction encodeResult(buffer, format) {\n switch (format) {\n case 'raw':\n return buffer;\n case 'hex':\n return buffer.toString('hex');\n case 'base64':\n return buffer.toString('base64');\n default:\n throw new InvalidXdrEncodingFormatError(format);\n }\n}\n\nfunction decodeInput(input, format) {\n switch (format) {\n case 'raw':\n return input;\n case 'hex':\n return Buffer.from(input, 'hex');\n case 'base64':\n return Buffer.from(input, 'base64');\n default:\n throw new InvalidXdrEncodingFormatError(format);\n }\n}\n\n/**\n * Provides a \"duck typed\" version of the native `instanceof` for read/write.\n *\n * \"Duck typing\" means if the parameter _looks like_ and _acts like_ a duck\n * (i.e. the type we're checking), it will be treated as that type.\n *\n * In this case, the \"type\" we're looking for is \"like XdrType\" but also \"like\n * XdrCompositeType|XdrPrimitiveType\" (i.e. serializable), but also conditioned\n * on a particular subclass of \"XdrType\" (e.g. {@link Union} which extends\n * XdrType).\n *\n * This makes the package resilient to downstream systems that may be combining\n * many versions of a package across its stack that are technically compatible\n * but fail `instanceof` checks due to cross-pollination.\n */\nexport function isSerializableIsh(value, subtype) {\n return (\n value !== undefined &&\n value !== null && // prereqs, otherwise `getPrototypeOf` pops\n (value instanceof subtype || // quickest check\n // Do an initial constructor check (anywhere is fine so that children of\n // `subtype` still work), then\n (hasConstructor(value, subtype) &&\n // ensure it has read/write methods, then\n typeof value.constructor.read === 'function' &&\n typeof value.constructor.write === 'function' &&\n // ensure XdrType is in the prototype chain\n hasConstructor(value, 'XdrType')))\n );\n}\n\n/** Tries to find `subtype` in any of the constructors or meta of `instance`. */\nexport function hasConstructor(instance, subtype) {\n do {\n const ctor = instance.constructor;\n if (ctor.name === subtype) {\n return true;\n }\n } while ((instance = Object.getPrototypeOf(instance)));\n return false;\n}\n\n/**\n * @typedef {'raw'|'hex'|'base64'} XdrEncodingFormat\n */\n","import { XdrPrimitiveType } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nconst MAX_VALUE = 2147483647;\nconst MIN_VALUE = -2147483648;\n\nexport class Int extends XdrPrimitiveType {\n /**\n * @inheritDoc\n */\n static read(reader) {\n return reader.readInt32BE();\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (typeof value !== 'number') throw new XdrWriterError('not a number');\n\n if ((value | 0) !== value) throw new XdrWriterError('invalid i32 value');\n\n writer.writeInt32BE(value);\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n if (typeof value !== 'number' || (value | 0) !== value) {\n return false;\n }\n\n return value >= MIN_VALUE && value <= MAX_VALUE;\n }\n}\n\nInt.MAX_VALUE = MAX_VALUE;\nInt.MIN_VALUE = -MIN_VALUE;\n","/**\n * Encode a native `bigint` value from a list of arbitrary integer-like values.\n *\n * @param {Array} parts - Slices to encode in big-endian\n * format (i.e. earlier elements are higher bits)\n * @param {64|128|256} size - Number of bits in the target integer type\n * @param {boolean} unsigned - Whether it's an unsigned integer\n *\n * @returns {bigint}\n */\nexport function encodeBigIntFromBits(parts, size, unsigned) {\n if (!(parts instanceof Array)) {\n // allow a single parameter instead of an array\n parts = [parts];\n } else if (parts.length && parts[0] instanceof Array) {\n // unpack nested array param\n parts = parts[0];\n }\n\n const total = parts.length;\n const sliceSize = size / total;\n switch (sliceSize) {\n case 32:\n case 64:\n case 128:\n case 256:\n break;\n\n default:\n throw new RangeError(\n `expected slices to fit in 32/64/128/256 bits, got ${parts}`\n );\n }\n\n // normalize all inputs to bigint\n try {\n for (let i = 0; i < parts.length; i++) {\n if (typeof parts[i] !== 'bigint') {\n parts[i] = BigInt(parts[i].valueOf());\n }\n }\n } catch (e) {\n throw new TypeError(`expected bigint-like values, got: ${parts} (${e})`);\n }\n\n // check for sign mismatches for single inputs (this is a special case to\n // handle one parameter passed to e.g. UnsignedHyper et al.)\n // see https://github.com/stellar/js-xdr/pull/100#discussion_r1228770845\n if (unsigned && parts.length === 1 && parts[0] < 0n) {\n throw new RangeError(`expected a positive value, got: ${parts}`);\n }\n\n // encode in big-endian fashion, shifting each slice by the slice size\n let result = BigInt.asUintN(sliceSize, parts[0]); // safe: len >= 1\n for (let i = 1; i < parts.length; i++) {\n result |= BigInt.asUintN(sliceSize, parts[i]) << BigInt(i * sliceSize);\n }\n\n // interpret value as signed if necessary and clamp it\n if (!unsigned) {\n result = BigInt.asIntN(size, result);\n }\n\n // check boundaries\n const [min, max] = calculateBigIntBoundaries(size, unsigned);\n if (result >= min && result <= max) {\n return result;\n }\n\n // failed to encode\n throw new TypeError(\n `bigint values [${parts}] for ${formatIntName(\n size,\n unsigned\n )} out of range [${min}, ${max}]: ${result}`\n );\n}\n\n/**\n * Transforms a single bigint value that's supposed to represent a `size`-bit\n * integer into a list of `sliceSize`d chunks.\n *\n * @param {bigint} value - Single bigint value to decompose\n * @param {64|128|256} iSize - Number of bits represented by `value`\n * @param {32|64|128} sliceSize - Number of chunks to decompose into\n * @return {bigint[]}\n */\nexport function sliceBigInt(value, iSize, sliceSize) {\n if (typeof value !== 'bigint') {\n throw new TypeError(`Expected bigint 'value', got ${typeof value}`);\n }\n\n const total = iSize / sliceSize;\n if (total === 1) {\n return [value];\n }\n\n if (\n sliceSize < 32 ||\n sliceSize > 128 ||\n (total !== 2 && total !== 4 && total !== 8)\n ) {\n throw new TypeError(\n `invalid bigint (${value}) and slice size (${iSize} -> ${sliceSize}) combination`\n );\n }\n\n const shift = BigInt(sliceSize);\n\n // iterate shift and mask application\n const result = new Array(total);\n for (let i = 0; i < total; i++) {\n // we force a signed interpretation to preserve sign in each slice value,\n // but downstream can convert to unsigned if it's appropriate\n result[i] = BigInt.asIntN(sliceSize, value); // clamps to size\n\n // move on to the next chunk\n value >>= shift;\n }\n\n return result;\n}\n\nexport function formatIntName(precision, unsigned) {\n return `${unsigned ? 'u' : 'i'}${precision}`;\n}\n\n/**\n * Get min|max boundaries for an integer with a specified bits size\n * @param {64|128|256} size - Number of bits in the source integer type\n * @param {Boolean} unsigned - Whether it's an unsigned integer\n * @return {BigInt[]}\n */\nexport function calculateBigIntBoundaries(size, unsigned) {\n if (unsigned) {\n return [0n, (1n << BigInt(size)) - 1n];\n }\n\n const boundary = 1n << BigInt(size - 1);\n return [0n - boundary, boundary - 1n];\n}\n","import { XdrPrimitiveType } from './xdr-type';\nimport {\n calculateBigIntBoundaries,\n encodeBigIntFromBits,\n sliceBigInt\n} from './bigint-encoder';\nimport { XdrNotImplementedDefinitionError, XdrWriterError } from './errors';\n\nexport class LargeInt extends XdrPrimitiveType {\n /**\n * @param {Array} parts - Slices to encode\n */\n constructor(args) {\n super();\n this._value = encodeBigIntFromBits(args, this.size, this.unsigned);\n }\n\n /**\n * Signed/unsigned representation\n * @type {Boolean}\n * @abstract\n */\n get unsigned() {\n throw new XdrNotImplementedDefinitionError();\n }\n\n /**\n * Size of the integer in bits\n * @type {Number}\n * @abstract\n */\n get size() {\n throw new XdrNotImplementedDefinitionError();\n }\n\n /**\n * Slice integer to parts with smaller bit size\n * @param {32|64|128} sliceSize - Size of each part in bits\n * @return {BigInt[]}\n */\n slice(sliceSize) {\n return sliceBigInt(this._value, this.size, sliceSize);\n }\n\n toString() {\n return this._value.toString();\n }\n\n toJSON() {\n return { _value: this._value.toString() };\n }\n\n toBigInt() {\n return BigInt(this._value);\n }\n\n /**\n * @inheritDoc\n */\n static read(reader) {\n const { size } = this.prototype;\n if (size === 64) return new this(reader.readBigUInt64BE());\n return new this(\n ...Array.from({ length: size / 64 }, () =>\n reader.readBigUInt64BE()\n ).reverse()\n );\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (value instanceof this) {\n value = value._value;\n } else if (\n typeof value !== 'bigint' ||\n value > this.MAX_VALUE ||\n value < this.MIN_VALUE\n )\n throw new XdrWriterError(`${value} is not a ${this.name}`);\n\n const { unsigned, size } = this.prototype;\n if (size === 64) {\n if (unsigned) {\n writer.writeBigUInt64BE(value);\n } else {\n writer.writeBigInt64BE(value);\n }\n } else {\n for (const part of sliceBigInt(value, size, 64).reverse()) {\n if (unsigned) {\n writer.writeBigUInt64BE(part);\n } else {\n writer.writeBigInt64BE(part);\n }\n }\n }\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n return typeof value === 'bigint' || value instanceof this;\n }\n\n /**\n * Create instance from string\n * @param {String} string - Numeric representation\n * @return {LargeInt}\n */\n static fromString(string) {\n return new this(string);\n }\n\n static MAX_VALUE = 0n;\n\n static MIN_VALUE = 0n;\n\n /**\n * @internal\n * @return {void}\n */\n static defineIntBoundaries() {\n const [min, max] = calculateBigIntBoundaries(\n this.prototype.size,\n this.prototype.unsigned\n );\n this.MIN_VALUE = min;\n this.MAX_VALUE = max;\n }\n}\n","import { LargeInt } from './large-int';\n\nexport class Hyper extends LargeInt {\n /**\n * @param {Array} parts - Slices to encode\n */\n constructor(...args) {\n super(args);\n }\n\n get low() {\n return Number(this._value & 0xffffffffn) << 0;\n }\n\n get high() {\n return Number(this._value >> 32n) >> 0;\n }\n\n get size() {\n return 64;\n }\n\n get unsigned() {\n return false;\n }\n\n /**\n * Create Hyper instance from two [high][low] i32 values\n * @param {Number} low - Low part of i64 number\n * @param {Number} high - High part of i64 number\n * @return {LargeInt}\n */\n static fromBits(low, high) {\n return new this(low, high);\n }\n}\n\nHyper.defineIntBoundaries();\n","import { XdrPrimitiveType } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nconst MAX_VALUE = 4294967295;\nconst MIN_VALUE = 0;\n\nexport class UnsignedInt extends XdrPrimitiveType {\n /**\n * @inheritDoc\n */\n static read(reader) {\n return reader.readUInt32BE();\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (\n typeof value !== 'number' ||\n !(value >= MIN_VALUE && value <= MAX_VALUE) ||\n value % 1 !== 0\n )\n throw new XdrWriterError('invalid u32 value');\n\n writer.writeUInt32BE(value);\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n if (typeof value !== 'number' || value % 1 !== 0) {\n return false;\n }\n\n return value >= MIN_VALUE && value <= MAX_VALUE;\n }\n}\n\nUnsignedInt.MAX_VALUE = MAX_VALUE;\nUnsignedInt.MIN_VALUE = MIN_VALUE;\n","import { LargeInt } from './large-int';\n\nexport class UnsignedHyper extends LargeInt {\n /**\n * @param {Array} parts - Slices to encode\n */\n constructor(...args) {\n super(args);\n }\n\n get low() {\n return Number(this._value & 0xffffffffn) << 0;\n }\n\n get high() {\n return Number(this._value >> 32n) >> 0;\n }\n\n get size() {\n return 64;\n }\n\n get unsigned() {\n return true;\n }\n\n /**\n * Create UnsignedHyper instance from two [high][low] i32 values\n * @param {Number} low - Low part of u64 number\n * @param {Number} high - High part of u64 number\n * @return {UnsignedHyper}\n */\n static fromBits(low, high) {\n return new this(low, high);\n }\n}\n\nUnsignedHyper.defineIntBoundaries();\n","import { XdrPrimitiveType } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nexport class Float extends XdrPrimitiveType {\n /**\n * @inheritDoc\n */\n static read(reader) {\n return reader.readFloatBE();\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (typeof value !== 'number') throw new XdrWriterError('not a number');\n\n writer.writeFloatBE(value);\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n return typeof value === 'number';\n }\n}\n","import { XdrPrimitiveType } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nexport class Double extends XdrPrimitiveType {\n /**\n * @inheritDoc\n */\n static read(reader) {\n return reader.readDoubleBE();\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (typeof value !== 'number') throw new XdrWriterError('not a number');\n\n writer.writeDoubleBE(value);\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n return typeof value === 'number';\n }\n}\n","import { XdrPrimitiveType } from './xdr-type';\nimport { XdrDefinitionError } from './errors';\n\nexport class Quadruple extends XdrPrimitiveType {\n static read() {\n throw new XdrDefinitionError('quadruple not supported');\n }\n\n static write() {\n throw new XdrDefinitionError('quadruple not supported');\n }\n\n static isValid() {\n return false;\n }\n}\n","import { Int } from './int';\nimport { XdrPrimitiveType } from './xdr-type';\nimport { XdrReaderError } from './errors';\n\nexport class Bool extends XdrPrimitiveType {\n /**\n * @inheritDoc\n */\n static read(reader) {\n const value = Int.read(reader);\n\n switch (value) {\n case 0:\n return false;\n case 1:\n return true;\n default:\n throw new XdrReaderError(`got ${value} when trying to read a bool`);\n }\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n const intVal = value ? 1 : 0;\n Int.write(intVal, writer);\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n return typeof value === 'boolean';\n }\n}\n","import { UnsignedInt } from './unsigned-int';\nimport { XdrCompositeType } from './xdr-type';\nimport { XdrReaderError, XdrWriterError } from './errors';\n\nexport class String extends XdrCompositeType {\n constructor(maxLength = UnsignedInt.MAX_VALUE) {\n super();\n this._maxLength = maxLength;\n }\n\n /**\n * @inheritDoc\n */\n read(reader) {\n const size = UnsignedInt.read(reader);\n if (size > this._maxLength)\n throw new XdrReaderError(\n `saw ${size} length String, max allowed is ${this._maxLength}`\n );\n\n return reader.read(size);\n }\n\n readString(reader) {\n return this.read(reader).toString('utf8');\n }\n\n /**\n * @inheritDoc\n */\n write(value, writer) {\n // calculate string byte size before writing\n const size =\n typeof value === 'string'\n ? Buffer.byteLength(value, 'utf8')\n : value.length;\n if (size > this._maxLength)\n throw new XdrWriterError(\n `got ${value.length} bytes, max allowed is ${this._maxLength}`\n );\n // write size info\n UnsignedInt.write(size, writer);\n writer.write(value, size);\n }\n\n /**\n * @inheritDoc\n */\n isValid(value) {\n if (typeof value === 'string') {\n return Buffer.byteLength(value, 'utf8') <= this._maxLength;\n }\n if (value instanceof Array || Buffer.isBuffer(value)) {\n return value.length <= this._maxLength;\n }\n return false;\n }\n}\n","import { XdrCompositeType } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nexport class Opaque extends XdrCompositeType {\n constructor(length) {\n super();\n this._length = length;\n }\n\n /**\n * @inheritDoc\n */\n read(reader) {\n return reader.read(this._length);\n }\n\n /**\n * @inheritDoc\n */\n write(value, writer) {\n const { length } = value;\n if (length !== this._length)\n throw new XdrWriterError(\n `got ${value.length} bytes, expected ${this._length}`\n );\n writer.write(value, length);\n }\n\n /**\n * @inheritDoc\n */\n isValid(value) {\n return Buffer.isBuffer(value) && value.length === this._length;\n }\n}\n","import { UnsignedInt } from './unsigned-int';\nimport { XdrCompositeType } from './xdr-type';\nimport { XdrReaderError, XdrWriterError } from './errors';\n\nexport class VarOpaque extends XdrCompositeType {\n constructor(maxLength = UnsignedInt.MAX_VALUE) {\n super();\n this._maxLength = maxLength;\n }\n\n /**\n * @inheritDoc\n */\n read(reader) {\n const size = UnsignedInt.read(reader);\n if (size > this._maxLength)\n throw new XdrReaderError(\n `saw ${size} length VarOpaque, max allowed is ${this._maxLength}`\n );\n return reader.read(size);\n }\n\n /**\n * @inheritDoc\n */\n write(value, writer) {\n const { length } = value;\n if (value.length > this._maxLength)\n throw new XdrWriterError(\n `got ${value.length} bytes, max allowed is ${this._maxLength}`\n );\n // write size info\n UnsignedInt.write(length, writer);\n writer.write(value, length);\n }\n\n /**\n * @inheritDoc\n */\n isValid(value) {\n return Buffer.isBuffer(value) && value.length <= this._maxLength;\n }\n}\n","import { XdrCompositeType } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nexport class Array extends XdrCompositeType {\n constructor(childType, length) {\n super();\n this._childType = childType;\n this._length = length;\n }\n\n /**\n * @inheritDoc\n */\n read(reader) {\n // allocate array of specified length\n const result = new global.Array(this._length);\n // read values\n for (let i = 0; i < this._length; i++) {\n result[i] = this._childType.read(reader);\n }\n return result;\n }\n\n /**\n * @inheritDoc\n */\n write(value, writer) {\n if (!global.Array.isArray(value))\n throw new XdrWriterError(`value is not array`);\n\n if (value.length !== this._length)\n throw new XdrWriterError(\n `got array of size ${value.length}, expected ${this._length}`\n );\n\n for (const child of value) {\n this._childType.write(child, writer);\n }\n }\n\n /**\n * @inheritDoc\n */\n isValid(value) {\n if (!(value instanceof global.Array) || value.length !== this._length) {\n return false;\n }\n\n for (const child of value) {\n if (!this._childType.isValid(child)) return false;\n }\n return true;\n }\n}\n","import { UnsignedInt } from './unsigned-int';\nimport { XdrCompositeType } from './xdr-type';\nimport { XdrReaderError, XdrWriterError } from './errors';\n\nexport class VarArray extends XdrCompositeType {\n constructor(childType, maxLength = UnsignedInt.MAX_VALUE) {\n super();\n this._childType = childType;\n this._maxLength = maxLength;\n }\n\n /**\n * @inheritDoc\n */\n read(reader) {\n const length = UnsignedInt.read(reader);\n if (length > this._maxLength)\n throw new XdrReaderError(\n `saw ${length} length VarArray, max allowed is ${this._maxLength}`\n );\n\n const result = new Array(length);\n for (let i = 0; i < length; i++) {\n result[i] = this._childType.read(reader);\n }\n return result;\n }\n\n /**\n * @inheritDoc\n */\n write(value, writer) {\n if (!(value instanceof Array))\n throw new XdrWriterError(`value is not array`);\n\n if (value.length > this._maxLength)\n throw new XdrWriterError(\n `got array of size ${value.length}, max allowed is ${this._maxLength}`\n );\n\n UnsignedInt.write(value.length, writer);\n for (const child of value) {\n this._childType.write(child, writer);\n }\n }\n\n /**\n * @inheritDoc\n */\n isValid(value) {\n if (!(value instanceof Array) || value.length > this._maxLength) {\n return false;\n }\n for (const child of value) {\n if (!this._childType.isValid(child)) return false;\n }\n return true;\n }\n}\n","import { Bool } from './bool';\nimport { XdrPrimitiveType } from './xdr-type';\n\nexport class Option extends XdrPrimitiveType {\n constructor(childType) {\n super();\n this._childType = childType;\n }\n\n /**\n * @inheritDoc\n */\n read(reader) {\n if (Bool.read(reader)) {\n return this._childType.read(reader);\n }\n\n return undefined;\n }\n\n /**\n * @inheritDoc\n */\n write(value, writer) {\n const isPresent = value !== null && value !== undefined;\n\n Bool.write(isPresent, writer);\n\n if (isPresent) {\n this._childType.write(value, writer);\n }\n }\n\n /**\n * @inheritDoc\n */\n isValid(value) {\n if (value === null || value === undefined) {\n return true;\n }\n return this._childType.isValid(value);\n }\n}\n","import { XdrPrimitiveType } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nexport class Void extends XdrPrimitiveType {\n /* jshint unused: false */\n\n static read() {\n return undefined;\n }\n\n static write(value) {\n if (value !== undefined)\n throw new XdrWriterError('trying to write value to a void slot');\n }\n\n static isValid(value) {\n return value === undefined;\n }\n}\n","import { Int } from './int';\nimport { XdrPrimitiveType, isSerializableIsh } from './xdr-type';\nimport { XdrReaderError, XdrWriterError } from './errors';\n\nexport class Enum extends XdrPrimitiveType {\n constructor(name, value) {\n super();\n this.name = name;\n this.value = value;\n }\n\n /**\n * @inheritDoc\n */\n static read(reader) {\n const intVal = Int.read(reader);\n const res = this._byValue[intVal];\n if (res === undefined)\n throw new XdrReaderError(\n `unknown ${this.enumName} member for value ${intVal}`\n );\n return res;\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (!this.isValid(value)) {\n throw new XdrWriterError(\n `${value} has enum name ${value?.enumName}, not ${\n this.enumName\n }: ${JSON.stringify(value)}`\n );\n }\n\n Int.write(value.value, writer);\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n return (\n value?.constructor?.enumName === this.enumName ||\n isSerializableIsh(value, this)\n );\n }\n\n static members() {\n return this._members;\n }\n\n static values() {\n return Object.values(this._members);\n }\n\n static fromName(name) {\n const result = this._members[name];\n\n if (!result)\n throw new TypeError(`${name} is not a member of ${this.enumName}`);\n\n return result;\n }\n\n static fromValue(value) {\n const result = this._byValue[value];\n if (result === undefined)\n throw new TypeError(\n `${value} is not a value of any member of ${this.enumName}`\n );\n return result;\n }\n\n static create(context, name, members) {\n const ChildEnum = class extends Enum {};\n\n ChildEnum.enumName = name;\n context.results[name] = ChildEnum;\n\n ChildEnum._members = {};\n ChildEnum._byValue = {};\n\n for (const [key, value] of Object.entries(members)) {\n const inst = new ChildEnum(key, value);\n ChildEnum._members[key] = inst;\n ChildEnum._byValue[value] = inst;\n ChildEnum[key] = () => inst;\n }\n\n return ChildEnum;\n }\n}\n","import { XdrPrimitiveType } from './xdr-type';\nimport { XdrDefinitionError } from './errors';\n\nexport class Reference extends XdrPrimitiveType {\n /* jshint unused: false */\n resolve() {\n throw new XdrDefinitionError(\n '\"resolve\" method should be implemented in the descendant class'\n );\n }\n}\n","import { Reference } from './reference';\nimport { XdrCompositeType, isSerializableIsh } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nexport class Struct extends XdrCompositeType {\n constructor(attributes) {\n super();\n this._attributes = attributes || {};\n }\n\n /**\n * @inheritDoc\n */\n static read(reader) {\n const attributes = {};\n for (const [fieldName, type] of this._fields) {\n attributes[fieldName] = type.read(reader);\n }\n return new this(attributes);\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (!this.isValid(value)) {\n throw new XdrWriterError(\n `${value} has struct name ${value?.constructor?.structName}, not ${\n this.structName\n }: ${JSON.stringify(value)}`\n );\n }\n\n for (const [fieldName, type] of this._fields) {\n const attribute = value._attributes[fieldName];\n type.write(attribute, writer);\n }\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n return (\n value?.constructor?.structName === this.structName ||\n isSerializableIsh(value, this)\n );\n }\n\n static create(context, name, fields) {\n const ChildStruct = class extends Struct {};\n\n ChildStruct.structName = name;\n\n context.results[name] = ChildStruct;\n\n const mappedFields = new Array(fields.length);\n for (let i = 0; i < fields.length; i++) {\n const fieldDescriptor = fields[i];\n const fieldName = fieldDescriptor[0];\n let field = fieldDescriptor[1];\n if (field instanceof Reference) {\n field = field.resolve(context);\n }\n mappedFields[i] = [fieldName, field];\n // create accessors\n ChildStruct.prototype[fieldName] = createAccessorMethod(fieldName);\n }\n\n ChildStruct._fields = mappedFields;\n\n return ChildStruct;\n }\n}\n\nfunction createAccessorMethod(name) {\n return function readOrWriteAttribute(value) {\n if (value !== undefined) {\n this._attributes[name] = value;\n }\n return this._attributes[name];\n };\n}\n","import { Void } from './void';\nimport { Reference } from './reference';\nimport { XdrCompositeType, isSerializableIsh } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nexport class Union extends XdrCompositeType {\n constructor(aSwitch, value) {\n super();\n this.set(aSwitch, value);\n }\n\n set(aSwitch, value) {\n if (typeof aSwitch === 'string') {\n aSwitch = this.constructor._switchOn.fromName(aSwitch);\n }\n\n this._switch = aSwitch;\n const arm = this.constructor.armForSwitch(this._switch);\n this._arm = arm;\n this._armType = arm === Void ? Void : this.constructor._arms[arm];\n this._value = value;\n }\n\n get(armName = this._arm) {\n if (this._arm !== Void && this._arm !== armName)\n throw new TypeError(`${armName} not set`);\n return this._value;\n }\n\n switch() {\n return this._switch;\n }\n\n arm() {\n return this._arm;\n }\n\n armType() {\n return this._armType;\n }\n\n value() {\n return this._value;\n }\n\n static armForSwitch(aSwitch) {\n const member = this._switches.get(aSwitch);\n if (member !== undefined) {\n return member;\n }\n if (this._defaultArm) {\n return this._defaultArm;\n }\n throw new TypeError(`Bad union switch: ${aSwitch}`);\n }\n\n static armTypeForArm(arm) {\n if (arm === Void) {\n return Void;\n }\n return this._arms[arm];\n }\n\n /**\n * @inheritDoc\n */\n static read(reader) {\n const aSwitch = this._switchOn.read(reader);\n const arm = this.armForSwitch(aSwitch);\n const armType = arm === Void ? Void : this._arms[arm];\n let value;\n if (armType !== undefined) {\n value = armType.read(reader);\n } else {\n value = arm.read(reader);\n }\n return new this(aSwitch, value);\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (!this.isValid(value)) {\n throw new XdrWriterError(\n `${value} has union name ${value?.unionName}, not ${\n this.unionName\n }: ${JSON.stringify(value)}`\n );\n }\n\n this._switchOn.write(value.switch(), writer);\n value.armType().write(value.value(), writer);\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n return (\n value?.constructor?.unionName === this.unionName ||\n isSerializableIsh(value, this)\n );\n }\n\n static create(context, name, config) {\n const ChildUnion = class extends Union {};\n\n ChildUnion.unionName = name;\n context.results[name] = ChildUnion;\n\n if (config.switchOn instanceof Reference) {\n ChildUnion._switchOn = config.switchOn.resolve(context);\n } else {\n ChildUnion._switchOn = config.switchOn;\n }\n\n ChildUnion._switches = new Map();\n ChildUnion._arms = {};\n\n // resolve default arm\n let defaultArm = config.defaultArm;\n if (defaultArm instanceof Reference) {\n defaultArm = defaultArm.resolve(context);\n }\n\n ChildUnion._defaultArm = defaultArm;\n\n for (const [aSwitch, armName] of config.switches) {\n const key =\n typeof aSwitch === 'string'\n ? ChildUnion._switchOn.fromName(aSwitch)\n : aSwitch;\n\n ChildUnion._switches.set(key, armName);\n }\n\n // add enum-based helpers\n // NOTE: we don't have good notation for \"is a subclass of XDR.Enum\",\n // and so we use the following check (does _switchOn have a `values`\n // attribute) to approximate the intent.\n if (ChildUnion._switchOn.values !== undefined) {\n for (const aSwitch of ChildUnion._switchOn.values()) {\n // Add enum-based constructors\n ChildUnion[aSwitch.name] = function ctr(value) {\n return new ChildUnion(aSwitch, value);\n };\n\n // Add enum-based \"set\" helpers\n ChildUnion.prototype[aSwitch.name] = function set(value) {\n return this.set(aSwitch, value);\n };\n }\n }\n\n if (config.arms) {\n for (const [armsName, value] of Object.entries(config.arms)) {\n ChildUnion._arms[armsName] =\n value instanceof Reference ? value.resolve(context) : value;\n // Add arm accessor helpers\n if (value !== Void) {\n ChildUnion.prototype[armsName] = function get() {\n return this.get(armsName);\n };\n }\n }\n }\n\n return ChildUnion;\n }\n}\n","// eslint-disable-next-line max-classes-per-file\nimport * as XDRTypes from './types';\nimport { Reference } from './reference';\nimport { XdrDefinitionError } from './errors';\n\nexport * from './reference';\n\nclass SimpleReference extends Reference {\n constructor(name) {\n super();\n this.name = name;\n }\n\n resolve(context) {\n const defn = context.definitions[this.name];\n return defn.resolve(context);\n }\n}\n\nclass ArrayReference extends Reference {\n constructor(childReference, length, variable = false) {\n super();\n this.childReference = childReference;\n this.length = length;\n this.variable = variable;\n }\n\n resolve(context) {\n let resolvedChild = this.childReference;\n let length = this.length;\n\n if (resolvedChild instanceof Reference) {\n resolvedChild = resolvedChild.resolve(context);\n }\n\n if (length instanceof Reference) {\n length = length.resolve(context);\n }\n\n if (this.variable) {\n return new XDRTypes.VarArray(resolvedChild, length);\n }\n return new XDRTypes.Array(resolvedChild, length);\n }\n}\n\nclass OptionReference extends Reference {\n constructor(childReference) {\n super();\n this.childReference = childReference;\n this.name = childReference.name;\n }\n\n resolve(context) {\n let resolvedChild = this.childReference;\n\n if (resolvedChild instanceof Reference) {\n resolvedChild = resolvedChild.resolve(context);\n }\n\n return new XDRTypes.Option(resolvedChild);\n }\n}\n\nclass SizedReference extends Reference {\n constructor(sizedType, length) {\n super();\n this.sizedType = sizedType;\n this.length = length;\n }\n\n resolve(context) {\n let length = this.length;\n\n if (length instanceof Reference) {\n length = length.resolve(context);\n }\n\n return new this.sizedType(length);\n }\n}\n\nclass Definition {\n constructor(constructor, name, cfg) {\n this.constructor = constructor;\n this.name = name;\n this.config = cfg;\n }\n\n // resolve calls the constructor of this definition with the provided context\n // and this definitions config values. The definitions constructor should\n // populate the final type on `context.results`, and may refer to other\n // definitions through `context.definitions`\n resolve(context) {\n if (this.name in context.results) {\n return context.results[this.name];\n }\n\n return this.constructor(context, this.name, this.config);\n }\n}\n\n// let the reference resolution system do its thing\n// the \"constructor\" for a typedef just returns the resolved value\nfunction createTypedef(context, typeName, value) {\n if (value instanceof Reference) {\n value = value.resolve(context);\n }\n context.results[typeName] = value;\n return value;\n}\n\nfunction createConst(context, name, value) {\n context.results[name] = value;\n return value;\n}\n\nclass TypeBuilder {\n constructor(destination) {\n this._destination = destination;\n this._definitions = {};\n }\n\n enum(name, members) {\n const result = new Definition(XDRTypes.Enum.create, name, members);\n this.define(name, result);\n }\n\n struct(name, members) {\n const result = new Definition(XDRTypes.Struct.create, name, members);\n this.define(name, result);\n }\n\n union(name, cfg) {\n const result = new Definition(XDRTypes.Union.create, name, cfg);\n this.define(name, result);\n }\n\n typedef(name, cfg) {\n const result = new Definition(createTypedef, name, cfg);\n this.define(name, result);\n }\n\n const(name, cfg) {\n const result = new Definition(createConst, name, cfg);\n this.define(name, result);\n }\n\n void() {\n return XDRTypes.Void;\n }\n\n bool() {\n return XDRTypes.Bool;\n }\n\n int() {\n return XDRTypes.Int;\n }\n\n hyper() {\n return XDRTypes.Hyper;\n }\n\n uint() {\n return XDRTypes.UnsignedInt;\n }\n\n uhyper() {\n return XDRTypes.UnsignedHyper;\n }\n\n float() {\n return XDRTypes.Float;\n }\n\n double() {\n return XDRTypes.Double;\n }\n\n quadruple() {\n return XDRTypes.Quadruple;\n }\n\n string(length) {\n return new SizedReference(XDRTypes.String, length);\n }\n\n opaque(length) {\n return new SizedReference(XDRTypes.Opaque, length);\n }\n\n varOpaque(length) {\n return new SizedReference(XDRTypes.VarOpaque, length);\n }\n\n array(childType, length) {\n return new ArrayReference(childType, length);\n }\n\n varArray(childType, maxLength) {\n return new ArrayReference(childType, maxLength, true);\n }\n\n option(childType) {\n return new OptionReference(childType);\n }\n\n define(name, definition) {\n if (this._destination[name] === undefined) {\n this._definitions[name] = definition;\n } else {\n throw new XdrDefinitionError(`${name} is already defined`);\n }\n }\n\n lookup(name) {\n return new SimpleReference(name);\n }\n\n resolve() {\n for (const defn of Object.values(this._definitions)) {\n defn.resolve({\n definitions: this._definitions,\n results: this._destination\n });\n }\n }\n}\n\nexport function config(fn, types = {}) {\n if (fn) {\n const builder = new TypeBuilder(types);\n fn(builder);\n builder.resolve();\n }\n\n return types;\n}\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nconst base64 = require('base64-js')\nconst ieee754 = require('ieee754')\nconst customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nconst K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n const arr = new Uint8Array(1)\n const proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n const buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n const valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n const b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n const length = byteLength(string, encoding) | 0\n let buf = createBuffer(length)\n\n const actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n const length = array.length < 0 ? 0 : checked(array.length) | 0\n const buf = createBuffer(length)\n for (let i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n const copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n let buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n const len = checked(obj.length) | 0\n const buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n let x = a.length\n let y = b.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n let i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n const buffer = Buffer.allocUnsafe(length)\n let pos = 0\n for (i = 0; i < list.length; ++i) {\n let buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n buf.copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n const len = string.length\n const mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n let loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n const i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n const len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (let i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n const len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (let i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n const len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (let i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n const length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n let str = ''\n const max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n let x = thisEnd - thisStart\n let y = end - start\n const len = Math.min(x, y)\n\n const thisCopy = this.slice(thisStart, thisEnd)\n const targetCopy = target.slice(start, end)\n\n for (let i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n let indexSize = 1\n let arrLength = arr.length\n let valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n let i\n if (dir) {\n let foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n let found = true\n for (let j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n const remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n const strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n let i\n for (i = 0; i < length; ++i) {\n const parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n const remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n const res = []\n\n let i = start\n while (i < end) {\n const firstByte = buf[i]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n const len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n let out = ''\n for (let i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n const bytes = buf.slice(start, end)\n let res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (let i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n const len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n const newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n let val = this[offset + --byteLength]\n let mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const lo = first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24\n\n const hi = this[++offset] +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n last * 2 ** 24\n\n return BigInt(lo) + (BigInt(hi) << BigInt(32))\n})\n\nBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const hi = first * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n const lo = this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last\n\n return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n})\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let i = byteLength\n let mul = 1\n let val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = this[offset + 4] +\n this[offset + 5] * 2 ** 8 +\n this[offset + 6] * 2 ** 16 +\n (last << 24) // Overflow\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24)\n})\n\nBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = (first << 24) + // Overflow\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last)\n})\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let mul = 1\n let i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let i = byteLength - 1\n let mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n return offset\n}\n\nfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset + 7] = lo\n lo = lo >> 8\n buf[offset + 6] = lo\n lo = lo >> 8\n buf[offset + 5] = lo\n lo = lo >> 8\n buf[offset + 4] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset + 3] = hi\n hi = hi >> 8\n buf[offset + 2] = hi\n hi = hi >> 8\n buf[offset + 1] = hi\n hi = hi >> 8\n buf[offset] = hi\n return offset + 8\n}\n\nBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = 0\n let mul = 1\n let sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = byteLength - 1\n let mul = 1\n let sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n const len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n const code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n let i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n const bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n const len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// CUSTOM ERRORS\n// =============\n\n// Simplified versions from Node, changed for Buffer-only usage\nconst errors = {}\nfunction E (sym, getMessage, Base) {\n errors[sym] = class NodeError extends Base {\n constructor () {\n super()\n\n Object.defineProperty(this, 'message', {\n value: getMessage.apply(this, arguments),\n writable: true,\n configurable: true\n })\n\n // Add the error code to the name to include it in the stack trace.\n this.name = `${this.name} [${sym}]`\n // Access the stack to generate the error message including the error code\n // from the name.\n this.stack // eslint-disable-line no-unused-expressions\n // Reset the name to the actual name.\n delete this.name\n }\n\n get code () {\n return sym\n }\n\n set code (value) {\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n value,\n writable: true\n })\n }\n\n toString () {\n return `${this.name} [${sym}]: ${this.message}`\n }\n }\n}\n\nE('ERR_BUFFER_OUT_OF_BOUNDS',\n function (name) {\n if (name) {\n return `${name} is outside of buffer bounds`\n }\n\n return 'Attempt to access memory outside buffer bounds'\n }, RangeError)\nE('ERR_INVALID_ARG_TYPE',\n function (name, actual) {\n return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n }, TypeError)\nE('ERR_OUT_OF_RANGE',\n function (str, range, input) {\n let msg = `The value of \"${str}\" is out of range.`\n let received = input\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n }\n msg += ` It must be ${range}. Received ${received}`\n return msg\n }, RangeError)\n\nfunction addNumericalSeparator (val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\n\n// CHECK FUNCTIONS\n// ===============\n\nfunction checkBounds (buf, offset, byteLength) {\n validateNumber(offset, 'offset')\n if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n boundsError(offset, buf.length - (byteLength + 1))\n }\n}\n\nfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n if (value > max || value < min) {\n const n = typeof min === 'bigint' ? 'n' : ''\n let range\n if (byteLength > 3) {\n if (min === 0 || min === BigInt(0)) {\n range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`\n } else {\n range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n `${(byteLength + 1) * 8 - 1}${n}`\n }\n } else {\n range = `>= ${min}${n} and <= ${max}${n}`\n }\n throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n }\n checkBounds(buf, offset, byteLength)\n}\n\nfunction validateNumber (value, name) {\n if (typeof value !== 'number') {\n throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n}\n\nfunction boundsError (value, length, type) {\n if (Math.floor(value) !== value) {\n validateNumber(value, type)\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)\n }\n\n if (length < 0) {\n throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n }\n\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset',\n `>= ${type ? 1 : 0} and <= ${length}`,\n value)\n}\n\n// HELPER FUNCTIONS\n// ================\n\nconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n let codePoint\n const length = string.length\n let leadSurrogate = null\n const bytes = []\n\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n let c, hi, lo\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n let i\n for (i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nconst hexSliceLookupTable = (function () {\n const alphabet = '0123456789abcdef'\n const table = new Array(256)\n for (let i = 0; i < 16; ++i) {\n const i16 = i * 16\n for (let j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n\n// Return not function with Error if BigInt not supported\nfunction defineBigIntMethod (fn) {\n return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n}\n\nfunction BufferBigIntNotDefined () {\n throw new Error('BigInt not supported')\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(281);\n"],"names":["root","factory","exports","module","define","amd","this","Buffer","alloc","subarray","prototype","start","end","result","Uint8Array","call","Object","setPrototypeOf","require","XdrWriterError","TypeError","constructor","message","super","XdrReaderError","XdrDefinitionError","XdrNotImplementedDefinitionError","XdrReader","source","isBuffer","Array","isArray","ArrayBuffer","isView","from","_buffer","_length","length","_index","eof","advance","size","padding","i","rewind","read","readInt32BE","readUInt32BE","readBigInt64BE","readBigUInt64BE","readFloatBE","readDoubleBE","ensureInputConsumed","BUFFER_CHUNK","XdrWriter","buffer","allocUnsafe","resize","minRequiredSize","newLength","Math","ceil","newBuffer","copy","finalize","toArray","write","value","offset","fill","writeInt32BE","writeUInt32BE","writeBigInt64BE","writeBigUInt64BE","writeFloatBE","writeDoubleBE","static","XdrType","toXDR","format","writer","encodeResult","fromXDR","input","reader","decodeInput","validateXDR","e","XdrPrimitiveType","isValid","XdrCompositeType","InvalidXdrEncodingFormatError","toString","isSerializableIsh","subtype","hasConstructor","instance","name","getPrototypeOf","MAX_VALUE","MIN_VALUE","Int","sliceBigInt","iSize","sliceSize","total","shift","BigInt","asIntN","calculateBigIntBoundaries","unsigned","boundary","LargeInt","args","_value","parts","RangeError","valueOf","asUintN","min","max","precision","formatIntName","encodeBigIntFromBits","slice","toJSON","toBigInt","reverse","part","fromString","string","defineIntBoundaries","Hyper","low","Number","high","fromBits","UnsignedInt","UnsignedHyper","Float","Double","Quadruple","Bool","intVal","String","maxLength","_maxLength","readString","byteLength","Opaque","VarOpaque","childType","_childType","global","child","VarArray","Option","isPresent","Void","undefined","Enum","res","_byValue","enumName","JSON","stringify","members","_members","values","fromName","fromValue","create","context","ChildEnum","results","key","entries","inst","Reference","resolve","Struct","attributes","_attributes","fieldName","type","_fields","structName","attribute","fields","ChildStruct","mappedFields","fieldDescriptor","field","createAccessorMethod","Union","aSwitch","set","_switchOn","_switch","arm","armForSwitch","_arm","_armType","_arms","get","armName","switch","armType","member","_switches","_defaultArm","armTypeForArm","unionName","config","ChildUnion","switchOn","Map","defaultArm","switches","arms","armsName","SimpleReference","definitions","ArrayReference","childReference","variable","resolvedChild","XDRTypes","OptionReference","SizedReference","sizedType","Definition","cfg","createTypedef","typeName","createConst","TypeBuilder","destination","_destination","_definitions","enum","struct","union","typedef","const","void","bool","int","hyper","uint","uhyper","float","double","quadruple","opaque","varOpaque","array","varArray","option","definition","lookup","defn","fn","types","builder","b64","lens","getLens","validLen","placeHoldersLen","toByteArray","tmp","arr","Arr","_byteLength","curByte","len","revLookup","charCodeAt","fromByteArray","uint8","extraBytes","maxChunkLength","len2","push","encodeChunk","join","code","Error","indexOf","num","output","base64","ieee754","customInspectSymbol","Symbol","K_MAX_LENGTH","createBuffer","buf","arg","encodingOrOffset","encoding","isEncoding","actual","arrayView","isInstance","fromArrayBuffer","byteOffset","fromArrayLike","fromArrayView","SharedArrayBuffer","b","obj","checked","numberIsNaN","data","fromObject","toPrimitive","assertSize","mustMatch","arguments","loweredCase","utf8ToBytes","base64ToBytes","toLowerCase","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","n","m","bidirectionalIndexOf","val","dir","arrayIndexOf","lastIndexOf","indexSize","arrLength","valLength","readUInt16BE","foundIndex","found","j","hexWrite","remaining","strLen","parsed","parseInt","substr","utf8Write","blitBuffer","asciiWrite","str","byteArray","asciiToBytes","base64Write","ucs2Write","units","c","hi","lo","utf16leToBytes","firstByte","codePoint","bytesPerSequence","secondByte","thirdByte","fourthByte","tempCodePoint","codePoints","MAX_ARGUMENTS_LENGTH","fromCharCode","apply","decodeCodePointsArray","TYPED_ARRAY_SUPPORT","proto","foo","typedArraySupport","console","error","defineProperty","enumerable","poolSize","allocUnsafeSlow","_isBuffer","compare","a","x","y","concat","list","pos","swap16","swap32","swap64","toLocaleString","equals","inspect","replace","trim","target","thisStart","thisEnd","thisCopy","targetCopy","includes","isFinite","_arr","ret","out","hexSliceLookupTable","bytes","checkOffset","ext","checkInt","wrtBigUInt64LE","checkIntBI","wrtBigUInt64BE","checkIEEE754","writeFloat","littleEndian","noAssert","writeDouble","newBuf","readUintLE","readUIntLE","mul","readUintBE","readUIntBE","readUint8","readUInt8","readUint16LE","readUInt16LE","readUint16BE","readUint32LE","readUInt32LE","readUint32BE","readBigUInt64LE","defineBigIntMethod","validateNumber","first","last","boundsError","readIntLE","pow","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readBigInt64LE","readFloatLE","readDoubleLE","writeUintLE","writeUIntLE","writeUintBE","writeUIntBE","writeUint8","writeUInt8","writeUint16LE","writeUInt16LE","writeUint16BE","writeUInt16BE","writeUint32LE","writeUInt32LE","writeUint32BE","writeBigUInt64LE","writeIntLE","limit","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeBigInt64LE","writeFloatLE","writeDoubleLE","targetStart","copyWithin","errors","E","sym","getMessage","Base","writable","configurable","stack","addNumericalSeparator","range","ERR_OUT_OF_RANGE","checkBounds","ERR_INVALID_ARG_TYPE","floor","ERR_BUFFER_OUT_OF_BOUNDS","msg","received","isInteger","abs","INVALID_BASE64_RE","Infinity","leadSurrogate","split","base64clean","src","dst","alphabet","table","i16","BufferBigIntNotDefined","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","d","s","NaN","rt","isNaN","log","LN2","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","o","g","globalThis","Function","window","prop","hasOwnProperty","r","toStringTag"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/@stellar/js-xdr/examples/enum.js b/node_modules/@stellar/js-xdr/examples/enum.js new file mode 100644 index 000000000..972976520 --- /dev/null +++ b/node_modules/@stellar/js-xdr/examples/enum.js @@ -0,0 +1,27 @@ +import * as XDR from '../src'; + +let xdr = XDR.config((xdr) => { + xdr.enum('Color', { + red: 0, + green: 1, + blue: 2 + }); + + xdr.enum('ResultType', { + ok: 0, + error: 1 + }); +}); + +console.log(xdr); + +// +console.log(xdr.Color.members()); // { red: 0, green: 1, blue: 2, } + +console.log(xdr.Color.fromName('red')); + +console.log(xdr.Color.fromXDR(Buffer.from([0, 0, 0, 0]))); // Color.red +console.log(xdr.Color.red().toXDR()); // Buffer +console.log(xdr.Color.red().toXDR('hex')); // + +console.log(xdr.Color.red() !== xdr.ResultType.ok()); diff --git a/node_modules/@stellar/js-xdr/examples/linked_list.js b/node_modules/@stellar/js-xdr/examples/linked_list.js new file mode 100644 index 000000000..512a22456 --- /dev/null +++ b/node_modules/@stellar/js-xdr/examples/linked_list.js @@ -0,0 +1,13 @@ +import * as XDR from '../src'; + +let xdr = XDR.config((xdr) => { + xdr.struct('IntList', [ + ['value', xdr.int()], + ['rest', xdr.option(xdr.lookup('IntList'))] + ]); +}); + +let n1 = new xdr.IntList({ value: 1 }); +let n2 = new xdr.IntList({ value: 3, rest: n1 }); + +console.log(n2.toXDR()); diff --git a/node_modules/@stellar/js-xdr/examples/struct.js b/node_modules/@stellar/js-xdr/examples/struct.js new file mode 100644 index 000000000..9349e2a27 --- /dev/null +++ b/node_modules/@stellar/js-xdr/examples/struct.js @@ -0,0 +1,30 @@ +import * as XDR from '../src'; + +let xdr = XDR.config((xdr) => { + xdr.struct('Signature', [ + ['publicKey', xdr.opaque(32)], + ['data', xdr.opaque(32)] + ]); + + xdr.struct('Envelope', [ + ['body', xdr.varOpaque(1000)], + ['timestamp', xdr.uint()], + ['signature', xdr.lookup('Signature')] + ]); +}); + +let sig = new xdr.Signature(); +sig.publicKey(Buffer.alloc(32)); +sig.data(Buffer.from('00000000000000000000000000000000')); + +let env = new xdr.Envelope({ + signature: sig, + body: Buffer.from('hello'), + timestamp: Math.floor(new Date() / 1000) +}); + +let output = env.toXDR(); +let parsed = xdr.Envelope.fromXDR(output); + +console.log(env); +console.log(parsed); diff --git a/node_modules/@stellar/js-xdr/examples/test.x b/node_modules/@stellar/js-xdr/examples/test.x new file mode 100644 index 000000000..b54ed8b80 --- /dev/null +++ b/node_modules/@stellar/js-xdr/examples/test.x @@ -0,0 +1,164 @@ +const HASH_SIZE = 32; + +typedef opaque Signature[32]; + +enum ResultType +{ + OK = 0, + ERROR = 1 +}; + +union Result switch(ResultType type) +{ + case OK: + void; + case ERROR: + int code; +}; + +typedef unsigned int ColorCode; + +struct Color +{ + ColorCode red; + ColorCode green; + ColorCode blue; +}; + + +struct Exhaustive +{ + + // Bools + bool aBool; + bool* anOptionalBool; + bool aBoolArray[5]; + bool aBoolVarArray<5>; + bool anUnboundedBoolVarArray<>; + + // Ints + int anInt; + int* anOptionalInt; + int anIntArray[5]; + int anIntVarArray<5>; + int anUnboundedIntVarArray<>; + + // Uints + unsigned int anUnsignedInt; + unsigned int* anOptionalUnsignedInt; + unsigned int anUnsignedIntArray[5]; + unsigned int anUnsignedIntVarArray<5>; + unsigned int anUnboundedUnsignedIntVarArray<>; + + // Hypers + hyper aHyper; + hyper* anOptionalHyper; + hyper aHyperArray[5]; + hyper aHyperVarArray<5>; + hyper anUnboundedHyperVarArray<>; + + // Uhypers + unsigned hyper anUnsignedHyper; + unsigned hyper* anOptionalUnsignedHyper; + unsigned hyper anUnsignedHyperArray[5]; + unsigned hyper anUnsignedHyperVarArray<5>; + unsigned hyper anUnboundedUnsignedHyperVarArray<>; + + // Floats + float aFloat; + float* anOptionalFloat; + float aFloatArray[5]; + float aFloatVarArray<5>; + float anUnboundedFloatVarArray<>; + + + // Doubles + double aDouble; + double* anOptionalDouble; + double aDoubleArray[5]; + double aDoubleVarArray<5>; + double anUnboundedDoubleVarArray<>; + + + // Opaque + opaque anOpaque[10]; + + // VarOpaque + opaque aVarOpaque<10>; + opaque anUnboundedVarOpaque<>; + + // String + string aString<19>; + string anUnboundedString<>; + + + // Typedef + Signature aSignature; + Signature* anOptionalSignature; + Signature aSignatureArray[5]; + Signature aSignatureVarArray<5>; + Signature anUnboundedSignatureVarArray<>; + + // Enum + ResultType aResultType; + ResultType* anOptionalResultType; + ResultType aResultTypeArray[5]; + ResultType aResultTypeVarArray<5>; + ResultType anUnboundedResultTypeVarArray<>; + + + // Struct + Color aColor; + Color* anOptionalColor; + Color aColorArray[5]; + Color aColorVarArray<5>; + Color anUnboundedColorVarArray<>; + + // Union + Result aResult; + Result* anOptionalResult; + Result aResultArray[5]; + Result aResultVarArray<5>; + Result anUnboundedResultVarArray<>; + + //Nested enum + enum { OK = 0 } aNestedEnum; + enum { OK = 0 } *anOptionalNestedEnum; + enum { OK = 0 } aNestedEnumArray[3]; + enum { OK = 0 } aNestedEnumVarArray<3>; + enum { OK = 0 } anUnboundedNestedEnumVarArray<>; + + //Nested Struct + struct { int value; } aNestedStruct; + struct { int value; } *anOptionalNestedStruct; + struct { int value; } aNestedStructArray[3]; + struct { int value; } aNestedStructVarArray<3>; + struct { int value; } anUnboundedNestedStructVarArray<>; + +}; + +enum ExhaustiveUnionType { + VOID_ARM = 0, + + PRIMITIVE_SIMPLE_ARM = 1, + PRIMITIVE_OPTIONAL_ARM = 2, + PRIMITIVE_ARRAY_ARM = 2, + PRIMITIVE_VARARRAY_ARM = 3, + + CUSTOM_SIMPLE_ARM = 4, + CUSTOM_OPTIONAL_ARM = 5, + CUSTOM_ARRAY_ARM = 6, + CUSTOM_VARARRAY_ARM = 7, + + FOR_DEFAULT = -1 +}; + + +union ExhaustiveUnion switch(ExhaustiveUnionType type) +{ + case VOID_ARM: void; + case PRIMITIVE_SIMPLE_ARM: int aPrimitiveSimpleArm; + case PRIMITIVE_OPTIONAL_ARM: int* aPrimitiveOptionalArm; + + default: int aPrimitiveDefault; +}; \ No newline at end of file diff --git a/node_modules/@stellar/js-xdr/examples/typedef.js b/node_modules/@stellar/js-xdr/examples/typedef.js new file mode 100644 index 000000000..5c05f7361 --- /dev/null +++ b/node_modules/@stellar/js-xdr/examples/typedef.js @@ -0,0 +1,14 @@ +import * as XDR from '../src'; + +let xdr = XDR.config((xdr) => { + xdr.struct('Signature', [ + ['publicKey', xdr.opaque(32)], + ['data', xdr.opaque(32)] + ]); + + xdr.typedef('SignatureTypedef', xdr.lookup('Signature')); + xdr.typedef('IntTypedef', xdr.int()); +}); + +console.log(xdr.SignatureTypedef === xdr.Signature); +console.log(xdr.IntTypedef === XDR.Int); diff --git a/node_modules/@stellar/js-xdr/examples/union.js b/node_modules/@stellar/js-xdr/examples/union.js new file mode 100644 index 000000000..8beb6a81a --- /dev/null +++ b/node_modules/@stellar/js-xdr/examples/union.js @@ -0,0 +1,39 @@ +import * as XDR from '../src'; + +let xdr = XDR.config((xdr) => { + xdr.union('Result', { + switchOn: xdr.lookup('ResultType'), + switches: [ + ['ok', xdr.void()], + ['error', 'message'] + ], + // defaultArm: xdr.void(), + arms: { + message: xdr.string(100) + } + }); + + xdr.enum('ResultType', { + ok: 0, + error: 1, + nonsense: 2 + }); +}); + +let r = xdr.Result.ok(); +r.set('error', 'this is an error'); +r.message(); // => "this is an error" +r.get('message'); // => "this is an error" + +r.set(xdr.ResultType.ok()); +r.get(); // => undefined + +// r.set("nonsense"); +r.get(); // => undefined + +let output = r.toXDR(); +let parsed = xdr.Result.fromXDR(output); + +console.log(r); +console.log(r.arm()); +console.log(parsed); diff --git a/node_modules/@stellar/js-xdr/karma.conf.js b/node_modules/@stellar/js-xdr/karma.conf.js new file mode 100644 index 000000000..b5f2a29b7 --- /dev/null +++ b/node_modules/@stellar/js-xdr/karma.conf.js @@ -0,0 +1,37 @@ +const webpack = require('webpack'); + +module.exports = function (config) { + config.set({ + frameworks: ['mocha', 'webpack', 'sinon-chai'], + browsers: ['FirefoxHeadless', 'ChromeHeadless'], + browserNoActivityTimeout: 20000, + + files: ['dist/xdr.js', 'test/unit/**/*.js'], + + preprocessors: { + 'test/unit/**/*.js': ['webpack'] + }, + + webpack: { + mode: 'development', + module: { + rules: [ + { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' } + ] + }, + plugins: [ + new webpack.ProvidePlugin({ + Buffer: ['buffer', 'Buffer'] + }) + ] + }, + + webpackMiddleware: { + noInfo: true + }, + + singleRun: true, + + reporters: ['dots'] + }); +}; diff --git a/node_modules/@stellar/js-xdr/lib/xdr.js b/node_modules/@stellar/js-xdr/lib/xdr.js new file mode 100644 index 000000000..90798065a --- /dev/null +++ b/node_modules/@stellar/js-xdr/lib/xdr.js @@ -0,0 +1,2391 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["XDR"] = factory(); + else + root["XDR"] = factory(); +})(this, () => { +return /******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ "./src/array.js": +/*!**********************!*\ + !*** ./src/array.js ***! + \**********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Array: () => (/* binding */ Array) +/* harmony export */ }); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + +class Array extends _xdr_type__WEBPACK_IMPORTED_MODULE_0__.XdrCompositeType { + constructor(childType, length) { + super(); + this._childType = childType; + this._length = length; + } + + /** + * @inheritDoc + */ + read(reader) { + // allocate array of specified length + const result = new global.Array(this._length); + // read values + for (let i = 0; i < this._length; i++) { + result[i] = this._childType.read(reader); + } + return result; + } + + /** + * @inheritDoc + */ + write(value, writer) { + if (!global.Array.isArray(value)) throw new _errors__WEBPACK_IMPORTED_MODULE_1__.XdrWriterError(`value is not array`); + if (value.length !== this._length) throw new _errors__WEBPACK_IMPORTED_MODULE_1__.XdrWriterError(`got array of size ${value.length}, expected ${this._length}`); + for (const child of value) { + this._childType.write(child, writer); + } + } + + /** + * @inheritDoc + */ + isValid(value) { + if (!(value instanceof global.Array) || value.length !== this._length) { + return false; + } + for (const child of value) { + if (!this._childType.isValid(child)) return false; + } + return true; + } +} + +/***/ }), + +/***/ "./src/bigint-encoder.js": +/*!*******************************!*\ + !*** ./src/bigint-encoder.js ***! + \*******************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ calculateBigIntBoundaries: () => (/* binding */ calculateBigIntBoundaries), +/* harmony export */ encodeBigIntFromBits: () => (/* binding */ encodeBigIntFromBits), +/* harmony export */ formatIntName: () => (/* binding */ formatIntName), +/* harmony export */ sliceBigInt: () => (/* binding */ sliceBigInt) +/* harmony export */ }); +/** + * Encode a native `bigint` value from a list of arbitrary integer-like values. + * + * @param {Array} parts - Slices to encode in big-endian + * format (i.e. earlier elements are higher bits) + * @param {64|128|256} size - Number of bits in the target integer type + * @param {boolean} unsigned - Whether it's an unsigned integer + * + * @returns {bigint} + */ +function encodeBigIntFromBits(parts, size, unsigned) { + if (!(parts instanceof Array)) { + // allow a single parameter instead of an array + parts = [parts]; + } else if (parts.length && parts[0] instanceof Array) { + // unpack nested array param + parts = parts[0]; + } + const total = parts.length; + const sliceSize = size / total; + switch (sliceSize) { + case 32: + case 64: + case 128: + case 256: + break; + default: + throw new RangeError(`expected slices to fit in 32/64/128/256 bits, got ${parts}`); + } + + // normalize all inputs to bigint + try { + for (let i = 0; i < parts.length; i++) { + if (typeof parts[i] !== 'bigint') { + parts[i] = BigInt(parts[i].valueOf()); + } + } + } catch (e) { + throw new TypeError(`expected bigint-like values, got: ${parts} (${e})`); + } + + // check for sign mismatches for single inputs (this is a special case to + // handle one parameter passed to e.g. UnsignedHyper et al.) + // see https://github.com/stellar/js-xdr/pull/100#discussion_r1228770845 + if (unsigned && parts.length === 1 && parts[0] < 0n) { + throw new RangeError(`expected a positive value, got: ${parts}`); + } + + // encode in big-endian fashion, shifting each slice by the slice size + let result = BigInt.asUintN(sliceSize, parts[0]); // safe: len >= 1 + for (let i = 1; i < parts.length; i++) { + result |= BigInt.asUintN(sliceSize, parts[i]) << BigInt(i * sliceSize); + } + + // interpret value as signed if necessary and clamp it + if (!unsigned) { + result = BigInt.asIntN(size, result); + } + + // check boundaries + const [min, max] = calculateBigIntBoundaries(size, unsigned); + if (result >= min && result <= max) { + return result; + } + + // failed to encode + throw new TypeError(`bigint values [${parts}] for ${formatIntName(size, unsigned)} out of range [${min}, ${max}]: ${result}`); +} + +/** + * Transforms a single bigint value that's supposed to represent a `size`-bit + * integer into a list of `sliceSize`d chunks. + * + * @param {bigint} value - Single bigint value to decompose + * @param {64|128|256} iSize - Number of bits represented by `value` + * @param {32|64|128} sliceSize - Number of chunks to decompose into + * @return {bigint[]} + */ +function sliceBigInt(value, iSize, sliceSize) { + if (typeof value !== 'bigint') { + throw new TypeError(`Expected bigint 'value', got ${typeof value}`); + } + const total = iSize / sliceSize; + if (total === 1) { + return [value]; + } + if (sliceSize < 32 || sliceSize > 128 || total !== 2 && total !== 4 && total !== 8) { + throw new TypeError(`invalid bigint (${value}) and slice size (${iSize} -> ${sliceSize}) combination`); + } + const shift = BigInt(sliceSize); + + // iterate shift and mask application + const result = new Array(total); + for (let i = 0; i < total; i++) { + // we force a signed interpretation to preserve sign in each slice value, + // but downstream can convert to unsigned if it's appropriate + result[i] = BigInt.asIntN(sliceSize, value); // clamps to size + + // move on to the next chunk + value >>= shift; + } + return result; +} +function formatIntName(precision, unsigned) { + return `${unsigned ? 'u' : 'i'}${precision}`; +} + +/** + * Get min|max boundaries for an integer with a specified bits size + * @param {64|128|256} size - Number of bits in the source integer type + * @param {Boolean} unsigned - Whether it's an unsigned integer + * @return {BigInt[]} + */ +function calculateBigIntBoundaries(size, unsigned) { + if (unsigned) { + return [0n, (1n << BigInt(size)) - 1n]; + } + const boundary = 1n << BigInt(size - 1); + return [0n - boundary, boundary - 1n]; +} + +/***/ }), + +/***/ "./src/bool.js": +/*!*********************!*\ + !*** ./src/bool.js ***! + \*********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Bool: () => (/* binding */ Bool) +/* harmony export */ }); +/* harmony import */ var _int__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./int */ "./src/int.js"); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + + +class Bool extends _xdr_type__WEBPACK_IMPORTED_MODULE_1__.XdrPrimitiveType { + /** + * @inheritDoc + */ + static read(reader) { + const value = _int__WEBPACK_IMPORTED_MODULE_0__.Int.read(reader); + switch (value) { + case 0: + return false; + case 1: + return true; + default: + throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrReaderError(`got ${value} when trying to read a bool`); + } + } + + /** + * @inheritDoc + */ + static write(value, writer) { + const intVal = value ? 1 : 0; + _int__WEBPACK_IMPORTED_MODULE_0__.Int.write(intVal, writer); + } + + /** + * @inheritDoc + */ + static isValid(value) { + return typeof value === 'boolean'; + } +} + +/***/ }), + +/***/ "./src/browser.js": +/*!************************!*\ + !*** ./src/browser.js ***! + \************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// eslint-disable-next-line prefer-import/prefer-import-over-require +const exports = __webpack_require__(/*! ./index */ "./src/index.js"); +module.exports = exports; + +/***/ }), + +/***/ "./src/config.js": +/*!***********************!*\ + !*** ./src/config.js ***! + \***********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Reference: () => (/* reexport safe */ _reference__WEBPACK_IMPORTED_MODULE_1__.Reference), +/* harmony export */ config: () => (/* binding */ config) +/* harmony export */ }); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./types */ "./src/types.js"); +/* harmony import */ var _reference__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./reference */ "./src/reference.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); +// eslint-disable-next-line max-classes-per-file + + + + +class SimpleReference extends _reference__WEBPACK_IMPORTED_MODULE_1__.Reference { + constructor(name) { + super(); + this.name = name; + } + resolve(context) { + const defn = context.definitions[this.name]; + return defn.resolve(context); + } +} +class ArrayReference extends _reference__WEBPACK_IMPORTED_MODULE_1__.Reference { + constructor(childReference, length, variable = false) { + super(); + this.childReference = childReference; + this.length = length; + this.variable = variable; + } + resolve(context) { + let resolvedChild = this.childReference; + let length = this.length; + if (resolvedChild instanceof _reference__WEBPACK_IMPORTED_MODULE_1__.Reference) { + resolvedChild = resolvedChild.resolve(context); + } + if (length instanceof _reference__WEBPACK_IMPORTED_MODULE_1__.Reference) { + length = length.resolve(context); + } + if (this.variable) { + return new _types__WEBPACK_IMPORTED_MODULE_0__.VarArray(resolvedChild, length); + } + return new _types__WEBPACK_IMPORTED_MODULE_0__.Array(resolvedChild, length); + } +} +class OptionReference extends _reference__WEBPACK_IMPORTED_MODULE_1__.Reference { + constructor(childReference) { + super(); + this.childReference = childReference; + this.name = childReference.name; + } + resolve(context) { + let resolvedChild = this.childReference; + if (resolvedChild instanceof _reference__WEBPACK_IMPORTED_MODULE_1__.Reference) { + resolvedChild = resolvedChild.resolve(context); + } + return new _types__WEBPACK_IMPORTED_MODULE_0__.Option(resolvedChild); + } +} +class SizedReference extends _reference__WEBPACK_IMPORTED_MODULE_1__.Reference { + constructor(sizedType, length) { + super(); + this.sizedType = sizedType; + this.length = length; + } + resolve(context) { + let length = this.length; + if (length instanceof _reference__WEBPACK_IMPORTED_MODULE_1__.Reference) { + length = length.resolve(context); + } + return new this.sizedType(length); + } +} +class Definition { + constructor(constructor, name, cfg) { + this.constructor = constructor; + this.name = name; + this.config = cfg; + } + + // resolve calls the constructor of this definition with the provided context + // and this definitions config values. The definitions constructor should + // populate the final type on `context.results`, and may refer to other + // definitions through `context.definitions` + resolve(context) { + if (this.name in context.results) { + return context.results[this.name]; + } + return this.constructor(context, this.name, this.config); + } +} + +// let the reference resolution system do its thing +// the "constructor" for a typedef just returns the resolved value +function createTypedef(context, typeName, value) { + if (value instanceof _reference__WEBPACK_IMPORTED_MODULE_1__.Reference) { + value = value.resolve(context); + } + context.results[typeName] = value; + return value; +} +function createConst(context, name, value) { + context.results[name] = value; + return value; +} +class TypeBuilder { + constructor(destination) { + this._destination = destination; + this._definitions = {}; + } + enum(name, members) { + const result = new Definition(_types__WEBPACK_IMPORTED_MODULE_0__.Enum.create, name, members); + this.define(name, result); + } + struct(name, members) { + const result = new Definition(_types__WEBPACK_IMPORTED_MODULE_0__.Struct.create, name, members); + this.define(name, result); + } + union(name, cfg) { + const result = new Definition(_types__WEBPACK_IMPORTED_MODULE_0__.Union.create, name, cfg); + this.define(name, result); + } + typedef(name, cfg) { + const result = new Definition(createTypedef, name, cfg); + this.define(name, result); + } + const(name, cfg) { + const result = new Definition(createConst, name, cfg); + this.define(name, result); + } + void() { + return _types__WEBPACK_IMPORTED_MODULE_0__.Void; + } + bool() { + return _types__WEBPACK_IMPORTED_MODULE_0__.Bool; + } + int() { + return _types__WEBPACK_IMPORTED_MODULE_0__.Int; + } + hyper() { + return _types__WEBPACK_IMPORTED_MODULE_0__.Hyper; + } + uint() { + return _types__WEBPACK_IMPORTED_MODULE_0__.UnsignedInt; + } + uhyper() { + return _types__WEBPACK_IMPORTED_MODULE_0__.UnsignedHyper; + } + float() { + return _types__WEBPACK_IMPORTED_MODULE_0__.Float; + } + double() { + return _types__WEBPACK_IMPORTED_MODULE_0__.Double; + } + quadruple() { + return _types__WEBPACK_IMPORTED_MODULE_0__.Quadruple; + } + string(length) { + return new SizedReference(_types__WEBPACK_IMPORTED_MODULE_0__.String, length); + } + opaque(length) { + return new SizedReference(_types__WEBPACK_IMPORTED_MODULE_0__.Opaque, length); + } + varOpaque(length) { + return new SizedReference(_types__WEBPACK_IMPORTED_MODULE_0__.VarOpaque, length); + } + array(childType, length) { + return new ArrayReference(childType, length); + } + varArray(childType, maxLength) { + return new ArrayReference(childType, maxLength, true); + } + option(childType) { + return new OptionReference(childType); + } + define(name, definition) { + if (this._destination[name] === undefined) { + this._definitions[name] = definition; + } else { + throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrDefinitionError(`${name} is already defined`); + } + } + lookup(name) { + return new SimpleReference(name); + } + resolve() { + for (const defn of Object.values(this._definitions)) { + defn.resolve({ + definitions: this._definitions, + results: this._destination + }); + } + } +} +function config(fn, types = {}) { + if (fn) { + const builder = new TypeBuilder(types); + fn(builder); + builder.resolve(); + } + return types; +} + +/***/ }), + +/***/ "./src/double.js": +/*!***********************!*\ + !*** ./src/double.js ***! + \***********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Double: () => (/* binding */ Double) +/* harmony export */ }); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + +class Double extends _xdr_type__WEBPACK_IMPORTED_MODULE_0__.XdrPrimitiveType { + /** + * @inheritDoc + */ + static read(reader) { + return reader.readDoubleBE(); + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (typeof value !== 'number') throw new _errors__WEBPACK_IMPORTED_MODULE_1__.XdrWriterError('not a number'); + writer.writeDoubleBE(value); + } + + /** + * @inheritDoc + */ + static isValid(value) { + return typeof value === 'number'; + } +} + +/***/ }), + +/***/ "./src/enum.js": +/*!*********************!*\ + !*** ./src/enum.js ***! + \*********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Enum: () => (/* binding */ Enum) +/* harmony export */ }); +/* harmony import */ var _int__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./int */ "./src/int.js"); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + + +class Enum extends _xdr_type__WEBPACK_IMPORTED_MODULE_1__.XdrPrimitiveType { + constructor(name, value) { + super(); + this.name = name; + this.value = value; + } + + /** + * @inheritDoc + */ + static read(reader) { + const intVal = _int__WEBPACK_IMPORTED_MODULE_0__.Int.read(reader); + const res = this._byValue[intVal]; + if (res === undefined) throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrReaderError(`unknown ${this.enumName} member for value ${intVal}`); + return res; + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (!this.isValid(value)) { + throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrWriterError(`${value} has enum name ${value?.enumName}, not ${this.enumName}: ${JSON.stringify(value)}`); + } + _int__WEBPACK_IMPORTED_MODULE_0__.Int.write(value.value, writer); + } + + /** + * @inheritDoc + */ + static isValid(value) { + return value?.constructor?.enumName === this.enumName || (0,_xdr_type__WEBPACK_IMPORTED_MODULE_1__.isSerializableIsh)(value, this); + } + static members() { + return this._members; + } + static values() { + return Object.values(this._members); + } + static fromName(name) { + const result = this._members[name]; + if (!result) throw new TypeError(`${name} is not a member of ${this.enumName}`); + return result; + } + static fromValue(value) { + const result = this._byValue[value]; + if (result === undefined) throw new TypeError(`${value} is not a value of any member of ${this.enumName}`); + return result; + } + static create(context, name, members) { + const ChildEnum = class extends Enum {}; + ChildEnum.enumName = name; + context.results[name] = ChildEnum; + ChildEnum._members = {}; + ChildEnum._byValue = {}; + for (const [key, value] of Object.entries(members)) { + const inst = new ChildEnum(key, value); + ChildEnum._members[key] = inst; + ChildEnum._byValue[value] = inst; + ChildEnum[key] = () => inst; + } + return ChildEnum; + } +} + +/***/ }), + +/***/ "./src/errors.js": +/*!***********************!*\ + !*** ./src/errors.js ***! + \***********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ XdrDefinitionError: () => (/* binding */ XdrDefinitionError), +/* harmony export */ XdrNotImplementedDefinitionError: () => (/* binding */ XdrNotImplementedDefinitionError), +/* harmony export */ XdrReaderError: () => (/* binding */ XdrReaderError), +/* harmony export */ XdrWriterError: () => (/* binding */ XdrWriterError) +/* harmony export */ }); +class XdrWriterError extends TypeError { + constructor(message) { + super(`XDR Write Error: ${message}`); + } +} +class XdrReaderError extends TypeError { + constructor(message) { + super(`XDR Read Error: ${message}`); + } +} +class XdrDefinitionError extends TypeError { + constructor(message) { + super(`XDR Type Definition Error: ${message}`); + } +} +class XdrNotImplementedDefinitionError extends XdrDefinitionError { + constructor() { + super(`method not implemented, it should be overloaded in the descendant class.`); + } +} + +/***/ }), + +/***/ "./src/float.js": +/*!**********************!*\ + !*** ./src/float.js ***! + \**********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Float: () => (/* binding */ Float) +/* harmony export */ }); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + +class Float extends _xdr_type__WEBPACK_IMPORTED_MODULE_0__.XdrPrimitiveType { + /** + * @inheritDoc + */ + static read(reader) { + return reader.readFloatBE(); + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (typeof value !== 'number') throw new _errors__WEBPACK_IMPORTED_MODULE_1__.XdrWriterError('not a number'); + writer.writeFloatBE(value); + } + + /** + * @inheritDoc + */ + static isValid(value) { + return typeof value === 'number'; + } +} + +/***/ }), + +/***/ "./src/hyper.js": +/*!**********************!*\ + !*** ./src/hyper.js ***! + \**********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Hyper: () => (/* binding */ Hyper) +/* harmony export */ }); +/* harmony import */ var _large_int__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./large-int */ "./src/large-int.js"); + +class Hyper extends _large_int__WEBPACK_IMPORTED_MODULE_0__.LargeInt { + /** + * @param {Array} parts - Slices to encode + */ + constructor(...args) { + super(args); + } + get low() { + return Number(this._value & 0xffffffffn) << 0; + } + get high() { + return Number(this._value >> 32n) >> 0; + } + get size() { + return 64; + } + get unsigned() { + return false; + } + + /** + * Create Hyper instance from two [high][low] i32 values + * @param {Number} low - Low part of i64 number + * @param {Number} high - High part of i64 number + * @return {LargeInt} + */ + static fromBits(low, high) { + return new this(low, high); + } +} +Hyper.defineIntBoundaries(); + +/***/ }), + +/***/ "./src/index.js": +/*!**********************!*\ + !*** ./src/index.js ***! + \**********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Array: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.Array), +/* harmony export */ Bool: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.Bool), +/* harmony export */ Double: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.Double), +/* harmony export */ Enum: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.Enum), +/* harmony export */ Float: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.Float), +/* harmony export */ Hyper: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.Hyper), +/* harmony export */ Int: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.Int), +/* harmony export */ LargeInt: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.LargeInt), +/* harmony export */ Opaque: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.Opaque), +/* harmony export */ Option: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.Option), +/* harmony export */ Quadruple: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.Quadruple), +/* harmony export */ Reference: () => (/* reexport safe */ _config__WEBPACK_IMPORTED_MODULE_1__.Reference), +/* harmony export */ String: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.String), +/* harmony export */ Struct: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.Struct), +/* harmony export */ Union: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.Union), +/* harmony export */ UnsignedHyper: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.UnsignedHyper), +/* harmony export */ UnsignedInt: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.UnsignedInt), +/* harmony export */ VarArray: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.VarArray), +/* harmony export */ VarOpaque: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.VarOpaque), +/* harmony export */ Void: () => (/* reexport safe */ _types__WEBPACK_IMPORTED_MODULE_0__.Void), +/* harmony export */ XdrReader: () => (/* reexport safe */ _serialization_xdr_reader__WEBPACK_IMPORTED_MODULE_2__.XdrReader), +/* harmony export */ XdrWriter: () => (/* reexport safe */ _serialization_xdr_writer__WEBPACK_IMPORTED_MODULE_3__.XdrWriter), +/* harmony export */ config: () => (/* reexport safe */ _config__WEBPACK_IMPORTED_MODULE_1__.config) +/* harmony export */ }); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./types */ "./src/types.js"); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./config */ "./src/config.js"); +/* harmony import */ var _serialization_xdr_reader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./serialization/xdr-reader */ "./src/serialization/xdr-reader.js"); +/* harmony import */ var _serialization_xdr_writer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./serialization/xdr-writer */ "./src/serialization/xdr-writer.js"); + + + + + +/***/ }), + +/***/ "./src/int.js": +/*!********************!*\ + !*** ./src/int.js ***! + \********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Int: () => (/* binding */ Int) +/* harmony export */ }); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + +const MAX_VALUE = 2147483647; +const MIN_VALUE = -2147483648; +class Int extends _xdr_type__WEBPACK_IMPORTED_MODULE_0__.XdrPrimitiveType { + /** + * @inheritDoc + */ + static read(reader) { + return reader.readInt32BE(); + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (typeof value !== 'number') throw new _errors__WEBPACK_IMPORTED_MODULE_1__.XdrWriterError('not a number'); + if ((value | 0) !== value) throw new _errors__WEBPACK_IMPORTED_MODULE_1__.XdrWriterError('invalid i32 value'); + writer.writeInt32BE(value); + } + + /** + * @inheritDoc + */ + static isValid(value) { + if (typeof value !== 'number' || (value | 0) !== value) { + return false; + } + return value >= MIN_VALUE && value <= MAX_VALUE; + } +} +Int.MAX_VALUE = MAX_VALUE; +Int.MIN_VALUE = -MIN_VALUE; + +/***/ }), + +/***/ "./src/large-int.js": +/*!**************************!*\ + !*** ./src/large-int.js ***! + \**************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ LargeInt: () => (/* binding */ LargeInt) +/* harmony export */ }); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _bigint_encoder__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bigint-encoder */ "./src/bigint-encoder.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + + +class LargeInt extends _xdr_type__WEBPACK_IMPORTED_MODULE_0__.XdrPrimitiveType { + /** + * @param {Array} parts - Slices to encode + */ + constructor(args) { + super(); + this._value = (0,_bigint_encoder__WEBPACK_IMPORTED_MODULE_1__.encodeBigIntFromBits)(args, this.size, this.unsigned); + } + + /** + * Signed/unsigned representation + * @type {Boolean} + * @abstract + */ + get unsigned() { + throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrNotImplementedDefinitionError(); + } + + /** + * Size of the integer in bits + * @type {Number} + * @abstract + */ + get size() { + throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrNotImplementedDefinitionError(); + } + + /** + * Slice integer to parts with smaller bit size + * @param {32|64|128} sliceSize - Size of each part in bits + * @return {BigInt[]} + */ + slice(sliceSize) { + return (0,_bigint_encoder__WEBPACK_IMPORTED_MODULE_1__.sliceBigInt)(this._value, this.size, sliceSize); + } + toString() { + return this._value.toString(); + } + toJSON() { + return { + _value: this._value.toString() + }; + } + toBigInt() { + return BigInt(this._value); + } + + /** + * @inheritDoc + */ + static read(reader) { + const { + size + } = this.prototype; + if (size === 64) return new this(reader.readBigUInt64BE()); + return new this(...Array.from({ + length: size / 64 + }, () => reader.readBigUInt64BE()).reverse()); + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (value instanceof this) { + value = value._value; + } else if (typeof value !== 'bigint' || value > this.MAX_VALUE || value < this.MIN_VALUE) throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrWriterError(`${value} is not a ${this.name}`); + const { + unsigned, + size + } = this.prototype; + if (size === 64) { + if (unsigned) { + writer.writeBigUInt64BE(value); + } else { + writer.writeBigInt64BE(value); + } + } else { + for (const part of (0,_bigint_encoder__WEBPACK_IMPORTED_MODULE_1__.sliceBigInt)(value, size, 64).reverse()) { + if (unsigned) { + writer.writeBigUInt64BE(part); + } else { + writer.writeBigInt64BE(part); + } + } + } + } + + /** + * @inheritDoc + */ + static isValid(value) { + return typeof value === 'bigint' || value instanceof this; + } + + /** + * Create instance from string + * @param {String} string - Numeric representation + * @return {LargeInt} + */ + static fromString(string) { + return new this(string); + } + static MAX_VALUE = 0n; + static MIN_VALUE = 0n; + + /** + * @internal + * @return {void} + */ + static defineIntBoundaries() { + const [min, max] = (0,_bigint_encoder__WEBPACK_IMPORTED_MODULE_1__.calculateBigIntBoundaries)(this.prototype.size, this.prototype.unsigned); + this.MIN_VALUE = min; + this.MAX_VALUE = max; + } +} + +/***/ }), + +/***/ "./src/opaque.js": +/*!***********************!*\ + !*** ./src/opaque.js ***! + \***********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Opaque: () => (/* binding */ Opaque) +/* harmony export */ }); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + +class Opaque extends _xdr_type__WEBPACK_IMPORTED_MODULE_0__.XdrCompositeType { + constructor(length) { + super(); + this._length = length; + } + + /** + * @inheritDoc + */ + read(reader) { + return reader.read(this._length); + } + + /** + * @inheritDoc + */ + write(value, writer) { + const { + length + } = value; + if (length !== this._length) throw new _errors__WEBPACK_IMPORTED_MODULE_1__.XdrWriterError(`got ${value.length} bytes, expected ${this._length}`); + writer.write(value, length); + } + + /** + * @inheritDoc + */ + isValid(value) { + return Buffer.isBuffer(value) && value.length === this._length; + } +} + +/***/ }), + +/***/ "./src/option.js": +/*!***********************!*\ + !*** ./src/option.js ***! + \***********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Option: () => (/* binding */ Option) +/* harmony export */ }); +/* harmony import */ var _bool__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bool */ "./src/bool.js"); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); + + +class Option extends _xdr_type__WEBPACK_IMPORTED_MODULE_1__.XdrPrimitiveType { + constructor(childType) { + super(); + this._childType = childType; + } + + /** + * @inheritDoc + */ + read(reader) { + if (_bool__WEBPACK_IMPORTED_MODULE_0__.Bool.read(reader)) { + return this._childType.read(reader); + } + return undefined; + } + + /** + * @inheritDoc + */ + write(value, writer) { + const isPresent = value !== null && value !== undefined; + _bool__WEBPACK_IMPORTED_MODULE_0__.Bool.write(isPresent, writer); + if (isPresent) { + this._childType.write(value, writer); + } + } + + /** + * @inheritDoc + */ + isValid(value) { + if (value === null || value === undefined) { + return true; + } + return this._childType.isValid(value); + } +} + +/***/ }), + +/***/ "./src/quadruple.js": +/*!**************************!*\ + !*** ./src/quadruple.js ***! + \**************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Quadruple: () => (/* binding */ Quadruple) +/* harmony export */ }); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + +class Quadruple extends _xdr_type__WEBPACK_IMPORTED_MODULE_0__.XdrPrimitiveType { + static read() { + throw new _errors__WEBPACK_IMPORTED_MODULE_1__.XdrDefinitionError('quadruple not supported'); + } + static write() { + throw new _errors__WEBPACK_IMPORTED_MODULE_1__.XdrDefinitionError('quadruple not supported'); + } + static isValid() { + return false; + } +} + +/***/ }), + +/***/ "./src/reference.js": +/*!**************************!*\ + !*** ./src/reference.js ***! + \**************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Reference: () => (/* binding */ Reference) +/* harmony export */ }); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + +class Reference extends _xdr_type__WEBPACK_IMPORTED_MODULE_0__.XdrPrimitiveType { + /* jshint unused: false */ + resolve() { + throw new _errors__WEBPACK_IMPORTED_MODULE_1__.XdrDefinitionError('"resolve" method should be implemented in the descendant class'); + } +} + +/***/ }), + +/***/ "./src/serialization/xdr-reader.js": +/*!*****************************************!*\ + !*** ./src/serialization/xdr-reader.js ***! + \*****************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ XdrReader: () => (/* binding */ XdrReader) +/* harmony export */ }); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors */ "./src/errors.js"); +/** + * @internal + */ + +class XdrReader { + /** + * @constructor + * @param {Buffer} source - Buffer containing serialized data + */ + constructor(source) { + if (!Buffer.isBuffer(source)) { + if (source instanceof Array || Array.isArray(source) || ArrayBuffer.isView(source)) { + source = Buffer.from(source); + } else { + throw new _errors__WEBPACK_IMPORTED_MODULE_0__.XdrReaderError(`source invalid: ${source}`); + } + } + this._buffer = source; + this._length = source.length; + this._index = 0; + } + + /** + * @type {Buffer} + * @private + * @readonly + */ + _buffer; + /** + * @type {Number} + * @private + * @readonly + */ + _length; + /** + * @type {Number} + * @private + * @readonly + */ + _index; + + /** + * Check if the reader reached the end of the input buffer + * @return {Boolean} + */ + get eof() { + return this._index === this._length; + } + + /** + * Advance reader position, check padding and overflow + * @param {Number} size - Bytes to read + * @return {Number} Position to read from + * @private + */ + advance(size) { + const from = this._index; + // advance cursor position + this._index += size; + // check buffer boundaries + if (this._length < this._index) throw new _errors__WEBPACK_IMPORTED_MODULE_0__.XdrReaderError('attempt to read outside the boundary of the buffer'); + // check that padding is correct for Opaque and String + const padding = 4 - (size % 4 || 4); + if (padding > 0) { + for (let i = 0; i < padding; i++) if (this._buffer[this._index + i] !== 0) + // all bytes in the padding should be zeros + throw new _errors__WEBPACK_IMPORTED_MODULE_0__.XdrReaderError('invalid padding'); + this._index += padding; + } + return from; + } + + /** + * Reset reader position + * @return {void} + */ + rewind() { + this._index = 0; + } + + /** + * Read byte array from the buffer + * @param {Number} size - Bytes to read + * @return {Buffer} - Sliced portion of the underlying buffer + */ + read(size) { + const from = this.advance(size); + return this._buffer.subarray(from, from + size); + } + + /** + * Read i32 from buffer + * @return {Number} + */ + readInt32BE() { + return this._buffer.readInt32BE(this.advance(4)); + } + + /** + * Read u32 from buffer + * @return {Number} + */ + readUInt32BE() { + return this._buffer.readUInt32BE(this.advance(4)); + } + + /** + * Read i64 from buffer + * @return {BigInt} + */ + readBigInt64BE() { + return this._buffer.readBigInt64BE(this.advance(8)); + } + + /** + * Read u64 from buffer + * @return {BigInt} + */ + readBigUInt64BE() { + return this._buffer.readBigUInt64BE(this.advance(8)); + } + + /** + * Read float from buffer + * @return {Number} + */ + readFloatBE() { + return this._buffer.readFloatBE(this.advance(4)); + } + + /** + * Read double from buffer + * @return {Number} + */ + readDoubleBE() { + return this._buffer.readDoubleBE(this.advance(8)); + } + + /** + * Ensure that input buffer has been consumed in full, otherwise it's a type mismatch + * @return {void} + * @throws {XdrReaderError} + */ + ensureInputConsumed() { + if (this._index !== this._length) throw new _errors__WEBPACK_IMPORTED_MODULE_0__.XdrReaderError(`invalid XDR contract typecast - source buffer not entirely consumed`); + } +} + +/***/ }), + +/***/ "./src/serialization/xdr-writer.js": +/*!*****************************************!*\ + !*** ./src/serialization/xdr-writer.js ***! + \*****************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ XdrWriter: () => (/* binding */ XdrWriter) +/* harmony export */ }); +const BUFFER_CHUNK = 8192; // 8 KB chunk size increment + +/** + * @internal + */ +class XdrWriter { + /** + * @param {Buffer|Number} [buffer] - Optional destination buffer + */ + constructor(buffer) { + if (typeof buffer === 'number') { + buffer = Buffer.allocUnsafe(buffer); + } else if (!(buffer instanceof Buffer)) { + buffer = Buffer.allocUnsafe(BUFFER_CHUNK); + } + this._buffer = buffer; + this._length = buffer.length; + } + + /** + * @type {Buffer} + * @private + * @readonly + */ + _buffer; + /** + * @type {Number} + * @private + * @readonly + */ + _length; + /** + * @type {Number} + * @private + * @readonly + */ + _index = 0; + + /** + * Advance writer position, write padding if needed, auto-resize the buffer + * @param {Number} size - Bytes to write + * @return {Number} Position to read from + * @private + */ + alloc(size) { + const from = this._index; + // advance cursor position + this._index += size; + // ensure sufficient buffer size + if (this._length < this._index) { + this.resize(this._index); + } + return from; + } + + /** + * Increase size of the underlying buffer + * @param {Number} minRequiredSize - Minimum required buffer size + * @return {void} + * @private + */ + resize(minRequiredSize) { + // calculate new length, align new buffer length by chunk size + const newLength = Math.ceil(minRequiredSize / BUFFER_CHUNK) * BUFFER_CHUNK; + // create new buffer and copy previous data + const newBuffer = Buffer.allocUnsafe(newLength); + this._buffer.copy(newBuffer, 0, 0, this._length); + // update references + this._buffer = newBuffer; + this._length = newLength; + } + + /** + * Return XDR-serialized value + * @return {Buffer} + */ + finalize() { + // clip underlying buffer to the actually written value + return this._buffer.subarray(0, this._index); + } + + /** + * Return XDR-serialized value as byte array + * @return {Number[]} + */ + toArray() { + return [...this.finalize()]; + } + + /** + * Write byte array from the buffer + * @param {Buffer|String} value - Bytes/string to write + * @param {Number} size - Size in bytes + * @return {XdrReader} - XdrReader wrapper on top of a subarray + */ + write(value, size) { + if (typeof value === 'string') { + // serialize string directly to the output buffer + const offset = this.alloc(size); + this._buffer.write(value, offset, 'utf8'); + } else { + // copy data to the output buffer + if (!(value instanceof Buffer)) { + value = Buffer.from(value); + } + const offset = this.alloc(size); + value.copy(this._buffer, offset, 0, size); + } + + // add padding for 4-byte XDR alignment + const padding = 4 - (size % 4 || 4); + if (padding > 0) { + const offset = this.alloc(padding); + this._buffer.fill(0, offset, this._index); + } + } + + /** + * Write i32 from buffer + * @param {Number} value - Value to serialize + * @return {void} + */ + writeInt32BE(value) { + const offset = this.alloc(4); + this._buffer.writeInt32BE(value, offset); + } + + /** + * Write u32 from buffer + * @param {Number} value - Value to serialize + * @return {void} + */ + writeUInt32BE(value) { + const offset = this.alloc(4); + this._buffer.writeUInt32BE(value, offset); + } + + /** + * Write i64 from buffer + * @param {BigInt} value - Value to serialize + * @return {void} + */ + writeBigInt64BE(value) { + const offset = this.alloc(8); + this._buffer.writeBigInt64BE(value, offset); + } + + /** + * Write u64 from buffer + * @param {BigInt} value - Value to serialize + * @return {void} + */ + writeBigUInt64BE(value) { + const offset = this.alloc(8); + this._buffer.writeBigUInt64BE(value, offset); + } + + /** + * Write float from buffer + * @param {Number} value - Value to serialize + * @return {void} + */ + writeFloatBE(value) { + const offset = this.alloc(4); + this._buffer.writeFloatBE(value, offset); + } + + /** + * Write double from buffer + * @param {Number} value - Value to serialize + * @return {void} + */ + writeDoubleBE(value) { + const offset = this.alloc(8); + this._buffer.writeDoubleBE(value, offset); + } + static bufferChunkSize = BUFFER_CHUNK; +} + +/***/ }), + +/***/ "./src/string.js": +/*!***********************!*\ + !*** ./src/string.js ***! + \***********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ String: () => (/* binding */ String) +/* harmony export */ }); +/* harmony import */ var _unsigned_int__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./unsigned-int */ "./src/unsigned-int.js"); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + + +class String extends _xdr_type__WEBPACK_IMPORTED_MODULE_1__.XdrCompositeType { + constructor(maxLength = _unsigned_int__WEBPACK_IMPORTED_MODULE_0__.UnsignedInt.MAX_VALUE) { + super(); + this._maxLength = maxLength; + } + + /** + * @inheritDoc + */ + read(reader) { + const size = _unsigned_int__WEBPACK_IMPORTED_MODULE_0__.UnsignedInt.read(reader); + if (size > this._maxLength) throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrReaderError(`saw ${size} length String, max allowed is ${this._maxLength}`); + return reader.read(size); + } + readString(reader) { + return this.read(reader).toString('utf8'); + } + + /** + * @inheritDoc + */ + write(value, writer) { + // calculate string byte size before writing + const size = typeof value === 'string' ? Buffer.byteLength(value, 'utf8') : value.length; + if (size > this._maxLength) throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrWriterError(`got ${value.length} bytes, max allowed is ${this._maxLength}`); + // write size info + _unsigned_int__WEBPACK_IMPORTED_MODULE_0__.UnsignedInt.write(size, writer); + writer.write(value, size); + } + + /** + * @inheritDoc + */ + isValid(value) { + if (typeof value === 'string') { + return Buffer.byteLength(value, 'utf8') <= this._maxLength; + } + if (value instanceof Array || Buffer.isBuffer(value)) { + return value.length <= this._maxLength; + } + return false; + } +} + +/***/ }), + +/***/ "./src/struct.js": +/*!***********************!*\ + !*** ./src/struct.js ***! + \***********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Struct: () => (/* binding */ Struct) +/* harmony export */ }); +/* harmony import */ var _reference__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./reference */ "./src/reference.js"); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + + +class Struct extends _xdr_type__WEBPACK_IMPORTED_MODULE_1__.XdrCompositeType { + constructor(attributes) { + super(); + this._attributes = attributes || {}; + } + + /** + * @inheritDoc + */ + static read(reader) { + const attributes = {}; + for (const [fieldName, type] of this._fields) { + attributes[fieldName] = type.read(reader); + } + return new this(attributes); + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (!this.isValid(value)) { + throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrWriterError(`${value} has struct name ${value?.constructor?.structName}, not ${this.structName}: ${JSON.stringify(value)}`); + } + for (const [fieldName, type] of this._fields) { + const attribute = value._attributes[fieldName]; + type.write(attribute, writer); + } + } + + /** + * @inheritDoc + */ + static isValid(value) { + return value?.constructor?.structName === this.structName || (0,_xdr_type__WEBPACK_IMPORTED_MODULE_1__.isSerializableIsh)(value, this); + } + static create(context, name, fields) { + const ChildStruct = class extends Struct {}; + ChildStruct.structName = name; + context.results[name] = ChildStruct; + const mappedFields = new Array(fields.length); + for (let i = 0; i < fields.length; i++) { + const fieldDescriptor = fields[i]; + const fieldName = fieldDescriptor[0]; + let field = fieldDescriptor[1]; + if (field instanceof _reference__WEBPACK_IMPORTED_MODULE_0__.Reference) { + field = field.resolve(context); + } + mappedFields[i] = [fieldName, field]; + // create accessors + ChildStruct.prototype[fieldName] = createAccessorMethod(fieldName); + } + ChildStruct._fields = mappedFields; + return ChildStruct; + } +} +function createAccessorMethod(name) { + return function readOrWriteAttribute(value) { + if (value !== undefined) { + this._attributes[name] = value; + } + return this._attributes[name]; + }; +} + +/***/ }), + +/***/ "./src/types.js": +/*!**********************!*\ + !*** ./src/types.js ***! + \**********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Array: () => (/* reexport safe */ _array__WEBPACK_IMPORTED_MODULE_12__.Array), +/* harmony export */ Bool: () => (/* reexport safe */ _bool__WEBPACK_IMPORTED_MODULE_8__.Bool), +/* harmony export */ Double: () => (/* reexport safe */ _double__WEBPACK_IMPORTED_MODULE_6__.Double), +/* harmony export */ Enum: () => (/* reexport safe */ _enum__WEBPACK_IMPORTED_MODULE_16__.Enum), +/* harmony export */ Float: () => (/* reexport safe */ _float__WEBPACK_IMPORTED_MODULE_5__.Float), +/* harmony export */ Hyper: () => (/* reexport safe */ _hyper__WEBPACK_IMPORTED_MODULE_1__.Hyper), +/* harmony export */ Int: () => (/* reexport safe */ _int__WEBPACK_IMPORTED_MODULE_0__.Int), +/* harmony export */ LargeInt: () => (/* reexport safe */ _large_int__WEBPACK_IMPORTED_MODULE_4__.LargeInt), +/* harmony export */ Opaque: () => (/* reexport safe */ _opaque__WEBPACK_IMPORTED_MODULE_10__.Opaque), +/* harmony export */ Option: () => (/* reexport safe */ _option__WEBPACK_IMPORTED_MODULE_14__.Option), +/* harmony export */ Quadruple: () => (/* reexport safe */ _quadruple__WEBPACK_IMPORTED_MODULE_7__.Quadruple), +/* harmony export */ String: () => (/* reexport safe */ _string__WEBPACK_IMPORTED_MODULE_9__.String), +/* harmony export */ Struct: () => (/* reexport safe */ _struct__WEBPACK_IMPORTED_MODULE_17__.Struct), +/* harmony export */ Union: () => (/* reexport safe */ _union__WEBPACK_IMPORTED_MODULE_18__.Union), +/* harmony export */ UnsignedHyper: () => (/* reexport safe */ _unsigned_hyper__WEBPACK_IMPORTED_MODULE_3__.UnsignedHyper), +/* harmony export */ UnsignedInt: () => (/* reexport safe */ _unsigned_int__WEBPACK_IMPORTED_MODULE_2__.UnsignedInt), +/* harmony export */ VarArray: () => (/* reexport safe */ _var_array__WEBPACK_IMPORTED_MODULE_13__.VarArray), +/* harmony export */ VarOpaque: () => (/* reexport safe */ _var_opaque__WEBPACK_IMPORTED_MODULE_11__.VarOpaque), +/* harmony export */ Void: () => (/* reexport safe */ _void__WEBPACK_IMPORTED_MODULE_15__.Void) +/* harmony export */ }); +/* harmony import */ var _int__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./int */ "./src/int.js"); +/* harmony import */ var _hyper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hyper */ "./src/hyper.js"); +/* harmony import */ var _unsigned_int__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./unsigned-int */ "./src/unsigned-int.js"); +/* harmony import */ var _unsigned_hyper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./unsigned-hyper */ "./src/unsigned-hyper.js"); +/* harmony import */ var _large_int__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./large-int */ "./src/large-int.js"); +/* harmony import */ var _float__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./float */ "./src/float.js"); +/* harmony import */ var _double__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./double */ "./src/double.js"); +/* harmony import */ var _quadruple__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./quadruple */ "./src/quadruple.js"); +/* harmony import */ var _bool__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./bool */ "./src/bool.js"); +/* harmony import */ var _string__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./string */ "./src/string.js"); +/* harmony import */ var _opaque__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./opaque */ "./src/opaque.js"); +/* harmony import */ var _var_opaque__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./var-opaque */ "./src/var-opaque.js"); +/* harmony import */ var _array__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./array */ "./src/array.js"); +/* harmony import */ var _var_array__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./var-array */ "./src/var-array.js"); +/* harmony import */ var _option__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./option */ "./src/option.js"); +/* harmony import */ var _void__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./void */ "./src/void.js"); +/* harmony import */ var _enum__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./enum */ "./src/enum.js"); +/* harmony import */ var _struct__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./struct */ "./src/struct.js"); +/* harmony import */ var _union__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./union */ "./src/union.js"); + + + + + + + + + + + + + + + + + + + + +/***/ }), + +/***/ "./src/union.js": +/*!**********************!*\ + !*** ./src/union.js ***! + \**********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Union: () => (/* binding */ Union) +/* harmony export */ }); +/* harmony import */ var _void__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./void */ "./src/void.js"); +/* harmony import */ var _reference__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./reference */ "./src/reference.js"); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + + + +class Union extends _xdr_type__WEBPACK_IMPORTED_MODULE_2__.XdrCompositeType { + constructor(aSwitch, value) { + super(); + this.set(aSwitch, value); + } + set(aSwitch, value) { + if (typeof aSwitch === 'string') { + aSwitch = this.constructor._switchOn.fromName(aSwitch); + } + this._switch = aSwitch; + const arm = this.constructor.armForSwitch(this._switch); + this._arm = arm; + this._armType = arm === _void__WEBPACK_IMPORTED_MODULE_0__.Void ? _void__WEBPACK_IMPORTED_MODULE_0__.Void : this.constructor._arms[arm]; + this._value = value; + } + get(armName = this._arm) { + if (this._arm !== _void__WEBPACK_IMPORTED_MODULE_0__.Void && this._arm !== armName) throw new TypeError(`${armName} not set`); + return this._value; + } + switch() { + return this._switch; + } + arm() { + return this._arm; + } + armType() { + return this._armType; + } + value() { + return this._value; + } + static armForSwitch(aSwitch) { + const member = this._switches.get(aSwitch); + if (member !== undefined) { + return member; + } + if (this._defaultArm) { + return this._defaultArm; + } + throw new TypeError(`Bad union switch: ${aSwitch}`); + } + static armTypeForArm(arm) { + if (arm === _void__WEBPACK_IMPORTED_MODULE_0__.Void) { + return _void__WEBPACK_IMPORTED_MODULE_0__.Void; + } + return this._arms[arm]; + } + + /** + * @inheritDoc + */ + static read(reader) { + const aSwitch = this._switchOn.read(reader); + const arm = this.armForSwitch(aSwitch); + const armType = arm === _void__WEBPACK_IMPORTED_MODULE_0__.Void ? _void__WEBPACK_IMPORTED_MODULE_0__.Void : this._arms[arm]; + let value; + if (armType !== undefined) { + value = armType.read(reader); + } else { + value = arm.read(reader); + } + return new this(aSwitch, value); + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (!this.isValid(value)) { + throw new _errors__WEBPACK_IMPORTED_MODULE_3__.XdrWriterError(`${value} has union name ${value?.unionName}, not ${this.unionName}: ${JSON.stringify(value)}`); + } + this._switchOn.write(value.switch(), writer); + value.armType().write(value.value(), writer); + } + + /** + * @inheritDoc + */ + static isValid(value) { + return value?.constructor?.unionName === this.unionName || (0,_xdr_type__WEBPACK_IMPORTED_MODULE_2__.isSerializableIsh)(value, this); + } + static create(context, name, config) { + const ChildUnion = class extends Union {}; + ChildUnion.unionName = name; + context.results[name] = ChildUnion; + if (config.switchOn instanceof _reference__WEBPACK_IMPORTED_MODULE_1__.Reference) { + ChildUnion._switchOn = config.switchOn.resolve(context); + } else { + ChildUnion._switchOn = config.switchOn; + } + ChildUnion._switches = new Map(); + ChildUnion._arms = {}; + + // resolve default arm + let defaultArm = config.defaultArm; + if (defaultArm instanceof _reference__WEBPACK_IMPORTED_MODULE_1__.Reference) { + defaultArm = defaultArm.resolve(context); + } + ChildUnion._defaultArm = defaultArm; + for (const [aSwitch, armName] of config.switches) { + const key = typeof aSwitch === 'string' ? ChildUnion._switchOn.fromName(aSwitch) : aSwitch; + ChildUnion._switches.set(key, armName); + } + + // add enum-based helpers + // NOTE: we don't have good notation for "is a subclass of XDR.Enum", + // and so we use the following check (does _switchOn have a `values` + // attribute) to approximate the intent. + if (ChildUnion._switchOn.values !== undefined) { + for (const aSwitch of ChildUnion._switchOn.values()) { + // Add enum-based constructors + ChildUnion[aSwitch.name] = function ctr(value) { + return new ChildUnion(aSwitch, value); + }; + + // Add enum-based "set" helpers + ChildUnion.prototype[aSwitch.name] = function set(value) { + return this.set(aSwitch, value); + }; + } + } + if (config.arms) { + for (const [armsName, value] of Object.entries(config.arms)) { + ChildUnion._arms[armsName] = value instanceof _reference__WEBPACK_IMPORTED_MODULE_1__.Reference ? value.resolve(context) : value; + // Add arm accessor helpers + if (value !== _void__WEBPACK_IMPORTED_MODULE_0__.Void) { + ChildUnion.prototype[armsName] = function get() { + return this.get(armsName); + }; + } + } + } + return ChildUnion; + } +} + +/***/ }), + +/***/ "./src/unsigned-hyper.js": +/*!*******************************!*\ + !*** ./src/unsigned-hyper.js ***! + \*******************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ UnsignedHyper: () => (/* binding */ UnsignedHyper) +/* harmony export */ }); +/* harmony import */ var _large_int__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./large-int */ "./src/large-int.js"); + +class UnsignedHyper extends _large_int__WEBPACK_IMPORTED_MODULE_0__.LargeInt { + /** + * @param {Array} parts - Slices to encode + */ + constructor(...args) { + super(args); + } + get low() { + return Number(this._value & 0xffffffffn) << 0; + } + get high() { + return Number(this._value >> 32n) >> 0; + } + get size() { + return 64; + } + get unsigned() { + return true; + } + + /** + * Create UnsignedHyper instance from two [high][low] i32 values + * @param {Number} low - Low part of u64 number + * @param {Number} high - High part of u64 number + * @return {UnsignedHyper} + */ + static fromBits(low, high) { + return new this(low, high); + } +} +UnsignedHyper.defineIntBoundaries(); + +/***/ }), + +/***/ "./src/unsigned-int.js": +/*!*****************************!*\ + !*** ./src/unsigned-int.js ***! + \*****************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ UnsignedInt: () => (/* binding */ UnsignedInt) +/* harmony export */ }); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + +const MAX_VALUE = 4294967295; +const MIN_VALUE = 0; +class UnsignedInt extends _xdr_type__WEBPACK_IMPORTED_MODULE_0__.XdrPrimitiveType { + /** + * @inheritDoc + */ + static read(reader) { + return reader.readUInt32BE(); + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (typeof value !== 'number' || !(value >= MIN_VALUE && value <= MAX_VALUE) || value % 1 !== 0) throw new _errors__WEBPACK_IMPORTED_MODULE_1__.XdrWriterError('invalid u32 value'); + writer.writeUInt32BE(value); + } + + /** + * @inheritDoc + */ + static isValid(value) { + if (typeof value !== 'number' || value % 1 !== 0) { + return false; + } + return value >= MIN_VALUE && value <= MAX_VALUE; + } +} +UnsignedInt.MAX_VALUE = MAX_VALUE; +UnsignedInt.MIN_VALUE = MIN_VALUE; + +/***/ }), + +/***/ "./src/var-array.js": +/*!**************************!*\ + !*** ./src/var-array.js ***! + \**************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ VarArray: () => (/* binding */ VarArray) +/* harmony export */ }); +/* harmony import */ var _unsigned_int__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./unsigned-int */ "./src/unsigned-int.js"); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + + +class VarArray extends _xdr_type__WEBPACK_IMPORTED_MODULE_1__.XdrCompositeType { + constructor(childType, maxLength = _unsigned_int__WEBPACK_IMPORTED_MODULE_0__.UnsignedInt.MAX_VALUE) { + super(); + this._childType = childType; + this._maxLength = maxLength; + } + + /** + * @inheritDoc + */ + read(reader) { + const length = _unsigned_int__WEBPACK_IMPORTED_MODULE_0__.UnsignedInt.read(reader); + if (length > this._maxLength) throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrReaderError(`saw ${length} length VarArray, max allowed is ${this._maxLength}`); + const result = new Array(length); + for (let i = 0; i < length; i++) { + result[i] = this._childType.read(reader); + } + return result; + } + + /** + * @inheritDoc + */ + write(value, writer) { + if (!(value instanceof Array)) throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrWriterError(`value is not array`); + if (value.length > this._maxLength) throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrWriterError(`got array of size ${value.length}, max allowed is ${this._maxLength}`); + _unsigned_int__WEBPACK_IMPORTED_MODULE_0__.UnsignedInt.write(value.length, writer); + for (const child of value) { + this._childType.write(child, writer); + } + } + + /** + * @inheritDoc + */ + isValid(value) { + if (!(value instanceof Array) || value.length > this._maxLength) { + return false; + } + for (const child of value) { + if (!this._childType.isValid(child)) return false; + } + return true; + } +} + +/***/ }), + +/***/ "./src/var-opaque.js": +/*!***************************!*\ + !*** ./src/var-opaque.js ***! + \***************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ VarOpaque: () => (/* binding */ VarOpaque) +/* harmony export */ }); +/* harmony import */ var _unsigned_int__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./unsigned-int */ "./src/unsigned-int.js"); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + + +class VarOpaque extends _xdr_type__WEBPACK_IMPORTED_MODULE_1__.XdrCompositeType { + constructor(maxLength = _unsigned_int__WEBPACK_IMPORTED_MODULE_0__.UnsignedInt.MAX_VALUE) { + super(); + this._maxLength = maxLength; + } + + /** + * @inheritDoc + */ + read(reader) { + const size = _unsigned_int__WEBPACK_IMPORTED_MODULE_0__.UnsignedInt.read(reader); + if (size > this._maxLength) throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrReaderError(`saw ${size} length VarOpaque, max allowed is ${this._maxLength}`); + return reader.read(size); + } + + /** + * @inheritDoc + */ + write(value, writer) { + const { + length + } = value; + if (value.length > this._maxLength) throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrWriterError(`got ${value.length} bytes, max allowed is ${this._maxLength}`); + // write size info + _unsigned_int__WEBPACK_IMPORTED_MODULE_0__.UnsignedInt.write(length, writer); + writer.write(value, length); + } + + /** + * @inheritDoc + */ + isValid(value) { + return Buffer.isBuffer(value) && value.length <= this._maxLength; + } +} + +/***/ }), + +/***/ "./src/void.js": +/*!*********************!*\ + !*** ./src/void.js ***! + \*********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Void: () => (/* binding */ Void) +/* harmony export */ }); +/* harmony import */ var _xdr_type__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./xdr-type */ "./src/xdr-type.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + +class Void extends _xdr_type__WEBPACK_IMPORTED_MODULE_0__.XdrPrimitiveType { + /* jshint unused: false */ + + static read() { + return undefined; + } + static write(value) { + if (value !== undefined) throw new _errors__WEBPACK_IMPORTED_MODULE_1__.XdrWriterError('trying to write value to a void slot'); + } + static isValid(value) { + return value === undefined; + } +} + +/***/ }), + +/***/ "./src/xdr-type.js": +/*!*************************!*\ + !*** ./src/xdr-type.js ***! + \*************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ XdrCompositeType: () => (/* binding */ XdrCompositeType), +/* harmony export */ XdrPrimitiveType: () => (/* binding */ XdrPrimitiveType), +/* harmony export */ hasConstructor: () => (/* binding */ hasConstructor), +/* harmony export */ isSerializableIsh: () => (/* binding */ isSerializableIsh) +/* harmony export */ }); +/* harmony import */ var _serialization_xdr_reader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./serialization/xdr-reader */ "./src/serialization/xdr-reader.js"); +/* harmony import */ var _serialization_xdr_writer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./serialization/xdr-writer */ "./src/serialization/xdr-writer.js"); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors */ "./src/errors.js"); + + + +class XdrType { + /** + * Encode value to XDR format + * @param {XdrEncodingFormat} [format] - Encoding format (one of "raw", "hex", "base64") + * @return {String|Buffer} + */ + toXDR(format = 'raw') { + if (!this.write) return this.constructor.toXDR(this, format); + const writer = new _serialization_xdr_writer__WEBPACK_IMPORTED_MODULE_1__.XdrWriter(); + this.write(this, writer); + return encodeResult(writer.finalize(), format); + } + + /** + * Decode XDR-encoded value + * @param {Buffer|String} input - XDR-encoded input data + * @param {XdrEncodingFormat} [format] - Encoding format (one of "raw", "hex", "base64") + * @return {this} + */ + fromXDR(input, format = 'raw') { + if (!this.read) return this.constructor.fromXDR(input, format); + const reader = new _serialization_xdr_reader__WEBPACK_IMPORTED_MODULE_0__.XdrReader(decodeInput(input, format)); + const result = this.read(reader); + reader.ensureInputConsumed(); + return result; + } + + /** + * Check whether input contains a valid XDR-encoded value + * @param {Buffer|String} input - XDR-encoded input data + * @param {XdrEncodingFormat} [format] - Encoding format (one of "raw", "hex", "base64") + * @return {Boolean} + */ + validateXDR(input, format = 'raw') { + try { + this.fromXDR(input, format); + return true; + } catch (e) { + return false; + } + } + + /** + * Encode value to XDR format + * @param {this} value - Value to serialize + * @param {XdrEncodingFormat} [format] - Encoding format (one of "raw", "hex", "base64") + * @return {Buffer} + */ + static toXDR(value, format = 'raw') { + const writer = new _serialization_xdr_writer__WEBPACK_IMPORTED_MODULE_1__.XdrWriter(); + this.write(value, writer); + return encodeResult(writer.finalize(), format); + } + + /** + * Decode XDR-encoded value + * @param {Buffer|String} input - XDR-encoded input data + * @param {XdrEncodingFormat} [format] - Encoding format (one of "raw", "hex", "base64") + * @return {this} + */ + static fromXDR(input, format = 'raw') { + const reader = new _serialization_xdr_reader__WEBPACK_IMPORTED_MODULE_0__.XdrReader(decodeInput(input, format)); + const result = this.read(reader); + reader.ensureInputConsumed(); + return result; + } + + /** + * Check whether input contains a valid XDR-encoded value + * @param {Buffer|String} input - XDR-encoded input data + * @param {XdrEncodingFormat} [format] - Encoding format (one of "raw", "hex", "base64") + * @return {Boolean} + */ + static validateXDR(input, format = 'raw') { + try { + this.fromXDR(input, format); + return true; + } catch (e) { + return false; + } + } +} +class XdrPrimitiveType extends XdrType { + /** + * Read value from the XDR-serialized input + * @param {XdrReader} reader - XdrReader instance + * @return {this} + * @abstract + */ + // eslint-disable-next-line no-unused-vars + static read(reader) { + throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrNotImplementedDefinitionError(); + } + + /** + * Write XDR value to the buffer + * @param {this} value - Value to write + * @param {XdrWriter} writer - XdrWriter instance + * @return {void} + * @abstract + */ + // eslint-disable-next-line no-unused-vars + static write(value, writer) { + throw new _errors__WEBPACK_IMPORTED_MODULE_2__.XdrNotImplementedDefinitionError(); + } + + /** + * Check whether XDR primitive value is valid + * @param {this} value - Value to check + * @return {Boolean} + * @abstract + */ + // eslint-disable-next-line no-unused-vars + static isValid(value) { + return false; + } +} +class XdrCompositeType extends XdrType { + // Every descendant should implement two methods: read(reader) and write(value, writer) + + /** + * Check whether XDR primitive value is valid + * @param {this} value - Value to check + * @return {Boolean} + * @abstract + */ + // eslint-disable-next-line no-unused-vars + isValid(value) { + return false; + } +} +class InvalidXdrEncodingFormatError extends TypeError { + constructor(format) { + super(`Invalid format ${format}, must be one of "raw", "hex", "base64"`); + } +} +function encodeResult(buffer, format) { + switch (format) { + case 'raw': + return buffer; + case 'hex': + return buffer.toString('hex'); + case 'base64': + return buffer.toString('base64'); + default: + throw new InvalidXdrEncodingFormatError(format); + } +} +function decodeInput(input, format) { + switch (format) { + case 'raw': + return input; + case 'hex': + return Buffer.from(input, 'hex'); + case 'base64': + return Buffer.from(input, 'base64'); + default: + throw new InvalidXdrEncodingFormatError(format); + } +} + +/** + * Provides a "duck typed" version of the native `instanceof` for read/write. + * + * "Duck typing" means if the parameter _looks like_ and _acts like_ a duck + * (i.e. the type we're checking), it will be treated as that type. + * + * In this case, the "type" we're looking for is "like XdrType" but also "like + * XdrCompositeType|XdrPrimitiveType" (i.e. serializable), but also conditioned + * on a particular subclass of "XdrType" (e.g. {@link Union} which extends + * XdrType). + * + * This makes the package resilient to downstream systems that may be combining + * many versions of a package across its stack that are technically compatible + * but fail `instanceof` checks due to cross-pollination. + */ +function isSerializableIsh(value, subtype) { + return value !== undefined && value !== null && ( + // prereqs, otherwise `getPrototypeOf` pops + value instanceof subtype || + // quickest check + // Do an initial constructor check (anywhere is fine so that children of + // `subtype` still work), then + hasConstructor(value, subtype) && + // ensure it has read/write methods, then + typeof value.constructor.read === 'function' && typeof value.constructor.write === 'function' && + // ensure XdrType is in the prototype chain + hasConstructor(value, 'XdrType')); +} + +/** Tries to find `subtype` in any of the constructors or meta of `instance`. */ +function hasConstructor(instance, subtype) { + do { + const ctor = instance.constructor; + if (ctor.name === subtype) { + return true; + } + } while (instance = Object.getPrototypeOf(instance)); + return false; +} + +/** + * @typedef {'raw'|'hex'|'base64'} XdrEncodingFormat + */ + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __webpack_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ +/************************************************************************/ +/******/ +/******/ // startup +/******/ // Load entry module and return exports +/******/ // This entry module is referenced by other modules so it can't be inlined +/******/ var __webpack_exports__ = __webpack_require__("./src/browser.js"); +/******/ +/******/ return __webpack_exports__; +/******/ })() +; +}); +//# sourceMappingURL=xdr.js.map \ No newline at end of file diff --git a/node_modules/@stellar/js-xdr/lib/xdr.js.map b/node_modules/@stellar/js-xdr/lib/xdr.js.map new file mode 100644 index 000000000..3626e5734 --- /dev/null +++ b/node_modules/@stellar/js-xdr/lib/xdr.js.map @@ -0,0 +1 @@ +{"version":3,"file":"xdr.js","mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;;;;;;;;;;;;;;;;ACV8C;AACJ;AAEnC,MAAME,KAAK,SAASF,uDAAgB,CAAC;EAC1CG,WAAWA,CAACC,SAAS,EAAEC,MAAM,EAAE;IAC7B,KAAK,CAAC,CAAC;IACP,IAAI,CAACC,UAAU,GAAGF,SAAS;IAC3B,IAAI,CAACG,OAAO,GAAGF,MAAM;EACvB;;EAEA;AACF;AACA;EACEG,IAAIA,CAACC,MAAM,EAAE;IACX;IACA,MAAMC,MAAM,GAAG,IAAIC,MAAM,CAACT,KAAK,CAAC,IAAI,CAACK,OAAO,CAAC;IAC7C;IACA,KAAK,IAAIK,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAG,IAAI,CAACL,OAAO,EAAEK,CAAC,EAAE,EAAE;MACrCF,MAAM,CAACE,CAAC,CAAC,GAAG,IAAI,CAACN,UAAU,CAACE,IAAI,CAACC,MAAM,CAAC;IAC1C;IACA,OAAOC,MAAM;EACf;;EAEA;AACF;AACA;EACEG,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IACnB,IAAI,CAACJ,MAAM,CAACT,KAAK,CAACc,OAAO,CAACF,KAAK,CAAC,EAC9B,MAAM,IAAIb,mDAAc,CAAC,oBAAoB,CAAC;IAEhD,IAAIa,KAAK,CAACT,MAAM,KAAK,IAAI,CAACE,OAAO,EAC/B,MAAM,IAAIN,mDAAc,CACtB,qBAAqBa,KAAK,CAACT,MAAM,cAAc,IAAI,CAACE,OAAO,EAC7D,CAAC;IAEH,KAAK,MAAMU,KAAK,IAAIH,KAAK,EAAE;MACzB,IAAI,CAACR,UAAU,CAACO,KAAK,CAACI,KAAK,EAAEF,MAAM,CAAC;IACtC;EACF;;EAEA;AACF;AACA;EACEG,OAAOA,CAACJ,KAAK,EAAE;IACb,IAAI,EAAEA,KAAK,YAAYH,MAAM,CAACT,KAAK,CAAC,IAAIY,KAAK,CAACT,MAAM,KAAK,IAAI,CAACE,OAAO,EAAE;MACrE,OAAO,KAAK;IACd;IAEA,KAAK,MAAMU,KAAK,IAAIH,KAAK,EAAE;MACzB,IAAI,CAAC,IAAI,CAACR,UAAU,CAACY,OAAO,CAACD,KAAK,CAAC,EAAE,OAAO,KAAK;IACnD;IACA,OAAO,IAAI;EACb;AACF;;;;;;;;;;;;;;;;;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASE,oBAAoBA,CAACC,KAAK,EAAEC,IAAI,EAAEC,QAAQ,EAAE;EAC1D,IAAI,EAAEF,KAAK,YAAYlB,KAAK,CAAC,EAAE;IAC7B;IACAkB,KAAK,GAAG,CAACA,KAAK,CAAC;EACjB,CAAC,MAAM,IAAIA,KAAK,CAACf,MAAM,IAAIe,KAAK,CAAC,CAAC,CAAC,YAAYlB,KAAK,EAAE;IACpD;IACAkB,KAAK,GAAGA,KAAK,CAAC,CAAC,CAAC;EAClB;EAEA,MAAMG,KAAK,GAAGH,KAAK,CAACf,MAAM;EAC1B,MAAMmB,SAAS,GAAGH,IAAI,GAAGE,KAAK;EAC9B,QAAQC,SAAS;IACf,KAAK,EAAE;IACP,KAAK,EAAE;IACP,KAAK,GAAG;IACR,KAAK,GAAG;MACN;IAEF;MACE,MAAM,IAAIC,UAAU,CAClB,qDAAqDL,KAAK,EAC5D,CAAC;EACL;;EAEA;EACA,IAAI;IACF,KAAK,IAAIR,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGQ,KAAK,CAACf,MAAM,EAAEO,CAAC,EAAE,EAAE;MACrC,IAAI,OAAOQ,KAAK,CAACR,CAAC,CAAC,KAAK,QAAQ,EAAE;QAChCQ,KAAK,CAACR,CAAC,CAAC,GAAGc,MAAM,CAACN,KAAK,CAACR,CAAC,CAAC,CAACe,OAAO,CAAC,CAAC,CAAC;MACvC;IACF;EACF,CAAC,CAAC,OAAOC,CAAC,EAAE;IACV,MAAM,IAAIC,SAAS,CAAC,qCAAqCT,KAAK,KAAKQ,CAAC,GAAG,CAAC;EAC1E;;EAEA;EACA;EACA;EACA,IAAIN,QAAQ,IAAIF,KAAK,CAACf,MAAM,KAAK,CAAC,IAAIe,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,EAAE;IACnD,MAAM,IAAIK,UAAU,CAAC,mCAAmCL,KAAK,EAAE,CAAC;EAClE;;EAEA;EACA,IAAIV,MAAM,GAAGgB,MAAM,CAACI,OAAO,CAACN,SAAS,EAAEJ,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;EAClD,KAAK,IAAIR,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGQ,KAAK,CAACf,MAAM,EAAEO,CAAC,EAAE,EAAE;IACrCF,MAAM,IAAIgB,MAAM,CAACI,OAAO,CAACN,SAAS,EAAEJ,KAAK,CAACR,CAAC,CAAC,CAAC,IAAIc,MAAM,CAACd,CAAC,GAAGY,SAAS,CAAC;EACxE;;EAEA;EACA,IAAI,CAACF,QAAQ,EAAE;IACbZ,MAAM,GAAGgB,MAAM,CAACK,MAAM,CAACV,IAAI,EAAEX,MAAM,CAAC;EACtC;;EAEA;EACA,MAAM,CAACsB,GAAG,EAAEC,GAAG,CAAC,GAAGC,yBAAyB,CAACb,IAAI,EAAEC,QAAQ,CAAC;EAC5D,IAAIZ,MAAM,IAAIsB,GAAG,IAAItB,MAAM,IAAIuB,GAAG,EAAE;IAClC,OAAOvB,MAAM;EACf;;EAEA;EACA,MAAM,IAAImB,SAAS,CACjB,kBAAkBT,KAAK,SAASe,aAAa,CAC3Cd,IAAI,EACJC,QACF,CAAC,kBAAkBU,GAAG,KAAKC,GAAG,MAAMvB,MAAM,EAC5C,CAAC;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS0B,WAAWA,CAACtB,KAAK,EAAEuB,KAAK,EAAEb,SAAS,EAAE;EACnD,IAAI,OAAOV,KAAK,KAAK,QAAQ,EAAE;IAC7B,MAAM,IAAIe,SAAS,CAAC,gCAAgC,OAAOf,KAAK,EAAE,CAAC;EACrE;EAEA,MAAMS,KAAK,GAAGc,KAAK,GAAGb,SAAS;EAC/B,IAAID,KAAK,KAAK,CAAC,EAAE;IACf,OAAO,CAACT,KAAK,CAAC;EAChB;EAEA,IACEU,SAAS,GAAG,EAAE,IACdA,SAAS,GAAG,GAAG,IACdD,KAAK,KAAK,CAAC,IAAIA,KAAK,KAAK,CAAC,IAAIA,KAAK,KAAK,CAAE,EAC3C;IACA,MAAM,IAAIM,SAAS,CACjB,mBAAmBf,KAAK,qBAAqBuB,KAAK,OAAOb,SAAS,eACpE,CAAC;EACH;EAEA,MAAMc,KAAK,GAAGZ,MAAM,CAACF,SAAS,CAAC;;EAE/B;EACA,MAAMd,MAAM,GAAG,IAAIR,KAAK,CAACqB,KAAK,CAAC;EAC/B,KAAK,IAAIX,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGW,KAAK,EAAEX,CAAC,EAAE,EAAE;IAC9B;IACA;IACAF,MAAM,CAACE,CAAC,CAAC,GAAGc,MAAM,CAACK,MAAM,CAACP,SAAS,EAAEV,KAAK,CAAC,CAAC,CAAC;;IAE7C;IACAA,KAAK,KAAKwB,KAAK;EACjB;EAEA,OAAO5B,MAAM;AACf;AAEO,SAASyB,aAAaA,CAACI,SAAS,EAAEjB,QAAQ,EAAE;EACjD,OAAO,GAAGA,QAAQ,GAAG,GAAG,GAAG,GAAG,GAAGiB,SAAS,EAAE;AAC9C;;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,SAASL,yBAAyBA,CAACb,IAAI,EAAEC,QAAQ,EAAE;EACxD,IAAIA,QAAQ,EAAE;IACZ,OAAO,CAAC,EAAE,EAAE,CAAC,EAAE,IAAII,MAAM,CAACL,IAAI,CAAC,IAAI,EAAE,CAAC;EACxC;EAEA,MAAMmB,QAAQ,GAAG,EAAE,IAAId,MAAM,CAACL,IAAI,GAAG,CAAC,CAAC;EACvC,OAAO,CAAC,EAAE,GAAGmB,QAAQ,EAAEA,QAAQ,GAAG,EAAE,CAAC;AACvC;;;;;;;;;;;;;;;;;;AC5I4B;AACkB;AACJ;AAEnC,MAAMI,IAAI,SAASF,uDAAgB,CAAC;EACzC;AACF;AACA;EACE,OAAOlC,IAAIA,CAACC,MAAM,EAAE;IAClB,MAAMK,KAAK,GAAG2B,qCAAG,CAACjC,IAAI,CAACC,MAAM,CAAC;IAE9B,QAAQK,KAAK;MACX,KAAK,CAAC;QACJ,OAAO,KAAK;MACd,KAAK,CAAC;QACJ,OAAO,IAAI;MACb;QACE,MAAM,IAAI6B,mDAAc,CAAC,OAAO7B,KAAK,6BAA6B,CAAC;IACvE;EACF;;EAEA;AACF;AACA;EACE,OAAOD,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IAC1B,MAAM8B,MAAM,GAAG/B,KAAK,GAAG,CAAC,GAAG,CAAC;IAC5B2B,qCAAG,CAAC5B,KAAK,CAACgC,MAAM,EAAE9B,MAAM,CAAC;EAC3B;;EAEA;AACF;AACA;EACE,OAAOG,OAAOA,CAACJ,KAAK,EAAE;IACpB,OAAO,OAAOA,KAAK,KAAK,SAAS;EACnC;AACF;;;;;;;;;;ACnCA;AACA,MAAMgC,OAAO,GAAGC,mBAAO,CAAC,+BAAS,CAAC;AAClCC,MAAM,CAACF,OAAO,GAAGA,OAAO;;;;;;;;;;;;;;;;;;;ACFxB;AACoC;AACI;AACM;AAElB;AAE5B,MAAMM,eAAe,SAASF,iDAAS,CAAC;EACtC/C,WAAWA,CAACkD,IAAI,EAAE;IAChB,KAAK,CAAC,CAAC;IACP,IAAI,CAACA,IAAI,GAAGA,IAAI;EAClB;EAEAC,OAAOA,CAACC,OAAO,EAAE;IACf,MAAMC,IAAI,GAAGD,OAAO,CAACE,WAAW,CAAC,IAAI,CAACJ,IAAI,CAAC;IAC3C,OAAOG,IAAI,CAACF,OAAO,CAACC,OAAO,CAAC;EAC9B;AACF;AAEA,MAAMG,cAAc,SAASR,iDAAS,CAAC;EACrC/C,WAAWA,CAACwD,cAAc,EAAEtD,MAAM,EAAEuD,QAAQ,GAAG,KAAK,EAAE;IACpD,KAAK,CAAC,CAAC;IACP,IAAI,CAACD,cAAc,GAAGA,cAAc;IACpC,IAAI,CAACtD,MAAM,GAAGA,MAAM;IACpB,IAAI,CAACuD,QAAQ,GAAGA,QAAQ;EAC1B;EAEAN,OAAOA,CAACC,OAAO,EAAE;IACf,IAAIM,aAAa,GAAG,IAAI,CAACF,cAAc;IACvC,IAAItD,MAAM,GAAG,IAAI,CAACA,MAAM;IAExB,IAAIwD,aAAa,YAAYX,iDAAS,EAAE;MACtCW,aAAa,GAAGA,aAAa,CAACP,OAAO,CAACC,OAAO,CAAC;IAChD;IAEA,IAAIlD,MAAM,YAAY6C,iDAAS,EAAE;MAC/B7C,MAAM,GAAGA,MAAM,CAACiD,OAAO,CAACC,OAAO,CAAC;IAClC;IAEA,IAAI,IAAI,CAACK,QAAQ,EAAE;MACjB,OAAO,IAAIX,4CAAiB,CAACY,aAAa,EAAExD,MAAM,CAAC;IACrD;IACA,OAAO,IAAI4C,yCAAc,CAACY,aAAa,EAAExD,MAAM,CAAC;EAClD;AACF;AAEA,MAAM0D,eAAe,SAASb,iDAAS,CAAC;EACtC/C,WAAWA,CAACwD,cAAc,EAAE;IAC1B,KAAK,CAAC,CAAC;IACP,IAAI,CAACA,cAAc,GAAGA,cAAc;IACpC,IAAI,CAACN,IAAI,GAAGM,cAAc,CAACN,IAAI;EACjC;EAEAC,OAAOA,CAACC,OAAO,EAAE;IACf,IAAIM,aAAa,GAAG,IAAI,CAACF,cAAc;IAEvC,IAAIE,aAAa,YAAYX,iDAAS,EAAE;MACtCW,aAAa,GAAGA,aAAa,CAACP,OAAO,CAACC,OAAO,CAAC;IAChD;IAEA,OAAO,IAAIN,0CAAe,CAACY,aAAa,CAAC;EAC3C;AACF;AAEA,MAAMI,cAAc,SAASf,iDAAS,CAAC;EACrC/C,WAAWA,CAAC+D,SAAS,EAAE7D,MAAM,EAAE;IAC7B,KAAK,CAAC,CAAC;IACP,IAAI,CAAC6D,SAAS,GAAGA,SAAS;IAC1B,IAAI,CAAC7D,MAAM,GAAGA,MAAM;EACtB;EAEAiD,OAAOA,CAACC,OAAO,EAAE;IACf,IAAIlD,MAAM,GAAG,IAAI,CAACA,MAAM;IAExB,IAAIA,MAAM,YAAY6C,iDAAS,EAAE;MAC/B7C,MAAM,GAAGA,MAAM,CAACiD,OAAO,CAACC,OAAO,CAAC;IAClC;IAEA,OAAO,IAAI,IAAI,CAACW,SAAS,CAAC7D,MAAM,CAAC;EACnC;AACF;AAEA,MAAM8D,UAAU,CAAC;EACfhE,WAAWA,CAACA,WAAW,EAAEkD,IAAI,EAAEe,GAAG,EAAE;IAClC,IAAI,CAACjE,WAAW,GAAGA,WAAW;IAC9B,IAAI,CAACkD,IAAI,GAAGA,IAAI;IAChB,IAAI,CAACgB,MAAM,GAAGD,GAAG;EACnB;;EAEA;EACA;EACA;EACA;EACAd,OAAOA,CAACC,OAAO,EAAE;IACf,IAAI,IAAI,CAACF,IAAI,IAAIE,OAAO,CAACe,OAAO,EAAE;MAChC,OAAOf,OAAO,CAACe,OAAO,CAAC,IAAI,CAACjB,IAAI,CAAC;IACnC;IAEA,OAAO,IAAI,CAAClD,WAAW,CAACoD,OAAO,EAAE,IAAI,CAACF,IAAI,EAAE,IAAI,CAACgB,MAAM,CAAC;EAC1D;AACF;;AAEA;AACA;AACA,SAASE,aAAaA,CAAChB,OAAO,EAAEiB,QAAQ,EAAE1D,KAAK,EAAE;EAC/C,IAAIA,KAAK,YAAYoC,iDAAS,EAAE;IAC9BpC,KAAK,GAAGA,KAAK,CAACwC,OAAO,CAACC,OAAO,CAAC;EAChC;EACAA,OAAO,CAACe,OAAO,CAACE,QAAQ,CAAC,GAAG1D,KAAK;EACjC,OAAOA,KAAK;AACd;AAEA,SAAS2D,WAAWA,CAAClB,OAAO,EAAEF,IAAI,EAAEvC,KAAK,EAAE;EACzCyC,OAAO,CAACe,OAAO,CAACjB,IAAI,CAAC,GAAGvC,KAAK;EAC7B,OAAOA,KAAK;AACd;AAEA,MAAM4D,WAAW,CAAC;EAChBvE,WAAWA,CAACwE,WAAW,EAAE;IACvB,IAAI,CAACC,YAAY,GAAGD,WAAW;IAC/B,IAAI,CAACE,YAAY,GAAG,CAAC,CAAC;EACxB;EAEAC,IAAIA,CAACzB,IAAI,EAAE0B,OAAO,EAAE;IAClB,MAAMrE,MAAM,GAAG,IAAIyD,UAAU,CAAClB,wCAAa,CAACgC,MAAM,EAAE5B,IAAI,EAAE0B,OAAO,CAAC;IAClE,IAAI,CAACG,MAAM,CAAC7B,IAAI,EAAE3C,MAAM,CAAC;EAC3B;EAEAyE,MAAMA,CAAC9B,IAAI,EAAE0B,OAAO,EAAE;IACpB,MAAMrE,MAAM,GAAG,IAAIyD,UAAU,CAAClB,0CAAe,CAACgC,MAAM,EAAE5B,IAAI,EAAE0B,OAAO,CAAC;IACpE,IAAI,CAACG,MAAM,CAAC7B,IAAI,EAAE3C,MAAM,CAAC;EAC3B;EAEA2E,KAAKA,CAAChC,IAAI,EAAEe,GAAG,EAAE;IACf,MAAM1D,MAAM,GAAG,IAAIyD,UAAU,CAAClB,yCAAc,CAACgC,MAAM,EAAE5B,IAAI,EAAEe,GAAG,CAAC;IAC/D,IAAI,CAACc,MAAM,CAAC7B,IAAI,EAAE3C,MAAM,CAAC;EAC3B;EAEA6E,OAAOA,CAAClC,IAAI,EAAEe,GAAG,EAAE;IACjB,MAAM1D,MAAM,GAAG,IAAIyD,UAAU,CAACI,aAAa,EAAElB,IAAI,EAAEe,GAAG,CAAC;IACvD,IAAI,CAACc,MAAM,CAAC7B,IAAI,EAAE3C,MAAM,CAAC;EAC3B;EAEA8E,KAAKA,CAACnC,IAAI,EAAEe,GAAG,EAAE;IACf,MAAM1D,MAAM,GAAG,IAAIyD,UAAU,CAACM,WAAW,EAAEpB,IAAI,EAAEe,GAAG,CAAC;IACrD,IAAI,CAACc,MAAM,CAAC7B,IAAI,EAAE3C,MAAM,CAAC;EAC3B;EAEA+E,IAAIA,CAAA,EAAG;IACL,OAAOxC,wCAAa;EACtB;EAEA0C,IAAIA,CAAA,EAAG;IACL,OAAO1C,wCAAa;EACtB;EAEA2C,GAAGA,CAAA,EAAG;IACJ,OAAO3C,uCAAY;EACrB;EAEA4C,KAAKA,CAAA,EAAG;IACN,OAAO5C,yCAAc;EACvB;EAEA8C,IAAIA,CAAA,EAAG;IACL,OAAO9C,+CAAoB;EAC7B;EAEAgD,MAAMA,CAAA,EAAG;IACP,OAAOhD,iDAAsB;EAC/B;EAEAkD,KAAKA,CAAA,EAAG;IACN,OAAOlD,yCAAc;EACvB;EAEAoD,MAAMA,CAAA,EAAG;IACP,OAAOpD,0CAAe;EACxB;EAEAsD,SAASA,CAAA,EAAG;IACV,OAAOtD,6CAAkB;EAC3B;EAEAwD,MAAMA,CAACpG,MAAM,EAAE;IACb,OAAO,IAAI4D,cAAc,CAAChB,0CAAe,EAAE5C,MAAM,CAAC;EACpD;EAEAsG,MAAMA,CAACtG,MAAM,EAAE;IACb,OAAO,IAAI4D,cAAc,CAAChB,0CAAe,EAAE5C,MAAM,CAAC;EACpD;EAEAwG,SAASA,CAACxG,MAAM,EAAE;IAChB,OAAO,IAAI4D,cAAc,CAAChB,6CAAkB,EAAE5C,MAAM,CAAC;EACvD;EAEA0G,KAAKA,CAAC3G,SAAS,EAAEC,MAAM,EAAE;IACvB,OAAO,IAAIqD,cAAc,CAACtD,SAAS,EAAEC,MAAM,CAAC;EAC9C;EAEA2G,QAAQA,CAAC5G,SAAS,EAAE6G,SAAS,EAAE;IAC7B,OAAO,IAAIvD,cAAc,CAACtD,SAAS,EAAE6G,SAAS,EAAE,IAAI,CAAC;EACvD;EAEAC,MAAMA,CAAC9G,SAAS,EAAE;IAChB,OAAO,IAAI2D,eAAe,CAAC3D,SAAS,CAAC;EACvC;EAEA8E,MAAMA,CAAC7B,IAAI,EAAE8D,UAAU,EAAE;IACvB,IAAI,IAAI,CAACvC,YAAY,CAACvB,IAAI,CAAC,KAAK+D,SAAS,EAAE;MACzC,IAAI,CAACvC,YAAY,CAACxB,IAAI,CAAC,GAAG8D,UAAU;IACtC,CAAC,MAAM;MACL,MAAM,IAAIhE,uDAAkB,CAAC,GAAGE,IAAI,qBAAqB,CAAC;IAC5D;EACF;EAEAgE,MAAMA,CAAChE,IAAI,EAAE;IACX,OAAO,IAAID,eAAe,CAACC,IAAI,CAAC;EAClC;EAEAC,OAAOA,CAAA,EAAG;IACR,KAAK,MAAME,IAAI,IAAI8D,MAAM,CAACC,MAAM,CAAC,IAAI,CAAC1C,YAAY,CAAC,EAAE;MACnDrB,IAAI,CAACF,OAAO,CAAC;QACXG,WAAW,EAAE,IAAI,CAACoB,YAAY;QAC9BP,OAAO,EAAE,IAAI,CAACM;MAChB,CAAC,CAAC;IACJ;EACF;AACF;AAEO,SAASP,MAAMA,CAACmD,EAAE,EAAEC,KAAK,GAAG,CAAC,CAAC,EAAE;EACrC,IAAID,EAAE,EAAE;IACN,MAAME,OAAO,GAAG,IAAIhD,WAAW,CAAC+C,KAAK,CAAC;IACtCD,EAAE,CAACE,OAAO,CAAC;IACXA,OAAO,CAACpE,OAAO,CAAC,CAAC;EACnB;EAEA,OAAOmE,KAAK;AACd;;;;;;;;;;;;;;;;;AC9O8C;AACJ;AAEnC,MAAMnB,MAAM,SAAS5D,uDAAgB,CAAC;EAC3C;AACF;AACA;EACE,OAAOlC,IAAIA,CAACC,MAAM,EAAE;IAClB,OAAOA,MAAM,CAACkH,YAAY,CAAC,CAAC;EAC9B;;EAEA;AACF;AACA;EACE,OAAO9G,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IAC1B,IAAI,OAAOD,KAAK,KAAK,QAAQ,EAAE,MAAM,IAAIb,mDAAc,CAAC,cAAc,CAAC;IAEvEc,MAAM,CAAC6G,aAAa,CAAC9G,KAAK,CAAC;EAC7B;;EAEA;AACF;AACA;EACE,OAAOI,OAAOA,CAACJ,KAAK,EAAE;IACpB,OAAO,OAAOA,KAAK,KAAK,QAAQ;EAClC;AACF;;;;;;;;;;;;;;;;;;AC1B4B;AACqC;AACP;AAEnD,MAAMkE,IAAI,SAAStC,uDAAgB,CAAC;EACzCvC,WAAWA,CAACkD,IAAI,EAAEvC,KAAK,EAAE;IACvB,KAAK,CAAC,CAAC;IACP,IAAI,CAACuC,IAAI,GAAGA,IAAI;IAChB,IAAI,CAACvC,KAAK,GAAGA,KAAK;EACpB;;EAEA;AACF;AACA;EACE,OAAON,IAAIA,CAACC,MAAM,EAAE;IAClB,MAAMoC,MAAM,GAAGJ,qCAAG,CAACjC,IAAI,CAACC,MAAM,CAAC;IAC/B,MAAMqH,GAAG,GAAG,IAAI,CAACC,QAAQ,CAAClF,MAAM,CAAC;IACjC,IAAIiF,GAAG,KAAKV,SAAS,EACnB,MAAM,IAAIzE,mDAAc,CACtB,WAAW,IAAI,CAACqF,QAAQ,qBAAqBnF,MAAM,EACrD,CAAC;IACH,OAAOiF,GAAG;EACZ;;EAEA;AACF;AACA;EACE,OAAOjH,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IAC1B,IAAI,CAAC,IAAI,CAACG,OAAO,CAACJ,KAAK,CAAC,EAAE;MACxB,MAAM,IAAIb,mDAAc,CACtB,GAAGa,KAAK,kBAAkBA,KAAK,EAAEkH,QAAQ,SACvC,IAAI,CAACA,QAAQ,KACVC,IAAI,CAACC,SAAS,CAACpH,KAAK,CAAC,EAC5B,CAAC;IACH;IAEA2B,qCAAG,CAAC5B,KAAK,CAACC,KAAK,CAACA,KAAK,EAAEC,MAAM,CAAC;EAChC;;EAEA;AACF;AACA;EACE,OAAOG,OAAOA,CAACJ,KAAK,EAAE;IACpB,OACEA,KAAK,EAAEX,WAAW,EAAE6H,QAAQ,KAAK,IAAI,CAACA,QAAQ,IAC9CH,4DAAiB,CAAC/G,KAAK,EAAE,IAAI,CAAC;EAElC;EAEA,OAAOiE,OAAOA,CAAA,EAAG;IACf,OAAO,IAAI,CAACoD,QAAQ;EACtB;EAEA,OAAOZ,MAAMA,CAAA,EAAG;IACd,OAAOD,MAAM,CAACC,MAAM,CAAC,IAAI,CAACY,QAAQ,CAAC;EACrC;EAEA,OAAOC,QAAQA,CAAC/E,IAAI,EAAE;IACpB,MAAM3C,MAAM,GAAG,IAAI,CAACyH,QAAQ,CAAC9E,IAAI,CAAC;IAElC,IAAI,CAAC3C,MAAM,EACT,MAAM,IAAImB,SAAS,CAAC,GAAGwB,IAAI,uBAAuB,IAAI,CAAC2E,QAAQ,EAAE,CAAC;IAEpE,OAAOtH,MAAM;EACf;EAEA,OAAO2H,SAASA,CAACvH,KAAK,EAAE;IACtB,MAAMJ,MAAM,GAAG,IAAI,CAACqH,QAAQ,CAACjH,KAAK,CAAC;IACnC,IAAIJ,MAAM,KAAK0G,SAAS,EACtB,MAAM,IAAIvF,SAAS,CACjB,GAAGf,KAAK,oCAAoC,IAAI,CAACkH,QAAQ,EAC3D,CAAC;IACH,OAAOtH,MAAM;EACf;EAEA,OAAOuE,MAAMA,CAAC1B,OAAO,EAAEF,IAAI,EAAE0B,OAAO,EAAE;IACpC,MAAMuD,SAAS,GAAG,cAActD,IAAI,CAAC,EAAE;IAEvCsD,SAAS,CAACN,QAAQ,GAAG3E,IAAI;IACzBE,OAAO,CAACe,OAAO,CAACjB,IAAI,CAAC,GAAGiF,SAAS;IAEjCA,SAAS,CAACH,QAAQ,GAAG,CAAC,CAAC;IACvBG,SAAS,CAACP,QAAQ,GAAG,CAAC,CAAC;IAEvB,KAAK,MAAM,CAACQ,GAAG,EAAEzH,KAAK,CAAC,IAAIwG,MAAM,CAACkB,OAAO,CAACzD,OAAO,CAAC,EAAE;MAClD,MAAM0D,IAAI,GAAG,IAAIH,SAAS,CAACC,GAAG,EAAEzH,KAAK,CAAC;MACtCwH,SAAS,CAACH,QAAQ,CAACI,GAAG,CAAC,GAAGE,IAAI;MAC9BH,SAAS,CAACP,QAAQ,CAACjH,KAAK,CAAC,GAAG2H,IAAI;MAChCH,SAAS,CAACC,GAAG,CAAC,GAAG,MAAME,IAAI;IAC7B;IAEA,OAAOH,SAAS;EAClB;AACF;;;;;;;;;;;;;;;;;;AC7FO,MAAMrI,cAAc,SAAS4B,SAAS,CAAC;EAC5C1B,WAAWA,CAACuI,OAAO,EAAE;IACnB,KAAK,CAAC,oBAAoBA,OAAO,EAAE,CAAC;EACtC;AACF;AAEO,MAAM/F,cAAc,SAASd,SAAS,CAAC;EAC5C1B,WAAWA,CAACuI,OAAO,EAAE;IACnB,KAAK,CAAC,mBAAmBA,OAAO,EAAE,CAAC;EACrC;AACF;AAEO,MAAMvF,kBAAkB,SAAStB,SAAS,CAAC;EAChD1B,WAAWA,CAACuI,OAAO,EAAE;IACnB,KAAK,CAAC,8BAA8BA,OAAO,EAAE,CAAC;EAChD;AACF;AAEO,MAAMC,gCAAgC,SAASxF,kBAAkB,CAAC;EACvEhD,WAAWA,CAAA,EAAG;IACZ,KAAK,CACH,0EACF,CAAC;EACH;AACF;;;;;;;;;;;;;;;;;ACxB8C;AACJ;AAEnC,MAAMiG,KAAK,SAAS1D,uDAAgB,CAAC;EAC1C;AACF;AACA;EACE,OAAOlC,IAAIA,CAACC,MAAM,EAAE;IAClB,OAAOA,MAAM,CAACmI,WAAW,CAAC,CAAC;EAC7B;;EAEA;AACF;AACA;EACE,OAAO/H,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IAC1B,IAAI,OAAOD,KAAK,KAAK,QAAQ,EAAE,MAAM,IAAIb,mDAAc,CAAC,cAAc,CAAC;IAEvEc,MAAM,CAAC8H,YAAY,CAAC/H,KAAK,CAAC;EAC5B;;EAEA;AACF;AACA;EACE,OAAOI,OAAOA,CAACJ,KAAK,EAAE;IACpB,OAAO,OAAOA,KAAK,KAAK,QAAQ;EAClC;AACF;;;;;;;;;;;;;;;;AC1BuC;AAEhC,MAAMgF,KAAK,SAASgD,gDAAQ,CAAC;EAClC;AACF;AACA;EACE3I,WAAWA,CAAC,GAAG4I,IAAI,EAAE;IACnB,KAAK,CAACA,IAAI,CAAC;EACb;EAEA,IAAIC,GAAGA,CAAA,EAAG;IACR,OAAOC,MAAM,CAAC,IAAI,CAACC,MAAM,GAAG,WAAW,CAAC,IAAI,CAAC;EAC/C;EAEA,IAAIC,IAAIA,CAAA,EAAG;IACT,OAAOF,MAAM,CAAC,IAAI,CAACC,MAAM,IAAI,GAAG,CAAC,IAAI,CAAC;EACxC;EAEA,IAAI7H,IAAIA,CAAA,EAAG;IACT,OAAO,EAAE;EACX;EAEA,IAAIC,QAAQA,CAAA,EAAG;IACb,OAAO,KAAK;EACd;;EAEA;AACF;AACA;AACA;AACA;AACA;EACE,OAAO8H,QAAQA,CAACJ,GAAG,EAAEG,IAAI,EAAE;IACzB,OAAO,IAAI,IAAI,CAACH,GAAG,EAAEG,IAAI,CAAC;EAC5B;AACF;AAEArD,KAAK,CAACuD,mBAAmB,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACrCH;AACC;AAE8B;;;;;;;;;;;;;;;;;;ACHT;AACJ;AAE1C,MAAMG,SAAS,GAAG,UAAU;AAC5B,MAAMC,SAAS,GAAG,CAAC,UAAU;AAEtB,MAAMhH,GAAG,SAASC,uDAAgB,CAAC;EACxC;AACF;AACA;EACE,OAAOlC,IAAIA,CAACC,MAAM,EAAE;IAClB,OAAOA,MAAM,CAACiJ,WAAW,CAAC,CAAC;EAC7B;;EAEA;AACF;AACA;EACE,OAAO7I,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IAC1B,IAAI,OAAOD,KAAK,KAAK,QAAQ,EAAE,MAAM,IAAIb,mDAAc,CAAC,cAAc,CAAC;IAEvE,IAAI,CAACa,KAAK,GAAG,CAAC,MAAMA,KAAK,EAAE,MAAM,IAAIb,mDAAc,CAAC,mBAAmB,CAAC;IAExEc,MAAM,CAAC4I,YAAY,CAAC7I,KAAK,CAAC;EAC5B;;EAEA;AACF;AACA;EACE,OAAOI,OAAOA,CAACJ,KAAK,EAAE;IACpB,IAAI,OAAOA,KAAK,KAAK,QAAQ,IAAI,CAACA,KAAK,GAAG,CAAC,MAAMA,KAAK,EAAE;MACtD,OAAO,KAAK;IACd;IAEA,OAAOA,KAAK,IAAI2I,SAAS,IAAI3I,KAAK,IAAI0I,SAAS;EACjD;AACF;AAEA/G,GAAG,CAAC+G,SAAS,GAAGA,SAAS;AACzB/G,GAAG,CAACgH,SAAS,GAAG,CAACA,SAAS;;;;;;;;;;;;;;;;;;ACtCoB;AAKpB;AACkD;AAErE,MAAMX,QAAQ,SAASpG,uDAAgB,CAAC;EAC7C;AACF;AACA;EACEvC,WAAWA,CAAC4I,IAAI,EAAE;IAChB,KAAK,CAAC,CAAC;IACP,IAAI,CAACG,MAAM,GAAG/H,qEAAoB,CAAC4H,IAAI,EAAE,IAAI,CAAC1H,IAAI,EAAE,IAAI,CAACC,QAAQ,CAAC;EACpE;;EAEA;AACF;AACA;AACA;AACA;EACE,IAAIA,QAAQA,CAAA,EAAG;IACb,MAAM,IAAIqH,qEAAgC,CAAC,CAAC;EAC9C;;EAEA;AACF;AACA;AACA;AACA;EACE,IAAItH,IAAIA,CAAA,EAAG;IACT,MAAM,IAAIsH,qEAAgC,CAAC,CAAC;EAC9C;;EAEA;AACF;AACA;AACA;AACA;EACEiB,KAAKA,CAACpI,SAAS,EAAE;IACf,OAAOY,4DAAW,CAAC,IAAI,CAAC8G,MAAM,EAAE,IAAI,CAAC7H,IAAI,EAAEG,SAAS,CAAC;EACvD;EAEAqI,QAAQA,CAAA,EAAG;IACT,OAAO,IAAI,CAACX,MAAM,CAACW,QAAQ,CAAC,CAAC;EAC/B;EAEAC,MAAMA,CAAA,EAAG;IACP,OAAO;MAAEZ,MAAM,EAAE,IAAI,CAACA,MAAM,CAACW,QAAQ,CAAC;IAAE,CAAC;EAC3C;EAEAE,QAAQA,CAAA,EAAG;IACT,OAAOrI,MAAM,CAAC,IAAI,CAACwH,MAAM,CAAC;EAC5B;;EAEA;AACF;AACA;EACE,OAAO1I,IAAIA,CAACC,MAAM,EAAE;IAClB,MAAM;MAAEY;IAAK,CAAC,GAAG,IAAI,CAAC2I,SAAS;IAC/B,IAAI3I,IAAI,KAAK,EAAE,EAAE,OAAO,IAAI,IAAI,CAACZ,MAAM,CAACwJ,eAAe,CAAC,CAAC,CAAC;IAC1D,OAAO,IAAI,IAAI,CACb,GAAG/J,KAAK,CAACgK,IAAI,CAAC;MAAE7J,MAAM,EAAEgB,IAAI,GAAG;IAAG,CAAC,EAAE,MACnCZ,MAAM,CAACwJ,eAAe,CAAC,CACzB,CAAC,CAACE,OAAO,CAAC,CACZ,CAAC;EACH;;EAEA;AACF;AACA;EACE,OAAOtJ,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IAC1B,IAAID,KAAK,YAAY,IAAI,EAAE;MACzBA,KAAK,GAAGA,KAAK,CAACoI,MAAM;IACtB,CAAC,MAAM,IACL,OAAOpI,KAAK,KAAK,QAAQ,IACzBA,KAAK,GAAG,IAAI,CAAC0I,SAAS,IACtB1I,KAAK,GAAG,IAAI,CAAC2I,SAAS,EAEtB,MAAM,IAAIxJ,mDAAc,CAAC,GAAGa,KAAK,aAAa,IAAI,CAACuC,IAAI,EAAE,CAAC;IAE5D,MAAM;MAAE/B,QAAQ;MAAED;IAAK,CAAC,GAAG,IAAI,CAAC2I,SAAS;IACzC,IAAI3I,IAAI,KAAK,EAAE,EAAE;MACf,IAAIC,QAAQ,EAAE;QACZP,MAAM,CAACqJ,gBAAgB,CAACtJ,KAAK,CAAC;MAChC,CAAC,MAAM;QACLC,MAAM,CAACsJ,eAAe,CAACvJ,KAAK,CAAC;MAC/B;IACF,CAAC,MAAM;MACL,KAAK,MAAMwJ,IAAI,IAAIlI,4DAAW,CAACtB,KAAK,EAAEO,IAAI,EAAE,EAAE,CAAC,CAAC8I,OAAO,CAAC,CAAC,EAAE;QACzD,IAAI7I,QAAQ,EAAE;UACZP,MAAM,CAACqJ,gBAAgB,CAACE,IAAI,CAAC;QAC/B,CAAC,MAAM;UACLvJ,MAAM,CAACsJ,eAAe,CAACC,IAAI,CAAC;QAC9B;MACF;IACF;EACF;;EAEA;AACF;AACA;EACE,OAAOpJ,OAAOA,CAACJ,KAAK,EAAE;IACpB,OAAO,OAAOA,KAAK,KAAK,QAAQ,IAAIA,KAAK,YAAY,IAAI;EAC3D;;EAEA;AACF;AACA;AACA;AACA;EACE,OAAOyJ,UAAUA,CAAC9D,MAAM,EAAE;IACxB,OAAO,IAAI,IAAI,CAACA,MAAM,CAAC;EACzB;EAEA,OAAO+C,SAAS,GAAG,EAAE;EAErB,OAAOC,SAAS,GAAG,EAAE;;EAErB;AACF;AACA;AACA;EACE,OAAOJ,mBAAmBA,CAAA,EAAG;IAC3B,MAAM,CAACrH,GAAG,EAAEC,GAAG,CAAC,GAAGC,0EAAyB,CAC1C,IAAI,CAAC8H,SAAS,CAAC3I,IAAI,EACnB,IAAI,CAAC2I,SAAS,CAAC1I,QACjB,CAAC;IACD,IAAI,CAACmI,SAAS,GAAGzH,GAAG;IACpB,IAAI,CAACwH,SAAS,GAAGvH,GAAG;EACtB;AACF;;;;;;;;;;;;;;;;;ACpI8C;AACJ;AAEnC,MAAM2E,MAAM,SAAS5G,uDAAgB,CAAC;EAC3CG,WAAWA,CAACE,MAAM,EAAE;IAClB,KAAK,CAAC,CAAC;IACP,IAAI,CAACE,OAAO,GAAGF,MAAM;EACvB;;EAEA;AACF;AACA;EACEG,IAAIA,CAACC,MAAM,EAAE;IACX,OAAOA,MAAM,CAACD,IAAI,CAAC,IAAI,CAACD,OAAO,CAAC;EAClC;;EAEA;AACF;AACA;EACEM,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IACnB,MAAM;MAAEV;IAAO,CAAC,GAAGS,KAAK;IACxB,IAAIT,MAAM,KAAK,IAAI,CAACE,OAAO,EACzB,MAAM,IAAIN,mDAAc,CACtB,OAAOa,KAAK,CAACT,MAAM,oBAAoB,IAAI,CAACE,OAAO,EACrD,CAAC;IACHQ,MAAM,CAACF,KAAK,CAACC,KAAK,EAAET,MAAM,CAAC;EAC7B;;EAEA;AACF;AACA;EACEa,OAAOA,CAACJ,KAAK,EAAE;IACb,OAAO0J,MAAM,CAACC,QAAQ,CAAC3J,KAAK,CAAC,IAAIA,KAAK,CAACT,MAAM,KAAK,IAAI,CAACE,OAAO;EAChE;AACF;;;;;;;;;;;;;;;;;AClC8B;AACgB;AAEvC,MAAMyD,MAAM,SAAStB,uDAAgB,CAAC;EAC3CvC,WAAWA,CAACC,SAAS,EAAE;IACrB,KAAK,CAAC,CAAC;IACP,IAAI,CAACE,UAAU,GAAGF,SAAS;EAC7B;;EAEA;AACF;AACA;EACEI,IAAIA,CAACC,MAAM,EAAE;IACX,IAAImC,uCAAI,CAACpC,IAAI,CAACC,MAAM,CAAC,EAAE;MACrB,OAAO,IAAI,CAACH,UAAU,CAACE,IAAI,CAACC,MAAM,CAAC;IACrC;IAEA,OAAO2G,SAAS;EAClB;;EAEA;AACF;AACA;EACEvG,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IACnB,MAAM2J,SAAS,GAAG5J,KAAK,KAAK,IAAI,IAAIA,KAAK,KAAKsG,SAAS;IAEvDxE,uCAAI,CAAC/B,KAAK,CAAC6J,SAAS,EAAE3J,MAAM,CAAC;IAE7B,IAAI2J,SAAS,EAAE;MACb,IAAI,CAACpK,UAAU,CAACO,KAAK,CAACC,KAAK,EAAEC,MAAM,CAAC;IACtC;EACF;;EAEA;AACF;AACA;EACEG,OAAOA,CAACJ,KAAK,EAAE;IACb,IAAIA,KAAK,KAAK,IAAI,IAAIA,KAAK,KAAKsG,SAAS,EAAE;MACzC,OAAO,IAAI;IACb;IACA,OAAO,IAAI,CAAC9G,UAAU,CAACY,OAAO,CAACJ,KAAK,CAAC;EACvC;AACF;;;;;;;;;;;;;;;;;AC1C8C;AACA;AAEvC,MAAM0F,SAAS,SAAS9D,uDAAgB,CAAC;EAC9C,OAAOlC,IAAIA,CAAA,EAAG;IACZ,MAAM,IAAI2C,uDAAkB,CAAC,yBAAyB,CAAC;EACzD;EAEA,OAAOtC,KAAKA,CAAA,EAAG;IACb,MAAM,IAAIsC,uDAAkB,CAAC,yBAAyB,CAAC;EACzD;EAEA,OAAOjC,OAAOA,CAAA,EAAG;IACf,OAAO,KAAK;EACd;AACF;;;;;;;;;;;;;;;;;ACf8C;AACA;AAEvC,MAAMgC,SAAS,SAASR,uDAAgB,CAAC;EAC9C;EACAY,OAAOA,CAAA,EAAG;IACR,MAAM,IAAIH,uDAAkB,CAC1B,gEACF,CAAC;EACH;AACF;;;;;;;;;;;;;;;;ACVA;AACA;AACA;AAC2C;AAEpC,MAAMmG,SAAS,CAAC;EACrB;AACF;AACA;AACA;EACEnJ,WAAWA,CAACwK,MAAM,EAAE;IAClB,IAAI,CAACH,MAAM,CAACC,QAAQ,CAACE,MAAM,CAAC,EAAE;MAC5B,IACEA,MAAM,YAAYzK,KAAK,IACvBA,KAAK,CAACc,OAAO,CAAC2J,MAAM,CAAC,IACrBC,WAAW,CAACC,MAAM,CAACF,MAAM,CAAC,EAC1B;QACAA,MAAM,GAAGH,MAAM,CAACN,IAAI,CAACS,MAAM,CAAC;MAC9B,CAAC,MAAM;QACL,MAAM,IAAIhI,mDAAc,CAAC,mBAAmBgI,MAAM,EAAE,CAAC;MACvD;IACF;IAEA,IAAI,CAACG,OAAO,GAAGH,MAAM;IACrB,IAAI,CAACpK,OAAO,GAAGoK,MAAM,CAACtK,MAAM;IAC5B,IAAI,CAAC0K,MAAM,GAAG,CAAC;EACjB;;EAEA;AACF;AACA;AACA;AACA;EACED,OAAO;EACP;AACF;AACA;AACA;AACA;EACEvK,OAAO;EACP;AACF;AACA;AACA;AACA;EACEwK,MAAM;;EAEN;AACF;AACA;AACA;EACE,IAAIC,GAAGA,CAAA,EAAG;IACR,OAAO,IAAI,CAACD,MAAM,KAAK,IAAI,CAACxK,OAAO;EACrC;;EAEA;AACF;AACA;AACA;AACA;AACA;EACE0K,OAAOA,CAAC5J,IAAI,EAAE;IACZ,MAAM6I,IAAI,GAAG,IAAI,CAACa,MAAM;IACxB;IACA,IAAI,CAACA,MAAM,IAAI1J,IAAI;IACnB;IACA,IAAI,IAAI,CAACd,OAAO,GAAG,IAAI,CAACwK,MAAM,EAC5B,MAAM,IAAIpI,mDAAc,CACtB,oDACF,CAAC;IACH;IACA,MAAMuI,OAAO,GAAG,CAAC,IAAI7J,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC;IACnC,IAAI6J,OAAO,GAAG,CAAC,EAAE;MACf,KAAK,IAAItK,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGsK,OAAO,EAAEtK,CAAC,EAAE,EAC9B,IAAI,IAAI,CAACkK,OAAO,CAAC,IAAI,CAACC,MAAM,GAAGnK,CAAC,CAAC,KAAK,CAAC;QACrC;QACA,MAAM,IAAI+B,mDAAc,CAAC,iBAAiB,CAAC;MAC/C,IAAI,CAACoI,MAAM,IAAIG,OAAO;IACxB;IACA,OAAOhB,IAAI;EACb;;EAEA;AACF;AACA;AACA;EACEiB,MAAMA,CAAA,EAAG;IACP,IAAI,CAACJ,MAAM,GAAG,CAAC;EACjB;;EAEA;AACF;AACA;AACA;AACA;EACEvK,IAAIA,CAACa,IAAI,EAAE;IACT,MAAM6I,IAAI,GAAG,IAAI,CAACe,OAAO,CAAC5J,IAAI,CAAC;IAC/B,OAAO,IAAI,CAACyJ,OAAO,CAACM,QAAQ,CAAClB,IAAI,EAAEA,IAAI,GAAG7I,IAAI,CAAC;EACjD;;EAEA;AACF;AACA;AACA;EACEqI,WAAWA,CAAA,EAAG;IACZ,OAAO,IAAI,CAACoB,OAAO,CAACpB,WAAW,CAAC,IAAI,CAACuB,OAAO,CAAC,CAAC,CAAC,CAAC;EAClD;;EAEA;AACF;AACA;AACA;EACEI,YAAYA,CAAA,EAAG;IACb,OAAO,IAAI,CAACP,OAAO,CAACO,YAAY,CAAC,IAAI,CAACJ,OAAO,CAAC,CAAC,CAAC,CAAC;EACnD;;EAEA;AACF;AACA;AACA;EACEK,cAAcA,CAAA,EAAG;IACf,OAAO,IAAI,CAACR,OAAO,CAACQ,cAAc,CAAC,IAAI,CAACL,OAAO,CAAC,CAAC,CAAC,CAAC;EACrD;;EAEA;AACF;AACA;AACA;EACEhB,eAAeA,CAAA,EAAG;IAChB,OAAO,IAAI,CAACa,OAAO,CAACb,eAAe,CAAC,IAAI,CAACgB,OAAO,CAAC,CAAC,CAAC,CAAC;EACtD;;EAEA;AACF;AACA;AACA;EACErC,WAAWA,CAAA,EAAG;IACZ,OAAO,IAAI,CAACkC,OAAO,CAAClC,WAAW,CAAC,IAAI,CAACqC,OAAO,CAAC,CAAC,CAAC,CAAC;EAClD;;EAEA;AACF;AACA;AACA;EACEtD,YAAYA,CAAA,EAAG;IACb,OAAO,IAAI,CAACmD,OAAO,CAACnD,YAAY,CAAC,IAAI,CAACsD,OAAO,CAAC,CAAC,CAAC,CAAC;EACnD;;EAEA;AACF;AACA;AACA;AACA;EACEM,mBAAmBA,CAAA,EAAG;IACpB,IAAI,IAAI,CAACR,MAAM,KAAK,IAAI,CAACxK,OAAO,EAC9B,MAAM,IAAIoC,mDAAc,CACtB,qEACF,CAAC;EACL;AACF;;;;;;;;;;;;;;;AC/JA,MAAM6I,YAAY,GAAG,IAAI,CAAC,CAAC;;AAE3B;AACA;AACA;AACO,MAAMjC,SAAS,CAAC;EACrB;AACF;AACA;EACEpJ,WAAWA,CAACsL,MAAM,EAAE;IAClB,IAAI,OAAOA,MAAM,KAAK,QAAQ,EAAE;MAC9BA,MAAM,GAAGjB,MAAM,CAACkB,WAAW,CAACD,MAAM,CAAC;IACrC,CAAC,MAAM,IAAI,EAAEA,MAAM,YAAYjB,MAAM,CAAC,EAAE;MACtCiB,MAAM,GAAGjB,MAAM,CAACkB,WAAW,CAACF,YAAY,CAAC;IAC3C;IACA,IAAI,CAACV,OAAO,GAAGW,MAAM;IACrB,IAAI,CAAClL,OAAO,GAAGkL,MAAM,CAACpL,MAAM;EAC9B;;EAEA;AACF;AACA;AACA;AACA;EACEyK,OAAO;EACP;AACF;AACA;AACA;AACA;EACEvK,OAAO;EACP;AACF;AACA;AACA;AACA;EACEwK,MAAM,GAAG,CAAC;;EAEV;AACF;AACA;AACA;AACA;AACA;EACEY,KAAKA,CAACtK,IAAI,EAAE;IACV,MAAM6I,IAAI,GAAG,IAAI,CAACa,MAAM;IACxB;IACA,IAAI,CAACA,MAAM,IAAI1J,IAAI;IACnB;IACA,IAAI,IAAI,CAACd,OAAO,GAAG,IAAI,CAACwK,MAAM,EAAE;MAC9B,IAAI,CAACa,MAAM,CAAC,IAAI,CAACb,MAAM,CAAC;IAC1B;IACA,OAAOb,IAAI;EACb;;EAEA;AACF;AACA;AACA;AACA;AACA;EACE0B,MAAMA,CAACC,eAAe,EAAE;IACtB;IACA,MAAMC,SAAS,GAAGC,IAAI,CAACC,IAAI,CAACH,eAAe,GAAGL,YAAY,CAAC,GAAGA,YAAY;IAC1E;IACA,MAAMS,SAAS,GAAGzB,MAAM,CAACkB,WAAW,CAACI,SAAS,CAAC;IAC/C,IAAI,CAAChB,OAAO,CAACoB,IAAI,CAACD,SAAS,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC1L,OAAO,CAAC;IAChD;IACA,IAAI,CAACuK,OAAO,GAAGmB,SAAS;IACxB,IAAI,CAAC1L,OAAO,GAAGuL,SAAS;EAC1B;;EAEA;AACF;AACA;AACA;EACEK,QAAQA,CAAA,EAAG;IACT;IACA,OAAO,IAAI,CAACrB,OAAO,CAACM,QAAQ,CAAC,CAAC,EAAE,IAAI,CAACL,MAAM,CAAC;EAC9C;;EAEA;AACF;AACA;AACA;EACEqB,OAAOA,CAAA,EAAG;IACR,OAAO,CAAC,GAAG,IAAI,CAACD,QAAQ,CAAC,CAAC,CAAC;EAC7B;;EAEA;AACF;AACA;AACA;AACA;AACA;EACEtL,KAAKA,CAACC,KAAK,EAAEO,IAAI,EAAE;IACjB,IAAI,OAAOP,KAAK,KAAK,QAAQ,EAAE;MAC7B;MACA,MAAMuL,MAAM,GAAG,IAAI,CAACV,KAAK,CAACtK,IAAI,CAAC;MAC/B,IAAI,CAACyJ,OAAO,CAACjK,KAAK,CAACC,KAAK,EAAEuL,MAAM,EAAE,MAAM,CAAC;IAC3C,CAAC,MAAM;MACL;MACA,IAAI,EAAEvL,KAAK,YAAY0J,MAAM,CAAC,EAAE;QAC9B1J,KAAK,GAAG0J,MAAM,CAACN,IAAI,CAACpJ,KAAK,CAAC;MAC5B;MACA,MAAMuL,MAAM,GAAG,IAAI,CAACV,KAAK,CAACtK,IAAI,CAAC;MAC/BP,KAAK,CAACoL,IAAI,CAAC,IAAI,CAACpB,OAAO,EAAEuB,MAAM,EAAE,CAAC,EAAEhL,IAAI,CAAC;IAC3C;;IAEA;IACA,MAAM6J,OAAO,GAAG,CAAC,IAAI7J,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC;IACnC,IAAI6J,OAAO,GAAG,CAAC,EAAE;MACf,MAAMmB,MAAM,GAAG,IAAI,CAACV,KAAK,CAACT,OAAO,CAAC;MAClC,IAAI,CAACJ,OAAO,CAACwB,IAAI,CAAC,CAAC,EAAED,MAAM,EAAE,IAAI,CAACtB,MAAM,CAAC;IAC3C;EACF;;EAEA;AACF;AACA;AACA;AACA;EACEpB,YAAYA,CAAC7I,KAAK,EAAE;IAClB,MAAMuL,MAAM,GAAG,IAAI,CAACV,KAAK,CAAC,CAAC,CAAC;IAC5B,IAAI,CAACb,OAAO,CAACnB,YAAY,CAAC7I,KAAK,EAAEuL,MAAM,CAAC;EAC1C;;EAEA;AACF;AACA;AACA;AACA;EACEE,aAAaA,CAACzL,KAAK,EAAE;IACnB,MAAMuL,MAAM,GAAG,IAAI,CAACV,KAAK,CAAC,CAAC,CAAC;IAC5B,IAAI,CAACb,OAAO,CAACyB,aAAa,CAACzL,KAAK,EAAEuL,MAAM,CAAC;EAC3C;;EAEA;AACF;AACA;AACA;AACA;EACEhC,eAAeA,CAACvJ,KAAK,EAAE;IACrB,MAAMuL,MAAM,GAAG,IAAI,CAACV,KAAK,CAAC,CAAC,CAAC;IAC5B,IAAI,CAACb,OAAO,CAACT,eAAe,CAACvJ,KAAK,EAAEuL,MAAM,CAAC;EAC7C;;EAEA;AACF;AACA;AACA;AACA;EACEjC,gBAAgBA,CAACtJ,KAAK,EAAE;IACtB,MAAMuL,MAAM,GAAG,IAAI,CAACV,KAAK,CAAC,CAAC,CAAC;IAC5B,IAAI,CAACb,OAAO,CAACV,gBAAgB,CAACtJ,KAAK,EAAEuL,MAAM,CAAC;EAC9C;;EAEA;AACF;AACA;AACA;AACA;EACExD,YAAYA,CAAC/H,KAAK,EAAE;IAClB,MAAMuL,MAAM,GAAG,IAAI,CAACV,KAAK,CAAC,CAAC,CAAC;IAC5B,IAAI,CAACb,OAAO,CAACjC,YAAY,CAAC/H,KAAK,EAAEuL,MAAM,CAAC;EAC1C;;EAEA;AACF;AACA;AACA;AACA;EACEzE,aAAaA,CAAC9G,KAAK,EAAE;IACnB,MAAMuL,MAAM,GAAG,IAAI,CAACV,KAAK,CAAC,CAAC,CAAC;IAC5B,IAAI,CAACb,OAAO,CAAClD,aAAa,CAAC9G,KAAK,EAAEuL,MAAM,CAAC;EAC3C;EAEA,OAAOG,eAAe,GAAGhB,YAAY;AACvC;;;;;;;;;;;;;;;;;;AClL6C;AACC;AACY;AAEnD,MAAM9E,MAAM,SAAS1G,uDAAgB,CAAC;EAC3CG,WAAWA,CAAC8G,SAAS,GAAGjB,sDAAW,CAACwD,SAAS,EAAE;IAC7C,KAAK,CAAC,CAAC;IACP,IAAI,CAACiD,UAAU,GAAGxF,SAAS;EAC7B;;EAEA;AACF;AACA;EACEzG,IAAIA,CAACC,MAAM,EAAE;IACX,MAAMY,IAAI,GAAG2E,sDAAW,CAACxF,IAAI,CAACC,MAAM,CAAC;IACrC,IAAIY,IAAI,GAAG,IAAI,CAACoL,UAAU,EACxB,MAAM,IAAI9J,mDAAc,CACtB,OAAOtB,IAAI,kCAAkC,IAAI,CAACoL,UAAU,EAC9D,CAAC;IAEH,OAAOhM,MAAM,CAACD,IAAI,CAACa,IAAI,CAAC;EAC1B;EAEAqL,UAAUA,CAACjM,MAAM,EAAE;IACjB,OAAO,IAAI,CAACD,IAAI,CAACC,MAAM,CAAC,CAACoJ,QAAQ,CAAC,MAAM,CAAC;EAC3C;;EAEA;AACF;AACA;EACEhJ,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IACnB;IACA,MAAMM,IAAI,GACR,OAAOP,KAAK,KAAK,QAAQ,GACrB0J,MAAM,CAACmC,UAAU,CAAC7L,KAAK,EAAE,MAAM,CAAC,GAChCA,KAAK,CAACT,MAAM;IAClB,IAAIgB,IAAI,GAAG,IAAI,CAACoL,UAAU,EACxB,MAAM,IAAIxM,mDAAc,CACtB,OAAOa,KAAK,CAACT,MAAM,0BAA0B,IAAI,CAACoM,UAAU,EAC9D,CAAC;IACH;IACAzG,sDAAW,CAACnF,KAAK,CAACQ,IAAI,EAAEN,MAAM,CAAC;IAC/BA,MAAM,CAACF,KAAK,CAACC,KAAK,EAAEO,IAAI,CAAC;EAC3B;;EAEA;AACF;AACA;EACEH,OAAOA,CAACJ,KAAK,EAAE;IACb,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE;MAC7B,OAAO0J,MAAM,CAACmC,UAAU,CAAC7L,KAAK,EAAE,MAAM,CAAC,IAAI,IAAI,CAAC2L,UAAU;IAC5D;IACA,IAAI3L,KAAK,YAAYZ,KAAK,IAAIsK,MAAM,CAACC,QAAQ,CAAC3J,KAAK,CAAC,EAAE;MACpD,OAAOA,KAAK,CAACT,MAAM,IAAI,IAAI,CAACoM,UAAU;IACxC;IACA,OAAO,KAAK;EACd;AACF;;;;;;;;;;;;;;;;;;ACzDwC;AACyB;AACvB;AAEnC,MAAMrH,MAAM,SAASpF,uDAAgB,CAAC;EAC3CG,WAAWA,CAACyM,UAAU,EAAE;IACtB,KAAK,CAAC,CAAC;IACP,IAAI,CAACC,WAAW,GAAGD,UAAU,IAAI,CAAC,CAAC;EACrC;;EAEA;AACF;AACA;EACE,OAAOpM,IAAIA,CAACC,MAAM,EAAE;IAClB,MAAMmM,UAAU,GAAG,CAAC,CAAC;IACrB,KAAK,MAAM,CAACE,SAAS,EAAEC,IAAI,CAAC,IAAI,IAAI,CAACC,OAAO,EAAE;MAC5CJ,UAAU,CAACE,SAAS,CAAC,GAAGC,IAAI,CAACvM,IAAI,CAACC,MAAM,CAAC;IAC3C;IACA,OAAO,IAAI,IAAI,CAACmM,UAAU,CAAC;EAC7B;;EAEA;AACF;AACA;EACE,OAAO/L,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IAC1B,IAAI,CAAC,IAAI,CAACG,OAAO,CAACJ,KAAK,CAAC,EAAE;MACxB,MAAM,IAAIb,mDAAc,CACtB,GAAGa,KAAK,oBAAoBA,KAAK,EAAEX,WAAW,EAAE8M,UAAU,SACxD,IAAI,CAACA,UAAU,KACZhF,IAAI,CAACC,SAAS,CAACpH,KAAK,CAAC,EAC5B,CAAC;IACH;IAEA,KAAK,MAAM,CAACgM,SAAS,EAAEC,IAAI,CAAC,IAAI,IAAI,CAACC,OAAO,EAAE;MAC5C,MAAME,SAAS,GAAGpM,KAAK,CAAC+L,WAAW,CAACC,SAAS,CAAC;MAC9CC,IAAI,CAAClM,KAAK,CAACqM,SAAS,EAAEnM,MAAM,CAAC;IAC/B;EACF;;EAEA;AACF;AACA;EACE,OAAOG,OAAOA,CAACJ,KAAK,EAAE;IACpB,OACEA,KAAK,EAAEX,WAAW,EAAE8M,UAAU,KAAK,IAAI,CAACA,UAAU,IAClDpF,4DAAiB,CAAC/G,KAAK,EAAE,IAAI,CAAC;EAElC;EAEA,OAAOmE,MAAMA,CAAC1B,OAAO,EAAEF,IAAI,EAAE8J,MAAM,EAAE;IACnC,MAAMC,WAAW,GAAG,cAAchI,MAAM,CAAC,EAAE;IAE3CgI,WAAW,CAACH,UAAU,GAAG5J,IAAI;IAE7BE,OAAO,CAACe,OAAO,CAACjB,IAAI,CAAC,GAAG+J,WAAW;IAEnC,MAAMC,YAAY,GAAG,IAAInN,KAAK,CAACiN,MAAM,CAAC9M,MAAM,CAAC;IAC7C,KAAK,IAAIO,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGuM,MAAM,CAAC9M,MAAM,EAAEO,CAAC,EAAE,EAAE;MACtC,MAAM0M,eAAe,GAAGH,MAAM,CAACvM,CAAC,CAAC;MACjC,MAAMkM,SAAS,GAAGQ,eAAe,CAAC,CAAC,CAAC;MACpC,IAAIC,KAAK,GAAGD,eAAe,CAAC,CAAC,CAAC;MAC9B,IAAIC,KAAK,YAAYrK,iDAAS,EAAE;QAC9BqK,KAAK,GAAGA,KAAK,CAACjK,OAAO,CAACC,OAAO,CAAC;MAChC;MACA8J,YAAY,CAACzM,CAAC,CAAC,GAAG,CAACkM,SAAS,EAAES,KAAK,CAAC;MACpC;MACAH,WAAW,CAACpD,SAAS,CAAC8C,SAAS,CAAC,GAAGU,oBAAoB,CAACV,SAAS,CAAC;IACpE;IAEAM,WAAW,CAACJ,OAAO,GAAGK,YAAY;IAElC,OAAOD,WAAW;EACpB;AACF;AAEA,SAASI,oBAAoBA,CAACnK,IAAI,EAAE;EAClC,OAAO,SAASoK,oBAAoBA,CAAC3M,KAAK,EAAE;IAC1C,IAAIA,KAAK,KAAKsG,SAAS,EAAE;MACvB,IAAI,CAACyF,WAAW,CAACxJ,IAAI,CAAC,GAAGvC,KAAK;IAChC;IACA,OAAO,IAAI,CAAC+L,WAAW,CAACxJ,IAAI,CAAC;EAC/B,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AClFsB;AACE;AACO;AACE;AACL;AAEJ;AACC;AACG;AAEL;AAEE;AAEA;AACI;AAEL;AACI;AAEH;AACF;AAEA;AACE;;;;;;;;;;;;;;;;;;;;ACxBK;AACU;AACyB;AACvB;AAEnC,MAAMiC,KAAK,SAAStF,uDAAgB,CAAC;EAC1CG,WAAWA,CAACuN,OAAO,EAAE5M,KAAK,EAAE;IAC1B,KAAK,CAAC,CAAC;IACP,IAAI,CAAC6M,GAAG,CAACD,OAAO,EAAE5M,KAAK,CAAC;EAC1B;EAEA6M,GAAGA,CAACD,OAAO,EAAE5M,KAAK,EAAE;IAClB,IAAI,OAAO4M,OAAO,KAAK,QAAQ,EAAE;MAC/BA,OAAO,GAAG,IAAI,CAACvN,WAAW,CAACyN,SAAS,CAACxF,QAAQ,CAACsF,OAAO,CAAC;IACxD;IAEA,IAAI,CAACG,OAAO,GAAGH,OAAO;IACtB,MAAMI,GAAG,GAAG,IAAI,CAAC3N,WAAW,CAAC4N,YAAY,CAAC,IAAI,CAACF,OAAO,CAAC;IACvD,IAAI,CAACG,IAAI,GAAGF,GAAG;IACf,IAAI,CAACG,QAAQ,GAAGH,GAAG,KAAKpI,uCAAI,GAAGA,uCAAI,GAAG,IAAI,CAACvF,WAAW,CAAC+N,KAAK,CAACJ,GAAG,CAAC;IACjE,IAAI,CAAC5E,MAAM,GAAGpI,KAAK;EACrB;EAEAqN,GAAGA,CAACC,OAAO,GAAG,IAAI,CAACJ,IAAI,EAAE;IACvB,IAAI,IAAI,CAACA,IAAI,KAAKtI,uCAAI,IAAI,IAAI,CAACsI,IAAI,KAAKI,OAAO,EAC7C,MAAM,IAAIvM,SAAS,CAAC,GAAGuM,OAAO,UAAU,CAAC;IAC3C,OAAO,IAAI,CAAClF,MAAM;EACpB;EAEAmF,MAAMA,CAAA,EAAG;IACP,OAAO,IAAI,CAACR,OAAO;EACrB;EAEAC,GAAGA,CAAA,EAAG;IACJ,OAAO,IAAI,CAACE,IAAI;EAClB;EAEAM,OAAOA,CAAA,EAAG;IACR,OAAO,IAAI,CAACL,QAAQ;EACtB;EAEAnN,KAAKA,CAAA,EAAG;IACN,OAAO,IAAI,CAACoI,MAAM;EACpB;EAEA,OAAO6E,YAAYA,CAACL,OAAO,EAAE;IAC3B,MAAMa,MAAM,GAAG,IAAI,CAACC,SAAS,CAACL,GAAG,CAACT,OAAO,CAAC;IAC1C,IAAIa,MAAM,KAAKnH,SAAS,EAAE;MACxB,OAAOmH,MAAM;IACf;IACA,IAAI,IAAI,CAACE,WAAW,EAAE;MACpB,OAAO,IAAI,CAACA,WAAW;IACzB;IACA,MAAM,IAAI5M,SAAS,CAAC,qBAAqB6L,OAAO,EAAE,CAAC;EACrD;EAEA,OAAOgB,aAAaA,CAACZ,GAAG,EAAE;IACxB,IAAIA,GAAG,KAAKpI,uCAAI,EAAE;MAChB,OAAOA,uCAAI;IACb;IACA,OAAO,IAAI,CAACwI,KAAK,CAACJ,GAAG,CAAC;EACxB;;EAEA;AACF;AACA;EACE,OAAOtN,IAAIA,CAACC,MAAM,EAAE;IAClB,MAAMiN,OAAO,GAAG,IAAI,CAACE,SAAS,CAACpN,IAAI,CAACC,MAAM,CAAC;IAC3C,MAAMqN,GAAG,GAAG,IAAI,CAACC,YAAY,CAACL,OAAO,CAAC;IACtC,MAAMY,OAAO,GAAGR,GAAG,KAAKpI,uCAAI,GAAGA,uCAAI,GAAG,IAAI,CAACwI,KAAK,CAACJ,GAAG,CAAC;IACrD,IAAIhN,KAAK;IACT,IAAIwN,OAAO,KAAKlH,SAAS,EAAE;MACzBtG,KAAK,GAAGwN,OAAO,CAAC9N,IAAI,CAACC,MAAM,CAAC;IAC9B,CAAC,MAAM;MACLK,KAAK,GAAGgN,GAAG,CAACtN,IAAI,CAACC,MAAM,CAAC;IAC1B;IACA,OAAO,IAAI,IAAI,CAACiN,OAAO,EAAE5M,KAAK,CAAC;EACjC;;EAEA;AACF;AACA;EACE,OAAOD,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IAC1B,IAAI,CAAC,IAAI,CAACG,OAAO,CAACJ,KAAK,CAAC,EAAE;MACxB,MAAM,IAAIb,mDAAc,CACtB,GAAGa,KAAK,mBAAmBA,KAAK,EAAE6N,SAAS,SACzC,IAAI,CAACA,SAAS,KACX1G,IAAI,CAACC,SAAS,CAACpH,KAAK,CAAC,EAC5B,CAAC;IACH;IAEA,IAAI,CAAC8M,SAAS,CAAC/M,KAAK,CAACC,KAAK,CAACuN,MAAM,CAAC,CAAC,EAAEtN,MAAM,CAAC;IAC5CD,KAAK,CAACwN,OAAO,CAAC,CAAC,CAACzN,KAAK,CAACC,KAAK,CAACA,KAAK,CAAC,CAAC,EAAEC,MAAM,CAAC;EAC9C;;EAEA;AACF;AACA;EACE,OAAOG,OAAOA,CAACJ,KAAK,EAAE;IACpB,OACEA,KAAK,EAAEX,WAAW,EAAEwO,SAAS,KAAK,IAAI,CAACA,SAAS,IAChD9G,4DAAiB,CAAC/G,KAAK,EAAE,IAAI,CAAC;EAElC;EAEA,OAAOmE,MAAMA,CAAC1B,OAAO,EAAEF,IAAI,EAAEgB,MAAM,EAAE;IACnC,MAAMuK,UAAU,GAAG,cAActJ,KAAK,CAAC,EAAE;IAEzCsJ,UAAU,CAACD,SAAS,GAAGtL,IAAI;IAC3BE,OAAO,CAACe,OAAO,CAACjB,IAAI,CAAC,GAAGuL,UAAU;IAElC,IAAIvK,MAAM,CAACwK,QAAQ,YAAY3L,iDAAS,EAAE;MACxC0L,UAAU,CAAChB,SAAS,GAAGvJ,MAAM,CAACwK,QAAQ,CAACvL,OAAO,CAACC,OAAO,CAAC;IACzD,CAAC,MAAM;MACLqL,UAAU,CAAChB,SAAS,GAAGvJ,MAAM,CAACwK,QAAQ;IACxC;IAEAD,UAAU,CAACJ,SAAS,GAAG,IAAIM,GAAG,CAAC,CAAC;IAChCF,UAAU,CAACV,KAAK,GAAG,CAAC,CAAC;;IAErB;IACA,IAAIa,UAAU,GAAG1K,MAAM,CAAC0K,UAAU;IAClC,IAAIA,UAAU,YAAY7L,iDAAS,EAAE;MACnC6L,UAAU,GAAGA,UAAU,CAACzL,OAAO,CAACC,OAAO,CAAC;IAC1C;IAEAqL,UAAU,CAACH,WAAW,GAAGM,UAAU;IAEnC,KAAK,MAAM,CAACrB,OAAO,EAAEU,OAAO,CAAC,IAAI/J,MAAM,CAAC2K,QAAQ,EAAE;MAChD,MAAMzG,GAAG,GACP,OAAOmF,OAAO,KAAK,QAAQ,GACvBkB,UAAU,CAAChB,SAAS,CAACxF,QAAQ,CAACsF,OAAO,CAAC,GACtCA,OAAO;MAEbkB,UAAU,CAACJ,SAAS,CAACb,GAAG,CAACpF,GAAG,EAAE6F,OAAO,CAAC;IACxC;;IAEA;IACA;IACA;IACA;IACA,IAAIQ,UAAU,CAAChB,SAAS,CAACrG,MAAM,KAAKH,SAAS,EAAE;MAC7C,KAAK,MAAMsG,OAAO,IAAIkB,UAAU,CAAChB,SAAS,CAACrG,MAAM,CAAC,CAAC,EAAE;QACnD;QACAqH,UAAU,CAAClB,OAAO,CAACrK,IAAI,CAAC,GAAG,SAAS4L,GAAGA,CAACnO,KAAK,EAAE;UAC7C,OAAO,IAAI8N,UAAU,CAAClB,OAAO,EAAE5M,KAAK,CAAC;QACvC,CAAC;;QAED;QACA8N,UAAU,CAAC5E,SAAS,CAAC0D,OAAO,CAACrK,IAAI,CAAC,GAAG,SAASsK,GAAGA,CAAC7M,KAAK,EAAE;UACvD,OAAO,IAAI,CAAC6M,GAAG,CAACD,OAAO,EAAE5M,KAAK,CAAC;QACjC,CAAC;MACH;IACF;IAEA,IAAIuD,MAAM,CAAC6K,IAAI,EAAE;MACf,KAAK,MAAM,CAACC,QAAQ,EAAErO,KAAK,CAAC,IAAIwG,MAAM,CAACkB,OAAO,CAACnE,MAAM,CAAC6K,IAAI,CAAC,EAAE;QAC3DN,UAAU,CAACV,KAAK,CAACiB,QAAQ,CAAC,GACxBrO,KAAK,YAAYoC,iDAAS,GAAGpC,KAAK,CAACwC,OAAO,CAACC,OAAO,CAAC,GAAGzC,KAAK;QAC7D;QACA,IAAIA,KAAK,KAAK4E,uCAAI,EAAE;UAClBkJ,UAAU,CAAC5E,SAAS,CAACmF,QAAQ,CAAC,GAAG,SAAShB,GAAGA,CAAA,EAAG;YAC9C,OAAO,IAAI,CAACA,GAAG,CAACgB,QAAQ,CAAC;UAC3B,CAAC;QACH;MACF;IACF;IAEA,OAAOP,UAAU;EACnB;AACF;;;;;;;;;;;;;;;;AC1KuC;AAEhC,MAAM1I,aAAa,SAAS4C,gDAAQ,CAAC;EAC1C;AACF;AACA;EACE3I,WAAWA,CAAC,GAAG4I,IAAI,EAAE;IACnB,KAAK,CAACA,IAAI,CAAC;EACb;EAEA,IAAIC,GAAGA,CAAA,EAAG;IACR,OAAOC,MAAM,CAAC,IAAI,CAACC,MAAM,GAAG,WAAW,CAAC,IAAI,CAAC;EAC/C;EAEA,IAAIC,IAAIA,CAAA,EAAG;IACT,OAAOF,MAAM,CAAC,IAAI,CAACC,MAAM,IAAI,GAAG,CAAC,IAAI,CAAC;EACxC;EAEA,IAAI7H,IAAIA,CAAA,EAAG;IACT,OAAO,EAAE;EACX;EAEA,IAAIC,QAAQA,CAAA,EAAG;IACb,OAAO,IAAI;EACb;;EAEA;AACF;AACA;AACA;AACA;AACA;EACE,OAAO8H,QAAQA,CAACJ,GAAG,EAAEG,IAAI,EAAE;IACzB,OAAO,IAAI,IAAI,CAACH,GAAG,EAAEG,IAAI,CAAC;EAC5B;AACF;AAEAjD,aAAa,CAACmD,mBAAmB,CAAC,CAAC;;;;;;;;;;;;;;;;;ACrCW;AACJ;AAE1C,MAAMG,SAAS,GAAG,UAAU;AAC5B,MAAMC,SAAS,GAAG,CAAC;AAEZ,MAAMzD,WAAW,SAAStD,uDAAgB,CAAC;EAChD;AACF;AACA;EACE,OAAOlC,IAAIA,CAACC,MAAM,EAAE;IAClB,OAAOA,MAAM,CAAC4K,YAAY,CAAC,CAAC;EAC9B;;EAEA;AACF;AACA;EACE,OAAOxK,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IAC1B,IACE,OAAOD,KAAK,KAAK,QAAQ,IACzB,EAAEA,KAAK,IAAI2I,SAAS,IAAI3I,KAAK,IAAI0I,SAAS,CAAC,IAC3C1I,KAAK,GAAG,CAAC,KAAK,CAAC,EAEf,MAAM,IAAIb,mDAAc,CAAC,mBAAmB,CAAC;IAE/Cc,MAAM,CAACwL,aAAa,CAACzL,KAAK,CAAC;EAC7B;;EAEA;AACF;AACA;EACE,OAAOI,OAAOA,CAACJ,KAAK,EAAE;IACpB,IAAI,OAAOA,KAAK,KAAK,QAAQ,IAAIA,KAAK,GAAG,CAAC,KAAK,CAAC,EAAE;MAChD,OAAO,KAAK;IACd;IAEA,OAAOA,KAAK,IAAI2I,SAAS,IAAI3I,KAAK,IAAI0I,SAAS;EACjD;AACF;AAEAxD,WAAW,CAACwD,SAAS,GAAGA,SAAS;AACjCxD,WAAW,CAACyD,SAAS,GAAGA,SAAS;;;;;;;;;;;;;;;;;;ACzCY;AACC;AACY;AAEnD,MAAM3F,QAAQ,SAAS9D,uDAAgB,CAAC;EAC7CG,WAAWA,CAACC,SAAS,EAAE6G,SAAS,GAAGjB,sDAAW,CAACwD,SAAS,EAAE;IACxD,KAAK,CAAC,CAAC;IACP,IAAI,CAAClJ,UAAU,GAAGF,SAAS;IAC3B,IAAI,CAACqM,UAAU,GAAGxF,SAAS;EAC7B;;EAEA;AACF;AACA;EACEzG,IAAIA,CAACC,MAAM,EAAE;IACX,MAAMJ,MAAM,GAAG2F,sDAAW,CAACxF,IAAI,CAACC,MAAM,CAAC;IACvC,IAAIJ,MAAM,GAAG,IAAI,CAACoM,UAAU,EAC1B,MAAM,IAAI9J,mDAAc,CACtB,OAAOtC,MAAM,oCAAoC,IAAI,CAACoM,UAAU,EAClE,CAAC;IAEH,MAAM/L,MAAM,GAAG,IAAIR,KAAK,CAACG,MAAM,CAAC;IAChC,KAAK,IAAIO,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGP,MAAM,EAAEO,CAAC,EAAE,EAAE;MAC/BF,MAAM,CAACE,CAAC,CAAC,GAAG,IAAI,CAACN,UAAU,CAACE,IAAI,CAACC,MAAM,CAAC;IAC1C;IACA,OAAOC,MAAM;EACf;;EAEA;AACF;AACA;EACEG,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IACnB,IAAI,EAAED,KAAK,YAAYZ,KAAK,CAAC,EAC3B,MAAM,IAAID,mDAAc,CAAC,oBAAoB,CAAC;IAEhD,IAAIa,KAAK,CAACT,MAAM,GAAG,IAAI,CAACoM,UAAU,EAChC,MAAM,IAAIxM,mDAAc,CACtB,qBAAqBa,KAAK,CAACT,MAAM,oBAAoB,IAAI,CAACoM,UAAU,EACtE,CAAC;IAEHzG,sDAAW,CAACnF,KAAK,CAACC,KAAK,CAACT,MAAM,EAAEU,MAAM,CAAC;IACvC,KAAK,MAAME,KAAK,IAAIH,KAAK,EAAE;MACzB,IAAI,CAACR,UAAU,CAACO,KAAK,CAACI,KAAK,EAAEF,MAAM,CAAC;IACtC;EACF;;EAEA;AACF;AACA;EACEG,OAAOA,CAACJ,KAAK,EAAE;IACb,IAAI,EAAEA,KAAK,YAAYZ,KAAK,CAAC,IAAIY,KAAK,CAACT,MAAM,GAAG,IAAI,CAACoM,UAAU,EAAE;MAC/D,OAAO,KAAK;IACd;IACA,KAAK,MAAMxL,KAAK,IAAIH,KAAK,EAAE;MACzB,IAAI,CAAC,IAAI,CAACR,UAAU,CAACY,OAAO,CAACD,KAAK,CAAC,EAAE,OAAO,KAAK;IACnD;IACA,OAAO,IAAI;EACb;AACF;;;;;;;;;;;;;;;;;;AC1D6C;AACC;AACY;AAEnD,MAAM6F,SAAS,SAAS9G,uDAAgB,CAAC;EAC9CG,WAAWA,CAAC8G,SAAS,GAAGjB,sDAAW,CAACwD,SAAS,EAAE;IAC7C,KAAK,CAAC,CAAC;IACP,IAAI,CAACiD,UAAU,GAAGxF,SAAS;EAC7B;;EAEA;AACF;AACA;EACEzG,IAAIA,CAACC,MAAM,EAAE;IACX,MAAMY,IAAI,GAAG2E,sDAAW,CAACxF,IAAI,CAACC,MAAM,CAAC;IACrC,IAAIY,IAAI,GAAG,IAAI,CAACoL,UAAU,EACxB,MAAM,IAAI9J,mDAAc,CACtB,OAAOtB,IAAI,qCAAqC,IAAI,CAACoL,UAAU,EACjE,CAAC;IACH,OAAOhM,MAAM,CAACD,IAAI,CAACa,IAAI,CAAC;EAC1B;;EAEA;AACF;AACA;EACER,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IACnB,MAAM;MAAEV;IAAO,CAAC,GAAGS,KAAK;IACxB,IAAIA,KAAK,CAACT,MAAM,GAAG,IAAI,CAACoM,UAAU,EAChC,MAAM,IAAIxM,mDAAc,CACtB,OAAOa,KAAK,CAACT,MAAM,0BAA0B,IAAI,CAACoM,UAAU,EAC9D,CAAC;IACH;IACAzG,sDAAW,CAACnF,KAAK,CAACR,MAAM,EAAEU,MAAM,CAAC;IACjCA,MAAM,CAACF,KAAK,CAACC,KAAK,EAAET,MAAM,CAAC;EAC7B;;EAEA;AACF;AACA;EACEa,OAAOA,CAACJ,KAAK,EAAE;IACb,OAAO0J,MAAM,CAACC,QAAQ,CAAC3J,KAAK,CAAC,IAAIA,KAAK,CAACT,MAAM,IAAI,IAAI,CAACoM,UAAU;EAClE;AACF;;;;;;;;;;;;;;;;;AC1C8C;AACJ;AAEnC,MAAM/G,IAAI,SAAShD,uDAAgB,CAAC;EACzC;;EAEA,OAAOlC,IAAIA,CAAA,EAAG;IACZ,OAAO4G,SAAS;EAClB;EAEA,OAAOvG,KAAKA,CAACC,KAAK,EAAE;IAClB,IAAIA,KAAK,KAAKsG,SAAS,EACrB,MAAM,IAAInH,mDAAc,CAAC,sCAAsC,CAAC;EACpE;EAEA,OAAOiB,OAAOA,CAACJ,KAAK,EAAE;IACpB,OAAOA,KAAK,KAAKsG,SAAS;EAC5B;AACF;;;;;;;;;;;;;;;;;;;;;AClBuD;AACA;AACK;AAE5D,MAAMgI,OAAO,CAAC;EACZ;AACF;AACA;AACA;AACA;EACEC,KAAKA,CAACC,MAAM,GAAG,KAAK,EAAE;IACpB,IAAI,CAAC,IAAI,CAACzO,KAAK,EAAE,OAAO,IAAI,CAACV,WAAW,CAACkP,KAAK,CAAC,IAAI,EAAEC,MAAM,CAAC;IAE5D,MAAMvO,MAAM,GAAG,IAAIwI,gEAAS,CAAC,CAAC;IAC9B,IAAI,CAAC1I,KAAK,CAAC,IAAI,EAAEE,MAAM,CAAC;IACxB,OAAOwO,YAAY,CAACxO,MAAM,CAACoL,QAAQ,CAAC,CAAC,EAAEmD,MAAM,CAAC;EAChD;;EAEA;AACF;AACA;AACA;AACA;AACA;EACEE,OAAOA,CAACC,KAAK,EAAEH,MAAM,GAAG,KAAK,EAAE;IAC7B,IAAI,CAAC,IAAI,CAAC9O,IAAI,EAAE,OAAO,IAAI,CAACL,WAAW,CAACqP,OAAO,CAACC,KAAK,EAAEH,MAAM,CAAC;IAE9D,MAAM7O,MAAM,GAAG,IAAI6I,gEAAS,CAACoG,WAAW,CAACD,KAAK,EAAEH,MAAM,CAAC,CAAC;IACxD,MAAM5O,MAAM,GAAG,IAAI,CAACF,IAAI,CAACC,MAAM,CAAC;IAChCA,MAAM,CAAC8K,mBAAmB,CAAC,CAAC;IAC5B,OAAO7K,MAAM;EACf;;EAEA;AACF;AACA;AACA;AACA;AACA;EACEiP,WAAWA,CAACF,KAAK,EAAEH,MAAM,GAAG,KAAK,EAAE;IACjC,IAAI;MACF,IAAI,CAACE,OAAO,CAACC,KAAK,EAAEH,MAAM,CAAC;MAC3B,OAAO,IAAI;IACb,CAAC,CAAC,OAAO1N,CAAC,EAAE;MACV,OAAO,KAAK;IACd;EACF;;EAEA;AACF;AACA;AACA;AACA;AACA;EACE,OAAOyN,KAAKA,CAACvO,KAAK,EAAEwO,MAAM,GAAG,KAAK,EAAE;IAClC,MAAMvO,MAAM,GAAG,IAAIwI,gEAAS,CAAC,CAAC;IAC9B,IAAI,CAAC1I,KAAK,CAACC,KAAK,EAAEC,MAAM,CAAC;IACzB,OAAOwO,YAAY,CAACxO,MAAM,CAACoL,QAAQ,CAAC,CAAC,EAAEmD,MAAM,CAAC;EAChD;;EAEA;AACF;AACA;AACA;AACA;AACA;EACE,OAAOE,OAAOA,CAACC,KAAK,EAAEH,MAAM,GAAG,KAAK,EAAE;IACpC,MAAM7O,MAAM,GAAG,IAAI6I,gEAAS,CAACoG,WAAW,CAACD,KAAK,EAAEH,MAAM,CAAC,CAAC;IACxD,MAAM5O,MAAM,GAAG,IAAI,CAACF,IAAI,CAACC,MAAM,CAAC;IAChCA,MAAM,CAAC8K,mBAAmB,CAAC,CAAC;IAC5B,OAAO7K,MAAM;EACf;;EAEA;AACF;AACA;AACA;AACA;AACA;EACE,OAAOiP,WAAWA,CAACF,KAAK,EAAEH,MAAM,GAAG,KAAK,EAAE;IACxC,IAAI;MACF,IAAI,CAACE,OAAO,CAACC,KAAK,EAAEH,MAAM,CAAC;MAC3B,OAAO,IAAI;IACb,CAAC,CAAC,OAAO1N,CAAC,EAAE;MACV,OAAO,KAAK;IACd;EACF;AACF;AAEO,MAAMc,gBAAgB,SAAS0M,OAAO,CAAC;EAC5C;AACF;AACA;AACA;AACA;AACA;EACE;EACA,OAAO5O,IAAIA,CAACC,MAAM,EAAE;IAClB,MAAM,IAAIkI,qEAAgC,CAAC,CAAC;EAC9C;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;EACE;EACA,OAAO9H,KAAKA,CAACC,KAAK,EAAEC,MAAM,EAAE;IAC1B,MAAM,IAAI4H,qEAAgC,CAAC,CAAC;EAC9C;;EAEA;AACF;AACA;AACA;AACA;AACA;EACE;EACA,OAAOzH,OAAOA,CAACJ,KAAK,EAAE;IACpB,OAAO,KAAK;EACd;AACF;AAEO,MAAMd,gBAAgB,SAASoP,OAAO,CAAC;EAC5C;;EAEA;AACF;AACA;AACA;AACA;AACA;EACE;EACAlO,OAAOA,CAACJ,KAAK,EAAE;IACb,OAAO,KAAK;EACd;AACF;AAEA,MAAM8O,6BAA6B,SAAS/N,SAAS,CAAC;EACpD1B,WAAWA,CAACmP,MAAM,EAAE;IAClB,KAAK,CAAC,kBAAkBA,MAAM,yCAAyC,CAAC;EAC1E;AACF;AAEA,SAASC,YAAYA,CAAC9D,MAAM,EAAE6D,MAAM,EAAE;EACpC,QAAQA,MAAM;IACZ,KAAK,KAAK;MACR,OAAO7D,MAAM;IACf,KAAK,KAAK;MACR,OAAOA,MAAM,CAAC5B,QAAQ,CAAC,KAAK,CAAC;IAC/B,KAAK,QAAQ;MACX,OAAO4B,MAAM,CAAC5B,QAAQ,CAAC,QAAQ,CAAC;IAClC;MACE,MAAM,IAAI+F,6BAA6B,CAACN,MAAM,CAAC;EACnD;AACF;AAEA,SAASI,WAAWA,CAACD,KAAK,EAAEH,MAAM,EAAE;EAClC,QAAQA,MAAM;IACZ,KAAK,KAAK;MACR,OAAOG,KAAK;IACd,KAAK,KAAK;MACR,OAAOjF,MAAM,CAACN,IAAI,CAACuF,KAAK,EAAE,KAAK,CAAC;IAClC,KAAK,QAAQ;MACX,OAAOjF,MAAM,CAACN,IAAI,CAACuF,KAAK,EAAE,QAAQ,CAAC;IACrC;MACE,MAAM,IAAIG,6BAA6B,CAACN,MAAM,CAAC;EACnD;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASzH,iBAAiBA,CAAC/G,KAAK,EAAE+O,OAAO,EAAE;EAChD,OACE/O,KAAK,KAAKsG,SAAS,IACnBtG,KAAK,KAAK,IAAI;EAAI;EACjBA,KAAK,YAAY+O,OAAO;EAAI;EAC3B;EACA;EACCC,cAAc,CAAChP,KAAK,EAAE+O,OAAO,CAAC;EAC7B;EACA,OAAO/O,KAAK,CAACX,WAAW,CAACK,IAAI,KAAK,UAAU,IAC5C,OAAOM,KAAK,CAACX,WAAW,CAACU,KAAK,KAAK,UAAU;EAC7C;EACAiP,cAAc,CAAChP,KAAK,EAAE,SAAS,CAAE,CAAC;AAE1C;;AAEA;AACO,SAASgP,cAAcA,CAACC,QAAQ,EAAEF,OAAO,EAAE;EAChD,GAAG;IACD,MAAMG,IAAI,GAAGD,QAAQ,CAAC5P,WAAW;IACjC,IAAI6P,IAAI,CAAC3M,IAAI,KAAKwM,OAAO,EAAE;MACzB,OAAO,IAAI;IACb;EACF,CAAC,QAASE,QAAQ,GAAGzI,MAAM,CAAC2I,cAAc,CAACF,QAAQ,CAAC;EACpD,OAAO,KAAK;AACd;;AAEA;AACA;AACA;;;;;;UCxNA;UACA;;UAEA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;;UAEA;UACA;;UAEA;UACA;UACA;;;;;WCtBA;WACA;WACA;WACA;WACA,yCAAyC,wCAAwC;WACjF;WACA;WACA;;;;;WCPA;;;;;WCAA;WACA;WACA;WACA,uDAAuD,iBAAiB;WACxE;WACA,gDAAgD,aAAa;WAC7D;;;;;UENA;UACA;UACA;UACA","sources":["webpack://XDR/webpack/universalModuleDefinition","webpack://XDR/./src/array.js","webpack://XDR/./src/bigint-encoder.js","webpack://XDR/./src/bool.js","webpack://XDR/./src/browser.js","webpack://XDR/./src/config.js","webpack://XDR/./src/double.js","webpack://XDR/./src/enum.js","webpack://XDR/./src/errors.js","webpack://XDR/./src/float.js","webpack://XDR/./src/hyper.js","webpack://XDR/./src/index.js","webpack://XDR/./src/int.js","webpack://XDR/./src/large-int.js","webpack://XDR/./src/opaque.js","webpack://XDR/./src/option.js","webpack://XDR/./src/quadruple.js","webpack://XDR/./src/reference.js","webpack://XDR/./src/serialization/xdr-reader.js","webpack://XDR/./src/serialization/xdr-writer.js","webpack://XDR/./src/string.js","webpack://XDR/./src/struct.js","webpack://XDR/./src/types.js","webpack://XDR/./src/union.js","webpack://XDR/./src/unsigned-hyper.js","webpack://XDR/./src/unsigned-int.js","webpack://XDR/./src/var-array.js","webpack://XDR/./src/var-opaque.js","webpack://XDR/./src/void.js","webpack://XDR/./src/xdr-type.js","webpack://XDR/webpack/bootstrap","webpack://XDR/webpack/runtime/define property getters","webpack://XDR/webpack/runtime/hasOwnProperty shorthand","webpack://XDR/webpack/runtime/make namespace object","webpack://XDR/webpack/before-startup","webpack://XDR/webpack/startup","webpack://XDR/webpack/after-startup"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"XDR\"] = factory();\n\telse\n\t\troot[\"XDR\"] = factory();\n})(this, () => {\nreturn ","import { XdrCompositeType } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nexport class Array extends XdrCompositeType {\n constructor(childType, length) {\n super();\n this._childType = childType;\n this._length = length;\n }\n\n /**\n * @inheritDoc\n */\n read(reader) {\n // allocate array of specified length\n const result = new global.Array(this._length);\n // read values\n for (let i = 0; i < this._length; i++) {\n result[i] = this._childType.read(reader);\n }\n return result;\n }\n\n /**\n * @inheritDoc\n */\n write(value, writer) {\n if (!global.Array.isArray(value))\n throw new XdrWriterError(`value is not array`);\n\n if (value.length !== this._length)\n throw new XdrWriterError(\n `got array of size ${value.length}, expected ${this._length}`\n );\n\n for (const child of value) {\n this._childType.write(child, writer);\n }\n }\n\n /**\n * @inheritDoc\n */\n isValid(value) {\n if (!(value instanceof global.Array) || value.length !== this._length) {\n return false;\n }\n\n for (const child of value) {\n if (!this._childType.isValid(child)) return false;\n }\n return true;\n }\n}\n","/**\n * Encode a native `bigint` value from a list of arbitrary integer-like values.\n *\n * @param {Array} parts - Slices to encode in big-endian\n * format (i.e. earlier elements are higher bits)\n * @param {64|128|256} size - Number of bits in the target integer type\n * @param {boolean} unsigned - Whether it's an unsigned integer\n *\n * @returns {bigint}\n */\nexport function encodeBigIntFromBits(parts, size, unsigned) {\n if (!(parts instanceof Array)) {\n // allow a single parameter instead of an array\n parts = [parts];\n } else if (parts.length && parts[0] instanceof Array) {\n // unpack nested array param\n parts = parts[0];\n }\n\n const total = parts.length;\n const sliceSize = size / total;\n switch (sliceSize) {\n case 32:\n case 64:\n case 128:\n case 256:\n break;\n\n default:\n throw new RangeError(\n `expected slices to fit in 32/64/128/256 bits, got ${parts}`\n );\n }\n\n // normalize all inputs to bigint\n try {\n for (let i = 0; i < parts.length; i++) {\n if (typeof parts[i] !== 'bigint') {\n parts[i] = BigInt(parts[i].valueOf());\n }\n }\n } catch (e) {\n throw new TypeError(`expected bigint-like values, got: ${parts} (${e})`);\n }\n\n // check for sign mismatches for single inputs (this is a special case to\n // handle one parameter passed to e.g. UnsignedHyper et al.)\n // see https://github.com/stellar/js-xdr/pull/100#discussion_r1228770845\n if (unsigned && parts.length === 1 && parts[0] < 0n) {\n throw new RangeError(`expected a positive value, got: ${parts}`);\n }\n\n // encode in big-endian fashion, shifting each slice by the slice size\n let result = BigInt.asUintN(sliceSize, parts[0]); // safe: len >= 1\n for (let i = 1; i < parts.length; i++) {\n result |= BigInt.asUintN(sliceSize, parts[i]) << BigInt(i * sliceSize);\n }\n\n // interpret value as signed if necessary and clamp it\n if (!unsigned) {\n result = BigInt.asIntN(size, result);\n }\n\n // check boundaries\n const [min, max] = calculateBigIntBoundaries(size, unsigned);\n if (result >= min && result <= max) {\n return result;\n }\n\n // failed to encode\n throw new TypeError(\n `bigint values [${parts}] for ${formatIntName(\n size,\n unsigned\n )} out of range [${min}, ${max}]: ${result}`\n );\n}\n\n/**\n * Transforms a single bigint value that's supposed to represent a `size`-bit\n * integer into a list of `sliceSize`d chunks.\n *\n * @param {bigint} value - Single bigint value to decompose\n * @param {64|128|256} iSize - Number of bits represented by `value`\n * @param {32|64|128} sliceSize - Number of chunks to decompose into\n * @return {bigint[]}\n */\nexport function sliceBigInt(value, iSize, sliceSize) {\n if (typeof value !== 'bigint') {\n throw new TypeError(`Expected bigint 'value', got ${typeof value}`);\n }\n\n const total = iSize / sliceSize;\n if (total === 1) {\n return [value];\n }\n\n if (\n sliceSize < 32 ||\n sliceSize > 128 ||\n (total !== 2 && total !== 4 && total !== 8)\n ) {\n throw new TypeError(\n `invalid bigint (${value}) and slice size (${iSize} -> ${sliceSize}) combination`\n );\n }\n\n const shift = BigInt(sliceSize);\n\n // iterate shift and mask application\n const result = new Array(total);\n for (let i = 0; i < total; i++) {\n // we force a signed interpretation to preserve sign in each slice value,\n // but downstream can convert to unsigned if it's appropriate\n result[i] = BigInt.asIntN(sliceSize, value); // clamps to size\n\n // move on to the next chunk\n value >>= shift;\n }\n\n return result;\n}\n\nexport function formatIntName(precision, unsigned) {\n return `${unsigned ? 'u' : 'i'}${precision}`;\n}\n\n/**\n * Get min|max boundaries for an integer with a specified bits size\n * @param {64|128|256} size - Number of bits in the source integer type\n * @param {Boolean} unsigned - Whether it's an unsigned integer\n * @return {BigInt[]}\n */\nexport function calculateBigIntBoundaries(size, unsigned) {\n if (unsigned) {\n return [0n, (1n << BigInt(size)) - 1n];\n }\n\n const boundary = 1n << BigInt(size - 1);\n return [0n - boundary, boundary - 1n];\n}\n","import { Int } from './int';\nimport { XdrPrimitiveType } from './xdr-type';\nimport { XdrReaderError } from './errors';\n\nexport class Bool extends XdrPrimitiveType {\n /**\n * @inheritDoc\n */\n static read(reader) {\n const value = Int.read(reader);\n\n switch (value) {\n case 0:\n return false;\n case 1:\n return true;\n default:\n throw new XdrReaderError(`got ${value} when trying to read a bool`);\n }\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n const intVal = value ? 1 : 0;\n Int.write(intVal, writer);\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n return typeof value === 'boolean';\n }\n}\n","// eslint-disable-next-line prefer-import/prefer-import-over-require\nconst exports = require('./index');\nmodule.exports = exports;\n","// eslint-disable-next-line max-classes-per-file\nimport * as XDRTypes from './types';\nimport { Reference } from './reference';\nimport { XdrDefinitionError } from './errors';\n\nexport * from './reference';\n\nclass SimpleReference extends Reference {\n constructor(name) {\n super();\n this.name = name;\n }\n\n resolve(context) {\n const defn = context.definitions[this.name];\n return defn.resolve(context);\n }\n}\n\nclass ArrayReference extends Reference {\n constructor(childReference, length, variable = false) {\n super();\n this.childReference = childReference;\n this.length = length;\n this.variable = variable;\n }\n\n resolve(context) {\n let resolvedChild = this.childReference;\n let length = this.length;\n\n if (resolvedChild instanceof Reference) {\n resolvedChild = resolvedChild.resolve(context);\n }\n\n if (length instanceof Reference) {\n length = length.resolve(context);\n }\n\n if (this.variable) {\n return new XDRTypes.VarArray(resolvedChild, length);\n }\n return new XDRTypes.Array(resolvedChild, length);\n }\n}\n\nclass OptionReference extends Reference {\n constructor(childReference) {\n super();\n this.childReference = childReference;\n this.name = childReference.name;\n }\n\n resolve(context) {\n let resolvedChild = this.childReference;\n\n if (resolvedChild instanceof Reference) {\n resolvedChild = resolvedChild.resolve(context);\n }\n\n return new XDRTypes.Option(resolvedChild);\n }\n}\n\nclass SizedReference extends Reference {\n constructor(sizedType, length) {\n super();\n this.sizedType = sizedType;\n this.length = length;\n }\n\n resolve(context) {\n let length = this.length;\n\n if (length instanceof Reference) {\n length = length.resolve(context);\n }\n\n return new this.sizedType(length);\n }\n}\n\nclass Definition {\n constructor(constructor, name, cfg) {\n this.constructor = constructor;\n this.name = name;\n this.config = cfg;\n }\n\n // resolve calls the constructor of this definition with the provided context\n // and this definitions config values. The definitions constructor should\n // populate the final type on `context.results`, and may refer to other\n // definitions through `context.definitions`\n resolve(context) {\n if (this.name in context.results) {\n return context.results[this.name];\n }\n\n return this.constructor(context, this.name, this.config);\n }\n}\n\n// let the reference resolution system do its thing\n// the \"constructor\" for a typedef just returns the resolved value\nfunction createTypedef(context, typeName, value) {\n if (value instanceof Reference) {\n value = value.resolve(context);\n }\n context.results[typeName] = value;\n return value;\n}\n\nfunction createConst(context, name, value) {\n context.results[name] = value;\n return value;\n}\n\nclass TypeBuilder {\n constructor(destination) {\n this._destination = destination;\n this._definitions = {};\n }\n\n enum(name, members) {\n const result = new Definition(XDRTypes.Enum.create, name, members);\n this.define(name, result);\n }\n\n struct(name, members) {\n const result = new Definition(XDRTypes.Struct.create, name, members);\n this.define(name, result);\n }\n\n union(name, cfg) {\n const result = new Definition(XDRTypes.Union.create, name, cfg);\n this.define(name, result);\n }\n\n typedef(name, cfg) {\n const result = new Definition(createTypedef, name, cfg);\n this.define(name, result);\n }\n\n const(name, cfg) {\n const result = new Definition(createConst, name, cfg);\n this.define(name, result);\n }\n\n void() {\n return XDRTypes.Void;\n }\n\n bool() {\n return XDRTypes.Bool;\n }\n\n int() {\n return XDRTypes.Int;\n }\n\n hyper() {\n return XDRTypes.Hyper;\n }\n\n uint() {\n return XDRTypes.UnsignedInt;\n }\n\n uhyper() {\n return XDRTypes.UnsignedHyper;\n }\n\n float() {\n return XDRTypes.Float;\n }\n\n double() {\n return XDRTypes.Double;\n }\n\n quadruple() {\n return XDRTypes.Quadruple;\n }\n\n string(length) {\n return new SizedReference(XDRTypes.String, length);\n }\n\n opaque(length) {\n return new SizedReference(XDRTypes.Opaque, length);\n }\n\n varOpaque(length) {\n return new SizedReference(XDRTypes.VarOpaque, length);\n }\n\n array(childType, length) {\n return new ArrayReference(childType, length);\n }\n\n varArray(childType, maxLength) {\n return new ArrayReference(childType, maxLength, true);\n }\n\n option(childType) {\n return new OptionReference(childType);\n }\n\n define(name, definition) {\n if (this._destination[name] === undefined) {\n this._definitions[name] = definition;\n } else {\n throw new XdrDefinitionError(`${name} is already defined`);\n }\n }\n\n lookup(name) {\n return new SimpleReference(name);\n }\n\n resolve() {\n for (const defn of Object.values(this._definitions)) {\n defn.resolve({\n definitions: this._definitions,\n results: this._destination\n });\n }\n }\n}\n\nexport function config(fn, types = {}) {\n if (fn) {\n const builder = new TypeBuilder(types);\n fn(builder);\n builder.resolve();\n }\n\n return types;\n}\n","import { XdrPrimitiveType } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nexport class Double extends XdrPrimitiveType {\n /**\n * @inheritDoc\n */\n static read(reader) {\n return reader.readDoubleBE();\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (typeof value !== 'number') throw new XdrWriterError('not a number');\n\n writer.writeDoubleBE(value);\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n return typeof value === 'number';\n }\n}\n","import { Int } from './int';\nimport { XdrPrimitiveType, isSerializableIsh } from './xdr-type';\nimport { XdrReaderError, XdrWriterError } from './errors';\n\nexport class Enum extends XdrPrimitiveType {\n constructor(name, value) {\n super();\n this.name = name;\n this.value = value;\n }\n\n /**\n * @inheritDoc\n */\n static read(reader) {\n const intVal = Int.read(reader);\n const res = this._byValue[intVal];\n if (res === undefined)\n throw new XdrReaderError(\n `unknown ${this.enumName} member for value ${intVal}`\n );\n return res;\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (!this.isValid(value)) {\n throw new XdrWriterError(\n `${value} has enum name ${value?.enumName}, not ${\n this.enumName\n }: ${JSON.stringify(value)}`\n );\n }\n\n Int.write(value.value, writer);\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n return (\n value?.constructor?.enumName === this.enumName ||\n isSerializableIsh(value, this)\n );\n }\n\n static members() {\n return this._members;\n }\n\n static values() {\n return Object.values(this._members);\n }\n\n static fromName(name) {\n const result = this._members[name];\n\n if (!result)\n throw new TypeError(`${name} is not a member of ${this.enumName}`);\n\n return result;\n }\n\n static fromValue(value) {\n const result = this._byValue[value];\n if (result === undefined)\n throw new TypeError(\n `${value} is not a value of any member of ${this.enumName}`\n );\n return result;\n }\n\n static create(context, name, members) {\n const ChildEnum = class extends Enum {};\n\n ChildEnum.enumName = name;\n context.results[name] = ChildEnum;\n\n ChildEnum._members = {};\n ChildEnum._byValue = {};\n\n for (const [key, value] of Object.entries(members)) {\n const inst = new ChildEnum(key, value);\n ChildEnum._members[key] = inst;\n ChildEnum._byValue[value] = inst;\n ChildEnum[key] = () => inst;\n }\n\n return ChildEnum;\n }\n}\n","export class XdrWriterError extends TypeError {\n constructor(message) {\n super(`XDR Write Error: ${message}`);\n }\n}\n\nexport class XdrReaderError extends TypeError {\n constructor(message) {\n super(`XDR Read Error: ${message}`);\n }\n}\n\nexport class XdrDefinitionError extends TypeError {\n constructor(message) {\n super(`XDR Type Definition Error: ${message}`);\n }\n}\n\nexport class XdrNotImplementedDefinitionError extends XdrDefinitionError {\n constructor() {\n super(\n `method not implemented, it should be overloaded in the descendant class.`\n );\n }\n}\n","import { XdrPrimitiveType } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nexport class Float extends XdrPrimitiveType {\n /**\n * @inheritDoc\n */\n static read(reader) {\n return reader.readFloatBE();\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (typeof value !== 'number') throw new XdrWriterError('not a number');\n\n writer.writeFloatBE(value);\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n return typeof value === 'number';\n }\n}\n","import { LargeInt } from './large-int';\n\nexport class Hyper extends LargeInt {\n /**\n * @param {Array} parts - Slices to encode\n */\n constructor(...args) {\n super(args);\n }\n\n get low() {\n return Number(this._value & 0xffffffffn) << 0;\n }\n\n get high() {\n return Number(this._value >> 32n) >> 0;\n }\n\n get size() {\n return 64;\n }\n\n get unsigned() {\n return false;\n }\n\n /**\n * Create Hyper instance from two [high][low] i32 values\n * @param {Number} low - Low part of i64 number\n * @param {Number} high - High part of i64 number\n * @return {LargeInt}\n */\n static fromBits(low, high) {\n return new this(low, high);\n }\n}\n\nHyper.defineIntBoundaries();\n","export * from './types';\nexport * from './config';\n\nexport { XdrReader } from './serialization/xdr-reader';\nexport { XdrWriter } from './serialization/xdr-writer';\n","import { XdrPrimitiveType } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nconst MAX_VALUE = 2147483647;\nconst MIN_VALUE = -2147483648;\n\nexport class Int extends XdrPrimitiveType {\n /**\n * @inheritDoc\n */\n static read(reader) {\n return reader.readInt32BE();\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (typeof value !== 'number') throw new XdrWriterError('not a number');\n\n if ((value | 0) !== value) throw new XdrWriterError('invalid i32 value');\n\n writer.writeInt32BE(value);\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n if (typeof value !== 'number' || (value | 0) !== value) {\n return false;\n }\n\n return value >= MIN_VALUE && value <= MAX_VALUE;\n }\n}\n\nInt.MAX_VALUE = MAX_VALUE;\nInt.MIN_VALUE = -MIN_VALUE;\n","import { XdrPrimitiveType } from './xdr-type';\nimport {\n calculateBigIntBoundaries,\n encodeBigIntFromBits,\n sliceBigInt\n} from './bigint-encoder';\nimport { XdrNotImplementedDefinitionError, XdrWriterError } from './errors';\n\nexport class LargeInt extends XdrPrimitiveType {\n /**\n * @param {Array} parts - Slices to encode\n */\n constructor(args) {\n super();\n this._value = encodeBigIntFromBits(args, this.size, this.unsigned);\n }\n\n /**\n * Signed/unsigned representation\n * @type {Boolean}\n * @abstract\n */\n get unsigned() {\n throw new XdrNotImplementedDefinitionError();\n }\n\n /**\n * Size of the integer in bits\n * @type {Number}\n * @abstract\n */\n get size() {\n throw new XdrNotImplementedDefinitionError();\n }\n\n /**\n * Slice integer to parts with smaller bit size\n * @param {32|64|128} sliceSize - Size of each part in bits\n * @return {BigInt[]}\n */\n slice(sliceSize) {\n return sliceBigInt(this._value, this.size, sliceSize);\n }\n\n toString() {\n return this._value.toString();\n }\n\n toJSON() {\n return { _value: this._value.toString() };\n }\n\n toBigInt() {\n return BigInt(this._value);\n }\n\n /**\n * @inheritDoc\n */\n static read(reader) {\n const { size } = this.prototype;\n if (size === 64) return new this(reader.readBigUInt64BE());\n return new this(\n ...Array.from({ length: size / 64 }, () =>\n reader.readBigUInt64BE()\n ).reverse()\n );\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (value instanceof this) {\n value = value._value;\n } else if (\n typeof value !== 'bigint' ||\n value > this.MAX_VALUE ||\n value < this.MIN_VALUE\n )\n throw new XdrWriterError(`${value} is not a ${this.name}`);\n\n const { unsigned, size } = this.prototype;\n if (size === 64) {\n if (unsigned) {\n writer.writeBigUInt64BE(value);\n } else {\n writer.writeBigInt64BE(value);\n }\n } else {\n for (const part of sliceBigInt(value, size, 64).reverse()) {\n if (unsigned) {\n writer.writeBigUInt64BE(part);\n } else {\n writer.writeBigInt64BE(part);\n }\n }\n }\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n return typeof value === 'bigint' || value instanceof this;\n }\n\n /**\n * Create instance from string\n * @param {String} string - Numeric representation\n * @return {LargeInt}\n */\n static fromString(string) {\n return new this(string);\n }\n\n static MAX_VALUE = 0n;\n\n static MIN_VALUE = 0n;\n\n /**\n * @internal\n * @return {void}\n */\n static defineIntBoundaries() {\n const [min, max] = calculateBigIntBoundaries(\n this.prototype.size,\n this.prototype.unsigned\n );\n this.MIN_VALUE = min;\n this.MAX_VALUE = max;\n }\n}\n","import { XdrCompositeType } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nexport class Opaque extends XdrCompositeType {\n constructor(length) {\n super();\n this._length = length;\n }\n\n /**\n * @inheritDoc\n */\n read(reader) {\n return reader.read(this._length);\n }\n\n /**\n * @inheritDoc\n */\n write(value, writer) {\n const { length } = value;\n if (length !== this._length)\n throw new XdrWriterError(\n `got ${value.length} bytes, expected ${this._length}`\n );\n writer.write(value, length);\n }\n\n /**\n * @inheritDoc\n */\n isValid(value) {\n return Buffer.isBuffer(value) && value.length === this._length;\n }\n}\n","import { Bool } from './bool';\nimport { XdrPrimitiveType } from './xdr-type';\n\nexport class Option extends XdrPrimitiveType {\n constructor(childType) {\n super();\n this._childType = childType;\n }\n\n /**\n * @inheritDoc\n */\n read(reader) {\n if (Bool.read(reader)) {\n return this._childType.read(reader);\n }\n\n return undefined;\n }\n\n /**\n * @inheritDoc\n */\n write(value, writer) {\n const isPresent = value !== null && value !== undefined;\n\n Bool.write(isPresent, writer);\n\n if (isPresent) {\n this._childType.write(value, writer);\n }\n }\n\n /**\n * @inheritDoc\n */\n isValid(value) {\n if (value === null || value === undefined) {\n return true;\n }\n return this._childType.isValid(value);\n }\n}\n","import { XdrPrimitiveType } from './xdr-type';\nimport { XdrDefinitionError } from './errors';\n\nexport class Quadruple extends XdrPrimitiveType {\n static read() {\n throw new XdrDefinitionError('quadruple not supported');\n }\n\n static write() {\n throw new XdrDefinitionError('quadruple not supported');\n }\n\n static isValid() {\n return false;\n }\n}\n","import { XdrPrimitiveType } from './xdr-type';\nimport { XdrDefinitionError } from './errors';\n\nexport class Reference extends XdrPrimitiveType {\n /* jshint unused: false */\n resolve() {\n throw new XdrDefinitionError(\n '\"resolve\" method should be implemented in the descendant class'\n );\n }\n}\n","/**\n * @internal\n */\nimport { XdrReaderError } from '../errors';\n\nexport class XdrReader {\n /**\n * @constructor\n * @param {Buffer} source - Buffer containing serialized data\n */\n constructor(source) {\n if (!Buffer.isBuffer(source)) {\n if (\n source instanceof Array ||\n Array.isArray(source) ||\n ArrayBuffer.isView(source)\n ) {\n source = Buffer.from(source);\n } else {\n throw new XdrReaderError(`source invalid: ${source}`);\n }\n }\n\n this._buffer = source;\n this._length = source.length;\n this._index = 0;\n }\n\n /**\n * @type {Buffer}\n * @private\n * @readonly\n */\n _buffer;\n /**\n * @type {Number}\n * @private\n * @readonly\n */\n _length;\n /**\n * @type {Number}\n * @private\n * @readonly\n */\n _index;\n\n /**\n * Check if the reader reached the end of the input buffer\n * @return {Boolean}\n */\n get eof() {\n return this._index === this._length;\n }\n\n /**\n * Advance reader position, check padding and overflow\n * @param {Number} size - Bytes to read\n * @return {Number} Position to read from\n * @private\n */\n advance(size) {\n const from = this._index;\n // advance cursor position\n this._index += size;\n // check buffer boundaries\n if (this._length < this._index)\n throw new XdrReaderError(\n 'attempt to read outside the boundary of the buffer'\n );\n // check that padding is correct for Opaque and String\n const padding = 4 - (size % 4 || 4);\n if (padding > 0) {\n for (let i = 0; i < padding; i++)\n if (this._buffer[this._index + i] !== 0)\n // all bytes in the padding should be zeros\n throw new XdrReaderError('invalid padding');\n this._index += padding;\n }\n return from;\n }\n\n /**\n * Reset reader position\n * @return {void}\n */\n rewind() {\n this._index = 0;\n }\n\n /**\n * Read byte array from the buffer\n * @param {Number} size - Bytes to read\n * @return {Buffer} - Sliced portion of the underlying buffer\n */\n read(size) {\n const from = this.advance(size);\n return this._buffer.subarray(from, from + size);\n }\n\n /**\n * Read i32 from buffer\n * @return {Number}\n */\n readInt32BE() {\n return this._buffer.readInt32BE(this.advance(4));\n }\n\n /**\n * Read u32 from buffer\n * @return {Number}\n */\n readUInt32BE() {\n return this._buffer.readUInt32BE(this.advance(4));\n }\n\n /**\n * Read i64 from buffer\n * @return {BigInt}\n */\n readBigInt64BE() {\n return this._buffer.readBigInt64BE(this.advance(8));\n }\n\n /**\n * Read u64 from buffer\n * @return {BigInt}\n */\n readBigUInt64BE() {\n return this._buffer.readBigUInt64BE(this.advance(8));\n }\n\n /**\n * Read float from buffer\n * @return {Number}\n */\n readFloatBE() {\n return this._buffer.readFloatBE(this.advance(4));\n }\n\n /**\n * Read double from buffer\n * @return {Number}\n */\n readDoubleBE() {\n return this._buffer.readDoubleBE(this.advance(8));\n }\n\n /**\n * Ensure that input buffer has been consumed in full, otherwise it's a type mismatch\n * @return {void}\n * @throws {XdrReaderError}\n */\n ensureInputConsumed() {\n if (this._index !== this._length)\n throw new XdrReaderError(\n `invalid XDR contract typecast - source buffer not entirely consumed`\n );\n }\n}\n","const BUFFER_CHUNK = 8192; // 8 KB chunk size increment\n\n/**\n * @internal\n */\nexport class XdrWriter {\n /**\n * @param {Buffer|Number} [buffer] - Optional destination buffer\n */\n constructor(buffer) {\n if (typeof buffer === 'number') {\n buffer = Buffer.allocUnsafe(buffer);\n } else if (!(buffer instanceof Buffer)) {\n buffer = Buffer.allocUnsafe(BUFFER_CHUNK);\n }\n this._buffer = buffer;\n this._length = buffer.length;\n }\n\n /**\n * @type {Buffer}\n * @private\n * @readonly\n */\n _buffer;\n /**\n * @type {Number}\n * @private\n * @readonly\n */\n _length;\n /**\n * @type {Number}\n * @private\n * @readonly\n */\n _index = 0;\n\n /**\n * Advance writer position, write padding if needed, auto-resize the buffer\n * @param {Number} size - Bytes to write\n * @return {Number} Position to read from\n * @private\n */\n alloc(size) {\n const from = this._index;\n // advance cursor position\n this._index += size;\n // ensure sufficient buffer size\n if (this._length < this._index) {\n this.resize(this._index);\n }\n return from;\n }\n\n /**\n * Increase size of the underlying buffer\n * @param {Number} minRequiredSize - Minimum required buffer size\n * @return {void}\n * @private\n */\n resize(minRequiredSize) {\n // calculate new length, align new buffer length by chunk size\n const newLength = Math.ceil(minRequiredSize / BUFFER_CHUNK) * BUFFER_CHUNK;\n // create new buffer and copy previous data\n const newBuffer = Buffer.allocUnsafe(newLength);\n this._buffer.copy(newBuffer, 0, 0, this._length);\n // update references\n this._buffer = newBuffer;\n this._length = newLength;\n }\n\n /**\n * Return XDR-serialized value\n * @return {Buffer}\n */\n finalize() {\n // clip underlying buffer to the actually written value\n return this._buffer.subarray(0, this._index);\n }\n\n /**\n * Return XDR-serialized value as byte array\n * @return {Number[]}\n */\n toArray() {\n return [...this.finalize()];\n }\n\n /**\n * Write byte array from the buffer\n * @param {Buffer|String} value - Bytes/string to write\n * @param {Number} size - Size in bytes\n * @return {XdrReader} - XdrReader wrapper on top of a subarray\n */\n write(value, size) {\n if (typeof value === 'string') {\n // serialize string directly to the output buffer\n const offset = this.alloc(size);\n this._buffer.write(value, offset, 'utf8');\n } else {\n // copy data to the output buffer\n if (!(value instanceof Buffer)) {\n value = Buffer.from(value);\n }\n const offset = this.alloc(size);\n value.copy(this._buffer, offset, 0, size);\n }\n\n // add padding for 4-byte XDR alignment\n const padding = 4 - (size % 4 || 4);\n if (padding > 0) {\n const offset = this.alloc(padding);\n this._buffer.fill(0, offset, this._index);\n }\n }\n\n /**\n * Write i32 from buffer\n * @param {Number} value - Value to serialize\n * @return {void}\n */\n writeInt32BE(value) {\n const offset = this.alloc(4);\n this._buffer.writeInt32BE(value, offset);\n }\n\n /**\n * Write u32 from buffer\n * @param {Number} value - Value to serialize\n * @return {void}\n */\n writeUInt32BE(value) {\n const offset = this.alloc(4);\n this._buffer.writeUInt32BE(value, offset);\n }\n\n /**\n * Write i64 from buffer\n * @param {BigInt} value - Value to serialize\n * @return {void}\n */\n writeBigInt64BE(value) {\n const offset = this.alloc(8);\n this._buffer.writeBigInt64BE(value, offset);\n }\n\n /**\n * Write u64 from buffer\n * @param {BigInt} value - Value to serialize\n * @return {void}\n */\n writeBigUInt64BE(value) {\n const offset = this.alloc(8);\n this._buffer.writeBigUInt64BE(value, offset);\n }\n\n /**\n * Write float from buffer\n * @param {Number} value - Value to serialize\n * @return {void}\n */\n writeFloatBE(value) {\n const offset = this.alloc(4);\n this._buffer.writeFloatBE(value, offset);\n }\n\n /**\n * Write double from buffer\n * @param {Number} value - Value to serialize\n * @return {void}\n */\n writeDoubleBE(value) {\n const offset = this.alloc(8);\n this._buffer.writeDoubleBE(value, offset);\n }\n\n static bufferChunkSize = BUFFER_CHUNK;\n}\n","import { UnsignedInt } from './unsigned-int';\nimport { XdrCompositeType } from './xdr-type';\nimport { XdrReaderError, XdrWriterError } from './errors';\n\nexport class String extends XdrCompositeType {\n constructor(maxLength = UnsignedInt.MAX_VALUE) {\n super();\n this._maxLength = maxLength;\n }\n\n /**\n * @inheritDoc\n */\n read(reader) {\n const size = UnsignedInt.read(reader);\n if (size > this._maxLength)\n throw new XdrReaderError(\n `saw ${size} length String, max allowed is ${this._maxLength}`\n );\n\n return reader.read(size);\n }\n\n readString(reader) {\n return this.read(reader).toString('utf8');\n }\n\n /**\n * @inheritDoc\n */\n write(value, writer) {\n // calculate string byte size before writing\n const size =\n typeof value === 'string'\n ? Buffer.byteLength(value, 'utf8')\n : value.length;\n if (size > this._maxLength)\n throw new XdrWriterError(\n `got ${value.length} bytes, max allowed is ${this._maxLength}`\n );\n // write size info\n UnsignedInt.write(size, writer);\n writer.write(value, size);\n }\n\n /**\n * @inheritDoc\n */\n isValid(value) {\n if (typeof value === 'string') {\n return Buffer.byteLength(value, 'utf8') <= this._maxLength;\n }\n if (value instanceof Array || Buffer.isBuffer(value)) {\n return value.length <= this._maxLength;\n }\n return false;\n }\n}\n","import { Reference } from './reference';\nimport { XdrCompositeType, isSerializableIsh } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nexport class Struct extends XdrCompositeType {\n constructor(attributes) {\n super();\n this._attributes = attributes || {};\n }\n\n /**\n * @inheritDoc\n */\n static read(reader) {\n const attributes = {};\n for (const [fieldName, type] of this._fields) {\n attributes[fieldName] = type.read(reader);\n }\n return new this(attributes);\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (!this.isValid(value)) {\n throw new XdrWriterError(\n `${value} has struct name ${value?.constructor?.structName}, not ${\n this.structName\n }: ${JSON.stringify(value)}`\n );\n }\n\n for (const [fieldName, type] of this._fields) {\n const attribute = value._attributes[fieldName];\n type.write(attribute, writer);\n }\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n return (\n value?.constructor?.structName === this.structName ||\n isSerializableIsh(value, this)\n );\n }\n\n static create(context, name, fields) {\n const ChildStruct = class extends Struct {};\n\n ChildStruct.structName = name;\n\n context.results[name] = ChildStruct;\n\n const mappedFields = new Array(fields.length);\n for (let i = 0; i < fields.length; i++) {\n const fieldDescriptor = fields[i];\n const fieldName = fieldDescriptor[0];\n let field = fieldDescriptor[1];\n if (field instanceof Reference) {\n field = field.resolve(context);\n }\n mappedFields[i] = [fieldName, field];\n // create accessors\n ChildStruct.prototype[fieldName] = createAccessorMethod(fieldName);\n }\n\n ChildStruct._fields = mappedFields;\n\n return ChildStruct;\n }\n}\n\nfunction createAccessorMethod(name) {\n return function readOrWriteAttribute(value) {\n if (value !== undefined) {\n this._attributes[name] = value;\n }\n return this._attributes[name];\n };\n}\n","export * from './int';\nexport * from './hyper';\nexport * from './unsigned-int';\nexport * from './unsigned-hyper';\nexport * from './large-int';\n\nexport * from './float';\nexport * from './double';\nexport * from './quadruple';\n\nexport * from './bool';\n\nexport * from './string';\n\nexport * from './opaque';\nexport * from './var-opaque';\n\nexport * from './array';\nexport * from './var-array';\n\nexport * from './option';\nexport * from './void';\n\nexport * from './enum';\nexport * from './struct';\nexport * from './union';\n","import { Void } from './void';\nimport { Reference } from './reference';\nimport { XdrCompositeType, isSerializableIsh } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nexport class Union extends XdrCompositeType {\n constructor(aSwitch, value) {\n super();\n this.set(aSwitch, value);\n }\n\n set(aSwitch, value) {\n if (typeof aSwitch === 'string') {\n aSwitch = this.constructor._switchOn.fromName(aSwitch);\n }\n\n this._switch = aSwitch;\n const arm = this.constructor.armForSwitch(this._switch);\n this._arm = arm;\n this._armType = arm === Void ? Void : this.constructor._arms[arm];\n this._value = value;\n }\n\n get(armName = this._arm) {\n if (this._arm !== Void && this._arm !== armName)\n throw new TypeError(`${armName} not set`);\n return this._value;\n }\n\n switch() {\n return this._switch;\n }\n\n arm() {\n return this._arm;\n }\n\n armType() {\n return this._armType;\n }\n\n value() {\n return this._value;\n }\n\n static armForSwitch(aSwitch) {\n const member = this._switches.get(aSwitch);\n if (member !== undefined) {\n return member;\n }\n if (this._defaultArm) {\n return this._defaultArm;\n }\n throw new TypeError(`Bad union switch: ${aSwitch}`);\n }\n\n static armTypeForArm(arm) {\n if (arm === Void) {\n return Void;\n }\n return this._arms[arm];\n }\n\n /**\n * @inheritDoc\n */\n static read(reader) {\n const aSwitch = this._switchOn.read(reader);\n const arm = this.armForSwitch(aSwitch);\n const armType = arm === Void ? Void : this._arms[arm];\n let value;\n if (armType !== undefined) {\n value = armType.read(reader);\n } else {\n value = arm.read(reader);\n }\n return new this(aSwitch, value);\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (!this.isValid(value)) {\n throw new XdrWriterError(\n `${value} has union name ${value?.unionName}, not ${\n this.unionName\n }: ${JSON.stringify(value)}`\n );\n }\n\n this._switchOn.write(value.switch(), writer);\n value.armType().write(value.value(), writer);\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n return (\n value?.constructor?.unionName === this.unionName ||\n isSerializableIsh(value, this)\n );\n }\n\n static create(context, name, config) {\n const ChildUnion = class extends Union {};\n\n ChildUnion.unionName = name;\n context.results[name] = ChildUnion;\n\n if (config.switchOn instanceof Reference) {\n ChildUnion._switchOn = config.switchOn.resolve(context);\n } else {\n ChildUnion._switchOn = config.switchOn;\n }\n\n ChildUnion._switches = new Map();\n ChildUnion._arms = {};\n\n // resolve default arm\n let defaultArm = config.defaultArm;\n if (defaultArm instanceof Reference) {\n defaultArm = defaultArm.resolve(context);\n }\n\n ChildUnion._defaultArm = defaultArm;\n\n for (const [aSwitch, armName] of config.switches) {\n const key =\n typeof aSwitch === 'string'\n ? ChildUnion._switchOn.fromName(aSwitch)\n : aSwitch;\n\n ChildUnion._switches.set(key, armName);\n }\n\n // add enum-based helpers\n // NOTE: we don't have good notation for \"is a subclass of XDR.Enum\",\n // and so we use the following check (does _switchOn have a `values`\n // attribute) to approximate the intent.\n if (ChildUnion._switchOn.values !== undefined) {\n for (const aSwitch of ChildUnion._switchOn.values()) {\n // Add enum-based constructors\n ChildUnion[aSwitch.name] = function ctr(value) {\n return new ChildUnion(aSwitch, value);\n };\n\n // Add enum-based \"set\" helpers\n ChildUnion.prototype[aSwitch.name] = function set(value) {\n return this.set(aSwitch, value);\n };\n }\n }\n\n if (config.arms) {\n for (const [armsName, value] of Object.entries(config.arms)) {\n ChildUnion._arms[armsName] =\n value instanceof Reference ? value.resolve(context) : value;\n // Add arm accessor helpers\n if (value !== Void) {\n ChildUnion.prototype[armsName] = function get() {\n return this.get(armsName);\n };\n }\n }\n }\n\n return ChildUnion;\n }\n}\n","import { LargeInt } from './large-int';\n\nexport class UnsignedHyper extends LargeInt {\n /**\n * @param {Array} parts - Slices to encode\n */\n constructor(...args) {\n super(args);\n }\n\n get low() {\n return Number(this._value & 0xffffffffn) << 0;\n }\n\n get high() {\n return Number(this._value >> 32n) >> 0;\n }\n\n get size() {\n return 64;\n }\n\n get unsigned() {\n return true;\n }\n\n /**\n * Create UnsignedHyper instance from two [high][low] i32 values\n * @param {Number} low - Low part of u64 number\n * @param {Number} high - High part of u64 number\n * @return {UnsignedHyper}\n */\n static fromBits(low, high) {\n return new this(low, high);\n }\n}\n\nUnsignedHyper.defineIntBoundaries();\n","import { XdrPrimitiveType } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nconst MAX_VALUE = 4294967295;\nconst MIN_VALUE = 0;\n\nexport class UnsignedInt extends XdrPrimitiveType {\n /**\n * @inheritDoc\n */\n static read(reader) {\n return reader.readUInt32BE();\n }\n\n /**\n * @inheritDoc\n */\n static write(value, writer) {\n if (\n typeof value !== 'number' ||\n !(value >= MIN_VALUE && value <= MAX_VALUE) ||\n value % 1 !== 0\n )\n throw new XdrWriterError('invalid u32 value');\n\n writer.writeUInt32BE(value);\n }\n\n /**\n * @inheritDoc\n */\n static isValid(value) {\n if (typeof value !== 'number' || value % 1 !== 0) {\n return false;\n }\n\n return value >= MIN_VALUE && value <= MAX_VALUE;\n }\n}\n\nUnsignedInt.MAX_VALUE = MAX_VALUE;\nUnsignedInt.MIN_VALUE = MIN_VALUE;\n","import { UnsignedInt } from './unsigned-int';\nimport { XdrCompositeType } from './xdr-type';\nimport { XdrReaderError, XdrWriterError } from './errors';\n\nexport class VarArray extends XdrCompositeType {\n constructor(childType, maxLength = UnsignedInt.MAX_VALUE) {\n super();\n this._childType = childType;\n this._maxLength = maxLength;\n }\n\n /**\n * @inheritDoc\n */\n read(reader) {\n const length = UnsignedInt.read(reader);\n if (length > this._maxLength)\n throw new XdrReaderError(\n `saw ${length} length VarArray, max allowed is ${this._maxLength}`\n );\n\n const result = new Array(length);\n for (let i = 0; i < length; i++) {\n result[i] = this._childType.read(reader);\n }\n return result;\n }\n\n /**\n * @inheritDoc\n */\n write(value, writer) {\n if (!(value instanceof Array))\n throw new XdrWriterError(`value is not array`);\n\n if (value.length > this._maxLength)\n throw new XdrWriterError(\n `got array of size ${value.length}, max allowed is ${this._maxLength}`\n );\n\n UnsignedInt.write(value.length, writer);\n for (const child of value) {\n this._childType.write(child, writer);\n }\n }\n\n /**\n * @inheritDoc\n */\n isValid(value) {\n if (!(value instanceof Array) || value.length > this._maxLength) {\n return false;\n }\n for (const child of value) {\n if (!this._childType.isValid(child)) return false;\n }\n return true;\n }\n}\n","import { UnsignedInt } from './unsigned-int';\nimport { XdrCompositeType } from './xdr-type';\nimport { XdrReaderError, XdrWriterError } from './errors';\n\nexport class VarOpaque extends XdrCompositeType {\n constructor(maxLength = UnsignedInt.MAX_VALUE) {\n super();\n this._maxLength = maxLength;\n }\n\n /**\n * @inheritDoc\n */\n read(reader) {\n const size = UnsignedInt.read(reader);\n if (size > this._maxLength)\n throw new XdrReaderError(\n `saw ${size} length VarOpaque, max allowed is ${this._maxLength}`\n );\n return reader.read(size);\n }\n\n /**\n * @inheritDoc\n */\n write(value, writer) {\n const { length } = value;\n if (value.length > this._maxLength)\n throw new XdrWriterError(\n `got ${value.length} bytes, max allowed is ${this._maxLength}`\n );\n // write size info\n UnsignedInt.write(length, writer);\n writer.write(value, length);\n }\n\n /**\n * @inheritDoc\n */\n isValid(value) {\n return Buffer.isBuffer(value) && value.length <= this._maxLength;\n }\n}\n","import { XdrPrimitiveType } from './xdr-type';\nimport { XdrWriterError } from './errors';\n\nexport class Void extends XdrPrimitiveType {\n /* jshint unused: false */\n\n static read() {\n return undefined;\n }\n\n static write(value) {\n if (value !== undefined)\n throw new XdrWriterError('trying to write value to a void slot');\n }\n\n static isValid(value) {\n return value === undefined;\n }\n}\n","import { XdrReader } from './serialization/xdr-reader';\nimport { XdrWriter } from './serialization/xdr-writer';\nimport { XdrNotImplementedDefinitionError } from './errors';\n\nclass XdrType {\n /**\n * Encode value to XDR format\n * @param {XdrEncodingFormat} [format] - Encoding format (one of \"raw\", \"hex\", \"base64\")\n * @return {String|Buffer}\n */\n toXDR(format = 'raw') {\n if (!this.write) return this.constructor.toXDR(this, format);\n\n const writer = new XdrWriter();\n this.write(this, writer);\n return encodeResult(writer.finalize(), format);\n }\n\n /**\n * Decode XDR-encoded value\n * @param {Buffer|String} input - XDR-encoded input data\n * @param {XdrEncodingFormat} [format] - Encoding format (one of \"raw\", \"hex\", \"base64\")\n * @return {this}\n */\n fromXDR(input, format = 'raw') {\n if (!this.read) return this.constructor.fromXDR(input, format);\n\n const reader = new XdrReader(decodeInput(input, format));\n const result = this.read(reader);\n reader.ensureInputConsumed();\n return result;\n }\n\n /**\n * Check whether input contains a valid XDR-encoded value\n * @param {Buffer|String} input - XDR-encoded input data\n * @param {XdrEncodingFormat} [format] - Encoding format (one of \"raw\", \"hex\", \"base64\")\n * @return {Boolean}\n */\n validateXDR(input, format = 'raw') {\n try {\n this.fromXDR(input, format);\n return true;\n } catch (e) {\n return false;\n }\n }\n\n /**\n * Encode value to XDR format\n * @param {this} value - Value to serialize\n * @param {XdrEncodingFormat} [format] - Encoding format (one of \"raw\", \"hex\", \"base64\")\n * @return {Buffer}\n */\n static toXDR(value, format = 'raw') {\n const writer = new XdrWriter();\n this.write(value, writer);\n return encodeResult(writer.finalize(), format);\n }\n\n /**\n * Decode XDR-encoded value\n * @param {Buffer|String} input - XDR-encoded input data\n * @param {XdrEncodingFormat} [format] - Encoding format (one of \"raw\", \"hex\", \"base64\")\n * @return {this}\n */\n static fromXDR(input, format = 'raw') {\n const reader = new XdrReader(decodeInput(input, format));\n const result = this.read(reader);\n reader.ensureInputConsumed();\n return result;\n }\n\n /**\n * Check whether input contains a valid XDR-encoded value\n * @param {Buffer|String} input - XDR-encoded input data\n * @param {XdrEncodingFormat} [format] - Encoding format (one of \"raw\", \"hex\", \"base64\")\n * @return {Boolean}\n */\n static validateXDR(input, format = 'raw') {\n try {\n this.fromXDR(input, format);\n return true;\n } catch (e) {\n return false;\n }\n }\n}\n\nexport class XdrPrimitiveType extends XdrType {\n /**\n * Read value from the XDR-serialized input\n * @param {XdrReader} reader - XdrReader instance\n * @return {this}\n * @abstract\n */\n // eslint-disable-next-line no-unused-vars\n static read(reader) {\n throw new XdrNotImplementedDefinitionError();\n }\n\n /**\n * Write XDR value to the buffer\n * @param {this} value - Value to write\n * @param {XdrWriter} writer - XdrWriter instance\n * @return {void}\n * @abstract\n */\n // eslint-disable-next-line no-unused-vars\n static write(value, writer) {\n throw new XdrNotImplementedDefinitionError();\n }\n\n /**\n * Check whether XDR primitive value is valid\n * @param {this} value - Value to check\n * @return {Boolean}\n * @abstract\n */\n // eslint-disable-next-line no-unused-vars\n static isValid(value) {\n return false;\n }\n}\n\nexport class XdrCompositeType extends XdrType {\n // Every descendant should implement two methods: read(reader) and write(value, writer)\n\n /**\n * Check whether XDR primitive value is valid\n * @param {this} value - Value to check\n * @return {Boolean}\n * @abstract\n */\n // eslint-disable-next-line no-unused-vars\n isValid(value) {\n return false;\n }\n}\n\nclass InvalidXdrEncodingFormatError extends TypeError {\n constructor(format) {\n super(`Invalid format ${format}, must be one of \"raw\", \"hex\", \"base64\"`);\n }\n}\n\nfunction encodeResult(buffer, format) {\n switch (format) {\n case 'raw':\n return buffer;\n case 'hex':\n return buffer.toString('hex');\n case 'base64':\n return buffer.toString('base64');\n default:\n throw new InvalidXdrEncodingFormatError(format);\n }\n}\n\nfunction decodeInput(input, format) {\n switch (format) {\n case 'raw':\n return input;\n case 'hex':\n return Buffer.from(input, 'hex');\n case 'base64':\n return Buffer.from(input, 'base64');\n default:\n throw new InvalidXdrEncodingFormatError(format);\n }\n}\n\n/**\n * Provides a \"duck typed\" version of the native `instanceof` for read/write.\n *\n * \"Duck typing\" means if the parameter _looks like_ and _acts like_ a duck\n * (i.e. the type we're checking), it will be treated as that type.\n *\n * In this case, the \"type\" we're looking for is \"like XdrType\" but also \"like\n * XdrCompositeType|XdrPrimitiveType\" (i.e. serializable), but also conditioned\n * on a particular subclass of \"XdrType\" (e.g. {@link Union} which extends\n * XdrType).\n *\n * This makes the package resilient to downstream systems that may be combining\n * many versions of a package across its stack that are technically compatible\n * but fail `instanceof` checks due to cross-pollination.\n */\nexport function isSerializableIsh(value, subtype) {\n return (\n value !== undefined &&\n value !== null && // prereqs, otherwise `getPrototypeOf` pops\n (value instanceof subtype || // quickest check\n // Do an initial constructor check (anywhere is fine so that children of\n // `subtype` still work), then\n (hasConstructor(value, subtype) &&\n // ensure it has read/write methods, then\n typeof value.constructor.read === 'function' &&\n typeof value.constructor.write === 'function' &&\n // ensure XdrType is in the prototype chain\n hasConstructor(value, 'XdrType')))\n );\n}\n\n/** Tries to find `subtype` in any of the constructors or meta of `instance`. */\nexport function hasConstructor(instance, subtype) {\n do {\n const ctor = instance.constructor;\n if (ctor.name === subtype) {\n return true;\n }\n } while ((instance = Object.getPrototypeOf(instance)));\n return false;\n}\n\n/**\n * @typedef {'raw'|'hex'|'base64'} XdrEncodingFormat\n */\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(\"./src/browser.js\");\n",""],"names":["XdrCompositeType","XdrWriterError","Array","constructor","childType","length","_childType","_length","read","reader","result","global","i","write","value","writer","isArray","child","isValid","encodeBigIntFromBits","parts","size","unsigned","total","sliceSize","RangeError","BigInt","valueOf","e","TypeError","asUintN","asIntN","min","max","calculateBigIntBoundaries","formatIntName","sliceBigInt","iSize","shift","precision","boundary","Int","XdrPrimitiveType","XdrReaderError","Bool","intVal","exports","require","module","XDRTypes","Reference","XdrDefinitionError","SimpleReference","name","resolve","context","defn","definitions","ArrayReference","childReference","variable","resolvedChild","VarArray","OptionReference","Option","SizedReference","sizedType","Definition","cfg","config","results","createTypedef","typeName","createConst","TypeBuilder","destination","_destination","_definitions","enum","members","Enum","create","define","struct","Struct","union","Union","typedef","const","void","Void","bool","int","hyper","Hyper","uint","UnsignedInt","uhyper","UnsignedHyper","float","Float","double","Double","quadruple","Quadruple","string","String","opaque","Opaque","varOpaque","VarOpaque","array","varArray","maxLength","option","definition","undefined","lookup","Object","values","fn","types","builder","readDoubleBE","writeDoubleBE","isSerializableIsh","res","_byValue","enumName","JSON","stringify","_members","fromName","fromValue","ChildEnum","key","entries","inst","message","XdrNotImplementedDefinitionError","readFloatBE","writeFloatBE","LargeInt","args","low","Number","_value","high","fromBits","defineIntBoundaries","XdrReader","XdrWriter","MAX_VALUE","MIN_VALUE","readInt32BE","writeInt32BE","slice","toString","toJSON","toBigInt","prototype","readBigUInt64BE","from","reverse","writeBigUInt64BE","writeBigInt64BE","part","fromString","Buffer","isBuffer","isPresent","source","ArrayBuffer","isView","_buffer","_index","eof","advance","padding","rewind","subarray","readUInt32BE","readBigInt64BE","ensureInputConsumed","BUFFER_CHUNK","buffer","allocUnsafe","alloc","resize","minRequiredSize","newLength","Math","ceil","newBuffer","copy","finalize","toArray","offset","fill","writeUInt32BE","bufferChunkSize","_maxLength","readString","byteLength","attributes","_attributes","fieldName","type","_fields","structName","attribute","fields","ChildStruct","mappedFields","fieldDescriptor","field","createAccessorMethod","readOrWriteAttribute","aSwitch","set","_switchOn","_switch","arm","armForSwitch","_arm","_armType","_arms","get","armName","switch","armType","member","_switches","_defaultArm","armTypeForArm","unionName","ChildUnion","switchOn","Map","defaultArm","switches","ctr","arms","armsName","XdrType","toXDR","format","encodeResult","fromXDR","input","decodeInput","validateXDR","InvalidXdrEncodingFormatError","subtype","hasConstructor","instance","ctor","getPrototypeOf"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/@stellar/js-xdr/package.json b/node_modules/@stellar/js-xdr/package.json new file mode 100644 index 000000000..d74eb9d09 --- /dev/null +++ b/node_modules/@stellar/js-xdr/package.json @@ -0,0 +1,81 @@ +{ + "name": "@stellar/js-xdr", + "version": "3.1.2", + "description": "Read/write XDR encoded data structures (RFC 4506)", + "main": "lib/xdr.js", + "browser": "dist/xdr.js", + "module": "src/index.js", + "scripts": { + "build": "yarn run build:browser && yarn run build:node", + "build:browser": "webpack --mode=production --config ./webpack.config.js", + "build:node": "webpack --mode=development --config ./webpack.config.js", + "test:node": "yarn run build:node && mocha", + "test:browser": "yarn run build:browser && karma start", + "test": "yarn run test:node && yarn run test:browser", + "test-generate": "bundle exec xdrgen -o generated -n test -l javascript examples/test.x", + "fmt": "prettier --write '**/*.js'", + "prepare": "yarn build", + "clean": "rm -rf lib/ dist/" + }, + "repository": { + "type": "git", + "url": "https://github.com/stellar/js-xdr.git" + }, + "keywords": [], + "author": "Stellar Development Foundation ", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/stellar/js-xdr/issues" + }, + "homepage": "https://github.com/stellar/js-xdr", + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "**/*.{js,json}": [ + "yarn fmt", + "git add" + ] + }, + "mocha": { + "require": [ + "@babel/register", + "./test/setup.js" + ], + "recursive": true, + "ui": "bdd" + }, + "devDependencies": { + "@babel/core": "^7.24.9", + "@babel/eslint-parser": "^7.24.8", + "@babel/preset-env": "^7.24.8", + "@babel/register": "^7.24.6", + "babel-loader": "^9.1.3", + "buffer": "^6.0.3", + "chai": "^4.3.10", + "eslint": "^8.57.0", + "eslint-config-airbnb-base": "^15.0.0", + "eslint-config-prettier": "^8.8.0", + "eslint-plugin-import": "^2.29.1", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-prefer-import": "^0.0.1", + "eslint-plugin-prettier": "^4.2.1", + "husky": "^8.0.3", + "karma": "^6.4.3", + "karma-chrome-launcher": "^3.2.0", + "karma-firefox-launcher": "^2.1.3", + "karma-mocha": "^2.0.1", + "karma-sinon-chai": "^2.0.2", + "karma-webpack": "^5.0.1", + "lint-staged": "13.2.2", + "mocha": "^10.6.0", + "prettier": "^2.8.7", + "sinon": "^15.2.0", + "sinon-chai": "^3.7.0", + "terser-webpack-plugin": "^5.3.10", + "webpack": "^5.93.0", + "webpack-cli": "^5.0.2" + } +} diff --git a/node_modules/@stellar/js-xdr/prettier.config.js b/node_modules/@stellar/js-xdr/prettier.config.js new file mode 100644 index 000000000..a87a3ac31 --- /dev/null +++ b/node_modules/@stellar/js-xdr/prettier.config.js @@ -0,0 +1,12 @@ +module.exports = { + arrowParens: 'always', + bracketSpacing: true, + jsxBracketSameLine: false, + printWidth: 80, + proseWrap: 'always', + semi: true, + singleQuote: true, + tabWidth: 2, + trailingComma: 'none', + useTabs: false +}; diff --git a/node_modules/@stellar/js-xdr/src/.eslintrc.js b/node_modules/@stellar/js-xdr/src/.eslintrc.js new file mode 100644 index 000000000..6a5046dfb --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/.eslintrc.js @@ -0,0 +1,117 @@ +module.exports = { + env: { + es6: true, + es2017: true, + es2020: true, + es2022: true + }, + parserOptions: { ecmaVersion: 13 }, + extends: ['airbnb-base', 'prettier'], + plugins: ['prettier', 'prefer-import'], + rules: { + // OFF + 'import/prefer-default-export': 0, + 'node/no-unsupported-features/es-syntax': 0, + 'node/no-unsupported-features/es-builtins': 0, + camelcase: 0, + 'class-methods-use-this': 0, + 'linebreak-style': 0, + 'new-cap': 0, + 'no-param-reassign': 0, + 'no-underscore-dangle': 0, + 'no-use-before-define': 0, + 'prefer-destructuring': 0, + 'lines-between-class-members': 0, + 'no-plusplus': 0, // allow ++ for iterators + 'no-bitwise': 0, // allow high-performant bitwise operations + + // WARN + 'prefer-import/prefer-import-over-require': [1], + 'no-console': ['warn', { allow: ['assert'] }], + 'no-debugger': 1, + 'no-unused-vars': 1, + 'arrow-body-style': 1, + 'valid-jsdoc': [ + 1, + { + requireReturnDescription: false + } + ], + 'prefer-const': 1, + 'object-shorthand': 1, + 'require-await': 1, + 'max-classes-per-file': ['warn', 3], // do not block imports from other classes + + // ERROR + 'no-unused-expressions': [2, { allowTaggedTemplates: true }], + + // we're redefining this without the Math.pow restriction + // (since we don't want to manually add support for it) + // copied from https://github.com/airbnb/javascript/blob/070e6200bb6c70fa31470ed7a6294f2497468b44/packages/eslint-config-airbnb-base/rules/best-practices.js#L200 + 'no-restricted-properties': [ + 'error', + { + object: 'arguments', + property: 'callee', + message: 'arguments.callee is deprecated' + }, + { + object: 'global', + property: 'isFinite', + message: 'Please use Number.isFinite instead' + }, + { + object: 'self', + property: 'isFinite', + message: 'Please use Number.isFinite instead' + }, + { + object: 'window', + property: 'isFinite', + message: 'Please use Number.isFinite instead' + }, + { + object: 'global', + property: 'isNaN', + message: 'Please use Number.isNaN instead' + }, + { + object: 'self', + property: 'isNaN', + message: 'Please use Number.isNaN instead' + }, + { + object: 'window', + property: 'isNaN', + message: 'Please use Number.isNaN instead' + }, + { + property: '__defineGetter__', + message: 'Please use Object.defineProperty instead.' + }, + { + property: '__defineSetter__', + message: 'Please use Object.defineProperty instead.' + } + ], + 'no-restricted-syntax': [ + // override basic rule to allow ForOfStatement + 'error', + { + selector: 'ForInStatement', + message: + 'for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array.' + }, + { + selector: 'LabeledStatement', + message: + 'Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand.' + }, + { + selector: 'WithStatement', + message: + '`with` is disallowed in strict mode because it makes code impossible to predict and optimize.' + } + ] + } +}; diff --git a/node_modules/@stellar/js-xdr/src/array.js b/node_modules/@stellar/js-xdr/src/array.js new file mode 100644 index 000000000..189865ff8 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/array.js @@ -0,0 +1,54 @@ +import { XdrCompositeType } from './xdr-type'; +import { XdrWriterError } from './errors'; + +export class Array extends XdrCompositeType { + constructor(childType, length) { + super(); + this._childType = childType; + this._length = length; + } + + /** + * @inheritDoc + */ + read(reader) { + // allocate array of specified length + const result = new global.Array(this._length); + // read values + for (let i = 0; i < this._length; i++) { + result[i] = this._childType.read(reader); + } + return result; + } + + /** + * @inheritDoc + */ + write(value, writer) { + if (!global.Array.isArray(value)) + throw new XdrWriterError(`value is not array`); + + if (value.length !== this._length) + throw new XdrWriterError( + `got array of size ${value.length}, expected ${this._length}` + ); + + for (const child of value) { + this._childType.write(child, writer); + } + } + + /** + * @inheritDoc + */ + isValid(value) { + if (!(value instanceof global.Array) || value.length !== this._length) { + return false; + } + + for (const child of value) { + if (!this._childType.isValid(child)) return false; + } + return true; + } +} diff --git a/node_modules/@stellar/js-xdr/src/bigint-encoder.js b/node_modules/@stellar/js-xdr/src/bigint-encoder.js new file mode 100644 index 000000000..861096df2 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/bigint-encoder.js @@ -0,0 +1,141 @@ +/** + * Encode a native `bigint` value from a list of arbitrary integer-like values. + * + * @param {Array} parts - Slices to encode in big-endian + * format (i.e. earlier elements are higher bits) + * @param {64|128|256} size - Number of bits in the target integer type + * @param {boolean} unsigned - Whether it's an unsigned integer + * + * @returns {bigint} + */ +export function encodeBigIntFromBits(parts, size, unsigned) { + if (!(parts instanceof Array)) { + // allow a single parameter instead of an array + parts = [parts]; + } else if (parts.length && parts[0] instanceof Array) { + // unpack nested array param + parts = parts[0]; + } + + const total = parts.length; + const sliceSize = size / total; + switch (sliceSize) { + case 32: + case 64: + case 128: + case 256: + break; + + default: + throw new RangeError( + `expected slices to fit in 32/64/128/256 bits, got ${parts}` + ); + } + + // normalize all inputs to bigint + try { + for (let i = 0; i < parts.length; i++) { + if (typeof parts[i] !== 'bigint') { + parts[i] = BigInt(parts[i].valueOf()); + } + } + } catch (e) { + throw new TypeError(`expected bigint-like values, got: ${parts} (${e})`); + } + + // check for sign mismatches for single inputs (this is a special case to + // handle one parameter passed to e.g. UnsignedHyper et al.) + // see https://github.com/stellar/js-xdr/pull/100#discussion_r1228770845 + if (unsigned && parts.length === 1 && parts[0] < 0n) { + throw new RangeError(`expected a positive value, got: ${parts}`); + } + + // encode in big-endian fashion, shifting each slice by the slice size + let result = BigInt.asUintN(sliceSize, parts[0]); // safe: len >= 1 + for (let i = 1; i < parts.length; i++) { + result |= BigInt.asUintN(sliceSize, parts[i]) << BigInt(i * sliceSize); + } + + // interpret value as signed if necessary and clamp it + if (!unsigned) { + result = BigInt.asIntN(size, result); + } + + // check boundaries + const [min, max] = calculateBigIntBoundaries(size, unsigned); + if (result >= min && result <= max) { + return result; + } + + // failed to encode + throw new TypeError( + `bigint values [${parts}] for ${formatIntName( + size, + unsigned + )} out of range [${min}, ${max}]: ${result}` + ); +} + +/** + * Transforms a single bigint value that's supposed to represent a `size`-bit + * integer into a list of `sliceSize`d chunks. + * + * @param {bigint} value - Single bigint value to decompose + * @param {64|128|256} iSize - Number of bits represented by `value` + * @param {32|64|128} sliceSize - Number of chunks to decompose into + * @return {bigint[]} + */ +export function sliceBigInt(value, iSize, sliceSize) { + if (typeof value !== 'bigint') { + throw new TypeError(`Expected bigint 'value', got ${typeof value}`); + } + + const total = iSize / sliceSize; + if (total === 1) { + return [value]; + } + + if ( + sliceSize < 32 || + sliceSize > 128 || + (total !== 2 && total !== 4 && total !== 8) + ) { + throw new TypeError( + `invalid bigint (${value}) and slice size (${iSize} -> ${sliceSize}) combination` + ); + } + + const shift = BigInt(sliceSize); + + // iterate shift and mask application + const result = new Array(total); + for (let i = 0; i < total; i++) { + // we force a signed interpretation to preserve sign in each slice value, + // but downstream can convert to unsigned if it's appropriate + result[i] = BigInt.asIntN(sliceSize, value); // clamps to size + + // move on to the next chunk + value >>= shift; + } + + return result; +} + +export function formatIntName(precision, unsigned) { + return `${unsigned ? 'u' : 'i'}${precision}`; +} + +/** + * Get min|max boundaries for an integer with a specified bits size + * @param {64|128|256} size - Number of bits in the source integer type + * @param {Boolean} unsigned - Whether it's an unsigned integer + * @return {BigInt[]} + */ +export function calculateBigIntBoundaries(size, unsigned) { + if (unsigned) { + return [0n, (1n << BigInt(size)) - 1n]; + } + + const boundary = 1n << BigInt(size - 1); + return [0n - boundary, boundary - 1n]; +} diff --git a/node_modules/@stellar/js-xdr/src/bool.js b/node_modules/@stellar/js-xdr/src/bool.js new file mode 100644 index 000000000..7909cb9a7 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/bool.js @@ -0,0 +1,36 @@ +import { Int } from './int'; +import { XdrPrimitiveType } from './xdr-type'; +import { XdrReaderError } from './errors'; + +export class Bool extends XdrPrimitiveType { + /** + * @inheritDoc + */ + static read(reader) { + const value = Int.read(reader); + + switch (value) { + case 0: + return false; + case 1: + return true; + default: + throw new XdrReaderError(`got ${value} when trying to read a bool`); + } + } + + /** + * @inheritDoc + */ + static write(value, writer) { + const intVal = value ? 1 : 0; + Int.write(intVal, writer); + } + + /** + * @inheritDoc + */ + static isValid(value) { + return typeof value === 'boolean'; + } +} diff --git a/node_modules/@stellar/js-xdr/src/browser.js b/node_modules/@stellar/js-xdr/src/browser.js new file mode 100644 index 000000000..09ec44dcf --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/browser.js @@ -0,0 +1,3 @@ +// eslint-disable-next-line prefer-import/prefer-import-over-require +const exports = require('./index'); +module.exports = exports; diff --git a/node_modules/@stellar/js-xdr/src/config.js b/node_modules/@stellar/js-xdr/src/config.js new file mode 100644 index 000000000..151a06d4b --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/config.js @@ -0,0 +1,239 @@ +// eslint-disable-next-line max-classes-per-file +import * as XDRTypes from './types'; +import { Reference } from './reference'; +import { XdrDefinitionError } from './errors'; + +export * from './reference'; + +class SimpleReference extends Reference { + constructor(name) { + super(); + this.name = name; + } + + resolve(context) { + const defn = context.definitions[this.name]; + return defn.resolve(context); + } +} + +class ArrayReference extends Reference { + constructor(childReference, length, variable = false) { + super(); + this.childReference = childReference; + this.length = length; + this.variable = variable; + } + + resolve(context) { + let resolvedChild = this.childReference; + let length = this.length; + + if (resolvedChild instanceof Reference) { + resolvedChild = resolvedChild.resolve(context); + } + + if (length instanceof Reference) { + length = length.resolve(context); + } + + if (this.variable) { + return new XDRTypes.VarArray(resolvedChild, length); + } + return new XDRTypes.Array(resolvedChild, length); + } +} + +class OptionReference extends Reference { + constructor(childReference) { + super(); + this.childReference = childReference; + this.name = childReference.name; + } + + resolve(context) { + let resolvedChild = this.childReference; + + if (resolvedChild instanceof Reference) { + resolvedChild = resolvedChild.resolve(context); + } + + return new XDRTypes.Option(resolvedChild); + } +} + +class SizedReference extends Reference { + constructor(sizedType, length) { + super(); + this.sizedType = sizedType; + this.length = length; + } + + resolve(context) { + let length = this.length; + + if (length instanceof Reference) { + length = length.resolve(context); + } + + return new this.sizedType(length); + } +} + +class Definition { + constructor(constructor, name, cfg) { + this.constructor = constructor; + this.name = name; + this.config = cfg; + } + + // resolve calls the constructor of this definition with the provided context + // and this definitions config values. The definitions constructor should + // populate the final type on `context.results`, and may refer to other + // definitions through `context.definitions` + resolve(context) { + if (this.name in context.results) { + return context.results[this.name]; + } + + return this.constructor(context, this.name, this.config); + } +} + +// let the reference resolution system do its thing +// the "constructor" for a typedef just returns the resolved value +function createTypedef(context, typeName, value) { + if (value instanceof Reference) { + value = value.resolve(context); + } + context.results[typeName] = value; + return value; +} + +function createConst(context, name, value) { + context.results[name] = value; + return value; +} + +class TypeBuilder { + constructor(destination) { + this._destination = destination; + this._definitions = {}; + } + + enum(name, members) { + const result = new Definition(XDRTypes.Enum.create, name, members); + this.define(name, result); + } + + struct(name, members) { + const result = new Definition(XDRTypes.Struct.create, name, members); + this.define(name, result); + } + + union(name, cfg) { + const result = new Definition(XDRTypes.Union.create, name, cfg); + this.define(name, result); + } + + typedef(name, cfg) { + const result = new Definition(createTypedef, name, cfg); + this.define(name, result); + } + + const(name, cfg) { + const result = new Definition(createConst, name, cfg); + this.define(name, result); + } + + void() { + return XDRTypes.Void; + } + + bool() { + return XDRTypes.Bool; + } + + int() { + return XDRTypes.Int; + } + + hyper() { + return XDRTypes.Hyper; + } + + uint() { + return XDRTypes.UnsignedInt; + } + + uhyper() { + return XDRTypes.UnsignedHyper; + } + + float() { + return XDRTypes.Float; + } + + double() { + return XDRTypes.Double; + } + + quadruple() { + return XDRTypes.Quadruple; + } + + string(length) { + return new SizedReference(XDRTypes.String, length); + } + + opaque(length) { + return new SizedReference(XDRTypes.Opaque, length); + } + + varOpaque(length) { + return new SizedReference(XDRTypes.VarOpaque, length); + } + + array(childType, length) { + return new ArrayReference(childType, length); + } + + varArray(childType, maxLength) { + return new ArrayReference(childType, maxLength, true); + } + + option(childType) { + return new OptionReference(childType); + } + + define(name, definition) { + if (this._destination[name] === undefined) { + this._definitions[name] = definition; + } else { + throw new XdrDefinitionError(`${name} is already defined`); + } + } + + lookup(name) { + return new SimpleReference(name); + } + + resolve() { + for (const defn of Object.values(this._definitions)) { + defn.resolve({ + definitions: this._definitions, + results: this._destination + }); + } + } +} + +export function config(fn, types = {}) { + if (fn) { + const builder = new TypeBuilder(types); + fn(builder); + builder.resolve(); + } + + return types; +} diff --git a/node_modules/@stellar/js-xdr/src/double.js b/node_modules/@stellar/js-xdr/src/double.js new file mode 100644 index 000000000..963617f1d --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/double.js @@ -0,0 +1,27 @@ +import { XdrPrimitiveType } from './xdr-type'; +import { XdrWriterError } from './errors'; + +export class Double extends XdrPrimitiveType { + /** + * @inheritDoc + */ + static read(reader) { + return reader.readDoubleBE(); + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (typeof value !== 'number') throw new XdrWriterError('not a number'); + + writer.writeDoubleBE(value); + } + + /** + * @inheritDoc + */ + static isValid(value) { + return typeof value === 'number'; + } +} diff --git a/node_modules/@stellar/js-xdr/src/enum.js b/node_modules/@stellar/js-xdr/src/enum.js new file mode 100644 index 000000000..ec949f185 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/enum.js @@ -0,0 +1,94 @@ +import { Int } from './int'; +import { XdrPrimitiveType, isSerializableIsh } from './xdr-type'; +import { XdrReaderError, XdrWriterError } from './errors'; + +export class Enum extends XdrPrimitiveType { + constructor(name, value) { + super(); + this.name = name; + this.value = value; + } + + /** + * @inheritDoc + */ + static read(reader) { + const intVal = Int.read(reader); + const res = this._byValue[intVal]; + if (res === undefined) + throw new XdrReaderError( + `unknown ${this.enumName} member for value ${intVal}` + ); + return res; + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (!this.isValid(value)) { + throw new XdrWriterError( + `${value} has enum name ${value?.enumName}, not ${ + this.enumName + }: ${JSON.stringify(value)}` + ); + } + + Int.write(value.value, writer); + } + + /** + * @inheritDoc + */ + static isValid(value) { + return ( + value?.constructor?.enumName === this.enumName || + isSerializableIsh(value, this) + ); + } + + static members() { + return this._members; + } + + static values() { + return Object.values(this._members); + } + + static fromName(name) { + const result = this._members[name]; + + if (!result) + throw new TypeError(`${name} is not a member of ${this.enumName}`); + + return result; + } + + static fromValue(value) { + const result = this._byValue[value]; + if (result === undefined) + throw new TypeError( + `${value} is not a value of any member of ${this.enumName}` + ); + return result; + } + + static create(context, name, members) { + const ChildEnum = class extends Enum {}; + + ChildEnum.enumName = name; + context.results[name] = ChildEnum; + + ChildEnum._members = {}; + ChildEnum._byValue = {}; + + for (const [key, value] of Object.entries(members)) { + const inst = new ChildEnum(key, value); + ChildEnum._members[key] = inst; + ChildEnum._byValue[value] = inst; + ChildEnum[key] = () => inst; + } + + return ChildEnum; + } +} diff --git a/node_modules/@stellar/js-xdr/src/errors.js b/node_modules/@stellar/js-xdr/src/errors.js new file mode 100644 index 000000000..9786e645f --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/errors.js @@ -0,0 +1,25 @@ +export class XdrWriterError extends TypeError { + constructor(message) { + super(`XDR Write Error: ${message}`); + } +} + +export class XdrReaderError extends TypeError { + constructor(message) { + super(`XDR Read Error: ${message}`); + } +} + +export class XdrDefinitionError extends TypeError { + constructor(message) { + super(`XDR Type Definition Error: ${message}`); + } +} + +export class XdrNotImplementedDefinitionError extends XdrDefinitionError { + constructor() { + super( + `method not implemented, it should be overloaded in the descendant class.` + ); + } +} diff --git a/node_modules/@stellar/js-xdr/src/float.js b/node_modules/@stellar/js-xdr/src/float.js new file mode 100644 index 000000000..706db16cb --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/float.js @@ -0,0 +1,27 @@ +import { XdrPrimitiveType } from './xdr-type'; +import { XdrWriterError } from './errors'; + +export class Float extends XdrPrimitiveType { + /** + * @inheritDoc + */ + static read(reader) { + return reader.readFloatBE(); + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (typeof value !== 'number') throw new XdrWriterError('not a number'); + + writer.writeFloatBE(value); + } + + /** + * @inheritDoc + */ + static isValid(value) { + return typeof value === 'number'; + } +} diff --git a/node_modules/@stellar/js-xdr/src/hyper.js b/node_modules/@stellar/js-xdr/src/hyper.js new file mode 100644 index 000000000..dbe7da208 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/hyper.js @@ -0,0 +1,38 @@ +import { LargeInt } from './large-int'; + +export class Hyper extends LargeInt { + /** + * @param {Array} parts - Slices to encode + */ + constructor(...args) { + super(args); + } + + get low() { + return Number(this._value & 0xffffffffn) << 0; + } + + get high() { + return Number(this._value >> 32n) >> 0; + } + + get size() { + return 64; + } + + get unsigned() { + return false; + } + + /** + * Create Hyper instance from two [high][low] i32 values + * @param {Number} low - Low part of i64 number + * @param {Number} high - High part of i64 number + * @return {LargeInt} + */ + static fromBits(low, high) { + return new this(low, high); + } +} + +Hyper.defineIntBoundaries(); diff --git a/node_modules/@stellar/js-xdr/src/index.js b/node_modules/@stellar/js-xdr/src/index.js new file mode 100644 index 000000000..7bfaaa8ef --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/index.js @@ -0,0 +1,5 @@ +export * from './types'; +export * from './config'; + +export { XdrReader } from './serialization/xdr-reader'; +export { XdrWriter } from './serialization/xdr-writer'; diff --git a/node_modules/@stellar/js-xdr/src/int.js b/node_modules/@stellar/js-xdr/src/int.js new file mode 100644 index 000000000..3990f14f8 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/int.js @@ -0,0 +1,39 @@ +import { XdrPrimitiveType } from './xdr-type'; +import { XdrWriterError } from './errors'; + +const MAX_VALUE = 2147483647; +const MIN_VALUE = -2147483648; + +export class Int extends XdrPrimitiveType { + /** + * @inheritDoc + */ + static read(reader) { + return reader.readInt32BE(); + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (typeof value !== 'number') throw new XdrWriterError('not a number'); + + if ((value | 0) !== value) throw new XdrWriterError('invalid i32 value'); + + writer.writeInt32BE(value); + } + + /** + * @inheritDoc + */ + static isValid(value) { + if (typeof value !== 'number' || (value | 0) !== value) { + return false; + } + + return value >= MIN_VALUE && value <= MAX_VALUE; + } +} + +Int.MAX_VALUE = MAX_VALUE; +Int.MIN_VALUE = -MIN_VALUE; diff --git a/node_modules/@stellar/js-xdr/src/large-int.js b/node_modules/@stellar/js-xdr/src/large-int.js new file mode 100644 index 000000000..78f083545 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/large-int.js @@ -0,0 +1,133 @@ +import { XdrPrimitiveType } from './xdr-type'; +import { + calculateBigIntBoundaries, + encodeBigIntFromBits, + sliceBigInt +} from './bigint-encoder'; +import { XdrNotImplementedDefinitionError, XdrWriterError } from './errors'; + +export class LargeInt extends XdrPrimitiveType { + /** + * @param {Array} parts - Slices to encode + */ + constructor(args) { + super(); + this._value = encodeBigIntFromBits(args, this.size, this.unsigned); + } + + /** + * Signed/unsigned representation + * @type {Boolean} + * @abstract + */ + get unsigned() { + throw new XdrNotImplementedDefinitionError(); + } + + /** + * Size of the integer in bits + * @type {Number} + * @abstract + */ + get size() { + throw new XdrNotImplementedDefinitionError(); + } + + /** + * Slice integer to parts with smaller bit size + * @param {32|64|128} sliceSize - Size of each part in bits + * @return {BigInt[]} + */ + slice(sliceSize) { + return sliceBigInt(this._value, this.size, sliceSize); + } + + toString() { + return this._value.toString(); + } + + toJSON() { + return { _value: this._value.toString() }; + } + + toBigInt() { + return BigInt(this._value); + } + + /** + * @inheritDoc + */ + static read(reader) { + const { size } = this.prototype; + if (size === 64) return new this(reader.readBigUInt64BE()); + return new this( + ...Array.from({ length: size / 64 }, () => + reader.readBigUInt64BE() + ).reverse() + ); + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (value instanceof this) { + value = value._value; + } else if ( + typeof value !== 'bigint' || + value > this.MAX_VALUE || + value < this.MIN_VALUE + ) + throw new XdrWriterError(`${value} is not a ${this.name}`); + + const { unsigned, size } = this.prototype; + if (size === 64) { + if (unsigned) { + writer.writeBigUInt64BE(value); + } else { + writer.writeBigInt64BE(value); + } + } else { + for (const part of sliceBigInt(value, size, 64).reverse()) { + if (unsigned) { + writer.writeBigUInt64BE(part); + } else { + writer.writeBigInt64BE(part); + } + } + } + } + + /** + * @inheritDoc + */ + static isValid(value) { + return typeof value === 'bigint' || value instanceof this; + } + + /** + * Create instance from string + * @param {String} string - Numeric representation + * @return {LargeInt} + */ + static fromString(string) { + return new this(string); + } + + static MAX_VALUE = 0n; + + static MIN_VALUE = 0n; + + /** + * @internal + * @return {void} + */ + static defineIntBoundaries() { + const [min, max] = calculateBigIntBoundaries( + this.prototype.size, + this.prototype.unsigned + ); + this.MIN_VALUE = min; + this.MAX_VALUE = max; + } +} diff --git a/node_modules/@stellar/js-xdr/src/opaque.js b/node_modules/@stellar/js-xdr/src/opaque.js new file mode 100644 index 000000000..ae5f744f2 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/opaque.js @@ -0,0 +1,35 @@ +import { XdrCompositeType } from './xdr-type'; +import { XdrWriterError } from './errors'; + +export class Opaque extends XdrCompositeType { + constructor(length) { + super(); + this._length = length; + } + + /** + * @inheritDoc + */ + read(reader) { + return reader.read(this._length); + } + + /** + * @inheritDoc + */ + write(value, writer) { + const { length } = value; + if (length !== this._length) + throw new XdrWriterError( + `got ${value.length} bytes, expected ${this._length}` + ); + writer.write(value, length); + } + + /** + * @inheritDoc + */ + isValid(value) { + return Buffer.isBuffer(value) && value.length === this._length; + } +} diff --git a/node_modules/@stellar/js-xdr/src/option.js b/node_modules/@stellar/js-xdr/src/option.js new file mode 100644 index 000000000..0193ead01 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/option.js @@ -0,0 +1,43 @@ +import { Bool } from './bool'; +import { XdrPrimitiveType } from './xdr-type'; + +export class Option extends XdrPrimitiveType { + constructor(childType) { + super(); + this._childType = childType; + } + + /** + * @inheritDoc + */ + read(reader) { + if (Bool.read(reader)) { + return this._childType.read(reader); + } + + return undefined; + } + + /** + * @inheritDoc + */ + write(value, writer) { + const isPresent = value !== null && value !== undefined; + + Bool.write(isPresent, writer); + + if (isPresent) { + this._childType.write(value, writer); + } + } + + /** + * @inheritDoc + */ + isValid(value) { + if (value === null || value === undefined) { + return true; + } + return this._childType.isValid(value); + } +} diff --git a/node_modules/@stellar/js-xdr/src/quadruple.js b/node_modules/@stellar/js-xdr/src/quadruple.js new file mode 100644 index 000000000..ccf2f551d --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/quadruple.js @@ -0,0 +1,16 @@ +import { XdrPrimitiveType } from './xdr-type'; +import { XdrDefinitionError } from './errors'; + +export class Quadruple extends XdrPrimitiveType { + static read() { + throw new XdrDefinitionError('quadruple not supported'); + } + + static write() { + throw new XdrDefinitionError('quadruple not supported'); + } + + static isValid() { + return false; + } +} diff --git a/node_modules/@stellar/js-xdr/src/reference.js b/node_modules/@stellar/js-xdr/src/reference.js new file mode 100644 index 000000000..e210b43a5 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/reference.js @@ -0,0 +1,11 @@ +import { XdrPrimitiveType } from './xdr-type'; +import { XdrDefinitionError } from './errors'; + +export class Reference extends XdrPrimitiveType { + /* jshint unused: false */ + resolve() { + throw new XdrDefinitionError( + '"resolve" method should be implemented in the descendant class' + ); + } +} diff --git a/node_modules/@stellar/js-xdr/src/serialization/xdr-reader.js b/node_modules/@stellar/js-xdr/src/serialization/xdr-reader.js new file mode 100644 index 000000000..194befe4e --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/serialization/xdr-reader.js @@ -0,0 +1,160 @@ +/** + * @internal + */ +import { XdrReaderError } from '../errors'; + +export class XdrReader { + /** + * @constructor + * @param {Buffer} source - Buffer containing serialized data + */ + constructor(source) { + if (!Buffer.isBuffer(source)) { + if ( + source instanceof Array || + Array.isArray(source) || + ArrayBuffer.isView(source) + ) { + source = Buffer.from(source); + } else { + throw new XdrReaderError(`source invalid: ${source}`); + } + } + + this._buffer = source; + this._length = source.length; + this._index = 0; + } + + /** + * @type {Buffer} + * @private + * @readonly + */ + _buffer; + /** + * @type {Number} + * @private + * @readonly + */ + _length; + /** + * @type {Number} + * @private + * @readonly + */ + _index; + + /** + * Check if the reader reached the end of the input buffer + * @return {Boolean} + */ + get eof() { + return this._index === this._length; + } + + /** + * Advance reader position, check padding and overflow + * @param {Number} size - Bytes to read + * @return {Number} Position to read from + * @private + */ + advance(size) { + const from = this._index; + // advance cursor position + this._index += size; + // check buffer boundaries + if (this._length < this._index) + throw new XdrReaderError( + 'attempt to read outside the boundary of the buffer' + ); + // check that padding is correct for Opaque and String + const padding = 4 - (size % 4 || 4); + if (padding > 0) { + for (let i = 0; i < padding; i++) + if (this._buffer[this._index + i] !== 0) + // all bytes in the padding should be zeros + throw new XdrReaderError('invalid padding'); + this._index += padding; + } + return from; + } + + /** + * Reset reader position + * @return {void} + */ + rewind() { + this._index = 0; + } + + /** + * Read byte array from the buffer + * @param {Number} size - Bytes to read + * @return {Buffer} - Sliced portion of the underlying buffer + */ + read(size) { + const from = this.advance(size); + return this._buffer.subarray(from, from + size); + } + + /** + * Read i32 from buffer + * @return {Number} + */ + readInt32BE() { + return this._buffer.readInt32BE(this.advance(4)); + } + + /** + * Read u32 from buffer + * @return {Number} + */ + readUInt32BE() { + return this._buffer.readUInt32BE(this.advance(4)); + } + + /** + * Read i64 from buffer + * @return {BigInt} + */ + readBigInt64BE() { + return this._buffer.readBigInt64BE(this.advance(8)); + } + + /** + * Read u64 from buffer + * @return {BigInt} + */ + readBigUInt64BE() { + return this._buffer.readBigUInt64BE(this.advance(8)); + } + + /** + * Read float from buffer + * @return {Number} + */ + readFloatBE() { + return this._buffer.readFloatBE(this.advance(4)); + } + + /** + * Read double from buffer + * @return {Number} + */ + readDoubleBE() { + return this._buffer.readDoubleBE(this.advance(8)); + } + + /** + * Ensure that input buffer has been consumed in full, otherwise it's a type mismatch + * @return {void} + * @throws {XdrReaderError} + */ + ensureInputConsumed() { + if (this._index !== this._length) + throw new XdrReaderError( + `invalid XDR contract typecast - source buffer not entirely consumed` + ); + } +} diff --git a/node_modules/@stellar/js-xdr/src/serialization/xdr-writer.js b/node_modules/@stellar/js-xdr/src/serialization/xdr-writer.js new file mode 100644 index 000000000..aad22450d --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/serialization/xdr-writer.js @@ -0,0 +1,179 @@ +const BUFFER_CHUNK = 8192; // 8 KB chunk size increment + +/** + * @internal + */ +export class XdrWriter { + /** + * @param {Buffer|Number} [buffer] - Optional destination buffer + */ + constructor(buffer) { + if (typeof buffer === 'number') { + buffer = Buffer.allocUnsafe(buffer); + } else if (!(buffer instanceof Buffer)) { + buffer = Buffer.allocUnsafe(BUFFER_CHUNK); + } + this._buffer = buffer; + this._length = buffer.length; + } + + /** + * @type {Buffer} + * @private + * @readonly + */ + _buffer; + /** + * @type {Number} + * @private + * @readonly + */ + _length; + /** + * @type {Number} + * @private + * @readonly + */ + _index = 0; + + /** + * Advance writer position, write padding if needed, auto-resize the buffer + * @param {Number} size - Bytes to write + * @return {Number} Position to read from + * @private + */ + alloc(size) { + const from = this._index; + // advance cursor position + this._index += size; + // ensure sufficient buffer size + if (this._length < this._index) { + this.resize(this._index); + } + return from; + } + + /** + * Increase size of the underlying buffer + * @param {Number} minRequiredSize - Minimum required buffer size + * @return {void} + * @private + */ + resize(minRequiredSize) { + // calculate new length, align new buffer length by chunk size + const newLength = Math.ceil(minRequiredSize / BUFFER_CHUNK) * BUFFER_CHUNK; + // create new buffer and copy previous data + const newBuffer = Buffer.allocUnsafe(newLength); + this._buffer.copy(newBuffer, 0, 0, this._length); + // update references + this._buffer = newBuffer; + this._length = newLength; + } + + /** + * Return XDR-serialized value + * @return {Buffer} + */ + finalize() { + // clip underlying buffer to the actually written value + return this._buffer.subarray(0, this._index); + } + + /** + * Return XDR-serialized value as byte array + * @return {Number[]} + */ + toArray() { + return [...this.finalize()]; + } + + /** + * Write byte array from the buffer + * @param {Buffer|String} value - Bytes/string to write + * @param {Number} size - Size in bytes + * @return {XdrReader} - XdrReader wrapper on top of a subarray + */ + write(value, size) { + if (typeof value === 'string') { + // serialize string directly to the output buffer + const offset = this.alloc(size); + this._buffer.write(value, offset, 'utf8'); + } else { + // copy data to the output buffer + if (!(value instanceof Buffer)) { + value = Buffer.from(value); + } + const offset = this.alloc(size); + value.copy(this._buffer, offset, 0, size); + } + + // add padding for 4-byte XDR alignment + const padding = 4 - (size % 4 || 4); + if (padding > 0) { + const offset = this.alloc(padding); + this._buffer.fill(0, offset, this._index); + } + } + + /** + * Write i32 from buffer + * @param {Number} value - Value to serialize + * @return {void} + */ + writeInt32BE(value) { + const offset = this.alloc(4); + this._buffer.writeInt32BE(value, offset); + } + + /** + * Write u32 from buffer + * @param {Number} value - Value to serialize + * @return {void} + */ + writeUInt32BE(value) { + const offset = this.alloc(4); + this._buffer.writeUInt32BE(value, offset); + } + + /** + * Write i64 from buffer + * @param {BigInt} value - Value to serialize + * @return {void} + */ + writeBigInt64BE(value) { + const offset = this.alloc(8); + this._buffer.writeBigInt64BE(value, offset); + } + + /** + * Write u64 from buffer + * @param {BigInt} value - Value to serialize + * @return {void} + */ + writeBigUInt64BE(value) { + const offset = this.alloc(8); + this._buffer.writeBigUInt64BE(value, offset); + } + + /** + * Write float from buffer + * @param {Number} value - Value to serialize + * @return {void} + */ + writeFloatBE(value) { + const offset = this.alloc(4); + this._buffer.writeFloatBE(value, offset); + } + + /** + * Write double from buffer + * @param {Number} value - Value to serialize + * @return {void} + */ + writeDoubleBE(value) { + const offset = this.alloc(8); + this._buffer.writeDoubleBE(value, offset); + } + + static bufferChunkSize = BUFFER_CHUNK; +} diff --git a/node_modules/@stellar/js-xdr/src/string.js b/node_modules/@stellar/js-xdr/src/string.js new file mode 100644 index 000000000..fec9d4a21 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/string.js @@ -0,0 +1,58 @@ +import { UnsignedInt } from './unsigned-int'; +import { XdrCompositeType } from './xdr-type'; +import { XdrReaderError, XdrWriterError } from './errors'; + +export class String extends XdrCompositeType { + constructor(maxLength = UnsignedInt.MAX_VALUE) { + super(); + this._maxLength = maxLength; + } + + /** + * @inheritDoc + */ + read(reader) { + const size = UnsignedInt.read(reader); + if (size > this._maxLength) + throw new XdrReaderError( + `saw ${size} length String, max allowed is ${this._maxLength}` + ); + + return reader.read(size); + } + + readString(reader) { + return this.read(reader).toString('utf8'); + } + + /** + * @inheritDoc + */ + write(value, writer) { + // calculate string byte size before writing + const size = + typeof value === 'string' + ? Buffer.byteLength(value, 'utf8') + : value.length; + if (size > this._maxLength) + throw new XdrWriterError( + `got ${value.length} bytes, max allowed is ${this._maxLength}` + ); + // write size info + UnsignedInt.write(size, writer); + writer.write(value, size); + } + + /** + * @inheritDoc + */ + isValid(value) { + if (typeof value === 'string') { + return Buffer.byteLength(value, 'utf8') <= this._maxLength; + } + if (value instanceof Array || Buffer.isBuffer(value)) { + return value.length <= this._maxLength; + } + return false; + } +} diff --git a/node_modules/@stellar/js-xdr/src/struct.js b/node_modules/@stellar/js-xdr/src/struct.js new file mode 100644 index 000000000..93e38984c --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/struct.js @@ -0,0 +1,83 @@ +import { Reference } from './reference'; +import { XdrCompositeType, isSerializableIsh } from './xdr-type'; +import { XdrWriterError } from './errors'; + +export class Struct extends XdrCompositeType { + constructor(attributes) { + super(); + this._attributes = attributes || {}; + } + + /** + * @inheritDoc + */ + static read(reader) { + const attributes = {}; + for (const [fieldName, type] of this._fields) { + attributes[fieldName] = type.read(reader); + } + return new this(attributes); + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (!this.isValid(value)) { + throw new XdrWriterError( + `${value} has struct name ${value?.constructor?.structName}, not ${ + this.structName + }: ${JSON.stringify(value)}` + ); + } + + for (const [fieldName, type] of this._fields) { + const attribute = value._attributes[fieldName]; + type.write(attribute, writer); + } + } + + /** + * @inheritDoc + */ + static isValid(value) { + return ( + value?.constructor?.structName === this.structName || + isSerializableIsh(value, this) + ); + } + + static create(context, name, fields) { + const ChildStruct = class extends Struct {}; + + ChildStruct.structName = name; + + context.results[name] = ChildStruct; + + const mappedFields = new Array(fields.length); + for (let i = 0; i < fields.length; i++) { + const fieldDescriptor = fields[i]; + const fieldName = fieldDescriptor[0]; + let field = fieldDescriptor[1]; + if (field instanceof Reference) { + field = field.resolve(context); + } + mappedFields[i] = [fieldName, field]; + // create accessors + ChildStruct.prototype[fieldName] = createAccessorMethod(fieldName); + } + + ChildStruct._fields = mappedFields; + + return ChildStruct; + } +} + +function createAccessorMethod(name) { + return function readOrWriteAttribute(value) { + if (value !== undefined) { + this._attributes[name] = value; + } + return this._attributes[name]; + }; +} diff --git a/node_modules/@stellar/js-xdr/src/types.js b/node_modules/@stellar/js-xdr/src/types.js new file mode 100644 index 000000000..f1785f815 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/types.js @@ -0,0 +1,26 @@ +export * from './int'; +export * from './hyper'; +export * from './unsigned-int'; +export * from './unsigned-hyper'; +export * from './large-int'; + +export * from './float'; +export * from './double'; +export * from './quadruple'; + +export * from './bool'; + +export * from './string'; + +export * from './opaque'; +export * from './var-opaque'; + +export * from './array'; +export * from './var-array'; + +export * from './option'; +export * from './void'; + +export * from './enum'; +export * from './struct'; +export * from './union'; diff --git a/node_modules/@stellar/js-xdr/src/union.js b/node_modules/@stellar/js-xdr/src/union.js new file mode 100644 index 000000000..2523334e7 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/union.js @@ -0,0 +1,171 @@ +import { Void } from './void'; +import { Reference } from './reference'; +import { XdrCompositeType, isSerializableIsh } from './xdr-type'; +import { XdrWriterError } from './errors'; + +export class Union extends XdrCompositeType { + constructor(aSwitch, value) { + super(); + this.set(aSwitch, value); + } + + set(aSwitch, value) { + if (typeof aSwitch === 'string') { + aSwitch = this.constructor._switchOn.fromName(aSwitch); + } + + this._switch = aSwitch; + const arm = this.constructor.armForSwitch(this._switch); + this._arm = arm; + this._armType = arm === Void ? Void : this.constructor._arms[arm]; + this._value = value; + } + + get(armName = this._arm) { + if (this._arm !== Void && this._arm !== armName) + throw new TypeError(`${armName} not set`); + return this._value; + } + + switch() { + return this._switch; + } + + arm() { + return this._arm; + } + + armType() { + return this._armType; + } + + value() { + return this._value; + } + + static armForSwitch(aSwitch) { + const member = this._switches.get(aSwitch); + if (member !== undefined) { + return member; + } + if (this._defaultArm) { + return this._defaultArm; + } + throw new TypeError(`Bad union switch: ${aSwitch}`); + } + + static armTypeForArm(arm) { + if (arm === Void) { + return Void; + } + return this._arms[arm]; + } + + /** + * @inheritDoc + */ + static read(reader) { + const aSwitch = this._switchOn.read(reader); + const arm = this.armForSwitch(aSwitch); + const armType = arm === Void ? Void : this._arms[arm]; + let value; + if (armType !== undefined) { + value = armType.read(reader); + } else { + value = arm.read(reader); + } + return new this(aSwitch, value); + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if (!this.isValid(value)) { + throw new XdrWriterError( + `${value} has union name ${value?.unionName}, not ${ + this.unionName + }: ${JSON.stringify(value)}` + ); + } + + this._switchOn.write(value.switch(), writer); + value.armType().write(value.value(), writer); + } + + /** + * @inheritDoc + */ + static isValid(value) { + return ( + value?.constructor?.unionName === this.unionName || + isSerializableIsh(value, this) + ); + } + + static create(context, name, config) { + const ChildUnion = class extends Union {}; + + ChildUnion.unionName = name; + context.results[name] = ChildUnion; + + if (config.switchOn instanceof Reference) { + ChildUnion._switchOn = config.switchOn.resolve(context); + } else { + ChildUnion._switchOn = config.switchOn; + } + + ChildUnion._switches = new Map(); + ChildUnion._arms = {}; + + // resolve default arm + let defaultArm = config.defaultArm; + if (defaultArm instanceof Reference) { + defaultArm = defaultArm.resolve(context); + } + + ChildUnion._defaultArm = defaultArm; + + for (const [aSwitch, armName] of config.switches) { + const key = + typeof aSwitch === 'string' + ? ChildUnion._switchOn.fromName(aSwitch) + : aSwitch; + + ChildUnion._switches.set(key, armName); + } + + // add enum-based helpers + // NOTE: we don't have good notation for "is a subclass of XDR.Enum", + // and so we use the following check (does _switchOn have a `values` + // attribute) to approximate the intent. + if (ChildUnion._switchOn.values !== undefined) { + for (const aSwitch of ChildUnion._switchOn.values()) { + // Add enum-based constructors + ChildUnion[aSwitch.name] = function ctr(value) { + return new ChildUnion(aSwitch, value); + }; + + // Add enum-based "set" helpers + ChildUnion.prototype[aSwitch.name] = function set(value) { + return this.set(aSwitch, value); + }; + } + } + + if (config.arms) { + for (const [armsName, value] of Object.entries(config.arms)) { + ChildUnion._arms[armsName] = + value instanceof Reference ? value.resolve(context) : value; + // Add arm accessor helpers + if (value !== Void) { + ChildUnion.prototype[armsName] = function get() { + return this.get(armsName); + }; + } + } + } + + return ChildUnion; + } +} diff --git a/node_modules/@stellar/js-xdr/src/unsigned-hyper.js b/node_modules/@stellar/js-xdr/src/unsigned-hyper.js new file mode 100644 index 000000000..af3b81dc2 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/unsigned-hyper.js @@ -0,0 +1,38 @@ +import { LargeInt } from './large-int'; + +export class UnsignedHyper extends LargeInt { + /** + * @param {Array} parts - Slices to encode + */ + constructor(...args) { + super(args); + } + + get low() { + return Number(this._value & 0xffffffffn) << 0; + } + + get high() { + return Number(this._value >> 32n) >> 0; + } + + get size() { + return 64; + } + + get unsigned() { + return true; + } + + /** + * Create UnsignedHyper instance from two [high][low] i32 values + * @param {Number} low - Low part of u64 number + * @param {Number} high - High part of u64 number + * @return {UnsignedHyper} + */ + static fromBits(low, high) { + return new this(low, high); + } +} + +UnsignedHyper.defineIntBoundaries(); diff --git a/node_modules/@stellar/js-xdr/src/unsigned-int.js b/node_modules/@stellar/js-xdr/src/unsigned-int.js new file mode 100644 index 000000000..6d71fa42e --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/unsigned-int.js @@ -0,0 +1,42 @@ +import { XdrPrimitiveType } from './xdr-type'; +import { XdrWriterError } from './errors'; + +const MAX_VALUE = 4294967295; +const MIN_VALUE = 0; + +export class UnsignedInt extends XdrPrimitiveType { + /** + * @inheritDoc + */ + static read(reader) { + return reader.readUInt32BE(); + } + + /** + * @inheritDoc + */ + static write(value, writer) { + if ( + typeof value !== 'number' || + !(value >= MIN_VALUE && value <= MAX_VALUE) || + value % 1 !== 0 + ) + throw new XdrWriterError('invalid u32 value'); + + writer.writeUInt32BE(value); + } + + /** + * @inheritDoc + */ + static isValid(value) { + if (typeof value !== 'number' || value % 1 !== 0) { + return false; + } + + return value >= MIN_VALUE && value <= MAX_VALUE; + } +} + +UnsignedInt.MAX_VALUE = MAX_VALUE; +UnsignedInt.MIN_VALUE = MIN_VALUE; diff --git a/node_modules/@stellar/js-xdr/src/var-array.js b/node_modules/@stellar/js-xdr/src/var-array.js new file mode 100644 index 000000000..860c39aa5 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/var-array.js @@ -0,0 +1,59 @@ +import { UnsignedInt } from './unsigned-int'; +import { XdrCompositeType } from './xdr-type'; +import { XdrReaderError, XdrWriterError } from './errors'; + +export class VarArray extends XdrCompositeType { + constructor(childType, maxLength = UnsignedInt.MAX_VALUE) { + super(); + this._childType = childType; + this._maxLength = maxLength; + } + + /** + * @inheritDoc + */ + read(reader) { + const length = UnsignedInt.read(reader); + if (length > this._maxLength) + throw new XdrReaderError( + `saw ${length} length VarArray, max allowed is ${this._maxLength}` + ); + + const result = new Array(length); + for (let i = 0; i < length; i++) { + result[i] = this._childType.read(reader); + } + return result; + } + + /** + * @inheritDoc + */ + write(value, writer) { + if (!(value instanceof Array)) + throw new XdrWriterError(`value is not array`); + + if (value.length > this._maxLength) + throw new XdrWriterError( + `got array of size ${value.length}, max allowed is ${this._maxLength}` + ); + + UnsignedInt.write(value.length, writer); + for (const child of value) { + this._childType.write(child, writer); + } + } + + /** + * @inheritDoc + */ + isValid(value) { + if (!(value instanceof Array) || value.length > this._maxLength) { + return false; + } + for (const child of value) { + if (!this._childType.isValid(child)) return false; + } + return true; + } +} diff --git a/node_modules/@stellar/js-xdr/src/var-opaque.js b/node_modules/@stellar/js-xdr/src/var-opaque.js new file mode 100644 index 000000000..056c97fee --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/var-opaque.js @@ -0,0 +1,43 @@ +import { UnsignedInt } from './unsigned-int'; +import { XdrCompositeType } from './xdr-type'; +import { XdrReaderError, XdrWriterError } from './errors'; + +export class VarOpaque extends XdrCompositeType { + constructor(maxLength = UnsignedInt.MAX_VALUE) { + super(); + this._maxLength = maxLength; + } + + /** + * @inheritDoc + */ + read(reader) { + const size = UnsignedInt.read(reader); + if (size > this._maxLength) + throw new XdrReaderError( + `saw ${size} length VarOpaque, max allowed is ${this._maxLength}` + ); + return reader.read(size); + } + + /** + * @inheritDoc + */ + write(value, writer) { + const { length } = value; + if (value.length > this._maxLength) + throw new XdrWriterError( + `got ${value.length} bytes, max allowed is ${this._maxLength}` + ); + // write size info + UnsignedInt.write(length, writer); + writer.write(value, length); + } + + /** + * @inheritDoc + */ + isValid(value) { + return Buffer.isBuffer(value) && value.length <= this._maxLength; + } +} diff --git a/node_modules/@stellar/js-xdr/src/void.js b/node_modules/@stellar/js-xdr/src/void.js new file mode 100644 index 000000000..631379d63 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/void.js @@ -0,0 +1,19 @@ +import { XdrPrimitiveType } from './xdr-type'; +import { XdrWriterError } from './errors'; + +export class Void extends XdrPrimitiveType { + /* jshint unused: false */ + + static read() { + return undefined; + } + + static write(value) { + if (value !== undefined) + throw new XdrWriterError('trying to write value to a void slot'); + } + + static isValid(value) { + return value === undefined; + } +} diff --git a/node_modules/@stellar/js-xdr/src/xdr-type.js b/node_modules/@stellar/js-xdr/src/xdr-type.js new file mode 100644 index 000000000..8dd631dc4 --- /dev/null +++ b/node_modules/@stellar/js-xdr/src/xdr-type.js @@ -0,0 +1,217 @@ +import { XdrReader } from './serialization/xdr-reader'; +import { XdrWriter } from './serialization/xdr-writer'; +import { XdrNotImplementedDefinitionError } from './errors'; + +class XdrType { + /** + * Encode value to XDR format + * @param {XdrEncodingFormat} [format] - Encoding format (one of "raw", "hex", "base64") + * @return {String|Buffer} + */ + toXDR(format = 'raw') { + if (!this.write) return this.constructor.toXDR(this, format); + + const writer = new XdrWriter(); + this.write(this, writer); + return encodeResult(writer.finalize(), format); + } + + /** + * Decode XDR-encoded value + * @param {Buffer|String} input - XDR-encoded input data + * @param {XdrEncodingFormat} [format] - Encoding format (one of "raw", "hex", "base64") + * @return {this} + */ + fromXDR(input, format = 'raw') { + if (!this.read) return this.constructor.fromXDR(input, format); + + const reader = new XdrReader(decodeInput(input, format)); + const result = this.read(reader); + reader.ensureInputConsumed(); + return result; + } + + /** + * Check whether input contains a valid XDR-encoded value + * @param {Buffer|String} input - XDR-encoded input data + * @param {XdrEncodingFormat} [format] - Encoding format (one of "raw", "hex", "base64") + * @return {Boolean} + */ + validateXDR(input, format = 'raw') { + try { + this.fromXDR(input, format); + return true; + } catch (e) { + return false; + } + } + + /** + * Encode value to XDR format + * @param {this} value - Value to serialize + * @param {XdrEncodingFormat} [format] - Encoding format (one of "raw", "hex", "base64") + * @return {Buffer} + */ + static toXDR(value, format = 'raw') { + const writer = new XdrWriter(); + this.write(value, writer); + return encodeResult(writer.finalize(), format); + } + + /** + * Decode XDR-encoded value + * @param {Buffer|String} input - XDR-encoded input data + * @param {XdrEncodingFormat} [format] - Encoding format (one of "raw", "hex", "base64") + * @return {this} + */ + static fromXDR(input, format = 'raw') { + const reader = new XdrReader(decodeInput(input, format)); + const result = this.read(reader); + reader.ensureInputConsumed(); + return result; + } + + /** + * Check whether input contains a valid XDR-encoded value + * @param {Buffer|String} input - XDR-encoded input data + * @param {XdrEncodingFormat} [format] - Encoding format (one of "raw", "hex", "base64") + * @return {Boolean} + */ + static validateXDR(input, format = 'raw') { + try { + this.fromXDR(input, format); + return true; + } catch (e) { + return false; + } + } +} + +export class XdrPrimitiveType extends XdrType { + /** + * Read value from the XDR-serialized input + * @param {XdrReader} reader - XdrReader instance + * @return {this} + * @abstract + */ + // eslint-disable-next-line no-unused-vars + static read(reader) { + throw new XdrNotImplementedDefinitionError(); + } + + /** + * Write XDR value to the buffer + * @param {this} value - Value to write + * @param {XdrWriter} writer - XdrWriter instance + * @return {void} + * @abstract + */ + // eslint-disable-next-line no-unused-vars + static write(value, writer) { + throw new XdrNotImplementedDefinitionError(); + } + + /** + * Check whether XDR primitive value is valid + * @param {this} value - Value to check + * @return {Boolean} + * @abstract + */ + // eslint-disable-next-line no-unused-vars + static isValid(value) { + return false; + } +} + +export class XdrCompositeType extends XdrType { + // Every descendant should implement two methods: read(reader) and write(value, writer) + + /** + * Check whether XDR primitive value is valid + * @param {this} value - Value to check + * @return {Boolean} + * @abstract + */ + // eslint-disable-next-line no-unused-vars + isValid(value) { + return false; + } +} + +class InvalidXdrEncodingFormatError extends TypeError { + constructor(format) { + super(`Invalid format ${format}, must be one of "raw", "hex", "base64"`); + } +} + +function encodeResult(buffer, format) { + switch (format) { + case 'raw': + return buffer; + case 'hex': + return buffer.toString('hex'); + case 'base64': + return buffer.toString('base64'); + default: + throw new InvalidXdrEncodingFormatError(format); + } +} + +function decodeInput(input, format) { + switch (format) { + case 'raw': + return input; + case 'hex': + return Buffer.from(input, 'hex'); + case 'base64': + return Buffer.from(input, 'base64'); + default: + throw new InvalidXdrEncodingFormatError(format); + } +} + +/** + * Provides a "duck typed" version of the native `instanceof` for read/write. + * + * "Duck typing" means if the parameter _looks like_ and _acts like_ a duck + * (i.e. the type we're checking), it will be treated as that type. + * + * In this case, the "type" we're looking for is "like XdrType" but also "like + * XdrCompositeType|XdrPrimitiveType" (i.e. serializable), but also conditioned + * on a particular subclass of "XdrType" (e.g. {@link Union} which extends + * XdrType). + * + * This makes the package resilient to downstream systems that may be combining + * many versions of a package across its stack that are technically compatible + * but fail `instanceof` checks due to cross-pollination. + */ +export function isSerializableIsh(value, subtype) { + return ( + value !== undefined && + value !== null && // prereqs, otherwise `getPrototypeOf` pops + (value instanceof subtype || // quickest check + // Do an initial constructor check (anywhere is fine so that children of + // `subtype` still work), then + (hasConstructor(value, subtype) && + // ensure it has read/write methods, then + typeof value.constructor.read === 'function' && + typeof value.constructor.write === 'function' && + // ensure XdrType is in the prototype chain + hasConstructor(value, 'XdrType'))) + ); +} + +/** Tries to find `subtype` in any of the constructors or meta of `instance`. */ +export function hasConstructor(instance, subtype) { + do { + const ctor = instance.constructor; + if (ctor.name === subtype) { + return true; + } + } while ((instance = Object.getPrototypeOf(instance))); + return false; +} + +/** + * @typedef {'raw'|'hex'|'base64'} XdrEncodingFormat + */ diff --git a/node_modules/@stellar/js-xdr/test/.eslintrc.js b/node_modules/@stellar/js-xdr/test/.eslintrc.js new file mode 100644 index 000000000..4bc70f288 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/.eslintrc.js @@ -0,0 +1,16 @@ +module.exports = { + env: { + mocha: true + }, + globals: { + XDR: true, + chai: true, + sinon: true, + expect: true, + stub: true, + spy: true + }, + rules: { + 'no-unused-vars': 0 + } +}; diff --git a/node_modules/@stellar/js-xdr/test/setup.js b/node_modules/@stellar/js-xdr/test/setup.js new file mode 100644 index 000000000..35394b946 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/setup.js @@ -0,0 +1,23 @@ +if (typeof global === 'undefined') { + // eslint-disable-next-line no-undef + window.global = window; +} +global['XDR'] = require('../src'); +global.chai = require('chai'); +global.sinon = require('sinon'); +global.chai.use(require('sinon-chai')); + +global.expect = global.chai.expect; + +exports.mochaHooks = { + beforeEach: function () { + this.sandbox = global.sinon.createSandbox(); + global.stub = this.sandbox.stub.bind(this.sandbox); + global.spy = this.sandbox.spy.bind(this.sandbox); + }, + afterEach: function () { + delete global.stub; + delete global.spy; + this.sandbox.restore(); + } +}; diff --git a/node_modules/@stellar/js-xdr/test/unit/array_test.js b/node_modules/@stellar/js-xdr/test/unit/array_test.js new file mode 100644 index 000000000..28b77923e --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/array_test.js @@ -0,0 +1,89 @@ +import { XdrReader } from '../../src/serialization/xdr-reader'; +import { XdrWriter } from '../../src/serialization/xdr-writer'; + +let zero = new XDR.Array(XDR.Int, 0); +let one = new XDR.Array(XDR.Int, 1); +let many = new XDR.Array(XDR.Int, 2); + +describe('Array#read', function () { + it('decodes correctly', function () { + expect(read(zero, [])).to.eql([]); + expect(read(zero, [0x00, 0x00, 0x00, 0x00])).to.eql([]); + + expect(read(one, [0x00, 0x00, 0x00, 0x00])).to.eql([0]); + expect(read(one, [0x00, 0x00, 0x00, 0x01])).to.eql([1]); + + expect(read(many, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01])).to.eql( + [0, 1] + ); + expect(read(many, [0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01])).to.eql( + [1, 1] + ); + }); + + it("throws XdrReaderError when the byte stream isn't large enough", function () { + expect(() => read(many, [0x00, 0x00, 0x00, 0x00])).to.throw( + /read outside the boundary/i + ); + }); + + function read(arr, bytes) { + let reader = new XdrReader(bytes); + return arr.read(reader); + } +}); + +describe('Array#write', function () { + let subject = many; + + it('encodes correctly', function () { + expect(write([1, 2])).to.eql([ + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02 + ]); + expect(write([3, 4])).to.eql([ + 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04 + ]); + }); + + it('throws a write error if the value is not the correct length', function () { + expect(() => write(null)).to.throw(/write error/i); + expect(() => write(undefined)).to.throw(/write error/i); + expect(() => write([])).to.throw(/write error/i); + expect(() => write([1])).to.throw(/write error/i); + expect(() => write([1, 2, 3])).to.throw(/write error/i); + }); + + it('throws a write error if a child element is of the wrong type', function () { + expect(() => write([1, null])).to.throw(/write error/i); + expect(() => write([1, undefined])).to.throw(/write error/i); + expect(() => write([1, 'hi'])).to.throw(/write error/i); + }); + + function write(value) { + let writer = new XdrWriter(8); + subject.write(value, writer); + return writer.toArray(); + } +}); + +describe('Array#isValid', function () { + let subject = many; + + it('returns true for an array of the correct size with the correct types', function () { + expect(subject.isValid([1, 2])).to.be.true; + }); + + it('returns false for arrays of the wrong size', function () { + expect(subject.isValid([])).to.be.false; + expect(subject.isValid([1])).to.be.false; + expect(subject.isValid([1, 2, 3])).to.be.false; + }); + + it('returns false if a child element is invalid for the child type', function () { + expect(subject.isValid([1, null])).to.be.false; + expect(subject.isValid([1, undefined])).to.be.false; + expect(subject.isValid([1, 'hello'])).to.be.false; + expect(subject.isValid([1, []])).to.be.false; + expect(subject.isValid([1, {}])).to.be.false; + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/bigint-encoder_test.js b/node_modules/@stellar/js-xdr/test/unit/bigint-encoder_test.js new file mode 100644 index 000000000..1424c8456 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/bigint-encoder_test.js @@ -0,0 +1,318 @@ +import { + encodeBigIntFromBits, + formatIntName, + sliceBigInt +} from '../../src/bigint-encoder'; + +describe('encodeBigIntWithPrecision', function () { + it(`encodes values correctly`, () => { + const testCases = [ + // i64 + [[0], 64, false, 0n], + [[-1], 64, false, -1n], + [['-15258'], 64, false, -15258n], + [[-0x8000000000000000n], 64, false, -0x8000000000000000n], + [[0x7fffffffffffffffn], 64, false, 0x7fffffffffffffffn], + [[1, -0x80000000n], 64, false, -0x7fffffffffffffffn], + [[-1, -1], 64, false, -1n], + [[-2, 0x7fffffffn], 64, false, 0x7ffffffffffffffen], + [[345, -345], 64, false, -0x158fffffea7n], + // u64 + [[0], 64, true, 0n], + [[1n], 64, true, 1n], + [[0xffffffffffffffffn], 64, true, 0xffffffffffffffffn], + [[0n, 0n], 64, true, 0n], + [[1, 0], 64, true, 1n], + [[-1, -1], 64, true, 0xffffffffffffffffn], + [[-2, -1], 64, true, 0xfffffffffffffffen], + // i128 + [[0], 128, false, 0n], + [[-1], 128, false, -1n], + [['-15258'], 128, false, -15258n], + [ + [-0x80000000000000000000000000000000n], + 128, + false, + -0x80000000000000000000000000000000n + ], + [ + [0x7fffffffffffffffffffffffffffffffn], + 128, + false, + 0x7fffffffffffffffffffffffffffffffn + ], + [[1, -2147483648], 128, false, -0x7fffffffffffffffffffffffn], + [[-1, -1], 128, false, -1n], + [ + [-1, 0x7fffffffffffffffn], + 128, + false, + 0x7fffffffffffffffffffffffffffffffn + ], + [ + [0xffffffffffffffffn, 0x7fffffffffffffffn], + 128, + false, + 0x7fffffffffffffffffffffffffffffffn + ], + [ + [0, -0x8000000000000000n], + 128, + false, + -0x80000000000000000000000000000000n + ], + [ + [1, -0x8000000000000000n], + 128, + false, + -0x7fffffffffffffffffffffffffffffffn + ], + [ + [1, 0, 0, -0x80000000n], + 128, + false, + -0x7fffffffffffffffffffffffffffffffn + ], + [[345, 345n, '345', 0x159], 128, false, 0x159000001590000015900000159n], + // u128 + [[0], 128, true, 0n], + [[1n], 128, true, 1n], + [ + [0xffffffffffffffffffffffffffffffffn], + 128, + true, + 0xffffffffffffffffffffffffffffffffn + ], + [[0n, 0n], 128, true, 0n], + [[1, 0], 128, true, 1n], + [[-1, -1], 128, true, 0xffffffffffffffffffffffffffffffffn], + [[-2, -1], 128, true, 0xfffffffffffffffffffffffffffffffen], + [ + [0x5cffffffffffffffn, 0x7fffffffffffffffn], + 128, + true, + 0x7fffffffffffffff5cffffffffffffffn + ], + [ + [1, 1, -1, -0x80000000n], + 128, + true, + 0x80000000ffffffff0000000100000001n + ], + [[345, 345n, '345', 0x159], 128, false, 0x159000001590000015900000159n], + // i256 + [[0], 256, false, 0n], + [[-1], 256, false, -1n], + [['-15258'], 256, false, -15258n], + [ + [-0x8000000000000000000000000000000000000000000000000000000000000000n], + 256, + false, + -0x8000000000000000000000000000000000000000000000000000000000000000n + ], + [ + [0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn], + 256, + false, + 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn + ], + [ + [1, -2147483648], + 256, + false, + -0x7fffffffffffffffffffffffffffffffffffffffn + ], + [[-1, -1], 256, false, -1n], + [ + [-1, 0x7fffffffffffffffn], + 256, + false, + 0x7fffffffffffffffffffffffffffffffffffffffffffffffn + ], + [ + [ + 0xffffffffffffffffffffffffffffffffn, + 0x7fffffffffffffffffffffffffffffffn + ], + 256, + false, + 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn + ], + [ + [0, -0x80000000000000000000000000000000n], + 256, + false, + -0x8000000000000000000000000000000000000000000000000000000000000000n + ], + [ + [1, -0x80000000000000000000000000000000n], + 256, + false, + -0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn + ], + [ + [1, 0, 0, -0x800000000000000n], + 256, + false, + -0x7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn + ], + [ + [345, 345n, '345', -0x159], + 256, + false, + -0x158fffffffffffffea6fffffffffffffea6fffffffffffffea7n + ], + [ + [1, 2, 3, 4, 5, 6, 7, -8], + 256, + false, + -0x7fffffff8fffffff9fffffffafffffffbfffffffcfffffffdffffffffn + ], + [ + [1, -2, 3, -4, 5, -6, 7, -8], + 256, + false, + -0x7fffffff800000005fffffffa00000003fffffffc00000001ffffffffn + ], + // u256 + [[0], 256, true, 0n], + [[1n], 256, true, 1n], + [ + [0xffffffffffffffffffffffffffffffffn], + 256, + true, + 0xffffffffffffffffffffffffffffffffn + ], + [[0n, 0n], 256, true, 0n], + [[1, 0], 256, true, 1n], + [ + [-1, -1], + 256, + true, + 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn + ], + [ + [-2, -1], + 256, + true, + 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffen + ], + [ + [ + 0x5cffffffffffffffffffffffffffffffn, + 0x7fffffffffffffffffffffffffffffffn + ], + 256, + true, + 0x7fffffffffffffffffffffffffffffff5cffffffffffffffffffffffffffffffn + ], + [ + [1, 1, -1, -0x80000000n], + 256, + true, + 0xffffffff80000000ffffffffffffffff00000000000000010000000000000001n + ], + [ + [ + 1558245471070191615n, + 1558245471070191615n, + '1558245471070191615', + 0x159fffffffffffffn + ], + 256, + false, + 0x159fffffffffffff159fffffffffffff159fffffffffffff159fffffffffffffn + ], + [ + [1, 2, 3, 4, 5, 6, 7, 8], + 256, + false, + 0x0000000800000007000000060000000500000004000000030000000200000001n + ] + ]; + + for (let [args, bits, unsigned, expected] of testCases) { + try { + const actual = encodeBigIntFromBits(args, bits, unsigned); + expect(actual).to.eq( + expected, + `bigint values for ${formatIntName( + bits, + unsigned + )} out of range: [${args.join()}]` + ); + } catch (e) { + e.message = `Encoding [${args.join()}] => ${formatIntName( + bits, + unsigned + )} BigInt failed with error: ${e.message}`; + throw e; + } + } + }); +}); + +describe('sliceBigInt', function () { + it(`slices values correctly`, () => { + const testCases = [ + [0n, 64, 64, [0n]], + [0n, 256, 256, [0n]], + [-1n, 64, 32, [-1n, -1n]], + [0xfffffffffffffffen, 64, 32, [-2n, -1n]], + [ + 0x7fffffffffffffff5cffffffffffffffn, + 128, + 64, + [0x5cffffffffffffffn, 0x7fffffffffffffffn] + ], + [ + 0x80000000ffffffff0000000100000001n, + 128, + 32, + [1n, 1n, -1n, -0x80000000n] + ], + [ + -0x158fffffffffffffea6fffffffffffffea6fffffffffffffea7n, + 256, + 64, + [345n, 345n, 345n, -345n] + ], + [ + 0x0000000800000007000000060000000500000004000000030000000200000001n, + 256, + 32, + [1n, 2n, 3n, 4n, 5n, 6n, 7n, 8n] + ], + [ + -0x7fffffff8fffffff9fffffffafffffffbfffffffcfffffffdffffffffn, + 256, + 32, + [1n, 2n, 3n, 4n, 5n, 6n, 7n, -8n] + ], + [ + -0x7fffffff800000005fffffffa00000003fffffffc00000001ffffffffn, + 256, + 32, + [1n, -2n, 3n, -4n, 5n, -6n, 7n, -8n] + ] + ]; + for (let [value, size, sliceSize, expected] of testCases) { + try { + const actual = sliceBigInt(value, size, sliceSize); + expect(actual).to.eql( + expected, + `Invalid ${formatIntName( + size, + false + )} / ${sliceSize} slicing result for ${value}` + ); + } catch (e) { + e.message = `Slicing ${value} for ${formatIntName( + size, + false + )} / ${sliceSize} failed with error: ${e.message}`; + throw e; + } + } + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/bool_test.js b/node_modules/@stellar/js-xdr/test/unit/bool_test.js new file mode 100644 index 000000000..237c44871 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/bool_test.js @@ -0,0 +1,47 @@ +import { XdrWriter } from '../../src/serialization/xdr-writer'; +import { XdrReader } from '../../src/serialization/xdr-reader'; +let Bool = XDR.Bool; + +describe('Bool.read', function () { + it('decodes correctly', function () { + expect(read([0, 0, 0, 0])).to.eql(false); + expect(read([0, 0, 0, 1])).to.eql(true); + + expect(() => read([0, 0, 0, 2])).to.throw(/read error/i); + expect(() => read([255, 255, 255, 255])).to.throw(/read error/i); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return Bool.read(io); + } +}); + +describe('Bool.write', function () { + it('encodes correctly', function () { + expect(write(false)).to.eql([0, 0, 0, 0]); + expect(write(true)).to.eql([0, 0, 0, 1]); + }); + + function write(value) { + let io = new XdrWriter(8); + Bool.write(value, io); + return io.toArray(); + } +}); + +describe('Bool.isValid', function () { + it('returns true for booleans', function () { + expect(Bool.isValid(true)).to.be.true; + expect(Bool.isValid(false)).to.be.true; + }); + + it('returns false for non booleans', function () { + expect(Bool.isValid(0)).to.be.false; + expect(Bool.isValid('0')).to.be.false; + expect(Bool.isValid([true])).to.be.false; + expect(Bool.isValid(null)).to.be.false; + expect(Bool.isValid({})).to.be.false; + expect(Bool.isValid(undefined)).to.be.false; + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/define_test.js b/node_modules/@stellar/js-xdr/test/unit/define_test.js new file mode 100644 index 000000000..504b471a5 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/define_test.js @@ -0,0 +1,175 @@ +import * as XDR from '../../src'; + +describe('XDR.config', function () { + beforeEach(function () { + this.types = XDR.config(); // get the xdr object root + for (const toDelete of Object.keys(this.types)) { + delete this.types[toDelete]; + } + }); + + it('can define objects that have no dependency', function () { + XDR.config((xdr) => { + xdr.enum('Color', { + red: 0, + green: 1, + blue: 2 + }); + + xdr.enum('ResultType', { + ok: 0, + error: 1 + }); + }, this.types); + + expect(this.types.Color).to.exist; + expect(this.types.ResultType).to.exist; + }); + + it('can define objects with the same name from different contexts', function () { + XDR.config((xdr) => { + xdr.enum('Color', { + red: 0, + green: 1, + blue: 2 + }); + }); + + XDR.config((xdr) => { + xdr.enum('Color', { + red: 0, + green: 1, + blue: 2 + }); + }); + }); + + it('can define objects that have simple dependencies', function () { + XDR.config((xdr) => { + xdr.union('Result', { + switchOn: xdr.lookup('ResultType'), + switches: [ + ['ok', XDR.Void], + ['error', 'message'] + ], + defaultArm: XDR.Void, + arms: { + message: new XDR.String(100) + } + }); + + xdr.enum('ResultType', { + ok: 0, + error: 1 + }); + }, this.types); + + expect(this.types.Result).to.exist; + expect(this.types.ResultType).to.exist; + + let result = this.types.Result.ok(); + expect(result.switch()).to.eql(this.types.ResultType.ok()); + + result = this.types.Result.error('It broke!'); + expect(result.switch()).to.eql(this.types.ResultType.error()); + expect(result.message()).to.eql('It broke!'); + }); + + it('can define structs', function () { + XDR.config((xdr) => { + xdr.struct('Color', [ + ['red', xdr.int()], + ['green', xdr.int()], + ['blue', xdr.int()] + ]); + }, this.types); + + expect(this.types.Color).to.exist; + + let result = new this.types.Color({ + red: 0, + green: 1, + blue: 2 + }); + expect(result.red()).to.eql(0); + expect(result.green()).to.eql(1); + expect(result.blue()).to.eql(2); + }); + + it('can define typedefs', function () { + let xdr = XDR.config((xdr) => { + xdr.typedef('Uint256', xdr.opaque(32)); + }); + expect(xdr.Uint256).to.be.instanceof(XDR.Opaque); + }); + + it('can define consts', function () { + let xdr = XDR.config((xdr) => { + xdr.typedef('MAX_SIZE', 300); + }); + expect(xdr.MAX_SIZE).to.eql(300); + }); + + it('can define arrays', function () { + let xdr = XDR.config((xdr) => { + xdr.typedef('ArrayOfInts', xdr.array(xdr.int(), 3)); + xdr.struct('MyStruct', [['red', xdr.int()]]); + xdr.typedef('ArrayOfEmpty', xdr.array(xdr.lookup('MyStruct'), 5)); + }); + + expect(xdr.ArrayOfInts).to.be.instanceof(XDR.Array); + expect(xdr.ArrayOfInts._childType).to.eql(XDR.Int); + expect(xdr.ArrayOfInts._length).to.eql(3); + + expect(xdr.ArrayOfEmpty).to.be.instanceof(XDR.Array); + expect(xdr.ArrayOfEmpty._childType).to.eql(xdr.MyStruct); + expect(xdr.ArrayOfEmpty._length).to.eql(5); + }); + + it('can define vararrays', function () { + let xdr = XDR.config((xdr) => { + xdr.typedef('ArrayOfInts', xdr.varArray(xdr.int(), 3)); + }); + + expect(xdr.ArrayOfInts).to.be.instanceof(XDR.VarArray); + expect(xdr.ArrayOfInts._childType).to.eql(XDR.Int); + expect(xdr.ArrayOfInts._maxLength).to.eql(3); + }); + + it('can define options', function () { + let xdr = XDR.config((xdr) => { + xdr.typedef('OptionalInt', xdr.option(xdr.int())); + }); + + expect(xdr.OptionalInt).to.be.instanceof(XDR.Option); + expect(xdr.OptionalInt._childType).to.eql(XDR.Int); + }); + + it('can use sizes defined as an xdr const', function () { + let xdr = XDR.config((xdr) => { + xdr.const('SIZE', 5); + xdr.typedef('MyArray', xdr.array(xdr.int(), xdr.lookup('SIZE'))); + xdr.typedef('MyVarArray', xdr.varArray(xdr.int(), xdr.lookup('SIZE'))); + xdr.typedef('MyString', xdr.string(xdr.lookup('SIZE'))); + xdr.typedef('MyOpaque', xdr.opaque(xdr.lookup('SIZE'))); + xdr.typedef('MyVarOpaque', xdr.varOpaque(xdr.lookup('SIZE'))); + }); + + expect(xdr.MyArray).to.be.instanceof(XDR.Array); + expect(xdr.MyArray._childType).to.eql(XDR.Int); + expect(xdr.MyArray._length).to.eql(5); + + expect(xdr.MyVarArray).to.be.instanceof(XDR.VarArray); + expect(xdr.MyVarArray._childType).to.eql(XDR.Int); + expect(xdr.MyVarArray._maxLength).to.eql(5); + + expect(xdr.MyString).to.be.instanceof(XDR.String); + expect(xdr.MyString._maxLength).to.eql(5); + + expect(xdr.MyOpaque).to.be.instanceof(XDR.Opaque); + expect(xdr.MyOpaque._length).to.eql(5); + + expect(xdr.MyVarOpaque).to.be.instanceof(XDR.VarOpaque); + expect(xdr.MyVarOpaque._maxLength).to.eql(5); + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/double_test.js b/node_modules/@stellar/js-xdr/test/unit/double_test.js new file mode 100644 index 000000000..98ccc26c8 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/double_test.js @@ -0,0 +1,62 @@ +import { XdrWriter } from '../../src/serialization/xdr-writer'; +import { XdrReader } from '../../src/serialization/xdr-reader'; +let Double = XDR.Double; + +describe('Double.read', function () { + it('decodes correctly', function () { + expect(read([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])).to.eql(0.0); + expect(read([0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])).to.eql(-0.0); + expect(read([0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])).to.eql(1.0); + expect(read([0xbf, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])).to.eql(-1.0); + expect(read([0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])).to.eql(NaN); + expect(read([0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01])).to.eql(NaN); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return Double.read(io); + } +}); + +describe('Double.write', function () { + it('encodes correctly', function () { + expect(write(0.0)).to.eql([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); + expect(write(-0.0)).to.eql([ + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ]); + expect(write(1.0)).to.eql([0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); + expect(write(-1.0)).to.eql([ + 0xbf, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ]); + }); + + function write(value) { + let io = new XdrWriter(8); + Double.write(value, io); + return io.toArray(); + } +}); + +describe('Double.isValid', function () { + it('returns true for numbers', function () { + expect(Double.isValid(0)).to.be.true; + expect(Double.isValid(-1)).to.be.true; + expect(Double.isValid(1.0)).to.be.true; + expect(Double.isValid(100000.0)).to.be.true; + expect(Double.isValid(NaN)).to.be.true; + expect(Double.isValid(Infinity)).to.be.true; + expect(Double.isValid(-Infinity)).to.be.true; + }); + + it('returns false for non numbers', function () { + expect(Double.isValid(true)).to.be.false; + expect(Double.isValid(false)).to.be.false; + expect(Double.isValid(null)).to.be.false; + expect(Double.isValid('0')).to.be.false; + expect(Double.isValid([])).to.be.false; + expect(Double.isValid([0])).to.be.false; + expect(Double.isValid('hello')).to.be.false; + expect(Double.isValid({ why: 'hello' })).to.be.false; + expect(Double.isValid(['how', 'do', 'you', 'do'])).to.be.false; + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/dynamic-buffer-resize_test.js b/node_modules/@stellar/js-xdr/test/unit/dynamic-buffer-resize_test.js new file mode 100644 index 000000000..3ad5b64bb --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/dynamic-buffer-resize_test.js @@ -0,0 +1,19 @@ +import { XdrWriter } from '../../src/serialization/xdr-writer'; + +describe('Dynamic writer buffer resize', function () { + it('automatically resize buffer', function () { + const str = new XDR.String(32768); + let io = new XdrWriter(12); + str.write('7 bytes', io); + // expect buffer size to equal base size + expect(io._buffer.length).to.eql(12); + str.write('a'.repeat(32768), io); + // expect buffer growth up to 5 chunks + expect(io._buffer.length).to.eql(40960); + // increase by 1 more 8 KB chunk + str.write('a'.repeat(9000), io); + expect(io._buffer.length).to.eql(49152); + // check final buffer size + expect(io.toArray().length).to.eql(41788); + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/enum_test.js b/node_modules/@stellar/js-xdr/test/unit/enum_test.js new file mode 100644 index 000000000..f9b59c77a --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/enum_test.js @@ -0,0 +1,117 @@ +import { XdrReader } from '../../src/serialization/xdr-reader'; +import { XdrWriter } from '../../src/serialization/xdr-writer'; +import { Enum } from '../../src/enum'; + +/* jshint -W030 */ + +let emptyContext = { definitions: {}, results: {} }; +let Color = XDR.Enum.create(emptyContext, 'Color', { + red: 0, + green: 1, + evenMoreGreen: 3 +}); + +describe('Enum.fromName', function () { + it('returns the member with the provided name', function () { + expect(Color.fromName('red')).to.eql(Color.red()); + expect(Color.fromName('green')).to.eql(Color.green()); + expect(Color.fromName('evenMoreGreen')).to.eql(Color.evenMoreGreen()); + }); + + it('throws an error if the name is not correct', function () { + expect(() => Color.fromName('obviouslyNotAColor')).to.throw( + /not a member/i + ); + }); +}); + +describe('Enum.fromValue', function () { + it('returns the member with the provided value', function () { + expect(Color.fromValue(0)).to.eql(Color.red()); + expect(Color.fromValue(1)).to.eql(Color.green()); + expect(Color.fromValue(3)).to.eql(Color.evenMoreGreen()); + }); + + it('throws an error if the value is not correct', function () { + expect(() => Color.fromValue(999)).to.throw(/not a value/i); + }); +}); + +describe('Enum.read', function () { + it('decodes correctly', function () { + expect(read([0x00, 0x00, 0x00, 0x00])).to.eql(Color.red()); + expect(read([0x00, 0x00, 0x00, 0x01])).to.eql(Color.green()); + expect(read([0x00, 0x00, 0x00, 0x03])).to.eql(Color.evenMoreGreen()); + }); + + it("throws read error when encoded value isn't defined on the enum", function () { + expect(() => read([0x00, 0x00, 0x00, 0x02])).to.throw(/read error/i); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return Color.read(io); + } +}); + +describe('Enum.write', function () { + it('encodes correctly', function () { + expect(write(Color.red())).to.eql([0x00, 0x00, 0x00, 0x00]); + expect(write(Color.green())).to.eql([0x00, 0x00, 0x00, 0x01]); + expect(write(Color.evenMoreGreen())).to.eql([0x00, 0x00, 0x00, 0x03]); + + expect(Color.red().toXDR('hex')).to.eql('00000000'); + expect(Color.green().toXDR('hex')).to.eql('00000001'); + expect(Color.evenMoreGreen().toXDR('hex')).to.eql('00000003'); + }); + + it('throws a write error if the value is not the correct type', function () { + expect(() => write(null)).to.throw(/write error/i); + expect(() => write(undefined)).to.throw(/write error/i); + expect(() => write([])).to.throw(/write error/i); + expect(() => write({})).to.throw(/write error/i); + expect(() => write(1)).to.throw(/write error/i); + expect(() => write(true)).to.throw(/write error/i); + }); + + function write(value) { + let io = new XdrWriter(8); + Color.write(value, io); + return io.toArray(); + } +}); + +describe('Enum.isValid', function () { + it('returns true for members of the enum', function () { + expect(Color.isValid(Color.red())).to.be.true; + expect(Color.isValid(Color.green())).to.be.true; + expect(Color.isValid(Color.evenMoreGreen())).to.be.true; + }); + + it('works for "enum-like" objects', function () { + class FakeEnum extends Enum {} + FakeEnum.enumName = 'Color'; + + let r = new FakeEnum(); + expect(Color.isValid(r)).to.be.true; + + FakeEnum.enumName = 'NotColor'; + r = new FakeEnum(); + expect(Color.isValid(r)).to.be.false; + + // make sure you can't fool it + FakeEnum.enumName = undefined; + FakeEnum.unionName = 'Color'; + r = new FakeEnum(); + expect(Color.isValid(r)).to.be.false; + }); + + it('returns false for arrays of the wrong size', function () { + expect(Color.isValid(null)).to.be.false; + expect(Color.isValid(undefined)).to.be.false; + expect(Color.isValid([])).to.be.false; + expect(Color.isValid({})).to.be.false; + expect(Color.isValid(1)).to.be.false; + expect(Color.isValid(true)).to.be.false; + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/float_test.js b/node_modules/@stellar/js-xdr/test/unit/float_test.js new file mode 100644 index 000000000..be790ddfb --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/float_test.js @@ -0,0 +1,58 @@ +let Float = XDR.Float; +import { XdrReader } from '../../src/serialization/xdr-reader'; +import { XdrWriter } from '../../src/serialization/xdr-writer'; + +describe('Float.read', function () { + it('decodes correctly', function () { + expect(read([0x00, 0x00, 0x00, 0x00])).to.eql(0.0); + expect(read([0x80, 0x00, 0x00, 0x00])).to.eql(-0.0); + expect(read([0x3f, 0x80, 0x00, 0x00])).to.eql(1.0); + expect(read([0xbf, 0x80, 0x00, 0x00])).to.eql(-1.0); + expect(read([0x7f, 0xc0, 0x00, 0x00])).to.eql(NaN); + expect(read([0x7f, 0xf8, 0x00, 0x00])).to.eql(NaN); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return Float.read(io); + } +}); + +describe('Float.write', function () { + it('encodes correctly', function () { + expect(write(0.0)).to.eql([0x00, 0x00, 0x00, 0x00]); + expect(write(-0.0)).to.eql([0x80, 0x00, 0x00, 0x00]); + expect(write(1.0)).to.eql([0x3f, 0x80, 0x00, 0x00]); + expect(write(-1.0)).to.eql([0xbf, 0x80, 0x00, 0x00]); + }); + + function write(value) { + let io = new XdrWriter(8); + Float.write(value, io); + return io.toArray(); + } +}); + +describe('Float.isValid', function () { + it('returns true for numbers', function () { + expect(Float.isValid(0)).to.be.true; + expect(Float.isValid(-1)).to.be.true; + expect(Float.isValid(1.0)).to.be.true; + expect(Float.isValid(100000.0)).to.be.true; + expect(Float.isValid(NaN)).to.be.true; + expect(Float.isValid(Infinity)).to.be.true; + expect(Float.isValid(-Infinity)).to.be.true; + }); + + it('returns false for non numbers', function () { + expect(Float.isValid(true)).to.be.false; + expect(Float.isValid(false)).to.be.false; + expect(Float.isValid(null)).to.be.false; + expect(Float.isValid('0')).to.be.false; + expect(Float.isValid([])).to.be.false; + expect(Float.isValid([0])).to.be.false; + expect(Float.isValid('hello')).to.be.false; + expect(Float.isValid({ why: 'hello' })).to.be.false; + expect(Float.isValid(['how', 'do', 'you', 'do'])).to.be.false; + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/hyper_test.js b/node_modules/@stellar/js-xdr/test/unit/hyper_test.js new file mode 100644 index 000000000..2d5acd45f --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/hyper_test.js @@ -0,0 +1,86 @@ +import { XdrWriter } from '../../src/serialization/xdr-writer'; +import { XdrReader } from '../../src/serialization/xdr-reader'; +let Hyper = XDR.Hyper; + +describe('Hyper.read', function () { + it('decodes correctly', function () { + expect(read([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])).to.eql( + Hyper.fromString('0') + ); + expect(read([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01])).to.eql( + Hyper.fromString('1') + ); + expect(read([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff])).to.eql( + Hyper.fromString('-1') + ); + expect(read([0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff])).to.eql( + new Hyper(Hyper.MAX_VALUE) + ); + expect(read([0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])).to.eql( + new Hyper(Hyper.MIN_VALUE) + ); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return Hyper.read(io); + } +}); + +describe('Hyper.write', function () { + it('encodes correctly', function () { + expect(write(Hyper.fromString('0'))).to.eql([ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ]); + expect(write(Hyper.fromString('1'))).to.eql([ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 + ]); + expect(write(Hyper.fromString('-1'))).to.eql([ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff + ]); + expect(write(Hyper.MAX_VALUE)).to.eql([ + 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff + ]); + expect(write(Hyper.MIN_VALUE)).to.eql([ + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ]); + }); + + function write(value) { + let io = new XdrWriter(8); + Hyper.write(value, io); + return io.toArray(); + } +}); + +describe('Hyper.isValid', function () { + it('returns true for Hyper instances', function () { + expect(Hyper.isValid(Hyper.MIN_VALUE)).to.be.true; + expect(Hyper.isValid(Hyper.MAX_VALUE)).to.be.true; + expect(Hyper.isValid(Hyper.fromString('0'))).to.be.true; + expect(Hyper.isValid(Hyper.fromString('-1'))).to.be.true; + }); + + it('returns false for non Hypers', function () { + expect(Hyper.isValid(null)).to.be.false; + expect(Hyper.isValid(undefined)).to.be.false; + expect(Hyper.isValid([])).to.be.false; + expect(Hyper.isValid({})).to.be.false; + expect(Hyper.isValid(1)).to.be.false; + expect(Hyper.isValid(true)).to.be.false; + }); +}); + +describe('Hyper.fromString', function () { + it('works for positive numbers', function () { + expect(Hyper.fromString('1059').toString()).to.eql('1059'); + }); + + it('works for negative numbers', function () { + expect(Hyper.fromString('-1059').toString()).to.eql('-1059'); + }); + + it('fails when providing a string with a decimal place', function () { + expect(() => Hyper.fromString('105946095601.5')).to.throw(/bigint/); + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/int_test.js b/node_modules/@stellar/js-xdr/test/unit/int_test.js new file mode 100644 index 000000000..122260453 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/int_test.js @@ -0,0 +1,78 @@ +import { XdrWriter } from '../../src/serialization/xdr-writer'; +import { XdrReader } from '../../src/serialization/xdr-reader'; +let Int = XDR.Int; + +describe('Int.read', function () { + it('decodes correctly', function () { + expect(read([0x00, 0x00, 0x00, 0x00])).to.eql(0); + expect(read([0x00, 0x00, 0x00, 0x01])).to.eql(1); + expect(read([0xff, 0xff, 0xff, 0xff])).to.eql(-1); + expect(read([0x7f, 0xff, 0xff, 0xff])).to.eql(Math.pow(2, 31) - 1); + expect(read([0x80, 0x00, 0x00, 0x00])).to.eql(-Math.pow(2, 31)); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return Int.read(io); + } +}); + +describe('Int.write', function () { + it('encodes correctly', function () { + expect(write(0)).to.eql([0x00, 0x00, 0x00, 0x00]); + expect(write(1)).to.eql([0x00, 0x00, 0x00, 0x01]); + expect(write(-1)).to.eql([0xff, 0xff, 0xff, 0xff]); + expect(write(Math.pow(2, 31) - 1)).to.eql([0x7f, 0xff, 0xff, 0xff]); + expect(write(-Math.pow(2, 31))).to.eql([0x80, 0x00, 0x00, 0x00]); + }); + + it('throws a write error if the value is not an integral number', function () { + expect(() => write(true)).to.throw(/write error/i); + expect(() => write(undefined)).to.throw(/write error/i); + expect(() => write([])).to.throw(/write error/i); + expect(() => write({})).to.throw(/write error/i); + expect(() => write(1.1)).to.throw(/write error/i); + }); + + function write(value) { + let io = new XdrWriter(8); + Int.write(value, io); + return io.toArray(); + } +}); + +describe('Int.isValid', function () { + it('returns true for number in a 32-bit range', function () { + expect(Int.isValid(0)).to.be.true; + expect(Int.isValid(-1)).to.be.true; + expect(Int.isValid(1.0)).to.be.true; + expect(Int.isValid(Math.pow(2, 31) - 1)).to.be.true; + expect(Int.isValid(-Math.pow(2, 31))).to.be.true; + }); + + it('returns false for numbers outside a 32-bit range', function () { + expect(Int.isValid(Math.pow(2, 31))).to.be.false; + expect(Int.isValid(-(Math.pow(2, 31) + 1))).to.be.false; + expect(Int.isValid(1000000000000)).to.be.false; + }); + + it('returns false for non numbers', function () { + expect(Int.isValid(true)).to.be.false; + expect(Int.isValid(false)).to.be.false; + expect(Int.isValid(null)).to.be.false; + expect(Int.isValid('0')).to.be.false; + expect(Int.isValid([])).to.be.false; + expect(Int.isValid([0])).to.be.false; + expect(Int.isValid('hello')).to.be.false; + expect(Int.isValid({ why: 'hello' })).to.be.false; + expect(Int.isValid(['how', 'do', 'you', 'do'])).to.be.false; + expect(Int.isValid(NaN)).to.be.false; + }); + + it('returns false for non-integral values', function () { + expect(Int.isValid(1.1)).to.be.false; + expect(Int.isValid(0.1)).to.be.false; + expect(Int.isValid(-0.1)).to.be.false; + expect(Int.isValid(-1.1)).to.be.false; + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/opaque_test.js b/node_modules/@stellar/js-xdr/test/unit/opaque_test.js new file mode 100644 index 000000000..7bab2169b --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/opaque_test.js @@ -0,0 +1,54 @@ +import { XdrReader } from '../../src/serialization/xdr-reader'; +import { XdrWriter } from '../../src/serialization/xdr-writer'; +let Opaque = XDR.Opaque; + +let subject = new Opaque(3); + +describe('Opaque#read', function () { + it('decodes correctly', function () { + expect(read([0, 0, 0, 0])).to.eql(Buffer.from([0, 0, 0])); + expect(read([0, 0, 1, 0])).to.eql(Buffer.from([0, 0, 1])); + }); + + it('throws a read error if the padding bytes are not zero', function () { + expect(() => read([0, 0, 1, 1])).to.throw(/read error/i); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + const res = subject.read(io); + expect(io._index).to.eql(4, 'padding not processed by the reader'); + return res; + } +}); + +describe('Opaque#write', function () { + it('encodes correctly', function () { + expect(write(Buffer.from([0, 0, 0]))).to.eql([0, 0, 0, 0]); + expect(write(Buffer.from([0, 0, 1]))).to.eql([0, 0, 1, 0]); + }); + + function write(value) { + let io = new XdrWriter(8); + subject.write(value, io); + return io.toArray(); + } +}); + +describe('Opaque#isValid', function () { + it('returns true for buffers of the correct length', function () { + expect(subject.isValid(Buffer.alloc(3))).to.be.true; + }); + + it('returns false for buffers of the wrong size', function () { + expect(subject.isValid(Buffer.alloc(2))).to.be.false; + expect(subject.isValid(Buffer.alloc(4))).to.be.false; + }); + + it('returns false for non buffers', function () { + expect(subject.isValid(true)).to.be.false; + expect(subject.isValid(null)).to.be.false; + expect(subject.isValid(3)).to.be.false; + expect(subject.isValid([0])).to.be.false; + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/option_test.js b/node_modules/@stellar/js-xdr/test/unit/option_test.js new file mode 100644 index 000000000..d924bc447 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/option_test.js @@ -0,0 +1,49 @@ +import { XdrReader } from '../../src/serialization/xdr-reader'; +import { XdrWriter } from '../../src/serialization/xdr-writer'; + +const subject = new XDR.Option(XDR.Int); + +describe('Option#read', function () { + it('decodes correctly', function () { + expect(read([0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00])).to.eql(0); + expect(read([0x00, 0x00, 0x00, 0x00])).to.be.undefined; + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return subject.read(io); + } +}); + +describe('Option#write', function () { + it('encodes correctly', function () { + expect(write(3)).to.eql([0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03]); + expect(write(null)).to.eql([0x00, 0x00, 0x00, 0x00]); + expect(write(undefined)).to.eql([0x00, 0x00, 0x00, 0x00]); + }); + + function write(value) { + let io = new XdrWriter(8); + subject.write(value, io); + return io.toArray(); + } +}); + +describe('Option#isValid', function () { + it('returns true for values of the correct child type', function () { + expect(subject.isValid(0)).to.be.true; + expect(subject.isValid(-1)).to.be.true; + expect(subject.isValid(1)).to.be.true; + }); + + it('returns true for null and undefined', function () { + expect(subject.isValid(null)).to.be.true; + expect(subject.isValid(undefined)).to.be.true; + }); + + it('returns false for values of the wrong type', function () { + expect(subject.isValid(false)).to.be.false; + expect(subject.isValid('hello')).to.be.false; + expect(subject.isValid({})).to.be.false; + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/quadruple_test.js b/node_modules/@stellar/js-xdr/test/unit/quadruple_test.js new file mode 100644 index 000000000..8f1c0af01 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/quadruple_test.js @@ -0,0 +1,35 @@ +import { XdrWriter } from '../../src/serialization/xdr-writer'; +import { XdrReader } from '../../src/serialization/xdr-reader'; + +const Quadruple = XDR.Quadruple; + +describe('Quadruple.read', function () { + it('is not supported', function () { + expect(() => read([0x00, 0x00, 0x00, 0x00])).to.throw( + /Type Definition Error/i + ); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return Quadruple.read(io); + } +}); + +describe('Quadruple.write', function () { + it('is not supported', function () { + expect(() => write(0.0)).to.throw(/Type Definition Error/i); + }); + + function write(value) { + let io = new XdrWriter(8); + Quadruple.write(value, io); + return io.toArray(); + } +}); + +describe('Quadruple.isValid', function () { + it('returns false', function () { + expect(Quadruple.isValid(1.0)).to.be.false; + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/string_test.js b/node_modules/@stellar/js-xdr/test/unit/string_test.js new file mode 100644 index 000000000..5e8ad32fc --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/string_test.js @@ -0,0 +1,148 @@ +import { XdrReader } from '../../src/serialization/xdr-reader'; +import { XdrWriter } from '../../src/serialization/xdr-writer'; + +let subject = new XDR.String(4); + +describe('String#read', function () { + it('decodes correctly', function () { + expect(read([0x00, 0x00, 0x00, 0x00]).toString('utf8')).to.eql(''); + expect( + read([0x00, 0x00, 0x00, 0x01, 0x41, 0x00, 0x00, 0x00]).toString('utf8') + ).to.eql('A'); + expect( + read([0x00, 0x00, 0x00, 0x03, 0xe4, 0xb8, 0x89, 0x00]).toString('utf8') + ).to.eql('三'); + expect( + read([0x00, 0x00, 0x00, 0x02, 0x41, 0x41, 0x00, 0x00]).toString('utf8') + ).to.eql('AA'); + }); + + it('decodes correctly to string', function () { + expect(readString([0x00, 0x00, 0x00, 0x00])).to.eql(''); + expect(readString([0x00, 0x00, 0x00, 0x01, 0x41, 0x00, 0x00, 0x00])).to.eql( + 'A' + ); + expect(readString([0x00, 0x00, 0x00, 0x03, 0xe4, 0xb8, 0x89, 0x00])).to.eql( + '三' + ); + expect(readString([0x00, 0x00, 0x00, 0x02, 0x41, 0x41, 0x00, 0x00])).to.eql( + 'AA' + ); + }); + + it('decodes non-utf-8 correctly', function () { + let val = read([0x00, 0x00, 0x00, 0x01, 0xd1, 0x00, 0x00, 0x00]); + expect(val[0]).to.eql(0xd1); + }); + + it('throws a read error when the encoded length is greater than the allowed max', function () { + expect(() => + read([0x00, 0x00, 0x00, 0x05, 0x41, 0x41, 0x41, 0x41, 0x41]) + ).to.throw(/read error/i); + }); + + it('throws a read error if the padding bytes are not zero', function () { + expect(() => + read([0x00, 0x00, 0x00, 0x01, 0x41, 0x01, 0x00, 0x00]) + ).to.throw(/read error/i); + expect(() => + read([0x00, 0x00, 0x00, 0x01, 0x41, 0x00, 0x01, 0x00]) + ).to.throw(/read error/i); + expect(() => + read([0x00, 0x00, 0x00, 0x01, 0x41, 0x00, 0x00, 0x01]) + ).to.throw(/read error/i); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return subject.read(io); + } + + function readString(bytes) { + const io = new XdrReader(bytes); + const res = subject.readString(io); + expect(io._index).to.eql( + !res ? 4 : 8, + 'padding not processed by the reader' + ); + return res; + } +}); + +describe('String#write', function () { + it('encodes string correctly', function () { + expect(write('')).to.eql([0x00, 0x00, 0x00, 0x00]); + expect(write('三')).to.eql([ + 0x00, 0x00, 0x00, 0x03, 0xe4, 0xb8, 0x89, 0x00 + ]); + expect(write('A')).to.eql([0x00, 0x00, 0x00, 0x01, 0x41, 0x00, 0x00, 0x00]); + expect(write('AA')).to.eql([ + 0x00, 0x00, 0x00, 0x02, 0x41, 0x41, 0x00, 0x00 + ]); + }); + + it('encodes non-utf-8 correctly', function () { + expect(write([0xd1])).to.eql([ + 0x00, 0x00, 0x00, 0x01, 0xd1, 0x00, 0x00, 0x00 + ]); + }); + + it('encodes non-utf-8 correctly (buffer)', function () { + expect(write(Buffer.from([0xd1]))).to.eql([ + 0x00, 0x00, 0x00, 0x01, 0xd1, 0x00, 0x00, 0x00 + ]); + }); + + it('checks actual utf-8 strings length on write', function () { + expect(() => write('€€€€')).to.throw(/max allowed/i); + }); + + function write(value) { + let io = new XdrWriter(8); + subject.write(value, io); + return io.toArray(); + } +}); + +describe('String#isValid', function () { + it('returns true for strings of the correct length', function () { + expect(subject.isValid('')).to.be.true; + expect(subject.isValid('a')).to.be.true; + expect(subject.isValid('aa')).to.be.true; + }); + + it('returns true for arrays of the correct length', function () { + expect(subject.isValid([0x01])).to.be.true; + }); + + it('returns true for buffers of the correct length', function () { + expect(subject.isValid(Buffer.from([0x01]))).to.be.true; + }); + + it('returns false for strings that are too large', function () { + expect(subject.isValid('aaaaa')).to.be.false; + }); + + it('returns false for arrays that are too large', function () { + expect(subject.isValid([0x01, 0x01, 0x01, 0x01, 0x01])).to.be.false; + }); + + it('returns false for buffers that are too large', function () { + expect(subject.isValid(Buffer.from([0x01, 0x01, 0x01, 0x01, 0x01]))).to.be + .false; + }); + + it('returns false for non string/array/buffer', function () { + expect(subject.isValid(true)).to.be.false; + expect(subject.isValid(null)).to.be.false; + expect(subject.isValid(3)).to.be.false; + }); +}); + +describe('String#constructor', function () { + let subject = new XDR.String(); + + it('defaults to max length of a uint max value', function () { + expect(subject._maxLength).to.eql(Math.pow(2, 32) - 1); + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/struct_test.js b/node_modules/@stellar/js-xdr/test/unit/struct_test.js new file mode 100644 index 000000000..ee6e50b1a --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/struct_test.js @@ -0,0 +1,135 @@ +import { XdrReader } from '../../src/serialization/xdr-reader'; +import { XdrWriter } from '../../src/serialization/xdr-writer'; +import { Struct } from '../../src/struct'; + +/* jshint -W030 */ + +let emptyContext = { definitions: {}, results: {} }; +let MyRange = XDR.Struct.create(emptyContext, 'MyRange', [ + ['begin', XDR.Int], + ['end', XDR.Int], + ['inclusive', XDR.Bool] +]); + +describe('Struct.read', function () { + it('decodes correctly', function () { + let empty = read([ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ]); + expect(empty).to.be.instanceof(MyRange); + expect(empty.begin()).to.eql(0); + expect(empty.end()).to.eql(0); + expect(empty.inclusive()).to.eql(false); + + let filled = read([ + 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x01 + ]); + expect(filled).to.be.instanceof(MyRange); + expect(filled.begin()).to.eql(5); + expect(filled.end()).to.eql(255); + expect(filled.inclusive()).to.eql(true); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return MyRange.read(io); + } +}); + +describe('Struct.write', function () { + it('encodes correctly', function () { + let empty = new MyRange({ + begin: 0, + end: 0, + inclusive: false + }); + + expect(write(empty)).to.eql([ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ]); + + let filled = new MyRange({ + begin: 5, + end: 255, + inclusive: true + }); + + expect(write(filled)).to.eql([ + 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x01 + ]); + }); + + it('throws a write error if the value is not the correct type', function () { + expect(() => write(null)).to.throw(/write error/i); + expect(() => write(undefined)).to.throw(/write error/i); + expect(() => write([])).to.throw(/write error/i); + expect(() => write({})).to.throw(/write error/i); + expect(() => write(1)).to.throw(/write error/i); + expect(() => write(true)).to.throw(/write error/i); + }); + + it('throws a write error if the struct is not valid', function () { + expect(() => write(new MyRange({}))).to.throw(/write error/i); + }); + + function write(value) { + let io = new XdrWriter(256); + MyRange.write(value, io); + return io.toArray(); + } +}); + +describe('Struct.isValid', function () { + it('returns true for instances of the struct', function () { + expect(MyRange.isValid(new MyRange({}))).to.be.true; + }); + + it('works for "struct-like" objects', function () { + class FakeStruct extends Struct {} + + FakeStruct.structName = 'MyRange'; + let r = new FakeStruct(); + expect(MyRange.isValid(r)).to.be.true; + + FakeStruct.structName = 'NotMyRange'; + r = new FakeStruct(); + expect(MyRange.isValid(r)).to.be.false; + }); + + it('returns false for anything else', function () { + expect(MyRange.isValid(null)).to.be.false; + expect(MyRange.isValid(undefined)).to.be.false; + expect(MyRange.isValid([])).to.be.false; + expect(MyRange.isValid({})).to.be.false; + expect(MyRange.isValid(1)).to.be.false; + expect(MyRange.isValid(true)).to.be.false; + }); +}); + +describe('Struct.validateXDR', function () { + it('returns true for valid XDRs', function () { + let subject = new MyRange({ begin: 5, end: 255, inclusive: true }); + expect(MyRange.validateXDR(subject.toXDR())).to.be.true; + expect(MyRange.validateXDR(subject.toXDR('hex'), 'hex')).to.be.true; + expect(MyRange.validateXDR(subject.toXDR('base64'), 'base64')).to.be.true; + }); + + it('returns false for invalid XDRs', function () { + expect(MyRange.validateXDR(Buffer.alloc(1))).to.be.false; + expect(MyRange.validateXDR('00', 'hex')).to.be.false; + expect(MyRange.validateXDR('AA==', 'base64')).to.be.false; + }); +}); + +describe('Struct: attributes', function () { + it('properly retrieves attributes', function () { + let subject = new MyRange({ begin: 5, end: 255, inclusive: true }); + expect(subject.begin()).to.eql(5); + }); + + it('properly sets attributes', function () { + let subject = new MyRange({ begin: 5, end: 255, inclusive: true }); + expect(subject.begin(10)).to.eql(10); + expect(subject.begin()).to.eql(10); + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/struct_union_test.js b/node_modules/@stellar/js-xdr/test/unit/struct_union_test.js new file mode 100644 index 000000000..8e32120b6 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/struct_union_test.js @@ -0,0 +1,43 @@ +import { XdrReader } from '../../src/serialization/xdr-reader'; + +/* jshint -W030 */ + +let emptyContext = { definitions: {}, results: {} }; + +let Ext = XDR.Union.create(emptyContext, 'Ext', { + switchOn: XDR.Int, + switches: [ + [0, XDR.Void], + [1, XDR.Int] + ] +}); + +let StructUnion = XDR.Struct.create(emptyContext, 'StructUnion', [ + ['id', XDR.Int], + ['ext', Ext] +]); + +describe('StructUnion.read', function () { + it('decodes correctly', function () { + let empty = read([0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00]); + expect(empty).to.be.instanceof(StructUnion); + expect(empty.id()).to.eql(1); + expect(empty.ext().switch()).to.eql(0); + expect(empty.ext().arm()).to.eql(XDR.Void); + + let filled = read([ + 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02 + ]); + + expect(filled).to.be.instanceof(StructUnion); + expect(filled.id()).to.eql(2); + expect(filled.ext().switch()).to.eql(1); + expect(filled.ext().arm()).to.eql(XDR.Int); + expect(filled.ext().value()).to.eql(2); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return StructUnion.read(io); + } +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/union_test.js b/node_modules/@stellar/js-xdr/test/unit/union_test.js new file mode 100644 index 000000000..cd57f7469 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/union_test.js @@ -0,0 +1,161 @@ +import { XdrReader } from '../../src/serialization/xdr-reader'; +import { XdrWriter } from '../../src/serialization/xdr-writer'; +import { XdrPrimitiveType } from '../../src/xdr-type'; + +/* jshint -W030 */ + +let emptyContext = { definitions: {}, results: {} }; +let ResultType = XDR.Enum.create(emptyContext, 'ResultType', { + ok: 0, + error: 1, + nonsense: 2 +}); + +let Result = XDR.Union.create(emptyContext, 'Result', { + switchOn: ResultType, + switches: [ + ['ok', XDR.Void], + ['error', 'code'] + ], + defaultArm: XDR.Void, + arms: { + code: XDR.Int + } +}); + +let Ext = XDR.Union.create(emptyContext, 'Ext', { + switchOn: XDR.Int, + switches: [[0, XDR.Void]] +}); + +describe('Union.armForSwitch', function () { + it('returns the defined arm for the provided switch', function () { + expect(Result.armForSwitch(ResultType.ok())).to.eql(XDR.Void); + expect(Result.armForSwitch(ResultType.error())).to.eql('code'); + }); + + it('returns the default arm if no specific arm is defined', function () { + expect(Result.armForSwitch(ResultType.nonsense())).to.eql(XDR.Void); + }); + + it('works for XDR.Int discriminated unions', function () { + expect(Ext.armForSwitch(0)).to.eql(XDR.Void); + }); +}); + +describe('Union: constructor', function () { + it('works for XDR.Int discriminated unions', function () { + expect(() => new Ext(0)).to.not.throw(); + }); + + it('works for Enum discriminated unions', function () { + expect(() => new Result('ok')).to.not.throw(); + expect(() => new Result(ResultType.ok())).to.not.throw(); + }); +}); + +describe('Union: set', function () { + it('works for XDR.Int discriminated unions', function () { + let u = new Ext(0); + u.set(0); + }); + + it('works for Enum discriminated unions', function () { + let u = Result.ok(); + + expect(() => u.set('ok')).to.not.throw(); + expect(() => u.set('notok')).to.throw(/not a member/); + expect(() => u.set(ResultType.ok())).to.not.throw(); + }); +}); + +describe('Union.read', function () { + it('decodes correctly', function () { + let ok = read([0x00, 0x00, 0x00, 0x00]); + + expect(ok).to.be.instanceof(Result); + expect(ok.switch()).to.eql(ResultType.ok()); + expect(ok.arm()).to.eql(XDR.Void); + expect(ok.armType()).to.eql(XDR.Void); + expect(ok.value()).to.be.undefined; + + let error = read([0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05]); + + expect(error).to.be.instanceof(Result); + expect(error.switch()).to.eql(ResultType.error()); + expect(error.arm()).to.eql('code'); + expect(error.armType()).to.eql(XDR.Int); + expect(error.value()).to.eql(5); + expect(error.code()).to.eql(5); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return Result.read(io); + } +}); + +describe('Union.write', function () { + it('encodes correctly', function () { + let ok = Result.ok(); + + expect(write(ok)).to.eql([0x00, 0x00, 0x00, 0x00]); + + let error = Result.error(5); + + expect(write(error)).to.eql([ + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05 + ]); + }); + + it('throws a write error if the value is not the correct type', function () { + expect(() => write(null)).to.throw(/write error/i); + expect(() => write(undefined)).to.throw(/write error/i); + expect(() => write([])).to.throw(/write error/i); + expect(() => write({})).to.throw(/write error/i); + expect(() => write(1)).to.throw(/write error/i); + expect(() => write(true)).to.throw(/write error/i); + }); + + function write(value) { + let io = new XdrWriter(256); + Result.write(value, io); + return io.toArray(); + } +}); + +describe('Union.isValid', function () { + it('returns true for instances of the union', function () { + expect(Result.isValid(Result.ok())).to.be.true; + expect(Result.isValid(Result.error(1))).to.be.true; + expect(Result.isValid(Result.nonsense())).to.be.true; + }); + + it('works for "union-like" objects', function () { + class FakeUnion extends XdrPrimitiveType {} + + FakeUnion.unionName = 'Result'; + let r = new FakeUnion(); + expect(Result.isValid(r)).to.be.true; + + FakeUnion.unionName = 'NotResult'; + r = new FakeUnion(); + expect(Result.isValid(r)).to.be.false; + + // make sure you can't fool it + FakeUnion.unionName = undefined; + FakeUnion.structName = 'Result'; + r = new FakeUnion(); + expect(Result.isValid(r)).to.be.false; + }); + + it('returns false for anything else', function () { + expect(Result.isValid(null)).to.be.false; + expect(Result.isValid(undefined)).to.be.false; + expect(Result.isValid([])).to.be.false; + expect(Result.isValid({})).to.be.false; + expect(Result.isValid(1)).to.be.false; + expect(Result.isValid(true)).to.be.false; + expect(Result.isValid('ok')).to.be.false; + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/unsigned-hyper_test.js b/node_modules/@stellar/js-xdr/test/unit/unsigned-hyper_test.js new file mode 100644 index 000000000..6a1f773c2 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/unsigned-hyper_test.js @@ -0,0 +1,74 @@ +import { XdrReader } from '../../src/serialization/xdr-reader'; +import { XdrWriter } from '../../src/serialization/xdr-writer'; + +const UnsignedHyper = XDR.UnsignedHyper; + +describe('UnsignedHyper.read', function () { + it('decodes correctly', function () { + expect(read([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])).to.eql( + UnsignedHyper.fromString('0') + ); + expect(read([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01])).to.eql( + UnsignedHyper.fromString('1') + ); + expect(read([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff])).to.eql( + new UnsignedHyper(UnsignedHyper.MAX_VALUE) + ); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return UnsignedHyper.read(io); + } +}); + +describe('UnsignedHyper.write', function () { + it('encodes correctly', function () { + expect(write(UnsignedHyper.fromString('0'))).to.eql([ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ]); + expect(write(UnsignedHyper.fromString('1'))).to.eql([ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 + ]); + expect(write(UnsignedHyper.MAX_VALUE)).to.eql([ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff + ]); + }); + + function write(value) { + let io = new XdrWriter(8); + UnsignedHyper.write(value, io); + return io.toArray(); + } +}); + +describe('UnsignedHyper.isValid', function () { + it('returns true for UnsignedHyper instances', function () { + expect(UnsignedHyper.isValid(UnsignedHyper.fromString('1'))).to.be.true; + expect(UnsignedHyper.isValid(UnsignedHyper.MIN_VALUE)).to.be.true; + expect(UnsignedHyper.isValid(UnsignedHyper.MAX_VALUE)).to.be.true; + }); + + it('returns false for non UnsignedHypers', function () { + expect(UnsignedHyper.isValid(null)).to.be.false; + expect(UnsignedHyper.isValid(undefined)).to.be.false; + expect(UnsignedHyper.isValid([])).to.be.false; + expect(UnsignedHyper.isValid({})).to.be.false; + expect(UnsignedHyper.isValid(1)).to.be.false; + expect(UnsignedHyper.isValid(true)).to.be.false; + }); +}); + +describe('UnsignedHyper.fromString', function () { + it('works for positive numbers', function () { + expect(UnsignedHyper.fromString('1059').toString()).to.eql('1059'); + }); + + it('fails for negative numbers', function () { + expect(() => UnsignedHyper.fromString('-1059')).to.throw(/positive/); + }); + + it('fails when providing a string with a decimal place', function () { + expect(() => UnsignedHyper.fromString('105946095601.5')).to.throw(/bigint/); + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/unsigned-int_test.js b/node_modules/@stellar/js-xdr/test/unit/unsigned-int_test.js new file mode 100644 index 000000000..d8ff87131 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/unsigned-int_test.js @@ -0,0 +1,70 @@ +import { XdrReader } from '../../src/serialization/xdr-reader'; +import { XdrWriter } from '../../src/serialization/xdr-writer'; +let UnsignedInt = XDR.UnsignedInt; + +describe('UnsignedInt.read', function () { + it('decodes correctly', function () { + expect(read([0x00, 0x00, 0x00, 0x00])).to.eql(0); + expect(read([0x00, 0x00, 0x00, 0x01])).to.eql(1); + expect(read([0xff, 0xff, 0xff, 0xff])).to.eql(Math.pow(2, 32) - 1); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return UnsignedInt.read(io); + } +}); + +describe('UnsignedInt.write', function () { + it('encodes correctly', function () { + expect(write(0)).to.eql([0x00, 0x00, 0x00, 0x00]); + expect(write(1)).to.eql([0x00, 0x00, 0x00, 0x01]); + expect(write(Math.pow(2, 32) - 1)).to.eql([0xff, 0xff, 0xff, 0xff]); + }); + + it('throws a write error if the value is not an integral number', function () { + expect(() => write(true)).to.throw(/write error/i); + expect(() => write(undefined)).to.throw(/write error/i); + expect(() => write([])).to.throw(/write error/i); + expect(() => write({})).to.throw(/write error/i); + expect(() => write(1.1)).to.throw(/write error/i); + }); + + function write(value) { + let io = new XdrWriter(8); + UnsignedInt.write(value, io); + return io.toArray(); + } +}); + +describe('UnsignedInt.isValid', function () { + it('returns true for number in a 32-bit range', function () { + expect(UnsignedInt.isValid(0)).to.be.true; + expect(UnsignedInt.isValid(1)).to.be.true; + expect(UnsignedInt.isValid(1.0)).to.be.true; + expect(UnsignedInt.isValid(Math.pow(2, 32) - 1)).to.be.true; + }); + + it('returns false for numbers outside a 32-bit range', function () { + expect(UnsignedInt.isValid(Math.pow(2, 32))).to.be.false; + expect(UnsignedInt.isValid(-1)).to.be.false; + }); + + it('returns false for non numbers', function () { + expect(UnsignedInt.isValid(true)).to.be.false; + expect(UnsignedInt.isValid(false)).to.be.false; + expect(UnsignedInt.isValid(null)).to.be.false; + expect(UnsignedInt.isValid('0')).to.be.false; + expect(UnsignedInt.isValid([])).to.be.false; + expect(UnsignedInt.isValid([0])).to.be.false; + expect(UnsignedInt.isValid('hello')).to.be.false; + expect(UnsignedInt.isValid({ why: 'hello' })).to.be.false; + expect(UnsignedInt.isValid(['how', 'do', 'you', 'do'])).to.be.false; + expect(UnsignedInt.isValid(NaN)).to.be.false; + }); + + it('returns false for non-integral values', function () { + expect(UnsignedInt.isValid(1.1)).to.be.false; + expect(UnsignedInt.isValid(0.1)).to.be.false; + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/var-array_test.js b/node_modules/@stellar/js-xdr/test/unit/var-array_test.js new file mode 100644 index 000000000..fbaa22c0f --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/var-array_test.js @@ -0,0 +1,87 @@ +import { XdrReader } from '../../src/serialization/xdr-reader'; +import { XdrWriter } from '../../src/serialization/xdr-writer'; + +const subject = new XDR.VarArray(XDR.Int, 2); + +describe('VarArray#read', function () { + it('decodes correctly', function () { + expect(read([0x00, 0x00, 0x00, 0x00])).to.eql([]); + + expect(read([0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00])).to.eql([0]); + expect(read([0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01])).to.eql([1]); + + expect( + read([ + 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 + ]) + ).to.eql([0, 1]); + expect( + read([ + 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01 + ]) + ).to.eql([1, 1]); + }); + + it('throws read error when the encoded array is too large', function () { + expect(() => read([0x00, 0x00, 0x00, 0x03])).to.throw(/read error/i); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return subject.read(io); + } +}); + +describe('VarArray#write', function () { + it('encodes correctly', function () { + expect(write([])).to.eql([0x00, 0x00, 0x00, 0x00]); + expect(write([0])).to.eql([0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00]); + expect(write([0, 1])).to.eql([ + 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 + ]); + }); + + it('throws a write error if the value is too large', function () { + expect(() => write([1, 2, 3])).to.throw(/write error/i); + }); + + it('throws a write error if a child element is of the wrong type', function () { + expect(() => write([1, null])).to.throw(/write error/i); + expect(() => write([1, undefined])).to.throw(/write error/i); + expect(() => write([1, 'hi'])).to.throw(/write error/i); + }); + + function write(value) { + let io = new XdrWriter(256); + subject.write(value, io); + return io.toArray(); + } +}); + +describe('VarArray#isValid', function () { + it('returns true for an array of the correct sizes with the correct types', function () { + expect(subject.isValid([])).to.be.true; + expect(subject.isValid([1])).to.be.true; + expect(subject.isValid([1, 2])).to.be.true; + }); + + it('returns false for arrays of the wrong size', function () { + expect(subject.isValid([1, 2, 3])).to.be.false; + }); + + it('returns false if a child element is invalid for the child type', function () { + expect(subject.isValid([1, null])).to.be.false; + expect(subject.isValid([1, undefined])).to.be.false; + expect(subject.isValid([1, 'hello'])).to.be.false; + expect(subject.isValid([1, []])).to.be.false; + expect(subject.isValid([1, {}])).to.be.false; + }); +}); + +describe('VarArray#constructor', function () { + let subject = new XDR.VarArray(XDR.Int); + + it('defaults to max length of a uint max value', function () { + expect(subject._maxLength).to.eql(Math.pow(2, 32) - 1); + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/var-opaque_test.js b/node_modules/@stellar/js-xdr/test/unit/var-opaque_test.js new file mode 100644 index 000000000..ee85a8bd5 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/var-opaque_test.js @@ -0,0 +1,84 @@ +import { XdrReader } from '../../src/serialization/xdr-reader'; +import { XdrWriter } from '../../src/serialization/xdr-writer'; + +const VarOpaque = XDR.VarOpaque; + +let subject = new VarOpaque(2); + +describe('VarOpaque#read', function () { + it('decodes correctly', function () { + expect(read([0, 0, 0, 0])).to.eql(Buffer.from([])); + expect(read([0, 0, 0, 1, 0, 0, 0, 0])).to.eql(Buffer.from([0])); + expect(read([0, 0, 0, 1, 1, 0, 0, 0])).to.eql(Buffer.from([1])); + expect(read([0, 0, 0, 2, 0, 1, 0, 0])).to.eql(Buffer.from([0, 1])); + }); + + it('throws a read error when the encoded length is greater than the allowed max', function () { + expect(() => read([0, 0, 0, 3, 0, 0, 0, 0])).to.throw(/read error/i); + }); + + it('throws a read error if the padding bytes are not zero', function () { + expect(() => + read([0x00, 0x00, 0x00, 0x01, 0x41, 0x01, 0x00, 0x00]) + ).to.throw(/read error/i); + expect(() => + read([0x00, 0x00, 0x00, 0x01, 0x41, 0x00, 0x01, 0x00]) + ).to.throw(/read error/i); + expect(() => + read([0x00, 0x00, 0x00, 0x01, 0x41, 0x00, 0x00, 0x01]) + ).to.throw(/read error/i); + }); + + function read(bytes) { + let io = new XdrReader(bytes); + const res = subject.read(io); + expect(io._index).to.eql( + !res.length ? 4 : 8, + 'padding not processed by the reader' + ); + return res; + } +}); + +describe('VarOpaque#write', function () { + it('encodes correctly', function () { + expect(write(Buffer.from([]))).to.eql([0, 0, 0, 0]); + expect(write(Buffer.from([0]))).to.eql([0, 0, 0, 1, 0, 0, 0, 0]); + expect(write(Buffer.from([1]))).to.eql([0, 0, 0, 1, 1, 0, 0, 0]); + expect(write(Buffer.from([0, 1]))).to.eql([0, 0, 0, 2, 0, 1, 0, 0]); + }); + + function write(value) { + let io = new XdrWriter(8); + subject.write(value, io); + return io.toArray(); + } +}); + +describe('VarOpaque#isValid', function () { + it('returns true for buffers of the correct length', function () { + expect(subject.isValid(Buffer.alloc(0))).to.be.true; + expect(subject.isValid(Buffer.alloc(1))).to.be.true; + expect(subject.isValid(Buffer.alloc(2))).to.be.true; + }); + + it('returns false for buffers of the wrong size', function () { + expect(subject.isValid(Buffer.alloc(3))).to.be.false; + expect(subject.isValid(Buffer.alloc(3000))).to.be.false; + }); + + it('returns false for non buffers', function () { + expect(subject.isValid(true)).to.be.false; + expect(subject.isValid(null)).to.be.false; + expect(subject.isValid(3)).to.be.false; + expect(subject.isValid([0])).to.be.false; + }); +}); + +describe('VarOpaque#constructor', function () { + let subject = new XDR.VarOpaque(); + + it('defaults to max length of a uint max value', function () { + expect(subject._maxLength).to.eql(Math.pow(2, 32) - 1); + }); +}); diff --git a/node_modules/@stellar/js-xdr/test/unit/void_test.js b/node_modules/@stellar/js-xdr/test/unit/void_test.js new file mode 100644 index 000000000..08dc20ac6 --- /dev/null +++ b/node_modules/@stellar/js-xdr/test/unit/void_test.js @@ -0,0 +1,44 @@ +import { XdrReader } from '../../src/serialization/xdr-reader'; +import { XdrWriter } from '../../src/serialization/xdr-writer'; + +let subject = XDR.Void; + +describe('Void#read', function () { + it('decodes correctly', function () { + expect(read([0x00, 0x00, 0x00, 0x00])).to.be.undefined; + expect(read([0x00, 0x00, 0x00, 0x01])).to.be.undefined; + expect(read([0x00, 0x00, 0x00, 0x02])).to.be.undefined; + }); + + function read(bytes) { + let io = new XdrReader(bytes); + return subject.read(io); + } +}); + +describe('Void#write', function () { + it('encodes correctly', function () { + expect(write(undefined)).to.eql([]); + }); + + function write(value) { + let io = new XdrWriter(8); + subject.write(value, io); + return io.toArray(); + } +}); + +describe('Void#isValid', function () { + it('returns true undefined', function () { + expect(subject.isValid(undefined)).to.be.true; + }); + + it('returns false for anything defined', function () { + expect(subject.isValid(null)).to.be.false; + expect(subject.isValid(false)).to.be.false; + expect(subject.isValid(1)).to.be.false; + expect(subject.isValid('aaa')).to.be.false; + expect(subject.isValid({})).to.be.false; + expect(subject.isValid([undefined])).to.be.false; + }); +}); diff --git a/node_modules/@stellar/js-xdr/webpack.config.js b/node_modules/@stellar/js-xdr/webpack.config.js new file mode 100644 index 000000000..f378abcb1 --- /dev/null +++ b/node_modules/@stellar/js-xdr/webpack.config.js @@ -0,0 +1,57 @@ +const path = require('path'); +const webpack = require('webpack'); +const TerserPlugin = require('terser-webpack-plugin'); + +const browserBuild = !process.argv.includes('--mode=development'); + +module.exports = function () { + const mode = browserBuild ? 'production' : 'development'; + const config = { + mode, + devtool: 'source-map', + entry: { + xdr: [path.join(__dirname, '/src/browser.js')] + }, + output: { + path: path.join(__dirname, browserBuild ? './dist' : './lib'), + filename: '[name].js', + library: { + name: 'XDR', + type: 'umd' + }, + globalObject: 'this' + }, + module: { + rules: [ + { + test: /\.js$/, + loader: 'babel-loader', + exclude: /node_modules/ + } + ] + }, + plugins: [ + new webpack.DefinePlugin({ + 'process.env.NODE_ENV': JSON.stringify(mode) + }) + ] + }; + if (browserBuild) { + config.optimization = { + minimize: true, + minimizer: [ + new TerserPlugin({ + parallel: true + }) + ] + }; + config.plugins.push( + new webpack.ProvidePlugin({ + Buffer: [path.resolve(__dirname, 'buffer.js'), 'default'] + }) + ); + } else { + config.target = 'node'; + } + return config; +}; diff --git a/node_modules/@stellar/stellar-base/CHANGELOG.md b/node_modules/@stellar/stellar-base/CHANGELOG.md new file mode 100644 index 000000000..601a3faf7 --- /dev/null +++ b/node_modules/@stellar/stellar-base/CHANGELOG.md @@ -0,0 +1,1376 @@ +# Changelog + +## Unreleased + + +## [`v13.0.1`](https://github.com/stellar/js-stellar-base/compare/v13.0.0...v13.0.1) + +### Fixed +* `buildInvocationTree` will now successfully walk creation invocations with constructor arguments ([#784](https://github.com/stellar/js-stellar-base/pull/784)). + + +## [`v13.0.0`](https://github.com/stellar/js-stellar-base/compare/v12.1.1...v13.0.0) + +**This release supports Protocol 22.** While the network has not upgraded yet, you can start integrating the new features into your codebase if you want a head start. Keep in mind that while the binary XDR is backwards-compatible, the naming and layout of structures is not. In other words, this build will continue to work on Protocol 21, but you may have to update code that references XDR directly. + +This version is unchanged from [`beta.1`](#v13.0.0-beta.1). + + +## [`v13.0.0-beta.1`](https://github.com/stellar/js-stellar-base/compare/v12.1.1...v13.0.0-beta.1) + +**This is the first release that supports Protocol 22.** While the network has not upgraded yet, you can start integrating the new features into your codebase if you want a head start. Keep in mind that while the binary XDR is backwards-compatible, the naming and layout of structures is not. In other words, this build will continue to work on Protocol 21, but you may have to update code that references XDR directly. + +### Breaking Changes +* XDR definitions have been upgraded to Protocol 22 ([#777](https://github.com/stellar/js-stellar-base/pull/777)). + +### Added +* You can create contracts with constructors a new, optional parameter of `Operation.createCustomContract`, `constructorArgs: xdr.ScVal[]` ([#770](https://github.com/stellar/js-stellar-base/pull/770)). + + +## [`v12.1.1`](https://github.com/stellar/js-stellar-base/compare/v12.1.0...v12.1.1) + +### Fixed +* Add missing methods to TypeScript definitions ([#766](https://github.com/stellar/js-stellar-base/pull/766)). +* Fix the TypeScript definition of `walkInvocationTree` to allow void returns on the callback function as intended rather than forcing a `return null` ([#765](https://github.com/stellar/js-stellar-base/pull/765)). +* Fix `authorizeEntry` to use the correct public key when passing `Keypair`s ([#772](https://github.com/stellar/js-stellar-base/pull/772)). +* Upgrade misc. dependencies ([#771](https://github.com/stellar/js-stellar-base/pull/771), [#773](https://github.com/stellar/js-stellar-base/pull/773)). + + +## [`v12.1.0`](https://github.com/stellar/js-stellar-base/compare/v12.0.1...v12.1.0) + +### Added +* `TransactionBuilder` now has `addOperationAt` and `clearOperationAt` methods to allow manipulation of individual operations ([#757](https://github.com/stellar/js-stellar-base/pull/757)). + +### Fixed +* Improve the efficiency and portability of asset type retrieval ([#758](https://github.com/stellar/js-stellar-base/pull/758)). +* `nativeToScVal` now correctly sorts maps lexicographically based on the keys to match what the Soroban environment expects ([#759](https://github.com/stellar/js-stellar-base/pull/759)). +* `nativeToScVal` now allows all integer types to come from strings ([#763](https://github.com/stellar/js-stellar-base/pull/763)). +* `humanizeEvents` now handles events without a `contractId` set more reliably ([#764](https://github.com/stellar/js-stellar-base/pull/764)). + + +## [`v12.0.1`](https://github.com/stellar/js-stellar-base/compare/v12.0.0...v12.0.1) + +### Fixed +* Export TypeScript definition for `StrKey.isValidContract` ([#751](https://github.com/stellar/js-stellar-base/pull/751)). +* `scValToNative` would fail when the values contained error codes because the parsing routine hadn't been updated to the new error schemas. Errors are now converted to the following format ([#753](https://github.com/stellar/js-stellar-base/pull/753)): + +```typescript +interface Error { + type: "contract" | "system"; + code: number; + value?: string; // only present for type === 'system' +} +``` + +You can refer to the [XDR documentation](https://github.com/stellar/stellar-xdr/blob/70180d5e8d9caee9e8645ed8a38c36a8cf403cd9/Stellar-contract.x#L76-L115) for additional explanations for each error code. + + +## [`v12.0.0`](https://github.com/stellar/js-stellar-base/compare/v11.0.1...v12.0.0) + +This is a re-tag of v12.0.0-rc.1 with only developer dependency updates in-between. + + +## [`v12.0.0-rc.1`](https://github.com/stellar/js-stellar-base/compare/v11.0.1...v12.0.0-rc.1) + +### Breaking Changes +* The generated XDR has been upgraded to match the upcoming Protocol 21, namely [stellar/stellar-xdr@`1a04392`](https://github.com/stellar/stellar-xdr/commit/1a04392432dacc0092caaeae22a600ea1af3c6a5) ([#738](https://github.com/stellar/js-stellar-base/pull/738)). + +### Added +* To facilitate serialization and deserialization for downstream systems, this package now exports `cereal.XdrWriter` and `cereal.XdrReader` which come directly from `@stellar/js-xdr` ([#744](https://github.com/stellar/js-stellar-base/pull/744)). + +### Fixed +* Updated various dependencies ([#737](https://github.com/stellar/js-stellar-base/pull/737), [#739](https://github.com/stellar/js-stellar-base/pull/739)). +* `Buffer` and `Uint8Array` compatibility has improved in `StrKey` ([#746](https://github.com/stellar/js-stellar-base/pull/746)). + + +## [`v11.0.1`](https://github.com/stellar/js-stellar-base/compare/v11.0.0...v11.0.1) + +### Fixed +* Add compatibility with pre-ES2016 environments (like some React Native JS compilers) by adding a custom `Buffer.subarray` polyfill ([#733](https://github.com/stellar/js-stellar-base/pull/733)). +* Upgrade underlying dependencies, including `@stellar/js-xdr` which should broaden compatibility to pre-ES2016 environments ([#734](https://github.com/stellar/js-stellar-base/pull/734), [#735](https://github.com/stellar/js-stellar-base/pull/735)). + + +## [`v11.0.0`](https://github.com/stellar/js-stellar-base/compare/v10.0.2...v11.0.0) + +**Note:** This version is (still) compatible with Protocol 20. Most people should be unaffected by the technically-breaking changes below and can treat this more like a v10.0.3 patch release. + +### Breaking Changes +* Starting from **v10.0.0-beta.0**, we set [`BigNumber.DEBUG`](https://mikemcl.github.io/bignumber.js/#debug) in `bignumber.js` to `true` internally, which affects all code using `BigNumber`. This behavior has been fixed and only affects this library: globally, `BigNumber.DEBUG` now remains at its default setting (i.e. disabled). This is technically a breaking behavior change and is released as such ([#729](https://github.com/stellar/js-stellar-base/pull/729)). + +### Fixed +* Dependencies have been updated to their latest compatible versions ([#726](https://github.com/stellar/js-stellar-base/pull/729), [#730](https://github.com/stellar/js-stellar-base/pull/730)). + + +## [`v10.0.2`](https://github.com/stellar/js-stellar-base/compare/v10.0.1...v10.0.2) + +### Fixed +* The `contractId` field is correctly omitted from humanized events when it wasn't present in the structure ([#721](https://github.com/stellar/js-stellar-base/pull/721)). +* Misc. outdated or incorrect documentation has been updated ([#723](https://github.com/stellar/js-stellar-base/pull/723), [#720](https://github.com/stellar/js-stellar-base/pull/720)). +* Dependencies have been updated ([#724](https://github.com/stellar/js-stellar-base/pull/724)). + + +## [`v10.0.1`](https://github.com/stellar/js-stellar-base/compare/v10.0.0...v10.0.1) + +### Fixed +* The TypeScript definition for `Asset.contractId()` now includes a missing parameter (the `networkPassphrase` changes the ID for a contract; [#718](https://github.com/stellar/js-stellar-base/pull/#718)). + + +## [`v10.0.0`](https://github.com/stellar/js-stellar-base/compare/v9.0.0...v10.0.0): Protocol 20 Stable Release + +### Breaking Changes +* The new minimum supported Node version is Node 18. +* XDR has been upgraded to the latest stable version ([stellar-xdr@`6a620d1`](https://github.com/stellar/stellar-xdr/tree/6a620d160aab22609c982d54578ff6a63bfcdc01)). This is mostly renames, but it includes the following relevant breaking changes ([#704](https://github.com/stellar/js-stellar-base/pull/704)): + - `Operation.bumpFootprintExpiration` is now `extendFootprintTtl` and its `ledgersToExpire` field is now named `extendTo`, but it serves the same purpose. + - In TypeScript, the `Operation.BumpFootprintExpiration` is now `Operation.ExtendFootprintTTL` + - `xdr.ContractExecutable.contractExecutableToken` is now `contractExecutableStellarAsset` + - `xdr.SorobanTransactionData.refundableFee` is now `resourceFee` + - In turn, `SorobanDataBuilder.setRefundableFee` is now `setResourceFee` + - This new fee encompasses the entirety of the Soroban-related resource fees. Note that this is distinct from the "network-inclusion" fee that you would set on your transaction (i.e. `TransactionBuilder(..., { fee: ... })`). +- `Contract.getFootprint()` now only returns a single result: the ledger key of the deployed instance for the given ID, because the key for the code entry was incorrect (it should not be the ID but rather the WASM hash, which is not calculatable w/o network access) ([#709](https://github.com/stellar/js-stellar-base/pull/709)). + + +## [`v10.0.0-beta.4`](https://github.com/stellar/js-stellar-base/compare/v10.0.0-beta.3...v10.0.0-beta.4) + +### Fixed +- You can now correctly clone transactions (`TransactionBuilder.cloneFrom`) with large sequence numbers ([#711](https://github.com/stellar/js-stellar-base/pull/711)). + + +## [`v10.0.0-beta.3`](https://github.com/stellar/js-stellar-base/compare/v10.0.0-beta.2...v10.0.0-beta.3) + +### Fixed +* Fixes a bug where `authorizeEntry` might perform a no-op when it shouldn't ([#701](https://github.com/stellar/js-stellar-base/pull/701)). +* Fixes a TypeScript bug where `Memo.hash` did not accept a `Buffer` ([#698](https://github.com/stellar/js-stellar-base/pull/698)). +* Upgrades a transient dependency for security ([#296](https://github.com/stellar/js-stellar-base/pull/696)). + + +## [`v10.0.0-beta.2`](https://github.com/stellar/js-stellar-base/compare/v10.0.0-beta.1...v10.0.0-beta.2) + +### Breaking Changes + * The wrappers around multi-party authorization have changed ([#678](https://github.com/stellar/js-stellar-base/pull/678)): + - `authorizeEntry` has been added to help sign auth entries in-place + - the signature for `authorizeInvocation` has changed: it now offers a callback approach by default and requires slightly different parameters + - `buildAuthEntry`, `buildAuthEnvelope`, and `authorizeInvocationCallback` have been removed + +### Fixed + * The TypeScript definitions for XDR schemas now point to the current protocol rather than vNext ([#694](https://github.com/stellar/js-stellar-base/pull/694)). + * Misc. dependencies have been updated to their latest versions ([#694](https://github.com/stellar/js-stellar-base/pull/694)). + + +## [`v10.0.0-beta.1`](https://github.com/stellar/js-stellar-base/compare/v10.0.0-beta.0...v10.0.0-beta.1) + +### Fixed + * `nativeToScVal` now allows anything to be passed to the `opts.type` specifier. Previously, it was only integer types ([#691](https://github.com/stellar/js-stellar-base/pull/691)). + * `Contract.call()` now produces valid `Operation` XDR ([#692](https://github.com/stellar/js-stellar-base/pull/692)). + + +## [`v10.0.0-beta.0`](https://github.com/stellar/js-stellar-base/compare/v9.0.0...v10.0.0-beta.0): Protocol 20 + +### Breaking Changes + * **Node 16 is the new minimum version** to use the SDKs. + * The XDR has been massively overhauled to support [Soroban in Protocol 20](https://soroban.stellar.org/docs/category/fundamentals-and-concepts), which means new operations, data structures, and a transaction format as well as new overlay features ([#538](https://github.com/stellar/js-stellar-base/pull/538)). + +The core data structure of Soroban is a generic type called an `ScVal` (**s**mart **c**ontract **val**ue, which is a union of types that can basically represent anything [numbers, strings, arrays, maps, contract bytecode, etc.]). You can refer to the XDR for details, and you can utilize new APIs to make dealing with these complex values easier: + - `nativeToScVal` helps convert native types to their closest Soroban equivalent + - `scValToNative` helps find the closest native JavaScript type(s) corresponding to a smart contract value + - `scValToBigInt` helps convert numeric `ScVal`s into native `bigint`s + - `ScInt` and `XdrLargeInt` help convert to and from `bigint`s to other types and form sized integer types for smart contract usage + +### Added +The following are new APIs to deal with new Soroban constructs: + - **`Address`, which helps manage "smart" addresses in the Soroban context.** Addresses there (used for auth and identity purposes) can either be contracts (strkey `C...`) or accounts (strkey `G...`). This abstraction helps manage them and distinguish between them easily. + - **`Contract`, which helps manage contract identifiers.** The primary purpose is to build invocations of its methods via the generic `call(...)`, but it also provides utilities for converting to an `Address` or calculating its minimum footprint for state expiration. + - **Three new operations** have been added related to Soroban transactions: + * `invokeHostFunction` for calling contract code + * `bumpFootprintExpiration` for extending the state lifetime of Soroban data + * `restoreFootprint` for restoring expired, off-chain state back onto the ledger + - The `TransactionBuilder` now takes a `sorobanData` parameter (and has a corresponding `.setSorobanData()` builder method) which primarily describes the storage footprint of a Soroban (that is, which parts of the ledger state [in the form of `xdr.LedgerKey`s] it plans to read and write as part of the transaction). + * To facilitate building this out, there's a new `SorobanDataBuilder` factory to set fields individually + - The `TransactionBuilder` now has a `cloneFrom(tx, opts)` constructor method to create an instance from an existing transaction, also allowing parameter overrides via `opts`. + - The following are convenience methods for building out certain types of smart contract-related structures: + * `buildInvocationTree` and `walkInvocationTree` are both ways to visualize invocation calling trees better + * `authorizeInvocation` helps multiple parties sign invocation calling trees + * `humanizeEvents` helps make diagnostic events more readable + - We've added a GHA to track bundle size changes as PRs are made. This protocol upgrade adds +18% to the final, minified bundle size which is significant but acceptable given the size of the upgrade. + +### Fixes +* Improves the error messages when passing invalid amounts to deposit and withdraw operations ([#679](https://github.com/stellar/js-stellar-base/pull/679)). + + +## [v9.0.0](https://github.com/stellar/js-stellar-base/compare/v8.2.2..v9.0.0) + +This is a large update and the following changelog incorporates ALL changes across the `beta.N` versions of this upgrade. + +This version is marked by a major version bump because of the significant upgrades to underlying dependencies. While there should be no noticeable API changes from a downstream perspective, there may be breaking changes in the way that this library is bundled. + +The browser bundle size has decreased **significantly**: + + * `stellar-base.min.js` is **340 KiB**, down from **1.2 MiB** previously. + * the new, unminified `stellar-base.js` is **895 KiB**. + +### Breaking Changes + +- The build system has been completely overhauled to support Webpack 5 ([#584](https://github.com/stellar/js-stellar-base/pull/584), [#585](https://github.com/stellar/js-stellar-base/pull/585)). + +Though we have tried to maintain compatibility with older JavaScript implementations, this still means you may need to update your build pipeline to transpile to certain targets. + +### Fixes + +- Fixes a bug when sorting mixed-case assets for liquidity pools ([#606](https://github.com/stellar/js-stellar-base/pull/606)). +- Documentation is fixed and should generate correctly on https://stellar.github.io/js-stellar-base/ ([#609](https://github.com/stellar/js-stellar-base/pull/609)). + +### Updates + +- XDR has been updated to its latest version (both `curr` and `next` versions, [#587](https://github.com/stellar/js-stellar-base/pull/587)). +- Drop the `lodash` dependency entirely ([#624](https://github.com/stellar/js-stellar-base/issues/624)). +- Drop the `crc` dependency and inline it to lower bundle size ([#621](https://github.com/stellar/js-stellar-base/pull/621)). +- Upgrade all dependencies to their latest versions ([#608](https://github.com/stellar/js-stellar-base/pull/608)). + + +## [v9.0.0-beta.3](https://github.com/stellar/js-stellar-base/compare/v9.0.0-beta.1..v9.0.0-beta.2) + +### Fix + +- Fixes a bug when sorting mixed-case assets for liquidity pools ([#606](https://github.com/stellar/js-stellar-base/pull/606)). + +### Update +- Upgrade all dependencies to their latest versions ([#608](https://github.com/stellar/js-stellar-base/pull/608)). +- Drop the `crc` dependency and inline it to lower bundle size ([#621](https://github.com/stellar/js-stellar-base/pull/621)). + + +## [v9.0.0-beta.2](https://github.com/stellar/js-stellar-base/compare/v9.0.0-beta.1..v9.0.0-beta.2) + +### Update + +- Upgrades the `js-xdr` dependency (major performance improvements, see [`js-xdr@v2.0.0`](https://github.com/stellar/js-xdr/releases/tag/v2.0.0)) and other dependencies to their latest versions ([#592](https://github.com/stellar/js-stellar-base/pull/592)). + + +## [v9.0.0-beta.1](https://github.com/stellar/js-stellar-base/compare/v9.0.0-beta.0..v9.0.0-beta.1) + +### Fix + +- Correct XDR type definition for raw `xdr.Operation`s ([#591](https://github.com/stellar/js-stellar-base/pull/591)). + + +## [v9.0.0-beta.0](https://github.com/stellar/js-stellar-base/compare/v8.2.2..v9.0.0-beta.0) + +This version is marked by a major version bump because of the significant upgrades to underlying dependencies. While there should be no noticeable API changes from a downstream perspective, there may be breaking changes in the way that this library is bundled. + +### Fix + +- Build system has been overhauled to support Webpack 5 ([#585](https://github.com/stellar/js-stellar-base/pull/585)). + +- Current and vNext XDR updated to latest versions ([#587](https://github.com/stellar/js-stellar-base/pull/587)). + + +## [v8.2.2](https://github.com/stellar/js-stellar-base/compare/v8.2.1..v8.2.2) + +### Fix + +- Enable signing in service workers using FastSigning ([#567](https://github.com/stellar/js-stellar-base/pull/567)). + +## [v8.2.1](https://github.com/stellar/js-stellar-base/compare/v8.2.0..v8.2.1) + +### Fix + +* Turn all XLM-like (i.e. casing agnostic) asset codes into the native asset with code `XLM` ([#546](https://github.com/stellar/js-stellar-base/pull/546)). + + +## [v8.2.0](https://github.com/stellar/js-stellar-base/compare/v8.1.0..v8.2.0) + +### Add + +* `Operation.setOptions` now supports the new [CAP-40](https://stellar.org/protocol/cap-40) signed payload signer (`ed25519SignedPayload`) thanks to @orbitlens ([#542](https://github.com/stellar/js-stellar-base/pull/542)). + + +## [v8.1.0](https://github.com/stellar/js-stellar-base/compare/v8.0.1..v8.1.0) + +### Add + +* `TransactionBase.addDecoratedSignature` is a clearer way to add signatures directly to a built transaction without fiddling with the underlying `signatures` array ([#535](https://github.com/stellar/js-stellar-base/pull/535)). + +* Update the XDR definitions (and the way in which they're generated) to contain both the latest current XDR (which introduces [CAP-42](https://stellar.org/protocol/cap-42)) and the "v-next" XDR (which contains XDR related to Soroban and should be considered unstable) ([#537](https://github.com/stellar/js-stellar-base/pull/537)). + +### Fix + +* Correctly set `minAccountSequence` in `TransactionBuilder` for large values ([#539](https://github.com/stellar/js-stellar-base/pull/539), thank you @overcat!). + + +## [v8.0.1](https://github.com/stellar/js-stellar-base/compare/v8.0.0..v8.0.1) + +### Fix + +- Correctly predict claimable balance IDs with large sequence numbers ([#530](https://github.com/stellar/js-stellar-base/pull/530), thank you @overcat!). + + +## [v8.0.0](https://github.com/stellar/js-stellar-base/compare/v7.0.0..v8.0.0) + +This is a promotion from the beta version without changes, now that the CAP-21 and CAP-40 implementations have made it into [stellar/stellar-core#master](https://github.com/stellar/stellar-core/tree/master/). + + +## [v8.0.0-beta.0](https://github.com/stellar/js-stellar-base/compare/v7.0.0..v8.0.0-beta.0) + +**This release adds support for Protocol 19**, which includes [CAP-21](https://stellar.org/protocol/cap-21) (new transaction preconditions) and [CAP-40](https://stellar.org/protocol/cap-40) (signed payload signers). + +This is considered a beta release until the XDR for the Stellar protocol stabilizes and is officially released. + +### Breaking + +As of this release, the minimum supported version of NodeJS is **14.x**. + +- Two XDR types have been renamed: + * `xdr.OperationId` is now `xdr.HashIdPreimage` + * `xdr.OperationIdId` is now `xdr.HashIdPreimageOperationId` + +### Add + +- Support for converting signed payloads ([CAP-40](https://stellar.org/protocol/cap-40)) to and from their StrKey (`P...`) representation ([#511](https://github.com/stellar/js-stellar-base/pull/511)): + * `Keypair.signPayloadDecorated(data)` + * `StrKey.encodeSignedPayload(buf)` + * `StrKey.decodeSignedPayload(str)` + * `StrKey.isValidSignedPayload(str)` + +- Support for creating transactions with the new preconditions ([CAP-21](https://stellar.org/protocol/cap-21)) via `TransactionBuilder` ([#513](https://github.com/stellar/js-stellar-base/pull/513)). + +- A way to convert between addresses (like `G...` and `P...`, i.e. the `StrKey` class) and their respective signer keys (i.e. `xdr.SignerKey`s), particularly for use in the new transaction preconditions ([#520](https://github.com/stellar/js-stellar-base/pull/520)): + * `SignerKey.decodeAddress(address)` + * `SignerKey.encodeSignerKey(address)` + * `TransactionBuilder.setTimebounds(min, max)` + * `TransactionBuilder.setLedgerbounds(min, max)` + * `TransactionBuilder.setMinAccountSequence(seq)` + * `TransactionBuilder.setMinAccountSequenceAge(age)` + * `TransactionBuilder.setMinAccountSequenceLedgerGap(gap)` + * `TransactionBuilder.setExtraSigners([signers])` + +### Fix + +- Correct a TypeScript definition on the `RevokeLiquidityPoolSponsorship` operation ([#522](https://github.com/stellar/js-stellar-base/pull/522)). + +- Resolves a bug that incorrectly sorted `Asset`s with mixed-case asset codes (it preferred lowercase codes incorrectly) ([#516](https://github.com/stellar/js-stellar-base/pull/516)). + +- Update developer dependencies: + * `isparta`, `jsdoc`, and `underscore` ([#500](https://github.com/stellar/js-stellar-base/pull/500)) + * `ajv` ([#503](https://github.com/stellar/js-stellar-base/pull/503)) + * `karma` ([#505](https://github.com/stellar/js-stellar-base/pull/505)) + * `minimist` ([#514](https://github.com/stellar/js-stellar-base/pull/514)) + + +## [v7.0.0](https://github.com/stellar/js-stellar-base/compare/v6.0.6..v7.0.0) + +This release introduces **unconditional support for muxed accounts** ([#485](https://github.com/stellar/js-stellar-base/pull/485)). + +### Breaking Changes + +In [v5.2.0](https://github.com/stellar/js-stellar-base/releases/tag/v5.2.0), we introduced _opt-in_ support for muxed accounts, where you would need to explicitly pass a `true` flag if you wanted to interpret muxed account objects as muxed addresses (in the form `M...`, see [SEP-23](https://stellar.org/protocol/sep-23)). We stated that this would become the default in the future. That is now the case. + +The following fields will now always support muxed properties: + + * `FeeBumpTransaction.feeSource` + * `Transaction.sourceAccount` + * `Operation.sourceAccount` + * `Payment.destination` + * `PathPaymentStrictReceive.destination` + * `PathPaymentStrictSend.destination` + * `AccountMerge.destination` + * `Clawback.from` + +The following functions had a `withMuxing` parameter removed: + + - `Operation.fromXDRObject` + - `Transaction.constructor` + - `FeeBumpTransaction.constructor` + - `TransactionBuilder.fromXDR` + - `TransactionBuilder.buildFeeBumpTransaction` + +The following functions will no longer check the `opts` object for a `withMuxing` field: + + - `TransactionBuilder.constructor` + - `Operation.setSourceAccount` + +There are several other breaking changes: + + - `TransactionBuilder.enableMuxedAccounts()` is removed + - `decodeAddressToMuxedAccount()` and `encodeMuxedAccountToAddress()` no longer accept a second boolean parameter + - `Account.createSubaccount()` and `MuxedAccount.createSubaccount()` are removed ([#487](https://github.com/stellar/js-stellar-base/pull/487)). You should prefer to create them manually: + +```js + let mux1 = new MuxedAccount(someAccount, '1'); + + // before: + let mux2 = mux1.createSubaccount('2'); + + // now: + let mux2 = new MuxedAccount(mux1.baseAccount(), '2'); +``` + + + - Introduced a new helper method to help convert from muxed account addresses to their underlying Stellar addresses ([#485](https://github.com/stellar/js-stellar-base/pull/485)): + +```ts +function extractBaseAddess(address: string): string; +``` + + - The following muxed account validation functions are now available from Typescript ([#483](https://github.com/stellar/js-stellar-base/pull/483/files)): + +```typescript +namespace StrKey { + function encodeMed25519PublicKey(data: Buffer): string; + function decodeMed25519PublicKey(data: string): Buffer; + function isValidMed25519PublicKey(publicKey: string): boolean; +} + +function decodeAddressToMuxedAccount(address: string, supportMuxing: boolean): xdr.MuxedAccount; +function encodeMuxedAccountToAddress(account: xdr.MuxedAccount, supportMuxing: boolean): string; +function encodeMuxedAccount(gAddress: string, id: string): xdr.MuxedAccount; +``` + +- Added a helper function `Transaction.getClaimableBalanceId(int)` which lets you pre-determine the hex claimable balance ID of a `createClaimableBalance` operation prior to submission to the network ([#482](https://github.com/stellar/js-stellar-base/pull/482)). + +### Fix + +- Add `Buffer` as a parameter type option for the `Keypair` constructor in Typescript ([#484](https://github.com/stellar/js-stellar-base/pull/484)). + + +## [v6.0.6](https://github.com/stellar/js-stellar-base/compare/v6.0.5..v6.0.6) + +### Fix + +- Upgrades dependencies: `path-parse` (1.0.6 --> 1.0.7) and `jszip` (3.4.0 to 3.7.1) ([#450](https://github.com/stellar/js-stellar-base/pull/450), [#458](https://github.com/stellar/js-stellar-base/pull/458)). + + +## [v6.0.5](https://github.com/stellar/js-stellar-base/compare/v6.0.4..v6.0.5) + +This version bump fixes a security vulnerability in a _developer_ dependency; **please upgrade as soon as possible!** You may be affected if you are working on this package in a developer capacity (i.e. you've cloned this repository) and have run `yarn` or `yarn install` any time on Oct 22nd, 2021. + +Please refer to the [security advisory](https://github.com/advisories/GHSA-pjwm-rvh2-c87w) for details. + + +### Security Fix +- Pin `ua-parser-js` to a known safe version ([#477](https://github.com/stellar/js-stellar-base/pull/477)). + + +## [v6.0.4](https://github.com/stellar/js-stellar-base/compare/v6.0.3..v6.0.4) + +### Fix +- Allow muxed accounts when decoding transactions via `TransactionBuilder.fromXDR()` ([#470](https://github.com/stellar/js-stellar-base/pull/470)). + + +## [v6.0.3](https://github.com/stellar/js-stellar-base/compare/v6.0.2..v6.0.3) + +### Fix +- When creating a `Transaction`, forward the optional `withMuxing` flag along to its operations so that their properties are also decoded with the appropriate muxing state ([#469](https://github.com/stellar/js-stellar-base/pull/469)). + + +## [v6.0.2](https://github.com/stellar/js-stellar-base/compare/v6.0.1..v6.0.2) + +### Fix +- Fix Typescript signatures for operations to universally allow setting the `withMuxing` flag ([#466](https://github.com/stellar/js-stellar-base/pull/466)). + + +## [v6.0.1](https://github.com/stellar/js-stellar-base/compare/v5.3.2..v6.0.1) + +### Add + +- Introduced new CAP-38 operations `LiquidityPoolDepositOp` and `LiquidityPoolWithdrawOp`. +- Introduced two new types of assets, `LiquidityPoolId` and `LiquidityPoolAsset`. + +### Update + +- The XDR definitions have been updated to support CAP-38. +- Extended `Operation` class with the `Operation.revokeLiquidityPoolSponsorship` helper that allows revoking a liquidity pool sponsorship. +- Asset types now include `AssetType.liquidityPoolShares`. +- `Operation.changeTrust` and `ChangeTrustOp` can now use `LiquidityPoolAsset` in addition to `Asset`. +- `Operation.revokeTrustlineSponsorship` can now use `LiquidityPoolId` in addition to `Asset`. + +## [v5.3.2](https://github.com/stellar/js-stellar-base/compare/v5.3.1..v5.3.2) + +### Fix +- Update various dependencies to secure versions. Most are developer dependencies which means no or minimal downstream effects ([#446](https://github.com/stellar/js-stellar-base/pull/446), [#447](https://github.com/stellar/js-stellar-base/pull/447), [#392](https://github.com/stellar/js-stellar-base/pull/392), [#428](https://github.com/stellar/js-stellar-base/pull/428)); the only non-developer dependency upgrade is a patch version bump to `lodash` ([#449](https://github.com/stellar/js-stellar-base/pull/449)). + + +## [v5.3.1](https://github.com/stellar/js-stellar-base/compare/v5.3.0..v5.3.1) + +### Fix +- Creating operations with both muxed and unmuxed properties resulted in unintuitive XDR. Specifically, the unmuxed property would be transformed into the equivalent property with an ID of 0 ([#441](https://github.com/stellar/js-stellar-base/pull/441)). + + +## [v5.3.0](https://github.com/stellar/js-stellar-base/compare/v5.2.1..v5.3.0) + +### Add +- **Opt-in support for muxed accounts.** In addition to the support introduced in [v5.2.0](https://github.com/stellar/js-stellar-base/releases/v5.2.0), this completes support for muxed accounts by enabling them for fee-bump transactions. Pass a muxed account address (in the `M...` form) as the first parameter (and explicitly opt-in to muxing by passing `true` as the last parameter) to `TransactionBuilder.buildFeeBumpTransaction` to make the `feeSource` a fully-muxed account instance ([#434](https://github.com/stellar/js-stellar-base/pull/434)). + + +## [v5.2.1](https://github.com/stellar/js-stellar-base/compare/v5.2.0..v5.2.1) + +### Fix +- Fix regression where raw public keys were [sometimes](https://github.com/stellar/js-stellar-sdk/issues/645) being parsed incorrectly ([#429](https://github.com/stellar/js-stellar-base/pull/429)). + + +## [v5.2.0](https://github.com/stellar/js-stellar-base/compare/v5.1.0..v5.2.0) + +### Add +- **Opt-in support for muxed accounts.** This introduces `M...` addresses from [SEP-23](https://stellar.org/protocol/sep-23), which multiplex a Stellar `G...` address across IDs to eliminate the need for ad-hoc multiplexing via the Transaction.memo field (see the relevant [SEP-29](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md) and [blog post](https://www.stellar.org/developers-blog/fixing-memo-less-payments) on the topic). The following operations now support muxed accounts ([#416](https://github.com/stellar/js-stellar-base/pull/416)): + * `Payment.destination` + * `PathPaymentStrictReceive.destination` + * `PathPaymentStrictSend.destination` + * `Operation.sourceAccount` + * `AccountMerge.destination` + * `Transaction.sourceAccount` + +- The above changeset also introduces a new high-level object, `MuxedAccount` (not to be confused with `xdr.MuxedAccount`, which is the underlying raw representation) to make working with muxed accounts easier. You can use it to easily create and manage muxed accounts and their underlying shared `Account`, passing them along to the supported operations and `TransactionBuilder` ([#416](https://github.com/stellar/js-stellar-base/pull/416)): + +```js + const PUBKEY = 'GA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJVSGZ'; + const ACC = new StellarBase.Account(PUBKEY, '1'); + + const mux1 = new StellarBase.MuxedAccount(ACC, '1000'); + console.log(mux1.accountId(), mux1.id()); + // MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAD5DTGC 1000 + + const mux2 = ACC.createSubaccount('2000'); + console.log("Parent relationship preserved:", + mux2.baseAccount().accountId() === mux1.baseAccount().accountId()); + console.log(mux2.accountId(), mux2.id()); + // MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAH2B4RU 2000 + + mux1.setID('3000'); + console.log("Underlying account unchanged:", + ACC.accountId() === mux1.baseAccount().accountId()); + console.log(mux1.accountId(), mux1.id()); + // MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAALXC5LE 3000 +``` + +- You can refer to the [documentation](https://stellar.github.io/js-stellar-sdk/MuxedAccount.html) or the [test suite](../test/unit/muxed_account_test.js) for more uses of the API. + +### Update +- Modernize the minimum-supported browser versions for the library ([#419](https://github.com/stellar/js-stellar-base/pull/419)). + +### Fix +- Update Typescript test for `SetOptions` to use authorization flags (e.g. `AuthRequiredFlag`) correctly ([#418](https://github.com/stellar/js-stellar-base/pull/418)). + + +## [v5.1.0](https://github.com/stellar/js-stellar-base/compare/v5.0.0..v5.1.0) + +### Update + +- The Typescript definitions have been updated to support CAP-35 ([#407](https://github.com/stellar/js-stellar-base/pull/407)). + +## [v5.0.0](https://github.com/stellar/js-stellar-base/compare/v4.0.3..v5.0.0) + +### Add + +- Introduced new CAP-35 operations, `ClawbackOp`, `ClawbackClaimableBalanceOp`, and `SetTrustLineFlagsOp` ([#397](https://github.com/stellar/js-stellar-base/pull/397/)). + +### Update + +- Add an additional parameter check to `claimClaimableBalance` to fail faster ([#390](https://github.com/stellar/js-stellar-base/pull/390)). + +- The XDR definitions have been updated to support CAP-35 ([#394](https://github.com/stellar/js-stellar-base/pull/394)). + +### Breaking + +- `AllowTrustOpAsset` has been renamed to `AssetCode` ([#394](https://github.com/stellar/js-stellar-base/pull/394)) + + +### Deprecated + +- `AllowTrustOp` is now a deprecated operation. + +## [v4.0.3](https://github.com/stellar/js-stellar-base/compare/v4.0.2..v4.0.3) + +## Update + +- Update TS definitions for XDRs ([#381](https://github.com/stellar/js-stellar-base/pull/381)) +- Fix typing for ManageData.value ([#379](https://github.com/stellar/js-stellar-base/pull/379)) + + +## [v4.0.2](https://github.com/stellar/js-stellar-base/compare/v4.0.1..v4.0.2) + +## Update + +- Fix deployment script. + + +## [v4.0.1](https://github.com/stellar/js-stellar-base/compare/v4.0.0..v4.0.1) + +## Update + +- Update `createAccount` operation to accept `0` as the starting balance ([#375](https://github.com/stellar/js-stellar-base/pull/375)). + +## [v4.0.0](https://github.com/stellar/js-stellar-base/compare/v3.0.4..v4.0.0) + +## Add +- Add the `Claimant` class which helps the creation of claimable balances. ([#367](https://github.com/stellar/js-stellar-base/pull/367)). +The default behavior of this class it to create claimants with an unconditional predicate if none is passed: + +``` +const claimant = new StellarBase.Claimant( + 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ' +); +``` + +However, you can use any of the following helpers to create a predicate: + +``` +StellarBase.Claimant.predicateUnconditional(); +StellarBase.Claimant.predicateAnd(left, right); +StellarBase.Claimant.predicateOr(left, right); +StellarBase.Claimant.predicateNot(predicate); +StellarBase.Claimant.predicateBeforeAbsoluteTime(unixEpoch); +StellarBase.Claimant.predicateBeforeRelativeTime(seconds); +``` + +And then pass the predicate in the constructor: + +``` +const left = StellarBase.Claimant.predicateBeforeRelativeTime('800'); +const right = StellarBase.Claimant.predicateBeforeRelativeTime( + '1200' +); +const predicate = StellarBase.Claimant.predicateOr(left, right); +const claimant = new StellarBase.Claimant( + 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ', + predicate +); +``` + +- Add `Operation.createClaimableBalance` ([#368](https://github.com/stellar/js-stellar-base/pull/368)) +Extend the operation class with a new helper to create claimable balance operations. + +```js +const asset = new Asset( + 'USD', + 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' +); +const amount = '100.0000000'; +const claimants = [ + new Claimant( + 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ', + Claimant.predicateBeforeAbsoluteTime("4102444800000") + ) +]; + +const op = Operation.createClaimableBalance({ + asset, + amount, + claimants +}); +``` + +- Add `Operation.claimClaimableBalance` ([#368](https://github.com/stellar/js-stellar-base/pull/368)) +Extend the operation class with a new helper to create claim claimable balance operations. It receives the `balanceId` as exposed by Horizon in the `/claimable_balances` end-point. + +```js +const op = Operation.createClaimableBalance({ + balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', +}); +``` +- Add support for Sponsored Reserves (CAP33)([#369](https://github.com/stellar/js-stellar-base/pull/369/)) + +Extend the operation class with helpers that allow sponsoring reserves and also revoke sponsorships. + +To start sponsoring reserves for an account use: +- `Operation.beginSponsoringFutureReserves` +- `Operation.endSponsoringFutureReserves` + +To revoke a sponsorship after it has been created use any of the following helpers: + +- `Operation.revokeAccountSponsorship` +- `Operation.revokeTrustlineSponsorship` +- `Operation.revokeOfferSponsorship` +- `Operation.revokeDataSponsorship` +- `Operation.revokeClaimableBalanceSponsorship` +- `Operation.revokeSignerSponsorship` + +The following example contains a transaction which sponsors operations for an account and then revoke some sponsorships. + +``` +const transaction = new StellarSdk.TransactionBuilder(account, { + fee: "100", + networkPassphrase: StellarSdk.Networks.TESTNET +}) + .addOperation( + StellarSdk.Operation.beginSponsoringFutureReserves({ + sponsoredId: account.accountId(), + source: masterKey.publicKey() + }) + ) + .addOperation( + StellarSdk.Operation.accountMerge({ destination: destKey.publicKey() }), + ).addOperation( + StellarSdk.Operation.createClaimableBalance({ + amount: "10", + asset: StellarSdk.Asset.native(), + claimants: [ + new StellarSdk.Claimant(account.accountId()) + ] + }), + ).addOperation( + StellarSdk.Operation.claimClaimableBalance({ + balanceId: "00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be", + }), + ).addOperation( + StellarSdk.Operation.endSponsoringFutureReserves({ + }) + ).addOperation( + StellarSdk.Operation.revokeAccountSponsorship({ + account: account.accountId(), + }) + ).addOperation( + StellarSdk.Operation.revokeTrustlineSponsorship({ + account: account.accountId(), + asset: usd, + }) + ).addOperation( + StellarSdk.Operation.revokeOfferSponsorship({ + seller: account.accountId(), + offerId: '12345' + }) + ).addOperation( + StellarSdk.Operation.revokeDataSponsorship({ + account: account.accountId(), + name: 'foo' + }) + ).addOperation( + StellarSdk.Operation.revokeClaimableBalanceSponsorship({ + balanceId: "00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be", + }) + ).addOperation( + StellarSdk.Operation.revokeSignerSponsorship({ + account: account.accountId(), + signer: { + ed25519PublicKey: sourceKey.publicKey() + } + }) + ).addOperation( + StellarSdk.Operation.revokeSignerSponsorship({ + account: account.accountId(), + signer: { + sha256Hash: "da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be" + } + }) + ).addOperation( + StellarSdk.Operation.revokeSignerSponsorship({ + account: account.accountId(), + signer: { + preAuthTx: "da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be" + } + }) + ).build(); +``` + +### Breaking + +- The XDR generated in this code includes breaking changes on the internal XDR library since a bug was fixed which was causing incorrect code to be generated (see https://github.com/stellar/xdrgen/pull/52). + +The following functions were renamed: + +- `xdr.OperationBody.setOption()` -> `xdr.OperationBody.setOptions()` +- `xdr.OperationBody.manageDatum()` -> `xdr.OperationBody.manageData()` +- `xdr.OperationType.setOption()` -> `xdr.OperationType.setOptions()` +- `xdr.OperationType.manageDatum()` -> `xdr.OperationType.manageData()` + +The following enum values were rename in `OperationType`: + +- `setOption` -> `setOptions` +- `manageDatum` -> `manageData` + +## [v3.0.4](https://github.com/stellar/js-stellar-base/compare/v3.0.3..v3.0.4) + +### Update + +- Generate V1 transactions by default and allow V0 transactions to be fee bumped ([#355](https://github.com/stellar/js-stellar-base/pull/355)). + +## [v3.0.3](https://github.com/stellar/js-stellar-base/compare/v3.0.2..v3.0.3) + +### Remove + +- Rollback support for SEP23 (Muxed Account StrKey) ([#349](https://github.com/stellar/js-stellar-base/pull/349)). + +## [v3.0.2](https://github.com/stellar/js-stellar-base/compare/v3.0.1..v3.0.2) + +### Fix +- Extend `files` in npm package to include XDR type definitions ([#345](https://github.com/stellar/js-stellar-base/pull/345)). + +## [v3.0.1](https://github.com/stellar/js-stellar-base/compare/v3.0.0..v3.0.1) + +### Add +- Add TypeScript definitions for auto-generated XDR code ([#342](https://github.com/stellar/js-stellar-base/pull/342)). + +## [v3.0.0](https://github.com/stellar/js-stellar-base/compare/v2.1.9..v3.0.0) + +This version brings protocol 13 support with backwards compatibility support for protocol 12. + +### Add +- Add `TransactionBuilder.buildFeeBumpTransaction` which makes it easy to create `FeeBumpTransaction` ([#321](https://github.com/stellar/js-stellar-base/pull/321)). +- Adds a feature flag which allow consumers of this library to create V1 (protocol 13) transactions using the `TransactionBuilder` ([#321](https://github.com/stellar/js-stellar-base/pull/321)). +- Add support for [CAP0027](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0027.md): First-class multiplexed accounts ([#325](https://github.com/stellar/js-stellar-base/pull/325)). +- ~Add `Keypair.xdrMuxedAccount` which creates a new `xdr.MuxedAccount`([#325](https://github.com/stellar/js-stellar-base/pull/325)).~ +- Add `FeeBumpTransaction` which makes it easy to work with fee bump transactions ([#328](https://github.com/stellar/js-stellar-base/pull/328)). +- Add `TransactionBuilder.fromXDR` which receives an xdr envelope and return a `Transaction` or `FeeBumpTransaction` ([#328](https://github.com/stellar/js-stellar-base/pull/328)). + +### Update +- Update XDR definitions with protocol 13 ([#317](https://github.com/stellar/js-stellar-base/pull/317)). +- Extend `Transaction` to work with `TransactionV1Envelope` and `TransactionV0Envelope` ([#317](https://github.com/stellar/js-stellar-base/pull/317)). +- Add backward compatibility support for [CAP0018](https://github.com/stellar/stellar-protocol/blob/f01c9354aaab1e8ca97a25cf888829749cadf36a/core/cap-0018.md) ([#317](https://github.com/stellar/js-stellar-base/pull/317)). + CAP0018 provides issuers with a new level of authorization between unauthorized and fully authorized, called "authorized to maintain liabilities". The changes in this release allow you to use the new authorization level and provides backward compatible support for Protocol 12. + + Before Protocol 13, the argument `authorize` in the `AllowTrust` operation was of type `boolean` where `true` was authorize and `false` deauthorize. Starting in Protocol 13, this value is now a `number` where `0` is deauthorize, `1` is authorize, and `2` is authorize to maintain liabilities. + + The syntax for authorizing a trustline is still the same, but the authorize parameter is now a `number`. + + ```js + Operation.allowTrust({ + trustor: trustor.publicKey(), + assetCode: "COP", + authorize: 1 + }); + ``` + + You can use still use a `boolean`; however, we recommend you update your code to pass a `number` instead. Finally, using the value `2` for authorize to maintain liabilities will only be valid if Stellar Core is running on Protocol 13; otherwise, you'll get an error. + +- ~Update operations builder to support multiplexed accounts ([#337](https://github.com/stellar/js-stellar-base/pull/337)).~ + +### Breaking changes + +- `Transaction.toEnvelope()` returns a protocol 13 `xdr.TransactionEnvelope` which is an `xdr.Union` ([#317](https://github.com/stellar/js-stellar-base/pull/317)). + If you have code that looks like this - `transaction.toEnvelope().tx` - you have two options: + - You can grab the value wrapped by the union, calling `value()` like `transaction.toEnvelope().value().tx`. + - You can check which is the discriminant by using `switch()` and then call `v0()`, `v1()`, or `feeBump()`. +- The return value from `Transaction.fee` changed from `number` to `string`. This brings support for `Int64` values ([#321](https://github.com/stellar/js-stellar-base/pull/321)). +- The const `BASE_FEE` changed from `number` to `string` ([#321](https://github.com/stellar/js-stellar-base/pull/321)). +- The option `fee` passed to `new TransactionBuilder({fee: ..})` changed from `number` to `string` ([#321](https://github.com/stellar/js-stellar-base/pull/321)). +- The following fields, which were previously an `xdr.AccountID` are now a `xdr.MuxedAccount` ([#325](https://github.com/stellar/js-stellar-base/pull/325)): + - `PaymentOp.destination` + - `PathPaymentStrictReceiveOp.destination` + - `PathPaymentStrictSendOp.destination` + - `Operation.sourceAccount` + - `Operation.destination` (for `ACCOUNT_MERGE`) + - `Transaction.sourceAccount` + - `FeeBumpTransaction.feeSource` + + You can get the string representation by calling `StrKey.encodeMuxedAccount` which will return a `G..` or `M..` account. +- Remove the following deprecated functions ([#331](https://github.com/stellar/js-stellar-base/pull/331)): + - `Operation.manageOffer` + - `Operation.createPassiveOffer` + - `Operation.pathPayment` + - `Keypair.fromBase58Seed` +- Remove the `Network` class ([#331](https://github.com/stellar/js-stellar-base/pull/331)). +- Remove `vendor/base58.js` ([#331](https://github.com/stellar/js-stellar-base/pull/331)). + +## [v3.0.0-alpha.1](https://github.com/stellar/js-stellar-base/compare/v3.0.0-alpha.0..v3.0.0-alpha.1) + +### Update + +- Update operations builder to support multiplexed accounts ([#337](https://github.com/stellar/js-stellar-base/pull/337)). + + This allows you to specify an `M` account as the destination or source: + ``` + var destination = 'MAAAAAAAAAAAAAB7BQ2L7E5NBWMXDUCMZSIPOBKRDSBYVLMXGSSKF6YNPIB7Y77ITLVL6'; + var amount = '1000.0000000'; + var asset = new StellarBase.Asset( + 'USDUSD', + 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + ); + var source = + 'MAAAAAAAAAAAAAB7BQ2L7E5NBWMXDUCMZSIPOBKRDSBYVLMXGSSKF6YNPIB7Y77ITLVL6'; + StellarBase.Operation.payment({ + destination, + asset, + amount, + source + }); + ``` + + **To use multiplexed accounts you need an instance of Stellar running on Protocol 13 or higher** + +## [v3.0.0-alpha.0](https://github.com/stellar/js-stellar-base/compare/v2.1.9..v3.0.0-alpha.0) + +This version brings protocol 13 support with backwards compatibility support for protocol 12. + +### Add +- Add `TransactionBuilder.buildFeeBumpTransaction` which makes it easy to create `FeeBumpTransaction` ([#321](https://github.com/stellar/js-stellar-base/pull/321)). +- Adds a feature flag which allow consumers of this library to create V1 (protocol 13) transactions using the `TransactionBuilder` ([#321](https://github.com/stellar/js-stellar-base/pull/321)). +- Add support for [CAP0027](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0027.md): First-class multiplexed accounts ([#325](https://github.com/stellar/js-stellar-base/pull/325)). +- Add `Keypair.xdrMuxedAccount` which creates a new `xdr.MuxedAccount`([#325](https://github.com/stellar/js-stellar-base/pull/325)). +- Add `FeeBumpTransaction` which makes it easy to work with fee bump transactions ([#328](https://github.com/stellar/js-stellar-base/pull/328)). +- Add `TransactionBuilder.fromXDR` which receives an xdr envelope and return a `Transaction` or `FeeBumpTransaction` ([#328](https://github.com/stellar/js-stellar-base/pull/328)). + +### Update +- Update XDR definitions with protocol 13 ([#317](https://github.com/stellar/js-stellar-base/pull/317)). +- Extend `Transaction` to work with `TransactionV1Envelope` and `TransactionV0Envelope` ([#317](https://github.com/stellar/js-stellar-base/pull/317)). +- Add backward compatibility support for [CAP0018](https://github.com/stellar/stellar-protocol/blob/f01c9354aaab1e8ca97a25cf888829749cadf36a/core/cap-0018.md) ([#317](https://github.com/stellar/js-stellar-base/pull/317)). + +### Breaking changes + +- `Transaction.toEnvelope()` returns a protocol 13 `xdr.TransactionEnvelope` which is an `xdr.Union` ([#317](https://github.com/stellar/js-stellar-base/pull/317)). + If you have code that looks like this `transaction.toEnvelope().tx` you have two options: + - You can grab the value wrapped by the union, calling `value()` like `transaction.toEnvelope().value().tx`. + - You can check which is the discriminant by using `switch()` and then call `v0()`, `v1()`, or `feeBump()`. +- The return value from `Transaction.fee` changed from `number` to `string`. This brings support for `Int64` values ([#321](https://github.com/stellar/js-stellar-base/pull/321)). +- The const `BASE_FEE` changed from `number` to `string` ([#321](https://github.com/stellar/js-stellar-base/pull/321)). +- The option `fee` passed to `new TransactionBuilder({fee: ..})` changed from `number` to `string` ([#321](https://github.com/stellar/js-stellar-base/pull/321)). +- The following fields, which were previously an `xdr.AccountID` are now a `xdr.MuxedAccount` ([#325](https://github.com/stellar/js-stellar-base/pull/325)): + - `PaymentOp.destination` + - `PathPaymentStrictReceiveOp.destination` + - `PathPaymentStrictSendOp.destination` + - `Operation.sourceAccount` + - `Operation.destination` (for `ACCOUNT_MERGE`) + - `Transaction.sourceAccount` + - `FeeBumpTransaction.feeSource` + + You can get the string representation by calling `StrKey.encodeMuxedAccount` which will return a `G..` or `M..` account. +- Remove the following deprecated functions ([#331](https://github.com/stellar/js-stellar-base/pull/331)): + - `Operation.manageOffer` + - `Operation.createPassiveOffer` + - `Operation.pathPayment` + - `Keypair.fromBase58Seed` +- Remove the `Network` class ([#331](https://github.com/stellar/js-stellar-base/pull/331)). +- Remove `vendor/base58.js` ([#331](https://github.com/stellar/js-stellar-base/pull/331)). + + +## [v2.1.9](https://github.com/stellar/js-stellar-base/compare/v2.1.8..v2.1.9) + +### Fix +- Update dependencies which depend on minimist. ([#332](https://github.com/stellar/js-stellar-base/pull/332)) + +## [v2.1.8](https://github.com/stellar/js-stellar-base/compare/v2.1.7..v2.1.8) + +### Fix +- Fix `setTimeout(0)` and partially defined timebounds ([#315](https://github.com/stellar/js-stellar-base/pull/315)). + +## [v2.1.7](https://github.com/stellar/js-stellar-base/compare/v2.1.6..v2.1.7) + +### Fix +- Fix TypeScript options for `ManageData` operation to allow setting value to `null` ([#310](https://github.com/stellar/js-stellar-base/issues/310)) +- Fix crash on partially defined time bounds ([#303](https://github.com/stellar/js-stellar-base/issues/303)) + +## [v2.1.6](https://github.com/stellar/js-stellar-base/compare/v2.1.5..v2.1.6) + +### Fix +- Fix npm deployment. + +## [v2.1.5](https://github.com/stellar/js-stellar-base/compare/v2.1.4..v2.1.5) + +### Add +- Add `toXDR` type to Transaction class ([#296](https://github.com/stellar/js-stellar-base/issues/296)) + +### Fix +- Fix doc link ([#298](https://github.com/stellar/js-stellar-base/issues/298)) + +### Remove +- Remove node engine restriction ([#294](https://github.com/stellar/js-stellar-base/issues/294)) + +### Update +- Update creating an account example ([#299](https://github.com/stellar/js-stellar-base/issues/299)) +- Use `console.trace` to get line num in `Networks.use` ([#300](https://github.com/stellar/js-stellar-base/issues/300)) + +## [v2.1.4](https://github.com/stellar/js-stellar-base/compare/v2.1.3..v2.1.4) + +## Update +- Regenerate the XDR definitions to include MetaV2 ([#288](https://github.com/stellar/js-stellar-base/issues/288)) + +## [v2.1.3](https://github.com/stellar/js-stellar-base/compare/v2.1.2...v2.1.3) + +## Update 📣 + +- Throw errors when obviously invalid network passphrases are used in + `new Transaction()`. + ([284](https://github.com/stellar/js-stellar-base/pull/284)) + +## [v2.1.2](https://github.com/stellar/js-stellar-base/compare/v2.1.1...v2.1.2) + +## Update 📣 + +- Update documentation for `Operation` to show `pathPaymentStrictSend` and `pathPaymentStrictReceive`. ([279](https://github.com/stellar/js-stellar-base/pull/279)) + +## [v2.1.1](https://github.com/stellar/js-stellar-base/compare/v2.1.0...v2.1.1) + +## Update 📣 + +- Update `asset.toString()` to return canonical representation for asset. ([277](https://github.com/stellar/js-stellar-base/pull/277)). + + Calling `asset.toString()` will return `native` for `XLM` or `AssetCode:AssetIssuer` for issued assets. See [this PR](https://github.com/stellar/stellar-protocol/pull/313) for more information. + +## [v2.1.0](https://github.com/stellar/js-stellar-base/compare/v2.0.2...v2.1.0) + +This release adds support for [stellar-core protocol 12 release](https://github.com/stellar/stellar-core/projects/11) and [CAP 24](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0024.md) ("Make PathPayment Symmetrical"). + +### Add ➕ + + - `Operation.pathPaymentStrictSend`: Sends a path payments, debiting from the source account exactly a specified amount of one asset, crediting at least a given amount of another asset. ([#274](https://github.com/stellar/js-stellar-base/pull/274)). + + The following operation will debit exactly 10 USD from the source account, crediting at least 9.2 EUR in the destination account 💸: + ```js + var sendAsset = new StellarBase.Asset( + 'USD', + 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + ); + var sendAmount = '10'; + var destination = + 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ'; + var destAsset = new StellarBase.Asset( + 'USD', + 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + ); + var destMin = '9.2'; + var path = [ + new StellarBase.Asset( + 'USD', + 'GBBM6BKZPEHWYO3E3YKREDPQXMS4VK35YLNU7NFBRI26RAN7GI5POFBB' + ), + new StellarBase.Asset( + 'EUR', + 'GDTNXRLOJD2YEBPKK7KCMR7J33AAG5VZXHAJTHIG736D6LVEFLLLKPDL' + ) + ]; + let op = StellarBase.Operation.pathPaymentStrictSend({ + sendAsset, + sendAmount, + destination, + destAsset, + destMin, + path + }); + ``` + - `Operation.pathPaymentStrictReceive`: This behaves the same as the former `pathPayments` operation. ([#274](https://github.com/stellar/js-stellar-base/pull/274)). + + The following operation will debit maximum 10 USD from the source account, crediting exactly 9.2 EUR in the destination account 💸: + ```js + var sendAsset = new StellarBase.Asset( + 'USD', + 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + ); + var sendMax = '10'; + var destination = + 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ'; + var destAsset = new StellarBase.Asset( + 'USD', + 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + ); + var destAmount = '9.2'; + var path = [ + new StellarBase.Asset( + 'USD', + 'GBBM6BKZPEHWYO3E3YKREDPQXMS4VK35YLNU7NFBRI26RAN7GI5POFBB' + ), + new StellarBase.Asset( + 'EUR', + 'GDTNXRLOJD2YEBPKK7KCMR7J33AAG5VZXHAJTHIG736D6LVEFLLLKPDL' + ) + ]; + let op = StellarBase.Operation.pathPaymentStrictReceive({ + sendAsset, + sendMax, + destination, + destAsset, + destAmount, + path + }); + ``` + +## Deprecated ❗️ + +- `Operation.pathPayment` is being deprecated in favor of `Operation.pathPaymentStrictReceive`. Both functions take the same arguments and behave the same. ([#274](https://github.com/stellar/js-stellar-base/pull/274)). + +## [v2.0.2](https://github.com/stellar/js-stellar-base/compare/v2.0.1...v2.0.2) + +### Fix +- Fix issue [#269](https://github.com/stellar/js-stellar-base/issues/269). ManageBuyOffer should extend BaseOptions and inherited property "source". ([#270](https://github.com/stellar/js-stellar-base/pull/270)). + +## [v2.0.1](https://github.com/stellar/js-stellar-base/compare/v2.0.0...v2.0.1) + +No changes. Fixes deploy script and includes changes from [v2.0.0](https://github.com/stellar/js-stellar-base/compare/v1.1.2...v2.0.0). + +## [v2.0.0](https://github.com/stellar/js-stellar-base/compare/v1.1.2...v2.0.0) + +### BREAKING CHANGES + +- Drop Support for Node 6 since it has been end-of-lifed and no longer in LTS. We now require Node 10 which is the current LTS until April 1st, 2021. ([#255](https://github.com/stellar/js-stellar-base/pull/255)) + +## [v1.1.2](https://github.com/stellar/js-stellar-base/compare/v1.1.1...v1.1.2) + +### Fix +- Fix no-network warnings ([#248](https://github.com/stellar/js-stellar-base/issues/248)) + +## [v1.1.1](https://github.com/stellar/js-stellar-base/compare/v1.1.0...v1.1.1) + +### Fix +- Add types for new networkPassphrase argument. Fix [#237](https://github.com/stellar/js-stellar-base/issues/237). ([#238](https://github.com/stellar/js-stellar-base/issues/238)) + +## [v1.1.0](https://github.com/stellar/js-stellar-base/compare/v1.0.3...v1.1.0) + +### Deprecated + +Deprecate global singleton for `Network`. The following classes and +methods take an optional network passphrase, and issue a warning if it +is not passed: + +#### `Keypair.master` + +```js +Keypair.master(Networks.TESTNET) +``` + +#### constructor for `Transaction` + +```js +const xenv = new xdr.TransactionEnvelope({ tx: xtx }); +new Transaction(xenv, Networks.TESTNET); +``` + +#### constructor for `TransactionBuilder` and method `TransactionBuilder.setNetworkPassphrase` + +```js +const transaction = new StellarSdk.TransactionBuilder(account, { + fee: StellarSdk.BASE_FEE, + networkPassphrase: Networks.TESTNET +}) +``` + +See [#207](https://github.com/stellar/js-stellar-base/issues/207) and [#112](https://github.com/stellar/js-stellar-base/issues/112) for more information. + +The `Network` class will be removed on the `2.0` release. + +### Add +- Add docs for BASE_FEE const. ([#211](https://github.com/stellar/js-stellar-base/issues/211)) + +### Fix +- Fix typo. ([#213](https://github.com/stellar/js-stellar-base/issues/213)) + +## [v1.0.3](https://github.com/stellar/js-stellar-base/compare/v1.0.2...v1.0.3) + +### Add + +- Add `toString()` to Asset ([#172](https://github.com/stellar/js-stellar-base/issues/172)) +- Add types for missing Network functions ([#208](https://github.com/stellar/js-stellar-base/issues/208)) +- Add BASE_FEE to TS types ([#209](https://github.com/stellar/js-stellar-base/issues/209)) + +### Fix +- Fix typo in types ([#194](https://github.com/stellar/js-stellar-base/issues/194)) +- Fix types: Fee is no longer optional ([#195](https://github.com/stellar/js-stellar-base/issues/195)) +- Fix typings for Account Sequence Number ([#203](https://github.com/stellar/js-stellar-base/issues/203)) +- Fix typings for Transaction Sequence Number ([#205](https://github.com/stellar/js-stellar-base/issues/205)) + +## [v1.0.2](https://github.com/stellar/js-stellar-base/compare/v1.0.1...v1.0.2) + +- Fix a bug where `sodium-native` was making it into the browser bundle, which + is supposed to use `tweetnacl`. + +## [v1.0.1](https://github.com/stellar/js-stellar-base/compare/v1.0.0...v1.0.1) + +- Restore `Operation.manageOffer` and `Operation.createPassiveOffer`, and issue + a warning if they're called. +- Add type definitions for the timeBounds property of transactions. + +## [v1.0.0](https://github.com/stellar/js-stellar-base/compare/v0.13.2...v1.0.0) + +- **Breaking change** Stellar Protocol 11 compatibility + - Rename `Operation.manageOffer` to `Operation.manageSellOffer`. + - Rename `Operation.createPassiveOffer` to `Operation.createPassiveSellOffer`. + - Add `Operation.manageBuyOffer`. +- **Breaking change** The `fee` parameter to `TransactionBuilder` is now + required. Failing to provide a fee will throw an error. + +## [v0.13.2](https://github.com/stellar/js-stellar-base/compare/v0.13.1...v0.13.2) + +- Bring DefinitelyTyped definitions into the repo for faster updating. +- Add missing Typescript type definitions. +- Add code to verify signatures when added to transactions. +- Replace ed25519 with sodium-native. +- Fix the xdr for SCP_MESSAGE. +- Update the README for the latest info. + +## [v0.13.1](https://github.com/stellar/js-stellar-base/compare/v0.13.0...v0.13.1) + +- Travis: Deploy NPM with an environment variable instead of an encrypted API + key. +- Instruct Travis to cache node_modules + +## [v0.13.0](https://github.com/stellar/js-stellar-base/compare/v0.12.0...v0.13.0) + +- Remove the `crypto` library. This reduces the number of Node built-ins we have + to shim into the production bundle, and incidentally fixes a bug with + Angular 6. + +## [v0.12.0](https://github.com/stellar/js-stellar-base/compare/v0.11.0...v0.12.0) + +- _Warning_ Calling TransactionBuilder without a `fee` param is now deprecated + and will issue a warning. In a later release, it will throw an error. Please + update your transaction builders as soon as you can! +- Add a `toXDR` function for transactions that lets you get the transaction as a + base64-encoded string (so you may enter it into the Stellar Laboratory XDR + viewer, for one) +- Fix TransactionBuilder example syntax errors +- Use more thorough "create account" documentation +- Add `Date` support for `TransactionBuilder` `timebounds` +- Add two functions to `Transaction` that support pre-generated transactions: + - `getKeypairSignature` helps users sign pre-generated transaction XDRs + - `addSignature` lets you add pre-generated signatures to a built transaction + +## 0.11.0 + +- Added ESLint and Prettier to enforce code style +- Upgraded dependencies, including Babel to 6 +- Bump local node version to 6.14.0 +- Change Operations.\_fromXDRAmount to not use scientific notation (1e-7) for + small amounts like 0.0000001. + +## 0.10.0 + +- **Breaking change** Added + [`TransactionBuilder.setTimeout`](https://stellar.github.io/js-stellar-base/TransactionBuilder.html#setTimeout) + method that sets `timebounds.max_time` on a transaction. Because of the + distributed nature of the Stellar network it is possible that the status of + your transaction will be determined after a long time if the network is highly + congested. If you want to be sure to receive the status of the transaction + within a given period you should set the TimeBounds with `maxTime` on the + transaction (this is what `setTimeout` does internally; if there's `minTime` + set but no `maxTime` it will be added). Call to + `TransactionBuilder.setTimeout` is required if Transaction does not have + `max_time` set. If you don't want to set timeout, use `TimeoutInfinite`. In + general you should set `TimeoutInfinite` only in smart contracts. Please check + [`TransactionBuilder.setTimeout`](https://stellar.github.io/js-stellar-base/TransactionBuilder.html#setTimeout) + docs for more information. +- Fixed decoding empty `homeDomain`. + +## 0.9.0 + +- Update `js-xdr` to support unmarshaling non-utf8 strings. +- String fields returned by `Operation.fromXDRObject()` are of type `Buffer` now + (except `SetOptions.home_domain` and `ManageData.name` - both required to be + ASCII by stellar-core). + +## 0.8.3 + +- Update `xdr` files to V10. + +## 0.8.2 + +- Upgrade `js-xdr`. + +## 0.8.1 + +- Removed `src` from `.npmignore`. + +## 0.8.0 + +- Added support for `bump_sequence` operation. +- Fixed many code style issues. +- Updated docs. + +## 0.7.8 + +- Updated dependencies. + +## 0.7.7 + +- Updated docs. + +## 0.7.6 + +- Updated docs. + +## 0.7.5 + +- `Keypair.constructor` now requires `type` field to define public-key signature + system used in this instance (so `Keypair` can support other systems in a + future). It also checks if public key and secret key match if both are passed + (to prevent nasty bugs). +- `Keypair.fromRawSeed` has been renamed to `Keypair.fromRawEd25519Seed` to make + it clear that the seed must be Ed25519 seed. +- It's now possible to instantiate `Memo` class so it's easier to check it's + type and value (without dealing with low level `xdr.Memo` objects). +- Changed `Asset.toXdrObject` to `Asset.toXDRObject` and + `Operation.operationToObject` to `Operation.toXDRObject` for consistency. +- Time bounds support for numeric input values. +- Added `browser` prop to package.json. + +## 0.7.4 + +- Update dependencies. +- Remove unused methods. + +## 0.7.3 + +- Allow hex string in setOptions signers + +## 0.7.2 + +- Updated XDR files + +## 0.7.1 + +- Checking hash preimage length + +## 0.7.0 + +- Support for new signer types: `sha256Hash`, `preAuthTx`. +- `StrKey` helper class with `strkey` encoding related methods. +- Removed deprecated methods: `Keypair.isValidPublicKey` (use `StrKey`), + `Keypair.isValidSecretKey` (use `StrKey`), `Keypair.fromSeed`, `Keypair.seed`, + `Keypair.rawSeed`. +- **Breaking changes**: + - `Network` must be explicitly selected. Previously testnet was a default + network. + - `Operation.setOptions()` method `signer` param changed. + - `Keypair.fromAccountId()` renamed to `Keypair.fromPublicKey()`. + - `Keypair.accountId()` renamed to `Keypair.publicKey()`. + - Dropping support for `End-of-Life` node versions. + +## 0.6.0 + +- **Breaking change** `ed25519` package is now optional dependency. +- Export account flags constants. + +## 0.5.7 + +- Fixes XDR decoding issue when using firefox + +## 0.5.6 + +- UTF-8 support in `Memo.text()`. + +## 0.5.5 + +- Make 0 a valid number for transaction fee, +- Fix signer in Operation.operationToObject() - close #82 + +## 0.5.4 + +- Fixed Lodash registering itself to global scope. + +## 0.5.3 + +- Add support for ManageData operation. + +## 0.5.2 + +- Moved `Account.isValidAccountId` to `Keypair.isValidPublicKey`. It's still + possible to use `Account.isValidAccountId` but it will be removed in the next + minor release (breaking change). (af10f2a) +- `signer.address` option in `Operation.setOptions` was changed to + `signer.pubKey`. It's still possible to use `signer.address` but it will be + removed in the next minor release (breaking change). (07f43fb) +- `Operation.setOptions` now accepts strings for `clearFlags`, `setFlags`, + `masterWeight`, `lowThreshold`, `medThreshold`, `highThreshold`, + `signer.weight` options. (665e018) +- Fixed TransactionBuilder timebounds option. (854f275) +- Added `CHANGELOG.md` file. + +## 0.5.1 + +- Now it's possible to pass `price` params as `{n: numerator, d: denominator}` + object. Thanks @FredericHeem. (#73) + +## 0.5.0 + +- **Breaking change** `sequence` in `Account` constructor must be a string. + (4da5dfc) +- **Breaking change** Removed deprecated methods (180a5b8): + - `Account.isValidAddress` (replaced by `Account.isValidAccountId`) + - `Account.getSequenceNumber` (replaced by `Account.sequenceNumber`) + - `Keypair.address` (replaced by `Keypair.accountId`) + - `Network.usePublicNet` (replaced by `Network.usePublicNetwork`) + - `Network.useTestNet` (replaced by `Network.useTestNetwork`) + - `TransactionBuilder.addSigner` (call `Transaction.sign` on build + `Transaction` object) diff --git a/node_modules/@stellar/stellar-base/LICENSE b/node_modules/@stellar/stellar-base/LICENSE new file mode 100644 index 000000000..e936ce3e0 --- /dev/null +++ b/node_modules/@stellar/stellar-base/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015 Stellar Development Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/README.md b/node_modules/@stellar/stellar-base/README.md new file mode 100644 index 000000000..502204330 --- /dev/null +++ b/node_modules/@stellar/stellar-base/README.md @@ -0,0 +1,198 @@ +# JS Stellar Base + +[![Tests](https://github.com/stellar/js-stellar-base/actions/workflows/tests.yml/badge.svg)](https://github.com/stellar/js-stellar-base/actions/workflows/tests.yml) +[![Code Climate](https://codeclimate.com/github/stellar/js-stellar-base/badges/gpa.svg)](https://codeclimate.com/github/stellar/js-stellar-base) +[![Coverage Status](https://coveralls.io/repos/stellar/js-stellar-base/badge.svg?branch=master&service=github)](https://coveralls.io/github/stellar/js-stellar-base?branch=master) +[![Dependency Status](https://david-dm.org/stellar/js-stellar-base.svg)](https://david-dm.org/stellar/js-stellar-base) + +The stellar-base library is the lowest-level stellar helper library. It consists +of classes to read, write, hash, and sign the xdr structures that are used in +[stellar-core](https://github.com/stellar/stellar-core). This is an +implementation in JavaScript that can be used on either Node.js or web browsers. + +- **[API Reference](https://stellar.github.io/js-stellar-base/)** + +> **Warning!** The Node version of this package uses the [`sodium-native`](https://www.npmjs.com/package/sodium-native) package, a native implementation of [Ed25519](https://ed25519.cr.yp.to/) in Node.js, as an [optional dependency](https://docs.npmjs.com/files/package.json#optionaldependencies). +> This means that if for any reason installation of this package fails, `stellar-base` will fallback to the much slower implementation contained in [`tweetnacl`](https://www.npmjs.com/package/tweetnacl). +> +> If you'd explicitly prefer **not** to install the `sodium-native` package, pass the appropriate flag to skip optional dependencies when installing this package (e.g. `--no-optional` if using `npm install` or `--without-optional` using `yarn install`). +> +> If you are using `stellar-base` in a browser you can ignore this. However, for production backend deployments you should most likely be using `sodium-native`. +> If `sodium-native` is successfully installed and working, +> `StellarBase.FastSigning` variable will be equal `true`. Otherwise it will be +> `false`. + +## Quick start + +Using yarn to include js-stellar-base in your own project: + +```shell +yarn add @stellar/stellar-base +``` + +For browsers, [use Bower to install it](#to-use-in-the-browser). It exports a +variable `StellarBase`. The example below assumes you have `stellar-base.js` +relative to your html file. + +```html + + +``` + +## Install + +### To use as a module in a Node.js project + +1. Install it using yarn: + +```shell +yarn add @stellar/stellar-base +``` + +2. require/import it in your JavaScript: + +```js +var StellarBase = require('@stellar/stellar-base'); +``` + +### To self host for use in the browser + +1. Install it using [bower](http://bower.io): + +```shell +bower install stellar-base +``` + +2. Include it in the browser: + +```html + + +``` + +If you don't want to use install Bower, you can copy built JS files from the +[bower-js-stellar-base repo](https://github.com/stellar/bower-js-stellar-base). + +### To use the [cdnjs](https://cdnjs.com/libraries/stellar-base) hosted script in the browser + +1. Instruct the browser to fetch the library from + [cdnjs](https://cdnjs.com/libraries/stellar-base), a 3rd party service that + hosts js libraries: + +```html + + +``` + +Note that this method relies using a third party to host the JS library. This +may not be entirely secure. + +Make sure that you are using the latest version number. They can be found on the +[releases page in Github](https://github.com/stellar/js-stellar-base/releases). + +### To develop and test js-stellar-base itself + +1. Install Node 18.x + +We support the oldest LTS release of Node, which is [currently 18.x](https://nodejs.org/en/about/releases/). Please likewise install and develop on Node 16 so you don't get surprised when your code works locally but breaks in CI. + +If you work on several projects that use different Node versions, you might find helpful to install a NodeJS version manager: + + - https://github.com/creationix/nvm + - https://github.com/wbyoung/avn + - https://github.com/asdf-vm/asdf + +2. Install Yarn + +This project uses [Yarn](https://yarnpkg.com/) to manages its dependencies. To install Yarn, follow the project instructions available at https://yarnpkg.com/en/docs/install. + +3. Clone the repo + +```shell +git clone https://github.com/stellar/js-stellar-base.git +``` + +4. Install dependencies inside js-stellar-base folder + +```shell +cd js-stellar-base +yarn +``` + +5. Observe the project's code style + +While you're making changes, make sure to regularly run the linter to catch any +linting errors (in addition to making sure your text editor supports ESLint) + +```shell +yarn lint +``` + +as well as fixing any formatting errors with + +```shell +yarn fmt +``` + +If you're working on a file not in `src`, limit your code to Node 6.16 ES! See +what's supported here: https://node.green/. (Our npm library must support +earlier versions of Node, so the tests need to run on those versions.) + +#### Updating XDR definitions + +1. Make sure you have [Docker](https://www.docker.com/) installed and running. +2. `make reset-xdr` + +## Usage + +For information on how to use js-stellar-base, take a look at the docs in the +[docs folder](./docs). + +## Testing + +To run all tests: + +```shell +yarn test +``` + +To run a specific set of tests: + +```shell +yarn test:node +yarn test:browser +``` + +Tests are also run automatically in Github Actions for every master commit and +pull request. + +## Documentation + +Documentation for this repo lives inside the [docs folder](./docs). + +## Contributing + +Please see the [CONTRIBUTING.md](./CONTRIBUTING.md) for details on how to +contribute to this project. + +## Publishing to npm + +``` +npm version [ | major | minor | patch | premajor | preminor | prepatch | prerelease] +``` + +A new version will be published to npm **and** Bower by GitHub Actions. + +npm >= 2.13.0 required. Read more about +[npm version](https://docs.npmjs.com/cli/version). + +## License + +js-stellar-base is licensed under an Apache-2.0 license. See the +[LICENSE](./LICENSE) file for details. diff --git a/node_modules/@stellar/stellar-base/dist/stellar-base.js b/node_modules/@stellar/stellar-base/dist/stellar-base.js new file mode 100644 index 000000000..506675b09 --- /dev/null +++ b/node_modules/@stellar/stellar-base/dist/stellar-base.js @@ -0,0 +1,31868 @@ +var StellarBase; +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 3740: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* provided dependency */ var console = __webpack_require__(6763); +/*! For license information please see xdr.js.LICENSE.txt */ +!function(t,e){ true?module.exports=e():0}(this,(()=>(()=>{var t={616:(t,e,r)=>{"use strict";r.d(e,{A:()=>i});var n=r(287);n.hp.alloc(1).subarray(0,1)instanceof n.hp||(n.hp.prototype.subarray=function(t,e){const r=Uint8Array.prototype.subarray.call(this,t,e);return Object.setPrototypeOf(r,n.hp.prototype),r});const i=n.hp},281:(t,e,r)=>{const n=r(164);t.exports=n},164:(t,e,r)=>{"use strict";r.r(e),r.d(e,{Array:()=>F,Bool:()=>S,Double:()=>L,Enum:()=>q,Float:()=>O,Hyper:()=>U,Int:()=>v,LargeInt:()=>x,Opaque:()=>D,Option:()=>X,Quadruple:()=>N,Reference:()=>G,String:()=>M,Struct:()=>Y,Union:()=>W,UnsignedHyper:()=>T,UnsignedInt:()=>R,VarArray:()=>P,VarOpaque:()=>z,Void:()=>k,XdrReader:()=>f,XdrWriter:()=>c,config:()=>it});class n extends TypeError{constructor(t){super(`XDR Write Error: ${t}`)}}class i extends TypeError{constructor(t){super(`XDR Read Error: ${t}`)}}class o extends TypeError{constructor(t){super(`XDR Type Definition Error: ${t}`)}}class s extends o{constructor(){super("method not implemented, it should be overloaded in the descendant class.")}}var u=r(616).A;class f{constructor(t){if(!u.isBuffer(t)){if(!(t instanceof Array||Array.isArray(t)||ArrayBuffer.isView(t)))throw new i(`source invalid: ${t}`);t=u.from(t)}this._buffer=t,this._length=t.length,this._index=0}_buffer;_length;_index;get eof(){return this._index===this._length}advance(t){const e=this._index;if(this._index+=t,this._length0){for(let t=0;t0){const t=this.alloc(r);this._buffer.fill(0,t,this._index)}}writeInt32BE(t){const e=this.alloc(4);this._buffer.writeInt32BE(t,e)}writeUInt32BE(t){const e=this.alloc(4);this._buffer.writeUInt32BE(t,e)}writeBigInt64BE(t){const e=this.alloc(8);this._buffer.writeBigInt64BE(t,e)}writeBigUInt64BE(t){const e=this.alloc(8);this._buffer.writeBigUInt64BE(t,e)}writeFloatBE(t){const e=this.alloc(4);this._buffer.writeFloatBE(t,e)}writeDoubleBE(t){const e=this.alloc(8);this._buffer.writeDoubleBE(t,e)}static bufferChunkSize=h}var l=r(616).A;class p{toXDR(t="raw"){if(!this.write)return this.constructor.toXDR(this,t);const e=new c;return this.write(this,e),w(e.finalize(),t)}fromXDR(t,e="raw"){if(!this.read)return this.constructor.fromXDR(t,e);const r=new f(m(t,e)),n=this.read(r);return r.ensureInputConsumed(),n}validateXDR(t,e="raw"){try{return this.fromXDR(t,e),!0}catch(t){return!1}}static toXDR(t,e="raw"){const r=new c;return this.write(t,r),w(r.finalize(),e)}static fromXDR(t,e="raw"){const r=new f(m(t,e)),n=this.read(r);return r.ensureInputConsumed(),n}static validateXDR(t,e="raw"){try{return this.fromXDR(t,e),!0}catch(t){return!1}}}class d extends p{static read(t){throw new s}static write(t,e){throw new s}static isValid(t){return!1}}class g extends p{isValid(t){return!1}}class y extends TypeError{constructor(t){super(`Invalid format ${t}, must be one of "raw", "hex", "base64"`)}}function w(t,e){switch(e){case"raw":return t;case"hex":return t.toString("hex");case"base64":return t.toString("base64");default:throw new y(e)}}function m(t,e){switch(e){case"raw":return t;case"hex":return l.from(t,"hex");case"base64":return l.from(t,"base64");default:throw new y(e)}}function b(t,e){return null!=t&&(t instanceof e||_(t,e)&&"function"==typeof t.constructor.read&&"function"==typeof t.constructor.write&&_(t,"XdrType"))}function _(t,e){do{if(t.constructor.name===e)return!0}while(t=Object.getPrototypeOf(t));return!1}const B=2147483647,E=-2147483648;class v extends d{static read(t){return t.readInt32BE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");if((0|t)!==t)throw new n("invalid i32 value");e.writeInt32BE(t)}static isValid(t){return"number"==typeof t&&(0|t)===t&&(t>=E&&t<=B)}}function A(t,e,r){if("bigint"!=typeof t)throw new TypeError("Expected bigint 'value', got "+typeof t);const n=e/r;if(1===n)return[t];if(r<32||r>128||2!==n&&4!==n&&8!==n)throw new TypeError(`invalid bigint (${t}) and slice size (${e} -> ${r}) combination`);const i=BigInt(r),o=new Array(n);for(let e=0;e>=i;return o}function I(t,e){if(e)return[0n,(1n<=o&&i<=s)return i;throw new TypeError(`bigint values [${t}] for ${function(t,e){return`${e?"u":"i"}${t}`}(e,r)} out of range [${o}, ${s}]: ${i}`)}(t,this.size,this.unsigned)}get unsigned(){throw new s}get size(){throw new s}slice(t){return A(this._value,this.size,t)}toString(){return this._value.toString()}toJSON(){return{_value:this._value.toString()}}toBigInt(){return BigInt(this._value)}static read(t){const{size:e}=this.prototype;return 64===e?new this(t.readBigUInt64BE()):new this(...Array.from({length:e/64},(()=>t.readBigUInt64BE())).reverse())}static write(t,e){if(t instanceof this)t=t._value;else if("bigint"!=typeof t||t>this.MAX_VALUE||t>32n)|0}get size(){return 64}get unsigned(){return!1}static fromBits(t,e){return new this(t,e)}}U.defineIntBoundaries();const $=4294967295;class R extends d{static read(t){return t.readUInt32BE()}static write(t,e){if("number"!=typeof t||!(t>=0&&t<=$)||t%1!=0)throw new n("invalid u32 value");e.writeUInt32BE(t)}static isValid(t){return"number"==typeof t&&t%1==0&&(t>=0&&t<=$)}}R.MAX_VALUE=$,R.MIN_VALUE=0;class T extends x{constructor(...t){super(t)}get low(){return Number(0xffffffffn&this._value)|0}get high(){return Number(this._value>>32n)|0}get size(){return 64}get unsigned(){return!0}static fromBits(t,e){return new this(t,e)}}T.defineIntBoundaries();class O extends d{static read(t){return t.readFloatBE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");e.writeFloatBE(t)}static isValid(t){return"number"==typeof t}}class L extends d{static read(t){return t.readDoubleBE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");e.writeDoubleBE(t)}static isValid(t){return"number"==typeof t}}class N extends d{static read(){throw new o("quadruple not supported")}static write(){throw new o("quadruple not supported")}static isValid(){return!1}}class S extends d{static read(t){const e=v.read(t);switch(e){case 0:return!1;case 1:return!0;default:throw new i(`got ${e} when trying to read a bool`)}}static write(t,e){const r=t?1:0;v.write(r,e)}static isValid(t){return"boolean"==typeof t}}var V=r(616).A;class M extends g{constructor(t=R.MAX_VALUE){super(),this._maxLength=t}read(t){const e=R.read(t);if(e>this._maxLength)throw new i(`saw ${e} length String, max allowed is ${this._maxLength}`);return t.read(e)}readString(t){return this.read(t).toString("utf8")}write(t,e){const r="string"==typeof t?V.byteLength(t,"utf8"):t.length;if(r>this._maxLength)throw new n(`got ${t.length} bytes, max allowed is ${this._maxLength}`);R.write(r,e),e.write(t,r)}isValid(t){return"string"==typeof t?V.byteLength(t,"utf8")<=this._maxLength:!!(t instanceof Array||V.isBuffer(t))&&t.length<=this._maxLength}}var C=r(616).A;class D extends g{constructor(t){super(),this._length=t}read(t){return t.read(this._length)}write(t,e){const{length:r}=t;if(r!==this._length)throw new n(`got ${t.length} bytes, expected ${this._length}`);e.write(t,r)}isValid(t){return C.isBuffer(t)&&t.length===this._length}}var j=r(616).A;class z extends g{constructor(t=R.MAX_VALUE){super(),this._maxLength=t}read(t){const e=R.read(t);if(e>this._maxLength)throw new i(`saw ${e} length VarOpaque, max allowed is ${this._maxLength}`);return t.read(e)}write(t,e){const{length:r}=t;if(t.length>this._maxLength)throw new n(`got ${t.length} bytes, max allowed is ${this._maxLength}`);R.write(r,e),e.write(t,r)}isValid(t){return j.isBuffer(t)&&t.length<=this._maxLength}}class F extends g{constructor(t,e){super(),this._childType=t,this._length=e}read(t){const e=new r.g.Array(this._length);for(let r=0;rthis._maxLength)throw new i(`saw ${e} length VarArray, max allowed is ${this._maxLength}`);const r=new Array(e);for(let n=0;nthis._maxLength)throw new n(`got array of size ${t.length}, max allowed is ${this._maxLength}`);R.write(t.length,e);for(const r of t)this._childType.write(r,e)}isValid(t){if(!(t instanceof Array)||t.length>this._maxLength)return!1;for(const e of t)if(!this._childType.isValid(e))return!1;return!0}}class X extends d{constructor(t){super(),this._childType=t}read(t){if(S.read(t))return this._childType.read(t)}write(t,e){const r=null!=t;S.write(r,e),r&&this._childType.write(t,e)}isValid(t){return null==t||this._childType.isValid(t)}}class k extends d{static read(){}static write(t){if(void 0!==t)throw new n("trying to write value to a void slot")}static isValid(t){return void 0===t}}class q extends d{constructor(t,e){super(),this.name=t,this.value=e}static read(t){const e=v.read(t),r=this._byValue[e];if(void 0===r)throw new i(`unknown ${this.enumName} member for value ${e}`);return r}static write(t,e){if(!this.isValid(t))throw new n(`${t} has enum name ${t?.enumName}, not ${this.enumName}: ${JSON.stringify(t)}`);v.write(t.value,e)}static isValid(t){return t?.constructor?.enumName===this.enumName||b(t,this)}static members(){return this._members}static values(){return Object.values(this._members)}static fromName(t){const e=this._members[t];if(!e)throw new TypeError(`${t} is not a member of ${this.enumName}`);return e}static fromValue(t){const e=this._byValue[t];if(void 0===e)throw new TypeError(`${t} is not a value of any member of ${this.enumName}`);return e}static create(t,e,r){const n=class extends q{};n.enumName=e,t.results[e]=n,n._members={},n._byValue={};for(const[t,e]of Object.entries(r)){const r=new n(t,e);n._members[t]=r,n._byValue[e]=r,n[t]=()=>r}return n}}class G extends d{resolve(){throw new o('"resolve" method should be implemented in the descendant class')}}class Y extends g{constructor(t){super(),this._attributes=t||{}}static read(t){const e={};for(const[r,n]of this._fields)e[r]=n.read(t);return new this(e)}static write(t,e){if(!this.isValid(t))throw new n(`${t} has struct name ${t?.constructor?.structName}, not ${this.structName}: ${JSON.stringify(t)}`);for(const[r,n]of this._fields){const i=t._attributes[r];n.write(i,e)}}static isValid(t){return t?.constructor?.structName===this.structName||b(t,this)}static create(t,e,r){const n=class extends Y{};n.structName=e,t.results[e]=n;const i=new Array(r.length);for(let e=0;e{"use strict";e.byteLength=function(t){var e=u(t),r=e[0],n=e[1];return 3*(r+n)/4-n},e.toByteArray=function(t){var e,r,o=u(t),s=o[0],f=o[1],a=new i(function(t,e,r){return 3*(e+r)/4-r}(0,s,f)),h=0,c=f>0?s-4:s;for(r=0;r>16&255,a[h++]=e>>8&255,a[h++]=255&e;2===f&&(e=n[t.charCodeAt(r)]<<2|n[t.charCodeAt(r+1)]>>4,a[h++]=255&e);1===f&&(e=n[t.charCodeAt(r)]<<10|n[t.charCodeAt(r+1)]<<4|n[t.charCodeAt(r+2)]>>2,a[h++]=e>>8&255,a[h++]=255&e);return a},e.fromByteArray=function(t){for(var e,n=t.length,i=n%3,o=[],s=16383,u=0,a=n-i;ua?a:u+s));1===i?(e=t[n-1],o.push(r[e>>2]+r[e<<4&63]+"==")):2===i&&(e=(t[n-2]<<8)+t[n-1],o.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"="));return o.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)r[s]=o[s],n[o.charCodeAt(s)]=s;function u(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function f(t,e,n){for(var i,o,s=[],u=e;u>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return s.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287:(t,e,r)=>{"use strict";const n=r(526),i=r(251),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.hp=f,e.IS=50;const s=2147483647;function u(t){if(t>s)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,f.prototype),e}function f(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return c(t)}return a(t,e,r)}function a(t,e,r){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!f.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|g(t,e);let n=u(r);const i=n.write(t,e);i!==r&&(n=n.slice(0,i));return n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(W(t,Uint8Array)){const e=new Uint8Array(t);return p(e.buffer,e.byteOffset,e.byteLength)}return l(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(W(t,ArrayBuffer)||t&&W(t.buffer,ArrayBuffer))return p(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(W(t,SharedArrayBuffer)||t&&W(t.buffer,SharedArrayBuffer)))return p(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return f.from(n,e,r);const i=function(t){if(f.isBuffer(t)){const e=0|d(t.length),r=u(e);return 0===r.length||t.copy(r,0,0,e),r}if(void 0!==t.length)return"number"!=typeof t.length||H(t.length)?u(0):l(t);if("Buffer"===t.type&&Array.isArray(t.data))return l(t.data)}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return f.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function h(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function c(t){return h(t),u(t<0?0:0|d(t))}function l(t){const e=t.length<0?0:0|d(t.length),r=u(e);for(let n=0;n=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|t}function g(t,e){if(f.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||W(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return G(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Y(t).length;default:if(i)return n?-1:G(t).length;e=(""+e).toLowerCase(),i=!0}}function y(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return x(this,e,r);case"ascii":return $(this,e,r);case"latin1":case"binary":return R(this,e,r);case"base64":return I(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function w(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function m(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),H(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=f.from(e,n)),f.isBuffer(e))return 0===e.length?-1:b(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):b(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(t,e,r,n,i){let o,s=1,u=t.length,f=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,f/=2,r/=2}function a(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){let n=-1;for(o=r;ou&&(r=u-f),o=r;o>=0;o--){let r=!0;for(let n=0;ni&&(n=i):n=i;const o=e.length;let s;for(n>o/2&&(n=o/2),s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function I(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function x(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+s<=r){let r,n,u,f;switch(s){case 1:e<128&&(o=e);break;case 2:r=t[i+1],128==(192&r)&&(f=(31&e)<<6|63&r,f>127&&(o=f));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(f=(15&e)<<12|(63&r)<<6|63&n,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:r=t[i+1],n=t[i+2],u=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&u)&&(f=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&u,f>65535&&f<1114112&&(o=f))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return function(t){const e=t.length;if(e<=U)return String.fromCharCode.apply(String,t);let r="",n=0;for(;nn.length?(f.isBuffer(e)||(e=f.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!f.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},f.byteLength=g,f.prototype._isBuffer=!0,f.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;er&&(t+=" ... "),""},o&&(f.prototype[o]=f.prototype.inspect),f.prototype.compare=function(t,e,r,n,i){if(W(t,Uint8Array)&&(t=f.from(t,t.offset,t.byteLength)),!f.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0);const u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r);for(let t=0;t>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return _(this,t,e,r);case"utf8":case"utf-8":return B(this,t,e,r);case"ascii":case"latin1":case"binary":return E(this,t,e,r);case"base64":return v(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},f.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const U=4096;function $(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;in)&&(r=n);let i="";for(let n=e;nr)throw new RangeError("Trying to access beyond buffer length")}function N(t,e,r,n,i,o){if(!f.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function S(t,e,r,n,i){P(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,r}function V(t,e,r,n,i){P(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r+7]=o,o>>=8,t[r+6]=o,o>>=8,t[r+5]=o,o>>=8,t[r+4]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=s,s>>=8,t[r+2]=s,s>>=8,t[r+1]=s,s>>=8,t[r]=s,r+8}function M(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function C(t,e,r,n,o){return e=+e,r>>>=0,o||M(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function D(t,e,r,n,o){return e=+e,r>>>=0,o||M(t,0,r,8),i.write(t,e,r,n,52,8),r+8}f.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t],i=1,o=0;for(;++o>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},f.prototype.readUint8=f.prototype.readUInt8=function(t,e){return t>>>=0,e||L(t,1,this.length),this[t]},f.prototype.readUint16LE=f.prototype.readUInt16LE=function(t,e){return t>>>=0,e||L(t,2,this.length),this[t]|this[t+1]<<8},f.prototype.readUint16BE=f.prototype.readUInt16BE=function(t,e){return t>>>=0,e||L(t,2,this.length),this[t]<<8|this[t+1]},f.prototype.readUint32LE=f.prototype.readUInt32LE=function(t,e){return t>>>=0,e||L(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},f.prototype.readUint32BE=f.prototype.readUInt32BE=function(t,e){return t>>>=0,e||L(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},f.prototype.readBigUInt64LE=Z((function(t){X(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t],i=1,o=0;for(;++o=i&&(n-=Math.pow(2,8*e)),n},f.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||L(t,e,this.length);let n=e,i=1,o=this[t+--n];for(;n>0&&(i*=256);)o+=this[t+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*e)),o},f.prototype.readInt8=function(t,e){return t>>>=0,e||L(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},f.prototype.readInt16LE=function(t,e){t>>>=0,e||L(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},f.prototype.readInt16BE=function(t,e){t>>>=0,e||L(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},f.prototype.readInt32LE=function(t,e){return t>>>=0,e||L(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},f.prototype.readInt32BE=function(t,e){return t>>>=0,e||L(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},f.prototype.readBigInt64LE=Z((function(t){X(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<>>=0,e||L(t,4,this.length),i.read(this,t,!0,23,4)},f.prototype.readFloatBE=function(t,e){return t>>>=0,e||L(t,4,this.length),i.read(this,t,!1,23,4)},f.prototype.readDoubleLE=function(t,e){return t>>>=0,e||L(t,8,this.length),i.read(this,t,!0,52,8)},f.prototype.readDoubleBE=function(t,e){return t>>>=0,e||L(t,8,this.length),i.read(this,t,!1,52,8)},f.prototype.writeUintLE=f.prototype.writeUIntLE=function(t,e,r,n){if(t=+t,e>>>=0,r>>>=0,!n){N(this,t,e,r,Math.pow(2,8*r)-1,0)}let i=1,o=0;for(this[e]=255&t;++o>>=0,r>>>=0,!n){N(this,t,e,r,Math.pow(2,8*r)-1,0)}let i=r-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+r},f.prototype.writeUint8=f.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,1,255,0),this[e]=255&t,e+1},f.prototype.writeUint16LE=f.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},f.prototype.writeUint16BE=f.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},f.prototype.writeUint32LE=f.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},f.prototype.writeUint32BE=f.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},f.prototype.writeBigUInt64LE=Z((function(t,e=0){return S(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),f.prototype.writeBigUInt64BE=Z((function(t,e=0){return V(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),f.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);N(this,t,e,r,n-1,-n)}let i=0,o=1,s=0;for(this[e]=255&t;++i>>=0,!n){const n=Math.pow(2,8*r-1);N(this,t,e,r,n-1,-n)}let i=r-1,o=1,s=0;for(this[e+i]=255&t;--i>=0&&(o*=256);)t<0&&0===s&&0!==this[e+i+1]&&(s=1),this[e+i]=(t/o|0)-s&255;return e+r},f.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},f.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},f.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},f.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},f.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},f.prototype.writeBigInt64LE=Z((function(t,e=0){return S(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),f.prototype.writeBigInt64BE=Z((function(t,e=0){return V(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),f.prototype.writeFloatLE=function(t,e,r){return C(this,t,e,!0,r)},f.prototype.writeFloatBE=function(t,e,r){return C(this,t,e,!1,r)},f.prototype.writeDoubleLE=function(t,e,r){return D(this,t,e,!0,r)},f.prototype.writeDoubleBE=function(t,e,r){return D(this,t,e,!1,r)},f.prototype.copy=function(t,e,r,n){if(!f.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function P(t,e,r,n,i,o){if(t>r||t3?0===e||e===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`:`>= ${e}${n} and <= ${r}${n}`,new j.ERR_OUT_OF_RANGE("value",i,t)}!function(t,e,r){X(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||k(e,t.length-(r+1))}(n,i,o)}function X(t,e){if("number"!=typeof t)throw new j.ERR_INVALID_ARG_TYPE(e,"number",t)}function k(t,e,r){if(Math.floor(t)!==t)throw X(t,r),new j.ERR_OUT_OF_RANGE(r||"offset","an integer",t);if(e<0)throw new j.ERR_BUFFER_OUT_OF_BOUNDS;throw new j.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}z("ERR_BUFFER_OUT_OF_BOUNDS",(function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),z("ERR_INVALID_ARG_TYPE",(function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`}),TypeError),z("ERR_OUT_OF_RANGE",(function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=F(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=F(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n}),RangeError);const q=/[^+/0-9A-Za-z-_]/g;function G(t,e){let r;e=e||1/0;const n=t.length;let i=null;const o=[];for(let s=0;s55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function Y(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(q,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function J(t,e,r,n){let i;for(i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function W(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function H(t){return t!=t}const Q=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function Z(t){return"undefined"==typeof BigInt?K:t}function K(){throw new Error("BigInt not supported")}},251:(t,e)=>{e.read=function(t,e,r,n,i){var o,s,u=8*i-n-1,f=(1<>1,h=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-h)-1,p>>=-h,h+=u;h>0;o=256*o+t[e+c],c+=l,h-=8);for(s=o&(1<<-h)-1,o>>=-h,h+=n;h>0;s=256*s+t[e+c],c+=l,h-=8);if(0===o)o=1-a;else{if(o===f)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=a}return(p?-1:1)*s*Math.pow(2,o-n)},e.write=function(t,e,r,n,i,o){var s,u,f,a=8*o-i-1,h=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=h):(s=Math.floor(Math.log(e)/Math.LN2),e*(f=Math.pow(2,-s))<1&&(s--,f*=2),(e+=s+c>=1?l/f:l*Math.pow(2,1-c))*f>=2&&(s++,f/=2),s+c>=h?(u=0,s=h):s+c>=1?(u=(e*f-1)*Math.pow(2,i),s+=c):(u=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,a-=8);t[r+p-d]|=128*g}}},e={};function r(n){var i=e[n];if(void 0!==i)return i.exports;var o=e[n]={exports:{}};return t[n](o,o.exports,r),o.exports}return r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r(281)})())); +//# sourceMappingURL=xdr.js.map + +/***/ }), + +/***/ 4148: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(5606); +/* provided dependency */ var console = __webpack_require__(6763); +// Currently in sync with Node.js lib/assert.js +// https://github.com/nodejs/node/commit/2a51ae424a513ec9a6aa3466baa0cc1d55dd4f3b + +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.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 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. + + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +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); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +var _require = __webpack_require__(9597), + _require$codes = _require.codes, + ERR_AMBIGUOUS_ARGUMENT = _require$codes.ERR_AMBIGUOUS_ARGUMENT, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_INVALID_ARG_VALUE = _require$codes.ERR_INVALID_ARG_VALUE, + ERR_INVALID_RETURN_VALUE = _require$codes.ERR_INVALID_RETURN_VALUE, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; +var AssertionError = __webpack_require__(3918); +var _require2 = __webpack_require__(537), + inspect = _require2.inspect; +var _require$types = (__webpack_require__(537).types), + isPromise = _require$types.isPromise, + isRegExp = _require$types.isRegExp; +var objectAssign = __webpack_require__(1514)(); +var objectIs = __webpack_require__(9394)(); +var RegExpPrototypeTest = __webpack_require__(8075)('RegExp.prototype.test'); +var errorCache = new Map(); +var isDeepEqual; +var isDeepStrictEqual; +var parseExpressionAt; +var findNodeAround; +var decoder; +function lazyLoadComparison() { + var comparison = __webpack_require__(2299); + isDeepEqual = comparison.isDeepEqual; + isDeepStrictEqual = comparison.isDeepStrictEqual; +} + +// Escape control characters but not \n and \t to keep the line breaks and +// indentation intact. +// eslint-disable-next-line no-control-regex +var escapeSequencesRegExp = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g; +var meta = (/* unused pure expression or super */ null && (["\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006", "\\u0007", '\\b', '', '', "\\u000b", '\\f', '', "\\u000e", "\\u000f", "\\u0010", "\\u0011", "\\u0012", "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017", "\\u0018", "\\u0019", "\\u001a", "\\u001b", "\\u001c", "\\u001d", "\\u001e", "\\u001f"])); +var escapeFn = function escapeFn(str) { + return meta[str.charCodeAt(0)]; +}; +var warned = false; + +// The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; +var NO_EXCEPTION_SENTINEL = {}; + +// All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function innerFail(obj) { + if (obj.message instanceof Error) throw obj.message; + throw new AssertionError(obj); +} +function fail(actual, expected, message, operator, stackStartFn) { + var argsLen = arguments.length; + var internalMessage; + if (argsLen === 0) { + internalMessage = 'Failed'; + } else if (argsLen === 1) { + message = actual; + actual = undefined; + } else { + if (warned === false) { + warned = true; + var warn = process.emitWarning ? process.emitWarning : console.warn.bind(console); + warn('assert.fail() with more than one argument is deprecated. ' + 'Please use assert.strictEqual() instead or only pass a message.', 'DeprecationWarning', 'DEP0094'); + } + if (argsLen === 2) operator = '!='; + } + if (message instanceof Error) throw message; + var errArgs = { + actual: actual, + expected: expected, + operator: operator === undefined ? 'fail' : operator, + stackStartFn: stackStartFn || fail + }; + if (message !== undefined) { + errArgs.message = message; + } + var err = new AssertionError(errArgs); + if (internalMessage) { + err.message = internalMessage; + err.generatedMessage = true; + } + throw err; +} +assert.fail = fail; + +// The AssertionError is defined in internal/error. +assert.AssertionError = AssertionError; +function innerOk(fn, argLen, value, message) { + if (!value) { + var generatedMessage = false; + if (argLen === 0) { + generatedMessage = true; + message = 'No value argument passed to `assert.ok()`'; + } else if (message instanceof Error) { + throw message; + } + var err = new AssertionError({ + actual: value, + expected: true, + message: message, + operator: '==', + stackStartFn: fn + }); + err.generatedMessage = generatedMessage; + throw err; + } +} + +// Pure assertion tests whether a value is truthy, as determined +// by !!value. +function ok() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + innerOk.apply(void 0, [ok, args.length].concat(args)); +} +assert.ok = ok; + +// The equality assertion tests shallow, coercive equality with ==. +/* eslint-disable no-restricted-properties */ +assert.equal = function equal(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + // eslint-disable-next-line eqeqeq + if (actual != expected) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: '==', + stackStartFn: equal + }); + } +}; + +// The non-equality assertion tests for whether two objects are not +// equal with !=. +assert.notEqual = function notEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + // eslint-disable-next-line eqeqeq + if (actual == expected) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: '!=', + stackStartFn: notEqual + }); + } +}; + +// The equivalence assertion tests a deep equality relation. +assert.deepEqual = function deepEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + if (!isDeepEqual(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'deepEqual', + stackStartFn: deepEqual + }); + } +}; + +// The non-equivalence assertion tests for any deep inequality. +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + if (isDeepEqual(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'notDeepEqual', + stackStartFn: notDeepEqual + }); + } +}; +/* eslint-enable */ + +assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + if (!isDeepStrictEqual(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'deepStrictEqual', + stackStartFn: deepStrictEqual + }); + } +}; +assert.notDeepStrictEqual = notDeepStrictEqual; +function notDeepStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + if (isDeepStrictEqual(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'notDeepStrictEqual', + stackStartFn: notDeepStrictEqual + }); + } +} +assert.strictEqual = function strictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (!objectIs(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'strictEqual', + stackStartFn: strictEqual + }); + } +}; +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (arguments.length < 2) { + throw new ERR_MISSING_ARGS('actual', 'expected'); + } + if (objectIs(actual, expected)) { + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: 'notStrictEqual', + stackStartFn: notStrictEqual + }); + } +}; +var Comparison = /*#__PURE__*/_createClass(function Comparison(obj, keys, actual) { + var _this = this; + _classCallCheck(this, Comparison); + keys.forEach(function (key) { + if (key in obj) { + if (actual !== undefined && typeof actual[key] === 'string' && isRegExp(obj[key]) && RegExpPrototypeTest(obj[key], actual[key])) { + _this[key] = actual[key]; + } else { + _this[key] = obj[key]; + } + } + }); +}); +function compareExceptionKey(actual, expected, key, message, keys, fn) { + if (!(key in actual) || !isDeepStrictEqual(actual[key], expected[key])) { + if (!message) { + // Create placeholder objects to create a nice output. + var a = new Comparison(actual, keys); + var b = new Comparison(expected, keys, actual); + var err = new AssertionError({ + actual: a, + expected: b, + operator: 'deepStrictEqual', + stackStartFn: fn + }); + err.actual = actual; + err.expected = expected; + err.operator = fn.name; + throw err; + } + innerFail({ + actual: actual, + expected: expected, + message: message, + operator: fn.name, + stackStartFn: fn + }); + } +} +function expectedException(actual, expected, msg, fn) { + if (typeof expected !== 'function') { + if (isRegExp(expected)) return RegExpPrototypeTest(expected, actual); + // assert.doesNotThrow does not accept objects. + if (arguments.length === 2) { + throw new ERR_INVALID_ARG_TYPE('expected', ['Function', 'RegExp'], expected); + } + + // Handle primitives properly. + if (_typeof(actual) !== 'object' || actual === null) { + var err = new AssertionError({ + actual: actual, + expected: expected, + message: msg, + operator: 'deepStrictEqual', + stackStartFn: fn + }); + err.operator = fn.name; + throw err; + } + var keys = Object.keys(expected); + // Special handle errors to make sure the name and the message are compared + // as well. + if (expected instanceof Error) { + keys.push('name', 'message'); + } else if (keys.length === 0) { + throw new ERR_INVALID_ARG_VALUE('error', expected, 'may not be an empty object'); + } + if (isDeepEqual === undefined) lazyLoadComparison(); + keys.forEach(function (key) { + if (typeof actual[key] === 'string' && isRegExp(expected[key]) && RegExpPrototypeTest(expected[key], actual[key])) { + return; + } + compareExceptionKey(actual, expected, key, msg, keys, fn); + }); + return true; + } + // Guard instanceof against arrow functions as they don't have a prototype. + if (expected.prototype !== undefined && actual instanceof expected) { + return true; + } + if (Error.isPrototypeOf(expected)) { + return false; + } + return expected.call({}, actual) === true; +} +function getActual(fn) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', 'Function', fn); + } + try { + fn(); + } catch (e) { + return e; + } + return NO_EXCEPTION_SENTINEL; +} +function checkIsPromise(obj) { + // Accept native ES6 promises and promises that are implemented in a similar + // way. Do not accept thenables that use a function as `obj` and that have no + // `catch` handler. + + // TODO: thenables are checked up until they have the correct methods, + // but according to documentation, the `then` method should receive + // the `fulfill` and `reject` arguments as well or it may be never resolved. + + return isPromise(obj) || obj !== null && _typeof(obj) === 'object' && typeof obj.then === 'function' && typeof obj.catch === 'function'; +} +function waitForActual(promiseFn) { + return Promise.resolve().then(function () { + var resultPromise; + if (typeof promiseFn === 'function') { + // Return a rejected promise if `promiseFn` throws synchronously. + resultPromise = promiseFn(); + // Fail in case no promise is returned. + if (!checkIsPromise(resultPromise)) { + throw new ERR_INVALID_RETURN_VALUE('instance of Promise', 'promiseFn', resultPromise); + } + } else if (checkIsPromise(promiseFn)) { + resultPromise = promiseFn; + } else { + throw new ERR_INVALID_ARG_TYPE('promiseFn', ['Function', 'Promise'], promiseFn); + } + return Promise.resolve().then(function () { + return resultPromise; + }).then(function () { + return NO_EXCEPTION_SENTINEL; + }).catch(function (e) { + return e; + }); + }); +} +function expectsError(stackStartFn, actual, error, message) { + if (typeof error === 'string') { + if (arguments.length === 4) { + throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error); + } + if (_typeof(actual) === 'object' && actual !== null) { + if (actual.message === error) { + throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error message \"".concat(actual.message, "\" is identical to the message.")); + } + } else if (actual === error) { + throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error \"".concat(actual, "\" is identical to the message.")); + } + message = error; + error = undefined; + } else if (error != null && _typeof(error) !== 'object' && typeof error !== 'function') { + throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error); + } + if (actual === NO_EXCEPTION_SENTINEL) { + var details = ''; + if (error && error.name) { + details += " (".concat(error.name, ")"); + } + details += message ? ": ".concat(message) : '.'; + var fnType = stackStartFn.name === 'rejects' ? 'rejection' : 'exception'; + innerFail({ + actual: undefined, + expected: error, + operator: stackStartFn.name, + message: "Missing expected ".concat(fnType).concat(details), + stackStartFn: stackStartFn + }); + } + if (error && !expectedException(actual, error, message, stackStartFn)) { + throw actual; + } +} +function expectsNoError(stackStartFn, actual, error, message) { + if (actual === NO_EXCEPTION_SENTINEL) return; + if (typeof error === 'string') { + message = error; + error = undefined; + } + if (!error || expectedException(actual, error)) { + var details = message ? ": ".concat(message) : '.'; + var fnType = stackStartFn.name === 'doesNotReject' ? 'rejection' : 'exception'; + innerFail({ + actual: actual, + expected: error, + operator: stackStartFn.name, + message: "Got unwanted ".concat(fnType).concat(details, "\n") + "Actual message: \"".concat(actual && actual.message, "\""), + stackStartFn: stackStartFn + }); + } + throw actual; +} +assert.throws = function throws(promiseFn) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + expectsError.apply(void 0, [throws, getActual(promiseFn)].concat(args)); +}; +assert.rejects = function rejects(promiseFn) { + for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + args[_key3 - 1] = arguments[_key3]; + } + return waitForActual(promiseFn).then(function (result) { + return expectsError.apply(void 0, [rejects, result].concat(args)); + }); +}; +assert.doesNotThrow = function doesNotThrow(fn) { + for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + expectsNoError.apply(void 0, [doesNotThrow, getActual(fn)].concat(args)); +}; +assert.doesNotReject = function doesNotReject(fn) { + for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { + args[_key5 - 1] = arguments[_key5]; + } + return waitForActual(fn).then(function (result) { + return expectsNoError.apply(void 0, [doesNotReject, result].concat(args)); + }); +}; +assert.ifError = function ifError(err) { + if (err !== null && err !== undefined) { + var message = 'ifError got unwanted exception: '; + if (_typeof(err) === 'object' && typeof err.message === 'string') { + if (err.message.length === 0 && err.constructor) { + message += err.constructor.name; + } else { + message += err.message; + } + } else { + message += inspect(err); + } + var newErr = new AssertionError({ + actual: err, + expected: null, + operator: 'ifError', + message: message, + stackStartFn: ifError + }); + + // Make sure we actually have a stack trace! + var origStack = err.stack; + if (typeof origStack === 'string') { + // This will remove any duplicated frames from the error frames taken + // from within `ifError` and add the original error frames to the newly + // created ones. + var tmp2 = origStack.split('\n'); + tmp2.shift(); + // Filter all frames existing in err.stack. + var tmp1 = newErr.stack.split('\n'); + for (var i = 0; i < tmp2.length; i++) { + // Find the first occurrence of the frame. + var pos = tmp1.indexOf(tmp2[i]); + if (pos !== -1) { + // Only keep new frames. + tmp1 = tmp1.slice(0, pos); + break; + } + } + newErr.stack = "".concat(tmp1.join('\n'), "\n").concat(tmp2.join('\n')); + } + throw newErr; + } +}; + +// Currently in sync with Node.js lib/assert.js +// https://github.com/nodejs/node/commit/2a871df3dfb8ea663ef5e1f8f62701ec51384ecb +function internalMatch(string, regexp, message, fn, fnName) { + if (!isRegExp(regexp)) { + throw new ERR_INVALID_ARG_TYPE('regexp', 'RegExp', regexp); + } + var match = fnName === 'match'; + if (typeof string !== 'string' || RegExpPrototypeTest(regexp, string) !== match) { + if (message instanceof Error) { + throw message; + } + var generatedMessage = !message; + + // 'The input was expected to not match the regular expression ' + + message = message || (typeof string !== 'string' ? 'The "string" argument must be of type string. Received type ' + "".concat(_typeof(string), " (").concat(inspect(string), ")") : (match ? 'The input did not match the regular expression ' : 'The input was expected to not match the regular expression ') + "".concat(inspect(regexp), ". Input:\n\n").concat(inspect(string), "\n")); + var err = new AssertionError({ + actual: string, + expected: regexp, + message: message, + operator: fnName, + stackStartFn: fn + }); + err.generatedMessage = generatedMessage; + throw err; + } +} +assert.match = function match(string, regexp, message) { + internalMatch(string, regexp, message, match, 'match'); +}; +assert.doesNotMatch = function doesNotMatch(string, regexp, message) { + internalMatch(string, regexp, message, doesNotMatch, 'doesNotMatch'); +}; + +// Expose a strict only variant of assert +function strict() { + for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + args[_key6] = arguments[_key6]; + } + innerOk.apply(void 0, [strict, args.length].concat(args)); +} +assert.strict = objectAssign(strict, assert, { + equal: assert.strictEqual, + deepEqual: assert.deepStrictEqual, + notEqual: assert.notStrictEqual, + notDeepEqual: assert.notDeepStrictEqual +}); +assert.strict.strict = assert.strict; + +/***/ }), + +/***/ 3918: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(5606); +// Currently in sync with Node.js lib/internal/assert/assertion_error.js +// https://github.com/nodejs/node/commit/0817840f775032169ddd70c85ac059f18ffcc81c + + + +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +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); } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } +function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +var _require = __webpack_require__(537), + inspect = _require.inspect; +var _require2 = __webpack_require__(9597), + ERR_INVALID_ARG_TYPE = _require2.codes.ERR_INVALID_ARG_TYPE; + +// 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/repeat +function repeat(str, count) { + count = Math.floor(count); + if (str.length == 0 || count == 0) return ''; + var maxCount = str.length * count; + count = Math.floor(Math.log(count) / Math.log(2)); + while (count) { + str += str; + count--; + } + str += str.substring(0, maxCount - str.length); + return str; +} +var blue = ''; +var green = ''; +var red = ''; +var white = ''; +var kReadableOperator = { + deepStrictEqual: 'Expected values to be strictly deep-equal:', + strictEqual: 'Expected values to be strictly equal:', + strictEqualObject: 'Expected "actual" to be reference-equal to "expected":', + deepEqual: 'Expected values to be loosely deep-equal:', + equal: 'Expected values to be loosely equal:', + notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:', + notStrictEqual: 'Expected "actual" to be strictly unequal to:', + notStrictEqualObject: 'Expected "actual" not to be reference-equal to "expected":', + notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:', + notEqual: 'Expected "actual" to be loosely unequal to:', + notIdentical: 'Values identical but not reference-equal:' +}; + +// Comparing short primitives should just show === / !== instead of using the +// diff. +var kMaxShortLength = 10; +function copyError(source) { + var keys = Object.keys(source); + var target = Object.create(Object.getPrototypeOf(source)); + keys.forEach(function (key) { + target[key] = source[key]; + }); + Object.defineProperty(target, 'message', { + value: source.message + }); + return target; +} +function inspectValue(val) { + // The util.inspect default values could be changed. This makes sure the + // error messages contain the necessary information nevertheless. + return inspect(val, { + compact: false, + customInspect: false, + depth: 1000, + maxArrayLength: Infinity, + // Assert compares only enumerable properties (with a few exceptions). + showHidden: false, + // Having a long line as error is better than wrapping the line for + // comparison for now. + // TODO(BridgeAR): `breakLength` should be limited as soon as soon as we + // have meta information about the inspected properties (i.e., know where + // in what line the property starts and ends). + breakLength: Infinity, + // Assert does not detect proxies currently. + showProxy: false, + sorted: true, + // Inspect getters as we also check them when comparing entries. + getters: true + }); +} +function createErrDiff(actual, expected, operator) { + var other = ''; + var res = ''; + var lastPos = 0; + var end = ''; + var skipped = false; + var actualInspected = inspectValue(actual); + var actualLines = actualInspected.split('\n'); + var expectedLines = inspectValue(expected).split('\n'); + var i = 0; + var indicator = ''; + + // In case both values are objects explicitly mark them as not reference equal + // for the `strictEqual` operator. + if (operator === 'strictEqual' && _typeof(actual) === 'object' && _typeof(expected) === 'object' && actual !== null && expected !== null) { + operator = 'strictEqualObject'; + } + + // If "actual" and "expected" fit on a single line and they are not strictly + // equal, check further special handling. + if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) { + var inputLength = actualLines[0].length + expectedLines[0].length; + // If the character length of "actual" and "expected" together is less than + // kMaxShortLength and if neither is an object and at least one of them is + // not `zero`, use the strict equal comparison to visualize the output. + if (inputLength <= kMaxShortLength) { + if ((_typeof(actual) !== 'object' || actual === null) && (_typeof(expected) !== 'object' || expected === null) && (actual !== 0 || expected !== 0)) { + // -0 === +0 + return "".concat(kReadableOperator[operator], "\n\n") + "".concat(actualLines[0], " !== ").concat(expectedLines[0], "\n"); + } + } else if (operator !== 'strictEqualObject') { + // If the stderr is a tty and the input length is lower than the current + // columns per line, add a mismatch indicator below the output. If it is + // not a tty, use a default value of 80 characters. + var maxLength = process.stderr && process.stderr.isTTY ? process.stderr.columns : 80; + if (inputLength < maxLength) { + while (actualLines[0][i] === expectedLines[0][i]) { + i++; + } + // Ignore the first characters. + if (i > 2) { + // Add position indicator for the first mismatch in case it is a + // single line and the input length is less than the column length. + indicator = "\n ".concat(repeat(' ', i), "^"); + i = 0; + } + } + } + } + + // Remove all ending lines that match (this optimizes the output for + // readability by reducing the number of total changed lines). + var a = actualLines[actualLines.length - 1]; + var b = expectedLines[expectedLines.length - 1]; + while (a === b) { + if (i++ < 2) { + end = "\n ".concat(a).concat(end); + } else { + other = a; + } + actualLines.pop(); + expectedLines.pop(); + if (actualLines.length === 0 || expectedLines.length === 0) break; + a = actualLines[actualLines.length - 1]; + b = expectedLines[expectedLines.length - 1]; + } + var maxLines = Math.max(actualLines.length, expectedLines.length); + // Strict equal with identical objects that are not identical by reference. + // E.g., assert.deepStrictEqual({ a: Symbol() }, { a: Symbol() }) + if (maxLines === 0) { + // We have to get the result again. The lines were all removed before. + var _actualLines = actualInspected.split('\n'); + + // Only remove lines in case it makes sense to collapse those. + // TODO: Accept env to always show the full error. + if (_actualLines.length > 30) { + _actualLines[26] = "".concat(blue, "...").concat(white); + while (_actualLines.length > 27) { + _actualLines.pop(); + } + } + return "".concat(kReadableOperator.notIdentical, "\n\n").concat(_actualLines.join('\n'), "\n"); + } + if (i > 3) { + end = "\n".concat(blue, "...").concat(white).concat(end); + skipped = true; + } + if (other !== '') { + end = "\n ".concat(other).concat(end); + other = ''; + } + var printedLines = 0; + var msg = kReadableOperator[operator] + "\n".concat(green, "+ actual").concat(white, " ").concat(red, "- expected").concat(white); + var skippedMsg = " ".concat(blue, "...").concat(white, " Lines skipped"); + for (i = 0; i < maxLines; i++) { + // Only extra expected lines exist + var cur = i - lastPos; + if (actualLines.length < i + 1) { + // If the last diverging line is more than one line above and the + // current line is at least line three, add some of the former lines and + // also add dots to indicate skipped entries. + if (cur > 1 && i > 2) { + if (cur > 4) { + res += "\n".concat(blue, "...").concat(white); + skipped = true; + } else if (cur > 3) { + res += "\n ".concat(expectedLines[i - 2]); + printedLines++; + } + res += "\n ".concat(expectedLines[i - 1]); + printedLines++; + } + // Mark the current line as the last diverging one. + lastPos = i; + // Add the expected line to the cache. + other += "\n".concat(red, "-").concat(white, " ").concat(expectedLines[i]); + printedLines++; + // Only extra actual lines exist + } else if (expectedLines.length < i + 1) { + // If the last diverging line is more than one line above and the + // current line is at least line three, add some of the former lines and + // also add dots to indicate skipped entries. + if (cur > 1 && i > 2) { + if (cur > 4) { + res += "\n".concat(blue, "...").concat(white); + skipped = true; + } else if (cur > 3) { + res += "\n ".concat(actualLines[i - 2]); + printedLines++; + } + res += "\n ".concat(actualLines[i - 1]); + printedLines++; + } + // Mark the current line as the last diverging one. + lastPos = i; + // Add the actual line to the result. + res += "\n".concat(green, "+").concat(white, " ").concat(actualLines[i]); + printedLines++; + // Lines diverge + } else { + var expectedLine = expectedLines[i]; + var actualLine = actualLines[i]; + // If the lines diverge, specifically check for lines that only diverge by + // a trailing comma. In that case it is actually identical and we should + // mark it as such. + var divergingLines = actualLine !== expectedLine && (!endsWith(actualLine, ',') || actualLine.slice(0, -1) !== expectedLine); + // If the expected line has a trailing comma but is otherwise identical, + // add a comma at the end of the actual line. Otherwise the output could + // look weird as in: + // + // [ + // 1 // No comma at the end! + // + 2 + // ] + // + if (divergingLines && endsWith(expectedLine, ',') && expectedLine.slice(0, -1) === actualLine) { + divergingLines = false; + actualLine += ','; + } + if (divergingLines) { + // If the last diverging line is more than one line above and the + // current line is at least line three, add some of the former lines and + // also add dots to indicate skipped entries. + if (cur > 1 && i > 2) { + if (cur > 4) { + res += "\n".concat(blue, "...").concat(white); + skipped = true; + } else if (cur > 3) { + res += "\n ".concat(actualLines[i - 2]); + printedLines++; + } + res += "\n ".concat(actualLines[i - 1]); + printedLines++; + } + // Mark the current line as the last diverging one. + lastPos = i; + // Add the actual line to the result and cache the expected diverging + // line so consecutive diverging lines show up as +++--- and not +-+-+-. + res += "\n".concat(green, "+").concat(white, " ").concat(actualLine); + other += "\n".concat(red, "-").concat(white, " ").concat(expectedLine); + printedLines += 2; + // Lines are identical + } else { + // Add all cached information to the result before adding other things + // and reset the cache. + res += other; + other = ''; + // If the last diverging line is exactly one line above or if it is the + // very first line, add the line to the result. + if (cur === 1 || i === 0) { + res += "\n ".concat(actualLine); + printedLines++; + } + } + } + // Inspected object to big (Show ~20 rows max) + if (printedLines > 20 && i < maxLines - 2) { + return "".concat(msg).concat(skippedMsg, "\n").concat(res, "\n").concat(blue, "...").concat(white).concat(other, "\n") + "".concat(blue, "...").concat(white); + } + } + return "".concat(msg).concat(skipped ? skippedMsg : '', "\n").concat(res).concat(other).concat(end).concat(indicator); +} +var AssertionError = /*#__PURE__*/function (_Error, _inspect$custom) { + _inherits(AssertionError, _Error); + var _super = _createSuper(AssertionError); + function AssertionError(options) { + var _this; + _classCallCheck(this, AssertionError); + if (_typeof(options) !== 'object' || options === null) { + throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); + } + var message = options.message, + operator = options.operator, + stackStartFn = options.stackStartFn; + var actual = options.actual, + expected = options.expected; + var limit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + if (message != null) { + _this = _super.call(this, String(message)); + } else { + if (process.stderr && process.stderr.isTTY) { + // Reset on each call to make sure we handle dynamically set environment + // variables correct. + if (process.stderr && process.stderr.getColorDepth && process.stderr.getColorDepth() !== 1) { + blue = "\x1B[34m"; + green = "\x1B[32m"; + white = "\x1B[39m"; + red = "\x1B[31m"; + } else { + blue = ''; + green = ''; + white = ''; + red = ''; + } + } + // Prevent the error stack from being visible by duplicating the error + // in a very close way to the original in case both sides are actually + // instances of Error. + if (_typeof(actual) === 'object' && actual !== null && _typeof(expected) === 'object' && expected !== null && 'stack' in actual && actual instanceof Error && 'stack' in expected && expected instanceof Error) { + actual = copyError(actual); + expected = copyError(expected); + } + if (operator === 'deepStrictEqual' || operator === 'strictEqual') { + _this = _super.call(this, createErrDiff(actual, expected, operator)); + } else if (operator === 'notDeepStrictEqual' || operator === 'notStrictEqual') { + // In case the objects are equal but the operator requires unequal, show + // the first object and say A equals B + var base = kReadableOperator[operator]; + var res = inspectValue(actual).split('\n'); + + // In case "actual" is an object, it should not be reference equal. + if (operator === 'notStrictEqual' && _typeof(actual) === 'object' && actual !== null) { + base = kReadableOperator.notStrictEqualObject; + } + + // Only remove lines in case it makes sense to collapse those. + // TODO: Accept env to always show the full error. + if (res.length > 30) { + res[26] = "".concat(blue, "...").concat(white); + while (res.length > 27) { + res.pop(); + } + } + + // Only print a single input. + if (res.length === 1) { + _this = _super.call(this, "".concat(base, " ").concat(res[0])); + } else { + _this = _super.call(this, "".concat(base, "\n\n").concat(res.join('\n'), "\n")); + } + } else { + var _res = inspectValue(actual); + var other = ''; + var knownOperators = kReadableOperator[operator]; + if (operator === 'notDeepEqual' || operator === 'notEqual') { + _res = "".concat(kReadableOperator[operator], "\n\n").concat(_res); + if (_res.length > 1024) { + _res = "".concat(_res.slice(0, 1021), "..."); + } + } else { + other = "".concat(inspectValue(expected)); + if (_res.length > 512) { + _res = "".concat(_res.slice(0, 509), "..."); + } + if (other.length > 512) { + other = "".concat(other.slice(0, 509), "..."); + } + if (operator === 'deepEqual' || operator === 'equal') { + _res = "".concat(knownOperators, "\n\n").concat(_res, "\n\nshould equal\n\n"); + } else { + other = " ".concat(operator, " ").concat(other); + } + } + _this = _super.call(this, "".concat(_res).concat(other)); + } + } + Error.stackTraceLimit = limit; + _this.generatedMessage = !message; + Object.defineProperty(_assertThisInitialized(_this), 'name', { + value: 'AssertionError [ERR_ASSERTION]', + enumerable: false, + writable: true, + configurable: true + }); + _this.code = 'ERR_ASSERTION'; + _this.actual = actual; + _this.expected = expected; + _this.operator = operator; + if (Error.captureStackTrace) { + // eslint-disable-next-line no-restricted-syntax + Error.captureStackTrace(_assertThisInitialized(_this), stackStartFn); + } + // Create error message including the error code in the name. + _this.stack; + // Reset the name. + _this.name = 'AssertionError'; + return _possibleConstructorReturn(_this); + } + _createClass(AssertionError, [{ + key: "toString", + value: function toString() { + return "".concat(this.name, " [").concat(this.code, "]: ").concat(this.message); + } + }, { + key: _inspect$custom, + value: function value(recurseTimes, ctx) { + // This limits the `actual` and `expected` property default inspection to + // the minimum depth. Otherwise those values would be too verbose compared + // to the actual error message which contains a combined view of these two + // input values. + return inspect(this, _objectSpread(_objectSpread({}, ctx), {}, { + customInspect: false, + depth: 0 + })); + } + }]); + return AssertionError; +}( /*#__PURE__*/_wrapNativeSuper(Error), inspect.custom); +module.exports = AssertionError; + +/***/ }), + +/***/ 9597: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Currently in sync with Node.js lib/internal/errors.js +// https://github.com/nodejs/node/commit/3b044962c48fe313905877a96b5d0894a5404f6f + +/* eslint node-core/documented-errors: "error" */ +/* eslint node-core/alphabetize-errors: "error" */ +/* eslint node-core/prefer-util-format-errors: "error" */ + + + +// The whole point behind this internal module is to allow Node.js to no +// longer be forced to treat every error message change as a semver-major +// change. The NodeError classes here all expose a `code` property whose +// value statically and permanently identifies the error. While the error +// message may change, the code should not. +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +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); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +var codes = {}; + +// Lazy loaded +var assert; +var util; +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) { + _inherits(NodeError, _Base); + var _super = _createSuper(NodeError); + function NodeError(arg1, arg2, arg3) { + var _this; + _classCallCheck(this, NodeError); + _this = _super.call(this, getMessage(arg1, arg2, arg3)); + _this.code = code; + return _this; + } + return _createClass(NodeError); + }(Base); + 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_AMBIGUOUS_ARGUMENT', 'The "%s" argument is ambiguous. %s', TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + if (assert === undefined) assert = __webpack_require__(4148); + assert(typeof name === 'string', "'name' must be a string"); + + // 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')); + } + + // TODO(BridgeAR): Improve the output by showing `null` and similar. + msg += ". Received type ".concat(_typeof(actual)); + return msg; +}, TypeError); +createErrorType('ERR_INVALID_ARG_VALUE', function (name, value) { + var reason = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'is invalid'; + if (util === undefined) util = __webpack_require__(537); + var inspected = util.inspect(value); + if (inspected.length > 128) { + inspected = "".concat(inspected.slice(0, 128), "..."); + } + return "The argument '".concat(name, "' ").concat(reason, ". Received ").concat(inspected); +}, TypeError, RangeError); +createErrorType('ERR_INVALID_RETURN_VALUE', function (input, name, value) { + var type; + if (value && value.constructor && value.constructor.name) { + type = "instance of ".concat(value.constructor.name); + } else { + type = "type ".concat(_typeof(value)); + } + return "Expected ".concat(input, " to be returned from the \"").concat(name, "\"") + " function but got ".concat(type, "."); +}, TypeError); +createErrorType('ERR_MISSING_ARGS', function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (assert === undefined) assert = __webpack_require__(4148); + assert(args.length > 0, 'At least one arg needs to be specified'); + var msg = 'The '; + var len = args.length; + args = args.map(function (a) { + return "\"".concat(a, "\""); + }); + switch (len) { + case 1: + msg += "".concat(args[0], " argument"); + break; + case 2: + msg += "".concat(args[0], " and ").concat(args[1], " arguments"); + break; + default: + msg += args.slice(0, len - 1).join(', '); + msg += ", and ".concat(args[len - 1], " arguments"); + break; + } + return "".concat(msg, " must be specified"); +}, TypeError); +module.exports.codes = codes; + +/***/ }), + +/***/ 2299: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Currently in sync with Node.js lib/internal/util/comparisons.js +// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 + + + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +var regexFlagsSupported = /a/g.flags !== undefined; +var arrayFromSet = function arrayFromSet(set) { + var array = []; + set.forEach(function (value) { + return array.push(value); + }); + return array; +}; +var arrayFromMap = function arrayFromMap(map) { + var array = []; + map.forEach(function (value, key) { + return array.push([key, value]); + }); + return array; +}; +var objectIs = Object.is ? Object.is : __webpack_require__(7653); +var objectGetOwnPropertySymbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols : function () { + return []; +}; +var numberIsNaN = Number.isNaN ? Number.isNaN : __webpack_require__(4133); +function uncurryThis(f) { + return f.call.bind(f); +} +var hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty); +var propertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable); +var objectToString = uncurryThis(Object.prototype.toString); +var _require$types = (__webpack_require__(537).types), + isAnyArrayBuffer = _require$types.isAnyArrayBuffer, + isArrayBufferView = _require$types.isArrayBufferView, + isDate = _require$types.isDate, + isMap = _require$types.isMap, + isRegExp = _require$types.isRegExp, + isSet = _require$types.isSet, + isNativeError = _require$types.isNativeError, + isBoxedPrimitive = _require$types.isBoxedPrimitive, + isNumberObject = _require$types.isNumberObject, + isStringObject = _require$types.isStringObject, + isBooleanObject = _require$types.isBooleanObject, + isBigIntObject = _require$types.isBigIntObject, + isSymbolObject = _require$types.isSymbolObject, + isFloat32Array = _require$types.isFloat32Array, + isFloat64Array = _require$types.isFloat64Array; +function isNonIndex(key) { + if (key.length === 0 || key.length > 10) return true; + for (var i = 0; i < key.length; i++) { + var code = key.charCodeAt(i); + if (code < 48 || code > 57) return true; + } + // The maximum size for an array is 2 ** 32 -1. + return key.length === 10 && key >= Math.pow(2, 32); +} +function getOwnNonIndexProperties(value) { + return Object.keys(value).filter(isNonIndex).concat(objectGetOwnPropertySymbols(value).filter(Object.prototype.propertyIsEnumerable.bind(value))); +} + +// Taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js +// original notice: +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +function compare(a, b) { + if (a === b) { + return 0; + } + var x = a.length; + var y = b.length; + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +} +var ONLY_ENUMERABLE = undefined; +var kStrict = true; +var kLoose = false; +var kNoIterator = 0; +var kIsArray = 1; +var kIsSet = 2; +var kIsMap = 3; + +// Check if they have the same source and flags +function areSimilarRegExps(a, b) { + return regexFlagsSupported ? a.source === b.source && a.flags === b.flags : RegExp.prototype.toString.call(a) === RegExp.prototype.toString.call(b); +} +function areSimilarFloatArrays(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (var offset = 0; offset < a.byteLength; offset++) { + if (a[offset] !== b[offset]) { + return false; + } + } + return true; +} +function areSimilarTypedArrays(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + return compare(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)) === 0; +} +function areEqualArrayBuffers(buf1, buf2) { + return buf1.byteLength === buf2.byteLength && compare(new Uint8Array(buf1), new Uint8Array(buf2)) === 0; +} +function isEqualBoxedPrimitive(val1, val2) { + if (isNumberObject(val1)) { + return isNumberObject(val2) && objectIs(Number.prototype.valueOf.call(val1), Number.prototype.valueOf.call(val2)); + } + if (isStringObject(val1)) { + return isStringObject(val2) && String.prototype.valueOf.call(val1) === String.prototype.valueOf.call(val2); + } + if (isBooleanObject(val1)) { + return isBooleanObject(val2) && Boolean.prototype.valueOf.call(val1) === Boolean.prototype.valueOf.call(val2); + } + if (isBigIntObject(val1)) { + return isBigIntObject(val2) && BigInt.prototype.valueOf.call(val1) === BigInt.prototype.valueOf.call(val2); + } + return isSymbolObject(val2) && Symbol.prototype.valueOf.call(val1) === Symbol.prototype.valueOf.call(val2); +} + +// Notes: Type tags are historical [[Class]] properties that can be set by +// FunctionTemplate::SetClassName() in C++ or Symbol.toStringTag in JS +// and retrieved using Object.prototype.toString.call(obj) in JS +// See https://tc39.github.io/ecma262/#sec-object.prototype.tostring +// for a list of tags pre-defined in the spec. +// There are some unspecified tags in the wild too (e.g. typed array tags). +// Since tags can be altered, they only serve fast failures +// +// Typed arrays and buffers are checked by comparing the content in their +// underlying ArrayBuffer. This optimization requires that it's +// reasonable to interpret their underlying memory in the same way, +// which is checked by comparing their type tags. +// (e.g. a Uint8Array and a Uint16Array with the same memory content +// could still be different because they will be interpreted differently). +// +// For strict comparison, objects should have +// a) The same built-in type tags +// b) The same prototypes. + +function innerDeepEqual(val1, val2, strict, memos) { + // All identical values are equivalent, as determined by ===. + if (val1 === val2) { + if (val1 !== 0) return true; + return strict ? objectIs(val1, val2) : true; + } + + // Check more closely if val1 and val2 are equal. + if (strict) { + if (_typeof(val1) !== 'object') { + return typeof val1 === 'number' && numberIsNaN(val1) && numberIsNaN(val2); + } + if (_typeof(val2) !== 'object' || val1 === null || val2 === null) { + return false; + } + if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) { + return false; + } + } else { + if (val1 === null || _typeof(val1) !== 'object') { + if (val2 === null || _typeof(val2) !== 'object') { + // eslint-disable-next-line eqeqeq + return val1 == val2; + } + return false; + } + if (val2 === null || _typeof(val2) !== 'object') { + return false; + } + } + var val1Tag = objectToString(val1); + var val2Tag = objectToString(val2); + if (val1Tag !== val2Tag) { + return false; + } + if (Array.isArray(val1)) { + // Check for sparse arrays and general fast path + if (val1.length !== val2.length) { + return false; + } + var keys1 = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE); + var keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE); + if (keys1.length !== keys2.length) { + return false; + } + return keyCheck(val1, val2, strict, memos, kIsArray, keys1); + } + // [browserify] This triggers on certain types in IE (Map/Set) so we don't + // wan't to early return out of the rest of the checks. However we can check + // if the second value is one of these values and the first isn't. + if (val1Tag === '[object Object]') { + // return keyCheck(val1, val2, strict, memos, kNoIterator); + if (!isMap(val1) && isMap(val2) || !isSet(val1) && isSet(val2)) { + return false; + } + } + if (isDate(val1)) { + if (!isDate(val2) || Date.prototype.getTime.call(val1) !== Date.prototype.getTime.call(val2)) { + return false; + } + } else if (isRegExp(val1)) { + if (!isRegExp(val2) || !areSimilarRegExps(val1, val2)) { + return false; + } + } else if (isNativeError(val1) || val1 instanceof Error) { + // Do not compare the stack as it might differ even though the error itself + // is otherwise identical. + if (val1.message !== val2.message || val1.name !== val2.name) { + return false; + } + } else if (isArrayBufferView(val1)) { + if (!strict && (isFloat32Array(val1) || isFloat64Array(val1))) { + if (!areSimilarFloatArrays(val1, val2)) { + return false; + } + } else if (!areSimilarTypedArrays(val1, val2)) { + return false; + } + // Buffer.compare returns true, so val1.length === val2.length. If they both + // only contain numeric keys, we don't need to exam further than checking + // the symbols. + var _keys = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE); + var _keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE); + if (_keys.length !== _keys2.length) { + return false; + } + return keyCheck(val1, val2, strict, memos, kNoIterator, _keys); + } else if (isSet(val1)) { + if (!isSet(val2) || val1.size !== val2.size) { + return false; + } + return keyCheck(val1, val2, strict, memos, kIsSet); + } else if (isMap(val1)) { + if (!isMap(val2) || val1.size !== val2.size) { + return false; + } + return keyCheck(val1, val2, strict, memos, kIsMap); + } else if (isAnyArrayBuffer(val1)) { + if (!areEqualArrayBuffers(val1, val2)) { + return false; + } + } else if (isBoxedPrimitive(val1) && !isEqualBoxedPrimitive(val1, val2)) { + return false; + } + return keyCheck(val1, val2, strict, memos, kNoIterator); +} +function getEnumerables(val, keys) { + return keys.filter(function (k) { + return propertyIsEnumerable(val, k); + }); +} +function keyCheck(val1, val2, strict, memos, iterationType, aKeys) { + // For all remaining Object pairs, including Array, objects and Maps, + // equivalence is determined by having: + // a) The same number of owned enumerable properties + // b) The same set of keys/indexes (although not necessarily the same order) + // c) Equivalent values for every corresponding key/index + // d) For Sets and Maps, equal contents + // Note: this accounts for both named and indexed properties on Arrays. + if (arguments.length === 5) { + aKeys = Object.keys(val1); + var bKeys = Object.keys(val2); + + // The pair must have the same number of owned properties. + if (aKeys.length !== bKeys.length) { + return false; + } + } + + // Cheap key test + var i = 0; + for (; i < aKeys.length; i++) { + if (!hasOwnProperty(val2, aKeys[i])) { + return false; + } + } + if (strict && arguments.length === 5) { + var symbolKeysA = objectGetOwnPropertySymbols(val1); + if (symbolKeysA.length !== 0) { + var count = 0; + for (i = 0; i < symbolKeysA.length; i++) { + var key = symbolKeysA[i]; + if (propertyIsEnumerable(val1, key)) { + if (!propertyIsEnumerable(val2, key)) { + return false; + } + aKeys.push(key); + count++; + } else if (propertyIsEnumerable(val2, key)) { + return false; + } + } + var symbolKeysB = objectGetOwnPropertySymbols(val2); + if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count) { + return false; + } + } else { + var _symbolKeysB = objectGetOwnPropertySymbols(val2); + if (_symbolKeysB.length !== 0 && getEnumerables(val2, _symbolKeysB).length !== 0) { + return false; + } + } + } + if (aKeys.length === 0 && (iterationType === kNoIterator || iterationType === kIsArray && val1.length === 0 || val1.size === 0)) { + return true; + } + + // Use memos to handle cycles. + if (memos === undefined) { + memos = { + val1: new Map(), + val2: new Map(), + position: 0 + }; + } else { + // We prevent up to two map.has(x) calls by directly retrieving the value + // and checking for undefined. The map can only contain numbers, so it is + // safe to check for undefined only. + var val2MemoA = memos.val1.get(val1); + if (val2MemoA !== undefined) { + var val2MemoB = memos.val2.get(val2); + if (val2MemoB !== undefined) { + return val2MemoA === val2MemoB; + } + } + memos.position++; + } + memos.val1.set(val1, memos.position); + memos.val2.set(val2, memos.position); + var areEq = objEquiv(val1, val2, strict, aKeys, memos, iterationType); + memos.val1.delete(val1); + memos.val2.delete(val2); + return areEq; +} +function setHasEqualElement(set, val1, strict, memo) { + // Go looking. + var setValues = arrayFromSet(set); + for (var i = 0; i < setValues.length; i++) { + var val2 = setValues[i]; + if (innerDeepEqual(val1, val2, strict, memo)) { + // Remove the matching element to make sure we do not check that again. + set.delete(val2); + return true; + } + } + return false; +} + +// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using +// Sadly it is not possible to detect corresponding values properly in case the +// type is a string, number, bigint or boolean. The reason is that those values +// can match lots of different string values (e.g., 1n == '+00001'). +function findLooseMatchingPrimitives(prim) { + switch (_typeof(prim)) { + case 'undefined': + return null; + case 'object': + // Only pass in null as object! + return undefined; + case 'symbol': + return false; + case 'string': + prim = +prim; + // Loose equal entries exist only if the string is possible to convert to + // a regular number and not NaN. + // Fall through + case 'number': + if (numberIsNaN(prim)) { + return false; + } + } + return true; +} +function setMightHaveLoosePrim(a, b, prim) { + var altValue = findLooseMatchingPrimitives(prim); + if (altValue != null) return altValue; + return b.has(altValue) && !a.has(altValue); +} +function mapMightHaveLoosePrim(a, b, prim, item, memo) { + var altValue = findLooseMatchingPrimitives(prim); + if (altValue != null) { + return altValue; + } + var curB = b.get(altValue); + if (curB === undefined && !b.has(altValue) || !innerDeepEqual(item, curB, false, memo)) { + return false; + } + return !a.has(altValue) && innerDeepEqual(item, curB, false, memo); +} +function setEquiv(a, b, strict, memo) { + // This is a lazily initiated Set of entries which have to be compared + // pairwise. + var set = null; + var aValues = arrayFromSet(a); + for (var i = 0; i < aValues.length; i++) { + var val = aValues[i]; + // Note: Checking for the objects first improves the performance for object + // heavy sets but it is a minor slow down for primitives. As they are fast + // to check this improves the worst case scenario instead. + if (_typeof(val) === 'object' && val !== null) { + if (set === null) { + set = new Set(); + } + // If the specified value doesn't exist in the second set its an not null + // object (or non strict only: a not matching primitive) we'll need to go + // hunting for something thats deep-(strict-)equal to it. To make this + // O(n log n) complexity we have to copy these values in a new set first. + set.add(val); + } else if (!b.has(val)) { + if (strict) return false; + + // Fast path to detect missing string, symbol, undefined and null values. + if (!setMightHaveLoosePrim(a, b, val)) { + return false; + } + if (set === null) { + set = new Set(); + } + set.add(val); + } + } + if (set !== null) { + var bValues = arrayFromSet(b); + for (var _i = 0; _i < bValues.length; _i++) { + var _val = bValues[_i]; + // We have to check if a primitive value is already + // matching and only if it's not, go hunting for it. + if (_typeof(_val) === 'object' && _val !== null) { + if (!setHasEqualElement(set, _val, strict, memo)) return false; + } else if (!strict && !a.has(_val) && !setHasEqualElement(set, _val, strict, memo)) { + return false; + } + } + return set.size === 0; + } + return true; +} +function mapHasEqualEntry(set, map, key1, item1, strict, memo) { + // To be able to handle cases like: + // Map([[{}, 'a'], [{}, 'b']]) vs Map([[{}, 'b'], [{}, 'a']]) + // ... we need to consider *all* matching keys, not just the first we find. + var setValues = arrayFromSet(set); + for (var i = 0; i < setValues.length; i++) { + var key2 = setValues[i]; + if (innerDeepEqual(key1, key2, strict, memo) && innerDeepEqual(item1, map.get(key2), strict, memo)) { + set.delete(key2); + return true; + } + } + return false; +} +function mapEquiv(a, b, strict, memo) { + var set = null; + var aEntries = arrayFromMap(a); + for (var i = 0; i < aEntries.length; i++) { + var _aEntries$i = _slicedToArray(aEntries[i], 2), + key = _aEntries$i[0], + item1 = _aEntries$i[1]; + if (_typeof(key) === 'object' && key !== null) { + if (set === null) { + set = new Set(); + } + set.add(key); + } else { + // By directly retrieving the value we prevent another b.has(key) check in + // almost all possible cases. + var item2 = b.get(key); + if (item2 === undefined && !b.has(key) || !innerDeepEqual(item1, item2, strict, memo)) { + if (strict) return false; + // Fast path to detect missing string, symbol, undefined and null + // keys. + if (!mapMightHaveLoosePrim(a, b, key, item1, memo)) return false; + if (set === null) { + set = new Set(); + } + set.add(key); + } + } + } + if (set !== null) { + var bEntries = arrayFromMap(b); + for (var _i2 = 0; _i2 < bEntries.length; _i2++) { + var _bEntries$_i = _slicedToArray(bEntries[_i2], 2), + _key = _bEntries$_i[0], + item = _bEntries$_i[1]; + if (_typeof(_key) === 'object' && _key !== null) { + if (!mapHasEqualEntry(set, a, _key, item, strict, memo)) return false; + } else if (!strict && (!a.has(_key) || !innerDeepEqual(a.get(_key), item, false, memo)) && !mapHasEqualEntry(set, a, _key, item, false, memo)) { + return false; + } + } + return set.size === 0; + } + return true; +} +function objEquiv(a, b, strict, keys, memos, iterationType) { + // Sets and maps don't have their entries accessible via normal object + // properties. + var i = 0; + if (iterationType === kIsSet) { + if (!setEquiv(a, b, strict, memos)) { + return false; + } + } else if (iterationType === kIsMap) { + if (!mapEquiv(a, b, strict, memos)) { + return false; + } + } else if (iterationType === kIsArray) { + for (; i < a.length; i++) { + if (hasOwnProperty(a, i)) { + if (!hasOwnProperty(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) { + return false; + } + } else if (hasOwnProperty(b, i)) { + return false; + } else { + // Array is sparse. + var keysA = Object.keys(a); + for (; i < keysA.length; i++) { + var key = keysA[i]; + if (!hasOwnProperty(b, key) || !innerDeepEqual(a[key], b[key], strict, memos)) { + return false; + } + } + if (keysA.length !== Object.keys(b).length) { + return false; + } + return true; + } + } + } + + // The pair must have equivalent values for every corresponding key. + // Possibly expensive deep test: + for (i = 0; i < keys.length; i++) { + var _key2 = keys[i]; + if (!innerDeepEqual(a[_key2], b[_key2], strict, memos)) { + return false; + } + } + return true; +} +function isDeepEqual(val1, val2) { + return innerDeepEqual(val1, val2, kLoose); +} +function isDeepStrictEqual(val1, val2) { + return innerDeepEqual(val1, val2, kStrict); +} +module.exports = { + isDeepEqual: isDeepEqual, + isDeepStrictEqual: isDeepStrictEqual +}; + +/***/ }), + +/***/ 3626: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ A: () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8287); +// See https://github.com/stellar/js-xdr/issues/117 + +if (!(buffer__WEBPACK_IMPORTED_MODULE_0__.Buffer.alloc(1).subarray(0, 1) instanceof buffer__WEBPACK_IMPORTED_MODULE_0__.Buffer)) { + buffer__WEBPACK_IMPORTED_MODULE_0__.Buffer.prototype.subarray = function subarray(start, end) { + var result = Uint8Array.prototype.subarray.call(this, start, end); + Object.setPrototypeOf(result, buffer__WEBPACK_IMPORTED_MODULE_0__.Buffer.prototype); + return result; + }; +} +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (buffer__WEBPACK_IMPORTED_MODULE_0__.Buffer); + +/***/ }), + +/***/ 7957: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Account: () => (/* reexport */ Account), + Address: () => (/* reexport */ Address), + Asset: () => (/* reexport */ Asset), + AuthClawbackEnabledFlag: () => (/* reexport */ AuthClawbackEnabledFlag), + AuthImmutableFlag: () => (/* reexport */ AuthImmutableFlag), + AuthRequiredFlag: () => (/* reexport */ AuthRequiredFlag), + AuthRevocableFlag: () => (/* reexport */ AuthRevocableFlag), + BASE_FEE: () => (/* reexport */ BASE_FEE), + Claimant: () => (/* reexport */ Claimant), + Contract: () => (/* reexport */ Contract), + FastSigning: () => (/* reexport */ FastSigning), + FeeBumpTransaction: () => (/* reexport */ FeeBumpTransaction), + Hyper: () => (/* reexport */ xdr.Hyper), + Int128: () => (/* reexport */ Int128), + Int256: () => (/* reexport */ Int256), + Keypair: () => (/* reexport */ Keypair), + LiquidityPoolAsset: () => (/* reexport */ LiquidityPoolAsset), + LiquidityPoolFeeV18: () => (/* reexport */ LiquidityPoolFeeV18), + LiquidityPoolId: () => (/* reexport */ LiquidityPoolId), + Memo: () => (/* reexport */ Memo), + MemoHash: () => (/* reexport */ MemoHash), + MemoID: () => (/* reexport */ MemoID), + MemoNone: () => (/* reexport */ MemoNone), + MemoReturn: () => (/* reexport */ MemoReturn), + MemoText: () => (/* reexport */ MemoText), + MuxedAccount: () => (/* reexport */ MuxedAccount), + Networks: () => (/* reexport */ Networks), + Operation: () => (/* reexport */ Operation), + ScInt: () => (/* reexport */ ScInt), + SignerKey: () => (/* reexport */ SignerKey), + Soroban: () => (/* reexport */ Soroban), + SorobanDataBuilder: () => (/* reexport */ SorobanDataBuilder), + StrKey: () => (/* reexport */ StrKey), + TimeoutInfinite: () => (/* reexport */ TimeoutInfinite), + Transaction: () => (/* reexport */ Transaction), + TransactionBase: () => (/* reexport */ TransactionBase), + TransactionBuilder: () => (/* reexport */ TransactionBuilder), + Uint128: () => (/* reexport */ Uint128), + Uint256: () => (/* reexport */ Uint256), + UnsignedHyper: () => (/* reexport */ xdr.UnsignedHyper), + XdrLargeInt: () => (/* reexport */ XdrLargeInt), + authorizeEntry: () => (/* reexport */ authorizeEntry), + authorizeInvocation: () => (/* reexport */ authorizeInvocation), + buildInvocationTree: () => (/* reexport */ buildInvocationTree), + cereal: () => (/* reexport */ jsxdr), + decodeAddressToMuxedAccount: () => (/* reexport */ decodeAddressToMuxedAccount), + "default": () => (/* binding */ src), + encodeMuxedAccount: () => (/* reexport */ encodeMuxedAccount), + encodeMuxedAccountToAddress: () => (/* reexport */ encodeMuxedAccountToAddress), + extractBaseAddress: () => (/* reexport */ extractBaseAddress), + getLiquidityPoolId: () => (/* reexport */ getLiquidityPoolId), + hash: () => (/* reexport */ hashing_hash), + humanizeEvents: () => (/* reexport */ humanizeEvents), + nativeToScVal: () => (/* reexport */ nativeToScVal), + scValToBigInt: () => (/* reexport */ scValToBigInt), + scValToNative: () => (/* reexport */ scValToNative), + sign: () => (/* reexport */ signing_sign), + verify: () => (/* reexport */ signing_verify), + walkInvocationTree: () => (/* reexport */ walkInvocationTree), + xdr: () => (/* reexport */ src_xdr) +}); + +// EXTERNAL MODULE: ./node_modules/@stellar/js-xdr/dist/xdr.js +var xdr = __webpack_require__(3740); +;// ./src/generated/curr_generated.js +// Automatically generated by xdrgen on 2024-09-12T11:09:00-08:00 +// DO NOT EDIT or your changes may be overwritten + +/* jshint maxstatements:2147483647 */ +/* jshint esnext:true */ + + +var types = xdr.config(function (xdr) { + // Workaround for https://github.com/stellar/xdrgen/issues/152 + // + // The "correct" way would be to replace bare instances of each constant with + // xdr.lookup("..."), but that's more error-prone. + var SCSYMBOL_LIMIT = 32; + var SC_SPEC_DOC_LIMIT = 1024; + + // === xdr source ============================================================ + // + // typedef opaque Value<>; + // + // =========================================================================== + xdr.typedef("Value", xdr.varOpaque()); + + // === xdr source ============================================================ + // + // struct SCPBallot + // { + // uint32 counter; // n + // Value value; // x + // }; + // + // =========================================================================== + xdr.struct("ScpBallot", [["counter", xdr.lookup("Uint32")], ["value", xdr.lookup("Value")]]); + + // === xdr source ============================================================ + // + // enum SCPStatementType + // { + // SCP_ST_PREPARE = 0, + // SCP_ST_CONFIRM = 1, + // SCP_ST_EXTERNALIZE = 2, + // SCP_ST_NOMINATE = 3 + // }; + // + // =========================================================================== + xdr["enum"]("ScpStatementType", { + scpStPrepare: 0, + scpStConfirm: 1, + scpStExternalize: 2, + scpStNominate: 3 + }); + + // === xdr source ============================================================ + // + // struct SCPNomination + // { + // Hash quorumSetHash; // D + // Value votes<>; // X + // Value accepted<>; // Y + // }; + // + // =========================================================================== + xdr.struct("ScpNomination", [["quorumSetHash", xdr.lookup("Hash")], ["votes", xdr.varArray(xdr.lookup("Value"), 2147483647)], ["accepted", xdr.varArray(xdr.lookup("Value"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } + // + // =========================================================================== + xdr.struct("ScpStatementPrepare", [["quorumSetHash", xdr.lookup("Hash")], ["ballot", xdr.lookup("ScpBallot")], ["prepared", xdr.option(xdr.lookup("ScpBallot"))], ["preparedPrime", xdr.option(xdr.lookup("ScpBallot"))], ["nC", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } + // + // =========================================================================== + xdr.struct("ScpStatementConfirm", [["ballot", xdr.lookup("ScpBallot")], ["nPrepared", xdr.lookup("Uint32")], ["nCommit", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")], ["quorumSetHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } + // + // =========================================================================== + xdr.struct("ScpStatementExternalize", [["commit", xdr.lookup("ScpBallot")], ["nH", xdr.lookup("Uint32")], ["commitQuorumSetHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union switch (SCPStatementType type) + // { + // case SCP_ST_PREPARE: + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } prepare; + // case SCP_ST_CONFIRM: + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } confirm; + // case SCP_ST_EXTERNALIZE: + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } externalize; + // case SCP_ST_NOMINATE: + // SCPNomination nominate; + // } + // + // =========================================================================== + xdr.union("ScpStatementPledges", { + switchOn: xdr.lookup("ScpStatementType"), + switchName: "type", + switches: [["scpStPrepare", "prepare"], ["scpStConfirm", "confirm"], ["scpStExternalize", "externalize"], ["scpStNominate", "nominate"]], + arms: { + prepare: xdr.lookup("ScpStatementPrepare"), + confirm: xdr.lookup("ScpStatementConfirm"), + externalize: xdr.lookup("ScpStatementExternalize"), + nominate: xdr.lookup("ScpNomination") + } + }); + + // === xdr source ============================================================ + // + // struct SCPStatement + // { + // NodeID nodeID; // v + // uint64 slotIndex; // i + // + // union switch (SCPStatementType type) + // { + // case SCP_ST_PREPARE: + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } prepare; + // case SCP_ST_CONFIRM: + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } confirm; + // case SCP_ST_EXTERNALIZE: + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } externalize; + // case SCP_ST_NOMINATE: + // SCPNomination nominate; + // } + // pledges; + // }; + // + // =========================================================================== + xdr.struct("ScpStatement", [["nodeId", xdr.lookup("NodeId")], ["slotIndex", xdr.lookup("Uint64")], ["pledges", xdr.lookup("ScpStatementPledges")]]); + + // === xdr source ============================================================ + // + // struct SCPEnvelope + // { + // SCPStatement statement; + // Signature signature; + // }; + // + // =========================================================================== + xdr.struct("ScpEnvelope", [["statement", xdr.lookup("ScpStatement")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // struct SCPQuorumSet + // { + // uint32 threshold; + // NodeID validators<>; + // SCPQuorumSet innerSets<>; + // }; + // + // =========================================================================== + xdr.struct("ScpQuorumSet", [["threshold", xdr.lookup("Uint32")], ["validators", xdr.varArray(xdr.lookup("NodeId"), 2147483647)], ["innerSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)]]); + + // === xdr source ============================================================ + // + // typedef opaque Thresholds[4]; + // + // =========================================================================== + xdr.typedef("Thresholds", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef string string32<32>; + // + // =========================================================================== + xdr.typedef("String32", xdr.string(32)); + + // === xdr source ============================================================ + // + // typedef string string64<64>; + // + // =========================================================================== + xdr.typedef("String64", xdr.string(64)); + + // === xdr source ============================================================ + // + // typedef int64 SequenceNumber; + // + // =========================================================================== + xdr.typedef("SequenceNumber", xdr.lookup("Int64")); + + // === xdr source ============================================================ + // + // typedef opaque DataValue<64>; + // + // =========================================================================== + xdr.typedef("DataValue", xdr.varOpaque(64)); + + // === xdr source ============================================================ + // + // typedef Hash PoolID; + // + // =========================================================================== + xdr.typedef("PoolId", xdr.lookup("Hash")); + + // === xdr source ============================================================ + // + // typedef opaque AssetCode4[4]; + // + // =========================================================================== + xdr.typedef("AssetCode4", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef opaque AssetCode12[12]; + // + // =========================================================================== + xdr.typedef("AssetCode12", xdr.opaque(12)); + + // === xdr source ============================================================ + // + // enum AssetType + // { + // ASSET_TYPE_NATIVE = 0, + // ASSET_TYPE_CREDIT_ALPHANUM4 = 1, + // ASSET_TYPE_CREDIT_ALPHANUM12 = 2, + // ASSET_TYPE_POOL_SHARE = 3 + // }; + // + // =========================================================================== + xdr["enum"]("AssetType", { + assetTypeNative: 0, + assetTypeCreditAlphanum4: 1, + assetTypeCreditAlphanum12: 2, + assetTypePoolShare: 3 + }); + + // === xdr source ============================================================ + // + // union AssetCode switch (AssetType type) + // { + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AssetCode4 assetCode4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AssetCode12 assetCode12; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("AssetCode", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeCreditAlphanum4", "assetCode4"], ["assetTypeCreditAlphanum12", "assetCode12"]], + arms: { + assetCode4: xdr.lookup("AssetCode4"), + assetCode12: xdr.lookup("AssetCode12") + } + }); + + // === xdr source ============================================================ + // + // struct AlphaNum4 + // { + // AssetCode4 assetCode; + // AccountID issuer; + // }; + // + // =========================================================================== + xdr.struct("AlphaNum4", [["assetCode", xdr.lookup("AssetCode4")], ["issuer", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // struct AlphaNum12 + // { + // AssetCode12 assetCode; + // AccountID issuer; + // }; + // + // =========================================================================== + xdr.struct("AlphaNum12", [["assetCode", xdr.lookup("AssetCode12")], ["issuer", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // union Asset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("Asset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12") + } + }); + + // === xdr source ============================================================ + // + // struct Price + // { + // int32 n; // numerator + // int32 d; // denominator + // }; + // + // =========================================================================== + xdr.struct("Price", [["n", xdr.lookup("Int32")], ["d", xdr.lookup("Int32")]]); + + // === xdr source ============================================================ + // + // struct Liabilities + // { + // int64 buying; + // int64 selling; + // }; + // + // =========================================================================== + xdr.struct("Liabilities", [["buying", xdr.lookup("Int64")], ["selling", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum ThresholdIndexes + // { + // THRESHOLD_MASTER_WEIGHT = 0, + // THRESHOLD_LOW = 1, + // THRESHOLD_MED = 2, + // THRESHOLD_HIGH = 3 + // }; + // + // =========================================================================== + xdr["enum"]("ThresholdIndices", { + thresholdMasterWeight: 0, + thresholdLow: 1, + thresholdMed: 2, + thresholdHigh: 3 + }); + + // === xdr source ============================================================ + // + // enum LedgerEntryType + // { + // ACCOUNT = 0, + // TRUSTLINE = 1, + // OFFER = 2, + // DATA = 3, + // CLAIMABLE_BALANCE = 4, + // LIQUIDITY_POOL = 5, + // CONTRACT_DATA = 6, + // CONTRACT_CODE = 7, + // CONFIG_SETTING = 8, + // TTL = 9 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerEntryType", { + account: 0, + trustline: 1, + offer: 2, + data: 3, + claimableBalance: 4, + liquidityPool: 5, + contractData: 6, + contractCode: 7, + configSetting: 8, + ttl: 9 + }); + + // === xdr source ============================================================ + // + // struct Signer + // { + // SignerKey key; + // uint32 weight; // really only need 1 byte + // }; + // + // =========================================================================== + xdr.struct("Signer", [["key", xdr.lookup("SignerKey")], ["weight", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // enum AccountFlags + // { // masks for each flag + // + // // Flags set on issuer accounts + // // TrustLines are created with authorized set to "false" requiring + // // the issuer to set it for each TrustLine + // AUTH_REQUIRED_FLAG = 0x1, + // // If set, the authorized flag in TrustLines can be cleared + // // otherwise, authorization cannot be revoked + // AUTH_REVOCABLE_FLAG = 0x2, + // // Once set, causes all AUTH_* flags to be read-only + // AUTH_IMMUTABLE_FLAG = 0x4, + // // Trustlines are created with clawback enabled set to "true", + // // and claimable balances created from those trustlines are created + // // with clawback enabled set to "true" + // AUTH_CLAWBACK_ENABLED_FLAG = 0x8 + // }; + // + // =========================================================================== + xdr["enum"]("AccountFlags", { + authRequiredFlag: 1, + authRevocableFlag: 2, + authImmutableFlag: 4, + authClawbackEnabledFlag: 8 + }); + + // === xdr source ============================================================ + // + // const MASK_ACCOUNT_FLAGS = 0x7; + // + // =========================================================================== + xdr["const"]("MASK_ACCOUNT_FLAGS", 0x7); + + // === xdr source ============================================================ + // + // const MASK_ACCOUNT_FLAGS_V17 = 0xF; + // + // =========================================================================== + xdr["const"]("MASK_ACCOUNT_FLAGS_V17", 0xF); + + // === xdr source ============================================================ + // + // const MAX_SIGNERS = 20; + // + // =========================================================================== + xdr["const"]("MAX_SIGNERS", 20); + + // === xdr source ============================================================ + // + // typedef AccountID* SponsorshipDescriptor; + // + // =========================================================================== + xdr.typedef("SponsorshipDescriptor", xdr.option(xdr.lookup("AccountId"))); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV3 + // { + // // We can use this to add more fields, or because it is first, to + // // change AccountEntryExtensionV3 into a union. + // ExtensionPoint ext; + // + // // Ledger number at which `seqNum` took on its present value. + // uint32 seqLedger; + // + // // Time at which `seqNum` took on its present value. + // TimePoint seqTime; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV3", [["ext", xdr.lookup("ExtensionPoint")], ["seqLedger", xdr.lookup("Uint32")], ["seqTime", xdr.lookup("TimePoint")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 3: + // AccountEntryExtensionV3 v3; + // } + // + // =========================================================================== + xdr.union("AccountEntryExtensionV2Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [3, "v3"]], + arms: { + v3: xdr.lookup("AccountEntryExtensionV3") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV2 + // { + // uint32 numSponsored; + // uint32 numSponsoring; + // SponsorshipDescriptor signerSponsoringIDs; + // + // union switch (int v) + // { + // case 0: + // void; + // case 3: + // AccountEntryExtensionV3 v3; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV2", [["numSponsored", xdr.lookup("Uint32")], ["numSponsoring", xdr.lookup("Uint32")], ["signerSponsoringIDs", xdr.varArray(xdr.lookup("SponsorshipDescriptor"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExtensionV2Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // AccountEntryExtensionV2 v2; + // } + // + // =========================================================================== + xdr.union("AccountEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [2, "v2"]], + arms: { + v2: xdr.lookup("AccountEntryExtensionV2") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV1 + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // AccountEntryExtensionV2 v2; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("AccountEntryExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // AccountEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("AccountEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("AccountEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntry + // { + // AccountID accountID; // master public key for this account + // int64 balance; // in stroops + // SequenceNumber seqNum; // last sequence number used for this account + // uint32 numSubEntries; // number of sub-entries this account has + // // drives the reserve + // AccountID* inflationDest; // Account to vote for during inflation + // uint32 flags; // see AccountFlags + // + // string32 homeDomain; // can be used for reverse federation and memo lookup + // + // // fields used for signatures + // // thresholds stores unsigned bytes: [weight of master|low|medium|high] + // Thresholds thresholds; + // + // Signer signers; // possible signers for this account + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // AccountEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntry", [["accountId", xdr.lookup("AccountId")], ["balance", xdr.lookup("Int64")], ["seqNum", xdr.lookup("SequenceNumber")], ["numSubEntries", xdr.lookup("Uint32")], ["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["flags", xdr.lookup("Uint32")], ["homeDomain", xdr.lookup("String32")], ["thresholds", xdr.lookup("Thresholds")], ["signers", xdr.varArray(xdr.lookup("Signer"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExt")]]); + + // === xdr source ============================================================ + // + // enum TrustLineFlags + // { + // // issuer has authorized account to perform transactions with its credit + // AUTHORIZED_FLAG = 1, + // // issuer has authorized account to maintain and reduce liabilities for its + // // credit + // AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG = 2, + // // issuer has specified that it may clawback its credit, and that claimable + // // balances created with its credit may also be clawed back + // TRUSTLINE_CLAWBACK_ENABLED_FLAG = 4 + // }; + // + // =========================================================================== + xdr["enum"]("TrustLineFlags", { + authorizedFlag: 1, + authorizedToMaintainLiabilitiesFlag: 2, + trustlineClawbackEnabledFlag: 4 + }); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS = 1; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS", 1); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS_V13 = 3; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS_V13", 3); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS_V17 = 7; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS_V17", 7); + + // === xdr source ============================================================ + // + // enum LiquidityPoolType + // { + // LIQUIDITY_POOL_CONSTANT_PRODUCT = 0 + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolType", { + liquidityPoolConstantProduct: 0 + }); + + // === xdr source ============================================================ + // + // union TrustLineAsset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // case ASSET_TYPE_POOL_SHARE: + // PoolID liquidityPoolID; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("TrustLineAsset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPoolId"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12"), + liquidityPoolId: xdr.lookup("PoolId") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryExtensionV2Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TrustLineEntryExtensionV2 + // { + // int32 liquidityPoolUseCount; + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TrustLineEntryExtensionV2", [["liquidityPoolUseCount", xdr.lookup("Int32")], ["ext", xdr.lookup("TrustLineEntryExtensionV2Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [2, "v2"]], + arms: { + v2: xdr.lookup("TrustLineEntryExtensionV2") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } + // + // =========================================================================== + xdr.struct("TrustLineEntryV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("TrustLineEntryV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } v1; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("TrustLineEntryV1") + } + }); + + // === xdr source ============================================================ + // + // struct TrustLineEntry + // { + // AccountID accountID; // account this trustline belongs to + // TrustLineAsset asset; // type of asset (with issuer) + // int64 balance; // how much of this asset the user has. + // // Asset defines the unit for this; + // + // int64 limit; // balance cannot be above this + // uint32 flags; // see TrustLineFlags + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TrustLineEntry", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")], ["balance", xdr.lookup("Int64")], ["limit", xdr.lookup("Int64")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("TrustLineEntryExt")]]); + + // === xdr source ============================================================ + // + // enum OfferEntryFlags + // { + // // an offer with this flag will not act on and take a reverse offer of equal + // // price + // PASSIVE_FLAG = 1 + // }; + // + // =========================================================================== + xdr["enum"]("OfferEntryFlags", { + passiveFlag: 1 + }); + + // === xdr source ============================================================ + // + // const MASK_OFFERENTRY_FLAGS = 1; + // + // =========================================================================== + xdr["const"]("MASK_OFFERENTRY_FLAGS", 1); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("OfferEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct OfferEntry + // { + // AccountID sellerID; + // int64 offerID; + // Asset selling; // A + // Asset buying; // B + // int64 amount; // amount of A + // + // /* price for this offer: + // price of A in terms of B + // price=AmountB/AmountA=priceNumerator/priceDenominator + // price is after fees + // */ + // Price price; + // uint32 flags; // see OfferEntryFlags + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("OfferEntry", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("OfferEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("DataEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct DataEntry + // { + // AccountID accountID; // account this data belongs to + // string64 dataName; + // DataValue dataValue; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("DataEntry", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")], ["dataValue", xdr.lookup("DataValue")], ["ext", xdr.lookup("DataEntryExt")]]); + + // === xdr source ============================================================ + // + // enum ClaimPredicateType + // { + // CLAIM_PREDICATE_UNCONDITIONAL = 0, + // CLAIM_PREDICATE_AND = 1, + // CLAIM_PREDICATE_OR = 2, + // CLAIM_PREDICATE_NOT = 3, + // CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME = 4, + // CLAIM_PREDICATE_BEFORE_RELATIVE_TIME = 5 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimPredicateType", { + claimPredicateUnconditional: 0, + claimPredicateAnd: 1, + claimPredicateOr: 2, + claimPredicateNot: 3, + claimPredicateBeforeAbsoluteTime: 4, + claimPredicateBeforeRelativeTime: 5 + }); + + // === xdr source ============================================================ + // + // union ClaimPredicate switch (ClaimPredicateType type) + // { + // case CLAIM_PREDICATE_UNCONDITIONAL: + // void; + // case CLAIM_PREDICATE_AND: + // ClaimPredicate andPredicates<2>; + // case CLAIM_PREDICATE_OR: + // ClaimPredicate orPredicates<2>; + // case CLAIM_PREDICATE_NOT: + // ClaimPredicate* notPredicate; + // case CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME: + // int64 absBefore; // Predicate will be true if closeTime < absBefore + // case CLAIM_PREDICATE_BEFORE_RELATIVE_TIME: + // int64 relBefore; // Seconds since closeTime of the ledger in which the + // // ClaimableBalanceEntry was created + // }; + // + // =========================================================================== + xdr.union("ClaimPredicate", { + switchOn: xdr.lookup("ClaimPredicateType"), + switchName: "type", + switches: [["claimPredicateUnconditional", xdr["void"]()], ["claimPredicateAnd", "andPredicates"], ["claimPredicateOr", "orPredicates"], ["claimPredicateNot", "notPredicate"], ["claimPredicateBeforeAbsoluteTime", "absBefore"], ["claimPredicateBeforeRelativeTime", "relBefore"]], + arms: { + andPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2), + orPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2), + notPredicate: xdr.option(xdr.lookup("ClaimPredicate")), + absBefore: xdr.lookup("Int64"), + relBefore: xdr.lookup("Int64") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimantType + // { + // CLAIMANT_TYPE_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimantType", { + claimantTypeV0: 0 + }); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID destination; // The account that can use this condition + // ClaimPredicate predicate; // Claimable if predicate is true + // } + // + // =========================================================================== + xdr.struct("ClaimantV0", [["destination", xdr.lookup("AccountId")], ["predicate", xdr.lookup("ClaimPredicate")]]); + + // === xdr source ============================================================ + // + // union Claimant switch (ClaimantType type) + // { + // case CLAIMANT_TYPE_V0: + // struct + // { + // AccountID destination; // The account that can use this condition + // ClaimPredicate predicate; // Claimable if predicate is true + // } v0; + // }; + // + // =========================================================================== + xdr.union("Claimant", { + switchOn: xdr.lookup("ClaimantType"), + switchName: "type", + switches: [["claimantTypeV0", "v0"]], + arms: { + v0: xdr.lookup("ClaimantV0") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimableBalanceIDType + // { + // CLAIMABLE_BALANCE_ID_TYPE_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimableBalanceIdType", { + claimableBalanceIdTypeV0: 0 + }); + + // === xdr source ============================================================ + // + // union ClaimableBalanceID switch (ClaimableBalanceIDType type) + // { + // case CLAIMABLE_BALANCE_ID_TYPE_V0: + // Hash v0; + // }; + // + // =========================================================================== + xdr.union("ClaimableBalanceId", { + switchOn: xdr.lookup("ClaimableBalanceIdType"), + switchName: "type", + switches: [["claimableBalanceIdTypeV0", "v0"]], + arms: { + v0: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimableBalanceFlags + // { + // // If set, the issuer account of the asset held by the claimable balance may + // // clawback the claimable balance + // CLAIMABLE_BALANCE_CLAWBACK_ENABLED_FLAG = 0x1 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimableBalanceFlags", { + claimableBalanceClawbackEnabledFlag: 1 + }); + + // === xdr source ============================================================ + // + // const MASK_CLAIMABLE_BALANCE_FLAGS = 0x1; + // + // =========================================================================== + xdr["const"]("MASK_CLAIMABLE_BALANCE_FLAGS", 0x1); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("ClaimableBalanceEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct ClaimableBalanceEntryExtensionV1 + // { + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // + // uint32 flags; // see ClaimableBalanceFlags + // }; + // + // =========================================================================== + xdr.struct("ClaimableBalanceEntryExtensionV1", [["ext", xdr.lookup("ClaimableBalanceEntryExtensionV1Ext")], ["flags", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ClaimableBalanceEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("ClaimableBalanceEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("ClaimableBalanceEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct ClaimableBalanceEntry + // { + // // Unique identifier for this ClaimableBalanceEntry + // ClaimableBalanceID balanceID; + // + // // List of claimants with associated predicate + // Claimant claimants<10>; + // + // // Any asset including native + // Asset asset; + // + // // Amount of asset + // int64 amount; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ClaimableBalanceEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("ClaimableBalanceEntry", [["balanceId", xdr.lookup("ClaimableBalanceId")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["ext", xdr.lookup("ClaimableBalanceEntryExt")]]); + + // === xdr source ============================================================ + // + // struct LiquidityPoolConstantProductParameters + // { + // Asset assetA; // assetA < assetB + // Asset assetB; + // int32 fee; // Fee is in basis points, so the actual rate is (fee/100)% + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolConstantProductParameters", [["assetA", xdr.lookup("Asset")], ["assetB", xdr.lookup("Asset")], ["fee", xdr.lookup("Int32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } + // + // =========================================================================== + xdr.struct("LiquidityPoolEntryConstantProduct", [["params", xdr.lookup("LiquidityPoolConstantProductParameters")], ["reserveA", xdr.lookup("Int64")], ["reserveB", xdr.lookup("Int64")], ["totalPoolShares", xdr.lookup("Int64")], ["poolSharesTrustLineCount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } constantProduct; + // } + // + // =========================================================================== + xdr.union("LiquidityPoolEntryBody", { + switchOn: xdr.lookup("LiquidityPoolType"), + switchName: "type", + switches: [["liquidityPoolConstantProduct", "constantProduct"]], + arms: { + constantProduct: xdr.lookup("LiquidityPoolEntryConstantProduct") + } + }); + + // === xdr source ============================================================ + // + // struct LiquidityPoolEntry + // { + // PoolID liquidityPoolID; + // + // union switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } constantProduct; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolEntry", [["liquidityPoolId", xdr.lookup("PoolId")], ["body", xdr.lookup("LiquidityPoolEntryBody")]]); + + // === xdr source ============================================================ + // + // enum ContractDataDurability { + // TEMPORARY = 0, + // PERSISTENT = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractDataDurability", { + temporary: 0, + persistent: 1 + }); + + // === xdr source ============================================================ + // + // struct ContractDataEntry { + // ExtensionPoint ext; + // + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // SCVal val; + // }; + // + // =========================================================================== + xdr.struct("ContractDataEntry", [["ext", xdr.lookup("ExtensionPoint")], ["contract", xdr.lookup("ScAddress")], ["key", xdr.lookup("ScVal")], ["durability", xdr.lookup("ContractDataDurability")], ["val", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // struct ContractCodeCostInputs { + // ExtensionPoint ext; + // uint32 nInstructions; + // uint32 nFunctions; + // uint32 nGlobals; + // uint32 nTableEntries; + // uint32 nTypes; + // uint32 nDataSegments; + // uint32 nElemSegments; + // uint32 nImports; + // uint32 nExports; + // uint32 nDataSegmentBytes; + // }; + // + // =========================================================================== + xdr.struct("ContractCodeCostInputs", [["ext", xdr.lookup("ExtensionPoint")], ["nInstructions", xdr.lookup("Uint32")], ["nFunctions", xdr.lookup("Uint32")], ["nGlobals", xdr.lookup("Uint32")], ["nTableEntries", xdr.lookup("Uint32")], ["nTypes", xdr.lookup("Uint32")], ["nDataSegments", xdr.lookup("Uint32")], ["nElemSegments", xdr.lookup("Uint32")], ["nImports", xdr.lookup("Uint32")], ["nExports", xdr.lookup("Uint32")], ["nDataSegmentBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } + // + // =========================================================================== + xdr.struct("ContractCodeEntryV1", [["ext", xdr.lookup("ExtensionPoint")], ["costInputs", xdr.lookup("ContractCodeCostInputs")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } v1; + // } + // + // =========================================================================== + xdr.union("ContractCodeEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("ContractCodeEntryV1") + } + }); + + // === xdr source ============================================================ + // + // struct ContractCodeEntry { + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } v1; + // } ext; + // + // Hash hash; + // opaque code<>; + // }; + // + // =========================================================================== + xdr.struct("ContractCodeEntry", [["ext", xdr.lookup("ContractCodeEntryExt")], ["hash", xdr.lookup("Hash")], ["code", xdr.varOpaque()]]); + + // === xdr source ============================================================ + // + // struct TTLEntry { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // uint32 liveUntilLedgerSeq; + // }; + // + // =========================================================================== + xdr.struct("TtlEntry", [["keyHash", xdr.lookup("Hash")], ["liveUntilLedgerSeq", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerEntryExtensionV1 + // { + // SponsorshipDescriptor sponsoringID; + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerEntryExtensionV1", [["sponsoringId", xdr.lookup("SponsorshipDescriptor")], ["ext", xdr.lookup("LedgerEntryExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (LedgerEntryType type) + // { + // case ACCOUNT: + // AccountEntry account; + // case TRUSTLINE: + // TrustLineEntry trustLine; + // case OFFER: + // OfferEntry offer; + // case DATA: + // DataEntry data; + // case CLAIMABLE_BALANCE: + // ClaimableBalanceEntry claimableBalance; + // case LIQUIDITY_POOL: + // LiquidityPoolEntry liquidityPool; + // case CONTRACT_DATA: + // ContractDataEntry contractData; + // case CONTRACT_CODE: + // ContractCodeEntry contractCode; + // case CONFIG_SETTING: + // ConfigSettingEntry configSetting; + // case TTL: + // TTLEntry ttl; + // } + // + // =========================================================================== + xdr.union("LedgerEntryData", { + switchOn: xdr.lookup("LedgerEntryType"), + switchName: "type", + switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"], ["contractData", "contractData"], ["contractCode", "contractCode"], ["configSetting", "configSetting"], ["ttl", "ttl"]], + arms: { + account: xdr.lookup("AccountEntry"), + trustLine: xdr.lookup("TrustLineEntry"), + offer: xdr.lookup("OfferEntry"), + data: xdr.lookup("DataEntry"), + claimableBalance: xdr.lookup("ClaimableBalanceEntry"), + liquidityPool: xdr.lookup("LiquidityPoolEntry"), + contractData: xdr.lookup("ContractDataEntry"), + contractCode: xdr.lookup("ContractCodeEntry"), + configSetting: xdr.lookup("ConfigSettingEntry"), + ttl: xdr.lookup("TtlEntry") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("LedgerEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerEntry + // { + // uint32 lastModifiedLedgerSeq; // ledger the LedgerEntry was last changed + // + // union switch (LedgerEntryType type) + // { + // case ACCOUNT: + // AccountEntry account; + // case TRUSTLINE: + // TrustLineEntry trustLine; + // case OFFER: + // OfferEntry offer; + // case DATA: + // DataEntry data; + // case CLAIMABLE_BALANCE: + // ClaimableBalanceEntry claimableBalance; + // case LIQUIDITY_POOL: + // LiquidityPoolEntry liquidityPool; + // case CONTRACT_DATA: + // ContractDataEntry contractData; + // case CONTRACT_CODE: + // ContractCodeEntry contractCode; + // case CONFIG_SETTING: + // ConfigSettingEntry configSetting; + // case TTL: + // TTLEntry ttl; + // } + // data; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerEntry", [["lastModifiedLedgerSeq", xdr.lookup("Uint32")], ["data", xdr.lookup("LedgerEntryData")], ["ext", xdr.lookup("LedgerEntryExt")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyAccount", [["accountId", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // TrustLineAsset asset; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyTrustLine", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sellerID; + // int64 offerID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyOffer", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // string64 dataName; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyData", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimableBalanceID balanceID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyClaimableBalance", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // PoolID liquidityPoolID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyLiquidityPool", [["liquidityPoolId", xdr.lookup("PoolId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyContractData", [["contract", xdr.lookup("ScAddress")], ["key", xdr.lookup("ScVal")], ["durability", xdr.lookup("ContractDataDurability")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash hash; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyContractCode", [["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ConfigSettingID configSettingID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyConfigSetting", [["configSettingId", xdr.lookup("ConfigSettingId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyTtl", [["keyHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union LedgerKey switch (LedgerEntryType type) + // { + // case ACCOUNT: + // struct + // { + // AccountID accountID; + // } account; + // + // case TRUSTLINE: + // struct + // { + // AccountID accountID; + // TrustLineAsset asset; + // } trustLine; + // + // case OFFER: + // struct + // { + // AccountID sellerID; + // int64 offerID; + // } offer; + // + // case DATA: + // struct + // { + // AccountID accountID; + // string64 dataName; + // } data; + // + // case CLAIMABLE_BALANCE: + // struct + // { + // ClaimableBalanceID balanceID; + // } claimableBalance; + // + // case LIQUIDITY_POOL: + // struct + // { + // PoolID liquidityPoolID; + // } liquidityPool; + // case CONTRACT_DATA: + // struct + // { + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // } contractData; + // case CONTRACT_CODE: + // struct + // { + // Hash hash; + // } contractCode; + // case CONFIG_SETTING: + // struct + // { + // ConfigSettingID configSettingID; + // } configSetting; + // case TTL: + // struct + // { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // } ttl; + // }; + // + // =========================================================================== + xdr.union("LedgerKey", { + switchOn: xdr.lookup("LedgerEntryType"), + switchName: "type", + switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"], ["contractData", "contractData"], ["contractCode", "contractCode"], ["configSetting", "configSetting"], ["ttl", "ttl"]], + arms: { + account: xdr.lookup("LedgerKeyAccount"), + trustLine: xdr.lookup("LedgerKeyTrustLine"), + offer: xdr.lookup("LedgerKeyOffer"), + data: xdr.lookup("LedgerKeyData"), + claimableBalance: xdr.lookup("LedgerKeyClaimableBalance"), + liquidityPool: xdr.lookup("LedgerKeyLiquidityPool"), + contractData: xdr.lookup("LedgerKeyContractData"), + contractCode: xdr.lookup("LedgerKeyContractCode"), + configSetting: xdr.lookup("LedgerKeyConfigSetting"), + ttl: xdr.lookup("LedgerKeyTtl") + } + }); + + // === xdr source ============================================================ + // + // enum EnvelopeType + // { + // ENVELOPE_TYPE_TX_V0 = 0, + // ENVELOPE_TYPE_SCP = 1, + // ENVELOPE_TYPE_TX = 2, + // ENVELOPE_TYPE_AUTH = 3, + // ENVELOPE_TYPE_SCPVALUE = 4, + // ENVELOPE_TYPE_TX_FEE_BUMP = 5, + // ENVELOPE_TYPE_OP_ID = 6, + // ENVELOPE_TYPE_POOL_REVOKE_OP_ID = 7, + // ENVELOPE_TYPE_CONTRACT_ID = 8, + // ENVELOPE_TYPE_SOROBAN_AUTHORIZATION = 9 + // }; + // + // =========================================================================== + xdr["enum"]("EnvelopeType", { + envelopeTypeTxV0: 0, + envelopeTypeScp: 1, + envelopeTypeTx: 2, + envelopeTypeAuth: 3, + envelopeTypeScpvalue: 4, + envelopeTypeTxFeeBump: 5, + envelopeTypeOpId: 6, + envelopeTypePoolRevokeOpId: 7, + envelopeTypeContractId: 8, + envelopeTypeSorobanAuthorization: 9 + }); + + // === xdr source ============================================================ + // + // enum BucketListType + // { + // LIVE = 0, + // HOT_ARCHIVE = 1, + // COLD_ARCHIVE = 2 + // }; + // + // =========================================================================== + xdr["enum"]("BucketListType", { + live: 0, + hotArchive: 1, + coldArchive: 2 + }); + + // === xdr source ============================================================ + // + // enum BucketEntryType + // { + // METAENTRY = + // -1, // At-and-after protocol 11: bucket metadata, should come first. + // LIVEENTRY = 0, // Before protocol 11: created-or-updated; + // // At-and-after protocol 11: only updated. + // DEADENTRY = 1, + // INITENTRY = 2 // At-and-after protocol 11: only created. + // }; + // + // =========================================================================== + xdr["enum"]("BucketEntryType", { + metaentry: -1, + liveentry: 0, + deadentry: 1, + initentry: 2 + }); + + // === xdr source ============================================================ + // + // enum HotArchiveBucketEntryType + // { + // HOT_ARCHIVE_METAENTRY = -1, // Bucket metadata, should come first. + // HOT_ARCHIVE_ARCHIVED = 0, // Entry is Archived + // HOT_ARCHIVE_LIVE = 1, // Entry was previously HOT_ARCHIVE_ARCHIVED, or HOT_ARCHIVE_DELETED, but + // // has been added back to the live BucketList. + // // Does not need to be persisted. + // HOT_ARCHIVE_DELETED = 2 // Entry deleted (Note: must be persisted in archive) + // }; + // + // =========================================================================== + xdr["enum"]("HotArchiveBucketEntryType", { + hotArchiveMetaentry: -1, + hotArchiveArchived: 0, + hotArchiveLive: 1, + hotArchiveDeleted: 2 + }); + + // === xdr source ============================================================ + // + // enum ColdArchiveBucketEntryType + // { + // COLD_ARCHIVE_METAENTRY = -1, // Bucket metadata, should come first. + // COLD_ARCHIVE_ARCHIVED_LEAF = 0, // Full LedgerEntry that was archived during the epoch + // COLD_ARCHIVE_DELETED_LEAF = 1, // LedgerKey that was deleted during the epoch + // COLD_ARCHIVE_BOUNDARY_LEAF = 2, // Dummy leaf representing low/high bound + // COLD_ARCHIVE_HASH = 3 // Intermediary Merkle hash entry + // }; + // + // =========================================================================== + xdr["enum"]("ColdArchiveBucketEntryType", { + coldArchiveMetaentry: -1, + coldArchiveArchivedLeaf: 0, + coldArchiveDeletedLeaf: 1, + coldArchiveBoundaryLeaf: 2, + coldArchiveHash: 3 + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // BucketListType bucketListType; + // } + // + // =========================================================================== + xdr.union("BucketMetadataExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "bucketListType"]], + arms: { + bucketListType: xdr.lookup("BucketListType") + } + }); + + // === xdr source ============================================================ + // + // struct BucketMetadata + // { + // // Indicates the protocol version used to create / merge this bucket. + // uint32 ledgerVersion; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // BucketListType bucketListType; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("BucketMetadata", [["ledgerVersion", xdr.lookup("Uint32")], ["ext", xdr.lookup("BucketMetadataExt")]]); + + // === xdr source ============================================================ + // + // union BucketEntry switch (BucketEntryType type) + // { + // case LIVEENTRY: + // case INITENTRY: + // LedgerEntry liveEntry; + // + // case DEADENTRY: + // LedgerKey deadEntry; + // case METAENTRY: + // BucketMetadata metaEntry; + // }; + // + // =========================================================================== + xdr.union("BucketEntry", { + switchOn: xdr.lookup("BucketEntryType"), + switchName: "type", + switches: [["liveentry", "liveEntry"], ["initentry", "liveEntry"], ["deadentry", "deadEntry"], ["metaentry", "metaEntry"]], + arms: { + liveEntry: xdr.lookup("LedgerEntry"), + deadEntry: xdr.lookup("LedgerKey"), + metaEntry: xdr.lookup("BucketMetadata") + } + }); + + // === xdr source ============================================================ + // + // union HotArchiveBucketEntry switch (HotArchiveBucketEntryType type) + // { + // case HOT_ARCHIVE_ARCHIVED: + // LedgerEntry archivedEntry; + // + // case HOT_ARCHIVE_LIVE: + // case HOT_ARCHIVE_DELETED: + // LedgerKey key; + // case HOT_ARCHIVE_METAENTRY: + // BucketMetadata metaEntry; + // }; + // + // =========================================================================== + xdr.union("HotArchiveBucketEntry", { + switchOn: xdr.lookup("HotArchiveBucketEntryType"), + switchName: "type", + switches: [["hotArchiveArchived", "archivedEntry"], ["hotArchiveLive", "key"], ["hotArchiveDeleted", "key"], ["hotArchiveMetaentry", "metaEntry"]], + arms: { + archivedEntry: xdr.lookup("LedgerEntry"), + key: xdr.lookup("LedgerKey"), + metaEntry: xdr.lookup("BucketMetadata") + } + }); + + // === xdr source ============================================================ + // + // struct ColdArchiveArchivedLeaf + // { + // uint32 index; + // LedgerEntry archivedEntry; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveArchivedLeaf", [["index", xdr.lookup("Uint32")], ["archivedEntry", xdr.lookup("LedgerEntry")]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveDeletedLeaf + // { + // uint32 index; + // LedgerKey deletedKey; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveDeletedLeaf", [["index", xdr.lookup("Uint32")], ["deletedKey", xdr.lookup("LedgerKey")]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveBoundaryLeaf + // { + // uint32 index; + // bool isLowerBound; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveBoundaryLeaf", [["index", xdr.lookup("Uint32")], ["isLowerBound", xdr.bool()]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveHashEntry + // { + // uint32 index; + // uint32 level; + // Hash hash; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveHashEntry", [["index", xdr.lookup("Uint32")], ["level", xdr.lookup("Uint32")], ["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union ColdArchiveBucketEntry switch (ColdArchiveBucketEntryType type) + // { + // case COLD_ARCHIVE_METAENTRY: + // BucketMetadata metaEntry; + // case COLD_ARCHIVE_ARCHIVED_LEAF: + // ColdArchiveArchivedLeaf archivedLeaf; + // case COLD_ARCHIVE_DELETED_LEAF: + // ColdArchiveDeletedLeaf deletedLeaf; + // case COLD_ARCHIVE_BOUNDARY_LEAF: + // ColdArchiveBoundaryLeaf boundaryLeaf; + // case COLD_ARCHIVE_HASH: + // ColdArchiveHashEntry hashEntry; + // }; + // + // =========================================================================== + xdr.union("ColdArchiveBucketEntry", { + switchOn: xdr.lookup("ColdArchiveBucketEntryType"), + switchName: "type", + switches: [["coldArchiveMetaentry", "metaEntry"], ["coldArchiveArchivedLeaf", "archivedLeaf"], ["coldArchiveDeletedLeaf", "deletedLeaf"], ["coldArchiveBoundaryLeaf", "boundaryLeaf"], ["coldArchiveHash", "hashEntry"]], + arms: { + metaEntry: xdr.lookup("BucketMetadata"), + archivedLeaf: xdr.lookup("ColdArchiveArchivedLeaf"), + deletedLeaf: xdr.lookup("ColdArchiveDeletedLeaf"), + boundaryLeaf: xdr.lookup("ColdArchiveBoundaryLeaf"), + hashEntry: xdr.lookup("ColdArchiveHashEntry") + } + }); + + // === xdr source ============================================================ + // + // typedef opaque UpgradeType<128>; + // + // =========================================================================== + xdr.typedef("UpgradeType", xdr.varOpaque(128)); + + // === xdr source ============================================================ + // + // enum StellarValueType + // { + // STELLAR_VALUE_BASIC = 0, + // STELLAR_VALUE_SIGNED = 1 + // }; + // + // =========================================================================== + xdr["enum"]("StellarValueType", { + stellarValueBasic: 0, + stellarValueSigned: 1 + }); + + // === xdr source ============================================================ + // + // struct LedgerCloseValueSignature + // { + // NodeID nodeID; // which node introduced the value + // Signature signature; // nodeID's signature + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseValueSignature", [["nodeId", xdr.lookup("NodeId")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // union switch (StellarValueType v) + // { + // case STELLAR_VALUE_BASIC: + // void; + // case STELLAR_VALUE_SIGNED: + // LedgerCloseValueSignature lcValueSignature; + // } + // + // =========================================================================== + xdr.union("StellarValueExt", { + switchOn: xdr.lookup("StellarValueType"), + switchName: "v", + switches: [["stellarValueBasic", xdr["void"]()], ["stellarValueSigned", "lcValueSignature"]], + arms: { + lcValueSignature: xdr.lookup("LedgerCloseValueSignature") + } + }); + + // === xdr source ============================================================ + // + // struct StellarValue + // { + // Hash txSetHash; // transaction set to apply to previous ledger + // TimePoint closeTime; // network close time + // + // // upgrades to apply to the previous ledger (usually empty) + // // this is a vector of encoded 'LedgerUpgrade' so that nodes can drop + // // unknown steps during consensus if needed. + // // see notes below on 'LedgerUpgrade' for more detail + // // max size is dictated by number of upgrade types (+ room for future) + // UpgradeType upgrades<6>; + // + // // reserved for future use + // union switch (StellarValueType v) + // { + // case STELLAR_VALUE_BASIC: + // void; + // case STELLAR_VALUE_SIGNED: + // LedgerCloseValueSignature lcValueSignature; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("StellarValue", [["txSetHash", xdr.lookup("Hash")], ["closeTime", xdr.lookup("TimePoint")], ["upgrades", xdr.varArray(xdr.lookup("UpgradeType"), 6)], ["ext", xdr.lookup("StellarValueExt")]]); + + // === xdr source ============================================================ + // + // const MASK_LEDGER_HEADER_FLAGS = 0x7; + // + // =========================================================================== + xdr["const"]("MASK_LEDGER_HEADER_FLAGS", 0x7); + + // === xdr source ============================================================ + // + // enum LedgerHeaderFlags + // { + // DISABLE_LIQUIDITY_POOL_TRADING_FLAG = 0x1, + // DISABLE_LIQUIDITY_POOL_DEPOSIT_FLAG = 0x2, + // DISABLE_LIQUIDITY_POOL_WITHDRAWAL_FLAG = 0x4 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerHeaderFlags", { + disableLiquidityPoolTradingFlag: 1, + disableLiquidityPoolDepositFlag: 2, + disableLiquidityPoolWithdrawalFlag: 4 + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerHeaderExtensionV1 + // { + // uint32 flags; // LedgerHeaderFlags + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeaderExtensionV1", [["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("LedgerHeaderExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerHeaderExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerHeaderExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerHeader + // { + // uint32 ledgerVersion; // the protocol version of the ledger + // Hash previousLedgerHash; // hash of the previous ledger header + // StellarValue scpValue; // what consensus agreed to + // Hash txSetResultHash; // the TransactionResultSet that led to this ledger + // Hash bucketListHash; // hash of the ledger state + // + // uint32 ledgerSeq; // sequence number of this ledger + // + // int64 totalCoins; // total number of stroops in existence. + // // 10,000,000 stroops in 1 XLM + // + // int64 feePool; // fees burned since last inflation run + // uint32 inflationSeq; // inflation sequence number + // + // uint64 idPool; // last used global ID, used for generating objects + // + // uint32 baseFee; // base fee per operation in stroops + // uint32 baseReserve; // account base reserve in stroops + // + // uint32 maxTxSetSize; // maximum size a transaction set can be + // + // Hash skipList[4]; // hashes of ledgers in the past. allows you to jump back + // // in time without walking the chain back ledger by ledger + // // each slot contains the oldest ledger that is mod of + // // either 50 5000 50000 or 500000 depending on index + // // skipList[0] mod(50), skipList[1] mod(5000), etc + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerHeaderExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeader", [["ledgerVersion", xdr.lookup("Uint32")], ["previousLedgerHash", xdr.lookup("Hash")], ["scpValue", xdr.lookup("StellarValue")], ["txSetResultHash", xdr.lookup("Hash")], ["bucketListHash", xdr.lookup("Hash")], ["ledgerSeq", xdr.lookup("Uint32")], ["totalCoins", xdr.lookup("Int64")], ["feePool", xdr.lookup("Int64")], ["inflationSeq", xdr.lookup("Uint32")], ["idPool", xdr.lookup("Uint64")], ["baseFee", xdr.lookup("Uint32")], ["baseReserve", xdr.lookup("Uint32")], ["maxTxSetSize", xdr.lookup("Uint32")], ["skipList", xdr.array(xdr.lookup("Hash"), 4)], ["ext", xdr.lookup("LedgerHeaderExt")]]); + + // === xdr source ============================================================ + // + // enum LedgerUpgradeType + // { + // LEDGER_UPGRADE_VERSION = 1, + // LEDGER_UPGRADE_BASE_FEE = 2, + // LEDGER_UPGRADE_MAX_TX_SET_SIZE = 3, + // LEDGER_UPGRADE_BASE_RESERVE = 4, + // LEDGER_UPGRADE_FLAGS = 5, + // LEDGER_UPGRADE_CONFIG = 6, + // LEDGER_UPGRADE_MAX_SOROBAN_TX_SET_SIZE = 7 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerUpgradeType", { + ledgerUpgradeVersion: 1, + ledgerUpgradeBaseFee: 2, + ledgerUpgradeMaxTxSetSize: 3, + ledgerUpgradeBaseReserve: 4, + ledgerUpgradeFlags: 5, + ledgerUpgradeConfig: 6, + ledgerUpgradeMaxSorobanTxSetSize: 7 + }); + + // === xdr source ============================================================ + // + // struct ConfigUpgradeSetKey { + // Hash contractID; + // Hash contentHash; + // }; + // + // =========================================================================== + xdr.struct("ConfigUpgradeSetKey", [["contractId", xdr.lookup("Hash")], ["contentHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union LedgerUpgrade switch (LedgerUpgradeType type) + // { + // case LEDGER_UPGRADE_VERSION: + // uint32 newLedgerVersion; // update ledgerVersion + // case LEDGER_UPGRADE_BASE_FEE: + // uint32 newBaseFee; // update baseFee + // case LEDGER_UPGRADE_MAX_TX_SET_SIZE: + // uint32 newMaxTxSetSize; // update maxTxSetSize + // case LEDGER_UPGRADE_BASE_RESERVE: + // uint32 newBaseReserve; // update baseReserve + // case LEDGER_UPGRADE_FLAGS: + // uint32 newFlags; // update flags + // case LEDGER_UPGRADE_CONFIG: + // // Update arbitrary `ConfigSetting` entries identified by the key. + // ConfigUpgradeSetKey newConfig; + // case LEDGER_UPGRADE_MAX_SOROBAN_TX_SET_SIZE: + // // Update ConfigSettingContractExecutionLanesV0.ledgerMaxTxCount without + // // using `LEDGER_UPGRADE_CONFIG`. + // uint32 newMaxSorobanTxSetSize; + // }; + // + // =========================================================================== + xdr.union("LedgerUpgrade", { + switchOn: xdr.lookup("LedgerUpgradeType"), + switchName: "type", + switches: [["ledgerUpgradeVersion", "newLedgerVersion"], ["ledgerUpgradeBaseFee", "newBaseFee"], ["ledgerUpgradeMaxTxSetSize", "newMaxTxSetSize"], ["ledgerUpgradeBaseReserve", "newBaseReserve"], ["ledgerUpgradeFlags", "newFlags"], ["ledgerUpgradeConfig", "newConfig"], ["ledgerUpgradeMaxSorobanTxSetSize", "newMaxSorobanTxSetSize"]], + arms: { + newLedgerVersion: xdr.lookup("Uint32"), + newBaseFee: xdr.lookup("Uint32"), + newMaxTxSetSize: xdr.lookup("Uint32"), + newBaseReserve: xdr.lookup("Uint32"), + newFlags: xdr.lookup("Uint32"), + newConfig: xdr.lookup("ConfigUpgradeSetKey"), + newMaxSorobanTxSetSize: xdr.lookup("Uint32") + } + }); + + // === xdr source ============================================================ + // + // struct ConfigUpgradeSet { + // ConfigSettingEntry updatedEntry<>; + // }; + // + // =========================================================================== + xdr.struct("ConfigUpgradeSet", [["updatedEntry", xdr.varArray(xdr.lookup("ConfigSettingEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // enum TxSetComponentType + // { + // // txs with effective fee <= bid derived from a base fee (if any). + // // If base fee is not specified, no discount is applied. + // TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE = 0 + // }; + // + // =========================================================================== + xdr["enum"]("TxSetComponentType", { + txsetCompTxsMaybeDiscountedFee: 0 + }); + + // === xdr source ============================================================ + // + // struct + // { + // int64* baseFee; + // TransactionEnvelope txs<>; + // } + // + // =========================================================================== + xdr.struct("TxSetComponentTxsMaybeDiscountedFee", [["baseFee", xdr.option(xdr.lookup("Int64"))], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union TxSetComponent switch (TxSetComponentType type) + // { + // case TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE: + // struct + // { + // int64* baseFee; + // TransactionEnvelope txs<>; + // } txsMaybeDiscountedFee; + // }; + // + // =========================================================================== + xdr.union("TxSetComponent", { + switchOn: xdr.lookup("TxSetComponentType"), + switchName: "type", + switches: [["txsetCompTxsMaybeDiscountedFee", "txsMaybeDiscountedFee"]], + arms: { + txsMaybeDiscountedFee: xdr.lookup("TxSetComponentTxsMaybeDiscountedFee") + } + }); + + // === xdr source ============================================================ + // + // union TransactionPhase switch (int v) + // { + // case 0: + // TxSetComponent v0Components<>; + // }; + // + // =========================================================================== + xdr.union("TransactionPhase", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0Components"]], + arms: { + v0Components: xdr.varArray(xdr.lookup("TxSetComponent"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // struct TransactionSet + // { + // Hash previousLedgerHash; + // TransactionEnvelope txs<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionSet", [["previousLedgerHash", xdr.lookup("Hash")], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionSetV1 + // { + // Hash previousLedgerHash; + // TransactionPhase phases<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionSetV1", [["previousLedgerHash", xdr.lookup("Hash")], ["phases", xdr.varArray(xdr.lookup("TransactionPhase"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union GeneralizedTransactionSet switch (int v) + // { + // // We consider the legacy TransactionSet to be v0. + // case 1: + // TransactionSetV1 v1TxSet; + // }; + // + // =========================================================================== + xdr.union("GeneralizedTransactionSet", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[1, "v1TxSet"]], + arms: { + v1TxSet: xdr.lookup("TransactionSetV1") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionResultPair + // { + // Hash transactionHash; + // TransactionResult result; // result for the transaction + // }; + // + // =========================================================================== + xdr.struct("TransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("TransactionResult")]]); + + // === xdr source ============================================================ + // + // struct TransactionResultSet + // { + // TransactionResultPair results<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionResultSet", [["results", xdr.varArray(xdr.lookup("TransactionResultPair"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // GeneralizedTransactionSet generalizedTxSet; + // } + // + // =========================================================================== + xdr.union("TransactionHistoryEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "generalizedTxSet"]], + arms: { + generalizedTxSet: xdr.lookup("GeneralizedTransactionSet") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionHistoryEntry + // { + // uint32 ledgerSeq; + // TransactionSet txSet; + // + // // when v != 0, txSet must be empty + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // GeneralizedTransactionSet generalizedTxSet; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionHistoryEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txSet", xdr.lookup("TransactionSet")], ["ext", xdr.lookup("TransactionHistoryEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionHistoryResultEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionHistoryResultEntry + // { + // uint32 ledgerSeq; + // TransactionResultSet txResultSet; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionHistoryResultEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txResultSet", xdr.lookup("TransactionResultSet")], ["ext", xdr.lookup("TransactionHistoryResultEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderHistoryEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerHeaderHistoryEntry + // { + // Hash hash; + // LedgerHeader header; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeaderHistoryEntry", [["hash", xdr.lookup("Hash")], ["header", xdr.lookup("LedgerHeader")], ["ext", xdr.lookup("LedgerHeaderHistoryEntryExt")]]); + + // === xdr source ============================================================ + // + // struct LedgerSCPMessages + // { + // uint32 ledgerSeq; + // SCPEnvelope messages<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerScpMessages", [["ledgerSeq", xdr.lookup("Uint32")], ["messages", xdr.varArray(xdr.lookup("ScpEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct SCPHistoryEntryV0 + // { + // SCPQuorumSet quorumSets<>; // additional quorum sets used by ledgerMessages + // LedgerSCPMessages ledgerMessages; + // }; + // + // =========================================================================== + xdr.struct("ScpHistoryEntryV0", [["quorumSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)], ["ledgerMessages", xdr.lookup("LedgerScpMessages")]]); + + // === xdr source ============================================================ + // + // union SCPHistoryEntry switch (int v) + // { + // case 0: + // SCPHistoryEntryV0 v0; + // }; + // + // =========================================================================== + xdr.union("ScpHistoryEntry", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("ScpHistoryEntryV0") + } + }); + + // === xdr source ============================================================ + // + // enum LedgerEntryChangeType + // { + // LEDGER_ENTRY_CREATED = 0, // entry was added to the ledger + // LEDGER_ENTRY_UPDATED = 1, // entry was modified in the ledger + // LEDGER_ENTRY_REMOVED = 2, // entry was removed from the ledger + // LEDGER_ENTRY_STATE = 3 // value of the entry + // }; + // + // =========================================================================== + xdr["enum"]("LedgerEntryChangeType", { + ledgerEntryCreated: 0, + ledgerEntryUpdated: 1, + ledgerEntryRemoved: 2, + ledgerEntryState: 3 + }); + + // === xdr source ============================================================ + // + // union LedgerEntryChange switch (LedgerEntryChangeType type) + // { + // case LEDGER_ENTRY_CREATED: + // LedgerEntry created; + // case LEDGER_ENTRY_UPDATED: + // LedgerEntry updated; + // case LEDGER_ENTRY_REMOVED: + // LedgerKey removed; + // case LEDGER_ENTRY_STATE: + // LedgerEntry state; + // }; + // + // =========================================================================== + xdr.union("LedgerEntryChange", { + switchOn: xdr.lookup("LedgerEntryChangeType"), + switchName: "type", + switches: [["ledgerEntryCreated", "created"], ["ledgerEntryUpdated", "updated"], ["ledgerEntryRemoved", "removed"], ["ledgerEntryState", "state"]], + arms: { + created: xdr.lookup("LedgerEntry"), + updated: xdr.lookup("LedgerEntry"), + removed: xdr.lookup("LedgerKey"), + state: xdr.lookup("LedgerEntry") + } + }); + + // === xdr source ============================================================ + // + // typedef LedgerEntryChange LedgerEntryChanges<>; + // + // =========================================================================== + xdr.typedef("LedgerEntryChanges", xdr.varArray(xdr.lookup("LedgerEntryChange"), 2147483647)); + + // === xdr source ============================================================ + // + // struct OperationMeta + // { + // LedgerEntryChanges changes; + // }; + // + // =========================================================================== + xdr.struct("OperationMeta", [["changes", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV1 + // { + // LedgerEntryChanges txChanges; // tx level changes if any + // OperationMeta operations<>; // meta for each operation + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV1", [["txChanges", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV2 + // { + // LedgerEntryChanges txChangesBefore; // tx level changes before operations + // // are applied if any + // OperationMeta operations<>; // meta for each operation + // LedgerEntryChanges txChangesAfter; // tx level changes after operations are + // // applied if any + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV2", [["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // enum ContractEventType + // { + // SYSTEM = 0, + // CONTRACT = 1, + // DIAGNOSTIC = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ContractEventType", { + system: 0, + contract: 1, + diagnostic: 2 + }); + + // === xdr source ============================================================ + // + // struct + // { + // SCVal topics<>; + // SCVal data; + // } + // + // =========================================================================== + xdr.struct("ContractEventV0", [["topics", xdr.varArray(xdr.lookup("ScVal"), 2147483647)], ["data", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // struct + // { + // SCVal topics<>; + // SCVal data; + // } v0; + // } + // + // =========================================================================== + xdr.union("ContractEventBody", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("ContractEventV0") + } + }); + + // === xdr source ============================================================ + // + // struct ContractEvent + // { + // // We can use this to add more fields, or because it + // // is first, to change ContractEvent into a union. + // ExtensionPoint ext; + // + // Hash* contractID; + // ContractEventType type; + // + // union switch (int v) + // { + // case 0: + // struct + // { + // SCVal topics<>; + // SCVal data; + // } v0; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("ContractEvent", [["ext", xdr.lookup("ExtensionPoint")], ["contractId", xdr.option(xdr.lookup("Hash"))], ["type", xdr.lookup("ContractEventType")], ["body", xdr.lookup("ContractEventBody")]]); + + // === xdr source ============================================================ + // + // struct DiagnosticEvent + // { + // bool inSuccessfulContractCall; + // ContractEvent event; + // }; + // + // =========================================================================== + xdr.struct("DiagnosticEvent", [["inSuccessfulContractCall", xdr.bool()], ["event", xdr.lookup("ContractEvent")]]); + + // === xdr source ============================================================ + // + // typedef DiagnosticEvent DiagnosticEvents<>; + // + // =========================================================================== + xdr.typedef("DiagnosticEvents", xdr.varArray(xdr.lookup("DiagnosticEvent"), 2147483647)); + + // === xdr source ============================================================ + // + // struct SorobanTransactionMetaExtV1 + // { + // ExtensionPoint ext; + // + // // The following are the components of the overall Soroban resource fee + // // charged for the transaction. + // // The following relation holds: + // // `resourceFeeCharged = totalNonRefundableResourceFeeCharged + totalRefundableResourceFeeCharged` + // // where `resourceFeeCharged` is the overall fee charged for the + // // transaction. Also, `resourceFeeCharged` <= `sorobanData.resourceFee` + // // i.e.we never charge more than the declared resource fee. + // // The inclusion fee for charged the Soroban transaction can be found using + // // the following equation: + // // `result.feeCharged = resourceFeeCharged + inclusionFeeCharged`. + // + // // Total amount (in stroops) that has been charged for non-refundable + // // Soroban resources. + // // Non-refundable resources are charged based on the usage declared in + // // the transaction envelope (such as `instructions`, `readBytes` etc.) and + // // is charged regardless of the success of the transaction. + // int64 totalNonRefundableResourceFeeCharged; + // // Total amount (in stroops) that has been charged for refundable + // // Soroban resource fees. + // // Currently this comprises the rent fee (`rentFeeCharged`) and the + // // fee for the events and return value. + // // Refundable resources are charged based on the actual resources usage. + // // Since currently refundable resources are only used for the successful + // // transactions, this will be `0` for failed transactions. + // int64 totalRefundableResourceFeeCharged; + // // Amount (in stroops) that has been charged for rent. + // // This is a part of `totalNonRefundableResourceFeeCharged`. + // int64 rentFeeCharged; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionMetaExtV1", [["ext", xdr.lookup("ExtensionPoint")], ["totalNonRefundableResourceFeeCharged", xdr.lookup("Int64")], ["totalRefundableResourceFeeCharged", xdr.lookup("Int64")], ["rentFeeCharged", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union SorobanTransactionMetaExt switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionMetaExtV1 v1; + // }; + // + // =========================================================================== + xdr.union("SorobanTransactionMetaExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("SorobanTransactionMetaExtV1") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanTransactionMeta + // { + // SorobanTransactionMetaExt ext; + // + // ContractEvent events<>; // custom events populated by the + // // contracts themselves. + // SCVal returnValue; // return value of the host fn invocation + // + // // Diagnostics events that are not hashed. + // // This will contain all contract and diagnostic events. Even ones + // // that were emitted in a failed contract call. + // DiagnosticEvent diagnosticEvents<>; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionMeta", [["ext", xdr.lookup("SorobanTransactionMetaExt")], ["events", xdr.varArray(xdr.lookup("ContractEvent"), 2147483647)], ["returnValue", xdr.lookup("ScVal")], ["diagnosticEvents", xdr.varArray(xdr.lookup("DiagnosticEvent"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV3 + // { + // ExtensionPoint ext; + // + // LedgerEntryChanges txChangesBefore; // tx level changes before operations + // // are applied if any + // OperationMeta operations<>; // meta for each operation + // LedgerEntryChanges txChangesAfter; // tx level changes after operations are + // // applied if any + // SorobanTransactionMeta* sorobanMeta; // Soroban-specific meta (only for + // // Soroban transactions). + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV3", [["ext", xdr.lookup("ExtensionPoint")], ["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")], ["sorobanMeta", xdr.option(xdr.lookup("SorobanTransactionMeta"))]]); + + // === xdr source ============================================================ + // + // struct InvokeHostFunctionSuccessPreImage + // { + // SCVal returnValue; + // ContractEvent events<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeHostFunctionSuccessPreImage", [["returnValue", xdr.lookup("ScVal")], ["events", xdr.varArray(xdr.lookup("ContractEvent"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union TransactionMeta switch (int v) + // { + // case 0: + // OperationMeta operations<>; + // case 1: + // TransactionMetaV1 v1; + // case 2: + // TransactionMetaV2 v2; + // case 3: + // TransactionMetaV3 v3; + // }; + // + // =========================================================================== + xdr.union("TransactionMeta", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "operations"], [1, "v1"], [2, "v2"], [3, "v3"]], + arms: { + operations: xdr.varArray(xdr.lookup("OperationMeta"), 2147483647), + v1: xdr.lookup("TransactionMetaV1"), + v2: xdr.lookup("TransactionMetaV2"), + v3: xdr.lookup("TransactionMetaV3") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionResultMeta + // { + // TransactionResultPair result; + // LedgerEntryChanges feeProcessing; + // TransactionMeta txApplyProcessing; + // }; + // + // =========================================================================== + xdr.struct("TransactionResultMeta", [["result", xdr.lookup("TransactionResultPair")], ["feeProcessing", xdr.lookup("LedgerEntryChanges")], ["txApplyProcessing", xdr.lookup("TransactionMeta")]]); + + // === xdr source ============================================================ + // + // struct UpgradeEntryMeta + // { + // LedgerUpgrade upgrade; + // LedgerEntryChanges changes; + // }; + // + // =========================================================================== + xdr.struct("UpgradeEntryMeta", [["upgrade", xdr.lookup("LedgerUpgrade")], ["changes", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaV0 + // { + // LedgerHeaderHistoryEntry ledgerHeader; + // // NB: txSet is sorted in "Hash order" + // TransactionSet txSet; + // + // // NB: transactions are sorted in apply order here + // // fees for all transactions are processed first + // // followed by applying transactions + // TransactionResultMeta txProcessing<>; + // + // // upgrades are applied last + // UpgradeEntryMeta upgradesProcessing<>; + // + // // other misc information attached to the ledger close + // SCPHistoryEntry scpInfo<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaV0", [["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("TransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaExtV1 + // { + // ExtensionPoint ext; + // int64 sorobanFeeWrite1KB; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaExtV1", [["ext", xdr.lookup("ExtensionPoint")], ["sorobanFeeWrite1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union LedgerCloseMetaExt switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerCloseMetaExtV1 v1; + // }; + // + // =========================================================================== + xdr.union("LedgerCloseMetaExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerCloseMetaExtV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaV1 + // { + // LedgerCloseMetaExt ext; + // + // LedgerHeaderHistoryEntry ledgerHeader; + // + // GeneralizedTransactionSet txSet; + // + // // NB: transactions are sorted in apply order here + // // fees for all transactions are processed first + // // followed by applying transactions + // TransactionResultMeta txProcessing<>; + // + // // upgrades are applied last + // UpgradeEntryMeta upgradesProcessing<>; + // + // // other misc information attached to the ledger close + // SCPHistoryEntry scpInfo<>; + // + // // Size in bytes of BucketList, to support downstream + // // systems calculating storage fees correctly. + // uint64 totalByteSizeOfBucketList; + // + // // Temp keys that are being evicted at this ledger. + // LedgerKey evictedTemporaryLedgerKeys<>; + // + // // Archived restorable ledger entries that are being + // // evicted at this ledger. + // LedgerEntry evictedPersistentLedgerEntries<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaV1", [["ext", xdr.lookup("LedgerCloseMetaExt")], ["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("GeneralizedTransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)], ["totalByteSizeOfBucketList", xdr.lookup("Uint64")], ["evictedTemporaryLedgerKeys", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["evictedPersistentLedgerEntries", xdr.varArray(xdr.lookup("LedgerEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union LedgerCloseMeta switch (int v) + // { + // case 0: + // LedgerCloseMetaV0 v0; + // case 1: + // LedgerCloseMetaV1 v1; + // }; + // + // =========================================================================== + xdr.union("LedgerCloseMeta", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"], [1, "v1"]], + arms: { + v0: xdr.lookup("LedgerCloseMetaV0"), + v1: xdr.lookup("LedgerCloseMetaV1") + } + }); + + // === xdr source ============================================================ + // + // enum ErrorCode + // { + // ERR_MISC = 0, // Unspecific error + // ERR_DATA = 1, // Malformed data + // ERR_CONF = 2, // Misconfiguration error + // ERR_AUTH = 3, // Authentication failure + // ERR_LOAD = 4 // System overloaded + // }; + // + // =========================================================================== + xdr["enum"]("ErrorCode", { + errMisc: 0, + errData: 1, + errConf: 2, + errAuth: 3, + errLoad: 4 + }); + + // === xdr source ============================================================ + // + // struct Error + // { + // ErrorCode code; + // string msg<100>; + // }; + // + // =========================================================================== + xdr.struct("Error", [["code", xdr.lookup("ErrorCode")], ["msg", xdr.string(100)]]); + + // === xdr source ============================================================ + // + // struct SendMore + // { + // uint32 numMessages; + // }; + // + // =========================================================================== + xdr.struct("SendMore", [["numMessages", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SendMoreExtended + // { + // uint32 numMessages; + // uint32 numBytes; + // }; + // + // =========================================================================== + xdr.struct("SendMoreExtended", [["numMessages", xdr.lookup("Uint32")], ["numBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct AuthCert + // { + // Curve25519Public pubkey; + // uint64 expiration; + // Signature sig; + // }; + // + // =========================================================================== + xdr.struct("AuthCert", [["pubkey", xdr.lookup("Curve25519Public")], ["expiration", xdr.lookup("Uint64")], ["sig", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // struct Hello + // { + // uint32 ledgerVersion; + // uint32 overlayVersion; + // uint32 overlayMinVersion; + // Hash networkID; + // string versionStr<100>; + // int listeningPort; + // NodeID peerID; + // AuthCert cert; + // uint256 nonce; + // }; + // + // =========================================================================== + xdr.struct("Hello", [["ledgerVersion", xdr.lookup("Uint32")], ["overlayVersion", xdr.lookup("Uint32")], ["overlayMinVersion", xdr.lookup("Uint32")], ["networkId", xdr.lookup("Hash")], ["versionStr", xdr.string(100)], ["listeningPort", xdr["int"]()], ["peerId", xdr.lookup("NodeId")], ["cert", xdr.lookup("AuthCert")], ["nonce", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // const AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED = 200; + // + // =========================================================================== + xdr["const"]("AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED", 200); + + // === xdr source ============================================================ + // + // struct Auth + // { + // int flags; + // }; + // + // =========================================================================== + xdr.struct("Auth", [["flags", xdr["int"]()]]); + + // === xdr source ============================================================ + // + // enum IPAddrType + // { + // IPv4 = 0, + // IPv6 = 1 + // }; + // + // =========================================================================== + xdr["enum"]("IpAddrType", { + iPv4: 0, + iPv6: 1 + }); + + // === xdr source ============================================================ + // + // union switch (IPAddrType type) + // { + // case IPv4: + // opaque ipv4[4]; + // case IPv6: + // opaque ipv6[16]; + // } + // + // =========================================================================== + xdr.union("PeerAddressIp", { + switchOn: xdr.lookup("IpAddrType"), + switchName: "type", + switches: [["iPv4", "ipv4"], ["iPv6", "ipv6"]], + arms: { + ipv4: xdr.opaque(4), + ipv6: xdr.opaque(16) + } + }); + + // === xdr source ============================================================ + // + // struct PeerAddress + // { + // union switch (IPAddrType type) + // { + // case IPv4: + // opaque ipv4[4]; + // case IPv6: + // opaque ipv6[16]; + // } + // ip; + // uint32 port; + // uint32 numFailures; + // }; + // + // =========================================================================== + xdr.struct("PeerAddress", [["ip", xdr.lookup("PeerAddressIp")], ["port", xdr.lookup("Uint32")], ["numFailures", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // enum MessageType + // { + // ERROR_MSG = 0, + // AUTH = 2, + // DONT_HAVE = 3, + // + // GET_PEERS = 4, // gets a list of peers this guy knows about + // PEERS = 5, + // + // GET_TX_SET = 6, // gets a particular txset by hash + // TX_SET = 7, + // GENERALIZED_TX_SET = 17, + // + // TRANSACTION = 8, // pass on a tx you have heard about + // + // // SCP + // GET_SCP_QUORUMSET = 9, + // SCP_QUORUMSET = 10, + // SCP_MESSAGE = 11, + // GET_SCP_STATE = 12, + // + // // new messages + // HELLO = 13, + // + // SURVEY_REQUEST = 14, + // SURVEY_RESPONSE = 15, + // + // SEND_MORE = 16, + // SEND_MORE_EXTENDED = 20, + // + // FLOOD_ADVERT = 18, + // FLOOD_DEMAND = 19, + // + // TIME_SLICED_SURVEY_REQUEST = 21, + // TIME_SLICED_SURVEY_RESPONSE = 22, + // TIME_SLICED_SURVEY_START_COLLECTING = 23, + // TIME_SLICED_SURVEY_STOP_COLLECTING = 24 + // }; + // + // =========================================================================== + xdr["enum"]("MessageType", { + errorMsg: 0, + auth: 2, + dontHave: 3, + getPeers: 4, + peers: 5, + getTxSet: 6, + txSet: 7, + generalizedTxSet: 17, + transaction: 8, + getScpQuorumset: 9, + scpQuorumset: 10, + scpMessage: 11, + getScpState: 12, + hello: 13, + surveyRequest: 14, + surveyResponse: 15, + sendMore: 16, + sendMoreExtended: 20, + floodAdvert: 18, + floodDemand: 19, + timeSlicedSurveyRequest: 21, + timeSlicedSurveyResponse: 22, + timeSlicedSurveyStartCollecting: 23, + timeSlicedSurveyStopCollecting: 24 + }); + + // === xdr source ============================================================ + // + // struct DontHave + // { + // MessageType type; + // uint256 reqHash; + // }; + // + // =========================================================================== + xdr.struct("DontHave", [["type", xdr.lookup("MessageType")], ["reqHash", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // enum SurveyMessageCommandType + // { + // SURVEY_TOPOLOGY = 0, + // TIME_SLICED_SURVEY_TOPOLOGY = 1 + // }; + // + // =========================================================================== + xdr["enum"]("SurveyMessageCommandType", { + surveyTopology: 0, + timeSlicedSurveyTopology: 1 + }); + + // === xdr source ============================================================ + // + // enum SurveyMessageResponseType + // { + // SURVEY_TOPOLOGY_RESPONSE_V0 = 0, + // SURVEY_TOPOLOGY_RESPONSE_V1 = 1, + // SURVEY_TOPOLOGY_RESPONSE_V2 = 2 + // }; + // + // =========================================================================== + xdr["enum"]("SurveyMessageResponseType", { + surveyTopologyResponseV0: 0, + surveyTopologyResponseV1: 1, + surveyTopologyResponseV2: 2 + }); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyStartCollectingMessage + // { + // NodeID surveyorID; + // uint32 nonce; + // uint32 ledgerNum; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyStartCollectingMessage", [["surveyorId", xdr.lookup("NodeId")], ["nonce", xdr.lookup("Uint32")], ["ledgerNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyStartCollectingMessage + // { + // Signature signature; + // TimeSlicedSurveyStartCollectingMessage startCollecting; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyStartCollectingMessage", [["signature", xdr.lookup("Signature")], ["startCollecting", xdr.lookup("TimeSlicedSurveyStartCollectingMessage")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyStopCollectingMessage + // { + // NodeID surveyorID; + // uint32 nonce; + // uint32 ledgerNum; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyStopCollectingMessage", [["surveyorId", xdr.lookup("NodeId")], ["nonce", xdr.lookup("Uint32")], ["ledgerNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyStopCollectingMessage + // { + // Signature signature; + // TimeSlicedSurveyStopCollectingMessage stopCollecting; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyStopCollectingMessage", [["signature", xdr.lookup("Signature")], ["stopCollecting", xdr.lookup("TimeSlicedSurveyStopCollectingMessage")]]); + + // === xdr source ============================================================ + // + // struct SurveyRequestMessage + // { + // NodeID surveyorPeerID; + // NodeID surveyedPeerID; + // uint32 ledgerNum; + // Curve25519Public encryptionKey; + // SurveyMessageCommandType commandType; + // }; + // + // =========================================================================== + xdr.struct("SurveyRequestMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["encryptionKey", xdr.lookup("Curve25519Public")], ["commandType", xdr.lookup("SurveyMessageCommandType")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyRequestMessage + // { + // SurveyRequestMessage request; + // uint32 nonce; + // uint32 inboundPeersIndex; + // uint32 outboundPeersIndex; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyRequestMessage", [["request", xdr.lookup("SurveyRequestMessage")], ["nonce", xdr.lookup("Uint32")], ["inboundPeersIndex", xdr.lookup("Uint32")], ["outboundPeersIndex", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedSurveyRequestMessage + // { + // Signature requestSignature; + // SurveyRequestMessage request; + // }; + // + // =========================================================================== + xdr.struct("SignedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("SurveyRequestMessage")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyRequestMessage + // { + // Signature requestSignature; + // TimeSlicedSurveyRequestMessage request; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("TimeSlicedSurveyRequestMessage")]]); + + // === xdr source ============================================================ + // + // typedef opaque EncryptedBody<64000>; + // + // =========================================================================== + xdr.typedef("EncryptedBody", xdr.varOpaque(64000)); + + // === xdr source ============================================================ + // + // struct SurveyResponseMessage + // { + // NodeID surveyorPeerID; + // NodeID surveyedPeerID; + // uint32 ledgerNum; + // SurveyMessageCommandType commandType; + // EncryptedBody encryptedBody; + // }; + // + // =========================================================================== + xdr.struct("SurveyResponseMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["commandType", xdr.lookup("SurveyMessageCommandType")], ["encryptedBody", xdr.lookup("EncryptedBody")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyResponseMessage + // { + // SurveyResponseMessage response; + // uint32 nonce; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyResponseMessage", [["response", xdr.lookup("SurveyResponseMessage")], ["nonce", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedSurveyResponseMessage + // { + // Signature responseSignature; + // SurveyResponseMessage response; + // }; + // + // =========================================================================== + xdr.struct("SignedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("SurveyResponseMessage")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyResponseMessage + // { + // Signature responseSignature; + // TimeSlicedSurveyResponseMessage response; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("TimeSlicedSurveyResponseMessage")]]); + + // === xdr source ============================================================ + // + // struct PeerStats + // { + // NodeID id; + // string versionStr<100>; + // uint64 messagesRead; + // uint64 messagesWritten; + // uint64 bytesRead; + // uint64 bytesWritten; + // uint64 secondsConnected; + // + // uint64 uniqueFloodBytesRecv; + // uint64 duplicateFloodBytesRecv; + // uint64 uniqueFetchBytesRecv; + // uint64 duplicateFetchBytesRecv; + // + // uint64 uniqueFloodMessageRecv; + // uint64 duplicateFloodMessageRecv; + // uint64 uniqueFetchMessageRecv; + // uint64 duplicateFetchMessageRecv; + // }; + // + // =========================================================================== + xdr.struct("PeerStats", [["id", xdr.lookup("NodeId")], ["versionStr", xdr.string(100)], ["messagesRead", xdr.lookup("Uint64")], ["messagesWritten", xdr.lookup("Uint64")], ["bytesRead", xdr.lookup("Uint64")], ["bytesWritten", xdr.lookup("Uint64")], ["secondsConnected", xdr.lookup("Uint64")], ["uniqueFloodBytesRecv", xdr.lookup("Uint64")], ["duplicateFloodBytesRecv", xdr.lookup("Uint64")], ["uniqueFetchBytesRecv", xdr.lookup("Uint64")], ["duplicateFetchBytesRecv", xdr.lookup("Uint64")], ["uniqueFloodMessageRecv", xdr.lookup("Uint64")], ["duplicateFloodMessageRecv", xdr.lookup("Uint64")], ["uniqueFetchMessageRecv", xdr.lookup("Uint64")], ["duplicateFetchMessageRecv", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // typedef PeerStats PeerStatList<25>; + // + // =========================================================================== + xdr.typedef("PeerStatList", xdr.varArray(xdr.lookup("PeerStats"), 25)); + + // === xdr source ============================================================ + // + // struct TimeSlicedNodeData + // { + // uint32 addedAuthenticatedPeers; + // uint32 droppedAuthenticatedPeers; + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // + // // SCP stats + // uint32 p75SCPFirstToSelfLatencyMs; + // uint32 p75SCPSelfToOtherLatencyMs; + // + // // How many times the node lost sync in the time slice + // uint32 lostSyncCount; + // + // // Config data + // bool isValidator; + // uint32 maxInboundPeerCount; + // uint32 maxOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedNodeData", [["addedAuthenticatedPeers", xdr.lookup("Uint32")], ["droppedAuthenticatedPeers", xdr.lookup("Uint32")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")], ["p75ScpFirstToSelfLatencyMs", xdr.lookup("Uint32")], ["p75ScpSelfToOtherLatencyMs", xdr.lookup("Uint32")], ["lostSyncCount", xdr.lookup("Uint32")], ["isValidator", xdr.bool()], ["maxInboundPeerCount", xdr.lookup("Uint32")], ["maxOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedPeerData + // { + // PeerStats peerStats; + // uint32 averageLatencyMs; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedPeerData", [["peerStats", xdr.lookup("PeerStats")], ["averageLatencyMs", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // typedef TimeSlicedPeerData TimeSlicedPeerDataList<25>; + // + // =========================================================================== + xdr.typedef("TimeSlicedPeerDataList", xdr.varArray(xdr.lookup("TimeSlicedPeerData"), 25)); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV0 + // { + // PeerStatList inboundPeers; + // PeerStatList outboundPeers; + // + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV0", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV1 + // { + // PeerStatList inboundPeers; + // PeerStatList outboundPeers; + // + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // + // uint32 maxInboundPeerCount; + // uint32 maxOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV1", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")], ["maxInboundPeerCount", xdr.lookup("Uint32")], ["maxOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV2 + // { + // TimeSlicedPeerDataList inboundPeers; + // TimeSlicedPeerDataList outboundPeers; + // TimeSlicedNodeData nodeData; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV2", [["inboundPeers", xdr.lookup("TimeSlicedPeerDataList")], ["outboundPeers", xdr.lookup("TimeSlicedPeerDataList")], ["nodeData", xdr.lookup("TimeSlicedNodeData")]]); + + // === xdr source ============================================================ + // + // union SurveyResponseBody switch (SurveyMessageResponseType type) + // { + // case SURVEY_TOPOLOGY_RESPONSE_V0: + // TopologyResponseBodyV0 topologyResponseBodyV0; + // case SURVEY_TOPOLOGY_RESPONSE_V1: + // TopologyResponseBodyV1 topologyResponseBodyV1; + // case SURVEY_TOPOLOGY_RESPONSE_V2: + // TopologyResponseBodyV2 topologyResponseBodyV2; + // }; + // + // =========================================================================== + xdr.union("SurveyResponseBody", { + switchOn: xdr.lookup("SurveyMessageResponseType"), + switchName: "type", + switches: [["surveyTopologyResponseV0", "topologyResponseBodyV0"], ["surveyTopologyResponseV1", "topologyResponseBodyV1"], ["surveyTopologyResponseV2", "topologyResponseBodyV2"]], + arms: { + topologyResponseBodyV0: xdr.lookup("TopologyResponseBodyV0"), + topologyResponseBodyV1: xdr.lookup("TopologyResponseBodyV1"), + topologyResponseBodyV2: xdr.lookup("TopologyResponseBodyV2") + } + }); + + // === xdr source ============================================================ + // + // const TX_ADVERT_VECTOR_MAX_SIZE = 1000; + // + // =========================================================================== + xdr["const"]("TX_ADVERT_VECTOR_MAX_SIZE", 1000); + + // === xdr source ============================================================ + // + // typedef Hash TxAdvertVector; + // + // =========================================================================== + xdr.typedef("TxAdvertVector", xdr.varArray(xdr.lookup("Hash"), xdr.lookup("TX_ADVERT_VECTOR_MAX_SIZE"))); + + // === xdr source ============================================================ + // + // struct FloodAdvert + // { + // TxAdvertVector txHashes; + // }; + // + // =========================================================================== + xdr.struct("FloodAdvert", [["txHashes", xdr.lookup("TxAdvertVector")]]); + + // === xdr source ============================================================ + // + // const TX_DEMAND_VECTOR_MAX_SIZE = 1000; + // + // =========================================================================== + xdr["const"]("TX_DEMAND_VECTOR_MAX_SIZE", 1000); + + // === xdr source ============================================================ + // + // typedef Hash TxDemandVector; + // + // =========================================================================== + xdr.typedef("TxDemandVector", xdr.varArray(xdr.lookup("Hash"), xdr.lookup("TX_DEMAND_VECTOR_MAX_SIZE"))); + + // === xdr source ============================================================ + // + // struct FloodDemand + // { + // TxDemandVector txHashes; + // }; + // + // =========================================================================== + xdr.struct("FloodDemand", [["txHashes", xdr.lookup("TxDemandVector")]]); + + // === xdr source ============================================================ + // + // union StellarMessage switch (MessageType type) + // { + // case ERROR_MSG: + // Error error; + // case HELLO: + // Hello hello; + // case AUTH: + // Auth auth; + // case DONT_HAVE: + // DontHave dontHave; + // case GET_PEERS: + // void; + // case PEERS: + // PeerAddress peers<100>; + // + // case GET_TX_SET: + // uint256 txSetHash; + // case TX_SET: + // TransactionSet txSet; + // case GENERALIZED_TX_SET: + // GeneralizedTransactionSet generalizedTxSet; + // + // case TRANSACTION: + // TransactionEnvelope transaction; + // + // case SURVEY_REQUEST: + // SignedSurveyRequestMessage signedSurveyRequestMessage; + // + // case SURVEY_RESPONSE: + // SignedSurveyResponseMessage signedSurveyResponseMessage; + // + // case TIME_SLICED_SURVEY_REQUEST: + // SignedTimeSlicedSurveyRequestMessage signedTimeSlicedSurveyRequestMessage; + // + // case TIME_SLICED_SURVEY_RESPONSE: + // SignedTimeSlicedSurveyResponseMessage signedTimeSlicedSurveyResponseMessage; + // + // case TIME_SLICED_SURVEY_START_COLLECTING: + // SignedTimeSlicedSurveyStartCollectingMessage + // signedTimeSlicedSurveyStartCollectingMessage; + // + // case TIME_SLICED_SURVEY_STOP_COLLECTING: + // SignedTimeSlicedSurveyStopCollectingMessage + // signedTimeSlicedSurveyStopCollectingMessage; + // + // // SCP + // case GET_SCP_QUORUMSET: + // uint256 qSetHash; + // case SCP_QUORUMSET: + // SCPQuorumSet qSet; + // case SCP_MESSAGE: + // SCPEnvelope envelope; + // case GET_SCP_STATE: + // uint32 getSCPLedgerSeq; // ledger seq requested ; if 0, requests the latest + // case SEND_MORE: + // SendMore sendMoreMessage; + // case SEND_MORE_EXTENDED: + // SendMoreExtended sendMoreExtendedMessage; + // // Pull mode + // case FLOOD_ADVERT: + // FloodAdvert floodAdvert; + // case FLOOD_DEMAND: + // FloodDemand floodDemand; + // }; + // + // =========================================================================== + xdr.union("StellarMessage", { + switchOn: xdr.lookup("MessageType"), + switchName: "type", + switches: [["errorMsg", "error"], ["hello", "hello"], ["auth", "auth"], ["dontHave", "dontHave"], ["getPeers", xdr["void"]()], ["peers", "peers"], ["getTxSet", "txSetHash"], ["txSet", "txSet"], ["generalizedTxSet", "generalizedTxSet"], ["transaction", "transaction"], ["surveyRequest", "signedSurveyRequestMessage"], ["surveyResponse", "signedSurveyResponseMessage"], ["timeSlicedSurveyRequest", "signedTimeSlicedSurveyRequestMessage"], ["timeSlicedSurveyResponse", "signedTimeSlicedSurveyResponseMessage"], ["timeSlicedSurveyStartCollecting", "signedTimeSlicedSurveyStartCollectingMessage"], ["timeSlicedSurveyStopCollecting", "signedTimeSlicedSurveyStopCollectingMessage"], ["getScpQuorumset", "qSetHash"], ["scpQuorumset", "qSet"], ["scpMessage", "envelope"], ["getScpState", "getScpLedgerSeq"], ["sendMore", "sendMoreMessage"], ["sendMoreExtended", "sendMoreExtendedMessage"], ["floodAdvert", "floodAdvert"], ["floodDemand", "floodDemand"]], + arms: { + error: xdr.lookup("Error"), + hello: xdr.lookup("Hello"), + auth: xdr.lookup("Auth"), + dontHave: xdr.lookup("DontHave"), + peers: xdr.varArray(xdr.lookup("PeerAddress"), 100), + txSetHash: xdr.lookup("Uint256"), + txSet: xdr.lookup("TransactionSet"), + generalizedTxSet: xdr.lookup("GeneralizedTransactionSet"), + transaction: xdr.lookup("TransactionEnvelope"), + signedSurveyRequestMessage: xdr.lookup("SignedSurveyRequestMessage"), + signedSurveyResponseMessage: xdr.lookup("SignedSurveyResponseMessage"), + signedTimeSlicedSurveyRequestMessage: xdr.lookup("SignedTimeSlicedSurveyRequestMessage"), + signedTimeSlicedSurveyResponseMessage: xdr.lookup("SignedTimeSlicedSurveyResponseMessage"), + signedTimeSlicedSurveyStartCollectingMessage: xdr.lookup("SignedTimeSlicedSurveyStartCollectingMessage"), + signedTimeSlicedSurveyStopCollectingMessage: xdr.lookup("SignedTimeSlicedSurveyStopCollectingMessage"), + qSetHash: xdr.lookup("Uint256"), + qSet: xdr.lookup("ScpQuorumSet"), + envelope: xdr.lookup("ScpEnvelope"), + getScpLedgerSeq: xdr.lookup("Uint32"), + sendMoreMessage: xdr.lookup("SendMore"), + sendMoreExtendedMessage: xdr.lookup("SendMoreExtended"), + floodAdvert: xdr.lookup("FloodAdvert"), + floodDemand: xdr.lookup("FloodDemand") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // uint64 sequence; + // StellarMessage message; + // HmacSha256Mac mac; + // } + // + // =========================================================================== + xdr.struct("AuthenticatedMessageV0", [["sequence", xdr.lookup("Uint64")], ["message", xdr.lookup("StellarMessage")], ["mac", xdr.lookup("HmacSha256Mac")]]); + + // === xdr source ============================================================ + // + // union AuthenticatedMessage switch (uint32 v) + // { + // case 0: + // struct + // { + // uint64 sequence; + // StellarMessage message; + // HmacSha256Mac mac; + // } v0; + // }; + // + // =========================================================================== + xdr.union("AuthenticatedMessage", { + switchOn: xdr.lookup("Uint32"), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("AuthenticatedMessageV0") + } + }); + + // === xdr source ============================================================ + // + // const MAX_OPS_PER_TX = 100; + // + // =========================================================================== + xdr["const"]("MAX_OPS_PER_TX", 100); + + // === xdr source ============================================================ + // + // union LiquidityPoolParameters switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // LiquidityPoolConstantProductParameters constantProduct; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolParameters", { + switchOn: xdr.lookup("LiquidityPoolType"), + switchName: "type", + switches: [["liquidityPoolConstantProduct", "constantProduct"]], + arms: { + constantProduct: xdr.lookup("LiquidityPoolConstantProductParameters") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // uint64 id; + // uint256 ed25519; + // } + // + // =========================================================================== + xdr.struct("MuxedAccountMed25519", [["id", xdr.lookup("Uint64")], ["ed25519", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // union MuxedAccount switch (CryptoKeyType type) + // { + // case KEY_TYPE_ED25519: + // uint256 ed25519; + // case KEY_TYPE_MUXED_ED25519: + // struct + // { + // uint64 id; + // uint256 ed25519; + // } med25519; + // }; + // + // =========================================================================== + xdr.union("MuxedAccount", { + switchOn: xdr.lookup("CryptoKeyType"), + switchName: "type", + switches: [["keyTypeEd25519", "ed25519"], ["keyTypeMuxedEd25519", "med25519"]], + arms: { + ed25519: xdr.lookup("Uint256"), + med25519: xdr.lookup("MuxedAccountMed25519") + } + }); + + // === xdr source ============================================================ + // + // struct DecoratedSignature + // { + // SignatureHint hint; // last 4 bytes of the public key, used as a hint + // Signature signature; // actual signature + // }; + // + // =========================================================================== + xdr.struct("DecoratedSignature", [["hint", xdr.lookup("SignatureHint")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // enum OperationType + // { + // CREATE_ACCOUNT = 0, + // PAYMENT = 1, + // PATH_PAYMENT_STRICT_RECEIVE = 2, + // MANAGE_SELL_OFFER = 3, + // CREATE_PASSIVE_SELL_OFFER = 4, + // SET_OPTIONS = 5, + // CHANGE_TRUST = 6, + // ALLOW_TRUST = 7, + // ACCOUNT_MERGE = 8, + // INFLATION = 9, + // MANAGE_DATA = 10, + // BUMP_SEQUENCE = 11, + // MANAGE_BUY_OFFER = 12, + // PATH_PAYMENT_STRICT_SEND = 13, + // CREATE_CLAIMABLE_BALANCE = 14, + // CLAIM_CLAIMABLE_BALANCE = 15, + // BEGIN_SPONSORING_FUTURE_RESERVES = 16, + // END_SPONSORING_FUTURE_RESERVES = 17, + // REVOKE_SPONSORSHIP = 18, + // CLAWBACK = 19, + // CLAWBACK_CLAIMABLE_BALANCE = 20, + // SET_TRUST_LINE_FLAGS = 21, + // LIQUIDITY_POOL_DEPOSIT = 22, + // LIQUIDITY_POOL_WITHDRAW = 23, + // INVOKE_HOST_FUNCTION = 24, + // EXTEND_FOOTPRINT_TTL = 25, + // RESTORE_FOOTPRINT = 26 + // }; + // + // =========================================================================== + xdr["enum"]("OperationType", { + createAccount: 0, + payment: 1, + pathPaymentStrictReceive: 2, + manageSellOffer: 3, + createPassiveSellOffer: 4, + setOptions: 5, + changeTrust: 6, + allowTrust: 7, + accountMerge: 8, + inflation: 9, + manageData: 10, + bumpSequence: 11, + manageBuyOffer: 12, + pathPaymentStrictSend: 13, + createClaimableBalance: 14, + claimClaimableBalance: 15, + beginSponsoringFutureReserves: 16, + endSponsoringFutureReserves: 17, + revokeSponsorship: 18, + clawback: 19, + clawbackClaimableBalance: 20, + setTrustLineFlags: 21, + liquidityPoolDeposit: 22, + liquidityPoolWithdraw: 23, + invokeHostFunction: 24, + extendFootprintTtl: 25, + restoreFootprint: 26 + }); + + // === xdr source ============================================================ + // + // struct CreateAccountOp + // { + // AccountID destination; // account to create + // int64 startingBalance; // amount they end up with + // }; + // + // =========================================================================== + xdr.struct("CreateAccountOp", [["destination", xdr.lookup("AccountId")], ["startingBalance", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct PaymentOp + // { + // MuxedAccount destination; // recipient of the payment + // Asset asset; // what they end up with + // int64 amount; // amount they end up with + // }; + // + // =========================================================================== + xdr.struct("PaymentOp", [["destination", xdr.lookup("MuxedAccount")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct PathPaymentStrictReceiveOp + // { + // Asset sendAsset; // asset we pay with + // int64 sendMax; // the maximum amount of sendAsset to + // // send (excluding fees). + // // The operation will fail if can't be met + // + // MuxedAccount destination; // recipient of the payment + // Asset destAsset; // what they end up with + // int64 destAmount; // amount they end up with + // + // Asset path<5>; // additional hops it must go through to get there + // }; + // + // =========================================================================== + xdr.struct("PathPaymentStrictReceiveOp", [["sendAsset", xdr.lookup("Asset")], ["sendMax", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destAmount", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]); + + // === xdr source ============================================================ + // + // struct PathPaymentStrictSendOp + // { + // Asset sendAsset; // asset we pay with + // int64 sendAmount; // amount of sendAsset to send (excluding fees) + // + // MuxedAccount destination; // recipient of the payment + // Asset destAsset; // what they end up with + // int64 destMin; // the minimum amount of dest asset to + // // be received + // // The operation will fail if it can't be met + // + // Asset path<5>; // additional hops it must go through to get there + // }; + // + // =========================================================================== + xdr.struct("PathPaymentStrictSendOp", [["sendAsset", xdr.lookup("Asset")], ["sendAmount", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destMin", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]); + + // === xdr source ============================================================ + // + // struct ManageSellOfferOp + // { + // Asset selling; + // Asset buying; + // int64 amount; // amount being sold. if set to 0, delete the offer + // Price price; // price of thing being sold in terms of what you are buying + // + // // 0=create a new offer, otherwise edit an existing offer + // int64 offerID; + // }; + // + // =========================================================================== + xdr.struct("ManageSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ManageBuyOfferOp + // { + // Asset selling; + // Asset buying; + // int64 buyAmount; // amount being bought. if set to 0, delete the offer + // Price price; // price of thing being bought in terms of what you are + // // selling + // + // // 0=create a new offer, otherwise edit an existing offer + // int64 offerID; + // }; + // + // =========================================================================== + xdr.struct("ManageBuyOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["buyAmount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct CreatePassiveSellOfferOp + // { + // Asset selling; // A + // Asset buying; // B + // int64 amount; // amount taker gets + // Price price; // cost of A in terms of B + // }; + // + // =========================================================================== + xdr.struct("CreatePassiveSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")]]); + + // === xdr source ============================================================ + // + // struct SetOptionsOp + // { + // AccountID* inflationDest; // sets the inflation destination + // + // uint32* clearFlags; // which flags to clear + // uint32* setFlags; // which flags to set + // + // // account threshold manipulation + // uint32* masterWeight; // weight of the master account + // uint32* lowThreshold; + // uint32* medThreshold; + // uint32* highThreshold; + // + // string32* homeDomain; // sets the home domain + // + // // Add, update or remove a signer for the account + // // signer is deleted if the weight is 0 + // Signer* signer; + // }; + // + // =========================================================================== + xdr.struct("SetOptionsOp", [["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["clearFlags", xdr.option(xdr.lookup("Uint32"))], ["setFlags", xdr.option(xdr.lookup("Uint32"))], ["masterWeight", xdr.option(xdr.lookup("Uint32"))], ["lowThreshold", xdr.option(xdr.lookup("Uint32"))], ["medThreshold", xdr.option(xdr.lookup("Uint32"))], ["highThreshold", xdr.option(xdr.lookup("Uint32"))], ["homeDomain", xdr.option(xdr.lookup("String32"))], ["signer", xdr.option(xdr.lookup("Signer"))]]); + + // === xdr source ============================================================ + // + // union ChangeTrustAsset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // case ASSET_TYPE_POOL_SHARE: + // LiquidityPoolParameters liquidityPool; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("ChangeTrustAsset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPool"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12"), + liquidityPool: xdr.lookup("LiquidityPoolParameters") + } + }); + + // === xdr source ============================================================ + // + // struct ChangeTrustOp + // { + // ChangeTrustAsset line; + // + // // if limit is set to 0, deletes the trust line + // int64 limit; + // }; + // + // =========================================================================== + xdr.struct("ChangeTrustOp", [["line", xdr.lookup("ChangeTrustAsset")], ["limit", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct AllowTrustOp + // { + // AccountID trustor; + // AssetCode asset; + // + // // One of 0, AUTHORIZED_FLAG, or AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG + // uint32 authorize; + // }; + // + // =========================================================================== + xdr.struct("AllowTrustOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("AssetCode")], ["authorize", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ManageDataOp + // { + // string64 dataName; + // DataValue* dataValue; // set to null to clear + // }; + // + // =========================================================================== + xdr.struct("ManageDataOp", [["dataName", xdr.lookup("String64")], ["dataValue", xdr.option(xdr.lookup("DataValue"))]]); + + // === xdr source ============================================================ + // + // struct BumpSequenceOp + // { + // SequenceNumber bumpTo; + // }; + // + // =========================================================================== + xdr.struct("BumpSequenceOp", [["bumpTo", xdr.lookup("SequenceNumber")]]); + + // === xdr source ============================================================ + // + // struct CreateClaimableBalanceOp + // { + // Asset asset; + // int64 amount; + // Claimant claimants<10>; + // }; + // + // =========================================================================== + xdr.struct("CreateClaimableBalanceOp", [["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)]]); + + // === xdr source ============================================================ + // + // struct ClaimClaimableBalanceOp + // { + // ClaimableBalanceID balanceID; + // }; + // + // =========================================================================== + xdr.struct("ClaimClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct BeginSponsoringFutureReservesOp + // { + // AccountID sponsoredID; + // }; + // + // =========================================================================== + xdr.struct("BeginSponsoringFutureReservesOp", [["sponsoredId", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // enum RevokeSponsorshipType + // { + // REVOKE_SPONSORSHIP_LEDGER_ENTRY = 0, + // REVOKE_SPONSORSHIP_SIGNER = 1 + // }; + // + // =========================================================================== + xdr["enum"]("RevokeSponsorshipType", { + revokeSponsorshipLedgerEntry: 0, + revokeSponsorshipSigner: 1 + }); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // SignerKey signerKey; + // } + // + // =========================================================================== + xdr.struct("RevokeSponsorshipOpSigner", [["accountId", xdr.lookup("AccountId")], ["signerKey", xdr.lookup("SignerKey")]]); + + // === xdr source ============================================================ + // + // union RevokeSponsorshipOp switch (RevokeSponsorshipType type) + // { + // case REVOKE_SPONSORSHIP_LEDGER_ENTRY: + // LedgerKey ledgerKey; + // case REVOKE_SPONSORSHIP_SIGNER: + // struct + // { + // AccountID accountID; + // SignerKey signerKey; + // } signer; + // }; + // + // =========================================================================== + xdr.union("RevokeSponsorshipOp", { + switchOn: xdr.lookup("RevokeSponsorshipType"), + switchName: "type", + switches: [["revokeSponsorshipLedgerEntry", "ledgerKey"], ["revokeSponsorshipSigner", "signer"]], + arms: { + ledgerKey: xdr.lookup("LedgerKey"), + signer: xdr.lookup("RevokeSponsorshipOpSigner") + } + }); + + // === xdr source ============================================================ + // + // struct ClawbackOp + // { + // Asset asset; + // MuxedAccount from; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("ClawbackOp", [["asset", xdr.lookup("Asset")], ["from", xdr.lookup("MuxedAccount")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClawbackClaimableBalanceOp + // { + // ClaimableBalanceID balanceID; + // }; + // + // =========================================================================== + xdr.struct("ClawbackClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct SetTrustLineFlagsOp + // { + // AccountID trustor; + // Asset asset; + // + // uint32 clearFlags; // which flags to clear + // uint32 setFlags; // which flags to set + // }; + // + // =========================================================================== + xdr.struct("SetTrustLineFlagsOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["clearFlags", xdr.lookup("Uint32")], ["setFlags", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // const LIQUIDITY_POOL_FEE_V18 = 30; + // + // =========================================================================== + xdr["const"]("LIQUIDITY_POOL_FEE_V18", 30); + + // === xdr source ============================================================ + // + // struct LiquidityPoolDepositOp + // { + // PoolID liquidityPoolID; + // int64 maxAmountA; // maximum amount of first asset to deposit + // int64 maxAmountB; // maximum amount of second asset to deposit + // Price minPrice; // minimum depositA/depositB + // Price maxPrice; // maximum depositA/depositB + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolDepositOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["maxAmountA", xdr.lookup("Int64")], ["maxAmountB", xdr.lookup("Int64")], ["minPrice", xdr.lookup("Price")], ["maxPrice", xdr.lookup("Price")]]); + + // === xdr source ============================================================ + // + // struct LiquidityPoolWithdrawOp + // { + // PoolID liquidityPoolID; + // int64 amount; // amount of pool shares to withdraw + // int64 minAmountA; // minimum amount of first asset to withdraw + // int64 minAmountB; // minimum amount of second asset to withdraw + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolWithdrawOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["amount", xdr.lookup("Int64")], ["minAmountA", xdr.lookup("Int64")], ["minAmountB", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum HostFunctionType + // { + // HOST_FUNCTION_TYPE_INVOKE_CONTRACT = 0, + // HOST_FUNCTION_TYPE_CREATE_CONTRACT = 1, + // HOST_FUNCTION_TYPE_UPLOAD_CONTRACT_WASM = 2, + // HOST_FUNCTION_TYPE_CREATE_CONTRACT_V2 = 3 + // }; + // + // =========================================================================== + xdr["enum"]("HostFunctionType", { + hostFunctionTypeInvokeContract: 0, + hostFunctionTypeCreateContract: 1, + hostFunctionTypeUploadContractWasm: 2, + hostFunctionTypeCreateContractV2: 3 + }); + + // === xdr source ============================================================ + // + // enum ContractIDPreimageType + // { + // CONTRACT_ID_PREIMAGE_FROM_ADDRESS = 0, + // CONTRACT_ID_PREIMAGE_FROM_ASSET = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractIdPreimageType", { + contractIdPreimageFromAddress: 0, + contractIdPreimageFromAsset: 1 + }); + + // === xdr source ============================================================ + // + // struct + // { + // SCAddress address; + // uint256 salt; + // } + // + // =========================================================================== + xdr.struct("ContractIdPreimageFromAddress", [["address", xdr.lookup("ScAddress")], ["salt", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // union ContractIDPreimage switch (ContractIDPreimageType type) + // { + // case CONTRACT_ID_PREIMAGE_FROM_ADDRESS: + // struct + // { + // SCAddress address; + // uint256 salt; + // } fromAddress; + // case CONTRACT_ID_PREIMAGE_FROM_ASSET: + // Asset fromAsset; + // }; + // + // =========================================================================== + xdr.union("ContractIdPreimage", { + switchOn: xdr.lookup("ContractIdPreimageType"), + switchName: "type", + switches: [["contractIdPreimageFromAddress", "fromAddress"], ["contractIdPreimageFromAsset", "fromAsset"]], + arms: { + fromAddress: xdr.lookup("ContractIdPreimageFromAddress"), + fromAsset: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // struct CreateContractArgs + // { + // ContractIDPreimage contractIDPreimage; + // ContractExecutable executable; + // }; + // + // =========================================================================== + xdr.struct("CreateContractArgs", [["contractIdPreimage", xdr.lookup("ContractIdPreimage")], ["executable", xdr.lookup("ContractExecutable")]]); + + // === xdr source ============================================================ + // + // struct CreateContractArgsV2 + // { + // ContractIDPreimage contractIDPreimage; + // ContractExecutable executable; + // // Arguments of the contract's constructor. + // SCVal constructorArgs<>; + // }; + // + // =========================================================================== + xdr.struct("CreateContractArgsV2", [["contractIdPreimage", xdr.lookup("ContractIdPreimage")], ["executable", xdr.lookup("ContractExecutable")], ["constructorArgs", xdr.varArray(xdr.lookup("ScVal"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct InvokeContractArgs { + // SCAddress contractAddress; + // SCSymbol functionName; + // SCVal args<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeContractArgs", [["contractAddress", xdr.lookup("ScAddress")], ["functionName", xdr.lookup("ScSymbol")], ["args", xdr.varArray(xdr.lookup("ScVal"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union HostFunction switch (HostFunctionType type) + // { + // case HOST_FUNCTION_TYPE_INVOKE_CONTRACT: + // InvokeContractArgs invokeContract; + // case HOST_FUNCTION_TYPE_CREATE_CONTRACT: + // CreateContractArgs createContract; + // case HOST_FUNCTION_TYPE_UPLOAD_CONTRACT_WASM: + // opaque wasm<>; + // case HOST_FUNCTION_TYPE_CREATE_CONTRACT_V2: + // CreateContractArgsV2 createContractV2; + // }; + // + // =========================================================================== + xdr.union("HostFunction", { + switchOn: xdr.lookup("HostFunctionType"), + switchName: "type", + switches: [["hostFunctionTypeInvokeContract", "invokeContract"], ["hostFunctionTypeCreateContract", "createContract"], ["hostFunctionTypeUploadContractWasm", "wasm"], ["hostFunctionTypeCreateContractV2", "createContractV2"]], + arms: { + invokeContract: xdr.lookup("InvokeContractArgs"), + createContract: xdr.lookup("CreateContractArgs"), + wasm: xdr.varOpaque(), + createContractV2: xdr.lookup("CreateContractArgsV2") + } + }); + + // === xdr source ============================================================ + // + // enum SorobanAuthorizedFunctionType + // { + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN = 0, + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_HOST_FN = 1, + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN = 2 + // }; + // + // =========================================================================== + xdr["enum"]("SorobanAuthorizedFunctionType", { + sorobanAuthorizedFunctionTypeContractFn: 0, + sorobanAuthorizedFunctionTypeCreateContractHostFn: 1, + sorobanAuthorizedFunctionTypeCreateContractV2HostFn: 2 + }); + + // === xdr source ============================================================ + // + // union SorobanAuthorizedFunction switch (SorobanAuthorizedFunctionType type) + // { + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN: + // InvokeContractArgs contractFn; + // // This variant of auth payload for creating new contract instances + // // doesn't allow specifying the constructor arguments, creating contracts + // // with constructors that take arguments is only possible by authorizing + // // `SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN` + // // (protocol 22+). + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_HOST_FN: + // CreateContractArgs createContractHostFn; + // // This variant of auth payload for creating new contract instances + // // is only accepted in and after protocol 22. It allows authorizing the + // // contract constructor arguments. + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN: + // CreateContractArgsV2 createContractV2HostFn; + // }; + // + // =========================================================================== + xdr.union("SorobanAuthorizedFunction", { + switchOn: xdr.lookup("SorobanAuthorizedFunctionType"), + switchName: "type", + switches: [["sorobanAuthorizedFunctionTypeContractFn", "contractFn"], ["sorobanAuthorizedFunctionTypeCreateContractHostFn", "createContractHostFn"], ["sorobanAuthorizedFunctionTypeCreateContractV2HostFn", "createContractV2HostFn"]], + arms: { + contractFn: xdr.lookup("InvokeContractArgs"), + createContractHostFn: xdr.lookup("CreateContractArgs"), + createContractV2HostFn: xdr.lookup("CreateContractArgsV2") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanAuthorizedInvocation + // { + // SorobanAuthorizedFunction function; + // SorobanAuthorizedInvocation subInvocations<>; + // }; + // + // =========================================================================== + xdr.struct("SorobanAuthorizedInvocation", [["function", xdr.lookup("SorobanAuthorizedFunction")], ["subInvocations", xdr.varArray(xdr.lookup("SorobanAuthorizedInvocation"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct SorobanAddressCredentials + // { + // SCAddress address; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SCVal signature; + // }; + // + // =========================================================================== + xdr.struct("SorobanAddressCredentials", [["address", xdr.lookup("ScAddress")], ["nonce", xdr.lookup("Int64")], ["signatureExpirationLedger", xdr.lookup("Uint32")], ["signature", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // enum SorobanCredentialsType + // { + // SOROBAN_CREDENTIALS_SOURCE_ACCOUNT = 0, + // SOROBAN_CREDENTIALS_ADDRESS = 1 + // }; + // + // =========================================================================== + xdr["enum"]("SorobanCredentialsType", { + sorobanCredentialsSourceAccount: 0, + sorobanCredentialsAddress: 1 + }); + + // === xdr source ============================================================ + // + // union SorobanCredentials switch (SorobanCredentialsType type) + // { + // case SOROBAN_CREDENTIALS_SOURCE_ACCOUNT: + // void; + // case SOROBAN_CREDENTIALS_ADDRESS: + // SorobanAddressCredentials address; + // }; + // + // =========================================================================== + xdr.union("SorobanCredentials", { + switchOn: xdr.lookup("SorobanCredentialsType"), + switchName: "type", + switches: [["sorobanCredentialsSourceAccount", xdr["void"]()], ["sorobanCredentialsAddress", "address"]], + arms: { + address: xdr.lookup("SorobanAddressCredentials") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanAuthorizationEntry + // { + // SorobanCredentials credentials; + // SorobanAuthorizedInvocation rootInvocation; + // }; + // + // =========================================================================== + xdr.struct("SorobanAuthorizationEntry", [["credentials", xdr.lookup("SorobanCredentials")], ["rootInvocation", xdr.lookup("SorobanAuthorizedInvocation")]]); + + // === xdr source ============================================================ + // + // struct InvokeHostFunctionOp + // { + // // Host function to invoke. + // HostFunction hostFunction; + // // Per-address authorizations for this host function. + // SorobanAuthorizationEntry auth<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeHostFunctionOp", [["hostFunction", xdr.lookup("HostFunction")], ["auth", xdr.varArray(xdr.lookup("SorobanAuthorizationEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct ExtendFootprintTTLOp + // { + // ExtensionPoint ext; + // uint32 extendTo; + // }; + // + // =========================================================================== + xdr.struct("ExtendFootprintTtlOp", [["ext", xdr.lookup("ExtensionPoint")], ["extendTo", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct RestoreFootprintOp + // { + // ExtensionPoint ext; + // }; + // + // =========================================================================== + xdr.struct("RestoreFootprintOp", [["ext", xdr.lookup("ExtensionPoint")]]); + + // === xdr source ============================================================ + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountOp createAccountOp; + // case PAYMENT: + // PaymentOp paymentOp; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp; + // case MANAGE_SELL_OFFER: + // ManageSellOfferOp manageSellOfferOp; + // case CREATE_PASSIVE_SELL_OFFER: + // CreatePassiveSellOfferOp createPassiveSellOfferOp; + // case SET_OPTIONS: + // SetOptionsOp setOptionsOp; + // case CHANGE_TRUST: + // ChangeTrustOp changeTrustOp; + // case ALLOW_TRUST: + // AllowTrustOp allowTrustOp; + // case ACCOUNT_MERGE: + // MuxedAccount destination; + // case INFLATION: + // void; + // case MANAGE_DATA: + // ManageDataOp manageDataOp; + // case BUMP_SEQUENCE: + // BumpSequenceOp bumpSequenceOp; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferOp manageBuyOfferOp; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendOp pathPaymentStrictSendOp; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceOp createClaimableBalanceOp; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceOp claimClaimableBalanceOp; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp; + // case END_SPONSORING_FUTURE_RESERVES: + // void; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipOp revokeSponsorshipOp; + // case CLAWBACK: + // ClawbackOp clawbackOp; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceOp clawbackClaimableBalanceOp; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsOp setTrustLineFlagsOp; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositOp liquidityPoolDepositOp; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawOp liquidityPoolWithdrawOp; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionOp invokeHostFunctionOp; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLOp extendFootprintTTLOp; + // case RESTORE_FOOTPRINT: + // RestoreFootprintOp restoreFootprintOp; + // } + // + // =========================================================================== + xdr.union("OperationBody", { + switchOn: xdr.lookup("OperationType"), + switchName: "type", + switches: [["createAccount", "createAccountOp"], ["payment", "paymentOp"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveOp"], ["manageSellOffer", "manageSellOfferOp"], ["createPassiveSellOffer", "createPassiveSellOfferOp"], ["setOptions", "setOptionsOp"], ["changeTrust", "changeTrustOp"], ["allowTrust", "allowTrustOp"], ["accountMerge", "destination"], ["inflation", xdr["void"]()], ["manageData", "manageDataOp"], ["bumpSequence", "bumpSequenceOp"], ["manageBuyOffer", "manageBuyOfferOp"], ["pathPaymentStrictSend", "pathPaymentStrictSendOp"], ["createClaimableBalance", "createClaimableBalanceOp"], ["claimClaimableBalance", "claimClaimableBalanceOp"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesOp"], ["endSponsoringFutureReserves", xdr["void"]()], ["revokeSponsorship", "revokeSponsorshipOp"], ["clawback", "clawbackOp"], ["clawbackClaimableBalance", "clawbackClaimableBalanceOp"], ["setTrustLineFlags", "setTrustLineFlagsOp"], ["liquidityPoolDeposit", "liquidityPoolDepositOp"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawOp"], ["invokeHostFunction", "invokeHostFunctionOp"], ["extendFootprintTtl", "extendFootprintTtlOp"], ["restoreFootprint", "restoreFootprintOp"]], + arms: { + createAccountOp: xdr.lookup("CreateAccountOp"), + paymentOp: xdr.lookup("PaymentOp"), + pathPaymentStrictReceiveOp: xdr.lookup("PathPaymentStrictReceiveOp"), + manageSellOfferOp: xdr.lookup("ManageSellOfferOp"), + createPassiveSellOfferOp: xdr.lookup("CreatePassiveSellOfferOp"), + setOptionsOp: xdr.lookup("SetOptionsOp"), + changeTrustOp: xdr.lookup("ChangeTrustOp"), + allowTrustOp: xdr.lookup("AllowTrustOp"), + destination: xdr.lookup("MuxedAccount"), + manageDataOp: xdr.lookup("ManageDataOp"), + bumpSequenceOp: xdr.lookup("BumpSequenceOp"), + manageBuyOfferOp: xdr.lookup("ManageBuyOfferOp"), + pathPaymentStrictSendOp: xdr.lookup("PathPaymentStrictSendOp"), + createClaimableBalanceOp: xdr.lookup("CreateClaimableBalanceOp"), + claimClaimableBalanceOp: xdr.lookup("ClaimClaimableBalanceOp"), + beginSponsoringFutureReservesOp: xdr.lookup("BeginSponsoringFutureReservesOp"), + revokeSponsorshipOp: xdr.lookup("RevokeSponsorshipOp"), + clawbackOp: xdr.lookup("ClawbackOp"), + clawbackClaimableBalanceOp: xdr.lookup("ClawbackClaimableBalanceOp"), + setTrustLineFlagsOp: xdr.lookup("SetTrustLineFlagsOp"), + liquidityPoolDepositOp: xdr.lookup("LiquidityPoolDepositOp"), + liquidityPoolWithdrawOp: xdr.lookup("LiquidityPoolWithdrawOp"), + invokeHostFunctionOp: xdr.lookup("InvokeHostFunctionOp"), + extendFootprintTtlOp: xdr.lookup("ExtendFootprintTtlOp"), + restoreFootprintOp: xdr.lookup("RestoreFootprintOp") + } + }); + + // === xdr source ============================================================ + // + // struct Operation + // { + // // sourceAccount is the account used to run the operation + // // if not set, the runtime defaults to "sourceAccount" specified at + // // the transaction level + // MuxedAccount* sourceAccount; + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountOp createAccountOp; + // case PAYMENT: + // PaymentOp paymentOp; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp; + // case MANAGE_SELL_OFFER: + // ManageSellOfferOp manageSellOfferOp; + // case CREATE_PASSIVE_SELL_OFFER: + // CreatePassiveSellOfferOp createPassiveSellOfferOp; + // case SET_OPTIONS: + // SetOptionsOp setOptionsOp; + // case CHANGE_TRUST: + // ChangeTrustOp changeTrustOp; + // case ALLOW_TRUST: + // AllowTrustOp allowTrustOp; + // case ACCOUNT_MERGE: + // MuxedAccount destination; + // case INFLATION: + // void; + // case MANAGE_DATA: + // ManageDataOp manageDataOp; + // case BUMP_SEQUENCE: + // BumpSequenceOp bumpSequenceOp; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferOp manageBuyOfferOp; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendOp pathPaymentStrictSendOp; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceOp createClaimableBalanceOp; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceOp claimClaimableBalanceOp; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp; + // case END_SPONSORING_FUTURE_RESERVES: + // void; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipOp revokeSponsorshipOp; + // case CLAWBACK: + // ClawbackOp clawbackOp; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceOp clawbackClaimableBalanceOp; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsOp setTrustLineFlagsOp; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositOp liquidityPoolDepositOp; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawOp liquidityPoolWithdrawOp; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionOp invokeHostFunctionOp; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLOp extendFootprintTTLOp; + // case RESTORE_FOOTPRINT: + // RestoreFootprintOp restoreFootprintOp; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("Operation", [["sourceAccount", xdr.option(xdr.lookup("MuxedAccount"))], ["body", xdr.lookup("OperationBody")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageOperationId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // PoolID liquidityPoolID; + // Asset asset; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageRevokeId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")], ["liquidityPoolId", xdr.lookup("PoolId")], ["asset", xdr.lookup("Asset")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash networkID; + // ContractIDPreimage contractIDPreimage; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageContractId", [["networkId", xdr.lookup("Hash")], ["contractIdPreimage", xdr.lookup("ContractIdPreimage")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash networkID; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SorobanAuthorizedInvocation invocation; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageSorobanAuthorization", [["networkId", xdr.lookup("Hash")], ["nonce", xdr.lookup("Int64")], ["signatureExpirationLedger", xdr.lookup("Uint32")], ["invocation", xdr.lookup("SorobanAuthorizedInvocation")]]); + + // === xdr source ============================================================ + // + // union HashIDPreimage switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_OP_ID: + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // } operationID; + // case ENVELOPE_TYPE_POOL_REVOKE_OP_ID: + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // PoolID liquidityPoolID; + // Asset asset; + // } revokeID; + // case ENVELOPE_TYPE_CONTRACT_ID: + // struct + // { + // Hash networkID; + // ContractIDPreimage contractIDPreimage; + // } contractID; + // case ENVELOPE_TYPE_SOROBAN_AUTHORIZATION: + // struct + // { + // Hash networkID; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SorobanAuthorizedInvocation invocation; + // } sorobanAuthorization; + // }; + // + // =========================================================================== + xdr.union("HashIdPreimage", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeOpId", "operationId"], ["envelopeTypePoolRevokeOpId", "revokeId"], ["envelopeTypeContractId", "contractId"], ["envelopeTypeSorobanAuthorization", "sorobanAuthorization"]], + arms: { + operationId: xdr.lookup("HashIdPreimageOperationId"), + revokeId: xdr.lookup("HashIdPreimageRevokeId"), + contractId: xdr.lookup("HashIdPreimageContractId"), + sorobanAuthorization: xdr.lookup("HashIdPreimageSorobanAuthorization") + } + }); + + // === xdr source ============================================================ + // + // enum MemoType + // { + // MEMO_NONE = 0, + // MEMO_TEXT = 1, + // MEMO_ID = 2, + // MEMO_HASH = 3, + // MEMO_RETURN = 4 + // }; + // + // =========================================================================== + xdr["enum"]("MemoType", { + memoNone: 0, + memoText: 1, + memoId: 2, + memoHash: 3, + memoReturn: 4 + }); + + // === xdr source ============================================================ + // + // union Memo switch (MemoType type) + // { + // case MEMO_NONE: + // void; + // case MEMO_TEXT: + // string text<28>; + // case MEMO_ID: + // uint64 id; + // case MEMO_HASH: + // Hash hash; // the hash of what to pull from the content server + // case MEMO_RETURN: + // Hash retHash; // the hash of the tx you are rejecting + // }; + // + // =========================================================================== + xdr.union("Memo", { + switchOn: xdr.lookup("MemoType"), + switchName: "type", + switches: [["memoNone", xdr["void"]()], ["memoText", "text"], ["memoId", "id"], ["memoHash", "hash"], ["memoReturn", "retHash"]], + arms: { + text: xdr.string(28), + id: xdr.lookup("Uint64"), + hash: xdr.lookup("Hash"), + retHash: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // struct TimeBounds + // { + // TimePoint minTime; + // TimePoint maxTime; // 0 here means no maxTime + // }; + // + // =========================================================================== + xdr.struct("TimeBounds", [["minTime", xdr.lookup("TimePoint")], ["maxTime", xdr.lookup("TimePoint")]]); + + // === xdr source ============================================================ + // + // struct LedgerBounds + // { + // uint32 minLedger; + // uint32 maxLedger; // 0 here means no maxLedger + // }; + // + // =========================================================================== + xdr.struct("LedgerBounds", [["minLedger", xdr.lookup("Uint32")], ["maxLedger", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct PreconditionsV2 + // { + // TimeBounds* timeBounds; + // + // // Transaction only valid for ledger numbers n such that + // // minLedger <= n < maxLedger (if maxLedger == 0, then + // // only minLedger is checked) + // LedgerBounds* ledgerBounds; + // + // // If NULL, only valid when sourceAccount's sequence number + // // is seqNum - 1. Otherwise, valid when sourceAccount's + // // sequence number n satisfies minSeqNum <= n < tx.seqNum. + // // Note that after execution the account's sequence number + // // is always raised to tx.seqNum, and a transaction is not + // // valid if tx.seqNum is too high to ensure replay protection. + // SequenceNumber* minSeqNum; + // + // // For the transaction to be valid, the current ledger time must + // // be at least minSeqAge greater than sourceAccount's seqTime. + // Duration minSeqAge; + // + // // For the transaction to be valid, the current ledger number + // // must be at least minSeqLedgerGap greater than sourceAccount's + // // seqLedger. + // uint32 minSeqLedgerGap; + // + // // For the transaction to be valid, there must be a signature + // // corresponding to every Signer in this array, even if the + // // signature is not otherwise required by the sourceAccount or + // // operations. + // SignerKey extraSigners<2>; + // }; + // + // =========================================================================== + xdr.struct("PreconditionsV2", [["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["ledgerBounds", xdr.option(xdr.lookup("LedgerBounds"))], ["minSeqNum", xdr.option(xdr.lookup("SequenceNumber"))], ["minSeqAge", xdr.lookup("Duration")], ["minSeqLedgerGap", xdr.lookup("Uint32")], ["extraSigners", xdr.varArray(xdr.lookup("SignerKey"), 2)]]); + + // === xdr source ============================================================ + // + // enum PreconditionType + // { + // PRECOND_NONE = 0, + // PRECOND_TIME = 1, + // PRECOND_V2 = 2 + // }; + // + // =========================================================================== + xdr["enum"]("PreconditionType", { + precondNone: 0, + precondTime: 1, + precondV2: 2 + }); + + // === xdr source ============================================================ + // + // union Preconditions switch (PreconditionType type) + // { + // case PRECOND_NONE: + // void; + // case PRECOND_TIME: + // TimeBounds timeBounds; + // case PRECOND_V2: + // PreconditionsV2 v2; + // }; + // + // =========================================================================== + xdr.union("Preconditions", { + switchOn: xdr.lookup("PreconditionType"), + switchName: "type", + switches: [["precondNone", xdr["void"]()], ["precondTime", "timeBounds"], ["precondV2", "v2"]], + arms: { + timeBounds: xdr.lookup("TimeBounds"), + v2: xdr.lookup("PreconditionsV2") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerFootprint + // { + // LedgerKey readOnly<>; + // LedgerKey readWrite<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerFootprint", [["readOnly", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["readWrite", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)]]); + + // === xdr source ============================================================ + // + // enum ArchivalProofType + // { + // EXISTENCE = 0, + // NONEXISTENCE = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ArchivalProofType", { + existence: 0, + nonexistence: 1 + }); + + // === xdr source ============================================================ + // + // struct ArchivalProofNode + // { + // uint32 index; + // Hash hash; + // }; + // + // =========================================================================== + xdr.struct("ArchivalProofNode", [["index", xdr.lookup("Uint32")], ["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // typedef ArchivalProofNode ProofLevel<>; + // + // =========================================================================== + xdr.typedef("ProofLevel", xdr.varArray(xdr.lookup("ArchivalProofNode"), 2147483647)); + + // === xdr source ============================================================ + // + // struct NonexistenceProofBody + // { + // ColdArchiveBucketEntry entriesToProve<>; + // + // // Vector of vectors, where proofLevels[level] + // // contains all HashNodes that correspond with that level + // ProofLevel proofLevels<>; + // }; + // + // =========================================================================== + xdr.struct("NonexistenceProofBody", [["entriesToProve", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["proofLevels", xdr.varArray(xdr.lookup("ProofLevel"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct ExistenceProofBody + // { + // LedgerKey keysToProve<>; + // + // // Bounds for each key being proved, where bound[n] + // // corresponds to keysToProve[n] + // ColdArchiveBucketEntry lowBoundEntries<>; + // ColdArchiveBucketEntry highBoundEntries<>; + // + // // Vector of vectors, where proofLevels[level] + // // contains all HashNodes that correspond with that level + // ProofLevel proofLevels<>; + // }; + // + // =========================================================================== + xdr.struct("ExistenceProofBody", [["keysToProve", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["lowBoundEntries", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["highBoundEntries", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["proofLevels", xdr.varArray(xdr.lookup("ProofLevel"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union switch (ArchivalProofType t) + // { + // case EXISTENCE: + // NonexistenceProofBody nonexistenceProof; + // case NONEXISTENCE: + // ExistenceProofBody existenceProof; + // } + // + // =========================================================================== + xdr.union("ArchivalProofBody", { + switchOn: xdr.lookup("ArchivalProofType"), + switchName: "t", + switches: [["existence", "nonexistenceProof"], ["nonexistence", "existenceProof"]], + arms: { + nonexistenceProof: xdr.lookup("NonexistenceProofBody"), + existenceProof: xdr.lookup("ExistenceProofBody") + } + }); + + // === xdr source ============================================================ + // + // struct ArchivalProof + // { + // uint32 epoch; // AST Subtree for this proof + // + // union switch (ArchivalProofType t) + // { + // case EXISTENCE: + // NonexistenceProofBody nonexistenceProof; + // case NONEXISTENCE: + // ExistenceProofBody existenceProof; + // } body; + // }; + // + // =========================================================================== + xdr.struct("ArchivalProof", [["epoch", xdr.lookup("Uint32")], ["body", xdr.lookup("ArchivalProofBody")]]); + + // === xdr source ============================================================ + // + // struct SorobanResources + // { + // // The ledger footprint of the transaction. + // LedgerFootprint footprint; + // // The maximum number of instructions this transaction can use + // uint32 instructions; + // + // // The maximum number of bytes this transaction can read from ledger + // uint32 readBytes; + // // The maximum number of bytes this transaction can write to ledger + // uint32 writeBytes; + // }; + // + // =========================================================================== + xdr.struct("SorobanResources", [["footprint", xdr.lookup("LedgerFootprint")], ["instructions", xdr.lookup("Uint32")], ["readBytes", xdr.lookup("Uint32")], ["writeBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SorobanTransactionData + // { + // ExtensionPoint ext; + // SorobanResources resources; + // // Amount of the transaction `fee` allocated to the Soroban resource fees. + // // The fraction of `resourceFee` corresponding to `resources` specified + // // above is *not* refundable (i.e. fees for instructions, ledger I/O), as + // // well as fees for the transaction size. + // // The remaining part of the fee is refundable and the charged value is + // // based on the actual consumption of refundable resources (events, ledger + // // rent bumps). + // // The `inclusionFee` used for prioritization of the transaction is defined + // // as `tx.fee - resourceFee`. + // int64 resourceFee; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionData", [["ext", xdr.lookup("ExtensionPoint")], ["resources", xdr.lookup("SorobanResources")], ["resourceFee", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionV0Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionV0 + // { + // uint256 sourceAccountEd25519; + // uint32 fee; + // SequenceNumber seqNum; + // TimeBounds* timeBounds; + // Memo memo; + // Operation operations; + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionV0", [["sourceAccountEd25519", xdr.lookup("Uint256")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionV0Ext")]]); + + // === xdr source ============================================================ + // + // struct TransactionV0Envelope + // { + // TransactionV0 tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("TransactionV0Envelope", [["tx", xdr.lookup("TransactionV0")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionData sorobanData; + // } + // + // =========================================================================== + xdr.union("TransactionExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "sorobanData"]], + arms: { + sorobanData: xdr.lookup("SorobanTransactionData") + } + }); + + // === xdr source ============================================================ + // + // struct Transaction + // { + // // account used to run the transaction + // MuxedAccount sourceAccount; + // + // // the fee the sourceAccount will pay + // uint32 fee; + // + // // sequence number to consume in the account + // SequenceNumber seqNum; + // + // // validity conditions + // Preconditions cond; + // + // Memo memo; + // + // Operation operations; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionData sorobanData; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("Transaction", [["sourceAccount", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["cond", xdr.lookup("Preconditions")], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionExt")]]); + + // === xdr source ============================================================ + // + // struct TransactionV1Envelope + // { + // Transaction tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("TransactionV1Envelope", [["tx", xdr.lookup("Transaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // } + // + // =========================================================================== + xdr.union("FeeBumpTransactionInnerTx", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTx", "v1"]], + arms: { + v1: xdr.lookup("TransactionV1Envelope") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("FeeBumpTransactionExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct FeeBumpTransaction + // { + // MuxedAccount feeSource; + // int64 fee; + // union switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // } + // innerTx; + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("FeeBumpTransaction", [["feeSource", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Int64")], ["innerTx", xdr.lookup("FeeBumpTransactionInnerTx")], ["ext", xdr.lookup("FeeBumpTransactionExt")]]); + + // === xdr source ============================================================ + // + // struct FeeBumpTransactionEnvelope + // { + // FeeBumpTransaction tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("FeeBumpTransactionEnvelope", [["tx", xdr.lookup("FeeBumpTransaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union TransactionEnvelope switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX_V0: + // TransactionV0Envelope v0; + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransactionEnvelope feeBump; + // }; + // + // =========================================================================== + xdr.union("TransactionEnvelope", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTxV0", "v0"], ["envelopeTypeTx", "v1"], ["envelopeTypeTxFeeBump", "feeBump"]], + arms: { + v0: xdr.lookup("TransactionV0Envelope"), + v1: xdr.lookup("TransactionV1Envelope"), + feeBump: xdr.lookup("FeeBumpTransactionEnvelope") + } + }); + + // === xdr source ============================================================ + // + // union switch (EnvelopeType type) + // { + // // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // case ENVELOPE_TYPE_TX: + // Transaction tx; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransaction feeBump; + // } + // + // =========================================================================== + xdr.union("TransactionSignaturePayloadTaggedTransaction", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTx", "tx"], ["envelopeTypeTxFeeBump", "feeBump"]], + arms: { + tx: xdr.lookup("Transaction"), + feeBump: xdr.lookup("FeeBumpTransaction") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionSignaturePayload + // { + // Hash networkId; + // union switch (EnvelopeType type) + // { + // // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // case ENVELOPE_TYPE_TX: + // Transaction tx; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransaction feeBump; + // } + // taggedTransaction; + // }; + // + // =========================================================================== + xdr.struct("TransactionSignaturePayload", [["networkId", xdr.lookup("Hash")], ["taggedTransaction", xdr.lookup("TransactionSignaturePayloadTaggedTransaction")]]); + + // === xdr source ============================================================ + // + // enum ClaimAtomType + // { + // CLAIM_ATOM_TYPE_V0 = 0, + // CLAIM_ATOM_TYPE_ORDER_BOOK = 1, + // CLAIM_ATOM_TYPE_LIQUIDITY_POOL = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimAtomType", { + claimAtomTypeV0: 0, + claimAtomTypeOrderBook: 1, + claimAtomTypeLiquidityPool: 2 + }); + + // === xdr source ============================================================ + // + // struct ClaimOfferAtomV0 + // { + // // emitted to identify the offer + // uint256 sellerEd25519; // Account that owns the offer + // int64 offerID; + // + // // amount and asset taken from the owner + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the owner + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimOfferAtomV0", [["sellerEd25519", xdr.lookup("Uint256")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClaimOfferAtom + // { + // // emitted to identify the offer + // AccountID sellerID; // Account that owns the offer + // int64 offerID; + // + // // amount and asset taken from the owner + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the owner + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimOfferAtom", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClaimLiquidityAtom + // { + // PoolID liquidityPoolID; + // + // // amount and asset taken from the pool + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the pool + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimLiquidityAtom", [["liquidityPoolId", xdr.lookup("PoolId")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union ClaimAtom switch (ClaimAtomType type) + // { + // case CLAIM_ATOM_TYPE_V0: + // ClaimOfferAtomV0 v0; + // case CLAIM_ATOM_TYPE_ORDER_BOOK: + // ClaimOfferAtom orderBook; + // case CLAIM_ATOM_TYPE_LIQUIDITY_POOL: + // ClaimLiquidityAtom liquidityPool; + // }; + // + // =========================================================================== + xdr.union("ClaimAtom", { + switchOn: xdr.lookup("ClaimAtomType"), + switchName: "type", + switches: [["claimAtomTypeV0", "v0"], ["claimAtomTypeOrderBook", "orderBook"], ["claimAtomTypeLiquidityPool", "liquidityPool"]], + arms: { + v0: xdr.lookup("ClaimOfferAtomV0"), + orderBook: xdr.lookup("ClaimOfferAtom"), + liquidityPool: xdr.lookup("ClaimLiquidityAtom") + } + }); + + // === xdr source ============================================================ + // + // enum CreateAccountResultCode + // { + // // codes considered as "success" for the operation + // CREATE_ACCOUNT_SUCCESS = 0, // account was created + // + // // codes considered as "failure" for the operation + // CREATE_ACCOUNT_MALFORMED = -1, // invalid destination + // CREATE_ACCOUNT_UNDERFUNDED = -2, // not enough funds in source account + // CREATE_ACCOUNT_LOW_RESERVE = + // -3, // would create an account below the min reserve + // CREATE_ACCOUNT_ALREADY_EXIST = -4 // account already exists + // }; + // + // =========================================================================== + xdr["enum"]("CreateAccountResultCode", { + createAccountSuccess: 0, + createAccountMalformed: -1, + createAccountUnderfunded: -2, + createAccountLowReserve: -3, + createAccountAlreadyExist: -4 + }); + + // === xdr source ============================================================ + // + // union CreateAccountResult switch (CreateAccountResultCode code) + // { + // case CREATE_ACCOUNT_SUCCESS: + // void; + // case CREATE_ACCOUNT_MALFORMED: + // case CREATE_ACCOUNT_UNDERFUNDED: + // case CREATE_ACCOUNT_LOW_RESERVE: + // case CREATE_ACCOUNT_ALREADY_EXIST: + // void; + // }; + // + // =========================================================================== + xdr.union("CreateAccountResult", { + switchOn: xdr.lookup("CreateAccountResultCode"), + switchName: "code", + switches: [["createAccountSuccess", xdr["void"]()], ["createAccountMalformed", xdr["void"]()], ["createAccountUnderfunded", xdr["void"]()], ["createAccountLowReserve", xdr["void"]()], ["createAccountAlreadyExist", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum PaymentResultCode + // { + // // codes considered as "success" for the operation + // PAYMENT_SUCCESS = 0, // payment successfully completed + // + // // codes considered as "failure" for the operation + // PAYMENT_MALFORMED = -1, // bad input + // PAYMENT_UNDERFUNDED = -2, // not enough funds in source account + // PAYMENT_SRC_NO_TRUST = -3, // no trust line on source account + // PAYMENT_SRC_NOT_AUTHORIZED = -4, // source not authorized to transfer + // PAYMENT_NO_DESTINATION = -5, // destination account does not exist + // PAYMENT_NO_TRUST = -6, // destination missing a trust line for asset + // PAYMENT_NOT_AUTHORIZED = -7, // destination not authorized to hold asset + // PAYMENT_LINE_FULL = -8, // destination would go above their limit + // PAYMENT_NO_ISSUER = -9 // missing issuer on asset + // }; + // + // =========================================================================== + xdr["enum"]("PaymentResultCode", { + paymentSuccess: 0, + paymentMalformed: -1, + paymentUnderfunded: -2, + paymentSrcNoTrust: -3, + paymentSrcNotAuthorized: -4, + paymentNoDestination: -5, + paymentNoTrust: -6, + paymentNotAuthorized: -7, + paymentLineFull: -8, + paymentNoIssuer: -9 + }); + + // === xdr source ============================================================ + // + // union PaymentResult switch (PaymentResultCode code) + // { + // case PAYMENT_SUCCESS: + // void; + // case PAYMENT_MALFORMED: + // case PAYMENT_UNDERFUNDED: + // case PAYMENT_SRC_NO_TRUST: + // case PAYMENT_SRC_NOT_AUTHORIZED: + // case PAYMENT_NO_DESTINATION: + // case PAYMENT_NO_TRUST: + // case PAYMENT_NOT_AUTHORIZED: + // case PAYMENT_LINE_FULL: + // case PAYMENT_NO_ISSUER: + // void; + // }; + // + // =========================================================================== + xdr.union("PaymentResult", { + switchOn: xdr.lookup("PaymentResultCode"), + switchName: "code", + switches: [["paymentSuccess", xdr["void"]()], ["paymentMalformed", xdr["void"]()], ["paymentUnderfunded", xdr["void"]()], ["paymentSrcNoTrust", xdr["void"]()], ["paymentSrcNotAuthorized", xdr["void"]()], ["paymentNoDestination", xdr["void"]()], ["paymentNoTrust", xdr["void"]()], ["paymentNotAuthorized", xdr["void"]()], ["paymentLineFull", xdr["void"]()], ["paymentNoIssuer", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum PathPaymentStrictReceiveResultCode + // { + // // codes considered as "success" for the operation + // PATH_PAYMENT_STRICT_RECEIVE_SUCCESS = 0, // success + // + // // codes considered as "failure" for the operation + // PATH_PAYMENT_STRICT_RECEIVE_MALFORMED = -1, // bad input + // PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED = + // -2, // not enough funds in source account + // PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST = + // -3, // no trust line on source account + // PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED = + // -4, // source not authorized to transfer + // PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION = + // -5, // destination account does not exist + // PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST = + // -6, // dest missing a trust line for asset + // PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED = + // -7, // dest not authorized to hold asset + // PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL = + // -8, // dest would go above their limit + // PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER = -9, // missing issuer on one asset + // PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS = + // -10, // not enough offers to satisfy path + // PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF = + // -11, // would cross one of its own offers + // PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX = -12 // could not satisfy sendmax + // }; + // + // =========================================================================== + xdr["enum"]("PathPaymentStrictReceiveResultCode", { + pathPaymentStrictReceiveSuccess: 0, + pathPaymentStrictReceiveMalformed: -1, + pathPaymentStrictReceiveUnderfunded: -2, + pathPaymentStrictReceiveSrcNoTrust: -3, + pathPaymentStrictReceiveSrcNotAuthorized: -4, + pathPaymentStrictReceiveNoDestination: -5, + pathPaymentStrictReceiveNoTrust: -6, + pathPaymentStrictReceiveNotAuthorized: -7, + pathPaymentStrictReceiveLineFull: -8, + pathPaymentStrictReceiveNoIssuer: -9, + pathPaymentStrictReceiveTooFewOffers: -10, + pathPaymentStrictReceiveOfferCrossSelf: -11, + pathPaymentStrictReceiveOverSendmax: -12 + }); + + // === xdr source ============================================================ + // + // struct SimplePaymentResult + // { + // AccountID destination; + // Asset asset; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("SimplePaymentResult", [["destination", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } + // + // =========================================================================== + xdr.struct("PathPaymentStrictReceiveResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]); + + // === xdr source ============================================================ + // + // union PathPaymentStrictReceiveResult switch ( + // PathPaymentStrictReceiveResultCode code) + // { + // case PATH_PAYMENT_STRICT_RECEIVE_SUCCESS: + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } success; + // case PATH_PAYMENT_STRICT_RECEIVE_MALFORMED: + // case PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED: + // case PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST: + // case PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION: + // case PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST: + // case PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL: + // void; + // case PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER: + // Asset noIssuer; // the asset that caused the error + // case PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS: + // case PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF: + // case PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX: + // void; + // }; + // + // =========================================================================== + xdr.union("PathPaymentStrictReceiveResult", { + switchOn: xdr.lookup("PathPaymentStrictReceiveResultCode"), + switchName: "code", + switches: [["pathPaymentStrictReceiveSuccess", "success"], ["pathPaymentStrictReceiveMalformed", xdr["void"]()], ["pathPaymentStrictReceiveUnderfunded", xdr["void"]()], ["pathPaymentStrictReceiveSrcNoTrust", xdr["void"]()], ["pathPaymentStrictReceiveSrcNotAuthorized", xdr["void"]()], ["pathPaymentStrictReceiveNoDestination", xdr["void"]()], ["pathPaymentStrictReceiveNoTrust", xdr["void"]()], ["pathPaymentStrictReceiveNotAuthorized", xdr["void"]()], ["pathPaymentStrictReceiveLineFull", xdr["void"]()], ["pathPaymentStrictReceiveNoIssuer", "noIssuer"], ["pathPaymentStrictReceiveTooFewOffers", xdr["void"]()], ["pathPaymentStrictReceiveOfferCrossSelf", xdr["void"]()], ["pathPaymentStrictReceiveOverSendmax", xdr["void"]()]], + arms: { + success: xdr.lookup("PathPaymentStrictReceiveResultSuccess"), + noIssuer: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // enum PathPaymentStrictSendResultCode + // { + // // codes considered as "success" for the operation + // PATH_PAYMENT_STRICT_SEND_SUCCESS = 0, // success + // + // // codes considered as "failure" for the operation + // PATH_PAYMENT_STRICT_SEND_MALFORMED = -1, // bad input + // PATH_PAYMENT_STRICT_SEND_UNDERFUNDED = + // -2, // not enough funds in source account + // PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST = + // -3, // no trust line on source account + // PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED = + // -4, // source not authorized to transfer + // PATH_PAYMENT_STRICT_SEND_NO_DESTINATION = + // -5, // destination account does not exist + // PATH_PAYMENT_STRICT_SEND_NO_TRUST = + // -6, // dest missing a trust line for asset + // PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED = + // -7, // dest not authorized to hold asset + // PATH_PAYMENT_STRICT_SEND_LINE_FULL = -8, // dest would go above their limit + // PATH_PAYMENT_STRICT_SEND_NO_ISSUER = -9, // missing issuer on one asset + // PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS = + // -10, // not enough offers to satisfy path + // PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF = + // -11, // would cross one of its own offers + // PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN = -12 // could not satisfy destMin + // }; + // + // =========================================================================== + xdr["enum"]("PathPaymentStrictSendResultCode", { + pathPaymentStrictSendSuccess: 0, + pathPaymentStrictSendMalformed: -1, + pathPaymentStrictSendUnderfunded: -2, + pathPaymentStrictSendSrcNoTrust: -3, + pathPaymentStrictSendSrcNotAuthorized: -4, + pathPaymentStrictSendNoDestination: -5, + pathPaymentStrictSendNoTrust: -6, + pathPaymentStrictSendNotAuthorized: -7, + pathPaymentStrictSendLineFull: -8, + pathPaymentStrictSendNoIssuer: -9, + pathPaymentStrictSendTooFewOffers: -10, + pathPaymentStrictSendOfferCrossSelf: -11, + pathPaymentStrictSendUnderDestmin: -12 + }); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } + // + // =========================================================================== + xdr.struct("PathPaymentStrictSendResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]); + + // === xdr source ============================================================ + // + // union PathPaymentStrictSendResult switch (PathPaymentStrictSendResultCode code) + // { + // case PATH_PAYMENT_STRICT_SEND_SUCCESS: + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } success; + // case PATH_PAYMENT_STRICT_SEND_MALFORMED: + // case PATH_PAYMENT_STRICT_SEND_UNDERFUNDED: + // case PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST: + // case PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_SEND_NO_DESTINATION: + // case PATH_PAYMENT_STRICT_SEND_NO_TRUST: + // case PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_SEND_LINE_FULL: + // void; + // case PATH_PAYMENT_STRICT_SEND_NO_ISSUER: + // Asset noIssuer; // the asset that caused the error + // case PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS: + // case PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF: + // case PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN: + // void; + // }; + // + // =========================================================================== + xdr.union("PathPaymentStrictSendResult", { + switchOn: xdr.lookup("PathPaymentStrictSendResultCode"), + switchName: "code", + switches: [["pathPaymentStrictSendSuccess", "success"], ["pathPaymentStrictSendMalformed", xdr["void"]()], ["pathPaymentStrictSendUnderfunded", xdr["void"]()], ["pathPaymentStrictSendSrcNoTrust", xdr["void"]()], ["pathPaymentStrictSendSrcNotAuthorized", xdr["void"]()], ["pathPaymentStrictSendNoDestination", xdr["void"]()], ["pathPaymentStrictSendNoTrust", xdr["void"]()], ["pathPaymentStrictSendNotAuthorized", xdr["void"]()], ["pathPaymentStrictSendLineFull", xdr["void"]()], ["pathPaymentStrictSendNoIssuer", "noIssuer"], ["pathPaymentStrictSendTooFewOffers", xdr["void"]()], ["pathPaymentStrictSendOfferCrossSelf", xdr["void"]()], ["pathPaymentStrictSendUnderDestmin", xdr["void"]()]], + arms: { + success: xdr.lookup("PathPaymentStrictSendResultSuccess"), + noIssuer: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // enum ManageSellOfferResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_SELL_OFFER_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // MANAGE_SELL_OFFER_MALFORMED = -1, // generated offer would be invalid + // MANAGE_SELL_OFFER_SELL_NO_TRUST = + // -2, // no trust line for what we're selling + // MANAGE_SELL_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying + // MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell + // MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy + // MANAGE_SELL_OFFER_LINE_FULL = -6, // can't receive more of what it's buying + // MANAGE_SELL_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell + // MANAGE_SELL_OFFER_CROSS_SELF = + // -8, // would cross an offer from the same user + // MANAGE_SELL_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling + // MANAGE_SELL_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying + // + // // update errors + // MANAGE_SELL_OFFER_NOT_FOUND = + // -11, // offerID does not match an existing offer + // + // MANAGE_SELL_OFFER_LOW_RESERVE = + // -12 // not enough funds to create a new Offer + // }; + // + // =========================================================================== + xdr["enum"]("ManageSellOfferResultCode", { + manageSellOfferSuccess: 0, + manageSellOfferMalformed: -1, + manageSellOfferSellNoTrust: -2, + manageSellOfferBuyNoTrust: -3, + manageSellOfferSellNotAuthorized: -4, + manageSellOfferBuyNotAuthorized: -5, + manageSellOfferLineFull: -6, + manageSellOfferUnderfunded: -7, + manageSellOfferCrossSelf: -8, + manageSellOfferSellNoIssuer: -9, + manageSellOfferBuyNoIssuer: -10, + manageSellOfferNotFound: -11, + manageSellOfferLowReserve: -12 + }); + + // === xdr source ============================================================ + // + // enum ManageOfferEffect + // { + // MANAGE_OFFER_CREATED = 0, + // MANAGE_OFFER_UPDATED = 1, + // MANAGE_OFFER_DELETED = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ManageOfferEffect", { + manageOfferCreated: 0, + manageOfferUpdated: 1, + manageOfferDeleted: 2 + }); + + // === xdr source ============================================================ + // + // union switch (ManageOfferEffect effect) + // { + // case MANAGE_OFFER_CREATED: + // case MANAGE_OFFER_UPDATED: + // OfferEntry offer; + // case MANAGE_OFFER_DELETED: + // void; + // } + // + // =========================================================================== + xdr.union("ManageOfferSuccessResultOffer", { + switchOn: xdr.lookup("ManageOfferEffect"), + switchName: "effect", + switches: [["manageOfferCreated", "offer"], ["manageOfferUpdated", "offer"], ["manageOfferDeleted", xdr["void"]()]], + arms: { + offer: xdr.lookup("OfferEntry") + } + }); + + // === xdr source ============================================================ + // + // struct ManageOfferSuccessResult + // { + // // offers that got claimed while creating this offer + // ClaimAtom offersClaimed<>; + // + // union switch (ManageOfferEffect effect) + // { + // case MANAGE_OFFER_CREATED: + // case MANAGE_OFFER_UPDATED: + // OfferEntry offer; + // case MANAGE_OFFER_DELETED: + // void; + // } + // offer; + // }; + // + // =========================================================================== + xdr.struct("ManageOfferSuccessResult", [["offersClaimed", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["offer", xdr.lookup("ManageOfferSuccessResultOffer")]]); + + // === xdr source ============================================================ + // + // union ManageSellOfferResult switch (ManageSellOfferResultCode code) + // { + // case MANAGE_SELL_OFFER_SUCCESS: + // ManageOfferSuccessResult success; + // case MANAGE_SELL_OFFER_MALFORMED: + // case MANAGE_SELL_OFFER_SELL_NO_TRUST: + // case MANAGE_SELL_OFFER_BUY_NO_TRUST: + // case MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED: + // case MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED: + // case MANAGE_SELL_OFFER_LINE_FULL: + // case MANAGE_SELL_OFFER_UNDERFUNDED: + // case MANAGE_SELL_OFFER_CROSS_SELF: + // case MANAGE_SELL_OFFER_SELL_NO_ISSUER: + // case MANAGE_SELL_OFFER_BUY_NO_ISSUER: + // case MANAGE_SELL_OFFER_NOT_FOUND: + // case MANAGE_SELL_OFFER_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageSellOfferResult", { + switchOn: xdr.lookup("ManageSellOfferResultCode"), + switchName: "code", + switches: [["manageSellOfferSuccess", "success"], ["manageSellOfferMalformed", xdr["void"]()], ["manageSellOfferSellNoTrust", xdr["void"]()], ["manageSellOfferBuyNoTrust", xdr["void"]()], ["manageSellOfferSellNotAuthorized", xdr["void"]()], ["manageSellOfferBuyNotAuthorized", xdr["void"]()], ["manageSellOfferLineFull", xdr["void"]()], ["manageSellOfferUnderfunded", xdr["void"]()], ["manageSellOfferCrossSelf", xdr["void"]()], ["manageSellOfferSellNoIssuer", xdr["void"]()], ["manageSellOfferBuyNoIssuer", xdr["void"]()], ["manageSellOfferNotFound", xdr["void"]()], ["manageSellOfferLowReserve", xdr["void"]()]], + arms: { + success: xdr.lookup("ManageOfferSuccessResult") + } + }); + + // === xdr source ============================================================ + // + // enum ManageBuyOfferResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_BUY_OFFER_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // MANAGE_BUY_OFFER_MALFORMED = -1, // generated offer would be invalid + // MANAGE_BUY_OFFER_SELL_NO_TRUST = -2, // no trust line for what we're selling + // MANAGE_BUY_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying + // MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell + // MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy + // MANAGE_BUY_OFFER_LINE_FULL = -6, // can't receive more of what it's buying + // MANAGE_BUY_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell + // MANAGE_BUY_OFFER_CROSS_SELF = -8, // would cross an offer from the same user + // MANAGE_BUY_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling + // MANAGE_BUY_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying + // + // // update errors + // MANAGE_BUY_OFFER_NOT_FOUND = + // -11, // offerID does not match an existing offer + // + // MANAGE_BUY_OFFER_LOW_RESERVE = -12 // not enough funds to create a new Offer + // }; + // + // =========================================================================== + xdr["enum"]("ManageBuyOfferResultCode", { + manageBuyOfferSuccess: 0, + manageBuyOfferMalformed: -1, + manageBuyOfferSellNoTrust: -2, + manageBuyOfferBuyNoTrust: -3, + manageBuyOfferSellNotAuthorized: -4, + manageBuyOfferBuyNotAuthorized: -5, + manageBuyOfferLineFull: -6, + manageBuyOfferUnderfunded: -7, + manageBuyOfferCrossSelf: -8, + manageBuyOfferSellNoIssuer: -9, + manageBuyOfferBuyNoIssuer: -10, + manageBuyOfferNotFound: -11, + manageBuyOfferLowReserve: -12 + }); + + // === xdr source ============================================================ + // + // union ManageBuyOfferResult switch (ManageBuyOfferResultCode code) + // { + // case MANAGE_BUY_OFFER_SUCCESS: + // ManageOfferSuccessResult success; + // case MANAGE_BUY_OFFER_MALFORMED: + // case MANAGE_BUY_OFFER_SELL_NO_TRUST: + // case MANAGE_BUY_OFFER_BUY_NO_TRUST: + // case MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED: + // case MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED: + // case MANAGE_BUY_OFFER_LINE_FULL: + // case MANAGE_BUY_OFFER_UNDERFUNDED: + // case MANAGE_BUY_OFFER_CROSS_SELF: + // case MANAGE_BUY_OFFER_SELL_NO_ISSUER: + // case MANAGE_BUY_OFFER_BUY_NO_ISSUER: + // case MANAGE_BUY_OFFER_NOT_FOUND: + // case MANAGE_BUY_OFFER_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageBuyOfferResult", { + switchOn: xdr.lookup("ManageBuyOfferResultCode"), + switchName: "code", + switches: [["manageBuyOfferSuccess", "success"], ["manageBuyOfferMalformed", xdr["void"]()], ["manageBuyOfferSellNoTrust", xdr["void"]()], ["manageBuyOfferBuyNoTrust", xdr["void"]()], ["manageBuyOfferSellNotAuthorized", xdr["void"]()], ["manageBuyOfferBuyNotAuthorized", xdr["void"]()], ["manageBuyOfferLineFull", xdr["void"]()], ["manageBuyOfferUnderfunded", xdr["void"]()], ["manageBuyOfferCrossSelf", xdr["void"]()], ["manageBuyOfferSellNoIssuer", xdr["void"]()], ["manageBuyOfferBuyNoIssuer", xdr["void"]()], ["manageBuyOfferNotFound", xdr["void"]()], ["manageBuyOfferLowReserve", xdr["void"]()]], + arms: { + success: xdr.lookup("ManageOfferSuccessResult") + } + }); + + // === xdr source ============================================================ + // + // enum SetOptionsResultCode + // { + // // codes considered as "success" for the operation + // SET_OPTIONS_SUCCESS = 0, + // // codes considered as "failure" for the operation + // SET_OPTIONS_LOW_RESERVE = -1, // not enough funds to add a signer + // SET_OPTIONS_TOO_MANY_SIGNERS = -2, // max number of signers already reached + // SET_OPTIONS_BAD_FLAGS = -3, // invalid combination of clear/set flags + // SET_OPTIONS_INVALID_INFLATION = -4, // inflation account does not exist + // SET_OPTIONS_CANT_CHANGE = -5, // can no longer change this option + // SET_OPTIONS_UNKNOWN_FLAG = -6, // can't set an unknown flag + // SET_OPTIONS_THRESHOLD_OUT_OF_RANGE = -7, // bad value for weight/threshold + // SET_OPTIONS_BAD_SIGNER = -8, // signer cannot be masterkey + // SET_OPTIONS_INVALID_HOME_DOMAIN = -9, // malformed home domain + // SET_OPTIONS_AUTH_REVOCABLE_REQUIRED = + // -10 // auth revocable is required for clawback + // }; + // + // =========================================================================== + xdr["enum"]("SetOptionsResultCode", { + setOptionsSuccess: 0, + setOptionsLowReserve: -1, + setOptionsTooManySigners: -2, + setOptionsBadFlags: -3, + setOptionsInvalidInflation: -4, + setOptionsCantChange: -5, + setOptionsUnknownFlag: -6, + setOptionsThresholdOutOfRange: -7, + setOptionsBadSigner: -8, + setOptionsInvalidHomeDomain: -9, + setOptionsAuthRevocableRequired: -10 + }); + + // === xdr source ============================================================ + // + // union SetOptionsResult switch (SetOptionsResultCode code) + // { + // case SET_OPTIONS_SUCCESS: + // void; + // case SET_OPTIONS_LOW_RESERVE: + // case SET_OPTIONS_TOO_MANY_SIGNERS: + // case SET_OPTIONS_BAD_FLAGS: + // case SET_OPTIONS_INVALID_INFLATION: + // case SET_OPTIONS_CANT_CHANGE: + // case SET_OPTIONS_UNKNOWN_FLAG: + // case SET_OPTIONS_THRESHOLD_OUT_OF_RANGE: + // case SET_OPTIONS_BAD_SIGNER: + // case SET_OPTIONS_INVALID_HOME_DOMAIN: + // case SET_OPTIONS_AUTH_REVOCABLE_REQUIRED: + // void; + // }; + // + // =========================================================================== + xdr.union("SetOptionsResult", { + switchOn: xdr.lookup("SetOptionsResultCode"), + switchName: "code", + switches: [["setOptionsSuccess", xdr["void"]()], ["setOptionsLowReserve", xdr["void"]()], ["setOptionsTooManySigners", xdr["void"]()], ["setOptionsBadFlags", xdr["void"]()], ["setOptionsInvalidInflation", xdr["void"]()], ["setOptionsCantChange", xdr["void"]()], ["setOptionsUnknownFlag", xdr["void"]()], ["setOptionsThresholdOutOfRange", xdr["void"]()], ["setOptionsBadSigner", xdr["void"]()], ["setOptionsInvalidHomeDomain", xdr["void"]()], ["setOptionsAuthRevocableRequired", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ChangeTrustResultCode + // { + // // codes considered as "success" for the operation + // CHANGE_TRUST_SUCCESS = 0, + // // codes considered as "failure" for the operation + // CHANGE_TRUST_MALFORMED = -1, // bad input + // CHANGE_TRUST_NO_ISSUER = -2, // could not find issuer + // CHANGE_TRUST_INVALID_LIMIT = -3, // cannot drop limit below balance + // // cannot create with a limit of 0 + // CHANGE_TRUST_LOW_RESERVE = + // -4, // not enough funds to create a new trust line, + // CHANGE_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed + // CHANGE_TRUST_TRUST_LINE_MISSING = -6, // Asset trustline is missing for pool + // CHANGE_TRUST_CANNOT_DELETE = + // -7, // Asset trustline is still referenced in a pool + // CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES = + // -8 // Asset trustline is deauthorized + // }; + // + // =========================================================================== + xdr["enum"]("ChangeTrustResultCode", { + changeTrustSuccess: 0, + changeTrustMalformed: -1, + changeTrustNoIssuer: -2, + changeTrustInvalidLimit: -3, + changeTrustLowReserve: -4, + changeTrustSelfNotAllowed: -5, + changeTrustTrustLineMissing: -6, + changeTrustCannotDelete: -7, + changeTrustNotAuthMaintainLiabilities: -8 + }); + + // === xdr source ============================================================ + // + // union ChangeTrustResult switch (ChangeTrustResultCode code) + // { + // case CHANGE_TRUST_SUCCESS: + // void; + // case CHANGE_TRUST_MALFORMED: + // case CHANGE_TRUST_NO_ISSUER: + // case CHANGE_TRUST_INVALID_LIMIT: + // case CHANGE_TRUST_LOW_RESERVE: + // case CHANGE_TRUST_SELF_NOT_ALLOWED: + // case CHANGE_TRUST_TRUST_LINE_MISSING: + // case CHANGE_TRUST_CANNOT_DELETE: + // case CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES: + // void; + // }; + // + // =========================================================================== + xdr.union("ChangeTrustResult", { + switchOn: xdr.lookup("ChangeTrustResultCode"), + switchName: "code", + switches: [["changeTrustSuccess", xdr["void"]()], ["changeTrustMalformed", xdr["void"]()], ["changeTrustNoIssuer", xdr["void"]()], ["changeTrustInvalidLimit", xdr["void"]()], ["changeTrustLowReserve", xdr["void"]()], ["changeTrustSelfNotAllowed", xdr["void"]()], ["changeTrustTrustLineMissing", xdr["void"]()], ["changeTrustCannotDelete", xdr["void"]()], ["changeTrustNotAuthMaintainLiabilities", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum AllowTrustResultCode + // { + // // codes considered as "success" for the operation + // ALLOW_TRUST_SUCCESS = 0, + // // codes considered as "failure" for the operation + // ALLOW_TRUST_MALFORMED = -1, // asset is not ASSET_TYPE_ALPHANUM + // ALLOW_TRUST_NO_TRUST_LINE = -2, // trustor does not have a trustline + // // source account does not require trust + // ALLOW_TRUST_TRUST_NOT_REQUIRED = -3, + // ALLOW_TRUST_CANT_REVOKE = -4, // source account can't revoke trust, + // ALLOW_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed + // ALLOW_TRUST_LOW_RESERVE = -6 // claimable balances can't be created + // // on revoke due to low reserves + // }; + // + // =========================================================================== + xdr["enum"]("AllowTrustResultCode", { + allowTrustSuccess: 0, + allowTrustMalformed: -1, + allowTrustNoTrustLine: -2, + allowTrustTrustNotRequired: -3, + allowTrustCantRevoke: -4, + allowTrustSelfNotAllowed: -5, + allowTrustLowReserve: -6 + }); + + // === xdr source ============================================================ + // + // union AllowTrustResult switch (AllowTrustResultCode code) + // { + // case ALLOW_TRUST_SUCCESS: + // void; + // case ALLOW_TRUST_MALFORMED: + // case ALLOW_TRUST_NO_TRUST_LINE: + // case ALLOW_TRUST_TRUST_NOT_REQUIRED: + // case ALLOW_TRUST_CANT_REVOKE: + // case ALLOW_TRUST_SELF_NOT_ALLOWED: + // case ALLOW_TRUST_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("AllowTrustResult", { + switchOn: xdr.lookup("AllowTrustResultCode"), + switchName: "code", + switches: [["allowTrustSuccess", xdr["void"]()], ["allowTrustMalformed", xdr["void"]()], ["allowTrustNoTrustLine", xdr["void"]()], ["allowTrustTrustNotRequired", xdr["void"]()], ["allowTrustCantRevoke", xdr["void"]()], ["allowTrustSelfNotAllowed", xdr["void"]()], ["allowTrustLowReserve", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum AccountMergeResultCode + // { + // // codes considered as "success" for the operation + // ACCOUNT_MERGE_SUCCESS = 0, + // // codes considered as "failure" for the operation + // ACCOUNT_MERGE_MALFORMED = -1, // can't merge onto itself + // ACCOUNT_MERGE_NO_ACCOUNT = -2, // destination does not exist + // ACCOUNT_MERGE_IMMUTABLE_SET = -3, // source account has AUTH_IMMUTABLE set + // ACCOUNT_MERGE_HAS_SUB_ENTRIES = -4, // account has trust lines/offers + // ACCOUNT_MERGE_SEQNUM_TOO_FAR = -5, // sequence number is over max allowed + // ACCOUNT_MERGE_DEST_FULL = -6, // can't add source balance to + // // destination balance + // ACCOUNT_MERGE_IS_SPONSOR = -7 // can't merge account that is a sponsor + // }; + // + // =========================================================================== + xdr["enum"]("AccountMergeResultCode", { + accountMergeSuccess: 0, + accountMergeMalformed: -1, + accountMergeNoAccount: -2, + accountMergeImmutableSet: -3, + accountMergeHasSubEntries: -4, + accountMergeSeqnumTooFar: -5, + accountMergeDestFull: -6, + accountMergeIsSponsor: -7 + }); + + // === xdr source ============================================================ + // + // union AccountMergeResult switch (AccountMergeResultCode code) + // { + // case ACCOUNT_MERGE_SUCCESS: + // int64 sourceAccountBalance; // how much got transferred from source account + // case ACCOUNT_MERGE_MALFORMED: + // case ACCOUNT_MERGE_NO_ACCOUNT: + // case ACCOUNT_MERGE_IMMUTABLE_SET: + // case ACCOUNT_MERGE_HAS_SUB_ENTRIES: + // case ACCOUNT_MERGE_SEQNUM_TOO_FAR: + // case ACCOUNT_MERGE_DEST_FULL: + // case ACCOUNT_MERGE_IS_SPONSOR: + // void; + // }; + // + // =========================================================================== + xdr.union("AccountMergeResult", { + switchOn: xdr.lookup("AccountMergeResultCode"), + switchName: "code", + switches: [["accountMergeSuccess", "sourceAccountBalance"], ["accountMergeMalformed", xdr["void"]()], ["accountMergeNoAccount", xdr["void"]()], ["accountMergeImmutableSet", xdr["void"]()], ["accountMergeHasSubEntries", xdr["void"]()], ["accountMergeSeqnumTooFar", xdr["void"]()], ["accountMergeDestFull", xdr["void"]()], ["accountMergeIsSponsor", xdr["void"]()]], + arms: { + sourceAccountBalance: xdr.lookup("Int64") + } + }); + + // === xdr source ============================================================ + // + // enum InflationResultCode + // { + // // codes considered as "success" for the operation + // INFLATION_SUCCESS = 0, + // // codes considered as "failure" for the operation + // INFLATION_NOT_TIME = -1 + // }; + // + // =========================================================================== + xdr["enum"]("InflationResultCode", { + inflationSuccess: 0, + inflationNotTime: -1 + }); + + // === xdr source ============================================================ + // + // struct InflationPayout // or use PaymentResultAtom to limit types? + // { + // AccountID destination; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("InflationPayout", [["destination", xdr.lookup("AccountId")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union InflationResult switch (InflationResultCode code) + // { + // case INFLATION_SUCCESS: + // InflationPayout payouts<>; + // case INFLATION_NOT_TIME: + // void; + // }; + // + // =========================================================================== + xdr.union("InflationResult", { + switchOn: xdr.lookup("InflationResultCode"), + switchName: "code", + switches: [["inflationSuccess", "payouts"], ["inflationNotTime", xdr["void"]()]], + arms: { + payouts: xdr.varArray(xdr.lookup("InflationPayout"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // enum ManageDataResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_DATA_SUCCESS = 0, + // // codes considered as "failure" for the operation + // MANAGE_DATA_NOT_SUPPORTED_YET = + // -1, // The network hasn't moved to this protocol change yet + // MANAGE_DATA_NAME_NOT_FOUND = + // -2, // Trying to remove a Data Entry that isn't there + // MANAGE_DATA_LOW_RESERVE = -3, // not enough funds to create a new Data Entry + // MANAGE_DATA_INVALID_NAME = -4 // Name not a valid string + // }; + // + // =========================================================================== + xdr["enum"]("ManageDataResultCode", { + manageDataSuccess: 0, + manageDataNotSupportedYet: -1, + manageDataNameNotFound: -2, + manageDataLowReserve: -3, + manageDataInvalidName: -4 + }); + + // === xdr source ============================================================ + // + // union ManageDataResult switch (ManageDataResultCode code) + // { + // case MANAGE_DATA_SUCCESS: + // void; + // case MANAGE_DATA_NOT_SUPPORTED_YET: + // case MANAGE_DATA_NAME_NOT_FOUND: + // case MANAGE_DATA_LOW_RESERVE: + // case MANAGE_DATA_INVALID_NAME: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageDataResult", { + switchOn: xdr.lookup("ManageDataResultCode"), + switchName: "code", + switches: [["manageDataSuccess", xdr["void"]()], ["manageDataNotSupportedYet", xdr["void"]()], ["manageDataNameNotFound", xdr["void"]()], ["manageDataLowReserve", xdr["void"]()], ["manageDataInvalidName", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum BumpSequenceResultCode + // { + // // codes considered as "success" for the operation + // BUMP_SEQUENCE_SUCCESS = 0, + // // codes considered as "failure" for the operation + // BUMP_SEQUENCE_BAD_SEQ = -1 // `bumpTo` is not within bounds + // }; + // + // =========================================================================== + xdr["enum"]("BumpSequenceResultCode", { + bumpSequenceSuccess: 0, + bumpSequenceBadSeq: -1 + }); + + // === xdr source ============================================================ + // + // union BumpSequenceResult switch (BumpSequenceResultCode code) + // { + // case BUMP_SEQUENCE_SUCCESS: + // void; + // case BUMP_SEQUENCE_BAD_SEQ: + // void; + // }; + // + // =========================================================================== + xdr.union("BumpSequenceResult", { + switchOn: xdr.lookup("BumpSequenceResultCode"), + switchName: "code", + switches: [["bumpSequenceSuccess", xdr["void"]()], ["bumpSequenceBadSeq", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum CreateClaimableBalanceResultCode + // { + // CREATE_CLAIMABLE_BALANCE_SUCCESS = 0, + // CREATE_CLAIMABLE_BALANCE_MALFORMED = -1, + // CREATE_CLAIMABLE_BALANCE_LOW_RESERVE = -2, + // CREATE_CLAIMABLE_BALANCE_NO_TRUST = -3, + // CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -4, + // CREATE_CLAIMABLE_BALANCE_UNDERFUNDED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("CreateClaimableBalanceResultCode", { + createClaimableBalanceSuccess: 0, + createClaimableBalanceMalformed: -1, + createClaimableBalanceLowReserve: -2, + createClaimableBalanceNoTrust: -3, + createClaimableBalanceNotAuthorized: -4, + createClaimableBalanceUnderfunded: -5 + }); + + // === xdr source ============================================================ + // + // union CreateClaimableBalanceResult switch ( + // CreateClaimableBalanceResultCode code) + // { + // case CREATE_CLAIMABLE_BALANCE_SUCCESS: + // ClaimableBalanceID balanceID; + // case CREATE_CLAIMABLE_BALANCE_MALFORMED: + // case CREATE_CLAIMABLE_BALANCE_LOW_RESERVE: + // case CREATE_CLAIMABLE_BALANCE_NO_TRUST: + // case CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED: + // case CREATE_CLAIMABLE_BALANCE_UNDERFUNDED: + // void; + // }; + // + // =========================================================================== + xdr.union("CreateClaimableBalanceResult", { + switchOn: xdr.lookup("CreateClaimableBalanceResultCode"), + switchName: "code", + switches: [["createClaimableBalanceSuccess", "balanceId"], ["createClaimableBalanceMalformed", xdr["void"]()], ["createClaimableBalanceLowReserve", xdr["void"]()], ["createClaimableBalanceNoTrust", xdr["void"]()], ["createClaimableBalanceNotAuthorized", xdr["void"]()], ["createClaimableBalanceUnderfunded", xdr["void"]()]], + arms: { + balanceId: xdr.lookup("ClaimableBalanceId") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimClaimableBalanceResultCode + // { + // CLAIM_CLAIMABLE_BALANCE_SUCCESS = 0, + // CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1, + // CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM = -2, + // CLAIM_CLAIMABLE_BALANCE_LINE_FULL = -3, + // CLAIM_CLAIMABLE_BALANCE_NO_TRUST = -4, + // CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimClaimableBalanceResultCode", { + claimClaimableBalanceSuccess: 0, + claimClaimableBalanceDoesNotExist: -1, + claimClaimableBalanceCannotClaim: -2, + claimClaimableBalanceLineFull: -3, + claimClaimableBalanceNoTrust: -4, + claimClaimableBalanceNotAuthorized: -5 + }); + + // === xdr source ============================================================ + // + // union ClaimClaimableBalanceResult switch (ClaimClaimableBalanceResultCode code) + // { + // case CLAIM_CLAIMABLE_BALANCE_SUCCESS: + // void; + // case CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST: + // case CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM: + // case CLAIM_CLAIMABLE_BALANCE_LINE_FULL: + // case CLAIM_CLAIMABLE_BALANCE_NO_TRUST: + // case CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClaimClaimableBalanceResult", { + switchOn: xdr.lookup("ClaimClaimableBalanceResultCode"), + switchName: "code", + switches: [["claimClaimableBalanceSuccess", xdr["void"]()], ["claimClaimableBalanceDoesNotExist", xdr["void"]()], ["claimClaimableBalanceCannotClaim", xdr["void"]()], ["claimClaimableBalanceLineFull", xdr["void"]()], ["claimClaimableBalanceNoTrust", xdr["void"]()], ["claimClaimableBalanceNotAuthorized", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum BeginSponsoringFutureReservesResultCode + // { + // // codes considered as "success" for the operation + // BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED = -1, + // BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED = -2, + // BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("BeginSponsoringFutureReservesResultCode", { + beginSponsoringFutureReservesSuccess: 0, + beginSponsoringFutureReservesMalformed: -1, + beginSponsoringFutureReservesAlreadySponsored: -2, + beginSponsoringFutureReservesRecursive: -3 + }); + + // === xdr source ============================================================ + // + // union BeginSponsoringFutureReservesResult switch ( + // BeginSponsoringFutureReservesResultCode code) + // { + // case BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS: + // void; + // case BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED: + // case BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED: + // case BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE: + // void; + // }; + // + // =========================================================================== + xdr.union("BeginSponsoringFutureReservesResult", { + switchOn: xdr.lookup("BeginSponsoringFutureReservesResultCode"), + switchName: "code", + switches: [["beginSponsoringFutureReservesSuccess", xdr["void"]()], ["beginSponsoringFutureReservesMalformed", xdr["void"]()], ["beginSponsoringFutureReservesAlreadySponsored", xdr["void"]()], ["beginSponsoringFutureReservesRecursive", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum EndSponsoringFutureReservesResultCode + // { + // // codes considered as "success" for the operation + // END_SPONSORING_FUTURE_RESERVES_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED = -1 + // }; + // + // =========================================================================== + xdr["enum"]("EndSponsoringFutureReservesResultCode", { + endSponsoringFutureReservesSuccess: 0, + endSponsoringFutureReservesNotSponsored: -1 + }); + + // === xdr source ============================================================ + // + // union EndSponsoringFutureReservesResult switch ( + // EndSponsoringFutureReservesResultCode code) + // { + // case END_SPONSORING_FUTURE_RESERVES_SUCCESS: + // void; + // case END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED: + // void; + // }; + // + // =========================================================================== + xdr.union("EndSponsoringFutureReservesResult", { + switchOn: xdr.lookup("EndSponsoringFutureReservesResultCode"), + switchName: "code", + switches: [["endSponsoringFutureReservesSuccess", xdr["void"]()], ["endSponsoringFutureReservesNotSponsored", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum RevokeSponsorshipResultCode + // { + // // codes considered as "success" for the operation + // REVOKE_SPONSORSHIP_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // REVOKE_SPONSORSHIP_DOES_NOT_EXIST = -1, + // REVOKE_SPONSORSHIP_NOT_SPONSOR = -2, + // REVOKE_SPONSORSHIP_LOW_RESERVE = -3, + // REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE = -4, + // REVOKE_SPONSORSHIP_MALFORMED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("RevokeSponsorshipResultCode", { + revokeSponsorshipSuccess: 0, + revokeSponsorshipDoesNotExist: -1, + revokeSponsorshipNotSponsor: -2, + revokeSponsorshipLowReserve: -3, + revokeSponsorshipOnlyTransferable: -4, + revokeSponsorshipMalformed: -5 + }); + + // === xdr source ============================================================ + // + // union RevokeSponsorshipResult switch (RevokeSponsorshipResultCode code) + // { + // case REVOKE_SPONSORSHIP_SUCCESS: + // void; + // case REVOKE_SPONSORSHIP_DOES_NOT_EXIST: + // case REVOKE_SPONSORSHIP_NOT_SPONSOR: + // case REVOKE_SPONSORSHIP_LOW_RESERVE: + // case REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE: + // case REVOKE_SPONSORSHIP_MALFORMED: + // void; + // }; + // + // =========================================================================== + xdr.union("RevokeSponsorshipResult", { + switchOn: xdr.lookup("RevokeSponsorshipResultCode"), + switchName: "code", + switches: [["revokeSponsorshipSuccess", xdr["void"]()], ["revokeSponsorshipDoesNotExist", xdr["void"]()], ["revokeSponsorshipNotSponsor", xdr["void"]()], ["revokeSponsorshipLowReserve", xdr["void"]()], ["revokeSponsorshipOnlyTransferable", xdr["void"]()], ["revokeSponsorshipMalformed", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ClawbackResultCode + // { + // // codes considered as "success" for the operation + // CLAWBACK_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // CLAWBACK_MALFORMED = -1, + // CLAWBACK_NOT_CLAWBACK_ENABLED = -2, + // CLAWBACK_NO_TRUST = -3, + // CLAWBACK_UNDERFUNDED = -4 + // }; + // + // =========================================================================== + xdr["enum"]("ClawbackResultCode", { + clawbackSuccess: 0, + clawbackMalformed: -1, + clawbackNotClawbackEnabled: -2, + clawbackNoTrust: -3, + clawbackUnderfunded: -4 + }); + + // === xdr source ============================================================ + // + // union ClawbackResult switch (ClawbackResultCode code) + // { + // case CLAWBACK_SUCCESS: + // void; + // case CLAWBACK_MALFORMED: + // case CLAWBACK_NOT_CLAWBACK_ENABLED: + // case CLAWBACK_NO_TRUST: + // case CLAWBACK_UNDERFUNDED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClawbackResult", { + switchOn: xdr.lookup("ClawbackResultCode"), + switchName: "code", + switches: [["clawbackSuccess", xdr["void"]()], ["clawbackMalformed", xdr["void"]()], ["clawbackNotClawbackEnabled", xdr["void"]()], ["clawbackNoTrust", xdr["void"]()], ["clawbackUnderfunded", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ClawbackClaimableBalanceResultCode + // { + // // codes considered as "success" for the operation + // CLAWBACK_CLAIMABLE_BALANCE_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1, + // CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER = -2, + // CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED = -3 + // }; + // + // =========================================================================== + xdr["enum"]("ClawbackClaimableBalanceResultCode", { + clawbackClaimableBalanceSuccess: 0, + clawbackClaimableBalanceDoesNotExist: -1, + clawbackClaimableBalanceNotIssuer: -2, + clawbackClaimableBalanceNotClawbackEnabled: -3 + }); + + // === xdr source ============================================================ + // + // union ClawbackClaimableBalanceResult switch ( + // ClawbackClaimableBalanceResultCode code) + // { + // case CLAWBACK_CLAIMABLE_BALANCE_SUCCESS: + // void; + // case CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST: + // case CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER: + // case CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClawbackClaimableBalanceResult", { + switchOn: xdr.lookup("ClawbackClaimableBalanceResultCode"), + switchName: "code", + switches: [["clawbackClaimableBalanceSuccess", xdr["void"]()], ["clawbackClaimableBalanceDoesNotExist", xdr["void"]()], ["clawbackClaimableBalanceNotIssuer", xdr["void"]()], ["clawbackClaimableBalanceNotClawbackEnabled", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum SetTrustLineFlagsResultCode + // { + // // codes considered as "success" for the operation + // SET_TRUST_LINE_FLAGS_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // SET_TRUST_LINE_FLAGS_MALFORMED = -1, + // SET_TRUST_LINE_FLAGS_NO_TRUST_LINE = -2, + // SET_TRUST_LINE_FLAGS_CANT_REVOKE = -3, + // SET_TRUST_LINE_FLAGS_INVALID_STATE = -4, + // SET_TRUST_LINE_FLAGS_LOW_RESERVE = -5 // claimable balances can't be created + // // on revoke due to low reserves + // }; + // + // =========================================================================== + xdr["enum"]("SetTrustLineFlagsResultCode", { + setTrustLineFlagsSuccess: 0, + setTrustLineFlagsMalformed: -1, + setTrustLineFlagsNoTrustLine: -2, + setTrustLineFlagsCantRevoke: -3, + setTrustLineFlagsInvalidState: -4, + setTrustLineFlagsLowReserve: -5 + }); + + // === xdr source ============================================================ + // + // union SetTrustLineFlagsResult switch (SetTrustLineFlagsResultCode code) + // { + // case SET_TRUST_LINE_FLAGS_SUCCESS: + // void; + // case SET_TRUST_LINE_FLAGS_MALFORMED: + // case SET_TRUST_LINE_FLAGS_NO_TRUST_LINE: + // case SET_TRUST_LINE_FLAGS_CANT_REVOKE: + // case SET_TRUST_LINE_FLAGS_INVALID_STATE: + // case SET_TRUST_LINE_FLAGS_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("SetTrustLineFlagsResult", { + switchOn: xdr.lookup("SetTrustLineFlagsResultCode"), + switchName: "code", + switches: [["setTrustLineFlagsSuccess", xdr["void"]()], ["setTrustLineFlagsMalformed", xdr["void"]()], ["setTrustLineFlagsNoTrustLine", xdr["void"]()], ["setTrustLineFlagsCantRevoke", xdr["void"]()], ["setTrustLineFlagsInvalidState", xdr["void"]()], ["setTrustLineFlagsLowReserve", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum LiquidityPoolDepositResultCode + // { + // // codes considered as "success" for the operation + // LIQUIDITY_POOL_DEPOSIT_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // LIQUIDITY_POOL_DEPOSIT_MALFORMED = -1, // bad input + // LIQUIDITY_POOL_DEPOSIT_NO_TRUST = -2, // no trust line for one of the + // // assets + // LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED = -3, // not authorized for one of the + // // assets + // LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED = -4, // not enough balance for one of + // // the assets + // LIQUIDITY_POOL_DEPOSIT_LINE_FULL = -5, // pool share trust line doesn't + // // have sufficient limit + // LIQUIDITY_POOL_DEPOSIT_BAD_PRICE = -6, // deposit price outside bounds + // LIQUIDITY_POOL_DEPOSIT_POOL_FULL = -7 // pool reserves are full + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolDepositResultCode", { + liquidityPoolDepositSuccess: 0, + liquidityPoolDepositMalformed: -1, + liquidityPoolDepositNoTrust: -2, + liquidityPoolDepositNotAuthorized: -3, + liquidityPoolDepositUnderfunded: -4, + liquidityPoolDepositLineFull: -5, + liquidityPoolDepositBadPrice: -6, + liquidityPoolDepositPoolFull: -7 + }); + + // === xdr source ============================================================ + // + // union LiquidityPoolDepositResult switch (LiquidityPoolDepositResultCode code) + // { + // case LIQUIDITY_POOL_DEPOSIT_SUCCESS: + // void; + // case LIQUIDITY_POOL_DEPOSIT_MALFORMED: + // case LIQUIDITY_POOL_DEPOSIT_NO_TRUST: + // case LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED: + // case LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED: + // case LIQUIDITY_POOL_DEPOSIT_LINE_FULL: + // case LIQUIDITY_POOL_DEPOSIT_BAD_PRICE: + // case LIQUIDITY_POOL_DEPOSIT_POOL_FULL: + // void; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolDepositResult", { + switchOn: xdr.lookup("LiquidityPoolDepositResultCode"), + switchName: "code", + switches: [["liquidityPoolDepositSuccess", xdr["void"]()], ["liquidityPoolDepositMalformed", xdr["void"]()], ["liquidityPoolDepositNoTrust", xdr["void"]()], ["liquidityPoolDepositNotAuthorized", xdr["void"]()], ["liquidityPoolDepositUnderfunded", xdr["void"]()], ["liquidityPoolDepositLineFull", xdr["void"]()], ["liquidityPoolDepositBadPrice", xdr["void"]()], ["liquidityPoolDepositPoolFull", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum LiquidityPoolWithdrawResultCode + // { + // // codes considered as "success" for the operation + // LIQUIDITY_POOL_WITHDRAW_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // LIQUIDITY_POOL_WITHDRAW_MALFORMED = -1, // bad input + // LIQUIDITY_POOL_WITHDRAW_NO_TRUST = -2, // no trust line for one of the + // // assets + // LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED = -3, // not enough balance of the + // // pool share + // LIQUIDITY_POOL_WITHDRAW_LINE_FULL = -4, // would go above limit for one + // // of the assets + // LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM = -5 // didn't withdraw enough + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolWithdrawResultCode", { + liquidityPoolWithdrawSuccess: 0, + liquidityPoolWithdrawMalformed: -1, + liquidityPoolWithdrawNoTrust: -2, + liquidityPoolWithdrawUnderfunded: -3, + liquidityPoolWithdrawLineFull: -4, + liquidityPoolWithdrawUnderMinimum: -5 + }); + + // === xdr source ============================================================ + // + // union LiquidityPoolWithdrawResult switch (LiquidityPoolWithdrawResultCode code) + // { + // case LIQUIDITY_POOL_WITHDRAW_SUCCESS: + // void; + // case LIQUIDITY_POOL_WITHDRAW_MALFORMED: + // case LIQUIDITY_POOL_WITHDRAW_NO_TRUST: + // case LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED: + // case LIQUIDITY_POOL_WITHDRAW_LINE_FULL: + // case LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM: + // void; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolWithdrawResult", { + switchOn: xdr.lookup("LiquidityPoolWithdrawResultCode"), + switchName: "code", + switches: [["liquidityPoolWithdrawSuccess", xdr["void"]()], ["liquidityPoolWithdrawMalformed", xdr["void"]()], ["liquidityPoolWithdrawNoTrust", xdr["void"]()], ["liquidityPoolWithdrawUnderfunded", xdr["void"]()], ["liquidityPoolWithdrawLineFull", xdr["void"]()], ["liquidityPoolWithdrawUnderMinimum", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum InvokeHostFunctionResultCode + // { + // // codes considered as "success" for the operation + // INVOKE_HOST_FUNCTION_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // INVOKE_HOST_FUNCTION_MALFORMED = -1, + // INVOKE_HOST_FUNCTION_TRAPPED = -2, + // INVOKE_HOST_FUNCTION_RESOURCE_LIMIT_EXCEEDED = -3, + // INVOKE_HOST_FUNCTION_ENTRY_ARCHIVED = -4, + // INVOKE_HOST_FUNCTION_INSUFFICIENT_REFUNDABLE_FEE = -5 + // }; + // + // =========================================================================== + xdr["enum"]("InvokeHostFunctionResultCode", { + invokeHostFunctionSuccess: 0, + invokeHostFunctionMalformed: -1, + invokeHostFunctionTrapped: -2, + invokeHostFunctionResourceLimitExceeded: -3, + invokeHostFunctionEntryArchived: -4, + invokeHostFunctionInsufficientRefundableFee: -5 + }); + + // === xdr source ============================================================ + // + // union InvokeHostFunctionResult switch (InvokeHostFunctionResultCode code) + // { + // case INVOKE_HOST_FUNCTION_SUCCESS: + // Hash success; // sha256(InvokeHostFunctionSuccessPreImage) + // case INVOKE_HOST_FUNCTION_MALFORMED: + // case INVOKE_HOST_FUNCTION_TRAPPED: + // case INVOKE_HOST_FUNCTION_RESOURCE_LIMIT_EXCEEDED: + // case INVOKE_HOST_FUNCTION_ENTRY_ARCHIVED: + // case INVOKE_HOST_FUNCTION_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("InvokeHostFunctionResult", { + switchOn: xdr.lookup("InvokeHostFunctionResultCode"), + switchName: "code", + switches: [["invokeHostFunctionSuccess", "success"], ["invokeHostFunctionMalformed", xdr["void"]()], ["invokeHostFunctionTrapped", xdr["void"]()], ["invokeHostFunctionResourceLimitExceeded", xdr["void"]()], ["invokeHostFunctionEntryArchived", xdr["void"]()], ["invokeHostFunctionInsufficientRefundableFee", xdr["void"]()]], + arms: { + success: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum ExtendFootprintTTLResultCode + // { + // // codes considered as "success" for the operation + // EXTEND_FOOTPRINT_TTL_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // EXTEND_FOOTPRINT_TTL_MALFORMED = -1, + // EXTEND_FOOTPRINT_TTL_RESOURCE_LIMIT_EXCEEDED = -2, + // EXTEND_FOOTPRINT_TTL_INSUFFICIENT_REFUNDABLE_FEE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("ExtendFootprintTtlResultCode", { + extendFootprintTtlSuccess: 0, + extendFootprintTtlMalformed: -1, + extendFootprintTtlResourceLimitExceeded: -2, + extendFootprintTtlInsufficientRefundableFee: -3 + }); + + // === xdr source ============================================================ + // + // union ExtendFootprintTTLResult switch (ExtendFootprintTTLResultCode code) + // { + // case EXTEND_FOOTPRINT_TTL_SUCCESS: + // void; + // case EXTEND_FOOTPRINT_TTL_MALFORMED: + // case EXTEND_FOOTPRINT_TTL_RESOURCE_LIMIT_EXCEEDED: + // case EXTEND_FOOTPRINT_TTL_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("ExtendFootprintTtlResult", { + switchOn: xdr.lookup("ExtendFootprintTtlResultCode"), + switchName: "code", + switches: [["extendFootprintTtlSuccess", xdr["void"]()], ["extendFootprintTtlMalformed", xdr["void"]()], ["extendFootprintTtlResourceLimitExceeded", xdr["void"]()], ["extendFootprintTtlInsufficientRefundableFee", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum RestoreFootprintResultCode + // { + // // codes considered as "success" for the operation + // RESTORE_FOOTPRINT_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // RESTORE_FOOTPRINT_MALFORMED = -1, + // RESTORE_FOOTPRINT_RESOURCE_LIMIT_EXCEEDED = -2, + // RESTORE_FOOTPRINT_INSUFFICIENT_REFUNDABLE_FEE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("RestoreFootprintResultCode", { + restoreFootprintSuccess: 0, + restoreFootprintMalformed: -1, + restoreFootprintResourceLimitExceeded: -2, + restoreFootprintInsufficientRefundableFee: -3 + }); + + // === xdr source ============================================================ + // + // union RestoreFootprintResult switch (RestoreFootprintResultCode code) + // { + // case RESTORE_FOOTPRINT_SUCCESS: + // void; + // case RESTORE_FOOTPRINT_MALFORMED: + // case RESTORE_FOOTPRINT_RESOURCE_LIMIT_EXCEEDED: + // case RESTORE_FOOTPRINT_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("RestoreFootprintResult", { + switchOn: xdr.lookup("RestoreFootprintResultCode"), + switchName: "code", + switches: [["restoreFootprintSuccess", xdr["void"]()], ["restoreFootprintMalformed", xdr["void"]()], ["restoreFootprintResourceLimitExceeded", xdr["void"]()], ["restoreFootprintInsufficientRefundableFee", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum OperationResultCode + // { + // opINNER = 0, // inner object result is valid + // + // opBAD_AUTH = -1, // too few valid signatures / wrong network + // opNO_ACCOUNT = -2, // source account was not found + // opNOT_SUPPORTED = -3, // operation not supported at this time + // opTOO_MANY_SUBENTRIES = -4, // max number of subentries already reached + // opEXCEEDED_WORK_LIMIT = -5, // operation did too much work + // opTOO_MANY_SPONSORING = -6 // account is sponsoring too many entries + // }; + // + // =========================================================================== + xdr["enum"]("OperationResultCode", { + opInner: 0, + opBadAuth: -1, + opNoAccount: -2, + opNotSupported: -3, + opTooManySubentries: -4, + opExceededWorkLimit: -5, + opTooManySponsoring: -6 + }); + + // === xdr source ============================================================ + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountResult createAccountResult; + // case PAYMENT: + // PaymentResult paymentResult; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult; + // case MANAGE_SELL_OFFER: + // ManageSellOfferResult manageSellOfferResult; + // case CREATE_PASSIVE_SELL_OFFER: + // ManageSellOfferResult createPassiveSellOfferResult; + // case SET_OPTIONS: + // SetOptionsResult setOptionsResult; + // case CHANGE_TRUST: + // ChangeTrustResult changeTrustResult; + // case ALLOW_TRUST: + // AllowTrustResult allowTrustResult; + // case ACCOUNT_MERGE: + // AccountMergeResult accountMergeResult; + // case INFLATION: + // InflationResult inflationResult; + // case MANAGE_DATA: + // ManageDataResult manageDataResult; + // case BUMP_SEQUENCE: + // BumpSequenceResult bumpSeqResult; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferResult manageBuyOfferResult; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendResult pathPaymentStrictSendResult; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceResult createClaimableBalanceResult; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceResult claimClaimableBalanceResult; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult; + // case END_SPONSORING_FUTURE_RESERVES: + // EndSponsoringFutureReservesResult endSponsoringFutureReservesResult; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipResult revokeSponsorshipResult; + // case CLAWBACK: + // ClawbackResult clawbackResult; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceResult clawbackClaimableBalanceResult; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsResult setTrustLineFlagsResult; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositResult liquidityPoolDepositResult; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawResult liquidityPoolWithdrawResult; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionResult invokeHostFunctionResult; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLResult extendFootprintTTLResult; + // case RESTORE_FOOTPRINT: + // RestoreFootprintResult restoreFootprintResult; + // } + // + // =========================================================================== + xdr.union("OperationResultTr", { + switchOn: xdr.lookup("OperationType"), + switchName: "type", + switches: [["createAccount", "createAccountResult"], ["payment", "paymentResult"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveResult"], ["manageSellOffer", "manageSellOfferResult"], ["createPassiveSellOffer", "createPassiveSellOfferResult"], ["setOptions", "setOptionsResult"], ["changeTrust", "changeTrustResult"], ["allowTrust", "allowTrustResult"], ["accountMerge", "accountMergeResult"], ["inflation", "inflationResult"], ["manageData", "manageDataResult"], ["bumpSequence", "bumpSeqResult"], ["manageBuyOffer", "manageBuyOfferResult"], ["pathPaymentStrictSend", "pathPaymentStrictSendResult"], ["createClaimableBalance", "createClaimableBalanceResult"], ["claimClaimableBalance", "claimClaimableBalanceResult"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesResult"], ["endSponsoringFutureReserves", "endSponsoringFutureReservesResult"], ["revokeSponsorship", "revokeSponsorshipResult"], ["clawback", "clawbackResult"], ["clawbackClaimableBalance", "clawbackClaimableBalanceResult"], ["setTrustLineFlags", "setTrustLineFlagsResult"], ["liquidityPoolDeposit", "liquidityPoolDepositResult"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawResult"], ["invokeHostFunction", "invokeHostFunctionResult"], ["extendFootprintTtl", "extendFootprintTtlResult"], ["restoreFootprint", "restoreFootprintResult"]], + arms: { + createAccountResult: xdr.lookup("CreateAccountResult"), + paymentResult: xdr.lookup("PaymentResult"), + pathPaymentStrictReceiveResult: xdr.lookup("PathPaymentStrictReceiveResult"), + manageSellOfferResult: xdr.lookup("ManageSellOfferResult"), + createPassiveSellOfferResult: xdr.lookup("ManageSellOfferResult"), + setOptionsResult: xdr.lookup("SetOptionsResult"), + changeTrustResult: xdr.lookup("ChangeTrustResult"), + allowTrustResult: xdr.lookup("AllowTrustResult"), + accountMergeResult: xdr.lookup("AccountMergeResult"), + inflationResult: xdr.lookup("InflationResult"), + manageDataResult: xdr.lookup("ManageDataResult"), + bumpSeqResult: xdr.lookup("BumpSequenceResult"), + manageBuyOfferResult: xdr.lookup("ManageBuyOfferResult"), + pathPaymentStrictSendResult: xdr.lookup("PathPaymentStrictSendResult"), + createClaimableBalanceResult: xdr.lookup("CreateClaimableBalanceResult"), + claimClaimableBalanceResult: xdr.lookup("ClaimClaimableBalanceResult"), + beginSponsoringFutureReservesResult: xdr.lookup("BeginSponsoringFutureReservesResult"), + endSponsoringFutureReservesResult: xdr.lookup("EndSponsoringFutureReservesResult"), + revokeSponsorshipResult: xdr.lookup("RevokeSponsorshipResult"), + clawbackResult: xdr.lookup("ClawbackResult"), + clawbackClaimableBalanceResult: xdr.lookup("ClawbackClaimableBalanceResult"), + setTrustLineFlagsResult: xdr.lookup("SetTrustLineFlagsResult"), + liquidityPoolDepositResult: xdr.lookup("LiquidityPoolDepositResult"), + liquidityPoolWithdrawResult: xdr.lookup("LiquidityPoolWithdrawResult"), + invokeHostFunctionResult: xdr.lookup("InvokeHostFunctionResult"), + extendFootprintTtlResult: xdr.lookup("ExtendFootprintTtlResult"), + restoreFootprintResult: xdr.lookup("RestoreFootprintResult") + } + }); + + // === xdr source ============================================================ + // + // union OperationResult switch (OperationResultCode code) + // { + // case opINNER: + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountResult createAccountResult; + // case PAYMENT: + // PaymentResult paymentResult; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult; + // case MANAGE_SELL_OFFER: + // ManageSellOfferResult manageSellOfferResult; + // case CREATE_PASSIVE_SELL_OFFER: + // ManageSellOfferResult createPassiveSellOfferResult; + // case SET_OPTIONS: + // SetOptionsResult setOptionsResult; + // case CHANGE_TRUST: + // ChangeTrustResult changeTrustResult; + // case ALLOW_TRUST: + // AllowTrustResult allowTrustResult; + // case ACCOUNT_MERGE: + // AccountMergeResult accountMergeResult; + // case INFLATION: + // InflationResult inflationResult; + // case MANAGE_DATA: + // ManageDataResult manageDataResult; + // case BUMP_SEQUENCE: + // BumpSequenceResult bumpSeqResult; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferResult manageBuyOfferResult; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendResult pathPaymentStrictSendResult; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceResult createClaimableBalanceResult; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceResult claimClaimableBalanceResult; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult; + // case END_SPONSORING_FUTURE_RESERVES: + // EndSponsoringFutureReservesResult endSponsoringFutureReservesResult; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipResult revokeSponsorshipResult; + // case CLAWBACK: + // ClawbackResult clawbackResult; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceResult clawbackClaimableBalanceResult; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsResult setTrustLineFlagsResult; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositResult liquidityPoolDepositResult; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawResult liquidityPoolWithdrawResult; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionResult invokeHostFunctionResult; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLResult extendFootprintTTLResult; + // case RESTORE_FOOTPRINT: + // RestoreFootprintResult restoreFootprintResult; + // } + // tr; + // case opBAD_AUTH: + // case opNO_ACCOUNT: + // case opNOT_SUPPORTED: + // case opTOO_MANY_SUBENTRIES: + // case opEXCEEDED_WORK_LIMIT: + // case opTOO_MANY_SPONSORING: + // void; + // }; + // + // =========================================================================== + xdr.union("OperationResult", { + switchOn: xdr.lookup("OperationResultCode"), + switchName: "code", + switches: [["opInner", "tr"], ["opBadAuth", xdr["void"]()], ["opNoAccount", xdr["void"]()], ["opNotSupported", xdr["void"]()], ["opTooManySubentries", xdr["void"]()], ["opExceededWorkLimit", xdr["void"]()], ["opTooManySponsoring", xdr["void"]()]], + arms: { + tr: xdr.lookup("OperationResultTr") + } + }); + + // === xdr source ============================================================ + // + // enum TransactionResultCode + // { + // txFEE_BUMP_INNER_SUCCESS = 1, // fee bump inner transaction succeeded + // txSUCCESS = 0, // all operations succeeded + // + // txFAILED = -1, // one of the operations failed (none were applied) + // + // txTOO_EARLY = -2, // ledger closeTime before minTime + // txTOO_LATE = -3, // ledger closeTime after maxTime + // txMISSING_OPERATION = -4, // no operation was specified + // txBAD_SEQ = -5, // sequence number does not match source account + // + // txBAD_AUTH = -6, // too few valid signatures / wrong network + // txINSUFFICIENT_BALANCE = -7, // fee would bring account below reserve + // txNO_ACCOUNT = -8, // source account not found + // txINSUFFICIENT_FEE = -9, // fee is too small + // txBAD_AUTH_EXTRA = -10, // unused signatures attached to transaction + // txINTERNAL_ERROR = -11, // an unknown error occurred + // + // txNOT_SUPPORTED = -12, // transaction type not supported + // txFEE_BUMP_INNER_FAILED = -13, // fee bump inner transaction failed + // txBAD_SPONSORSHIP = -14, // sponsorship not confirmed + // txBAD_MIN_SEQ_AGE_OR_GAP = -15, // minSeqAge or minSeqLedgerGap conditions not met + // txMALFORMED = -16, // precondition is invalid + // txSOROBAN_INVALID = -17 // soroban-specific preconditions were not met + // }; + // + // =========================================================================== + xdr["enum"]("TransactionResultCode", { + txFeeBumpInnerSuccess: 1, + txSuccess: 0, + txFailed: -1, + txTooEarly: -2, + txTooLate: -3, + txMissingOperation: -4, + txBadSeq: -5, + txBadAuth: -6, + txInsufficientBalance: -7, + txNoAccount: -8, + txInsufficientFee: -9, + txBadAuthExtra: -10, + txInternalError: -11, + txNotSupported: -12, + txFeeBumpInnerFailed: -13, + txBadSponsorship: -14, + txBadMinSeqAgeOrGap: -15, + txMalformed: -16, + txSorobanInvalid: -17 + }); + + // === xdr source ============================================================ + // + // union switch (TransactionResultCode code) + // { + // // txFEE_BUMP_INNER_SUCCESS is not included + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // txFEE_BUMP_INNER_FAILED is not included + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // + // =========================================================================== + xdr.union("InnerTransactionResultResult", { + switchOn: xdr.lookup("TransactionResultCode"), + switchName: "code", + switches: [["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr["void"]()], ["txTooLate", xdr["void"]()], ["txMissingOperation", xdr["void"]()], ["txBadSeq", xdr["void"]()], ["txBadAuth", xdr["void"]()], ["txInsufficientBalance", xdr["void"]()], ["txNoAccount", xdr["void"]()], ["txInsufficientFee", xdr["void"]()], ["txBadAuthExtra", xdr["void"]()], ["txInternalError", xdr["void"]()], ["txNotSupported", xdr["void"]()], ["txBadSponsorship", xdr["void"]()], ["txBadMinSeqAgeOrGap", xdr["void"]()], ["txMalformed", xdr["void"]()], ["txSorobanInvalid", xdr["void"]()]], + arms: { + results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("InnerTransactionResultExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct InnerTransactionResult + // { + // // Always 0. Here for binary compatibility. + // int64 feeCharged; + // + // union switch (TransactionResultCode code) + // { + // // txFEE_BUMP_INNER_SUCCESS is not included + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // txFEE_BUMP_INNER_FAILED is not included + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // result; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("InnerTransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("InnerTransactionResultResult")], ["ext", xdr.lookup("InnerTransactionResultExt")]]); + + // === xdr source ============================================================ + // + // struct InnerTransactionResultPair + // { + // Hash transactionHash; // hash of the inner transaction + // InnerTransactionResult result; // result for the inner transaction + // }; + // + // =========================================================================== + xdr.struct("InnerTransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("InnerTransactionResult")]]); + + // === xdr source ============================================================ + // + // union switch (TransactionResultCode code) + // { + // case txFEE_BUMP_INNER_SUCCESS: + // case txFEE_BUMP_INNER_FAILED: + // InnerTransactionResultPair innerResultPair; + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // case txFEE_BUMP_INNER_FAILED: handled above + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionResultResult", { + switchOn: xdr.lookup("TransactionResultCode"), + switchName: "code", + switches: [["txFeeBumpInnerSuccess", "innerResultPair"], ["txFeeBumpInnerFailed", "innerResultPair"], ["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr["void"]()], ["txTooLate", xdr["void"]()], ["txMissingOperation", xdr["void"]()], ["txBadSeq", xdr["void"]()], ["txBadAuth", xdr["void"]()], ["txInsufficientBalance", xdr["void"]()], ["txNoAccount", xdr["void"]()], ["txInsufficientFee", xdr["void"]()], ["txBadAuthExtra", xdr["void"]()], ["txInternalError", xdr["void"]()], ["txNotSupported", xdr["void"]()], ["txBadSponsorship", xdr["void"]()], ["txBadMinSeqAgeOrGap", xdr["void"]()], ["txMalformed", xdr["void"]()], ["txSorobanInvalid", xdr["void"]()]], + arms: { + innerResultPair: xdr.lookup("InnerTransactionResultPair"), + results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionResultExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionResult + // { + // int64 feeCharged; // actual fee charged for the transaction + // + // union switch (TransactionResultCode code) + // { + // case txFEE_BUMP_INNER_SUCCESS: + // case txFEE_BUMP_INNER_FAILED: + // InnerTransactionResultPair innerResultPair; + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // case txFEE_BUMP_INNER_FAILED: handled above + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // result; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("TransactionResultResult")], ["ext", xdr.lookup("TransactionResultExt")]]); + + // === xdr source ============================================================ + // + // typedef opaque Hash[32]; + // + // =========================================================================== + xdr.typedef("Hash", xdr.opaque(32)); + + // === xdr source ============================================================ + // + // typedef opaque uint256[32]; + // + // =========================================================================== + xdr.typedef("Uint256", xdr.opaque(32)); + + // === xdr source ============================================================ + // + // typedef unsigned int uint32; + // + // =========================================================================== + xdr.typedef("Uint32", xdr.uint()); + + // === xdr source ============================================================ + // + // typedef int int32; + // + // =========================================================================== + xdr.typedef("Int32", xdr["int"]()); + + // === xdr source ============================================================ + // + // typedef unsigned hyper uint64; + // + // =========================================================================== + xdr.typedef("Uint64", xdr.uhyper()); + + // === xdr source ============================================================ + // + // typedef hyper int64; + // + // =========================================================================== + xdr.typedef("Int64", xdr.hyper()); + + // === xdr source ============================================================ + // + // typedef uint64 TimePoint; + // + // =========================================================================== + xdr.typedef("TimePoint", xdr.lookup("Uint64")); + + // === xdr source ============================================================ + // + // typedef uint64 Duration; + // + // =========================================================================== + xdr.typedef("Duration", xdr.lookup("Uint64")); + + // === xdr source ============================================================ + // + // union ExtensionPoint switch (int v) + // { + // case 0: + // void; + // }; + // + // =========================================================================== + xdr.union("ExtensionPoint", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum CryptoKeyType + // { + // KEY_TYPE_ED25519 = 0, + // KEY_TYPE_PRE_AUTH_TX = 1, + // KEY_TYPE_HASH_X = 2, + // KEY_TYPE_ED25519_SIGNED_PAYLOAD = 3, + // // MUXED enum values for supported type are derived from the enum values + // // above by ORing them with 0x100 + // KEY_TYPE_MUXED_ED25519 = 0x100 + // }; + // + // =========================================================================== + xdr["enum"]("CryptoKeyType", { + keyTypeEd25519: 0, + keyTypePreAuthTx: 1, + keyTypeHashX: 2, + keyTypeEd25519SignedPayload: 3, + keyTypeMuxedEd25519: 256 + }); + + // === xdr source ============================================================ + // + // enum PublicKeyType + // { + // PUBLIC_KEY_TYPE_ED25519 = KEY_TYPE_ED25519 + // }; + // + // =========================================================================== + xdr["enum"]("PublicKeyType", { + publicKeyTypeEd25519: 0 + }); + + // === xdr source ============================================================ + // + // enum SignerKeyType + // { + // SIGNER_KEY_TYPE_ED25519 = KEY_TYPE_ED25519, + // SIGNER_KEY_TYPE_PRE_AUTH_TX = KEY_TYPE_PRE_AUTH_TX, + // SIGNER_KEY_TYPE_HASH_X = KEY_TYPE_HASH_X, + // SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD = KEY_TYPE_ED25519_SIGNED_PAYLOAD + // }; + // + // =========================================================================== + xdr["enum"]("SignerKeyType", { + signerKeyTypeEd25519: 0, + signerKeyTypePreAuthTx: 1, + signerKeyTypeHashX: 2, + signerKeyTypeEd25519SignedPayload: 3 + }); + + // === xdr source ============================================================ + // + // union PublicKey switch (PublicKeyType type) + // { + // case PUBLIC_KEY_TYPE_ED25519: + // uint256 ed25519; + // }; + // + // =========================================================================== + xdr.union("PublicKey", { + switchOn: xdr.lookup("PublicKeyType"), + switchName: "type", + switches: [["publicKeyTypeEd25519", "ed25519"]], + arms: { + ed25519: xdr.lookup("Uint256") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // /* Public key that must sign the payload. */ + // uint256 ed25519; + // /* Payload to be raw signed by ed25519. */ + // opaque payload<64>; + // } + // + // =========================================================================== + xdr.struct("SignerKeyEd25519SignedPayload", [["ed25519", xdr.lookup("Uint256")], ["payload", xdr.varOpaque(64)]]); + + // === xdr source ============================================================ + // + // union SignerKey switch (SignerKeyType type) + // { + // case SIGNER_KEY_TYPE_ED25519: + // uint256 ed25519; + // case SIGNER_KEY_TYPE_PRE_AUTH_TX: + // /* SHA-256 Hash of TransactionSignaturePayload structure */ + // uint256 preAuthTx; + // case SIGNER_KEY_TYPE_HASH_X: + // /* Hash of random 256 bit preimage X */ + // uint256 hashX; + // case SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD: + // struct + // { + // /* Public key that must sign the payload. */ + // uint256 ed25519; + // /* Payload to be raw signed by ed25519. */ + // opaque payload<64>; + // } ed25519SignedPayload; + // }; + // + // =========================================================================== + xdr.union("SignerKey", { + switchOn: xdr.lookup("SignerKeyType"), + switchName: "type", + switches: [["signerKeyTypeEd25519", "ed25519"], ["signerKeyTypePreAuthTx", "preAuthTx"], ["signerKeyTypeHashX", "hashX"], ["signerKeyTypeEd25519SignedPayload", "ed25519SignedPayload"]], + arms: { + ed25519: xdr.lookup("Uint256"), + preAuthTx: xdr.lookup("Uint256"), + hashX: xdr.lookup("Uint256"), + ed25519SignedPayload: xdr.lookup("SignerKeyEd25519SignedPayload") + } + }); + + // === xdr source ============================================================ + // + // typedef opaque Signature<64>; + // + // =========================================================================== + xdr.typedef("Signature", xdr.varOpaque(64)); + + // === xdr source ============================================================ + // + // typedef opaque SignatureHint[4]; + // + // =========================================================================== + xdr.typedef("SignatureHint", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef PublicKey NodeID; + // + // =========================================================================== + xdr.typedef("NodeId", xdr.lookup("PublicKey")); + + // === xdr source ============================================================ + // + // typedef PublicKey AccountID; + // + // =========================================================================== + xdr.typedef("AccountId", xdr.lookup("PublicKey")); + + // === xdr source ============================================================ + // + // struct Curve25519Secret + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("Curve25519Secret", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct Curve25519Public + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("Curve25519Public", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct HmacSha256Key + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("HmacSha256Key", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct HmacSha256Mac + // { + // opaque mac[32]; + // }; + // + // =========================================================================== + xdr.struct("HmacSha256Mac", [["mac", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct ShortHashSeed + // { + // opaque seed[16]; + // }; + // + // =========================================================================== + xdr.struct("ShortHashSeed", [["seed", xdr.opaque(16)]]); + + // === xdr source ============================================================ + // + // enum BinaryFuseFilterType + // { + // BINARY_FUSE_FILTER_8_BIT = 0, + // BINARY_FUSE_FILTER_16_BIT = 1, + // BINARY_FUSE_FILTER_32_BIT = 2 + // }; + // + // =========================================================================== + xdr["enum"]("BinaryFuseFilterType", { + binaryFuseFilter8Bit: 0, + binaryFuseFilter16Bit: 1, + binaryFuseFilter32Bit: 2 + }); + + // === xdr source ============================================================ + // + // struct SerializedBinaryFuseFilter + // { + // BinaryFuseFilterType type; + // + // // Seed used to hash input to filter + // ShortHashSeed inputHashSeed; + // + // // Seed used for internal filter hash operations + // ShortHashSeed filterSeed; + // uint32 segmentLength; + // uint32 segementLengthMask; + // uint32 segmentCount; + // uint32 segmentCountLength; + // uint32 fingerprintLength; // Length in terms of element count, not bytes + // + // // Array of uint8_t, uint16_t, or uint32_t depending on filter type + // opaque fingerprints<>; + // }; + // + // =========================================================================== + xdr.struct("SerializedBinaryFuseFilter", [["type", xdr.lookup("BinaryFuseFilterType")], ["inputHashSeed", xdr.lookup("ShortHashSeed")], ["filterSeed", xdr.lookup("ShortHashSeed")], ["segmentLength", xdr.lookup("Uint32")], ["segementLengthMask", xdr.lookup("Uint32")], ["segmentCount", xdr.lookup("Uint32")], ["segmentCountLength", xdr.lookup("Uint32")], ["fingerprintLength", xdr.lookup("Uint32")], ["fingerprints", xdr.varOpaque()]]); + + // === xdr source ============================================================ + // + // enum SCValType + // { + // SCV_BOOL = 0, + // SCV_VOID = 1, + // SCV_ERROR = 2, + // + // // 32 bits is the smallest type in WASM or XDR; no need for u8/u16. + // SCV_U32 = 3, + // SCV_I32 = 4, + // + // // 64 bits is naturally supported by both WASM and XDR also. + // SCV_U64 = 5, + // SCV_I64 = 6, + // + // // Time-related u64 subtypes with their own functions and formatting. + // SCV_TIMEPOINT = 7, + // SCV_DURATION = 8, + // + // // 128 bits is naturally supported by Rust and we use it for Soroban + // // fixed-point arithmetic prices / balances / similar "quantities". These + // // are represented in XDR as a pair of 2 u64s. + // SCV_U128 = 9, + // SCV_I128 = 10, + // + // // 256 bits is the size of sha256 output, ed25519 keys, and the EVM machine + // // word, so for interop use we include this even though it requires a small + // // amount of Rust guest and/or host library code. + // SCV_U256 = 11, + // SCV_I256 = 12, + // + // // Bytes come in 3 flavors, 2 of which have meaningfully different + // // formatting and validity-checking / domain-restriction. + // SCV_BYTES = 13, + // SCV_STRING = 14, + // SCV_SYMBOL = 15, + // + // // Vecs and maps are just polymorphic containers of other ScVals. + // SCV_VEC = 16, + // SCV_MAP = 17, + // + // // Address is the universal identifier for contracts and classic + // // accounts. + // SCV_ADDRESS = 18, + // + // // The following are the internal SCVal variants that are not + // // exposed to the contracts. + // SCV_CONTRACT_INSTANCE = 19, + // + // // SCV_LEDGER_KEY_CONTRACT_INSTANCE and SCV_LEDGER_KEY_NONCE are unique + // // symbolic SCVals used as the key for ledger entries for a contract's + // // instance and an address' nonce, respectively. + // SCV_LEDGER_KEY_CONTRACT_INSTANCE = 20, + // SCV_LEDGER_KEY_NONCE = 21 + // }; + // + // =========================================================================== + xdr["enum"]("ScValType", { + scvBool: 0, + scvVoid: 1, + scvError: 2, + scvU32: 3, + scvI32: 4, + scvU64: 5, + scvI64: 6, + scvTimepoint: 7, + scvDuration: 8, + scvU128: 9, + scvI128: 10, + scvU256: 11, + scvI256: 12, + scvBytes: 13, + scvString: 14, + scvSymbol: 15, + scvVec: 16, + scvMap: 17, + scvAddress: 18, + scvContractInstance: 19, + scvLedgerKeyContractInstance: 20, + scvLedgerKeyNonce: 21 + }); + + // === xdr source ============================================================ + // + // enum SCErrorType + // { + // SCE_CONTRACT = 0, // Contract-specific, user-defined codes. + // SCE_WASM_VM = 1, // Errors while interpreting WASM bytecode. + // SCE_CONTEXT = 2, // Errors in the contract's host context. + // SCE_STORAGE = 3, // Errors accessing host storage. + // SCE_OBJECT = 4, // Errors working with host objects. + // SCE_CRYPTO = 5, // Errors in cryptographic operations. + // SCE_EVENTS = 6, // Errors while emitting events. + // SCE_BUDGET = 7, // Errors relating to budget limits. + // SCE_VALUE = 8, // Errors working with host values or SCVals. + // SCE_AUTH = 9 // Errors from the authentication subsystem. + // }; + // + // =========================================================================== + xdr["enum"]("ScErrorType", { + sceContract: 0, + sceWasmVm: 1, + sceContext: 2, + sceStorage: 3, + sceObject: 4, + sceCrypto: 5, + sceEvents: 6, + sceBudget: 7, + sceValue: 8, + sceAuth: 9 + }); + + // === xdr source ============================================================ + // + // enum SCErrorCode + // { + // SCEC_ARITH_DOMAIN = 0, // Some arithmetic was undefined (overflow, divide-by-zero). + // SCEC_INDEX_BOUNDS = 1, // Something was indexed beyond its bounds. + // SCEC_INVALID_INPUT = 2, // User provided some otherwise-bad data. + // SCEC_MISSING_VALUE = 3, // Some value was required but not provided. + // SCEC_EXISTING_VALUE = 4, // Some value was provided where not allowed. + // SCEC_EXCEEDED_LIMIT = 5, // Some arbitrary limit -- gas or otherwise -- was hit. + // SCEC_INVALID_ACTION = 6, // Data was valid but action requested was not. + // SCEC_INTERNAL_ERROR = 7, // The host detected an error in its own logic. + // SCEC_UNEXPECTED_TYPE = 8, // Some type wasn't as expected. + // SCEC_UNEXPECTED_SIZE = 9 // Something's size wasn't as expected. + // }; + // + // =========================================================================== + xdr["enum"]("ScErrorCode", { + scecArithDomain: 0, + scecIndexBounds: 1, + scecInvalidInput: 2, + scecMissingValue: 3, + scecExistingValue: 4, + scecExceededLimit: 5, + scecInvalidAction: 6, + scecInternalError: 7, + scecUnexpectedType: 8, + scecUnexpectedSize: 9 + }); + + // === xdr source ============================================================ + // + // union SCError switch (SCErrorType type) + // { + // case SCE_CONTRACT: + // uint32 contractCode; + // case SCE_WASM_VM: + // case SCE_CONTEXT: + // case SCE_STORAGE: + // case SCE_OBJECT: + // case SCE_CRYPTO: + // case SCE_EVENTS: + // case SCE_BUDGET: + // case SCE_VALUE: + // case SCE_AUTH: + // SCErrorCode code; + // }; + // + // =========================================================================== + xdr.union("ScError", { + switchOn: xdr.lookup("ScErrorType"), + switchName: "type", + switches: [["sceContract", "contractCode"], ["sceWasmVm", "code"], ["sceContext", "code"], ["sceStorage", "code"], ["sceObject", "code"], ["sceCrypto", "code"], ["sceEvents", "code"], ["sceBudget", "code"], ["sceValue", "code"], ["sceAuth", "code"]], + arms: { + contractCode: xdr.lookup("Uint32"), + code: xdr.lookup("ScErrorCode") + } + }); + + // === xdr source ============================================================ + // + // struct UInt128Parts { + // uint64 hi; + // uint64 lo; + // }; + // + // =========================================================================== + xdr.struct("UInt128Parts", [["hi", xdr.lookup("Uint64")], ["lo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct Int128Parts { + // int64 hi; + // uint64 lo; + // }; + // + // =========================================================================== + xdr.struct("Int128Parts", [["hi", xdr.lookup("Int64")], ["lo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct UInt256Parts { + // uint64 hi_hi; + // uint64 hi_lo; + // uint64 lo_hi; + // uint64 lo_lo; + // }; + // + // =========================================================================== + xdr.struct("UInt256Parts", [["hiHi", xdr.lookup("Uint64")], ["hiLo", xdr.lookup("Uint64")], ["loHi", xdr.lookup("Uint64")], ["loLo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct Int256Parts { + // int64 hi_hi; + // uint64 hi_lo; + // uint64 lo_hi; + // uint64 lo_lo; + // }; + // + // =========================================================================== + xdr.struct("Int256Parts", [["hiHi", xdr.lookup("Int64")], ["hiLo", xdr.lookup("Uint64")], ["loHi", xdr.lookup("Uint64")], ["loLo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // enum ContractExecutableType + // { + // CONTRACT_EXECUTABLE_WASM = 0, + // CONTRACT_EXECUTABLE_STELLAR_ASSET = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractExecutableType", { + contractExecutableWasm: 0, + contractExecutableStellarAsset: 1 + }); + + // === xdr source ============================================================ + // + // union ContractExecutable switch (ContractExecutableType type) + // { + // case CONTRACT_EXECUTABLE_WASM: + // Hash wasm_hash; + // case CONTRACT_EXECUTABLE_STELLAR_ASSET: + // void; + // }; + // + // =========================================================================== + xdr.union("ContractExecutable", { + switchOn: xdr.lookup("ContractExecutableType"), + switchName: "type", + switches: [["contractExecutableWasm", "wasmHash"], ["contractExecutableStellarAsset", xdr["void"]()]], + arms: { + wasmHash: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum SCAddressType + // { + // SC_ADDRESS_TYPE_ACCOUNT = 0, + // SC_ADDRESS_TYPE_CONTRACT = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ScAddressType", { + scAddressTypeAccount: 0, + scAddressTypeContract: 1 + }); + + // === xdr source ============================================================ + // + // union SCAddress switch (SCAddressType type) + // { + // case SC_ADDRESS_TYPE_ACCOUNT: + // AccountID accountId; + // case SC_ADDRESS_TYPE_CONTRACT: + // Hash contractId; + // }; + // + // =========================================================================== + xdr.union("ScAddress", { + switchOn: xdr.lookup("ScAddressType"), + switchName: "type", + switches: [["scAddressTypeAccount", "accountId"], ["scAddressTypeContract", "contractId"]], + arms: { + accountId: xdr.lookup("AccountId"), + contractId: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // const SCSYMBOL_LIMIT = 32; + // + // =========================================================================== + xdr["const"]("SCSYMBOL_LIMIT", 32); + + // === xdr source ============================================================ + // + // typedef SCVal SCVec<>; + // + // =========================================================================== + xdr.typedef("ScVec", xdr.varArray(xdr.lookup("ScVal"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef SCMapEntry SCMap<>; + // + // =========================================================================== + xdr.typedef("ScMap", xdr.varArray(xdr.lookup("ScMapEntry"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef opaque SCBytes<>; + // + // =========================================================================== + xdr.typedef("ScBytes", xdr.varOpaque()); + + // === xdr source ============================================================ + // + // typedef string SCString<>; + // + // =========================================================================== + xdr.typedef("ScString", xdr.string()); + + // === xdr source ============================================================ + // + // typedef string SCSymbol; + // + // =========================================================================== + xdr.typedef("ScSymbol", xdr.string(SCSYMBOL_LIMIT)); + + // === xdr source ============================================================ + // + // struct SCNonceKey { + // int64 nonce; + // }; + // + // =========================================================================== + xdr.struct("ScNonceKey", [["nonce", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct SCContractInstance { + // ContractExecutable executable; + // SCMap* storage; + // }; + // + // =========================================================================== + xdr.struct("ScContractInstance", [["executable", xdr.lookup("ContractExecutable")], ["storage", xdr.option(xdr.lookup("ScMap"))]]); + + // === xdr source ============================================================ + // + // union SCVal switch (SCValType type) + // { + // + // case SCV_BOOL: + // bool b; + // case SCV_VOID: + // void; + // case SCV_ERROR: + // SCError error; + // + // case SCV_U32: + // uint32 u32; + // case SCV_I32: + // int32 i32; + // + // case SCV_U64: + // uint64 u64; + // case SCV_I64: + // int64 i64; + // case SCV_TIMEPOINT: + // TimePoint timepoint; + // case SCV_DURATION: + // Duration duration; + // + // case SCV_U128: + // UInt128Parts u128; + // case SCV_I128: + // Int128Parts i128; + // + // case SCV_U256: + // UInt256Parts u256; + // case SCV_I256: + // Int256Parts i256; + // + // case SCV_BYTES: + // SCBytes bytes; + // case SCV_STRING: + // SCString str; + // case SCV_SYMBOL: + // SCSymbol sym; + // + // // Vec and Map are recursive so need to live + // // behind an option, due to xdrpp limitations. + // case SCV_VEC: + // SCVec *vec; + // case SCV_MAP: + // SCMap *map; + // + // case SCV_ADDRESS: + // SCAddress address; + // + // // Special SCVals reserved for system-constructed contract-data + // // ledger keys, not generally usable elsewhere. + // case SCV_LEDGER_KEY_CONTRACT_INSTANCE: + // void; + // case SCV_LEDGER_KEY_NONCE: + // SCNonceKey nonce_key; + // + // case SCV_CONTRACT_INSTANCE: + // SCContractInstance instance; + // }; + // + // =========================================================================== + xdr.union("ScVal", { + switchOn: xdr.lookup("ScValType"), + switchName: "type", + switches: [["scvBool", "b"], ["scvVoid", xdr["void"]()], ["scvError", "error"], ["scvU32", "u32"], ["scvI32", "i32"], ["scvU64", "u64"], ["scvI64", "i64"], ["scvTimepoint", "timepoint"], ["scvDuration", "duration"], ["scvU128", "u128"], ["scvI128", "i128"], ["scvU256", "u256"], ["scvI256", "i256"], ["scvBytes", "bytes"], ["scvString", "str"], ["scvSymbol", "sym"], ["scvVec", "vec"], ["scvMap", "map"], ["scvAddress", "address"], ["scvLedgerKeyContractInstance", xdr["void"]()], ["scvLedgerKeyNonce", "nonceKey"], ["scvContractInstance", "instance"]], + arms: { + b: xdr.bool(), + error: xdr.lookup("ScError"), + u32: xdr.lookup("Uint32"), + i32: xdr.lookup("Int32"), + u64: xdr.lookup("Uint64"), + i64: xdr.lookup("Int64"), + timepoint: xdr.lookup("TimePoint"), + duration: xdr.lookup("Duration"), + u128: xdr.lookup("UInt128Parts"), + i128: xdr.lookup("Int128Parts"), + u256: xdr.lookup("UInt256Parts"), + i256: xdr.lookup("Int256Parts"), + bytes: xdr.lookup("ScBytes"), + str: xdr.lookup("ScString"), + sym: xdr.lookup("ScSymbol"), + vec: xdr.option(xdr.lookup("ScVec")), + map: xdr.option(xdr.lookup("ScMap")), + address: xdr.lookup("ScAddress"), + nonceKey: xdr.lookup("ScNonceKey"), + instance: xdr.lookup("ScContractInstance") + } + }); + + // === xdr source ============================================================ + // + // struct SCMapEntry + // { + // SCVal key; + // SCVal val; + // }; + // + // =========================================================================== + xdr.struct("ScMapEntry", [["key", xdr.lookup("ScVal")], ["val", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // enum SCEnvMetaKind + // { + // SC_ENV_META_KIND_INTERFACE_VERSION = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ScEnvMetaKind", { + scEnvMetaKindInterfaceVersion: 0 + }); + + // === xdr source ============================================================ + // + // struct { + // uint32 protocol; + // uint32 preRelease; + // } + // + // =========================================================================== + xdr.struct("ScEnvMetaEntryInterfaceVersion", [["protocol", xdr.lookup("Uint32")], ["preRelease", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union SCEnvMetaEntry switch (SCEnvMetaKind kind) + // { + // case SC_ENV_META_KIND_INTERFACE_VERSION: + // struct { + // uint32 protocol; + // uint32 preRelease; + // } interfaceVersion; + // }; + // + // =========================================================================== + xdr.union("ScEnvMetaEntry", { + switchOn: xdr.lookup("ScEnvMetaKind"), + switchName: "kind", + switches: [["scEnvMetaKindInterfaceVersion", "interfaceVersion"]], + arms: { + interfaceVersion: xdr.lookup("ScEnvMetaEntryInterfaceVersion") + } + }); + + // === xdr source ============================================================ + // + // struct SCMetaV0 + // { + // string key<>; + // string val<>; + // }; + // + // =========================================================================== + xdr.struct("ScMetaV0", [["key", xdr.string()], ["val", xdr.string()]]); + + // === xdr source ============================================================ + // + // enum SCMetaKind + // { + // SC_META_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ScMetaKind", { + scMetaV0: 0 + }); + + // === xdr source ============================================================ + // + // union SCMetaEntry switch (SCMetaKind kind) + // { + // case SC_META_V0: + // SCMetaV0 v0; + // }; + // + // =========================================================================== + xdr.union("ScMetaEntry", { + switchOn: xdr.lookup("ScMetaKind"), + switchName: "kind", + switches: [["scMetaV0", "v0"]], + arms: { + v0: xdr.lookup("ScMetaV0") + } + }); + + // === xdr source ============================================================ + // + // const SC_SPEC_DOC_LIMIT = 1024; + // + // =========================================================================== + xdr["const"]("SC_SPEC_DOC_LIMIT", 1024); + + // === xdr source ============================================================ + // + // enum SCSpecType + // { + // SC_SPEC_TYPE_VAL = 0, + // + // // Types with no parameters. + // SC_SPEC_TYPE_BOOL = 1, + // SC_SPEC_TYPE_VOID = 2, + // SC_SPEC_TYPE_ERROR = 3, + // SC_SPEC_TYPE_U32 = 4, + // SC_SPEC_TYPE_I32 = 5, + // SC_SPEC_TYPE_U64 = 6, + // SC_SPEC_TYPE_I64 = 7, + // SC_SPEC_TYPE_TIMEPOINT = 8, + // SC_SPEC_TYPE_DURATION = 9, + // SC_SPEC_TYPE_U128 = 10, + // SC_SPEC_TYPE_I128 = 11, + // SC_SPEC_TYPE_U256 = 12, + // SC_SPEC_TYPE_I256 = 13, + // SC_SPEC_TYPE_BYTES = 14, + // SC_SPEC_TYPE_STRING = 16, + // SC_SPEC_TYPE_SYMBOL = 17, + // SC_SPEC_TYPE_ADDRESS = 19, + // + // // Types with parameters. + // SC_SPEC_TYPE_OPTION = 1000, + // SC_SPEC_TYPE_RESULT = 1001, + // SC_SPEC_TYPE_VEC = 1002, + // SC_SPEC_TYPE_MAP = 1004, + // SC_SPEC_TYPE_TUPLE = 1005, + // SC_SPEC_TYPE_BYTES_N = 1006, + // + // // User defined types. + // SC_SPEC_TYPE_UDT = 2000 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecType", { + scSpecTypeVal: 0, + scSpecTypeBool: 1, + scSpecTypeVoid: 2, + scSpecTypeError: 3, + scSpecTypeU32: 4, + scSpecTypeI32: 5, + scSpecTypeU64: 6, + scSpecTypeI64: 7, + scSpecTypeTimepoint: 8, + scSpecTypeDuration: 9, + scSpecTypeU128: 10, + scSpecTypeI128: 11, + scSpecTypeU256: 12, + scSpecTypeI256: 13, + scSpecTypeBytes: 14, + scSpecTypeString: 16, + scSpecTypeSymbol: 17, + scSpecTypeAddress: 19, + scSpecTypeOption: 1000, + scSpecTypeResult: 1001, + scSpecTypeVec: 1002, + scSpecTypeMap: 1004, + scSpecTypeTuple: 1005, + scSpecTypeBytesN: 1006, + scSpecTypeUdt: 2000 + }); + + // === xdr source ============================================================ + // + // struct SCSpecTypeOption + // { + // SCSpecTypeDef valueType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeOption", [["valueType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeResult + // { + // SCSpecTypeDef okType; + // SCSpecTypeDef errorType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeResult", [["okType", xdr.lookup("ScSpecTypeDef")], ["errorType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeVec + // { + // SCSpecTypeDef elementType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeVec", [["elementType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeMap + // { + // SCSpecTypeDef keyType; + // SCSpecTypeDef valueType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeMap", [["keyType", xdr.lookup("ScSpecTypeDef")], ["valueType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeTuple + // { + // SCSpecTypeDef valueTypes<12>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeTuple", [["valueTypes", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 12)]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeBytesN + // { + // uint32 n; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeBytesN", [["n", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeUDT + // { + // string name<60>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeUdt", [["name", xdr.string(60)]]); + + // === xdr source ============================================================ + // + // union SCSpecTypeDef switch (SCSpecType type) + // { + // case SC_SPEC_TYPE_VAL: + // case SC_SPEC_TYPE_BOOL: + // case SC_SPEC_TYPE_VOID: + // case SC_SPEC_TYPE_ERROR: + // case SC_SPEC_TYPE_U32: + // case SC_SPEC_TYPE_I32: + // case SC_SPEC_TYPE_U64: + // case SC_SPEC_TYPE_I64: + // case SC_SPEC_TYPE_TIMEPOINT: + // case SC_SPEC_TYPE_DURATION: + // case SC_SPEC_TYPE_U128: + // case SC_SPEC_TYPE_I128: + // case SC_SPEC_TYPE_U256: + // case SC_SPEC_TYPE_I256: + // case SC_SPEC_TYPE_BYTES: + // case SC_SPEC_TYPE_STRING: + // case SC_SPEC_TYPE_SYMBOL: + // case SC_SPEC_TYPE_ADDRESS: + // void; + // case SC_SPEC_TYPE_OPTION: + // SCSpecTypeOption option; + // case SC_SPEC_TYPE_RESULT: + // SCSpecTypeResult result; + // case SC_SPEC_TYPE_VEC: + // SCSpecTypeVec vec; + // case SC_SPEC_TYPE_MAP: + // SCSpecTypeMap map; + // case SC_SPEC_TYPE_TUPLE: + // SCSpecTypeTuple tuple; + // case SC_SPEC_TYPE_BYTES_N: + // SCSpecTypeBytesN bytesN; + // case SC_SPEC_TYPE_UDT: + // SCSpecTypeUDT udt; + // }; + // + // =========================================================================== + xdr.union("ScSpecTypeDef", { + switchOn: xdr.lookup("ScSpecType"), + switchName: "type", + switches: [["scSpecTypeVal", xdr["void"]()], ["scSpecTypeBool", xdr["void"]()], ["scSpecTypeVoid", xdr["void"]()], ["scSpecTypeError", xdr["void"]()], ["scSpecTypeU32", xdr["void"]()], ["scSpecTypeI32", xdr["void"]()], ["scSpecTypeU64", xdr["void"]()], ["scSpecTypeI64", xdr["void"]()], ["scSpecTypeTimepoint", xdr["void"]()], ["scSpecTypeDuration", xdr["void"]()], ["scSpecTypeU128", xdr["void"]()], ["scSpecTypeI128", xdr["void"]()], ["scSpecTypeU256", xdr["void"]()], ["scSpecTypeI256", xdr["void"]()], ["scSpecTypeBytes", xdr["void"]()], ["scSpecTypeString", xdr["void"]()], ["scSpecTypeSymbol", xdr["void"]()], ["scSpecTypeAddress", xdr["void"]()], ["scSpecTypeOption", "option"], ["scSpecTypeResult", "result"], ["scSpecTypeVec", "vec"], ["scSpecTypeMap", "map"], ["scSpecTypeTuple", "tuple"], ["scSpecTypeBytesN", "bytesN"], ["scSpecTypeUdt", "udt"]], + arms: { + option: xdr.lookup("ScSpecTypeOption"), + result: xdr.lookup("ScSpecTypeResult"), + vec: xdr.lookup("ScSpecTypeVec"), + map: xdr.lookup("ScSpecTypeMap"), + tuple: xdr.lookup("ScSpecTypeTuple"), + bytesN: xdr.lookup("ScSpecTypeBytesN"), + udt: xdr.lookup("ScSpecTypeUdt") + } + }); + + // === xdr source ============================================================ + // + // struct SCSpecUDTStructFieldV0 + // { + // string doc; + // string name<30>; + // SCSpecTypeDef type; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtStructFieldV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(30)], ["type", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTStructV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTStructFieldV0 fields<40>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtStructV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["fields", xdr.varArray(xdr.lookup("ScSpecUdtStructFieldV0"), 40)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionCaseVoidV0 + // { + // string doc; + // string name<60>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionCaseVoidV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionCaseTupleV0 + // { + // string doc; + // string name<60>; + // SCSpecTypeDef type<12>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionCaseTupleV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["type", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 12)]]); + + // === xdr source ============================================================ + // + // enum SCSpecUDTUnionCaseV0Kind + // { + // SC_SPEC_UDT_UNION_CASE_VOID_V0 = 0, + // SC_SPEC_UDT_UNION_CASE_TUPLE_V0 = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecUdtUnionCaseV0Kind", { + scSpecUdtUnionCaseVoidV0: 0, + scSpecUdtUnionCaseTupleV0: 1 + }); + + // === xdr source ============================================================ + // + // union SCSpecUDTUnionCaseV0 switch (SCSpecUDTUnionCaseV0Kind kind) + // { + // case SC_SPEC_UDT_UNION_CASE_VOID_V0: + // SCSpecUDTUnionCaseVoidV0 voidCase; + // case SC_SPEC_UDT_UNION_CASE_TUPLE_V0: + // SCSpecUDTUnionCaseTupleV0 tupleCase; + // }; + // + // =========================================================================== + xdr.union("ScSpecUdtUnionCaseV0", { + switchOn: xdr.lookup("ScSpecUdtUnionCaseV0Kind"), + switchName: "kind", + switches: [["scSpecUdtUnionCaseVoidV0", "voidCase"], ["scSpecUdtUnionCaseTupleV0", "tupleCase"]], + arms: { + voidCase: xdr.lookup("ScSpecUdtUnionCaseVoidV0"), + tupleCase: xdr.lookup("ScSpecUdtUnionCaseTupleV0") + } + }); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTUnionCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtUnionCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTEnumCaseV0 + // { + // string doc; + // string name<60>; + // uint32 value; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtEnumCaseV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["value", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTEnumV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTEnumCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtEnumV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtEnumCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTErrorEnumCaseV0 + // { + // string doc; + // string name<60>; + // uint32 value; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtErrorEnumCaseV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["value", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTErrorEnumV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTErrorEnumCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtErrorEnumV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtErrorEnumCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecFunctionInputV0 + // { + // string doc; + // string name<30>; + // SCSpecTypeDef type; + // }; + // + // =========================================================================== + xdr.struct("ScSpecFunctionInputV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(30)], ["type", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecFunctionV0 + // { + // string doc; + // SCSymbol name; + // SCSpecFunctionInputV0 inputs<10>; + // SCSpecTypeDef outputs<1>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecFunctionV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.lookup("ScSymbol")], ["inputs", xdr.varArray(xdr.lookup("ScSpecFunctionInputV0"), 10)], ["outputs", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 1)]]); + + // === xdr source ============================================================ + // + // enum SCSpecEntryKind + // { + // SC_SPEC_ENTRY_FUNCTION_V0 = 0, + // SC_SPEC_ENTRY_UDT_STRUCT_V0 = 1, + // SC_SPEC_ENTRY_UDT_UNION_V0 = 2, + // SC_SPEC_ENTRY_UDT_ENUM_V0 = 3, + // SC_SPEC_ENTRY_UDT_ERROR_ENUM_V0 = 4 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecEntryKind", { + scSpecEntryFunctionV0: 0, + scSpecEntryUdtStructV0: 1, + scSpecEntryUdtUnionV0: 2, + scSpecEntryUdtEnumV0: 3, + scSpecEntryUdtErrorEnumV0: 4 + }); + + // === xdr source ============================================================ + // + // union SCSpecEntry switch (SCSpecEntryKind kind) + // { + // case SC_SPEC_ENTRY_FUNCTION_V0: + // SCSpecFunctionV0 functionV0; + // case SC_SPEC_ENTRY_UDT_STRUCT_V0: + // SCSpecUDTStructV0 udtStructV0; + // case SC_SPEC_ENTRY_UDT_UNION_V0: + // SCSpecUDTUnionV0 udtUnionV0; + // case SC_SPEC_ENTRY_UDT_ENUM_V0: + // SCSpecUDTEnumV0 udtEnumV0; + // case SC_SPEC_ENTRY_UDT_ERROR_ENUM_V0: + // SCSpecUDTErrorEnumV0 udtErrorEnumV0; + // }; + // + // =========================================================================== + xdr.union("ScSpecEntry", { + switchOn: xdr.lookup("ScSpecEntryKind"), + switchName: "kind", + switches: [["scSpecEntryFunctionV0", "functionV0"], ["scSpecEntryUdtStructV0", "udtStructV0"], ["scSpecEntryUdtUnionV0", "udtUnionV0"], ["scSpecEntryUdtEnumV0", "udtEnumV0"], ["scSpecEntryUdtErrorEnumV0", "udtErrorEnumV0"]], + arms: { + functionV0: xdr.lookup("ScSpecFunctionV0"), + udtStructV0: xdr.lookup("ScSpecUdtStructV0"), + udtUnionV0: xdr.lookup("ScSpecUdtUnionV0"), + udtEnumV0: xdr.lookup("ScSpecUdtEnumV0"), + udtErrorEnumV0: xdr.lookup("ScSpecUdtErrorEnumV0") + } + }); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractExecutionLanesV0 + // { + // // maximum number of Soroban transactions per ledger + // uint32 ledgerMaxTxCount; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractExecutionLanesV0", [["ledgerMaxTxCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractComputeV0 + // { + // // Maximum instructions per ledger + // int64 ledgerMaxInstructions; + // // Maximum instructions per transaction + // int64 txMaxInstructions; + // // Cost of 10000 instructions + // int64 feeRatePerInstructionsIncrement; + // + // // Memory limit per transaction. Unlike instructions, there is no fee + // // for memory, just the limit. + // uint32 txMemoryLimit; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractComputeV0", [["ledgerMaxInstructions", xdr.lookup("Int64")], ["txMaxInstructions", xdr.lookup("Int64")], ["feeRatePerInstructionsIncrement", xdr.lookup("Int64")], ["txMemoryLimit", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractLedgerCostV0 + // { + // // Maximum number of ledger entry read operations per ledger + // uint32 ledgerMaxReadLedgerEntries; + // // Maximum number of bytes that can be read per ledger + // uint32 ledgerMaxReadBytes; + // // Maximum number of ledger entry write operations per ledger + // uint32 ledgerMaxWriteLedgerEntries; + // // Maximum number of bytes that can be written per ledger + // uint32 ledgerMaxWriteBytes; + // + // // Maximum number of ledger entry read operations per transaction + // uint32 txMaxReadLedgerEntries; + // // Maximum number of bytes that can be read per transaction + // uint32 txMaxReadBytes; + // // Maximum number of ledger entry write operations per transaction + // uint32 txMaxWriteLedgerEntries; + // // Maximum number of bytes that can be written per transaction + // uint32 txMaxWriteBytes; + // + // int64 feeReadLedgerEntry; // Fee per ledger entry read + // int64 feeWriteLedgerEntry; // Fee per ledger entry write + // + // int64 feeRead1KB; // Fee for reading 1KB + // + // // The following parameters determine the write fee per 1KB. + // // Write fee grows linearly until bucket list reaches this size + // int64 bucketListTargetSizeBytes; + // // Fee per 1KB write when the bucket list is empty + // int64 writeFee1KBBucketListLow; + // // Fee per 1KB write when the bucket list has reached `bucketListTargetSizeBytes` + // int64 writeFee1KBBucketListHigh; + // // Write fee multiplier for any additional data past the first `bucketListTargetSizeBytes` + // uint32 bucketListWriteFeeGrowthFactor; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractLedgerCostV0", [["ledgerMaxReadLedgerEntries", xdr.lookup("Uint32")], ["ledgerMaxReadBytes", xdr.lookup("Uint32")], ["ledgerMaxWriteLedgerEntries", xdr.lookup("Uint32")], ["ledgerMaxWriteBytes", xdr.lookup("Uint32")], ["txMaxReadLedgerEntries", xdr.lookup("Uint32")], ["txMaxReadBytes", xdr.lookup("Uint32")], ["txMaxWriteLedgerEntries", xdr.lookup("Uint32")], ["txMaxWriteBytes", xdr.lookup("Uint32")], ["feeReadLedgerEntry", xdr.lookup("Int64")], ["feeWriteLedgerEntry", xdr.lookup("Int64")], ["feeRead1Kb", xdr.lookup("Int64")], ["bucketListTargetSizeBytes", xdr.lookup("Int64")], ["writeFee1KbBucketListLow", xdr.lookup("Int64")], ["writeFee1KbBucketListHigh", xdr.lookup("Int64")], ["bucketListWriteFeeGrowthFactor", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractHistoricalDataV0 + // { + // int64 feeHistorical1KB; // Fee for storing 1KB in archives + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractHistoricalDataV0", [["feeHistorical1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractEventsV0 + // { + // // Maximum size of events that a contract call can emit. + // uint32 txMaxContractEventsSizeBytes; + // // Fee for generating 1KB of contract events. + // int64 feeContractEvents1KB; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractEventsV0", [["txMaxContractEventsSizeBytes", xdr.lookup("Uint32")], ["feeContractEvents1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractBandwidthV0 + // { + // // Maximum sum of all transaction sizes in the ledger in bytes + // uint32 ledgerMaxTxsSizeBytes; + // // Maximum size in bytes for a transaction + // uint32 txMaxSizeBytes; + // + // // Fee for 1 KB of transaction size + // int64 feeTxSize1KB; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractBandwidthV0", [["ledgerMaxTxsSizeBytes", xdr.lookup("Uint32")], ["txMaxSizeBytes", xdr.lookup("Uint32")], ["feeTxSize1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum ContractCostType { + // // Cost of running 1 wasm instruction + // WasmInsnExec = 0, + // // Cost of allocating a slice of memory (in bytes) + // MemAlloc = 1, + // // Cost of copying a slice of bytes into a pre-allocated memory + // MemCpy = 2, + // // Cost of comparing two slices of memory + // MemCmp = 3, + // // Cost of a host function dispatch, not including the actual work done by + // // the function nor the cost of VM invocation machinary + // DispatchHostFunction = 4, + // // Cost of visiting a host object from the host object storage. Exists to + // // make sure some baseline cost coverage, i.e. repeatly visiting objects + // // by the guest will always incur some charges. + // VisitObject = 5, + // // Cost of serializing an xdr object to bytes + // ValSer = 6, + // // Cost of deserializing an xdr object from bytes + // ValDeser = 7, + // // Cost of computing the sha256 hash from bytes + // ComputeSha256Hash = 8, + // // Cost of computing the ed25519 pubkey from bytes + // ComputeEd25519PubKey = 9, + // // Cost of verifying ed25519 signature of a payload. + // VerifyEd25519Sig = 10, + // // Cost of instantiation a VM from wasm bytes code. + // VmInstantiation = 11, + // // Cost of instantiation a VM from a cached state. + // VmCachedInstantiation = 12, + // // Cost of invoking a function on the VM. If the function is a host function, + // // additional cost will be covered by `DispatchHostFunction`. + // InvokeVmFunction = 13, + // // Cost of computing a keccak256 hash from bytes. + // ComputeKeccak256Hash = 14, + // // Cost of decoding an ECDSA signature computed from a 256-bit prime modulus + // // curve (e.g. secp256k1 and secp256r1) + // DecodeEcdsaCurve256Sig = 15, + // // Cost of recovering an ECDSA secp256k1 key from a signature. + // RecoverEcdsaSecp256k1Key = 16, + // // Cost of int256 addition (`+`) and subtraction (`-`) operations + // Int256AddSub = 17, + // // Cost of int256 multiplication (`*`) operation + // Int256Mul = 18, + // // Cost of int256 division (`/`) operation + // Int256Div = 19, + // // Cost of int256 power (`exp`) operation + // Int256Pow = 20, + // // Cost of int256 shift (`shl`, `shr`) operation + // Int256Shift = 21, + // // Cost of drawing random bytes using a ChaCha20 PRNG + // ChaCha20DrawBytes = 22, + // + // // Cost of parsing wasm bytes that only encode instructions. + // ParseWasmInstructions = 23, + // // Cost of parsing a known number of wasm functions. + // ParseWasmFunctions = 24, + // // Cost of parsing a known number of wasm globals. + // ParseWasmGlobals = 25, + // // Cost of parsing a known number of wasm table entries. + // ParseWasmTableEntries = 26, + // // Cost of parsing a known number of wasm types. + // ParseWasmTypes = 27, + // // Cost of parsing a known number of wasm data segments. + // ParseWasmDataSegments = 28, + // // Cost of parsing a known number of wasm element segments. + // ParseWasmElemSegments = 29, + // // Cost of parsing a known number of wasm imports. + // ParseWasmImports = 30, + // // Cost of parsing a known number of wasm exports. + // ParseWasmExports = 31, + // // Cost of parsing a known number of data segment bytes. + // ParseWasmDataSegmentBytes = 32, + // + // // Cost of instantiating wasm bytes that only encode instructions. + // InstantiateWasmInstructions = 33, + // // Cost of instantiating a known number of wasm functions. + // InstantiateWasmFunctions = 34, + // // Cost of instantiating a known number of wasm globals. + // InstantiateWasmGlobals = 35, + // // Cost of instantiating a known number of wasm table entries. + // InstantiateWasmTableEntries = 36, + // // Cost of instantiating a known number of wasm types. + // InstantiateWasmTypes = 37, + // // Cost of instantiating a known number of wasm data segments. + // InstantiateWasmDataSegments = 38, + // // Cost of instantiating a known number of wasm element segments. + // InstantiateWasmElemSegments = 39, + // // Cost of instantiating a known number of wasm imports. + // InstantiateWasmImports = 40, + // // Cost of instantiating a known number of wasm exports. + // InstantiateWasmExports = 41, + // // Cost of instantiating a known number of data segment bytes. + // InstantiateWasmDataSegmentBytes = 42, + // + // // Cost of decoding a bytes array representing an uncompressed SEC-1 encoded + // // point on a 256-bit elliptic curve + // Sec1DecodePointUncompressed = 43, + // // Cost of verifying an ECDSA Secp256r1 signature + // VerifyEcdsaSecp256r1Sig = 44, + // + // // Cost of encoding a BLS12-381 Fp (base field element) + // Bls12381EncodeFp = 45, + // // Cost of decoding a BLS12-381 Fp (base field element) + // Bls12381DecodeFp = 46, + // // Cost of checking a G1 point lies on the curve + // Bls12381G1CheckPointOnCurve = 47, + // // Cost of checking a G1 point belongs to the correct subgroup + // Bls12381G1CheckPointInSubgroup = 48, + // // Cost of checking a G2 point lies on the curve + // Bls12381G2CheckPointOnCurve = 49, + // // Cost of checking a G2 point belongs to the correct subgroup + // Bls12381G2CheckPointInSubgroup = 50, + // // Cost of converting a BLS12-381 G1 point from projective to affine coordinates + // Bls12381G1ProjectiveToAffine = 51, + // // Cost of converting a BLS12-381 G2 point from projective to affine coordinates + // Bls12381G2ProjectiveToAffine = 52, + // // Cost of performing BLS12-381 G1 point addition + // Bls12381G1Add = 53, + // // Cost of performing BLS12-381 G1 scalar multiplication + // Bls12381G1Mul = 54, + // // Cost of performing BLS12-381 G1 multi-scalar multiplication (MSM) + // Bls12381G1Msm = 55, + // // Cost of mapping a BLS12-381 Fp field element to a G1 point + // Bls12381MapFpToG1 = 56, + // // Cost of hashing to a BLS12-381 G1 point + // Bls12381HashToG1 = 57, + // // Cost of performing BLS12-381 G2 point addition + // Bls12381G2Add = 58, + // // Cost of performing BLS12-381 G2 scalar multiplication + // Bls12381G2Mul = 59, + // // Cost of performing BLS12-381 G2 multi-scalar multiplication (MSM) + // Bls12381G2Msm = 60, + // // Cost of mapping a BLS12-381 Fp2 field element to a G2 point + // Bls12381MapFp2ToG2 = 61, + // // Cost of hashing to a BLS12-381 G2 point + // Bls12381HashToG2 = 62, + // // Cost of performing BLS12-381 pairing operation + // Bls12381Pairing = 63, + // // Cost of converting a BLS12-381 scalar element from U256 + // Bls12381FrFromU256 = 64, + // // Cost of converting a BLS12-381 scalar element to U256 + // Bls12381FrToU256 = 65, + // // Cost of performing BLS12-381 scalar element addition/subtraction + // Bls12381FrAddSub = 66, + // // Cost of performing BLS12-381 scalar element multiplication + // Bls12381FrMul = 67, + // // Cost of performing BLS12-381 scalar element exponentiation + // Bls12381FrPow = 68, + // // Cost of performing BLS12-381 scalar element inversion + // Bls12381FrInv = 69 + // }; + // + // =========================================================================== + xdr["enum"]("ContractCostType", { + wasmInsnExec: 0, + memAlloc: 1, + memCpy: 2, + memCmp: 3, + dispatchHostFunction: 4, + visitObject: 5, + valSer: 6, + valDeser: 7, + computeSha256Hash: 8, + computeEd25519PubKey: 9, + verifyEd25519Sig: 10, + vmInstantiation: 11, + vmCachedInstantiation: 12, + invokeVmFunction: 13, + computeKeccak256Hash: 14, + decodeEcdsaCurve256Sig: 15, + recoverEcdsaSecp256k1Key: 16, + int256AddSub: 17, + int256Mul: 18, + int256Div: 19, + int256Pow: 20, + int256Shift: 21, + chaCha20DrawBytes: 22, + parseWasmInstructions: 23, + parseWasmFunctions: 24, + parseWasmGlobals: 25, + parseWasmTableEntries: 26, + parseWasmTypes: 27, + parseWasmDataSegments: 28, + parseWasmElemSegments: 29, + parseWasmImports: 30, + parseWasmExports: 31, + parseWasmDataSegmentBytes: 32, + instantiateWasmInstructions: 33, + instantiateWasmFunctions: 34, + instantiateWasmGlobals: 35, + instantiateWasmTableEntries: 36, + instantiateWasmTypes: 37, + instantiateWasmDataSegments: 38, + instantiateWasmElemSegments: 39, + instantiateWasmImports: 40, + instantiateWasmExports: 41, + instantiateWasmDataSegmentBytes: 42, + sec1DecodePointUncompressed: 43, + verifyEcdsaSecp256r1Sig: 44, + bls12381EncodeFp: 45, + bls12381DecodeFp: 46, + bls12381G1CheckPointOnCurve: 47, + bls12381G1CheckPointInSubgroup: 48, + bls12381G2CheckPointOnCurve: 49, + bls12381G2CheckPointInSubgroup: 50, + bls12381G1ProjectiveToAffine: 51, + bls12381G2ProjectiveToAffine: 52, + bls12381G1Add: 53, + bls12381G1Mul: 54, + bls12381G1Msm: 55, + bls12381MapFpToG1: 56, + bls12381HashToG1: 57, + bls12381G2Add: 58, + bls12381G2Mul: 59, + bls12381G2Msm: 60, + bls12381MapFp2ToG2: 61, + bls12381HashToG2: 62, + bls12381Pairing: 63, + bls12381FrFromU256: 64, + bls12381FrToU256: 65, + bls12381FrAddSub: 66, + bls12381FrMul: 67, + bls12381FrPow: 68, + bls12381FrInv: 69 + }); + + // === xdr source ============================================================ + // + // struct ContractCostParamEntry { + // // use `ext` to add more terms (e.g. higher order polynomials) in the future + // ExtensionPoint ext; + // + // int64 constTerm; + // int64 linearTerm; + // }; + // + // =========================================================================== + xdr.struct("ContractCostParamEntry", [["ext", xdr.lookup("ExtensionPoint")], ["constTerm", xdr.lookup("Int64")], ["linearTerm", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct StateArchivalSettings { + // uint32 maxEntryTTL; + // uint32 minTemporaryTTL; + // uint32 minPersistentTTL; + // + // // rent_fee = wfee_rate_average / rent_rate_denominator_for_type + // int64 persistentRentRateDenominator; + // int64 tempRentRateDenominator; + // + // // max number of entries that emit archival meta in a single ledger + // uint32 maxEntriesToArchive; + // + // // Number of snapshots to use when calculating average BucketList size + // uint32 bucketListSizeWindowSampleSize; + // + // // How often to sample the BucketList size for the average, in ledgers + // uint32 bucketListWindowSamplePeriod; + // + // // Maximum number of bytes that we scan for eviction per ledger + // uint32 evictionScanSize; + // + // // Lowest BucketList level to be scanned to evict entries + // uint32 startingEvictionScanLevel; + // }; + // + // =========================================================================== + xdr.struct("StateArchivalSettings", [["maxEntryTtl", xdr.lookup("Uint32")], ["minTemporaryTtl", xdr.lookup("Uint32")], ["minPersistentTtl", xdr.lookup("Uint32")], ["persistentRentRateDenominator", xdr.lookup("Int64")], ["tempRentRateDenominator", xdr.lookup("Int64")], ["maxEntriesToArchive", xdr.lookup("Uint32")], ["bucketListSizeWindowSampleSize", xdr.lookup("Uint32")], ["bucketListWindowSamplePeriod", xdr.lookup("Uint32")], ["evictionScanSize", xdr.lookup("Uint32")], ["startingEvictionScanLevel", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct EvictionIterator { + // uint32 bucketListLevel; + // bool isCurrBucket; + // uint64 bucketFileOffset; + // }; + // + // =========================================================================== + xdr.struct("EvictionIterator", [["bucketListLevel", xdr.lookup("Uint32")], ["isCurrBucket", xdr.bool()], ["bucketFileOffset", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // const CONTRACT_COST_COUNT_LIMIT = 1024; + // + // =========================================================================== + xdr["const"]("CONTRACT_COST_COUNT_LIMIT", 1024); + + // === xdr source ============================================================ + // + // typedef ContractCostParamEntry ContractCostParams; + // + // =========================================================================== + xdr.typedef("ContractCostParams", xdr.varArray(xdr.lookup("ContractCostParamEntry"), xdr.lookup("CONTRACT_COST_COUNT_LIMIT"))); + + // === xdr source ============================================================ + // + // enum ConfigSettingID + // { + // CONFIG_SETTING_CONTRACT_MAX_SIZE_BYTES = 0, + // CONFIG_SETTING_CONTRACT_COMPUTE_V0 = 1, + // CONFIG_SETTING_CONTRACT_LEDGER_COST_V0 = 2, + // CONFIG_SETTING_CONTRACT_HISTORICAL_DATA_V0 = 3, + // CONFIG_SETTING_CONTRACT_EVENTS_V0 = 4, + // CONFIG_SETTING_CONTRACT_BANDWIDTH_V0 = 5, + // CONFIG_SETTING_CONTRACT_COST_PARAMS_CPU_INSTRUCTIONS = 6, + // CONFIG_SETTING_CONTRACT_COST_PARAMS_MEMORY_BYTES = 7, + // CONFIG_SETTING_CONTRACT_DATA_KEY_SIZE_BYTES = 8, + // CONFIG_SETTING_CONTRACT_DATA_ENTRY_SIZE_BYTES = 9, + // CONFIG_SETTING_STATE_ARCHIVAL = 10, + // CONFIG_SETTING_CONTRACT_EXECUTION_LANES = 11, + // CONFIG_SETTING_BUCKETLIST_SIZE_WINDOW = 12, + // CONFIG_SETTING_EVICTION_ITERATOR = 13 + // }; + // + // =========================================================================== + xdr["enum"]("ConfigSettingId", { + configSettingContractMaxSizeBytes: 0, + configSettingContractComputeV0: 1, + configSettingContractLedgerCostV0: 2, + configSettingContractHistoricalDataV0: 3, + configSettingContractEventsV0: 4, + configSettingContractBandwidthV0: 5, + configSettingContractCostParamsCpuInstructions: 6, + configSettingContractCostParamsMemoryBytes: 7, + configSettingContractDataKeySizeBytes: 8, + configSettingContractDataEntrySizeBytes: 9, + configSettingStateArchival: 10, + configSettingContractExecutionLanes: 11, + configSettingBucketlistSizeWindow: 12, + configSettingEvictionIterator: 13 + }); + + // === xdr source ============================================================ + // + // union ConfigSettingEntry switch (ConfigSettingID configSettingID) + // { + // case CONFIG_SETTING_CONTRACT_MAX_SIZE_BYTES: + // uint32 contractMaxSizeBytes; + // case CONFIG_SETTING_CONTRACT_COMPUTE_V0: + // ConfigSettingContractComputeV0 contractCompute; + // case CONFIG_SETTING_CONTRACT_LEDGER_COST_V0: + // ConfigSettingContractLedgerCostV0 contractLedgerCost; + // case CONFIG_SETTING_CONTRACT_HISTORICAL_DATA_V0: + // ConfigSettingContractHistoricalDataV0 contractHistoricalData; + // case CONFIG_SETTING_CONTRACT_EVENTS_V0: + // ConfigSettingContractEventsV0 contractEvents; + // case CONFIG_SETTING_CONTRACT_BANDWIDTH_V0: + // ConfigSettingContractBandwidthV0 contractBandwidth; + // case CONFIG_SETTING_CONTRACT_COST_PARAMS_CPU_INSTRUCTIONS: + // ContractCostParams contractCostParamsCpuInsns; + // case CONFIG_SETTING_CONTRACT_COST_PARAMS_MEMORY_BYTES: + // ContractCostParams contractCostParamsMemBytes; + // case CONFIG_SETTING_CONTRACT_DATA_KEY_SIZE_BYTES: + // uint32 contractDataKeySizeBytes; + // case CONFIG_SETTING_CONTRACT_DATA_ENTRY_SIZE_BYTES: + // uint32 contractDataEntrySizeBytes; + // case CONFIG_SETTING_STATE_ARCHIVAL: + // StateArchivalSettings stateArchivalSettings; + // case CONFIG_SETTING_CONTRACT_EXECUTION_LANES: + // ConfigSettingContractExecutionLanesV0 contractExecutionLanes; + // case CONFIG_SETTING_BUCKETLIST_SIZE_WINDOW: + // uint64 bucketListSizeWindow<>; + // case CONFIG_SETTING_EVICTION_ITERATOR: + // EvictionIterator evictionIterator; + // }; + // + // =========================================================================== + xdr.union("ConfigSettingEntry", { + switchOn: xdr.lookup("ConfigSettingId"), + switchName: "configSettingId", + switches: [["configSettingContractMaxSizeBytes", "contractMaxSizeBytes"], ["configSettingContractComputeV0", "contractCompute"], ["configSettingContractLedgerCostV0", "contractLedgerCost"], ["configSettingContractHistoricalDataV0", "contractHistoricalData"], ["configSettingContractEventsV0", "contractEvents"], ["configSettingContractBandwidthV0", "contractBandwidth"], ["configSettingContractCostParamsCpuInstructions", "contractCostParamsCpuInsns"], ["configSettingContractCostParamsMemoryBytes", "contractCostParamsMemBytes"], ["configSettingContractDataKeySizeBytes", "contractDataKeySizeBytes"], ["configSettingContractDataEntrySizeBytes", "contractDataEntrySizeBytes"], ["configSettingStateArchival", "stateArchivalSettings"], ["configSettingContractExecutionLanes", "contractExecutionLanes"], ["configSettingBucketlistSizeWindow", "bucketListSizeWindow"], ["configSettingEvictionIterator", "evictionIterator"]], + arms: { + contractMaxSizeBytes: xdr.lookup("Uint32"), + contractCompute: xdr.lookup("ConfigSettingContractComputeV0"), + contractLedgerCost: xdr.lookup("ConfigSettingContractLedgerCostV0"), + contractHistoricalData: xdr.lookup("ConfigSettingContractHistoricalDataV0"), + contractEvents: xdr.lookup("ConfigSettingContractEventsV0"), + contractBandwidth: xdr.lookup("ConfigSettingContractBandwidthV0"), + contractCostParamsCpuInsns: xdr.lookup("ContractCostParams"), + contractCostParamsMemBytes: xdr.lookup("ContractCostParams"), + contractDataKeySizeBytes: xdr.lookup("Uint32"), + contractDataEntrySizeBytes: xdr.lookup("Uint32"), + stateArchivalSettings: xdr.lookup("StateArchivalSettings"), + contractExecutionLanes: xdr.lookup("ConfigSettingContractExecutionLanesV0"), + bucketListSizeWindow: xdr.varArray(xdr.lookup("Uint64"), 2147483647), + evictionIterator: xdr.lookup("EvictionIterator") + } + }); +}); +/* harmony default export */ const curr_generated = (types); +;// ./src/xdr.js + +/* harmony default export */ const src_xdr = (curr_generated); +;// ./src/jsxdr.js + +var cereal = { + XdrWriter: xdr.XdrWriter, + XdrReader: xdr.XdrReader +}; +/* harmony default export */ const jsxdr = (cereal); +// EXTERNAL MODULE: ./node_modules/sha.js/index.js +var sha_js = __webpack_require__(2802); +;// ./src/hashing.js + +function hashing_hash(data) { + var hasher = new sha_js.sha256(); + hasher.update(data, 'utf8'); + return hasher.digest(); +} +;// ./src/signing.js +/* provided dependency */ var Buffer = __webpack_require__(3626)["A"]; +// This module provides the signing functionality used by the stellar network +// The code below may look a little strange... this is because we try to provide +// the most efficient signing method possible. First, we try to load the +// native `sodium-native` package for node.js environments, and if that fails we +// fallback to `tweetnacl` + +var actualMethods = {}; + +/** + * Use this flag to check if fast signing (provided by `sodium-native` package) is available. + * If your app is signing a large number of transaction or verifying a large number + * of signatures make sure `sodium-native` package is installed. + */ +var FastSigning = checkFastSigning(); +function signing_sign(data, secretKey) { + return actualMethods.sign(data, secretKey); +} +function signing_verify(data, signature, publicKey) { + return actualMethods.verify(data, signature, publicKey); +} +function generate(secretKey) { + return actualMethods.generate(secretKey); +} +function checkFastSigning() { + return typeof window === 'undefined' ? checkFastSigningNode() : checkFastSigningBrowser(); +} +function checkFastSigningNode() { + // NOTE: we use commonjs style require here because es6 imports + // can only occur at the top level. thanks, obama. + var sodium; + try { + // eslint-disable-next-line + sodium = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module 'sodium-native'"); e.code = 'MODULE_NOT_FOUND'; throw e; }())); + } catch (err) { + return checkFastSigningBrowser(); + } + if (!Object.keys(sodium).length) { + return checkFastSigningBrowser(); + } + actualMethods.generate = function (secretKey) { + var pk = Buffer.alloc(sodium.crypto_sign_PUBLICKEYBYTES); + var sk = Buffer.alloc(sodium.crypto_sign_SECRETKEYBYTES); + sodium.crypto_sign_seed_keypair(pk, sk, secretKey); + return pk; + }; + actualMethods.sign = function (data, secretKey) { + data = Buffer.from(data); + var signature = Buffer.alloc(sodium.crypto_sign_BYTES); + sodium.crypto_sign_detached(signature, data, secretKey); + return signature; + }; + actualMethods.verify = function (data, signature, publicKey) { + data = Buffer.from(data); + try { + return sodium.crypto_sign_verify_detached(signature, data, publicKey); + } catch (e) { + return false; + } + }; + return true; +} +function checkFastSigningBrowser() { + // fallback to `tweetnacl` if we're in the browser or + // if there was a failure installing `sodium-native` + // eslint-disable-next-line + var nacl = __webpack_require__(8947); + actualMethods.generate = function (secretKey) { + var secretKeyUint8 = new Uint8Array(secretKey); + var naclKeys = nacl.sign.keyPair.fromSeed(secretKeyUint8); + return Buffer.from(naclKeys.publicKey); + }; + actualMethods.sign = function (data, secretKey) { + data = Buffer.from(data); + data = new Uint8Array(data.toJSON().data); + secretKey = new Uint8Array(secretKey.toJSON().data); + var signature = nacl.sign.detached(data, secretKey); + return Buffer.from(signature); + }; + actualMethods.verify = function (data, signature, publicKey) { + data = Buffer.from(data); + data = new Uint8Array(data.toJSON().data); + signature = new Uint8Array(signature.toJSON().data); + publicKey = new Uint8Array(publicKey.toJSON().data); + return nacl.sign.detached.verify(data, signature, publicKey); + }; + return false; +} +;// ./src/util/util.js +var trimEnd = function trimEnd(input, _char) { + var isNumber = typeof input === 'number'; + var str = String(input); + while (str.endsWith(_char)) { + str = str.slice(0, -1); + } + return isNumber ? Number(str) : str; +}; +// EXTERNAL MODULE: ./node_modules/tweetnacl/nacl-fast.js +var nacl_fast = __webpack_require__(8947); +var nacl_fast_default = /*#__PURE__*/__webpack_require__.n(nacl_fast); +// EXTERNAL MODULE: ./node_modules/base32.js/base32.js +var base32 = __webpack_require__(5360); +;// ./src/util/checksum.js +function verifyChecksum(expected, actual) { + if (expected.length !== actual.length) { + return false; + } + if (expected.length === 0) { + return true; + } + for (var i = 0; i < expected.length; i += 1) { + if (expected[i] !== actual[i]) { + return false; + } + } + return true; +} +;// ./src/strkey.js +/* provided dependency */ var strkey_Buffer = __webpack_require__(3626)["A"]; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/* eslint no-bitwise: ["error", {"allow": ["<<", ">>", "^", "&", "&="]}] */ + + + +var versionBytes = { + ed25519PublicKey: 6 << 3, + // G (when encoded in base32) + ed25519SecretSeed: 18 << 3, + // S + med25519PublicKey: 12 << 3, + // M + preAuthTx: 19 << 3, + // T + sha256Hash: 23 << 3, + // X + signedPayload: 15 << 3, + // P + contract: 2 << 3 // C +}; +var strkeyTypes = { + G: 'ed25519PublicKey', + S: 'ed25519SecretSeed', + M: 'med25519PublicKey', + T: 'preAuthTx', + X: 'sha256Hash', + P: 'signedPayload', + C: 'contract' +}; + +/** + * StrKey is a helper class that allows encoding and decoding Stellar keys + * to/from strings, i.e. between their binary (Buffer, xdr.PublicKey, etc.) and + * string (i.e. "GABCD...", etc.) representations. + */ +var StrKey = /*#__PURE__*/function () { + function StrKey() { + _classCallCheck(this, StrKey); + } + return _createClass(StrKey, null, [{ + key: "encodeEd25519PublicKey", + value: + /** + * Encodes `data` to strkey ed25519 public key. + * + * @param {Buffer} data raw data to encode + * @returns {string} "G..." representation of the key + */ + function encodeEd25519PublicKey(data) { + return encodeCheck('ed25519PublicKey', data); + } + + /** + * Decodes strkey ed25519 public key to raw data. + * + * If the parameter is a muxed account key ("M..."), this will only encode it + * as a basic Ed25519 key (as if in "G..." format). + * + * @param {string} data "G..." (or "M...") key representation to decode + * @returns {Buffer} raw key + */ + }, { + key: "decodeEd25519PublicKey", + value: function decodeEd25519PublicKey(data) { + return decodeCheck('ed25519PublicKey', data); + } + + /** + * Returns true if the given Stellar public key is a valid ed25519 public key. + * @param {string} publicKey public key to check + * @returns {boolean} + */ + }, { + key: "isValidEd25519PublicKey", + value: function isValidEd25519PublicKey(publicKey) { + return isValid('ed25519PublicKey', publicKey); + } + + /** + * Encodes data to strkey ed25519 seed. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeEd25519SecretSeed", + value: function encodeEd25519SecretSeed(data) { + return encodeCheck('ed25519SecretSeed', data); + } + + /** + * Decodes strkey ed25519 seed to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeEd25519SecretSeed", + value: function decodeEd25519SecretSeed(address) { + return decodeCheck('ed25519SecretSeed', address); + } + + /** + * Returns true if the given Stellar secret key is a valid ed25519 secret seed. + * @param {string} seed seed to check + * @returns {boolean} + */ + }, { + key: "isValidEd25519SecretSeed", + value: function isValidEd25519SecretSeed(seed) { + return isValid('ed25519SecretSeed', seed); + } + + /** + * Encodes data to strkey med25519 public key. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeMed25519PublicKey", + value: function encodeMed25519PublicKey(data) { + return encodeCheck('med25519PublicKey', data); + } + + /** + * Decodes strkey med25519 public key to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeMed25519PublicKey", + value: function decodeMed25519PublicKey(address) { + return decodeCheck('med25519PublicKey', address); + } + + /** + * Returns true if the given Stellar public key is a valid med25519 public key. + * @param {string} publicKey public key to check + * @returns {boolean} + */ + }, { + key: "isValidMed25519PublicKey", + value: function isValidMed25519PublicKey(publicKey) { + return isValid('med25519PublicKey', publicKey); + } + + /** + * Encodes data to strkey preAuthTx. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodePreAuthTx", + value: function encodePreAuthTx(data) { + return encodeCheck('preAuthTx', data); + } + + /** + * Decodes strkey PreAuthTx to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodePreAuthTx", + value: function decodePreAuthTx(address) { + return decodeCheck('preAuthTx', address); + } + + /** + * Encodes data to strkey sha256 hash. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeSha256Hash", + value: function encodeSha256Hash(data) { + return encodeCheck('sha256Hash', data); + } + + /** + * Decodes strkey sha256 hash to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeSha256Hash", + value: function decodeSha256Hash(address) { + return decodeCheck('sha256Hash', address); + } + + /** + * Encodes raw data to strkey signed payload (P...). + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeSignedPayload", + value: function encodeSignedPayload(data) { + return encodeCheck('signedPayload', data); + } + + /** + * Decodes strkey signed payload (P...) to raw data. + * @param {string} address address to decode + * @returns {Buffer} + */ + }, { + key: "decodeSignedPayload", + value: function decodeSignedPayload(address) { + return decodeCheck('signedPayload', address); + } + + /** + * Checks validity of alleged signed payload (P...) strkey address. + * @param {string} address signer key to check + * @returns {boolean} + */ + }, { + key: "isValidSignedPayload", + value: function isValidSignedPayload(address) { + return isValid('signedPayload', address); + } + + /** + * Encodes raw data to strkey contract (C...). + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeContract", + value: function encodeContract(data) { + return encodeCheck('contract', data); + } + + /** + * Decodes strkey contract (C...) to raw data. + * @param {string} address address to decode + * @returns {Buffer} + */ + }, { + key: "decodeContract", + value: function decodeContract(address) { + return decodeCheck('contract', address); + } + + /** + * Checks validity of alleged contract (C...) strkey address. + * @param {string} address signer key to check + * @returns {boolean} + */ + }, { + key: "isValidContract", + value: function isValidContract(address) { + return isValid('contract', address); + } + }, { + key: "getVersionByteForPrefix", + value: function getVersionByteForPrefix(address) { + return strkeyTypes[address[0]]; + } + }]); +}(); + +/** + * Sanity-checks whether or not a strkey *appears* valid. + * + * @param {string} versionByteName the type of strkey to expect in `encoded` + * @param {string} encoded the strkey to validate + * + * @return {Boolean} whether or not the `encoded` strkey appears valid for the + * `versionByteName` strkey type (see `versionBytes`, above). + * + * @note This isn't a *definitive* check of validity, but rather a best-effort + * check based on (a) input length, (b) whether or not it can be decoded, + * and (c) output length. + */ +function isValid(versionByteName, encoded) { + if (typeof encoded !== 'string') { + return false; + } + + // basic length checks on the strkey lengths + switch (versionByteName) { + case 'ed25519PublicKey': // falls through + case 'ed25519SecretSeed': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + case 'contract': + if (encoded.length !== 56) { + return false; + } + break; + case 'med25519PublicKey': + if (encoded.length !== 69) { + return false; + } + break; + case 'signedPayload': + if (encoded.length < 56 || encoded.length > 165) { + return false; + } + break; + default: + return false; + } + var decoded = ''; + try { + decoded = decodeCheck(versionByteName, encoded); + } catch (err) { + return false; + } + + // basic length checks on the resulting buffer sizes + switch (versionByteName) { + case 'ed25519PublicKey': // falls through + case 'ed25519SecretSeed': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + case 'contract': + return decoded.length === 32; + case 'med25519PublicKey': + return decoded.length === 40; + // +8 bytes for the ID + + case 'signedPayload': + return ( + // 32 for the signer, +4 for the payload size, then either +4 for the + // min or +64 for the max payload + decoded.length >= 32 + 4 + 4 && decoded.length <= 32 + 4 + 64 + ); + default: + return false; + } +} +function decodeCheck(versionByteName, encoded) { + if (typeof encoded !== 'string') { + throw new TypeError('encoded argument must be of type String'); + } + var decoded = base32.decode(encoded); + var versionByte = decoded[0]; + var payload = decoded.slice(0, -2); + var data = payload.slice(1); + var checksum = decoded.slice(-2); + if (encoded !== base32.encode(decoded)) { + throw new Error('invalid encoded string'); + } + var expectedVersion = versionBytes[versionByteName]; + if (expectedVersion === undefined) { + throw new Error("".concat(versionByteName, " is not a valid version byte name. ") + "Expected one of ".concat(Object.keys(versionBytes).join(', '))); + } + if (versionByte !== expectedVersion) { + throw new Error("invalid version byte. expected ".concat(expectedVersion, ", got ").concat(versionByte)); + } + var expectedChecksum = calculateChecksum(payload); + if (!verifyChecksum(expectedChecksum, checksum)) { + throw new Error("invalid checksum"); + } + return strkey_Buffer.from(data); +} +function encodeCheck(versionByteName, data) { + if (data === null || data === undefined) { + throw new Error('cannot encode null data'); + } + var versionByte = versionBytes[versionByteName]; + if (versionByte === undefined) { + throw new Error("".concat(versionByteName, " is not a valid version byte name. ") + "Expected one of ".concat(Object.keys(versionBytes).join(', '))); + } + data = strkey_Buffer.from(data); + var versionBuffer = strkey_Buffer.from([versionByte]); + var payload = strkey_Buffer.concat([versionBuffer, data]); + var checksum = strkey_Buffer.from(calculateChecksum(payload)); + var unencoded = strkey_Buffer.concat([payload, checksum]); + return base32.encode(unencoded); +} + +// Computes the CRC16-XModem checksum of `payload` in little-endian order +function calculateChecksum(payload) { + var crcTable = [0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0]; + var crc16 = 0x0; + for (var i = 0; i < payload.length; i += 1) { + var _byte = payload[i]; + var lookupIndex = crc16 >> 8 ^ _byte; + crc16 = crc16 << 8 ^ crcTable[lookupIndex]; + crc16 &= 0xffff; + } + var checksum = new Uint8Array(2); + checksum[0] = crc16 & 0xff; + checksum[1] = crc16 >> 8 & 0xff; + return checksum; +} +;// ./src/keypair.js +/* provided dependency */ var keypair_Buffer = __webpack_require__(3626)["A"]; +function keypair_typeof(o) { "@babel/helpers - typeof"; return keypair_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, keypair_typeof(o); } +function keypair_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function keypair_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, keypair_toPropertyKey(o.key), o); } } +function keypair_createClass(e, r, t) { return r && keypair_defineProperties(e.prototype, r), t && keypair_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function keypair_toPropertyKey(t) { var i = keypair_toPrimitive(t, "string"); return "symbol" == keypair_typeof(i) ? i : i + ""; } +function keypair_toPrimitive(t, r) { if ("object" != keypair_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != keypair_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/* eslint no-bitwise: ["error", {"allow": ["^"]}] */ + + + + + + + +/** + * `Keypair` represents public (and secret) keys of the account. + * + * Currently `Keypair` only supports ed25519 but in a future this class can be abstraction layer for other + * public-key signature systems. + * + * Use more convenient methods to create `Keypair` object: + * * `{@link Keypair.fromPublicKey}` + * * `{@link Keypair.fromSecret}` + * * `{@link Keypair.random}` + * + * @constructor + * @param {object} keys At least one of keys must be provided. + * @param {string} keys.type Public-key signature system name. (currently only `ed25519` keys are supported) + * @param {Buffer} [keys.publicKey] Raw public key + * @param {Buffer} [keys.secretKey] Raw secret key (32-byte secret seed in ed25519`) + */ +var Keypair = /*#__PURE__*/function () { + function Keypair(keys) { + keypair_classCallCheck(this, Keypair); + if (keys.type !== 'ed25519') { + throw new Error('Invalid keys type'); + } + this.type = keys.type; + if (keys.secretKey) { + keys.secretKey = keypair_Buffer.from(keys.secretKey); + if (keys.secretKey.length !== 32) { + throw new Error('secretKey length is invalid'); + } + this._secretSeed = keys.secretKey; + this._publicKey = generate(keys.secretKey); + this._secretKey = keypair_Buffer.concat([keys.secretKey, this._publicKey]); + if (keys.publicKey && !this._publicKey.equals(keypair_Buffer.from(keys.publicKey))) { + throw new Error('secretKey does not match publicKey'); + } + } else { + this._publicKey = keypair_Buffer.from(keys.publicKey); + if (this._publicKey.length !== 32) { + throw new Error('publicKey length is invalid'); + } + } + } + + /** + * Creates a new `Keypair` instance from secret. This can either be secret key or secret seed depending + * on underlying public-key signature system. Currently `Keypair` only supports ed25519. + * @param {string} secret secret key (ex. `SDAKFNYEIAORZKKCYRILFQKLLOCNPL5SWJ3YY5NM3ZH6GJSZGXHZEPQS`) + * @returns {Keypair} + */ + return keypair_createClass(Keypair, [{ + key: "xdrAccountId", + value: function xdrAccountId() { + return new src_xdr.AccountId.publicKeyTypeEd25519(this._publicKey); + } + }, { + key: "xdrPublicKey", + value: function xdrPublicKey() { + return new src_xdr.PublicKey.publicKeyTypeEd25519(this._publicKey); + } + + /** + * Creates a {@link xdr.MuxedAccount} object from the public key. + * + * You will get a different type of muxed account depending on whether or not + * you pass an ID. + * + * @param {string} [id] - stringified integer indicating the underlying muxed + * ID of the new account object + * + * @return {xdr.MuxedAccount} + */ + }, { + key: "xdrMuxedAccount", + value: function xdrMuxedAccount(id) { + if (typeof id !== 'undefined') { + if (typeof id !== 'string') { + throw new TypeError("expected string for ID, got ".concat(keypair_typeof(id))); + } + return src_xdr.MuxedAccount.keyTypeMuxedEd25519(new src_xdr.MuxedAccountMed25519({ + id: src_xdr.Uint64.fromString(id), + ed25519: this._publicKey + })); + } + return new src_xdr.MuxedAccount.keyTypeEd25519(this._publicKey); + } + + /** + * Returns raw public key + * @returns {Buffer} + */ + }, { + key: "rawPublicKey", + value: function rawPublicKey() { + return this._publicKey; + } + }, { + key: "signatureHint", + value: function signatureHint() { + var a = this.xdrAccountId().toXDR(); + return a.slice(a.length - 4); + } + + /** + * Returns public key associated with this `Keypair` object. + * @returns {string} + */ + }, { + key: "publicKey", + value: function publicKey() { + return StrKey.encodeEd25519PublicKey(this._publicKey); + } + + /** + * Returns secret key associated with this `Keypair` object + * @returns {string} + */ + }, { + key: "secret", + value: function secret() { + if (!this._secretSeed) { + throw new Error('no secret key available'); + } + if (this.type === 'ed25519') { + return StrKey.encodeEd25519SecretSeed(this._secretSeed); + } + throw new Error('Invalid Keypair type'); + } + + /** + * Returns raw secret key. + * @returns {Buffer} + */ + }, { + key: "rawSecretKey", + value: function rawSecretKey() { + return this._secretSeed; + } + + /** + * Returns `true` if this `Keypair` object contains secret key and can sign. + * @returns {boolean} + */ + }, { + key: "canSign", + value: function canSign() { + return !!this._secretKey; + } + + /** + * Signs data. + * @param {Buffer} data Data to sign + * @returns {Buffer} + */ + }, { + key: "sign", + value: function sign(data) { + if (!this.canSign()) { + throw new Error('cannot sign: no secret key available'); + } + return signing_sign(data, this._secretKey); + } + + /** + * Verifies if `signature` for `data` is valid. + * @param {Buffer} data Signed data + * @param {Buffer} signature Signature + * @returns {boolean} + */ + }, { + key: "verify", + value: function verify(data, signature) { + return signing_verify(data, signature, this._publicKey); + } + + /** + * Returns the decorated signature (hint+sig) for arbitrary data. + * + * @param {Buffer} data arbitrary data to sign + * @return {xdr.DecoratedSignature} the raw signature structure which can be + * added directly to a transaction envelope + * + * @see TransactionBase.addDecoratedSignature + */ + }, { + key: "signDecorated", + value: function signDecorated(data) { + var signature = this.sign(data); + var hint = this.signatureHint(); + return new src_xdr.DecoratedSignature({ + hint: hint, + signature: signature + }); + } + + /** + * Returns the raw decorated signature (hint+sig) for a signed payload signer. + * + * The hint is defined as the last 4 bytes of the signer key XORed with last + * 4 bytes of the payload (zero-left-padded if necessary). + * + * @param {Buffer} data data to both sign and treat as the payload + * @return {xdr.DecoratedSignature} + * + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0040.md#signature-hint + * @see TransactionBase.addDecoratedSignature + */ + }, { + key: "signPayloadDecorated", + value: function signPayloadDecorated(data) { + var signature = this.sign(data); + var keyHint = this.signatureHint(); + var hint = keypair_Buffer.from(data.slice(-4)); + if (hint.length < 4) { + // append zeroes as needed + hint = keypair_Buffer.concat([hint, keypair_Buffer.alloc(4 - data.length, 0)]); + } + return new src_xdr.DecoratedSignature({ + hint: hint.map(function (_byte, i) { + return _byte ^ keyHint[i]; + }), + signature: signature + }); + } + }], [{ + key: "fromSecret", + value: function fromSecret(secret) { + var rawSecret = StrKey.decodeEd25519SecretSeed(secret); + return this.fromRawEd25519Seed(rawSecret); + } + + /** + * Creates a new `Keypair` object from ed25519 secret key seed raw bytes. + * + * @param {Buffer} rawSeed Raw 32-byte ed25519 secret key seed + * @returns {Keypair} + */ + }, { + key: "fromRawEd25519Seed", + value: function fromRawEd25519Seed(rawSeed) { + return new this({ + type: 'ed25519', + secretKey: rawSeed + }); + } + + /** + * Returns `Keypair` object representing network master key. + * @param {string} networkPassphrase passphrase of the target stellar network (e.g. "Public Global Stellar Network ; September 2015"). + * @returns {Keypair} + */ + }, { + key: "master", + value: function master(networkPassphrase) { + if (!networkPassphrase) { + throw new Error('No network selected. Please pass a network argument, e.g. `Keypair.master(Networks.PUBLIC)`.'); + } + return this.fromRawEd25519Seed(hashing_hash(networkPassphrase)); + } + + /** + * Creates a new `Keypair` object from public key. + * @param {string} publicKey public key (ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`) + * @returns {Keypair} + */ + }, { + key: "fromPublicKey", + value: function fromPublicKey(publicKey) { + publicKey = StrKey.decodeEd25519PublicKey(publicKey); + if (publicKey.length !== 32) { + throw new Error('Invalid Stellar public key'); + } + return new this({ + type: 'ed25519', + publicKey: publicKey + }); + } + + /** + * Create a random `Keypair` object. + * @returns {Keypair} + */ + }, { + key: "random", + value: function random() { + var secret = nacl_fast_default().randomBytes(32); + return this.fromRawEd25519Seed(secret); + } + }]); +}(); +;// ./src/asset.js +/* provided dependency */ var asset_Buffer = __webpack_require__(3626)["A"]; +function asset_typeof(o) { "@babel/helpers - typeof"; return asset_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, asset_typeof(o); } +function asset_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function asset_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, asset_toPropertyKey(o.key), o); } } +function asset_createClass(e, r, t) { return r && asset_defineProperties(e.prototype, r), t && asset_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function asset_toPropertyKey(t) { var i = asset_toPrimitive(t, "string"); return "symbol" == asset_typeof(i) ? i : i + ""; } +function asset_toPrimitive(t, r) { if ("object" != asset_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != asset_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + +/** + * Asset class represents an asset, either the native asset (`XLM`) + * or an asset code / issuer account ID pair. + * + * An asset code describes an asset code and issuer pair. In the case of the native + * asset XLM, the issuer will be null. + * + * @constructor + * @param {string} code - The asset code. + * @param {string} issuer - The account ID of the issuer. + */ +var Asset = /*#__PURE__*/function () { + function Asset(code, issuer) { + asset_classCallCheck(this, Asset); + if (!/^[a-zA-Z0-9]{1,12}$/.test(code)) { + throw new Error('Asset code is invalid (maximum alphanumeric, 12 characters at max)'); + } + if (String(code).toLowerCase() !== 'xlm' && !issuer) { + throw new Error('Issuer cannot be null'); + } + if (issuer && !StrKey.isValidEd25519PublicKey(issuer)) { + throw new Error('Issuer is invalid'); + } + if (String(code).toLowerCase() === 'xlm') { + // transform all xLM, Xlm, etc. variants -> XLM + this.code = 'XLM'; + } else { + this.code = code; + } + this.issuer = issuer; + } + + /** + * Returns an asset object for the native asset. + * @Return {Asset} + */ + return asset_createClass(Asset, [{ + key: "toXDRObject", + value: + /** + * Returns the xdr.Asset object for this asset. + * @returns {xdr.Asset} XDR asset object + */ + function toXDRObject() { + return this._toXDRObject(src_xdr.Asset); + } + + /** + * Returns the xdr.ChangeTrustAsset object for this asset. + * @returns {xdr.ChangeTrustAsset} XDR asset object + */ + }, { + key: "toChangeTrustXDRObject", + value: function toChangeTrustXDRObject() { + return this._toXDRObject(src_xdr.ChangeTrustAsset); + } + + /** + * Returns the xdr.TrustLineAsset object for this asset. + * @returns {xdr.TrustLineAsset} XDR asset object + */ + }, { + key: "toTrustLineXDRObject", + value: function toTrustLineXDRObject() { + return this._toXDRObject(src_xdr.TrustLineAsset); + } + + /** + * Returns the would-be contract ID (`C...` format) for this asset on a given + * network. + * + * @param {string} networkPassphrase indicates which network the contract + * ID should refer to, since every network will have a unique ID for the + * same contract (see {@link Networks} for options) + * + * @returns {string} the strkey-encoded (`C...`) contract ID for this asset + * + * @warning This makes no guarantee that this contract actually *exists*. + */ + }, { + key: "contractId", + value: function contractId(networkPassphrase) { + var networkId = hashing_hash(asset_Buffer.from(networkPassphrase)); + var preimage = src_xdr.HashIdPreimage.envelopeTypeContractId(new src_xdr.HashIdPreimageContractId({ + networkId: networkId, + contractIdPreimage: src_xdr.ContractIdPreimage.contractIdPreimageFromAsset(this.toXDRObject()) + })); + return StrKey.encodeContract(hashing_hash(preimage.toXDR())); + } + + /** + * Returns the xdr object for this asset. + * @param {xdr.Asset | xdr.ChangeTrustAsset} xdrAsset - The asset xdr object. + * @returns {xdr.Asset | xdr.ChangeTrustAsset | xdr.TrustLineAsset} XDR Asset object + */ + }, { + key: "_toXDRObject", + value: function _toXDRObject() { + var xdrAsset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : src_xdr.Asset; + if (this.isNative()) { + return xdrAsset.assetTypeNative(); + } + var xdrType; + var xdrTypeString; + if (this.code.length <= 4) { + xdrType = src_xdr.AlphaNum4; + xdrTypeString = 'assetTypeCreditAlphanum4'; + } else { + xdrType = src_xdr.AlphaNum12; + xdrTypeString = 'assetTypeCreditAlphanum12'; + } + + // pad code with null bytes if necessary + var padLength = this.code.length <= 4 ? 4 : 12; + var paddedCode = this.code.padEnd(padLength, '\0'); + + // eslint-disable-next-line new-cap + var assetType = new xdrType({ + assetCode: paddedCode, + issuer: Keypair.fromPublicKey(this.issuer).xdrAccountId() + }); + return new xdrAsset(xdrTypeString, assetType); + } + + /** + * @returns {string} Asset code + */ + }, { + key: "getCode", + value: function getCode() { + if (this.code === undefined) { + return undefined; + } + return String(this.code); + } + + /** + * @returns {string} Asset issuer + */ + }, { + key: "getIssuer", + value: function getIssuer() { + if (this.issuer === undefined) { + return undefined; + } + return String(this.issuer); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {string} Asset type. Can be one of following types: + * + * - `native`, + * - `credit_alphanum4`, + * - `credit_alphanum12`, or + * - `unknown` as the error case (which should never occur) + */ + }, { + key: "getAssetType", + value: function getAssetType() { + switch (this.getRawAssetType().value) { + case src_xdr.AssetType.assetTypeNative().value: + return 'native'; + case src_xdr.AssetType.assetTypeCreditAlphanum4().value: + return 'credit_alphanum4'; + case src_xdr.AssetType.assetTypeCreditAlphanum12().value: + return 'credit_alphanum12'; + default: + return 'unknown'; + } + } + + /** + * @returns {xdr.AssetType} the raw XDR representation of the asset type + */ + }, { + key: "getRawAssetType", + value: function getRawAssetType() { + if (this.isNative()) { + return src_xdr.AssetType.assetTypeNative(); + } + if (this.code.length <= 4) { + return src_xdr.AssetType.assetTypeCreditAlphanum4(); + } + return src_xdr.AssetType.assetTypeCreditAlphanum12(); + } + + /** + * @returns {boolean} true if this asset object is the native asset. + */ + }, { + key: "isNative", + value: function isNative() { + return !this.issuer; + } + + /** + * @param {Asset} asset Asset to compare + * @returns {boolean} true if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(asset) { + return this.code === asset.getCode() && this.issuer === asset.getIssuer(); + } + }, { + key: "toString", + value: function toString() { + if (this.isNative()) { + return 'native'; + } + return "".concat(this.getCode(), ":").concat(this.getIssuer()); + } + + /** + * Compares two assets according to the criteria: + * + * 1. First compare the type (native < alphanum4 < alphanum12). + * 2. If the types are equal, compare the assets codes. + * 3. If the asset codes are equal, compare the issuers. + * + * @param {Asset} assetA - the first asset + * @param {Asset} assetB - the second asset + * @returns {number} `-1` if assetA < assetB, `0` if assetA == assetB, `1` if assetA > assetB. + * + * @static + * @memberof Asset + */ + }], [{ + key: "native", + value: function _native() { + return new Asset('XLM'); + } + + /** + * Returns an asset object from its XDR object representation. + * @param {xdr.Asset} assetXdr - The asset xdr object. + * @returns {Asset} + */ + }, { + key: "fromOperation", + value: function fromOperation(assetXdr) { + var anum; + var code; + var issuer; + switch (assetXdr["switch"]()) { + case src_xdr.AssetType.assetTypeNative(): + return this["native"](); + case src_xdr.AssetType.assetTypeCreditAlphanum4(): + anum = assetXdr.alphaNum4(); + /* falls through */ + case src_xdr.AssetType.assetTypeCreditAlphanum12(): + anum = anum || assetXdr.alphaNum12(); + issuer = StrKey.encodeEd25519PublicKey(anum.issuer().ed25519()); + code = trimEnd(anum.assetCode(), '\0'); + return new this(code, issuer); + default: + throw new Error("Invalid asset type: ".concat(assetXdr["switch"]().name)); + } + } + }, { + key: "compare", + value: function compare(assetA, assetB) { + if (!assetA || !(assetA instanceof Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof Asset)) { + throw new Error('assetB is invalid'); + } + if (assetA.equals(assetB)) { + return 0; + } + + // Compare asset types. + var xdrAtype = assetA.getRawAssetType().value; + var xdrBtype = assetB.getRawAssetType().value; + if (xdrAtype !== xdrBtype) { + return xdrAtype < xdrBtype ? -1 : 1; + } + + // Compare asset codes. + var result = asciiCompare(assetA.getCode(), assetB.getCode()); + if (result !== 0) { + return result; + } + + // Compare asset issuers. + return asciiCompare(assetA.getIssuer(), assetB.getIssuer()); + } + }]); +}(); + +/** + * Compares two ASCII strings in lexographic order with uppercase precedence. + * + * @param {string} a - the first string to compare + * @param {string} b - the second + * @returns {number} like all `compare()`s: + * -1 if `a < b`, 0 if `a == b`, and 1 if `a > b` + * + * @warning No type-checks are done on the parameters + */ +function asciiCompare(a, b) { + return asset_Buffer.compare(asset_Buffer.from(a, 'ascii'), asset_Buffer.from(b, 'ascii')); +} +;// ./src/get_liquidity_pool_id.js +/* provided dependency */ var get_liquidity_pool_id_Buffer = __webpack_require__(3626)["A"]; + + + + +// LiquidityPoolFeeV18 is the default liquidity pool fee in protocol v18. It defaults to 30 base points (0.3%). +var LiquidityPoolFeeV18 = 30; + +/** + * getLiquidityPoolId computes the Pool ID for the given assets, fee and pool type. + * + * @see [stellar-core getPoolID](https://github.com/stellar/stellar-core/blob/9f3a48c6a8f1aa77b6043a055d0638661f718080/src/ledger/test/LedgerTxnTests.cpp#L3746-L3751) + * + * @export + * @param {string} liquidityPoolType – A string representing the liquidity pool type. + * @param {object} liquidityPoolParameters – The liquidity pool parameters. + * @param {Asset} liquidityPoolParameters.assetA – The first asset in the Pool, it must respect the rule assetA < assetB. + * @param {Asset} liquidityPoolParameters.assetB – The second asset in the Pool, it must respect the rule assetA < assetB. + * @param {number} liquidityPoolParameters.fee – The liquidity pool fee. For now the only fee supported is `30`. + * + * @return {Buffer} the raw Pool ID buffer, which can be stringfied with `toString('hex')` + */ +function getLiquidityPoolId(liquidityPoolType) { + var liquidityPoolParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (liquidityPoolType !== 'constant_product') { + throw new Error('liquidityPoolType is invalid'); + } + var assetA = liquidityPoolParameters.assetA, + assetB = liquidityPoolParameters.assetB, + fee = liquidityPoolParameters.fee; + if (!assetA || !(assetA instanceof Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof Asset)) { + throw new Error('assetB is invalid'); + } + if (!fee || fee !== LiquidityPoolFeeV18) { + throw new Error('fee is invalid'); + } + if (Asset.compare(assetA, assetB) !== -1) { + throw new Error('Assets are not in lexicographic order'); + } + var lpTypeData = src_xdr.LiquidityPoolType.liquidityPoolConstantProduct().toXDR(); + var lpParamsData = new src_xdr.LiquidityPoolConstantProductParameters({ + assetA: assetA.toXDRObject(), + assetB: assetB.toXDRObject(), + fee: fee + }).toXDR(); + var payload = get_liquidity_pool_id_Buffer.concat([lpTypeData, lpParamsData]); + return hashing_hash(payload); +} +;// ./src/transaction_base.js +/* provided dependency */ var transaction_base_Buffer = __webpack_require__(3626)["A"]; +function transaction_base_typeof(o) { "@babel/helpers - typeof"; return transaction_base_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, transaction_base_typeof(o); } +function transaction_base_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function transaction_base_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, transaction_base_toPropertyKey(o.key), o); } } +function transaction_base_createClass(e, r, t) { return r && transaction_base_defineProperties(e.prototype, r), t && transaction_base_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function transaction_base_toPropertyKey(t) { var i = transaction_base_toPrimitive(t, "string"); return "symbol" == transaction_base_typeof(i) ? i : i + ""; } +function transaction_base_toPrimitive(t, r) { if ("object" != transaction_base_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != transaction_base_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + +/** + * @ignore + */ +var TransactionBase = /*#__PURE__*/function () { + function TransactionBase(tx, signatures, fee, networkPassphrase) { + transaction_base_classCallCheck(this, TransactionBase); + if (typeof networkPassphrase !== 'string') { + throw new Error("Invalid passphrase provided to Transaction: expected a string but got a ".concat(transaction_base_typeof(networkPassphrase))); + } + this._networkPassphrase = networkPassphrase; + this._tx = tx; + this._signatures = signatures; + this._fee = fee; + } + + /** + * @type {Array.} + * @readonly + */ + return transaction_base_createClass(TransactionBase, [{ + key: "signatures", + get: function get() { + return this._signatures; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + }, { + key: "tx", + get: function get() { + return this._tx; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "fee", + get: function get() { + return this._fee; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "networkPassphrase", + get: function get() { + return this._networkPassphrase; + }, + set: function set(networkPassphrase) { + this._networkPassphrase = networkPassphrase; + } + + /** + * Signs the transaction with the given {@link Keypair}. + * @param {...Keypair} keypairs Keypairs of signers + * @returns {void} + */ + }, { + key: "sign", + value: function sign() { + var _this = this; + var txHash = this.hash(); + for (var _len = arguments.length, keypairs = new Array(_len), _key = 0; _key < _len; _key++) { + keypairs[_key] = arguments[_key]; + } + keypairs.forEach(function (kp) { + var sig = kp.signDecorated(txHash); + _this.signatures.push(sig); + }); + } + + /** + * Signs a transaction with the given {@link Keypair}. Useful if someone sends + * you a transaction XDR for you to sign and return (see + * [addSignature](#addSignature) for more information). + * + * When you get a transaction XDR to sign.... + * - Instantiate a `Transaction` object with the XDR + * - Use {@link Keypair} to generate a keypair object for your Stellar seed. + * - Run `getKeypairSignature` with that keypair + * - Send back the signature along with your publicKey (not your secret seed!) + * + * Example: + * ```javascript + * // `transactionXDR` is a string from the person generating the transaction + * const transaction = new Transaction(transactionXDR, networkPassphrase); + * const keypair = Keypair.fromSecret(myStellarSeed); + * return transaction.getKeypairSignature(keypair); + * ``` + * + * @param {Keypair} keypair Keypair of signer + * @returns {string} Signature string + */ + }, { + key: "getKeypairSignature", + value: function getKeypairSignature(keypair) { + return keypair.sign(this.hash()).toString('base64'); + } + + /** + * Add a signature to the transaction. Useful when a party wants to pre-sign + * a transaction but doesn't want to give access to their secret keys. + * This will also verify whether the signature is valid. + * + * Here's how you would use this feature to solicit multiple signatures. + * - Use `TransactionBuilder` to build a new transaction. + * - Make sure to set a long enough timeout on that transaction to give your + * signers enough time to sign! + * - Once you build the transaction, use `transaction.toXDR()` to get the + * base64-encoded XDR string. + * - _Warning!_ Once you've built this transaction, don't submit any other + * transactions onto your account! Doing so will invalidate this pre-compiled + * transaction! + * - Send this XDR string to your other parties. They can use the instructions + * for [getKeypairSignature](#getKeypairSignature) to sign the transaction. + * - They should send you back their `publicKey` and the `signature` string + * from [getKeypairSignature](#getKeypairSignature), both of which you pass to + * this function. + * + * @param {string} publicKey The public key of the signer + * @param {string} signature The base64 value of the signature XDR + * @returns {void} + */ + }, { + key: "addSignature", + value: function addSignature() { + var publicKey = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var signature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + if (!signature || typeof signature !== 'string') { + throw new Error('Invalid signature'); + } + if (!publicKey || typeof publicKey !== 'string') { + throw new Error('Invalid publicKey'); + } + var keypair; + var hint; + var signatureBuffer = transaction_base_Buffer.from(signature, 'base64'); + try { + keypair = Keypair.fromPublicKey(publicKey); + hint = keypair.signatureHint(); + } catch (e) { + throw new Error('Invalid publicKey'); + } + if (!keypair.verify(this.hash(), signatureBuffer)) { + throw new Error('Invalid signature'); + } + this.signatures.push(new src_xdr.DecoratedSignature({ + hint: hint, + signature: signatureBuffer + })); + } + + /** + * Add a decorated signature directly to the transaction envelope. + * + * @param {xdr.DecoratedSignature} signature raw signature to add + * @returns {void} + * + * @see Keypair.signDecorated + * @see Keypair.signPayloadDecorated + */ + }, { + key: "addDecoratedSignature", + value: function addDecoratedSignature(signature) { + this.signatures.push(signature); + } + + /** + * Add `hashX` signer preimage as signature. + * @param {Buffer|String} preimage Preimage of hash used as signer + * @returns {void} + */ + }, { + key: "signHashX", + value: function signHashX(preimage) { + if (typeof preimage === 'string') { + preimage = transaction_base_Buffer.from(preimage, 'hex'); + } + if (preimage.length > 64) { + throw new Error('preimage cannnot be longer than 64 bytes'); + } + var signature = preimage; + var hashX = hashing_hash(preimage); + var hint = hashX.slice(hashX.length - 4); + this.signatures.push(new src_xdr.DecoratedSignature({ + hint: hint, + signature: signature + })); + } + + /** + * Returns a hash for this transaction, suitable for signing. + * @returns {Buffer} + */ + }, { + key: "hash", + value: function hash() { + return hashing_hash(this.signatureBase()); + } + }, { + key: "signatureBase", + value: function signatureBase() { + throw new Error('Implement in subclass'); + } + }, { + key: "toEnvelope", + value: function toEnvelope() { + throw new Error('Implement in subclass'); + } + + /** + * Get the transaction envelope as a base64-encoded string + * @returns {string} XDR string + */ + }, { + key: "toXDR", + value: function toXDR() { + return this.toEnvelope().toXDR().toString('base64'); + } + }]); +}(); +;// ./node_modules/bignumber.js/bignumber.mjs +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + +var + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + +/* + * Create and return a BigNumber constructor. + */ +function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + P[Symbol.toStringTag] = 'BigNumber'; + + // Node.js v10.12.0+ + P[Symbol.for('nodejs.util.inspect.custom')] = P.valueOf; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; +} + + +// PRIVATE HELPER FUNCTIONS + +// These functions don't need access to variables, +// e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + +function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; +} + + +// Return a coefficient array as a string of base 10 digits. +function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); +} + + +// Compare the value of BigNumbers x and y. +function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; +} + + +/* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ +function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } +} + + +// Assumes finite n. +function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; +} + + +function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; +} + + +function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; +} + + +// EXPORT + + +var BigNumber = clone(); + +/* harmony default export */ const bignumber = (BigNumber); + +;// ./src/util/bignumber.js + +var bignumber_BigNumber = bignumber.clone(); +bignumber_BigNumber.DEBUG = true; // gives us exceptions on bad constructor values + +/* harmony default export */ const util_bignumber = (bignumber_BigNumber); +;// ./src/util/continued_fraction.js +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } + + +// eslint-disable-next-line no-bitwise +var MAX_INT = (1 << 31 >>> 0) - 1; + +/** + * Calculates and returns the best rational approximation of the given real number. + * @private + * @param {string|number|BigNumber} rawNumber Real number + * @throws Error Throws `Error` when the best rational approximation cannot be found. + * @returns {array} first element is n (numerator), second element is d (denominator) + */ +function best_r(rawNumber) { + var number = new util_bignumber(rawNumber); + var a; + var f; + var fractions = [[new util_bignumber(0), new util_bignumber(1)], [new util_bignumber(1), new util_bignumber(0)]]; + var i = 2; + + // eslint-disable-next-line no-constant-condition + while (true) { + if (number.gt(MAX_INT)) { + break; + } + a = number.integerValue(util_bignumber.ROUND_FLOOR); + f = number.minus(a); + var h = a.times(fractions[i - 1][0]).plus(fractions[i - 2][0]); + var k = a.times(fractions[i - 1][1]).plus(fractions[i - 2][1]); + if (h.gt(MAX_INT) || k.gt(MAX_INT)) { + break; + } + fractions.push([h, k]); + if (f.eq(0)) { + break; + } + number = new util_bignumber(1).div(f); + i += 1; + } + var _fractions = _slicedToArray(fractions[fractions.length - 1], 2), + n = _fractions[0], + d = _fractions[1]; + if (n.isZero() || d.isZero()) { + throw new Error("Couldn't find approximation"); + } + return [n.toNumber(), d.toNumber()]; +} +;// ./src/liquidity_pool_asset.js +function liquidity_pool_asset_typeof(o) { "@babel/helpers - typeof"; return liquidity_pool_asset_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, liquidity_pool_asset_typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = liquidity_pool_asset_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function liquidity_pool_asset_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function liquidity_pool_asset_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, liquidity_pool_asset_toPropertyKey(o.key), o); } } +function liquidity_pool_asset_createClass(e, r, t) { return r && liquidity_pool_asset_defineProperties(e.prototype, r), t && liquidity_pool_asset_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function liquidity_pool_asset_toPropertyKey(t) { var i = liquidity_pool_asset_toPrimitive(t, "string"); return "symbol" == liquidity_pool_asset_typeof(i) ? i : i + ""; } +function liquidity_pool_asset_toPrimitive(t, r) { if ("object" != liquidity_pool_asset_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != liquidity_pool_asset_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + +/** + * LiquidityPoolAsset class represents a liquidity pool trustline change. + * + * @constructor + * @param {Asset} assetA – The first asset in the Pool, it must respect the rule assetA < assetB. See {@link Asset.compare} for more details on how assets are sorted. + * @param {Asset} assetB – The second asset in the Pool, it must respect the rule assetA < assetB. See {@link Asset.compare} for more details on how assets are sorted. + * @param {number} fee – The liquidity pool fee. For now the only fee supported is `30`. + */ +var LiquidityPoolAsset = /*#__PURE__*/function () { + function LiquidityPoolAsset(assetA, assetB, fee) { + liquidity_pool_asset_classCallCheck(this, LiquidityPoolAsset); + if (!assetA || !(assetA instanceof Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof Asset)) { + throw new Error('assetB is invalid'); + } + if (Asset.compare(assetA, assetB) !== -1) { + throw new Error('Assets are not in lexicographic order'); + } + if (!fee || fee !== LiquidityPoolFeeV18) { + throw new Error('fee is invalid'); + } + this.assetA = assetA; + this.assetB = assetB; + this.fee = fee; + } + + /** + * Returns a liquidity pool asset object from its XDR ChangeTrustAsset object + * representation. + * @param {xdr.ChangeTrustAsset} ctAssetXdr - The asset XDR object. + * @returns {LiquidityPoolAsset} + */ + return liquidity_pool_asset_createClass(LiquidityPoolAsset, [{ + key: "toXDRObject", + value: + /** + * Returns the `xdr.ChangeTrustAsset` object for this liquidity pool asset. + * + * Note: To convert from an {@link Asset `Asset`} to `xdr.ChangeTrustAsset` + * please refer to the + * {@link Asset.toChangeTrustXDRObject `Asset.toChangeTrustXDRObject`} method. + * + * @returns {xdr.ChangeTrustAsset} XDR ChangeTrustAsset object. + */ + function toXDRObject() { + var lpConstantProductParamsXdr = new src_xdr.LiquidityPoolConstantProductParameters({ + assetA: this.assetA.toXDRObject(), + assetB: this.assetB.toXDRObject(), + fee: this.fee + }); + var lpParamsXdr = new src_xdr.LiquidityPoolParameters('liquidityPoolConstantProduct', lpConstantProductParamsXdr); + return new src_xdr.ChangeTrustAsset('assetTypePoolShare', lpParamsXdr); + } + + /** + * @returns {LiquidityPoolParameters} Liquidity pool parameters. + */ + }, { + key: "getLiquidityPoolParameters", + value: function getLiquidityPoolParameters() { + return _objectSpread(_objectSpread({}, this), {}, { + assetA: this.assetA, + assetB: this.assetB, + fee: this.fee + }); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {AssetType.liquidityPoolShares} asset type. Can only be `liquidity_pool_shares`. + */ + }, { + key: "getAssetType", + value: function getAssetType() { + return 'liquidity_pool_shares'; + } + + /** + * @param {LiquidityPoolAsset} other the LiquidityPoolAsset to compare + * @returns {boolean} `true` if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(other) { + return this.assetA.equals(other.assetA) && this.assetB.equals(other.assetB) && this.fee === other.fee; + } + }, { + key: "toString", + value: function toString() { + var poolId = getLiquidityPoolId('constant_product', this.getLiquidityPoolParameters()).toString('hex'); + return "liquidity_pool:".concat(poolId); + } + }], [{ + key: "fromOperation", + value: function fromOperation(ctAssetXdr) { + var assetType = ctAssetXdr["switch"](); + if (assetType === src_xdr.AssetType.assetTypePoolShare()) { + var liquidityPoolParameters = ctAssetXdr.liquidityPool().constantProduct(); + return new this(Asset.fromOperation(liquidityPoolParameters.assetA()), Asset.fromOperation(liquidityPoolParameters.assetB()), liquidityPoolParameters.fee()); + } + throw new Error("Invalid asset type: ".concat(assetType.name)); + } + }]); +}(); +;// ./src/claimant.js +function claimant_typeof(o) { "@babel/helpers - typeof"; return claimant_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, claimant_typeof(o); } +function claimant_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function claimant_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, claimant_toPropertyKey(o.key), o); } } +function claimant_createClass(e, r, t) { return r && claimant_defineProperties(e.prototype, r), t && claimant_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function claimant_toPropertyKey(t) { var i = claimant_toPrimitive(t, "string"); return "symbol" == claimant_typeof(i) ? i : i + ""; } +function claimant_toPrimitive(t, r) { if ("object" != claimant_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != claimant_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + +/** + * Claimant class represents an xdr.Claimant + * + * The claim predicate is optional, it defaults to unconditional if none is specified. + * + * @constructor + * @param {string} destination - The destination account ID. + * @param {xdr.ClaimPredicate} [predicate] - The claim predicate. + */ +var Claimant = /*#__PURE__*/function () { + function Claimant(destination, predicate) { + claimant_classCallCheck(this, Claimant); + if (destination && !StrKey.isValidEd25519PublicKey(destination)) { + throw new Error('Destination is invalid'); + } + this._destination = destination; + if (!predicate) { + this._predicate = src_xdr.ClaimPredicate.claimPredicateUnconditional(); + } else if (predicate instanceof src_xdr.ClaimPredicate) { + this._predicate = predicate; + } else { + throw new Error('Predicate should be an xdr.ClaimPredicate'); + } + } + + /** + * Returns an unconditional claim predicate + * @Return {xdr.ClaimPredicate} + */ + return claimant_createClass(Claimant, [{ + key: "toXDRObject", + value: + /** + * Returns the xdr object for this claimant. + * @returns {xdr.Claimant} XDR Claimant object + */ + function toXDRObject() { + var claimant = new src_xdr.ClaimantV0({ + destination: Keypair.fromPublicKey(this._destination).xdrAccountId(), + predicate: this._predicate + }); + return src_xdr.Claimant.claimantTypeV0(claimant); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "destination", + get: function get() { + return this._destination; + }, + set: function set(value) { + throw new Error('Claimant is immutable'); + } + + /** + * @type {xdr.ClaimPredicate} + * @readonly + */ + }, { + key: "predicate", + get: function get() { + return this._predicate; + }, + set: function set(value) { + throw new Error('Claimant is immutable'); + } + }], [{ + key: "predicateUnconditional", + value: function predicateUnconditional() { + return src_xdr.ClaimPredicate.claimPredicateUnconditional(); + } + + /** + * Returns an `and` claim predicate + * @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate + * @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateAnd", + value: function predicateAnd(left, right) { + if (!(left instanceof src_xdr.ClaimPredicate)) { + throw new Error('left Predicate should be an xdr.ClaimPredicate'); + } + if (!(right instanceof src_xdr.ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return src_xdr.ClaimPredicate.claimPredicateAnd([left, right]); + } + + /** + * Returns an `or` claim predicate + * @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate + * @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateOr", + value: function predicateOr(left, right) { + if (!(left instanceof src_xdr.ClaimPredicate)) { + throw new Error('left Predicate should be an xdr.ClaimPredicate'); + } + if (!(right instanceof src_xdr.ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return src_xdr.ClaimPredicate.claimPredicateOr([left, right]); + } + + /** + * Returns a `not` claim predicate + * @param {xdr.ClaimPredicate} predicate an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateNot", + value: function predicateNot(predicate) { + if (!(predicate instanceof src_xdr.ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return src_xdr.ClaimPredicate.claimPredicateNot(predicate); + } + + /** + * Returns a `BeforeAbsoluteTime` claim predicate + * + * This predicate will be fulfilled if the closing time of the ledger that + * includes the CreateClaimableBalance operation is less than this (absolute) + * Unix timestamp (expressed in seconds). + * + * @param {string} absBefore Unix epoch (in seconds) as a string + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateBeforeAbsoluteTime", + value: function predicateBeforeAbsoluteTime(absBefore) { + return src_xdr.ClaimPredicate.claimPredicateBeforeAbsoluteTime(src_xdr.Int64.fromString(absBefore)); + } + + /** + * Returns a `BeforeRelativeTime` claim predicate + * + * This predicate will be fulfilled if the closing time of the ledger that + * includes the CreateClaimableBalance operation plus this relative time delta + * (in seconds) is less than the current time. + * + * @param {strings} seconds seconds since closeTime of the ledger in which the ClaimableBalanceEntry was created (as string) + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateBeforeRelativeTime", + value: function predicateBeforeRelativeTime(seconds) { + return src_xdr.ClaimPredicate.claimPredicateBeforeRelativeTime(src_xdr.Int64.fromString(seconds)); + } + + /** + * Returns a claimant object from its XDR object representation. + * @param {xdr.Claimant} claimantXdr - The claimant xdr object. + * @returns {Claimant} + */ + }, { + key: "fromXDR", + value: function fromXDR(claimantXdr) { + var value; + switch (claimantXdr["switch"]()) { + case src_xdr.ClaimantType.claimantTypeV0(): + value = claimantXdr.v0(); + return new this(StrKey.encodeEd25519PublicKey(value.destination().ed25519()), value.predicate()); + default: + throw new Error("Invalid claimant type: ".concat(claimantXdr["switch"]().name)); + } + } + }]); +}(); +;// ./src/liquidity_pool_id.js +function liquidity_pool_id_typeof(o) { "@babel/helpers - typeof"; return liquidity_pool_id_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, liquidity_pool_id_typeof(o); } +function liquidity_pool_id_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function liquidity_pool_id_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, liquidity_pool_id_toPropertyKey(o.key), o); } } +function liquidity_pool_id_createClass(e, r, t) { return r && liquidity_pool_id_defineProperties(e.prototype, r), t && liquidity_pool_id_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function liquidity_pool_id_toPropertyKey(t) { var i = liquidity_pool_id_toPrimitive(t, "string"); return "symbol" == liquidity_pool_id_typeof(i) ? i : i + ""; } +function liquidity_pool_id_toPrimitive(t, r) { if ("object" != liquidity_pool_id_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != liquidity_pool_id_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + +/** + * LiquidityPoolId class represents the asset referenced by a trustline to a + * liquidity pool. + * + * @constructor + * @param {string} liquidityPoolId - The ID of the liquidity pool in string 'hex'. + */ +var LiquidityPoolId = /*#__PURE__*/function () { + function LiquidityPoolId(liquidityPoolId) { + liquidity_pool_id_classCallCheck(this, LiquidityPoolId); + if (!liquidityPoolId) { + throw new Error('liquidityPoolId cannot be empty'); + } + if (!/^[a-f0-9]{64}$/.test(liquidityPoolId)) { + throw new Error('Liquidity pool ID is not a valid hash'); + } + this.liquidityPoolId = liquidityPoolId; + } + + /** + * Returns a liquidity pool ID object from its xdr.TrustLineAsset representation. + * @param {xdr.TrustLineAsset} tlAssetXdr - The asset XDR object. + * @returns {LiquidityPoolId} + */ + return liquidity_pool_id_createClass(LiquidityPoolId, [{ + key: "toXDRObject", + value: + /** + * Returns the `xdr.TrustLineAsset` object for this liquidity pool ID. + * + * Note: To convert from {@link Asset `Asset`} to `xdr.TrustLineAsset` please + * refer to the + * {@link Asset.toTrustLineXDRObject `Asset.toTrustLineXDRObject`} method. + * + * @returns {xdr.TrustLineAsset} XDR LiquidityPoolId object + */ + function toXDRObject() { + var xdrPoolId = src_xdr.PoolId.fromXDR(this.liquidityPoolId, 'hex'); + return new src_xdr.TrustLineAsset('assetTypePoolShare', xdrPoolId); + } + + /** + * @returns {string} Liquidity pool ID. + */ + }, { + key: "getLiquidityPoolId", + value: function getLiquidityPoolId() { + return String(this.liquidityPoolId); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {AssetType.liquidityPoolShares} asset type. Can only be `liquidity_pool_shares`. + */ + }, { + key: "getAssetType", + value: function getAssetType() { + return 'liquidity_pool_shares'; + } + + /** + * @param {LiquidityPoolId} asset LiquidityPoolId to compare. + * @returns {boolean} `true` if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(asset) { + return this.liquidityPoolId === asset.getLiquidityPoolId(); + } + }, { + key: "toString", + value: function toString() { + return "liquidity_pool:".concat(this.liquidityPoolId); + } + }], [{ + key: "fromOperation", + value: function fromOperation(tlAssetXdr) { + var assetType = tlAssetXdr["switch"](); + if (assetType === src_xdr.AssetType.assetTypePoolShare()) { + var liquidityPoolId = tlAssetXdr.liquidityPoolId().toString('hex'); + return new this(liquidityPoolId); + } + throw new Error("Invalid asset type: ".concat(assetType.name)); + } + }]); +}(); +;// ./src/operations/manage_sell_offer.js + + +/** + * Returns a XDR ManageSellOfferOp. A "manage sell offer" operation creates, updates, or + * deletes an offer. + * @function + * @alias Operation.manageSellOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.ManageSellOfferOp} Manage Sell Offer operation + */ +function manageSellOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.amount, true)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + if (opts.offerId !== undefined) { + opts.offerId = opts.offerId.toString(); + } else { + opts.offerId = '0'; + } + attributes.offerId = xdr.Hyper.fromString(opts.offerId); + var manageSellOfferOp = new src_xdr.ManageSellOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.manageSellOffer(manageSellOfferOp); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/create_passive_sell_offer.js + + +/** + * Returns a XDR CreatePasiveSellOfferOp. A "create passive offer" operation creates an + * offer that won't consume a counter offer that exactly matches this offer. This is + * useful for offers just used as 1:1 exchanges for path payments. Use manage offer + * to manage this offer after using this operation to create it. + * @function + * @alias Operation.createPassiveSellOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.CreatePassiveSellOfferOp} Create Passive Sell Offer operation + */ +function createPassiveSellOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + var createPassiveSellOfferOp = new src_xdr.CreatePassiveSellOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.createPassiveSellOffer(createPassiveSellOfferOp); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/util/decode_encode_muxed_account.js +/* provided dependency */ var decode_encode_muxed_account_Buffer = __webpack_require__(3626)["A"]; + + + +/** + * Converts a Stellar address (in G... or M... form) to an `xdr.MuxedAccount` + * structure, using the ed25519 representation when possible. + * + * This supports full muxed accounts, where an `M...` address will resolve to + * both its underlying `G...` address and an integer ID. + * + * @param {string} address G... or M... address to encode into XDR + * @returns {xdr.MuxedAccount} a muxed account object for this address string + */ +function decodeAddressToMuxedAccount(address) { + if (StrKey.isValidMed25519PublicKey(address)) { + return _decodeAddressFullyToMuxedAccount(address); + } + return src_xdr.MuxedAccount.keyTypeEd25519(StrKey.decodeEd25519PublicKey(address)); +} + +/** + * Converts an xdr.MuxedAccount to its StrKey representation. + * + * This returns its "M..." string representation if there is a muxing ID within + * the object and returns the "G..." representation otherwise. + * + * @param {xdr.MuxedAccount} muxedAccount Raw account to stringify + * @returns {string} Stringified G... (corresponding to the underlying pubkey) + * or M... address (corresponding to both the key and the muxed ID) + * + * @see https://stellar.org/protocol/sep-23 + */ +function encodeMuxedAccountToAddress(muxedAccount) { + if (muxedAccount["switch"]().value === src_xdr.CryptoKeyType.keyTypeMuxedEd25519().value) { + return _encodeMuxedAccountFullyToAddress(muxedAccount); + } + return StrKey.encodeEd25519PublicKey(muxedAccount.ed25519()); +} + +/** + * Transform a Stellar address (G...) and an ID into its XDR representation. + * + * @param {string} address - a Stellar G... address + * @param {string} id - a Uint64 ID represented as a string + * + * @return {xdr.MuxedAccount} - XDR representation of the above muxed account + */ +function encodeMuxedAccount(address, id) { + if (!StrKey.isValidEd25519PublicKey(address)) { + throw new Error('address should be a Stellar account ID (G...)'); + } + if (typeof id !== 'string') { + throw new Error('id should be a string representing a number (uint64)'); + } + return src_xdr.MuxedAccount.keyTypeMuxedEd25519(new src_xdr.MuxedAccountMed25519({ + id: src_xdr.Uint64.fromString(id), + ed25519: StrKey.decodeEd25519PublicKey(address) + })); +} + +/** + * Extracts the underlying base (G...) address from an M-address. + * @param {string} address an account address (either M... or G...) + * @return {string} a Stellar public key address (G...) + */ +function extractBaseAddress(address) { + if (StrKey.isValidEd25519PublicKey(address)) { + return address; + } + if (!StrKey.isValidMed25519PublicKey(address)) { + throw new TypeError("expected muxed account (M...), got ".concat(address)); + } + var muxedAccount = decodeAddressToMuxedAccount(address); + return StrKey.encodeEd25519PublicKey(muxedAccount.med25519().ed25519()); +} + +// Decodes an "M..." account ID into its MuxedAccount object representation. +function _decodeAddressFullyToMuxedAccount(address) { + var rawBytes = StrKey.decodeMed25519PublicKey(address); + + // Decoding M... addresses cannot be done through a simple + // MuxedAccountMed25519.fromXDR() call, because the definition is: + // + // constructor(attributes: { id: Uint64; ed25519: Buffer }); + // + // Note the ID is the first attribute. However, the ID comes *last* in the + // stringified (base32-encoded) address itself (it's the last 8-byte suffix). + // The `fromXDR()` method interprets bytes in order, so we need to parse out + // the raw binary into its requisite parts, i.e. use the MuxedAccountMed25519 + // constructor directly. + // + // Refer to https://github.com/stellar/go/blob/master/xdr/muxed_account.go#L26 + // for the Golang implementation of the M... parsing. + return src_xdr.MuxedAccount.keyTypeMuxedEd25519(new src_xdr.MuxedAccountMed25519({ + id: src_xdr.Uint64.fromXDR(rawBytes.subarray(-8)), + ed25519: rawBytes.subarray(0, -8) + })); +} + +// Converts an xdr.MuxedAccount into its *true* "M..." string representation. +function _encodeMuxedAccountFullyToAddress(muxedAccount) { + if (muxedAccount["switch"]() === src_xdr.CryptoKeyType.keyTypeEd25519()) { + return encodeMuxedAccountToAddress(muxedAccount); + } + var muxed = muxedAccount.med25519(); + return StrKey.encodeMed25519PublicKey(decode_encode_muxed_account_Buffer.concat([muxed.ed25519(), muxed.id().toXDR('raw')])); +} +;// ./src/operations/account_merge.js + + + +/** + * Transfers native balance to destination account. + * + * @function + * @alias Operation.accountMerge + * + * @param {object} opts - options object + * @param {string} opts.destination - destination to merge the source account into + * @param {string} [opts.source] - operation source account (defaults to + * transaction source) + * + * @returns {xdr.Operation} an Account Merge operation (xdr.AccountMergeOp) + */ +function accountMerge(opts) { + var opAttributes = {}; + try { + opAttributes.body = src_xdr.OperationBody.accountMerge(decodeAddressToMuxedAccount(opts.destination)); + } catch (e) { + throw new Error('destination is invalid'); + } + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/allow_trust.js + + + + +/** + * @deprecated since v5.0 + * + * Returns an XDR AllowTrustOp. An "allow trust" operation authorizes another + * account to hold your account's credit for a given asset. + * + * @function + * @alias Operation.allowTrust + * + * @param {object} opts Options object + * @param {string} opts.trustor - The trusting account (the one being authorized) + * @param {string} opts.assetCode - The asset code being authorized. + * @param {(0|1|2)} opts.authorize - `1` to authorize, `2` to authorize to maintain liabilities, and `0` to deauthorize. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * + * @returns {xdr.AllowTrustOp} Allow Trust operation + */ +function allowTrust(opts) { + if (!StrKey.isValidEd25519PublicKey(opts.trustor)) { + throw new Error('trustor is invalid'); + } + var attributes = {}; + attributes.trustor = Keypair.fromPublicKey(opts.trustor).xdrAccountId(); + if (opts.assetCode.length <= 4) { + var code = opts.assetCode.padEnd(4, '\0'); + attributes.asset = src_xdr.AssetCode.assetTypeCreditAlphanum4(code); + } else if (opts.assetCode.length <= 12) { + var _code = opts.assetCode.padEnd(12, '\0'); + attributes.asset = src_xdr.AssetCode.assetTypeCreditAlphanum12(_code); + } else { + throw new Error('Asset code must be 12 characters at max.'); + } + if (typeof opts.authorize === 'boolean') { + if (opts.authorize) { + attributes.authorize = src_xdr.TrustLineFlags.authorizedFlag().value; + } else { + attributes.authorize = 0; + } + } else { + attributes.authorize = opts.authorize; + } + var allowTrustOp = new src_xdr.AllowTrustOp(attributes); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.allowTrust(allowTrustOp); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/bump_sequence.js + + + + +/** + * This operation bumps sequence number. + * @function + * @alias Operation.bumpSequence + * @param {object} opts Options object + * @param {string} opts.bumpTo - Sequence number to bump to. + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.BumpSequenceOp} Operation + */ +function bumpSequence(opts) { + var attributes = {}; + if (typeof opts.bumpTo !== 'string') { + throw new Error('bumpTo must be a string'); + } + try { + // eslint-disable-next-line no-new + new util_bignumber(opts.bumpTo); + } catch (e) { + throw new Error('bumpTo must be a stringified number'); + } + attributes.bumpTo = xdr.Hyper.fromString(opts.bumpTo); + var bumpSequenceOp = new src_xdr.BumpSequenceOp(attributes); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.bumpSequence(bumpSequenceOp); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/change_trust.js + + + + + +var MAX_INT64 = '9223372036854775807'; + +/** + * Returns an XDR ChangeTrustOp. A "change trust" operation adds, removes, or updates a + * trust line for a given asset from the source account to another. + * @function + * @alias Operation.changeTrust + * @param {object} opts Options object + * @param {Asset | LiquidityPoolAsset} opts.asset - The asset for the trust line. + * @param {string} [opts.limit] - The limit for the asset, defaults to max int64. + * If the limit is set to "0" it deletes the trustline. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @returns {xdr.ChangeTrustOp} Change Trust operation + */ +function changeTrust(opts) { + var attributes = {}; + if (opts.asset instanceof Asset) { + attributes.line = opts.asset.toChangeTrustXDRObject(); + } else if (opts.asset instanceof LiquidityPoolAsset) { + attributes.line = opts.asset.toXDRObject(); + } else { + throw new TypeError('asset must be Asset or LiquidityPoolAsset'); + } + if (opts.limit !== undefined && !this.isValidAmount(opts.limit, true)) { + throw new TypeError(this.constructAmountRequirementsError('limit')); + } + if (opts.limit) { + attributes.limit = this._toXDRAmount(opts.limit); + } else { + attributes.limit = xdr.Hyper.fromString(new util_bignumber(MAX_INT64).toString()); + } + if (opts.source) { + attributes.source = opts.source.masterKeypair; + } + var changeTrustOP = new src_xdr.ChangeTrustOp(attributes); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.changeTrust(changeTrustOP); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/create_account.js + + + + +/** + * Create and fund a non existent account. + * @function + * @alias Operation.createAccount + * @param {object} opts Options object + * @param {string} opts.destination - Destination account ID to create an account for. + * @param {string} opts.startingBalance - Amount in XLM the account should be funded for. Must be greater + * than the [reserve balance amount](https://developers.stellar.org/docs/glossary/fees/). + * @param {string} [opts.source] - The source account for the payment. Defaults to the transaction's source account. + * @returns {xdr.CreateAccountOp} Create account operation + */ +function createAccount(opts) { + if (!StrKey.isValidEd25519PublicKey(opts.destination)) { + throw new Error('destination is invalid'); + } + if (!this.isValidAmount(opts.startingBalance, true)) { + throw new TypeError(this.constructAmountRequirementsError('startingBalance')); + } + var attributes = {}; + attributes.destination = Keypair.fromPublicKey(opts.destination).xdrAccountId(); + attributes.startingBalance = this._toXDRAmount(opts.startingBalance); + var createAccountOp = new src_xdr.CreateAccountOp(attributes); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.createAccount(createAccountOp); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/create_claimable_balance.js + + + +/** + * Create a new claimable balance operation. + * + * @function + * @alias Operation.createClaimableBalance + * + * @param {object} opts Options object + * @param {Asset} opts.asset - The asset for the claimable balance. + * @param {string} opts.amount - Amount. + * @param {Claimant[]} opts.claimants - An array of Claimants + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} Create claimable balance operation + * + * @example + * const asset = new Asset( + * 'USD', + * 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * ); + * const amount = '100.0000000'; + * const claimants = [ + * new Claimant( + * 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ', + * Claimant.predicateBeforeAbsoluteTime("4102444800000") + * ) + * ]; + * + * const op = Operation.createClaimableBalance({ + * asset, + * amount, + * claimants + * }); + * + */ +function createClaimableBalance(opts) { + if (!(opts.asset instanceof Asset)) { + throw new Error('must provide an asset for create claimable balance operation'); + } + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + if (!Array.isArray(opts.claimants) || opts.claimants.length === 0) { + throw new Error('must provide at least one claimant'); + } + var attributes = {}; + attributes.asset = opts.asset.toXDRObject(); + attributes.amount = this._toXDRAmount(opts.amount); + attributes.claimants = Object.values(opts.claimants).map(function (c) { + return c.toXDRObject(); + }); + var createClaimableBalanceOp = new src_xdr.CreateClaimableBalanceOp(attributes); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.createClaimableBalance(createClaimableBalanceOp); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/claim_claimable_balance.js + + +/** + * Create a new claim claimable balance operation. + * @function + * @alias Operation.claimClaimableBalance + * @param {object} opts Options object + * @param {string} opts.balanceId - The claimable balance id to be claimed. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} Claim claimable balance operation + * + * @example + * const op = Operation.claimClaimableBalance({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + */ +function claimClaimableBalance() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + validateClaimableBalanceId(opts.balanceId); + var attributes = {}; + attributes.balanceId = src_xdr.ClaimableBalanceId.fromXDR(opts.balanceId, 'hex'); + var claimClaimableBalanceOp = new src_xdr.ClaimClaimableBalanceOp(attributes); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.claimClaimableBalance(claimClaimableBalanceOp); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +function validateClaimableBalanceId(balanceId) { + if (typeof balanceId !== 'string' || balanceId.length !== 8 + 64 /* 8b discriminant + 64b string */) { + throw new Error('must provide a valid claimable balance id'); + } +} +;// ./src/operations/clawback_claimable_balance.js + + + +/** + * Creates a clawback operation for a claimable balance. + * + * @function + * @alias Operation.clawbackClaimableBalance + * @param {object} opts - Options object + * @param {string} opts.balanceId - The claimable balance ID to be clawed back. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @return {xdr.ClawbackClaimableBalanceOp} + * + * @example + * const op = Operation.clawbackClaimableBalance({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + * @link https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#clawback-claimable-balance-operation + */ +function clawbackClaimableBalance() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + validateClaimableBalanceId(opts.balanceId); + var attributes = { + balanceId: src_xdr.ClaimableBalanceId.fromXDR(opts.balanceId, 'hex') + }; + var opAttributes = { + body: src_xdr.OperationBody.clawbackClaimableBalance(new src_xdr.ClawbackClaimableBalanceOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/inflation.js + + +/** + * This operation generates the inflation. + * @function + * @alias Operation.inflation + * @param {object} [opts] Options object + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.InflationOp} Inflation operation + */ +function inflation() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.inflation(); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/manage_data.js +/* provided dependency */ var manage_data_Buffer = __webpack_require__(3626)["A"]; + + +/** + * This operation adds data entry to the ledger. + * @function + * @alias Operation.manageData + * @param {object} opts Options object + * @param {string} opts.name - The name of the data entry. + * @param {string|Buffer} opts.value - The value of the data entry. + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.ManageDataOp} Manage Data operation + */ +function manageData(opts) { + var attributes = {}; + if (!(typeof opts.name === 'string' && opts.name.length <= 64)) { + throw new Error('name must be a string, up to 64 characters'); + } + attributes.dataName = opts.name; + if (typeof opts.value !== 'string' && !manage_data_Buffer.isBuffer(opts.value) && opts.value !== null) { + throw new Error('value must be a string, Buffer or null'); + } + if (typeof opts.value === 'string') { + attributes.dataValue = manage_data_Buffer.from(opts.value); + } else { + attributes.dataValue = opts.value; + } + if (attributes.dataValue !== null && attributes.dataValue.length > 64) { + throw new Error('value cannot be longer that 64 bytes'); + } + var manageDataOp = new src_xdr.ManageDataOp(attributes); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.manageData(manageDataOp); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/manage_buy_offer.js + + +/** + * Returns a XDR ManageBuyOfferOp. A "manage buy offer" operation creates, updates, or + * deletes a buy offer. + * @function + * @alias Operation.manageBuyOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.buyAmount - The total amount you're buying. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `buying` in terms of `selling`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.ManageBuyOfferOp} Manage Buy Offer operation + */ +function manageBuyOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.buyAmount, true)) { + throw new TypeError(this.constructAmountRequirementsError('buyAmount')); + } + attributes.buyAmount = this._toXDRAmount(opts.buyAmount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + if (opts.offerId !== undefined) { + opts.offerId = opts.offerId.toString(); + } else { + opts.offerId = '0'; + } + attributes.offerId = xdr.Hyper.fromString(opts.offerId); + var manageBuyOfferOp = new src_xdr.ManageBuyOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.manageBuyOffer(manageBuyOfferOp); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/path_payment_strict_receive.js + + + +/** + * Creates a PathPaymentStrictReceive operation. + * + * A `PathPaymentStrictReceive` operation sends the specified amount to the + * destination account. It credits the destination with `destAmount` of + * `destAsset`, while debiting at most `sendMax` of `sendAsset` from the source. + * The transfer optionally occurs through a path. XLM payments create the + * destination account if it does not exist. + * + * @function + * @alias Operation.pathPaymentStrictReceive + * @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-receive + * + * @param {object} opts - Options object + * @param {Asset} opts.sendAsset - asset to pay with + * @param {string} opts.sendMax - maximum amount of sendAsset to send + * @param {string} opts.destination - destination account to send to + * @param {Asset} opts.destAsset - asset the destination will receive + * @param {string} opts.destAmount - amount the destination receives + * @param {Asset[]} opts.path - array of Asset objects to use as the path + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.PathPaymentStrictReceiveOp} the resulting path payment op + */ +function pathPaymentStrictReceive(opts) { + switch (true) { + case !opts.sendAsset: + throw new Error('Must specify a send asset'); + case !this.isValidAmount(opts.sendMax): + throw new TypeError(this.constructAmountRequirementsError('sendMax')); + case !opts.destAsset: + throw new Error('Must provide a destAsset for a payment operation'); + case !this.isValidAmount(opts.destAmount): + throw new TypeError(this.constructAmountRequirementsError('destAmount')); + default: + break; + } + var attributes = {}; + attributes.sendAsset = opts.sendAsset.toXDRObject(); + attributes.sendMax = this._toXDRAmount(opts.sendMax); + try { + attributes.destination = decodeAddressToMuxedAccount(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.destAsset = opts.destAsset.toXDRObject(); + attributes.destAmount = this._toXDRAmount(opts.destAmount); + var path = opts.path ? opts.path : []; + attributes.path = path.map(function (x) { + return x.toXDRObject(); + }); + var payment = new src_xdr.PathPaymentStrictReceiveOp(attributes); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.pathPaymentStrictReceive(payment); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/path_payment_strict_send.js + + + +/** + * Creates a PathPaymentStrictSend operation. + * + * A `PathPaymentStrictSend` operation sends the specified amount to the + * destination account crediting at least `destMin` of `destAsset`, optionally + * through a path. XLM payments create the destination account if it does not + * exist. + * + * @function + * @alias Operation.pathPaymentStrictSend + * @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-send + * + * @param {object} opts - Options object + * @param {Asset} opts.sendAsset - asset to pay with + * @param {string} opts.sendAmount - amount of sendAsset to send (excluding fees) + * @param {string} opts.destination - destination account to send to + * @param {Asset} opts.destAsset - asset the destination will receive + * @param {string} opts.destMin - minimum amount of destAsset to be receive + * @param {Asset[]} opts.path - array of Asset objects to use as the path + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.Operation} the resulting path payment operation + * (xdr.PathPaymentStrictSendOp) + */ +function pathPaymentStrictSend(opts) { + switch (true) { + case !opts.sendAsset: + throw new Error('Must specify a send asset'); + case !this.isValidAmount(opts.sendAmount): + throw new TypeError(this.constructAmountRequirementsError('sendAmount')); + case !opts.destAsset: + throw new Error('Must provide a destAsset for a payment operation'); + case !this.isValidAmount(opts.destMin): + throw new TypeError(this.constructAmountRequirementsError('destMin')); + default: + break; + } + var attributes = {}; + attributes.sendAsset = opts.sendAsset.toXDRObject(); + attributes.sendAmount = this._toXDRAmount(opts.sendAmount); + try { + attributes.destination = decodeAddressToMuxedAccount(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.destAsset = opts.destAsset.toXDRObject(); + attributes.destMin = this._toXDRAmount(opts.destMin); + var path = opts.path ? opts.path : []; + attributes.path = path.map(function (x) { + return x.toXDRObject(); + }); + var payment = new src_xdr.PathPaymentStrictSendOp(attributes); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.pathPaymentStrictSend(payment); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/payment.js + + + +/** + * Create a payment operation. + * + * @function + * @alias Operation.payment + * @see https://developers.stellar.org/docs/start/list-of-operations/#payment + * + * @param {object} opts - Options object + * @param {string} opts.destination - destination account ID + * @param {Asset} opts.asset - asset to send + * @param {string} opts.amount - amount to send + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting payment operation (xdr.PaymentOp) + */ +function payment(opts) { + if (!opts.asset) { + throw new Error('Must provide an asset for a payment operation'); + } + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + var attributes = {}; + try { + attributes.destination = decodeAddressToMuxedAccount(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.asset = opts.asset.toXDRObject(); + attributes.amount = this._toXDRAmount(opts.amount); + var paymentOp = new src_xdr.PaymentOp(attributes); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.payment(paymentOp); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/set_options.js +/* provided dependency */ var set_options_Buffer = __webpack_require__(3626)["A"]; +/* eslint-disable no-param-reassign */ + + + + +function weightCheckFunction(value, name) { + if (value >= 0 && value <= 255) { + return true; + } + throw new Error("".concat(name, " value must be between 0 and 255")); +} + +/** + * Returns an XDR SetOptionsOp. A "set options" operations set or clear account flags, + * set the account's inflation destination, and/or add new signers to the account. + * The flags used in `opts.clearFlags` and `opts.setFlags` can be the following: + * - `{@link AuthRequiredFlag}` + * - `{@link AuthRevocableFlag}` + * - `{@link AuthImmutableFlag}` + * - `{@link AuthClawbackEnabledFlag}` + * + * It's possible to set/clear multiple flags at once using logical or. + * + * @function + * @alias Operation.setOptions + * + * @param {object} opts Options object + * @param {string} [opts.inflationDest] - Set this account ID as the account's inflation destination. + * @param {(number|string)} [opts.clearFlags] - Bitmap integer for which account flags to clear. + * @param {(number|string)} [opts.setFlags] - Bitmap integer for which account flags to set. + * @param {number|string} [opts.masterWeight] - The master key weight. + * @param {number|string} [opts.lowThreshold] - The sum weight for the low threshold. + * @param {number|string} [opts.medThreshold] - The sum weight for the medium threshold. + * @param {number|string} [opts.highThreshold] - The sum weight for the high threshold. + * @param {object} [opts.signer] - Add or remove a signer from the account. The signer is + * deleted if the weight is 0. Only one of `ed25519PublicKey`, `sha256Hash`, `preAuthTx` should be defined. + * @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer. + * @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string) of preimage that will unlock funds. Preimage should be used as signature of future transaction. + * @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction that will unlock funds. + * @param {string} [opts.signer.ed25519SignedPayload] - Signed payload signer (ed25519 public key + raw payload) for atomic transaction signature disclosure. + * @param {number|string} [opts.signer.weight] - The weight of the new signer (0 to delete or 1-255) + * @param {string} [opts.homeDomain] - sets the home domain used for reverse federation lookup. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * + * @returns {xdr.SetOptionsOp} XDR operation + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +function setOptions(opts) { + var attributes = {}; + if (opts.inflationDest) { + if (!StrKey.isValidEd25519PublicKey(opts.inflationDest)) { + throw new Error('inflationDest is invalid'); + } + attributes.inflationDest = Keypair.fromPublicKey(opts.inflationDest).xdrAccountId(); + } + attributes.clearFlags = this._checkUnsignedIntValue('clearFlags', opts.clearFlags); + attributes.setFlags = this._checkUnsignedIntValue('setFlags', opts.setFlags); + attributes.masterWeight = this._checkUnsignedIntValue('masterWeight', opts.masterWeight, weightCheckFunction); + attributes.lowThreshold = this._checkUnsignedIntValue('lowThreshold', opts.lowThreshold, weightCheckFunction); + attributes.medThreshold = this._checkUnsignedIntValue('medThreshold', opts.medThreshold, weightCheckFunction); + attributes.highThreshold = this._checkUnsignedIntValue('highThreshold', opts.highThreshold, weightCheckFunction); + if (opts.homeDomain !== undefined && typeof opts.homeDomain !== 'string') { + throw new TypeError('homeDomain argument must be of type String'); + } + attributes.homeDomain = opts.homeDomain; + if (opts.signer) { + var weight = this._checkUnsignedIntValue('signer.weight', opts.signer.weight, weightCheckFunction); + var key; + var setValues = 0; + if (opts.signer.ed25519PublicKey) { + if (!StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) { + throw new Error('signer.ed25519PublicKey is invalid.'); + } + var rawKey = StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey); + + // eslint-disable-next-line new-cap + key = new src_xdr.SignerKey.signerKeyTypeEd25519(rawKey); + setValues += 1; + } + if (opts.signer.preAuthTx) { + if (typeof opts.signer.preAuthTx === 'string') { + opts.signer.preAuthTx = set_options_Buffer.from(opts.signer.preAuthTx, 'hex'); + } + if (!(set_options_Buffer.isBuffer(opts.signer.preAuthTx) && opts.signer.preAuthTx.length === 32)) { + throw new Error('signer.preAuthTx must be 32 bytes Buffer.'); + } + + // eslint-disable-next-line new-cap + key = new src_xdr.SignerKey.signerKeyTypePreAuthTx(opts.signer.preAuthTx); + setValues += 1; + } + if (opts.signer.sha256Hash) { + if (typeof opts.signer.sha256Hash === 'string') { + opts.signer.sha256Hash = set_options_Buffer.from(opts.signer.sha256Hash, 'hex'); + } + if (!(set_options_Buffer.isBuffer(opts.signer.sha256Hash) && opts.signer.sha256Hash.length === 32)) { + throw new Error('signer.sha256Hash must be 32 bytes Buffer.'); + } + + // eslint-disable-next-line new-cap + key = new src_xdr.SignerKey.signerKeyTypeHashX(opts.signer.sha256Hash); + setValues += 1; + } + if (opts.signer.ed25519SignedPayload) { + if (!StrKey.isValidSignedPayload(opts.signer.ed25519SignedPayload)) { + throw new Error('signer.ed25519SignedPayload is invalid.'); + } + var _rawKey = StrKey.decodeSignedPayload(opts.signer.ed25519SignedPayload); + var signedPayloadXdr = src_xdr.SignerKeyEd25519SignedPayload.fromXDR(_rawKey); + + // eslint-disable-next-line new-cap + key = src_xdr.SignerKey.signerKeyTypeEd25519SignedPayload(signedPayloadXdr); + setValues += 1; + } + if (setValues !== 1) { + throw new Error('Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx.'); + } + attributes.signer = new src_xdr.Signer({ + key: key, + weight: weight + }); + } + var setOptionsOp = new src_xdr.SetOptionsOp(attributes); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.setOptions(setOptionsOp); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/begin_sponsoring_future_reserves.js + + + + +/** + * Create a "begin sponsoring future reserves" operation. + * @function + * @alias Operation.beginSponsoringFutureReserves + * @param {object} opts Options object + * @param {string} opts.sponsoredId - The sponsored account id. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.beginSponsoringFutureReserves({ + * sponsoredId: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * }); + * + */ +function beginSponsoringFutureReserves() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!StrKey.isValidEd25519PublicKey(opts.sponsoredId)) { + throw new Error('sponsoredId is invalid'); + } + var op = new src_xdr.BeginSponsoringFutureReservesOp({ + sponsoredId: Keypair.fromPublicKey(opts.sponsoredId).xdrAccountId() + }); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.beginSponsoringFutureReserves(op); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/end_sponsoring_future_reserves.js + + +/** + * Create an "end sponsoring future reserves" operation. + * @function + * @alias Operation.endSponsoringFutureReserves + * @param {object} opts Options object + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.endSponsoringFutureReserves(); + * + */ +function endSponsoringFutureReserves() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.endSponsoringFutureReserves(); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/revoke_sponsorship.js +/* provided dependency */ var revoke_sponsorship_Buffer = __webpack_require__(3626)["A"]; + + + + + + +/** + * Create a "revoke sponsorship" operation for an account. + * + * @function + * @alias Operation.revokeAccountSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The sponsored account ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeAccountSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * }); + * + */ +function revokeAccountSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var ledgerKey = src_xdr.LedgerKey.account(new src_xdr.LedgerKeyAccount({ + accountId: Keypair.fromPublicKey(opts.account).xdrAccountId() + })); + var op = src_xdr.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a trustline. + * + * @function + * @alias Operation.revokeTrustlineSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID which owns the trustline. + * @param {Asset | LiquidityPoolId} opts.asset - The trustline asset. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeTrustlineSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * asset: new StellarBase.LiquidityPoolId( + * 'USDUSD', + * 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * ) + * }); + * + */ +function revokeTrustlineSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var asset; + if (opts.asset instanceof Asset) { + asset = opts.asset.toTrustLineXDRObject(); + } else if (opts.asset instanceof LiquidityPoolId) { + asset = opts.asset.toXDRObject(); + } else { + throw new TypeError('asset must be an Asset or LiquidityPoolId'); + } + var ledgerKey = src_xdr.LedgerKey.trustline(new src_xdr.LedgerKeyTrustLine({ + accountId: Keypair.fromPublicKey(opts.account).xdrAccountId(), + asset: asset + })); + var op = src_xdr.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for an offer. + * + * @function + * @alias Operation.revokeOfferSponsorship + * @param {object} opts Options object + * @param {string} opts.seller - The account ID which created the offer. + * @param {string} opts.offerId - The offer ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeOfferSponsorship({ + * seller: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * offerId: '1234' + * }); + * + */ +function revokeOfferSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!StrKey.isValidEd25519PublicKey(opts.seller)) { + throw new Error('seller is invalid'); + } + if (typeof opts.offerId !== 'string') { + throw new Error('offerId is invalid'); + } + var ledgerKey = src_xdr.LedgerKey.offer(new src_xdr.LedgerKeyOffer({ + sellerId: Keypair.fromPublicKey(opts.seller).xdrAccountId(), + offerId: src_xdr.Int64.fromString(opts.offerId) + })); + var op = src_xdr.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a data entry. + * + * @function + * @alias Operation.revokeDataSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID which owns the data entry. + * @param {string} opts.name - The name of the data entry + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeDataSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * name: 'foo' + * }); + * + */ +function revokeDataSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + if (typeof opts.name !== 'string' || opts.name.length > 64) { + throw new Error('name must be a string, up to 64 characters'); + } + var ledgerKey = src_xdr.LedgerKey.data(new src_xdr.LedgerKeyData({ + accountId: Keypair.fromPublicKey(opts.account).xdrAccountId(), + dataName: opts.name + })); + var op = src_xdr.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a claimable balance. + * + * @function + * @alias Operation.revokeClaimableBalanceSponsorship + * @param {object} opts Options object + * @param {string} opts.balanceId - The sponsored claimable balance ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeClaimableBalanceSponsorship({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + */ +function revokeClaimableBalanceSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (typeof opts.balanceId !== 'string') { + throw new Error('balanceId is invalid'); + } + var ledgerKey = src_xdr.LedgerKey.claimableBalance(new src_xdr.LedgerKeyClaimableBalance({ + balanceId: src_xdr.ClaimableBalanceId.fromXDR(opts.balanceId, 'hex') + })); + var op = src_xdr.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} + +/** + * Creates a "revoke sponsorship" operation for a liquidity pool. + * + * @function + * @alias Operation.revokeLiquidityPoolSponsorship + * @param {object} opts – Options object. + * @param {string} opts.liquidityPoolId - The sponsored liquidity pool ID in 'hex' string. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr Operation. + * + * @example + * const op = Operation.revokeLiquidityPoolSponsorship({ + * liquidityPoolId: 'dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7', + * }); + * + */ +function revokeLiquidityPoolSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (typeof opts.liquidityPoolId !== 'string') { + throw new Error('liquidityPoolId is invalid'); + } + var ledgerKey = src_xdr.LedgerKey.liquidityPool(new src_xdr.LedgerKeyLiquidityPool({ + liquidityPoolId: src_xdr.PoolId.fromXDR(opts.liquidityPoolId, 'hex') + })); + var op = src_xdr.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = { + body: src_xdr.OperationBody.revokeSponsorship(op) + }; + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a signer. + * + * @function + * @alias Operation.revokeSignerSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID where the signer sponsorship is being removed from. + * @param {object} opts.signer - The signer whose sponsorship is being removed. + * @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer. + * @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string). + * @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeSignerSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * signer: { + * ed25519PublicKey: 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ' + * } + * }) + * + */ +function revokeSignerSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var key; + if (opts.signer.ed25519PublicKey) { + if (!StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) { + throw new Error('signer.ed25519PublicKey is invalid.'); + } + var rawKey = StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey); + key = new src_xdr.SignerKey.signerKeyTypeEd25519(rawKey); + } else if (opts.signer.preAuthTx) { + var buffer; + if (typeof opts.signer.preAuthTx === 'string') { + buffer = revoke_sponsorship_Buffer.from(opts.signer.preAuthTx, 'hex'); + } else { + buffer = opts.signer.preAuthTx; + } + if (!(revoke_sponsorship_Buffer.isBuffer(buffer) && buffer.length === 32)) { + throw new Error('signer.preAuthTx must be 32 bytes Buffer.'); + } + key = new src_xdr.SignerKey.signerKeyTypePreAuthTx(buffer); + } else if (opts.signer.sha256Hash) { + var _buffer; + if (typeof opts.signer.sha256Hash === 'string') { + _buffer = revoke_sponsorship_Buffer.from(opts.signer.sha256Hash, 'hex'); + } else { + _buffer = opts.signer.sha256Hash; + } + if (!(revoke_sponsorship_Buffer.isBuffer(_buffer) && _buffer.length === 32)) { + throw new Error('signer.sha256Hash must be 32 bytes Buffer.'); + } + key = new src_xdr.SignerKey.signerKeyTypeHashX(_buffer); + } else { + throw new Error('signer is invalid'); + } + var signer = new src_xdr.RevokeSponsorshipOpSigner({ + accountId: Keypair.fromPublicKey(opts.account).xdrAccountId(), + signerKey: key + }); + var op = src_xdr.RevokeSponsorshipOp.revokeSponsorshipSigner(signer); + var opAttributes = {}; + opAttributes.body = src_xdr.OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/clawback.js + + + +/** + * Creates a clawback operation. + * + * @function + * @alias Operation.clawback + * + * @param {object} opts - Options object + * @param {Asset} opts.asset - The asset being clawed back. + * @param {string} opts.amount - The amount of the asset to claw back. + * @param {string} opts.from - The public key of the (optionally-muxed) + * account to claw back from. + * + * @param {string} [opts.source] - The source account for the operation. + * Defaults to the transaction's source account. + * + * @return {xdr.ClawbackOp} + * + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#clawback-operation + */ +function clawback(opts) { + var attributes = {}; + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + attributes.asset = opts.asset.toXDRObject(); + try { + attributes.from = decodeAddressToMuxedAccount(opts.from); + } catch (e) { + throw new Error('from address is invalid'); + } + var opAttributes = { + body: src_xdr.OperationBody.clawback(new src_xdr.ClawbackOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/set_trustline_flags.js +function set_trustline_flags_typeof(o) { "@babel/helpers - typeof"; return set_trustline_flags_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, set_trustline_flags_typeof(o); } + + + +/** + * Creates a trustline flag configuring operation. + * + * For the flags, set them to true to enable them and false to disable them. Any + * unmodified operations will be marked `undefined` in the result. + * + * Note that you can only **clear** the clawbackEnabled flag set; it must be set + * account-wide via operations.SetOptions (setting + * xdr.AccountFlags.clawbackEnabled). + * + * @function + * @alias Operation.setTrustLineFlags + * + * @param {object} opts - Options object + * @param {string} opts.trustor - the account whose trustline this is + * @param {Asset} opts.asset - the asset on the trustline + * @param {object} opts.flags - the set of flags to modify + * + * @param {bool} [opts.flags.authorized] - authorize account to perform + * transactions with its credit + * @param {bool} [opts.flags.authorizedToMaintainLiabilities] - authorize + * account to maintain and reduce liabilities for its credit + * @param {bool} [opts.flags.clawbackEnabled] - stop claimable balances on + * this trustlines from having clawbacks enabled (this flag can only be set + * to false!) + * @param {string} [opts.source] - The source account for the operation. + * Defaults to the transaction's source account. + * + * @note You must include at least one flag. + * + * @return {xdr.SetTrustLineFlagsOp} + * + * @link xdr.AccountFlags + * @link xdr.TrustLineFlags + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#set-trustline-flags-operation + * @see https://developers.stellar.org/docs/start/list-of-operations/#set-options + */ +function setTrustLineFlags() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var attributes = {}; + if (set_trustline_flags_typeof(opts.flags) !== 'object' || Object.keys(opts.flags).length === 0) { + throw new Error('opts.flags must be a map of boolean flags to modify'); + } + var mapping = { + authorized: src_xdr.TrustLineFlags.authorizedFlag(), + authorizedToMaintainLiabilities: src_xdr.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(), + clawbackEnabled: src_xdr.TrustLineFlags.trustlineClawbackEnabledFlag() + }; + + /* eslint no-bitwise: "off" */ + var clearFlag = 0; + var setFlag = 0; + Object.keys(opts.flags).forEach(function (flagName) { + if (!Object.prototype.hasOwnProperty.call(mapping, flagName)) { + throw new Error("unsupported flag name specified: ".concat(flagName)); + } + var flagValue = opts.flags[flagName]; + var bit = mapping[flagName].value; + if (flagValue === true) { + setFlag |= bit; + } else if (flagValue === false) { + clearFlag |= bit; + } + }); + attributes.trustor = Keypair.fromPublicKey(opts.trustor).xdrAccountId(); + attributes.asset = opts.asset.toXDRObject(); + attributes.clearFlags = clearFlag; + attributes.setFlags = setFlag; + var opAttributes = { + body: src_xdr.OperationBody.setTrustLineFlags(new src_xdr.SetTrustLineFlagsOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/liquidity_pool_deposit.js + + +/** + * Creates a liquidity pool deposit operation. + * + * @function + * @alias Operation.liquidityPoolDeposit + * @see https://developers.stellar.org/docs/start/list-of-operations/#liquidity-pool-deposit + * + * @param {object} opts - Options object + * @param {string} opts.liquidityPoolId - The liquidity pool ID. + * @param {string} opts.maxAmountA - Maximum amount of first asset to deposit. + * @param {string} opts.maxAmountB - Maximum amount of second asset to deposit. + * @param {number|string|BigNumber|Object} opts.minPrice - Minimum depositA/depositB price. + * @param {number} opts.minPrice.n - If `opts.minPrice` is an object: the price numerator + * @param {number} opts.minPrice.d - If `opts.minPrice` is an object: the price denominator + * @param {number|string|BigNumber|Object} opts.maxPrice - Maximum depositA/depositB price. + * @param {number} opts.maxPrice.n - If `opts.maxPrice` is an object: the price numerator + * @param {number} opts.maxPrice.d - If `opts.maxPrice` is an object: the price denominator + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting operation (xdr.LiquidityPoolDepositOp). + */ +function liquidityPoolDeposit() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var liquidityPoolId = opts.liquidityPoolId, + maxAmountA = opts.maxAmountA, + maxAmountB = opts.maxAmountB, + minPrice = opts.minPrice, + maxPrice = opts.maxPrice; + var attributes = {}; + if (!liquidityPoolId) { + throw new TypeError('liquidityPoolId argument is required'); + } + attributes.liquidityPoolId = src_xdr.PoolId.fromXDR(liquidityPoolId, 'hex'); + if (!this.isValidAmount(maxAmountA, true)) { + throw new TypeError(this.constructAmountRequirementsError('maxAmountA')); + } + attributes.maxAmountA = this._toXDRAmount(maxAmountA); + if (!this.isValidAmount(maxAmountB, true)) { + throw new TypeError(this.constructAmountRequirementsError('maxAmountB')); + } + attributes.maxAmountB = this._toXDRAmount(maxAmountB); + if (minPrice === undefined) { + throw new TypeError('minPrice argument is required'); + } + attributes.minPrice = this._toXDRPrice(minPrice); + if (maxPrice === undefined) { + throw new TypeError('maxPrice argument is required'); + } + attributes.maxPrice = this._toXDRPrice(maxPrice); + var liquidityPoolDepositOp = new src_xdr.LiquidityPoolDepositOp(attributes); + var opAttributes = { + body: src_xdr.OperationBody.liquidityPoolDeposit(liquidityPoolDepositOp) + }; + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/liquidity_pool_withdraw.js + + +/** + * Creates a liquidity pool withdraw operation. + * + * @function + * @alias Operation.liquidityPoolWithdraw + * @see https://developers.stellar.org/docs/start/list-of-operations/#liquidity-pool-withdraw + * + * @param {object} opts - Options object + * @param {string} opts.liquidityPoolId - The liquidity pool ID. + * @param {string} opts.amount - Amount of pool shares to withdraw. + * @param {string} opts.minAmountA - Minimum amount of first asset to withdraw. + * @param {string} opts.minAmountB - Minimum amount of second asset to withdraw. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting operation (xdr.LiquidityPoolWithdrawOp). + */ +function liquidityPoolWithdraw() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var attributes = {}; + if (!opts.liquidityPoolId) { + throw new TypeError('liquidityPoolId argument is required'); + } + attributes.liquidityPoolId = src_xdr.PoolId.fromXDR(opts.liquidityPoolId, 'hex'); + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (!this.isValidAmount(opts.minAmountA, true)) { + throw new TypeError(this.constructAmountRequirementsError('minAmountA')); + } + attributes.minAmountA = this._toXDRAmount(opts.minAmountA); + if (!this.isValidAmount(opts.minAmountB, true)) { + throw new TypeError(this.constructAmountRequirementsError('minAmountB')); + } + attributes.minAmountB = this._toXDRAmount(opts.minAmountB); + var liquidityPoolWithdrawOp = new src_xdr.LiquidityPoolWithdrawOp(attributes); + var opAttributes = { + body: src_xdr.OperationBody.liquidityPoolWithdraw(liquidityPoolWithdrawOp) + }; + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/address.js +function address_typeof(o) { "@babel/helpers - typeof"; return address_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, address_typeof(o); } +function address_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function address_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, address_toPropertyKey(o.key), o); } } +function address_createClass(e, r, t) { return r && address_defineProperties(e.prototype, r), t && address_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function address_toPropertyKey(t) { var i = address_toPrimitive(t, "string"); return "symbol" == address_typeof(i) ? i : i + ""; } +function address_toPrimitive(t, r) { if ("object" != address_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != address_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + +/** + * Create a new Address object. + * + * `Address` represents a single address in the Stellar network. An address can + * represent an account or a contract. + * + * @constructor + * + * @param {string} address - ID of the account (ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`). If you + * provide a muxed account address, this will throw; use {@link + * MuxedAccount} instead. + */ +var Address = /*#__PURE__*/function () { + function Address(address) { + address_classCallCheck(this, Address); + if (StrKey.isValidEd25519PublicKey(address)) { + this._type = 'account'; + this._key = StrKey.decodeEd25519PublicKey(address); + } else if (StrKey.isValidContract(address)) { + this._type = 'contract'; + this._key = StrKey.decodeContract(address); + } else { + throw new Error("Unsupported address type: ".concat(address)); + } + } + + /** + * Parses a string and returns an Address object. + * + * @param {string} address - The address to parse. ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA` + * @returns {Address} + */ + return address_createClass(Address, [{ + key: "toString", + value: + /** + * Serialize an address to string. + * + * @returns {string} + */ + function toString() { + switch (this._type) { + case 'account': + return StrKey.encodeEd25519PublicKey(this._key); + case 'contract': + return StrKey.encodeContract(this._key); + default: + throw new Error('Unsupported address type'); + } + } + + /** + * Convert this Address to an xdr.ScVal type. + * + * @returns {xdr.ScVal} + */ + }, { + key: "toScVal", + value: function toScVal() { + return src_xdr.ScVal.scvAddress(this.toScAddress()); + } + + /** + * Convert this Address to an xdr.ScAddress type. + * + * @returns {xdr.ScAddress} + */ + }, { + key: "toScAddress", + value: function toScAddress() { + switch (this._type) { + case 'account': + return src_xdr.ScAddress.scAddressTypeAccount(src_xdr.PublicKey.publicKeyTypeEd25519(this._key)); + case 'contract': + return src_xdr.ScAddress.scAddressTypeContract(this._key); + default: + throw new Error('Unsupported address type'); + } + } + + /** + * Return the raw public key bytes for this address. + * + * @returns {Buffer} + */ + }, { + key: "toBuffer", + value: function toBuffer() { + return this._key; + } + }], [{ + key: "fromString", + value: function fromString(address) { + return new Address(address); + } + + /** + * Creates a new account Address object from a buffer of raw bytes. + * + * @param {Buffer} buffer - The bytes of an address to parse. + * @returns {Address} + */ + }, { + key: "account", + value: function account(buffer) { + return new Address(StrKey.encodeEd25519PublicKey(buffer)); + } + + /** + * Creates a new contract Address object from a buffer of raw bytes. + * + * @param {Buffer} buffer - The bytes of an address to parse. + * @returns {Address} + */ + }, { + key: "contract", + value: function contract(buffer) { + return new Address(StrKey.encodeContract(buffer)); + } + + /** + * Convert this from an xdr.ScVal type + * + * @param {xdr.ScVal} scVal - The xdr.ScVal type to parse + * @returns {Address} + */ + }, { + key: "fromScVal", + value: function fromScVal(scVal) { + return Address.fromScAddress(scVal.address()); + } + + /** + * Convert this from an xdr.ScAddress type + * + * @param {xdr.ScAddress} scAddress - The xdr.ScAddress type to parse + * @returns {Address} + */ + }, { + key: "fromScAddress", + value: function fromScAddress(scAddress) { + switch (scAddress["switch"]()) { + case src_xdr.ScAddressType.scAddressTypeAccount(): + return Address.account(scAddress.accountId().ed25519()); + case src_xdr.ScAddressType.scAddressTypeContract(): + return Address.contract(scAddress.contractId()); + default: + throw new Error('Unsupported address type'); + } + } + }]); +}(); +;// ./src/operations/invoke_host_function.js +/* provided dependency */ var invoke_host_function_Buffer = __webpack_require__(3626)["A"]; +function invoke_host_function_slicedToArray(r, e) { return invoke_host_function_arrayWithHoles(r) || invoke_host_function_iterableToArrayLimit(r, e) || invoke_host_function_unsupportedIterableToArray(r, e) || invoke_host_function_nonIterableRest(); } +function invoke_host_function_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function invoke_host_function_unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return invoke_host_function_arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? invoke_host_function_arrayLikeToArray(r, a) : void 0; } } +function invoke_host_function_arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function invoke_host_function_iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function invoke_host_function_arrayWithHoles(r) { if (Array.isArray(r)) return r; } + + + + + +/** + * Invokes a single smart contract host function. + * + * @function + * @alias Operation.invokeHostFunction + * + * @param {object} opts - options object + * @param {xdr.HostFunction} opts.func - host function to execute (with its + * wrapped parameters) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - list outlining the + * tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + * @see Operation.invokeContractFunction + * @see Operation.createCustomContract + * @see Operation.createStellarAssetContract + * @see Operation.uploadContractWasm + * @see Contract.call + */ +function invokeHostFunction(opts) { + if (!opts.func) { + throw new TypeError("host function invocation ('func') required (got ".concat(JSON.stringify(opts), ")")); + } + var invokeHostFunctionOp = new src_xdr.InvokeHostFunctionOp({ + hostFunction: opts.func, + auth: opts.auth || [] + }); + var opAttributes = { + body: src_xdr.OperationBody.invokeHostFunction(invokeHostFunctionOp) + }; + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} + +/** + * Returns an operation that invokes a contract function. + * + * @function + * @alias Operation.invokeContractFunction + * + * @param {any} opts - the set of parameters + * @param {string} opts.contract - a strkey-fied contract address (`C...`) + * @param {string} opts.function - the name of the contract fn to invoke + * @param {xdr.ScVal[]} opts.args - parameters to pass to the function + * invocation (try {@link nativeToScVal} or {@link ScInt} to make building + * these easier) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see Operation.invokeHostFunction + * @see Contract.call + * @see Address + */ +function invokeContractFunction(opts) { + var c = new Address(opts.contract); + if (c._type !== 'contract') { + throw new TypeError("expected contract strkey instance, got ".concat(c)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: src_xdr.HostFunction.hostFunctionTypeInvokeContract(new src_xdr.InvokeContractArgs({ + contractAddress: c.toScAddress(), + functionName: opts["function"], + args: opts.args + })) + }); +} + +/** + * Returns an operation that creates a custom WASM contract and atomically + * invokes its constructor. + * + * @function + * @alias Operation.createCustomContract + * + * @param {any} opts - the set of parameters + * @param {Address} opts.address - the contract uploader address + * @param {Uint8Array|Buffer} opts.wasmHash - the SHA-256 hash of the contract + * WASM you're uploading (see {@link hash} and + * {@link Operation.uploadContractWasm}) + * @param {xdr.ScVal[]} [opts.constructorArgs] - the optional parameters to pass + * to the constructor of this contract (see {@link nativeToScVal} for ways to + * easily create these parameters from native JS values) + * @param {Uint8Array|Buffer} [opts.salt] - an optional, 32-byte salt to + * distinguish deployment instances of the same wasm from the same user (if + * omitted, one will be generated for you) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + */ +function createCustomContract(opts) { + var _opts$constructorArgs; + var salt = invoke_host_function_Buffer.from(opts.salt || getSalty()); + if (!opts.wasmHash || opts.wasmHash.length !== 32) { + throw new TypeError("expected hash(contract WASM) in 'opts.wasmHash', got ".concat(opts.wasmHash)); + } + if (salt.length !== 32) { + throw new TypeError("expected 32-byte salt in 'opts.salt', got ".concat(opts.wasmHash)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: src_xdr.HostFunction.hostFunctionTypeCreateContractV2(new src_xdr.CreateContractArgsV2({ + executable: src_xdr.ContractExecutable.contractExecutableWasm(invoke_host_function_Buffer.from(opts.wasmHash)), + contractIdPreimage: src_xdr.ContractIdPreimage.contractIdPreimageFromAddress(new src_xdr.ContractIdPreimageFromAddress({ + address: opts.address.toScAddress(), + salt: salt + })), + constructorArgs: (_opts$constructorArgs = opts.constructorArgs) !== null && _opts$constructorArgs !== void 0 ? _opts$constructorArgs : [] + })) + }); +} + +/** + * Returns an operation that wraps a Stellar asset into a token contract. + * + * @function + * @alias Operation.createStellarAssetContract + * + * @param {any} opts - the set of parameters + * @param {Asset|string} opts.asset - the Stellar asset to wrap, either as an + * {@link Asset} object or in canonical form (SEP-11, `code:issuer`) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see https://stellar.org/protocol/sep-11#alphanum4-alphanum12 + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions + * @see + * https://soroban.stellar.org/docs/advanced-tutorials/stellar-asset-contract + * @see Operation.invokeHostFunction + */ +function createStellarAssetContract(opts) { + var asset = opts.asset; + if (typeof asset === 'string') { + var _asset$split = asset.split(':'), + _asset$split2 = invoke_host_function_slicedToArray(_asset$split, 2), + code = _asset$split2[0], + issuer = _asset$split2[1]; + asset = new Asset(code, issuer); // handles 'xlm' by default + } + if (!(asset instanceof Asset)) { + throw new TypeError("expected Asset in 'opts.asset', got ".concat(asset)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: src_xdr.HostFunction.hostFunctionTypeCreateContract(new src_xdr.CreateContractArgs({ + executable: src_xdr.ContractExecutable.contractExecutableStellarAsset(), + contractIdPreimage: src_xdr.ContractIdPreimage.contractIdPreimageFromAsset(asset.toXDRObject()) + })) + }); +} + +/** + * Returns an operation that uploads WASM for a contract. + * + * @function + * @alias Operation.uploadContractWasm + * + * @param {any} opts - the set of parameters + * @param {Uint8Array|Buffer} opts.wasm - a WASM blob to upload to the ledger + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + */ +function uploadContractWasm(opts) { + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: src_xdr.HostFunction.hostFunctionTypeUploadContractWasm(invoke_host_function_Buffer.from(opts.wasm) // coalesce so we can drop `Buffer` someday + ) + }); +} + +/** @returns {Buffer} a random 256-bit "salt" value. */ +function getSalty() { + return Keypair.random().xdrPublicKey().value(); // ed25519 is 256 bits, too +} +;// ./src/operations/extend_footprint_ttl.js + + +/** + * Builds an operation to bump the time-to-live (TTL) of the ledger keys. The + * keys for extension have to be provided in the read-only footprint of + * the transaction. + * + * The only parameter of the operation itself is the new minimum TTL for + * all the provided entries. If an entry already has a higher TTL, then it + * will just be skipped. + * + * TTL is the number of ledgers from the current ledger (exclusive) until + * the last ledger the entry is still considered alive (inclusive). Thus + * the exact ledger until the entries will live will only be determined + * when transaction has been applied. + * + * The footprint has to be specified in the transaction. See + * {@link TransactionBuilder}'s `opts.sorobanData` parameter, which is a + * {@link xdr.SorobanTransactionData} instance that contains fee data & resource + * usage as part of {@link xdr.SorobanResources}. + * + * @function + * @alias Operation.extendFootprintTtl + * + * @param {object} opts - object holding operation parameters + * @param {number} opts.extendTo - the minimum TTL that all the entries in + * the read-only footprint will have + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Extend Footprint TTL operation + * (xdr.ExtendFootprintTTLOp) + */ +function extendFootprintTtl(opts) { + var _opts$extendTo; + if (((_opts$extendTo = opts.extendTo) !== null && _opts$extendTo !== void 0 ? _opts$extendTo : -1) <= 0) { + throw new RangeError('extendTo has to be positive'); + } + var extendFootprintOp = new src_xdr.ExtendFootprintTtlOp({ + ext: new src_xdr.ExtensionPoint(0), + extendTo: opts.extendTo + }); + var opAttributes = { + body: src_xdr.OperationBody.extendFootprintTtl(extendFootprintOp) + }; + this.setSourceAccount(opAttributes, opts); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/restore_footprint.js + + +/** + * Builds an operation to restore the archived ledger entries specified + * by the ledger keys. + * + * The ledger keys to restore are specified separately from the operation + * in read-write footprint of the transaction. + * + * It takes no parameters because the relevant footprint is derived from the + * transaction itself. See {@link TransactionBuilder}'s `opts.sorobanData` + * parameter (or {@link TransactionBuilder.setSorobanData} / + * {@link TransactionBuilder.setLedgerKeys}), which is a + * {@link xdr.SorobanTransactionData} instance that contains fee data & resource + * usage as part of {@link xdr.SorobanTransactionData}. + * + * @function + * @alias Operation.restoreFootprint + * + * @param {object} [opts] - an optional set of parameters + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} a Bump Footprint Expiration operation + * (xdr.RestoreFootprintOp) + */ +function restoreFootprint() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var op = new src_xdr.RestoreFootprintOp({ + ext: new src_xdr.ExtensionPoint(0) + }); + var opAttributes = { + body: src_xdr.OperationBody.restoreFootprint(op) + }; + this.setSourceAccount(opAttributes, opts !== null && opts !== void 0 ? opts : {}); + return new src_xdr.Operation(opAttributes); +} +;// ./src/operations/index.js + + + + + + + + + + + + + + + + + + + + + + + + + + + +;// ./src/operation.js +function operation_typeof(o) { "@babel/helpers - typeof"; return operation_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, operation_typeof(o); } +function operation_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function operation_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, operation_toPropertyKey(o.key), o); } } +function operation_createClass(e, r, t) { return r && operation_defineProperties(e.prototype, r), t && operation_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function operation_toPropertyKey(t) { var i = operation_toPrimitive(t, "string"); return "symbol" == operation_typeof(i) ? i : i + ""; } +function operation_toPrimitive(t, r) { if ("object" != operation_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != operation_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/* eslint-disable no-bitwise */ + + + + + + + + + + + + + +var ONE = 10000000; +var operation_MAX_INT64 = '9223372036854775807'; + +/** + * When set using `{@link Operation.setOptions}` option, requires the issuing + * account to give other accounts permission before they can hold the issuing + * account’s credit. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthRequiredFlag = 1 << 0; +/** + * When set using `{@link Operation.setOptions}` option, allows the issuing + * account to revoke its credit held by other accounts. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthRevocableFlag = 1 << 1; +/** + * When set using `{@link Operation.setOptions}` option, then none of the + * authorization flags can be set and the account can never be deleted. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthImmutableFlag = 1 << 2; + +/** + * When set using `{@link Operation.setOptions}` option, then any trustlines + * created by this account can have a ClawbackOp operation submitted for the + * corresponding asset. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthClawbackEnabledFlag = 1 << 3; + +/** + * `Operation` class represents + * [operations](https://developers.stellar.org/docs/glossary/operations/) in + * Stellar network. + * + * Use one of static methods to create operations: + * * `{@link Operation.createAccount}` + * * `{@link Operation.payment}` + * * `{@link Operation.pathPaymentStrictReceive}` + * * `{@link Operation.pathPaymentStrictSend}` + * * `{@link Operation.manageSellOffer}` + * * `{@link Operation.manageBuyOffer}` + * * `{@link Operation.createPassiveSellOffer}` + * * `{@link Operation.setOptions}` + * * `{@link Operation.changeTrust}` + * * `{@link Operation.allowTrust}` + * * `{@link Operation.accountMerge}` + * * `{@link Operation.inflation}` + * * `{@link Operation.manageData}` + * * `{@link Operation.bumpSequence}` + * * `{@link Operation.createClaimableBalance}` + * * `{@link Operation.claimClaimableBalance}` + * * `{@link Operation.beginSponsoringFutureReserves}` + * * `{@link Operation.endSponsoringFutureReserves}` + * * `{@link Operation.revokeAccountSponsorship}` + * * `{@link Operation.revokeTrustlineSponsorship}` + * * `{@link Operation.revokeOfferSponsorship}` + * * `{@link Operation.revokeDataSponsorship}` + * * `{@link Operation.revokeClaimableBalanceSponsorship}` + * * `{@link Operation.revokeLiquidityPoolSponsorship}` + * * `{@link Operation.revokeSignerSponsorship}` + * * `{@link Operation.clawback}` + * * `{@link Operation.clawbackClaimableBalance}` + * * `{@link Operation.setTrustLineFlags}` + * * `{@link Operation.liquidityPoolDeposit}` + * * `{@link Operation.liquidityPoolWithdraw}` + * * `{@link Operation.invokeHostFunction}`, which has the following additional + * "pseudo-operations" that make building host functions easier: + * - `{@link Operation.createStellarAssetContract}` + * - `{@link Operation.invokeContractFunction}` + * - `{@link Operation.createCustomContract}` + * - `{@link Operation.uploadContractWasm}` + * * `{@link Operation.extendFootprintTtlOp}` + * * `{@link Operation.restoreFootprint}` + * + * @class Operation + */ +var Operation = /*#__PURE__*/function () { + function Operation() { + operation_classCallCheck(this, Operation); + } + return operation_createClass(Operation, null, [{ + key: "setSourceAccount", + value: function setSourceAccount(opAttributes, opts) { + if (opts.source) { + try { + opAttributes.sourceAccount = decodeAddressToMuxedAccount(opts.source); + } catch (e) { + throw new Error('Source address is invalid'); + } + } + } + + /** + * Deconstructs the raw XDR operation object into the structured object that + * was used to create the operation (i.e. the `opts` parameter to most ops). + * + * @param {xdr.Operation} operation - An XDR Operation. + * @return {Operation} + */ + }, { + key: "fromXDRObject", + value: function fromXDRObject(operation) { + var result = {}; + if (operation.sourceAccount()) { + result.source = encodeMuxedAccountToAddress(operation.sourceAccount()); + } + var attrs = operation.body().value(); + var operationName = operation.body()["switch"]().name; + switch (operationName) { + case 'createAccount': + { + result.type = 'createAccount'; + result.destination = accountIdtoAddress(attrs.destination()); + result.startingBalance = this._fromXDRAmount(attrs.startingBalance()); + break; + } + case 'payment': + { + result.type = 'payment'; + result.destination = encodeMuxedAccountToAddress(attrs.destination()); + result.asset = Asset.fromOperation(attrs.asset()); + result.amount = this._fromXDRAmount(attrs.amount()); + break; + } + case 'pathPaymentStrictReceive': + { + result.type = 'pathPaymentStrictReceive'; + result.sendAsset = Asset.fromOperation(attrs.sendAsset()); + result.sendMax = this._fromXDRAmount(attrs.sendMax()); + result.destination = encodeMuxedAccountToAddress(attrs.destination()); + result.destAsset = Asset.fromOperation(attrs.destAsset()); + result.destAmount = this._fromXDRAmount(attrs.destAmount()); + result.path = []; + var path = attrs.path(); + + // note that Object.values isn't supported by node 6! + Object.keys(path).forEach(function (pathKey) { + result.path.push(Asset.fromOperation(path[pathKey])); + }); + break; + } + case 'pathPaymentStrictSend': + { + result.type = 'pathPaymentStrictSend'; + result.sendAsset = Asset.fromOperation(attrs.sendAsset()); + result.sendAmount = this._fromXDRAmount(attrs.sendAmount()); + result.destination = encodeMuxedAccountToAddress(attrs.destination()); + result.destAsset = Asset.fromOperation(attrs.destAsset()); + result.destMin = this._fromXDRAmount(attrs.destMin()); + result.path = []; + var _path = attrs.path(); + + // note that Object.values isn't supported by node 6! + Object.keys(_path).forEach(function (pathKey) { + result.path.push(Asset.fromOperation(_path[pathKey])); + }); + break; + } + case 'changeTrust': + { + result.type = 'changeTrust'; + switch (attrs.line()["switch"]()) { + case src_xdr.AssetType.assetTypePoolShare(): + result.line = LiquidityPoolAsset.fromOperation(attrs.line()); + break; + default: + result.line = Asset.fromOperation(attrs.line()); + break; + } + result.limit = this._fromXDRAmount(attrs.limit()); + break; + } + case 'allowTrust': + { + result.type = 'allowTrust'; + result.trustor = accountIdtoAddress(attrs.trustor()); + result.assetCode = attrs.asset().value().toString(); + result.assetCode = trimEnd(result.assetCode, '\0'); + result.authorize = attrs.authorize(); + break; + } + case 'setOptions': + { + result.type = 'setOptions'; + if (attrs.inflationDest()) { + result.inflationDest = accountIdtoAddress(attrs.inflationDest()); + } + result.clearFlags = attrs.clearFlags(); + result.setFlags = attrs.setFlags(); + result.masterWeight = attrs.masterWeight(); + result.lowThreshold = attrs.lowThreshold(); + result.medThreshold = attrs.medThreshold(); + result.highThreshold = attrs.highThreshold(); + // home_domain is checked by iscntrl in stellar-core + result.homeDomain = attrs.homeDomain() !== undefined ? attrs.homeDomain().toString('ascii') : undefined; + if (attrs.signer()) { + var signer = {}; + var arm = attrs.signer().key().arm(); + if (arm === 'ed25519') { + signer.ed25519PublicKey = accountIdtoAddress(attrs.signer().key()); + } else if (arm === 'preAuthTx') { + signer.preAuthTx = attrs.signer().key().preAuthTx(); + } else if (arm === 'hashX') { + signer.sha256Hash = attrs.signer().key().hashX(); + } else if (arm === 'ed25519SignedPayload') { + var signedPayload = attrs.signer().key().ed25519SignedPayload(); + signer.ed25519SignedPayload = StrKey.encodeSignedPayload(signedPayload.toXDR()); + } + signer.weight = attrs.signer().weight(); + result.signer = signer; + } + break; + } + // the next case intentionally falls through! + case 'manageOffer': + case 'manageSellOffer': + { + result.type = 'manageSellOffer'; + result.selling = Asset.fromOperation(attrs.selling()); + result.buying = Asset.fromOperation(attrs.buying()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.price = this._fromXDRPrice(attrs.price()); + result.offerId = attrs.offerId().toString(); + break; + } + case 'manageBuyOffer': + { + result.type = 'manageBuyOffer'; + result.selling = Asset.fromOperation(attrs.selling()); + result.buying = Asset.fromOperation(attrs.buying()); + result.buyAmount = this._fromXDRAmount(attrs.buyAmount()); + result.price = this._fromXDRPrice(attrs.price()); + result.offerId = attrs.offerId().toString(); + break; + } + // the next case intentionally falls through! + case 'createPassiveOffer': + case 'createPassiveSellOffer': + { + result.type = 'createPassiveSellOffer'; + result.selling = Asset.fromOperation(attrs.selling()); + result.buying = Asset.fromOperation(attrs.buying()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.price = this._fromXDRPrice(attrs.price()); + break; + } + case 'accountMerge': + { + result.type = 'accountMerge'; + result.destination = encodeMuxedAccountToAddress(attrs); + break; + } + case 'manageData': + { + result.type = 'manageData'; + // manage_data.name is checked by iscntrl in stellar-core + result.name = attrs.dataName().toString('ascii'); + result.value = attrs.dataValue(); + break; + } + case 'inflation': + { + result.type = 'inflation'; + break; + } + case 'bumpSequence': + { + result.type = 'bumpSequence'; + result.bumpTo = attrs.bumpTo().toString(); + break; + } + case 'createClaimableBalance': + { + result.type = 'createClaimableBalance'; + result.asset = Asset.fromOperation(attrs.asset()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.claimants = []; + attrs.claimants().forEach(function (claimant) { + result.claimants.push(Claimant.fromXDR(claimant)); + }); + break; + } + case 'claimClaimableBalance': + { + result.type = 'claimClaimableBalance'; + result.balanceId = attrs.toXDR('hex'); + break; + } + case 'beginSponsoringFutureReserves': + { + result.type = 'beginSponsoringFutureReserves'; + result.sponsoredId = accountIdtoAddress(attrs.sponsoredId()); + break; + } + case 'endSponsoringFutureReserves': + { + result.type = 'endSponsoringFutureReserves'; + break; + } + case 'revokeSponsorship': + { + extractRevokeSponshipDetails(attrs, result); + break; + } + case 'clawback': + { + result.type = 'clawback'; + result.amount = this._fromXDRAmount(attrs.amount()); + result.from = encodeMuxedAccountToAddress(attrs.from()); + result.asset = Asset.fromOperation(attrs.asset()); + break; + } + case 'clawbackClaimableBalance': + { + result.type = 'clawbackClaimableBalance'; + result.balanceId = attrs.toXDR('hex'); + break; + } + case 'setTrustLineFlags': + { + result.type = 'setTrustLineFlags'; + result.asset = Asset.fromOperation(attrs.asset()); + result.trustor = accountIdtoAddress(attrs.trustor()); + + // Convert from the integer-bitwised flag into a sensible object that + // indicates true/false for each flag that's on/off. + var clears = attrs.clearFlags(); + var sets = attrs.setFlags(); + var mapping = { + authorized: src_xdr.TrustLineFlags.authorizedFlag(), + authorizedToMaintainLiabilities: src_xdr.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(), + clawbackEnabled: src_xdr.TrustLineFlags.trustlineClawbackEnabledFlag() + }; + var getFlagValue = function getFlagValue(key) { + var bit = mapping[key].value; + if (sets & bit) { + return true; + } + if (clears & bit) { + return false; + } + return undefined; + }; + result.flags = {}; + Object.keys(mapping).forEach(function (flagName) { + result.flags[flagName] = getFlagValue(flagName); + }); + break; + } + case 'liquidityPoolDeposit': + { + result.type = 'liquidityPoolDeposit'; + result.liquidityPoolId = attrs.liquidityPoolId().toString('hex'); + result.maxAmountA = this._fromXDRAmount(attrs.maxAmountA()); + result.maxAmountB = this._fromXDRAmount(attrs.maxAmountB()); + result.minPrice = this._fromXDRPrice(attrs.minPrice()); + result.maxPrice = this._fromXDRPrice(attrs.maxPrice()); + break; + } + case 'liquidityPoolWithdraw': + { + result.type = 'liquidityPoolWithdraw'; + result.liquidityPoolId = attrs.liquidityPoolId().toString('hex'); + result.amount = this._fromXDRAmount(attrs.amount()); + result.minAmountA = this._fromXDRAmount(attrs.minAmountA()); + result.minAmountB = this._fromXDRAmount(attrs.minAmountB()); + break; + } + case 'invokeHostFunction': + { + var _attrs$auth; + result.type = 'invokeHostFunction'; + result.func = attrs.hostFunction(); + result.auth = (_attrs$auth = attrs.auth()) !== null && _attrs$auth !== void 0 ? _attrs$auth : []; + break; + } + case 'extendFootprintTtl': + { + result.type = 'extendFootprintTtl'; + result.extendTo = attrs.extendTo(); + break; + } + case 'restoreFootprint': + { + result.type = 'restoreFootprint'; + break; + } + default: + { + throw new Error("Unknown operation: ".concat(operationName)); + } + } + return result; + } + + /** + * Validates that a given amount is possible for a Stellar asset. + * + * Specifically, this means that the amount is well, a valid number, but also + * that it is within the int64 range and has no more than 7 decimal levels of + * precision. + * + * Note that while smart contracts allow larger amounts, this is oriented + * towards validating the standard Stellar operations. + * + * @param {string} value the amount to validate + * @param {boolean} allowZero optionally, whether or not zero is valid (default: no) + * + * @returns {boolean} + */ + }, { + key: "isValidAmount", + value: function isValidAmount(value) { + var allowZero = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (typeof value !== 'string') { + return false; + } + var amount; + try { + amount = new util_bignumber(value); + } catch (e) { + return false; + } + if ( + // == 0 + !allowZero && amount.isZero() || + // < 0 + amount.isNegative() || + // > Max value + amount.times(ONE).gt(new util_bignumber(operation_MAX_INT64).toString()) || + // Decimal places (max 7) + amount.decimalPlaces() > 7 || + // NaN or Infinity + amount.isNaN() || !amount.isFinite()) { + return false; + } + return true; + } + }, { + key: "constructAmountRequirementsError", + value: function constructAmountRequirementsError(arg) { + return "".concat(arg, " argument must be of type String, represent a positive number and have at most 7 digits after the decimal"); + } + + /** + * Returns value converted to uint32 value or undefined. + * If `value` is not `Number`, `String` or `Undefined` then throws an error. + * Used in {@link Operation.setOptions}. + * @private + * @param {string} name Name of the property (used in error message only) + * @param {*} value Value to check + * @param {function(value, name)} isValidFunction Function to check other constraints (the argument will be a `Number`) + * @returns {undefined|Number} + */ + }, { + key: "_checkUnsignedIntValue", + value: function _checkUnsignedIntValue(name, value) { + var isValidFunction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + if (typeof value === 'undefined') { + return undefined; + } + if (typeof value === 'string') { + value = parseFloat(value); + } + switch (true) { + case typeof value !== 'number' || !Number.isFinite(value) || value % 1 !== 0: + throw new Error("".concat(name, " value is invalid")); + case value < 0: + throw new Error("".concat(name, " value must be unsigned")); + case !isValidFunction || isValidFunction && isValidFunction(value, name): + return value; + default: + throw new Error("".concat(name, " value is invalid")); + } + } + /** + * @private + * @param {string|BigNumber} value Value + * @returns {Hyper} XDR amount + */ + }, { + key: "_toXDRAmount", + value: function _toXDRAmount(value) { + var amount = new util_bignumber(value).times(ONE); + return xdr.Hyper.fromString(amount.toString()); + } + + /** + * @private + * @param {string|BigNumber} value XDR amount + * @returns {BigNumber} Number + */ + }, { + key: "_fromXDRAmount", + value: function _fromXDRAmount(value) { + return new util_bignumber(value).div(ONE).toFixed(7); + } + + /** + * @private + * @param {object} price Price object + * @param {function} price.n numerator function that returns a value + * @param {function} price.d denominator function that returns a value + * @returns {BigNumber} Big string + */ + }, { + key: "_fromXDRPrice", + value: function _fromXDRPrice(price) { + var n = new util_bignumber(price.n()); + return n.div(new util_bignumber(price.d())).toString(); + } + + /** + * @private + * @param {object} price Price object + * @param {function} price.n numerator function that returns a value + * @param {function} price.d denominator function that returns a value + * @returns {object} XDR price object + */ + }, { + key: "_toXDRPrice", + value: function _toXDRPrice(price) { + var xdrObject; + if (price.n && price.d) { + xdrObject = new src_xdr.Price(price); + } else { + var approx = best_r(price); + xdrObject = new src_xdr.Price({ + n: parseInt(approx[0], 10), + d: parseInt(approx[1], 10) + }); + } + if (xdrObject.n() < 0 || xdrObject.d() < 0) { + throw new Error('price must be positive'); + } + return xdrObject; + } + }]); +}(); +function extractRevokeSponshipDetails(attrs, result) { + switch (attrs["switch"]().name) { + case 'revokeSponsorshipLedgerEntry': + { + var ledgerKey = attrs.ledgerKey(); + switch (ledgerKey["switch"]().name) { + case src_xdr.LedgerEntryType.account().name: + { + result.type = 'revokeAccountSponsorship'; + result.account = accountIdtoAddress(ledgerKey.account().accountId()); + break; + } + case src_xdr.LedgerEntryType.trustline().name: + { + result.type = 'revokeTrustlineSponsorship'; + result.account = accountIdtoAddress(ledgerKey.trustLine().accountId()); + var xdrAsset = ledgerKey.trustLine().asset(); + switch (xdrAsset["switch"]()) { + case src_xdr.AssetType.assetTypePoolShare(): + result.asset = LiquidityPoolId.fromOperation(xdrAsset); + break; + default: + result.asset = Asset.fromOperation(xdrAsset); + break; + } + break; + } + case src_xdr.LedgerEntryType.offer().name: + { + result.type = 'revokeOfferSponsorship'; + result.seller = accountIdtoAddress(ledgerKey.offer().sellerId()); + result.offerId = ledgerKey.offer().offerId().toString(); + break; + } + case src_xdr.LedgerEntryType.data().name: + { + result.type = 'revokeDataSponsorship'; + result.account = accountIdtoAddress(ledgerKey.data().accountId()); + result.name = ledgerKey.data().dataName().toString('ascii'); + break; + } + case src_xdr.LedgerEntryType.claimableBalance().name: + { + result.type = 'revokeClaimableBalanceSponsorship'; + result.balanceId = ledgerKey.claimableBalance().balanceId().toXDR('hex'); + break; + } + case src_xdr.LedgerEntryType.liquidityPool().name: + { + result.type = 'revokeLiquidityPoolSponsorship'; + result.liquidityPoolId = ledgerKey.liquidityPool().liquidityPoolId().toString('hex'); + break; + } + default: + { + throw new Error("Unknown ledgerKey: ".concat(attrs["switch"]().name)); + } + } + break; + } + case 'revokeSponsorshipSigner': + { + result.type = 'revokeSignerSponsorship'; + result.account = accountIdtoAddress(attrs.signer().accountId()); + result.signer = convertXDRSignerKeyToObject(attrs.signer().signerKey()); + break; + } + default: + { + throw new Error("Unknown revokeSponsorship: ".concat(attrs["switch"]().name)); + } + } +} +function convertXDRSignerKeyToObject(signerKey) { + var attrs = {}; + switch (signerKey["switch"]().name) { + case src_xdr.SignerKeyType.signerKeyTypeEd25519().name: + { + attrs.ed25519PublicKey = StrKey.encodeEd25519PublicKey(signerKey.ed25519()); + break; + } + case src_xdr.SignerKeyType.signerKeyTypePreAuthTx().name: + { + attrs.preAuthTx = signerKey.preAuthTx().toString('hex'); + break; + } + case src_xdr.SignerKeyType.signerKeyTypeHashX().name: + { + attrs.sha256Hash = signerKey.hashX().toString('hex'); + break; + } + default: + { + throw new Error("Unknown signerKey: ".concat(signerKey["switch"]().name)); + } + } + return attrs; +} +function accountIdtoAddress(accountId) { + return StrKey.encodeEd25519PublicKey(accountId.ed25519()); +} + +// Attach all imported operations as static methods on the Operation class +Operation.accountMerge = accountMerge; +Operation.allowTrust = allowTrust; +Operation.bumpSequence = bumpSequence; +Operation.changeTrust = changeTrust; +Operation.createAccount = createAccount; +Operation.createClaimableBalance = createClaimableBalance; +Operation.claimClaimableBalance = claimClaimableBalance; +Operation.clawbackClaimableBalance = clawbackClaimableBalance; +Operation.createPassiveSellOffer = createPassiveSellOffer; +Operation.inflation = inflation; +Operation.manageData = manageData; +Operation.manageSellOffer = manageSellOffer; +Operation.manageBuyOffer = manageBuyOffer; +Operation.pathPaymentStrictReceive = pathPaymentStrictReceive; +Operation.pathPaymentStrictSend = pathPaymentStrictSend; +Operation.payment = payment; +Operation.setOptions = setOptions; +Operation.beginSponsoringFutureReserves = beginSponsoringFutureReserves; +Operation.endSponsoringFutureReserves = endSponsoringFutureReserves; +Operation.revokeAccountSponsorship = revokeAccountSponsorship; +Operation.revokeTrustlineSponsorship = revokeTrustlineSponsorship; +Operation.revokeOfferSponsorship = revokeOfferSponsorship; +Operation.revokeDataSponsorship = revokeDataSponsorship; +Operation.revokeClaimableBalanceSponsorship = revokeClaimableBalanceSponsorship; +Operation.revokeLiquidityPoolSponsorship = revokeLiquidityPoolSponsorship; +Operation.revokeSignerSponsorship = revokeSignerSponsorship; +Operation.clawback = clawback; +Operation.setTrustLineFlags = setTrustLineFlags; +Operation.liquidityPoolDeposit = liquidityPoolDeposit; +Operation.liquidityPoolWithdraw = liquidityPoolWithdraw; +Operation.invokeHostFunction = invokeHostFunction; +Operation.extendFootprintTtl = extendFootprintTtl; +Operation.restoreFootprint = restoreFootprint; + +// these are not `xdr.Operation`s directly, but are proxies for complex but +// common versions of `Operation.invokeHostFunction` +Operation.createStellarAssetContract = createStellarAssetContract; +Operation.invokeContractFunction = invokeContractFunction; +Operation.createCustomContract = createCustomContract; +Operation.uploadContractWasm = uploadContractWasm; +;// ./src/memo.js +/* provided dependency */ var memo_Buffer = __webpack_require__(3626)["A"]; +function memo_typeof(o) { "@babel/helpers - typeof"; return memo_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, memo_typeof(o); } +function memo_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function memo_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, memo_toPropertyKey(o.key), o); } } +function memo_createClass(e, r, t) { return r && memo_defineProperties(e.prototype, r), t && memo_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function memo_toPropertyKey(t) { var i = memo_toPrimitive(t, "string"); return "symbol" == memo_typeof(i) ? i : i + ""; } +function memo_toPrimitive(t, r) { if ("object" != memo_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != memo_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + +/** + * Type of {@link Memo}. + */ +var MemoNone = 'none'; +/** + * Type of {@link Memo}. + */ +var MemoID = 'id'; +/** + * Type of {@link Memo}. + */ +var MemoText = 'text'; +/** + * Type of {@link Memo}. + */ +var MemoHash = 'hash'; +/** + * Type of {@link Memo}. + */ +var MemoReturn = 'return'; + +/** + * `Memo` represents memos attached to transactions. + * + * @param {string} type - `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn` + * @param {*} value - `string` for `MemoID`, `MemoText`, buffer of hex string for `MemoHash` or `MemoReturn` + * @see [Transactions concept](https://developers.stellar.org/docs/glossary/transactions/) + * @class Memo + */ +var Memo = /*#__PURE__*/function () { + function Memo(type) { + var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + memo_classCallCheck(this, Memo); + this._type = type; + this._value = value; + switch (this._type) { + case MemoNone: + break; + case MemoID: + Memo._validateIdValue(value); + break; + case MemoText: + Memo._validateTextValue(value); + break; + case MemoHash: + case MemoReturn: + Memo._validateHashValue(value); + // We want MemoHash and MemoReturn to have Buffer as a value + if (typeof value === 'string') { + this._value = memo_Buffer.from(value, 'hex'); + } + break; + default: + throw new Error('Invalid memo type'); + } + } + + /** + * Contains memo type: `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn` + */ + return memo_createClass(Memo, [{ + key: "type", + get: function get() { + return this._type; + }, + set: function set(type) { + throw new Error('Memo is immutable'); + } + + /** + * Contains memo value: + * * `null` for `MemoNone`, + * * `string` for `MemoID`, + * * `Buffer` for `MemoText` after decoding using `fromXDRObject`, original value otherwise, + * * `Buffer` for `MemoHash`, `MemoReturn`. + */ + }, { + key: "value", + get: function get() { + switch (this._type) { + case MemoNone: + return null; + case MemoID: + case MemoText: + return this._value; + case MemoHash: + case MemoReturn: + return memo_Buffer.from(this._value); + default: + throw new Error('Invalid memo type'); + } + }, + set: function set(value) { + throw new Error('Memo is immutable'); + } + }, { + key: "toXDRObject", + value: + /** + * Returns XDR memo object. + * @returns {xdr.Memo} + */ + function toXDRObject() { + switch (this._type) { + case MemoNone: + return src_xdr.Memo.memoNone(); + case MemoID: + return src_xdr.Memo.memoId(xdr.UnsignedHyper.fromString(this._value)); + case MemoText: + return src_xdr.Memo.memoText(this._value); + case MemoHash: + return src_xdr.Memo.memoHash(this._value); + case MemoReturn: + return src_xdr.Memo.memoReturn(this._value); + default: + return null; + } + } + + /** + * Returns {@link Memo} from XDR memo object. + * @param {xdr.Memo} object XDR memo object + * @returns {Memo} + */ + }], [{ + key: "_validateIdValue", + value: function _validateIdValue(value) { + var error = new Error("Expects a int64 as a string. Got ".concat(value)); + if (typeof value !== 'string') { + throw error; + } + var number; + try { + number = new util_bignumber(value); + } catch (e) { + throw error; + } + + // Infinity + if (!number.isFinite()) { + throw error; + } + + // NaN + if (number.isNaN()) { + throw error; + } + } + }, { + key: "_validateTextValue", + value: function _validateTextValue(value) { + if (!src_xdr.Memo.armTypeForArm('text').isValid(value)) { + throw new Error('Expects string, array or buffer, max 28 bytes'); + } + } + }, { + key: "_validateHashValue", + value: function _validateHashValue(value) { + var error = new Error("Expects a 32 byte hash value or hex encoded string. Got ".concat(value)); + if (value === null || typeof value === 'undefined') { + throw error; + } + var valueBuffer; + if (typeof value === 'string') { + if (!/^[0-9A-Fa-f]{64}$/g.test(value)) { + throw error; + } + valueBuffer = memo_Buffer.from(value, 'hex'); + } else if (memo_Buffer.isBuffer(value)) { + valueBuffer = memo_Buffer.from(value); + } else { + throw error; + } + if (!valueBuffer.length || valueBuffer.length !== 32) { + throw error; + } + } + + /** + * Returns an empty memo (`MemoNone`). + * @returns {Memo} + */ + }, { + key: "none", + value: function none() { + return new Memo(MemoNone); + } + + /** + * Creates and returns a `MemoText` memo. + * @param {string} text - memo text + * @returns {Memo} + */ + }, { + key: "text", + value: function text(_text) { + return new Memo(MemoText, _text); + } + + /** + * Creates and returns a `MemoID` memo. + * @param {string} id - 64-bit number represented as a string + * @returns {Memo} + */ + }, { + key: "id", + value: function id(_id) { + return new Memo(MemoID, _id); + } + + /** + * Creates and returns a `MemoHash` memo. + * @param {array|string} hash - 32 byte hash or hex encoded string + * @returns {Memo} + */ + }, { + key: "hash", + value: function hash(_hash) { + return new Memo(MemoHash, _hash); + } + + /** + * Creates and returns a `MemoReturn` memo. + * @param {array|string} hash - 32 byte hash or hex encoded string + * @returns {Memo} + */ + }, { + key: "return", + value: function _return(hash) { + return new Memo(MemoReturn, hash); + } + }, { + key: "fromXDRObject", + value: function fromXDRObject(object) { + switch (object.arm()) { + case 'id': + return Memo.id(object.value().toString()); + case 'text': + return Memo.text(object.value()); + case 'hash': + return Memo.hash(object.value()); + case 'retHash': + return Memo["return"](object.value()); + default: + break; + } + if (typeof object.value() === 'undefined') { + return Memo.none(); + } + throw new Error('Unknown type'); + } + }]); +}(); +;// ./src/transaction.js +/* provided dependency */ var transaction_Buffer = __webpack_require__(3626)["A"]; +function transaction_typeof(o) { "@babel/helpers - typeof"; return transaction_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, transaction_typeof(o); } +function transaction_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function transaction_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, transaction_toPropertyKey(o.key), o); } } +function transaction_createClass(e, r, t) { return r && transaction_defineProperties(e.prototype, r), t && transaction_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function transaction_toPropertyKey(t) { var i = transaction_toPrimitive(t, "string"); return "symbol" == transaction_typeof(i) ? i : i + ""; } +function transaction_toPrimitive(t, r) { if ("object" != transaction_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != transaction_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == transaction_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } + + + + + + + + +/** + * Use {@link TransactionBuilder} to build a transaction object. If you have an + * object or base64-encoded string of the transaction envelope XDR, use {@link + * TransactionBuilder.fromXDR}. + * + * Once a Transaction has been created, its attributes and operations should not + * be changed. You should only add signatures (using {@link Transaction#sign}) + * to a Transaction object before submitting to the network or forwarding on to + * additional signers. + * + * @constructor + * + * @param {string|xdr.TransactionEnvelope} envelope - transaction envelope + * object or base64 encoded string + * @param {string} [networkPassphrase] - passphrase of the target stellar + * network (e.g. "Public Global Stellar Network ; September 2015") + * + * @extends TransactionBase + */ +var Transaction = /*#__PURE__*/function (_TransactionBase) { + function Transaction(envelope, networkPassphrase) { + var _this; + transaction_classCallCheck(this, Transaction); + if (typeof envelope === 'string') { + var buffer = transaction_Buffer.from(envelope, 'base64'); + envelope = src_xdr.TransactionEnvelope.fromXDR(buffer); + } + var envelopeType = envelope["switch"](); + if (!(envelopeType === src_xdr.EnvelopeType.envelopeTypeTxV0() || envelopeType === src_xdr.EnvelopeType.envelopeTypeTx())) { + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ".concat(envelopeType.name, ".")); + } + var txEnvelope = envelope.value(); + var tx = txEnvelope.tx(); + var fee = tx.fee().toString(); + var signatures = (txEnvelope.signatures() || []).slice(); + _this = _callSuper(this, Transaction, [tx, signatures, fee, networkPassphrase]); + _this._envelopeType = envelopeType; + _this._memo = tx.memo(); + _this._sequence = tx.seqNum().toString(); + switch (_this._envelopeType) { + case src_xdr.EnvelopeType.envelopeTypeTxV0(): + _this._source = StrKey.encodeEd25519PublicKey(_this.tx.sourceAccountEd25519()); + break; + default: + _this._source = encodeMuxedAccountToAddress(_this.tx.sourceAccount()); + break; + } + var cond = null; + var timeBounds = null; + switch (_this._envelopeType) { + case src_xdr.EnvelopeType.envelopeTypeTxV0(): + timeBounds = tx.timeBounds(); + break; + case src_xdr.EnvelopeType.envelopeTypeTx(): + switch (tx.cond()["switch"]()) { + case src_xdr.PreconditionType.precondTime(): + timeBounds = tx.cond().timeBounds(); + break; + case src_xdr.PreconditionType.precondV2(): + cond = tx.cond().v2(); + timeBounds = cond.timeBounds(); + break; + default: + break; + } + break; + default: + break; + } + if (timeBounds) { + _this._timeBounds = { + minTime: timeBounds.minTime().toString(), + maxTime: timeBounds.maxTime().toString() + }; + } + if (cond) { + var ledgerBounds = cond.ledgerBounds(); + if (ledgerBounds) { + _this._ledgerBounds = { + minLedger: ledgerBounds.minLedger(), + maxLedger: ledgerBounds.maxLedger() + }; + } + var minSeq = cond.minSeqNum(); + if (minSeq) { + _this._minAccountSequence = minSeq.toString(); + } + _this._minAccountSequenceAge = cond.minSeqAge(); + _this._minAccountSequenceLedgerGap = cond.minSeqLedgerGap(); + _this._extraSigners = cond.extraSigners(); + } + var operations = tx.operations() || []; + _this._operations = operations.map(function (op) { + return Operation.fromXDRObject(op); + }); + return _this; + } + + /** + * @type {object} + * @property {string} 64 bit unix timestamp + * @property {string} 64 bit unix timestamp + * @readonly + */ + _inherits(Transaction, _TransactionBase); + return transaction_createClass(Transaction, [{ + key: "timeBounds", + get: function get() { + return this._timeBounds; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {object} + * @property {number} minLedger - smallest ledger bound (uint32) + * @property {number} maxLedger - largest ledger bound (or 0 for inf) + * @readonly + */ + }, { + key: "ledgerBounds", + get: function get() { + return this._ledgerBounds; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 64 bit account sequence + * @readonly + * @type {string} + */ + }, { + key: "minAccountSequence", + get: function get() { + return this._minAccountSequence; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 64 bit number of seconds + * @type {number} + * @readonly + */ + }, { + key: "minAccountSequenceAge", + get: function get() { + return this._minAccountSequenceAge; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 32 bit number of ledgers + * @type {number} + * @readonly + */ + }, { + key: "minAccountSequenceLedgerGap", + get: function get() { + return this._minAccountSequenceLedgerGap; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * array of extra signers ({@link StrKey}s) + * @type {string[]} + * @readonly + */ + }, { + key: "extraSigners", + get: function get() { + return this._extraSigners; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "sequence", + get: function get() { + return this._sequence; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "source", + get: function get() { + return this._source; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {Array.} + * @readonly + */ + }, { + key: "operations", + get: function get() { + return this._operations; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "memo", + get: function get() { + return Memo.fromXDRObject(this._memo); + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * Returns the "signature base" of this transaction, which is the value + * that, when hashed, should be signed to create a signature that + * validators on the Stellar Network will accept. + * + * It is composed of a 4 prefix bytes followed by the xdr-encoded form + * of this transaction. + * @returns {Buffer} + */ + }, { + key: "signatureBase", + value: function signatureBase() { + var tx = this.tx; + + // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // we need a Transaction to generate the signature base + if (this._envelopeType === src_xdr.EnvelopeType.envelopeTypeTxV0()) { + tx = src_xdr.Transaction.fromXDR(transaction_Buffer.concat([ + // TransactionV0 is a transaction with the AccountID discriminant + // stripped off, we need to put it back to build a valid transaction + // which we can use to build a TransactionSignaturePayloadTaggedTransaction + src_xdr.PublicKeyType.publicKeyTypeEd25519().toXDR(), tx.toXDR()])); + } + var taggedTransaction = new src_xdr.TransactionSignaturePayloadTaggedTransaction.envelopeTypeTx(tx); + var txSignature = new src_xdr.TransactionSignaturePayload({ + networkId: src_xdr.Hash.fromXDR(hashing_hash(this.networkPassphrase)), + taggedTransaction: taggedTransaction + }); + return txSignature.toXDR(); + } + + /** + * To envelope returns a xdr.TransactionEnvelope which can be submitted to the network. + * @returns {xdr.TransactionEnvelope} + */ + }, { + key: "toEnvelope", + value: function toEnvelope() { + var rawTx = this.tx.toXDR(); + var signatures = this.signatures.slice(); // make a copy of the signatures + + var envelope; + switch (this._envelopeType) { + case src_xdr.EnvelopeType.envelopeTypeTxV0(): + envelope = new src_xdr.TransactionEnvelope.envelopeTypeTxV0(new src_xdr.TransactionV0Envelope({ + tx: src_xdr.TransactionV0.fromXDR(rawTx), + // make a copy of tx + signatures: signatures + })); + break; + case src_xdr.EnvelopeType.envelopeTypeTx(): + envelope = new src_xdr.TransactionEnvelope.envelopeTypeTx(new src_xdr.TransactionV1Envelope({ + tx: src_xdr.Transaction.fromXDR(rawTx), + // make a copy of tx + signatures: signatures + })); + break; + default: + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ".concat(this._envelopeType.name, ".")); + } + return envelope; + } + + /** + * Calculate the claimable balance ID for an operation within the transaction. + * + * @param {integer} opIndex the index of the CreateClaimableBalance op + * @returns {string} a hex string representing the claimable balance ID + * + * @throws {RangeError} for invalid `opIndex` value + * @throws {TypeError} if op at `opIndex` is not `CreateClaimableBalance` + * @throws for general XDR un/marshalling failures + * + * @see https://github.com/stellar/go/blob/d712346e61e288d450b0c08038c158f8848cc3e4/txnbuild/transaction.go#L392-L435 + * + */ + }, { + key: "getClaimableBalanceId", + value: function getClaimableBalanceId(opIndex) { + // Validate and then extract the operation from the transaction. + if (!Number.isInteger(opIndex) || opIndex < 0 || opIndex >= this.operations.length) { + throw new RangeError('invalid operation index'); + } + var op = this.operations[opIndex]; + try { + op = Operation.createClaimableBalance(op); + } catch (err) { + throw new TypeError("expected createClaimableBalance, got ".concat(op.type, ": ").concat(err)); + } + + // Always use the transaction's *unmuxed* source. + var account = StrKey.decodeEd25519PublicKey(extractBaseAddress(this.source)); + var operationId = src_xdr.HashIdPreimage.envelopeTypeOpId(new src_xdr.HashIdPreimageOperationId({ + sourceAccount: src_xdr.AccountId.publicKeyTypeEd25519(account), + seqNum: src_xdr.SequenceNumber.fromString(this.sequence), + opNum: opIndex + })); + var opIdHash = hashing_hash(operationId.toXDR('raw')); + var balanceId = src_xdr.ClaimableBalanceId.claimableBalanceIdTypeV0(opIdHash); + return balanceId.toXDR('hex'); + } + }]); +}(TransactionBase); +;// ./src/fee_bump_transaction.js +/* provided dependency */ var fee_bump_transaction_Buffer = __webpack_require__(3626)["A"]; +function fee_bump_transaction_typeof(o) { "@babel/helpers - typeof"; return fee_bump_transaction_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, fee_bump_transaction_typeof(o); } +function fee_bump_transaction_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function fee_bump_transaction_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, fee_bump_transaction_toPropertyKey(o.key), o); } } +function fee_bump_transaction_createClass(e, r, t) { return r && fee_bump_transaction_defineProperties(e.prototype, r), t && fee_bump_transaction_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function fee_bump_transaction_toPropertyKey(t) { var i = fee_bump_transaction_toPrimitive(t, "string"); return "symbol" == fee_bump_transaction_typeof(i) ? i : i + ""; } +function fee_bump_transaction_toPrimitive(t, r) { if ("object" != fee_bump_transaction_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != fee_bump_transaction_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function fee_bump_transaction_callSuper(t, o, e) { return o = fee_bump_transaction_getPrototypeOf(o), fee_bump_transaction_possibleConstructorReturn(t, fee_bump_transaction_isNativeReflectConstruct() ? Reflect.construct(o, e || [], fee_bump_transaction_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function fee_bump_transaction_possibleConstructorReturn(t, e) { if (e && ("object" == fee_bump_transaction_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return fee_bump_transaction_assertThisInitialized(t); } +function fee_bump_transaction_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function fee_bump_transaction_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (fee_bump_transaction_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function fee_bump_transaction_getPrototypeOf(t) { return fee_bump_transaction_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, fee_bump_transaction_getPrototypeOf(t); } +function fee_bump_transaction_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && fee_bump_transaction_setPrototypeOf(t, e); } +function fee_bump_transaction_setPrototypeOf(t, e) { return fee_bump_transaction_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, fee_bump_transaction_setPrototypeOf(t, e); } + + + + + + +/** + * Use {@link TransactionBuilder.buildFeeBumpTransaction} to build a + * FeeBumpTransaction object. If you have an object or base64-encoded string of + * the transaction envelope XDR use {@link TransactionBuilder.fromXDR}. + * + * Once a {@link FeeBumpTransaction} has been created, its attributes and operations + * should not be changed. You should only add signatures (using {@link FeeBumpTransaction#sign}) before + * submitting to the network or forwarding on to additional signers. + * + * @param {string|xdr.TransactionEnvelope} envelope - transaction envelope + * object or base64 encoded string. + * @param {string} networkPassphrase - passphrase of the target Stellar network + * (e.g. "Public Global Stellar Network ; September 2015"). + * + * @extends TransactionBase + */ +var FeeBumpTransaction = /*#__PURE__*/function (_TransactionBase) { + function FeeBumpTransaction(envelope, networkPassphrase) { + var _this; + fee_bump_transaction_classCallCheck(this, FeeBumpTransaction); + if (typeof envelope === 'string') { + var buffer = fee_bump_transaction_Buffer.from(envelope, 'base64'); + envelope = src_xdr.TransactionEnvelope.fromXDR(buffer); + } + var envelopeType = envelope["switch"](); + if (envelopeType !== src_xdr.EnvelopeType.envelopeTypeTxFeeBump()) { + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxFeeBump but received an ".concat(envelopeType.name, ".")); + } + var txEnvelope = envelope.value(); + var tx = txEnvelope.tx(); + var fee = tx.fee().toString(); + // clone signatures + var signatures = (txEnvelope.signatures() || []).slice(); + _this = fee_bump_transaction_callSuper(this, FeeBumpTransaction, [tx, signatures, fee, networkPassphrase]); + var innerTxEnvelope = src_xdr.TransactionEnvelope.envelopeTypeTx(tx.innerTx().v1()); + _this._feeSource = encodeMuxedAccountToAddress(_this.tx.feeSource()); + _this._innerTransaction = new Transaction(innerTxEnvelope, networkPassphrase); + return _this; + } + + /** + * @type {Transaction} + * @readonly + */ + fee_bump_transaction_inherits(FeeBumpTransaction, _TransactionBase); + return fee_bump_transaction_createClass(FeeBumpTransaction, [{ + key: "innerTransaction", + get: function get() { + return this._innerTransaction; + } + + /** + * @type {Operation[]} + * @readonly + */ + }, { + key: "operations", + get: function get() { + return this._innerTransaction.operations; + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "feeSource", + get: function get() { + return this._feeSource; + } + + /** + * Returns the "signature base" of this transaction, which is the value + * that, when hashed, should be signed to create a signature that + * validators on the Stellar Network will accept. + * + * It is composed of a 4 prefix bytes followed by the xdr-encoded form + * of this transaction. + * @returns {Buffer} + */ + }, { + key: "signatureBase", + value: function signatureBase() { + var taggedTransaction = new src_xdr.TransactionSignaturePayloadTaggedTransaction.envelopeTypeTxFeeBump(this.tx); + var txSignature = new src_xdr.TransactionSignaturePayload({ + networkId: src_xdr.Hash.fromXDR(hashing_hash(this.networkPassphrase)), + taggedTransaction: taggedTransaction + }); + return txSignature.toXDR(); + } + + /** + * To envelope returns a xdr.TransactionEnvelope which can be submitted to the network. + * @returns {xdr.TransactionEnvelope} + */ + }, { + key: "toEnvelope", + value: function toEnvelope() { + var envelope = new src_xdr.FeeBumpTransactionEnvelope({ + tx: src_xdr.FeeBumpTransaction.fromXDR(this.tx.toXDR()), + // make a copy of the tx + signatures: this.signatures.slice() // make a copy of the signatures + }); + return new src_xdr.TransactionEnvelope.envelopeTypeTxFeeBump(envelope); + } + }]); +}(TransactionBase); +;// ./src/account.js +function account_typeof(o) { "@babel/helpers - typeof"; return account_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, account_typeof(o); } +function account_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function account_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, account_toPropertyKey(o.key), o); } } +function account_createClass(e, r, t) { return r && account_defineProperties(e.prototype, r), t && account_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function account_toPropertyKey(t) { var i = account_toPrimitive(t, "string"); return "symbol" == account_typeof(i) ? i : i + ""; } +function account_toPrimitive(t, r) { if ("object" != account_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != account_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + +/** + * Create a new Account object. + * + * `Account` represents a single account in the Stellar network and its sequence + * number. Account tracks the sequence number as it is used by {@link + * TransactionBuilder}. See + * [Accounts](https://developers.stellar.org/docs/glossary/accounts/) for + * more information about how accounts work in Stellar. + * + * @constructor + * + * @param {string} accountId - ID of the account (ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`). If you + * provide a muxed account address, this will throw; use {@link + * MuxedAccount} instead. + * @param {string} sequence - current sequence number of the account + */ +var Account = /*#__PURE__*/function () { + function Account(accountId, sequence) { + account_classCallCheck(this, Account); + if (StrKey.isValidMed25519PublicKey(accountId)) { + throw new Error('accountId is an M-address; use MuxedAccount instead'); + } + if (!StrKey.isValidEd25519PublicKey(accountId)) { + throw new Error('accountId is invalid'); + } + if (!(typeof sequence === 'string')) { + throw new Error('sequence must be of type string'); + } + this._accountId = accountId; + this.sequence = new util_bignumber(sequence); + } + + /** + * Returns Stellar account ID, ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`. + * @returns {string} + */ + return account_createClass(Account, [{ + key: "accountId", + value: function accountId() { + return this._accountId; + } + + /** + * @returns {string} sequence number for the account as a string + */ + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this.sequence.toString(); + } + + /** + * Increments sequence number in this object by one. + * @returns {void} + */ + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + this.sequence = this.sequence.plus(1); + } + }]); +}(); +;// ./src/muxed_account.js +function muxed_account_typeof(o) { "@babel/helpers - typeof"; return muxed_account_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, muxed_account_typeof(o); } +function muxed_account_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function muxed_account_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, muxed_account_toPropertyKey(o.key), o); } } +function muxed_account_createClass(e, r, t) { return r && muxed_account_defineProperties(e.prototype, r), t && muxed_account_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function muxed_account_toPropertyKey(t) { var i = muxed_account_toPrimitive(t, "string"); return "symbol" == muxed_account_typeof(i) ? i : i + ""; } +function muxed_account_toPrimitive(t, r) { if ("object" != muxed_account_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != muxed_account_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + +/** + * Represents a muxed account for transactions and operations. + * + * A muxed (or *multiplexed*) account (defined rigorously in + * [CAP-27](https://stellar.org/protocol/cap-27) and briefly in + * [SEP-23](https://stellar.org/protocol/sep-23)) is one that resolves a single + * Stellar `G...`` account to many different underlying IDs. + * + * For example, you may have a single Stellar address for accounting purposes: + * GA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJVSGZ + * + * Yet would like to use it for 4 different family members: + * 1: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAGZFQ + * 2: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAALIWQ + * 3: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAPYHQ + * 4: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAQLQQ + * + * This object makes it easy to create muxed accounts from regular accounts, + * duplicate them, get/set the underlying IDs, etc. without mucking around with + * the raw XDR. + * + * Because muxed accounts are purely an off-chain convention, they all share the + * sequence number tied to their underlying G... account. Thus, this object + * *requires* an {@link Account} instance to be passed in, so that muxed + * instances of an account can collectively modify the sequence number whenever + * a muxed account is used as the source of a @{link Transaction} with {@link + * TransactionBuilder}. + * + * @constructor + * + * @param {Account} account - the @{link Account} instance representing the + * underlying G... address + * @param {string} id - a stringified uint64 value that represents the + * ID of the muxed account + * + * @link https://developers.stellar.org/docs/glossary/muxed-accounts/ + */ +var MuxedAccount = /*#__PURE__*/function () { + function MuxedAccount(baseAccount, id) { + muxed_account_classCallCheck(this, MuxedAccount); + var accountId = baseAccount.accountId(); + if (!StrKey.isValidEd25519PublicKey(accountId)) { + throw new Error('accountId is invalid'); + } + this.account = baseAccount; + this._muxedXdr = encodeMuxedAccount(accountId, id); + this._mAddress = encodeMuxedAccountToAddress(this._muxedXdr); + this._id = id; + } + + /** + * Parses an M-address into a MuxedAccount object. + * + * @param {string} mAddress - an M-address to transform + * @param {string} sequenceNum - the sequence number of the underlying {@link + * Account}, to use for the underlying base account (@link + * MuxedAccount.baseAccount). If you're using the SDK, you can use + * `server.loadAccount` to fetch this if you don't know it. + * + * @return {MuxedAccount} + */ + return muxed_account_createClass(MuxedAccount, [{ + key: "baseAccount", + value: + /** + * @return {Account} the underlying account object shared among all muxed + * accounts with this Stellar address + */ + function baseAccount() { + return this.account; + } + + /** + * @return {string} the M-address representing this account's (G-address, ID) + */ + }, { + key: "accountId", + value: function accountId() { + return this._mAddress; + } + }, { + key: "id", + value: function id() { + return this._id; + } + }, { + key: "setId", + value: function setId(id) { + if (typeof id !== 'string') { + throw new Error('id should be a string representing a number (uint64)'); + } + this._muxedXdr.med25519().id(src_xdr.Uint64.fromString(id)); + this._mAddress = encodeMuxedAccountToAddress(this._muxedXdr); + this._id = id; + return this; + } + + /** + * Accesses the underlying account's sequence number. + * @return {string} strigified sequence number for the underlying account + */ + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this.account.sequenceNumber(); + } + + /** + * Increments the underlying account's sequence number by one. + * @return {void} + */ + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + return this.account.incrementSequenceNumber(); + } + + /** + * @return {xdr.MuxedAccount} the XDR object representing this muxed account's + * G-address and uint64 ID + */ + }, { + key: "toXDRObject", + value: function toXDRObject() { + return this._muxedXdr; + } + }, { + key: "equals", + value: function equals(otherMuxedAccount) { + return this.accountId() === otherMuxedAccount.accountId(); + } + }], [{ + key: "fromAddress", + value: function fromAddress(mAddress, sequenceNum) { + var muxedAccount = decodeAddressToMuxedAccount(mAddress); + var gAddress = extractBaseAddress(mAddress); + var id = muxedAccount.med25519().id().toString(); + return new MuxedAccount(new Account(gAddress, sequenceNum), id); + } + }]); +}(); +;// ./src/sorobandata_builder.js +function sorobandata_builder_typeof(o) { "@babel/helpers - typeof"; return sorobandata_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, sorobandata_builder_typeof(o); } +function sorobandata_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function sorobandata_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, sorobandata_builder_toPropertyKey(o.key), o); } } +function sorobandata_builder_createClass(e, r, t) { return r && sorobandata_builder_defineProperties(e.prototype, r), t && sorobandata_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function sorobandata_builder_defineProperty(e, r, t) { return (r = sorobandata_builder_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function sorobandata_builder_toPropertyKey(t) { var i = sorobandata_builder_toPrimitive(t, "string"); return "symbol" == sorobandata_builder_typeof(i) ? i : i + ""; } +function sorobandata_builder_toPrimitive(t, r) { if ("object" != sorobandata_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != sorobandata_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + +/** + * Supports building {@link xdr.SorobanTransactionData} structures with various + * items set to specific values. + * + * This is recommended for when you are building + * {@link Operation.extendFootprintTtl} / {@link Operation.restoreFootprint} + * operations and need to {@link TransactionBuilder.setSorobanData} to avoid + * (re)building the entire data structure from scratch. + * + * @constructor + * + * @param {string | xdr.SorobanTransactionData} [sorobanData] either a + * base64-encoded string that represents an + * {@link xdr.SorobanTransactionData} instance or an XDR instance itself + * (it will be copied); if omitted or "falsy" (e.g. an empty string), it + * starts with an empty instance + * + * @example + * // You want to use an existing data blob but override specific parts. + * const newData = new SorobanDataBuilder(existing) + * .setReadOnly(someLedgerKeys) + * .setRefundableFee("1000") + * .build(); + * + * // You want an instance from scratch + * const newData = new SorobanDataBuilder() + * .setFootprint([someLedgerKey], []) + * .setRefundableFee("1000") + * .build(); + */ +var SorobanDataBuilder = /*#__PURE__*/function () { + function SorobanDataBuilder(sorobanData) { + sorobandata_builder_classCallCheck(this, SorobanDataBuilder); + sorobandata_builder_defineProperty(this, "_data", void 0); + var data; + if (!sorobanData) { + data = new src_xdr.SorobanTransactionData({ + resources: new src_xdr.SorobanResources({ + footprint: new src_xdr.LedgerFootprint({ + readOnly: [], + readWrite: [] + }), + instructions: 0, + readBytes: 0, + writeBytes: 0 + }), + ext: new src_xdr.ExtensionPoint(0), + resourceFee: new src_xdr.Int64(0) + }); + } else if (typeof sorobanData === 'string' || ArrayBuffer.isView(sorobanData)) { + data = SorobanDataBuilder.fromXDR(sorobanData); + } else { + data = SorobanDataBuilder.fromXDR(sorobanData.toXDR()); // copy + } + this._data = data; + } + + /** + * Decodes and builds a {@link xdr.SorobanTransactionData} instance. + * @param {Uint8Array|Buffer|string} data raw input to decode + * @returns {xdr.SorobanTransactionData} + */ + return sorobandata_builder_createClass(SorobanDataBuilder, [{ + key: "setResourceFee", + value: + /** + * Sets the resource fee portion of the Soroban data. + * @param {number | bigint | string} fee the resource fee to set (int64) + * @returns {SorobanDataBuilder} + */ + function setResourceFee(fee) { + this._data.resourceFee(new src_xdr.Int64(fee)); + return this; + } + + /** + * Sets up the resource metrics. + * + * You should almost NEVER need this, as its often generated / provided to you + * by transaction simulation/preflight from a Soroban RPC server. + * + * @param {number} cpuInstrs number of CPU instructions + * @param {number} readBytes number of bytes being read + * @param {number} writeBytes number of bytes being written + * + * @returns {SorobanDataBuilder} + */ + }, { + key: "setResources", + value: function setResources(cpuInstrs, readBytes, writeBytes) { + this._data.resources().instructions(cpuInstrs); + this._data.resources().readBytes(readBytes); + this._data.resources().writeBytes(writeBytes); + return this; + } + + /** + * Appends the given ledger keys to the existing storage access footprint. + * @param {xdr.LedgerKey[]} readOnly read-only keys to add + * @param {xdr.LedgerKey[]} readWrite read-write keys to add + * @returns {SorobanDataBuilder} this builder instance + */ + }, { + key: "appendFootprint", + value: function appendFootprint(readOnly, readWrite) { + return this.setFootprint(this.getReadOnly().concat(readOnly), this.getReadWrite().concat(readWrite)); + } + + /** + * Sets the storage access footprint to be a certain set of ledger keys. + * + * You can also set each field explicitly via + * {@link SorobanDataBuilder.setReadOnly} and + * {@link SorobanDataBuilder.setReadWrite} or add to the existing footprint + * via {@link SorobanDataBuilder.appendFootprint}. + * + * Passing `null|undefined` to either parameter will IGNORE the existing + * values. If you want to clear them, pass `[]`, instead. + * + * @param {xdr.LedgerKey[]|null} [readOnly] the set of ledger keys to set in + * the read-only portion of the transaction's `sorobanData`, or `null | + * undefined` to keep the existing keys + * @param {xdr.LedgerKey[]|null} [readWrite] the set of ledger keys to set in + * the read-write portion of the transaction's `sorobanData`, or `null | + * undefined` to keep the existing keys + * @returns {SorobanDataBuilder} this builder instance + */ + }, { + key: "setFootprint", + value: function setFootprint(readOnly, readWrite) { + if (readOnly !== null) { + // null means "leave me alone" + this.setReadOnly(readOnly); + } + if (readWrite !== null) { + this.setReadWrite(readWrite); + } + return this; + } + + /** + * @param {xdr.LedgerKey[]} readOnly read-only keys in the access footprint + * @returns {SorobanDataBuilder} + */ + }, { + key: "setReadOnly", + value: function setReadOnly(readOnly) { + this._data.resources().footprint().readOnly(readOnly !== null && readOnly !== void 0 ? readOnly : []); + return this; + } + + /** + * @param {xdr.LedgerKey[]} readWrite read-write keys in the access footprint + * @returns {SorobanDataBuilder} + */ + }, { + key: "setReadWrite", + value: function setReadWrite(readWrite) { + this._data.resources().footprint().readWrite(readWrite !== null && readWrite !== void 0 ? readWrite : []); + return this; + } + + /** + * @returns {xdr.SorobanTransactionData} a copy of the final data structure + */ + }, { + key: "build", + value: function build() { + return src_xdr.SorobanTransactionData.fromXDR(this._data.toXDR()); // clone + } + + // + // getters follow + // + + /** @returns {xdr.LedgerKey[]} the read-only storage access pattern */ + }, { + key: "getReadOnly", + value: function getReadOnly() { + return this.getFootprint().readOnly(); + } + + /** @returns {xdr.LedgerKey[]} the read-write storage access pattern */ + }, { + key: "getReadWrite", + value: function getReadWrite() { + return this.getFootprint().readWrite(); + } + + /** @returns {xdr.LedgerFootprint} the storage access pattern */ + }, { + key: "getFootprint", + value: function getFootprint() { + return this._data.resources().footprint(); + } + }], [{ + key: "fromXDR", + value: function fromXDR(data) { + return src_xdr.SorobanTransactionData.fromXDR(data, typeof data === 'string' ? 'base64' : 'raw'); + } + }]); +}(); +;// ./src/signerkey.js +function signerkey_typeof(o) { "@babel/helpers - typeof"; return signerkey_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, signerkey_typeof(o); } +function signerkey_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function signerkey_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, signerkey_toPropertyKey(o.key), o); } } +function signerkey_createClass(e, r, t) { return r && signerkey_defineProperties(e.prototype, r), t && signerkey_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function signerkey_toPropertyKey(t) { var i = signerkey_toPrimitive(t, "string"); return "symbol" == signerkey_typeof(i) ? i : i + ""; } +function signerkey_toPrimitive(t, r) { if ("object" != signerkey_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != signerkey_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + +/** + * A container class with helpers to convert between signer keys + * (`xdr.SignerKey`) and {@link StrKey}s. + * + * It's primarly used for manipulating the `extraSigners` precondition on a + * {@link Transaction}. + * + * @see {@link TransactionBuilder.setExtraSigners} + */ +var SignerKey = /*#__PURE__*/function () { + function SignerKey() { + signerkey_classCallCheck(this, SignerKey); + } + return signerkey_createClass(SignerKey, null, [{ + key: "decodeAddress", + value: + /** + * Decodes a StrKey address into an xdr.SignerKey instance. + * + * Only ED25519 public keys (G...), pre-auth transactions (T...), hashes + * (H...), and signed payloads (P...) can be signer keys. + * + * @param {string} address a StrKey-encoded signer address + * @returns {xdr.SignerKey} + */ + function decodeAddress(address) { + var signerKeyMap = { + ed25519PublicKey: src_xdr.SignerKey.signerKeyTypeEd25519, + preAuthTx: src_xdr.SignerKey.signerKeyTypePreAuthTx, + sha256Hash: src_xdr.SignerKey.signerKeyTypeHashX, + signedPayload: src_xdr.SignerKey.signerKeyTypeEd25519SignedPayload + }; + var vb = StrKey.getVersionByteForPrefix(address); + var encoder = signerKeyMap[vb]; + if (!encoder) { + throw new Error("invalid signer key type (".concat(vb, ")")); + } + var raw = decodeCheck(vb, address); + switch (vb) { + case 'signedPayload': + return encoder(new src_xdr.SignerKeyEd25519SignedPayload({ + ed25519: raw.slice(0, 32), + payload: raw.slice(32 + 4) + })); + case 'ed25519PublicKey': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + default: + return encoder(raw); + } + } + + /** + * Encodes a signer key into its StrKey equivalent. + * + * @param {xdr.SignerKey} signerKey the signer + * @returns {string} the StrKey representation of the signer + */ + }, { + key: "encodeSignerKey", + value: function encodeSignerKey(signerKey) { + var strkeyType; + var raw; + switch (signerKey["switch"]()) { + case src_xdr.SignerKeyType.signerKeyTypeEd25519(): + strkeyType = 'ed25519PublicKey'; + raw = signerKey.value(); + break; + case src_xdr.SignerKeyType.signerKeyTypePreAuthTx(): + strkeyType = 'preAuthTx'; + raw = signerKey.value(); + break; + case src_xdr.SignerKeyType.signerKeyTypeHashX(): + strkeyType = 'sha256Hash'; + raw = signerKey.value(); + break; + case src_xdr.SignerKeyType.signerKeyTypeEd25519SignedPayload(): + strkeyType = 'signedPayload'; + raw = signerKey.ed25519SignedPayload().toXDR('raw'); + break; + default: + throw new Error("invalid SignerKey (type: ".concat(signerKey["switch"](), ")")); + } + return encodeCheck(strkeyType, raw); + } + }]); +}(); +;// ./src/transaction_builder.js +function transaction_builder_typeof(o) { "@babel/helpers - typeof"; return transaction_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, transaction_builder_typeof(o); } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || transaction_builder_unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function transaction_builder_unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return transaction_builder_arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? transaction_builder_arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return transaction_builder_arrayLikeToArray(r); } +function transaction_builder_arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function transaction_builder_ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function transaction_builder_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? transaction_builder_ownKeys(Object(t), !0).forEach(function (r) { transaction_builder_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : transaction_builder_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function transaction_builder_defineProperty(e, r, t) { return (r = transaction_builder_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function transaction_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function transaction_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, transaction_builder_toPropertyKey(o.key), o); } } +function transaction_builder_createClass(e, r, t) { return r && transaction_builder_defineProperties(e.prototype, r), t && transaction_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function transaction_builder_toPropertyKey(t) { var i = transaction_builder_toPrimitive(t, "string"); return "symbol" == transaction_builder_typeof(i) ? i : i + ""; } +function transaction_builder_toPrimitive(t, r) { if ("object" != transaction_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != transaction_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + + + + + + + + +/** + * Minimum base fee for transactions. If this fee is below the network + * minimum, the transaction will fail. The more operations in the + * transaction, the greater the required fee. Use {@link + * Server#fetchBaseFee} to get an accurate value of minimum transaction + * fee on the network. + * + * @constant + * @see [Fees](https://developers.stellar.org/docs/glossary/fees/) + */ +var BASE_FEE = '100'; // Stroops + +/** + * @constant + * @see {@link TransactionBuilder#setTimeout} + * @see [Timeout](https://developers.stellar.org/api/resources/transactions/post/) + */ +var TimeoutInfinite = 0; + +/** + *

Transaction builder helps constructs a new `{@link Transaction}` using the + * given {@link Account} as the transaction's "source account". The transaction + * will use the current sequence number of the given account as its sequence + * number and increment the given account's sequence number by one. The given + * source account must include a private key for signing the transaction or an + * error will be thrown.

+ * + *

Operations can be added to the transaction via their corresponding builder + * methods, and each returns the TransactionBuilder object so they can be + * chained together. After adding the desired operations, call the `build()` + * method on the `TransactionBuilder` to return a fully constructed `{@link + * Transaction}` that can be signed. The returned transaction will contain the + * sequence number of the source account and include the signature from the + * source account.

+ * + *

Be careful about unsubmitted transactions! When you build + * a transaction, `stellar-sdk` automatically increments the source account's + * sequence number. If you end up not submitting this transaction and submitting + * another one instead, it'll fail due to the sequence number being wrong. So if + * you decide not to use a built transaction, make sure to update the source + * account's sequence number with + * [Server.loadAccount](https://stellar.github.io/js-stellar-sdk/Server.html#loadAccount) + * before creating another transaction.

+ * + *

The following code example creates a new transaction with {@link + * Operation.createAccount} and {@link Operation.payment} operations. The + * Transaction's source account first funds `destinationA`, then sends a payment + * to `destinationB`. The built transaction is then signed by + * `sourceKeypair`.

+ * + * ``` + * var transaction = new TransactionBuilder(source, { fee, networkPassphrase: Networks.TESTNET }) + * .addOperation(Operation.createAccount({ + * destination: destinationA, + * startingBalance: "20" + * })) // <- funds and creates destinationA + * .addOperation(Operation.payment({ + * destination: destinationB, + * amount: "100", + * asset: Asset.native() + * })) // <- sends 100 XLM to destinationB + * .setTimeout(30) + * .build(); + * + * transaction.sign(sourceKeypair); + * ``` + * + * @constructor + * + * @param {Account} sourceAccount - source account for this transaction + * @param {object} opts - Options object + * @param {string} opts.fee - max fee you're willing to pay per + * operation in this transaction (**in stroops**) + * + * @param {object} [opts.timebounds] - timebounds for the + * validity of this transaction + * @param {number|string|Date} [opts.timebounds.minTime] - 64-bit UNIX + * timestamp or Date object + * @param {number|string|Date} [opts.timebounds.maxTime] - 64-bit UNIX + * timestamp or Date object + * @param {object} [opts.ledgerbounds] - ledger bounds for the + * validity of this transaction + * @param {number} [opts.ledgerbounds.minLedger] - number of the minimum + * ledger sequence + * @param {number} [opts.ledgerbounds.maxLedger] - number of the maximum + * ledger sequence + * @param {string} [opts.minAccountSequence] - number for + * the minimum account sequence + * @param {number} [opts.minAccountSequenceAge] - number of + * seconds for the minimum account sequence age + * @param {number} [opts.minAccountSequenceLedgerGap] - number of + * ledgers for the minimum account sequence ledger gap + * @param {string[]} [opts.extraSigners] - list of the extra signers + * required for this transaction + * @param {Memo} [opts.memo] - memo for the transaction + * @param {string} [opts.networkPassphrase] passphrase of the + * target Stellar network (e.g. "Public Global Stellar Network ; September + * 2015" for the pubnet) + * @param {xdr.SorobanTransactionData | string} [opts.sorobanData] - an + * optional instance of {@link xdr.SorobanTransactionData} to be set as the + * internal `Transaction.Ext.SorobanData` field (either the xdr object or a + * base64 string). In the case of Soroban transactions, this can be obtained + * from a prior simulation of the transaction with a contract invocation and + * provides necessary resource estimations. You can also use + * {@link SorobanDataBuilder} to construct complicated combinations of + * parameters without mucking with XDR directly. **Note:** For + * non-contract(non-Soroban) transactions, this has no effect. + */ +var TransactionBuilder = /*#__PURE__*/function () { + function TransactionBuilder(sourceAccount) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + transaction_builder_classCallCheck(this, TransactionBuilder); + if (!sourceAccount) { + throw new Error('must specify source account for the transaction'); + } + if (opts.fee === undefined) { + throw new Error('must specify fee for the transaction (in stroops)'); + } + this.source = sourceAccount; + this.operations = []; + this.baseFee = opts.fee; + this.timebounds = opts.timebounds ? transaction_builder_objectSpread({}, opts.timebounds) : null; + this.ledgerbounds = opts.ledgerbounds ? transaction_builder_objectSpread({}, opts.ledgerbounds) : null; + this.minAccountSequence = opts.minAccountSequence || null; + this.minAccountSequenceAge = opts.minAccountSequenceAge || null; + this.minAccountSequenceLedgerGap = opts.minAccountSequenceLedgerGap || null; + this.extraSigners = opts.extraSigners ? _toConsumableArray(opts.extraSigners) : null; + this.memo = opts.memo || Memo.none(); + this.networkPassphrase = opts.networkPassphrase || null; + this.sorobanData = opts.sorobanData ? new SorobanDataBuilder(opts.sorobanData).build() : null; + } + + /** + * Creates a builder instance using an existing {@link Transaction} as a + * template, ignoring any existing envelope signatures. + * + * Note that the sequence number WILL be cloned, so EITHER this transaction or + * the one it was cloned from will be valid. This is useful in situations + * where you are constructing a transaction in pieces and need to make + * adjustments as you go (for example, when filling out Soroban resource + * information). + * + * @param {Transaction} tx a "template" transaction to clone exactly + * @param {object} [opts] additional options to override the clone, e.g. + * {fee: '1000'} will override the existing base fee derived from `tx` (see + * the {@link TransactionBuilder} constructor for detailed options) + * + * @returns {TransactionBuilder} a "prepared" builder instance with the same + * configuration and operations as the given transaction + * + * @warning This does not clone the transaction's + * {@link xdr.SorobanTransactionData} (if applicable), use + * {@link SorobanDataBuilder} and {@link TransactionBuilder.setSorobanData} + * as needed, instead.. + * + * @todo This cannot clone {@link FeeBumpTransaction}s, yet. + */ + return transaction_builder_createClass(TransactionBuilder, [{ + key: "addOperation", + value: + /** + * Adds an operation to the transaction. + * + * @param {xdr.Operation} operation The xdr operation object, use {@link + * Operation} static methods. + * + * @returns {TransactionBuilder} + */ + function addOperation(operation) { + this.operations.push(operation); + return this; + } + + /** + * Adds an operation to the transaction at a specific index. + * + * @param {xdr.Operation} operation - The xdr operation object to add, use {@link Operation} static methods. + * @param {number} index - The index at which to insert the operation. + * + * @returns {TransactionBuilder} - The TransactionBuilder instance for method chaining. + */ + }, { + key: "addOperationAt", + value: function addOperationAt(operation, index) { + this.operations.splice(index, 0, operation); + return this; + } + + /** + * Removes the operations from the builder (useful when cloning). + * @returns {TransactionBuilder} this builder instance + */ + }, { + key: "clearOperations", + value: function clearOperations() { + this.operations = []; + return this; + } + + /** + * Removes the operation at the specified index from the transaction. + * + * @param {number} index - The index of the operation to remove. + * + * @returns {TransactionBuilder} The TransactionBuilder instance for method chaining. + */ + }, { + key: "clearOperationAt", + value: function clearOperationAt(index) { + this.operations.splice(index, 1); + return this; + } + + /** + * Adds a memo to the transaction. + * @param {Memo} memo {@link Memo} object + * @returns {TransactionBuilder} + */ + }, { + key: "addMemo", + value: function addMemo(memo) { + this.memo = memo; + return this; + } + + /** + * Sets a timeout precondition on the transaction. + * + * Because of the distributed nature of the Stellar network it is possible + * that the status of your transaction will be determined after a long time + * if the network is highly congested. If you want to be sure to receive the + * status of the transaction within a given period you should set the {@link + * TimeBounds} with `maxTime` on the transaction (this is what `setTimeout` + * does internally; if there's `minTime` set but no `maxTime` it will be + * added). + * + * A call to `TransactionBuilder.setTimeout` is **required** if Transaction + * does not have `max_time` set. If you don't want to set timeout, use + * `{@link TimeoutInfinite}`. In general you should set `{@link + * TimeoutInfinite}` only in smart contracts. + * + * Please note that Horizon may still return 504 Gateway Timeout + * error, even for short timeouts. In such case you need to resubmit the same + * transaction again without making any changes to receive a status. This + * method is using the machine system time (UTC), make sure it is set + * correctly. + * + * @param {number} timeoutSeconds Number of seconds the transaction is good. + * Can't be negative. If the value is {@link TimeoutInfinite}, the + * transaction is good indefinitely. + * + * @returns {TransactionBuilder} + * + * @see {@link TimeoutInfinite} + * @see https://developers.stellar.org/docs/tutorials/handling-errors/ + */ + }, { + key: "setTimeout", + value: function setTimeout(timeoutSeconds) { + if (this.timebounds !== null && this.timebounds.maxTime > 0) { + throw new Error('TimeBounds.max_time has been already set - setting timeout would overwrite it.'); + } + if (timeoutSeconds < 0) { + throw new Error('timeout cannot be negative'); + } + if (timeoutSeconds > 0) { + var timeoutTimestamp = Math.floor(Date.now() / 1000) + timeoutSeconds; + if (this.timebounds === null) { + this.timebounds = { + minTime: 0, + maxTime: timeoutTimestamp + }; + } else { + this.timebounds = { + minTime: this.timebounds.minTime, + maxTime: timeoutTimestamp + }; + } + } else { + this.timebounds = { + minTime: 0, + maxTime: 0 + }; + } + return this; + } + + /** + * If you want to prepare a transaction which will become valid at some point + * in the future, or be invalid after some time, you can set a timebounds + * precondition. Internally this will set the `minTime`, and `maxTime` + * preconditions. Conflicts with `setTimeout`, so use one or the other. + * + * @param {Date|number} minEpochOrDate Either a JS Date object, or a number + * of UNIX epoch seconds. The transaction is valid after this timestamp. + * Can't be negative. If the value is `0`, the transaction is valid + * immediately. + * @param {Date|number} maxEpochOrDate Either a JS Date object, or a number + * of UNIX epoch seconds. The transaction is valid until this timestamp. + * Can't be negative. If the value is `0`, the transaction is valid + * indefinitely. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setTimebounds", + value: function setTimebounds(minEpochOrDate, maxEpochOrDate) { + // Force it to a date type + if (typeof minEpochOrDate === 'number') { + minEpochOrDate = new Date(minEpochOrDate * 1000); + } + if (typeof maxEpochOrDate === 'number') { + maxEpochOrDate = new Date(maxEpochOrDate * 1000); + } + if (this.timebounds !== null) { + throw new Error('TimeBounds has been already set - setting timebounds would overwrite it.'); + } + + // Convert that date to the epoch seconds + var minTime = Math.floor(minEpochOrDate.valueOf() / 1000); + var maxTime = Math.floor(maxEpochOrDate.valueOf() / 1000); + if (minTime < 0) { + throw new Error('min_time cannot be negative'); + } + if (maxTime < 0) { + throw new Error('max_time cannot be negative'); + } + if (maxTime > 0 && minTime > maxTime) { + throw new Error('min_time cannot be greater than max_time'); + } + this.timebounds = { + minTime: minTime, + maxTime: maxTime + }; + return this; + } + + /** + * If you want to prepare a transaction which will only be valid within some + * range of ledgers, you can set a ledgerbounds precondition. + * Internally this will set the `minLedger` and `maxLedger` preconditions. + * + * @param {number} minLedger The minimum ledger this transaction is valid at + * or after. Cannot be negative. If the value is `0` (the default), the + * transaction is valid immediately. + * + * @param {number} maxLedger The maximum ledger this transaction is valid + * before. Cannot be negative. If the value is `0`, the transaction is + * valid indefinitely. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setLedgerbounds", + value: function setLedgerbounds(minLedger, maxLedger) { + if (this.ledgerbounds !== null) { + throw new Error('LedgerBounds has been already set - setting ledgerbounds would overwrite it.'); + } + if (minLedger < 0) { + throw new Error('min_ledger cannot be negative'); + } + if (maxLedger < 0) { + throw new Error('max_ledger cannot be negative'); + } + if (maxLedger > 0 && minLedger > maxLedger) { + throw new Error('min_ledger cannot be greater than max_ledger'); + } + this.ledgerbounds = { + minLedger: minLedger, + maxLedger: maxLedger + }; + return this; + } + + /** + * If you want to prepare a transaction which will be valid only while the + * account sequence number is + * + * minAccountSequence <= sourceAccountSequence < tx.seqNum + * + * Note that after execution the account's sequence number is always raised to + * `tx.seqNum`. Internally this will set the `minAccountSequence` + * precondition. + * + * @param {string} minAccountSequence The minimum source account sequence + * number this transaction is valid for. If the value is `0` (the + * default), the transaction is valid when `sourceAccount's sequence + * number == tx.seqNum- 1`. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequence", + value: function setMinAccountSequence(minAccountSequence) { + if (this.minAccountSequence !== null) { + throw new Error('min_account_sequence has been already set - setting min_account_sequence would overwrite it.'); + } + this.minAccountSequence = minAccountSequence; + return this; + } + + /** + * For the transaction to be valid, the current ledger time must be at least + * `minAccountSequenceAge` greater than sourceAccount's `sequenceTime`. + * Internally this will set the `minAccountSequenceAge` precondition. + * + * @param {number} durationInSeconds The minimum amount of time between + * source account sequence time and the ledger time when this transaction + * will become valid. If the value is `0`, the transaction is unrestricted + * by the account sequence age. Cannot be negative. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequenceAge", + value: function setMinAccountSequenceAge(durationInSeconds) { + if (typeof durationInSeconds !== 'number') { + throw new Error('min_account_sequence_age must be a number'); + } + if (this.minAccountSequenceAge !== null) { + throw new Error('min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.'); + } + if (durationInSeconds < 0) { + throw new Error('min_account_sequence_age cannot be negative'); + } + this.minAccountSequenceAge = durationInSeconds; + return this; + } + + /** + * For the transaction to be valid, the current ledger number must be at least + * `minAccountSequenceLedgerGap` greater than sourceAccount's ledger sequence. + * Internally this will set the `minAccountSequenceLedgerGap` precondition. + * + * @param {number} gap The minimum number of ledgers between source account + * sequence and the ledger number when this transaction will become valid. + * If the value is `0`, the transaction is unrestricted by the account + * sequence ledger. Cannot be negative. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequenceLedgerGap", + value: function setMinAccountSequenceLedgerGap(gap) { + if (this.minAccountSequenceLedgerGap !== null) { + throw new Error('min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.'); + } + if (gap < 0) { + throw new Error('min_account_sequence_ledger_gap cannot be negative'); + } + this.minAccountSequenceLedgerGap = gap; + return this; + } + + /** + * For the transaction to be valid, there must be a signature corresponding to + * every Signer in this array, even if the signature is not otherwise required + * by the sourceAccount or operations. Internally this will set the + * `extraSigners` precondition. + * + * @param {string[]} extraSigners required extra signers (as {@link StrKey}s) + * + * @returns {TransactionBuilder} + */ + }, { + key: "setExtraSigners", + value: function setExtraSigners(extraSigners) { + if (!Array.isArray(extraSigners)) { + throw new Error('extra_signers must be an array of strings.'); + } + if (this.extraSigners !== null) { + throw new Error('extra_signers has been already set - setting extra_signers would overwrite it.'); + } + if (extraSigners.length > 2) { + throw new Error('extra_signers cannot be longer than 2 elements.'); + } + this.extraSigners = _toConsumableArray(extraSigners); + return this; + } + + /** + * Set network nassphrase for the Transaction that will be built. + * + * @param {string} networkPassphrase passphrase of the target Stellar + * network (e.g. "Public Global Stellar Network ; September 2015"). + * + * @returns {TransactionBuilder} + */ + }, { + key: "setNetworkPassphrase", + value: function setNetworkPassphrase(networkPassphrase) { + this.networkPassphrase = networkPassphrase; + return this; + } + + /** + * Sets the transaction's internal Soroban transaction data (resources, + * footprint, etc.). + * + * For non-contract(non-Soroban) transactions, this setting has no effect. In + * the case of Soroban transactions, this is either an instance of + * {@link xdr.SorobanTransactionData} or a base64-encoded string of said + * structure. This is usually obtained from the simulation response based on a + * transaction with a Soroban operation (e.g. + * {@link Operation.invokeHostFunction}, providing necessary resource + * and storage footprint estimations for contract invocation. + * + * @param {xdr.SorobanTransactionData | string} sorobanData the + * {@link xdr.SorobanTransactionData} as a raw xdr object or a base64 + * string to be decoded + * + * @returns {TransactionBuilder} + * @see {SorobanDataBuilder} + */ + }, { + key: "setSorobanData", + value: function setSorobanData(sorobanData) { + this.sorobanData = new SorobanDataBuilder(sorobanData).build(); + return this; + } + + /** + * This will build the transaction. + * It will also increment the source account's sequence number by 1. + * @returns {Transaction} This method will return the built {@link Transaction}. + */ + }, { + key: "build", + value: function build() { + var sequenceNumber = new util_bignumber(this.source.sequenceNumber()).plus(1); + var fee = new util_bignumber(this.baseFee).times(this.operations.length).toNumber(); + var attrs = { + fee: fee, + seqNum: src_xdr.SequenceNumber.fromString(sequenceNumber.toString()), + memo: this.memo ? this.memo.toXDRObject() : null + }; + if (this.timebounds === null || typeof this.timebounds.minTime === 'undefined' || typeof this.timebounds.maxTime === 'undefined') { + throw new Error('TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).'); + } + if (isValidDate(this.timebounds.minTime)) { + this.timebounds.minTime = this.timebounds.minTime.getTime() / 1000; + } + if (isValidDate(this.timebounds.maxTime)) { + this.timebounds.maxTime = this.timebounds.maxTime.getTime() / 1000; + } + this.timebounds.minTime = xdr.UnsignedHyper.fromString(this.timebounds.minTime.toString()); + this.timebounds.maxTime = xdr.UnsignedHyper.fromString(this.timebounds.maxTime.toString()); + var timeBounds = new src_xdr.TimeBounds(this.timebounds); + if (this.hasV2Preconditions()) { + var ledgerBounds = null; + if (this.ledgerbounds !== null) { + ledgerBounds = new src_xdr.LedgerBounds(this.ledgerbounds); + } + var minSeqNum = this.minAccountSequence || '0'; + minSeqNum = src_xdr.SequenceNumber.fromString(minSeqNum); + var minSeqAge = xdr.UnsignedHyper.fromString(this.minAccountSequenceAge !== null ? this.minAccountSequenceAge.toString() : '0'); + var minSeqLedgerGap = this.minAccountSequenceLedgerGap || 0; + var extraSigners = this.extraSigners !== null ? this.extraSigners.map(SignerKey.decodeAddress) : []; + attrs.cond = src_xdr.Preconditions.precondV2(new src_xdr.PreconditionsV2({ + timeBounds: timeBounds, + ledgerBounds: ledgerBounds, + minSeqNum: minSeqNum, + minSeqAge: minSeqAge, + minSeqLedgerGap: minSeqLedgerGap, + extraSigners: extraSigners + })); + } else { + attrs.cond = src_xdr.Preconditions.precondTime(timeBounds); + } + attrs.sourceAccount = decodeAddressToMuxedAccount(this.source.accountId()); + + // TODO - remove this workaround for TransactionExt ts constructor + // and use the typescript generated static factory method once fixed + // https://github.com/stellar/dts-xdr/issues/5 + if (this.sorobanData) { + // @ts-ignore + attrs.ext = new src_xdr.TransactionExt(1, this.sorobanData); + } else { + // @ts-ignore + attrs.ext = new src_xdr.TransactionExt(0, src_xdr.Void); + } + var xtx = new src_xdr.Transaction(attrs); + xtx.operations(this.operations); + var txEnvelope = new src_xdr.TransactionEnvelope.envelopeTypeTx(new src_xdr.TransactionV1Envelope({ + tx: xtx + })); + var tx = new Transaction(txEnvelope, this.networkPassphrase); + this.source.incrementSequenceNumber(); + return tx; + } + }, { + key: "hasV2Preconditions", + value: function hasV2Preconditions() { + return this.ledgerbounds !== null || this.minAccountSequence !== null || this.minAccountSequenceAge !== null || this.minAccountSequenceLedgerGap !== null || this.extraSigners !== null && this.extraSigners.length > 0; + } + + /** + * Builds a {@link FeeBumpTransaction}, enabling you to resubmit an existing + * transaction with a higher fee. + * + * @param {Keypair|string} feeSource - account paying for the transaction, + * in the form of either a Keypair (only the public key is used) or + * an account ID (in G... or M... form, but refer to `withMuxing`) + * @param {string} baseFee - max fee willing to pay per operation + * in inner transaction (**in stroops**) + * @param {Transaction} innerTx - {@link Transaction} to be bumped by + * the fee bump transaction + * @param {string} networkPassphrase - passphrase of the target + * Stellar network (e.g. "Public Global Stellar Network ; September 2015", + * see {@link Networks}) + * + * @todo Alongside the next major version bump, this type signature can be + * changed to be less awkward: accept a MuxedAccount as the `feeSource` + * rather than a keypair or string. + * + * @note Your fee-bump amount should be >= 10x the original fee. + * @see https://developers.stellar.org/docs/glossary/fee-bumps/#replace-by-fee + * + * @returns {FeeBumpTransaction} + */ + }], [{ + key: "cloneFrom", + value: function cloneFrom(tx) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (!(tx instanceof Transaction)) { + throw new TypeError("expected a 'Transaction', got: ".concat(tx)); + } + var sequenceNum = (BigInt(tx.sequence) - 1n).toString(); + var source; + // rebuild the source account based on the strkey + if (StrKey.isValidMed25519PublicKey(tx.source)) { + source = MuxedAccount.fromAddress(tx.source, sequenceNum); + } else if (StrKey.isValidEd25519PublicKey(tx.source)) { + source = new Account(tx.source, sequenceNum); + } else { + throw new TypeError("unsupported tx source account: ".concat(tx.source)); + } + + // the initial fee passed to the builder gets scaled up based on the number + // of operations at the end, so we have to down-scale first + var unscaledFee = parseInt(tx.fee, 10) / tx.operations.length; + var builder = new TransactionBuilder(source, transaction_builder_objectSpread({ + fee: (unscaledFee || BASE_FEE).toString(), + memo: tx.memo, + networkPassphrase: tx.networkPassphrase, + timebounds: tx.timeBounds, + ledgerbounds: tx.ledgerBounds, + minAccountSequence: tx.minAccountSequence, + minAccountSequenceAge: tx.minAccountSequenceAge, + minAccountSequenceLedgerGap: tx.minAccountSequenceLedgerGap, + extraSigners: tx.extraSigners + }, opts)); + tx._tx.operations().forEach(function (op) { + return builder.addOperation(op); + }); + return builder; + } + }, { + key: "buildFeeBumpTransaction", + value: function buildFeeBumpTransaction(feeSource, baseFee, innerTx, networkPassphrase) { + var innerOps = innerTx.operations.length; + var innerBaseFeeRate = new util_bignumber(innerTx.fee).div(innerOps); + var base = new util_bignumber(baseFee); + + // The fee rate for fee bump is at least the fee rate of the inner transaction + if (base.lt(innerBaseFeeRate)) { + throw new Error("Invalid baseFee, it should be at least ".concat(innerBaseFeeRate, " stroops.")); + } + var minBaseFee = new util_bignumber(BASE_FEE); + + // The fee rate is at least the minimum fee + if (base.lt(minBaseFee)) { + throw new Error("Invalid baseFee, it should be at least ".concat(minBaseFee, " stroops.")); + } + var innerTxEnvelope = innerTx.toEnvelope(); + if (innerTxEnvelope["switch"]() === src_xdr.EnvelopeType.envelopeTypeTxV0()) { + var v0Tx = innerTxEnvelope.v0().tx(); + var v1Tx = new src_xdr.Transaction({ + sourceAccount: new src_xdr.MuxedAccount.keyTypeEd25519(v0Tx.sourceAccountEd25519()), + fee: v0Tx.fee(), + seqNum: v0Tx.seqNum(), + cond: src_xdr.Preconditions.precondTime(v0Tx.timeBounds()), + memo: v0Tx.memo(), + operations: v0Tx.operations(), + ext: new src_xdr.TransactionExt(0) + }); + innerTxEnvelope = new src_xdr.TransactionEnvelope.envelopeTypeTx(new src_xdr.TransactionV1Envelope({ + tx: v1Tx, + signatures: innerTxEnvelope.v0().signatures() + })); + } + var feeSourceAccount; + if (typeof feeSource === 'string') { + feeSourceAccount = decodeAddressToMuxedAccount(feeSource); + } else { + feeSourceAccount = feeSource.xdrMuxedAccount(); + } + var tx = new src_xdr.FeeBumpTransaction({ + feeSource: feeSourceAccount, + fee: src_xdr.Int64.fromString(base.times(innerOps + 1).toString()), + innerTx: src_xdr.FeeBumpTransactionInnerTx.envelopeTypeTx(innerTxEnvelope.v1()), + ext: new src_xdr.FeeBumpTransactionExt(0) + }); + var feeBumpTxEnvelope = new src_xdr.FeeBumpTransactionEnvelope({ + tx: tx, + signatures: [] + }); + var envelope = new src_xdr.TransactionEnvelope.envelopeTypeTxFeeBump(feeBumpTxEnvelope); + return new FeeBumpTransaction(envelope, networkPassphrase); + } + + /** + * Build a {@link Transaction} or {@link FeeBumpTransaction} from an + * xdr.TransactionEnvelope. + * + * @param {string|xdr.TransactionEnvelope} envelope - The transaction envelope + * object or base64 encoded string. + * @param {string} networkPassphrase - The network passphrase of the target + * Stellar network (e.g. "Public Global Stellar Network ; September + * 2015"), see {@link Networks}. + * + * @returns {Transaction|FeeBumpTransaction} + */ + }, { + key: "fromXDR", + value: function fromXDR(envelope, networkPassphrase) { + if (typeof envelope === 'string') { + envelope = src_xdr.TransactionEnvelope.fromXDR(envelope, 'base64'); + } + if (envelope["switch"]() === src_xdr.EnvelopeType.envelopeTypeTxFeeBump()) { + return new FeeBumpTransaction(envelope, networkPassphrase); + } + return new Transaction(envelope, networkPassphrase); + } + }]); +}(); + +/** + * Checks whether a provided object is a valid Date. + * @argument {Date} d date object + * @returns {boolean} + */ +function isValidDate(d) { + // isnan is okay here because it correctly checks for invalid date objects + // eslint-disable-next-line no-restricted-globals + return d instanceof Date && !isNaN(d); +} +;// ./src/network.js +/** + * Contains passphrases for common networks: + * * `Networks.PUBLIC`: `Public Global Stellar Network ; September 2015` + * * `Networks.TESTNET`: `Test SDF Network ; September 2015` + * * `Networks.FUTURENET`: `Test SDF Future Network ; October 2022` + * * `Networks.STANDALONE`: `Standalone Network ; February 2017` + * + * @type {{PUBLIC: string, TESTNET: string, FUTURENET: string, STANDALONE: string }} + */ +var Networks = { + PUBLIC: 'Public Global Stellar Network ; September 2015', + TESTNET: 'Test SDF Network ; September 2015', + FUTURENET: 'Test SDF Future Network ; October 2022', + SANDBOX: 'Local Sandbox Stellar Network ; September 2022', + STANDALONE: 'Standalone Network ; February 2017' +}; +;// ./src/soroban.js +function soroban_typeof(o) { "@babel/helpers - typeof"; return soroban_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, soroban_typeof(o); } +function _toArray(r) { return soroban_arrayWithHoles(r) || soroban_iterableToArray(r) || soroban_unsupportedIterableToArray(r) || soroban_nonIterableRest(); } +function soroban_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function soroban_unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return soroban_arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? soroban_arrayLikeToArray(r, a) : void 0; } } +function soroban_arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function soroban_iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function soroban_arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function soroban_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function soroban_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, soroban_toPropertyKey(o.key), o); } } +function soroban_createClass(e, r, t) { return r && soroban_defineProperties(e.prototype, r), t && soroban_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function soroban_toPropertyKey(t) { var i = soroban_toPrimitive(t, "string"); return "symbol" == soroban_typeof(i) ? i : i + ""; } +function soroban_toPrimitive(t, r) { if ("object" != soroban_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != soroban_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/* Helper class to assist with formatting and parsing token amounts. */ +var Soroban = /*#__PURE__*/function () { + function Soroban() { + soroban_classCallCheck(this, Soroban); + } + return soroban_createClass(Soroban, null, [{ + key: "formatTokenAmount", + value: + /** + * Given a whole number smart contract amount of a token and an amount of + * decimal places (if the token has any), it returns a "display" value. + * + * All arithmetic inside the contract is performed on integers to avoid + * potential precision and consistency issues of floating-point. + * + * @param {string} amount the token amount you want to display + * @param {number} decimals specify how many decimal places a token has + * + * @returns {string} the display value + * @throws {TypeError} if the given amount has a decimal point already + * @example + * formatTokenAmount("123000", 4) === "12.3"; + */ + function formatTokenAmount(amount, decimals) { + if (amount.includes('.')) { + throw new TypeError('No decimals are allowed'); + } + var formatted = amount; + if (decimals > 0) { + if (decimals > formatted.length) { + formatted = ['0', formatted.toString().padStart(decimals, '0')].join('.'); + } else { + formatted = [formatted.slice(0, -decimals), formatted.slice(-decimals)].join('.'); + } + } + + // remove trailing zero if any + return formatted.replace(/(\.\d*?)0+$/, '$1'); + } + + /** + * Parse a token amount to use it on smart contract + * + * This function takes the display value and its decimals (if the token has + * any) and returns a string that'll be used within the smart contract. + * + * @param {string} value the token amount you want to use it on smart + * contract which you've been displaying in a UI + * @param {number} decimals the number of decimal places expected in the + * display value (different than the "actual" number, because suffix zeroes + * might not be present) + * + * @returns {string} the whole number token amount represented by the display + * value with the decimal places shifted over + * + * @example + * const displayValueAmount = "123.4560" + * const parsedAmtForSmartContract = parseTokenAmount(displayValueAmount, 5); + * parsedAmtForSmartContract === "12345600" + */ + }, { + key: "parseTokenAmount", + value: function parseTokenAmount(value, decimals) { + var _fraction$padEnd; + var _value$split$slice = value.split('.').slice(), + _value$split$slice2 = _toArray(_value$split$slice), + whole = _value$split$slice2[0], + fraction = _value$split$slice2[1], + rest = _value$split$slice2.slice(2); + if (rest.length) { + throw new Error("Invalid decimal value: ".concat(value)); + } + var shifted = BigInt(whole + ((_fraction$padEnd = fraction === null || fraction === void 0 ? void 0 : fraction.padEnd(decimals, '0')) !== null && _fraction$padEnd !== void 0 ? _fraction$padEnd : '0'.repeat(decimals))); + return shifted.toString(); + } + }]); +}(); +;// ./src/contract.js +function contract_typeof(o) { "@babel/helpers - typeof"; return contract_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, contract_typeof(o); } +function contract_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function contract_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, contract_toPropertyKey(o.key), o); } } +function contract_createClass(e, r, t) { return r && contract_defineProperties(e.prototype, r), t && contract_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function contract_toPropertyKey(t) { var i = contract_toPrimitive(t, "string"); return "symbol" == contract_typeof(i) ? i : i + ""; } +function contract_toPrimitive(t, r) { if ("object" != contract_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != contract_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + +/** + * Create a new Contract object. + * + * `Contract` represents a single contract in the Stellar network, embodying the + * interface of the contract. See + * [Contracts](https://soroban.stellar.org/docs/learn/interacting-with-contracts) + * for more information about how contracts work in Stellar. + * + * @constructor + * + * @param {string} contractId - ID of the contract (ex. + * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`). + */ +var Contract = /*#__PURE__*/function () { + function Contract(contractId) { + contract_classCallCheck(this, Contract); + try { + // First, try it as a strkey + this._id = StrKey.decodeContract(contractId); + } catch (_) { + throw new Error("Invalid contract ID: ".concat(contractId)); + } + } + + /** + * Returns Stellar contract ID as a strkey, ex. + * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`. + * @returns {string} + */ + return contract_createClass(Contract, [{ + key: "contractId", + value: function contractId() { + return StrKey.encodeContract(this._id); + } + + /** @returns {string} the ID as a strkey (C...) */ + }, { + key: "toString", + value: function toString() { + return this.contractId(); + } + + /** @returns {Address} the wrapped address of this contract */ + }, { + key: "address", + value: function address() { + return Address.contract(this._id); + } + + /** + * Returns an operation that will invoke this contract call. + * + * @param {string} method name of the method to call + * @param {...xdr.ScVal} params arguments to pass to the function call + * + * @returns {xdr.Operation} an InvokeHostFunctionOp operation to call the + * contract with the given method and parameters + * + * @see Operation.invokeHostFunction + * @see Operation.invokeContractFunction + * @see Operation.createCustomContract + * @see Operation.createStellarAssetContract + * @see Operation.uploadContractWasm + */ + }, { + key: "call", + value: function call(method) { + for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + params[_key - 1] = arguments[_key]; + } + return Operation.invokeContractFunction({ + contract: this.address().toString(), + "function": method, + args: params + }); + } + + /** + * Returns the read-only footprint entries necessary for any invocations to + * this contract, for convenience when manually adding it to your + * transaction's overall footprint or doing bump/restore operations. + * + * @returns {xdr.LedgerKey} the ledger key for the deployed contract instance + */ + }, { + key: "getFootprint", + value: function getFootprint() { + return src_xdr.LedgerKey.contractData(new src_xdr.LedgerKeyContractData({ + contract: this.address().toScAddress(), + key: src_xdr.ScVal.scvLedgerKeyContractInstance(), + durability: src_xdr.ContractDataDurability.persistent() + })); + } + }]); +}(); +;// ./src/numbers/uint128.js +function uint128_typeof(o) { "@babel/helpers - typeof"; return uint128_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, uint128_typeof(o); } +function uint128_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function uint128_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, uint128_toPropertyKey(o.key), o); } } +function uint128_createClass(e, r, t) { return r && uint128_defineProperties(e.prototype, r), t && uint128_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function uint128_toPropertyKey(t) { var i = uint128_toPrimitive(t, "string"); return "symbol" == uint128_typeof(i) ? i : i + ""; } +function uint128_toPrimitive(t, r) { if ("object" != uint128_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != uint128_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function uint128_callSuper(t, o, e) { return o = uint128_getPrototypeOf(o), uint128_possibleConstructorReturn(t, uint128_isNativeReflectConstruct() ? Reflect.construct(o, e || [], uint128_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function uint128_possibleConstructorReturn(t, e) { if (e && ("object" == uint128_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return uint128_assertThisInitialized(t); } +function uint128_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function uint128_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (uint128_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function uint128_getPrototypeOf(t) { return uint128_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, uint128_getPrototypeOf(t); } +function uint128_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && uint128_setPrototypeOf(t, e); } +function uint128_setPrototypeOf(t, e) { return uint128_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, uint128_setPrototypeOf(t, e); } + +var Uint128 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct an unsigned 128-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Uint128() { + uint128_classCallCheck(this, Uint128); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return uint128_callSuper(this, Uint128, [args]); + } + uint128_inherits(Uint128, _LargeInt); + return uint128_createClass(Uint128, [{ + key: "unsigned", + get: function get() { + return true; + } + }, { + key: "size", + get: function get() { + return 128; + } + }]); +}(xdr.LargeInt); +Uint128.defineIntBoundaries(); +;// ./src/numbers/uint256.js +function uint256_typeof(o) { "@babel/helpers - typeof"; return uint256_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, uint256_typeof(o); } +function uint256_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function uint256_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, uint256_toPropertyKey(o.key), o); } } +function uint256_createClass(e, r, t) { return r && uint256_defineProperties(e.prototype, r), t && uint256_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function uint256_toPropertyKey(t) { var i = uint256_toPrimitive(t, "string"); return "symbol" == uint256_typeof(i) ? i : i + ""; } +function uint256_toPrimitive(t, r) { if ("object" != uint256_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != uint256_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function uint256_callSuper(t, o, e) { return o = uint256_getPrototypeOf(o), uint256_possibleConstructorReturn(t, uint256_isNativeReflectConstruct() ? Reflect.construct(o, e || [], uint256_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function uint256_possibleConstructorReturn(t, e) { if (e && ("object" == uint256_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return uint256_assertThisInitialized(t); } +function uint256_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function uint256_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (uint256_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function uint256_getPrototypeOf(t) { return uint256_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, uint256_getPrototypeOf(t); } +function uint256_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && uint256_setPrototypeOf(t, e); } +function uint256_setPrototypeOf(t, e) { return uint256_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, uint256_setPrototypeOf(t, e); } + +var Uint256 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct an unsigned 256-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Uint256() { + uint256_classCallCheck(this, Uint256); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return uint256_callSuper(this, Uint256, [args]); + } + uint256_inherits(Uint256, _LargeInt); + return uint256_createClass(Uint256, [{ + key: "unsigned", + get: function get() { + return true; + } + }, { + key: "size", + get: function get() { + return 256; + } + }]); +}(xdr.LargeInt); +Uint256.defineIntBoundaries(); +;// ./src/numbers/int128.js +function int128_typeof(o) { "@babel/helpers - typeof"; return int128_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, int128_typeof(o); } +function int128_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function int128_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, int128_toPropertyKey(o.key), o); } } +function int128_createClass(e, r, t) { return r && int128_defineProperties(e.prototype, r), t && int128_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function int128_toPropertyKey(t) { var i = int128_toPrimitive(t, "string"); return "symbol" == int128_typeof(i) ? i : i + ""; } +function int128_toPrimitive(t, r) { if ("object" != int128_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != int128_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function int128_callSuper(t, o, e) { return o = int128_getPrototypeOf(o), int128_possibleConstructorReturn(t, int128_isNativeReflectConstruct() ? Reflect.construct(o, e || [], int128_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function int128_possibleConstructorReturn(t, e) { if (e && ("object" == int128_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return int128_assertThisInitialized(t); } +function int128_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function int128_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (int128_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function int128_getPrototypeOf(t) { return int128_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, int128_getPrototypeOf(t); } +function int128_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && int128_setPrototypeOf(t, e); } +function int128_setPrototypeOf(t, e) { return int128_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, int128_setPrototypeOf(t, e); } + +var Int128 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct a signed 128-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Int128() { + int128_classCallCheck(this, Int128); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return int128_callSuper(this, Int128, [args]); + } + int128_inherits(Int128, _LargeInt); + return int128_createClass(Int128, [{ + key: "unsigned", + get: function get() { + return false; + } + }, { + key: "size", + get: function get() { + return 128; + } + }]); +}(xdr.LargeInt); +Int128.defineIntBoundaries(); +;// ./src/numbers/int256.js +function int256_typeof(o) { "@babel/helpers - typeof"; return int256_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, int256_typeof(o); } +function int256_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function int256_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, int256_toPropertyKey(o.key), o); } } +function int256_createClass(e, r, t) { return r && int256_defineProperties(e.prototype, r), t && int256_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function int256_toPropertyKey(t) { var i = int256_toPrimitive(t, "string"); return "symbol" == int256_typeof(i) ? i : i + ""; } +function int256_toPrimitive(t, r) { if ("object" != int256_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != int256_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function int256_callSuper(t, o, e) { return o = int256_getPrototypeOf(o), int256_possibleConstructorReturn(t, int256_isNativeReflectConstruct() ? Reflect.construct(o, e || [], int256_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function int256_possibleConstructorReturn(t, e) { if (e && ("object" == int256_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return int256_assertThisInitialized(t); } +function int256_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function int256_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (int256_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function int256_getPrototypeOf(t) { return int256_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, int256_getPrototypeOf(t); } +function int256_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && int256_setPrototypeOf(t, e); } +function int256_setPrototypeOf(t, e) { return int256_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, int256_setPrototypeOf(t, e); } + +var Int256 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct a signed 256-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Int256() { + int256_classCallCheck(this, Int256); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return int256_callSuper(this, Int256, [args]); + } + int256_inherits(Int256, _LargeInt); + return int256_createClass(Int256, [{ + key: "unsigned", + get: function get() { + return false; + } + }, { + key: "size", + get: function get() { + return 256; + } + }]); +}(xdr.LargeInt); +Int256.defineIntBoundaries(); +;// ./src/numbers/xdr_large_int.js +function xdr_large_int_typeof(o) { "@babel/helpers - typeof"; return xdr_large_int_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, xdr_large_int_typeof(o); } +function xdr_large_int_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function xdr_large_int_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, xdr_large_int_toPropertyKey(o.key), o); } } +function xdr_large_int_createClass(e, r, t) { return r && xdr_large_int_defineProperties(e.prototype, r), t && xdr_large_int_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function xdr_large_int_defineProperty(e, r, t) { return (r = xdr_large_int_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function xdr_large_int_toPropertyKey(t) { var i = xdr_large_int_toPrimitive(t, "string"); return "symbol" == xdr_large_int_typeof(i) ? i : i + ""; } +function xdr_large_int_toPrimitive(t, r) { if ("object" != xdr_large_int_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != xdr_large_int_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/* eslint no-bitwise: ["error", {"allow": [">>"]}] */ + + + + + + + +/** + * A wrapper class to represent large XDR-encodable integers. + * + * This operates at a lower level than {@link ScInt} by forcing you to specify + * the type / width / size in bits of the integer you're targeting, regardless + * of the input value(s) you provide. + * + * @param {string} type - force a specific data type. the type choices are: + * 'i64', 'u64', 'i128', 'u128', 'i256', and 'u256' (default: the smallest + * one that fits the `value`) (see {@link XdrLargeInt.isType}) + * @param {number|bigint|string|Array} values a list of + * integer-like values interpreted in big-endian order + */ +var XdrLargeInt = /*#__PURE__*/function () { + function XdrLargeInt(type, values) { + xdr_large_int_classCallCheck(this, XdrLargeInt); + /** @type {xdr.LargeInt} */ + xdr_large_int_defineProperty(this, "int", void 0); + // child class of a jsXdr.LargeInt + /** @type {string} */ + xdr_large_int_defineProperty(this, "type", void 0); + if (!(values instanceof Array)) { + values = [values]; + } + + // normalize values to one type + values = values.map(function (i) { + // micro-optimization to no-op on the likeliest input value: + if (typeof i === 'bigint') { + return i; + } + if (i instanceof XdrLargeInt) { + return i.toBigInt(); + } + return BigInt(i); + }); + switch (type) { + case 'i64': + this["int"] = new xdr.Hyper(values); + break; + case 'i128': + this["int"] = new Int128(values); + break; + case 'i256': + this["int"] = new Int256(values); + break; + case 'u64': + this["int"] = new xdr.UnsignedHyper(values); + break; + case 'u128': + this["int"] = new Uint128(values); + break; + case 'u256': + this["int"] = new Uint256(values); + break; + default: + throw TypeError("invalid type: ".concat(type)); + } + this.type = type; + } + + /** + * @returns {number} + * @throws {RangeError} if the value can't fit into a Number + */ + return xdr_large_int_createClass(XdrLargeInt, [{ + key: "toNumber", + value: function toNumber() { + var bi = this["int"].toBigInt(); + if (bi > Number.MAX_SAFE_INTEGER || bi < Number.MIN_SAFE_INTEGER) { + throw RangeError("value ".concat(bi, " not in range for Number ") + "[".concat(Number.MAX_SAFE_INTEGER, ", ").concat(Number.MIN_SAFE_INTEGER, "]")); + } + return Number(bi); + } + + /** @returns {bigint} */ + }, { + key: "toBigInt", + value: function toBigInt() { + return this["int"].toBigInt(); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = I64` */ + }, { + key: "toI64", + value: function toI64() { + this._sizeCheck(64); + var v = this.toBigInt(); + if (BigInt.asIntN(64, v) !== v) { + throw RangeError("value too large for i64: ".concat(v)); + } + return src_xdr.ScVal.scvI64(new src_xdr.Int64(v)); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = U64` */ + }, { + key: "toU64", + value: function toU64() { + this._sizeCheck(64); + return src_xdr.ScVal.scvU64(new src_xdr.Uint64(BigInt.asUintN(64, this.toBigInt())) // reiterpret as unsigned + ); + } + + /** + * @returns {xdr.ScVal} the integer encoded with `ScValType = I128` + * @throws {RangeError} if the value cannot fit in 128 bits + */ + }, { + key: "toI128", + value: function toI128() { + this._sizeCheck(128); + var v = this["int"].toBigInt(); + var hi64 = BigInt.asIntN(64, v >> 64n); // encode top 64 w/ sign bit + var lo64 = BigInt.asUintN(64, v); // grab btm 64, encode sign + + return src_xdr.ScVal.scvI128(new src_xdr.Int128Parts({ + hi: new src_xdr.Int64(hi64), + lo: new src_xdr.Uint64(lo64) + })); + } + + /** + * @returns {xdr.ScVal} the integer encoded with `ScValType = U128` + * @throws {RangeError} if the value cannot fit in 128 bits + */ + }, { + key: "toU128", + value: function toU128() { + this._sizeCheck(128); + var v = this["int"].toBigInt(); + return src_xdr.ScVal.scvU128(new src_xdr.UInt128Parts({ + hi: new src_xdr.Uint64(BigInt.asUintN(64, v >> 64n)), + lo: new src_xdr.Uint64(BigInt.asUintN(64, v)) + })); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = I256` */ + }, { + key: "toI256", + value: function toI256() { + var v = this["int"].toBigInt(); + var hiHi64 = BigInt.asIntN(64, v >> 192n); // keep sign bit + var hiLo64 = BigInt.asUintN(64, v >> 128n); + var loHi64 = BigInt.asUintN(64, v >> 64n); + var loLo64 = BigInt.asUintN(64, v); + return src_xdr.ScVal.scvI256(new src_xdr.Int256Parts({ + hiHi: new src_xdr.Int64(hiHi64), + hiLo: new src_xdr.Uint64(hiLo64), + loHi: new src_xdr.Uint64(loHi64), + loLo: new src_xdr.Uint64(loLo64) + })); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = U256` */ + }, { + key: "toU256", + value: function toU256() { + var v = this["int"].toBigInt(); + var hiHi64 = BigInt.asUintN(64, v >> 192n); // encode sign bit + var hiLo64 = BigInt.asUintN(64, v >> 128n); + var loHi64 = BigInt.asUintN(64, v >> 64n); + var loLo64 = BigInt.asUintN(64, v); + return src_xdr.ScVal.scvU256(new src_xdr.UInt256Parts({ + hiHi: new src_xdr.Uint64(hiHi64), + hiLo: new src_xdr.Uint64(hiLo64), + loHi: new src_xdr.Uint64(loHi64), + loLo: new src_xdr.Uint64(loLo64) + })); + } + + /** @returns {xdr.ScVal} the smallest interpretation of the stored value */ + }, { + key: "toScVal", + value: function toScVal() { + switch (this.type) { + case 'i64': + return this.toI64(); + case 'i128': + return this.toI128(); + case 'i256': + return this.toI256(); + case 'u64': + return this.toU64(); + case 'u128': + return this.toU128(); + case 'u256': + return this.toU256(); + default: + throw TypeError("invalid type: ".concat(this.type)); + } + } + }, { + key: "valueOf", + value: function valueOf() { + return this["int"].valueOf(); + } + }, { + key: "toString", + value: function toString() { + return this["int"].toString(); + } + }, { + key: "toJSON", + value: function toJSON() { + return { + value: this.toBigInt().toString(), + type: this.type + }; + } + }, { + key: "_sizeCheck", + value: function _sizeCheck(bits) { + if (this["int"].size > bits) { + throw RangeError("value too large for ".concat(bits, " bits (").concat(this.type, ")")); + } + } + }], [{ + key: "isType", + value: function isType(type) { + switch (type) { + case 'i64': + case 'i128': + case 'i256': + case 'u64': + case 'u128': + case 'u256': + return true; + default: + return false; + } + } + + /** + * Convert the raw `ScValType` string (e.g. 'scvI128', generated by the XDR) + * to a type description for {@link XdrLargeInt} construction (e.g. 'i128') + * + * @param {string} scvType the `xdr.ScValType` as a string + * @returns {string} a suitable equivalent type to construct this object + */ + }, { + key: "getType", + value: function getType(scvType) { + return scvType.slice(3).toLowerCase(); + } + }]); +}(); +;// ./src/numbers/sc_int.js +function sc_int_typeof(o) { "@babel/helpers - typeof"; return sc_int_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, sc_int_typeof(o); } +function sc_int_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, sc_int_toPropertyKey(o.key), o); } } +function sc_int_createClass(e, r, t) { return r && sc_int_defineProperties(e.prototype, r), t && sc_int_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function sc_int_toPropertyKey(t) { var i = sc_int_toPrimitive(t, "string"); return "symbol" == sc_int_typeof(i) ? i : i + ""; } +function sc_int_toPrimitive(t, r) { if ("object" != sc_int_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != sc_int_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function sc_int_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function sc_int_callSuper(t, o, e) { return o = sc_int_getPrototypeOf(o), sc_int_possibleConstructorReturn(t, sc_int_isNativeReflectConstruct() ? Reflect.construct(o, e || [], sc_int_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function sc_int_possibleConstructorReturn(t, e) { if (e && ("object" == sc_int_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return sc_int_assertThisInitialized(t); } +function sc_int_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function sc_int_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (sc_int_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function sc_int_getPrototypeOf(t) { return sc_int_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, sc_int_getPrototypeOf(t); } +function sc_int_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && sc_int_setPrototypeOf(t, e); } +function sc_int_setPrototypeOf(t, e) { return sc_int_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, sc_int_setPrototypeOf(t, e); } + + +/** + * Provides an easier way to manipulate large numbers for Stellar operations. + * + * You can instantiate this "**s**mart **c**ontract integer" value either from + * bigints, strings, or numbers (whole numbers, or this will throw). + * + * If you need to create a native BigInt from a list of integer "parts" (for + * example, you have a series of encoded 32-bit integers that represent a larger + * value), you can use the lower level abstraction {@link XdrLargeInt}. For + * example, you could do `new XdrLargeInt('u128', bytes...).toBigInt()`. + * + * @example + * import { xdr, ScInt, scValToBigInt } from "@stellar/stellar-base"; + * + * // You have an ScVal from a contract and want to parse it into JS native. + * const value = xdr.ScVal.fromXDR(someXdr, "base64"); + * const bigi = scValToBigInt(value); // grab it as a BigInt + * let sci = new ScInt(bigi); + * + * sci.toNumber(); // gives native JS type (w/ size check) + * sci.toBigInt(); // gives the native BigInt value + * sci.toU64(); // gives ScValType-specific XDR constructs (with size checks) + * + * // You have a number and want to shove it into a contract. + * sci = ScInt(0xdeadcafebabe); + * sci.toBigInt() // returns 244838016400062n + * sci.toNumber() // throws: too large + * + * // Pass any to e.g. a Contract.call(), conversion happens automatically + * // regardless of the initial type. + * const scValU128 = sci.toU128(); + * const scValI256 = sci.toI256(); + * const scValU64 = sci.toU64(); + * + * // Lots of ways to initialize: + * ScInt("123456789123456789") + * ScInt(123456789123456789n); + * ScInt(1n << 140n); + * ScInt(-42); + * ScInt(scValToBigInt(scValU128)); // from above + * + * // If you know the type ahead of time (accessing `.raw` is faster than + * // conversions), you can specify the type directly (otherwise, it's + * // interpreted from the numbers you pass in): + * const i = ScInt(123456789n, { type: "u256" }); + * + * // For example, you can use the underlying `sdk.U256` and convert it to an + * // `xdr.ScVal` directly like so: + * const scv = new xdr.ScVal.scvU256(i.raw); + * + * // Or reinterpret it as a different type (size permitting): + * const scv = i.toI64(); + * + * @param {number|bigint|string} value - a single, integer-like value which will + * be interpreted in the smallest appropriate XDR type supported by Stellar + * (64, 128, or 256 bit integer values). signed values are supported, though + * they are sanity-checked against `opts.type`. if you need 32-bit values, + * you can construct them directly without needing this wrapper, e.g. + * `xdr.ScVal.scvU32(1234)`. + * + * @param {object} [opts] - an optional object controlling optional parameters + * @param {string} [opts.type] - force a specific data type. the type choices + * are: 'i64', 'u64', 'i128', 'u128', 'i256', and 'u256' (default: the + * smallest one that fits the `value`) + * + * @throws {RangeError} if the `value` is invalid (e.g. floating point), too + * large (i.e. exceeds a 256-bit value), or doesn't fit in the `opts.type` + * @throws {TypeError} on missing parameters, or if the "signedness" of `opts` + * doesn't match input `value`, e.g. passing `{type: 'u64'}` yet passing -1n + * @throws {SyntaxError} if a string `value` can't be parsed as a big integer + */ +var ScInt = /*#__PURE__*/function (_XdrLargeInt) { + function ScInt(value, opts) { + var _opts$type; + sc_int_classCallCheck(this, ScInt); + var signed = value < 0; + var type = (_opts$type = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type !== void 0 ? _opts$type : ''; + if (type.startsWith('u') && signed) { + throw TypeError("specified type ".concat(opts.type, " yet negative (").concat(value, ")")); + } + + // If unspecified, we make a best guess at the type based on the bit length + // of the value, treating 64 as a minimum and 256 as a maximum. + if (type === '') { + type = signed ? 'i' : 'u'; + var bitlen = nearestBigIntSize(value); + switch (bitlen) { + case 64: + case 128: + case 256: + type += bitlen.toString(); + break; + default: + throw RangeError("expected 64/128/256 bits for input (".concat(value, "), got ").concat(bitlen)); + } + } + return sc_int_callSuper(this, ScInt, [type, value]); + } + sc_int_inherits(ScInt, _XdrLargeInt); + return sc_int_createClass(ScInt); +}(XdrLargeInt); +function nearestBigIntSize(bigI) { + var _find; + // Note: Even though BigInt.toString(2) includes the negative sign for + // negative values (???), the following is still accurate, because the + // negative sign would be represented by a sign bit. + var bitlen = bigI.toString(2).length; + return (_find = [64, 128, 256].find(function (len) { + return bitlen <= len; + })) !== null && _find !== void 0 ? _find : bitlen; +} +;// ./src/numbers/index.js + + + + + + + + +/** + * Transforms an opaque {@link xdr.ScVal} into a native bigint, if possible. + * + * If you then want to use this in the abstractions provided by this module, + * you can pass it to the constructor of {@link XdrLargeInt}. + * + * @example + * let scv = contract.call("add", x, y); // assume it returns an xdr.ScVal + * let bigi = scValToBigInt(scv); + * + * new ScInt(bigi); // if you don't care about types, and + * new XdrLargeInt('i128', bigi); // if you do + * + * @param {xdr.ScVal} scv - the raw XDR value to parse into an integer + * @returns {bigint} the native value of this input value + * + * @throws {TypeError} if the `scv` input value doesn't represent an integer + */ +function scValToBigInt(scv) { + var scIntType = XdrLargeInt.getType(scv["switch"]().name); + switch (scv["switch"]().name) { + case 'scvU32': + case 'scvI32': + return BigInt(scv.value()); + case 'scvU64': + case 'scvI64': + return new XdrLargeInt(scIntType, scv.value()).toBigInt(); + case 'scvU128': + case 'scvI128': + return new XdrLargeInt(scIntType, [scv.value().lo(), scv.value().hi()]).toBigInt(); + case 'scvU256': + case 'scvI256': + return new XdrLargeInt(scIntType, [scv.value().loLo(), scv.value().loHi(), scv.value().hiLo(), scv.value().hiHi()]).toBigInt(); + default: + throw TypeError("expected integer type, got ".concat(scv["switch"]())); + } +} +;// ./src/scval.js +/* provided dependency */ var scval_Buffer = __webpack_require__(3626)["A"]; +function scval_slicedToArray(r, e) { return scval_arrayWithHoles(r) || scval_iterableToArrayLimit(r, e) || scval_unsupportedIterableToArray(r, e) || scval_nonIterableRest(); } +function scval_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function scval_unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return scval_arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? scval_arrayLikeToArray(r, a) : void 0; } } +function scval_arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function scval_iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function scval_arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function scval_typeof(o) { "@babel/helpers - typeof"; return scval_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, scval_typeof(o); } + + + + + +/** + * Attempts to convert native types into smart contract values + * ({@link xdr.ScVal}). + * + * Provides conversions from smart contract XDR values ({@link xdr.ScVal}) to + * native JavaScript types. + * + * The conversions are as follows: + * + * - xdr.ScVal -> passthrough + * - null/undefined -> scvVoid + * - string -> scvString (a copy is made) + * - UintArray8 -> scvBytes (a copy is made) + * - boolean -> scvBool + * + * - number/bigint -> the smallest possible XDR integer type that will fit the + * input value (if you want a specific type, use {@link ScInt}) + * + * - {@link Address} or {@link Contract} -> scvAddress (for contracts and + * public keys) + * + * - Array -> scvVec after attempting to convert each item of type `T` to an + * xdr.ScVal (recursively). note that all values must be the same type! + * + * - object -> scvMap after attempting to convert each key and value to an + * xdr.ScVal (recursively). note that there is no restriction on types + * matching anywhere (unlike arrays) + * + * When passing an integer-like native value, you can also optionally specify a + * type which will force a particular interpretation of that value. + * + * Note that not all type specifications are compatible with all `ScVal`s, e.g. + * `toScVal("a string", {type: "i256"})` will throw. + * + * @param {any} val - a native (or convertible) input value to wrap + * @param {object} [opts] - an optional set of hints around the type of + * conversion you'd like to see + * @param {string} [opts.type] - there is different behavior for different input + * types for `val`: + * + * - when `val` is an integer-like type (i.e. number|bigint), this will be + * forwarded to {@link ScInt} or forced to be u32/i32. + * + * - when `val` is an array type, this is forwarded to the recursion + * + * - when `val` is an object type (key-value entries), this should be an + * object in which each key has a pair of types (to represent forced types + * for the key and the value), where `null` (or a missing entry) indicates + * the default interpretation(s) (refer to the examples, below) + * + * - when `val` is a string type, this can be 'string' or 'symbol' to force + * a particular interpretation of `val`. + * + * - when `val` is a bytes-like type, this can be 'string', 'symbol', or + * 'bytes' to force a particular interpretation + * + * As a simple example, `nativeToScVal("hello", {type: 'symbol'})` will + * return an `scvSymbol`, whereas without the type it would have been an + * `scvString`. + * + * @returns {xdr.ScVal} a wrapped, smart, XDR version of the input value + * @throws {TypeError} if... + * - there are arrays with more than one type in them + * - there are values that do not have a sensible conversion (e.g. random XDR + * types, custom classes) + * - the type of the input object (or some inner value of said object) cannot + * be determined (via `typeof`) + * - the type you specified (via `opts.type`) is incompatible with the value + * you passed in (`val`), e.g. `nativeToScVal("a string", { type: 'i128' })`, + * though this does not apply for types that ignore `opts` (e.g. addresses). + * @see scValToNative + * + * @example + * nativeToScVal(1000); // gives ScValType === scvU64 + * nativeToScVal(1000n); // gives ScValType === scvU64 + * nativeToScVal(1n << 100n); // gives ScValType === scvU128 + * nativeToScVal(1000, { type: 'u32' }); // gives ScValType === scvU32 + * nativeToScVal(1000, { type: 'i125' }); // gives ScValType === scvI256 + * nativeToScVal("a string"); // gives ScValType === scvString + * nativeToScVal("a string", { type: 'symbol' }); // gives scvSymbol + * nativeToScVal(new Uint8Array(5)); // scvBytes + * nativeToScVal(new Uint8Array(5), { type: 'symbol' }); // scvSymbol + * nativeToScVal(null); // scvVoid + * nativeToScVal(true); // scvBool + * nativeToScVal([1, 2, 3]); // gives scvVec with each element as scvU64 + * nativeToScVal([1, 2, 3], { type: 'i128' }); // scvVec + * nativeToScVal({ 'hello': 1, 'world': [ true, false ] }, { + * type: { + * 'hello': [ 'symbol', 'i128' ], + * } + * }) + * // gives scvMap with entries: [ + * // [ scvSymbol, scvI128 ], + * // [ scvString, scvArray ] + * // ] + * + * @example + * import { + * nativeToScVal, + * scValToNative, + * ScInt, + * xdr + * } from '@stellar/stellar-base'; + * + * let gigaMap = { + * bool: true, + * void: null, + * u32: xdr.ScVal.scvU32(1), + * i32: xdr.ScVal.scvI32(1), + * u64: 1n, + * i64: -1n, + * u128: new ScInt(1).toU128(), + * i128: new ScInt(1).toI128(), + * u256: new ScInt(1).toU256(), + * i256: new ScInt(1).toI256(), + * map: { + * arbitrary: 1n, + * nested: 'values', + * etc: false + * }, + * vec: ['same', 'type', 'list'], + * }; + * + * // then, simply: + * let scv = nativeToScVal(gigaMap); // scv.switch() == xdr.ScValType.scvMap() + * + * // then... + * someContract.call("method", scv); + * + * // Similarly, the inverse should work: + * scValToNative(scv) == gigaMap; // true + */ +function nativeToScVal(val) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + switch (scval_typeof(val)) { + case 'object': + { + var _val$constructor$name, _val$constructor; + if (val === null) { + return src_xdr.ScVal.scvVoid(); + } + if (val instanceof src_xdr.ScVal) { + return val; // should we copy? + } + if (val instanceof Address) { + return val.toScVal(); + } + if (val instanceof Contract) { + return val.address().toScVal(); + } + if (val instanceof Uint8Array || scval_Buffer.isBuffer(val)) { + var _opts$type; + var copy = Uint8Array.from(val); + switch ((_opts$type = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type !== void 0 ? _opts$type : 'bytes') { + case 'bytes': + return src_xdr.ScVal.scvBytes(copy); + case 'symbol': + return src_xdr.ScVal.scvSymbol(copy); + case 'string': + return src_xdr.ScVal.scvString(copy); + default: + throw new TypeError("invalid type (".concat(opts.type, ") specified for bytes-like value")); + } + } + if (Array.isArray(val)) { + if (val.length > 0 && val.some(function (v) { + return scval_typeof(v) !== scval_typeof(val[0]); + })) { + throw new TypeError("array values (".concat(val, ") must have the same type (types: ").concat(val.map(function (v) { + return scval_typeof(v); + }).join(','), ")")); + } + return src_xdr.ScVal.scvVec(val.map(function (v) { + return nativeToScVal(v, opts); + })); + } + if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : '') !== 'Object') { + var _val$constructor2; + throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")")); + } + return src_xdr.ScVal.scvMap(Object.entries(val) + // The Soroban runtime expects maps to have their keys in sorted + // order, so let's do that here as part of the conversion to prevent + // confusing error messages on execution. + .sort(function (_ref, _ref2) { + var _ref3 = scval_slicedToArray(_ref, 1), + key1 = _ref3[0]; + var _ref4 = scval_slicedToArray(_ref2, 1), + key2 = _ref4[0]; + return key1.localeCompare(key2); + }).map(function (_ref5) { + var _k, _opts$type2; + var _ref6 = scval_slicedToArray(_ref5, 2), + k = _ref6[0], + v = _ref6[1]; + // the type can be specified with an entry for the key and the value, + // e.g. val = { 'hello': 1 } and opts.type = { hello: [ 'symbol', + // 'u128' ]} or you can use `null` for the default interpretation + var _ref7 = (_k = ((_opts$type2 = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type2 !== void 0 ? _opts$type2 : {})[k]) !== null && _k !== void 0 ? _k : [null, null], + _ref8 = scval_slicedToArray(_ref7, 2), + keyType = _ref8[0], + valType = _ref8[1]; + var keyOpts = keyType ? { + type: keyType + } : {}; + var valOpts = valType ? { + type: valType + } : {}; + return new src_xdr.ScMapEntry({ + key: nativeToScVal(k, keyOpts), + val: nativeToScVal(v, valOpts) + }); + })); + } + case 'number': + case 'bigint': + switch (opts === null || opts === void 0 ? void 0 : opts.type) { + case 'u32': + return src_xdr.ScVal.scvU32(val); + case 'i32': + return src_xdr.ScVal.scvI32(val); + default: + break; + } + return new ScInt(val, { + type: opts === null || opts === void 0 ? void 0 : opts.type + }).toScVal(); + case 'string': + { + var _opts$type3; + var optType = (_opts$type3 = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type3 !== void 0 ? _opts$type3 : 'string'; + switch (optType) { + case 'string': + return src_xdr.ScVal.scvString(val); + case 'symbol': + return src_xdr.ScVal.scvSymbol(val); + case 'address': + return new Address(val).toScVal(); + case 'u32': + return src_xdr.ScVal.scvU32(parseInt(val, 10)); + case 'i32': + return src_xdr.ScVal.scvI32(parseInt(val, 10)); + default: + if (XdrLargeInt.isType(optType)) { + return new XdrLargeInt(optType, val).toScVal(); + } + throw new TypeError("invalid type (".concat(opts.type, ") specified for string value")); + } + } + case 'boolean': + return src_xdr.ScVal.scvBool(val); + case 'undefined': + return src_xdr.ScVal.scvVoid(); + case 'function': + // FIXME: Is this too helpful? + return nativeToScVal(val()); + default: + throw new TypeError("failed to convert typeof ".concat(scval_typeof(val), " (").concat(val, ")")); + } +} + +/** + * Given a smart contract value, attempt to convert it to a native type. + * Possible conversions include: + * + * - void -> `null` + * - u32, i32 -> `number` + * - u64, i64, u128, i128, u256, i256 -> `bigint` + * - vec -> `Array` of any of the above (via recursion) + * - map -> key-value object of any of the above (via recursion) + * - bool -> `boolean` + * - bytes -> `Uint8Array` + * - symbol -> `string` + * - string -> `string` IF the underlying buffer can be decoded as ascii/utf8, + * `Uint8Array` of the raw contents in any error case + * + * If no viable conversion can be determined, this just "unwraps" the smart + * value to return its underlying XDR value. + * + * @param {xdr.ScVal} scv - the input smart contract value + * + * @returns {any} + * @see nativeToScVal + */ +function scValToNative(scv) { + var _scv$vec, _scv$map; + // we use the verbose xdr.ScValType..value form here because it's faster + // than string comparisons and the underlying constants never need to be + // updated + switch (scv["switch"]().value) { + case src_xdr.ScValType.scvVoid().value: + return null; + + // these can be converted to bigints directly + case src_xdr.ScValType.scvU64().value: + case src_xdr.ScValType.scvI64().value: + return scv.value().toBigInt(); + + // these can be parsed by internal abstractions note that this can also + // handle the above two cases, but it's not as efficient (another + // type-check, parsing, etc.) + case src_xdr.ScValType.scvU128().value: + case src_xdr.ScValType.scvI128().value: + case src_xdr.ScValType.scvU256().value: + case src_xdr.ScValType.scvI256().value: + return scValToBigInt(scv); + case src_xdr.ScValType.scvVec().value: + return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(scValToNative); + case src_xdr.ScValType.scvAddress().value: + return Address.fromScVal(scv).toString(); + case src_xdr.ScValType.scvMap().value: + return Object.fromEntries(((_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []).map(function (entry) { + return [scValToNative(entry.key()), scValToNative(entry.val())]; + })); + + // these return the primitive type directly + case src_xdr.ScValType.scvBool().value: + case src_xdr.ScValType.scvU32().value: + case src_xdr.ScValType.scvI32().value: + case src_xdr.ScValType.scvBytes().value: + return scv.value(); + + // Symbols are limited to [a-zA-Z0-9_]+, so we can safely make ascii strings + // + // Strings, however, are "presented" as strings and we treat them as such + // (in other words, string = bytes with a hint that it's text). If the user + // encoded non-printable bytes in their string value, that's on them. + // + // Note that we assume a utf8 encoding (ascii-compatible). For other + // encodings, you should probably use bytes anyway. If it cannot be decoded, + // the raw bytes are returned. + case src_xdr.ScValType.scvSymbol().value: + case src_xdr.ScValType.scvString().value: + { + var v = scv.value(); // string|Buffer + if (scval_Buffer.isBuffer(v) || ArrayBuffer.isView(v)) { + try { + return new TextDecoder().decode(v); + } catch (e) { + return new Uint8Array(v.buffer); // copy of bytes + } + } + return v; // string already + } + + // these can be converted to bigint + case src_xdr.ScValType.scvTimepoint().value: + case src_xdr.ScValType.scvDuration().value: + return new src_xdr.Uint64(scv.value()).toBigInt(); + case src_xdr.ScValType.scvError().value: + switch (scv.error()["switch"]().value) { + // Distinguish errors from the user contract. + case src_xdr.ScErrorType.sceContract().value: + return { + type: 'contract', + code: scv.error().contractCode() + }; + default: + { + var err = scv.error(); + return { + type: 'system', + code: err.code().value, + value: err.code().name + }; + } + } + + // in the fallthrough case, just return the underlying value directly + default: + return scv.value(); + } +} +;// ./src/events.js +function events_typeof(o) { "@babel/helpers - typeof"; return events_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, events_typeof(o); } +function events_ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function events_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? events_ownKeys(Object(t), !0).forEach(function (r) { events_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : events_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function events_defineProperty(e, r, t) { return (r = events_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function events_toPropertyKey(t) { var i = events_toPrimitive(t, "string"); return "symbol" == events_typeof(i) ? i : i + ""; } +function events_toPrimitive(t, r) { if ("object" != events_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != events_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + +/** + * Converts raw diagnostic or contract events into something with a flatter, + * human-readable, and understandable structure. + * + * @param {xdr.DiagnosticEvent[] | xdr.ContractEvent[]} events either contract + * events or diagnostic events to parse into a friendly format + * + * @returns {SorobanEvent[]} a list of human-readable event structures, where + * each element has the following properties: + * - type: a string of one of 'system', 'contract', 'diagnostic + * - contractId?: optionally, a `C...` encoded strkey + * - topics: a list of {@link scValToNative} invocations on the topics + * - data: similarly, a {@link scValToNative} invocation on the raw event data + */ +function humanizeEvents(events) { + return events.map(function (e) { + // A pseudo-instanceof check for xdr.DiagnosticEvent more reliable + // in mixed SDK environments: + if (e.inSuccessfulContractCall) { + return extractEvent(e.event()); + } + return extractEvent(e); + }); +} +function extractEvent(event) { + return events_objectSpread(events_objectSpread({}, typeof event.contractId === 'function' && event.contractId() != null && { + contractId: StrKey.encodeContract(event.contractId()) + }), {}, { + type: event.type().name, + topics: event.body().value().topics().map(function (t) { + return scValToNative(t); + }), + data: scValToNative(event.body().value().data()) + }); +} +;// ./src/auth.js +/* provided dependency */ var auth_Buffer = __webpack_require__(3626)["A"]; +function auth_typeof(o) { "@babel/helpers - typeof"; return auth_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, auth_typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == auth_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(auth_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + + + + + + + + +/** + * @async + * @callback SigningCallback A callback for signing an XDR structure + * representing all of the details necessary to authorize an invocation tree. + * + * @param {xdr.HashIdPreimage} preimage the entire authorization envelope + * whose hash you should sign, so that you can inspect the entire structure + * if necessary (rather than blindly signing a hash) + * + * @returns {Promise} the signature of the raw payload (which is + * the sha256 hash of the preimage bytes, so `hash(preimage.toXDR())`) signed + * by the key corresponding to the public key in the entry you pass to + * {@link authorizeEntry} (decipherable from its + * `credentials().address().address()`) + */ + +/** + * Actually authorizes an existing authorization entry using the given the + * credentials and expiration details, returning a signed copy. + * + * This "fills out" the authorization entry with a signature, indicating to the + * {@link Operation.invokeHostFunction} its attached to that: + * - a particular identity (i.e. signing {@link Keypair} or other signer) + * - approving the execution of an invocation tree (i.e. a simulation-acquired + * {@link xdr.SorobanAuthorizedInvocation} or otherwise built) + * - on a particular network (uniquely identified by its passphrase, see + * {@link Networks}) + * - until a particular ledger sequence is reached. + * + * This one lets you pass a either a {@link Keypair} (or, more accurately, + * anything with a `sign(Buffer): Buffer` method) or a callback function (see + * {@link SigningCallback}) to handle signing the envelope hash. + * + * @param {xdr.SorobanAuthorizationEntry} entry an unsigned authorization entr + * @param {Keypair | SigningCallback} signer either a {@link Keypair} instance + * or a function which takes a payload (a + * {@link xdr.HashIdPreimageSorobanAuthorization} instance) input and returns + * the signature of the hash of the raw payload bytes (where the signing key + * should correspond to the address in the `entry`) + * @param {number} validUntilLedgerSeq the (exclusive) future ledger sequence + * number until which this authorization entry should be valid (if + * `currentLedgerSeq==validUntil`, this is expired)) + * @param {string} [networkPassphrase] the network passphrase is incorprated + * into the signature (see {@link Networks} for options) + * + * @returns {Promise} a promise for an + * authorization entry that you can pass along to + * {@link Operation.invokeHostFunction} + * + * @note If using the `SigningCallback` variation, the signer is assumed to be + * the entry's credential address. If you need a different key to sign the + * entry, you will need to use different method (e.g., fork this code). + * + * @see authorizeInvocation + * @example + * import { + * SorobanRpc, + * Transaction, + * Networks, + * authorizeEntry + * } from '@stellar/stellar-sdk'; + * + * // Assume signPayloadCallback is a well-formed signing callback. + * // + * // It might, for example, pop up a modal from a browser extension, send the + * // transaction to a third-party service for signing, or just do simple + * // signing via Keypair like it does here: + * function signPayloadCallback(payload) { + * return signer.sign(hash(payload.toXDR()); + * } + * + * function multiPartyAuth( + * server: SorobanRpc.Server, + * // assume this involves multi-party auth + * tx: Transaction, + * ) { + * return server + * .simulateTransaction(tx) + * .then((simResult) => { + * tx.operations[0].auth.map(entry => + * authorizeEntry( + * entry, + * signPayloadCallback, + * currentLedger + 1000, + * Networks.TESTNET); + * )); + * + * return server.prepareTransaction(tx, simResult); + * }) + * .then((preppedTx) => { + * preppedTx.sign(source); + * return server.sendTransaction(preppedTx); + * }); + * } + */ +function authorizeEntry(_x, _x2, _x3) { + return _authorizeEntry.apply(this, arguments); +} + +/** + * This builds an entry from scratch, allowing you to express authorization as a + * function of: + * - a particular identity (i.e. signing {@link Keypair} or other signer) + * - approving the execution of an invocation tree (i.e. a simulation-acquired + * {@link xdr.SorobanAuthorizedInvocation} or otherwise built) + * - on a particular network (uniquely identified by its passphrase, see + * {@link Networks}) + * - until a particular ledger sequence is reached. + * + * This is in contrast to {@link authorizeEntry}, which signs an existing entry. + * + * @param {Keypair | SigningCallback} signer either a {@link Keypair} instance + * (or anything with a `.sign(buf): Buffer-like` method) or a function which + * takes a payload (a {@link xdr.HashIdPreimageSorobanAuthorization} + * instance) input and returns the signature of the hash of the raw payload + * bytes (where the signing key should correspond to the address in the + * `entry`) + * @param {number} validUntilLedgerSeq the (exclusive) future ledger sequence + * number until which this authorization entry should be valid (if + * `currentLedgerSeq==validUntilLedgerSeq`, this is expired)) + * @param {xdr.SorobanAuthorizedInvocation} invocation the invocation tree that + * we're authorizing (likely, this comes from transaction simulation) + * @param {string} [publicKey] the public identity of the signer (when + * providing a {@link Keypair} to `signer`, this can be omitted, as it just + * uses {@link Keypair.publicKey}) + * @param {string} [networkPassphrase] the network passphrase is incorprated + * into the signature (see {@link Networks} for options, default: + * {@link Networks.FUTURENET}) + * + * @returns {Promise} a promise for an + * authorization entry that you can pass along to + * {@link Operation.invokeHostFunction} + * + * @see authorizeEntry + */ +function _authorizeEntry() { + _authorizeEntry = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(entry, signer, validUntilLedgerSeq) { + var networkPassphrase, + clone, + addrAuth, + networkId, + preimage, + payload, + signature, + publicKey, + sigScVal, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + networkPassphrase = _args.length > 3 && _args[3] !== undefined ? _args[3] : Networks.FUTURENET; + if (!(entry.credentials()["switch"]().value !== src_xdr.SorobanCredentialsType.sorobanCredentialsAddress().value)) { + _context.next = 3; + break; + } + return _context.abrupt("return", entry); + case 3: + clone = src_xdr.SorobanAuthorizationEntry.fromXDR(entry.toXDR()); + /** @type {xdr.SorobanAddressCredentials} */ + addrAuth = clone.credentials().address(); + addrAuth.signatureExpirationLedger(validUntilLedgerSeq); + networkId = hashing_hash(auth_Buffer.from(networkPassphrase)); + preimage = src_xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(new src_xdr.HashIdPreimageSorobanAuthorization({ + networkId: networkId, + nonce: addrAuth.nonce(), + invocation: clone.rootInvocation(), + signatureExpirationLedger: addrAuth.signatureExpirationLedger() + })); + payload = hashing_hash(preimage.toXDR()); + if (!(typeof signer === 'function')) { + _context.next = 18; + break; + } + _context.t0 = auth_Buffer; + _context.next = 13; + return signer(preimage); + case 13: + _context.t1 = _context.sent; + signature = _context.t0.from.call(_context.t0, _context.t1); + publicKey = Address.fromScAddress(addrAuth.address()).toString(); + _context.next = 20; + break; + case 18: + signature = auth_Buffer.from(signer.sign(payload)); + publicKey = signer.publicKey(); + case 20: + if (Keypair.fromPublicKey(publicKey).verify(payload, signature)) { + _context.next = 22; + break; + } + throw new Error("signature doesn't match payload"); + case 22: + // This structure is defined here: + // https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#stellar-account-signatures + // + // Encoding a contract structure as an ScVal means the map keys are supposed + // to be symbols, hence the forced typing here. + sigScVal = nativeToScVal({ + public_key: StrKey.decodeEd25519PublicKey(publicKey), + signature: signature + }, { + type: { + public_key: ['symbol', null], + signature: ['symbol', null] + } + }); + addrAuth.signature(src_xdr.ScVal.scvVec([sigScVal])); + return _context.abrupt("return", clone); + case 25: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _authorizeEntry.apply(this, arguments); +} +function authorizeInvocation(signer, validUntilLedgerSeq, invocation) { + var publicKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; + var networkPassphrase = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Networks.FUTURENET; + // We use keypairs as a source of randomness for the nonce to avoid mucking + // with any crypto dependencies. Note that this just has to be random and + // unique, not cryptographically secure, so it's fine. + var kp = Keypair.random().rawPublicKey(); + var nonce = new src_xdr.Int64(bytesToInt64(kp)); + var pk = publicKey || signer.publicKey(); + if (!pk) { + throw new Error("authorizeInvocation requires publicKey parameter"); + } + var entry = new src_xdr.SorobanAuthorizationEntry({ + rootInvocation: invocation, + credentials: src_xdr.SorobanCredentials.sorobanCredentialsAddress(new src_xdr.SorobanAddressCredentials({ + address: new Address(pk).toScAddress(), + nonce: nonce, + signatureExpirationLedger: 0, + // replaced + signature: src_xdr.ScVal.scvVec([]) // replaced + })) + }); + return authorizeEntry(entry, signer, validUntilLedgerSeq, networkPassphrase); +} +function bytesToInt64(bytes) { + // eslint-disable-next-line no-bitwise + return bytes.subarray(0, 8).reduce(function (accum, b) { + return accum << 8 | b; + }, 0); +} +;// ./src/invocation.js +function invocation_typeof(o) { "@babel/helpers - typeof"; return invocation_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, invocation_typeof(o); } +function invocation_ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function invocation_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? invocation_ownKeys(Object(t), !0).forEach(function (r) { invocation_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : invocation_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function invocation_defineProperty(e, r, t) { return (r = invocation_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function invocation_toPropertyKey(t) { var i = invocation_toPrimitive(t, "string"); return "symbol" == invocation_typeof(i) ? i : i + ""; } +function invocation_toPrimitive(t, r) { if ("object" != invocation_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != invocation_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + +/** + * @typedef CreateInvocation + * + * @prop {'wasm'|'sac'} type a type indicating if this creation was a custom + * contract or a wrapping of an existing Stellar asset + * @prop {string} [token] when `type=='sac'`, the canonical {@link Asset} that + * is being wrapped by this Stellar Asset Contract + * @prop {object} [wasm] when `type=='wasm'`, add'l creation parameters + * + * @prop {string} wasm.hash hex hash of WASM bytecode backing this contract + * @prop {string} wasm.address contract address of this deployment + * @prop {string} wasm.salt hex salt that the user consumed when creating + * this contract (encoded in the resulting address) + * @prop {any[]} [wasm.constructorArgs] a list of natively-represented values + * (see {@link scValToNative}) that are passed to the constructor when + * creating this contract + */ + +/** + * @typedef ExecuteInvocation + * + * @prop {string} source the strkey of the contract (C...) being invoked + * @prop {string} function the name of the function being invoked + * @prop {any[]} args the natively-represented parameters to the function + * invocation (see {@link scValToNative} for rules on how they're + * represented a JS types) + */ + +/** + * @typedef InvocationTree + * @prop {'execute' | 'create'} type the type of invocation occurring, either + * contract creation or host function execution + * @prop {CreateInvocation | ExecuteInvocation} args the parameters to the + * invocation, depending on the type + * @prop {InvocationTree[]} invocations any sub-invocations that (may) occur + * as a result of this invocation (i.e. a tree of call stacks) + */ + +/** + * Turns a raw invocation tree into a human-readable format. + * + * This is designed to make the invocation tree easier to understand in order to + * inform users about the side-effects of their contract calls. This will help + * make informed decisions about whether or not a particular invocation will + * result in what you expect it to. + * + * @param {xdr.SorobanAuthorizedInvocation} root the raw XDR of the invocation, + * likely acquired from transaction simulation. this is either from the + * {@link Operation.invokeHostFunction} itself (the `func` field), or from + * the authorization entries ({@link xdr.SorobanAuthorizationEntry}, the + * `rootInvocation` field) + * + * @returns {InvocationTree} a human-readable version of the invocation tree + * + * @example + * Here, we show a browser modal after simulating an arbitrary transaction, + * `tx`, which we assume has an `Operation.invokeHostFunction` inside of it: + * + * ```typescript + * import { Server, buildInvocationTree } from '@stellar/stellar-sdk'; + * + * const s = new Server("fill in accordingly"); + * + * s.simulateTransaction(tx).then( + * (resp: SorobanRpc.SimulateTransactionResponse) => { + * if (SorobanRpc.isSuccessfulSim(resp) && ) { + * // bold assumption: there's a valid result with an auth entry + * alert( + * "You are authorizing the following invocation:\n" + + * JSON.stringify( + * buildInvocationTree(resp.result!.auth[0].rootInvocation()), + * null, + * 2 + * ) + * ); + * } + * } + * ); + * ``` + */ +function buildInvocationTree(root) { + var fn = root["function"](); + + /** @type {InvocationTree} */ + var output = {}; + + /** @type {xdr.CreateContractArgs|xdr.CreateContractArgsV2|xdr.InvokeContractArgs} */ + var inner = fn.value(); + switch (fn["switch"]().value) { + // sorobanAuthorizedFunctionTypeContractFn + case 0: + output.type = 'execute'; + output.args = { + source: Address.fromScAddress(inner.contractAddress()).toString(), + "function": inner.functionName(), + args: inner.args().map(function (arg) { + return scValToNative(arg); + }) + }; + break; + + // sorobanAuthorizedFunctionTypeCreateContractHostFn + // sorobanAuthorizedFunctionTypeCreateContractV2HostFn + case 1: // fallthrough: just no ctor args in V1 + case 2: + { + var createV2 = fn["switch"]().value === 2; + output.type = 'create'; + output.args = {}; + + // If the executable is a WASM, the preimage MUST be an address. If it's a + // token, the preimage MUST be an asset. This is a cheeky way to check + // that, because wasm=0, token=1 and address=0, asset=1 in the XDR switch + // values. + // + // The first part may not be true in V2, but we'd need to update this code + // anyway so it can still be an error. + var _ref = [inner.executable(), inner.contractIdPreimage()], + exec = _ref[0], + preimage = _ref[1]; + if (!!exec["switch"]().value !== !!preimage["switch"]().value) { + throw new Error("creation function appears invalid: ".concat(JSON.stringify(inner), " (should be wasm+address or token+asset)")); + } + switch (exec["switch"]().value) { + // contractExecutableWasm + case 0: + { + /** @type {xdr.ContractIdPreimageFromAddress} */ + var details = preimage.fromAddress(); + output.args.type = 'wasm'; + output.args.wasm = invocation_objectSpread({ + salt: details.salt().toString('hex'), + hash: exec.wasmHash().toString('hex'), + address: Address.fromScAddress(details.address()).toString() + }, createV2 && { + constructorArgs: inner.constructorArgs().map(function (arg) { + return scValToNative(arg); + }) + }); + break; + } + + // contractExecutableStellarAsset + case 1: + output.args.type = 'sac'; + output.args.asset = Asset.fromOperation(preimage.fromAsset()).toString(); + break; + default: + throw new Error("unknown creation type: ".concat(JSON.stringify(exec))); + } + break; + } + default: + throw new Error("unknown invocation type (".concat(fn["switch"](), "): ").concat(JSON.stringify(fn))); + } + output.invocations = root.subInvocations().map(function (i) { + return buildInvocationTree(i); + }); + return output; +} + +/** + * @callback InvocationWalker + * + * @param {xdr.SorobanAuthorizedInvocation} node the currently explored node + * @param {number} depth the depth of the tree this node is occurring at (the + * root starts at a depth of 1) + * @param {xdr.SorobanAuthorizedInvocation} [parent] this `node`s parent node, + * if any (i.e. this doesn't exist at the root) + * + * @returns {boolean|null|void} returning exactly `false` is a hint to stop + * exploring, other values are ignored + */ + +/** + * Executes a callback function on each node in the tree until stopped. + * + * Nodes are walked in a depth-first order. Returning `false` from the callback + * stops further depth exploration at that node, but it does not stop the walk + * in a "global" view. + * + * @param {xdr.SorobanAuthorizedInvocation} root the tree to explore + * @param {InvocationWalker} callback the callback to execute for each node + * @returns {void} + */ +function walkInvocationTree(root, callback) { + walkHelper(root, 1, callback); +} +function walkHelper(node, depth, callback, parent) { + if (callback(node, depth, parent) === false /* allow void rv */) { + return; + } + node.subInvocations().forEach(function (i) { + return walkHelper(i, depth + 1, callback, node); + }); +} +;// ./src/index.js +/* module decorator */ module = __webpack_require__.hmd(module); +/* eslint-disable import/no-import-module-exports */ + + + + + + + + + + + + + + + + + + + + + + + + + + + +// +// Soroban +// + + + + + + + + + +/* harmony default export */ const src = (module.exports); + +/***/ }), + +/***/ 5360: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +/** + * Generate a character map. + * @param {string} alphabet e.g. "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" + * @param {object} mappings map overrides from key to value + * @method + */ + +var charmap = function (alphabet, mappings) { + mappings || (mappings = {}); + alphabet.split("").forEach(function (c, i) { + if (!(c in mappings)) mappings[c] = i; + }); + return mappings; +} + +/** + * The RFC 4648 base 32 alphabet and character map. + * @see {@link https://tools.ietf.org/html/rfc4648} + */ + +var rfc4648 = { + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", + charmap: { + 0: 14, + 1: 8 + } +}; + +rfc4648.charmap = charmap(rfc4648.alphabet, rfc4648.charmap); + +/** + * The Crockford base 32 alphabet and character map. + * @see {@link http://www.crockford.com/wrmg/base32.html} + */ + +var crockford = { + alphabet: "0123456789ABCDEFGHJKMNPQRSTVWXYZ", + charmap: { + O: 0, + I: 1, + L: 1 + } +}; + +crockford.charmap = charmap(crockford.alphabet, crockford.charmap); + +/** + * base32hex + * @see {@link https://en.wikipedia.org/wiki/Base32#base32hex} + */ + +var base32hex = { + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", + charmap: {} +}; + +base32hex.charmap = charmap(base32hex.alphabet, base32hex.charmap); + +/** + * Create a new `Decoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [charmap] Override the character map used in decoding. + * @constructor + */ + +function Decoder (options) { + this.buf = []; + this.shift = 8; + this.carry = 0; + + if (options) { + + switch (options.type) { + case "rfc4648": + this.charmap = exports.rfc4648.charmap; + break; + case "crockford": + this.charmap = exports.crockford.charmap; + break; + case "base32hex": + this.charmap = exports.base32hex.charmap; + break; + default: + throw new Error("invalid type"); + } + + if (options.charmap) this.charmap = options.charmap; + } +} + +/** + * The default character map coresponds to RFC4648. + */ + +Decoder.prototype.charmap = rfc4648.charmap; + +/** + * Decode a string, continuing from the previous state. + * + * @param {string} str + * @return {Decoder} this + */ + +Decoder.prototype.write = function (str) { + var charmap = this.charmap; + var buf = this.buf; + var shift = this.shift; + var carry = this.carry; + + // decode string + str.toUpperCase().split("").forEach(function (char) { + + // ignore padding + if (char == "=") return; + + // lookup symbol + var symbol = charmap[char] & 0xff; + + // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 + + shift -= 5; + if (shift > 0) { + carry |= symbol << shift; + } else if (shift < 0) { + buf.push(carry | (symbol >> -shift)); + shift += 8; + carry = (symbol << shift) & 0xff; + } else { + buf.push(carry | symbol); + shift = 8; + carry = 0; + } + }); + + // save state + this.shift = shift; + this.carry = carry; + + // for chaining + return this; +}; + +/** + * Finish decoding. + * + * @param {string} [str] The final string to decode. + * @return {Array} Decoded byte array. + */ + +Decoder.prototype.finalize = function (str) { + if (str) { + this.write(str); + } + if (this.shift !== 8 && this.carry !== 0) { + this.buf.push(this.carry); + this.shift = 8; + this.carry = 0; + } + return this.buf; +}; + +/** + * Create a new `Encoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [alphabet] Override the alphabet used in encoding. + * @constructor + */ + +function Encoder (options) { + this.buf = ""; + this.shift = 3; + this.carry = 0; + + if (options) { + + switch (options.type) { + case "rfc4648": + this.alphabet = exports.rfc4648.alphabet; + break; + case "crockford": + this.alphabet = exports.crockford.alphabet; + break; + case "base32hex": + this.alphabet = exports.base32hex.alphabet; + break; + default: + throw new Error("invalid type"); + } + + if (options.alphabet) this.alphabet = options.alphabet; + else if (options.lc) this.alphabet = this.alphabet.toLowerCase(); + } +} + +/** + * The default alphabet coresponds to RFC4648. + */ + +Encoder.prototype.alphabet = rfc4648.alphabet; + +/** + * Encode a byte array, continuing from the previous state. + * + * @param {byte[]} buf The byte array to encode. + * @return {Encoder} this + */ + +Encoder.prototype.write = function (buf) { + var shift = this.shift; + var carry = this.carry; + var symbol; + var byte; + var i; + + // encode each byte in buf + for (i = 0; i < buf.length; i++) { + byte = buf[i]; + + // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 + + symbol = carry | (byte >> shift); + this.buf += this.alphabet[symbol & 0x1f]; + + if (shift > 5) { + shift -= 5; + symbol = byte >> shift; + this.buf += this.alphabet[symbol & 0x1f]; + } + + shift = 5 - shift; + carry = byte << shift; + shift = 8 - shift; + } + + // save state + this.shift = shift; + this.carry = carry; + + // for chaining + return this; +}; + +/** + * Finish encoding. + * + * @param {byte[]} [buf] The final byte array to encode. + * @return {string} The encoded byte array. + */ + +Encoder.prototype.finalize = function (buf) { + if (buf) { + this.write(buf); + } + if (this.shift !== 3) { + this.buf += this.alphabet[this.carry & 0x1f]; + this.shift = 3; + this.carry = 0; + } + return this.buf; +}; + +/** + * Convenience encoder. + * + * @param {byte[]} buf The byte array to encode. + * @param {object} [options] Options to pass to the encoder. + * @return {string} The encoded string. + */ + +exports.encode = function (buf, options) { + return new Encoder(options).finalize(buf); +}; + +/** + * Convenience decoder. + * + * @param {string} str The string to decode. + * @param {object} [options] Options to pass to the decoder. + * @return {byte[]} The decoded byte array. + */ + +exports.decode = function (str, options) { + return new Decoder(options).finalize(str); +}; + +// Exports. +exports.Decoder = Decoder; +exports.Encoder = Encoder; +exports.charmap = charmap; +exports.crockford = crockford; +exports.rfc4648 = rfc4648; +exports.base32hex = base32hex; + + +/***/ }), + +/***/ 7526: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + + +/***/ }), + +/***/ 8287: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var console = __webpack_require__(6763); +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + + + +const base64 = __webpack_require__(7526) +const ieee754 = __webpack_require__(251) +const customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +const K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + const arr = new Uint8Array(1) + const proto = { foo: function () { return 42 } } + Object.setPrototypeOf(proto, Uint8Array.prototype) + Object.setPrototypeOf(arr, proto) + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + const buf = new Uint8Array(length) + Object.setPrototypeOf(buf, Buffer.prototype) + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + const valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + const b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) +Object.setPrototypeOf(Buffer, Uint8Array) + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + const length = byteLength(string, encoding) | 0 + let buf = createBuffer(length) + + const actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0 + const buf = createBuffer(length) + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView) + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + let buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype) + + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + const len = checked(obj.length) | 0 + const buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + let x = a.length + let y = b.length + + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + let i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + const buffer = Buffer.allocUnsafe(length) + let pos = 0 + for (i = 0; i < list.length; ++i) { + let buf = list[i] + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) + buf.copy(buffer, pos) + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ) + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos) + } + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + const len = string.length + const mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + let loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + let loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + const i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + const len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + const len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + const len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + const length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + let str = '' + const max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + let x = thisEnd - thisStart + let y = end - start + const len = Math.min(x, y) + + const thisCopy = this.slice(thisStart, thisEnd) + const targetCopy = target.slice(start, end) + + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + let indexSize = 1 + let arrLength = arr.length + let valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + let i + if (dir) { + let foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + let found = true + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + const remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + const strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + let i + for (i = 0; i < length; ++i) { + const parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + const remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + let loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + const res = [] + + let i = start + while (i < end) { + const firstByte = buf[i] + let codePoint = null + let bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +const MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + const len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + let res = '' + let i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + const len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + let out = '' + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]] + } + return out +} + +function utf16leSlice (buf, start, end) { + const bytes = buf.slice(start, end) + let res = '' + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + const len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + const newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype) + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + let val = this[offset + --byteLength] + let mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const lo = first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24 + + const hi = this[++offset] + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + last * 2 ** 24 + + return BigInt(lo) + (BigInt(hi) << BigInt(32)) +}) + +Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const hi = first * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + const lo = this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last + + return (BigInt(hi) << BigInt(32)) + BigInt(lo) +}) + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let i = byteLength + let mul = 1 + let val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = this[offset + 4] + + this[offset + 5] * 2 ** 8 + + this[offset + 6] * 2 ** 16 + + (last << 24) // Overflow + + return (BigInt(val) << BigInt(32)) + + BigInt(first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24) +}) + +Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + return (BigInt(val) << BigInt(32)) + + BigInt(this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last) +}) + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let mul = 1 + let i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let i = byteLength - 1 + let mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function wrtBigUInt64LE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + return offset +} + +function wrtBigUInt64BE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset + 7] = lo + lo = lo >> 8 + buf[offset + 6] = lo + lo = lo >> 8 + buf[offset + 5] = lo + lo = lo >> 8 + buf[offset + 4] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset + 3] = hi + hi = hi >> 8 + buf[offset + 2] = hi + hi = hi >> 8 + buf[offset + 1] = hi + hi = hi >> 8 + buf[offset] = hi + return offset + 8 +} + +Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = 0 + let mul = 1 + let sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = byteLength - 1 + let mul = 1 + let sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + const len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + const code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } else if (typeof val === 'boolean') { + val = Number(val) + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + let i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + const bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + const len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// CUSTOM ERRORS +// ============= + +// Simplified versions from Node, changed for Buffer-only usage +const errors = {} +function E (sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor () { + super() + + Object.defineProperty(this, 'message', { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }) + + // Add the error code to the name to include it in the stack trace. + this.name = `${this.name} [${sym}]` + // Access the stack to generate the error message including the error code + // from the name. + this.stack // eslint-disable-line no-unused-expressions + // Reset the name to the actual name. + delete this.name + } + + get code () { + return sym + } + + set code (value) { + Object.defineProperty(this, 'code', { + configurable: true, + enumerable: true, + value, + writable: true + }) + } + + toString () { + return `${this.name} [${sym}]: ${this.message}` + } + } +} + +E('ERR_BUFFER_OUT_OF_BOUNDS', + function (name) { + if (name) { + return `${name} is outside of buffer bounds` + } + + return 'Attempt to access memory outside buffer bounds' + }, RangeError) +E('ERR_INVALID_ARG_TYPE', + function (name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}` + }, TypeError) +E('ERR_OUT_OF_RANGE', + function (str, range, input) { + let msg = `The value of "${str}" is out of range.` + let received = input + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)) + } else if (typeof input === 'bigint') { + received = String(input) + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received) + } + received += 'n' + } + msg += ` It must be ${range}. Received ${received}` + return msg + }, RangeError) + +function addNumericalSeparator (val) { + let res = '' + let i = val.length + const start = val[0] === '-' ? 1 : 0 + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}` + } + return `${val.slice(0, i)}${res}` +} + +// CHECK FUNCTIONS +// =============== + +function checkBounds (buf, offset, byteLength) { + validateNumber(offset, 'offset') + if (buf[offset] === undefined || buf[offset + byteLength] === undefined) { + boundsError(offset, buf.length - (byteLength + 1)) + } +} + +function checkIntBI (value, min, max, buf, offset, byteLength) { + if (value > max || value < min) { + const n = typeof min === 'bigint' ? 'n' : '' + let range + if (byteLength > 3) { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}` + } else { + range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` + + `${(byteLength + 1) * 8 - 1}${n}` + } + } else { + range = `>= ${min}${n} and <= ${max}${n}` + } + throw new errors.ERR_OUT_OF_RANGE('value', range, value) + } + checkBounds(buf, offset, byteLength) +} + +function validateNumber (value, name) { + if (typeof value !== 'number') { + throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value) + } +} + +function boundsError (value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type) + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value) + } + + if (length < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS() + } + + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', + `>= ${type ? 1 : 0} and <= ${length}`, + value) +} + +// HELPER FUNCTIONS +// ================ + +const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function utf8ToBytes (string, units) { + units = units || Infinity + let codePoint + const length = string.length + let leadSurrogate = null + const bytes = [] + + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + let c, hi, lo + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + let i + for (i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +const hexSliceLookupTable = (function () { + const alphabet = '0123456789abcdef' + const table = new Array(256) + for (let i = 0; i < 16; ++i) { + const i16 = i * 16 + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})() + +// Return not function with Error if BigInt not supported +function defineBigIntMethod (fn) { + return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn +} + +function BufferBigIntNotDefined () { + throw new Error('BigInt not supported') +} + + +/***/ }), + +/***/ 8075: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); + +var callBind = __webpack_require__(487); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; + + +/***/ }), + +/***/ 487: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var bind = __webpack_require__(6743); +var GetIntrinsic = __webpack_require__(453); +var setFunctionLength = __webpack_require__(6897); + +var $TypeError = __webpack_require__(9675); +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + +var $defineProperty = __webpack_require__(655); +var $max = GetIntrinsic('%Math.max%'); + +module.exports = function callBind(originalFunction) { + if (typeof originalFunction !== 'function') { + throw new $TypeError('a function is required'); + } + var func = $reflectApply(bind, $call, arguments); + return setFunctionLength( + func, + 1 + $max(0, originalFunction.length - (arguments.length - 1)), + true + ); +}; + +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} + + +/***/ }), + +/***/ 6763: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/*global window, global*/ +var util = __webpack_require__(537) +var assert = __webpack_require__(4148) +function now() { return new Date().getTime() } + +var slice = Array.prototype.slice +var console +var times = {} + +if (typeof __webpack_require__.g !== "undefined" && __webpack_require__.g.console) { + console = __webpack_require__.g.console +} else if (typeof window !== "undefined" && window.console) { + console = window.console +} else { + console = {} +} + +var functions = [ + [log, "log"], + [info, "info"], + [warn, "warn"], + [error, "error"], + [time, "time"], + [timeEnd, "timeEnd"], + [trace, "trace"], + [dir, "dir"], + [consoleAssert, "assert"] +] + +for (var i = 0; i < functions.length; i++) { + var tuple = functions[i] + var f = tuple[0] + var name = tuple[1] + + if (!console[name]) { + console[name] = f + } +} + +module.exports = console + +function log() {} + +function info() { + console.log.apply(console, arguments) +} + +function warn() { + console.log.apply(console, arguments) +} + +function error() { + console.warn.apply(console, arguments) +} + +function time(label) { + times[label] = now() +} + +function timeEnd(label) { + var time = times[label] + if (!time) { + throw new Error("No such label: " + label) + } + + delete times[label] + var duration = now() - time + console.log(label + ": " + duration + "ms") +} + +function trace() { + var err = new Error() + err.name = "Trace" + err.message = util.format.apply(null, arguments) + console.error(err.stack) +} + +function dir(object) { + console.log(util.inspect(object) + "\n") +} + +function consoleAssert(expression) { + if (!expression) { + var arr = slice.call(arguments, 1) + assert.ok(false, util.format.apply(null, arr)) + } +} + + +/***/ }), + +/***/ 41: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var $defineProperty = __webpack_require__(655); + +var $SyntaxError = __webpack_require__(8068); +var $TypeError = __webpack_require__(9675); + +var gopd = __webpack_require__(5795); + +/** @type {import('.')} */ +module.exports = function defineDataProperty( + obj, + property, + value +) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new $TypeError('`obj` must be an object or a function`'); + } + if (typeof property !== 'string' && typeof property !== 'symbol') { + throw new $TypeError('`property` must be a string or a symbol`'); + } + if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { + throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null'); + } + if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { + throw new $TypeError('`nonWritable`, if provided, must be a boolean or null'); + } + if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { + throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null'); + } + if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { + throw new $TypeError('`loose`, if provided, must be a boolean'); + } + + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + + /* @type {false | TypedPropertyDescriptor} */ + var desc = !!gopd && gopd(obj, property); + + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value: value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { + // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable + obj[property] = value; // eslint-disable-line no-param-reassign + } else { + throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); + } +}; + + +/***/ }), + +/***/ 8452: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var keys = __webpack_require__(1189); +var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; + +var toStr = Object.prototype.toString; +var concat = Array.prototype.concat; +var defineDataProperty = __webpack_require__(41); + +var isFunction = function (fn) { + return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; +}; + +var supportsDescriptors = __webpack_require__(592)(); + +var defineProperty = function (object, name, value, predicate) { + if (name in object) { + if (predicate === true) { + if (object[name] === value) { + return; + } + } else if (!isFunction(predicate) || !predicate()) { + return; + } + } + + if (supportsDescriptors) { + defineDataProperty(object, name, value, true); + } else { + defineDataProperty(object, name, value); + } +}; + +var defineProperties = function (object, map) { + var predicates = arguments.length > 2 ? arguments[2] : {}; + var props = keys(map); + if (hasSymbols) { + props = concat.call(props, Object.getOwnPropertySymbols(map)); + } + for (var i = 0; i < props.length; i += 1) { + defineProperty(object, props[i], map[props[i]], predicates[props[i]]); + } +}; + +defineProperties.supportsDescriptors = !!supportsDescriptors; + +module.exports = defineProperties; + + +/***/ }), + +/***/ 655: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); + +/** @type {import('.')} */ +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true) || false; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} + +module.exports = $defineProperty; + + +/***/ }), + +/***/ 1237: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./eval')} */ +module.exports = EvalError; + + +/***/ }), + +/***/ 9383: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +module.exports = Error; + + +/***/ }), + +/***/ 9290: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./range')} */ +module.exports = RangeError; + + +/***/ }), + +/***/ 9538: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./ref')} */ +module.exports = ReferenceError; + + +/***/ }), + +/***/ 8068: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./syntax')} */ +module.exports = SyntaxError; + + +/***/ }), + +/***/ 9675: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./type')} */ +module.exports = TypeError; + + +/***/ }), + +/***/ 5345: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./uri')} */ +module.exports = URIError; + + +/***/ }), + +/***/ 2682: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isCallable = __webpack_require__(9600); + +var toStr = Object.prototype.toString; +var hasOwnProperty = Object.prototype.hasOwnProperty; + +var forEachArray = function forEachArray(array, iterator, receiver) { + for (var i = 0, len = array.length; i < len; i++) { + if (hasOwnProperty.call(array, i)) { + if (receiver == null) { + iterator(array[i], i, array); + } else { + iterator.call(receiver, array[i], i, array); + } + } + } +}; + +var forEachString = function forEachString(string, iterator, receiver) { + for (var i = 0, len = string.length; i < len; i++) { + // no such thing as a sparse string. + if (receiver == null) { + iterator(string.charAt(i), i, string); + } else { + iterator.call(receiver, string.charAt(i), i, string); + } + } +}; + +var forEachObject = function forEachObject(object, iterator, receiver) { + for (var k in object) { + if (hasOwnProperty.call(object, k)) { + if (receiver == null) { + iterator(object[k], k, object); + } else { + iterator.call(receiver, object[k], k, object); + } + } + } +}; + +var forEach = function forEach(list, iterator, thisArg) { + if (!isCallable(iterator)) { + throw new TypeError('iterator must be a function'); + } + + var receiver; + if (arguments.length >= 3) { + receiver = thisArg; + } + + if (toStr.call(list) === '[object Array]') { + forEachArray(list, iterator, receiver); + } else if (typeof list === 'string') { + forEachString(list, iterator, receiver); + } else { + forEachObject(list, iterator, receiver); + } +}; + +module.exports = forEach; + + +/***/ }), + +/***/ 9353: +/***/ ((module) => { + +"use strict"; + + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + + +/***/ }), + +/***/ 6743: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var implementation = __webpack_require__(9353); + +module.exports = Function.prototype.bind || implementation; + + +/***/ }), + +/***/ 453: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var undefined; + +var $Error = __webpack_require__(9383); +var $EvalError = __webpack_require__(1237); +var $RangeError = __webpack_require__(9290); +var $ReferenceError = __webpack_require__(9538); +var $SyntaxError = __webpack_require__(8068); +var $TypeError = __webpack_require__(9675); +var $URIError = __webpack_require__(5345); + +var $Function = Function; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = __webpack_require__(4039)(); +var hasProto = __webpack_require__(24)(); + +var getProto = Object.getPrototypeOf || ( + hasProto + ? function (x) { return x.__proto__; } // eslint-disable-line no-proto + : null +); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = __webpack_require__(6743); +var hasOwn = __webpack_require__(9957); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); +var $exec = bind.call(Function.call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; + + +/***/ }), + +/***/ 5795: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; + + +/***/ }), + +/***/ 592: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var $defineProperty = __webpack_require__(655); + +var hasPropertyDescriptors = function hasPropertyDescriptors() { + return !!$defineProperty; +}; + +hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + // node v0.6 has a bug where array lengths can be Set but not Defined + if (!$defineProperty) { + return null; + } + try { + return $defineProperty([], 'length', { value: 1 }).length !== 1; + } catch (e) { + // In Firefox 4-22, defining length on an array throws an exception. + return true; + } +}; + +module.exports = hasPropertyDescriptors; + + +/***/ }), + +/***/ 24: +/***/ ((module) => { + +"use strict"; + + +var test = { + __proto__: null, + foo: {} +}; + +var $Object = Object; + +/** @type {import('.')} */ +module.exports = function hasProto() { + // @ts-expect-error: TS errors on an inherited property for some reason + return { __proto__: test }.foo === test.foo + && !(test instanceof $Object); +}; + + +/***/ }), + +/***/ 4039: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = __webpack_require__(1333); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; + + +/***/ }), + +/***/ 1333: +/***/ ((module) => { + +"use strict"; + + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; + + +/***/ }), + +/***/ 9092: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hasSymbols = __webpack_require__(1333); + +/** @type {import('.')} */ +module.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; +}; + + +/***/ }), + +/***/ 9957: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = __webpack_require__(6743); + +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); + + +/***/ }), + +/***/ 251: +/***/ ((__unused_webpack_module, exports) => { + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + + +/***/ }), + +/***/ 6698: +/***/ ((module) => { + +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 + } + } +} + + +/***/ }), + +/***/ 7244: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hasToStringTag = __webpack_require__(9092)(); +var callBound = __webpack_require__(8075); + +var $toString = callBound('Object.prototype.toString'); + +var isStandardArguments = function isArguments(value) { + if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { + return false; + } + return $toString(value) === '[object Arguments]'; +}; + +var isLegacyArguments = function isArguments(value) { + if (isStandardArguments(value)) { + return true; + } + return value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + $toString(value) !== '[object Array]' && + $toString(value.callee) === '[object Function]'; +}; + +var supportsStandardArguments = (function () { + return isStandardArguments(arguments); +}()); + +isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests + +module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; + + +/***/ }), + +/***/ 9600: +/***/ ((module) => { + +"use strict"; + + +var fnToStr = Function.prototype.toString; +var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply; +var badArrayLike; +var isCallableMarker; +if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') { + try { + badArrayLike = Object.defineProperty({}, 'length', { + get: function () { + throw isCallableMarker; + } + }); + isCallableMarker = {}; + // eslint-disable-next-line no-throw-literal + reflectApply(function () { throw 42; }, null, badArrayLike); + } catch (_) { + if (_ !== isCallableMarker) { + reflectApply = null; + } + } +} else { + reflectApply = null; +} + +var constructorRegex = /^\s*class\b/; +var isES6ClassFn = function isES6ClassFunction(value) { + try { + var fnStr = fnToStr.call(value); + return constructorRegex.test(fnStr); + } catch (e) { + return false; // not a function + } +}; + +var tryFunctionObject = function tryFunctionToStr(value) { + try { + if (isES6ClassFn(value)) { return false; } + fnToStr.call(value); + return true; + } catch (e) { + return false; + } +}; +var toStr = Object.prototype.toString; +var objectClass = '[object Object]'; +var fnClass = '[object Function]'; +var genClass = '[object GeneratorFunction]'; +var ddaClass = '[object HTMLAllCollection]'; // IE 11 +var ddaClass2 = '[object HTML document.all class]'; +var ddaClass3 = '[object HTMLCollection]'; // IE 9-10 +var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag` + +var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing + +var isDDA = function isDocumentDotAll() { return false; }; +if (typeof document === 'object') { + // Firefox 3 canonicalizes DDA to undefined when it's not accessed directly + var all = document.all; + if (toStr.call(all) === toStr.call(document.all)) { + isDDA = function isDocumentDotAll(value) { + /* globals document: false */ + // in IE 6-8, typeof document.all is "object" and it's truthy + if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) { + try { + var str = toStr.call(value); + return ( + str === ddaClass + || str === ddaClass2 + || str === ddaClass3 // opera 12.16 + || str === objectClass // IE 6-8 + ) && value('') == null; // eslint-disable-line eqeqeq + } catch (e) { /**/ } + } + return false; + }; + } +} + +module.exports = reflectApply + ? function isCallable(value) { + if (isDDA(value)) { return true; } + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + try { + reflectApply(value, null, badArrayLike); + } catch (e) { + if (e !== isCallableMarker) { return false; } + } + return !isES6ClassFn(value) && tryFunctionObject(value); + } + : function isCallable(value) { + if (isDDA(value)) { return true; } + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + if (hasToStringTag) { return tryFunctionObject(value); } + if (isES6ClassFn(value)) { return false; } + var strClass = toStr.call(value); + if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; } + return tryFunctionObject(value); + }; + + +/***/ }), + +/***/ 8184: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var toStr = Object.prototype.toString; +var fnToStr = Function.prototype.toString; +var isFnRegex = /^\s*(?:function)?\*/; +var hasToStringTag = __webpack_require__(9092)(); +var getProto = Object.getPrototypeOf; +var getGeneratorFunc = function () { // eslint-disable-line consistent-return + if (!hasToStringTag) { + return false; + } + try { + return Function('return function*() {}')(); + } catch (e) { + } +}; +var GeneratorFunction; + +module.exports = function isGeneratorFunction(fn) { + if (typeof fn !== 'function') { + return false; + } + if (isFnRegex.test(fnToStr.call(fn))) { + return true; + } + if (!hasToStringTag) { + var str = toStr.call(fn); + return str === '[object GeneratorFunction]'; + } + if (!getProto) { + return false; + } + if (typeof GeneratorFunction === 'undefined') { + var generatorFunc = getGeneratorFunc(); + GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; + } + return getProto(fn) === GeneratorFunction; +}; + + +/***/ }), + +/***/ 3003: +/***/ ((module) => { + +"use strict"; + + +/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ + +module.exports = function isNaN(value) { + return value !== value; +}; + + +/***/ }), + +/***/ 4133: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var callBind = __webpack_require__(487); +var define = __webpack_require__(8452); + +var implementation = __webpack_require__(3003); +var getPolyfill = __webpack_require__(6642); +var shim = __webpack_require__(2464); + +var polyfill = callBind(getPolyfill(), Number); + +/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ + +define(polyfill, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = polyfill; + + +/***/ }), + +/***/ 6642: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var implementation = __webpack_require__(3003); + +module.exports = function getPolyfill() { + if (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN('a')) { + return Number.isNaN; + } + return implementation; +}; + + +/***/ }), + +/***/ 2464: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var define = __webpack_require__(8452); +var getPolyfill = __webpack_require__(6642); + +/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ + +module.exports = function shimNumberIsNaN() { + var polyfill = getPolyfill(); + define(Number, { isNaN: polyfill }, { + isNaN: function testIsNaN() { + return Number.isNaN !== polyfill; + } + }); + return polyfill; +}; + + +/***/ }), + +/***/ 5680: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var whichTypedArray = __webpack_require__(5767); + +/** @type {import('.')} */ +module.exports = function isTypedArray(value) { + return !!whichTypedArray(value); +}; + + +/***/ }), + +/***/ 9211: +/***/ ((module) => { + +"use strict"; + + +var numberIsNaN = function (value) { + return value !== value; +}; + +module.exports = function is(a, b) { + if (a === 0 && b === 0) { + return 1 / a === 1 / b; + } + if (a === b) { + return true; + } + if (numberIsNaN(a) && numberIsNaN(b)) { + return true; + } + return false; +}; + + + +/***/ }), + +/***/ 7653: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var define = __webpack_require__(8452); +var callBind = __webpack_require__(487); + +var implementation = __webpack_require__(9211); +var getPolyfill = __webpack_require__(9394); +var shim = __webpack_require__(6576); + +var polyfill = callBind(getPolyfill(), Object); + +define(polyfill, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = polyfill; + + +/***/ }), + +/***/ 9394: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var implementation = __webpack_require__(9211); + +module.exports = function getPolyfill() { + return typeof Object.is === 'function' ? Object.is : implementation; +}; + + +/***/ }), + +/***/ 6576: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var getPolyfill = __webpack_require__(9394); +var define = __webpack_require__(8452); + +module.exports = function shimObjectIs() { + var polyfill = getPolyfill(); + define(Object, { is: polyfill }, { + is: function testObjectIs() { + return Object.is !== polyfill; + } + }); + return polyfill; +}; + + +/***/ }), + +/***/ 8875: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var keysShim; +if (!Object.keys) { + // modified from https://github.com/es-shims/es5-shim + var has = Object.prototype.hasOwnProperty; + var toStr = Object.prototype.toString; + var isArgs = __webpack_require__(1093); // eslint-disable-line global-require + var isEnumerable = Object.prototype.propertyIsEnumerable; + var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); + var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); + var dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ]; + var equalsConstructorPrototype = function (o) { + var ctor = o.constructor; + return ctor && ctor.prototype === o; + }; + var excludedKeys = { + $applicationCache: true, + $console: true, + $external: true, + $frame: true, + $frameElement: true, + $frames: true, + $innerHeight: true, + $innerWidth: true, + $onmozfullscreenchange: true, + $onmozfullscreenerror: true, + $outerHeight: true, + $outerWidth: true, + $pageXOffset: true, + $pageYOffset: true, + $parent: true, + $scrollLeft: true, + $scrollTop: true, + $scrollX: true, + $scrollY: true, + $self: true, + $webkitIndexedDB: true, + $webkitStorageInfo: true, + $window: true + }; + var hasAutomationEqualityBug = (function () { + /* global window */ + if (typeof window === 'undefined') { return false; } + for (var k in window) { + try { + if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { + try { + equalsConstructorPrototype(window[k]); + } catch (e) { + return true; + } + } + } catch (e) { + return true; + } + } + return false; + }()); + var equalsConstructorPrototypeIfNotBuggy = function (o) { + /* global window */ + if (typeof window === 'undefined' || !hasAutomationEqualityBug) { + return equalsConstructorPrototype(o); + } + try { + return equalsConstructorPrototype(o); + } catch (e) { + return false; + } + }; + + keysShim = function keys(object) { + var isObject = object !== null && typeof object === 'object'; + var isFunction = toStr.call(object) === '[object Function]'; + var isArguments = isArgs(object); + var isString = isObject && toStr.call(object) === '[object String]'; + var theKeys = []; + + if (!isObject && !isFunction && !isArguments) { + throw new TypeError('Object.keys called on a non-object'); + } + + var skipProto = hasProtoEnumBug && isFunction; + if (isString && object.length > 0 && !has.call(object, 0)) { + for (var i = 0; i < object.length; ++i) { + theKeys.push(String(i)); + } + } + + if (isArguments && object.length > 0) { + for (var j = 0; j < object.length; ++j) { + theKeys.push(String(j)); + } + } else { + for (var name in object) { + if (!(skipProto && name === 'prototype') && has.call(object, name)) { + theKeys.push(String(name)); + } + } + } + + if (hasDontEnumBug) { + var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); + + for (var k = 0; k < dontEnums.length; ++k) { + if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { + theKeys.push(dontEnums[k]); + } + } + } + return theKeys; + }; +} +module.exports = keysShim; + + +/***/ }), + +/***/ 1189: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var slice = Array.prototype.slice; +var isArgs = __webpack_require__(1093); + +var origKeys = Object.keys; +var keysShim = origKeys ? function keys(o) { return origKeys(o); } : __webpack_require__(8875); + +var originalKeys = Object.keys; + +keysShim.shim = function shimObjectKeys() { + if (Object.keys) { + var keysWorksWithArguments = (function () { + // Safari 5.0 bug + var args = Object.keys(arguments); + return args && args.length === arguments.length; + }(1, 2)); + if (!keysWorksWithArguments) { + Object.keys = function keys(object) { // eslint-disable-line func-name-matching + if (isArgs(object)) { + return originalKeys(slice.call(object)); + } + return originalKeys(object); + }; + } + } else { + Object.keys = keysShim; + } + return Object.keys || keysShim; +}; + +module.exports = keysShim; + + +/***/ }), + +/***/ 1093: +/***/ ((module) => { + +"use strict"; + + +var toStr = Object.prototype.toString; + +module.exports = function isArguments(value) { + var str = toStr.call(value); + var isArgs = str === '[object Arguments]'; + if (!isArgs) { + isArgs = str !== '[object Array]' && + value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + toStr.call(value.callee) === '[object Function]'; + } + return isArgs; +}; + + +/***/ }), + +/***/ 8403: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +// modified from https://github.com/es-shims/es6-shim +var objectKeys = __webpack_require__(1189); +var hasSymbols = __webpack_require__(1333)(); +var callBound = __webpack_require__(8075); +var toObject = Object; +var $push = callBound('Array.prototype.push'); +var $propIsEnumerable = callBound('Object.prototype.propertyIsEnumerable'); +var originalGetSymbols = hasSymbols ? Object.getOwnPropertySymbols : null; + +// eslint-disable-next-line no-unused-vars +module.exports = function assign(target, source1) { + if (target == null) { throw new TypeError('target must be an object'); } + var to = toObject(target); // step 1 + if (arguments.length === 1) { + return to; // step 2 + } + for (var s = 1; s < arguments.length; ++s) { + var from = toObject(arguments[s]); // step 3.a.i + + // step 3.a.ii: + var keys = objectKeys(from); + var getSymbols = hasSymbols && (Object.getOwnPropertySymbols || originalGetSymbols); + if (getSymbols) { + var syms = getSymbols(from); + for (var j = 0; j < syms.length; ++j) { + var key = syms[j]; + if ($propIsEnumerable(from, key)) { + $push(keys, key); + } + } + } + + // step 3.a.iii: + for (var i = 0; i < keys.length; ++i) { + var nextKey = keys[i]; + if ($propIsEnumerable(from, nextKey)) { // step 3.a.iii.2 + var propValue = from[nextKey]; // step 3.a.iii.2.a + to[nextKey] = propValue; // step 3.a.iii.2.b + } + } + } + + return to; // step 4 +}; + + +/***/ }), + +/***/ 1514: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var implementation = __webpack_require__(8403); + +var lacksProperEnumerationOrder = function () { + if (!Object.assign) { + return false; + } + /* + * v8, specifically in node 4.x, has a bug with incorrect property enumeration order + * note: this does not detect the bug unless there's 20 characters + */ + var str = 'abcdefghijklmnopqrst'; + var letters = str.split(''); + var map = {}; + for (var i = 0; i < letters.length; ++i) { + map[letters[i]] = letters[i]; + } + var obj = Object.assign({}, map); + var actual = ''; + for (var k in obj) { + actual += k; + } + return str !== actual; +}; + +var assignHasPendingExceptions = function () { + if (!Object.assign || !Object.preventExtensions) { + return false; + } + /* + * Firefox 37 still has "pending exception" logic in its Object.assign implementation, + * which is 72% slower than our shim, and Firefox 40's native implementation. + */ + var thrower = Object.preventExtensions({ 1: 2 }); + try { + Object.assign(thrower, 'xy'); + } catch (e) { + return thrower[1] === 'y'; + } + return false; +}; + +module.exports = function getPolyfill() { + if (!Object.assign) { + return implementation; + } + if (lacksProperEnumerationOrder()) { + return implementation; + } + if (assignHasPendingExceptions()) { + return implementation; + } + return Object.assign; +}; + + +/***/ }), + +/***/ 6578: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +module.exports = [ + 'Float32Array', + 'Float64Array', + 'Int8Array', + 'Int16Array', + 'Int32Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Uint16Array', + 'Uint32Array', + 'BigInt64Array', + 'BigUint64Array' +]; + + +/***/ }), + +/***/ 5606: +/***/ ((module) => { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }), + +/***/ 2861: +/***/ ((module, exports, __webpack_require__) => { + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(8287) +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) +} + + +/***/ }), + +/***/ 6897: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); +var define = __webpack_require__(41); +var hasDescriptors = __webpack_require__(592)(); +var gOPD = __webpack_require__(5795); + +var $TypeError = __webpack_require__(9675); +var $floor = GetIntrinsic('%Math.floor%'); + +/** @type {import('.')} */ +module.exports = function setFunctionLength(fn, length) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { + throw new $TypeError('`length` must be a positive 32-bit integer'); + } + + var loose = arguments.length > 2 && !!arguments[2]; + + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ('length' in fn && gOPD) { + var desc = gOPD(fn, 'length'); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define(/** @type {Parameters[0]} */ (fn), 'length', length, true, true); + } else { + define(/** @type {Parameters[0]} */ (fn), 'length', length); + } + } + return fn; +}; + + +/***/ }), + +/***/ 392: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2802: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +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 = __webpack_require__(7816) +exports.sha1 = __webpack_require__(3737) +exports.sha224 = __webpack_require__(6710) +exports.sha256 = __webpack_require__(4107) +exports.sha384 = __webpack_require__(2827) +exports.sha512 = __webpack_require__(2890) + + +/***/ }), + +/***/ 7816: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 3737: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 6710: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * 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 = __webpack_require__(6698) +var Sha256 = __webpack_require__(4107) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 4107: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2827: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698) +var SHA512 = __webpack_require__(2890) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2890: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 8947: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +(function(nacl) { +'use strict'; + +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ + +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; + +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; + +var _0 = new Uint8Array(16); +var _9 = new Uint8Array(32); _9[0] = 9; + +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + +function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; +} + +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; +} + +function crypto_verify_16(x, xi, y, yi) { + return vn(x,xi,y,yi,16); +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); +} + +function core_salsa20(o, p, k, c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; + + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + + o[ 4] = x1 >>> 0 & 0xff; + o[ 5] = x1 >>> 8 & 0xff; + o[ 6] = x1 >>> 16 & 0xff; + o[ 7] = x1 >>> 24 & 0xff; + + o[ 8] = x2 >>> 0 & 0xff; + o[ 9] = x2 >>> 8 & 0xff; + o[10] = x2 >>> 16 & 0xff; + o[11] = x2 >>> 24 & 0xff; + + o[12] = x3 >>> 0 & 0xff; + o[13] = x3 >>> 8 & 0xff; + o[14] = x3 >>> 16 & 0xff; + o[15] = x3 >>> 24 & 0xff; + + o[16] = x4 >>> 0 & 0xff; + o[17] = x4 >>> 8 & 0xff; + o[18] = x4 >>> 16 & 0xff; + o[19] = x4 >>> 24 & 0xff; + + o[20] = x5 >>> 0 & 0xff; + o[21] = x5 >>> 8 & 0xff; + o[22] = x5 >>> 16 & 0xff; + o[23] = x5 >>> 24 & 0xff; + + o[24] = x6 >>> 0 & 0xff; + o[25] = x6 >>> 8 & 0xff; + o[26] = x6 >>> 16 & 0xff; + o[27] = x6 >>> 24 & 0xff; + + o[28] = x7 >>> 0 & 0xff; + o[29] = x7 >>> 8 & 0xff; + o[30] = x7 >>> 16 & 0xff; + o[31] = x7 >>> 24 & 0xff; + + o[32] = x8 >>> 0 & 0xff; + o[33] = x8 >>> 8 & 0xff; + o[34] = x8 >>> 16 & 0xff; + o[35] = x8 >>> 24 & 0xff; + + o[36] = x9 >>> 0 & 0xff; + o[37] = x9 >>> 8 & 0xff; + o[38] = x9 >>> 16 & 0xff; + o[39] = x9 >>> 24 & 0xff; + + o[40] = x10 >>> 0 & 0xff; + o[41] = x10 >>> 8 & 0xff; + o[42] = x10 >>> 16 & 0xff; + o[43] = x10 >>> 24 & 0xff; + + o[44] = x11 >>> 0 & 0xff; + o[45] = x11 >>> 8 & 0xff; + o[46] = x11 >>> 16 & 0xff; + o[47] = x11 >>> 24 & 0xff; + + o[48] = x12 >>> 0 & 0xff; + o[49] = x12 >>> 8 & 0xff; + o[50] = x12 >>> 16 & 0xff; + o[51] = x12 >>> 24 & 0xff; + + o[52] = x13 >>> 0 & 0xff; + o[53] = x13 >>> 8 & 0xff; + o[54] = x13 >>> 16 & 0xff; + o[55] = x13 >>> 24 & 0xff; + + o[56] = x14 >>> 0 & 0xff; + o[57] = x14 >>> 8 & 0xff; + o[58] = x14 >>> 16 & 0xff; + o[59] = x14 >>> 24 & 0xff; + + o[60] = x15 >>> 0 & 0xff; + o[61] = x15 >>> 8 & 0xff; + o[62] = x15 >>> 16 & 0xff; + o[63] = x15 >>> 24 & 0xff; +} + +function core_hsalsa20(o,p,k,c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + + o[ 4] = x5 >>> 0 & 0xff; + o[ 5] = x5 >>> 8 & 0xff; + o[ 6] = x5 >>> 16 & 0xff; + o[ 7] = x5 >>> 24 & 0xff; + + o[ 8] = x10 >>> 0 & 0xff; + o[ 9] = x10 >>> 8 & 0xff; + o[10] = x10 >>> 16 & 0xff; + o[11] = x10 >>> 24 & 0xff; + + o[12] = x15 >>> 0 & 0xff; + o[13] = x15 >>> 8 & 0xff; + o[14] = x15 >>> 16 & 0xff; + o[15] = x15 >>> 24 & 0xff; + + o[16] = x6 >>> 0 & 0xff; + o[17] = x6 >>> 8 & 0xff; + o[18] = x6 >>> 16 & 0xff; + o[19] = x6 >>> 24 & 0xff; + + o[20] = x7 >>> 0 & 0xff; + o[21] = x7 >>> 8 & 0xff; + o[22] = x7 >>> 16 & 0xff; + o[23] = x7 >>> 24 & 0xff; + + o[24] = x8 >>> 0 & 0xff; + o[25] = x8 >>> 8 & 0xff; + o[26] = x8 >>> 16 & 0xff; + o[27] = x8 >>> 24 & 0xff; + + o[28] = x9 >>> 0 & 0xff; + o[29] = x9 >>> 8 & 0xff; + o[30] = x9 >>> 16 & 0xff; + o[31] = x9 >>> 24 & 0xff; +} + +function crypto_core_salsa20(out,inp,k,c) { + core_salsa20(out,inp,k,c); +} + +function crypto_core_hsalsa20(out,inp,k,c) { + core_hsalsa20(out,inp,k,c); +} + +var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); + // "expand 32-byte k" + +function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + mpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + } + return 0; +} + +function crypto_stream_salsa20(c,cpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = x[i]; + } + return 0; +} + +function crypto_stream(c,cpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20(c,cpos,d,sn,s); +} + +function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); +} + +/* +* Port of Andrew Moon's Poly1305-donna-16. Public domain. +* https://github.com/floodyberry/poly1305-donna +*/ + +var poly1305 = function(key) { + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.leftover = 0; + this.fin = 0; + + var t0, t1, t2, t3, t4, t5, t6, t7; + + t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; + t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = ((t4 >>> 1)) & 0x1ffe; + t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = ((t7 >>> 5)) & 0x007f; + + this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; + this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; + this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; + this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; + this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; + this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; + this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; + this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; +}; + +poly1305.prototype.blocks = function(m, mpos, bytes) { + var hibit = this.fin ? 0 : (1 << 11); + var t0, t1, t2, t3, t4, t5, t6, t7, c; + var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; + + var h0 = this.h[0], + h1 = this.h[1], + h2 = this.h[2], + h3 = this.h[3], + h4 = this.h[4], + h5 = this.h[5], + h6 = this.h[6], + h7 = this.h[7], + h8 = this.h[8], + h9 = this.h[9]; + + var r0 = this.r[0], + r1 = this.r[1], + r2 = this.r[2], + r3 = this.r[3], + r4 = this.r[4], + r5 = this.r[5], + r6 = this.r[6], + r7 = this.r[7], + r8 = this.r[8], + r9 = this.r[9]; + + while (bytes >= 16) { + t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; + t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; + t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; + h5 += ((t4 >>> 1)) & 0x1fff; + t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; + t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + h9 += ((t7 >>> 5)) | hibit; + + c = 0; + + d0 = c; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h2 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c = (d0 >>> 13); d0 &= 0x1fff; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c += (d0 >>> 13); d0 &= 0x1fff; + + d1 = c; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h2 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c = (d1 >>> 13); d1 &= 0x1fff; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c += (d1 >>> 13); d1 &= 0x1fff; + + d2 = c; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h2 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c = (d2 >>> 13); d2 &= 0x1fff; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c += (d2 >>> 13); d2 &= 0x1fff; + + d3 = c; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h2 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c = (d3 >>> 13); d3 &= 0x1fff; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c += (d3 >>> 13); d3 &= 0x1fff; + + d4 = c; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h2 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c = (d4 >>> 13); d4 &= 0x1fff; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c += (d4 >>> 13); d4 &= 0x1fff; + + d5 = c; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h2 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c = (d5 >>> 13); d5 &= 0x1fff; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c += (d5 >>> 13); d5 &= 0x1fff; + + d6 = c; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h2 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c = (d6 >>> 13); d6 &= 0x1fff; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c += (d6 >>> 13); d6 &= 0x1fff; + + d7 = c; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h2 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c = (d7 >>> 13); d7 &= 0x1fff; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c += (d7 >>> 13); d7 &= 0x1fff; + + d8 = c; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h2 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c = (d8 >>> 13); d8 &= 0x1fff; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c += (d8 >>> 13); d8 &= 0x1fff; + + d9 = c; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h2 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c = (d9 >>> 13); d9 &= 0x1fff; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c += (d9 >>> 13); d9 &= 0x1fff; + + c = (((c << 2) + c)) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = (c >>> 13); + d1 += c; + + h0 = d0; + h1 = d1; + h2 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; + + mpos += 16; + bytes -= 16; + } + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h2; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; +}; + +poly1305.prototype.finish = function(mac, macpos) { + var g = new Uint16Array(10); + var c, mask, f, i; + + if (this.leftover) { + i = this.leftover; + this.buffer[i++] = 1; + for (; i < 16; i++) this.buffer[i] = 0; + this.fin = 1; + this.blocks(this.buffer, 0, 16); + } + + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + for (i = 2; i < 10; i++) { + this.h[i] += c; + c = this.h[i] >>> 13; + this.h[i] &= 0x1fff; + } + this.h[0] += (c * 5); + c = this.h[0] >>> 13; + this.h[0] &= 0x1fff; + this.h[1] += c; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + this.h[2] += c; + + g[0] = this.h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (i = 1; i < 10; i++) { + g[i] = this.h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= (1 << 13); + + mask = (c ^ 1) - 1; + for (i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; + + this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; + this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; + this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; + this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; + this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; + this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; + this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; + this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; + + f = this.h[0] + this.pad[0]; + this.h[0] = f & 0xffff; + for (i = 1; i < 8; i++) { + f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; + this.h[i] = f & 0xffff; + } + + mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; + mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; + mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; + mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; + mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; + mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; + mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; + mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; + mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; + mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; + mac[macpos+10] = (this.h[5] >>> 0) & 0xff; + mac[macpos+11] = (this.h[5] >>> 8) & 0xff; + mac[macpos+12] = (this.h[6] >>> 0) & 0xff; + mac[macpos+13] = (this.h[6] >>> 8) & 0xff; + mac[macpos+14] = (this.h[7] >>> 0) & 0xff; + mac[macpos+15] = (this.h[7] >>> 8) & 0xff; +}; + +poly1305.prototype.update = function(m, mpos, bytes) { + var i, want; + + if (this.leftover) { + want = (16 - this.leftover); + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) + return; + this.blocks(this.buffer, 0, 16); + this.leftover = 0; + } + + if (bytes >= 16) { + want = bytes - (bytes % 16); + this.blocks(m, mpos, want); + mpos += want; + bytes -= want; + } + + if (bytes) { + for (i = 0; i < bytes; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + this.leftover += bytes; + } +}; + +function crypto_onetimeauth(out, outpos, m, mpos, n, k) { + var s = new poly1305(k); + s.update(m, mpos, n); + s.finish(out, outpos); + return 0; +} + +function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { + var x = new Uint8Array(16); + crypto_onetimeauth(x,0,m,mpos,n,k); + return crypto_verify_16(h,hpos,x,0); +} + +function crypto_secretbox(c,m,d,n,k) { + var i; + if (d < 32) return -1; + crypto_stream_xor(c,0,m,0,d,n,k); + crypto_onetimeauth(c, 16, c, 32, d - 32, c); + for (i = 0; i < 16; i++) c[i] = 0; + return 0; +} + +function crypto_secretbox_open(m,c,d,n,k) { + var i; + var x = new Uint8Array(32); + if (d < 32) return -1; + crypto_stream(x,0,32,n,k); + if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; + crypto_stream_xor(m,0,c,0,d,n,k); + for (i = 0; i < 32; i++) m[i] = 0; + return 0; +} + +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} + +function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c-1 + 37 * (c-1); +} + +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; + } +} + +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} + +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; +} + +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} + +function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +} + +function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +} + +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is + + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} + +function S(o, a) { + M(o, a, a); +} + +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; + } + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); + } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; + } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; +} + +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); +} + +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); +} + +function crypto_box_beforenm(k, y, x) { + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y); + return crypto_core_hsalsa20(k, _0, s, sigma); +} + +var crypto_box_afternm = crypto_secretbox; +var crypto_box_open_afternm = crypto_secretbox_open; + +function crypto_box(c, m, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_afternm(c, m, d, n, k); +} + +function crypto_box_open(m, c, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_open_afternm(m, c, d, n, k); +} + +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 +]; + +function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; + + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; + } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; + + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; + + // add + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // K + h = K[i*2]; + l = K[i*2+1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // w + h = wh[i%16]; + l = wl[i%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; + + // add + h = th; + l = tl; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); + + // add + h = bh3; + l = bl3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = th; + l = tl; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); + + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); + } + } + } + + // add + h = ah0; + l = al0; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[0]; + l = hl[0]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); + + h = ah1; + l = al1; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[1]; + l = hl[1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); + + h = ah2; + l = al2; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[2]; + l = hl[2]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); + + h = ah3; + l = al3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[3]; + l = hl[3]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); + + h = ah4; + l = al4; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[4]; + l = hl[4]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); + + h = ah5; + l = al5; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[5]; + l = hl[5]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); + + h = ah6; + l = al6; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[6]; + l = hl[6]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); + + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[7]; + l = hl[7]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); + + pos += 128; + n -= 128; + } + + return n; +} + +function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; + + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; + + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; + + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; + + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; + + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); + + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); + + return 0; +} + +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } +} + +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} + +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } +} + +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} + +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; + + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + scalarbase(p, d); + pack(pk, p); + + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} + +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); + +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = Math.floor((x[j] + 128) / 256); + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} + +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} + +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; + + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); + + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; + } + } + + modL(sm.subarray(32), x); + return smlen; +} + +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + return 0; +} + +function crypto_sign_open(m, sm, n, pk) { + var i; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; + + if (n < 64) return -1; + + if (unpackneg(q, pk)) return -1; + + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); + + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; + } + + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + return n; +} + +var crypto_secretbox_KEYBYTES = 32, + crypto_secretbox_NONCEBYTES = 24, + crypto_secretbox_ZEROBYTES = 32, + crypto_secretbox_BOXZEROBYTES = 16, + crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_box_BEFORENMBYTES = 32, + crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, + crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, + crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32, + crypto_hash_BYTES = 64; + +nacl.lowlevel = { + crypto_core_hsalsa20: crypto_core_hsalsa20, + crypto_stream_xor: crypto_stream_xor, + crypto_stream: crypto_stream, + crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, + crypto_stream_salsa20: crypto_stream_salsa20, + crypto_onetimeauth: crypto_onetimeauth, + crypto_onetimeauth_verify: crypto_onetimeauth_verify, + crypto_verify_16: crypto_verify_16, + crypto_verify_32: crypto_verify_32, + crypto_secretbox: crypto_secretbox, + crypto_secretbox_open: crypto_secretbox_open, + crypto_scalarmult: crypto_scalarmult, + crypto_scalarmult_base: crypto_scalarmult_base, + crypto_box_beforenm: crypto_box_beforenm, + crypto_box_afternm: crypto_box_afternm, + crypto_box: crypto_box, + crypto_box_open: crypto_box_open, + crypto_box_keypair: crypto_box_keypair, + crypto_hash: crypto_hash, + crypto_sign: crypto_sign, + crypto_sign_keypair: crypto_sign_keypair, + crypto_sign_open: crypto_sign_open, + + crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, + crypto_sign_BYTES: crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, + crypto_hash_BYTES: crypto_hash_BYTES, + + gf: gf, + D: D, + L: L, + pack25519: pack25519, + unpack25519: unpack25519, + M: M, + A: A, + S: S, + Z: Z, + pow2523: pow2523, + add: add, + set25519: set25519, + modL: modL, + scalarmult: scalarmult, + scalarbase: scalarbase, +}; + +/* High-level API */ + +function checkLengths(k, n) { + if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); +} + +function checkBoxLengths(pk, sk) { + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); +} + +function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError('unexpected type, use Uint8Array'); + } +} + +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} + +nacl.randomBytes = function(n) { + var b = new Uint8Array(n); + randombytes(b, n); + return b; +}; + +nacl.secretbox = function(msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c = new Uint8Array(m.length); + for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; + crypto_secretbox(c, m, m.length, nonce, key); + return c.subarray(crypto_secretbox_BOXZEROBYTES); +}; + +nacl.secretbox.open = function(box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m = new Uint8Array(c.length); + for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; + if (c.length < 32) return null; + if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null; + return m.subarray(crypto_secretbox_ZEROBYTES); +}; + +nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; +nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; +nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; + +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; + +nacl.scalarMult.base = function(n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; +}; + +nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; +nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; + +nacl.box = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k); +}; + +nacl.box.before = function(publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k, publicKey, secretKey); + return k; +}; + +nacl.box.after = nacl.secretbox; + +nacl.box.open = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k); +}; + +nacl.box.open.after = nacl.secretbox.open; + +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; +nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; +nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; +nacl.box.nonceLength = crypto_box_NONCEBYTES; +nacl.box.overheadLength = nacl.secretbox.overheadLength; + +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; + +nacl.sign.open = function(signedMsg, publicKey) { + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m = new Uint8Array(mlen); + for (var i = 0; i < m.length; i++) m[i] = tmp[i]; + return m; +}; + +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; + +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; + +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; +nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; +nacl.sign.seedLength = crypto_sign_SEEDBYTES; +nacl.sign.signatureLength = crypto_sign_BYTES; + +nacl.hash = function(msg) { + checkArrayTypes(msg); + var h = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h, msg, msg.length); + return h; +}; + +nacl.hash.hashLength = crypto_hash_BYTES; + +nacl.verify = function(x, y) { + checkArrayTypes(x, y); + // Zero length arguments are considered not equal. + if (x.length === 0 || y.length === 0) return false; + if (x.length !== y.length) return false; + return (vn(x, 0, y, 0, x.length) === 0) ? true : false; +}; + +nacl.setPRNG = function(fn) { + randombytes = fn; +}; + +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; + if (crypto && crypto.getRandomValues) { + // Browsers. + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } else if (true) { + // Node.js. + crypto = __webpack_require__(1281); + if (crypto && crypto.randomBytes) { + nacl.setPRNG(function(x, n) { + var i, v = crypto.randomBytes(n); + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } + } +})(); + +})( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); + + +/***/ }), + +/***/ 1135: +/***/ ((module) => { + +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} + +/***/ }), + +/***/ 9032: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Currently in sync with Node.js lib/internal/util/types.js +// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 + + + +var isArgumentsObject = __webpack_require__(7244); +var isGeneratorFunction = __webpack_require__(8184); +var whichTypedArray = __webpack_require__(5767); +var isTypedArray = __webpack_require__(5680); + +function uncurryThis(f) { + return f.call.bind(f); +} + +var BigIntSupported = typeof BigInt !== 'undefined'; +var SymbolSupported = typeof Symbol !== 'undefined'; + +var ObjectToString = uncurryThis(Object.prototype.toString); + +var numberValue = uncurryThis(Number.prototype.valueOf); +var stringValue = uncurryThis(String.prototype.valueOf); +var booleanValue = uncurryThis(Boolean.prototype.valueOf); + +if (BigIntSupported) { + var bigIntValue = uncurryThis(BigInt.prototype.valueOf); +} + +if (SymbolSupported) { + var symbolValue = uncurryThis(Symbol.prototype.valueOf); +} + +function checkBoxedPrimitive(value, prototypeValueOf) { + if (typeof value !== 'object') { + return false; + } + try { + prototypeValueOf(value); + return true; + } catch(e) { + return false; + } +} + +exports.isArgumentsObject = isArgumentsObject; +exports.isGeneratorFunction = isGeneratorFunction; +exports.isTypedArray = isTypedArray; + +// Taken from here and modified for better browser support +// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js +function isPromise(input) { + return ( + ( + typeof Promise !== 'undefined' && + input instanceof Promise + ) || + ( + input !== null && + typeof input === 'object' && + typeof input.then === 'function' && + typeof input.catch === 'function' + ) + ); +} +exports.isPromise = isPromise; + +function isArrayBufferView(value) { + if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { + return ArrayBuffer.isView(value); + } + + return ( + isTypedArray(value) || + isDataView(value) + ); +} +exports.isArrayBufferView = isArrayBufferView; + + +function isUint8Array(value) { + return whichTypedArray(value) === 'Uint8Array'; +} +exports.isUint8Array = isUint8Array; + +function isUint8ClampedArray(value) { + return whichTypedArray(value) === 'Uint8ClampedArray'; +} +exports.isUint8ClampedArray = isUint8ClampedArray; + +function isUint16Array(value) { + return whichTypedArray(value) === 'Uint16Array'; +} +exports.isUint16Array = isUint16Array; + +function isUint32Array(value) { + return whichTypedArray(value) === 'Uint32Array'; +} +exports.isUint32Array = isUint32Array; + +function isInt8Array(value) { + return whichTypedArray(value) === 'Int8Array'; +} +exports.isInt8Array = isInt8Array; + +function isInt16Array(value) { + return whichTypedArray(value) === 'Int16Array'; +} +exports.isInt16Array = isInt16Array; + +function isInt32Array(value) { + return whichTypedArray(value) === 'Int32Array'; +} +exports.isInt32Array = isInt32Array; + +function isFloat32Array(value) { + return whichTypedArray(value) === 'Float32Array'; +} +exports.isFloat32Array = isFloat32Array; + +function isFloat64Array(value) { + return whichTypedArray(value) === 'Float64Array'; +} +exports.isFloat64Array = isFloat64Array; + +function isBigInt64Array(value) { + return whichTypedArray(value) === 'BigInt64Array'; +} +exports.isBigInt64Array = isBigInt64Array; + +function isBigUint64Array(value) { + return whichTypedArray(value) === 'BigUint64Array'; +} +exports.isBigUint64Array = isBigUint64Array; + +function isMapToString(value) { + return ObjectToString(value) === '[object Map]'; +} +isMapToString.working = ( + typeof Map !== 'undefined' && + isMapToString(new Map()) +); + +function isMap(value) { + if (typeof Map === 'undefined') { + return false; + } + + return isMapToString.working + ? isMapToString(value) + : value instanceof Map; +} +exports.isMap = isMap; + +function isSetToString(value) { + return ObjectToString(value) === '[object Set]'; +} +isSetToString.working = ( + typeof Set !== 'undefined' && + isSetToString(new Set()) +); +function isSet(value) { + if (typeof Set === 'undefined') { + return false; + } + + return isSetToString.working + ? isSetToString(value) + : value instanceof Set; +} +exports.isSet = isSet; + +function isWeakMapToString(value) { + return ObjectToString(value) === '[object WeakMap]'; +} +isWeakMapToString.working = ( + typeof WeakMap !== 'undefined' && + isWeakMapToString(new WeakMap()) +); +function isWeakMap(value) { + if (typeof WeakMap === 'undefined') { + return false; + } + + return isWeakMapToString.working + ? isWeakMapToString(value) + : value instanceof WeakMap; +} +exports.isWeakMap = isWeakMap; + +function isWeakSetToString(value) { + return ObjectToString(value) === '[object WeakSet]'; +} +isWeakSetToString.working = ( + typeof WeakSet !== 'undefined' && + isWeakSetToString(new WeakSet()) +); +function isWeakSet(value) { + return isWeakSetToString(value); +} +exports.isWeakSet = isWeakSet; + +function isArrayBufferToString(value) { + return ObjectToString(value) === '[object ArrayBuffer]'; +} +isArrayBufferToString.working = ( + typeof ArrayBuffer !== 'undefined' && + isArrayBufferToString(new ArrayBuffer()) +); +function isArrayBuffer(value) { + if (typeof ArrayBuffer === 'undefined') { + return false; + } + + return isArrayBufferToString.working + ? isArrayBufferToString(value) + : value instanceof ArrayBuffer; +} +exports.isArrayBuffer = isArrayBuffer; + +function isDataViewToString(value) { + return ObjectToString(value) === '[object DataView]'; +} +isDataViewToString.working = ( + typeof ArrayBuffer !== 'undefined' && + typeof DataView !== 'undefined' && + isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) +); +function isDataView(value) { + if (typeof DataView === 'undefined') { + return false; + } + + return isDataViewToString.working + ? isDataViewToString(value) + : value instanceof DataView; +} +exports.isDataView = isDataView; + +// Store a copy of SharedArrayBuffer in case it's deleted elsewhere +var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; +function isSharedArrayBufferToString(value) { + return ObjectToString(value) === '[object SharedArrayBuffer]'; +} +function isSharedArrayBuffer(value) { + if (typeof SharedArrayBufferCopy === 'undefined') { + return false; + } + + if (typeof isSharedArrayBufferToString.working === 'undefined') { + isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); + } + + return isSharedArrayBufferToString.working + ? isSharedArrayBufferToString(value) + : value instanceof SharedArrayBufferCopy; +} +exports.isSharedArrayBuffer = isSharedArrayBuffer; + +function isAsyncFunction(value) { + return ObjectToString(value) === '[object AsyncFunction]'; +} +exports.isAsyncFunction = isAsyncFunction; + +function isMapIterator(value) { + return ObjectToString(value) === '[object Map Iterator]'; +} +exports.isMapIterator = isMapIterator; + +function isSetIterator(value) { + return ObjectToString(value) === '[object Set Iterator]'; +} +exports.isSetIterator = isSetIterator; + +function isGeneratorObject(value) { + return ObjectToString(value) === '[object Generator]'; +} +exports.isGeneratorObject = isGeneratorObject; + +function isWebAssemblyCompiledModule(value) { + return ObjectToString(value) === '[object WebAssembly.Module]'; +} +exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; + +function isNumberObject(value) { + return checkBoxedPrimitive(value, numberValue); +} +exports.isNumberObject = isNumberObject; + +function isStringObject(value) { + return checkBoxedPrimitive(value, stringValue); +} +exports.isStringObject = isStringObject; + +function isBooleanObject(value) { + return checkBoxedPrimitive(value, booleanValue); +} +exports.isBooleanObject = isBooleanObject; + +function isBigIntObject(value) { + return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); +} +exports.isBigIntObject = isBigIntObject; + +function isSymbolObject(value) { + return SymbolSupported && checkBoxedPrimitive(value, symbolValue); +} +exports.isSymbolObject = isSymbolObject; + +function isBoxedPrimitive(value) { + return ( + isNumberObject(value) || + isStringObject(value) || + isBooleanObject(value) || + isBigIntObject(value) || + isSymbolObject(value) + ); +} +exports.isBoxedPrimitive = isBoxedPrimitive; + +function isAnyArrayBuffer(value) { + return typeof Uint8Array !== 'undefined' && ( + isArrayBuffer(value) || + isSharedArrayBuffer(value) + ); +} +exports.isAnyArrayBuffer = isAnyArrayBuffer; + +['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { + Object.defineProperty(exports, method, { + enumerable: false, + value: function() { + throw new Error(method + ' is not supported in userland'); + } + }); +}); + + +/***/ }), + +/***/ 537: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* provided dependency */ var process = __webpack_require__(5606); +/* provided dependency */ var console = __webpack_require__(6763); +// 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. + +var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || + function getOwnPropertyDescriptors(obj) { + var keys = Object.keys(obj); + var descriptors = {}; + for (var i = 0; i < keys.length; i++) { + descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); + } + return descriptors; + }; + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + if (typeof process !== 'undefined' && process.noDeprecation === true) { + return fn; + } + + // Allow for deprecating things in the process of starting up. + if (typeof process === 'undefined') { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnvRegex = /^$/; + +if (process.env.NODE_DEBUG) { + var debugEnv = process.env.NODE_DEBUG; + debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/,/g, '$|^') + .toUpperCase(); + debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); +} +exports.debuglog = function(set) { + set = set.toUpperCase(); + if (!debugs[set]) { + if (debugEnvRegex.test(set)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').slice(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.slice(1, -1); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +exports.types = __webpack_require__(9032); + +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; +exports.types.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; +exports.types.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; +exports.types.isNativeError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = __webpack_require__(1135); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = __webpack_require__(6698); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; + +exports.promisify = function promisify(original) { + if (typeof original !== 'function') + throw new TypeError('The "original" argument must be of type Function'); + + if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { + var fn = original[kCustomPromisifiedSymbol]; + if (typeof fn !== 'function') { + throw new TypeError('The "util.promisify.custom" argument must be of type Function'); + } + Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return fn; + } + + function fn() { + var promiseResolve, promiseReject; + var promise = new Promise(function (resolve, reject) { + promiseResolve = resolve; + promiseReject = reject; + }); + + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + args.push(function (err, value) { + if (err) { + promiseReject(err); + } else { + promiseResolve(value); + } + }); + + try { + original.apply(this, args); + } catch (err) { + promiseReject(err); + } + + return promise; + } + + Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); + + if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return Object.defineProperties( + fn, + getOwnPropertyDescriptors(original) + ); +} + +exports.promisify.custom = kCustomPromisifiedSymbol + +function callbackifyOnRejected(reason, cb) { + // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). + // Because `null` is a special error value in callbacks which means "no error + // occurred", we error-wrap so the callback consumer can distinguish between + // "the promise rejected with null" or "the promise fulfilled with undefined". + if (!reason) { + var newReason = new Error('Promise was rejected with a falsy value'); + newReason.reason = reason; + reason = newReason; + } + return cb(reason); +} + +function callbackify(original) { + if (typeof original !== 'function') { + throw new TypeError('The "original" argument must be of type Function'); + } + + // We DO NOT return the promise as it gives the user a false sense that + // the promise is actually somehow related to the callback's execution + // and that the callback throwing will reject the promise. + function callbackified() { + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + + var maybeCb = args.pop(); + if (typeof maybeCb !== 'function') { + throw new TypeError('The last argument must be of type Function'); + } + var self = this; + var cb = function() { + return maybeCb.apply(self, arguments); + }; + // In true node style we process the callback on `nextTick` with all the + // implications (stack, `uncaughtException`, `async_hooks`) + original.apply(this, args) + .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, + function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); + } + + Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); + Object.defineProperties(callbackified, + getOwnPropertyDescriptors(original)); + return callbackified; +} +exports.callbackify = callbackify; + + +/***/ }), + +/***/ 5767: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var forEach = __webpack_require__(2682); +var availableTypedArrays = __webpack_require__(9209); +var callBind = __webpack_require__(487); +var callBound = __webpack_require__(8075); +var gOPD = __webpack_require__(5795); + +/** @type {(O: object) => string} */ +var $toString = callBound('Object.prototype.toString'); +var hasToStringTag = __webpack_require__(9092)(); + +var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; +var typedArrays = availableTypedArrays(); + +var $slice = callBound('String.prototype.slice'); +var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); + +/** @type {(array: readonly T[], value: unknown) => number} */ +var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { + for (var i = 0; i < array.length; i += 1) { + if (array[i] === value) { + return i; + } + } + return -1; +}; + +/** @typedef {(receiver: import('.').TypedArray) => string | typeof Uint8Array.prototype.slice.call | typeof Uint8Array.prototype.set.call} Getter */ +/** @type {{ [k in `\$${import('.').TypedArrayName}`]?: Getter } & { __proto__: null }} */ +var cache = { __proto__: null }; +if (hasToStringTag && gOPD && getPrototypeOf) { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + if (Symbol.toStringTag in arr) { + var proto = getPrototypeOf(arr); + // @ts-expect-error TS won't narrow inside a closure + var descriptor = gOPD(proto, Symbol.toStringTag); + if (!descriptor) { + var superProto = getPrototypeOf(proto); + // @ts-expect-error TS won't narrow inside a closure + descriptor = gOPD(superProto, Symbol.toStringTag); + } + // @ts-expect-error TODO: fix + cache['$' + typedArray] = callBind(descriptor.get); + } + }); +} else { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + var fn = arr.slice || arr.set; + if (fn) { + // @ts-expect-error TODO: fix + cache['$' + typedArray] = callBind(fn); + } + }); +} + +/** @type {(value: object) => false | import('.').TypedArrayName} */ +var tryTypedArrays = function tryAllTypedArrays(value) { + /** @type {ReturnType} */ var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), + /** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */ + function (getter, typedArray) { + if (!found) { + try { + // @ts-expect-error TODO: fix + if ('$' + getter(value) === typedArray) { + found = $slice(typedArray, 1); + } + } catch (e) { /**/ } + } + } + ); + return found; +}; + +/** @type {(value: object) => false | import('.').TypedArrayName} */ +var trySlices = function tryAllSlices(value) { + /** @type {ReturnType} */ var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), + /** @type {(getter: typeof cache, name: `\$${import('.').TypedArrayName}`) => void} */ function (getter, name) { + if (!found) { + try { + // @ts-expect-error TODO: fix + getter(value); + found = $slice(name, 1); + } catch (e) { /**/ } + } + } + ); + return found; +}; + +/** @type {import('.')} */ +module.exports = function whichTypedArray(value) { + if (!value || typeof value !== 'object') { return false; } + if (!hasToStringTag) { + /** @type {string} */ + var tag = $slice($toString(value), 8, -1); + if ($indexOf(typedArrays, tag) > -1) { + return tag; + } + if (tag !== 'Object') { + return false; + } + // node < 0.6 hits here on real Typed Arrays + return trySlices(value); + } + if (!gOPD) { return null; } // unknown engine + return tryTypedArrays(value); +}; + + +/***/ }), + +/***/ 1281: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 9209: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var possibleNames = __webpack_require__(6578); + +var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; + +/** @type {import('.')} */ +module.exports = function availableTypedArrays() { + var /** @type {ReturnType} */ out = []; + for (var i = 0; i < possibleNames.length; i++) { + if (typeof g[possibleNames[i]] === 'function') { + // @ts-expect-error + out[out.length] = possibleNames[i]; + } + } + return out; +}; + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat get default export */ +/******/ (() => { +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = (module) => { +/******/ var getter = module && module.__esModule ? +/******/ () => (module['default']) : +/******/ () => (module); +/******/ __webpack_require__.d(getter, { a: getter }); +/******/ return getter; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/global */ +/******/ (() => { +/******/ __webpack_require__.g = (function() { +/******/ if (typeof globalThis === 'object') return globalThis; +/******/ try { +/******/ return this || new Function('return this')(); +/******/ } catch (e) { +/******/ if (typeof window === 'object') return window; +/******/ } +/******/ })(); +/******/ })(); +/******/ +/******/ /* webpack/runtime/harmony module decorator */ +/******/ (() => { +/******/ __webpack_require__.hmd = (module) => { +/******/ module = Object.create(module); +/******/ if (!module.children) module.children = []; +/******/ Object.defineProperty(module, 'exports', { +/******/ enumerable: true, +/******/ set: () => { +/******/ throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id); +/******/ } +/******/ }); +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __webpack_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ +/************************************************************************/ +/******/ +/******/ // startup +/******/ // Load entry module and return exports +/******/ // This entry module is referenced by other modules so it can't be inlined +/******/ var __webpack_exports__ = __webpack_require__(7957); +/******/ StellarBase = __webpack_exports__; +/******/ +/******/ })() +; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/dist/stellar-base.min.js b/node_modules/@stellar/stellar-base/dist/stellar-base.min.js new file mode 100644 index 000000000..a12aebbe5 --- /dev/null +++ b/node_modules/@stellar/stellar-base/dist/stellar-base.min.js @@ -0,0 +1,2 @@ +/*! For license information please see stellar-base.min.js.LICENSE.txt */ +var StellarBase;(()=>{var e={3740:function(e,t,r){var n,o=r(6763);n=()=>(()=>{var e={616:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(287);n.hp.alloc(1).subarray(0,1)instanceof n.hp||(n.hp.prototype.subarray=function(e,t){const r=Uint8Array.prototype.subarray.call(this,e,t);return Object.setPrototypeOf(r,n.hp.prototype),r});const o=n.hp},281:(e,t,r)=>{const n=r(164);e.exports=n},164:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Array:()=>D,Bool:()=>C,Double:()=>_,Enum:()=>H,Float:()=>B,Hyper:()=>O,Int:()=>k,LargeInt:()=>T,Opaque:()=>M,Option:()=>q,Quadruple:()=>R,Reference:()=>z,String:()=>N,Struct:()=>X,Union:()=>G,UnsignedHyper:()=>I,UnsignedInt:()=>x,VarArray:()=>V,VarOpaque:()=>F,Void:()=>K,XdrReader:()=>u,XdrWriter:()=>f,config:()=>ne});class n extends TypeError{constructor(e){super(`XDR Write Error: ${e}`)}}class o extends TypeError{constructor(e){super(`XDR Read Error: ${e}`)}}class i extends TypeError{constructor(e){super(`XDR Type Definition Error: ${e}`)}}class a extends i{constructor(){super("method not implemented, it should be overloaded in the descendant class.")}}var s=r(616).A;class u{constructor(e){if(!s.isBuffer(e)){if(!(e instanceof Array||Array.isArray(e)||ArrayBuffer.isView(e)))throw new o(`source invalid: ${e}`);e=s.from(e)}this._buffer=e,this._length=e.length,this._index=0}_buffer;_length;_index;get eof(){return this._index===this._length}advance(e){const t=this._index;if(this._index+=e,this._length0){for(let e=0;e0){const e=this.alloc(r);this._buffer.fill(0,e,this._index)}}writeInt32BE(e){const t=this.alloc(4);this._buffer.writeInt32BE(e,t)}writeUInt32BE(e){const t=this.alloc(4);this._buffer.writeUInt32BE(e,t)}writeBigInt64BE(e){const t=this.alloc(8);this._buffer.writeBigInt64BE(e,t)}writeBigUInt64BE(e){const t=this.alloc(8);this._buffer.writeBigUInt64BE(e,t)}writeFloatBE(e){const t=this.alloc(4);this._buffer.writeFloatBE(e,t)}writeDoubleBE(e){const t=this.alloc(8);this._buffer.writeDoubleBE(e,t)}static bufferChunkSize=l}var p=r(616).A;class h{toXDR(e="raw"){if(!this.write)return this.constructor.toXDR(this,e);const t=new f;return this.write(this,t),g(t.finalize(),e)}fromXDR(e,t="raw"){if(!this.read)return this.constructor.fromXDR(e,t);const r=new u(v(e,t)),n=this.read(r);return r.ensureInputConsumed(),n}validateXDR(e,t="raw"){try{return this.fromXDR(e,t),!0}catch(e){return!1}}static toXDR(e,t="raw"){const r=new f;return this.write(e,r),g(r.finalize(),t)}static fromXDR(e,t="raw"){const r=new u(v(e,t)),n=this.read(r);return r.ensureInputConsumed(),n}static validateXDR(e,t="raw"){try{return this.fromXDR(e,t),!0}catch(e){return!1}}}class d extends h{static read(e){throw new a}static write(e,t){throw new a}static isValid(e){return!1}}class y extends h{isValid(e){return!1}}class m extends TypeError{constructor(e){super(`Invalid format ${e}, must be one of "raw", "hex", "base64"`)}}function g(e,t){switch(t){case"raw":return e;case"hex":return e.toString("hex");case"base64":return e.toString("base64");default:throw new m(t)}}function v(e,t){switch(t){case"raw":return e;case"hex":return p.from(e,"hex");case"base64":return p.from(e,"base64");default:throw new m(t)}}function b(e,t){return null!=e&&(e instanceof t||w(e,t)&&"function"==typeof e.constructor.read&&"function"==typeof e.constructor.write&&w(e,"XdrType"))}function w(e,t){do{if(e.constructor.name===t)return!0}while(e=Object.getPrototypeOf(e));return!1}const S=2147483647;class k extends d{static read(e){return e.readInt32BE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");if((0|e)!==e)throw new n("invalid i32 value");t.writeInt32BE(e)}static isValid(e){return"number"==typeof e&&(0|e)===e&&e>=-2147483648&&e<=S}}function E(e,t,r){if("bigint"!=typeof e)throw new TypeError("Expected bigint 'value', got "+typeof e);const n=t/r;if(1===n)return[e];if(r<32||r>128||2!==n&&4!==n&&8!==n)throw new TypeError(`invalid bigint (${e}) and slice size (${t} -> ${r}) combination`);const o=BigInt(r),i=new Array(n);for(let t=0;t>=o;return i}function A(e,t){if(t)return[0n,(1n<=i&&o<=a)return o;throw new TypeError(`bigint values [${e}] for ${function(e,t){return`${t?"u":"i"}${e}`}(t,r)} out of range [${i}, ${a}]: ${o}`)}(e,this.size,this.unsigned)}get unsigned(){throw new a}get size(){throw new a}slice(e){return E(this._value,this.size,e)}toString(){return this._value.toString()}toJSON(){return{_value:this._value.toString()}}toBigInt(){return BigInt(this._value)}static read(e){const{size:t}=this.prototype;return 64===t?new this(e.readBigUInt64BE()):new this(...Array.from({length:t/64},(()=>e.readBigUInt64BE())).reverse())}static write(e,t){if(e instanceof this)e=e._value;else if("bigint"!=typeof e||e>this.MAX_VALUE||e>32n)}get size(){return 64}get unsigned(){return!1}static fromBits(e,t){return new this(e,t)}}O.defineIntBoundaries();const P=4294967295;class x extends d{static read(e){return e.readUInt32BE()}static write(e,t){if("number"!=typeof e||!(e>=0&&e<=P)||e%1!=0)throw new n("invalid u32 value");t.writeUInt32BE(e)}static isValid(e){return"number"==typeof e&&e%1==0&&e>=0&&e<=P}}x.MAX_VALUE=P,x.MIN_VALUE=0;class I extends T{constructor(...e){super(e)}get low(){return 0|Number(0xffffffffn&this._value)}get high(){return 0|Number(this._value>>32n)}get size(){return 64}get unsigned(){return!0}static fromBits(e,t){return new this(e,t)}}I.defineIntBoundaries();class B extends d{static read(e){return e.readFloatBE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");t.writeFloatBE(e)}static isValid(e){return"number"==typeof e}}class _ extends d{static read(e){return e.readDoubleBE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");t.writeDoubleBE(e)}static isValid(e){return"number"==typeof e}}class R extends d{static read(){throw new i("quadruple not supported")}static write(){throw new i("quadruple not supported")}static isValid(){return!1}}class C extends d{static read(e){const t=k.read(e);switch(t){case 0:return!1;case 1:return!0;default:throw new o(`got ${t} when trying to read a bool`)}}static write(e,t){const r=e?1:0;k.write(r,t)}static isValid(e){return"boolean"==typeof e}}var U=r(616).A;class N extends y{constructor(e=x.MAX_VALUE){super(),this._maxLength=e}read(e){const t=x.read(e);if(t>this._maxLength)throw new o(`saw ${t} length String, max allowed is ${this._maxLength}`);return e.read(t)}readString(e){return this.read(e).toString("utf8")}write(e,t){const r="string"==typeof e?U.byteLength(e,"utf8"):e.length;if(r>this._maxLength)throw new n(`got ${e.length} bytes, max allowed is ${this._maxLength}`);x.write(r,t),t.write(e,r)}isValid(e){return"string"==typeof e?U.byteLength(e,"utf8")<=this._maxLength:!!(e instanceof Array||U.isBuffer(e))&&e.length<=this._maxLength}}var L=r(616).A;class M extends y{constructor(e){super(),this._length=e}read(e){return e.read(this._length)}write(e,t){const{length:r}=e;if(r!==this._length)throw new n(`got ${e.length} bytes, expected ${this._length}`);t.write(e,r)}isValid(e){return L.isBuffer(e)&&e.length===this._length}}var j=r(616).A;class F extends y{constructor(e=x.MAX_VALUE){super(),this._maxLength=e}read(e){const t=x.read(e);if(t>this._maxLength)throw new o(`saw ${t} length VarOpaque, max allowed is ${this._maxLength}`);return e.read(t)}write(e,t){const{length:r}=e;if(e.length>this._maxLength)throw new n(`got ${e.length} bytes, max allowed is ${this._maxLength}`);x.write(r,t),t.write(e,r)}isValid(e){return j.isBuffer(e)&&e.length<=this._maxLength}}class D extends y{constructor(e,t){super(),this._childType=e,this._length=t}read(e){const t=new r.g.Array(this._length);for(let r=0;rthis._maxLength)throw new o(`saw ${t} length VarArray, max allowed is ${this._maxLength}`);const r=new Array(t);for(let n=0;nthis._maxLength)throw new n(`got array of size ${e.length}, max allowed is ${this._maxLength}`);x.write(e.length,t);for(const r of e)this._childType.write(r,t)}isValid(e){if(!(e instanceof Array)||e.length>this._maxLength)return!1;for(const t of e)if(!this._childType.isValid(t))return!1;return!0}}class q extends d{constructor(e){super(),this._childType=e}read(e){if(C.read(e))return this._childType.read(e)}write(e,t){const r=null!=e;C.write(r,t),r&&this._childType.write(e,t)}isValid(e){return null==e||this._childType.isValid(e)}}class K extends d{static read(){}static write(e){if(void 0!==e)throw new n("trying to write value to a void slot")}static isValid(e){return void 0===e}}class H extends d{constructor(e,t){super(),this.name=e,this.value=t}static read(e){const t=k.read(e),r=this._byValue[t];if(void 0===r)throw new o(`unknown ${this.enumName} member for value ${t}`);return r}static write(e,t){if(!this.isValid(e))throw new n(`${e} has enum name ${e?.enumName}, not ${this.enumName}: ${JSON.stringify(e)}`);k.write(e.value,t)}static isValid(e){return e?.constructor?.enumName===this.enumName||b(e,this)}static members(){return this._members}static values(){return Object.values(this._members)}static fromName(e){const t=this._members[e];if(!t)throw new TypeError(`${e} is not a member of ${this.enumName}`);return t}static fromValue(e){const t=this._byValue[e];if(void 0===t)throw new TypeError(`${e} is not a value of any member of ${this.enumName}`);return t}static create(e,t,r){const n=class extends H{};n.enumName=t,e.results[t]=n,n._members={},n._byValue={};for(const[e,t]of Object.entries(r)){const r=new n(e,t);n._members[e]=r,n._byValue[t]=r,n[e]=()=>r}return n}}class z extends d{resolve(){throw new i('"resolve" method should be implemented in the descendant class')}}class X extends y{constructor(e){super(),this._attributes=e||{}}static read(e){const t={};for(const[r,n]of this._fields)t[r]=n.read(e);return new this(t)}static write(e,t){if(!this.isValid(e))throw new n(`${e} has struct name ${e?.constructor?.structName}, not ${this.structName}: ${JSON.stringify(e)}`);for(const[r,n]of this._fields){const o=e._attributes[r];n.write(o,t)}}static isValid(e){return e?.constructor?.structName===this.structName||b(e,this)}static create(e,t,r){const n=class extends X{};n.structName=t,e.results[t]=n;const o=new Array(r.length);for(let t=0;t{"use strict";t.byteLength=function(e){var t=s(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,i=s(e),a=i[0],u=i[1],c=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,u)),l=0,f=u>0?a-4:a;for(r=0;r>16&255,c[l++]=t>>8&255,c[l++]=255&t;return 2===u&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,c[l++]=255&t),1===u&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t),c},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],a=16383,s=0,c=n-o;sc?c:s+a));return 1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),i.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)r[a]=i[a],n[i.charCodeAt(a)]=a;function s(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,n){for(var o,i,a=[],s=t;s>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return a.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287:(e,t,r)=>{"use strict";const n=r(526),i=r(251),a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=c,t.IS=50;const s=2147483647;function u(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,c.prototype),t}function c(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return p(e)}return l(e,t,r)}function l(e,t,r){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!c.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|m(e,t);let n=u(r);const o=n.write(e,t);return o!==r&&(n=n.slice(0,o)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(Y(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Y(e,ArrayBuffer)||e&&Y(e.buffer,ArrayBuffer))return d(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(Y(e,SharedArrayBuffer)||e&&Y(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return c.from(n,t,r);const o=function(e){if(c.isBuffer(e)){const t=0|y(e.length),r=u(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||J(e.length)?u(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return c.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function f(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function p(e){return f(e),u(e<0?0:0|y(e))}function h(e){const t=e.length<0?0:0|y(e.length),r=u(t);for(let n=0;n=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function m(e,t){if(c.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Y(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return $(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(o)return n?-1:$(e).length;t=(""+t).toLowerCase(),o=!0}}function g(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return _(this,t,r);case"utf8":case"utf-8":return P(this,t,r);case"ascii":return I(this,t,r);case"latin1":case"binary":return B(this,t,r);case"base64":return O(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function v(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function b(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),J(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=c.from(t,n)),c.isBuffer(t))return 0===t.length?-1:w(e,t,r,n,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):w(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function w(e,t,r,n,o){let i,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){let n=-1;for(i=r;is&&(r=s-u),i=r;i>=0;i--){let r=!0;for(let n=0;no&&(n=o):n=o;const i=t.length;let a;for(n>i/2&&(n=i/2),a=0;a>8,o=r%256,i.push(o),i.push(n);return i}(t,e.length-r),e,r,n)}function O(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function P(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o239?4:t>223?3:t>191?2:1;if(o+a<=r){let r,n,s,u;switch(a){case 1:t<128&&(i=t);break;case 2:r=e[o+1],128==(192&r)&&(u=(31&t)<<6|63&r,u>127&&(i=u));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(u=(15&t)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:r=e[o+1],n=e[o+2],s=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(u=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,u>65535&&u<1114112&&(i=u))}}null===i?(i=65533,a=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),o+=a}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(c.isBuffer(t)||(t=c.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!c.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},c.byteLength=m,c.prototype._isBuffer=!0,c.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(e+=" ... "),""},a&&(c.prototype[a]=c.prototype.inspect),c.prototype.compare=function(e,t,r,n,o){if(Y(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),!c.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let i=(o>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0);const s=Math.min(i,a),u=this.slice(n,o),l=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let i=!1;for(;;)switch(n){case"hex":return S(this,e,t,r);case"utf8":case"utf-8":return k(this,e,t,r);case"ascii":case"latin1":case"binary":return E(this,e,t,r);case"base64":return A(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function I(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;on)&&(r=n);let o="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function U(e,t,r,n,o,i){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function N(e,t,r,n,o){K(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function L(e,t,r,n,o){K(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r+7]=i,i>>=8,e[r+6]=i,i>>=8,e[r+5]=i,i>>=8,e[r+4]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function M(e,t,r,n,o,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function j(e,t,r,n,o){return t=+t,r>>>=0,o||M(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function F(e,t,r,n,o){return t=+t,r>>>=0,o||M(e,0,r,8),i.write(e,t,r,n,52,8),r+8}c.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e+--t],o=1;for(;t>0&&(o*=256);)n+=this[e+--t]*o;return n},c.prototype.readUint8=c.prototype.readUInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),this[e]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUint32BE=c.prototype.readUInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readBigUInt64LE=Q((function(e){H(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(o)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i=o&&(n-=Math.pow(2,8*t)),n},c.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=t,o=1,i=this[e+--n];for(;n>0&&(o*=256);)i+=this[e+--n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},c.prototype.readInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readBigInt64LE=Q((function(e){H(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||C(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||C(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||C(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||C(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUintLE=c.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||U(this,e,t,r,Math.pow(2,8*r)-1,0);let o=1,i=0;for(this[t]=255&e;++i>>=0,r>>>=0,n||U(this,e,t,r,Math.pow(2,8*r)-1,0);let o=r-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+r},c.prototype.writeUint8=c.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,1,255,0),this[t]=255&e,t+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigUInt64LE=Q((function(e,t=0){return N(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeBigUInt64BE=Q((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);U(this,e,t,r,n-1,-n)}let o=0,i=1,a=0;for(this[t]=255&e;++o>>=0,!n){const n=Math.pow(2,8*r-1);U(this,e,t,r,n-1,-n)}let o=r-1,i=1,a=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/i|0)-a&255;return t+r},c.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},c.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigInt64LE=Q((function(e,t=0){return N(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeBigInt64BE=Q((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeFloatLE=function(e,t,r){return j(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return j(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return F(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return F(this,e,t,!1,r)},c.prototype.copy=function(e,t,r,n){if(!c.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function K(e,t,r,n,o,i){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new D.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){H(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||z(t,e.length-(r+1))}(n,o,i)}function H(e,t){if("number"!=typeof e)throw new D.ERR_INVALID_ARG_TYPE(t,"number",e)}function z(e,t,r){if(Math.floor(e)!==e)throw H(e,r),new D.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new D.ERR_BUFFER_OUT_OF_BOUNDS;throw new D.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}V("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),V("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),V("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=q(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=q(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const X=/[^+/0-9A-Za-z-_]/g;function $(e,t){let r;t=t||1/0;const n=e.length;let o=null;const i=[];for(let a=0;a55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function G(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(X,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function W(e,t,r,n){let o;for(o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function Y(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function J(e){return e!=e}const Z=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let o=0;o<16;++o)t[n+o]=e[r]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?ee:e}function ee(){throw new Error("BigInt not supported")}},251:(e,t)=>{t.read=function(e,t,r,n,o){var i,a,s=8*o-n-1,u=(1<>1,l=-7,f=r?o-1:0,p=r?-1:1,h=e[t+f];for(f+=p,i=h&(1<<-l)-1,h>>=-l,l+=s;l>0;i=256*i+e[t+f],f+=p,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=p,l-=8);if(0===i)i=1-c;else{if(i===u)return a?NaN:1/0*(h?-1:1);a+=Math.pow(2,n),i-=c}return(h?-1:1)*a*Math.pow(2,i-n)},t.write=function(e,t,r,n,o,i){var a,s,u,c=8*i-o-1,l=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:i-1,d=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?p/u:p*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=l?(s=0,a=l):a+f>=1?(s=(t*u-1)*Math.pow(2,o),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,o),a=0));o>=8;e[r+h]=255&s,h+=d,s/=256,o-=8);for(a=a<0;e[r+h]=255&a,h+=d,a/=256,c-=8);e[r+h-d]|=128*y}}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}return r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r(281)})(),e.exports=n()},4148:(e,t,r)=>{"use strict";var n=r(5606),o=r(6763);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){for(var r=0;r1?r-1:0),o=1;o1?r-1:0),o=1;o1?r-1:0),o=1;o1?r-1:0),o=1;o{"use strict";var n=r(5606);function o(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function i(e){for(var t=1;te.length)&&(r=e.length),e.substring(r-t.length,r)===t}var w="",S="",k="",E="",A={deepStrictEqual:"Expected values to be strictly deep-equal:",strictEqual:"Expected values to be strictly equal:",strictEqualObject:'Expected "actual" to be reference-equal to "expected":',deepEqual:"Expected values to be loosely deep-equal:",equal:"Expected values to be loosely equal:",notDeepStrictEqual:'Expected "actual" not to be strictly deep-equal to:',notStrictEqual:'Expected "actual" to be strictly unequal to:',notStrictEqualObject:'Expected "actual" not to be reference-equal to "expected":',notDeepEqual:'Expected "actual" not to be loosely deep-equal to:',notEqual:'Expected "actual" to be loosely unequal to:',notIdentical:"Values identical but not reference-equal:"};function T(e){var t=Object.keys(e),r=Object.create(Object.getPrototypeOf(e));return t.forEach((function(t){r[t]=e[t]})),Object.defineProperty(r,"message",{value:e.message}),r}function O(e){return g(e,{compact:!1,customInspect:!1,depth:1e3,maxArrayLength:1/0,showHidden:!1,breakLength:1/0,showProxy:!1,sorted:!0,getters:!0})}function P(e,t,r){var o="",i="",a=0,s="",u=!1,c=O(e),l=c.split("\n"),f=O(t).split("\n"),p=0,h="";if("strictEqual"===r&&"object"===m(e)&&"object"===m(t)&&null!==e&&null!==t&&(r="strictEqualObject"),1===l.length&&1===f.length&&l[0]!==f[0]){var d=l[0].length+f[0].length;if(d<=10){if(!("object"===m(e)&&null!==e||"object"===m(t)&&null!==t||0===e&&0===t))return"".concat(A[r],"\n\n")+"".concat(l[0]," !== ").concat(f[0],"\n")}else if("strictEqualObject"!==r){if(d<(n.stderr&&n.stderr.isTTY?n.stderr.columns:80)){for(;l[0][p]===f[0][p];)p++;p>2&&(h="\n ".concat(function(e,t){if(t=Math.floor(t),0==e.length||0==t)return"";var r=e.length*t;for(t=Math.floor(Math.log(t)/Math.log(2));t;)e+=e,t--;return e+e.substring(0,r-e.length)}(" ",p),"^"),p=0)}}}for(var y=l[l.length-1],g=f[f.length-1];y===g&&(p++<2?s="\n ".concat(y).concat(s):o=y,l.pop(),f.pop(),0!==l.length&&0!==f.length);)y=l[l.length-1],g=f[f.length-1];var v=Math.max(l.length,f.length);if(0===v){var T=c.split("\n");if(T.length>30)for(T[26]="".concat(w,"...").concat(E);T.length>27;)T.pop();return"".concat(A.notIdentical,"\n\n").concat(T.join("\n"),"\n")}p>3&&(s="\n".concat(w,"...").concat(E).concat(s),u=!0),""!==o&&(s="\n ".concat(o).concat(s),o="");var P=0,x=A[r]+"\n".concat(S,"+ actual").concat(E," ").concat(k,"- expected").concat(E),I=" ".concat(w,"...").concat(E," Lines skipped");for(p=0;p1&&p>2&&(B>4?(i+="\n".concat(w,"...").concat(E),u=!0):B>3&&(i+="\n ".concat(f[p-2]),P++),i+="\n ".concat(f[p-1]),P++),a=p,o+="\n".concat(k,"-").concat(E," ").concat(f[p]),P++;else if(f.length1&&p>2&&(B>4?(i+="\n".concat(w,"...").concat(E),u=!0):B>3&&(i+="\n ".concat(l[p-2]),P++),i+="\n ".concat(l[p-1]),P++),a=p,i+="\n".concat(S,"+").concat(E," ").concat(l[p]),P++;else{var _=f[p],R=l[p],C=R!==_&&(!b(R,",")||R.slice(0,-1)!==_);C&&b(_,",")&&_.slice(0,-1)===R&&(C=!1,R+=","),C?(B>1&&p>2&&(B>4?(i+="\n".concat(w,"...").concat(E),u=!0):B>3&&(i+="\n ".concat(l[p-2]),P++),i+="\n ".concat(l[p-1]),P++),a=p,i+="\n".concat(S,"+").concat(E," ").concat(R),o+="\n".concat(k,"-").concat(E," ").concat(_),P+=2):(i+=o,o="",1!==B&&0!==p||(i+="\n ".concat(R),P++))}if(P>20&&p30)for(h[26]="".concat(w,"...").concat(E);h.length>27;)h.pop();t=1===h.length?p.call(this,"".concat(f," ").concat(h[0])):p.call(this,"".concat(f,"\n\n").concat(h.join("\n"),"\n"))}else{var d=O(a),y="",g=A[o];"notDeepEqual"===o||"notEqual"===o?(d="".concat(A[o],"\n\n").concat(d)).length>1024&&(d="".concat(d.slice(0,1021),"...")):(y="".concat(O(s)),d.length>512&&(d="".concat(d.slice(0,509),"...")),y.length>512&&(y="".concat(y.slice(0,509),"...")),"deepEqual"===o||"equal"===o?d="".concat(g,"\n\n").concat(d,"\n\nshould equal\n\n"):y=" ".concat(o," ").concat(y)),t=p.call(this,"".concat(d).concat(y))}return Error.stackTraceLimit=u,t.generatedMessage=!r,Object.defineProperty(l(t),"name",{value:"AssertionError [ERR_ASSERTION]",enumerable:!1,writable:!0,configurable:!0}),t.code="ERR_ASSERTION",t.actual=a,t.expected=s,t.operator=o,Error.captureStackTrace&&Error.captureStackTrace(l(t),i),t.stack,t.name="AssertionError",c(t)}return a=b,(u=[{key:"toString",value:function(){return"".concat(this.name," [").concat(this.code,"]: ").concat(this.message)}},{key:t,value:function(e,t){return g(this,i(i({},t),{},{customInspect:!1,depth:0}))}}])&&s(a.prototype,u),f&&s(a,f),Object.defineProperty(a,"prototype",{writable:!1}),b}(f(Error),g.custom);e.exports=x},9597:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;r2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:2===r?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}f("ERR_AMBIGUOUS_ARGUMENT",'The "%s" argument is ambiguous. %s',TypeError),f("ERR_INVALID_ARG_TYPE",(function(e,t,o){var i,a,s,c;if(void 0===u&&(u=r(4148)),u("string"==typeof e,"'name' must be a string"),"string"==typeof t&&(a="not ",t.substr(!s||s<0?0:+s,a.length)===a)?(i="must not be",t=t.replace(/^not /,"")):i="must be",function(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}(e," argument"))c="The ".concat(e," ").concat(i," ").concat(p(t,"type"));else{var l=function(e,t,r){return"number"!=typeof r&&(r=0),!(r+t.length>e.length)&&-1!==e.indexOf(t,r)}(e,".")?"property":"argument";c='The "'.concat(e,'" ').concat(l," ").concat(i," ").concat(p(t,"type"))}return c+=". Received type ".concat(n(o))}),TypeError),f("ERR_INVALID_ARG_VALUE",(function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"is invalid";void 0===c&&(c=r(537));var o=c.inspect(t);return o.length>128&&(o="".concat(o.slice(0,128),"...")),"The argument '".concat(e,"' ").concat(n,". Received ").concat(o)}),TypeError,RangeError),f("ERR_INVALID_RETURN_VALUE",(function(e,t,r){var o;return o=r&&r.constructor&&r.constructor.name?"instance of ".concat(r.constructor.name):"type ".concat(n(r)),"Expected ".concat(e,' to be returned from the "').concat(t,'"')+" function but got ".concat(o,".")}),TypeError),f("ERR_MISSING_ARGS",(function(){for(var e=arguments.length,t=new Array(e),n=0;n0,"At least one arg needs to be specified");var o="The ",i=t.length;switch(t=t.map((function(e){return'"'.concat(e,'"')})),i){case 1:o+="".concat(t[0]," argument");break;case 2:o+="".concat(t[0]," and ").concat(t[1]," arguments");break;default:o+=t.slice(0,i-1).join(", "),o+=", and ".concat(t[i-1]," arguments")}return"".concat(o," must be specified")}),TypeError),e.exports.codes=l},2299:(e,t,r)=>{"use strict";function n(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(e,t)||function(e,t){if(!e)return;if("string"==typeof e)return o(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return Array.from(e);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return o(e,t)}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r10)return!0;for(var t=0;t57)return!0}return 10===e.length&&e>=Math.pow(2,32)}function C(e){return Object.keys(e).filter(R).concat(l(e).filter(Object.prototype.propertyIsEnumerable.bind(e)))}function U(e,t){if(e===t)return 0;for(var r=e.length,n=t.length,o=0,i=Math.min(r,n);o{"use strict";r.d(t,{A:()=>o});var n=r(8287);n.Buffer.alloc(1).subarray(0,1)instanceof n.Buffer||(n.Buffer.prototype.subarray=function(e,t){var r=Uint8Array.prototype.subarray.call(this,e,t);return Object.setPrototypeOf(r,n.Buffer.prototype),r});const o=n.Buffer},7957:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Account:()=>Ft,Address:()=>Ge,Asset:()=>F,AuthClawbackEnabledFlag:()=>it,AuthImmutableFlag:()=>ot,AuthRequiredFlag:()=>rt,AuthRevocableFlag:()=>nt,BASE_FEE:()=>ar,Claimant:()=>Ie,Contract:()=>wr,FastSigning:()=>f,FeeBumpTransaction:()=>Nt,Hyper:()=>n.Hyper,Int128:()=>Hr,Int256:()=>Zr,Keypair:()=>U,LiquidityPoolAsset:()=>Te,LiquidityPoolFeeV18:()=>q,LiquidityPoolId:()=>Ce,Memo:()=>gt,MemoHash:()=>yt,MemoID:()=>ht,MemoNone:()=>pt,MemoReturn:()=>mt,MemoText:()=>dt,MuxedAccount:()=>Kt,Networks:()=>lr,Operation:()=>at,ScInt:()=>pn,SignerKey:()=>Jt,Soroban:()=>mr,SorobanDataBuilder:()=>$t,StrKey:()=>T,TimeoutInfinite:()=>sr,Transaction:()=>Ot,TransactionBase:()=>G,TransactionBuilder:()=>ur,Uint128:()=>xr,Uint256:()=>Lr,UnsignedHyper:()=>n.UnsignedHyper,XdrLargeInt:()=>nn,authorizeEntry:()=>Bn,authorizeInvocation:()=>Rn,buildInvocationTree:()=>Ln,cereal:()=>a,decodeAddressToMuxedAccount:()=>Ne,default:()=>Fn,encodeMuxedAccount:()=>Me,encodeMuxedAccountToAddress:()=>Le,extractBaseAddress:()=>je,getLiquidityPoolId:()=>K,hash:()=>u,humanizeEvents:()=>An,nativeToScVal:()=>vn,scValToBigInt:()=>hn,scValToNative:()=>bn,sign:()=>p,verify:()=>h,walkInvocationTree:()=>Mn,xdr:()=>i});var n=r(3740),o=n.config((function(e){var t=1024;e.typedef("Value",e.varOpaque()),e.struct("ScpBallot",[["counter",e.lookup("Uint32")],["value",e.lookup("Value")]]),e.enum("ScpStatementType",{scpStPrepare:0,scpStConfirm:1,scpStExternalize:2,scpStNominate:3}),e.struct("ScpNomination",[["quorumSetHash",e.lookup("Hash")],["votes",e.varArray(e.lookup("Value"),2147483647)],["accepted",e.varArray(e.lookup("Value"),2147483647)]]),e.struct("ScpStatementPrepare",[["quorumSetHash",e.lookup("Hash")],["ballot",e.lookup("ScpBallot")],["prepared",e.option(e.lookup("ScpBallot"))],["preparedPrime",e.option(e.lookup("ScpBallot"))],["nC",e.lookup("Uint32")],["nH",e.lookup("Uint32")]]),e.struct("ScpStatementConfirm",[["ballot",e.lookup("ScpBallot")],["nPrepared",e.lookup("Uint32")],["nCommit",e.lookup("Uint32")],["nH",e.lookup("Uint32")],["quorumSetHash",e.lookup("Hash")]]),e.struct("ScpStatementExternalize",[["commit",e.lookup("ScpBallot")],["nH",e.lookup("Uint32")],["commitQuorumSetHash",e.lookup("Hash")]]),e.union("ScpStatementPledges",{switchOn:e.lookup("ScpStatementType"),switchName:"type",switches:[["scpStPrepare","prepare"],["scpStConfirm","confirm"],["scpStExternalize","externalize"],["scpStNominate","nominate"]],arms:{prepare:e.lookup("ScpStatementPrepare"),confirm:e.lookup("ScpStatementConfirm"),externalize:e.lookup("ScpStatementExternalize"),nominate:e.lookup("ScpNomination")}}),e.struct("ScpStatement",[["nodeId",e.lookup("NodeId")],["slotIndex",e.lookup("Uint64")],["pledges",e.lookup("ScpStatementPledges")]]),e.struct("ScpEnvelope",[["statement",e.lookup("ScpStatement")],["signature",e.lookup("Signature")]]),e.struct("ScpQuorumSet",[["threshold",e.lookup("Uint32")],["validators",e.varArray(e.lookup("NodeId"),2147483647)],["innerSets",e.varArray(e.lookup("ScpQuorumSet"),2147483647)]]),e.typedef("Thresholds",e.opaque(4)),e.typedef("String32",e.string(32)),e.typedef("String64",e.string(64)),e.typedef("SequenceNumber",e.lookup("Int64")),e.typedef("DataValue",e.varOpaque(64)),e.typedef("PoolId",e.lookup("Hash")),e.typedef("AssetCode4",e.opaque(4)),e.typedef("AssetCode12",e.opaque(12)),e.enum("AssetType",{assetTypeNative:0,assetTypeCreditAlphanum4:1,assetTypeCreditAlphanum12:2,assetTypePoolShare:3}),e.union("AssetCode",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeCreditAlphanum4","assetCode4"],["assetTypeCreditAlphanum12","assetCode12"]],arms:{assetCode4:e.lookup("AssetCode4"),assetCode12:e.lookup("AssetCode12")}}),e.struct("AlphaNum4",[["assetCode",e.lookup("AssetCode4")],["issuer",e.lookup("AccountId")]]),e.struct("AlphaNum12",[["assetCode",e.lookup("AssetCode12")],["issuer",e.lookup("AccountId")]]),e.union("Asset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12")}}),e.struct("Price",[["n",e.lookup("Int32")],["d",e.lookup("Int32")]]),e.struct("Liabilities",[["buying",e.lookup("Int64")],["selling",e.lookup("Int64")]]),e.enum("ThresholdIndices",{thresholdMasterWeight:0,thresholdLow:1,thresholdMed:2,thresholdHigh:3}),e.enum("LedgerEntryType",{account:0,trustline:1,offer:2,data:3,claimableBalance:4,liquidityPool:5,contractData:6,contractCode:7,configSetting:8,ttl:9}),e.struct("Signer",[["key",e.lookup("SignerKey")],["weight",e.lookup("Uint32")]]),e.enum("AccountFlags",{authRequiredFlag:1,authRevocableFlag:2,authImmutableFlag:4,authClawbackEnabledFlag:8}),e.const("MASK_ACCOUNT_FLAGS",7),e.const("MASK_ACCOUNT_FLAGS_V17",15),e.const("MAX_SIGNERS",20),e.typedef("SponsorshipDescriptor",e.option(e.lookup("AccountId"))),e.struct("AccountEntryExtensionV3",[["ext",e.lookup("ExtensionPoint")],["seqLedger",e.lookup("Uint32")],["seqTime",e.lookup("TimePoint")]]),e.union("AccountEntryExtensionV2Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[3,"v3"]],arms:{v3:e.lookup("AccountEntryExtensionV3")}}),e.struct("AccountEntryExtensionV2",[["numSponsored",e.lookup("Uint32")],["numSponsoring",e.lookup("Uint32")],["signerSponsoringIDs",e.varArray(e.lookup("SponsorshipDescriptor"),e.lookup("MAX_SIGNERS"))],["ext",e.lookup("AccountEntryExtensionV2Ext")]]),e.union("AccountEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[2,"v2"]],arms:{v2:e.lookup("AccountEntryExtensionV2")}}),e.struct("AccountEntryExtensionV1",[["liabilities",e.lookup("Liabilities")],["ext",e.lookup("AccountEntryExtensionV1Ext")]]),e.union("AccountEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("AccountEntryExtensionV1")}}),e.struct("AccountEntry",[["accountId",e.lookup("AccountId")],["balance",e.lookup("Int64")],["seqNum",e.lookup("SequenceNumber")],["numSubEntries",e.lookup("Uint32")],["inflationDest",e.option(e.lookup("AccountId"))],["flags",e.lookup("Uint32")],["homeDomain",e.lookup("String32")],["thresholds",e.lookup("Thresholds")],["signers",e.varArray(e.lookup("Signer"),e.lookup("MAX_SIGNERS"))],["ext",e.lookup("AccountEntryExt")]]),e.enum("TrustLineFlags",{authorizedFlag:1,authorizedToMaintainLiabilitiesFlag:2,trustlineClawbackEnabledFlag:4}),e.const("MASK_TRUSTLINE_FLAGS",1),e.const("MASK_TRUSTLINE_FLAGS_V13",3),e.const("MASK_TRUSTLINE_FLAGS_V17",7),e.enum("LiquidityPoolType",{liquidityPoolConstantProduct:0}),e.union("TrustLineAsset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"],["assetTypePoolShare","liquidityPoolId"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12"),liquidityPoolId:e.lookup("PoolId")}}),e.union("TrustLineEntryExtensionV2Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TrustLineEntryExtensionV2",[["liquidityPoolUseCount",e.lookup("Int32")],["ext",e.lookup("TrustLineEntryExtensionV2Ext")]]),e.union("TrustLineEntryV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[2,"v2"]],arms:{v2:e.lookup("TrustLineEntryExtensionV2")}}),e.struct("TrustLineEntryV1",[["liabilities",e.lookup("Liabilities")],["ext",e.lookup("TrustLineEntryV1Ext")]]),e.union("TrustLineEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("TrustLineEntryV1")}}),e.struct("TrustLineEntry",[["accountId",e.lookup("AccountId")],["asset",e.lookup("TrustLineAsset")],["balance",e.lookup("Int64")],["limit",e.lookup("Int64")],["flags",e.lookup("Uint32")],["ext",e.lookup("TrustLineEntryExt")]]),e.enum("OfferEntryFlags",{passiveFlag:1}),e.const("MASK_OFFERENTRY_FLAGS",1),e.union("OfferEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("OfferEntry",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")],["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")],["flags",e.lookup("Uint32")],["ext",e.lookup("OfferEntryExt")]]),e.union("DataEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("DataEntry",[["accountId",e.lookup("AccountId")],["dataName",e.lookup("String64")],["dataValue",e.lookup("DataValue")],["ext",e.lookup("DataEntryExt")]]),e.enum("ClaimPredicateType",{claimPredicateUnconditional:0,claimPredicateAnd:1,claimPredicateOr:2,claimPredicateNot:3,claimPredicateBeforeAbsoluteTime:4,claimPredicateBeforeRelativeTime:5}),e.union("ClaimPredicate",{switchOn:e.lookup("ClaimPredicateType"),switchName:"type",switches:[["claimPredicateUnconditional",e.void()],["claimPredicateAnd","andPredicates"],["claimPredicateOr","orPredicates"],["claimPredicateNot","notPredicate"],["claimPredicateBeforeAbsoluteTime","absBefore"],["claimPredicateBeforeRelativeTime","relBefore"]],arms:{andPredicates:e.varArray(e.lookup("ClaimPredicate"),2),orPredicates:e.varArray(e.lookup("ClaimPredicate"),2),notPredicate:e.option(e.lookup("ClaimPredicate")),absBefore:e.lookup("Int64"),relBefore:e.lookup("Int64")}}),e.enum("ClaimantType",{claimantTypeV0:0}),e.struct("ClaimantV0",[["destination",e.lookup("AccountId")],["predicate",e.lookup("ClaimPredicate")]]),e.union("Claimant",{switchOn:e.lookup("ClaimantType"),switchName:"type",switches:[["claimantTypeV0","v0"]],arms:{v0:e.lookup("ClaimantV0")}}),e.enum("ClaimableBalanceIdType",{claimableBalanceIdTypeV0:0}),e.union("ClaimableBalanceId",{switchOn:e.lookup("ClaimableBalanceIdType"),switchName:"type",switches:[["claimableBalanceIdTypeV0","v0"]],arms:{v0:e.lookup("Hash")}}),e.enum("ClaimableBalanceFlags",{claimableBalanceClawbackEnabledFlag:1}),e.const("MASK_CLAIMABLE_BALANCE_FLAGS",1),e.union("ClaimableBalanceEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("ClaimableBalanceEntryExtensionV1",[["ext",e.lookup("ClaimableBalanceEntryExtensionV1Ext")],["flags",e.lookup("Uint32")]]),e.union("ClaimableBalanceEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("ClaimableBalanceEntryExtensionV1")}}),e.struct("ClaimableBalanceEntry",[["balanceId",e.lookup("ClaimableBalanceId")],["claimants",e.varArray(e.lookup("Claimant"),10)],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")],["ext",e.lookup("ClaimableBalanceEntryExt")]]),e.struct("LiquidityPoolConstantProductParameters",[["assetA",e.lookup("Asset")],["assetB",e.lookup("Asset")],["fee",e.lookup("Int32")]]),e.struct("LiquidityPoolEntryConstantProduct",[["params",e.lookup("LiquidityPoolConstantProductParameters")],["reserveA",e.lookup("Int64")],["reserveB",e.lookup("Int64")],["totalPoolShares",e.lookup("Int64")],["poolSharesTrustLineCount",e.lookup("Int64")]]),e.union("LiquidityPoolEntryBody",{switchOn:e.lookup("LiquidityPoolType"),switchName:"type",switches:[["liquidityPoolConstantProduct","constantProduct"]],arms:{constantProduct:e.lookup("LiquidityPoolEntryConstantProduct")}}),e.struct("LiquidityPoolEntry",[["liquidityPoolId",e.lookup("PoolId")],["body",e.lookup("LiquidityPoolEntryBody")]]),e.enum("ContractDataDurability",{temporary:0,persistent:1}),e.struct("ContractDataEntry",[["ext",e.lookup("ExtensionPoint")],["contract",e.lookup("ScAddress")],["key",e.lookup("ScVal")],["durability",e.lookup("ContractDataDurability")],["val",e.lookup("ScVal")]]),e.struct("ContractCodeCostInputs",[["ext",e.lookup("ExtensionPoint")],["nInstructions",e.lookup("Uint32")],["nFunctions",e.lookup("Uint32")],["nGlobals",e.lookup("Uint32")],["nTableEntries",e.lookup("Uint32")],["nTypes",e.lookup("Uint32")],["nDataSegments",e.lookup("Uint32")],["nElemSegments",e.lookup("Uint32")],["nImports",e.lookup("Uint32")],["nExports",e.lookup("Uint32")],["nDataSegmentBytes",e.lookup("Uint32")]]),e.struct("ContractCodeEntryV1",[["ext",e.lookup("ExtensionPoint")],["costInputs",e.lookup("ContractCodeCostInputs")]]),e.union("ContractCodeEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("ContractCodeEntryV1")}}),e.struct("ContractCodeEntry",[["ext",e.lookup("ContractCodeEntryExt")],["hash",e.lookup("Hash")],["code",e.varOpaque()]]),e.struct("TtlEntry",[["keyHash",e.lookup("Hash")],["liveUntilLedgerSeq",e.lookup("Uint32")]]),e.union("LedgerEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerEntryExtensionV1",[["sponsoringId",e.lookup("SponsorshipDescriptor")],["ext",e.lookup("LedgerEntryExtensionV1Ext")]]),e.union("LedgerEntryData",{switchOn:e.lookup("LedgerEntryType"),switchName:"type",switches:[["account","account"],["trustline","trustLine"],["offer","offer"],["data","data"],["claimableBalance","claimableBalance"],["liquidityPool","liquidityPool"],["contractData","contractData"],["contractCode","contractCode"],["configSetting","configSetting"],["ttl","ttl"]],arms:{account:e.lookup("AccountEntry"),trustLine:e.lookup("TrustLineEntry"),offer:e.lookup("OfferEntry"),data:e.lookup("DataEntry"),claimableBalance:e.lookup("ClaimableBalanceEntry"),liquidityPool:e.lookup("LiquidityPoolEntry"),contractData:e.lookup("ContractDataEntry"),contractCode:e.lookup("ContractCodeEntry"),configSetting:e.lookup("ConfigSettingEntry"),ttl:e.lookup("TtlEntry")}}),e.union("LedgerEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerEntryExtensionV1")}}),e.struct("LedgerEntry",[["lastModifiedLedgerSeq",e.lookup("Uint32")],["data",e.lookup("LedgerEntryData")],["ext",e.lookup("LedgerEntryExt")]]),e.struct("LedgerKeyAccount",[["accountId",e.lookup("AccountId")]]),e.struct("LedgerKeyTrustLine",[["accountId",e.lookup("AccountId")],["asset",e.lookup("TrustLineAsset")]]),e.struct("LedgerKeyOffer",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")]]),e.struct("LedgerKeyData",[["accountId",e.lookup("AccountId")],["dataName",e.lookup("String64")]]),e.struct("LedgerKeyClaimableBalance",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("LedgerKeyLiquidityPool",[["liquidityPoolId",e.lookup("PoolId")]]),e.struct("LedgerKeyContractData",[["contract",e.lookup("ScAddress")],["key",e.lookup("ScVal")],["durability",e.lookup("ContractDataDurability")]]),e.struct("LedgerKeyContractCode",[["hash",e.lookup("Hash")]]),e.struct("LedgerKeyConfigSetting",[["configSettingId",e.lookup("ConfigSettingId")]]),e.struct("LedgerKeyTtl",[["keyHash",e.lookup("Hash")]]),e.union("LedgerKey",{switchOn:e.lookup("LedgerEntryType"),switchName:"type",switches:[["account","account"],["trustline","trustLine"],["offer","offer"],["data","data"],["claimableBalance","claimableBalance"],["liquidityPool","liquidityPool"],["contractData","contractData"],["contractCode","contractCode"],["configSetting","configSetting"],["ttl","ttl"]],arms:{account:e.lookup("LedgerKeyAccount"),trustLine:e.lookup("LedgerKeyTrustLine"),offer:e.lookup("LedgerKeyOffer"),data:e.lookup("LedgerKeyData"),claimableBalance:e.lookup("LedgerKeyClaimableBalance"),liquidityPool:e.lookup("LedgerKeyLiquidityPool"),contractData:e.lookup("LedgerKeyContractData"),contractCode:e.lookup("LedgerKeyContractCode"),configSetting:e.lookup("LedgerKeyConfigSetting"),ttl:e.lookup("LedgerKeyTtl")}}),e.enum("EnvelopeType",{envelopeTypeTxV0:0,envelopeTypeScp:1,envelopeTypeTx:2,envelopeTypeAuth:3,envelopeTypeScpvalue:4,envelopeTypeTxFeeBump:5,envelopeTypeOpId:6,envelopeTypePoolRevokeOpId:7,envelopeTypeContractId:8,envelopeTypeSorobanAuthorization:9}),e.enum("BucketListType",{live:0,hotArchive:1,coldArchive:2}),e.enum("BucketEntryType",{metaentry:-1,liveentry:0,deadentry:1,initentry:2}),e.enum("HotArchiveBucketEntryType",{hotArchiveMetaentry:-1,hotArchiveArchived:0,hotArchiveLive:1,hotArchiveDeleted:2}),e.enum("ColdArchiveBucketEntryType",{coldArchiveMetaentry:-1,coldArchiveArchivedLeaf:0,coldArchiveDeletedLeaf:1,coldArchiveBoundaryLeaf:2,coldArchiveHash:3}),e.union("BucketMetadataExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"bucketListType"]],arms:{bucketListType:e.lookup("BucketListType")}}),e.struct("BucketMetadata",[["ledgerVersion",e.lookup("Uint32")],["ext",e.lookup("BucketMetadataExt")]]),e.union("BucketEntry",{switchOn:e.lookup("BucketEntryType"),switchName:"type",switches:[["liveentry","liveEntry"],["initentry","liveEntry"],["deadentry","deadEntry"],["metaentry","metaEntry"]],arms:{liveEntry:e.lookup("LedgerEntry"),deadEntry:e.lookup("LedgerKey"),metaEntry:e.lookup("BucketMetadata")}}),e.union("HotArchiveBucketEntry",{switchOn:e.lookup("HotArchiveBucketEntryType"),switchName:"type",switches:[["hotArchiveArchived","archivedEntry"],["hotArchiveLive","key"],["hotArchiveDeleted","key"],["hotArchiveMetaentry","metaEntry"]],arms:{archivedEntry:e.lookup("LedgerEntry"),key:e.lookup("LedgerKey"),metaEntry:e.lookup("BucketMetadata")}}),e.struct("ColdArchiveArchivedLeaf",[["index",e.lookup("Uint32")],["archivedEntry",e.lookup("LedgerEntry")]]),e.struct("ColdArchiveDeletedLeaf",[["index",e.lookup("Uint32")],["deletedKey",e.lookup("LedgerKey")]]),e.struct("ColdArchiveBoundaryLeaf",[["index",e.lookup("Uint32")],["isLowerBound",e.bool()]]),e.struct("ColdArchiveHashEntry",[["index",e.lookup("Uint32")],["level",e.lookup("Uint32")],["hash",e.lookup("Hash")]]),e.union("ColdArchiveBucketEntry",{switchOn:e.lookup("ColdArchiveBucketEntryType"),switchName:"type",switches:[["coldArchiveMetaentry","metaEntry"],["coldArchiveArchivedLeaf","archivedLeaf"],["coldArchiveDeletedLeaf","deletedLeaf"],["coldArchiveBoundaryLeaf","boundaryLeaf"],["coldArchiveHash","hashEntry"]],arms:{metaEntry:e.lookup("BucketMetadata"),archivedLeaf:e.lookup("ColdArchiveArchivedLeaf"),deletedLeaf:e.lookup("ColdArchiveDeletedLeaf"),boundaryLeaf:e.lookup("ColdArchiveBoundaryLeaf"),hashEntry:e.lookup("ColdArchiveHashEntry")}}),e.typedef("UpgradeType",e.varOpaque(128)),e.enum("StellarValueType",{stellarValueBasic:0,stellarValueSigned:1}),e.struct("LedgerCloseValueSignature",[["nodeId",e.lookup("NodeId")],["signature",e.lookup("Signature")]]),e.union("StellarValueExt",{switchOn:e.lookup("StellarValueType"),switchName:"v",switches:[["stellarValueBasic",e.void()],["stellarValueSigned","lcValueSignature"]],arms:{lcValueSignature:e.lookup("LedgerCloseValueSignature")}}),e.struct("StellarValue",[["txSetHash",e.lookup("Hash")],["closeTime",e.lookup("TimePoint")],["upgrades",e.varArray(e.lookup("UpgradeType"),6)],["ext",e.lookup("StellarValueExt")]]),e.const("MASK_LEDGER_HEADER_FLAGS",7),e.enum("LedgerHeaderFlags",{disableLiquidityPoolTradingFlag:1,disableLiquidityPoolDepositFlag:2,disableLiquidityPoolWithdrawalFlag:4}),e.union("LedgerHeaderExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerHeaderExtensionV1",[["flags",e.lookup("Uint32")],["ext",e.lookup("LedgerHeaderExtensionV1Ext")]]),e.union("LedgerHeaderExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerHeaderExtensionV1")}}),e.struct("LedgerHeader",[["ledgerVersion",e.lookup("Uint32")],["previousLedgerHash",e.lookup("Hash")],["scpValue",e.lookup("StellarValue")],["txSetResultHash",e.lookup("Hash")],["bucketListHash",e.lookup("Hash")],["ledgerSeq",e.lookup("Uint32")],["totalCoins",e.lookup("Int64")],["feePool",e.lookup("Int64")],["inflationSeq",e.lookup("Uint32")],["idPool",e.lookup("Uint64")],["baseFee",e.lookup("Uint32")],["baseReserve",e.lookup("Uint32")],["maxTxSetSize",e.lookup("Uint32")],["skipList",e.array(e.lookup("Hash"),4)],["ext",e.lookup("LedgerHeaderExt")]]),e.enum("LedgerUpgradeType",{ledgerUpgradeVersion:1,ledgerUpgradeBaseFee:2,ledgerUpgradeMaxTxSetSize:3,ledgerUpgradeBaseReserve:4,ledgerUpgradeFlags:5,ledgerUpgradeConfig:6,ledgerUpgradeMaxSorobanTxSetSize:7}),e.struct("ConfigUpgradeSetKey",[["contractId",e.lookup("Hash")],["contentHash",e.lookup("Hash")]]),e.union("LedgerUpgrade",{switchOn:e.lookup("LedgerUpgradeType"),switchName:"type",switches:[["ledgerUpgradeVersion","newLedgerVersion"],["ledgerUpgradeBaseFee","newBaseFee"],["ledgerUpgradeMaxTxSetSize","newMaxTxSetSize"],["ledgerUpgradeBaseReserve","newBaseReserve"],["ledgerUpgradeFlags","newFlags"],["ledgerUpgradeConfig","newConfig"],["ledgerUpgradeMaxSorobanTxSetSize","newMaxSorobanTxSetSize"]],arms:{newLedgerVersion:e.lookup("Uint32"),newBaseFee:e.lookup("Uint32"),newMaxTxSetSize:e.lookup("Uint32"),newBaseReserve:e.lookup("Uint32"),newFlags:e.lookup("Uint32"),newConfig:e.lookup("ConfigUpgradeSetKey"),newMaxSorobanTxSetSize:e.lookup("Uint32")}}),e.struct("ConfigUpgradeSet",[["updatedEntry",e.varArray(e.lookup("ConfigSettingEntry"),2147483647)]]),e.enum("TxSetComponentType",{txsetCompTxsMaybeDiscountedFee:0}),e.struct("TxSetComponentTxsMaybeDiscountedFee",[["baseFee",e.option(e.lookup("Int64"))],["txes",e.varArray(e.lookup("TransactionEnvelope"),2147483647)]]),e.union("TxSetComponent",{switchOn:e.lookup("TxSetComponentType"),switchName:"type",switches:[["txsetCompTxsMaybeDiscountedFee","txsMaybeDiscountedFee"]],arms:{txsMaybeDiscountedFee:e.lookup("TxSetComponentTxsMaybeDiscountedFee")}}),e.union("TransactionPhase",{switchOn:e.int(),switchName:"v",switches:[[0,"v0Components"]],arms:{v0Components:e.varArray(e.lookup("TxSetComponent"),2147483647)}}),e.struct("TransactionSet",[["previousLedgerHash",e.lookup("Hash")],["txes",e.varArray(e.lookup("TransactionEnvelope"),2147483647)]]),e.struct("TransactionSetV1",[["previousLedgerHash",e.lookup("Hash")],["phases",e.varArray(e.lookup("TransactionPhase"),2147483647)]]),e.union("GeneralizedTransactionSet",{switchOn:e.int(),switchName:"v",switches:[[1,"v1TxSet"]],arms:{v1TxSet:e.lookup("TransactionSetV1")}}),e.struct("TransactionResultPair",[["transactionHash",e.lookup("Hash")],["result",e.lookup("TransactionResult")]]),e.struct("TransactionResultSet",[["results",e.varArray(e.lookup("TransactionResultPair"),2147483647)]]),e.union("TransactionHistoryEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"generalizedTxSet"]],arms:{generalizedTxSet:e.lookup("GeneralizedTransactionSet")}}),e.struct("TransactionHistoryEntry",[["ledgerSeq",e.lookup("Uint32")],["txSet",e.lookup("TransactionSet")],["ext",e.lookup("TransactionHistoryEntryExt")]]),e.union("TransactionHistoryResultEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionHistoryResultEntry",[["ledgerSeq",e.lookup("Uint32")],["txResultSet",e.lookup("TransactionResultSet")],["ext",e.lookup("TransactionHistoryResultEntryExt")]]),e.union("LedgerHeaderHistoryEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerHeaderHistoryEntry",[["hash",e.lookup("Hash")],["header",e.lookup("LedgerHeader")],["ext",e.lookup("LedgerHeaderHistoryEntryExt")]]),e.struct("LedgerScpMessages",[["ledgerSeq",e.lookup("Uint32")],["messages",e.varArray(e.lookup("ScpEnvelope"),2147483647)]]),e.struct("ScpHistoryEntryV0",[["quorumSets",e.varArray(e.lookup("ScpQuorumSet"),2147483647)],["ledgerMessages",e.lookup("LedgerScpMessages")]]),e.union("ScpHistoryEntry",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("ScpHistoryEntryV0")}}),e.enum("LedgerEntryChangeType",{ledgerEntryCreated:0,ledgerEntryUpdated:1,ledgerEntryRemoved:2,ledgerEntryState:3}),e.union("LedgerEntryChange",{switchOn:e.lookup("LedgerEntryChangeType"),switchName:"type",switches:[["ledgerEntryCreated","created"],["ledgerEntryUpdated","updated"],["ledgerEntryRemoved","removed"],["ledgerEntryState","state"]],arms:{created:e.lookup("LedgerEntry"),updated:e.lookup("LedgerEntry"),removed:e.lookup("LedgerKey"),state:e.lookup("LedgerEntry")}}),e.typedef("LedgerEntryChanges",e.varArray(e.lookup("LedgerEntryChange"),2147483647)),e.struct("OperationMeta",[["changes",e.lookup("LedgerEntryChanges")]]),e.struct("TransactionMetaV1",[["txChanges",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)]]),e.struct("TransactionMetaV2",[["txChangesBefore",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)],["txChangesAfter",e.lookup("LedgerEntryChanges")]]),e.enum("ContractEventType",{system:0,contract:1,diagnostic:2}),e.struct("ContractEventV0",[["topics",e.varArray(e.lookup("ScVal"),2147483647)],["data",e.lookup("ScVal")]]),e.union("ContractEventBody",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("ContractEventV0")}}),e.struct("ContractEvent",[["ext",e.lookup("ExtensionPoint")],["contractId",e.option(e.lookup("Hash"))],["type",e.lookup("ContractEventType")],["body",e.lookup("ContractEventBody")]]),e.struct("DiagnosticEvent",[["inSuccessfulContractCall",e.bool()],["event",e.lookup("ContractEvent")]]),e.typedef("DiagnosticEvents",e.varArray(e.lookup("DiagnosticEvent"),2147483647)),e.struct("SorobanTransactionMetaExtV1",[["ext",e.lookup("ExtensionPoint")],["totalNonRefundableResourceFeeCharged",e.lookup("Int64")],["totalRefundableResourceFeeCharged",e.lookup("Int64")],["rentFeeCharged",e.lookup("Int64")]]),e.union("SorobanTransactionMetaExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("SorobanTransactionMetaExtV1")}}),e.struct("SorobanTransactionMeta",[["ext",e.lookup("SorobanTransactionMetaExt")],["events",e.varArray(e.lookup("ContractEvent"),2147483647)],["returnValue",e.lookup("ScVal")],["diagnosticEvents",e.varArray(e.lookup("DiagnosticEvent"),2147483647)]]),e.struct("TransactionMetaV3",[["ext",e.lookup("ExtensionPoint")],["txChangesBefore",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)],["txChangesAfter",e.lookup("LedgerEntryChanges")],["sorobanMeta",e.option(e.lookup("SorobanTransactionMeta"))]]),e.struct("InvokeHostFunctionSuccessPreImage",[["returnValue",e.lookup("ScVal")],["events",e.varArray(e.lookup("ContractEvent"),2147483647)]]),e.union("TransactionMeta",{switchOn:e.int(),switchName:"v",switches:[[0,"operations"],[1,"v1"],[2,"v2"],[3,"v3"]],arms:{operations:e.varArray(e.lookup("OperationMeta"),2147483647),v1:e.lookup("TransactionMetaV1"),v2:e.lookup("TransactionMetaV2"),v3:e.lookup("TransactionMetaV3")}}),e.struct("TransactionResultMeta",[["result",e.lookup("TransactionResultPair")],["feeProcessing",e.lookup("LedgerEntryChanges")],["txApplyProcessing",e.lookup("TransactionMeta")]]),e.struct("UpgradeEntryMeta",[["upgrade",e.lookup("LedgerUpgrade")],["changes",e.lookup("LedgerEntryChanges")]]),e.struct("LedgerCloseMetaV0",[["ledgerHeader",e.lookup("LedgerHeaderHistoryEntry")],["txSet",e.lookup("TransactionSet")],["txProcessing",e.varArray(e.lookup("TransactionResultMeta"),2147483647)],["upgradesProcessing",e.varArray(e.lookup("UpgradeEntryMeta"),2147483647)],["scpInfo",e.varArray(e.lookup("ScpHistoryEntry"),2147483647)]]),e.struct("LedgerCloseMetaExtV1",[["ext",e.lookup("ExtensionPoint")],["sorobanFeeWrite1Kb",e.lookup("Int64")]]),e.union("LedgerCloseMetaExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerCloseMetaExtV1")}}),e.struct("LedgerCloseMetaV1",[["ext",e.lookup("LedgerCloseMetaExt")],["ledgerHeader",e.lookup("LedgerHeaderHistoryEntry")],["txSet",e.lookup("GeneralizedTransactionSet")],["txProcessing",e.varArray(e.lookup("TransactionResultMeta"),2147483647)],["upgradesProcessing",e.varArray(e.lookup("UpgradeEntryMeta"),2147483647)],["scpInfo",e.varArray(e.lookup("ScpHistoryEntry"),2147483647)],["totalByteSizeOfBucketList",e.lookup("Uint64")],["evictedTemporaryLedgerKeys",e.varArray(e.lookup("LedgerKey"),2147483647)],["evictedPersistentLedgerEntries",e.varArray(e.lookup("LedgerEntry"),2147483647)]]),e.union("LedgerCloseMeta",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"],[1,"v1"]],arms:{v0:e.lookup("LedgerCloseMetaV0"),v1:e.lookup("LedgerCloseMetaV1")}}),e.enum("ErrorCode",{errMisc:0,errData:1,errConf:2,errAuth:3,errLoad:4}),e.struct("Error",[["code",e.lookup("ErrorCode")],["msg",e.string(100)]]),e.struct("SendMore",[["numMessages",e.lookup("Uint32")]]),e.struct("SendMoreExtended",[["numMessages",e.lookup("Uint32")],["numBytes",e.lookup("Uint32")]]),e.struct("AuthCert",[["pubkey",e.lookup("Curve25519Public")],["expiration",e.lookup("Uint64")],["sig",e.lookup("Signature")]]),e.struct("Hello",[["ledgerVersion",e.lookup("Uint32")],["overlayVersion",e.lookup("Uint32")],["overlayMinVersion",e.lookup("Uint32")],["networkId",e.lookup("Hash")],["versionStr",e.string(100)],["listeningPort",e.int()],["peerId",e.lookup("NodeId")],["cert",e.lookup("AuthCert")],["nonce",e.lookup("Uint256")]]),e.const("AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED",200),e.struct("Auth",[["flags",e.int()]]),e.enum("IpAddrType",{iPv4:0,iPv6:1}),e.union("PeerAddressIp",{switchOn:e.lookup("IpAddrType"),switchName:"type",switches:[["iPv4","ipv4"],["iPv6","ipv6"]],arms:{ipv4:e.opaque(4),ipv6:e.opaque(16)}}),e.struct("PeerAddress",[["ip",e.lookup("PeerAddressIp")],["port",e.lookup("Uint32")],["numFailures",e.lookup("Uint32")]]),e.enum("MessageType",{errorMsg:0,auth:2,dontHave:3,getPeers:4,peers:5,getTxSet:6,txSet:7,generalizedTxSet:17,transaction:8,getScpQuorumset:9,scpQuorumset:10,scpMessage:11,getScpState:12,hello:13,surveyRequest:14,surveyResponse:15,sendMore:16,sendMoreExtended:20,floodAdvert:18,floodDemand:19,timeSlicedSurveyRequest:21,timeSlicedSurveyResponse:22,timeSlicedSurveyStartCollecting:23,timeSlicedSurveyStopCollecting:24}),e.struct("DontHave",[["type",e.lookup("MessageType")],["reqHash",e.lookup("Uint256")]]),e.enum("SurveyMessageCommandType",{surveyTopology:0,timeSlicedSurveyTopology:1}),e.enum("SurveyMessageResponseType",{surveyTopologyResponseV0:0,surveyTopologyResponseV1:1,surveyTopologyResponseV2:2}),e.struct("TimeSlicedSurveyStartCollectingMessage",[["surveyorId",e.lookup("NodeId")],["nonce",e.lookup("Uint32")],["ledgerNum",e.lookup("Uint32")]]),e.struct("SignedTimeSlicedSurveyStartCollectingMessage",[["signature",e.lookup("Signature")],["startCollecting",e.lookup("TimeSlicedSurveyStartCollectingMessage")]]),e.struct("TimeSlicedSurveyStopCollectingMessage",[["surveyorId",e.lookup("NodeId")],["nonce",e.lookup("Uint32")],["ledgerNum",e.lookup("Uint32")]]),e.struct("SignedTimeSlicedSurveyStopCollectingMessage",[["signature",e.lookup("Signature")],["stopCollecting",e.lookup("TimeSlicedSurveyStopCollectingMessage")]]),e.struct("SurveyRequestMessage",[["surveyorPeerId",e.lookup("NodeId")],["surveyedPeerId",e.lookup("NodeId")],["ledgerNum",e.lookup("Uint32")],["encryptionKey",e.lookup("Curve25519Public")],["commandType",e.lookup("SurveyMessageCommandType")]]),e.struct("TimeSlicedSurveyRequestMessage",[["request",e.lookup("SurveyRequestMessage")],["nonce",e.lookup("Uint32")],["inboundPeersIndex",e.lookup("Uint32")],["outboundPeersIndex",e.lookup("Uint32")]]),e.struct("SignedSurveyRequestMessage",[["requestSignature",e.lookup("Signature")],["request",e.lookup("SurveyRequestMessage")]]),e.struct("SignedTimeSlicedSurveyRequestMessage",[["requestSignature",e.lookup("Signature")],["request",e.lookup("TimeSlicedSurveyRequestMessage")]]),e.typedef("EncryptedBody",e.varOpaque(64e3)),e.struct("SurveyResponseMessage",[["surveyorPeerId",e.lookup("NodeId")],["surveyedPeerId",e.lookup("NodeId")],["ledgerNum",e.lookup("Uint32")],["commandType",e.lookup("SurveyMessageCommandType")],["encryptedBody",e.lookup("EncryptedBody")]]),e.struct("TimeSlicedSurveyResponseMessage",[["response",e.lookup("SurveyResponseMessage")],["nonce",e.lookup("Uint32")]]),e.struct("SignedSurveyResponseMessage",[["responseSignature",e.lookup("Signature")],["response",e.lookup("SurveyResponseMessage")]]),e.struct("SignedTimeSlicedSurveyResponseMessage",[["responseSignature",e.lookup("Signature")],["response",e.lookup("TimeSlicedSurveyResponseMessage")]]),e.struct("PeerStats",[["id",e.lookup("NodeId")],["versionStr",e.string(100)],["messagesRead",e.lookup("Uint64")],["messagesWritten",e.lookup("Uint64")],["bytesRead",e.lookup("Uint64")],["bytesWritten",e.lookup("Uint64")],["secondsConnected",e.lookup("Uint64")],["uniqueFloodBytesRecv",e.lookup("Uint64")],["duplicateFloodBytesRecv",e.lookup("Uint64")],["uniqueFetchBytesRecv",e.lookup("Uint64")],["duplicateFetchBytesRecv",e.lookup("Uint64")],["uniqueFloodMessageRecv",e.lookup("Uint64")],["duplicateFloodMessageRecv",e.lookup("Uint64")],["uniqueFetchMessageRecv",e.lookup("Uint64")],["duplicateFetchMessageRecv",e.lookup("Uint64")]]),e.typedef("PeerStatList",e.varArray(e.lookup("PeerStats"),25)),e.struct("TimeSlicedNodeData",[["addedAuthenticatedPeers",e.lookup("Uint32")],["droppedAuthenticatedPeers",e.lookup("Uint32")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")],["p75ScpFirstToSelfLatencyMs",e.lookup("Uint32")],["p75ScpSelfToOtherLatencyMs",e.lookup("Uint32")],["lostSyncCount",e.lookup("Uint32")],["isValidator",e.bool()],["maxInboundPeerCount",e.lookup("Uint32")],["maxOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TimeSlicedPeerData",[["peerStats",e.lookup("PeerStats")],["averageLatencyMs",e.lookup("Uint32")]]),e.typedef("TimeSlicedPeerDataList",e.varArray(e.lookup("TimeSlicedPeerData"),25)),e.struct("TopologyResponseBodyV0",[["inboundPeers",e.lookup("PeerStatList")],["outboundPeers",e.lookup("PeerStatList")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TopologyResponseBodyV1",[["inboundPeers",e.lookup("PeerStatList")],["outboundPeers",e.lookup("PeerStatList")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")],["maxInboundPeerCount",e.lookup("Uint32")],["maxOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TopologyResponseBodyV2",[["inboundPeers",e.lookup("TimeSlicedPeerDataList")],["outboundPeers",e.lookup("TimeSlicedPeerDataList")],["nodeData",e.lookup("TimeSlicedNodeData")]]),e.union("SurveyResponseBody",{switchOn:e.lookup("SurveyMessageResponseType"),switchName:"type",switches:[["surveyTopologyResponseV0","topologyResponseBodyV0"],["surveyTopologyResponseV1","topologyResponseBodyV1"],["surveyTopologyResponseV2","topologyResponseBodyV2"]],arms:{topologyResponseBodyV0:e.lookup("TopologyResponseBodyV0"),topologyResponseBodyV1:e.lookup("TopologyResponseBodyV1"),topologyResponseBodyV2:e.lookup("TopologyResponseBodyV2")}}),e.const("TX_ADVERT_VECTOR_MAX_SIZE",1e3),e.typedef("TxAdvertVector",e.varArray(e.lookup("Hash"),e.lookup("TX_ADVERT_VECTOR_MAX_SIZE"))),e.struct("FloodAdvert",[["txHashes",e.lookup("TxAdvertVector")]]),e.const("TX_DEMAND_VECTOR_MAX_SIZE",1e3),e.typedef("TxDemandVector",e.varArray(e.lookup("Hash"),e.lookup("TX_DEMAND_VECTOR_MAX_SIZE"))),e.struct("FloodDemand",[["txHashes",e.lookup("TxDemandVector")]]),e.union("StellarMessage",{switchOn:e.lookup("MessageType"),switchName:"type",switches:[["errorMsg","error"],["hello","hello"],["auth","auth"],["dontHave","dontHave"],["getPeers",e.void()],["peers","peers"],["getTxSet","txSetHash"],["txSet","txSet"],["generalizedTxSet","generalizedTxSet"],["transaction","transaction"],["surveyRequest","signedSurveyRequestMessage"],["surveyResponse","signedSurveyResponseMessage"],["timeSlicedSurveyRequest","signedTimeSlicedSurveyRequestMessage"],["timeSlicedSurveyResponse","signedTimeSlicedSurveyResponseMessage"],["timeSlicedSurveyStartCollecting","signedTimeSlicedSurveyStartCollectingMessage"],["timeSlicedSurveyStopCollecting","signedTimeSlicedSurveyStopCollectingMessage"],["getScpQuorumset","qSetHash"],["scpQuorumset","qSet"],["scpMessage","envelope"],["getScpState","getScpLedgerSeq"],["sendMore","sendMoreMessage"],["sendMoreExtended","sendMoreExtendedMessage"],["floodAdvert","floodAdvert"],["floodDemand","floodDemand"]],arms:{error:e.lookup("Error"),hello:e.lookup("Hello"),auth:e.lookup("Auth"),dontHave:e.lookup("DontHave"),peers:e.varArray(e.lookup("PeerAddress"),100),txSetHash:e.lookup("Uint256"),txSet:e.lookup("TransactionSet"),generalizedTxSet:e.lookup("GeneralizedTransactionSet"),transaction:e.lookup("TransactionEnvelope"),signedSurveyRequestMessage:e.lookup("SignedSurveyRequestMessage"),signedSurveyResponseMessage:e.lookup("SignedSurveyResponseMessage"),signedTimeSlicedSurveyRequestMessage:e.lookup("SignedTimeSlicedSurveyRequestMessage"),signedTimeSlicedSurveyResponseMessage:e.lookup("SignedTimeSlicedSurveyResponseMessage"),signedTimeSlicedSurveyStartCollectingMessage:e.lookup("SignedTimeSlicedSurveyStartCollectingMessage"),signedTimeSlicedSurveyStopCollectingMessage:e.lookup("SignedTimeSlicedSurveyStopCollectingMessage"),qSetHash:e.lookup("Uint256"),qSet:e.lookup("ScpQuorumSet"),envelope:e.lookup("ScpEnvelope"),getScpLedgerSeq:e.lookup("Uint32"),sendMoreMessage:e.lookup("SendMore"),sendMoreExtendedMessage:e.lookup("SendMoreExtended"),floodAdvert:e.lookup("FloodAdvert"),floodDemand:e.lookup("FloodDemand")}}),e.struct("AuthenticatedMessageV0",[["sequence",e.lookup("Uint64")],["message",e.lookup("StellarMessage")],["mac",e.lookup("HmacSha256Mac")]]),e.union("AuthenticatedMessage",{switchOn:e.lookup("Uint32"),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("AuthenticatedMessageV0")}}),e.const("MAX_OPS_PER_TX",100),e.union("LiquidityPoolParameters",{switchOn:e.lookup("LiquidityPoolType"),switchName:"type",switches:[["liquidityPoolConstantProduct","constantProduct"]],arms:{constantProduct:e.lookup("LiquidityPoolConstantProductParameters")}}),e.struct("MuxedAccountMed25519",[["id",e.lookup("Uint64")],["ed25519",e.lookup("Uint256")]]),e.union("MuxedAccount",{switchOn:e.lookup("CryptoKeyType"),switchName:"type",switches:[["keyTypeEd25519","ed25519"],["keyTypeMuxedEd25519","med25519"]],arms:{ed25519:e.lookup("Uint256"),med25519:e.lookup("MuxedAccountMed25519")}}),e.struct("DecoratedSignature",[["hint",e.lookup("SignatureHint")],["signature",e.lookup("Signature")]]),e.enum("OperationType",{createAccount:0,payment:1,pathPaymentStrictReceive:2,manageSellOffer:3,createPassiveSellOffer:4,setOptions:5,changeTrust:6,allowTrust:7,accountMerge:8,inflation:9,manageData:10,bumpSequence:11,manageBuyOffer:12,pathPaymentStrictSend:13,createClaimableBalance:14,claimClaimableBalance:15,beginSponsoringFutureReserves:16,endSponsoringFutureReserves:17,revokeSponsorship:18,clawback:19,clawbackClaimableBalance:20,setTrustLineFlags:21,liquidityPoolDeposit:22,liquidityPoolWithdraw:23,invokeHostFunction:24,extendFootprintTtl:25,restoreFootprint:26}),e.struct("CreateAccountOp",[["destination",e.lookup("AccountId")],["startingBalance",e.lookup("Int64")]]),e.struct("PaymentOp",[["destination",e.lookup("MuxedAccount")],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")]]),e.struct("PathPaymentStrictReceiveOp",[["sendAsset",e.lookup("Asset")],["sendMax",e.lookup("Int64")],["destination",e.lookup("MuxedAccount")],["destAsset",e.lookup("Asset")],["destAmount",e.lookup("Int64")],["path",e.varArray(e.lookup("Asset"),5)]]),e.struct("PathPaymentStrictSendOp",[["sendAsset",e.lookup("Asset")],["sendAmount",e.lookup("Int64")],["destination",e.lookup("MuxedAccount")],["destAsset",e.lookup("Asset")],["destMin",e.lookup("Int64")],["path",e.varArray(e.lookup("Asset"),5)]]),e.struct("ManageSellOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")],["offerId",e.lookup("Int64")]]),e.struct("ManageBuyOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["buyAmount",e.lookup("Int64")],["price",e.lookup("Price")],["offerId",e.lookup("Int64")]]),e.struct("CreatePassiveSellOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")]]),e.struct("SetOptionsOp",[["inflationDest",e.option(e.lookup("AccountId"))],["clearFlags",e.option(e.lookup("Uint32"))],["setFlags",e.option(e.lookup("Uint32"))],["masterWeight",e.option(e.lookup("Uint32"))],["lowThreshold",e.option(e.lookup("Uint32"))],["medThreshold",e.option(e.lookup("Uint32"))],["highThreshold",e.option(e.lookup("Uint32"))],["homeDomain",e.option(e.lookup("String32"))],["signer",e.option(e.lookup("Signer"))]]),e.union("ChangeTrustAsset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"],["assetTypePoolShare","liquidityPool"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12"),liquidityPool:e.lookup("LiquidityPoolParameters")}}),e.struct("ChangeTrustOp",[["line",e.lookup("ChangeTrustAsset")],["limit",e.lookup("Int64")]]),e.struct("AllowTrustOp",[["trustor",e.lookup("AccountId")],["asset",e.lookup("AssetCode")],["authorize",e.lookup("Uint32")]]),e.struct("ManageDataOp",[["dataName",e.lookup("String64")],["dataValue",e.option(e.lookup("DataValue"))]]),e.struct("BumpSequenceOp",[["bumpTo",e.lookup("SequenceNumber")]]),e.struct("CreateClaimableBalanceOp",[["asset",e.lookup("Asset")],["amount",e.lookup("Int64")],["claimants",e.varArray(e.lookup("Claimant"),10)]]),e.struct("ClaimClaimableBalanceOp",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("BeginSponsoringFutureReservesOp",[["sponsoredId",e.lookup("AccountId")]]),e.enum("RevokeSponsorshipType",{revokeSponsorshipLedgerEntry:0,revokeSponsorshipSigner:1}),e.struct("RevokeSponsorshipOpSigner",[["accountId",e.lookup("AccountId")],["signerKey",e.lookup("SignerKey")]]),e.union("RevokeSponsorshipOp",{switchOn:e.lookup("RevokeSponsorshipType"),switchName:"type",switches:[["revokeSponsorshipLedgerEntry","ledgerKey"],["revokeSponsorshipSigner","signer"]],arms:{ledgerKey:e.lookup("LedgerKey"),signer:e.lookup("RevokeSponsorshipOpSigner")}}),e.struct("ClawbackOp",[["asset",e.lookup("Asset")],["from",e.lookup("MuxedAccount")],["amount",e.lookup("Int64")]]),e.struct("ClawbackClaimableBalanceOp",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("SetTrustLineFlagsOp",[["trustor",e.lookup("AccountId")],["asset",e.lookup("Asset")],["clearFlags",e.lookup("Uint32")],["setFlags",e.lookup("Uint32")]]),e.const("LIQUIDITY_POOL_FEE_V18",30),e.struct("LiquidityPoolDepositOp",[["liquidityPoolId",e.lookup("PoolId")],["maxAmountA",e.lookup("Int64")],["maxAmountB",e.lookup("Int64")],["minPrice",e.lookup("Price")],["maxPrice",e.lookup("Price")]]),e.struct("LiquidityPoolWithdrawOp",[["liquidityPoolId",e.lookup("PoolId")],["amount",e.lookup("Int64")],["minAmountA",e.lookup("Int64")],["minAmountB",e.lookup("Int64")]]),e.enum("HostFunctionType",{hostFunctionTypeInvokeContract:0,hostFunctionTypeCreateContract:1,hostFunctionTypeUploadContractWasm:2,hostFunctionTypeCreateContractV2:3}),e.enum("ContractIdPreimageType",{contractIdPreimageFromAddress:0,contractIdPreimageFromAsset:1}),e.struct("ContractIdPreimageFromAddress",[["address",e.lookup("ScAddress")],["salt",e.lookup("Uint256")]]),e.union("ContractIdPreimage",{switchOn:e.lookup("ContractIdPreimageType"),switchName:"type",switches:[["contractIdPreimageFromAddress","fromAddress"],["contractIdPreimageFromAsset","fromAsset"]],arms:{fromAddress:e.lookup("ContractIdPreimageFromAddress"),fromAsset:e.lookup("Asset")}}),e.struct("CreateContractArgs",[["contractIdPreimage",e.lookup("ContractIdPreimage")],["executable",e.lookup("ContractExecutable")]]),e.struct("CreateContractArgsV2",[["contractIdPreimage",e.lookup("ContractIdPreimage")],["executable",e.lookup("ContractExecutable")],["constructorArgs",e.varArray(e.lookup("ScVal"),2147483647)]]),e.struct("InvokeContractArgs",[["contractAddress",e.lookup("ScAddress")],["functionName",e.lookup("ScSymbol")],["args",e.varArray(e.lookup("ScVal"),2147483647)]]),e.union("HostFunction",{switchOn:e.lookup("HostFunctionType"),switchName:"type",switches:[["hostFunctionTypeInvokeContract","invokeContract"],["hostFunctionTypeCreateContract","createContract"],["hostFunctionTypeUploadContractWasm","wasm"],["hostFunctionTypeCreateContractV2","createContractV2"]],arms:{invokeContract:e.lookup("InvokeContractArgs"),createContract:e.lookup("CreateContractArgs"),wasm:e.varOpaque(),createContractV2:e.lookup("CreateContractArgsV2")}}),e.enum("SorobanAuthorizedFunctionType",{sorobanAuthorizedFunctionTypeContractFn:0,sorobanAuthorizedFunctionTypeCreateContractHostFn:1,sorobanAuthorizedFunctionTypeCreateContractV2HostFn:2}),e.union("SorobanAuthorizedFunction",{switchOn:e.lookup("SorobanAuthorizedFunctionType"),switchName:"type",switches:[["sorobanAuthorizedFunctionTypeContractFn","contractFn"],["sorobanAuthorizedFunctionTypeCreateContractHostFn","createContractHostFn"],["sorobanAuthorizedFunctionTypeCreateContractV2HostFn","createContractV2HostFn"]],arms:{contractFn:e.lookup("InvokeContractArgs"),createContractHostFn:e.lookup("CreateContractArgs"),createContractV2HostFn:e.lookup("CreateContractArgsV2")}}),e.struct("SorobanAuthorizedInvocation",[["function",e.lookup("SorobanAuthorizedFunction")],["subInvocations",e.varArray(e.lookup("SorobanAuthorizedInvocation"),2147483647)]]),e.struct("SorobanAddressCredentials",[["address",e.lookup("ScAddress")],["nonce",e.lookup("Int64")],["signatureExpirationLedger",e.lookup("Uint32")],["signature",e.lookup("ScVal")]]),e.enum("SorobanCredentialsType",{sorobanCredentialsSourceAccount:0,sorobanCredentialsAddress:1}),e.union("SorobanCredentials",{switchOn:e.lookup("SorobanCredentialsType"),switchName:"type",switches:[["sorobanCredentialsSourceAccount",e.void()],["sorobanCredentialsAddress","address"]],arms:{address:e.lookup("SorobanAddressCredentials")}}),e.struct("SorobanAuthorizationEntry",[["credentials",e.lookup("SorobanCredentials")],["rootInvocation",e.lookup("SorobanAuthorizedInvocation")]]),e.struct("InvokeHostFunctionOp",[["hostFunction",e.lookup("HostFunction")],["auth",e.varArray(e.lookup("SorobanAuthorizationEntry"),2147483647)]]),e.struct("ExtendFootprintTtlOp",[["ext",e.lookup("ExtensionPoint")],["extendTo",e.lookup("Uint32")]]),e.struct("RestoreFootprintOp",[["ext",e.lookup("ExtensionPoint")]]),e.union("OperationBody",{switchOn:e.lookup("OperationType"),switchName:"type",switches:[["createAccount","createAccountOp"],["payment","paymentOp"],["pathPaymentStrictReceive","pathPaymentStrictReceiveOp"],["manageSellOffer","manageSellOfferOp"],["createPassiveSellOffer","createPassiveSellOfferOp"],["setOptions","setOptionsOp"],["changeTrust","changeTrustOp"],["allowTrust","allowTrustOp"],["accountMerge","destination"],["inflation",e.void()],["manageData","manageDataOp"],["bumpSequence","bumpSequenceOp"],["manageBuyOffer","manageBuyOfferOp"],["pathPaymentStrictSend","pathPaymentStrictSendOp"],["createClaimableBalance","createClaimableBalanceOp"],["claimClaimableBalance","claimClaimableBalanceOp"],["beginSponsoringFutureReserves","beginSponsoringFutureReservesOp"],["endSponsoringFutureReserves",e.void()],["revokeSponsorship","revokeSponsorshipOp"],["clawback","clawbackOp"],["clawbackClaimableBalance","clawbackClaimableBalanceOp"],["setTrustLineFlags","setTrustLineFlagsOp"],["liquidityPoolDeposit","liquidityPoolDepositOp"],["liquidityPoolWithdraw","liquidityPoolWithdrawOp"],["invokeHostFunction","invokeHostFunctionOp"],["extendFootprintTtl","extendFootprintTtlOp"],["restoreFootprint","restoreFootprintOp"]],arms:{createAccountOp:e.lookup("CreateAccountOp"),paymentOp:e.lookup("PaymentOp"),pathPaymentStrictReceiveOp:e.lookup("PathPaymentStrictReceiveOp"),manageSellOfferOp:e.lookup("ManageSellOfferOp"),createPassiveSellOfferOp:e.lookup("CreatePassiveSellOfferOp"),setOptionsOp:e.lookup("SetOptionsOp"),changeTrustOp:e.lookup("ChangeTrustOp"),allowTrustOp:e.lookup("AllowTrustOp"),destination:e.lookup("MuxedAccount"),manageDataOp:e.lookup("ManageDataOp"),bumpSequenceOp:e.lookup("BumpSequenceOp"),manageBuyOfferOp:e.lookup("ManageBuyOfferOp"),pathPaymentStrictSendOp:e.lookup("PathPaymentStrictSendOp"),createClaimableBalanceOp:e.lookup("CreateClaimableBalanceOp"),claimClaimableBalanceOp:e.lookup("ClaimClaimableBalanceOp"),beginSponsoringFutureReservesOp:e.lookup("BeginSponsoringFutureReservesOp"),revokeSponsorshipOp:e.lookup("RevokeSponsorshipOp"),clawbackOp:e.lookup("ClawbackOp"),clawbackClaimableBalanceOp:e.lookup("ClawbackClaimableBalanceOp"),setTrustLineFlagsOp:e.lookup("SetTrustLineFlagsOp"),liquidityPoolDepositOp:e.lookup("LiquidityPoolDepositOp"),liquidityPoolWithdrawOp:e.lookup("LiquidityPoolWithdrawOp"),invokeHostFunctionOp:e.lookup("InvokeHostFunctionOp"),extendFootprintTtlOp:e.lookup("ExtendFootprintTtlOp"),restoreFootprintOp:e.lookup("RestoreFootprintOp")}}),e.struct("Operation",[["sourceAccount",e.option(e.lookup("MuxedAccount"))],["body",e.lookup("OperationBody")]]),e.struct("HashIdPreimageOperationId",[["sourceAccount",e.lookup("AccountId")],["seqNum",e.lookup("SequenceNumber")],["opNum",e.lookup("Uint32")]]),e.struct("HashIdPreimageRevokeId",[["sourceAccount",e.lookup("AccountId")],["seqNum",e.lookup("SequenceNumber")],["opNum",e.lookup("Uint32")],["liquidityPoolId",e.lookup("PoolId")],["asset",e.lookup("Asset")]]),e.struct("HashIdPreimageContractId",[["networkId",e.lookup("Hash")],["contractIdPreimage",e.lookup("ContractIdPreimage")]]),e.struct("HashIdPreimageSorobanAuthorization",[["networkId",e.lookup("Hash")],["nonce",e.lookup("Int64")],["signatureExpirationLedger",e.lookup("Uint32")],["invocation",e.lookup("SorobanAuthorizedInvocation")]]),e.union("HashIdPreimage",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeOpId","operationId"],["envelopeTypePoolRevokeOpId","revokeId"],["envelopeTypeContractId","contractId"],["envelopeTypeSorobanAuthorization","sorobanAuthorization"]],arms:{operationId:e.lookup("HashIdPreimageOperationId"),revokeId:e.lookup("HashIdPreimageRevokeId"),contractId:e.lookup("HashIdPreimageContractId"),sorobanAuthorization:e.lookup("HashIdPreimageSorobanAuthorization")}}),e.enum("MemoType",{memoNone:0,memoText:1,memoId:2,memoHash:3,memoReturn:4}),e.union("Memo",{switchOn:e.lookup("MemoType"),switchName:"type",switches:[["memoNone",e.void()],["memoText","text"],["memoId","id"],["memoHash","hash"],["memoReturn","retHash"]],arms:{text:e.string(28),id:e.lookup("Uint64"),hash:e.lookup("Hash"),retHash:e.lookup("Hash")}}),e.struct("TimeBounds",[["minTime",e.lookup("TimePoint")],["maxTime",e.lookup("TimePoint")]]),e.struct("LedgerBounds",[["minLedger",e.lookup("Uint32")],["maxLedger",e.lookup("Uint32")]]),e.struct("PreconditionsV2",[["timeBounds",e.option(e.lookup("TimeBounds"))],["ledgerBounds",e.option(e.lookup("LedgerBounds"))],["minSeqNum",e.option(e.lookup("SequenceNumber"))],["minSeqAge",e.lookup("Duration")],["minSeqLedgerGap",e.lookup("Uint32")],["extraSigners",e.varArray(e.lookup("SignerKey"),2)]]),e.enum("PreconditionType",{precondNone:0,precondTime:1,precondV2:2}),e.union("Preconditions",{switchOn:e.lookup("PreconditionType"),switchName:"type",switches:[["precondNone",e.void()],["precondTime","timeBounds"],["precondV2","v2"]],arms:{timeBounds:e.lookup("TimeBounds"),v2:e.lookup("PreconditionsV2")}}),e.struct("LedgerFootprint",[["readOnly",e.varArray(e.lookup("LedgerKey"),2147483647)],["readWrite",e.varArray(e.lookup("LedgerKey"),2147483647)]]),e.enum("ArchivalProofType",{existence:0,nonexistence:1}),e.struct("ArchivalProofNode",[["index",e.lookup("Uint32")],["hash",e.lookup("Hash")]]),e.typedef("ProofLevel",e.varArray(e.lookup("ArchivalProofNode"),2147483647)),e.struct("NonexistenceProofBody",[["entriesToProve",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["proofLevels",e.varArray(e.lookup("ProofLevel"),2147483647)]]),e.struct("ExistenceProofBody",[["keysToProve",e.varArray(e.lookup("LedgerKey"),2147483647)],["lowBoundEntries",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["highBoundEntries",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["proofLevels",e.varArray(e.lookup("ProofLevel"),2147483647)]]),e.union("ArchivalProofBody",{switchOn:e.lookup("ArchivalProofType"),switchName:"t",switches:[["existence","nonexistenceProof"],["nonexistence","existenceProof"]],arms:{nonexistenceProof:e.lookup("NonexistenceProofBody"),existenceProof:e.lookup("ExistenceProofBody")}}),e.struct("ArchivalProof",[["epoch",e.lookup("Uint32")],["body",e.lookup("ArchivalProofBody")]]),e.struct("SorobanResources",[["footprint",e.lookup("LedgerFootprint")],["instructions",e.lookup("Uint32")],["readBytes",e.lookup("Uint32")],["writeBytes",e.lookup("Uint32")]]),e.struct("SorobanTransactionData",[["ext",e.lookup("ExtensionPoint")],["resources",e.lookup("SorobanResources")],["resourceFee",e.lookup("Int64")]]),e.union("TransactionV0Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionV0",[["sourceAccountEd25519",e.lookup("Uint256")],["fee",e.lookup("Uint32")],["seqNum",e.lookup("SequenceNumber")],["timeBounds",e.option(e.lookup("TimeBounds"))],["memo",e.lookup("Memo")],["operations",e.varArray(e.lookup("Operation"),e.lookup("MAX_OPS_PER_TX"))],["ext",e.lookup("TransactionV0Ext")]]),e.struct("TransactionV0Envelope",[["tx",e.lookup("TransactionV0")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("TransactionExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"sorobanData"]],arms:{sorobanData:e.lookup("SorobanTransactionData")}}),e.struct("Transaction",[["sourceAccount",e.lookup("MuxedAccount")],["fee",e.lookup("Uint32")],["seqNum",e.lookup("SequenceNumber")],["cond",e.lookup("Preconditions")],["memo",e.lookup("Memo")],["operations",e.varArray(e.lookup("Operation"),e.lookup("MAX_OPS_PER_TX"))],["ext",e.lookup("TransactionExt")]]),e.struct("TransactionV1Envelope",[["tx",e.lookup("Transaction")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("FeeBumpTransactionInnerTx",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTx","v1"]],arms:{v1:e.lookup("TransactionV1Envelope")}}),e.union("FeeBumpTransactionExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("FeeBumpTransaction",[["feeSource",e.lookup("MuxedAccount")],["fee",e.lookup("Int64")],["innerTx",e.lookup("FeeBumpTransactionInnerTx")],["ext",e.lookup("FeeBumpTransactionExt")]]),e.struct("FeeBumpTransactionEnvelope",[["tx",e.lookup("FeeBumpTransaction")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("TransactionEnvelope",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTxV0","v0"],["envelopeTypeTx","v1"],["envelopeTypeTxFeeBump","feeBump"]],arms:{v0:e.lookup("TransactionV0Envelope"),v1:e.lookup("TransactionV1Envelope"),feeBump:e.lookup("FeeBumpTransactionEnvelope")}}),e.union("TransactionSignaturePayloadTaggedTransaction",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTx","tx"],["envelopeTypeTxFeeBump","feeBump"]],arms:{tx:e.lookup("Transaction"),feeBump:e.lookup("FeeBumpTransaction")}}),e.struct("TransactionSignaturePayload",[["networkId",e.lookup("Hash")],["taggedTransaction",e.lookup("TransactionSignaturePayloadTaggedTransaction")]]),e.enum("ClaimAtomType",{claimAtomTypeV0:0,claimAtomTypeOrderBook:1,claimAtomTypeLiquidityPool:2}),e.struct("ClaimOfferAtomV0",[["sellerEd25519",e.lookup("Uint256")],["offerId",e.lookup("Int64")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.struct("ClaimOfferAtom",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.struct("ClaimLiquidityAtom",[["liquidityPoolId",e.lookup("PoolId")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.union("ClaimAtom",{switchOn:e.lookup("ClaimAtomType"),switchName:"type",switches:[["claimAtomTypeV0","v0"],["claimAtomTypeOrderBook","orderBook"],["claimAtomTypeLiquidityPool","liquidityPool"]],arms:{v0:e.lookup("ClaimOfferAtomV0"),orderBook:e.lookup("ClaimOfferAtom"),liquidityPool:e.lookup("ClaimLiquidityAtom")}}),e.enum("CreateAccountResultCode",{createAccountSuccess:0,createAccountMalformed:-1,createAccountUnderfunded:-2,createAccountLowReserve:-3,createAccountAlreadyExist:-4}),e.union("CreateAccountResult",{switchOn:e.lookup("CreateAccountResultCode"),switchName:"code",switches:[["createAccountSuccess",e.void()],["createAccountMalformed",e.void()],["createAccountUnderfunded",e.void()],["createAccountLowReserve",e.void()],["createAccountAlreadyExist",e.void()]],arms:{}}),e.enum("PaymentResultCode",{paymentSuccess:0,paymentMalformed:-1,paymentUnderfunded:-2,paymentSrcNoTrust:-3,paymentSrcNotAuthorized:-4,paymentNoDestination:-5,paymentNoTrust:-6,paymentNotAuthorized:-7,paymentLineFull:-8,paymentNoIssuer:-9}),e.union("PaymentResult",{switchOn:e.lookup("PaymentResultCode"),switchName:"code",switches:[["paymentSuccess",e.void()],["paymentMalformed",e.void()],["paymentUnderfunded",e.void()],["paymentSrcNoTrust",e.void()],["paymentSrcNotAuthorized",e.void()],["paymentNoDestination",e.void()],["paymentNoTrust",e.void()],["paymentNotAuthorized",e.void()],["paymentLineFull",e.void()],["paymentNoIssuer",e.void()]],arms:{}}),e.enum("PathPaymentStrictReceiveResultCode",{pathPaymentStrictReceiveSuccess:0,pathPaymentStrictReceiveMalformed:-1,pathPaymentStrictReceiveUnderfunded:-2,pathPaymentStrictReceiveSrcNoTrust:-3,pathPaymentStrictReceiveSrcNotAuthorized:-4,pathPaymentStrictReceiveNoDestination:-5,pathPaymentStrictReceiveNoTrust:-6,pathPaymentStrictReceiveNotAuthorized:-7,pathPaymentStrictReceiveLineFull:-8,pathPaymentStrictReceiveNoIssuer:-9,pathPaymentStrictReceiveTooFewOffers:-10,pathPaymentStrictReceiveOfferCrossSelf:-11,pathPaymentStrictReceiveOverSendmax:-12}),e.struct("SimplePaymentResult",[["destination",e.lookup("AccountId")],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")]]),e.struct("PathPaymentStrictReceiveResultSuccess",[["offers",e.varArray(e.lookup("ClaimAtom"),2147483647)],["last",e.lookup("SimplePaymentResult")]]),e.union("PathPaymentStrictReceiveResult",{switchOn:e.lookup("PathPaymentStrictReceiveResultCode"),switchName:"code",switches:[["pathPaymentStrictReceiveSuccess","success"],["pathPaymentStrictReceiveMalformed",e.void()],["pathPaymentStrictReceiveUnderfunded",e.void()],["pathPaymentStrictReceiveSrcNoTrust",e.void()],["pathPaymentStrictReceiveSrcNotAuthorized",e.void()],["pathPaymentStrictReceiveNoDestination",e.void()],["pathPaymentStrictReceiveNoTrust",e.void()],["pathPaymentStrictReceiveNotAuthorized",e.void()],["pathPaymentStrictReceiveLineFull",e.void()],["pathPaymentStrictReceiveNoIssuer","noIssuer"],["pathPaymentStrictReceiveTooFewOffers",e.void()],["pathPaymentStrictReceiveOfferCrossSelf",e.void()],["pathPaymentStrictReceiveOverSendmax",e.void()]],arms:{success:e.lookup("PathPaymentStrictReceiveResultSuccess"),noIssuer:e.lookup("Asset")}}),e.enum("PathPaymentStrictSendResultCode",{pathPaymentStrictSendSuccess:0,pathPaymentStrictSendMalformed:-1,pathPaymentStrictSendUnderfunded:-2,pathPaymentStrictSendSrcNoTrust:-3,pathPaymentStrictSendSrcNotAuthorized:-4,pathPaymentStrictSendNoDestination:-5,pathPaymentStrictSendNoTrust:-6,pathPaymentStrictSendNotAuthorized:-7,pathPaymentStrictSendLineFull:-8,pathPaymentStrictSendNoIssuer:-9,pathPaymentStrictSendTooFewOffers:-10,pathPaymentStrictSendOfferCrossSelf:-11,pathPaymentStrictSendUnderDestmin:-12}),e.struct("PathPaymentStrictSendResultSuccess",[["offers",e.varArray(e.lookup("ClaimAtom"),2147483647)],["last",e.lookup("SimplePaymentResult")]]),e.union("PathPaymentStrictSendResult",{switchOn:e.lookup("PathPaymentStrictSendResultCode"),switchName:"code",switches:[["pathPaymentStrictSendSuccess","success"],["pathPaymentStrictSendMalformed",e.void()],["pathPaymentStrictSendUnderfunded",e.void()],["pathPaymentStrictSendSrcNoTrust",e.void()],["pathPaymentStrictSendSrcNotAuthorized",e.void()],["pathPaymentStrictSendNoDestination",e.void()],["pathPaymentStrictSendNoTrust",e.void()],["pathPaymentStrictSendNotAuthorized",e.void()],["pathPaymentStrictSendLineFull",e.void()],["pathPaymentStrictSendNoIssuer","noIssuer"],["pathPaymentStrictSendTooFewOffers",e.void()],["pathPaymentStrictSendOfferCrossSelf",e.void()],["pathPaymentStrictSendUnderDestmin",e.void()]],arms:{success:e.lookup("PathPaymentStrictSendResultSuccess"),noIssuer:e.lookup("Asset")}}),e.enum("ManageSellOfferResultCode",{manageSellOfferSuccess:0,manageSellOfferMalformed:-1,manageSellOfferSellNoTrust:-2,manageSellOfferBuyNoTrust:-3,manageSellOfferSellNotAuthorized:-4,manageSellOfferBuyNotAuthorized:-5,manageSellOfferLineFull:-6,manageSellOfferUnderfunded:-7,manageSellOfferCrossSelf:-8,manageSellOfferSellNoIssuer:-9,manageSellOfferBuyNoIssuer:-10,manageSellOfferNotFound:-11,manageSellOfferLowReserve:-12}),e.enum("ManageOfferEffect",{manageOfferCreated:0,manageOfferUpdated:1,manageOfferDeleted:2}),e.union("ManageOfferSuccessResultOffer",{switchOn:e.lookup("ManageOfferEffect"),switchName:"effect",switches:[["manageOfferCreated","offer"],["manageOfferUpdated","offer"],["manageOfferDeleted",e.void()]],arms:{offer:e.lookup("OfferEntry")}}),e.struct("ManageOfferSuccessResult",[["offersClaimed",e.varArray(e.lookup("ClaimAtom"),2147483647)],["offer",e.lookup("ManageOfferSuccessResultOffer")]]),e.union("ManageSellOfferResult",{switchOn:e.lookup("ManageSellOfferResultCode"),switchName:"code",switches:[["manageSellOfferSuccess","success"],["manageSellOfferMalformed",e.void()],["manageSellOfferSellNoTrust",e.void()],["manageSellOfferBuyNoTrust",e.void()],["manageSellOfferSellNotAuthorized",e.void()],["manageSellOfferBuyNotAuthorized",e.void()],["manageSellOfferLineFull",e.void()],["manageSellOfferUnderfunded",e.void()],["manageSellOfferCrossSelf",e.void()],["manageSellOfferSellNoIssuer",e.void()],["manageSellOfferBuyNoIssuer",e.void()],["manageSellOfferNotFound",e.void()],["manageSellOfferLowReserve",e.void()]],arms:{success:e.lookup("ManageOfferSuccessResult")}}),e.enum("ManageBuyOfferResultCode",{manageBuyOfferSuccess:0,manageBuyOfferMalformed:-1,manageBuyOfferSellNoTrust:-2,manageBuyOfferBuyNoTrust:-3,manageBuyOfferSellNotAuthorized:-4,manageBuyOfferBuyNotAuthorized:-5,manageBuyOfferLineFull:-6,manageBuyOfferUnderfunded:-7,manageBuyOfferCrossSelf:-8,manageBuyOfferSellNoIssuer:-9,manageBuyOfferBuyNoIssuer:-10,manageBuyOfferNotFound:-11,manageBuyOfferLowReserve:-12}),e.union("ManageBuyOfferResult",{switchOn:e.lookup("ManageBuyOfferResultCode"),switchName:"code",switches:[["manageBuyOfferSuccess","success"],["manageBuyOfferMalformed",e.void()],["manageBuyOfferSellNoTrust",e.void()],["manageBuyOfferBuyNoTrust",e.void()],["manageBuyOfferSellNotAuthorized",e.void()],["manageBuyOfferBuyNotAuthorized",e.void()],["manageBuyOfferLineFull",e.void()],["manageBuyOfferUnderfunded",e.void()],["manageBuyOfferCrossSelf",e.void()],["manageBuyOfferSellNoIssuer",e.void()],["manageBuyOfferBuyNoIssuer",e.void()],["manageBuyOfferNotFound",e.void()],["manageBuyOfferLowReserve",e.void()]],arms:{success:e.lookup("ManageOfferSuccessResult")}}),e.enum("SetOptionsResultCode",{setOptionsSuccess:0,setOptionsLowReserve:-1,setOptionsTooManySigners:-2,setOptionsBadFlags:-3,setOptionsInvalidInflation:-4,setOptionsCantChange:-5,setOptionsUnknownFlag:-6,setOptionsThresholdOutOfRange:-7,setOptionsBadSigner:-8,setOptionsInvalidHomeDomain:-9,setOptionsAuthRevocableRequired:-10}),e.union("SetOptionsResult",{switchOn:e.lookup("SetOptionsResultCode"),switchName:"code",switches:[["setOptionsSuccess",e.void()],["setOptionsLowReserve",e.void()],["setOptionsTooManySigners",e.void()],["setOptionsBadFlags",e.void()],["setOptionsInvalidInflation",e.void()],["setOptionsCantChange",e.void()],["setOptionsUnknownFlag",e.void()],["setOptionsThresholdOutOfRange",e.void()],["setOptionsBadSigner",e.void()],["setOptionsInvalidHomeDomain",e.void()],["setOptionsAuthRevocableRequired",e.void()]],arms:{}}),e.enum("ChangeTrustResultCode",{changeTrustSuccess:0,changeTrustMalformed:-1,changeTrustNoIssuer:-2,changeTrustInvalidLimit:-3,changeTrustLowReserve:-4,changeTrustSelfNotAllowed:-5,changeTrustTrustLineMissing:-6,changeTrustCannotDelete:-7,changeTrustNotAuthMaintainLiabilities:-8}),e.union("ChangeTrustResult",{switchOn:e.lookup("ChangeTrustResultCode"),switchName:"code",switches:[["changeTrustSuccess",e.void()],["changeTrustMalformed",e.void()],["changeTrustNoIssuer",e.void()],["changeTrustInvalidLimit",e.void()],["changeTrustLowReserve",e.void()],["changeTrustSelfNotAllowed",e.void()],["changeTrustTrustLineMissing",e.void()],["changeTrustCannotDelete",e.void()],["changeTrustNotAuthMaintainLiabilities",e.void()]],arms:{}}),e.enum("AllowTrustResultCode",{allowTrustSuccess:0,allowTrustMalformed:-1,allowTrustNoTrustLine:-2,allowTrustTrustNotRequired:-3,allowTrustCantRevoke:-4,allowTrustSelfNotAllowed:-5,allowTrustLowReserve:-6}),e.union("AllowTrustResult",{switchOn:e.lookup("AllowTrustResultCode"),switchName:"code",switches:[["allowTrustSuccess",e.void()],["allowTrustMalformed",e.void()],["allowTrustNoTrustLine",e.void()],["allowTrustTrustNotRequired",e.void()],["allowTrustCantRevoke",e.void()],["allowTrustSelfNotAllowed",e.void()],["allowTrustLowReserve",e.void()]],arms:{}}),e.enum("AccountMergeResultCode",{accountMergeSuccess:0,accountMergeMalformed:-1,accountMergeNoAccount:-2,accountMergeImmutableSet:-3,accountMergeHasSubEntries:-4,accountMergeSeqnumTooFar:-5,accountMergeDestFull:-6,accountMergeIsSponsor:-7}),e.union("AccountMergeResult",{switchOn:e.lookup("AccountMergeResultCode"),switchName:"code",switches:[["accountMergeSuccess","sourceAccountBalance"],["accountMergeMalformed",e.void()],["accountMergeNoAccount",e.void()],["accountMergeImmutableSet",e.void()],["accountMergeHasSubEntries",e.void()],["accountMergeSeqnumTooFar",e.void()],["accountMergeDestFull",e.void()],["accountMergeIsSponsor",e.void()]],arms:{sourceAccountBalance:e.lookup("Int64")}}),e.enum("InflationResultCode",{inflationSuccess:0,inflationNotTime:-1}),e.struct("InflationPayout",[["destination",e.lookup("AccountId")],["amount",e.lookup("Int64")]]),e.union("InflationResult",{switchOn:e.lookup("InflationResultCode"),switchName:"code",switches:[["inflationSuccess","payouts"],["inflationNotTime",e.void()]],arms:{payouts:e.varArray(e.lookup("InflationPayout"),2147483647)}}),e.enum("ManageDataResultCode",{manageDataSuccess:0,manageDataNotSupportedYet:-1,manageDataNameNotFound:-2,manageDataLowReserve:-3,manageDataInvalidName:-4}),e.union("ManageDataResult",{switchOn:e.lookup("ManageDataResultCode"),switchName:"code",switches:[["manageDataSuccess",e.void()],["manageDataNotSupportedYet",e.void()],["manageDataNameNotFound",e.void()],["manageDataLowReserve",e.void()],["manageDataInvalidName",e.void()]],arms:{}}),e.enum("BumpSequenceResultCode",{bumpSequenceSuccess:0,bumpSequenceBadSeq:-1}),e.union("BumpSequenceResult",{switchOn:e.lookup("BumpSequenceResultCode"),switchName:"code",switches:[["bumpSequenceSuccess",e.void()],["bumpSequenceBadSeq",e.void()]],arms:{}}),e.enum("CreateClaimableBalanceResultCode",{createClaimableBalanceSuccess:0,createClaimableBalanceMalformed:-1,createClaimableBalanceLowReserve:-2,createClaimableBalanceNoTrust:-3,createClaimableBalanceNotAuthorized:-4,createClaimableBalanceUnderfunded:-5}),e.union("CreateClaimableBalanceResult",{switchOn:e.lookup("CreateClaimableBalanceResultCode"),switchName:"code",switches:[["createClaimableBalanceSuccess","balanceId"],["createClaimableBalanceMalformed",e.void()],["createClaimableBalanceLowReserve",e.void()],["createClaimableBalanceNoTrust",e.void()],["createClaimableBalanceNotAuthorized",e.void()],["createClaimableBalanceUnderfunded",e.void()]],arms:{balanceId:e.lookup("ClaimableBalanceId")}}),e.enum("ClaimClaimableBalanceResultCode",{claimClaimableBalanceSuccess:0,claimClaimableBalanceDoesNotExist:-1,claimClaimableBalanceCannotClaim:-2,claimClaimableBalanceLineFull:-3,claimClaimableBalanceNoTrust:-4,claimClaimableBalanceNotAuthorized:-5}),e.union("ClaimClaimableBalanceResult",{switchOn:e.lookup("ClaimClaimableBalanceResultCode"),switchName:"code",switches:[["claimClaimableBalanceSuccess",e.void()],["claimClaimableBalanceDoesNotExist",e.void()],["claimClaimableBalanceCannotClaim",e.void()],["claimClaimableBalanceLineFull",e.void()],["claimClaimableBalanceNoTrust",e.void()],["claimClaimableBalanceNotAuthorized",e.void()]],arms:{}}),e.enum("BeginSponsoringFutureReservesResultCode",{beginSponsoringFutureReservesSuccess:0,beginSponsoringFutureReservesMalformed:-1,beginSponsoringFutureReservesAlreadySponsored:-2,beginSponsoringFutureReservesRecursive:-3}),e.union("BeginSponsoringFutureReservesResult",{switchOn:e.lookup("BeginSponsoringFutureReservesResultCode"),switchName:"code",switches:[["beginSponsoringFutureReservesSuccess",e.void()],["beginSponsoringFutureReservesMalformed",e.void()],["beginSponsoringFutureReservesAlreadySponsored",e.void()],["beginSponsoringFutureReservesRecursive",e.void()]],arms:{}}),e.enum("EndSponsoringFutureReservesResultCode",{endSponsoringFutureReservesSuccess:0,endSponsoringFutureReservesNotSponsored:-1}),e.union("EndSponsoringFutureReservesResult",{switchOn:e.lookup("EndSponsoringFutureReservesResultCode"),switchName:"code",switches:[["endSponsoringFutureReservesSuccess",e.void()],["endSponsoringFutureReservesNotSponsored",e.void()]],arms:{}}),e.enum("RevokeSponsorshipResultCode",{revokeSponsorshipSuccess:0,revokeSponsorshipDoesNotExist:-1,revokeSponsorshipNotSponsor:-2,revokeSponsorshipLowReserve:-3,revokeSponsorshipOnlyTransferable:-4,revokeSponsorshipMalformed:-5}),e.union("RevokeSponsorshipResult",{switchOn:e.lookup("RevokeSponsorshipResultCode"),switchName:"code",switches:[["revokeSponsorshipSuccess",e.void()],["revokeSponsorshipDoesNotExist",e.void()],["revokeSponsorshipNotSponsor",e.void()],["revokeSponsorshipLowReserve",e.void()],["revokeSponsorshipOnlyTransferable",e.void()],["revokeSponsorshipMalformed",e.void()]],arms:{}}),e.enum("ClawbackResultCode",{clawbackSuccess:0,clawbackMalformed:-1,clawbackNotClawbackEnabled:-2,clawbackNoTrust:-3,clawbackUnderfunded:-4}),e.union("ClawbackResult",{switchOn:e.lookup("ClawbackResultCode"),switchName:"code",switches:[["clawbackSuccess",e.void()],["clawbackMalformed",e.void()],["clawbackNotClawbackEnabled",e.void()],["clawbackNoTrust",e.void()],["clawbackUnderfunded",e.void()]],arms:{}}),e.enum("ClawbackClaimableBalanceResultCode",{clawbackClaimableBalanceSuccess:0,clawbackClaimableBalanceDoesNotExist:-1,clawbackClaimableBalanceNotIssuer:-2,clawbackClaimableBalanceNotClawbackEnabled:-3}),e.union("ClawbackClaimableBalanceResult",{switchOn:e.lookup("ClawbackClaimableBalanceResultCode"),switchName:"code",switches:[["clawbackClaimableBalanceSuccess",e.void()],["clawbackClaimableBalanceDoesNotExist",e.void()],["clawbackClaimableBalanceNotIssuer",e.void()],["clawbackClaimableBalanceNotClawbackEnabled",e.void()]],arms:{}}),e.enum("SetTrustLineFlagsResultCode",{setTrustLineFlagsSuccess:0,setTrustLineFlagsMalformed:-1,setTrustLineFlagsNoTrustLine:-2,setTrustLineFlagsCantRevoke:-3,setTrustLineFlagsInvalidState:-4,setTrustLineFlagsLowReserve:-5}),e.union("SetTrustLineFlagsResult",{switchOn:e.lookup("SetTrustLineFlagsResultCode"),switchName:"code",switches:[["setTrustLineFlagsSuccess",e.void()],["setTrustLineFlagsMalformed",e.void()],["setTrustLineFlagsNoTrustLine",e.void()],["setTrustLineFlagsCantRevoke",e.void()],["setTrustLineFlagsInvalidState",e.void()],["setTrustLineFlagsLowReserve",e.void()]],arms:{}}),e.enum("LiquidityPoolDepositResultCode",{liquidityPoolDepositSuccess:0,liquidityPoolDepositMalformed:-1,liquidityPoolDepositNoTrust:-2,liquidityPoolDepositNotAuthorized:-3,liquidityPoolDepositUnderfunded:-4,liquidityPoolDepositLineFull:-5,liquidityPoolDepositBadPrice:-6,liquidityPoolDepositPoolFull:-7}),e.union("LiquidityPoolDepositResult",{switchOn:e.lookup("LiquidityPoolDepositResultCode"),switchName:"code",switches:[["liquidityPoolDepositSuccess",e.void()],["liquidityPoolDepositMalformed",e.void()],["liquidityPoolDepositNoTrust",e.void()],["liquidityPoolDepositNotAuthorized",e.void()],["liquidityPoolDepositUnderfunded",e.void()],["liquidityPoolDepositLineFull",e.void()],["liquidityPoolDepositBadPrice",e.void()],["liquidityPoolDepositPoolFull",e.void()]],arms:{}}),e.enum("LiquidityPoolWithdrawResultCode",{liquidityPoolWithdrawSuccess:0,liquidityPoolWithdrawMalformed:-1,liquidityPoolWithdrawNoTrust:-2,liquidityPoolWithdrawUnderfunded:-3,liquidityPoolWithdrawLineFull:-4,liquidityPoolWithdrawUnderMinimum:-5}),e.union("LiquidityPoolWithdrawResult",{switchOn:e.lookup("LiquidityPoolWithdrawResultCode"),switchName:"code",switches:[["liquidityPoolWithdrawSuccess",e.void()],["liquidityPoolWithdrawMalformed",e.void()],["liquidityPoolWithdrawNoTrust",e.void()],["liquidityPoolWithdrawUnderfunded",e.void()],["liquidityPoolWithdrawLineFull",e.void()],["liquidityPoolWithdrawUnderMinimum",e.void()]],arms:{}}),e.enum("InvokeHostFunctionResultCode",{invokeHostFunctionSuccess:0,invokeHostFunctionMalformed:-1,invokeHostFunctionTrapped:-2,invokeHostFunctionResourceLimitExceeded:-3,invokeHostFunctionEntryArchived:-4,invokeHostFunctionInsufficientRefundableFee:-5}),e.union("InvokeHostFunctionResult",{switchOn:e.lookup("InvokeHostFunctionResultCode"),switchName:"code",switches:[["invokeHostFunctionSuccess","success"],["invokeHostFunctionMalformed",e.void()],["invokeHostFunctionTrapped",e.void()],["invokeHostFunctionResourceLimitExceeded",e.void()],["invokeHostFunctionEntryArchived",e.void()],["invokeHostFunctionInsufficientRefundableFee",e.void()]],arms:{success:e.lookup("Hash")}}),e.enum("ExtendFootprintTtlResultCode",{extendFootprintTtlSuccess:0,extendFootprintTtlMalformed:-1,extendFootprintTtlResourceLimitExceeded:-2,extendFootprintTtlInsufficientRefundableFee:-3}),e.union("ExtendFootprintTtlResult",{switchOn:e.lookup("ExtendFootprintTtlResultCode"),switchName:"code",switches:[["extendFootprintTtlSuccess",e.void()],["extendFootprintTtlMalformed",e.void()],["extendFootprintTtlResourceLimitExceeded",e.void()],["extendFootprintTtlInsufficientRefundableFee",e.void()]],arms:{}}),e.enum("RestoreFootprintResultCode",{restoreFootprintSuccess:0,restoreFootprintMalformed:-1,restoreFootprintResourceLimitExceeded:-2,restoreFootprintInsufficientRefundableFee:-3}),e.union("RestoreFootprintResult",{switchOn:e.lookup("RestoreFootprintResultCode"),switchName:"code",switches:[["restoreFootprintSuccess",e.void()],["restoreFootprintMalformed",e.void()],["restoreFootprintResourceLimitExceeded",e.void()],["restoreFootprintInsufficientRefundableFee",e.void()]],arms:{}}),e.enum("OperationResultCode",{opInner:0,opBadAuth:-1,opNoAccount:-2,opNotSupported:-3,opTooManySubentries:-4,opExceededWorkLimit:-5,opTooManySponsoring:-6}),e.union("OperationResultTr",{switchOn:e.lookup("OperationType"),switchName:"type",switches:[["createAccount","createAccountResult"],["payment","paymentResult"],["pathPaymentStrictReceive","pathPaymentStrictReceiveResult"],["manageSellOffer","manageSellOfferResult"],["createPassiveSellOffer","createPassiveSellOfferResult"],["setOptions","setOptionsResult"],["changeTrust","changeTrustResult"],["allowTrust","allowTrustResult"],["accountMerge","accountMergeResult"],["inflation","inflationResult"],["manageData","manageDataResult"],["bumpSequence","bumpSeqResult"],["manageBuyOffer","manageBuyOfferResult"],["pathPaymentStrictSend","pathPaymentStrictSendResult"],["createClaimableBalance","createClaimableBalanceResult"],["claimClaimableBalance","claimClaimableBalanceResult"],["beginSponsoringFutureReserves","beginSponsoringFutureReservesResult"],["endSponsoringFutureReserves","endSponsoringFutureReservesResult"],["revokeSponsorship","revokeSponsorshipResult"],["clawback","clawbackResult"],["clawbackClaimableBalance","clawbackClaimableBalanceResult"],["setTrustLineFlags","setTrustLineFlagsResult"],["liquidityPoolDeposit","liquidityPoolDepositResult"],["liquidityPoolWithdraw","liquidityPoolWithdrawResult"],["invokeHostFunction","invokeHostFunctionResult"],["extendFootprintTtl","extendFootprintTtlResult"],["restoreFootprint","restoreFootprintResult"]],arms:{createAccountResult:e.lookup("CreateAccountResult"),paymentResult:e.lookup("PaymentResult"),pathPaymentStrictReceiveResult:e.lookup("PathPaymentStrictReceiveResult"),manageSellOfferResult:e.lookup("ManageSellOfferResult"),createPassiveSellOfferResult:e.lookup("ManageSellOfferResult"),setOptionsResult:e.lookup("SetOptionsResult"),changeTrustResult:e.lookup("ChangeTrustResult"),allowTrustResult:e.lookup("AllowTrustResult"),accountMergeResult:e.lookup("AccountMergeResult"),inflationResult:e.lookup("InflationResult"),manageDataResult:e.lookup("ManageDataResult"),bumpSeqResult:e.lookup("BumpSequenceResult"),manageBuyOfferResult:e.lookup("ManageBuyOfferResult"),pathPaymentStrictSendResult:e.lookup("PathPaymentStrictSendResult"),createClaimableBalanceResult:e.lookup("CreateClaimableBalanceResult"),claimClaimableBalanceResult:e.lookup("ClaimClaimableBalanceResult"),beginSponsoringFutureReservesResult:e.lookup("BeginSponsoringFutureReservesResult"),endSponsoringFutureReservesResult:e.lookup("EndSponsoringFutureReservesResult"),revokeSponsorshipResult:e.lookup("RevokeSponsorshipResult"),clawbackResult:e.lookup("ClawbackResult"),clawbackClaimableBalanceResult:e.lookup("ClawbackClaimableBalanceResult"),setTrustLineFlagsResult:e.lookup("SetTrustLineFlagsResult"),liquidityPoolDepositResult:e.lookup("LiquidityPoolDepositResult"),liquidityPoolWithdrawResult:e.lookup("LiquidityPoolWithdrawResult"),invokeHostFunctionResult:e.lookup("InvokeHostFunctionResult"),extendFootprintTtlResult:e.lookup("ExtendFootprintTtlResult"),restoreFootprintResult:e.lookup("RestoreFootprintResult")}}),e.union("OperationResult",{switchOn:e.lookup("OperationResultCode"),switchName:"code",switches:[["opInner","tr"],["opBadAuth",e.void()],["opNoAccount",e.void()],["opNotSupported",e.void()],["opTooManySubentries",e.void()],["opExceededWorkLimit",e.void()],["opTooManySponsoring",e.void()]],arms:{tr:e.lookup("OperationResultTr")}}),e.enum("TransactionResultCode",{txFeeBumpInnerSuccess:1,txSuccess:0,txFailed:-1,txTooEarly:-2,txTooLate:-3,txMissingOperation:-4,txBadSeq:-5,txBadAuth:-6,txInsufficientBalance:-7,txNoAccount:-8,txInsufficientFee:-9,txBadAuthExtra:-10,txInternalError:-11,txNotSupported:-12,txFeeBumpInnerFailed:-13,txBadSponsorship:-14,txBadMinSeqAgeOrGap:-15,txMalformed:-16,txSorobanInvalid:-17}),e.union("InnerTransactionResultResult",{switchOn:e.lookup("TransactionResultCode"),switchName:"code",switches:[["txSuccess","results"],["txFailed","results"],["txTooEarly",e.void()],["txTooLate",e.void()],["txMissingOperation",e.void()],["txBadSeq",e.void()],["txBadAuth",e.void()],["txInsufficientBalance",e.void()],["txNoAccount",e.void()],["txInsufficientFee",e.void()],["txBadAuthExtra",e.void()],["txInternalError",e.void()],["txNotSupported",e.void()],["txBadSponsorship",e.void()],["txBadMinSeqAgeOrGap",e.void()],["txMalformed",e.void()],["txSorobanInvalid",e.void()]],arms:{results:e.varArray(e.lookup("OperationResult"),2147483647)}}),e.union("InnerTransactionResultExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("InnerTransactionResult",[["feeCharged",e.lookup("Int64")],["result",e.lookup("InnerTransactionResultResult")],["ext",e.lookup("InnerTransactionResultExt")]]),e.struct("InnerTransactionResultPair",[["transactionHash",e.lookup("Hash")],["result",e.lookup("InnerTransactionResult")]]),e.union("TransactionResultResult",{switchOn:e.lookup("TransactionResultCode"),switchName:"code",switches:[["txFeeBumpInnerSuccess","innerResultPair"],["txFeeBumpInnerFailed","innerResultPair"],["txSuccess","results"],["txFailed","results"],["txTooEarly",e.void()],["txTooLate",e.void()],["txMissingOperation",e.void()],["txBadSeq",e.void()],["txBadAuth",e.void()],["txInsufficientBalance",e.void()],["txNoAccount",e.void()],["txInsufficientFee",e.void()],["txBadAuthExtra",e.void()],["txInternalError",e.void()],["txNotSupported",e.void()],["txBadSponsorship",e.void()],["txBadMinSeqAgeOrGap",e.void()],["txMalformed",e.void()],["txSorobanInvalid",e.void()]],arms:{innerResultPair:e.lookup("InnerTransactionResultPair"),results:e.varArray(e.lookup("OperationResult"),2147483647)}}),e.union("TransactionResultExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionResult",[["feeCharged",e.lookup("Int64")],["result",e.lookup("TransactionResultResult")],["ext",e.lookup("TransactionResultExt")]]),e.typedef("Hash",e.opaque(32)),e.typedef("Uint256",e.opaque(32)),e.typedef("Uint32",e.uint()),e.typedef("Int32",e.int()),e.typedef("Uint64",e.uhyper()),e.typedef("Int64",e.hyper()),e.typedef("TimePoint",e.lookup("Uint64")),e.typedef("Duration",e.lookup("Uint64")),e.union("ExtensionPoint",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.enum("CryptoKeyType",{keyTypeEd25519:0,keyTypePreAuthTx:1,keyTypeHashX:2,keyTypeEd25519SignedPayload:3,keyTypeMuxedEd25519:256}),e.enum("PublicKeyType",{publicKeyTypeEd25519:0}),e.enum("SignerKeyType",{signerKeyTypeEd25519:0,signerKeyTypePreAuthTx:1,signerKeyTypeHashX:2,signerKeyTypeEd25519SignedPayload:3}),e.union("PublicKey",{switchOn:e.lookup("PublicKeyType"),switchName:"type",switches:[["publicKeyTypeEd25519","ed25519"]],arms:{ed25519:e.lookup("Uint256")}}),e.struct("SignerKeyEd25519SignedPayload",[["ed25519",e.lookup("Uint256")],["payload",e.varOpaque(64)]]),e.union("SignerKey",{switchOn:e.lookup("SignerKeyType"),switchName:"type",switches:[["signerKeyTypeEd25519","ed25519"],["signerKeyTypePreAuthTx","preAuthTx"],["signerKeyTypeHashX","hashX"],["signerKeyTypeEd25519SignedPayload","ed25519SignedPayload"]],arms:{ed25519:e.lookup("Uint256"),preAuthTx:e.lookup("Uint256"),hashX:e.lookup("Uint256"),ed25519SignedPayload:e.lookup("SignerKeyEd25519SignedPayload")}}),e.typedef("Signature",e.varOpaque(64)),e.typedef("SignatureHint",e.opaque(4)),e.typedef("NodeId",e.lookup("PublicKey")),e.typedef("AccountId",e.lookup("PublicKey")),e.struct("Curve25519Secret",[["key",e.opaque(32)]]),e.struct("Curve25519Public",[["key",e.opaque(32)]]),e.struct("HmacSha256Key",[["key",e.opaque(32)]]),e.struct("HmacSha256Mac",[["mac",e.opaque(32)]]),e.struct("ShortHashSeed",[["seed",e.opaque(16)]]),e.enum("BinaryFuseFilterType",{binaryFuseFilter8Bit:0,binaryFuseFilter16Bit:1,binaryFuseFilter32Bit:2}),e.struct("SerializedBinaryFuseFilter",[["type",e.lookup("BinaryFuseFilterType")],["inputHashSeed",e.lookup("ShortHashSeed")],["filterSeed",e.lookup("ShortHashSeed")],["segmentLength",e.lookup("Uint32")],["segementLengthMask",e.lookup("Uint32")],["segmentCount",e.lookup("Uint32")],["segmentCountLength",e.lookup("Uint32")],["fingerprintLength",e.lookup("Uint32")],["fingerprints",e.varOpaque()]]),e.enum("ScValType",{scvBool:0,scvVoid:1,scvError:2,scvU32:3,scvI32:4,scvU64:5,scvI64:6,scvTimepoint:7,scvDuration:8,scvU128:9,scvI128:10,scvU256:11,scvI256:12,scvBytes:13,scvString:14,scvSymbol:15,scvVec:16,scvMap:17,scvAddress:18,scvContractInstance:19,scvLedgerKeyContractInstance:20,scvLedgerKeyNonce:21}),e.enum("ScErrorType",{sceContract:0,sceWasmVm:1,sceContext:2,sceStorage:3,sceObject:4,sceCrypto:5,sceEvents:6,sceBudget:7,sceValue:8,sceAuth:9}),e.enum("ScErrorCode",{scecArithDomain:0,scecIndexBounds:1,scecInvalidInput:2,scecMissingValue:3,scecExistingValue:4,scecExceededLimit:5,scecInvalidAction:6,scecInternalError:7,scecUnexpectedType:8,scecUnexpectedSize:9}),e.union("ScError",{switchOn:e.lookup("ScErrorType"),switchName:"type",switches:[["sceContract","contractCode"],["sceWasmVm","code"],["sceContext","code"],["sceStorage","code"],["sceObject","code"],["sceCrypto","code"],["sceEvents","code"],["sceBudget","code"],["sceValue","code"],["sceAuth","code"]],arms:{contractCode:e.lookup("Uint32"),code:e.lookup("ScErrorCode")}}),e.struct("UInt128Parts",[["hi",e.lookup("Uint64")],["lo",e.lookup("Uint64")]]),e.struct("Int128Parts",[["hi",e.lookup("Int64")],["lo",e.lookup("Uint64")]]),e.struct("UInt256Parts",[["hiHi",e.lookup("Uint64")],["hiLo",e.lookup("Uint64")],["loHi",e.lookup("Uint64")],["loLo",e.lookup("Uint64")]]),e.struct("Int256Parts",[["hiHi",e.lookup("Int64")],["hiLo",e.lookup("Uint64")],["loHi",e.lookup("Uint64")],["loLo",e.lookup("Uint64")]]),e.enum("ContractExecutableType",{contractExecutableWasm:0,contractExecutableStellarAsset:1}),e.union("ContractExecutable",{switchOn:e.lookup("ContractExecutableType"),switchName:"type",switches:[["contractExecutableWasm","wasmHash"],["contractExecutableStellarAsset",e.void()]],arms:{wasmHash:e.lookup("Hash")}}),e.enum("ScAddressType",{scAddressTypeAccount:0,scAddressTypeContract:1}),e.union("ScAddress",{switchOn:e.lookup("ScAddressType"),switchName:"type",switches:[["scAddressTypeAccount","accountId"],["scAddressTypeContract","contractId"]],arms:{accountId:e.lookup("AccountId"),contractId:e.lookup("Hash")}}),e.const("SCSYMBOL_LIMIT",32),e.typedef("ScVec",e.varArray(e.lookup("ScVal"),2147483647)),e.typedef("ScMap",e.varArray(e.lookup("ScMapEntry"),2147483647)),e.typedef("ScBytes",e.varOpaque()),e.typedef("ScString",e.string()),e.typedef("ScSymbol",e.string(32)),e.struct("ScNonceKey",[["nonce",e.lookup("Int64")]]),e.struct("ScContractInstance",[["executable",e.lookup("ContractExecutable")],["storage",e.option(e.lookup("ScMap"))]]),e.union("ScVal",{switchOn:e.lookup("ScValType"),switchName:"type",switches:[["scvBool","b"],["scvVoid",e.void()],["scvError","error"],["scvU32","u32"],["scvI32","i32"],["scvU64","u64"],["scvI64","i64"],["scvTimepoint","timepoint"],["scvDuration","duration"],["scvU128","u128"],["scvI128","i128"],["scvU256","u256"],["scvI256","i256"],["scvBytes","bytes"],["scvString","str"],["scvSymbol","sym"],["scvVec","vec"],["scvMap","map"],["scvAddress","address"],["scvLedgerKeyContractInstance",e.void()],["scvLedgerKeyNonce","nonceKey"],["scvContractInstance","instance"]],arms:{b:e.bool(),error:e.lookup("ScError"),u32:e.lookup("Uint32"),i32:e.lookup("Int32"),u64:e.lookup("Uint64"),i64:e.lookup("Int64"),timepoint:e.lookup("TimePoint"),duration:e.lookup("Duration"),u128:e.lookup("UInt128Parts"),i128:e.lookup("Int128Parts"),u256:e.lookup("UInt256Parts"),i256:e.lookup("Int256Parts"),bytes:e.lookup("ScBytes"),str:e.lookup("ScString"),sym:e.lookup("ScSymbol"),vec:e.option(e.lookup("ScVec")),map:e.option(e.lookup("ScMap")),address:e.lookup("ScAddress"),nonceKey:e.lookup("ScNonceKey"),instance:e.lookup("ScContractInstance")}}),e.struct("ScMapEntry",[["key",e.lookup("ScVal")],["val",e.lookup("ScVal")]]),e.enum("ScEnvMetaKind",{scEnvMetaKindInterfaceVersion:0}),e.struct("ScEnvMetaEntryInterfaceVersion",[["protocol",e.lookup("Uint32")],["preRelease",e.lookup("Uint32")]]),e.union("ScEnvMetaEntry",{switchOn:e.lookup("ScEnvMetaKind"),switchName:"kind",switches:[["scEnvMetaKindInterfaceVersion","interfaceVersion"]],arms:{interfaceVersion:e.lookup("ScEnvMetaEntryInterfaceVersion")}}),e.struct("ScMetaV0",[["key",e.string()],["val",e.string()]]),e.enum("ScMetaKind",{scMetaV0:0}),e.union("ScMetaEntry",{switchOn:e.lookup("ScMetaKind"),switchName:"kind",switches:[["scMetaV0","v0"]],arms:{v0:e.lookup("ScMetaV0")}}),e.const("SC_SPEC_DOC_LIMIT",1024),e.enum("ScSpecType",{scSpecTypeVal:0,scSpecTypeBool:1,scSpecTypeVoid:2,scSpecTypeError:3,scSpecTypeU32:4,scSpecTypeI32:5,scSpecTypeU64:6,scSpecTypeI64:7,scSpecTypeTimepoint:8,scSpecTypeDuration:9,scSpecTypeU128:10,scSpecTypeI128:11,scSpecTypeU256:12,scSpecTypeI256:13,scSpecTypeBytes:14,scSpecTypeString:16,scSpecTypeSymbol:17,scSpecTypeAddress:19,scSpecTypeOption:1e3,scSpecTypeResult:1001,scSpecTypeVec:1002,scSpecTypeMap:1004,scSpecTypeTuple:1005,scSpecTypeBytesN:1006,scSpecTypeUdt:2e3}),e.struct("ScSpecTypeOption",[["valueType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeResult",[["okType",e.lookup("ScSpecTypeDef")],["errorType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeVec",[["elementType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeMap",[["keyType",e.lookup("ScSpecTypeDef")],["valueType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeTuple",[["valueTypes",e.varArray(e.lookup("ScSpecTypeDef"),12)]]),e.struct("ScSpecTypeBytesN",[["n",e.lookup("Uint32")]]),e.struct("ScSpecTypeUdt",[["name",e.string(60)]]),e.union("ScSpecTypeDef",{switchOn:e.lookup("ScSpecType"),switchName:"type",switches:[["scSpecTypeVal",e.void()],["scSpecTypeBool",e.void()],["scSpecTypeVoid",e.void()],["scSpecTypeError",e.void()],["scSpecTypeU32",e.void()],["scSpecTypeI32",e.void()],["scSpecTypeU64",e.void()],["scSpecTypeI64",e.void()],["scSpecTypeTimepoint",e.void()],["scSpecTypeDuration",e.void()],["scSpecTypeU128",e.void()],["scSpecTypeI128",e.void()],["scSpecTypeU256",e.void()],["scSpecTypeI256",e.void()],["scSpecTypeBytes",e.void()],["scSpecTypeString",e.void()],["scSpecTypeSymbol",e.void()],["scSpecTypeAddress",e.void()],["scSpecTypeOption","option"],["scSpecTypeResult","result"],["scSpecTypeVec","vec"],["scSpecTypeMap","map"],["scSpecTypeTuple","tuple"],["scSpecTypeBytesN","bytesN"],["scSpecTypeUdt","udt"]],arms:{option:e.lookup("ScSpecTypeOption"),result:e.lookup("ScSpecTypeResult"),vec:e.lookup("ScSpecTypeVec"),map:e.lookup("ScSpecTypeMap"),tuple:e.lookup("ScSpecTypeTuple"),bytesN:e.lookup("ScSpecTypeBytesN"),udt:e.lookup("ScSpecTypeUdt")}}),e.struct("ScSpecUdtStructFieldV0",[["doc",e.string(t)],["name",e.string(30)],["type",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecUdtStructV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["fields",e.varArray(e.lookup("ScSpecUdtStructFieldV0"),40)]]),e.struct("ScSpecUdtUnionCaseVoidV0",[["doc",e.string(t)],["name",e.string(60)]]),e.struct("ScSpecUdtUnionCaseTupleV0",[["doc",e.string(t)],["name",e.string(60)],["type",e.varArray(e.lookup("ScSpecTypeDef"),12)]]),e.enum("ScSpecUdtUnionCaseV0Kind",{scSpecUdtUnionCaseVoidV0:0,scSpecUdtUnionCaseTupleV0:1}),e.union("ScSpecUdtUnionCaseV0",{switchOn:e.lookup("ScSpecUdtUnionCaseV0Kind"),switchName:"kind",switches:[["scSpecUdtUnionCaseVoidV0","voidCase"],["scSpecUdtUnionCaseTupleV0","tupleCase"]],arms:{voidCase:e.lookup("ScSpecUdtUnionCaseVoidV0"),tupleCase:e.lookup("ScSpecUdtUnionCaseTupleV0")}}),e.struct("ScSpecUdtUnionV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtUnionCaseV0"),50)]]),e.struct("ScSpecUdtEnumCaseV0",[["doc",e.string(t)],["name",e.string(60)],["value",e.lookup("Uint32")]]),e.struct("ScSpecUdtEnumV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtEnumCaseV0"),50)]]),e.struct("ScSpecUdtErrorEnumCaseV0",[["doc",e.string(t)],["name",e.string(60)],["value",e.lookup("Uint32")]]),e.struct("ScSpecUdtErrorEnumV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtErrorEnumCaseV0"),50)]]),e.struct("ScSpecFunctionInputV0",[["doc",e.string(t)],["name",e.string(30)],["type",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecFunctionV0",[["doc",e.string(t)],["name",e.lookup("ScSymbol")],["inputs",e.varArray(e.lookup("ScSpecFunctionInputV0"),10)],["outputs",e.varArray(e.lookup("ScSpecTypeDef"),1)]]),e.enum("ScSpecEntryKind",{scSpecEntryFunctionV0:0,scSpecEntryUdtStructV0:1,scSpecEntryUdtUnionV0:2,scSpecEntryUdtEnumV0:3,scSpecEntryUdtErrorEnumV0:4}),e.union("ScSpecEntry",{switchOn:e.lookup("ScSpecEntryKind"),switchName:"kind",switches:[["scSpecEntryFunctionV0","functionV0"],["scSpecEntryUdtStructV0","udtStructV0"],["scSpecEntryUdtUnionV0","udtUnionV0"],["scSpecEntryUdtEnumV0","udtEnumV0"],["scSpecEntryUdtErrorEnumV0","udtErrorEnumV0"]],arms:{functionV0:e.lookup("ScSpecFunctionV0"),udtStructV0:e.lookup("ScSpecUdtStructV0"),udtUnionV0:e.lookup("ScSpecUdtUnionV0"),udtEnumV0:e.lookup("ScSpecUdtEnumV0"),udtErrorEnumV0:e.lookup("ScSpecUdtErrorEnumV0")}}),e.struct("ConfigSettingContractExecutionLanesV0",[["ledgerMaxTxCount",e.lookup("Uint32")]]),e.struct("ConfigSettingContractComputeV0",[["ledgerMaxInstructions",e.lookup("Int64")],["txMaxInstructions",e.lookup("Int64")],["feeRatePerInstructionsIncrement",e.lookup("Int64")],["txMemoryLimit",e.lookup("Uint32")]]),e.struct("ConfigSettingContractLedgerCostV0",[["ledgerMaxReadLedgerEntries",e.lookup("Uint32")],["ledgerMaxReadBytes",e.lookup("Uint32")],["ledgerMaxWriteLedgerEntries",e.lookup("Uint32")],["ledgerMaxWriteBytes",e.lookup("Uint32")],["txMaxReadLedgerEntries",e.lookup("Uint32")],["txMaxReadBytes",e.lookup("Uint32")],["txMaxWriteLedgerEntries",e.lookup("Uint32")],["txMaxWriteBytes",e.lookup("Uint32")],["feeReadLedgerEntry",e.lookup("Int64")],["feeWriteLedgerEntry",e.lookup("Int64")],["feeRead1Kb",e.lookup("Int64")],["bucketListTargetSizeBytes",e.lookup("Int64")],["writeFee1KbBucketListLow",e.lookup("Int64")],["writeFee1KbBucketListHigh",e.lookup("Int64")],["bucketListWriteFeeGrowthFactor",e.lookup("Uint32")]]),e.struct("ConfigSettingContractHistoricalDataV0",[["feeHistorical1Kb",e.lookup("Int64")]]),e.struct("ConfigSettingContractEventsV0",[["txMaxContractEventsSizeBytes",e.lookup("Uint32")],["feeContractEvents1Kb",e.lookup("Int64")]]),e.struct("ConfigSettingContractBandwidthV0",[["ledgerMaxTxsSizeBytes",e.lookup("Uint32")],["txMaxSizeBytes",e.lookup("Uint32")],["feeTxSize1Kb",e.lookup("Int64")]]),e.enum("ContractCostType",{wasmInsnExec:0,memAlloc:1,memCpy:2,memCmp:3,dispatchHostFunction:4,visitObject:5,valSer:6,valDeser:7,computeSha256Hash:8,computeEd25519PubKey:9,verifyEd25519Sig:10,vmInstantiation:11,vmCachedInstantiation:12,invokeVmFunction:13,computeKeccak256Hash:14,decodeEcdsaCurve256Sig:15,recoverEcdsaSecp256k1Key:16,int256AddSub:17,int256Mul:18,int256Div:19,int256Pow:20,int256Shift:21,chaCha20DrawBytes:22,parseWasmInstructions:23,parseWasmFunctions:24,parseWasmGlobals:25,parseWasmTableEntries:26,parseWasmTypes:27,parseWasmDataSegments:28,parseWasmElemSegments:29,parseWasmImports:30,parseWasmExports:31,parseWasmDataSegmentBytes:32,instantiateWasmInstructions:33,instantiateWasmFunctions:34,instantiateWasmGlobals:35,instantiateWasmTableEntries:36,instantiateWasmTypes:37,instantiateWasmDataSegments:38,instantiateWasmElemSegments:39,instantiateWasmImports:40,instantiateWasmExports:41,instantiateWasmDataSegmentBytes:42,sec1DecodePointUncompressed:43,verifyEcdsaSecp256r1Sig:44,bls12381EncodeFp:45,bls12381DecodeFp:46,bls12381G1CheckPointOnCurve:47,bls12381G1CheckPointInSubgroup:48,bls12381G2CheckPointOnCurve:49,bls12381G2CheckPointInSubgroup:50,bls12381G1ProjectiveToAffine:51,bls12381G2ProjectiveToAffine:52,bls12381G1Add:53,bls12381G1Mul:54,bls12381G1Msm:55,bls12381MapFpToG1:56,bls12381HashToG1:57,bls12381G2Add:58,bls12381G2Mul:59,bls12381G2Msm:60,bls12381MapFp2ToG2:61,bls12381HashToG2:62,bls12381Pairing:63,bls12381FrFromU256:64,bls12381FrToU256:65,bls12381FrAddSub:66,bls12381FrMul:67,bls12381FrPow:68,bls12381FrInv:69}),e.struct("ContractCostParamEntry",[["ext",e.lookup("ExtensionPoint")],["constTerm",e.lookup("Int64")],["linearTerm",e.lookup("Int64")]]),e.struct("StateArchivalSettings",[["maxEntryTtl",e.lookup("Uint32")],["minTemporaryTtl",e.lookup("Uint32")],["minPersistentTtl",e.lookup("Uint32")],["persistentRentRateDenominator",e.lookup("Int64")],["tempRentRateDenominator",e.lookup("Int64")],["maxEntriesToArchive",e.lookup("Uint32")],["bucketListSizeWindowSampleSize",e.lookup("Uint32")],["bucketListWindowSamplePeriod",e.lookup("Uint32")],["evictionScanSize",e.lookup("Uint32")],["startingEvictionScanLevel",e.lookup("Uint32")]]),e.struct("EvictionIterator",[["bucketListLevel",e.lookup("Uint32")],["isCurrBucket",e.bool()],["bucketFileOffset",e.lookup("Uint64")]]),e.const("CONTRACT_COST_COUNT_LIMIT",1024),e.typedef("ContractCostParams",e.varArray(e.lookup("ContractCostParamEntry"),e.lookup("CONTRACT_COST_COUNT_LIMIT"))),e.enum("ConfigSettingId",{configSettingContractMaxSizeBytes:0,configSettingContractComputeV0:1,configSettingContractLedgerCostV0:2,configSettingContractHistoricalDataV0:3,configSettingContractEventsV0:4,configSettingContractBandwidthV0:5,configSettingContractCostParamsCpuInstructions:6,configSettingContractCostParamsMemoryBytes:7,configSettingContractDataKeySizeBytes:8,configSettingContractDataEntrySizeBytes:9,configSettingStateArchival:10,configSettingContractExecutionLanes:11,configSettingBucketlistSizeWindow:12,configSettingEvictionIterator:13}),e.union("ConfigSettingEntry",{switchOn:e.lookup("ConfigSettingId"),switchName:"configSettingId",switches:[["configSettingContractMaxSizeBytes","contractMaxSizeBytes"],["configSettingContractComputeV0","contractCompute"],["configSettingContractLedgerCostV0","contractLedgerCost"],["configSettingContractHistoricalDataV0","contractHistoricalData"],["configSettingContractEventsV0","contractEvents"],["configSettingContractBandwidthV0","contractBandwidth"],["configSettingContractCostParamsCpuInstructions","contractCostParamsCpuInsns"],["configSettingContractCostParamsMemoryBytes","contractCostParamsMemBytes"],["configSettingContractDataKeySizeBytes","contractDataKeySizeBytes"],["configSettingContractDataEntrySizeBytes","contractDataEntrySizeBytes"],["configSettingStateArchival","stateArchivalSettings"],["configSettingContractExecutionLanes","contractExecutionLanes"],["configSettingBucketlistSizeWindow","bucketListSizeWindow"],["configSettingEvictionIterator","evictionIterator"]],arms:{contractMaxSizeBytes:e.lookup("Uint32"),contractCompute:e.lookup("ConfigSettingContractComputeV0"),contractLedgerCost:e.lookup("ConfigSettingContractLedgerCostV0"),contractHistoricalData:e.lookup("ConfigSettingContractHistoricalDataV0"),contractEvents:e.lookup("ConfigSettingContractEventsV0"),contractBandwidth:e.lookup("ConfigSettingContractBandwidthV0"),contractCostParamsCpuInsns:e.lookup("ContractCostParams"),contractCostParamsMemBytes:e.lookup("ContractCostParams"),contractDataKeySizeBytes:e.lookup("Uint32"),contractDataEntrySizeBytes:e.lookup("Uint32"),stateArchivalSettings:e.lookup("StateArchivalSettings"),contractExecutionLanes:e.lookup("ConfigSettingContractExecutionLanesV0"),bucketListSizeWindow:e.varArray(e.lookup("Uint64"),2147483647),evictionIterator:e.lookup("EvictionIterator")}})}));const i=o;const a={XdrWriter:n.XdrWriter,XdrReader:n.XdrReader};var s=r(2802);function u(e){var t=new s.sha256;return t.update(e,"utf8"),t.digest()}var c=r(3626).A,l={},f="undefined"==typeof window?function(){var e;try{e=r(Object(function(){var e=new Error("Cannot find module 'sodium-native'");throw e.code="MODULE_NOT_FOUND",e}()))}catch(e){return d()}return Object.keys(e).length?(l.generate=function(t){var r=c.alloc(e.crypto_sign_PUBLICKEYBYTES),n=c.alloc(e.crypto_sign_SECRETKEYBYTES);return e.crypto_sign_seed_keypair(r,n,t),r},l.sign=function(t,r){t=c.from(t);var n=c.alloc(e.crypto_sign_BYTES);return e.crypto_sign_detached(n,t,r),n},l.verify=function(t,r,n){t=c.from(t);try{return e.crypto_sign_verify_detached(r,t,n)}catch(e){return!1}},!0):d()}():d();function p(e,t){return l.sign(e,t)}function h(e,t,r){return l.verify(e,t,r)}function d(){var e=r(8947);return l.generate=function(t){var r=new Uint8Array(t),n=e.sign.keyPair.fromSeed(r);return c.from(n.publicKey)},l.sign=function(t,r){t=c.from(t),t=new Uint8Array(t.toJSON().data),r=new Uint8Array(r.toJSON().data);var n=e.sign.detached(t,r);return c.from(n)},l.verify=function(t,r,n){return t=c.from(t),t=new Uint8Array(t.toJSON().data),r=new Uint8Array(r.toJSON().data),n=new Uint8Array(n.toJSON().data),e.sign.detached.verify(t,r,n)},!1}var y=function(e,t){for(var r="number"==typeof e,n=String(e);n.endsWith(t);)n=n.slice(0,-1);return r?Number(n):n},m=r(8947),g=r.n(m),v=r(5360);var b=r(3626).A;function w(e){return w="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},w(e)}function S(e,t){for(var r=0;r165)return!1;break;default:return!1}var r="";try{r=P(e,t)}catch(e){return!1}switch(e){case"ed25519PublicKey":case"ed25519SecretSeed":case"preAuthTx":case"sha256Hash":case"contract":return 32===r.length;case"med25519PublicKey":return 40===r.length;case"signedPayload":return r.length>=40&&r.length<=100;default:return!1}}function P(e,t){if("string"!=typeof t)throw new TypeError("encoded argument must be of type String");var r=v.decode(t),n=r[0],o=r.slice(0,-2),i=o.slice(1),a=r.slice(-2);if(t!==v.encode(r))throw new Error("invalid encoded string");var s=E[e];if(void 0===s)throw new Error("".concat(e," is not a valid version byte name. ")+"Expected one of ".concat(Object.keys(E).join(", ")));if(n!==s)throw new Error("invalid version byte. expected ".concat(s,", got ").concat(n));if(!function(e,t){if(e.length!==t.length)return!1;if(0===e.length)return!0;for(var r=0;r>8^e[n]],r&=65535}var o=new Uint8Array(2);return o[0]=255&r,o[1]=r>>8&255,o}var B=r(3626).A;function _(e){return _="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_(e)}function R(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:i.Asset;if(this.isNative())return r.assetTypeNative();this.code.length<=4?(e=i.AlphaNum4,t="assetTypeCreditAlphanum4"):(e=i.AlphaNum12,t="assetTypeCreditAlphanum12");var n=this.code.length<=4?4:12;return new r(t,new e({assetCode:this.code.padEnd(n,"\0"),issuer:U.fromPublicKey(this.issuer).xdrAccountId()}))}},{key:"getCode",value:function(){if(void 0!==this.code)return String(this.code)}},{key:"getIssuer",value:function(){if(void 0!==this.issuer)return String(this.issuer)}},{key:"getAssetType",value:function(){switch(this.getRawAssetType().value){case i.AssetType.assetTypeNative().value:return"native";case i.AssetType.assetTypeCreditAlphanum4().value:return"credit_alphanum4";case i.AssetType.assetTypeCreditAlphanum12().value:return"credit_alphanum12";default:return"unknown"}}},{key:"getRawAssetType",value:function(){return this.isNative()?i.AssetType.assetTypeNative():this.code.length<=4?i.AssetType.assetTypeCreditAlphanum4():i.AssetType.assetTypeCreditAlphanum12()}},{key:"isNative",value:function(){return!this.issuer}},{key:"equals",value:function(e){return this.code===e.getCode()&&this.issuer===e.getIssuer()}},{key:"toString",value:function(){return this.isNative()?"native":"".concat(this.getCode(),":").concat(this.getIssuer())}}],n=[{key:"native",value:function(){return new e("XLM")}},{key:"fromOperation",value:function(e){var t,r;switch(e.switch()){case i.AssetType.assetTypeNative():return this.native();case i.AssetType.assetTypeCreditAlphanum4():t=e.alphaNum4();case i.AssetType.assetTypeCreditAlphanum12():return t=t||e.alphaNum12(),r=T.encodeEd25519PublicKey(t.issuer().ed25519()),new this(y(t.assetCode(),"\0"),r);default:throw new Error("Invalid asset type: ".concat(e.switch().name))}}},{key:"compare",value:function(t,r){if(!(t&&t instanceof e))throw new Error("assetA is invalid");if(!(r&&r instanceof e))throw new Error("assetB is invalid");if(t.equals(r))return 0;var n=t.getRawAssetType().value,o=r.getRawAssetType().value;if(n!==o)return n1&&void 0!==arguments[1]?arguments[1]:{};if("constant_product"!==e)throw new Error("liquidityPoolType is invalid");var r=t.assetA,n=t.assetB,o=t.fee;if(!(r&&r instanceof F))throw new Error("assetA is invalid");if(!(n&&n instanceof F))throw new Error("assetB is invalid");if(!o||o!==q)throw new Error("fee is invalid");if(-1!==F.compare(r,n))throw new Error("Assets are not in lexicographic order");var a=i.LiquidityPoolType.liquidityPoolConstantProduct().toXDR(),s=new i.LiquidityPoolConstantProductParameters({assetA:r.toXDRObject(),assetB:n.toXDRObject(),fee:o}).toXDR();return u(V.concat([a,s]))}var H=r(3626).A;function z(e){return z="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},z(e)}function X(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(!n||"string"!=typeof n)throw new Error("Invalid signature");if(!r||"string"!=typeof r)throw new Error("Invalid publicKey");var o=H.from(n,"base64");try{t=(e=U.fromPublicKey(r)).signatureHint()}catch(e){throw new Error("Invalid publicKey")}if(!e.verify(this.hash(),o))throw new Error("Invalid signature");this.signatures.push(new i.DecoratedSignature({hint:t,signature:o}))}},{key:"addDecoratedSignature",value:function(e){this.signatures.push(e)}},{key:"signHashX",value:function(e){if("string"==typeof e&&(e=H.from(e,"hex")),e.length>64)throw new Error("preimage cannnot be longer than 64 bytes");var t=e,r=u(e),n=r.slice(r.length-4);this.signatures.push(new i.DecoratedSignature({hint:n,signature:t}))}},{key:"hash",value:function(){return u(this.signatureBase())}},{key:"signatureBase",value:function(){throw new Error("Implement in subclass")}},{key:"toEnvelope",value:function(){throw new Error("Implement in subclass")}},{key:"toXDR",value:function(){return this.toEnvelope().toXDR().toString("base64")}}],t&&X(e.prototype,t),r&&X(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,r}(),W=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Y=Math.ceil,J=Math.floor,Z="[BigNumber Error] ",Q=Z+"Number primitive has more than 15 significant digits: ",ee=1e14,te=14,re=9007199254740991,ne=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],oe=1e7,ie=1e9;function ae(e){var t=0|e;return e>0||e===t?t:t-1}function se(e){for(var t,r,n=1,o=e.length,i=e[0]+"";nc^r?1:-1;for(s=(u=o.length)<(c=i.length)?u:c,a=0;ai[a]^r?1:-1;return u==c?0:u>c^r?1:-1}function ce(e,t,r,n){if(er||e!==J(e))throw Error(Z+(n||"Argument")+("number"==typeof e?er?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function le(e){var t=e.c.length-1;return ae(e.e/te)==t&&e.c[t]%2!=0}function fe(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function pe(e,t,r){var n,o;if(t<0){for(o=r+".";++t;o+=r);e=o+e}else if(++t>(n=e.length)){for(o=r,t-=n;--t;o+=r);e+=o}else tb?p.c=p.e=null:e.e=10;u/=10,s++);return void(s>b?p.c=p.e=null:(p.e=s,p.c=[e]))}f=String(e)}else{if(!W.test(f=String(e)))return o(p,f,c);p.s=45==f.charCodeAt(0)?(f=f.slice(1),-1):1}(s=f.indexOf("."))>-1&&(f=f.replace(".","")),(u=f.search(/e/i))>0?(s<0&&(s=u),s+=+f.slice(u+1),f=f.substring(0,u)):s<0&&(s=f.length)}else{if(ce(t,2,A.length,"Base"),10==t&&T)return B(p=new O(e),d+p.e+1,y);if(f=String(e),c="number"==typeof e){if(0*e!=0)return o(p,f,c,t);if(p.s=1/e<0?(f=f.slice(1),-1):1,O.DEBUG&&f.replace(/^0\.0*|\./,"").length>15)throw Error(Q+e)}else p.s=45===f.charCodeAt(0)?(f=f.slice(1),-1):1;for(r=A.slice(0,t),s=u=0,l=f.length;us){s=l;continue}}else if(!a&&(f==f.toUpperCase()&&(f=f.toLowerCase())||f==f.toLowerCase()&&(f=f.toUpperCase()))){a=!0,u=-1,s=0;continue}return o(p,String(e),c,t)}c=!1,(s=(f=n(f,t,10,p.s)).indexOf("."))>-1?f=f.replace(".",""):s=f.length}for(u=0;48===f.charCodeAt(u);u++);for(l=f.length;48===f.charCodeAt(--l););if(f=f.slice(u,++l)){if(l-=u,c&&O.DEBUG&&l>15&&(e>re||e!==J(e)))throw Error(Q+p.s*e);if((s=s-u-1)>b)p.c=p.e=null;else if(s=g)?fe(u,a):pe(u,a,"0");else if(i=(e=B(new O(e),t,r)).e,s=(u=se(e.c)).length,1==n||2==n&&(t<=i||i<=m)){for(;ss){if(--t>0)for(u+=".";t--;u+="0");}else if((t+=i-s)>0)for(i+1==s&&(u+=".");t--;u+="0");return e.s<0&&o?"-"+u:u}function x(e,t){for(var r,n,o=1,i=new O(e[0]);o=10;o/=10,n++);return(r=n+r*te-1)>b?e.c=e.e=null:r=10;s/=10,o++);if((i=t-o)<0)i+=te,a=t,u=f[c=0],l=J(u/p[o-a-1]%10);else if((c=Y((i+1)/te))>=f.length){if(!n)break e;for(;f.length<=c;f.push(0));u=l=0,o=1,a=(i%=te)-te+1}else{for(u=s=f[c],o=1;s>=10;s/=10,o++);l=(a=(i%=te)-te+o)<0?0:J(u/p[o-a-1]%10)}if(n=n||t<0||null!=f[c+1]||(a<0?u:u%p[o-a-1]),n=r<4?(l||n)&&(0==r||r==(e.s<0?3:2)):l>5||5==l&&(4==r||n||6==r&&(i>0?a>0?u/p[o-a]:0:f[c-1])%10&1||r==(e.s<0?8:7)),t<1||!f[0])return f.length=0,n?(t-=e.e+1,f[0]=p[(te-t%te)%te],e.e=-t||0):f[0]=e.e=0,e;if(0==i?(f.length=c,s=1,c--):(f.length=c+1,s=p[te-i],f[c]=a>0?J(u/p[o-a]%p[a])*s:0),n)for(;;){if(0==c){for(i=1,a=f[0];a>=10;a/=10,i++);for(a=f[0]+=s,s=1;a>=10;a/=10,s++);i!=s&&(e.e++,f[0]==ee&&(f[0]=1));break}if(f[c]+=s,f[c]!=ee)break;f[c--]=0,s=1}for(i=f.length;0===f[--i];f.pop());}e.e>b?e.c=e.e=null:e.e=g?fe(t,r):pe(t,r,"0"),e.s<0?"-"+t:t)}return O.clone=e,O.ROUND_UP=0,O.ROUND_DOWN=1,O.ROUND_CEIL=2,O.ROUND_FLOOR=3,O.ROUND_HALF_UP=4,O.ROUND_HALF_DOWN=5,O.ROUND_HALF_EVEN=6,O.ROUND_HALF_CEIL=7,O.ROUND_HALF_FLOOR=8,O.EUCLID=9,O.config=O.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(Z+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(ce(r=e[t],0,ie,t),d=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(ce(r=e[t],0,8,t),y=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(ce(r[0],-ie,0,t),ce(r[1],0,ie,t),m=r[0],g=r[1]):(ce(r,-ie,ie,t),m=-(g=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)ce(r[0],-ie,-1,t),ce(r[1],1,ie,t),v=r[0],b=r[1];else{if(ce(r,-ie,ie,t),!r)throw Error(Z+t+" cannot be zero: "+r);v=-(b=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(Z+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw w=!r,Error(Z+"crypto unavailable");w=r}else w=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(ce(r=e[t],0,9,t),S=r),e.hasOwnProperty(t="POW_PRECISION")&&(ce(r=e[t],0,ie,t),k=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(Z+t+" not an object: "+r);E=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(Z+t+" invalid: "+r);T="0123456789"==r.slice(0,10),A=r}}return{DECIMAL_PLACES:d,ROUNDING_MODE:y,EXPONENTIAL_AT:[m,g],RANGE:[v,b],CRYPTO:w,MODULO_MODE:S,POW_PRECISION:k,FORMAT:E,ALPHABET:A}},O.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!O.DEBUG)return!0;var t,r,n=e.c,o=e.e,i=e.s;e:if("[object Array]"=={}.toString.call(n)){if((1===i||-1===i)&&o>=-ie&&o<=ie&&o===J(o)){if(0===n[0]){if(0===o&&1===n.length)return!0;break e}if((t=(o+1)%te)<1&&(t+=te),String(n[0]).length==t){for(t=0;t=ee||r!==J(r))break e;if(0!==r)return!0}}}else if(null===n&&null===o&&(null===i||1===i||-1===i))return!0;throw Error(Z+"Invalid BigNumber: "+e)},O.maximum=O.max=function(){return x(arguments,-1)},O.minimum=O.min=function(){return x(arguments,1)},O.random=(i=9007199254740992,a=Math.random()*i&2097151?function(){return J(Math.random()*i)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,n,o,i,s=0,u=[],c=new O(h);if(null==e?e=d:ce(e,0,ie),o=Y(e/te),w)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(o*=2));s>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[s]=r[0],t[s+1]=r[1]):(u.push(i%1e14),s+=2);s=o/2}else{if(!crypto.randomBytes)throw w=!1,Error(Z+"crypto unavailable");for(t=crypto.randomBytes(o*=7);s=9e15?crypto.randomBytes(7).copy(t,s):(u.push(i%1e14),s+=7);s=o/7}if(!w)for(;s=10;i/=10,s++);sr-1&&(null==a[o+1]&&(a[o+1]=0),a[o+1]+=a[o]/r|0,a[o]%=r)}return a.reverse()}return function(n,o,i,a,s){var u,c,l,f,p,h,m,g,v=n.indexOf("."),b=d,w=y;for(v>=0&&(f=k,k=0,n=n.replace(".",""),h=(g=new O(o)).pow(n.length-v),k=f,g.c=t(pe(se(h.c),h.e,"0"),10,i,e),g.e=g.c.length),l=f=(m=t(n,o,i,s?(u=A,e):(u=e,A))).length;0==m[--f];m.pop());if(!m[0])return u.charAt(0);if(v<0?--l:(h.c=m,h.e=l,h.s=a,m=(h=r(h,g,b,w,i)).c,p=h.r,l=h.e),v=m[c=l+b+1],f=i/2,p=p||c<0||null!=m[c+1],p=w<4?(null!=v||p)&&(0==w||w==(h.s<0?3:2)):v>f||v==f&&(4==w||p||6==w&&1&m[c-1]||w==(h.s<0?8:7)),c<1||!m[0])n=p?pe(u.charAt(1),-b,u.charAt(0)):u.charAt(0);else{if(m.length=c,p)for(--i;++m[--c]>i;)m[c]=0,c||(++l,m=[1].concat(m));for(f=m.length;!m[--f];);for(v=0,n="";v<=f;n+=u.charAt(m[v++]));n=pe(n,l,u.charAt(0))}return n}}(),r=function(){function e(e,t,r){var n,o,i,a,s=0,u=e.length,c=t%oe,l=t/oe|0;for(e=e.slice();u--;)s=((o=c*(i=e[u]%oe)+(n=l*i+(a=e[u]/oe|0)*c)%oe*oe+s)/r|0)+(n/oe|0)+l*a,e[u]=o%r;return s&&(e=[s].concat(e)),e}function t(e,t,r,n){var o,i;if(r!=n)i=r>n?1:-1;else for(o=i=0;ot[o]?1:-1;break}return i}function r(e,t,r,n){for(var o=0;r--;)e[r]-=o,o=e[r]1;e.splice(0,1));}return function(n,o,i,a,s){var u,c,l,f,p,h,d,y,m,g,v,b,w,S,k,E,A,T=n.s==o.s?1:-1,P=n.c,x=o.c;if(!(P&&P[0]&&x&&x[0]))return new O(n.s&&o.s&&(P?!x||P[0]!=x[0]:x)?P&&0==P[0]||!x?0*T:T/0:NaN);for(m=(y=new O(T)).c=[],T=i+(c=n.e-o.e)+1,s||(s=ee,c=ae(n.e/te)-ae(o.e/te),T=T/te|0),l=0;x[l]==(P[l]||0);l++);if(x[l]>(P[l]||0)&&c--,T<0)m.push(1),f=!0;else{for(S=P.length,E=x.length,l=0,T+=2,(p=J(s/(x[0]+1)))>1&&(x=e(x,p,s),P=e(P,p,s),E=x.length,S=P.length),w=E,v=(g=P.slice(0,E)).length;v=s/2&&k++;do{if(p=0,(u=t(x,g,E,v))<0){if(b=g[0],E!=v&&(b=b*s+(g[1]||0)),(p=J(b/k))>1)for(p>=s&&(p=s-1),d=(h=e(x,p,s)).length,v=g.length;1==t(h,g,d,v);)p--,r(h,E=10;T/=10,l++);B(y,i+(y.e=l+c*te-1)+1,a,f)}else y.e=c,y.r=+f;return y}}(),s=/^(-?)0([xbo])(?=\w[\w.]*$)/i,u=/^([^.]+)\.$/,c=/^\.([^.]+)$/,l=/^-?(Infinity|NaN)$/,f=/^\s*\+(?=[\w.])|^\s+|\s+$/g,o=function(e,t,r,n){var o,i=r?t:t.replace(f,"");if(l.test(i))e.s=isNaN(i)?null:i<0?-1:1;else{if(!r&&(i=i.replace(s,(function(e,t,r){return o="x"==(r=r.toLowerCase())?16:"b"==r?2:8,n&&n!=o?e:t})),n&&(o=n,i=i.replace(u,"$1").replace(c,"0.$1")),t!=i))return new O(i,o);if(O.DEBUG)throw Error(Z+"Not a"+(n?" base "+n:"")+" number: "+t);e.s=null}e.c=e.e=null},p.absoluteValue=p.abs=function(){var e=new O(this);return e.s<0&&(e.s=1),e},p.comparedTo=function(e,t){return ue(this,new O(e,t))},p.decimalPlaces=p.dp=function(e,t){var r,n,o,i=this;if(null!=e)return ce(e,0,ie),null==t?t=y:ce(t,0,8),B(new O(i),e+i.e+1,t);if(!(r=i.c))return null;if(n=((o=r.length-1)-ae(this.e/te))*te,o=r[o])for(;o%10==0;o/=10,n--);return n<0&&(n=0),n},p.dividedBy=p.div=function(e,t){return r(this,new O(e,t),d,y)},p.dividedToIntegerBy=p.idiv=function(e,t){return r(this,new O(e,t),0,1)},p.exponentiatedBy=p.pow=function(e,t){var r,n,o,i,a,s,u,c,l=this;if((e=new O(e)).c&&!e.isInteger())throw Error(Z+"Exponent not an integer: "+_(e));if(null!=t&&(t=new O(t)),a=e.e>14,!l.c||!l.c[0]||1==l.c[0]&&!l.e&&1==l.c.length||!e.c||!e.c[0])return c=new O(Math.pow(+_(l),a?e.s*(2-le(e)):+_(e))),t?c.mod(t):c;if(s=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new O(NaN);(n=!s&&l.isInteger()&&t.isInteger())&&(l=l.mod(t))}else{if(e.e>9&&(l.e>0||l.e<-1||(0==l.e?l.c[0]>1||a&&l.c[1]>=24e7:l.c[0]<8e13||a&&l.c[0]<=9999975e7)))return i=l.s<0&&le(e)?-0:0,l.e>-1&&(i=1/i),new O(s?1/i:i);k&&(i=Y(k/te+2))}for(a?(r=new O(.5),s&&(e.s=1),u=le(e)):u=(o=Math.abs(+_(e)))%2,c=new O(h);;){if(u){if(!(c=c.times(l)).c)break;i?c.c.length>i&&(c.c.length=i):n&&(c=c.mod(t))}if(o){if(0===(o=J(o/2)))break;u=o%2}else if(B(e=e.times(r),e.e+1,1),e.e>14)u=le(e);else{if(0===(o=+_(e)))break;u=o%2}l=l.times(l),i?l.c&&l.c.length>i&&(l.c.length=i):n&&(l=l.mod(t))}return n?c:(s&&(c=h.div(c)),t?c.mod(t):i?B(c,k,y,undefined):c)},p.integerValue=function(e){var t=new O(this);return null==e?e=y:ce(e,0,8),B(t,t.e+1,e)},p.isEqualTo=p.eq=function(e,t){return 0===ue(this,new O(e,t))},p.isFinite=function(){return!!this.c},p.isGreaterThan=p.gt=function(e,t){return ue(this,new O(e,t))>0},p.isGreaterThanOrEqualTo=p.gte=function(e,t){return 1===(t=ue(this,new O(e,t)))||0===t},p.isInteger=function(){return!!this.c&&ae(this.e/te)>this.c.length-2},p.isLessThan=p.lt=function(e,t){return ue(this,new O(e,t))<0},p.isLessThanOrEqualTo=p.lte=function(e,t){return-1===(t=ue(this,new O(e,t)))||0===t},p.isNaN=function(){return!this.s},p.isNegative=function(){return this.s<0},p.isPositive=function(){return this.s>0},p.isZero=function(){return!!this.c&&0==this.c[0]},p.minus=function(e,t){var r,n,o,i,a=this,s=a.s;if(t=(e=new O(e,t)).s,!s||!t)return new O(NaN);if(s!=t)return e.s=-t,a.plus(e);var u=a.e/te,c=e.e/te,l=a.c,f=e.c;if(!u||!c){if(!l||!f)return l?(e.s=-t,e):new O(f?a:NaN);if(!l[0]||!f[0])return f[0]?(e.s=-t,e):new O(l[0]?a:3==y?-0:0)}if(u=ae(u),c=ae(c),l=l.slice(),s=u-c){for((i=s<0)?(s=-s,o=l):(c=u,o=f),o.reverse(),t=s;t--;o.push(0));o.reverse()}else for(n=(i=(s=l.length)<(t=f.length))?s:t,s=t=0;t0)for(;t--;l[r++]=0);for(t=ee-1;n>s;){if(l[--n]=0;){for(r=0,p=b[o]%m,h=b[o]/m|0,i=o+(a=u);i>o;)r=((c=p*(c=v[--a]%m)+(s=h*c+(l=v[a]/m|0)*p)%m*m+d[i]+r)/y|0)+(s/m|0)+h*l,d[i--]=c%y;d[i]=r}return r?++n:d.splice(0,1),I(e,d,n)},p.negated=function(){var e=new O(this);return e.s=-e.s||null,e},p.plus=function(e,t){var r,n=this,o=n.s;if(t=(e=new O(e,t)).s,!o||!t)return new O(NaN);if(o!=t)return e.s=-t,n.minus(e);var i=n.e/te,a=e.e/te,s=n.c,u=e.c;if(!i||!a){if(!s||!u)return new O(o/0);if(!s[0]||!u[0])return u[0]?e:new O(s[0]?n:0*o)}if(i=ae(i),a=ae(a),s=s.slice(),o=i-a){for(o>0?(a=i,r=u):(o=-o,r=s),r.reverse();o--;r.push(0));r.reverse()}for((o=s.length)-(t=u.length)<0&&(r=u,u=s,s=r,t=o),o=0;t;)o=(s[--t]=s[t]+u[t]+o)/ee|0,s[t]=ee===s[t]?0:s[t]%ee;return o&&(s=[o].concat(s),++a),I(e,s,a)},p.precision=p.sd=function(e,t){var r,n,o,i=this;if(null!=e&&e!==!!e)return ce(e,1,ie),null==t?t=y:ce(t,0,8),B(new O(i),e,t);if(!(r=i.c))return null;if(n=(o=r.length-1)*te+1,o=r[o]){for(;o%10==0;o/=10,n--);for(o=r[0];o>=10;o/=10,n++);}return e&&i.e+1>n&&(n=i.e+1),n},p.shiftedBy=function(e){return ce(e,-9007199254740991,re),this.times("1e"+e)},p.squareRoot=p.sqrt=function(){var e,t,n,o,i,a=this,s=a.c,u=a.s,c=a.e,l=d+4,f=new O("0.5");if(1!==u||!s||!s[0])return new O(!u||u<0&&(!s||s[0])?NaN:s?a:1/0);if(0==(u=Math.sqrt(+_(a)))||u==1/0?(((t=se(s)).length+c)%2==0&&(t+="0"),u=Math.sqrt(+t),c=ae((c+1)/2)-(c<0||c%2),n=new O(t=u==1/0?"5e"+c:(t=u.toExponential()).slice(0,t.indexOf("e")+1)+c)):n=new O(u+""),n.c[0])for((u=(c=n.e)+l)<3&&(u=0);;)if(i=n,n=f.times(i.plus(r(a,i,l,1))),se(i.c).slice(0,u)===(t=se(n.c)).slice(0,u)){if(n.e0&&d>0){for(i=d%s||s,l=h.substr(0,i);i0&&(l+=c+h.slice(i)),p&&(l="-"+l)}n=f?l+(r.decimalSeparator||"")+((u=+r.fractionGroupSize)?f.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):f):l}return(r.prefix||"")+n+(r.suffix||"")},p.toFraction=function(e){var t,n,o,i,a,s,u,c,l,f,p,d,m=this,g=m.c;if(null!=e&&(!(u=new O(e)).isInteger()&&(u.c||1!==u.s)||u.lt(h)))throw Error(Z+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+_(u));if(!g)return new O(m);for(t=new O(h),l=n=new O(h),o=c=new O(h),d=se(g),a=t.e=d.length-m.e-1,t.c[0]=ne[(s=a%te)<0?te+s:s],e=!e||u.comparedTo(t)>0?a>0?t:l:u,s=b,b=1/0,u=new O(d),c.c[0]=0;f=r(u,t,0,1),1!=(i=n.plus(f.times(o))).comparedTo(e);)n=o,o=i,l=c.plus(f.times(i=l)),c=i,t=u.minus(f.times(i=t)),u=i;return i=r(e.minus(n),o,0,1),c=c.plus(i.times(l)),n=n.plus(i.times(o)),c.s=l.s=m.s,p=r(l,o,a*=2,y).minus(m).abs().comparedTo(r(c,n,a,y).minus(m).abs())<1?[l,o]:[c,n],b=s,p},p.toNumber=function(){return+_(this)},p.toPrecision=function(e,t){return null!=e&&ce(e,1,ie),P(this,e,t,2)},p.toString=function(e){var t,r=this,o=r.s,i=r.e;return null===i?o?(t="Infinity",o<0&&(t="-"+t)):t="NaN":(null==e?t=i<=m||i>=g?fe(se(r.c),i):pe(se(r.c),i,"0"):10===e&&T?t=pe(se((r=B(new O(r),d+i+1,y)).c),r.e,"0"):(ce(e,2,A.length,"Base"),t=n(pe(se(r.c),i,"0"),10,e,o,!0)),o<0&&r.c[0]&&(t="-"+t)),t},p.valueOf=p.toJSON=function(){return _(this)},p._isBigNumber=!0,p[Symbol.toStringTag]="BigNumber",p[Symbol.for("nodejs.util.inspect.custom")]=p.valueOf,null!=t&&O.set(t),O}();var de=he.clone();de.DEBUG=!0;const ye=de;function me(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return ge(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ge(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function ge(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r=0&&e<=255)return!0;throw new Error("".concat(t," value must be between 0 and 255"))}var Ke=r(3626).A;function He(e){return He="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},He(e)}function ze(e){return ze="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ze(e)}function Xe(e,t){for(var r=0;re.length)&&(t=e.length);for(var r=0,n=Array(t);r1&&void 0!==arguments[1]&&arguments[1];if("string"!=typeof e)return!1;try{t=new ye(e)}catch(e){return!1}return!(!r&&t.isZero()||t.isNegative()||t.times(tt).gt(new ye("9223372036854775807").toString())||t.decimalPlaces()>7||t.isNaN()||!t.isFinite())}},{key:"constructAmountRequirementsError",value:function(e){return"".concat(e," argument must be of type String, represent a positive number and have at most 7 digits after the decimal")}},{key:"_checkUnsignedIntValue",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;if(void 0!==t)switch("string"==typeof t&&(t=parseFloat(t)),!0){case"number"!=typeof t||!Number.isFinite(t)||t%1!=0:throw new Error("".concat(e," value is invalid"));case t<0:throw new Error("".concat(e," value must be unsigned"));case!r||r&&r(t,e):return t;default:throw new Error("".concat(e," value is invalid"))}}},{key:"_toXDRAmount",value:function(e){var t=new ye(e).times(tt);return n.Hyper.fromString(t.toString())}},{key:"_fromXDRAmount",value:function(e){return new ye(e).div(tt).toFixed(7)}},{key:"_fromXDRPrice",value:function(e){return new ye(e.n()).div(new ye(e.d())).toString()}},{key:"_toXDRPrice",value:function(e){var t;if(e.n&&e.d)t=new i.Price(e);else{var r=function(e){for(var t,r,n=new ye(e),o=[[new ye(0),new ye(1)],[new ye(1),new ye(0)]],i=2;!n.gt(ve);){t=n.integerValue(ye.ROUND_FLOOR),r=n.minus(t);var a=t.times(o[i-1][0]).plus(o[i-2][0]),s=t.times(o[i-1][1]).plus(o[i-2][1]);if(a.gt(ve)||s.gt(ve))break;if(o.push([a,s]),r.eq(0))break;n=new ye(1).div(r),i+=1}var u=me(o[o.length-1],2),c=u[0],l=u[1];if(c.isZero()||l.isZero())throw new Error("Couldn't find approximation");return[c.toNumber(),l.toNumber()]}(e);t=new i.Price({n:parseInt(r[0],10),d:parseInt(r[1],10)})}if(t.n()<0||t.d()<0)throw new Error("price must be positive");return t}}],(t=null)&&Qe(e.prototype,t),r&&Qe(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,r}();function st(e){return T.encodeEd25519PublicKey(e.ed25519())}at.accountMerge=function(e){var t={};try{t.body=i.OperationBody.accountMerge(Ne(e.destination))}catch(e){throw new Error("destination is invalid")}return this.setSourceAccount(t,e),new i.Operation(t)},at.allowTrust=function(e){if(!T.isValidEd25519PublicKey(e.trustor))throw new Error("trustor is invalid");var t={};if(t.trustor=U.fromPublicKey(e.trustor).xdrAccountId(),e.assetCode.length<=4){var r=e.assetCode.padEnd(4,"\0");t.asset=i.AssetCode.assetTypeCreditAlphanum4(r)}else{if(!(e.assetCode.length<=12))throw new Error("Asset code must be 12 characters at max.");var n=e.assetCode.padEnd(12,"\0");t.asset=i.AssetCode.assetTypeCreditAlphanum12(n)}"boolean"==typeof e.authorize?e.authorize?t.authorize=i.TrustLineFlags.authorizedFlag().value:t.authorize=0:t.authorize=e.authorize;var o=new i.AllowTrustOp(t),a={};return a.body=i.OperationBody.allowTrust(o),this.setSourceAccount(a,e),new i.Operation(a)},at.bumpSequence=function(e){var t={};if("string"!=typeof e.bumpTo)throw new Error("bumpTo must be a string");try{new ye(e.bumpTo)}catch(e){throw new Error("bumpTo must be a stringified number")}t.bumpTo=n.Hyper.fromString(e.bumpTo);var r=new i.BumpSequenceOp(t),o={};return o.body=i.OperationBody.bumpSequence(r),this.setSourceAccount(o,e),new i.Operation(o)},at.changeTrust=function(e){var t={};if(e.asset instanceof F)t.line=e.asset.toChangeTrustXDRObject();else{if(!(e.asset instanceof Te))throw new TypeError("asset must be Asset or LiquidityPoolAsset");t.line=e.asset.toXDRObject()}if(void 0!==e.limit&&!this.isValidAmount(e.limit,!0))throw new TypeError(this.constructAmountRequirementsError("limit"));e.limit?t.limit=this._toXDRAmount(e.limit):t.limit=n.Hyper.fromString(new ye("9223372036854775807").toString()),e.source&&(t.source=e.source.masterKeypair);var r=new i.ChangeTrustOp(t),o={};return o.body=i.OperationBody.changeTrust(r),this.setSourceAccount(o,e),new i.Operation(o)},at.createAccount=function(e){if(!T.isValidEd25519PublicKey(e.destination))throw new Error("destination is invalid");if(!this.isValidAmount(e.startingBalance,!0))throw new TypeError(this.constructAmountRequirementsError("startingBalance"));var t={};t.destination=U.fromPublicKey(e.destination).xdrAccountId(),t.startingBalance=this._toXDRAmount(e.startingBalance);var r=new i.CreateAccountOp(t),n={};return n.body=i.OperationBody.createAccount(r),this.setSourceAccount(n,e),new i.Operation(n)},at.createClaimableBalance=function(e){if(!(e.asset instanceof F))throw new Error("must provide an asset for create claimable balance operation");if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(!Array.isArray(e.claimants)||0===e.claimants.length)throw new Error("must provide at least one claimant");var t={};t.asset=e.asset.toXDRObject(),t.amount=this._toXDRAmount(e.amount),t.claimants=Object.values(e.claimants).map((function(e){return e.toXDRObject()}));var r=new i.CreateClaimableBalanceOp(t),n={};return n.body=i.OperationBody.createClaimableBalance(r),this.setSourceAccount(n,e),new i.Operation(n)},at.claimClaimableBalance=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Fe(e.balanceId);var t={};t.balanceId=i.ClaimableBalanceId.fromXDR(e.balanceId,"hex");var r=new i.ClaimClaimableBalanceOp(t),n={};return n.body=i.OperationBody.claimClaimableBalance(r),this.setSourceAccount(n,e),new i.Operation(n)},at.clawbackClaimableBalance=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Fe(e.balanceId);var t={balanceId:i.ClaimableBalanceId.fromXDR(e.balanceId,"hex")},r={body:i.OperationBody.clawbackClaimableBalance(new i.ClawbackClaimableBalanceOp(t))};return this.setSourceAccount(r,e),new i.Operation(r)},at.createPassiveSellOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price);var r=new i.CreatePassiveSellOfferOp(t),n={};return n.body=i.OperationBody.createPassiveSellOffer(r),this.setSourceAccount(n,e),new i.Operation(n)},at.inflation=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};return t.body=i.OperationBody.inflation(),this.setSourceAccount(t,e),new i.Operation(t)},at.manageData=function(e){var t={};if(!("string"==typeof e.name&&e.name.length<=64))throw new Error("name must be a string, up to 64 characters");if(t.dataName=e.name,"string"!=typeof e.value&&!De.isBuffer(e.value)&&null!==e.value)throw new Error("value must be a string, Buffer or null");if("string"==typeof e.value?t.dataValue=De.from(e.value):t.dataValue=e.value,null!==t.dataValue&&t.dataValue.length>64)throw new Error("value cannot be longer that 64 bytes");var r=new i.ManageDataOp(t),n={};return n.body=i.OperationBody.manageData(r),this.setSourceAccount(n,e),new i.Operation(n)},at.manageSellOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.amount,!0))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price),void 0!==e.offerId?e.offerId=e.offerId.toString():e.offerId="0",t.offerId=n.Hyper.fromString(e.offerId);var r=new i.ManageSellOfferOp(t),o={};return o.body=i.OperationBody.manageSellOffer(r),this.setSourceAccount(o,e),new i.Operation(o)},at.manageBuyOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.buyAmount,!0))throw new TypeError(this.constructAmountRequirementsError("buyAmount"));if(t.buyAmount=this._toXDRAmount(e.buyAmount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price),void 0!==e.offerId?e.offerId=e.offerId.toString():e.offerId="0",t.offerId=n.Hyper.fromString(e.offerId);var r=new i.ManageBuyOfferOp(t),o={};return o.body=i.OperationBody.manageBuyOffer(r),this.setSourceAccount(o,e),new i.Operation(o)},at.pathPaymentStrictReceive=function(e){switch(!0){case!e.sendAsset:throw new Error("Must specify a send asset");case!this.isValidAmount(e.sendMax):throw new TypeError(this.constructAmountRequirementsError("sendMax"));case!e.destAsset:throw new Error("Must provide a destAsset for a payment operation");case!this.isValidAmount(e.destAmount):throw new TypeError(this.constructAmountRequirementsError("destAmount"))}var t={};t.sendAsset=e.sendAsset.toXDRObject(),t.sendMax=this._toXDRAmount(e.sendMax);try{t.destination=Ne(e.destination)}catch(e){throw new Error("destination is invalid")}t.destAsset=e.destAsset.toXDRObject(),t.destAmount=this._toXDRAmount(e.destAmount);var r=e.path?e.path:[];t.path=r.map((function(e){return e.toXDRObject()}));var n=new i.PathPaymentStrictReceiveOp(t),o={};return o.body=i.OperationBody.pathPaymentStrictReceive(n),this.setSourceAccount(o,e),new i.Operation(o)},at.pathPaymentStrictSend=function(e){switch(!0){case!e.sendAsset:throw new Error("Must specify a send asset");case!this.isValidAmount(e.sendAmount):throw new TypeError(this.constructAmountRequirementsError("sendAmount"));case!e.destAsset:throw new Error("Must provide a destAsset for a payment operation");case!this.isValidAmount(e.destMin):throw new TypeError(this.constructAmountRequirementsError("destMin"))}var t={};t.sendAsset=e.sendAsset.toXDRObject(),t.sendAmount=this._toXDRAmount(e.sendAmount);try{t.destination=Ne(e.destination)}catch(e){throw new Error("destination is invalid")}t.destAsset=e.destAsset.toXDRObject(),t.destMin=this._toXDRAmount(e.destMin);var r=e.path?e.path:[];t.path=r.map((function(e){return e.toXDRObject()}));var n=new i.PathPaymentStrictSendOp(t),o={};return o.body=i.OperationBody.pathPaymentStrictSend(n),this.setSourceAccount(o,e),new i.Operation(o)},at.payment=function(e){if(!e.asset)throw new Error("Must provide an asset for a payment operation");if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));var t={};try{t.destination=Ne(e.destination)}catch(e){throw new Error("destination is invalid")}t.asset=e.asset.toXDRObject(),t.amount=this._toXDRAmount(e.amount);var r=new i.PaymentOp(t),n={};return n.body=i.OperationBody.payment(r),this.setSourceAccount(n,e),new i.Operation(n)},at.setOptions=function(e){var t={};if(e.inflationDest){if(!T.isValidEd25519PublicKey(e.inflationDest))throw new Error("inflationDest is invalid");t.inflationDest=U.fromPublicKey(e.inflationDest).xdrAccountId()}if(t.clearFlags=this._checkUnsignedIntValue("clearFlags",e.clearFlags),t.setFlags=this._checkUnsignedIntValue("setFlags",e.setFlags),t.masterWeight=this._checkUnsignedIntValue("masterWeight",e.masterWeight,qe),t.lowThreshold=this._checkUnsignedIntValue("lowThreshold",e.lowThreshold,qe),t.medThreshold=this._checkUnsignedIntValue("medThreshold",e.medThreshold,qe),t.highThreshold=this._checkUnsignedIntValue("highThreshold",e.highThreshold,qe),void 0!==e.homeDomain&&"string"!=typeof e.homeDomain)throw new TypeError("homeDomain argument must be of type String");if(t.homeDomain=e.homeDomain,e.signer){var r,n=this._checkUnsignedIntValue("signer.weight",e.signer.weight,qe),o=0;if(e.signer.ed25519PublicKey){if(!T.isValidEd25519PublicKey(e.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");var a=T.decodeEd25519PublicKey(e.signer.ed25519PublicKey);r=new i.SignerKey.signerKeyTypeEd25519(a),o+=1}if(e.signer.preAuthTx){if("string"==typeof e.signer.preAuthTx&&(e.signer.preAuthTx=Ve.from(e.signer.preAuthTx,"hex")),!Ve.isBuffer(e.signer.preAuthTx)||32!==e.signer.preAuthTx.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");r=new i.SignerKey.signerKeyTypePreAuthTx(e.signer.preAuthTx),o+=1}if(e.signer.sha256Hash){if("string"==typeof e.signer.sha256Hash&&(e.signer.sha256Hash=Ve.from(e.signer.sha256Hash,"hex")),!Ve.isBuffer(e.signer.sha256Hash)||32!==e.signer.sha256Hash.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");r=new i.SignerKey.signerKeyTypeHashX(e.signer.sha256Hash),o+=1}if(e.signer.ed25519SignedPayload){if(!T.isValidSignedPayload(e.signer.ed25519SignedPayload))throw new Error("signer.ed25519SignedPayload is invalid.");var s=T.decodeSignedPayload(e.signer.ed25519SignedPayload),u=i.SignerKeyEd25519SignedPayload.fromXDR(s);r=i.SignerKey.signerKeyTypeEd25519SignedPayload(u),o+=1}if(1!==o)throw new Error("Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx.");t.signer=new i.Signer({key:r,weight:n})}var c=new i.SetOptionsOp(t),l={};return l.body=i.OperationBody.setOptions(c),this.setSourceAccount(l,e),new i.Operation(l)},at.beginSponsoringFutureReserves=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!T.isValidEd25519PublicKey(e.sponsoredId))throw new Error("sponsoredId is invalid");var t=new i.BeginSponsoringFutureReservesOp({sponsoredId:U.fromPublicKey(e.sponsoredId).xdrAccountId()}),r={};return r.body=i.OperationBody.beginSponsoringFutureReserves(t),this.setSourceAccount(r,e),new i.Operation(r)},at.endSponsoringFutureReserves=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};return t.body=i.OperationBody.endSponsoringFutureReserves(),this.setSourceAccount(t,e),new i.Operation(t)},at.revokeAccountSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!T.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");var t=i.LedgerKey.account(new i.LedgerKeyAccount({accountId:U.fromPublicKey(e.account).xdrAccountId()})),r=i.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.Operation(n)},at.revokeTrustlineSponsorship=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!T.isValidEd25519PublicKey(t.account))throw new Error("account is invalid");if(t.asset instanceof F)e=t.asset.toTrustLineXDRObject();else{if(!(t.asset instanceof Ce))throw new TypeError("asset must be an Asset or LiquidityPoolId");e=t.asset.toXDRObject()}var r=i.LedgerKey.trustline(new i.LedgerKeyTrustLine({accountId:U.fromPublicKey(t.account).xdrAccountId(),asset:e})),n=i.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(r),o={};return o.body=i.OperationBody.revokeSponsorship(n),this.setSourceAccount(o,t),new i.Operation(o)},at.revokeOfferSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!T.isValidEd25519PublicKey(e.seller))throw new Error("seller is invalid");if("string"!=typeof e.offerId)throw new Error("offerId is invalid");var t=i.LedgerKey.offer(new i.LedgerKeyOffer({sellerId:U.fromPublicKey(e.seller).xdrAccountId(),offerId:i.Int64.fromString(e.offerId)})),r=i.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.Operation(n)},at.revokeDataSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!T.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");if("string"!=typeof e.name||e.name.length>64)throw new Error("name must be a string, up to 64 characters");var t=i.LedgerKey.data(new i.LedgerKeyData({accountId:U.fromPublicKey(e.account).xdrAccountId(),dataName:e.name})),r=i.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.Operation(n)},at.revokeClaimableBalanceSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if("string"!=typeof e.balanceId)throw new Error("balanceId is invalid");var t=i.LedgerKey.claimableBalance(new i.LedgerKeyClaimableBalance({balanceId:i.ClaimableBalanceId.fromXDR(e.balanceId,"hex")})),r=i.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.Operation(n)},at.revokeLiquidityPoolSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if("string"!=typeof e.liquidityPoolId)throw new Error("liquidityPoolId is invalid");var t=i.LedgerKey.liquidityPool(new i.LedgerKeyLiquidityPool({liquidityPoolId:i.PoolId.fromXDR(e.liquidityPoolId,"hex")})),r=i.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={body:i.OperationBody.revokeSponsorship(r)};return this.setSourceAccount(n,e),new i.Operation(n)},at.revokeSignerSponsorship=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!T.isValidEd25519PublicKey(t.account))throw new Error("account is invalid");if(t.signer.ed25519PublicKey){if(!T.isValidEd25519PublicKey(t.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");var r=T.decodeEd25519PublicKey(t.signer.ed25519PublicKey);e=new i.SignerKey.signerKeyTypeEd25519(r)}else if(t.signer.preAuthTx){var n;if(n="string"==typeof t.signer.preAuthTx?Ke.from(t.signer.preAuthTx,"hex"):t.signer.preAuthTx,!Ke.isBuffer(n)||32!==n.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");e=new i.SignerKey.signerKeyTypePreAuthTx(n)}else{if(!t.signer.sha256Hash)throw new Error("signer is invalid");var o;if(o="string"==typeof t.signer.sha256Hash?Ke.from(t.signer.sha256Hash,"hex"):t.signer.sha256Hash,!Ke.isBuffer(o)||32!==o.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");e=new i.SignerKey.signerKeyTypeHashX(o)}var a=new i.RevokeSponsorshipOpSigner({accountId:U.fromPublicKey(t.account).xdrAccountId(),signerKey:e}),s=i.RevokeSponsorshipOp.revokeSponsorshipSigner(a),u={};return u.body=i.OperationBody.revokeSponsorship(s),this.setSourceAccount(u,t),new i.Operation(u)},at.clawback=function(e){var t={};if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));t.amount=this._toXDRAmount(e.amount),t.asset=e.asset.toXDRObject();try{t.from=Ne(e.from)}catch(e){throw new Error("from address is invalid")}var r={body:i.OperationBody.clawback(new i.ClawbackOp(t))};return this.setSourceAccount(r,e),new i.Operation(r)},at.setTrustLineFlags=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};if("object"!==He(e.flags)||0===Object.keys(e.flags).length)throw new Error("opts.flags must be a map of boolean flags to modify");var r={authorized:i.TrustLineFlags.authorizedFlag(),authorizedToMaintainLiabilities:i.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),clawbackEnabled:i.TrustLineFlags.trustlineClawbackEnabledFlag()},n=0,o=0;Object.keys(e.flags).forEach((function(t){if(!Object.prototype.hasOwnProperty.call(r,t))throw new Error("unsupported flag name specified: ".concat(t));var i=e.flags[t],a=r[t].value;!0===i?o|=a:!1===i&&(n|=a)})),t.trustor=U.fromPublicKey(e.trustor).xdrAccountId(),t.asset=e.asset.toXDRObject(),t.clearFlags=n,t.setFlags=o;var a={body:i.OperationBody.setTrustLineFlags(new i.SetTrustLineFlagsOp(t))};return this.setSourceAccount(a,e),new i.Operation(a)},at.liquidityPoolDeposit=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.liquidityPoolId,r=e.maxAmountA,n=e.maxAmountB,o=e.minPrice,a=e.maxPrice,s={};if(!t)throw new TypeError("liquidityPoolId argument is required");if(s.liquidityPoolId=i.PoolId.fromXDR(t,"hex"),!this.isValidAmount(r,!0))throw new TypeError(this.constructAmountRequirementsError("maxAmountA"));if(s.maxAmountA=this._toXDRAmount(r),!this.isValidAmount(n,!0))throw new TypeError(this.constructAmountRequirementsError("maxAmountB"));if(s.maxAmountB=this._toXDRAmount(n),void 0===o)throw new TypeError("minPrice argument is required");if(s.minPrice=this._toXDRPrice(o),void 0===a)throw new TypeError("maxPrice argument is required");s.maxPrice=this._toXDRPrice(a);var u=new i.LiquidityPoolDepositOp(s),c={body:i.OperationBody.liquidityPoolDeposit(u)};return this.setSourceAccount(c,e),new i.Operation(c)},at.liquidityPoolWithdraw=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};if(!e.liquidityPoolId)throw new TypeError("liquidityPoolId argument is required");if(t.liquidityPoolId=i.PoolId.fromXDR(e.liquidityPoolId,"hex"),!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),!this.isValidAmount(e.minAmountA,!0))throw new TypeError(this.constructAmountRequirementsError("minAmountA"));if(t.minAmountA=this._toXDRAmount(e.minAmountA),!this.isValidAmount(e.minAmountB,!0))throw new TypeError(this.constructAmountRequirementsError("minAmountB"));t.minAmountB=this._toXDRAmount(e.minAmountB);var r=new i.LiquidityPoolWithdrawOp(t),n={body:i.OperationBody.liquidityPoolWithdraw(r)};return this.setSourceAccount(n,e),new i.Operation(n)},at.invokeHostFunction=function(e){if(!e.func)throw new TypeError("host function invocation ('func') required (got ".concat(JSON.stringify(e),")"));var t=new i.InvokeHostFunctionOp({hostFunction:e.func,auth:e.auth||[]}),r={body:i.OperationBody.invokeHostFunction(t)};return this.setSourceAccount(r,e),new i.Operation(r)},at.extendFootprintTtl=function(e){var t;if((null!==(t=e.extendTo)&&void 0!==t?t:-1)<=0)throw new RangeError("extendTo has to be positive");var r=new i.ExtendFootprintTtlOp({ext:new i.ExtensionPoint(0),extendTo:e.extendTo}),n={body:i.OperationBody.extendFootprintTtl(r)};return this.setSourceAccount(n,e),new i.Operation(n)},at.restoreFootprint=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=new i.RestoreFootprintOp({ext:new i.ExtensionPoint(0)}),r={body:i.OperationBody.restoreFootprint(t)};return this.setSourceAccount(r,null!=e?e:{}),new i.Operation(r)},at.createStellarAssetContract=function(e){var t=e.asset;if("string"==typeof t){var r=Ye(t.split(":"),2),n=r[0],o=r[1];t=new F(n,o)}if(!(t instanceof F))throw new TypeError("expected Asset in 'opts.asset', got ".concat(t));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.HostFunction.hostFunctionTypeCreateContract(new i.CreateContractArgs({executable:i.ContractExecutable.contractExecutableStellarAsset(),contractIdPreimage:i.ContractIdPreimage.contractIdPreimageFromAsset(t.toXDRObject())}))})},at.invokeContractFunction=function(e){var t=new Ge(e.contract);if("contract"!==t._type)throw new TypeError("expected contract strkey instance, got ".concat(t));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.HostFunction.hostFunctionTypeInvokeContract(new i.InvokeContractArgs({contractAddress:t.toScAddress(),functionName:e.function,args:e.args}))})},at.createCustomContract=function(e){var t,r=We.from(e.salt||U.random().xdrPublicKey().value());if(!e.wasmHash||32!==e.wasmHash.length)throw new TypeError("expected hash(contract WASM) in 'opts.wasmHash', got ".concat(e.wasmHash));if(32!==r.length)throw new TypeError("expected 32-byte salt in 'opts.salt', got ".concat(e.wasmHash));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.HostFunction.hostFunctionTypeCreateContractV2(new i.CreateContractArgsV2({executable:i.ContractExecutable.contractExecutableWasm(We.from(e.wasmHash)),contractIdPreimage:i.ContractIdPreimage.contractIdPreimageFromAddress(new i.ContractIdPreimageFromAddress({address:e.address.toScAddress(),salt:r})),constructorArgs:null!==(t=e.constructorArgs)&&void 0!==t?t:[]}))})},at.uploadContractWasm=function(e){return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.HostFunction.hostFunctionTypeUploadContractWasm(We.from(e.wasm))})};var ut=r(3626).A;function ct(e){return ct="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ct(e)}function lt(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:null;switch(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._type=t,this._value=r,this._type){case pt:break;case ht:e._validateIdValue(r);break;case dt:e._validateTextValue(r);break;case yt:case mt:e._validateHashValue(r),"string"==typeof r&&(this._value=ut.from(r,"hex"));break;default:throw new Error("Invalid memo type")}}return t=e,o=[{key:"_validateIdValue",value:function(e){var t,r=new Error("Expects a int64 as a string. Got ".concat(e));if("string"!=typeof e)throw r;try{t=new ye(e)}catch(e){throw r}if(!t.isFinite())throw r;if(t.isNaN())throw r}},{key:"_validateTextValue",value:function(e){if(!i.Memo.armTypeForArm("text").isValid(e))throw new Error("Expects string, array or buffer, max 28 bytes")}},{key:"_validateHashValue",value:function(e){var t,r=new Error("Expects a 32 byte hash value or hex encoded string. Got ".concat(e));if(null==e)throw r;if("string"==typeof e){if(!/^[0-9A-Fa-f]{64}$/g.test(e))throw r;t=ut.from(e,"hex")}else{if(!ut.isBuffer(e))throw r;t=ut.from(e)}if(!t.length||32!==t.length)throw r}},{key:"none",value:function(){return new e(pt)}},{key:"text",value:function(t){return new e(dt,t)}},{key:"id",value:function(t){return new e(ht,t)}},{key:"hash",value:function(t){return new e(yt,t)}},{key:"return",value:function(t){return new e(mt,t)}},{key:"fromXDRObject",value:function(t){switch(t.arm()){case"id":return e.id(t.value().toString());case"text":return e.text(t.value());case"hash":return e.hash(t.value());case"retHash":return e.return(t.value())}if(void 0===t.value())return e.none();throw new Error("Unknown type")}}],(r=[{key:"type",get:function(){return this._type},set:function(e){throw new Error("Memo is immutable")}},{key:"value",get:function(){switch(this._type){case pt:return null;case ht:case dt:return this._value;case yt:case mt:return ut.from(this._value);default:throw new Error("Invalid memo type")}},set:function(e){throw new Error("Memo is immutable")}},{key:"toXDRObject",value:function(){switch(this._type){case pt:return i.Memo.memoNone();case ht:return i.Memo.memoId(n.UnsignedHyper.fromString(this._value));case dt:return i.Memo.memoText(this._value);case yt:return i.Memo.memoHash(this._value);case mt:return i.Memo.memoReturn(this._value);default:return null}}}])&<(t.prototype,r),o&<(t,o),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,o}(),vt=r(3626).A;function bt(e){return bt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},bt(e)}function wt(e,t){for(var r=0;r=this.operations.length)throw new RangeError("invalid operation index");var t=this.operations[e];try{t=at.createClaimableBalance(t)}catch(e){throw new TypeError("expected createClaimableBalance, got ".concat(t.type,": ").concat(e))}var r=T.decodeEd25519PublicKey(je(this.source)),n=u(i.HashIdPreimage.envelopeTypeOpId(new i.HashIdPreimageOperationId({sourceAccount:i.AccountId.publicKeyTypeEd25519(r),seqNum:i.SequenceNumber.fromString(this.sequence),opNum:e})).toXDR("raw"));return i.ClaimableBalanceId.claimableBalanceIdTypeV0(n).toXDR("hex")}}])&&wt(r.prototype,n),o&&wt(r,o),Object.defineProperty(r,"prototype",{writable:!1}),r;var r,n,o}(G),Pt=r(3626).A;function xt(e){return xt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},xt(e)}function It(e,t){for(var r=0;re.length)&&(t=e.length);for(var r=0,n=Array(t);r1&&void 0!==arguments[1]?arguments[1]:{};if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw new Error("must specify source account for the transaction");if(void 0===r.fee)throw new Error("must specify fee for the transaction (in stroops)");this.source=t,this.operations=[],this.baseFee=r.fee,this.timebounds=r.timebounds?rr({},r.timebounds):null,this.ledgerbounds=r.ledgerbounds?rr({},r.ledgerbounds):null,this.minAccountSequence=r.minAccountSequence||null,this.minAccountSequenceAge=r.minAccountSequenceAge||null,this.minAccountSequenceLedgerGap=r.minAccountSequenceLedgerGap||null,this.extraSigners=r.extraSigners?Qt(r.extraSigners):null,this.memo=r.memo||gt.none(),this.networkPassphrase=r.networkPassphrase||null,this.sorobanData=r.sorobanData?new $t(r.sorobanData).build():null}return t=e,o=[{key:"cloneFrom",value:function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!(t instanceof Ot))throw new TypeError("expected a 'Transaction', got: ".concat(t));var n,o=(BigInt(t.sequence)-1n).toString();if(T.isValidMed25519PublicKey(t.source))n=Kt.fromAddress(t.source,o);else{if(!T.isValidEd25519PublicKey(t.source))throw new TypeError("unsupported tx source account: ".concat(t.source));n=new Ft(t.source,o)}var i=new e(n,rr({fee:(parseInt(t.fee,10)/t.operations.length||ar).toString(),memo:t.memo,networkPassphrase:t.networkPassphrase,timebounds:t.timeBounds,ledgerbounds:t.ledgerBounds,minAccountSequence:t.minAccountSequence,minAccountSequenceAge:t.minAccountSequenceAge,minAccountSequenceLedgerGap:t.minAccountSequenceLedgerGap,extraSigners:t.extraSigners},r));return t._tx.operations().forEach((function(e){return i.addOperation(e)})),i}},{key:"buildFeeBumpTransaction",value:function(e,t,r,n){var o=r.operations.length,a=new ye(r.fee).div(o),s=new ye(t);if(s.lt(a))throw new Error("Invalid baseFee, it should be at least ".concat(a," stroops."));var u=new ye(ar);if(s.lt(u))throw new Error("Invalid baseFee, it should be at least ".concat(u," stroops."));var c,l=r.toEnvelope();if(l.switch()===i.EnvelopeType.envelopeTypeTxV0()){var f=l.v0().tx(),p=new i.Transaction({sourceAccount:new i.MuxedAccount.keyTypeEd25519(f.sourceAccountEd25519()),fee:f.fee(),seqNum:f.seqNum(),cond:i.Preconditions.precondTime(f.timeBounds()),memo:f.memo(),operations:f.operations(),ext:new i.TransactionExt(0)});l=new i.TransactionEnvelope.envelopeTypeTx(new i.TransactionV1Envelope({tx:p,signatures:l.v0().signatures()}))}c="string"==typeof e?Ne(e):e.xdrMuxedAccount();var h=new i.FeeBumpTransaction({feeSource:c,fee:i.Int64.fromString(s.times(o+1).toString()),innerTx:i.FeeBumpTransactionInnerTx.envelopeTypeTx(l.v1()),ext:new i.FeeBumpTransactionExt(0)}),d=new i.FeeBumpTransactionEnvelope({tx:h,signatures:[]}),y=new i.TransactionEnvelope.envelopeTypeTxFeeBump(d);return new Nt(y,n)}},{key:"fromXDR",value:function(e,t){return"string"==typeof e&&(e=i.TransactionEnvelope.fromXDR(e,"base64")),e.switch()===i.EnvelopeType.envelopeTypeTxFeeBump()?new Nt(e,t):new Ot(e,t)}}],(r=[{key:"addOperation",value:function(e){return this.operations.push(e),this}},{key:"addOperationAt",value:function(e,t){return this.operations.splice(t,0,e),this}},{key:"clearOperations",value:function(){return this.operations=[],this}},{key:"clearOperationAt",value:function(e){return this.operations.splice(e,1),this}},{key:"addMemo",value:function(e){return this.memo=e,this}},{key:"setTimeout",value:function(e){if(null!==this.timebounds&&this.timebounds.maxTime>0)throw new Error("TimeBounds.max_time has been already set - setting timeout would overwrite it.");if(e<0)throw new Error("timeout cannot be negative");if(e>0){var t=Math.floor(Date.now()/1e3)+e;null===this.timebounds?this.timebounds={minTime:0,maxTime:t}:this.timebounds={minTime:this.timebounds.minTime,maxTime:t}}else this.timebounds={minTime:0,maxTime:0};return this}},{key:"setTimebounds",value:function(e,t){if("number"==typeof e&&(e=new Date(1e3*e)),"number"==typeof t&&(t=new Date(1e3*t)),null!==this.timebounds)throw new Error("TimeBounds has been already set - setting timebounds would overwrite it.");var r=Math.floor(e.valueOf()/1e3),n=Math.floor(t.valueOf()/1e3);if(r<0)throw new Error("min_time cannot be negative");if(n<0)throw new Error("max_time cannot be negative");if(n>0&&r>n)throw new Error("min_time cannot be greater than max_time");return this.timebounds={minTime:r,maxTime:n},this}},{key:"setLedgerbounds",value:function(e,t){if(null!==this.ledgerbounds)throw new Error("LedgerBounds has been already set - setting ledgerbounds would overwrite it.");if(e<0)throw new Error("min_ledger cannot be negative");if(t<0)throw new Error("max_ledger cannot be negative");if(t>0&&e>t)throw new Error("min_ledger cannot be greater than max_ledger");return this.ledgerbounds={minLedger:e,maxLedger:t},this}},{key:"setMinAccountSequence",value:function(e){if(null!==this.minAccountSequence)throw new Error("min_account_sequence has been already set - setting min_account_sequence would overwrite it.");return this.minAccountSequence=e,this}},{key:"setMinAccountSequenceAge",value:function(e){if("number"!=typeof e)throw new Error("min_account_sequence_age must be a number");if(null!==this.minAccountSequenceAge)throw new Error("min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.");if(e<0)throw new Error("min_account_sequence_age cannot be negative");return this.minAccountSequenceAge=e,this}},{key:"setMinAccountSequenceLedgerGap",value:function(e){if(null!==this.minAccountSequenceLedgerGap)throw new Error("min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.");if(e<0)throw new Error("min_account_sequence_ledger_gap cannot be negative");return this.minAccountSequenceLedgerGap=e,this}},{key:"setExtraSigners",value:function(e){if(!Array.isArray(e))throw new Error("extra_signers must be an array of strings.");if(null!==this.extraSigners)throw new Error("extra_signers has been already set - setting extra_signers would overwrite it.");if(e.length>2)throw new Error("extra_signers cannot be longer than 2 elements.");return this.extraSigners=Qt(e),this}},{key:"setNetworkPassphrase",value:function(e){return this.networkPassphrase=e,this}},{key:"setSorobanData",value:function(e){return this.sorobanData=new $t(e).build(),this}},{key:"build",value:function(){var e=new ye(this.source.sequenceNumber()).plus(1),t={fee:new ye(this.baseFee).times(this.operations.length).toNumber(),seqNum:i.SequenceNumber.fromString(e.toString()),memo:this.memo?this.memo.toXDRObject():null};if(null===this.timebounds||void 0===this.timebounds.minTime||void 0===this.timebounds.maxTime)throw new Error("TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).");cr(this.timebounds.minTime)&&(this.timebounds.minTime=this.timebounds.minTime.getTime()/1e3),cr(this.timebounds.maxTime)&&(this.timebounds.maxTime=this.timebounds.maxTime.getTime()/1e3),this.timebounds.minTime=n.UnsignedHyper.fromString(this.timebounds.minTime.toString()),this.timebounds.maxTime=n.UnsignedHyper.fromString(this.timebounds.maxTime.toString());var r=new i.TimeBounds(this.timebounds);if(this.hasV2Preconditions()){var o=null;null!==this.ledgerbounds&&(o=new i.LedgerBounds(this.ledgerbounds));var a=this.minAccountSequence||"0";a=i.SequenceNumber.fromString(a);var s=n.UnsignedHyper.fromString(null!==this.minAccountSequenceAge?this.minAccountSequenceAge.toString():"0"),u=this.minAccountSequenceLedgerGap||0,c=null!==this.extraSigners?this.extraSigners.map(Jt.decodeAddress):[];t.cond=i.Preconditions.precondV2(new i.PreconditionsV2({timeBounds:r,ledgerBounds:o,minSeqNum:a,minSeqAge:s,minSeqLedgerGap:u,extraSigners:c}))}else t.cond=i.Preconditions.precondTime(r);t.sourceAccount=Ne(this.source.accountId()),this.sorobanData?t.ext=new i.TransactionExt(1,this.sorobanData):t.ext=new i.TransactionExt(0,i.Void);var l=new i.Transaction(t);l.operations(this.operations);var f=new i.TransactionEnvelope.envelopeTypeTx(new i.TransactionV1Envelope({tx:l})),p=new Ot(f,this.networkPassphrase);return this.source.incrementSequenceNumber(),p}},{key:"hasV2Preconditions",value:function(){return null!==this.ledgerbounds||null!==this.minAccountSequence||null!==this.minAccountSequenceAge||null!==this.minAccountSequenceLedgerGap||null!==this.extraSigners&&this.extraSigners.length>0}}])&&or(t.prototype,r),o&&or(t,o),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,o}();function cr(e){return e instanceof Date&&!isNaN(e)}var lr={PUBLIC:"Public Global Stellar Network ; September 2015",TESTNET:"Test SDF Network ; September 2015",FUTURENET:"Test SDF Future Network ; October 2022",SANDBOX:"Local Sandbox Stellar Network ; September 2022",STANDALONE:"Standalone Network ; February 2017"};function fr(e){return fr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},fr(e)}function pr(e){return function(e){if(Array.isArray(e))return e}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return hr(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?hr(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function hr(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r0&&(r=t>r.length?["0",r.toString().padStart(t,"0")].join("."):[r.slice(0,-t),r.slice(-t)].join(".")),r.replace(/(\.\d*?)0+$/,"$1")}},{key:"parseTokenAmount",value:function(e,t){var r,n=pr(e.split(".").slice()),o=n[0],i=n[1];if(n.slice(2).length)throw new Error("Invalid decimal value: ".concat(e));return BigInt(o+(null!==(r=null==i?void 0:i.padEnd(t,"0"))&&void 0!==r?r:"0".repeat(t))).toString()}}],(t=null)&&dr(e.prototype,t),r&&dr(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,r}();function gr(e){return gr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gr(e)}function vr(e,t){for(var r=0;r1?t-1:0),n=1;nNumber.MAX_SAFE_INTEGER||e>64n),r=BigInt.asUintN(64,e);return i.ScVal.scvI128(new i.Int128Parts({hi:new i.Int64(t),lo:new i.Uint64(r)}))}},{key:"toU128",value:function(){this._sizeCheck(128);var e=this.int.toBigInt();return i.ScVal.scvU128(new i.UInt128Parts({hi:new i.Uint64(BigInt.asUintN(64,e>>64n)),lo:new i.Uint64(BigInt.asUintN(64,e))}))}},{key:"toI256",value:function(){var e=this.int.toBigInt(),t=BigInt.asIntN(64,e>>192n),r=BigInt.asUintN(64,e>>128n),n=BigInt.asUintN(64,e>>64n),o=BigInt.asUintN(64,e);return i.ScVal.scvI256(new i.Int256Parts({hiHi:new i.Int64(t),hiLo:new i.Uint64(r),loHi:new i.Uint64(n),loLo:new i.Uint64(o)}))}},{key:"toU256",value:function(){var e=this.int.toBigInt(),t=BigInt.asUintN(64,e>>192n),r=BigInt.asUintN(64,e>>128n),n=BigInt.asUintN(64,e>>64n),o=BigInt.asUintN(64,e);return i.ScVal.scvU256(new i.UInt256Parts({hiHi:new i.Uint64(t),hiLo:new i.Uint64(r),loHi:new i.Uint64(n),loLo:new i.Uint64(o)}))}},{key:"toScVal",value:function(){switch(this.type){case"i64":return this.toI64();case"i128":return this.toI128();case"i256":return this.toI256();case"u64":return this.toU64();case"u128":return this.toU128();case"u256":return this.toU256();default:throw TypeError("invalid type: ".concat(this.type))}}},{key:"valueOf",value:function(){return this.int.valueOf()}},{key:"toString",value:function(){return this.int.toString()}},{key:"toJSON",value:function(){return{value:this.toBigInt().toString(),type:this.type}}},{key:"_sizeCheck",value:function(e){if(this.int.size>e)throw RangeError("value too large for ".concat(e," bits (").concat(this.type,")"))}}])&&en(e.prototype,t),r&&en(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,r}();function on(e){return on="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},on(e)}function an(e,t){for(var r=0;re.length)&&(t=e.length);for(var r=0,n=Array(t);r1&&void 0!==arguments[1]?arguments[1]:{};switch(gn(e)){case"object":var r,n,o;if(null===e)return i.ScVal.scvVoid();if(e instanceof i.ScVal)return e;if(e instanceof Ge)return e.toScVal();if(e instanceof wr)return e.address().toScVal();if(e instanceof Uint8Array||dn.isBuffer(e)){var a,s=Uint8Array.from(e);switch(null!==(a=null==t?void 0:t.type)&&void 0!==a?a:"bytes"){case"bytes":return i.ScVal.scvBytes(s);case"symbol":return i.ScVal.scvSymbol(s);case"string":return i.ScVal.scvString(s);default:throw new TypeError("invalid type (".concat(t.type,") specified for bytes-like value"))}}if(Array.isArray(e)){if(e.length>0&&e.some((function(t){return gn(t)!==gn(e[0])})))throw new TypeError("array values (".concat(e,") must have the same type (types: ").concat(e.map((function(e){return gn(e)})).join(","),")"));return i.ScVal.scvVec(e.map((function(e){return vn(e,t)})))}if("Object"!==(null!==(r=null===(n=e.constructor)||void 0===n?void 0:n.name)&&void 0!==r?r:""))throw new TypeError("cannot interpret ".concat(null===(o=e.constructor)||void 0===o?void 0:o.name," value as ScVal (").concat(JSON.stringify(e),")"));return i.ScVal.scvMap(Object.entries(e).sort((function(e,t){var r=yn(e,1)[0],n=yn(t,1)[0];return r.localeCompare(n)})).map((function(e){var r,n,o=yn(e,2),a=o[0],s=o[1],u=yn(null!==(r=(null!==(n=null==t?void 0:t.type)&&void 0!==n?n:{})[a])&&void 0!==r?r:[null,null],2),c=u[0],l=u[1],f=c?{type:c}:{},p=l?{type:l}:{};return new i.ScMapEntry({key:vn(a,f),val:vn(s,p)})})));case"number":case"bigint":switch(null==t?void 0:t.type){case"u32":return i.ScVal.scvU32(e);case"i32":return i.ScVal.scvI32(e)}return new pn(e,{type:null==t?void 0:t.type}).toScVal();case"string":var u,c=null!==(u=null==t?void 0:t.type)&&void 0!==u?u:"string";switch(c){case"string":return i.ScVal.scvString(e);case"symbol":return i.ScVal.scvSymbol(e);case"address":return new Ge(e).toScVal();case"u32":return i.ScVal.scvU32(parseInt(e,10));case"i32":return i.ScVal.scvI32(parseInt(e,10));default:if(nn.isType(c))return new nn(c,e).toScVal();throw new TypeError("invalid type (".concat(t.type,") specified for string value"))}case"boolean":return i.ScVal.scvBool(e);case"undefined":return i.ScVal.scvVoid();case"function":return vn(e());default:throw new TypeError("failed to convert typeof ".concat(gn(e)," (").concat(e,")"))}}function bn(e){var t,r;switch(e.switch().value){case i.ScValType.scvVoid().value:return null;case i.ScValType.scvU64().value:case i.ScValType.scvI64().value:return e.value().toBigInt();case i.ScValType.scvU128().value:case i.ScValType.scvI128().value:case i.ScValType.scvU256().value:case i.ScValType.scvI256().value:return hn(e);case i.ScValType.scvVec().value:return(null!==(t=e.vec())&&void 0!==t?t:[]).map(bn);case i.ScValType.scvAddress().value:return Ge.fromScVal(e).toString();case i.ScValType.scvMap().value:return Object.fromEntries((null!==(r=e.map())&&void 0!==r?r:[]).map((function(e){return[bn(e.key()),bn(e.val())]})));case i.ScValType.scvBool().value:case i.ScValType.scvU32().value:case i.ScValType.scvI32().value:case i.ScValType.scvBytes().value:return e.value();case i.ScValType.scvSymbol().value:case i.ScValType.scvString().value:var n=e.value();if(dn.isBuffer(n)||ArrayBuffer.isView(n))try{return(new TextDecoder).decode(n)}catch(e){return new Uint8Array(n.buffer)}return n;case i.ScValType.scvTimepoint().value:case i.ScValType.scvDuration().value:return new i.Uint64(e.value()).toBigInt();case i.ScValType.scvError().value:if(e.error().switch().value===i.ScErrorType.sceContract().value)return{type:"contract",code:e.error().contractCode()};var o=e.error();return{type:"system",code:o.code().value,value:o.code().name};default:return e.value()}}function wn(e){return wn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},wn(e)}function Sn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function kn(e){for(var t=1;t=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),I(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;I(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:_(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function In(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function Bn(e,t,r){return _n.apply(this,arguments)}function _n(){var e;return e=xn().mark((function e(t,r,n){var o,a,s,c,l,f,p,h,d,y=arguments;return xn().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(o=y.length>3&&void 0!==y[3]?y[3]:lr.FUTURENET,t.credentials().switch().value===i.SorobanCredentialsType.sorobanCredentialsAddress().value){e.next=3;break}return e.abrupt("return",t);case 3:if(a=i.SorobanAuthorizationEntry.fromXDR(t.toXDR()),(s=a.credentials().address()).signatureExpirationLedger(n),c=u(On.from(o)),l=i.HashIdPreimage.envelopeTypeSorobanAuthorization(new i.HashIdPreimageSorobanAuthorization({networkId:c,nonce:s.nonce(),invocation:a.rootInvocation(),signatureExpirationLedger:s.signatureExpirationLedger()})),f=u(l.toXDR()),"function"!=typeof r){e.next=18;break}return e.t0=On,e.next=13,r(l);case 13:e.t1=e.sent,p=e.t0.from.call(e.t0,e.t1),h=Ge.fromScAddress(s.address()).toString(),e.next=20;break;case 18:p=On.from(r.sign(f)),h=r.publicKey();case 20:if(U.fromPublicKey(h).verify(f,p)){e.next=22;break}throw new Error("signature doesn't match payload");case 22:return d=vn({public_key:T.decodeEd25519PublicKey(h),signature:p},{type:{public_key:["symbol",null],signature:["symbol",null]}}),s.signature(i.ScVal.scvVec([d])),e.abrupt("return",a);case 25:case"end":return e.stop()}}),e)})),_n=function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){In(i,n,o,a,s,"next",e)}function s(e){In(i,n,o,a,s,"throw",e)}a(void 0)}))},_n.apply(this,arguments)}function Rn(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:lr.FUTURENET,a=U.random().rawPublicKey(),s=new i.Int64(a.subarray(0,8).reduce((function(e,t){return e<<8|t}),0)),u=n||e.publicKey();if(!u)throw new Error("authorizeInvocation requires publicKey parameter");return Bn(new i.SorobanAuthorizationEntry({rootInvocation:r,credentials:i.SorobanCredentials.sorobanCredentialsAddress(new i.SorobanAddressCredentials({address:new Ge(u).toScAddress(),nonce:s,signatureExpirationLedger:0,signature:i.ScVal.scvVec([])}))}),e,t,o)}function Cn(e){return Cn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Cn(e)}function Un(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Nn(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=Cn(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=Cn(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==Cn(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Ln(e){var t=e.function(),r={},n=t.value();switch(t.switch().value){case 0:r.type="execute",r.args={source:Ge.fromScAddress(n.contractAddress()).toString(),function:n.functionName(),args:n.args().map((function(e){return bn(e)}))};break;case 1:case 2:var o=2===t.switch().value;r.type="create",r.args={};var i=[n.executable(),n.contractIdPreimage()],a=i[0],s=i[1];if(!!a.switch().value!=!!s.switch().value)throw new Error("creation function appears invalid: ".concat(JSON.stringify(n)," (should be wasm+address or token+asset)"));switch(a.switch().value){case 0:var u=s.fromAddress();r.args.type="wasm",r.args.wasm=function(e){for(var t=1;t{"use strict";var r=function(e,t){return t||(t={}),e.split("").forEach((function(e,r){e in t||(t[e]=r)})),t},n={alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",charmap:{0:14,1:8}};n.charmap=r(n.alphabet,n.charmap);var o={alphabet:"0123456789ABCDEFGHJKMNPQRSTVWXYZ",charmap:{O:0,I:1,L:1}};o.charmap=r(o.alphabet,o.charmap);var i={alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",charmap:{}};function a(e){if(this.buf=[],this.shift=8,this.carry=0,e){switch(e.type){case"rfc4648":this.charmap=t.rfc4648.charmap;break;case"crockford":this.charmap=t.crockford.charmap;break;case"base32hex":this.charmap=t.base32hex.charmap;break;default:throw new Error("invalid type")}e.charmap&&(this.charmap=e.charmap)}}function s(e){if(this.buf="",this.shift=3,this.carry=0,e){switch(e.type){case"rfc4648":this.alphabet=t.rfc4648.alphabet;break;case"crockford":this.alphabet=t.crockford.alphabet;break;case"base32hex":this.alphabet=t.base32hex.alphabet;break;default:throw new Error("invalid type")}e.alphabet?this.alphabet=e.alphabet:e.lc&&(this.alphabet=this.alphabet.toLowerCase())}}i.charmap=r(i.alphabet,i.charmap),a.prototype.charmap=n.charmap,a.prototype.write=function(e){var t=this.charmap,r=this.buf,n=this.shift,o=this.carry;return e.toUpperCase().split("").forEach((function(e){if("="!=e){var i=255&t[e];(n-=5)>0?o|=i<>-n),o=i<<(n+=8)&255):(r.push(o|i),n=8,o=0)}})),this.shift=n,this.carry=o,this},a.prototype.finalize=function(e){return e&&this.write(e),8!==this.shift&&0!==this.carry&&(this.buf.push(this.carry),this.shift=8,this.carry=0),this.buf},s.prototype.alphabet=n.alphabet,s.prototype.write=function(e){var t,r,n,o=this.shift,i=this.carry;for(n=0;n>o,this.buf+=this.alphabet[31&t],o>5&&(t=r>>(o-=5),this.buf+=this.alphabet[31&t]),i=r<<(o=5-o),o=8-o;return this.shift=o,this.carry=i,this},s.prototype.finalize=function(e){return e&&this.write(e),3!==this.shift&&(this.buf+=this.alphabet[31&this.carry],this.shift=3,this.carry=0),this.buf},t.encode=function(e,t){return new s(t).finalize(e)},t.decode=function(e,t){return new a(t).finalize(e)},t.Decoder=a,t.Encoder=s,t.charmap=r,t.crockford=o,t.rfc4648=n,t.base32hex=i},7526:(e,t)=>{"use strict";t.byteLength=function(e){var t=s(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,i=s(e),a=i[0],u=i[1],c=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,u)),l=0,f=u>0?a-4:a;for(r=0;r>16&255,c[l++]=t>>8&255,c[l++]=255&t;2===u&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,c[l++]=255&t);1===u&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t);return c},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],a=16383,s=0,c=n-o;sc?c:s+a));1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return i.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)r[a]=i[a],n[i.charCodeAt(a)]=a;function s(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,n){for(var o,i,a=[],s=t;s>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return a.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},8287:(e,t,r)=>{"use strict";var n=r(6763);const o=r(7526),i=r(251),a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=c,t.SlowBuffer=function(e){+e!=e&&(e=0);return c.alloc(+e)},t.INSPECT_MAX_BYTES=50;const s=2147483647;function u(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,c.prototype),t}function c(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return p(e)}return l(e,t,r)}function l(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!c.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|m(e,t);let n=u(r);const o=n.write(e,t);o!==r&&(n=n.slice(0,o));return n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(Y(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Y(e,ArrayBuffer)||e&&Y(e.buffer,ArrayBuffer))return d(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(Y(e,SharedArrayBuffer)||e&&Y(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return c.from(n,t,r);const o=function(e){if(c.isBuffer(e)){const t=0|y(e.length),r=u(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||J(e.length)?u(0):h(e);if("Buffer"===e.type&&Array.isArray(e.data))return h(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return c.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function f(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function p(e){return f(e),u(e<0?0:0|y(e))}function h(e){const t=e.length<0?0:0|y(e.length),r=u(t);for(let n=0;n=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function m(e,t){if(c.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Y(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return $(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(o)return n?-1:$(e).length;t=(""+t).toLowerCase(),o=!0}}function g(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return _(this,t,r);case"utf8":case"utf-8":return P(this,t,r);case"ascii":return I(this,t,r);case"latin1":case"binary":return B(this,t,r);case"base64":return O(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function v(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function b(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),J(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=c.from(t,n)),c.isBuffer(t))return 0===t.length?-1:w(e,t,r,n,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):w(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function w(e,t,r,n,o){let i,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){let n=-1;for(i=r;is&&(r=s-u),i=r;i>=0;i--){let r=!0;for(let n=0;no&&(n=o):n=o;const i=t.length;let a;for(n>i/2&&(n=i/2),a=0;a>8,o=r%256,i.push(o),i.push(n);return i}(t,e.length-r),e,r,n)}function O(e,t,r){return 0===t&&r===e.length?o.fromByteArray(e):o.fromByteArray(e.slice(t,r))}function P(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o239?4:t>223?3:t>191?2:1;if(o+a<=r){let r,n,s,u;switch(a){case 1:t<128&&(i=t);break;case 2:r=e[o+1],128==(192&r)&&(u=(31&t)<<6|63&r,u>127&&(i=u));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(u=(15&t)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:r=e[o+1],n=e[o+2],s=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(u=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,u>65535&&u<1114112&&(i=u))}}null===i?(i=65533,a=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),o+=a}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(c.isBuffer(t)||(t=c.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!c.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},c.byteLength=m,c.prototype._isBuffer=!0,c.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(e+=" ... "),""},a&&(c.prototype[a]=c.prototype.inspect),c.prototype.compare=function(e,t,r,n,o){if(Y(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),!c.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let i=(o>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0);const s=Math.min(i,a),u=this.slice(n,o),l=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let i=!1;for(;;)switch(n){case"hex":return S(this,e,t,r);case"utf8":case"utf-8":return k(this,e,t,r);case"ascii":case"latin1":case"binary":return E(this,e,t,r);case"base64":return A(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function I(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;on)&&(r=n);let o="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function U(e,t,r,n,o,i){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function N(e,t,r,n,o){K(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function L(e,t,r,n,o){K(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r+7]=i,i>>=8,e[r+6]=i,i>>=8,e[r+5]=i,i>>=8,e[r+4]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function M(e,t,r,n,o,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function j(e,t,r,n,o){return t=+t,r>>>=0,o||M(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function F(e,t,r,n,o){return t=+t,r>>>=0,o||M(e,0,r,8),i.write(e,t,r,n,52,8),r+8}c.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e+--t],o=1;for(;t>0&&(o*=256);)n+=this[e+--t]*o;return n},c.prototype.readUint8=c.prototype.readUInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),this[e]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUint32BE=c.prototype.readUInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readBigUInt64LE=Q((function(e){H(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(o)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i=o&&(n-=Math.pow(2,8*t)),n},c.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=t,o=1,i=this[e+--n];for(;n>0&&(o*=256);)i+=this[e+--n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},c.prototype.readInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readBigInt64LE=Q((function(e){H(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||z(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||C(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||C(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||C(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||C(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUintLE=c.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){U(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=1,i=0;for(this[t]=255&e;++i>>=0,r>>>=0,!n){U(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=r-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+r},c.prototype.writeUint8=c.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,1,255,0),this[t]=255&e,t+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigUInt64LE=Q((function(e,t=0){return N(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeBigUInt64BE=Q((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);U(this,e,t,r,n-1,-n)}let o=0,i=1,a=0;for(this[t]=255&e;++o>>=0,!n){const n=Math.pow(2,8*r-1);U(this,e,t,r,n-1,-n)}let o=r-1,i=1,a=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/i|0)-a&255;return t+r},c.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},c.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||U(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigInt64LE=Q((function(e,t=0){return N(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeBigInt64BE=Q((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeFloatLE=function(e,t,r){return j(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return j(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return F(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return F(this,e,t,!1,r)},c.prototype.copy=function(e,t,r,n){if(!c.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function K(e,t,r,n,o,i){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new D.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){H(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||z(t,e.length-(r+1))}(n,o,i)}function H(e,t){if("number"!=typeof e)throw new D.ERR_INVALID_ARG_TYPE(t,"number",e)}function z(e,t,r){if(Math.floor(e)!==e)throw H(e,r),new D.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new D.ERR_BUFFER_OUT_OF_BOUNDS;throw new D.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}V("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),V("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),V("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=q(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=q(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const X=/[^+/0-9A-Za-z-_]/g;function $(e,t){let r;t=t||1/0;const n=e.length;let o=null;const i=[];for(let a=0;a55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function G(e){return o.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(X,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function W(e,t,r,n){let o;for(o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function Y(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function J(e){return e!=e}const Z=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let o=0;o<16;++o)t[n+o]=e[r]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?ee:e}function ee(){throw new Error("BigInt not supported")}},8075:(e,t,r)=>{"use strict";var n=r(453),o=r(487),i=o(n("String.prototype.indexOf"));e.exports=function(e,t){var r=n(e,!!t);return"function"==typeof r&&i(e,".prototype.")>-1?o(r):r}},487:(e,t,r)=>{"use strict";var n=r(6743),o=r(453),i=r(6897),a=r(9675),s=o("%Function.prototype.apply%"),u=o("%Function.prototype.call%"),c=o("%Reflect.apply%",!0)||n.call(u,s),l=r(655),f=o("%Math.max%");e.exports=function(e){if("function"!=typeof e)throw new a("a function is required");var t=c(n,u,arguments);return i(t,1+f(0,e.length-(arguments.length-1)),!0)};var p=function(){return c(n,s,arguments)};l?l(e.exports,"apply",{value:p}):e.exports.apply=p},6763:(e,t,r)=>{var n=r(537),o=r(4148);function i(){return(new Date).getTime()}var a,s=Array.prototype.slice,u={};a=void 0!==r.g&&r.g.console?r.g.console:"undefined"!=typeof window&&window.console?window.console:{};for(var c=[[function(){},"log"],[function(){a.log.apply(a,arguments)},"info"],[function(){a.log.apply(a,arguments)},"warn"],[function(){a.warn.apply(a,arguments)},"error"],[function(e){u[e]=i()},"time"],[function(e){var t=u[e];if(!t)throw new Error("No such label: "+e);delete u[e];var r=i()-t;a.log(e+": "+r+"ms")},"timeEnd"],[function(){var e=new Error;e.name="Trace",e.message=n.format.apply(null,arguments),a.error(e.stack)},"trace"],[function(e){a.log(n.inspect(e)+"\n")},"dir"],[function(e){if(!e){var t=s.call(arguments,1);o.ok(!1,n.format.apply(null,t))}},"assert"]],l=0;l{"use strict";var n=r(655),o=r(8068),i=r(9675),a=r(5795);e.exports=function(e,t,r){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new i("`obj` must be an object or a function`");if("string"!=typeof t&&"symbol"!=typeof t)throw new i("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new i("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new i("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new i("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new i("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,u=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,l=arguments.length>6&&arguments[6],f=!!a&&a(e,t);if(n)n(e,t,{configurable:null===c&&f?f.configurable:!c,enumerable:null===s&&f?f.enumerable:!s,value:r,writable:null===u&&f?f.writable:!u});else{if(!l&&(s||u||c))throw new o("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");e[t]=r}}},8452:(e,t,r)=>{"use strict";var n=r(1189),o="function"==typeof Symbol&&"symbol"==typeof Symbol("foo"),i=Object.prototype.toString,a=Array.prototype.concat,s=r(41),u=r(592)(),c=function(e,t,r,n){if(t in e)if(!0===n){if(e[t]===r)return}else if("function"!=typeof(o=n)||"[object Function]"!==i.call(o)||!n())return;var o;u?s(e,t,r,!0):s(e,t,r)},l=function(e,t){var r=arguments.length>2?arguments[2]:{},i=n(t);o&&(i=a.call(i,Object.getOwnPropertySymbols(t)));for(var s=0;s{"use strict";var n=r(453)("%Object.defineProperty%",!0)||!1;if(n)try{n({},"a",{value:1})}catch(e){n=!1}e.exports=n},1237:e=>{"use strict";e.exports=EvalError},9383:e=>{"use strict";e.exports=Error},9290:e=>{"use strict";e.exports=RangeError},9538:e=>{"use strict";e.exports=ReferenceError},8068:e=>{"use strict";e.exports=SyntaxError},9675:e=>{"use strict";e.exports=TypeError},5345:e=>{"use strict";e.exports=URIError},2682:(e,t,r)=>{"use strict";var n=r(9600),o=Object.prototype.toString,i=Object.prototype.hasOwnProperty;e.exports=function(e,t,r){if(!n(t))throw new TypeError("iterator must be a function");var a;arguments.length>=3&&(a=r),"[object Array]"===o.call(e)?function(e,t,r){for(var n=0,o=e.length;n{"use strict";var t=Object.prototype.toString,r=Math.max,n=function(e,t){for(var r=[],n=0;n{"use strict";var n=r(9353);e.exports=Function.prototype.bind||n},453:(e,t,r)=>{"use strict";var n,o=r(9383),i=r(1237),a=r(9290),s=r(9538),u=r(8068),c=r(9675),l=r(5345),f=Function,p=function(e){try{return f('"use strict"; return ('+e+").constructor;")()}catch(e){}},h=Object.getOwnPropertyDescriptor;if(h)try{h({},"")}catch(e){h=null}var d=function(){throw new c},y=h?function(){try{return d}catch(e){try{return h(arguments,"callee").get}catch(e){return d}}}():d,m=r(4039)(),g=r(24)(),v=Object.getPrototypeOf||(g?function(e){return e.__proto__}:null),b={},w="undefined"!=typeof Uint8Array&&v?v(Uint8Array):n,S={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?n:ArrayBuffer,"%ArrayIteratorPrototype%":m&&v?v([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":b,"%AsyncGenerator%":b,"%AsyncGeneratorFunction%":b,"%AsyncIteratorPrototype%":b,"%Atomics%":"undefined"==typeof Atomics?n:Atomics,"%BigInt%":"undefined"==typeof BigInt?n:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?n:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":o,"%eval%":eval,"%EvalError%":i,"%Float32Array%":"undefined"==typeof Float32Array?n:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?n:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?n:FinalizationRegistry,"%Function%":f,"%GeneratorFunction%":b,"%Int8Array%":"undefined"==typeof Int8Array?n:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?n:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":m&&v?v(v([][Symbol.iterator]())):n,"%JSON%":"object"==typeof JSON?JSON:n,"%Map%":"undefined"==typeof Map?n:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&m&&v?v((new Map)[Symbol.iterator]()):n,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?n:Promise,"%Proxy%":"undefined"==typeof Proxy?n:Proxy,"%RangeError%":a,"%ReferenceError%":s,"%Reflect%":"undefined"==typeof Reflect?n:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?n:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&m&&v?v((new Set)[Symbol.iterator]()):n,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":m&&v?v(""[Symbol.iterator]()):n,"%Symbol%":m?Symbol:n,"%SyntaxError%":u,"%ThrowTypeError%":y,"%TypedArray%":w,"%TypeError%":c,"%Uint8Array%":"undefined"==typeof Uint8Array?n:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?n:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?n:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?n:Uint32Array,"%URIError%":l,"%WeakMap%":"undefined"==typeof WeakMap?n:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?n:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?n:WeakSet};if(v)try{null.error}catch(e){var k=v(v(e));S["%Error.prototype%"]=k}var E=function e(t){var r;if("%AsyncFunction%"===t)r=p("async function () {}");else if("%GeneratorFunction%"===t)r=p("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=p("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var o=e("%AsyncGenerator%");o&&v&&(r=v(o.prototype))}return S[t]=r,r},A={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},T=r(6743),O=r(9957),P=T.call(Function.call,Array.prototype.concat),x=T.call(Function.apply,Array.prototype.splice),I=T.call(Function.call,String.prototype.replace),B=T.call(Function.call,String.prototype.slice),_=T.call(Function.call,RegExp.prototype.exec),R=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,C=/\\(\\)?/g,U=function(e,t){var r,n=e;if(O(A,n)&&(n="%"+(r=A[n])[0]+"%"),O(S,n)){var o=S[n];if(o===b&&(o=E(n)),void 0===o&&!t)throw new c("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:o}}throw new u("intrinsic "+e+" does not exist!")};e.exports=function(e,t){if("string"!=typeof e||0===e.length)throw new c("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new c('"allowMissing" argument must be a boolean');if(null===_(/^%?[^%]*%?$/,e))throw new u("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=function(e){var t=B(e,0,1),r=B(e,-1);if("%"===t&&"%"!==r)throw new u("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new u("invalid intrinsic syntax, expected opening `%`");var n=[];return I(e,R,(function(e,t,r,o){n[n.length]=r?I(o,C,"$1"):t||e})),n}(e),n=r.length>0?r[0]:"",o=U("%"+n+"%",t),i=o.name,a=o.value,s=!1,l=o.alias;l&&(n=l[0],x(r,P([0,1],l)));for(var f=1,p=!0;f=r.length){var g=h(a,d);a=(p=!!g)&&"get"in g&&!("originalValue"in g.get)?g.get:a[d]}else p=O(a,d),a=a[d];p&&!s&&(S[i]=a)}}return a}},5795:(e,t,r)=>{"use strict";var n=r(453)("%Object.getOwnPropertyDescriptor%",!0);if(n)try{n([],"length")}catch(e){n=null}e.exports=n},592:(e,t,r)=>{"use strict";var n=r(655),o=function(){return!!n};o.hasArrayLengthDefineBug=function(){if(!n)return null;try{return 1!==n([],"length",{value:1}).length}catch(e){return!0}},e.exports=o},24:e=>{"use strict";var t={__proto__:null,foo:{}},r=Object;e.exports=function(){return{__proto__:t}.foo===t.foo&&!(t instanceof r)}},4039:(e,t,r)=>{"use strict";var n="undefined"!=typeof Symbol&&Symbol,o=r(1333);e.exports=function(){return"function"==typeof n&&("function"==typeof Symbol&&("symbol"==typeof n("foo")&&("symbol"==typeof Symbol("bar")&&o())))}},1333:e=>{"use strict";e.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var n=Object.getOwnPropertySymbols(e);if(1!==n.length||n[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var o=Object.getOwnPropertyDescriptor(e,t);if(42!==o.value||!0!==o.enumerable)return!1}return!0}},9092:(e,t,r)=>{"use strict";var n=r(1333);e.exports=function(){return n()&&!!Symbol.toStringTag}},9957:(e,t,r)=>{"use strict";var n=Function.prototype.call,o=Object.prototype.hasOwnProperty,i=r(6743);e.exports=i.call(n,o)},251:(e,t)=>{t.read=function(e,t,r,n,o){var i,a,s=8*o-n-1,u=(1<>1,l=-7,f=r?o-1:0,p=r?-1:1,h=e[t+f];for(f+=p,i=h&(1<<-l)-1,h>>=-l,l+=s;l>0;i=256*i+e[t+f],f+=p,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=p,l-=8);if(0===i)i=1-c;else{if(i===u)return a?NaN:1/0*(h?-1:1);a+=Math.pow(2,n),i-=c}return(h?-1:1)*a*Math.pow(2,i-n)},t.write=function(e,t,r,n,o,i){var a,s,u,c=8*i-o-1,l=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:i-1,d=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?p/u:p*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=l?(s=0,a=l):a+f>=1?(s=(t*u-1)*Math.pow(2,o),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,o),a=0));o>=8;e[r+h]=255&s,h+=d,s/=256,o-=8);for(a=a<0;e[r+h]=255&a,h+=d,a/=256,c-=8);e[r+h-d]|=128*y}},6698:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},7244:(e,t,r)=>{"use strict";var n=r(9092)(),o=r(8075)("Object.prototype.toString"),i=function(e){return!(n&&e&&"object"==typeof e&&Symbol.toStringTag in e)&&"[object Arguments]"===o(e)},a=function(e){return!!i(e)||null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==o(e)&&"[object Function]"===o(e.callee)},s=function(){return i(arguments)}();i.isLegacyArguments=a,e.exports=s?i:a},9600:e=>{"use strict";var t,r,n=Function.prototype.toString,o="object"==typeof Reflect&&null!==Reflect&&Reflect.apply;if("function"==typeof o&&"function"==typeof Object.defineProperty)try{t=Object.defineProperty({},"length",{get:function(){throw r}}),r={},o((function(){throw 42}),null,t)}catch(e){e!==r&&(o=null)}else o=null;var i=/^\s*class\b/,a=function(e){try{var t=n.call(e);return i.test(t)}catch(e){return!1}},s=function(e){try{return!a(e)&&(n.call(e),!0)}catch(e){return!1}},u=Object.prototype.toString,c="function"==typeof Symbol&&!!Symbol.toStringTag,l=!(0 in[,]),f=function(){return!1};if("object"==typeof document){var p=document.all;u.call(p)===u.call(document.all)&&(f=function(e){if((l||!e)&&(void 0===e||"object"==typeof e))try{var t=u.call(e);return("[object HTMLAllCollection]"===t||"[object HTML document.all class]"===t||"[object HTMLCollection]"===t||"[object Object]"===t)&&null==e("")}catch(e){}return!1})}e.exports=o?function(e){if(f(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;try{o(e,null,t)}catch(e){if(e!==r)return!1}return!a(e)&&s(e)}:function(e){if(f(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;if(c)return s(e);if(a(e))return!1;var t=u.call(e);return!("[object Function]"!==t&&"[object GeneratorFunction]"!==t&&!/^\[object HTML/.test(t))&&s(e)}},8184:(e,t,r)=>{"use strict";var n,o=Object.prototype.toString,i=Function.prototype.toString,a=/^\s*(?:function)?\*/,s=r(9092)(),u=Object.getPrototypeOf;e.exports=function(e){if("function"!=typeof e)return!1;if(a.test(i.call(e)))return!0;if(!s)return"[object GeneratorFunction]"===o.call(e);if(!u)return!1;if(void 0===n){var t=function(){if(!s)return!1;try{return Function("return function*() {}")()}catch(e){}}();n=!!t&&u(t)}return u(e)===n}},3003:e=>{"use strict";e.exports=function(e){return e!=e}},4133:(e,t,r)=>{"use strict";var n=r(487),o=r(8452),i=r(3003),a=r(6642),s=r(2464),u=n(a(),Number);o(u,{getPolyfill:a,implementation:i,shim:s}),e.exports=u},6642:(e,t,r)=>{"use strict";var n=r(3003);e.exports=function(){return Number.isNaN&&Number.isNaN(NaN)&&!Number.isNaN("a")?Number.isNaN:n}},2464:(e,t,r)=>{"use strict";var n=r(8452),o=r(6642);e.exports=function(){var e=o();return n(Number,{isNaN:e},{isNaN:function(){return Number.isNaN!==e}}),e}},5680:(e,t,r)=>{"use strict";var n=r(5767);e.exports=function(e){return!!n(e)}},9211:e=>{"use strict";var t=function(e){return e!=e};e.exports=function(e,r){return 0===e&&0===r?1/e==1/r:e===r||!(!t(e)||!t(r))}},7653:(e,t,r)=>{"use strict";var n=r(8452),o=r(487),i=r(9211),a=r(9394),s=r(6576),u=o(a(),Object);n(u,{getPolyfill:a,implementation:i,shim:s}),e.exports=u},9394:(e,t,r)=>{"use strict";var n=r(9211);e.exports=function(){return"function"==typeof Object.is?Object.is:n}},6576:(e,t,r)=>{"use strict";var n=r(9394),o=r(8452);e.exports=function(){var e=n();return o(Object,{is:e},{is:function(){return Object.is!==e}}),e}},8875:(e,t,r)=>{"use strict";var n;if(!Object.keys){var o=Object.prototype.hasOwnProperty,i=Object.prototype.toString,a=r(1093),s=Object.prototype.propertyIsEnumerable,u=!s.call({toString:null},"toString"),c=s.call((function(){}),"prototype"),l=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],f=function(e){var t=e.constructor;return t&&t.prototype===e},p={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},h=function(){if("undefined"==typeof window)return!1;for(var e in window)try{if(!p["$"+e]&&o.call(window,e)&&null!==window[e]&&"object"==typeof window[e])try{f(window[e])}catch(e){return!0}}catch(e){return!0}return!1}();n=function(e){var t=null!==e&&"object"==typeof e,r="[object Function]"===i.call(e),n=a(e),s=t&&"[object String]"===i.call(e),p=[];if(!t&&!r&&!n)throw new TypeError("Object.keys called on a non-object");var d=c&&r;if(s&&e.length>0&&!o.call(e,0))for(var y=0;y0)for(var m=0;m{"use strict";var n=Array.prototype.slice,o=r(1093),i=Object.keys,a=i?function(e){return i(e)}:r(8875),s=Object.keys;a.shim=function(){if(Object.keys){var e=function(){var e=Object.keys(arguments);return e&&e.length===arguments.length}(1,2);e||(Object.keys=function(e){return o(e)?s(n.call(e)):s(e)})}else Object.keys=a;return Object.keys||a},e.exports=a},1093:e=>{"use strict";var t=Object.prototype.toString;e.exports=function(e){var r=t.call(e),n="[object Arguments]"===r;return n||(n="[object Array]"!==r&&null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Function]"===t.call(e.callee)),n}},8403:(e,t,r)=>{"use strict";var n=r(1189),o=r(1333)(),i=r(8075),a=Object,s=i("Array.prototype.push"),u=i("Object.prototype.propertyIsEnumerable"),c=o?Object.getOwnPropertySymbols:null;e.exports=function(e,t){if(null==e)throw new TypeError("target must be an object");var r=a(e);if(1===arguments.length)return r;for(var i=1;i{"use strict";var n=r(8403);e.exports=function(){return Object.assign?function(){if(!Object.assign)return!1;for(var e="abcdefghijklmnopqrst",t=e.split(""),r={},n=0;n{"use strict";e.exports=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]},5606:e=>{var t,r,n=e.exports={};function o(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function a(e){if(t===setTimeout)return setTimeout(e,0);if((t===o||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:o}catch(e){t=o}try{r="function"==typeof clearTimeout?clearTimeout:i}catch(e){r=i}}();var s,u=[],c=!1,l=-1;function f(){c&&s&&(c=!1,s.length?u=s.concat(u):l=-1,u.length&&p())}function p(){if(!c){var e=a(f);c=!0;for(var t=u.length;t;){for(s=u,u=[];++l1)for(var r=1;r{var n=r(8287),o=n.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return o(e,t,r)}o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=a),a.prototype=Object.create(o.prototype),i(o,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=o(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},6897:(e,t,r)=>{"use strict";var n=r(453),o=r(41),i=r(592)(),a=r(5795),s=r(9675),u=n("%Math.floor%");e.exports=function(e,t){if("function"!=typeof e)throw new s("`fn` is not a function");if("number"!=typeof t||t<0||t>4294967295||u(t)!==t)throw new s("`length` must be a positive 32-bit integer");var r=arguments.length>2&&!!arguments[2],n=!0,c=!0;if("length"in e&&a){var l=a(e,"length");l&&!l.configurable&&(n=!1),l&&!l.writable&&(c=!1)}return(n||c||!r)&&(i?o(e,"length",t,!0,!0):o(e,"length",t)),e}},392:(e,t,r)=>{var n=r(2861).Buffer;function o(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}o.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=n.from(e,t));for(var r=this._block,o=this._blockSize,i=e.length,a=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,o=(r-n)/4294967296;this._block.writeUInt32BE(o,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var i=this._hash();return e?i.toString(e):i},o.prototype._update=function(){throw new Error("_update must be implemented by subclass")},e.exports=o},2802:(e,t,r)=>{var n=e.exports=function(e){e=e.toLowerCase();var t=n[e];if(!t)throw new Error(e+" is not supported (we accept pull requests)");return new t};n.sha=r(7816),n.sha1=r(3737),n.sha224=r(6710),n.sha256=r(4107),n.sha384=r(2827),n.sha512=r(2890)},7816:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,o.call(this,64,56)}function c(e){return e<<30|e>>>2}function l(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,o),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,s=0|this._d,u=0|this._e,f=0;f<16;++f)r[f]=e.readInt32BE(4*f);for(;f<80;++f)r[f]=r[f-3]^r[f-8]^r[f-14]^r[f-16];for(var p=0;p<80;++p){var h=~~(p/20),d=0|((t=n)<<5|t>>>27)+l(h,o,i,s)+u+r[p]+a[h];u=s,s=i,i=c(o),o=n,n=d}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},e.exports=u},3737:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,o.call(this,64,56)}function c(e){return e<<5|e>>>27}function l(e){return e<<30|e>>>2}function f(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,o),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,s=0|this._d,u=0|this._e,p=0;p<16;++p)r[p]=e.readInt32BE(4*p);for(;p<80;++p)r[p]=(t=r[p-3]^r[p-8]^r[p-14]^r[p-16])<<1|t>>>31;for(var h=0;h<80;++h){var d=~~(h/20),y=c(n)+f(d,o,i,s)+u+r[h]+a[d]|0;u=s,s=i,i=l(o),o=n,n=y}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},e.exports=u},6710:(e,t,r)=>{var n=r(6698),o=r(4107),i=r(392),a=r(2861).Buffer,s=new Array(64);function u(){this.init(),this._w=s,i.call(this,64,56)}n(u,o),u.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e},e.exports=u},4107:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],s=new Array(64);function u(){this.init(),this._w=s,o.call(this,64,56)}function c(e,t,r){return r^e&(t^r)}function l(e,t,r){return e&t|r&(e|t)}function f(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function p(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function h(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}n(u,o),u.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,s=0|this._d,u=0|this._e,d=0|this._f,y=0|this._g,m=0|this._h,g=0;g<16;++g)r[g]=e.readInt32BE(4*g);for(;g<64;++g)r[g]=0|(((t=r[g-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+r[g-7]+h(r[g-15])+r[g-16];for(var v=0;v<64;++v){var b=m+p(u)+c(u,d,y)+a[v]+r[v]|0,w=f(n)+l(n,o,i)|0;m=y,y=d,d=u,u=s+b|0,s=i,i=o,o=n,n=b+w|0}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0,this._f=d+this._f|0,this._g=y+this._g|0,this._h=m+this._h|0},u.prototype._hash=function(){var e=i.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},e.exports=u},2827:(e,t,r)=>{var n=r(6698),o=r(2890),i=r(392),a=r(2861).Buffer,s=new Array(160);function u(){this.init(),this._w=s,i.call(this,128,112)}n(u,o),u.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(48);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},e.exports=u},2890:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],s=new Array(160);function u(){this.init(),this._w=s,o.call(this,128,112)}function c(e,t,r){return r^e&(t^r)}function l(e,t,r){return e&t|r&(e|t)}function f(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function p(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function h(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function d(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function y(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function m(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function g(e,t){return e>>>0>>0?1:0}n(u,o),u.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},u.prototype._update=function(e){for(var t=this._w,r=0|this._ah,n=0|this._bh,o=0|this._ch,i=0|this._dh,s=0|this._eh,u=0|this._fh,v=0|this._gh,b=0|this._hh,w=0|this._al,S=0|this._bl,k=0|this._cl,E=0|this._dl,A=0|this._el,T=0|this._fl,O=0|this._gl,P=0|this._hl,x=0;x<32;x+=2)t[x]=e.readInt32BE(4*x),t[x+1]=e.readInt32BE(4*x+4);for(;x<160;x+=2){var I=t[x-30],B=t[x-30+1],_=h(I,B),R=d(B,I),C=y(I=t[x-4],B=t[x-4+1]),U=m(B,I),N=t[x-14],L=t[x-14+1],M=t[x-32],j=t[x-32+1],F=R+L|0,D=_+N+g(F,R)|0;D=(D=D+C+g(F=F+U|0,U)|0)+M+g(F=F+j|0,j)|0,t[x]=D,t[x+1]=F}for(var V=0;V<160;V+=2){D=t[V],F=t[V+1];var q=l(r,n,o),K=l(w,S,k),H=f(r,w),z=f(w,r),X=p(s,A),$=p(A,s),G=a[V],W=a[V+1],Y=c(s,u,v),J=c(A,T,O),Z=P+$|0,Q=b+X+g(Z,P)|0;Q=(Q=(Q=Q+Y+g(Z=Z+J|0,J)|0)+G+g(Z=Z+W|0,W)|0)+D+g(Z=Z+F|0,F)|0;var ee=z+K|0,te=H+q+g(ee,z)|0;b=v,P=O,v=u,O=T,u=s,T=A,s=i+Q+g(A=E+Z|0,E)|0,i=o,E=k,o=n,k=S,n=r,S=w,r=Q+te+g(w=Z+ee|0,Z)|0}this._al=this._al+w|0,this._bl=this._bl+S|0,this._cl=this._cl+k|0,this._dl=this._dl+E|0,this._el=this._el+A|0,this._fl=this._fl+T|0,this._gl=this._gl+O|0,this._hl=this._hl+P|0,this._ah=this._ah+r+g(this._al,w)|0,this._bh=this._bh+n+g(this._bl,S)|0,this._ch=this._ch+o+g(this._cl,k)|0,this._dh=this._dh+i+g(this._dl,E)|0,this._eh=this._eh+s+g(this._el,A)|0,this._fh=this._fh+u+g(this._fl,T)|0,this._gh=this._gh+v+g(this._gl,O)|0,this._hh=this._hh+b+g(this._hl,P)|0},u.prototype._hash=function(){var e=i.allocUnsafe(64);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},e.exports=u},8947:(e,t,r)=>{!function(e){"use strict";var t=function(e){var t,r=new Float64Array(16);if(e)for(t=0;t>24&255,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r,e[t+4]=n>>24&255,e[t+5]=n>>16&255,e[t+6]=n>>8&255,e[t+7]=255&n}function y(e,t,r,n,o){var i,a=0;for(i=0;i>>8)-1}function m(e,t,r,n){return y(e,t,r,n,16)}function g(e,t,r,n){return y(e,t,r,n,32)}function v(e,t,r,n){!function(e,t,r,n){for(var o,i=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,s=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,c=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,l=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,p=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,h=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,d=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,y=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,m=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,g=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,v=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,b=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,w=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,S=i,k=a,E=s,A=u,T=c,O=l,P=f,x=p,I=h,B=d,_=y,R=m,C=g,U=v,N=b,L=w,M=0;M<20;M+=2)S^=(o=(C^=(o=(I^=(o=(T^=(o=S+C|0)<<7|o>>>25)+S|0)<<9|o>>>23)+T|0)<<13|o>>>19)+I|0)<<18|o>>>14,O^=(o=(k^=(o=(U^=(o=(B^=(o=O+k|0)<<7|o>>>25)+O|0)<<9|o>>>23)+B|0)<<13|o>>>19)+U|0)<<18|o>>>14,_^=(o=(P^=(o=(E^=(o=(N^=(o=_+P|0)<<7|o>>>25)+_|0)<<9|o>>>23)+N|0)<<13|o>>>19)+E|0)<<18|o>>>14,L^=(o=(R^=(o=(x^=(o=(A^=(o=L+R|0)<<7|o>>>25)+L|0)<<9|o>>>23)+A|0)<<13|o>>>19)+x|0)<<18|o>>>14,S^=(o=(A^=(o=(E^=(o=(k^=(o=S+A|0)<<7|o>>>25)+S|0)<<9|o>>>23)+k|0)<<13|o>>>19)+E|0)<<18|o>>>14,O^=(o=(T^=(o=(x^=(o=(P^=(o=O+T|0)<<7|o>>>25)+O|0)<<9|o>>>23)+P|0)<<13|o>>>19)+x|0)<<18|o>>>14,_^=(o=(B^=(o=(I^=(o=(R^=(o=_+B|0)<<7|o>>>25)+_|0)<<9|o>>>23)+R|0)<<13|o>>>19)+I|0)<<18|o>>>14,L^=(o=(N^=(o=(U^=(o=(C^=(o=L+N|0)<<7|o>>>25)+L|0)<<9|o>>>23)+C|0)<<13|o>>>19)+U|0)<<18|o>>>14;S=S+i|0,k=k+a|0,E=E+s|0,A=A+u|0,T=T+c|0,O=O+l|0,P=P+f|0,x=x+p|0,I=I+h|0,B=B+d|0,_=_+y|0,R=R+m|0,C=C+g|0,U=U+v|0,N=N+b|0,L=L+w|0,e[0]=S>>>0&255,e[1]=S>>>8&255,e[2]=S>>>16&255,e[3]=S>>>24&255,e[4]=k>>>0&255,e[5]=k>>>8&255,e[6]=k>>>16&255,e[7]=k>>>24&255,e[8]=E>>>0&255,e[9]=E>>>8&255,e[10]=E>>>16&255,e[11]=E>>>24&255,e[12]=A>>>0&255,e[13]=A>>>8&255,e[14]=A>>>16&255,e[15]=A>>>24&255,e[16]=T>>>0&255,e[17]=T>>>8&255,e[18]=T>>>16&255,e[19]=T>>>24&255,e[20]=O>>>0&255,e[21]=O>>>8&255,e[22]=O>>>16&255,e[23]=O>>>24&255,e[24]=P>>>0&255,e[25]=P>>>8&255,e[26]=P>>>16&255,e[27]=P>>>24&255,e[28]=x>>>0&255,e[29]=x>>>8&255,e[30]=x>>>16&255,e[31]=x>>>24&255,e[32]=I>>>0&255,e[33]=I>>>8&255,e[34]=I>>>16&255,e[35]=I>>>24&255,e[36]=B>>>0&255,e[37]=B>>>8&255,e[38]=B>>>16&255,e[39]=B>>>24&255,e[40]=_>>>0&255,e[41]=_>>>8&255,e[42]=_>>>16&255,e[43]=_>>>24&255,e[44]=R>>>0&255,e[45]=R>>>8&255,e[46]=R>>>16&255,e[47]=R>>>24&255,e[48]=C>>>0&255,e[49]=C>>>8&255,e[50]=C>>>16&255,e[51]=C>>>24&255,e[52]=U>>>0&255,e[53]=U>>>8&255,e[54]=U>>>16&255,e[55]=U>>>24&255,e[56]=N>>>0&255,e[57]=N>>>8&255,e[58]=N>>>16&255,e[59]=N>>>24&255,e[60]=L>>>0&255,e[61]=L>>>8&255,e[62]=L>>>16&255,e[63]=L>>>24&255}(e,t,r,n)}function b(e,t,r,n){!function(e,t,r,n){for(var o,i=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,s=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,c=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,l=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,p=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,h=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,d=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,y=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,m=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,g=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,v=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,b=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,w=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,S=0;S<20;S+=2)i^=(o=(g^=(o=(h^=(o=(c^=(o=i+g|0)<<7|o>>>25)+i|0)<<9|o>>>23)+c|0)<<13|o>>>19)+h|0)<<18|o>>>14,l^=(o=(a^=(o=(v^=(o=(d^=(o=l+a|0)<<7|o>>>25)+l|0)<<9|o>>>23)+d|0)<<13|o>>>19)+v|0)<<18|o>>>14,y^=(o=(f^=(o=(s^=(o=(b^=(o=y+f|0)<<7|o>>>25)+y|0)<<9|o>>>23)+b|0)<<13|o>>>19)+s|0)<<18|o>>>14,w^=(o=(m^=(o=(p^=(o=(u^=(o=w+m|0)<<7|o>>>25)+w|0)<<9|o>>>23)+u|0)<<13|o>>>19)+p|0)<<18|o>>>14,i^=(o=(u^=(o=(s^=(o=(a^=(o=i+u|0)<<7|o>>>25)+i|0)<<9|o>>>23)+a|0)<<13|o>>>19)+s|0)<<18|o>>>14,l^=(o=(c^=(o=(p^=(o=(f^=(o=l+c|0)<<7|o>>>25)+l|0)<<9|o>>>23)+f|0)<<13|o>>>19)+p|0)<<18|o>>>14,y^=(o=(d^=(o=(h^=(o=(m^=(o=y+d|0)<<7|o>>>25)+y|0)<<9|o>>>23)+m|0)<<13|o>>>19)+h|0)<<18|o>>>14,w^=(o=(b^=(o=(v^=(o=(g^=(o=w+b|0)<<7|o>>>25)+w|0)<<9|o>>>23)+g|0)<<13|o>>>19)+v|0)<<18|o>>>14;e[0]=i>>>0&255,e[1]=i>>>8&255,e[2]=i>>>16&255,e[3]=i>>>24&255,e[4]=l>>>0&255,e[5]=l>>>8&255,e[6]=l>>>16&255,e[7]=l>>>24&255,e[8]=y>>>0&255,e[9]=y>>>8&255,e[10]=y>>>16&255,e[11]=y>>>24&255,e[12]=w>>>0&255,e[13]=w>>>8&255,e[14]=w>>>16&255,e[15]=w>>>24&255,e[16]=f>>>0&255,e[17]=f>>>8&255,e[18]=f>>>16&255,e[19]=f>>>24&255,e[20]=p>>>0&255,e[21]=p>>>8&255,e[22]=p>>>16&255,e[23]=p>>>24&255,e[24]=h>>>0&255,e[25]=h>>>8&255,e[26]=h>>>16&255,e[27]=h>>>24&255,e[28]=d>>>0&255,e[29]=d>>>8&255,e[30]=d>>>16&255,e[31]=d>>>24&255}(e,t,r,n)}var w=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function S(e,t,r,n,o,i,a){var s,u,c=new Uint8Array(16),l=new Uint8Array(64);for(u=0;u<16;u++)c[u]=0;for(u=0;u<8;u++)c[u]=i[u];for(;o>=64;){for(v(l,c,a,w),u=0;u<64;u++)e[t+u]=r[n+u]^l[u];for(s=1,u=8;u<16;u++)s=s+(255&c[u])|0,c[u]=255&s,s>>>=8;o-=64,t+=64,n+=64}if(o>0)for(v(l,c,a,w),u=0;u=64;){for(v(u,s,o,w),a=0;a<64;a++)e[t+a]=u[a];for(i=1,a=8;a<16;a++)i=i+(255&s[a])|0,s[a]=255&i,i>>>=8;r-=64,t+=64}if(r>0)for(v(u,s,o,w),a=0;a>>13|r<<3),n=255&e[4]|(255&e[5])<<8,this.r[2]=7939&(r>>>10|n<<6),o=255&e[6]|(255&e[7])<<8,this.r[3]=8191&(n>>>7|o<<9),i=255&e[8]|(255&e[9])<<8,this.r[4]=255&(o>>>4|i<<12),this.r[5]=i>>>1&8190,a=255&e[10]|(255&e[11])<<8,this.r[6]=8191&(i>>>14|a<<2),s=255&e[12]|(255&e[13])<<8,this.r[7]=8065&(a>>>11|s<<5),u=255&e[14]|(255&e[15])<<8,this.r[8]=8191&(s>>>8|u<<8),this.r[9]=u>>>5&127,this.pad[0]=255&e[16]|(255&e[17])<<8,this.pad[1]=255&e[18]|(255&e[19])<<8,this.pad[2]=255&e[20]|(255&e[21])<<8,this.pad[3]=255&e[22]|(255&e[23])<<8,this.pad[4]=255&e[24]|(255&e[25])<<8,this.pad[5]=255&e[26]|(255&e[27])<<8,this.pad[6]=255&e[28]|(255&e[29])<<8,this.pad[7]=255&e[30]|(255&e[31])<<8};function O(e,t,r,n,o,i){var a=new T(i);return a.update(r,n,o),a.finish(e,t),0}function P(e,t,r,n,o,i){var a=new Uint8Array(16);return O(a,0,r,n,o,i),m(e,t,a,0)}function x(e,t,r,n,o){var i;if(r<32)return-1;for(A(e,0,t,0,r,n,o),O(e,16,e,32,r-32,e),i=0;i<16;i++)e[i]=0;return 0}function I(e,t,r,n,o){var i,a=new Uint8Array(32);if(r<32)return-1;if(E(a,0,32,n,o),0!==P(t,16,t,32,r-32,a))return-1;for(A(e,0,t,0,r,n,o),i=0;i<32;i++)e[i]=0;return 0}function B(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function _(e){var t,r,n=1;for(t=0;t<16;t++)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function R(e,t,r){for(var n,o=~(r-1),i=0;i<16;i++)n=o&(e[i]^t[i]),e[i]^=n,t[i]^=n}function C(e,r){var n,o,i,a=t(),s=t();for(n=0;n<16;n++)s[n]=r[n];for(_(s),_(s),_(s),o=0;o<2;o++){for(a[0]=s[0]-65517,n=1;n<15;n++)a[n]=s[n]-65535-(a[n-1]>>16&1),a[n-1]&=65535;a[15]=s[15]-32767-(a[14]>>16&1),i=a[15]>>16&1,a[14]&=65535,R(s,a,1-i)}for(n=0;n<16;n++)e[2*n]=255&s[n],e[2*n+1]=s[n]>>8}function U(e,t){var r=new Uint8Array(32),n=new Uint8Array(32);return C(r,e),C(n,t),g(r,0,n,0)}function N(e){var t=new Uint8Array(32);return C(t,e),1&t[0]}function L(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function M(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]+r[n]}function j(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]-r[n]}function F(e,t,r){var n,o,i=0,a=0,s=0,u=0,c=0,l=0,f=0,p=0,h=0,d=0,y=0,m=0,g=0,v=0,b=0,w=0,S=0,k=0,E=0,A=0,T=0,O=0,P=0,x=0,I=0,B=0,_=0,R=0,C=0,U=0,N=0,L=r[0],M=r[1],j=r[2],F=r[3],D=r[4],V=r[5],q=r[6],K=r[7],H=r[8],z=r[9],X=r[10],$=r[11],G=r[12],W=r[13],Y=r[14],J=r[15];i+=(n=t[0])*L,a+=n*M,s+=n*j,u+=n*F,c+=n*D,l+=n*V,f+=n*q,p+=n*K,h+=n*H,d+=n*z,y+=n*X,m+=n*$,g+=n*G,v+=n*W,b+=n*Y,w+=n*J,a+=(n=t[1])*L,s+=n*M,u+=n*j,c+=n*F,l+=n*D,f+=n*V,p+=n*q,h+=n*K,d+=n*H,y+=n*z,m+=n*X,g+=n*$,v+=n*G,b+=n*W,w+=n*Y,S+=n*J,s+=(n=t[2])*L,u+=n*M,c+=n*j,l+=n*F,f+=n*D,p+=n*V,h+=n*q,d+=n*K,y+=n*H,m+=n*z,g+=n*X,v+=n*$,b+=n*G,w+=n*W,S+=n*Y,k+=n*J,u+=(n=t[3])*L,c+=n*M,l+=n*j,f+=n*F,p+=n*D,h+=n*V,d+=n*q,y+=n*K,m+=n*H,g+=n*z,v+=n*X,b+=n*$,w+=n*G,S+=n*W,k+=n*Y,E+=n*J,c+=(n=t[4])*L,l+=n*M,f+=n*j,p+=n*F,h+=n*D,d+=n*V,y+=n*q,m+=n*K,g+=n*H,v+=n*z,b+=n*X,w+=n*$,S+=n*G,k+=n*W,E+=n*Y,A+=n*J,l+=(n=t[5])*L,f+=n*M,p+=n*j,h+=n*F,d+=n*D,y+=n*V,m+=n*q,g+=n*K,v+=n*H,b+=n*z,w+=n*X,S+=n*$,k+=n*G,E+=n*W,A+=n*Y,T+=n*J,f+=(n=t[6])*L,p+=n*M,h+=n*j,d+=n*F,y+=n*D,m+=n*V,g+=n*q,v+=n*K,b+=n*H,w+=n*z,S+=n*X,k+=n*$,E+=n*G,A+=n*W,T+=n*Y,O+=n*J,p+=(n=t[7])*L,h+=n*M,d+=n*j,y+=n*F,m+=n*D,g+=n*V,v+=n*q,b+=n*K,w+=n*H,S+=n*z,k+=n*X,E+=n*$,A+=n*G,T+=n*W,O+=n*Y,P+=n*J,h+=(n=t[8])*L,d+=n*M,y+=n*j,m+=n*F,g+=n*D,v+=n*V,b+=n*q,w+=n*K,S+=n*H,k+=n*z,E+=n*X,A+=n*$,T+=n*G,O+=n*W,P+=n*Y,x+=n*J,d+=(n=t[9])*L,y+=n*M,m+=n*j,g+=n*F,v+=n*D,b+=n*V,w+=n*q,S+=n*K,k+=n*H,E+=n*z,A+=n*X,T+=n*$,O+=n*G,P+=n*W,x+=n*Y,I+=n*J,y+=(n=t[10])*L,m+=n*M,g+=n*j,v+=n*F,b+=n*D,w+=n*V,S+=n*q,k+=n*K,E+=n*H,A+=n*z,T+=n*X,O+=n*$,P+=n*G,x+=n*W,I+=n*Y,B+=n*J,m+=(n=t[11])*L,g+=n*M,v+=n*j,b+=n*F,w+=n*D,S+=n*V,k+=n*q,E+=n*K,A+=n*H,T+=n*z,O+=n*X,P+=n*$,x+=n*G,I+=n*W,B+=n*Y,_+=n*J,g+=(n=t[12])*L,v+=n*M,b+=n*j,w+=n*F,S+=n*D,k+=n*V,E+=n*q,A+=n*K,T+=n*H,O+=n*z,P+=n*X,x+=n*$,I+=n*G,B+=n*W,_+=n*Y,R+=n*J,v+=(n=t[13])*L,b+=n*M,w+=n*j,S+=n*F,k+=n*D,E+=n*V,A+=n*q,T+=n*K,O+=n*H,P+=n*z,x+=n*X,I+=n*$,B+=n*G,_+=n*W,R+=n*Y,C+=n*J,b+=(n=t[14])*L,w+=n*M,S+=n*j,k+=n*F,E+=n*D,A+=n*V,T+=n*q,O+=n*K,P+=n*H,x+=n*z,I+=n*X,B+=n*$,_+=n*G,R+=n*W,C+=n*Y,U+=n*J,w+=(n=t[15])*L,a+=38*(k+=n*j),s+=38*(E+=n*F),u+=38*(A+=n*D),c+=38*(T+=n*V),l+=38*(O+=n*q),f+=38*(P+=n*K),p+=38*(x+=n*H),h+=38*(I+=n*z),d+=38*(B+=n*X),y+=38*(_+=n*$),m+=38*(R+=n*G),g+=38*(C+=n*W),v+=38*(U+=n*Y),b+=38*(N+=n*J),i=(n=(i+=38*(S+=n*M))+(o=1)+65535)-65536*(o=Math.floor(n/65536)),a=(n=a+o+65535)-65536*(o=Math.floor(n/65536)),s=(n=s+o+65535)-65536*(o=Math.floor(n/65536)),u=(n=u+o+65535)-65536*(o=Math.floor(n/65536)),c=(n=c+o+65535)-65536*(o=Math.floor(n/65536)),l=(n=l+o+65535)-65536*(o=Math.floor(n/65536)),f=(n=f+o+65535)-65536*(o=Math.floor(n/65536)),p=(n=p+o+65535)-65536*(o=Math.floor(n/65536)),h=(n=h+o+65535)-65536*(o=Math.floor(n/65536)),d=(n=d+o+65535)-65536*(o=Math.floor(n/65536)),y=(n=y+o+65535)-65536*(o=Math.floor(n/65536)),m=(n=m+o+65535)-65536*(o=Math.floor(n/65536)),g=(n=g+o+65535)-65536*(o=Math.floor(n/65536)),v=(n=v+o+65535)-65536*(o=Math.floor(n/65536)),b=(n=b+o+65535)-65536*(o=Math.floor(n/65536)),w=(n=w+o+65535)-65536*(o=Math.floor(n/65536)),i=(n=(i+=o-1+37*(o-1))+(o=1)+65535)-65536*(o=Math.floor(n/65536)),a=(n=a+o+65535)-65536*(o=Math.floor(n/65536)),s=(n=s+o+65535)-65536*(o=Math.floor(n/65536)),u=(n=u+o+65535)-65536*(o=Math.floor(n/65536)),c=(n=c+o+65535)-65536*(o=Math.floor(n/65536)),l=(n=l+o+65535)-65536*(o=Math.floor(n/65536)),f=(n=f+o+65535)-65536*(o=Math.floor(n/65536)),p=(n=p+o+65535)-65536*(o=Math.floor(n/65536)),h=(n=h+o+65535)-65536*(o=Math.floor(n/65536)),d=(n=d+o+65535)-65536*(o=Math.floor(n/65536)),y=(n=y+o+65535)-65536*(o=Math.floor(n/65536)),m=(n=m+o+65535)-65536*(o=Math.floor(n/65536)),g=(n=g+o+65535)-65536*(o=Math.floor(n/65536)),v=(n=v+o+65535)-65536*(o=Math.floor(n/65536)),b=(n=b+o+65535)-65536*(o=Math.floor(n/65536)),w=(n=w+o+65535)-65536*(o=Math.floor(n/65536)),i+=o-1+37*(o-1),e[0]=i,e[1]=a,e[2]=s,e[3]=u,e[4]=c,e[5]=l,e[6]=f,e[7]=p,e[8]=h,e[9]=d,e[10]=y,e[11]=m,e[12]=g,e[13]=v,e[14]=b,e[15]=w}function D(e,t){F(e,t,t)}function V(e,r){var n,o=t();for(n=0;n<16;n++)o[n]=r[n];for(n=253;n>=0;n--)D(o,o),2!==n&&4!==n&&F(o,o,r);for(n=0;n<16;n++)e[n]=o[n]}function q(e,r){var n,o=t();for(n=0;n<16;n++)o[n]=r[n];for(n=250;n>=0;n--)D(o,o),1!==n&&F(o,o,r);for(n=0;n<16;n++)e[n]=o[n]}function K(e,r,n){var o,i,a=new Uint8Array(32),s=new Float64Array(80),c=t(),l=t(),f=t(),p=t(),h=t(),d=t();for(i=0;i<31;i++)a[i]=r[i];for(a[31]=127&r[31]|64,a[0]&=248,L(s,n),i=0;i<16;i++)l[i]=s[i],p[i]=c[i]=f[i]=0;for(c[0]=p[0]=1,i=254;i>=0;--i)R(c,l,o=a[i>>>3]>>>(7&i)&1),R(f,p,o),M(h,c,f),j(c,c,f),M(f,l,p),j(l,l,p),D(p,h),D(d,c),F(c,f,c),F(f,l,h),M(h,c,f),j(c,c,f),D(l,c),j(f,p,d),F(c,f,u),M(c,c,p),F(f,f,c),F(c,p,d),F(p,l,s),D(l,h),R(c,l,o),R(f,p,o);for(i=0;i<16;i++)s[i+16]=c[i],s[i+32]=f[i],s[i+48]=l[i],s[i+64]=p[i];var y=s.subarray(32),m=s.subarray(16);return V(y,y),F(m,m,y),C(e,m),0}function H(e,t){return K(e,t,i)}function z(e,t){return n(t,32),H(e,t)}function X(e,t,r){var n=new Uint8Array(32);return K(n,r,t),b(e,o,n,w)}T.prototype.blocks=function(e,t,r){for(var n,o,i,a,s,u,c,l,f,p,h,d,y,m,g,v,b,w,S,k=this.fin?0:2048,E=this.h[0],A=this.h[1],T=this.h[2],O=this.h[3],P=this.h[4],x=this.h[5],I=this.h[6],B=this.h[7],_=this.h[8],R=this.h[9],C=this.r[0],U=this.r[1],N=this.r[2],L=this.r[3],M=this.r[4],j=this.r[5],F=this.r[6],D=this.r[7],V=this.r[8],q=this.r[9];r>=16;)p=f=0,p+=(E+=8191&(n=255&e[t+0]|(255&e[t+1])<<8))*C,p+=(A+=8191&(n>>>13|(o=255&e[t+2]|(255&e[t+3])<<8)<<3))*(5*q),p+=(T+=8191&(o>>>10|(i=255&e[t+4]|(255&e[t+5])<<8)<<6))*(5*V),p+=(O+=8191&(i>>>7|(a=255&e[t+6]|(255&e[t+7])<<8)<<9))*(5*D),f=(p+=(P+=8191&(a>>>4|(s=255&e[t+8]|(255&e[t+9])<<8)<<12))*(5*F))>>>13,p&=8191,p+=(x+=s>>>1&8191)*(5*j),p+=(I+=8191&(s>>>14|(u=255&e[t+10]|(255&e[t+11])<<8)<<2))*(5*M),p+=(B+=8191&(u>>>11|(c=255&e[t+12]|(255&e[t+13])<<8)<<5))*(5*L),p+=(_+=8191&(c>>>8|(l=255&e[t+14]|(255&e[t+15])<<8)<<8))*(5*N),h=f+=(p+=(R+=l>>>5|k)*(5*U))>>>13,h+=E*U,h+=A*C,h+=T*(5*q),h+=O*(5*V),f=(h+=P*(5*D))>>>13,h&=8191,h+=x*(5*F),h+=I*(5*j),h+=B*(5*M),h+=_*(5*L),f+=(h+=R*(5*N))>>>13,h&=8191,d=f,d+=E*N,d+=A*U,d+=T*C,d+=O*(5*q),f=(d+=P*(5*V))>>>13,d&=8191,d+=x*(5*D),d+=I*(5*F),d+=B*(5*j),d+=_*(5*M),y=f+=(d+=R*(5*L))>>>13,y+=E*L,y+=A*N,y+=T*U,y+=O*C,f=(y+=P*(5*q))>>>13,y&=8191,y+=x*(5*V),y+=I*(5*D),y+=B*(5*F),y+=_*(5*j),m=f+=(y+=R*(5*M))>>>13,m+=E*M,m+=A*L,m+=T*N,m+=O*U,f=(m+=P*C)>>>13,m&=8191,m+=x*(5*q),m+=I*(5*V),m+=B*(5*D),m+=_*(5*F),g=f+=(m+=R*(5*j))>>>13,g+=E*j,g+=A*M,g+=T*L,g+=O*N,f=(g+=P*U)>>>13,g&=8191,g+=x*C,g+=I*(5*q),g+=B*(5*V),g+=_*(5*D),v=f+=(g+=R*(5*F))>>>13,v+=E*F,v+=A*j,v+=T*M,v+=O*L,f=(v+=P*N)>>>13,v&=8191,v+=x*U,v+=I*C,v+=B*(5*q),v+=_*(5*V),b=f+=(v+=R*(5*D))>>>13,b+=E*D,b+=A*F,b+=T*j,b+=O*M,f=(b+=P*L)>>>13,b&=8191,b+=x*N,b+=I*U,b+=B*C,b+=_*(5*q),w=f+=(b+=R*(5*V))>>>13,w+=E*V,w+=A*D,w+=T*F,w+=O*j,f=(w+=P*M)>>>13,w&=8191,w+=x*L,w+=I*N,w+=B*U,w+=_*C,S=f+=(w+=R*(5*q))>>>13,S+=E*q,S+=A*V,S+=T*D,S+=O*F,f=(S+=P*j)>>>13,S&=8191,S+=x*M,S+=I*L,S+=B*N,S+=_*U,E=p=8191&(f=(f=((f+=(S+=R*C)>>>13)<<2)+f|0)+(p&=8191)|0),A=h+=f>>>=13,T=d&=8191,O=y&=8191,P=m&=8191,x=g&=8191,I=v&=8191,B=b&=8191,_=w&=8191,R=S&=8191,t+=16,r-=16;this.h[0]=E,this.h[1]=A,this.h[2]=T,this.h[3]=O,this.h[4]=P,this.h[5]=x,this.h[6]=I,this.h[7]=B,this.h[8]=_,this.h[9]=R},T.prototype.finish=function(e,t){var r,n,o,i,a=new Uint16Array(10);if(this.leftover){for(i=this.leftover,this.buffer[i++]=1;i<16;i++)this.buffer[i]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(r=this.h[1]>>>13,this.h[1]&=8191,i=2;i<10;i++)this.h[i]+=r,r=this.h[i]>>>13,this.h[i]&=8191;for(this.h[0]+=5*r,r=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=r,r=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=r,a[0]=this.h[0]+5,r=a[0]>>>13,a[0]&=8191,i=1;i<10;i++)a[i]=this.h[i]+r,r=a[i]>>>13,a[i]&=8191;for(a[9]-=8192,n=(1^r)-1,i=0;i<10;i++)a[i]&=n;for(n=~n,i=0;i<10;i++)this.h[i]=this.h[i]&n|a[i];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),o=this.h[0]+this.pad[0],this.h[0]=65535&o,i=1;i<8;i++)o=(this.h[i]+this.pad[i]|0)+(o>>>16)|0,this.h[i]=65535&o;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},T.prototype.update=function(e,t,r){var n,o;if(this.leftover){for((o=16-this.leftover)>r&&(o=r),n=0;n=16&&(o=r-r%16,this.blocks(e,t,o),t+=o,r-=o),r){for(n=0;n=128;){for(k=0;k<16;k++)E=8*k+G,B[k]=r[E+0]<<24|r[E+1]<<16|r[E+2]<<8|r[E+3],_[k]=r[E+4]<<24|r[E+5]<<16|r[E+6]<<8|r[E+7];for(k=0;k<80;k++)if(o=R,i=C,a=U,s=N,u=L,c=M,l=j,F,p=D,h=V,d=q,y=K,m=H,g=z,v=X,$,O=65535&(T=$),P=T>>>16,x=65535&(A=F),I=A>>>16,O+=65535&(T=(H>>>14|L<<18)^(H>>>18|L<<14)^(L>>>9|H<<23)),P+=T>>>16,x+=65535&(A=(L>>>14|H<<18)^(L>>>18|H<<14)^(H>>>9|L<<23)),I+=A>>>16,O+=65535&(T=H&z^~H&X),P+=T>>>16,x+=65535&(A=L&M^~L&j),I+=A>>>16,A=W[2*k],O+=65535&(T=W[2*k+1]),P+=T>>>16,x+=65535&A,I+=A>>>16,A=B[k%16],P+=(T=_[k%16])>>>16,x+=65535&A,I+=A>>>16,x+=(P+=(O+=65535&T)>>>16)>>>16,O=65535&(T=S=65535&O|P<<16),P=T>>>16,x=65535&(A=w=65535&x|(I+=x>>>16)<<16),I=A>>>16,O+=65535&(T=(D>>>28|R<<4)^(R>>>2|D<<30)^(R>>>7|D<<25)),P+=T>>>16,x+=65535&(A=(R>>>28|D<<4)^(D>>>2|R<<30)^(D>>>7|R<<25)),I+=A>>>16,P+=(T=D&V^D&q^V&q)>>>16,x+=65535&(A=R&C^R&U^C&U),I+=A>>>16,f=65535&(x+=(P+=(O+=65535&T)>>>16)>>>16)|(I+=x>>>16)<<16,b=65535&O|P<<16,O=65535&(T=y),P=T>>>16,x=65535&(A=s),I=A>>>16,P+=(T=S)>>>16,x+=65535&(A=w),I+=A>>>16,C=o,U=i,N=a,L=s=65535&(x+=(P+=(O+=65535&T)>>>16)>>>16)|(I+=x>>>16)<<16,M=u,j=c,F=l,R=f,V=p,q=h,K=d,H=y=65535&O|P<<16,z=m,X=g,$=v,D=b,k%16==15)for(E=0;E<16;E++)A=B[E],O=65535&(T=_[E]),P=T>>>16,x=65535&A,I=A>>>16,A=B[(E+9)%16],O+=65535&(T=_[(E+9)%16]),P+=T>>>16,x+=65535&A,I+=A>>>16,w=B[(E+1)%16],O+=65535&(T=((S=_[(E+1)%16])>>>1|w<<31)^(S>>>8|w<<24)^(S>>>7|w<<25)),P+=T>>>16,x+=65535&(A=(w>>>1|S<<31)^(w>>>8|S<<24)^w>>>7),I+=A>>>16,w=B[(E+14)%16],P+=(T=((S=_[(E+14)%16])>>>19|w<<13)^(w>>>29|S<<3)^(S>>>6|w<<26))>>>16,x+=65535&(A=(w>>>19|S<<13)^(S>>>29|w<<3)^w>>>6),I+=A>>>16,I+=(x+=(P+=(O+=65535&T)>>>16)>>>16)>>>16,B[E]=65535&x|I<<16,_[E]=65535&O|P<<16;O=65535&(T=D),P=T>>>16,x=65535&(A=R),I=A>>>16,A=e[0],P+=(T=t[0])>>>16,x+=65535&A,I+=A>>>16,I+=(x+=(P+=(O+=65535&T)>>>16)>>>16)>>>16,e[0]=R=65535&x|I<<16,t[0]=D=65535&O|P<<16,O=65535&(T=V),P=T>>>16,x=65535&(A=C),I=A>>>16,A=e[1],P+=(T=t[1])>>>16,x+=65535&A,I+=A>>>16,I+=(x+=(P+=(O+=65535&T)>>>16)>>>16)>>>16,e[1]=C=65535&x|I<<16,t[1]=V=65535&O|P<<16,O=65535&(T=q),P=T>>>16,x=65535&(A=U),I=A>>>16,A=e[2],P+=(T=t[2])>>>16,x+=65535&A,I+=A>>>16,I+=(x+=(P+=(O+=65535&T)>>>16)>>>16)>>>16,e[2]=U=65535&x|I<<16,t[2]=q=65535&O|P<<16,O=65535&(T=K),P=T>>>16,x=65535&(A=N),I=A>>>16,A=e[3],P+=(T=t[3])>>>16,x+=65535&A,I+=A>>>16,I+=(x+=(P+=(O+=65535&T)>>>16)>>>16)>>>16,e[3]=N=65535&x|I<<16,t[3]=K=65535&O|P<<16,O=65535&(T=H),P=T>>>16,x=65535&(A=L),I=A>>>16,A=e[4],P+=(T=t[4])>>>16,x+=65535&A,I+=A>>>16,I+=(x+=(P+=(O+=65535&T)>>>16)>>>16)>>>16,e[4]=L=65535&x|I<<16,t[4]=H=65535&O|P<<16,O=65535&(T=z),P=T>>>16,x=65535&(A=M),I=A>>>16,A=e[5],P+=(T=t[5])>>>16,x+=65535&A,I+=A>>>16,I+=(x+=(P+=(O+=65535&T)>>>16)>>>16)>>>16,e[5]=M=65535&x|I<<16,t[5]=z=65535&O|P<<16,O=65535&(T=X),P=T>>>16,x=65535&(A=j),I=A>>>16,A=e[6],P+=(T=t[6])>>>16,x+=65535&A,I+=A>>>16,I+=(x+=(P+=(O+=65535&T)>>>16)>>>16)>>>16,e[6]=j=65535&x|I<<16,t[6]=X=65535&O|P<<16,O=65535&(T=$),P=T>>>16,x=65535&(A=F),I=A>>>16,A=e[7],P+=(T=t[7])>>>16,x+=65535&A,I+=A>>>16,I+=(x+=(P+=(O+=65535&T)>>>16)>>>16)>>>16,e[7]=F=65535&x|I<<16,t[7]=$=65535&O|P<<16,G+=128,n-=128}return n}function J(e,t,r){var n,o=new Int32Array(8),i=new Int32Array(8),a=new Uint8Array(256),s=r;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,i[0]=4089235720,i[1]=2227873595,i[2]=4271175723,i[3]=1595750129,i[4]=2917565137,i[5]=725511199,i[6]=4215389547,i[7]=327033209,Y(o,i,t,r),r%=128,n=0;n=0;--o)Q(e,t,n=r[o/8|0]>>(7&o)&1),Z(t,e),Z(e,e),Q(e,t,n)}function re(e,r){var n=[t(),t(),t(),t()];B(n[0],f),B(n[1],p),B(n[2],s),F(n[3],f,p),te(e,n,r)}function ne(e,r,o){var i,a=new Uint8Array(64),s=[t(),t(),t(),t()];for(o||n(r,32),J(a,r,32),a[0]&=248,a[31]&=127,a[31]|=64,re(s,a),ee(e,s),i=0;i<32;i++)r[i+32]=e[i];return 0}var oe=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function ie(e,t){var r,n,o,i;for(n=63;n>=32;--n){for(r=0,o=n-32,i=n-12;o>4)*oe[o],r=t[o]>>8,t[o]&=255;for(o=0;o<32;o++)t[o]-=r*oe[o];for(n=0;n<32;n++)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function ae(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;ie(e,r)}function se(e,r,n,o){var i,a,s=new Uint8Array(64),u=new Uint8Array(64),c=new Uint8Array(64),l=new Float64Array(64),f=[t(),t(),t(),t()];J(s,o,32),s[0]&=248,s[31]&=127,s[31]|=64;var p=n+64;for(i=0;i>7&&j(e[0],a,e[0]),F(e[3],e[0],e[1]),0)}(p,o))return-1;for(i=0;i=0},e.sign.keyPair=function(){var e=new Uint8Array(fe),t=new Uint8Array(pe);return ne(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(de(e),e.length!==pe)throw new Error("bad secret key size");for(var t=new Uint8Array(fe),r=0;r{e.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},9032:(e,t,r)=>{"use strict";var n=r(7244),o=r(8184),i=r(5767),a=r(5680);function s(e){return e.call.bind(e)}var u="undefined"!=typeof BigInt,c="undefined"!=typeof Symbol,l=s(Object.prototype.toString),f=s(Number.prototype.valueOf),p=s(String.prototype.valueOf),h=s(Boolean.prototype.valueOf);if(u)var d=s(BigInt.prototype.valueOf);if(c)var y=s(Symbol.prototype.valueOf);function m(e,t){if("object"!=typeof e)return!1;try{return t(e),!0}catch(e){return!1}}function g(e){return"[object Map]"===l(e)}function v(e){return"[object Set]"===l(e)}function b(e){return"[object WeakMap]"===l(e)}function w(e){return"[object WeakSet]"===l(e)}function S(e){return"[object ArrayBuffer]"===l(e)}function k(e){return"undefined"!=typeof ArrayBuffer&&(S.working?S(e):e instanceof ArrayBuffer)}function E(e){return"[object DataView]"===l(e)}function A(e){return"undefined"!=typeof DataView&&(E.working?E(e):e instanceof DataView)}t.isArgumentsObject=n,t.isGeneratorFunction=o,t.isTypedArray=a,t.isPromise=function(e){return"undefined"!=typeof Promise&&e instanceof Promise||null!==e&&"object"==typeof e&&"function"==typeof e.then&&"function"==typeof e.catch},t.isArrayBufferView=function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):a(e)||A(e)},t.isUint8Array=function(e){return"Uint8Array"===i(e)},t.isUint8ClampedArray=function(e){return"Uint8ClampedArray"===i(e)},t.isUint16Array=function(e){return"Uint16Array"===i(e)},t.isUint32Array=function(e){return"Uint32Array"===i(e)},t.isInt8Array=function(e){return"Int8Array"===i(e)},t.isInt16Array=function(e){return"Int16Array"===i(e)},t.isInt32Array=function(e){return"Int32Array"===i(e)},t.isFloat32Array=function(e){return"Float32Array"===i(e)},t.isFloat64Array=function(e){return"Float64Array"===i(e)},t.isBigInt64Array=function(e){return"BigInt64Array"===i(e)},t.isBigUint64Array=function(e){return"BigUint64Array"===i(e)},g.working="undefined"!=typeof Map&&g(new Map),t.isMap=function(e){return"undefined"!=typeof Map&&(g.working?g(e):e instanceof Map)},v.working="undefined"!=typeof Set&&v(new Set),t.isSet=function(e){return"undefined"!=typeof Set&&(v.working?v(e):e instanceof Set)},b.working="undefined"!=typeof WeakMap&&b(new WeakMap),t.isWeakMap=function(e){return"undefined"!=typeof WeakMap&&(b.working?b(e):e instanceof WeakMap)},w.working="undefined"!=typeof WeakSet&&w(new WeakSet),t.isWeakSet=function(e){return w(e)},S.working="undefined"!=typeof ArrayBuffer&&S(new ArrayBuffer),t.isArrayBuffer=k,E.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&E(new DataView(new ArrayBuffer(1),0,1)),t.isDataView=A;var T="undefined"!=typeof SharedArrayBuffer?SharedArrayBuffer:void 0;function O(e){return"[object SharedArrayBuffer]"===l(e)}function P(e){return void 0!==T&&(void 0===O.working&&(O.working=O(new T)),O.working?O(e):e instanceof T)}function x(e){return m(e,f)}function I(e){return m(e,p)}function B(e){return m(e,h)}function _(e){return u&&m(e,d)}function R(e){return c&&m(e,y)}t.isSharedArrayBuffer=P,t.isAsyncFunction=function(e){return"[object AsyncFunction]"===l(e)},t.isMapIterator=function(e){return"[object Map Iterator]"===l(e)},t.isSetIterator=function(e){return"[object Set Iterator]"===l(e)},t.isGeneratorObject=function(e){return"[object Generator]"===l(e)},t.isWebAssemblyCompiledModule=function(e){return"[object WebAssembly.Module]"===l(e)},t.isNumberObject=x,t.isStringObject=I,t.isBooleanObject=B,t.isBigIntObject=_,t.isSymbolObject=R,t.isBoxedPrimitive=function(e){return x(e)||I(e)||B(e)||_(e)||R(e)},t.isAnyArrayBuffer=function(e){return"undefined"!=typeof Uint8Array&&(k(e)||P(e))},["isProxy","isExternal","isModuleNamespaceObject"].forEach((function(e){Object.defineProperty(t,e,{enumerable:!1,value:function(){throw new Error(e+" is not supported in userland")}})}))},537:(e,t,r)=>{var n=r(5606),o=r(6763),i=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),r={},n=0;n=o)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}})),s=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),g(r)?n.showHidden=r:r&&t._extend(n,r),S(n.showHidden)&&(n.showHidden=!1),S(n.depth)&&(n.depth=2),S(n.colors)&&(n.colors=!1),S(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=f),h(n,e,n.depth)}function f(e,t){var r=l.styles[t];return r?"\x1b["+l.colors[r][0]+"m"+e+"\x1b["+l.colors[r][1]+"m":e}function p(e,t){return e}function h(e,r,n){if(e.customInspect&&r&&O(r.inspect)&&r.inspect!==t.inspect&&(!r.constructor||r.constructor.prototype!==r)){var o=r.inspect(n,e);return w(o)||(o=h(e,o,n)),o}var i=function(e,t){if(S(t))return e.stylize("undefined","undefined");if(w(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(b(t))return e.stylize(""+t,"number");if(g(t))return e.stylize(""+t,"boolean");if(v(t))return e.stylize("null","null")}(e,r);if(i)return i;var a=Object.keys(r),s=function(e){var t={};return e.forEach((function(e,r){t[e]=!0})),t}(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(r)),T(r)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return d(r);if(0===a.length){if(O(r)){var u=r.name?": "+r.name:"";return e.stylize("[Function"+u+"]","special")}if(k(r))return e.stylize(RegExp.prototype.toString.call(r),"regexp");if(A(r))return e.stylize(Date.prototype.toString.call(r),"date");if(T(r))return d(r)}var c,l="",f=!1,p=["{","}"];(m(r)&&(f=!0,p=["[","]"]),O(r))&&(l=" [Function"+(r.name?": "+r.name:"")+"]");return k(r)&&(l=" "+RegExp.prototype.toString.call(r)),A(r)&&(l=" "+Date.prototype.toUTCString.call(r)),T(r)&&(l=" "+d(r)),0!==a.length||f&&0!=r.length?n<0?k(r)?e.stylize(RegExp.prototype.toString.call(r),"regexp"):e.stylize("[Object]","special"):(e.seen.push(r),c=f?function(e,t,r,n,o){for(var i=[],a=0,s=t.length;a=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1}),0);if(n>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(c,l,p)):p[0]+l+p[1]}function d(e){return"["+Error.prototype.toString.call(e)+"]"}function y(e,t,r,n,o,i){var a,s,u;if((u=Object.getOwnPropertyDescriptor(t,o)||{value:t[o]}).get?s=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(s=e.stylize("[Setter]","special")),B(n,o)||(a="["+o+"]"),s||(e.seen.indexOf(u.value)<0?(s=v(r)?h(e,u.value,null):h(e,u.value,r-1)).indexOf("\n")>-1&&(s=i?s.split("\n").map((function(e){return" "+e})).join("\n").slice(2):"\n"+s.split("\n").map((function(e){return" "+e})).join("\n")):s=e.stylize("[Circular]","special")),S(a)){if(i&&o.match(/^\d+$/))return s;(a=JSON.stringify(""+o)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.slice(1,-1),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function m(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function v(e){return null===e}function b(e){return"number"==typeof e}function w(e){return"string"==typeof e}function S(e){return void 0===e}function k(e){return E(e)&&"[object RegExp]"===P(e)}function E(e){return"object"==typeof e&&null!==e}function A(e){return E(e)&&"[object Date]"===P(e)}function T(e){return E(e)&&("[object Error]"===P(e)||e instanceof Error)}function O(e){return"function"==typeof e}function P(e){return Object.prototype.toString.call(e)}function x(e){return e<10?"0"+e.toString(10):e.toString(10)}t.debuglog=function(e){if(e=e.toUpperCase(),!s[e])if(u.test(e)){var r=n.pid;s[e]=function(){var n=t.format.apply(t,arguments);o.error("%s %d: %s",e,r,n)}}else s[e]=function(){};return s[e]},t.inspect=l,l.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},l.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},t.types=r(9032),t.isArray=m,t.isBoolean=g,t.isNull=v,t.isNullOrUndefined=function(e){return null==e},t.isNumber=b,t.isString=w,t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=S,t.isRegExp=k,t.types.isRegExp=k,t.isObject=E,t.isDate=A,t.types.isDate=A,t.isError=T,t.types.isNativeError=T,t.isFunction=O,t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=r(1135);var I=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function B(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.log=function(){var e,r;o.log("%s - %s",(e=new Date,r=[x(e.getHours()),x(e.getMinutes()),x(e.getSeconds())].join(":"),[e.getDate(),I[e.getMonth()],r].join(" ")),t.format.apply(t,arguments))},t.inherits=r(6698),t._extend=function(e,t){if(!t||!E(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e};var _="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function R(e,t){if(!e){var r=new Error("Promise was rejected with a falsy value");r.reason=e,e=r}return t(e)}t.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(_&&e[_]){var t;if("function"!=typeof(t=e[_]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(t,_,{value:t,enumerable:!1,writable:!1,configurable:!0}),t}function t(){for(var t,r,n=new Promise((function(e,n){t=e,r=n})),o=[],i=0;i{"use strict";var n=r(2682),o=r(9209),i=r(487),a=r(8075),s=r(5795),u=a("Object.prototype.toString"),c=r(9092)(),l="undefined"==typeof globalThis?r.g:globalThis,f=o(),p=a("String.prototype.slice"),h=Object.getPrototypeOf,d=a("Array.prototype.indexOf",!0)||function(e,t){for(var r=0;r-1?t:"Object"===t&&function(e){var t=!1;return n(y,(function(r,n){if(!t)try{r(e),t=p(n,1)}catch(e){}})),t}(e)}return s?function(e){var t=!1;return n(y,(function(r,n){if(!t)try{"$"+r(e)===n&&(t=p(n,1))}catch(e){}})),t}(e):null}},1281:()=>{},9209:(e,t,r)=>{"use strict";var n=r(6578),o="undefined"==typeof globalThis?r.g:globalThis;e.exports=function(){for(var e=[],t=0;t{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n=r(7957);StellarBase=n})(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/account.js b/node_modules/@stellar/stellar-base/lib/account.js new file mode 100644 index 000000000..8846ac278 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/account.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Account = void 0; +var _bignumber = _interopRequireDefault(require("./util/bignumber")); +var _strkey = require("./strkey"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Account object. + * + * `Account` represents a single account in the Stellar network and its sequence + * number. Account tracks the sequence number as it is used by {@link + * TransactionBuilder}. See + * [Accounts](https://developers.stellar.org/docs/glossary/accounts/) for + * more information about how accounts work in Stellar. + * + * @constructor + * + * @param {string} accountId - ID of the account (ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`). If you + * provide a muxed account address, this will throw; use {@link + * MuxedAccount} instead. + * @param {string} sequence - current sequence number of the account + */ +var Account = exports.Account = /*#__PURE__*/function () { + function Account(accountId, sequence) { + _classCallCheck(this, Account); + if (_strkey.StrKey.isValidMed25519PublicKey(accountId)) { + throw new Error('accountId is an M-address; use MuxedAccount instead'); + } + if (!_strkey.StrKey.isValidEd25519PublicKey(accountId)) { + throw new Error('accountId is invalid'); + } + if (!(typeof sequence === 'string')) { + throw new Error('sequence must be of type string'); + } + this._accountId = accountId; + this.sequence = new _bignumber["default"](sequence); + } + + /** + * Returns Stellar account ID, ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`. + * @returns {string} + */ + return _createClass(Account, [{ + key: "accountId", + value: function accountId() { + return this._accountId; + } + + /** + * @returns {string} sequence number for the account as a string + */ + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this.sequence.toString(); + } + + /** + * Increments sequence number in this object by one. + * @returns {void} + */ + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + this.sequence = this.sequence.plus(1); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/address.js b/node_modules/@stellar/stellar-base/lib/address.js new file mode 100644 index 000000000..83c6586d9 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/address.js @@ -0,0 +1,168 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Address = void 0; +var _strkey = require("./strkey"); +var _xdr = _interopRequireDefault(require("./xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Address object. + * + * `Address` represents a single address in the Stellar network. An address can + * represent an account or a contract. + * + * @constructor + * + * @param {string} address - ID of the account (ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`). If you + * provide a muxed account address, this will throw; use {@link + * MuxedAccount} instead. + */ +var Address = exports.Address = /*#__PURE__*/function () { + function Address(address) { + _classCallCheck(this, Address); + if (_strkey.StrKey.isValidEd25519PublicKey(address)) { + this._type = 'account'; + this._key = _strkey.StrKey.decodeEd25519PublicKey(address); + } else if (_strkey.StrKey.isValidContract(address)) { + this._type = 'contract'; + this._key = _strkey.StrKey.decodeContract(address); + } else { + throw new Error("Unsupported address type: ".concat(address)); + } + } + + /** + * Parses a string and returns an Address object. + * + * @param {string} address - The address to parse. ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA` + * @returns {Address} + */ + return _createClass(Address, [{ + key: "toString", + value: + /** + * Serialize an address to string. + * + * @returns {string} + */ + function toString() { + switch (this._type) { + case 'account': + return _strkey.StrKey.encodeEd25519PublicKey(this._key); + case 'contract': + return _strkey.StrKey.encodeContract(this._key); + default: + throw new Error('Unsupported address type'); + } + } + + /** + * Convert this Address to an xdr.ScVal type. + * + * @returns {xdr.ScVal} + */ + }, { + key: "toScVal", + value: function toScVal() { + return _xdr["default"].ScVal.scvAddress(this.toScAddress()); + } + + /** + * Convert this Address to an xdr.ScAddress type. + * + * @returns {xdr.ScAddress} + */ + }, { + key: "toScAddress", + value: function toScAddress() { + switch (this._type) { + case 'account': + return _xdr["default"].ScAddress.scAddressTypeAccount(_xdr["default"].PublicKey.publicKeyTypeEd25519(this._key)); + case 'contract': + return _xdr["default"].ScAddress.scAddressTypeContract(this._key); + default: + throw new Error('Unsupported address type'); + } + } + + /** + * Return the raw public key bytes for this address. + * + * @returns {Buffer} + */ + }, { + key: "toBuffer", + value: function toBuffer() { + return this._key; + } + }], [{ + key: "fromString", + value: function fromString(address) { + return new Address(address); + } + + /** + * Creates a new account Address object from a buffer of raw bytes. + * + * @param {Buffer} buffer - The bytes of an address to parse. + * @returns {Address} + */ + }, { + key: "account", + value: function account(buffer) { + return new Address(_strkey.StrKey.encodeEd25519PublicKey(buffer)); + } + + /** + * Creates a new contract Address object from a buffer of raw bytes. + * + * @param {Buffer} buffer - The bytes of an address to parse. + * @returns {Address} + */ + }, { + key: "contract", + value: function contract(buffer) { + return new Address(_strkey.StrKey.encodeContract(buffer)); + } + + /** + * Convert this from an xdr.ScVal type + * + * @param {xdr.ScVal} scVal - The xdr.ScVal type to parse + * @returns {Address} + */ + }, { + key: "fromScVal", + value: function fromScVal(scVal) { + return Address.fromScAddress(scVal.address()); + } + + /** + * Convert this from an xdr.ScAddress type + * + * @param {xdr.ScAddress} scAddress - The xdr.ScAddress type to parse + * @returns {Address} + */ + }, { + key: "fromScAddress", + value: function fromScAddress(scAddress) { + switch (scAddress["switch"]()) { + case _xdr["default"].ScAddressType.scAddressTypeAccount(): + return Address.account(scAddress.accountId().ed25519()); + case _xdr["default"].ScAddressType.scAddressTypeContract(): + return Address.contract(scAddress.contractId()); + default: + throw new Error('Unsupported address type'); + } + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/asset.js b/node_modules/@stellar/stellar-base/lib/asset.js new file mode 100644 index 000000000..e4aa22f62 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/asset.js @@ -0,0 +1,322 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Asset = void 0; +var _util = require("./util/util"); +var _xdr = _interopRequireDefault(require("./xdr")); +var _keypair = require("./keypair"); +var _strkey = require("./strkey"); +var _hashing = require("./hashing"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Asset class represents an asset, either the native asset (`XLM`) + * or an asset code / issuer account ID pair. + * + * An asset code describes an asset code and issuer pair. In the case of the native + * asset XLM, the issuer will be null. + * + * @constructor + * @param {string} code - The asset code. + * @param {string} issuer - The account ID of the issuer. + */ +var Asset = exports.Asset = /*#__PURE__*/function () { + function Asset(code, issuer) { + _classCallCheck(this, Asset); + if (!/^[a-zA-Z0-9]{1,12}$/.test(code)) { + throw new Error('Asset code is invalid (maximum alphanumeric, 12 characters at max)'); + } + if (String(code).toLowerCase() !== 'xlm' && !issuer) { + throw new Error('Issuer cannot be null'); + } + if (issuer && !_strkey.StrKey.isValidEd25519PublicKey(issuer)) { + throw new Error('Issuer is invalid'); + } + if (String(code).toLowerCase() === 'xlm') { + // transform all xLM, Xlm, etc. variants -> XLM + this.code = 'XLM'; + } else { + this.code = code; + } + this.issuer = issuer; + } + + /** + * Returns an asset object for the native asset. + * @Return {Asset} + */ + return _createClass(Asset, [{ + key: "toXDRObject", + value: + /** + * Returns the xdr.Asset object for this asset. + * @returns {xdr.Asset} XDR asset object + */ + function toXDRObject() { + return this._toXDRObject(_xdr["default"].Asset); + } + + /** + * Returns the xdr.ChangeTrustAsset object for this asset. + * @returns {xdr.ChangeTrustAsset} XDR asset object + */ + }, { + key: "toChangeTrustXDRObject", + value: function toChangeTrustXDRObject() { + return this._toXDRObject(_xdr["default"].ChangeTrustAsset); + } + + /** + * Returns the xdr.TrustLineAsset object for this asset. + * @returns {xdr.TrustLineAsset} XDR asset object + */ + }, { + key: "toTrustLineXDRObject", + value: function toTrustLineXDRObject() { + return this._toXDRObject(_xdr["default"].TrustLineAsset); + } + + /** + * Returns the would-be contract ID (`C...` format) for this asset on a given + * network. + * + * @param {string} networkPassphrase indicates which network the contract + * ID should refer to, since every network will have a unique ID for the + * same contract (see {@link Networks} for options) + * + * @returns {string} the strkey-encoded (`C...`) contract ID for this asset + * + * @warning This makes no guarantee that this contract actually *exists*. + */ + }, { + key: "contractId", + value: function contractId(networkPassphrase) { + var networkId = (0, _hashing.hash)(Buffer.from(networkPassphrase)); + var preimage = _xdr["default"].HashIdPreimage.envelopeTypeContractId(new _xdr["default"].HashIdPreimageContractId({ + networkId: networkId, + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAsset(this.toXDRObject()) + })); + return _strkey.StrKey.encodeContract((0, _hashing.hash)(preimage.toXDR())); + } + + /** + * Returns the xdr object for this asset. + * @param {xdr.Asset | xdr.ChangeTrustAsset} xdrAsset - The asset xdr object. + * @returns {xdr.Asset | xdr.ChangeTrustAsset | xdr.TrustLineAsset} XDR Asset object + */ + }, { + key: "_toXDRObject", + value: function _toXDRObject() { + var xdrAsset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _xdr["default"].Asset; + if (this.isNative()) { + return xdrAsset.assetTypeNative(); + } + var xdrType; + var xdrTypeString; + if (this.code.length <= 4) { + xdrType = _xdr["default"].AlphaNum4; + xdrTypeString = 'assetTypeCreditAlphanum4'; + } else { + xdrType = _xdr["default"].AlphaNum12; + xdrTypeString = 'assetTypeCreditAlphanum12'; + } + + // pad code with null bytes if necessary + var padLength = this.code.length <= 4 ? 4 : 12; + var paddedCode = this.code.padEnd(padLength, '\0'); + + // eslint-disable-next-line new-cap + var assetType = new xdrType({ + assetCode: paddedCode, + issuer: _keypair.Keypair.fromPublicKey(this.issuer).xdrAccountId() + }); + return new xdrAsset(xdrTypeString, assetType); + } + + /** + * @returns {string} Asset code + */ + }, { + key: "getCode", + value: function getCode() { + if (this.code === undefined) { + return undefined; + } + return String(this.code); + } + + /** + * @returns {string} Asset issuer + */ + }, { + key: "getIssuer", + value: function getIssuer() { + if (this.issuer === undefined) { + return undefined; + } + return String(this.issuer); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {string} Asset type. Can be one of following types: + * + * - `native`, + * - `credit_alphanum4`, + * - `credit_alphanum12`, or + * - `unknown` as the error case (which should never occur) + */ + }, { + key: "getAssetType", + value: function getAssetType() { + switch (this.getRawAssetType().value) { + case _xdr["default"].AssetType.assetTypeNative().value: + return 'native'; + case _xdr["default"].AssetType.assetTypeCreditAlphanum4().value: + return 'credit_alphanum4'; + case _xdr["default"].AssetType.assetTypeCreditAlphanum12().value: + return 'credit_alphanum12'; + default: + return 'unknown'; + } + } + + /** + * @returns {xdr.AssetType} the raw XDR representation of the asset type + */ + }, { + key: "getRawAssetType", + value: function getRawAssetType() { + if (this.isNative()) { + return _xdr["default"].AssetType.assetTypeNative(); + } + if (this.code.length <= 4) { + return _xdr["default"].AssetType.assetTypeCreditAlphanum4(); + } + return _xdr["default"].AssetType.assetTypeCreditAlphanum12(); + } + + /** + * @returns {boolean} true if this asset object is the native asset. + */ + }, { + key: "isNative", + value: function isNative() { + return !this.issuer; + } + + /** + * @param {Asset} asset Asset to compare + * @returns {boolean} true if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(asset) { + return this.code === asset.getCode() && this.issuer === asset.getIssuer(); + } + }, { + key: "toString", + value: function toString() { + if (this.isNative()) { + return 'native'; + } + return "".concat(this.getCode(), ":").concat(this.getIssuer()); + } + + /** + * Compares two assets according to the criteria: + * + * 1. First compare the type (native < alphanum4 < alphanum12). + * 2. If the types are equal, compare the assets codes. + * 3. If the asset codes are equal, compare the issuers. + * + * @param {Asset} assetA - the first asset + * @param {Asset} assetB - the second asset + * @returns {number} `-1` if assetA < assetB, `0` if assetA == assetB, `1` if assetA > assetB. + * + * @static + * @memberof Asset + */ + }], [{ + key: "native", + value: function _native() { + return new Asset('XLM'); + } + + /** + * Returns an asset object from its XDR object representation. + * @param {xdr.Asset} assetXdr - The asset xdr object. + * @returns {Asset} + */ + }, { + key: "fromOperation", + value: function fromOperation(assetXdr) { + var anum; + var code; + var issuer; + switch (assetXdr["switch"]()) { + case _xdr["default"].AssetType.assetTypeNative(): + return this["native"](); + case _xdr["default"].AssetType.assetTypeCreditAlphanum4(): + anum = assetXdr.alphaNum4(); + /* falls through */ + case _xdr["default"].AssetType.assetTypeCreditAlphanum12(): + anum = anum || assetXdr.alphaNum12(); + issuer = _strkey.StrKey.encodeEd25519PublicKey(anum.issuer().ed25519()); + code = (0, _util.trimEnd)(anum.assetCode(), '\0'); + return new this(code, issuer); + default: + throw new Error("Invalid asset type: ".concat(assetXdr["switch"]().name)); + } + } + }, { + key: "compare", + value: function compare(assetA, assetB) { + if (!assetA || !(assetA instanceof Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof Asset)) { + throw new Error('assetB is invalid'); + } + if (assetA.equals(assetB)) { + return 0; + } + + // Compare asset types. + var xdrAtype = assetA.getRawAssetType().value; + var xdrBtype = assetB.getRawAssetType().value; + if (xdrAtype !== xdrBtype) { + return xdrAtype < xdrBtype ? -1 : 1; + } + + // Compare asset codes. + var result = asciiCompare(assetA.getCode(), assetB.getCode()); + if (result !== 0) { + return result; + } + + // Compare asset issuers. + return asciiCompare(assetA.getIssuer(), assetB.getIssuer()); + } + }]); +}(); +/** + * Compares two ASCII strings in lexographic order with uppercase precedence. + * + * @param {string} a - the first string to compare + * @param {string} b - the second + * @returns {number} like all `compare()`s: + * -1 if `a < b`, 0 if `a == b`, and 1 if `a > b` + * + * @warning No type-checks are done on the parameters + */ +function asciiCompare(a, b) { + return Buffer.compare(Buffer.from(a, 'ascii'), Buffer.from(b, 'ascii')); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/auth.js b/node_modules/@stellar/stellar-base/lib/auth.js new file mode 100644 index 000000000..971bac280 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/auth.js @@ -0,0 +1,263 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.authorizeEntry = authorizeEntry; +exports.authorizeInvocation = authorizeInvocation; +var _xdr = _interopRequireDefault(require("./xdr")); +var _keypair = require("./keypair"); +var _strkey = require("./strkey"); +var _network = require("./network"); +var _hashing = require("./hashing"); +var _address = require("./address"); +var _scval = require("./scval"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +/** + * @async + * @callback SigningCallback A callback for signing an XDR structure + * representing all of the details necessary to authorize an invocation tree. + * + * @param {xdr.HashIdPreimage} preimage the entire authorization envelope + * whose hash you should sign, so that you can inspect the entire structure + * if necessary (rather than blindly signing a hash) + * + * @returns {Promise} the signature of the raw payload (which is + * the sha256 hash of the preimage bytes, so `hash(preimage.toXDR())`) signed + * by the key corresponding to the public key in the entry you pass to + * {@link authorizeEntry} (decipherable from its + * `credentials().address().address()`) + */ +/** + * Actually authorizes an existing authorization entry using the given the + * credentials and expiration details, returning a signed copy. + * + * This "fills out" the authorization entry with a signature, indicating to the + * {@link Operation.invokeHostFunction} its attached to that: + * - a particular identity (i.e. signing {@link Keypair} or other signer) + * - approving the execution of an invocation tree (i.e. a simulation-acquired + * {@link xdr.SorobanAuthorizedInvocation} or otherwise built) + * - on a particular network (uniquely identified by its passphrase, see + * {@link Networks}) + * - until a particular ledger sequence is reached. + * + * This one lets you pass a either a {@link Keypair} (or, more accurately, + * anything with a `sign(Buffer): Buffer` method) or a callback function (see + * {@link SigningCallback}) to handle signing the envelope hash. + * + * @param {xdr.SorobanAuthorizationEntry} entry an unsigned authorization entr + * @param {Keypair | SigningCallback} signer either a {@link Keypair} instance + * or a function which takes a payload (a + * {@link xdr.HashIdPreimageSorobanAuthorization} instance) input and returns + * the signature of the hash of the raw payload bytes (where the signing key + * should correspond to the address in the `entry`) + * @param {number} validUntilLedgerSeq the (exclusive) future ledger sequence + * number until which this authorization entry should be valid (if + * `currentLedgerSeq==validUntil`, this is expired)) + * @param {string} [networkPassphrase] the network passphrase is incorprated + * into the signature (see {@link Networks} for options) + * + * @returns {Promise} a promise for an + * authorization entry that you can pass along to + * {@link Operation.invokeHostFunction} + * + * @note If using the `SigningCallback` variation, the signer is assumed to be + * the entry's credential address. If you need a different key to sign the + * entry, you will need to use different method (e.g., fork this code). + * + * @see authorizeInvocation + * @example + * import { + * SorobanRpc, + * Transaction, + * Networks, + * authorizeEntry + * } from '@stellar/stellar-sdk'; + * + * // Assume signPayloadCallback is a well-formed signing callback. + * // + * // It might, for example, pop up a modal from a browser extension, send the + * // transaction to a third-party service for signing, or just do simple + * // signing via Keypair like it does here: + * function signPayloadCallback(payload) { + * return signer.sign(hash(payload.toXDR()); + * } + * + * function multiPartyAuth( + * server: SorobanRpc.Server, + * // assume this involves multi-party auth + * tx: Transaction, + * ) { + * return server + * .simulateTransaction(tx) + * .then((simResult) => { + * tx.operations[0].auth.map(entry => + * authorizeEntry( + * entry, + * signPayloadCallback, + * currentLedger + 1000, + * Networks.TESTNET); + * )); + * + * return server.prepareTransaction(tx, simResult); + * }) + * .then((preppedTx) => { + * preppedTx.sign(source); + * return server.sendTransaction(preppedTx); + * }); + * } + */ +function authorizeEntry(_x, _x2, _x3) { + return _authorizeEntry.apply(this, arguments); +} +/** + * This builds an entry from scratch, allowing you to express authorization as a + * function of: + * - a particular identity (i.e. signing {@link Keypair} or other signer) + * - approving the execution of an invocation tree (i.e. a simulation-acquired + * {@link xdr.SorobanAuthorizedInvocation} or otherwise built) + * - on a particular network (uniquely identified by its passphrase, see + * {@link Networks}) + * - until a particular ledger sequence is reached. + * + * This is in contrast to {@link authorizeEntry}, which signs an existing entry. + * + * @param {Keypair | SigningCallback} signer either a {@link Keypair} instance + * (or anything with a `.sign(buf): Buffer-like` method) or a function which + * takes a payload (a {@link xdr.HashIdPreimageSorobanAuthorization} + * instance) input and returns the signature of the hash of the raw payload + * bytes (where the signing key should correspond to the address in the + * `entry`) + * @param {number} validUntilLedgerSeq the (exclusive) future ledger sequence + * number until which this authorization entry should be valid (if + * `currentLedgerSeq==validUntilLedgerSeq`, this is expired)) + * @param {xdr.SorobanAuthorizedInvocation} invocation the invocation tree that + * we're authorizing (likely, this comes from transaction simulation) + * @param {string} [publicKey] the public identity of the signer (when + * providing a {@link Keypair} to `signer`, this can be omitted, as it just + * uses {@link Keypair.publicKey}) + * @param {string} [networkPassphrase] the network passphrase is incorprated + * into the signature (see {@link Networks} for options, default: + * {@link Networks.FUTURENET}) + * + * @returns {Promise} a promise for an + * authorization entry that you can pass along to + * {@link Operation.invokeHostFunction} + * + * @see authorizeEntry + */ +function _authorizeEntry() { + _authorizeEntry = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(entry, signer, validUntilLedgerSeq) { + var networkPassphrase, + clone, + addrAuth, + networkId, + preimage, + payload, + signature, + publicKey, + sigScVal, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + networkPassphrase = _args.length > 3 && _args[3] !== undefined ? _args[3] : _network.Networks.FUTURENET; + if (!(entry.credentials()["switch"]().value !== _xdr["default"].SorobanCredentialsType.sorobanCredentialsAddress().value)) { + _context.next = 3; + break; + } + return _context.abrupt("return", entry); + case 3: + clone = _xdr["default"].SorobanAuthorizationEntry.fromXDR(entry.toXDR()); + /** @type {xdr.SorobanAddressCredentials} */ + addrAuth = clone.credentials().address(); + addrAuth.signatureExpirationLedger(validUntilLedgerSeq); + networkId = (0, _hashing.hash)(Buffer.from(networkPassphrase)); + preimage = _xdr["default"].HashIdPreimage.envelopeTypeSorobanAuthorization(new _xdr["default"].HashIdPreimageSorobanAuthorization({ + networkId: networkId, + nonce: addrAuth.nonce(), + invocation: clone.rootInvocation(), + signatureExpirationLedger: addrAuth.signatureExpirationLedger() + })); + payload = (0, _hashing.hash)(preimage.toXDR()); + if (!(typeof signer === 'function')) { + _context.next = 18; + break; + } + _context.t0 = Buffer; + _context.next = 13; + return signer(preimage); + case 13: + _context.t1 = _context.sent; + signature = _context.t0.from.call(_context.t0, _context.t1); + publicKey = _address.Address.fromScAddress(addrAuth.address()).toString(); + _context.next = 20; + break; + case 18: + signature = Buffer.from(signer.sign(payload)); + publicKey = signer.publicKey(); + case 20: + if (_keypair.Keypair.fromPublicKey(publicKey).verify(payload, signature)) { + _context.next = 22; + break; + } + throw new Error("signature doesn't match payload"); + case 22: + // This structure is defined here: + // https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#stellar-account-signatures + // + // Encoding a contract structure as an ScVal means the map keys are supposed + // to be symbols, hence the forced typing here. + sigScVal = (0, _scval.nativeToScVal)({ + public_key: _strkey.StrKey.decodeEd25519PublicKey(publicKey), + signature: signature + }, { + type: { + public_key: ['symbol', null], + signature: ['symbol', null] + } + }); + addrAuth.signature(_xdr["default"].ScVal.scvVec([sigScVal])); + return _context.abrupt("return", clone); + case 25: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _authorizeEntry.apply(this, arguments); +} +function authorizeInvocation(signer, validUntilLedgerSeq, invocation) { + var publicKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; + var networkPassphrase = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : _network.Networks.FUTURENET; + // We use keypairs as a source of randomness for the nonce to avoid mucking + // with any crypto dependencies. Note that this just has to be random and + // unique, not cryptographically secure, so it's fine. + var kp = _keypair.Keypair.random().rawPublicKey(); + var nonce = new _xdr["default"].Int64(bytesToInt64(kp)); + var pk = publicKey || signer.publicKey(); + if (!pk) { + throw new Error("authorizeInvocation requires publicKey parameter"); + } + var entry = new _xdr["default"].SorobanAuthorizationEntry({ + rootInvocation: invocation, + credentials: _xdr["default"].SorobanCredentials.sorobanCredentialsAddress(new _xdr["default"].SorobanAddressCredentials({ + address: new _address.Address(pk).toScAddress(), + nonce: nonce, + signatureExpirationLedger: 0, + // replaced + signature: _xdr["default"].ScVal.scvVec([]) // replaced + })) + }); + return authorizeEntry(entry, signer, validUntilLedgerSeq, networkPassphrase); +} +function bytesToInt64(bytes) { + // eslint-disable-next-line no-bitwise + return bytes.subarray(0, 8).reduce(function (accum, b) { + return accum << 8 | b; + }, 0); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/claimant.js b/node_modules/@stellar/stellar-base/lib/claimant.js new file mode 100644 index 000000000..0584d95d0 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/claimant.js @@ -0,0 +1,192 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Claimant = void 0; +var _xdr = _interopRequireDefault(require("./xdr")); +var _keypair = require("./keypair"); +var _strkey = require("./strkey"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Claimant class represents an xdr.Claimant + * + * The claim predicate is optional, it defaults to unconditional if none is specified. + * + * @constructor + * @param {string} destination - The destination account ID. + * @param {xdr.ClaimPredicate} [predicate] - The claim predicate. + */ +var Claimant = exports.Claimant = /*#__PURE__*/function () { + function Claimant(destination, predicate) { + _classCallCheck(this, Claimant); + if (destination && !_strkey.StrKey.isValidEd25519PublicKey(destination)) { + throw new Error('Destination is invalid'); + } + this._destination = destination; + if (!predicate) { + this._predicate = _xdr["default"].ClaimPredicate.claimPredicateUnconditional(); + } else if (predicate instanceof _xdr["default"].ClaimPredicate) { + this._predicate = predicate; + } else { + throw new Error('Predicate should be an xdr.ClaimPredicate'); + } + } + + /** + * Returns an unconditional claim predicate + * @Return {xdr.ClaimPredicate} + */ + return _createClass(Claimant, [{ + key: "toXDRObject", + value: + /** + * Returns the xdr object for this claimant. + * @returns {xdr.Claimant} XDR Claimant object + */ + function toXDRObject() { + var claimant = new _xdr["default"].ClaimantV0({ + destination: _keypair.Keypair.fromPublicKey(this._destination).xdrAccountId(), + predicate: this._predicate + }); + return _xdr["default"].Claimant.claimantTypeV0(claimant); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "destination", + get: function get() { + return this._destination; + }, + set: function set(value) { + throw new Error('Claimant is immutable'); + } + + /** + * @type {xdr.ClaimPredicate} + * @readonly + */ + }, { + key: "predicate", + get: function get() { + return this._predicate; + }, + set: function set(value) { + throw new Error('Claimant is immutable'); + } + }], [{ + key: "predicateUnconditional", + value: function predicateUnconditional() { + return _xdr["default"].ClaimPredicate.claimPredicateUnconditional(); + } + + /** + * Returns an `and` claim predicate + * @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate + * @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateAnd", + value: function predicateAnd(left, right) { + if (!(left instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('left Predicate should be an xdr.ClaimPredicate'); + } + if (!(right instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateAnd([left, right]); + } + + /** + * Returns an `or` claim predicate + * @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate + * @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateOr", + value: function predicateOr(left, right) { + if (!(left instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('left Predicate should be an xdr.ClaimPredicate'); + } + if (!(right instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateOr([left, right]); + } + + /** + * Returns a `not` claim predicate + * @param {xdr.ClaimPredicate} predicate an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateNot", + value: function predicateNot(predicate) { + if (!(predicate instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateNot(predicate); + } + + /** + * Returns a `BeforeAbsoluteTime` claim predicate + * + * This predicate will be fulfilled if the closing time of the ledger that + * includes the CreateClaimableBalance operation is less than this (absolute) + * Unix timestamp (expressed in seconds). + * + * @param {string} absBefore Unix epoch (in seconds) as a string + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateBeforeAbsoluteTime", + value: function predicateBeforeAbsoluteTime(absBefore) { + return _xdr["default"].ClaimPredicate.claimPredicateBeforeAbsoluteTime(_xdr["default"].Int64.fromString(absBefore)); + } + + /** + * Returns a `BeforeRelativeTime` claim predicate + * + * This predicate will be fulfilled if the closing time of the ledger that + * includes the CreateClaimableBalance operation plus this relative time delta + * (in seconds) is less than the current time. + * + * @param {strings} seconds seconds since closeTime of the ledger in which the ClaimableBalanceEntry was created (as string) + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateBeforeRelativeTime", + value: function predicateBeforeRelativeTime(seconds) { + return _xdr["default"].ClaimPredicate.claimPredicateBeforeRelativeTime(_xdr["default"].Int64.fromString(seconds)); + } + + /** + * Returns a claimant object from its XDR object representation. + * @param {xdr.Claimant} claimantXdr - The claimant xdr object. + * @returns {Claimant} + */ + }, { + key: "fromXDR", + value: function fromXDR(claimantXdr) { + var value; + switch (claimantXdr["switch"]()) { + case _xdr["default"].ClaimantType.claimantTypeV0(): + value = claimantXdr.v0(); + return new this(_strkey.StrKey.encodeEd25519PublicKey(value.destination().ed25519()), value.predicate()); + default: + throw new Error("Invalid claimant type: ".concat(claimantXdr["switch"]().name)); + } + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/contract.js b/node_modules/@stellar/stellar-base/lib/contract.js new file mode 100644 index 000000000..cf8df59bc --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/contract.js @@ -0,0 +1,112 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Contract = void 0; +var _address = require("./address"); +var _operation = require("./operation"); +var _xdr = _interopRequireDefault(require("./xdr")); +var _strkey = require("./strkey"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Contract object. + * + * `Contract` represents a single contract in the Stellar network, embodying the + * interface of the contract. See + * [Contracts](https://soroban.stellar.org/docs/learn/interacting-with-contracts) + * for more information about how contracts work in Stellar. + * + * @constructor + * + * @param {string} contractId - ID of the contract (ex. + * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`). + */ +var Contract = exports.Contract = /*#__PURE__*/function () { + function Contract(contractId) { + _classCallCheck(this, Contract); + try { + // First, try it as a strkey + this._id = _strkey.StrKey.decodeContract(contractId); + } catch (_) { + throw new Error("Invalid contract ID: ".concat(contractId)); + } + } + + /** + * Returns Stellar contract ID as a strkey, ex. + * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`. + * @returns {string} + */ + return _createClass(Contract, [{ + key: "contractId", + value: function contractId() { + return _strkey.StrKey.encodeContract(this._id); + } + + /** @returns {string} the ID as a strkey (C...) */ + }, { + key: "toString", + value: function toString() { + return this.contractId(); + } + + /** @returns {Address} the wrapped address of this contract */ + }, { + key: "address", + value: function address() { + return _address.Address.contract(this._id); + } + + /** + * Returns an operation that will invoke this contract call. + * + * @param {string} method name of the method to call + * @param {...xdr.ScVal} params arguments to pass to the function call + * + * @returns {xdr.Operation} an InvokeHostFunctionOp operation to call the + * contract with the given method and parameters + * + * @see Operation.invokeHostFunction + * @see Operation.invokeContractFunction + * @see Operation.createCustomContract + * @see Operation.createStellarAssetContract + * @see Operation.uploadContractWasm + */ + }, { + key: "call", + value: function call(method) { + for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + params[_key - 1] = arguments[_key]; + } + return _operation.Operation.invokeContractFunction({ + contract: this.address().toString(), + "function": method, + args: params + }); + } + + /** + * Returns the read-only footprint entries necessary for any invocations to + * this contract, for convenience when manually adding it to your + * transaction's overall footprint or doing bump/restore operations. + * + * @returns {xdr.LedgerKey} the ledger key for the deployed contract instance + */ + }, { + key: "getFootprint", + value: function getFootprint() { + return _xdr["default"].LedgerKey.contractData(new _xdr["default"].LedgerKeyContractData({ + contract: this.address().toScAddress(), + key: _xdr["default"].ScVal.scvLedgerKeyContractInstance(), + durability: _xdr["default"].ContractDataDurability.persistent() + })); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/events.js b/node_modules/@stellar/stellar-base/lib/events.js new file mode 100644 index 000000000..5ae406359 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/events.js @@ -0,0 +1,49 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.humanizeEvents = humanizeEvents; +var _strkey = require("./strkey"); +var _scval = require("./scval"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Converts raw diagnostic or contract events into something with a flatter, + * human-readable, and understandable structure. + * + * @param {xdr.DiagnosticEvent[] | xdr.ContractEvent[]} events either contract + * events or diagnostic events to parse into a friendly format + * + * @returns {SorobanEvent[]} a list of human-readable event structures, where + * each element has the following properties: + * - type: a string of one of 'system', 'contract', 'diagnostic + * - contractId?: optionally, a `C...` encoded strkey + * - topics: a list of {@link scValToNative} invocations on the topics + * - data: similarly, a {@link scValToNative} invocation on the raw event data + */ +function humanizeEvents(events) { + return events.map(function (e) { + // A pseudo-instanceof check for xdr.DiagnosticEvent more reliable + // in mixed SDK environments: + if (e.inSuccessfulContractCall) { + return extractEvent(e.event()); + } + return extractEvent(e); + }); +} +function extractEvent(event) { + return _objectSpread(_objectSpread({}, typeof event.contractId === 'function' && event.contractId() != null && { + contractId: _strkey.StrKey.encodeContract(event.contractId()) + }), {}, { + type: event.type().name, + topics: event.body().value().topics().map(function (t) { + return (0, _scval.scValToNative)(t); + }), + data: (0, _scval.scValToNative)(event.body().value().data()) + }); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/fee_bump_transaction.js b/node_modules/@stellar/stellar-base/lib/fee_bump_transaction.js new file mode 100644 index 000000000..640c23fb7 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/fee_bump_transaction.js @@ -0,0 +1,132 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FeeBumpTransaction = void 0; +var _xdr = _interopRequireDefault(require("./xdr")); +var _hashing = require("./hashing"); +var _transaction = require("./transaction"); +var _transaction_base = require("./transaction_base"); +var _decode_encode_muxed_account = require("./util/decode_encode_muxed_account"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Use {@link TransactionBuilder.buildFeeBumpTransaction} to build a + * FeeBumpTransaction object. If you have an object or base64-encoded string of + * the transaction envelope XDR use {@link TransactionBuilder.fromXDR}. + * + * Once a {@link FeeBumpTransaction} has been created, its attributes and operations + * should not be changed. You should only add signatures (using {@link FeeBumpTransaction#sign}) before + * submitting to the network or forwarding on to additional signers. + * + * @param {string|xdr.TransactionEnvelope} envelope - transaction envelope + * object or base64 encoded string. + * @param {string} networkPassphrase - passphrase of the target Stellar network + * (e.g. "Public Global Stellar Network ; September 2015"). + * + * @extends TransactionBase + */ +var FeeBumpTransaction = exports.FeeBumpTransaction = /*#__PURE__*/function (_TransactionBase) { + function FeeBumpTransaction(envelope, networkPassphrase) { + var _this; + _classCallCheck(this, FeeBumpTransaction); + if (typeof envelope === 'string') { + var buffer = Buffer.from(envelope, 'base64'); + envelope = _xdr["default"].TransactionEnvelope.fromXDR(buffer); + } + var envelopeType = envelope["switch"](); + if (envelopeType !== _xdr["default"].EnvelopeType.envelopeTypeTxFeeBump()) { + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxFeeBump but received an ".concat(envelopeType.name, ".")); + } + var txEnvelope = envelope.value(); + var tx = txEnvelope.tx(); + var fee = tx.fee().toString(); + // clone signatures + var signatures = (txEnvelope.signatures() || []).slice(); + _this = _callSuper(this, FeeBumpTransaction, [tx, signatures, fee, networkPassphrase]); + var innerTxEnvelope = _xdr["default"].TransactionEnvelope.envelopeTypeTx(tx.innerTx().v1()); + _this._feeSource = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(_this.tx.feeSource()); + _this._innerTransaction = new _transaction.Transaction(innerTxEnvelope, networkPassphrase); + return _this; + } + + /** + * @type {Transaction} + * @readonly + */ + _inherits(FeeBumpTransaction, _TransactionBase); + return _createClass(FeeBumpTransaction, [{ + key: "innerTransaction", + get: function get() { + return this._innerTransaction; + } + + /** + * @type {Operation[]} + * @readonly + */ + }, { + key: "operations", + get: function get() { + return this._innerTransaction.operations; + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "feeSource", + get: function get() { + return this._feeSource; + } + + /** + * Returns the "signature base" of this transaction, which is the value + * that, when hashed, should be signed to create a signature that + * validators on the Stellar Network will accept. + * + * It is composed of a 4 prefix bytes followed by the xdr-encoded form + * of this transaction. + * @returns {Buffer} + */ + }, { + key: "signatureBase", + value: function signatureBase() { + var taggedTransaction = new _xdr["default"].TransactionSignaturePayloadTaggedTransaction.envelopeTypeTxFeeBump(this.tx); + var txSignature = new _xdr["default"].TransactionSignaturePayload({ + networkId: _xdr["default"].Hash.fromXDR((0, _hashing.hash)(this.networkPassphrase)), + taggedTransaction: taggedTransaction + }); + return txSignature.toXDR(); + } + + /** + * To envelope returns a xdr.TransactionEnvelope which can be submitted to the network. + * @returns {xdr.TransactionEnvelope} + */ + }, { + key: "toEnvelope", + value: function toEnvelope() { + var envelope = new _xdr["default"].FeeBumpTransactionEnvelope({ + tx: _xdr["default"].FeeBumpTransaction.fromXDR(this.tx.toXDR()), + // make a copy of the tx + signatures: this.signatures.slice() // make a copy of the signatures + }); + return new _xdr["default"].TransactionEnvelope.envelopeTypeTxFeeBump(envelope); + } + }]); +}(_transaction_base.TransactionBase); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/generated/curr_generated.js b/node_modules/@stellar/stellar-base/lib/generated/curr_generated.js new file mode 100644 index 000000000..7c299ed7e --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/generated/curr_generated.js @@ -0,0 +1,9166 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var XDR = _interopRequireWildcard(require("@stellar/js-xdr")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +// Automatically generated by xdrgen on 2024-09-12T11:09:00-08:00 +// DO NOT EDIT or your changes may be overwritten + +/* jshint maxstatements:2147483647 */ +/* jshint esnext:true */ + +var types = XDR.config(function (xdr) { + // Workaround for https://github.com/stellar/xdrgen/issues/152 + // + // The "correct" way would be to replace bare instances of each constant with + // xdr.lookup("..."), but that's more error-prone. + var SCSYMBOL_LIMIT = 32; + var SC_SPEC_DOC_LIMIT = 1024; + + // === xdr source ============================================================ + // + // typedef opaque Value<>; + // + // =========================================================================== + xdr.typedef("Value", xdr.varOpaque()); + + // === xdr source ============================================================ + // + // struct SCPBallot + // { + // uint32 counter; // n + // Value value; // x + // }; + // + // =========================================================================== + xdr.struct("ScpBallot", [["counter", xdr.lookup("Uint32")], ["value", xdr.lookup("Value")]]); + + // === xdr source ============================================================ + // + // enum SCPStatementType + // { + // SCP_ST_PREPARE = 0, + // SCP_ST_CONFIRM = 1, + // SCP_ST_EXTERNALIZE = 2, + // SCP_ST_NOMINATE = 3 + // }; + // + // =========================================================================== + xdr["enum"]("ScpStatementType", { + scpStPrepare: 0, + scpStConfirm: 1, + scpStExternalize: 2, + scpStNominate: 3 + }); + + // === xdr source ============================================================ + // + // struct SCPNomination + // { + // Hash quorumSetHash; // D + // Value votes<>; // X + // Value accepted<>; // Y + // }; + // + // =========================================================================== + xdr.struct("ScpNomination", [["quorumSetHash", xdr.lookup("Hash")], ["votes", xdr.varArray(xdr.lookup("Value"), 2147483647)], ["accepted", xdr.varArray(xdr.lookup("Value"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } + // + // =========================================================================== + xdr.struct("ScpStatementPrepare", [["quorumSetHash", xdr.lookup("Hash")], ["ballot", xdr.lookup("ScpBallot")], ["prepared", xdr.option(xdr.lookup("ScpBallot"))], ["preparedPrime", xdr.option(xdr.lookup("ScpBallot"))], ["nC", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } + // + // =========================================================================== + xdr.struct("ScpStatementConfirm", [["ballot", xdr.lookup("ScpBallot")], ["nPrepared", xdr.lookup("Uint32")], ["nCommit", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")], ["quorumSetHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } + // + // =========================================================================== + xdr.struct("ScpStatementExternalize", [["commit", xdr.lookup("ScpBallot")], ["nH", xdr.lookup("Uint32")], ["commitQuorumSetHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union switch (SCPStatementType type) + // { + // case SCP_ST_PREPARE: + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } prepare; + // case SCP_ST_CONFIRM: + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } confirm; + // case SCP_ST_EXTERNALIZE: + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } externalize; + // case SCP_ST_NOMINATE: + // SCPNomination nominate; + // } + // + // =========================================================================== + xdr.union("ScpStatementPledges", { + switchOn: xdr.lookup("ScpStatementType"), + switchName: "type", + switches: [["scpStPrepare", "prepare"], ["scpStConfirm", "confirm"], ["scpStExternalize", "externalize"], ["scpStNominate", "nominate"]], + arms: { + prepare: xdr.lookup("ScpStatementPrepare"), + confirm: xdr.lookup("ScpStatementConfirm"), + externalize: xdr.lookup("ScpStatementExternalize"), + nominate: xdr.lookup("ScpNomination") + } + }); + + // === xdr source ============================================================ + // + // struct SCPStatement + // { + // NodeID nodeID; // v + // uint64 slotIndex; // i + // + // union switch (SCPStatementType type) + // { + // case SCP_ST_PREPARE: + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } prepare; + // case SCP_ST_CONFIRM: + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } confirm; + // case SCP_ST_EXTERNALIZE: + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } externalize; + // case SCP_ST_NOMINATE: + // SCPNomination nominate; + // } + // pledges; + // }; + // + // =========================================================================== + xdr.struct("ScpStatement", [["nodeId", xdr.lookup("NodeId")], ["slotIndex", xdr.lookup("Uint64")], ["pledges", xdr.lookup("ScpStatementPledges")]]); + + // === xdr source ============================================================ + // + // struct SCPEnvelope + // { + // SCPStatement statement; + // Signature signature; + // }; + // + // =========================================================================== + xdr.struct("ScpEnvelope", [["statement", xdr.lookup("ScpStatement")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // struct SCPQuorumSet + // { + // uint32 threshold; + // NodeID validators<>; + // SCPQuorumSet innerSets<>; + // }; + // + // =========================================================================== + xdr.struct("ScpQuorumSet", [["threshold", xdr.lookup("Uint32")], ["validators", xdr.varArray(xdr.lookup("NodeId"), 2147483647)], ["innerSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)]]); + + // === xdr source ============================================================ + // + // typedef opaque Thresholds[4]; + // + // =========================================================================== + xdr.typedef("Thresholds", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef string string32<32>; + // + // =========================================================================== + xdr.typedef("String32", xdr.string(32)); + + // === xdr source ============================================================ + // + // typedef string string64<64>; + // + // =========================================================================== + xdr.typedef("String64", xdr.string(64)); + + // === xdr source ============================================================ + // + // typedef int64 SequenceNumber; + // + // =========================================================================== + xdr.typedef("SequenceNumber", xdr.lookup("Int64")); + + // === xdr source ============================================================ + // + // typedef opaque DataValue<64>; + // + // =========================================================================== + xdr.typedef("DataValue", xdr.varOpaque(64)); + + // === xdr source ============================================================ + // + // typedef Hash PoolID; + // + // =========================================================================== + xdr.typedef("PoolId", xdr.lookup("Hash")); + + // === xdr source ============================================================ + // + // typedef opaque AssetCode4[4]; + // + // =========================================================================== + xdr.typedef("AssetCode4", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef opaque AssetCode12[12]; + // + // =========================================================================== + xdr.typedef("AssetCode12", xdr.opaque(12)); + + // === xdr source ============================================================ + // + // enum AssetType + // { + // ASSET_TYPE_NATIVE = 0, + // ASSET_TYPE_CREDIT_ALPHANUM4 = 1, + // ASSET_TYPE_CREDIT_ALPHANUM12 = 2, + // ASSET_TYPE_POOL_SHARE = 3 + // }; + // + // =========================================================================== + xdr["enum"]("AssetType", { + assetTypeNative: 0, + assetTypeCreditAlphanum4: 1, + assetTypeCreditAlphanum12: 2, + assetTypePoolShare: 3 + }); + + // === xdr source ============================================================ + // + // union AssetCode switch (AssetType type) + // { + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AssetCode4 assetCode4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AssetCode12 assetCode12; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("AssetCode", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeCreditAlphanum4", "assetCode4"], ["assetTypeCreditAlphanum12", "assetCode12"]], + arms: { + assetCode4: xdr.lookup("AssetCode4"), + assetCode12: xdr.lookup("AssetCode12") + } + }); + + // === xdr source ============================================================ + // + // struct AlphaNum4 + // { + // AssetCode4 assetCode; + // AccountID issuer; + // }; + // + // =========================================================================== + xdr.struct("AlphaNum4", [["assetCode", xdr.lookup("AssetCode4")], ["issuer", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // struct AlphaNum12 + // { + // AssetCode12 assetCode; + // AccountID issuer; + // }; + // + // =========================================================================== + xdr.struct("AlphaNum12", [["assetCode", xdr.lookup("AssetCode12")], ["issuer", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // union Asset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("Asset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12") + } + }); + + // === xdr source ============================================================ + // + // struct Price + // { + // int32 n; // numerator + // int32 d; // denominator + // }; + // + // =========================================================================== + xdr.struct("Price", [["n", xdr.lookup("Int32")], ["d", xdr.lookup("Int32")]]); + + // === xdr source ============================================================ + // + // struct Liabilities + // { + // int64 buying; + // int64 selling; + // }; + // + // =========================================================================== + xdr.struct("Liabilities", [["buying", xdr.lookup("Int64")], ["selling", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum ThresholdIndexes + // { + // THRESHOLD_MASTER_WEIGHT = 0, + // THRESHOLD_LOW = 1, + // THRESHOLD_MED = 2, + // THRESHOLD_HIGH = 3 + // }; + // + // =========================================================================== + xdr["enum"]("ThresholdIndices", { + thresholdMasterWeight: 0, + thresholdLow: 1, + thresholdMed: 2, + thresholdHigh: 3 + }); + + // === xdr source ============================================================ + // + // enum LedgerEntryType + // { + // ACCOUNT = 0, + // TRUSTLINE = 1, + // OFFER = 2, + // DATA = 3, + // CLAIMABLE_BALANCE = 4, + // LIQUIDITY_POOL = 5, + // CONTRACT_DATA = 6, + // CONTRACT_CODE = 7, + // CONFIG_SETTING = 8, + // TTL = 9 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerEntryType", { + account: 0, + trustline: 1, + offer: 2, + data: 3, + claimableBalance: 4, + liquidityPool: 5, + contractData: 6, + contractCode: 7, + configSetting: 8, + ttl: 9 + }); + + // === xdr source ============================================================ + // + // struct Signer + // { + // SignerKey key; + // uint32 weight; // really only need 1 byte + // }; + // + // =========================================================================== + xdr.struct("Signer", [["key", xdr.lookup("SignerKey")], ["weight", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // enum AccountFlags + // { // masks for each flag + // + // // Flags set on issuer accounts + // // TrustLines are created with authorized set to "false" requiring + // // the issuer to set it for each TrustLine + // AUTH_REQUIRED_FLAG = 0x1, + // // If set, the authorized flag in TrustLines can be cleared + // // otherwise, authorization cannot be revoked + // AUTH_REVOCABLE_FLAG = 0x2, + // // Once set, causes all AUTH_* flags to be read-only + // AUTH_IMMUTABLE_FLAG = 0x4, + // // Trustlines are created with clawback enabled set to "true", + // // and claimable balances created from those trustlines are created + // // with clawback enabled set to "true" + // AUTH_CLAWBACK_ENABLED_FLAG = 0x8 + // }; + // + // =========================================================================== + xdr["enum"]("AccountFlags", { + authRequiredFlag: 1, + authRevocableFlag: 2, + authImmutableFlag: 4, + authClawbackEnabledFlag: 8 + }); + + // === xdr source ============================================================ + // + // const MASK_ACCOUNT_FLAGS = 0x7; + // + // =========================================================================== + xdr["const"]("MASK_ACCOUNT_FLAGS", 0x7); + + // === xdr source ============================================================ + // + // const MASK_ACCOUNT_FLAGS_V17 = 0xF; + // + // =========================================================================== + xdr["const"]("MASK_ACCOUNT_FLAGS_V17", 0xF); + + // === xdr source ============================================================ + // + // const MAX_SIGNERS = 20; + // + // =========================================================================== + xdr["const"]("MAX_SIGNERS", 20); + + // === xdr source ============================================================ + // + // typedef AccountID* SponsorshipDescriptor; + // + // =========================================================================== + xdr.typedef("SponsorshipDescriptor", xdr.option(xdr.lookup("AccountId"))); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV3 + // { + // // We can use this to add more fields, or because it is first, to + // // change AccountEntryExtensionV3 into a union. + // ExtensionPoint ext; + // + // // Ledger number at which `seqNum` took on its present value. + // uint32 seqLedger; + // + // // Time at which `seqNum` took on its present value. + // TimePoint seqTime; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV3", [["ext", xdr.lookup("ExtensionPoint")], ["seqLedger", xdr.lookup("Uint32")], ["seqTime", xdr.lookup("TimePoint")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 3: + // AccountEntryExtensionV3 v3; + // } + // + // =========================================================================== + xdr.union("AccountEntryExtensionV2Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [3, "v3"]], + arms: { + v3: xdr.lookup("AccountEntryExtensionV3") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV2 + // { + // uint32 numSponsored; + // uint32 numSponsoring; + // SponsorshipDescriptor signerSponsoringIDs; + // + // union switch (int v) + // { + // case 0: + // void; + // case 3: + // AccountEntryExtensionV3 v3; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV2", [["numSponsored", xdr.lookup("Uint32")], ["numSponsoring", xdr.lookup("Uint32")], ["signerSponsoringIDs", xdr.varArray(xdr.lookup("SponsorshipDescriptor"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExtensionV2Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // AccountEntryExtensionV2 v2; + // } + // + // =========================================================================== + xdr.union("AccountEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [2, "v2"]], + arms: { + v2: xdr.lookup("AccountEntryExtensionV2") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV1 + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // AccountEntryExtensionV2 v2; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("AccountEntryExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // AccountEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("AccountEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("AccountEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntry + // { + // AccountID accountID; // master public key for this account + // int64 balance; // in stroops + // SequenceNumber seqNum; // last sequence number used for this account + // uint32 numSubEntries; // number of sub-entries this account has + // // drives the reserve + // AccountID* inflationDest; // Account to vote for during inflation + // uint32 flags; // see AccountFlags + // + // string32 homeDomain; // can be used for reverse federation and memo lookup + // + // // fields used for signatures + // // thresholds stores unsigned bytes: [weight of master|low|medium|high] + // Thresholds thresholds; + // + // Signer signers; // possible signers for this account + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // AccountEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntry", [["accountId", xdr.lookup("AccountId")], ["balance", xdr.lookup("Int64")], ["seqNum", xdr.lookup("SequenceNumber")], ["numSubEntries", xdr.lookup("Uint32")], ["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["flags", xdr.lookup("Uint32")], ["homeDomain", xdr.lookup("String32")], ["thresholds", xdr.lookup("Thresholds")], ["signers", xdr.varArray(xdr.lookup("Signer"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExt")]]); + + // === xdr source ============================================================ + // + // enum TrustLineFlags + // { + // // issuer has authorized account to perform transactions with its credit + // AUTHORIZED_FLAG = 1, + // // issuer has authorized account to maintain and reduce liabilities for its + // // credit + // AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG = 2, + // // issuer has specified that it may clawback its credit, and that claimable + // // balances created with its credit may also be clawed back + // TRUSTLINE_CLAWBACK_ENABLED_FLAG = 4 + // }; + // + // =========================================================================== + xdr["enum"]("TrustLineFlags", { + authorizedFlag: 1, + authorizedToMaintainLiabilitiesFlag: 2, + trustlineClawbackEnabledFlag: 4 + }); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS = 1; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS", 1); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS_V13 = 3; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS_V13", 3); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS_V17 = 7; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS_V17", 7); + + // === xdr source ============================================================ + // + // enum LiquidityPoolType + // { + // LIQUIDITY_POOL_CONSTANT_PRODUCT = 0 + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolType", { + liquidityPoolConstantProduct: 0 + }); + + // === xdr source ============================================================ + // + // union TrustLineAsset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // case ASSET_TYPE_POOL_SHARE: + // PoolID liquidityPoolID; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("TrustLineAsset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPoolId"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12"), + liquidityPoolId: xdr.lookup("PoolId") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryExtensionV2Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TrustLineEntryExtensionV2 + // { + // int32 liquidityPoolUseCount; + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TrustLineEntryExtensionV2", [["liquidityPoolUseCount", xdr.lookup("Int32")], ["ext", xdr.lookup("TrustLineEntryExtensionV2Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [2, "v2"]], + arms: { + v2: xdr.lookup("TrustLineEntryExtensionV2") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } + // + // =========================================================================== + xdr.struct("TrustLineEntryV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("TrustLineEntryV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } v1; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("TrustLineEntryV1") + } + }); + + // === xdr source ============================================================ + // + // struct TrustLineEntry + // { + // AccountID accountID; // account this trustline belongs to + // TrustLineAsset asset; // type of asset (with issuer) + // int64 balance; // how much of this asset the user has. + // // Asset defines the unit for this; + // + // int64 limit; // balance cannot be above this + // uint32 flags; // see TrustLineFlags + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TrustLineEntry", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")], ["balance", xdr.lookup("Int64")], ["limit", xdr.lookup("Int64")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("TrustLineEntryExt")]]); + + // === xdr source ============================================================ + // + // enum OfferEntryFlags + // { + // // an offer with this flag will not act on and take a reverse offer of equal + // // price + // PASSIVE_FLAG = 1 + // }; + // + // =========================================================================== + xdr["enum"]("OfferEntryFlags", { + passiveFlag: 1 + }); + + // === xdr source ============================================================ + // + // const MASK_OFFERENTRY_FLAGS = 1; + // + // =========================================================================== + xdr["const"]("MASK_OFFERENTRY_FLAGS", 1); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("OfferEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct OfferEntry + // { + // AccountID sellerID; + // int64 offerID; + // Asset selling; // A + // Asset buying; // B + // int64 amount; // amount of A + // + // /* price for this offer: + // price of A in terms of B + // price=AmountB/AmountA=priceNumerator/priceDenominator + // price is after fees + // */ + // Price price; + // uint32 flags; // see OfferEntryFlags + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("OfferEntry", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("OfferEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("DataEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct DataEntry + // { + // AccountID accountID; // account this data belongs to + // string64 dataName; + // DataValue dataValue; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("DataEntry", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")], ["dataValue", xdr.lookup("DataValue")], ["ext", xdr.lookup("DataEntryExt")]]); + + // === xdr source ============================================================ + // + // enum ClaimPredicateType + // { + // CLAIM_PREDICATE_UNCONDITIONAL = 0, + // CLAIM_PREDICATE_AND = 1, + // CLAIM_PREDICATE_OR = 2, + // CLAIM_PREDICATE_NOT = 3, + // CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME = 4, + // CLAIM_PREDICATE_BEFORE_RELATIVE_TIME = 5 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimPredicateType", { + claimPredicateUnconditional: 0, + claimPredicateAnd: 1, + claimPredicateOr: 2, + claimPredicateNot: 3, + claimPredicateBeforeAbsoluteTime: 4, + claimPredicateBeforeRelativeTime: 5 + }); + + // === xdr source ============================================================ + // + // union ClaimPredicate switch (ClaimPredicateType type) + // { + // case CLAIM_PREDICATE_UNCONDITIONAL: + // void; + // case CLAIM_PREDICATE_AND: + // ClaimPredicate andPredicates<2>; + // case CLAIM_PREDICATE_OR: + // ClaimPredicate orPredicates<2>; + // case CLAIM_PREDICATE_NOT: + // ClaimPredicate* notPredicate; + // case CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME: + // int64 absBefore; // Predicate will be true if closeTime < absBefore + // case CLAIM_PREDICATE_BEFORE_RELATIVE_TIME: + // int64 relBefore; // Seconds since closeTime of the ledger in which the + // // ClaimableBalanceEntry was created + // }; + // + // =========================================================================== + xdr.union("ClaimPredicate", { + switchOn: xdr.lookup("ClaimPredicateType"), + switchName: "type", + switches: [["claimPredicateUnconditional", xdr["void"]()], ["claimPredicateAnd", "andPredicates"], ["claimPredicateOr", "orPredicates"], ["claimPredicateNot", "notPredicate"], ["claimPredicateBeforeAbsoluteTime", "absBefore"], ["claimPredicateBeforeRelativeTime", "relBefore"]], + arms: { + andPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2), + orPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2), + notPredicate: xdr.option(xdr.lookup("ClaimPredicate")), + absBefore: xdr.lookup("Int64"), + relBefore: xdr.lookup("Int64") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimantType + // { + // CLAIMANT_TYPE_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimantType", { + claimantTypeV0: 0 + }); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID destination; // The account that can use this condition + // ClaimPredicate predicate; // Claimable if predicate is true + // } + // + // =========================================================================== + xdr.struct("ClaimantV0", [["destination", xdr.lookup("AccountId")], ["predicate", xdr.lookup("ClaimPredicate")]]); + + // === xdr source ============================================================ + // + // union Claimant switch (ClaimantType type) + // { + // case CLAIMANT_TYPE_V0: + // struct + // { + // AccountID destination; // The account that can use this condition + // ClaimPredicate predicate; // Claimable if predicate is true + // } v0; + // }; + // + // =========================================================================== + xdr.union("Claimant", { + switchOn: xdr.lookup("ClaimantType"), + switchName: "type", + switches: [["claimantTypeV0", "v0"]], + arms: { + v0: xdr.lookup("ClaimantV0") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimableBalanceIDType + // { + // CLAIMABLE_BALANCE_ID_TYPE_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimableBalanceIdType", { + claimableBalanceIdTypeV0: 0 + }); + + // === xdr source ============================================================ + // + // union ClaimableBalanceID switch (ClaimableBalanceIDType type) + // { + // case CLAIMABLE_BALANCE_ID_TYPE_V0: + // Hash v0; + // }; + // + // =========================================================================== + xdr.union("ClaimableBalanceId", { + switchOn: xdr.lookup("ClaimableBalanceIdType"), + switchName: "type", + switches: [["claimableBalanceIdTypeV0", "v0"]], + arms: { + v0: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimableBalanceFlags + // { + // // If set, the issuer account of the asset held by the claimable balance may + // // clawback the claimable balance + // CLAIMABLE_BALANCE_CLAWBACK_ENABLED_FLAG = 0x1 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimableBalanceFlags", { + claimableBalanceClawbackEnabledFlag: 1 + }); + + // === xdr source ============================================================ + // + // const MASK_CLAIMABLE_BALANCE_FLAGS = 0x1; + // + // =========================================================================== + xdr["const"]("MASK_CLAIMABLE_BALANCE_FLAGS", 0x1); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("ClaimableBalanceEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct ClaimableBalanceEntryExtensionV1 + // { + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // + // uint32 flags; // see ClaimableBalanceFlags + // }; + // + // =========================================================================== + xdr.struct("ClaimableBalanceEntryExtensionV1", [["ext", xdr.lookup("ClaimableBalanceEntryExtensionV1Ext")], ["flags", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ClaimableBalanceEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("ClaimableBalanceEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("ClaimableBalanceEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct ClaimableBalanceEntry + // { + // // Unique identifier for this ClaimableBalanceEntry + // ClaimableBalanceID balanceID; + // + // // List of claimants with associated predicate + // Claimant claimants<10>; + // + // // Any asset including native + // Asset asset; + // + // // Amount of asset + // int64 amount; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ClaimableBalanceEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("ClaimableBalanceEntry", [["balanceId", xdr.lookup("ClaimableBalanceId")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["ext", xdr.lookup("ClaimableBalanceEntryExt")]]); + + // === xdr source ============================================================ + // + // struct LiquidityPoolConstantProductParameters + // { + // Asset assetA; // assetA < assetB + // Asset assetB; + // int32 fee; // Fee is in basis points, so the actual rate is (fee/100)% + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolConstantProductParameters", [["assetA", xdr.lookup("Asset")], ["assetB", xdr.lookup("Asset")], ["fee", xdr.lookup("Int32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } + // + // =========================================================================== + xdr.struct("LiquidityPoolEntryConstantProduct", [["params", xdr.lookup("LiquidityPoolConstantProductParameters")], ["reserveA", xdr.lookup("Int64")], ["reserveB", xdr.lookup("Int64")], ["totalPoolShares", xdr.lookup("Int64")], ["poolSharesTrustLineCount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } constantProduct; + // } + // + // =========================================================================== + xdr.union("LiquidityPoolEntryBody", { + switchOn: xdr.lookup("LiquidityPoolType"), + switchName: "type", + switches: [["liquidityPoolConstantProduct", "constantProduct"]], + arms: { + constantProduct: xdr.lookup("LiquidityPoolEntryConstantProduct") + } + }); + + // === xdr source ============================================================ + // + // struct LiquidityPoolEntry + // { + // PoolID liquidityPoolID; + // + // union switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } constantProduct; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolEntry", [["liquidityPoolId", xdr.lookup("PoolId")], ["body", xdr.lookup("LiquidityPoolEntryBody")]]); + + // === xdr source ============================================================ + // + // enum ContractDataDurability { + // TEMPORARY = 0, + // PERSISTENT = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractDataDurability", { + temporary: 0, + persistent: 1 + }); + + // === xdr source ============================================================ + // + // struct ContractDataEntry { + // ExtensionPoint ext; + // + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // SCVal val; + // }; + // + // =========================================================================== + xdr.struct("ContractDataEntry", [["ext", xdr.lookup("ExtensionPoint")], ["contract", xdr.lookup("ScAddress")], ["key", xdr.lookup("ScVal")], ["durability", xdr.lookup("ContractDataDurability")], ["val", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // struct ContractCodeCostInputs { + // ExtensionPoint ext; + // uint32 nInstructions; + // uint32 nFunctions; + // uint32 nGlobals; + // uint32 nTableEntries; + // uint32 nTypes; + // uint32 nDataSegments; + // uint32 nElemSegments; + // uint32 nImports; + // uint32 nExports; + // uint32 nDataSegmentBytes; + // }; + // + // =========================================================================== + xdr.struct("ContractCodeCostInputs", [["ext", xdr.lookup("ExtensionPoint")], ["nInstructions", xdr.lookup("Uint32")], ["nFunctions", xdr.lookup("Uint32")], ["nGlobals", xdr.lookup("Uint32")], ["nTableEntries", xdr.lookup("Uint32")], ["nTypes", xdr.lookup("Uint32")], ["nDataSegments", xdr.lookup("Uint32")], ["nElemSegments", xdr.lookup("Uint32")], ["nImports", xdr.lookup("Uint32")], ["nExports", xdr.lookup("Uint32")], ["nDataSegmentBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } + // + // =========================================================================== + xdr.struct("ContractCodeEntryV1", [["ext", xdr.lookup("ExtensionPoint")], ["costInputs", xdr.lookup("ContractCodeCostInputs")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } v1; + // } + // + // =========================================================================== + xdr.union("ContractCodeEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("ContractCodeEntryV1") + } + }); + + // === xdr source ============================================================ + // + // struct ContractCodeEntry { + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } v1; + // } ext; + // + // Hash hash; + // opaque code<>; + // }; + // + // =========================================================================== + xdr.struct("ContractCodeEntry", [["ext", xdr.lookup("ContractCodeEntryExt")], ["hash", xdr.lookup("Hash")], ["code", xdr.varOpaque()]]); + + // === xdr source ============================================================ + // + // struct TTLEntry { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // uint32 liveUntilLedgerSeq; + // }; + // + // =========================================================================== + xdr.struct("TtlEntry", [["keyHash", xdr.lookup("Hash")], ["liveUntilLedgerSeq", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerEntryExtensionV1 + // { + // SponsorshipDescriptor sponsoringID; + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerEntryExtensionV1", [["sponsoringId", xdr.lookup("SponsorshipDescriptor")], ["ext", xdr.lookup("LedgerEntryExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (LedgerEntryType type) + // { + // case ACCOUNT: + // AccountEntry account; + // case TRUSTLINE: + // TrustLineEntry trustLine; + // case OFFER: + // OfferEntry offer; + // case DATA: + // DataEntry data; + // case CLAIMABLE_BALANCE: + // ClaimableBalanceEntry claimableBalance; + // case LIQUIDITY_POOL: + // LiquidityPoolEntry liquidityPool; + // case CONTRACT_DATA: + // ContractDataEntry contractData; + // case CONTRACT_CODE: + // ContractCodeEntry contractCode; + // case CONFIG_SETTING: + // ConfigSettingEntry configSetting; + // case TTL: + // TTLEntry ttl; + // } + // + // =========================================================================== + xdr.union("LedgerEntryData", { + switchOn: xdr.lookup("LedgerEntryType"), + switchName: "type", + switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"], ["contractData", "contractData"], ["contractCode", "contractCode"], ["configSetting", "configSetting"], ["ttl", "ttl"]], + arms: { + account: xdr.lookup("AccountEntry"), + trustLine: xdr.lookup("TrustLineEntry"), + offer: xdr.lookup("OfferEntry"), + data: xdr.lookup("DataEntry"), + claimableBalance: xdr.lookup("ClaimableBalanceEntry"), + liquidityPool: xdr.lookup("LiquidityPoolEntry"), + contractData: xdr.lookup("ContractDataEntry"), + contractCode: xdr.lookup("ContractCodeEntry"), + configSetting: xdr.lookup("ConfigSettingEntry"), + ttl: xdr.lookup("TtlEntry") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("LedgerEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerEntry + // { + // uint32 lastModifiedLedgerSeq; // ledger the LedgerEntry was last changed + // + // union switch (LedgerEntryType type) + // { + // case ACCOUNT: + // AccountEntry account; + // case TRUSTLINE: + // TrustLineEntry trustLine; + // case OFFER: + // OfferEntry offer; + // case DATA: + // DataEntry data; + // case CLAIMABLE_BALANCE: + // ClaimableBalanceEntry claimableBalance; + // case LIQUIDITY_POOL: + // LiquidityPoolEntry liquidityPool; + // case CONTRACT_DATA: + // ContractDataEntry contractData; + // case CONTRACT_CODE: + // ContractCodeEntry contractCode; + // case CONFIG_SETTING: + // ConfigSettingEntry configSetting; + // case TTL: + // TTLEntry ttl; + // } + // data; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerEntry", [["lastModifiedLedgerSeq", xdr.lookup("Uint32")], ["data", xdr.lookup("LedgerEntryData")], ["ext", xdr.lookup("LedgerEntryExt")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyAccount", [["accountId", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // TrustLineAsset asset; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyTrustLine", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sellerID; + // int64 offerID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyOffer", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // string64 dataName; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyData", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimableBalanceID balanceID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyClaimableBalance", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // PoolID liquidityPoolID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyLiquidityPool", [["liquidityPoolId", xdr.lookup("PoolId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyContractData", [["contract", xdr.lookup("ScAddress")], ["key", xdr.lookup("ScVal")], ["durability", xdr.lookup("ContractDataDurability")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash hash; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyContractCode", [["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ConfigSettingID configSettingID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyConfigSetting", [["configSettingId", xdr.lookup("ConfigSettingId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyTtl", [["keyHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union LedgerKey switch (LedgerEntryType type) + // { + // case ACCOUNT: + // struct + // { + // AccountID accountID; + // } account; + // + // case TRUSTLINE: + // struct + // { + // AccountID accountID; + // TrustLineAsset asset; + // } trustLine; + // + // case OFFER: + // struct + // { + // AccountID sellerID; + // int64 offerID; + // } offer; + // + // case DATA: + // struct + // { + // AccountID accountID; + // string64 dataName; + // } data; + // + // case CLAIMABLE_BALANCE: + // struct + // { + // ClaimableBalanceID balanceID; + // } claimableBalance; + // + // case LIQUIDITY_POOL: + // struct + // { + // PoolID liquidityPoolID; + // } liquidityPool; + // case CONTRACT_DATA: + // struct + // { + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // } contractData; + // case CONTRACT_CODE: + // struct + // { + // Hash hash; + // } contractCode; + // case CONFIG_SETTING: + // struct + // { + // ConfigSettingID configSettingID; + // } configSetting; + // case TTL: + // struct + // { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // } ttl; + // }; + // + // =========================================================================== + xdr.union("LedgerKey", { + switchOn: xdr.lookup("LedgerEntryType"), + switchName: "type", + switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"], ["contractData", "contractData"], ["contractCode", "contractCode"], ["configSetting", "configSetting"], ["ttl", "ttl"]], + arms: { + account: xdr.lookup("LedgerKeyAccount"), + trustLine: xdr.lookup("LedgerKeyTrustLine"), + offer: xdr.lookup("LedgerKeyOffer"), + data: xdr.lookup("LedgerKeyData"), + claimableBalance: xdr.lookup("LedgerKeyClaimableBalance"), + liquidityPool: xdr.lookup("LedgerKeyLiquidityPool"), + contractData: xdr.lookup("LedgerKeyContractData"), + contractCode: xdr.lookup("LedgerKeyContractCode"), + configSetting: xdr.lookup("LedgerKeyConfigSetting"), + ttl: xdr.lookup("LedgerKeyTtl") + } + }); + + // === xdr source ============================================================ + // + // enum EnvelopeType + // { + // ENVELOPE_TYPE_TX_V0 = 0, + // ENVELOPE_TYPE_SCP = 1, + // ENVELOPE_TYPE_TX = 2, + // ENVELOPE_TYPE_AUTH = 3, + // ENVELOPE_TYPE_SCPVALUE = 4, + // ENVELOPE_TYPE_TX_FEE_BUMP = 5, + // ENVELOPE_TYPE_OP_ID = 6, + // ENVELOPE_TYPE_POOL_REVOKE_OP_ID = 7, + // ENVELOPE_TYPE_CONTRACT_ID = 8, + // ENVELOPE_TYPE_SOROBAN_AUTHORIZATION = 9 + // }; + // + // =========================================================================== + xdr["enum"]("EnvelopeType", { + envelopeTypeTxV0: 0, + envelopeTypeScp: 1, + envelopeTypeTx: 2, + envelopeTypeAuth: 3, + envelopeTypeScpvalue: 4, + envelopeTypeTxFeeBump: 5, + envelopeTypeOpId: 6, + envelopeTypePoolRevokeOpId: 7, + envelopeTypeContractId: 8, + envelopeTypeSorobanAuthorization: 9 + }); + + // === xdr source ============================================================ + // + // enum BucketListType + // { + // LIVE = 0, + // HOT_ARCHIVE = 1, + // COLD_ARCHIVE = 2 + // }; + // + // =========================================================================== + xdr["enum"]("BucketListType", { + live: 0, + hotArchive: 1, + coldArchive: 2 + }); + + // === xdr source ============================================================ + // + // enum BucketEntryType + // { + // METAENTRY = + // -1, // At-and-after protocol 11: bucket metadata, should come first. + // LIVEENTRY = 0, // Before protocol 11: created-or-updated; + // // At-and-after protocol 11: only updated. + // DEADENTRY = 1, + // INITENTRY = 2 // At-and-after protocol 11: only created. + // }; + // + // =========================================================================== + xdr["enum"]("BucketEntryType", { + metaentry: -1, + liveentry: 0, + deadentry: 1, + initentry: 2 + }); + + // === xdr source ============================================================ + // + // enum HotArchiveBucketEntryType + // { + // HOT_ARCHIVE_METAENTRY = -1, // Bucket metadata, should come first. + // HOT_ARCHIVE_ARCHIVED = 0, // Entry is Archived + // HOT_ARCHIVE_LIVE = 1, // Entry was previously HOT_ARCHIVE_ARCHIVED, or HOT_ARCHIVE_DELETED, but + // // has been added back to the live BucketList. + // // Does not need to be persisted. + // HOT_ARCHIVE_DELETED = 2 // Entry deleted (Note: must be persisted in archive) + // }; + // + // =========================================================================== + xdr["enum"]("HotArchiveBucketEntryType", { + hotArchiveMetaentry: -1, + hotArchiveArchived: 0, + hotArchiveLive: 1, + hotArchiveDeleted: 2 + }); + + // === xdr source ============================================================ + // + // enum ColdArchiveBucketEntryType + // { + // COLD_ARCHIVE_METAENTRY = -1, // Bucket metadata, should come first. + // COLD_ARCHIVE_ARCHIVED_LEAF = 0, // Full LedgerEntry that was archived during the epoch + // COLD_ARCHIVE_DELETED_LEAF = 1, // LedgerKey that was deleted during the epoch + // COLD_ARCHIVE_BOUNDARY_LEAF = 2, // Dummy leaf representing low/high bound + // COLD_ARCHIVE_HASH = 3 // Intermediary Merkle hash entry + // }; + // + // =========================================================================== + xdr["enum"]("ColdArchiveBucketEntryType", { + coldArchiveMetaentry: -1, + coldArchiveArchivedLeaf: 0, + coldArchiveDeletedLeaf: 1, + coldArchiveBoundaryLeaf: 2, + coldArchiveHash: 3 + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // BucketListType bucketListType; + // } + // + // =========================================================================== + xdr.union("BucketMetadataExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "bucketListType"]], + arms: { + bucketListType: xdr.lookup("BucketListType") + } + }); + + // === xdr source ============================================================ + // + // struct BucketMetadata + // { + // // Indicates the protocol version used to create / merge this bucket. + // uint32 ledgerVersion; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // BucketListType bucketListType; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("BucketMetadata", [["ledgerVersion", xdr.lookup("Uint32")], ["ext", xdr.lookup("BucketMetadataExt")]]); + + // === xdr source ============================================================ + // + // union BucketEntry switch (BucketEntryType type) + // { + // case LIVEENTRY: + // case INITENTRY: + // LedgerEntry liveEntry; + // + // case DEADENTRY: + // LedgerKey deadEntry; + // case METAENTRY: + // BucketMetadata metaEntry; + // }; + // + // =========================================================================== + xdr.union("BucketEntry", { + switchOn: xdr.lookup("BucketEntryType"), + switchName: "type", + switches: [["liveentry", "liveEntry"], ["initentry", "liveEntry"], ["deadentry", "deadEntry"], ["metaentry", "metaEntry"]], + arms: { + liveEntry: xdr.lookup("LedgerEntry"), + deadEntry: xdr.lookup("LedgerKey"), + metaEntry: xdr.lookup("BucketMetadata") + } + }); + + // === xdr source ============================================================ + // + // union HotArchiveBucketEntry switch (HotArchiveBucketEntryType type) + // { + // case HOT_ARCHIVE_ARCHIVED: + // LedgerEntry archivedEntry; + // + // case HOT_ARCHIVE_LIVE: + // case HOT_ARCHIVE_DELETED: + // LedgerKey key; + // case HOT_ARCHIVE_METAENTRY: + // BucketMetadata metaEntry; + // }; + // + // =========================================================================== + xdr.union("HotArchiveBucketEntry", { + switchOn: xdr.lookup("HotArchiveBucketEntryType"), + switchName: "type", + switches: [["hotArchiveArchived", "archivedEntry"], ["hotArchiveLive", "key"], ["hotArchiveDeleted", "key"], ["hotArchiveMetaentry", "metaEntry"]], + arms: { + archivedEntry: xdr.lookup("LedgerEntry"), + key: xdr.lookup("LedgerKey"), + metaEntry: xdr.lookup("BucketMetadata") + } + }); + + // === xdr source ============================================================ + // + // struct ColdArchiveArchivedLeaf + // { + // uint32 index; + // LedgerEntry archivedEntry; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveArchivedLeaf", [["index", xdr.lookup("Uint32")], ["archivedEntry", xdr.lookup("LedgerEntry")]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveDeletedLeaf + // { + // uint32 index; + // LedgerKey deletedKey; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveDeletedLeaf", [["index", xdr.lookup("Uint32")], ["deletedKey", xdr.lookup("LedgerKey")]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveBoundaryLeaf + // { + // uint32 index; + // bool isLowerBound; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveBoundaryLeaf", [["index", xdr.lookup("Uint32")], ["isLowerBound", xdr.bool()]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveHashEntry + // { + // uint32 index; + // uint32 level; + // Hash hash; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveHashEntry", [["index", xdr.lookup("Uint32")], ["level", xdr.lookup("Uint32")], ["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union ColdArchiveBucketEntry switch (ColdArchiveBucketEntryType type) + // { + // case COLD_ARCHIVE_METAENTRY: + // BucketMetadata metaEntry; + // case COLD_ARCHIVE_ARCHIVED_LEAF: + // ColdArchiveArchivedLeaf archivedLeaf; + // case COLD_ARCHIVE_DELETED_LEAF: + // ColdArchiveDeletedLeaf deletedLeaf; + // case COLD_ARCHIVE_BOUNDARY_LEAF: + // ColdArchiveBoundaryLeaf boundaryLeaf; + // case COLD_ARCHIVE_HASH: + // ColdArchiveHashEntry hashEntry; + // }; + // + // =========================================================================== + xdr.union("ColdArchiveBucketEntry", { + switchOn: xdr.lookup("ColdArchiveBucketEntryType"), + switchName: "type", + switches: [["coldArchiveMetaentry", "metaEntry"], ["coldArchiveArchivedLeaf", "archivedLeaf"], ["coldArchiveDeletedLeaf", "deletedLeaf"], ["coldArchiveBoundaryLeaf", "boundaryLeaf"], ["coldArchiveHash", "hashEntry"]], + arms: { + metaEntry: xdr.lookup("BucketMetadata"), + archivedLeaf: xdr.lookup("ColdArchiveArchivedLeaf"), + deletedLeaf: xdr.lookup("ColdArchiveDeletedLeaf"), + boundaryLeaf: xdr.lookup("ColdArchiveBoundaryLeaf"), + hashEntry: xdr.lookup("ColdArchiveHashEntry") + } + }); + + // === xdr source ============================================================ + // + // typedef opaque UpgradeType<128>; + // + // =========================================================================== + xdr.typedef("UpgradeType", xdr.varOpaque(128)); + + // === xdr source ============================================================ + // + // enum StellarValueType + // { + // STELLAR_VALUE_BASIC = 0, + // STELLAR_VALUE_SIGNED = 1 + // }; + // + // =========================================================================== + xdr["enum"]("StellarValueType", { + stellarValueBasic: 0, + stellarValueSigned: 1 + }); + + // === xdr source ============================================================ + // + // struct LedgerCloseValueSignature + // { + // NodeID nodeID; // which node introduced the value + // Signature signature; // nodeID's signature + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseValueSignature", [["nodeId", xdr.lookup("NodeId")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // union switch (StellarValueType v) + // { + // case STELLAR_VALUE_BASIC: + // void; + // case STELLAR_VALUE_SIGNED: + // LedgerCloseValueSignature lcValueSignature; + // } + // + // =========================================================================== + xdr.union("StellarValueExt", { + switchOn: xdr.lookup("StellarValueType"), + switchName: "v", + switches: [["stellarValueBasic", xdr["void"]()], ["stellarValueSigned", "lcValueSignature"]], + arms: { + lcValueSignature: xdr.lookup("LedgerCloseValueSignature") + } + }); + + // === xdr source ============================================================ + // + // struct StellarValue + // { + // Hash txSetHash; // transaction set to apply to previous ledger + // TimePoint closeTime; // network close time + // + // // upgrades to apply to the previous ledger (usually empty) + // // this is a vector of encoded 'LedgerUpgrade' so that nodes can drop + // // unknown steps during consensus if needed. + // // see notes below on 'LedgerUpgrade' for more detail + // // max size is dictated by number of upgrade types (+ room for future) + // UpgradeType upgrades<6>; + // + // // reserved for future use + // union switch (StellarValueType v) + // { + // case STELLAR_VALUE_BASIC: + // void; + // case STELLAR_VALUE_SIGNED: + // LedgerCloseValueSignature lcValueSignature; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("StellarValue", [["txSetHash", xdr.lookup("Hash")], ["closeTime", xdr.lookup("TimePoint")], ["upgrades", xdr.varArray(xdr.lookup("UpgradeType"), 6)], ["ext", xdr.lookup("StellarValueExt")]]); + + // === xdr source ============================================================ + // + // const MASK_LEDGER_HEADER_FLAGS = 0x7; + // + // =========================================================================== + xdr["const"]("MASK_LEDGER_HEADER_FLAGS", 0x7); + + // === xdr source ============================================================ + // + // enum LedgerHeaderFlags + // { + // DISABLE_LIQUIDITY_POOL_TRADING_FLAG = 0x1, + // DISABLE_LIQUIDITY_POOL_DEPOSIT_FLAG = 0x2, + // DISABLE_LIQUIDITY_POOL_WITHDRAWAL_FLAG = 0x4 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerHeaderFlags", { + disableLiquidityPoolTradingFlag: 1, + disableLiquidityPoolDepositFlag: 2, + disableLiquidityPoolWithdrawalFlag: 4 + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerHeaderExtensionV1 + // { + // uint32 flags; // LedgerHeaderFlags + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeaderExtensionV1", [["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("LedgerHeaderExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerHeaderExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerHeaderExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerHeader + // { + // uint32 ledgerVersion; // the protocol version of the ledger + // Hash previousLedgerHash; // hash of the previous ledger header + // StellarValue scpValue; // what consensus agreed to + // Hash txSetResultHash; // the TransactionResultSet that led to this ledger + // Hash bucketListHash; // hash of the ledger state + // + // uint32 ledgerSeq; // sequence number of this ledger + // + // int64 totalCoins; // total number of stroops in existence. + // // 10,000,000 stroops in 1 XLM + // + // int64 feePool; // fees burned since last inflation run + // uint32 inflationSeq; // inflation sequence number + // + // uint64 idPool; // last used global ID, used for generating objects + // + // uint32 baseFee; // base fee per operation in stroops + // uint32 baseReserve; // account base reserve in stroops + // + // uint32 maxTxSetSize; // maximum size a transaction set can be + // + // Hash skipList[4]; // hashes of ledgers in the past. allows you to jump back + // // in time without walking the chain back ledger by ledger + // // each slot contains the oldest ledger that is mod of + // // either 50 5000 50000 or 500000 depending on index + // // skipList[0] mod(50), skipList[1] mod(5000), etc + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerHeaderExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeader", [["ledgerVersion", xdr.lookup("Uint32")], ["previousLedgerHash", xdr.lookup("Hash")], ["scpValue", xdr.lookup("StellarValue")], ["txSetResultHash", xdr.lookup("Hash")], ["bucketListHash", xdr.lookup("Hash")], ["ledgerSeq", xdr.lookup("Uint32")], ["totalCoins", xdr.lookup("Int64")], ["feePool", xdr.lookup("Int64")], ["inflationSeq", xdr.lookup("Uint32")], ["idPool", xdr.lookup("Uint64")], ["baseFee", xdr.lookup("Uint32")], ["baseReserve", xdr.lookup("Uint32")], ["maxTxSetSize", xdr.lookup("Uint32")], ["skipList", xdr.array(xdr.lookup("Hash"), 4)], ["ext", xdr.lookup("LedgerHeaderExt")]]); + + // === xdr source ============================================================ + // + // enum LedgerUpgradeType + // { + // LEDGER_UPGRADE_VERSION = 1, + // LEDGER_UPGRADE_BASE_FEE = 2, + // LEDGER_UPGRADE_MAX_TX_SET_SIZE = 3, + // LEDGER_UPGRADE_BASE_RESERVE = 4, + // LEDGER_UPGRADE_FLAGS = 5, + // LEDGER_UPGRADE_CONFIG = 6, + // LEDGER_UPGRADE_MAX_SOROBAN_TX_SET_SIZE = 7 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerUpgradeType", { + ledgerUpgradeVersion: 1, + ledgerUpgradeBaseFee: 2, + ledgerUpgradeMaxTxSetSize: 3, + ledgerUpgradeBaseReserve: 4, + ledgerUpgradeFlags: 5, + ledgerUpgradeConfig: 6, + ledgerUpgradeMaxSorobanTxSetSize: 7 + }); + + // === xdr source ============================================================ + // + // struct ConfigUpgradeSetKey { + // Hash contractID; + // Hash contentHash; + // }; + // + // =========================================================================== + xdr.struct("ConfigUpgradeSetKey", [["contractId", xdr.lookup("Hash")], ["contentHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union LedgerUpgrade switch (LedgerUpgradeType type) + // { + // case LEDGER_UPGRADE_VERSION: + // uint32 newLedgerVersion; // update ledgerVersion + // case LEDGER_UPGRADE_BASE_FEE: + // uint32 newBaseFee; // update baseFee + // case LEDGER_UPGRADE_MAX_TX_SET_SIZE: + // uint32 newMaxTxSetSize; // update maxTxSetSize + // case LEDGER_UPGRADE_BASE_RESERVE: + // uint32 newBaseReserve; // update baseReserve + // case LEDGER_UPGRADE_FLAGS: + // uint32 newFlags; // update flags + // case LEDGER_UPGRADE_CONFIG: + // // Update arbitrary `ConfigSetting` entries identified by the key. + // ConfigUpgradeSetKey newConfig; + // case LEDGER_UPGRADE_MAX_SOROBAN_TX_SET_SIZE: + // // Update ConfigSettingContractExecutionLanesV0.ledgerMaxTxCount without + // // using `LEDGER_UPGRADE_CONFIG`. + // uint32 newMaxSorobanTxSetSize; + // }; + // + // =========================================================================== + xdr.union("LedgerUpgrade", { + switchOn: xdr.lookup("LedgerUpgradeType"), + switchName: "type", + switches: [["ledgerUpgradeVersion", "newLedgerVersion"], ["ledgerUpgradeBaseFee", "newBaseFee"], ["ledgerUpgradeMaxTxSetSize", "newMaxTxSetSize"], ["ledgerUpgradeBaseReserve", "newBaseReserve"], ["ledgerUpgradeFlags", "newFlags"], ["ledgerUpgradeConfig", "newConfig"], ["ledgerUpgradeMaxSorobanTxSetSize", "newMaxSorobanTxSetSize"]], + arms: { + newLedgerVersion: xdr.lookup("Uint32"), + newBaseFee: xdr.lookup("Uint32"), + newMaxTxSetSize: xdr.lookup("Uint32"), + newBaseReserve: xdr.lookup("Uint32"), + newFlags: xdr.lookup("Uint32"), + newConfig: xdr.lookup("ConfigUpgradeSetKey"), + newMaxSorobanTxSetSize: xdr.lookup("Uint32") + } + }); + + // === xdr source ============================================================ + // + // struct ConfigUpgradeSet { + // ConfigSettingEntry updatedEntry<>; + // }; + // + // =========================================================================== + xdr.struct("ConfigUpgradeSet", [["updatedEntry", xdr.varArray(xdr.lookup("ConfigSettingEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // enum TxSetComponentType + // { + // // txs with effective fee <= bid derived from a base fee (if any). + // // If base fee is not specified, no discount is applied. + // TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE = 0 + // }; + // + // =========================================================================== + xdr["enum"]("TxSetComponentType", { + txsetCompTxsMaybeDiscountedFee: 0 + }); + + // === xdr source ============================================================ + // + // struct + // { + // int64* baseFee; + // TransactionEnvelope txs<>; + // } + // + // =========================================================================== + xdr.struct("TxSetComponentTxsMaybeDiscountedFee", [["baseFee", xdr.option(xdr.lookup("Int64"))], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union TxSetComponent switch (TxSetComponentType type) + // { + // case TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE: + // struct + // { + // int64* baseFee; + // TransactionEnvelope txs<>; + // } txsMaybeDiscountedFee; + // }; + // + // =========================================================================== + xdr.union("TxSetComponent", { + switchOn: xdr.lookup("TxSetComponentType"), + switchName: "type", + switches: [["txsetCompTxsMaybeDiscountedFee", "txsMaybeDiscountedFee"]], + arms: { + txsMaybeDiscountedFee: xdr.lookup("TxSetComponentTxsMaybeDiscountedFee") + } + }); + + // === xdr source ============================================================ + // + // union TransactionPhase switch (int v) + // { + // case 0: + // TxSetComponent v0Components<>; + // }; + // + // =========================================================================== + xdr.union("TransactionPhase", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0Components"]], + arms: { + v0Components: xdr.varArray(xdr.lookup("TxSetComponent"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // struct TransactionSet + // { + // Hash previousLedgerHash; + // TransactionEnvelope txs<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionSet", [["previousLedgerHash", xdr.lookup("Hash")], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionSetV1 + // { + // Hash previousLedgerHash; + // TransactionPhase phases<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionSetV1", [["previousLedgerHash", xdr.lookup("Hash")], ["phases", xdr.varArray(xdr.lookup("TransactionPhase"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union GeneralizedTransactionSet switch (int v) + // { + // // We consider the legacy TransactionSet to be v0. + // case 1: + // TransactionSetV1 v1TxSet; + // }; + // + // =========================================================================== + xdr.union("GeneralizedTransactionSet", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[1, "v1TxSet"]], + arms: { + v1TxSet: xdr.lookup("TransactionSetV1") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionResultPair + // { + // Hash transactionHash; + // TransactionResult result; // result for the transaction + // }; + // + // =========================================================================== + xdr.struct("TransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("TransactionResult")]]); + + // === xdr source ============================================================ + // + // struct TransactionResultSet + // { + // TransactionResultPair results<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionResultSet", [["results", xdr.varArray(xdr.lookup("TransactionResultPair"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // GeneralizedTransactionSet generalizedTxSet; + // } + // + // =========================================================================== + xdr.union("TransactionHistoryEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "generalizedTxSet"]], + arms: { + generalizedTxSet: xdr.lookup("GeneralizedTransactionSet") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionHistoryEntry + // { + // uint32 ledgerSeq; + // TransactionSet txSet; + // + // // when v != 0, txSet must be empty + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // GeneralizedTransactionSet generalizedTxSet; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionHistoryEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txSet", xdr.lookup("TransactionSet")], ["ext", xdr.lookup("TransactionHistoryEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionHistoryResultEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionHistoryResultEntry + // { + // uint32 ledgerSeq; + // TransactionResultSet txResultSet; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionHistoryResultEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txResultSet", xdr.lookup("TransactionResultSet")], ["ext", xdr.lookup("TransactionHistoryResultEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderHistoryEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerHeaderHistoryEntry + // { + // Hash hash; + // LedgerHeader header; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeaderHistoryEntry", [["hash", xdr.lookup("Hash")], ["header", xdr.lookup("LedgerHeader")], ["ext", xdr.lookup("LedgerHeaderHistoryEntryExt")]]); + + // === xdr source ============================================================ + // + // struct LedgerSCPMessages + // { + // uint32 ledgerSeq; + // SCPEnvelope messages<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerScpMessages", [["ledgerSeq", xdr.lookup("Uint32")], ["messages", xdr.varArray(xdr.lookup("ScpEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct SCPHistoryEntryV0 + // { + // SCPQuorumSet quorumSets<>; // additional quorum sets used by ledgerMessages + // LedgerSCPMessages ledgerMessages; + // }; + // + // =========================================================================== + xdr.struct("ScpHistoryEntryV0", [["quorumSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)], ["ledgerMessages", xdr.lookup("LedgerScpMessages")]]); + + // === xdr source ============================================================ + // + // union SCPHistoryEntry switch (int v) + // { + // case 0: + // SCPHistoryEntryV0 v0; + // }; + // + // =========================================================================== + xdr.union("ScpHistoryEntry", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("ScpHistoryEntryV0") + } + }); + + // === xdr source ============================================================ + // + // enum LedgerEntryChangeType + // { + // LEDGER_ENTRY_CREATED = 0, // entry was added to the ledger + // LEDGER_ENTRY_UPDATED = 1, // entry was modified in the ledger + // LEDGER_ENTRY_REMOVED = 2, // entry was removed from the ledger + // LEDGER_ENTRY_STATE = 3 // value of the entry + // }; + // + // =========================================================================== + xdr["enum"]("LedgerEntryChangeType", { + ledgerEntryCreated: 0, + ledgerEntryUpdated: 1, + ledgerEntryRemoved: 2, + ledgerEntryState: 3 + }); + + // === xdr source ============================================================ + // + // union LedgerEntryChange switch (LedgerEntryChangeType type) + // { + // case LEDGER_ENTRY_CREATED: + // LedgerEntry created; + // case LEDGER_ENTRY_UPDATED: + // LedgerEntry updated; + // case LEDGER_ENTRY_REMOVED: + // LedgerKey removed; + // case LEDGER_ENTRY_STATE: + // LedgerEntry state; + // }; + // + // =========================================================================== + xdr.union("LedgerEntryChange", { + switchOn: xdr.lookup("LedgerEntryChangeType"), + switchName: "type", + switches: [["ledgerEntryCreated", "created"], ["ledgerEntryUpdated", "updated"], ["ledgerEntryRemoved", "removed"], ["ledgerEntryState", "state"]], + arms: { + created: xdr.lookup("LedgerEntry"), + updated: xdr.lookup("LedgerEntry"), + removed: xdr.lookup("LedgerKey"), + state: xdr.lookup("LedgerEntry") + } + }); + + // === xdr source ============================================================ + // + // typedef LedgerEntryChange LedgerEntryChanges<>; + // + // =========================================================================== + xdr.typedef("LedgerEntryChanges", xdr.varArray(xdr.lookup("LedgerEntryChange"), 2147483647)); + + // === xdr source ============================================================ + // + // struct OperationMeta + // { + // LedgerEntryChanges changes; + // }; + // + // =========================================================================== + xdr.struct("OperationMeta", [["changes", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV1 + // { + // LedgerEntryChanges txChanges; // tx level changes if any + // OperationMeta operations<>; // meta for each operation + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV1", [["txChanges", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV2 + // { + // LedgerEntryChanges txChangesBefore; // tx level changes before operations + // // are applied if any + // OperationMeta operations<>; // meta for each operation + // LedgerEntryChanges txChangesAfter; // tx level changes after operations are + // // applied if any + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV2", [["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // enum ContractEventType + // { + // SYSTEM = 0, + // CONTRACT = 1, + // DIAGNOSTIC = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ContractEventType", { + system: 0, + contract: 1, + diagnostic: 2 + }); + + // === xdr source ============================================================ + // + // struct + // { + // SCVal topics<>; + // SCVal data; + // } + // + // =========================================================================== + xdr.struct("ContractEventV0", [["topics", xdr.varArray(xdr.lookup("ScVal"), 2147483647)], ["data", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // struct + // { + // SCVal topics<>; + // SCVal data; + // } v0; + // } + // + // =========================================================================== + xdr.union("ContractEventBody", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("ContractEventV0") + } + }); + + // === xdr source ============================================================ + // + // struct ContractEvent + // { + // // We can use this to add more fields, or because it + // // is first, to change ContractEvent into a union. + // ExtensionPoint ext; + // + // Hash* contractID; + // ContractEventType type; + // + // union switch (int v) + // { + // case 0: + // struct + // { + // SCVal topics<>; + // SCVal data; + // } v0; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("ContractEvent", [["ext", xdr.lookup("ExtensionPoint")], ["contractId", xdr.option(xdr.lookup("Hash"))], ["type", xdr.lookup("ContractEventType")], ["body", xdr.lookup("ContractEventBody")]]); + + // === xdr source ============================================================ + // + // struct DiagnosticEvent + // { + // bool inSuccessfulContractCall; + // ContractEvent event; + // }; + // + // =========================================================================== + xdr.struct("DiagnosticEvent", [["inSuccessfulContractCall", xdr.bool()], ["event", xdr.lookup("ContractEvent")]]); + + // === xdr source ============================================================ + // + // typedef DiagnosticEvent DiagnosticEvents<>; + // + // =========================================================================== + xdr.typedef("DiagnosticEvents", xdr.varArray(xdr.lookup("DiagnosticEvent"), 2147483647)); + + // === xdr source ============================================================ + // + // struct SorobanTransactionMetaExtV1 + // { + // ExtensionPoint ext; + // + // // The following are the components of the overall Soroban resource fee + // // charged for the transaction. + // // The following relation holds: + // // `resourceFeeCharged = totalNonRefundableResourceFeeCharged + totalRefundableResourceFeeCharged` + // // where `resourceFeeCharged` is the overall fee charged for the + // // transaction. Also, `resourceFeeCharged` <= `sorobanData.resourceFee` + // // i.e.we never charge more than the declared resource fee. + // // The inclusion fee for charged the Soroban transaction can be found using + // // the following equation: + // // `result.feeCharged = resourceFeeCharged + inclusionFeeCharged`. + // + // // Total amount (in stroops) that has been charged for non-refundable + // // Soroban resources. + // // Non-refundable resources are charged based on the usage declared in + // // the transaction envelope (such as `instructions`, `readBytes` etc.) and + // // is charged regardless of the success of the transaction. + // int64 totalNonRefundableResourceFeeCharged; + // // Total amount (in stroops) that has been charged for refundable + // // Soroban resource fees. + // // Currently this comprises the rent fee (`rentFeeCharged`) and the + // // fee for the events and return value. + // // Refundable resources are charged based on the actual resources usage. + // // Since currently refundable resources are only used for the successful + // // transactions, this will be `0` for failed transactions. + // int64 totalRefundableResourceFeeCharged; + // // Amount (in stroops) that has been charged for rent. + // // This is a part of `totalNonRefundableResourceFeeCharged`. + // int64 rentFeeCharged; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionMetaExtV1", [["ext", xdr.lookup("ExtensionPoint")], ["totalNonRefundableResourceFeeCharged", xdr.lookup("Int64")], ["totalRefundableResourceFeeCharged", xdr.lookup("Int64")], ["rentFeeCharged", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union SorobanTransactionMetaExt switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionMetaExtV1 v1; + // }; + // + // =========================================================================== + xdr.union("SorobanTransactionMetaExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("SorobanTransactionMetaExtV1") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanTransactionMeta + // { + // SorobanTransactionMetaExt ext; + // + // ContractEvent events<>; // custom events populated by the + // // contracts themselves. + // SCVal returnValue; // return value of the host fn invocation + // + // // Diagnostics events that are not hashed. + // // This will contain all contract and diagnostic events. Even ones + // // that were emitted in a failed contract call. + // DiagnosticEvent diagnosticEvents<>; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionMeta", [["ext", xdr.lookup("SorobanTransactionMetaExt")], ["events", xdr.varArray(xdr.lookup("ContractEvent"), 2147483647)], ["returnValue", xdr.lookup("ScVal")], ["diagnosticEvents", xdr.varArray(xdr.lookup("DiagnosticEvent"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV3 + // { + // ExtensionPoint ext; + // + // LedgerEntryChanges txChangesBefore; // tx level changes before operations + // // are applied if any + // OperationMeta operations<>; // meta for each operation + // LedgerEntryChanges txChangesAfter; // tx level changes after operations are + // // applied if any + // SorobanTransactionMeta* sorobanMeta; // Soroban-specific meta (only for + // // Soroban transactions). + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV3", [["ext", xdr.lookup("ExtensionPoint")], ["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")], ["sorobanMeta", xdr.option(xdr.lookup("SorobanTransactionMeta"))]]); + + // === xdr source ============================================================ + // + // struct InvokeHostFunctionSuccessPreImage + // { + // SCVal returnValue; + // ContractEvent events<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeHostFunctionSuccessPreImage", [["returnValue", xdr.lookup("ScVal")], ["events", xdr.varArray(xdr.lookup("ContractEvent"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union TransactionMeta switch (int v) + // { + // case 0: + // OperationMeta operations<>; + // case 1: + // TransactionMetaV1 v1; + // case 2: + // TransactionMetaV2 v2; + // case 3: + // TransactionMetaV3 v3; + // }; + // + // =========================================================================== + xdr.union("TransactionMeta", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "operations"], [1, "v1"], [2, "v2"], [3, "v3"]], + arms: { + operations: xdr.varArray(xdr.lookup("OperationMeta"), 2147483647), + v1: xdr.lookup("TransactionMetaV1"), + v2: xdr.lookup("TransactionMetaV2"), + v3: xdr.lookup("TransactionMetaV3") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionResultMeta + // { + // TransactionResultPair result; + // LedgerEntryChanges feeProcessing; + // TransactionMeta txApplyProcessing; + // }; + // + // =========================================================================== + xdr.struct("TransactionResultMeta", [["result", xdr.lookup("TransactionResultPair")], ["feeProcessing", xdr.lookup("LedgerEntryChanges")], ["txApplyProcessing", xdr.lookup("TransactionMeta")]]); + + // === xdr source ============================================================ + // + // struct UpgradeEntryMeta + // { + // LedgerUpgrade upgrade; + // LedgerEntryChanges changes; + // }; + // + // =========================================================================== + xdr.struct("UpgradeEntryMeta", [["upgrade", xdr.lookup("LedgerUpgrade")], ["changes", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaV0 + // { + // LedgerHeaderHistoryEntry ledgerHeader; + // // NB: txSet is sorted in "Hash order" + // TransactionSet txSet; + // + // // NB: transactions are sorted in apply order here + // // fees for all transactions are processed first + // // followed by applying transactions + // TransactionResultMeta txProcessing<>; + // + // // upgrades are applied last + // UpgradeEntryMeta upgradesProcessing<>; + // + // // other misc information attached to the ledger close + // SCPHistoryEntry scpInfo<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaV0", [["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("TransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaExtV1 + // { + // ExtensionPoint ext; + // int64 sorobanFeeWrite1KB; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaExtV1", [["ext", xdr.lookup("ExtensionPoint")], ["sorobanFeeWrite1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union LedgerCloseMetaExt switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerCloseMetaExtV1 v1; + // }; + // + // =========================================================================== + xdr.union("LedgerCloseMetaExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerCloseMetaExtV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaV1 + // { + // LedgerCloseMetaExt ext; + // + // LedgerHeaderHistoryEntry ledgerHeader; + // + // GeneralizedTransactionSet txSet; + // + // // NB: transactions are sorted in apply order here + // // fees for all transactions are processed first + // // followed by applying transactions + // TransactionResultMeta txProcessing<>; + // + // // upgrades are applied last + // UpgradeEntryMeta upgradesProcessing<>; + // + // // other misc information attached to the ledger close + // SCPHistoryEntry scpInfo<>; + // + // // Size in bytes of BucketList, to support downstream + // // systems calculating storage fees correctly. + // uint64 totalByteSizeOfBucketList; + // + // // Temp keys that are being evicted at this ledger. + // LedgerKey evictedTemporaryLedgerKeys<>; + // + // // Archived restorable ledger entries that are being + // // evicted at this ledger. + // LedgerEntry evictedPersistentLedgerEntries<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaV1", [["ext", xdr.lookup("LedgerCloseMetaExt")], ["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("GeneralizedTransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)], ["totalByteSizeOfBucketList", xdr.lookup("Uint64")], ["evictedTemporaryLedgerKeys", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["evictedPersistentLedgerEntries", xdr.varArray(xdr.lookup("LedgerEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union LedgerCloseMeta switch (int v) + // { + // case 0: + // LedgerCloseMetaV0 v0; + // case 1: + // LedgerCloseMetaV1 v1; + // }; + // + // =========================================================================== + xdr.union("LedgerCloseMeta", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"], [1, "v1"]], + arms: { + v0: xdr.lookup("LedgerCloseMetaV0"), + v1: xdr.lookup("LedgerCloseMetaV1") + } + }); + + // === xdr source ============================================================ + // + // enum ErrorCode + // { + // ERR_MISC = 0, // Unspecific error + // ERR_DATA = 1, // Malformed data + // ERR_CONF = 2, // Misconfiguration error + // ERR_AUTH = 3, // Authentication failure + // ERR_LOAD = 4 // System overloaded + // }; + // + // =========================================================================== + xdr["enum"]("ErrorCode", { + errMisc: 0, + errData: 1, + errConf: 2, + errAuth: 3, + errLoad: 4 + }); + + // === xdr source ============================================================ + // + // struct Error + // { + // ErrorCode code; + // string msg<100>; + // }; + // + // =========================================================================== + xdr.struct("Error", [["code", xdr.lookup("ErrorCode")], ["msg", xdr.string(100)]]); + + // === xdr source ============================================================ + // + // struct SendMore + // { + // uint32 numMessages; + // }; + // + // =========================================================================== + xdr.struct("SendMore", [["numMessages", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SendMoreExtended + // { + // uint32 numMessages; + // uint32 numBytes; + // }; + // + // =========================================================================== + xdr.struct("SendMoreExtended", [["numMessages", xdr.lookup("Uint32")], ["numBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct AuthCert + // { + // Curve25519Public pubkey; + // uint64 expiration; + // Signature sig; + // }; + // + // =========================================================================== + xdr.struct("AuthCert", [["pubkey", xdr.lookup("Curve25519Public")], ["expiration", xdr.lookup("Uint64")], ["sig", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // struct Hello + // { + // uint32 ledgerVersion; + // uint32 overlayVersion; + // uint32 overlayMinVersion; + // Hash networkID; + // string versionStr<100>; + // int listeningPort; + // NodeID peerID; + // AuthCert cert; + // uint256 nonce; + // }; + // + // =========================================================================== + xdr.struct("Hello", [["ledgerVersion", xdr.lookup("Uint32")], ["overlayVersion", xdr.lookup("Uint32")], ["overlayMinVersion", xdr.lookup("Uint32")], ["networkId", xdr.lookup("Hash")], ["versionStr", xdr.string(100)], ["listeningPort", xdr["int"]()], ["peerId", xdr.lookup("NodeId")], ["cert", xdr.lookup("AuthCert")], ["nonce", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // const AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED = 200; + // + // =========================================================================== + xdr["const"]("AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED", 200); + + // === xdr source ============================================================ + // + // struct Auth + // { + // int flags; + // }; + // + // =========================================================================== + xdr.struct("Auth", [["flags", xdr["int"]()]]); + + // === xdr source ============================================================ + // + // enum IPAddrType + // { + // IPv4 = 0, + // IPv6 = 1 + // }; + // + // =========================================================================== + xdr["enum"]("IpAddrType", { + iPv4: 0, + iPv6: 1 + }); + + // === xdr source ============================================================ + // + // union switch (IPAddrType type) + // { + // case IPv4: + // opaque ipv4[4]; + // case IPv6: + // opaque ipv6[16]; + // } + // + // =========================================================================== + xdr.union("PeerAddressIp", { + switchOn: xdr.lookup("IpAddrType"), + switchName: "type", + switches: [["iPv4", "ipv4"], ["iPv6", "ipv6"]], + arms: { + ipv4: xdr.opaque(4), + ipv6: xdr.opaque(16) + } + }); + + // === xdr source ============================================================ + // + // struct PeerAddress + // { + // union switch (IPAddrType type) + // { + // case IPv4: + // opaque ipv4[4]; + // case IPv6: + // opaque ipv6[16]; + // } + // ip; + // uint32 port; + // uint32 numFailures; + // }; + // + // =========================================================================== + xdr.struct("PeerAddress", [["ip", xdr.lookup("PeerAddressIp")], ["port", xdr.lookup("Uint32")], ["numFailures", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // enum MessageType + // { + // ERROR_MSG = 0, + // AUTH = 2, + // DONT_HAVE = 3, + // + // GET_PEERS = 4, // gets a list of peers this guy knows about + // PEERS = 5, + // + // GET_TX_SET = 6, // gets a particular txset by hash + // TX_SET = 7, + // GENERALIZED_TX_SET = 17, + // + // TRANSACTION = 8, // pass on a tx you have heard about + // + // // SCP + // GET_SCP_QUORUMSET = 9, + // SCP_QUORUMSET = 10, + // SCP_MESSAGE = 11, + // GET_SCP_STATE = 12, + // + // // new messages + // HELLO = 13, + // + // SURVEY_REQUEST = 14, + // SURVEY_RESPONSE = 15, + // + // SEND_MORE = 16, + // SEND_MORE_EXTENDED = 20, + // + // FLOOD_ADVERT = 18, + // FLOOD_DEMAND = 19, + // + // TIME_SLICED_SURVEY_REQUEST = 21, + // TIME_SLICED_SURVEY_RESPONSE = 22, + // TIME_SLICED_SURVEY_START_COLLECTING = 23, + // TIME_SLICED_SURVEY_STOP_COLLECTING = 24 + // }; + // + // =========================================================================== + xdr["enum"]("MessageType", { + errorMsg: 0, + auth: 2, + dontHave: 3, + getPeers: 4, + peers: 5, + getTxSet: 6, + txSet: 7, + generalizedTxSet: 17, + transaction: 8, + getScpQuorumset: 9, + scpQuorumset: 10, + scpMessage: 11, + getScpState: 12, + hello: 13, + surveyRequest: 14, + surveyResponse: 15, + sendMore: 16, + sendMoreExtended: 20, + floodAdvert: 18, + floodDemand: 19, + timeSlicedSurveyRequest: 21, + timeSlicedSurveyResponse: 22, + timeSlicedSurveyStartCollecting: 23, + timeSlicedSurveyStopCollecting: 24 + }); + + // === xdr source ============================================================ + // + // struct DontHave + // { + // MessageType type; + // uint256 reqHash; + // }; + // + // =========================================================================== + xdr.struct("DontHave", [["type", xdr.lookup("MessageType")], ["reqHash", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // enum SurveyMessageCommandType + // { + // SURVEY_TOPOLOGY = 0, + // TIME_SLICED_SURVEY_TOPOLOGY = 1 + // }; + // + // =========================================================================== + xdr["enum"]("SurveyMessageCommandType", { + surveyTopology: 0, + timeSlicedSurveyTopology: 1 + }); + + // === xdr source ============================================================ + // + // enum SurveyMessageResponseType + // { + // SURVEY_TOPOLOGY_RESPONSE_V0 = 0, + // SURVEY_TOPOLOGY_RESPONSE_V1 = 1, + // SURVEY_TOPOLOGY_RESPONSE_V2 = 2 + // }; + // + // =========================================================================== + xdr["enum"]("SurveyMessageResponseType", { + surveyTopologyResponseV0: 0, + surveyTopologyResponseV1: 1, + surveyTopologyResponseV2: 2 + }); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyStartCollectingMessage + // { + // NodeID surveyorID; + // uint32 nonce; + // uint32 ledgerNum; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyStartCollectingMessage", [["surveyorId", xdr.lookup("NodeId")], ["nonce", xdr.lookup("Uint32")], ["ledgerNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyStartCollectingMessage + // { + // Signature signature; + // TimeSlicedSurveyStartCollectingMessage startCollecting; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyStartCollectingMessage", [["signature", xdr.lookup("Signature")], ["startCollecting", xdr.lookup("TimeSlicedSurveyStartCollectingMessage")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyStopCollectingMessage + // { + // NodeID surveyorID; + // uint32 nonce; + // uint32 ledgerNum; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyStopCollectingMessage", [["surveyorId", xdr.lookup("NodeId")], ["nonce", xdr.lookup("Uint32")], ["ledgerNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyStopCollectingMessage + // { + // Signature signature; + // TimeSlicedSurveyStopCollectingMessage stopCollecting; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyStopCollectingMessage", [["signature", xdr.lookup("Signature")], ["stopCollecting", xdr.lookup("TimeSlicedSurveyStopCollectingMessage")]]); + + // === xdr source ============================================================ + // + // struct SurveyRequestMessage + // { + // NodeID surveyorPeerID; + // NodeID surveyedPeerID; + // uint32 ledgerNum; + // Curve25519Public encryptionKey; + // SurveyMessageCommandType commandType; + // }; + // + // =========================================================================== + xdr.struct("SurveyRequestMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["encryptionKey", xdr.lookup("Curve25519Public")], ["commandType", xdr.lookup("SurveyMessageCommandType")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyRequestMessage + // { + // SurveyRequestMessage request; + // uint32 nonce; + // uint32 inboundPeersIndex; + // uint32 outboundPeersIndex; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyRequestMessage", [["request", xdr.lookup("SurveyRequestMessage")], ["nonce", xdr.lookup("Uint32")], ["inboundPeersIndex", xdr.lookup("Uint32")], ["outboundPeersIndex", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedSurveyRequestMessage + // { + // Signature requestSignature; + // SurveyRequestMessage request; + // }; + // + // =========================================================================== + xdr.struct("SignedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("SurveyRequestMessage")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyRequestMessage + // { + // Signature requestSignature; + // TimeSlicedSurveyRequestMessage request; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("TimeSlicedSurveyRequestMessage")]]); + + // === xdr source ============================================================ + // + // typedef opaque EncryptedBody<64000>; + // + // =========================================================================== + xdr.typedef("EncryptedBody", xdr.varOpaque(64000)); + + // === xdr source ============================================================ + // + // struct SurveyResponseMessage + // { + // NodeID surveyorPeerID; + // NodeID surveyedPeerID; + // uint32 ledgerNum; + // SurveyMessageCommandType commandType; + // EncryptedBody encryptedBody; + // }; + // + // =========================================================================== + xdr.struct("SurveyResponseMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["commandType", xdr.lookup("SurveyMessageCommandType")], ["encryptedBody", xdr.lookup("EncryptedBody")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyResponseMessage + // { + // SurveyResponseMessage response; + // uint32 nonce; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyResponseMessage", [["response", xdr.lookup("SurveyResponseMessage")], ["nonce", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedSurveyResponseMessage + // { + // Signature responseSignature; + // SurveyResponseMessage response; + // }; + // + // =========================================================================== + xdr.struct("SignedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("SurveyResponseMessage")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyResponseMessage + // { + // Signature responseSignature; + // TimeSlicedSurveyResponseMessage response; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("TimeSlicedSurveyResponseMessage")]]); + + // === xdr source ============================================================ + // + // struct PeerStats + // { + // NodeID id; + // string versionStr<100>; + // uint64 messagesRead; + // uint64 messagesWritten; + // uint64 bytesRead; + // uint64 bytesWritten; + // uint64 secondsConnected; + // + // uint64 uniqueFloodBytesRecv; + // uint64 duplicateFloodBytesRecv; + // uint64 uniqueFetchBytesRecv; + // uint64 duplicateFetchBytesRecv; + // + // uint64 uniqueFloodMessageRecv; + // uint64 duplicateFloodMessageRecv; + // uint64 uniqueFetchMessageRecv; + // uint64 duplicateFetchMessageRecv; + // }; + // + // =========================================================================== + xdr.struct("PeerStats", [["id", xdr.lookup("NodeId")], ["versionStr", xdr.string(100)], ["messagesRead", xdr.lookup("Uint64")], ["messagesWritten", xdr.lookup("Uint64")], ["bytesRead", xdr.lookup("Uint64")], ["bytesWritten", xdr.lookup("Uint64")], ["secondsConnected", xdr.lookup("Uint64")], ["uniqueFloodBytesRecv", xdr.lookup("Uint64")], ["duplicateFloodBytesRecv", xdr.lookup("Uint64")], ["uniqueFetchBytesRecv", xdr.lookup("Uint64")], ["duplicateFetchBytesRecv", xdr.lookup("Uint64")], ["uniqueFloodMessageRecv", xdr.lookup("Uint64")], ["duplicateFloodMessageRecv", xdr.lookup("Uint64")], ["uniqueFetchMessageRecv", xdr.lookup("Uint64")], ["duplicateFetchMessageRecv", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // typedef PeerStats PeerStatList<25>; + // + // =========================================================================== + xdr.typedef("PeerStatList", xdr.varArray(xdr.lookup("PeerStats"), 25)); + + // === xdr source ============================================================ + // + // struct TimeSlicedNodeData + // { + // uint32 addedAuthenticatedPeers; + // uint32 droppedAuthenticatedPeers; + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // + // // SCP stats + // uint32 p75SCPFirstToSelfLatencyMs; + // uint32 p75SCPSelfToOtherLatencyMs; + // + // // How many times the node lost sync in the time slice + // uint32 lostSyncCount; + // + // // Config data + // bool isValidator; + // uint32 maxInboundPeerCount; + // uint32 maxOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedNodeData", [["addedAuthenticatedPeers", xdr.lookup("Uint32")], ["droppedAuthenticatedPeers", xdr.lookup("Uint32")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")], ["p75ScpFirstToSelfLatencyMs", xdr.lookup("Uint32")], ["p75ScpSelfToOtherLatencyMs", xdr.lookup("Uint32")], ["lostSyncCount", xdr.lookup("Uint32")], ["isValidator", xdr.bool()], ["maxInboundPeerCount", xdr.lookup("Uint32")], ["maxOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedPeerData + // { + // PeerStats peerStats; + // uint32 averageLatencyMs; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedPeerData", [["peerStats", xdr.lookup("PeerStats")], ["averageLatencyMs", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // typedef TimeSlicedPeerData TimeSlicedPeerDataList<25>; + // + // =========================================================================== + xdr.typedef("TimeSlicedPeerDataList", xdr.varArray(xdr.lookup("TimeSlicedPeerData"), 25)); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV0 + // { + // PeerStatList inboundPeers; + // PeerStatList outboundPeers; + // + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV0", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV1 + // { + // PeerStatList inboundPeers; + // PeerStatList outboundPeers; + // + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // + // uint32 maxInboundPeerCount; + // uint32 maxOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV1", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")], ["maxInboundPeerCount", xdr.lookup("Uint32")], ["maxOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV2 + // { + // TimeSlicedPeerDataList inboundPeers; + // TimeSlicedPeerDataList outboundPeers; + // TimeSlicedNodeData nodeData; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV2", [["inboundPeers", xdr.lookup("TimeSlicedPeerDataList")], ["outboundPeers", xdr.lookup("TimeSlicedPeerDataList")], ["nodeData", xdr.lookup("TimeSlicedNodeData")]]); + + // === xdr source ============================================================ + // + // union SurveyResponseBody switch (SurveyMessageResponseType type) + // { + // case SURVEY_TOPOLOGY_RESPONSE_V0: + // TopologyResponseBodyV0 topologyResponseBodyV0; + // case SURVEY_TOPOLOGY_RESPONSE_V1: + // TopologyResponseBodyV1 topologyResponseBodyV1; + // case SURVEY_TOPOLOGY_RESPONSE_V2: + // TopologyResponseBodyV2 topologyResponseBodyV2; + // }; + // + // =========================================================================== + xdr.union("SurveyResponseBody", { + switchOn: xdr.lookup("SurveyMessageResponseType"), + switchName: "type", + switches: [["surveyTopologyResponseV0", "topologyResponseBodyV0"], ["surveyTopologyResponseV1", "topologyResponseBodyV1"], ["surveyTopologyResponseV2", "topologyResponseBodyV2"]], + arms: { + topologyResponseBodyV0: xdr.lookup("TopologyResponseBodyV0"), + topologyResponseBodyV1: xdr.lookup("TopologyResponseBodyV1"), + topologyResponseBodyV2: xdr.lookup("TopologyResponseBodyV2") + } + }); + + // === xdr source ============================================================ + // + // const TX_ADVERT_VECTOR_MAX_SIZE = 1000; + // + // =========================================================================== + xdr["const"]("TX_ADVERT_VECTOR_MAX_SIZE", 1000); + + // === xdr source ============================================================ + // + // typedef Hash TxAdvertVector; + // + // =========================================================================== + xdr.typedef("TxAdvertVector", xdr.varArray(xdr.lookup("Hash"), xdr.lookup("TX_ADVERT_VECTOR_MAX_SIZE"))); + + // === xdr source ============================================================ + // + // struct FloodAdvert + // { + // TxAdvertVector txHashes; + // }; + // + // =========================================================================== + xdr.struct("FloodAdvert", [["txHashes", xdr.lookup("TxAdvertVector")]]); + + // === xdr source ============================================================ + // + // const TX_DEMAND_VECTOR_MAX_SIZE = 1000; + // + // =========================================================================== + xdr["const"]("TX_DEMAND_VECTOR_MAX_SIZE", 1000); + + // === xdr source ============================================================ + // + // typedef Hash TxDemandVector; + // + // =========================================================================== + xdr.typedef("TxDemandVector", xdr.varArray(xdr.lookup("Hash"), xdr.lookup("TX_DEMAND_VECTOR_MAX_SIZE"))); + + // === xdr source ============================================================ + // + // struct FloodDemand + // { + // TxDemandVector txHashes; + // }; + // + // =========================================================================== + xdr.struct("FloodDemand", [["txHashes", xdr.lookup("TxDemandVector")]]); + + // === xdr source ============================================================ + // + // union StellarMessage switch (MessageType type) + // { + // case ERROR_MSG: + // Error error; + // case HELLO: + // Hello hello; + // case AUTH: + // Auth auth; + // case DONT_HAVE: + // DontHave dontHave; + // case GET_PEERS: + // void; + // case PEERS: + // PeerAddress peers<100>; + // + // case GET_TX_SET: + // uint256 txSetHash; + // case TX_SET: + // TransactionSet txSet; + // case GENERALIZED_TX_SET: + // GeneralizedTransactionSet generalizedTxSet; + // + // case TRANSACTION: + // TransactionEnvelope transaction; + // + // case SURVEY_REQUEST: + // SignedSurveyRequestMessage signedSurveyRequestMessage; + // + // case SURVEY_RESPONSE: + // SignedSurveyResponseMessage signedSurveyResponseMessage; + // + // case TIME_SLICED_SURVEY_REQUEST: + // SignedTimeSlicedSurveyRequestMessage signedTimeSlicedSurveyRequestMessage; + // + // case TIME_SLICED_SURVEY_RESPONSE: + // SignedTimeSlicedSurveyResponseMessage signedTimeSlicedSurveyResponseMessage; + // + // case TIME_SLICED_SURVEY_START_COLLECTING: + // SignedTimeSlicedSurveyStartCollectingMessage + // signedTimeSlicedSurveyStartCollectingMessage; + // + // case TIME_SLICED_SURVEY_STOP_COLLECTING: + // SignedTimeSlicedSurveyStopCollectingMessage + // signedTimeSlicedSurveyStopCollectingMessage; + // + // // SCP + // case GET_SCP_QUORUMSET: + // uint256 qSetHash; + // case SCP_QUORUMSET: + // SCPQuorumSet qSet; + // case SCP_MESSAGE: + // SCPEnvelope envelope; + // case GET_SCP_STATE: + // uint32 getSCPLedgerSeq; // ledger seq requested ; if 0, requests the latest + // case SEND_MORE: + // SendMore sendMoreMessage; + // case SEND_MORE_EXTENDED: + // SendMoreExtended sendMoreExtendedMessage; + // // Pull mode + // case FLOOD_ADVERT: + // FloodAdvert floodAdvert; + // case FLOOD_DEMAND: + // FloodDemand floodDemand; + // }; + // + // =========================================================================== + xdr.union("StellarMessage", { + switchOn: xdr.lookup("MessageType"), + switchName: "type", + switches: [["errorMsg", "error"], ["hello", "hello"], ["auth", "auth"], ["dontHave", "dontHave"], ["getPeers", xdr["void"]()], ["peers", "peers"], ["getTxSet", "txSetHash"], ["txSet", "txSet"], ["generalizedTxSet", "generalizedTxSet"], ["transaction", "transaction"], ["surveyRequest", "signedSurveyRequestMessage"], ["surveyResponse", "signedSurveyResponseMessage"], ["timeSlicedSurveyRequest", "signedTimeSlicedSurveyRequestMessage"], ["timeSlicedSurveyResponse", "signedTimeSlicedSurveyResponseMessage"], ["timeSlicedSurveyStartCollecting", "signedTimeSlicedSurveyStartCollectingMessage"], ["timeSlicedSurveyStopCollecting", "signedTimeSlicedSurveyStopCollectingMessage"], ["getScpQuorumset", "qSetHash"], ["scpQuorumset", "qSet"], ["scpMessage", "envelope"], ["getScpState", "getScpLedgerSeq"], ["sendMore", "sendMoreMessage"], ["sendMoreExtended", "sendMoreExtendedMessage"], ["floodAdvert", "floodAdvert"], ["floodDemand", "floodDemand"]], + arms: { + error: xdr.lookup("Error"), + hello: xdr.lookup("Hello"), + auth: xdr.lookup("Auth"), + dontHave: xdr.lookup("DontHave"), + peers: xdr.varArray(xdr.lookup("PeerAddress"), 100), + txSetHash: xdr.lookup("Uint256"), + txSet: xdr.lookup("TransactionSet"), + generalizedTxSet: xdr.lookup("GeneralizedTransactionSet"), + transaction: xdr.lookup("TransactionEnvelope"), + signedSurveyRequestMessage: xdr.lookup("SignedSurveyRequestMessage"), + signedSurveyResponseMessage: xdr.lookup("SignedSurveyResponseMessage"), + signedTimeSlicedSurveyRequestMessage: xdr.lookup("SignedTimeSlicedSurveyRequestMessage"), + signedTimeSlicedSurveyResponseMessage: xdr.lookup("SignedTimeSlicedSurveyResponseMessage"), + signedTimeSlicedSurveyStartCollectingMessage: xdr.lookup("SignedTimeSlicedSurveyStartCollectingMessage"), + signedTimeSlicedSurveyStopCollectingMessage: xdr.lookup("SignedTimeSlicedSurveyStopCollectingMessage"), + qSetHash: xdr.lookup("Uint256"), + qSet: xdr.lookup("ScpQuorumSet"), + envelope: xdr.lookup("ScpEnvelope"), + getScpLedgerSeq: xdr.lookup("Uint32"), + sendMoreMessage: xdr.lookup("SendMore"), + sendMoreExtendedMessage: xdr.lookup("SendMoreExtended"), + floodAdvert: xdr.lookup("FloodAdvert"), + floodDemand: xdr.lookup("FloodDemand") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // uint64 sequence; + // StellarMessage message; + // HmacSha256Mac mac; + // } + // + // =========================================================================== + xdr.struct("AuthenticatedMessageV0", [["sequence", xdr.lookup("Uint64")], ["message", xdr.lookup("StellarMessage")], ["mac", xdr.lookup("HmacSha256Mac")]]); + + // === xdr source ============================================================ + // + // union AuthenticatedMessage switch (uint32 v) + // { + // case 0: + // struct + // { + // uint64 sequence; + // StellarMessage message; + // HmacSha256Mac mac; + // } v0; + // }; + // + // =========================================================================== + xdr.union("AuthenticatedMessage", { + switchOn: xdr.lookup("Uint32"), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("AuthenticatedMessageV0") + } + }); + + // === xdr source ============================================================ + // + // const MAX_OPS_PER_TX = 100; + // + // =========================================================================== + xdr["const"]("MAX_OPS_PER_TX", 100); + + // === xdr source ============================================================ + // + // union LiquidityPoolParameters switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // LiquidityPoolConstantProductParameters constantProduct; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolParameters", { + switchOn: xdr.lookup("LiquidityPoolType"), + switchName: "type", + switches: [["liquidityPoolConstantProduct", "constantProduct"]], + arms: { + constantProduct: xdr.lookup("LiquidityPoolConstantProductParameters") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // uint64 id; + // uint256 ed25519; + // } + // + // =========================================================================== + xdr.struct("MuxedAccountMed25519", [["id", xdr.lookup("Uint64")], ["ed25519", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // union MuxedAccount switch (CryptoKeyType type) + // { + // case KEY_TYPE_ED25519: + // uint256 ed25519; + // case KEY_TYPE_MUXED_ED25519: + // struct + // { + // uint64 id; + // uint256 ed25519; + // } med25519; + // }; + // + // =========================================================================== + xdr.union("MuxedAccount", { + switchOn: xdr.lookup("CryptoKeyType"), + switchName: "type", + switches: [["keyTypeEd25519", "ed25519"], ["keyTypeMuxedEd25519", "med25519"]], + arms: { + ed25519: xdr.lookup("Uint256"), + med25519: xdr.lookup("MuxedAccountMed25519") + } + }); + + // === xdr source ============================================================ + // + // struct DecoratedSignature + // { + // SignatureHint hint; // last 4 bytes of the public key, used as a hint + // Signature signature; // actual signature + // }; + // + // =========================================================================== + xdr.struct("DecoratedSignature", [["hint", xdr.lookup("SignatureHint")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // enum OperationType + // { + // CREATE_ACCOUNT = 0, + // PAYMENT = 1, + // PATH_PAYMENT_STRICT_RECEIVE = 2, + // MANAGE_SELL_OFFER = 3, + // CREATE_PASSIVE_SELL_OFFER = 4, + // SET_OPTIONS = 5, + // CHANGE_TRUST = 6, + // ALLOW_TRUST = 7, + // ACCOUNT_MERGE = 8, + // INFLATION = 9, + // MANAGE_DATA = 10, + // BUMP_SEQUENCE = 11, + // MANAGE_BUY_OFFER = 12, + // PATH_PAYMENT_STRICT_SEND = 13, + // CREATE_CLAIMABLE_BALANCE = 14, + // CLAIM_CLAIMABLE_BALANCE = 15, + // BEGIN_SPONSORING_FUTURE_RESERVES = 16, + // END_SPONSORING_FUTURE_RESERVES = 17, + // REVOKE_SPONSORSHIP = 18, + // CLAWBACK = 19, + // CLAWBACK_CLAIMABLE_BALANCE = 20, + // SET_TRUST_LINE_FLAGS = 21, + // LIQUIDITY_POOL_DEPOSIT = 22, + // LIQUIDITY_POOL_WITHDRAW = 23, + // INVOKE_HOST_FUNCTION = 24, + // EXTEND_FOOTPRINT_TTL = 25, + // RESTORE_FOOTPRINT = 26 + // }; + // + // =========================================================================== + xdr["enum"]("OperationType", { + createAccount: 0, + payment: 1, + pathPaymentStrictReceive: 2, + manageSellOffer: 3, + createPassiveSellOffer: 4, + setOptions: 5, + changeTrust: 6, + allowTrust: 7, + accountMerge: 8, + inflation: 9, + manageData: 10, + bumpSequence: 11, + manageBuyOffer: 12, + pathPaymentStrictSend: 13, + createClaimableBalance: 14, + claimClaimableBalance: 15, + beginSponsoringFutureReserves: 16, + endSponsoringFutureReserves: 17, + revokeSponsorship: 18, + clawback: 19, + clawbackClaimableBalance: 20, + setTrustLineFlags: 21, + liquidityPoolDeposit: 22, + liquidityPoolWithdraw: 23, + invokeHostFunction: 24, + extendFootprintTtl: 25, + restoreFootprint: 26 + }); + + // === xdr source ============================================================ + // + // struct CreateAccountOp + // { + // AccountID destination; // account to create + // int64 startingBalance; // amount they end up with + // }; + // + // =========================================================================== + xdr.struct("CreateAccountOp", [["destination", xdr.lookup("AccountId")], ["startingBalance", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct PaymentOp + // { + // MuxedAccount destination; // recipient of the payment + // Asset asset; // what they end up with + // int64 amount; // amount they end up with + // }; + // + // =========================================================================== + xdr.struct("PaymentOp", [["destination", xdr.lookup("MuxedAccount")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct PathPaymentStrictReceiveOp + // { + // Asset sendAsset; // asset we pay with + // int64 sendMax; // the maximum amount of sendAsset to + // // send (excluding fees). + // // The operation will fail if can't be met + // + // MuxedAccount destination; // recipient of the payment + // Asset destAsset; // what they end up with + // int64 destAmount; // amount they end up with + // + // Asset path<5>; // additional hops it must go through to get there + // }; + // + // =========================================================================== + xdr.struct("PathPaymentStrictReceiveOp", [["sendAsset", xdr.lookup("Asset")], ["sendMax", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destAmount", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]); + + // === xdr source ============================================================ + // + // struct PathPaymentStrictSendOp + // { + // Asset sendAsset; // asset we pay with + // int64 sendAmount; // amount of sendAsset to send (excluding fees) + // + // MuxedAccount destination; // recipient of the payment + // Asset destAsset; // what they end up with + // int64 destMin; // the minimum amount of dest asset to + // // be received + // // The operation will fail if it can't be met + // + // Asset path<5>; // additional hops it must go through to get there + // }; + // + // =========================================================================== + xdr.struct("PathPaymentStrictSendOp", [["sendAsset", xdr.lookup("Asset")], ["sendAmount", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destMin", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]); + + // === xdr source ============================================================ + // + // struct ManageSellOfferOp + // { + // Asset selling; + // Asset buying; + // int64 amount; // amount being sold. if set to 0, delete the offer + // Price price; // price of thing being sold in terms of what you are buying + // + // // 0=create a new offer, otherwise edit an existing offer + // int64 offerID; + // }; + // + // =========================================================================== + xdr.struct("ManageSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ManageBuyOfferOp + // { + // Asset selling; + // Asset buying; + // int64 buyAmount; // amount being bought. if set to 0, delete the offer + // Price price; // price of thing being bought in terms of what you are + // // selling + // + // // 0=create a new offer, otherwise edit an existing offer + // int64 offerID; + // }; + // + // =========================================================================== + xdr.struct("ManageBuyOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["buyAmount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct CreatePassiveSellOfferOp + // { + // Asset selling; // A + // Asset buying; // B + // int64 amount; // amount taker gets + // Price price; // cost of A in terms of B + // }; + // + // =========================================================================== + xdr.struct("CreatePassiveSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")]]); + + // === xdr source ============================================================ + // + // struct SetOptionsOp + // { + // AccountID* inflationDest; // sets the inflation destination + // + // uint32* clearFlags; // which flags to clear + // uint32* setFlags; // which flags to set + // + // // account threshold manipulation + // uint32* masterWeight; // weight of the master account + // uint32* lowThreshold; + // uint32* medThreshold; + // uint32* highThreshold; + // + // string32* homeDomain; // sets the home domain + // + // // Add, update or remove a signer for the account + // // signer is deleted if the weight is 0 + // Signer* signer; + // }; + // + // =========================================================================== + xdr.struct("SetOptionsOp", [["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["clearFlags", xdr.option(xdr.lookup("Uint32"))], ["setFlags", xdr.option(xdr.lookup("Uint32"))], ["masterWeight", xdr.option(xdr.lookup("Uint32"))], ["lowThreshold", xdr.option(xdr.lookup("Uint32"))], ["medThreshold", xdr.option(xdr.lookup("Uint32"))], ["highThreshold", xdr.option(xdr.lookup("Uint32"))], ["homeDomain", xdr.option(xdr.lookup("String32"))], ["signer", xdr.option(xdr.lookup("Signer"))]]); + + // === xdr source ============================================================ + // + // union ChangeTrustAsset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // case ASSET_TYPE_POOL_SHARE: + // LiquidityPoolParameters liquidityPool; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("ChangeTrustAsset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPool"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12"), + liquidityPool: xdr.lookup("LiquidityPoolParameters") + } + }); + + // === xdr source ============================================================ + // + // struct ChangeTrustOp + // { + // ChangeTrustAsset line; + // + // // if limit is set to 0, deletes the trust line + // int64 limit; + // }; + // + // =========================================================================== + xdr.struct("ChangeTrustOp", [["line", xdr.lookup("ChangeTrustAsset")], ["limit", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct AllowTrustOp + // { + // AccountID trustor; + // AssetCode asset; + // + // // One of 0, AUTHORIZED_FLAG, or AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG + // uint32 authorize; + // }; + // + // =========================================================================== + xdr.struct("AllowTrustOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("AssetCode")], ["authorize", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ManageDataOp + // { + // string64 dataName; + // DataValue* dataValue; // set to null to clear + // }; + // + // =========================================================================== + xdr.struct("ManageDataOp", [["dataName", xdr.lookup("String64")], ["dataValue", xdr.option(xdr.lookup("DataValue"))]]); + + // === xdr source ============================================================ + // + // struct BumpSequenceOp + // { + // SequenceNumber bumpTo; + // }; + // + // =========================================================================== + xdr.struct("BumpSequenceOp", [["bumpTo", xdr.lookup("SequenceNumber")]]); + + // === xdr source ============================================================ + // + // struct CreateClaimableBalanceOp + // { + // Asset asset; + // int64 amount; + // Claimant claimants<10>; + // }; + // + // =========================================================================== + xdr.struct("CreateClaimableBalanceOp", [["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)]]); + + // === xdr source ============================================================ + // + // struct ClaimClaimableBalanceOp + // { + // ClaimableBalanceID balanceID; + // }; + // + // =========================================================================== + xdr.struct("ClaimClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct BeginSponsoringFutureReservesOp + // { + // AccountID sponsoredID; + // }; + // + // =========================================================================== + xdr.struct("BeginSponsoringFutureReservesOp", [["sponsoredId", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // enum RevokeSponsorshipType + // { + // REVOKE_SPONSORSHIP_LEDGER_ENTRY = 0, + // REVOKE_SPONSORSHIP_SIGNER = 1 + // }; + // + // =========================================================================== + xdr["enum"]("RevokeSponsorshipType", { + revokeSponsorshipLedgerEntry: 0, + revokeSponsorshipSigner: 1 + }); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // SignerKey signerKey; + // } + // + // =========================================================================== + xdr.struct("RevokeSponsorshipOpSigner", [["accountId", xdr.lookup("AccountId")], ["signerKey", xdr.lookup("SignerKey")]]); + + // === xdr source ============================================================ + // + // union RevokeSponsorshipOp switch (RevokeSponsorshipType type) + // { + // case REVOKE_SPONSORSHIP_LEDGER_ENTRY: + // LedgerKey ledgerKey; + // case REVOKE_SPONSORSHIP_SIGNER: + // struct + // { + // AccountID accountID; + // SignerKey signerKey; + // } signer; + // }; + // + // =========================================================================== + xdr.union("RevokeSponsorshipOp", { + switchOn: xdr.lookup("RevokeSponsorshipType"), + switchName: "type", + switches: [["revokeSponsorshipLedgerEntry", "ledgerKey"], ["revokeSponsorshipSigner", "signer"]], + arms: { + ledgerKey: xdr.lookup("LedgerKey"), + signer: xdr.lookup("RevokeSponsorshipOpSigner") + } + }); + + // === xdr source ============================================================ + // + // struct ClawbackOp + // { + // Asset asset; + // MuxedAccount from; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("ClawbackOp", [["asset", xdr.lookup("Asset")], ["from", xdr.lookup("MuxedAccount")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClawbackClaimableBalanceOp + // { + // ClaimableBalanceID balanceID; + // }; + // + // =========================================================================== + xdr.struct("ClawbackClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct SetTrustLineFlagsOp + // { + // AccountID trustor; + // Asset asset; + // + // uint32 clearFlags; // which flags to clear + // uint32 setFlags; // which flags to set + // }; + // + // =========================================================================== + xdr.struct("SetTrustLineFlagsOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["clearFlags", xdr.lookup("Uint32")], ["setFlags", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // const LIQUIDITY_POOL_FEE_V18 = 30; + // + // =========================================================================== + xdr["const"]("LIQUIDITY_POOL_FEE_V18", 30); + + // === xdr source ============================================================ + // + // struct LiquidityPoolDepositOp + // { + // PoolID liquidityPoolID; + // int64 maxAmountA; // maximum amount of first asset to deposit + // int64 maxAmountB; // maximum amount of second asset to deposit + // Price minPrice; // minimum depositA/depositB + // Price maxPrice; // maximum depositA/depositB + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolDepositOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["maxAmountA", xdr.lookup("Int64")], ["maxAmountB", xdr.lookup("Int64")], ["minPrice", xdr.lookup("Price")], ["maxPrice", xdr.lookup("Price")]]); + + // === xdr source ============================================================ + // + // struct LiquidityPoolWithdrawOp + // { + // PoolID liquidityPoolID; + // int64 amount; // amount of pool shares to withdraw + // int64 minAmountA; // minimum amount of first asset to withdraw + // int64 minAmountB; // minimum amount of second asset to withdraw + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolWithdrawOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["amount", xdr.lookup("Int64")], ["minAmountA", xdr.lookup("Int64")], ["minAmountB", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum HostFunctionType + // { + // HOST_FUNCTION_TYPE_INVOKE_CONTRACT = 0, + // HOST_FUNCTION_TYPE_CREATE_CONTRACT = 1, + // HOST_FUNCTION_TYPE_UPLOAD_CONTRACT_WASM = 2, + // HOST_FUNCTION_TYPE_CREATE_CONTRACT_V2 = 3 + // }; + // + // =========================================================================== + xdr["enum"]("HostFunctionType", { + hostFunctionTypeInvokeContract: 0, + hostFunctionTypeCreateContract: 1, + hostFunctionTypeUploadContractWasm: 2, + hostFunctionTypeCreateContractV2: 3 + }); + + // === xdr source ============================================================ + // + // enum ContractIDPreimageType + // { + // CONTRACT_ID_PREIMAGE_FROM_ADDRESS = 0, + // CONTRACT_ID_PREIMAGE_FROM_ASSET = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractIdPreimageType", { + contractIdPreimageFromAddress: 0, + contractIdPreimageFromAsset: 1 + }); + + // === xdr source ============================================================ + // + // struct + // { + // SCAddress address; + // uint256 salt; + // } + // + // =========================================================================== + xdr.struct("ContractIdPreimageFromAddress", [["address", xdr.lookup("ScAddress")], ["salt", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // union ContractIDPreimage switch (ContractIDPreimageType type) + // { + // case CONTRACT_ID_PREIMAGE_FROM_ADDRESS: + // struct + // { + // SCAddress address; + // uint256 salt; + // } fromAddress; + // case CONTRACT_ID_PREIMAGE_FROM_ASSET: + // Asset fromAsset; + // }; + // + // =========================================================================== + xdr.union("ContractIdPreimage", { + switchOn: xdr.lookup("ContractIdPreimageType"), + switchName: "type", + switches: [["contractIdPreimageFromAddress", "fromAddress"], ["contractIdPreimageFromAsset", "fromAsset"]], + arms: { + fromAddress: xdr.lookup("ContractIdPreimageFromAddress"), + fromAsset: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // struct CreateContractArgs + // { + // ContractIDPreimage contractIDPreimage; + // ContractExecutable executable; + // }; + // + // =========================================================================== + xdr.struct("CreateContractArgs", [["contractIdPreimage", xdr.lookup("ContractIdPreimage")], ["executable", xdr.lookup("ContractExecutable")]]); + + // === xdr source ============================================================ + // + // struct CreateContractArgsV2 + // { + // ContractIDPreimage contractIDPreimage; + // ContractExecutable executable; + // // Arguments of the contract's constructor. + // SCVal constructorArgs<>; + // }; + // + // =========================================================================== + xdr.struct("CreateContractArgsV2", [["contractIdPreimage", xdr.lookup("ContractIdPreimage")], ["executable", xdr.lookup("ContractExecutable")], ["constructorArgs", xdr.varArray(xdr.lookup("ScVal"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct InvokeContractArgs { + // SCAddress contractAddress; + // SCSymbol functionName; + // SCVal args<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeContractArgs", [["contractAddress", xdr.lookup("ScAddress")], ["functionName", xdr.lookup("ScSymbol")], ["args", xdr.varArray(xdr.lookup("ScVal"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union HostFunction switch (HostFunctionType type) + // { + // case HOST_FUNCTION_TYPE_INVOKE_CONTRACT: + // InvokeContractArgs invokeContract; + // case HOST_FUNCTION_TYPE_CREATE_CONTRACT: + // CreateContractArgs createContract; + // case HOST_FUNCTION_TYPE_UPLOAD_CONTRACT_WASM: + // opaque wasm<>; + // case HOST_FUNCTION_TYPE_CREATE_CONTRACT_V2: + // CreateContractArgsV2 createContractV2; + // }; + // + // =========================================================================== + xdr.union("HostFunction", { + switchOn: xdr.lookup("HostFunctionType"), + switchName: "type", + switches: [["hostFunctionTypeInvokeContract", "invokeContract"], ["hostFunctionTypeCreateContract", "createContract"], ["hostFunctionTypeUploadContractWasm", "wasm"], ["hostFunctionTypeCreateContractV2", "createContractV2"]], + arms: { + invokeContract: xdr.lookup("InvokeContractArgs"), + createContract: xdr.lookup("CreateContractArgs"), + wasm: xdr.varOpaque(), + createContractV2: xdr.lookup("CreateContractArgsV2") + } + }); + + // === xdr source ============================================================ + // + // enum SorobanAuthorizedFunctionType + // { + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN = 0, + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_HOST_FN = 1, + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN = 2 + // }; + // + // =========================================================================== + xdr["enum"]("SorobanAuthorizedFunctionType", { + sorobanAuthorizedFunctionTypeContractFn: 0, + sorobanAuthorizedFunctionTypeCreateContractHostFn: 1, + sorobanAuthorizedFunctionTypeCreateContractV2HostFn: 2 + }); + + // === xdr source ============================================================ + // + // union SorobanAuthorizedFunction switch (SorobanAuthorizedFunctionType type) + // { + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN: + // InvokeContractArgs contractFn; + // // This variant of auth payload for creating new contract instances + // // doesn't allow specifying the constructor arguments, creating contracts + // // with constructors that take arguments is only possible by authorizing + // // `SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN` + // // (protocol 22+). + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_HOST_FN: + // CreateContractArgs createContractHostFn; + // // This variant of auth payload for creating new contract instances + // // is only accepted in and after protocol 22. It allows authorizing the + // // contract constructor arguments. + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN: + // CreateContractArgsV2 createContractV2HostFn; + // }; + // + // =========================================================================== + xdr.union("SorobanAuthorizedFunction", { + switchOn: xdr.lookup("SorobanAuthorizedFunctionType"), + switchName: "type", + switches: [["sorobanAuthorizedFunctionTypeContractFn", "contractFn"], ["sorobanAuthorizedFunctionTypeCreateContractHostFn", "createContractHostFn"], ["sorobanAuthorizedFunctionTypeCreateContractV2HostFn", "createContractV2HostFn"]], + arms: { + contractFn: xdr.lookup("InvokeContractArgs"), + createContractHostFn: xdr.lookup("CreateContractArgs"), + createContractV2HostFn: xdr.lookup("CreateContractArgsV2") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanAuthorizedInvocation + // { + // SorobanAuthorizedFunction function; + // SorobanAuthorizedInvocation subInvocations<>; + // }; + // + // =========================================================================== + xdr.struct("SorobanAuthorizedInvocation", [["function", xdr.lookup("SorobanAuthorizedFunction")], ["subInvocations", xdr.varArray(xdr.lookup("SorobanAuthorizedInvocation"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct SorobanAddressCredentials + // { + // SCAddress address; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SCVal signature; + // }; + // + // =========================================================================== + xdr.struct("SorobanAddressCredentials", [["address", xdr.lookup("ScAddress")], ["nonce", xdr.lookup("Int64")], ["signatureExpirationLedger", xdr.lookup("Uint32")], ["signature", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // enum SorobanCredentialsType + // { + // SOROBAN_CREDENTIALS_SOURCE_ACCOUNT = 0, + // SOROBAN_CREDENTIALS_ADDRESS = 1 + // }; + // + // =========================================================================== + xdr["enum"]("SorobanCredentialsType", { + sorobanCredentialsSourceAccount: 0, + sorobanCredentialsAddress: 1 + }); + + // === xdr source ============================================================ + // + // union SorobanCredentials switch (SorobanCredentialsType type) + // { + // case SOROBAN_CREDENTIALS_SOURCE_ACCOUNT: + // void; + // case SOROBAN_CREDENTIALS_ADDRESS: + // SorobanAddressCredentials address; + // }; + // + // =========================================================================== + xdr.union("SorobanCredentials", { + switchOn: xdr.lookup("SorobanCredentialsType"), + switchName: "type", + switches: [["sorobanCredentialsSourceAccount", xdr["void"]()], ["sorobanCredentialsAddress", "address"]], + arms: { + address: xdr.lookup("SorobanAddressCredentials") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanAuthorizationEntry + // { + // SorobanCredentials credentials; + // SorobanAuthorizedInvocation rootInvocation; + // }; + // + // =========================================================================== + xdr.struct("SorobanAuthorizationEntry", [["credentials", xdr.lookup("SorobanCredentials")], ["rootInvocation", xdr.lookup("SorobanAuthorizedInvocation")]]); + + // === xdr source ============================================================ + // + // struct InvokeHostFunctionOp + // { + // // Host function to invoke. + // HostFunction hostFunction; + // // Per-address authorizations for this host function. + // SorobanAuthorizationEntry auth<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeHostFunctionOp", [["hostFunction", xdr.lookup("HostFunction")], ["auth", xdr.varArray(xdr.lookup("SorobanAuthorizationEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct ExtendFootprintTTLOp + // { + // ExtensionPoint ext; + // uint32 extendTo; + // }; + // + // =========================================================================== + xdr.struct("ExtendFootprintTtlOp", [["ext", xdr.lookup("ExtensionPoint")], ["extendTo", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct RestoreFootprintOp + // { + // ExtensionPoint ext; + // }; + // + // =========================================================================== + xdr.struct("RestoreFootprintOp", [["ext", xdr.lookup("ExtensionPoint")]]); + + // === xdr source ============================================================ + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountOp createAccountOp; + // case PAYMENT: + // PaymentOp paymentOp; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp; + // case MANAGE_SELL_OFFER: + // ManageSellOfferOp manageSellOfferOp; + // case CREATE_PASSIVE_SELL_OFFER: + // CreatePassiveSellOfferOp createPassiveSellOfferOp; + // case SET_OPTIONS: + // SetOptionsOp setOptionsOp; + // case CHANGE_TRUST: + // ChangeTrustOp changeTrustOp; + // case ALLOW_TRUST: + // AllowTrustOp allowTrustOp; + // case ACCOUNT_MERGE: + // MuxedAccount destination; + // case INFLATION: + // void; + // case MANAGE_DATA: + // ManageDataOp manageDataOp; + // case BUMP_SEQUENCE: + // BumpSequenceOp bumpSequenceOp; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferOp manageBuyOfferOp; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendOp pathPaymentStrictSendOp; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceOp createClaimableBalanceOp; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceOp claimClaimableBalanceOp; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp; + // case END_SPONSORING_FUTURE_RESERVES: + // void; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipOp revokeSponsorshipOp; + // case CLAWBACK: + // ClawbackOp clawbackOp; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceOp clawbackClaimableBalanceOp; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsOp setTrustLineFlagsOp; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositOp liquidityPoolDepositOp; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawOp liquidityPoolWithdrawOp; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionOp invokeHostFunctionOp; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLOp extendFootprintTTLOp; + // case RESTORE_FOOTPRINT: + // RestoreFootprintOp restoreFootprintOp; + // } + // + // =========================================================================== + xdr.union("OperationBody", { + switchOn: xdr.lookup("OperationType"), + switchName: "type", + switches: [["createAccount", "createAccountOp"], ["payment", "paymentOp"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveOp"], ["manageSellOffer", "manageSellOfferOp"], ["createPassiveSellOffer", "createPassiveSellOfferOp"], ["setOptions", "setOptionsOp"], ["changeTrust", "changeTrustOp"], ["allowTrust", "allowTrustOp"], ["accountMerge", "destination"], ["inflation", xdr["void"]()], ["manageData", "manageDataOp"], ["bumpSequence", "bumpSequenceOp"], ["manageBuyOffer", "manageBuyOfferOp"], ["pathPaymentStrictSend", "pathPaymentStrictSendOp"], ["createClaimableBalance", "createClaimableBalanceOp"], ["claimClaimableBalance", "claimClaimableBalanceOp"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesOp"], ["endSponsoringFutureReserves", xdr["void"]()], ["revokeSponsorship", "revokeSponsorshipOp"], ["clawback", "clawbackOp"], ["clawbackClaimableBalance", "clawbackClaimableBalanceOp"], ["setTrustLineFlags", "setTrustLineFlagsOp"], ["liquidityPoolDeposit", "liquidityPoolDepositOp"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawOp"], ["invokeHostFunction", "invokeHostFunctionOp"], ["extendFootprintTtl", "extendFootprintTtlOp"], ["restoreFootprint", "restoreFootprintOp"]], + arms: { + createAccountOp: xdr.lookup("CreateAccountOp"), + paymentOp: xdr.lookup("PaymentOp"), + pathPaymentStrictReceiveOp: xdr.lookup("PathPaymentStrictReceiveOp"), + manageSellOfferOp: xdr.lookup("ManageSellOfferOp"), + createPassiveSellOfferOp: xdr.lookup("CreatePassiveSellOfferOp"), + setOptionsOp: xdr.lookup("SetOptionsOp"), + changeTrustOp: xdr.lookup("ChangeTrustOp"), + allowTrustOp: xdr.lookup("AllowTrustOp"), + destination: xdr.lookup("MuxedAccount"), + manageDataOp: xdr.lookup("ManageDataOp"), + bumpSequenceOp: xdr.lookup("BumpSequenceOp"), + manageBuyOfferOp: xdr.lookup("ManageBuyOfferOp"), + pathPaymentStrictSendOp: xdr.lookup("PathPaymentStrictSendOp"), + createClaimableBalanceOp: xdr.lookup("CreateClaimableBalanceOp"), + claimClaimableBalanceOp: xdr.lookup("ClaimClaimableBalanceOp"), + beginSponsoringFutureReservesOp: xdr.lookup("BeginSponsoringFutureReservesOp"), + revokeSponsorshipOp: xdr.lookup("RevokeSponsorshipOp"), + clawbackOp: xdr.lookup("ClawbackOp"), + clawbackClaimableBalanceOp: xdr.lookup("ClawbackClaimableBalanceOp"), + setTrustLineFlagsOp: xdr.lookup("SetTrustLineFlagsOp"), + liquidityPoolDepositOp: xdr.lookup("LiquidityPoolDepositOp"), + liquidityPoolWithdrawOp: xdr.lookup("LiquidityPoolWithdrawOp"), + invokeHostFunctionOp: xdr.lookup("InvokeHostFunctionOp"), + extendFootprintTtlOp: xdr.lookup("ExtendFootprintTtlOp"), + restoreFootprintOp: xdr.lookup("RestoreFootprintOp") + } + }); + + // === xdr source ============================================================ + // + // struct Operation + // { + // // sourceAccount is the account used to run the operation + // // if not set, the runtime defaults to "sourceAccount" specified at + // // the transaction level + // MuxedAccount* sourceAccount; + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountOp createAccountOp; + // case PAYMENT: + // PaymentOp paymentOp; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp; + // case MANAGE_SELL_OFFER: + // ManageSellOfferOp manageSellOfferOp; + // case CREATE_PASSIVE_SELL_OFFER: + // CreatePassiveSellOfferOp createPassiveSellOfferOp; + // case SET_OPTIONS: + // SetOptionsOp setOptionsOp; + // case CHANGE_TRUST: + // ChangeTrustOp changeTrustOp; + // case ALLOW_TRUST: + // AllowTrustOp allowTrustOp; + // case ACCOUNT_MERGE: + // MuxedAccount destination; + // case INFLATION: + // void; + // case MANAGE_DATA: + // ManageDataOp manageDataOp; + // case BUMP_SEQUENCE: + // BumpSequenceOp bumpSequenceOp; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferOp manageBuyOfferOp; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendOp pathPaymentStrictSendOp; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceOp createClaimableBalanceOp; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceOp claimClaimableBalanceOp; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp; + // case END_SPONSORING_FUTURE_RESERVES: + // void; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipOp revokeSponsorshipOp; + // case CLAWBACK: + // ClawbackOp clawbackOp; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceOp clawbackClaimableBalanceOp; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsOp setTrustLineFlagsOp; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositOp liquidityPoolDepositOp; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawOp liquidityPoolWithdrawOp; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionOp invokeHostFunctionOp; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLOp extendFootprintTTLOp; + // case RESTORE_FOOTPRINT: + // RestoreFootprintOp restoreFootprintOp; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("Operation", [["sourceAccount", xdr.option(xdr.lookup("MuxedAccount"))], ["body", xdr.lookup("OperationBody")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageOperationId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // PoolID liquidityPoolID; + // Asset asset; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageRevokeId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")], ["liquidityPoolId", xdr.lookup("PoolId")], ["asset", xdr.lookup("Asset")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash networkID; + // ContractIDPreimage contractIDPreimage; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageContractId", [["networkId", xdr.lookup("Hash")], ["contractIdPreimage", xdr.lookup("ContractIdPreimage")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash networkID; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SorobanAuthorizedInvocation invocation; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageSorobanAuthorization", [["networkId", xdr.lookup("Hash")], ["nonce", xdr.lookup("Int64")], ["signatureExpirationLedger", xdr.lookup("Uint32")], ["invocation", xdr.lookup("SorobanAuthorizedInvocation")]]); + + // === xdr source ============================================================ + // + // union HashIDPreimage switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_OP_ID: + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // } operationID; + // case ENVELOPE_TYPE_POOL_REVOKE_OP_ID: + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // PoolID liquidityPoolID; + // Asset asset; + // } revokeID; + // case ENVELOPE_TYPE_CONTRACT_ID: + // struct + // { + // Hash networkID; + // ContractIDPreimage contractIDPreimage; + // } contractID; + // case ENVELOPE_TYPE_SOROBAN_AUTHORIZATION: + // struct + // { + // Hash networkID; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SorobanAuthorizedInvocation invocation; + // } sorobanAuthorization; + // }; + // + // =========================================================================== + xdr.union("HashIdPreimage", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeOpId", "operationId"], ["envelopeTypePoolRevokeOpId", "revokeId"], ["envelopeTypeContractId", "contractId"], ["envelopeTypeSorobanAuthorization", "sorobanAuthorization"]], + arms: { + operationId: xdr.lookup("HashIdPreimageOperationId"), + revokeId: xdr.lookup("HashIdPreimageRevokeId"), + contractId: xdr.lookup("HashIdPreimageContractId"), + sorobanAuthorization: xdr.lookup("HashIdPreimageSorobanAuthorization") + } + }); + + // === xdr source ============================================================ + // + // enum MemoType + // { + // MEMO_NONE = 0, + // MEMO_TEXT = 1, + // MEMO_ID = 2, + // MEMO_HASH = 3, + // MEMO_RETURN = 4 + // }; + // + // =========================================================================== + xdr["enum"]("MemoType", { + memoNone: 0, + memoText: 1, + memoId: 2, + memoHash: 3, + memoReturn: 4 + }); + + // === xdr source ============================================================ + // + // union Memo switch (MemoType type) + // { + // case MEMO_NONE: + // void; + // case MEMO_TEXT: + // string text<28>; + // case MEMO_ID: + // uint64 id; + // case MEMO_HASH: + // Hash hash; // the hash of what to pull from the content server + // case MEMO_RETURN: + // Hash retHash; // the hash of the tx you are rejecting + // }; + // + // =========================================================================== + xdr.union("Memo", { + switchOn: xdr.lookup("MemoType"), + switchName: "type", + switches: [["memoNone", xdr["void"]()], ["memoText", "text"], ["memoId", "id"], ["memoHash", "hash"], ["memoReturn", "retHash"]], + arms: { + text: xdr.string(28), + id: xdr.lookup("Uint64"), + hash: xdr.lookup("Hash"), + retHash: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // struct TimeBounds + // { + // TimePoint minTime; + // TimePoint maxTime; // 0 here means no maxTime + // }; + // + // =========================================================================== + xdr.struct("TimeBounds", [["minTime", xdr.lookup("TimePoint")], ["maxTime", xdr.lookup("TimePoint")]]); + + // === xdr source ============================================================ + // + // struct LedgerBounds + // { + // uint32 minLedger; + // uint32 maxLedger; // 0 here means no maxLedger + // }; + // + // =========================================================================== + xdr.struct("LedgerBounds", [["minLedger", xdr.lookup("Uint32")], ["maxLedger", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct PreconditionsV2 + // { + // TimeBounds* timeBounds; + // + // // Transaction only valid for ledger numbers n such that + // // minLedger <= n < maxLedger (if maxLedger == 0, then + // // only minLedger is checked) + // LedgerBounds* ledgerBounds; + // + // // If NULL, only valid when sourceAccount's sequence number + // // is seqNum - 1. Otherwise, valid when sourceAccount's + // // sequence number n satisfies minSeqNum <= n < tx.seqNum. + // // Note that after execution the account's sequence number + // // is always raised to tx.seqNum, and a transaction is not + // // valid if tx.seqNum is too high to ensure replay protection. + // SequenceNumber* minSeqNum; + // + // // For the transaction to be valid, the current ledger time must + // // be at least minSeqAge greater than sourceAccount's seqTime. + // Duration minSeqAge; + // + // // For the transaction to be valid, the current ledger number + // // must be at least minSeqLedgerGap greater than sourceAccount's + // // seqLedger. + // uint32 minSeqLedgerGap; + // + // // For the transaction to be valid, there must be a signature + // // corresponding to every Signer in this array, even if the + // // signature is not otherwise required by the sourceAccount or + // // operations. + // SignerKey extraSigners<2>; + // }; + // + // =========================================================================== + xdr.struct("PreconditionsV2", [["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["ledgerBounds", xdr.option(xdr.lookup("LedgerBounds"))], ["minSeqNum", xdr.option(xdr.lookup("SequenceNumber"))], ["minSeqAge", xdr.lookup("Duration")], ["minSeqLedgerGap", xdr.lookup("Uint32")], ["extraSigners", xdr.varArray(xdr.lookup("SignerKey"), 2)]]); + + // === xdr source ============================================================ + // + // enum PreconditionType + // { + // PRECOND_NONE = 0, + // PRECOND_TIME = 1, + // PRECOND_V2 = 2 + // }; + // + // =========================================================================== + xdr["enum"]("PreconditionType", { + precondNone: 0, + precondTime: 1, + precondV2: 2 + }); + + // === xdr source ============================================================ + // + // union Preconditions switch (PreconditionType type) + // { + // case PRECOND_NONE: + // void; + // case PRECOND_TIME: + // TimeBounds timeBounds; + // case PRECOND_V2: + // PreconditionsV2 v2; + // }; + // + // =========================================================================== + xdr.union("Preconditions", { + switchOn: xdr.lookup("PreconditionType"), + switchName: "type", + switches: [["precondNone", xdr["void"]()], ["precondTime", "timeBounds"], ["precondV2", "v2"]], + arms: { + timeBounds: xdr.lookup("TimeBounds"), + v2: xdr.lookup("PreconditionsV2") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerFootprint + // { + // LedgerKey readOnly<>; + // LedgerKey readWrite<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerFootprint", [["readOnly", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["readWrite", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)]]); + + // === xdr source ============================================================ + // + // enum ArchivalProofType + // { + // EXISTENCE = 0, + // NONEXISTENCE = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ArchivalProofType", { + existence: 0, + nonexistence: 1 + }); + + // === xdr source ============================================================ + // + // struct ArchivalProofNode + // { + // uint32 index; + // Hash hash; + // }; + // + // =========================================================================== + xdr.struct("ArchivalProofNode", [["index", xdr.lookup("Uint32")], ["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // typedef ArchivalProofNode ProofLevel<>; + // + // =========================================================================== + xdr.typedef("ProofLevel", xdr.varArray(xdr.lookup("ArchivalProofNode"), 2147483647)); + + // === xdr source ============================================================ + // + // struct NonexistenceProofBody + // { + // ColdArchiveBucketEntry entriesToProve<>; + // + // // Vector of vectors, where proofLevels[level] + // // contains all HashNodes that correspond with that level + // ProofLevel proofLevels<>; + // }; + // + // =========================================================================== + xdr.struct("NonexistenceProofBody", [["entriesToProve", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["proofLevels", xdr.varArray(xdr.lookup("ProofLevel"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct ExistenceProofBody + // { + // LedgerKey keysToProve<>; + // + // // Bounds for each key being proved, where bound[n] + // // corresponds to keysToProve[n] + // ColdArchiveBucketEntry lowBoundEntries<>; + // ColdArchiveBucketEntry highBoundEntries<>; + // + // // Vector of vectors, where proofLevels[level] + // // contains all HashNodes that correspond with that level + // ProofLevel proofLevels<>; + // }; + // + // =========================================================================== + xdr.struct("ExistenceProofBody", [["keysToProve", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["lowBoundEntries", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["highBoundEntries", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["proofLevels", xdr.varArray(xdr.lookup("ProofLevel"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union switch (ArchivalProofType t) + // { + // case EXISTENCE: + // NonexistenceProofBody nonexistenceProof; + // case NONEXISTENCE: + // ExistenceProofBody existenceProof; + // } + // + // =========================================================================== + xdr.union("ArchivalProofBody", { + switchOn: xdr.lookup("ArchivalProofType"), + switchName: "t", + switches: [["existence", "nonexistenceProof"], ["nonexistence", "existenceProof"]], + arms: { + nonexistenceProof: xdr.lookup("NonexistenceProofBody"), + existenceProof: xdr.lookup("ExistenceProofBody") + } + }); + + // === xdr source ============================================================ + // + // struct ArchivalProof + // { + // uint32 epoch; // AST Subtree for this proof + // + // union switch (ArchivalProofType t) + // { + // case EXISTENCE: + // NonexistenceProofBody nonexistenceProof; + // case NONEXISTENCE: + // ExistenceProofBody existenceProof; + // } body; + // }; + // + // =========================================================================== + xdr.struct("ArchivalProof", [["epoch", xdr.lookup("Uint32")], ["body", xdr.lookup("ArchivalProofBody")]]); + + // === xdr source ============================================================ + // + // struct SorobanResources + // { + // // The ledger footprint of the transaction. + // LedgerFootprint footprint; + // // The maximum number of instructions this transaction can use + // uint32 instructions; + // + // // The maximum number of bytes this transaction can read from ledger + // uint32 readBytes; + // // The maximum number of bytes this transaction can write to ledger + // uint32 writeBytes; + // }; + // + // =========================================================================== + xdr.struct("SorobanResources", [["footprint", xdr.lookup("LedgerFootprint")], ["instructions", xdr.lookup("Uint32")], ["readBytes", xdr.lookup("Uint32")], ["writeBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SorobanTransactionData + // { + // ExtensionPoint ext; + // SorobanResources resources; + // // Amount of the transaction `fee` allocated to the Soroban resource fees. + // // The fraction of `resourceFee` corresponding to `resources` specified + // // above is *not* refundable (i.e. fees for instructions, ledger I/O), as + // // well as fees for the transaction size. + // // The remaining part of the fee is refundable and the charged value is + // // based on the actual consumption of refundable resources (events, ledger + // // rent bumps). + // // The `inclusionFee` used for prioritization of the transaction is defined + // // as `tx.fee - resourceFee`. + // int64 resourceFee; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionData", [["ext", xdr.lookup("ExtensionPoint")], ["resources", xdr.lookup("SorobanResources")], ["resourceFee", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionV0Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionV0 + // { + // uint256 sourceAccountEd25519; + // uint32 fee; + // SequenceNumber seqNum; + // TimeBounds* timeBounds; + // Memo memo; + // Operation operations; + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionV0", [["sourceAccountEd25519", xdr.lookup("Uint256")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionV0Ext")]]); + + // === xdr source ============================================================ + // + // struct TransactionV0Envelope + // { + // TransactionV0 tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("TransactionV0Envelope", [["tx", xdr.lookup("TransactionV0")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionData sorobanData; + // } + // + // =========================================================================== + xdr.union("TransactionExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "sorobanData"]], + arms: { + sorobanData: xdr.lookup("SorobanTransactionData") + } + }); + + // === xdr source ============================================================ + // + // struct Transaction + // { + // // account used to run the transaction + // MuxedAccount sourceAccount; + // + // // the fee the sourceAccount will pay + // uint32 fee; + // + // // sequence number to consume in the account + // SequenceNumber seqNum; + // + // // validity conditions + // Preconditions cond; + // + // Memo memo; + // + // Operation operations; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionData sorobanData; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("Transaction", [["sourceAccount", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["cond", xdr.lookup("Preconditions")], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionExt")]]); + + // === xdr source ============================================================ + // + // struct TransactionV1Envelope + // { + // Transaction tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("TransactionV1Envelope", [["tx", xdr.lookup("Transaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // } + // + // =========================================================================== + xdr.union("FeeBumpTransactionInnerTx", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTx", "v1"]], + arms: { + v1: xdr.lookup("TransactionV1Envelope") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("FeeBumpTransactionExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct FeeBumpTransaction + // { + // MuxedAccount feeSource; + // int64 fee; + // union switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // } + // innerTx; + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("FeeBumpTransaction", [["feeSource", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Int64")], ["innerTx", xdr.lookup("FeeBumpTransactionInnerTx")], ["ext", xdr.lookup("FeeBumpTransactionExt")]]); + + // === xdr source ============================================================ + // + // struct FeeBumpTransactionEnvelope + // { + // FeeBumpTransaction tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("FeeBumpTransactionEnvelope", [["tx", xdr.lookup("FeeBumpTransaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union TransactionEnvelope switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX_V0: + // TransactionV0Envelope v0; + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransactionEnvelope feeBump; + // }; + // + // =========================================================================== + xdr.union("TransactionEnvelope", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTxV0", "v0"], ["envelopeTypeTx", "v1"], ["envelopeTypeTxFeeBump", "feeBump"]], + arms: { + v0: xdr.lookup("TransactionV0Envelope"), + v1: xdr.lookup("TransactionV1Envelope"), + feeBump: xdr.lookup("FeeBumpTransactionEnvelope") + } + }); + + // === xdr source ============================================================ + // + // union switch (EnvelopeType type) + // { + // // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // case ENVELOPE_TYPE_TX: + // Transaction tx; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransaction feeBump; + // } + // + // =========================================================================== + xdr.union("TransactionSignaturePayloadTaggedTransaction", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTx", "tx"], ["envelopeTypeTxFeeBump", "feeBump"]], + arms: { + tx: xdr.lookup("Transaction"), + feeBump: xdr.lookup("FeeBumpTransaction") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionSignaturePayload + // { + // Hash networkId; + // union switch (EnvelopeType type) + // { + // // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // case ENVELOPE_TYPE_TX: + // Transaction tx; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransaction feeBump; + // } + // taggedTransaction; + // }; + // + // =========================================================================== + xdr.struct("TransactionSignaturePayload", [["networkId", xdr.lookup("Hash")], ["taggedTransaction", xdr.lookup("TransactionSignaturePayloadTaggedTransaction")]]); + + // === xdr source ============================================================ + // + // enum ClaimAtomType + // { + // CLAIM_ATOM_TYPE_V0 = 0, + // CLAIM_ATOM_TYPE_ORDER_BOOK = 1, + // CLAIM_ATOM_TYPE_LIQUIDITY_POOL = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimAtomType", { + claimAtomTypeV0: 0, + claimAtomTypeOrderBook: 1, + claimAtomTypeLiquidityPool: 2 + }); + + // === xdr source ============================================================ + // + // struct ClaimOfferAtomV0 + // { + // // emitted to identify the offer + // uint256 sellerEd25519; // Account that owns the offer + // int64 offerID; + // + // // amount and asset taken from the owner + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the owner + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimOfferAtomV0", [["sellerEd25519", xdr.lookup("Uint256")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClaimOfferAtom + // { + // // emitted to identify the offer + // AccountID sellerID; // Account that owns the offer + // int64 offerID; + // + // // amount and asset taken from the owner + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the owner + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimOfferAtom", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClaimLiquidityAtom + // { + // PoolID liquidityPoolID; + // + // // amount and asset taken from the pool + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the pool + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimLiquidityAtom", [["liquidityPoolId", xdr.lookup("PoolId")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union ClaimAtom switch (ClaimAtomType type) + // { + // case CLAIM_ATOM_TYPE_V0: + // ClaimOfferAtomV0 v0; + // case CLAIM_ATOM_TYPE_ORDER_BOOK: + // ClaimOfferAtom orderBook; + // case CLAIM_ATOM_TYPE_LIQUIDITY_POOL: + // ClaimLiquidityAtom liquidityPool; + // }; + // + // =========================================================================== + xdr.union("ClaimAtom", { + switchOn: xdr.lookup("ClaimAtomType"), + switchName: "type", + switches: [["claimAtomTypeV0", "v0"], ["claimAtomTypeOrderBook", "orderBook"], ["claimAtomTypeLiquidityPool", "liquidityPool"]], + arms: { + v0: xdr.lookup("ClaimOfferAtomV0"), + orderBook: xdr.lookup("ClaimOfferAtom"), + liquidityPool: xdr.lookup("ClaimLiquidityAtom") + } + }); + + // === xdr source ============================================================ + // + // enum CreateAccountResultCode + // { + // // codes considered as "success" for the operation + // CREATE_ACCOUNT_SUCCESS = 0, // account was created + // + // // codes considered as "failure" for the operation + // CREATE_ACCOUNT_MALFORMED = -1, // invalid destination + // CREATE_ACCOUNT_UNDERFUNDED = -2, // not enough funds in source account + // CREATE_ACCOUNT_LOW_RESERVE = + // -3, // would create an account below the min reserve + // CREATE_ACCOUNT_ALREADY_EXIST = -4 // account already exists + // }; + // + // =========================================================================== + xdr["enum"]("CreateAccountResultCode", { + createAccountSuccess: 0, + createAccountMalformed: -1, + createAccountUnderfunded: -2, + createAccountLowReserve: -3, + createAccountAlreadyExist: -4 + }); + + // === xdr source ============================================================ + // + // union CreateAccountResult switch (CreateAccountResultCode code) + // { + // case CREATE_ACCOUNT_SUCCESS: + // void; + // case CREATE_ACCOUNT_MALFORMED: + // case CREATE_ACCOUNT_UNDERFUNDED: + // case CREATE_ACCOUNT_LOW_RESERVE: + // case CREATE_ACCOUNT_ALREADY_EXIST: + // void; + // }; + // + // =========================================================================== + xdr.union("CreateAccountResult", { + switchOn: xdr.lookup("CreateAccountResultCode"), + switchName: "code", + switches: [["createAccountSuccess", xdr["void"]()], ["createAccountMalformed", xdr["void"]()], ["createAccountUnderfunded", xdr["void"]()], ["createAccountLowReserve", xdr["void"]()], ["createAccountAlreadyExist", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum PaymentResultCode + // { + // // codes considered as "success" for the operation + // PAYMENT_SUCCESS = 0, // payment successfully completed + // + // // codes considered as "failure" for the operation + // PAYMENT_MALFORMED = -1, // bad input + // PAYMENT_UNDERFUNDED = -2, // not enough funds in source account + // PAYMENT_SRC_NO_TRUST = -3, // no trust line on source account + // PAYMENT_SRC_NOT_AUTHORIZED = -4, // source not authorized to transfer + // PAYMENT_NO_DESTINATION = -5, // destination account does not exist + // PAYMENT_NO_TRUST = -6, // destination missing a trust line for asset + // PAYMENT_NOT_AUTHORIZED = -7, // destination not authorized to hold asset + // PAYMENT_LINE_FULL = -8, // destination would go above their limit + // PAYMENT_NO_ISSUER = -9 // missing issuer on asset + // }; + // + // =========================================================================== + xdr["enum"]("PaymentResultCode", { + paymentSuccess: 0, + paymentMalformed: -1, + paymentUnderfunded: -2, + paymentSrcNoTrust: -3, + paymentSrcNotAuthorized: -4, + paymentNoDestination: -5, + paymentNoTrust: -6, + paymentNotAuthorized: -7, + paymentLineFull: -8, + paymentNoIssuer: -9 + }); + + // === xdr source ============================================================ + // + // union PaymentResult switch (PaymentResultCode code) + // { + // case PAYMENT_SUCCESS: + // void; + // case PAYMENT_MALFORMED: + // case PAYMENT_UNDERFUNDED: + // case PAYMENT_SRC_NO_TRUST: + // case PAYMENT_SRC_NOT_AUTHORIZED: + // case PAYMENT_NO_DESTINATION: + // case PAYMENT_NO_TRUST: + // case PAYMENT_NOT_AUTHORIZED: + // case PAYMENT_LINE_FULL: + // case PAYMENT_NO_ISSUER: + // void; + // }; + // + // =========================================================================== + xdr.union("PaymentResult", { + switchOn: xdr.lookup("PaymentResultCode"), + switchName: "code", + switches: [["paymentSuccess", xdr["void"]()], ["paymentMalformed", xdr["void"]()], ["paymentUnderfunded", xdr["void"]()], ["paymentSrcNoTrust", xdr["void"]()], ["paymentSrcNotAuthorized", xdr["void"]()], ["paymentNoDestination", xdr["void"]()], ["paymentNoTrust", xdr["void"]()], ["paymentNotAuthorized", xdr["void"]()], ["paymentLineFull", xdr["void"]()], ["paymentNoIssuer", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum PathPaymentStrictReceiveResultCode + // { + // // codes considered as "success" for the operation + // PATH_PAYMENT_STRICT_RECEIVE_SUCCESS = 0, // success + // + // // codes considered as "failure" for the operation + // PATH_PAYMENT_STRICT_RECEIVE_MALFORMED = -1, // bad input + // PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED = + // -2, // not enough funds in source account + // PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST = + // -3, // no trust line on source account + // PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED = + // -4, // source not authorized to transfer + // PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION = + // -5, // destination account does not exist + // PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST = + // -6, // dest missing a trust line for asset + // PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED = + // -7, // dest not authorized to hold asset + // PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL = + // -8, // dest would go above their limit + // PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER = -9, // missing issuer on one asset + // PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS = + // -10, // not enough offers to satisfy path + // PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF = + // -11, // would cross one of its own offers + // PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX = -12 // could not satisfy sendmax + // }; + // + // =========================================================================== + xdr["enum"]("PathPaymentStrictReceiveResultCode", { + pathPaymentStrictReceiveSuccess: 0, + pathPaymentStrictReceiveMalformed: -1, + pathPaymentStrictReceiveUnderfunded: -2, + pathPaymentStrictReceiveSrcNoTrust: -3, + pathPaymentStrictReceiveSrcNotAuthorized: -4, + pathPaymentStrictReceiveNoDestination: -5, + pathPaymentStrictReceiveNoTrust: -6, + pathPaymentStrictReceiveNotAuthorized: -7, + pathPaymentStrictReceiveLineFull: -8, + pathPaymentStrictReceiveNoIssuer: -9, + pathPaymentStrictReceiveTooFewOffers: -10, + pathPaymentStrictReceiveOfferCrossSelf: -11, + pathPaymentStrictReceiveOverSendmax: -12 + }); + + // === xdr source ============================================================ + // + // struct SimplePaymentResult + // { + // AccountID destination; + // Asset asset; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("SimplePaymentResult", [["destination", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } + // + // =========================================================================== + xdr.struct("PathPaymentStrictReceiveResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]); + + // === xdr source ============================================================ + // + // union PathPaymentStrictReceiveResult switch ( + // PathPaymentStrictReceiveResultCode code) + // { + // case PATH_PAYMENT_STRICT_RECEIVE_SUCCESS: + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } success; + // case PATH_PAYMENT_STRICT_RECEIVE_MALFORMED: + // case PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED: + // case PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST: + // case PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION: + // case PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST: + // case PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL: + // void; + // case PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER: + // Asset noIssuer; // the asset that caused the error + // case PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS: + // case PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF: + // case PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX: + // void; + // }; + // + // =========================================================================== + xdr.union("PathPaymentStrictReceiveResult", { + switchOn: xdr.lookup("PathPaymentStrictReceiveResultCode"), + switchName: "code", + switches: [["pathPaymentStrictReceiveSuccess", "success"], ["pathPaymentStrictReceiveMalformed", xdr["void"]()], ["pathPaymentStrictReceiveUnderfunded", xdr["void"]()], ["pathPaymentStrictReceiveSrcNoTrust", xdr["void"]()], ["pathPaymentStrictReceiveSrcNotAuthorized", xdr["void"]()], ["pathPaymentStrictReceiveNoDestination", xdr["void"]()], ["pathPaymentStrictReceiveNoTrust", xdr["void"]()], ["pathPaymentStrictReceiveNotAuthorized", xdr["void"]()], ["pathPaymentStrictReceiveLineFull", xdr["void"]()], ["pathPaymentStrictReceiveNoIssuer", "noIssuer"], ["pathPaymentStrictReceiveTooFewOffers", xdr["void"]()], ["pathPaymentStrictReceiveOfferCrossSelf", xdr["void"]()], ["pathPaymentStrictReceiveOverSendmax", xdr["void"]()]], + arms: { + success: xdr.lookup("PathPaymentStrictReceiveResultSuccess"), + noIssuer: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // enum PathPaymentStrictSendResultCode + // { + // // codes considered as "success" for the operation + // PATH_PAYMENT_STRICT_SEND_SUCCESS = 0, // success + // + // // codes considered as "failure" for the operation + // PATH_PAYMENT_STRICT_SEND_MALFORMED = -1, // bad input + // PATH_PAYMENT_STRICT_SEND_UNDERFUNDED = + // -2, // not enough funds in source account + // PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST = + // -3, // no trust line on source account + // PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED = + // -4, // source not authorized to transfer + // PATH_PAYMENT_STRICT_SEND_NO_DESTINATION = + // -5, // destination account does not exist + // PATH_PAYMENT_STRICT_SEND_NO_TRUST = + // -6, // dest missing a trust line for asset + // PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED = + // -7, // dest not authorized to hold asset + // PATH_PAYMENT_STRICT_SEND_LINE_FULL = -8, // dest would go above their limit + // PATH_PAYMENT_STRICT_SEND_NO_ISSUER = -9, // missing issuer on one asset + // PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS = + // -10, // not enough offers to satisfy path + // PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF = + // -11, // would cross one of its own offers + // PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN = -12 // could not satisfy destMin + // }; + // + // =========================================================================== + xdr["enum"]("PathPaymentStrictSendResultCode", { + pathPaymentStrictSendSuccess: 0, + pathPaymentStrictSendMalformed: -1, + pathPaymentStrictSendUnderfunded: -2, + pathPaymentStrictSendSrcNoTrust: -3, + pathPaymentStrictSendSrcNotAuthorized: -4, + pathPaymentStrictSendNoDestination: -5, + pathPaymentStrictSendNoTrust: -6, + pathPaymentStrictSendNotAuthorized: -7, + pathPaymentStrictSendLineFull: -8, + pathPaymentStrictSendNoIssuer: -9, + pathPaymentStrictSendTooFewOffers: -10, + pathPaymentStrictSendOfferCrossSelf: -11, + pathPaymentStrictSendUnderDestmin: -12 + }); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } + // + // =========================================================================== + xdr.struct("PathPaymentStrictSendResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]); + + // === xdr source ============================================================ + // + // union PathPaymentStrictSendResult switch (PathPaymentStrictSendResultCode code) + // { + // case PATH_PAYMENT_STRICT_SEND_SUCCESS: + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } success; + // case PATH_PAYMENT_STRICT_SEND_MALFORMED: + // case PATH_PAYMENT_STRICT_SEND_UNDERFUNDED: + // case PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST: + // case PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_SEND_NO_DESTINATION: + // case PATH_PAYMENT_STRICT_SEND_NO_TRUST: + // case PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_SEND_LINE_FULL: + // void; + // case PATH_PAYMENT_STRICT_SEND_NO_ISSUER: + // Asset noIssuer; // the asset that caused the error + // case PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS: + // case PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF: + // case PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN: + // void; + // }; + // + // =========================================================================== + xdr.union("PathPaymentStrictSendResult", { + switchOn: xdr.lookup("PathPaymentStrictSendResultCode"), + switchName: "code", + switches: [["pathPaymentStrictSendSuccess", "success"], ["pathPaymentStrictSendMalformed", xdr["void"]()], ["pathPaymentStrictSendUnderfunded", xdr["void"]()], ["pathPaymentStrictSendSrcNoTrust", xdr["void"]()], ["pathPaymentStrictSendSrcNotAuthorized", xdr["void"]()], ["pathPaymentStrictSendNoDestination", xdr["void"]()], ["pathPaymentStrictSendNoTrust", xdr["void"]()], ["pathPaymentStrictSendNotAuthorized", xdr["void"]()], ["pathPaymentStrictSendLineFull", xdr["void"]()], ["pathPaymentStrictSendNoIssuer", "noIssuer"], ["pathPaymentStrictSendTooFewOffers", xdr["void"]()], ["pathPaymentStrictSendOfferCrossSelf", xdr["void"]()], ["pathPaymentStrictSendUnderDestmin", xdr["void"]()]], + arms: { + success: xdr.lookup("PathPaymentStrictSendResultSuccess"), + noIssuer: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // enum ManageSellOfferResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_SELL_OFFER_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // MANAGE_SELL_OFFER_MALFORMED = -1, // generated offer would be invalid + // MANAGE_SELL_OFFER_SELL_NO_TRUST = + // -2, // no trust line for what we're selling + // MANAGE_SELL_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying + // MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell + // MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy + // MANAGE_SELL_OFFER_LINE_FULL = -6, // can't receive more of what it's buying + // MANAGE_SELL_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell + // MANAGE_SELL_OFFER_CROSS_SELF = + // -8, // would cross an offer from the same user + // MANAGE_SELL_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling + // MANAGE_SELL_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying + // + // // update errors + // MANAGE_SELL_OFFER_NOT_FOUND = + // -11, // offerID does not match an existing offer + // + // MANAGE_SELL_OFFER_LOW_RESERVE = + // -12 // not enough funds to create a new Offer + // }; + // + // =========================================================================== + xdr["enum"]("ManageSellOfferResultCode", { + manageSellOfferSuccess: 0, + manageSellOfferMalformed: -1, + manageSellOfferSellNoTrust: -2, + manageSellOfferBuyNoTrust: -3, + manageSellOfferSellNotAuthorized: -4, + manageSellOfferBuyNotAuthorized: -5, + manageSellOfferLineFull: -6, + manageSellOfferUnderfunded: -7, + manageSellOfferCrossSelf: -8, + manageSellOfferSellNoIssuer: -9, + manageSellOfferBuyNoIssuer: -10, + manageSellOfferNotFound: -11, + manageSellOfferLowReserve: -12 + }); + + // === xdr source ============================================================ + // + // enum ManageOfferEffect + // { + // MANAGE_OFFER_CREATED = 0, + // MANAGE_OFFER_UPDATED = 1, + // MANAGE_OFFER_DELETED = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ManageOfferEffect", { + manageOfferCreated: 0, + manageOfferUpdated: 1, + manageOfferDeleted: 2 + }); + + // === xdr source ============================================================ + // + // union switch (ManageOfferEffect effect) + // { + // case MANAGE_OFFER_CREATED: + // case MANAGE_OFFER_UPDATED: + // OfferEntry offer; + // case MANAGE_OFFER_DELETED: + // void; + // } + // + // =========================================================================== + xdr.union("ManageOfferSuccessResultOffer", { + switchOn: xdr.lookup("ManageOfferEffect"), + switchName: "effect", + switches: [["manageOfferCreated", "offer"], ["manageOfferUpdated", "offer"], ["manageOfferDeleted", xdr["void"]()]], + arms: { + offer: xdr.lookup("OfferEntry") + } + }); + + // === xdr source ============================================================ + // + // struct ManageOfferSuccessResult + // { + // // offers that got claimed while creating this offer + // ClaimAtom offersClaimed<>; + // + // union switch (ManageOfferEffect effect) + // { + // case MANAGE_OFFER_CREATED: + // case MANAGE_OFFER_UPDATED: + // OfferEntry offer; + // case MANAGE_OFFER_DELETED: + // void; + // } + // offer; + // }; + // + // =========================================================================== + xdr.struct("ManageOfferSuccessResult", [["offersClaimed", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["offer", xdr.lookup("ManageOfferSuccessResultOffer")]]); + + // === xdr source ============================================================ + // + // union ManageSellOfferResult switch (ManageSellOfferResultCode code) + // { + // case MANAGE_SELL_OFFER_SUCCESS: + // ManageOfferSuccessResult success; + // case MANAGE_SELL_OFFER_MALFORMED: + // case MANAGE_SELL_OFFER_SELL_NO_TRUST: + // case MANAGE_SELL_OFFER_BUY_NO_TRUST: + // case MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED: + // case MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED: + // case MANAGE_SELL_OFFER_LINE_FULL: + // case MANAGE_SELL_OFFER_UNDERFUNDED: + // case MANAGE_SELL_OFFER_CROSS_SELF: + // case MANAGE_SELL_OFFER_SELL_NO_ISSUER: + // case MANAGE_SELL_OFFER_BUY_NO_ISSUER: + // case MANAGE_SELL_OFFER_NOT_FOUND: + // case MANAGE_SELL_OFFER_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageSellOfferResult", { + switchOn: xdr.lookup("ManageSellOfferResultCode"), + switchName: "code", + switches: [["manageSellOfferSuccess", "success"], ["manageSellOfferMalformed", xdr["void"]()], ["manageSellOfferSellNoTrust", xdr["void"]()], ["manageSellOfferBuyNoTrust", xdr["void"]()], ["manageSellOfferSellNotAuthorized", xdr["void"]()], ["manageSellOfferBuyNotAuthorized", xdr["void"]()], ["manageSellOfferLineFull", xdr["void"]()], ["manageSellOfferUnderfunded", xdr["void"]()], ["manageSellOfferCrossSelf", xdr["void"]()], ["manageSellOfferSellNoIssuer", xdr["void"]()], ["manageSellOfferBuyNoIssuer", xdr["void"]()], ["manageSellOfferNotFound", xdr["void"]()], ["manageSellOfferLowReserve", xdr["void"]()]], + arms: { + success: xdr.lookup("ManageOfferSuccessResult") + } + }); + + // === xdr source ============================================================ + // + // enum ManageBuyOfferResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_BUY_OFFER_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // MANAGE_BUY_OFFER_MALFORMED = -1, // generated offer would be invalid + // MANAGE_BUY_OFFER_SELL_NO_TRUST = -2, // no trust line for what we're selling + // MANAGE_BUY_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying + // MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell + // MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy + // MANAGE_BUY_OFFER_LINE_FULL = -6, // can't receive more of what it's buying + // MANAGE_BUY_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell + // MANAGE_BUY_OFFER_CROSS_SELF = -8, // would cross an offer from the same user + // MANAGE_BUY_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling + // MANAGE_BUY_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying + // + // // update errors + // MANAGE_BUY_OFFER_NOT_FOUND = + // -11, // offerID does not match an existing offer + // + // MANAGE_BUY_OFFER_LOW_RESERVE = -12 // not enough funds to create a new Offer + // }; + // + // =========================================================================== + xdr["enum"]("ManageBuyOfferResultCode", { + manageBuyOfferSuccess: 0, + manageBuyOfferMalformed: -1, + manageBuyOfferSellNoTrust: -2, + manageBuyOfferBuyNoTrust: -3, + manageBuyOfferSellNotAuthorized: -4, + manageBuyOfferBuyNotAuthorized: -5, + manageBuyOfferLineFull: -6, + manageBuyOfferUnderfunded: -7, + manageBuyOfferCrossSelf: -8, + manageBuyOfferSellNoIssuer: -9, + manageBuyOfferBuyNoIssuer: -10, + manageBuyOfferNotFound: -11, + manageBuyOfferLowReserve: -12 + }); + + // === xdr source ============================================================ + // + // union ManageBuyOfferResult switch (ManageBuyOfferResultCode code) + // { + // case MANAGE_BUY_OFFER_SUCCESS: + // ManageOfferSuccessResult success; + // case MANAGE_BUY_OFFER_MALFORMED: + // case MANAGE_BUY_OFFER_SELL_NO_TRUST: + // case MANAGE_BUY_OFFER_BUY_NO_TRUST: + // case MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED: + // case MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED: + // case MANAGE_BUY_OFFER_LINE_FULL: + // case MANAGE_BUY_OFFER_UNDERFUNDED: + // case MANAGE_BUY_OFFER_CROSS_SELF: + // case MANAGE_BUY_OFFER_SELL_NO_ISSUER: + // case MANAGE_BUY_OFFER_BUY_NO_ISSUER: + // case MANAGE_BUY_OFFER_NOT_FOUND: + // case MANAGE_BUY_OFFER_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageBuyOfferResult", { + switchOn: xdr.lookup("ManageBuyOfferResultCode"), + switchName: "code", + switches: [["manageBuyOfferSuccess", "success"], ["manageBuyOfferMalformed", xdr["void"]()], ["manageBuyOfferSellNoTrust", xdr["void"]()], ["manageBuyOfferBuyNoTrust", xdr["void"]()], ["manageBuyOfferSellNotAuthorized", xdr["void"]()], ["manageBuyOfferBuyNotAuthorized", xdr["void"]()], ["manageBuyOfferLineFull", xdr["void"]()], ["manageBuyOfferUnderfunded", xdr["void"]()], ["manageBuyOfferCrossSelf", xdr["void"]()], ["manageBuyOfferSellNoIssuer", xdr["void"]()], ["manageBuyOfferBuyNoIssuer", xdr["void"]()], ["manageBuyOfferNotFound", xdr["void"]()], ["manageBuyOfferLowReserve", xdr["void"]()]], + arms: { + success: xdr.lookup("ManageOfferSuccessResult") + } + }); + + // === xdr source ============================================================ + // + // enum SetOptionsResultCode + // { + // // codes considered as "success" for the operation + // SET_OPTIONS_SUCCESS = 0, + // // codes considered as "failure" for the operation + // SET_OPTIONS_LOW_RESERVE = -1, // not enough funds to add a signer + // SET_OPTIONS_TOO_MANY_SIGNERS = -2, // max number of signers already reached + // SET_OPTIONS_BAD_FLAGS = -3, // invalid combination of clear/set flags + // SET_OPTIONS_INVALID_INFLATION = -4, // inflation account does not exist + // SET_OPTIONS_CANT_CHANGE = -5, // can no longer change this option + // SET_OPTIONS_UNKNOWN_FLAG = -6, // can't set an unknown flag + // SET_OPTIONS_THRESHOLD_OUT_OF_RANGE = -7, // bad value for weight/threshold + // SET_OPTIONS_BAD_SIGNER = -8, // signer cannot be masterkey + // SET_OPTIONS_INVALID_HOME_DOMAIN = -9, // malformed home domain + // SET_OPTIONS_AUTH_REVOCABLE_REQUIRED = + // -10 // auth revocable is required for clawback + // }; + // + // =========================================================================== + xdr["enum"]("SetOptionsResultCode", { + setOptionsSuccess: 0, + setOptionsLowReserve: -1, + setOptionsTooManySigners: -2, + setOptionsBadFlags: -3, + setOptionsInvalidInflation: -4, + setOptionsCantChange: -5, + setOptionsUnknownFlag: -6, + setOptionsThresholdOutOfRange: -7, + setOptionsBadSigner: -8, + setOptionsInvalidHomeDomain: -9, + setOptionsAuthRevocableRequired: -10 + }); + + // === xdr source ============================================================ + // + // union SetOptionsResult switch (SetOptionsResultCode code) + // { + // case SET_OPTIONS_SUCCESS: + // void; + // case SET_OPTIONS_LOW_RESERVE: + // case SET_OPTIONS_TOO_MANY_SIGNERS: + // case SET_OPTIONS_BAD_FLAGS: + // case SET_OPTIONS_INVALID_INFLATION: + // case SET_OPTIONS_CANT_CHANGE: + // case SET_OPTIONS_UNKNOWN_FLAG: + // case SET_OPTIONS_THRESHOLD_OUT_OF_RANGE: + // case SET_OPTIONS_BAD_SIGNER: + // case SET_OPTIONS_INVALID_HOME_DOMAIN: + // case SET_OPTIONS_AUTH_REVOCABLE_REQUIRED: + // void; + // }; + // + // =========================================================================== + xdr.union("SetOptionsResult", { + switchOn: xdr.lookup("SetOptionsResultCode"), + switchName: "code", + switches: [["setOptionsSuccess", xdr["void"]()], ["setOptionsLowReserve", xdr["void"]()], ["setOptionsTooManySigners", xdr["void"]()], ["setOptionsBadFlags", xdr["void"]()], ["setOptionsInvalidInflation", xdr["void"]()], ["setOptionsCantChange", xdr["void"]()], ["setOptionsUnknownFlag", xdr["void"]()], ["setOptionsThresholdOutOfRange", xdr["void"]()], ["setOptionsBadSigner", xdr["void"]()], ["setOptionsInvalidHomeDomain", xdr["void"]()], ["setOptionsAuthRevocableRequired", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ChangeTrustResultCode + // { + // // codes considered as "success" for the operation + // CHANGE_TRUST_SUCCESS = 0, + // // codes considered as "failure" for the operation + // CHANGE_TRUST_MALFORMED = -1, // bad input + // CHANGE_TRUST_NO_ISSUER = -2, // could not find issuer + // CHANGE_TRUST_INVALID_LIMIT = -3, // cannot drop limit below balance + // // cannot create with a limit of 0 + // CHANGE_TRUST_LOW_RESERVE = + // -4, // not enough funds to create a new trust line, + // CHANGE_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed + // CHANGE_TRUST_TRUST_LINE_MISSING = -6, // Asset trustline is missing for pool + // CHANGE_TRUST_CANNOT_DELETE = + // -7, // Asset trustline is still referenced in a pool + // CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES = + // -8 // Asset trustline is deauthorized + // }; + // + // =========================================================================== + xdr["enum"]("ChangeTrustResultCode", { + changeTrustSuccess: 0, + changeTrustMalformed: -1, + changeTrustNoIssuer: -2, + changeTrustInvalidLimit: -3, + changeTrustLowReserve: -4, + changeTrustSelfNotAllowed: -5, + changeTrustTrustLineMissing: -6, + changeTrustCannotDelete: -7, + changeTrustNotAuthMaintainLiabilities: -8 + }); + + // === xdr source ============================================================ + // + // union ChangeTrustResult switch (ChangeTrustResultCode code) + // { + // case CHANGE_TRUST_SUCCESS: + // void; + // case CHANGE_TRUST_MALFORMED: + // case CHANGE_TRUST_NO_ISSUER: + // case CHANGE_TRUST_INVALID_LIMIT: + // case CHANGE_TRUST_LOW_RESERVE: + // case CHANGE_TRUST_SELF_NOT_ALLOWED: + // case CHANGE_TRUST_TRUST_LINE_MISSING: + // case CHANGE_TRUST_CANNOT_DELETE: + // case CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES: + // void; + // }; + // + // =========================================================================== + xdr.union("ChangeTrustResult", { + switchOn: xdr.lookup("ChangeTrustResultCode"), + switchName: "code", + switches: [["changeTrustSuccess", xdr["void"]()], ["changeTrustMalformed", xdr["void"]()], ["changeTrustNoIssuer", xdr["void"]()], ["changeTrustInvalidLimit", xdr["void"]()], ["changeTrustLowReserve", xdr["void"]()], ["changeTrustSelfNotAllowed", xdr["void"]()], ["changeTrustTrustLineMissing", xdr["void"]()], ["changeTrustCannotDelete", xdr["void"]()], ["changeTrustNotAuthMaintainLiabilities", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum AllowTrustResultCode + // { + // // codes considered as "success" for the operation + // ALLOW_TRUST_SUCCESS = 0, + // // codes considered as "failure" for the operation + // ALLOW_TRUST_MALFORMED = -1, // asset is not ASSET_TYPE_ALPHANUM + // ALLOW_TRUST_NO_TRUST_LINE = -2, // trustor does not have a trustline + // // source account does not require trust + // ALLOW_TRUST_TRUST_NOT_REQUIRED = -3, + // ALLOW_TRUST_CANT_REVOKE = -4, // source account can't revoke trust, + // ALLOW_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed + // ALLOW_TRUST_LOW_RESERVE = -6 // claimable balances can't be created + // // on revoke due to low reserves + // }; + // + // =========================================================================== + xdr["enum"]("AllowTrustResultCode", { + allowTrustSuccess: 0, + allowTrustMalformed: -1, + allowTrustNoTrustLine: -2, + allowTrustTrustNotRequired: -3, + allowTrustCantRevoke: -4, + allowTrustSelfNotAllowed: -5, + allowTrustLowReserve: -6 + }); + + // === xdr source ============================================================ + // + // union AllowTrustResult switch (AllowTrustResultCode code) + // { + // case ALLOW_TRUST_SUCCESS: + // void; + // case ALLOW_TRUST_MALFORMED: + // case ALLOW_TRUST_NO_TRUST_LINE: + // case ALLOW_TRUST_TRUST_NOT_REQUIRED: + // case ALLOW_TRUST_CANT_REVOKE: + // case ALLOW_TRUST_SELF_NOT_ALLOWED: + // case ALLOW_TRUST_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("AllowTrustResult", { + switchOn: xdr.lookup("AllowTrustResultCode"), + switchName: "code", + switches: [["allowTrustSuccess", xdr["void"]()], ["allowTrustMalformed", xdr["void"]()], ["allowTrustNoTrustLine", xdr["void"]()], ["allowTrustTrustNotRequired", xdr["void"]()], ["allowTrustCantRevoke", xdr["void"]()], ["allowTrustSelfNotAllowed", xdr["void"]()], ["allowTrustLowReserve", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum AccountMergeResultCode + // { + // // codes considered as "success" for the operation + // ACCOUNT_MERGE_SUCCESS = 0, + // // codes considered as "failure" for the operation + // ACCOUNT_MERGE_MALFORMED = -1, // can't merge onto itself + // ACCOUNT_MERGE_NO_ACCOUNT = -2, // destination does not exist + // ACCOUNT_MERGE_IMMUTABLE_SET = -3, // source account has AUTH_IMMUTABLE set + // ACCOUNT_MERGE_HAS_SUB_ENTRIES = -4, // account has trust lines/offers + // ACCOUNT_MERGE_SEQNUM_TOO_FAR = -5, // sequence number is over max allowed + // ACCOUNT_MERGE_DEST_FULL = -6, // can't add source balance to + // // destination balance + // ACCOUNT_MERGE_IS_SPONSOR = -7 // can't merge account that is a sponsor + // }; + // + // =========================================================================== + xdr["enum"]("AccountMergeResultCode", { + accountMergeSuccess: 0, + accountMergeMalformed: -1, + accountMergeNoAccount: -2, + accountMergeImmutableSet: -3, + accountMergeHasSubEntries: -4, + accountMergeSeqnumTooFar: -5, + accountMergeDestFull: -6, + accountMergeIsSponsor: -7 + }); + + // === xdr source ============================================================ + // + // union AccountMergeResult switch (AccountMergeResultCode code) + // { + // case ACCOUNT_MERGE_SUCCESS: + // int64 sourceAccountBalance; // how much got transferred from source account + // case ACCOUNT_MERGE_MALFORMED: + // case ACCOUNT_MERGE_NO_ACCOUNT: + // case ACCOUNT_MERGE_IMMUTABLE_SET: + // case ACCOUNT_MERGE_HAS_SUB_ENTRIES: + // case ACCOUNT_MERGE_SEQNUM_TOO_FAR: + // case ACCOUNT_MERGE_DEST_FULL: + // case ACCOUNT_MERGE_IS_SPONSOR: + // void; + // }; + // + // =========================================================================== + xdr.union("AccountMergeResult", { + switchOn: xdr.lookup("AccountMergeResultCode"), + switchName: "code", + switches: [["accountMergeSuccess", "sourceAccountBalance"], ["accountMergeMalformed", xdr["void"]()], ["accountMergeNoAccount", xdr["void"]()], ["accountMergeImmutableSet", xdr["void"]()], ["accountMergeHasSubEntries", xdr["void"]()], ["accountMergeSeqnumTooFar", xdr["void"]()], ["accountMergeDestFull", xdr["void"]()], ["accountMergeIsSponsor", xdr["void"]()]], + arms: { + sourceAccountBalance: xdr.lookup("Int64") + } + }); + + // === xdr source ============================================================ + // + // enum InflationResultCode + // { + // // codes considered as "success" for the operation + // INFLATION_SUCCESS = 0, + // // codes considered as "failure" for the operation + // INFLATION_NOT_TIME = -1 + // }; + // + // =========================================================================== + xdr["enum"]("InflationResultCode", { + inflationSuccess: 0, + inflationNotTime: -1 + }); + + // === xdr source ============================================================ + // + // struct InflationPayout // or use PaymentResultAtom to limit types? + // { + // AccountID destination; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("InflationPayout", [["destination", xdr.lookup("AccountId")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union InflationResult switch (InflationResultCode code) + // { + // case INFLATION_SUCCESS: + // InflationPayout payouts<>; + // case INFLATION_NOT_TIME: + // void; + // }; + // + // =========================================================================== + xdr.union("InflationResult", { + switchOn: xdr.lookup("InflationResultCode"), + switchName: "code", + switches: [["inflationSuccess", "payouts"], ["inflationNotTime", xdr["void"]()]], + arms: { + payouts: xdr.varArray(xdr.lookup("InflationPayout"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // enum ManageDataResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_DATA_SUCCESS = 0, + // // codes considered as "failure" for the operation + // MANAGE_DATA_NOT_SUPPORTED_YET = + // -1, // The network hasn't moved to this protocol change yet + // MANAGE_DATA_NAME_NOT_FOUND = + // -2, // Trying to remove a Data Entry that isn't there + // MANAGE_DATA_LOW_RESERVE = -3, // not enough funds to create a new Data Entry + // MANAGE_DATA_INVALID_NAME = -4 // Name not a valid string + // }; + // + // =========================================================================== + xdr["enum"]("ManageDataResultCode", { + manageDataSuccess: 0, + manageDataNotSupportedYet: -1, + manageDataNameNotFound: -2, + manageDataLowReserve: -3, + manageDataInvalidName: -4 + }); + + // === xdr source ============================================================ + // + // union ManageDataResult switch (ManageDataResultCode code) + // { + // case MANAGE_DATA_SUCCESS: + // void; + // case MANAGE_DATA_NOT_SUPPORTED_YET: + // case MANAGE_DATA_NAME_NOT_FOUND: + // case MANAGE_DATA_LOW_RESERVE: + // case MANAGE_DATA_INVALID_NAME: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageDataResult", { + switchOn: xdr.lookup("ManageDataResultCode"), + switchName: "code", + switches: [["manageDataSuccess", xdr["void"]()], ["manageDataNotSupportedYet", xdr["void"]()], ["manageDataNameNotFound", xdr["void"]()], ["manageDataLowReserve", xdr["void"]()], ["manageDataInvalidName", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum BumpSequenceResultCode + // { + // // codes considered as "success" for the operation + // BUMP_SEQUENCE_SUCCESS = 0, + // // codes considered as "failure" for the operation + // BUMP_SEQUENCE_BAD_SEQ = -1 // `bumpTo` is not within bounds + // }; + // + // =========================================================================== + xdr["enum"]("BumpSequenceResultCode", { + bumpSequenceSuccess: 0, + bumpSequenceBadSeq: -1 + }); + + // === xdr source ============================================================ + // + // union BumpSequenceResult switch (BumpSequenceResultCode code) + // { + // case BUMP_SEQUENCE_SUCCESS: + // void; + // case BUMP_SEQUENCE_BAD_SEQ: + // void; + // }; + // + // =========================================================================== + xdr.union("BumpSequenceResult", { + switchOn: xdr.lookup("BumpSequenceResultCode"), + switchName: "code", + switches: [["bumpSequenceSuccess", xdr["void"]()], ["bumpSequenceBadSeq", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum CreateClaimableBalanceResultCode + // { + // CREATE_CLAIMABLE_BALANCE_SUCCESS = 0, + // CREATE_CLAIMABLE_BALANCE_MALFORMED = -1, + // CREATE_CLAIMABLE_BALANCE_LOW_RESERVE = -2, + // CREATE_CLAIMABLE_BALANCE_NO_TRUST = -3, + // CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -4, + // CREATE_CLAIMABLE_BALANCE_UNDERFUNDED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("CreateClaimableBalanceResultCode", { + createClaimableBalanceSuccess: 0, + createClaimableBalanceMalformed: -1, + createClaimableBalanceLowReserve: -2, + createClaimableBalanceNoTrust: -3, + createClaimableBalanceNotAuthorized: -4, + createClaimableBalanceUnderfunded: -5 + }); + + // === xdr source ============================================================ + // + // union CreateClaimableBalanceResult switch ( + // CreateClaimableBalanceResultCode code) + // { + // case CREATE_CLAIMABLE_BALANCE_SUCCESS: + // ClaimableBalanceID balanceID; + // case CREATE_CLAIMABLE_BALANCE_MALFORMED: + // case CREATE_CLAIMABLE_BALANCE_LOW_RESERVE: + // case CREATE_CLAIMABLE_BALANCE_NO_TRUST: + // case CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED: + // case CREATE_CLAIMABLE_BALANCE_UNDERFUNDED: + // void; + // }; + // + // =========================================================================== + xdr.union("CreateClaimableBalanceResult", { + switchOn: xdr.lookup("CreateClaimableBalanceResultCode"), + switchName: "code", + switches: [["createClaimableBalanceSuccess", "balanceId"], ["createClaimableBalanceMalformed", xdr["void"]()], ["createClaimableBalanceLowReserve", xdr["void"]()], ["createClaimableBalanceNoTrust", xdr["void"]()], ["createClaimableBalanceNotAuthorized", xdr["void"]()], ["createClaimableBalanceUnderfunded", xdr["void"]()]], + arms: { + balanceId: xdr.lookup("ClaimableBalanceId") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimClaimableBalanceResultCode + // { + // CLAIM_CLAIMABLE_BALANCE_SUCCESS = 0, + // CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1, + // CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM = -2, + // CLAIM_CLAIMABLE_BALANCE_LINE_FULL = -3, + // CLAIM_CLAIMABLE_BALANCE_NO_TRUST = -4, + // CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimClaimableBalanceResultCode", { + claimClaimableBalanceSuccess: 0, + claimClaimableBalanceDoesNotExist: -1, + claimClaimableBalanceCannotClaim: -2, + claimClaimableBalanceLineFull: -3, + claimClaimableBalanceNoTrust: -4, + claimClaimableBalanceNotAuthorized: -5 + }); + + // === xdr source ============================================================ + // + // union ClaimClaimableBalanceResult switch (ClaimClaimableBalanceResultCode code) + // { + // case CLAIM_CLAIMABLE_BALANCE_SUCCESS: + // void; + // case CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST: + // case CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM: + // case CLAIM_CLAIMABLE_BALANCE_LINE_FULL: + // case CLAIM_CLAIMABLE_BALANCE_NO_TRUST: + // case CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClaimClaimableBalanceResult", { + switchOn: xdr.lookup("ClaimClaimableBalanceResultCode"), + switchName: "code", + switches: [["claimClaimableBalanceSuccess", xdr["void"]()], ["claimClaimableBalanceDoesNotExist", xdr["void"]()], ["claimClaimableBalanceCannotClaim", xdr["void"]()], ["claimClaimableBalanceLineFull", xdr["void"]()], ["claimClaimableBalanceNoTrust", xdr["void"]()], ["claimClaimableBalanceNotAuthorized", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum BeginSponsoringFutureReservesResultCode + // { + // // codes considered as "success" for the operation + // BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED = -1, + // BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED = -2, + // BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("BeginSponsoringFutureReservesResultCode", { + beginSponsoringFutureReservesSuccess: 0, + beginSponsoringFutureReservesMalformed: -1, + beginSponsoringFutureReservesAlreadySponsored: -2, + beginSponsoringFutureReservesRecursive: -3 + }); + + // === xdr source ============================================================ + // + // union BeginSponsoringFutureReservesResult switch ( + // BeginSponsoringFutureReservesResultCode code) + // { + // case BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS: + // void; + // case BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED: + // case BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED: + // case BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE: + // void; + // }; + // + // =========================================================================== + xdr.union("BeginSponsoringFutureReservesResult", { + switchOn: xdr.lookup("BeginSponsoringFutureReservesResultCode"), + switchName: "code", + switches: [["beginSponsoringFutureReservesSuccess", xdr["void"]()], ["beginSponsoringFutureReservesMalformed", xdr["void"]()], ["beginSponsoringFutureReservesAlreadySponsored", xdr["void"]()], ["beginSponsoringFutureReservesRecursive", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum EndSponsoringFutureReservesResultCode + // { + // // codes considered as "success" for the operation + // END_SPONSORING_FUTURE_RESERVES_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED = -1 + // }; + // + // =========================================================================== + xdr["enum"]("EndSponsoringFutureReservesResultCode", { + endSponsoringFutureReservesSuccess: 0, + endSponsoringFutureReservesNotSponsored: -1 + }); + + // === xdr source ============================================================ + // + // union EndSponsoringFutureReservesResult switch ( + // EndSponsoringFutureReservesResultCode code) + // { + // case END_SPONSORING_FUTURE_RESERVES_SUCCESS: + // void; + // case END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED: + // void; + // }; + // + // =========================================================================== + xdr.union("EndSponsoringFutureReservesResult", { + switchOn: xdr.lookup("EndSponsoringFutureReservesResultCode"), + switchName: "code", + switches: [["endSponsoringFutureReservesSuccess", xdr["void"]()], ["endSponsoringFutureReservesNotSponsored", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum RevokeSponsorshipResultCode + // { + // // codes considered as "success" for the operation + // REVOKE_SPONSORSHIP_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // REVOKE_SPONSORSHIP_DOES_NOT_EXIST = -1, + // REVOKE_SPONSORSHIP_NOT_SPONSOR = -2, + // REVOKE_SPONSORSHIP_LOW_RESERVE = -3, + // REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE = -4, + // REVOKE_SPONSORSHIP_MALFORMED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("RevokeSponsorshipResultCode", { + revokeSponsorshipSuccess: 0, + revokeSponsorshipDoesNotExist: -1, + revokeSponsorshipNotSponsor: -2, + revokeSponsorshipLowReserve: -3, + revokeSponsorshipOnlyTransferable: -4, + revokeSponsorshipMalformed: -5 + }); + + // === xdr source ============================================================ + // + // union RevokeSponsorshipResult switch (RevokeSponsorshipResultCode code) + // { + // case REVOKE_SPONSORSHIP_SUCCESS: + // void; + // case REVOKE_SPONSORSHIP_DOES_NOT_EXIST: + // case REVOKE_SPONSORSHIP_NOT_SPONSOR: + // case REVOKE_SPONSORSHIP_LOW_RESERVE: + // case REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE: + // case REVOKE_SPONSORSHIP_MALFORMED: + // void; + // }; + // + // =========================================================================== + xdr.union("RevokeSponsorshipResult", { + switchOn: xdr.lookup("RevokeSponsorshipResultCode"), + switchName: "code", + switches: [["revokeSponsorshipSuccess", xdr["void"]()], ["revokeSponsorshipDoesNotExist", xdr["void"]()], ["revokeSponsorshipNotSponsor", xdr["void"]()], ["revokeSponsorshipLowReserve", xdr["void"]()], ["revokeSponsorshipOnlyTransferable", xdr["void"]()], ["revokeSponsorshipMalformed", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ClawbackResultCode + // { + // // codes considered as "success" for the operation + // CLAWBACK_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // CLAWBACK_MALFORMED = -1, + // CLAWBACK_NOT_CLAWBACK_ENABLED = -2, + // CLAWBACK_NO_TRUST = -3, + // CLAWBACK_UNDERFUNDED = -4 + // }; + // + // =========================================================================== + xdr["enum"]("ClawbackResultCode", { + clawbackSuccess: 0, + clawbackMalformed: -1, + clawbackNotClawbackEnabled: -2, + clawbackNoTrust: -3, + clawbackUnderfunded: -4 + }); + + // === xdr source ============================================================ + // + // union ClawbackResult switch (ClawbackResultCode code) + // { + // case CLAWBACK_SUCCESS: + // void; + // case CLAWBACK_MALFORMED: + // case CLAWBACK_NOT_CLAWBACK_ENABLED: + // case CLAWBACK_NO_TRUST: + // case CLAWBACK_UNDERFUNDED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClawbackResult", { + switchOn: xdr.lookup("ClawbackResultCode"), + switchName: "code", + switches: [["clawbackSuccess", xdr["void"]()], ["clawbackMalformed", xdr["void"]()], ["clawbackNotClawbackEnabled", xdr["void"]()], ["clawbackNoTrust", xdr["void"]()], ["clawbackUnderfunded", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ClawbackClaimableBalanceResultCode + // { + // // codes considered as "success" for the operation + // CLAWBACK_CLAIMABLE_BALANCE_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1, + // CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER = -2, + // CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED = -3 + // }; + // + // =========================================================================== + xdr["enum"]("ClawbackClaimableBalanceResultCode", { + clawbackClaimableBalanceSuccess: 0, + clawbackClaimableBalanceDoesNotExist: -1, + clawbackClaimableBalanceNotIssuer: -2, + clawbackClaimableBalanceNotClawbackEnabled: -3 + }); + + // === xdr source ============================================================ + // + // union ClawbackClaimableBalanceResult switch ( + // ClawbackClaimableBalanceResultCode code) + // { + // case CLAWBACK_CLAIMABLE_BALANCE_SUCCESS: + // void; + // case CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST: + // case CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER: + // case CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClawbackClaimableBalanceResult", { + switchOn: xdr.lookup("ClawbackClaimableBalanceResultCode"), + switchName: "code", + switches: [["clawbackClaimableBalanceSuccess", xdr["void"]()], ["clawbackClaimableBalanceDoesNotExist", xdr["void"]()], ["clawbackClaimableBalanceNotIssuer", xdr["void"]()], ["clawbackClaimableBalanceNotClawbackEnabled", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum SetTrustLineFlagsResultCode + // { + // // codes considered as "success" for the operation + // SET_TRUST_LINE_FLAGS_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // SET_TRUST_LINE_FLAGS_MALFORMED = -1, + // SET_TRUST_LINE_FLAGS_NO_TRUST_LINE = -2, + // SET_TRUST_LINE_FLAGS_CANT_REVOKE = -3, + // SET_TRUST_LINE_FLAGS_INVALID_STATE = -4, + // SET_TRUST_LINE_FLAGS_LOW_RESERVE = -5 // claimable balances can't be created + // // on revoke due to low reserves + // }; + // + // =========================================================================== + xdr["enum"]("SetTrustLineFlagsResultCode", { + setTrustLineFlagsSuccess: 0, + setTrustLineFlagsMalformed: -1, + setTrustLineFlagsNoTrustLine: -2, + setTrustLineFlagsCantRevoke: -3, + setTrustLineFlagsInvalidState: -4, + setTrustLineFlagsLowReserve: -5 + }); + + // === xdr source ============================================================ + // + // union SetTrustLineFlagsResult switch (SetTrustLineFlagsResultCode code) + // { + // case SET_TRUST_LINE_FLAGS_SUCCESS: + // void; + // case SET_TRUST_LINE_FLAGS_MALFORMED: + // case SET_TRUST_LINE_FLAGS_NO_TRUST_LINE: + // case SET_TRUST_LINE_FLAGS_CANT_REVOKE: + // case SET_TRUST_LINE_FLAGS_INVALID_STATE: + // case SET_TRUST_LINE_FLAGS_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("SetTrustLineFlagsResult", { + switchOn: xdr.lookup("SetTrustLineFlagsResultCode"), + switchName: "code", + switches: [["setTrustLineFlagsSuccess", xdr["void"]()], ["setTrustLineFlagsMalformed", xdr["void"]()], ["setTrustLineFlagsNoTrustLine", xdr["void"]()], ["setTrustLineFlagsCantRevoke", xdr["void"]()], ["setTrustLineFlagsInvalidState", xdr["void"]()], ["setTrustLineFlagsLowReserve", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum LiquidityPoolDepositResultCode + // { + // // codes considered as "success" for the operation + // LIQUIDITY_POOL_DEPOSIT_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // LIQUIDITY_POOL_DEPOSIT_MALFORMED = -1, // bad input + // LIQUIDITY_POOL_DEPOSIT_NO_TRUST = -2, // no trust line for one of the + // // assets + // LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED = -3, // not authorized for one of the + // // assets + // LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED = -4, // not enough balance for one of + // // the assets + // LIQUIDITY_POOL_DEPOSIT_LINE_FULL = -5, // pool share trust line doesn't + // // have sufficient limit + // LIQUIDITY_POOL_DEPOSIT_BAD_PRICE = -6, // deposit price outside bounds + // LIQUIDITY_POOL_DEPOSIT_POOL_FULL = -7 // pool reserves are full + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolDepositResultCode", { + liquidityPoolDepositSuccess: 0, + liquidityPoolDepositMalformed: -1, + liquidityPoolDepositNoTrust: -2, + liquidityPoolDepositNotAuthorized: -3, + liquidityPoolDepositUnderfunded: -4, + liquidityPoolDepositLineFull: -5, + liquidityPoolDepositBadPrice: -6, + liquidityPoolDepositPoolFull: -7 + }); + + // === xdr source ============================================================ + // + // union LiquidityPoolDepositResult switch (LiquidityPoolDepositResultCode code) + // { + // case LIQUIDITY_POOL_DEPOSIT_SUCCESS: + // void; + // case LIQUIDITY_POOL_DEPOSIT_MALFORMED: + // case LIQUIDITY_POOL_DEPOSIT_NO_TRUST: + // case LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED: + // case LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED: + // case LIQUIDITY_POOL_DEPOSIT_LINE_FULL: + // case LIQUIDITY_POOL_DEPOSIT_BAD_PRICE: + // case LIQUIDITY_POOL_DEPOSIT_POOL_FULL: + // void; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolDepositResult", { + switchOn: xdr.lookup("LiquidityPoolDepositResultCode"), + switchName: "code", + switches: [["liquidityPoolDepositSuccess", xdr["void"]()], ["liquidityPoolDepositMalformed", xdr["void"]()], ["liquidityPoolDepositNoTrust", xdr["void"]()], ["liquidityPoolDepositNotAuthorized", xdr["void"]()], ["liquidityPoolDepositUnderfunded", xdr["void"]()], ["liquidityPoolDepositLineFull", xdr["void"]()], ["liquidityPoolDepositBadPrice", xdr["void"]()], ["liquidityPoolDepositPoolFull", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum LiquidityPoolWithdrawResultCode + // { + // // codes considered as "success" for the operation + // LIQUIDITY_POOL_WITHDRAW_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // LIQUIDITY_POOL_WITHDRAW_MALFORMED = -1, // bad input + // LIQUIDITY_POOL_WITHDRAW_NO_TRUST = -2, // no trust line for one of the + // // assets + // LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED = -3, // not enough balance of the + // // pool share + // LIQUIDITY_POOL_WITHDRAW_LINE_FULL = -4, // would go above limit for one + // // of the assets + // LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM = -5 // didn't withdraw enough + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolWithdrawResultCode", { + liquidityPoolWithdrawSuccess: 0, + liquidityPoolWithdrawMalformed: -1, + liquidityPoolWithdrawNoTrust: -2, + liquidityPoolWithdrawUnderfunded: -3, + liquidityPoolWithdrawLineFull: -4, + liquidityPoolWithdrawUnderMinimum: -5 + }); + + // === xdr source ============================================================ + // + // union LiquidityPoolWithdrawResult switch (LiquidityPoolWithdrawResultCode code) + // { + // case LIQUIDITY_POOL_WITHDRAW_SUCCESS: + // void; + // case LIQUIDITY_POOL_WITHDRAW_MALFORMED: + // case LIQUIDITY_POOL_WITHDRAW_NO_TRUST: + // case LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED: + // case LIQUIDITY_POOL_WITHDRAW_LINE_FULL: + // case LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM: + // void; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolWithdrawResult", { + switchOn: xdr.lookup("LiquidityPoolWithdrawResultCode"), + switchName: "code", + switches: [["liquidityPoolWithdrawSuccess", xdr["void"]()], ["liquidityPoolWithdrawMalformed", xdr["void"]()], ["liquidityPoolWithdrawNoTrust", xdr["void"]()], ["liquidityPoolWithdrawUnderfunded", xdr["void"]()], ["liquidityPoolWithdrawLineFull", xdr["void"]()], ["liquidityPoolWithdrawUnderMinimum", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum InvokeHostFunctionResultCode + // { + // // codes considered as "success" for the operation + // INVOKE_HOST_FUNCTION_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // INVOKE_HOST_FUNCTION_MALFORMED = -1, + // INVOKE_HOST_FUNCTION_TRAPPED = -2, + // INVOKE_HOST_FUNCTION_RESOURCE_LIMIT_EXCEEDED = -3, + // INVOKE_HOST_FUNCTION_ENTRY_ARCHIVED = -4, + // INVOKE_HOST_FUNCTION_INSUFFICIENT_REFUNDABLE_FEE = -5 + // }; + // + // =========================================================================== + xdr["enum"]("InvokeHostFunctionResultCode", { + invokeHostFunctionSuccess: 0, + invokeHostFunctionMalformed: -1, + invokeHostFunctionTrapped: -2, + invokeHostFunctionResourceLimitExceeded: -3, + invokeHostFunctionEntryArchived: -4, + invokeHostFunctionInsufficientRefundableFee: -5 + }); + + // === xdr source ============================================================ + // + // union InvokeHostFunctionResult switch (InvokeHostFunctionResultCode code) + // { + // case INVOKE_HOST_FUNCTION_SUCCESS: + // Hash success; // sha256(InvokeHostFunctionSuccessPreImage) + // case INVOKE_HOST_FUNCTION_MALFORMED: + // case INVOKE_HOST_FUNCTION_TRAPPED: + // case INVOKE_HOST_FUNCTION_RESOURCE_LIMIT_EXCEEDED: + // case INVOKE_HOST_FUNCTION_ENTRY_ARCHIVED: + // case INVOKE_HOST_FUNCTION_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("InvokeHostFunctionResult", { + switchOn: xdr.lookup("InvokeHostFunctionResultCode"), + switchName: "code", + switches: [["invokeHostFunctionSuccess", "success"], ["invokeHostFunctionMalformed", xdr["void"]()], ["invokeHostFunctionTrapped", xdr["void"]()], ["invokeHostFunctionResourceLimitExceeded", xdr["void"]()], ["invokeHostFunctionEntryArchived", xdr["void"]()], ["invokeHostFunctionInsufficientRefundableFee", xdr["void"]()]], + arms: { + success: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum ExtendFootprintTTLResultCode + // { + // // codes considered as "success" for the operation + // EXTEND_FOOTPRINT_TTL_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // EXTEND_FOOTPRINT_TTL_MALFORMED = -1, + // EXTEND_FOOTPRINT_TTL_RESOURCE_LIMIT_EXCEEDED = -2, + // EXTEND_FOOTPRINT_TTL_INSUFFICIENT_REFUNDABLE_FEE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("ExtendFootprintTtlResultCode", { + extendFootprintTtlSuccess: 0, + extendFootprintTtlMalformed: -1, + extendFootprintTtlResourceLimitExceeded: -2, + extendFootprintTtlInsufficientRefundableFee: -3 + }); + + // === xdr source ============================================================ + // + // union ExtendFootprintTTLResult switch (ExtendFootprintTTLResultCode code) + // { + // case EXTEND_FOOTPRINT_TTL_SUCCESS: + // void; + // case EXTEND_FOOTPRINT_TTL_MALFORMED: + // case EXTEND_FOOTPRINT_TTL_RESOURCE_LIMIT_EXCEEDED: + // case EXTEND_FOOTPRINT_TTL_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("ExtendFootprintTtlResult", { + switchOn: xdr.lookup("ExtendFootprintTtlResultCode"), + switchName: "code", + switches: [["extendFootprintTtlSuccess", xdr["void"]()], ["extendFootprintTtlMalformed", xdr["void"]()], ["extendFootprintTtlResourceLimitExceeded", xdr["void"]()], ["extendFootprintTtlInsufficientRefundableFee", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum RestoreFootprintResultCode + // { + // // codes considered as "success" for the operation + // RESTORE_FOOTPRINT_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // RESTORE_FOOTPRINT_MALFORMED = -1, + // RESTORE_FOOTPRINT_RESOURCE_LIMIT_EXCEEDED = -2, + // RESTORE_FOOTPRINT_INSUFFICIENT_REFUNDABLE_FEE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("RestoreFootprintResultCode", { + restoreFootprintSuccess: 0, + restoreFootprintMalformed: -1, + restoreFootprintResourceLimitExceeded: -2, + restoreFootprintInsufficientRefundableFee: -3 + }); + + // === xdr source ============================================================ + // + // union RestoreFootprintResult switch (RestoreFootprintResultCode code) + // { + // case RESTORE_FOOTPRINT_SUCCESS: + // void; + // case RESTORE_FOOTPRINT_MALFORMED: + // case RESTORE_FOOTPRINT_RESOURCE_LIMIT_EXCEEDED: + // case RESTORE_FOOTPRINT_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("RestoreFootprintResult", { + switchOn: xdr.lookup("RestoreFootprintResultCode"), + switchName: "code", + switches: [["restoreFootprintSuccess", xdr["void"]()], ["restoreFootprintMalformed", xdr["void"]()], ["restoreFootprintResourceLimitExceeded", xdr["void"]()], ["restoreFootprintInsufficientRefundableFee", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum OperationResultCode + // { + // opINNER = 0, // inner object result is valid + // + // opBAD_AUTH = -1, // too few valid signatures / wrong network + // opNO_ACCOUNT = -2, // source account was not found + // opNOT_SUPPORTED = -3, // operation not supported at this time + // opTOO_MANY_SUBENTRIES = -4, // max number of subentries already reached + // opEXCEEDED_WORK_LIMIT = -5, // operation did too much work + // opTOO_MANY_SPONSORING = -6 // account is sponsoring too many entries + // }; + // + // =========================================================================== + xdr["enum"]("OperationResultCode", { + opInner: 0, + opBadAuth: -1, + opNoAccount: -2, + opNotSupported: -3, + opTooManySubentries: -4, + opExceededWorkLimit: -5, + opTooManySponsoring: -6 + }); + + // === xdr source ============================================================ + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountResult createAccountResult; + // case PAYMENT: + // PaymentResult paymentResult; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult; + // case MANAGE_SELL_OFFER: + // ManageSellOfferResult manageSellOfferResult; + // case CREATE_PASSIVE_SELL_OFFER: + // ManageSellOfferResult createPassiveSellOfferResult; + // case SET_OPTIONS: + // SetOptionsResult setOptionsResult; + // case CHANGE_TRUST: + // ChangeTrustResult changeTrustResult; + // case ALLOW_TRUST: + // AllowTrustResult allowTrustResult; + // case ACCOUNT_MERGE: + // AccountMergeResult accountMergeResult; + // case INFLATION: + // InflationResult inflationResult; + // case MANAGE_DATA: + // ManageDataResult manageDataResult; + // case BUMP_SEQUENCE: + // BumpSequenceResult bumpSeqResult; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferResult manageBuyOfferResult; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendResult pathPaymentStrictSendResult; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceResult createClaimableBalanceResult; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceResult claimClaimableBalanceResult; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult; + // case END_SPONSORING_FUTURE_RESERVES: + // EndSponsoringFutureReservesResult endSponsoringFutureReservesResult; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipResult revokeSponsorshipResult; + // case CLAWBACK: + // ClawbackResult clawbackResult; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceResult clawbackClaimableBalanceResult; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsResult setTrustLineFlagsResult; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositResult liquidityPoolDepositResult; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawResult liquidityPoolWithdrawResult; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionResult invokeHostFunctionResult; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLResult extendFootprintTTLResult; + // case RESTORE_FOOTPRINT: + // RestoreFootprintResult restoreFootprintResult; + // } + // + // =========================================================================== + xdr.union("OperationResultTr", { + switchOn: xdr.lookup("OperationType"), + switchName: "type", + switches: [["createAccount", "createAccountResult"], ["payment", "paymentResult"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveResult"], ["manageSellOffer", "manageSellOfferResult"], ["createPassiveSellOffer", "createPassiveSellOfferResult"], ["setOptions", "setOptionsResult"], ["changeTrust", "changeTrustResult"], ["allowTrust", "allowTrustResult"], ["accountMerge", "accountMergeResult"], ["inflation", "inflationResult"], ["manageData", "manageDataResult"], ["bumpSequence", "bumpSeqResult"], ["manageBuyOffer", "manageBuyOfferResult"], ["pathPaymentStrictSend", "pathPaymentStrictSendResult"], ["createClaimableBalance", "createClaimableBalanceResult"], ["claimClaimableBalance", "claimClaimableBalanceResult"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesResult"], ["endSponsoringFutureReserves", "endSponsoringFutureReservesResult"], ["revokeSponsorship", "revokeSponsorshipResult"], ["clawback", "clawbackResult"], ["clawbackClaimableBalance", "clawbackClaimableBalanceResult"], ["setTrustLineFlags", "setTrustLineFlagsResult"], ["liquidityPoolDeposit", "liquidityPoolDepositResult"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawResult"], ["invokeHostFunction", "invokeHostFunctionResult"], ["extendFootprintTtl", "extendFootprintTtlResult"], ["restoreFootprint", "restoreFootprintResult"]], + arms: { + createAccountResult: xdr.lookup("CreateAccountResult"), + paymentResult: xdr.lookup("PaymentResult"), + pathPaymentStrictReceiveResult: xdr.lookup("PathPaymentStrictReceiveResult"), + manageSellOfferResult: xdr.lookup("ManageSellOfferResult"), + createPassiveSellOfferResult: xdr.lookup("ManageSellOfferResult"), + setOptionsResult: xdr.lookup("SetOptionsResult"), + changeTrustResult: xdr.lookup("ChangeTrustResult"), + allowTrustResult: xdr.lookup("AllowTrustResult"), + accountMergeResult: xdr.lookup("AccountMergeResult"), + inflationResult: xdr.lookup("InflationResult"), + manageDataResult: xdr.lookup("ManageDataResult"), + bumpSeqResult: xdr.lookup("BumpSequenceResult"), + manageBuyOfferResult: xdr.lookup("ManageBuyOfferResult"), + pathPaymentStrictSendResult: xdr.lookup("PathPaymentStrictSendResult"), + createClaimableBalanceResult: xdr.lookup("CreateClaimableBalanceResult"), + claimClaimableBalanceResult: xdr.lookup("ClaimClaimableBalanceResult"), + beginSponsoringFutureReservesResult: xdr.lookup("BeginSponsoringFutureReservesResult"), + endSponsoringFutureReservesResult: xdr.lookup("EndSponsoringFutureReservesResult"), + revokeSponsorshipResult: xdr.lookup("RevokeSponsorshipResult"), + clawbackResult: xdr.lookup("ClawbackResult"), + clawbackClaimableBalanceResult: xdr.lookup("ClawbackClaimableBalanceResult"), + setTrustLineFlagsResult: xdr.lookup("SetTrustLineFlagsResult"), + liquidityPoolDepositResult: xdr.lookup("LiquidityPoolDepositResult"), + liquidityPoolWithdrawResult: xdr.lookup("LiquidityPoolWithdrawResult"), + invokeHostFunctionResult: xdr.lookup("InvokeHostFunctionResult"), + extendFootprintTtlResult: xdr.lookup("ExtendFootprintTtlResult"), + restoreFootprintResult: xdr.lookup("RestoreFootprintResult") + } + }); + + // === xdr source ============================================================ + // + // union OperationResult switch (OperationResultCode code) + // { + // case opINNER: + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountResult createAccountResult; + // case PAYMENT: + // PaymentResult paymentResult; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult; + // case MANAGE_SELL_OFFER: + // ManageSellOfferResult manageSellOfferResult; + // case CREATE_PASSIVE_SELL_OFFER: + // ManageSellOfferResult createPassiveSellOfferResult; + // case SET_OPTIONS: + // SetOptionsResult setOptionsResult; + // case CHANGE_TRUST: + // ChangeTrustResult changeTrustResult; + // case ALLOW_TRUST: + // AllowTrustResult allowTrustResult; + // case ACCOUNT_MERGE: + // AccountMergeResult accountMergeResult; + // case INFLATION: + // InflationResult inflationResult; + // case MANAGE_DATA: + // ManageDataResult manageDataResult; + // case BUMP_SEQUENCE: + // BumpSequenceResult bumpSeqResult; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferResult manageBuyOfferResult; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendResult pathPaymentStrictSendResult; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceResult createClaimableBalanceResult; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceResult claimClaimableBalanceResult; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult; + // case END_SPONSORING_FUTURE_RESERVES: + // EndSponsoringFutureReservesResult endSponsoringFutureReservesResult; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipResult revokeSponsorshipResult; + // case CLAWBACK: + // ClawbackResult clawbackResult; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceResult clawbackClaimableBalanceResult; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsResult setTrustLineFlagsResult; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositResult liquidityPoolDepositResult; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawResult liquidityPoolWithdrawResult; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionResult invokeHostFunctionResult; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLResult extendFootprintTTLResult; + // case RESTORE_FOOTPRINT: + // RestoreFootprintResult restoreFootprintResult; + // } + // tr; + // case opBAD_AUTH: + // case opNO_ACCOUNT: + // case opNOT_SUPPORTED: + // case opTOO_MANY_SUBENTRIES: + // case opEXCEEDED_WORK_LIMIT: + // case opTOO_MANY_SPONSORING: + // void; + // }; + // + // =========================================================================== + xdr.union("OperationResult", { + switchOn: xdr.lookup("OperationResultCode"), + switchName: "code", + switches: [["opInner", "tr"], ["opBadAuth", xdr["void"]()], ["opNoAccount", xdr["void"]()], ["opNotSupported", xdr["void"]()], ["opTooManySubentries", xdr["void"]()], ["opExceededWorkLimit", xdr["void"]()], ["opTooManySponsoring", xdr["void"]()]], + arms: { + tr: xdr.lookup("OperationResultTr") + } + }); + + // === xdr source ============================================================ + // + // enum TransactionResultCode + // { + // txFEE_BUMP_INNER_SUCCESS = 1, // fee bump inner transaction succeeded + // txSUCCESS = 0, // all operations succeeded + // + // txFAILED = -1, // one of the operations failed (none were applied) + // + // txTOO_EARLY = -2, // ledger closeTime before minTime + // txTOO_LATE = -3, // ledger closeTime after maxTime + // txMISSING_OPERATION = -4, // no operation was specified + // txBAD_SEQ = -5, // sequence number does not match source account + // + // txBAD_AUTH = -6, // too few valid signatures / wrong network + // txINSUFFICIENT_BALANCE = -7, // fee would bring account below reserve + // txNO_ACCOUNT = -8, // source account not found + // txINSUFFICIENT_FEE = -9, // fee is too small + // txBAD_AUTH_EXTRA = -10, // unused signatures attached to transaction + // txINTERNAL_ERROR = -11, // an unknown error occurred + // + // txNOT_SUPPORTED = -12, // transaction type not supported + // txFEE_BUMP_INNER_FAILED = -13, // fee bump inner transaction failed + // txBAD_SPONSORSHIP = -14, // sponsorship not confirmed + // txBAD_MIN_SEQ_AGE_OR_GAP = -15, // minSeqAge or minSeqLedgerGap conditions not met + // txMALFORMED = -16, // precondition is invalid + // txSOROBAN_INVALID = -17 // soroban-specific preconditions were not met + // }; + // + // =========================================================================== + xdr["enum"]("TransactionResultCode", { + txFeeBumpInnerSuccess: 1, + txSuccess: 0, + txFailed: -1, + txTooEarly: -2, + txTooLate: -3, + txMissingOperation: -4, + txBadSeq: -5, + txBadAuth: -6, + txInsufficientBalance: -7, + txNoAccount: -8, + txInsufficientFee: -9, + txBadAuthExtra: -10, + txInternalError: -11, + txNotSupported: -12, + txFeeBumpInnerFailed: -13, + txBadSponsorship: -14, + txBadMinSeqAgeOrGap: -15, + txMalformed: -16, + txSorobanInvalid: -17 + }); + + // === xdr source ============================================================ + // + // union switch (TransactionResultCode code) + // { + // // txFEE_BUMP_INNER_SUCCESS is not included + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // txFEE_BUMP_INNER_FAILED is not included + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // + // =========================================================================== + xdr.union("InnerTransactionResultResult", { + switchOn: xdr.lookup("TransactionResultCode"), + switchName: "code", + switches: [["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr["void"]()], ["txTooLate", xdr["void"]()], ["txMissingOperation", xdr["void"]()], ["txBadSeq", xdr["void"]()], ["txBadAuth", xdr["void"]()], ["txInsufficientBalance", xdr["void"]()], ["txNoAccount", xdr["void"]()], ["txInsufficientFee", xdr["void"]()], ["txBadAuthExtra", xdr["void"]()], ["txInternalError", xdr["void"]()], ["txNotSupported", xdr["void"]()], ["txBadSponsorship", xdr["void"]()], ["txBadMinSeqAgeOrGap", xdr["void"]()], ["txMalformed", xdr["void"]()], ["txSorobanInvalid", xdr["void"]()]], + arms: { + results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("InnerTransactionResultExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct InnerTransactionResult + // { + // // Always 0. Here for binary compatibility. + // int64 feeCharged; + // + // union switch (TransactionResultCode code) + // { + // // txFEE_BUMP_INNER_SUCCESS is not included + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // txFEE_BUMP_INNER_FAILED is not included + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // result; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("InnerTransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("InnerTransactionResultResult")], ["ext", xdr.lookup("InnerTransactionResultExt")]]); + + // === xdr source ============================================================ + // + // struct InnerTransactionResultPair + // { + // Hash transactionHash; // hash of the inner transaction + // InnerTransactionResult result; // result for the inner transaction + // }; + // + // =========================================================================== + xdr.struct("InnerTransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("InnerTransactionResult")]]); + + // === xdr source ============================================================ + // + // union switch (TransactionResultCode code) + // { + // case txFEE_BUMP_INNER_SUCCESS: + // case txFEE_BUMP_INNER_FAILED: + // InnerTransactionResultPair innerResultPair; + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // case txFEE_BUMP_INNER_FAILED: handled above + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionResultResult", { + switchOn: xdr.lookup("TransactionResultCode"), + switchName: "code", + switches: [["txFeeBumpInnerSuccess", "innerResultPair"], ["txFeeBumpInnerFailed", "innerResultPair"], ["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr["void"]()], ["txTooLate", xdr["void"]()], ["txMissingOperation", xdr["void"]()], ["txBadSeq", xdr["void"]()], ["txBadAuth", xdr["void"]()], ["txInsufficientBalance", xdr["void"]()], ["txNoAccount", xdr["void"]()], ["txInsufficientFee", xdr["void"]()], ["txBadAuthExtra", xdr["void"]()], ["txInternalError", xdr["void"]()], ["txNotSupported", xdr["void"]()], ["txBadSponsorship", xdr["void"]()], ["txBadMinSeqAgeOrGap", xdr["void"]()], ["txMalformed", xdr["void"]()], ["txSorobanInvalid", xdr["void"]()]], + arms: { + innerResultPair: xdr.lookup("InnerTransactionResultPair"), + results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionResultExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionResult + // { + // int64 feeCharged; // actual fee charged for the transaction + // + // union switch (TransactionResultCode code) + // { + // case txFEE_BUMP_INNER_SUCCESS: + // case txFEE_BUMP_INNER_FAILED: + // InnerTransactionResultPair innerResultPair; + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // case txFEE_BUMP_INNER_FAILED: handled above + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // result; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("TransactionResultResult")], ["ext", xdr.lookup("TransactionResultExt")]]); + + // === xdr source ============================================================ + // + // typedef opaque Hash[32]; + // + // =========================================================================== + xdr.typedef("Hash", xdr.opaque(32)); + + // === xdr source ============================================================ + // + // typedef opaque uint256[32]; + // + // =========================================================================== + xdr.typedef("Uint256", xdr.opaque(32)); + + // === xdr source ============================================================ + // + // typedef unsigned int uint32; + // + // =========================================================================== + xdr.typedef("Uint32", xdr.uint()); + + // === xdr source ============================================================ + // + // typedef int int32; + // + // =========================================================================== + xdr.typedef("Int32", xdr["int"]()); + + // === xdr source ============================================================ + // + // typedef unsigned hyper uint64; + // + // =========================================================================== + xdr.typedef("Uint64", xdr.uhyper()); + + // === xdr source ============================================================ + // + // typedef hyper int64; + // + // =========================================================================== + xdr.typedef("Int64", xdr.hyper()); + + // === xdr source ============================================================ + // + // typedef uint64 TimePoint; + // + // =========================================================================== + xdr.typedef("TimePoint", xdr.lookup("Uint64")); + + // === xdr source ============================================================ + // + // typedef uint64 Duration; + // + // =========================================================================== + xdr.typedef("Duration", xdr.lookup("Uint64")); + + // === xdr source ============================================================ + // + // union ExtensionPoint switch (int v) + // { + // case 0: + // void; + // }; + // + // =========================================================================== + xdr.union("ExtensionPoint", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum CryptoKeyType + // { + // KEY_TYPE_ED25519 = 0, + // KEY_TYPE_PRE_AUTH_TX = 1, + // KEY_TYPE_HASH_X = 2, + // KEY_TYPE_ED25519_SIGNED_PAYLOAD = 3, + // // MUXED enum values for supported type are derived from the enum values + // // above by ORing them with 0x100 + // KEY_TYPE_MUXED_ED25519 = 0x100 + // }; + // + // =========================================================================== + xdr["enum"]("CryptoKeyType", { + keyTypeEd25519: 0, + keyTypePreAuthTx: 1, + keyTypeHashX: 2, + keyTypeEd25519SignedPayload: 3, + keyTypeMuxedEd25519: 256 + }); + + // === xdr source ============================================================ + // + // enum PublicKeyType + // { + // PUBLIC_KEY_TYPE_ED25519 = KEY_TYPE_ED25519 + // }; + // + // =========================================================================== + xdr["enum"]("PublicKeyType", { + publicKeyTypeEd25519: 0 + }); + + // === xdr source ============================================================ + // + // enum SignerKeyType + // { + // SIGNER_KEY_TYPE_ED25519 = KEY_TYPE_ED25519, + // SIGNER_KEY_TYPE_PRE_AUTH_TX = KEY_TYPE_PRE_AUTH_TX, + // SIGNER_KEY_TYPE_HASH_X = KEY_TYPE_HASH_X, + // SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD = KEY_TYPE_ED25519_SIGNED_PAYLOAD + // }; + // + // =========================================================================== + xdr["enum"]("SignerKeyType", { + signerKeyTypeEd25519: 0, + signerKeyTypePreAuthTx: 1, + signerKeyTypeHashX: 2, + signerKeyTypeEd25519SignedPayload: 3 + }); + + // === xdr source ============================================================ + // + // union PublicKey switch (PublicKeyType type) + // { + // case PUBLIC_KEY_TYPE_ED25519: + // uint256 ed25519; + // }; + // + // =========================================================================== + xdr.union("PublicKey", { + switchOn: xdr.lookup("PublicKeyType"), + switchName: "type", + switches: [["publicKeyTypeEd25519", "ed25519"]], + arms: { + ed25519: xdr.lookup("Uint256") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // /* Public key that must sign the payload. */ + // uint256 ed25519; + // /* Payload to be raw signed by ed25519. */ + // opaque payload<64>; + // } + // + // =========================================================================== + xdr.struct("SignerKeyEd25519SignedPayload", [["ed25519", xdr.lookup("Uint256")], ["payload", xdr.varOpaque(64)]]); + + // === xdr source ============================================================ + // + // union SignerKey switch (SignerKeyType type) + // { + // case SIGNER_KEY_TYPE_ED25519: + // uint256 ed25519; + // case SIGNER_KEY_TYPE_PRE_AUTH_TX: + // /* SHA-256 Hash of TransactionSignaturePayload structure */ + // uint256 preAuthTx; + // case SIGNER_KEY_TYPE_HASH_X: + // /* Hash of random 256 bit preimage X */ + // uint256 hashX; + // case SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD: + // struct + // { + // /* Public key that must sign the payload. */ + // uint256 ed25519; + // /* Payload to be raw signed by ed25519. */ + // opaque payload<64>; + // } ed25519SignedPayload; + // }; + // + // =========================================================================== + xdr.union("SignerKey", { + switchOn: xdr.lookup("SignerKeyType"), + switchName: "type", + switches: [["signerKeyTypeEd25519", "ed25519"], ["signerKeyTypePreAuthTx", "preAuthTx"], ["signerKeyTypeHashX", "hashX"], ["signerKeyTypeEd25519SignedPayload", "ed25519SignedPayload"]], + arms: { + ed25519: xdr.lookup("Uint256"), + preAuthTx: xdr.lookup("Uint256"), + hashX: xdr.lookup("Uint256"), + ed25519SignedPayload: xdr.lookup("SignerKeyEd25519SignedPayload") + } + }); + + // === xdr source ============================================================ + // + // typedef opaque Signature<64>; + // + // =========================================================================== + xdr.typedef("Signature", xdr.varOpaque(64)); + + // === xdr source ============================================================ + // + // typedef opaque SignatureHint[4]; + // + // =========================================================================== + xdr.typedef("SignatureHint", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef PublicKey NodeID; + // + // =========================================================================== + xdr.typedef("NodeId", xdr.lookup("PublicKey")); + + // === xdr source ============================================================ + // + // typedef PublicKey AccountID; + // + // =========================================================================== + xdr.typedef("AccountId", xdr.lookup("PublicKey")); + + // === xdr source ============================================================ + // + // struct Curve25519Secret + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("Curve25519Secret", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct Curve25519Public + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("Curve25519Public", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct HmacSha256Key + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("HmacSha256Key", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct HmacSha256Mac + // { + // opaque mac[32]; + // }; + // + // =========================================================================== + xdr.struct("HmacSha256Mac", [["mac", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct ShortHashSeed + // { + // opaque seed[16]; + // }; + // + // =========================================================================== + xdr.struct("ShortHashSeed", [["seed", xdr.opaque(16)]]); + + // === xdr source ============================================================ + // + // enum BinaryFuseFilterType + // { + // BINARY_FUSE_FILTER_8_BIT = 0, + // BINARY_FUSE_FILTER_16_BIT = 1, + // BINARY_FUSE_FILTER_32_BIT = 2 + // }; + // + // =========================================================================== + xdr["enum"]("BinaryFuseFilterType", { + binaryFuseFilter8Bit: 0, + binaryFuseFilter16Bit: 1, + binaryFuseFilter32Bit: 2 + }); + + // === xdr source ============================================================ + // + // struct SerializedBinaryFuseFilter + // { + // BinaryFuseFilterType type; + // + // // Seed used to hash input to filter + // ShortHashSeed inputHashSeed; + // + // // Seed used for internal filter hash operations + // ShortHashSeed filterSeed; + // uint32 segmentLength; + // uint32 segementLengthMask; + // uint32 segmentCount; + // uint32 segmentCountLength; + // uint32 fingerprintLength; // Length in terms of element count, not bytes + // + // // Array of uint8_t, uint16_t, or uint32_t depending on filter type + // opaque fingerprints<>; + // }; + // + // =========================================================================== + xdr.struct("SerializedBinaryFuseFilter", [["type", xdr.lookup("BinaryFuseFilterType")], ["inputHashSeed", xdr.lookup("ShortHashSeed")], ["filterSeed", xdr.lookup("ShortHashSeed")], ["segmentLength", xdr.lookup("Uint32")], ["segementLengthMask", xdr.lookup("Uint32")], ["segmentCount", xdr.lookup("Uint32")], ["segmentCountLength", xdr.lookup("Uint32")], ["fingerprintLength", xdr.lookup("Uint32")], ["fingerprints", xdr.varOpaque()]]); + + // === xdr source ============================================================ + // + // enum SCValType + // { + // SCV_BOOL = 0, + // SCV_VOID = 1, + // SCV_ERROR = 2, + // + // // 32 bits is the smallest type in WASM or XDR; no need for u8/u16. + // SCV_U32 = 3, + // SCV_I32 = 4, + // + // // 64 bits is naturally supported by both WASM and XDR also. + // SCV_U64 = 5, + // SCV_I64 = 6, + // + // // Time-related u64 subtypes with their own functions and formatting. + // SCV_TIMEPOINT = 7, + // SCV_DURATION = 8, + // + // // 128 bits is naturally supported by Rust and we use it for Soroban + // // fixed-point arithmetic prices / balances / similar "quantities". These + // // are represented in XDR as a pair of 2 u64s. + // SCV_U128 = 9, + // SCV_I128 = 10, + // + // // 256 bits is the size of sha256 output, ed25519 keys, and the EVM machine + // // word, so for interop use we include this even though it requires a small + // // amount of Rust guest and/or host library code. + // SCV_U256 = 11, + // SCV_I256 = 12, + // + // // Bytes come in 3 flavors, 2 of which have meaningfully different + // // formatting and validity-checking / domain-restriction. + // SCV_BYTES = 13, + // SCV_STRING = 14, + // SCV_SYMBOL = 15, + // + // // Vecs and maps are just polymorphic containers of other ScVals. + // SCV_VEC = 16, + // SCV_MAP = 17, + // + // // Address is the universal identifier for contracts and classic + // // accounts. + // SCV_ADDRESS = 18, + // + // // The following are the internal SCVal variants that are not + // // exposed to the contracts. + // SCV_CONTRACT_INSTANCE = 19, + // + // // SCV_LEDGER_KEY_CONTRACT_INSTANCE and SCV_LEDGER_KEY_NONCE are unique + // // symbolic SCVals used as the key for ledger entries for a contract's + // // instance and an address' nonce, respectively. + // SCV_LEDGER_KEY_CONTRACT_INSTANCE = 20, + // SCV_LEDGER_KEY_NONCE = 21 + // }; + // + // =========================================================================== + xdr["enum"]("ScValType", { + scvBool: 0, + scvVoid: 1, + scvError: 2, + scvU32: 3, + scvI32: 4, + scvU64: 5, + scvI64: 6, + scvTimepoint: 7, + scvDuration: 8, + scvU128: 9, + scvI128: 10, + scvU256: 11, + scvI256: 12, + scvBytes: 13, + scvString: 14, + scvSymbol: 15, + scvVec: 16, + scvMap: 17, + scvAddress: 18, + scvContractInstance: 19, + scvLedgerKeyContractInstance: 20, + scvLedgerKeyNonce: 21 + }); + + // === xdr source ============================================================ + // + // enum SCErrorType + // { + // SCE_CONTRACT = 0, // Contract-specific, user-defined codes. + // SCE_WASM_VM = 1, // Errors while interpreting WASM bytecode. + // SCE_CONTEXT = 2, // Errors in the contract's host context. + // SCE_STORAGE = 3, // Errors accessing host storage. + // SCE_OBJECT = 4, // Errors working with host objects. + // SCE_CRYPTO = 5, // Errors in cryptographic operations. + // SCE_EVENTS = 6, // Errors while emitting events. + // SCE_BUDGET = 7, // Errors relating to budget limits. + // SCE_VALUE = 8, // Errors working with host values or SCVals. + // SCE_AUTH = 9 // Errors from the authentication subsystem. + // }; + // + // =========================================================================== + xdr["enum"]("ScErrorType", { + sceContract: 0, + sceWasmVm: 1, + sceContext: 2, + sceStorage: 3, + sceObject: 4, + sceCrypto: 5, + sceEvents: 6, + sceBudget: 7, + sceValue: 8, + sceAuth: 9 + }); + + // === xdr source ============================================================ + // + // enum SCErrorCode + // { + // SCEC_ARITH_DOMAIN = 0, // Some arithmetic was undefined (overflow, divide-by-zero). + // SCEC_INDEX_BOUNDS = 1, // Something was indexed beyond its bounds. + // SCEC_INVALID_INPUT = 2, // User provided some otherwise-bad data. + // SCEC_MISSING_VALUE = 3, // Some value was required but not provided. + // SCEC_EXISTING_VALUE = 4, // Some value was provided where not allowed. + // SCEC_EXCEEDED_LIMIT = 5, // Some arbitrary limit -- gas or otherwise -- was hit. + // SCEC_INVALID_ACTION = 6, // Data was valid but action requested was not. + // SCEC_INTERNAL_ERROR = 7, // The host detected an error in its own logic. + // SCEC_UNEXPECTED_TYPE = 8, // Some type wasn't as expected. + // SCEC_UNEXPECTED_SIZE = 9 // Something's size wasn't as expected. + // }; + // + // =========================================================================== + xdr["enum"]("ScErrorCode", { + scecArithDomain: 0, + scecIndexBounds: 1, + scecInvalidInput: 2, + scecMissingValue: 3, + scecExistingValue: 4, + scecExceededLimit: 5, + scecInvalidAction: 6, + scecInternalError: 7, + scecUnexpectedType: 8, + scecUnexpectedSize: 9 + }); + + // === xdr source ============================================================ + // + // union SCError switch (SCErrorType type) + // { + // case SCE_CONTRACT: + // uint32 contractCode; + // case SCE_WASM_VM: + // case SCE_CONTEXT: + // case SCE_STORAGE: + // case SCE_OBJECT: + // case SCE_CRYPTO: + // case SCE_EVENTS: + // case SCE_BUDGET: + // case SCE_VALUE: + // case SCE_AUTH: + // SCErrorCode code; + // }; + // + // =========================================================================== + xdr.union("ScError", { + switchOn: xdr.lookup("ScErrorType"), + switchName: "type", + switches: [["sceContract", "contractCode"], ["sceWasmVm", "code"], ["sceContext", "code"], ["sceStorage", "code"], ["sceObject", "code"], ["sceCrypto", "code"], ["sceEvents", "code"], ["sceBudget", "code"], ["sceValue", "code"], ["sceAuth", "code"]], + arms: { + contractCode: xdr.lookup("Uint32"), + code: xdr.lookup("ScErrorCode") + } + }); + + // === xdr source ============================================================ + // + // struct UInt128Parts { + // uint64 hi; + // uint64 lo; + // }; + // + // =========================================================================== + xdr.struct("UInt128Parts", [["hi", xdr.lookup("Uint64")], ["lo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct Int128Parts { + // int64 hi; + // uint64 lo; + // }; + // + // =========================================================================== + xdr.struct("Int128Parts", [["hi", xdr.lookup("Int64")], ["lo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct UInt256Parts { + // uint64 hi_hi; + // uint64 hi_lo; + // uint64 lo_hi; + // uint64 lo_lo; + // }; + // + // =========================================================================== + xdr.struct("UInt256Parts", [["hiHi", xdr.lookup("Uint64")], ["hiLo", xdr.lookup("Uint64")], ["loHi", xdr.lookup("Uint64")], ["loLo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct Int256Parts { + // int64 hi_hi; + // uint64 hi_lo; + // uint64 lo_hi; + // uint64 lo_lo; + // }; + // + // =========================================================================== + xdr.struct("Int256Parts", [["hiHi", xdr.lookup("Int64")], ["hiLo", xdr.lookup("Uint64")], ["loHi", xdr.lookup("Uint64")], ["loLo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // enum ContractExecutableType + // { + // CONTRACT_EXECUTABLE_WASM = 0, + // CONTRACT_EXECUTABLE_STELLAR_ASSET = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractExecutableType", { + contractExecutableWasm: 0, + contractExecutableStellarAsset: 1 + }); + + // === xdr source ============================================================ + // + // union ContractExecutable switch (ContractExecutableType type) + // { + // case CONTRACT_EXECUTABLE_WASM: + // Hash wasm_hash; + // case CONTRACT_EXECUTABLE_STELLAR_ASSET: + // void; + // }; + // + // =========================================================================== + xdr.union("ContractExecutable", { + switchOn: xdr.lookup("ContractExecutableType"), + switchName: "type", + switches: [["contractExecutableWasm", "wasmHash"], ["contractExecutableStellarAsset", xdr["void"]()]], + arms: { + wasmHash: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum SCAddressType + // { + // SC_ADDRESS_TYPE_ACCOUNT = 0, + // SC_ADDRESS_TYPE_CONTRACT = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ScAddressType", { + scAddressTypeAccount: 0, + scAddressTypeContract: 1 + }); + + // === xdr source ============================================================ + // + // union SCAddress switch (SCAddressType type) + // { + // case SC_ADDRESS_TYPE_ACCOUNT: + // AccountID accountId; + // case SC_ADDRESS_TYPE_CONTRACT: + // Hash contractId; + // }; + // + // =========================================================================== + xdr.union("ScAddress", { + switchOn: xdr.lookup("ScAddressType"), + switchName: "type", + switches: [["scAddressTypeAccount", "accountId"], ["scAddressTypeContract", "contractId"]], + arms: { + accountId: xdr.lookup("AccountId"), + contractId: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // const SCSYMBOL_LIMIT = 32; + // + // =========================================================================== + xdr["const"]("SCSYMBOL_LIMIT", 32); + + // === xdr source ============================================================ + // + // typedef SCVal SCVec<>; + // + // =========================================================================== + xdr.typedef("ScVec", xdr.varArray(xdr.lookup("ScVal"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef SCMapEntry SCMap<>; + // + // =========================================================================== + xdr.typedef("ScMap", xdr.varArray(xdr.lookup("ScMapEntry"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef opaque SCBytes<>; + // + // =========================================================================== + xdr.typedef("ScBytes", xdr.varOpaque()); + + // === xdr source ============================================================ + // + // typedef string SCString<>; + // + // =========================================================================== + xdr.typedef("ScString", xdr.string()); + + // === xdr source ============================================================ + // + // typedef string SCSymbol; + // + // =========================================================================== + xdr.typedef("ScSymbol", xdr.string(SCSYMBOL_LIMIT)); + + // === xdr source ============================================================ + // + // struct SCNonceKey { + // int64 nonce; + // }; + // + // =========================================================================== + xdr.struct("ScNonceKey", [["nonce", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct SCContractInstance { + // ContractExecutable executable; + // SCMap* storage; + // }; + // + // =========================================================================== + xdr.struct("ScContractInstance", [["executable", xdr.lookup("ContractExecutable")], ["storage", xdr.option(xdr.lookup("ScMap"))]]); + + // === xdr source ============================================================ + // + // union SCVal switch (SCValType type) + // { + // + // case SCV_BOOL: + // bool b; + // case SCV_VOID: + // void; + // case SCV_ERROR: + // SCError error; + // + // case SCV_U32: + // uint32 u32; + // case SCV_I32: + // int32 i32; + // + // case SCV_U64: + // uint64 u64; + // case SCV_I64: + // int64 i64; + // case SCV_TIMEPOINT: + // TimePoint timepoint; + // case SCV_DURATION: + // Duration duration; + // + // case SCV_U128: + // UInt128Parts u128; + // case SCV_I128: + // Int128Parts i128; + // + // case SCV_U256: + // UInt256Parts u256; + // case SCV_I256: + // Int256Parts i256; + // + // case SCV_BYTES: + // SCBytes bytes; + // case SCV_STRING: + // SCString str; + // case SCV_SYMBOL: + // SCSymbol sym; + // + // // Vec and Map are recursive so need to live + // // behind an option, due to xdrpp limitations. + // case SCV_VEC: + // SCVec *vec; + // case SCV_MAP: + // SCMap *map; + // + // case SCV_ADDRESS: + // SCAddress address; + // + // // Special SCVals reserved for system-constructed contract-data + // // ledger keys, not generally usable elsewhere. + // case SCV_LEDGER_KEY_CONTRACT_INSTANCE: + // void; + // case SCV_LEDGER_KEY_NONCE: + // SCNonceKey nonce_key; + // + // case SCV_CONTRACT_INSTANCE: + // SCContractInstance instance; + // }; + // + // =========================================================================== + xdr.union("ScVal", { + switchOn: xdr.lookup("ScValType"), + switchName: "type", + switches: [["scvBool", "b"], ["scvVoid", xdr["void"]()], ["scvError", "error"], ["scvU32", "u32"], ["scvI32", "i32"], ["scvU64", "u64"], ["scvI64", "i64"], ["scvTimepoint", "timepoint"], ["scvDuration", "duration"], ["scvU128", "u128"], ["scvI128", "i128"], ["scvU256", "u256"], ["scvI256", "i256"], ["scvBytes", "bytes"], ["scvString", "str"], ["scvSymbol", "sym"], ["scvVec", "vec"], ["scvMap", "map"], ["scvAddress", "address"], ["scvLedgerKeyContractInstance", xdr["void"]()], ["scvLedgerKeyNonce", "nonceKey"], ["scvContractInstance", "instance"]], + arms: { + b: xdr.bool(), + error: xdr.lookup("ScError"), + u32: xdr.lookup("Uint32"), + i32: xdr.lookup("Int32"), + u64: xdr.lookup("Uint64"), + i64: xdr.lookup("Int64"), + timepoint: xdr.lookup("TimePoint"), + duration: xdr.lookup("Duration"), + u128: xdr.lookup("UInt128Parts"), + i128: xdr.lookup("Int128Parts"), + u256: xdr.lookup("UInt256Parts"), + i256: xdr.lookup("Int256Parts"), + bytes: xdr.lookup("ScBytes"), + str: xdr.lookup("ScString"), + sym: xdr.lookup("ScSymbol"), + vec: xdr.option(xdr.lookup("ScVec")), + map: xdr.option(xdr.lookup("ScMap")), + address: xdr.lookup("ScAddress"), + nonceKey: xdr.lookup("ScNonceKey"), + instance: xdr.lookup("ScContractInstance") + } + }); + + // === xdr source ============================================================ + // + // struct SCMapEntry + // { + // SCVal key; + // SCVal val; + // }; + // + // =========================================================================== + xdr.struct("ScMapEntry", [["key", xdr.lookup("ScVal")], ["val", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // enum SCEnvMetaKind + // { + // SC_ENV_META_KIND_INTERFACE_VERSION = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ScEnvMetaKind", { + scEnvMetaKindInterfaceVersion: 0 + }); + + // === xdr source ============================================================ + // + // struct { + // uint32 protocol; + // uint32 preRelease; + // } + // + // =========================================================================== + xdr.struct("ScEnvMetaEntryInterfaceVersion", [["protocol", xdr.lookup("Uint32")], ["preRelease", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union SCEnvMetaEntry switch (SCEnvMetaKind kind) + // { + // case SC_ENV_META_KIND_INTERFACE_VERSION: + // struct { + // uint32 protocol; + // uint32 preRelease; + // } interfaceVersion; + // }; + // + // =========================================================================== + xdr.union("ScEnvMetaEntry", { + switchOn: xdr.lookup("ScEnvMetaKind"), + switchName: "kind", + switches: [["scEnvMetaKindInterfaceVersion", "interfaceVersion"]], + arms: { + interfaceVersion: xdr.lookup("ScEnvMetaEntryInterfaceVersion") + } + }); + + // === xdr source ============================================================ + // + // struct SCMetaV0 + // { + // string key<>; + // string val<>; + // }; + // + // =========================================================================== + xdr.struct("ScMetaV0", [["key", xdr.string()], ["val", xdr.string()]]); + + // === xdr source ============================================================ + // + // enum SCMetaKind + // { + // SC_META_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ScMetaKind", { + scMetaV0: 0 + }); + + // === xdr source ============================================================ + // + // union SCMetaEntry switch (SCMetaKind kind) + // { + // case SC_META_V0: + // SCMetaV0 v0; + // }; + // + // =========================================================================== + xdr.union("ScMetaEntry", { + switchOn: xdr.lookup("ScMetaKind"), + switchName: "kind", + switches: [["scMetaV0", "v0"]], + arms: { + v0: xdr.lookup("ScMetaV0") + } + }); + + // === xdr source ============================================================ + // + // const SC_SPEC_DOC_LIMIT = 1024; + // + // =========================================================================== + xdr["const"]("SC_SPEC_DOC_LIMIT", 1024); + + // === xdr source ============================================================ + // + // enum SCSpecType + // { + // SC_SPEC_TYPE_VAL = 0, + // + // // Types with no parameters. + // SC_SPEC_TYPE_BOOL = 1, + // SC_SPEC_TYPE_VOID = 2, + // SC_SPEC_TYPE_ERROR = 3, + // SC_SPEC_TYPE_U32 = 4, + // SC_SPEC_TYPE_I32 = 5, + // SC_SPEC_TYPE_U64 = 6, + // SC_SPEC_TYPE_I64 = 7, + // SC_SPEC_TYPE_TIMEPOINT = 8, + // SC_SPEC_TYPE_DURATION = 9, + // SC_SPEC_TYPE_U128 = 10, + // SC_SPEC_TYPE_I128 = 11, + // SC_SPEC_TYPE_U256 = 12, + // SC_SPEC_TYPE_I256 = 13, + // SC_SPEC_TYPE_BYTES = 14, + // SC_SPEC_TYPE_STRING = 16, + // SC_SPEC_TYPE_SYMBOL = 17, + // SC_SPEC_TYPE_ADDRESS = 19, + // + // // Types with parameters. + // SC_SPEC_TYPE_OPTION = 1000, + // SC_SPEC_TYPE_RESULT = 1001, + // SC_SPEC_TYPE_VEC = 1002, + // SC_SPEC_TYPE_MAP = 1004, + // SC_SPEC_TYPE_TUPLE = 1005, + // SC_SPEC_TYPE_BYTES_N = 1006, + // + // // User defined types. + // SC_SPEC_TYPE_UDT = 2000 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecType", { + scSpecTypeVal: 0, + scSpecTypeBool: 1, + scSpecTypeVoid: 2, + scSpecTypeError: 3, + scSpecTypeU32: 4, + scSpecTypeI32: 5, + scSpecTypeU64: 6, + scSpecTypeI64: 7, + scSpecTypeTimepoint: 8, + scSpecTypeDuration: 9, + scSpecTypeU128: 10, + scSpecTypeI128: 11, + scSpecTypeU256: 12, + scSpecTypeI256: 13, + scSpecTypeBytes: 14, + scSpecTypeString: 16, + scSpecTypeSymbol: 17, + scSpecTypeAddress: 19, + scSpecTypeOption: 1000, + scSpecTypeResult: 1001, + scSpecTypeVec: 1002, + scSpecTypeMap: 1004, + scSpecTypeTuple: 1005, + scSpecTypeBytesN: 1006, + scSpecTypeUdt: 2000 + }); + + // === xdr source ============================================================ + // + // struct SCSpecTypeOption + // { + // SCSpecTypeDef valueType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeOption", [["valueType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeResult + // { + // SCSpecTypeDef okType; + // SCSpecTypeDef errorType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeResult", [["okType", xdr.lookup("ScSpecTypeDef")], ["errorType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeVec + // { + // SCSpecTypeDef elementType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeVec", [["elementType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeMap + // { + // SCSpecTypeDef keyType; + // SCSpecTypeDef valueType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeMap", [["keyType", xdr.lookup("ScSpecTypeDef")], ["valueType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeTuple + // { + // SCSpecTypeDef valueTypes<12>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeTuple", [["valueTypes", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 12)]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeBytesN + // { + // uint32 n; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeBytesN", [["n", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeUDT + // { + // string name<60>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeUdt", [["name", xdr.string(60)]]); + + // === xdr source ============================================================ + // + // union SCSpecTypeDef switch (SCSpecType type) + // { + // case SC_SPEC_TYPE_VAL: + // case SC_SPEC_TYPE_BOOL: + // case SC_SPEC_TYPE_VOID: + // case SC_SPEC_TYPE_ERROR: + // case SC_SPEC_TYPE_U32: + // case SC_SPEC_TYPE_I32: + // case SC_SPEC_TYPE_U64: + // case SC_SPEC_TYPE_I64: + // case SC_SPEC_TYPE_TIMEPOINT: + // case SC_SPEC_TYPE_DURATION: + // case SC_SPEC_TYPE_U128: + // case SC_SPEC_TYPE_I128: + // case SC_SPEC_TYPE_U256: + // case SC_SPEC_TYPE_I256: + // case SC_SPEC_TYPE_BYTES: + // case SC_SPEC_TYPE_STRING: + // case SC_SPEC_TYPE_SYMBOL: + // case SC_SPEC_TYPE_ADDRESS: + // void; + // case SC_SPEC_TYPE_OPTION: + // SCSpecTypeOption option; + // case SC_SPEC_TYPE_RESULT: + // SCSpecTypeResult result; + // case SC_SPEC_TYPE_VEC: + // SCSpecTypeVec vec; + // case SC_SPEC_TYPE_MAP: + // SCSpecTypeMap map; + // case SC_SPEC_TYPE_TUPLE: + // SCSpecTypeTuple tuple; + // case SC_SPEC_TYPE_BYTES_N: + // SCSpecTypeBytesN bytesN; + // case SC_SPEC_TYPE_UDT: + // SCSpecTypeUDT udt; + // }; + // + // =========================================================================== + xdr.union("ScSpecTypeDef", { + switchOn: xdr.lookup("ScSpecType"), + switchName: "type", + switches: [["scSpecTypeVal", xdr["void"]()], ["scSpecTypeBool", xdr["void"]()], ["scSpecTypeVoid", xdr["void"]()], ["scSpecTypeError", xdr["void"]()], ["scSpecTypeU32", xdr["void"]()], ["scSpecTypeI32", xdr["void"]()], ["scSpecTypeU64", xdr["void"]()], ["scSpecTypeI64", xdr["void"]()], ["scSpecTypeTimepoint", xdr["void"]()], ["scSpecTypeDuration", xdr["void"]()], ["scSpecTypeU128", xdr["void"]()], ["scSpecTypeI128", xdr["void"]()], ["scSpecTypeU256", xdr["void"]()], ["scSpecTypeI256", xdr["void"]()], ["scSpecTypeBytes", xdr["void"]()], ["scSpecTypeString", xdr["void"]()], ["scSpecTypeSymbol", xdr["void"]()], ["scSpecTypeAddress", xdr["void"]()], ["scSpecTypeOption", "option"], ["scSpecTypeResult", "result"], ["scSpecTypeVec", "vec"], ["scSpecTypeMap", "map"], ["scSpecTypeTuple", "tuple"], ["scSpecTypeBytesN", "bytesN"], ["scSpecTypeUdt", "udt"]], + arms: { + option: xdr.lookup("ScSpecTypeOption"), + result: xdr.lookup("ScSpecTypeResult"), + vec: xdr.lookup("ScSpecTypeVec"), + map: xdr.lookup("ScSpecTypeMap"), + tuple: xdr.lookup("ScSpecTypeTuple"), + bytesN: xdr.lookup("ScSpecTypeBytesN"), + udt: xdr.lookup("ScSpecTypeUdt") + } + }); + + // === xdr source ============================================================ + // + // struct SCSpecUDTStructFieldV0 + // { + // string doc; + // string name<30>; + // SCSpecTypeDef type; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtStructFieldV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(30)], ["type", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTStructV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTStructFieldV0 fields<40>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtStructV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["fields", xdr.varArray(xdr.lookup("ScSpecUdtStructFieldV0"), 40)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionCaseVoidV0 + // { + // string doc; + // string name<60>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionCaseVoidV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionCaseTupleV0 + // { + // string doc; + // string name<60>; + // SCSpecTypeDef type<12>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionCaseTupleV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["type", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 12)]]); + + // === xdr source ============================================================ + // + // enum SCSpecUDTUnionCaseV0Kind + // { + // SC_SPEC_UDT_UNION_CASE_VOID_V0 = 0, + // SC_SPEC_UDT_UNION_CASE_TUPLE_V0 = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecUdtUnionCaseV0Kind", { + scSpecUdtUnionCaseVoidV0: 0, + scSpecUdtUnionCaseTupleV0: 1 + }); + + // === xdr source ============================================================ + // + // union SCSpecUDTUnionCaseV0 switch (SCSpecUDTUnionCaseV0Kind kind) + // { + // case SC_SPEC_UDT_UNION_CASE_VOID_V0: + // SCSpecUDTUnionCaseVoidV0 voidCase; + // case SC_SPEC_UDT_UNION_CASE_TUPLE_V0: + // SCSpecUDTUnionCaseTupleV0 tupleCase; + // }; + // + // =========================================================================== + xdr.union("ScSpecUdtUnionCaseV0", { + switchOn: xdr.lookup("ScSpecUdtUnionCaseV0Kind"), + switchName: "kind", + switches: [["scSpecUdtUnionCaseVoidV0", "voidCase"], ["scSpecUdtUnionCaseTupleV0", "tupleCase"]], + arms: { + voidCase: xdr.lookup("ScSpecUdtUnionCaseVoidV0"), + tupleCase: xdr.lookup("ScSpecUdtUnionCaseTupleV0") + } + }); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTUnionCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtUnionCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTEnumCaseV0 + // { + // string doc; + // string name<60>; + // uint32 value; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtEnumCaseV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["value", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTEnumV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTEnumCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtEnumV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtEnumCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTErrorEnumCaseV0 + // { + // string doc; + // string name<60>; + // uint32 value; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtErrorEnumCaseV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["value", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTErrorEnumV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTErrorEnumCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtErrorEnumV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtErrorEnumCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecFunctionInputV0 + // { + // string doc; + // string name<30>; + // SCSpecTypeDef type; + // }; + // + // =========================================================================== + xdr.struct("ScSpecFunctionInputV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(30)], ["type", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecFunctionV0 + // { + // string doc; + // SCSymbol name; + // SCSpecFunctionInputV0 inputs<10>; + // SCSpecTypeDef outputs<1>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecFunctionV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.lookup("ScSymbol")], ["inputs", xdr.varArray(xdr.lookup("ScSpecFunctionInputV0"), 10)], ["outputs", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 1)]]); + + // === xdr source ============================================================ + // + // enum SCSpecEntryKind + // { + // SC_SPEC_ENTRY_FUNCTION_V0 = 0, + // SC_SPEC_ENTRY_UDT_STRUCT_V0 = 1, + // SC_SPEC_ENTRY_UDT_UNION_V0 = 2, + // SC_SPEC_ENTRY_UDT_ENUM_V0 = 3, + // SC_SPEC_ENTRY_UDT_ERROR_ENUM_V0 = 4 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecEntryKind", { + scSpecEntryFunctionV0: 0, + scSpecEntryUdtStructV0: 1, + scSpecEntryUdtUnionV0: 2, + scSpecEntryUdtEnumV0: 3, + scSpecEntryUdtErrorEnumV0: 4 + }); + + // === xdr source ============================================================ + // + // union SCSpecEntry switch (SCSpecEntryKind kind) + // { + // case SC_SPEC_ENTRY_FUNCTION_V0: + // SCSpecFunctionV0 functionV0; + // case SC_SPEC_ENTRY_UDT_STRUCT_V0: + // SCSpecUDTStructV0 udtStructV0; + // case SC_SPEC_ENTRY_UDT_UNION_V0: + // SCSpecUDTUnionV0 udtUnionV0; + // case SC_SPEC_ENTRY_UDT_ENUM_V0: + // SCSpecUDTEnumV0 udtEnumV0; + // case SC_SPEC_ENTRY_UDT_ERROR_ENUM_V0: + // SCSpecUDTErrorEnumV0 udtErrorEnumV0; + // }; + // + // =========================================================================== + xdr.union("ScSpecEntry", { + switchOn: xdr.lookup("ScSpecEntryKind"), + switchName: "kind", + switches: [["scSpecEntryFunctionV0", "functionV0"], ["scSpecEntryUdtStructV0", "udtStructV0"], ["scSpecEntryUdtUnionV0", "udtUnionV0"], ["scSpecEntryUdtEnumV0", "udtEnumV0"], ["scSpecEntryUdtErrorEnumV0", "udtErrorEnumV0"]], + arms: { + functionV0: xdr.lookup("ScSpecFunctionV0"), + udtStructV0: xdr.lookup("ScSpecUdtStructV0"), + udtUnionV0: xdr.lookup("ScSpecUdtUnionV0"), + udtEnumV0: xdr.lookup("ScSpecUdtEnumV0"), + udtErrorEnumV0: xdr.lookup("ScSpecUdtErrorEnumV0") + } + }); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractExecutionLanesV0 + // { + // // maximum number of Soroban transactions per ledger + // uint32 ledgerMaxTxCount; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractExecutionLanesV0", [["ledgerMaxTxCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractComputeV0 + // { + // // Maximum instructions per ledger + // int64 ledgerMaxInstructions; + // // Maximum instructions per transaction + // int64 txMaxInstructions; + // // Cost of 10000 instructions + // int64 feeRatePerInstructionsIncrement; + // + // // Memory limit per transaction. Unlike instructions, there is no fee + // // for memory, just the limit. + // uint32 txMemoryLimit; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractComputeV0", [["ledgerMaxInstructions", xdr.lookup("Int64")], ["txMaxInstructions", xdr.lookup("Int64")], ["feeRatePerInstructionsIncrement", xdr.lookup("Int64")], ["txMemoryLimit", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractLedgerCostV0 + // { + // // Maximum number of ledger entry read operations per ledger + // uint32 ledgerMaxReadLedgerEntries; + // // Maximum number of bytes that can be read per ledger + // uint32 ledgerMaxReadBytes; + // // Maximum number of ledger entry write operations per ledger + // uint32 ledgerMaxWriteLedgerEntries; + // // Maximum number of bytes that can be written per ledger + // uint32 ledgerMaxWriteBytes; + // + // // Maximum number of ledger entry read operations per transaction + // uint32 txMaxReadLedgerEntries; + // // Maximum number of bytes that can be read per transaction + // uint32 txMaxReadBytes; + // // Maximum number of ledger entry write operations per transaction + // uint32 txMaxWriteLedgerEntries; + // // Maximum number of bytes that can be written per transaction + // uint32 txMaxWriteBytes; + // + // int64 feeReadLedgerEntry; // Fee per ledger entry read + // int64 feeWriteLedgerEntry; // Fee per ledger entry write + // + // int64 feeRead1KB; // Fee for reading 1KB + // + // // The following parameters determine the write fee per 1KB. + // // Write fee grows linearly until bucket list reaches this size + // int64 bucketListTargetSizeBytes; + // // Fee per 1KB write when the bucket list is empty + // int64 writeFee1KBBucketListLow; + // // Fee per 1KB write when the bucket list has reached `bucketListTargetSizeBytes` + // int64 writeFee1KBBucketListHigh; + // // Write fee multiplier for any additional data past the first `bucketListTargetSizeBytes` + // uint32 bucketListWriteFeeGrowthFactor; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractLedgerCostV0", [["ledgerMaxReadLedgerEntries", xdr.lookup("Uint32")], ["ledgerMaxReadBytes", xdr.lookup("Uint32")], ["ledgerMaxWriteLedgerEntries", xdr.lookup("Uint32")], ["ledgerMaxWriteBytes", xdr.lookup("Uint32")], ["txMaxReadLedgerEntries", xdr.lookup("Uint32")], ["txMaxReadBytes", xdr.lookup("Uint32")], ["txMaxWriteLedgerEntries", xdr.lookup("Uint32")], ["txMaxWriteBytes", xdr.lookup("Uint32")], ["feeReadLedgerEntry", xdr.lookup("Int64")], ["feeWriteLedgerEntry", xdr.lookup("Int64")], ["feeRead1Kb", xdr.lookup("Int64")], ["bucketListTargetSizeBytes", xdr.lookup("Int64")], ["writeFee1KbBucketListLow", xdr.lookup("Int64")], ["writeFee1KbBucketListHigh", xdr.lookup("Int64")], ["bucketListWriteFeeGrowthFactor", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractHistoricalDataV0 + // { + // int64 feeHistorical1KB; // Fee for storing 1KB in archives + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractHistoricalDataV0", [["feeHistorical1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractEventsV0 + // { + // // Maximum size of events that a contract call can emit. + // uint32 txMaxContractEventsSizeBytes; + // // Fee for generating 1KB of contract events. + // int64 feeContractEvents1KB; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractEventsV0", [["txMaxContractEventsSizeBytes", xdr.lookup("Uint32")], ["feeContractEvents1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractBandwidthV0 + // { + // // Maximum sum of all transaction sizes in the ledger in bytes + // uint32 ledgerMaxTxsSizeBytes; + // // Maximum size in bytes for a transaction + // uint32 txMaxSizeBytes; + // + // // Fee for 1 KB of transaction size + // int64 feeTxSize1KB; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractBandwidthV0", [["ledgerMaxTxsSizeBytes", xdr.lookup("Uint32")], ["txMaxSizeBytes", xdr.lookup("Uint32")], ["feeTxSize1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum ContractCostType { + // // Cost of running 1 wasm instruction + // WasmInsnExec = 0, + // // Cost of allocating a slice of memory (in bytes) + // MemAlloc = 1, + // // Cost of copying a slice of bytes into a pre-allocated memory + // MemCpy = 2, + // // Cost of comparing two slices of memory + // MemCmp = 3, + // // Cost of a host function dispatch, not including the actual work done by + // // the function nor the cost of VM invocation machinary + // DispatchHostFunction = 4, + // // Cost of visiting a host object from the host object storage. Exists to + // // make sure some baseline cost coverage, i.e. repeatly visiting objects + // // by the guest will always incur some charges. + // VisitObject = 5, + // // Cost of serializing an xdr object to bytes + // ValSer = 6, + // // Cost of deserializing an xdr object from bytes + // ValDeser = 7, + // // Cost of computing the sha256 hash from bytes + // ComputeSha256Hash = 8, + // // Cost of computing the ed25519 pubkey from bytes + // ComputeEd25519PubKey = 9, + // // Cost of verifying ed25519 signature of a payload. + // VerifyEd25519Sig = 10, + // // Cost of instantiation a VM from wasm bytes code. + // VmInstantiation = 11, + // // Cost of instantiation a VM from a cached state. + // VmCachedInstantiation = 12, + // // Cost of invoking a function on the VM. If the function is a host function, + // // additional cost will be covered by `DispatchHostFunction`. + // InvokeVmFunction = 13, + // // Cost of computing a keccak256 hash from bytes. + // ComputeKeccak256Hash = 14, + // // Cost of decoding an ECDSA signature computed from a 256-bit prime modulus + // // curve (e.g. secp256k1 and secp256r1) + // DecodeEcdsaCurve256Sig = 15, + // // Cost of recovering an ECDSA secp256k1 key from a signature. + // RecoverEcdsaSecp256k1Key = 16, + // // Cost of int256 addition (`+`) and subtraction (`-`) operations + // Int256AddSub = 17, + // // Cost of int256 multiplication (`*`) operation + // Int256Mul = 18, + // // Cost of int256 division (`/`) operation + // Int256Div = 19, + // // Cost of int256 power (`exp`) operation + // Int256Pow = 20, + // // Cost of int256 shift (`shl`, `shr`) operation + // Int256Shift = 21, + // // Cost of drawing random bytes using a ChaCha20 PRNG + // ChaCha20DrawBytes = 22, + // + // // Cost of parsing wasm bytes that only encode instructions. + // ParseWasmInstructions = 23, + // // Cost of parsing a known number of wasm functions. + // ParseWasmFunctions = 24, + // // Cost of parsing a known number of wasm globals. + // ParseWasmGlobals = 25, + // // Cost of parsing a known number of wasm table entries. + // ParseWasmTableEntries = 26, + // // Cost of parsing a known number of wasm types. + // ParseWasmTypes = 27, + // // Cost of parsing a known number of wasm data segments. + // ParseWasmDataSegments = 28, + // // Cost of parsing a known number of wasm element segments. + // ParseWasmElemSegments = 29, + // // Cost of parsing a known number of wasm imports. + // ParseWasmImports = 30, + // // Cost of parsing a known number of wasm exports. + // ParseWasmExports = 31, + // // Cost of parsing a known number of data segment bytes. + // ParseWasmDataSegmentBytes = 32, + // + // // Cost of instantiating wasm bytes that only encode instructions. + // InstantiateWasmInstructions = 33, + // // Cost of instantiating a known number of wasm functions. + // InstantiateWasmFunctions = 34, + // // Cost of instantiating a known number of wasm globals. + // InstantiateWasmGlobals = 35, + // // Cost of instantiating a known number of wasm table entries. + // InstantiateWasmTableEntries = 36, + // // Cost of instantiating a known number of wasm types. + // InstantiateWasmTypes = 37, + // // Cost of instantiating a known number of wasm data segments. + // InstantiateWasmDataSegments = 38, + // // Cost of instantiating a known number of wasm element segments. + // InstantiateWasmElemSegments = 39, + // // Cost of instantiating a known number of wasm imports. + // InstantiateWasmImports = 40, + // // Cost of instantiating a known number of wasm exports. + // InstantiateWasmExports = 41, + // // Cost of instantiating a known number of data segment bytes. + // InstantiateWasmDataSegmentBytes = 42, + // + // // Cost of decoding a bytes array representing an uncompressed SEC-1 encoded + // // point on a 256-bit elliptic curve + // Sec1DecodePointUncompressed = 43, + // // Cost of verifying an ECDSA Secp256r1 signature + // VerifyEcdsaSecp256r1Sig = 44, + // + // // Cost of encoding a BLS12-381 Fp (base field element) + // Bls12381EncodeFp = 45, + // // Cost of decoding a BLS12-381 Fp (base field element) + // Bls12381DecodeFp = 46, + // // Cost of checking a G1 point lies on the curve + // Bls12381G1CheckPointOnCurve = 47, + // // Cost of checking a G1 point belongs to the correct subgroup + // Bls12381G1CheckPointInSubgroup = 48, + // // Cost of checking a G2 point lies on the curve + // Bls12381G2CheckPointOnCurve = 49, + // // Cost of checking a G2 point belongs to the correct subgroup + // Bls12381G2CheckPointInSubgroup = 50, + // // Cost of converting a BLS12-381 G1 point from projective to affine coordinates + // Bls12381G1ProjectiveToAffine = 51, + // // Cost of converting a BLS12-381 G2 point from projective to affine coordinates + // Bls12381G2ProjectiveToAffine = 52, + // // Cost of performing BLS12-381 G1 point addition + // Bls12381G1Add = 53, + // // Cost of performing BLS12-381 G1 scalar multiplication + // Bls12381G1Mul = 54, + // // Cost of performing BLS12-381 G1 multi-scalar multiplication (MSM) + // Bls12381G1Msm = 55, + // // Cost of mapping a BLS12-381 Fp field element to a G1 point + // Bls12381MapFpToG1 = 56, + // // Cost of hashing to a BLS12-381 G1 point + // Bls12381HashToG1 = 57, + // // Cost of performing BLS12-381 G2 point addition + // Bls12381G2Add = 58, + // // Cost of performing BLS12-381 G2 scalar multiplication + // Bls12381G2Mul = 59, + // // Cost of performing BLS12-381 G2 multi-scalar multiplication (MSM) + // Bls12381G2Msm = 60, + // // Cost of mapping a BLS12-381 Fp2 field element to a G2 point + // Bls12381MapFp2ToG2 = 61, + // // Cost of hashing to a BLS12-381 G2 point + // Bls12381HashToG2 = 62, + // // Cost of performing BLS12-381 pairing operation + // Bls12381Pairing = 63, + // // Cost of converting a BLS12-381 scalar element from U256 + // Bls12381FrFromU256 = 64, + // // Cost of converting a BLS12-381 scalar element to U256 + // Bls12381FrToU256 = 65, + // // Cost of performing BLS12-381 scalar element addition/subtraction + // Bls12381FrAddSub = 66, + // // Cost of performing BLS12-381 scalar element multiplication + // Bls12381FrMul = 67, + // // Cost of performing BLS12-381 scalar element exponentiation + // Bls12381FrPow = 68, + // // Cost of performing BLS12-381 scalar element inversion + // Bls12381FrInv = 69 + // }; + // + // =========================================================================== + xdr["enum"]("ContractCostType", { + wasmInsnExec: 0, + memAlloc: 1, + memCpy: 2, + memCmp: 3, + dispatchHostFunction: 4, + visitObject: 5, + valSer: 6, + valDeser: 7, + computeSha256Hash: 8, + computeEd25519PubKey: 9, + verifyEd25519Sig: 10, + vmInstantiation: 11, + vmCachedInstantiation: 12, + invokeVmFunction: 13, + computeKeccak256Hash: 14, + decodeEcdsaCurve256Sig: 15, + recoverEcdsaSecp256k1Key: 16, + int256AddSub: 17, + int256Mul: 18, + int256Div: 19, + int256Pow: 20, + int256Shift: 21, + chaCha20DrawBytes: 22, + parseWasmInstructions: 23, + parseWasmFunctions: 24, + parseWasmGlobals: 25, + parseWasmTableEntries: 26, + parseWasmTypes: 27, + parseWasmDataSegments: 28, + parseWasmElemSegments: 29, + parseWasmImports: 30, + parseWasmExports: 31, + parseWasmDataSegmentBytes: 32, + instantiateWasmInstructions: 33, + instantiateWasmFunctions: 34, + instantiateWasmGlobals: 35, + instantiateWasmTableEntries: 36, + instantiateWasmTypes: 37, + instantiateWasmDataSegments: 38, + instantiateWasmElemSegments: 39, + instantiateWasmImports: 40, + instantiateWasmExports: 41, + instantiateWasmDataSegmentBytes: 42, + sec1DecodePointUncompressed: 43, + verifyEcdsaSecp256r1Sig: 44, + bls12381EncodeFp: 45, + bls12381DecodeFp: 46, + bls12381G1CheckPointOnCurve: 47, + bls12381G1CheckPointInSubgroup: 48, + bls12381G2CheckPointOnCurve: 49, + bls12381G2CheckPointInSubgroup: 50, + bls12381G1ProjectiveToAffine: 51, + bls12381G2ProjectiveToAffine: 52, + bls12381G1Add: 53, + bls12381G1Mul: 54, + bls12381G1Msm: 55, + bls12381MapFpToG1: 56, + bls12381HashToG1: 57, + bls12381G2Add: 58, + bls12381G2Mul: 59, + bls12381G2Msm: 60, + bls12381MapFp2ToG2: 61, + bls12381HashToG2: 62, + bls12381Pairing: 63, + bls12381FrFromU256: 64, + bls12381FrToU256: 65, + bls12381FrAddSub: 66, + bls12381FrMul: 67, + bls12381FrPow: 68, + bls12381FrInv: 69 + }); + + // === xdr source ============================================================ + // + // struct ContractCostParamEntry { + // // use `ext` to add more terms (e.g. higher order polynomials) in the future + // ExtensionPoint ext; + // + // int64 constTerm; + // int64 linearTerm; + // }; + // + // =========================================================================== + xdr.struct("ContractCostParamEntry", [["ext", xdr.lookup("ExtensionPoint")], ["constTerm", xdr.lookup("Int64")], ["linearTerm", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct StateArchivalSettings { + // uint32 maxEntryTTL; + // uint32 minTemporaryTTL; + // uint32 minPersistentTTL; + // + // // rent_fee = wfee_rate_average / rent_rate_denominator_for_type + // int64 persistentRentRateDenominator; + // int64 tempRentRateDenominator; + // + // // max number of entries that emit archival meta in a single ledger + // uint32 maxEntriesToArchive; + // + // // Number of snapshots to use when calculating average BucketList size + // uint32 bucketListSizeWindowSampleSize; + // + // // How often to sample the BucketList size for the average, in ledgers + // uint32 bucketListWindowSamplePeriod; + // + // // Maximum number of bytes that we scan for eviction per ledger + // uint32 evictionScanSize; + // + // // Lowest BucketList level to be scanned to evict entries + // uint32 startingEvictionScanLevel; + // }; + // + // =========================================================================== + xdr.struct("StateArchivalSettings", [["maxEntryTtl", xdr.lookup("Uint32")], ["minTemporaryTtl", xdr.lookup("Uint32")], ["minPersistentTtl", xdr.lookup("Uint32")], ["persistentRentRateDenominator", xdr.lookup("Int64")], ["tempRentRateDenominator", xdr.lookup("Int64")], ["maxEntriesToArchive", xdr.lookup("Uint32")], ["bucketListSizeWindowSampleSize", xdr.lookup("Uint32")], ["bucketListWindowSamplePeriod", xdr.lookup("Uint32")], ["evictionScanSize", xdr.lookup("Uint32")], ["startingEvictionScanLevel", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct EvictionIterator { + // uint32 bucketListLevel; + // bool isCurrBucket; + // uint64 bucketFileOffset; + // }; + // + // =========================================================================== + xdr.struct("EvictionIterator", [["bucketListLevel", xdr.lookup("Uint32")], ["isCurrBucket", xdr.bool()], ["bucketFileOffset", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // const CONTRACT_COST_COUNT_LIMIT = 1024; + // + // =========================================================================== + xdr["const"]("CONTRACT_COST_COUNT_LIMIT", 1024); + + // === xdr source ============================================================ + // + // typedef ContractCostParamEntry ContractCostParams; + // + // =========================================================================== + xdr.typedef("ContractCostParams", xdr.varArray(xdr.lookup("ContractCostParamEntry"), xdr.lookup("CONTRACT_COST_COUNT_LIMIT"))); + + // === xdr source ============================================================ + // + // enum ConfigSettingID + // { + // CONFIG_SETTING_CONTRACT_MAX_SIZE_BYTES = 0, + // CONFIG_SETTING_CONTRACT_COMPUTE_V0 = 1, + // CONFIG_SETTING_CONTRACT_LEDGER_COST_V0 = 2, + // CONFIG_SETTING_CONTRACT_HISTORICAL_DATA_V0 = 3, + // CONFIG_SETTING_CONTRACT_EVENTS_V0 = 4, + // CONFIG_SETTING_CONTRACT_BANDWIDTH_V0 = 5, + // CONFIG_SETTING_CONTRACT_COST_PARAMS_CPU_INSTRUCTIONS = 6, + // CONFIG_SETTING_CONTRACT_COST_PARAMS_MEMORY_BYTES = 7, + // CONFIG_SETTING_CONTRACT_DATA_KEY_SIZE_BYTES = 8, + // CONFIG_SETTING_CONTRACT_DATA_ENTRY_SIZE_BYTES = 9, + // CONFIG_SETTING_STATE_ARCHIVAL = 10, + // CONFIG_SETTING_CONTRACT_EXECUTION_LANES = 11, + // CONFIG_SETTING_BUCKETLIST_SIZE_WINDOW = 12, + // CONFIG_SETTING_EVICTION_ITERATOR = 13 + // }; + // + // =========================================================================== + xdr["enum"]("ConfigSettingId", { + configSettingContractMaxSizeBytes: 0, + configSettingContractComputeV0: 1, + configSettingContractLedgerCostV0: 2, + configSettingContractHistoricalDataV0: 3, + configSettingContractEventsV0: 4, + configSettingContractBandwidthV0: 5, + configSettingContractCostParamsCpuInstructions: 6, + configSettingContractCostParamsMemoryBytes: 7, + configSettingContractDataKeySizeBytes: 8, + configSettingContractDataEntrySizeBytes: 9, + configSettingStateArchival: 10, + configSettingContractExecutionLanes: 11, + configSettingBucketlistSizeWindow: 12, + configSettingEvictionIterator: 13 + }); + + // === xdr source ============================================================ + // + // union ConfigSettingEntry switch (ConfigSettingID configSettingID) + // { + // case CONFIG_SETTING_CONTRACT_MAX_SIZE_BYTES: + // uint32 contractMaxSizeBytes; + // case CONFIG_SETTING_CONTRACT_COMPUTE_V0: + // ConfigSettingContractComputeV0 contractCompute; + // case CONFIG_SETTING_CONTRACT_LEDGER_COST_V0: + // ConfigSettingContractLedgerCostV0 contractLedgerCost; + // case CONFIG_SETTING_CONTRACT_HISTORICAL_DATA_V0: + // ConfigSettingContractHistoricalDataV0 contractHistoricalData; + // case CONFIG_SETTING_CONTRACT_EVENTS_V0: + // ConfigSettingContractEventsV0 contractEvents; + // case CONFIG_SETTING_CONTRACT_BANDWIDTH_V0: + // ConfigSettingContractBandwidthV0 contractBandwidth; + // case CONFIG_SETTING_CONTRACT_COST_PARAMS_CPU_INSTRUCTIONS: + // ContractCostParams contractCostParamsCpuInsns; + // case CONFIG_SETTING_CONTRACT_COST_PARAMS_MEMORY_BYTES: + // ContractCostParams contractCostParamsMemBytes; + // case CONFIG_SETTING_CONTRACT_DATA_KEY_SIZE_BYTES: + // uint32 contractDataKeySizeBytes; + // case CONFIG_SETTING_CONTRACT_DATA_ENTRY_SIZE_BYTES: + // uint32 contractDataEntrySizeBytes; + // case CONFIG_SETTING_STATE_ARCHIVAL: + // StateArchivalSettings stateArchivalSettings; + // case CONFIG_SETTING_CONTRACT_EXECUTION_LANES: + // ConfigSettingContractExecutionLanesV0 contractExecutionLanes; + // case CONFIG_SETTING_BUCKETLIST_SIZE_WINDOW: + // uint64 bucketListSizeWindow<>; + // case CONFIG_SETTING_EVICTION_ITERATOR: + // EvictionIterator evictionIterator; + // }; + // + // =========================================================================== + xdr.union("ConfigSettingEntry", { + switchOn: xdr.lookup("ConfigSettingId"), + switchName: "configSettingId", + switches: [["configSettingContractMaxSizeBytes", "contractMaxSizeBytes"], ["configSettingContractComputeV0", "contractCompute"], ["configSettingContractLedgerCostV0", "contractLedgerCost"], ["configSettingContractHistoricalDataV0", "contractHistoricalData"], ["configSettingContractEventsV0", "contractEvents"], ["configSettingContractBandwidthV0", "contractBandwidth"], ["configSettingContractCostParamsCpuInstructions", "contractCostParamsCpuInsns"], ["configSettingContractCostParamsMemoryBytes", "contractCostParamsMemBytes"], ["configSettingContractDataKeySizeBytes", "contractDataKeySizeBytes"], ["configSettingContractDataEntrySizeBytes", "contractDataEntrySizeBytes"], ["configSettingStateArchival", "stateArchivalSettings"], ["configSettingContractExecutionLanes", "contractExecutionLanes"], ["configSettingBucketlistSizeWindow", "bucketListSizeWindow"], ["configSettingEvictionIterator", "evictionIterator"]], + arms: { + contractMaxSizeBytes: xdr.lookup("Uint32"), + contractCompute: xdr.lookup("ConfigSettingContractComputeV0"), + contractLedgerCost: xdr.lookup("ConfigSettingContractLedgerCostV0"), + contractHistoricalData: xdr.lookup("ConfigSettingContractHistoricalDataV0"), + contractEvents: xdr.lookup("ConfigSettingContractEventsV0"), + contractBandwidth: xdr.lookup("ConfigSettingContractBandwidthV0"), + contractCostParamsCpuInsns: xdr.lookup("ContractCostParams"), + contractCostParamsMemBytes: xdr.lookup("ContractCostParams"), + contractDataKeySizeBytes: xdr.lookup("Uint32"), + contractDataEntrySizeBytes: xdr.lookup("Uint32"), + stateArchivalSettings: xdr.lookup("StateArchivalSettings"), + contractExecutionLanes: xdr.lookup("ConfigSettingContractExecutionLanesV0"), + bucketListSizeWindow: xdr.varArray(xdr.lookup("Uint64"), 2147483647), + evictionIterator: xdr.lookup("EvictionIterator") + } + }); +}); +var _default = exports["default"] = types; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/generated/next_generated.js b/node_modules/@stellar/stellar-base/lib/generated/next_generated.js new file mode 100644 index 000000000..868dc863b --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/generated/next_generated.js @@ -0,0 +1,9227 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var XDR = _interopRequireWildcard(require("@stellar/js-xdr")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +// Automatically generated by xdrgen on 2024-09-12T11:09:00-08:00 +// DO NOT EDIT or your changes may be overwritten + +/* jshint maxstatements:2147483647 */ +/* jshint esnext:true */ + +var types = XDR.config(function (xdr) { + // Workaround for https://github.com/stellar/xdrgen/issues/152 + // + // The "correct" way would be to replace bare instances of each constant with + // xdr.lookup("..."), but that's more error-prone. + var SCSYMBOL_LIMIT = 32; + var SC_SPEC_DOC_LIMIT = 1024; + + // === xdr source ============================================================ + // + // struct SCPBallot + // { + // uint32 counter; // n + // Value value; // x + // }; + // + // =========================================================================== + xdr.struct("ScpBallot", [["counter", xdr.lookup("Uint32")], ["value", xdr.lookup("Value")]]); + + // === xdr source ============================================================ + // + // enum SCPStatementType + // { + // SCP_ST_PREPARE = 0, + // SCP_ST_CONFIRM = 1, + // SCP_ST_EXTERNALIZE = 2, + // SCP_ST_NOMINATE = 3 + // }; + // + // =========================================================================== + xdr["enum"]("ScpStatementType", { + scpStPrepare: 0, + scpStConfirm: 1, + scpStExternalize: 2, + scpStNominate: 3 + }); + + // === xdr source ============================================================ + // + // struct SCPNomination + // { + // Hash quorumSetHash; // D + // Value votes<>; // X + // Value accepted<>; // Y + // }; + // + // =========================================================================== + xdr.struct("ScpNomination", [["quorumSetHash", xdr.lookup("Hash")], ["votes", xdr.varArray(xdr.lookup("Value"), 2147483647)], ["accepted", xdr.varArray(xdr.lookup("Value"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } + // + // =========================================================================== + xdr.struct("ScpStatementPrepare", [["quorumSetHash", xdr.lookup("Hash")], ["ballot", xdr.lookup("ScpBallot")], ["prepared", xdr.option(xdr.lookup("ScpBallot"))], ["preparedPrime", xdr.option(xdr.lookup("ScpBallot"))], ["nC", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } + // + // =========================================================================== + xdr.struct("ScpStatementConfirm", [["ballot", xdr.lookup("ScpBallot")], ["nPrepared", xdr.lookup("Uint32")], ["nCommit", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")], ["quorumSetHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } + // + // =========================================================================== + xdr.struct("ScpStatementExternalize", [["commit", xdr.lookup("ScpBallot")], ["nH", xdr.lookup("Uint32")], ["commitQuorumSetHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union switch (SCPStatementType type) + // { + // case SCP_ST_PREPARE: + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } prepare; + // case SCP_ST_CONFIRM: + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } confirm; + // case SCP_ST_EXTERNALIZE: + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } externalize; + // case SCP_ST_NOMINATE: + // SCPNomination nominate; + // } + // + // =========================================================================== + xdr.union("ScpStatementPledges", { + switchOn: xdr.lookup("ScpStatementType"), + switchName: "type", + switches: [["scpStPrepare", "prepare"], ["scpStConfirm", "confirm"], ["scpStExternalize", "externalize"], ["scpStNominate", "nominate"]], + arms: { + prepare: xdr.lookup("ScpStatementPrepare"), + confirm: xdr.lookup("ScpStatementConfirm"), + externalize: xdr.lookup("ScpStatementExternalize"), + nominate: xdr.lookup("ScpNomination") + } + }); + + // === xdr source ============================================================ + // + // struct SCPStatement + // { + // NodeID nodeID; // v + // uint64 slotIndex; // i + // + // union switch (SCPStatementType type) + // { + // case SCP_ST_PREPARE: + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } prepare; + // case SCP_ST_CONFIRM: + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } confirm; + // case SCP_ST_EXTERNALIZE: + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } externalize; + // case SCP_ST_NOMINATE: + // SCPNomination nominate; + // } + // pledges; + // }; + // + // =========================================================================== + xdr.struct("ScpStatement", [["nodeId", xdr.lookup("NodeId")], ["slotIndex", xdr.lookup("Uint64")], ["pledges", xdr.lookup("ScpStatementPledges")]]); + + // === xdr source ============================================================ + // + // struct SCPEnvelope + // { + // SCPStatement statement; + // Signature signature; + // }; + // + // =========================================================================== + xdr.struct("ScpEnvelope", [["statement", xdr.lookup("ScpStatement")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // struct SCPQuorumSet + // { + // uint32 threshold; + // NodeID validators<>; + // SCPQuorumSet innerSets<>; + // }; + // + // =========================================================================== + xdr.struct("ScpQuorumSet", [["threshold", xdr.lookup("Uint32")], ["validators", xdr.varArray(xdr.lookup("NodeId"), 2147483647)], ["innerSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)]]); + + // === xdr source ============================================================ + // + // typedef opaque Thresholds[4]; + // + // =========================================================================== + xdr.typedef("Thresholds", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef string string32<32>; + // + // =========================================================================== + xdr.typedef("String32", xdr.string(32)); + + // === xdr source ============================================================ + // + // typedef string string64<64>; + // + // =========================================================================== + xdr.typedef("String64", xdr.string(64)); + + // === xdr source ============================================================ + // + // typedef int64 SequenceNumber; + // + // =========================================================================== + xdr.typedef("SequenceNumber", xdr.lookup("Int64")); + + // === xdr source ============================================================ + // + // typedef opaque DataValue<64>; + // + // =========================================================================== + xdr.typedef("DataValue", xdr.varOpaque(64)); + + // === xdr source ============================================================ + // + // typedef Hash PoolID; + // + // =========================================================================== + xdr.typedef("PoolId", xdr.lookup("Hash")); + + // === xdr source ============================================================ + // + // typedef opaque AssetCode4[4]; + // + // =========================================================================== + xdr.typedef("AssetCode4", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef opaque AssetCode12[12]; + // + // =========================================================================== + xdr.typedef("AssetCode12", xdr.opaque(12)); + + // === xdr source ============================================================ + // + // enum AssetType + // { + // ASSET_TYPE_NATIVE = 0, + // ASSET_TYPE_CREDIT_ALPHANUM4 = 1, + // ASSET_TYPE_CREDIT_ALPHANUM12 = 2, + // ASSET_TYPE_POOL_SHARE = 3 + // }; + // + // =========================================================================== + xdr["enum"]("AssetType", { + assetTypeNative: 0, + assetTypeCreditAlphanum4: 1, + assetTypeCreditAlphanum12: 2, + assetTypePoolShare: 3 + }); + + // === xdr source ============================================================ + // + // union AssetCode switch (AssetType type) + // { + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AssetCode4 assetCode4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AssetCode12 assetCode12; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("AssetCode", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeCreditAlphanum4", "assetCode4"], ["assetTypeCreditAlphanum12", "assetCode12"]], + arms: { + assetCode4: xdr.lookup("AssetCode4"), + assetCode12: xdr.lookup("AssetCode12") + } + }); + + // === xdr source ============================================================ + // + // struct AlphaNum4 + // { + // AssetCode4 assetCode; + // AccountID issuer; + // }; + // + // =========================================================================== + xdr.struct("AlphaNum4", [["assetCode", xdr.lookup("AssetCode4")], ["issuer", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // struct AlphaNum12 + // { + // AssetCode12 assetCode; + // AccountID issuer; + // }; + // + // =========================================================================== + xdr.struct("AlphaNum12", [["assetCode", xdr.lookup("AssetCode12")], ["issuer", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // union Asset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("Asset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12") + } + }); + + // === xdr source ============================================================ + // + // struct Price + // { + // int32 n; // numerator + // int32 d; // denominator + // }; + // + // =========================================================================== + xdr.struct("Price", [["n", xdr.lookup("Int32")], ["d", xdr.lookup("Int32")]]); + + // === xdr source ============================================================ + // + // struct Liabilities + // { + // int64 buying; + // int64 selling; + // }; + // + // =========================================================================== + xdr.struct("Liabilities", [["buying", xdr.lookup("Int64")], ["selling", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum ThresholdIndexes + // { + // THRESHOLD_MASTER_WEIGHT = 0, + // THRESHOLD_LOW = 1, + // THRESHOLD_MED = 2, + // THRESHOLD_HIGH = 3 + // }; + // + // =========================================================================== + xdr["enum"]("ThresholdIndices", { + thresholdMasterWeight: 0, + thresholdLow: 1, + thresholdMed: 2, + thresholdHigh: 3 + }); + + // === xdr source ============================================================ + // + // enum LedgerEntryType + // { + // ACCOUNT = 0, + // TRUSTLINE = 1, + // OFFER = 2, + // DATA = 3, + // CLAIMABLE_BALANCE = 4, + // LIQUIDITY_POOL = 5, + // CONTRACT_DATA = 6, + // CONTRACT_CODE = 7, + // CONFIG_SETTING = 8, + // TTL = 9 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerEntryType", { + account: 0, + trustline: 1, + offer: 2, + data: 3, + claimableBalance: 4, + liquidityPool: 5, + contractData: 6, + contractCode: 7, + configSetting: 8, + ttl: 9 + }); + + // === xdr source ============================================================ + // + // struct Signer + // { + // SignerKey key; + // uint32 weight; // really only need 1 byte + // }; + // + // =========================================================================== + xdr.struct("Signer", [["key", xdr.lookup("SignerKey")], ["weight", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // enum AccountFlags + // { // masks for each flag + // + // // Flags set on issuer accounts + // // TrustLines are created with authorized set to "false" requiring + // // the issuer to set it for each TrustLine + // AUTH_REQUIRED_FLAG = 0x1, + // // If set, the authorized flag in TrustLines can be cleared + // // otherwise, authorization cannot be revoked + // AUTH_REVOCABLE_FLAG = 0x2, + // // Once set, causes all AUTH_* flags to be read-only + // AUTH_IMMUTABLE_FLAG = 0x4, + // // Trustlines are created with clawback enabled set to "true", + // // and claimable balances created from those trustlines are created + // // with clawback enabled set to "true" + // AUTH_CLAWBACK_ENABLED_FLAG = 0x8 + // }; + // + // =========================================================================== + xdr["enum"]("AccountFlags", { + authRequiredFlag: 1, + authRevocableFlag: 2, + authImmutableFlag: 4, + authClawbackEnabledFlag: 8 + }); + + // === xdr source ============================================================ + // + // const MASK_ACCOUNT_FLAGS = 0x7; + // + // =========================================================================== + xdr["const"]("MASK_ACCOUNT_FLAGS", 0x7); + + // === xdr source ============================================================ + // + // const MASK_ACCOUNT_FLAGS_V17 = 0xF; + // + // =========================================================================== + xdr["const"]("MASK_ACCOUNT_FLAGS_V17", 0xF); + + // === xdr source ============================================================ + // + // const MAX_SIGNERS = 20; + // + // =========================================================================== + xdr["const"]("MAX_SIGNERS", 20); + + // === xdr source ============================================================ + // + // typedef AccountID* SponsorshipDescriptor; + // + // =========================================================================== + xdr.typedef("SponsorshipDescriptor", xdr.option(xdr.lookup("AccountId"))); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV3 + // { + // // We can use this to add more fields, or because it is first, to + // // change AccountEntryExtensionV3 into a union. + // ExtensionPoint ext; + // + // // Ledger number at which `seqNum` took on its present value. + // uint32 seqLedger; + // + // // Time at which `seqNum` took on its present value. + // TimePoint seqTime; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV3", [["ext", xdr.lookup("ExtensionPoint")], ["seqLedger", xdr.lookup("Uint32")], ["seqTime", xdr.lookup("TimePoint")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 3: + // AccountEntryExtensionV3 v3; + // } + // + // =========================================================================== + xdr.union("AccountEntryExtensionV2Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [3, "v3"]], + arms: { + v3: xdr.lookup("AccountEntryExtensionV3") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV2 + // { + // uint32 numSponsored; + // uint32 numSponsoring; + // SponsorshipDescriptor signerSponsoringIDs; + // + // union switch (int v) + // { + // case 0: + // void; + // case 3: + // AccountEntryExtensionV3 v3; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV2", [["numSponsored", xdr.lookup("Uint32")], ["numSponsoring", xdr.lookup("Uint32")], ["signerSponsoringIDs", xdr.varArray(xdr.lookup("SponsorshipDescriptor"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExtensionV2Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // AccountEntryExtensionV2 v2; + // } + // + // =========================================================================== + xdr.union("AccountEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [2, "v2"]], + arms: { + v2: xdr.lookup("AccountEntryExtensionV2") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV1 + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // AccountEntryExtensionV2 v2; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("AccountEntryExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // AccountEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("AccountEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("AccountEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntry + // { + // AccountID accountID; // master public key for this account + // int64 balance; // in stroops + // SequenceNumber seqNum; // last sequence number used for this account + // uint32 numSubEntries; // number of sub-entries this account has + // // drives the reserve + // AccountID* inflationDest; // Account to vote for during inflation + // uint32 flags; // see AccountFlags + // + // string32 homeDomain; // can be used for reverse federation and memo lookup + // + // // fields used for signatures + // // thresholds stores unsigned bytes: [weight of master|low|medium|high] + // Thresholds thresholds; + // + // Signer signers; // possible signers for this account + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // AccountEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntry", [["accountId", xdr.lookup("AccountId")], ["balance", xdr.lookup("Int64")], ["seqNum", xdr.lookup("SequenceNumber")], ["numSubEntries", xdr.lookup("Uint32")], ["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["flags", xdr.lookup("Uint32")], ["homeDomain", xdr.lookup("String32")], ["thresholds", xdr.lookup("Thresholds")], ["signers", xdr.varArray(xdr.lookup("Signer"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExt")]]); + + // === xdr source ============================================================ + // + // enum TrustLineFlags + // { + // // issuer has authorized account to perform transactions with its credit + // AUTHORIZED_FLAG = 1, + // // issuer has authorized account to maintain and reduce liabilities for its + // // credit + // AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG = 2, + // // issuer has specified that it may clawback its credit, and that claimable + // // balances created with its credit may also be clawed back + // TRUSTLINE_CLAWBACK_ENABLED_FLAG = 4 + // }; + // + // =========================================================================== + xdr["enum"]("TrustLineFlags", { + authorizedFlag: 1, + authorizedToMaintainLiabilitiesFlag: 2, + trustlineClawbackEnabledFlag: 4 + }); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS = 1; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS", 1); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS_V13 = 3; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS_V13", 3); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS_V17 = 7; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS_V17", 7); + + // === xdr source ============================================================ + // + // enum LiquidityPoolType + // { + // LIQUIDITY_POOL_CONSTANT_PRODUCT = 0 + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolType", { + liquidityPoolConstantProduct: 0 + }); + + // === xdr source ============================================================ + // + // union TrustLineAsset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // case ASSET_TYPE_POOL_SHARE: + // PoolID liquidityPoolID; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("TrustLineAsset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPoolId"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12"), + liquidityPoolId: xdr.lookup("PoolId") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryExtensionV2Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TrustLineEntryExtensionV2 + // { + // int32 liquidityPoolUseCount; + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TrustLineEntryExtensionV2", [["liquidityPoolUseCount", xdr.lookup("Int32")], ["ext", xdr.lookup("TrustLineEntryExtensionV2Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [2, "v2"]], + arms: { + v2: xdr.lookup("TrustLineEntryExtensionV2") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } + // + // =========================================================================== + xdr.struct("TrustLineEntryV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("TrustLineEntryV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } v1; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("TrustLineEntryV1") + } + }); + + // === xdr source ============================================================ + // + // struct TrustLineEntry + // { + // AccountID accountID; // account this trustline belongs to + // TrustLineAsset asset; // type of asset (with issuer) + // int64 balance; // how much of this asset the user has. + // // Asset defines the unit for this; + // + // int64 limit; // balance cannot be above this + // uint32 flags; // see TrustLineFlags + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TrustLineEntry", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")], ["balance", xdr.lookup("Int64")], ["limit", xdr.lookup("Int64")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("TrustLineEntryExt")]]); + + // === xdr source ============================================================ + // + // enum OfferEntryFlags + // { + // // an offer with this flag will not act on and take a reverse offer of equal + // // price + // PASSIVE_FLAG = 1 + // }; + // + // =========================================================================== + xdr["enum"]("OfferEntryFlags", { + passiveFlag: 1 + }); + + // === xdr source ============================================================ + // + // const MASK_OFFERENTRY_FLAGS = 1; + // + // =========================================================================== + xdr["const"]("MASK_OFFERENTRY_FLAGS", 1); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("OfferEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct OfferEntry + // { + // AccountID sellerID; + // int64 offerID; + // Asset selling; // A + // Asset buying; // B + // int64 amount; // amount of A + // + // /* price for this offer: + // price of A in terms of B + // price=AmountB/AmountA=priceNumerator/priceDenominator + // price is after fees + // */ + // Price price; + // uint32 flags; // see OfferEntryFlags + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("OfferEntry", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("OfferEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("DataEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct DataEntry + // { + // AccountID accountID; // account this data belongs to + // string64 dataName; + // DataValue dataValue; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("DataEntry", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")], ["dataValue", xdr.lookup("DataValue")], ["ext", xdr.lookup("DataEntryExt")]]); + + // === xdr source ============================================================ + // + // enum ClaimPredicateType + // { + // CLAIM_PREDICATE_UNCONDITIONAL = 0, + // CLAIM_PREDICATE_AND = 1, + // CLAIM_PREDICATE_OR = 2, + // CLAIM_PREDICATE_NOT = 3, + // CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME = 4, + // CLAIM_PREDICATE_BEFORE_RELATIVE_TIME = 5 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimPredicateType", { + claimPredicateUnconditional: 0, + claimPredicateAnd: 1, + claimPredicateOr: 2, + claimPredicateNot: 3, + claimPredicateBeforeAbsoluteTime: 4, + claimPredicateBeforeRelativeTime: 5 + }); + + // === xdr source ============================================================ + // + // union ClaimPredicate switch (ClaimPredicateType type) + // { + // case CLAIM_PREDICATE_UNCONDITIONAL: + // void; + // case CLAIM_PREDICATE_AND: + // ClaimPredicate andPredicates<2>; + // case CLAIM_PREDICATE_OR: + // ClaimPredicate orPredicates<2>; + // case CLAIM_PREDICATE_NOT: + // ClaimPredicate* notPredicate; + // case CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME: + // int64 absBefore; // Predicate will be true if closeTime < absBefore + // case CLAIM_PREDICATE_BEFORE_RELATIVE_TIME: + // int64 relBefore; // Seconds since closeTime of the ledger in which the + // // ClaimableBalanceEntry was created + // }; + // + // =========================================================================== + xdr.union("ClaimPredicate", { + switchOn: xdr.lookup("ClaimPredicateType"), + switchName: "type", + switches: [["claimPredicateUnconditional", xdr["void"]()], ["claimPredicateAnd", "andPredicates"], ["claimPredicateOr", "orPredicates"], ["claimPredicateNot", "notPredicate"], ["claimPredicateBeforeAbsoluteTime", "absBefore"], ["claimPredicateBeforeRelativeTime", "relBefore"]], + arms: { + andPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2), + orPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2), + notPredicate: xdr.option(xdr.lookup("ClaimPredicate")), + absBefore: xdr.lookup("Int64"), + relBefore: xdr.lookup("Int64") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimantType + // { + // CLAIMANT_TYPE_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimantType", { + claimantTypeV0: 0 + }); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID destination; // The account that can use this condition + // ClaimPredicate predicate; // Claimable if predicate is true + // } + // + // =========================================================================== + xdr.struct("ClaimantV0", [["destination", xdr.lookup("AccountId")], ["predicate", xdr.lookup("ClaimPredicate")]]); + + // === xdr source ============================================================ + // + // union Claimant switch (ClaimantType type) + // { + // case CLAIMANT_TYPE_V0: + // struct + // { + // AccountID destination; // The account that can use this condition + // ClaimPredicate predicate; // Claimable if predicate is true + // } v0; + // }; + // + // =========================================================================== + xdr.union("Claimant", { + switchOn: xdr.lookup("ClaimantType"), + switchName: "type", + switches: [["claimantTypeV0", "v0"]], + arms: { + v0: xdr.lookup("ClaimantV0") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimableBalanceIDType + // { + // CLAIMABLE_BALANCE_ID_TYPE_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimableBalanceIdType", { + claimableBalanceIdTypeV0: 0 + }); + + // === xdr source ============================================================ + // + // union ClaimableBalanceID switch (ClaimableBalanceIDType type) + // { + // case CLAIMABLE_BALANCE_ID_TYPE_V0: + // Hash v0; + // }; + // + // =========================================================================== + xdr.union("ClaimableBalanceId", { + switchOn: xdr.lookup("ClaimableBalanceIdType"), + switchName: "type", + switches: [["claimableBalanceIdTypeV0", "v0"]], + arms: { + v0: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimableBalanceFlags + // { + // // If set, the issuer account of the asset held by the claimable balance may + // // clawback the claimable balance + // CLAIMABLE_BALANCE_CLAWBACK_ENABLED_FLAG = 0x1 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimableBalanceFlags", { + claimableBalanceClawbackEnabledFlag: 1 + }); + + // === xdr source ============================================================ + // + // const MASK_CLAIMABLE_BALANCE_FLAGS = 0x1; + // + // =========================================================================== + xdr["const"]("MASK_CLAIMABLE_BALANCE_FLAGS", 0x1); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("ClaimableBalanceEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct ClaimableBalanceEntryExtensionV1 + // { + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // + // uint32 flags; // see ClaimableBalanceFlags + // }; + // + // =========================================================================== + xdr.struct("ClaimableBalanceEntryExtensionV1", [["ext", xdr.lookup("ClaimableBalanceEntryExtensionV1Ext")], ["flags", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ClaimableBalanceEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("ClaimableBalanceEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("ClaimableBalanceEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct ClaimableBalanceEntry + // { + // // Unique identifier for this ClaimableBalanceEntry + // ClaimableBalanceID balanceID; + // + // // List of claimants with associated predicate + // Claimant claimants<10>; + // + // // Any asset including native + // Asset asset; + // + // // Amount of asset + // int64 amount; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ClaimableBalanceEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("ClaimableBalanceEntry", [["balanceId", xdr.lookup("ClaimableBalanceId")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["ext", xdr.lookup("ClaimableBalanceEntryExt")]]); + + // === xdr source ============================================================ + // + // struct LiquidityPoolConstantProductParameters + // { + // Asset assetA; // assetA < assetB + // Asset assetB; + // int32 fee; // Fee is in basis points, so the actual rate is (fee/100)% + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolConstantProductParameters", [["assetA", xdr.lookup("Asset")], ["assetB", xdr.lookup("Asset")], ["fee", xdr.lookup("Int32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } + // + // =========================================================================== + xdr.struct("LiquidityPoolEntryConstantProduct", [["params", xdr.lookup("LiquidityPoolConstantProductParameters")], ["reserveA", xdr.lookup("Int64")], ["reserveB", xdr.lookup("Int64")], ["totalPoolShares", xdr.lookup("Int64")], ["poolSharesTrustLineCount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } constantProduct; + // } + // + // =========================================================================== + xdr.union("LiquidityPoolEntryBody", { + switchOn: xdr.lookup("LiquidityPoolType"), + switchName: "type", + switches: [["liquidityPoolConstantProduct", "constantProduct"]], + arms: { + constantProduct: xdr.lookup("LiquidityPoolEntryConstantProduct") + } + }); + + // === xdr source ============================================================ + // + // struct LiquidityPoolEntry + // { + // PoolID liquidityPoolID; + // + // union switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } constantProduct; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolEntry", [["liquidityPoolId", xdr.lookup("PoolId")], ["body", xdr.lookup("LiquidityPoolEntryBody")]]); + + // === xdr source ============================================================ + // + // enum ContractDataDurability { + // TEMPORARY = 0, + // PERSISTENT = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractDataDurability", { + temporary: 0, + persistent: 1 + }); + + // === xdr source ============================================================ + // + // struct ContractDataEntry { + // ExtensionPoint ext; + // + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // SCVal val; + // }; + // + // =========================================================================== + xdr.struct("ContractDataEntry", [["ext", xdr.lookup("ExtensionPoint")], ["contract", xdr.lookup("ScAddress")], ["key", xdr.lookup("ScVal")], ["durability", xdr.lookup("ContractDataDurability")], ["val", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // struct ContractCodeCostInputs { + // ExtensionPoint ext; + // uint32 nInstructions; + // uint32 nFunctions; + // uint32 nGlobals; + // uint32 nTableEntries; + // uint32 nTypes; + // uint32 nDataSegments; + // uint32 nElemSegments; + // uint32 nImports; + // uint32 nExports; + // uint32 nDataSegmentBytes; + // }; + // + // =========================================================================== + xdr.struct("ContractCodeCostInputs", [["ext", xdr.lookup("ExtensionPoint")], ["nInstructions", xdr.lookup("Uint32")], ["nFunctions", xdr.lookup("Uint32")], ["nGlobals", xdr.lookup("Uint32")], ["nTableEntries", xdr.lookup("Uint32")], ["nTypes", xdr.lookup("Uint32")], ["nDataSegments", xdr.lookup("Uint32")], ["nElemSegments", xdr.lookup("Uint32")], ["nImports", xdr.lookup("Uint32")], ["nExports", xdr.lookup("Uint32")], ["nDataSegmentBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } + // + // =========================================================================== + xdr.struct("ContractCodeEntryV1", [["ext", xdr.lookup("ExtensionPoint")], ["costInputs", xdr.lookup("ContractCodeCostInputs")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } v1; + // } + // + // =========================================================================== + xdr.union("ContractCodeEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("ContractCodeEntryV1") + } + }); + + // === xdr source ============================================================ + // + // struct ContractCodeEntry { + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } v1; + // } ext; + // + // Hash hash; + // opaque code<>; + // }; + // + // =========================================================================== + xdr.struct("ContractCodeEntry", [["ext", xdr.lookup("ContractCodeEntryExt")], ["hash", xdr.lookup("Hash")], ["code", xdr.varOpaque()]]); + + // === xdr source ============================================================ + // + // struct TTLEntry { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // uint32 liveUntilLedgerSeq; + // }; + // + // =========================================================================== + xdr.struct("TtlEntry", [["keyHash", xdr.lookup("Hash")], ["liveUntilLedgerSeq", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerEntryExtensionV1 + // { + // SponsorshipDescriptor sponsoringID; + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerEntryExtensionV1", [["sponsoringId", xdr.lookup("SponsorshipDescriptor")], ["ext", xdr.lookup("LedgerEntryExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (LedgerEntryType type) + // { + // case ACCOUNT: + // AccountEntry account; + // case TRUSTLINE: + // TrustLineEntry trustLine; + // case OFFER: + // OfferEntry offer; + // case DATA: + // DataEntry data; + // case CLAIMABLE_BALANCE: + // ClaimableBalanceEntry claimableBalance; + // case LIQUIDITY_POOL: + // LiquidityPoolEntry liquidityPool; + // case CONTRACT_DATA: + // ContractDataEntry contractData; + // case CONTRACT_CODE: + // ContractCodeEntry contractCode; + // case CONFIG_SETTING: + // ConfigSettingEntry configSetting; + // case TTL: + // TTLEntry ttl; + // } + // + // =========================================================================== + xdr.union("LedgerEntryData", { + switchOn: xdr.lookup("LedgerEntryType"), + switchName: "type", + switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"], ["contractData", "contractData"], ["contractCode", "contractCode"], ["configSetting", "configSetting"], ["ttl", "ttl"]], + arms: { + account: xdr.lookup("AccountEntry"), + trustLine: xdr.lookup("TrustLineEntry"), + offer: xdr.lookup("OfferEntry"), + data: xdr.lookup("DataEntry"), + claimableBalance: xdr.lookup("ClaimableBalanceEntry"), + liquidityPool: xdr.lookup("LiquidityPoolEntry"), + contractData: xdr.lookup("ContractDataEntry"), + contractCode: xdr.lookup("ContractCodeEntry"), + configSetting: xdr.lookup("ConfigSettingEntry"), + ttl: xdr.lookup("TtlEntry") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("LedgerEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerEntry + // { + // uint32 lastModifiedLedgerSeq; // ledger the LedgerEntry was last changed + // + // union switch (LedgerEntryType type) + // { + // case ACCOUNT: + // AccountEntry account; + // case TRUSTLINE: + // TrustLineEntry trustLine; + // case OFFER: + // OfferEntry offer; + // case DATA: + // DataEntry data; + // case CLAIMABLE_BALANCE: + // ClaimableBalanceEntry claimableBalance; + // case LIQUIDITY_POOL: + // LiquidityPoolEntry liquidityPool; + // case CONTRACT_DATA: + // ContractDataEntry contractData; + // case CONTRACT_CODE: + // ContractCodeEntry contractCode; + // case CONFIG_SETTING: + // ConfigSettingEntry configSetting; + // case TTL: + // TTLEntry ttl; + // } + // data; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerEntry", [["lastModifiedLedgerSeq", xdr.lookup("Uint32")], ["data", xdr.lookup("LedgerEntryData")], ["ext", xdr.lookup("LedgerEntryExt")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyAccount", [["accountId", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // TrustLineAsset asset; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyTrustLine", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sellerID; + // int64 offerID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyOffer", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // string64 dataName; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyData", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimableBalanceID balanceID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyClaimableBalance", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // PoolID liquidityPoolID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyLiquidityPool", [["liquidityPoolId", xdr.lookup("PoolId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyContractData", [["contract", xdr.lookup("ScAddress")], ["key", xdr.lookup("ScVal")], ["durability", xdr.lookup("ContractDataDurability")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash hash; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyContractCode", [["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ConfigSettingID configSettingID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyConfigSetting", [["configSettingId", xdr.lookup("ConfigSettingId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyTtl", [["keyHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union LedgerKey switch (LedgerEntryType type) + // { + // case ACCOUNT: + // struct + // { + // AccountID accountID; + // } account; + // + // case TRUSTLINE: + // struct + // { + // AccountID accountID; + // TrustLineAsset asset; + // } trustLine; + // + // case OFFER: + // struct + // { + // AccountID sellerID; + // int64 offerID; + // } offer; + // + // case DATA: + // struct + // { + // AccountID accountID; + // string64 dataName; + // } data; + // + // case CLAIMABLE_BALANCE: + // struct + // { + // ClaimableBalanceID balanceID; + // } claimableBalance; + // + // case LIQUIDITY_POOL: + // struct + // { + // PoolID liquidityPoolID; + // } liquidityPool; + // case CONTRACT_DATA: + // struct + // { + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // } contractData; + // case CONTRACT_CODE: + // struct + // { + // Hash hash; + // } contractCode; + // case CONFIG_SETTING: + // struct + // { + // ConfigSettingID configSettingID; + // } configSetting; + // case TTL: + // struct + // { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // } ttl; + // }; + // + // =========================================================================== + xdr.union("LedgerKey", { + switchOn: xdr.lookup("LedgerEntryType"), + switchName: "type", + switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"], ["contractData", "contractData"], ["contractCode", "contractCode"], ["configSetting", "configSetting"], ["ttl", "ttl"]], + arms: { + account: xdr.lookup("LedgerKeyAccount"), + trustLine: xdr.lookup("LedgerKeyTrustLine"), + offer: xdr.lookup("LedgerKeyOffer"), + data: xdr.lookup("LedgerKeyData"), + claimableBalance: xdr.lookup("LedgerKeyClaimableBalance"), + liquidityPool: xdr.lookup("LedgerKeyLiquidityPool"), + contractData: xdr.lookup("LedgerKeyContractData"), + contractCode: xdr.lookup("LedgerKeyContractCode"), + configSetting: xdr.lookup("LedgerKeyConfigSetting"), + ttl: xdr.lookup("LedgerKeyTtl") + } + }); + + // === xdr source ============================================================ + // + // enum EnvelopeType + // { + // ENVELOPE_TYPE_TX_V0 = 0, + // ENVELOPE_TYPE_SCP = 1, + // ENVELOPE_TYPE_TX = 2, + // ENVELOPE_TYPE_AUTH = 3, + // ENVELOPE_TYPE_SCPVALUE = 4, + // ENVELOPE_TYPE_TX_FEE_BUMP = 5, + // ENVELOPE_TYPE_OP_ID = 6, + // ENVELOPE_TYPE_POOL_REVOKE_OP_ID = 7, + // ENVELOPE_TYPE_CONTRACT_ID = 8, + // ENVELOPE_TYPE_SOROBAN_AUTHORIZATION = 9 + // }; + // + // =========================================================================== + xdr["enum"]("EnvelopeType", { + envelopeTypeTxV0: 0, + envelopeTypeScp: 1, + envelopeTypeTx: 2, + envelopeTypeAuth: 3, + envelopeTypeScpvalue: 4, + envelopeTypeTxFeeBump: 5, + envelopeTypeOpId: 6, + envelopeTypePoolRevokeOpId: 7, + envelopeTypeContractId: 8, + envelopeTypeSorobanAuthorization: 9 + }); + + // === xdr source ============================================================ + // + // enum BucketListType + // { + // LIVE = 0, + // HOT_ARCHIVE = 1, + // COLD_ARCHIVE = 2 + // }; + // + // =========================================================================== + xdr["enum"]("BucketListType", { + live: 0, + hotArchive: 1, + coldArchive: 2 + }); + + // === xdr source ============================================================ + // + // enum BucketEntryType + // { + // METAENTRY = + // -1, // At-and-after protocol 11: bucket metadata, should come first. + // LIVEENTRY = 0, // Before protocol 11: created-or-updated; + // // At-and-after protocol 11: only updated. + // DEADENTRY = 1, + // INITENTRY = 2 // At-and-after protocol 11: only created. + // }; + // + // =========================================================================== + xdr["enum"]("BucketEntryType", { + metaentry: -1, + liveentry: 0, + deadentry: 1, + initentry: 2 + }); + + // === xdr source ============================================================ + // + // enum HotArchiveBucketEntryType + // { + // HOT_ARCHIVE_METAENTRY = -1, // Bucket metadata, should come first. + // HOT_ARCHIVE_ARCHIVED = 0, // Entry is Archived + // HOT_ARCHIVE_LIVE = 1, // Entry was previously HOT_ARCHIVE_ARCHIVED, or HOT_ARCHIVE_DELETED, but + // // has been added back to the live BucketList. + // // Does not need to be persisted. + // HOT_ARCHIVE_DELETED = 2 // Entry deleted (Note: must be persisted in archive) + // }; + // + // =========================================================================== + xdr["enum"]("HotArchiveBucketEntryType", { + hotArchiveMetaentry: -1, + hotArchiveArchived: 0, + hotArchiveLive: 1, + hotArchiveDeleted: 2 + }); + + // === xdr source ============================================================ + // + // enum ColdArchiveBucketEntryType + // { + // COLD_ARCHIVE_METAENTRY = -1, // Bucket metadata, should come first. + // COLD_ARCHIVE_ARCHIVED_LEAF = 0, // Full LedgerEntry that was archived during the epoch + // COLD_ARCHIVE_DELETED_LEAF = 1, // LedgerKey that was deleted during the epoch + // COLD_ARCHIVE_BOUNDARY_LEAF = 2, // Dummy leaf representing low/high bound + // COLD_ARCHIVE_HASH = 3 // Intermediary Merkle hash entry + // }; + // + // =========================================================================== + xdr["enum"]("ColdArchiveBucketEntryType", { + coldArchiveMetaentry: -1, + coldArchiveArchivedLeaf: 0, + coldArchiveDeletedLeaf: 1, + coldArchiveBoundaryLeaf: 2, + coldArchiveHash: 3 + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // BucketListType bucketListType; + // } + // + // =========================================================================== + xdr.union("BucketMetadataExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "bucketListType"]], + arms: { + bucketListType: xdr.lookup("BucketListType") + } + }); + + // === xdr source ============================================================ + // + // struct BucketMetadata + // { + // // Indicates the protocol version used to create / merge this bucket. + // uint32 ledgerVersion; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // BucketListType bucketListType; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("BucketMetadata", [["ledgerVersion", xdr.lookup("Uint32")], ["ext", xdr.lookup("BucketMetadataExt")]]); + + // === xdr source ============================================================ + // + // union BucketEntry switch (BucketEntryType type) + // { + // case LIVEENTRY: + // case INITENTRY: + // LedgerEntry liveEntry; + // + // case DEADENTRY: + // LedgerKey deadEntry; + // case METAENTRY: + // BucketMetadata metaEntry; + // }; + // + // =========================================================================== + xdr.union("BucketEntry", { + switchOn: xdr.lookup("BucketEntryType"), + switchName: "type", + switches: [["liveentry", "liveEntry"], ["initentry", "liveEntry"], ["deadentry", "deadEntry"], ["metaentry", "metaEntry"]], + arms: { + liveEntry: xdr.lookup("LedgerEntry"), + deadEntry: xdr.lookup("LedgerKey"), + metaEntry: xdr.lookup("BucketMetadata") + } + }); + + // === xdr source ============================================================ + // + // union HotArchiveBucketEntry switch (HotArchiveBucketEntryType type) + // { + // case HOT_ARCHIVE_ARCHIVED: + // LedgerEntry archivedEntry; + // + // case HOT_ARCHIVE_LIVE: + // case HOT_ARCHIVE_DELETED: + // LedgerKey key; + // case HOT_ARCHIVE_METAENTRY: + // BucketMetadata metaEntry; + // }; + // + // =========================================================================== + xdr.union("HotArchiveBucketEntry", { + switchOn: xdr.lookup("HotArchiveBucketEntryType"), + switchName: "type", + switches: [["hotArchiveArchived", "archivedEntry"], ["hotArchiveLive", "key"], ["hotArchiveDeleted", "key"], ["hotArchiveMetaentry", "metaEntry"]], + arms: { + archivedEntry: xdr.lookup("LedgerEntry"), + key: xdr.lookup("LedgerKey"), + metaEntry: xdr.lookup("BucketMetadata") + } + }); + + // === xdr source ============================================================ + // + // struct ColdArchiveArchivedLeaf + // { + // uint32 index; + // LedgerEntry archivedEntry; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveArchivedLeaf", [["index", xdr.lookup("Uint32")], ["archivedEntry", xdr.lookup("LedgerEntry")]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveDeletedLeaf + // { + // uint32 index; + // LedgerKey deletedKey; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveDeletedLeaf", [["index", xdr.lookup("Uint32")], ["deletedKey", xdr.lookup("LedgerKey")]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveBoundaryLeaf + // { + // uint32 index; + // bool isLowerBound; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveBoundaryLeaf", [["index", xdr.lookup("Uint32")], ["isLowerBound", xdr.bool()]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveHashEntry + // { + // uint32 index; + // uint32 level; + // Hash hash; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveHashEntry", [["index", xdr.lookup("Uint32")], ["level", xdr.lookup("Uint32")], ["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union ColdArchiveBucketEntry switch (ColdArchiveBucketEntryType type) + // { + // case COLD_ARCHIVE_METAENTRY: + // BucketMetadata metaEntry; + // case COLD_ARCHIVE_ARCHIVED_LEAF: + // ColdArchiveArchivedLeaf archivedLeaf; + // case COLD_ARCHIVE_DELETED_LEAF: + // ColdArchiveDeletedLeaf deletedLeaf; + // case COLD_ARCHIVE_BOUNDARY_LEAF: + // ColdArchiveBoundaryLeaf boundaryLeaf; + // case COLD_ARCHIVE_HASH: + // ColdArchiveHashEntry hashEntry; + // }; + // + // =========================================================================== + xdr.union("ColdArchiveBucketEntry", { + switchOn: xdr.lookup("ColdArchiveBucketEntryType"), + switchName: "type", + switches: [["coldArchiveMetaentry", "metaEntry"], ["coldArchiveArchivedLeaf", "archivedLeaf"], ["coldArchiveDeletedLeaf", "deletedLeaf"], ["coldArchiveBoundaryLeaf", "boundaryLeaf"], ["coldArchiveHash", "hashEntry"]], + arms: { + metaEntry: xdr.lookup("BucketMetadata"), + archivedLeaf: xdr.lookup("ColdArchiveArchivedLeaf"), + deletedLeaf: xdr.lookup("ColdArchiveDeletedLeaf"), + boundaryLeaf: xdr.lookup("ColdArchiveBoundaryLeaf"), + hashEntry: xdr.lookup("ColdArchiveHashEntry") + } + }); + + // === xdr source ============================================================ + // + // typedef opaque UpgradeType<128>; + // + // =========================================================================== + xdr.typedef("UpgradeType", xdr.varOpaque(128)); + + // === xdr source ============================================================ + // + // enum StellarValueType + // { + // STELLAR_VALUE_BASIC = 0, + // STELLAR_VALUE_SIGNED = 1 + // }; + // + // =========================================================================== + xdr["enum"]("StellarValueType", { + stellarValueBasic: 0, + stellarValueSigned: 1 + }); + + // === xdr source ============================================================ + // + // struct LedgerCloseValueSignature + // { + // NodeID nodeID; // which node introduced the value + // Signature signature; // nodeID's signature + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseValueSignature", [["nodeId", xdr.lookup("NodeId")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // union switch (StellarValueType v) + // { + // case STELLAR_VALUE_BASIC: + // void; + // case STELLAR_VALUE_SIGNED: + // LedgerCloseValueSignature lcValueSignature; + // } + // + // =========================================================================== + xdr.union("StellarValueExt", { + switchOn: xdr.lookup("StellarValueType"), + switchName: "v", + switches: [["stellarValueBasic", xdr["void"]()], ["stellarValueSigned", "lcValueSignature"]], + arms: { + lcValueSignature: xdr.lookup("LedgerCloseValueSignature") + } + }); + + // === xdr source ============================================================ + // + // struct StellarValue + // { + // Hash txSetHash; // transaction set to apply to previous ledger + // TimePoint closeTime; // network close time + // + // // upgrades to apply to the previous ledger (usually empty) + // // this is a vector of encoded 'LedgerUpgrade' so that nodes can drop + // // unknown steps during consensus if needed. + // // see notes below on 'LedgerUpgrade' for more detail + // // max size is dictated by number of upgrade types (+ room for future) + // UpgradeType upgrades<6>; + // + // // reserved for future use + // union switch (StellarValueType v) + // { + // case STELLAR_VALUE_BASIC: + // void; + // case STELLAR_VALUE_SIGNED: + // LedgerCloseValueSignature lcValueSignature; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("StellarValue", [["txSetHash", xdr.lookup("Hash")], ["closeTime", xdr.lookup("TimePoint")], ["upgrades", xdr.varArray(xdr.lookup("UpgradeType"), 6)], ["ext", xdr.lookup("StellarValueExt")]]); + + // === xdr source ============================================================ + // + // const MASK_LEDGER_HEADER_FLAGS = 0x7; + // + // =========================================================================== + xdr["const"]("MASK_LEDGER_HEADER_FLAGS", 0x7); + + // === xdr source ============================================================ + // + // enum LedgerHeaderFlags + // { + // DISABLE_LIQUIDITY_POOL_TRADING_FLAG = 0x1, + // DISABLE_LIQUIDITY_POOL_DEPOSIT_FLAG = 0x2, + // DISABLE_LIQUIDITY_POOL_WITHDRAWAL_FLAG = 0x4 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerHeaderFlags", { + disableLiquidityPoolTradingFlag: 1, + disableLiquidityPoolDepositFlag: 2, + disableLiquidityPoolWithdrawalFlag: 4 + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerHeaderExtensionV1 + // { + // uint32 flags; // LedgerHeaderFlags + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeaderExtensionV1", [["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("LedgerHeaderExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerHeaderExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerHeaderExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerHeader + // { + // uint32 ledgerVersion; // the protocol version of the ledger + // Hash previousLedgerHash; // hash of the previous ledger header + // StellarValue scpValue; // what consensus agreed to + // Hash txSetResultHash; // the TransactionResultSet that led to this ledger + // Hash bucketListHash; // hash of the ledger state + // + // uint32 ledgerSeq; // sequence number of this ledger + // + // int64 totalCoins; // total number of stroops in existence. + // // 10,000,000 stroops in 1 XLM + // + // int64 feePool; // fees burned since last inflation run + // uint32 inflationSeq; // inflation sequence number + // + // uint64 idPool; // last used global ID, used for generating objects + // + // uint32 baseFee; // base fee per operation in stroops + // uint32 baseReserve; // account base reserve in stroops + // + // uint32 maxTxSetSize; // maximum size a transaction set can be + // + // Hash skipList[4]; // hashes of ledgers in the past. allows you to jump back + // // in time without walking the chain back ledger by ledger + // // each slot contains the oldest ledger that is mod of + // // either 50 5000 50000 or 500000 depending on index + // // skipList[0] mod(50), skipList[1] mod(5000), etc + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerHeaderExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeader", [["ledgerVersion", xdr.lookup("Uint32")], ["previousLedgerHash", xdr.lookup("Hash")], ["scpValue", xdr.lookup("StellarValue")], ["txSetResultHash", xdr.lookup("Hash")], ["bucketListHash", xdr.lookup("Hash")], ["ledgerSeq", xdr.lookup("Uint32")], ["totalCoins", xdr.lookup("Int64")], ["feePool", xdr.lookup("Int64")], ["inflationSeq", xdr.lookup("Uint32")], ["idPool", xdr.lookup("Uint64")], ["baseFee", xdr.lookup("Uint32")], ["baseReserve", xdr.lookup("Uint32")], ["maxTxSetSize", xdr.lookup("Uint32")], ["skipList", xdr.array(xdr.lookup("Hash"), 4)], ["ext", xdr.lookup("LedgerHeaderExt")]]); + + // === xdr source ============================================================ + // + // enum LedgerUpgradeType + // { + // LEDGER_UPGRADE_VERSION = 1, + // LEDGER_UPGRADE_BASE_FEE = 2, + // LEDGER_UPGRADE_MAX_TX_SET_SIZE = 3, + // LEDGER_UPGRADE_BASE_RESERVE = 4, + // LEDGER_UPGRADE_FLAGS = 5, + // LEDGER_UPGRADE_CONFIG = 6, + // LEDGER_UPGRADE_MAX_SOROBAN_TX_SET_SIZE = 7 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerUpgradeType", { + ledgerUpgradeVersion: 1, + ledgerUpgradeBaseFee: 2, + ledgerUpgradeMaxTxSetSize: 3, + ledgerUpgradeBaseReserve: 4, + ledgerUpgradeFlags: 5, + ledgerUpgradeConfig: 6, + ledgerUpgradeMaxSorobanTxSetSize: 7 + }); + + // === xdr source ============================================================ + // + // struct ConfigUpgradeSetKey { + // Hash contractID; + // Hash contentHash; + // }; + // + // =========================================================================== + xdr.struct("ConfigUpgradeSetKey", [["contractId", xdr.lookup("Hash")], ["contentHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union LedgerUpgrade switch (LedgerUpgradeType type) + // { + // case LEDGER_UPGRADE_VERSION: + // uint32 newLedgerVersion; // update ledgerVersion + // case LEDGER_UPGRADE_BASE_FEE: + // uint32 newBaseFee; // update baseFee + // case LEDGER_UPGRADE_MAX_TX_SET_SIZE: + // uint32 newMaxTxSetSize; // update maxTxSetSize + // case LEDGER_UPGRADE_BASE_RESERVE: + // uint32 newBaseReserve; // update baseReserve + // case LEDGER_UPGRADE_FLAGS: + // uint32 newFlags; // update flags + // case LEDGER_UPGRADE_CONFIG: + // // Update arbitrary `ConfigSetting` entries identified by the key. + // ConfigUpgradeSetKey newConfig; + // case LEDGER_UPGRADE_MAX_SOROBAN_TX_SET_SIZE: + // // Update ConfigSettingContractExecutionLanesV0.ledgerMaxTxCount without + // // using `LEDGER_UPGRADE_CONFIG`. + // uint32 newMaxSorobanTxSetSize; + // }; + // + // =========================================================================== + xdr.union("LedgerUpgrade", { + switchOn: xdr.lookup("LedgerUpgradeType"), + switchName: "type", + switches: [["ledgerUpgradeVersion", "newLedgerVersion"], ["ledgerUpgradeBaseFee", "newBaseFee"], ["ledgerUpgradeMaxTxSetSize", "newMaxTxSetSize"], ["ledgerUpgradeBaseReserve", "newBaseReserve"], ["ledgerUpgradeFlags", "newFlags"], ["ledgerUpgradeConfig", "newConfig"], ["ledgerUpgradeMaxSorobanTxSetSize", "newMaxSorobanTxSetSize"]], + arms: { + newLedgerVersion: xdr.lookup("Uint32"), + newBaseFee: xdr.lookup("Uint32"), + newMaxTxSetSize: xdr.lookup("Uint32"), + newBaseReserve: xdr.lookup("Uint32"), + newFlags: xdr.lookup("Uint32"), + newConfig: xdr.lookup("ConfigUpgradeSetKey"), + newMaxSorobanTxSetSize: xdr.lookup("Uint32") + } + }); + + // === xdr source ============================================================ + // + // struct ConfigUpgradeSet { + // ConfigSettingEntry updatedEntry<>; + // }; + // + // =========================================================================== + xdr.struct("ConfigUpgradeSet", [["updatedEntry", xdr.varArray(xdr.lookup("ConfigSettingEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // enum TxSetComponentType + // { + // // txs with effective fee <= bid derived from a base fee (if any). + // // If base fee is not specified, no discount is applied. + // TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE = 0 + // }; + // + // =========================================================================== + xdr["enum"]("TxSetComponentType", { + txsetCompTxsMaybeDiscountedFee: 0 + }); + + // === xdr source ============================================================ + // + // typedef TransactionEnvelope TxExecutionThread<>; + // + // =========================================================================== + xdr.typedef("TxExecutionThread", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef TxExecutionThread ParallelTxExecutionStage<>; + // + // =========================================================================== + xdr.typedef("ParallelTxExecutionStage", xdr.varArray(xdr.lookup("TxExecutionThread"), 2147483647)); + + // === xdr source ============================================================ + // + // struct ParallelTxsComponent + // { + // int64* baseFee; + // ParallelTxExecutionStage executionStages<>; + // }; + // + // =========================================================================== + xdr.struct("ParallelTxsComponent", [["baseFee", xdr.option(xdr.lookup("Int64"))], ["executionStages", xdr.varArray(xdr.lookup("ParallelTxExecutionStage"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct + // { + // int64* baseFee; + // TransactionEnvelope txs<>; + // } + // + // =========================================================================== + xdr.struct("TxSetComponentTxsMaybeDiscountedFee", [["baseFee", xdr.option(xdr.lookup("Int64"))], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union TxSetComponent switch (TxSetComponentType type) + // { + // case TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE: + // struct + // { + // int64* baseFee; + // TransactionEnvelope txs<>; + // } txsMaybeDiscountedFee; + // }; + // + // =========================================================================== + xdr.union("TxSetComponent", { + switchOn: xdr.lookup("TxSetComponentType"), + switchName: "type", + switches: [["txsetCompTxsMaybeDiscountedFee", "txsMaybeDiscountedFee"]], + arms: { + txsMaybeDiscountedFee: xdr.lookup("TxSetComponentTxsMaybeDiscountedFee") + } + }); + + // === xdr source ============================================================ + // + // union TransactionPhase switch (int v) + // { + // case 0: + // TxSetComponent v0Components<>; + // case 1: + // ParallelTxsComponent parallelTxsComponent; + // }; + // + // =========================================================================== + xdr.union("TransactionPhase", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0Components"], [1, "parallelTxsComponent"]], + arms: { + v0Components: xdr.varArray(xdr.lookup("TxSetComponent"), 2147483647), + parallelTxsComponent: xdr.lookup("ParallelTxsComponent") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionSet + // { + // Hash previousLedgerHash; + // TransactionEnvelope txs<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionSet", [["previousLedgerHash", xdr.lookup("Hash")], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionSetV1 + // { + // Hash previousLedgerHash; + // TransactionPhase phases<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionSetV1", [["previousLedgerHash", xdr.lookup("Hash")], ["phases", xdr.varArray(xdr.lookup("TransactionPhase"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union GeneralizedTransactionSet switch (int v) + // { + // // We consider the legacy TransactionSet to be v0. + // case 1: + // TransactionSetV1 v1TxSet; + // }; + // + // =========================================================================== + xdr.union("GeneralizedTransactionSet", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[1, "v1TxSet"]], + arms: { + v1TxSet: xdr.lookup("TransactionSetV1") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionResultPair + // { + // Hash transactionHash; + // TransactionResult result; // result for the transaction + // }; + // + // =========================================================================== + xdr.struct("TransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("TransactionResult")]]); + + // === xdr source ============================================================ + // + // struct TransactionResultSet + // { + // TransactionResultPair results<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionResultSet", [["results", xdr.varArray(xdr.lookup("TransactionResultPair"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // GeneralizedTransactionSet generalizedTxSet; + // } + // + // =========================================================================== + xdr.union("TransactionHistoryEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "generalizedTxSet"]], + arms: { + generalizedTxSet: xdr.lookup("GeneralizedTransactionSet") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionHistoryEntry + // { + // uint32 ledgerSeq; + // TransactionSet txSet; + // + // // when v != 0, txSet must be empty + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // GeneralizedTransactionSet generalizedTxSet; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionHistoryEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txSet", xdr.lookup("TransactionSet")], ["ext", xdr.lookup("TransactionHistoryEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionHistoryResultEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionHistoryResultEntry + // { + // uint32 ledgerSeq; + // TransactionResultSet txResultSet; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionHistoryResultEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txResultSet", xdr.lookup("TransactionResultSet")], ["ext", xdr.lookup("TransactionHistoryResultEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderHistoryEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerHeaderHistoryEntry + // { + // Hash hash; + // LedgerHeader header; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeaderHistoryEntry", [["hash", xdr.lookup("Hash")], ["header", xdr.lookup("LedgerHeader")], ["ext", xdr.lookup("LedgerHeaderHistoryEntryExt")]]); + + // === xdr source ============================================================ + // + // struct LedgerSCPMessages + // { + // uint32 ledgerSeq; + // SCPEnvelope messages<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerScpMessages", [["ledgerSeq", xdr.lookup("Uint32")], ["messages", xdr.varArray(xdr.lookup("ScpEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct SCPHistoryEntryV0 + // { + // SCPQuorumSet quorumSets<>; // additional quorum sets used by ledgerMessages + // LedgerSCPMessages ledgerMessages; + // }; + // + // =========================================================================== + xdr.struct("ScpHistoryEntryV0", [["quorumSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)], ["ledgerMessages", xdr.lookup("LedgerScpMessages")]]); + + // === xdr source ============================================================ + // + // union SCPHistoryEntry switch (int v) + // { + // case 0: + // SCPHistoryEntryV0 v0; + // }; + // + // =========================================================================== + xdr.union("ScpHistoryEntry", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("ScpHistoryEntryV0") + } + }); + + // === xdr source ============================================================ + // + // enum LedgerEntryChangeType + // { + // LEDGER_ENTRY_CREATED = 0, // entry was added to the ledger + // LEDGER_ENTRY_UPDATED = 1, // entry was modified in the ledger + // LEDGER_ENTRY_REMOVED = 2, // entry was removed from the ledger + // LEDGER_ENTRY_STATE = 3 // value of the entry + // }; + // + // =========================================================================== + xdr["enum"]("LedgerEntryChangeType", { + ledgerEntryCreated: 0, + ledgerEntryUpdated: 1, + ledgerEntryRemoved: 2, + ledgerEntryState: 3 + }); + + // === xdr source ============================================================ + // + // union LedgerEntryChange switch (LedgerEntryChangeType type) + // { + // case LEDGER_ENTRY_CREATED: + // LedgerEntry created; + // case LEDGER_ENTRY_UPDATED: + // LedgerEntry updated; + // case LEDGER_ENTRY_REMOVED: + // LedgerKey removed; + // case LEDGER_ENTRY_STATE: + // LedgerEntry state; + // }; + // + // =========================================================================== + xdr.union("LedgerEntryChange", { + switchOn: xdr.lookup("LedgerEntryChangeType"), + switchName: "type", + switches: [["ledgerEntryCreated", "created"], ["ledgerEntryUpdated", "updated"], ["ledgerEntryRemoved", "removed"], ["ledgerEntryState", "state"]], + arms: { + created: xdr.lookup("LedgerEntry"), + updated: xdr.lookup("LedgerEntry"), + removed: xdr.lookup("LedgerKey"), + state: xdr.lookup("LedgerEntry") + } + }); + + // === xdr source ============================================================ + // + // typedef LedgerEntryChange LedgerEntryChanges<>; + // + // =========================================================================== + xdr.typedef("LedgerEntryChanges", xdr.varArray(xdr.lookup("LedgerEntryChange"), 2147483647)); + + // === xdr source ============================================================ + // + // struct OperationMeta + // { + // LedgerEntryChanges changes; + // }; + // + // =========================================================================== + xdr.struct("OperationMeta", [["changes", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV1 + // { + // LedgerEntryChanges txChanges; // tx level changes if any + // OperationMeta operations<>; // meta for each operation + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV1", [["txChanges", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV2 + // { + // LedgerEntryChanges txChangesBefore; // tx level changes before operations + // // are applied if any + // OperationMeta operations<>; // meta for each operation + // LedgerEntryChanges txChangesAfter; // tx level changes after operations are + // // applied if any + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV2", [["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // enum ContractEventType + // { + // SYSTEM = 0, + // CONTRACT = 1, + // DIAGNOSTIC = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ContractEventType", { + system: 0, + contract: 1, + diagnostic: 2 + }); + + // === xdr source ============================================================ + // + // struct + // { + // SCVal topics<>; + // SCVal data; + // } + // + // =========================================================================== + xdr.struct("ContractEventV0", [["topics", xdr.varArray(xdr.lookup("ScVal"), 2147483647)], ["data", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // struct + // { + // SCVal topics<>; + // SCVal data; + // } v0; + // } + // + // =========================================================================== + xdr.union("ContractEventBody", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("ContractEventV0") + } + }); + + // === xdr source ============================================================ + // + // struct ContractEvent + // { + // // We can use this to add more fields, or because it + // // is first, to change ContractEvent into a union. + // ExtensionPoint ext; + // + // Hash* contractID; + // ContractEventType type; + // + // union switch (int v) + // { + // case 0: + // struct + // { + // SCVal topics<>; + // SCVal data; + // } v0; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("ContractEvent", [["ext", xdr.lookup("ExtensionPoint")], ["contractId", xdr.option(xdr.lookup("Hash"))], ["type", xdr.lookup("ContractEventType")], ["body", xdr.lookup("ContractEventBody")]]); + + // === xdr source ============================================================ + // + // struct DiagnosticEvent + // { + // bool inSuccessfulContractCall; + // ContractEvent event; + // }; + // + // =========================================================================== + xdr.struct("DiagnosticEvent", [["inSuccessfulContractCall", xdr.bool()], ["event", xdr.lookup("ContractEvent")]]); + + // === xdr source ============================================================ + // + // struct SorobanTransactionMetaExtV1 + // { + // ExtensionPoint ext; + // + // // The following are the components of the overall Soroban resource fee + // // charged for the transaction. + // // The following relation holds: + // // `resourceFeeCharged = totalNonRefundableResourceFeeCharged + totalRefundableResourceFeeCharged` + // // where `resourceFeeCharged` is the overall fee charged for the + // // transaction. Also, `resourceFeeCharged` <= `sorobanData.resourceFee` + // // i.e.we never charge more than the declared resource fee. + // // The inclusion fee for charged the Soroban transaction can be found using + // // the following equation: + // // `result.feeCharged = resourceFeeCharged + inclusionFeeCharged`. + // + // // Total amount (in stroops) that has been charged for non-refundable + // // Soroban resources. + // // Non-refundable resources are charged based on the usage declared in + // // the transaction envelope (such as `instructions`, `readBytes` etc.) and + // // is charged regardless of the success of the transaction. + // int64 totalNonRefundableResourceFeeCharged; + // // Total amount (in stroops) that has been charged for refundable + // // Soroban resource fees. + // // Currently this comprises the rent fee (`rentFeeCharged`) and the + // // fee for the events and return value. + // // Refundable resources are charged based on the actual resources usage. + // // Since currently refundable resources are only used for the successful + // // transactions, this will be `0` for failed transactions. + // int64 totalRefundableResourceFeeCharged; + // // Amount (in stroops) that has been charged for rent. + // // This is a part of `totalNonRefundableResourceFeeCharged`. + // int64 rentFeeCharged; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionMetaExtV1", [["ext", xdr.lookup("ExtensionPoint")], ["totalNonRefundableResourceFeeCharged", xdr.lookup("Int64")], ["totalRefundableResourceFeeCharged", xdr.lookup("Int64")], ["rentFeeCharged", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union SorobanTransactionMetaExt switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionMetaExtV1 v1; + // }; + // + // =========================================================================== + xdr.union("SorobanTransactionMetaExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("SorobanTransactionMetaExtV1") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanTransactionMeta + // { + // SorobanTransactionMetaExt ext; + // + // ContractEvent events<>; // custom events populated by the + // // contracts themselves. + // SCVal returnValue; // return value of the host fn invocation + // + // // Diagnostics events that are not hashed. + // // This will contain all contract and diagnostic events. Even ones + // // that were emitted in a failed contract call. + // DiagnosticEvent diagnosticEvents<>; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionMeta", [["ext", xdr.lookup("SorobanTransactionMetaExt")], ["events", xdr.varArray(xdr.lookup("ContractEvent"), 2147483647)], ["returnValue", xdr.lookup("ScVal")], ["diagnosticEvents", xdr.varArray(xdr.lookup("DiagnosticEvent"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV3 + // { + // ExtensionPoint ext; + // + // LedgerEntryChanges txChangesBefore; // tx level changes before operations + // // are applied if any + // OperationMeta operations<>; // meta for each operation + // LedgerEntryChanges txChangesAfter; // tx level changes after operations are + // // applied if any + // SorobanTransactionMeta* sorobanMeta; // Soroban-specific meta (only for + // // Soroban transactions). + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV3", [["ext", xdr.lookup("ExtensionPoint")], ["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")], ["sorobanMeta", xdr.option(xdr.lookup("SorobanTransactionMeta"))]]); + + // === xdr source ============================================================ + // + // struct InvokeHostFunctionSuccessPreImage + // { + // SCVal returnValue; + // ContractEvent events<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeHostFunctionSuccessPreImage", [["returnValue", xdr.lookup("ScVal")], ["events", xdr.varArray(xdr.lookup("ContractEvent"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union TransactionMeta switch (int v) + // { + // case 0: + // OperationMeta operations<>; + // case 1: + // TransactionMetaV1 v1; + // case 2: + // TransactionMetaV2 v2; + // case 3: + // TransactionMetaV3 v3; + // }; + // + // =========================================================================== + xdr.union("TransactionMeta", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "operations"], [1, "v1"], [2, "v2"], [3, "v3"]], + arms: { + operations: xdr.varArray(xdr.lookup("OperationMeta"), 2147483647), + v1: xdr.lookup("TransactionMetaV1"), + v2: xdr.lookup("TransactionMetaV2"), + v3: xdr.lookup("TransactionMetaV3") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionResultMeta + // { + // TransactionResultPair result; + // LedgerEntryChanges feeProcessing; + // TransactionMeta txApplyProcessing; + // }; + // + // =========================================================================== + xdr.struct("TransactionResultMeta", [["result", xdr.lookup("TransactionResultPair")], ["feeProcessing", xdr.lookup("LedgerEntryChanges")], ["txApplyProcessing", xdr.lookup("TransactionMeta")]]); + + // === xdr source ============================================================ + // + // struct UpgradeEntryMeta + // { + // LedgerUpgrade upgrade; + // LedgerEntryChanges changes; + // }; + // + // =========================================================================== + xdr.struct("UpgradeEntryMeta", [["upgrade", xdr.lookup("LedgerUpgrade")], ["changes", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaV0 + // { + // LedgerHeaderHistoryEntry ledgerHeader; + // // NB: txSet is sorted in "Hash order" + // TransactionSet txSet; + // + // // NB: transactions are sorted in apply order here + // // fees for all transactions are processed first + // // followed by applying transactions + // TransactionResultMeta txProcessing<>; + // + // // upgrades are applied last + // UpgradeEntryMeta upgradesProcessing<>; + // + // // other misc information attached to the ledger close + // SCPHistoryEntry scpInfo<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaV0", [["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("TransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaExtV1 + // { + // ExtensionPoint ext; + // int64 sorobanFeeWrite1KB; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaExtV1", [["ext", xdr.lookup("ExtensionPoint")], ["sorobanFeeWrite1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union LedgerCloseMetaExt switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerCloseMetaExtV1 v1; + // }; + // + // =========================================================================== + xdr.union("LedgerCloseMetaExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerCloseMetaExtV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaV1 + // { + // LedgerCloseMetaExt ext; + // + // LedgerHeaderHistoryEntry ledgerHeader; + // + // GeneralizedTransactionSet txSet; + // + // // NB: transactions are sorted in apply order here + // // fees for all transactions are processed first + // // followed by applying transactions + // TransactionResultMeta txProcessing<>; + // + // // upgrades are applied last + // UpgradeEntryMeta upgradesProcessing<>; + // + // // other misc information attached to the ledger close + // SCPHistoryEntry scpInfo<>; + // + // // Size in bytes of BucketList, to support downstream + // // systems calculating storage fees correctly. + // uint64 totalByteSizeOfBucketList; + // + // // Temp keys that are being evicted at this ledger. + // LedgerKey evictedTemporaryLedgerKeys<>; + // + // // Archived restorable ledger entries that are being + // // evicted at this ledger. + // LedgerEntry evictedPersistentLedgerEntries<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaV1", [["ext", xdr.lookup("LedgerCloseMetaExt")], ["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("GeneralizedTransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)], ["totalByteSizeOfBucketList", xdr.lookup("Uint64")], ["evictedTemporaryLedgerKeys", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["evictedPersistentLedgerEntries", xdr.varArray(xdr.lookup("LedgerEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union LedgerCloseMeta switch (int v) + // { + // case 0: + // LedgerCloseMetaV0 v0; + // case 1: + // LedgerCloseMetaV1 v1; + // }; + // + // =========================================================================== + xdr.union("LedgerCloseMeta", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"], [1, "v1"]], + arms: { + v0: xdr.lookup("LedgerCloseMetaV0"), + v1: xdr.lookup("LedgerCloseMetaV1") + } + }); + + // === xdr source ============================================================ + // + // enum ErrorCode + // { + // ERR_MISC = 0, // Unspecific error + // ERR_DATA = 1, // Malformed data + // ERR_CONF = 2, // Misconfiguration error + // ERR_AUTH = 3, // Authentication failure + // ERR_LOAD = 4 // System overloaded + // }; + // + // =========================================================================== + xdr["enum"]("ErrorCode", { + errMisc: 0, + errData: 1, + errConf: 2, + errAuth: 3, + errLoad: 4 + }); + + // === xdr source ============================================================ + // + // struct Error + // { + // ErrorCode code; + // string msg<100>; + // }; + // + // =========================================================================== + xdr.struct("Error", [["code", xdr.lookup("ErrorCode")], ["msg", xdr.string(100)]]); + + // === xdr source ============================================================ + // + // struct SendMore + // { + // uint32 numMessages; + // }; + // + // =========================================================================== + xdr.struct("SendMore", [["numMessages", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SendMoreExtended + // { + // uint32 numMessages; + // uint32 numBytes; + // }; + // + // =========================================================================== + xdr.struct("SendMoreExtended", [["numMessages", xdr.lookup("Uint32")], ["numBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct AuthCert + // { + // Curve25519Public pubkey; + // uint64 expiration; + // Signature sig; + // }; + // + // =========================================================================== + xdr.struct("AuthCert", [["pubkey", xdr.lookup("Curve25519Public")], ["expiration", xdr.lookup("Uint64")], ["sig", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // struct Hello + // { + // uint32 ledgerVersion; + // uint32 overlayVersion; + // uint32 overlayMinVersion; + // Hash networkID; + // string versionStr<100>; + // int listeningPort; + // NodeID peerID; + // AuthCert cert; + // uint256 nonce; + // }; + // + // =========================================================================== + xdr.struct("Hello", [["ledgerVersion", xdr.lookup("Uint32")], ["overlayVersion", xdr.lookup("Uint32")], ["overlayMinVersion", xdr.lookup("Uint32")], ["networkId", xdr.lookup("Hash")], ["versionStr", xdr.string(100)], ["listeningPort", xdr["int"]()], ["peerId", xdr.lookup("NodeId")], ["cert", xdr.lookup("AuthCert")], ["nonce", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // const AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED = 200; + // + // =========================================================================== + xdr["const"]("AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED", 200); + + // === xdr source ============================================================ + // + // struct Auth + // { + // int flags; + // }; + // + // =========================================================================== + xdr.struct("Auth", [["flags", xdr["int"]()]]); + + // === xdr source ============================================================ + // + // enum IPAddrType + // { + // IPv4 = 0, + // IPv6 = 1 + // }; + // + // =========================================================================== + xdr["enum"]("IpAddrType", { + iPv4: 0, + iPv6: 1 + }); + + // === xdr source ============================================================ + // + // union switch (IPAddrType type) + // { + // case IPv4: + // opaque ipv4[4]; + // case IPv6: + // opaque ipv6[16]; + // } + // + // =========================================================================== + xdr.union("PeerAddressIp", { + switchOn: xdr.lookup("IpAddrType"), + switchName: "type", + switches: [["iPv4", "ipv4"], ["iPv6", "ipv6"]], + arms: { + ipv4: xdr.opaque(4), + ipv6: xdr.opaque(16) + } + }); + + // === xdr source ============================================================ + // + // struct PeerAddress + // { + // union switch (IPAddrType type) + // { + // case IPv4: + // opaque ipv4[4]; + // case IPv6: + // opaque ipv6[16]; + // } + // ip; + // uint32 port; + // uint32 numFailures; + // }; + // + // =========================================================================== + xdr.struct("PeerAddress", [["ip", xdr.lookup("PeerAddressIp")], ["port", xdr.lookup("Uint32")], ["numFailures", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // enum MessageType + // { + // ERROR_MSG = 0, + // AUTH = 2, + // DONT_HAVE = 3, + // + // GET_PEERS = 4, // gets a list of peers this guy knows about + // PEERS = 5, + // + // GET_TX_SET = 6, // gets a particular txset by hash + // TX_SET = 7, + // GENERALIZED_TX_SET = 17, + // + // TRANSACTION = 8, // pass on a tx you have heard about + // + // // SCP + // GET_SCP_QUORUMSET = 9, + // SCP_QUORUMSET = 10, + // SCP_MESSAGE = 11, + // GET_SCP_STATE = 12, + // + // // new messages + // HELLO = 13, + // + // SURVEY_REQUEST = 14, + // SURVEY_RESPONSE = 15, + // + // SEND_MORE = 16, + // SEND_MORE_EXTENDED = 20, + // + // FLOOD_ADVERT = 18, + // FLOOD_DEMAND = 19, + // + // TIME_SLICED_SURVEY_REQUEST = 21, + // TIME_SLICED_SURVEY_RESPONSE = 22, + // TIME_SLICED_SURVEY_START_COLLECTING = 23, + // TIME_SLICED_SURVEY_STOP_COLLECTING = 24 + // }; + // + // =========================================================================== + xdr["enum"]("MessageType", { + errorMsg: 0, + auth: 2, + dontHave: 3, + getPeers: 4, + peers: 5, + getTxSet: 6, + txSet: 7, + generalizedTxSet: 17, + transaction: 8, + getScpQuorumset: 9, + scpQuorumset: 10, + scpMessage: 11, + getScpState: 12, + hello: 13, + surveyRequest: 14, + surveyResponse: 15, + sendMore: 16, + sendMoreExtended: 20, + floodAdvert: 18, + floodDemand: 19, + timeSlicedSurveyRequest: 21, + timeSlicedSurveyResponse: 22, + timeSlicedSurveyStartCollecting: 23, + timeSlicedSurveyStopCollecting: 24 + }); + + // === xdr source ============================================================ + // + // struct DontHave + // { + // MessageType type; + // uint256 reqHash; + // }; + // + // =========================================================================== + xdr.struct("DontHave", [["type", xdr.lookup("MessageType")], ["reqHash", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // enum SurveyMessageCommandType + // { + // SURVEY_TOPOLOGY = 0, + // TIME_SLICED_SURVEY_TOPOLOGY = 1 + // }; + // + // =========================================================================== + xdr["enum"]("SurveyMessageCommandType", { + surveyTopology: 0, + timeSlicedSurveyTopology: 1 + }); + + // === xdr source ============================================================ + // + // enum SurveyMessageResponseType + // { + // SURVEY_TOPOLOGY_RESPONSE_V0 = 0, + // SURVEY_TOPOLOGY_RESPONSE_V1 = 1, + // SURVEY_TOPOLOGY_RESPONSE_V2 = 2 + // }; + // + // =========================================================================== + xdr["enum"]("SurveyMessageResponseType", { + surveyTopologyResponseV0: 0, + surveyTopologyResponseV1: 1, + surveyTopologyResponseV2: 2 + }); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyStartCollectingMessage + // { + // NodeID surveyorID; + // uint32 nonce; + // uint32 ledgerNum; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyStartCollectingMessage", [["surveyorId", xdr.lookup("NodeId")], ["nonce", xdr.lookup("Uint32")], ["ledgerNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyStartCollectingMessage + // { + // Signature signature; + // TimeSlicedSurveyStartCollectingMessage startCollecting; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyStartCollectingMessage", [["signature", xdr.lookup("Signature")], ["startCollecting", xdr.lookup("TimeSlicedSurveyStartCollectingMessage")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyStopCollectingMessage + // { + // NodeID surveyorID; + // uint32 nonce; + // uint32 ledgerNum; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyStopCollectingMessage", [["surveyorId", xdr.lookup("NodeId")], ["nonce", xdr.lookup("Uint32")], ["ledgerNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyStopCollectingMessage + // { + // Signature signature; + // TimeSlicedSurveyStopCollectingMessage stopCollecting; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyStopCollectingMessage", [["signature", xdr.lookup("Signature")], ["stopCollecting", xdr.lookup("TimeSlicedSurveyStopCollectingMessage")]]); + + // === xdr source ============================================================ + // + // struct SurveyRequestMessage + // { + // NodeID surveyorPeerID; + // NodeID surveyedPeerID; + // uint32 ledgerNum; + // Curve25519Public encryptionKey; + // SurveyMessageCommandType commandType; + // }; + // + // =========================================================================== + xdr.struct("SurveyRequestMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["encryptionKey", xdr.lookup("Curve25519Public")], ["commandType", xdr.lookup("SurveyMessageCommandType")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyRequestMessage + // { + // SurveyRequestMessage request; + // uint32 nonce; + // uint32 inboundPeersIndex; + // uint32 outboundPeersIndex; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyRequestMessage", [["request", xdr.lookup("SurveyRequestMessage")], ["nonce", xdr.lookup("Uint32")], ["inboundPeersIndex", xdr.lookup("Uint32")], ["outboundPeersIndex", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedSurveyRequestMessage + // { + // Signature requestSignature; + // SurveyRequestMessage request; + // }; + // + // =========================================================================== + xdr.struct("SignedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("SurveyRequestMessage")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyRequestMessage + // { + // Signature requestSignature; + // TimeSlicedSurveyRequestMessage request; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("TimeSlicedSurveyRequestMessage")]]); + + // === xdr source ============================================================ + // + // typedef opaque EncryptedBody<64000>; + // + // =========================================================================== + xdr.typedef("EncryptedBody", xdr.varOpaque(64000)); + + // === xdr source ============================================================ + // + // struct SurveyResponseMessage + // { + // NodeID surveyorPeerID; + // NodeID surveyedPeerID; + // uint32 ledgerNum; + // SurveyMessageCommandType commandType; + // EncryptedBody encryptedBody; + // }; + // + // =========================================================================== + xdr.struct("SurveyResponseMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["commandType", xdr.lookup("SurveyMessageCommandType")], ["encryptedBody", xdr.lookup("EncryptedBody")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyResponseMessage + // { + // SurveyResponseMessage response; + // uint32 nonce; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyResponseMessage", [["response", xdr.lookup("SurveyResponseMessage")], ["nonce", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedSurveyResponseMessage + // { + // Signature responseSignature; + // SurveyResponseMessage response; + // }; + // + // =========================================================================== + xdr.struct("SignedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("SurveyResponseMessage")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyResponseMessage + // { + // Signature responseSignature; + // TimeSlicedSurveyResponseMessage response; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("TimeSlicedSurveyResponseMessage")]]); + + // === xdr source ============================================================ + // + // struct PeerStats + // { + // NodeID id; + // string versionStr<100>; + // uint64 messagesRead; + // uint64 messagesWritten; + // uint64 bytesRead; + // uint64 bytesWritten; + // uint64 secondsConnected; + // + // uint64 uniqueFloodBytesRecv; + // uint64 duplicateFloodBytesRecv; + // uint64 uniqueFetchBytesRecv; + // uint64 duplicateFetchBytesRecv; + // + // uint64 uniqueFloodMessageRecv; + // uint64 duplicateFloodMessageRecv; + // uint64 uniqueFetchMessageRecv; + // uint64 duplicateFetchMessageRecv; + // }; + // + // =========================================================================== + xdr.struct("PeerStats", [["id", xdr.lookup("NodeId")], ["versionStr", xdr.string(100)], ["messagesRead", xdr.lookup("Uint64")], ["messagesWritten", xdr.lookup("Uint64")], ["bytesRead", xdr.lookup("Uint64")], ["bytesWritten", xdr.lookup("Uint64")], ["secondsConnected", xdr.lookup("Uint64")], ["uniqueFloodBytesRecv", xdr.lookup("Uint64")], ["duplicateFloodBytesRecv", xdr.lookup("Uint64")], ["uniqueFetchBytesRecv", xdr.lookup("Uint64")], ["duplicateFetchBytesRecv", xdr.lookup("Uint64")], ["uniqueFloodMessageRecv", xdr.lookup("Uint64")], ["duplicateFloodMessageRecv", xdr.lookup("Uint64")], ["uniqueFetchMessageRecv", xdr.lookup("Uint64")], ["duplicateFetchMessageRecv", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // typedef PeerStats PeerStatList<25>; + // + // =========================================================================== + xdr.typedef("PeerStatList", xdr.varArray(xdr.lookup("PeerStats"), 25)); + + // === xdr source ============================================================ + // + // struct TimeSlicedNodeData + // { + // uint32 addedAuthenticatedPeers; + // uint32 droppedAuthenticatedPeers; + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // + // // SCP stats + // uint32 p75SCPFirstToSelfLatencyMs; + // uint32 p75SCPSelfToOtherLatencyMs; + // + // // How many times the node lost sync in the time slice + // uint32 lostSyncCount; + // + // // Config data + // bool isValidator; + // uint32 maxInboundPeerCount; + // uint32 maxOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedNodeData", [["addedAuthenticatedPeers", xdr.lookup("Uint32")], ["droppedAuthenticatedPeers", xdr.lookup("Uint32")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")], ["p75ScpFirstToSelfLatencyMs", xdr.lookup("Uint32")], ["p75ScpSelfToOtherLatencyMs", xdr.lookup("Uint32")], ["lostSyncCount", xdr.lookup("Uint32")], ["isValidator", xdr.bool()], ["maxInboundPeerCount", xdr.lookup("Uint32")], ["maxOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedPeerData + // { + // PeerStats peerStats; + // uint32 averageLatencyMs; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedPeerData", [["peerStats", xdr.lookup("PeerStats")], ["averageLatencyMs", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // typedef TimeSlicedPeerData TimeSlicedPeerDataList<25>; + // + // =========================================================================== + xdr.typedef("TimeSlicedPeerDataList", xdr.varArray(xdr.lookup("TimeSlicedPeerData"), 25)); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV0 + // { + // PeerStatList inboundPeers; + // PeerStatList outboundPeers; + // + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV0", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV1 + // { + // PeerStatList inboundPeers; + // PeerStatList outboundPeers; + // + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // + // uint32 maxInboundPeerCount; + // uint32 maxOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV1", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")], ["maxInboundPeerCount", xdr.lookup("Uint32")], ["maxOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV2 + // { + // TimeSlicedPeerDataList inboundPeers; + // TimeSlicedPeerDataList outboundPeers; + // TimeSlicedNodeData nodeData; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV2", [["inboundPeers", xdr.lookup("TimeSlicedPeerDataList")], ["outboundPeers", xdr.lookup("TimeSlicedPeerDataList")], ["nodeData", xdr.lookup("TimeSlicedNodeData")]]); + + // === xdr source ============================================================ + // + // union SurveyResponseBody switch (SurveyMessageResponseType type) + // { + // case SURVEY_TOPOLOGY_RESPONSE_V0: + // TopologyResponseBodyV0 topologyResponseBodyV0; + // case SURVEY_TOPOLOGY_RESPONSE_V1: + // TopologyResponseBodyV1 topologyResponseBodyV1; + // case SURVEY_TOPOLOGY_RESPONSE_V2: + // TopologyResponseBodyV2 topologyResponseBodyV2; + // }; + // + // =========================================================================== + xdr.union("SurveyResponseBody", { + switchOn: xdr.lookup("SurveyMessageResponseType"), + switchName: "type", + switches: [["surveyTopologyResponseV0", "topologyResponseBodyV0"], ["surveyTopologyResponseV1", "topologyResponseBodyV1"], ["surveyTopologyResponseV2", "topologyResponseBodyV2"]], + arms: { + topologyResponseBodyV0: xdr.lookup("TopologyResponseBodyV0"), + topologyResponseBodyV1: xdr.lookup("TopologyResponseBodyV1"), + topologyResponseBodyV2: xdr.lookup("TopologyResponseBodyV2") + } + }); + + // === xdr source ============================================================ + // + // const TX_ADVERT_VECTOR_MAX_SIZE = 1000; + // + // =========================================================================== + xdr["const"]("TX_ADVERT_VECTOR_MAX_SIZE", 1000); + + // === xdr source ============================================================ + // + // typedef Hash TxAdvertVector; + // + // =========================================================================== + xdr.typedef("TxAdvertVector", xdr.varArray(xdr.lookup("Hash"), xdr.lookup("TX_ADVERT_VECTOR_MAX_SIZE"))); + + // === xdr source ============================================================ + // + // struct FloodAdvert + // { + // TxAdvertVector txHashes; + // }; + // + // =========================================================================== + xdr.struct("FloodAdvert", [["txHashes", xdr.lookup("TxAdvertVector")]]); + + // === xdr source ============================================================ + // + // const TX_DEMAND_VECTOR_MAX_SIZE = 1000; + // + // =========================================================================== + xdr["const"]("TX_DEMAND_VECTOR_MAX_SIZE", 1000); + + // === xdr source ============================================================ + // + // typedef Hash TxDemandVector; + // + // =========================================================================== + xdr.typedef("TxDemandVector", xdr.varArray(xdr.lookup("Hash"), xdr.lookup("TX_DEMAND_VECTOR_MAX_SIZE"))); + + // === xdr source ============================================================ + // + // struct FloodDemand + // { + // TxDemandVector txHashes; + // }; + // + // =========================================================================== + xdr.struct("FloodDemand", [["txHashes", xdr.lookup("TxDemandVector")]]); + + // === xdr source ============================================================ + // + // union StellarMessage switch (MessageType type) + // { + // case ERROR_MSG: + // Error error; + // case HELLO: + // Hello hello; + // case AUTH: + // Auth auth; + // case DONT_HAVE: + // DontHave dontHave; + // case GET_PEERS: + // void; + // case PEERS: + // PeerAddress peers<100>; + // + // case GET_TX_SET: + // uint256 txSetHash; + // case TX_SET: + // TransactionSet txSet; + // case GENERALIZED_TX_SET: + // GeneralizedTransactionSet generalizedTxSet; + // + // case TRANSACTION: + // TransactionEnvelope transaction; + // + // case SURVEY_REQUEST: + // SignedSurveyRequestMessage signedSurveyRequestMessage; + // + // case SURVEY_RESPONSE: + // SignedSurveyResponseMessage signedSurveyResponseMessage; + // + // case TIME_SLICED_SURVEY_REQUEST: + // SignedTimeSlicedSurveyRequestMessage signedTimeSlicedSurveyRequestMessage; + // + // case TIME_SLICED_SURVEY_RESPONSE: + // SignedTimeSlicedSurveyResponseMessage signedTimeSlicedSurveyResponseMessage; + // + // case TIME_SLICED_SURVEY_START_COLLECTING: + // SignedTimeSlicedSurveyStartCollectingMessage + // signedTimeSlicedSurveyStartCollectingMessage; + // + // case TIME_SLICED_SURVEY_STOP_COLLECTING: + // SignedTimeSlicedSurveyStopCollectingMessage + // signedTimeSlicedSurveyStopCollectingMessage; + // + // // SCP + // case GET_SCP_QUORUMSET: + // uint256 qSetHash; + // case SCP_QUORUMSET: + // SCPQuorumSet qSet; + // case SCP_MESSAGE: + // SCPEnvelope envelope; + // case GET_SCP_STATE: + // uint32 getSCPLedgerSeq; // ledger seq requested ; if 0, requests the latest + // case SEND_MORE: + // SendMore sendMoreMessage; + // case SEND_MORE_EXTENDED: + // SendMoreExtended sendMoreExtendedMessage; + // // Pull mode + // case FLOOD_ADVERT: + // FloodAdvert floodAdvert; + // case FLOOD_DEMAND: + // FloodDemand floodDemand; + // }; + // + // =========================================================================== + xdr.union("StellarMessage", { + switchOn: xdr.lookup("MessageType"), + switchName: "type", + switches: [["errorMsg", "error"], ["hello", "hello"], ["auth", "auth"], ["dontHave", "dontHave"], ["getPeers", xdr["void"]()], ["peers", "peers"], ["getTxSet", "txSetHash"], ["txSet", "txSet"], ["generalizedTxSet", "generalizedTxSet"], ["transaction", "transaction"], ["surveyRequest", "signedSurveyRequestMessage"], ["surveyResponse", "signedSurveyResponseMessage"], ["timeSlicedSurveyRequest", "signedTimeSlicedSurveyRequestMessage"], ["timeSlicedSurveyResponse", "signedTimeSlicedSurveyResponseMessage"], ["timeSlicedSurveyStartCollecting", "signedTimeSlicedSurveyStartCollectingMessage"], ["timeSlicedSurveyStopCollecting", "signedTimeSlicedSurveyStopCollectingMessage"], ["getScpQuorumset", "qSetHash"], ["scpQuorumset", "qSet"], ["scpMessage", "envelope"], ["getScpState", "getScpLedgerSeq"], ["sendMore", "sendMoreMessage"], ["sendMoreExtended", "sendMoreExtendedMessage"], ["floodAdvert", "floodAdvert"], ["floodDemand", "floodDemand"]], + arms: { + error: xdr.lookup("Error"), + hello: xdr.lookup("Hello"), + auth: xdr.lookup("Auth"), + dontHave: xdr.lookup("DontHave"), + peers: xdr.varArray(xdr.lookup("PeerAddress"), 100), + txSetHash: xdr.lookup("Uint256"), + txSet: xdr.lookup("TransactionSet"), + generalizedTxSet: xdr.lookup("GeneralizedTransactionSet"), + transaction: xdr.lookup("TransactionEnvelope"), + signedSurveyRequestMessage: xdr.lookup("SignedSurveyRequestMessage"), + signedSurveyResponseMessage: xdr.lookup("SignedSurveyResponseMessage"), + signedTimeSlicedSurveyRequestMessage: xdr.lookup("SignedTimeSlicedSurveyRequestMessage"), + signedTimeSlicedSurveyResponseMessage: xdr.lookup("SignedTimeSlicedSurveyResponseMessage"), + signedTimeSlicedSurveyStartCollectingMessage: xdr.lookup("SignedTimeSlicedSurveyStartCollectingMessage"), + signedTimeSlicedSurveyStopCollectingMessage: xdr.lookup("SignedTimeSlicedSurveyStopCollectingMessage"), + qSetHash: xdr.lookup("Uint256"), + qSet: xdr.lookup("ScpQuorumSet"), + envelope: xdr.lookup("ScpEnvelope"), + getScpLedgerSeq: xdr.lookup("Uint32"), + sendMoreMessage: xdr.lookup("SendMore"), + sendMoreExtendedMessage: xdr.lookup("SendMoreExtended"), + floodAdvert: xdr.lookup("FloodAdvert"), + floodDemand: xdr.lookup("FloodDemand") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // uint64 sequence; + // StellarMessage message; + // HmacSha256Mac mac; + // } + // + // =========================================================================== + xdr.struct("AuthenticatedMessageV0", [["sequence", xdr.lookup("Uint64")], ["message", xdr.lookup("StellarMessage")], ["mac", xdr.lookup("HmacSha256Mac")]]); + + // === xdr source ============================================================ + // + // union AuthenticatedMessage switch (uint32 v) + // { + // case 0: + // struct + // { + // uint64 sequence; + // StellarMessage message; + // HmacSha256Mac mac; + // } v0; + // }; + // + // =========================================================================== + xdr.union("AuthenticatedMessage", { + switchOn: xdr.lookup("Uint32"), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("AuthenticatedMessageV0") + } + }); + + // === xdr source ============================================================ + // + // const MAX_OPS_PER_TX = 100; + // + // =========================================================================== + xdr["const"]("MAX_OPS_PER_TX", 100); + + // === xdr source ============================================================ + // + // union LiquidityPoolParameters switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // LiquidityPoolConstantProductParameters constantProduct; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolParameters", { + switchOn: xdr.lookup("LiquidityPoolType"), + switchName: "type", + switches: [["liquidityPoolConstantProduct", "constantProduct"]], + arms: { + constantProduct: xdr.lookup("LiquidityPoolConstantProductParameters") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // uint64 id; + // uint256 ed25519; + // } + // + // =========================================================================== + xdr.struct("MuxedAccountMed25519", [["id", xdr.lookup("Uint64")], ["ed25519", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // union MuxedAccount switch (CryptoKeyType type) + // { + // case KEY_TYPE_ED25519: + // uint256 ed25519; + // case KEY_TYPE_MUXED_ED25519: + // struct + // { + // uint64 id; + // uint256 ed25519; + // } med25519; + // }; + // + // =========================================================================== + xdr.union("MuxedAccount", { + switchOn: xdr.lookup("CryptoKeyType"), + switchName: "type", + switches: [["keyTypeEd25519", "ed25519"], ["keyTypeMuxedEd25519", "med25519"]], + arms: { + ed25519: xdr.lookup("Uint256"), + med25519: xdr.lookup("MuxedAccountMed25519") + } + }); + + // === xdr source ============================================================ + // + // struct DecoratedSignature + // { + // SignatureHint hint; // last 4 bytes of the public key, used as a hint + // Signature signature; // actual signature + // }; + // + // =========================================================================== + xdr.struct("DecoratedSignature", [["hint", xdr.lookup("SignatureHint")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // enum OperationType + // { + // CREATE_ACCOUNT = 0, + // PAYMENT = 1, + // PATH_PAYMENT_STRICT_RECEIVE = 2, + // MANAGE_SELL_OFFER = 3, + // CREATE_PASSIVE_SELL_OFFER = 4, + // SET_OPTIONS = 5, + // CHANGE_TRUST = 6, + // ALLOW_TRUST = 7, + // ACCOUNT_MERGE = 8, + // INFLATION = 9, + // MANAGE_DATA = 10, + // BUMP_SEQUENCE = 11, + // MANAGE_BUY_OFFER = 12, + // PATH_PAYMENT_STRICT_SEND = 13, + // CREATE_CLAIMABLE_BALANCE = 14, + // CLAIM_CLAIMABLE_BALANCE = 15, + // BEGIN_SPONSORING_FUTURE_RESERVES = 16, + // END_SPONSORING_FUTURE_RESERVES = 17, + // REVOKE_SPONSORSHIP = 18, + // CLAWBACK = 19, + // CLAWBACK_CLAIMABLE_BALANCE = 20, + // SET_TRUST_LINE_FLAGS = 21, + // LIQUIDITY_POOL_DEPOSIT = 22, + // LIQUIDITY_POOL_WITHDRAW = 23, + // INVOKE_HOST_FUNCTION = 24, + // EXTEND_FOOTPRINT_TTL = 25, + // RESTORE_FOOTPRINT = 26 + // }; + // + // =========================================================================== + xdr["enum"]("OperationType", { + createAccount: 0, + payment: 1, + pathPaymentStrictReceive: 2, + manageSellOffer: 3, + createPassiveSellOffer: 4, + setOptions: 5, + changeTrust: 6, + allowTrust: 7, + accountMerge: 8, + inflation: 9, + manageData: 10, + bumpSequence: 11, + manageBuyOffer: 12, + pathPaymentStrictSend: 13, + createClaimableBalance: 14, + claimClaimableBalance: 15, + beginSponsoringFutureReserves: 16, + endSponsoringFutureReserves: 17, + revokeSponsorship: 18, + clawback: 19, + clawbackClaimableBalance: 20, + setTrustLineFlags: 21, + liquidityPoolDeposit: 22, + liquidityPoolWithdraw: 23, + invokeHostFunction: 24, + extendFootprintTtl: 25, + restoreFootprint: 26 + }); + + // === xdr source ============================================================ + // + // struct CreateAccountOp + // { + // AccountID destination; // account to create + // int64 startingBalance; // amount they end up with + // }; + // + // =========================================================================== + xdr.struct("CreateAccountOp", [["destination", xdr.lookup("AccountId")], ["startingBalance", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct PaymentOp + // { + // MuxedAccount destination; // recipient of the payment + // Asset asset; // what they end up with + // int64 amount; // amount they end up with + // }; + // + // =========================================================================== + xdr.struct("PaymentOp", [["destination", xdr.lookup("MuxedAccount")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct PathPaymentStrictReceiveOp + // { + // Asset sendAsset; // asset we pay with + // int64 sendMax; // the maximum amount of sendAsset to + // // send (excluding fees). + // // The operation will fail if can't be met + // + // MuxedAccount destination; // recipient of the payment + // Asset destAsset; // what they end up with + // int64 destAmount; // amount they end up with + // + // Asset path<5>; // additional hops it must go through to get there + // }; + // + // =========================================================================== + xdr.struct("PathPaymentStrictReceiveOp", [["sendAsset", xdr.lookup("Asset")], ["sendMax", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destAmount", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]); + + // === xdr source ============================================================ + // + // struct PathPaymentStrictSendOp + // { + // Asset sendAsset; // asset we pay with + // int64 sendAmount; // amount of sendAsset to send (excluding fees) + // + // MuxedAccount destination; // recipient of the payment + // Asset destAsset; // what they end up with + // int64 destMin; // the minimum amount of dest asset to + // // be received + // // The operation will fail if it can't be met + // + // Asset path<5>; // additional hops it must go through to get there + // }; + // + // =========================================================================== + xdr.struct("PathPaymentStrictSendOp", [["sendAsset", xdr.lookup("Asset")], ["sendAmount", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destMin", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]); + + // === xdr source ============================================================ + // + // struct ManageSellOfferOp + // { + // Asset selling; + // Asset buying; + // int64 amount; // amount being sold. if set to 0, delete the offer + // Price price; // price of thing being sold in terms of what you are buying + // + // // 0=create a new offer, otherwise edit an existing offer + // int64 offerID; + // }; + // + // =========================================================================== + xdr.struct("ManageSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ManageBuyOfferOp + // { + // Asset selling; + // Asset buying; + // int64 buyAmount; // amount being bought. if set to 0, delete the offer + // Price price; // price of thing being bought in terms of what you are + // // selling + // + // // 0=create a new offer, otherwise edit an existing offer + // int64 offerID; + // }; + // + // =========================================================================== + xdr.struct("ManageBuyOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["buyAmount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct CreatePassiveSellOfferOp + // { + // Asset selling; // A + // Asset buying; // B + // int64 amount; // amount taker gets + // Price price; // cost of A in terms of B + // }; + // + // =========================================================================== + xdr.struct("CreatePassiveSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")]]); + + // === xdr source ============================================================ + // + // struct SetOptionsOp + // { + // AccountID* inflationDest; // sets the inflation destination + // + // uint32* clearFlags; // which flags to clear + // uint32* setFlags; // which flags to set + // + // // account threshold manipulation + // uint32* masterWeight; // weight of the master account + // uint32* lowThreshold; + // uint32* medThreshold; + // uint32* highThreshold; + // + // string32* homeDomain; // sets the home domain + // + // // Add, update or remove a signer for the account + // // signer is deleted if the weight is 0 + // Signer* signer; + // }; + // + // =========================================================================== + xdr.struct("SetOptionsOp", [["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["clearFlags", xdr.option(xdr.lookup("Uint32"))], ["setFlags", xdr.option(xdr.lookup("Uint32"))], ["masterWeight", xdr.option(xdr.lookup("Uint32"))], ["lowThreshold", xdr.option(xdr.lookup("Uint32"))], ["medThreshold", xdr.option(xdr.lookup("Uint32"))], ["highThreshold", xdr.option(xdr.lookup("Uint32"))], ["homeDomain", xdr.option(xdr.lookup("String32"))], ["signer", xdr.option(xdr.lookup("Signer"))]]); + + // === xdr source ============================================================ + // + // union ChangeTrustAsset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // case ASSET_TYPE_POOL_SHARE: + // LiquidityPoolParameters liquidityPool; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("ChangeTrustAsset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPool"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12"), + liquidityPool: xdr.lookup("LiquidityPoolParameters") + } + }); + + // === xdr source ============================================================ + // + // struct ChangeTrustOp + // { + // ChangeTrustAsset line; + // + // // if limit is set to 0, deletes the trust line + // int64 limit; + // }; + // + // =========================================================================== + xdr.struct("ChangeTrustOp", [["line", xdr.lookup("ChangeTrustAsset")], ["limit", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct AllowTrustOp + // { + // AccountID trustor; + // AssetCode asset; + // + // // One of 0, AUTHORIZED_FLAG, or AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG + // uint32 authorize; + // }; + // + // =========================================================================== + xdr.struct("AllowTrustOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("AssetCode")], ["authorize", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ManageDataOp + // { + // string64 dataName; + // DataValue* dataValue; // set to null to clear + // }; + // + // =========================================================================== + xdr.struct("ManageDataOp", [["dataName", xdr.lookup("String64")], ["dataValue", xdr.option(xdr.lookup("DataValue"))]]); + + // === xdr source ============================================================ + // + // struct BumpSequenceOp + // { + // SequenceNumber bumpTo; + // }; + // + // =========================================================================== + xdr.struct("BumpSequenceOp", [["bumpTo", xdr.lookup("SequenceNumber")]]); + + // === xdr source ============================================================ + // + // struct CreateClaimableBalanceOp + // { + // Asset asset; + // int64 amount; + // Claimant claimants<10>; + // }; + // + // =========================================================================== + xdr.struct("CreateClaimableBalanceOp", [["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)]]); + + // === xdr source ============================================================ + // + // struct ClaimClaimableBalanceOp + // { + // ClaimableBalanceID balanceID; + // }; + // + // =========================================================================== + xdr.struct("ClaimClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct BeginSponsoringFutureReservesOp + // { + // AccountID sponsoredID; + // }; + // + // =========================================================================== + xdr.struct("BeginSponsoringFutureReservesOp", [["sponsoredId", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // enum RevokeSponsorshipType + // { + // REVOKE_SPONSORSHIP_LEDGER_ENTRY = 0, + // REVOKE_SPONSORSHIP_SIGNER = 1 + // }; + // + // =========================================================================== + xdr["enum"]("RevokeSponsorshipType", { + revokeSponsorshipLedgerEntry: 0, + revokeSponsorshipSigner: 1 + }); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // SignerKey signerKey; + // } + // + // =========================================================================== + xdr.struct("RevokeSponsorshipOpSigner", [["accountId", xdr.lookup("AccountId")], ["signerKey", xdr.lookup("SignerKey")]]); + + // === xdr source ============================================================ + // + // union RevokeSponsorshipOp switch (RevokeSponsorshipType type) + // { + // case REVOKE_SPONSORSHIP_LEDGER_ENTRY: + // LedgerKey ledgerKey; + // case REVOKE_SPONSORSHIP_SIGNER: + // struct + // { + // AccountID accountID; + // SignerKey signerKey; + // } signer; + // }; + // + // =========================================================================== + xdr.union("RevokeSponsorshipOp", { + switchOn: xdr.lookup("RevokeSponsorshipType"), + switchName: "type", + switches: [["revokeSponsorshipLedgerEntry", "ledgerKey"], ["revokeSponsorshipSigner", "signer"]], + arms: { + ledgerKey: xdr.lookup("LedgerKey"), + signer: xdr.lookup("RevokeSponsorshipOpSigner") + } + }); + + // === xdr source ============================================================ + // + // struct ClawbackOp + // { + // Asset asset; + // MuxedAccount from; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("ClawbackOp", [["asset", xdr.lookup("Asset")], ["from", xdr.lookup("MuxedAccount")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClawbackClaimableBalanceOp + // { + // ClaimableBalanceID balanceID; + // }; + // + // =========================================================================== + xdr.struct("ClawbackClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct SetTrustLineFlagsOp + // { + // AccountID trustor; + // Asset asset; + // + // uint32 clearFlags; // which flags to clear + // uint32 setFlags; // which flags to set + // }; + // + // =========================================================================== + xdr.struct("SetTrustLineFlagsOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["clearFlags", xdr.lookup("Uint32")], ["setFlags", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // const LIQUIDITY_POOL_FEE_V18 = 30; + // + // =========================================================================== + xdr["const"]("LIQUIDITY_POOL_FEE_V18", 30); + + // === xdr source ============================================================ + // + // struct LiquidityPoolDepositOp + // { + // PoolID liquidityPoolID; + // int64 maxAmountA; // maximum amount of first asset to deposit + // int64 maxAmountB; // maximum amount of second asset to deposit + // Price minPrice; // minimum depositA/depositB + // Price maxPrice; // maximum depositA/depositB + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolDepositOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["maxAmountA", xdr.lookup("Int64")], ["maxAmountB", xdr.lookup("Int64")], ["minPrice", xdr.lookup("Price")], ["maxPrice", xdr.lookup("Price")]]); + + // === xdr source ============================================================ + // + // struct LiquidityPoolWithdrawOp + // { + // PoolID liquidityPoolID; + // int64 amount; // amount of pool shares to withdraw + // int64 minAmountA; // minimum amount of first asset to withdraw + // int64 minAmountB; // minimum amount of second asset to withdraw + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolWithdrawOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["amount", xdr.lookup("Int64")], ["minAmountA", xdr.lookup("Int64")], ["minAmountB", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum HostFunctionType + // { + // HOST_FUNCTION_TYPE_INVOKE_CONTRACT = 0, + // HOST_FUNCTION_TYPE_CREATE_CONTRACT = 1, + // HOST_FUNCTION_TYPE_UPLOAD_CONTRACT_WASM = 2, + // HOST_FUNCTION_TYPE_CREATE_CONTRACT_V2 = 3 + // }; + // + // =========================================================================== + xdr["enum"]("HostFunctionType", { + hostFunctionTypeInvokeContract: 0, + hostFunctionTypeCreateContract: 1, + hostFunctionTypeUploadContractWasm: 2, + hostFunctionTypeCreateContractV2: 3 + }); + + // === xdr source ============================================================ + // + // enum ContractIDPreimageType + // { + // CONTRACT_ID_PREIMAGE_FROM_ADDRESS = 0, + // CONTRACT_ID_PREIMAGE_FROM_ASSET = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractIdPreimageType", { + contractIdPreimageFromAddress: 0, + contractIdPreimageFromAsset: 1 + }); + + // === xdr source ============================================================ + // + // struct + // { + // SCAddress address; + // uint256 salt; + // } + // + // =========================================================================== + xdr.struct("ContractIdPreimageFromAddress", [["address", xdr.lookup("ScAddress")], ["salt", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // union ContractIDPreimage switch (ContractIDPreimageType type) + // { + // case CONTRACT_ID_PREIMAGE_FROM_ADDRESS: + // struct + // { + // SCAddress address; + // uint256 salt; + // } fromAddress; + // case CONTRACT_ID_PREIMAGE_FROM_ASSET: + // Asset fromAsset; + // }; + // + // =========================================================================== + xdr.union("ContractIdPreimage", { + switchOn: xdr.lookup("ContractIdPreimageType"), + switchName: "type", + switches: [["contractIdPreimageFromAddress", "fromAddress"], ["contractIdPreimageFromAsset", "fromAsset"]], + arms: { + fromAddress: xdr.lookup("ContractIdPreimageFromAddress"), + fromAsset: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // struct CreateContractArgs + // { + // ContractIDPreimage contractIDPreimage; + // ContractExecutable executable; + // }; + // + // =========================================================================== + xdr.struct("CreateContractArgs", [["contractIdPreimage", xdr.lookup("ContractIdPreimage")], ["executable", xdr.lookup("ContractExecutable")]]); + + // === xdr source ============================================================ + // + // struct CreateContractArgsV2 + // { + // ContractIDPreimage contractIDPreimage; + // ContractExecutable executable; + // // Arguments of the contract's constructor. + // SCVal constructorArgs<>; + // }; + // + // =========================================================================== + xdr.struct("CreateContractArgsV2", [["contractIdPreimage", xdr.lookup("ContractIdPreimage")], ["executable", xdr.lookup("ContractExecutable")], ["constructorArgs", xdr.varArray(xdr.lookup("ScVal"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct InvokeContractArgs { + // SCAddress contractAddress; + // SCSymbol functionName; + // SCVal args<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeContractArgs", [["contractAddress", xdr.lookup("ScAddress")], ["functionName", xdr.lookup("ScSymbol")], ["args", xdr.varArray(xdr.lookup("ScVal"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union HostFunction switch (HostFunctionType type) + // { + // case HOST_FUNCTION_TYPE_INVOKE_CONTRACT: + // InvokeContractArgs invokeContract; + // case HOST_FUNCTION_TYPE_CREATE_CONTRACT: + // CreateContractArgs createContract; + // case HOST_FUNCTION_TYPE_UPLOAD_CONTRACT_WASM: + // opaque wasm<>; + // case HOST_FUNCTION_TYPE_CREATE_CONTRACT_V2: + // CreateContractArgsV2 createContractV2; + // }; + // + // =========================================================================== + xdr.union("HostFunction", { + switchOn: xdr.lookup("HostFunctionType"), + switchName: "type", + switches: [["hostFunctionTypeInvokeContract", "invokeContract"], ["hostFunctionTypeCreateContract", "createContract"], ["hostFunctionTypeUploadContractWasm", "wasm"], ["hostFunctionTypeCreateContractV2", "createContractV2"]], + arms: { + invokeContract: xdr.lookup("InvokeContractArgs"), + createContract: xdr.lookup("CreateContractArgs"), + wasm: xdr.varOpaque(), + createContractV2: xdr.lookup("CreateContractArgsV2") + } + }); + + // === xdr source ============================================================ + // + // enum SorobanAuthorizedFunctionType + // { + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN = 0, + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_HOST_FN = 1, + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN = 2 + // }; + // + // =========================================================================== + xdr["enum"]("SorobanAuthorizedFunctionType", { + sorobanAuthorizedFunctionTypeContractFn: 0, + sorobanAuthorizedFunctionTypeCreateContractHostFn: 1, + sorobanAuthorizedFunctionTypeCreateContractV2HostFn: 2 + }); + + // === xdr source ============================================================ + // + // union SorobanAuthorizedFunction switch (SorobanAuthorizedFunctionType type) + // { + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN: + // InvokeContractArgs contractFn; + // // This variant of auth payload for creating new contract instances + // // doesn't allow specifying the constructor arguments, creating contracts + // // with constructors that take arguments is only possible by authorizing + // // `SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN` + // // (protocol 22+). + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_HOST_FN: + // CreateContractArgs createContractHostFn; + // // This variant of auth payload for creating new contract instances + // // is only accepted in and after protocol 22. It allows authorizing the + // // contract constructor arguments. + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN: + // CreateContractArgsV2 createContractV2HostFn; + // }; + // + // =========================================================================== + xdr.union("SorobanAuthorizedFunction", { + switchOn: xdr.lookup("SorobanAuthorizedFunctionType"), + switchName: "type", + switches: [["sorobanAuthorizedFunctionTypeContractFn", "contractFn"], ["sorobanAuthorizedFunctionTypeCreateContractHostFn", "createContractHostFn"], ["sorobanAuthorizedFunctionTypeCreateContractV2HostFn", "createContractV2HostFn"]], + arms: { + contractFn: xdr.lookup("InvokeContractArgs"), + createContractHostFn: xdr.lookup("CreateContractArgs"), + createContractV2HostFn: xdr.lookup("CreateContractArgsV2") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanAuthorizedInvocation + // { + // SorobanAuthorizedFunction function; + // SorobanAuthorizedInvocation subInvocations<>; + // }; + // + // =========================================================================== + xdr.struct("SorobanAuthorizedInvocation", [["function", xdr.lookup("SorobanAuthorizedFunction")], ["subInvocations", xdr.varArray(xdr.lookup("SorobanAuthorizedInvocation"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct SorobanAddressCredentials + // { + // SCAddress address; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SCVal signature; + // }; + // + // =========================================================================== + xdr.struct("SorobanAddressCredentials", [["address", xdr.lookup("ScAddress")], ["nonce", xdr.lookup("Int64")], ["signatureExpirationLedger", xdr.lookup("Uint32")], ["signature", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // enum SorobanCredentialsType + // { + // SOROBAN_CREDENTIALS_SOURCE_ACCOUNT = 0, + // SOROBAN_CREDENTIALS_ADDRESS = 1 + // }; + // + // =========================================================================== + xdr["enum"]("SorobanCredentialsType", { + sorobanCredentialsSourceAccount: 0, + sorobanCredentialsAddress: 1 + }); + + // === xdr source ============================================================ + // + // union SorobanCredentials switch (SorobanCredentialsType type) + // { + // case SOROBAN_CREDENTIALS_SOURCE_ACCOUNT: + // void; + // case SOROBAN_CREDENTIALS_ADDRESS: + // SorobanAddressCredentials address; + // }; + // + // =========================================================================== + xdr.union("SorobanCredentials", { + switchOn: xdr.lookup("SorobanCredentialsType"), + switchName: "type", + switches: [["sorobanCredentialsSourceAccount", xdr["void"]()], ["sorobanCredentialsAddress", "address"]], + arms: { + address: xdr.lookup("SorobanAddressCredentials") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanAuthorizationEntry + // { + // SorobanCredentials credentials; + // SorobanAuthorizedInvocation rootInvocation; + // }; + // + // =========================================================================== + xdr.struct("SorobanAuthorizationEntry", [["credentials", xdr.lookup("SorobanCredentials")], ["rootInvocation", xdr.lookup("SorobanAuthorizedInvocation")]]); + + // === xdr source ============================================================ + // + // struct InvokeHostFunctionOp + // { + // // Host function to invoke. + // HostFunction hostFunction; + // // Per-address authorizations for this host function. + // SorobanAuthorizationEntry auth<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeHostFunctionOp", [["hostFunction", xdr.lookup("HostFunction")], ["auth", xdr.varArray(xdr.lookup("SorobanAuthorizationEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct ExtendFootprintTTLOp + // { + // ExtensionPoint ext; + // uint32 extendTo; + // }; + // + // =========================================================================== + xdr.struct("ExtendFootprintTtlOp", [["ext", xdr.lookup("ExtensionPoint")], ["extendTo", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct RestoreFootprintOp + // { + // ExtensionPoint ext; + // }; + // + // =========================================================================== + xdr.struct("RestoreFootprintOp", [["ext", xdr.lookup("ExtensionPoint")]]); + + // === xdr source ============================================================ + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountOp createAccountOp; + // case PAYMENT: + // PaymentOp paymentOp; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp; + // case MANAGE_SELL_OFFER: + // ManageSellOfferOp manageSellOfferOp; + // case CREATE_PASSIVE_SELL_OFFER: + // CreatePassiveSellOfferOp createPassiveSellOfferOp; + // case SET_OPTIONS: + // SetOptionsOp setOptionsOp; + // case CHANGE_TRUST: + // ChangeTrustOp changeTrustOp; + // case ALLOW_TRUST: + // AllowTrustOp allowTrustOp; + // case ACCOUNT_MERGE: + // MuxedAccount destination; + // case INFLATION: + // void; + // case MANAGE_DATA: + // ManageDataOp manageDataOp; + // case BUMP_SEQUENCE: + // BumpSequenceOp bumpSequenceOp; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferOp manageBuyOfferOp; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendOp pathPaymentStrictSendOp; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceOp createClaimableBalanceOp; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceOp claimClaimableBalanceOp; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp; + // case END_SPONSORING_FUTURE_RESERVES: + // void; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipOp revokeSponsorshipOp; + // case CLAWBACK: + // ClawbackOp clawbackOp; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceOp clawbackClaimableBalanceOp; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsOp setTrustLineFlagsOp; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositOp liquidityPoolDepositOp; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawOp liquidityPoolWithdrawOp; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionOp invokeHostFunctionOp; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLOp extendFootprintTTLOp; + // case RESTORE_FOOTPRINT: + // RestoreFootprintOp restoreFootprintOp; + // } + // + // =========================================================================== + xdr.union("OperationBody", { + switchOn: xdr.lookup("OperationType"), + switchName: "type", + switches: [["createAccount", "createAccountOp"], ["payment", "paymentOp"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveOp"], ["manageSellOffer", "manageSellOfferOp"], ["createPassiveSellOffer", "createPassiveSellOfferOp"], ["setOptions", "setOptionsOp"], ["changeTrust", "changeTrustOp"], ["allowTrust", "allowTrustOp"], ["accountMerge", "destination"], ["inflation", xdr["void"]()], ["manageData", "manageDataOp"], ["bumpSequence", "bumpSequenceOp"], ["manageBuyOffer", "manageBuyOfferOp"], ["pathPaymentStrictSend", "pathPaymentStrictSendOp"], ["createClaimableBalance", "createClaimableBalanceOp"], ["claimClaimableBalance", "claimClaimableBalanceOp"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesOp"], ["endSponsoringFutureReserves", xdr["void"]()], ["revokeSponsorship", "revokeSponsorshipOp"], ["clawback", "clawbackOp"], ["clawbackClaimableBalance", "clawbackClaimableBalanceOp"], ["setTrustLineFlags", "setTrustLineFlagsOp"], ["liquidityPoolDeposit", "liquidityPoolDepositOp"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawOp"], ["invokeHostFunction", "invokeHostFunctionOp"], ["extendFootprintTtl", "extendFootprintTtlOp"], ["restoreFootprint", "restoreFootprintOp"]], + arms: { + createAccountOp: xdr.lookup("CreateAccountOp"), + paymentOp: xdr.lookup("PaymentOp"), + pathPaymentStrictReceiveOp: xdr.lookup("PathPaymentStrictReceiveOp"), + manageSellOfferOp: xdr.lookup("ManageSellOfferOp"), + createPassiveSellOfferOp: xdr.lookup("CreatePassiveSellOfferOp"), + setOptionsOp: xdr.lookup("SetOptionsOp"), + changeTrustOp: xdr.lookup("ChangeTrustOp"), + allowTrustOp: xdr.lookup("AllowTrustOp"), + destination: xdr.lookup("MuxedAccount"), + manageDataOp: xdr.lookup("ManageDataOp"), + bumpSequenceOp: xdr.lookup("BumpSequenceOp"), + manageBuyOfferOp: xdr.lookup("ManageBuyOfferOp"), + pathPaymentStrictSendOp: xdr.lookup("PathPaymentStrictSendOp"), + createClaimableBalanceOp: xdr.lookup("CreateClaimableBalanceOp"), + claimClaimableBalanceOp: xdr.lookup("ClaimClaimableBalanceOp"), + beginSponsoringFutureReservesOp: xdr.lookup("BeginSponsoringFutureReservesOp"), + revokeSponsorshipOp: xdr.lookup("RevokeSponsorshipOp"), + clawbackOp: xdr.lookup("ClawbackOp"), + clawbackClaimableBalanceOp: xdr.lookup("ClawbackClaimableBalanceOp"), + setTrustLineFlagsOp: xdr.lookup("SetTrustLineFlagsOp"), + liquidityPoolDepositOp: xdr.lookup("LiquidityPoolDepositOp"), + liquidityPoolWithdrawOp: xdr.lookup("LiquidityPoolWithdrawOp"), + invokeHostFunctionOp: xdr.lookup("InvokeHostFunctionOp"), + extendFootprintTtlOp: xdr.lookup("ExtendFootprintTtlOp"), + restoreFootprintOp: xdr.lookup("RestoreFootprintOp") + } + }); + + // === xdr source ============================================================ + // + // struct Operation + // { + // // sourceAccount is the account used to run the operation + // // if not set, the runtime defaults to "sourceAccount" specified at + // // the transaction level + // MuxedAccount* sourceAccount; + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountOp createAccountOp; + // case PAYMENT: + // PaymentOp paymentOp; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp; + // case MANAGE_SELL_OFFER: + // ManageSellOfferOp manageSellOfferOp; + // case CREATE_PASSIVE_SELL_OFFER: + // CreatePassiveSellOfferOp createPassiveSellOfferOp; + // case SET_OPTIONS: + // SetOptionsOp setOptionsOp; + // case CHANGE_TRUST: + // ChangeTrustOp changeTrustOp; + // case ALLOW_TRUST: + // AllowTrustOp allowTrustOp; + // case ACCOUNT_MERGE: + // MuxedAccount destination; + // case INFLATION: + // void; + // case MANAGE_DATA: + // ManageDataOp manageDataOp; + // case BUMP_SEQUENCE: + // BumpSequenceOp bumpSequenceOp; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferOp manageBuyOfferOp; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendOp pathPaymentStrictSendOp; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceOp createClaimableBalanceOp; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceOp claimClaimableBalanceOp; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp; + // case END_SPONSORING_FUTURE_RESERVES: + // void; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipOp revokeSponsorshipOp; + // case CLAWBACK: + // ClawbackOp clawbackOp; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceOp clawbackClaimableBalanceOp; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsOp setTrustLineFlagsOp; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositOp liquidityPoolDepositOp; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawOp liquidityPoolWithdrawOp; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionOp invokeHostFunctionOp; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLOp extendFootprintTTLOp; + // case RESTORE_FOOTPRINT: + // RestoreFootprintOp restoreFootprintOp; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("Operation", [["sourceAccount", xdr.option(xdr.lookup("MuxedAccount"))], ["body", xdr.lookup("OperationBody")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageOperationId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // PoolID liquidityPoolID; + // Asset asset; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageRevokeId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")], ["liquidityPoolId", xdr.lookup("PoolId")], ["asset", xdr.lookup("Asset")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash networkID; + // ContractIDPreimage contractIDPreimage; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageContractId", [["networkId", xdr.lookup("Hash")], ["contractIdPreimage", xdr.lookup("ContractIdPreimage")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash networkID; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SorobanAuthorizedInvocation invocation; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageSorobanAuthorization", [["networkId", xdr.lookup("Hash")], ["nonce", xdr.lookup("Int64")], ["signatureExpirationLedger", xdr.lookup("Uint32")], ["invocation", xdr.lookup("SorobanAuthorizedInvocation")]]); + + // === xdr source ============================================================ + // + // union HashIDPreimage switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_OP_ID: + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // } operationID; + // case ENVELOPE_TYPE_POOL_REVOKE_OP_ID: + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // PoolID liquidityPoolID; + // Asset asset; + // } revokeID; + // case ENVELOPE_TYPE_CONTRACT_ID: + // struct + // { + // Hash networkID; + // ContractIDPreimage contractIDPreimage; + // } contractID; + // case ENVELOPE_TYPE_SOROBAN_AUTHORIZATION: + // struct + // { + // Hash networkID; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SorobanAuthorizedInvocation invocation; + // } sorobanAuthorization; + // }; + // + // =========================================================================== + xdr.union("HashIdPreimage", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeOpId", "operationId"], ["envelopeTypePoolRevokeOpId", "revokeId"], ["envelopeTypeContractId", "contractId"], ["envelopeTypeSorobanAuthorization", "sorobanAuthorization"]], + arms: { + operationId: xdr.lookup("HashIdPreimageOperationId"), + revokeId: xdr.lookup("HashIdPreimageRevokeId"), + contractId: xdr.lookup("HashIdPreimageContractId"), + sorobanAuthorization: xdr.lookup("HashIdPreimageSorobanAuthorization") + } + }); + + // === xdr source ============================================================ + // + // enum MemoType + // { + // MEMO_NONE = 0, + // MEMO_TEXT = 1, + // MEMO_ID = 2, + // MEMO_HASH = 3, + // MEMO_RETURN = 4 + // }; + // + // =========================================================================== + xdr["enum"]("MemoType", { + memoNone: 0, + memoText: 1, + memoId: 2, + memoHash: 3, + memoReturn: 4 + }); + + // === xdr source ============================================================ + // + // union Memo switch (MemoType type) + // { + // case MEMO_NONE: + // void; + // case MEMO_TEXT: + // string text<28>; + // case MEMO_ID: + // uint64 id; + // case MEMO_HASH: + // Hash hash; // the hash of what to pull from the content server + // case MEMO_RETURN: + // Hash retHash; // the hash of the tx you are rejecting + // }; + // + // =========================================================================== + xdr.union("Memo", { + switchOn: xdr.lookup("MemoType"), + switchName: "type", + switches: [["memoNone", xdr["void"]()], ["memoText", "text"], ["memoId", "id"], ["memoHash", "hash"], ["memoReturn", "retHash"]], + arms: { + text: xdr.string(28), + id: xdr.lookup("Uint64"), + hash: xdr.lookup("Hash"), + retHash: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // struct TimeBounds + // { + // TimePoint minTime; + // TimePoint maxTime; // 0 here means no maxTime + // }; + // + // =========================================================================== + xdr.struct("TimeBounds", [["minTime", xdr.lookup("TimePoint")], ["maxTime", xdr.lookup("TimePoint")]]); + + // === xdr source ============================================================ + // + // struct LedgerBounds + // { + // uint32 minLedger; + // uint32 maxLedger; // 0 here means no maxLedger + // }; + // + // =========================================================================== + xdr.struct("LedgerBounds", [["minLedger", xdr.lookup("Uint32")], ["maxLedger", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct PreconditionsV2 + // { + // TimeBounds* timeBounds; + // + // // Transaction only valid for ledger numbers n such that + // // minLedger <= n < maxLedger (if maxLedger == 0, then + // // only minLedger is checked) + // LedgerBounds* ledgerBounds; + // + // // If NULL, only valid when sourceAccount's sequence number + // // is seqNum - 1. Otherwise, valid when sourceAccount's + // // sequence number n satisfies minSeqNum <= n < tx.seqNum. + // // Note that after execution the account's sequence number + // // is always raised to tx.seqNum, and a transaction is not + // // valid if tx.seqNum is too high to ensure replay protection. + // SequenceNumber* minSeqNum; + // + // // For the transaction to be valid, the current ledger time must + // // be at least minSeqAge greater than sourceAccount's seqTime. + // Duration minSeqAge; + // + // // For the transaction to be valid, the current ledger number + // // must be at least minSeqLedgerGap greater than sourceAccount's + // // seqLedger. + // uint32 minSeqLedgerGap; + // + // // For the transaction to be valid, there must be a signature + // // corresponding to every Signer in this array, even if the + // // signature is not otherwise required by the sourceAccount or + // // operations. + // SignerKey extraSigners<2>; + // }; + // + // =========================================================================== + xdr.struct("PreconditionsV2", [["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["ledgerBounds", xdr.option(xdr.lookup("LedgerBounds"))], ["minSeqNum", xdr.option(xdr.lookup("SequenceNumber"))], ["minSeqAge", xdr.lookup("Duration")], ["minSeqLedgerGap", xdr.lookup("Uint32")], ["extraSigners", xdr.varArray(xdr.lookup("SignerKey"), 2)]]); + + // === xdr source ============================================================ + // + // enum PreconditionType + // { + // PRECOND_NONE = 0, + // PRECOND_TIME = 1, + // PRECOND_V2 = 2 + // }; + // + // =========================================================================== + xdr["enum"]("PreconditionType", { + precondNone: 0, + precondTime: 1, + precondV2: 2 + }); + + // === xdr source ============================================================ + // + // union Preconditions switch (PreconditionType type) + // { + // case PRECOND_NONE: + // void; + // case PRECOND_TIME: + // TimeBounds timeBounds; + // case PRECOND_V2: + // PreconditionsV2 v2; + // }; + // + // =========================================================================== + xdr.union("Preconditions", { + switchOn: xdr.lookup("PreconditionType"), + switchName: "type", + switches: [["precondNone", xdr["void"]()], ["precondTime", "timeBounds"], ["precondV2", "v2"]], + arms: { + timeBounds: xdr.lookup("TimeBounds"), + v2: xdr.lookup("PreconditionsV2") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerFootprint + // { + // LedgerKey readOnly<>; + // LedgerKey readWrite<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerFootprint", [["readOnly", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["readWrite", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)]]); + + // === xdr source ============================================================ + // + // enum ArchivalProofType + // { + // EXISTENCE = 0, + // NONEXISTENCE = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ArchivalProofType", { + existence: 0, + nonexistence: 1 + }); + + // === xdr source ============================================================ + // + // struct ArchivalProofNode + // { + // uint32 index; + // Hash hash; + // }; + // + // =========================================================================== + xdr.struct("ArchivalProofNode", [["index", xdr.lookup("Uint32")], ["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // typedef ArchivalProofNode ProofLevel<>; + // + // =========================================================================== + xdr.typedef("ProofLevel", xdr.varArray(xdr.lookup("ArchivalProofNode"), 2147483647)); + + // === xdr source ============================================================ + // + // struct NonexistenceProofBody + // { + // ColdArchiveBucketEntry entriesToProve<>; + // + // // Vector of vectors, where proofLevels[level] + // // contains all HashNodes that correspond with that level + // ProofLevel proofLevels<>; + // }; + // + // =========================================================================== + xdr.struct("NonexistenceProofBody", [["entriesToProve", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["proofLevels", xdr.varArray(xdr.lookup("ProofLevel"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct ExistenceProofBody + // { + // LedgerKey keysToProve<>; + // + // // Bounds for each key being proved, where bound[n] + // // corresponds to keysToProve[n] + // ColdArchiveBucketEntry lowBoundEntries<>; + // ColdArchiveBucketEntry highBoundEntries<>; + // + // // Vector of vectors, where proofLevels[level] + // // contains all HashNodes that correspond with that level + // ProofLevel proofLevels<>; + // }; + // + // =========================================================================== + xdr.struct("ExistenceProofBody", [["keysToProve", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["lowBoundEntries", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["highBoundEntries", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["proofLevels", xdr.varArray(xdr.lookup("ProofLevel"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union switch (ArchivalProofType t) + // { + // case EXISTENCE: + // NonexistenceProofBody nonexistenceProof; + // case NONEXISTENCE: + // ExistenceProofBody existenceProof; + // } + // + // =========================================================================== + xdr.union("ArchivalProofBody", { + switchOn: xdr.lookup("ArchivalProofType"), + switchName: "t", + switches: [["existence", "nonexistenceProof"], ["nonexistence", "existenceProof"]], + arms: { + nonexistenceProof: xdr.lookup("NonexistenceProofBody"), + existenceProof: xdr.lookup("ExistenceProofBody") + } + }); + + // === xdr source ============================================================ + // + // struct ArchivalProof + // { + // uint32 epoch; // AST Subtree for this proof + // + // union switch (ArchivalProofType t) + // { + // case EXISTENCE: + // NonexistenceProofBody nonexistenceProof; + // case NONEXISTENCE: + // ExistenceProofBody existenceProof; + // } body; + // }; + // + // =========================================================================== + xdr.struct("ArchivalProof", [["epoch", xdr.lookup("Uint32")], ["body", xdr.lookup("ArchivalProofBody")]]); + + // === xdr source ============================================================ + // + // struct SorobanResources + // { + // // The ledger footprint of the transaction. + // LedgerFootprint footprint; + // // The maximum number of instructions this transaction can use + // uint32 instructions; + // + // // The maximum number of bytes this transaction can read from ledger + // uint32 readBytes; + // // The maximum number of bytes this transaction can write to ledger + // uint32 writeBytes; + // }; + // + // =========================================================================== + xdr.struct("SorobanResources", [["footprint", xdr.lookup("LedgerFootprint")], ["instructions", xdr.lookup("Uint32")], ["readBytes", xdr.lookup("Uint32")], ["writeBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ArchivalProof proofs<>; + // } + // + // =========================================================================== + xdr.union("SorobanTransactionDataExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "proofs"]], + arms: { + proofs: xdr.varArray(xdr.lookup("ArchivalProof"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // struct SorobanTransactionData + // { + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ArchivalProof proofs<>; + // } ext; + // SorobanResources resources; + // // Amount of the transaction `fee` allocated to the Soroban resource fees. + // // The fraction of `resourceFee` corresponding to `resources` specified + // // above is *not* refundable (i.e. fees for instructions, ledger I/O), as + // // well as fees for the transaction size. + // // The remaining part of the fee is refundable and the charged value is + // // based on the actual consumption of refundable resources (events, ledger + // // rent bumps). + // // The `inclusionFee` used for prioritization of the transaction is defined + // // as `tx.fee - resourceFee`. + // int64 resourceFee; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionData", [["ext", xdr.lookup("SorobanTransactionDataExt")], ["resources", xdr.lookup("SorobanResources")], ["resourceFee", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionV0Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionV0 + // { + // uint256 sourceAccountEd25519; + // uint32 fee; + // SequenceNumber seqNum; + // TimeBounds* timeBounds; + // Memo memo; + // Operation operations; + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionV0", [["sourceAccountEd25519", xdr.lookup("Uint256")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionV0Ext")]]); + + // === xdr source ============================================================ + // + // struct TransactionV0Envelope + // { + // TransactionV0 tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("TransactionV0Envelope", [["tx", xdr.lookup("TransactionV0")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionData sorobanData; + // } + // + // =========================================================================== + xdr.union("TransactionExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "sorobanData"]], + arms: { + sorobanData: xdr.lookup("SorobanTransactionData") + } + }); + + // === xdr source ============================================================ + // + // struct Transaction + // { + // // account used to run the transaction + // MuxedAccount sourceAccount; + // + // // the fee the sourceAccount will pay + // uint32 fee; + // + // // sequence number to consume in the account + // SequenceNumber seqNum; + // + // // validity conditions + // Preconditions cond; + // + // Memo memo; + // + // Operation operations; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionData sorobanData; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("Transaction", [["sourceAccount", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["cond", xdr.lookup("Preconditions")], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionExt")]]); + + // === xdr source ============================================================ + // + // struct TransactionV1Envelope + // { + // Transaction tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("TransactionV1Envelope", [["tx", xdr.lookup("Transaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // } + // + // =========================================================================== + xdr.union("FeeBumpTransactionInnerTx", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTx", "v1"]], + arms: { + v1: xdr.lookup("TransactionV1Envelope") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("FeeBumpTransactionExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct FeeBumpTransaction + // { + // MuxedAccount feeSource; + // int64 fee; + // union switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // } + // innerTx; + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("FeeBumpTransaction", [["feeSource", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Int64")], ["innerTx", xdr.lookup("FeeBumpTransactionInnerTx")], ["ext", xdr.lookup("FeeBumpTransactionExt")]]); + + // === xdr source ============================================================ + // + // struct FeeBumpTransactionEnvelope + // { + // FeeBumpTransaction tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("FeeBumpTransactionEnvelope", [["tx", xdr.lookup("FeeBumpTransaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union TransactionEnvelope switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX_V0: + // TransactionV0Envelope v0; + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransactionEnvelope feeBump; + // }; + // + // =========================================================================== + xdr.union("TransactionEnvelope", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTxV0", "v0"], ["envelopeTypeTx", "v1"], ["envelopeTypeTxFeeBump", "feeBump"]], + arms: { + v0: xdr.lookup("TransactionV0Envelope"), + v1: xdr.lookup("TransactionV1Envelope"), + feeBump: xdr.lookup("FeeBumpTransactionEnvelope") + } + }); + + // === xdr source ============================================================ + // + // union switch (EnvelopeType type) + // { + // // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // case ENVELOPE_TYPE_TX: + // Transaction tx; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransaction feeBump; + // } + // + // =========================================================================== + xdr.union("TransactionSignaturePayloadTaggedTransaction", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTx", "tx"], ["envelopeTypeTxFeeBump", "feeBump"]], + arms: { + tx: xdr.lookup("Transaction"), + feeBump: xdr.lookup("FeeBumpTransaction") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionSignaturePayload + // { + // Hash networkId; + // union switch (EnvelopeType type) + // { + // // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // case ENVELOPE_TYPE_TX: + // Transaction tx; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransaction feeBump; + // } + // taggedTransaction; + // }; + // + // =========================================================================== + xdr.struct("TransactionSignaturePayload", [["networkId", xdr.lookup("Hash")], ["taggedTransaction", xdr.lookup("TransactionSignaturePayloadTaggedTransaction")]]); + + // === xdr source ============================================================ + // + // enum ClaimAtomType + // { + // CLAIM_ATOM_TYPE_V0 = 0, + // CLAIM_ATOM_TYPE_ORDER_BOOK = 1, + // CLAIM_ATOM_TYPE_LIQUIDITY_POOL = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimAtomType", { + claimAtomTypeV0: 0, + claimAtomTypeOrderBook: 1, + claimAtomTypeLiquidityPool: 2 + }); + + // === xdr source ============================================================ + // + // struct ClaimOfferAtomV0 + // { + // // emitted to identify the offer + // uint256 sellerEd25519; // Account that owns the offer + // int64 offerID; + // + // // amount and asset taken from the owner + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the owner + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimOfferAtomV0", [["sellerEd25519", xdr.lookup("Uint256")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClaimOfferAtom + // { + // // emitted to identify the offer + // AccountID sellerID; // Account that owns the offer + // int64 offerID; + // + // // amount and asset taken from the owner + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the owner + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimOfferAtom", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClaimLiquidityAtom + // { + // PoolID liquidityPoolID; + // + // // amount and asset taken from the pool + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the pool + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimLiquidityAtom", [["liquidityPoolId", xdr.lookup("PoolId")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union ClaimAtom switch (ClaimAtomType type) + // { + // case CLAIM_ATOM_TYPE_V0: + // ClaimOfferAtomV0 v0; + // case CLAIM_ATOM_TYPE_ORDER_BOOK: + // ClaimOfferAtom orderBook; + // case CLAIM_ATOM_TYPE_LIQUIDITY_POOL: + // ClaimLiquidityAtom liquidityPool; + // }; + // + // =========================================================================== + xdr.union("ClaimAtom", { + switchOn: xdr.lookup("ClaimAtomType"), + switchName: "type", + switches: [["claimAtomTypeV0", "v0"], ["claimAtomTypeOrderBook", "orderBook"], ["claimAtomTypeLiquidityPool", "liquidityPool"]], + arms: { + v0: xdr.lookup("ClaimOfferAtomV0"), + orderBook: xdr.lookup("ClaimOfferAtom"), + liquidityPool: xdr.lookup("ClaimLiquidityAtom") + } + }); + + // === xdr source ============================================================ + // + // enum CreateAccountResultCode + // { + // // codes considered as "success" for the operation + // CREATE_ACCOUNT_SUCCESS = 0, // account was created + // + // // codes considered as "failure" for the operation + // CREATE_ACCOUNT_MALFORMED = -1, // invalid destination + // CREATE_ACCOUNT_UNDERFUNDED = -2, // not enough funds in source account + // CREATE_ACCOUNT_LOW_RESERVE = + // -3, // would create an account below the min reserve + // CREATE_ACCOUNT_ALREADY_EXIST = -4 // account already exists + // }; + // + // =========================================================================== + xdr["enum"]("CreateAccountResultCode", { + createAccountSuccess: 0, + createAccountMalformed: -1, + createAccountUnderfunded: -2, + createAccountLowReserve: -3, + createAccountAlreadyExist: -4 + }); + + // === xdr source ============================================================ + // + // union CreateAccountResult switch (CreateAccountResultCode code) + // { + // case CREATE_ACCOUNT_SUCCESS: + // void; + // case CREATE_ACCOUNT_MALFORMED: + // case CREATE_ACCOUNT_UNDERFUNDED: + // case CREATE_ACCOUNT_LOW_RESERVE: + // case CREATE_ACCOUNT_ALREADY_EXIST: + // void; + // }; + // + // =========================================================================== + xdr.union("CreateAccountResult", { + switchOn: xdr.lookup("CreateAccountResultCode"), + switchName: "code", + switches: [["createAccountSuccess", xdr["void"]()], ["createAccountMalformed", xdr["void"]()], ["createAccountUnderfunded", xdr["void"]()], ["createAccountLowReserve", xdr["void"]()], ["createAccountAlreadyExist", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum PaymentResultCode + // { + // // codes considered as "success" for the operation + // PAYMENT_SUCCESS = 0, // payment successfully completed + // + // // codes considered as "failure" for the operation + // PAYMENT_MALFORMED = -1, // bad input + // PAYMENT_UNDERFUNDED = -2, // not enough funds in source account + // PAYMENT_SRC_NO_TRUST = -3, // no trust line on source account + // PAYMENT_SRC_NOT_AUTHORIZED = -4, // source not authorized to transfer + // PAYMENT_NO_DESTINATION = -5, // destination account does not exist + // PAYMENT_NO_TRUST = -6, // destination missing a trust line for asset + // PAYMENT_NOT_AUTHORIZED = -7, // destination not authorized to hold asset + // PAYMENT_LINE_FULL = -8, // destination would go above their limit + // PAYMENT_NO_ISSUER = -9 // missing issuer on asset + // }; + // + // =========================================================================== + xdr["enum"]("PaymentResultCode", { + paymentSuccess: 0, + paymentMalformed: -1, + paymentUnderfunded: -2, + paymentSrcNoTrust: -3, + paymentSrcNotAuthorized: -4, + paymentNoDestination: -5, + paymentNoTrust: -6, + paymentNotAuthorized: -7, + paymentLineFull: -8, + paymentNoIssuer: -9 + }); + + // === xdr source ============================================================ + // + // union PaymentResult switch (PaymentResultCode code) + // { + // case PAYMENT_SUCCESS: + // void; + // case PAYMENT_MALFORMED: + // case PAYMENT_UNDERFUNDED: + // case PAYMENT_SRC_NO_TRUST: + // case PAYMENT_SRC_NOT_AUTHORIZED: + // case PAYMENT_NO_DESTINATION: + // case PAYMENT_NO_TRUST: + // case PAYMENT_NOT_AUTHORIZED: + // case PAYMENT_LINE_FULL: + // case PAYMENT_NO_ISSUER: + // void; + // }; + // + // =========================================================================== + xdr.union("PaymentResult", { + switchOn: xdr.lookup("PaymentResultCode"), + switchName: "code", + switches: [["paymentSuccess", xdr["void"]()], ["paymentMalformed", xdr["void"]()], ["paymentUnderfunded", xdr["void"]()], ["paymentSrcNoTrust", xdr["void"]()], ["paymentSrcNotAuthorized", xdr["void"]()], ["paymentNoDestination", xdr["void"]()], ["paymentNoTrust", xdr["void"]()], ["paymentNotAuthorized", xdr["void"]()], ["paymentLineFull", xdr["void"]()], ["paymentNoIssuer", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum PathPaymentStrictReceiveResultCode + // { + // // codes considered as "success" for the operation + // PATH_PAYMENT_STRICT_RECEIVE_SUCCESS = 0, // success + // + // // codes considered as "failure" for the operation + // PATH_PAYMENT_STRICT_RECEIVE_MALFORMED = -1, // bad input + // PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED = + // -2, // not enough funds in source account + // PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST = + // -3, // no trust line on source account + // PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED = + // -4, // source not authorized to transfer + // PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION = + // -5, // destination account does not exist + // PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST = + // -6, // dest missing a trust line for asset + // PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED = + // -7, // dest not authorized to hold asset + // PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL = + // -8, // dest would go above their limit + // PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER = -9, // missing issuer on one asset + // PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS = + // -10, // not enough offers to satisfy path + // PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF = + // -11, // would cross one of its own offers + // PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX = -12 // could not satisfy sendmax + // }; + // + // =========================================================================== + xdr["enum"]("PathPaymentStrictReceiveResultCode", { + pathPaymentStrictReceiveSuccess: 0, + pathPaymentStrictReceiveMalformed: -1, + pathPaymentStrictReceiveUnderfunded: -2, + pathPaymentStrictReceiveSrcNoTrust: -3, + pathPaymentStrictReceiveSrcNotAuthorized: -4, + pathPaymentStrictReceiveNoDestination: -5, + pathPaymentStrictReceiveNoTrust: -6, + pathPaymentStrictReceiveNotAuthorized: -7, + pathPaymentStrictReceiveLineFull: -8, + pathPaymentStrictReceiveNoIssuer: -9, + pathPaymentStrictReceiveTooFewOffers: -10, + pathPaymentStrictReceiveOfferCrossSelf: -11, + pathPaymentStrictReceiveOverSendmax: -12 + }); + + // === xdr source ============================================================ + // + // struct SimplePaymentResult + // { + // AccountID destination; + // Asset asset; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("SimplePaymentResult", [["destination", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } + // + // =========================================================================== + xdr.struct("PathPaymentStrictReceiveResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]); + + // === xdr source ============================================================ + // + // union PathPaymentStrictReceiveResult switch ( + // PathPaymentStrictReceiveResultCode code) + // { + // case PATH_PAYMENT_STRICT_RECEIVE_SUCCESS: + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } success; + // case PATH_PAYMENT_STRICT_RECEIVE_MALFORMED: + // case PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED: + // case PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST: + // case PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION: + // case PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST: + // case PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL: + // void; + // case PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER: + // Asset noIssuer; // the asset that caused the error + // case PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS: + // case PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF: + // case PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX: + // void; + // }; + // + // =========================================================================== + xdr.union("PathPaymentStrictReceiveResult", { + switchOn: xdr.lookup("PathPaymentStrictReceiveResultCode"), + switchName: "code", + switches: [["pathPaymentStrictReceiveSuccess", "success"], ["pathPaymentStrictReceiveMalformed", xdr["void"]()], ["pathPaymentStrictReceiveUnderfunded", xdr["void"]()], ["pathPaymentStrictReceiveSrcNoTrust", xdr["void"]()], ["pathPaymentStrictReceiveSrcNotAuthorized", xdr["void"]()], ["pathPaymentStrictReceiveNoDestination", xdr["void"]()], ["pathPaymentStrictReceiveNoTrust", xdr["void"]()], ["pathPaymentStrictReceiveNotAuthorized", xdr["void"]()], ["pathPaymentStrictReceiveLineFull", xdr["void"]()], ["pathPaymentStrictReceiveNoIssuer", "noIssuer"], ["pathPaymentStrictReceiveTooFewOffers", xdr["void"]()], ["pathPaymentStrictReceiveOfferCrossSelf", xdr["void"]()], ["pathPaymentStrictReceiveOverSendmax", xdr["void"]()]], + arms: { + success: xdr.lookup("PathPaymentStrictReceiveResultSuccess"), + noIssuer: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // enum PathPaymentStrictSendResultCode + // { + // // codes considered as "success" for the operation + // PATH_PAYMENT_STRICT_SEND_SUCCESS = 0, // success + // + // // codes considered as "failure" for the operation + // PATH_PAYMENT_STRICT_SEND_MALFORMED = -1, // bad input + // PATH_PAYMENT_STRICT_SEND_UNDERFUNDED = + // -2, // not enough funds in source account + // PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST = + // -3, // no trust line on source account + // PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED = + // -4, // source not authorized to transfer + // PATH_PAYMENT_STRICT_SEND_NO_DESTINATION = + // -5, // destination account does not exist + // PATH_PAYMENT_STRICT_SEND_NO_TRUST = + // -6, // dest missing a trust line for asset + // PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED = + // -7, // dest not authorized to hold asset + // PATH_PAYMENT_STRICT_SEND_LINE_FULL = -8, // dest would go above their limit + // PATH_PAYMENT_STRICT_SEND_NO_ISSUER = -9, // missing issuer on one asset + // PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS = + // -10, // not enough offers to satisfy path + // PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF = + // -11, // would cross one of its own offers + // PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN = -12 // could not satisfy destMin + // }; + // + // =========================================================================== + xdr["enum"]("PathPaymentStrictSendResultCode", { + pathPaymentStrictSendSuccess: 0, + pathPaymentStrictSendMalformed: -1, + pathPaymentStrictSendUnderfunded: -2, + pathPaymentStrictSendSrcNoTrust: -3, + pathPaymentStrictSendSrcNotAuthorized: -4, + pathPaymentStrictSendNoDestination: -5, + pathPaymentStrictSendNoTrust: -6, + pathPaymentStrictSendNotAuthorized: -7, + pathPaymentStrictSendLineFull: -8, + pathPaymentStrictSendNoIssuer: -9, + pathPaymentStrictSendTooFewOffers: -10, + pathPaymentStrictSendOfferCrossSelf: -11, + pathPaymentStrictSendUnderDestmin: -12 + }); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } + // + // =========================================================================== + xdr.struct("PathPaymentStrictSendResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]); + + // === xdr source ============================================================ + // + // union PathPaymentStrictSendResult switch (PathPaymentStrictSendResultCode code) + // { + // case PATH_PAYMENT_STRICT_SEND_SUCCESS: + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } success; + // case PATH_PAYMENT_STRICT_SEND_MALFORMED: + // case PATH_PAYMENT_STRICT_SEND_UNDERFUNDED: + // case PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST: + // case PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_SEND_NO_DESTINATION: + // case PATH_PAYMENT_STRICT_SEND_NO_TRUST: + // case PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_SEND_LINE_FULL: + // void; + // case PATH_PAYMENT_STRICT_SEND_NO_ISSUER: + // Asset noIssuer; // the asset that caused the error + // case PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS: + // case PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF: + // case PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN: + // void; + // }; + // + // =========================================================================== + xdr.union("PathPaymentStrictSendResult", { + switchOn: xdr.lookup("PathPaymentStrictSendResultCode"), + switchName: "code", + switches: [["pathPaymentStrictSendSuccess", "success"], ["pathPaymentStrictSendMalformed", xdr["void"]()], ["pathPaymentStrictSendUnderfunded", xdr["void"]()], ["pathPaymentStrictSendSrcNoTrust", xdr["void"]()], ["pathPaymentStrictSendSrcNotAuthorized", xdr["void"]()], ["pathPaymentStrictSendNoDestination", xdr["void"]()], ["pathPaymentStrictSendNoTrust", xdr["void"]()], ["pathPaymentStrictSendNotAuthorized", xdr["void"]()], ["pathPaymentStrictSendLineFull", xdr["void"]()], ["pathPaymentStrictSendNoIssuer", "noIssuer"], ["pathPaymentStrictSendTooFewOffers", xdr["void"]()], ["pathPaymentStrictSendOfferCrossSelf", xdr["void"]()], ["pathPaymentStrictSendUnderDestmin", xdr["void"]()]], + arms: { + success: xdr.lookup("PathPaymentStrictSendResultSuccess"), + noIssuer: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // enum ManageSellOfferResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_SELL_OFFER_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // MANAGE_SELL_OFFER_MALFORMED = -1, // generated offer would be invalid + // MANAGE_SELL_OFFER_SELL_NO_TRUST = + // -2, // no trust line for what we're selling + // MANAGE_SELL_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying + // MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell + // MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy + // MANAGE_SELL_OFFER_LINE_FULL = -6, // can't receive more of what it's buying + // MANAGE_SELL_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell + // MANAGE_SELL_OFFER_CROSS_SELF = + // -8, // would cross an offer from the same user + // MANAGE_SELL_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling + // MANAGE_SELL_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying + // + // // update errors + // MANAGE_SELL_OFFER_NOT_FOUND = + // -11, // offerID does not match an existing offer + // + // MANAGE_SELL_OFFER_LOW_RESERVE = + // -12 // not enough funds to create a new Offer + // }; + // + // =========================================================================== + xdr["enum"]("ManageSellOfferResultCode", { + manageSellOfferSuccess: 0, + manageSellOfferMalformed: -1, + manageSellOfferSellNoTrust: -2, + manageSellOfferBuyNoTrust: -3, + manageSellOfferSellNotAuthorized: -4, + manageSellOfferBuyNotAuthorized: -5, + manageSellOfferLineFull: -6, + manageSellOfferUnderfunded: -7, + manageSellOfferCrossSelf: -8, + manageSellOfferSellNoIssuer: -9, + manageSellOfferBuyNoIssuer: -10, + manageSellOfferNotFound: -11, + manageSellOfferLowReserve: -12 + }); + + // === xdr source ============================================================ + // + // enum ManageOfferEffect + // { + // MANAGE_OFFER_CREATED = 0, + // MANAGE_OFFER_UPDATED = 1, + // MANAGE_OFFER_DELETED = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ManageOfferEffect", { + manageOfferCreated: 0, + manageOfferUpdated: 1, + manageOfferDeleted: 2 + }); + + // === xdr source ============================================================ + // + // union switch (ManageOfferEffect effect) + // { + // case MANAGE_OFFER_CREATED: + // case MANAGE_OFFER_UPDATED: + // OfferEntry offer; + // case MANAGE_OFFER_DELETED: + // void; + // } + // + // =========================================================================== + xdr.union("ManageOfferSuccessResultOffer", { + switchOn: xdr.lookup("ManageOfferEffect"), + switchName: "effect", + switches: [["manageOfferCreated", "offer"], ["manageOfferUpdated", "offer"], ["manageOfferDeleted", xdr["void"]()]], + arms: { + offer: xdr.lookup("OfferEntry") + } + }); + + // === xdr source ============================================================ + // + // struct ManageOfferSuccessResult + // { + // // offers that got claimed while creating this offer + // ClaimAtom offersClaimed<>; + // + // union switch (ManageOfferEffect effect) + // { + // case MANAGE_OFFER_CREATED: + // case MANAGE_OFFER_UPDATED: + // OfferEntry offer; + // case MANAGE_OFFER_DELETED: + // void; + // } + // offer; + // }; + // + // =========================================================================== + xdr.struct("ManageOfferSuccessResult", [["offersClaimed", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["offer", xdr.lookup("ManageOfferSuccessResultOffer")]]); + + // === xdr source ============================================================ + // + // union ManageSellOfferResult switch (ManageSellOfferResultCode code) + // { + // case MANAGE_SELL_OFFER_SUCCESS: + // ManageOfferSuccessResult success; + // case MANAGE_SELL_OFFER_MALFORMED: + // case MANAGE_SELL_OFFER_SELL_NO_TRUST: + // case MANAGE_SELL_OFFER_BUY_NO_TRUST: + // case MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED: + // case MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED: + // case MANAGE_SELL_OFFER_LINE_FULL: + // case MANAGE_SELL_OFFER_UNDERFUNDED: + // case MANAGE_SELL_OFFER_CROSS_SELF: + // case MANAGE_SELL_OFFER_SELL_NO_ISSUER: + // case MANAGE_SELL_OFFER_BUY_NO_ISSUER: + // case MANAGE_SELL_OFFER_NOT_FOUND: + // case MANAGE_SELL_OFFER_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageSellOfferResult", { + switchOn: xdr.lookup("ManageSellOfferResultCode"), + switchName: "code", + switches: [["manageSellOfferSuccess", "success"], ["manageSellOfferMalformed", xdr["void"]()], ["manageSellOfferSellNoTrust", xdr["void"]()], ["manageSellOfferBuyNoTrust", xdr["void"]()], ["manageSellOfferSellNotAuthorized", xdr["void"]()], ["manageSellOfferBuyNotAuthorized", xdr["void"]()], ["manageSellOfferLineFull", xdr["void"]()], ["manageSellOfferUnderfunded", xdr["void"]()], ["manageSellOfferCrossSelf", xdr["void"]()], ["manageSellOfferSellNoIssuer", xdr["void"]()], ["manageSellOfferBuyNoIssuer", xdr["void"]()], ["manageSellOfferNotFound", xdr["void"]()], ["manageSellOfferLowReserve", xdr["void"]()]], + arms: { + success: xdr.lookup("ManageOfferSuccessResult") + } + }); + + // === xdr source ============================================================ + // + // enum ManageBuyOfferResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_BUY_OFFER_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // MANAGE_BUY_OFFER_MALFORMED = -1, // generated offer would be invalid + // MANAGE_BUY_OFFER_SELL_NO_TRUST = -2, // no trust line for what we're selling + // MANAGE_BUY_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying + // MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell + // MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy + // MANAGE_BUY_OFFER_LINE_FULL = -6, // can't receive more of what it's buying + // MANAGE_BUY_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell + // MANAGE_BUY_OFFER_CROSS_SELF = -8, // would cross an offer from the same user + // MANAGE_BUY_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling + // MANAGE_BUY_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying + // + // // update errors + // MANAGE_BUY_OFFER_NOT_FOUND = + // -11, // offerID does not match an existing offer + // + // MANAGE_BUY_OFFER_LOW_RESERVE = -12 // not enough funds to create a new Offer + // }; + // + // =========================================================================== + xdr["enum"]("ManageBuyOfferResultCode", { + manageBuyOfferSuccess: 0, + manageBuyOfferMalformed: -1, + manageBuyOfferSellNoTrust: -2, + manageBuyOfferBuyNoTrust: -3, + manageBuyOfferSellNotAuthorized: -4, + manageBuyOfferBuyNotAuthorized: -5, + manageBuyOfferLineFull: -6, + manageBuyOfferUnderfunded: -7, + manageBuyOfferCrossSelf: -8, + manageBuyOfferSellNoIssuer: -9, + manageBuyOfferBuyNoIssuer: -10, + manageBuyOfferNotFound: -11, + manageBuyOfferLowReserve: -12 + }); + + // === xdr source ============================================================ + // + // union ManageBuyOfferResult switch (ManageBuyOfferResultCode code) + // { + // case MANAGE_BUY_OFFER_SUCCESS: + // ManageOfferSuccessResult success; + // case MANAGE_BUY_OFFER_MALFORMED: + // case MANAGE_BUY_OFFER_SELL_NO_TRUST: + // case MANAGE_BUY_OFFER_BUY_NO_TRUST: + // case MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED: + // case MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED: + // case MANAGE_BUY_OFFER_LINE_FULL: + // case MANAGE_BUY_OFFER_UNDERFUNDED: + // case MANAGE_BUY_OFFER_CROSS_SELF: + // case MANAGE_BUY_OFFER_SELL_NO_ISSUER: + // case MANAGE_BUY_OFFER_BUY_NO_ISSUER: + // case MANAGE_BUY_OFFER_NOT_FOUND: + // case MANAGE_BUY_OFFER_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageBuyOfferResult", { + switchOn: xdr.lookup("ManageBuyOfferResultCode"), + switchName: "code", + switches: [["manageBuyOfferSuccess", "success"], ["manageBuyOfferMalformed", xdr["void"]()], ["manageBuyOfferSellNoTrust", xdr["void"]()], ["manageBuyOfferBuyNoTrust", xdr["void"]()], ["manageBuyOfferSellNotAuthorized", xdr["void"]()], ["manageBuyOfferBuyNotAuthorized", xdr["void"]()], ["manageBuyOfferLineFull", xdr["void"]()], ["manageBuyOfferUnderfunded", xdr["void"]()], ["manageBuyOfferCrossSelf", xdr["void"]()], ["manageBuyOfferSellNoIssuer", xdr["void"]()], ["manageBuyOfferBuyNoIssuer", xdr["void"]()], ["manageBuyOfferNotFound", xdr["void"]()], ["manageBuyOfferLowReserve", xdr["void"]()]], + arms: { + success: xdr.lookup("ManageOfferSuccessResult") + } + }); + + // === xdr source ============================================================ + // + // enum SetOptionsResultCode + // { + // // codes considered as "success" for the operation + // SET_OPTIONS_SUCCESS = 0, + // // codes considered as "failure" for the operation + // SET_OPTIONS_LOW_RESERVE = -1, // not enough funds to add a signer + // SET_OPTIONS_TOO_MANY_SIGNERS = -2, // max number of signers already reached + // SET_OPTIONS_BAD_FLAGS = -3, // invalid combination of clear/set flags + // SET_OPTIONS_INVALID_INFLATION = -4, // inflation account does not exist + // SET_OPTIONS_CANT_CHANGE = -5, // can no longer change this option + // SET_OPTIONS_UNKNOWN_FLAG = -6, // can't set an unknown flag + // SET_OPTIONS_THRESHOLD_OUT_OF_RANGE = -7, // bad value for weight/threshold + // SET_OPTIONS_BAD_SIGNER = -8, // signer cannot be masterkey + // SET_OPTIONS_INVALID_HOME_DOMAIN = -9, // malformed home domain + // SET_OPTIONS_AUTH_REVOCABLE_REQUIRED = + // -10 // auth revocable is required for clawback + // }; + // + // =========================================================================== + xdr["enum"]("SetOptionsResultCode", { + setOptionsSuccess: 0, + setOptionsLowReserve: -1, + setOptionsTooManySigners: -2, + setOptionsBadFlags: -3, + setOptionsInvalidInflation: -4, + setOptionsCantChange: -5, + setOptionsUnknownFlag: -6, + setOptionsThresholdOutOfRange: -7, + setOptionsBadSigner: -8, + setOptionsInvalidHomeDomain: -9, + setOptionsAuthRevocableRequired: -10 + }); + + // === xdr source ============================================================ + // + // union SetOptionsResult switch (SetOptionsResultCode code) + // { + // case SET_OPTIONS_SUCCESS: + // void; + // case SET_OPTIONS_LOW_RESERVE: + // case SET_OPTIONS_TOO_MANY_SIGNERS: + // case SET_OPTIONS_BAD_FLAGS: + // case SET_OPTIONS_INVALID_INFLATION: + // case SET_OPTIONS_CANT_CHANGE: + // case SET_OPTIONS_UNKNOWN_FLAG: + // case SET_OPTIONS_THRESHOLD_OUT_OF_RANGE: + // case SET_OPTIONS_BAD_SIGNER: + // case SET_OPTIONS_INVALID_HOME_DOMAIN: + // case SET_OPTIONS_AUTH_REVOCABLE_REQUIRED: + // void; + // }; + // + // =========================================================================== + xdr.union("SetOptionsResult", { + switchOn: xdr.lookup("SetOptionsResultCode"), + switchName: "code", + switches: [["setOptionsSuccess", xdr["void"]()], ["setOptionsLowReserve", xdr["void"]()], ["setOptionsTooManySigners", xdr["void"]()], ["setOptionsBadFlags", xdr["void"]()], ["setOptionsInvalidInflation", xdr["void"]()], ["setOptionsCantChange", xdr["void"]()], ["setOptionsUnknownFlag", xdr["void"]()], ["setOptionsThresholdOutOfRange", xdr["void"]()], ["setOptionsBadSigner", xdr["void"]()], ["setOptionsInvalidHomeDomain", xdr["void"]()], ["setOptionsAuthRevocableRequired", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ChangeTrustResultCode + // { + // // codes considered as "success" for the operation + // CHANGE_TRUST_SUCCESS = 0, + // // codes considered as "failure" for the operation + // CHANGE_TRUST_MALFORMED = -1, // bad input + // CHANGE_TRUST_NO_ISSUER = -2, // could not find issuer + // CHANGE_TRUST_INVALID_LIMIT = -3, // cannot drop limit below balance + // // cannot create with a limit of 0 + // CHANGE_TRUST_LOW_RESERVE = + // -4, // not enough funds to create a new trust line, + // CHANGE_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed + // CHANGE_TRUST_TRUST_LINE_MISSING = -6, // Asset trustline is missing for pool + // CHANGE_TRUST_CANNOT_DELETE = + // -7, // Asset trustline is still referenced in a pool + // CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES = + // -8 // Asset trustline is deauthorized + // }; + // + // =========================================================================== + xdr["enum"]("ChangeTrustResultCode", { + changeTrustSuccess: 0, + changeTrustMalformed: -1, + changeTrustNoIssuer: -2, + changeTrustInvalidLimit: -3, + changeTrustLowReserve: -4, + changeTrustSelfNotAllowed: -5, + changeTrustTrustLineMissing: -6, + changeTrustCannotDelete: -7, + changeTrustNotAuthMaintainLiabilities: -8 + }); + + // === xdr source ============================================================ + // + // union ChangeTrustResult switch (ChangeTrustResultCode code) + // { + // case CHANGE_TRUST_SUCCESS: + // void; + // case CHANGE_TRUST_MALFORMED: + // case CHANGE_TRUST_NO_ISSUER: + // case CHANGE_TRUST_INVALID_LIMIT: + // case CHANGE_TRUST_LOW_RESERVE: + // case CHANGE_TRUST_SELF_NOT_ALLOWED: + // case CHANGE_TRUST_TRUST_LINE_MISSING: + // case CHANGE_TRUST_CANNOT_DELETE: + // case CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES: + // void; + // }; + // + // =========================================================================== + xdr.union("ChangeTrustResult", { + switchOn: xdr.lookup("ChangeTrustResultCode"), + switchName: "code", + switches: [["changeTrustSuccess", xdr["void"]()], ["changeTrustMalformed", xdr["void"]()], ["changeTrustNoIssuer", xdr["void"]()], ["changeTrustInvalidLimit", xdr["void"]()], ["changeTrustLowReserve", xdr["void"]()], ["changeTrustSelfNotAllowed", xdr["void"]()], ["changeTrustTrustLineMissing", xdr["void"]()], ["changeTrustCannotDelete", xdr["void"]()], ["changeTrustNotAuthMaintainLiabilities", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum AllowTrustResultCode + // { + // // codes considered as "success" for the operation + // ALLOW_TRUST_SUCCESS = 0, + // // codes considered as "failure" for the operation + // ALLOW_TRUST_MALFORMED = -1, // asset is not ASSET_TYPE_ALPHANUM + // ALLOW_TRUST_NO_TRUST_LINE = -2, // trustor does not have a trustline + // // source account does not require trust + // ALLOW_TRUST_TRUST_NOT_REQUIRED = -3, + // ALLOW_TRUST_CANT_REVOKE = -4, // source account can't revoke trust, + // ALLOW_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed + // ALLOW_TRUST_LOW_RESERVE = -6 // claimable balances can't be created + // // on revoke due to low reserves + // }; + // + // =========================================================================== + xdr["enum"]("AllowTrustResultCode", { + allowTrustSuccess: 0, + allowTrustMalformed: -1, + allowTrustNoTrustLine: -2, + allowTrustTrustNotRequired: -3, + allowTrustCantRevoke: -4, + allowTrustSelfNotAllowed: -5, + allowTrustLowReserve: -6 + }); + + // === xdr source ============================================================ + // + // union AllowTrustResult switch (AllowTrustResultCode code) + // { + // case ALLOW_TRUST_SUCCESS: + // void; + // case ALLOW_TRUST_MALFORMED: + // case ALLOW_TRUST_NO_TRUST_LINE: + // case ALLOW_TRUST_TRUST_NOT_REQUIRED: + // case ALLOW_TRUST_CANT_REVOKE: + // case ALLOW_TRUST_SELF_NOT_ALLOWED: + // case ALLOW_TRUST_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("AllowTrustResult", { + switchOn: xdr.lookup("AllowTrustResultCode"), + switchName: "code", + switches: [["allowTrustSuccess", xdr["void"]()], ["allowTrustMalformed", xdr["void"]()], ["allowTrustNoTrustLine", xdr["void"]()], ["allowTrustTrustNotRequired", xdr["void"]()], ["allowTrustCantRevoke", xdr["void"]()], ["allowTrustSelfNotAllowed", xdr["void"]()], ["allowTrustLowReserve", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum AccountMergeResultCode + // { + // // codes considered as "success" for the operation + // ACCOUNT_MERGE_SUCCESS = 0, + // // codes considered as "failure" for the operation + // ACCOUNT_MERGE_MALFORMED = -1, // can't merge onto itself + // ACCOUNT_MERGE_NO_ACCOUNT = -2, // destination does not exist + // ACCOUNT_MERGE_IMMUTABLE_SET = -3, // source account has AUTH_IMMUTABLE set + // ACCOUNT_MERGE_HAS_SUB_ENTRIES = -4, // account has trust lines/offers + // ACCOUNT_MERGE_SEQNUM_TOO_FAR = -5, // sequence number is over max allowed + // ACCOUNT_MERGE_DEST_FULL = -6, // can't add source balance to + // // destination balance + // ACCOUNT_MERGE_IS_SPONSOR = -7 // can't merge account that is a sponsor + // }; + // + // =========================================================================== + xdr["enum"]("AccountMergeResultCode", { + accountMergeSuccess: 0, + accountMergeMalformed: -1, + accountMergeNoAccount: -2, + accountMergeImmutableSet: -3, + accountMergeHasSubEntries: -4, + accountMergeSeqnumTooFar: -5, + accountMergeDestFull: -6, + accountMergeIsSponsor: -7 + }); + + // === xdr source ============================================================ + // + // union AccountMergeResult switch (AccountMergeResultCode code) + // { + // case ACCOUNT_MERGE_SUCCESS: + // int64 sourceAccountBalance; // how much got transferred from source account + // case ACCOUNT_MERGE_MALFORMED: + // case ACCOUNT_MERGE_NO_ACCOUNT: + // case ACCOUNT_MERGE_IMMUTABLE_SET: + // case ACCOUNT_MERGE_HAS_SUB_ENTRIES: + // case ACCOUNT_MERGE_SEQNUM_TOO_FAR: + // case ACCOUNT_MERGE_DEST_FULL: + // case ACCOUNT_MERGE_IS_SPONSOR: + // void; + // }; + // + // =========================================================================== + xdr.union("AccountMergeResult", { + switchOn: xdr.lookup("AccountMergeResultCode"), + switchName: "code", + switches: [["accountMergeSuccess", "sourceAccountBalance"], ["accountMergeMalformed", xdr["void"]()], ["accountMergeNoAccount", xdr["void"]()], ["accountMergeImmutableSet", xdr["void"]()], ["accountMergeHasSubEntries", xdr["void"]()], ["accountMergeSeqnumTooFar", xdr["void"]()], ["accountMergeDestFull", xdr["void"]()], ["accountMergeIsSponsor", xdr["void"]()]], + arms: { + sourceAccountBalance: xdr.lookup("Int64") + } + }); + + // === xdr source ============================================================ + // + // enum InflationResultCode + // { + // // codes considered as "success" for the operation + // INFLATION_SUCCESS = 0, + // // codes considered as "failure" for the operation + // INFLATION_NOT_TIME = -1 + // }; + // + // =========================================================================== + xdr["enum"]("InflationResultCode", { + inflationSuccess: 0, + inflationNotTime: -1 + }); + + // === xdr source ============================================================ + // + // struct InflationPayout // or use PaymentResultAtom to limit types? + // { + // AccountID destination; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("InflationPayout", [["destination", xdr.lookup("AccountId")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union InflationResult switch (InflationResultCode code) + // { + // case INFLATION_SUCCESS: + // InflationPayout payouts<>; + // case INFLATION_NOT_TIME: + // void; + // }; + // + // =========================================================================== + xdr.union("InflationResult", { + switchOn: xdr.lookup("InflationResultCode"), + switchName: "code", + switches: [["inflationSuccess", "payouts"], ["inflationNotTime", xdr["void"]()]], + arms: { + payouts: xdr.varArray(xdr.lookup("InflationPayout"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // enum ManageDataResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_DATA_SUCCESS = 0, + // // codes considered as "failure" for the operation + // MANAGE_DATA_NOT_SUPPORTED_YET = + // -1, // The network hasn't moved to this protocol change yet + // MANAGE_DATA_NAME_NOT_FOUND = + // -2, // Trying to remove a Data Entry that isn't there + // MANAGE_DATA_LOW_RESERVE = -3, // not enough funds to create a new Data Entry + // MANAGE_DATA_INVALID_NAME = -4 // Name not a valid string + // }; + // + // =========================================================================== + xdr["enum"]("ManageDataResultCode", { + manageDataSuccess: 0, + manageDataNotSupportedYet: -1, + manageDataNameNotFound: -2, + manageDataLowReserve: -3, + manageDataInvalidName: -4 + }); + + // === xdr source ============================================================ + // + // union ManageDataResult switch (ManageDataResultCode code) + // { + // case MANAGE_DATA_SUCCESS: + // void; + // case MANAGE_DATA_NOT_SUPPORTED_YET: + // case MANAGE_DATA_NAME_NOT_FOUND: + // case MANAGE_DATA_LOW_RESERVE: + // case MANAGE_DATA_INVALID_NAME: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageDataResult", { + switchOn: xdr.lookup("ManageDataResultCode"), + switchName: "code", + switches: [["manageDataSuccess", xdr["void"]()], ["manageDataNotSupportedYet", xdr["void"]()], ["manageDataNameNotFound", xdr["void"]()], ["manageDataLowReserve", xdr["void"]()], ["manageDataInvalidName", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum BumpSequenceResultCode + // { + // // codes considered as "success" for the operation + // BUMP_SEQUENCE_SUCCESS = 0, + // // codes considered as "failure" for the operation + // BUMP_SEQUENCE_BAD_SEQ = -1 // `bumpTo` is not within bounds + // }; + // + // =========================================================================== + xdr["enum"]("BumpSequenceResultCode", { + bumpSequenceSuccess: 0, + bumpSequenceBadSeq: -1 + }); + + // === xdr source ============================================================ + // + // union BumpSequenceResult switch (BumpSequenceResultCode code) + // { + // case BUMP_SEQUENCE_SUCCESS: + // void; + // case BUMP_SEQUENCE_BAD_SEQ: + // void; + // }; + // + // =========================================================================== + xdr.union("BumpSequenceResult", { + switchOn: xdr.lookup("BumpSequenceResultCode"), + switchName: "code", + switches: [["bumpSequenceSuccess", xdr["void"]()], ["bumpSequenceBadSeq", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum CreateClaimableBalanceResultCode + // { + // CREATE_CLAIMABLE_BALANCE_SUCCESS = 0, + // CREATE_CLAIMABLE_BALANCE_MALFORMED = -1, + // CREATE_CLAIMABLE_BALANCE_LOW_RESERVE = -2, + // CREATE_CLAIMABLE_BALANCE_NO_TRUST = -3, + // CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -4, + // CREATE_CLAIMABLE_BALANCE_UNDERFUNDED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("CreateClaimableBalanceResultCode", { + createClaimableBalanceSuccess: 0, + createClaimableBalanceMalformed: -1, + createClaimableBalanceLowReserve: -2, + createClaimableBalanceNoTrust: -3, + createClaimableBalanceNotAuthorized: -4, + createClaimableBalanceUnderfunded: -5 + }); + + // === xdr source ============================================================ + // + // union CreateClaimableBalanceResult switch ( + // CreateClaimableBalanceResultCode code) + // { + // case CREATE_CLAIMABLE_BALANCE_SUCCESS: + // ClaimableBalanceID balanceID; + // case CREATE_CLAIMABLE_BALANCE_MALFORMED: + // case CREATE_CLAIMABLE_BALANCE_LOW_RESERVE: + // case CREATE_CLAIMABLE_BALANCE_NO_TRUST: + // case CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED: + // case CREATE_CLAIMABLE_BALANCE_UNDERFUNDED: + // void; + // }; + // + // =========================================================================== + xdr.union("CreateClaimableBalanceResult", { + switchOn: xdr.lookup("CreateClaimableBalanceResultCode"), + switchName: "code", + switches: [["createClaimableBalanceSuccess", "balanceId"], ["createClaimableBalanceMalformed", xdr["void"]()], ["createClaimableBalanceLowReserve", xdr["void"]()], ["createClaimableBalanceNoTrust", xdr["void"]()], ["createClaimableBalanceNotAuthorized", xdr["void"]()], ["createClaimableBalanceUnderfunded", xdr["void"]()]], + arms: { + balanceId: xdr.lookup("ClaimableBalanceId") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimClaimableBalanceResultCode + // { + // CLAIM_CLAIMABLE_BALANCE_SUCCESS = 0, + // CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1, + // CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM = -2, + // CLAIM_CLAIMABLE_BALANCE_LINE_FULL = -3, + // CLAIM_CLAIMABLE_BALANCE_NO_TRUST = -4, + // CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimClaimableBalanceResultCode", { + claimClaimableBalanceSuccess: 0, + claimClaimableBalanceDoesNotExist: -1, + claimClaimableBalanceCannotClaim: -2, + claimClaimableBalanceLineFull: -3, + claimClaimableBalanceNoTrust: -4, + claimClaimableBalanceNotAuthorized: -5 + }); + + // === xdr source ============================================================ + // + // union ClaimClaimableBalanceResult switch (ClaimClaimableBalanceResultCode code) + // { + // case CLAIM_CLAIMABLE_BALANCE_SUCCESS: + // void; + // case CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST: + // case CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM: + // case CLAIM_CLAIMABLE_BALANCE_LINE_FULL: + // case CLAIM_CLAIMABLE_BALANCE_NO_TRUST: + // case CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClaimClaimableBalanceResult", { + switchOn: xdr.lookup("ClaimClaimableBalanceResultCode"), + switchName: "code", + switches: [["claimClaimableBalanceSuccess", xdr["void"]()], ["claimClaimableBalanceDoesNotExist", xdr["void"]()], ["claimClaimableBalanceCannotClaim", xdr["void"]()], ["claimClaimableBalanceLineFull", xdr["void"]()], ["claimClaimableBalanceNoTrust", xdr["void"]()], ["claimClaimableBalanceNotAuthorized", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum BeginSponsoringFutureReservesResultCode + // { + // // codes considered as "success" for the operation + // BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED = -1, + // BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED = -2, + // BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("BeginSponsoringFutureReservesResultCode", { + beginSponsoringFutureReservesSuccess: 0, + beginSponsoringFutureReservesMalformed: -1, + beginSponsoringFutureReservesAlreadySponsored: -2, + beginSponsoringFutureReservesRecursive: -3 + }); + + // === xdr source ============================================================ + // + // union BeginSponsoringFutureReservesResult switch ( + // BeginSponsoringFutureReservesResultCode code) + // { + // case BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS: + // void; + // case BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED: + // case BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED: + // case BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE: + // void; + // }; + // + // =========================================================================== + xdr.union("BeginSponsoringFutureReservesResult", { + switchOn: xdr.lookup("BeginSponsoringFutureReservesResultCode"), + switchName: "code", + switches: [["beginSponsoringFutureReservesSuccess", xdr["void"]()], ["beginSponsoringFutureReservesMalformed", xdr["void"]()], ["beginSponsoringFutureReservesAlreadySponsored", xdr["void"]()], ["beginSponsoringFutureReservesRecursive", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum EndSponsoringFutureReservesResultCode + // { + // // codes considered as "success" for the operation + // END_SPONSORING_FUTURE_RESERVES_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED = -1 + // }; + // + // =========================================================================== + xdr["enum"]("EndSponsoringFutureReservesResultCode", { + endSponsoringFutureReservesSuccess: 0, + endSponsoringFutureReservesNotSponsored: -1 + }); + + // === xdr source ============================================================ + // + // union EndSponsoringFutureReservesResult switch ( + // EndSponsoringFutureReservesResultCode code) + // { + // case END_SPONSORING_FUTURE_RESERVES_SUCCESS: + // void; + // case END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED: + // void; + // }; + // + // =========================================================================== + xdr.union("EndSponsoringFutureReservesResult", { + switchOn: xdr.lookup("EndSponsoringFutureReservesResultCode"), + switchName: "code", + switches: [["endSponsoringFutureReservesSuccess", xdr["void"]()], ["endSponsoringFutureReservesNotSponsored", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum RevokeSponsorshipResultCode + // { + // // codes considered as "success" for the operation + // REVOKE_SPONSORSHIP_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // REVOKE_SPONSORSHIP_DOES_NOT_EXIST = -1, + // REVOKE_SPONSORSHIP_NOT_SPONSOR = -2, + // REVOKE_SPONSORSHIP_LOW_RESERVE = -3, + // REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE = -4, + // REVOKE_SPONSORSHIP_MALFORMED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("RevokeSponsorshipResultCode", { + revokeSponsorshipSuccess: 0, + revokeSponsorshipDoesNotExist: -1, + revokeSponsorshipNotSponsor: -2, + revokeSponsorshipLowReserve: -3, + revokeSponsorshipOnlyTransferable: -4, + revokeSponsorshipMalformed: -5 + }); + + // === xdr source ============================================================ + // + // union RevokeSponsorshipResult switch (RevokeSponsorshipResultCode code) + // { + // case REVOKE_SPONSORSHIP_SUCCESS: + // void; + // case REVOKE_SPONSORSHIP_DOES_NOT_EXIST: + // case REVOKE_SPONSORSHIP_NOT_SPONSOR: + // case REVOKE_SPONSORSHIP_LOW_RESERVE: + // case REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE: + // case REVOKE_SPONSORSHIP_MALFORMED: + // void; + // }; + // + // =========================================================================== + xdr.union("RevokeSponsorshipResult", { + switchOn: xdr.lookup("RevokeSponsorshipResultCode"), + switchName: "code", + switches: [["revokeSponsorshipSuccess", xdr["void"]()], ["revokeSponsorshipDoesNotExist", xdr["void"]()], ["revokeSponsorshipNotSponsor", xdr["void"]()], ["revokeSponsorshipLowReserve", xdr["void"]()], ["revokeSponsorshipOnlyTransferable", xdr["void"]()], ["revokeSponsorshipMalformed", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ClawbackResultCode + // { + // // codes considered as "success" for the operation + // CLAWBACK_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // CLAWBACK_MALFORMED = -1, + // CLAWBACK_NOT_CLAWBACK_ENABLED = -2, + // CLAWBACK_NO_TRUST = -3, + // CLAWBACK_UNDERFUNDED = -4 + // }; + // + // =========================================================================== + xdr["enum"]("ClawbackResultCode", { + clawbackSuccess: 0, + clawbackMalformed: -1, + clawbackNotClawbackEnabled: -2, + clawbackNoTrust: -3, + clawbackUnderfunded: -4 + }); + + // === xdr source ============================================================ + // + // union ClawbackResult switch (ClawbackResultCode code) + // { + // case CLAWBACK_SUCCESS: + // void; + // case CLAWBACK_MALFORMED: + // case CLAWBACK_NOT_CLAWBACK_ENABLED: + // case CLAWBACK_NO_TRUST: + // case CLAWBACK_UNDERFUNDED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClawbackResult", { + switchOn: xdr.lookup("ClawbackResultCode"), + switchName: "code", + switches: [["clawbackSuccess", xdr["void"]()], ["clawbackMalformed", xdr["void"]()], ["clawbackNotClawbackEnabled", xdr["void"]()], ["clawbackNoTrust", xdr["void"]()], ["clawbackUnderfunded", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ClawbackClaimableBalanceResultCode + // { + // // codes considered as "success" for the operation + // CLAWBACK_CLAIMABLE_BALANCE_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1, + // CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER = -2, + // CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED = -3 + // }; + // + // =========================================================================== + xdr["enum"]("ClawbackClaimableBalanceResultCode", { + clawbackClaimableBalanceSuccess: 0, + clawbackClaimableBalanceDoesNotExist: -1, + clawbackClaimableBalanceNotIssuer: -2, + clawbackClaimableBalanceNotClawbackEnabled: -3 + }); + + // === xdr source ============================================================ + // + // union ClawbackClaimableBalanceResult switch ( + // ClawbackClaimableBalanceResultCode code) + // { + // case CLAWBACK_CLAIMABLE_BALANCE_SUCCESS: + // void; + // case CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST: + // case CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER: + // case CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClawbackClaimableBalanceResult", { + switchOn: xdr.lookup("ClawbackClaimableBalanceResultCode"), + switchName: "code", + switches: [["clawbackClaimableBalanceSuccess", xdr["void"]()], ["clawbackClaimableBalanceDoesNotExist", xdr["void"]()], ["clawbackClaimableBalanceNotIssuer", xdr["void"]()], ["clawbackClaimableBalanceNotClawbackEnabled", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum SetTrustLineFlagsResultCode + // { + // // codes considered as "success" for the operation + // SET_TRUST_LINE_FLAGS_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // SET_TRUST_LINE_FLAGS_MALFORMED = -1, + // SET_TRUST_LINE_FLAGS_NO_TRUST_LINE = -2, + // SET_TRUST_LINE_FLAGS_CANT_REVOKE = -3, + // SET_TRUST_LINE_FLAGS_INVALID_STATE = -4, + // SET_TRUST_LINE_FLAGS_LOW_RESERVE = -5 // claimable balances can't be created + // // on revoke due to low reserves + // }; + // + // =========================================================================== + xdr["enum"]("SetTrustLineFlagsResultCode", { + setTrustLineFlagsSuccess: 0, + setTrustLineFlagsMalformed: -1, + setTrustLineFlagsNoTrustLine: -2, + setTrustLineFlagsCantRevoke: -3, + setTrustLineFlagsInvalidState: -4, + setTrustLineFlagsLowReserve: -5 + }); + + // === xdr source ============================================================ + // + // union SetTrustLineFlagsResult switch (SetTrustLineFlagsResultCode code) + // { + // case SET_TRUST_LINE_FLAGS_SUCCESS: + // void; + // case SET_TRUST_LINE_FLAGS_MALFORMED: + // case SET_TRUST_LINE_FLAGS_NO_TRUST_LINE: + // case SET_TRUST_LINE_FLAGS_CANT_REVOKE: + // case SET_TRUST_LINE_FLAGS_INVALID_STATE: + // case SET_TRUST_LINE_FLAGS_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("SetTrustLineFlagsResult", { + switchOn: xdr.lookup("SetTrustLineFlagsResultCode"), + switchName: "code", + switches: [["setTrustLineFlagsSuccess", xdr["void"]()], ["setTrustLineFlagsMalformed", xdr["void"]()], ["setTrustLineFlagsNoTrustLine", xdr["void"]()], ["setTrustLineFlagsCantRevoke", xdr["void"]()], ["setTrustLineFlagsInvalidState", xdr["void"]()], ["setTrustLineFlagsLowReserve", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum LiquidityPoolDepositResultCode + // { + // // codes considered as "success" for the operation + // LIQUIDITY_POOL_DEPOSIT_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // LIQUIDITY_POOL_DEPOSIT_MALFORMED = -1, // bad input + // LIQUIDITY_POOL_DEPOSIT_NO_TRUST = -2, // no trust line for one of the + // // assets + // LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED = -3, // not authorized for one of the + // // assets + // LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED = -4, // not enough balance for one of + // // the assets + // LIQUIDITY_POOL_DEPOSIT_LINE_FULL = -5, // pool share trust line doesn't + // // have sufficient limit + // LIQUIDITY_POOL_DEPOSIT_BAD_PRICE = -6, // deposit price outside bounds + // LIQUIDITY_POOL_DEPOSIT_POOL_FULL = -7 // pool reserves are full + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolDepositResultCode", { + liquidityPoolDepositSuccess: 0, + liquidityPoolDepositMalformed: -1, + liquidityPoolDepositNoTrust: -2, + liquidityPoolDepositNotAuthorized: -3, + liquidityPoolDepositUnderfunded: -4, + liquidityPoolDepositLineFull: -5, + liquidityPoolDepositBadPrice: -6, + liquidityPoolDepositPoolFull: -7 + }); + + // === xdr source ============================================================ + // + // union LiquidityPoolDepositResult switch (LiquidityPoolDepositResultCode code) + // { + // case LIQUIDITY_POOL_DEPOSIT_SUCCESS: + // void; + // case LIQUIDITY_POOL_DEPOSIT_MALFORMED: + // case LIQUIDITY_POOL_DEPOSIT_NO_TRUST: + // case LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED: + // case LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED: + // case LIQUIDITY_POOL_DEPOSIT_LINE_FULL: + // case LIQUIDITY_POOL_DEPOSIT_BAD_PRICE: + // case LIQUIDITY_POOL_DEPOSIT_POOL_FULL: + // void; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolDepositResult", { + switchOn: xdr.lookup("LiquidityPoolDepositResultCode"), + switchName: "code", + switches: [["liquidityPoolDepositSuccess", xdr["void"]()], ["liquidityPoolDepositMalformed", xdr["void"]()], ["liquidityPoolDepositNoTrust", xdr["void"]()], ["liquidityPoolDepositNotAuthorized", xdr["void"]()], ["liquidityPoolDepositUnderfunded", xdr["void"]()], ["liquidityPoolDepositLineFull", xdr["void"]()], ["liquidityPoolDepositBadPrice", xdr["void"]()], ["liquidityPoolDepositPoolFull", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum LiquidityPoolWithdrawResultCode + // { + // // codes considered as "success" for the operation + // LIQUIDITY_POOL_WITHDRAW_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // LIQUIDITY_POOL_WITHDRAW_MALFORMED = -1, // bad input + // LIQUIDITY_POOL_WITHDRAW_NO_TRUST = -2, // no trust line for one of the + // // assets + // LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED = -3, // not enough balance of the + // // pool share + // LIQUIDITY_POOL_WITHDRAW_LINE_FULL = -4, // would go above limit for one + // // of the assets + // LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM = -5 // didn't withdraw enough + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolWithdrawResultCode", { + liquidityPoolWithdrawSuccess: 0, + liquidityPoolWithdrawMalformed: -1, + liquidityPoolWithdrawNoTrust: -2, + liquidityPoolWithdrawUnderfunded: -3, + liquidityPoolWithdrawLineFull: -4, + liquidityPoolWithdrawUnderMinimum: -5 + }); + + // === xdr source ============================================================ + // + // union LiquidityPoolWithdrawResult switch (LiquidityPoolWithdrawResultCode code) + // { + // case LIQUIDITY_POOL_WITHDRAW_SUCCESS: + // void; + // case LIQUIDITY_POOL_WITHDRAW_MALFORMED: + // case LIQUIDITY_POOL_WITHDRAW_NO_TRUST: + // case LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED: + // case LIQUIDITY_POOL_WITHDRAW_LINE_FULL: + // case LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM: + // void; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolWithdrawResult", { + switchOn: xdr.lookup("LiquidityPoolWithdrawResultCode"), + switchName: "code", + switches: [["liquidityPoolWithdrawSuccess", xdr["void"]()], ["liquidityPoolWithdrawMalformed", xdr["void"]()], ["liquidityPoolWithdrawNoTrust", xdr["void"]()], ["liquidityPoolWithdrawUnderfunded", xdr["void"]()], ["liquidityPoolWithdrawLineFull", xdr["void"]()], ["liquidityPoolWithdrawUnderMinimum", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum InvokeHostFunctionResultCode + // { + // // codes considered as "success" for the operation + // INVOKE_HOST_FUNCTION_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // INVOKE_HOST_FUNCTION_MALFORMED = -1, + // INVOKE_HOST_FUNCTION_TRAPPED = -2, + // INVOKE_HOST_FUNCTION_RESOURCE_LIMIT_EXCEEDED = -3, + // INVOKE_HOST_FUNCTION_ENTRY_ARCHIVED = -4, + // INVOKE_HOST_FUNCTION_INSUFFICIENT_REFUNDABLE_FEE = -5 + // }; + // + // =========================================================================== + xdr["enum"]("InvokeHostFunctionResultCode", { + invokeHostFunctionSuccess: 0, + invokeHostFunctionMalformed: -1, + invokeHostFunctionTrapped: -2, + invokeHostFunctionResourceLimitExceeded: -3, + invokeHostFunctionEntryArchived: -4, + invokeHostFunctionInsufficientRefundableFee: -5 + }); + + // === xdr source ============================================================ + // + // union InvokeHostFunctionResult switch (InvokeHostFunctionResultCode code) + // { + // case INVOKE_HOST_FUNCTION_SUCCESS: + // Hash success; // sha256(InvokeHostFunctionSuccessPreImage) + // case INVOKE_HOST_FUNCTION_MALFORMED: + // case INVOKE_HOST_FUNCTION_TRAPPED: + // case INVOKE_HOST_FUNCTION_RESOURCE_LIMIT_EXCEEDED: + // case INVOKE_HOST_FUNCTION_ENTRY_ARCHIVED: + // case INVOKE_HOST_FUNCTION_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("InvokeHostFunctionResult", { + switchOn: xdr.lookup("InvokeHostFunctionResultCode"), + switchName: "code", + switches: [["invokeHostFunctionSuccess", "success"], ["invokeHostFunctionMalformed", xdr["void"]()], ["invokeHostFunctionTrapped", xdr["void"]()], ["invokeHostFunctionResourceLimitExceeded", xdr["void"]()], ["invokeHostFunctionEntryArchived", xdr["void"]()], ["invokeHostFunctionInsufficientRefundableFee", xdr["void"]()]], + arms: { + success: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum ExtendFootprintTTLResultCode + // { + // // codes considered as "success" for the operation + // EXTEND_FOOTPRINT_TTL_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // EXTEND_FOOTPRINT_TTL_MALFORMED = -1, + // EXTEND_FOOTPRINT_TTL_RESOURCE_LIMIT_EXCEEDED = -2, + // EXTEND_FOOTPRINT_TTL_INSUFFICIENT_REFUNDABLE_FEE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("ExtendFootprintTtlResultCode", { + extendFootprintTtlSuccess: 0, + extendFootprintTtlMalformed: -1, + extendFootprintTtlResourceLimitExceeded: -2, + extendFootprintTtlInsufficientRefundableFee: -3 + }); + + // === xdr source ============================================================ + // + // union ExtendFootprintTTLResult switch (ExtendFootprintTTLResultCode code) + // { + // case EXTEND_FOOTPRINT_TTL_SUCCESS: + // void; + // case EXTEND_FOOTPRINT_TTL_MALFORMED: + // case EXTEND_FOOTPRINT_TTL_RESOURCE_LIMIT_EXCEEDED: + // case EXTEND_FOOTPRINT_TTL_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("ExtendFootprintTtlResult", { + switchOn: xdr.lookup("ExtendFootprintTtlResultCode"), + switchName: "code", + switches: [["extendFootprintTtlSuccess", xdr["void"]()], ["extendFootprintTtlMalformed", xdr["void"]()], ["extendFootprintTtlResourceLimitExceeded", xdr["void"]()], ["extendFootprintTtlInsufficientRefundableFee", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum RestoreFootprintResultCode + // { + // // codes considered as "success" for the operation + // RESTORE_FOOTPRINT_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // RESTORE_FOOTPRINT_MALFORMED = -1, + // RESTORE_FOOTPRINT_RESOURCE_LIMIT_EXCEEDED = -2, + // RESTORE_FOOTPRINT_INSUFFICIENT_REFUNDABLE_FEE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("RestoreFootprintResultCode", { + restoreFootprintSuccess: 0, + restoreFootprintMalformed: -1, + restoreFootprintResourceLimitExceeded: -2, + restoreFootprintInsufficientRefundableFee: -3 + }); + + // === xdr source ============================================================ + // + // union RestoreFootprintResult switch (RestoreFootprintResultCode code) + // { + // case RESTORE_FOOTPRINT_SUCCESS: + // void; + // case RESTORE_FOOTPRINT_MALFORMED: + // case RESTORE_FOOTPRINT_RESOURCE_LIMIT_EXCEEDED: + // case RESTORE_FOOTPRINT_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("RestoreFootprintResult", { + switchOn: xdr.lookup("RestoreFootprintResultCode"), + switchName: "code", + switches: [["restoreFootprintSuccess", xdr["void"]()], ["restoreFootprintMalformed", xdr["void"]()], ["restoreFootprintResourceLimitExceeded", xdr["void"]()], ["restoreFootprintInsufficientRefundableFee", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum OperationResultCode + // { + // opINNER = 0, // inner object result is valid + // + // opBAD_AUTH = -1, // too few valid signatures / wrong network + // opNO_ACCOUNT = -2, // source account was not found + // opNOT_SUPPORTED = -3, // operation not supported at this time + // opTOO_MANY_SUBENTRIES = -4, // max number of subentries already reached + // opEXCEEDED_WORK_LIMIT = -5, // operation did too much work + // opTOO_MANY_SPONSORING = -6 // account is sponsoring too many entries + // }; + // + // =========================================================================== + xdr["enum"]("OperationResultCode", { + opInner: 0, + opBadAuth: -1, + opNoAccount: -2, + opNotSupported: -3, + opTooManySubentries: -4, + opExceededWorkLimit: -5, + opTooManySponsoring: -6 + }); + + // === xdr source ============================================================ + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountResult createAccountResult; + // case PAYMENT: + // PaymentResult paymentResult; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult; + // case MANAGE_SELL_OFFER: + // ManageSellOfferResult manageSellOfferResult; + // case CREATE_PASSIVE_SELL_OFFER: + // ManageSellOfferResult createPassiveSellOfferResult; + // case SET_OPTIONS: + // SetOptionsResult setOptionsResult; + // case CHANGE_TRUST: + // ChangeTrustResult changeTrustResult; + // case ALLOW_TRUST: + // AllowTrustResult allowTrustResult; + // case ACCOUNT_MERGE: + // AccountMergeResult accountMergeResult; + // case INFLATION: + // InflationResult inflationResult; + // case MANAGE_DATA: + // ManageDataResult manageDataResult; + // case BUMP_SEQUENCE: + // BumpSequenceResult bumpSeqResult; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferResult manageBuyOfferResult; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendResult pathPaymentStrictSendResult; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceResult createClaimableBalanceResult; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceResult claimClaimableBalanceResult; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult; + // case END_SPONSORING_FUTURE_RESERVES: + // EndSponsoringFutureReservesResult endSponsoringFutureReservesResult; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipResult revokeSponsorshipResult; + // case CLAWBACK: + // ClawbackResult clawbackResult; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceResult clawbackClaimableBalanceResult; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsResult setTrustLineFlagsResult; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositResult liquidityPoolDepositResult; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawResult liquidityPoolWithdrawResult; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionResult invokeHostFunctionResult; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLResult extendFootprintTTLResult; + // case RESTORE_FOOTPRINT: + // RestoreFootprintResult restoreFootprintResult; + // } + // + // =========================================================================== + xdr.union("OperationResultTr", { + switchOn: xdr.lookup("OperationType"), + switchName: "type", + switches: [["createAccount", "createAccountResult"], ["payment", "paymentResult"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveResult"], ["manageSellOffer", "manageSellOfferResult"], ["createPassiveSellOffer", "createPassiveSellOfferResult"], ["setOptions", "setOptionsResult"], ["changeTrust", "changeTrustResult"], ["allowTrust", "allowTrustResult"], ["accountMerge", "accountMergeResult"], ["inflation", "inflationResult"], ["manageData", "manageDataResult"], ["bumpSequence", "bumpSeqResult"], ["manageBuyOffer", "manageBuyOfferResult"], ["pathPaymentStrictSend", "pathPaymentStrictSendResult"], ["createClaimableBalance", "createClaimableBalanceResult"], ["claimClaimableBalance", "claimClaimableBalanceResult"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesResult"], ["endSponsoringFutureReserves", "endSponsoringFutureReservesResult"], ["revokeSponsorship", "revokeSponsorshipResult"], ["clawback", "clawbackResult"], ["clawbackClaimableBalance", "clawbackClaimableBalanceResult"], ["setTrustLineFlags", "setTrustLineFlagsResult"], ["liquidityPoolDeposit", "liquidityPoolDepositResult"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawResult"], ["invokeHostFunction", "invokeHostFunctionResult"], ["extendFootprintTtl", "extendFootprintTtlResult"], ["restoreFootprint", "restoreFootprintResult"]], + arms: { + createAccountResult: xdr.lookup("CreateAccountResult"), + paymentResult: xdr.lookup("PaymentResult"), + pathPaymentStrictReceiveResult: xdr.lookup("PathPaymentStrictReceiveResult"), + manageSellOfferResult: xdr.lookup("ManageSellOfferResult"), + createPassiveSellOfferResult: xdr.lookup("ManageSellOfferResult"), + setOptionsResult: xdr.lookup("SetOptionsResult"), + changeTrustResult: xdr.lookup("ChangeTrustResult"), + allowTrustResult: xdr.lookup("AllowTrustResult"), + accountMergeResult: xdr.lookup("AccountMergeResult"), + inflationResult: xdr.lookup("InflationResult"), + manageDataResult: xdr.lookup("ManageDataResult"), + bumpSeqResult: xdr.lookup("BumpSequenceResult"), + manageBuyOfferResult: xdr.lookup("ManageBuyOfferResult"), + pathPaymentStrictSendResult: xdr.lookup("PathPaymentStrictSendResult"), + createClaimableBalanceResult: xdr.lookup("CreateClaimableBalanceResult"), + claimClaimableBalanceResult: xdr.lookup("ClaimClaimableBalanceResult"), + beginSponsoringFutureReservesResult: xdr.lookup("BeginSponsoringFutureReservesResult"), + endSponsoringFutureReservesResult: xdr.lookup("EndSponsoringFutureReservesResult"), + revokeSponsorshipResult: xdr.lookup("RevokeSponsorshipResult"), + clawbackResult: xdr.lookup("ClawbackResult"), + clawbackClaimableBalanceResult: xdr.lookup("ClawbackClaimableBalanceResult"), + setTrustLineFlagsResult: xdr.lookup("SetTrustLineFlagsResult"), + liquidityPoolDepositResult: xdr.lookup("LiquidityPoolDepositResult"), + liquidityPoolWithdrawResult: xdr.lookup("LiquidityPoolWithdrawResult"), + invokeHostFunctionResult: xdr.lookup("InvokeHostFunctionResult"), + extendFootprintTtlResult: xdr.lookup("ExtendFootprintTtlResult"), + restoreFootprintResult: xdr.lookup("RestoreFootprintResult") + } + }); + + // === xdr source ============================================================ + // + // union OperationResult switch (OperationResultCode code) + // { + // case opINNER: + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountResult createAccountResult; + // case PAYMENT: + // PaymentResult paymentResult; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult; + // case MANAGE_SELL_OFFER: + // ManageSellOfferResult manageSellOfferResult; + // case CREATE_PASSIVE_SELL_OFFER: + // ManageSellOfferResult createPassiveSellOfferResult; + // case SET_OPTIONS: + // SetOptionsResult setOptionsResult; + // case CHANGE_TRUST: + // ChangeTrustResult changeTrustResult; + // case ALLOW_TRUST: + // AllowTrustResult allowTrustResult; + // case ACCOUNT_MERGE: + // AccountMergeResult accountMergeResult; + // case INFLATION: + // InflationResult inflationResult; + // case MANAGE_DATA: + // ManageDataResult manageDataResult; + // case BUMP_SEQUENCE: + // BumpSequenceResult bumpSeqResult; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferResult manageBuyOfferResult; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendResult pathPaymentStrictSendResult; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceResult createClaimableBalanceResult; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceResult claimClaimableBalanceResult; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult; + // case END_SPONSORING_FUTURE_RESERVES: + // EndSponsoringFutureReservesResult endSponsoringFutureReservesResult; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipResult revokeSponsorshipResult; + // case CLAWBACK: + // ClawbackResult clawbackResult; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceResult clawbackClaimableBalanceResult; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsResult setTrustLineFlagsResult; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositResult liquidityPoolDepositResult; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawResult liquidityPoolWithdrawResult; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionResult invokeHostFunctionResult; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLResult extendFootprintTTLResult; + // case RESTORE_FOOTPRINT: + // RestoreFootprintResult restoreFootprintResult; + // } + // tr; + // case opBAD_AUTH: + // case opNO_ACCOUNT: + // case opNOT_SUPPORTED: + // case opTOO_MANY_SUBENTRIES: + // case opEXCEEDED_WORK_LIMIT: + // case opTOO_MANY_SPONSORING: + // void; + // }; + // + // =========================================================================== + xdr.union("OperationResult", { + switchOn: xdr.lookup("OperationResultCode"), + switchName: "code", + switches: [["opInner", "tr"], ["opBadAuth", xdr["void"]()], ["opNoAccount", xdr["void"]()], ["opNotSupported", xdr["void"]()], ["opTooManySubentries", xdr["void"]()], ["opExceededWorkLimit", xdr["void"]()], ["opTooManySponsoring", xdr["void"]()]], + arms: { + tr: xdr.lookup("OperationResultTr") + } + }); + + // === xdr source ============================================================ + // + // enum TransactionResultCode + // { + // txFEE_BUMP_INNER_SUCCESS = 1, // fee bump inner transaction succeeded + // txSUCCESS = 0, // all operations succeeded + // + // txFAILED = -1, // one of the operations failed (none were applied) + // + // txTOO_EARLY = -2, // ledger closeTime before minTime + // txTOO_LATE = -3, // ledger closeTime after maxTime + // txMISSING_OPERATION = -4, // no operation was specified + // txBAD_SEQ = -5, // sequence number does not match source account + // + // txBAD_AUTH = -6, // too few valid signatures / wrong network + // txINSUFFICIENT_BALANCE = -7, // fee would bring account below reserve + // txNO_ACCOUNT = -8, // source account not found + // txINSUFFICIENT_FEE = -9, // fee is too small + // txBAD_AUTH_EXTRA = -10, // unused signatures attached to transaction + // txINTERNAL_ERROR = -11, // an unknown error occurred + // + // txNOT_SUPPORTED = -12, // transaction type not supported + // txFEE_BUMP_INNER_FAILED = -13, // fee bump inner transaction failed + // txBAD_SPONSORSHIP = -14, // sponsorship not confirmed + // txBAD_MIN_SEQ_AGE_OR_GAP = -15, // minSeqAge or minSeqLedgerGap conditions not met + // txMALFORMED = -16, // precondition is invalid + // txSOROBAN_INVALID = -17 // soroban-specific preconditions were not met + // }; + // + // =========================================================================== + xdr["enum"]("TransactionResultCode", { + txFeeBumpInnerSuccess: 1, + txSuccess: 0, + txFailed: -1, + txTooEarly: -2, + txTooLate: -3, + txMissingOperation: -4, + txBadSeq: -5, + txBadAuth: -6, + txInsufficientBalance: -7, + txNoAccount: -8, + txInsufficientFee: -9, + txBadAuthExtra: -10, + txInternalError: -11, + txNotSupported: -12, + txFeeBumpInnerFailed: -13, + txBadSponsorship: -14, + txBadMinSeqAgeOrGap: -15, + txMalformed: -16, + txSorobanInvalid: -17 + }); + + // === xdr source ============================================================ + // + // union switch (TransactionResultCode code) + // { + // // txFEE_BUMP_INNER_SUCCESS is not included + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // txFEE_BUMP_INNER_FAILED is not included + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // + // =========================================================================== + xdr.union("InnerTransactionResultResult", { + switchOn: xdr.lookup("TransactionResultCode"), + switchName: "code", + switches: [["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr["void"]()], ["txTooLate", xdr["void"]()], ["txMissingOperation", xdr["void"]()], ["txBadSeq", xdr["void"]()], ["txBadAuth", xdr["void"]()], ["txInsufficientBalance", xdr["void"]()], ["txNoAccount", xdr["void"]()], ["txInsufficientFee", xdr["void"]()], ["txBadAuthExtra", xdr["void"]()], ["txInternalError", xdr["void"]()], ["txNotSupported", xdr["void"]()], ["txBadSponsorship", xdr["void"]()], ["txBadMinSeqAgeOrGap", xdr["void"]()], ["txMalformed", xdr["void"]()], ["txSorobanInvalid", xdr["void"]()]], + arms: { + results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("InnerTransactionResultExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct InnerTransactionResult + // { + // // Always 0. Here for binary compatibility. + // int64 feeCharged; + // + // union switch (TransactionResultCode code) + // { + // // txFEE_BUMP_INNER_SUCCESS is not included + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // txFEE_BUMP_INNER_FAILED is not included + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // result; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("InnerTransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("InnerTransactionResultResult")], ["ext", xdr.lookup("InnerTransactionResultExt")]]); + + // === xdr source ============================================================ + // + // struct InnerTransactionResultPair + // { + // Hash transactionHash; // hash of the inner transaction + // InnerTransactionResult result; // result for the inner transaction + // }; + // + // =========================================================================== + xdr.struct("InnerTransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("InnerTransactionResult")]]); + + // === xdr source ============================================================ + // + // union switch (TransactionResultCode code) + // { + // case txFEE_BUMP_INNER_SUCCESS: + // case txFEE_BUMP_INNER_FAILED: + // InnerTransactionResultPair innerResultPair; + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // case txFEE_BUMP_INNER_FAILED: handled above + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionResultResult", { + switchOn: xdr.lookup("TransactionResultCode"), + switchName: "code", + switches: [["txFeeBumpInnerSuccess", "innerResultPair"], ["txFeeBumpInnerFailed", "innerResultPair"], ["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr["void"]()], ["txTooLate", xdr["void"]()], ["txMissingOperation", xdr["void"]()], ["txBadSeq", xdr["void"]()], ["txBadAuth", xdr["void"]()], ["txInsufficientBalance", xdr["void"]()], ["txNoAccount", xdr["void"]()], ["txInsufficientFee", xdr["void"]()], ["txBadAuthExtra", xdr["void"]()], ["txInternalError", xdr["void"]()], ["txNotSupported", xdr["void"]()], ["txBadSponsorship", xdr["void"]()], ["txBadMinSeqAgeOrGap", xdr["void"]()], ["txMalformed", xdr["void"]()], ["txSorobanInvalid", xdr["void"]()]], + arms: { + innerResultPair: xdr.lookup("InnerTransactionResultPair"), + results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionResultExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionResult + // { + // int64 feeCharged; // actual fee charged for the transaction + // + // union switch (TransactionResultCode code) + // { + // case txFEE_BUMP_INNER_SUCCESS: + // case txFEE_BUMP_INNER_FAILED: + // InnerTransactionResultPair innerResultPair; + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // case txFEE_BUMP_INNER_FAILED: handled above + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // result; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("TransactionResultResult")], ["ext", xdr.lookup("TransactionResultExt")]]); + + // === xdr source ============================================================ + // + // typedef opaque Hash[32]; + // + // =========================================================================== + xdr.typedef("Hash", xdr.opaque(32)); + + // === xdr source ============================================================ + // + // typedef opaque uint256[32]; + // + // =========================================================================== + xdr.typedef("Uint256", xdr.opaque(32)); + + // === xdr source ============================================================ + // + // typedef unsigned int uint32; + // + // =========================================================================== + xdr.typedef("Uint32", xdr.uint()); + + // === xdr source ============================================================ + // + // typedef int int32; + // + // =========================================================================== + xdr.typedef("Int32", xdr["int"]()); + + // === xdr source ============================================================ + // + // typedef unsigned hyper uint64; + // + // =========================================================================== + xdr.typedef("Uint64", xdr.uhyper()); + + // === xdr source ============================================================ + // + // typedef hyper int64; + // + // =========================================================================== + xdr.typedef("Int64", xdr.hyper()); + + // === xdr source ============================================================ + // + // typedef uint64 TimePoint; + // + // =========================================================================== + xdr.typedef("TimePoint", xdr.lookup("Uint64")); + + // === xdr source ============================================================ + // + // typedef uint64 Duration; + // + // =========================================================================== + xdr.typedef("Duration", xdr.lookup("Uint64")); + + // === xdr source ============================================================ + // + // union ExtensionPoint switch (int v) + // { + // case 0: + // void; + // }; + // + // =========================================================================== + xdr.union("ExtensionPoint", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum CryptoKeyType + // { + // KEY_TYPE_ED25519 = 0, + // KEY_TYPE_PRE_AUTH_TX = 1, + // KEY_TYPE_HASH_X = 2, + // KEY_TYPE_ED25519_SIGNED_PAYLOAD = 3, + // // MUXED enum values for supported type are derived from the enum values + // // above by ORing them with 0x100 + // KEY_TYPE_MUXED_ED25519 = 0x100 + // }; + // + // =========================================================================== + xdr["enum"]("CryptoKeyType", { + keyTypeEd25519: 0, + keyTypePreAuthTx: 1, + keyTypeHashX: 2, + keyTypeEd25519SignedPayload: 3, + keyTypeMuxedEd25519: 256 + }); + + // === xdr source ============================================================ + // + // enum PublicKeyType + // { + // PUBLIC_KEY_TYPE_ED25519 = KEY_TYPE_ED25519 + // }; + // + // =========================================================================== + xdr["enum"]("PublicKeyType", { + publicKeyTypeEd25519: 0 + }); + + // === xdr source ============================================================ + // + // enum SignerKeyType + // { + // SIGNER_KEY_TYPE_ED25519 = KEY_TYPE_ED25519, + // SIGNER_KEY_TYPE_PRE_AUTH_TX = KEY_TYPE_PRE_AUTH_TX, + // SIGNER_KEY_TYPE_HASH_X = KEY_TYPE_HASH_X, + // SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD = KEY_TYPE_ED25519_SIGNED_PAYLOAD + // }; + // + // =========================================================================== + xdr["enum"]("SignerKeyType", { + signerKeyTypeEd25519: 0, + signerKeyTypePreAuthTx: 1, + signerKeyTypeHashX: 2, + signerKeyTypeEd25519SignedPayload: 3 + }); + + // === xdr source ============================================================ + // + // union PublicKey switch (PublicKeyType type) + // { + // case PUBLIC_KEY_TYPE_ED25519: + // uint256 ed25519; + // }; + // + // =========================================================================== + xdr.union("PublicKey", { + switchOn: xdr.lookup("PublicKeyType"), + switchName: "type", + switches: [["publicKeyTypeEd25519", "ed25519"]], + arms: { + ed25519: xdr.lookup("Uint256") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // /* Public key that must sign the payload. */ + // uint256 ed25519; + // /* Payload to be raw signed by ed25519. */ + // opaque payload<64>; + // } + // + // =========================================================================== + xdr.struct("SignerKeyEd25519SignedPayload", [["ed25519", xdr.lookup("Uint256")], ["payload", xdr.varOpaque(64)]]); + + // === xdr source ============================================================ + // + // union SignerKey switch (SignerKeyType type) + // { + // case SIGNER_KEY_TYPE_ED25519: + // uint256 ed25519; + // case SIGNER_KEY_TYPE_PRE_AUTH_TX: + // /* SHA-256 Hash of TransactionSignaturePayload structure */ + // uint256 preAuthTx; + // case SIGNER_KEY_TYPE_HASH_X: + // /* Hash of random 256 bit preimage X */ + // uint256 hashX; + // case SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD: + // struct + // { + // /* Public key that must sign the payload. */ + // uint256 ed25519; + // /* Payload to be raw signed by ed25519. */ + // opaque payload<64>; + // } ed25519SignedPayload; + // }; + // + // =========================================================================== + xdr.union("SignerKey", { + switchOn: xdr.lookup("SignerKeyType"), + switchName: "type", + switches: [["signerKeyTypeEd25519", "ed25519"], ["signerKeyTypePreAuthTx", "preAuthTx"], ["signerKeyTypeHashX", "hashX"], ["signerKeyTypeEd25519SignedPayload", "ed25519SignedPayload"]], + arms: { + ed25519: xdr.lookup("Uint256"), + preAuthTx: xdr.lookup("Uint256"), + hashX: xdr.lookup("Uint256"), + ed25519SignedPayload: xdr.lookup("SignerKeyEd25519SignedPayload") + } + }); + + // === xdr source ============================================================ + // + // typedef opaque Signature<64>; + // + // =========================================================================== + xdr.typedef("Signature", xdr.varOpaque(64)); + + // === xdr source ============================================================ + // + // typedef opaque SignatureHint[4]; + // + // =========================================================================== + xdr.typedef("SignatureHint", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef PublicKey NodeID; + // + // =========================================================================== + xdr.typedef("NodeId", xdr.lookup("PublicKey")); + + // === xdr source ============================================================ + // + // typedef PublicKey AccountID; + // + // =========================================================================== + xdr.typedef("AccountId", xdr.lookup("PublicKey")); + + // === xdr source ============================================================ + // + // struct Curve25519Secret + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("Curve25519Secret", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct Curve25519Public + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("Curve25519Public", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct HmacSha256Key + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("HmacSha256Key", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct HmacSha256Mac + // { + // opaque mac[32]; + // }; + // + // =========================================================================== + xdr.struct("HmacSha256Mac", [["mac", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct ShortHashSeed + // { + // opaque seed[16]; + // }; + // + // =========================================================================== + xdr.struct("ShortHashSeed", [["seed", xdr.opaque(16)]]); + + // === xdr source ============================================================ + // + // enum BinaryFuseFilterType + // { + // BINARY_FUSE_FILTER_8_BIT = 0, + // BINARY_FUSE_FILTER_16_BIT = 1, + // BINARY_FUSE_FILTER_32_BIT = 2 + // }; + // + // =========================================================================== + xdr["enum"]("BinaryFuseFilterType", { + binaryFuseFilter8Bit: 0, + binaryFuseFilter16Bit: 1, + binaryFuseFilter32Bit: 2 + }); + + // === xdr source ============================================================ + // + // struct SerializedBinaryFuseFilter + // { + // BinaryFuseFilterType type; + // + // // Seed used to hash input to filter + // ShortHashSeed inputHashSeed; + // + // // Seed used for internal filter hash operations + // ShortHashSeed filterSeed; + // uint32 segmentLength; + // uint32 segementLengthMask; + // uint32 segmentCount; + // uint32 segmentCountLength; + // uint32 fingerprintLength; // Length in terms of element count, not bytes + // + // // Array of uint8_t, uint16_t, or uint32_t depending on filter type + // opaque fingerprints<>; + // }; + // + // =========================================================================== + xdr.struct("SerializedBinaryFuseFilter", [["type", xdr.lookup("BinaryFuseFilterType")], ["inputHashSeed", xdr.lookup("ShortHashSeed")], ["filterSeed", xdr.lookup("ShortHashSeed")], ["segmentLength", xdr.lookup("Uint32")], ["segementLengthMask", xdr.lookup("Uint32")], ["segmentCount", xdr.lookup("Uint32")], ["segmentCountLength", xdr.lookup("Uint32")], ["fingerprintLength", xdr.lookup("Uint32")], ["fingerprints", xdr.varOpaque()]]); + + // === xdr source ============================================================ + // + // enum SCValType + // { + // SCV_BOOL = 0, + // SCV_VOID = 1, + // SCV_ERROR = 2, + // + // // 32 bits is the smallest type in WASM or XDR; no need for u8/u16. + // SCV_U32 = 3, + // SCV_I32 = 4, + // + // // 64 bits is naturally supported by both WASM and XDR also. + // SCV_U64 = 5, + // SCV_I64 = 6, + // + // // Time-related u64 subtypes with their own functions and formatting. + // SCV_TIMEPOINT = 7, + // SCV_DURATION = 8, + // + // // 128 bits is naturally supported by Rust and we use it for Soroban + // // fixed-point arithmetic prices / balances / similar "quantities". These + // // are represented in XDR as a pair of 2 u64s. + // SCV_U128 = 9, + // SCV_I128 = 10, + // + // // 256 bits is the size of sha256 output, ed25519 keys, and the EVM machine + // // word, so for interop use we include this even though it requires a small + // // amount of Rust guest and/or host library code. + // SCV_U256 = 11, + // SCV_I256 = 12, + // + // // Bytes come in 3 flavors, 2 of which have meaningfully different + // // formatting and validity-checking / domain-restriction. + // SCV_BYTES = 13, + // SCV_STRING = 14, + // SCV_SYMBOL = 15, + // + // // Vecs and maps are just polymorphic containers of other ScVals. + // SCV_VEC = 16, + // SCV_MAP = 17, + // + // // Address is the universal identifier for contracts and classic + // // accounts. + // SCV_ADDRESS = 18, + // + // // The following are the internal SCVal variants that are not + // // exposed to the contracts. + // SCV_CONTRACT_INSTANCE = 19, + // + // // SCV_LEDGER_KEY_CONTRACT_INSTANCE and SCV_LEDGER_KEY_NONCE are unique + // // symbolic SCVals used as the key for ledger entries for a contract's + // // instance and an address' nonce, respectively. + // SCV_LEDGER_KEY_CONTRACT_INSTANCE = 20, + // SCV_LEDGER_KEY_NONCE = 21 + // }; + // + // =========================================================================== + xdr["enum"]("ScValType", { + scvBool: 0, + scvVoid: 1, + scvError: 2, + scvU32: 3, + scvI32: 4, + scvU64: 5, + scvI64: 6, + scvTimepoint: 7, + scvDuration: 8, + scvU128: 9, + scvI128: 10, + scvU256: 11, + scvI256: 12, + scvBytes: 13, + scvString: 14, + scvSymbol: 15, + scvVec: 16, + scvMap: 17, + scvAddress: 18, + scvContractInstance: 19, + scvLedgerKeyContractInstance: 20, + scvLedgerKeyNonce: 21 + }); + + // === xdr source ============================================================ + // + // enum SCErrorType + // { + // SCE_CONTRACT = 0, // Contract-specific, user-defined codes. + // SCE_WASM_VM = 1, // Errors while interpreting WASM bytecode. + // SCE_CONTEXT = 2, // Errors in the contract's host context. + // SCE_STORAGE = 3, // Errors accessing host storage. + // SCE_OBJECT = 4, // Errors working with host objects. + // SCE_CRYPTO = 5, // Errors in cryptographic operations. + // SCE_EVENTS = 6, // Errors while emitting events. + // SCE_BUDGET = 7, // Errors relating to budget limits. + // SCE_VALUE = 8, // Errors working with host values or SCVals. + // SCE_AUTH = 9 // Errors from the authentication subsystem. + // }; + // + // =========================================================================== + xdr["enum"]("ScErrorType", { + sceContract: 0, + sceWasmVm: 1, + sceContext: 2, + sceStorage: 3, + sceObject: 4, + sceCrypto: 5, + sceEvents: 6, + sceBudget: 7, + sceValue: 8, + sceAuth: 9 + }); + + // === xdr source ============================================================ + // + // enum SCErrorCode + // { + // SCEC_ARITH_DOMAIN = 0, // Some arithmetic was undefined (overflow, divide-by-zero). + // SCEC_INDEX_BOUNDS = 1, // Something was indexed beyond its bounds. + // SCEC_INVALID_INPUT = 2, // User provided some otherwise-bad data. + // SCEC_MISSING_VALUE = 3, // Some value was required but not provided. + // SCEC_EXISTING_VALUE = 4, // Some value was provided where not allowed. + // SCEC_EXCEEDED_LIMIT = 5, // Some arbitrary limit -- gas or otherwise -- was hit. + // SCEC_INVALID_ACTION = 6, // Data was valid but action requested was not. + // SCEC_INTERNAL_ERROR = 7, // The host detected an error in its own logic. + // SCEC_UNEXPECTED_TYPE = 8, // Some type wasn't as expected. + // SCEC_UNEXPECTED_SIZE = 9 // Something's size wasn't as expected. + // }; + // + // =========================================================================== + xdr["enum"]("ScErrorCode", { + scecArithDomain: 0, + scecIndexBounds: 1, + scecInvalidInput: 2, + scecMissingValue: 3, + scecExistingValue: 4, + scecExceededLimit: 5, + scecInvalidAction: 6, + scecInternalError: 7, + scecUnexpectedType: 8, + scecUnexpectedSize: 9 + }); + + // === xdr source ============================================================ + // + // union SCError switch (SCErrorType type) + // { + // case SCE_CONTRACT: + // uint32 contractCode; + // case SCE_WASM_VM: + // case SCE_CONTEXT: + // case SCE_STORAGE: + // case SCE_OBJECT: + // case SCE_CRYPTO: + // case SCE_EVENTS: + // case SCE_BUDGET: + // case SCE_VALUE: + // case SCE_AUTH: + // SCErrorCode code; + // }; + // + // =========================================================================== + xdr.union("ScError", { + switchOn: xdr.lookup("ScErrorType"), + switchName: "type", + switches: [["sceContract", "contractCode"], ["sceWasmVm", "code"], ["sceContext", "code"], ["sceStorage", "code"], ["sceObject", "code"], ["sceCrypto", "code"], ["sceEvents", "code"], ["sceBudget", "code"], ["sceValue", "code"], ["sceAuth", "code"]], + arms: { + contractCode: xdr.lookup("Uint32"), + code: xdr.lookup("ScErrorCode") + } + }); + + // === xdr source ============================================================ + // + // struct UInt128Parts { + // uint64 hi; + // uint64 lo; + // }; + // + // =========================================================================== + xdr.struct("UInt128Parts", [["hi", xdr.lookup("Uint64")], ["lo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct Int128Parts { + // int64 hi; + // uint64 lo; + // }; + // + // =========================================================================== + xdr.struct("Int128Parts", [["hi", xdr.lookup("Int64")], ["lo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct UInt256Parts { + // uint64 hi_hi; + // uint64 hi_lo; + // uint64 lo_hi; + // uint64 lo_lo; + // }; + // + // =========================================================================== + xdr.struct("UInt256Parts", [["hiHi", xdr.lookup("Uint64")], ["hiLo", xdr.lookup("Uint64")], ["loHi", xdr.lookup("Uint64")], ["loLo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct Int256Parts { + // int64 hi_hi; + // uint64 hi_lo; + // uint64 lo_hi; + // uint64 lo_lo; + // }; + // + // =========================================================================== + xdr.struct("Int256Parts", [["hiHi", xdr.lookup("Int64")], ["hiLo", xdr.lookup("Uint64")], ["loHi", xdr.lookup("Uint64")], ["loLo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // enum ContractExecutableType + // { + // CONTRACT_EXECUTABLE_WASM = 0, + // CONTRACT_EXECUTABLE_STELLAR_ASSET = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractExecutableType", { + contractExecutableWasm: 0, + contractExecutableStellarAsset: 1 + }); + + // === xdr source ============================================================ + // + // union ContractExecutable switch (ContractExecutableType type) + // { + // case CONTRACT_EXECUTABLE_WASM: + // Hash wasm_hash; + // case CONTRACT_EXECUTABLE_STELLAR_ASSET: + // void; + // }; + // + // =========================================================================== + xdr.union("ContractExecutable", { + switchOn: xdr.lookup("ContractExecutableType"), + switchName: "type", + switches: [["contractExecutableWasm", "wasmHash"], ["contractExecutableStellarAsset", xdr["void"]()]], + arms: { + wasmHash: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum SCAddressType + // { + // SC_ADDRESS_TYPE_ACCOUNT = 0, + // SC_ADDRESS_TYPE_CONTRACT = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ScAddressType", { + scAddressTypeAccount: 0, + scAddressTypeContract: 1 + }); + + // === xdr source ============================================================ + // + // union SCAddress switch (SCAddressType type) + // { + // case SC_ADDRESS_TYPE_ACCOUNT: + // AccountID accountId; + // case SC_ADDRESS_TYPE_CONTRACT: + // Hash contractId; + // }; + // + // =========================================================================== + xdr.union("ScAddress", { + switchOn: xdr.lookup("ScAddressType"), + switchName: "type", + switches: [["scAddressTypeAccount", "accountId"], ["scAddressTypeContract", "contractId"]], + arms: { + accountId: xdr.lookup("AccountId"), + contractId: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // const SCSYMBOL_LIMIT = 32; + // + // =========================================================================== + xdr["const"]("SCSYMBOL_LIMIT", 32); + + // === xdr source ============================================================ + // + // typedef SCVal SCVec<>; + // + // =========================================================================== + xdr.typedef("ScVec", xdr.varArray(xdr.lookup("ScVal"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef SCMapEntry SCMap<>; + // + // =========================================================================== + xdr.typedef("ScMap", xdr.varArray(xdr.lookup("ScMapEntry"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef opaque SCBytes<>; + // + // =========================================================================== + xdr.typedef("ScBytes", xdr.varOpaque()); + + // === xdr source ============================================================ + // + // typedef string SCString<>; + // + // =========================================================================== + xdr.typedef("ScString", xdr.string()); + + // === xdr source ============================================================ + // + // typedef string SCSymbol; + // + // =========================================================================== + xdr.typedef("ScSymbol", xdr.string(SCSYMBOL_LIMIT)); + + // === xdr source ============================================================ + // + // struct SCNonceKey { + // int64 nonce; + // }; + // + // =========================================================================== + xdr.struct("ScNonceKey", [["nonce", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct SCContractInstance { + // ContractExecutable executable; + // SCMap* storage; + // }; + // + // =========================================================================== + xdr.struct("ScContractInstance", [["executable", xdr.lookup("ContractExecutable")], ["storage", xdr.option(xdr.lookup("ScMap"))]]); + + // === xdr source ============================================================ + // + // union SCVal switch (SCValType type) + // { + // + // case SCV_BOOL: + // bool b; + // case SCV_VOID: + // void; + // case SCV_ERROR: + // SCError error; + // + // case SCV_U32: + // uint32 u32; + // case SCV_I32: + // int32 i32; + // + // case SCV_U64: + // uint64 u64; + // case SCV_I64: + // int64 i64; + // case SCV_TIMEPOINT: + // TimePoint timepoint; + // case SCV_DURATION: + // Duration duration; + // + // case SCV_U128: + // UInt128Parts u128; + // case SCV_I128: + // Int128Parts i128; + // + // case SCV_U256: + // UInt256Parts u256; + // case SCV_I256: + // Int256Parts i256; + // + // case SCV_BYTES: + // SCBytes bytes; + // case SCV_STRING: + // SCString str; + // case SCV_SYMBOL: + // SCSymbol sym; + // + // // Vec and Map are recursive so need to live + // // behind an option, due to xdrpp limitations. + // case SCV_VEC: + // SCVec *vec; + // case SCV_MAP: + // SCMap *map; + // + // case SCV_ADDRESS: + // SCAddress address; + // + // // Special SCVals reserved for system-constructed contract-data + // // ledger keys, not generally usable elsewhere. + // case SCV_LEDGER_KEY_CONTRACT_INSTANCE: + // void; + // case SCV_LEDGER_KEY_NONCE: + // SCNonceKey nonce_key; + // + // case SCV_CONTRACT_INSTANCE: + // SCContractInstance instance; + // }; + // + // =========================================================================== + xdr.union("ScVal", { + switchOn: xdr.lookup("ScValType"), + switchName: "type", + switches: [["scvBool", "b"], ["scvVoid", xdr["void"]()], ["scvError", "error"], ["scvU32", "u32"], ["scvI32", "i32"], ["scvU64", "u64"], ["scvI64", "i64"], ["scvTimepoint", "timepoint"], ["scvDuration", "duration"], ["scvU128", "u128"], ["scvI128", "i128"], ["scvU256", "u256"], ["scvI256", "i256"], ["scvBytes", "bytes"], ["scvString", "str"], ["scvSymbol", "sym"], ["scvVec", "vec"], ["scvMap", "map"], ["scvAddress", "address"], ["scvLedgerKeyContractInstance", xdr["void"]()], ["scvLedgerKeyNonce", "nonceKey"], ["scvContractInstance", "instance"]], + arms: { + b: xdr.bool(), + error: xdr.lookup("ScError"), + u32: xdr.lookup("Uint32"), + i32: xdr.lookup("Int32"), + u64: xdr.lookup("Uint64"), + i64: xdr.lookup("Int64"), + timepoint: xdr.lookup("TimePoint"), + duration: xdr.lookup("Duration"), + u128: xdr.lookup("UInt128Parts"), + i128: xdr.lookup("Int128Parts"), + u256: xdr.lookup("UInt256Parts"), + i256: xdr.lookup("Int256Parts"), + bytes: xdr.lookup("ScBytes"), + str: xdr.lookup("ScString"), + sym: xdr.lookup("ScSymbol"), + vec: xdr.option(xdr.lookup("ScVec")), + map: xdr.option(xdr.lookup("ScMap")), + address: xdr.lookup("ScAddress"), + nonceKey: xdr.lookup("ScNonceKey"), + instance: xdr.lookup("ScContractInstance") + } + }); + + // === xdr source ============================================================ + // + // struct SCMapEntry + // { + // SCVal key; + // SCVal val; + // }; + // + // =========================================================================== + xdr.struct("ScMapEntry", [["key", xdr.lookup("ScVal")], ["val", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // enum SCEnvMetaKind + // { + // SC_ENV_META_KIND_INTERFACE_VERSION = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ScEnvMetaKind", { + scEnvMetaKindInterfaceVersion: 0 + }); + + // === xdr source ============================================================ + // + // struct { + // uint32 protocol; + // uint32 preRelease; + // } + // + // =========================================================================== + xdr.struct("ScEnvMetaEntryInterfaceVersion", [["protocol", xdr.lookup("Uint32")], ["preRelease", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union SCEnvMetaEntry switch (SCEnvMetaKind kind) + // { + // case SC_ENV_META_KIND_INTERFACE_VERSION: + // struct { + // uint32 protocol; + // uint32 preRelease; + // } interfaceVersion; + // }; + // + // =========================================================================== + xdr.union("ScEnvMetaEntry", { + switchOn: xdr.lookup("ScEnvMetaKind"), + switchName: "kind", + switches: [["scEnvMetaKindInterfaceVersion", "interfaceVersion"]], + arms: { + interfaceVersion: xdr.lookup("ScEnvMetaEntryInterfaceVersion") + } + }); + + // === xdr source ============================================================ + // + // struct SCMetaV0 + // { + // string key<>; + // string val<>; + // }; + // + // =========================================================================== + xdr.struct("ScMetaV0", [["key", xdr.string()], ["val", xdr.string()]]); + + // === xdr source ============================================================ + // + // enum SCMetaKind + // { + // SC_META_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ScMetaKind", { + scMetaV0: 0 + }); + + // === xdr source ============================================================ + // + // union SCMetaEntry switch (SCMetaKind kind) + // { + // case SC_META_V0: + // SCMetaV0 v0; + // }; + // + // =========================================================================== + xdr.union("ScMetaEntry", { + switchOn: xdr.lookup("ScMetaKind"), + switchName: "kind", + switches: [["scMetaV0", "v0"]], + arms: { + v0: xdr.lookup("ScMetaV0") + } + }); + + // === xdr source ============================================================ + // + // const SC_SPEC_DOC_LIMIT = 1024; + // + // =========================================================================== + xdr["const"]("SC_SPEC_DOC_LIMIT", 1024); + + // === xdr source ============================================================ + // + // enum SCSpecType + // { + // SC_SPEC_TYPE_VAL = 0, + // + // // Types with no parameters. + // SC_SPEC_TYPE_BOOL = 1, + // SC_SPEC_TYPE_VOID = 2, + // SC_SPEC_TYPE_ERROR = 3, + // SC_SPEC_TYPE_U32 = 4, + // SC_SPEC_TYPE_I32 = 5, + // SC_SPEC_TYPE_U64 = 6, + // SC_SPEC_TYPE_I64 = 7, + // SC_SPEC_TYPE_TIMEPOINT = 8, + // SC_SPEC_TYPE_DURATION = 9, + // SC_SPEC_TYPE_U128 = 10, + // SC_SPEC_TYPE_I128 = 11, + // SC_SPEC_TYPE_U256 = 12, + // SC_SPEC_TYPE_I256 = 13, + // SC_SPEC_TYPE_BYTES = 14, + // SC_SPEC_TYPE_STRING = 16, + // SC_SPEC_TYPE_SYMBOL = 17, + // SC_SPEC_TYPE_ADDRESS = 19, + // + // // Types with parameters. + // SC_SPEC_TYPE_OPTION = 1000, + // SC_SPEC_TYPE_RESULT = 1001, + // SC_SPEC_TYPE_VEC = 1002, + // SC_SPEC_TYPE_MAP = 1004, + // SC_SPEC_TYPE_TUPLE = 1005, + // SC_SPEC_TYPE_BYTES_N = 1006, + // + // // User defined types. + // SC_SPEC_TYPE_UDT = 2000 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecType", { + scSpecTypeVal: 0, + scSpecTypeBool: 1, + scSpecTypeVoid: 2, + scSpecTypeError: 3, + scSpecTypeU32: 4, + scSpecTypeI32: 5, + scSpecTypeU64: 6, + scSpecTypeI64: 7, + scSpecTypeTimepoint: 8, + scSpecTypeDuration: 9, + scSpecTypeU128: 10, + scSpecTypeI128: 11, + scSpecTypeU256: 12, + scSpecTypeI256: 13, + scSpecTypeBytes: 14, + scSpecTypeString: 16, + scSpecTypeSymbol: 17, + scSpecTypeAddress: 19, + scSpecTypeOption: 1000, + scSpecTypeResult: 1001, + scSpecTypeVec: 1002, + scSpecTypeMap: 1004, + scSpecTypeTuple: 1005, + scSpecTypeBytesN: 1006, + scSpecTypeUdt: 2000 + }); + + // === xdr source ============================================================ + // + // struct SCSpecTypeOption + // { + // SCSpecTypeDef valueType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeOption", [["valueType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeResult + // { + // SCSpecTypeDef okType; + // SCSpecTypeDef errorType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeResult", [["okType", xdr.lookup("ScSpecTypeDef")], ["errorType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeVec + // { + // SCSpecTypeDef elementType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeVec", [["elementType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeMap + // { + // SCSpecTypeDef keyType; + // SCSpecTypeDef valueType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeMap", [["keyType", xdr.lookup("ScSpecTypeDef")], ["valueType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeTuple + // { + // SCSpecTypeDef valueTypes<12>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeTuple", [["valueTypes", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 12)]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeBytesN + // { + // uint32 n; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeBytesN", [["n", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeUDT + // { + // string name<60>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeUdt", [["name", xdr.string(60)]]); + + // === xdr source ============================================================ + // + // union SCSpecTypeDef switch (SCSpecType type) + // { + // case SC_SPEC_TYPE_VAL: + // case SC_SPEC_TYPE_BOOL: + // case SC_SPEC_TYPE_VOID: + // case SC_SPEC_TYPE_ERROR: + // case SC_SPEC_TYPE_U32: + // case SC_SPEC_TYPE_I32: + // case SC_SPEC_TYPE_U64: + // case SC_SPEC_TYPE_I64: + // case SC_SPEC_TYPE_TIMEPOINT: + // case SC_SPEC_TYPE_DURATION: + // case SC_SPEC_TYPE_U128: + // case SC_SPEC_TYPE_I128: + // case SC_SPEC_TYPE_U256: + // case SC_SPEC_TYPE_I256: + // case SC_SPEC_TYPE_BYTES: + // case SC_SPEC_TYPE_STRING: + // case SC_SPEC_TYPE_SYMBOL: + // case SC_SPEC_TYPE_ADDRESS: + // void; + // case SC_SPEC_TYPE_OPTION: + // SCSpecTypeOption option; + // case SC_SPEC_TYPE_RESULT: + // SCSpecTypeResult result; + // case SC_SPEC_TYPE_VEC: + // SCSpecTypeVec vec; + // case SC_SPEC_TYPE_MAP: + // SCSpecTypeMap map; + // case SC_SPEC_TYPE_TUPLE: + // SCSpecTypeTuple tuple; + // case SC_SPEC_TYPE_BYTES_N: + // SCSpecTypeBytesN bytesN; + // case SC_SPEC_TYPE_UDT: + // SCSpecTypeUDT udt; + // }; + // + // =========================================================================== + xdr.union("ScSpecTypeDef", { + switchOn: xdr.lookup("ScSpecType"), + switchName: "type", + switches: [["scSpecTypeVal", xdr["void"]()], ["scSpecTypeBool", xdr["void"]()], ["scSpecTypeVoid", xdr["void"]()], ["scSpecTypeError", xdr["void"]()], ["scSpecTypeU32", xdr["void"]()], ["scSpecTypeI32", xdr["void"]()], ["scSpecTypeU64", xdr["void"]()], ["scSpecTypeI64", xdr["void"]()], ["scSpecTypeTimepoint", xdr["void"]()], ["scSpecTypeDuration", xdr["void"]()], ["scSpecTypeU128", xdr["void"]()], ["scSpecTypeI128", xdr["void"]()], ["scSpecTypeU256", xdr["void"]()], ["scSpecTypeI256", xdr["void"]()], ["scSpecTypeBytes", xdr["void"]()], ["scSpecTypeString", xdr["void"]()], ["scSpecTypeSymbol", xdr["void"]()], ["scSpecTypeAddress", xdr["void"]()], ["scSpecTypeOption", "option"], ["scSpecTypeResult", "result"], ["scSpecTypeVec", "vec"], ["scSpecTypeMap", "map"], ["scSpecTypeTuple", "tuple"], ["scSpecTypeBytesN", "bytesN"], ["scSpecTypeUdt", "udt"]], + arms: { + option: xdr.lookup("ScSpecTypeOption"), + result: xdr.lookup("ScSpecTypeResult"), + vec: xdr.lookup("ScSpecTypeVec"), + map: xdr.lookup("ScSpecTypeMap"), + tuple: xdr.lookup("ScSpecTypeTuple"), + bytesN: xdr.lookup("ScSpecTypeBytesN"), + udt: xdr.lookup("ScSpecTypeUdt") + } + }); + + // === xdr source ============================================================ + // + // struct SCSpecUDTStructFieldV0 + // { + // string doc; + // string name<30>; + // SCSpecTypeDef type; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtStructFieldV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(30)], ["type", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTStructV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTStructFieldV0 fields<40>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtStructV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["fields", xdr.varArray(xdr.lookup("ScSpecUdtStructFieldV0"), 40)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionCaseVoidV0 + // { + // string doc; + // string name<60>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionCaseVoidV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionCaseTupleV0 + // { + // string doc; + // string name<60>; + // SCSpecTypeDef type<12>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionCaseTupleV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["type", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 12)]]); + + // === xdr source ============================================================ + // + // enum SCSpecUDTUnionCaseV0Kind + // { + // SC_SPEC_UDT_UNION_CASE_VOID_V0 = 0, + // SC_SPEC_UDT_UNION_CASE_TUPLE_V0 = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecUdtUnionCaseV0Kind", { + scSpecUdtUnionCaseVoidV0: 0, + scSpecUdtUnionCaseTupleV0: 1 + }); + + // === xdr source ============================================================ + // + // union SCSpecUDTUnionCaseV0 switch (SCSpecUDTUnionCaseV0Kind kind) + // { + // case SC_SPEC_UDT_UNION_CASE_VOID_V0: + // SCSpecUDTUnionCaseVoidV0 voidCase; + // case SC_SPEC_UDT_UNION_CASE_TUPLE_V0: + // SCSpecUDTUnionCaseTupleV0 tupleCase; + // }; + // + // =========================================================================== + xdr.union("ScSpecUdtUnionCaseV0", { + switchOn: xdr.lookup("ScSpecUdtUnionCaseV0Kind"), + switchName: "kind", + switches: [["scSpecUdtUnionCaseVoidV0", "voidCase"], ["scSpecUdtUnionCaseTupleV0", "tupleCase"]], + arms: { + voidCase: xdr.lookup("ScSpecUdtUnionCaseVoidV0"), + tupleCase: xdr.lookup("ScSpecUdtUnionCaseTupleV0") + } + }); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTUnionCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtUnionCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTEnumCaseV0 + // { + // string doc; + // string name<60>; + // uint32 value; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtEnumCaseV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["value", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTEnumV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTEnumCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtEnumV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtEnumCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTErrorEnumCaseV0 + // { + // string doc; + // string name<60>; + // uint32 value; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtErrorEnumCaseV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["value", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTErrorEnumV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTErrorEnumCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtErrorEnumV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtErrorEnumCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecFunctionInputV0 + // { + // string doc; + // string name<30>; + // SCSpecTypeDef type; + // }; + // + // =========================================================================== + xdr.struct("ScSpecFunctionInputV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(30)], ["type", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecFunctionV0 + // { + // string doc; + // SCSymbol name; + // SCSpecFunctionInputV0 inputs<10>; + // SCSpecTypeDef outputs<1>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecFunctionV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.lookup("ScSymbol")], ["inputs", xdr.varArray(xdr.lookup("ScSpecFunctionInputV0"), 10)], ["outputs", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 1)]]); + + // === xdr source ============================================================ + // + // enum SCSpecEntryKind + // { + // SC_SPEC_ENTRY_FUNCTION_V0 = 0, + // SC_SPEC_ENTRY_UDT_STRUCT_V0 = 1, + // SC_SPEC_ENTRY_UDT_UNION_V0 = 2, + // SC_SPEC_ENTRY_UDT_ENUM_V0 = 3, + // SC_SPEC_ENTRY_UDT_ERROR_ENUM_V0 = 4 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecEntryKind", { + scSpecEntryFunctionV0: 0, + scSpecEntryUdtStructV0: 1, + scSpecEntryUdtUnionV0: 2, + scSpecEntryUdtEnumV0: 3, + scSpecEntryUdtErrorEnumV0: 4 + }); + + // === xdr source ============================================================ + // + // union SCSpecEntry switch (SCSpecEntryKind kind) + // { + // case SC_SPEC_ENTRY_FUNCTION_V0: + // SCSpecFunctionV0 functionV0; + // case SC_SPEC_ENTRY_UDT_STRUCT_V0: + // SCSpecUDTStructV0 udtStructV0; + // case SC_SPEC_ENTRY_UDT_UNION_V0: + // SCSpecUDTUnionV0 udtUnionV0; + // case SC_SPEC_ENTRY_UDT_ENUM_V0: + // SCSpecUDTEnumV0 udtEnumV0; + // case SC_SPEC_ENTRY_UDT_ERROR_ENUM_V0: + // SCSpecUDTErrorEnumV0 udtErrorEnumV0; + // }; + // + // =========================================================================== + xdr.union("ScSpecEntry", { + switchOn: xdr.lookup("ScSpecEntryKind"), + switchName: "kind", + switches: [["scSpecEntryFunctionV0", "functionV0"], ["scSpecEntryUdtStructV0", "udtStructV0"], ["scSpecEntryUdtUnionV0", "udtUnionV0"], ["scSpecEntryUdtEnumV0", "udtEnumV0"], ["scSpecEntryUdtErrorEnumV0", "udtErrorEnumV0"]], + arms: { + functionV0: xdr.lookup("ScSpecFunctionV0"), + udtStructV0: xdr.lookup("ScSpecUdtStructV0"), + udtUnionV0: xdr.lookup("ScSpecUdtUnionV0"), + udtEnumV0: xdr.lookup("ScSpecUdtEnumV0"), + udtErrorEnumV0: xdr.lookup("ScSpecUdtErrorEnumV0") + } + }); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractExecutionLanesV0 + // { + // // maximum number of Soroban transactions per ledger + // uint32 ledgerMaxTxCount; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractExecutionLanesV0", [["ledgerMaxTxCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractComputeV0 + // { + // // Maximum instructions per ledger + // int64 ledgerMaxInstructions; + // // Maximum instructions per transaction + // int64 txMaxInstructions; + // // Cost of 10000 instructions + // int64 feeRatePerInstructionsIncrement; + // + // // Memory limit per transaction. Unlike instructions, there is no fee + // // for memory, just the limit. + // uint32 txMemoryLimit; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractComputeV0", [["ledgerMaxInstructions", xdr.lookup("Int64")], ["txMaxInstructions", xdr.lookup("Int64")], ["feeRatePerInstructionsIncrement", xdr.lookup("Int64")], ["txMemoryLimit", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractParallelComputeV0 + // { + // // Maximum number of threads that can be used to apply a + // // transaction set to close the ledger. + // // This doesn't limit or defined the actual number of + // // threads used and instead only defines the minimum number + // // of physical threads that a tier-1 validator has to support + // // in order to not fall out of sync with the network. + // uint32 ledgerMaxParallelThreads; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractParallelComputeV0", [["ledgerMaxParallelThreads", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractLedgerCostV0 + // { + // // Maximum number of ledger entry read operations per ledger + // uint32 ledgerMaxReadLedgerEntries; + // // Maximum number of bytes that can be read per ledger + // uint32 ledgerMaxReadBytes; + // // Maximum number of ledger entry write operations per ledger + // uint32 ledgerMaxWriteLedgerEntries; + // // Maximum number of bytes that can be written per ledger + // uint32 ledgerMaxWriteBytes; + // + // // Maximum number of ledger entry read operations per transaction + // uint32 txMaxReadLedgerEntries; + // // Maximum number of bytes that can be read per transaction + // uint32 txMaxReadBytes; + // // Maximum number of ledger entry write operations per transaction + // uint32 txMaxWriteLedgerEntries; + // // Maximum number of bytes that can be written per transaction + // uint32 txMaxWriteBytes; + // + // int64 feeReadLedgerEntry; // Fee per ledger entry read + // int64 feeWriteLedgerEntry; // Fee per ledger entry write + // + // int64 feeRead1KB; // Fee for reading 1KB + // + // // The following parameters determine the write fee per 1KB. + // // Write fee grows linearly until bucket list reaches this size + // int64 bucketListTargetSizeBytes; + // // Fee per 1KB write when the bucket list is empty + // int64 writeFee1KBBucketListLow; + // // Fee per 1KB write when the bucket list has reached `bucketListTargetSizeBytes` + // int64 writeFee1KBBucketListHigh; + // // Write fee multiplier for any additional data past the first `bucketListTargetSizeBytes` + // uint32 bucketListWriteFeeGrowthFactor; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractLedgerCostV0", [["ledgerMaxReadLedgerEntries", xdr.lookup("Uint32")], ["ledgerMaxReadBytes", xdr.lookup("Uint32")], ["ledgerMaxWriteLedgerEntries", xdr.lookup("Uint32")], ["ledgerMaxWriteBytes", xdr.lookup("Uint32")], ["txMaxReadLedgerEntries", xdr.lookup("Uint32")], ["txMaxReadBytes", xdr.lookup("Uint32")], ["txMaxWriteLedgerEntries", xdr.lookup("Uint32")], ["txMaxWriteBytes", xdr.lookup("Uint32")], ["feeReadLedgerEntry", xdr.lookup("Int64")], ["feeWriteLedgerEntry", xdr.lookup("Int64")], ["feeRead1Kb", xdr.lookup("Int64")], ["bucketListTargetSizeBytes", xdr.lookup("Int64")], ["writeFee1KbBucketListLow", xdr.lookup("Int64")], ["writeFee1KbBucketListHigh", xdr.lookup("Int64")], ["bucketListWriteFeeGrowthFactor", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractHistoricalDataV0 + // { + // int64 feeHistorical1KB; // Fee for storing 1KB in archives + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractHistoricalDataV0", [["feeHistorical1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractEventsV0 + // { + // // Maximum size of events that a contract call can emit. + // uint32 txMaxContractEventsSizeBytes; + // // Fee for generating 1KB of contract events. + // int64 feeContractEvents1KB; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractEventsV0", [["txMaxContractEventsSizeBytes", xdr.lookup("Uint32")], ["feeContractEvents1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractBandwidthV0 + // { + // // Maximum sum of all transaction sizes in the ledger in bytes + // uint32 ledgerMaxTxsSizeBytes; + // // Maximum size in bytes for a transaction + // uint32 txMaxSizeBytes; + // + // // Fee for 1 KB of transaction size + // int64 feeTxSize1KB; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractBandwidthV0", [["ledgerMaxTxsSizeBytes", xdr.lookup("Uint32")], ["txMaxSizeBytes", xdr.lookup("Uint32")], ["feeTxSize1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum ContractCostType { + // // Cost of running 1 wasm instruction + // WasmInsnExec = 0, + // // Cost of allocating a slice of memory (in bytes) + // MemAlloc = 1, + // // Cost of copying a slice of bytes into a pre-allocated memory + // MemCpy = 2, + // // Cost of comparing two slices of memory + // MemCmp = 3, + // // Cost of a host function dispatch, not including the actual work done by + // // the function nor the cost of VM invocation machinary + // DispatchHostFunction = 4, + // // Cost of visiting a host object from the host object storage. Exists to + // // make sure some baseline cost coverage, i.e. repeatly visiting objects + // // by the guest will always incur some charges. + // VisitObject = 5, + // // Cost of serializing an xdr object to bytes + // ValSer = 6, + // // Cost of deserializing an xdr object from bytes + // ValDeser = 7, + // // Cost of computing the sha256 hash from bytes + // ComputeSha256Hash = 8, + // // Cost of computing the ed25519 pubkey from bytes + // ComputeEd25519PubKey = 9, + // // Cost of verifying ed25519 signature of a payload. + // VerifyEd25519Sig = 10, + // // Cost of instantiation a VM from wasm bytes code. + // VmInstantiation = 11, + // // Cost of instantiation a VM from a cached state. + // VmCachedInstantiation = 12, + // // Cost of invoking a function on the VM. If the function is a host function, + // // additional cost will be covered by `DispatchHostFunction`. + // InvokeVmFunction = 13, + // // Cost of computing a keccak256 hash from bytes. + // ComputeKeccak256Hash = 14, + // // Cost of decoding an ECDSA signature computed from a 256-bit prime modulus + // // curve (e.g. secp256k1 and secp256r1) + // DecodeEcdsaCurve256Sig = 15, + // // Cost of recovering an ECDSA secp256k1 key from a signature. + // RecoverEcdsaSecp256k1Key = 16, + // // Cost of int256 addition (`+`) and subtraction (`-`) operations + // Int256AddSub = 17, + // // Cost of int256 multiplication (`*`) operation + // Int256Mul = 18, + // // Cost of int256 division (`/`) operation + // Int256Div = 19, + // // Cost of int256 power (`exp`) operation + // Int256Pow = 20, + // // Cost of int256 shift (`shl`, `shr`) operation + // Int256Shift = 21, + // // Cost of drawing random bytes using a ChaCha20 PRNG + // ChaCha20DrawBytes = 22, + // + // // Cost of parsing wasm bytes that only encode instructions. + // ParseWasmInstructions = 23, + // // Cost of parsing a known number of wasm functions. + // ParseWasmFunctions = 24, + // // Cost of parsing a known number of wasm globals. + // ParseWasmGlobals = 25, + // // Cost of parsing a known number of wasm table entries. + // ParseWasmTableEntries = 26, + // // Cost of parsing a known number of wasm types. + // ParseWasmTypes = 27, + // // Cost of parsing a known number of wasm data segments. + // ParseWasmDataSegments = 28, + // // Cost of parsing a known number of wasm element segments. + // ParseWasmElemSegments = 29, + // // Cost of parsing a known number of wasm imports. + // ParseWasmImports = 30, + // // Cost of parsing a known number of wasm exports. + // ParseWasmExports = 31, + // // Cost of parsing a known number of data segment bytes. + // ParseWasmDataSegmentBytes = 32, + // + // // Cost of instantiating wasm bytes that only encode instructions. + // InstantiateWasmInstructions = 33, + // // Cost of instantiating a known number of wasm functions. + // InstantiateWasmFunctions = 34, + // // Cost of instantiating a known number of wasm globals. + // InstantiateWasmGlobals = 35, + // // Cost of instantiating a known number of wasm table entries. + // InstantiateWasmTableEntries = 36, + // // Cost of instantiating a known number of wasm types. + // InstantiateWasmTypes = 37, + // // Cost of instantiating a known number of wasm data segments. + // InstantiateWasmDataSegments = 38, + // // Cost of instantiating a known number of wasm element segments. + // InstantiateWasmElemSegments = 39, + // // Cost of instantiating a known number of wasm imports. + // InstantiateWasmImports = 40, + // // Cost of instantiating a known number of wasm exports. + // InstantiateWasmExports = 41, + // // Cost of instantiating a known number of data segment bytes. + // InstantiateWasmDataSegmentBytes = 42, + // + // // Cost of decoding a bytes array representing an uncompressed SEC-1 encoded + // // point on a 256-bit elliptic curve + // Sec1DecodePointUncompressed = 43, + // // Cost of verifying an ECDSA Secp256r1 signature + // VerifyEcdsaSecp256r1Sig = 44, + // + // // Cost of encoding a BLS12-381 Fp (base field element) + // Bls12381EncodeFp = 45, + // // Cost of decoding a BLS12-381 Fp (base field element) + // Bls12381DecodeFp = 46, + // // Cost of checking a G1 point lies on the curve + // Bls12381G1CheckPointOnCurve = 47, + // // Cost of checking a G1 point belongs to the correct subgroup + // Bls12381G1CheckPointInSubgroup = 48, + // // Cost of checking a G2 point lies on the curve + // Bls12381G2CheckPointOnCurve = 49, + // // Cost of checking a G2 point belongs to the correct subgroup + // Bls12381G2CheckPointInSubgroup = 50, + // // Cost of converting a BLS12-381 G1 point from projective to affine coordinates + // Bls12381G1ProjectiveToAffine = 51, + // // Cost of converting a BLS12-381 G2 point from projective to affine coordinates + // Bls12381G2ProjectiveToAffine = 52, + // // Cost of performing BLS12-381 G1 point addition + // Bls12381G1Add = 53, + // // Cost of performing BLS12-381 G1 scalar multiplication + // Bls12381G1Mul = 54, + // // Cost of performing BLS12-381 G1 multi-scalar multiplication (MSM) + // Bls12381G1Msm = 55, + // // Cost of mapping a BLS12-381 Fp field element to a G1 point + // Bls12381MapFpToG1 = 56, + // // Cost of hashing to a BLS12-381 G1 point + // Bls12381HashToG1 = 57, + // // Cost of performing BLS12-381 G2 point addition + // Bls12381G2Add = 58, + // // Cost of performing BLS12-381 G2 scalar multiplication + // Bls12381G2Mul = 59, + // // Cost of performing BLS12-381 G2 multi-scalar multiplication (MSM) + // Bls12381G2Msm = 60, + // // Cost of mapping a BLS12-381 Fp2 field element to a G2 point + // Bls12381MapFp2ToG2 = 61, + // // Cost of hashing to a BLS12-381 G2 point + // Bls12381HashToG2 = 62, + // // Cost of performing BLS12-381 pairing operation + // Bls12381Pairing = 63, + // // Cost of converting a BLS12-381 scalar element from U256 + // Bls12381FrFromU256 = 64, + // // Cost of converting a BLS12-381 scalar element to U256 + // Bls12381FrToU256 = 65, + // // Cost of performing BLS12-381 scalar element addition/subtraction + // Bls12381FrAddSub = 66, + // // Cost of performing BLS12-381 scalar element multiplication + // Bls12381FrMul = 67, + // // Cost of performing BLS12-381 scalar element exponentiation + // Bls12381FrPow = 68, + // // Cost of performing BLS12-381 scalar element inversion + // Bls12381FrInv = 69 + // }; + // + // =========================================================================== + xdr["enum"]("ContractCostType", { + wasmInsnExec: 0, + memAlloc: 1, + memCpy: 2, + memCmp: 3, + dispatchHostFunction: 4, + visitObject: 5, + valSer: 6, + valDeser: 7, + computeSha256Hash: 8, + computeEd25519PubKey: 9, + verifyEd25519Sig: 10, + vmInstantiation: 11, + vmCachedInstantiation: 12, + invokeVmFunction: 13, + computeKeccak256Hash: 14, + decodeEcdsaCurve256Sig: 15, + recoverEcdsaSecp256k1Key: 16, + int256AddSub: 17, + int256Mul: 18, + int256Div: 19, + int256Pow: 20, + int256Shift: 21, + chaCha20DrawBytes: 22, + parseWasmInstructions: 23, + parseWasmFunctions: 24, + parseWasmGlobals: 25, + parseWasmTableEntries: 26, + parseWasmTypes: 27, + parseWasmDataSegments: 28, + parseWasmElemSegments: 29, + parseWasmImports: 30, + parseWasmExports: 31, + parseWasmDataSegmentBytes: 32, + instantiateWasmInstructions: 33, + instantiateWasmFunctions: 34, + instantiateWasmGlobals: 35, + instantiateWasmTableEntries: 36, + instantiateWasmTypes: 37, + instantiateWasmDataSegments: 38, + instantiateWasmElemSegments: 39, + instantiateWasmImports: 40, + instantiateWasmExports: 41, + instantiateWasmDataSegmentBytes: 42, + sec1DecodePointUncompressed: 43, + verifyEcdsaSecp256r1Sig: 44, + bls12381EncodeFp: 45, + bls12381DecodeFp: 46, + bls12381G1CheckPointOnCurve: 47, + bls12381G1CheckPointInSubgroup: 48, + bls12381G2CheckPointOnCurve: 49, + bls12381G2CheckPointInSubgroup: 50, + bls12381G1ProjectiveToAffine: 51, + bls12381G2ProjectiveToAffine: 52, + bls12381G1Add: 53, + bls12381G1Mul: 54, + bls12381G1Msm: 55, + bls12381MapFpToG1: 56, + bls12381HashToG1: 57, + bls12381G2Add: 58, + bls12381G2Mul: 59, + bls12381G2Msm: 60, + bls12381MapFp2ToG2: 61, + bls12381HashToG2: 62, + bls12381Pairing: 63, + bls12381FrFromU256: 64, + bls12381FrToU256: 65, + bls12381FrAddSub: 66, + bls12381FrMul: 67, + bls12381FrPow: 68, + bls12381FrInv: 69 + }); + + // === xdr source ============================================================ + // + // struct ContractCostParamEntry { + // // use `ext` to add more terms (e.g. higher order polynomials) in the future + // ExtensionPoint ext; + // + // int64 constTerm; + // int64 linearTerm; + // }; + // + // =========================================================================== + xdr.struct("ContractCostParamEntry", [["ext", xdr.lookup("ExtensionPoint")], ["constTerm", xdr.lookup("Int64")], ["linearTerm", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct StateArchivalSettings { + // uint32 maxEntryTTL; + // uint32 minTemporaryTTL; + // uint32 minPersistentTTL; + // + // // rent_fee = wfee_rate_average / rent_rate_denominator_for_type + // int64 persistentRentRateDenominator; + // int64 tempRentRateDenominator; + // + // // max number of entries that emit archival meta in a single ledger + // uint32 maxEntriesToArchive; + // + // // Number of snapshots to use when calculating average BucketList size + // uint32 bucketListSizeWindowSampleSize; + // + // // How often to sample the BucketList size for the average, in ledgers + // uint32 bucketListWindowSamplePeriod; + // + // // Maximum number of bytes that we scan for eviction per ledger + // uint32 evictionScanSize; + // + // // Lowest BucketList level to be scanned to evict entries + // uint32 startingEvictionScanLevel; + // }; + // + // =========================================================================== + xdr.struct("StateArchivalSettings", [["maxEntryTtl", xdr.lookup("Uint32")], ["minTemporaryTtl", xdr.lookup("Uint32")], ["minPersistentTtl", xdr.lookup("Uint32")], ["persistentRentRateDenominator", xdr.lookup("Int64")], ["tempRentRateDenominator", xdr.lookup("Int64")], ["maxEntriesToArchive", xdr.lookup("Uint32")], ["bucketListSizeWindowSampleSize", xdr.lookup("Uint32")], ["bucketListWindowSamplePeriod", xdr.lookup("Uint32")], ["evictionScanSize", xdr.lookup("Uint32")], ["startingEvictionScanLevel", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct EvictionIterator { + // uint32 bucketListLevel; + // bool isCurrBucket; + // uint64 bucketFileOffset; + // }; + // + // =========================================================================== + xdr.struct("EvictionIterator", [["bucketListLevel", xdr.lookup("Uint32")], ["isCurrBucket", xdr.bool()], ["bucketFileOffset", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // const CONTRACT_COST_COUNT_LIMIT = 1024; + // + // =========================================================================== + xdr["const"]("CONTRACT_COST_COUNT_LIMIT", 1024); + + // === xdr source ============================================================ + // + // typedef ContractCostParamEntry ContractCostParams; + // + // =========================================================================== + xdr.typedef("ContractCostParams", xdr.varArray(xdr.lookup("ContractCostParamEntry"), xdr.lookup("CONTRACT_COST_COUNT_LIMIT"))); + + // === xdr source ============================================================ + // + // enum ConfigSettingID + // { + // CONFIG_SETTING_CONTRACT_MAX_SIZE_BYTES = 0, + // CONFIG_SETTING_CONTRACT_COMPUTE_V0 = 1, + // CONFIG_SETTING_CONTRACT_LEDGER_COST_V0 = 2, + // CONFIG_SETTING_CONTRACT_HISTORICAL_DATA_V0 = 3, + // CONFIG_SETTING_CONTRACT_EVENTS_V0 = 4, + // CONFIG_SETTING_CONTRACT_BANDWIDTH_V0 = 5, + // CONFIG_SETTING_CONTRACT_COST_PARAMS_CPU_INSTRUCTIONS = 6, + // CONFIG_SETTING_CONTRACT_COST_PARAMS_MEMORY_BYTES = 7, + // CONFIG_SETTING_CONTRACT_DATA_KEY_SIZE_BYTES = 8, + // CONFIG_SETTING_CONTRACT_DATA_ENTRY_SIZE_BYTES = 9, + // CONFIG_SETTING_STATE_ARCHIVAL = 10, + // CONFIG_SETTING_CONTRACT_EXECUTION_LANES = 11, + // CONFIG_SETTING_BUCKETLIST_SIZE_WINDOW = 12, + // CONFIG_SETTING_EVICTION_ITERATOR = 13, + // CONFIG_SETTING_CONTRACT_PARALLEL_COMPUTE_V0 = 14 + // }; + // + // =========================================================================== + xdr["enum"]("ConfigSettingId", { + configSettingContractMaxSizeBytes: 0, + configSettingContractComputeV0: 1, + configSettingContractLedgerCostV0: 2, + configSettingContractHistoricalDataV0: 3, + configSettingContractEventsV0: 4, + configSettingContractBandwidthV0: 5, + configSettingContractCostParamsCpuInstructions: 6, + configSettingContractCostParamsMemoryBytes: 7, + configSettingContractDataKeySizeBytes: 8, + configSettingContractDataEntrySizeBytes: 9, + configSettingStateArchival: 10, + configSettingContractExecutionLanes: 11, + configSettingBucketlistSizeWindow: 12, + configSettingEvictionIterator: 13, + configSettingContractParallelComputeV0: 14 + }); + + // === xdr source ============================================================ + // + // union ConfigSettingEntry switch (ConfigSettingID configSettingID) + // { + // case CONFIG_SETTING_CONTRACT_MAX_SIZE_BYTES: + // uint32 contractMaxSizeBytes; + // case CONFIG_SETTING_CONTRACT_COMPUTE_V0: + // ConfigSettingContractComputeV0 contractCompute; + // case CONFIG_SETTING_CONTRACT_LEDGER_COST_V0: + // ConfigSettingContractLedgerCostV0 contractLedgerCost; + // case CONFIG_SETTING_CONTRACT_HISTORICAL_DATA_V0: + // ConfigSettingContractHistoricalDataV0 contractHistoricalData; + // case CONFIG_SETTING_CONTRACT_EVENTS_V0: + // ConfigSettingContractEventsV0 contractEvents; + // case CONFIG_SETTING_CONTRACT_BANDWIDTH_V0: + // ConfigSettingContractBandwidthV0 contractBandwidth; + // case CONFIG_SETTING_CONTRACT_COST_PARAMS_CPU_INSTRUCTIONS: + // ContractCostParams contractCostParamsCpuInsns; + // case CONFIG_SETTING_CONTRACT_COST_PARAMS_MEMORY_BYTES: + // ContractCostParams contractCostParamsMemBytes; + // case CONFIG_SETTING_CONTRACT_DATA_KEY_SIZE_BYTES: + // uint32 contractDataKeySizeBytes; + // case CONFIG_SETTING_CONTRACT_DATA_ENTRY_SIZE_BYTES: + // uint32 contractDataEntrySizeBytes; + // case CONFIG_SETTING_STATE_ARCHIVAL: + // StateArchivalSettings stateArchivalSettings; + // case CONFIG_SETTING_CONTRACT_EXECUTION_LANES: + // ConfigSettingContractExecutionLanesV0 contractExecutionLanes; + // case CONFIG_SETTING_BUCKETLIST_SIZE_WINDOW: + // uint64 bucketListSizeWindow<>; + // case CONFIG_SETTING_EVICTION_ITERATOR: + // EvictionIterator evictionIterator; + // case CONFIG_SETTING_CONTRACT_PARALLEL_COMPUTE_V0: + // ConfigSettingContractParallelComputeV0 contractParallelCompute; + // }; + // + // =========================================================================== + xdr.union("ConfigSettingEntry", { + switchOn: xdr.lookup("ConfigSettingId"), + switchName: "configSettingId", + switches: [["configSettingContractMaxSizeBytes", "contractMaxSizeBytes"], ["configSettingContractComputeV0", "contractCompute"], ["configSettingContractLedgerCostV0", "contractLedgerCost"], ["configSettingContractHistoricalDataV0", "contractHistoricalData"], ["configSettingContractEventsV0", "contractEvents"], ["configSettingContractBandwidthV0", "contractBandwidth"], ["configSettingContractCostParamsCpuInstructions", "contractCostParamsCpuInsns"], ["configSettingContractCostParamsMemoryBytes", "contractCostParamsMemBytes"], ["configSettingContractDataKeySizeBytes", "contractDataKeySizeBytes"], ["configSettingContractDataEntrySizeBytes", "contractDataEntrySizeBytes"], ["configSettingStateArchival", "stateArchivalSettings"], ["configSettingContractExecutionLanes", "contractExecutionLanes"], ["configSettingBucketlistSizeWindow", "bucketListSizeWindow"], ["configSettingEvictionIterator", "evictionIterator"], ["configSettingContractParallelComputeV0", "contractParallelCompute"]], + arms: { + contractMaxSizeBytes: xdr.lookup("Uint32"), + contractCompute: xdr.lookup("ConfigSettingContractComputeV0"), + contractLedgerCost: xdr.lookup("ConfigSettingContractLedgerCostV0"), + contractHistoricalData: xdr.lookup("ConfigSettingContractHistoricalDataV0"), + contractEvents: xdr.lookup("ConfigSettingContractEventsV0"), + contractBandwidth: xdr.lookup("ConfigSettingContractBandwidthV0"), + contractCostParamsCpuInsns: xdr.lookup("ContractCostParams"), + contractCostParamsMemBytes: xdr.lookup("ContractCostParams"), + contractDataKeySizeBytes: xdr.lookup("Uint32"), + contractDataEntrySizeBytes: xdr.lookup("Uint32"), + stateArchivalSettings: xdr.lookup("StateArchivalSettings"), + contractExecutionLanes: xdr.lookup("ConfigSettingContractExecutionLanesV0"), + bucketListSizeWindow: xdr.varArray(xdr.lookup("Uint64"), 2147483647), + evictionIterator: xdr.lookup("EvictionIterator"), + contractParallelCompute: xdr.lookup("ConfigSettingContractParallelComputeV0") + } + }); +}); +var _default = exports["default"] = types; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/get_liquidity_pool_id.js b/node_modules/@stellar/stellar-base/lib/get_liquidity_pool_id.js new file mode 100644 index 000000000..ead7d49b2 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/get_liquidity_pool_id.js @@ -0,0 +1,57 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LiquidityPoolFeeV18 = void 0; +exports.getLiquidityPoolId = getLiquidityPoolId; +var _xdr = _interopRequireDefault(require("./xdr")); +var _asset = require("./asset"); +var _hashing = require("./hashing"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +// LiquidityPoolFeeV18 is the default liquidity pool fee in protocol v18. It defaults to 30 base points (0.3%). +var LiquidityPoolFeeV18 = exports.LiquidityPoolFeeV18 = 30; + +/** + * getLiquidityPoolId computes the Pool ID for the given assets, fee and pool type. + * + * @see [stellar-core getPoolID](https://github.com/stellar/stellar-core/blob/9f3a48c6a8f1aa77b6043a055d0638661f718080/src/ledger/test/LedgerTxnTests.cpp#L3746-L3751) + * + * @export + * @param {string} liquidityPoolType – A string representing the liquidity pool type. + * @param {object} liquidityPoolParameters – The liquidity pool parameters. + * @param {Asset} liquidityPoolParameters.assetA – The first asset in the Pool, it must respect the rule assetA < assetB. + * @param {Asset} liquidityPoolParameters.assetB – The second asset in the Pool, it must respect the rule assetA < assetB. + * @param {number} liquidityPoolParameters.fee – The liquidity pool fee. For now the only fee supported is `30`. + * + * @return {Buffer} the raw Pool ID buffer, which can be stringfied with `toString('hex')` + */ +function getLiquidityPoolId(liquidityPoolType) { + var liquidityPoolParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (liquidityPoolType !== 'constant_product') { + throw new Error('liquidityPoolType is invalid'); + } + var assetA = liquidityPoolParameters.assetA, + assetB = liquidityPoolParameters.assetB, + fee = liquidityPoolParameters.fee; + if (!assetA || !(assetA instanceof _asset.Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof _asset.Asset)) { + throw new Error('assetB is invalid'); + } + if (!fee || fee !== LiquidityPoolFeeV18) { + throw new Error('fee is invalid'); + } + if (_asset.Asset.compare(assetA, assetB) !== -1) { + throw new Error('Assets are not in lexicographic order'); + } + var lpTypeData = _xdr["default"].LiquidityPoolType.liquidityPoolConstantProduct().toXDR(); + var lpParamsData = new _xdr["default"].LiquidityPoolConstantProductParameters({ + assetA: assetA.toXDRObject(), + assetB: assetB.toXDRObject(), + fee: fee + }).toXDR(); + var payload = Buffer.concat([lpTypeData, lpParamsData]); + return (0, _hashing.hash)(payload); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/hashing.js b/node_modules/@stellar/stellar-base/lib/hashing.js new file mode 100644 index 000000000..21190b894 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/hashing.js @@ -0,0 +1,12 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.hash = hash; +var _sha = require("sha.js"); +function hash(data) { + var hasher = new _sha.sha256(); + hasher.update(data, 'utf8'); + return hasher.digest(); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/index.js b/node_modules/@stellar/stellar-base/lib/index.js new file mode 100644 index 000000000..f94c54a06 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/index.js @@ -0,0 +1,389 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + xdr: true, + cereal: true, + hash: true, + sign: true, + verify: true, + FastSigning: true, + getLiquidityPoolId: true, + LiquidityPoolFeeV18: true, + Keypair: true, + UnsignedHyper: true, + Hyper: true, + TransactionBase: true, + Transaction: true, + FeeBumpTransaction: true, + TransactionBuilder: true, + TimeoutInfinite: true, + BASE_FEE: true, + Asset: true, + LiquidityPoolAsset: true, + LiquidityPoolId: true, + Operation: true, + AuthRequiredFlag: true, + AuthRevocableFlag: true, + AuthImmutableFlag: true, + AuthClawbackEnabledFlag: true, + Account: true, + MuxedAccount: true, + Claimant: true, + Networks: true, + StrKey: true, + SignerKey: true, + Soroban: true, + decodeAddressToMuxedAccount: true, + encodeMuxedAccountToAddress: true, + extractBaseAddress: true, + encodeMuxedAccount: true, + Contract: true, + Address: true +}; +Object.defineProperty(exports, "Account", { + enumerable: true, + get: function get() { + return _account.Account; + } +}); +Object.defineProperty(exports, "Address", { + enumerable: true, + get: function get() { + return _address.Address; + } +}); +Object.defineProperty(exports, "Asset", { + enumerable: true, + get: function get() { + return _asset.Asset; + } +}); +Object.defineProperty(exports, "AuthClawbackEnabledFlag", { + enumerable: true, + get: function get() { + return _operation.AuthClawbackEnabledFlag; + } +}); +Object.defineProperty(exports, "AuthImmutableFlag", { + enumerable: true, + get: function get() { + return _operation.AuthImmutableFlag; + } +}); +Object.defineProperty(exports, "AuthRequiredFlag", { + enumerable: true, + get: function get() { + return _operation.AuthRequiredFlag; + } +}); +Object.defineProperty(exports, "AuthRevocableFlag", { + enumerable: true, + get: function get() { + return _operation.AuthRevocableFlag; + } +}); +Object.defineProperty(exports, "BASE_FEE", { + enumerable: true, + get: function get() { + return _transaction_builder.BASE_FEE; + } +}); +Object.defineProperty(exports, "Claimant", { + enumerable: true, + get: function get() { + return _claimant.Claimant; + } +}); +Object.defineProperty(exports, "Contract", { + enumerable: true, + get: function get() { + return _contract.Contract; + } +}); +Object.defineProperty(exports, "FastSigning", { + enumerable: true, + get: function get() { + return _signing.FastSigning; + } +}); +Object.defineProperty(exports, "FeeBumpTransaction", { + enumerable: true, + get: function get() { + return _fee_bump_transaction.FeeBumpTransaction; + } +}); +Object.defineProperty(exports, "Hyper", { + enumerable: true, + get: function get() { + return _jsXdr.Hyper; + } +}); +Object.defineProperty(exports, "Keypair", { + enumerable: true, + get: function get() { + return _keypair.Keypair; + } +}); +Object.defineProperty(exports, "LiquidityPoolAsset", { + enumerable: true, + get: function get() { + return _liquidity_pool_asset.LiquidityPoolAsset; + } +}); +Object.defineProperty(exports, "LiquidityPoolFeeV18", { + enumerable: true, + get: function get() { + return _get_liquidity_pool_id.LiquidityPoolFeeV18; + } +}); +Object.defineProperty(exports, "LiquidityPoolId", { + enumerable: true, + get: function get() { + return _liquidity_pool_id.LiquidityPoolId; + } +}); +Object.defineProperty(exports, "MuxedAccount", { + enumerable: true, + get: function get() { + return _muxed_account.MuxedAccount; + } +}); +Object.defineProperty(exports, "Networks", { + enumerable: true, + get: function get() { + return _network.Networks; + } +}); +Object.defineProperty(exports, "Operation", { + enumerable: true, + get: function get() { + return _operation.Operation; + } +}); +Object.defineProperty(exports, "SignerKey", { + enumerable: true, + get: function get() { + return _signerkey.SignerKey; + } +}); +Object.defineProperty(exports, "Soroban", { + enumerable: true, + get: function get() { + return _soroban.Soroban; + } +}); +Object.defineProperty(exports, "StrKey", { + enumerable: true, + get: function get() { + return _strkey.StrKey; + } +}); +Object.defineProperty(exports, "TimeoutInfinite", { + enumerable: true, + get: function get() { + return _transaction_builder.TimeoutInfinite; + } +}); +Object.defineProperty(exports, "Transaction", { + enumerable: true, + get: function get() { + return _transaction.Transaction; + } +}); +Object.defineProperty(exports, "TransactionBase", { + enumerable: true, + get: function get() { + return _transaction_base.TransactionBase; + } +}); +Object.defineProperty(exports, "TransactionBuilder", { + enumerable: true, + get: function get() { + return _transaction_builder.TransactionBuilder; + } +}); +Object.defineProperty(exports, "UnsignedHyper", { + enumerable: true, + get: function get() { + return _jsXdr.UnsignedHyper; + } +}); +Object.defineProperty(exports, "cereal", { + enumerable: true, + get: function get() { + return _jsxdr["default"]; + } +}); +Object.defineProperty(exports, "decodeAddressToMuxedAccount", { + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.decodeAddressToMuxedAccount; + } +}); +exports["default"] = void 0; +Object.defineProperty(exports, "encodeMuxedAccount", { + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.encodeMuxedAccount; + } +}); +Object.defineProperty(exports, "encodeMuxedAccountToAddress", { + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.encodeMuxedAccountToAddress; + } +}); +Object.defineProperty(exports, "extractBaseAddress", { + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.extractBaseAddress; + } +}); +Object.defineProperty(exports, "getLiquidityPoolId", { + enumerable: true, + get: function get() { + return _get_liquidity_pool_id.getLiquidityPoolId; + } +}); +Object.defineProperty(exports, "hash", { + enumerable: true, + get: function get() { + return _hashing.hash; + } +}); +Object.defineProperty(exports, "sign", { + enumerable: true, + get: function get() { + return _signing.sign; + } +}); +Object.defineProperty(exports, "verify", { + enumerable: true, + get: function get() { + return _signing.verify; + } +}); +Object.defineProperty(exports, "xdr", { + enumerable: true, + get: function get() { + return _xdr["default"]; + } +}); +var _xdr = _interopRequireDefault(require("./xdr")); +var _jsxdr = _interopRequireDefault(require("./jsxdr")); +var _hashing = require("./hashing"); +var _signing = require("./signing"); +var _get_liquidity_pool_id = require("./get_liquidity_pool_id"); +var _keypair = require("./keypair"); +var _jsXdr = require("@stellar/js-xdr"); +var _transaction_base = require("./transaction_base"); +var _transaction = require("./transaction"); +var _fee_bump_transaction = require("./fee_bump_transaction"); +var _transaction_builder = require("./transaction_builder"); +var _asset = require("./asset"); +var _liquidity_pool_asset = require("./liquidity_pool_asset"); +var _liquidity_pool_id = require("./liquidity_pool_id"); +var _operation = require("./operation"); +var _memo = require("./memo"); +Object.keys(_memo).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _memo[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _memo[key]; + } + }); +}); +var _account = require("./account"); +var _muxed_account = require("./muxed_account"); +var _claimant = require("./claimant"); +var _network = require("./network"); +var _strkey = require("./strkey"); +var _signerkey = require("./signerkey"); +var _soroban = require("./soroban"); +var _decode_encode_muxed_account = require("./util/decode_encode_muxed_account"); +var _contract = require("./contract"); +var _address = require("./address"); +var _numbers = require("./numbers"); +Object.keys(_numbers).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _numbers[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _numbers[key]; + } + }); +}); +var _scval = require("./scval"); +Object.keys(_scval).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _scval[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _scval[key]; + } + }); +}); +var _events = require("./events"); +Object.keys(_events).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _events[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _events[key]; + } + }); +}); +var _sorobandata_builder = require("./sorobandata_builder"); +Object.keys(_sorobandata_builder).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _sorobandata_builder[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _sorobandata_builder[key]; + } + }); +}); +var _auth = require("./auth"); +Object.keys(_auth).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _auth[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _auth[key]; + } + }); +}); +var _invocation = require("./invocation"); +Object.keys(_invocation).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _invocation[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _invocation[key]; + } + }); +}); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/* eslint-disable import/no-import-module-exports */ +// +// Soroban +// +var _default = exports["default"] = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/invocation.js b/node_modules/@stellar/stellar-base/lib/invocation.js new file mode 100644 index 000000000..b7be9c108 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/invocation.js @@ -0,0 +1,212 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildInvocationTree = buildInvocationTree; +exports.walkInvocationTree = walkInvocationTree; +var _asset = require("./asset"); +var _address = require("./address"); +var _scval = require("./scval"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * @typedef CreateInvocation + * + * @prop {'wasm'|'sac'} type a type indicating if this creation was a custom + * contract or a wrapping of an existing Stellar asset + * @prop {string} [token] when `type=='sac'`, the canonical {@link Asset} that + * is being wrapped by this Stellar Asset Contract + * @prop {object} [wasm] when `type=='wasm'`, add'l creation parameters + * + * @prop {string} wasm.hash hex hash of WASM bytecode backing this contract + * @prop {string} wasm.address contract address of this deployment + * @prop {string} wasm.salt hex salt that the user consumed when creating + * this contract (encoded in the resulting address) + * @prop {any[]} [wasm.constructorArgs] a list of natively-represented values + * (see {@link scValToNative}) that are passed to the constructor when + * creating this contract + */ + +/** + * @typedef ExecuteInvocation + * + * @prop {string} source the strkey of the contract (C...) being invoked + * @prop {string} function the name of the function being invoked + * @prop {any[]} args the natively-represented parameters to the function + * invocation (see {@link scValToNative} for rules on how they're + * represented a JS types) + */ + +/** + * @typedef InvocationTree + * @prop {'execute' | 'create'} type the type of invocation occurring, either + * contract creation or host function execution + * @prop {CreateInvocation | ExecuteInvocation} args the parameters to the + * invocation, depending on the type + * @prop {InvocationTree[]} invocations any sub-invocations that (may) occur + * as a result of this invocation (i.e. a tree of call stacks) + */ + +/** + * Turns a raw invocation tree into a human-readable format. + * + * This is designed to make the invocation tree easier to understand in order to + * inform users about the side-effects of their contract calls. This will help + * make informed decisions about whether or not a particular invocation will + * result in what you expect it to. + * + * @param {xdr.SorobanAuthorizedInvocation} root the raw XDR of the invocation, + * likely acquired from transaction simulation. this is either from the + * {@link Operation.invokeHostFunction} itself (the `func` field), or from + * the authorization entries ({@link xdr.SorobanAuthorizationEntry}, the + * `rootInvocation` field) + * + * @returns {InvocationTree} a human-readable version of the invocation tree + * + * @example + * Here, we show a browser modal after simulating an arbitrary transaction, + * `tx`, which we assume has an `Operation.invokeHostFunction` inside of it: + * + * ```typescript + * import { Server, buildInvocationTree } from '@stellar/stellar-sdk'; + * + * const s = new Server("fill in accordingly"); + * + * s.simulateTransaction(tx).then( + * (resp: SorobanRpc.SimulateTransactionResponse) => { + * if (SorobanRpc.isSuccessfulSim(resp) && ) { + * // bold assumption: there's a valid result with an auth entry + * alert( + * "You are authorizing the following invocation:\n" + + * JSON.stringify( + * buildInvocationTree(resp.result!.auth[0].rootInvocation()), + * null, + * 2 + * ) + * ); + * } + * } + * ); + * ``` + */ +function buildInvocationTree(root) { + var fn = root["function"](); + + /** @type {InvocationTree} */ + var output = {}; + + /** @type {xdr.CreateContractArgs|xdr.CreateContractArgsV2|xdr.InvokeContractArgs} */ + var inner = fn.value(); + switch (fn["switch"]().value) { + // sorobanAuthorizedFunctionTypeContractFn + case 0: + output.type = 'execute'; + output.args = { + source: _address.Address.fromScAddress(inner.contractAddress()).toString(), + "function": inner.functionName(), + args: inner.args().map(function (arg) { + return (0, _scval.scValToNative)(arg); + }) + }; + break; + + // sorobanAuthorizedFunctionTypeCreateContractHostFn + // sorobanAuthorizedFunctionTypeCreateContractV2HostFn + case 1: // fallthrough: just no ctor args in V1 + case 2: + { + var createV2 = fn["switch"]().value === 2; + output.type = 'create'; + output.args = {}; + + // If the executable is a WASM, the preimage MUST be an address. If it's a + // token, the preimage MUST be an asset. This is a cheeky way to check + // that, because wasm=0, token=1 and address=0, asset=1 in the XDR switch + // values. + // + // The first part may not be true in V2, but we'd need to update this code + // anyway so it can still be an error. + var _ref = [inner.executable(), inner.contractIdPreimage()], + exec = _ref[0], + preimage = _ref[1]; + if (!!exec["switch"]().value !== !!preimage["switch"]().value) { + throw new Error("creation function appears invalid: ".concat(JSON.stringify(inner), " (should be wasm+address or token+asset)")); + } + switch (exec["switch"]().value) { + // contractExecutableWasm + case 0: + { + /** @type {xdr.ContractIdPreimageFromAddress} */ + var details = preimage.fromAddress(); + output.args.type = 'wasm'; + output.args.wasm = _objectSpread({ + salt: details.salt().toString('hex'), + hash: exec.wasmHash().toString('hex'), + address: _address.Address.fromScAddress(details.address()).toString() + }, createV2 && { + constructorArgs: inner.constructorArgs().map(function (arg) { + return (0, _scval.scValToNative)(arg); + }) + }); + break; + } + + // contractExecutableStellarAsset + case 1: + output.args.type = 'sac'; + output.args.asset = _asset.Asset.fromOperation(preimage.fromAsset()).toString(); + break; + default: + throw new Error("unknown creation type: ".concat(JSON.stringify(exec))); + } + break; + } + default: + throw new Error("unknown invocation type (".concat(fn["switch"](), "): ").concat(JSON.stringify(fn))); + } + output.invocations = root.subInvocations().map(function (i) { + return buildInvocationTree(i); + }); + return output; +} + +/** + * @callback InvocationWalker + * + * @param {xdr.SorobanAuthorizedInvocation} node the currently explored node + * @param {number} depth the depth of the tree this node is occurring at (the + * root starts at a depth of 1) + * @param {xdr.SorobanAuthorizedInvocation} [parent] this `node`s parent node, + * if any (i.e. this doesn't exist at the root) + * + * @returns {boolean|null|void} returning exactly `false` is a hint to stop + * exploring, other values are ignored + */ + +/** + * Executes a callback function on each node in the tree until stopped. + * + * Nodes are walked in a depth-first order. Returning `false` from the callback + * stops further depth exploration at that node, but it does not stop the walk + * in a "global" view. + * + * @param {xdr.SorobanAuthorizedInvocation} root the tree to explore + * @param {InvocationWalker} callback the callback to execute for each node + * @returns {void} + */ +function walkInvocationTree(root, callback) { + walkHelper(root, 1, callback); +} +function walkHelper(node, depth, callback, parent) { + if (callback(node, depth, parent) === false /* allow void rv */) { + return; + } + node.subInvocations().forEach(function (i) { + return walkHelper(i, depth + 1, callback, node); + }); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/jsxdr.js b/node_modules/@stellar/stellar-base/lib/jsxdr.js new file mode 100644 index 000000000..0fec4e998 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/jsxdr.js @@ -0,0 +1,12 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _jsXdr = require("@stellar/js-xdr"); +var cereal = { + XdrWriter: _jsXdr.XdrWriter, + XdrReader: _jsXdr.XdrReader +}; +var _default = exports["default"] = cereal; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/keypair.js b/node_modules/@stellar/stellar-base/lib/keypair.js new file mode 100644 index 000000000..1bf249c15 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/keypair.js @@ -0,0 +1,307 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Keypair = void 0; +var _tweetnacl = _interopRequireDefault(require("tweetnacl")); +var _signing = require("./signing"); +var _strkey = require("./strkey"); +var _hashing = require("./hashing"); +var _xdr = _interopRequireDefault(require("./xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": ["^"]}] */ +/** + * `Keypair` represents public (and secret) keys of the account. + * + * Currently `Keypair` only supports ed25519 but in a future this class can be abstraction layer for other + * public-key signature systems. + * + * Use more convenient methods to create `Keypair` object: + * * `{@link Keypair.fromPublicKey}` + * * `{@link Keypair.fromSecret}` + * * `{@link Keypair.random}` + * + * @constructor + * @param {object} keys At least one of keys must be provided. + * @param {string} keys.type Public-key signature system name. (currently only `ed25519` keys are supported) + * @param {Buffer} [keys.publicKey] Raw public key + * @param {Buffer} [keys.secretKey] Raw secret key (32-byte secret seed in ed25519`) + */ +var Keypair = exports.Keypair = /*#__PURE__*/function () { + function Keypair(keys) { + _classCallCheck(this, Keypair); + if (keys.type !== 'ed25519') { + throw new Error('Invalid keys type'); + } + this.type = keys.type; + if (keys.secretKey) { + keys.secretKey = Buffer.from(keys.secretKey); + if (keys.secretKey.length !== 32) { + throw new Error('secretKey length is invalid'); + } + this._secretSeed = keys.secretKey; + this._publicKey = (0, _signing.generate)(keys.secretKey); + this._secretKey = Buffer.concat([keys.secretKey, this._publicKey]); + if (keys.publicKey && !this._publicKey.equals(Buffer.from(keys.publicKey))) { + throw new Error('secretKey does not match publicKey'); + } + } else { + this._publicKey = Buffer.from(keys.publicKey); + if (this._publicKey.length !== 32) { + throw new Error('publicKey length is invalid'); + } + } + } + + /** + * Creates a new `Keypair` instance from secret. This can either be secret key or secret seed depending + * on underlying public-key signature system. Currently `Keypair` only supports ed25519. + * @param {string} secret secret key (ex. `SDAKFNYEIAORZKKCYRILFQKLLOCNPL5SWJ3YY5NM3ZH6GJSZGXHZEPQS`) + * @returns {Keypair} + */ + return _createClass(Keypair, [{ + key: "xdrAccountId", + value: function xdrAccountId() { + return new _xdr["default"].AccountId.publicKeyTypeEd25519(this._publicKey); + } + }, { + key: "xdrPublicKey", + value: function xdrPublicKey() { + return new _xdr["default"].PublicKey.publicKeyTypeEd25519(this._publicKey); + } + + /** + * Creates a {@link xdr.MuxedAccount} object from the public key. + * + * You will get a different type of muxed account depending on whether or not + * you pass an ID. + * + * @param {string} [id] - stringified integer indicating the underlying muxed + * ID of the new account object + * + * @return {xdr.MuxedAccount} + */ + }, { + key: "xdrMuxedAccount", + value: function xdrMuxedAccount(id) { + if (typeof id !== 'undefined') { + if (typeof id !== 'string') { + throw new TypeError("expected string for ID, got ".concat(_typeof(id))); + } + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromString(id), + ed25519: this._publicKey + })); + } + return new _xdr["default"].MuxedAccount.keyTypeEd25519(this._publicKey); + } + + /** + * Returns raw public key + * @returns {Buffer} + */ + }, { + key: "rawPublicKey", + value: function rawPublicKey() { + return this._publicKey; + } + }, { + key: "signatureHint", + value: function signatureHint() { + var a = this.xdrAccountId().toXDR(); + return a.slice(a.length - 4); + } + + /** + * Returns public key associated with this `Keypair` object. + * @returns {string} + */ + }, { + key: "publicKey", + value: function publicKey() { + return _strkey.StrKey.encodeEd25519PublicKey(this._publicKey); + } + + /** + * Returns secret key associated with this `Keypair` object + * @returns {string} + */ + }, { + key: "secret", + value: function secret() { + if (!this._secretSeed) { + throw new Error('no secret key available'); + } + if (this.type === 'ed25519') { + return _strkey.StrKey.encodeEd25519SecretSeed(this._secretSeed); + } + throw new Error('Invalid Keypair type'); + } + + /** + * Returns raw secret key. + * @returns {Buffer} + */ + }, { + key: "rawSecretKey", + value: function rawSecretKey() { + return this._secretSeed; + } + + /** + * Returns `true` if this `Keypair` object contains secret key and can sign. + * @returns {boolean} + */ + }, { + key: "canSign", + value: function canSign() { + return !!this._secretKey; + } + + /** + * Signs data. + * @param {Buffer} data Data to sign + * @returns {Buffer} + */ + }, { + key: "sign", + value: function sign(data) { + if (!this.canSign()) { + throw new Error('cannot sign: no secret key available'); + } + return (0, _signing.sign)(data, this._secretKey); + } + + /** + * Verifies if `signature` for `data` is valid. + * @param {Buffer} data Signed data + * @param {Buffer} signature Signature + * @returns {boolean} + */ + }, { + key: "verify", + value: function verify(data, signature) { + return (0, _signing.verify)(data, signature, this._publicKey); + } + + /** + * Returns the decorated signature (hint+sig) for arbitrary data. + * + * @param {Buffer} data arbitrary data to sign + * @return {xdr.DecoratedSignature} the raw signature structure which can be + * added directly to a transaction envelope + * + * @see TransactionBase.addDecoratedSignature + */ + }, { + key: "signDecorated", + value: function signDecorated(data) { + var signature = this.sign(data); + var hint = this.signatureHint(); + return new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signature + }); + } + + /** + * Returns the raw decorated signature (hint+sig) for a signed payload signer. + * + * The hint is defined as the last 4 bytes of the signer key XORed with last + * 4 bytes of the payload (zero-left-padded if necessary). + * + * @param {Buffer} data data to both sign and treat as the payload + * @return {xdr.DecoratedSignature} + * + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0040.md#signature-hint + * @see TransactionBase.addDecoratedSignature + */ + }, { + key: "signPayloadDecorated", + value: function signPayloadDecorated(data) { + var signature = this.sign(data); + var keyHint = this.signatureHint(); + var hint = Buffer.from(data.slice(-4)); + if (hint.length < 4) { + // append zeroes as needed + hint = Buffer.concat([hint, Buffer.alloc(4 - data.length, 0)]); + } + return new _xdr["default"].DecoratedSignature({ + hint: hint.map(function (_byte, i) { + return _byte ^ keyHint[i]; + }), + signature: signature + }); + } + }], [{ + key: "fromSecret", + value: function fromSecret(secret) { + var rawSecret = _strkey.StrKey.decodeEd25519SecretSeed(secret); + return this.fromRawEd25519Seed(rawSecret); + } + + /** + * Creates a new `Keypair` object from ed25519 secret key seed raw bytes. + * + * @param {Buffer} rawSeed Raw 32-byte ed25519 secret key seed + * @returns {Keypair} + */ + }, { + key: "fromRawEd25519Seed", + value: function fromRawEd25519Seed(rawSeed) { + return new this({ + type: 'ed25519', + secretKey: rawSeed + }); + } + + /** + * Returns `Keypair` object representing network master key. + * @param {string} networkPassphrase passphrase of the target stellar network (e.g. "Public Global Stellar Network ; September 2015"). + * @returns {Keypair} + */ + }, { + key: "master", + value: function master(networkPassphrase) { + if (!networkPassphrase) { + throw new Error('No network selected. Please pass a network argument, e.g. `Keypair.master(Networks.PUBLIC)`.'); + } + return this.fromRawEd25519Seed((0, _hashing.hash)(networkPassphrase)); + } + + /** + * Creates a new `Keypair` object from public key. + * @param {string} publicKey public key (ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`) + * @returns {Keypair} + */ + }, { + key: "fromPublicKey", + value: function fromPublicKey(publicKey) { + publicKey = _strkey.StrKey.decodeEd25519PublicKey(publicKey); + if (publicKey.length !== 32) { + throw new Error('Invalid Stellar public key'); + } + return new this({ + type: 'ed25519', + publicKey: publicKey + }); + } + + /** + * Create a random `Keypair` object. + * @returns {Keypair} + */ + }, { + key: "random", + value: function random() { + var secret = _tweetnacl["default"].randomBytes(32); + return this.fromRawEd25519Seed(secret); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/liquidity_pool_asset.js b/node_modules/@stellar/stellar-base/lib/liquidity_pool_asset.js new file mode 100644 index 000000000..ab2ad1621 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/liquidity_pool_asset.js @@ -0,0 +1,125 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LiquidityPoolAsset = void 0; +var _xdr = _interopRequireDefault(require("./xdr")); +var _asset = require("./asset"); +var _get_liquidity_pool_id = require("./get_liquidity_pool_id"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * LiquidityPoolAsset class represents a liquidity pool trustline change. + * + * @constructor + * @param {Asset} assetA – The first asset in the Pool, it must respect the rule assetA < assetB. See {@link Asset.compare} for more details on how assets are sorted. + * @param {Asset} assetB – The second asset in the Pool, it must respect the rule assetA < assetB. See {@link Asset.compare} for more details on how assets are sorted. + * @param {number} fee – The liquidity pool fee. For now the only fee supported is `30`. + */ +var LiquidityPoolAsset = exports.LiquidityPoolAsset = /*#__PURE__*/function () { + function LiquidityPoolAsset(assetA, assetB, fee) { + _classCallCheck(this, LiquidityPoolAsset); + if (!assetA || !(assetA instanceof _asset.Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof _asset.Asset)) { + throw new Error('assetB is invalid'); + } + if (_asset.Asset.compare(assetA, assetB) !== -1) { + throw new Error('Assets are not in lexicographic order'); + } + if (!fee || fee !== _get_liquidity_pool_id.LiquidityPoolFeeV18) { + throw new Error('fee is invalid'); + } + this.assetA = assetA; + this.assetB = assetB; + this.fee = fee; + } + + /** + * Returns a liquidity pool asset object from its XDR ChangeTrustAsset object + * representation. + * @param {xdr.ChangeTrustAsset} ctAssetXdr - The asset XDR object. + * @returns {LiquidityPoolAsset} + */ + return _createClass(LiquidityPoolAsset, [{ + key: "toXDRObject", + value: + /** + * Returns the `xdr.ChangeTrustAsset` object for this liquidity pool asset. + * + * Note: To convert from an {@link Asset `Asset`} to `xdr.ChangeTrustAsset` + * please refer to the + * {@link Asset.toChangeTrustXDRObject `Asset.toChangeTrustXDRObject`} method. + * + * @returns {xdr.ChangeTrustAsset} XDR ChangeTrustAsset object. + */ + function toXDRObject() { + var lpConstantProductParamsXdr = new _xdr["default"].LiquidityPoolConstantProductParameters({ + assetA: this.assetA.toXDRObject(), + assetB: this.assetB.toXDRObject(), + fee: this.fee + }); + var lpParamsXdr = new _xdr["default"].LiquidityPoolParameters('liquidityPoolConstantProduct', lpConstantProductParamsXdr); + return new _xdr["default"].ChangeTrustAsset('assetTypePoolShare', lpParamsXdr); + } + + /** + * @returns {LiquidityPoolParameters} Liquidity pool parameters. + */ + }, { + key: "getLiquidityPoolParameters", + value: function getLiquidityPoolParameters() { + return _objectSpread(_objectSpread({}, this), {}, { + assetA: this.assetA, + assetB: this.assetB, + fee: this.fee + }); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {AssetType.liquidityPoolShares} asset type. Can only be `liquidity_pool_shares`. + */ + }, { + key: "getAssetType", + value: function getAssetType() { + return 'liquidity_pool_shares'; + } + + /** + * @param {LiquidityPoolAsset} other the LiquidityPoolAsset to compare + * @returns {boolean} `true` if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(other) { + return this.assetA.equals(other.assetA) && this.assetB.equals(other.assetB) && this.fee === other.fee; + } + }, { + key: "toString", + value: function toString() { + var poolId = (0, _get_liquidity_pool_id.getLiquidityPoolId)('constant_product', this.getLiquidityPoolParameters()).toString('hex'); + return "liquidity_pool:".concat(poolId); + } + }], [{ + key: "fromOperation", + value: function fromOperation(ctAssetXdr) { + var assetType = ctAssetXdr["switch"](); + if (assetType === _xdr["default"].AssetType.assetTypePoolShare()) { + var liquidityPoolParameters = ctAssetXdr.liquidityPool().constantProduct(); + return new this(_asset.Asset.fromOperation(liquidityPoolParameters.assetA()), _asset.Asset.fromOperation(liquidityPoolParameters.assetB()), liquidityPoolParameters.fee()); + } + throw new Error("Invalid asset type: ".concat(assetType.name)); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/liquidity_pool_id.js b/node_modules/@stellar/stellar-base/lib/liquidity_pool_id.js new file mode 100644 index 000000000..ea22ddb1c --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/liquidity_pool_id.js @@ -0,0 +1,100 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LiquidityPoolId = void 0; +var _xdr = _interopRequireDefault(require("./xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * LiquidityPoolId class represents the asset referenced by a trustline to a + * liquidity pool. + * + * @constructor + * @param {string} liquidityPoolId - The ID of the liquidity pool in string 'hex'. + */ +var LiquidityPoolId = exports.LiquidityPoolId = /*#__PURE__*/function () { + function LiquidityPoolId(liquidityPoolId) { + _classCallCheck(this, LiquidityPoolId); + if (!liquidityPoolId) { + throw new Error('liquidityPoolId cannot be empty'); + } + if (!/^[a-f0-9]{64}$/.test(liquidityPoolId)) { + throw new Error('Liquidity pool ID is not a valid hash'); + } + this.liquidityPoolId = liquidityPoolId; + } + + /** + * Returns a liquidity pool ID object from its xdr.TrustLineAsset representation. + * @param {xdr.TrustLineAsset} tlAssetXdr - The asset XDR object. + * @returns {LiquidityPoolId} + */ + return _createClass(LiquidityPoolId, [{ + key: "toXDRObject", + value: + /** + * Returns the `xdr.TrustLineAsset` object for this liquidity pool ID. + * + * Note: To convert from {@link Asset `Asset`} to `xdr.TrustLineAsset` please + * refer to the + * {@link Asset.toTrustLineXDRObject `Asset.toTrustLineXDRObject`} method. + * + * @returns {xdr.TrustLineAsset} XDR LiquidityPoolId object + */ + function toXDRObject() { + var xdrPoolId = _xdr["default"].PoolId.fromXDR(this.liquidityPoolId, 'hex'); + return new _xdr["default"].TrustLineAsset('assetTypePoolShare', xdrPoolId); + } + + /** + * @returns {string} Liquidity pool ID. + */ + }, { + key: "getLiquidityPoolId", + value: function getLiquidityPoolId() { + return String(this.liquidityPoolId); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {AssetType.liquidityPoolShares} asset type. Can only be `liquidity_pool_shares`. + */ + }, { + key: "getAssetType", + value: function getAssetType() { + return 'liquidity_pool_shares'; + } + + /** + * @param {LiquidityPoolId} asset LiquidityPoolId to compare. + * @returns {boolean} `true` if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(asset) { + return this.liquidityPoolId === asset.getLiquidityPoolId(); + } + }, { + key: "toString", + value: function toString() { + return "liquidity_pool:".concat(this.liquidityPoolId); + } + }], [{ + key: "fromOperation", + value: function fromOperation(tlAssetXdr) { + var assetType = tlAssetXdr["switch"](); + if (assetType === _xdr["default"].AssetType.assetTypePoolShare()) { + var liquidityPoolId = tlAssetXdr.liquidityPoolId().toString('hex'); + return new this(liquidityPoolId); + } + throw new Error("Invalid asset type: ".concat(assetType.name)); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/memo.js b/node_modules/@stellar/stellar-base/lib/memo.js new file mode 100644 index 000000000..473bb72da --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/memo.js @@ -0,0 +1,269 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.MemoText = exports.MemoReturn = exports.MemoNone = exports.MemoID = exports.MemoHash = exports.Memo = void 0; +var _jsXdr = require("@stellar/js-xdr"); +var _bignumber = _interopRequireDefault(require("./util/bignumber")); +var _xdr = _interopRequireDefault(require("./xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Type of {@link Memo}. + */ +var MemoNone = exports.MemoNone = 'none'; +/** + * Type of {@link Memo}. + */ +var MemoID = exports.MemoID = 'id'; +/** + * Type of {@link Memo}. + */ +var MemoText = exports.MemoText = 'text'; +/** + * Type of {@link Memo}. + */ +var MemoHash = exports.MemoHash = 'hash'; +/** + * Type of {@link Memo}. + */ +var MemoReturn = exports.MemoReturn = 'return'; + +/** + * `Memo` represents memos attached to transactions. + * + * @param {string} type - `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn` + * @param {*} value - `string` for `MemoID`, `MemoText`, buffer of hex string for `MemoHash` or `MemoReturn` + * @see [Transactions concept](https://developers.stellar.org/docs/glossary/transactions/) + * @class Memo + */ +var Memo = exports.Memo = /*#__PURE__*/function () { + function Memo(type) { + var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + _classCallCheck(this, Memo); + this._type = type; + this._value = value; + switch (this._type) { + case MemoNone: + break; + case MemoID: + Memo._validateIdValue(value); + break; + case MemoText: + Memo._validateTextValue(value); + break; + case MemoHash: + case MemoReturn: + Memo._validateHashValue(value); + // We want MemoHash and MemoReturn to have Buffer as a value + if (typeof value === 'string') { + this._value = Buffer.from(value, 'hex'); + } + break; + default: + throw new Error('Invalid memo type'); + } + } + + /** + * Contains memo type: `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn` + */ + return _createClass(Memo, [{ + key: "type", + get: function get() { + return this._type; + }, + set: function set(type) { + throw new Error('Memo is immutable'); + } + + /** + * Contains memo value: + * * `null` for `MemoNone`, + * * `string` for `MemoID`, + * * `Buffer` for `MemoText` after decoding using `fromXDRObject`, original value otherwise, + * * `Buffer` for `MemoHash`, `MemoReturn`. + */ + }, { + key: "value", + get: function get() { + switch (this._type) { + case MemoNone: + return null; + case MemoID: + case MemoText: + return this._value; + case MemoHash: + case MemoReturn: + return Buffer.from(this._value); + default: + throw new Error('Invalid memo type'); + } + }, + set: function set(value) { + throw new Error('Memo is immutable'); + } + }, { + key: "toXDRObject", + value: + /** + * Returns XDR memo object. + * @returns {xdr.Memo} + */ + function toXDRObject() { + switch (this._type) { + case MemoNone: + return _xdr["default"].Memo.memoNone(); + case MemoID: + return _xdr["default"].Memo.memoId(_jsXdr.UnsignedHyper.fromString(this._value)); + case MemoText: + return _xdr["default"].Memo.memoText(this._value); + case MemoHash: + return _xdr["default"].Memo.memoHash(this._value); + case MemoReturn: + return _xdr["default"].Memo.memoReturn(this._value); + default: + return null; + } + } + + /** + * Returns {@link Memo} from XDR memo object. + * @param {xdr.Memo} object XDR memo object + * @returns {Memo} + */ + }], [{ + key: "_validateIdValue", + value: function _validateIdValue(value) { + var error = new Error("Expects a int64 as a string. Got ".concat(value)); + if (typeof value !== 'string') { + throw error; + } + var number; + try { + number = new _bignumber["default"](value); + } catch (e) { + throw error; + } + + // Infinity + if (!number.isFinite()) { + throw error; + } + + // NaN + if (number.isNaN()) { + throw error; + } + } + }, { + key: "_validateTextValue", + value: function _validateTextValue(value) { + if (!_xdr["default"].Memo.armTypeForArm('text').isValid(value)) { + throw new Error('Expects string, array or buffer, max 28 bytes'); + } + } + }, { + key: "_validateHashValue", + value: function _validateHashValue(value) { + var error = new Error("Expects a 32 byte hash value or hex encoded string. Got ".concat(value)); + if (value === null || typeof value === 'undefined') { + throw error; + } + var valueBuffer; + if (typeof value === 'string') { + if (!/^[0-9A-Fa-f]{64}$/g.test(value)) { + throw error; + } + valueBuffer = Buffer.from(value, 'hex'); + } else if (Buffer.isBuffer(value)) { + valueBuffer = Buffer.from(value); + } else { + throw error; + } + if (!valueBuffer.length || valueBuffer.length !== 32) { + throw error; + } + } + + /** + * Returns an empty memo (`MemoNone`). + * @returns {Memo} + */ + }, { + key: "none", + value: function none() { + return new Memo(MemoNone); + } + + /** + * Creates and returns a `MemoText` memo. + * @param {string} text - memo text + * @returns {Memo} + */ + }, { + key: "text", + value: function text(_text) { + return new Memo(MemoText, _text); + } + + /** + * Creates and returns a `MemoID` memo. + * @param {string} id - 64-bit number represented as a string + * @returns {Memo} + */ + }, { + key: "id", + value: function id(_id) { + return new Memo(MemoID, _id); + } + + /** + * Creates and returns a `MemoHash` memo. + * @param {array|string} hash - 32 byte hash or hex encoded string + * @returns {Memo} + */ + }, { + key: "hash", + value: function hash(_hash) { + return new Memo(MemoHash, _hash); + } + + /** + * Creates and returns a `MemoReturn` memo. + * @param {array|string} hash - 32 byte hash or hex encoded string + * @returns {Memo} + */ + }, { + key: "return", + value: function _return(hash) { + return new Memo(MemoReturn, hash); + } + }, { + key: "fromXDRObject", + value: function fromXDRObject(object) { + switch (object.arm()) { + case 'id': + return Memo.id(object.value().toString()); + case 'text': + return Memo.text(object.value()); + case 'hash': + return Memo.hash(object.value()); + case 'retHash': + return Memo["return"](object.value()); + default: + break; + } + if (typeof object.value() === 'undefined') { + return Memo.none(); + } + throw new Error('Unknown type'); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/muxed_account.js b/node_modules/@stellar/stellar-base/lib/muxed_account.js new file mode 100644 index 000000000..4f02b6608 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/muxed_account.js @@ -0,0 +1,158 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.MuxedAccount = void 0; +var _xdr = _interopRequireDefault(require("./xdr")); +var _account = require("./account"); +var _strkey = require("./strkey"); +var _decode_encode_muxed_account = require("./util/decode_encode_muxed_account"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Represents a muxed account for transactions and operations. + * + * A muxed (or *multiplexed*) account (defined rigorously in + * [CAP-27](https://stellar.org/protocol/cap-27) and briefly in + * [SEP-23](https://stellar.org/protocol/sep-23)) is one that resolves a single + * Stellar `G...`` account to many different underlying IDs. + * + * For example, you may have a single Stellar address for accounting purposes: + * GA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJVSGZ + * + * Yet would like to use it for 4 different family members: + * 1: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAGZFQ + * 2: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAALIWQ + * 3: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAPYHQ + * 4: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAQLQQ + * + * This object makes it easy to create muxed accounts from regular accounts, + * duplicate them, get/set the underlying IDs, etc. without mucking around with + * the raw XDR. + * + * Because muxed accounts are purely an off-chain convention, they all share the + * sequence number tied to their underlying G... account. Thus, this object + * *requires* an {@link Account} instance to be passed in, so that muxed + * instances of an account can collectively modify the sequence number whenever + * a muxed account is used as the source of a @{link Transaction} with {@link + * TransactionBuilder}. + * + * @constructor + * + * @param {Account} account - the @{link Account} instance representing the + * underlying G... address + * @param {string} id - a stringified uint64 value that represents the + * ID of the muxed account + * + * @link https://developers.stellar.org/docs/glossary/muxed-accounts/ + */ +var MuxedAccount = exports.MuxedAccount = /*#__PURE__*/function () { + function MuxedAccount(baseAccount, id) { + _classCallCheck(this, MuxedAccount); + var accountId = baseAccount.accountId(); + if (!_strkey.StrKey.isValidEd25519PublicKey(accountId)) { + throw new Error('accountId is invalid'); + } + this.account = baseAccount; + this._muxedXdr = (0, _decode_encode_muxed_account.encodeMuxedAccount)(accountId, id); + this._mAddress = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(this._muxedXdr); + this._id = id; + } + + /** + * Parses an M-address into a MuxedAccount object. + * + * @param {string} mAddress - an M-address to transform + * @param {string} sequenceNum - the sequence number of the underlying {@link + * Account}, to use for the underlying base account (@link + * MuxedAccount.baseAccount). If you're using the SDK, you can use + * `server.loadAccount` to fetch this if you don't know it. + * + * @return {MuxedAccount} + */ + return _createClass(MuxedAccount, [{ + key: "baseAccount", + value: + /** + * @return {Account} the underlying account object shared among all muxed + * accounts with this Stellar address + */ + function baseAccount() { + return this.account; + } + + /** + * @return {string} the M-address representing this account's (G-address, ID) + */ + }, { + key: "accountId", + value: function accountId() { + return this._mAddress; + } + }, { + key: "id", + value: function id() { + return this._id; + } + }, { + key: "setId", + value: function setId(id) { + if (typeof id !== 'string') { + throw new Error('id should be a string representing a number (uint64)'); + } + this._muxedXdr.med25519().id(_xdr["default"].Uint64.fromString(id)); + this._mAddress = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(this._muxedXdr); + this._id = id; + return this; + } + + /** + * Accesses the underlying account's sequence number. + * @return {string} strigified sequence number for the underlying account + */ + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this.account.sequenceNumber(); + } + + /** + * Increments the underlying account's sequence number by one. + * @return {void} + */ + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + return this.account.incrementSequenceNumber(); + } + + /** + * @return {xdr.MuxedAccount} the XDR object representing this muxed account's + * G-address and uint64 ID + */ + }, { + key: "toXDRObject", + value: function toXDRObject() { + return this._muxedXdr; + } + }, { + key: "equals", + value: function equals(otherMuxedAccount) { + return this.accountId() === otherMuxedAccount.accountId(); + } + }], [{ + key: "fromAddress", + value: function fromAddress(mAddress, sequenceNum) { + var muxedAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(mAddress); + var gAddress = (0, _decode_encode_muxed_account.extractBaseAddress)(mAddress); + var id = muxedAccount.med25519().id().toString(); + return new MuxedAccount(new _account.Account(gAddress, sequenceNum), id); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/network.js b/node_modules/@stellar/stellar-base/lib/network.js new file mode 100644 index 000000000..0bd81df78 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/network.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Networks = void 0; +/** + * Contains passphrases for common networks: + * * `Networks.PUBLIC`: `Public Global Stellar Network ; September 2015` + * * `Networks.TESTNET`: `Test SDF Network ; September 2015` + * * `Networks.FUTURENET`: `Test SDF Future Network ; October 2022` + * * `Networks.STANDALONE`: `Standalone Network ; February 2017` + * + * @type {{PUBLIC: string, TESTNET: string, FUTURENET: string, STANDALONE: string }} + */ +var Networks = exports.Networks = { + PUBLIC: 'Public Global Stellar Network ; September 2015', + TESTNET: 'Test SDF Network ; September 2015', + FUTURENET: 'Test SDF Future Network ; October 2022', + SANDBOX: 'Local Sandbox Stellar Network ; September 2022', + STANDALONE: 'Standalone Network ; February 2017' +}; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/numbers/index.js b/node_modules/@stellar/stellar-base/lib/numbers/index.js new file mode 100644 index 000000000..a797b7cc9 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/numbers/index.js @@ -0,0 +1,85 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "Int128", { + enumerable: true, + get: function get() { + return _int.Int128; + } +}); +Object.defineProperty(exports, "Int256", { + enumerable: true, + get: function get() { + return _int2.Int256; + } +}); +Object.defineProperty(exports, "ScInt", { + enumerable: true, + get: function get() { + return _sc_int.ScInt; + } +}); +Object.defineProperty(exports, "Uint128", { + enumerable: true, + get: function get() { + return _uint.Uint128; + } +}); +Object.defineProperty(exports, "Uint256", { + enumerable: true, + get: function get() { + return _uint2.Uint256; + } +}); +Object.defineProperty(exports, "XdrLargeInt", { + enumerable: true, + get: function get() { + return _xdr_large_int.XdrLargeInt; + } +}); +exports.scValToBigInt = scValToBigInt; +var _xdr_large_int = require("./xdr_large_int"); +var _uint = require("./uint128"); +var _uint2 = require("./uint256"); +var _int = require("./int128"); +var _int2 = require("./int256"); +var _sc_int = require("./sc_int"); +/** + * Transforms an opaque {@link xdr.ScVal} into a native bigint, if possible. + * + * If you then want to use this in the abstractions provided by this module, + * you can pass it to the constructor of {@link XdrLargeInt}. + * + * @example + * let scv = contract.call("add", x, y); // assume it returns an xdr.ScVal + * let bigi = scValToBigInt(scv); + * + * new ScInt(bigi); // if you don't care about types, and + * new XdrLargeInt('i128', bigi); // if you do + * + * @param {xdr.ScVal} scv - the raw XDR value to parse into an integer + * @returns {bigint} the native value of this input value + * + * @throws {TypeError} if the `scv` input value doesn't represent an integer + */ +function scValToBigInt(scv) { + var scIntType = _xdr_large_int.XdrLargeInt.getType(scv["switch"]().name); + switch (scv["switch"]().name) { + case 'scvU32': + case 'scvI32': + return BigInt(scv.value()); + case 'scvU64': + case 'scvI64': + return new _xdr_large_int.XdrLargeInt(scIntType, scv.value()).toBigInt(); + case 'scvU128': + case 'scvI128': + return new _xdr_large_int.XdrLargeInt(scIntType, [scv.value().lo(), scv.value().hi()]).toBigInt(); + case 'scvU256': + case 'scvI256': + return new _xdr_large_int.XdrLargeInt(scIntType, [scv.value().loLo(), scv.value().loHi(), scv.value().hiLo(), scv.value().hiHi()]).toBigInt(); + default: + throw TypeError("expected integer type, got ".concat(scv["switch"]())); + } +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/numbers/int128.js b/node_modules/@stellar/stellar-base/lib/numbers/int128.js new file mode 100644 index 000000000..5abe97ec4 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/numbers/int128.js @@ -0,0 +1,48 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Int128 = void 0; +var _jsXdr = require("@stellar/js-xdr"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Int128 = exports.Int128 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct a signed 128-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Int128() { + _classCallCheck(this, Int128); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Int128, [args]); + } + _inherits(Int128, _LargeInt); + return _createClass(Int128, [{ + key: "unsigned", + get: function get() { + return false; + } + }, { + key: "size", + get: function get() { + return 128; + } + }]); +}(_jsXdr.LargeInt); +Int128.defineIntBoundaries(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/numbers/int256.js b/node_modules/@stellar/stellar-base/lib/numbers/int256.js new file mode 100644 index 000000000..8407671b4 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/numbers/int256.js @@ -0,0 +1,48 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Int256 = void 0; +var _jsXdr = require("@stellar/js-xdr"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Int256 = exports.Int256 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct a signed 256-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Int256() { + _classCallCheck(this, Int256); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Int256, [args]); + } + _inherits(Int256, _LargeInt); + return _createClass(Int256, [{ + key: "unsigned", + get: function get() { + return false; + } + }, { + key: "size", + get: function get() { + return 256; + } + }]); +}(_jsXdr.LargeInt); +Int256.defineIntBoundaries(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/numbers/sc_int.js b/node_modules/@stellar/stellar-base/lib/numbers/sc_int.js new file mode 100644 index 000000000..fc33f328c --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/numbers/sc_int.js @@ -0,0 +1,131 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ScInt = void 0; +var _xdr_large_int = require("./xdr_large_int"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Provides an easier way to manipulate large numbers for Stellar operations. + * + * You can instantiate this "**s**mart **c**ontract integer" value either from + * bigints, strings, or numbers (whole numbers, or this will throw). + * + * If you need to create a native BigInt from a list of integer "parts" (for + * example, you have a series of encoded 32-bit integers that represent a larger + * value), you can use the lower level abstraction {@link XdrLargeInt}. For + * example, you could do `new XdrLargeInt('u128', bytes...).toBigInt()`. + * + * @example + * import { xdr, ScInt, scValToBigInt } from "@stellar/stellar-base"; + * + * // You have an ScVal from a contract and want to parse it into JS native. + * const value = xdr.ScVal.fromXDR(someXdr, "base64"); + * const bigi = scValToBigInt(value); // grab it as a BigInt + * let sci = new ScInt(bigi); + * + * sci.toNumber(); // gives native JS type (w/ size check) + * sci.toBigInt(); // gives the native BigInt value + * sci.toU64(); // gives ScValType-specific XDR constructs (with size checks) + * + * // You have a number and want to shove it into a contract. + * sci = ScInt(0xdeadcafebabe); + * sci.toBigInt() // returns 244838016400062n + * sci.toNumber() // throws: too large + * + * // Pass any to e.g. a Contract.call(), conversion happens automatically + * // regardless of the initial type. + * const scValU128 = sci.toU128(); + * const scValI256 = sci.toI256(); + * const scValU64 = sci.toU64(); + * + * // Lots of ways to initialize: + * ScInt("123456789123456789") + * ScInt(123456789123456789n); + * ScInt(1n << 140n); + * ScInt(-42); + * ScInt(scValToBigInt(scValU128)); // from above + * + * // If you know the type ahead of time (accessing `.raw` is faster than + * // conversions), you can specify the type directly (otherwise, it's + * // interpreted from the numbers you pass in): + * const i = ScInt(123456789n, { type: "u256" }); + * + * // For example, you can use the underlying `sdk.U256` and convert it to an + * // `xdr.ScVal` directly like so: + * const scv = new xdr.ScVal.scvU256(i.raw); + * + * // Or reinterpret it as a different type (size permitting): + * const scv = i.toI64(); + * + * @param {number|bigint|string} value - a single, integer-like value which will + * be interpreted in the smallest appropriate XDR type supported by Stellar + * (64, 128, or 256 bit integer values). signed values are supported, though + * they are sanity-checked against `opts.type`. if you need 32-bit values, + * you can construct them directly without needing this wrapper, e.g. + * `xdr.ScVal.scvU32(1234)`. + * + * @param {object} [opts] - an optional object controlling optional parameters + * @param {string} [opts.type] - force a specific data type. the type choices + * are: 'i64', 'u64', 'i128', 'u128', 'i256', and 'u256' (default: the + * smallest one that fits the `value`) + * + * @throws {RangeError} if the `value` is invalid (e.g. floating point), too + * large (i.e. exceeds a 256-bit value), or doesn't fit in the `opts.type` + * @throws {TypeError} on missing parameters, or if the "signedness" of `opts` + * doesn't match input `value`, e.g. passing `{type: 'u64'}` yet passing -1n + * @throws {SyntaxError} if a string `value` can't be parsed as a big integer + */ +var ScInt = exports.ScInt = /*#__PURE__*/function (_XdrLargeInt) { + function ScInt(value, opts) { + var _opts$type; + _classCallCheck(this, ScInt); + var signed = value < 0; + var type = (_opts$type = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type !== void 0 ? _opts$type : ''; + if (type.startsWith('u') && signed) { + throw TypeError("specified type ".concat(opts.type, " yet negative (").concat(value, ")")); + } + + // If unspecified, we make a best guess at the type based on the bit length + // of the value, treating 64 as a minimum and 256 as a maximum. + if (type === '') { + type = signed ? 'i' : 'u'; + var bitlen = nearestBigIntSize(value); + switch (bitlen) { + case 64: + case 128: + case 256: + type += bitlen.toString(); + break; + default: + throw RangeError("expected 64/128/256 bits for input (".concat(value, "), got ").concat(bitlen)); + } + } + return _callSuper(this, ScInt, [type, value]); + } + _inherits(ScInt, _XdrLargeInt); + return _createClass(ScInt); +}(_xdr_large_int.XdrLargeInt); +function nearestBigIntSize(bigI) { + var _find; + // Note: Even though BigInt.toString(2) includes the negative sign for + // negative values (???), the following is still accurate, because the + // negative sign would be represented by a sign bit. + var bitlen = bigI.toString(2).length; + return (_find = [64, 128, 256].find(function (len) { + return bitlen <= len; + })) !== null && _find !== void 0 ? _find : bitlen; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/numbers/uint128.js b/node_modules/@stellar/stellar-base/lib/numbers/uint128.js new file mode 100644 index 000000000..906c06c14 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/numbers/uint128.js @@ -0,0 +1,48 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Uint128 = void 0; +var _jsXdr = require("@stellar/js-xdr"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Uint128 = exports.Uint128 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct an unsigned 128-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Uint128() { + _classCallCheck(this, Uint128); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Uint128, [args]); + } + _inherits(Uint128, _LargeInt); + return _createClass(Uint128, [{ + key: "unsigned", + get: function get() { + return true; + } + }, { + key: "size", + get: function get() { + return 128; + } + }]); +}(_jsXdr.LargeInt); +Uint128.defineIntBoundaries(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/numbers/uint256.js b/node_modules/@stellar/stellar-base/lib/numbers/uint256.js new file mode 100644 index 000000000..c037860ff --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/numbers/uint256.js @@ -0,0 +1,48 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Uint256 = void 0; +var _jsXdr = require("@stellar/js-xdr"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Uint256 = exports.Uint256 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct an unsigned 256-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Uint256() { + _classCallCheck(this, Uint256); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Uint256, [args]); + } + _inherits(Uint256, _LargeInt); + return _createClass(Uint256, [{ + key: "unsigned", + get: function get() { + return true; + } + }, { + key: "size", + get: function get() { + return 256; + } + }]); +}(_jsXdr.LargeInt); +Uint256.defineIntBoundaries(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/numbers/xdr_large_int.js b/node_modules/@stellar/stellar-base/lib/numbers/xdr_large_int.js new file mode 100644 index 000000000..e929c49eb --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/numbers/xdr_large_int.js @@ -0,0 +1,266 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.XdrLargeInt = void 0; +var _jsXdr = require("@stellar/js-xdr"); +var _uint = require("./uint128"); +var _uint2 = require("./uint256"); +var _int = require("./int128"); +var _int2 = require("./int256"); +var _xdr = _interopRequireDefault(require("../xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": [">>"]}] */ +/** + * A wrapper class to represent large XDR-encodable integers. + * + * This operates at a lower level than {@link ScInt} by forcing you to specify + * the type / width / size in bits of the integer you're targeting, regardless + * of the input value(s) you provide. + * + * @param {string} type - force a specific data type. the type choices are: + * 'i64', 'u64', 'i128', 'u128', 'i256', and 'u256' (default: the smallest + * one that fits the `value`) (see {@link XdrLargeInt.isType}) + * @param {number|bigint|string|Array} values a list of + * integer-like values interpreted in big-endian order + */ +var XdrLargeInt = exports.XdrLargeInt = /*#__PURE__*/function () { + function XdrLargeInt(type, values) { + _classCallCheck(this, XdrLargeInt); + /** @type {xdr.LargeInt} */ + _defineProperty(this, "int", void 0); + // child class of a jsXdr.LargeInt + /** @type {string} */ + _defineProperty(this, "type", void 0); + if (!(values instanceof Array)) { + values = [values]; + } + + // normalize values to one type + values = values.map(function (i) { + // micro-optimization to no-op on the likeliest input value: + if (typeof i === 'bigint') { + return i; + } + if (i instanceof XdrLargeInt) { + return i.toBigInt(); + } + return BigInt(i); + }); + switch (type) { + case 'i64': + this["int"] = new _jsXdr.Hyper(values); + break; + case 'i128': + this["int"] = new _int.Int128(values); + break; + case 'i256': + this["int"] = new _int2.Int256(values); + break; + case 'u64': + this["int"] = new _jsXdr.UnsignedHyper(values); + break; + case 'u128': + this["int"] = new _uint.Uint128(values); + break; + case 'u256': + this["int"] = new _uint2.Uint256(values); + break; + default: + throw TypeError("invalid type: ".concat(type)); + } + this.type = type; + } + + /** + * @returns {number} + * @throws {RangeError} if the value can't fit into a Number + */ + return _createClass(XdrLargeInt, [{ + key: "toNumber", + value: function toNumber() { + var bi = this["int"].toBigInt(); + if (bi > Number.MAX_SAFE_INTEGER || bi < Number.MIN_SAFE_INTEGER) { + throw RangeError("value ".concat(bi, " not in range for Number ") + "[".concat(Number.MAX_SAFE_INTEGER, ", ").concat(Number.MIN_SAFE_INTEGER, "]")); + } + return Number(bi); + } + + /** @returns {bigint} */ + }, { + key: "toBigInt", + value: function toBigInt() { + return this["int"].toBigInt(); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = I64` */ + }, { + key: "toI64", + value: function toI64() { + this._sizeCheck(64); + var v = this.toBigInt(); + if (BigInt.asIntN(64, v) !== v) { + throw RangeError("value too large for i64: ".concat(v)); + } + return _xdr["default"].ScVal.scvI64(new _xdr["default"].Int64(v)); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = U64` */ + }, { + key: "toU64", + value: function toU64() { + this._sizeCheck(64); + return _xdr["default"].ScVal.scvU64(new _xdr["default"].Uint64(BigInt.asUintN(64, this.toBigInt())) // reiterpret as unsigned + ); + } + + /** + * @returns {xdr.ScVal} the integer encoded with `ScValType = I128` + * @throws {RangeError} if the value cannot fit in 128 bits + */ + }, { + key: "toI128", + value: function toI128() { + this._sizeCheck(128); + var v = this["int"].toBigInt(); + var hi64 = BigInt.asIntN(64, v >> 64n); // encode top 64 w/ sign bit + var lo64 = BigInt.asUintN(64, v); // grab btm 64, encode sign + + return _xdr["default"].ScVal.scvI128(new _xdr["default"].Int128Parts({ + hi: new _xdr["default"].Int64(hi64), + lo: new _xdr["default"].Uint64(lo64) + })); + } + + /** + * @returns {xdr.ScVal} the integer encoded with `ScValType = U128` + * @throws {RangeError} if the value cannot fit in 128 bits + */ + }, { + key: "toU128", + value: function toU128() { + this._sizeCheck(128); + var v = this["int"].toBigInt(); + return _xdr["default"].ScVal.scvU128(new _xdr["default"].UInt128Parts({ + hi: new _xdr["default"].Uint64(BigInt.asUintN(64, v >> 64n)), + lo: new _xdr["default"].Uint64(BigInt.asUintN(64, v)) + })); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = I256` */ + }, { + key: "toI256", + value: function toI256() { + var v = this["int"].toBigInt(); + var hiHi64 = BigInt.asIntN(64, v >> 192n); // keep sign bit + var hiLo64 = BigInt.asUintN(64, v >> 128n); + var loHi64 = BigInt.asUintN(64, v >> 64n); + var loLo64 = BigInt.asUintN(64, v); + return _xdr["default"].ScVal.scvI256(new _xdr["default"].Int256Parts({ + hiHi: new _xdr["default"].Int64(hiHi64), + hiLo: new _xdr["default"].Uint64(hiLo64), + loHi: new _xdr["default"].Uint64(loHi64), + loLo: new _xdr["default"].Uint64(loLo64) + })); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = U256` */ + }, { + key: "toU256", + value: function toU256() { + var v = this["int"].toBigInt(); + var hiHi64 = BigInt.asUintN(64, v >> 192n); // encode sign bit + var hiLo64 = BigInt.asUintN(64, v >> 128n); + var loHi64 = BigInt.asUintN(64, v >> 64n); + var loLo64 = BigInt.asUintN(64, v); + return _xdr["default"].ScVal.scvU256(new _xdr["default"].UInt256Parts({ + hiHi: new _xdr["default"].Uint64(hiHi64), + hiLo: new _xdr["default"].Uint64(hiLo64), + loHi: new _xdr["default"].Uint64(loHi64), + loLo: new _xdr["default"].Uint64(loLo64) + })); + } + + /** @returns {xdr.ScVal} the smallest interpretation of the stored value */ + }, { + key: "toScVal", + value: function toScVal() { + switch (this.type) { + case 'i64': + return this.toI64(); + case 'i128': + return this.toI128(); + case 'i256': + return this.toI256(); + case 'u64': + return this.toU64(); + case 'u128': + return this.toU128(); + case 'u256': + return this.toU256(); + default: + throw TypeError("invalid type: ".concat(this.type)); + } + } + }, { + key: "valueOf", + value: function valueOf() { + return this["int"].valueOf(); + } + }, { + key: "toString", + value: function toString() { + return this["int"].toString(); + } + }, { + key: "toJSON", + value: function toJSON() { + return { + value: this.toBigInt().toString(), + type: this.type + }; + } + }, { + key: "_sizeCheck", + value: function _sizeCheck(bits) { + if (this["int"].size > bits) { + throw RangeError("value too large for ".concat(bits, " bits (").concat(this.type, ")")); + } + } + }], [{ + key: "isType", + value: function isType(type) { + switch (type) { + case 'i64': + case 'i128': + case 'i256': + case 'u64': + case 'u128': + case 'u256': + return true; + default: + return false; + } + } + + /** + * Convert the raw `ScValType` string (e.g. 'scvI128', generated by the XDR) + * to a type description for {@link XdrLargeInt} construction (e.g. 'i128') + * + * @param {string} scvType the `xdr.ScValType` as a string + * @returns {string} a suitable equivalent type to construct this object + */ + }, { + key: "getType", + value: function getType(scvType) { + return scvType.slice(3).toLowerCase(); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operation.js b/node_modules/@stellar/stellar-base/lib/operation.js new file mode 100644 index 000000000..17ea8620b --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operation.js @@ -0,0 +1,719 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Operation = exports.AuthRevocableFlag = exports.AuthRequiredFlag = exports.AuthImmutableFlag = exports.AuthClawbackEnabledFlag = void 0; +var _jsXdr = require("@stellar/js-xdr"); +var _bignumber = _interopRequireDefault(require("./util/bignumber")); +var _util = require("./util/util"); +var _continued_fraction = require("./util/continued_fraction"); +var _asset = require("./asset"); +var _liquidity_pool_asset = require("./liquidity_pool_asset"); +var _claimant = require("./claimant"); +var _strkey = require("./strkey"); +var _liquidity_pool_id = require("./liquidity_pool_id"); +var _xdr = _interopRequireDefault(require("./xdr")); +var ops = _interopRequireWildcard(require("./operations")); +var _decode_encode_muxed_account = require("./util/decode_encode_muxed_account"); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint-disable no-bitwise */ +var ONE = 10000000; +var MAX_INT64 = '9223372036854775807'; + +/** + * When set using `{@link Operation.setOptions}` option, requires the issuing + * account to give other accounts permission before they can hold the issuing + * account’s credit. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthRequiredFlag = exports.AuthRequiredFlag = 1 << 0; +/** + * When set using `{@link Operation.setOptions}` option, allows the issuing + * account to revoke its credit held by other accounts. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthRevocableFlag = exports.AuthRevocableFlag = 1 << 1; +/** + * When set using `{@link Operation.setOptions}` option, then none of the + * authorization flags can be set and the account can never be deleted. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthImmutableFlag = exports.AuthImmutableFlag = 1 << 2; + +/** + * When set using `{@link Operation.setOptions}` option, then any trustlines + * created by this account can have a ClawbackOp operation submitted for the + * corresponding asset. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthClawbackEnabledFlag = exports.AuthClawbackEnabledFlag = 1 << 3; + +/** + * `Operation` class represents + * [operations](https://developers.stellar.org/docs/glossary/operations/) in + * Stellar network. + * + * Use one of static methods to create operations: + * * `{@link Operation.createAccount}` + * * `{@link Operation.payment}` + * * `{@link Operation.pathPaymentStrictReceive}` + * * `{@link Operation.pathPaymentStrictSend}` + * * `{@link Operation.manageSellOffer}` + * * `{@link Operation.manageBuyOffer}` + * * `{@link Operation.createPassiveSellOffer}` + * * `{@link Operation.setOptions}` + * * `{@link Operation.changeTrust}` + * * `{@link Operation.allowTrust}` + * * `{@link Operation.accountMerge}` + * * `{@link Operation.inflation}` + * * `{@link Operation.manageData}` + * * `{@link Operation.bumpSequence}` + * * `{@link Operation.createClaimableBalance}` + * * `{@link Operation.claimClaimableBalance}` + * * `{@link Operation.beginSponsoringFutureReserves}` + * * `{@link Operation.endSponsoringFutureReserves}` + * * `{@link Operation.revokeAccountSponsorship}` + * * `{@link Operation.revokeTrustlineSponsorship}` + * * `{@link Operation.revokeOfferSponsorship}` + * * `{@link Operation.revokeDataSponsorship}` + * * `{@link Operation.revokeClaimableBalanceSponsorship}` + * * `{@link Operation.revokeLiquidityPoolSponsorship}` + * * `{@link Operation.revokeSignerSponsorship}` + * * `{@link Operation.clawback}` + * * `{@link Operation.clawbackClaimableBalance}` + * * `{@link Operation.setTrustLineFlags}` + * * `{@link Operation.liquidityPoolDeposit}` + * * `{@link Operation.liquidityPoolWithdraw}` + * * `{@link Operation.invokeHostFunction}`, which has the following additional + * "pseudo-operations" that make building host functions easier: + * - `{@link Operation.createStellarAssetContract}` + * - `{@link Operation.invokeContractFunction}` + * - `{@link Operation.createCustomContract}` + * - `{@link Operation.uploadContractWasm}` + * * `{@link Operation.extendFootprintTtlOp}` + * * `{@link Operation.restoreFootprint}` + * + * @class Operation + */ +var Operation = exports.Operation = /*#__PURE__*/function () { + function Operation() { + _classCallCheck(this, Operation); + } + return _createClass(Operation, null, [{ + key: "setSourceAccount", + value: function setSourceAccount(opAttributes, opts) { + if (opts.source) { + try { + opAttributes.sourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.source); + } catch (e) { + throw new Error('Source address is invalid'); + } + } + } + + /** + * Deconstructs the raw XDR operation object into the structured object that + * was used to create the operation (i.e. the `opts` parameter to most ops). + * + * @param {xdr.Operation} operation - An XDR Operation. + * @return {Operation} + */ + }, { + key: "fromXDRObject", + value: function fromXDRObject(operation) { + var result = {}; + if (operation.sourceAccount()) { + result.source = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(operation.sourceAccount()); + } + var attrs = operation.body().value(); + var operationName = operation.body()["switch"]().name; + switch (operationName) { + case 'createAccount': + { + result.type = 'createAccount'; + result.destination = accountIdtoAddress(attrs.destination()); + result.startingBalance = this._fromXDRAmount(attrs.startingBalance()); + break; + } + case 'payment': + { + result.type = 'payment'; + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.amount = this._fromXDRAmount(attrs.amount()); + break; + } + case 'pathPaymentStrictReceive': + { + result.type = 'pathPaymentStrictReceive'; + result.sendAsset = _asset.Asset.fromOperation(attrs.sendAsset()); + result.sendMax = this._fromXDRAmount(attrs.sendMax()); + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.destAsset = _asset.Asset.fromOperation(attrs.destAsset()); + result.destAmount = this._fromXDRAmount(attrs.destAmount()); + result.path = []; + var path = attrs.path(); + + // note that Object.values isn't supported by node 6! + Object.keys(path).forEach(function (pathKey) { + result.path.push(_asset.Asset.fromOperation(path[pathKey])); + }); + break; + } + case 'pathPaymentStrictSend': + { + result.type = 'pathPaymentStrictSend'; + result.sendAsset = _asset.Asset.fromOperation(attrs.sendAsset()); + result.sendAmount = this._fromXDRAmount(attrs.sendAmount()); + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.destAsset = _asset.Asset.fromOperation(attrs.destAsset()); + result.destMin = this._fromXDRAmount(attrs.destMin()); + result.path = []; + var _path = attrs.path(); + + // note that Object.values isn't supported by node 6! + Object.keys(_path).forEach(function (pathKey) { + result.path.push(_asset.Asset.fromOperation(_path[pathKey])); + }); + break; + } + case 'changeTrust': + { + result.type = 'changeTrust'; + switch (attrs.line()["switch"]()) { + case _xdr["default"].AssetType.assetTypePoolShare(): + result.line = _liquidity_pool_asset.LiquidityPoolAsset.fromOperation(attrs.line()); + break; + default: + result.line = _asset.Asset.fromOperation(attrs.line()); + break; + } + result.limit = this._fromXDRAmount(attrs.limit()); + break; + } + case 'allowTrust': + { + result.type = 'allowTrust'; + result.trustor = accountIdtoAddress(attrs.trustor()); + result.assetCode = attrs.asset().value().toString(); + result.assetCode = (0, _util.trimEnd)(result.assetCode, '\0'); + result.authorize = attrs.authorize(); + break; + } + case 'setOptions': + { + result.type = 'setOptions'; + if (attrs.inflationDest()) { + result.inflationDest = accountIdtoAddress(attrs.inflationDest()); + } + result.clearFlags = attrs.clearFlags(); + result.setFlags = attrs.setFlags(); + result.masterWeight = attrs.masterWeight(); + result.lowThreshold = attrs.lowThreshold(); + result.medThreshold = attrs.medThreshold(); + result.highThreshold = attrs.highThreshold(); + // home_domain is checked by iscntrl in stellar-core + result.homeDomain = attrs.homeDomain() !== undefined ? attrs.homeDomain().toString('ascii') : undefined; + if (attrs.signer()) { + var signer = {}; + var arm = attrs.signer().key().arm(); + if (arm === 'ed25519') { + signer.ed25519PublicKey = accountIdtoAddress(attrs.signer().key()); + } else if (arm === 'preAuthTx') { + signer.preAuthTx = attrs.signer().key().preAuthTx(); + } else if (arm === 'hashX') { + signer.sha256Hash = attrs.signer().key().hashX(); + } else if (arm === 'ed25519SignedPayload') { + var signedPayload = attrs.signer().key().ed25519SignedPayload(); + signer.ed25519SignedPayload = _strkey.StrKey.encodeSignedPayload(signedPayload.toXDR()); + } + signer.weight = attrs.signer().weight(); + result.signer = signer; + } + break; + } + // the next case intentionally falls through! + case 'manageOffer': + case 'manageSellOffer': + { + result.type = 'manageSellOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.price = this._fromXDRPrice(attrs.price()); + result.offerId = attrs.offerId().toString(); + break; + } + case 'manageBuyOffer': + { + result.type = 'manageBuyOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.buyAmount = this._fromXDRAmount(attrs.buyAmount()); + result.price = this._fromXDRPrice(attrs.price()); + result.offerId = attrs.offerId().toString(); + break; + } + // the next case intentionally falls through! + case 'createPassiveOffer': + case 'createPassiveSellOffer': + { + result.type = 'createPassiveSellOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.price = this._fromXDRPrice(attrs.price()); + break; + } + case 'accountMerge': + { + result.type = 'accountMerge'; + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs); + break; + } + case 'manageData': + { + result.type = 'manageData'; + // manage_data.name is checked by iscntrl in stellar-core + result.name = attrs.dataName().toString('ascii'); + result.value = attrs.dataValue(); + break; + } + case 'inflation': + { + result.type = 'inflation'; + break; + } + case 'bumpSequence': + { + result.type = 'bumpSequence'; + result.bumpTo = attrs.bumpTo().toString(); + break; + } + case 'createClaimableBalance': + { + result.type = 'createClaimableBalance'; + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.claimants = []; + attrs.claimants().forEach(function (claimant) { + result.claimants.push(_claimant.Claimant.fromXDR(claimant)); + }); + break; + } + case 'claimClaimableBalance': + { + result.type = 'claimClaimableBalance'; + result.balanceId = attrs.toXDR('hex'); + break; + } + case 'beginSponsoringFutureReserves': + { + result.type = 'beginSponsoringFutureReserves'; + result.sponsoredId = accountIdtoAddress(attrs.sponsoredId()); + break; + } + case 'endSponsoringFutureReserves': + { + result.type = 'endSponsoringFutureReserves'; + break; + } + case 'revokeSponsorship': + { + extractRevokeSponshipDetails(attrs, result); + break; + } + case 'clawback': + { + result.type = 'clawback'; + result.amount = this._fromXDRAmount(attrs.amount()); + result.from = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.from()); + result.asset = _asset.Asset.fromOperation(attrs.asset()); + break; + } + case 'clawbackClaimableBalance': + { + result.type = 'clawbackClaimableBalance'; + result.balanceId = attrs.toXDR('hex'); + break; + } + case 'setTrustLineFlags': + { + result.type = 'setTrustLineFlags'; + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.trustor = accountIdtoAddress(attrs.trustor()); + + // Convert from the integer-bitwised flag into a sensible object that + // indicates true/false for each flag that's on/off. + var clears = attrs.clearFlags(); + var sets = attrs.setFlags(); + var mapping = { + authorized: _xdr["default"].TrustLineFlags.authorizedFlag(), + authorizedToMaintainLiabilities: _xdr["default"].TrustLineFlags.authorizedToMaintainLiabilitiesFlag(), + clawbackEnabled: _xdr["default"].TrustLineFlags.trustlineClawbackEnabledFlag() + }; + var getFlagValue = function getFlagValue(key) { + var bit = mapping[key].value; + if (sets & bit) { + return true; + } + if (clears & bit) { + return false; + } + return undefined; + }; + result.flags = {}; + Object.keys(mapping).forEach(function (flagName) { + result.flags[flagName] = getFlagValue(flagName); + }); + break; + } + case 'liquidityPoolDeposit': + { + result.type = 'liquidityPoolDeposit'; + result.liquidityPoolId = attrs.liquidityPoolId().toString('hex'); + result.maxAmountA = this._fromXDRAmount(attrs.maxAmountA()); + result.maxAmountB = this._fromXDRAmount(attrs.maxAmountB()); + result.minPrice = this._fromXDRPrice(attrs.minPrice()); + result.maxPrice = this._fromXDRPrice(attrs.maxPrice()); + break; + } + case 'liquidityPoolWithdraw': + { + result.type = 'liquidityPoolWithdraw'; + result.liquidityPoolId = attrs.liquidityPoolId().toString('hex'); + result.amount = this._fromXDRAmount(attrs.amount()); + result.minAmountA = this._fromXDRAmount(attrs.minAmountA()); + result.minAmountB = this._fromXDRAmount(attrs.minAmountB()); + break; + } + case 'invokeHostFunction': + { + var _attrs$auth; + result.type = 'invokeHostFunction'; + result.func = attrs.hostFunction(); + result.auth = (_attrs$auth = attrs.auth()) !== null && _attrs$auth !== void 0 ? _attrs$auth : []; + break; + } + case 'extendFootprintTtl': + { + result.type = 'extendFootprintTtl'; + result.extendTo = attrs.extendTo(); + break; + } + case 'restoreFootprint': + { + result.type = 'restoreFootprint'; + break; + } + default: + { + throw new Error("Unknown operation: ".concat(operationName)); + } + } + return result; + } + + /** + * Validates that a given amount is possible for a Stellar asset. + * + * Specifically, this means that the amount is well, a valid number, but also + * that it is within the int64 range and has no more than 7 decimal levels of + * precision. + * + * Note that while smart contracts allow larger amounts, this is oriented + * towards validating the standard Stellar operations. + * + * @param {string} value the amount to validate + * @param {boolean} allowZero optionally, whether or not zero is valid (default: no) + * + * @returns {boolean} + */ + }, { + key: "isValidAmount", + value: function isValidAmount(value) { + var allowZero = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (typeof value !== 'string') { + return false; + } + var amount; + try { + amount = new _bignumber["default"](value); + } catch (e) { + return false; + } + if ( + // == 0 + !allowZero && amount.isZero() || + // < 0 + amount.isNegative() || + // > Max value + amount.times(ONE).gt(new _bignumber["default"](MAX_INT64).toString()) || + // Decimal places (max 7) + amount.decimalPlaces() > 7 || + // NaN or Infinity + amount.isNaN() || !amount.isFinite()) { + return false; + } + return true; + } + }, { + key: "constructAmountRequirementsError", + value: function constructAmountRequirementsError(arg) { + return "".concat(arg, " argument must be of type String, represent a positive number and have at most 7 digits after the decimal"); + } + + /** + * Returns value converted to uint32 value or undefined. + * If `value` is not `Number`, `String` or `Undefined` then throws an error. + * Used in {@link Operation.setOptions}. + * @private + * @param {string} name Name of the property (used in error message only) + * @param {*} value Value to check + * @param {function(value, name)} isValidFunction Function to check other constraints (the argument will be a `Number`) + * @returns {undefined|Number} + */ + }, { + key: "_checkUnsignedIntValue", + value: function _checkUnsignedIntValue(name, value) { + var isValidFunction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + if (typeof value === 'undefined') { + return undefined; + } + if (typeof value === 'string') { + value = parseFloat(value); + } + switch (true) { + case typeof value !== 'number' || !Number.isFinite(value) || value % 1 !== 0: + throw new Error("".concat(name, " value is invalid")); + case value < 0: + throw new Error("".concat(name, " value must be unsigned")); + case !isValidFunction || isValidFunction && isValidFunction(value, name): + return value; + default: + throw new Error("".concat(name, " value is invalid")); + } + } + /** + * @private + * @param {string|BigNumber} value Value + * @returns {Hyper} XDR amount + */ + }, { + key: "_toXDRAmount", + value: function _toXDRAmount(value) { + var amount = new _bignumber["default"](value).times(ONE); + return _jsXdr.Hyper.fromString(amount.toString()); + } + + /** + * @private + * @param {string|BigNumber} value XDR amount + * @returns {BigNumber} Number + */ + }, { + key: "_fromXDRAmount", + value: function _fromXDRAmount(value) { + return new _bignumber["default"](value).div(ONE).toFixed(7); + } + + /** + * @private + * @param {object} price Price object + * @param {function} price.n numerator function that returns a value + * @param {function} price.d denominator function that returns a value + * @returns {BigNumber} Big string + */ + }, { + key: "_fromXDRPrice", + value: function _fromXDRPrice(price) { + var n = new _bignumber["default"](price.n()); + return n.div(new _bignumber["default"](price.d())).toString(); + } + + /** + * @private + * @param {object} price Price object + * @param {function} price.n numerator function that returns a value + * @param {function} price.d denominator function that returns a value + * @returns {object} XDR price object + */ + }, { + key: "_toXDRPrice", + value: function _toXDRPrice(price) { + var xdrObject; + if (price.n && price.d) { + xdrObject = new _xdr["default"].Price(price); + } else { + var approx = (0, _continued_fraction.best_r)(price); + xdrObject = new _xdr["default"].Price({ + n: parseInt(approx[0], 10), + d: parseInt(approx[1], 10) + }); + } + if (xdrObject.n() < 0 || xdrObject.d() < 0) { + throw new Error('price must be positive'); + } + return xdrObject; + } + }]); +}(); +function extractRevokeSponshipDetails(attrs, result) { + switch (attrs["switch"]().name) { + case 'revokeSponsorshipLedgerEntry': + { + var ledgerKey = attrs.ledgerKey(); + switch (ledgerKey["switch"]().name) { + case _xdr["default"].LedgerEntryType.account().name: + { + result.type = 'revokeAccountSponsorship'; + result.account = accountIdtoAddress(ledgerKey.account().accountId()); + break; + } + case _xdr["default"].LedgerEntryType.trustline().name: + { + result.type = 'revokeTrustlineSponsorship'; + result.account = accountIdtoAddress(ledgerKey.trustLine().accountId()); + var xdrAsset = ledgerKey.trustLine().asset(); + switch (xdrAsset["switch"]()) { + case _xdr["default"].AssetType.assetTypePoolShare(): + result.asset = _liquidity_pool_id.LiquidityPoolId.fromOperation(xdrAsset); + break; + default: + result.asset = _asset.Asset.fromOperation(xdrAsset); + break; + } + break; + } + case _xdr["default"].LedgerEntryType.offer().name: + { + result.type = 'revokeOfferSponsorship'; + result.seller = accountIdtoAddress(ledgerKey.offer().sellerId()); + result.offerId = ledgerKey.offer().offerId().toString(); + break; + } + case _xdr["default"].LedgerEntryType.data().name: + { + result.type = 'revokeDataSponsorship'; + result.account = accountIdtoAddress(ledgerKey.data().accountId()); + result.name = ledgerKey.data().dataName().toString('ascii'); + break; + } + case _xdr["default"].LedgerEntryType.claimableBalance().name: + { + result.type = 'revokeClaimableBalanceSponsorship'; + result.balanceId = ledgerKey.claimableBalance().balanceId().toXDR('hex'); + break; + } + case _xdr["default"].LedgerEntryType.liquidityPool().name: + { + result.type = 'revokeLiquidityPoolSponsorship'; + result.liquidityPoolId = ledgerKey.liquidityPool().liquidityPoolId().toString('hex'); + break; + } + default: + { + throw new Error("Unknown ledgerKey: ".concat(attrs["switch"]().name)); + } + } + break; + } + case 'revokeSponsorshipSigner': + { + result.type = 'revokeSignerSponsorship'; + result.account = accountIdtoAddress(attrs.signer().accountId()); + result.signer = convertXDRSignerKeyToObject(attrs.signer().signerKey()); + break; + } + default: + { + throw new Error("Unknown revokeSponsorship: ".concat(attrs["switch"]().name)); + } + } +} +function convertXDRSignerKeyToObject(signerKey) { + var attrs = {}; + switch (signerKey["switch"]().name) { + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519().name: + { + attrs.ed25519PublicKey = _strkey.StrKey.encodeEd25519PublicKey(signerKey.ed25519()); + break; + } + case _xdr["default"].SignerKeyType.signerKeyTypePreAuthTx().name: + { + attrs.preAuthTx = signerKey.preAuthTx().toString('hex'); + break; + } + case _xdr["default"].SignerKeyType.signerKeyTypeHashX().name: + { + attrs.sha256Hash = signerKey.hashX().toString('hex'); + break; + } + default: + { + throw new Error("Unknown signerKey: ".concat(signerKey["switch"]().name)); + } + } + return attrs; +} +function accountIdtoAddress(accountId) { + return _strkey.StrKey.encodeEd25519PublicKey(accountId.ed25519()); +} + +// Attach all imported operations as static methods on the Operation class +Operation.accountMerge = ops.accountMerge; +Operation.allowTrust = ops.allowTrust; +Operation.bumpSequence = ops.bumpSequence; +Operation.changeTrust = ops.changeTrust; +Operation.createAccount = ops.createAccount; +Operation.createClaimableBalance = ops.createClaimableBalance; +Operation.claimClaimableBalance = ops.claimClaimableBalance; +Operation.clawbackClaimableBalance = ops.clawbackClaimableBalance; +Operation.createPassiveSellOffer = ops.createPassiveSellOffer; +Operation.inflation = ops.inflation; +Operation.manageData = ops.manageData; +Operation.manageSellOffer = ops.manageSellOffer; +Operation.manageBuyOffer = ops.manageBuyOffer; +Operation.pathPaymentStrictReceive = ops.pathPaymentStrictReceive; +Operation.pathPaymentStrictSend = ops.pathPaymentStrictSend; +Operation.payment = ops.payment; +Operation.setOptions = ops.setOptions; +Operation.beginSponsoringFutureReserves = ops.beginSponsoringFutureReserves; +Operation.endSponsoringFutureReserves = ops.endSponsoringFutureReserves; +Operation.revokeAccountSponsorship = ops.revokeAccountSponsorship; +Operation.revokeTrustlineSponsorship = ops.revokeTrustlineSponsorship; +Operation.revokeOfferSponsorship = ops.revokeOfferSponsorship; +Operation.revokeDataSponsorship = ops.revokeDataSponsorship; +Operation.revokeClaimableBalanceSponsorship = ops.revokeClaimableBalanceSponsorship; +Operation.revokeLiquidityPoolSponsorship = ops.revokeLiquidityPoolSponsorship; +Operation.revokeSignerSponsorship = ops.revokeSignerSponsorship; +Operation.clawback = ops.clawback; +Operation.setTrustLineFlags = ops.setTrustLineFlags; +Operation.liquidityPoolDeposit = ops.liquidityPoolDeposit; +Operation.liquidityPoolWithdraw = ops.liquidityPoolWithdraw; +Operation.invokeHostFunction = ops.invokeHostFunction; +Operation.extendFootprintTtl = ops.extendFootprintTtl; +Operation.restoreFootprint = ops.restoreFootprint; + +// these are not `xdr.Operation`s directly, but are proxies for complex but +// common versions of `Operation.invokeHostFunction` +Operation.createStellarAssetContract = ops.createStellarAssetContract; +Operation.invokeContractFunction = ops.invokeContractFunction; +Operation.createCustomContract = ops.createCustomContract; +Operation.uploadContractWasm = ops.uploadContractWasm; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/account_merge.js b/node_modules/@stellar/stellar-base/lib/operations/account_merge.js new file mode 100644 index 000000000..f910fa543 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/account_merge.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.accountMerge = accountMerge; +var _xdr = _interopRequireDefault(require("../xdr")); +var _decode_encode_muxed_account = require("../util/decode_encode_muxed_account"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Transfers native balance to destination account. + * + * @function + * @alias Operation.accountMerge + * + * @param {object} opts - options object + * @param {string} opts.destination - destination to merge the source account into + * @param {string} [opts.source] - operation source account (defaults to + * transaction source) + * + * @returns {xdr.Operation} an Account Merge operation (xdr.AccountMergeOp) + */ +function accountMerge(opts) { + var opAttributes = {}; + try { + opAttributes.body = _xdr["default"].OperationBody.accountMerge((0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination)); + } catch (e) { + throw new Error('destination is invalid'); + } + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/allow_trust.js b/node_modules/@stellar/stellar-base/lib/operations/allow_trust.js new file mode 100644 index 000000000..85dd6e61f --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/allow_trust.js @@ -0,0 +1,57 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.allowTrust = allowTrust; +var _xdr = _interopRequireDefault(require("../xdr")); +var _keypair = require("../keypair"); +var _strkey = require("../strkey"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * @deprecated since v5.0 + * + * Returns an XDR AllowTrustOp. An "allow trust" operation authorizes another + * account to hold your account's credit for a given asset. + * + * @function + * @alias Operation.allowTrust + * + * @param {object} opts Options object + * @param {string} opts.trustor - The trusting account (the one being authorized) + * @param {string} opts.assetCode - The asset code being authorized. + * @param {(0|1|2)} opts.authorize - `1` to authorize, `2` to authorize to maintain liabilities, and `0` to deauthorize. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * + * @returns {xdr.AllowTrustOp} Allow Trust operation + */ +function allowTrust(opts) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.trustor)) { + throw new Error('trustor is invalid'); + } + var attributes = {}; + attributes.trustor = _keypair.Keypair.fromPublicKey(opts.trustor).xdrAccountId(); + if (opts.assetCode.length <= 4) { + var code = opts.assetCode.padEnd(4, '\0'); + attributes.asset = _xdr["default"].AssetCode.assetTypeCreditAlphanum4(code); + } else if (opts.assetCode.length <= 12) { + var _code = opts.assetCode.padEnd(12, '\0'); + attributes.asset = _xdr["default"].AssetCode.assetTypeCreditAlphanum12(_code); + } else { + throw new Error('Asset code must be 12 characters at max.'); + } + if (typeof opts.authorize === 'boolean') { + if (opts.authorize) { + attributes.authorize = _xdr["default"].TrustLineFlags.authorizedFlag().value; + } else { + attributes.authorize = 0; + } + } else { + attributes.authorize = opts.authorize; + } + var allowTrustOp = new _xdr["default"].AllowTrustOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.allowTrust(allowTrustOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/begin_sponsoring_future_reserves.js b/node_modules/@stellar/stellar-base/lib/operations/begin_sponsoring_future_reserves.js new file mode 100644 index 000000000..0e7e0e894 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/begin_sponsoring_future_reserves.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.beginSponsoringFutureReserves = beginSponsoringFutureReserves; +var _xdr = _interopRequireDefault(require("../xdr")); +var _strkey = require("../strkey"); +var _keypair = require("../keypair"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a "begin sponsoring future reserves" operation. + * @function + * @alias Operation.beginSponsoringFutureReserves + * @param {object} opts Options object + * @param {string} opts.sponsoredId - The sponsored account id. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.beginSponsoringFutureReserves({ + * sponsoredId: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * }); + * + */ +function beginSponsoringFutureReserves() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.sponsoredId)) { + throw new Error('sponsoredId is invalid'); + } + var op = new _xdr["default"].BeginSponsoringFutureReservesOp({ + sponsoredId: _keypair.Keypair.fromPublicKey(opts.sponsoredId).xdrAccountId() + }); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.beginSponsoringFutureReserves(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/bump_sequence.js b/node_modules/@stellar/stellar-base/lib/operations/bump_sequence.js new file mode 100644 index 000000000..9e48d6ab1 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/bump_sequence.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.bumpSequence = bumpSequence; +var _jsXdr = require("@stellar/js-xdr"); +var _bignumber = _interopRequireDefault(require("../util/bignumber")); +var _xdr = _interopRequireDefault(require("../xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation bumps sequence number. + * @function + * @alias Operation.bumpSequence + * @param {object} opts Options object + * @param {string} opts.bumpTo - Sequence number to bump to. + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.BumpSequenceOp} Operation + */ +function bumpSequence(opts) { + var attributes = {}; + if (typeof opts.bumpTo !== 'string') { + throw new Error('bumpTo must be a string'); + } + try { + // eslint-disable-next-line no-new + new _bignumber["default"](opts.bumpTo); + } catch (e) { + throw new Error('bumpTo must be a stringified number'); + } + attributes.bumpTo = _jsXdr.Hyper.fromString(opts.bumpTo); + var bumpSequenceOp = new _xdr["default"].BumpSequenceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.bumpSequence(bumpSequenceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/change_trust.js b/node_modules/@stellar/stellar-base/lib/operations/change_trust.js new file mode 100644 index 000000000..0c9ad2143 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/change_trust.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.changeTrust = changeTrust; +var _jsXdr = require("@stellar/js-xdr"); +var _bignumber = _interopRequireDefault(require("../util/bignumber")); +var _xdr = _interopRequireDefault(require("../xdr")); +var _asset = require("../asset"); +var _liquidity_pool_asset = require("../liquidity_pool_asset"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var MAX_INT64 = '9223372036854775807'; + +/** + * Returns an XDR ChangeTrustOp. A "change trust" operation adds, removes, or updates a + * trust line for a given asset from the source account to another. + * @function + * @alias Operation.changeTrust + * @param {object} opts Options object + * @param {Asset | LiquidityPoolAsset} opts.asset - The asset for the trust line. + * @param {string} [opts.limit] - The limit for the asset, defaults to max int64. + * If the limit is set to "0" it deletes the trustline. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @returns {xdr.ChangeTrustOp} Change Trust operation + */ +function changeTrust(opts) { + var attributes = {}; + if (opts.asset instanceof _asset.Asset) { + attributes.line = opts.asset.toChangeTrustXDRObject(); + } else if (opts.asset instanceof _liquidity_pool_asset.LiquidityPoolAsset) { + attributes.line = opts.asset.toXDRObject(); + } else { + throw new TypeError('asset must be Asset or LiquidityPoolAsset'); + } + if (opts.limit !== undefined && !this.isValidAmount(opts.limit, true)) { + throw new TypeError(this.constructAmountRequirementsError('limit')); + } + if (opts.limit) { + attributes.limit = this._toXDRAmount(opts.limit); + } else { + attributes.limit = _jsXdr.Hyper.fromString(new _bignumber["default"](MAX_INT64).toString()); + } + if (opts.source) { + attributes.source = opts.source.masterKeypair; + } + var changeTrustOP = new _xdr["default"].ChangeTrustOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.changeTrust(changeTrustOP); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/claim_claimable_balance.js b/node_modules/@stellar/stellar-base/lib/operations/claim_claimable_balance.js new file mode 100644 index 000000000..62434b862 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/claim_claimable_balance.js @@ -0,0 +1,40 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.claimClaimableBalance = claimClaimableBalance; +exports.validateClaimableBalanceId = validateClaimableBalanceId; +var _xdr = _interopRequireDefault(require("../xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a new claim claimable balance operation. + * @function + * @alias Operation.claimClaimableBalance + * @param {object} opts Options object + * @param {string} opts.balanceId - The claimable balance id to be claimed. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} Claim claimable balance operation + * + * @example + * const op = Operation.claimClaimableBalance({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + */ +function claimClaimableBalance() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + validateClaimableBalanceId(opts.balanceId); + var attributes = {}; + attributes.balanceId = _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex'); + var claimClaimableBalanceOp = new _xdr["default"].ClaimClaimableBalanceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.claimClaimableBalance(claimClaimableBalanceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} +function validateClaimableBalanceId(balanceId) { + if (typeof balanceId !== 'string' || balanceId.length !== 8 + 64 /* 8b discriminant + 64b string */) { + throw new Error('must provide a valid claimable balance id'); + } +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/clawback.js b/node_modules/@stellar/stellar-base/lib/operations/clawback.js new file mode 100644 index 000000000..eb4bf6d74 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/clawback.js @@ -0,0 +1,46 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.clawback = clawback; +var _xdr = _interopRequireDefault(require("../xdr")); +var _decode_encode_muxed_account = require("../util/decode_encode_muxed_account"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a clawback operation. + * + * @function + * @alias Operation.clawback + * + * @param {object} opts - Options object + * @param {Asset} opts.asset - The asset being clawed back. + * @param {string} opts.amount - The amount of the asset to claw back. + * @param {string} opts.from - The public key of the (optionally-muxed) + * account to claw back from. + * + * @param {string} [opts.source] - The source account for the operation. + * Defaults to the transaction's source account. + * + * @return {xdr.ClawbackOp} + * + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#clawback-operation + */ +function clawback(opts) { + var attributes = {}; + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + attributes.asset = opts.asset.toXDRObject(); + try { + attributes.from = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.from); + } catch (e) { + throw new Error('from address is invalid'); + } + var opAttributes = { + body: _xdr["default"].OperationBody.clawback(new _xdr["default"].ClawbackOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/clawback_claimable_balance.js b/node_modules/@stellar/stellar-base/lib/operations/clawback_claimable_balance.js new file mode 100644 index 000000000..2603ce18c --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/clawback_claimable_balance.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.clawbackClaimableBalance = clawbackClaimableBalance; +var _xdr = _interopRequireDefault(require("../xdr")); +var _claim_claimable_balance = require("./claim_claimable_balance"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a clawback operation for a claimable balance. + * + * @function + * @alias Operation.clawbackClaimableBalance + * @param {object} opts - Options object + * @param {string} opts.balanceId - The claimable balance ID to be clawed back. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @return {xdr.ClawbackClaimableBalanceOp} + * + * @example + * const op = Operation.clawbackClaimableBalance({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + * @link https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#clawback-claimable-balance-operation + */ +function clawbackClaimableBalance() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + (0, _claim_claimable_balance.validateClaimableBalanceId)(opts.balanceId); + var attributes = { + balanceId: _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex') + }; + var opAttributes = { + body: _xdr["default"].OperationBody.clawbackClaimableBalance(new _xdr["default"].ClawbackClaimableBalanceOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/create_account.js b/node_modules/@stellar/stellar-base/lib/operations/create_account.js new file mode 100644 index 000000000..dd64bf664 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/create_account.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createAccount = createAccount; +var _xdr = _interopRequireDefault(require("../xdr")); +var _keypair = require("../keypair"); +var _strkey = require("../strkey"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create and fund a non existent account. + * @function + * @alias Operation.createAccount + * @param {object} opts Options object + * @param {string} opts.destination - Destination account ID to create an account for. + * @param {string} opts.startingBalance - Amount in XLM the account should be funded for. Must be greater + * than the [reserve balance amount](https://developers.stellar.org/docs/glossary/fees/). + * @param {string} [opts.source] - The source account for the payment. Defaults to the transaction's source account. + * @returns {xdr.CreateAccountOp} Create account operation + */ +function createAccount(opts) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.destination)) { + throw new Error('destination is invalid'); + } + if (!this.isValidAmount(opts.startingBalance, true)) { + throw new TypeError(this.constructAmountRequirementsError('startingBalance')); + } + var attributes = {}; + attributes.destination = _keypair.Keypair.fromPublicKey(opts.destination).xdrAccountId(); + attributes.startingBalance = this._toXDRAmount(opts.startingBalance); + var createAccountOp = new _xdr["default"].CreateAccountOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createAccount(createAccountOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/create_claimable_balance.js b/node_modules/@stellar/stellar-base/lib/operations/create_claimable_balance.js new file mode 100644 index 000000000..1e3437c45 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/create_claimable_balance.js @@ -0,0 +1,65 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createClaimableBalance = createClaimableBalance; +var _xdr = _interopRequireDefault(require("../xdr")); +var _asset = require("../asset"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a new claimable balance operation. + * + * @function + * @alias Operation.createClaimableBalance + * + * @param {object} opts Options object + * @param {Asset} opts.asset - The asset for the claimable balance. + * @param {string} opts.amount - Amount. + * @param {Claimant[]} opts.claimants - An array of Claimants + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} Create claimable balance operation + * + * @example + * const asset = new Asset( + * 'USD', + * 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * ); + * const amount = '100.0000000'; + * const claimants = [ + * new Claimant( + * 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ', + * Claimant.predicateBeforeAbsoluteTime("4102444800000") + * ) + * ]; + * + * const op = Operation.createClaimableBalance({ + * asset, + * amount, + * claimants + * }); + * + */ +function createClaimableBalance(opts) { + if (!(opts.asset instanceof _asset.Asset)) { + throw new Error('must provide an asset for create claimable balance operation'); + } + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + if (!Array.isArray(opts.claimants) || opts.claimants.length === 0) { + throw new Error('must provide at least one claimant'); + } + var attributes = {}; + attributes.asset = opts.asset.toXDRObject(); + attributes.amount = this._toXDRAmount(opts.amount); + attributes.claimants = Object.values(opts.claimants).map(function (c) { + return c.toXDRObject(); + }); + var createClaimableBalanceOp = new _xdr["default"].CreateClaimableBalanceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createClaimableBalance(createClaimableBalanceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/create_passive_sell_offer.js b/node_modules/@stellar/stellar-base/lib/operations/create_passive_sell_offer.js new file mode 100644 index 000000000..af9438a8b --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/create_passive_sell_offer.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createPassiveSellOffer = createPassiveSellOffer; +var _xdr = _interopRequireDefault(require("../xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR CreatePasiveSellOfferOp. A "create passive offer" operation creates an + * offer that won't consume a counter offer that exactly matches this offer. This is + * useful for offers just used as 1:1 exchanges for path payments. Use manage offer + * to manage this offer after using this operation to create it. + * @function + * @alias Operation.createPassiveSellOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.CreatePassiveSellOfferOp} Create Passive Sell Offer operation + */ +function createPassiveSellOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + var createPassiveSellOfferOp = new _xdr["default"].CreatePassiveSellOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createPassiveSellOffer(createPassiveSellOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/end_sponsoring_future_reserves.js b/node_modules/@stellar/stellar-base/lib/operations/end_sponsoring_future_reserves.js new file mode 100644 index 000000000..1ccf91ea7 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/end_sponsoring_future_reserves.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.endSponsoringFutureReserves = endSponsoringFutureReserves; +var _xdr = _interopRequireDefault(require("../xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create an "end sponsoring future reserves" operation. + * @function + * @alias Operation.endSponsoringFutureReserves + * @param {object} opts Options object + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.endSponsoringFutureReserves(); + * + */ +function endSponsoringFutureReserves() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.endSponsoringFutureReserves(); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/extend_footprint_ttl.js b/node_modules/@stellar/stellar-base/lib/operations/extend_footprint_ttl.js new file mode 100644 index 000000000..c91a5189f --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/extend_footprint_ttl.js @@ -0,0 +1,53 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.extendFootprintTtl = extendFootprintTtl; +var _xdr = _interopRequireDefault(require("../xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Builds an operation to bump the time-to-live (TTL) of the ledger keys. The + * keys for extension have to be provided in the read-only footprint of + * the transaction. + * + * The only parameter of the operation itself is the new minimum TTL for + * all the provided entries. If an entry already has a higher TTL, then it + * will just be skipped. + * + * TTL is the number of ledgers from the current ledger (exclusive) until + * the last ledger the entry is still considered alive (inclusive). Thus + * the exact ledger until the entries will live will only be determined + * when transaction has been applied. + * + * The footprint has to be specified in the transaction. See + * {@link TransactionBuilder}'s `opts.sorobanData` parameter, which is a + * {@link xdr.SorobanTransactionData} instance that contains fee data & resource + * usage as part of {@link xdr.SorobanResources}. + * + * @function + * @alias Operation.extendFootprintTtl + * + * @param {object} opts - object holding operation parameters + * @param {number} opts.extendTo - the minimum TTL that all the entries in + * the read-only footprint will have + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Extend Footprint TTL operation + * (xdr.ExtendFootprintTTLOp) + */ +function extendFootprintTtl(opts) { + var _opts$extendTo; + if (((_opts$extendTo = opts.extendTo) !== null && _opts$extendTo !== void 0 ? _opts$extendTo : -1) <= 0) { + throw new RangeError('extendTo has to be positive'); + } + var extendFootprintOp = new _xdr["default"].ExtendFootprintTtlOp({ + ext: new _xdr["default"].ExtensionPoint(0), + extendTo: opts.extendTo + }); + var opAttributes = { + body: _xdr["default"].OperationBody.extendFootprintTtl(extendFootprintOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/index.js b/node_modules/@stellar/stellar-base/lib/operations/index.js new file mode 100644 index 000000000..b0fbd9893 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/index.js @@ -0,0 +1,254 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "accountMerge", { + enumerable: true, + get: function get() { + return _account_merge.accountMerge; + } +}); +Object.defineProperty(exports, "allowTrust", { + enumerable: true, + get: function get() { + return _allow_trust.allowTrust; + } +}); +Object.defineProperty(exports, "beginSponsoringFutureReserves", { + enumerable: true, + get: function get() { + return _begin_sponsoring_future_reserves.beginSponsoringFutureReserves; + } +}); +Object.defineProperty(exports, "bumpSequence", { + enumerable: true, + get: function get() { + return _bump_sequence.bumpSequence; + } +}); +Object.defineProperty(exports, "changeTrust", { + enumerable: true, + get: function get() { + return _change_trust.changeTrust; + } +}); +Object.defineProperty(exports, "claimClaimableBalance", { + enumerable: true, + get: function get() { + return _claim_claimable_balance.claimClaimableBalance; + } +}); +Object.defineProperty(exports, "clawback", { + enumerable: true, + get: function get() { + return _clawback.clawback; + } +}); +Object.defineProperty(exports, "clawbackClaimableBalance", { + enumerable: true, + get: function get() { + return _clawback_claimable_balance.clawbackClaimableBalance; + } +}); +Object.defineProperty(exports, "createAccount", { + enumerable: true, + get: function get() { + return _create_account.createAccount; + } +}); +Object.defineProperty(exports, "createClaimableBalance", { + enumerable: true, + get: function get() { + return _create_claimable_balance.createClaimableBalance; + } +}); +Object.defineProperty(exports, "createCustomContract", { + enumerable: true, + get: function get() { + return _invoke_host_function.createCustomContract; + } +}); +Object.defineProperty(exports, "createPassiveSellOffer", { + enumerable: true, + get: function get() { + return _create_passive_sell_offer.createPassiveSellOffer; + } +}); +Object.defineProperty(exports, "createStellarAssetContract", { + enumerable: true, + get: function get() { + return _invoke_host_function.createStellarAssetContract; + } +}); +Object.defineProperty(exports, "endSponsoringFutureReserves", { + enumerable: true, + get: function get() { + return _end_sponsoring_future_reserves.endSponsoringFutureReserves; + } +}); +Object.defineProperty(exports, "extendFootprintTtl", { + enumerable: true, + get: function get() { + return _extend_footprint_ttl.extendFootprintTtl; + } +}); +Object.defineProperty(exports, "inflation", { + enumerable: true, + get: function get() { + return _inflation.inflation; + } +}); +Object.defineProperty(exports, "invokeContractFunction", { + enumerable: true, + get: function get() { + return _invoke_host_function.invokeContractFunction; + } +}); +Object.defineProperty(exports, "invokeHostFunction", { + enumerable: true, + get: function get() { + return _invoke_host_function.invokeHostFunction; + } +}); +Object.defineProperty(exports, "liquidityPoolDeposit", { + enumerable: true, + get: function get() { + return _liquidity_pool_deposit.liquidityPoolDeposit; + } +}); +Object.defineProperty(exports, "liquidityPoolWithdraw", { + enumerable: true, + get: function get() { + return _liquidity_pool_withdraw.liquidityPoolWithdraw; + } +}); +Object.defineProperty(exports, "manageBuyOffer", { + enumerable: true, + get: function get() { + return _manage_buy_offer.manageBuyOffer; + } +}); +Object.defineProperty(exports, "manageData", { + enumerable: true, + get: function get() { + return _manage_data.manageData; + } +}); +Object.defineProperty(exports, "manageSellOffer", { + enumerable: true, + get: function get() { + return _manage_sell_offer.manageSellOffer; + } +}); +Object.defineProperty(exports, "pathPaymentStrictReceive", { + enumerable: true, + get: function get() { + return _path_payment_strict_receive.pathPaymentStrictReceive; + } +}); +Object.defineProperty(exports, "pathPaymentStrictSend", { + enumerable: true, + get: function get() { + return _path_payment_strict_send.pathPaymentStrictSend; + } +}); +Object.defineProperty(exports, "payment", { + enumerable: true, + get: function get() { + return _payment.payment; + } +}); +Object.defineProperty(exports, "restoreFootprint", { + enumerable: true, + get: function get() { + return _restore_footprint.restoreFootprint; + } +}); +Object.defineProperty(exports, "revokeAccountSponsorship", { + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeAccountSponsorship; + } +}); +Object.defineProperty(exports, "revokeClaimableBalanceSponsorship", { + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeClaimableBalanceSponsorship; + } +}); +Object.defineProperty(exports, "revokeDataSponsorship", { + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeDataSponsorship; + } +}); +Object.defineProperty(exports, "revokeLiquidityPoolSponsorship", { + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeLiquidityPoolSponsorship; + } +}); +Object.defineProperty(exports, "revokeOfferSponsorship", { + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeOfferSponsorship; + } +}); +Object.defineProperty(exports, "revokeSignerSponsorship", { + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeSignerSponsorship; + } +}); +Object.defineProperty(exports, "revokeTrustlineSponsorship", { + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeTrustlineSponsorship; + } +}); +Object.defineProperty(exports, "setOptions", { + enumerable: true, + get: function get() { + return _set_options.setOptions; + } +}); +Object.defineProperty(exports, "setTrustLineFlags", { + enumerable: true, + get: function get() { + return _set_trustline_flags.setTrustLineFlags; + } +}); +Object.defineProperty(exports, "uploadContractWasm", { + enumerable: true, + get: function get() { + return _invoke_host_function.uploadContractWasm; + } +}); +var _manage_sell_offer = require("./manage_sell_offer"); +var _create_passive_sell_offer = require("./create_passive_sell_offer"); +var _account_merge = require("./account_merge"); +var _allow_trust = require("./allow_trust"); +var _bump_sequence = require("./bump_sequence"); +var _change_trust = require("./change_trust"); +var _create_account = require("./create_account"); +var _create_claimable_balance = require("./create_claimable_balance"); +var _claim_claimable_balance = require("./claim_claimable_balance"); +var _clawback_claimable_balance = require("./clawback_claimable_balance"); +var _inflation = require("./inflation"); +var _manage_data = require("./manage_data"); +var _manage_buy_offer = require("./manage_buy_offer"); +var _path_payment_strict_receive = require("./path_payment_strict_receive"); +var _path_payment_strict_send = require("./path_payment_strict_send"); +var _payment = require("./payment"); +var _set_options = require("./set_options"); +var _begin_sponsoring_future_reserves = require("./begin_sponsoring_future_reserves"); +var _end_sponsoring_future_reserves = require("./end_sponsoring_future_reserves"); +var _revoke_sponsorship = require("./revoke_sponsorship"); +var _clawback = require("./clawback"); +var _set_trustline_flags = require("./set_trustline_flags"); +var _liquidity_pool_deposit = require("./liquidity_pool_deposit"); +var _liquidity_pool_withdraw = require("./liquidity_pool_withdraw"); +var _invoke_host_function = require("./invoke_host_function"); +var _extend_footprint_ttl = require("./extend_footprint_ttl"); +var _restore_footprint = require("./restore_footprint"); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/inflation.js b/node_modules/@stellar/stellar-base/lib/operations/inflation.js new file mode 100644 index 000000000..1485dbbb7 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/inflation.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.inflation = inflation; +var _xdr = _interopRequireDefault(require("../xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation generates the inflation. + * @function + * @alias Operation.inflation + * @param {object} [opts] Options object + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.InflationOp} Inflation operation + */ +function inflation() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.inflation(); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/invoke_host_function.js b/node_modules/@stellar/stellar-base/lib/operations/invoke_host_function.js new file mode 100644 index 000000000..4e692581e --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/invoke_host_function.js @@ -0,0 +1,225 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createCustomContract = createCustomContract; +exports.createStellarAssetContract = createStellarAssetContract; +exports.invokeContractFunction = invokeContractFunction; +exports.invokeHostFunction = invokeHostFunction; +exports.uploadContractWasm = uploadContractWasm; +var _xdr = _interopRequireDefault(require("../xdr")); +var _keypair = require("../keypair"); +var _address = require("../address"); +var _asset = require("../asset"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +/** + * Invokes a single smart contract host function. + * + * @function + * @alias Operation.invokeHostFunction + * + * @param {object} opts - options object + * @param {xdr.HostFunction} opts.func - host function to execute (with its + * wrapped parameters) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - list outlining the + * tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + * @see Operation.invokeContractFunction + * @see Operation.createCustomContract + * @see Operation.createStellarAssetContract + * @see Operation.uploadContractWasm + * @see Contract.call + */ +function invokeHostFunction(opts) { + if (!opts.func) { + throw new TypeError("host function invocation ('func') required (got ".concat(JSON.stringify(opts), ")")); + } + var invokeHostFunctionOp = new _xdr["default"].InvokeHostFunctionOp({ + hostFunction: opts.func, + auth: opts.auth || [] + }); + var opAttributes = { + body: _xdr["default"].OperationBody.invokeHostFunction(invokeHostFunctionOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Returns an operation that invokes a contract function. + * + * @function + * @alias Operation.invokeContractFunction + * + * @param {any} opts - the set of parameters + * @param {string} opts.contract - a strkey-fied contract address (`C...`) + * @param {string} opts.function - the name of the contract fn to invoke + * @param {xdr.ScVal[]} opts.args - parameters to pass to the function + * invocation (try {@link nativeToScVal} or {@link ScInt} to make building + * these easier) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see Operation.invokeHostFunction + * @see Contract.call + * @see Address + */ +function invokeContractFunction(opts) { + var c = new _address.Address(opts.contract); + if (c._type !== 'contract') { + throw new TypeError("expected contract strkey instance, got ".concat(c)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeInvokeContract(new _xdr["default"].InvokeContractArgs({ + contractAddress: c.toScAddress(), + functionName: opts["function"], + args: opts.args + })) + }); +} + +/** + * Returns an operation that creates a custom WASM contract and atomically + * invokes its constructor. + * + * @function + * @alias Operation.createCustomContract + * + * @param {any} opts - the set of parameters + * @param {Address} opts.address - the contract uploader address + * @param {Uint8Array|Buffer} opts.wasmHash - the SHA-256 hash of the contract + * WASM you're uploading (see {@link hash} and + * {@link Operation.uploadContractWasm}) + * @param {xdr.ScVal[]} [opts.constructorArgs] - the optional parameters to pass + * to the constructor of this contract (see {@link nativeToScVal} for ways to + * easily create these parameters from native JS values) + * @param {Uint8Array|Buffer} [opts.salt] - an optional, 32-byte salt to + * distinguish deployment instances of the same wasm from the same user (if + * omitted, one will be generated for you) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + */ +function createCustomContract(opts) { + var _opts$constructorArgs; + var salt = Buffer.from(opts.salt || getSalty()); + if (!opts.wasmHash || opts.wasmHash.length !== 32) { + throw new TypeError("expected hash(contract WASM) in 'opts.wasmHash', got ".concat(opts.wasmHash)); + } + if (salt.length !== 32) { + throw new TypeError("expected 32-byte salt in 'opts.salt', got ".concat(opts.wasmHash)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeCreateContractV2(new _xdr["default"].CreateContractArgsV2({ + executable: _xdr["default"].ContractExecutable.contractExecutableWasm(Buffer.from(opts.wasmHash)), + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAddress(new _xdr["default"].ContractIdPreimageFromAddress({ + address: opts.address.toScAddress(), + salt: salt + })), + constructorArgs: (_opts$constructorArgs = opts.constructorArgs) !== null && _opts$constructorArgs !== void 0 ? _opts$constructorArgs : [] + })) + }); +} + +/** + * Returns an operation that wraps a Stellar asset into a token contract. + * + * @function + * @alias Operation.createStellarAssetContract + * + * @param {any} opts - the set of parameters + * @param {Asset|string} opts.asset - the Stellar asset to wrap, either as an + * {@link Asset} object or in canonical form (SEP-11, `code:issuer`) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see https://stellar.org/protocol/sep-11#alphanum4-alphanum12 + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions + * @see + * https://soroban.stellar.org/docs/advanced-tutorials/stellar-asset-contract + * @see Operation.invokeHostFunction + */ +function createStellarAssetContract(opts) { + var asset = opts.asset; + if (typeof asset === 'string') { + var _asset$split = asset.split(':'), + _asset$split2 = _slicedToArray(_asset$split, 2), + code = _asset$split2[0], + issuer = _asset$split2[1]; + asset = new _asset.Asset(code, issuer); // handles 'xlm' by default + } + if (!(asset instanceof _asset.Asset)) { + throw new TypeError("expected Asset in 'opts.asset', got ".concat(asset)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeCreateContract(new _xdr["default"].CreateContractArgs({ + executable: _xdr["default"].ContractExecutable.contractExecutableStellarAsset(), + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAsset(asset.toXDRObject()) + })) + }); +} + +/** + * Returns an operation that uploads WASM for a contract. + * + * @function + * @alias Operation.uploadContractWasm + * + * @param {any} opts - the set of parameters + * @param {Uint8Array|Buffer} opts.wasm - a WASM blob to upload to the ledger + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + */ +function uploadContractWasm(opts) { + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeUploadContractWasm(Buffer.from(opts.wasm) // coalesce so we can drop `Buffer` someday + ) + }); +} + +/** @returns {Buffer} a random 256-bit "salt" value. */ +function getSalty() { + return _keypair.Keypair.random().xdrPublicKey().value(); // ed25519 is 256 bits, too +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/liquidity_pool_deposit.js b/node_modules/@stellar/stellar-base/lib/operations/liquidity_pool_deposit.js new file mode 100644 index 000000000..553c25f7a --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/liquidity_pool_deposit.js @@ -0,0 +1,64 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.liquidityPoolDeposit = liquidityPoolDeposit; +var _xdr = _interopRequireDefault(require("../xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a liquidity pool deposit operation. + * + * @function + * @alias Operation.liquidityPoolDeposit + * @see https://developers.stellar.org/docs/start/list-of-operations/#liquidity-pool-deposit + * + * @param {object} opts - Options object + * @param {string} opts.liquidityPoolId - The liquidity pool ID. + * @param {string} opts.maxAmountA - Maximum amount of first asset to deposit. + * @param {string} opts.maxAmountB - Maximum amount of second asset to deposit. + * @param {number|string|BigNumber|Object} opts.minPrice - Minimum depositA/depositB price. + * @param {number} opts.minPrice.n - If `opts.minPrice` is an object: the price numerator + * @param {number} opts.minPrice.d - If `opts.minPrice` is an object: the price denominator + * @param {number|string|BigNumber|Object} opts.maxPrice - Maximum depositA/depositB price. + * @param {number} opts.maxPrice.n - If `opts.maxPrice` is an object: the price numerator + * @param {number} opts.maxPrice.d - If `opts.maxPrice` is an object: the price denominator + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting operation (xdr.LiquidityPoolDepositOp). + */ +function liquidityPoolDeposit() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var liquidityPoolId = opts.liquidityPoolId, + maxAmountA = opts.maxAmountA, + maxAmountB = opts.maxAmountB, + minPrice = opts.minPrice, + maxPrice = opts.maxPrice; + var attributes = {}; + if (!liquidityPoolId) { + throw new TypeError('liquidityPoolId argument is required'); + } + attributes.liquidityPoolId = _xdr["default"].PoolId.fromXDR(liquidityPoolId, 'hex'); + if (!this.isValidAmount(maxAmountA, true)) { + throw new TypeError(this.constructAmountRequirementsError('maxAmountA')); + } + attributes.maxAmountA = this._toXDRAmount(maxAmountA); + if (!this.isValidAmount(maxAmountB, true)) { + throw new TypeError(this.constructAmountRequirementsError('maxAmountB')); + } + attributes.maxAmountB = this._toXDRAmount(maxAmountB); + if (minPrice === undefined) { + throw new TypeError('minPrice argument is required'); + } + attributes.minPrice = this._toXDRPrice(minPrice); + if (maxPrice === undefined) { + throw new TypeError('maxPrice argument is required'); + } + attributes.maxPrice = this._toXDRPrice(maxPrice); + var liquidityPoolDepositOp = new _xdr["default"].LiquidityPoolDepositOp(attributes); + var opAttributes = { + body: _xdr["default"].OperationBody.liquidityPoolDeposit(liquidityPoolDepositOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/liquidity_pool_withdraw.js b/node_modules/@stellar/stellar-base/lib/operations/liquidity_pool_withdraw.js new file mode 100644 index 000000000..cb0f6a942 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/liquidity_pool_withdraw.js @@ -0,0 +1,50 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.liquidityPoolWithdraw = liquidityPoolWithdraw; +var _xdr = _interopRequireDefault(require("../xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a liquidity pool withdraw operation. + * + * @function + * @alias Operation.liquidityPoolWithdraw + * @see https://developers.stellar.org/docs/start/list-of-operations/#liquidity-pool-withdraw + * + * @param {object} opts - Options object + * @param {string} opts.liquidityPoolId - The liquidity pool ID. + * @param {string} opts.amount - Amount of pool shares to withdraw. + * @param {string} opts.minAmountA - Minimum amount of first asset to withdraw. + * @param {string} opts.minAmountB - Minimum amount of second asset to withdraw. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting operation (xdr.LiquidityPoolWithdrawOp). + */ +function liquidityPoolWithdraw() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var attributes = {}; + if (!opts.liquidityPoolId) { + throw new TypeError('liquidityPoolId argument is required'); + } + attributes.liquidityPoolId = _xdr["default"].PoolId.fromXDR(opts.liquidityPoolId, 'hex'); + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (!this.isValidAmount(opts.minAmountA, true)) { + throw new TypeError(this.constructAmountRequirementsError('minAmountA')); + } + attributes.minAmountA = this._toXDRAmount(opts.minAmountA); + if (!this.isValidAmount(opts.minAmountB, true)) { + throw new TypeError(this.constructAmountRequirementsError('minAmountB')); + } + attributes.minAmountB = this._toXDRAmount(opts.minAmountB); + var liquidityPoolWithdrawOp = new _xdr["default"].LiquidityPoolWithdrawOp(attributes); + var opAttributes = { + body: _xdr["default"].OperationBody.liquidityPoolWithdraw(liquidityPoolWithdrawOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/manage_buy_offer.js b/node_modules/@stellar/stellar-base/lib/operations/manage_buy_offer.js new file mode 100644 index 000000000..feef33d20 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/manage_buy_offer.js @@ -0,0 +1,50 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.manageBuyOffer = manageBuyOffer; +var _jsXdr = require("@stellar/js-xdr"); +var _xdr = _interopRequireDefault(require("../xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR ManageBuyOfferOp. A "manage buy offer" operation creates, updates, or + * deletes a buy offer. + * @function + * @alias Operation.manageBuyOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.buyAmount - The total amount you're buying. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `buying` in terms of `selling`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.ManageBuyOfferOp} Manage Buy Offer operation + */ +function manageBuyOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.buyAmount, true)) { + throw new TypeError(this.constructAmountRequirementsError('buyAmount')); + } + attributes.buyAmount = this._toXDRAmount(opts.buyAmount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + if (opts.offerId !== undefined) { + opts.offerId = opts.offerId.toString(); + } else { + opts.offerId = '0'; + } + attributes.offerId = _jsXdr.Hyper.fromString(opts.offerId); + var manageBuyOfferOp = new _xdr["default"].ManageBuyOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageBuyOffer(manageBuyOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/manage_data.js b/node_modules/@stellar/stellar-base/lib/operations/manage_data.js new file mode 100644 index 000000000..f66fc6177 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/manage_data.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.manageData = manageData; +var _xdr = _interopRequireDefault(require("../xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation adds data entry to the ledger. + * @function + * @alias Operation.manageData + * @param {object} opts Options object + * @param {string} opts.name - The name of the data entry. + * @param {string|Buffer} opts.value - The value of the data entry. + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.ManageDataOp} Manage Data operation + */ +function manageData(opts) { + var attributes = {}; + if (!(typeof opts.name === 'string' && opts.name.length <= 64)) { + throw new Error('name must be a string, up to 64 characters'); + } + attributes.dataName = opts.name; + if (typeof opts.value !== 'string' && !Buffer.isBuffer(opts.value) && opts.value !== null) { + throw new Error('value must be a string, Buffer or null'); + } + if (typeof opts.value === 'string') { + attributes.dataValue = Buffer.from(opts.value); + } else { + attributes.dataValue = opts.value; + } + if (attributes.dataValue !== null && attributes.dataValue.length > 64) { + throw new Error('value cannot be longer that 64 bytes'); + } + var manageDataOp = new _xdr["default"].ManageDataOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageData(manageDataOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/manage_sell_offer.js b/node_modules/@stellar/stellar-base/lib/operations/manage_sell_offer.js new file mode 100644 index 000000000..62b772e1e --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/manage_sell_offer.js @@ -0,0 +1,50 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.manageSellOffer = manageSellOffer; +var _jsXdr = require("@stellar/js-xdr"); +var _xdr = _interopRequireDefault(require("../xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR ManageSellOfferOp. A "manage sell offer" operation creates, updates, or + * deletes an offer. + * @function + * @alias Operation.manageSellOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.ManageSellOfferOp} Manage Sell Offer operation + */ +function manageSellOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.amount, true)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + if (opts.offerId !== undefined) { + opts.offerId = opts.offerId.toString(); + } else { + opts.offerId = '0'; + } + attributes.offerId = _jsXdr.Hyper.fromString(opts.offerId); + var manageSellOfferOp = new _xdr["default"].ManageSellOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageSellOffer(manageSellOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/path_payment_strict_receive.js b/node_modules/@stellar/stellar-base/lib/operations/path_payment_strict_receive.js new file mode 100644 index 000000000..dc6213417 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/path_payment_strict_receive.js @@ -0,0 +1,68 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.pathPaymentStrictReceive = pathPaymentStrictReceive; +var _xdr = _interopRequireDefault(require("../xdr")); +var _decode_encode_muxed_account = require("../util/decode_encode_muxed_account"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a PathPaymentStrictReceive operation. + * + * A `PathPaymentStrictReceive` operation sends the specified amount to the + * destination account. It credits the destination with `destAmount` of + * `destAsset`, while debiting at most `sendMax` of `sendAsset` from the source. + * The transfer optionally occurs through a path. XLM payments create the + * destination account if it does not exist. + * + * @function + * @alias Operation.pathPaymentStrictReceive + * @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-receive + * + * @param {object} opts - Options object + * @param {Asset} opts.sendAsset - asset to pay with + * @param {string} opts.sendMax - maximum amount of sendAsset to send + * @param {string} opts.destination - destination account to send to + * @param {Asset} opts.destAsset - asset the destination will receive + * @param {string} opts.destAmount - amount the destination receives + * @param {Asset[]} opts.path - array of Asset objects to use as the path + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.PathPaymentStrictReceiveOp} the resulting path payment op + */ +function pathPaymentStrictReceive(opts) { + switch (true) { + case !opts.sendAsset: + throw new Error('Must specify a send asset'); + case !this.isValidAmount(opts.sendMax): + throw new TypeError(this.constructAmountRequirementsError('sendMax')); + case !opts.destAsset: + throw new Error('Must provide a destAsset for a payment operation'); + case !this.isValidAmount(opts.destAmount): + throw new TypeError(this.constructAmountRequirementsError('destAmount')); + default: + break; + } + var attributes = {}; + attributes.sendAsset = opts.sendAsset.toXDRObject(); + attributes.sendMax = this._toXDRAmount(opts.sendMax); + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.destAsset = opts.destAsset.toXDRObject(); + attributes.destAmount = this._toXDRAmount(opts.destAmount); + var path = opts.path ? opts.path : []; + attributes.path = path.map(function (x) { + return x.toXDRObject(); + }); + var payment = new _xdr["default"].PathPaymentStrictReceiveOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.pathPaymentStrictReceive(payment); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/path_payment_strict_send.js b/node_modules/@stellar/stellar-base/lib/operations/path_payment_strict_send.js new file mode 100644 index 000000000..f10c3a1a8 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/path_payment_strict_send.js @@ -0,0 +1,68 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.pathPaymentStrictSend = pathPaymentStrictSend; +var _xdr = _interopRequireDefault(require("../xdr")); +var _decode_encode_muxed_account = require("../util/decode_encode_muxed_account"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a PathPaymentStrictSend operation. + * + * A `PathPaymentStrictSend` operation sends the specified amount to the + * destination account crediting at least `destMin` of `destAsset`, optionally + * through a path. XLM payments create the destination account if it does not + * exist. + * + * @function + * @alias Operation.pathPaymentStrictSend + * @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-send + * + * @param {object} opts - Options object + * @param {Asset} opts.sendAsset - asset to pay with + * @param {string} opts.sendAmount - amount of sendAsset to send (excluding fees) + * @param {string} opts.destination - destination account to send to + * @param {Asset} opts.destAsset - asset the destination will receive + * @param {string} opts.destMin - minimum amount of destAsset to be receive + * @param {Asset[]} opts.path - array of Asset objects to use as the path + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.Operation} the resulting path payment operation + * (xdr.PathPaymentStrictSendOp) + */ +function pathPaymentStrictSend(opts) { + switch (true) { + case !opts.sendAsset: + throw new Error('Must specify a send asset'); + case !this.isValidAmount(opts.sendAmount): + throw new TypeError(this.constructAmountRequirementsError('sendAmount')); + case !opts.destAsset: + throw new Error('Must provide a destAsset for a payment operation'); + case !this.isValidAmount(opts.destMin): + throw new TypeError(this.constructAmountRequirementsError('destMin')); + default: + break; + } + var attributes = {}; + attributes.sendAsset = opts.sendAsset.toXDRObject(); + attributes.sendAmount = this._toXDRAmount(opts.sendAmount); + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.destAsset = opts.destAsset.toXDRObject(); + attributes.destMin = this._toXDRAmount(opts.destMin); + var path = opts.path ? opts.path : []; + attributes.path = path.map(function (x) { + return x.toXDRObject(); + }); + var payment = new _xdr["default"].PathPaymentStrictSendOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.pathPaymentStrictSend(payment); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/payment.js b/node_modules/@stellar/stellar-base/lib/operations/payment.js new file mode 100644 index 000000000..b74d50ee7 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/payment.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.payment = payment; +var _xdr = _interopRequireDefault(require("../xdr")); +var _decode_encode_muxed_account = require("../util/decode_encode_muxed_account"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a payment operation. + * + * @function + * @alias Operation.payment + * @see https://developers.stellar.org/docs/start/list-of-operations/#payment + * + * @param {object} opts - Options object + * @param {string} opts.destination - destination account ID + * @param {Asset} opts.asset - asset to send + * @param {string} opts.amount - amount to send + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting payment operation (xdr.PaymentOp) + */ +function payment(opts) { + if (!opts.asset) { + throw new Error('Must provide an asset for a payment operation'); + } + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + var attributes = {}; + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.asset = opts.asset.toXDRObject(); + attributes.amount = this._toXDRAmount(opts.amount); + var paymentOp = new _xdr["default"].PaymentOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.payment(paymentOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/restore_footprint.js b/node_modules/@stellar/stellar-base/lib/operations/restore_footprint.js new file mode 100644 index 000000000..a367c592f --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/restore_footprint.js @@ -0,0 +1,42 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.restoreFootprint = restoreFootprint; +var _xdr = _interopRequireDefault(require("../xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Builds an operation to restore the archived ledger entries specified + * by the ledger keys. + * + * The ledger keys to restore are specified separately from the operation + * in read-write footprint of the transaction. + * + * It takes no parameters because the relevant footprint is derived from the + * transaction itself. See {@link TransactionBuilder}'s `opts.sorobanData` + * parameter (or {@link TransactionBuilder.setSorobanData} / + * {@link TransactionBuilder.setLedgerKeys}), which is a + * {@link xdr.SorobanTransactionData} instance that contains fee data & resource + * usage as part of {@link xdr.SorobanTransactionData}. + * + * @function + * @alias Operation.restoreFootprint + * + * @param {object} [opts] - an optional set of parameters + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} a Bump Footprint Expiration operation + * (xdr.RestoreFootprintOp) + */ +function restoreFootprint() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var op = new _xdr["default"].RestoreFootprintOp({ + ext: new _xdr["default"].ExtensionPoint(0) + }); + var opAttributes = { + body: _xdr["default"].OperationBody.restoreFootprint(op) + }; + this.setSourceAccount(opAttributes, opts !== null && opts !== void 0 ? opts : {}); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/revoke_sponsorship.js b/node_modules/@stellar/stellar-base/lib/operations/revoke_sponsorship.js new file mode 100644 index 000000000..b6c2fe32c --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/revoke_sponsorship.js @@ -0,0 +1,301 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.revokeAccountSponsorship = revokeAccountSponsorship; +exports.revokeClaimableBalanceSponsorship = revokeClaimableBalanceSponsorship; +exports.revokeDataSponsorship = revokeDataSponsorship; +exports.revokeLiquidityPoolSponsorship = revokeLiquidityPoolSponsorship; +exports.revokeOfferSponsorship = revokeOfferSponsorship; +exports.revokeSignerSponsorship = revokeSignerSponsorship; +exports.revokeTrustlineSponsorship = revokeTrustlineSponsorship; +var _xdr = _interopRequireDefault(require("../xdr")); +var _strkey = require("../strkey"); +var _keypair = require("../keypair"); +var _asset = require("../asset"); +var _liquidity_pool_id = require("../liquidity_pool_id"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a "revoke sponsorship" operation for an account. + * + * @function + * @alias Operation.revokeAccountSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The sponsored account ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeAccountSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * }); + * + */ +function revokeAccountSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.account(new _xdr["default"].LedgerKeyAccount({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId() + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a trustline. + * + * @function + * @alias Operation.revokeTrustlineSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID which owns the trustline. + * @param {Asset | LiquidityPoolId} opts.asset - The trustline asset. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeTrustlineSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * asset: new StellarBase.LiquidityPoolId( + * 'USDUSD', + * 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * ) + * }); + * + */ +function revokeTrustlineSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var asset; + if (opts.asset instanceof _asset.Asset) { + asset = opts.asset.toTrustLineXDRObject(); + } else if (opts.asset instanceof _liquidity_pool_id.LiquidityPoolId) { + asset = opts.asset.toXDRObject(); + } else { + throw new TypeError('asset must be an Asset or LiquidityPoolId'); + } + var ledgerKey = _xdr["default"].LedgerKey.trustline(new _xdr["default"].LedgerKeyTrustLine({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + asset: asset + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for an offer. + * + * @function + * @alias Operation.revokeOfferSponsorship + * @param {object} opts Options object + * @param {string} opts.seller - The account ID which created the offer. + * @param {string} opts.offerId - The offer ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeOfferSponsorship({ + * seller: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * offerId: '1234' + * }); + * + */ +function revokeOfferSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.seller)) { + throw new Error('seller is invalid'); + } + if (typeof opts.offerId !== 'string') { + throw new Error('offerId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.offer(new _xdr["default"].LedgerKeyOffer({ + sellerId: _keypair.Keypair.fromPublicKey(opts.seller).xdrAccountId(), + offerId: _xdr["default"].Int64.fromString(opts.offerId) + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a data entry. + * + * @function + * @alias Operation.revokeDataSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID which owns the data entry. + * @param {string} opts.name - The name of the data entry + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeDataSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * name: 'foo' + * }); + * + */ +function revokeDataSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + if (typeof opts.name !== 'string' || opts.name.length > 64) { + throw new Error('name must be a string, up to 64 characters'); + } + var ledgerKey = _xdr["default"].LedgerKey.data(new _xdr["default"].LedgerKeyData({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + dataName: opts.name + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a claimable balance. + * + * @function + * @alias Operation.revokeClaimableBalanceSponsorship + * @param {object} opts Options object + * @param {string} opts.balanceId - The sponsored claimable balance ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeClaimableBalanceSponsorship({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + */ +function revokeClaimableBalanceSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (typeof opts.balanceId !== 'string') { + throw new Error('balanceId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.claimableBalance(new _xdr["default"].LedgerKeyClaimableBalance({ + balanceId: _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex') + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Creates a "revoke sponsorship" operation for a liquidity pool. + * + * @function + * @alias Operation.revokeLiquidityPoolSponsorship + * @param {object} opts – Options object. + * @param {string} opts.liquidityPoolId - The sponsored liquidity pool ID in 'hex' string. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr Operation. + * + * @example + * const op = Operation.revokeLiquidityPoolSponsorship({ + * liquidityPoolId: 'dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7', + * }); + * + */ +function revokeLiquidityPoolSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (typeof opts.liquidityPoolId !== 'string') { + throw new Error('liquidityPoolId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.liquidityPool(new _xdr["default"].LedgerKeyLiquidityPool({ + liquidityPoolId: _xdr["default"].PoolId.fromXDR(opts.liquidityPoolId, 'hex') + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = { + body: _xdr["default"].OperationBody.revokeSponsorship(op) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a signer. + * + * @function + * @alias Operation.revokeSignerSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID where the signer sponsorship is being removed from. + * @param {object} opts.signer - The signer whose sponsorship is being removed. + * @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer. + * @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string). + * @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeSignerSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * signer: { + * ed25519PublicKey: 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ' + * } + * }) + * + */ +function revokeSignerSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var key; + if (opts.signer.ed25519PublicKey) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) { + throw new Error('signer.ed25519PublicKey is invalid.'); + } + var rawKey = _strkey.StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey); + key = new _xdr["default"].SignerKey.signerKeyTypeEd25519(rawKey); + } else if (opts.signer.preAuthTx) { + var buffer; + if (typeof opts.signer.preAuthTx === 'string') { + buffer = Buffer.from(opts.signer.preAuthTx, 'hex'); + } else { + buffer = opts.signer.preAuthTx; + } + if (!(Buffer.isBuffer(buffer) && buffer.length === 32)) { + throw new Error('signer.preAuthTx must be 32 bytes Buffer.'); + } + key = new _xdr["default"].SignerKey.signerKeyTypePreAuthTx(buffer); + } else if (opts.signer.sha256Hash) { + var _buffer; + if (typeof opts.signer.sha256Hash === 'string') { + _buffer = Buffer.from(opts.signer.sha256Hash, 'hex'); + } else { + _buffer = opts.signer.sha256Hash; + } + if (!(Buffer.isBuffer(_buffer) && _buffer.length === 32)) { + throw new Error('signer.sha256Hash must be 32 bytes Buffer.'); + } + key = new _xdr["default"].SignerKey.signerKeyTypeHashX(_buffer); + } else { + throw new Error('signer is invalid'); + } + var signer = new _xdr["default"].RevokeSponsorshipOpSigner({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + signerKey: key + }); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipSigner(signer); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/set_options.js b/node_modules/@stellar/stellar-base/lib/operations/set_options.js new file mode 100644 index 000000000..82bb85dce --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/set_options.js @@ -0,0 +1,135 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.setOptions = setOptions; +var _xdr = _interopRequireDefault(require("../xdr")); +var _keypair = require("../keypair"); +var _strkey = require("../strkey"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/* eslint-disable no-param-reassign */ + +function weightCheckFunction(value, name) { + if (value >= 0 && value <= 255) { + return true; + } + throw new Error("".concat(name, " value must be between 0 and 255")); +} + +/** + * Returns an XDR SetOptionsOp. A "set options" operations set or clear account flags, + * set the account's inflation destination, and/or add new signers to the account. + * The flags used in `opts.clearFlags` and `opts.setFlags` can be the following: + * - `{@link AuthRequiredFlag}` + * - `{@link AuthRevocableFlag}` + * - `{@link AuthImmutableFlag}` + * - `{@link AuthClawbackEnabledFlag}` + * + * It's possible to set/clear multiple flags at once using logical or. + * + * @function + * @alias Operation.setOptions + * + * @param {object} opts Options object + * @param {string} [opts.inflationDest] - Set this account ID as the account's inflation destination. + * @param {(number|string)} [opts.clearFlags] - Bitmap integer for which account flags to clear. + * @param {(number|string)} [opts.setFlags] - Bitmap integer for which account flags to set. + * @param {number|string} [opts.masterWeight] - The master key weight. + * @param {number|string} [opts.lowThreshold] - The sum weight for the low threshold. + * @param {number|string} [opts.medThreshold] - The sum weight for the medium threshold. + * @param {number|string} [opts.highThreshold] - The sum weight for the high threshold. + * @param {object} [opts.signer] - Add or remove a signer from the account. The signer is + * deleted if the weight is 0. Only one of `ed25519PublicKey`, `sha256Hash`, `preAuthTx` should be defined. + * @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer. + * @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string) of preimage that will unlock funds. Preimage should be used as signature of future transaction. + * @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction that will unlock funds. + * @param {string} [opts.signer.ed25519SignedPayload] - Signed payload signer (ed25519 public key + raw payload) for atomic transaction signature disclosure. + * @param {number|string} [opts.signer.weight] - The weight of the new signer (0 to delete or 1-255) + * @param {string} [opts.homeDomain] - sets the home domain used for reverse federation lookup. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * + * @returns {xdr.SetOptionsOp} XDR operation + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +function setOptions(opts) { + var attributes = {}; + if (opts.inflationDest) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.inflationDest)) { + throw new Error('inflationDest is invalid'); + } + attributes.inflationDest = _keypair.Keypair.fromPublicKey(opts.inflationDest).xdrAccountId(); + } + attributes.clearFlags = this._checkUnsignedIntValue('clearFlags', opts.clearFlags); + attributes.setFlags = this._checkUnsignedIntValue('setFlags', opts.setFlags); + attributes.masterWeight = this._checkUnsignedIntValue('masterWeight', opts.masterWeight, weightCheckFunction); + attributes.lowThreshold = this._checkUnsignedIntValue('lowThreshold', opts.lowThreshold, weightCheckFunction); + attributes.medThreshold = this._checkUnsignedIntValue('medThreshold', opts.medThreshold, weightCheckFunction); + attributes.highThreshold = this._checkUnsignedIntValue('highThreshold', opts.highThreshold, weightCheckFunction); + if (opts.homeDomain !== undefined && typeof opts.homeDomain !== 'string') { + throw new TypeError('homeDomain argument must be of type String'); + } + attributes.homeDomain = opts.homeDomain; + if (opts.signer) { + var weight = this._checkUnsignedIntValue('signer.weight', opts.signer.weight, weightCheckFunction); + var key; + var setValues = 0; + if (opts.signer.ed25519PublicKey) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) { + throw new Error('signer.ed25519PublicKey is invalid.'); + } + var rawKey = _strkey.StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey); + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypeEd25519(rawKey); + setValues += 1; + } + if (opts.signer.preAuthTx) { + if (typeof opts.signer.preAuthTx === 'string') { + opts.signer.preAuthTx = Buffer.from(opts.signer.preAuthTx, 'hex'); + } + if (!(Buffer.isBuffer(opts.signer.preAuthTx) && opts.signer.preAuthTx.length === 32)) { + throw new Error('signer.preAuthTx must be 32 bytes Buffer.'); + } + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypePreAuthTx(opts.signer.preAuthTx); + setValues += 1; + } + if (opts.signer.sha256Hash) { + if (typeof opts.signer.sha256Hash === 'string') { + opts.signer.sha256Hash = Buffer.from(opts.signer.sha256Hash, 'hex'); + } + if (!(Buffer.isBuffer(opts.signer.sha256Hash) && opts.signer.sha256Hash.length === 32)) { + throw new Error('signer.sha256Hash must be 32 bytes Buffer.'); + } + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypeHashX(opts.signer.sha256Hash); + setValues += 1; + } + if (opts.signer.ed25519SignedPayload) { + if (!_strkey.StrKey.isValidSignedPayload(opts.signer.ed25519SignedPayload)) { + throw new Error('signer.ed25519SignedPayload is invalid.'); + } + var _rawKey = _strkey.StrKey.decodeSignedPayload(opts.signer.ed25519SignedPayload); + var signedPayloadXdr = _xdr["default"].SignerKeyEd25519SignedPayload.fromXDR(_rawKey); + + // eslint-disable-next-line new-cap + key = _xdr["default"].SignerKey.signerKeyTypeEd25519SignedPayload(signedPayloadXdr); + setValues += 1; + } + if (setValues !== 1) { + throw new Error('Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx.'); + } + attributes.signer = new _xdr["default"].Signer({ + key: key, + weight: weight + }); + } + var setOptionsOp = new _xdr["default"].SetOptionsOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.setOptions(setOptionsOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/operations/set_trustline_flags.js b/node_modules/@stellar/stellar-base/lib/operations/set_trustline_flags.js new file mode 100644 index 000000000..f6cd06e2f --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/operations/set_trustline_flags.js @@ -0,0 +1,84 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.setTrustLineFlags = setTrustLineFlags; +var _xdr = _interopRequireDefault(require("../xdr")); +var _keypair = require("../keypair"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/** + * Creates a trustline flag configuring operation. + * + * For the flags, set them to true to enable them and false to disable them. Any + * unmodified operations will be marked `undefined` in the result. + * + * Note that you can only **clear** the clawbackEnabled flag set; it must be set + * account-wide via operations.SetOptions (setting + * xdr.AccountFlags.clawbackEnabled). + * + * @function + * @alias Operation.setTrustLineFlags + * + * @param {object} opts - Options object + * @param {string} opts.trustor - the account whose trustline this is + * @param {Asset} opts.asset - the asset on the trustline + * @param {object} opts.flags - the set of flags to modify + * + * @param {bool} [opts.flags.authorized] - authorize account to perform + * transactions with its credit + * @param {bool} [opts.flags.authorizedToMaintainLiabilities] - authorize + * account to maintain and reduce liabilities for its credit + * @param {bool} [opts.flags.clawbackEnabled] - stop claimable balances on + * this trustlines from having clawbacks enabled (this flag can only be set + * to false!) + * @param {string} [opts.source] - The source account for the operation. + * Defaults to the transaction's source account. + * + * @note You must include at least one flag. + * + * @return {xdr.SetTrustLineFlagsOp} + * + * @link xdr.AccountFlags + * @link xdr.TrustLineFlags + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#set-trustline-flags-operation + * @see https://developers.stellar.org/docs/start/list-of-operations/#set-options + */ +function setTrustLineFlags() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var attributes = {}; + if (_typeof(opts.flags) !== 'object' || Object.keys(opts.flags).length === 0) { + throw new Error('opts.flags must be a map of boolean flags to modify'); + } + var mapping = { + authorized: _xdr["default"].TrustLineFlags.authorizedFlag(), + authorizedToMaintainLiabilities: _xdr["default"].TrustLineFlags.authorizedToMaintainLiabilitiesFlag(), + clawbackEnabled: _xdr["default"].TrustLineFlags.trustlineClawbackEnabledFlag() + }; + + /* eslint no-bitwise: "off" */ + var clearFlag = 0; + var setFlag = 0; + Object.keys(opts.flags).forEach(function (flagName) { + if (!Object.prototype.hasOwnProperty.call(mapping, flagName)) { + throw new Error("unsupported flag name specified: ".concat(flagName)); + } + var flagValue = opts.flags[flagName]; + var bit = mapping[flagName].value; + if (flagValue === true) { + setFlag |= bit; + } else if (flagValue === false) { + clearFlag |= bit; + } + }); + attributes.trustor = _keypair.Keypair.fromPublicKey(opts.trustor).xdrAccountId(); + attributes.asset = opts.asset.toXDRObject(); + attributes.clearFlags = clearFlag; + attributes.setFlags = setFlag; + var opAttributes = { + body: _xdr["default"].OperationBody.setTrustLineFlags(new _xdr["default"].SetTrustLineFlagsOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/scval.js b/node_modules/@stellar/stellar-base/lib/scval.js new file mode 100644 index 000000000..9ec165ed5 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/scval.js @@ -0,0 +1,392 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.nativeToScVal = nativeToScVal; +exports.scValToNative = scValToNative; +var _xdr = _interopRequireDefault(require("./xdr")); +var _address = require("./address"); +var _contract = require("./contract"); +var _index = require("./numbers/index"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/** + * Attempts to convert native types into smart contract values + * ({@link xdr.ScVal}). + * + * Provides conversions from smart contract XDR values ({@link xdr.ScVal}) to + * native JavaScript types. + * + * The conversions are as follows: + * + * - xdr.ScVal -> passthrough + * - null/undefined -> scvVoid + * - string -> scvString (a copy is made) + * - UintArray8 -> scvBytes (a copy is made) + * - boolean -> scvBool + * + * - number/bigint -> the smallest possible XDR integer type that will fit the + * input value (if you want a specific type, use {@link ScInt}) + * + * - {@link Address} or {@link Contract} -> scvAddress (for contracts and + * public keys) + * + * - Array -> scvVec after attempting to convert each item of type `T` to an + * xdr.ScVal (recursively). note that all values must be the same type! + * + * - object -> scvMap after attempting to convert each key and value to an + * xdr.ScVal (recursively). note that there is no restriction on types + * matching anywhere (unlike arrays) + * + * When passing an integer-like native value, you can also optionally specify a + * type which will force a particular interpretation of that value. + * + * Note that not all type specifications are compatible with all `ScVal`s, e.g. + * `toScVal("a string", {type: "i256"})` will throw. + * + * @param {any} val - a native (or convertible) input value to wrap + * @param {object} [opts] - an optional set of hints around the type of + * conversion you'd like to see + * @param {string} [opts.type] - there is different behavior for different input + * types for `val`: + * + * - when `val` is an integer-like type (i.e. number|bigint), this will be + * forwarded to {@link ScInt} or forced to be u32/i32. + * + * - when `val` is an array type, this is forwarded to the recursion + * + * - when `val` is an object type (key-value entries), this should be an + * object in which each key has a pair of types (to represent forced types + * for the key and the value), where `null` (or a missing entry) indicates + * the default interpretation(s) (refer to the examples, below) + * + * - when `val` is a string type, this can be 'string' or 'symbol' to force + * a particular interpretation of `val`. + * + * - when `val` is a bytes-like type, this can be 'string', 'symbol', or + * 'bytes' to force a particular interpretation + * + * As a simple example, `nativeToScVal("hello", {type: 'symbol'})` will + * return an `scvSymbol`, whereas without the type it would have been an + * `scvString`. + * + * @returns {xdr.ScVal} a wrapped, smart, XDR version of the input value + * @throws {TypeError} if... + * - there are arrays with more than one type in them + * - there are values that do not have a sensible conversion (e.g. random XDR + * types, custom classes) + * - the type of the input object (or some inner value of said object) cannot + * be determined (via `typeof`) + * - the type you specified (via `opts.type`) is incompatible with the value + * you passed in (`val`), e.g. `nativeToScVal("a string", { type: 'i128' })`, + * though this does not apply for types that ignore `opts` (e.g. addresses). + * @see scValToNative + * + * @example + * nativeToScVal(1000); // gives ScValType === scvU64 + * nativeToScVal(1000n); // gives ScValType === scvU64 + * nativeToScVal(1n << 100n); // gives ScValType === scvU128 + * nativeToScVal(1000, { type: 'u32' }); // gives ScValType === scvU32 + * nativeToScVal(1000, { type: 'i125' }); // gives ScValType === scvI256 + * nativeToScVal("a string"); // gives ScValType === scvString + * nativeToScVal("a string", { type: 'symbol' }); // gives scvSymbol + * nativeToScVal(new Uint8Array(5)); // scvBytes + * nativeToScVal(new Uint8Array(5), { type: 'symbol' }); // scvSymbol + * nativeToScVal(null); // scvVoid + * nativeToScVal(true); // scvBool + * nativeToScVal([1, 2, 3]); // gives scvVec with each element as scvU64 + * nativeToScVal([1, 2, 3], { type: 'i128' }); // scvVec + * nativeToScVal({ 'hello': 1, 'world': [ true, false ] }, { + * type: { + * 'hello': [ 'symbol', 'i128' ], + * } + * }) + * // gives scvMap with entries: [ + * // [ scvSymbol, scvI128 ], + * // [ scvString, scvArray ] + * // ] + * + * @example + * import { + * nativeToScVal, + * scValToNative, + * ScInt, + * xdr + * } from '@stellar/stellar-base'; + * + * let gigaMap = { + * bool: true, + * void: null, + * u32: xdr.ScVal.scvU32(1), + * i32: xdr.ScVal.scvI32(1), + * u64: 1n, + * i64: -1n, + * u128: new ScInt(1).toU128(), + * i128: new ScInt(1).toI128(), + * u256: new ScInt(1).toU256(), + * i256: new ScInt(1).toI256(), + * map: { + * arbitrary: 1n, + * nested: 'values', + * etc: false + * }, + * vec: ['same', 'type', 'list'], + * }; + * + * // then, simply: + * let scv = nativeToScVal(gigaMap); // scv.switch() == xdr.ScValType.scvMap() + * + * // then... + * someContract.call("method", scv); + * + * // Similarly, the inverse should work: + * scValToNative(scv) == gigaMap; // true + */ +function nativeToScVal(val) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + switch (_typeof(val)) { + case 'object': + { + var _val$constructor$name, _val$constructor; + if (val === null) { + return _xdr["default"].ScVal.scvVoid(); + } + if (val instanceof _xdr["default"].ScVal) { + return val; // should we copy? + } + if (val instanceof _address.Address) { + return val.toScVal(); + } + if (val instanceof _contract.Contract) { + return val.address().toScVal(); + } + if (val instanceof Uint8Array || Buffer.isBuffer(val)) { + var _opts$type; + var copy = Uint8Array.from(val); + switch ((_opts$type = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type !== void 0 ? _opts$type : 'bytes') { + case 'bytes': + return _xdr["default"].ScVal.scvBytes(copy); + case 'symbol': + return _xdr["default"].ScVal.scvSymbol(copy); + case 'string': + return _xdr["default"].ScVal.scvString(copy); + default: + throw new TypeError("invalid type (".concat(opts.type, ") specified for bytes-like value")); + } + } + if (Array.isArray(val)) { + if (val.length > 0 && val.some(function (v) { + return _typeof(v) !== _typeof(val[0]); + })) { + throw new TypeError("array values (".concat(val, ") must have the same type (types: ").concat(val.map(function (v) { + return _typeof(v); + }).join(','), ")")); + } + return _xdr["default"].ScVal.scvVec(val.map(function (v) { + return nativeToScVal(v, opts); + })); + } + if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : '') !== 'Object') { + var _val$constructor2; + throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")")); + } + return _xdr["default"].ScVal.scvMap(Object.entries(val) + // The Soroban runtime expects maps to have their keys in sorted + // order, so let's do that here as part of the conversion to prevent + // confusing error messages on execution. + .sort(function (_ref, _ref2) { + var _ref3 = _slicedToArray(_ref, 1), + key1 = _ref3[0]; + var _ref4 = _slicedToArray(_ref2, 1), + key2 = _ref4[0]; + return key1.localeCompare(key2); + }).map(function (_ref5) { + var _k, _opts$type2; + var _ref6 = _slicedToArray(_ref5, 2), + k = _ref6[0], + v = _ref6[1]; + // the type can be specified with an entry for the key and the value, + // e.g. val = { 'hello': 1 } and opts.type = { hello: [ 'symbol', + // 'u128' ]} or you can use `null` for the default interpretation + var _ref7 = (_k = ((_opts$type2 = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type2 !== void 0 ? _opts$type2 : {})[k]) !== null && _k !== void 0 ? _k : [null, null], + _ref8 = _slicedToArray(_ref7, 2), + keyType = _ref8[0], + valType = _ref8[1]; + var keyOpts = keyType ? { + type: keyType + } : {}; + var valOpts = valType ? { + type: valType + } : {}; + return new _xdr["default"].ScMapEntry({ + key: nativeToScVal(k, keyOpts), + val: nativeToScVal(v, valOpts) + }); + })); + } + case 'number': + case 'bigint': + switch (opts === null || opts === void 0 ? void 0 : opts.type) { + case 'u32': + return _xdr["default"].ScVal.scvU32(val); + case 'i32': + return _xdr["default"].ScVal.scvI32(val); + default: + break; + } + return new _index.ScInt(val, { + type: opts === null || opts === void 0 ? void 0 : opts.type + }).toScVal(); + case 'string': + { + var _opts$type3; + var optType = (_opts$type3 = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type3 !== void 0 ? _opts$type3 : 'string'; + switch (optType) { + case 'string': + return _xdr["default"].ScVal.scvString(val); + case 'symbol': + return _xdr["default"].ScVal.scvSymbol(val); + case 'address': + return new _address.Address(val).toScVal(); + case 'u32': + return _xdr["default"].ScVal.scvU32(parseInt(val, 10)); + case 'i32': + return _xdr["default"].ScVal.scvI32(parseInt(val, 10)); + default: + if (_index.XdrLargeInt.isType(optType)) { + return new _index.XdrLargeInt(optType, val).toScVal(); + } + throw new TypeError("invalid type (".concat(opts.type, ") specified for string value")); + } + } + case 'boolean': + return _xdr["default"].ScVal.scvBool(val); + case 'undefined': + return _xdr["default"].ScVal.scvVoid(); + case 'function': + // FIXME: Is this too helpful? + return nativeToScVal(val()); + default: + throw new TypeError("failed to convert typeof ".concat(_typeof(val), " (").concat(val, ")")); + } +} + +/** + * Given a smart contract value, attempt to convert it to a native type. + * Possible conversions include: + * + * - void -> `null` + * - u32, i32 -> `number` + * - u64, i64, u128, i128, u256, i256 -> `bigint` + * - vec -> `Array` of any of the above (via recursion) + * - map -> key-value object of any of the above (via recursion) + * - bool -> `boolean` + * - bytes -> `Uint8Array` + * - symbol -> `string` + * - string -> `string` IF the underlying buffer can be decoded as ascii/utf8, + * `Uint8Array` of the raw contents in any error case + * + * If no viable conversion can be determined, this just "unwraps" the smart + * value to return its underlying XDR value. + * + * @param {xdr.ScVal} scv - the input smart contract value + * + * @returns {any} + * @see nativeToScVal + */ +function scValToNative(scv) { + var _scv$vec, _scv$map; + // we use the verbose xdr.ScValType..value form here because it's faster + // than string comparisons and the underlying constants never need to be + // updated + switch (scv["switch"]().value) { + case _xdr["default"].ScValType.scvVoid().value: + return null; + + // these can be converted to bigints directly + case _xdr["default"].ScValType.scvU64().value: + case _xdr["default"].ScValType.scvI64().value: + return scv.value().toBigInt(); + + // these can be parsed by internal abstractions note that this can also + // handle the above two cases, but it's not as efficient (another + // type-check, parsing, etc.) + case _xdr["default"].ScValType.scvU128().value: + case _xdr["default"].ScValType.scvI128().value: + case _xdr["default"].ScValType.scvU256().value: + case _xdr["default"].ScValType.scvI256().value: + return (0, _index.scValToBigInt)(scv); + case _xdr["default"].ScValType.scvVec().value: + return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(scValToNative); + case _xdr["default"].ScValType.scvAddress().value: + return _address.Address.fromScVal(scv).toString(); + case _xdr["default"].ScValType.scvMap().value: + return Object.fromEntries(((_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []).map(function (entry) { + return [scValToNative(entry.key()), scValToNative(entry.val())]; + })); + + // these return the primitive type directly + case _xdr["default"].ScValType.scvBool().value: + case _xdr["default"].ScValType.scvU32().value: + case _xdr["default"].ScValType.scvI32().value: + case _xdr["default"].ScValType.scvBytes().value: + return scv.value(); + + // Symbols are limited to [a-zA-Z0-9_]+, so we can safely make ascii strings + // + // Strings, however, are "presented" as strings and we treat them as such + // (in other words, string = bytes with a hint that it's text). If the user + // encoded non-printable bytes in their string value, that's on them. + // + // Note that we assume a utf8 encoding (ascii-compatible). For other + // encodings, you should probably use bytes anyway. If it cannot be decoded, + // the raw bytes are returned. + case _xdr["default"].ScValType.scvSymbol().value: + case _xdr["default"].ScValType.scvString().value: + { + var v = scv.value(); // string|Buffer + if (Buffer.isBuffer(v) || ArrayBuffer.isView(v)) { + try { + return new TextDecoder().decode(v); + } catch (e) { + return new Uint8Array(v.buffer); // copy of bytes + } + } + return v; // string already + } + + // these can be converted to bigint + case _xdr["default"].ScValType.scvTimepoint().value: + case _xdr["default"].ScValType.scvDuration().value: + return new _xdr["default"].Uint64(scv.value()).toBigInt(); + case _xdr["default"].ScValType.scvError().value: + switch (scv.error()["switch"]().value) { + // Distinguish errors from the user contract. + case _xdr["default"].ScErrorType.sceContract().value: + return { + type: 'contract', + code: scv.error().contractCode() + }; + default: + { + var err = scv.error(); + return { + type: 'system', + code: err.code().value, + value: err.code().name + }; + } + } + + // in the fallthrough case, just return the underlying value directly + default: + return scv.value(); + } +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/signerkey.js b/node_modules/@stellar/stellar-base/lib/signerkey.js new file mode 100644 index 000000000..47e83d36a --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/signerkey.js @@ -0,0 +1,102 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SignerKey = void 0; +var _xdr = _interopRequireDefault(require("./xdr")); +var _strkey = require("./strkey"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * A container class with helpers to convert between signer keys + * (`xdr.SignerKey`) and {@link StrKey}s. + * + * It's primarly used for manipulating the `extraSigners` precondition on a + * {@link Transaction}. + * + * @see {@link TransactionBuilder.setExtraSigners} + */ +var SignerKey = exports.SignerKey = /*#__PURE__*/function () { + function SignerKey() { + _classCallCheck(this, SignerKey); + } + return _createClass(SignerKey, null, [{ + key: "decodeAddress", + value: + /** + * Decodes a StrKey address into an xdr.SignerKey instance. + * + * Only ED25519 public keys (G...), pre-auth transactions (T...), hashes + * (H...), and signed payloads (P...) can be signer keys. + * + * @param {string} address a StrKey-encoded signer address + * @returns {xdr.SignerKey} + */ + function decodeAddress(address) { + var signerKeyMap = { + ed25519PublicKey: _xdr["default"].SignerKey.signerKeyTypeEd25519, + preAuthTx: _xdr["default"].SignerKey.signerKeyTypePreAuthTx, + sha256Hash: _xdr["default"].SignerKey.signerKeyTypeHashX, + signedPayload: _xdr["default"].SignerKey.signerKeyTypeEd25519SignedPayload + }; + var vb = _strkey.StrKey.getVersionByteForPrefix(address); + var encoder = signerKeyMap[vb]; + if (!encoder) { + throw new Error("invalid signer key type (".concat(vb, ")")); + } + var raw = (0, _strkey.decodeCheck)(vb, address); + switch (vb) { + case 'signedPayload': + return encoder(new _xdr["default"].SignerKeyEd25519SignedPayload({ + ed25519: raw.slice(0, 32), + payload: raw.slice(32 + 4) + })); + case 'ed25519PublicKey': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + default: + return encoder(raw); + } + } + + /** + * Encodes a signer key into its StrKey equivalent. + * + * @param {xdr.SignerKey} signerKey the signer + * @returns {string} the StrKey representation of the signer + */ + }, { + key: "encodeSignerKey", + value: function encodeSignerKey(signerKey) { + var strkeyType; + var raw; + switch (signerKey["switch"]()) { + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519(): + strkeyType = 'ed25519PublicKey'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypePreAuthTx(): + strkeyType = 'preAuthTx'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypeHashX(): + strkeyType = 'sha256Hash'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519SignedPayload(): + strkeyType = 'signedPayload'; + raw = signerKey.ed25519SignedPayload().toXDR('raw'); + break; + default: + throw new Error("invalid SignerKey (type: ".concat(signerKey["switch"](), ")")); + } + return (0, _strkey.encodeCheck)(strkeyType, raw); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/signing.js b/node_modules/@stellar/stellar-base/lib/signing.js new file mode 100644 index 000000000..5cbd475ee --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/signing.js @@ -0,0 +1,96 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FastSigning = void 0; +exports.generate = generate; +exports.sign = sign; +exports.verify = verify; +// This module provides the signing functionality used by the stellar network +// The code below may look a little strange... this is because we try to provide +// the most efficient signing method possible. First, we try to load the +// native `sodium-native` package for node.js environments, and if that fails we +// fallback to `tweetnacl` + +var actualMethods = {}; + +/** + * Use this flag to check if fast signing (provided by `sodium-native` package) is available. + * If your app is signing a large number of transaction or verifying a large number + * of signatures make sure `sodium-native` package is installed. + */ +var FastSigning = exports.FastSigning = checkFastSigning(); +function sign(data, secretKey) { + return actualMethods.sign(data, secretKey); +} +function verify(data, signature, publicKey) { + return actualMethods.verify(data, signature, publicKey); +} +function generate(secretKey) { + return actualMethods.generate(secretKey); +} +function checkFastSigning() { + return typeof window === 'undefined' ? checkFastSigningNode() : checkFastSigningBrowser(); +} +function checkFastSigningNode() { + // NOTE: we use commonjs style require here because es6 imports + // can only occur at the top level. thanks, obama. + var sodium; + try { + // eslint-disable-next-line + sodium = require('sodium-native'); + } catch (err) { + return checkFastSigningBrowser(); + } + if (!Object.keys(sodium).length) { + return checkFastSigningBrowser(); + } + actualMethods.generate = function (secretKey) { + var pk = Buffer.alloc(sodium.crypto_sign_PUBLICKEYBYTES); + var sk = Buffer.alloc(sodium.crypto_sign_SECRETKEYBYTES); + sodium.crypto_sign_seed_keypair(pk, sk, secretKey); + return pk; + }; + actualMethods.sign = function (data, secretKey) { + data = Buffer.from(data); + var signature = Buffer.alloc(sodium.crypto_sign_BYTES); + sodium.crypto_sign_detached(signature, data, secretKey); + return signature; + }; + actualMethods.verify = function (data, signature, publicKey) { + data = Buffer.from(data); + try { + return sodium.crypto_sign_verify_detached(signature, data, publicKey); + } catch (e) { + return false; + } + }; + return true; +} +function checkFastSigningBrowser() { + // fallback to `tweetnacl` if we're in the browser or + // if there was a failure installing `sodium-native` + // eslint-disable-next-line + var nacl = require('tweetnacl'); + actualMethods.generate = function (secretKey) { + var secretKeyUint8 = new Uint8Array(secretKey); + var naclKeys = nacl.sign.keyPair.fromSeed(secretKeyUint8); + return Buffer.from(naclKeys.publicKey); + }; + actualMethods.sign = function (data, secretKey) { + data = Buffer.from(data); + data = new Uint8Array(data.toJSON().data); + secretKey = new Uint8Array(secretKey.toJSON().data); + var signature = nacl.sign.detached(data, secretKey); + return Buffer.from(signature); + }; + actualMethods.verify = function (data, signature, publicKey) { + data = Buffer.from(data); + data = new Uint8Array(data.toJSON().data); + signature = new Uint8Array(signature.toJSON().data); + publicKey = new Uint8Array(publicKey.toJSON().data); + return nacl.sign.detached.verify(data, signature, publicKey); + }; + return false; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/soroban.js b/node_modules/@stellar/stellar-base/lib/soroban.js new file mode 100644 index 000000000..5012a7db4 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/soroban.js @@ -0,0 +1,95 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Soroban = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/* Helper class to assist with formatting and parsing token amounts. */ +var Soroban = exports.Soroban = /*#__PURE__*/function () { + function Soroban() { + _classCallCheck(this, Soroban); + } + return _createClass(Soroban, null, [{ + key: "formatTokenAmount", + value: + /** + * Given a whole number smart contract amount of a token and an amount of + * decimal places (if the token has any), it returns a "display" value. + * + * All arithmetic inside the contract is performed on integers to avoid + * potential precision and consistency issues of floating-point. + * + * @param {string} amount the token amount you want to display + * @param {number} decimals specify how many decimal places a token has + * + * @returns {string} the display value + * @throws {TypeError} if the given amount has a decimal point already + * @example + * formatTokenAmount("123000", 4) === "12.3"; + */ + function formatTokenAmount(amount, decimals) { + if (amount.includes('.')) { + throw new TypeError('No decimals are allowed'); + } + var formatted = amount; + if (decimals > 0) { + if (decimals > formatted.length) { + formatted = ['0', formatted.toString().padStart(decimals, '0')].join('.'); + } else { + formatted = [formatted.slice(0, -decimals), formatted.slice(-decimals)].join('.'); + } + } + + // remove trailing zero if any + return formatted.replace(/(\.\d*?)0+$/, '$1'); + } + + /** + * Parse a token amount to use it on smart contract + * + * This function takes the display value and its decimals (if the token has + * any) and returns a string that'll be used within the smart contract. + * + * @param {string} value the token amount you want to use it on smart + * contract which you've been displaying in a UI + * @param {number} decimals the number of decimal places expected in the + * display value (different than the "actual" number, because suffix zeroes + * might not be present) + * + * @returns {string} the whole number token amount represented by the display + * value with the decimal places shifted over + * + * @example + * const displayValueAmount = "123.4560" + * const parsedAmtForSmartContract = parseTokenAmount(displayValueAmount, 5); + * parsedAmtForSmartContract === "12345600" + */ + }, { + key: "parseTokenAmount", + value: function parseTokenAmount(value, decimals) { + var _fraction$padEnd; + var _value$split$slice = value.split('.').slice(), + _value$split$slice2 = _toArray(_value$split$slice), + whole = _value$split$slice2[0], + fraction = _value$split$slice2[1], + rest = _value$split$slice2.slice(2); + if (rest.length) { + throw new Error("Invalid decimal value: ".concat(value)); + } + var shifted = BigInt(whole + ((_fraction$padEnd = fraction === null || fraction === void 0 ? void 0 : fraction.padEnd(decimals, '0')) !== null && _fraction$padEnd !== void 0 ? _fraction$padEnd : '0'.repeat(decimals))); + return shifted.toString(); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/sorobandata_builder.js b/node_modules/@stellar/stellar-base/lib/sorobandata_builder.js new file mode 100644 index 000000000..c86b0d8f6 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/sorobandata_builder.js @@ -0,0 +1,217 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SorobanDataBuilder = void 0; +var _xdr = _interopRequireDefault(require("./xdr")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Supports building {@link xdr.SorobanTransactionData} structures with various + * items set to specific values. + * + * This is recommended for when you are building + * {@link Operation.extendFootprintTtl} / {@link Operation.restoreFootprint} + * operations and need to {@link TransactionBuilder.setSorobanData} to avoid + * (re)building the entire data structure from scratch. + * + * @constructor + * + * @param {string | xdr.SorobanTransactionData} [sorobanData] either a + * base64-encoded string that represents an + * {@link xdr.SorobanTransactionData} instance or an XDR instance itself + * (it will be copied); if omitted or "falsy" (e.g. an empty string), it + * starts with an empty instance + * + * @example + * // You want to use an existing data blob but override specific parts. + * const newData = new SorobanDataBuilder(existing) + * .setReadOnly(someLedgerKeys) + * .setRefundableFee("1000") + * .build(); + * + * // You want an instance from scratch + * const newData = new SorobanDataBuilder() + * .setFootprint([someLedgerKey], []) + * .setRefundableFee("1000") + * .build(); + */ +var SorobanDataBuilder = exports.SorobanDataBuilder = /*#__PURE__*/function () { + function SorobanDataBuilder(sorobanData) { + _classCallCheck(this, SorobanDataBuilder); + _defineProperty(this, "_data", void 0); + var data; + if (!sorobanData) { + data = new _xdr["default"].SorobanTransactionData({ + resources: new _xdr["default"].SorobanResources({ + footprint: new _xdr["default"].LedgerFootprint({ + readOnly: [], + readWrite: [] + }), + instructions: 0, + readBytes: 0, + writeBytes: 0 + }), + ext: new _xdr["default"].ExtensionPoint(0), + resourceFee: new _xdr["default"].Int64(0) + }); + } else if (typeof sorobanData === 'string' || ArrayBuffer.isView(sorobanData)) { + data = SorobanDataBuilder.fromXDR(sorobanData); + } else { + data = SorobanDataBuilder.fromXDR(sorobanData.toXDR()); // copy + } + this._data = data; + } + + /** + * Decodes and builds a {@link xdr.SorobanTransactionData} instance. + * @param {Uint8Array|Buffer|string} data raw input to decode + * @returns {xdr.SorobanTransactionData} + */ + return _createClass(SorobanDataBuilder, [{ + key: "setResourceFee", + value: + /** + * Sets the resource fee portion of the Soroban data. + * @param {number | bigint | string} fee the resource fee to set (int64) + * @returns {SorobanDataBuilder} + */ + function setResourceFee(fee) { + this._data.resourceFee(new _xdr["default"].Int64(fee)); + return this; + } + + /** + * Sets up the resource metrics. + * + * You should almost NEVER need this, as its often generated / provided to you + * by transaction simulation/preflight from a Soroban RPC server. + * + * @param {number} cpuInstrs number of CPU instructions + * @param {number} readBytes number of bytes being read + * @param {number} writeBytes number of bytes being written + * + * @returns {SorobanDataBuilder} + */ + }, { + key: "setResources", + value: function setResources(cpuInstrs, readBytes, writeBytes) { + this._data.resources().instructions(cpuInstrs); + this._data.resources().readBytes(readBytes); + this._data.resources().writeBytes(writeBytes); + return this; + } + + /** + * Appends the given ledger keys to the existing storage access footprint. + * @param {xdr.LedgerKey[]} readOnly read-only keys to add + * @param {xdr.LedgerKey[]} readWrite read-write keys to add + * @returns {SorobanDataBuilder} this builder instance + */ + }, { + key: "appendFootprint", + value: function appendFootprint(readOnly, readWrite) { + return this.setFootprint(this.getReadOnly().concat(readOnly), this.getReadWrite().concat(readWrite)); + } + + /** + * Sets the storage access footprint to be a certain set of ledger keys. + * + * You can also set each field explicitly via + * {@link SorobanDataBuilder.setReadOnly} and + * {@link SorobanDataBuilder.setReadWrite} or add to the existing footprint + * via {@link SorobanDataBuilder.appendFootprint}. + * + * Passing `null|undefined` to either parameter will IGNORE the existing + * values. If you want to clear them, pass `[]`, instead. + * + * @param {xdr.LedgerKey[]|null} [readOnly] the set of ledger keys to set in + * the read-only portion of the transaction's `sorobanData`, or `null | + * undefined` to keep the existing keys + * @param {xdr.LedgerKey[]|null} [readWrite] the set of ledger keys to set in + * the read-write portion of the transaction's `sorobanData`, or `null | + * undefined` to keep the existing keys + * @returns {SorobanDataBuilder} this builder instance + */ + }, { + key: "setFootprint", + value: function setFootprint(readOnly, readWrite) { + if (readOnly !== null) { + // null means "leave me alone" + this.setReadOnly(readOnly); + } + if (readWrite !== null) { + this.setReadWrite(readWrite); + } + return this; + } + + /** + * @param {xdr.LedgerKey[]} readOnly read-only keys in the access footprint + * @returns {SorobanDataBuilder} + */ + }, { + key: "setReadOnly", + value: function setReadOnly(readOnly) { + this._data.resources().footprint().readOnly(readOnly !== null && readOnly !== void 0 ? readOnly : []); + return this; + } + + /** + * @param {xdr.LedgerKey[]} readWrite read-write keys in the access footprint + * @returns {SorobanDataBuilder} + */ + }, { + key: "setReadWrite", + value: function setReadWrite(readWrite) { + this._data.resources().footprint().readWrite(readWrite !== null && readWrite !== void 0 ? readWrite : []); + return this; + } + + /** + * @returns {xdr.SorobanTransactionData} a copy of the final data structure + */ + }, { + key: "build", + value: function build() { + return _xdr["default"].SorobanTransactionData.fromXDR(this._data.toXDR()); // clone + } + + // + // getters follow + // + + /** @returns {xdr.LedgerKey[]} the read-only storage access pattern */ + }, { + key: "getReadOnly", + value: function getReadOnly() { + return this.getFootprint().readOnly(); + } + + /** @returns {xdr.LedgerKey[]} the read-write storage access pattern */ + }, { + key: "getReadWrite", + value: function getReadWrite() { + return this.getFootprint().readWrite(); + } + + /** @returns {xdr.LedgerFootprint} the storage access pattern */ + }, { + key: "getFootprint", + value: function getFootprint() { + return this._data.resources().footprint(); + } + }], [{ + key: "fromXDR", + value: function fromXDR(data) { + return _xdr["default"].SorobanTransactionData.fromXDR(data, typeof data === 'string' ? 'base64' : 'raw'); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/strkey.js b/node_modules/@stellar/stellar-base/lib/strkey.js new file mode 100644 index 000000000..0159b2516 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/strkey.js @@ -0,0 +1,399 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.StrKey = void 0; +exports.decodeCheck = decodeCheck; +exports.encodeCheck = encodeCheck; +var _base = _interopRequireDefault(require("base32.js")); +var _checksum = require("./util/checksum"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": ["<<", ">>", "^", "&", "&="]}] */ +var versionBytes = { + ed25519PublicKey: 6 << 3, + // G (when encoded in base32) + ed25519SecretSeed: 18 << 3, + // S + med25519PublicKey: 12 << 3, + // M + preAuthTx: 19 << 3, + // T + sha256Hash: 23 << 3, + // X + signedPayload: 15 << 3, + // P + contract: 2 << 3 // C +}; +var strkeyTypes = { + G: 'ed25519PublicKey', + S: 'ed25519SecretSeed', + M: 'med25519PublicKey', + T: 'preAuthTx', + X: 'sha256Hash', + P: 'signedPayload', + C: 'contract' +}; + +/** + * StrKey is a helper class that allows encoding and decoding Stellar keys + * to/from strings, i.e. between their binary (Buffer, xdr.PublicKey, etc.) and + * string (i.e. "GABCD...", etc.) representations. + */ +var StrKey = exports.StrKey = /*#__PURE__*/function () { + function StrKey() { + _classCallCheck(this, StrKey); + } + return _createClass(StrKey, null, [{ + key: "encodeEd25519PublicKey", + value: + /** + * Encodes `data` to strkey ed25519 public key. + * + * @param {Buffer} data raw data to encode + * @returns {string} "G..." representation of the key + */ + function encodeEd25519PublicKey(data) { + return encodeCheck('ed25519PublicKey', data); + } + + /** + * Decodes strkey ed25519 public key to raw data. + * + * If the parameter is a muxed account key ("M..."), this will only encode it + * as a basic Ed25519 key (as if in "G..." format). + * + * @param {string} data "G..." (or "M...") key representation to decode + * @returns {Buffer} raw key + */ + }, { + key: "decodeEd25519PublicKey", + value: function decodeEd25519PublicKey(data) { + return decodeCheck('ed25519PublicKey', data); + } + + /** + * Returns true if the given Stellar public key is a valid ed25519 public key. + * @param {string} publicKey public key to check + * @returns {boolean} + */ + }, { + key: "isValidEd25519PublicKey", + value: function isValidEd25519PublicKey(publicKey) { + return isValid('ed25519PublicKey', publicKey); + } + + /** + * Encodes data to strkey ed25519 seed. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeEd25519SecretSeed", + value: function encodeEd25519SecretSeed(data) { + return encodeCheck('ed25519SecretSeed', data); + } + + /** + * Decodes strkey ed25519 seed to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeEd25519SecretSeed", + value: function decodeEd25519SecretSeed(address) { + return decodeCheck('ed25519SecretSeed', address); + } + + /** + * Returns true if the given Stellar secret key is a valid ed25519 secret seed. + * @param {string} seed seed to check + * @returns {boolean} + */ + }, { + key: "isValidEd25519SecretSeed", + value: function isValidEd25519SecretSeed(seed) { + return isValid('ed25519SecretSeed', seed); + } + + /** + * Encodes data to strkey med25519 public key. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeMed25519PublicKey", + value: function encodeMed25519PublicKey(data) { + return encodeCheck('med25519PublicKey', data); + } + + /** + * Decodes strkey med25519 public key to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeMed25519PublicKey", + value: function decodeMed25519PublicKey(address) { + return decodeCheck('med25519PublicKey', address); + } + + /** + * Returns true if the given Stellar public key is a valid med25519 public key. + * @param {string} publicKey public key to check + * @returns {boolean} + */ + }, { + key: "isValidMed25519PublicKey", + value: function isValidMed25519PublicKey(publicKey) { + return isValid('med25519PublicKey', publicKey); + } + + /** + * Encodes data to strkey preAuthTx. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodePreAuthTx", + value: function encodePreAuthTx(data) { + return encodeCheck('preAuthTx', data); + } + + /** + * Decodes strkey PreAuthTx to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodePreAuthTx", + value: function decodePreAuthTx(address) { + return decodeCheck('preAuthTx', address); + } + + /** + * Encodes data to strkey sha256 hash. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeSha256Hash", + value: function encodeSha256Hash(data) { + return encodeCheck('sha256Hash', data); + } + + /** + * Decodes strkey sha256 hash to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeSha256Hash", + value: function decodeSha256Hash(address) { + return decodeCheck('sha256Hash', address); + } + + /** + * Encodes raw data to strkey signed payload (P...). + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeSignedPayload", + value: function encodeSignedPayload(data) { + return encodeCheck('signedPayload', data); + } + + /** + * Decodes strkey signed payload (P...) to raw data. + * @param {string} address address to decode + * @returns {Buffer} + */ + }, { + key: "decodeSignedPayload", + value: function decodeSignedPayload(address) { + return decodeCheck('signedPayload', address); + } + + /** + * Checks validity of alleged signed payload (P...) strkey address. + * @param {string} address signer key to check + * @returns {boolean} + */ + }, { + key: "isValidSignedPayload", + value: function isValidSignedPayload(address) { + return isValid('signedPayload', address); + } + + /** + * Encodes raw data to strkey contract (C...). + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeContract", + value: function encodeContract(data) { + return encodeCheck('contract', data); + } + + /** + * Decodes strkey contract (C...) to raw data. + * @param {string} address address to decode + * @returns {Buffer} + */ + }, { + key: "decodeContract", + value: function decodeContract(address) { + return decodeCheck('contract', address); + } + + /** + * Checks validity of alleged contract (C...) strkey address. + * @param {string} address signer key to check + * @returns {boolean} + */ + }, { + key: "isValidContract", + value: function isValidContract(address) { + return isValid('contract', address); + } + }, { + key: "getVersionByteForPrefix", + value: function getVersionByteForPrefix(address) { + return strkeyTypes[address[0]]; + } + }]); +}(); +/** + * Sanity-checks whether or not a strkey *appears* valid. + * + * @param {string} versionByteName the type of strkey to expect in `encoded` + * @param {string} encoded the strkey to validate + * + * @return {Boolean} whether or not the `encoded` strkey appears valid for the + * `versionByteName` strkey type (see `versionBytes`, above). + * + * @note This isn't a *definitive* check of validity, but rather a best-effort + * check based on (a) input length, (b) whether or not it can be decoded, + * and (c) output length. + */ +function isValid(versionByteName, encoded) { + if (typeof encoded !== 'string') { + return false; + } + + // basic length checks on the strkey lengths + switch (versionByteName) { + case 'ed25519PublicKey': // falls through + case 'ed25519SecretSeed': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + case 'contract': + if (encoded.length !== 56) { + return false; + } + break; + case 'med25519PublicKey': + if (encoded.length !== 69) { + return false; + } + break; + case 'signedPayload': + if (encoded.length < 56 || encoded.length > 165) { + return false; + } + break; + default: + return false; + } + var decoded = ''; + try { + decoded = decodeCheck(versionByteName, encoded); + } catch (err) { + return false; + } + + // basic length checks on the resulting buffer sizes + switch (versionByteName) { + case 'ed25519PublicKey': // falls through + case 'ed25519SecretSeed': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + case 'contract': + return decoded.length === 32; + case 'med25519PublicKey': + return decoded.length === 40; + // +8 bytes for the ID + + case 'signedPayload': + return ( + // 32 for the signer, +4 for the payload size, then either +4 for the + // min or +64 for the max payload + decoded.length >= 32 + 4 + 4 && decoded.length <= 32 + 4 + 64 + ); + default: + return false; + } +} +function decodeCheck(versionByteName, encoded) { + if (typeof encoded !== 'string') { + throw new TypeError('encoded argument must be of type String'); + } + var decoded = _base["default"].decode(encoded); + var versionByte = decoded[0]; + var payload = decoded.slice(0, -2); + var data = payload.slice(1); + var checksum = decoded.slice(-2); + if (encoded !== _base["default"].encode(decoded)) { + throw new Error('invalid encoded string'); + } + var expectedVersion = versionBytes[versionByteName]; + if (expectedVersion === undefined) { + throw new Error("".concat(versionByteName, " is not a valid version byte name. ") + "Expected one of ".concat(Object.keys(versionBytes).join(', '))); + } + if (versionByte !== expectedVersion) { + throw new Error("invalid version byte. expected ".concat(expectedVersion, ", got ").concat(versionByte)); + } + var expectedChecksum = calculateChecksum(payload); + if (!(0, _checksum.verifyChecksum)(expectedChecksum, checksum)) { + throw new Error("invalid checksum"); + } + return Buffer.from(data); +} +function encodeCheck(versionByteName, data) { + if (data === null || data === undefined) { + throw new Error('cannot encode null data'); + } + var versionByte = versionBytes[versionByteName]; + if (versionByte === undefined) { + throw new Error("".concat(versionByteName, " is not a valid version byte name. ") + "Expected one of ".concat(Object.keys(versionBytes).join(', '))); + } + data = Buffer.from(data); + var versionBuffer = Buffer.from([versionByte]); + var payload = Buffer.concat([versionBuffer, data]); + var checksum = Buffer.from(calculateChecksum(payload)); + var unencoded = Buffer.concat([payload, checksum]); + return _base["default"].encode(unencoded); +} + +// Computes the CRC16-XModem checksum of `payload` in little-endian order +function calculateChecksum(payload) { + var crcTable = [0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0]; + var crc16 = 0x0; + for (var i = 0; i < payload.length; i += 1) { + var _byte = payload[i]; + var lookupIndex = crc16 >> 8 ^ _byte; + crc16 = crc16 << 8 ^ crcTable[lookupIndex]; + crc16 &= 0xffff; + } + var checksum = new Uint8Array(2); + checksum[0] = crc16 & 0xff; + checksum[1] = crc16 >> 8 & 0xff; + return checksum; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/transaction.js b/node_modules/@stellar/stellar-base/lib/transaction.js new file mode 100644 index 000000000..d7ff289f1 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/transaction.js @@ -0,0 +1,367 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Transaction = void 0; +var _xdr = _interopRequireDefault(require("./xdr")); +var _hashing = require("./hashing"); +var _strkey = require("./strkey"); +var _operation = require("./operation"); +var _memo = require("./memo"); +var _transaction_base = require("./transaction_base"); +var _decode_encode_muxed_account = require("./util/decode_encode_muxed_account"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Use {@link TransactionBuilder} to build a transaction object. If you have an + * object or base64-encoded string of the transaction envelope XDR, use {@link + * TransactionBuilder.fromXDR}. + * + * Once a Transaction has been created, its attributes and operations should not + * be changed. You should only add signatures (using {@link Transaction#sign}) + * to a Transaction object before submitting to the network or forwarding on to + * additional signers. + * + * @constructor + * + * @param {string|xdr.TransactionEnvelope} envelope - transaction envelope + * object or base64 encoded string + * @param {string} [networkPassphrase] - passphrase of the target stellar + * network (e.g. "Public Global Stellar Network ; September 2015") + * + * @extends TransactionBase + */ +var Transaction = exports.Transaction = /*#__PURE__*/function (_TransactionBase) { + function Transaction(envelope, networkPassphrase) { + var _this; + _classCallCheck(this, Transaction); + if (typeof envelope === 'string') { + var buffer = Buffer.from(envelope, 'base64'); + envelope = _xdr["default"].TransactionEnvelope.fromXDR(buffer); + } + var envelopeType = envelope["switch"](); + if (!(envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTxV0() || envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTx())) { + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ".concat(envelopeType.name, ".")); + } + var txEnvelope = envelope.value(); + var tx = txEnvelope.tx(); + var fee = tx.fee().toString(); + var signatures = (txEnvelope.signatures() || []).slice(); + _this = _callSuper(this, Transaction, [tx, signatures, fee, networkPassphrase]); + _this._envelopeType = envelopeType; + _this._memo = tx.memo(); + _this._sequence = tx.seqNum().toString(); + switch (_this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + _this._source = _strkey.StrKey.encodeEd25519PublicKey(_this.tx.sourceAccountEd25519()); + break; + default: + _this._source = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(_this.tx.sourceAccount()); + break; + } + var cond = null; + var timeBounds = null; + switch (_this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + timeBounds = tx.timeBounds(); + break; + case _xdr["default"].EnvelopeType.envelopeTypeTx(): + switch (tx.cond()["switch"]()) { + case _xdr["default"].PreconditionType.precondTime(): + timeBounds = tx.cond().timeBounds(); + break; + case _xdr["default"].PreconditionType.precondV2(): + cond = tx.cond().v2(); + timeBounds = cond.timeBounds(); + break; + default: + break; + } + break; + default: + break; + } + if (timeBounds) { + _this._timeBounds = { + minTime: timeBounds.minTime().toString(), + maxTime: timeBounds.maxTime().toString() + }; + } + if (cond) { + var ledgerBounds = cond.ledgerBounds(); + if (ledgerBounds) { + _this._ledgerBounds = { + minLedger: ledgerBounds.minLedger(), + maxLedger: ledgerBounds.maxLedger() + }; + } + var minSeq = cond.minSeqNum(); + if (minSeq) { + _this._minAccountSequence = minSeq.toString(); + } + _this._minAccountSequenceAge = cond.minSeqAge(); + _this._minAccountSequenceLedgerGap = cond.minSeqLedgerGap(); + _this._extraSigners = cond.extraSigners(); + } + var operations = tx.operations() || []; + _this._operations = operations.map(function (op) { + return _operation.Operation.fromXDRObject(op); + }); + return _this; + } + + /** + * @type {object} + * @property {string} 64 bit unix timestamp + * @property {string} 64 bit unix timestamp + * @readonly + */ + _inherits(Transaction, _TransactionBase); + return _createClass(Transaction, [{ + key: "timeBounds", + get: function get() { + return this._timeBounds; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {object} + * @property {number} minLedger - smallest ledger bound (uint32) + * @property {number} maxLedger - largest ledger bound (or 0 for inf) + * @readonly + */ + }, { + key: "ledgerBounds", + get: function get() { + return this._ledgerBounds; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 64 bit account sequence + * @readonly + * @type {string} + */ + }, { + key: "minAccountSequence", + get: function get() { + return this._minAccountSequence; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 64 bit number of seconds + * @type {number} + * @readonly + */ + }, { + key: "minAccountSequenceAge", + get: function get() { + return this._minAccountSequenceAge; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 32 bit number of ledgers + * @type {number} + * @readonly + */ + }, { + key: "minAccountSequenceLedgerGap", + get: function get() { + return this._minAccountSequenceLedgerGap; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * array of extra signers ({@link StrKey}s) + * @type {string[]} + * @readonly + */ + }, { + key: "extraSigners", + get: function get() { + return this._extraSigners; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "sequence", + get: function get() { + return this._sequence; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "source", + get: function get() { + return this._source; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {Array.} + * @readonly + */ + }, { + key: "operations", + get: function get() { + return this._operations; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "memo", + get: function get() { + return _memo.Memo.fromXDRObject(this._memo); + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * Returns the "signature base" of this transaction, which is the value + * that, when hashed, should be signed to create a signature that + * validators on the Stellar Network will accept. + * + * It is composed of a 4 prefix bytes followed by the xdr-encoded form + * of this transaction. + * @returns {Buffer} + */ + }, { + key: "signatureBase", + value: function signatureBase() { + var tx = this.tx; + + // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // we need a Transaction to generate the signature base + if (this._envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTxV0()) { + tx = _xdr["default"].Transaction.fromXDR(Buffer.concat([ + // TransactionV0 is a transaction with the AccountID discriminant + // stripped off, we need to put it back to build a valid transaction + // which we can use to build a TransactionSignaturePayloadTaggedTransaction + _xdr["default"].PublicKeyType.publicKeyTypeEd25519().toXDR(), tx.toXDR()])); + } + var taggedTransaction = new _xdr["default"].TransactionSignaturePayloadTaggedTransaction.envelopeTypeTx(tx); + var txSignature = new _xdr["default"].TransactionSignaturePayload({ + networkId: _xdr["default"].Hash.fromXDR((0, _hashing.hash)(this.networkPassphrase)), + taggedTransaction: taggedTransaction + }); + return txSignature.toXDR(); + } + + /** + * To envelope returns a xdr.TransactionEnvelope which can be submitted to the network. + * @returns {xdr.TransactionEnvelope} + */ + }, { + key: "toEnvelope", + value: function toEnvelope() { + var rawTx = this.tx.toXDR(); + var signatures = this.signatures.slice(); // make a copy of the signatures + + var envelope; + switch (this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTxV0(new _xdr["default"].TransactionV0Envelope({ + tx: _xdr["default"].TransactionV0.fromXDR(rawTx), + // make a copy of tx + signatures: signatures + })); + break; + case _xdr["default"].EnvelopeType.envelopeTypeTx(): + envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: _xdr["default"].Transaction.fromXDR(rawTx), + // make a copy of tx + signatures: signatures + })); + break; + default: + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ".concat(this._envelopeType.name, ".")); + } + return envelope; + } + + /** + * Calculate the claimable balance ID for an operation within the transaction. + * + * @param {integer} opIndex the index of the CreateClaimableBalance op + * @returns {string} a hex string representing the claimable balance ID + * + * @throws {RangeError} for invalid `opIndex` value + * @throws {TypeError} if op at `opIndex` is not `CreateClaimableBalance` + * @throws for general XDR un/marshalling failures + * + * @see https://github.com/stellar/go/blob/d712346e61e288d450b0c08038c158f8848cc3e4/txnbuild/transaction.go#L392-L435 + * + */ + }, { + key: "getClaimableBalanceId", + value: function getClaimableBalanceId(opIndex) { + // Validate and then extract the operation from the transaction. + if (!Number.isInteger(opIndex) || opIndex < 0 || opIndex >= this.operations.length) { + throw new RangeError('invalid operation index'); + } + var op = this.operations[opIndex]; + try { + op = _operation.Operation.createClaimableBalance(op); + } catch (err) { + throw new TypeError("expected createClaimableBalance, got ".concat(op.type, ": ").concat(err)); + } + + // Always use the transaction's *unmuxed* source. + var account = _strkey.StrKey.decodeEd25519PublicKey((0, _decode_encode_muxed_account.extractBaseAddress)(this.source)); + var operationId = _xdr["default"].HashIdPreimage.envelopeTypeOpId(new _xdr["default"].HashIdPreimageOperationId({ + sourceAccount: _xdr["default"].AccountId.publicKeyTypeEd25519(account), + seqNum: _xdr["default"].SequenceNumber.fromString(this.sequence), + opNum: opIndex + })); + var opIdHash = (0, _hashing.hash)(operationId.toXDR('raw')); + var balanceId = _xdr["default"].ClaimableBalanceId.claimableBalanceIdTypeV0(opIdHash); + return balanceId.toXDR('hex'); + } + }]); +}(_transaction_base.TransactionBase); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/transaction_base.js b/node_modules/@stellar/stellar-base/lib/transaction_base.js new file mode 100644 index 000000000..8454e86c3 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/transaction_base.js @@ -0,0 +1,247 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TransactionBase = void 0; +var _xdr = _interopRequireDefault(require("./xdr")); +var _hashing = require("./hashing"); +var _keypair = require("./keypair"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * @ignore + */ +var TransactionBase = exports.TransactionBase = /*#__PURE__*/function () { + function TransactionBase(tx, signatures, fee, networkPassphrase) { + _classCallCheck(this, TransactionBase); + if (typeof networkPassphrase !== 'string') { + throw new Error("Invalid passphrase provided to Transaction: expected a string but got a ".concat(_typeof(networkPassphrase))); + } + this._networkPassphrase = networkPassphrase; + this._tx = tx; + this._signatures = signatures; + this._fee = fee; + } + + /** + * @type {Array.} + * @readonly + */ + return _createClass(TransactionBase, [{ + key: "signatures", + get: function get() { + return this._signatures; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + }, { + key: "tx", + get: function get() { + return this._tx; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "fee", + get: function get() { + return this._fee; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "networkPassphrase", + get: function get() { + return this._networkPassphrase; + }, + set: function set(networkPassphrase) { + this._networkPassphrase = networkPassphrase; + } + + /** + * Signs the transaction with the given {@link Keypair}. + * @param {...Keypair} keypairs Keypairs of signers + * @returns {void} + */ + }, { + key: "sign", + value: function sign() { + var _this = this; + var txHash = this.hash(); + for (var _len = arguments.length, keypairs = new Array(_len), _key = 0; _key < _len; _key++) { + keypairs[_key] = arguments[_key]; + } + keypairs.forEach(function (kp) { + var sig = kp.signDecorated(txHash); + _this.signatures.push(sig); + }); + } + + /** + * Signs a transaction with the given {@link Keypair}. Useful if someone sends + * you a transaction XDR for you to sign and return (see + * [addSignature](#addSignature) for more information). + * + * When you get a transaction XDR to sign.... + * - Instantiate a `Transaction` object with the XDR + * - Use {@link Keypair} to generate a keypair object for your Stellar seed. + * - Run `getKeypairSignature` with that keypair + * - Send back the signature along with your publicKey (not your secret seed!) + * + * Example: + * ```javascript + * // `transactionXDR` is a string from the person generating the transaction + * const transaction = new Transaction(transactionXDR, networkPassphrase); + * const keypair = Keypair.fromSecret(myStellarSeed); + * return transaction.getKeypairSignature(keypair); + * ``` + * + * @param {Keypair} keypair Keypair of signer + * @returns {string} Signature string + */ + }, { + key: "getKeypairSignature", + value: function getKeypairSignature(keypair) { + return keypair.sign(this.hash()).toString('base64'); + } + + /** + * Add a signature to the transaction. Useful when a party wants to pre-sign + * a transaction but doesn't want to give access to their secret keys. + * This will also verify whether the signature is valid. + * + * Here's how you would use this feature to solicit multiple signatures. + * - Use `TransactionBuilder` to build a new transaction. + * - Make sure to set a long enough timeout on that transaction to give your + * signers enough time to sign! + * - Once you build the transaction, use `transaction.toXDR()` to get the + * base64-encoded XDR string. + * - _Warning!_ Once you've built this transaction, don't submit any other + * transactions onto your account! Doing so will invalidate this pre-compiled + * transaction! + * - Send this XDR string to your other parties. They can use the instructions + * for [getKeypairSignature](#getKeypairSignature) to sign the transaction. + * - They should send you back their `publicKey` and the `signature` string + * from [getKeypairSignature](#getKeypairSignature), both of which you pass to + * this function. + * + * @param {string} publicKey The public key of the signer + * @param {string} signature The base64 value of the signature XDR + * @returns {void} + */ + }, { + key: "addSignature", + value: function addSignature() { + var publicKey = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var signature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + if (!signature || typeof signature !== 'string') { + throw new Error('Invalid signature'); + } + if (!publicKey || typeof publicKey !== 'string') { + throw new Error('Invalid publicKey'); + } + var keypair; + var hint; + var signatureBuffer = Buffer.from(signature, 'base64'); + try { + keypair = _keypair.Keypair.fromPublicKey(publicKey); + hint = keypair.signatureHint(); + } catch (e) { + throw new Error('Invalid publicKey'); + } + if (!keypair.verify(this.hash(), signatureBuffer)) { + throw new Error('Invalid signature'); + } + this.signatures.push(new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signatureBuffer + })); + } + + /** + * Add a decorated signature directly to the transaction envelope. + * + * @param {xdr.DecoratedSignature} signature raw signature to add + * @returns {void} + * + * @see Keypair.signDecorated + * @see Keypair.signPayloadDecorated + */ + }, { + key: "addDecoratedSignature", + value: function addDecoratedSignature(signature) { + this.signatures.push(signature); + } + + /** + * Add `hashX` signer preimage as signature. + * @param {Buffer|String} preimage Preimage of hash used as signer + * @returns {void} + */ + }, { + key: "signHashX", + value: function signHashX(preimage) { + if (typeof preimage === 'string') { + preimage = Buffer.from(preimage, 'hex'); + } + if (preimage.length > 64) { + throw new Error('preimage cannnot be longer than 64 bytes'); + } + var signature = preimage; + var hashX = (0, _hashing.hash)(preimage); + var hint = hashX.slice(hashX.length - 4); + this.signatures.push(new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signature + })); + } + + /** + * Returns a hash for this transaction, suitable for signing. + * @returns {Buffer} + */ + }, { + key: "hash", + value: function hash() { + return (0, _hashing.hash)(this.signatureBase()); + } + }, { + key: "signatureBase", + value: function signatureBase() { + throw new Error('Implement in subclass'); + } + }, { + key: "toEnvelope", + value: function toEnvelope() { + throw new Error('Implement in subclass'); + } + + /** + * Get the transaction envelope as a base64-encoded string + * @returns {string} XDR string + */ + }, { + key: "toXDR", + value: function toXDR() { + return this.toEnvelope().toXDR().toString('base64'); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/transaction_builder.js b/node_modules/@stellar/stellar-base/lib/transaction_builder.js new file mode 100644 index 000000000..4b557f677 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/transaction_builder.js @@ -0,0 +1,781 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TransactionBuilder = exports.TimeoutInfinite = exports.BASE_FEE = void 0; +exports.isValidDate = isValidDate; +var _jsXdr = require("@stellar/js-xdr"); +var _bignumber = _interopRequireDefault(require("./util/bignumber")); +var _xdr = _interopRequireDefault(require("./xdr")); +var _account = require("./account"); +var _muxed_account = require("./muxed_account"); +var _decode_encode_muxed_account = require("./util/decode_encode_muxed_account"); +var _transaction = require("./transaction"); +var _fee_bump_transaction = require("./fee_bump_transaction"); +var _sorobandata_builder = require("./sorobandata_builder"); +var _strkey = require("./strkey"); +var _signerkey = require("./signerkey"); +var _memo = require("./memo"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Minimum base fee for transactions. If this fee is below the network + * minimum, the transaction will fail. The more operations in the + * transaction, the greater the required fee. Use {@link + * Server#fetchBaseFee} to get an accurate value of minimum transaction + * fee on the network. + * + * @constant + * @see [Fees](https://developers.stellar.org/docs/glossary/fees/) + */ +var BASE_FEE = exports.BASE_FEE = '100'; // Stroops + +/** + * @constant + * @see {@link TransactionBuilder#setTimeout} + * @see [Timeout](https://developers.stellar.org/api/resources/transactions/post/) + */ +var TimeoutInfinite = exports.TimeoutInfinite = 0; + +/** + *

Transaction builder helps constructs a new `{@link Transaction}` using the + * given {@link Account} as the transaction's "source account". The transaction + * will use the current sequence number of the given account as its sequence + * number and increment the given account's sequence number by one. The given + * source account must include a private key for signing the transaction or an + * error will be thrown.

+ * + *

Operations can be added to the transaction via their corresponding builder + * methods, and each returns the TransactionBuilder object so they can be + * chained together. After adding the desired operations, call the `build()` + * method on the `TransactionBuilder` to return a fully constructed `{@link + * Transaction}` that can be signed. The returned transaction will contain the + * sequence number of the source account and include the signature from the + * source account.

+ * + *

Be careful about unsubmitted transactions! When you build + * a transaction, `stellar-sdk` automatically increments the source account's + * sequence number. If you end up not submitting this transaction and submitting + * another one instead, it'll fail due to the sequence number being wrong. So if + * you decide not to use a built transaction, make sure to update the source + * account's sequence number with + * [Server.loadAccount](https://stellar.github.io/js-stellar-sdk/Server.html#loadAccount) + * before creating another transaction.

+ * + *

The following code example creates a new transaction with {@link + * Operation.createAccount} and {@link Operation.payment} operations. The + * Transaction's source account first funds `destinationA`, then sends a payment + * to `destinationB`. The built transaction is then signed by + * `sourceKeypair`.

+ * + * ``` + * var transaction = new TransactionBuilder(source, { fee, networkPassphrase: Networks.TESTNET }) + * .addOperation(Operation.createAccount({ + * destination: destinationA, + * startingBalance: "20" + * })) // <- funds and creates destinationA + * .addOperation(Operation.payment({ + * destination: destinationB, + * amount: "100", + * asset: Asset.native() + * })) // <- sends 100 XLM to destinationB + * .setTimeout(30) + * .build(); + * + * transaction.sign(sourceKeypair); + * ``` + * + * @constructor + * + * @param {Account} sourceAccount - source account for this transaction + * @param {object} opts - Options object + * @param {string} opts.fee - max fee you're willing to pay per + * operation in this transaction (**in stroops**) + * + * @param {object} [opts.timebounds] - timebounds for the + * validity of this transaction + * @param {number|string|Date} [opts.timebounds.minTime] - 64-bit UNIX + * timestamp or Date object + * @param {number|string|Date} [opts.timebounds.maxTime] - 64-bit UNIX + * timestamp or Date object + * @param {object} [opts.ledgerbounds] - ledger bounds for the + * validity of this transaction + * @param {number} [opts.ledgerbounds.minLedger] - number of the minimum + * ledger sequence + * @param {number} [opts.ledgerbounds.maxLedger] - number of the maximum + * ledger sequence + * @param {string} [opts.minAccountSequence] - number for + * the minimum account sequence + * @param {number} [opts.minAccountSequenceAge] - number of + * seconds for the minimum account sequence age + * @param {number} [opts.minAccountSequenceLedgerGap] - number of + * ledgers for the minimum account sequence ledger gap + * @param {string[]} [opts.extraSigners] - list of the extra signers + * required for this transaction + * @param {Memo} [opts.memo] - memo for the transaction + * @param {string} [opts.networkPassphrase] passphrase of the + * target Stellar network (e.g. "Public Global Stellar Network ; September + * 2015" for the pubnet) + * @param {xdr.SorobanTransactionData | string} [opts.sorobanData] - an + * optional instance of {@link xdr.SorobanTransactionData} to be set as the + * internal `Transaction.Ext.SorobanData` field (either the xdr object or a + * base64 string). In the case of Soroban transactions, this can be obtained + * from a prior simulation of the transaction with a contract invocation and + * provides necessary resource estimations. You can also use + * {@link SorobanDataBuilder} to construct complicated combinations of + * parameters without mucking with XDR directly. **Note:** For + * non-contract(non-Soroban) transactions, this has no effect. + */ +var TransactionBuilder = exports.TransactionBuilder = /*#__PURE__*/function () { + function TransactionBuilder(sourceAccount) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, TransactionBuilder); + if (!sourceAccount) { + throw new Error('must specify source account for the transaction'); + } + if (opts.fee === undefined) { + throw new Error('must specify fee for the transaction (in stroops)'); + } + this.source = sourceAccount; + this.operations = []; + this.baseFee = opts.fee; + this.timebounds = opts.timebounds ? _objectSpread({}, opts.timebounds) : null; + this.ledgerbounds = opts.ledgerbounds ? _objectSpread({}, opts.ledgerbounds) : null; + this.minAccountSequence = opts.minAccountSequence || null; + this.minAccountSequenceAge = opts.minAccountSequenceAge || null; + this.minAccountSequenceLedgerGap = opts.minAccountSequenceLedgerGap || null; + this.extraSigners = opts.extraSigners ? _toConsumableArray(opts.extraSigners) : null; + this.memo = opts.memo || _memo.Memo.none(); + this.networkPassphrase = opts.networkPassphrase || null; + this.sorobanData = opts.sorobanData ? new _sorobandata_builder.SorobanDataBuilder(opts.sorobanData).build() : null; + } + + /** + * Creates a builder instance using an existing {@link Transaction} as a + * template, ignoring any existing envelope signatures. + * + * Note that the sequence number WILL be cloned, so EITHER this transaction or + * the one it was cloned from will be valid. This is useful in situations + * where you are constructing a transaction in pieces and need to make + * adjustments as you go (for example, when filling out Soroban resource + * information). + * + * @param {Transaction} tx a "template" transaction to clone exactly + * @param {object} [opts] additional options to override the clone, e.g. + * {fee: '1000'} will override the existing base fee derived from `tx` (see + * the {@link TransactionBuilder} constructor for detailed options) + * + * @returns {TransactionBuilder} a "prepared" builder instance with the same + * configuration and operations as the given transaction + * + * @warning This does not clone the transaction's + * {@link xdr.SorobanTransactionData} (if applicable), use + * {@link SorobanDataBuilder} and {@link TransactionBuilder.setSorobanData} + * as needed, instead.. + * + * @todo This cannot clone {@link FeeBumpTransaction}s, yet. + */ + return _createClass(TransactionBuilder, [{ + key: "addOperation", + value: + /** + * Adds an operation to the transaction. + * + * @param {xdr.Operation} operation The xdr operation object, use {@link + * Operation} static methods. + * + * @returns {TransactionBuilder} + */ + function addOperation(operation) { + this.operations.push(operation); + return this; + } + + /** + * Adds an operation to the transaction at a specific index. + * + * @param {xdr.Operation} operation - The xdr operation object to add, use {@link Operation} static methods. + * @param {number} index - The index at which to insert the operation. + * + * @returns {TransactionBuilder} - The TransactionBuilder instance for method chaining. + */ + }, { + key: "addOperationAt", + value: function addOperationAt(operation, index) { + this.operations.splice(index, 0, operation); + return this; + } + + /** + * Removes the operations from the builder (useful when cloning). + * @returns {TransactionBuilder} this builder instance + */ + }, { + key: "clearOperations", + value: function clearOperations() { + this.operations = []; + return this; + } + + /** + * Removes the operation at the specified index from the transaction. + * + * @param {number} index - The index of the operation to remove. + * + * @returns {TransactionBuilder} The TransactionBuilder instance for method chaining. + */ + }, { + key: "clearOperationAt", + value: function clearOperationAt(index) { + this.operations.splice(index, 1); + return this; + } + + /** + * Adds a memo to the transaction. + * @param {Memo} memo {@link Memo} object + * @returns {TransactionBuilder} + */ + }, { + key: "addMemo", + value: function addMemo(memo) { + this.memo = memo; + return this; + } + + /** + * Sets a timeout precondition on the transaction. + * + * Because of the distributed nature of the Stellar network it is possible + * that the status of your transaction will be determined after a long time + * if the network is highly congested. If you want to be sure to receive the + * status of the transaction within a given period you should set the {@link + * TimeBounds} with `maxTime` on the transaction (this is what `setTimeout` + * does internally; if there's `minTime` set but no `maxTime` it will be + * added). + * + * A call to `TransactionBuilder.setTimeout` is **required** if Transaction + * does not have `max_time` set. If you don't want to set timeout, use + * `{@link TimeoutInfinite}`. In general you should set `{@link + * TimeoutInfinite}` only in smart contracts. + * + * Please note that Horizon may still return 504 Gateway Timeout + * error, even for short timeouts. In such case you need to resubmit the same + * transaction again without making any changes to receive a status. This + * method is using the machine system time (UTC), make sure it is set + * correctly. + * + * @param {number} timeoutSeconds Number of seconds the transaction is good. + * Can't be negative. If the value is {@link TimeoutInfinite}, the + * transaction is good indefinitely. + * + * @returns {TransactionBuilder} + * + * @see {@link TimeoutInfinite} + * @see https://developers.stellar.org/docs/tutorials/handling-errors/ + */ + }, { + key: "setTimeout", + value: function setTimeout(timeoutSeconds) { + if (this.timebounds !== null && this.timebounds.maxTime > 0) { + throw new Error('TimeBounds.max_time has been already set - setting timeout would overwrite it.'); + } + if (timeoutSeconds < 0) { + throw new Error('timeout cannot be negative'); + } + if (timeoutSeconds > 0) { + var timeoutTimestamp = Math.floor(Date.now() / 1000) + timeoutSeconds; + if (this.timebounds === null) { + this.timebounds = { + minTime: 0, + maxTime: timeoutTimestamp + }; + } else { + this.timebounds = { + minTime: this.timebounds.minTime, + maxTime: timeoutTimestamp + }; + } + } else { + this.timebounds = { + minTime: 0, + maxTime: 0 + }; + } + return this; + } + + /** + * If you want to prepare a transaction which will become valid at some point + * in the future, or be invalid after some time, you can set a timebounds + * precondition. Internally this will set the `minTime`, and `maxTime` + * preconditions. Conflicts with `setTimeout`, so use one or the other. + * + * @param {Date|number} minEpochOrDate Either a JS Date object, or a number + * of UNIX epoch seconds. The transaction is valid after this timestamp. + * Can't be negative. If the value is `0`, the transaction is valid + * immediately. + * @param {Date|number} maxEpochOrDate Either a JS Date object, or a number + * of UNIX epoch seconds. The transaction is valid until this timestamp. + * Can't be negative. If the value is `0`, the transaction is valid + * indefinitely. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setTimebounds", + value: function setTimebounds(minEpochOrDate, maxEpochOrDate) { + // Force it to a date type + if (typeof minEpochOrDate === 'number') { + minEpochOrDate = new Date(minEpochOrDate * 1000); + } + if (typeof maxEpochOrDate === 'number') { + maxEpochOrDate = new Date(maxEpochOrDate * 1000); + } + if (this.timebounds !== null) { + throw new Error('TimeBounds has been already set - setting timebounds would overwrite it.'); + } + + // Convert that date to the epoch seconds + var minTime = Math.floor(minEpochOrDate.valueOf() / 1000); + var maxTime = Math.floor(maxEpochOrDate.valueOf() / 1000); + if (minTime < 0) { + throw new Error('min_time cannot be negative'); + } + if (maxTime < 0) { + throw new Error('max_time cannot be negative'); + } + if (maxTime > 0 && minTime > maxTime) { + throw new Error('min_time cannot be greater than max_time'); + } + this.timebounds = { + minTime: minTime, + maxTime: maxTime + }; + return this; + } + + /** + * If you want to prepare a transaction which will only be valid within some + * range of ledgers, you can set a ledgerbounds precondition. + * Internally this will set the `minLedger` and `maxLedger` preconditions. + * + * @param {number} minLedger The minimum ledger this transaction is valid at + * or after. Cannot be negative. If the value is `0` (the default), the + * transaction is valid immediately. + * + * @param {number} maxLedger The maximum ledger this transaction is valid + * before. Cannot be negative. If the value is `0`, the transaction is + * valid indefinitely. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setLedgerbounds", + value: function setLedgerbounds(minLedger, maxLedger) { + if (this.ledgerbounds !== null) { + throw new Error('LedgerBounds has been already set - setting ledgerbounds would overwrite it.'); + } + if (minLedger < 0) { + throw new Error('min_ledger cannot be negative'); + } + if (maxLedger < 0) { + throw new Error('max_ledger cannot be negative'); + } + if (maxLedger > 0 && minLedger > maxLedger) { + throw new Error('min_ledger cannot be greater than max_ledger'); + } + this.ledgerbounds = { + minLedger: minLedger, + maxLedger: maxLedger + }; + return this; + } + + /** + * If you want to prepare a transaction which will be valid only while the + * account sequence number is + * + * minAccountSequence <= sourceAccountSequence < tx.seqNum + * + * Note that after execution the account's sequence number is always raised to + * `tx.seqNum`. Internally this will set the `minAccountSequence` + * precondition. + * + * @param {string} minAccountSequence The minimum source account sequence + * number this transaction is valid for. If the value is `0` (the + * default), the transaction is valid when `sourceAccount's sequence + * number == tx.seqNum- 1`. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequence", + value: function setMinAccountSequence(minAccountSequence) { + if (this.minAccountSequence !== null) { + throw new Error('min_account_sequence has been already set - setting min_account_sequence would overwrite it.'); + } + this.minAccountSequence = minAccountSequence; + return this; + } + + /** + * For the transaction to be valid, the current ledger time must be at least + * `minAccountSequenceAge` greater than sourceAccount's `sequenceTime`. + * Internally this will set the `minAccountSequenceAge` precondition. + * + * @param {number} durationInSeconds The minimum amount of time between + * source account sequence time and the ledger time when this transaction + * will become valid. If the value is `0`, the transaction is unrestricted + * by the account sequence age. Cannot be negative. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequenceAge", + value: function setMinAccountSequenceAge(durationInSeconds) { + if (typeof durationInSeconds !== 'number') { + throw new Error('min_account_sequence_age must be a number'); + } + if (this.minAccountSequenceAge !== null) { + throw new Error('min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.'); + } + if (durationInSeconds < 0) { + throw new Error('min_account_sequence_age cannot be negative'); + } + this.minAccountSequenceAge = durationInSeconds; + return this; + } + + /** + * For the transaction to be valid, the current ledger number must be at least + * `minAccountSequenceLedgerGap` greater than sourceAccount's ledger sequence. + * Internally this will set the `minAccountSequenceLedgerGap` precondition. + * + * @param {number} gap The minimum number of ledgers between source account + * sequence and the ledger number when this transaction will become valid. + * If the value is `0`, the transaction is unrestricted by the account + * sequence ledger. Cannot be negative. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequenceLedgerGap", + value: function setMinAccountSequenceLedgerGap(gap) { + if (this.minAccountSequenceLedgerGap !== null) { + throw new Error('min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.'); + } + if (gap < 0) { + throw new Error('min_account_sequence_ledger_gap cannot be negative'); + } + this.minAccountSequenceLedgerGap = gap; + return this; + } + + /** + * For the transaction to be valid, there must be a signature corresponding to + * every Signer in this array, even if the signature is not otherwise required + * by the sourceAccount or operations. Internally this will set the + * `extraSigners` precondition. + * + * @param {string[]} extraSigners required extra signers (as {@link StrKey}s) + * + * @returns {TransactionBuilder} + */ + }, { + key: "setExtraSigners", + value: function setExtraSigners(extraSigners) { + if (!Array.isArray(extraSigners)) { + throw new Error('extra_signers must be an array of strings.'); + } + if (this.extraSigners !== null) { + throw new Error('extra_signers has been already set - setting extra_signers would overwrite it.'); + } + if (extraSigners.length > 2) { + throw new Error('extra_signers cannot be longer than 2 elements.'); + } + this.extraSigners = _toConsumableArray(extraSigners); + return this; + } + + /** + * Set network nassphrase for the Transaction that will be built. + * + * @param {string} networkPassphrase passphrase of the target Stellar + * network (e.g. "Public Global Stellar Network ; September 2015"). + * + * @returns {TransactionBuilder} + */ + }, { + key: "setNetworkPassphrase", + value: function setNetworkPassphrase(networkPassphrase) { + this.networkPassphrase = networkPassphrase; + return this; + } + + /** + * Sets the transaction's internal Soroban transaction data (resources, + * footprint, etc.). + * + * For non-contract(non-Soroban) transactions, this setting has no effect. In + * the case of Soroban transactions, this is either an instance of + * {@link xdr.SorobanTransactionData} or a base64-encoded string of said + * structure. This is usually obtained from the simulation response based on a + * transaction with a Soroban operation (e.g. + * {@link Operation.invokeHostFunction}, providing necessary resource + * and storage footprint estimations for contract invocation. + * + * @param {xdr.SorobanTransactionData | string} sorobanData the + * {@link xdr.SorobanTransactionData} as a raw xdr object or a base64 + * string to be decoded + * + * @returns {TransactionBuilder} + * @see {SorobanDataBuilder} + */ + }, { + key: "setSorobanData", + value: function setSorobanData(sorobanData) { + this.sorobanData = new _sorobandata_builder.SorobanDataBuilder(sorobanData).build(); + return this; + } + + /** + * This will build the transaction. + * It will also increment the source account's sequence number by 1. + * @returns {Transaction} This method will return the built {@link Transaction}. + */ + }, { + key: "build", + value: function build() { + var sequenceNumber = new _bignumber["default"](this.source.sequenceNumber()).plus(1); + var fee = new _bignumber["default"](this.baseFee).times(this.operations.length).toNumber(); + var attrs = { + fee: fee, + seqNum: _xdr["default"].SequenceNumber.fromString(sequenceNumber.toString()), + memo: this.memo ? this.memo.toXDRObject() : null + }; + if (this.timebounds === null || typeof this.timebounds.minTime === 'undefined' || typeof this.timebounds.maxTime === 'undefined') { + throw new Error('TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).'); + } + if (isValidDate(this.timebounds.minTime)) { + this.timebounds.minTime = this.timebounds.minTime.getTime() / 1000; + } + if (isValidDate(this.timebounds.maxTime)) { + this.timebounds.maxTime = this.timebounds.maxTime.getTime() / 1000; + } + this.timebounds.minTime = _jsXdr.UnsignedHyper.fromString(this.timebounds.minTime.toString()); + this.timebounds.maxTime = _jsXdr.UnsignedHyper.fromString(this.timebounds.maxTime.toString()); + var timeBounds = new _xdr["default"].TimeBounds(this.timebounds); + if (this.hasV2Preconditions()) { + var ledgerBounds = null; + if (this.ledgerbounds !== null) { + ledgerBounds = new _xdr["default"].LedgerBounds(this.ledgerbounds); + } + var minSeqNum = this.minAccountSequence || '0'; + minSeqNum = _xdr["default"].SequenceNumber.fromString(minSeqNum); + var minSeqAge = _jsXdr.UnsignedHyper.fromString(this.minAccountSequenceAge !== null ? this.minAccountSequenceAge.toString() : '0'); + var minSeqLedgerGap = this.minAccountSequenceLedgerGap || 0; + var extraSigners = this.extraSigners !== null ? this.extraSigners.map(_signerkey.SignerKey.decodeAddress) : []; + attrs.cond = _xdr["default"].Preconditions.precondV2(new _xdr["default"].PreconditionsV2({ + timeBounds: timeBounds, + ledgerBounds: ledgerBounds, + minSeqNum: minSeqNum, + minSeqAge: minSeqAge, + minSeqLedgerGap: minSeqLedgerGap, + extraSigners: extraSigners + })); + } else { + attrs.cond = _xdr["default"].Preconditions.precondTime(timeBounds); + } + attrs.sourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(this.source.accountId()); + + // TODO - remove this workaround for TransactionExt ts constructor + // and use the typescript generated static factory method once fixed + // https://github.com/stellar/dts-xdr/issues/5 + if (this.sorobanData) { + // @ts-ignore + attrs.ext = new _xdr["default"].TransactionExt(1, this.sorobanData); + } else { + // @ts-ignore + attrs.ext = new _xdr["default"].TransactionExt(0, _xdr["default"].Void); + } + var xtx = new _xdr["default"].Transaction(attrs); + xtx.operations(this.operations); + var txEnvelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: xtx + })); + var tx = new _transaction.Transaction(txEnvelope, this.networkPassphrase); + this.source.incrementSequenceNumber(); + return tx; + } + }, { + key: "hasV2Preconditions", + value: function hasV2Preconditions() { + return this.ledgerbounds !== null || this.minAccountSequence !== null || this.minAccountSequenceAge !== null || this.minAccountSequenceLedgerGap !== null || this.extraSigners !== null && this.extraSigners.length > 0; + } + + /** + * Builds a {@link FeeBumpTransaction}, enabling you to resubmit an existing + * transaction with a higher fee. + * + * @param {Keypair|string} feeSource - account paying for the transaction, + * in the form of either a Keypair (only the public key is used) or + * an account ID (in G... or M... form, but refer to `withMuxing`) + * @param {string} baseFee - max fee willing to pay per operation + * in inner transaction (**in stroops**) + * @param {Transaction} innerTx - {@link Transaction} to be bumped by + * the fee bump transaction + * @param {string} networkPassphrase - passphrase of the target + * Stellar network (e.g. "Public Global Stellar Network ; September 2015", + * see {@link Networks}) + * + * @todo Alongside the next major version bump, this type signature can be + * changed to be less awkward: accept a MuxedAccount as the `feeSource` + * rather than a keypair or string. + * + * @note Your fee-bump amount should be >= 10x the original fee. + * @see https://developers.stellar.org/docs/glossary/fee-bumps/#replace-by-fee + * + * @returns {FeeBumpTransaction} + */ + }], [{ + key: "cloneFrom", + value: function cloneFrom(tx) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (!(tx instanceof _transaction.Transaction)) { + throw new TypeError("expected a 'Transaction', got: ".concat(tx)); + } + var sequenceNum = (BigInt(tx.sequence) - 1n).toString(); + var source; + // rebuild the source account based on the strkey + if (_strkey.StrKey.isValidMed25519PublicKey(tx.source)) { + source = _muxed_account.MuxedAccount.fromAddress(tx.source, sequenceNum); + } else if (_strkey.StrKey.isValidEd25519PublicKey(tx.source)) { + source = new _account.Account(tx.source, sequenceNum); + } else { + throw new TypeError("unsupported tx source account: ".concat(tx.source)); + } + + // the initial fee passed to the builder gets scaled up based on the number + // of operations at the end, so we have to down-scale first + var unscaledFee = parseInt(tx.fee, 10) / tx.operations.length; + var builder = new TransactionBuilder(source, _objectSpread({ + fee: (unscaledFee || BASE_FEE).toString(), + memo: tx.memo, + networkPassphrase: tx.networkPassphrase, + timebounds: tx.timeBounds, + ledgerbounds: tx.ledgerBounds, + minAccountSequence: tx.minAccountSequence, + minAccountSequenceAge: tx.minAccountSequenceAge, + minAccountSequenceLedgerGap: tx.minAccountSequenceLedgerGap, + extraSigners: tx.extraSigners + }, opts)); + tx._tx.operations().forEach(function (op) { + return builder.addOperation(op); + }); + return builder; + } + }, { + key: "buildFeeBumpTransaction", + value: function buildFeeBumpTransaction(feeSource, baseFee, innerTx, networkPassphrase) { + var innerOps = innerTx.operations.length; + var innerBaseFeeRate = new _bignumber["default"](innerTx.fee).div(innerOps); + var base = new _bignumber["default"](baseFee); + + // The fee rate for fee bump is at least the fee rate of the inner transaction + if (base.lt(innerBaseFeeRate)) { + throw new Error("Invalid baseFee, it should be at least ".concat(innerBaseFeeRate, " stroops.")); + } + var minBaseFee = new _bignumber["default"](BASE_FEE); + + // The fee rate is at least the minimum fee + if (base.lt(minBaseFee)) { + throw new Error("Invalid baseFee, it should be at least ".concat(minBaseFee, " stroops.")); + } + var innerTxEnvelope = innerTx.toEnvelope(); + if (innerTxEnvelope["switch"]() === _xdr["default"].EnvelopeType.envelopeTypeTxV0()) { + var v0Tx = innerTxEnvelope.v0().tx(); + var v1Tx = new _xdr["default"].Transaction({ + sourceAccount: new _xdr["default"].MuxedAccount.keyTypeEd25519(v0Tx.sourceAccountEd25519()), + fee: v0Tx.fee(), + seqNum: v0Tx.seqNum(), + cond: _xdr["default"].Preconditions.precondTime(v0Tx.timeBounds()), + memo: v0Tx.memo(), + operations: v0Tx.operations(), + ext: new _xdr["default"].TransactionExt(0) + }); + innerTxEnvelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: v1Tx, + signatures: innerTxEnvelope.v0().signatures() + })); + } + var feeSourceAccount; + if (typeof feeSource === 'string') { + feeSourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(feeSource); + } else { + feeSourceAccount = feeSource.xdrMuxedAccount(); + } + var tx = new _xdr["default"].FeeBumpTransaction({ + feeSource: feeSourceAccount, + fee: _xdr["default"].Int64.fromString(base.times(innerOps + 1).toString()), + innerTx: _xdr["default"].FeeBumpTransactionInnerTx.envelopeTypeTx(innerTxEnvelope.v1()), + ext: new _xdr["default"].FeeBumpTransactionExt(0) + }); + var feeBumpTxEnvelope = new _xdr["default"].FeeBumpTransactionEnvelope({ + tx: tx, + signatures: [] + }); + var envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTxFeeBump(feeBumpTxEnvelope); + return new _fee_bump_transaction.FeeBumpTransaction(envelope, networkPassphrase); + } + + /** + * Build a {@link Transaction} or {@link FeeBumpTransaction} from an + * xdr.TransactionEnvelope. + * + * @param {string|xdr.TransactionEnvelope} envelope - The transaction envelope + * object or base64 encoded string. + * @param {string} networkPassphrase - The network passphrase of the target + * Stellar network (e.g. "Public Global Stellar Network ; September + * 2015"), see {@link Networks}. + * + * @returns {Transaction|FeeBumpTransaction} + */ + }, { + key: "fromXDR", + value: function fromXDR(envelope, networkPassphrase) { + if (typeof envelope === 'string') { + envelope = _xdr["default"].TransactionEnvelope.fromXDR(envelope, 'base64'); + } + if (envelope["switch"]() === _xdr["default"].EnvelopeType.envelopeTypeTxFeeBump()) { + return new _fee_bump_transaction.FeeBumpTransaction(envelope, networkPassphrase); + } + return new _transaction.Transaction(envelope, networkPassphrase); + } + }]); +}(); +/** + * Checks whether a provided object is a valid Date. + * @argument {Date} d date object + * @returns {boolean} + */ +function isValidDate(d) { + // isnan is okay here because it correctly checks for invalid date objects + // eslint-disable-next-line no-restricted-globals + return d instanceof Date && !isNaN(d); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/util/bignumber.js b/node_modules/@stellar/stellar-base/lib/util/bignumber.js new file mode 100644 index 000000000..8654ac4b6 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/util/bignumber.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _bignumber = _interopRequireDefault(require("bignumber.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var BigNumber = _bignumber["default"].clone(); +BigNumber.DEBUG = true; // gives us exceptions on bad constructor values +var _default = exports["default"] = BigNumber; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/util/checksum.js b/node_modules/@stellar/stellar-base/lib/util/checksum.js new file mode 100644 index 000000000..2362ba3f0 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/util/checksum.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.verifyChecksum = verifyChecksum; +function verifyChecksum(expected, actual) { + if (expected.length !== actual.length) { + return false; + } + if (expected.length === 0) { + return true; + } + for (var i = 0; i < expected.length; i += 1) { + if (expected[i] !== actual[i]) { + return false; + } + } + return true; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/util/continued_fraction.js b/node_modules/@stellar/stellar-base/lib/util/continued_fraction.js new file mode 100644 index 000000000..d8a0666c1 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/util/continued_fraction.js @@ -0,0 +1,58 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.best_r = best_r; +var _bignumber = _interopRequireDefault(require("./bignumber")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +// eslint-disable-next-line no-bitwise +var MAX_INT = (1 << 31 >>> 0) - 1; + +/** + * Calculates and returns the best rational approximation of the given real number. + * @private + * @param {string|number|BigNumber} rawNumber Real number + * @throws Error Throws `Error` when the best rational approximation cannot be found. + * @returns {array} first element is n (numerator), second element is d (denominator) + */ +function best_r(rawNumber) { + var number = new _bignumber["default"](rawNumber); + var a; + var f; + var fractions = [[new _bignumber["default"](0), new _bignumber["default"](1)], [new _bignumber["default"](1), new _bignumber["default"](0)]]; + var i = 2; + + // eslint-disable-next-line no-constant-condition + while (true) { + if (number.gt(MAX_INT)) { + break; + } + a = number.integerValue(_bignumber["default"].ROUND_FLOOR); + f = number.minus(a); + var h = a.times(fractions[i - 1][0]).plus(fractions[i - 2][0]); + var k = a.times(fractions[i - 1][1]).plus(fractions[i - 2][1]); + if (h.gt(MAX_INT) || k.gt(MAX_INT)) { + break; + } + fractions.push([h, k]); + if (f.eq(0)) { + break; + } + number = new _bignumber["default"](1).div(f); + i += 1; + } + var _fractions = _slicedToArray(fractions[fractions.length - 1], 2), + n = _fractions[0], + d = _fractions[1]; + if (n.isZero() || d.isZero()) { + throw new Error("Couldn't find approximation"); + } + return [n.toNumber(), d.toNumber()]; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/util/decode_encode_muxed_account.js b/node_modules/@stellar/stellar-base/lib/util/decode_encode_muxed_account.js new file mode 100644 index 000000000..671d62d13 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/util/decode_encode_muxed_account.js @@ -0,0 +1,116 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.decodeAddressToMuxedAccount = decodeAddressToMuxedAccount; +exports.encodeMuxedAccount = encodeMuxedAccount; +exports.encodeMuxedAccountToAddress = encodeMuxedAccountToAddress; +exports.extractBaseAddress = extractBaseAddress; +var _xdr = _interopRequireDefault(require("../xdr")); +var _strkey = require("../strkey"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Converts a Stellar address (in G... or M... form) to an `xdr.MuxedAccount` + * structure, using the ed25519 representation when possible. + * + * This supports full muxed accounts, where an `M...` address will resolve to + * both its underlying `G...` address and an integer ID. + * + * @param {string} address G... or M... address to encode into XDR + * @returns {xdr.MuxedAccount} a muxed account object for this address string + */ +function decodeAddressToMuxedAccount(address) { + if (_strkey.StrKey.isValidMed25519PublicKey(address)) { + return _decodeAddressFullyToMuxedAccount(address); + } + return _xdr["default"].MuxedAccount.keyTypeEd25519(_strkey.StrKey.decodeEd25519PublicKey(address)); +} + +/** + * Converts an xdr.MuxedAccount to its StrKey representation. + * + * This returns its "M..." string representation if there is a muxing ID within + * the object and returns the "G..." representation otherwise. + * + * @param {xdr.MuxedAccount} muxedAccount Raw account to stringify + * @returns {string} Stringified G... (corresponding to the underlying pubkey) + * or M... address (corresponding to both the key and the muxed ID) + * + * @see https://stellar.org/protocol/sep-23 + */ +function encodeMuxedAccountToAddress(muxedAccount) { + if (muxedAccount["switch"]().value === _xdr["default"].CryptoKeyType.keyTypeMuxedEd25519().value) { + return _encodeMuxedAccountFullyToAddress(muxedAccount); + } + return _strkey.StrKey.encodeEd25519PublicKey(muxedAccount.ed25519()); +} + +/** + * Transform a Stellar address (G...) and an ID into its XDR representation. + * + * @param {string} address - a Stellar G... address + * @param {string} id - a Uint64 ID represented as a string + * + * @return {xdr.MuxedAccount} - XDR representation of the above muxed account + */ +function encodeMuxedAccount(address, id) { + if (!_strkey.StrKey.isValidEd25519PublicKey(address)) { + throw new Error('address should be a Stellar account ID (G...)'); + } + if (typeof id !== 'string') { + throw new Error('id should be a string representing a number (uint64)'); + } + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromString(id), + ed25519: _strkey.StrKey.decodeEd25519PublicKey(address) + })); +} + +/** + * Extracts the underlying base (G...) address from an M-address. + * @param {string} address an account address (either M... or G...) + * @return {string} a Stellar public key address (G...) + */ +function extractBaseAddress(address) { + if (_strkey.StrKey.isValidEd25519PublicKey(address)) { + return address; + } + if (!_strkey.StrKey.isValidMed25519PublicKey(address)) { + throw new TypeError("expected muxed account (M...), got ".concat(address)); + } + var muxedAccount = decodeAddressToMuxedAccount(address); + return _strkey.StrKey.encodeEd25519PublicKey(muxedAccount.med25519().ed25519()); +} + +// Decodes an "M..." account ID into its MuxedAccount object representation. +function _decodeAddressFullyToMuxedAccount(address) { + var rawBytes = _strkey.StrKey.decodeMed25519PublicKey(address); + + // Decoding M... addresses cannot be done through a simple + // MuxedAccountMed25519.fromXDR() call, because the definition is: + // + // constructor(attributes: { id: Uint64; ed25519: Buffer }); + // + // Note the ID is the first attribute. However, the ID comes *last* in the + // stringified (base32-encoded) address itself (it's the last 8-byte suffix). + // The `fromXDR()` method interprets bytes in order, so we need to parse out + // the raw binary into its requisite parts, i.e. use the MuxedAccountMed25519 + // constructor directly. + // + // Refer to https://github.com/stellar/go/blob/master/xdr/muxed_account.go#L26 + // for the Golang implementation of the M... parsing. + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromXDR(rawBytes.subarray(-8)), + ed25519: rawBytes.subarray(0, -8) + })); +} + +// Converts an xdr.MuxedAccount into its *true* "M..." string representation. +function _encodeMuxedAccountFullyToAddress(muxedAccount) { + if (muxedAccount["switch"]() === _xdr["default"].CryptoKeyType.keyTypeEd25519()) { + return encodeMuxedAccountToAddress(muxedAccount); + } + var muxed = muxedAccount.med25519(); + return _strkey.StrKey.encodeMed25519PublicKey(Buffer.concat([muxed.ed25519(), muxed.id().toXDR('raw')])); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/util/util.js b/node_modules/@stellar/stellar-base/lib/util/util.js new file mode 100644 index 000000000..d399b35c8 --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/util/util.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.trimEnd = void 0; +var trimEnd = exports.trimEnd = function trimEnd(input, _char) { + var isNumber = typeof input === 'number'; + var str = String(input); + while (str.endsWith(_char)) { + str = str.slice(0, -1); + } + return isNumber ? Number(str) : str; +}; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/lib/xdr.js b/node_modules/@stellar/stellar-base/lib/xdr.js new file mode 100644 index 000000000..9d55fc22d --- /dev/null +++ b/node_modules/@stellar/stellar-base/lib/xdr.js @@ -0,0 +1,9 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _curr_generated = _interopRequireDefault(require("./generated/curr_generated")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var _default = exports["default"] = _curr_generated["default"]; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-base/package.json b/node_modules/@stellar/stellar-base/package.json new file mode 100644 index 000000000..fc6f128c5 --- /dev/null +++ b/node_modules/@stellar/stellar-base/package.json @@ -0,0 +1,133 @@ +{ + "name": "@stellar/stellar-base", + "version": "13.0.1", + "description": "Low-level support library for the Stellar network.", + "main": "./lib/index.js", + "browser": { + "main": "./dist/stellar-base.min.js", + "sodium-native": false + }, + "types": "./types/index.d.ts", + "scripts": { + "build": "yarn build:node && yarn build:browser", + "build:node": "babel --out-dir ./lib/ ./src/", + "build:browser": "webpack -c ./config/webpack.config.browser.js", + "build:node:prod": "cross-env NODE_ENV=production yarn build", + "build:browser:prod": "cross-env NODE_ENV=production yarn build:browser", + "build:prod": "cross-env NODE_ENV=production yarn build", + "test": "yarn build && yarn test:node && yarn test:browser", + "test:node": "yarn _nyc mocha", + "test:browser": "karma start ./config/karma.conf.js", + "docs": "jsdoc -c ./config/.jsdoc.json --verbose", + "lint": "eslint -c ./config/.eslintrc.js src/ && dtslint --localTs node_modules/typescript/lib types/", + "preversion": "yarn clean && yarn fmt && yarn lint && yarn build:prod && yarn test", + "fmt": "prettier --config ./config/prettier.config.js --ignore-path ./config/.prettierignore --write './**/*.js'", + "prepare": "yarn build:prod", + "clean": "rm -rf lib/ dist/ coverage/ .nyc_output/", + "_nyc": "nyc --nycrc-path ./config/.nycrc" + }, + "mocha": { + "require": [ + "@babel/register", + "./test/test-helper.js" + ], + "reporter": "dot", + "recursive": true, + "timeout": 5000 + }, + "nyc": { + "sourceMap": false, + "instrument": false, + "reporter": "text-summary" + }, + "files": [ + "/dist/*.js", + "/lib/**/*.js", + "/types/*.d.ts" + ], + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "**/*.{js,json}": [ + "yarn fmt", + "yarn lint" + ] + }, + "repository": { + "type": "git", + "url": "https://github.com/stellar/js-stellar-base.git" + }, + "keywords": [ + "stellar" + ], + "author": "Stellar Development Foundation ", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/stellar/js-stellar-base/issues" + }, + "homepage": "https://github.com/stellar/js-stellar-base", + "devDependencies": { + "@babel/cli": "^7.25.9", + "@babel/core": "^7.26.0", + "@babel/eslint-parser": "^7.25.9", + "@babel/eslint-plugin": "^7.25.9", + "@babel/preset-env": "^7.26.0", + "@babel/register": "^7.25.9", + "@definitelytyped/dtslint": "^0.0.182", + "@istanbuljs/nyc-config-babel": "3.0.0", + "@types/node": "^20.14.11", + "@typescript-eslint/parser": "^6.20.0", + "babel-loader": "^9.2.1", + "babel-plugin-istanbul": "^6.1.1", + "chai": "^4.3.10", + "chai-as-promised": "^7.1.2", + "cross-env": "^7.0.3", + "eslint": "^8.57.0", + "eslint-config-airbnb-base": "^15.0.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-import": "^2.31.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-prefer-import": "^0.0.1", + "eslint-plugin-prettier": "^5.2.1", + "eslint-webpack-plugin": "^4.2.0", + "ghooks": "^2.0.4", + "husky": "^8.0.3", + "jsdoc": "^4.0.4", + "karma": "^6.4.4", + "karma-chrome-launcher": "^3.1.0", + "karma-coverage": "^2.2.1", + "karma-firefox-launcher": "^2.1.3", + "karma-mocha": "^2.0.0", + "karma-sinon-chai": "^2.0.2", + "karma-webpack": "^5.0.1", + "lint-staged": "^15.2.10", + "minami": "^1.1.1", + "mocha": "^10.8.2", + "node-polyfill-webpack-plugin": "^3.0.0", + "nyc": "^15.1.0", + "prettier": "^3.3.3", + "randombytes": "^2.1.0", + "sinon": "^16.1.0", + "sinon-chai": "^3.7.0", + "taffydb": "^2.7.3", + "terser-webpack-plugin": "^5.3.10", + "ts-node": "^10.9.2", + "typescript": "^5.6.3", + "webpack": "^5.96.1", + "webpack-cli": "^5.1.1" + }, + "dependencies": { + "@stellar/js-xdr": "^3.1.2", + "base32.js": "^0.1.0", + "bignumber.js": "^9.1.2", + "buffer": "^6.0.3", + "sha.js": "^2.3.6", + "tweetnacl": "^1.0.3" + }, + "optionalDependencies": { + "sodium-native": "^4.3.0" + } +} diff --git a/node_modules/@stellar/stellar-base/types/curr.d.ts b/node_modules/@stellar/stellar-base/types/curr.d.ts new file mode 100644 index 000000000..beafaa43e --- /dev/null +++ b/node_modules/@stellar/stellar-base/types/curr.d.ts @@ -0,0 +1,15714 @@ +// Automatically generated by xdrgen on 2024-09-12T11:09:00-08:00 +// DO NOT EDIT or your changes may be overwritten +import { Operation } from './index'; + +export {}; + +// Hidden namespace as hack to work around name collision. +declare namespace xdrHidden { + // tslint:disable-line:strict-export-declare-modifiers + class Operation2 { + constructor(attributes: { + sourceAccount: null | xdr.MuxedAccount; + body: xdr.OperationBody; + }); + + sourceAccount(value?: null | xdr.MuxedAccount): null | xdr.MuxedAccount; + + body(value?: xdr.OperationBody): xdr.OperationBody; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): xdr.Operation; + + static write(value: xdr.Operation, io: Buffer): void; + + static isValid(value: xdr.Operation): boolean; + + static toXDR(value: xdr.Operation): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): xdr.Operation; + + static fromXDR(input: string, format: 'hex' | 'base64'): xdr.Operation; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } +} + +export namespace xdr { + export import Operation = xdrHidden.Operation2; // tslint:disable-line:strict-export-declare-modifiers + + type Hash = Opaque[]; // workaround, cause unknown + + interface SignedInt { + readonly MAX_VALUE: 2147483647; + readonly MIN_VALUE: -2147483648; + read(io: Buffer): number; + write(value: number, io: Buffer): void; + isValid(value: number): boolean; + toXDR(value: number): Buffer; + fromXDR(input: Buffer, format?: 'raw'): number; + fromXDR(input: string, format: 'hex' | 'base64'): number; + validateXDR(input: Buffer, format?: 'raw'): boolean; + validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + interface UnsignedInt { + readonly MAX_VALUE: 4294967295; + readonly MIN_VALUE: 0; + read(io: Buffer): number; + write(value: number, io: Buffer): void; + isValid(value: number): boolean; + toXDR(value: number): Buffer; + fromXDR(input: Buffer, format?: 'raw'): number; + fromXDR(input: string, format: 'hex' | 'base64'): number; + validateXDR(input: Buffer, format?: 'raw'): boolean; + validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + interface Bool { + read(io: Buffer): boolean; + write(value: boolean, io: Buffer): void; + isValid(value: boolean): boolean; + toXDR(value: boolean): Buffer; + fromXDR(input: Buffer, format?: 'raw'): boolean; + fromXDR(input: string, format: 'hex' | 'base64'): boolean; + validateXDR(input: Buffer, format?: 'raw'): boolean; + validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Hyper { + low: number; + + high: number; + + unsigned: boolean; + + constructor( + values: string | bigint | number | Array, + ); + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static toXDR(value: Hyper): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Hyper; + + static fromXDR(input: string, format: 'hex' | 'base64'): Hyper; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + + static readonly MAX_VALUE: Hyper; + + static readonly MIN_VALUE: Hyper; + + static read(io: Buffer): Hyper; + + static write(value: Hyper, io: Buffer): void; + + static fromString(input: string): Hyper; + + static fromBytes(low: number, high: number): Hyper; + + static isValid(value: Hyper): boolean; + + toBigInt(): bigint; + + toString(): string; + } + + class UnsignedHyper { + low: number; + + high: number; + + unsigned: boolean; + + constructor( + values: string | bigint | number | Array, + ); + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static toXDR(value: UnsignedHyper): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): UnsignedHyper; + + static fromXDR(input: string, format: 'hex' | 'base64'): UnsignedHyper; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + + static readonly MAX_VALUE: UnsignedHyper; + + static readonly MIN_VALUE: UnsignedHyper; + + static read(io: Buffer): UnsignedHyper; + + static write(value: UnsignedHyper, io: Buffer): void; + + static fromString(input: string): UnsignedHyper; + + static fromBytes(low: number, high: number): UnsignedHyper; + + static isValid(value: UnsignedHyper): boolean; + + toBigInt(): bigint; + + toString(): string; + } + + class XDRString { + constructor(maxLength: 4294967295); + + read(io: Buffer): Buffer; + + readString(io: Buffer): string; + + write(value: string | Buffer, io: Buffer): void; + + isValid(value: string | number[] | Buffer): boolean; + + toXDR(value: string | Buffer): Buffer; + + fromXDR(input: Buffer, format?: 'raw'): Buffer; + + fromXDR(input: string, format: 'hex' | 'base64'): Buffer; + + validateXDR(input: Buffer, format?: 'raw'): boolean; + + validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class XDRArray { + read(io: Buffer): Buffer; + + write(value: T[], io: Buffer): void; + + isValid(value: T[]): boolean; + + toXDR(value: T[]): Buffer; + + fromXDR(input: Buffer, format?: 'raw'): T[]; + + fromXDR(input: string, format: 'hex' | 'base64'): T[]; + + validateXDR(input: Buffer, format?: 'raw'): boolean; + + validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Opaque { + constructor(length: number); + + read(io: Buffer): Buffer; + + write(value: Buffer, io: Buffer): void; + + isValid(value: Buffer): boolean; + + toXDR(value: Buffer): Buffer; + + fromXDR(input: Buffer, format?: 'raw'): Buffer; + + fromXDR(input: string, format: 'hex' | 'base64'): Buffer; + + validateXDR(input: Buffer, format?: 'raw'): boolean; + + validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class VarOpaque extends Opaque {} + + class Option { + constructor(childType: { + read(io: any): any; + write(value: any, io: Buffer): void; + isValid(value: any): boolean; + }); + + read(io: Buffer): any; + + write(value: any, io: Buffer): void; + + isValid(value: any): boolean; + + toXDR(value: any): Buffer; + + fromXDR(input: Buffer, format?: 'raw'): any; + + fromXDR(input: string, format: 'hex' | 'base64'): any; + + validateXDR(input: Buffer, format?: 'raw'): boolean; + + validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpStatementType { + readonly name: + | 'scpStPrepare' + | 'scpStConfirm' + | 'scpStExternalize' + | 'scpStNominate'; + + readonly value: 0 | 1 | 2 | 3; + + static scpStPrepare(): ScpStatementType; + + static scpStConfirm(): ScpStatementType; + + static scpStExternalize(): ScpStatementType; + + static scpStNominate(): ScpStatementType; + } + + class AssetType { + readonly name: + | 'assetTypeNative' + | 'assetTypeCreditAlphanum4' + | 'assetTypeCreditAlphanum12' + | 'assetTypePoolShare'; + + readonly value: 0 | 1 | 2 | 3; + + static assetTypeNative(): AssetType; + + static assetTypeCreditAlphanum4(): AssetType; + + static assetTypeCreditAlphanum12(): AssetType; + + static assetTypePoolShare(): AssetType; + } + + class ThresholdIndices { + readonly name: + | 'thresholdMasterWeight' + | 'thresholdLow' + | 'thresholdMed' + | 'thresholdHigh'; + + readonly value: 0 | 1 | 2 | 3; + + static thresholdMasterWeight(): ThresholdIndices; + + static thresholdLow(): ThresholdIndices; + + static thresholdMed(): ThresholdIndices; + + static thresholdHigh(): ThresholdIndices; + } + + class LedgerEntryType { + readonly name: + | 'account' + | 'trustline' + | 'offer' + | 'data' + | 'claimableBalance' + | 'liquidityPool' + | 'contractData' + | 'contractCode' + | 'configSetting' + | 'ttl'; + + readonly value: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + + static account(): LedgerEntryType; + + static trustline(): LedgerEntryType; + + static offer(): LedgerEntryType; + + static data(): LedgerEntryType; + + static claimableBalance(): LedgerEntryType; + + static liquidityPool(): LedgerEntryType; + + static contractData(): LedgerEntryType; + + static contractCode(): LedgerEntryType; + + static configSetting(): LedgerEntryType; + + static ttl(): LedgerEntryType; + } + + class AccountFlags { + readonly name: + | 'authRequiredFlag' + | 'authRevocableFlag' + | 'authImmutableFlag' + | 'authClawbackEnabledFlag'; + + readonly value: 1 | 2 | 4 | 8; + + static authRequiredFlag(): AccountFlags; + + static authRevocableFlag(): AccountFlags; + + static authImmutableFlag(): AccountFlags; + + static authClawbackEnabledFlag(): AccountFlags; + } + + class TrustLineFlags { + readonly name: + | 'authorizedFlag' + | 'authorizedToMaintainLiabilitiesFlag' + | 'trustlineClawbackEnabledFlag'; + + readonly value: 1 | 2 | 4; + + static authorizedFlag(): TrustLineFlags; + + static authorizedToMaintainLiabilitiesFlag(): TrustLineFlags; + + static trustlineClawbackEnabledFlag(): TrustLineFlags; + } + + class LiquidityPoolType { + readonly name: 'liquidityPoolConstantProduct'; + + readonly value: 0; + + static liquidityPoolConstantProduct(): LiquidityPoolType; + } + + class OfferEntryFlags { + readonly name: 'passiveFlag'; + + readonly value: 1; + + static passiveFlag(): OfferEntryFlags; + } + + class ClaimPredicateType { + readonly name: + | 'claimPredicateUnconditional' + | 'claimPredicateAnd' + | 'claimPredicateOr' + | 'claimPredicateNot' + | 'claimPredicateBeforeAbsoluteTime' + | 'claimPredicateBeforeRelativeTime'; + + readonly value: 0 | 1 | 2 | 3 | 4 | 5; + + static claimPredicateUnconditional(): ClaimPredicateType; + + static claimPredicateAnd(): ClaimPredicateType; + + static claimPredicateOr(): ClaimPredicateType; + + static claimPredicateNot(): ClaimPredicateType; + + static claimPredicateBeforeAbsoluteTime(): ClaimPredicateType; + + static claimPredicateBeforeRelativeTime(): ClaimPredicateType; + } + + class ClaimantType { + readonly name: 'claimantTypeV0'; + + readonly value: 0; + + static claimantTypeV0(): ClaimantType; + } + + class ClaimableBalanceIdType { + readonly name: 'claimableBalanceIdTypeV0'; + + readonly value: 0; + + static claimableBalanceIdTypeV0(): ClaimableBalanceIdType; + } + + class ClaimableBalanceFlags { + readonly name: 'claimableBalanceClawbackEnabledFlag'; + + readonly value: 1; + + static claimableBalanceClawbackEnabledFlag(): ClaimableBalanceFlags; + } + + class ContractDataDurability { + readonly name: 'temporary' | 'persistent'; + + readonly value: 0 | 1; + + static temporary(): ContractDataDurability; + + static persistent(): ContractDataDurability; + } + + class EnvelopeType { + readonly name: + | 'envelopeTypeTxV0' + | 'envelopeTypeScp' + | 'envelopeTypeTx' + | 'envelopeTypeAuth' + | 'envelopeTypeScpvalue' + | 'envelopeTypeTxFeeBump' + | 'envelopeTypeOpId' + | 'envelopeTypePoolRevokeOpId' + | 'envelopeTypeContractId' + | 'envelopeTypeSorobanAuthorization'; + + readonly value: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + + static envelopeTypeTxV0(): EnvelopeType; + + static envelopeTypeScp(): EnvelopeType; + + static envelopeTypeTx(): EnvelopeType; + + static envelopeTypeAuth(): EnvelopeType; + + static envelopeTypeScpvalue(): EnvelopeType; + + static envelopeTypeTxFeeBump(): EnvelopeType; + + static envelopeTypeOpId(): EnvelopeType; + + static envelopeTypePoolRevokeOpId(): EnvelopeType; + + static envelopeTypeContractId(): EnvelopeType; + + static envelopeTypeSorobanAuthorization(): EnvelopeType; + } + + class BucketListType { + readonly name: 'live' | 'hotArchive' | 'coldArchive'; + + readonly value: 0 | 1 | 2; + + static live(): BucketListType; + + static hotArchive(): BucketListType; + + static coldArchive(): BucketListType; + } + + class BucketEntryType { + readonly name: 'metaentry' | 'liveentry' | 'deadentry' | 'initentry'; + + readonly value: -1 | 0 | 1 | 2; + + static metaentry(): BucketEntryType; + + static liveentry(): BucketEntryType; + + static deadentry(): BucketEntryType; + + static initentry(): BucketEntryType; + } + + class HotArchiveBucketEntryType { + readonly name: + | 'hotArchiveMetaentry' + | 'hotArchiveArchived' + | 'hotArchiveLive' + | 'hotArchiveDeleted'; + + readonly value: -1 | 0 | 1 | 2; + + static hotArchiveMetaentry(): HotArchiveBucketEntryType; + + static hotArchiveArchived(): HotArchiveBucketEntryType; + + static hotArchiveLive(): HotArchiveBucketEntryType; + + static hotArchiveDeleted(): HotArchiveBucketEntryType; + } + + class ColdArchiveBucketEntryType { + readonly name: + | 'coldArchiveMetaentry' + | 'coldArchiveArchivedLeaf' + | 'coldArchiveDeletedLeaf' + | 'coldArchiveBoundaryLeaf' + | 'coldArchiveHash'; + + readonly value: -1 | 0 | 1 | 2 | 3; + + static coldArchiveMetaentry(): ColdArchiveBucketEntryType; + + static coldArchiveArchivedLeaf(): ColdArchiveBucketEntryType; + + static coldArchiveDeletedLeaf(): ColdArchiveBucketEntryType; + + static coldArchiveBoundaryLeaf(): ColdArchiveBucketEntryType; + + static coldArchiveHash(): ColdArchiveBucketEntryType; + } + + class StellarValueType { + readonly name: 'stellarValueBasic' | 'stellarValueSigned'; + + readonly value: 0 | 1; + + static stellarValueBasic(): StellarValueType; + + static stellarValueSigned(): StellarValueType; + } + + class LedgerHeaderFlags { + readonly name: + | 'disableLiquidityPoolTradingFlag' + | 'disableLiquidityPoolDepositFlag' + | 'disableLiquidityPoolWithdrawalFlag'; + + readonly value: 1 | 2 | 4; + + static disableLiquidityPoolTradingFlag(): LedgerHeaderFlags; + + static disableLiquidityPoolDepositFlag(): LedgerHeaderFlags; + + static disableLiquidityPoolWithdrawalFlag(): LedgerHeaderFlags; + } + + class LedgerUpgradeType { + readonly name: + | 'ledgerUpgradeVersion' + | 'ledgerUpgradeBaseFee' + | 'ledgerUpgradeMaxTxSetSize' + | 'ledgerUpgradeBaseReserve' + | 'ledgerUpgradeFlags' + | 'ledgerUpgradeConfig' + | 'ledgerUpgradeMaxSorobanTxSetSize'; + + readonly value: 1 | 2 | 3 | 4 | 5 | 6 | 7; + + static ledgerUpgradeVersion(): LedgerUpgradeType; + + static ledgerUpgradeBaseFee(): LedgerUpgradeType; + + static ledgerUpgradeMaxTxSetSize(): LedgerUpgradeType; + + static ledgerUpgradeBaseReserve(): LedgerUpgradeType; + + static ledgerUpgradeFlags(): LedgerUpgradeType; + + static ledgerUpgradeConfig(): LedgerUpgradeType; + + static ledgerUpgradeMaxSorobanTxSetSize(): LedgerUpgradeType; + } + + class TxSetComponentType { + readonly name: 'txsetCompTxsMaybeDiscountedFee'; + + readonly value: 0; + + static txsetCompTxsMaybeDiscountedFee(): TxSetComponentType; + } + + class LedgerEntryChangeType { + readonly name: + | 'ledgerEntryCreated' + | 'ledgerEntryUpdated' + | 'ledgerEntryRemoved' + | 'ledgerEntryState'; + + readonly value: 0 | 1 | 2 | 3; + + static ledgerEntryCreated(): LedgerEntryChangeType; + + static ledgerEntryUpdated(): LedgerEntryChangeType; + + static ledgerEntryRemoved(): LedgerEntryChangeType; + + static ledgerEntryState(): LedgerEntryChangeType; + } + + class ContractEventType { + readonly name: 'system' | 'contract' | 'diagnostic'; + + readonly value: 0 | 1 | 2; + + static system(): ContractEventType; + + static contract(): ContractEventType; + + static diagnostic(): ContractEventType; + } + + class ErrorCode { + readonly name: 'errMisc' | 'errData' | 'errConf' | 'errAuth' | 'errLoad'; + + readonly value: 0 | 1 | 2 | 3 | 4; + + static errMisc(): ErrorCode; + + static errData(): ErrorCode; + + static errConf(): ErrorCode; + + static errAuth(): ErrorCode; + + static errLoad(): ErrorCode; + } + + class IpAddrType { + readonly name: 'iPv4' | 'iPv6'; + + readonly value: 0 | 1; + + static iPv4(): IpAddrType; + + static iPv6(): IpAddrType; + } + + class MessageType { + readonly name: + | 'errorMsg' + | 'auth' + | 'dontHave' + | 'getPeers' + | 'peers' + | 'getTxSet' + | 'txSet' + | 'generalizedTxSet' + | 'transaction' + | 'getScpQuorumset' + | 'scpQuorumset' + | 'scpMessage' + | 'getScpState' + | 'hello' + | 'surveyRequest' + | 'surveyResponse' + | 'sendMore' + | 'sendMoreExtended' + | 'floodAdvert' + | 'floodDemand' + | 'timeSlicedSurveyRequest' + | 'timeSlicedSurveyResponse' + | 'timeSlicedSurveyStartCollecting' + | 'timeSlicedSurveyStopCollecting'; + + readonly value: + | 0 + | 2 + | 3 + | 4 + | 5 + | 6 + | 7 + | 17 + | 8 + | 9 + | 10 + | 11 + | 12 + | 13 + | 14 + | 15 + | 16 + | 20 + | 18 + | 19 + | 21 + | 22 + | 23 + | 24; + + static errorMsg(): MessageType; + + static auth(): MessageType; + + static dontHave(): MessageType; + + static getPeers(): MessageType; + + static peers(): MessageType; + + static getTxSet(): MessageType; + + static txSet(): MessageType; + + static generalizedTxSet(): MessageType; + + static transaction(): MessageType; + + static getScpQuorumset(): MessageType; + + static scpQuorumset(): MessageType; + + static scpMessage(): MessageType; + + static getScpState(): MessageType; + + static hello(): MessageType; + + static surveyRequest(): MessageType; + + static surveyResponse(): MessageType; + + static sendMore(): MessageType; + + static sendMoreExtended(): MessageType; + + static floodAdvert(): MessageType; + + static floodDemand(): MessageType; + + static timeSlicedSurveyRequest(): MessageType; + + static timeSlicedSurveyResponse(): MessageType; + + static timeSlicedSurveyStartCollecting(): MessageType; + + static timeSlicedSurveyStopCollecting(): MessageType; + } + + class SurveyMessageCommandType { + readonly name: 'surveyTopology' | 'timeSlicedSurveyTopology'; + + readonly value: 0 | 1; + + static surveyTopology(): SurveyMessageCommandType; + + static timeSlicedSurveyTopology(): SurveyMessageCommandType; + } + + class SurveyMessageResponseType { + readonly name: + | 'surveyTopologyResponseV0' + | 'surveyTopologyResponseV1' + | 'surveyTopologyResponseV2'; + + readonly value: 0 | 1 | 2; + + static surveyTopologyResponseV0(): SurveyMessageResponseType; + + static surveyTopologyResponseV1(): SurveyMessageResponseType; + + static surveyTopologyResponseV2(): SurveyMessageResponseType; + } + + class OperationType { + readonly name: + | 'createAccount' + | 'payment' + | 'pathPaymentStrictReceive' + | 'manageSellOffer' + | 'createPassiveSellOffer' + | 'setOptions' + | 'changeTrust' + | 'allowTrust' + | 'accountMerge' + | 'inflation' + | 'manageData' + | 'bumpSequence' + | 'manageBuyOffer' + | 'pathPaymentStrictSend' + | 'createClaimableBalance' + | 'claimClaimableBalance' + | 'beginSponsoringFutureReserves' + | 'endSponsoringFutureReserves' + | 'revokeSponsorship' + | 'clawback' + | 'clawbackClaimableBalance' + | 'setTrustLineFlags' + | 'liquidityPoolDeposit' + | 'liquidityPoolWithdraw' + | 'invokeHostFunction' + | 'extendFootprintTtl' + | 'restoreFootprint'; + + readonly value: + | 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; + + static createAccount(): OperationType; + + static payment(): OperationType; + + static pathPaymentStrictReceive(): OperationType; + + static manageSellOffer(): OperationType; + + static createPassiveSellOffer(): OperationType; + + static setOptions(): OperationType; + + static changeTrust(): OperationType; + + static allowTrust(): OperationType; + + static accountMerge(): OperationType; + + static inflation(): OperationType; + + static manageData(): OperationType; + + static bumpSequence(): OperationType; + + static manageBuyOffer(): OperationType; + + static pathPaymentStrictSend(): OperationType; + + static createClaimableBalance(): OperationType; + + static claimClaimableBalance(): OperationType; + + static beginSponsoringFutureReserves(): OperationType; + + static endSponsoringFutureReserves(): OperationType; + + static revokeSponsorship(): OperationType; + + static clawback(): OperationType; + + static clawbackClaimableBalance(): OperationType; + + static setTrustLineFlags(): OperationType; + + static liquidityPoolDeposit(): OperationType; + + static liquidityPoolWithdraw(): OperationType; + + static invokeHostFunction(): OperationType; + + static extendFootprintTtl(): OperationType; + + static restoreFootprint(): OperationType; + } + + class RevokeSponsorshipType { + readonly name: 'revokeSponsorshipLedgerEntry' | 'revokeSponsorshipSigner'; + + readonly value: 0 | 1; + + static revokeSponsorshipLedgerEntry(): RevokeSponsorshipType; + + static revokeSponsorshipSigner(): RevokeSponsorshipType; + } + + class HostFunctionType { + readonly name: + | 'hostFunctionTypeInvokeContract' + | 'hostFunctionTypeCreateContract' + | 'hostFunctionTypeUploadContractWasm' + | 'hostFunctionTypeCreateContractV2'; + + readonly value: 0 | 1 | 2 | 3; + + static hostFunctionTypeInvokeContract(): HostFunctionType; + + static hostFunctionTypeCreateContract(): HostFunctionType; + + static hostFunctionTypeUploadContractWasm(): HostFunctionType; + + static hostFunctionTypeCreateContractV2(): HostFunctionType; + } + + class ContractIdPreimageType { + readonly name: + | 'contractIdPreimageFromAddress' + | 'contractIdPreimageFromAsset'; + + readonly value: 0 | 1; + + static contractIdPreimageFromAddress(): ContractIdPreimageType; + + static contractIdPreimageFromAsset(): ContractIdPreimageType; + } + + class SorobanAuthorizedFunctionType { + readonly name: + | 'sorobanAuthorizedFunctionTypeContractFn' + | 'sorobanAuthorizedFunctionTypeCreateContractHostFn' + | 'sorobanAuthorizedFunctionTypeCreateContractV2HostFn'; + + readonly value: 0 | 1 | 2; + + static sorobanAuthorizedFunctionTypeContractFn(): SorobanAuthorizedFunctionType; + + static sorobanAuthorizedFunctionTypeCreateContractHostFn(): SorobanAuthorizedFunctionType; + + static sorobanAuthorizedFunctionTypeCreateContractV2HostFn(): SorobanAuthorizedFunctionType; + } + + class SorobanCredentialsType { + readonly name: + | 'sorobanCredentialsSourceAccount' + | 'sorobanCredentialsAddress'; + + readonly value: 0 | 1; + + static sorobanCredentialsSourceAccount(): SorobanCredentialsType; + + static sorobanCredentialsAddress(): SorobanCredentialsType; + } + + class MemoType { + readonly name: + | 'memoNone' + | 'memoText' + | 'memoId' + | 'memoHash' + | 'memoReturn'; + + readonly value: 0 | 1 | 2 | 3 | 4; + + static memoNone(): MemoType; + + static memoText(): MemoType; + + static memoId(): MemoType; + + static memoHash(): MemoType; + + static memoReturn(): MemoType; + } + + class PreconditionType { + readonly name: 'precondNone' | 'precondTime' | 'precondV2'; + + readonly value: 0 | 1 | 2; + + static precondNone(): PreconditionType; + + static precondTime(): PreconditionType; + + static precondV2(): PreconditionType; + } + + class ArchivalProofType { + readonly name: 'existence' | 'nonexistence'; + + readonly value: 0 | 1; + + static existence(): ArchivalProofType; + + static nonexistence(): ArchivalProofType; + } + + class ClaimAtomType { + readonly name: + | 'claimAtomTypeV0' + | 'claimAtomTypeOrderBook' + | 'claimAtomTypeLiquidityPool'; + + readonly value: 0 | 1 | 2; + + static claimAtomTypeV0(): ClaimAtomType; + + static claimAtomTypeOrderBook(): ClaimAtomType; + + static claimAtomTypeLiquidityPool(): ClaimAtomType; + } + + class CreateAccountResultCode { + readonly name: + | 'createAccountSuccess' + | 'createAccountMalformed' + | 'createAccountUnderfunded' + | 'createAccountLowReserve' + | 'createAccountAlreadyExist'; + + readonly value: 0 | -1 | -2 | -3 | -4; + + static createAccountSuccess(): CreateAccountResultCode; + + static createAccountMalformed(): CreateAccountResultCode; + + static createAccountUnderfunded(): CreateAccountResultCode; + + static createAccountLowReserve(): CreateAccountResultCode; + + static createAccountAlreadyExist(): CreateAccountResultCode; + } + + class PaymentResultCode { + readonly name: + | 'paymentSuccess' + | 'paymentMalformed' + | 'paymentUnderfunded' + | 'paymentSrcNoTrust' + | 'paymentSrcNotAuthorized' + | 'paymentNoDestination' + | 'paymentNoTrust' + | 'paymentNotAuthorized' + | 'paymentLineFull' + | 'paymentNoIssuer'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5 | -6 | -7 | -8 | -9; + + static paymentSuccess(): PaymentResultCode; + + static paymentMalformed(): PaymentResultCode; + + static paymentUnderfunded(): PaymentResultCode; + + static paymentSrcNoTrust(): PaymentResultCode; + + static paymentSrcNotAuthorized(): PaymentResultCode; + + static paymentNoDestination(): PaymentResultCode; + + static paymentNoTrust(): PaymentResultCode; + + static paymentNotAuthorized(): PaymentResultCode; + + static paymentLineFull(): PaymentResultCode; + + static paymentNoIssuer(): PaymentResultCode; + } + + class PathPaymentStrictReceiveResultCode { + readonly name: + | 'pathPaymentStrictReceiveSuccess' + | 'pathPaymentStrictReceiveMalformed' + | 'pathPaymentStrictReceiveUnderfunded' + | 'pathPaymentStrictReceiveSrcNoTrust' + | 'pathPaymentStrictReceiveSrcNotAuthorized' + | 'pathPaymentStrictReceiveNoDestination' + | 'pathPaymentStrictReceiveNoTrust' + | 'pathPaymentStrictReceiveNotAuthorized' + | 'pathPaymentStrictReceiveLineFull' + | 'pathPaymentStrictReceiveNoIssuer' + | 'pathPaymentStrictReceiveTooFewOffers' + | 'pathPaymentStrictReceiveOfferCrossSelf' + | 'pathPaymentStrictReceiveOverSendmax'; + + readonly value: + | 0 + | -1 + | -2 + | -3 + | -4 + | -5 + | -6 + | -7 + | -8 + | -9 + | -10 + | -11 + | -12; + + static pathPaymentStrictReceiveSuccess(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveMalformed(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveUnderfunded(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveSrcNoTrust(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveSrcNotAuthorized(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveNoDestination(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveNoTrust(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveNotAuthorized(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveLineFull(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveNoIssuer(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveTooFewOffers(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveOfferCrossSelf(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveOverSendmax(): PathPaymentStrictReceiveResultCode; + } + + class PathPaymentStrictSendResultCode { + readonly name: + | 'pathPaymentStrictSendSuccess' + | 'pathPaymentStrictSendMalformed' + | 'pathPaymentStrictSendUnderfunded' + | 'pathPaymentStrictSendSrcNoTrust' + | 'pathPaymentStrictSendSrcNotAuthorized' + | 'pathPaymentStrictSendNoDestination' + | 'pathPaymentStrictSendNoTrust' + | 'pathPaymentStrictSendNotAuthorized' + | 'pathPaymentStrictSendLineFull' + | 'pathPaymentStrictSendNoIssuer' + | 'pathPaymentStrictSendTooFewOffers' + | 'pathPaymentStrictSendOfferCrossSelf' + | 'pathPaymentStrictSendUnderDestmin'; + + readonly value: + | 0 + | -1 + | -2 + | -3 + | -4 + | -5 + | -6 + | -7 + | -8 + | -9 + | -10 + | -11 + | -12; + + static pathPaymentStrictSendSuccess(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendMalformed(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendUnderfunded(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendSrcNoTrust(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendSrcNotAuthorized(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendNoDestination(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendNoTrust(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendNotAuthorized(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendLineFull(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendNoIssuer(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendTooFewOffers(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendOfferCrossSelf(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendUnderDestmin(): PathPaymentStrictSendResultCode; + } + + class ManageSellOfferResultCode { + readonly name: + | 'manageSellOfferSuccess' + | 'manageSellOfferMalformed' + | 'manageSellOfferSellNoTrust' + | 'manageSellOfferBuyNoTrust' + | 'manageSellOfferSellNotAuthorized' + | 'manageSellOfferBuyNotAuthorized' + | 'manageSellOfferLineFull' + | 'manageSellOfferUnderfunded' + | 'manageSellOfferCrossSelf' + | 'manageSellOfferSellNoIssuer' + | 'manageSellOfferBuyNoIssuer' + | 'manageSellOfferNotFound' + | 'manageSellOfferLowReserve'; + + readonly value: + | 0 + | -1 + | -2 + | -3 + | -4 + | -5 + | -6 + | -7 + | -8 + | -9 + | -10 + | -11 + | -12; + + static manageSellOfferSuccess(): ManageSellOfferResultCode; + + static manageSellOfferMalformed(): ManageSellOfferResultCode; + + static manageSellOfferSellNoTrust(): ManageSellOfferResultCode; + + static manageSellOfferBuyNoTrust(): ManageSellOfferResultCode; + + static manageSellOfferSellNotAuthorized(): ManageSellOfferResultCode; + + static manageSellOfferBuyNotAuthorized(): ManageSellOfferResultCode; + + static manageSellOfferLineFull(): ManageSellOfferResultCode; + + static manageSellOfferUnderfunded(): ManageSellOfferResultCode; + + static manageSellOfferCrossSelf(): ManageSellOfferResultCode; + + static manageSellOfferSellNoIssuer(): ManageSellOfferResultCode; + + static manageSellOfferBuyNoIssuer(): ManageSellOfferResultCode; + + static manageSellOfferNotFound(): ManageSellOfferResultCode; + + static manageSellOfferLowReserve(): ManageSellOfferResultCode; + } + + class ManageOfferEffect { + readonly name: + | 'manageOfferCreated' + | 'manageOfferUpdated' + | 'manageOfferDeleted'; + + readonly value: 0 | 1 | 2; + + static manageOfferCreated(): ManageOfferEffect; + + static manageOfferUpdated(): ManageOfferEffect; + + static manageOfferDeleted(): ManageOfferEffect; + } + + class ManageBuyOfferResultCode { + readonly name: + | 'manageBuyOfferSuccess' + | 'manageBuyOfferMalformed' + | 'manageBuyOfferSellNoTrust' + | 'manageBuyOfferBuyNoTrust' + | 'manageBuyOfferSellNotAuthorized' + | 'manageBuyOfferBuyNotAuthorized' + | 'manageBuyOfferLineFull' + | 'manageBuyOfferUnderfunded' + | 'manageBuyOfferCrossSelf' + | 'manageBuyOfferSellNoIssuer' + | 'manageBuyOfferBuyNoIssuer' + | 'manageBuyOfferNotFound' + | 'manageBuyOfferLowReserve'; + + readonly value: + | 0 + | -1 + | -2 + | -3 + | -4 + | -5 + | -6 + | -7 + | -8 + | -9 + | -10 + | -11 + | -12; + + static manageBuyOfferSuccess(): ManageBuyOfferResultCode; + + static manageBuyOfferMalformed(): ManageBuyOfferResultCode; + + static manageBuyOfferSellNoTrust(): ManageBuyOfferResultCode; + + static manageBuyOfferBuyNoTrust(): ManageBuyOfferResultCode; + + static manageBuyOfferSellNotAuthorized(): ManageBuyOfferResultCode; + + static manageBuyOfferBuyNotAuthorized(): ManageBuyOfferResultCode; + + static manageBuyOfferLineFull(): ManageBuyOfferResultCode; + + static manageBuyOfferUnderfunded(): ManageBuyOfferResultCode; + + static manageBuyOfferCrossSelf(): ManageBuyOfferResultCode; + + static manageBuyOfferSellNoIssuer(): ManageBuyOfferResultCode; + + static manageBuyOfferBuyNoIssuer(): ManageBuyOfferResultCode; + + static manageBuyOfferNotFound(): ManageBuyOfferResultCode; + + static manageBuyOfferLowReserve(): ManageBuyOfferResultCode; + } + + class SetOptionsResultCode { + readonly name: + | 'setOptionsSuccess' + | 'setOptionsLowReserve' + | 'setOptionsTooManySigners' + | 'setOptionsBadFlags' + | 'setOptionsInvalidInflation' + | 'setOptionsCantChange' + | 'setOptionsUnknownFlag' + | 'setOptionsThresholdOutOfRange' + | 'setOptionsBadSigner' + | 'setOptionsInvalidHomeDomain' + | 'setOptionsAuthRevocableRequired'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5 | -6 | -7 | -8 | -9 | -10; + + static setOptionsSuccess(): SetOptionsResultCode; + + static setOptionsLowReserve(): SetOptionsResultCode; + + static setOptionsTooManySigners(): SetOptionsResultCode; + + static setOptionsBadFlags(): SetOptionsResultCode; + + static setOptionsInvalidInflation(): SetOptionsResultCode; + + static setOptionsCantChange(): SetOptionsResultCode; + + static setOptionsUnknownFlag(): SetOptionsResultCode; + + static setOptionsThresholdOutOfRange(): SetOptionsResultCode; + + static setOptionsBadSigner(): SetOptionsResultCode; + + static setOptionsInvalidHomeDomain(): SetOptionsResultCode; + + static setOptionsAuthRevocableRequired(): SetOptionsResultCode; + } + + class ChangeTrustResultCode { + readonly name: + | 'changeTrustSuccess' + | 'changeTrustMalformed' + | 'changeTrustNoIssuer' + | 'changeTrustInvalidLimit' + | 'changeTrustLowReserve' + | 'changeTrustSelfNotAllowed' + | 'changeTrustTrustLineMissing' + | 'changeTrustCannotDelete' + | 'changeTrustNotAuthMaintainLiabilities'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5 | -6 | -7 | -8; + + static changeTrustSuccess(): ChangeTrustResultCode; + + static changeTrustMalformed(): ChangeTrustResultCode; + + static changeTrustNoIssuer(): ChangeTrustResultCode; + + static changeTrustInvalidLimit(): ChangeTrustResultCode; + + static changeTrustLowReserve(): ChangeTrustResultCode; + + static changeTrustSelfNotAllowed(): ChangeTrustResultCode; + + static changeTrustTrustLineMissing(): ChangeTrustResultCode; + + static changeTrustCannotDelete(): ChangeTrustResultCode; + + static changeTrustNotAuthMaintainLiabilities(): ChangeTrustResultCode; + } + + class AllowTrustResultCode { + readonly name: + | 'allowTrustSuccess' + | 'allowTrustMalformed' + | 'allowTrustNoTrustLine' + | 'allowTrustTrustNotRequired' + | 'allowTrustCantRevoke' + | 'allowTrustSelfNotAllowed' + | 'allowTrustLowReserve'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5 | -6; + + static allowTrustSuccess(): AllowTrustResultCode; + + static allowTrustMalformed(): AllowTrustResultCode; + + static allowTrustNoTrustLine(): AllowTrustResultCode; + + static allowTrustTrustNotRequired(): AllowTrustResultCode; + + static allowTrustCantRevoke(): AllowTrustResultCode; + + static allowTrustSelfNotAllowed(): AllowTrustResultCode; + + static allowTrustLowReserve(): AllowTrustResultCode; + } + + class AccountMergeResultCode { + readonly name: + | 'accountMergeSuccess' + | 'accountMergeMalformed' + | 'accountMergeNoAccount' + | 'accountMergeImmutableSet' + | 'accountMergeHasSubEntries' + | 'accountMergeSeqnumTooFar' + | 'accountMergeDestFull' + | 'accountMergeIsSponsor'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5 | -6 | -7; + + static accountMergeSuccess(): AccountMergeResultCode; + + static accountMergeMalformed(): AccountMergeResultCode; + + static accountMergeNoAccount(): AccountMergeResultCode; + + static accountMergeImmutableSet(): AccountMergeResultCode; + + static accountMergeHasSubEntries(): AccountMergeResultCode; + + static accountMergeSeqnumTooFar(): AccountMergeResultCode; + + static accountMergeDestFull(): AccountMergeResultCode; + + static accountMergeIsSponsor(): AccountMergeResultCode; + } + + class InflationResultCode { + readonly name: 'inflationSuccess' | 'inflationNotTime'; + + readonly value: 0 | -1; + + static inflationSuccess(): InflationResultCode; + + static inflationNotTime(): InflationResultCode; + } + + class ManageDataResultCode { + readonly name: + | 'manageDataSuccess' + | 'manageDataNotSupportedYet' + | 'manageDataNameNotFound' + | 'manageDataLowReserve' + | 'manageDataInvalidName'; + + readonly value: 0 | -1 | -2 | -3 | -4; + + static manageDataSuccess(): ManageDataResultCode; + + static manageDataNotSupportedYet(): ManageDataResultCode; + + static manageDataNameNotFound(): ManageDataResultCode; + + static manageDataLowReserve(): ManageDataResultCode; + + static manageDataInvalidName(): ManageDataResultCode; + } + + class BumpSequenceResultCode { + readonly name: 'bumpSequenceSuccess' | 'bumpSequenceBadSeq'; + + readonly value: 0 | -1; + + static bumpSequenceSuccess(): BumpSequenceResultCode; + + static bumpSequenceBadSeq(): BumpSequenceResultCode; + } + + class CreateClaimableBalanceResultCode { + readonly name: + | 'createClaimableBalanceSuccess' + | 'createClaimableBalanceMalformed' + | 'createClaimableBalanceLowReserve' + | 'createClaimableBalanceNoTrust' + | 'createClaimableBalanceNotAuthorized' + | 'createClaimableBalanceUnderfunded'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5; + + static createClaimableBalanceSuccess(): CreateClaimableBalanceResultCode; + + static createClaimableBalanceMalformed(): CreateClaimableBalanceResultCode; + + static createClaimableBalanceLowReserve(): CreateClaimableBalanceResultCode; + + static createClaimableBalanceNoTrust(): CreateClaimableBalanceResultCode; + + static createClaimableBalanceNotAuthorized(): CreateClaimableBalanceResultCode; + + static createClaimableBalanceUnderfunded(): CreateClaimableBalanceResultCode; + } + + class ClaimClaimableBalanceResultCode { + readonly name: + | 'claimClaimableBalanceSuccess' + | 'claimClaimableBalanceDoesNotExist' + | 'claimClaimableBalanceCannotClaim' + | 'claimClaimableBalanceLineFull' + | 'claimClaimableBalanceNoTrust' + | 'claimClaimableBalanceNotAuthorized'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5; + + static claimClaimableBalanceSuccess(): ClaimClaimableBalanceResultCode; + + static claimClaimableBalanceDoesNotExist(): ClaimClaimableBalanceResultCode; + + static claimClaimableBalanceCannotClaim(): ClaimClaimableBalanceResultCode; + + static claimClaimableBalanceLineFull(): ClaimClaimableBalanceResultCode; + + static claimClaimableBalanceNoTrust(): ClaimClaimableBalanceResultCode; + + static claimClaimableBalanceNotAuthorized(): ClaimClaimableBalanceResultCode; + } + + class BeginSponsoringFutureReservesResultCode { + readonly name: + | 'beginSponsoringFutureReservesSuccess' + | 'beginSponsoringFutureReservesMalformed' + | 'beginSponsoringFutureReservesAlreadySponsored' + | 'beginSponsoringFutureReservesRecursive'; + + readonly value: 0 | -1 | -2 | -3; + + static beginSponsoringFutureReservesSuccess(): BeginSponsoringFutureReservesResultCode; + + static beginSponsoringFutureReservesMalformed(): BeginSponsoringFutureReservesResultCode; + + static beginSponsoringFutureReservesAlreadySponsored(): BeginSponsoringFutureReservesResultCode; + + static beginSponsoringFutureReservesRecursive(): BeginSponsoringFutureReservesResultCode; + } + + class EndSponsoringFutureReservesResultCode { + readonly name: + | 'endSponsoringFutureReservesSuccess' + | 'endSponsoringFutureReservesNotSponsored'; + + readonly value: 0 | -1; + + static endSponsoringFutureReservesSuccess(): EndSponsoringFutureReservesResultCode; + + static endSponsoringFutureReservesNotSponsored(): EndSponsoringFutureReservesResultCode; + } + + class RevokeSponsorshipResultCode { + readonly name: + | 'revokeSponsorshipSuccess' + | 'revokeSponsorshipDoesNotExist' + | 'revokeSponsorshipNotSponsor' + | 'revokeSponsorshipLowReserve' + | 'revokeSponsorshipOnlyTransferable' + | 'revokeSponsorshipMalformed'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5; + + static revokeSponsorshipSuccess(): RevokeSponsorshipResultCode; + + static revokeSponsorshipDoesNotExist(): RevokeSponsorshipResultCode; + + static revokeSponsorshipNotSponsor(): RevokeSponsorshipResultCode; + + static revokeSponsorshipLowReserve(): RevokeSponsorshipResultCode; + + static revokeSponsorshipOnlyTransferable(): RevokeSponsorshipResultCode; + + static revokeSponsorshipMalformed(): RevokeSponsorshipResultCode; + } + + class ClawbackResultCode { + readonly name: + | 'clawbackSuccess' + | 'clawbackMalformed' + | 'clawbackNotClawbackEnabled' + | 'clawbackNoTrust' + | 'clawbackUnderfunded'; + + readonly value: 0 | -1 | -2 | -3 | -4; + + static clawbackSuccess(): ClawbackResultCode; + + static clawbackMalformed(): ClawbackResultCode; + + static clawbackNotClawbackEnabled(): ClawbackResultCode; + + static clawbackNoTrust(): ClawbackResultCode; + + static clawbackUnderfunded(): ClawbackResultCode; + } + + class ClawbackClaimableBalanceResultCode { + readonly name: + | 'clawbackClaimableBalanceSuccess' + | 'clawbackClaimableBalanceDoesNotExist' + | 'clawbackClaimableBalanceNotIssuer' + | 'clawbackClaimableBalanceNotClawbackEnabled'; + + readonly value: 0 | -1 | -2 | -3; + + static clawbackClaimableBalanceSuccess(): ClawbackClaimableBalanceResultCode; + + static clawbackClaimableBalanceDoesNotExist(): ClawbackClaimableBalanceResultCode; + + static clawbackClaimableBalanceNotIssuer(): ClawbackClaimableBalanceResultCode; + + static clawbackClaimableBalanceNotClawbackEnabled(): ClawbackClaimableBalanceResultCode; + } + + class SetTrustLineFlagsResultCode { + readonly name: + | 'setTrustLineFlagsSuccess' + | 'setTrustLineFlagsMalformed' + | 'setTrustLineFlagsNoTrustLine' + | 'setTrustLineFlagsCantRevoke' + | 'setTrustLineFlagsInvalidState' + | 'setTrustLineFlagsLowReserve'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5; + + static setTrustLineFlagsSuccess(): SetTrustLineFlagsResultCode; + + static setTrustLineFlagsMalformed(): SetTrustLineFlagsResultCode; + + static setTrustLineFlagsNoTrustLine(): SetTrustLineFlagsResultCode; + + static setTrustLineFlagsCantRevoke(): SetTrustLineFlagsResultCode; + + static setTrustLineFlagsInvalidState(): SetTrustLineFlagsResultCode; + + static setTrustLineFlagsLowReserve(): SetTrustLineFlagsResultCode; + } + + class LiquidityPoolDepositResultCode { + readonly name: + | 'liquidityPoolDepositSuccess' + | 'liquidityPoolDepositMalformed' + | 'liquidityPoolDepositNoTrust' + | 'liquidityPoolDepositNotAuthorized' + | 'liquidityPoolDepositUnderfunded' + | 'liquidityPoolDepositLineFull' + | 'liquidityPoolDepositBadPrice' + | 'liquidityPoolDepositPoolFull'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5 | -6 | -7; + + static liquidityPoolDepositSuccess(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositMalformed(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositNoTrust(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositNotAuthorized(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositUnderfunded(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositLineFull(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositBadPrice(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositPoolFull(): LiquidityPoolDepositResultCode; + } + + class LiquidityPoolWithdrawResultCode { + readonly name: + | 'liquidityPoolWithdrawSuccess' + | 'liquidityPoolWithdrawMalformed' + | 'liquidityPoolWithdrawNoTrust' + | 'liquidityPoolWithdrawUnderfunded' + | 'liquidityPoolWithdrawLineFull' + | 'liquidityPoolWithdrawUnderMinimum'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5; + + static liquidityPoolWithdrawSuccess(): LiquidityPoolWithdrawResultCode; + + static liquidityPoolWithdrawMalformed(): LiquidityPoolWithdrawResultCode; + + static liquidityPoolWithdrawNoTrust(): LiquidityPoolWithdrawResultCode; + + static liquidityPoolWithdrawUnderfunded(): LiquidityPoolWithdrawResultCode; + + static liquidityPoolWithdrawLineFull(): LiquidityPoolWithdrawResultCode; + + static liquidityPoolWithdrawUnderMinimum(): LiquidityPoolWithdrawResultCode; + } + + class InvokeHostFunctionResultCode { + readonly name: + | 'invokeHostFunctionSuccess' + | 'invokeHostFunctionMalformed' + | 'invokeHostFunctionTrapped' + | 'invokeHostFunctionResourceLimitExceeded' + | 'invokeHostFunctionEntryArchived' + | 'invokeHostFunctionInsufficientRefundableFee'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5; + + static invokeHostFunctionSuccess(): InvokeHostFunctionResultCode; + + static invokeHostFunctionMalformed(): InvokeHostFunctionResultCode; + + static invokeHostFunctionTrapped(): InvokeHostFunctionResultCode; + + static invokeHostFunctionResourceLimitExceeded(): InvokeHostFunctionResultCode; + + static invokeHostFunctionEntryArchived(): InvokeHostFunctionResultCode; + + static invokeHostFunctionInsufficientRefundableFee(): InvokeHostFunctionResultCode; + } + + class ExtendFootprintTtlResultCode { + readonly name: + | 'extendFootprintTtlSuccess' + | 'extendFootprintTtlMalformed' + | 'extendFootprintTtlResourceLimitExceeded' + | 'extendFootprintTtlInsufficientRefundableFee'; + + readonly value: 0 | -1 | -2 | -3; + + static extendFootprintTtlSuccess(): ExtendFootprintTtlResultCode; + + static extendFootprintTtlMalformed(): ExtendFootprintTtlResultCode; + + static extendFootprintTtlResourceLimitExceeded(): ExtendFootprintTtlResultCode; + + static extendFootprintTtlInsufficientRefundableFee(): ExtendFootprintTtlResultCode; + } + + class RestoreFootprintResultCode { + readonly name: + | 'restoreFootprintSuccess' + | 'restoreFootprintMalformed' + | 'restoreFootprintResourceLimitExceeded' + | 'restoreFootprintInsufficientRefundableFee'; + + readonly value: 0 | -1 | -2 | -3; + + static restoreFootprintSuccess(): RestoreFootprintResultCode; + + static restoreFootprintMalformed(): RestoreFootprintResultCode; + + static restoreFootprintResourceLimitExceeded(): RestoreFootprintResultCode; + + static restoreFootprintInsufficientRefundableFee(): RestoreFootprintResultCode; + } + + class OperationResultCode { + readonly name: + | 'opInner' + | 'opBadAuth' + | 'opNoAccount' + | 'opNotSupported' + | 'opTooManySubentries' + | 'opExceededWorkLimit' + | 'opTooManySponsoring'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5 | -6; + + static opInner(): OperationResultCode; + + static opBadAuth(): OperationResultCode; + + static opNoAccount(): OperationResultCode; + + static opNotSupported(): OperationResultCode; + + static opTooManySubentries(): OperationResultCode; + + static opExceededWorkLimit(): OperationResultCode; + + static opTooManySponsoring(): OperationResultCode; + } + + class TransactionResultCode { + readonly name: + | 'txFeeBumpInnerSuccess' + | 'txSuccess' + | 'txFailed' + | 'txTooEarly' + | 'txTooLate' + | 'txMissingOperation' + | 'txBadSeq' + | 'txBadAuth' + | 'txInsufficientBalance' + | 'txNoAccount' + | 'txInsufficientFee' + | 'txBadAuthExtra' + | 'txInternalError' + | 'txNotSupported' + | 'txFeeBumpInnerFailed' + | 'txBadSponsorship' + | 'txBadMinSeqAgeOrGap' + | 'txMalformed' + | 'txSorobanInvalid'; + + readonly value: + | 1 + | 0 + | -1 + | -2 + | -3 + | -4 + | -5 + | -6 + | -7 + | -8 + | -9 + | -10 + | -11 + | -12 + | -13 + | -14 + | -15 + | -16 + | -17; + + static txFeeBumpInnerSuccess(): TransactionResultCode; + + static txSuccess(): TransactionResultCode; + + static txFailed(): TransactionResultCode; + + static txTooEarly(): TransactionResultCode; + + static txTooLate(): TransactionResultCode; + + static txMissingOperation(): TransactionResultCode; + + static txBadSeq(): TransactionResultCode; + + static txBadAuth(): TransactionResultCode; + + static txInsufficientBalance(): TransactionResultCode; + + static txNoAccount(): TransactionResultCode; + + static txInsufficientFee(): TransactionResultCode; + + static txBadAuthExtra(): TransactionResultCode; + + static txInternalError(): TransactionResultCode; + + static txNotSupported(): TransactionResultCode; + + static txFeeBumpInnerFailed(): TransactionResultCode; + + static txBadSponsorship(): TransactionResultCode; + + static txBadMinSeqAgeOrGap(): TransactionResultCode; + + static txMalformed(): TransactionResultCode; + + static txSorobanInvalid(): TransactionResultCode; + } + + class CryptoKeyType { + readonly name: + | 'keyTypeEd25519' + | 'keyTypePreAuthTx' + | 'keyTypeHashX' + | 'keyTypeEd25519SignedPayload' + | 'keyTypeMuxedEd25519'; + + readonly value: 0 | 1 | 2 | 3 | 256; + + static keyTypeEd25519(): CryptoKeyType; + + static keyTypePreAuthTx(): CryptoKeyType; + + static keyTypeHashX(): CryptoKeyType; + + static keyTypeEd25519SignedPayload(): CryptoKeyType; + + static keyTypeMuxedEd25519(): CryptoKeyType; + } + + class PublicKeyType { + readonly name: 'publicKeyTypeEd25519'; + + readonly value: 0; + + static publicKeyTypeEd25519(): PublicKeyType; + } + + class SignerKeyType { + readonly name: + | 'signerKeyTypeEd25519' + | 'signerKeyTypePreAuthTx' + | 'signerKeyTypeHashX' + | 'signerKeyTypeEd25519SignedPayload'; + + readonly value: 0 | 1 | 2 | 3; + + static signerKeyTypeEd25519(): SignerKeyType; + + static signerKeyTypePreAuthTx(): SignerKeyType; + + static signerKeyTypeHashX(): SignerKeyType; + + static signerKeyTypeEd25519SignedPayload(): SignerKeyType; + } + + class BinaryFuseFilterType { + readonly name: + | 'binaryFuseFilter8Bit' + | 'binaryFuseFilter16Bit' + | 'binaryFuseFilter32Bit'; + + readonly value: 0 | 1 | 2; + + static binaryFuseFilter8Bit(): BinaryFuseFilterType; + + static binaryFuseFilter16Bit(): BinaryFuseFilterType; + + static binaryFuseFilter32Bit(): BinaryFuseFilterType; + } + + class ScValType { + readonly name: + | 'scvBool' + | 'scvVoid' + | 'scvError' + | 'scvU32' + | 'scvI32' + | 'scvU64' + | 'scvI64' + | 'scvTimepoint' + | 'scvDuration' + | 'scvU128' + | 'scvI128' + | 'scvU256' + | 'scvI256' + | 'scvBytes' + | 'scvString' + | 'scvSymbol' + | 'scvVec' + | 'scvMap' + | 'scvAddress' + | 'scvContractInstance' + | 'scvLedgerKeyContractInstance' + | 'scvLedgerKeyNonce'; + + readonly value: + | 0 + | 1 + | 2 + | 3 + | 4 + | 5 + | 6 + | 7 + | 8 + | 9 + | 10 + | 11 + | 12 + | 13 + | 14 + | 15 + | 16 + | 17 + | 18 + | 19 + | 20 + | 21; + + static scvBool(): ScValType; + + static scvVoid(): ScValType; + + static scvError(): ScValType; + + static scvU32(): ScValType; + + static scvI32(): ScValType; + + static scvU64(): ScValType; + + static scvI64(): ScValType; + + static scvTimepoint(): ScValType; + + static scvDuration(): ScValType; + + static scvU128(): ScValType; + + static scvI128(): ScValType; + + static scvU256(): ScValType; + + static scvI256(): ScValType; + + static scvBytes(): ScValType; + + static scvString(): ScValType; + + static scvSymbol(): ScValType; + + static scvVec(): ScValType; + + static scvMap(): ScValType; + + static scvAddress(): ScValType; + + static scvContractInstance(): ScValType; + + static scvLedgerKeyContractInstance(): ScValType; + + static scvLedgerKeyNonce(): ScValType; + } + + class ScErrorType { + readonly name: + | 'sceContract' + | 'sceWasmVm' + | 'sceContext' + | 'sceStorage' + | 'sceObject' + | 'sceCrypto' + | 'sceEvents' + | 'sceBudget' + | 'sceValue' + | 'sceAuth'; + + readonly value: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + + static sceContract(): ScErrorType; + + static sceWasmVm(): ScErrorType; + + static sceContext(): ScErrorType; + + static sceStorage(): ScErrorType; + + static sceObject(): ScErrorType; + + static sceCrypto(): ScErrorType; + + static sceEvents(): ScErrorType; + + static sceBudget(): ScErrorType; + + static sceValue(): ScErrorType; + + static sceAuth(): ScErrorType; + } + + class ScErrorCode { + readonly name: + | 'scecArithDomain' + | 'scecIndexBounds' + | 'scecInvalidInput' + | 'scecMissingValue' + | 'scecExistingValue' + | 'scecExceededLimit' + | 'scecInvalidAction' + | 'scecInternalError' + | 'scecUnexpectedType' + | 'scecUnexpectedSize'; + + readonly value: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + + static scecArithDomain(): ScErrorCode; + + static scecIndexBounds(): ScErrorCode; + + static scecInvalidInput(): ScErrorCode; + + static scecMissingValue(): ScErrorCode; + + static scecExistingValue(): ScErrorCode; + + static scecExceededLimit(): ScErrorCode; + + static scecInvalidAction(): ScErrorCode; + + static scecInternalError(): ScErrorCode; + + static scecUnexpectedType(): ScErrorCode; + + static scecUnexpectedSize(): ScErrorCode; + } + + class ContractExecutableType { + readonly name: 'contractExecutableWasm' | 'contractExecutableStellarAsset'; + + readonly value: 0 | 1; + + static contractExecutableWasm(): ContractExecutableType; + + static contractExecutableStellarAsset(): ContractExecutableType; + } + + class ScAddressType { + readonly name: 'scAddressTypeAccount' | 'scAddressTypeContract'; + + readonly value: 0 | 1; + + static scAddressTypeAccount(): ScAddressType; + + static scAddressTypeContract(): ScAddressType; + } + + class ScEnvMetaKind { + readonly name: 'scEnvMetaKindInterfaceVersion'; + + readonly value: 0; + + static scEnvMetaKindInterfaceVersion(): ScEnvMetaKind; + } + + class ScMetaKind { + readonly name: 'scMetaV0'; + + readonly value: 0; + + static scMetaV0(): ScMetaKind; + } + + class ScSpecType { + readonly name: + | 'scSpecTypeVal' + | 'scSpecTypeBool' + | 'scSpecTypeVoid' + | 'scSpecTypeError' + | 'scSpecTypeU32' + | 'scSpecTypeI32' + | 'scSpecTypeU64' + | 'scSpecTypeI64' + | 'scSpecTypeTimepoint' + | 'scSpecTypeDuration' + | 'scSpecTypeU128' + | 'scSpecTypeI128' + | 'scSpecTypeU256' + | 'scSpecTypeI256' + | 'scSpecTypeBytes' + | 'scSpecTypeString' + | 'scSpecTypeSymbol' + | 'scSpecTypeAddress' + | 'scSpecTypeOption' + | 'scSpecTypeResult' + | 'scSpecTypeVec' + | 'scSpecTypeMap' + | 'scSpecTypeTuple' + | 'scSpecTypeBytesN' + | 'scSpecTypeUdt'; + + readonly value: + | 0 + | 1 + | 2 + | 3 + | 4 + | 5 + | 6 + | 7 + | 8 + | 9 + | 10 + | 11 + | 12 + | 13 + | 14 + | 16 + | 17 + | 19 + | 1000 + | 1001 + | 1002 + | 1004 + | 1005 + | 1006 + | 2000; + + static scSpecTypeVal(): ScSpecType; + + static scSpecTypeBool(): ScSpecType; + + static scSpecTypeVoid(): ScSpecType; + + static scSpecTypeError(): ScSpecType; + + static scSpecTypeU32(): ScSpecType; + + static scSpecTypeI32(): ScSpecType; + + static scSpecTypeU64(): ScSpecType; + + static scSpecTypeI64(): ScSpecType; + + static scSpecTypeTimepoint(): ScSpecType; + + static scSpecTypeDuration(): ScSpecType; + + static scSpecTypeU128(): ScSpecType; + + static scSpecTypeI128(): ScSpecType; + + static scSpecTypeU256(): ScSpecType; + + static scSpecTypeI256(): ScSpecType; + + static scSpecTypeBytes(): ScSpecType; + + static scSpecTypeString(): ScSpecType; + + static scSpecTypeSymbol(): ScSpecType; + + static scSpecTypeAddress(): ScSpecType; + + static scSpecTypeOption(): ScSpecType; + + static scSpecTypeResult(): ScSpecType; + + static scSpecTypeVec(): ScSpecType; + + static scSpecTypeMap(): ScSpecType; + + static scSpecTypeTuple(): ScSpecType; + + static scSpecTypeBytesN(): ScSpecType; + + static scSpecTypeUdt(): ScSpecType; + } + + class ScSpecUdtUnionCaseV0Kind { + readonly name: 'scSpecUdtUnionCaseVoidV0' | 'scSpecUdtUnionCaseTupleV0'; + + readonly value: 0 | 1; + + static scSpecUdtUnionCaseVoidV0(): ScSpecUdtUnionCaseV0Kind; + + static scSpecUdtUnionCaseTupleV0(): ScSpecUdtUnionCaseV0Kind; + } + + class ScSpecEntryKind { + readonly name: + | 'scSpecEntryFunctionV0' + | 'scSpecEntryUdtStructV0' + | 'scSpecEntryUdtUnionV0' + | 'scSpecEntryUdtEnumV0' + | 'scSpecEntryUdtErrorEnumV0'; + + readonly value: 0 | 1 | 2 | 3 | 4; + + static scSpecEntryFunctionV0(): ScSpecEntryKind; + + static scSpecEntryUdtStructV0(): ScSpecEntryKind; + + static scSpecEntryUdtUnionV0(): ScSpecEntryKind; + + static scSpecEntryUdtEnumV0(): ScSpecEntryKind; + + static scSpecEntryUdtErrorEnumV0(): ScSpecEntryKind; + } + + class ContractCostType { + readonly name: + | 'wasmInsnExec' + | 'memAlloc' + | 'memCpy' + | 'memCmp' + | 'dispatchHostFunction' + | 'visitObject' + | 'valSer' + | 'valDeser' + | 'computeSha256Hash' + | 'computeEd25519PubKey' + | 'verifyEd25519Sig' + | 'vmInstantiation' + | 'vmCachedInstantiation' + | 'invokeVmFunction' + | 'computeKeccak256Hash' + | 'decodeEcdsaCurve256Sig' + | 'recoverEcdsaSecp256k1Key' + | 'int256AddSub' + | 'int256Mul' + | 'int256Div' + | 'int256Pow' + | 'int256Shift' + | 'chaCha20DrawBytes' + | 'parseWasmInstructions' + | 'parseWasmFunctions' + | 'parseWasmGlobals' + | 'parseWasmTableEntries' + | 'parseWasmTypes' + | 'parseWasmDataSegments' + | 'parseWasmElemSegments' + | 'parseWasmImports' + | 'parseWasmExports' + | 'parseWasmDataSegmentBytes' + | 'instantiateWasmInstructions' + | 'instantiateWasmFunctions' + | 'instantiateWasmGlobals' + | 'instantiateWasmTableEntries' + | 'instantiateWasmTypes' + | 'instantiateWasmDataSegments' + | 'instantiateWasmElemSegments' + | 'instantiateWasmImports' + | 'instantiateWasmExports' + | 'instantiateWasmDataSegmentBytes' + | 'sec1DecodePointUncompressed' + | 'verifyEcdsaSecp256r1Sig' + | 'bls12381EncodeFp' + | 'bls12381DecodeFp' + | 'bls12381G1CheckPointOnCurve' + | 'bls12381G1CheckPointInSubgroup' + | 'bls12381G2CheckPointOnCurve' + | 'bls12381G2CheckPointInSubgroup' + | 'bls12381G1ProjectiveToAffine' + | 'bls12381G2ProjectiveToAffine' + | 'bls12381G1Add' + | 'bls12381G1Mul' + | 'bls12381G1Msm' + | 'bls12381MapFpToG1' + | 'bls12381HashToG1' + | 'bls12381G2Add' + | 'bls12381G2Mul' + | 'bls12381G2Msm' + | 'bls12381MapFp2ToG2' + | 'bls12381HashToG2' + | 'bls12381Pairing' + | 'bls12381FrFromU256' + | 'bls12381FrToU256' + | 'bls12381FrAddSub' + | 'bls12381FrMul' + | 'bls12381FrPow' + | 'bls12381FrInv'; + + readonly value: + | 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 + | 32 + | 33 + | 34 + | 35 + | 36 + | 37 + | 38 + | 39 + | 40 + | 41 + | 42 + | 43 + | 44 + | 45 + | 46 + | 47 + | 48 + | 49 + | 50 + | 51 + | 52 + | 53 + | 54 + | 55 + | 56 + | 57 + | 58 + | 59 + | 60 + | 61 + | 62 + | 63 + | 64 + | 65 + | 66 + | 67 + | 68 + | 69; + + static wasmInsnExec(): ContractCostType; + + static memAlloc(): ContractCostType; + + static memCpy(): ContractCostType; + + static memCmp(): ContractCostType; + + static dispatchHostFunction(): ContractCostType; + + static visitObject(): ContractCostType; + + static valSer(): ContractCostType; + + static valDeser(): ContractCostType; + + static computeSha256Hash(): ContractCostType; + + static computeEd25519PubKey(): ContractCostType; + + static verifyEd25519Sig(): ContractCostType; + + static vmInstantiation(): ContractCostType; + + static vmCachedInstantiation(): ContractCostType; + + static invokeVmFunction(): ContractCostType; + + static computeKeccak256Hash(): ContractCostType; + + static decodeEcdsaCurve256Sig(): ContractCostType; + + static recoverEcdsaSecp256k1Key(): ContractCostType; + + static int256AddSub(): ContractCostType; + + static int256Mul(): ContractCostType; + + static int256Div(): ContractCostType; + + static int256Pow(): ContractCostType; + + static int256Shift(): ContractCostType; + + static chaCha20DrawBytes(): ContractCostType; + + static parseWasmInstructions(): ContractCostType; + + static parseWasmFunctions(): ContractCostType; + + static parseWasmGlobals(): ContractCostType; + + static parseWasmTableEntries(): ContractCostType; + + static parseWasmTypes(): ContractCostType; + + static parseWasmDataSegments(): ContractCostType; + + static parseWasmElemSegments(): ContractCostType; + + static parseWasmImports(): ContractCostType; + + static parseWasmExports(): ContractCostType; + + static parseWasmDataSegmentBytes(): ContractCostType; + + static instantiateWasmInstructions(): ContractCostType; + + static instantiateWasmFunctions(): ContractCostType; + + static instantiateWasmGlobals(): ContractCostType; + + static instantiateWasmTableEntries(): ContractCostType; + + static instantiateWasmTypes(): ContractCostType; + + static instantiateWasmDataSegments(): ContractCostType; + + static instantiateWasmElemSegments(): ContractCostType; + + static instantiateWasmImports(): ContractCostType; + + static instantiateWasmExports(): ContractCostType; + + static instantiateWasmDataSegmentBytes(): ContractCostType; + + static sec1DecodePointUncompressed(): ContractCostType; + + static verifyEcdsaSecp256r1Sig(): ContractCostType; + + static bls12381EncodeFp(): ContractCostType; + + static bls12381DecodeFp(): ContractCostType; + + static bls12381G1CheckPointOnCurve(): ContractCostType; + + static bls12381G1CheckPointInSubgroup(): ContractCostType; + + static bls12381G2CheckPointOnCurve(): ContractCostType; + + static bls12381G2CheckPointInSubgroup(): ContractCostType; + + static bls12381G1ProjectiveToAffine(): ContractCostType; + + static bls12381G2ProjectiveToAffine(): ContractCostType; + + static bls12381G1Add(): ContractCostType; + + static bls12381G1Mul(): ContractCostType; + + static bls12381G1Msm(): ContractCostType; + + static bls12381MapFpToG1(): ContractCostType; + + static bls12381HashToG1(): ContractCostType; + + static bls12381G2Add(): ContractCostType; + + static bls12381G2Mul(): ContractCostType; + + static bls12381G2Msm(): ContractCostType; + + static bls12381MapFp2ToG2(): ContractCostType; + + static bls12381HashToG2(): ContractCostType; + + static bls12381Pairing(): ContractCostType; + + static bls12381FrFromU256(): ContractCostType; + + static bls12381FrToU256(): ContractCostType; + + static bls12381FrAddSub(): ContractCostType; + + static bls12381FrMul(): ContractCostType; + + static bls12381FrPow(): ContractCostType; + + static bls12381FrInv(): ContractCostType; + } + + class ConfigSettingId { + readonly name: + | 'configSettingContractMaxSizeBytes' + | 'configSettingContractComputeV0' + | 'configSettingContractLedgerCostV0' + | 'configSettingContractHistoricalDataV0' + | 'configSettingContractEventsV0' + | 'configSettingContractBandwidthV0' + | 'configSettingContractCostParamsCpuInstructions' + | 'configSettingContractCostParamsMemoryBytes' + | 'configSettingContractDataKeySizeBytes' + | 'configSettingContractDataEntrySizeBytes' + | 'configSettingStateArchival' + | 'configSettingContractExecutionLanes' + | 'configSettingBucketlistSizeWindow' + | 'configSettingEvictionIterator'; + + readonly value: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13; + + static configSettingContractMaxSizeBytes(): ConfigSettingId; + + static configSettingContractComputeV0(): ConfigSettingId; + + static configSettingContractLedgerCostV0(): ConfigSettingId; + + static configSettingContractHistoricalDataV0(): ConfigSettingId; + + static configSettingContractEventsV0(): ConfigSettingId; + + static configSettingContractBandwidthV0(): ConfigSettingId; + + static configSettingContractCostParamsCpuInstructions(): ConfigSettingId; + + static configSettingContractCostParamsMemoryBytes(): ConfigSettingId; + + static configSettingContractDataKeySizeBytes(): ConfigSettingId; + + static configSettingContractDataEntrySizeBytes(): ConfigSettingId; + + static configSettingStateArchival(): ConfigSettingId; + + static configSettingContractExecutionLanes(): ConfigSettingId; + + static configSettingBucketlistSizeWindow(): ConfigSettingId; + + static configSettingEvictionIterator(): ConfigSettingId; + } + + const Value: VarOpaque; + + const Thresholds: Opaque; + + const String32: XDRString; + + const String64: XDRString; + + type SequenceNumber = Int64; + + const DataValue: VarOpaque; + + type PoolId = Hash; + + const AssetCode4: Opaque; + + const AssetCode12: Opaque; + + type SponsorshipDescriptor = undefined | AccountId; + + const UpgradeType: VarOpaque; + + const LedgerEntryChanges: XDRArray; + + const DiagnosticEvents: XDRArray; + + const EncryptedBody: VarOpaque; + + const PeerStatList: XDRArray; + + const TimeSlicedPeerDataList: XDRArray; + + const TxAdvertVector: XDRArray; + + const TxDemandVector: XDRArray; + + const ProofLevel: XDRArray; + + const Hash: Opaque; + + const Uint256: Opaque; + + const Uint32: UnsignedInt; + + const Int32: SignedInt; + + class Uint64 extends UnsignedHyper {} + + class Int64 extends Hyper {} + + type TimePoint = Uint64; + + type Duration = Uint64; + + const Signature: VarOpaque; + + const SignatureHint: Opaque; + + type NodeId = PublicKey; + + type AccountId = PublicKey; + + const ScVec: XDRArray; + + const ScMap: XDRArray; + + const ScBytes: VarOpaque; + + const ScString: XDRString; + + const ScSymbol: XDRString; + + const ContractCostParams: XDRArray; + + class ScpBallot { + constructor(attributes: { counter: number; value: Buffer }); + + counter(value?: number): number; + + value(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpBallot; + + static write(value: ScpBallot, io: Buffer): void; + + static isValid(value: ScpBallot): boolean; + + static toXDR(value: ScpBallot): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpBallot; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScpBallot; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpNomination { + constructor(attributes: { + quorumSetHash: Buffer; + votes: Buffer[]; + accepted: Buffer[]; + }); + + quorumSetHash(value?: Buffer): Buffer; + + votes(value?: Buffer[]): Buffer[]; + + accepted(value?: Buffer[]): Buffer[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpNomination; + + static write(value: ScpNomination, io: Buffer): void; + + static isValid(value: ScpNomination): boolean; + + static toXDR(value: ScpNomination): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpNomination; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScpNomination; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpStatementPrepare { + constructor(attributes: { + quorumSetHash: Buffer; + ballot: ScpBallot; + prepared: null | ScpBallot; + preparedPrime: null | ScpBallot; + nC: number; + nH: number; + }); + + quorumSetHash(value?: Buffer): Buffer; + + ballot(value?: ScpBallot): ScpBallot; + + prepared(value?: null | ScpBallot): null | ScpBallot; + + preparedPrime(value?: null | ScpBallot): null | ScpBallot; + + nC(value?: number): number; + + nH(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpStatementPrepare; + + static write(value: ScpStatementPrepare, io: Buffer): void; + + static isValid(value: ScpStatementPrepare): boolean; + + static toXDR(value: ScpStatementPrepare): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpStatementPrepare; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScpStatementPrepare; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpStatementConfirm { + constructor(attributes: { + ballot: ScpBallot; + nPrepared: number; + nCommit: number; + nH: number; + quorumSetHash: Buffer; + }); + + ballot(value?: ScpBallot): ScpBallot; + + nPrepared(value?: number): number; + + nCommit(value?: number): number; + + nH(value?: number): number; + + quorumSetHash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpStatementConfirm; + + static write(value: ScpStatementConfirm, io: Buffer): void; + + static isValid(value: ScpStatementConfirm): boolean; + + static toXDR(value: ScpStatementConfirm): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpStatementConfirm; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScpStatementConfirm; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpStatementExternalize { + constructor(attributes: { + commit: ScpBallot; + nH: number; + commitQuorumSetHash: Buffer; + }); + + commit(value?: ScpBallot): ScpBallot; + + nH(value?: number): number; + + commitQuorumSetHash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpStatementExternalize; + + static write(value: ScpStatementExternalize, io: Buffer): void; + + static isValid(value: ScpStatementExternalize): boolean; + + static toXDR(value: ScpStatementExternalize): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpStatementExternalize; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScpStatementExternalize; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpStatement { + constructor(attributes: { + nodeId: NodeId; + slotIndex: Uint64; + pledges: ScpStatementPledges; + }); + + nodeId(value?: NodeId): NodeId; + + slotIndex(value?: Uint64): Uint64; + + pledges(value?: ScpStatementPledges): ScpStatementPledges; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpStatement; + + static write(value: ScpStatement, io: Buffer): void; + + static isValid(value: ScpStatement): boolean; + + static toXDR(value: ScpStatement): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpStatement; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScpStatement; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpEnvelope { + constructor(attributes: { statement: ScpStatement; signature: Buffer }); + + statement(value?: ScpStatement): ScpStatement; + + signature(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpEnvelope; + + static write(value: ScpEnvelope, io: Buffer): void; + + static isValid(value: ScpEnvelope): boolean; + + static toXDR(value: ScpEnvelope): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpEnvelope; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScpEnvelope; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpQuorumSet { + constructor(attributes: { + threshold: number; + validators: NodeId[]; + innerSets: ScpQuorumSet[]; + }); + + threshold(value?: number): number; + + validators(value?: NodeId[]): NodeId[]; + + innerSets(value?: ScpQuorumSet[]): ScpQuorumSet[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpQuorumSet; + + static write(value: ScpQuorumSet, io: Buffer): void; + + static isValid(value: ScpQuorumSet): boolean; + + static toXDR(value: ScpQuorumSet): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpQuorumSet; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScpQuorumSet; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AlphaNum4 { + constructor(attributes: { assetCode: Buffer; issuer: AccountId }); + + assetCode(value?: Buffer): Buffer; + + issuer(value?: AccountId): AccountId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AlphaNum4; + + static write(value: AlphaNum4, io: Buffer): void; + + static isValid(value: AlphaNum4): boolean; + + static toXDR(value: AlphaNum4): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AlphaNum4; + + static fromXDR(input: string, format: 'hex' | 'base64'): AlphaNum4; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AlphaNum12 { + constructor(attributes: { assetCode: Buffer; issuer: AccountId }); + + assetCode(value?: Buffer): Buffer; + + issuer(value?: AccountId): AccountId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AlphaNum12; + + static write(value: AlphaNum12, io: Buffer): void; + + static isValid(value: AlphaNum12): boolean; + + static toXDR(value: AlphaNum12): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AlphaNum12; + + static fromXDR(input: string, format: 'hex' | 'base64'): AlphaNum12; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Price { + constructor(attributes: { n: number; d: number }); + + n(value?: number): number; + + d(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Price; + + static write(value: Price, io: Buffer): void; + + static isValid(value: Price): boolean; + + static toXDR(value: Price): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Price; + + static fromXDR(input: string, format: 'hex' | 'base64'): Price; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Liabilities { + constructor(attributes: { buying: Int64; selling: Int64 }); + + buying(value?: Int64): Int64; + + selling(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Liabilities; + + static write(value: Liabilities, io: Buffer): void; + + static isValid(value: Liabilities): boolean; + + static toXDR(value: Liabilities): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Liabilities; + + static fromXDR(input: string, format: 'hex' | 'base64'): Liabilities; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Signer { + constructor(attributes: { key: SignerKey; weight: number }); + + key(value?: SignerKey): SignerKey; + + weight(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Signer; + + static write(value: Signer, io: Buffer): void; + + static isValid(value: Signer): boolean; + + static toXDR(value: Signer): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Signer; + + static fromXDR(input: string, format: 'hex' | 'base64'): Signer; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountEntryExtensionV3 { + constructor(attributes: { + ext: ExtensionPoint; + seqLedger: number; + seqTime: TimePoint; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + seqLedger(value?: number): number; + + seqTime(value?: TimePoint): TimePoint; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountEntryExtensionV3; + + static write(value: AccountEntryExtensionV3, io: Buffer): void; + + static isValid(value: AccountEntryExtensionV3): boolean; + + static toXDR(value: AccountEntryExtensionV3): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountEntryExtensionV3; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): AccountEntryExtensionV3; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountEntryExtensionV2 { + constructor(attributes: { + numSponsored: number; + numSponsoring: number; + signerSponsoringIDs: SponsorshipDescriptor[]; + ext: AccountEntryExtensionV2Ext; + }); + + numSponsored(value?: number): number; + + numSponsoring(value?: number): number; + + signerSponsoringIDs( + value?: SponsorshipDescriptor[], + ): SponsorshipDescriptor[]; + + ext(value?: AccountEntryExtensionV2Ext): AccountEntryExtensionV2Ext; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountEntryExtensionV2; + + static write(value: AccountEntryExtensionV2, io: Buffer): void; + + static isValid(value: AccountEntryExtensionV2): boolean; + + static toXDR(value: AccountEntryExtensionV2): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountEntryExtensionV2; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): AccountEntryExtensionV2; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountEntryExtensionV1 { + constructor(attributes: { + liabilities: Liabilities; + ext: AccountEntryExtensionV1Ext; + }); + + liabilities(value?: Liabilities): Liabilities; + + ext(value?: AccountEntryExtensionV1Ext): AccountEntryExtensionV1Ext; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountEntryExtensionV1; + + static write(value: AccountEntryExtensionV1, io: Buffer): void; + + static isValid(value: AccountEntryExtensionV1): boolean; + + static toXDR(value: AccountEntryExtensionV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountEntryExtensionV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): AccountEntryExtensionV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountEntry { + constructor(attributes: { + accountId: AccountId; + balance: Int64; + seqNum: SequenceNumber; + numSubEntries: number; + inflationDest: null | AccountId; + flags: number; + homeDomain: string | Buffer; + thresholds: Buffer; + signers: Signer[]; + ext: AccountEntryExt; + }); + + accountId(value?: AccountId): AccountId; + + balance(value?: Int64): Int64; + + seqNum(value?: SequenceNumber): SequenceNumber; + + numSubEntries(value?: number): number; + + inflationDest(value?: null | AccountId): null | AccountId; + + flags(value?: number): number; + + homeDomain(value?: string | Buffer): string | Buffer; + + thresholds(value?: Buffer): Buffer; + + signers(value?: Signer[]): Signer[]; + + ext(value?: AccountEntryExt): AccountEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountEntry; + + static write(value: AccountEntry, io: Buffer): void; + + static isValid(value: AccountEntry): boolean; + + static toXDR(value: AccountEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): AccountEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TrustLineEntryExtensionV2 { + constructor(attributes: { + liquidityPoolUseCount: number; + ext: TrustLineEntryExtensionV2Ext; + }); + + liquidityPoolUseCount(value?: number): number; + + ext(value?: TrustLineEntryExtensionV2Ext): TrustLineEntryExtensionV2Ext; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TrustLineEntryExtensionV2; + + static write(value: TrustLineEntryExtensionV2, io: Buffer): void; + + static isValid(value: TrustLineEntryExtensionV2): boolean; + + static toXDR(value: TrustLineEntryExtensionV2): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TrustLineEntryExtensionV2; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TrustLineEntryExtensionV2; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TrustLineEntryV1 { + constructor(attributes: { + liabilities: Liabilities; + ext: TrustLineEntryV1Ext; + }); + + liabilities(value?: Liabilities): Liabilities; + + ext(value?: TrustLineEntryV1Ext): TrustLineEntryV1Ext; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TrustLineEntryV1; + + static write(value: TrustLineEntryV1, io: Buffer): void; + + static isValid(value: TrustLineEntryV1): boolean; + + static toXDR(value: TrustLineEntryV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TrustLineEntryV1; + + static fromXDR(input: string, format: 'hex' | 'base64'): TrustLineEntryV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TrustLineEntry { + constructor(attributes: { + accountId: AccountId; + asset: TrustLineAsset; + balance: Int64; + limit: Int64; + flags: number; + ext: TrustLineEntryExt; + }); + + accountId(value?: AccountId): AccountId; + + asset(value?: TrustLineAsset): TrustLineAsset; + + balance(value?: Int64): Int64; + + limit(value?: Int64): Int64; + + flags(value?: number): number; + + ext(value?: TrustLineEntryExt): TrustLineEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TrustLineEntry; + + static write(value: TrustLineEntry, io: Buffer): void; + + static isValid(value: TrustLineEntry): boolean; + + static toXDR(value: TrustLineEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TrustLineEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): TrustLineEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class OfferEntry { + constructor(attributes: { + sellerId: AccountId; + offerId: Int64; + selling: Asset; + buying: Asset; + amount: Int64; + price: Price; + flags: number; + ext: OfferEntryExt; + }); + + sellerId(value?: AccountId): AccountId; + + offerId(value?: Int64): Int64; + + selling(value?: Asset): Asset; + + buying(value?: Asset): Asset; + + amount(value?: Int64): Int64; + + price(value?: Price): Price; + + flags(value?: number): number; + + ext(value?: OfferEntryExt): OfferEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): OfferEntry; + + static write(value: OfferEntry, io: Buffer): void; + + static isValid(value: OfferEntry): boolean; + + static toXDR(value: OfferEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): OfferEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): OfferEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class DataEntry { + constructor(attributes: { + accountId: AccountId; + dataName: string | Buffer; + dataValue: Buffer; + ext: DataEntryExt; + }); + + accountId(value?: AccountId): AccountId; + + dataName(value?: string | Buffer): string | Buffer; + + dataValue(value?: Buffer): Buffer; + + ext(value?: DataEntryExt): DataEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): DataEntry; + + static write(value: DataEntry, io: Buffer): void; + + static isValid(value: DataEntry): boolean; + + static toXDR(value: DataEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): DataEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): DataEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimantV0 { + constructor(attributes: { + destination: AccountId; + predicate: ClaimPredicate; + }); + + destination(value?: AccountId): AccountId; + + predicate(value?: ClaimPredicate): ClaimPredicate; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimantV0; + + static write(value: ClaimantV0, io: Buffer): void; + + static isValid(value: ClaimantV0): boolean; + + static toXDR(value: ClaimantV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimantV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClaimantV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimableBalanceEntryExtensionV1 { + constructor(attributes: { + ext: ClaimableBalanceEntryExtensionV1Ext; + flags: number; + }); + + ext( + value?: ClaimableBalanceEntryExtensionV1Ext, + ): ClaimableBalanceEntryExtensionV1Ext; + + flags(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimableBalanceEntryExtensionV1; + + static write(value: ClaimableBalanceEntryExtensionV1, io: Buffer): void; + + static isValid(value: ClaimableBalanceEntryExtensionV1): boolean; + + static toXDR(value: ClaimableBalanceEntryExtensionV1): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ClaimableBalanceEntryExtensionV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClaimableBalanceEntryExtensionV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimableBalanceEntry { + constructor(attributes: { + balanceId: ClaimableBalanceId; + claimants: Claimant[]; + asset: Asset; + amount: Int64; + ext: ClaimableBalanceEntryExt; + }); + + balanceId(value?: ClaimableBalanceId): ClaimableBalanceId; + + claimants(value?: Claimant[]): Claimant[]; + + asset(value?: Asset): Asset; + + amount(value?: Int64): Int64; + + ext(value?: ClaimableBalanceEntryExt): ClaimableBalanceEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimableBalanceEntry; + + static write(value: ClaimableBalanceEntry, io: Buffer): void; + + static isValid(value: ClaimableBalanceEntry): boolean; + + static toXDR(value: ClaimableBalanceEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimableBalanceEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClaimableBalanceEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolConstantProductParameters { + constructor(attributes: { assetA: Asset; assetB: Asset; fee: number }); + + assetA(value?: Asset): Asset; + + assetB(value?: Asset): Asset; + + fee(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolConstantProductParameters; + + static write( + value: LiquidityPoolConstantProductParameters, + io: Buffer, + ): void; + + static isValid(value: LiquidityPoolConstantProductParameters): boolean; + + static toXDR(value: LiquidityPoolConstantProductParameters): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): LiquidityPoolConstantProductParameters; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolConstantProductParameters; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolEntryConstantProduct { + constructor(attributes: { + params: LiquidityPoolConstantProductParameters; + reserveA: Int64; + reserveB: Int64; + totalPoolShares: Int64; + poolSharesTrustLineCount: Int64; + }); + + params( + value?: LiquidityPoolConstantProductParameters, + ): LiquidityPoolConstantProductParameters; + + reserveA(value?: Int64): Int64; + + reserveB(value?: Int64): Int64; + + totalPoolShares(value?: Int64): Int64; + + poolSharesTrustLineCount(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolEntryConstantProduct; + + static write(value: LiquidityPoolEntryConstantProduct, io: Buffer): void; + + static isValid(value: LiquidityPoolEntryConstantProduct): boolean; + + static toXDR(value: LiquidityPoolEntryConstantProduct): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): LiquidityPoolEntryConstantProduct; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolEntryConstantProduct; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolEntry { + constructor(attributes: { + liquidityPoolId: PoolId; + body: LiquidityPoolEntryBody; + }); + + liquidityPoolId(value?: PoolId): PoolId; + + body(value?: LiquidityPoolEntryBody): LiquidityPoolEntryBody; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolEntry; + + static write(value: LiquidityPoolEntry, io: Buffer): void; + + static isValid(value: LiquidityPoolEntry): boolean; + + static toXDR(value: LiquidityPoolEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LiquidityPoolEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): LiquidityPoolEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractDataEntry { + constructor(attributes: { + ext: ExtensionPoint; + contract: ScAddress; + key: ScVal; + durability: ContractDataDurability; + val: ScVal; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + contract(value?: ScAddress): ScAddress; + + key(value?: ScVal): ScVal; + + durability(value?: ContractDataDurability): ContractDataDurability; + + val(value?: ScVal): ScVal; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractDataEntry; + + static write(value: ContractDataEntry, io: Buffer): void; + + static isValid(value: ContractDataEntry): boolean; + + static toXDR(value: ContractDataEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractDataEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ContractDataEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractCodeCostInputs { + constructor(attributes: { + ext: ExtensionPoint; + nInstructions: number; + nFunctions: number; + nGlobals: number; + nTableEntries: number; + nTypes: number; + nDataSegments: number; + nElemSegments: number; + nImports: number; + nExports: number; + nDataSegmentBytes: number; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + nInstructions(value?: number): number; + + nFunctions(value?: number): number; + + nGlobals(value?: number): number; + + nTableEntries(value?: number): number; + + nTypes(value?: number): number; + + nDataSegments(value?: number): number; + + nElemSegments(value?: number): number; + + nImports(value?: number): number; + + nExports(value?: number): number; + + nDataSegmentBytes(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractCodeCostInputs; + + static write(value: ContractCodeCostInputs, io: Buffer): void; + + static isValid(value: ContractCodeCostInputs): boolean; + + static toXDR(value: ContractCodeCostInputs): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractCodeCostInputs; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ContractCodeCostInputs; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractCodeEntryV1 { + constructor(attributes: { + ext: ExtensionPoint; + costInputs: ContractCodeCostInputs; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + costInputs(value?: ContractCodeCostInputs): ContractCodeCostInputs; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractCodeEntryV1; + + static write(value: ContractCodeEntryV1, io: Buffer): void; + + static isValid(value: ContractCodeEntryV1): boolean; + + static toXDR(value: ContractCodeEntryV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractCodeEntryV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ContractCodeEntryV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractCodeEntry { + constructor(attributes: { + ext: ContractCodeEntryExt; + hash: Buffer; + code: Buffer; + }); + + ext(value?: ContractCodeEntryExt): ContractCodeEntryExt; + + hash(value?: Buffer): Buffer; + + code(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractCodeEntry; + + static write(value: ContractCodeEntry, io: Buffer): void; + + static isValid(value: ContractCodeEntry): boolean; + + static toXDR(value: ContractCodeEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractCodeEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ContractCodeEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TtlEntry { + constructor(attributes: { keyHash: Buffer; liveUntilLedgerSeq: number }); + + keyHash(value?: Buffer): Buffer; + + liveUntilLedgerSeq(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TtlEntry; + + static write(value: TtlEntry, io: Buffer): void; + + static isValid(value: TtlEntry): boolean; + + static toXDR(value: TtlEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TtlEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): TtlEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerEntryExtensionV1 { + constructor(attributes: { + sponsoringId: SponsorshipDescriptor; + ext: LedgerEntryExtensionV1Ext; + }); + + sponsoringId(value?: SponsorshipDescriptor): SponsorshipDescriptor; + + ext(value?: LedgerEntryExtensionV1Ext): LedgerEntryExtensionV1Ext; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerEntryExtensionV1; + + static write(value: LedgerEntryExtensionV1, io: Buffer): void; + + static isValid(value: LedgerEntryExtensionV1): boolean; + + static toXDR(value: LedgerEntryExtensionV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerEntryExtensionV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerEntryExtensionV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerEntry { + constructor(attributes: { + lastModifiedLedgerSeq: number; + data: LedgerEntryData; + ext: LedgerEntryExt; + }); + + lastModifiedLedgerSeq(value?: number): number; + + data(value?: LedgerEntryData): LedgerEntryData; + + ext(value?: LedgerEntryExt): LedgerEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerEntry; + + static write(value: LedgerEntry, io: Buffer): void; + + static isValid(value: LedgerEntry): boolean; + + static toXDR(value: LedgerEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyAccount { + constructor(attributes: { accountId: AccountId }); + + accountId(value?: AccountId): AccountId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyAccount; + + static write(value: LedgerKeyAccount, io: Buffer): void; + + static isValid(value: LedgerKeyAccount): boolean; + + static toXDR(value: LedgerKeyAccount): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyAccount; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerKeyAccount; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyTrustLine { + constructor(attributes: { accountId: AccountId; asset: TrustLineAsset }); + + accountId(value?: AccountId): AccountId; + + asset(value?: TrustLineAsset): TrustLineAsset; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyTrustLine; + + static write(value: LedgerKeyTrustLine, io: Buffer): void; + + static isValid(value: LedgerKeyTrustLine): boolean; + + static toXDR(value: LedgerKeyTrustLine): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyTrustLine; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerKeyTrustLine; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyOffer { + constructor(attributes: { sellerId: AccountId; offerId: Int64 }); + + sellerId(value?: AccountId): AccountId; + + offerId(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyOffer; + + static write(value: LedgerKeyOffer, io: Buffer): void; + + static isValid(value: LedgerKeyOffer): boolean; + + static toXDR(value: LedgerKeyOffer): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyOffer; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerKeyOffer; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyData { + constructor(attributes: { + accountId: AccountId; + dataName: string | Buffer; + }); + + accountId(value?: AccountId): AccountId; + + dataName(value?: string | Buffer): string | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyData; + + static write(value: LedgerKeyData, io: Buffer): void; + + static isValid(value: LedgerKeyData): boolean; + + static toXDR(value: LedgerKeyData): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyData; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerKeyData; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyClaimableBalance { + constructor(attributes: { balanceId: ClaimableBalanceId }); + + balanceId(value?: ClaimableBalanceId): ClaimableBalanceId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyClaimableBalance; + + static write(value: LedgerKeyClaimableBalance, io: Buffer): void; + + static isValid(value: LedgerKeyClaimableBalance): boolean; + + static toXDR(value: LedgerKeyClaimableBalance): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyClaimableBalance; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerKeyClaimableBalance; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyLiquidityPool { + constructor(attributes: { liquidityPoolId: PoolId }); + + liquidityPoolId(value?: PoolId): PoolId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyLiquidityPool; + + static write(value: LedgerKeyLiquidityPool, io: Buffer): void; + + static isValid(value: LedgerKeyLiquidityPool): boolean; + + static toXDR(value: LedgerKeyLiquidityPool): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyLiquidityPool; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerKeyLiquidityPool; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyContractData { + constructor(attributes: { + contract: ScAddress; + key: ScVal; + durability: ContractDataDurability; + }); + + contract(value?: ScAddress): ScAddress; + + key(value?: ScVal): ScVal; + + durability(value?: ContractDataDurability): ContractDataDurability; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyContractData; + + static write(value: LedgerKeyContractData, io: Buffer): void; + + static isValid(value: LedgerKeyContractData): boolean; + + static toXDR(value: LedgerKeyContractData): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyContractData; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerKeyContractData; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyContractCode { + constructor(attributes: { hash: Buffer }); + + hash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyContractCode; + + static write(value: LedgerKeyContractCode, io: Buffer): void; + + static isValid(value: LedgerKeyContractCode): boolean; + + static toXDR(value: LedgerKeyContractCode): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyContractCode; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerKeyContractCode; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyConfigSetting { + constructor(attributes: { configSettingId: ConfigSettingId }); + + configSettingId(value?: ConfigSettingId): ConfigSettingId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyConfigSetting; + + static write(value: LedgerKeyConfigSetting, io: Buffer): void; + + static isValid(value: LedgerKeyConfigSetting): boolean; + + static toXDR(value: LedgerKeyConfigSetting): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyConfigSetting; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerKeyConfigSetting; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyTtl { + constructor(attributes: { keyHash: Buffer }); + + keyHash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyTtl; + + static write(value: LedgerKeyTtl, io: Buffer): void; + + static isValid(value: LedgerKeyTtl): boolean; + + static toXDR(value: LedgerKeyTtl): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyTtl; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerKeyTtl; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class BucketMetadata { + constructor(attributes: { ledgerVersion: number; ext: BucketMetadataExt }); + + ledgerVersion(value?: number): number; + + ext(value?: BucketMetadataExt): BucketMetadataExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): BucketMetadata; + + static write(value: BucketMetadata, io: Buffer): void; + + static isValid(value: BucketMetadata): boolean; + + static toXDR(value: BucketMetadata): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): BucketMetadata; + + static fromXDR(input: string, format: 'hex' | 'base64'): BucketMetadata; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ColdArchiveArchivedLeaf { + constructor(attributes: { index: number; archivedEntry: LedgerEntry }); + + index(value?: number): number; + + archivedEntry(value?: LedgerEntry): LedgerEntry; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ColdArchiveArchivedLeaf; + + static write(value: ColdArchiveArchivedLeaf, io: Buffer): void; + + static isValid(value: ColdArchiveArchivedLeaf): boolean; + + static toXDR(value: ColdArchiveArchivedLeaf): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ColdArchiveArchivedLeaf; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ColdArchiveArchivedLeaf; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ColdArchiveDeletedLeaf { + constructor(attributes: { index: number; deletedKey: LedgerKey }); + + index(value?: number): number; + + deletedKey(value?: LedgerKey): LedgerKey; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ColdArchiveDeletedLeaf; + + static write(value: ColdArchiveDeletedLeaf, io: Buffer): void; + + static isValid(value: ColdArchiveDeletedLeaf): boolean; + + static toXDR(value: ColdArchiveDeletedLeaf): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ColdArchiveDeletedLeaf; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ColdArchiveDeletedLeaf; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ColdArchiveBoundaryLeaf { + constructor(attributes: { index: number; isLowerBound: boolean }); + + index(value?: number): number; + + isLowerBound(value?: boolean): boolean; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ColdArchiveBoundaryLeaf; + + static write(value: ColdArchiveBoundaryLeaf, io: Buffer): void; + + static isValid(value: ColdArchiveBoundaryLeaf): boolean; + + static toXDR(value: ColdArchiveBoundaryLeaf): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ColdArchiveBoundaryLeaf; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ColdArchiveBoundaryLeaf; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ColdArchiveHashEntry { + constructor(attributes: { index: number; level: number; hash: Buffer }); + + index(value?: number): number; + + level(value?: number): number; + + hash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ColdArchiveHashEntry; + + static write(value: ColdArchiveHashEntry, io: Buffer): void; + + static isValid(value: ColdArchiveHashEntry): boolean; + + static toXDR(value: ColdArchiveHashEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ColdArchiveHashEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ColdArchiveHashEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerCloseValueSignature { + constructor(attributes: { nodeId: NodeId; signature: Buffer }); + + nodeId(value?: NodeId): NodeId; + + signature(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerCloseValueSignature; + + static write(value: LedgerCloseValueSignature, io: Buffer): void; + + static isValid(value: LedgerCloseValueSignature): boolean; + + static toXDR(value: LedgerCloseValueSignature): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerCloseValueSignature; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerCloseValueSignature; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class StellarValue { + constructor(attributes: { + txSetHash: Buffer; + closeTime: TimePoint; + upgrades: Buffer[]; + ext: StellarValueExt; + }); + + txSetHash(value?: Buffer): Buffer; + + closeTime(value?: TimePoint): TimePoint; + + upgrades(value?: Buffer[]): Buffer[]; + + ext(value?: StellarValueExt): StellarValueExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): StellarValue; + + static write(value: StellarValue, io: Buffer): void; + + static isValid(value: StellarValue): boolean; + + static toXDR(value: StellarValue): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): StellarValue; + + static fromXDR(input: string, format: 'hex' | 'base64'): StellarValue; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerHeaderExtensionV1 { + constructor(attributes: { flags: number; ext: LedgerHeaderExtensionV1Ext }); + + flags(value?: number): number; + + ext(value?: LedgerHeaderExtensionV1Ext): LedgerHeaderExtensionV1Ext; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerHeaderExtensionV1; + + static write(value: LedgerHeaderExtensionV1, io: Buffer): void; + + static isValid(value: LedgerHeaderExtensionV1): boolean; + + static toXDR(value: LedgerHeaderExtensionV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerHeaderExtensionV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerHeaderExtensionV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerHeader { + constructor(attributes: { + ledgerVersion: number; + previousLedgerHash: Buffer; + scpValue: StellarValue; + txSetResultHash: Buffer; + bucketListHash: Buffer; + ledgerSeq: number; + totalCoins: Int64; + feePool: Int64; + inflationSeq: number; + idPool: Uint64; + baseFee: number; + baseReserve: number; + maxTxSetSize: number; + skipList: Buffer[]; + ext: LedgerHeaderExt; + }); + + ledgerVersion(value?: number): number; + + previousLedgerHash(value?: Buffer): Buffer; + + scpValue(value?: StellarValue): StellarValue; + + txSetResultHash(value?: Buffer): Buffer; + + bucketListHash(value?: Buffer): Buffer; + + ledgerSeq(value?: number): number; + + totalCoins(value?: Int64): Int64; + + feePool(value?: Int64): Int64; + + inflationSeq(value?: number): number; + + idPool(value?: Uint64): Uint64; + + baseFee(value?: number): number; + + baseReserve(value?: number): number; + + maxTxSetSize(value?: number): number; + + skipList(value?: Buffer[]): Buffer[]; + + ext(value?: LedgerHeaderExt): LedgerHeaderExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerHeader; + + static write(value: LedgerHeader, io: Buffer): void; + + static isValid(value: LedgerHeader): boolean; + + static toXDR(value: LedgerHeader): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerHeader; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerHeader; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigUpgradeSetKey { + constructor(attributes: { contractId: Buffer; contentHash: Buffer }); + + contractId(value?: Buffer): Buffer; + + contentHash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigUpgradeSetKey; + + static write(value: ConfigUpgradeSetKey, io: Buffer): void; + + static isValid(value: ConfigUpgradeSetKey): boolean; + + static toXDR(value: ConfigUpgradeSetKey): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ConfigUpgradeSetKey; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigUpgradeSetKey; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigUpgradeSet { + constructor(attributes: { updatedEntry: ConfigSettingEntry[] }); + + updatedEntry(value?: ConfigSettingEntry[]): ConfigSettingEntry[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigUpgradeSet; + + static write(value: ConfigUpgradeSet, io: Buffer): void; + + static isValid(value: ConfigUpgradeSet): boolean; + + static toXDR(value: ConfigUpgradeSet): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ConfigUpgradeSet; + + static fromXDR(input: string, format: 'hex' | 'base64'): ConfigUpgradeSet; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TxSetComponentTxsMaybeDiscountedFee { + constructor(attributes: { + baseFee: null | Int64; + txes: TransactionEnvelope[]; + }); + + baseFee(value?: null | Int64): null | Int64; + + txes(value?: TransactionEnvelope[]): TransactionEnvelope[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TxSetComponentTxsMaybeDiscountedFee; + + static write(value: TxSetComponentTxsMaybeDiscountedFee, io: Buffer): void; + + static isValid(value: TxSetComponentTxsMaybeDiscountedFee): boolean; + + static toXDR(value: TxSetComponentTxsMaybeDiscountedFee): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TxSetComponentTxsMaybeDiscountedFee; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TxSetComponentTxsMaybeDiscountedFee; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionSet { + constructor(attributes: { + previousLedgerHash: Buffer; + txes: TransactionEnvelope[]; + }); + + previousLedgerHash(value?: Buffer): Buffer; + + txes(value?: TransactionEnvelope[]): TransactionEnvelope[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionSet; + + static write(value: TransactionSet, io: Buffer): void; + + static isValid(value: TransactionSet): boolean; + + static toXDR(value: TransactionSet): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionSet; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionSet; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionSetV1 { + constructor(attributes: { + previousLedgerHash: Buffer; + phases: TransactionPhase[]; + }); + + previousLedgerHash(value?: Buffer): Buffer; + + phases(value?: TransactionPhase[]): TransactionPhase[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionSetV1; + + static write(value: TransactionSetV1, io: Buffer): void; + + static isValid(value: TransactionSetV1): boolean; + + static toXDR(value: TransactionSetV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionSetV1; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionSetV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionResultPair { + constructor(attributes: { + transactionHash: Buffer; + result: TransactionResult; + }); + + transactionHash(value?: Buffer): Buffer; + + result(value?: TransactionResult): TransactionResult; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionResultPair; + + static write(value: TransactionResultPair, io: Buffer): void; + + static isValid(value: TransactionResultPair): boolean; + + static toXDR(value: TransactionResultPair): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionResultPair; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionResultPair; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionResultSet { + constructor(attributes: { results: TransactionResultPair[] }); + + results(value?: TransactionResultPair[]): TransactionResultPair[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionResultSet; + + static write(value: TransactionResultSet, io: Buffer): void; + + static isValid(value: TransactionResultSet): boolean; + + static toXDR(value: TransactionResultSet): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionResultSet; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionResultSet; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionHistoryEntry { + constructor(attributes: { + ledgerSeq: number; + txSet: TransactionSet; + ext: TransactionHistoryEntryExt; + }); + + ledgerSeq(value?: number): number; + + txSet(value?: TransactionSet): TransactionSet; + + ext(value?: TransactionHistoryEntryExt): TransactionHistoryEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionHistoryEntry; + + static write(value: TransactionHistoryEntry, io: Buffer): void; + + static isValid(value: TransactionHistoryEntry): boolean; + + static toXDR(value: TransactionHistoryEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionHistoryEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionHistoryEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionHistoryResultEntry { + constructor(attributes: { + ledgerSeq: number; + txResultSet: TransactionResultSet; + ext: TransactionHistoryResultEntryExt; + }); + + ledgerSeq(value?: number): number; + + txResultSet(value?: TransactionResultSet): TransactionResultSet; + + ext( + value?: TransactionHistoryResultEntryExt, + ): TransactionHistoryResultEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionHistoryResultEntry; + + static write(value: TransactionHistoryResultEntry, io: Buffer): void; + + static isValid(value: TransactionHistoryResultEntry): boolean; + + static toXDR(value: TransactionHistoryResultEntry): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TransactionHistoryResultEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionHistoryResultEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerHeaderHistoryEntry { + constructor(attributes: { + hash: Buffer; + header: LedgerHeader; + ext: LedgerHeaderHistoryEntryExt; + }); + + hash(value?: Buffer): Buffer; + + header(value?: LedgerHeader): LedgerHeader; + + ext(value?: LedgerHeaderHistoryEntryExt): LedgerHeaderHistoryEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerHeaderHistoryEntry; + + static write(value: LedgerHeaderHistoryEntry, io: Buffer): void; + + static isValid(value: LedgerHeaderHistoryEntry): boolean; + + static toXDR(value: LedgerHeaderHistoryEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerHeaderHistoryEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerHeaderHistoryEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerScpMessages { + constructor(attributes: { ledgerSeq: number; messages: ScpEnvelope[] }); + + ledgerSeq(value?: number): number; + + messages(value?: ScpEnvelope[]): ScpEnvelope[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerScpMessages; + + static write(value: LedgerScpMessages, io: Buffer): void; + + static isValid(value: LedgerScpMessages): boolean; + + static toXDR(value: LedgerScpMessages): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerScpMessages; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerScpMessages; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpHistoryEntryV0 { + constructor(attributes: { + quorumSets: ScpQuorumSet[]; + ledgerMessages: LedgerScpMessages; + }); + + quorumSets(value?: ScpQuorumSet[]): ScpQuorumSet[]; + + ledgerMessages(value?: LedgerScpMessages): LedgerScpMessages; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpHistoryEntryV0; + + static write(value: ScpHistoryEntryV0, io: Buffer): void; + + static isValid(value: ScpHistoryEntryV0): boolean; + + static toXDR(value: ScpHistoryEntryV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpHistoryEntryV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScpHistoryEntryV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class OperationMeta { + constructor(attributes: { changes: LedgerEntryChange[] }); + + changes(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): OperationMeta; + + static write(value: OperationMeta, io: Buffer): void; + + static isValid(value: OperationMeta): boolean; + + static toXDR(value: OperationMeta): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): OperationMeta; + + static fromXDR(input: string, format: 'hex' | 'base64'): OperationMeta; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionMetaV1 { + constructor(attributes: { + txChanges: LedgerEntryChange[]; + operations: OperationMeta[]; + }); + + txChanges(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + operations(value?: OperationMeta[]): OperationMeta[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionMetaV1; + + static write(value: TransactionMetaV1, io: Buffer): void; + + static isValid(value: TransactionMetaV1): boolean; + + static toXDR(value: TransactionMetaV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionMetaV1; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionMetaV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionMetaV2 { + constructor(attributes: { + txChangesBefore: LedgerEntryChange[]; + operations: OperationMeta[]; + txChangesAfter: LedgerEntryChange[]; + }); + + txChangesBefore(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + operations(value?: OperationMeta[]): OperationMeta[]; + + txChangesAfter(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionMetaV2; + + static write(value: TransactionMetaV2, io: Buffer): void; + + static isValid(value: TransactionMetaV2): boolean; + + static toXDR(value: TransactionMetaV2): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionMetaV2; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionMetaV2; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractEventV0 { + constructor(attributes: { topics: ScVal[]; data: ScVal }); + + topics(value?: ScVal[]): ScVal[]; + + data(value?: ScVal): ScVal; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractEventV0; + + static write(value: ContractEventV0, io: Buffer): void; + + static isValid(value: ContractEventV0): boolean; + + static toXDR(value: ContractEventV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractEventV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ContractEventV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractEvent { + constructor(attributes: { + ext: ExtensionPoint; + contractId: null | Buffer; + type: ContractEventType; + body: ContractEventBody; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + contractId(value?: null | Buffer): null | Buffer; + + type(value?: ContractEventType): ContractEventType; + + body(value?: ContractEventBody): ContractEventBody; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractEvent; + + static write(value: ContractEvent, io: Buffer): void; + + static isValid(value: ContractEvent): boolean; + + static toXDR(value: ContractEvent): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractEvent; + + static fromXDR(input: string, format: 'hex' | 'base64'): ContractEvent; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class DiagnosticEvent { + constructor(attributes: { + inSuccessfulContractCall: boolean; + event: ContractEvent; + }); + + inSuccessfulContractCall(value?: boolean): boolean; + + event(value?: ContractEvent): ContractEvent; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): DiagnosticEvent; + + static write(value: DiagnosticEvent, io: Buffer): void; + + static isValid(value: DiagnosticEvent): boolean; + + static toXDR(value: DiagnosticEvent): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): DiagnosticEvent; + + static fromXDR(input: string, format: 'hex' | 'base64'): DiagnosticEvent; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanTransactionMetaExtV1 { + constructor(attributes: { + ext: ExtensionPoint; + totalNonRefundableResourceFeeCharged: Int64; + totalRefundableResourceFeeCharged: Int64; + rentFeeCharged: Int64; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + totalNonRefundableResourceFeeCharged(value?: Int64): Int64; + + totalRefundableResourceFeeCharged(value?: Int64): Int64; + + rentFeeCharged(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanTransactionMetaExtV1; + + static write(value: SorobanTransactionMetaExtV1, io: Buffer): void; + + static isValid(value: SorobanTransactionMetaExtV1): boolean; + + static toXDR(value: SorobanTransactionMetaExtV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanTransactionMetaExtV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanTransactionMetaExtV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanTransactionMeta { + constructor(attributes: { + ext: SorobanTransactionMetaExt; + events: ContractEvent[]; + returnValue: ScVal; + diagnosticEvents: DiagnosticEvent[]; + }); + + ext(value?: SorobanTransactionMetaExt): SorobanTransactionMetaExt; + + events(value?: ContractEvent[]): ContractEvent[]; + + returnValue(value?: ScVal): ScVal; + + diagnosticEvents(value?: DiagnosticEvent[]): DiagnosticEvent[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanTransactionMeta; + + static write(value: SorobanTransactionMeta, io: Buffer): void; + + static isValid(value: SorobanTransactionMeta): boolean; + + static toXDR(value: SorobanTransactionMeta): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanTransactionMeta; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanTransactionMeta; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionMetaV3 { + constructor(attributes: { + ext: ExtensionPoint; + txChangesBefore: LedgerEntryChange[]; + operations: OperationMeta[]; + txChangesAfter: LedgerEntryChange[]; + sorobanMeta: null | SorobanTransactionMeta; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + txChangesBefore(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + operations(value?: OperationMeta[]): OperationMeta[]; + + txChangesAfter(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + sorobanMeta( + value?: null | SorobanTransactionMeta, + ): null | SorobanTransactionMeta; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionMetaV3; + + static write(value: TransactionMetaV3, io: Buffer): void; + + static isValid(value: TransactionMetaV3): boolean; + + static toXDR(value: TransactionMetaV3): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionMetaV3; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionMetaV3; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InvokeHostFunctionSuccessPreImage { + constructor(attributes: { returnValue: ScVal; events: ContractEvent[] }); + + returnValue(value?: ScVal): ScVal; + + events(value?: ContractEvent[]): ContractEvent[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InvokeHostFunctionSuccessPreImage; + + static write(value: InvokeHostFunctionSuccessPreImage, io: Buffer): void; + + static isValid(value: InvokeHostFunctionSuccessPreImage): boolean; + + static toXDR(value: InvokeHostFunctionSuccessPreImage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): InvokeHostFunctionSuccessPreImage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): InvokeHostFunctionSuccessPreImage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionResultMeta { + constructor(attributes: { + result: TransactionResultPair; + feeProcessing: LedgerEntryChange[]; + txApplyProcessing: TransactionMeta; + }); + + result(value?: TransactionResultPair): TransactionResultPair; + + feeProcessing(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + txApplyProcessing(value?: TransactionMeta): TransactionMeta; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionResultMeta; + + static write(value: TransactionResultMeta, io: Buffer): void; + + static isValid(value: TransactionResultMeta): boolean; + + static toXDR(value: TransactionResultMeta): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionResultMeta; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionResultMeta; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class UpgradeEntryMeta { + constructor(attributes: { + upgrade: LedgerUpgrade; + changes: LedgerEntryChange[]; + }); + + upgrade(value?: LedgerUpgrade): LedgerUpgrade; + + changes(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): UpgradeEntryMeta; + + static write(value: UpgradeEntryMeta, io: Buffer): void; + + static isValid(value: UpgradeEntryMeta): boolean; + + static toXDR(value: UpgradeEntryMeta): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): UpgradeEntryMeta; + + static fromXDR(input: string, format: 'hex' | 'base64'): UpgradeEntryMeta; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerCloseMetaV0 { + constructor(attributes: { + ledgerHeader: LedgerHeaderHistoryEntry; + txSet: TransactionSet; + txProcessing: TransactionResultMeta[]; + upgradesProcessing: UpgradeEntryMeta[]; + scpInfo: ScpHistoryEntry[]; + }); + + ledgerHeader(value?: LedgerHeaderHistoryEntry): LedgerHeaderHistoryEntry; + + txSet(value?: TransactionSet): TransactionSet; + + txProcessing(value?: TransactionResultMeta[]): TransactionResultMeta[]; + + upgradesProcessing(value?: UpgradeEntryMeta[]): UpgradeEntryMeta[]; + + scpInfo(value?: ScpHistoryEntry[]): ScpHistoryEntry[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerCloseMetaV0; + + static write(value: LedgerCloseMetaV0, io: Buffer): void; + + static isValid(value: LedgerCloseMetaV0): boolean; + + static toXDR(value: LedgerCloseMetaV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerCloseMetaV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerCloseMetaV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerCloseMetaExtV1 { + constructor(attributes: { ext: ExtensionPoint; sorobanFeeWrite1Kb: Int64 }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + sorobanFeeWrite1Kb(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerCloseMetaExtV1; + + static write(value: LedgerCloseMetaExtV1, io: Buffer): void; + + static isValid(value: LedgerCloseMetaExtV1): boolean; + + static toXDR(value: LedgerCloseMetaExtV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerCloseMetaExtV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerCloseMetaExtV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerCloseMetaV1 { + constructor(attributes: { + ext: LedgerCloseMetaExt; + ledgerHeader: LedgerHeaderHistoryEntry; + txSet: GeneralizedTransactionSet; + txProcessing: TransactionResultMeta[]; + upgradesProcessing: UpgradeEntryMeta[]; + scpInfo: ScpHistoryEntry[]; + totalByteSizeOfBucketList: Uint64; + evictedTemporaryLedgerKeys: LedgerKey[]; + evictedPersistentLedgerEntries: LedgerEntry[]; + }); + + ext(value?: LedgerCloseMetaExt): LedgerCloseMetaExt; + + ledgerHeader(value?: LedgerHeaderHistoryEntry): LedgerHeaderHistoryEntry; + + txSet(value?: GeneralizedTransactionSet): GeneralizedTransactionSet; + + txProcessing(value?: TransactionResultMeta[]): TransactionResultMeta[]; + + upgradesProcessing(value?: UpgradeEntryMeta[]): UpgradeEntryMeta[]; + + scpInfo(value?: ScpHistoryEntry[]): ScpHistoryEntry[]; + + totalByteSizeOfBucketList(value?: Uint64): Uint64; + + evictedTemporaryLedgerKeys(value?: LedgerKey[]): LedgerKey[]; + + evictedPersistentLedgerEntries(value?: LedgerEntry[]): LedgerEntry[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerCloseMetaV1; + + static write(value: LedgerCloseMetaV1, io: Buffer): void; + + static isValid(value: LedgerCloseMetaV1): boolean; + + static toXDR(value: LedgerCloseMetaV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerCloseMetaV1; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerCloseMetaV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Error { + constructor(attributes: { code: ErrorCode; msg: string | Buffer }); + + code(value?: ErrorCode): ErrorCode; + + msg(value?: string | Buffer): string | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Error; + + static write(value: Error, io: Buffer): void; + + static isValid(value: Error): boolean; + + static toXDR(value: Error): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Error; + + static fromXDR(input: string, format: 'hex' | 'base64'): Error; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SendMore { + constructor(attributes: { numMessages: number }); + + numMessages(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SendMore; + + static write(value: SendMore, io: Buffer): void; + + static isValid(value: SendMore): boolean; + + static toXDR(value: SendMore): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SendMore; + + static fromXDR(input: string, format: 'hex' | 'base64'): SendMore; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SendMoreExtended { + constructor(attributes: { numMessages: number; numBytes: number }); + + numMessages(value?: number): number; + + numBytes(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SendMoreExtended; + + static write(value: SendMoreExtended, io: Buffer): void; + + static isValid(value: SendMoreExtended): boolean; + + static toXDR(value: SendMoreExtended): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SendMoreExtended; + + static fromXDR(input: string, format: 'hex' | 'base64'): SendMoreExtended; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AuthCert { + constructor(attributes: { + pubkey: Curve25519Public; + expiration: Uint64; + sig: Buffer; + }); + + pubkey(value?: Curve25519Public): Curve25519Public; + + expiration(value?: Uint64): Uint64; + + sig(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AuthCert; + + static write(value: AuthCert, io: Buffer): void; + + static isValid(value: AuthCert): boolean; + + static toXDR(value: AuthCert): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AuthCert; + + static fromXDR(input: string, format: 'hex' | 'base64'): AuthCert; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Hello { + constructor(attributes: { + ledgerVersion: number; + overlayVersion: number; + overlayMinVersion: number; + networkId: Buffer; + versionStr: string | Buffer; + listeningPort: number; + peerId: NodeId; + cert: AuthCert; + nonce: Buffer; + }); + + ledgerVersion(value?: number): number; + + overlayVersion(value?: number): number; + + overlayMinVersion(value?: number): number; + + networkId(value?: Buffer): Buffer; + + versionStr(value?: string | Buffer): string | Buffer; + + listeningPort(value?: number): number; + + peerId(value?: NodeId): NodeId; + + cert(value?: AuthCert): AuthCert; + + nonce(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Hello; + + static write(value: Hello, io: Buffer): void; + + static isValid(value: Hello): boolean; + + static toXDR(value: Hello): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Hello; + + static fromXDR(input: string, format: 'hex' | 'base64'): Hello; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Auth { + constructor(attributes: { flags: number }); + + flags(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Auth; + + static write(value: Auth, io: Buffer): void; + + static isValid(value: Auth): boolean; + + static toXDR(value: Auth): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Auth; + + static fromXDR(input: string, format: 'hex' | 'base64'): Auth; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PeerAddress { + constructor(attributes: { + ip: PeerAddressIp; + port: number; + numFailures: number; + }); + + ip(value?: PeerAddressIp): PeerAddressIp; + + port(value?: number): number; + + numFailures(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PeerAddress; + + static write(value: PeerAddress, io: Buffer): void; + + static isValid(value: PeerAddress): boolean; + + static toXDR(value: PeerAddress): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PeerAddress; + + static fromXDR(input: string, format: 'hex' | 'base64'): PeerAddress; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class DontHave { + constructor(attributes: { type: MessageType; reqHash: Buffer }); + + type(value?: MessageType): MessageType; + + reqHash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): DontHave; + + static write(value: DontHave, io: Buffer): void; + + static isValid(value: DontHave): boolean; + + static toXDR(value: DontHave): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): DontHave; + + static fromXDR(input: string, format: 'hex' | 'base64'): DontHave; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TimeSlicedSurveyStartCollectingMessage { + constructor(attributes: { + surveyorId: NodeId; + nonce: number; + ledgerNum: number; + }); + + surveyorId(value?: NodeId): NodeId; + + nonce(value?: number): number; + + ledgerNum(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TimeSlicedSurveyStartCollectingMessage; + + static write( + value: TimeSlicedSurveyStartCollectingMessage, + io: Buffer, + ): void; + + static isValid(value: TimeSlicedSurveyStartCollectingMessage): boolean; + + static toXDR(value: TimeSlicedSurveyStartCollectingMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TimeSlicedSurveyStartCollectingMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TimeSlicedSurveyStartCollectingMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignedTimeSlicedSurveyStartCollectingMessage { + constructor(attributes: { + signature: Buffer; + startCollecting: TimeSlicedSurveyStartCollectingMessage; + }); + + signature(value?: Buffer): Buffer; + + startCollecting( + value?: TimeSlicedSurveyStartCollectingMessage, + ): TimeSlicedSurveyStartCollectingMessage; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignedTimeSlicedSurveyStartCollectingMessage; + + static write( + value: SignedTimeSlicedSurveyStartCollectingMessage, + io: Buffer, + ): void; + + static isValid( + value: SignedTimeSlicedSurveyStartCollectingMessage, + ): boolean; + + static toXDR(value: SignedTimeSlicedSurveyStartCollectingMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): SignedTimeSlicedSurveyStartCollectingMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SignedTimeSlicedSurveyStartCollectingMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TimeSlicedSurveyStopCollectingMessage { + constructor(attributes: { + surveyorId: NodeId; + nonce: number; + ledgerNum: number; + }); + + surveyorId(value?: NodeId): NodeId; + + nonce(value?: number): number; + + ledgerNum(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TimeSlicedSurveyStopCollectingMessage; + + static write( + value: TimeSlicedSurveyStopCollectingMessage, + io: Buffer, + ): void; + + static isValid(value: TimeSlicedSurveyStopCollectingMessage): boolean; + + static toXDR(value: TimeSlicedSurveyStopCollectingMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TimeSlicedSurveyStopCollectingMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TimeSlicedSurveyStopCollectingMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignedTimeSlicedSurveyStopCollectingMessage { + constructor(attributes: { + signature: Buffer; + stopCollecting: TimeSlicedSurveyStopCollectingMessage; + }); + + signature(value?: Buffer): Buffer; + + stopCollecting( + value?: TimeSlicedSurveyStopCollectingMessage, + ): TimeSlicedSurveyStopCollectingMessage; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignedTimeSlicedSurveyStopCollectingMessage; + + static write( + value: SignedTimeSlicedSurveyStopCollectingMessage, + io: Buffer, + ): void; + + static isValid(value: SignedTimeSlicedSurveyStopCollectingMessage): boolean; + + static toXDR(value: SignedTimeSlicedSurveyStopCollectingMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): SignedTimeSlicedSurveyStopCollectingMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SignedTimeSlicedSurveyStopCollectingMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SurveyRequestMessage { + constructor(attributes: { + surveyorPeerId: NodeId; + surveyedPeerId: NodeId; + ledgerNum: number; + encryptionKey: Curve25519Public; + commandType: SurveyMessageCommandType; + }); + + surveyorPeerId(value?: NodeId): NodeId; + + surveyedPeerId(value?: NodeId): NodeId; + + ledgerNum(value?: number): number; + + encryptionKey(value?: Curve25519Public): Curve25519Public; + + commandType(value?: SurveyMessageCommandType): SurveyMessageCommandType; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SurveyRequestMessage; + + static write(value: SurveyRequestMessage, io: Buffer): void; + + static isValid(value: SurveyRequestMessage): boolean; + + static toXDR(value: SurveyRequestMessage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SurveyRequestMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SurveyRequestMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TimeSlicedSurveyRequestMessage { + constructor(attributes: { + request: SurveyRequestMessage; + nonce: number; + inboundPeersIndex: number; + outboundPeersIndex: number; + }); + + request(value?: SurveyRequestMessage): SurveyRequestMessage; + + nonce(value?: number): number; + + inboundPeersIndex(value?: number): number; + + outboundPeersIndex(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TimeSlicedSurveyRequestMessage; + + static write(value: TimeSlicedSurveyRequestMessage, io: Buffer): void; + + static isValid(value: TimeSlicedSurveyRequestMessage): boolean; + + static toXDR(value: TimeSlicedSurveyRequestMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TimeSlicedSurveyRequestMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TimeSlicedSurveyRequestMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignedSurveyRequestMessage { + constructor(attributes: { + requestSignature: Buffer; + request: SurveyRequestMessage; + }); + + requestSignature(value?: Buffer): Buffer; + + request(value?: SurveyRequestMessage): SurveyRequestMessage; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignedSurveyRequestMessage; + + static write(value: SignedSurveyRequestMessage, io: Buffer): void; + + static isValid(value: SignedSurveyRequestMessage): boolean; + + static toXDR(value: SignedSurveyRequestMessage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SignedSurveyRequestMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SignedSurveyRequestMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignedTimeSlicedSurveyRequestMessage { + constructor(attributes: { + requestSignature: Buffer; + request: TimeSlicedSurveyRequestMessage; + }); + + requestSignature(value?: Buffer): Buffer; + + request( + value?: TimeSlicedSurveyRequestMessage, + ): TimeSlicedSurveyRequestMessage; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignedTimeSlicedSurveyRequestMessage; + + static write(value: SignedTimeSlicedSurveyRequestMessage, io: Buffer): void; + + static isValid(value: SignedTimeSlicedSurveyRequestMessage): boolean; + + static toXDR(value: SignedTimeSlicedSurveyRequestMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): SignedTimeSlicedSurveyRequestMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SignedTimeSlicedSurveyRequestMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SurveyResponseMessage { + constructor(attributes: { + surveyorPeerId: NodeId; + surveyedPeerId: NodeId; + ledgerNum: number; + commandType: SurveyMessageCommandType; + encryptedBody: Buffer; + }); + + surveyorPeerId(value?: NodeId): NodeId; + + surveyedPeerId(value?: NodeId): NodeId; + + ledgerNum(value?: number): number; + + commandType(value?: SurveyMessageCommandType): SurveyMessageCommandType; + + encryptedBody(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SurveyResponseMessage; + + static write(value: SurveyResponseMessage, io: Buffer): void; + + static isValid(value: SurveyResponseMessage): boolean; + + static toXDR(value: SurveyResponseMessage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SurveyResponseMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SurveyResponseMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TimeSlicedSurveyResponseMessage { + constructor(attributes: { response: SurveyResponseMessage; nonce: number }); + + response(value?: SurveyResponseMessage): SurveyResponseMessage; + + nonce(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TimeSlicedSurveyResponseMessage; + + static write(value: TimeSlicedSurveyResponseMessage, io: Buffer): void; + + static isValid(value: TimeSlicedSurveyResponseMessage): boolean; + + static toXDR(value: TimeSlicedSurveyResponseMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TimeSlicedSurveyResponseMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TimeSlicedSurveyResponseMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignedSurveyResponseMessage { + constructor(attributes: { + responseSignature: Buffer; + response: SurveyResponseMessage; + }); + + responseSignature(value?: Buffer): Buffer; + + response(value?: SurveyResponseMessage): SurveyResponseMessage; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignedSurveyResponseMessage; + + static write(value: SignedSurveyResponseMessage, io: Buffer): void; + + static isValid(value: SignedSurveyResponseMessage): boolean; + + static toXDR(value: SignedSurveyResponseMessage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SignedSurveyResponseMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SignedSurveyResponseMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignedTimeSlicedSurveyResponseMessage { + constructor(attributes: { + responseSignature: Buffer; + response: TimeSlicedSurveyResponseMessage; + }); + + responseSignature(value?: Buffer): Buffer; + + response( + value?: TimeSlicedSurveyResponseMessage, + ): TimeSlicedSurveyResponseMessage; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignedTimeSlicedSurveyResponseMessage; + + static write( + value: SignedTimeSlicedSurveyResponseMessage, + io: Buffer, + ): void; + + static isValid(value: SignedTimeSlicedSurveyResponseMessage): boolean; + + static toXDR(value: SignedTimeSlicedSurveyResponseMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): SignedTimeSlicedSurveyResponseMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SignedTimeSlicedSurveyResponseMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PeerStats { + constructor(attributes: { + id: NodeId; + versionStr: string | Buffer; + messagesRead: Uint64; + messagesWritten: Uint64; + bytesRead: Uint64; + bytesWritten: Uint64; + secondsConnected: Uint64; + uniqueFloodBytesRecv: Uint64; + duplicateFloodBytesRecv: Uint64; + uniqueFetchBytesRecv: Uint64; + duplicateFetchBytesRecv: Uint64; + uniqueFloodMessageRecv: Uint64; + duplicateFloodMessageRecv: Uint64; + uniqueFetchMessageRecv: Uint64; + duplicateFetchMessageRecv: Uint64; + }); + + id(value?: NodeId): NodeId; + + versionStr(value?: string | Buffer): string | Buffer; + + messagesRead(value?: Uint64): Uint64; + + messagesWritten(value?: Uint64): Uint64; + + bytesRead(value?: Uint64): Uint64; + + bytesWritten(value?: Uint64): Uint64; + + secondsConnected(value?: Uint64): Uint64; + + uniqueFloodBytesRecv(value?: Uint64): Uint64; + + duplicateFloodBytesRecv(value?: Uint64): Uint64; + + uniqueFetchBytesRecv(value?: Uint64): Uint64; + + duplicateFetchBytesRecv(value?: Uint64): Uint64; + + uniqueFloodMessageRecv(value?: Uint64): Uint64; + + duplicateFloodMessageRecv(value?: Uint64): Uint64; + + uniqueFetchMessageRecv(value?: Uint64): Uint64; + + duplicateFetchMessageRecv(value?: Uint64): Uint64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PeerStats; + + static write(value: PeerStats, io: Buffer): void; + + static isValid(value: PeerStats): boolean; + + static toXDR(value: PeerStats): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PeerStats; + + static fromXDR(input: string, format: 'hex' | 'base64'): PeerStats; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TimeSlicedNodeData { + constructor(attributes: { + addedAuthenticatedPeers: number; + droppedAuthenticatedPeers: number; + totalInboundPeerCount: number; + totalOutboundPeerCount: number; + p75ScpFirstToSelfLatencyMs: number; + p75ScpSelfToOtherLatencyMs: number; + lostSyncCount: number; + isValidator: boolean; + maxInboundPeerCount: number; + maxOutboundPeerCount: number; + }); + + addedAuthenticatedPeers(value?: number): number; + + droppedAuthenticatedPeers(value?: number): number; + + totalInboundPeerCount(value?: number): number; + + totalOutboundPeerCount(value?: number): number; + + p75ScpFirstToSelfLatencyMs(value?: number): number; + + p75ScpSelfToOtherLatencyMs(value?: number): number; + + lostSyncCount(value?: number): number; + + isValidator(value?: boolean): boolean; + + maxInboundPeerCount(value?: number): number; + + maxOutboundPeerCount(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TimeSlicedNodeData; + + static write(value: TimeSlicedNodeData, io: Buffer): void; + + static isValid(value: TimeSlicedNodeData): boolean; + + static toXDR(value: TimeSlicedNodeData): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TimeSlicedNodeData; + + static fromXDR(input: string, format: 'hex' | 'base64'): TimeSlicedNodeData; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TimeSlicedPeerData { + constructor(attributes: { peerStats: PeerStats; averageLatencyMs: number }); + + peerStats(value?: PeerStats): PeerStats; + + averageLatencyMs(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TimeSlicedPeerData; + + static write(value: TimeSlicedPeerData, io: Buffer): void; + + static isValid(value: TimeSlicedPeerData): boolean; + + static toXDR(value: TimeSlicedPeerData): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TimeSlicedPeerData; + + static fromXDR(input: string, format: 'hex' | 'base64'): TimeSlicedPeerData; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TopologyResponseBodyV0 { + constructor(attributes: { + inboundPeers: PeerStats[]; + outboundPeers: PeerStats[]; + totalInboundPeerCount: number; + totalOutboundPeerCount: number; + }); + + inboundPeers(value?: PeerStats[]): PeerStats[]; + + outboundPeers(value?: PeerStats[]): PeerStats[]; + + totalInboundPeerCount(value?: number): number; + + totalOutboundPeerCount(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TopologyResponseBodyV0; + + static write(value: TopologyResponseBodyV0, io: Buffer): void; + + static isValid(value: TopologyResponseBodyV0): boolean; + + static toXDR(value: TopologyResponseBodyV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TopologyResponseBodyV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TopologyResponseBodyV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TopologyResponseBodyV1 { + constructor(attributes: { + inboundPeers: PeerStats[]; + outboundPeers: PeerStats[]; + totalInboundPeerCount: number; + totalOutboundPeerCount: number; + maxInboundPeerCount: number; + maxOutboundPeerCount: number; + }); + + inboundPeers(value?: PeerStats[]): PeerStats[]; + + outboundPeers(value?: PeerStats[]): PeerStats[]; + + totalInboundPeerCount(value?: number): number; + + totalOutboundPeerCount(value?: number): number; + + maxInboundPeerCount(value?: number): number; + + maxOutboundPeerCount(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TopologyResponseBodyV1; + + static write(value: TopologyResponseBodyV1, io: Buffer): void; + + static isValid(value: TopologyResponseBodyV1): boolean; + + static toXDR(value: TopologyResponseBodyV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TopologyResponseBodyV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TopologyResponseBodyV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TopologyResponseBodyV2 { + constructor(attributes: { + inboundPeers: TimeSlicedPeerData[]; + outboundPeers: TimeSlicedPeerData[]; + nodeData: TimeSlicedNodeData; + }); + + inboundPeers(value?: TimeSlicedPeerData[]): TimeSlicedPeerData[]; + + outboundPeers(value?: TimeSlicedPeerData[]): TimeSlicedPeerData[]; + + nodeData(value?: TimeSlicedNodeData): TimeSlicedNodeData; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TopologyResponseBodyV2; + + static write(value: TopologyResponseBodyV2, io: Buffer): void; + + static isValid(value: TopologyResponseBodyV2): boolean; + + static toXDR(value: TopologyResponseBodyV2): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TopologyResponseBodyV2; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TopologyResponseBodyV2; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class FloodAdvert { + constructor(attributes: { txHashes: Hash[] }); + + txHashes(value?: Hash[]): Hash[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): FloodAdvert; + + static write(value: FloodAdvert, io: Buffer): void; + + static isValid(value: FloodAdvert): boolean; + + static toXDR(value: FloodAdvert): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): FloodAdvert; + + static fromXDR(input: string, format: 'hex' | 'base64'): FloodAdvert; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class FloodDemand { + constructor(attributes: { txHashes: Hash[] }); + + txHashes(value?: Hash[]): Hash[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): FloodDemand; + + static write(value: FloodDemand, io: Buffer): void; + + static isValid(value: FloodDemand): boolean; + + static toXDR(value: FloodDemand): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): FloodDemand; + + static fromXDR(input: string, format: 'hex' | 'base64'): FloodDemand; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AuthenticatedMessageV0 { + constructor(attributes: { + sequence: Uint64; + message: StellarMessage; + mac: HmacSha256Mac; + }); + + sequence(value?: Uint64): Uint64; + + message(value?: StellarMessage): StellarMessage; + + mac(value?: HmacSha256Mac): HmacSha256Mac; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AuthenticatedMessageV0; + + static write(value: AuthenticatedMessageV0, io: Buffer): void; + + static isValid(value: AuthenticatedMessageV0): boolean; + + static toXDR(value: AuthenticatedMessageV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AuthenticatedMessageV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): AuthenticatedMessageV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class MuxedAccountMed25519 { + constructor(attributes: { id: Uint64; ed25519: Buffer }); + + id(value?: Uint64): Uint64; + + ed25519(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): MuxedAccountMed25519; + + static write(value: MuxedAccountMed25519, io: Buffer): void; + + static isValid(value: MuxedAccountMed25519): boolean; + + static toXDR(value: MuxedAccountMed25519): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): MuxedAccountMed25519; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): MuxedAccountMed25519; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class DecoratedSignature { + constructor(attributes: { hint: Buffer; signature: Buffer }); + + hint(value?: Buffer): Buffer; + + signature(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): DecoratedSignature; + + static write(value: DecoratedSignature, io: Buffer): void; + + static isValid(value: DecoratedSignature): boolean; + + static toXDR(value: DecoratedSignature): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): DecoratedSignature; + + static fromXDR(input: string, format: 'hex' | 'base64'): DecoratedSignature; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class CreateAccountOp { + constructor(attributes: { destination: AccountId; startingBalance: Int64 }); + + destination(value?: AccountId): AccountId; + + startingBalance(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): CreateAccountOp; + + static write(value: CreateAccountOp, io: Buffer): void; + + static isValid(value: CreateAccountOp): boolean; + + static toXDR(value: CreateAccountOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): CreateAccountOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): CreateAccountOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PaymentOp { + constructor(attributes: { + destination: MuxedAccount; + asset: Asset; + amount: Int64; + }); + + destination(value?: MuxedAccount): MuxedAccount; + + asset(value?: Asset): Asset; + + amount(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PaymentOp; + + static write(value: PaymentOp, io: Buffer): void; + + static isValid(value: PaymentOp): boolean; + + static toXDR(value: PaymentOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PaymentOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): PaymentOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PathPaymentStrictReceiveOp { + constructor(attributes: { + sendAsset: Asset; + sendMax: Int64; + destination: MuxedAccount; + destAsset: Asset; + destAmount: Int64; + path: Asset[]; + }); + + sendAsset(value?: Asset): Asset; + + sendMax(value?: Int64): Int64; + + destination(value?: MuxedAccount): MuxedAccount; + + destAsset(value?: Asset): Asset; + + destAmount(value?: Int64): Int64; + + path(value?: Asset[]): Asset[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PathPaymentStrictReceiveOp; + + static write(value: PathPaymentStrictReceiveOp, io: Buffer): void; + + static isValid(value: PathPaymentStrictReceiveOp): boolean; + + static toXDR(value: PathPaymentStrictReceiveOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PathPaymentStrictReceiveOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): PathPaymentStrictReceiveOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PathPaymentStrictSendOp { + constructor(attributes: { + sendAsset: Asset; + sendAmount: Int64; + destination: MuxedAccount; + destAsset: Asset; + destMin: Int64; + path: Asset[]; + }); + + sendAsset(value?: Asset): Asset; + + sendAmount(value?: Int64): Int64; + + destination(value?: MuxedAccount): MuxedAccount; + + destAsset(value?: Asset): Asset; + + destMin(value?: Int64): Int64; + + path(value?: Asset[]): Asset[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PathPaymentStrictSendOp; + + static write(value: PathPaymentStrictSendOp, io: Buffer): void; + + static isValid(value: PathPaymentStrictSendOp): boolean; + + static toXDR(value: PathPaymentStrictSendOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PathPaymentStrictSendOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): PathPaymentStrictSendOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageSellOfferOp { + constructor(attributes: { + selling: Asset; + buying: Asset; + amount: Int64; + price: Price; + offerId: Int64; + }); + + selling(value?: Asset): Asset; + + buying(value?: Asset): Asset; + + amount(value?: Int64): Int64; + + price(value?: Price): Price; + + offerId(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageSellOfferOp; + + static write(value: ManageSellOfferOp, io: Buffer): void; + + static isValid(value: ManageSellOfferOp): boolean; + + static toXDR(value: ManageSellOfferOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ManageSellOfferOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): ManageSellOfferOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageBuyOfferOp { + constructor(attributes: { + selling: Asset; + buying: Asset; + buyAmount: Int64; + price: Price; + offerId: Int64; + }); + + selling(value?: Asset): Asset; + + buying(value?: Asset): Asset; + + buyAmount(value?: Int64): Int64; + + price(value?: Price): Price; + + offerId(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageBuyOfferOp; + + static write(value: ManageBuyOfferOp, io: Buffer): void; + + static isValid(value: ManageBuyOfferOp): boolean; + + static toXDR(value: ManageBuyOfferOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ManageBuyOfferOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): ManageBuyOfferOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class CreatePassiveSellOfferOp { + constructor(attributes: { + selling: Asset; + buying: Asset; + amount: Int64; + price: Price; + }); + + selling(value?: Asset): Asset; + + buying(value?: Asset): Asset; + + amount(value?: Int64): Int64; + + price(value?: Price): Price; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): CreatePassiveSellOfferOp; + + static write(value: CreatePassiveSellOfferOp, io: Buffer): void; + + static isValid(value: CreatePassiveSellOfferOp): boolean; + + static toXDR(value: CreatePassiveSellOfferOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): CreatePassiveSellOfferOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): CreatePassiveSellOfferOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SetOptionsOp { + constructor(attributes: { + inflationDest: null | AccountId; + clearFlags: null | number; + setFlags: null | number; + masterWeight: null | number; + lowThreshold: null | number; + medThreshold: null | number; + highThreshold: null | number; + homeDomain: null | string | Buffer; + signer: null | Signer; + }); + + inflationDest(value?: null | AccountId): null | AccountId; + + clearFlags(value?: null | number): null | number; + + setFlags(value?: null | number): null | number; + + masterWeight(value?: null | number): null | number; + + lowThreshold(value?: null | number): null | number; + + medThreshold(value?: null | number): null | number; + + highThreshold(value?: null | number): null | number; + + homeDomain(value?: null | string | Buffer): null | string | Buffer; + + signer(value?: null | Signer): null | Signer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SetOptionsOp; + + static write(value: SetOptionsOp, io: Buffer): void; + + static isValid(value: SetOptionsOp): boolean; + + static toXDR(value: SetOptionsOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SetOptionsOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): SetOptionsOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ChangeTrustOp { + constructor(attributes: { line: ChangeTrustAsset; limit: Int64 }); + + line(value?: ChangeTrustAsset): ChangeTrustAsset; + + limit(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ChangeTrustOp; + + static write(value: ChangeTrustOp, io: Buffer): void; + + static isValid(value: ChangeTrustOp): boolean; + + static toXDR(value: ChangeTrustOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ChangeTrustOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): ChangeTrustOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AllowTrustOp { + constructor(attributes: { + trustor: AccountId; + asset: AssetCode; + authorize: number; + }); + + trustor(value?: AccountId): AccountId; + + asset(value?: AssetCode): AssetCode; + + authorize(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AllowTrustOp; + + static write(value: AllowTrustOp, io: Buffer): void; + + static isValid(value: AllowTrustOp): boolean; + + static toXDR(value: AllowTrustOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AllowTrustOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): AllowTrustOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageDataOp { + constructor(attributes: { + dataName: string | Buffer; + dataValue: null | Buffer; + }); + + dataName(value?: string | Buffer): string | Buffer; + + dataValue(value?: null | Buffer): null | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageDataOp; + + static write(value: ManageDataOp, io: Buffer): void; + + static isValid(value: ManageDataOp): boolean; + + static toXDR(value: ManageDataOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ManageDataOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): ManageDataOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class BumpSequenceOp { + constructor(attributes: { bumpTo: SequenceNumber }); + + bumpTo(value?: SequenceNumber): SequenceNumber; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): BumpSequenceOp; + + static write(value: BumpSequenceOp, io: Buffer): void; + + static isValid(value: BumpSequenceOp): boolean; + + static toXDR(value: BumpSequenceOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): BumpSequenceOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): BumpSequenceOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class CreateClaimableBalanceOp { + constructor(attributes: { + asset: Asset; + amount: Int64; + claimants: Claimant[]; + }); + + asset(value?: Asset): Asset; + + amount(value?: Int64): Int64; + + claimants(value?: Claimant[]): Claimant[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): CreateClaimableBalanceOp; + + static write(value: CreateClaimableBalanceOp, io: Buffer): void; + + static isValid(value: CreateClaimableBalanceOp): boolean; + + static toXDR(value: CreateClaimableBalanceOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): CreateClaimableBalanceOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): CreateClaimableBalanceOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimClaimableBalanceOp { + constructor(attributes: { balanceId: ClaimableBalanceId }); + + balanceId(value?: ClaimableBalanceId): ClaimableBalanceId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimClaimableBalanceOp; + + static write(value: ClaimClaimableBalanceOp, io: Buffer): void; + + static isValid(value: ClaimClaimableBalanceOp): boolean; + + static toXDR(value: ClaimClaimableBalanceOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimClaimableBalanceOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClaimClaimableBalanceOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class BeginSponsoringFutureReservesOp { + constructor(attributes: { sponsoredId: AccountId }); + + sponsoredId(value?: AccountId): AccountId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): BeginSponsoringFutureReservesOp; + + static write(value: BeginSponsoringFutureReservesOp, io: Buffer): void; + + static isValid(value: BeginSponsoringFutureReservesOp): boolean; + + static toXDR(value: BeginSponsoringFutureReservesOp): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): BeginSponsoringFutureReservesOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): BeginSponsoringFutureReservesOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class RevokeSponsorshipOpSigner { + constructor(attributes: { accountId: AccountId; signerKey: SignerKey }); + + accountId(value?: AccountId): AccountId; + + signerKey(value?: SignerKey): SignerKey; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): RevokeSponsorshipOpSigner; + + static write(value: RevokeSponsorshipOpSigner, io: Buffer): void; + + static isValid(value: RevokeSponsorshipOpSigner): boolean; + + static toXDR(value: RevokeSponsorshipOpSigner): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): RevokeSponsorshipOpSigner; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): RevokeSponsorshipOpSigner; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClawbackOp { + constructor(attributes: { + asset: Asset; + from: MuxedAccount; + amount: Int64; + }); + + asset(value?: Asset): Asset; + + from(value?: MuxedAccount): MuxedAccount; + + amount(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClawbackOp; + + static write(value: ClawbackOp, io: Buffer): void; + + static isValid(value: ClawbackOp): boolean; + + static toXDR(value: ClawbackOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClawbackOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClawbackOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClawbackClaimableBalanceOp { + constructor(attributes: { balanceId: ClaimableBalanceId }); + + balanceId(value?: ClaimableBalanceId): ClaimableBalanceId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClawbackClaimableBalanceOp; + + static write(value: ClawbackClaimableBalanceOp, io: Buffer): void; + + static isValid(value: ClawbackClaimableBalanceOp): boolean; + + static toXDR(value: ClawbackClaimableBalanceOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClawbackClaimableBalanceOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClawbackClaimableBalanceOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SetTrustLineFlagsOp { + constructor(attributes: { + trustor: AccountId; + asset: Asset; + clearFlags: number; + setFlags: number; + }); + + trustor(value?: AccountId): AccountId; + + asset(value?: Asset): Asset; + + clearFlags(value?: number): number; + + setFlags(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SetTrustLineFlagsOp; + + static write(value: SetTrustLineFlagsOp, io: Buffer): void; + + static isValid(value: SetTrustLineFlagsOp): boolean; + + static toXDR(value: SetTrustLineFlagsOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SetTrustLineFlagsOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SetTrustLineFlagsOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolDepositOp { + constructor(attributes: { + liquidityPoolId: PoolId; + maxAmountA: Int64; + maxAmountB: Int64; + minPrice: Price; + maxPrice: Price; + }); + + liquidityPoolId(value?: PoolId): PoolId; + + maxAmountA(value?: Int64): Int64; + + maxAmountB(value?: Int64): Int64; + + minPrice(value?: Price): Price; + + maxPrice(value?: Price): Price; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolDepositOp; + + static write(value: LiquidityPoolDepositOp, io: Buffer): void; + + static isValid(value: LiquidityPoolDepositOp): boolean; + + static toXDR(value: LiquidityPoolDepositOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LiquidityPoolDepositOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolDepositOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolWithdrawOp { + constructor(attributes: { + liquidityPoolId: PoolId; + amount: Int64; + minAmountA: Int64; + minAmountB: Int64; + }); + + liquidityPoolId(value?: PoolId): PoolId; + + amount(value?: Int64): Int64; + + minAmountA(value?: Int64): Int64; + + minAmountB(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolWithdrawOp; + + static write(value: LiquidityPoolWithdrawOp, io: Buffer): void; + + static isValid(value: LiquidityPoolWithdrawOp): boolean; + + static toXDR(value: LiquidityPoolWithdrawOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LiquidityPoolWithdrawOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolWithdrawOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractIdPreimageFromAddress { + constructor(attributes: { address: ScAddress; salt: Buffer }); + + address(value?: ScAddress): ScAddress; + + salt(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractIdPreimageFromAddress; + + static write(value: ContractIdPreimageFromAddress, io: Buffer): void; + + static isValid(value: ContractIdPreimageFromAddress): boolean; + + static toXDR(value: ContractIdPreimageFromAddress): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ContractIdPreimageFromAddress; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ContractIdPreimageFromAddress; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class CreateContractArgs { + constructor(attributes: { + contractIdPreimage: ContractIdPreimage; + executable: ContractExecutable; + }); + + contractIdPreimage(value?: ContractIdPreimage): ContractIdPreimage; + + executable(value?: ContractExecutable): ContractExecutable; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): CreateContractArgs; + + static write(value: CreateContractArgs, io: Buffer): void; + + static isValid(value: CreateContractArgs): boolean; + + static toXDR(value: CreateContractArgs): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): CreateContractArgs; + + static fromXDR(input: string, format: 'hex' | 'base64'): CreateContractArgs; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class CreateContractArgsV2 { + constructor(attributes: { + contractIdPreimage: ContractIdPreimage; + executable: ContractExecutable; + constructorArgs: ScVal[]; + }); + + contractIdPreimage(value?: ContractIdPreimage): ContractIdPreimage; + + executable(value?: ContractExecutable): ContractExecutable; + + constructorArgs(value?: ScVal[]): ScVal[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): CreateContractArgsV2; + + static write(value: CreateContractArgsV2, io: Buffer): void; + + static isValid(value: CreateContractArgsV2): boolean; + + static toXDR(value: CreateContractArgsV2): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): CreateContractArgsV2; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): CreateContractArgsV2; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InvokeContractArgs { + constructor(attributes: { + contractAddress: ScAddress; + functionName: string | Buffer; + args: ScVal[]; + }); + + contractAddress(value?: ScAddress): ScAddress; + + functionName(value?: string | Buffer): string | Buffer; + + args(value?: ScVal[]): ScVal[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InvokeContractArgs; + + static write(value: InvokeContractArgs, io: Buffer): void; + + static isValid(value: InvokeContractArgs): boolean; + + static toXDR(value: InvokeContractArgs): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InvokeContractArgs; + + static fromXDR(input: string, format: 'hex' | 'base64'): InvokeContractArgs; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanAuthorizedInvocation { + constructor(attributes: { + function: SorobanAuthorizedFunction; + subInvocations: SorobanAuthorizedInvocation[]; + }); + + function(value?: SorobanAuthorizedFunction): SorobanAuthorizedFunction; + + subInvocations( + value?: SorobanAuthorizedInvocation[], + ): SorobanAuthorizedInvocation[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanAuthorizedInvocation; + + static write(value: SorobanAuthorizedInvocation, io: Buffer): void; + + static isValid(value: SorobanAuthorizedInvocation): boolean; + + static toXDR(value: SorobanAuthorizedInvocation): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanAuthorizedInvocation; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanAuthorizedInvocation; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanAddressCredentials { + constructor(attributes: { + address: ScAddress; + nonce: Int64; + signatureExpirationLedger: number; + signature: ScVal; + }); + + address(value?: ScAddress): ScAddress; + + nonce(value?: Int64): Int64; + + signatureExpirationLedger(value?: number): number; + + signature(value?: ScVal): ScVal; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanAddressCredentials; + + static write(value: SorobanAddressCredentials, io: Buffer): void; + + static isValid(value: SorobanAddressCredentials): boolean; + + static toXDR(value: SorobanAddressCredentials): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanAddressCredentials; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanAddressCredentials; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanAuthorizationEntry { + constructor(attributes: { + credentials: SorobanCredentials; + rootInvocation: SorobanAuthorizedInvocation; + }); + + credentials(value?: SorobanCredentials): SorobanCredentials; + + rootInvocation( + value?: SorobanAuthorizedInvocation, + ): SorobanAuthorizedInvocation; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanAuthorizationEntry; + + static write(value: SorobanAuthorizationEntry, io: Buffer): void; + + static isValid(value: SorobanAuthorizationEntry): boolean; + + static toXDR(value: SorobanAuthorizationEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanAuthorizationEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanAuthorizationEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InvokeHostFunctionOp { + constructor(attributes: { + hostFunction: HostFunction; + auth: SorobanAuthorizationEntry[]; + }); + + hostFunction(value?: HostFunction): HostFunction; + + auth(value?: SorobanAuthorizationEntry[]): SorobanAuthorizationEntry[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InvokeHostFunctionOp; + + static write(value: InvokeHostFunctionOp, io: Buffer): void; + + static isValid(value: InvokeHostFunctionOp): boolean; + + static toXDR(value: InvokeHostFunctionOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InvokeHostFunctionOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): InvokeHostFunctionOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ExtendFootprintTtlOp { + constructor(attributes: { ext: ExtensionPoint; extendTo: number }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + extendTo(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ExtendFootprintTtlOp; + + static write(value: ExtendFootprintTtlOp, io: Buffer): void; + + static isValid(value: ExtendFootprintTtlOp): boolean; + + static toXDR(value: ExtendFootprintTtlOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ExtendFootprintTtlOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ExtendFootprintTtlOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class RestoreFootprintOp { + constructor(attributes: { ext: ExtensionPoint }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): RestoreFootprintOp; + + static write(value: RestoreFootprintOp, io: Buffer): void; + + static isValid(value: RestoreFootprintOp): boolean; + + static toXDR(value: RestoreFootprintOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): RestoreFootprintOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): RestoreFootprintOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HashIdPreimageOperationId { + constructor(attributes: { + sourceAccount: AccountId; + seqNum: SequenceNumber; + opNum: number; + }); + + sourceAccount(value?: AccountId): AccountId; + + seqNum(value?: SequenceNumber): SequenceNumber; + + opNum(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HashIdPreimageOperationId; + + static write(value: HashIdPreimageOperationId, io: Buffer): void; + + static isValid(value: HashIdPreimageOperationId): boolean; + + static toXDR(value: HashIdPreimageOperationId): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HashIdPreimageOperationId; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): HashIdPreimageOperationId; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HashIdPreimageRevokeId { + constructor(attributes: { + sourceAccount: AccountId; + seqNum: SequenceNumber; + opNum: number; + liquidityPoolId: PoolId; + asset: Asset; + }); + + sourceAccount(value?: AccountId): AccountId; + + seqNum(value?: SequenceNumber): SequenceNumber; + + opNum(value?: number): number; + + liquidityPoolId(value?: PoolId): PoolId; + + asset(value?: Asset): Asset; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HashIdPreimageRevokeId; + + static write(value: HashIdPreimageRevokeId, io: Buffer): void; + + static isValid(value: HashIdPreimageRevokeId): boolean; + + static toXDR(value: HashIdPreimageRevokeId): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HashIdPreimageRevokeId; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): HashIdPreimageRevokeId; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HashIdPreimageContractId { + constructor(attributes: { + networkId: Buffer; + contractIdPreimage: ContractIdPreimage; + }); + + networkId(value?: Buffer): Buffer; + + contractIdPreimage(value?: ContractIdPreimage): ContractIdPreimage; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HashIdPreimageContractId; + + static write(value: HashIdPreimageContractId, io: Buffer): void; + + static isValid(value: HashIdPreimageContractId): boolean; + + static toXDR(value: HashIdPreimageContractId): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HashIdPreimageContractId; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): HashIdPreimageContractId; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HashIdPreimageSorobanAuthorization { + constructor(attributes: { + networkId: Buffer; + nonce: Int64; + signatureExpirationLedger: number; + invocation: SorobanAuthorizedInvocation; + }); + + networkId(value?: Buffer): Buffer; + + nonce(value?: Int64): Int64; + + signatureExpirationLedger(value?: number): number; + + invocation( + value?: SorobanAuthorizedInvocation, + ): SorobanAuthorizedInvocation; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HashIdPreimageSorobanAuthorization; + + static write(value: HashIdPreimageSorobanAuthorization, io: Buffer): void; + + static isValid(value: HashIdPreimageSorobanAuthorization): boolean; + + static toXDR(value: HashIdPreimageSorobanAuthorization): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): HashIdPreimageSorobanAuthorization; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): HashIdPreimageSorobanAuthorization; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TimeBounds { + constructor(attributes: { minTime: TimePoint; maxTime: TimePoint }); + + minTime(value?: TimePoint): TimePoint; + + maxTime(value?: TimePoint): TimePoint; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TimeBounds; + + static write(value: TimeBounds, io: Buffer): void; + + static isValid(value: TimeBounds): boolean; + + static toXDR(value: TimeBounds): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TimeBounds; + + static fromXDR(input: string, format: 'hex' | 'base64'): TimeBounds; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerBounds { + constructor(attributes: { minLedger: number; maxLedger: number }); + + minLedger(value?: number): number; + + maxLedger(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerBounds; + + static write(value: LedgerBounds, io: Buffer): void; + + static isValid(value: LedgerBounds): boolean; + + static toXDR(value: LedgerBounds): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerBounds; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerBounds; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PreconditionsV2 { + constructor(attributes: { + timeBounds: null | TimeBounds; + ledgerBounds: null | LedgerBounds; + minSeqNum: null | SequenceNumber; + minSeqAge: Duration; + minSeqLedgerGap: number; + extraSigners: SignerKey[]; + }); + + timeBounds(value?: null | TimeBounds): null | TimeBounds; + + ledgerBounds(value?: null | LedgerBounds): null | LedgerBounds; + + minSeqNum(value?: null | SequenceNumber): null | SequenceNumber; + + minSeqAge(value?: Duration): Duration; + + minSeqLedgerGap(value?: number): number; + + extraSigners(value?: SignerKey[]): SignerKey[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PreconditionsV2; + + static write(value: PreconditionsV2, io: Buffer): void; + + static isValid(value: PreconditionsV2): boolean; + + static toXDR(value: PreconditionsV2): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PreconditionsV2; + + static fromXDR(input: string, format: 'hex' | 'base64'): PreconditionsV2; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerFootprint { + constructor(attributes: { readOnly: LedgerKey[]; readWrite: LedgerKey[] }); + + readOnly(value?: LedgerKey[]): LedgerKey[]; + + readWrite(value?: LedgerKey[]): LedgerKey[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerFootprint; + + static write(value: LedgerFootprint, io: Buffer): void; + + static isValid(value: LedgerFootprint): boolean; + + static toXDR(value: LedgerFootprint): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerFootprint; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerFootprint; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ArchivalProofNode { + constructor(attributes: { index: number; hash: Buffer }); + + index(value?: number): number; + + hash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ArchivalProofNode; + + static write(value: ArchivalProofNode, io: Buffer): void; + + static isValid(value: ArchivalProofNode): boolean; + + static toXDR(value: ArchivalProofNode): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ArchivalProofNode; + + static fromXDR(input: string, format: 'hex' | 'base64'): ArchivalProofNode; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class NonexistenceProofBody { + constructor(attributes: { + entriesToProve: ColdArchiveBucketEntry[]; + proofLevels: ArchivalProofNode[][]; + }); + + entriesToProve(value?: ColdArchiveBucketEntry[]): ColdArchiveBucketEntry[]; + + proofLevels(value?: ArchivalProofNode[][]): ArchivalProofNode[][]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): NonexistenceProofBody; + + static write(value: NonexistenceProofBody, io: Buffer): void; + + static isValid(value: NonexistenceProofBody): boolean; + + static toXDR(value: NonexistenceProofBody): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): NonexistenceProofBody; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): NonexistenceProofBody; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ExistenceProofBody { + constructor(attributes: { + keysToProve: LedgerKey[]; + lowBoundEntries: ColdArchiveBucketEntry[]; + highBoundEntries: ColdArchiveBucketEntry[]; + proofLevels: ArchivalProofNode[][]; + }); + + keysToProve(value?: LedgerKey[]): LedgerKey[]; + + lowBoundEntries(value?: ColdArchiveBucketEntry[]): ColdArchiveBucketEntry[]; + + highBoundEntries( + value?: ColdArchiveBucketEntry[], + ): ColdArchiveBucketEntry[]; + + proofLevels(value?: ArchivalProofNode[][]): ArchivalProofNode[][]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ExistenceProofBody; + + static write(value: ExistenceProofBody, io: Buffer): void; + + static isValid(value: ExistenceProofBody): boolean; + + static toXDR(value: ExistenceProofBody): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ExistenceProofBody; + + static fromXDR(input: string, format: 'hex' | 'base64'): ExistenceProofBody; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ArchivalProof { + constructor(attributes: { epoch: number; body: ArchivalProofBody }); + + epoch(value?: number): number; + + body(value?: ArchivalProofBody): ArchivalProofBody; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ArchivalProof; + + static write(value: ArchivalProof, io: Buffer): void; + + static isValid(value: ArchivalProof): boolean; + + static toXDR(value: ArchivalProof): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ArchivalProof; + + static fromXDR(input: string, format: 'hex' | 'base64'): ArchivalProof; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanResources { + constructor(attributes: { + footprint: LedgerFootprint; + instructions: number; + readBytes: number; + writeBytes: number; + }); + + footprint(value?: LedgerFootprint): LedgerFootprint; + + instructions(value?: number): number; + + readBytes(value?: number): number; + + writeBytes(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanResources; + + static write(value: SorobanResources, io: Buffer): void; + + static isValid(value: SorobanResources): boolean; + + static toXDR(value: SorobanResources): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanResources; + + static fromXDR(input: string, format: 'hex' | 'base64'): SorobanResources; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanTransactionData { + constructor(attributes: { + ext: ExtensionPoint; + resources: SorobanResources; + resourceFee: Int64; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + resources(value?: SorobanResources): SorobanResources; + + resourceFee(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanTransactionData; + + static write(value: SorobanTransactionData, io: Buffer): void; + + static isValid(value: SorobanTransactionData): boolean; + + static toXDR(value: SorobanTransactionData): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanTransactionData; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanTransactionData; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionV0 { + constructor(attributes: { + sourceAccountEd25519: Buffer; + fee: number; + seqNum: SequenceNumber; + timeBounds: null | TimeBounds; + memo: Memo; + operations: Operation[]; + ext: TransactionV0Ext; + }); + + sourceAccountEd25519(value?: Buffer): Buffer; + + fee(value?: number): number; + + seqNum(value?: SequenceNumber): SequenceNumber; + + timeBounds(value?: null | TimeBounds): null | TimeBounds; + + memo(value?: Memo): Memo; + + operations(value?: Operation[]): Operation[]; + + ext(value?: TransactionV0Ext): TransactionV0Ext; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionV0; + + static write(value: TransactionV0, io: Buffer): void; + + static isValid(value: TransactionV0): boolean; + + static toXDR(value: TransactionV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionV0Envelope { + constructor(attributes: { + tx: TransactionV0; + signatures: DecoratedSignature[]; + }); + + tx(value?: TransactionV0): TransactionV0; + + signatures(value?: DecoratedSignature[]): DecoratedSignature[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionV0Envelope; + + static write(value: TransactionV0Envelope, io: Buffer): void; + + static isValid(value: TransactionV0Envelope): boolean; + + static toXDR(value: TransactionV0Envelope): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionV0Envelope; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionV0Envelope; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Transaction { + constructor(attributes: { + sourceAccount: MuxedAccount; + fee: number; + seqNum: SequenceNumber; + cond: Preconditions; + memo: Memo; + operations: Operation[]; + ext: TransactionExt; + }); + + sourceAccount(value?: MuxedAccount): MuxedAccount; + + fee(value?: number): number; + + seqNum(value?: SequenceNumber): SequenceNumber; + + cond(value?: Preconditions): Preconditions; + + memo(value?: Memo): Memo; + + operations(value?: Operation[]): Operation[]; + + ext(value?: TransactionExt): TransactionExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Transaction; + + static write(value: Transaction, io: Buffer): void; + + static isValid(value: Transaction): boolean; + + static toXDR(value: Transaction): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Transaction; + + static fromXDR(input: string, format: 'hex' | 'base64'): Transaction; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionV1Envelope { + constructor(attributes: { + tx: Transaction; + signatures: DecoratedSignature[]; + }); + + tx(value?: Transaction): Transaction; + + signatures(value?: DecoratedSignature[]): DecoratedSignature[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionV1Envelope; + + static write(value: TransactionV1Envelope, io: Buffer): void; + + static isValid(value: TransactionV1Envelope): boolean; + + static toXDR(value: TransactionV1Envelope): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionV1Envelope; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionV1Envelope; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class FeeBumpTransaction { + constructor(attributes: { + feeSource: MuxedAccount; + fee: Int64; + innerTx: FeeBumpTransactionInnerTx; + ext: FeeBumpTransactionExt; + }); + + feeSource(value?: MuxedAccount): MuxedAccount; + + fee(value?: Int64): Int64; + + innerTx(value?: FeeBumpTransactionInnerTx): FeeBumpTransactionInnerTx; + + ext(value?: FeeBumpTransactionExt): FeeBumpTransactionExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): FeeBumpTransaction; + + static write(value: FeeBumpTransaction, io: Buffer): void; + + static isValid(value: FeeBumpTransaction): boolean; + + static toXDR(value: FeeBumpTransaction): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): FeeBumpTransaction; + + static fromXDR(input: string, format: 'hex' | 'base64'): FeeBumpTransaction; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class FeeBumpTransactionEnvelope { + constructor(attributes: { + tx: FeeBumpTransaction; + signatures: DecoratedSignature[]; + }); + + tx(value?: FeeBumpTransaction): FeeBumpTransaction; + + signatures(value?: DecoratedSignature[]): DecoratedSignature[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): FeeBumpTransactionEnvelope; + + static write(value: FeeBumpTransactionEnvelope, io: Buffer): void; + + static isValid(value: FeeBumpTransactionEnvelope): boolean; + + static toXDR(value: FeeBumpTransactionEnvelope): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): FeeBumpTransactionEnvelope; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): FeeBumpTransactionEnvelope; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionSignaturePayload { + constructor(attributes: { + networkId: Buffer; + taggedTransaction: TransactionSignaturePayloadTaggedTransaction; + }); + + networkId(value?: Buffer): Buffer; + + taggedTransaction( + value?: TransactionSignaturePayloadTaggedTransaction, + ): TransactionSignaturePayloadTaggedTransaction; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionSignaturePayload; + + static write(value: TransactionSignaturePayload, io: Buffer): void; + + static isValid(value: TransactionSignaturePayload): boolean; + + static toXDR(value: TransactionSignaturePayload): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionSignaturePayload; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionSignaturePayload; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimOfferAtomV0 { + constructor(attributes: { + sellerEd25519: Buffer; + offerId: Int64; + assetSold: Asset; + amountSold: Int64; + assetBought: Asset; + amountBought: Int64; + }); + + sellerEd25519(value?: Buffer): Buffer; + + offerId(value?: Int64): Int64; + + assetSold(value?: Asset): Asset; + + amountSold(value?: Int64): Int64; + + assetBought(value?: Asset): Asset; + + amountBought(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimOfferAtomV0; + + static write(value: ClaimOfferAtomV0, io: Buffer): void; + + static isValid(value: ClaimOfferAtomV0): boolean; + + static toXDR(value: ClaimOfferAtomV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimOfferAtomV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClaimOfferAtomV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimOfferAtom { + constructor(attributes: { + sellerId: AccountId; + offerId: Int64; + assetSold: Asset; + amountSold: Int64; + assetBought: Asset; + amountBought: Int64; + }); + + sellerId(value?: AccountId): AccountId; + + offerId(value?: Int64): Int64; + + assetSold(value?: Asset): Asset; + + amountSold(value?: Int64): Int64; + + assetBought(value?: Asset): Asset; + + amountBought(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimOfferAtom; + + static write(value: ClaimOfferAtom, io: Buffer): void; + + static isValid(value: ClaimOfferAtom): boolean; + + static toXDR(value: ClaimOfferAtom): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimOfferAtom; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClaimOfferAtom; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimLiquidityAtom { + constructor(attributes: { + liquidityPoolId: PoolId; + assetSold: Asset; + amountSold: Int64; + assetBought: Asset; + amountBought: Int64; + }); + + liquidityPoolId(value?: PoolId): PoolId; + + assetSold(value?: Asset): Asset; + + amountSold(value?: Int64): Int64; + + assetBought(value?: Asset): Asset; + + amountBought(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimLiquidityAtom; + + static write(value: ClaimLiquidityAtom, io: Buffer): void; + + static isValid(value: ClaimLiquidityAtom): boolean; + + static toXDR(value: ClaimLiquidityAtom): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimLiquidityAtom; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClaimLiquidityAtom; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SimplePaymentResult { + constructor(attributes: { + destination: AccountId; + asset: Asset; + amount: Int64; + }); + + destination(value?: AccountId): AccountId; + + asset(value?: Asset): Asset; + + amount(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SimplePaymentResult; + + static write(value: SimplePaymentResult, io: Buffer): void; + + static isValid(value: SimplePaymentResult): boolean; + + static toXDR(value: SimplePaymentResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SimplePaymentResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SimplePaymentResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PathPaymentStrictReceiveResultSuccess { + constructor(attributes: { offers: ClaimAtom[]; last: SimplePaymentResult }); + + offers(value?: ClaimAtom[]): ClaimAtom[]; + + last(value?: SimplePaymentResult): SimplePaymentResult; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PathPaymentStrictReceiveResultSuccess; + + static write( + value: PathPaymentStrictReceiveResultSuccess, + io: Buffer, + ): void; + + static isValid(value: PathPaymentStrictReceiveResultSuccess): boolean; + + static toXDR(value: PathPaymentStrictReceiveResultSuccess): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): PathPaymentStrictReceiveResultSuccess; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): PathPaymentStrictReceiveResultSuccess; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PathPaymentStrictSendResultSuccess { + constructor(attributes: { offers: ClaimAtom[]; last: SimplePaymentResult }); + + offers(value?: ClaimAtom[]): ClaimAtom[]; + + last(value?: SimplePaymentResult): SimplePaymentResult; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PathPaymentStrictSendResultSuccess; + + static write(value: PathPaymentStrictSendResultSuccess, io: Buffer): void; + + static isValid(value: PathPaymentStrictSendResultSuccess): boolean; + + static toXDR(value: PathPaymentStrictSendResultSuccess): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): PathPaymentStrictSendResultSuccess; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): PathPaymentStrictSendResultSuccess; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageOfferSuccessResult { + constructor(attributes: { + offersClaimed: ClaimAtom[]; + offer: ManageOfferSuccessResultOffer; + }); + + offersClaimed(value?: ClaimAtom[]): ClaimAtom[]; + + offer(value?: ManageOfferSuccessResultOffer): ManageOfferSuccessResultOffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageOfferSuccessResult; + + static write(value: ManageOfferSuccessResult, io: Buffer): void; + + static isValid(value: ManageOfferSuccessResult): boolean; + + static toXDR(value: ManageOfferSuccessResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ManageOfferSuccessResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ManageOfferSuccessResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InflationPayout { + constructor(attributes: { destination: AccountId; amount: Int64 }); + + destination(value?: AccountId): AccountId; + + amount(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InflationPayout; + + static write(value: InflationPayout, io: Buffer): void; + + static isValid(value: InflationPayout): boolean; + + static toXDR(value: InflationPayout): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InflationPayout; + + static fromXDR(input: string, format: 'hex' | 'base64'): InflationPayout; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InnerTransactionResult { + constructor(attributes: { + feeCharged: Int64; + result: InnerTransactionResultResult; + ext: InnerTransactionResultExt; + }); + + feeCharged(value?: Int64): Int64; + + result(value?: InnerTransactionResultResult): InnerTransactionResultResult; + + ext(value?: InnerTransactionResultExt): InnerTransactionResultExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InnerTransactionResult; + + static write(value: InnerTransactionResult, io: Buffer): void; + + static isValid(value: InnerTransactionResult): boolean; + + static toXDR(value: InnerTransactionResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InnerTransactionResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): InnerTransactionResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InnerTransactionResultPair { + constructor(attributes: { + transactionHash: Buffer; + result: InnerTransactionResult; + }); + + transactionHash(value?: Buffer): Buffer; + + result(value?: InnerTransactionResult): InnerTransactionResult; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InnerTransactionResultPair; + + static write(value: InnerTransactionResultPair, io: Buffer): void; + + static isValid(value: InnerTransactionResultPair): boolean; + + static toXDR(value: InnerTransactionResultPair): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InnerTransactionResultPair; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): InnerTransactionResultPair; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionResult { + constructor(attributes: { + feeCharged: Int64; + result: TransactionResultResult; + ext: TransactionResultExt; + }); + + feeCharged(value?: Int64): Int64; + + result(value?: TransactionResultResult): TransactionResultResult; + + ext(value?: TransactionResultExt): TransactionResultExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionResult; + + static write(value: TransactionResult, io: Buffer): void; + + static isValid(value: TransactionResult): boolean; + + static toXDR(value: TransactionResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignerKeyEd25519SignedPayload { + constructor(attributes: { ed25519: Buffer; payload: Buffer }); + + ed25519(value?: Buffer): Buffer; + + payload(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignerKeyEd25519SignedPayload; + + static write(value: SignerKeyEd25519SignedPayload, io: Buffer): void; + + static isValid(value: SignerKeyEd25519SignedPayload): boolean; + + static toXDR(value: SignerKeyEd25519SignedPayload): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): SignerKeyEd25519SignedPayload; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SignerKeyEd25519SignedPayload; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Curve25519Secret { + constructor(attributes: { key: Buffer }); + + key(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Curve25519Secret; + + static write(value: Curve25519Secret, io: Buffer): void; + + static isValid(value: Curve25519Secret): boolean; + + static toXDR(value: Curve25519Secret): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Curve25519Secret; + + static fromXDR(input: string, format: 'hex' | 'base64'): Curve25519Secret; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Curve25519Public { + constructor(attributes: { key: Buffer }); + + key(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Curve25519Public; + + static write(value: Curve25519Public, io: Buffer): void; + + static isValid(value: Curve25519Public): boolean; + + static toXDR(value: Curve25519Public): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Curve25519Public; + + static fromXDR(input: string, format: 'hex' | 'base64'): Curve25519Public; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HmacSha256Key { + constructor(attributes: { key: Buffer }); + + key(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HmacSha256Key; + + static write(value: HmacSha256Key, io: Buffer): void; + + static isValid(value: HmacSha256Key): boolean; + + static toXDR(value: HmacSha256Key): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HmacSha256Key; + + static fromXDR(input: string, format: 'hex' | 'base64'): HmacSha256Key; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HmacSha256Mac { + constructor(attributes: { mac: Buffer }); + + mac(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HmacSha256Mac; + + static write(value: HmacSha256Mac, io: Buffer): void; + + static isValid(value: HmacSha256Mac): boolean; + + static toXDR(value: HmacSha256Mac): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HmacSha256Mac; + + static fromXDR(input: string, format: 'hex' | 'base64'): HmacSha256Mac; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ShortHashSeed { + constructor(attributes: { seed: Buffer }); + + seed(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ShortHashSeed; + + static write(value: ShortHashSeed, io: Buffer): void; + + static isValid(value: ShortHashSeed): boolean; + + static toXDR(value: ShortHashSeed): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ShortHashSeed; + + static fromXDR(input: string, format: 'hex' | 'base64'): ShortHashSeed; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SerializedBinaryFuseFilter { + constructor(attributes: { + type: BinaryFuseFilterType; + inputHashSeed: ShortHashSeed; + filterSeed: ShortHashSeed; + segmentLength: number; + segementLengthMask: number; + segmentCount: number; + segmentCountLength: number; + fingerprintLength: number; + fingerprints: Buffer; + }); + + type(value?: BinaryFuseFilterType): BinaryFuseFilterType; + + inputHashSeed(value?: ShortHashSeed): ShortHashSeed; + + filterSeed(value?: ShortHashSeed): ShortHashSeed; + + segmentLength(value?: number): number; + + segementLengthMask(value?: number): number; + + segmentCount(value?: number): number; + + segmentCountLength(value?: number): number; + + fingerprintLength(value?: number): number; + + fingerprints(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SerializedBinaryFuseFilter; + + static write(value: SerializedBinaryFuseFilter, io: Buffer): void; + + static isValid(value: SerializedBinaryFuseFilter): boolean; + + static toXDR(value: SerializedBinaryFuseFilter): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SerializedBinaryFuseFilter; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SerializedBinaryFuseFilter; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class UInt128Parts { + constructor(attributes: { hi: Uint64; lo: Uint64 }); + + hi(value?: Uint64): Uint64; + + lo(value?: Uint64): Uint64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): UInt128Parts; + + static write(value: UInt128Parts, io: Buffer): void; + + static isValid(value: UInt128Parts): boolean; + + static toXDR(value: UInt128Parts): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): UInt128Parts; + + static fromXDR(input: string, format: 'hex' | 'base64'): UInt128Parts; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Int128Parts { + constructor(attributes: { hi: Int64; lo: Uint64 }); + + hi(value?: Int64): Int64; + + lo(value?: Uint64): Uint64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Int128Parts; + + static write(value: Int128Parts, io: Buffer): void; + + static isValid(value: Int128Parts): boolean; + + static toXDR(value: Int128Parts): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Int128Parts; + + static fromXDR(input: string, format: 'hex' | 'base64'): Int128Parts; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class UInt256Parts { + constructor(attributes: { + hiHi: Uint64; + hiLo: Uint64; + loHi: Uint64; + loLo: Uint64; + }); + + hiHi(value?: Uint64): Uint64; + + hiLo(value?: Uint64): Uint64; + + loHi(value?: Uint64): Uint64; + + loLo(value?: Uint64): Uint64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): UInt256Parts; + + static write(value: UInt256Parts, io: Buffer): void; + + static isValid(value: UInt256Parts): boolean; + + static toXDR(value: UInt256Parts): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): UInt256Parts; + + static fromXDR(input: string, format: 'hex' | 'base64'): UInt256Parts; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Int256Parts { + constructor(attributes: { + hiHi: Int64; + hiLo: Uint64; + loHi: Uint64; + loLo: Uint64; + }); + + hiHi(value?: Int64): Int64; + + hiLo(value?: Uint64): Uint64; + + loHi(value?: Uint64): Uint64; + + loLo(value?: Uint64): Uint64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Int256Parts; + + static write(value: Int256Parts, io: Buffer): void; + + static isValid(value: Int256Parts): boolean; + + static toXDR(value: Int256Parts): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Int256Parts; + + static fromXDR(input: string, format: 'hex' | 'base64'): Int256Parts; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScNonceKey { + constructor(attributes: { nonce: Int64 }); + + nonce(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScNonceKey; + + static write(value: ScNonceKey, io: Buffer): void; + + static isValid(value: ScNonceKey): boolean; + + static toXDR(value: ScNonceKey): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScNonceKey; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScNonceKey; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScContractInstance { + constructor(attributes: { + executable: ContractExecutable; + storage: null | ScMapEntry[]; + }); + + executable(value?: ContractExecutable): ContractExecutable; + + storage(value?: null | ScMapEntry[]): null | ScMapEntry[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScContractInstance; + + static write(value: ScContractInstance, io: Buffer): void; + + static isValid(value: ScContractInstance): boolean; + + static toXDR(value: ScContractInstance): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScContractInstance; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScContractInstance; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScMapEntry { + constructor(attributes: { key: ScVal; val: ScVal }); + + key(value?: ScVal): ScVal; + + val(value?: ScVal): ScVal; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScMapEntry; + + static write(value: ScMapEntry, io: Buffer): void; + + static isValid(value: ScMapEntry): boolean; + + static toXDR(value: ScMapEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScMapEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScMapEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScEnvMetaEntryInterfaceVersion { + constructor(attributes: { protocol: number; preRelease: number }); + + protocol(value?: number): number; + + preRelease(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScEnvMetaEntryInterfaceVersion; + + static write(value: ScEnvMetaEntryInterfaceVersion, io: Buffer): void; + + static isValid(value: ScEnvMetaEntryInterfaceVersion): boolean; + + static toXDR(value: ScEnvMetaEntryInterfaceVersion): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ScEnvMetaEntryInterfaceVersion; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScEnvMetaEntryInterfaceVersion; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScMetaV0 { + constructor(attributes: { key: string | Buffer; val: string | Buffer }); + + key(value?: string | Buffer): string | Buffer; + + val(value?: string | Buffer): string | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScMetaV0; + + static write(value: ScMetaV0, io: Buffer): void; + + static isValid(value: ScMetaV0): boolean; + + static toXDR(value: ScMetaV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScMetaV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScMetaV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeOption { + constructor(attributes: { valueType: ScSpecTypeDef }); + + valueType(value?: ScSpecTypeDef): ScSpecTypeDef; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeOption; + + static write(value: ScSpecTypeOption, io: Buffer): void; + + static isValid(value: ScSpecTypeOption): boolean; + + static toXDR(value: ScSpecTypeOption): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeOption; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeOption; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeResult { + constructor(attributes: { + okType: ScSpecTypeDef; + errorType: ScSpecTypeDef; + }); + + okType(value?: ScSpecTypeDef): ScSpecTypeDef; + + errorType(value?: ScSpecTypeDef): ScSpecTypeDef; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeResult; + + static write(value: ScSpecTypeResult, io: Buffer): void; + + static isValid(value: ScSpecTypeResult): boolean; + + static toXDR(value: ScSpecTypeResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeVec { + constructor(attributes: { elementType: ScSpecTypeDef }); + + elementType(value?: ScSpecTypeDef): ScSpecTypeDef; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeVec; + + static write(value: ScSpecTypeVec, io: Buffer): void; + + static isValid(value: ScSpecTypeVec): boolean; + + static toXDR(value: ScSpecTypeVec): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeVec; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeVec; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeMap { + constructor(attributes: { + keyType: ScSpecTypeDef; + valueType: ScSpecTypeDef; + }); + + keyType(value?: ScSpecTypeDef): ScSpecTypeDef; + + valueType(value?: ScSpecTypeDef): ScSpecTypeDef; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeMap; + + static write(value: ScSpecTypeMap, io: Buffer): void; + + static isValid(value: ScSpecTypeMap): boolean; + + static toXDR(value: ScSpecTypeMap): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeMap; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeMap; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeTuple { + constructor(attributes: { valueTypes: ScSpecTypeDef[] }); + + valueTypes(value?: ScSpecTypeDef[]): ScSpecTypeDef[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeTuple; + + static write(value: ScSpecTypeTuple, io: Buffer): void; + + static isValid(value: ScSpecTypeTuple): boolean; + + static toXDR(value: ScSpecTypeTuple): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeTuple; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeTuple; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeBytesN { + constructor(attributes: { n: number }); + + n(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeBytesN; + + static write(value: ScSpecTypeBytesN, io: Buffer): void; + + static isValid(value: ScSpecTypeBytesN): boolean; + + static toXDR(value: ScSpecTypeBytesN): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeBytesN; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeBytesN; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeUdt { + constructor(attributes: { name: string | Buffer }); + + name(value?: string | Buffer): string | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeUdt; + + static write(value: ScSpecTypeUdt, io: Buffer): void; + + static isValid(value: ScSpecTypeUdt): boolean; + + static toXDR(value: ScSpecTypeUdt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeUdt; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeUdt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtStructFieldV0 { + constructor(attributes: { + doc: string | Buffer; + name: string | Buffer; + type: ScSpecTypeDef; + }); + + doc(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + type(value?: ScSpecTypeDef): ScSpecTypeDef; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtStructFieldV0; + + static write(value: ScSpecUdtStructFieldV0, io: Buffer): void; + + static isValid(value: ScSpecUdtStructFieldV0): boolean; + + static toXDR(value: ScSpecUdtStructFieldV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtStructFieldV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecUdtStructFieldV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtStructV0 { + constructor(attributes: { + doc: string | Buffer; + lib: string | Buffer; + name: string | Buffer; + fields: ScSpecUdtStructFieldV0[]; + }); + + doc(value?: string | Buffer): string | Buffer; + + lib(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + fields(value?: ScSpecUdtStructFieldV0[]): ScSpecUdtStructFieldV0[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtStructV0; + + static write(value: ScSpecUdtStructV0, io: Buffer): void; + + static isValid(value: ScSpecUdtStructV0): boolean; + + static toXDR(value: ScSpecUdtStructV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtStructV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecUdtStructV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtUnionCaseVoidV0 { + constructor(attributes: { doc: string | Buffer; name: string | Buffer }); + + doc(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtUnionCaseVoidV0; + + static write(value: ScSpecUdtUnionCaseVoidV0, io: Buffer): void; + + static isValid(value: ScSpecUdtUnionCaseVoidV0): boolean; + + static toXDR(value: ScSpecUdtUnionCaseVoidV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtUnionCaseVoidV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecUdtUnionCaseVoidV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtUnionCaseTupleV0 { + constructor(attributes: { + doc: string | Buffer; + name: string | Buffer; + type: ScSpecTypeDef[]; + }); + + doc(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + type(value?: ScSpecTypeDef[]): ScSpecTypeDef[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtUnionCaseTupleV0; + + static write(value: ScSpecUdtUnionCaseTupleV0, io: Buffer): void; + + static isValid(value: ScSpecUdtUnionCaseTupleV0): boolean; + + static toXDR(value: ScSpecUdtUnionCaseTupleV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtUnionCaseTupleV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecUdtUnionCaseTupleV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtUnionV0 { + constructor(attributes: { + doc: string | Buffer; + lib: string | Buffer; + name: string | Buffer; + cases: ScSpecUdtUnionCaseV0[]; + }); + + doc(value?: string | Buffer): string | Buffer; + + lib(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + cases(value?: ScSpecUdtUnionCaseV0[]): ScSpecUdtUnionCaseV0[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtUnionV0; + + static write(value: ScSpecUdtUnionV0, io: Buffer): void; + + static isValid(value: ScSpecUdtUnionV0): boolean; + + static toXDR(value: ScSpecUdtUnionV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtUnionV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecUdtUnionV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtEnumCaseV0 { + constructor(attributes: { + doc: string | Buffer; + name: string | Buffer; + value: number; + }); + + doc(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + value(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtEnumCaseV0; + + static write(value: ScSpecUdtEnumCaseV0, io: Buffer): void; + + static isValid(value: ScSpecUdtEnumCaseV0): boolean; + + static toXDR(value: ScSpecUdtEnumCaseV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtEnumCaseV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecUdtEnumCaseV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtEnumV0 { + constructor(attributes: { + doc: string | Buffer; + lib: string | Buffer; + name: string | Buffer; + cases: ScSpecUdtEnumCaseV0[]; + }); + + doc(value?: string | Buffer): string | Buffer; + + lib(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + cases(value?: ScSpecUdtEnumCaseV0[]): ScSpecUdtEnumCaseV0[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtEnumV0; + + static write(value: ScSpecUdtEnumV0, io: Buffer): void; + + static isValid(value: ScSpecUdtEnumV0): boolean; + + static toXDR(value: ScSpecUdtEnumV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtEnumV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecUdtEnumV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtErrorEnumCaseV0 { + constructor(attributes: { + doc: string | Buffer; + name: string | Buffer; + value: number; + }); + + doc(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + value(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtErrorEnumCaseV0; + + static write(value: ScSpecUdtErrorEnumCaseV0, io: Buffer): void; + + static isValid(value: ScSpecUdtErrorEnumCaseV0): boolean; + + static toXDR(value: ScSpecUdtErrorEnumCaseV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtErrorEnumCaseV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecUdtErrorEnumCaseV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtErrorEnumV0 { + constructor(attributes: { + doc: string | Buffer; + lib: string | Buffer; + name: string | Buffer; + cases: ScSpecUdtErrorEnumCaseV0[]; + }); + + doc(value?: string | Buffer): string | Buffer; + + lib(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + cases(value?: ScSpecUdtErrorEnumCaseV0[]): ScSpecUdtErrorEnumCaseV0[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtErrorEnumV0; + + static write(value: ScSpecUdtErrorEnumV0, io: Buffer): void; + + static isValid(value: ScSpecUdtErrorEnumV0): boolean; + + static toXDR(value: ScSpecUdtErrorEnumV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtErrorEnumV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecUdtErrorEnumV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecFunctionInputV0 { + constructor(attributes: { + doc: string | Buffer; + name: string | Buffer; + type: ScSpecTypeDef; + }); + + doc(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + type(value?: ScSpecTypeDef): ScSpecTypeDef; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecFunctionInputV0; + + static write(value: ScSpecFunctionInputV0, io: Buffer): void; + + static isValid(value: ScSpecFunctionInputV0): boolean; + + static toXDR(value: ScSpecFunctionInputV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecFunctionInputV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecFunctionInputV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecFunctionV0 { + constructor(attributes: { + doc: string | Buffer; + name: string | Buffer; + inputs: ScSpecFunctionInputV0[]; + outputs: ScSpecTypeDef[]; + }); + + doc(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + inputs(value?: ScSpecFunctionInputV0[]): ScSpecFunctionInputV0[]; + + outputs(value?: ScSpecTypeDef[]): ScSpecTypeDef[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecFunctionV0; + + static write(value: ScSpecFunctionV0, io: Buffer): void; + + static isValid(value: ScSpecFunctionV0): boolean; + + static toXDR(value: ScSpecFunctionV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecFunctionV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecFunctionV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingContractExecutionLanesV0 { + constructor(attributes: { ledgerMaxTxCount: number }); + + ledgerMaxTxCount(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingContractExecutionLanesV0; + + static write( + value: ConfigSettingContractExecutionLanesV0, + io: Buffer, + ): void; + + static isValid(value: ConfigSettingContractExecutionLanesV0): boolean; + + static toXDR(value: ConfigSettingContractExecutionLanesV0): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ConfigSettingContractExecutionLanesV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigSettingContractExecutionLanesV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingContractComputeV0 { + constructor(attributes: { + ledgerMaxInstructions: Int64; + txMaxInstructions: Int64; + feeRatePerInstructionsIncrement: Int64; + txMemoryLimit: number; + }); + + ledgerMaxInstructions(value?: Int64): Int64; + + txMaxInstructions(value?: Int64): Int64; + + feeRatePerInstructionsIncrement(value?: Int64): Int64; + + txMemoryLimit(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingContractComputeV0; + + static write(value: ConfigSettingContractComputeV0, io: Buffer): void; + + static isValid(value: ConfigSettingContractComputeV0): boolean; + + static toXDR(value: ConfigSettingContractComputeV0): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ConfigSettingContractComputeV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigSettingContractComputeV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingContractLedgerCostV0 { + constructor(attributes: { + ledgerMaxReadLedgerEntries: number; + ledgerMaxReadBytes: number; + ledgerMaxWriteLedgerEntries: number; + ledgerMaxWriteBytes: number; + txMaxReadLedgerEntries: number; + txMaxReadBytes: number; + txMaxWriteLedgerEntries: number; + txMaxWriteBytes: number; + feeReadLedgerEntry: Int64; + feeWriteLedgerEntry: Int64; + feeRead1Kb: Int64; + bucketListTargetSizeBytes: Int64; + writeFee1KbBucketListLow: Int64; + writeFee1KbBucketListHigh: Int64; + bucketListWriteFeeGrowthFactor: number; + }); + + ledgerMaxReadLedgerEntries(value?: number): number; + + ledgerMaxReadBytes(value?: number): number; + + ledgerMaxWriteLedgerEntries(value?: number): number; + + ledgerMaxWriteBytes(value?: number): number; + + txMaxReadLedgerEntries(value?: number): number; + + txMaxReadBytes(value?: number): number; + + txMaxWriteLedgerEntries(value?: number): number; + + txMaxWriteBytes(value?: number): number; + + feeReadLedgerEntry(value?: Int64): Int64; + + feeWriteLedgerEntry(value?: Int64): Int64; + + feeRead1Kb(value?: Int64): Int64; + + bucketListTargetSizeBytes(value?: Int64): Int64; + + writeFee1KbBucketListLow(value?: Int64): Int64; + + writeFee1KbBucketListHigh(value?: Int64): Int64; + + bucketListWriteFeeGrowthFactor(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingContractLedgerCostV0; + + static write(value: ConfigSettingContractLedgerCostV0, io: Buffer): void; + + static isValid(value: ConfigSettingContractLedgerCostV0): boolean; + + static toXDR(value: ConfigSettingContractLedgerCostV0): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ConfigSettingContractLedgerCostV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigSettingContractLedgerCostV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingContractHistoricalDataV0 { + constructor(attributes: { feeHistorical1Kb: Int64 }); + + feeHistorical1Kb(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingContractHistoricalDataV0; + + static write( + value: ConfigSettingContractHistoricalDataV0, + io: Buffer, + ): void; + + static isValid(value: ConfigSettingContractHistoricalDataV0): boolean; + + static toXDR(value: ConfigSettingContractHistoricalDataV0): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ConfigSettingContractHistoricalDataV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigSettingContractHistoricalDataV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingContractEventsV0 { + constructor(attributes: { + txMaxContractEventsSizeBytes: number; + feeContractEvents1Kb: Int64; + }); + + txMaxContractEventsSizeBytes(value?: number): number; + + feeContractEvents1Kb(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingContractEventsV0; + + static write(value: ConfigSettingContractEventsV0, io: Buffer): void; + + static isValid(value: ConfigSettingContractEventsV0): boolean; + + static toXDR(value: ConfigSettingContractEventsV0): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ConfigSettingContractEventsV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigSettingContractEventsV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingContractBandwidthV0 { + constructor(attributes: { + ledgerMaxTxsSizeBytes: number; + txMaxSizeBytes: number; + feeTxSize1Kb: Int64; + }); + + ledgerMaxTxsSizeBytes(value?: number): number; + + txMaxSizeBytes(value?: number): number; + + feeTxSize1Kb(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingContractBandwidthV0; + + static write(value: ConfigSettingContractBandwidthV0, io: Buffer): void; + + static isValid(value: ConfigSettingContractBandwidthV0): boolean; + + static toXDR(value: ConfigSettingContractBandwidthV0): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ConfigSettingContractBandwidthV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigSettingContractBandwidthV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractCostParamEntry { + constructor(attributes: { + ext: ExtensionPoint; + constTerm: Int64; + linearTerm: Int64; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + constTerm(value?: Int64): Int64; + + linearTerm(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractCostParamEntry; + + static write(value: ContractCostParamEntry, io: Buffer): void; + + static isValid(value: ContractCostParamEntry): boolean; + + static toXDR(value: ContractCostParamEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractCostParamEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ContractCostParamEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class StateArchivalSettings { + constructor(attributes: { + maxEntryTtl: number; + minTemporaryTtl: number; + minPersistentTtl: number; + persistentRentRateDenominator: Int64; + tempRentRateDenominator: Int64; + maxEntriesToArchive: number; + bucketListSizeWindowSampleSize: number; + bucketListWindowSamplePeriod: number; + evictionScanSize: number; + startingEvictionScanLevel: number; + }); + + maxEntryTtl(value?: number): number; + + minTemporaryTtl(value?: number): number; + + minPersistentTtl(value?: number): number; + + persistentRentRateDenominator(value?: Int64): Int64; + + tempRentRateDenominator(value?: Int64): Int64; + + maxEntriesToArchive(value?: number): number; + + bucketListSizeWindowSampleSize(value?: number): number; + + bucketListWindowSamplePeriod(value?: number): number; + + evictionScanSize(value?: number): number; + + startingEvictionScanLevel(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): StateArchivalSettings; + + static write(value: StateArchivalSettings, io: Buffer): void; + + static isValid(value: StateArchivalSettings): boolean; + + static toXDR(value: StateArchivalSettings): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): StateArchivalSettings; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): StateArchivalSettings; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class EvictionIterator { + constructor(attributes: { + bucketListLevel: number; + isCurrBucket: boolean; + bucketFileOffset: Uint64; + }); + + bucketListLevel(value?: number): number; + + isCurrBucket(value?: boolean): boolean; + + bucketFileOffset(value?: Uint64): Uint64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): EvictionIterator; + + static write(value: EvictionIterator, io: Buffer): void; + + static isValid(value: EvictionIterator): boolean; + + static toXDR(value: EvictionIterator): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): EvictionIterator; + + static fromXDR(input: string, format: 'hex' | 'base64'): EvictionIterator; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpStatementPledges { + switch(): ScpStatementType; + + prepare(value?: ScpStatementPrepare): ScpStatementPrepare; + + confirm(value?: ScpStatementConfirm): ScpStatementConfirm; + + externalize(value?: ScpStatementExternalize): ScpStatementExternalize; + + nominate(value?: ScpNomination): ScpNomination; + + static scpStPrepare(value: ScpStatementPrepare): ScpStatementPledges; + + static scpStConfirm(value: ScpStatementConfirm): ScpStatementPledges; + + static scpStExternalize( + value: ScpStatementExternalize, + ): ScpStatementPledges; + + static scpStNominate(value: ScpNomination): ScpStatementPledges; + + value(): + | ScpStatementPrepare + | ScpStatementConfirm + | ScpStatementExternalize + | ScpNomination; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpStatementPledges; + + static write(value: ScpStatementPledges, io: Buffer): void; + + static isValid(value: ScpStatementPledges): boolean; + + static toXDR(value: ScpStatementPledges): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpStatementPledges; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScpStatementPledges; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AssetCode { + switch(): AssetType; + + assetCode4(value?: Buffer): Buffer; + + assetCode12(value?: Buffer): Buffer; + + static assetTypeCreditAlphanum4(value: Buffer): AssetCode; + + static assetTypeCreditAlphanum12(value: Buffer): AssetCode; + + value(): Buffer | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AssetCode; + + static write(value: AssetCode, io: Buffer): void; + + static isValid(value: AssetCode): boolean; + + static toXDR(value: AssetCode): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AssetCode; + + static fromXDR(input: string, format: 'hex' | 'base64'): AssetCode; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Asset { + switch(): AssetType; + + alphaNum4(value?: AlphaNum4): AlphaNum4; + + alphaNum12(value?: AlphaNum12): AlphaNum12; + + static assetTypeNative(): Asset; + + static assetTypeCreditAlphanum4(value: AlphaNum4): Asset; + + static assetTypeCreditAlphanum12(value: AlphaNum12): Asset; + + value(): AlphaNum4 | AlphaNum12 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Asset; + + static write(value: Asset, io: Buffer): void; + + static isValid(value: Asset): boolean; + + static toXDR(value: Asset): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Asset; + + static fromXDR(input: string, format: 'hex' | 'base64'): Asset; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountEntryExtensionV2Ext { + switch(): number; + + v3(value?: AccountEntryExtensionV3): AccountEntryExtensionV3; + + static 0(): AccountEntryExtensionV2Ext; + + static 3(value: AccountEntryExtensionV3): AccountEntryExtensionV2Ext; + + value(): AccountEntryExtensionV3 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountEntryExtensionV2Ext; + + static write(value: AccountEntryExtensionV2Ext, io: Buffer): void; + + static isValid(value: AccountEntryExtensionV2Ext): boolean; + + static toXDR(value: AccountEntryExtensionV2Ext): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountEntryExtensionV2Ext; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): AccountEntryExtensionV2Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountEntryExtensionV1Ext { + switch(): number; + + v2(value?: AccountEntryExtensionV2): AccountEntryExtensionV2; + + static 0(): AccountEntryExtensionV1Ext; + + static 2(value: AccountEntryExtensionV2): AccountEntryExtensionV1Ext; + + value(): AccountEntryExtensionV2 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountEntryExtensionV1Ext; + + static write(value: AccountEntryExtensionV1Ext, io: Buffer): void; + + static isValid(value: AccountEntryExtensionV1Ext): boolean; + + static toXDR(value: AccountEntryExtensionV1Ext): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountEntryExtensionV1Ext; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): AccountEntryExtensionV1Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountEntryExt { + switch(): number; + + v1(value?: AccountEntryExtensionV1): AccountEntryExtensionV1; + + static 0(): AccountEntryExt; + + static 1(value: AccountEntryExtensionV1): AccountEntryExt; + + value(): AccountEntryExtensionV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountEntryExt; + + static write(value: AccountEntryExt, io: Buffer): void; + + static isValid(value: AccountEntryExt): boolean; + + static toXDR(value: AccountEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountEntryExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): AccountEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TrustLineAsset { + switch(): AssetType; + + alphaNum4(value?: AlphaNum4): AlphaNum4; + + alphaNum12(value?: AlphaNum12): AlphaNum12; + + liquidityPoolId(value?: PoolId): PoolId; + + static assetTypeNative(): TrustLineAsset; + + static assetTypeCreditAlphanum4(value: AlphaNum4): TrustLineAsset; + + static assetTypeCreditAlphanum12(value: AlphaNum12): TrustLineAsset; + + static assetTypePoolShare(value: PoolId): TrustLineAsset; + + value(): AlphaNum4 | AlphaNum12 | PoolId | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TrustLineAsset; + + static write(value: TrustLineAsset, io: Buffer): void; + + static isValid(value: TrustLineAsset): boolean; + + static toXDR(value: TrustLineAsset): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TrustLineAsset; + + static fromXDR(input: string, format: 'hex' | 'base64'): TrustLineAsset; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TrustLineEntryExtensionV2Ext { + switch(): number; + + static 0(): TrustLineEntryExtensionV2Ext; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TrustLineEntryExtensionV2Ext; + + static write(value: TrustLineEntryExtensionV2Ext, io: Buffer): void; + + static isValid(value: TrustLineEntryExtensionV2Ext): boolean; + + static toXDR(value: TrustLineEntryExtensionV2Ext): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TrustLineEntryExtensionV2Ext; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TrustLineEntryExtensionV2Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TrustLineEntryV1Ext { + switch(): number; + + v2(value?: TrustLineEntryExtensionV2): TrustLineEntryExtensionV2; + + static 0(): TrustLineEntryV1Ext; + + static 2(value: TrustLineEntryExtensionV2): TrustLineEntryV1Ext; + + value(): TrustLineEntryExtensionV2 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TrustLineEntryV1Ext; + + static write(value: TrustLineEntryV1Ext, io: Buffer): void; + + static isValid(value: TrustLineEntryV1Ext): boolean; + + static toXDR(value: TrustLineEntryV1Ext): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TrustLineEntryV1Ext; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TrustLineEntryV1Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TrustLineEntryExt { + switch(): number; + + v1(value?: TrustLineEntryV1): TrustLineEntryV1; + + static 0(): TrustLineEntryExt; + + static 1(value: TrustLineEntryV1): TrustLineEntryExt; + + value(): TrustLineEntryV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TrustLineEntryExt; + + static write(value: TrustLineEntryExt, io: Buffer): void; + + static isValid(value: TrustLineEntryExt): boolean; + + static toXDR(value: TrustLineEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TrustLineEntryExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): TrustLineEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class OfferEntryExt { + switch(): number; + + static 0(): OfferEntryExt; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): OfferEntryExt; + + static write(value: OfferEntryExt, io: Buffer): void; + + static isValid(value: OfferEntryExt): boolean; + + static toXDR(value: OfferEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): OfferEntryExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): OfferEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class DataEntryExt { + switch(): number; + + static 0(): DataEntryExt; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): DataEntryExt; + + static write(value: DataEntryExt, io: Buffer): void; + + static isValid(value: DataEntryExt): boolean; + + static toXDR(value: DataEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): DataEntryExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): DataEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimPredicate { + switch(): ClaimPredicateType; + + andPredicates(value?: ClaimPredicate[]): ClaimPredicate[]; + + orPredicates(value?: ClaimPredicate[]): ClaimPredicate[]; + + notPredicate(value?: null | ClaimPredicate): null | ClaimPredicate; + + absBefore(value?: Int64): Int64; + + relBefore(value?: Int64): Int64; + + static claimPredicateUnconditional(): ClaimPredicate; + + static claimPredicateAnd(value: ClaimPredicate[]): ClaimPredicate; + + static claimPredicateOr(value: ClaimPredicate[]): ClaimPredicate; + + static claimPredicateNot(value: null | ClaimPredicate): ClaimPredicate; + + static claimPredicateBeforeAbsoluteTime(value: Int64): ClaimPredicate; + + static claimPredicateBeforeRelativeTime(value: Int64): ClaimPredicate; + + value(): + | ClaimPredicate[] + | ClaimPredicate[] + | null + | ClaimPredicate + | Int64 + | Int64 + | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimPredicate; + + static write(value: ClaimPredicate, io: Buffer): void; + + static isValid(value: ClaimPredicate): boolean; + + static toXDR(value: ClaimPredicate): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimPredicate; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClaimPredicate; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Claimant { + switch(): ClaimantType; + + v0(value?: ClaimantV0): ClaimantV0; + + static claimantTypeV0(value: ClaimantV0): Claimant; + + value(): ClaimantV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Claimant; + + static write(value: Claimant, io: Buffer): void; + + static isValid(value: Claimant): boolean; + + static toXDR(value: Claimant): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Claimant; + + static fromXDR(input: string, format: 'hex' | 'base64'): Claimant; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimableBalanceId { + switch(): ClaimableBalanceIdType; + + v0(value?: Buffer): Buffer; + + static claimableBalanceIdTypeV0(value: Buffer): ClaimableBalanceId; + + value(): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimableBalanceId; + + static write(value: ClaimableBalanceId, io: Buffer): void; + + static isValid(value: ClaimableBalanceId): boolean; + + static toXDR(value: ClaimableBalanceId): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimableBalanceId; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClaimableBalanceId; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimableBalanceEntryExtensionV1Ext { + switch(): number; + + static 0(): ClaimableBalanceEntryExtensionV1Ext; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimableBalanceEntryExtensionV1Ext; + + static write(value: ClaimableBalanceEntryExtensionV1Ext, io: Buffer): void; + + static isValid(value: ClaimableBalanceEntryExtensionV1Ext): boolean; + + static toXDR(value: ClaimableBalanceEntryExtensionV1Ext): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ClaimableBalanceEntryExtensionV1Ext; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClaimableBalanceEntryExtensionV1Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimableBalanceEntryExt { + switch(): number; + + v1( + value?: ClaimableBalanceEntryExtensionV1, + ): ClaimableBalanceEntryExtensionV1; + + static 0(): ClaimableBalanceEntryExt; + + static 1(value: ClaimableBalanceEntryExtensionV1): ClaimableBalanceEntryExt; + + value(): ClaimableBalanceEntryExtensionV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimableBalanceEntryExt; + + static write(value: ClaimableBalanceEntryExt, io: Buffer): void; + + static isValid(value: ClaimableBalanceEntryExt): boolean; + + static toXDR(value: ClaimableBalanceEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimableBalanceEntryExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClaimableBalanceEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolEntryBody { + switch(): LiquidityPoolType; + + constantProduct( + value?: LiquidityPoolEntryConstantProduct, + ): LiquidityPoolEntryConstantProduct; + + static liquidityPoolConstantProduct( + value: LiquidityPoolEntryConstantProduct, + ): LiquidityPoolEntryBody; + + value(): LiquidityPoolEntryConstantProduct; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolEntryBody; + + static write(value: LiquidityPoolEntryBody, io: Buffer): void; + + static isValid(value: LiquidityPoolEntryBody): boolean; + + static toXDR(value: LiquidityPoolEntryBody): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LiquidityPoolEntryBody; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolEntryBody; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractCodeEntryExt { + switch(): number; + + v1(value?: ContractCodeEntryV1): ContractCodeEntryV1; + + static 0(): ContractCodeEntryExt; + + static 1(value: ContractCodeEntryV1): ContractCodeEntryExt; + + value(): ContractCodeEntryV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractCodeEntryExt; + + static write(value: ContractCodeEntryExt, io: Buffer): void; + + static isValid(value: ContractCodeEntryExt): boolean; + + static toXDR(value: ContractCodeEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractCodeEntryExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ContractCodeEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerEntryExtensionV1Ext { + switch(): number; + + static 0(): LedgerEntryExtensionV1Ext; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerEntryExtensionV1Ext; + + static write(value: LedgerEntryExtensionV1Ext, io: Buffer): void; + + static isValid(value: LedgerEntryExtensionV1Ext): boolean; + + static toXDR(value: LedgerEntryExtensionV1Ext): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerEntryExtensionV1Ext; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerEntryExtensionV1Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerEntryData { + switch(): LedgerEntryType; + + account(value?: AccountEntry): AccountEntry; + + trustLine(value?: TrustLineEntry): TrustLineEntry; + + offer(value?: OfferEntry): OfferEntry; + + data(value?: DataEntry): DataEntry; + + claimableBalance(value?: ClaimableBalanceEntry): ClaimableBalanceEntry; + + liquidityPool(value?: LiquidityPoolEntry): LiquidityPoolEntry; + + contractData(value?: ContractDataEntry): ContractDataEntry; + + contractCode(value?: ContractCodeEntry): ContractCodeEntry; + + configSetting(value?: ConfigSettingEntry): ConfigSettingEntry; + + ttl(value?: TtlEntry): TtlEntry; + + static account(value: AccountEntry): LedgerEntryData; + + static trustline(value: TrustLineEntry): LedgerEntryData; + + static offer(value: OfferEntry): LedgerEntryData; + + static data(value: DataEntry): LedgerEntryData; + + static claimableBalance(value: ClaimableBalanceEntry): LedgerEntryData; + + static liquidityPool(value: LiquidityPoolEntry): LedgerEntryData; + + static contractData(value: ContractDataEntry): LedgerEntryData; + + static contractCode(value: ContractCodeEntry): LedgerEntryData; + + static configSetting(value: ConfigSettingEntry): LedgerEntryData; + + static ttl(value: TtlEntry): LedgerEntryData; + + value(): + | AccountEntry + | TrustLineEntry + | OfferEntry + | DataEntry + | ClaimableBalanceEntry + | LiquidityPoolEntry + | ContractDataEntry + | ContractCodeEntry + | ConfigSettingEntry + | TtlEntry; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerEntryData; + + static write(value: LedgerEntryData, io: Buffer): void; + + static isValid(value: LedgerEntryData): boolean; + + static toXDR(value: LedgerEntryData): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerEntryData; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerEntryData; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerEntryExt { + switch(): number; + + v1(value?: LedgerEntryExtensionV1): LedgerEntryExtensionV1; + + static 0(): LedgerEntryExt; + + static 1(value: LedgerEntryExtensionV1): LedgerEntryExt; + + value(): LedgerEntryExtensionV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerEntryExt; + + static write(value: LedgerEntryExt, io: Buffer): void; + + static isValid(value: LedgerEntryExt): boolean; + + static toXDR(value: LedgerEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerEntryExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKey { + switch(): LedgerEntryType; + + account(value?: LedgerKeyAccount): LedgerKeyAccount; + + trustLine(value?: LedgerKeyTrustLine): LedgerKeyTrustLine; + + offer(value?: LedgerKeyOffer): LedgerKeyOffer; + + data(value?: LedgerKeyData): LedgerKeyData; + + claimableBalance( + value?: LedgerKeyClaimableBalance, + ): LedgerKeyClaimableBalance; + + liquidityPool(value?: LedgerKeyLiquidityPool): LedgerKeyLiquidityPool; + + contractData(value?: LedgerKeyContractData): LedgerKeyContractData; + + contractCode(value?: LedgerKeyContractCode): LedgerKeyContractCode; + + configSetting(value?: LedgerKeyConfigSetting): LedgerKeyConfigSetting; + + ttl(value?: LedgerKeyTtl): LedgerKeyTtl; + + static account(value: LedgerKeyAccount): LedgerKey; + + static trustline(value: LedgerKeyTrustLine): LedgerKey; + + static offer(value: LedgerKeyOffer): LedgerKey; + + static data(value: LedgerKeyData): LedgerKey; + + static claimableBalance(value: LedgerKeyClaimableBalance): LedgerKey; + + static liquidityPool(value: LedgerKeyLiquidityPool): LedgerKey; + + static contractData(value: LedgerKeyContractData): LedgerKey; + + static contractCode(value: LedgerKeyContractCode): LedgerKey; + + static configSetting(value: LedgerKeyConfigSetting): LedgerKey; + + static ttl(value: LedgerKeyTtl): LedgerKey; + + value(): + | LedgerKeyAccount + | LedgerKeyTrustLine + | LedgerKeyOffer + | LedgerKeyData + | LedgerKeyClaimableBalance + | LedgerKeyLiquidityPool + | LedgerKeyContractData + | LedgerKeyContractCode + | LedgerKeyConfigSetting + | LedgerKeyTtl; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKey; + + static write(value: LedgerKey, io: Buffer): void; + + static isValid(value: LedgerKey): boolean; + + static toXDR(value: LedgerKey): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKey; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerKey; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class BucketMetadataExt { + switch(): number; + + bucketListType(value?: BucketListType): BucketListType; + + static 0(): BucketMetadataExt; + + static 1(value: BucketListType): BucketMetadataExt; + + value(): BucketListType | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): BucketMetadataExt; + + static write(value: BucketMetadataExt, io: Buffer): void; + + static isValid(value: BucketMetadataExt): boolean; + + static toXDR(value: BucketMetadataExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): BucketMetadataExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): BucketMetadataExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class BucketEntry { + switch(): BucketEntryType; + + liveEntry(value?: LedgerEntry): LedgerEntry; + + deadEntry(value?: LedgerKey): LedgerKey; + + metaEntry(value?: BucketMetadata): BucketMetadata; + + static liveentry(value: LedgerEntry): BucketEntry; + + static initentry(value: LedgerEntry): BucketEntry; + + static deadentry(value: LedgerKey): BucketEntry; + + static metaentry(value: BucketMetadata): BucketEntry; + + value(): LedgerEntry | LedgerKey | BucketMetadata; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): BucketEntry; + + static write(value: BucketEntry, io: Buffer): void; + + static isValid(value: BucketEntry): boolean; + + static toXDR(value: BucketEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): BucketEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): BucketEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HotArchiveBucketEntry { + switch(): HotArchiveBucketEntryType; + + archivedEntry(value?: LedgerEntry): LedgerEntry; + + key(value?: LedgerKey): LedgerKey; + + metaEntry(value?: BucketMetadata): BucketMetadata; + + static hotArchiveArchived(value: LedgerEntry): HotArchiveBucketEntry; + + static hotArchiveLive(value: LedgerKey): HotArchiveBucketEntry; + + static hotArchiveDeleted(value: LedgerKey): HotArchiveBucketEntry; + + static hotArchiveMetaentry(value: BucketMetadata): HotArchiveBucketEntry; + + value(): LedgerEntry | LedgerKey | BucketMetadata; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HotArchiveBucketEntry; + + static write(value: HotArchiveBucketEntry, io: Buffer): void; + + static isValid(value: HotArchiveBucketEntry): boolean; + + static toXDR(value: HotArchiveBucketEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HotArchiveBucketEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): HotArchiveBucketEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ColdArchiveBucketEntry { + switch(): ColdArchiveBucketEntryType; + + metaEntry(value?: BucketMetadata): BucketMetadata; + + archivedLeaf(value?: ColdArchiveArchivedLeaf): ColdArchiveArchivedLeaf; + + deletedLeaf(value?: ColdArchiveDeletedLeaf): ColdArchiveDeletedLeaf; + + boundaryLeaf(value?: ColdArchiveBoundaryLeaf): ColdArchiveBoundaryLeaf; + + hashEntry(value?: ColdArchiveHashEntry): ColdArchiveHashEntry; + + static coldArchiveMetaentry(value: BucketMetadata): ColdArchiveBucketEntry; + + static coldArchiveArchivedLeaf( + value: ColdArchiveArchivedLeaf, + ): ColdArchiveBucketEntry; + + static coldArchiveDeletedLeaf( + value: ColdArchiveDeletedLeaf, + ): ColdArchiveBucketEntry; + + static coldArchiveBoundaryLeaf( + value: ColdArchiveBoundaryLeaf, + ): ColdArchiveBucketEntry; + + static coldArchiveHash(value: ColdArchiveHashEntry): ColdArchiveBucketEntry; + + value(): + | BucketMetadata + | ColdArchiveArchivedLeaf + | ColdArchiveDeletedLeaf + | ColdArchiveBoundaryLeaf + | ColdArchiveHashEntry; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ColdArchiveBucketEntry; + + static write(value: ColdArchiveBucketEntry, io: Buffer): void; + + static isValid(value: ColdArchiveBucketEntry): boolean; + + static toXDR(value: ColdArchiveBucketEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ColdArchiveBucketEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ColdArchiveBucketEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class StellarValueExt { + switch(): StellarValueType; + + lcValueSignature( + value?: LedgerCloseValueSignature, + ): LedgerCloseValueSignature; + + static stellarValueBasic(): StellarValueExt; + + static stellarValueSigned( + value: LedgerCloseValueSignature, + ): StellarValueExt; + + value(): LedgerCloseValueSignature | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): StellarValueExt; + + static write(value: StellarValueExt, io: Buffer): void; + + static isValid(value: StellarValueExt): boolean; + + static toXDR(value: StellarValueExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): StellarValueExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): StellarValueExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerHeaderExtensionV1Ext { + switch(): number; + + static 0(): LedgerHeaderExtensionV1Ext; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerHeaderExtensionV1Ext; + + static write(value: LedgerHeaderExtensionV1Ext, io: Buffer): void; + + static isValid(value: LedgerHeaderExtensionV1Ext): boolean; + + static toXDR(value: LedgerHeaderExtensionV1Ext): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerHeaderExtensionV1Ext; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerHeaderExtensionV1Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerHeaderExt { + switch(): number; + + v1(value?: LedgerHeaderExtensionV1): LedgerHeaderExtensionV1; + + static 0(): LedgerHeaderExt; + + static 1(value: LedgerHeaderExtensionV1): LedgerHeaderExt; + + value(): LedgerHeaderExtensionV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerHeaderExt; + + static write(value: LedgerHeaderExt, io: Buffer): void; + + static isValid(value: LedgerHeaderExt): boolean; + + static toXDR(value: LedgerHeaderExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerHeaderExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerHeaderExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerUpgrade { + switch(): LedgerUpgradeType; + + newLedgerVersion(value?: number): number; + + newBaseFee(value?: number): number; + + newMaxTxSetSize(value?: number): number; + + newBaseReserve(value?: number): number; + + newFlags(value?: number): number; + + newConfig(value?: ConfigUpgradeSetKey): ConfigUpgradeSetKey; + + newMaxSorobanTxSetSize(value?: number): number; + + static ledgerUpgradeVersion(value: number): LedgerUpgrade; + + static ledgerUpgradeBaseFee(value: number): LedgerUpgrade; + + static ledgerUpgradeMaxTxSetSize(value: number): LedgerUpgrade; + + static ledgerUpgradeBaseReserve(value: number): LedgerUpgrade; + + static ledgerUpgradeFlags(value: number): LedgerUpgrade; + + static ledgerUpgradeConfig(value: ConfigUpgradeSetKey): LedgerUpgrade; + + static ledgerUpgradeMaxSorobanTxSetSize(value: number): LedgerUpgrade; + + value(): + | number + | number + | number + | number + | number + | ConfigUpgradeSetKey + | number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerUpgrade; + + static write(value: LedgerUpgrade, io: Buffer): void; + + static isValid(value: LedgerUpgrade): boolean; + + static toXDR(value: LedgerUpgrade): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerUpgrade; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerUpgrade; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TxSetComponent { + switch(): TxSetComponentType; + + txsMaybeDiscountedFee( + value?: TxSetComponentTxsMaybeDiscountedFee, + ): TxSetComponentTxsMaybeDiscountedFee; + + static txsetCompTxsMaybeDiscountedFee( + value: TxSetComponentTxsMaybeDiscountedFee, + ): TxSetComponent; + + value(): TxSetComponentTxsMaybeDiscountedFee; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TxSetComponent; + + static write(value: TxSetComponent, io: Buffer): void; + + static isValid(value: TxSetComponent): boolean; + + static toXDR(value: TxSetComponent): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TxSetComponent; + + static fromXDR(input: string, format: 'hex' | 'base64'): TxSetComponent; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionPhase { + switch(): number; + + v0Components(value?: TxSetComponent[]): TxSetComponent[]; + + static 0(value: TxSetComponent[]): TransactionPhase; + + value(): TxSetComponent[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionPhase; + + static write(value: TransactionPhase, io: Buffer): void; + + static isValid(value: TransactionPhase): boolean; + + static toXDR(value: TransactionPhase): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionPhase; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionPhase; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class GeneralizedTransactionSet { + switch(): number; + + v1TxSet(value?: TransactionSetV1): TransactionSetV1; + + static 1(value: TransactionSetV1): GeneralizedTransactionSet; + + value(): TransactionSetV1; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): GeneralizedTransactionSet; + + static write(value: GeneralizedTransactionSet, io: Buffer): void; + + static isValid(value: GeneralizedTransactionSet): boolean; + + static toXDR(value: GeneralizedTransactionSet): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): GeneralizedTransactionSet; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): GeneralizedTransactionSet; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionHistoryEntryExt { + switch(): number; + + generalizedTxSet( + value?: GeneralizedTransactionSet, + ): GeneralizedTransactionSet; + + static 0(): TransactionHistoryEntryExt; + + static 1(value: GeneralizedTransactionSet): TransactionHistoryEntryExt; + + value(): GeneralizedTransactionSet | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionHistoryEntryExt; + + static write(value: TransactionHistoryEntryExt, io: Buffer): void; + + static isValid(value: TransactionHistoryEntryExt): boolean; + + static toXDR(value: TransactionHistoryEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionHistoryEntryExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionHistoryEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionHistoryResultEntryExt { + switch(): number; + + static 0(): TransactionHistoryResultEntryExt; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionHistoryResultEntryExt; + + static write(value: TransactionHistoryResultEntryExt, io: Buffer): void; + + static isValid(value: TransactionHistoryResultEntryExt): boolean; + + static toXDR(value: TransactionHistoryResultEntryExt): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TransactionHistoryResultEntryExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionHistoryResultEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerHeaderHistoryEntryExt { + switch(): number; + + static 0(): LedgerHeaderHistoryEntryExt; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerHeaderHistoryEntryExt; + + static write(value: LedgerHeaderHistoryEntryExt, io: Buffer): void; + + static isValid(value: LedgerHeaderHistoryEntryExt): boolean; + + static toXDR(value: LedgerHeaderHistoryEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerHeaderHistoryEntryExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerHeaderHistoryEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpHistoryEntry { + switch(): number; + + v0(value?: ScpHistoryEntryV0): ScpHistoryEntryV0; + + static 0(value: ScpHistoryEntryV0): ScpHistoryEntry; + + value(): ScpHistoryEntryV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpHistoryEntry; + + static write(value: ScpHistoryEntry, io: Buffer): void; + + static isValid(value: ScpHistoryEntry): boolean; + + static toXDR(value: ScpHistoryEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpHistoryEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScpHistoryEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerEntryChange { + switch(): LedgerEntryChangeType; + + created(value?: LedgerEntry): LedgerEntry; + + updated(value?: LedgerEntry): LedgerEntry; + + removed(value?: LedgerKey): LedgerKey; + + state(value?: LedgerEntry): LedgerEntry; + + static ledgerEntryCreated(value: LedgerEntry): LedgerEntryChange; + + static ledgerEntryUpdated(value: LedgerEntry): LedgerEntryChange; + + static ledgerEntryRemoved(value: LedgerKey): LedgerEntryChange; + + static ledgerEntryState(value: LedgerEntry): LedgerEntryChange; + + value(): LedgerEntry | LedgerEntry | LedgerKey | LedgerEntry; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerEntryChange; + + static write(value: LedgerEntryChange, io: Buffer): void; + + static isValid(value: LedgerEntryChange): boolean; + + static toXDR(value: LedgerEntryChange): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerEntryChange; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerEntryChange; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractEventBody { + switch(): number; + + v0(value?: ContractEventV0): ContractEventV0; + + static 0(value: ContractEventV0): ContractEventBody; + + value(): ContractEventV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractEventBody; + + static write(value: ContractEventBody, io: Buffer): void; + + static isValid(value: ContractEventBody): boolean; + + static toXDR(value: ContractEventBody): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractEventBody; + + static fromXDR(input: string, format: 'hex' | 'base64'): ContractEventBody; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanTransactionMetaExt { + switch(): number; + + v1(value?: SorobanTransactionMetaExtV1): SorobanTransactionMetaExtV1; + + static 0(): SorobanTransactionMetaExt; + + static 1(value: SorobanTransactionMetaExtV1): SorobanTransactionMetaExt; + + value(): SorobanTransactionMetaExtV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanTransactionMetaExt; + + static write(value: SorobanTransactionMetaExt, io: Buffer): void; + + static isValid(value: SorobanTransactionMetaExt): boolean; + + static toXDR(value: SorobanTransactionMetaExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanTransactionMetaExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanTransactionMetaExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionMeta { + switch(): number; + + operations(value?: OperationMeta[]): OperationMeta[]; + + v1(value?: TransactionMetaV1): TransactionMetaV1; + + v2(value?: TransactionMetaV2): TransactionMetaV2; + + v3(value?: TransactionMetaV3): TransactionMetaV3; + + static 0(value: OperationMeta[]): TransactionMeta; + + static 1(value: TransactionMetaV1): TransactionMeta; + + static 2(value: TransactionMetaV2): TransactionMeta; + + static 3(value: TransactionMetaV3): TransactionMeta; + + value(): + | OperationMeta[] + | TransactionMetaV1 + | TransactionMetaV2 + | TransactionMetaV3; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionMeta; + + static write(value: TransactionMeta, io: Buffer): void; + + static isValid(value: TransactionMeta): boolean; + + static toXDR(value: TransactionMeta): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionMeta; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionMeta; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerCloseMetaExt { + switch(): number; + + v1(value?: LedgerCloseMetaExtV1): LedgerCloseMetaExtV1; + + static 0(): LedgerCloseMetaExt; + + static 1(value: LedgerCloseMetaExtV1): LedgerCloseMetaExt; + + value(): LedgerCloseMetaExtV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerCloseMetaExt; + + static write(value: LedgerCloseMetaExt, io: Buffer): void; + + static isValid(value: LedgerCloseMetaExt): boolean; + + static toXDR(value: LedgerCloseMetaExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerCloseMetaExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerCloseMetaExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerCloseMeta { + switch(): number; + + v0(value?: LedgerCloseMetaV0): LedgerCloseMetaV0; + + v1(value?: LedgerCloseMetaV1): LedgerCloseMetaV1; + + static 0(value: LedgerCloseMetaV0): LedgerCloseMeta; + + static 1(value: LedgerCloseMetaV1): LedgerCloseMeta; + + value(): LedgerCloseMetaV0 | LedgerCloseMetaV1; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerCloseMeta; + + static write(value: LedgerCloseMeta, io: Buffer): void; + + static isValid(value: LedgerCloseMeta): boolean; + + static toXDR(value: LedgerCloseMeta): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerCloseMeta; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerCloseMeta; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PeerAddressIp { + switch(): IpAddrType; + + ipv4(value?: Buffer): Buffer; + + ipv6(value?: Buffer): Buffer; + + static iPv4(value: Buffer): PeerAddressIp; + + static iPv6(value: Buffer): PeerAddressIp; + + value(): Buffer | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PeerAddressIp; + + static write(value: PeerAddressIp, io: Buffer): void; + + static isValid(value: PeerAddressIp): boolean; + + static toXDR(value: PeerAddressIp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PeerAddressIp; + + static fromXDR(input: string, format: 'hex' | 'base64'): PeerAddressIp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SurveyResponseBody { + switch(): SurveyMessageResponseType; + + topologyResponseBodyV0( + value?: TopologyResponseBodyV0, + ): TopologyResponseBodyV0; + + topologyResponseBodyV1( + value?: TopologyResponseBodyV1, + ): TopologyResponseBodyV1; + + topologyResponseBodyV2( + value?: TopologyResponseBodyV2, + ): TopologyResponseBodyV2; + + static surveyTopologyResponseV0( + value: TopologyResponseBodyV0, + ): SurveyResponseBody; + + static surveyTopologyResponseV1( + value: TopologyResponseBodyV1, + ): SurveyResponseBody; + + static surveyTopologyResponseV2( + value: TopologyResponseBodyV2, + ): SurveyResponseBody; + + value(): + | TopologyResponseBodyV0 + | TopologyResponseBodyV1 + | TopologyResponseBodyV2; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SurveyResponseBody; + + static write(value: SurveyResponseBody, io: Buffer): void; + + static isValid(value: SurveyResponseBody): boolean; + + static toXDR(value: SurveyResponseBody): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SurveyResponseBody; + + static fromXDR(input: string, format: 'hex' | 'base64'): SurveyResponseBody; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class StellarMessage { + switch(): MessageType; + + error(value?: Error): Error; + + hello(value?: Hello): Hello; + + auth(value?: Auth): Auth; + + dontHave(value?: DontHave): DontHave; + + peers(value?: PeerAddress[]): PeerAddress[]; + + txSetHash(value?: Buffer): Buffer; + + txSet(value?: TransactionSet): TransactionSet; + + generalizedTxSet( + value?: GeneralizedTransactionSet, + ): GeneralizedTransactionSet; + + transaction(value?: TransactionEnvelope): TransactionEnvelope; + + signedSurveyRequestMessage( + value?: SignedSurveyRequestMessage, + ): SignedSurveyRequestMessage; + + signedSurveyResponseMessage( + value?: SignedSurveyResponseMessage, + ): SignedSurveyResponseMessage; + + signedTimeSlicedSurveyRequestMessage( + value?: SignedTimeSlicedSurveyRequestMessage, + ): SignedTimeSlicedSurveyRequestMessage; + + signedTimeSlicedSurveyResponseMessage( + value?: SignedTimeSlicedSurveyResponseMessage, + ): SignedTimeSlicedSurveyResponseMessage; + + signedTimeSlicedSurveyStartCollectingMessage( + value?: SignedTimeSlicedSurveyStartCollectingMessage, + ): SignedTimeSlicedSurveyStartCollectingMessage; + + signedTimeSlicedSurveyStopCollectingMessage( + value?: SignedTimeSlicedSurveyStopCollectingMessage, + ): SignedTimeSlicedSurveyStopCollectingMessage; + + qSetHash(value?: Buffer): Buffer; + + qSet(value?: ScpQuorumSet): ScpQuorumSet; + + envelope(value?: ScpEnvelope): ScpEnvelope; + + getScpLedgerSeq(value?: number): number; + + sendMoreMessage(value?: SendMore): SendMore; + + sendMoreExtendedMessage(value?: SendMoreExtended): SendMoreExtended; + + floodAdvert(value?: FloodAdvert): FloodAdvert; + + floodDemand(value?: FloodDemand): FloodDemand; + + static errorMsg(value: Error): StellarMessage; + + static hello(value: Hello): StellarMessage; + + static auth(value: Auth): StellarMessage; + + static dontHave(value: DontHave): StellarMessage; + + static getPeers(): StellarMessage; + + static peers(value: PeerAddress[]): StellarMessage; + + static getTxSet(value: Buffer): StellarMessage; + + static txSet(value: TransactionSet): StellarMessage; + + static generalizedTxSet(value: GeneralizedTransactionSet): StellarMessage; + + static transaction(value: TransactionEnvelope): StellarMessage; + + static surveyRequest(value: SignedSurveyRequestMessage): StellarMessage; + + static surveyResponse(value: SignedSurveyResponseMessage): StellarMessage; + + static timeSlicedSurveyRequest( + value: SignedTimeSlicedSurveyRequestMessage, + ): StellarMessage; + + static timeSlicedSurveyResponse( + value: SignedTimeSlicedSurveyResponseMessage, + ): StellarMessage; + + static timeSlicedSurveyStartCollecting( + value: SignedTimeSlicedSurveyStartCollectingMessage, + ): StellarMessage; + + static timeSlicedSurveyStopCollecting( + value: SignedTimeSlicedSurveyStopCollectingMessage, + ): StellarMessage; + + static getScpQuorumset(value: Buffer): StellarMessage; + + static scpQuorumset(value: ScpQuorumSet): StellarMessage; + + static scpMessage(value: ScpEnvelope): StellarMessage; + + static getScpState(value: number): StellarMessage; + + static sendMore(value: SendMore): StellarMessage; + + static sendMoreExtended(value: SendMoreExtended): StellarMessage; + + static floodAdvert(value: FloodAdvert): StellarMessage; + + static floodDemand(value: FloodDemand): StellarMessage; + + value(): + | Error + | Hello + | Auth + | DontHave + | PeerAddress[] + | Buffer + | TransactionSet + | GeneralizedTransactionSet + | TransactionEnvelope + | SignedSurveyRequestMessage + | SignedSurveyResponseMessage + | SignedTimeSlicedSurveyRequestMessage + | SignedTimeSlicedSurveyResponseMessage + | SignedTimeSlicedSurveyStartCollectingMessage + | SignedTimeSlicedSurveyStopCollectingMessage + | Buffer + | ScpQuorumSet + | ScpEnvelope + | number + | SendMore + | SendMoreExtended + | FloodAdvert + | FloodDemand + | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): StellarMessage; + + static write(value: StellarMessage, io: Buffer): void; + + static isValid(value: StellarMessage): boolean; + + static toXDR(value: StellarMessage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): StellarMessage; + + static fromXDR(input: string, format: 'hex' | 'base64'): StellarMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AuthenticatedMessage { + switch(): number; + + v0(value?: AuthenticatedMessageV0): AuthenticatedMessageV0; + + static 0(value: AuthenticatedMessageV0): AuthenticatedMessage; + + value(): AuthenticatedMessageV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AuthenticatedMessage; + + static write(value: AuthenticatedMessage, io: Buffer): void; + + static isValid(value: AuthenticatedMessage): boolean; + + static toXDR(value: AuthenticatedMessage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AuthenticatedMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): AuthenticatedMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolParameters { + switch(): LiquidityPoolType; + + constantProduct( + value?: LiquidityPoolConstantProductParameters, + ): LiquidityPoolConstantProductParameters; + + static liquidityPoolConstantProduct( + value: LiquidityPoolConstantProductParameters, + ): LiquidityPoolParameters; + + value(): LiquidityPoolConstantProductParameters; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolParameters; + + static write(value: LiquidityPoolParameters, io: Buffer): void; + + static isValid(value: LiquidityPoolParameters): boolean; + + static toXDR(value: LiquidityPoolParameters): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LiquidityPoolParameters; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolParameters; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class MuxedAccount { + switch(): CryptoKeyType; + + ed25519(value?: Buffer): Buffer; + + med25519(value?: MuxedAccountMed25519): MuxedAccountMed25519; + + static keyTypeEd25519(value: Buffer): MuxedAccount; + + static keyTypeMuxedEd25519(value: MuxedAccountMed25519): MuxedAccount; + + value(): Buffer | MuxedAccountMed25519; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): MuxedAccount; + + static write(value: MuxedAccount, io: Buffer): void; + + static isValid(value: MuxedAccount): boolean; + + static toXDR(value: MuxedAccount): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): MuxedAccount; + + static fromXDR(input: string, format: 'hex' | 'base64'): MuxedAccount; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ChangeTrustAsset { + switch(): AssetType; + + alphaNum4(value?: AlphaNum4): AlphaNum4; + + alphaNum12(value?: AlphaNum12): AlphaNum12; + + liquidityPool(value?: LiquidityPoolParameters): LiquidityPoolParameters; + + static assetTypeNative(): ChangeTrustAsset; + + static assetTypeCreditAlphanum4(value: AlphaNum4): ChangeTrustAsset; + + static assetTypeCreditAlphanum12(value: AlphaNum12): ChangeTrustAsset; + + static assetTypePoolShare(value: LiquidityPoolParameters): ChangeTrustAsset; + + value(): AlphaNum4 | AlphaNum12 | LiquidityPoolParameters | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ChangeTrustAsset; + + static write(value: ChangeTrustAsset, io: Buffer): void; + + static isValid(value: ChangeTrustAsset): boolean; + + static toXDR(value: ChangeTrustAsset): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ChangeTrustAsset; + + static fromXDR(input: string, format: 'hex' | 'base64'): ChangeTrustAsset; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class RevokeSponsorshipOp { + switch(): RevokeSponsorshipType; + + ledgerKey(value?: LedgerKey): LedgerKey; + + signer(value?: RevokeSponsorshipOpSigner): RevokeSponsorshipOpSigner; + + static revokeSponsorshipLedgerEntry(value: LedgerKey): RevokeSponsorshipOp; + + static revokeSponsorshipSigner( + value: RevokeSponsorshipOpSigner, + ): RevokeSponsorshipOp; + + value(): LedgerKey | RevokeSponsorshipOpSigner; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): RevokeSponsorshipOp; + + static write(value: RevokeSponsorshipOp, io: Buffer): void; + + static isValid(value: RevokeSponsorshipOp): boolean; + + static toXDR(value: RevokeSponsorshipOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): RevokeSponsorshipOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): RevokeSponsorshipOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractIdPreimage { + switch(): ContractIdPreimageType; + + fromAddress( + value?: ContractIdPreimageFromAddress, + ): ContractIdPreimageFromAddress; + + fromAsset(value?: Asset): Asset; + + static contractIdPreimageFromAddress( + value: ContractIdPreimageFromAddress, + ): ContractIdPreimage; + + static contractIdPreimageFromAsset(value: Asset): ContractIdPreimage; + + value(): ContractIdPreimageFromAddress | Asset; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractIdPreimage; + + static write(value: ContractIdPreimage, io: Buffer): void; + + static isValid(value: ContractIdPreimage): boolean; + + static toXDR(value: ContractIdPreimage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractIdPreimage; + + static fromXDR(input: string, format: 'hex' | 'base64'): ContractIdPreimage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HostFunction { + switch(): HostFunctionType; + + invokeContract(value?: InvokeContractArgs): InvokeContractArgs; + + createContract(value?: CreateContractArgs): CreateContractArgs; + + wasm(value?: Buffer): Buffer; + + createContractV2(value?: CreateContractArgsV2): CreateContractArgsV2; + + static hostFunctionTypeInvokeContract( + value: InvokeContractArgs, + ): HostFunction; + + static hostFunctionTypeCreateContract( + value: CreateContractArgs, + ): HostFunction; + + static hostFunctionTypeUploadContractWasm(value: Buffer): HostFunction; + + static hostFunctionTypeCreateContractV2( + value: CreateContractArgsV2, + ): HostFunction; + + value(): + | InvokeContractArgs + | CreateContractArgs + | Buffer + | CreateContractArgsV2; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HostFunction; + + static write(value: HostFunction, io: Buffer): void; + + static isValid(value: HostFunction): boolean; + + static toXDR(value: HostFunction): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HostFunction; + + static fromXDR(input: string, format: 'hex' | 'base64'): HostFunction; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanAuthorizedFunction { + switch(): SorobanAuthorizedFunctionType; + + contractFn(value?: InvokeContractArgs): InvokeContractArgs; + + createContractHostFn(value?: CreateContractArgs): CreateContractArgs; + + createContractV2HostFn(value?: CreateContractArgsV2): CreateContractArgsV2; + + static sorobanAuthorizedFunctionTypeContractFn( + value: InvokeContractArgs, + ): SorobanAuthorizedFunction; + + static sorobanAuthorizedFunctionTypeCreateContractHostFn( + value: CreateContractArgs, + ): SorobanAuthorizedFunction; + + static sorobanAuthorizedFunctionTypeCreateContractV2HostFn( + value: CreateContractArgsV2, + ): SorobanAuthorizedFunction; + + value(): InvokeContractArgs | CreateContractArgs | CreateContractArgsV2; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanAuthorizedFunction; + + static write(value: SorobanAuthorizedFunction, io: Buffer): void; + + static isValid(value: SorobanAuthorizedFunction): boolean; + + static toXDR(value: SorobanAuthorizedFunction): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanAuthorizedFunction; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanAuthorizedFunction; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanCredentials { + switch(): SorobanCredentialsType; + + address(value?: SorobanAddressCredentials): SorobanAddressCredentials; + + static sorobanCredentialsSourceAccount(): SorobanCredentials; + + static sorobanCredentialsAddress( + value: SorobanAddressCredentials, + ): SorobanCredentials; + + value(): SorobanAddressCredentials | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanCredentials; + + static write(value: SorobanCredentials, io: Buffer): void; + + static isValid(value: SorobanCredentials): boolean; + + static toXDR(value: SorobanCredentials): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanCredentials; + + static fromXDR(input: string, format: 'hex' | 'base64'): SorobanCredentials; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class OperationBody { + switch(): OperationType; + + createAccountOp(value?: CreateAccountOp): CreateAccountOp; + + paymentOp(value?: PaymentOp): PaymentOp; + + pathPaymentStrictReceiveOp( + value?: PathPaymentStrictReceiveOp, + ): PathPaymentStrictReceiveOp; + + manageSellOfferOp(value?: ManageSellOfferOp): ManageSellOfferOp; + + createPassiveSellOfferOp( + value?: CreatePassiveSellOfferOp, + ): CreatePassiveSellOfferOp; + + setOptionsOp(value?: SetOptionsOp): SetOptionsOp; + + changeTrustOp(value?: ChangeTrustOp): ChangeTrustOp; + + allowTrustOp(value?: AllowTrustOp): AllowTrustOp; + + destination(value?: MuxedAccount): MuxedAccount; + + manageDataOp(value?: ManageDataOp): ManageDataOp; + + bumpSequenceOp(value?: BumpSequenceOp): BumpSequenceOp; + + manageBuyOfferOp(value?: ManageBuyOfferOp): ManageBuyOfferOp; + + pathPaymentStrictSendOp( + value?: PathPaymentStrictSendOp, + ): PathPaymentStrictSendOp; + + createClaimableBalanceOp( + value?: CreateClaimableBalanceOp, + ): CreateClaimableBalanceOp; + + claimClaimableBalanceOp( + value?: ClaimClaimableBalanceOp, + ): ClaimClaimableBalanceOp; + + beginSponsoringFutureReservesOp( + value?: BeginSponsoringFutureReservesOp, + ): BeginSponsoringFutureReservesOp; + + revokeSponsorshipOp(value?: RevokeSponsorshipOp): RevokeSponsorshipOp; + + clawbackOp(value?: ClawbackOp): ClawbackOp; + + clawbackClaimableBalanceOp( + value?: ClawbackClaimableBalanceOp, + ): ClawbackClaimableBalanceOp; + + setTrustLineFlagsOp(value?: SetTrustLineFlagsOp): SetTrustLineFlagsOp; + + liquidityPoolDepositOp( + value?: LiquidityPoolDepositOp, + ): LiquidityPoolDepositOp; + + liquidityPoolWithdrawOp( + value?: LiquidityPoolWithdrawOp, + ): LiquidityPoolWithdrawOp; + + invokeHostFunctionOp(value?: InvokeHostFunctionOp): InvokeHostFunctionOp; + + extendFootprintTtlOp(value?: ExtendFootprintTtlOp): ExtendFootprintTtlOp; + + restoreFootprintOp(value?: RestoreFootprintOp): RestoreFootprintOp; + + static createAccount(value: CreateAccountOp): OperationBody; + + static payment(value: PaymentOp): OperationBody; + + static pathPaymentStrictReceive( + value: PathPaymentStrictReceiveOp, + ): OperationBody; + + static manageSellOffer(value: ManageSellOfferOp): OperationBody; + + static createPassiveSellOffer( + value: CreatePassiveSellOfferOp, + ): OperationBody; + + static setOptions(value: SetOptionsOp): OperationBody; + + static changeTrust(value: ChangeTrustOp): OperationBody; + + static allowTrust(value: AllowTrustOp): OperationBody; + + static accountMerge(value: MuxedAccount): OperationBody; + + static inflation(): OperationBody; + + static manageData(value: ManageDataOp): OperationBody; + + static bumpSequence(value: BumpSequenceOp): OperationBody; + + static manageBuyOffer(value: ManageBuyOfferOp): OperationBody; + + static pathPaymentStrictSend(value: PathPaymentStrictSendOp): OperationBody; + + static createClaimableBalance( + value: CreateClaimableBalanceOp, + ): OperationBody; + + static claimClaimableBalance(value: ClaimClaimableBalanceOp): OperationBody; + + static beginSponsoringFutureReserves( + value: BeginSponsoringFutureReservesOp, + ): OperationBody; + + static endSponsoringFutureReserves(): OperationBody; + + static revokeSponsorship(value: RevokeSponsorshipOp): OperationBody; + + static clawback(value: ClawbackOp): OperationBody; + + static clawbackClaimableBalance( + value: ClawbackClaimableBalanceOp, + ): OperationBody; + + static setTrustLineFlags(value: SetTrustLineFlagsOp): OperationBody; + + static liquidityPoolDeposit(value: LiquidityPoolDepositOp): OperationBody; + + static liquidityPoolWithdraw(value: LiquidityPoolWithdrawOp): OperationBody; + + static invokeHostFunction(value: InvokeHostFunctionOp): OperationBody; + + static extendFootprintTtl(value: ExtendFootprintTtlOp): OperationBody; + + static restoreFootprint(value: RestoreFootprintOp): OperationBody; + + value(): + | CreateAccountOp + | PaymentOp + | PathPaymentStrictReceiveOp + | ManageSellOfferOp + | CreatePassiveSellOfferOp + | SetOptionsOp + | ChangeTrustOp + | AllowTrustOp + | MuxedAccount + | ManageDataOp + | BumpSequenceOp + | ManageBuyOfferOp + | PathPaymentStrictSendOp + | CreateClaimableBalanceOp + | ClaimClaimableBalanceOp + | BeginSponsoringFutureReservesOp + | RevokeSponsorshipOp + | ClawbackOp + | ClawbackClaimableBalanceOp + | SetTrustLineFlagsOp + | LiquidityPoolDepositOp + | LiquidityPoolWithdrawOp + | InvokeHostFunctionOp + | ExtendFootprintTtlOp + | RestoreFootprintOp + | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): OperationBody; + + static write(value: OperationBody, io: Buffer): void; + + static isValid(value: OperationBody): boolean; + + static toXDR(value: OperationBody): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): OperationBody; + + static fromXDR(input: string, format: 'hex' | 'base64'): OperationBody; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HashIdPreimage { + switch(): EnvelopeType; + + operationId(value?: HashIdPreimageOperationId): HashIdPreimageOperationId; + + revokeId(value?: HashIdPreimageRevokeId): HashIdPreimageRevokeId; + + contractId(value?: HashIdPreimageContractId): HashIdPreimageContractId; + + sorobanAuthorization( + value?: HashIdPreimageSorobanAuthorization, + ): HashIdPreimageSorobanAuthorization; + + static envelopeTypeOpId(value: HashIdPreimageOperationId): HashIdPreimage; + + static envelopeTypePoolRevokeOpId( + value: HashIdPreimageRevokeId, + ): HashIdPreimage; + + static envelopeTypeContractId( + value: HashIdPreimageContractId, + ): HashIdPreimage; + + static envelopeTypeSorobanAuthorization( + value: HashIdPreimageSorobanAuthorization, + ): HashIdPreimage; + + value(): + | HashIdPreimageOperationId + | HashIdPreimageRevokeId + | HashIdPreimageContractId + | HashIdPreimageSorobanAuthorization; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HashIdPreimage; + + static write(value: HashIdPreimage, io: Buffer): void; + + static isValid(value: HashIdPreimage): boolean; + + static toXDR(value: HashIdPreimage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HashIdPreimage; + + static fromXDR(input: string, format: 'hex' | 'base64'): HashIdPreimage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Memo { + switch(): MemoType; + + text(value?: string | Buffer): string | Buffer; + + id(value?: Uint64): Uint64; + + hash(value?: Buffer): Buffer; + + retHash(value?: Buffer): Buffer; + + static memoNone(): Memo; + + static memoText(value: string | Buffer): Memo; + + static memoId(value: Uint64): Memo; + + static memoHash(value: Buffer): Memo; + + static memoReturn(value: Buffer): Memo; + + value(): string | Buffer | Uint64 | Buffer | Buffer | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Memo; + + static write(value: Memo, io: Buffer): void; + + static isValid(value: Memo): boolean; + + static toXDR(value: Memo): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Memo; + + static fromXDR(input: string, format: 'hex' | 'base64'): Memo; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Preconditions { + switch(): PreconditionType; + + timeBounds(value?: TimeBounds): TimeBounds; + + v2(value?: PreconditionsV2): PreconditionsV2; + + static precondNone(): Preconditions; + + static precondTime(value: TimeBounds): Preconditions; + + static precondV2(value: PreconditionsV2): Preconditions; + + value(): TimeBounds | PreconditionsV2 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Preconditions; + + static write(value: Preconditions, io: Buffer): void; + + static isValid(value: Preconditions): boolean; + + static toXDR(value: Preconditions): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Preconditions; + + static fromXDR(input: string, format: 'hex' | 'base64'): Preconditions; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ArchivalProofBody { + switch(): ArchivalProofType; + + nonexistenceProof(value?: NonexistenceProofBody): NonexistenceProofBody; + + existenceProof(value?: ExistenceProofBody): ExistenceProofBody; + + static existence(value: NonexistenceProofBody): ArchivalProofBody; + + static nonexistence(value: ExistenceProofBody): ArchivalProofBody; + + value(): NonexistenceProofBody | ExistenceProofBody; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ArchivalProofBody; + + static write(value: ArchivalProofBody, io: Buffer): void; + + static isValid(value: ArchivalProofBody): boolean; + + static toXDR(value: ArchivalProofBody): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ArchivalProofBody; + + static fromXDR(input: string, format: 'hex' | 'base64'): ArchivalProofBody; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionV0Ext { + switch(): number; + + static 0(): TransactionV0Ext; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionV0Ext; + + static write(value: TransactionV0Ext, io: Buffer): void; + + static isValid(value: TransactionV0Ext): boolean; + + static toXDR(value: TransactionV0Ext): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionV0Ext; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionV0Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionExt { + switch(): number; + + sorobanData(value?: SorobanTransactionData): SorobanTransactionData; + + static 0(): TransactionExt; + + static 1(value: SorobanTransactionData): TransactionExt; + + value(): SorobanTransactionData | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionExt; + + static write(value: TransactionExt, io: Buffer): void; + + static isValid(value: TransactionExt): boolean; + + static toXDR(value: TransactionExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class FeeBumpTransactionInnerTx { + switch(): EnvelopeType; + + v1(value?: TransactionV1Envelope): TransactionV1Envelope; + + static envelopeTypeTx( + value: TransactionV1Envelope, + ): FeeBumpTransactionInnerTx; + + value(): TransactionV1Envelope; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): FeeBumpTransactionInnerTx; + + static write(value: FeeBumpTransactionInnerTx, io: Buffer): void; + + static isValid(value: FeeBumpTransactionInnerTx): boolean; + + static toXDR(value: FeeBumpTransactionInnerTx): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): FeeBumpTransactionInnerTx; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): FeeBumpTransactionInnerTx; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class FeeBumpTransactionExt { + switch(): number; + + static 0(): FeeBumpTransactionExt; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): FeeBumpTransactionExt; + + static write(value: FeeBumpTransactionExt, io: Buffer): void; + + static isValid(value: FeeBumpTransactionExt): boolean; + + static toXDR(value: FeeBumpTransactionExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): FeeBumpTransactionExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): FeeBumpTransactionExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionEnvelope { + switch(): EnvelopeType; + + v0(value?: TransactionV0Envelope): TransactionV0Envelope; + + v1(value?: TransactionV1Envelope): TransactionV1Envelope; + + feeBump(value?: FeeBumpTransactionEnvelope): FeeBumpTransactionEnvelope; + + static envelopeTypeTxV0(value: TransactionV0Envelope): TransactionEnvelope; + + static envelopeTypeTx(value: TransactionV1Envelope): TransactionEnvelope; + + static envelopeTypeTxFeeBump( + value: FeeBumpTransactionEnvelope, + ): TransactionEnvelope; + + value(): + | TransactionV0Envelope + | TransactionV1Envelope + | FeeBumpTransactionEnvelope; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionEnvelope; + + static write(value: TransactionEnvelope, io: Buffer): void; + + static isValid(value: TransactionEnvelope): boolean; + + static toXDR(value: TransactionEnvelope): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionEnvelope; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionEnvelope; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionSignaturePayloadTaggedTransaction { + switch(): EnvelopeType; + + tx(value?: Transaction): Transaction; + + feeBump(value?: FeeBumpTransaction): FeeBumpTransaction; + + static envelopeTypeTx( + value: Transaction, + ): TransactionSignaturePayloadTaggedTransaction; + + static envelopeTypeTxFeeBump( + value: FeeBumpTransaction, + ): TransactionSignaturePayloadTaggedTransaction; + + value(): Transaction | FeeBumpTransaction; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionSignaturePayloadTaggedTransaction; + + static write( + value: TransactionSignaturePayloadTaggedTransaction, + io: Buffer, + ): void; + + static isValid( + value: TransactionSignaturePayloadTaggedTransaction, + ): boolean; + + static toXDR(value: TransactionSignaturePayloadTaggedTransaction): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TransactionSignaturePayloadTaggedTransaction; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionSignaturePayloadTaggedTransaction; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimAtom { + switch(): ClaimAtomType; + + v0(value?: ClaimOfferAtomV0): ClaimOfferAtomV0; + + orderBook(value?: ClaimOfferAtom): ClaimOfferAtom; + + liquidityPool(value?: ClaimLiquidityAtom): ClaimLiquidityAtom; + + static claimAtomTypeV0(value: ClaimOfferAtomV0): ClaimAtom; + + static claimAtomTypeOrderBook(value: ClaimOfferAtom): ClaimAtom; + + static claimAtomTypeLiquidityPool(value: ClaimLiquidityAtom): ClaimAtom; + + value(): ClaimOfferAtomV0 | ClaimOfferAtom | ClaimLiquidityAtom; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimAtom; + + static write(value: ClaimAtom, io: Buffer): void; + + static isValid(value: ClaimAtom): boolean; + + static toXDR(value: ClaimAtom): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimAtom; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClaimAtom; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class CreateAccountResult { + switch(): CreateAccountResultCode; + + static createAccountSuccess(): CreateAccountResult; + + static createAccountMalformed(): CreateAccountResult; + + static createAccountUnderfunded(): CreateAccountResult; + + static createAccountLowReserve(): CreateAccountResult; + + static createAccountAlreadyExist(): CreateAccountResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): CreateAccountResult; + + static write(value: CreateAccountResult, io: Buffer): void; + + static isValid(value: CreateAccountResult): boolean; + + static toXDR(value: CreateAccountResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): CreateAccountResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): CreateAccountResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PaymentResult { + switch(): PaymentResultCode; + + static paymentSuccess(): PaymentResult; + + static paymentMalformed(): PaymentResult; + + static paymentUnderfunded(): PaymentResult; + + static paymentSrcNoTrust(): PaymentResult; + + static paymentSrcNotAuthorized(): PaymentResult; + + static paymentNoDestination(): PaymentResult; + + static paymentNoTrust(): PaymentResult; + + static paymentNotAuthorized(): PaymentResult; + + static paymentLineFull(): PaymentResult; + + static paymentNoIssuer(): PaymentResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PaymentResult; + + static write(value: PaymentResult, io: Buffer): void; + + static isValid(value: PaymentResult): boolean; + + static toXDR(value: PaymentResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PaymentResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): PaymentResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PathPaymentStrictReceiveResult { + switch(): PathPaymentStrictReceiveResultCode; + + success( + value?: PathPaymentStrictReceiveResultSuccess, + ): PathPaymentStrictReceiveResultSuccess; + + noIssuer(value?: Asset): Asset; + + static pathPaymentStrictReceiveSuccess( + value: PathPaymentStrictReceiveResultSuccess, + ): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveMalformed(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveUnderfunded(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveSrcNoTrust(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveSrcNotAuthorized(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveNoDestination(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveNoTrust(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveNotAuthorized(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveLineFull(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveNoIssuer( + value: Asset, + ): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveTooFewOffers(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveOfferCrossSelf(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveOverSendmax(): PathPaymentStrictReceiveResult; + + value(): PathPaymentStrictReceiveResultSuccess | Asset | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PathPaymentStrictReceiveResult; + + static write(value: PathPaymentStrictReceiveResult, io: Buffer): void; + + static isValid(value: PathPaymentStrictReceiveResult): boolean; + + static toXDR(value: PathPaymentStrictReceiveResult): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): PathPaymentStrictReceiveResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): PathPaymentStrictReceiveResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PathPaymentStrictSendResult { + switch(): PathPaymentStrictSendResultCode; + + success( + value?: PathPaymentStrictSendResultSuccess, + ): PathPaymentStrictSendResultSuccess; + + noIssuer(value?: Asset): Asset; + + static pathPaymentStrictSendSuccess( + value: PathPaymentStrictSendResultSuccess, + ): PathPaymentStrictSendResult; + + static pathPaymentStrictSendMalformed(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendUnderfunded(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendSrcNoTrust(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendSrcNotAuthorized(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendNoDestination(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendNoTrust(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendNotAuthorized(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendLineFull(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendNoIssuer( + value: Asset, + ): PathPaymentStrictSendResult; + + static pathPaymentStrictSendTooFewOffers(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendOfferCrossSelf(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendUnderDestmin(): PathPaymentStrictSendResult; + + value(): PathPaymentStrictSendResultSuccess | Asset | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PathPaymentStrictSendResult; + + static write(value: PathPaymentStrictSendResult, io: Buffer): void; + + static isValid(value: PathPaymentStrictSendResult): boolean; + + static toXDR(value: PathPaymentStrictSendResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PathPaymentStrictSendResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): PathPaymentStrictSendResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageOfferSuccessResultOffer { + switch(): ManageOfferEffect; + + offer(value?: OfferEntry): OfferEntry; + + static manageOfferCreated(value: OfferEntry): ManageOfferSuccessResultOffer; + + static manageOfferUpdated(value: OfferEntry): ManageOfferSuccessResultOffer; + + static manageOfferDeleted(): ManageOfferSuccessResultOffer; + + value(): OfferEntry | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageOfferSuccessResultOffer; + + static write(value: ManageOfferSuccessResultOffer, io: Buffer): void; + + static isValid(value: ManageOfferSuccessResultOffer): boolean; + + static toXDR(value: ManageOfferSuccessResultOffer): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ManageOfferSuccessResultOffer; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ManageOfferSuccessResultOffer; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageSellOfferResult { + switch(): ManageSellOfferResultCode; + + success(value?: ManageOfferSuccessResult): ManageOfferSuccessResult; + + static manageSellOfferSuccess( + value: ManageOfferSuccessResult, + ): ManageSellOfferResult; + + static manageSellOfferMalformed(): ManageSellOfferResult; + + static manageSellOfferSellNoTrust(): ManageSellOfferResult; + + static manageSellOfferBuyNoTrust(): ManageSellOfferResult; + + static manageSellOfferSellNotAuthorized(): ManageSellOfferResult; + + static manageSellOfferBuyNotAuthorized(): ManageSellOfferResult; + + static manageSellOfferLineFull(): ManageSellOfferResult; + + static manageSellOfferUnderfunded(): ManageSellOfferResult; + + static manageSellOfferCrossSelf(): ManageSellOfferResult; + + static manageSellOfferSellNoIssuer(): ManageSellOfferResult; + + static manageSellOfferBuyNoIssuer(): ManageSellOfferResult; + + static manageSellOfferNotFound(): ManageSellOfferResult; + + static manageSellOfferLowReserve(): ManageSellOfferResult; + + value(): ManageOfferSuccessResult | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageSellOfferResult; + + static write(value: ManageSellOfferResult, io: Buffer): void; + + static isValid(value: ManageSellOfferResult): boolean; + + static toXDR(value: ManageSellOfferResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ManageSellOfferResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ManageSellOfferResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageBuyOfferResult { + switch(): ManageBuyOfferResultCode; + + success(value?: ManageOfferSuccessResult): ManageOfferSuccessResult; + + static manageBuyOfferSuccess( + value: ManageOfferSuccessResult, + ): ManageBuyOfferResult; + + static manageBuyOfferMalformed(): ManageBuyOfferResult; + + static manageBuyOfferSellNoTrust(): ManageBuyOfferResult; + + static manageBuyOfferBuyNoTrust(): ManageBuyOfferResult; + + static manageBuyOfferSellNotAuthorized(): ManageBuyOfferResult; + + static manageBuyOfferBuyNotAuthorized(): ManageBuyOfferResult; + + static manageBuyOfferLineFull(): ManageBuyOfferResult; + + static manageBuyOfferUnderfunded(): ManageBuyOfferResult; + + static manageBuyOfferCrossSelf(): ManageBuyOfferResult; + + static manageBuyOfferSellNoIssuer(): ManageBuyOfferResult; + + static manageBuyOfferBuyNoIssuer(): ManageBuyOfferResult; + + static manageBuyOfferNotFound(): ManageBuyOfferResult; + + static manageBuyOfferLowReserve(): ManageBuyOfferResult; + + value(): ManageOfferSuccessResult | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageBuyOfferResult; + + static write(value: ManageBuyOfferResult, io: Buffer): void; + + static isValid(value: ManageBuyOfferResult): boolean; + + static toXDR(value: ManageBuyOfferResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ManageBuyOfferResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ManageBuyOfferResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SetOptionsResult { + switch(): SetOptionsResultCode; + + static setOptionsSuccess(): SetOptionsResult; + + static setOptionsLowReserve(): SetOptionsResult; + + static setOptionsTooManySigners(): SetOptionsResult; + + static setOptionsBadFlags(): SetOptionsResult; + + static setOptionsInvalidInflation(): SetOptionsResult; + + static setOptionsCantChange(): SetOptionsResult; + + static setOptionsUnknownFlag(): SetOptionsResult; + + static setOptionsThresholdOutOfRange(): SetOptionsResult; + + static setOptionsBadSigner(): SetOptionsResult; + + static setOptionsInvalidHomeDomain(): SetOptionsResult; + + static setOptionsAuthRevocableRequired(): SetOptionsResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SetOptionsResult; + + static write(value: SetOptionsResult, io: Buffer): void; + + static isValid(value: SetOptionsResult): boolean; + + static toXDR(value: SetOptionsResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SetOptionsResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): SetOptionsResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ChangeTrustResult { + switch(): ChangeTrustResultCode; + + static changeTrustSuccess(): ChangeTrustResult; + + static changeTrustMalformed(): ChangeTrustResult; + + static changeTrustNoIssuer(): ChangeTrustResult; + + static changeTrustInvalidLimit(): ChangeTrustResult; + + static changeTrustLowReserve(): ChangeTrustResult; + + static changeTrustSelfNotAllowed(): ChangeTrustResult; + + static changeTrustTrustLineMissing(): ChangeTrustResult; + + static changeTrustCannotDelete(): ChangeTrustResult; + + static changeTrustNotAuthMaintainLiabilities(): ChangeTrustResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ChangeTrustResult; + + static write(value: ChangeTrustResult, io: Buffer): void; + + static isValid(value: ChangeTrustResult): boolean; + + static toXDR(value: ChangeTrustResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ChangeTrustResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): ChangeTrustResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AllowTrustResult { + switch(): AllowTrustResultCode; + + static allowTrustSuccess(): AllowTrustResult; + + static allowTrustMalformed(): AllowTrustResult; + + static allowTrustNoTrustLine(): AllowTrustResult; + + static allowTrustTrustNotRequired(): AllowTrustResult; + + static allowTrustCantRevoke(): AllowTrustResult; + + static allowTrustSelfNotAllowed(): AllowTrustResult; + + static allowTrustLowReserve(): AllowTrustResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AllowTrustResult; + + static write(value: AllowTrustResult, io: Buffer): void; + + static isValid(value: AllowTrustResult): boolean; + + static toXDR(value: AllowTrustResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AllowTrustResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): AllowTrustResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountMergeResult { + switch(): AccountMergeResultCode; + + sourceAccountBalance(value?: Int64): Int64; + + static accountMergeSuccess(value: Int64): AccountMergeResult; + + static accountMergeMalformed(): AccountMergeResult; + + static accountMergeNoAccount(): AccountMergeResult; + + static accountMergeImmutableSet(): AccountMergeResult; + + static accountMergeHasSubEntries(): AccountMergeResult; + + static accountMergeSeqnumTooFar(): AccountMergeResult; + + static accountMergeDestFull(): AccountMergeResult; + + static accountMergeIsSponsor(): AccountMergeResult; + + value(): Int64 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountMergeResult; + + static write(value: AccountMergeResult, io: Buffer): void; + + static isValid(value: AccountMergeResult): boolean; + + static toXDR(value: AccountMergeResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountMergeResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): AccountMergeResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InflationResult { + switch(): InflationResultCode; + + payouts(value?: InflationPayout[]): InflationPayout[]; + + static inflationSuccess(value: InflationPayout[]): InflationResult; + + static inflationNotTime(): InflationResult; + + value(): InflationPayout[] | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InflationResult; + + static write(value: InflationResult, io: Buffer): void; + + static isValid(value: InflationResult): boolean; + + static toXDR(value: InflationResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InflationResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): InflationResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageDataResult { + switch(): ManageDataResultCode; + + static manageDataSuccess(): ManageDataResult; + + static manageDataNotSupportedYet(): ManageDataResult; + + static manageDataNameNotFound(): ManageDataResult; + + static manageDataLowReserve(): ManageDataResult; + + static manageDataInvalidName(): ManageDataResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageDataResult; + + static write(value: ManageDataResult, io: Buffer): void; + + static isValid(value: ManageDataResult): boolean; + + static toXDR(value: ManageDataResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ManageDataResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): ManageDataResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class BumpSequenceResult { + switch(): BumpSequenceResultCode; + + static bumpSequenceSuccess(): BumpSequenceResult; + + static bumpSequenceBadSeq(): BumpSequenceResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): BumpSequenceResult; + + static write(value: BumpSequenceResult, io: Buffer): void; + + static isValid(value: BumpSequenceResult): boolean; + + static toXDR(value: BumpSequenceResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): BumpSequenceResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): BumpSequenceResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class CreateClaimableBalanceResult { + switch(): CreateClaimableBalanceResultCode; + + balanceId(value?: ClaimableBalanceId): ClaimableBalanceId; + + static createClaimableBalanceSuccess( + value: ClaimableBalanceId, + ): CreateClaimableBalanceResult; + + static createClaimableBalanceMalformed(): CreateClaimableBalanceResult; + + static createClaimableBalanceLowReserve(): CreateClaimableBalanceResult; + + static createClaimableBalanceNoTrust(): CreateClaimableBalanceResult; + + static createClaimableBalanceNotAuthorized(): CreateClaimableBalanceResult; + + static createClaimableBalanceUnderfunded(): CreateClaimableBalanceResult; + + value(): ClaimableBalanceId | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): CreateClaimableBalanceResult; + + static write(value: CreateClaimableBalanceResult, io: Buffer): void; + + static isValid(value: CreateClaimableBalanceResult): boolean; + + static toXDR(value: CreateClaimableBalanceResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): CreateClaimableBalanceResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): CreateClaimableBalanceResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimClaimableBalanceResult { + switch(): ClaimClaimableBalanceResultCode; + + static claimClaimableBalanceSuccess(): ClaimClaimableBalanceResult; + + static claimClaimableBalanceDoesNotExist(): ClaimClaimableBalanceResult; + + static claimClaimableBalanceCannotClaim(): ClaimClaimableBalanceResult; + + static claimClaimableBalanceLineFull(): ClaimClaimableBalanceResult; + + static claimClaimableBalanceNoTrust(): ClaimClaimableBalanceResult; + + static claimClaimableBalanceNotAuthorized(): ClaimClaimableBalanceResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimClaimableBalanceResult; + + static write(value: ClaimClaimableBalanceResult, io: Buffer): void; + + static isValid(value: ClaimClaimableBalanceResult): boolean; + + static toXDR(value: ClaimClaimableBalanceResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimClaimableBalanceResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClaimClaimableBalanceResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class BeginSponsoringFutureReservesResult { + switch(): BeginSponsoringFutureReservesResultCode; + + static beginSponsoringFutureReservesSuccess(): BeginSponsoringFutureReservesResult; + + static beginSponsoringFutureReservesMalformed(): BeginSponsoringFutureReservesResult; + + static beginSponsoringFutureReservesAlreadySponsored(): BeginSponsoringFutureReservesResult; + + static beginSponsoringFutureReservesRecursive(): BeginSponsoringFutureReservesResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): BeginSponsoringFutureReservesResult; + + static write(value: BeginSponsoringFutureReservesResult, io: Buffer): void; + + static isValid(value: BeginSponsoringFutureReservesResult): boolean; + + static toXDR(value: BeginSponsoringFutureReservesResult): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): BeginSponsoringFutureReservesResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): BeginSponsoringFutureReservesResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class EndSponsoringFutureReservesResult { + switch(): EndSponsoringFutureReservesResultCode; + + static endSponsoringFutureReservesSuccess(): EndSponsoringFutureReservesResult; + + static endSponsoringFutureReservesNotSponsored(): EndSponsoringFutureReservesResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): EndSponsoringFutureReservesResult; + + static write(value: EndSponsoringFutureReservesResult, io: Buffer): void; + + static isValid(value: EndSponsoringFutureReservesResult): boolean; + + static toXDR(value: EndSponsoringFutureReservesResult): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): EndSponsoringFutureReservesResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): EndSponsoringFutureReservesResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class RevokeSponsorshipResult { + switch(): RevokeSponsorshipResultCode; + + static revokeSponsorshipSuccess(): RevokeSponsorshipResult; + + static revokeSponsorshipDoesNotExist(): RevokeSponsorshipResult; + + static revokeSponsorshipNotSponsor(): RevokeSponsorshipResult; + + static revokeSponsorshipLowReserve(): RevokeSponsorshipResult; + + static revokeSponsorshipOnlyTransferable(): RevokeSponsorshipResult; + + static revokeSponsorshipMalformed(): RevokeSponsorshipResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): RevokeSponsorshipResult; + + static write(value: RevokeSponsorshipResult, io: Buffer): void; + + static isValid(value: RevokeSponsorshipResult): boolean; + + static toXDR(value: RevokeSponsorshipResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): RevokeSponsorshipResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): RevokeSponsorshipResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClawbackResult { + switch(): ClawbackResultCode; + + static clawbackSuccess(): ClawbackResult; + + static clawbackMalformed(): ClawbackResult; + + static clawbackNotClawbackEnabled(): ClawbackResult; + + static clawbackNoTrust(): ClawbackResult; + + static clawbackUnderfunded(): ClawbackResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClawbackResult; + + static write(value: ClawbackResult, io: Buffer): void; + + static isValid(value: ClawbackResult): boolean; + + static toXDR(value: ClawbackResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClawbackResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClawbackResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClawbackClaimableBalanceResult { + switch(): ClawbackClaimableBalanceResultCode; + + static clawbackClaimableBalanceSuccess(): ClawbackClaimableBalanceResult; + + static clawbackClaimableBalanceDoesNotExist(): ClawbackClaimableBalanceResult; + + static clawbackClaimableBalanceNotIssuer(): ClawbackClaimableBalanceResult; + + static clawbackClaimableBalanceNotClawbackEnabled(): ClawbackClaimableBalanceResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClawbackClaimableBalanceResult; + + static write(value: ClawbackClaimableBalanceResult, io: Buffer): void; + + static isValid(value: ClawbackClaimableBalanceResult): boolean; + + static toXDR(value: ClawbackClaimableBalanceResult): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ClawbackClaimableBalanceResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClawbackClaimableBalanceResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SetTrustLineFlagsResult { + switch(): SetTrustLineFlagsResultCode; + + static setTrustLineFlagsSuccess(): SetTrustLineFlagsResult; + + static setTrustLineFlagsMalformed(): SetTrustLineFlagsResult; + + static setTrustLineFlagsNoTrustLine(): SetTrustLineFlagsResult; + + static setTrustLineFlagsCantRevoke(): SetTrustLineFlagsResult; + + static setTrustLineFlagsInvalidState(): SetTrustLineFlagsResult; + + static setTrustLineFlagsLowReserve(): SetTrustLineFlagsResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SetTrustLineFlagsResult; + + static write(value: SetTrustLineFlagsResult, io: Buffer): void; + + static isValid(value: SetTrustLineFlagsResult): boolean; + + static toXDR(value: SetTrustLineFlagsResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SetTrustLineFlagsResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SetTrustLineFlagsResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolDepositResult { + switch(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositSuccess(): LiquidityPoolDepositResult; + + static liquidityPoolDepositMalformed(): LiquidityPoolDepositResult; + + static liquidityPoolDepositNoTrust(): LiquidityPoolDepositResult; + + static liquidityPoolDepositNotAuthorized(): LiquidityPoolDepositResult; + + static liquidityPoolDepositUnderfunded(): LiquidityPoolDepositResult; + + static liquidityPoolDepositLineFull(): LiquidityPoolDepositResult; + + static liquidityPoolDepositBadPrice(): LiquidityPoolDepositResult; + + static liquidityPoolDepositPoolFull(): LiquidityPoolDepositResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolDepositResult; + + static write(value: LiquidityPoolDepositResult, io: Buffer): void; + + static isValid(value: LiquidityPoolDepositResult): boolean; + + static toXDR(value: LiquidityPoolDepositResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LiquidityPoolDepositResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolDepositResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolWithdrawResult { + switch(): LiquidityPoolWithdrawResultCode; + + static liquidityPoolWithdrawSuccess(): LiquidityPoolWithdrawResult; + + static liquidityPoolWithdrawMalformed(): LiquidityPoolWithdrawResult; + + static liquidityPoolWithdrawNoTrust(): LiquidityPoolWithdrawResult; + + static liquidityPoolWithdrawUnderfunded(): LiquidityPoolWithdrawResult; + + static liquidityPoolWithdrawLineFull(): LiquidityPoolWithdrawResult; + + static liquidityPoolWithdrawUnderMinimum(): LiquidityPoolWithdrawResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolWithdrawResult; + + static write(value: LiquidityPoolWithdrawResult, io: Buffer): void; + + static isValid(value: LiquidityPoolWithdrawResult): boolean; + + static toXDR(value: LiquidityPoolWithdrawResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LiquidityPoolWithdrawResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolWithdrawResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InvokeHostFunctionResult { + switch(): InvokeHostFunctionResultCode; + + success(value?: Buffer): Buffer; + + static invokeHostFunctionSuccess(value: Buffer): InvokeHostFunctionResult; + + static invokeHostFunctionMalformed(): InvokeHostFunctionResult; + + static invokeHostFunctionTrapped(): InvokeHostFunctionResult; + + static invokeHostFunctionResourceLimitExceeded(): InvokeHostFunctionResult; + + static invokeHostFunctionEntryArchived(): InvokeHostFunctionResult; + + static invokeHostFunctionInsufficientRefundableFee(): InvokeHostFunctionResult; + + value(): Buffer | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InvokeHostFunctionResult; + + static write(value: InvokeHostFunctionResult, io: Buffer): void; + + static isValid(value: InvokeHostFunctionResult): boolean; + + static toXDR(value: InvokeHostFunctionResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InvokeHostFunctionResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): InvokeHostFunctionResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ExtendFootprintTtlResult { + switch(): ExtendFootprintTtlResultCode; + + static extendFootprintTtlSuccess(): ExtendFootprintTtlResult; + + static extendFootprintTtlMalformed(): ExtendFootprintTtlResult; + + static extendFootprintTtlResourceLimitExceeded(): ExtendFootprintTtlResult; + + static extendFootprintTtlInsufficientRefundableFee(): ExtendFootprintTtlResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ExtendFootprintTtlResult; + + static write(value: ExtendFootprintTtlResult, io: Buffer): void; + + static isValid(value: ExtendFootprintTtlResult): boolean; + + static toXDR(value: ExtendFootprintTtlResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ExtendFootprintTtlResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ExtendFootprintTtlResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class RestoreFootprintResult { + switch(): RestoreFootprintResultCode; + + static restoreFootprintSuccess(): RestoreFootprintResult; + + static restoreFootprintMalformed(): RestoreFootprintResult; + + static restoreFootprintResourceLimitExceeded(): RestoreFootprintResult; + + static restoreFootprintInsufficientRefundableFee(): RestoreFootprintResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): RestoreFootprintResult; + + static write(value: RestoreFootprintResult, io: Buffer): void; + + static isValid(value: RestoreFootprintResult): boolean; + + static toXDR(value: RestoreFootprintResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): RestoreFootprintResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): RestoreFootprintResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class OperationResultTr { + switch(): OperationType; + + createAccountResult(value?: CreateAccountResult): CreateAccountResult; + + paymentResult(value?: PaymentResult): PaymentResult; + + pathPaymentStrictReceiveResult( + value?: PathPaymentStrictReceiveResult, + ): PathPaymentStrictReceiveResult; + + manageSellOfferResult(value?: ManageSellOfferResult): ManageSellOfferResult; + + createPassiveSellOfferResult( + value?: ManageSellOfferResult, + ): ManageSellOfferResult; + + setOptionsResult(value?: SetOptionsResult): SetOptionsResult; + + changeTrustResult(value?: ChangeTrustResult): ChangeTrustResult; + + allowTrustResult(value?: AllowTrustResult): AllowTrustResult; + + accountMergeResult(value?: AccountMergeResult): AccountMergeResult; + + inflationResult(value?: InflationResult): InflationResult; + + manageDataResult(value?: ManageDataResult): ManageDataResult; + + bumpSeqResult(value?: BumpSequenceResult): BumpSequenceResult; + + manageBuyOfferResult(value?: ManageBuyOfferResult): ManageBuyOfferResult; + + pathPaymentStrictSendResult( + value?: PathPaymentStrictSendResult, + ): PathPaymentStrictSendResult; + + createClaimableBalanceResult( + value?: CreateClaimableBalanceResult, + ): CreateClaimableBalanceResult; + + claimClaimableBalanceResult( + value?: ClaimClaimableBalanceResult, + ): ClaimClaimableBalanceResult; + + beginSponsoringFutureReservesResult( + value?: BeginSponsoringFutureReservesResult, + ): BeginSponsoringFutureReservesResult; + + endSponsoringFutureReservesResult( + value?: EndSponsoringFutureReservesResult, + ): EndSponsoringFutureReservesResult; + + revokeSponsorshipResult( + value?: RevokeSponsorshipResult, + ): RevokeSponsorshipResult; + + clawbackResult(value?: ClawbackResult): ClawbackResult; + + clawbackClaimableBalanceResult( + value?: ClawbackClaimableBalanceResult, + ): ClawbackClaimableBalanceResult; + + setTrustLineFlagsResult( + value?: SetTrustLineFlagsResult, + ): SetTrustLineFlagsResult; + + liquidityPoolDepositResult( + value?: LiquidityPoolDepositResult, + ): LiquidityPoolDepositResult; + + liquidityPoolWithdrawResult( + value?: LiquidityPoolWithdrawResult, + ): LiquidityPoolWithdrawResult; + + invokeHostFunctionResult( + value?: InvokeHostFunctionResult, + ): InvokeHostFunctionResult; + + extendFootprintTtlResult( + value?: ExtendFootprintTtlResult, + ): ExtendFootprintTtlResult; + + restoreFootprintResult( + value?: RestoreFootprintResult, + ): RestoreFootprintResult; + + static createAccount(value: CreateAccountResult): OperationResultTr; + + static payment(value: PaymentResult): OperationResultTr; + + static pathPaymentStrictReceive( + value: PathPaymentStrictReceiveResult, + ): OperationResultTr; + + static manageSellOffer(value: ManageSellOfferResult): OperationResultTr; + + static createPassiveSellOffer( + value: ManageSellOfferResult, + ): OperationResultTr; + + static setOptions(value: SetOptionsResult): OperationResultTr; + + static changeTrust(value: ChangeTrustResult): OperationResultTr; + + static allowTrust(value: AllowTrustResult): OperationResultTr; + + static accountMerge(value: AccountMergeResult): OperationResultTr; + + static inflation(value: InflationResult): OperationResultTr; + + static manageData(value: ManageDataResult): OperationResultTr; + + static bumpSequence(value: BumpSequenceResult): OperationResultTr; + + static manageBuyOffer(value: ManageBuyOfferResult): OperationResultTr; + + static pathPaymentStrictSend( + value: PathPaymentStrictSendResult, + ): OperationResultTr; + + static createClaimableBalance( + value: CreateClaimableBalanceResult, + ): OperationResultTr; + + static claimClaimableBalance( + value: ClaimClaimableBalanceResult, + ): OperationResultTr; + + static beginSponsoringFutureReserves( + value: BeginSponsoringFutureReservesResult, + ): OperationResultTr; + + static endSponsoringFutureReserves( + value: EndSponsoringFutureReservesResult, + ): OperationResultTr; + + static revokeSponsorship(value: RevokeSponsorshipResult): OperationResultTr; + + static clawback(value: ClawbackResult): OperationResultTr; + + static clawbackClaimableBalance( + value: ClawbackClaimableBalanceResult, + ): OperationResultTr; + + static setTrustLineFlags(value: SetTrustLineFlagsResult): OperationResultTr; + + static liquidityPoolDeposit( + value: LiquidityPoolDepositResult, + ): OperationResultTr; + + static liquidityPoolWithdraw( + value: LiquidityPoolWithdrawResult, + ): OperationResultTr; + + static invokeHostFunction( + value: InvokeHostFunctionResult, + ): OperationResultTr; + + static extendFootprintTtl( + value: ExtendFootprintTtlResult, + ): OperationResultTr; + + static restoreFootprint(value: RestoreFootprintResult): OperationResultTr; + + value(): + | CreateAccountResult + | PaymentResult + | PathPaymentStrictReceiveResult + | ManageSellOfferResult + | ManageSellOfferResult + | SetOptionsResult + | ChangeTrustResult + | AllowTrustResult + | AccountMergeResult + | InflationResult + | ManageDataResult + | BumpSequenceResult + | ManageBuyOfferResult + | PathPaymentStrictSendResult + | CreateClaimableBalanceResult + | ClaimClaimableBalanceResult + | BeginSponsoringFutureReservesResult + | EndSponsoringFutureReservesResult + | RevokeSponsorshipResult + | ClawbackResult + | ClawbackClaimableBalanceResult + | SetTrustLineFlagsResult + | LiquidityPoolDepositResult + | LiquidityPoolWithdrawResult + | InvokeHostFunctionResult + | ExtendFootprintTtlResult + | RestoreFootprintResult; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): OperationResultTr; + + static write(value: OperationResultTr, io: Buffer): void; + + static isValid(value: OperationResultTr): boolean; + + static toXDR(value: OperationResultTr): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): OperationResultTr; + + static fromXDR(input: string, format: 'hex' | 'base64'): OperationResultTr; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class OperationResult { + switch(): OperationResultCode; + + tr(value?: OperationResultTr): OperationResultTr; + + static opInner(value: OperationResultTr): OperationResult; + + static opBadAuth(): OperationResult; + + static opNoAccount(): OperationResult; + + static opNotSupported(): OperationResult; + + static opTooManySubentries(): OperationResult; + + static opExceededWorkLimit(): OperationResult; + + static opTooManySponsoring(): OperationResult; + + value(): OperationResultTr | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): OperationResult; + + static write(value: OperationResult, io: Buffer): void; + + static isValid(value: OperationResult): boolean; + + static toXDR(value: OperationResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): OperationResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): OperationResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InnerTransactionResultResult { + switch(): TransactionResultCode; + + results(value?: OperationResult[]): OperationResult[]; + + static txSuccess(value: OperationResult[]): InnerTransactionResultResult; + + static txFailed(value: OperationResult[]): InnerTransactionResultResult; + + static txTooEarly(): InnerTransactionResultResult; + + static txTooLate(): InnerTransactionResultResult; + + static txMissingOperation(): InnerTransactionResultResult; + + static txBadSeq(): InnerTransactionResultResult; + + static txBadAuth(): InnerTransactionResultResult; + + static txInsufficientBalance(): InnerTransactionResultResult; + + static txNoAccount(): InnerTransactionResultResult; + + static txInsufficientFee(): InnerTransactionResultResult; + + static txBadAuthExtra(): InnerTransactionResultResult; + + static txInternalError(): InnerTransactionResultResult; + + static txNotSupported(): InnerTransactionResultResult; + + static txBadSponsorship(): InnerTransactionResultResult; + + static txBadMinSeqAgeOrGap(): InnerTransactionResultResult; + + static txMalformed(): InnerTransactionResultResult; + + static txSorobanInvalid(): InnerTransactionResultResult; + + value(): OperationResult[] | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InnerTransactionResultResult; + + static write(value: InnerTransactionResultResult, io: Buffer): void; + + static isValid(value: InnerTransactionResultResult): boolean; + + static toXDR(value: InnerTransactionResultResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InnerTransactionResultResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): InnerTransactionResultResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InnerTransactionResultExt { + switch(): number; + + static 0(): InnerTransactionResultExt; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InnerTransactionResultExt; + + static write(value: InnerTransactionResultExt, io: Buffer): void; + + static isValid(value: InnerTransactionResultExt): boolean; + + static toXDR(value: InnerTransactionResultExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InnerTransactionResultExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): InnerTransactionResultExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionResultResult { + switch(): TransactionResultCode; + + innerResultPair( + value?: InnerTransactionResultPair, + ): InnerTransactionResultPair; + + results(value?: OperationResult[]): OperationResult[]; + + static txFeeBumpInnerSuccess( + value: InnerTransactionResultPair, + ): TransactionResultResult; + + static txFeeBumpInnerFailed( + value: InnerTransactionResultPair, + ): TransactionResultResult; + + static txSuccess(value: OperationResult[]): TransactionResultResult; + + static txFailed(value: OperationResult[]): TransactionResultResult; + + static txTooEarly(): TransactionResultResult; + + static txTooLate(): TransactionResultResult; + + static txMissingOperation(): TransactionResultResult; + + static txBadSeq(): TransactionResultResult; + + static txBadAuth(): TransactionResultResult; + + static txInsufficientBalance(): TransactionResultResult; + + static txNoAccount(): TransactionResultResult; + + static txInsufficientFee(): TransactionResultResult; + + static txBadAuthExtra(): TransactionResultResult; + + static txInternalError(): TransactionResultResult; + + static txNotSupported(): TransactionResultResult; + + static txBadSponsorship(): TransactionResultResult; + + static txBadMinSeqAgeOrGap(): TransactionResultResult; + + static txMalformed(): TransactionResultResult; + + static txSorobanInvalid(): TransactionResultResult; + + value(): InnerTransactionResultPair | OperationResult[] | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionResultResult; + + static write(value: TransactionResultResult, io: Buffer): void; + + static isValid(value: TransactionResultResult): boolean; + + static toXDR(value: TransactionResultResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionResultResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionResultResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionResultExt { + switch(): number; + + static 0(): TransactionResultExt; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionResultExt; + + static write(value: TransactionResultExt, io: Buffer): void; + + static isValid(value: TransactionResultExt): boolean; + + static toXDR(value: TransactionResultExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionResultExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionResultExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ExtensionPoint { + switch(): number; + + static 0(): ExtensionPoint; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ExtensionPoint; + + static write(value: ExtensionPoint, io: Buffer): void; + + static isValid(value: ExtensionPoint): boolean; + + static toXDR(value: ExtensionPoint): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ExtensionPoint; + + static fromXDR(input: string, format: 'hex' | 'base64'): ExtensionPoint; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PublicKey { + switch(): PublicKeyType; + + ed25519(value?: Buffer): Buffer; + + static publicKeyTypeEd25519(value: Buffer): PublicKey; + + value(): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PublicKey; + + static write(value: PublicKey, io: Buffer): void; + + static isValid(value: PublicKey): boolean; + + static toXDR(value: PublicKey): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PublicKey; + + static fromXDR(input: string, format: 'hex' | 'base64'): PublicKey; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignerKey { + switch(): SignerKeyType; + + ed25519(value?: Buffer): Buffer; + + preAuthTx(value?: Buffer): Buffer; + + hashX(value?: Buffer): Buffer; + + ed25519SignedPayload( + value?: SignerKeyEd25519SignedPayload, + ): SignerKeyEd25519SignedPayload; + + static signerKeyTypeEd25519(value: Buffer): SignerKey; + + static signerKeyTypePreAuthTx(value: Buffer): SignerKey; + + static signerKeyTypeHashX(value: Buffer): SignerKey; + + static signerKeyTypeEd25519SignedPayload( + value: SignerKeyEd25519SignedPayload, + ): SignerKey; + + value(): Buffer | Buffer | Buffer | SignerKeyEd25519SignedPayload; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignerKey; + + static write(value: SignerKey, io: Buffer): void; + + static isValid(value: SignerKey): boolean; + + static toXDR(value: SignerKey): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SignerKey; + + static fromXDR(input: string, format: 'hex' | 'base64'): SignerKey; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScError { + switch(): ScErrorType; + + contractCode(value?: number): number; + + code(value?: ScErrorCode): ScErrorCode; + + static sceContract(value: number): ScError; + + static sceWasmVm(value: ScErrorCode): ScError; + + static sceContext(value: ScErrorCode): ScError; + + static sceStorage(value: ScErrorCode): ScError; + + static sceObject(value: ScErrorCode): ScError; + + static sceCrypto(value: ScErrorCode): ScError; + + static sceEvents(value: ScErrorCode): ScError; + + static sceBudget(value: ScErrorCode): ScError; + + static sceValue(value: ScErrorCode): ScError; + + static sceAuth(value: ScErrorCode): ScError; + + value(): number | ScErrorCode; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScError; + + static write(value: ScError, io: Buffer): void; + + static isValid(value: ScError): boolean; + + static toXDR(value: ScError): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScError; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScError; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractExecutable { + switch(): ContractExecutableType; + + wasmHash(value?: Buffer): Buffer; + + static contractExecutableWasm(value: Buffer): ContractExecutable; + + static contractExecutableStellarAsset(): ContractExecutable; + + value(): Buffer | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractExecutable; + + static write(value: ContractExecutable, io: Buffer): void; + + static isValid(value: ContractExecutable): boolean; + + static toXDR(value: ContractExecutable): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractExecutable; + + static fromXDR(input: string, format: 'hex' | 'base64'): ContractExecutable; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScAddress { + switch(): ScAddressType; + + accountId(value?: AccountId): AccountId; + + contractId(value?: Buffer): Buffer; + + static scAddressTypeAccount(value: AccountId): ScAddress; + + static scAddressTypeContract(value: Buffer): ScAddress; + + value(): AccountId | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScAddress; + + static write(value: ScAddress, io: Buffer): void; + + static isValid(value: ScAddress): boolean; + + static toXDR(value: ScAddress): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScAddress; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScAddress; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScVal { + switch(): ScValType; + + b(value?: boolean): boolean; + + error(value?: ScError): ScError; + + u32(value?: number): number; + + i32(value?: number): number; + + u64(value?: Uint64): Uint64; + + i64(value?: Int64): Int64; + + timepoint(value?: TimePoint): TimePoint; + + duration(value?: Duration): Duration; + + u128(value?: UInt128Parts): UInt128Parts; + + i128(value?: Int128Parts): Int128Parts; + + u256(value?: UInt256Parts): UInt256Parts; + + i256(value?: Int256Parts): Int256Parts; + + bytes(value?: Buffer): Buffer; + + str(value?: string | Buffer): string | Buffer; + + sym(value?: string | Buffer): string | Buffer; + + vec(value?: null | ScVal[]): null | ScVal[]; + + map(value?: null | ScMapEntry[]): null | ScMapEntry[]; + + address(value?: ScAddress): ScAddress; + + nonceKey(value?: ScNonceKey): ScNonceKey; + + instance(value?: ScContractInstance): ScContractInstance; + + static scvBool(value: boolean): ScVal; + + static scvVoid(): ScVal; + + static scvError(value: ScError): ScVal; + + static scvU32(value: number): ScVal; + + static scvI32(value: number): ScVal; + + static scvU64(value: Uint64): ScVal; + + static scvI64(value: Int64): ScVal; + + static scvTimepoint(value: TimePoint): ScVal; + + static scvDuration(value: Duration): ScVal; + + static scvU128(value: UInt128Parts): ScVal; + + static scvI128(value: Int128Parts): ScVal; + + static scvU256(value: UInt256Parts): ScVal; + + static scvI256(value: Int256Parts): ScVal; + + static scvBytes(value: Buffer): ScVal; + + static scvString(value: string | Buffer): ScVal; + + static scvSymbol(value: string | Buffer): ScVal; + + static scvVec(value: null | ScVal[]): ScVal; + + static scvMap(value: null | ScMapEntry[]): ScVal; + + static scvAddress(value: ScAddress): ScVal; + + static scvLedgerKeyContractInstance(): ScVal; + + static scvLedgerKeyNonce(value: ScNonceKey): ScVal; + + static scvContractInstance(value: ScContractInstance): ScVal; + + value(): + | boolean + | ScError + | number + | number + | Uint64 + | Int64 + | TimePoint + | Duration + | UInt128Parts + | Int128Parts + | UInt256Parts + | Int256Parts + | Buffer + | string + | Buffer + | string + | Buffer + | null + | ScVal[] + | null + | ScMapEntry[] + | ScAddress + | ScNonceKey + | ScContractInstance + | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScVal; + + static write(value: ScVal, io: Buffer): void; + + static isValid(value: ScVal): boolean; + + static toXDR(value: ScVal): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScVal; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScVal; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScEnvMetaEntry { + switch(): ScEnvMetaKind; + + interfaceVersion( + value?: ScEnvMetaEntryInterfaceVersion, + ): ScEnvMetaEntryInterfaceVersion; + + static scEnvMetaKindInterfaceVersion( + value: ScEnvMetaEntryInterfaceVersion, + ): ScEnvMetaEntry; + + value(): ScEnvMetaEntryInterfaceVersion; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScEnvMetaEntry; + + static write(value: ScEnvMetaEntry, io: Buffer): void; + + static isValid(value: ScEnvMetaEntry): boolean; + + static toXDR(value: ScEnvMetaEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScEnvMetaEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScEnvMetaEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScMetaEntry { + switch(): ScMetaKind; + + v0(value?: ScMetaV0): ScMetaV0; + + static scMetaV0(value: ScMetaV0): ScMetaEntry; + + value(): ScMetaV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScMetaEntry; + + static write(value: ScMetaEntry, io: Buffer): void; + + static isValid(value: ScMetaEntry): boolean; + + static toXDR(value: ScMetaEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScMetaEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScMetaEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeDef { + switch(): ScSpecType; + + option(value?: ScSpecTypeOption): ScSpecTypeOption; + + result(value?: ScSpecTypeResult): ScSpecTypeResult; + + vec(value?: ScSpecTypeVec): ScSpecTypeVec; + + map(value?: ScSpecTypeMap): ScSpecTypeMap; + + tuple(value?: ScSpecTypeTuple): ScSpecTypeTuple; + + bytesN(value?: ScSpecTypeBytesN): ScSpecTypeBytesN; + + udt(value?: ScSpecTypeUdt): ScSpecTypeUdt; + + static scSpecTypeVal(): ScSpecTypeDef; + + static scSpecTypeBool(): ScSpecTypeDef; + + static scSpecTypeVoid(): ScSpecTypeDef; + + static scSpecTypeError(): ScSpecTypeDef; + + static scSpecTypeU32(): ScSpecTypeDef; + + static scSpecTypeI32(): ScSpecTypeDef; + + static scSpecTypeU64(): ScSpecTypeDef; + + static scSpecTypeI64(): ScSpecTypeDef; + + static scSpecTypeTimepoint(): ScSpecTypeDef; + + static scSpecTypeDuration(): ScSpecTypeDef; + + static scSpecTypeU128(): ScSpecTypeDef; + + static scSpecTypeI128(): ScSpecTypeDef; + + static scSpecTypeU256(): ScSpecTypeDef; + + static scSpecTypeI256(): ScSpecTypeDef; + + static scSpecTypeBytes(): ScSpecTypeDef; + + static scSpecTypeString(): ScSpecTypeDef; + + static scSpecTypeSymbol(): ScSpecTypeDef; + + static scSpecTypeAddress(): ScSpecTypeDef; + + static scSpecTypeOption(value: ScSpecTypeOption): ScSpecTypeDef; + + static scSpecTypeResult(value: ScSpecTypeResult): ScSpecTypeDef; + + static scSpecTypeVec(value: ScSpecTypeVec): ScSpecTypeDef; + + static scSpecTypeMap(value: ScSpecTypeMap): ScSpecTypeDef; + + static scSpecTypeTuple(value: ScSpecTypeTuple): ScSpecTypeDef; + + static scSpecTypeBytesN(value: ScSpecTypeBytesN): ScSpecTypeDef; + + static scSpecTypeUdt(value: ScSpecTypeUdt): ScSpecTypeDef; + + value(): + | ScSpecTypeOption + | ScSpecTypeResult + | ScSpecTypeVec + | ScSpecTypeMap + | ScSpecTypeTuple + | ScSpecTypeBytesN + | ScSpecTypeUdt + | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeDef; + + static write(value: ScSpecTypeDef, io: Buffer): void; + + static isValid(value: ScSpecTypeDef): boolean; + + static toXDR(value: ScSpecTypeDef): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeDef; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeDef; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtUnionCaseV0 { + switch(): ScSpecUdtUnionCaseV0Kind; + + voidCase(value?: ScSpecUdtUnionCaseVoidV0): ScSpecUdtUnionCaseVoidV0; + + tupleCase(value?: ScSpecUdtUnionCaseTupleV0): ScSpecUdtUnionCaseTupleV0; + + static scSpecUdtUnionCaseVoidV0( + value: ScSpecUdtUnionCaseVoidV0, + ): ScSpecUdtUnionCaseV0; + + static scSpecUdtUnionCaseTupleV0( + value: ScSpecUdtUnionCaseTupleV0, + ): ScSpecUdtUnionCaseV0; + + value(): ScSpecUdtUnionCaseVoidV0 | ScSpecUdtUnionCaseTupleV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtUnionCaseV0; + + static write(value: ScSpecUdtUnionCaseV0, io: Buffer): void; + + static isValid(value: ScSpecUdtUnionCaseV0): boolean; + + static toXDR(value: ScSpecUdtUnionCaseV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtUnionCaseV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecUdtUnionCaseV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecEntry { + switch(): ScSpecEntryKind; + + functionV0(value?: ScSpecFunctionV0): ScSpecFunctionV0; + + udtStructV0(value?: ScSpecUdtStructV0): ScSpecUdtStructV0; + + udtUnionV0(value?: ScSpecUdtUnionV0): ScSpecUdtUnionV0; + + udtEnumV0(value?: ScSpecUdtEnumV0): ScSpecUdtEnumV0; + + udtErrorEnumV0(value?: ScSpecUdtErrorEnumV0): ScSpecUdtErrorEnumV0; + + static scSpecEntryFunctionV0(value: ScSpecFunctionV0): ScSpecEntry; + + static scSpecEntryUdtStructV0(value: ScSpecUdtStructV0): ScSpecEntry; + + static scSpecEntryUdtUnionV0(value: ScSpecUdtUnionV0): ScSpecEntry; + + static scSpecEntryUdtEnumV0(value: ScSpecUdtEnumV0): ScSpecEntry; + + static scSpecEntryUdtErrorEnumV0(value: ScSpecUdtErrorEnumV0): ScSpecEntry; + + value(): + | ScSpecFunctionV0 + | ScSpecUdtStructV0 + | ScSpecUdtUnionV0 + | ScSpecUdtEnumV0 + | ScSpecUdtErrorEnumV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecEntry; + + static write(value: ScSpecEntry, io: Buffer): void; + + static isValid(value: ScSpecEntry): boolean; + + static toXDR(value: ScSpecEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingEntry { + switch(): ConfigSettingId; + + contractMaxSizeBytes(value?: number): number; + + contractCompute( + value?: ConfigSettingContractComputeV0, + ): ConfigSettingContractComputeV0; + + contractLedgerCost( + value?: ConfigSettingContractLedgerCostV0, + ): ConfigSettingContractLedgerCostV0; + + contractHistoricalData( + value?: ConfigSettingContractHistoricalDataV0, + ): ConfigSettingContractHistoricalDataV0; + + contractEvents( + value?: ConfigSettingContractEventsV0, + ): ConfigSettingContractEventsV0; + + contractBandwidth( + value?: ConfigSettingContractBandwidthV0, + ): ConfigSettingContractBandwidthV0; + + contractCostParamsCpuInsns( + value?: ContractCostParamEntry[], + ): ContractCostParamEntry[]; + + contractCostParamsMemBytes( + value?: ContractCostParamEntry[], + ): ContractCostParamEntry[]; + + contractDataKeySizeBytes(value?: number): number; + + contractDataEntrySizeBytes(value?: number): number; + + stateArchivalSettings(value?: StateArchivalSettings): StateArchivalSettings; + + contractExecutionLanes( + value?: ConfigSettingContractExecutionLanesV0, + ): ConfigSettingContractExecutionLanesV0; + + bucketListSizeWindow(value?: Uint64[]): Uint64[]; + + evictionIterator(value?: EvictionIterator): EvictionIterator; + + static configSettingContractMaxSizeBytes(value: number): ConfigSettingEntry; + + static configSettingContractComputeV0( + value: ConfigSettingContractComputeV0, + ): ConfigSettingEntry; + + static configSettingContractLedgerCostV0( + value: ConfigSettingContractLedgerCostV0, + ): ConfigSettingEntry; + + static configSettingContractHistoricalDataV0( + value: ConfigSettingContractHistoricalDataV0, + ): ConfigSettingEntry; + + static configSettingContractEventsV0( + value: ConfigSettingContractEventsV0, + ): ConfigSettingEntry; + + static configSettingContractBandwidthV0( + value: ConfigSettingContractBandwidthV0, + ): ConfigSettingEntry; + + static configSettingContractCostParamsCpuInstructions( + value: ContractCostParamEntry[], + ): ConfigSettingEntry; + + static configSettingContractCostParamsMemoryBytes( + value: ContractCostParamEntry[], + ): ConfigSettingEntry; + + static configSettingContractDataKeySizeBytes( + value: number, + ): ConfigSettingEntry; + + static configSettingContractDataEntrySizeBytes( + value: number, + ): ConfigSettingEntry; + + static configSettingStateArchival( + value: StateArchivalSettings, + ): ConfigSettingEntry; + + static configSettingContractExecutionLanes( + value: ConfigSettingContractExecutionLanesV0, + ): ConfigSettingEntry; + + static configSettingBucketlistSizeWindow( + value: Uint64[], + ): ConfigSettingEntry; + + static configSettingEvictionIterator( + value: EvictionIterator, + ): ConfigSettingEntry; + + value(): + | number + | ConfigSettingContractComputeV0 + | ConfigSettingContractLedgerCostV0 + | ConfigSettingContractHistoricalDataV0 + | ConfigSettingContractEventsV0 + | ConfigSettingContractBandwidthV0 + | ContractCostParamEntry[] + | ContractCostParamEntry[] + | number + | number + | StateArchivalSettings + | ConfigSettingContractExecutionLanesV0 + | Uint64[] + | EvictionIterator; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingEntry; + + static write(value: ConfigSettingEntry, io: Buffer): void; + + static isValid(value: ConfigSettingEntry): boolean; + + static toXDR(value: ConfigSettingEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ConfigSettingEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ConfigSettingEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } +} diff --git a/node_modules/@stellar/stellar-base/types/index.d.ts b/node_modules/@stellar/stellar-base/types/index.d.ts new file mode 100644 index 000000000..f53afb4d0 --- /dev/null +++ b/node_modules/@stellar/stellar-base/types/index.d.ts @@ -0,0 +1,1315 @@ +// TypeScript Version: 2.9 + +/// +import { xdr } from './xdr'; + +export { xdr }; + +export class Account { + constructor(accountId: string, sequence: string); + accountId(): string; + sequenceNumber(): string; + incrementSequenceNumber(): void; +} + +export class Address { + constructor(address: string); + static fromString(address: string): Address; + static account(buffer: Buffer): Address; + static contract(buffer: Buffer): Address; + static fromScVal(scVal: xdr.ScVal): Address; + static fromScAddress(scAddress: xdr.ScAddress): Address; + toString(): string; + toScVal(): xdr.ScVal; + toScAddress(): xdr.ScAddress; + toBuffer(): Buffer; +} + +export class Contract { + constructor(contractId: string); + call(method: string, ...params: xdr.ScVal[]): xdr.Operation; + contractId(): string; + address(): Address; + getFootprint(): xdr.LedgerKey; + + toString(): string; +} + +export class MuxedAccount { + constructor(account: Account, sequence: string); + static fromAddress(mAddress: string, sequenceNum: string): MuxedAccount; + static parseBaseAddress(mAddress: string): string; + + /* Modeled after Account, above */ + accountId(): string; + sequenceNumber(): string; + incrementSequenceNumber(): void; + + baseAccount(): Account; + id(): string; + setId(id: string): MuxedAccount; + toXDRObject(): xdr.MuxedAccount; + equals(otherMuxedAccount: MuxedAccount): boolean; +} + +export namespace AssetType { + type native = 'native'; + type credit4 = 'credit_alphanum4'; + type credit12 = 'credit_alphanum12'; + type liquidityPoolShares = 'liquidity_pool_shares'; +} +export type AssetType = + | AssetType.native + | AssetType.credit4 + | AssetType.credit12 + | AssetType.liquidityPoolShares; + +export class Asset { + static native(): Asset; + static fromOperation(xdr: xdr.Asset): Asset; + static compare(assetA: Asset, assetB: Asset): -1 | 0 | 1; + + constructor(code: string, issuer?: string); + + getCode(): string; + getIssuer(): string; + getAssetType(): AssetType; + isNative(): boolean; + equals(other: Asset): boolean; + toXDRObject(): xdr.Asset; + toChangeTrustXDRObject(): xdr.ChangeTrustAsset; + toTrustLineXDRObject(): xdr.TrustLineAsset; + contractId(networkPassphrase: string): string; + + code: string; + issuer: string; +} + +export class LiquidityPoolAsset { + constructor(assetA: Asset, assetB: Asset, fee: number); + + static fromOperation(xdr: xdr.ChangeTrustAsset): LiquidityPoolAsset; + + toXDRObject(): xdr.ChangeTrustAsset; + getLiquidityPoolParameters(): LiquidityPoolParameters; + getAssetType(): AssetType.liquidityPoolShares; + equals(other: LiquidityPoolAsset): boolean; + + assetA: Asset; + assetB: Asset; + fee: number; +} + +export class LiquidityPoolId { + constructor(liquidityPoolId: string); + + static fromOperation(xdr: xdr.TrustLineAsset): LiquidityPoolId; + + toXDRObject(): xdr.TrustLineAsset; + getLiquidityPoolId(): string; + equals(other: LiquidityPoolId): boolean; + + liquidityPoolId: string; +} + +export class Claimant { + readonly destination: string; + readonly predicate: xdr.ClaimPredicate; + constructor(destination: string, predicate?: xdr.ClaimPredicate); + + toXDRObject(): xdr.Claimant; + + static fromXDR(claimantXdr: xdr.Claimant): Claimant; + static predicateUnconditional(): xdr.ClaimPredicate; + static predicateAnd(left: xdr.ClaimPredicate, right: xdr.ClaimPredicate): xdr.ClaimPredicate; + static predicateOr(left: xdr.ClaimPredicate, right: xdr.ClaimPredicate): xdr.ClaimPredicate; + static predicateNot(predicate: xdr.ClaimPredicate): xdr.ClaimPredicate; + static predicateBeforeAbsoluteTime(absBefore: string): xdr.ClaimPredicate; + static predicateBeforeRelativeTime(seconds: string): xdr.ClaimPredicate; +} + +export const FastSigning: boolean; + +export type KeypairType = 'ed25519'; + +export class Keypair { + static fromRawEd25519Seed(secretSeed: Buffer): Keypair; + static fromSecret(secretKey: string): Keypair; + static master(networkPassphrase: string): Keypair; + static fromPublicKey(publicKey: string): Keypair; + static random(): Keypair; + + constructor( + keys: + | { + type: KeypairType; + secretKey: string | Buffer; + publicKey?: string | Buffer + } + | { + type: KeypairType; + publicKey: string | Buffer + } + ); + + readonly type: KeypairType; + publicKey(): string; + secret(): string; + rawPublicKey(): Buffer; + rawSecretKey(): Buffer; + canSign(): boolean; + sign(data: Buffer): Buffer; + signDecorated(data: Buffer): xdr.DecoratedSignature; + signPayloadDecorated(data: Buffer): xdr.DecoratedSignature; + signatureHint(): Buffer; + verify(data: Buffer, signature: Buffer): boolean; + + xdrAccountId(): xdr.AccountId; + xdrPublicKey(): xdr.PublicKey; + xdrMuxedAccount(id: string): xdr.MuxedAccount; +} + +export const LiquidityPoolFeeV18 = 30; + +export function getLiquidityPoolId(liquidityPoolType: LiquidityPoolType, liquidityPoolParameters: LiquidityPoolParameters): Buffer; + +export namespace LiquidityPoolParameters { + interface ConstantProduct { + assetA: Asset; + assetB: Asset; + fee: number; + } +} +export type LiquidityPoolParameters = + | LiquidityPoolParameters.ConstantProduct; + +export namespace LiquidityPoolType { + type constantProduct = 'constant_product'; +} +export type LiquidityPoolType = + | LiquidityPoolType.constantProduct; + +export const MemoNone = 'none'; +export const MemoID = 'id'; +export const MemoText = 'text'; +export const MemoHash = 'hash'; +export const MemoReturn = 'return'; +export namespace MemoType { + type None = typeof MemoNone; + type ID = typeof MemoID; + type Text = typeof MemoText; + type Hash = typeof MemoHash; + type Return = typeof MemoReturn; +} +export type MemoType = + | MemoType.None + | MemoType.ID + | MemoType.Text + | MemoType.Hash + | MemoType.Return; +export type MemoValue = null | string | Buffer; + +export class Memo { + static fromXDRObject(memo: xdr.Memo): Memo; + static hash(hash: string | Buffer): Memo; + static id(id: string): Memo; + static none(): Memo; + static return(hash: string): Memo; + static text(text: string): Memo; + + constructor(type: MemoType.None, value?: null); + constructor(type: MemoType.Hash | MemoType.Return, value: Buffer); + constructor( + type: MemoType.Hash | MemoType.Return | MemoType.ID | MemoType.Text, + value: string + ); + constructor(type: T, value: MemoValue); + + type: T; + value: T extends MemoType.None + ? null + : T extends MemoType.ID + ? string + : T extends MemoType.Text + ? string | Buffer // github.com/stellar/js-stellar-base/issues/152 + : T extends MemoType.Hash + ? Buffer + : T extends MemoType.Return + ? Buffer + : MemoValue; + + toXDRObject(): xdr.Memo; +} + +export enum Networks { + PUBLIC = 'Public Global Stellar Network ; September 2015', + TESTNET = 'Test SDF Network ; September 2015', + FUTURENET = 'Test SDF Future Network ; October 2022', + SANDBOX = 'Local Sandbox Stellar Network ; September 2022', + STANDALONE = 'Standalone Network ; February 2017' +} + +export const AuthRequiredFlag: 1; +export const AuthRevocableFlag: 2; +export const AuthImmutableFlag: 4; +export const AuthClawbackEnabledFlag: 8; +export namespace AuthFlag { + type immutable = typeof AuthImmutableFlag; + type required = typeof AuthRequiredFlag; + type revocable = typeof AuthRevocableFlag; + type clawbackEnabled = typeof AuthClawbackEnabledFlag; +} +export type AuthFlag = + | AuthFlag.required + | AuthFlag.immutable + | AuthFlag.revocable + | AuthFlag.clawbackEnabled; + +export namespace TrustLineFlag { + type deauthorize = 0; + type authorize = 1; + type authorizeToMaintainLiabilities = 2; +} +export type TrustLineFlag = + | TrustLineFlag.deauthorize + | TrustLineFlag.authorize + | TrustLineFlag.authorizeToMaintainLiabilities; + +export namespace Signer { + interface Ed25519PublicKey { + ed25519PublicKey: string; + weight: number | undefined; + } + interface Sha256Hash { + sha256Hash: Buffer; + weight: number | undefined; + } + interface PreAuthTx { + preAuthTx: Buffer; + weight: number | undefined; + } + interface Ed25519SignedPayload { + ed25519SignedPayload: string; + weight?: number | string; + } +} +export namespace SignerKeyOptions { + interface Ed25519PublicKey { + ed25519PublicKey: string; + } + interface Sha256Hash { + sha256Hash: Buffer | string; + } + interface PreAuthTx { + preAuthTx: Buffer | string; + } + interface Ed25519SignedPayload { + ed25519SignedPayload: string; + } +} +export type Signer = + | Signer.Ed25519PublicKey + | Signer.Sha256Hash + | Signer.PreAuthTx + | Signer.Ed25519SignedPayload; + +export type SignerKeyOptions = + | SignerKeyOptions.Ed25519PublicKey + | SignerKeyOptions.Sha256Hash + | SignerKeyOptions.PreAuthTx + | SignerKeyOptions.Ed25519SignedPayload; + +export namespace SignerOptions { + interface Ed25519PublicKey { + ed25519PublicKey: string; + weight?: number | string; + } + interface Sha256Hash { + sha256Hash: Buffer | string; + weight?: number | string; + } + interface PreAuthTx { + preAuthTx: Buffer | string; + weight?: number | string; + } + interface Ed25519SignedPayload { + ed25519SignedPayload: string; + weight?: number | string; + } +} +export type SignerOptions = + | SignerOptions.Ed25519PublicKey + | SignerOptions.Sha256Hash + | SignerOptions.PreAuthTx + | SignerOptions.Ed25519SignedPayload; + +export namespace OperationType { + type CreateAccount = 'createAccount'; + type Payment = 'payment'; + type PathPaymentStrictReceive = 'pathPaymentStrictReceive'; + type PathPaymentStrictSend = 'pathPaymentStrictSend'; + type CreatePassiveSellOffer = 'createPassiveSellOffer'; + type ManageSellOffer = 'manageSellOffer'; + type ManageBuyOffer = 'manageBuyOffer'; + type SetOptions = 'setOptions'; + type ChangeTrust = 'changeTrust'; + type AllowTrust = 'allowTrust'; + type AccountMerge = 'accountMerge'; + type Inflation = 'inflation'; + type ManageData = 'manageData'; + type BumpSequence = 'bumpSequence'; + type CreateClaimableBalance = 'createClaimableBalance'; + type ClaimClaimableBalance = 'claimClaimableBalance'; + type BeginSponsoringFutureReserves = 'beginSponsoringFutureReserves'; + type EndSponsoringFutureReserves = 'endSponsoringFutureReserves'; + type RevokeSponsorship = 'revokeSponsorship'; + type Clawback = 'clawback'; + type ClawbackClaimableBalance = 'clawbackClaimableBalance'; + type SetTrustLineFlags = 'setTrustLineFlags'; + type LiquidityPoolDeposit = 'liquidityPoolDeposit'; + type LiquidityPoolWithdraw = 'liquidityPoolWithdraw'; + type InvokeHostFunction = 'invokeHostFunction'; + type ExtendFootprintTTL = 'extendFootprintTtl'; + type RestoreFootprint = 'restoreFootprint'; +} +export type OperationType = + | OperationType.CreateAccount + | OperationType.Payment + | OperationType.PathPaymentStrictReceive + | OperationType.PathPaymentStrictSend + | OperationType.CreatePassiveSellOffer + | OperationType.ManageSellOffer + | OperationType.ManageBuyOffer + | OperationType.SetOptions + | OperationType.ChangeTrust + | OperationType.AllowTrust + | OperationType.AccountMerge + | OperationType.Inflation + | OperationType.ManageData + | OperationType.BumpSequence + | OperationType.CreateClaimableBalance + | OperationType.ClaimClaimableBalance + | OperationType.BeginSponsoringFutureReserves + | OperationType.EndSponsoringFutureReserves + | OperationType.RevokeSponsorship + | OperationType.Clawback + | OperationType.ClawbackClaimableBalance + | OperationType.SetTrustLineFlags + | OperationType.LiquidityPoolDeposit + | OperationType.LiquidityPoolWithdraw + | OperationType.InvokeHostFunction + | OperationType.ExtendFootprintTTL + | OperationType.RestoreFootprint; + +export namespace OperationOptions { + interface BaseOptions { + source?: string; + } + interface AccountMerge extends BaseOptions { + destination: string; + } + interface AllowTrust extends BaseOptions { + trustor: string; + assetCode: string; + authorize?: boolean | TrustLineFlag; + } + interface ChangeTrust extends BaseOptions { + asset: Asset | LiquidityPoolAsset; + limit?: string; + } + interface CreateAccount extends BaseOptions { + destination: string; + startingBalance: string; + } + interface CreatePassiveSellOffer extends BaseOptions { + selling: Asset; + buying: Asset; + amount: string; + price: number | string | object /* bignumber.js */; + } + interface ManageSellOffer extends CreatePassiveSellOffer { + offerId?: number | string; + } + interface ManageBuyOffer extends BaseOptions { + selling: Asset; + buying: Asset; + buyAmount: string; + price: number | string | object /* bignumber.js */; + offerId?: number | string; + } + // tslint:disable-next-line + interface Inflation extends BaseOptions { + // tslint:disable-line + } + interface ManageData extends BaseOptions { + name: string; + value: string | Buffer | null; + } + interface PathPaymentStrictReceive extends BaseOptions { + sendAsset: Asset; + sendMax: string; + destination: string; + destAsset: Asset; + destAmount: string; + path?: Asset[]; + } + interface PathPaymentStrictSend extends BaseOptions { + sendAsset: Asset; + sendAmount: string; + destination: string; + destAsset: Asset; + destMin: string; + path?: Asset[]; + } + interface Payment extends BaseOptions { + amount: string; + asset: Asset; + destination: string; + } + interface SetOptions extends BaseOptions { + inflationDest?: string; + clearFlags?: AuthFlag; + setFlags?: AuthFlag; + masterWeight?: number | string; + lowThreshold?: number | string; + medThreshold?: number | string; + highThreshold?: number | string; + homeDomain?: string; + signer?: T; + } + interface BumpSequence extends BaseOptions { + bumpTo: string; + } + interface CreateClaimableBalance extends BaseOptions { + asset: Asset; + amount: string; + claimants: Claimant[]; + } + interface ClaimClaimableBalance extends BaseOptions { + balanceId: string; + } + interface BeginSponsoringFutureReserves extends BaseOptions { + sponsoredId: string; + } + interface RevokeAccountSponsorship extends BaseOptions { + account: string; + } + interface RevokeTrustlineSponsorship extends BaseOptions { + account: string; + asset: Asset | LiquidityPoolId; + } + interface RevokeOfferSponsorship extends BaseOptions { + seller: string; + offerId: string; + } + interface RevokeDataSponsorship extends BaseOptions { + account: string; + name: string; + } + interface RevokeClaimableBalanceSponsorship extends BaseOptions { + balanceId: string; + } + interface RevokeLiquidityPoolSponsorship extends BaseOptions { + liquidityPoolId: string; + } + interface RevokeSignerSponsorship extends BaseOptions { + account: string; + signer: SignerKeyOptions; + } + interface Clawback extends BaseOptions { + asset: Asset; + amount: string; + from: string; + } + interface ClawbackClaimableBalance extends BaseOptions { + balanceId: string; + } + interface SetTrustLineFlags extends BaseOptions { + trustor: string; + asset: Asset; + flags: { + authorized?: boolean; + authorizedToMaintainLiabilities?: boolean; + clawbackEnabled?: boolean; + }; + } + interface LiquidityPoolDeposit extends BaseOptions { + liquidityPoolId: string; + maxAmountA: string; + maxAmountB: string; + minPrice: number | string | object /* bignumber.js */; + maxPrice: number | string | object /* bignumber.js */; + } + interface LiquidityPoolWithdraw extends BaseOptions { + liquidityPoolId: string; + amount: string; + minAmountA: string; + minAmountB: string; + } + + interface BaseInvocationOptions extends BaseOptions { + auth?: xdr.SorobanAuthorizationEntry[]; + } + interface InvokeHostFunction extends BaseInvocationOptions { + func: xdr.HostFunction; + } + interface InvokeContractFunction extends BaseInvocationOptions { + contract: string; + function: string; + args: xdr.ScVal[]; + } + interface CreateCustomContract extends BaseInvocationOptions { + address: Address; + wasmHash: Buffer | Uint8Array; + constructorArgs?: xdr.ScVal[]; + salt?: Buffer | Uint8Array; + } + interface CreateStellarAssetContract extends BaseOptions { + asset: Asset | string; + } + interface UploadContractWasm extends BaseOptions { + wasm: Buffer | Uint8Array; + } + + interface ExtendFootprintTTL extends BaseOptions { + extendTo: number; + } + type RestoreFootprint = BaseOptions; +} +export type OperationOptions = + | OperationOptions.CreateAccount + | OperationOptions.Payment + | OperationOptions.PathPaymentStrictReceive + | OperationOptions.PathPaymentStrictSend + | OperationOptions.CreatePassiveSellOffer + | OperationOptions.ManageSellOffer + | OperationOptions.ManageBuyOffer + | OperationOptions.SetOptions + | OperationOptions.ChangeTrust + | OperationOptions.AllowTrust + | OperationOptions.AccountMerge + | OperationOptions.Inflation + | OperationOptions.ManageData + | OperationOptions.BumpSequence + | OperationOptions.CreateClaimableBalance + | OperationOptions.ClaimClaimableBalance + | OperationOptions.BeginSponsoringFutureReserves + | OperationOptions.RevokeAccountSponsorship + | OperationOptions.RevokeTrustlineSponsorship + | OperationOptions.RevokeOfferSponsorship + | OperationOptions.RevokeDataSponsorship + | OperationOptions.RevokeClaimableBalanceSponsorship + | OperationOptions.RevokeLiquidityPoolSponsorship + | OperationOptions.RevokeSignerSponsorship + | OperationOptions.Clawback + | OperationOptions.ClawbackClaimableBalance + | OperationOptions.SetTrustLineFlags + | OperationOptions.LiquidityPoolDeposit + | OperationOptions.LiquidityPoolWithdraw + | OperationOptions.InvokeHostFunction + | OperationOptions.ExtendFootprintTTL + | OperationOptions.RestoreFootprint + | OperationOptions.CreateCustomContract + | OperationOptions.CreateStellarAssetContract + | OperationOptions.InvokeContractFunction + | OperationOptions.UploadContractWasm; + +export namespace Operation { + interface BaseOperation { + type: T; + source?: string; + } + + interface AccountMerge extends BaseOperation { + destination: string; + } + function accountMerge( + options: OperationOptions.AccountMerge + ): xdr.Operation; + + interface AllowTrust extends BaseOperation { + trustor: string; + assetCode: string; + // this is a boolean or a number so that it can support protocol 12 or 13 + authorize: boolean | TrustLineFlag | undefined; + } + function allowTrust( + options: OperationOptions.AllowTrust + ): xdr.Operation; + + interface ChangeTrust extends BaseOperation { + line: Asset | LiquidityPoolAsset; + limit: string; + } + function changeTrust( + options: OperationOptions.ChangeTrust + ): xdr.Operation; + + interface CreateAccount extends BaseOperation { + destination: string; + startingBalance: string; + } + function createAccount( + options: OperationOptions.CreateAccount + ): xdr.Operation; + + interface CreatePassiveSellOffer + extends BaseOperation { + selling: Asset; + buying: Asset; + amount: string; + price: string; + } + function createPassiveSellOffer( + options: OperationOptions.CreatePassiveSellOffer + ): xdr.Operation; + + interface Inflation extends BaseOperation {} + function inflation( + options: OperationOptions.Inflation + ): xdr.Operation; + + interface ManageData extends BaseOperation { + name: string; + value?: Buffer; + } + function manageData( + options: OperationOptions.ManageData + ): xdr.Operation; + + interface ManageSellOffer + extends BaseOperation { + selling: Asset; + buying: Asset; + amount: string; + price: string; + offerId: string; + } + function manageSellOffer( + options: OperationOptions.ManageSellOffer + ): xdr.Operation; + + interface ManageBuyOffer extends BaseOperation { + selling: Asset; + buying: Asset; + buyAmount: string; + price: string; + offerId: string; + } + function manageBuyOffer( + options: OperationOptions.ManageBuyOffer + ): xdr.Operation; + + interface PathPaymentStrictReceive + extends BaseOperation { + sendAsset: Asset; + sendMax: string; + destination: string; + destAsset: Asset; + destAmount: string; + path: Asset[]; + } + function pathPaymentStrictReceive( + options: OperationOptions.PathPaymentStrictReceive + ): xdr.Operation; + + interface PathPaymentStrictSend + extends BaseOperation { + sendAsset: Asset; + sendAmount: string; + destination: string; + destAsset: Asset; + destMin: string; + path: Asset[]; + } + function pathPaymentStrictSend( + options: OperationOptions.PathPaymentStrictSend + ): xdr.Operation; + + interface Payment extends BaseOperation { + amount: string; + asset: Asset; + destination: string; + } + function payment(options: OperationOptions.Payment): xdr.Operation; + + interface SetOptions + extends BaseOperation { + inflationDest?: string; + clearFlags?: AuthFlag; + setFlags?: AuthFlag; + masterWeight?: number; + lowThreshold?: number; + medThreshold?: number; + highThreshold?: number; + homeDomain?: string; + signer: T extends { ed25519PublicKey: any } + ? Signer.Ed25519PublicKey + : T extends { sha256Hash: any } + ? Signer.Sha256Hash + : T extends { preAuthTx: any } + ? Signer.PreAuthTx + : T extends { ed25519SignedPayload: any } + ? Signer.Ed25519SignedPayload + : never; + } + function setOptions( + options: OperationOptions.SetOptions + ): xdr.Operation>; + + interface BumpSequence extends BaseOperation { + bumpTo: string; + } + function bumpSequence( + options: OperationOptions.BumpSequence + ): xdr.Operation; + + interface CreateClaimableBalance extends BaseOperation { + amount: string; + asset: Asset; + claimants: Claimant[]; + } + function createClaimableBalance( + options: OperationOptions.CreateClaimableBalance + ): xdr.Operation; + + interface ClaimClaimableBalance extends BaseOperation { + balanceId: string; + } + function claimClaimableBalance( + options: OperationOptions.ClaimClaimableBalance + ): xdr.Operation; + + interface BeginSponsoringFutureReserves extends BaseOperation { + sponsoredId: string; + } + function beginSponsoringFutureReserves( + options: OperationOptions.BeginSponsoringFutureReserves + ): xdr.Operation; + + interface EndSponsoringFutureReserves extends BaseOperation { + } + function endSponsoringFutureReserves( + options: OperationOptions.BaseOptions + ): xdr.Operation; + + interface RevokeAccountSponsorship extends BaseOperation { + account: string; + } + function revokeAccountSponsorship( + options: OperationOptions.RevokeAccountSponsorship + ): xdr.Operation; + + interface RevokeTrustlineSponsorship extends BaseOperation { + account: string; + asset: Asset | LiquidityPoolId; + } + function revokeTrustlineSponsorship( + options: OperationOptions.RevokeTrustlineSponsorship + ): xdr.Operation; + + interface RevokeOfferSponsorship extends BaseOperation { + seller: string; + offerId: string; + } + function revokeOfferSponsorship( + options: OperationOptions.RevokeOfferSponsorship + ): xdr.Operation; + + interface RevokeDataSponsorship extends BaseOperation { + account: string; + name: string; + } + function revokeDataSponsorship( + options: OperationOptions.RevokeDataSponsorship + ): xdr.Operation; + + interface RevokeClaimableBalanceSponsorship extends BaseOperation { + balanceId: string; + } + function revokeClaimableBalanceSponsorship( + options: OperationOptions.RevokeClaimableBalanceSponsorship + ): xdr.Operation; + + interface RevokeLiquidityPoolSponsorship extends BaseOperation { + liquidityPoolId: string; + } + function revokeLiquidityPoolSponsorship( + options: OperationOptions.RevokeLiquidityPoolSponsorship + ): xdr.Operation; + + interface RevokeSignerSponsorship extends BaseOperation { + account: string; + signer: SignerKeyOptions; + } + function revokeSignerSponsorship( + options: OperationOptions.RevokeSignerSponsorship + ): xdr.Operation; + + interface Clawback extends BaseOperation { + asset: Asset; + amount: string; + from: string; + } + function clawback( + options: OperationOptions.Clawback + ): xdr.Operation; + + interface ClawbackClaimableBalance extends BaseOperation { + balanceId: string; + } + function clawbackClaimableBalance( + options: OperationOptions.ClawbackClaimableBalance + ): xdr.Operation; + + interface SetTrustLineFlags extends BaseOperation { + trustor: string; + asset: Asset; + flags: { + authorized?: boolean; + authorizedToMaintainLiabilities?: boolean; + clawbackEnabled?: boolean; + }; + } + function setTrustLineFlags( + options: OperationOptions.SetTrustLineFlags + ): xdr.Operation; + interface LiquidityPoolDeposit extends BaseOperation { + liquidityPoolId: string; + maxAmountA: string; + maxAmountB: string; + minPrice: string; + maxPrice: string; + } + function liquidityPoolDeposit( + options: OperationOptions.LiquidityPoolDeposit + ): xdr.Operation; + interface LiquidityPoolWithdraw extends BaseOperation { + liquidityPoolId: string; + amount: string; + minAmountA: string; + minAmountB: string; + } + function liquidityPoolWithdraw( + options: OperationOptions.LiquidityPoolWithdraw + ): xdr.Operation; + interface InvokeHostFunction extends BaseOperation { + func: xdr.HostFunction; + auth?: xdr.SorobanAuthorizationEntry[]; + } + function invokeHostFunction( + options: OperationOptions.InvokeHostFunction + ): xdr.Operation; + + function extendFootprintTtl( + options: OperationOptions.ExtendFootprintTTL + ): xdr.Operation; + interface ExtendFootprintTTL extends BaseOperation { + extendTo: number; + } + + function restoreFootprint(options: OperationOptions.RestoreFootprint): + xdr.Operation; + interface RestoreFootprint extends BaseOperation {} + + function createCustomContract( + opts: OperationOptions.CreateCustomContract + ): xdr.Operation; + function createStellarAssetContract( + opts: OperationOptions.CreateStellarAssetContract + ): xdr.Operation; + function invokeContractFunction( + opts: OperationOptions.InvokeContractFunction + ): xdr.Operation; + function uploadContractWasm( + opts: OperationOptions.UploadContractWasm + ): xdr.Operation; + + function fromXDRObject( + xdrOperation: xdr.Operation + ): T; +} +export type Operation = + | Operation.CreateAccount + | Operation.Payment + | Operation.PathPaymentStrictReceive + | Operation.PathPaymentStrictSend + | Operation.CreatePassiveSellOffer + | Operation.ManageSellOffer + | Operation.ManageBuyOffer + | Operation.SetOptions + | Operation.ChangeTrust + | Operation.AllowTrust + | Operation.AccountMerge + | Operation.Inflation + | Operation.ManageData + | Operation.BumpSequence + | Operation.CreateClaimableBalance + | Operation.ClaimClaimableBalance + | Operation.BeginSponsoringFutureReserves + | Operation.EndSponsoringFutureReserves + | Operation.RevokeAccountSponsorship + | Operation.RevokeTrustlineSponsorship + | Operation.RevokeOfferSponsorship + | Operation.RevokeDataSponsorship + | Operation.RevokeClaimableBalanceSponsorship + | Operation.RevokeLiquidityPoolSponsorship + | Operation.RevokeSignerSponsorship + | Operation.Clawback + | Operation.ClawbackClaimableBalance + | Operation.SetTrustLineFlags + | Operation.LiquidityPoolDeposit + | Operation.LiquidityPoolWithdraw + | Operation.InvokeHostFunction + | Operation.ExtendFootprintTTL + | Operation.RestoreFootprint; + +export namespace StrKey { + function encodeEd25519PublicKey(data: Buffer): string; + function decodeEd25519PublicKey(address: string): Buffer; + function isValidEd25519PublicKey(Key: string): boolean; + + function encodeEd25519SecretSeed(data: Buffer): string; + function decodeEd25519SecretSeed(address: string): Buffer; + function isValidEd25519SecretSeed(seed: string): boolean; + + function encodeMed25519PublicKey(data: Buffer): string; + function decodeMed25519PublicKey(address: string): Buffer; + function isValidMed25519PublicKey(publicKey: string): boolean; + + function encodeSignedPayload(data: Buffer): string; + function decodeSignedPayload(address: string): Buffer; + function isValidSignedPayload(address: string): boolean; + + function encodePreAuthTx(data: Buffer): string; + function decodePreAuthTx(address: string): Buffer; + + function encodeSha256Hash(data: Buffer): string; + function decodeSha256Hash(address: string): Buffer; + + function encodeContract(data: Buffer): string; + function decodeContract(address: string): Buffer; + function isValidContract(address: string): boolean; +} + +export namespace SignerKey { + function decodeAddress(address: string): xdr.SignerKey; + function encodeSignerKey(signerKey: xdr.SignerKey): string; +} + +export class TransactionI { + addSignature(publicKey: string, signature: string): void; + addDecoratedSignature(signature: xdr.DecoratedSignature): void; + + fee: string; + getKeypairSignature(keypair: Keypair): string; + hash(): Buffer; + networkPassphrase: string; + sign(...keypairs: Keypair[]): void; + signatureBase(): Buffer; + signatures: xdr.DecoratedSignature[]; + signHashX(preimage: Buffer | string): void; + toEnvelope(): xdr.TransactionEnvelope; + toXDR(): string; +} + +export class FeeBumpTransaction extends TransactionI { + constructor( + envelope: string | xdr.TransactionEnvelope, + networkPassphrase: string + ); + feeSource: string; + innerTransaction: Transaction; + get operations(): Operation[]; +} + +export class Transaction< + TMemo extends Memo = Memo, + TOps extends Operation[] = Operation[] +> extends TransactionI { + constructor( + envelope: string | xdr.TransactionEnvelope, + networkPassphrase: string + ); + memo: TMemo; + operations: TOps; + sequence: string; + source: string; + timeBounds?: { + minTime: string; + maxTime: string; + }; + ledgerBounds?: { + minLedger: number; + maxLedger: number; + }; + minAccountSequence?: string; + minAccountSequenceAge?: number; + minAccountSequenceLedgerGap?: number; + extraSigners?: string[]; + + getClaimableBalanceId(opIndex: number): string; +} + +export const BASE_FEE = '100'; +export const TimeoutInfinite = 0; + +export class TransactionBuilder { + constructor( + sourceAccount: Account, + options?: TransactionBuilder.TransactionBuilderOptions + ); + addOperation(operation: xdr.Operation): this; + addOperationAt(op: xdr.Operation, i: number): this; + clearOperations(): this; + clearOperationAt(i: number): this; + addMemo(memo: Memo): this; + setTimeout(timeoutInSeconds: number): this; + setTimebounds(min: Date | number, max: Date | number): this; + setLedgerbounds(minLedger: number, maxLedger: number): this; + setMinAccountSequence(minAccountSequence: string): this; + setMinAccountSequenceAge(durationInSeconds: number): this; + setMinAccountSequenceLedgerGap(gap: number): this; + setExtraSigners(extraSigners: string[]): this; + setSorobanData(sorobanData: string | xdr.SorobanTransactionData): this; + build(): Transaction; + setNetworkPassphrase(networkPassphrase: string): this; + + static cloneFrom( + tx: Transaction, + optionOverrides?: TransactionBuilder.TransactionBuilderOptions + ): TransactionBuilder; + static buildFeeBumpTransaction( + feeSource: Keypair | string, + baseFee: string, + innerTx: Transaction, + networkPassphrase: string + ): FeeBumpTransaction; + static fromXDR( + envelope: string | xdr.TransactionEnvelope, + networkPassphrase: string + ): Transaction | FeeBumpTransaction; + +} + +export namespace TransactionBuilder { + interface TransactionBuilderOptions { + fee: string; + memo?: Memo; + networkPassphrase?: string; + // preconditions: + timebounds?: { + minTime?: Date | number | string; + maxTime?: Date | number | string; + }; + ledgerbounds?: { + minLedger?: number; + maxLedger?: number; + }; + minAccountSequence?: string; + minAccountSequenceAge?: number; + minAccountSequenceLedgerGap?: number; + extraSigners?: string[]; + sorobanData?: string | xdr.SorobanTransactionData; + } +} + +export function hash(data: Buffer): Buffer; +export function sign(data: Buffer, rawSecret: Buffer): Buffer; +export function verify( + data: Buffer, + signature: Buffer, + rawPublicKey: Buffer +): boolean; + +export function decodeAddressToMuxedAccount(address: string, supportMuxing: boolean): xdr.MuxedAccount; +export function encodeMuxedAccountToAddress(account: xdr.MuxedAccount, supportMuxing: boolean): string; +export function encodeMuxedAccount(gAddress: string, id: string): xdr.MuxedAccount; +export function extractBaseAddress(address: string): string; + +export type IntLike = string | number | bigint; +export type ScIntType = + | 'i64' + | 'u64' + | 'i128' + | 'u128' + | 'i256' + | 'u256'; + +export class XdrLargeInt { + constructor( + type: ScIntType, + values: IntLike | IntLike[] + ); + + toNumber(): number; + toBigInt(): bigint; + + toI64(): xdr.ScVal; + toU64(): xdr.ScVal; + toI128(): xdr.ScVal; + toU128(): xdr.ScVal; + toI256(): xdr.ScVal; + toU256(): xdr.ScVal; + toScVal(): xdr.ScVal; + + valueOf(): any; // FIXME + toString(): string; + toJSON(): { + value: string; + type: ScIntType; + }; + + static isType(t: string): t is ScIntType; + static getType(scvType: string): ScIntType; +} + +export class ScInt extends XdrLargeInt { + constructor(value: IntLike, opts?: { type: ScIntType }); +} + +export function scValToBigInt(scv: xdr.ScVal): bigint; +export function nativeToScVal(val: any, opts?: { type: any }): xdr.ScVal; +export function scValToNative(scv: xdr.ScVal): any; + +interface SorobanEvent { + type: 'system'|'contract'|'diagnostic'; // xdr.ContractEventType.name + contractId?: string; // C... encoded strkey + + topics: any[]; // essentially a call of map(event.body.topics, scValToNative) + data: any; // similarly, scValToNative(rawEvent.data); +} + +export function humanizeEvents( + events: xdr.DiagnosticEvent[] | xdr.ContractEvent[] +): SorobanEvent[]; + +export class SorobanDataBuilder { + constructor(data?: string | Uint8Array | Buffer | xdr.SorobanTransactionData); + static fromXDR(data: Uint8Array | Buffer | string): SorobanDataBuilder; + + setResourceFee(fee: IntLike): SorobanDataBuilder; + setResources( + cpuInstrs: number, + readBytes: number, + writeBytes: number + ): SorobanDataBuilder; + + setFootprint( + readOnly?: xdr.LedgerKey[] | null, + readWrite?: xdr.LedgerKey[] | null + ): SorobanDataBuilder; + appendFootprint( + readOnly: xdr.LedgerKey[], + readWrite: xdr.LedgerKey[] + ): SorobanDataBuilder; + + setReadOnly(keys: xdr.LedgerKey[]): SorobanDataBuilder; + setReadWrite(keys: xdr.LedgerKey[]): SorobanDataBuilder; + + getFootprint(): xdr.LedgerFootprint; + getReadOnly(): xdr.LedgerKey[]; + getReadWrite(): xdr.LedgerKey[]; + + build(): xdr.SorobanTransactionData; +} + +export type SigningCallback = ( + preimage: xdr.HashIdPreimage +) => Promise; + +export function authorizeInvocation( + signer: Keypair | SigningCallback, + validUntil: number, + invocation: xdr.SorobanAuthorizedInvocation, + publicKey?: string, + networkPassphrase?: string +): Promise; + +export function authorizeEntry( + entry: xdr.SorobanAuthorizationEntry, + signer: Keypair | SigningCallback, + validUntilLedgerSeq: number, + networkPassphrase?: string +): Promise; + +export interface CreateInvocation { + type: 'wasm' | 'sac'; + token?: string; + wasm?: { + hash: string; + address: string; + salt: string; + constructorArgs?: any[]; + }; +} + +export interface ExecuteInvocation { + source: string; + function: string; + args: any[]; +} + +export interface InvocationTree { + type: 'execute' | 'create'; + args: CreateInvocation | ExecuteInvocation; + invocations: InvocationTree[]; +} + +export function buildInvocationTree( + root: xdr.SorobanAuthorizedInvocation +): InvocationTree; + +export type InvocationWalker = ( + node: xdr.SorobanAuthorizedInvocation, + depth: number, + parent?: any +) => boolean|null|void; + +export function walkInvocationTree( + root: xdr.SorobanAuthorizedInvocation, + callback: InvocationWalker +): void; + +export namespace Soroban { + function formatTokenAmount(address: string, decimals: number): string; + function parseTokenAmount(value: string, decimals: number): string; +} + +export namespace cereal { + // These belong in @stellar/js-xdr but that would be a huge lift since we'd + // need types for the whole thing. + export class XdrWriter { + constructor(buffer?: Buffer|number); + + alloc(size: number): number; + resize(minRequiredSize: number): void; + finalize(): Buffer; + toArray(): number[]; + + write(value: Buffer|string, size: number): XdrReader; + writeInt32BE(value: number): void; + writeUInt32BE(value: number): void; + writeBigInt64BE(value: BigInt): void; + writeBigUInt64BE(value: BigInt): void; + writeFloatBE(value: number): void; + writeDoubleBE(value: number): void; + } + + export class XdrReader { + constructor(data: Buffer); + + eof: boolean; + advance(size: number): number; + rewind(): void; + ensureInputConsumed(): void; + + read(size: number): Buffer; + readInt32BE(): number; + readUInt32BE(): number; + readBigInt64BE(): BigInt; + readBigUInt64BE(): BigInt; + readFloatBE(): number; + readDoubleBE(): number; + } +} diff --git a/node_modules/@stellar/stellar-base/types/next.d.ts b/node_modules/@stellar/stellar-base/types/next.d.ts new file mode 100644 index 000000000..ced3636f1 --- /dev/null +++ b/node_modules/@stellar/stellar-base/types/next.d.ts @@ -0,0 +1,15884 @@ +// Automatically generated by xdrgen on 2024-09-12T11:09:00-08:00 +// DO NOT EDIT or your changes may be overwritten +import { Operation } from './index'; + +export {}; + +// Hidden namespace as hack to work around name collision. +declare namespace xdrHidden { + // tslint:disable-line:strict-export-declare-modifiers + class Operation2 { + constructor(attributes: { + sourceAccount: null | xdr.MuxedAccount; + body: xdr.OperationBody; + }); + + sourceAccount(value?: null | xdr.MuxedAccount): null | xdr.MuxedAccount; + + body(value?: xdr.OperationBody): xdr.OperationBody; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): xdr.Operation; + + static write(value: xdr.Operation, io: Buffer): void; + + static isValid(value: xdr.Operation): boolean; + + static toXDR(value: xdr.Operation): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): xdr.Operation; + + static fromXDR(input: string, format: 'hex' | 'base64'): xdr.Operation; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } +} + +export namespace xdr { + export import Operation = xdrHidden.Operation2; // tslint:disable-line:strict-export-declare-modifiers + + type Hash = Opaque[]; // workaround, cause unknown + + interface SignedInt { + readonly MAX_VALUE: 2147483647; + readonly MIN_VALUE: -2147483648; + read(io: Buffer): number; + write(value: number, io: Buffer): void; + isValid(value: number): boolean; + toXDR(value: number): Buffer; + fromXDR(input: Buffer, format?: 'raw'): number; + fromXDR(input: string, format: 'hex' | 'base64'): number; + validateXDR(input: Buffer, format?: 'raw'): boolean; + validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + interface UnsignedInt { + readonly MAX_VALUE: 4294967295; + readonly MIN_VALUE: 0; + read(io: Buffer): number; + write(value: number, io: Buffer): void; + isValid(value: number): boolean; + toXDR(value: number): Buffer; + fromXDR(input: Buffer, format?: 'raw'): number; + fromXDR(input: string, format: 'hex' | 'base64'): number; + validateXDR(input: Buffer, format?: 'raw'): boolean; + validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + interface Bool { + read(io: Buffer): boolean; + write(value: boolean, io: Buffer): void; + isValid(value: boolean): boolean; + toXDR(value: boolean): Buffer; + fromXDR(input: Buffer, format?: 'raw'): boolean; + fromXDR(input: string, format: 'hex' | 'base64'): boolean; + validateXDR(input: Buffer, format?: 'raw'): boolean; + validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Hyper { + low: number; + + high: number; + + unsigned: boolean; + + constructor( + values: string | bigint | number | (string | bigint | number)[], + ); + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static toXDR(value: Hyper): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Hyper; + + static fromXDR(input: string, format: 'hex' | 'base64'): Hyper; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + + static readonly MAX_VALUE: Hyper; + + static readonly MIN_VALUE: Hyper; + + static read(io: Buffer): Hyper; + + static write(value: Hyper, io: Buffer): void; + + static fromString(input: string): Hyper; + + static fromBytes(low: number, high: number): Hyper; + + static isValid(value: Hyper): boolean; + + toBigInt(): bigint; + + toString(): string; + } + + class UnsignedHyper { + low: number; + + high: number; + + unsigned: boolean; + + constructor( + values: string | bigint | number | (string | bigint | number)[], + ); + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static toXDR(value: UnsignedHyper): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): UnsignedHyper; + + static fromXDR(input: string, format: 'hex' | 'base64'): UnsignedHyper; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + + static readonly MAX_VALUE: UnsignedHyper; + + static readonly MIN_VALUE: UnsignedHyper; + + static read(io: Buffer): UnsignedHyper; + + static write(value: UnsignedHyper, io: Buffer): void; + + static fromString(input: string): UnsignedHyper; + + static fromBytes(low: number, high: number): UnsignedHyper; + + static isValid(value: UnsignedHyper): boolean; + + toBigInt(): bigint; + + toString(): string; + } + + class XDRString { + constructor(maxLength: 4294967295); + + read(io: Buffer): Buffer; + + readString(io: Buffer): string; + + write(value: string | Buffer, io: Buffer): void; + + isValid(value: string | number[] | Buffer): boolean; + + toXDR(value: string | Buffer): Buffer; + + fromXDR(input: Buffer, format?: 'raw'): Buffer; + + fromXDR(input: string, format: 'hex' | 'base64'): Buffer; + + validateXDR(input: Buffer, format?: 'raw'): boolean; + + validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class XDRArray { + read(io: Buffer): Buffer; + + write(value: T[], io: Buffer): void; + + isValid(value: T[]): boolean; + + toXDR(value: T[]): Buffer; + + fromXDR(input: Buffer, format?: 'raw'): T[]; + + fromXDR(input: string, format: 'hex' | 'base64'): T[]; + + validateXDR(input: Buffer, format?: 'raw'): boolean; + + validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Opaque { + constructor(length: number); + + read(io: Buffer): Buffer; + + write(value: Buffer, io: Buffer): void; + + isValid(value: Buffer): boolean; + + toXDR(value: Buffer): Buffer; + + fromXDR(input: Buffer, format?: 'raw'): Buffer; + + fromXDR(input: string, format: 'hex' | 'base64'): Buffer; + + validateXDR(input: Buffer, format?: 'raw'): boolean; + + validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class VarOpaque extends Opaque {} + + class Option { + constructor(childType: { + read(io: any): any; + write(value: any, io: Buffer): void; + isValid(value: any): boolean; + }); + + read(io: Buffer): any; + + write(value: any, io: Buffer): void; + + isValid(value: any): boolean; + + toXDR(value: any): Buffer; + + fromXDR(input: Buffer, format?: 'raw'): any; + + fromXDR(input: string, format: 'hex' | 'base64'): any; + + validateXDR(input: Buffer, format?: 'raw'): boolean; + + validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpStatementType { + readonly name: + | 'scpStPrepare' + | 'scpStConfirm' + | 'scpStExternalize' + | 'scpStNominate'; + + readonly value: 0 | 1 | 2 | 3; + + static scpStPrepare(): ScpStatementType; + + static scpStConfirm(): ScpStatementType; + + static scpStExternalize(): ScpStatementType; + + static scpStNominate(): ScpStatementType; + } + + class AssetType { + readonly name: + | 'assetTypeNative' + | 'assetTypeCreditAlphanum4' + | 'assetTypeCreditAlphanum12' + | 'assetTypePoolShare'; + + readonly value: 0 | 1 | 2 | 3; + + static assetTypeNative(): AssetType; + + static assetTypeCreditAlphanum4(): AssetType; + + static assetTypeCreditAlphanum12(): AssetType; + + static assetTypePoolShare(): AssetType; + } + + class ThresholdIndices { + readonly name: + | 'thresholdMasterWeight' + | 'thresholdLow' + | 'thresholdMed' + | 'thresholdHigh'; + + readonly value: 0 | 1 | 2 | 3; + + static thresholdMasterWeight(): ThresholdIndices; + + static thresholdLow(): ThresholdIndices; + + static thresholdMed(): ThresholdIndices; + + static thresholdHigh(): ThresholdIndices; + } + + class LedgerEntryType { + readonly name: + | 'account' + | 'trustline' + | 'offer' + | 'data' + | 'claimableBalance' + | 'liquidityPool' + | 'contractData' + | 'contractCode' + | 'configSetting' + | 'ttl'; + + readonly value: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + + static account(): LedgerEntryType; + + static trustline(): LedgerEntryType; + + static offer(): LedgerEntryType; + + static data(): LedgerEntryType; + + static claimableBalance(): LedgerEntryType; + + static liquidityPool(): LedgerEntryType; + + static contractData(): LedgerEntryType; + + static contractCode(): LedgerEntryType; + + static configSetting(): LedgerEntryType; + + static ttl(): LedgerEntryType; + } + + class AccountFlags { + readonly name: + | 'authRequiredFlag' + | 'authRevocableFlag' + | 'authImmutableFlag' + | 'authClawbackEnabledFlag'; + + readonly value: 1 | 2 | 4 | 8; + + static authRequiredFlag(): AccountFlags; + + static authRevocableFlag(): AccountFlags; + + static authImmutableFlag(): AccountFlags; + + static authClawbackEnabledFlag(): AccountFlags; + } + + class TrustLineFlags { + readonly name: + | 'authorizedFlag' + | 'authorizedToMaintainLiabilitiesFlag' + | 'trustlineClawbackEnabledFlag'; + + readonly value: 1 | 2 | 4; + + static authorizedFlag(): TrustLineFlags; + + static authorizedToMaintainLiabilitiesFlag(): TrustLineFlags; + + static trustlineClawbackEnabledFlag(): TrustLineFlags; + } + + class LiquidityPoolType { + readonly name: 'liquidityPoolConstantProduct'; + + readonly value: 0; + + static liquidityPoolConstantProduct(): LiquidityPoolType; + } + + class OfferEntryFlags { + readonly name: 'passiveFlag'; + + readonly value: 1; + + static passiveFlag(): OfferEntryFlags; + } + + class ClaimPredicateType { + readonly name: + | 'claimPredicateUnconditional' + | 'claimPredicateAnd' + | 'claimPredicateOr' + | 'claimPredicateNot' + | 'claimPredicateBeforeAbsoluteTime' + | 'claimPredicateBeforeRelativeTime'; + + readonly value: 0 | 1 | 2 | 3 | 4 | 5; + + static claimPredicateUnconditional(): ClaimPredicateType; + + static claimPredicateAnd(): ClaimPredicateType; + + static claimPredicateOr(): ClaimPredicateType; + + static claimPredicateNot(): ClaimPredicateType; + + static claimPredicateBeforeAbsoluteTime(): ClaimPredicateType; + + static claimPredicateBeforeRelativeTime(): ClaimPredicateType; + } + + class ClaimantType { + readonly name: 'claimantTypeV0'; + + readonly value: 0; + + static claimantTypeV0(): ClaimantType; + } + + class ClaimableBalanceIdType { + readonly name: 'claimableBalanceIdTypeV0'; + + readonly value: 0; + + static claimableBalanceIdTypeV0(): ClaimableBalanceIdType; + } + + class ClaimableBalanceFlags { + readonly name: 'claimableBalanceClawbackEnabledFlag'; + + readonly value: 1; + + static claimableBalanceClawbackEnabledFlag(): ClaimableBalanceFlags; + } + + class ContractDataDurability { + readonly name: 'temporary' | 'persistent'; + + readonly value: 0 | 1; + + static temporary(): ContractDataDurability; + + static persistent(): ContractDataDurability; + } + + class EnvelopeType { + readonly name: + | 'envelopeTypeTxV0' + | 'envelopeTypeScp' + | 'envelopeTypeTx' + | 'envelopeTypeAuth' + | 'envelopeTypeScpvalue' + | 'envelopeTypeTxFeeBump' + | 'envelopeTypeOpId' + | 'envelopeTypePoolRevokeOpId' + | 'envelopeTypeContractId' + | 'envelopeTypeSorobanAuthorization'; + + readonly value: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + + static envelopeTypeTxV0(): EnvelopeType; + + static envelopeTypeScp(): EnvelopeType; + + static envelopeTypeTx(): EnvelopeType; + + static envelopeTypeAuth(): EnvelopeType; + + static envelopeTypeScpvalue(): EnvelopeType; + + static envelopeTypeTxFeeBump(): EnvelopeType; + + static envelopeTypeOpId(): EnvelopeType; + + static envelopeTypePoolRevokeOpId(): EnvelopeType; + + static envelopeTypeContractId(): EnvelopeType; + + static envelopeTypeSorobanAuthorization(): EnvelopeType; + } + + class BucketListType { + readonly name: 'live' | 'hotArchive' | 'coldArchive'; + + readonly value: 0 | 1 | 2; + + static live(): BucketListType; + + static hotArchive(): BucketListType; + + static coldArchive(): BucketListType; + } + + class BucketEntryType { + readonly name: 'metaentry' | 'liveentry' | 'deadentry' | 'initentry'; + + readonly value: -1 | 0 | 1 | 2; + + static metaentry(): BucketEntryType; + + static liveentry(): BucketEntryType; + + static deadentry(): BucketEntryType; + + static initentry(): BucketEntryType; + } + + class HotArchiveBucketEntryType { + readonly name: + | 'hotArchiveMetaentry' + | 'hotArchiveArchived' + | 'hotArchiveLive' + | 'hotArchiveDeleted'; + + readonly value: -1 | 0 | 1 | 2; + + static hotArchiveMetaentry(): HotArchiveBucketEntryType; + + static hotArchiveArchived(): HotArchiveBucketEntryType; + + static hotArchiveLive(): HotArchiveBucketEntryType; + + static hotArchiveDeleted(): HotArchiveBucketEntryType; + } + + class ColdArchiveBucketEntryType { + readonly name: + | 'coldArchiveMetaentry' + | 'coldArchiveArchivedLeaf' + | 'coldArchiveDeletedLeaf' + | 'coldArchiveBoundaryLeaf' + | 'coldArchiveHash'; + + readonly value: -1 | 0 | 1 | 2 | 3; + + static coldArchiveMetaentry(): ColdArchiveBucketEntryType; + + static coldArchiveArchivedLeaf(): ColdArchiveBucketEntryType; + + static coldArchiveDeletedLeaf(): ColdArchiveBucketEntryType; + + static coldArchiveBoundaryLeaf(): ColdArchiveBucketEntryType; + + static coldArchiveHash(): ColdArchiveBucketEntryType; + } + + class StellarValueType { + readonly name: 'stellarValueBasic' | 'stellarValueSigned'; + + readonly value: 0 | 1; + + static stellarValueBasic(): StellarValueType; + + static stellarValueSigned(): StellarValueType; + } + + class LedgerHeaderFlags { + readonly name: + | 'disableLiquidityPoolTradingFlag' + | 'disableLiquidityPoolDepositFlag' + | 'disableLiquidityPoolWithdrawalFlag'; + + readonly value: 1 | 2 | 4; + + static disableLiquidityPoolTradingFlag(): LedgerHeaderFlags; + + static disableLiquidityPoolDepositFlag(): LedgerHeaderFlags; + + static disableLiquidityPoolWithdrawalFlag(): LedgerHeaderFlags; + } + + class LedgerUpgradeType { + readonly name: + | 'ledgerUpgradeVersion' + | 'ledgerUpgradeBaseFee' + | 'ledgerUpgradeMaxTxSetSize' + | 'ledgerUpgradeBaseReserve' + | 'ledgerUpgradeFlags' + | 'ledgerUpgradeConfig' + | 'ledgerUpgradeMaxSorobanTxSetSize'; + + readonly value: 1 | 2 | 3 | 4 | 5 | 6 | 7; + + static ledgerUpgradeVersion(): LedgerUpgradeType; + + static ledgerUpgradeBaseFee(): LedgerUpgradeType; + + static ledgerUpgradeMaxTxSetSize(): LedgerUpgradeType; + + static ledgerUpgradeBaseReserve(): LedgerUpgradeType; + + static ledgerUpgradeFlags(): LedgerUpgradeType; + + static ledgerUpgradeConfig(): LedgerUpgradeType; + + static ledgerUpgradeMaxSorobanTxSetSize(): LedgerUpgradeType; + } + + class TxSetComponentType { + readonly name: 'txsetCompTxsMaybeDiscountedFee'; + + readonly value: 0; + + static txsetCompTxsMaybeDiscountedFee(): TxSetComponentType; + } + + class LedgerEntryChangeType { + readonly name: + | 'ledgerEntryCreated' + | 'ledgerEntryUpdated' + | 'ledgerEntryRemoved' + | 'ledgerEntryState'; + + readonly value: 0 | 1 | 2 | 3; + + static ledgerEntryCreated(): LedgerEntryChangeType; + + static ledgerEntryUpdated(): LedgerEntryChangeType; + + static ledgerEntryRemoved(): LedgerEntryChangeType; + + static ledgerEntryState(): LedgerEntryChangeType; + } + + class ContractEventType { + readonly name: 'system' | 'contract' | 'diagnostic'; + + readonly value: 0 | 1 | 2; + + static system(): ContractEventType; + + static contract(): ContractEventType; + + static diagnostic(): ContractEventType; + } + + class ErrorCode { + readonly name: 'errMisc' | 'errData' | 'errConf' | 'errAuth' | 'errLoad'; + + readonly value: 0 | 1 | 2 | 3 | 4; + + static errMisc(): ErrorCode; + + static errData(): ErrorCode; + + static errConf(): ErrorCode; + + static errAuth(): ErrorCode; + + static errLoad(): ErrorCode; + } + + class IpAddrType { + readonly name: 'iPv4' | 'iPv6'; + + readonly value: 0 | 1; + + static iPv4(): IpAddrType; + + static iPv6(): IpAddrType; + } + + class MessageType { + readonly name: + | 'errorMsg' + | 'auth' + | 'dontHave' + | 'getPeers' + | 'peers' + | 'getTxSet' + | 'txSet' + | 'generalizedTxSet' + | 'transaction' + | 'getScpQuorumset' + | 'scpQuorumset' + | 'scpMessage' + | 'getScpState' + | 'hello' + | 'surveyRequest' + | 'surveyResponse' + | 'sendMore' + | 'sendMoreExtended' + | 'floodAdvert' + | 'floodDemand' + | 'timeSlicedSurveyRequest' + | 'timeSlicedSurveyResponse' + | 'timeSlicedSurveyStartCollecting' + | 'timeSlicedSurveyStopCollecting'; + + readonly value: + | 0 + | 2 + | 3 + | 4 + | 5 + | 6 + | 7 + | 17 + | 8 + | 9 + | 10 + | 11 + | 12 + | 13 + | 14 + | 15 + | 16 + | 20 + | 18 + | 19 + | 21 + | 22 + | 23 + | 24; + + static errorMsg(): MessageType; + + static auth(): MessageType; + + static dontHave(): MessageType; + + static getPeers(): MessageType; + + static peers(): MessageType; + + static getTxSet(): MessageType; + + static txSet(): MessageType; + + static generalizedTxSet(): MessageType; + + static transaction(): MessageType; + + static getScpQuorumset(): MessageType; + + static scpQuorumset(): MessageType; + + static scpMessage(): MessageType; + + static getScpState(): MessageType; + + static hello(): MessageType; + + static surveyRequest(): MessageType; + + static surveyResponse(): MessageType; + + static sendMore(): MessageType; + + static sendMoreExtended(): MessageType; + + static floodAdvert(): MessageType; + + static floodDemand(): MessageType; + + static timeSlicedSurveyRequest(): MessageType; + + static timeSlicedSurveyResponse(): MessageType; + + static timeSlicedSurveyStartCollecting(): MessageType; + + static timeSlicedSurveyStopCollecting(): MessageType; + } + + class SurveyMessageCommandType { + readonly name: 'surveyTopology' | 'timeSlicedSurveyTopology'; + + readonly value: 0 | 1; + + static surveyTopology(): SurveyMessageCommandType; + + static timeSlicedSurveyTopology(): SurveyMessageCommandType; + } + + class SurveyMessageResponseType { + readonly name: + | 'surveyTopologyResponseV0' + | 'surveyTopologyResponseV1' + | 'surveyTopologyResponseV2'; + + readonly value: 0 | 1 | 2; + + static surveyTopologyResponseV0(): SurveyMessageResponseType; + + static surveyTopologyResponseV1(): SurveyMessageResponseType; + + static surveyTopologyResponseV2(): SurveyMessageResponseType; + } + + class OperationType { + readonly name: + | 'createAccount' + | 'payment' + | 'pathPaymentStrictReceive' + | 'manageSellOffer' + | 'createPassiveSellOffer' + | 'setOptions' + | 'changeTrust' + | 'allowTrust' + | 'accountMerge' + | 'inflation' + | 'manageData' + | 'bumpSequence' + | 'manageBuyOffer' + | 'pathPaymentStrictSend' + | 'createClaimableBalance' + | 'claimClaimableBalance' + | 'beginSponsoringFutureReserves' + | 'endSponsoringFutureReserves' + | 'revokeSponsorship' + | 'clawback' + | 'clawbackClaimableBalance' + | 'setTrustLineFlags' + | 'liquidityPoolDeposit' + | 'liquidityPoolWithdraw' + | 'invokeHostFunction' + | 'extendFootprintTtl' + | 'restoreFootprint'; + + readonly value: + | 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; + + static createAccount(): OperationType; + + static payment(): OperationType; + + static pathPaymentStrictReceive(): OperationType; + + static manageSellOffer(): OperationType; + + static createPassiveSellOffer(): OperationType; + + static setOptions(): OperationType; + + static changeTrust(): OperationType; + + static allowTrust(): OperationType; + + static accountMerge(): OperationType; + + static inflation(): OperationType; + + static manageData(): OperationType; + + static bumpSequence(): OperationType; + + static manageBuyOffer(): OperationType; + + static pathPaymentStrictSend(): OperationType; + + static createClaimableBalance(): OperationType; + + static claimClaimableBalance(): OperationType; + + static beginSponsoringFutureReserves(): OperationType; + + static endSponsoringFutureReserves(): OperationType; + + static revokeSponsorship(): OperationType; + + static clawback(): OperationType; + + static clawbackClaimableBalance(): OperationType; + + static setTrustLineFlags(): OperationType; + + static liquidityPoolDeposit(): OperationType; + + static liquidityPoolWithdraw(): OperationType; + + static invokeHostFunction(): OperationType; + + static extendFootprintTtl(): OperationType; + + static restoreFootprint(): OperationType; + } + + class RevokeSponsorshipType { + readonly name: 'revokeSponsorshipLedgerEntry' | 'revokeSponsorshipSigner'; + + readonly value: 0 | 1; + + static revokeSponsorshipLedgerEntry(): RevokeSponsorshipType; + + static revokeSponsorshipSigner(): RevokeSponsorshipType; + } + + class HostFunctionType { + readonly name: + | 'hostFunctionTypeInvokeContract' + | 'hostFunctionTypeCreateContract' + | 'hostFunctionTypeUploadContractWasm' + | 'hostFunctionTypeCreateContractV2'; + + readonly value: 0 | 1 | 2 | 3; + + static hostFunctionTypeInvokeContract(): HostFunctionType; + + static hostFunctionTypeCreateContract(): HostFunctionType; + + static hostFunctionTypeUploadContractWasm(): HostFunctionType; + + static hostFunctionTypeCreateContractV2(): HostFunctionType; + } + + class ContractIdPreimageType { + readonly name: + | 'contractIdPreimageFromAddress' + | 'contractIdPreimageFromAsset'; + + readonly value: 0 | 1; + + static contractIdPreimageFromAddress(): ContractIdPreimageType; + + static contractIdPreimageFromAsset(): ContractIdPreimageType; + } + + class SorobanAuthorizedFunctionType { + readonly name: + | 'sorobanAuthorizedFunctionTypeContractFn' + | 'sorobanAuthorizedFunctionTypeCreateContractHostFn' + | 'sorobanAuthorizedFunctionTypeCreateContractV2HostFn'; + + readonly value: 0 | 1 | 2; + + static sorobanAuthorizedFunctionTypeContractFn(): SorobanAuthorizedFunctionType; + + static sorobanAuthorizedFunctionTypeCreateContractHostFn(): SorobanAuthorizedFunctionType; + + static sorobanAuthorizedFunctionTypeCreateContractV2HostFn(): SorobanAuthorizedFunctionType; + } + + class SorobanCredentialsType { + readonly name: + | 'sorobanCredentialsSourceAccount' + | 'sorobanCredentialsAddress'; + + readonly value: 0 | 1; + + static sorobanCredentialsSourceAccount(): SorobanCredentialsType; + + static sorobanCredentialsAddress(): SorobanCredentialsType; + } + + class MemoType { + readonly name: + | 'memoNone' + | 'memoText' + | 'memoId' + | 'memoHash' + | 'memoReturn'; + + readonly value: 0 | 1 | 2 | 3 | 4; + + static memoNone(): MemoType; + + static memoText(): MemoType; + + static memoId(): MemoType; + + static memoHash(): MemoType; + + static memoReturn(): MemoType; + } + + class PreconditionType { + readonly name: 'precondNone' | 'precondTime' | 'precondV2'; + + readonly value: 0 | 1 | 2; + + static precondNone(): PreconditionType; + + static precondTime(): PreconditionType; + + static precondV2(): PreconditionType; + } + + class ArchivalProofType { + readonly name: 'existence' | 'nonexistence'; + + readonly value: 0 | 1; + + static existence(): ArchivalProofType; + + static nonexistence(): ArchivalProofType; + } + + class ClaimAtomType { + readonly name: + | 'claimAtomTypeV0' + | 'claimAtomTypeOrderBook' + | 'claimAtomTypeLiquidityPool'; + + readonly value: 0 | 1 | 2; + + static claimAtomTypeV0(): ClaimAtomType; + + static claimAtomTypeOrderBook(): ClaimAtomType; + + static claimAtomTypeLiquidityPool(): ClaimAtomType; + } + + class CreateAccountResultCode { + readonly name: + | 'createAccountSuccess' + | 'createAccountMalformed' + | 'createAccountUnderfunded' + | 'createAccountLowReserve' + | 'createAccountAlreadyExist'; + + readonly value: 0 | -1 | -2 | -3 | -4; + + static createAccountSuccess(): CreateAccountResultCode; + + static createAccountMalformed(): CreateAccountResultCode; + + static createAccountUnderfunded(): CreateAccountResultCode; + + static createAccountLowReserve(): CreateAccountResultCode; + + static createAccountAlreadyExist(): CreateAccountResultCode; + } + + class PaymentResultCode { + readonly name: + | 'paymentSuccess' + | 'paymentMalformed' + | 'paymentUnderfunded' + | 'paymentSrcNoTrust' + | 'paymentSrcNotAuthorized' + | 'paymentNoDestination' + | 'paymentNoTrust' + | 'paymentNotAuthorized' + | 'paymentLineFull' + | 'paymentNoIssuer'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5 | -6 | -7 | -8 | -9; + + static paymentSuccess(): PaymentResultCode; + + static paymentMalformed(): PaymentResultCode; + + static paymentUnderfunded(): PaymentResultCode; + + static paymentSrcNoTrust(): PaymentResultCode; + + static paymentSrcNotAuthorized(): PaymentResultCode; + + static paymentNoDestination(): PaymentResultCode; + + static paymentNoTrust(): PaymentResultCode; + + static paymentNotAuthorized(): PaymentResultCode; + + static paymentLineFull(): PaymentResultCode; + + static paymentNoIssuer(): PaymentResultCode; + } + + class PathPaymentStrictReceiveResultCode { + readonly name: + | 'pathPaymentStrictReceiveSuccess' + | 'pathPaymentStrictReceiveMalformed' + | 'pathPaymentStrictReceiveUnderfunded' + | 'pathPaymentStrictReceiveSrcNoTrust' + | 'pathPaymentStrictReceiveSrcNotAuthorized' + | 'pathPaymentStrictReceiveNoDestination' + | 'pathPaymentStrictReceiveNoTrust' + | 'pathPaymentStrictReceiveNotAuthorized' + | 'pathPaymentStrictReceiveLineFull' + | 'pathPaymentStrictReceiveNoIssuer' + | 'pathPaymentStrictReceiveTooFewOffers' + | 'pathPaymentStrictReceiveOfferCrossSelf' + | 'pathPaymentStrictReceiveOverSendmax'; + + readonly value: + | 0 + | -1 + | -2 + | -3 + | -4 + | -5 + | -6 + | -7 + | -8 + | -9 + | -10 + | -11 + | -12; + + static pathPaymentStrictReceiveSuccess(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveMalformed(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveUnderfunded(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveSrcNoTrust(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveSrcNotAuthorized(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveNoDestination(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveNoTrust(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveNotAuthorized(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveLineFull(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveNoIssuer(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveTooFewOffers(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveOfferCrossSelf(): PathPaymentStrictReceiveResultCode; + + static pathPaymentStrictReceiveOverSendmax(): PathPaymentStrictReceiveResultCode; + } + + class PathPaymentStrictSendResultCode { + readonly name: + | 'pathPaymentStrictSendSuccess' + | 'pathPaymentStrictSendMalformed' + | 'pathPaymentStrictSendUnderfunded' + | 'pathPaymentStrictSendSrcNoTrust' + | 'pathPaymentStrictSendSrcNotAuthorized' + | 'pathPaymentStrictSendNoDestination' + | 'pathPaymentStrictSendNoTrust' + | 'pathPaymentStrictSendNotAuthorized' + | 'pathPaymentStrictSendLineFull' + | 'pathPaymentStrictSendNoIssuer' + | 'pathPaymentStrictSendTooFewOffers' + | 'pathPaymentStrictSendOfferCrossSelf' + | 'pathPaymentStrictSendUnderDestmin'; + + readonly value: + | 0 + | -1 + | -2 + | -3 + | -4 + | -5 + | -6 + | -7 + | -8 + | -9 + | -10 + | -11 + | -12; + + static pathPaymentStrictSendSuccess(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendMalformed(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendUnderfunded(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendSrcNoTrust(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendSrcNotAuthorized(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendNoDestination(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendNoTrust(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendNotAuthorized(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendLineFull(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendNoIssuer(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendTooFewOffers(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendOfferCrossSelf(): PathPaymentStrictSendResultCode; + + static pathPaymentStrictSendUnderDestmin(): PathPaymentStrictSendResultCode; + } + + class ManageSellOfferResultCode { + readonly name: + | 'manageSellOfferSuccess' + | 'manageSellOfferMalformed' + | 'manageSellOfferSellNoTrust' + | 'manageSellOfferBuyNoTrust' + | 'manageSellOfferSellNotAuthorized' + | 'manageSellOfferBuyNotAuthorized' + | 'manageSellOfferLineFull' + | 'manageSellOfferUnderfunded' + | 'manageSellOfferCrossSelf' + | 'manageSellOfferSellNoIssuer' + | 'manageSellOfferBuyNoIssuer' + | 'manageSellOfferNotFound' + | 'manageSellOfferLowReserve'; + + readonly value: + | 0 + | -1 + | -2 + | -3 + | -4 + | -5 + | -6 + | -7 + | -8 + | -9 + | -10 + | -11 + | -12; + + static manageSellOfferSuccess(): ManageSellOfferResultCode; + + static manageSellOfferMalformed(): ManageSellOfferResultCode; + + static manageSellOfferSellNoTrust(): ManageSellOfferResultCode; + + static manageSellOfferBuyNoTrust(): ManageSellOfferResultCode; + + static manageSellOfferSellNotAuthorized(): ManageSellOfferResultCode; + + static manageSellOfferBuyNotAuthorized(): ManageSellOfferResultCode; + + static manageSellOfferLineFull(): ManageSellOfferResultCode; + + static manageSellOfferUnderfunded(): ManageSellOfferResultCode; + + static manageSellOfferCrossSelf(): ManageSellOfferResultCode; + + static manageSellOfferSellNoIssuer(): ManageSellOfferResultCode; + + static manageSellOfferBuyNoIssuer(): ManageSellOfferResultCode; + + static manageSellOfferNotFound(): ManageSellOfferResultCode; + + static manageSellOfferLowReserve(): ManageSellOfferResultCode; + } + + class ManageOfferEffect { + readonly name: + | 'manageOfferCreated' + | 'manageOfferUpdated' + | 'manageOfferDeleted'; + + readonly value: 0 | 1 | 2; + + static manageOfferCreated(): ManageOfferEffect; + + static manageOfferUpdated(): ManageOfferEffect; + + static manageOfferDeleted(): ManageOfferEffect; + } + + class ManageBuyOfferResultCode { + readonly name: + | 'manageBuyOfferSuccess' + | 'manageBuyOfferMalformed' + | 'manageBuyOfferSellNoTrust' + | 'manageBuyOfferBuyNoTrust' + | 'manageBuyOfferSellNotAuthorized' + | 'manageBuyOfferBuyNotAuthorized' + | 'manageBuyOfferLineFull' + | 'manageBuyOfferUnderfunded' + | 'manageBuyOfferCrossSelf' + | 'manageBuyOfferSellNoIssuer' + | 'manageBuyOfferBuyNoIssuer' + | 'manageBuyOfferNotFound' + | 'manageBuyOfferLowReserve'; + + readonly value: + | 0 + | -1 + | -2 + | -3 + | -4 + | -5 + | -6 + | -7 + | -8 + | -9 + | -10 + | -11 + | -12; + + static manageBuyOfferSuccess(): ManageBuyOfferResultCode; + + static manageBuyOfferMalformed(): ManageBuyOfferResultCode; + + static manageBuyOfferSellNoTrust(): ManageBuyOfferResultCode; + + static manageBuyOfferBuyNoTrust(): ManageBuyOfferResultCode; + + static manageBuyOfferSellNotAuthorized(): ManageBuyOfferResultCode; + + static manageBuyOfferBuyNotAuthorized(): ManageBuyOfferResultCode; + + static manageBuyOfferLineFull(): ManageBuyOfferResultCode; + + static manageBuyOfferUnderfunded(): ManageBuyOfferResultCode; + + static manageBuyOfferCrossSelf(): ManageBuyOfferResultCode; + + static manageBuyOfferSellNoIssuer(): ManageBuyOfferResultCode; + + static manageBuyOfferBuyNoIssuer(): ManageBuyOfferResultCode; + + static manageBuyOfferNotFound(): ManageBuyOfferResultCode; + + static manageBuyOfferLowReserve(): ManageBuyOfferResultCode; + } + + class SetOptionsResultCode { + readonly name: + | 'setOptionsSuccess' + | 'setOptionsLowReserve' + | 'setOptionsTooManySigners' + | 'setOptionsBadFlags' + | 'setOptionsInvalidInflation' + | 'setOptionsCantChange' + | 'setOptionsUnknownFlag' + | 'setOptionsThresholdOutOfRange' + | 'setOptionsBadSigner' + | 'setOptionsInvalidHomeDomain' + | 'setOptionsAuthRevocableRequired'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5 | -6 | -7 | -8 | -9 | -10; + + static setOptionsSuccess(): SetOptionsResultCode; + + static setOptionsLowReserve(): SetOptionsResultCode; + + static setOptionsTooManySigners(): SetOptionsResultCode; + + static setOptionsBadFlags(): SetOptionsResultCode; + + static setOptionsInvalidInflation(): SetOptionsResultCode; + + static setOptionsCantChange(): SetOptionsResultCode; + + static setOptionsUnknownFlag(): SetOptionsResultCode; + + static setOptionsThresholdOutOfRange(): SetOptionsResultCode; + + static setOptionsBadSigner(): SetOptionsResultCode; + + static setOptionsInvalidHomeDomain(): SetOptionsResultCode; + + static setOptionsAuthRevocableRequired(): SetOptionsResultCode; + } + + class ChangeTrustResultCode { + readonly name: + | 'changeTrustSuccess' + | 'changeTrustMalformed' + | 'changeTrustNoIssuer' + | 'changeTrustInvalidLimit' + | 'changeTrustLowReserve' + | 'changeTrustSelfNotAllowed' + | 'changeTrustTrustLineMissing' + | 'changeTrustCannotDelete' + | 'changeTrustNotAuthMaintainLiabilities'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5 | -6 | -7 | -8; + + static changeTrustSuccess(): ChangeTrustResultCode; + + static changeTrustMalformed(): ChangeTrustResultCode; + + static changeTrustNoIssuer(): ChangeTrustResultCode; + + static changeTrustInvalidLimit(): ChangeTrustResultCode; + + static changeTrustLowReserve(): ChangeTrustResultCode; + + static changeTrustSelfNotAllowed(): ChangeTrustResultCode; + + static changeTrustTrustLineMissing(): ChangeTrustResultCode; + + static changeTrustCannotDelete(): ChangeTrustResultCode; + + static changeTrustNotAuthMaintainLiabilities(): ChangeTrustResultCode; + } + + class AllowTrustResultCode { + readonly name: + | 'allowTrustSuccess' + | 'allowTrustMalformed' + | 'allowTrustNoTrustLine' + | 'allowTrustTrustNotRequired' + | 'allowTrustCantRevoke' + | 'allowTrustSelfNotAllowed' + | 'allowTrustLowReserve'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5 | -6; + + static allowTrustSuccess(): AllowTrustResultCode; + + static allowTrustMalformed(): AllowTrustResultCode; + + static allowTrustNoTrustLine(): AllowTrustResultCode; + + static allowTrustTrustNotRequired(): AllowTrustResultCode; + + static allowTrustCantRevoke(): AllowTrustResultCode; + + static allowTrustSelfNotAllowed(): AllowTrustResultCode; + + static allowTrustLowReserve(): AllowTrustResultCode; + } + + class AccountMergeResultCode { + readonly name: + | 'accountMergeSuccess' + | 'accountMergeMalformed' + | 'accountMergeNoAccount' + | 'accountMergeImmutableSet' + | 'accountMergeHasSubEntries' + | 'accountMergeSeqnumTooFar' + | 'accountMergeDestFull' + | 'accountMergeIsSponsor'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5 | -6 | -7; + + static accountMergeSuccess(): AccountMergeResultCode; + + static accountMergeMalformed(): AccountMergeResultCode; + + static accountMergeNoAccount(): AccountMergeResultCode; + + static accountMergeImmutableSet(): AccountMergeResultCode; + + static accountMergeHasSubEntries(): AccountMergeResultCode; + + static accountMergeSeqnumTooFar(): AccountMergeResultCode; + + static accountMergeDestFull(): AccountMergeResultCode; + + static accountMergeIsSponsor(): AccountMergeResultCode; + } + + class InflationResultCode { + readonly name: 'inflationSuccess' | 'inflationNotTime'; + + readonly value: 0 | -1; + + static inflationSuccess(): InflationResultCode; + + static inflationNotTime(): InflationResultCode; + } + + class ManageDataResultCode { + readonly name: + | 'manageDataSuccess' + | 'manageDataNotSupportedYet' + | 'manageDataNameNotFound' + | 'manageDataLowReserve' + | 'manageDataInvalidName'; + + readonly value: 0 | -1 | -2 | -3 | -4; + + static manageDataSuccess(): ManageDataResultCode; + + static manageDataNotSupportedYet(): ManageDataResultCode; + + static manageDataNameNotFound(): ManageDataResultCode; + + static manageDataLowReserve(): ManageDataResultCode; + + static manageDataInvalidName(): ManageDataResultCode; + } + + class BumpSequenceResultCode { + readonly name: 'bumpSequenceSuccess' | 'bumpSequenceBadSeq'; + + readonly value: 0 | -1; + + static bumpSequenceSuccess(): BumpSequenceResultCode; + + static bumpSequenceBadSeq(): BumpSequenceResultCode; + } + + class CreateClaimableBalanceResultCode { + readonly name: + | 'createClaimableBalanceSuccess' + | 'createClaimableBalanceMalformed' + | 'createClaimableBalanceLowReserve' + | 'createClaimableBalanceNoTrust' + | 'createClaimableBalanceNotAuthorized' + | 'createClaimableBalanceUnderfunded'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5; + + static createClaimableBalanceSuccess(): CreateClaimableBalanceResultCode; + + static createClaimableBalanceMalformed(): CreateClaimableBalanceResultCode; + + static createClaimableBalanceLowReserve(): CreateClaimableBalanceResultCode; + + static createClaimableBalanceNoTrust(): CreateClaimableBalanceResultCode; + + static createClaimableBalanceNotAuthorized(): CreateClaimableBalanceResultCode; + + static createClaimableBalanceUnderfunded(): CreateClaimableBalanceResultCode; + } + + class ClaimClaimableBalanceResultCode { + readonly name: + | 'claimClaimableBalanceSuccess' + | 'claimClaimableBalanceDoesNotExist' + | 'claimClaimableBalanceCannotClaim' + | 'claimClaimableBalanceLineFull' + | 'claimClaimableBalanceNoTrust' + | 'claimClaimableBalanceNotAuthorized'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5; + + static claimClaimableBalanceSuccess(): ClaimClaimableBalanceResultCode; + + static claimClaimableBalanceDoesNotExist(): ClaimClaimableBalanceResultCode; + + static claimClaimableBalanceCannotClaim(): ClaimClaimableBalanceResultCode; + + static claimClaimableBalanceLineFull(): ClaimClaimableBalanceResultCode; + + static claimClaimableBalanceNoTrust(): ClaimClaimableBalanceResultCode; + + static claimClaimableBalanceNotAuthorized(): ClaimClaimableBalanceResultCode; + } + + class BeginSponsoringFutureReservesResultCode { + readonly name: + | 'beginSponsoringFutureReservesSuccess' + | 'beginSponsoringFutureReservesMalformed' + | 'beginSponsoringFutureReservesAlreadySponsored' + | 'beginSponsoringFutureReservesRecursive'; + + readonly value: 0 | -1 | -2 | -3; + + static beginSponsoringFutureReservesSuccess(): BeginSponsoringFutureReservesResultCode; + + static beginSponsoringFutureReservesMalformed(): BeginSponsoringFutureReservesResultCode; + + static beginSponsoringFutureReservesAlreadySponsored(): BeginSponsoringFutureReservesResultCode; + + static beginSponsoringFutureReservesRecursive(): BeginSponsoringFutureReservesResultCode; + } + + class EndSponsoringFutureReservesResultCode { + readonly name: + | 'endSponsoringFutureReservesSuccess' + | 'endSponsoringFutureReservesNotSponsored'; + + readonly value: 0 | -1; + + static endSponsoringFutureReservesSuccess(): EndSponsoringFutureReservesResultCode; + + static endSponsoringFutureReservesNotSponsored(): EndSponsoringFutureReservesResultCode; + } + + class RevokeSponsorshipResultCode { + readonly name: + | 'revokeSponsorshipSuccess' + | 'revokeSponsorshipDoesNotExist' + | 'revokeSponsorshipNotSponsor' + | 'revokeSponsorshipLowReserve' + | 'revokeSponsorshipOnlyTransferable' + | 'revokeSponsorshipMalformed'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5; + + static revokeSponsorshipSuccess(): RevokeSponsorshipResultCode; + + static revokeSponsorshipDoesNotExist(): RevokeSponsorshipResultCode; + + static revokeSponsorshipNotSponsor(): RevokeSponsorshipResultCode; + + static revokeSponsorshipLowReserve(): RevokeSponsorshipResultCode; + + static revokeSponsorshipOnlyTransferable(): RevokeSponsorshipResultCode; + + static revokeSponsorshipMalformed(): RevokeSponsorshipResultCode; + } + + class ClawbackResultCode { + readonly name: + | 'clawbackSuccess' + | 'clawbackMalformed' + | 'clawbackNotClawbackEnabled' + | 'clawbackNoTrust' + | 'clawbackUnderfunded'; + + readonly value: 0 | -1 | -2 | -3 | -4; + + static clawbackSuccess(): ClawbackResultCode; + + static clawbackMalformed(): ClawbackResultCode; + + static clawbackNotClawbackEnabled(): ClawbackResultCode; + + static clawbackNoTrust(): ClawbackResultCode; + + static clawbackUnderfunded(): ClawbackResultCode; + } + + class ClawbackClaimableBalanceResultCode { + readonly name: + | 'clawbackClaimableBalanceSuccess' + | 'clawbackClaimableBalanceDoesNotExist' + | 'clawbackClaimableBalanceNotIssuer' + | 'clawbackClaimableBalanceNotClawbackEnabled'; + + readonly value: 0 | -1 | -2 | -3; + + static clawbackClaimableBalanceSuccess(): ClawbackClaimableBalanceResultCode; + + static clawbackClaimableBalanceDoesNotExist(): ClawbackClaimableBalanceResultCode; + + static clawbackClaimableBalanceNotIssuer(): ClawbackClaimableBalanceResultCode; + + static clawbackClaimableBalanceNotClawbackEnabled(): ClawbackClaimableBalanceResultCode; + } + + class SetTrustLineFlagsResultCode { + readonly name: + | 'setTrustLineFlagsSuccess' + | 'setTrustLineFlagsMalformed' + | 'setTrustLineFlagsNoTrustLine' + | 'setTrustLineFlagsCantRevoke' + | 'setTrustLineFlagsInvalidState' + | 'setTrustLineFlagsLowReserve'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5; + + static setTrustLineFlagsSuccess(): SetTrustLineFlagsResultCode; + + static setTrustLineFlagsMalformed(): SetTrustLineFlagsResultCode; + + static setTrustLineFlagsNoTrustLine(): SetTrustLineFlagsResultCode; + + static setTrustLineFlagsCantRevoke(): SetTrustLineFlagsResultCode; + + static setTrustLineFlagsInvalidState(): SetTrustLineFlagsResultCode; + + static setTrustLineFlagsLowReserve(): SetTrustLineFlagsResultCode; + } + + class LiquidityPoolDepositResultCode { + readonly name: + | 'liquidityPoolDepositSuccess' + | 'liquidityPoolDepositMalformed' + | 'liquidityPoolDepositNoTrust' + | 'liquidityPoolDepositNotAuthorized' + | 'liquidityPoolDepositUnderfunded' + | 'liquidityPoolDepositLineFull' + | 'liquidityPoolDepositBadPrice' + | 'liquidityPoolDepositPoolFull'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5 | -6 | -7; + + static liquidityPoolDepositSuccess(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositMalformed(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositNoTrust(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositNotAuthorized(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositUnderfunded(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositLineFull(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositBadPrice(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositPoolFull(): LiquidityPoolDepositResultCode; + } + + class LiquidityPoolWithdrawResultCode { + readonly name: + | 'liquidityPoolWithdrawSuccess' + | 'liquidityPoolWithdrawMalformed' + | 'liquidityPoolWithdrawNoTrust' + | 'liquidityPoolWithdrawUnderfunded' + | 'liquidityPoolWithdrawLineFull' + | 'liquidityPoolWithdrawUnderMinimum'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5; + + static liquidityPoolWithdrawSuccess(): LiquidityPoolWithdrawResultCode; + + static liquidityPoolWithdrawMalformed(): LiquidityPoolWithdrawResultCode; + + static liquidityPoolWithdrawNoTrust(): LiquidityPoolWithdrawResultCode; + + static liquidityPoolWithdrawUnderfunded(): LiquidityPoolWithdrawResultCode; + + static liquidityPoolWithdrawLineFull(): LiquidityPoolWithdrawResultCode; + + static liquidityPoolWithdrawUnderMinimum(): LiquidityPoolWithdrawResultCode; + } + + class InvokeHostFunctionResultCode { + readonly name: + | 'invokeHostFunctionSuccess' + | 'invokeHostFunctionMalformed' + | 'invokeHostFunctionTrapped' + | 'invokeHostFunctionResourceLimitExceeded' + | 'invokeHostFunctionEntryArchived' + | 'invokeHostFunctionInsufficientRefundableFee'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5; + + static invokeHostFunctionSuccess(): InvokeHostFunctionResultCode; + + static invokeHostFunctionMalformed(): InvokeHostFunctionResultCode; + + static invokeHostFunctionTrapped(): InvokeHostFunctionResultCode; + + static invokeHostFunctionResourceLimitExceeded(): InvokeHostFunctionResultCode; + + static invokeHostFunctionEntryArchived(): InvokeHostFunctionResultCode; + + static invokeHostFunctionInsufficientRefundableFee(): InvokeHostFunctionResultCode; + } + + class ExtendFootprintTtlResultCode { + readonly name: + | 'extendFootprintTtlSuccess' + | 'extendFootprintTtlMalformed' + | 'extendFootprintTtlResourceLimitExceeded' + | 'extendFootprintTtlInsufficientRefundableFee'; + + readonly value: 0 | -1 | -2 | -3; + + static extendFootprintTtlSuccess(): ExtendFootprintTtlResultCode; + + static extendFootprintTtlMalformed(): ExtendFootprintTtlResultCode; + + static extendFootprintTtlResourceLimitExceeded(): ExtendFootprintTtlResultCode; + + static extendFootprintTtlInsufficientRefundableFee(): ExtendFootprintTtlResultCode; + } + + class RestoreFootprintResultCode { + readonly name: + | 'restoreFootprintSuccess' + | 'restoreFootprintMalformed' + | 'restoreFootprintResourceLimitExceeded' + | 'restoreFootprintInsufficientRefundableFee'; + + readonly value: 0 | -1 | -2 | -3; + + static restoreFootprintSuccess(): RestoreFootprintResultCode; + + static restoreFootprintMalformed(): RestoreFootprintResultCode; + + static restoreFootprintResourceLimitExceeded(): RestoreFootprintResultCode; + + static restoreFootprintInsufficientRefundableFee(): RestoreFootprintResultCode; + } + + class OperationResultCode { + readonly name: + | 'opInner' + | 'opBadAuth' + | 'opNoAccount' + | 'opNotSupported' + | 'opTooManySubentries' + | 'opExceededWorkLimit' + | 'opTooManySponsoring'; + + readonly value: 0 | -1 | -2 | -3 | -4 | -5 | -6; + + static opInner(): OperationResultCode; + + static opBadAuth(): OperationResultCode; + + static opNoAccount(): OperationResultCode; + + static opNotSupported(): OperationResultCode; + + static opTooManySubentries(): OperationResultCode; + + static opExceededWorkLimit(): OperationResultCode; + + static opTooManySponsoring(): OperationResultCode; + } + + class TransactionResultCode { + readonly name: + | 'txFeeBumpInnerSuccess' + | 'txSuccess' + | 'txFailed' + | 'txTooEarly' + | 'txTooLate' + | 'txMissingOperation' + | 'txBadSeq' + | 'txBadAuth' + | 'txInsufficientBalance' + | 'txNoAccount' + | 'txInsufficientFee' + | 'txBadAuthExtra' + | 'txInternalError' + | 'txNotSupported' + | 'txFeeBumpInnerFailed' + | 'txBadSponsorship' + | 'txBadMinSeqAgeOrGap' + | 'txMalformed' + | 'txSorobanInvalid'; + + readonly value: + | 1 + | 0 + | -1 + | -2 + | -3 + | -4 + | -5 + | -6 + | -7 + | -8 + | -9 + | -10 + | -11 + | -12 + | -13 + | -14 + | -15 + | -16 + | -17; + + static txFeeBumpInnerSuccess(): TransactionResultCode; + + static txSuccess(): TransactionResultCode; + + static txFailed(): TransactionResultCode; + + static txTooEarly(): TransactionResultCode; + + static txTooLate(): TransactionResultCode; + + static txMissingOperation(): TransactionResultCode; + + static txBadSeq(): TransactionResultCode; + + static txBadAuth(): TransactionResultCode; + + static txInsufficientBalance(): TransactionResultCode; + + static txNoAccount(): TransactionResultCode; + + static txInsufficientFee(): TransactionResultCode; + + static txBadAuthExtra(): TransactionResultCode; + + static txInternalError(): TransactionResultCode; + + static txNotSupported(): TransactionResultCode; + + static txFeeBumpInnerFailed(): TransactionResultCode; + + static txBadSponsorship(): TransactionResultCode; + + static txBadMinSeqAgeOrGap(): TransactionResultCode; + + static txMalformed(): TransactionResultCode; + + static txSorobanInvalid(): TransactionResultCode; + } + + class CryptoKeyType { + readonly name: + | 'keyTypeEd25519' + | 'keyTypePreAuthTx' + | 'keyTypeHashX' + | 'keyTypeEd25519SignedPayload' + | 'keyTypeMuxedEd25519'; + + readonly value: 0 | 1 | 2 | 3 | 256; + + static keyTypeEd25519(): CryptoKeyType; + + static keyTypePreAuthTx(): CryptoKeyType; + + static keyTypeHashX(): CryptoKeyType; + + static keyTypeEd25519SignedPayload(): CryptoKeyType; + + static keyTypeMuxedEd25519(): CryptoKeyType; + } + + class PublicKeyType { + readonly name: 'publicKeyTypeEd25519'; + + readonly value: 0; + + static publicKeyTypeEd25519(): PublicKeyType; + } + + class SignerKeyType { + readonly name: + | 'signerKeyTypeEd25519' + | 'signerKeyTypePreAuthTx' + | 'signerKeyTypeHashX' + | 'signerKeyTypeEd25519SignedPayload'; + + readonly value: 0 | 1 | 2 | 3; + + static signerKeyTypeEd25519(): SignerKeyType; + + static signerKeyTypePreAuthTx(): SignerKeyType; + + static signerKeyTypeHashX(): SignerKeyType; + + static signerKeyTypeEd25519SignedPayload(): SignerKeyType; + } + + class BinaryFuseFilterType { + readonly name: + | 'binaryFuseFilter8Bit' + | 'binaryFuseFilter16Bit' + | 'binaryFuseFilter32Bit'; + + readonly value: 0 | 1 | 2; + + static binaryFuseFilter8Bit(): BinaryFuseFilterType; + + static binaryFuseFilter16Bit(): BinaryFuseFilterType; + + static binaryFuseFilter32Bit(): BinaryFuseFilterType; + } + + class ScValType { + readonly name: + | 'scvBool' + | 'scvVoid' + | 'scvError' + | 'scvU32' + | 'scvI32' + | 'scvU64' + | 'scvI64' + | 'scvTimepoint' + | 'scvDuration' + | 'scvU128' + | 'scvI128' + | 'scvU256' + | 'scvI256' + | 'scvBytes' + | 'scvString' + | 'scvSymbol' + | 'scvVec' + | 'scvMap' + | 'scvAddress' + | 'scvContractInstance' + | 'scvLedgerKeyContractInstance' + | 'scvLedgerKeyNonce'; + + readonly value: + | 0 + | 1 + | 2 + | 3 + | 4 + | 5 + | 6 + | 7 + | 8 + | 9 + | 10 + | 11 + | 12 + | 13 + | 14 + | 15 + | 16 + | 17 + | 18 + | 19 + | 20 + | 21; + + static scvBool(): ScValType; + + static scvVoid(): ScValType; + + static scvError(): ScValType; + + static scvU32(): ScValType; + + static scvI32(): ScValType; + + static scvU64(): ScValType; + + static scvI64(): ScValType; + + static scvTimepoint(): ScValType; + + static scvDuration(): ScValType; + + static scvU128(): ScValType; + + static scvI128(): ScValType; + + static scvU256(): ScValType; + + static scvI256(): ScValType; + + static scvBytes(): ScValType; + + static scvString(): ScValType; + + static scvSymbol(): ScValType; + + static scvVec(): ScValType; + + static scvMap(): ScValType; + + static scvAddress(): ScValType; + + static scvContractInstance(): ScValType; + + static scvLedgerKeyContractInstance(): ScValType; + + static scvLedgerKeyNonce(): ScValType; + } + + class ScErrorType { + readonly name: + | 'sceContract' + | 'sceWasmVm' + | 'sceContext' + | 'sceStorage' + | 'sceObject' + | 'sceCrypto' + | 'sceEvents' + | 'sceBudget' + | 'sceValue' + | 'sceAuth'; + + readonly value: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + + static sceContract(): ScErrorType; + + static sceWasmVm(): ScErrorType; + + static sceContext(): ScErrorType; + + static sceStorage(): ScErrorType; + + static sceObject(): ScErrorType; + + static sceCrypto(): ScErrorType; + + static sceEvents(): ScErrorType; + + static sceBudget(): ScErrorType; + + static sceValue(): ScErrorType; + + static sceAuth(): ScErrorType; + } + + class ScErrorCode { + readonly name: + | 'scecArithDomain' + | 'scecIndexBounds' + | 'scecInvalidInput' + | 'scecMissingValue' + | 'scecExistingValue' + | 'scecExceededLimit' + | 'scecInvalidAction' + | 'scecInternalError' + | 'scecUnexpectedType' + | 'scecUnexpectedSize'; + + readonly value: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + + static scecArithDomain(): ScErrorCode; + + static scecIndexBounds(): ScErrorCode; + + static scecInvalidInput(): ScErrorCode; + + static scecMissingValue(): ScErrorCode; + + static scecExistingValue(): ScErrorCode; + + static scecExceededLimit(): ScErrorCode; + + static scecInvalidAction(): ScErrorCode; + + static scecInternalError(): ScErrorCode; + + static scecUnexpectedType(): ScErrorCode; + + static scecUnexpectedSize(): ScErrorCode; + } + + class ContractExecutableType { + readonly name: 'contractExecutableWasm' | 'contractExecutableStellarAsset'; + + readonly value: 0 | 1; + + static contractExecutableWasm(): ContractExecutableType; + + static contractExecutableStellarAsset(): ContractExecutableType; + } + + class ScAddressType { + readonly name: 'scAddressTypeAccount' | 'scAddressTypeContract'; + + readonly value: 0 | 1; + + static scAddressTypeAccount(): ScAddressType; + + static scAddressTypeContract(): ScAddressType; + } + + class ScEnvMetaKind { + readonly name: 'scEnvMetaKindInterfaceVersion'; + + readonly value: 0; + + static scEnvMetaKindInterfaceVersion(): ScEnvMetaKind; + } + + class ScMetaKind { + readonly name: 'scMetaV0'; + + readonly value: 0; + + static scMetaV0(): ScMetaKind; + } + + class ScSpecType { + readonly name: + | 'scSpecTypeVal' + | 'scSpecTypeBool' + | 'scSpecTypeVoid' + | 'scSpecTypeError' + | 'scSpecTypeU32' + | 'scSpecTypeI32' + | 'scSpecTypeU64' + | 'scSpecTypeI64' + | 'scSpecTypeTimepoint' + | 'scSpecTypeDuration' + | 'scSpecTypeU128' + | 'scSpecTypeI128' + | 'scSpecTypeU256' + | 'scSpecTypeI256' + | 'scSpecTypeBytes' + | 'scSpecTypeString' + | 'scSpecTypeSymbol' + | 'scSpecTypeAddress' + | 'scSpecTypeOption' + | 'scSpecTypeResult' + | 'scSpecTypeVec' + | 'scSpecTypeMap' + | 'scSpecTypeTuple' + | 'scSpecTypeBytesN' + | 'scSpecTypeUdt'; + + readonly value: + | 0 + | 1 + | 2 + | 3 + | 4 + | 5 + | 6 + | 7 + | 8 + | 9 + | 10 + | 11 + | 12 + | 13 + | 14 + | 16 + | 17 + | 19 + | 1000 + | 1001 + | 1002 + | 1004 + | 1005 + | 1006 + | 2000; + + static scSpecTypeVal(): ScSpecType; + + static scSpecTypeBool(): ScSpecType; + + static scSpecTypeVoid(): ScSpecType; + + static scSpecTypeError(): ScSpecType; + + static scSpecTypeU32(): ScSpecType; + + static scSpecTypeI32(): ScSpecType; + + static scSpecTypeU64(): ScSpecType; + + static scSpecTypeI64(): ScSpecType; + + static scSpecTypeTimepoint(): ScSpecType; + + static scSpecTypeDuration(): ScSpecType; + + static scSpecTypeU128(): ScSpecType; + + static scSpecTypeI128(): ScSpecType; + + static scSpecTypeU256(): ScSpecType; + + static scSpecTypeI256(): ScSpecType; + + static scSpecTypeBytes(): ScSpecType; + + static scSpecTypeString(): ScSpecType; + + static scSpecTypeSymbol(): ScSpecType; + + static scSpecTypeAddress(): ScSpecType; + + static scSpecTypeOption(): ScSpecType; + + static scSpecTypeResult(): ScSpecType; + + static scSpecTypeVec(): ScSpecType; + + static scSpecTypeMap(): ScSpecType; + + static scSpecTypeTuple(): ScSpecType; + + static scSpecTypeBytesN(): ScSpecType; + + static scSpecTypeUdt(): ScSpecType; + } + + class ScSpecUdtUnionCaseV0Kind { + readonly name: 'scSpecUdtUnionCaseVoidV0' | 'scSpecUdtUnionCaseTupleV0'; + + readonly value: 0 | 1; + + static scSpecUdtUnionCaseVoidV0(): ScSpecUdtUnionCaseV0Kind; + + static scSpecUdtUnionCaseTupleV0(): ScSpecUdtUnionCaseV0Kind; + } + + class ScSpecEntryKind { + readonly name: + | 'scSpecEntryFunctionV0' + | 'scSpecEntryUdtStructV0' + | 'scSpecEntryUdtUnionV0' + | 'scSpecEntryUdtEnumV0' + | 'scSpecEntryUdtErrorEnumV0'; + + readonly value: 0 | 1 | 2 | 3 | 4; + + static scSpecEntryFunctionV0(): ScSpecEntryKind; + + static scSpecEntryUdtStructV0(): ScSpecEntryKind; + + static scSpecEntryUdtUnionV0(): ScSpecEntryKind; + + static scSpecEntryUdtEnumV0(): ScSpecEntryKind; + + static scSpecEntryUdtErrorEnumV0(): ScSpecEntryKind; + } + + class ContractCostType { + readonly name: + | 'wasmInsnExec' + | 'memAlloc' + | 'memCpy' + | 'memCmp' + | 'dispatchHostFunction' + | 'visitObject' + | 'valSer' + | 'valDeser' + | 'computeSha256Hash' + | 'computeEd25519PubKey' + | 'verifyEd25519Sig' + | 'vmInstantiation' + | 'vmCachedInstantiation' + | 'invokeVmFunction' + | 'computeKeccak256Hash' + | 'decodeEcdsaCurve256Sig' + | 'recoverEcdsaSecp256k1Key' + | 'int256AddSub' + | 'int256Mul' + | 'int256Div' + | 'int256Pow' + | 'int256Shift' + | 'chaCha20DrawBytes' + | 'parseWasmInstructions' + | 'parseWasmFunctions' + | 'parseWasmGlobals' + | 'parseWasmTableEntries' + | 'parseWasmTypes' + | 'parseWasmDataSegments' + | 'parseWasmElemSegments' + | 'parseWasmImports' + | 'parseWasmExports' + | 'parseWasmDataSegmentBytes' + | 'instantiateWasmInstructions' + | 'instantiateWasmFunctions' + | 'instantiateWasmGlobals' + | 'instantiateWasmTableEntries' + | 'instantiateWasmTypes' + | 'instantiateWasmDataSegments' + | 'instantiateWasmElemSegments' + | 'instantiateWasmImports' + | 'instantiateWasmExports' + | 'instantiateWasmDataSegmentBytes' + | 'sec1DecodePointUncompressed' + | 'verifyEcdsaSecp256r1Sig' + | 'bls12381EncodeFp' + | 'bls12381DecodeFp' + | 'bls12381G1CheckPointOnCurve' + | 'bls12381G1CheckPointInSubgroup' + | 'bls12381G2CheckPointOnCurve' + | 'bls12381G2CheckPointInSubgroup' + | 'bls12381G1ProjectiveToAffine' + | 'bls12381G2ProjectiveToAffine' + | 'bls12381G1Add' + | 'bls12381G1Mul' + | 'bls12381G1Msm' + | 'bls12381MapFpToG1' + | 'bls12381HashToG1' + | 'bls12381G2Add' + | 'bls12381G2Mul' + | 'bls12381G2Msm' + | 'bls12381MapFp2ToG2' + | 'bls12381HashToG2' + | 'bls12381Pairing' + | 'bls12381FrFromU256' + | 'bls12381FrToU256' + | 'bls12381FrAddSub' + | 'bls12381FrMul' + | 'bls12381FrPow' + | 'bls12381FrInv'; + + readonly value: + | 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 + | 32 + | 33 + | 34 + | 35 + | 36 + | 37 + | 38 + | 39 + | 40 + | 41 + | 42 + | 43 + | 44 + | 45 + | 46 + | 47 + | 48 + | 49 + | 50 + | 51 + | 52 + | 53 + | 54 + | 55 + | 56 + | 57 + | 58 + | 59 + | 60 + | 61 + | 62 + | 63 + | 64 + | 65 + | 66 + | 67 + | 68 + | 69; + + static wasmInsnExec(): ContractCostType; + + static memAlloc(): ContractCostType; + + static memCpy(): ContractCostType; + + static memCmp(): ContractCostType; + + static dispatchHostFunction(): ContractCostType; + + static visitObject(): ContractCostType; + + static valSer(): ContractCostType; + + static valDeser(): ContractCostType; + + static computeSha256Hash(): ContractCostType; + + static computeEd25519PubKey(): ContractCostType; + + static verifyEd25519Sig(): ContractCostType; + + static vmInstantiation(): ContractCostType; + + static vmCachedInstantiation(): ContractCostType; + + static invokeVmFunction(): ContractCostType; + + static computeKeccak256Hash(): ContractCostType; + + static decodeEcdsaCurve256Sig(): ContractCostType; + + static recoverEcdsaSecp256k1Key(): ContractCostType; + + static int256AddSub(): ContractCostType; + + static int256Mul(): ContractCostType; + + static int256Div(): ContractCostType; + + static int256Pow(): ContractCostType; + + static int256Shift(): ContractCostType; + + static chaCha20DrawBytes(): ContractCostType; + + static parseWasmInstructions(): ContractCostType; + + static parseWasmFunctions(): ContractCostType; + + static parseWasmGlobals(): ContractCostType; + + static parseWasmTableEntries(): ContractCostType; + + static parseWasmTypes(): ContractCostType; + + static parseWasmDataSegments(): ContractCostType; + + static parseWasmElemSegments(): ContractCostType; + + static parseWasmImports(): ContractCostType; + + static parseWasmExports(): ContractCostType; + + static parseWasmDataSegmentBytes(): ContractCostType; + + static instantiateWasmInstructions(): ContractCostType; + + static instantiateWasmFunctions(): ContractCostType; + + static instantiateWasmGlobals(): ContractCostType; + + static instantiateWasmTableEntries(): ContractCostType; + + static instantiateWasmTypes(): ContractCostType; + + static instantiateWasmDataSegments(): ContractCostType; + + static instantiateWasmElemSegments(): ContractCostType; + + static instantiateWasmImports(): ContractCostType; + + static instantiateWasmExports(): ContractCostType; + + static instantiateWasmDataSegmentBytes(): ContractCostType; + + static sec1DecodePointUncompressed(): ContractCostType; + + static verifyEcdsaSecp256r1Sig(): ContractCostType; + + static bls12381EncodeFp(): ContractCostType; + + static bls12381DecodeFp(): ContractCostType; + + static bls12381G1CheckPointOnCurve(): ContractCostType; + + static bls12381G1CheckPointInSubgroup(): ContractCostType; + + static bls12381G2CheckPointOnCurve(): ContractCostType; + + static bls12381G2CheckPointInSubgroup(): ContractCostType; + + static bls12381G1ProjectiveToAffine(): ContractCostType; + + static bls12381G2ProjectiveToAffine(): ContractCostType; + + static bls12381G1Add(): ContractCostType; + + static bls12381G1Mul(): ContractCostType; + + static bls12381G1Msm(): ContractCostType; + + static bls12381MapFpToG1(): ContractCostType; + + static bls12381HashToG1(): ContractCostType; + + static bls12381G2Add(): ContractCostType; + + static bls12381G2Mul(): ContractCostType; + + static bls12381G2Msm(): ContractCostType; + + static bls12381MapFp2ToG2(): ContractCostType; + + static bls12381HashToG2(): ContractCostType; + + static bls12381Pairing(): ContractCostType; + + static bls12381FrFromU256(): ContractCostType; + + static bls12381FrToU256(): ContractCostType; + + static bls12381FrAddSub(): ContractCostType; + + static bls12381FrMul(): ContractCostType; + + static bls12381FrPow(): ContractCostType; + + static bls12381FrInv(): ContractCostType; + } + + class ConfigSettingId { + readonly name: + | 'configSettingContractMaxSizeBytes' + | 'configSettingContractComputeV0' + | 'configSettingContractLedgerCostV0' + | 'configSettingContractHistoricalDataV0' + | 'configSettingContractEventsV0' + | 'configSettingContractBandwidthV0' + | 'configSettingContractCostParamsCpuInstructions' + | 'configSettingContractCostParamsMemoryBytes' + | 'configSettingContractDataKeySizeBytes' + | 'configSettingContractDataEntrySizeBytes' + | 'configSettingStateArchival' + | 'configSettingContractExecutionLanes' + | 'configSettingBucketlistSizeWindow' + | 'configSettingEvictionIterator' + | 'configSettingContractParallelComputeV0'; + + readonly value: + | 0 + | 1 + | 2 + | 3 + | 4 + | 5 + | 6 + | 7 + | 8 + | 9 + | 10 + | 11 + | 12 + | 13 + | 14; + + static configSettingContractMaxSizeBytes(): ConfigSettingId; + + static configSettingContractComputeV0(): ConfigSettingId; + + static configSettingContractLedgerCostV0(): ConfigSettingId; + + static configSettingContractHistoricalDataV0(): ConfigSettingId; + + static configSettingContractEventsV0(): ConfigSettingId; + + static configSettingContractBandwidthV0(): ConfigSettingId; + + static configSettingContractCostParamsCpuInstructions(): ConfigSettingId; + + static configSettingContractCostParamsMemoryBytes(): ConfigSettingId; + + static configSettingContractDataKeySizeBytes(): ConfigSettingId; + + static configSettingContractDataEntrySizeBytes(): ConfigSettingId; + + static configSettingStateArchival(): ConfigSettingId; + + static configSettingContractExecutionLanes(): ConfigSettingId; + + static configSettingBucketlistSizeWindow(): ConfigSettingId; + + static configSettingEvictionIterator(): ConfigSettingId; + + static configSettingContractParallelComputeV0(): ConfigSettingId; + } + + const Value: VarOpaque; + + const Thresholds: Opaque; + + const String32: XDRString; + + const String64: XDRString; + + type SequenceNumber = Int64; + + const DataValue: VarOpaque; + + type PoolId = Hash; + + const AssetCode4: Opaque; + + const AssetCode12: Opaque; + + type SponsorshipDescriptor = undefined | AccountId; + + const UpgradeType: VarOpaque; + + const TxExecutionThread: XDRArray; + + const ParallelTxExecutionStage: XDRArray; + + const LedgerEntryChanges: XDRArray; + + const EncryptedBody: VarOpaque; + + const PeerStatList: XDRArray; + + const TimeSlicedPeerDataList: XDRArray; + + const TxAdvertVector: XDRArray; + + const TxDemandVector: XDRArray; + + const ProofLevel: XDRArray; + + const Hash: Opaque; + + const Uint256: Opaque; + + const Uint32: UnsignedInt; + + const Int32: SignedInt; + + class Uint64 extends UnsignedHyper {} + + class Int64 extends Hyper {} + + type TimePoint = Uint64; + + type Duration = Uint64; + + const Signature: VarOpaque; + + const SignatureHint: Opaque; + + type NodeId = PublicKey; + + type AccountId = PublicKey; + + const ScVec: XDRArray; + + const ScMap: XDRArray; + + const ScBytes: VarOpaque; + + const ScString: XDRString; + + const ScSymbol: XDRString; + + const ContractCostParams: XDRArray; + + class ScpBallot { + constructor(attributes: { counter: number; value: Buffer }); + + counter(value?: number): number; + + value(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpBallot; + + static write(value: ScpBallot, io: Buffer): void; + + static isValid(value: ScpBallot): boolean; + + static toXDR(value: ScpBallot): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpBallot; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScpBallot; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpNomination { + constructor(attributes: { + quorumSetHash: Buffer; + votes: Buffer[]; + accepted: Buffer[]; + }); + + quorumSetHash(value?: Buffer): Buffer; + + votes(value?: Buffer[]): Buffer[]; + + accepted(value?: Buffer[]): Buffer[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpNomination; + + static write(value: ScpNomination, io: Buffer): void; + + static isValid(value: ScpNomination): boolean; + + static toXDR(value: ScpNomination): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpNomination; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScpNomination; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpStatementPrepare { + constructor(attributes: { + quorumSetHash: Buffer; + ballot: ScpBallot; + prepared: null | ScpBallot; + preparedPrime: null | ScpBallot; + nC: number; + nH: number; + }); + + quorumSetHash(value?: Buffer): Buffer; + + ballot(value?: ScpBallot): ScpBallot; + + prepared(value?: null | ScpBallot): null | ScpBallot; + + preparedPrime(value?: null | ScpBallot): null | ScpBallot; + + nC(value?: number): number; + + nH(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpStatementPrepare; + + static write(value: ScpStatementPrepare, io: Buffer): void; + + static isValid(value: ScpStatementPrepare): boolean; + + static toXDR(value: ScpStatementPrepare): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpStatementPrepare; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScpStatementPrepare; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpStatementConfirm { + constructor(attributes: { + ballot: ScpBallot; + nPrepared: number; + nCommit: number; + nH: number; + quorumSetHash: Buffer; + }); + + ballot(value?: ScpBallot): ScpBallot; + + nPrepared(value?: number): number; + + nCommit(value?: number): number; + + nH(value?: number): number; + + quorumSetHash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpStatementConfirm; + + static write(value: ScpStatementConfirm, io: Buffer): void; + + static isValid(value: ScpStatementConfirm): boolean; + + static toXDR(value: ScpStatementConfirm): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpStatementConfirm; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScpStatementConfirm; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpStatementExternalize { + constructor(attributes: { + commit: ScpBallot; + nH: number; + commitQuorumSetHash: Buffer; + }); + + commit(value?: ScpBallot): ScpBallot; + + nH(value?: number): number; + + commitQuorumSetHash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpStatementExternalize; + + static write(value: ScpStatementExternalize, io: Buffer): void; + + static isValid(value: ScpStatementExternalize): boolean; + + static toXDR(value: ScpStatementExternalize): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpStatementExternalize; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScpStatementExternalize; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpStatement { + constructor(attributes: { + nodeId: NodeId; + slotIndex: Uint64; + pledges: ScpStatementPledges; + }); + + nodeId(value?: NodeId): NodeId; + + slotIndex(value?: Uint64): Uint64; + + pledges(value?: ScpStatementPledges): ScpStatementPledges; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpStatement; + + static write(value: ScpStatement, io: Buffer): void; + + static isValid(value: ScpStatement): boolean; + + static toXDR(value: ScpStatement): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpStatement; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScpStatement; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpEnvelope { + constructor(attributes: { statement: ScpStatement; signature: Buffer }); + + statement(value?: ScpStatement): ScpStatement; + + signature(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpEnvelope; + + static write(value: ScpEnvelope, io: Buffer): void; + + static isValid(value: ScpEnvelope): boolean; + + static toXDR(value: ScpEnvelope): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpEnvelope; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScpEnvelope; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpQuorumSet { + constructor(attributes: { + threshold: number; + validators: NodeId[]; + innerSets: ScpQuorumSet[]; + }); + + threshold(value?: number): number; + + validators(value?: NodeId[]): NodeId[]; + + innerSets(value?: ScpQuorumSet[]): ScpQuorumSet[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpQuorumSet; + + static write(value: ScpQuorumSet, io: Buffer): void; + + static isValid(value: ScpQuorumSet): boolean; + + static toXDR(value: ScpQuorumSet): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpQuorumSet; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScpQuorumSet; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AlphaNum4 { + constructor(attributes: { assetCode: Buffer; issuer: AccountId }); + + assetCode(value?: Buffer): Buffer; + + issuer(value?: AccountId): AccountId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AlphaNum4; + + static write(value: AlphaNum4, io: Buffer): void; + + static isValid(value: AlphaNum4): boolean; + + static toXDR(value: AlphaNum4): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AlphaNum4; + + static fromXDR(input: string, format: 'hex' | 'base64'): AlphaNum4; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AlphaNum12 { + constructor(attributes: { assetCode: Buffer; issuer: AccountId }); + + assetCode(value?: Buffer): Buffer; + + issuer(value?: AccountId): AccountId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AlphaNum12; + + static write(value: AlphaNum12, io: Buffer): void; + + static isValid(value: AlphaNum12): boolean; + + static toXDR(value: AlphaNum12): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AlphaNum12; + + static fromXDR(input: string, format: 'hex' | 'base64'): AlphaNum12; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Price { + constructor(attributes: { n: number; d: number }); + + n(value?: number): number; + + d(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Price; + + static write(value: Price, io: Buffer): void; + + static isValid(value: Price): boolean; + + static toXDR(value: Price): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Price; + + static fromXDR(input: string, format: 'hex' | 'base64'): Price; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Liabilities { + constructor(attributes: { buying: Int64; selling: Int64 }); + + buying(value?: Int64): Int64; + + selling(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Liabilities; + + static write(value: Liabilities, io: Buffer): void; + + static isValid(value: Liabilities): boolean; + + static toXDR(value: Liabilities): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Liabilities; + + static fromXDR(input: string, format: 'hex' | 'base64'): Liabilities; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Signer { + constructor(attributes: { key: SignerKey; weight: number }); + + key(value?: SignerKey): SignerKey; + + weight(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Signer; + + static write(value: Signer, io: Buffer): void; + + static isValid(value: Signer): boolean; + + static toXDR(value: Signer): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Signer; + + static fromXDR(input: string, format: 'hex' | 'base64'): Signer; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountEntryExtensionV3 { + constructor(attributes: { + ext: ExtensionPoint; + seqLedger: number; + seqTime: TimePoint; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + seqLedger(value?: number): number; + + seqTime(value?: TimePoint): TimePoint; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountEntryExtensionV3; + + static write(value: AccountEntryExtensionV3, io: Buffer): void; + + static isValid(value: AccountEntryExtensionV3): boolean; + + static toXDR(value: AccountEntryExtensionV3): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountEntryExtensionV3; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): AccountEntryExtensionV3; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountEntryExtensionV2 { + constructor(attributes: { + numSponsored: number; + numSponsoring: number; + signerSponsoringIDs: SponsorshipDescriptor[]; + ext: AccountEntryExtensionV2Ext; + }); + + numSponsored(value?: number): number; + + numSponsoring(value?: number): number; + + signerSponsoringIDs( + value?: SponsorshipDescriptor[], + ): SponsorshipDescriptor[]; + + ext(value?: AccountEntryExtensionV2Ext): AccountEntryExtensionV2Ext; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountEntryExtensionV2; + + static write(value: AccountEntryExtensionV2, io: Buffer): void; + + static isValid(value: AccountEntryExtensionV2): boolean; + + static toXDR(value: AccountEntryExtensionV2): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountEntryExtensionV2; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): AccountEntryExtensionV2; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountEntryExtensionV1 { + constructor(attributes: { + liabilities: Liabilities; + ext: AccountEntryExtensionV1Ext; + }); + + liabilities(value?: Liabilities): Liabilities; + + ext(value?: AccountEntryExtensionV1Ext): AccountEntryExtensionV1Ext; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountEntryExtensionV1; + + static write(value: AccountEntryExtensionV1, io: Buffer): void; + + static isValid(value: AccountEntryExtensionV1): boolean; + + static toXDR(value: AccountEntryExtensionV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountEntryExtensionV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): AccountEntryExtensionV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountEntry { + constructor(attributes: { + accountId: AccountId; + balance: Int64; + seqNum: SequenceNumber; + numSubEntries: number; + inflationDest: null | AccountId; + flags: number; + homeDomain: string | Buffer; + thresholds: Buffer; + signers: Signer[]; + ext: AccountEntryExt; + }); + + accountId(value?: AccountId): AccountId; + + balance(value?: Int64): Int64; + + seqNum(value?: SequenceNumber): SequenceNumber; + + numSubEntries(value?: number): number; + + inflationDest(value?: null | AccountId): null | AccountId; + + flags(value?: number): number; + + homeDomain(value?: string | Buffer): string | Buffer; + + thresholds(value?: Buffer): Buffer; + + signers(value?: Signer[]): Signer[]; + + ext(value?: AccountEntryExt): AccountEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountEntry; + + static write(value: AccountEntry, io: Buffer): void; + + static isValid(value: AccountEntry): boolean; + + static toXDR(value: AccountEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): AccountEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TrustLineEntryExtensionV2 { + constructor(attributes: { + liquidityPoolUseCount: number; + ext: TrustLineEntryExtensionV2Ext; + }); + + liquidityPoolUseCount(value?: number): number; + + ext(value?: TrustLineEntryExtensionV2Ext): TrustLineEntryExtensionV2Ext; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TrustLineEntryExtensionV2; + + static write(value: TrustLineEntryExtensionV2, io: Buffer): void; + + static isValid(value: TrustLineEntryExtensionV2): boolean; + + static toXDR(value: TrustLineEntryExtensionV2): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TrustLineEntryExtensionV2; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TrustLineEntryExtensionV2; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TrustLineEntryV1 { + constructor(attributes: { + liabilities: Liabilities; + ext: TrustLineEntryV1Ext; + }); + + liabilities(value?: Liabilities): Liabilities; + + ext(value?: TrustLineEntryV1Ext): TrustLineEntryV1Ext; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TrustLineEntryV1; + + static write(value: TrustLineEntryV1, io: Buffer): void; + + static isValid(value: TrustLineEntryV1): boolean; + + static toXDR(value: TrustLineEntryV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TrustLineEntryV1; + + static fromXDR(input: string, format: 'hex' | 'base64'): TrustLineEntryV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TrustLineEntry { + constructor(attributes: { + accountId: AccountId; + asset: TrustLineAsset; + balance: Int64; + limit: Int64; + flags: number; + ext: TrustLineEntryExt; + }); + + accountId(value?: AccountId): AccountId; + + asset(value?: TrustLineAsset): TrustLineAsset; + + balance(value?: Int64): Int64; + + limit(value?: Int64): Int64; + + flags(value?: number): number; + + ext(value?: TrustLineEntryExt): TrustLineEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TrustLineEntry; + + static write(value: TrustLineEntry, io: Buffer): void; + + static isValid(value: TrustLineEntry): boolean; + + static toXDR(value: TrustLineEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TrustLineEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): TrustLineEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class OfferEntry { + constructor(attributes: { + sellerId: AccountId; + offerId: Int64; + selling: Asset; + buying: Asset; + amount: Int64; + price: Price; + flags: number; + ext: OfferEntryExt; + }); + + sellerId(value?: AccountId): AccountId; + + offerId(value?: Int64): Int64; + + selling(value?: Asset): Asset; + + buying(value?: Asset): Asset; + + amount(value?: Int64): Int64; + + price(value?: Price): Price; + + flags(value?: number): number; + + ext(value?: OfferEntryExt): OfferEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): OfferEntry; + + static write(value: OfferEntry, io: Buffer): void; + + static isValid(value: OfferEntry): boolean; + + static toXDR(value: OfferEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): OfferEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): OfferEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class DataEntry { + constructor(attributes: { + accountId: AccountId; + dataName: string | Buffer; + dataValue: Buffer; + ext: DataEntryExt; + }); + + accountId(value?: AccountId): AccountId; + + dataName(value?: string | Buffer): string | Buffer; + + dataValue(value?: Buffer): Buffer; + + ext(value?: DataEntryExt): DataEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): DataEntry; + + static write(value: DataEntry, io: Buffer): void; + + static isValid(value: DataEntry): boolean; + + static toXDR(value: DataEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): DataEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): DataEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimantV0 { + constructor(attributes: { + destination: AccountId; + predicate: ClaimPredicate; + }); + + destination(value?: AccountId): AccountId; + + predicate(value?: ClaimPredicate): ClaimPredicate; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimantV0; + + static write(value: ClaimantV0, io: Buffer): void; + + static isValid(value: ClaimantV0): boolean; + + static toXDR(value: ClaimantV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimantV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClaimantV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimableBalanceEntryExtensionV1 { + constructor(attributes: { + ext: ClaimableBalanceEntryExtensionV1Ext; + flags: number; + }); + + ext( + value?: ClaimableBalanceEntryExtensionV1Ext, + ): ClaimableBalanceEntryExtensionV1Ext; + + flags(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimableBalanceEntryExtensionV1; + + static write(value: ClaimableBalanceEntryExtensionV1, io: Buffer): void; + + static isValid(value: ClaimableBalanceEntryExtensionV1): boolean; + + static toXDR(value: ClaimableBalanceEntryExtensionV1): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ClaimableBalanceEntryExtensionV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClaimableBalanceEntryExtensionV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimableBalanceEntry { + constructor(attributes: { + balanceId: ClaimableBalanceId; + claimants: Claimant[]; + asset: Asset; + amount: Int64; + ext: ClaimableBalanceEntryExt; + }); + + balanceId(value?: ClaimableBalanceId): ClaimableBalanceId; + + claimants(value?: Claimant[]): Claimant[]; + + asset(value?: Asset): Asset; + + amount(value?: Int64): Int64; + + ext(value?: ClaimableBalanceEntryExt): ClaimableBalanceEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimableBalanceEntry; + + static write(value: ClaimableBalanceEntry, io: Buffer): void; + + static isValid(value: ClaimableBalanceEntry): boolean; + + static toXDR(value: ClaimableBalanceEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimableBalanceEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClaimableBalanceEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolConstantProductParameters { + constructor(attributes: { assetA: Asset; assetB: Asset; fee: number }); + + assetA(value?: Asset): Asset; + + assetB(value?: Asset): Asset; + + fee(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolConstantProductParameters; + + static write( + value: LiquidityPoolConstantProductParameters, + io: Buffer, + ): void; + + static isValid(value: LiquidityPoolConstantProductParameters): boolean; + + static toXDR(value: LiquidityPoolConstantProductParameters): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): LiquidityPoolConstantProductParameters; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolConstantProductParameters; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolEntryConstantProduct { + constructor(attributes: { + params: LiquidityPoolConstantProductParameters; + reserveA: Int64; + reserveB: Int64; + totalPoolShares: Int64; + poolSharesTrustLineCount: Int64; + }); + + params( + value?: LiquidityPoolConstantProductParameters, + ): LiquidityPoolConstantProductParameters; + + reserveA(value?: Int64): Int64; + + reserveB(value?: Int64): Int64; + + totalPoolShares(value?: Int64): Int64; + + poolSharesTrustLineCount(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolEntryConstantProduct; + + static write(value: LiquidityPoolEntryConstantProduct, io: Buffer): void; + + static isValid(value: LiquidityPoolEntryConstantProduct): boolean; + + static toXDR(value: LiquidityPoolEntryConstantProduct): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): LiquidityPoolEntryConstantProduct; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolEntryConstantProduct; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolEntry { + constructor(attributes: { + liquidityPoolId: PoolId; + body: LiquidityPoolEntryBody; + }); + + liquidityPoolId(value?: PoolId): PoolId; + + body(value?: LiquidityPoolEntryBody): LiquidityPoolEntryBody; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolEntry; + + static write(value: LiquidityPoolEntry, io: Buffer): void; + + static isValid(value: LiquidityPoolEntry): boolean; + + static toXDR(value: LiquidityPoolEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LiquidityPoolEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): LiquidityPoolEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractDataEntry { + constructor(attributes: { + ext: ExtensionPoint; + contract: ScAddress; + key: ScVal; + durability: ContractDataDurability; + val: ScVal; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + contract(value?: ScAddress): ScAddress; + + key(value?: ScVal): ScVal; + + durability(value?: ContractDataDurability): ContractDataDurability; + + val(value?: ScVal): ScVal; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractDataEntry; + + static write(value: ContractDataEntry, io: Buffer): void; + + static isValid(value: ContractDataEntry): boolean; + + static toXDR(value: ContractDataEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractDataEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ContractDataEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractCodeCostInputs { + constructor(attributes: { + ext: ExtensionPoint; + nInstructions: number; + nFunctions: number; + nGlobals: number; + nTableEntries: number; + nTypes: number; + nDataSegments: number; + nElemSegments: number; + nImports: number; + nExports: number; + nDataSegmentBytes: number; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + nInstructions(value?: number): number; + + nFunctions(value?: number): number; + + nGlobals(value?: number): number; + + nTableEntries(value?: number): number; + + nTypes(value?: number): number; + + nDataSegments(value?: number): number; + + nElemSegments(value?: number): number; + + nImports(value?: number): number; + + nExports(value?: number): number; + + nDataSegmentBytes(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractCodeCostInputs; + + static write(value: ContractCodeCostInputs, io: Buffer): void; + + static isValid(value: ContractCodeCostInputs): boolean; + + static toXDR(value: ContractCodeCostInputs): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractCodeCostInputs; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ContractCodeCostInputs; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractCodeEntryV1 { + constructor(attributes: { + ext: ExtensionPoint; + costInputs: ContractCodeCostInputs; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + costInputs(value?: ContractCodeCostInputs): ContractCodeCostInputs; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractCodeEntryV1; + + static write(value: ContractCodeEntryV1, io: Buffer): void; + + static isValid(value: ContractCodeEntryV1): boolean; + + static toXDR(value: ContractCodeEntryV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractCodeEntryV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ContractCodeEntryV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractCodeEntry { + constructor(attributes: { + ext: ContractCodeEntryExt; + hash: Buffer; + code: Buffer; + }); + + ext(value?: ContractCodeEntryExt): ContractCodeEntryExt; + + hash(value?: Buffer): Buffer; + + code(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractCodeEntry; + + static write(value: ContractCodeEntry, io: Buffer): void; + + static isValid(value: ContractCodeEntry): boolean; + + static toXDR(value: ContractCodeEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractCodeEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ContractCodeEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TtlEntry { + constructor(attributes: { keyHash: Buffer; liveUntilLedgerSeq: number }); + + keyHash(value?: Buffer): Buffer; + + liveUntilLedgerSeq(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TtlEntry; + + static write(value: TtlEntry, io: Buffer): void; + + static isValid(value: TtlEntry): boolean; + + static toXDR(value: TtlEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TtlEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): TtlEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerEntryExtensionV1 { + constructor(attributes: { + sponsoringId: SponsorshipDescriptor; + ext: LedgerEntryExtensionV1Ext; + }); + + sponsoringId(value?: SponsorshipDescriptor): SponsorshipDescriptor; + + ext(value?: LedgerEntryExtensionV1Ext): LedgerEntryExtensionV1Ext; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerEntryExtensionV1; + + static write(value: LedgerEntryExtensionV1, io: Buffer): void; + + static isValid(value: LedgerEntryExtensionV1): boolean; + + static toXDR(value: LedgerEntryExtensionV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerEntryExtensionV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerEntryExtensionV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerEntry { + constructor(attributes: { + lastModifiedLedgerSeq: number; + data: LedgerEntryData; + ext: LedgerEntryExt; + }); + + lastModifiedLedgerSeq(value?: number): number; + + data(value?: LedgerEntryData): LedgerEntryData; + + ext(value?: LedgerEntryExt): LedgerEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerEntry; + + static write(value: LedgerEntry, io: Buffer): void; + + static isValid(value: LedgerEntry): boolean; + + static toXDR(value: LedgerEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyAccount { + constructor(attributes: { accountId: AccountId }); + + accountId(value?: AccountId): AccountId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyAccount; + + static write(value: LedgerKeyAccount, io: Buffer): void; + + static isValid(value: LedgerKeyAccount): boolean; + + static toXDR(value: LedgerKeyAccount): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyAccount; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerKeyAccount; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyTrustLine { + constructor(attributes: { accountId: AccountId; asset: TrustLineAsset }); + + accountId(value?: AccountId): AccountId; + + asset(value?: TrustLineAsset): TrustLineAsset; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyTrustLine; + + static write(value: LedgerKeyTrustLine, io: Buffer): void; + + static isValid(value: LedgerKeyTrustLine): boolean; + + static toXDR(value: LedgerKeyTrustLine): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyTrustLine; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerKeyTrustLine; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyOffer { + constructor(attributes: { sellerId: AccountId; offerId: Int64 }); + + sellerId(value?: AccountId): AccountId; + + offerId(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyOffer; + + static write(value: LedgerKeyOffer, io: Buffer): void; + + static isValid(value: LedgerKeyOffer): boolean; + + static toXDR(value: LedgerKeyOffer): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyOffer; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerKeyOffer; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyData { + constructor(attributes: { + accountId: AccountId; + dataName: string | Buffer; + }); + + accountId(value?: AccountId): AccountId; + + dataName(value?: string | Buffer): string | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyData; + + static write(value: LedgerKeyData, io: Buffer): void; + + static isValid(value: LedgerKeyData): boolean; + + static toXDR(value: LedgerKeyData): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyData; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerKeyData; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyClaimableBalance { + constructor(attributes: { balanceId: ClaimableBalanceId }); + + balanceId(value?: ClaimableBalanceId): ClaimableBalanceId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyClaimableBalance; + + static write(value: LedgerKeyClaimableBalance, io: Buffer): void; + + static isValid(value: LedgerKeyClaimableBalance): boolean; + + static toXDR(value: LedgerKeyClaimableBalance): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyClaimableBalance; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerKeyClaimableBalance; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyLiquidityPool { + constructor(attributes: { liquidityPoolId: PoolId }); + + liquidityPoolId(value?: PoolId): PoolId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyLiquidityPool; + + static write(value: LedgerKeyLiquidityPool, io: Buffer): void; + + static isValid(value: LedgerKeyLiquidityPool): boolean; + + static toXDR(value: LedgerKeyLiquidityPool): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyLiquidityPool; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerKeyLiquidityPool; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyContractData { + constructor(attributes: { + contract: ScAddress; + key: ScVal; + durability: ContractDataDurability; + }); + + contract(value?: ScAddress): ScAddress; + + key(value?: ScVal): ScVal; + + durability(value?: ContractDataDurability): ContractDataDurability; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyContractData; + + static write(value: LedgerKeyContractData, io: Buffer): void; + + static isValid(value: LedgerKeyContractData): boolean; + + static toXDR(value: LedgerKeyContractData): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyContractData; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerKeyContractData; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyContractCode { + constructor(attributes: { hash: Buffer }); + + hash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyContractCode; + + static write(value: LedgerKeyContractCode, io: Buffer): void; + + static isValid(value: LedgerKeyContractCode): boolean; + + static toXDR(value: LedgerKeyContractCode): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyContractCode; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerKeyContractCode; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyConfigSetting { + constructor(attributes: { configSettingId: ConfigSettingId }); + + configSettingId(value?: ConfigSettingId): ConfigSettingId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyConfigSetting; + + static write(value: LedgerKeyConfigSetting, io: Buffer): void; + + static isValid(value: LedgerKeyConfigSetting): boolean; + + static toXDR(value: LedgerKeyConfigSetting): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyConfigSetting; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerKeyConfigSetting; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKeyTtl { + constructor(attributes: { keyHash: Buffer }); + + keyHash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKeyTtl; + + static write(value: LedgerKeyTtl, io: Buffer): void; + + static isValid(value: LedgerKeyTtl): boolean; + + static toXDR(value: LedgerKeyTtl): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKeyTtl; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerKeyTtl; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class BucketMetadata { + constructor(attributes: { ledgerVersion: number; ext: BucketMetadataExt }); + + ledgerVersion(value?: number): number; + + ext(value?: BucketMetadataExt): BucketMetadataExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): BucketMetadata; + + static write(value: BucketMetadata, io: Buffer): void; + + static isValid(value: BucketMetadata): boolean; + + static toXDR(value: BucketMetadata): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): BucketMetadata; + + static fromXDR(input: string, format: 'hex' | 'base64'): BucketMetadata; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ColdArchiveArchivedLeaf { + constructor(attributes: { index: number; archivedEntry: LedgerEntry }); + + index(value?: number): number; + + archivedEntry(value?: LedgerEntry): LedgerEntry; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ColdArchiveArchivedLeaf; + + static write(value: ColdArchiveArchivedLeaf, io: Buffer): void; + + static isValid(value: ColdArchiveArchivedLeaf): boolean; + + static toXDR(value: ColdArchiveArchivedLeaf): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ColdArchiveArchivedLeaf; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ColdArchiveArchivedLeaf; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ColdArchiveDeletedLeaf { + constructor(attributes: { index: number; deletedKey: LedgerKey }); + + index(value?: number): number; + + deletedKey(value?: LedgerKey): LedgerKey; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ColdArchiveDeletedLeaf; + + static write(value: ColdArchiveDeletedLeaf, io: Buffer): void; + + static isValid(value: ColdArchiveDeletedLeaf): boolean; + + static toXDR(value: ColdArchiveDeletedLeaf): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ColdArchiveDeletedLeaf; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ColdArchiveDeletedLeaf; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ColdArchiveBoundaryLeaf { + constructor(attributes: { index: number; isLowerBound: boolean }); + + index(value?: number): number; + + isLowerBound(value?: boolean): boolean; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ColdArchiveBoundaryLeaf; + + static write(value: ColdArchiveBoundaryLeaf, io: Buffer): void; + + static isValid(value: ColdArchiveBoundaryLeaf): boolean; + + static toXDR(value: ColdArchiveBoundaryLeaf): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ColdArchiveBoundaryLeaf; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ColdArchiveBoundaryLeaf; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ColdArchiveHashEntry { + constructor(attributes: { index: number; level: number; hash: Buffer }); + + index(value?: number): number; + + level(value?: number): number; + + hash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ColdArchiveHashEntry; + + static write(value: ColdArchiveHashEntry, io: Buffer): void; + + static isValid(value: ColdArchiveHashEntry): boolean; + + static toXDR(value: ColdArchiveHashEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ColdArchiveHashEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ColdArchiveHashEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerCloseValueSignature { + constructor(attributes: { nodeId: NodeId; signature: Buffer }); + + nodeId(value?: NodeId): NodeId; + + signature(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerCloseValueSignature; + + static write(value: LedgerCloseValueSignature, io: Buffer): void; + + static isValid(value: LedgerCloseValueSignature): boolean; + + static toXDR(value: LedgerCloseValueSignature): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerCloseValueSignature; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerCloseValueSignature; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class StellarValue { + constructor(attributes: { + txSetHash: Buffer; + closeTime: TimePoint; + upgrades: Buffer[]; + ext: StellarValueExt; + }); + + txSetHash(value?: Buffer): Buffer; + + closeTime(value?: TimePoint): TimePoint; + + upgrades(value?: Buffer[]): Buffer[]; + + ext(value?: StellarValueExt): StellarValueExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): StellarValue; + + static write(value: StellarValue, io: Buffer): void; + + static isValid(value: StellarValue): boolean; + + static toXDR(value: StellarValue): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): StellarValue; + + static fromXDR(input: string, format: 'hex' | 'base64'): StellarValue; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerHeaderExtensionV1 { + constructor(attributes: { flags: number; ext: LedgerHeaderExtensionV1Ext }); + + flags(value?: number): number; + + ext(value?: LedgerHeaderExtensionV1Ext): LedgerHeaderExtensionV1Ext; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerHeaderExtensionV1; + + static write(value: LedgerHeaderExtensionV1, io: Buffer): void; + + static isValid(value: LedgerHeaderExtensionV1): boolean; + + static toXDR(value: LedgerHeaderExtensionV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerHeaderExtensionV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerHeaderExtensionV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerHeader { + constructor(attributes: { + ledgerVersion: number; + previousLedgerHash: Buffer; + scpValue: StellarValue; + txSetResultHash: Buffer; + bucketListHash: Buffer; + ledgerSeq: number; + totalCoins: Int64; + feePool: Int64; + inflationSeq: number; + idPool: Uint64; + baseFee: number; + baseReserve: number; + maxTxSetSize: number; + skipList: Buffer[]; + ext: LedgerHeaderExt; + }); + + ledgerVersion(value?: number): number; + + previousLedgerHash(value?: Buffer): Buffer; + + scpValue(value?: StellarValue): StellarValue; + + txSetResultHash(value?: Buffer): Buffer; + + bucketListHash(value?: Buffer): Buffer; + + ledgerSeq(value?: number): number; + + totalCoins(value?: Int64): Int64; + + feePool(value?: Int64): Int64; + + inflationSeq(value?: number): number; + + idPool(value?: Uint64): Uint64; + + baseFee(value?: number): number; + + baseReserve(value?: number): number; + + maxTxSetSize(value?: number): number; + + skipList(value?: Buffer[]): Buffer[]; + + ext(value?: LedgerHeaderExt): LedgerHeaderExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerHeader; + + static write(value: LedgerHeader, io: Buffer): void; + + static isValid(value: LedgerHeader): boolean; + + static toXDR(value: LedgerHeader): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerHeader; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerHeader; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigUpgradeSetKey { + constructor(attributes: { contractId: Buffer; contentHash: Buffer }); + + contractId(value?: Buffer): Buffer; + + contentHash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigUpgradeSetKey; + + static write(value: ConfigUpgradeSetKey, io: Buffer): void; + + static isValid(value: ConfigUpgradeSetKey): boolean; + + static toXDR(value: ConfigUpgradeSetKey): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ConfigUpgradeSetKey; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigUpgradeSetKey; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigUpgradeSet { + constructor(attributes: { updatedEntry: ConfigSettingEntry[] }); + + updatedEntry(value?: ConfigSettingEntry[]): ConfigSettingEntry[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigUpgradeSet; + + static write(value: ConfigUpgradeSet, io: Buffer): void; + + static isValid(value: ConfigUpgradeSet): boolean; + + static toXDR(value: ConfigUpgradeSet): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ConfigUpgradeSet; + + static fromXDR(input: string, format: 'hex' | 'base64'): ConfigUpgradeSet; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ParallelTxsComponent { + constructor(attributes: { + baseFee: null | Int64; + executionStages: TransactionEnvelope[][][]; + }); + + baseFee(value?: null | Int64): null | Int64; + + executionStages( + value?: TransactionEnvelope[][][], + ): TransactionEnvelope[][][]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ParallelTxsComponent; + + static write(value: ParallelTxsComponent, io: Buffer): void; + + static isValid(value: ParallelTxsComponent): boolean; + + static toXDR(value: ParallelTxsComponent): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ParallelTxsComponent; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ParallelTxsComponent; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TxSetComponentTxsMaybeDiscountedFee { + constructor(attributes: { + baseFee: null | Int64; + txes: TransactionEnvelope[]; + }); + + baseFee(value?: null | Int64): null | Int64; + + txes(value?: TransactionEnvelope[]): TransactionEnvelope[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TxSetComponentTxsMaybeDiscountedFee; + + static write(value: TxSetComponentTxsMaybeDiscountedFee, io: Buffer): void; + + static isValid(value: TxSetComponentTxsMaybeDiscountedFee): boolean; + + static toXDR(value: TxSetComponentTxsMaybeDiscountedFee): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TxSetComponentTxsMaybeDiscountedFee; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TxSetComponentTxsMaybeDiscountedFee; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionSet { + constructor(attributes: { + previousLedgerHash: Buffer; + txes: TransactionEnvelope[]; + }); + + previousLedgerHash(value?: Buffer): Buffer; + + txes(value?: TransactionEnvelope[]): TransactionEnvelope[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionSet; + + static write(value: TransactionSet, io: Buffer): void; + + static isValid(value: TransactionSet): boolean; + + static toXDR(value: TransactionSet): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionSet; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionSet; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionSetV1 { + constructor(attributes: { + previousLedgerHash: Buffer; + phases: TransactionPhase[]; + }); + + previousLedgerHash(value?: Buffer): Buffer; + + phases(value?: TransactionPhase[]): TransactionPhase[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionSetV1; + + static write(value: TransactionSetV1, io: Buffer): void; + + static isValid(value: TransactionSetV1): boolean; + + static toXDR(value: TransactionSetV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionSetV1; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionSetV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionResultPair { + constructor(attributes: { + transactionHash: Buffer; + result: TransactionResult; + }); + + transactionHash(value?: Buffer): Buffer; + + result(value?: TransactionResult): TransactionResult; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionResultPair; + + static write(value: TransactionResultPair, io: Buffer): void; + + static isValid(value: TransactionResultPair): boolean; + + static toXDR(value: TransactionResultPair): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionResultPair; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionResultPair; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionResultSet { + constructor(attributes: { results: TransactionResultPair[] }); + + results(value?: TransactionResultPair[]): TransactionResultPair[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionResultSet; + + static write(value: TransactionResultSet, io: Buffer): void; + + static isValid(value: TransactionResultSet): boolean; + + static toXDR(value: TransactionResultSet): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionResultSet; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionResultSet; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionHistoryEntry { + constructor(attributes: { + ledgerSeq: number; + txSet: TransactionSet; + ext: TransactionHistoryEntryExt; + }); + + ledgerSeq(value?: number): number; + + txSet(value?: TransactionSet): TransactionSet; + + ext(value?: TransactionHistoryEntryExt): TransactionHistoryEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionHistoryEntry; + + static write(value: TransactionHistoryEntry, io: Buffer): void; + + static isValid(value: TransactionHistoryEntry): boolean; + + static toXDR(value: TransactionHistoryEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionHistoryEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionHistoryEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionHistoryResultEntry { + constructor(attributes: { + ledgerSeq: number; + txResultSet: TransactionResultSet; + ext: TransactionHistoryResultEntryExt; + }); + + ledgerSeq(value?: number): number; + + txResultSet(value?: TransactionResultSet): TransactionResultSet; + + ext( + value?: TransactionHistoryResultEntryExt, + ): TransactionHistoryResultEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionHistoryResultEntry; + + static write(value: TransactionHistoryResultEntry, io: Buffer): void; + + static isValid(value: TransactionHistoryResultEntry): boolean; + + static toXDR(value: TransactionHistoryResultEntry): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TransactionHistoryResultEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionHistoryResultEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerHeaderHistoryEntry { + constructor(attributes: { + hash: Buffer; + header: LedgerHeader; + ext: LedgerHeaderHistoryEntryExt; + }); + + hash(value?: Buffer): Buffer; + + header(value?: LedgerHeader): LedgerHeader; + + ext(value?: LedgerHeaderHistoryEntryExt): LedgerHeaderHistoryEntryExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerHeaderHistoryEntry; + + static write(value: LedgerHeaderHistoryEntry, io: Buffer): void; + + static isValid(value: LedgerHeaderHistoryEntry): boolean; + + static toXDR(value: LedgerHeaderHistoryEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerHeaderHistoryEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerHeaderHistoryEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerScpMessages { + constructor(attributes: { ledgerSeq: number; messages: ScpEnvelope[] }); + + ledgerSeq(value?: number): number; + + messages(value?: ScpEnvelope[]): ScpEnvelope[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerScpMessages; + + static write(value: LedgerScpMessages, io: Buffer): void; + + static isValid(value: LedgerScpMessages): boolean; + + static toXDR(value: LedgerScpMessages): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerScpMessages; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerScpMessages; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpHistoryEntryV0 { + constructor(attributes: { + quorumSets: ScpQuorumSet[]; + ledgerMessages: LedgerScpMessages; + }); + + quorumSets(value?: ScpQuorumSet[]): ScpQuorumSet[]; + + ledgerMessages(value?: LedgerScpMessages): LedgerScpMessages; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpHistoryEntryV0; + + static write(value: ScpHistoryEntryV0, io: Buffer): void; + + static isValid(value: ScpHistoryEntryV0): boolean; + + static toXDR(value: ScpHistoryEntryV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpHistoryEntryV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScpHistoryEntryV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class OperationMeta { + constructor(attributes: { changes: LedgerEntryChange[] }); + + changes(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): OperationMeta; + + static write(value: OperationMeta, io: Buffer): void; + + static isValid(value: OperationMeta): boolean; + + static toXDR(value: OperationMeta): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): OperationMeta; + + static fromXDR(input: string, format: 'hex' | 'base64'): OperationMeta; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionMetaV1 { + constructor(attributes: { + txChanges: LedgerEntryChange[]; + operations: OperationMeta[]; + }); + + txChanges(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + operations(value?: OperationMeta[]): OperationMeta[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionMetaV1; + + static write(value: TransactionMetaV1, io: Buffer): void; + + static isValid(value: TransactionMetaV1): boolean; + + static toXDR(value: TransactionMetaV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionMetaV1; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionMetaV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionMetaV2 { + constructor(attributes: { + txChangesBefore: LedgerEntryChange[]; + operations: OperationMeta[]; + txChangesAfter: LedgerEntryChange[]; + }); + + txChangesBefore(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + operations(value?: OperationMeta[]): OperationMeta[]; + + txChangesAfter(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionMetaV2; + + static write(value: TransactionMetaV2, io: Buffer): void; + + static isValid(value: TransactionMetaV2): boolean; + + static toXDR(value: TransactionMetaV2): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionMetaV2; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionMetaV2; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractEventV0 { + constructor(attributes: { topics: ScVal[]; data: ScVal }); + + topics(value?: ScVal[]): ScVal[]; + + data(value?: ScVal): ScVal; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractEventV0; + + static write(value: ContractEventV0, io: Buffer): void; + + static isValid(value: ContractEventV0): boolean; + + static toXDR(value: ContractEventV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractEventV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ContractEventV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractEvent { + constructor(attributes: { + ext: ExtensionPoint; + contractId: null | Buffer; + type: ContractEventType; + body: ContractEventBody; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + contractId(value?: null | Buffer): null | Buffer; + + type(value?: ContractEventType): ContractEventType; + + body(value?: ContractEventBody): ContractEventBody; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractEvent; + + static write(value: ContractEvent, io: Buffer): void; + + static isValid(value: ContractEvent): boolean; + + static toXDR(value: ContractEvent): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractEvent; + + static fromXDR(input: string, format: 'hex' | 'base64'): ContractEvent; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class DiagnosticEvent { + constructor(attributes: { + inSuccessfulContractCall: boolean; + event: ContractEvent; + }); + + inSuccessfulContractCall(value?: boolean): boolean; + + event(value?: ContractEvent): ContractEvent; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): DiagnosticEvent; + + static write(value: DiagnosticEvent, io: Buffer): void; + + static isValid(value: DiagnosticEvent): boolean; + + static toXDR(value: DiagnosticEvent): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): DiagnosticEvent; + + static fromXDR(input: string, format: 'hex' | 'base64'): DiagnosticEvent; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanTransactionMetaExtV1 { + constructor(attributes: { + ext: ExtensionPoint; + totalNonRefundableResourceFeeCharged: Int64; + totalRefundableResourceFeeCharged: Int64; + rentFeeCharged: Int64; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + totalNonRefundableResourceFeeCharged(value?: Int64): Int64; + + totalRefundableResourceFeeCharged(value?: Int64): Int64; + + rentFeeCharged(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanTransactionMetaExtV1; + + static write(value: SorobanTransactionMetaExtV1, io: Buffer): void; + + static isValid(value: SorobanTransactionMetaExtV1): boolean; + + static toXDR(value: SorobanTransactionMetaExtV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanTransactionMetaExtV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanTransactionMetaExtV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanTransactionMeta { + constructor(attributes: { + ext: SorobanTransactionMetaExt; + events: ContractEvent[]; + returnValue: ScVal; + diagnosticEvents: DiagnosticEvent[]; + }); + + ext(value?: SorobanTransactionMetaExt): SorobanTransactionMetaExt; + + events(value?: ContractEvent[]): ContractEvent[]; + + returnValue(value?: ScVal): ScVal; + + diagnosticEvents(value?: DiagnosticEvent[]): DiagnosticEvent[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanTransactionMeta; + + static write(value: SorobanTransactionMeta, io: Buffer): void; + + static isValid(value: SorobanTransactionMeta): boolean; + + static toXDR(value: SorobanTransactionMeta): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanTransactionMeta; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanTransactionMeta; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionMetaV3 { + constructor(attributes: { + ext: ExtensionPoint; + txChangesBefore: LedgerEntryChange[]; + operations: OperationMeta[]; + txChangesAfter: LedgerEntryChange[]; + sorobanMeta: null | SorobanTransactionMeta; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + txChangesBefore(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + operations(value?: OperationMeta[]): OperationMeta[]; + + txChangesAfter(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + sorobanMeta( + value?: null | SorobanTransactionMeta, + ): null | SorobanTransactionMeta; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionMetaV3; + + static write(value: TransactionMetaV3, io: Buffer): void; + + static isValid(value: TransactionMetaV3): boolean; + + static toXDR(value: TransactionMetaV3): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionMetaV3; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionMetaV3; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InvokeHostFunctionSuccessPreImage { + constructor(attributes: { returnValue: ScVal; events: ContractEvent[] }); + + returnValue(value?: ScVal): ScVal; + + events(value?: ContractEvent[]): ContractEvent[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InvokeHostFunctionSuccessPreImage; + + static write(value: InvokeHostFunctionSuccessPreImage, io: Buffer): void; + + static isValid(value: InvokeHostFunctionSuccessPreImage): boolean; + + static toXDR(value: InvokeHostFunctionSuccessPreImage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): InvokeHostFunctionSuccessPreImage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): InvokeHostFunctionSuccessPreImage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionResultMeta { + constructor(attributes: { + result: TransactionResultPair; + feeProcessing: LedgerEntryChange[]; + txApplyProcessing: TransactionMeta; + }); + + result(value?: TransactionResultPair): TransactionResultPair; + + feeProcessing(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + txApplyProcessing(value?: TransactionMeta): TransactionMeta; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionResultMeta; + + static write(value: TransactionResultMeta, io: Buffer): void; + + static isValid(value: TransactionResultMeta): boolean; + + static toXDR(value: TransactionResultMeta): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionResultMeta; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionResultMeta; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class UpgradeEntryMeta { + constructor(attributes: { + upgrade: LedgerUpgrade; + changes: LedgerEntryChange[]; + }); + + upgrade(value?: LedgerUpgrade): LedgerUpgrade; + + changes(value?: LedgerEntryChange[]): LedgerEntryChange[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): UpgradeEntryMeta; + + static write(value: UpgradeEntryMeta, io: Buffer): void; + + static isValid(value: UpgradeEntryMeta): boolean; + + static toXDR(value: UpgradeEntryMeta): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): UpgradeEntryMeta; + + static fromXDR(input: string, format: 'hex' | 'base64'): UpgradeEntryMeta; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerCloseMetaV0 { + constructor(attributes: { + ledgerHeader: LedgerHeaderHistoryEntry; + txSet: TransactionSet; + txProcessing: TransactionResultMeta[]; + upgradesProcessing: UpgradeEntryMeta[]; + scpInfo: ScpHistoryEntry[]; + }); + + ledgerHeader(value?: LedgerHeaderHistoryEntry): LedgerHeaderHistoryEntry; + + txSet(value?: TransactionSet): TransactionSet; + + txProcessing(value?: TransactionResultMeta[]): TransactionResultMeta[]; + + upgradesProcessing(value?: UpgradeEntryMeta[]): UpgradeEntryMeta[]; + + scpInfo(value?: ScpHistoryEntry[]): ScpHistoryEntry[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerCloseMetaV0; + + static write(value: LedgerCloseMetaV0, io: Buffer): void; + + static isValid(value: LedgerCloseMetaV0): boolean; + + static toXDR(value: LedgerCloseMetaV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerCloseMetaV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerCloseMetaV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerCloseMetaExtV1 { + constructor(attributes: { ext: ExtensionPoint; sorobanFeeWrite1Kb: Int64 }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + sorobanFeeWrite1Kb(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerCloseMetaExtV1; + + static write(value: LedgerCloseMetaExtV1, io: Buffer): void; + + static isValid(value: LedgerCloseMetaExtV1): boolean; + + static toXDR(value: LedgerCloseMetaExtV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerCloseMetaExtV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerCloseMetaExtV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerCloseMetaV1 { + constructor(attributes: { + ext: LedgerCloseMetaExt; + ledgerHeader: LedgerHeaderHistoryEntry; + txSet: GeneralizedTransactionSet; + txProcessing: TransactionResultMeta[]; + upgradesProcessing: UpgradeEntryMeta[]; + scpInfo: ScpHistoryEntry[]; + totalByteSizeOfBucketList: Uint64; + evictedTemporaryLedgerKeys: LedgerKey[]; + evictedPersistentLedgerEntries: LedgerEntry[]; + }); + + ext(value?: LedgerCloseMetaExt): LedgerCloseMetaExt; + + ledgerHeader(value?: LedgerHeaderHistoryEntry): LedgerHeaderHistoryEntry; + + txSet(value?: GeneralizedTransactionSet): GeneralizedTransactionSet; + + txProcessing(value?: TransactionResultMeta[]): TransactionResultMeta[]; + + upgradesProcessing(value?: UpgradeEntryMeta[]): UpgradeEntryMeta[]; + + scpInfo(value?: ScpHistoryEntry[]): ScpHistoryEntry[]; + + totalByteSizeOfBucketList(value?: Uint64): Uint64; + + evictedTemporaryLedgerKeys(value?: LedgerKey[]): LedgerKey[]; + + evictedPersistentLedgerEntries(value?: LedgerEntry[]): LedgerEntry[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerCloseMetaV1; + + static write(value: LedgerCloseMetaV1, io: Buffer): void; + + static isValid(value: LedgerCloseMetaV1): boolean; + + static toXDR(value: LedgerCloseMetaV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerCloseMetaV1; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerCloseMetaV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Error { + constructor(attributes: { code: ErrorCode; msg: string | Buffer }); + + code(value?: ErrorCode): ErrorCode; + + msg(value?: string | Buffer): string | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Error; + + static write(value: Error, io: Buffer): void; + + static isValid(value: Error): boolean; + + static toXDR(value: Error): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Error; + + static fromXDR(input: string, format: 'hex' | 'base64'): Error; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SendMore { + constructor(attributes: { numMessages: number }); + + numMessages(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SendMore; + + static write(value: SendMore, io: Buffer): void; + + static isValid(value: SendMore): boolean; + + static toXDR(value: SendMore): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SendMore; + + static fromXDR(input: string, format: 'hex' | 'base64'): SendMore; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SendMoreExtended { + constructor(attributes: { numMessages: number; numBytes: number }); + + numMessages(value?: number): number; + + numBytes(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SendMoreExtended; + + static write(value: SendMoreExtended, io: Buffer): void; + + static isValid(value: SendMoreExtended): boolean; + + static toXDR(value: SendMoreExtended): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SendMoreExtended; + + static fromXDR(input: string, format: 'hex' | 'base64'): SendMoreExtended; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AuthCert { + constructor(attributes: { + pubkey: Curve25519Public; + expiration: Uint64; + sig: Buffer; + }); + + pubkey(value?: Curve25519Public): Curve25519Public; + + expiration(value?: Uint64): Uint64; + + sig(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AuthCert; + + static write(value: AuthCert, io: Buffer): void; + + static isValid(value: AuthCert): boolean; + + static toXDR(value: AuthCert): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AuthCert; + + static fromXDR(input: string, format: 'hex' | 'base64'): AuthCert; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Hello { + constructor(attributes: { + ledgerVersion: number; + overlayVersion: number; + overlayMinVersion: number; + networkId: Buffer; + versionStr: string | Buffer; + listeningPort: number; + peerId: NodeId; + cert: AuthCert; + nonce: Buffer; + }); + + ledgerVersion(value?: number): number; + + overlayVersion(value?: number): number; + + overlayMinVersion(value?: number): number; + + networkId(value?: Buffer): Buffer; + + versionStr(value?: string | Buffer): string | Buffer; + + listeningPort(value?: number): number; + + peerId(value?: NodeId): NodeId; + + cert(value?: AuthCert): AuthCert; + + nonce(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Hello; + + static write(value: Hello, io: Buffer): void; + + static isValid(value: Hello): boolean; + + static toXDR(value: Hello): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Hello; + + static fromXDR(input: string, format: 'hex' | 'base64'): Hello; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Auth { + constructor(attributes: { flags: number }); + + flags(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Auth; + + static write(value: Auth, io: Buffer): void; + + static isValid(value: Auth): boolean; + + static toXDR(value: Auth): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Auth; + + static fromXDR(input: string, format: 'hex' | 'base64'): Auth; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PeerAddress { + constructor(attributes: { + ip: PeerAddressIp; + port: number; + numFailures: number; + }); + + ip(value?: PeerAddressIp): PeerAddressIp; + + port(value?: number): number; + + numFailures(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PeerAddress; + + static write(value: PeerAddress, io: Buffer): void; + + static isValid(value: PeerAddress): boolean; + + static toXDR(value: PeerAddress): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PeerAddress; + + static fromXDR(input: string, format: 'hex' | 'base64'): PeerAddress; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class DontHave { + constructor(attributes: { type: MessageType; reqHash: Buffer }); + + type(value?: MessageType): MessageType; + + reqHash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): DontHave; + + static write(value: DontHave, io: Buffer): void; + + static isValid(value: DontHave): boolean; + + static toXDR(value: DontHave): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): DontHave; + + static fromXDR(input: string, format: 'hex' | 'base64'): DontHave; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TimeSlicedSurveyStartCollectingMessage { + constructor(attributes: { + surveyorId: NodeId; + nonce: number; + ledgerNum: number; + }); + + surveyorId(value?: NodeId): NodeId; + + nonce(value?: number): number; + + ledgerNum(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TimeSlicedSurveyStartCollectingMessage; + + static write( + value: TimeSlicedSurveyStartCollectingMessage, + io: Buffer, + ): void; + + static isValid(value: TimeSlicedSurveyStartCollectingMessage): boolean; + + static toXDR(value: TimeSlicedSurveyStartCollectingMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TimeSlicedSurveyStartCollectingMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TimeSlicedSurveyStartCollectingMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignedTimeSlicedSurveyStartCollectingMessage { + constructor(attributes: { + signature: Buffer; + startCollecting: TimeSlicedSurveyStartCollectingMessage; + }); + + signature(value?: Buffer): Buffer; + + startCollecting( + value?: TimeSlicedSurveyStartCollectingMessage, + ): TimeSlicedSurveyStartCollectingMessage; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignedTimeSlicedSurveyStartCollectingMessage; + + static write( + value: SignedTimeSlicedSurveyStartCollectingMessage, + io: Buffer, + ): void; + + static isValid( + value: SignedTimeSlicedSurveyStartCollectingMessage, + ): boolean; + + static toXDR(value: SignedTimeSlicedSurveyStartCollectingMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): SignedTimeSlicedSurveyStartCollectingMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SignedTimeSlicedSurveyStartCollectingMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TimeSlicedSurveyStopCollectingMessage { + constructor(attributes: { + surveyorId: NodeId; + nonce: number; + ledgerNum: number; + }); + + surveyorId(value?: NodeId): NodeId; + + nonce(value?: number): number; + + ledgerNum(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TimeSlicedSurveyStopCollectingMessage; + + static write( + value: TimeSlicedSurveyStopCollectingMessage, + io: Buffer, + ): void; + + static isValid(value: TimeSlicedSurveyStopCollectingMessage): boolean; + + static toXDR(value: TimeSlicedSurveyStopCollectingMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TimeSlicedSurveyStopCollectingMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TimeSlicedSurveyStopCollectingMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignedTimeSlicedSurveyStopCollectingMessage { + constructor(attributes: { + signature: Buffer; + stopCollecting: TimeSlicedSurveyStopCollectingMessage; + }); + + signature(value?: Buffer): Buffer; + + stopCollecting( + value?: TimeSlicedSurveyStopCollectingMessage, + ): TimeSlicedSurveyStopCollectingMessage; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignedTimeSlicedSurveyStopCollectingMessage; + + static write( + value: SignedTimeSlicedSurveyStopCollectingMessage, + io: Buffer, + ): void; + + static isValid(value: SignedTimeSlicedSurveyStopCollectingMessage): boolean; + + static toXDR(value: SignedTimeSlicedSurveyStopCollectingMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): SignedTimeSlicedSurveyStopCollectingMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SignedTimeSlicedSurveyStopCollectingMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SurveyRequestMessage { + constructor(attributes: { + surveyorPeerId: NodeId; + surveyedPeerId: NodeId; + ledgerNum: number; + encryptionKey: Curve25519Public; + commandType: SurveyMessageCommandType; + }); + + surveyorPeerId(value?: NodeId): NodeId; + + surveyedPeerId(value?: NodeId): NodeId; + + ledgerNum(value?: number): number; + + encryptionKey(value?: Curve25519Public): Curve25519Public; + + commandType(value?: SurveyMessageCommandType): SurveyMessageCommandType; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SurveyRequestMessage; + + static write(value: SurveyRequestMessage, io: Buffer): void; + + static isValid(value: SurveyRequestMessage): boolean; + + static toXDR(value: SurveyRequestMessage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SurveyRequestMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SurveyRequestMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TimeSlicedSurveyRequestMessage { + constructor(attributes: { + request: SurveyRequestMessage; + nonce: number; + inboundPeersIndex: number; + outboundPeersIndex: number; + }); + + request(value?: SurveyRequestMessage): SurveyRequestMessage; + + nonce(value?: number): number; + + inboundPeersIndex(value?: number): number; + + outboundPeersIndex(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TimeSlicedSurveyRequestMessage; + + static write(value: TimeSlicedSurveyRequestMessage, io: Buffer): void; + + static isValid(value: TimeSlicedSurveyRequestMessage): boolean; + + static toXDR(value: TimeSlicedSurveyRequestMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TimeSlicedSurveyRequestMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TimeSlicedSurveyRequestMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignedSurveyRequestMessage { + constructor(attributes: { + requestSignature: Buffer; + request: SurveyRequestMessage; + }); + + requestSignature(value?: Buffer): Buffer; + + request(value?: SurveyRequestMessage): SurveyRequestMessage; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignedSurveyRequestMessage; + + static write(value: SignedSurveyRequestMessage, io: Buffer): void; + + static isValid(value: SignedSurveyRequestMessage): boolean; + + static toXDR(value: SignedSurveyRequestMessage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SignedSurveyRequestMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SignedSurveyRequestMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignedTimeSlicedSurveyRequestMessage { + constructor(attributes: { + requestSignature: Buffer; + request: TimeSlicedSurveyRequestMessage; + }); + + requestSignature(value?: Buffer): Buffer; + + request( + value?: TimeSlicedSurveyRequestMessage, + ): TimeSlicedSurveyRequestMessage; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignedTimeSlicedSurveyRequestMessage; + + static write(value: SignedTimeSlicedSurveyRequestMessage, io: Buffer): void; + + static isValid(value: SignedTimeSlicedSurveyRequestMessage): boolean; + + static toXDR(value: SignedTimeSlicedSurveyRequestMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): SignedTimeSlicedSurveyRequestMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SignedTimeSlicedSurveyRequestMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SurveyResponseMessage { + constructor(attributes: { + surveyorPeerId: NodeId; + surveyedPeerId: NodeId; + ledgerNum: number; + commandType: SurveyMessageCommandType; + encryptedBody: Buffer; + }); + + surveyorPeerId(value?: NodeId): NodeId; + + surveyedPeerId(value?: NodeId): NodeId; + + ledgerNum(value?: number): number; + + commandType(value?: SurveyMessageCommandType): SurveyMessageCommandType; + + encryptedBody(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SurveyResponseMessage; + + static write(value: SurveyResponseMessage, io: Buffer): void; + + static isValid(value: SurveyResponseMessage): boolean; + + static toXDR(value: SurveyResponseMessage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SurveyResponseMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SurveyResponseMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TimeSlicedSurveyResponseMessage { + constructor(attributes: { response: SurveyResponseMessage; nonce: number }); + + response(value?: SurveyResponseMessage): SurveyResponseMessage; + + nonce(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TimeSlicedSurveyResponseMessage; + + static write(value: TimeSlicedSurveyResponseMessage, io: Buffer): void; + + static isValid(value: TimeSlicedSurveyResponseMessage): boolean; + + static toXDR(value: TimeSlicedSurveyResponseMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TimeSlicedSurveyResponseMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TimeSlicedSurveyResponseMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignedSurveyResponseMessage { + constructor(attributes: { + responseSignature: Buffer; + response: SurveyResponseMessage; + }); + + responseSignature(value?: Buffer): Buffer; + + response(value?: SurveyResponseMessage): SurveyResponseMessage; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignedSurveyResponseMessage; + + static write(value: SignedSurveyResponseMessage, io: Buffer): void; + + static isValid(value: SignedSurveyResponseMessage): boolean; + + static toXDR(value: SignedSurveyResponseMessage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SignedSurveyResponseMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SignedSurveyResponseMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignedTimeSlicedSurveyResponseMessage { + constructor(attributes: { + responseSignature: Buffer; + response: TimeSlicedSurveyResponseMessage; + }); + + responseSignature(value?: Buffer): Buffer; + + response( + value?: TimeSlicedSurveyResponseMessage, + ): TimeSlicedSurveyResponseMessage; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignedTimeSlicedSurveyResponseMessage; + + static write( + value: SignedTimeSlicedSurveyResponseMessage, + io: Buffer, + ): void; + + static isValid(value: SignedTimeSlicedSurveyResponseMessage): boolean; + + static toXDR(value: SignedTimeSlicedSurveyResponseMessage): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): SignedTimeSlicedSurveyResponseMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SignedTimeSlicedSurveyResponseMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PeerStats { + constructor(attributes: { + id: NodeId; + versionStr: string | Buffer; + messagesRead: Uint64; + messagesWritten: Uint64; + bytesRead: Uint64; + bytesWritten: Uint64; + secondsConnected: Uint64; + uniqueFloodBytesRecv: Uint64; + duplicateFloodBytesRecv: Uint64; + uniqueFetchBytesRecv: Uint64; + duplicateFetchBytesRecv: Uint64; + uniqueFloodMessageRecv: Uint64; + duplicateFloodMessageRecv: Uint64; + uniqueFetchMessageRecv: Uint64; + duplicateFetchMessageRecv: Uint64; + }); + + id(value?: NodeId): NodeId; + + versionStr(value?: string | Buffer): string | Buffer; + + messagesRead(value?: Uint64): Uint64; + + messagesWritten(value?: Uint64): Uint64; + + bytesRead(value?: Uint64): Uint64; + + bytesWritten(value?: Uint64): Uint64; + + secondsConnected(value?: Uint64): Uint64; + + uniqueFloodBytesRecv(value?: Uint64): Uint64; + + duplicateFloodBytesRecv(value?: Uint64): Uint64; + + uniqueFetchBytesRecv(value?: Uint64): Uint64; + + duplicateFetchBytesRecv(value?: Uint64): Uint64; + + uniqueFloodMessageRecv(value?: Uint64): Uint64; + + duplicateFloodMessageRecv(value?: Uint64): Uint64; + + uniqueFetchMessageRecv(value?: Uint64): Uint64; + + duplicateFetchMessageRecv(value?: Uint64): Uint64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PeerStats; + + static write(value: PeerStats, io: Buffer): void; + + static isValid(value: PeerStats): boolean; + + static toXDR(value: PeerStats): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PeerStats; + + static fromXDR(input: string, format: 'hex' | 'base64'): PeerStats; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TimeSlicedNodeData { + constructor(attributes: { + addedAuthenticatedPeers: number; + droppedAuthenticatedPeers: number; + totalInboundPeerCount: number; + totalOutboundPeerCount: number; + p75ScpFirstToSelfLatencyMs: number; + p75ScpSelfToOtherLatencyMs: number; + lostSyncCount: number; + isValidator: boolean; + maxInboundPeerCount: number; + maxOutboundPeerCount: number; + }); + + addedAuthenticatedPeers(value?: number): number; + + droppedAuthenticatedPeers(value?: number): number; + + totalInboundPeerCount(value?: number): number; + + totalOutboundPeerCount(value?: number): number; + + p75ScpFirstToSelfLatencyMs(value?: number): number; + + p75ScpSelfToOtherLatencyMs(value?: number): number; + + lostSyncCount(value?: number): number; + + isValidator(value?: boolean): boolean; + + maxInboundPeerCount(value?: number): number; + + maxOutboundPeerCount(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TimeSlicedNodeData; + + static write(value: TimeSlicedNodeData, io: Buffer): void; + + static isValid(value: TimeSlicedNodeData): boolean; + + static toXDR(value: TimeSlicedNodeData): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TimeSlicedNodeData; + + static fromXDR(input: string, format: 'hex' | 'base64'): TimeSlicedNodeData; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TimeSlicedPeerData { + constructor(attributes: { peerStats: PeerStats; averageLatencyMs: number }); + + peerStats(value?: PeerStats): PeerStats; + + averageLatencyMs(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TimeSlicedPeerData; + + static write(value: TimeSlicedPeerData, io: Buffer): void; + + static isValid(value: TimeSlicedPeerData): boolean; + + static toXDR(value: TimeSlicedPeerData): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TimeSlicedPeerData; + + static fromXDR(input: string, format: 'hex' | 'base64'): TimeSlicedPeerData; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TopologyResponseBodyV0 { + constructor(attributes: { + inboundPeers: PeerStats[]; + outboundPeers: PeerStats[]; + totalInboundPeerCount: number; + totalOutboundPeerCount: number; + }); + + inboundPeers(value?: PeerStats[]): PeerStats[]; + + outboundPeers(value?: PeerStats[]): PeerStats[]; + + totalInboundPeerCount(value?: number): number; + + totalOutboundPeerCount(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TopologyResponseBodyV0; + + static write(value: TopologyResponseBodyV0, io: Buffer): void; + + static isValid(value: TopologyResponseBodyV0): boolean; + + static toXDR(value: TopologyResponseBodyV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TopologyResponseBodyV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TopologyResponseBodyV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TopologyResponseBodyV1 { + constructor(attributes: { + inboundPeers: PeerStats[]; + outboundPeers: PeerStats[]; + totalInboundPeerCount: number; + totalOutboundPeerCount: number; + maxInboundPeerCount: number; + maxOutboundPeerCount: number; + }); + + inboundPeers(value?: PeerStats[]): PeerStats[]; + + outboundPeers(value?: PeerStats[]): PeerStats[]; + + totalInboundPeerCount(value?: number): number; + + totalOutboundPeerCount(value?: number): number; + + maxInboundPeerCount(value?: number): number; + + maxOutboundPeerCount(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TopologyResponseBodyV1; + + static write(value: TopologyResponseBodyV1, io: Buffer): void; + + static isValid(value: TopologyResponseBodyV1): boolean; + + static toXDR(value: TopologyResponseBodyV1): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TopologyResponseBodyV1; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TopologyResponseBodyV1; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TopologyResponseBodyV2 { + constructor(attributes: { + inboundPeers: TimeSlicedPeerData[]; + outboundPeers: TimeSlicedPeerData[]; + nodeData: TimeSlicedNodeData; + }); + + inboundPeers(value?: TimeSlicedPeerData[]): TimeSlicedPeerData[]; + + outboundPeers(value?: TimeSlicedPeerData[]): TimeSlicedPeerData[]; + + nodeData(value?: TimeSlicedNodeData): TimeSlicedNodeData; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TopologyResponseBodyV2; + + static write(value: TopologyResponseBodyV2, io: Buffer): void; + + static isValid(value: TopologyResponseBodyV2): boolean; + + static toXDR(value: TopologyResponseBodyV2): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TopologyResponseBodyV2; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TopologyResponseBodyV2; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class FloodAdvert { + constructor(attributes: { txHashes: Hash[] }); + + txHashes(value?: Hash[]): Hash[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): FloodAdvert; + + static write(value: FloodAdvert, io: Buffer): void; + + static isValid(value: FloodAdvert): boolean; + + static toXDR(value: FloodAdvert): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): FloodAdvert; + + static fromXDR(input: string, format: 'hex' | 'base64'): FloodAdvert; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class FloodDemand { + constructor(attributes: { txHashes: Hash[] }); + + txHashes(value?: Hash[]): Hash[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): FloodDemand; + + static write(value: FloodDemand, io: Buffer): void; + + static isValid(value: FloodDemand): boolean; + + static toXDR(value: FloodDemand): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): FloodDemand; + + static fromXDR(input: string, format: 'hex' | 'base64'): FloodDemand; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AuthenticatedMessageV0 { + constructor(attributes: { + sequence: Uint64; + message: StellarMessage; + mac: HmacSha256Mac; + }); + + sequence(value?: Uint64): Uint64; + + message(value?: StellarMessage): StellarMessage; + + mac(value?: HmacSha256Mac): HmacSha256Mac; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AuthenticatedMessageV0; + + static write(value: AuthenticatedMessageV0, io: Buffer): void; + + static isValid(value: AuthenticatedMessageV0): boolean; + + static toXDR(value: AuthenticatedMessageV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AuthenticatedMessageV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): AuthenticatedMessageV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class MuxedAccountMed25519 { + constructor(attributes: { id: Uint64; ed25519: Buffer }); + + id(value?: Uint64): Uint64; + + ed25519(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): MuxedAccountMed25519; + + static write(value: MuxedAccountMed25519, io: Buffer): void; + + static isValid(value: MuxedAccountMed25519): boolean; + + static toXDR(value: MuxedAccountMed25519): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): MuxedAccountMed25519; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): MuxedAccountMed25519; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class DecoratedSignature { + constructor(attributes: { hint: Buffer; signature: Buffer }); + + hint(value?: Buffer): Buffer; + + signature(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): DecoratedSignature; + + static write(value: DecoratedSignature, io: Buffer): void; + + static isValid(value: DecoratedSignature): boolean; + + static toXDR(value: DecoratedSignature): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): DecoratedSignature; + + static fromXDR(input: string, format: 'hex' | 'base64'): DecoratedSignature; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class CreateAccountOp { + constructor(attributes: { destination: AccountId; startingBalance: Int64 }); + + destination(value?: AccountId): AccountId; + + startingBalance(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): CreateAccountOp; + + static write(value: CreateAccountOp, io: Buffer): void; + + static isValid(value: CreateAccountOp): boolean; + + static toXDR(value: CreateAccountOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): CreateAccountOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): CreateAccountOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PaymentOp { + constructor(attributes: { + destination: MuxedAccount; + asset: Asset; + amount: Int64; + }); + + destination(value?: MuxedAccount): MuxedAccount; + + asset(value?: Asset): Asset; + + amount(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PaymentOp; + + static write(value: PaymentOp, io: Buffer): void; + + static isValid(value: PaymentOp): boolean; + + static toXDR(value: PaymentOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PaymentOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): PaymentOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PathPaymentStrictReceiveOp { + constructor(attributes: { + sendAsset: Asset; + sendMax: Int64; + destination: MuxedAccount; + destAsset: Asset; + destAmount: Int64; + path: Asset[]; + }); + + sendAsset(value?: Asset): Asset; + + sendMax(value?: Int64): Int64; + + destination(value?: MuxedAccount): MuxedAccount; + + destAsset(value?: Asset): Asset; + + destAmount(value?: Int64): Int64; + + path(value?: Asset[]): Asset[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PathPaymentStrictReceiveOp; + + static write(value: PathPaymentStrictReceiveOp, io: Buffer): void; + + static isValid(value: PathPaymentStrictReceiveOp): boolean; + + static toXDR(value: PathPaymentStrictReceiveOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PathPaymentStrictReceiveOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): PathPaymentStrictReceiveOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PathPaymentStrictSendOp { + constructor(attributes: { + sendAsset: Asset; + sendAmount: Int64; + destination: MuxedAccount; + destAsset: Asset; + destMin: Int64; + path: Asset[]; + }); + + sendAsset(value?: Asset): Asset; + + sendAmount(value?: Int64): Int64; + + destination(value?: MuxedAccount): MuxedAccount; + + destAsset(value?: Asset): Asset; + + destMin(value?: Int64): Int64; + + path(value?: Asset[]): Asset[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PathPaymentStrictSendOp; + + static write(value: PathPaymentStrictSendOp, io: Buffer): void; + + static isValid(value: PathPaymentStrictSendOp): boolean; + + static toXDR(value: PathPaymentStrictSendOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PathPaymentStrictSendOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): PathPaymentStrictSendOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageSellOfferOp { + constructor(attributes: { + selling: Asset; + buying: Asset; + amount: Int64; + price: Price; + offerId: Int64; + }); + + selling(value?: Asset): Asset; + + buying(value?: Asset): Asset; + + amount(value?: Int64): Int64; + + price(value?: Price): Price; + + offerId(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageSellOfferOp; + + static write(value: ManageSellOfferOp, io: Buffer): void; + + static isValid(value: ManageSellOfferOp): boolean; + + static toXDR(value: ManageSellOfferOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ManageSellOfferOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): ManageSellOfferOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageBuyOfferOp { + constructor(attributes: { + selling: Asset; + buying: Asset; + buyAmount: Int64; + price: Price; + offerId: Int64; + }); + + selling(value?: Asset): Asset; + + buying(value?: Asset): Asset; + + buyAmount(value?: Int64): Int64; + + price(value?: Price): Price; + + offerId(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageBuyOfferOp; + + static write(value: ManageBuyOfferOp, io: Buffer): void; + + static isValid(value: ManageBuyOfferOp): boolean; + + static toXDR(value: ManageBuyOfferOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ManageBuyOfferOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): ManageBuyOfferOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class CreatePassiveSellOfferOp { + constructor(attributes: { + selling: Asset; + buying: Asset; + amount: Int64; + price: Price; + }); + + selling(value?: Asset): Asset; + + buying(value?: Asset): Asset; + + amount(value?: Int64): Int64; + + price(value?: Price): Price; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): CreatePassiveSellOfferOp; + + static write(value: CreatePassiveSellOfferOp, io: Buffer): void; + + static isValid(value: CreatePassiveSellOfferOp): boolean; + + static toXDR(value: CreatePassiveSellOfferOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): CreatePassiveSellOfferOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): CreatePassiveSellOfferOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SetOptionsOp { + constructor(attributes: { + inflationDest: null | AccountId; + clearFlags: null | number; + setFlags: null | number; + masterWeight: null | number; + lowThreshold: null | number; + medThreshold: null | number; + highThreshold: null | number; + homeDomain: null | string | Buffer; + signer: null | Signer; + }); + + inflationDest(value?: null | AccountId): null | AccountId; + + clearFlags(value?: null | number): null | number; + + setFlags(value?: null | number): null | number; + + masterWeight(value?: null | number): null | number; + + lowThreshold(value?: null | number): null | number; + + medThreshold(value?: null | number): null | number; + + highThreshold(value?: null | number): null | number; + + homeDomain(value?: null | string | Buffer): null | string | Buffer; + + signer(value?: null | Signer): null | Signer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SetOptionsOp; + + static write(value: SetOptionsOp, io: Buffer): void; + + static isValid(value: SetOptionsOp): boolean; + + static toXDR(value: SetOptionsOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SetOptionsOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): SetOptionsOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ChangeTrustOp { + constructor(attributes: { line: ChangeTrustAsset; limit: Int64 }); + + line(value?: ChangeTrustAsset): ChangeTrustAsset; + + limit(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ChangeTrustOp; + + static write(value: ChangeTrustOp, io: Buffer): void; + + static isValid(value: ChangeTrustOp): boolean; + + static toXDR(value: ChangeTrustOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ChangeTrustOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): ChangeTrustOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AllowTrustOp { + constructor(attributes: { + trustor: AccountId; + asset: AssetCode; + authorize: number; + }); + + trustor(value?: AccountId): AccountId; + + asset(value?: AssetCode): AssetCode; + + authorize(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AllowTrustOp; + + static write(value: AllowTrustOp, io: Buffer): void; + + static isValid(value: AllowTrustOp): boolean; + + static toXDR(value: AllowTrustOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AllowTrustOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): AllowTrustOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageDataOp { + constructor(attributes: { + dataName: string | Buffer; + dataValue: null | Buffer; + }); + + dataName(value?: string | Buffer): string | Buffer; + + dataValue(value?: null | Buffer): null | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageDataOp; + + static write(value: ManageDataOp, io: Buffer): void; + + static isValid(value: ManageDataOp): boolean; + + static toXDR(value: ManageDataOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ManageDataOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): ManageDataOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class BumpSequenceOp { + constructor(attributes: { bumpTo: SequenceNumber }); + + bumpTo(value?: SequenceNumber): SequenceNumber; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): BumpSequenceOp; + + static write(value: BumpSequenceOp, io: Buffer): void; + + static isValid(value: BumpSequenceOp): boolean; + + static toXDR(value: BumpSequenceOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): BumpSequenceOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): BumpSequenceOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class CreateClaimableBalanceOp { + constructor(attributes: { + asset: Asset; + amount: Int64; + claimants: Claimant[]; + }); + + asset(value?: Asset): Asset; + + amount(value?: Int64): Int64; + + claimants(value?: Claimant[]): Claimant[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): CreateClaimableBalanceOp; + + static write(value: CreateClaimableBalanceOp, io: Buffer): void; + + static isValid(value: CreateClaimableBalanceOp): boolean; + + static toXDR(value: CreateClaimableBalanceOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): CreateClaimableBalanceOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): CreateClaimableBalanceOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimClaimableBalanceOp { + constructor(attributes: { balanceId: ClaimableBalanceId }); + + balanceId(value?: ClaimableBalanceId): ClaimableBalanceId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimClaimableBalanceOp; + + static write(value: ClaimClaimableBalanceOp, io: Buffer): void; + + static isValid(value: ClaimClaimableBalanceOp): boolean; + + static toXDR(value: ClaimClaimableBalanceOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimClaimableBalanceOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClaimClaimableBalanceOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class BeginSponsoringFutureReservesOp { + constructor(attributes: { sponsoredId: AccountId }); + + sponsoredId(value?: AccountId): AccountId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): BeginSponsoringFutureReservesOp; + + static write(value: BeginSponsoringFutureReservesOp, io: Buffer): void; + + static isValid(value: BeginSponsoringFutureReservesOp): boolean; + + static toXDR(value: BeginSponsoringFutureReservesOp): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): BeginSponsoringFutureReservesOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): BeginSponsoringFutureReservesOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class RevokeSponsorshipOpSigner { + constructor(attributes: { accountId: AccountId; signerKey: SignerKey }); + + accountId(value?: AccountId): AccountId; + + signerKey(value?: SignerKey): SignerKey; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): RevokeSponsorshipOpSigner; + + static write(value: RevokeSponsorshipOpSigner, io: Buffer): void; + + static isValid(value: RevokeSponsorshipOpSigner): boolean; + + static toXDR(value: RevokeSponsorshipOpSigner): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): RevokeSponsorshipOpSigner; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): RevokeSponsorshipOpSigner; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClawbackOp { + constructor(attributes: { + asset: Asset; + from: MuxedAccount; + amount: Int64; + }); + + asset(value?: Asset): Asset; + + from(value?: MuxedAccount): MuxedAccount; + + amount(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClawbackOp; + + static write(value: ClawbackOp, io: Buffer): void; + + static isValid(value: ClawbackOp): boolean; + + static toXDR(value: ClawbackOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClawbackOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClawbackOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClawbackClaimableBalanceOp { + constructor(attributes: { balanceId: ClaimableBalanceId }); + + balanceId(value?: ClaimableBalanceId): ClaimableBalanceId; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClawbackClaimableBalanceOp; + + static write(value: ClawbackClaimableBalanceOp, io: Buffer): void; + + static isValid(value: ClawbackClaimableBalanceOp): boolean; + + static toXDR(value: ClawbackClaimableBalanceOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClawbackClaimableBalanceOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClawbackClaimableBalanceOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SetTrustLineFlagsOp { + constructor(attributes: { + trustor: AccountId; + asset: Asset; + clearFlags: number; + setFlags: number; + }); + + trustor(value?: AccountId): AccountId; + + asset(value?: Asset): Asset; + + clearFlags(value?: number): number; + + setFlags(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SetTrustLineFlagsOp; + + static write(value: SetTrustLineFlagsOp, io: Buffer): void; + + static isValid(value: SetTrustLineFlagsOp): boolean; + + static toXDR(value: SetTrustLineFlagsOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SetTrustLineFlagsOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SetTrustLineFlagsOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolDepositOp { + constructor(attributes: { + liquidityPoolId: PoolId; + maxAmountA: Int64; + maxAmountB: Int64; + minPrice: Price; + maxPrice: Price; + }); + + liquidityPoolId(value?: PoolId): PoolId; + + maxAmountA(value?: Int64): Int64; + + maxAmountB(value?: Int64): Int64; + + minPrice(value?: Price): Price; + + maxPrice(value?: Price): Price; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolDepositOp; + + static write(value: LiquidityPoolDepositOp, io: Buffer): void; + + static isValid(value: LiquidityPoolDepositOp): boolean; + + static toXDR(value: LiquidityPoolDepositOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LiquidityPoolDepositOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolDepositOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolWithdrawOp { + constructor(attributes: { + liquidityPoolId: PoolId; + amount: Int64; + minAmountA: Int64; + minAmountB: Int64; + }); + + liquidityPoolId(value?: PoolId): PoolId; + + amount(value?: Int64): Int64; + + minAmountA(value?: Int64): Int64; + + minAmountB(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolWithdrawOp; + + static write(value: LiquidityPoolWithdrawOp, io: Buffer): void; + + static isValid(value: LiquidityPoolWithdrawOp): boolean; + + static toXDR(value: LiquidityPoolWithdrawOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LiquidityPoolWithdrawOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolWithdrawOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractIdPreimageFromAddress { + constructor(attributes: { address: ScAddress; salt: Buffer }); + + address(value?: ScAddress): ScAddress; + + salt(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractIdPreimageFromAddress; + + static write(value: ContractIdPreimageFromAddress, io: Buffer): void; + + static isValid(value: ContractIdPreimageFromAddress): boolean; + + static toXDR(value: ContractIdPreimageFromAddress): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ContractIdPreimageFromAddress; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ContractIdPreimageFromAddress; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class CreateContractArgs { + constructor(attributes: { + contractIdPreimage: ContractIdPreimage; + executable: ContractExecutable; + }); + + contractIdPreimage(value?: ContractIdPreimage): ContractIdPreimage; + + executable(value?: ContractExecutable): ContractExecutable; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): CreateContractArgs; + + static write(value: CreateContractArgs, io: Buffer): void; + + static isValid(value: CreateContractArgs): boolean; + + static toXDR(value: CreateContractArgs): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): CreateContractArgs; + + static fromXDR(input: string, format: 'hex' | 'base64'): CreateContractArgs; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class CreateContractArgsV2 { + constructor(attributes: { + contractIdPreimage: ContractIdPreimage; + executable: ContractExecutable; + constructorArgs: ScVal[]; + }); + + contractIdPreimage(value?: ContractIdPreimage): ContractIdPreimage; + + executable(value?: ContractExecutable): ContractExecutable; + + constructorArgs(value?: ScVal[]): ScVal[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): CreateContractArgsV2; + + static write(value: CreateContractArgsV2, io: Buffer): void; + + static isValid(value: CreateContractArgsV2): boolean; + + static toXDR(value: CreateContractArgsV2): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): CreateContractArgsV2; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): CreateContractArgsV2; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InvokeContractArgs { + constructor(attributes: { + contractAddress: ScAddress; + functionName: string | Buffer; + args: ScVal[]; + }); + + contractAddress(value?: ScAddress): ScAddress; + + functionName(value?: string | Buffer): string | Buffer; + + args(value?: ScVal[]): ScVal[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InvokeContractArgs; + + static write(value: InvokeContractArgs, io: Buffer): void; + + static isValid(value: InvokeContractArgs): boolean; + + static toXDR(value: InvokeContractArgs): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InvokeContractArgs; + + static fromXDR(input: string, format: 'hex' | 'base64'): InvokeContractArgs; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanAuthorizedInvocation { + constructor(attributes: { + function: SorobanAuthorizedFunction; + subInvocations: SorobanAuthorizedInvocation[]; + }); + + function(value?: SorobanAuthorizedFunction): SorobanAuthorizedFunction; + + subInvocations( + value?: SorobanAuthorizedInvocation[], + ): SorobanAuthorizedInvocation[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanAuthorizedInvocation; + + static write(value: SorobanAuthorizedInvocation, io: Buffer): void; + + static isValid(value: SorobanAuthorizedInvocation): boolean; + + static toXDR(value: SorobanAuthorizedInvocation): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanAuthorizedInvocation; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanAuthorizedInvocation; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanAddressCredentials { + constructor(attributes: { + address: ScAddress; + nonce: Int64; + signatureExpirationLedger: number; + signature: ScVal; + }); + + address(value?: ScAddress): ScAddress; + + nonce(value?: Int64): Int64; + + signatureExpirationLedger(value?: number): number; + + signature(value?: ScVal): ScVal; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanAddressCredentials; + + static write(value: SorobanAddressCredentials, io: Buffer): void; + + static isValid(value: SorobanAddressCredentials): boolean; + + static toXDR(value: SorobanAddressCredentials): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanAddressCredentials; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanAddressCredentials; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanAuthorizationEntry { + constructor(attributes: { + credentials: SorobanCredentials; + rootInvocation: SorobanAuthorizedInvocation; + }); + + credentials(value?: SorobanCredentials): SorobanCredentials; + + rootInvocation( + value?: SorobanAuthorizedInvocation, + ): SorobanAuthorizedInvocation; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanAuthorizationEntry; + + static write(value: SorobanAuthorizationEntry, io: Buffer): void; + + static isValid(value: SorobanAuthorizationEntry): boolean; + + static toXDR(value: SorobanAuthorizationEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanAuthorizationEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanAuthorizationEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InvokeHostFunctionOp { + constructor(attributes: { + hostFunction: HostFunction; + auth: SorobanAuthorizationEntry[]; + }); + + hostFunction(value?: HostFunction): HostFunction; + + auth(value?: SorobanAuthorizationEntry[]): SorobanAuthorizationEntry[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InvokeHostFunctionOp; + + static write(value: InvokeHostFunctionOp, io: Buffer): void; + + static isValid(value: InvokeHostFunctionOp): boolean; + + static toXDR(value: InvokeHostFunctionOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InvokeHostFunctionOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): InvokeHostFunctionOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ExtendFootprintTtlOp { + constructor(attributes: { ext: ExtensionPoint; extendTo: number }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + extendTo(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ExtendFootprintTtlOp; + + static write(value: ExtendFootprintTtlOp, io: Buffer): void; + + static isValid(value: ExtendFootprintTtlOp): boolean; + + static toXDR(value: ExtendFootprintTtlOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ExtendFootprintTtlOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ExtendFootprintTtlOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class RestoreFootprintOp { + constructor(attributes: { ext: ExtensionPoint }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): RestoreFootprintOp; + + static write(value: RestoreFootprintOp, io: Buffer): void; + + static isValid(value: RestoreFootprintOp): boolean; + + static toXDR(value: RestoreFootprintOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): RestoreFootprintOp; + + static fromXDR(input: string, format: 'hex' | 'base64'): RestoreFootprintOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Operation { + constructor(attributes: { + sourceAccount: null | MuxedAccount; + body: OperationBody; + }); + + sourceAccount(value?: null | MuxedAccount): null | MuxedAccount; + + body(value?: OperationBody): OperationBody; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Operation; + + static write(value: Operation, io: Buffer): void; + + static isValid(value: Operation): boolean; + + static toXDR(value: Operation): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Operation; + + static fromXDR(input: string, format: 'hex' | 'base64'): Operation; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HashIdPreimageOperationId { + constructor(attributes: { + sourceAccount: AccountId; + seqNum: SequenceNumber; + opNum: number; + }); + + sourceAccount(value?: AccountId): AccountId; + + seqNum(value?: SequenceNumber): SequenceNumber; + + opNum(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HashIdPreimageOperationId; + + static write(value: HashIdPreimageOperationId, io: Buffer): void; + + static isValid(value: HashIdPreimageOperationId): boolean; + + static toXDR(value: HashIdPreimageOperationId): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HashIdPreimageOperationId; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): HashIdPreimageOperationId; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HashIdPreimageRevokeId { + constructor(attributes: { + sourceAccount: AccountId; + seqNum: SequenceNumber; + opNum: number; + liquidityPoolId: PoolId; + asset: Asset; + }); + + sourceAccount(value?: AccountId): AccountId; + + seqNum(value?: SequenceNumber): SequenceNumber; + + opNum(value?: number): number; + + liquidityPoolId(value?: PoolId): PoolId; + + asset(value?: Asset): Asset; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HashIdPreimageRevokeId; + + static write(value: HashIdPreimageRevokeId, io: Buffer): void; + + static isValid(value: HashIdPreimageRevokeId): boolean; + + static toXDR(value: HashIdPreimageRevokeId): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HashIdPreimageRevokeId; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): HashIdPreimageRevokeId; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HashIdPreimageContractId { + constructor(attributes: { + networkId: Buffer; + contractIdPreimage: ContractIdPreimage; + }); + + networkId(value?: Buffer): Buffer; + + contractIdPreimage(value?: ContractIdPreimage): ContractIdPreimage; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HashIdPreimageContractId; + + static write(value: HashIdPreimageContractId, io: Buffer): void; + + static isValid(value: HashIdPreimageContractId): boolean; + + static toXDR(value: HashIdPreimageContractId): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HashIdPreimageContractId; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): HashIdPreimageContractId; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HashIdPreimageSorobanAuthorization { + constructor(attributes: { + networkId: Buffer; + nonce: Int64; + signatureExpirationLedger: number; + invocation: SorobanAuthorizedInvocation; + }); + + networkId(value?: Buffer): Buffer; + + nonce(value?: Int64): Int64; + + signatureExpirationLedger(value?: number): number; + + invocation( + value?: SorobanAuthorizedInvocation, + ): SorobanAuthorizedInvocation; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HashIdPreimageSorobanAuthorization; + + static write(value: HashIdPreimageSorobanAuthorization, io: Buffer): void; + + static isValid(value: HashIdPreimageSorobanAuthorization): boolean; + + static toXDR(value: HashIdPreimageSorobanAuthorization): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): HashIdPreimageSorobanAuthorization; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): HashIdPreimageSorobanAuthorization; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TimeBounds { + constructor(attributes: { minTime: TimePoint; maxTime: TimePoint }); + + minTime(value?: TimePoint): TimePoint; + + maxTime(value?: TimePoint): TimePoint; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TimeBounds; + + static write(value: TimeBounds, io: Buffer): void; + + static isValid(value: TimeBounds): boolean; + + static toXDR(value: TimeBounds): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TimeBounds; + + static fromXDR(input: string, format: 'hex' | 'base64'): TimeBounds; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerBounds { + constructor(attributes: { minLedger: number; maxLedger: number }); + + minLedger(value?: number): number; + + maxLedger(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerBounds; + + static write(value: LedgerBounds, io: Buffer): void; + + static isValid(value: LedgerBounds): boolean; + + static toXDR(value: LedgerBounds): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerBounds; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerBounds; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PreconditionsV2 { + constructor(attributes: { + timeBounds: null | TimeBounds; + ledgerBounds: null | LedgerBounds; + minSeqNum: null | SequenceNumber; + minSeqAge: Duration; + minSeqLedgerGap: number; + extraSigners: SignerKey[]; + }); + + timeBounds(value?: null | TimeBounds): null | TimeBounds; + + ledgerBounds(value?: null | LedgerBounds): null | LedgerBounds; + + minSeqNum(value?: null | SequenceNumber): null | SequenceNumber; + + minSeqAge(value?: Duration): Duration; + + minSeqLedgerGap(value?: number): number; + + extraSigners(value?: SignerKey[]): SignerKey[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PreconditionsV2; + + static write(value: PreconditionsV2, io: Buffer): void; + + static isValid(value: PreconditionsV2): boolean; + + static toXDR(value: PreconditionsV2): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PreconditionsV2; + + static fromXDR(input: string, format: 'hex' | 'base64'): PreconditionsV2; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerFootprint { + constructor(attributes: { readOnly: LedgerKey[]; readWrite: LedgerKey[] }); + + readOnly(value?: LedgerKey[]): LedgerKey[]; + + readWrite(value?: LedgerKey[]): LedgerKey[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerFootprint; + + static write(value: LedgerFootprint, io: Buffer): void; + + static isValid(value: LedgerFootprint): boolean; + + static toXDR(value: LedgerFootprint): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerFootprint; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerFootprint; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ArchivalProofNode { + constructor(attributes: { index: number; hash: Buffer }); + + index(value?: number): number; + + hash(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ArchivalProofNode; + + static write(value: ArchivalProofNode, io: Buffer): void; + + static isValid(value: ArchivalProofNode): boolean; + + static toXDR(value: ArchivalProofNode): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ArchivalProofNode; + + static fromXDR(input: string, format: 'hex' | 'base64'): ArchivalProofNode; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class NonexistenceProofBody { + constructor(attributes: { + entriesToProve: ColdArchiveBucketEntry[]; + proofLevels: ArchivalProofNode[][]; + }); + + entriesToProve(value?: ColdArchiveBucketEntry[]): ColdArchiveBucketEntry[]; + + proofLevels(value?: ArchivalProofNode[][]): ArchivalProofNode[][]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): NonexistenceProofBody; + + static write(value: NonexistenceProofBody, io: Buffer): void; + + static isValid(value: NonexistenceProofBody): boolean; + + static toXDR(value: NonexistenceProofBody): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): NonexistenceProofBody; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): NonexistenceProofBody; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ExistenceProofBody { + constructor(attributes: { + keysToProve: LedgerKey[]; + lowBoundEntries: ColdArchiveBucketEntry[]; + highBoundEntries: ColdArchiveBucketEntry[]; + proofLevels: ArchivalProofNode[][]; + }); + + keysToProve(value?: LedgerKey[]): LedgerKey[]; + + lowBoundEntries(value?: ColdArchiveBucketEntry[]): ColdArchiveBucketEntry[]; + + highBoundEntries( + value?: ColdArchiveBucketEntry[], + ): ColdArchiveBucketEntry[]; + + proofLevels(value?: ArchivalProofNode[][]): ArchivalProofNode[][]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ExistenceProofBody; + + static write(value: ExistenceProofBody, io: Buffer): void; + + static isValid(value: ExistenceProofBody): boolean; + + static toXDR(value: ExistenceProofBody): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ExistenceProofBody; + + static fromXDR(input: string, format: 'hex' | 'base64'): ExistenceProofBody; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ArchivalProof { + constructor(attributes: { epoch: number; body: ArchivalProofBody }); + + epoch(value?: number): number; + + body(value?: ArchivalProofBody): ArchivalProofBody; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ArchivalProof; + + static write(value: ArchivalProof, io: Buffer): void; + + static isValid(value: ArchivalProof): boolean; + + static toXDR(value: ArchivalProof): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ArchivalProof; + + static fromXDR(input: string, format: 'hex' | 'base64'): ArchivalProof; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanResources { + constructor(attributes: { + footprint: LedgerFootprint; + instructions: number; + readBytes: number; + writeBytes: number; + }); + + footprint(value?: LedgerFootprint): LedgerFootprint; + + instructions(value?: number): number; + + readBytes(value?: number): number; + + writeBytes(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanResources; + + static write(value: SorobanResources, io: Buffer): void; + + static isValid(value: SorobanResources): boolean; + + static toXDR(value: SorobanResources): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanResources; + + static fromXDR(input: string, format: 'hex' | 'base64'): SorobanResources; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanTransactionData { + constructor(attributes: { + ext: SorobanTransactionDataExt; + resources: SorobanResources; + resourceFee: Int64; + }); + + ext(value?: SorobanTransactionDataExt): SorobanTransactionDataExt; + + resources(value?: SorobanResources): SorobanResources; + + resourceFee(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanTransactionData; + + static write(value: SorobanTransactionData, io: Buffer): void; + + static isValid(value: SorobanTransactionData): boolean; + + static toXDR(value: SorobanTransactionData): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanTransactionData; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanTransactionData; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionV0 { + constructor(attributes: { + sourceAccountEd25519: Buffer; + fee: number; + seqNum: SequenceNumber; + timeBounds: null | TimeBounds; + memo: Memo; + operations: Operation[]; + ext: TransactionV0Ext; + }); + + sourceAccountEd25519(value?: Buffer): Buffer; + + fee(value?: number): number; + + seqNum(value?: SequenceNumber): SequenceNumber; + + timeBounds(value?: null | TimeBounds): null | TimeBounds; + + memo(value?: Memo): Memo; + + operations(value?: Operation[]): Operation[]; + + ext(value?: TransactionV0Ext): TransactionV0Ext; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionV0; + + static write(value: TransactionV0, io: Buffer): void; + + static isValid(value: TransactionV0): boolean; + + static toXDR(value: TransactionV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionV0Envelope { + constructor(attributes: { + tx: TransactionV0; + signatures: DecoratedSignature[]; + }); + + tx(value?: TransactionV0): TransactionV0; + + signatures(value?: DecoratedSignature[]): DecoratedSignature[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionV0Envelope; + + static write(value: TransactionV0Envelope, io: Buffer): void; + + static isValid(value: TransactionV0Envelope): boolean; + + static toXDR(value: TransactionV0Envelope): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionV0Envelope; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionV0Envelope; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Transaction { + constructor(attributes: { + sourceAccount: MuxedAccount; + fee: number; + seqNum: SequenceNumber; + cond: Preconditions; + memo: Memo; + operations: Operation[]; + ext: TransactionExt; + }); + + sourceAccount(value?: MuxedAccount): MuxedAccount; + + fee(value?: number): number; + + seqNum(value?: SequenceNumber): SequenceNumber; + + cond(value?: Preconditions): Preconditions; + + memo(value?: Memo): Memo; + + operations(value?: Operation[]): Operation[]; + + ext(value?: TransactionExt): TransactionExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Transaction; + + static write(value: Transaction, io: Buffer): void; + + static isValid(value: Transaction): boolean; + + static toXDR(value: Transaction): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Transaction; + + static fromXDR(input: string, format: 'hex' | 'base64'): Transaction; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionV1Envelope { + constructor(attributes: { + tx: Transaction; + signatures: DecoratedSignature[]; + }); + + tx(value?: Transaction): Transaction; + + signatures(value?: DecoratedSignature[]): DecoratedSignature[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionV1Envelope; + + static write(value: TransactionV1Envelope, io: Buffer): void; + + static isValid(value: TransactionV1Envelope): boolean; + + static toXDR(value: TransactionV1Envelope): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionV1Envelope; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionV1Envelope; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class FeeBumpTransaction { + constructor(attributes: { + feeSource: MuxedAccount; + fee: Int64; + innerTx: FeeBumpTransactionInnerTx; + ext: FeeBumpTransactionExt; + }); + + feeSource(value?: MuxedAccount): MuxedAccount; + + fee(value?: Int64): Int64; + + innerTx(value?: FeeBumpTransactionInnerTx): FeeBumpTransactionInnerTx; + + ext(value?: FeeBumpTransactionExt): FeeBumpTransactionExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): FeeBumpTransaction; + + static write(value: FeeBumpTransaction, io: Buffer): void; + + static isValid(value: FeeBumpTransaction): boolean; + + static toXDR(value: FeeBumpTransaction): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): FeeBumpTransaction; + + static fromXDR(input: string, format: 'hex' | 'base64'): FeeBumpTransaction; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class FeeBumpTransactionEnvelope { + constructor(attributes: { + tx: FeeBumpTransaction; + signatures: DecoratedSignature[]; + }); + + tx(value?: FeeBumpTransaction): FeeBumpTransaction; + + signatures(value?: DecoratedSignature[]): DecoratedSignature[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): FeeBumpTransactionEnvelope; + + static write(value: FeeBumpTransactionEnvelope, io: Buffer): void; + + static isValid(value: FeeBumpTransactionEnvelope): boolean; + + static toXDR(value: FeeBumpTransactionEnvelope): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): FeeBumpTransactionEnvelope; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): FeeBumpTransactionEnvelope; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionSignaturePayload { + constructor(attributes: { + networkId: Buffer; + taggedTransaction: TransactionSignaturePayloadTaggedTransaction; + }); + + networkId(value?: Buffer): Buffer; + + taggedTransaction( + value?: TransactionSignaturePayloadTaggedTransaction, + ): TransactionSignaturePayloadTaggedTransaction; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionSignaturePayload; + + static write(value: TransactionSignaturePayload, io: Buffer): void; + + static isValid(value: TransactionSignaturePayload): boolean; + + static toXDR(value: TransactionSignaturePayload): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionSignaturePayload; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionSignaturePayload; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimOfferAtomV0 { + constructor(attributes: { + sellerEd25519: Buffer; + offerId: Int64; + assetSold: Asset; + amountSold: Int64; + assetBought: Asset; + amountBought: Int64; + }); + + sellerEd25519(value?: Buffer): Buffer; + + offerId(value?: Int64): Int64; + + assetSold(value?: Asset): Asset; + + amountSold(value?: Int64): Int64; + + assetBought(value?: Asset): Asset; + + amountBought(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimOfferAtomV0; + + static write(value: ClaimOfferAtomV0, io: Buffer): void; + + static isValid(value: ClaimOfferAtomV0): boolean; + + static toXDR(value: ClaimOfferAtomV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimOfferAtomV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClaimOfferAtomV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimOfferAtom { + constructor(attributes: { + sellerId: AccountId; + offerId: Int64; + assetSold: Asset; + amountSold: Int64; + assetBought: Asset; + amountBought: Int64; + }); + + sellerId(value?: AccountId): AccountId; + + offerId(value?: Int64): Int64; + + assetSold(value?: Asset): Asset; + + amountSold(value?: Int64): Int64; + + assetBought(value?: Asset): Asset; + + amountBought(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimOfferAtom; + + static write(value: ClaimOfferAtom, io: Buffer): void; + + static isValid(value: ClaimOfferAtom): boolean; + + static toXDR(value: ClaimOfferAtom): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimOfferAtom; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClaimOfferAtom; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimLiquidityAtom { + constructor(attributes: { + liquidityPoolId: PoolId; + assetSold: Asset; + amountSold: Int64; + assetBought: Asset; + amountBought: Int64; + }); + + liquidityPoolId(value?: PoolId): PoolId; + + assetSold(value?: Asset): Asset; + + amountSold(value?: Int64): Int64; + + assetBought(value?: Asset): Asset; + + amountBought(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimLiquidityAtom; + + static write(value: ClaimLiquidityAtom, io: Buffer): void; + + static isValid(value: ClaimLiquidityAtom): boolean; + + static toXDR(value: ClaimLiquidityAtom): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimLiquidityAtom; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClaimLiquidityAtom; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SimplePaymentResult { + constructor(attributes: { + destination: AccountId; + asset: Asset; + amount: Int64; + }); + + destination(value?: AccountId): AccountId; + + asset(value?: Asset): Asset; + + amount(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SimplePaymentResult; + + static write(value: SimplePaymentResult, io: Buffer): void; + + static isValid(value: SimplePaymentResult): boolean; + + static toXDR(value: SimplePaymentResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SimplePaymentResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SimplePaymentResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PathPaymentStrictReceiveResultSuccess { + constructor(attributes: { offers: ClaimAtom[]; last: SimplePaymentResult }); + + offers(value?: ClaimAtom[]): ClaimAtom[]; + + last(value?: SimplePaymentResult): SimplePaymentResult; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PathPaymentStrictReceiveResultSuccess; + + static write( + value: PathPaymentStrictReceiveResultSuccess, + io: Buffer, + ): void; + + static isValid(value: PathPaymentStrictReceiveResultSuccess): boolean; + + static toXDR(value: PathPaymentStrictReceiveResultSuccess): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): PathPaymentStrictReceiveResultSuccess; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): PathPaymentStrictReceiveResultSuccess; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PathPaymentStrictSendResultSuccess { + constructor(attributes: { offers: ClaimAtom[]; last: SimplePaymentResult }); + + offers(value?: ClaimAtom[]): ClaimAtom[]; + + last(value?: SimplePaymentResult): SimplePaymentResult; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PathPaymentStrictSendResultSuccess; + + static write(value: PathPaymentStrictSendResultSuccess, io: Buffer): void; + + static isValid(value: PathPaymentStrictSendResultSuccess): boolean; + + static toXDR(value: PathPaymentStrictSendResultSuccess): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): PathPaymentStrictSendResultSuccess; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): PathPaymentStrictSendResultSuccess; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageOfferSuccessResult { + constructor(attributes: { + offersClaimed: ClaimAtom[]; + offer: ManageOfferSuccessResultOffer; + }); + + offersClaimed(value?: ClaimAtom[]): ClaimAtom[]; + + offer(value?: ManageOfferSuccessResultOffer): ManageOfferSuccessResultOffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageOfferSuccessResult; + + static write(value: ManageOfferSuccessResult, io: Buffer): void; + + static isValid(value: ManageOfferSuccessResult): boolean; + + static toXDR(value: ManageOfferSuccessResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ManageOfferSuccessResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ManageOfferSuccessResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InflationPayout { + constructor(attributes: { destination: AccountId; amount: Int64 }); + + destination(value?: AccountId): AccountId; + + amount(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InflationPayout; + + static write(value: InflationPayout, io: Buffer): void; + + static isValid(value: InflationPayout): boolean; + + static toXDR(value: InflationPayout): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InflationPayout; + + static fromXDR(input: string, format: 'hex' | 'base64'): InflationPayout; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InnerTransactionResult { + constructor(attributes: { + feeCharged: Int64; + result: InnerTransactionResultResult; + ext: InnerTransactionResultExt; + }); + + feeCharged(value?: Int64): Int64; + + result(value?: InnerTransactionResultResult): InnerTransactionResultResult; + + ext(value?: InnerTransactionResultExt): InnerTransactionResultExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InnerTransactionResult; + + static write(value: InnerTransactionResult, io: Buffer): void; + + static isValid(value: InnerTransactionResult): boolean; + + static toXDR(value: InnerTransactionResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InnerTransactionResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): InnerTransactionResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InnerTransactionResultPair { + constructor(attributes: { + transactionHash: Buffer; + result: InnerTransactionResult; + }); + + transactionHash(value?: Buffer): Buffer; + + result(value?: InnerTransactionResult): InnerTransactionResult; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InnerTransactionResultPair; + + static write(value: InnerTransactionResultPair, io: Buffer): void; + + static isValid(value: InnerTransactionResultPair): boolean; + + static toXDR(value: InnerTransactionResultPair): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InnerTransactionResultPair; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): InnerTransactionResultPair; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionResult { + constructor(attributes: { + feeCharged: Int64; + result: TransactionResultResult; + ext: TransactionResultExt; + }); + + feeCharged(value?: Int64): Int64; + + result(value?: TransactionResultResult): TransactionResultResult; + + ext(value?: TransactionResultExt): TransactionResultExt; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionResult; + + static write(value: TransactionResult, io: Buffer): void; + + static isValid(value: TransactionResult): boolean; + + static toXDR(value: TransactionResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignerKeyEd25519SignedPayload { + constructor(attributes: { ed25519: Buffer; payload: Buffer }); + + ed25519(value?: Buffer): Buffer; + + payload(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignerKeyEd25519SignedPayload; + + static write(value: SignerKeyEd25519SignedPayload, io: Buffer): void; + + static isValid(value: SignerKeyEd25519SignedPayload): boolean; + + static toXDR(value: SignerKeyEd25519SignedPayload): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): SignerKeyEd25519SignedPayload; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SignerKeyEd25519SignedPayload; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Curve25519Secret { + constructor(attributes: { key: Buffer }); + + key(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Curve25519Secret; + + static write(value: Curve25519Secret, io: Buffer): void; + + static isValid(value: Curve25519Secret): boolean; + + static toXDR(value: Curve25519Secret): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Curve25519Secret; + + static fromXDR(input: string, format: 'hex' | 'base64'): Curve25519Secret; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Curve25519Public { + constructor(attributes: { key: Buffer }); + + key(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Curve25519Public; + + static write(value: Curve25519Public, io: Buffer): void; + + static isValid(value: Curve25519Public): boolean; + + static toXDR(value: Curve25519Public): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Curve25519Public; + + static fromXDR(input: string, format: 'hex' | 'base64'): Curve25519Public; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HmacSha256Key { + constructor(attributes: { key: Buffer }); + + key(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HmacSha256Key; + + static write(value: HmacSha256Key, io: Buffer): void; + + static isValid(value: HmacSha256Key): boolean; + + static toXDR(value: HmacSha256Key): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HmacSha256Key; + + static fromXDR(input: string, format: 'hex' | 'base64'): HmacSha256Key; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HmacSha256Mac { + constructor(attributes: { mac: Buffer }); + + mac(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HmacSha256Mac; + + static write(value: HmacSha256Mac, io: Buffer): void; + + static isValid(value: HmacSha256Mac): boolean; + + static toXDR(value: HmacSha256Mac): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HmacSha256Mac; + + static fromXDR(input: string, format: 'hex' | 'base64'): HmacSha256Mac; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ShortHashSeed { + constructor(attributes: { seed: Buffer }); + + seed(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ShortHashSeed; + + static write(value: ShortHashSeed, io: Buffer): void; + + static isValid(value: ShortHashSeed): boolean; + + static toXDR(value: ShortHashSeed): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ShortHashSeed; + + static fromXDR(input: string, format: 'hex' | 'base64'): ShortHashSeed; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SerializedBinaryFuseFilter { + constructor(attributes: { + type: BinaryFuseFilterType; + inputHashSeed: ShortHashSeed; + filterSeed: ShortHashSeed; + segmentLength: number; + segementLengthMask: number; + segmentCount: number; + segmentCountLength: number; + fingerprintLength: number; + fingerprints: Buffer; + }); + + type(value?: BinaryFuseFilterType): BinaryFuseFilterType; + + inputHashSeed(value?: ShortHashSeed): ShortHashSeed; + + filterSeed(value?: ShortHashSeed): ShortHashSeed; + + segmentLength(value?: number): number; + + segementLengthMask(value?: number): number; + + segmentCount(value?: number): number; + + segmentCountLength(value?: number): number; + + fingerprintLength(value?: number): number; + + fingerprints(value?: Buffer): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SerializedBinaryFuseFilter; + + static write(value: SerializedBinaryFuseFilter, io: Buffer): void; + + static isValid(value: SerializedBinaryFuseFilter): boolean; + + static toXDR(value: SerializedBinaryFuseFilter): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SerializedBinaryFuseFilter; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SerializedBinaryFuseFilter; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class UInt128Parts { + constructor(attributes: { hi: Uint64; lo: Uint64 }); + + hi(value?: Uint64): Uint64; + + lo(value?: Uint64): Uint64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): UInt128Parts; + + static write(value: UInt128Parts, io: Buffer): void; + + static isValid(value: UInt128Parts): boolean; + + static toXDR(value: UInt128Parts): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): UInt128Parts; + + static fromXDR(input: string, format: 'hex' | 'base64'): UInt128Parts; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Int128Parts { + constructor(attributes: { hi: Int64; lo: Uint64 }); + + hi(value?: Int64): Int64; + + lo(value?: Uint64): Uint64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Int128Parts; + + static write(value: Int128Parts, io: Buffer): void; + + static isValid(value: Int128Parts): boolean; + + static toXDR(value: Int128Parts): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Int128Parts; + + static fromXDR(input: string, format: 'hex' | 'base64'): Int128Parts; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class UInt256Parts { + constructor(attributes: { + hiHi: Uint64; + hiLo: Uint64; + loHi: Uint64; + loLo: Uint64; + }); + + hiHi(value?: Uint64): Uint64; + + hiLo(value?: Uint64): Uint64; + + loHi(value?: Uint64): Uint64; + + loLo(value?: Uint64): Uint64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): UInt256Parts; + + static write(value: UInt256Parts, io: Buffer): void; + + static isValid(value: UInt256Parts): boolean; + + static toXDR(value: UInt256Parts): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): UInt256Parts; + + static fromXDR(input: string, format: 'hex' | 'base64'): UInt256Parts; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Int256Parts { + constructor(attributes: { + hiHi: Int64; + hiLo: Uint64; + loHi: Uint64; + loLo: Uint64; + }); + + hiHi(value?: Int64): Int64; + + hiLo(value?: Uint64): Uint64; + + loHi(value?: Uint64): Uint64; + + loLo(value?: Uint64): Uint64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Int256Parts; + + static write(value: Int256Parts, io: Buffer): void; + + static isValid(value: Int256Parts): boolean; + + static toXDR(value: Int256Parts): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Int256Parts; + + static fromXDR(input: string, format: 'hex' | 'base64'): Int256Parts; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScNonceKey { + constructor(attributes: { nonce: Int64 }); + + nonce(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScNonceKey; + + static write(value: ScNonceKey, io: Buffer): void; + + static isValid(value: ScNonceKey): boolean; + + static toXDR(value: ScNonceKey): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScNonceKey; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScNonceKey; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScContractInstance { + constructor(attributes: { + executable: ContractExecutable; + storage: null | ScMapEntry[]; + }); + + executable(value?: ContractExecutable): ContractExecutable; + + storage(value?: null | ScMapEntry[]): null | ScMapEntry[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScContractInstance; + + static write(value: ScContractInstance, io: Buffer): void; + + static isValid(value: ScContractInstance): boolean; + + static toXDR(value: ScContractInstance): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScContractInstance; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScContractInstance; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScMapEntry { + constructor(attributes: { key: ScVal; val: ScVal }); + + key(value?: ScVal): ScVal; + + val(value?: ScVal): ScVal; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScMapEntry; + + static write(value: ScMapEntry, io: Buffer): void; + + static isValid(value: ScMapEntry): boolean; + + static toXDR(value: ScMapEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScMapEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScMapEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScEnvMetaEntryInterfaceVersion { + constructor(attributes: { protocol: number; preRelease: number }); + + protocol(value?: number): number; + + preRelease(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScEnvMetaEntryInterfaceVersion; + + static write(value: ScEnvMetaEntryInterfaceVersion, io: Buffer): void; + + static isValid(value: ScEnvMetaEntryInterfaceVersion): boolean; + + static toXDR(value: ScEnvMetaEntryInterfaceVersion): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ScEnvMetaEntryInterfaceVersion; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScEnvMetaEntryInterfaceVersion; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScMetaV0 { + constructor(attributes: { key: string | Buffer; val: string | Buffer }); + + key(value?: string | Buffer): string | Buffer; + + val(value?: string | Buffer): string | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScMetaV0; + + static write(value: ScMetaV0, io: Buffer): void; + + static isValid(value: ScMetaV0): boolean; + + static toXDR(value: ScMetaV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScMetaV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScMetaV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeOption { + constructor(attributes: { valueType: ScSpecTypeDef }); + + valueType(value?: ScSpecTypeDef): ScSpecTypeDef; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeOption; + + static write(value: ScSpecTypeOption, io: Buffer): void; + + static isValid(value: ScSpecTypeOption): boolean; + + static toXDR(value: ScSpecTypeOption): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeOption; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeOption; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeResult { + constructor(attributes: { + okType: ScSpecTypeDef; + errorType: ScSpecTypeDef; + }); + + okType(value?: ScSpecTypeDef): ScSpecTypeDef; + + errorType(value?: ScSpecTypeDef): ScSpecTypeDef; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeResult; + + static write(value: ScSpecTypeResult, io: Buffer): void; + + static isValid(value: ScSpecTypeResult): boolean; + + static toXDR(value: ScSpecTypeResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeVec { + constructor(attributes: { elementType: ScSpecTypeDef }); + + elementType(value?: ScSpecTypeDef): ScSpecTypeDef; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeVec; + + static write(value: ScSpecTypeVec, io: Buffer): void; + + static isValid(value: ScSpecTypeVec): boolean; + + static toXDR(value: ScSpecTypeVec): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeVec; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeVec; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeMap { + constructor(attributes: { + keyType: ScSpecTypeDef; + valueType: ScSpecTypeDef; + }); + + keyType(value?: ScSpecTypeDef): ScSpecTypeDef; + + valueType(value?: ScSpecTypeDef): ScSpecTypeDef; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeMap; + + static write(value: ScSpecTypeMap, io: Buffer): void; + + static isValid(value: ScSpecTypeMap): boolean; + + static toXDR(value: ScSpecTypeMap): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeMap; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeMap; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeTuple { + constructor(attributes: { valueTypes: ScSpecTypeDef[] }); + + valueTypes(value?: ScSpecTypeDef[]): ScSpecTypeDef[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeTuple; + + static write(value: ScSpecTypeTuple, io: Buffer): void; + + static isValid(value: ScSpecTypeTuple): boolean; + + static toXDR(value: ScSpecTypeTuple): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeTuple; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeTuple; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeBytesN { + constructor(attributes: { n: number }); + + n(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeBytesN; + + static write(value: ScSpecTypeBytesN, io: Buffer): void; + + static isValid(value: ScSpecTypeBytesN): boolean; + + static toXDR(value: ScSpecTypeBytesN): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeBytesN; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeBytesN; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeUdt { + constructor(attributes: { name: string | Buffer }); + + name(value?: string | Buffer): string | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeUdt; + + static write(value: ScSpecTypeUdt, io: Buffer): void; + + static isValid(value: ScSpecTypeUdt): boolean; + + static toXDR(value: ScSpecTypeUdt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeUdt; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeUdt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtStructFieldV0 { + constructor(attributes: { + doc: string | Buffer; + name: string | Buffer; + type: ScSpecTypeDef; + }); + + doc(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + type(value?: ScSpecTypeDef): ScSpecTypeDef; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtStructFieldV0; + + static write(value: ScSpecUdtStructFieldV0, io: Buffer): void; + + static isValid(value: ScSpecUdtStructFieldV0): boolean; + + static toXDR(value: ScSpecUdtStructFieldV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtStructFieldV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecUdtStructFieldV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtStructV0 { + constructor(attributes: { + doc: string | Buffer; + lib: string | Buffer; + name: string | Buffer; + fields: ScSpecUdtStructFieldV0[]; + }); + + doc(value?: string | Buffer): string | Buffer; + + lib(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + fields(value?: ScSpecUdtStructFieldV0[]): ScSpecUdtStructFieldV0[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtStructV0; + + static write(value: ScSpecUdtStructV0, io: Buffer): void; + + static isValid(value: ScSpecUdtStructV0): boolean; + + static toXDR(value: ScSpecUdtStructV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtStructV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecUdtStructV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtUnionCaseVoidV0 { + constructor(attributes: { doc: string | Buffer; name: string | Buffer }); + + doc(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtUnionCaseVoidV0; + + static write(value: ScSpecUdtUnionCaseVoidV0, io: Buffer): void; + + static isValid(value: ScSpecUdtUnionCaseVoidV0): boolean; + + static toXDR(value: ScSpecUdtUnionCaseVoidV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtUnionCaseVoidV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecUdtUnionCaseVoidV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtUnionCaseTupleV0 { + constructor(attributes: { + doc: string | Buffer; + name: string | Buffer; + type: ScSpecTypeDef[]; + }); + + doc(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + type(value?: ScSpecTypeDef[]): ScSpecTypeDef[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtUnionCaseTupleV0; + + static write(value: ScSpecUdtUnionCaseTupleV0, io: Buffer): void; + + static isValid(value: ScSpecUdtUnionCaseTupleV0): boolean; + + static toXDR(value: ScSpecUdtUnionCaseTupleV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtUnionCaseTupleV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecUdtUnionCaseTupleV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtUnionV0 { + constructor(attributes: { + doc: string | Buffer; + lib: string | Buffer; + name: string | Buffer; + cases: ScSpecUdtUnionCaseV0[]; + }); + + doc(value?: string | Buffer): string | Buffer; + + lib(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + cases(value?: ScSpecUdtUnionCaseV0[]): ScSpecUdtUnionCaseV0[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtUnionV0; + + static write(value: ScSpecUdtUnionV0, io: Buffer): void; + + static isValid(value: ScSpecUdtUnionV0): boolean; + + static toXDR(value: ScSpecUdtUnionV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtUnionV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecUdtUnionV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtEnumCaseV0 { + constructor(attributes: { + doc: string | Buffer; + name: string | Buffer; + value: number; + }); + + doc(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + value(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtEnumCaseV0; + + static write(value: ScSpecUdtEnumCaseV0, io: Buffer): void; + + static isValid(value: ScSpecUdtEnumCaseV0): boolean; + + static toXDR(value: ScSpecUdtEnumCaseV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtEnumCaseV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecUdtEnumCaseV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtEnumV0 { + constructor(attributes: { + doc: string | Buffer; + lib: string | Buffer; + name: string | Buffer; + cases: ScSpecUdtEnumCaseV0[]; + }); + + doc(value?: string | Buffer): string | Buffer; + + lib(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + cases(value?: ScSpecUdtEnumCaseV0[]): ScSpecUdtEnumCaseV0[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtEnumV0; + + static write(value: ScSpecUdtEnumV0, io: Buffer): void; + + static isValid(value: ScSpecUdtEnumV0): boolean; + + static toXDR(value: ScSpecUdtEnumV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtEnumV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecUdtEnumV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtErrorEnumCaseV0 { + constructor(attributes: { + doc: string | Buffer; + name: string | Buffer; + value: number; + }); + + doc(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + value(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtErrorEnumCaseV0; + + static write(value: ScSpecUdtErrorEnumCaseV0, io: Buffer): void; + + static isValid(value: ScSpecUdtErrorEnumCaseV0): boolean; + + static toXDR(value: ScSpecUdtErrorEnumCaseV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtErrorEnumCaseV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecUdtErrorEnumCaseV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtErrorEnumV0 { + constructor(attributes: { + doc: string | Buffer; + lib: string | Buffer; + name: string | Buffer; + cases: ScSpecUdtErrorEnumCaseV0[]; + }); + + doc(value?: string | Buffer): string | Buffer; + + lib(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + cases(value?: ScSpecUdtErrorEnumCaseV0[]): ScSpecUdtErrorEnumCaseV0[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtErrorEnumV0; + + static write(value: ScSpecUdtErrorEnumV0, io: Buffer): void; + + static isValid(value: ScSpecUdtErrorEnumV0): boolean; + + static toXDR(value: ScSpecUdtErrorEnumV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtErrorEnumV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecUdtErrorEnumV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecFunctionInputV0 { + constructor(attributes: { + doc: string | Buffer; + name: string | Buffer; + type: ScSpecTypeDef; + }); + + doc(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + type(value?: ScSpecTypeDef): ScSpecTypeDef; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecFunctionInputV0; + + static write(value: ScSpecFunctionInputV0, io: Buffer): void; + + static isValid(value: ScSpecFunctionInputV0): boolean; + + static toXDR(value: ScSpecFunctionInputV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecFunctionInputV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecFunctionInputV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecFunctionV0 { + constructor(attributes: { + doc: string | Buffer; + name: string | Buffer; + inputs: ScSpecFunctionInputV0[]; + outputs: ScSpecTypeDef[]; + }); + + doc(value?: string | Buffer): string | Buffer; + + name(value?: string | Buffer): string | Buffer; + + inputs(value?: ScSpecFunctionInputV0[]): ScSpecFunctionInputV0[]; + + outputs(value?: ScSpecTypeDef[]): ScSpecTypeDef[]; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecFunctionV0; + + static write(value: ScSpecFunctionV0, io: Buffer): void; + + static isValid(value: ScSpecFunctionV0): boolean; + + static toXDR(value: ScSpecFunctionV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecFunctionV0; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecFunctionV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingContractExecutionLanesV0 { + constructor(attributes: { ledgerMaxTxCount: number }); + + ledgerMaxTxCount(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingContractExecutionLanesV0; + + static write( + value: ConfigSettingContractExecutionLanesV0, + io: Buffer, + ): void; + + static isValid(value: ConfigSettingContractExecutionLanesV0): boolean; + + static toXDR(value: ConfigSettingContractExecutionLanesV0): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ConfigSettingContractExecutionLanesV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigSettingContractExecutionLanesV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingContractComputeV0 { + constructor(attributes: { + ledgerMaxInstructions: Int64; + txMaxInstructions: Int64; + feeRatePerInstructionsIncrement: Int64; + txMemoryLimit: number; + }); + + ledgerMaxInstructions(value?: Int64): Int64; + + txMaxInstructions(value?: Int64): Int64; + + feeRatePerInstructionsIncrement(value?: Int64): Int64; + + txMemoryLimit(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingContractComputeV0; + + static write(value: ConfigSettingContractComputeV0, io: Buffer): void; + + static isValid(value: ConfigSettingContractComputeV0): boolean; + + static toXDR(value: ConfigSettingContractComputeV0): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ConfigSettingContractComputeV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigSettingContractComputeV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingContractParallelComputeV0 { + constructor(attributes: { ledgerMaxParallelThreads: number }); + + ledgerMaxParallelThreads(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingContractParallelComputeV0; + + static write( + value: ConfigSettingContractParallelComputeV0, + io: Buffer, + ): void; + + static isValid(value: ConfigSettingContractParallelComputeV0): boolean; + + static toXDR(value: ConfigSettingContractParallelComputeV0): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ConfigSettingContractParallelComputeV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigSettingContractParallelComputeV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingContractLedgerCostV0 { + constructor(attributes: { + ledgerMaxReadLedgerEntries: number; + ledgerMaxReadBytes: number; + ledgerMaxWriteLedgerEntries: number; + ledgerMaxWriteBytes: number; + txMaxReadLedgerEntries: number; + txMaxReadBytes: number; + txMaxWriteLedgerEntries: number; + txMaxWriteBytes: number; + feeReadLedgerEntry: Int64; + feeWriteLedgerEntry: Int64; + feeRead1Kb: Int64; + bucketListTargetSizeBytes: Int64; + writeFee1KbBucketListLow: Int64; + writeFee1KbBucketListHigh: Int64; + bucketListWriteFeeGrowthFactor: number; + }); + + ledgerMaxReadLedgerEntries(value?: number): number; + + ledgerMaxReadBytes(value?: number): number; + + ledgerMaxWriteLedgerEntries(value?: number): number; + + ledgerMaxWriteBytes(value?: number): number; + + txMaxReadLedgerEntries(value?: number): number; + + txMaxReadBytes(value?: number): number; + + txMaxWriteLedgerEntries(value?: number): number; + + txMaxWriteBytes(value?: number): number; + + feeReadLedgerEntry(value?: Int64): Int64; + + feeWriteLedgerEntry(value?: Int64): Int64; + + feeRead1Kb(value?: Int64): Int64; + + bucketListTargetSizeBytes(value?: Int64): Int64; + + writeFee1KbBucketListLow(value?: Int64): Int64; + + writeFee1KbBucketListHigh(value?: Int64): Int64; + + bucketListWriteFeeGrowthFactor(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingContractLedgerCostV0; + + static write(value: ConfigSettingContractLedgerCostV0, io: Buffer): void; + + static isValid(value: ConfigSettingContractLedgerCostV0): boolean; + + static toXDR(value: ConfigSettingContractLedgerCostV0): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ConfigSettingContractLedgerCostV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigSettingContractLedgerCostV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingContractHistoricalDataV0 { + constructor(attributes: { feeHistorical1Kb: Int64 }); + + feeHistorical1Kb(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingContractHistoricalDataV0; + + static write( + value: ConfigSettingContractHistoricalDataV0, + io: Buffer, + ): void; + + static isValid(value: ConfigSettingContractHistoricalDataV0): boolean; + + static toXDR(value: ConfigSettingContractHistoricalDataV0): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ConfigSettingContractHistoricalDataV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigSettingContractHistoricalDataV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingContractEventsV0 { + constructor(attributes: { + txMaxContractEventsSizeBytes: number; + feeContractEvents1Kb: Int64; + }); + + txMaxContractEventsSizeBytes(value?: number): number; + + feeContractEvents1Kb(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingContractEventsV0; + + static write(value: ConfigSettingContractEventsV0, io: Buffer): void; + + static isValid(value: ConfigSettingContractEventsV0): boolean; + + static toXDR(value: ConfigSettingContractEventsV0): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ConfigSettingContractEventsV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigSettingContractEventsV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingContractBandwidthV0 { + constructor(attributes: { + ledgerMaxTxsSizeBytes: number; + txMaxSizeBytes: number; + feeTxSize1Kb: Int64; + }); + + ledgerMaxTxsSizeBytes(value?: number): number; + + txMaxSizeBytes(value?: number): number; + + feeTxSize1Kb(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingContractBandwidthV0; + + static write(value: ConfigSettingContractBandwidthV0, io: Buffer): void; + + static isValid(value: ConfigSettingContractBandwidthV0): boolean; + + static toXDR(value: ConfigSettingContractBandwidthV0): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ConfigSettingContractBandwidthV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ConfigSettingContractBandwidthV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractCostParamEntry { + constructor(attributes: { + ext: ExtensionPoint; + constTerm: Int64; + linearTerm: Int64; + }); + + ext(value?: ExtensionPoint): ExtensionPoint; + + constTerm(value?: Int64): Int64; + + linearTerm(value?: Int64): Int64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractCostParamEntry; + + static write(value: ContractCostParamEntry, io: Buffer): void; + + static isValid(value: ContractCostParamEntry): boolean; + + static toXDR(value: ContractCostParamEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractCostParamEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ContractCostParamEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class StateArchivalSettings { + constructor(attributes: { + maxEntryTtl: number; + minTemporaryTtl: number; + minPersistentTtl: number; + persistentRentRateDenominator: Int64; + tempRentRateDenominator: Int64; + maxEntriesToArchive: number; + bucketListSizeWindowSampleSize: number; + bucketListWindowSamplePeriod: number; + evictionScanSize: number; + startingEvictionScanLevel: number; + }); + + maxEntryTtl(value?: number): number; + + minTemporaryTtl(value?: number): number; + + minPersistentTtl(value?: number): number; + + persistentRentRateDenominator(value?: Int64): Int64; + + tempRentRateDenominator(value?: Int64): Int64; + + maxEntriesToArchive(value?: number): number; + + bucketListSizeWindowSampleSize(value?: number): number; + + bucketListWindowSamplePeriod(value?: number): number; + + evictionScanSize(value?: number): number; + + startingEvictionScanLevel(value?: number): number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): StateArchivalSettings; + + static write(value: StateArchivalSettings, io: Buffer): void; + + static isValid(value: StateArchivalSettings): boolean; + + static toXDR(value: StateArchivalSettings): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): StateArchivalSettings; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): StateArchivalSettings; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class EvictionIterator { + constructor(attributes: { + bucketListLevel: number; + isCurrBucket: boolean; + bucketFileOffset: Uint64; + }); + + bucketListLevel(value?: number): number; + + isCurrBucket(value?: boolean): boolean; + + bucketFileOffset(value?: Uint64): Uint64; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): EvictionIterator; + + static write(value: EvictionIterator, io: Buffer): void; + + static isValid(value: EvictionIterator): boolean; + + static toXDR(value: EvictionIterator): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): EvictionIterator; + + static fromXDR(input: string, format: 'hex' | 'base64'): EvictionIterator; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpStatementPledges { + switch(): ScpStatementType; + + prepare(value?: ScpStatementPrepare): ScpStatementPrepare; + + confirm(value?: ScpStatementConfirm): ScpStatementConfirm; + + externalize(value?: ScpStatementExternalize): ScpStatementExternalize; + + nominate(value?: ScpNomination): ScpNomination; + + static scpStPrepare(value: ScpStatementPrepare): ScpStatementPledges; + + static scpStConfirm(value: ScpStatementConfirm): ScpStatementPledges; + + static scpStExternalize( + value: ScpStatementExternalize, + ): ScpStatementPledges; + + static scpStNominate(value: ScpNomination): ScpStatementPledges; + + value(): + | ScpStatementPrepare + | ScpStatementConfirm + | ScpStatementExternalize + | ScpNomination; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpStatementPledges; + + static write(value: ScpStatementPledges, io: Buffer): void; + + static isValid(value: ScpStatementPledges): boolean; + + static toXDR(value: ScpStatementPledges): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpStatementPledges; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScpStatementPledges; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AssetCode { + switch(): AssetType; + + assetCode4(value?: Buffer): Buffer; + + assetCode12(value?: Buffer): Buffer; + + static assetTypeCreditAlphanum4(value: Buffer): AssetCode; + + static assetTypeCreditAlphanum12(value: Buffer): AssetCode; + + value(): Buffer | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AssetCode; + + static write(value: AssetCode, io: Buffer): void; + + static isValid(value: AssetCode): boolean; + + static toXDR(value: AssetCode): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AssetCode; + + static fromXDR(input: string, format: 'hex' | 'base64'): AssetCode; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Asset { + switch(): AssetType; + + alphaNum4(value?: AlphaNum4): AlphaNum4; + + alphaNum12(value?: AlphaNum12): AlphaNum12; + + static assetTypeNative(): Asset; + + static assetTypeCreditAlphanum4(value: AlphaNum4): Asset; + + static assetTypeCreditAlphanum12(value: AlphaNum12): Asset; + + value(): AlphaNum4 | AlphaNum12 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Asset; + + static write(value: Asset, io: Buffer): void; + + static isValid(value: Asset): boolean; + + static toXDR(value: Asset): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Asset; + + static fromXDR(input: string, format: 'hex' | 'base64'): Asset; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountEntryExtensionV2Ext { + switch(): number; + + v3(value?: AccountEntryExtensionV3): AccountEntryExtensionV3; + + static 0(): AccountEntryExtensionV2Ext; + + static 3(value: AccountEntryExtensionV3): AccountEntryExtensionV2Ext; + + value(): AccountEntryExtensionV3 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountEntryExtensionV2Ext; + + static write(value: AccountEntryExtensionV2Ext, io: Buffer): void; + + static isValid(value: AccountEntryExtensionV2Ext): boolean; + + static toXDR(value: AccountEntryExtensionV2Ext): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountEntryExtensionV2Ext; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): AccountEntryExtensionV2Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountEntryExtensionV1Ext { + switch(): number; + + v2(value?: AccountEntryExtensionV2): AccountEntryExtensionV2; + + static 0(): AccountEntryExtensionV1Ext; + + static 2(value: AccountEntryExtensionV2): AccountEntryExtensionV1Ext; + + value(): AccountEntryExtensionV2 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountEntryExtensionV1Ext; + + static write(value: AccountEntryExtensionV1Ext, io: Buffer): void; + + static isValid(value: AccountEntryExtensionV1Ext): boolean; + + static toXDR(value: AccountEntryExtensionV1Ext): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountEntryExtensionV1Ext; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): AccountEntryExtensionV1Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountEntryExt { + switch(): number; + + v1(value?: AccountEntryExtensionV1): AccountEntryExtensionV1; + + static 0(): AccountEntryExt; + + static 1(value: AccountEntryExtensionV1): AccountEntryExt; + + value(): AccountEntryExtensionV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountEntryExt; + + static write(value: AccountEntryExt, io: Buffer): void; + + static isValid(value: AccountEntryExt): boolean; + + static toXDR(value: AccountEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountEntryExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): AccountEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TrustLineAsset { + switch(): AssetType; + + alphaNum4(value?: AlphaNum4): AlphaNum4; + + alphaNum12(value?: AlphaNum12): AlphaNum12; + + liquidityPoolId(value?: PoolId): PoolId; + + static assetTypeNative(): TrustLineAsset; + + static assetTypeCreditAlphanum4(value: AlphaNum4): TrustLineAsset; + + static assetTypeCreditAlphanum12(value: AlphaNum12): TrustLineAsset; + + static assetTypePoolShare(value: PoolId): TrustLineAsset; + + value(): AlphaNum4 | AlphaNum12 | PoolId | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TrustLineAsset; + + static write(value: TrustLineAsset, io: Buffer): void; + + static isValid(value: TrustLineAsset): boolean; + + static toXDR(value: TrustLineAsset): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TrustLineAsset; + + static fromXDR(input: string, format: 'hex' | 'base64'): TrustLineAsset; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TrustLineEntryExtensionV2Ext { + switch(): number; + + static 0(): TrustLineEntryExtensionV2Ext; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TrustLineEntryExtensionV2Ext; + + static write(value: TrustLineEntryExtensionV2Ext, io: Buffer): void; + + static isValid(value: TrustLineEntryExtensionV2Ext): boolean; + + static toXDR(value: TrustLineEntryExtensionV2Ext): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TrustLineEntryExtensionV2Ext; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TrustLineEntryExtensionV2Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TrustLineEntryV1Ext { + switch(): number; + + v2(value?: TrustLineEntryExtensionV2): TrustLineEntryExtensionV2; + + static 0(): TrustLineEntryV1Ext; + + static 2(value: TrustLineEntryExtensionV2): TrustLineEntryV1Ext; + + value(): TrustLineEntryExtensionV2 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TrustLineEntryV1Ext; + + static write(value: TrustLineEntryV1Ext, io: Buffer): void; + + static isValid(value: TrustLineEntryV1Ext): boolean; + + static toXDR(value: TrustLineEntryV1Ext): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TrustLineEntryV1Ext; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TrustLineEntryV1Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TrustLineEntryExt { + switch(): number; + + v1(value?: TrustLineEntryV1): TrustLineEntryV1; + + static 0(): TrustLineEntryExt; + + static 1(value: TrustLineEntryV1): TrustLineEntryExt; + + value(): TrustLineEntryV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TrustLineEntryExt; + + static write(value: TrustLineEntryExt, io: Buffer): void; + + static isValid(value: TrustLineEntryExt): boolean; + + static toXDR(value: TrustLineEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TrustLineEntryExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): TrustLineEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class OfferEntryExt { + switch(): number; + + static 0(): OfferEntryExt; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): OfferEntryExt; + + static write(value: OfferEntryExt, io: Buffer): void; + + static isValid(value: OfferEntryExt): boolean; + + static toXDR(value: OfferEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): OfferEntryExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): OfferEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class DataEntryExt { + switch(): number; + + static 0(): DataEntryExt; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): DataEntryExt; + + static write(value: DataEntryExt, io: Buffer): void; + + static isValid(value: DataEntryExt): boolean; + + static toXDR(value: DataEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): DataEntryExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): DataEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimPredicate { + switch(): ClaimPredicateType; + + andPredicates(value?: ClaimPredicate[]): ClaimPredicate[]; + + orPredicates(value?: ClaimPredicate[]): ClaimPredicate[]; + + notPredicate(value?: null | ClaimPredicate): null | ClaimPredicate; + + absBefore(value?: Int64): Int64; + + relBefore(value?: Int64): Int64; + + static claimPredicateUnconditional(): ClaimPredicate; + + static claimPredicateAnd(value: ClaimPredicate[]): ClaimPredicate; + + static claimPredicateOr(value: ClaimPredicate[]): ClaimPredicate; + + static claimPredicateNot(value: null | ClaimPredicate): ClaimPredicate; + + static claimPredicateBeforeAbsoluteTime(value: Int64): ClaimPredicate; + + static claimPredicateBeforeRelativeTime(value: Int64): ClaimPredicate; + + value(): + | ClaimPredicate[] + | ClaimPredicate[] + | null + | ClaimPredicate + | Int64 + | Int64 + | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimPredicate; + + static write(value: ClaimPredicate, io: Buffer): void; + + static isValid(value: ClaimPredicate): boolean; + + static toXDR(value: ClaimPredicate): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimPredicate; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClaimPredicate; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Claimant { + switch(): ClaimantType; + + v0(value?: ClaimantV0): ClaimantV0; + + static claimantTypeV0(value: ClaimantV0): Claimant; + + value(): ClaimantV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Claimant; + + static write(value: Claimant, io: Buffer): void; + + static isValid(value: Claimant): boolean; + + static toXDR(value: Claimant): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Claimant; + + static fromXDR(input: string, format: 'hex' | 'base64'): Claimant; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimableBalanceId { + switch(): ClaimableBalanceIdType; + + v0(value?: Buffer): Buffer; + + static claimableBalanceIdTypeV0(value: Buffer): ClaimableBalanceId; + + value(): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimableBalanceId; + + static write(value: ClaimableBalanceId, io: Buffer): void; + + static isValid(value: ClaimableBalanceId): boolean; + + static toXDR(value: ClaimableBalanceId): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimableBalanceId; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClaimableBalanceId; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimableBalanceEntryExtensionV1Ext { + switch(): number; + + static 0(): ClaimableBalanceEntryExtensionV1Ext; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimableBalanceEntryExtensionV1Ext; + + static write(value: ClaimableBalanceEntryExtensionV1Ext, io: Buffer): void; + + static isValid(value: ClaimableBalanceEntryExtensionV1Ext): boolean; + + static toXDR(value: ClaimableBalanceEntryExtensionV1Ext): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ClaimableBalanceEntryExtensionV1Ext; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClaimableBalanceEntryExtensionV1Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimableBalanceEntryExt { + switch(): number; + + v1( + value?: ClaimableBalanceEntryExtensionV1, + ): ClaimableBalanceEntryExtensionV1; + + static 0(): ClaimableBalanceEntryExt; + + static 1(value: ClaimableBalanceEntryExtensionV1): ClaimableBalanceEntryExt; + + value(): ClaimableBalanceEntryExtensionV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimableBalanceEntryExt; + + static write(value: ClaimableBalanceEntryExt, io: Buffer): void; + + static isValid(value: ClaimableBalanceEntryExt): boolean; + + static toXDR(value: ClaimableBalanceEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimableBalanceEntryExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClaimableBalanceEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolEntryBody { + switch(): LiquidityPoolType; + + constantProduct( + value?: LiquidityPoolEntryConstantProduct, + ): LiquidityPoolEntryConstantProduct; + + static liquidityPoolConstantProduct( + value: LiquidityPoolEntryConstantProduct, + ): LiquidityPoolEntryBody; + + value(): LiquidityPoolEntryConstantProduct; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolEntryBody; + + static write(value: LiquidityPoolEntryBody, io: Buffer): void; + + static isValid(value: LiquidityPoolEntryBody): boolean; + + static toXDR(value: LiquidityPoolEntryBody): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LiquidityPoolEntryBody; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolEntryBody; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractCodeEntryExt { + switch(): number; + + v1(value?: ContractCodeEntryV1): ContractCodeEntryV1; + + static 0(): ContractCodeEntryExt; + + static 1(value: ContractCodeEntryV1): ContractCodeEntryExt; + + value(): ContractCodeEntryV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractCodeEntryExt; + + static write(value: ContractCodeEntryExt, io: Buffer): void; + + static isValid(value: ContractCodeEntryExt): boolean; + + static toXDR(value: ContractCodeEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractCodeEntryExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ContractCodeEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerEntryExtensionV1Ext { + switch(): number; + + static 0(): LedgerEntryExtensionV1Ext; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerEntryExtensionV1Ext; + + static write(value: LedgerEntryExtensionV1Ext, io: Buffer): void; + + static isValid(value: LedgerEntryExtensionV1Ext): boolean; + + static toXDR(value: LedgerEntryExtensionV1Ext): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerEntryExtensionV1Ext; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerEntryExtensionV1Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerEntryData { + switch(): LedgerEntryType; + + account(value?: AccountEntry): AccountEntry; + + trustLine(value?: TrustLineEntry): TrustLineEntry; + + offer(value?: OfferEntry): OfferEntry; + + data(value?: DataEntry): DataEntry; + + claimableBalance(value?: ClaimableBalanceEntry): ClaimableBalanceEntry; + + liquidityPool(value?: LiquidityPoolEntry): LiquidityPoolEntry; + + contractData(value?: ContractDataEntry): ContractDataEntry; + + contractCode(value?: ContractCodeEntry): ContractCodeEntry; + + configSetting(value?: ConfigSettingEntry): ConfigSettingEntry; + + ttl(value?: TtlEntry): TtlEntry; + + static account(value: AccountEntry): LedgerEntryData; + + static trustline(value: TrustLineEntry): LedgerEntryData; + + static offer(value: OfferEntry): LedgerEntryData; + + static data(value: DataEntry): LedgerEntryData; + + static claimableBalance(value: ClaimableBalanceEntry): LedgerEntryData; + + static liquidityPool(value: LiquidityPoolEntry): LedgerEntryData; + + static contractData(value: ContractDataEntry): LedgerEntryData; + + static contractCode(value: ContractCodeEntry): LedgerEntryData; + + static configSetting(value: ConfigSettingEntry): LedgerEntryData; + + static ttl(value: TtlEntry): LedgerEntryData; + + value(): + | AccountEntry + | TrustLineEntry + | OfferEntry + | DataEntry + | ClaimableBalanceEntry + | LiquidityPoolEntry + | ContractDataEntry + | ContractCodeEntry + | ConfigSettingEntry + | TtlEntry; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerEntryData; + + static write(value: LedgerEntryData, io: Buffer): void; + + static isValid(value: LedgerEntryData): boolean; + + static toXDR(value: LedgerEntryData): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerEntryData; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerEntryData; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerEntryExt { + switch(): number; + + v1(value?: LedgerEntryExtensionV1): LedgerEntryExtensionV1; + + static 0(): LedgerEntryExt; + + static 1(value: LedgerEntryExtensionV1): LedgerEntryExt; + + value(): LedgerEntryExtensionV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerEntryExt; + + static write(value: LedgerEntryExt, io: Buffer): void; + + static isValid(value: LedgerEntryExt): boolean; + + static toXDR(value: LedgerEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerEntryExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerKey { + switch(): LedgerEntryType; + + account(value?: LedgerKeyAccount): LedgerKeyAccount; + + trustLine(value?: LedgerKeyTrustLine): LedgerKeyTrustLine; + + offer(value?: LedgerKeyOffer): LedgerKeyOffer; + + data(value?: LedgerKeyData): LedgerKeyData; + + claimableBalance( + value?: LedgerKeyClaimableBalance, + ): LedgerKeyClaimableBalance; + + liquidityPool(value?: LedgerKeyLiquidityPool): LedgerKeyLiquidityPool; + + contractData(value?: LedgerKeyContractData): LedgerKeyContractData; + + contractCode(value?: LedgerKeyContractCode): LedgerKeyContractCode; + + configSetting(value?: LedgerKeyConfigSetting): LedgerKeyConfigSetting; + + ttl(value?: LedgerKeyTtl): LedgerKeyTtl; + + static account(value: LedgerKeyAccount): LedgerKey; + + static trustline(value: LedgerKeyTrustLine): LedgerKey; + + static offer(value: LedgerKeyOffer): LedgerKey; + + static data(value: LedgerKeyData): LedgerKey; + + static claimableBalance(value: LedgerKeyClaimableBalance): LedgerKey; + + static liquidityPool(value: LedgerKeyLiquidityPool): LedgerKey; + + static contractData(value: LedgerKeyContractData): LedgerKey; + + static contractCode(value: LedgerKeyContractCode): LedgerKey; + + static configSetting(value: LedgerKeyConfigSetting): LedgerKey; + + static ttl(value: LedgerKeyTtl): LedgerKey; + + value(): + | LedgerKeyAccount + | LedgerKeyTrustLine + | LedgerKeyOffer + | LedgerKeyData + | LedgerKeyClaimableBalance + | LedgerKeyLiquidityPool + | LedgerKeyContractData + | LedgerKeyContractCode + | LedgerKeyConfigSetting + | LedgerKeyTtl; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerKey; + + static write(value: LedgerKey, io: Buffer): void; + + static isValid(value: LedgerKey): boolean; + + static toXDR(value: LedgerKey): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerKey; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerKey; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class BucketMetadataExt { + switch(): number; + + bucketListType(value?: BucketListType): BucketListType; + + static 0(): BucketMetadataExt; + + static 1(value: BucketListType): BucketMetadataExt; + + value(): BucketListType | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): BucketMetadataExt; + + static write(value: BucketMetadataExt, io: Buffer): void; + + static isValid(value: BucketMetadataExt): boolean; + + static toXDR(value: BucketMetadataExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): BucketMetadataExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): BucketMetadataExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class BucketEntry { + switch(): BucketEntryType; + + liveEntry(value?: LedgerEntry): LedgerEntry; + + deadEntry(value?: LedgerKey): LedgerKey; + + metaEntry(value?: BucketMetadata): BucketMetadata; + + static liveentry(value: LedgerEntry): BucketEntry; + + static initentry(value: LedgerEntry): BucketEntry; + + static deadentry(value: LedgerKey): BucketEntry; + + static metaentry(value: BucketMetadata): BucketEntry; + + value(): LedgerEntry | LedgerKey | BucketMetadata; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): BucketEntry; + + static write(value: BucketEntry, io: Buffer): void; + + static isValid(value: BucketEntry): boolean; + + static toXDR(value: BucketEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): BucketEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): BucketEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HotArchiveBucketEntry { + switch(): HotArchiveBucketEntryType; + + archivedEntry(value?: LedgerEntry): LedgerEntry; + + key(value?: LedgerKey): LedgerKey; + + metaEntry(value?: BucketMetadata): BucketMetadata; + + static hotArchiveArchived(value: LedgerEntry): HotArchiveBucketEntry; + + static hotArchiveLive(value: LedgerKey): HotArchiveBucketEntry; + + static hotArchiveDeleted(value: LedgerKey): HotArchiveBucketEntry; + + static hotArchiveMetaentry(value: BucketMetadata): HotArchiveBucketEntry; + + value(): LedgerEntry | LedgerKey | BucketMetadata; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HotArchiveBucketEntry; + + static write(value: HotArchiveBucketEntry, io: Buffer): void; + + static isValid(value: HotArchiveBucketEntry): boolean; + + static toXDR(value: HotArchiveBucketEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HotArchiveBucketEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): HotArchiveBucketEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ColdArchiveBucketEntry { + switch(): ColdArchiveBucketEntryType; + + metaEntry(value?: BucketMetadata): BucketMetadata; + + archivedLeaf(value?: ColdArchiveArchivedLeaf): ColdArchiveArchivedLeaf; + + deletedLeaf(value?: ColdArchiveDeletedLeaf): ColdArchiveDeletedLeaf; + + boundaryLeaf(value?: ColdArchiveBoundaryLeaf): ColdArchiveBoundaryLeaf; + + hashEntry(value?: ColdArchiveHashEntry): ColdArchiveHashEntry; + + static coldArchiveMetaentry(value: BucketMetadata): ColdArchiveBucketEntry; + + static coldArchiveArchivedLeaf( + value: ColdArchiveArchivedLeaf, + ): ColdArchiveBucketEntry; + + static coldArchiveDeletedLeaf( + value: ColdArchiveDeletedLeaf, + ): ColdArchiveBucketEntry; + + static coldArchiveBoundaryLeaf( + value: ColdArchiveBoundaryLeaf, + ): ColdArchiveBucketEntry; + + static coldArchiveHash(value: ColdArchiveHashEntry): ColdArchiveBucketEntry; + + value(): + | BucketMetadata + | ColdArchiveArchivedLeaf + | ColdArchiveDeletedLeaf + | ColdArchiveBoundaryLeaf + | ColdArchiveHashEntry; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ColdArchiveBucketEntry; + + static write(value: ColdArchiveBucketEntry, io: Buffer): void; + + static isValid(value: ColdArchiveBucketEntry): boolean; + + static toXDR(value: ColdArchiveBucketEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ColdArchiveBucketEntry; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ColdArchiveBucketEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class StellarValueExt { + switch(): StellarValueType; + + lcValueSignature( + value?: LedgerCloseValueSignature, + ): LedgerCloseValueSignature; + + static stellarValueBasic(): StellarValueExt; + + static stellarValueSigned( + value: LedgerCloseValueSignature, + ): StellarValueExt; + + value(): LedgerCloseValueSignature | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): StellarValueExt; + + static write(value: StellarValueExt, io: Buffer): void; + + static isValid(value: StellarValueExt): boolean; + + static toXDR(value: StellarValueExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): StellarValueExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): StellarValueExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerHeaderExtensionV1Ext { + switch(): number; + + static 0(): LedgerHeaderExtensionV1Ext; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerHeaderExtensionV1Ext; + + static write(value: LedgerHeaderExtensionV1Ext, io: Buffer): void; + + static isValid(value: LedgerHeaderExtensionV1Ext): boolean; + + static toXDR(value: LedgerHeaderExtensionV1Ext): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerHeaderExtensionV1Ext; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerHeaderExtensionV1Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerHeaderExt { + switch(): number; + + v1(value?: LedgerHeaderExtensionV1): LedgerHeaderExtensionV1; + + static 0(): LedgerHeaderExt; + + static 1(value: LedgerHeaderExtensionV1): LedgerHeaderExt; + + value(): LedgerHeaderExtensionV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerHeaderExt; + + static write(value: LedgerHeaderExt, io: Buffer): void; + + static isValid(value: LedgerHeaderExt): boolean; + + static toXDR(value: LedgerHeaderExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerHeaderExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerHeaderExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerUpgrade { + switch(): LedgerUpgradeType; + + newLedgerVersion(value?: number): number; + + newBaseFee(value?: number): number; + + newMaxTxSetSize(value?: number): number; + + newBaseReserve(value?: number): number; + + newFlags(value?: number): number; + + newConfig(value?: ConfigUpgradeSetKey): ConfigUpgradeSetKey; + + newMaxSorobanTxSetSize(value?: number): number; + + static ledgerUpgradeVersion(value: number): LedgerUpgrade; + + static ledgerUpgradeBaseFee(value: number): LedgerUpgrade; + + static ledgerUpgradeMaxTxSetSize(value: number): LedgerUpgrade; + + static ledgerUpgradeBaseReserve(value: number): LedgerUpgrade; + + static ledgerUpgradeFlags(value: number): LedgerUpgrade; + + static ledgerUpgradeConfig(value: ConfigUpgradeSetKey): LedgerUpgrade; + + static ledgerUpgradeMaxSorobanTxSetSize(value: number): LedgerUpgrade; + + value(): + | number + | number + | number + | number + | number + | ConfigUpgradeSetKey + | number; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerUpgrade; + + static write(value: LedgerUpgrade, io: Buffer): void; + + static isValid(value: LedgerUpgrade): boolean; + + static toXDR(value: LedgerUpgrade): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerUpgrade; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerUpgrade; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TxSetComponent { + switch(): TxSetComponentType; + + txsMaybeDiscountedFee( + value?: TxSetComponentTxsMaybeDiscountedFee, + ): TxSetComponentTxsMaybeDiscountedFee; + + static txsetCompTxsMaybeDiscountedFee( + value: TxSetComponentTxsMaybeDiscountedFee, + ): TxSetComponent; + + value(): TxSetComponentTxsMaybeDiscountedFee; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TxSetComponent; + + static write(value: TxSetComponent, io: Buffer): void; + + static isValid(value: TxSetComponent): boolean; + + static toXDR(value: TxSetComponent): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TxSetComponent; + + static fromXDR(input: string, format: 'hex' | 'base64'): TxSetComponent; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionPhase { + switch(): number; + + v0Components(value?: TxSetComponent[]): TxSetComponent[]; + + parallelTxsComponent(value?: ParallelTxsComponent): ParallelTxsComponent; + + static 0(value: TxSetComponent[]): TransactionPhase; + + static 1(value: ParallelTxsComponent): TransactionPhase; + + value(): TxSetComponent[] | ParallelTxsComponent; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionPhase; + + static write(value: TransactionPhase, io: Buffer): void; + + static isValid(value: TransactionPhase): boolean; + + static toXDR(value: TransactionPhase): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionPhase; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionPhase; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class GeneralizedTransactionSet { + switch(): number; + + v1TxSet(value?: TransactionSetV1): TransactionSetV1; + + static 1(value: TransactionSetV1): GeneralizedTransactionSet; + + value(): TransactionSetV1; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): GeneralizedTransactionSet; + + static write(value: GeneralizedTransactionSet, io: Buffer): void; + + static isValid(value: GeneralizedTransactionSet): boolean; + + static toXDR(value: GeneralizedTransactionSet): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): GeneralizedTransactionSet; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): GeneralizedTransactionSet; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionHistoryEntryExt { + switch(): number; + + generalizedTxSet( + value?: GeneralizedTransactionSet, + ): GeneralizedTransactionSet; + + static 0(): TransactionHistoryEntryExt; + + static 1(value: GeneralizedTransactionSet): TransactionHistoryEntryExt; + + value(): GeneralizedTransactionSet | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionHistoryEntryExt; + + static write(value: TransactionHistoryEntryExt, io: Buffer): void; + + static isValid(value: TransactionHistoryEntryExt): boolean; + + static toXDR(value: TransactionHistoryEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionHistoryEntryExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionHistoryEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionHistoryResultEntryExt { + switch(): number; + + static 0(): TransactionHistoryResultEntryExt; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionHistoryResultEntryExt; + + static write(value: TransactionHistoryResultEntryExt, io: Buffer): void; + + static isValid(value: TransactionHistoryResultEntryExt): boolean; + + static toXDR(value: TransactionHistoryResultEntryExt): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TransactionHistoryResultEntryExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionHistoryResultEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerHeaderHistoryEntryExt { + switch(): number; + + static 0(): LedgerHeaderHistoryEntryExt; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerHeaderHistoryEntryExt; + + static write(value: LedgerHeaderHistoryEntryExt, io: Buffer): void; + + static isValid(value: LedgerHeaderHistoryEntryExt): boolean; + + static toXDR(value: LedgerHeaderHistoryEntryExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerHeaderHistoryEntryExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LedgerHeaderHistoryEntryExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScpHistoryEntry { + switch(): number; + + v0(value?: ScpHistoryEntryV0): ScpHistoryEntryV0; + + static 0(value: ScpHistoryEntryV0): ScpHistoryEntry; + + value(): ScpHistoryEntryV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScpHistoryEntry; + + static write(value: ScpHistoryEntry, io: Buffer): void; + + static isValid(value: ScpHistoryEntry): boolean; + + static toXDR(value: ScpHistoryEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScpHistoryEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScpHistoryEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerEntryChange { + switch(): LedgerEntryChangeType; + + created(value?: LedgerEntry): LedgerEntry; + + updated(value?: LedgerEntry): LedgerEntry; + + removed(value?: LedgerKey): LedgerKey; + + state(value?: LedgerEntry): LedgerEntry; + + static ledgerEntryCreated(value: LedgerEntry): LedgerEntryChange; + + static ledgerEntryUpdated(value: LedgerEntry): LedgerEntryChange; + + static ledgerEntryRemoved(value: LedgerKey): LedgerEntryChange; + + static ledgerEntryState(value: LedgerEntry): LedgerEntryChange; + + value(): LedgerEntry | LedgerEntry | LedgerKey | LedgerEntry; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerEntryChange; + + static write(value: LedgerEntryChange, io: Buffer): void; + + static isValid(value: LedgerEntryChange): boolean; + + static toXDR(value: LedgerEntryChange): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerEntryChange; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerEntryChange; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractEventBody { + switch(): number; + + v0(value?: ContractEventV0): ContractEventV0; + + static 0(value: ContractEventV0): ContractEventBody; + + value(): ContractEventV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractEventBody; + + static write(value: ContractEventBody, io: Buffer): void; + + static isValid(value: ContractEventBody): boolean; + + static toXDR(value: ContractEventBody): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractEventBody; + + static fromXDR(input: string, format: 'hex' | 'base64'): ContractEventBody; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanTransactionMetaExt { + switch(): number; + + v1(value?: SorobanTransactionMetaExtV1): SorobanTransactionMetaExtV1; + + static 0(): SorobanTransactionMetaExt; + + static 1(value: SorobanTransactionMetaExtV1): SorobanTransactionMetaExt; + + value(): SorobanTransactionMetaExtV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanTransactionMetaExt; + + static write(value: SorobanTransactionMetaExt, io: Buffer): void; + + static isValid(value: SorobanTransactionMetaExt): boolean; + + static toXDR(value: SorobanTransactionMetaExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanTransactionMetaExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanTransactionMetaExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionMeta { + switch(): number; + + operations(value?: OperationMeta[]): OperationMeta[]; + + v1(value?: TransactionMetaV1): TransactionMetaV1; + + v2(value?: TransactionMetaV2): TransactionMetaV2; + + v3(value?: TransactionMetaV3): TransactionMetaV3; + + static 0(value: OperationMeta[]): TransactionMeta; + + static 1(value: TransactionMetaV1): TransactionMeta; + + static 2(value: TransactionMetaV2): TransactionMeta; + + static 3(value: TransactionMetaV3): TransactionMeta; + + value(): + | OperationMeta[] + | TransactionMetaV1 + | TransactionMetaV2 + | TransactionMetaV3; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionMeta; + + static write(value: TransactionMeta, io: Buffer): void; + + static isValid(value: TransactionMeta): boolean; + + static toXDR(value: TransactionMeta): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionMeta; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionMeta; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerCloseMetaExt { + switch(): number; + + v1(value?: LedgerCloseMetaExtV1): LedgerCloseMetaExtV1; + + static 0(): LedgerCloseMetaExt; + + static 1(value: LedgerCloseMetaExtV1): LedgerCloseMetaExt; + + value(): LedgerCloseMetaExtV1 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerCloseMetaExt; + + static write(value: LedgerCloseMetaExt, io: Buffer): void; + + static isValid(value: LedgerCloseMetaExt): boolean; + + static toXDR(value: LedgerCloseMetaExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerCloseMetaExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerCloseMetaExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LedgerCloseMeta { + switch(): number; + + v0(value?: LedgerCloseMetaV0): LedgerCloseMetaV0; + + v1(value?: LedgerCloseMetaV1): LedgerCloseMetaV1; + + static 0(value: LedgerCloseMetaV0): LedgerCloseMeta; + + static 1(value: LedgerCloseMetaV1): LedgerCloseMeta; + + value(): LedgerCloseMetaV0 | LedgerCloseMetaV1; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LedgerCloseMeta; + + static write(value: LedgerCloseMeta, io: Buffer): void; + + static isValid(value: LedgerCloseMeta): boolean; + + static toXDR(value: LedgerCloseMeta): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LedgerCloseMeta; + + static fromXDR(input: string, format: 'hex' | 'base64'): LedgerCloseMeta; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PeerAddressIp { + switch(): IpAddrType; + + ipv4(value?: Buffer): Buffer; + + ipv6(value?: Buffer): Buffer; + + static iPv4(value: Buffer): PeerAddressIp; + + static iPv6(value: Buffer): PeerAddressIp; + + value(): Buffer | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PeerAddressIp; + + static write(value: PeerAddressIp, io: Buffer): void; + + static isValid(value: PeerAddressIp): boolean; + + static toXDR(value: PeerAddressIp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PeerAddressIp; + + static fromXDR(input: string, format: 'hex' | 'base64'): PeerAddressIp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SurveyResponseBody { + switch(): SurveyMessageResponseType; + + topologyResponseBodyV0( + value?: TopologyResponseBodyV0, + ): TopologyResponseBodyV0; + + topologyResponseBodyV1( + value?: TopologyResponseBodyV1, + ): TopologyResponseBodyV1; + + topologyResponseBodyV2( + value?: TopologyResponseBodyV2, + ): TopologyResponseBodyV2; + + static surveyTopologyResponseV0( + value: TopologyResponseBodyV0, + ): SurveyResponseBody; + + static surveyTopologyResponseV1( + value: TopologyResponseBodyV1, + ): SurveyResponseBody; + + static surveyTopologyResponseV2( + value: TopologyResponseBodyV2, + ): SurveyResponseBody; + + value(): + | TopologyResponseBodyV0 + | TopologyResponseBodyV1 + | TopologyResponseBodyV2; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SurveyResponseBody; + + static write(value: SurveyResponseBody, io: Buffer): void; + + static isValid(value: SurveyResponseBody): boolean; + + static toXDR(value: SurveyResponseBody): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SurveyResponseBody; + + static fromXDR(input: string, format: 'hex' | 'base64'): SurveyResponseBody; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class StellarMessage { + switch(): MessageType; + + error(value?: Error): Error; + + hello(value?: Hello): Hello; + + auth(value?: Auth): Auth; + + dontHave(value?: DontHave): DontHave; + + peers(value?: PeerAddress[]): PeerAddress[]; + + txSetHash(value?: Buffer): Buffer; + + txSet(value?: TransactionSet): TransactionSet; + + generalizedTxSet( + value?: GeneralizedTransactionSet, + ): GeneralizedTransactionSet; + + transaction(value?: TransactionEnvelope): TransactionEnvelope; + + signedSurveyRequestMessage( + value?: SignedSurveyRequestMessage, + ): SignedSurveyRequestMessage; + + signedSurveyResponseMessage( + value?: SignedSurveyResponseMessage, + ): SignedSurveyResponseMessage; + + signedTimeSlicedSurveyRequestMessage( + value?: SignedTimeSlicedSurveyRequestMessage, + ): SignedTimeSlicedSurveyRequestMessage; + + signedTimeSlicedSurveyResponseMessage( + value?: SignedTimeSlicedSurveyResponseMessage, + ): SignedTimeSlicedSurveyResponseMessage; + + signedTimeSlicedSurveyStartCollectingMessage( + value?: SignedTimeSlicedSurveyStartCollectingMessage, + ): SignedTimeSlicedSurveyStartCollectingMessage; + + signedTimeSlicedSurveyStopCollectingMessage( + value?: SignedTimeSlicedSurveyStopCollectingMessage, + ): SignedTimeSlicedSurveyStopCollectingMessage; + + qSetHash(value?: Buffer): Buffer; + + qSet(value?: ScpQuorumSet): ScpQuorumSet; + + envelope(value?: ScpEnvelope): ScpEnvelope; + + getScpLedgerSeq(value?: number): number; + + sendMoreMessage(value?: SendMore): SendMore; + + sendMoreExtendedMessage(value?: SendMoreExtended): SendMoreExtended; + + floodAdvert(value?: FloodAdvert): FloodAdvert; + + floodDemand(value?: FloodDemand): FloodDemand; + + static errorMsg(value: Error): StellarMessage; + + static hello(value: Hello): StellarMessage; + + static auth(value: Auth): StellarMessage; + + static dontHave(value: DontHave): StellarMessage; + + static getPeers(): StellarMessage; + + static peers(value: PeerAddress[]): StellarMessage; + + static getTxSet(value: Buffer): StellarMessage; + + static txSet(value: TransactionSet): StellarMessage; + + static generalizedTxSet(value: GeneralizedTransactionSet): StellarMessage; + + static transaction(value: TransactionEnvelope): StellarMessage; + + static surveyRequest(value: SignedSurveyRequestMessage): StellarMessage; + + static surveyResponse(value: SignedSurveyResponseMessage): StellarMessage; + + static timeSlicedSurveyRequest( + value: SignedTimeSlicedSurveyRequestMessage, + ): StellarMessage; + + static timeSlicedSurveyResponse( + value: SignedTimeSlicedSurveyResponseMessage, + ): StellarMessage; + + static timeSlicedSurveyStartCollecting( + value: SignedTimeSlicedSurveyStartCollectingMessage, + ): StellarMessage; + + static timeSlicedSurveyStopCollecting( + value: SignedTimeSlicedSurveyStopCollectingMessage, + ): StellarMessage; + + static getScpQuorumset(value: Buffer): StellarMessage; + + static scpQuorumset(value: ScpQuorumSet): StellarMessage; + + static scpMessage(value: ScpEnvelope): StellarMessage; + + static getScpState(value: number): StellarMessage; + + static sendMore(value: SendMore): StellarMessage; + + static sendMoreExtended(value: SendMoreExtended): StellarMessage; + + static floodAdvert(value: FloodAdvert): StellarMessage; + + static floodDemand(value: FloodDemand): StellarMessage; + + value(): + | Error + | Hello + | Auth + | DontHave + | PeerAddress[] + | Buffer + | TransactionSet + | GeneralizedTransactionSet + | TransactionEnvelope + | SignedSurveyRequestMessage + | SignedSurveyResponseMessage + | SignedTimeSlicedSurveyRequestMessage + | SignedTimeSlicedSurveyResponseMessage + | SignedTimeSlicedSurveyStartCollectingMessage + | SignedTimeSlicedSurveyStopCollectingMessage + | Buffer + | ScpQuorumSet + | ScpEnvelope + | number + | SendMore + | SendMoreExtended + | FloodAdvert + | FloodDemand + | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): StellarMessage; + + static write(value: StellarMessage, io: Buffer): void; + + static isValid(value: StellarMessage): boolean; + + static toXDR(value: StellarMessage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): StellarMessage; + + static fromXDR(input: string, format: 'hex' | 'base64'): StellarMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AuthenticatedMessage { + switch(): number; + + v0(value?: AuthenticatedMessageV0): AuthenticatedMessageV0; + + static 0(value: AuthenticatedMessageV0): AuthenticatedMessage; + + value(): AuthenticatedMessageV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AuthenticatedMessage; + + static write(value: AuthenticatedMessage, io: Buffer): void; + + static isValid(value: AuthenticatedMessage): boolean; + + static toXDR(value: AuthenticatedMessage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AuthenticatedMessage; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): AuthenticatedMessage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolParameters { + switch(): LiquidityPoolType; + + constantProduct( + value?: LiquidityPoolConstantProductParameters, + ): LiquidityPoolConstantProductParameters; + + static liquidityPoolConstantProduct( + value: LiquidityPoolConstantProductParameters, + ): LiquidityPoolParameters; + + value(): LiquidityPoolConstantProductParameters; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolParameters; + + static write(value: LiquidityPoolParameters, io: Buffer): void; + + static isValid(value: LiquidityPoolParameters): boolean; + + static toXDR(value: LiquidityPoolParameters): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LiquidityPoolParameters; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolParameters; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class MuxedAccount { + switch(): CryptoKeyType; + + ed25519(value?: Buffer): Buffer; + + med25519(value?: MuxedAccountMed25519): MuxedAccountMed25519; + + static keyTypeEd25519(value: Buffer): MuxedAccount; + + static keyTypeMuxedEd25519(value: MuxedAccountMed25519): MuxedAccount; + + value(): Buffer | MuxedAccountMed25519; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): MuxedAccount; + + static write(value: MuxedAccount, io: Buffer): void; + + static isValid(value: MuxedAccount): boolean; + + static toXDR(value: MuxedAccount): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): MuxedAccount; + + static fromXDR(input: string, format: 'hex' | 'base64'): MuxedAccount; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ChangeTrustAsset { + switch(): AssetType; + + alphaNum4(value?: AlphaNum4): AlphaNum4; + + alphaNum12(value?: AlphaNum12): AlphaNum12; + + liquidityPool(value?: LiquidityPoolParameters): LiquidityPoolParameters; + + static assetTypeNative(): ChangeTrustAsset; + + static assetTypeCreditAlphanum4(value: AlphaNum4): ChangeTrustAsset; + + static assetTypeCreditAlphanum12(value: AlphaNum12): ChangeTrustAsset; + + static assetTypePoolShare(value: LiquidityPoolParameters): ChangeTrustAsset; + + value(): AlphaNum4 | AlphaNum12 | LiquidityPoolParameters | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ChangeTrustAsset; + + static write(value: ChangeTrustAsset, io: Buffer): void; + + static isValid(value: ChangeTrustAsset): boolean; + + static toXDR(value: ChangeTrustAsset): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ChangeTrustAsset; + + static fromXDR(input: string, format: 'hex' | 'base64'): ChangeTrustAsset; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class RevokeSponsorshipOp { + switch(): RevokeSponsorshipType; + + ledgerKey(value?: LedgerKey): LedgerKey; + + signer(value?: RevokeSponsorshipOpSigner): RevokeSponsorshipOpSigner; + + static revokeSponsorshipLedgerEntry(value: LedgerKey): RevokeSponsorshipOp; + + static revokeSponsorshipSigner( + value: RevokeSponsorshipOpSigner, + ): RevokeSponsorshipOp; + + value(): LedgerKey | RevokeSponsorshipOpSigner; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): RevokeSponsorshipOp; + + static write(value: RevokeSponsorshipOp, io: Buffer): void; + + static isValid(value: RevokeSponsorshipOp): boolean; + + static toXDR(value: RevokeSponsorshipOp): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): RevokeSponsorshipOp; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): RevokeSponsorshipOp; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractIdPreimage { + switch(): ContractIdPreimageType; + + fromAddress( + value?: ContractIdPreimageFromAddress, + ): ContractIdPreimageFromAddress; + + fromAsset(value?: Asset): Asset; + + static contractIdPreimageFromAddress( + value: ContractIdPreimageFromAddress, + ): ContractIdPreimage; + + static contractIdPreimageFromAsset(value: Asset): ContractIdPreimage; + + value(): ContractIdPreimageFromAddress | Asset; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractIdPreimage; + + static write(value: ContractIdPreimage, io: Buffer): void; + + static isValid(value: ContractIdPreimage): boolean; + + static toXDR(value: ContractIdPreimage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractIdPreimage; + + static fromXDR(input: string, format: 'hex' | 'base64'): ContractIdPreimage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HostFunction { + switch(): HostFunctionType; + + invokeContract(value?: InvokeContractArgs): InvokeContractArgs; + + createContract(value?: CreateContractArgs): CreateContractArgs; + + wasm(value?: Buffer): Buffer; + + createContractV2(value?: CreateContractArgsV2): CreateContractArgsV2; + + static hostFunctionTypeInvokeContract( + value: InvokeContractArgs, + ): HostFunction; + + static hostFunctionTypeCreateContract( + value: CreateContractArgs, + ): HostFunction; + + static hostFunctionTypeUploadContractWasm(value: Buffer): HostFunction; + + static hostFunctionTypeCreateContractV2( + value: CreateContractArgsV2, + ): HostFunction; + + value(): + | InvokeContractArgs + | CreateContractArgs + | Buffer + | CreateContractArgsV2; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HostFunction; + + static write(value: HostFunction, io: Buffer): void; + + static isValid(value: HostFunction): boolean; + + static toXDR(value: HostFunction): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HostFunction; + + static fromXDR(input: string, format: 'hex' | 'base64'): HostFunction; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanAuthorizedFunction { + switch(): SorobanAuthorizedFunctionType; + + contractFn(value?: InvokeContractArgs): InvokeContractArgs; + + createContractHostFn(value?: CreateContractArgs): CreateContractArgs; + + createContractV2HostFn(value?: CreateContractArgsV2): CreateContractArgsV2; + + static sorobanAuthorizedFunctionTypeContractFn( + value: InvokeContractArgs, + ): SorobanAuthorizedFunction; + + static sorobanAuthorizedFunctionTypeCreateContractHostFn( + value: CreateContractArgs, + ): SorobanAuthorizedFunction; + + static sorobanAuthorizedFunctionTypeCreateContractV2HostFn( + value: CreateContractArgsV2, + ): SorobanAuthorizedFunction; + + value(): InvokeContractArgs | CreateContractArgs | CreateContractArgsV2; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanAuthorizedFunction; + + static write(value: SorobanAuthorizedFunction, io: Buffer): void; + + static isValid(value: SorobanAuthorizedFunction): boolean; + + static toXDR(value: SorobanAuthorizedFunction): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanAuthorizedFunction; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanAuthorizedFunction; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanCredentials { + switch(): SorobanCredentialsType; + + address(value?: SorobanAddressCredentials): SorobanAddressCredentials; + + static sorobanCredentialsSourceAccount(): SorobanCredentials; + + static sorobanCredentialsAddress( + value: SorobanAddressCredentials, + ): SorobanCredentials; + + value(): SorobanAddressCredentials | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanCredentials; + + static write(value: SorobanCredentials, io: Buffer): void; + + static isValid(value: SorobanCredentials): boolean; + + static toXDR(value: SorobanCredentials): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanCredentials; + + static fromXDR(input: string, format: 'hex' | 'base64'): SorobanCredentials; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class OperationBody { + switch(): OperationType; + + createAccountOp(value?: CreateAccountOp): CreateAccountOp; + + paymentOp(value?: PaymentOp): PaymentOp; + + pathPaymentStrictReceiveOp( + value?: PathPaymentStrictReceiveOp, + ): PathPaymentStrictReceiveOp; + + manageSellOfferOp(value?: ManageSellOfferOp): ManageSellOfferOp; + + createPassiveSellOfferOp( + value?: CreatePassiveSellOfferOp, + ): CreatePassiveSellOfferOp; + + setOptionsOp(value?: SetOptionsOp): SetOptionsOp; + + changeTrustOp(value?: ChangeTrustOp): ChangeTrustOp; + + allowTrustOp(value?: AllowTrustOp): AllowTrustOp; + + destination(value?: MuxedAccount): MuxedAccount; + + manageDataOp(value?: ManageDataOp): ManageDataOp; + + bumpSequenceOp(value?: BumpSequenceOp): BumpSequenceOp; + + manageBuyOfferOp(value?: ManageBuyOfferOp): ManageBuyOfferOp; + + pathPaymentStrictSendOp( + value?: PathPaymentStrictSendOp, + ): PathPaymentStrictSendOp; + + createClaimableBalanceOp( + value?: CreateClaimableBalanceOp, + ): CreateClaimableBalanceOp; + + claimClaimableBalanceOp( + value?: ClaimClaimableBalanceOp, + ): ClaimClaimableBalanceOp; + + beginSponsoringFutureReservesOp( + value?: BeginSponsoringFutureReservesOp, + ): BeginSponsoringFutureReservesOp; + + revokeSponsorshipOp(value?: RevokeSponsorshipOp): RevokeSponsorshipOp; + + clawbackOp(value?: ClawbackOp): ClawbackOp; + + clawbackClaimableBalanceOp( + value?: ClawbackClaimableBalanceOp, + ): ClawbackClaimableBalanceOp; + + setTrustLineFlagsOp(value?: SetTrustLineFlagsOp): SetTrustLineFlagsOp; + + liquidityPoolDepositOp( + value?: LiquidityPoolDepositOp, + ): LiquidityPoolDepositOp; + + liquidityPoolWithdrawOp( + value?: LiquidityPoolWithdrawOp, + ): LiquidityPoolWithdrawOp; + + invokeHostFunctionOp(value?: InvokeHostFunctionOp): InvokeHostFunctionOp; + + extendFootprintTtlOp(value?: ExtendFootprintTtlOp): ExtendFootprintTtlOp; + + restoreFootprintOp(value?: RestoreFootprintOp): RestoreFootprintOp; + + static createAccount(value: CreateAccountOp): OperationBody; + + static payment(value: PaymentOp): OperationBody; + + static pathPaymentStrictReceive( + value: PathPaymentStrictReceiveOp, + ): OperationBody; + + static manageSellOffer(value: ManageSellOfferOp): OperationBody; + + static createPassiveSellOffer( + value: CreatePassiveSellOfferOp, + ): OperationBody; + + static setOptions(value: SetOptionsOp): OperationBody; + + static changeTrust(value: ChangeTrustOp): OperationBody; + + static allowTrust(value: AllowTrustOp): OperationBody; + + static accountMerge(value: MuxedAccount): OperationBody; + + static inflation(): OperationBody; + + static manageData(value: ManageDataOp): OperationBody; + + static bumpSequence(value: BumpSequenceOp): OperationBody; + + static manageBuyOffer(value: ManageBuyOfferOp): OperationBody; + + static pathPaymentStrictSend(value: PathPaymentStrictSendOp): OperationBody; + + static createClaimableBalance( + value: CreateClaimableBalanceOp, + ): OperationBody; + + static claimClaimableBalance(value: ClaimClaimableBalanceOp): OperationBody; + + static beginSponsoringFutureReserves( + value: BeginSponsoringFutureReservesOp, + ): OperationBody; + + static endSponsoringFutureReserves(): OperationBody; + + static revokeSponsorship(value: RevokeSponsorshipOp): OperationBody; + + static clawback(value: ClawbackOp): OperationBody; + + static clawbackClaimableBalance( + value: ClawbackClaimableBalanceOp, + ): OperationBody; + + static setTrustLineFlags(value: SetTrustLineFlagsOp): OperationBody; + + static liquidityPoolDeposit(value: LiquidityPoolDepositOp): OperationBody; + + static liquidityPoolWithdraw(value: LiquidityPoolWithdrawOp): OperationBody; + + static invokeHostFunction(value: InvokeHostFunctionOp): OperationBody; + + static extendFootprintTtl(value: ExtendFootprintTtlOp): OperationBody; + + static restoreFootprint(value: RestoreFootprintOp): OperationBody; + + value(): + | CreateAccountOp + | PaymentOp + | PathPaymentStrictReceiveOp + | ManageSellOfferOp + | CreatePassiveSellOfferOp + | SetOptionsOp + | ChangeTrustOp + | AllowTrustOp + | MuxedAccount + | ManageDataOp + | BumpSequenceOp + | ManageBuyOfferOp + | PathPaymentStrictSendOp + | CreateClaimableBalanceOp + | ClaimClaimableBalanceOp + | BeginSponsoringFutureReservesOp + | RevokeSponsorshipOp + | ClawbackOp + | ClawbackClaimableBalanceOp + | SetTrustLineFlagsOp + | LiquidityPoolDepositOp + | LiquidityPoolWithdrawOp + | InvokeHostFunctionOp + | ExtendFootprintTtlOp + | RestoreFootprintOp + | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): OperationBody; + + static write(value: OperationBody, io: Buffer): void; + + static isValid(value: OperationBody): boolean; + + static toXDR(value: OperationBody): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): OperationBody; + + static fromXDR(input: string, format: 'hex' | 'base64'): OperationBody; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class HashIdPreimage { + switch(): EnvelopeType; + + operationId(value?: HashIdPreimageOperationId): HashIdPreimageOperationId; + + revokeId(value?: HashIdPreimageRevokeId): HashIdPreimageRevokeId; + + contractId(value?: HashIdPreimageContractId): HashIdPreimageContractId; + + sorobanAuthorization( + value?: HashIdPreimageSorobanAuthorization, + ): HashIdPreimageSorobanAuthorization; + + static envelopeTypeOpId(value: HashIdPreimageOperationId): HashIdPreimage; + + static envelopeTypePoolRevokeOpId( + value: HashIdPreimageRevokeId, + ): HashIdPreimage; + + static envelopeTypeContractId( + value: HashIdPreimageContractId, + ): HashIdPreimage; + + static envelopeTypeSorobanAuthorization( + value: HashIdPreimageSorobanAuthorization, + ): HashIdPreimage; + + value(): + | HashIdPreimageOperationId + | HashIdPreimageRevokeId + | HashIdPreimageContractId + | HashIdPreimageSorobanAuthorization; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): HashIdPreimage; + + static write(value: HashIdPreimage, io: Buffer): void; + + static isValid(value: HashIdPreimage): boolean; + + static toXDR(value: HashIdPreimage): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): HashIdPreimage; + + static fromXDR(input: string, format: 'hex' | 'base64'): HashIdPreimage; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Memo { + switch(): MemoType; + + text(value?: string | Buffer): string | Buffer; + + id(value?: Uint64): Uint64; + + hash(value?: Buffer): Buffer; + + retHash(value?: Buffer): Buffer; + + static memoNone(): Memo; + + static memoText(value: string | Buffer): Memo; + + static memoId(value: Uint64): Memo; + + static memoHash(value: Buffer): Memo; + + static memoReturn(value: Buffer): Memo; + + value(): string | Buffer | Uint64 | Buffer | Buffer | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Memo; + + static write(value: Memo, io: Buffer): void; + + static isValid(value: Memo): boolean; + + static toXDR(value: Memo): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Memo; + + static fromXDR(input: string, format: 'hex' | 'base64'): Memo; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class Preconditions { + switch(): PreconditionType; + + timeBounds(value?: TimeBounds): TimeBounds; + + v2(value?: PreconditionsV2): PreconditionsV2; + + static precondNone(): Preconditions; + + static precondTime(value: TimeBounds): Preconditions; + + static precondV2(value: PreconditionsV2): Preconditions; + + value(): TimeBounds | PreconditionsV2 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): Preconditions; + + static write(value: Preconditions, io: Buffer): void; + + static isValid(value: Preconditions): boolean; + + static toXDR(value: Preconditions): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): Preconditions; + + static fromXDR(input: string, format: 'hex' | 'base64'): Preconditions; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ArchivalProofBody { + switch(): ArchivalProofType; + + nonexistenceProof(value?: NonexistenceProofBody): NonexistenceProofBody; + + existenceProof(value?: ExistenceProofBody): ExistenceProofBody; + + static existence(value: NonexistenceProofBody): ArchivalProofBody; + + static nonexistence(value: ExistenceProofBody): ArchivalProofBody; + + value(): NonexistenceProofBody | ExistenceProofBody; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ArchivalProofBody; + + static write(value: ArchivalProofBody, io: Buffer): void; + + static isValid(value: ArchivalProofBody): boolean; + + static toXDR(value: ArchivalProofBody): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ArchivalProofBody; + + static fromXDR(input: string, format: 'hex' | 'base64'): ArchivalProofBody; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SorobanTransactionDataExt { + switch(): number; + + proofs(value?: ArchivalProof[]): ArchivalProof[]; + + static 0(): SorobanTransactionDataExt; + + static 1(value: ArchivalProof[]): SorobanTransactionDataExt; + + value(): ArchivalProof[] | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SorobanTransactionDataExt; + + static write(value: SorobanTransactionDataExt, io: Buffer): void; + + static isValid(value: SorobanTransactionDataExt): boolean; + + static toXDR(value: SorobanTransactionDataExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SorobanTransactionDataExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SorobanTransactionDataExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionV0Ext { + switch(): number; + + static 0(): TransactionV0Ext; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionV0Ext; + + static write(value: TransactionV0Ext, io: Buffer): void; + + static isValid(value: TransactionV0Ext): boolean; + + static toXDR(value: TransactionV0Ext): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionV0Ext; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionV0Ext; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionExt { + switch(): number; + + sorobanData(value?: SorobanTransactionData): SorobanTransactionData; + + static 0(): TransactionExt; + + static 1(value: SorobanTransactionData): TransactionExt; + + value(): SorobanTransactionData | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionExt; + + static write(value: TransactionExt, io: Buffer): void; + + static isValid(value: TransactionExt): boolean; + + static toXDR(value: TransactionExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionExt; + + static fromXDR(input: string, format: 'hex' | 'base64'): TransactionExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class FeeBumpTransactionInnerTx { + switch(): EnvelopeType; + + v1(value?: TransactionV1Envelope): TransactionV1Envelope; + + static envelopeTypeTx( + value: TransactionV1Envelope, + ): FeeBumpTransactionInnerTx; + + value(): TransactionV1Envelope; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): FeeBumpTransactionInnerTx; + + static write(value: FeeBumpTransactionInnerTx, io: Buffer): void; + + static isValid(value: FeeBumpTransactionInnerTx): boolean; + + static toXDR(value: FeeBumpTransactionInnerTx): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): FeeBumpTransactionInnerTx; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): FeeBumpTransactionInnerTx; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class FeeBumpTransactionExt { + switch(): number; + + static 0(): FeeBumpTransactionExt; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): FeeBumpTransactionExt; + + static write(value: FeeBumpTransactionExt, io: Buffer): void; + + static isValid(value: FeeBumpTransactionExt): boolean; + + static toXDR(value: FeeBumpTransactionExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): FeeBumpTransactionExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): FeeBumpTransactionExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionEnvelope { + switch(): EnvelopeType; + + v0(value?: TransactionV0Envelope): TransactionV0Envelope; + + v1(value?: TransactionV1Envelope): TransactionV1Envelope; + + feeBump(value?: FeeBumpTransactionEnvelope): FeeBumpTransactionEnvelope; + + static envelopeTypeTxV0(value: TransactionV0Envelope): TransactionEnvelope; + + static envelopeTypeTx(value: TransactionV1Envelope): TransactionEnvelope; + + static envelopeTypeTxFeeBump( + value: FeeBumpTransactionEnvelope, + ): TransactionEnvelope; + + value(): + | TransactionV0Envelope + | TransactionV1Envelope + | FeeBumpTransactionEnvelope; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionEnvelope; + + static write(value: TransactionEnvelope, io: Buffer): void; + + static isValid(value: TransactionEnvelope): boolean; + + static toXDR(value: TransactionEnvelope): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionEnvelope; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionEnvelope; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionSignaturePayloadTaggedTransaction { + switch(): EnvelopeType; + + tx(value?: Transaction): Transaction; + + feeBump(value?: FeeBumpTransaction): FeeBumpTransaction; + + static envelopeTypeTx( + value: Transaction, + ): TransactionSignaturePayloadTaggedTransaction; + + static envelopeTypeTxFeeBump( + value: FeeBumpTransaction, + ): TransactionSignaturePayloadTaggedTransaction; + + value(): Transaction | FeeBumpTransaction; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionSignaturePayloadTaggedTransaction; + + static write( + value: TransactionSignaturePayloadTaggedTransaction, + io: Buffer, + ): void; + + static isValid( + value: TransactionSignaturePayloadTaggedTransaction, + ): boolean; + + static toXDR(value: TransactionSignaturePayloadTaggedTransaction): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): TransactionSignaturePayloadTaggedTransaction; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionSignaturePayloadTaggedTransaction; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimAtom { + switch(): ClaimAtomType; + + v0(value?: ClaimOfferAtomV0): ClaimOfferAtomV0; + + orderBook(value?: ClaimOfferAtom): ClaimOfferAtom; + + liquidityPool(value?: ClaimLiquidityAtom): ClaimLiquidityAtom; + + static claimAtomTypeV0(value: ClaimOfferAtomV0): ClaimAtom; + + static claimAtomTypeOrderBook(value: ClaimOfferAtom): ClaimAtom; + + static claimAtomTypeLiquidityPool(value: ClaimLiquidityAtom): ClaimAtom; + + value(): ClaimOfferAtomV0 | ClaimOfferAtom | ClaimLiquidityAtom; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimAtom; + + static write(value: ClaimAtom, io: Buffer): void; + + static isValid(value: ClaimAtom): boolean; + + static toXDR(value: ClaimAtom): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimAtom; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClaimAtom; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class CreateAccountResult { + switch(): CreateAccountResultCode; + + static createAccountSuccess(): CreateAccountResult; + + static createAccountMalformed(): CreateAccountResult; + + static createAccountUnderfunded(): CreateAccountResult; + + static createAccountLowReserve(): CreateAccountResult; + + static createAccountAlreadyExist(): CreateAccountResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): CreateAccountResult; + + static write(value: CreateAccountResult, io: Buffer): void; + + static isValid(value: CreateAccountResult): boolean; + + static toXDR(value: CreateAccountResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): CreateAccountResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): CreateAccountResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PaymentResult { + switch(): PaymentResultCode; + + static paymentSuccess(): PaymentResult; + + static paymentMalformed(): PaymentResult; + + static paymentUnderfunded(): PaymentResult; + + static paymentSrcNoTrust(): PaymentResult; + + static paymentSrcNotAuthorized(): PaymentResult; + + static paymentNoDestination(): PaymentResult; + + static paymentNoTrust(): PaymentResult; + + static paymentNotAuthorized(): PaymentResult; + + static paymentLineFull(): PaymentResult; + + static paymentNoIssuer(): PaymentResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PaymentResult; + + static write(value: PaymentResult, io: Buffer): void; + + static isValid(value: PaymentResult): boolean; + + static toXDR(value: PaymentResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PaymentResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): PaymentResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PathPaymentStrictReceiveResult { + switch(): PathPaymentStrictReceiveResultCode; + + success( + value?: PathPaymentStrictReceiveResultSuccess, + ): PathPaymentStrictReceiveResultSuccess; + + noIssuer(value?: Asset): Asset; + + static pathPaymentStrictReceiveSuccess( + value: PathPaymentStrictReceiveResultSuccess, + ): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveMalformed(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveUnderfunded(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveSrcNoTrust(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveSrcNotAuthorized(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveNoDestination(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveNoTrust(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveNotAuthorized(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveLineFull(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveNoIssuer( + value: Asset, + ): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveTooFewOffers(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveOfferCrossSelf(): PathPaymentStrictReceiveResult; + + static pathPaymentStrictReceiveOverSendmax(): PathPaymentStrictReceiveResult; + + value(): PathPaymentStrictReceiveResultSuccess | Asset | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PathPaymentStrictReceiveResult; + + static write(value: PathPaymentStrictReceiveResult, io: Buffer): void; + + static isValid(value: PathPaymentStrictReceiveResult): boolean; + + static toXDR(value: PathPaymentStrictReceiveResult): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): PathPaymentStrictReceiveResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): PathPaymentStrictReceiveResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PathPaymentStrictSendResult { + switch(): PathPaymentStrictSendResultCode; + + success( + value?: PathPaymentStrictSendResultSuccess, + ): PathPaymentStrictSendResultSuccess; + + noIssuer(value?: Asset): Asset; + + static pathPaymentStrictSendSuccess( + value: PathPaymentStrictSendResultSuccess, + ): PathPaymentStrictSendResult; + + static pathPaymentStrictSendMalformed(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendUnderfunded(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendSrcNoTrust(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendSrcNotAuthorized(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendNoDestination(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendNoTrust(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendNotAuthorized(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendLineFull(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendNoIssuer( + value: Asset, + ): PathPaymentStrictSendResult; + + static pathPaymentStrictSendTooFewOffers(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendOfferCrossSelf(): PathPaymentStrictSendResult; + + static pathPaymentStrictSendUnderDestmin(): PathPaymentStrictSendResult; + + value(): PathPaymentStrictSendResultSuccess | Asset | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PathPaymentStrictSendResult; + + static write(value: PathPaymentStrictSendResult, io: Buffer): void; + + static isValid(value: PathPaymentStrictSendResult): boolean; + + static toXDR(value: PathPaymentStrictSendResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PathPaymentStrictSendResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): PathPaymentStrictSendResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageOfferSuccessResultOffer { + switch(): ManageOfferEffect; + + offer(value?: OfferEntry): OfferEntry; + + static manageOfferCreated(value: OfferEntry): ManageOfferSuccessResultOffer; + + static manageOfferUpdated(value: OfferEntry): ManageOfferSuccessResultOffer; + + static manageOfferDeleted(): ManageOfferSuccessResultOffer; + + value(): OfferEntry | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageOfferSuccessResultOffer; + + static write(value: ManageOfferSuccessResultOffer, io: Buffer): void; + + static isValid(value: ManageOfferSuccessResultOffer): boolean; + + static toXDR(value: ManageOfferSuccessResultOffer): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ManageOfferSuccessResultOffer; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ManageOfferSuccessResultOffer; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageSellOfferResult { + switch(): ManageSellOfferResultCode; + + success(value?: ManageOfferSuccessResult): ManageOfferSuccessResult; + + static manageSellOfferSuccess( + value: ManageOfferSuccessResult, + ): ManageSellOfferResult; + + static manageSellOfferMalformed(): ManageSellOfferResult; + + static manageSellOfferSellNoTrust(): ManageSellOfferResult; + + static manageSellOfferBuyNoTrust(): ManageSellOfferResult; + + static manageSellOfferSellNotAuthorized(): ManageSellOfferResult; + + static manageSellOfferBuyNotAuthorized(): ManageSellOfferResult; + + static manageSellOfferLineFull(): ManageSellOfferResult; + + static manageSellOfferUnderfunded(): ManageSellOfferResult; + + static manageSellOfferCrossSelf(): ManageSellOfferResult; + + static manageSellOfferSellNoIssuer(): ManageSellOfferResult; + + static manageSellOfferBuyNoIssuer(): ManageSellOfferResult; + + static manageSellOfferNotFound(): ManageSellOfferResult; + + static manageSellOfferLowReserve(): ManageSellOfferResult; + + value(): ManageOfferSuccessResult | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageSellOfferResult; + + static write(value: ManageSellOfferResult, io: Buffer): void; + + static isValid(value: ManageSellOfferResult): boolean; + + static toXDR(value: ManageSellOfferResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ManageSellOfferResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ManageSellOfferResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageBuyOfferResult { + switch(): ManageBuyOfferResultCode; + + success(value?: ManageOfferSuccessResult): ManageOfferSuccessResult; + + static manageBuyOfferSuccess( + value: ManageOfferSuccessResult, + ): ManageBuyOfferResult; + + static manageBuyOfferMalformed(): ManageBuyOfferResult; + + static manageBuyOfferSellNoTrust(): ManageBuyOfferResult; + + static manageBuyOfferBuyNoTrust(): ManageBuyOfferResult; + + static manageBuyOfferSellNotAuthorized(): ManageBuyOfferResult; + + static manageBuyOfferBuyNotAuthorized(): ManageBuyOfferResult; + + static manageBuyOfferLineFull(): ManageBuyOfferResult; + + static manageBuyOfferUnderfunded(): ManageBuyOfferResult; + + static manageBuyOfferCrossSelf(): ManageBuyOfferResult; + + static manageBuyOfferSellNoIssuer(): ManageBuyOfferResult; + + static manageBuyOfferBuyNoIssuer(): ManageBuyOfferResult; + + static manageBuyOfferNotFound(): ManageBuyOfferResult; + + static manageBuyOfferLowReserve(): ManageBuyOfferResult; + + value(): ManageOfferSuccessResult | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageBuyOfferResult; + + static write(value: ManageBuyOfferResult, io: Buffer): void; + + static isValid(value: ManageBuyOfferResult): boolean; + + static toXDR(value: ManageBuyOfferResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ManageBuyOfferResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ManageBuyOfferResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SetOptionsResult { + switch(): SetOptionsResultCode; + + static setOptionsSuccess(): SetOptionsResult; + + static setOptionsLowReserve(): SetOptionsResult; + + static setOptionsTooManySigners(): SetOptionsResult; + + static setOptionsBadFlags(): SetOptionsResult; + + static setOptionsInvalidInflation(): SetOptionsResult; + + static setOptionsCantChange(): SetOptionsResult; + + static setOptionsUnknownFlag(): SetOptionsResult; + + static setOptionsThresholdOutOfRange(): SetOptionsResult; + + static setOptionsBadSigner(): SetOptionsResult; + + static setOptionsInvalidHomeDomain(): SetOptionsResult; + + static setOptionsAuthRevocableRequired(): SetOptionsResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SetOptionsResult; + + static write(value: SetOptionsResult, io: Buffer): void; + + static isValid(value: SetOptionsResult): boolean; + + static toXDR(value: SetOptionsResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SetOptionsResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): SetOptionsResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ChangeTrustResult { + switch(): ChangeTrustResultCode; + + static changeTrustSuccess(): ChangeTrustResult; + + static changeTrustMalformed(): ChangeTrustResult; + + static changeTrustNoIssuer(): ChangeTrustResult; + + static changeTrustInvalidLimit(): ChangeTrustResult; + + static changeTrustLowReserve(): ChangeTrustResult; + + static changeTrustSelfNotAllowed(): ChangeTrustResult; + + static changeTrustTrustLineMissing(): ChangeTrustResult; + + static changeTrustCannotDelete(): ChangeTrustResult; + + static changeTrustNotAuthMaintainLiabilities(): ChangeTrustResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ChangeTrustResult; + + static write(value: ChangeTrustResult, io: Buffer): void; + + static isValid(value: ChangeTrustResult): boolean; + + static toXDR(value: ChangeTrustResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ChangeTrustResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): ChangeTrustResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AllowTrustResult { + switch(): AllowTrustResultCode; + + static allowTrustSuccess(): AllowTrustResult; + + static allowTrustMalformed(): AllowTrustResult; + + static allowTrustNoTrustLine(): AllowTrustResult; + + static allowTrustTrustNotRequired(): AllowTrustResult; + + static allowTrustCantRevoke(): AllowTrustResult; + + static allowTrustSelfNotAllowed(): AllowTrustResult; + + static allowTrustLowReserve(): AllowTrustResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AllowTrustResult; + + static write(value: AllowTrustResult, io: Buffer): void; + + static isValid(value: AllowTrustResult): boolean; + + static toXDR(value: AllowTrustResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AllowTrustResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): AllowTrustResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class AccountMergeResult { + switch(): AccountMergeResultCode; + + sourceAccountBalance(value?: Int64): Int64; + + static accountMergeSuccess(value: Int64): AccountMergeResult; + + static accountMergeMalformed(): AccountMergeResult; + + static accountMergeNoAccount(): AccountMergeResult; + + static accountMergeImmutableSet(): AccountMergeResult; + + static accountMergeHasSubEntries(): AccountMergeResult; + + static accountMergeSeqnumTooFar(): AccountMergeResult; + + static accountMergeDestFull(): AccountMergeResult; + + static accountMergeIsSponsor(): AccountMergeResult; + + value(): Int64 | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): AccountMergeResult; + + static write(value: AccountMergeResult, io: Buffer): void; + + static isValid(value: AccountMergeResult): boolean; + + static toXDR(value: AccountMergeResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): AccountMergeResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): AccountMergeResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InflationResult { + switch(): InflationResultCode; + + payouts(value?: InflationPayout[]): InflationPayout[]; + + static inflationSuccess(value: InflationPayout[]): InflationResult; + + static inflationNotTime(): InflationResult; + + value(): InflationPayout[] | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InflationResult; + + static write(value: InflationResult, io: Buffer): void; + + static isValid(value: InflationResult): boolean; + + static toXDR(value: InflationResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InflationResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): InflationResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ManageDataResult { + switch(): ManageDataResultCode; + + static manageDataSuccess(): ManageDataResult; + + static manageDataNotSupportedYet(): ManageDataResult; + + static manageDataNameNotFound(): ManageDataResult; + + static manageDataLowReserve(): ManageDataResult; + + static manageDataInvalidName(): ManageDataResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ManageDataResult; + + static write(value: ManageDataResult, io: Buffer): void; + + static isValid(value: ManageDataResult): boolean; + + static toXDR(value: ManageDataResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ManageDataResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): ManageDataResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class BumpSequenceResult { + switch(): BumpSequenceResultCode; + + static bumpSequenceSuccess(): BumpSequenceResult; + + static bumpSequenceBadSeq(): BumpSequenceResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): BumpSequenceResult; + + static write(value: BumpSequenceResult, io: Buffer): void; + + static isValid(value: BumpSequenceResult): boolean; + + static toXDR(value: BumpSequenceResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): BumpSequenceResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): BumpSequenceResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class CreateClaimableBalanceResult { + switch(): CreateClaimableBalanceResultCode; + + balanceId(value?: ClaimableBalanceId): ClaimableBalanceId; + + static createClaimableBalanceSuccess( + value: ClaimableBalanceId, + ): CreateClaimableBalanceResult; + + static createClaimableBalanceMalformed(): CreateClaimableBalanceResult; + + static createClaimableBalanceLowReserve(): CreateClaimableBalanceResult; + + static createClaimableBalanceNoTrust(): CreateClaimableBalanceResult; + + static createClaimableBalanceNotAuthorized(): CreateClaimableBalanceResult; + + static createClaimableBalanceUnderfunded(): CreateClaimableBalanceResult; + + value(): ClaimableBalanceId | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): CreateClaimableBalanceResult; + + static write(value: CreateClaimableBalanceResult, io: Buffer): void; + + static isValid(value: CreateClaimableBalanceResult): boolean; + + static toXDR(value: CreateClaimableBalanceResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): CreateClaimableBalanceResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): CreateClaimableBalanceResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClaimClaimableBalanceResult { + switch(): ClaimClaimableBalanceResultCode; + + static claimClaimableBalanceSuccess(): ClaimClaimableBalanceResult; + + static claimClaimableBalanceDoesNotExist(): ClaimClaimableBalanceResult; + + static claimClaimableBalanceCannotClaim(): ClaimClaimableBalanceResult; + + static claimClaimableBalanceLineFull(): ClaimClaimableBalanceResult; + + static claimClaimableBalanceNoTrust(): ClaimClaimableBalanceResult; + + static claimClaimableBalanceNotAuthorized(): ClaimClaimableBalanceResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClaimClaimableBalanceResult; + + static write(value: ClaimClaimableBalanceResult, io: Buffer): void; + + static isValid(value: ClaimClaimableBalanceResult): boolean; + + static toXDR(value: ClaimClaimableBalanceResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClaimClaimableBalanceResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClaimClaimableBalanceResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class BeginSponsoringFutureReservesResult { + switch(): BeginSponsoringFutureReservesResultCode; + + static beginSponsoringFutureReservesSuccess(): BeginSponsoringFutureReservesResult; + + static beginSponsoringFutureReservesMalformed(): BeginSponsoringFutureReservesResult; + + static beginSponsoringFutureReservesAlreadySponsored(): BeginSponsoringFutureReservesResult; + + static beginSponsoringFutureReservesRecursive(): BeginSponsoringFutureReservesResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): BeginSponsoringFutureReservesResult; + + static write(value: BeginSponsoringFutureReservesResult, io: Buffer): void; + + static isValid(value: BeginSponsoringFutureReservesResult): boolean; + + static toXDR(value: BeginSponsoringFutureReservesResult): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): BeginSponsoringFutureReservesResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): BeginSponsoringFutureReservesResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class EndSponsoringFutureReservesResult { + switch(): EndSponsoringFutureReservesResultCode; + + static endSponsoringFutureReservesSuccess(): EndSponsoringFutureReservesResult; + + static endSponsoringFutureReservesNotSponsored(): EndSponsoringFutureReservesResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): EndSponsoringFutureReservesResult; + + static write(value: EndSponsoringFutureReservesResult, io: Buffer): void; + + static isValid(value: EndSponsoringFutureReservesResult): boolean; + + static toXDR(value: EndSponsoringFutureReservesResult): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): EndSponsoringFutureReservesResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): EndSponsoringFutureReservesResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class RevokeSponsorshipResult { + switch(): RevokeSponsorshipResultCode; + + static revokeSponsorshipSuccess(): RevokeSponsorshipResult; + + static revokeSponsorshipDoesNotExist(): RevokeSponsorshipResult; + + static revokeSponsorshipNotSponsor(): RevokeSponsorshipResult; + + static revokeSponsorshipLowReserve(): RevokeSponsorshipResult; + + static revokeSponsorshipOnlyTransferable(): RevokeSponsorshipResult; + + static revokeSponsorshipMalformed(): RevokeSponsorshipResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): RevokeSponsorshipResult; + + static write(value: RevokeSponsorshipResult, io: Buffer): void; + + static isValid(value: RevokeSponsorshipResult): boolean; + + static toXDR(value: RevokeSponsorshipResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): RevokeSponsorshipResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): RevokeSponsorshipResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClawbackResult { + switch(): ClawbackResultCode; + + static clawbackSuccess(): ClawbackResult; + + static clawbackMalformed(): ClawbackResult; + + static clawbackNotClawbackEnabled(): ClawbackResult; + + static clawbackNoTrust(): ClawbackResult; + + static clawbackUnderfunded(): ClawbackResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClawbackResult; + + static write(value: ClawbackResult, io: Buffer): void; + + static isValid(value: ClawbackResult): boolean; + + static toXDR(value: ClawbackResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ClawbackResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): ClawbackResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ClawbackClaimableBalanceResult { + switch(): ClawbackClaimableBalanceResultCode; + + static clawbackClaimableBalanceSuccess(): ClawbackClaimableBalanceResult; + + static clawbackClaimableBalanceDoesNotExist(): ClawbackClaimableBalanceResult; + + static clawbackClaimableBalanceNotIssuer(): ClawbackClaimableBalanceResult; + + static clawbackClaimableBalanceNotClawbackEnabled(): ClawbackClaimableBalanceResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ClawbackClaimableBalanceResult; + + static write(value: ClawbackClaimableBalanceResult, io: Buffer): void; + + static isValid(value: ClawbackClaimableBalanceResult): boolean; + + static toXDR(value: ClawbackClaimableBalanceResult): Buffer; + + static fromXDR( + input: Buffer, + format?: 'raw', + ): ClawbackClaimableBalanceResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ClawbackClaimableBalanceResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SetTrustLineFlagsResult { + switch(): SetTrustLineFlagsResultCode; + + static setTrustLineFlagsSuccess(): SetTrustLineFlagsResult; + + static setTrustLineFlagsMalformed(): SetTrustLineFlagsResult; + + static setTrustLineFlagsNoTrustLine(): SetTrustLineFlagsResult; + + static setTrustLineFlagsCantRevoke(): SetTrustLineFlagsResult; + + static setTrustLineFlagsInvalidState(): SetTrustLineFlagsResult; + + static setTrustLineFlagsLowReserve(): SetTrustLineFlagsResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SetTrustLineFlagsResult; + + static write(value: SetTrustLineFlagsResult, io: Buffer): void; + + static isValid(value: SetTrustLineFlagsResult): boolean; + + static toXDR(value: SetTrustLineFlagsResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SetTrustLineFlagsResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): SetTrustLineFlagsResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolDepositResult { + switch(): LiquidityPoolDepositResultCode; + + static liquidityPoolDepositSuccess(): LiquidityPoolDepositResult; + + static liquidityPoolDepositMalformed(): LiquidityPoolDepositResult; + + static liquidityPoolDepositNoTrust(): LiquidityPoolDepositResult; + + static liquidityPoolDepositNotAuthorized(): LiquidityPoolDepositResult; + + static liquidityPoolDepositUnderfunded(): LiquidityPoolDepositResult; + + static liquidityPoolDepositLineFull(): LiquidityPoolDepositResult; + + static liquidityPoolDepositBadPrice(): LiquidityPoolDepositResult; + + static liquidityPoolDepositPoolFull(): LiquidityPoolDepositResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolDepositResult; + + static write(value: LiquidityPoolDepositResult, io: Buffer): void; + + static isValid(value: LiquidityPoolDepositResult): boolean; + + static toXDR(value: LiquidityPoolDepositResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LiquidityPoolDepositResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolDepositResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class LiquidityPoolWithdrawResult { + switch(): LiquidityPoolWithdrawResultCode; + + static liquidityPoolWithdrawSuccess(): LiquidityPoolWithdrawResult; + + static liquidityPoolWithdrawMalformed(): LiquidityPoolWithdrawResult; + + static liquidityPoolWithdrawNoTrust(): LiquidityPoolWithdrawResult; + + static liquidityPoolWithdrawUnderfunded(): LiquidityPoolWithdrawResult; + + static liquidityPoolWithdrawLineFull(): LiquidityPoolWithdrawResult; + + static liquidityPoolWithdrawUnderMinimum(): LiquidityPoolWithdrawResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): LiquidityPoolWithdrawResult; + + static write(value: LiquidityPoolWithdrawResult, io: Buffer): void; + + static isValid(value: LiquidityPoolWithdrawResult): boolean; + + static toXDR(value: LiquidityPoolWithdrawResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): LiquidityPoolWithdrawResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): LiquidityPoolWithdrawResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InvokeHostFunctionResult { + switch(): InvokeHostFunctionResultCode; + + success(value?: Buffer): Buffer; + + static invokeHostFunctionSuccess(value: Buffer): InvokeHostFunctionResult; + + static invokeHostFunctionMalformed(): InvokeHostFunctionResult; + + static invokeHostFunctionTrapped(): InvokeHostFunctionResult; + + static invokeHostFunctionResourceLimitExceeded(): InvokeHostFunctionResult; + + static invokeHostFunctionEntryArchived(): InvokeHostFunctionResult; + + static invokeHostFunctionInsufficientRefundableFee(): InvokeHostFunctionResult; + + value(): Buffer | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InvokeHostFunctionResult; + + static write(value: InvokeHostFunctionResult, io: Buffer): void; + + static isValid(value: InvokeHostFunctionResult): boolean; + + static toXDR(value: InvokeHostFunctionResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InvokeHostFunctionResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): InvokeHostFunctionResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ExtendFootprintTtlResult { + switch(): ExtendFootprintTtlResultCode; + + static extendFootprintTtlSuccess(): ExtendFootprintTtlResult; + + static extendFootprintTtlMalformed(): ExtendFootprintTtlResult; + + static extendFootprintTtlResourceLimitExceeded(): ExtendFootprintTtlResult; + + static extendFootprintTtlInsufficientRefundableFee(): ExtendFootprintTtlResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ExtendFootprintTtlResult; + + static write(value: ExtendFootprintTtlResult, io: Buffer): void; + + static isValid(value: ExtendFootprintTtlResult): boolean; + + static toXDR(value: ExtendFootprintTtlResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ExtendFootprintTtlResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ExtendFootprintTtlResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class RestoreFootprintResult { + switch(): RestoreFootprintResultCode; + + static restoreFootprintSuccess(): RestoreFootprintResult; + + static restoreFootprintMalformed(): RestoreFootprintResult; + + static restoreFootprintResourceLimitExceeded(): RestoreFootprintResult; + + static restoreFootprintInsufficientRefundableFee(): RestoreFootprintResult; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): RestoreFootprintResult; + + static write(value: RestoreFootprintResult, io: Buffer): void; + + static isValid(value: RestoreFootprintResult): boolean; + + static toXDR(value: RestoreFootprintResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): RestoreFootprintResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): RestoreFootprintResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class OperationResultTr { + switch(): OperationType; + + createAccountResult(value?: CreateAccountResult): CreateAccountResult; + + paymentResult(value?: PaymentResult): PaymentResult; + + pathPaymentStrictReceiveResult( + value?: PathPaymentStrictReceiveResult, + ): PathPaymentStrictReceiveResult; + + manageSellOfferResult(value?: ManageSellOfferResult): ManageSellOfferResult; + + createPassiveSellOfferResult( + value?: ManageSellOfferResult, + ): ManageSellOfferResult; + + setOptionsResult(value?: SetOptionsResult): SetOptionsResult; + + changeTrustResult(value?: ChangeTrustResult): ChangeTrustResult; + + allowTrustResult(value?: AllowTrustResult): AllowTrustResult; + + accountMergeResult(value?: AccountMergeResult): AccountMergeResult; + + inflationResult(value?: InflationResult): InflationResult; + + manageDataResult(value?: ManageDataResult): ManageDataResult; + + bumpSeqResult(value?: BumpSequenceResult): BumpSequenceResult; + + manageBuyOfferResult(value?: ManageBuyOfferResult): ManageBuyOfferResult; + + pathPaymentStrictSendResult( + value?: PathPaymentStrictSendResult, + ): PathPaymentStrictSendResult; + + createClaimableBalanceResult( + value?: CreateClaimableBalanceResult, + ): CreateClaimableBalanceResult; + + claimClaimableBalanceResult( + value?: ClaimClaimableBalanceResult, + ): ClaimClaimableBalanceResult; + + beginSponsoringFutureReservesResult( + value?: BeginSponsoringFutureReservesResult, + ): BeginSponsoringFutureReservesResult; + + endSponsoringFutureReservesResult( + value?: EndSponsoringFutureReservesResult, + ): EndSponsoringFutureReservesResult; + + revokeSponsorshipResult( + value?: RevokeSponsorshipResult, + ): RevokeSponsorshipResult; + + clawbackResult(value?: ClawbackResult): ClawbackResult; + + clawbackClaimableBalanceResult( + value?: ClawbackClaimableBalanceResult, + ): ClawbackClaimableBalanceResult; + + setTrustLineFlagsResult( + value?: SetTrustLineFlagsResult, + ): SetTrustLineFlagsResult; + + liquidityPoolDepositResult( + value?: LiquidityPoolDepositResult, + ): LiquidityPoolDepositResult; + + liquidityPoolWithdrawResult( + value?: LiquidityPoolWithdrawResult, + ): LiquidityPoolWithdrawResult; + + invokeHostFunctionResult( + value?: InvokeHostFunctionResult, + ): InvokeHostFunctionResult; + + extendFootprintTtlResult( + value?: ExtendFootprintTtlResult, + ): ExtendFootprintTtlResult; + + restoreFootprintResult( + value?: RestoreFootprintResult, + ): RestoreFootprintResult; + + static createAccount(value: CreateAccountResult): OperationResultTr; + + static payment(value: PaymentResult): OperationResultTr; + + static pathPaymentStrictReceive( + value: PathPaymentStrictReceiveResult, + ): OperationResultTr; + + static manageSellOffer(value: ManageSellOfferResult): OperationResultTr; + + static createPassiveSellOffer( + value: ManageSellOfferResult, + ): OperationResultTr; + + static setOptions(value: SetOptionsResult): OperationResultTr; + + static changeTrust(value: ChangeTrustResult): OperationResultTr; + + static allowTrust(value: AllowTrustResult): OperationResultTr; + + static accountMerge(value: AccountMergeResult): OperationResultTr; + + static inflation(value: InflationResult): OperationResultTr; + + static manageData(value: ManageDataResult): OperationResultTr; + + static bumpSequence(value: BumpSequenceResult): OperationResultTr; + + static manageBuyOffer(value: ManageBuyOfferResult): OperationResultTr; + + static pathPaymentStrictSend( + value: PathPaymentStrictSendResult, + ): OperationResultTr; + + static createClaimableBalance( + value: CreateClaimableBalanceResult, + ): OperationResultTr; + + static claimClaimableBalance( + value: ClaimClaimableBalanceResult, + ): OperationResultTr; + + static beginSponsoringFutureReserves( + value: BeginSponsoringFutureReservesResult, + ): OperationResultTr; + + static endSponsoringFutureReserves( + value: EndSponsoringFutureReservesResult, + ): OperationResultTr; + + static revokeSponsorship(value: RevokeSponsorshipResult): OperationResultTr; + + static clawback(value: ClawbackResult): OperationResultTr; + + static clawbackClaimableBalance( + value: ClawbackClaimableBalanceResult, + ): OperationResultTr; + + static setTrustLineFlags(value: SetTrustLineFlagsResult): OperationResultTr; + + static liquidityPoolDeposit( + value: LiquidityPoolDepositResult, + ): OperationResultTr; + + static liquidityPoolWithdraw( + value: LiquidityPoolWithdrawResult, + ): OperationResultTr; + + static invokeHostFunction( + value: InvokeHostFunctionResult, + ): OperationResultTr; + + static extendFootprintTtl( + value: ExtendFootprintTtlResult, + ): OperationResultTr; + + static restoreFootprint(value: RestoreFootprintResult): OperationResultTr; + + value(): + | CreateAccountResult + | PaymentResult + | PathPaymentStrictReceiveResult + | ManageSellOfferResult + | ManageSellOfferResult + | SetOptionsResult + | ChangeTrustResult + | AllowTrustResult + | AccountMergeResult + | InflationResult + | ManageDataResult + | BumpSequenceResult + | ManageBuyOfferResult + | PathPaymentStrictSendResult + | CreateClaimableBalanceResult + | ClaimClaimableBalanceResult + | BeginSponsoringFutureReservesResult + | EndSponsoringFutureReservesResult + | RevokeSponsorshipResult + | ClawbackResult + | ClawbackClaimableBalanceResult + | SetTrustLineFlagsResult + | LiquidityPoolDepositResult + | LiquidityPoolWithdrawResult + | InvokeHostFunctionResult + | ExtendFootprintTtlResult + | RestoreFootprintResult; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): OperationResultTr; + + static write(value: OperationResultTr, io: Buffer): void; + + static isValid(value: OperationResultTr): boolean; + + static toXDR(value: OperationResultTr): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): OperationResultTr; + + static fromXDR(input: string, format: 'hex' | 'base64'): OperationResultTr; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class OperationResult { + switch(): OperationResultCode; + + tr(value?: OperationResultTr): OperationResultTr; + + static opInner(value: OperationResultTr): OperationResult; + + static opBadAuth(): OperationResult; + + static opNoAccount(): OperationResult; + + static opNotSupported(): OperationResult; + + static opTooManySubentries(): OperationResult; + + static opExceededWorkLimit(): OperationResult; + + static opTooManySponsoring(): OperationResult; + + value(): OperationResultTr | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): OperationResult; + + static write(value: OperationResult, io: Buffer): void; + + static isValid(value: OperationResult): boolean; + + static toXDR(value: OperationResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): OperationResult; + + static fromXDR(input: string, format: 'hex' | 'base64'): OperationResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InnerTransactionResultResult { + switch(): TransactionResultCode; + + results(value?: OperationResult[]): OperationResult[]; + + static txSuccess(value: OperationResult[]): InnerTransactionResultResult; + + static txFailed(value: OperationResult[]): InnerTransactionResultResult; + + static txTooEarly(): InnerTransactionResultResult; + + static txTooLate(): InnerTransactionResultResult; + + static txMissingOperation(): InnerTransactionResultResult; + + static txBadSeq(): InnerTransactionResultResult; + + static txBadAuth(): InnerTransactionResultResult; + + static txInsufficientBalance(): InnerTransactionResultResult; + + static txNoAccount(): InnerTransactionResultResult; + + static txInsufficientFee(): InnerTransactionResultResult; + + static txBadAuthExtra(): InnerTransactionResultResult; + + static txInternalError(): InnerTransactionResultResult; + + static txNotSupported(): InnerTransactionResultResult; + + static txBadSponsorship(): InnerTransactionResultResult; + + static txBadMinSeqAgeOrGap(): InnerTransactionResultResult; + + static txMalformed(): InnerTransactionResultResult; + + static txSorobanInvalid(): InnerTransactionResultResult; + + value(): OperationResult[] | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InnerTransactionResultResult; + + static write(value: InnerTransactionResultResult, io: Buffer): void; + + static isValid(value: InnerTransactionResultResult): boolean; + + static toXDR(value: InnerTransactionResultResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InnerTransactionResultResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): InnerTransactionResultResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class InnerTransactionResultExt { + switch(): number; + + static 0(): InnerTransactionResultExt; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): InnerTransactionResultExt; + + static write(value: InnerTransactionResultExt, io: Buffer): void; + + static isValid(value: InnerTransactionResultExt): boolean; + + static toXDR(value: InnerTransactionResultExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): InnerTransactionResultExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): InnerTransactionResultExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionResultResult { + switch(): TransactionResultCode; + + innerResultPair( + value?: InnerTransactionResultPair, + ): InnerTransactionResultPair; + + results(value?: OperationResult[]): OperationResult[]; + + static txFeeBumpInnerSuccess( + value: InnerTransactionResultPair, + ): TransactionResultResult; + + static txFeeBumpInnerFailed( + value: InnerTransactionResultPair, + ): TransactionResultResult; + + static txSuccess(value: OperationResult[]): TransactionResultResult; + + static txFailed(value: OperationResult[]): TransactionResultResult; + + static txTooEarly(): TransactionResultResult; + + static txTooLate(): TransactionResultResult; + + static txMissingOperation(): TransactionResultResult; + + static txBadSeq(): TransactionResultResult; + + static txBadAuth(): TransactionResultResult; + + static txInsufficientBalance(): TransactionResultResult; + + static txNoAccount(): TransactionResultResult; + + static txInsufficientFee(): TransactionResultResult; + + static txBadAuthExtra(): TransactionResultResult; + + static txInternalError(): TransactionResultResult; + + static txNotSupported(): TransactionResultResult; + + static txBadSponsorship(): TransactionResultResult; + + static txBadMinSeqAgeOrGap(): TransactionResultResult; + + static txMalformed(): TransactionResultResult; + + static txSorobanInvalid(): TransactionResultResult; + + value(): InnerTransactionResultPair | OperationResult[] | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionResultResult; + + static write(value: TransactionResultResult, io: Buffer): void; + + static isValid(value: TransactionResultResult): boolean; + + static toXDR(value: TransactionResultResult): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionResultResult; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionResultResult; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class TransactionResultExt { + switch(): number; + + static 0(): TransactionResultExt; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): TransactionResultExt; + + static write(value: TransactionResultExt, io: Buffer): void; + + static isValid(value: TransactionResultExt): boolean; + + static toXDR(value: TransactionResultExt): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): TransactionResultExt; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): TransactionResultExt; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ExtensionPoint { + switch(): number; + + static 0(): ExtensionPoint; + + value(): void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ExtensionPoint; + + static write(value: ExtensionPoint, io: Buffer): void; + + static isValid(value: ExtensionPoint): boolean; + + static toXDR(value: ExtensionPoint): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ExtensionPoint; + + static fromXDR(input: string, format: 'hex' | 'base64'): ExtensionPoint; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class PublicKey { + switch(): PublicKeyType; + + ed25519(value?: Buffer): Buffer; + + static publicKeyTypeEd25519(value: Buffer): PublicKey; + + value(): Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): PublicKey; + + static write(value: PublicKey, io: Buffer): void; + + static isValid(value: PublicKey): boolean; + + static toXDR(value: PublicKey): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): PublicKey; + + static fromXDR(input: string, format: 'hex' | 'base64'): PublicKey; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class SignerKey { + switch(): SignerKeyType; + + ed25519(value?: Buffer): Buffer; + + preAuthTx(value?: Buffer): Buffer; + + hashX(value?: Buffer): Buffer; + + ed25519SignedPayload( + value?: SignerKeyEd25519SignedPayload, + ): SignerKeyEd25519SignedPayload; + + static signerKeyTypeEd25519(value: Buffer): SignerKey; + + static signerKeyTypePreAuthTx(value: Buffer): SignerKey; + + static signerKeyTypeHashX(value: Buffer): SignerKey; + + static signerKeyTypeEd25519SignedPayload( + value: SignerKeyEd25519SignedPayload, + ): SignerKey; + + value(): Buffer | Buffer | Buffer | SignerKeyEd25519SignedPayload; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): SignerKey; + + static write(value: SignerKey, io: Buffer): void; + + static isValid(value: SignerKey): boolean; + + static toXDR(value: SignerKey): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): SignerKey; + + static fromXDR(input: string, format: 'hex' | 'base64'): SignerKey; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScError { + switch(): ScErrorType; + + contractCode(value?: number): number; + + code(value?: ScErrorCode): ScErrorCode; + + static sceContract(value: number): ScError; + + static sceWasmVm(value: ScErrorCode): ScError; + + static sceContext(value: ScErrorCode): ScError; + + static sceStorage(value: ScErrorCode): ScError; + + static sceObject(value: ScErrorCode): ScError; + + static sceCrypto(value: ScErrorCode): ScError; + + static sceEvents(value: ScErrorCode): ScError; + + static sceBudget(value: ScErrorCode): ScError; + + static sceValue(value: ScErrorCode): ScError; + + static sceAuth(value: ScErrorCode): ScError; + + value(): number | ScErrorCode; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScError; + + static write(value: ScError, io: Buffer): void; + + static isValid(value: ScError): boolean; + + static toXDR(value: ScError): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScError; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScError; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ContractExecutable { + switch(): ContractExecutableType; + + wasmHash(value?: Buffer): Buffer; + + static contractExecutableWasm(value: Buffer): ContractExecutable; + + static contractExecutableStellarAsset(): ContractExecutable; + + value(): Buffer | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ContractExecutable; + + static write(value: ContractExecutable, io: Buffer): void; + + static isValid(value: ContractExecutable): boolean; + + static toXDR(value: ContractExecutable): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ContractExecutable; + + static fromXDR(input: string, format: 'hex' | 'base64'): ContractExecutable; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScAddress { + switch(): ScAddressType; + + accountId(value?: AccountId): AccountId; + + contractId(value?: Buffer): Buffer; + + static scAddressTypeAccount(value: AccountId): ScAddress; + + static scAddressTypeContract(value: Buffer): ScAddress; + + value(): AccountId | Buffer; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScAddress; + + static write(value: ScAddress, io: Buffer): void; + + static isValid(value: ScAddress): boolean; + + static toXDR(value: ScAddress): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScAddress; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScAddress; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScVal { + switch(): ScValType; + + b(value?: boolean): boolean; + + error(value?: ScError): ScError; + + u32(value?: number): number; + + i32(value?: number): number; + + u64(value?: Uint64): Uint64; + + i64(value?: Int64): Int64; + + timepoint(value?: TimePoint): TimePoint; + + duration(value?: Duration): Duration; + + u128(value?: UInt128Parts): UInt128Parts; + + i128(value?: Int128Parts): Int128Parts; + + u256(value?: UInt256Parts): UInt256Parts; + + i256(value?: Int256Parts): Int256Parts; + + bytes(value?: Buffer): Buffer; + + str(value?: string | Buffer): string | Buffer; + + sym(value?: string | Buffer): string | Buffer; + + vec(value?: null | ScVal[]): null | ScVal[]; + + map(value?: null | ScMapEntry[]): null | ScMapEntry[]; + + address(value?: ScAddress): ScAddress; + + nonceKey(value?: ScNonceKey): ScNonceKey; + + instance(value?: ScContractInstance): ScContractInstance; + + static scvBool(value: boolean): ScVal; + + static scvVoid(): ScVal; + + static scvError(value: ScError): ScVal; + + static scvU32(value: number): ScVal; + + static scvI32(value: number): ScVal; + + static scvU64(value: Uint64): ScVal; + + static scvI64(value: Int64): ScVal; + + static scvTimepoint(value: TimePoint): ScVal; + + static scvDuration(value: Duration): ScVal; + + static scvU128(value: UInt128Parts): ScVal; + + static scvI128(value: Int128Parts): ScVal; + + static scvU256(value: UInt256Parts): ScVal; + + static scvI256(value: Int256Parts): ScVal; + + static scvBytes(value: Buffer): ScVal; + + static scvString(value: string | Buffer): ScVal; + + static scvSymbol(value: string | Buffer): ScVal; + + static scvVec(value: null | ScVal[]): ScVal; + + static scvMap(value: null | ScMapEntry[]): ScVal; + + static scvAddress(value: ScAddress): ScVal; + + static scvLedgerKeyContractInstance(): ScVal; + + static scvLedgerKeyNonce(value: ScNonceKey): ScVal; + + static scvContractInstance(value: ScContractInstance): ScVal; + + value(): + | boolean + | ScError + | number + | number + | Uint64 + | Int64 + | TimePoint + | Duration + | UInt128Parts + | Int128Parts + | UInt256Parts + | Int256Parts + | Buffer + | string + | Buffer + | string + | Buffer + | null + | ScVal[] + | null + | ScMapEntry[] + | ScAddress + | ScNonceKey + | ScContractInstance + | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScVal; + + static write(value: ScVal, io: Buffer): void; + + static isValid(value: ScVal): boolean; + + static toXDR(value: ScVal): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScVal; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScVal; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScEnvMetaEntry { + switch(): ScEnvMetaKind; + + interfaceVersion( + value?: ScEnvMetaEntryInterfaceVersion, + ): ScEnvMetaEntryInterfaceVersion; + + static scEnvMetaKindInterfaceVersion( + value: ScEnvMetaEntryInterfaceVersion, + ): ScEnvMetaEntry; + + value(): ScEnvMetaEntryInterfaceVersion; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScEnvMetaEntry; + + static write(value: ScEnvMetaEntry, io: Buffer): void; + + static isValid(value: ScEnvMetaEntry): boolean; + + static toXDR(value: ScEnvMetaEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScEnvMetaEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScEnvMetaEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScMetaEntry { + switch(): ScMetaKind; + + v0(value?: ScMetaV0): ScMetaV0; + + static scMetaV0(value: ScMetaV0): ScMetaEntry; + + value(): ScMetaV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScMetaEntry; + + static write(value: ScMetaEntry, io: Buffer): void; + + static isValid(value: ScMetaEntry): boolean; + + static toXDR(value: ScMetaEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScMetaEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScMetaEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecTypeDef { + switch(): ScSpecType; + + option(value?: ScSpecTypeOption): ScSpecTypeOption; + + result(value?: ScSpecTypeResult): ScSpecTypeResult; + + vec(value?: ScSpecTypeVec): ScSpecTypeVec; + + map(value?: ScSpecTypeMap): ScSpecTypeMap; + + tuple(value?: ScSpecTypeTuple): ScSpecTypeTuple; + + bytesN(value?: ScSpecTypeBytesN): ScSpecTypeBytesN; + + udt(value?: ScSpecTypeUdt): ScSpecTypeUdt; + + static scSpecTypeVal(): ScSpecTypeDef; + + static scSpecTypeBool(): ScSpecTypeDef; + + static scSpecTypeVoid(): ScSpecTypeDef; + + static scSpecTypeError(): ScSpecTypeDef; + + static scSpecTypeU32(): ScSpecTypeDef; + + static scSpecTypeI32(): ScSpecTypeDef; + + static scSpecTypeU64(): ScSpecTypeDef; + + static scSpecTypeI64(): ScSpecTypeDef; + + static scSpecTypeTimepoint(): ScSpecTypeDef; + + static scSpecTypeDuration(): ScSpecTypeDef; + + static scSpecTypeU128(): ScSpecTypeDef; + + static scSpecTypeI128(): ScSpecTypeDef; + + static scSpecTypeU256(): ScSpecTypeDef; + + static scSpecTypeI256(): ScSpecTypeDef; + + static scSpecTypeBytes(): ScSpecTypeDef; + + static scSpecTypeString(): ScSpecTypeDef; + + static scSpecTypeSymbol(): ScSpecTypeDef; + + static scSpecTypeAddress(): ScSpecTypeDef; + + static scSpecTypeOption(value: ScSpecTypeOption): ScSpecTypeDef; + + static scSpecTypeResult(value: ScSpecTypeResult): ScSpecTypeDef; + + static scSpecTypeVec(value: ScSpecTypeVec): ScSpecTypeDef; + + static scSpecTypeMap(value: ScSpecTypeMap): ScSpecTypeDef; + + static scSpecTypeTuple(value: ScSpecTypeTuple): ScSpecTypeDef; + + static scSpecTypeBytesN(value: ScSpecTypeBytesN): ScSpecTypeDef; + + static scSpecTypeUdt(value: ScSpecTypeUdt): ScSpecTypeDef; + + value(): + | ScSpecTypeOption + | ScSpecTypeResult + | ScSpecTypeVec + | ScSpecTypeMap + | ScSpecTypeTuple + | ScSpecTypeBytesN + | ScSpecTypeUdt + | void; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecTypeDef; + + static write(value: ScSpecTypeDef, io: Buffer): void; + + static isValid(value: ScSpecTypeDef): boolean; + + static toXDR(value: ScSpecTypeDef): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecTypeDef; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecTypeDef; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecUdtUnionCaseV0 { + switch(): ScSpecUdtUnionCaseV0Kind; + + voidCase(value?: ScSpecUdtUnionCaseVoidV0): ScSpecUdtUnionCaseVoidV0; + + tupleCase(value?: ScSpecUdtUnionCaseTupleV0): ScSpecUdtUnionCaseTupleV0; + + static scSpecUdtUnionCaseVoidV0( + value: ScSpecUdtUnionCaseVoidV0, + ): ScSpecUdtUnionCaseV0; + + static scSpecUdtUnionCaseTupleV0( + value: ScSpecUdtUnionCaseTupleV0, + ): ScSpecUdtUnionCaseV0; + + value(): ScSpecUdtUnionCaseVoidV0 | ScSpecUdtUnionCaseTupleV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecUdtUnionCaseV0; + + static write(value: ScSpecUdtUnionCaseV0, io: Buffer): void; + + static isValid(value: ScSpecUdtUnionCaseV0): boolean; + + static toXDR(value: ScSpecUdtUnionCaseV0): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecUdtUnionCaseV0; + + static fromXDR( + input: string, + format: 'hex' | 'base64', + ): ScSpecUdtUnionCaseV0; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ScSpecEntry { + switch(): ScSpecEntryKind; + + functionV0(value?: ScSpecFunctionV0): ScSpecFunctionV0; + + udtStructV0(value?: ScSpecUdtStructV0): ScSpecUdtStructV0; + + udtUnionV0(value?: ScSpecUdtUnionV0): ScSpecUdtUnionV0; + + udtEnumV0(value?: ScSpecUdtEnumV0): ScSpecUdtEnumV0; + + udtErrorEnumV0(value?: ScSpecUdtErrorEnumV0): ScSpecUdtErrorEnumV0; + + static scSpecEntryFunctionV0(value: ScSpecFunctionV0): ScSpecEntry; + + static scSpecEntryUdtStructV0(value: ScSpecUdtStructV0): ScSpecEntry; + + static scSpecEntryUdtUnionV0(value: ScSpecUdtUnionV0): ScSpecEntry; + + static scSpecEntryUdtEnumV0(value: ScSpecUdtEnumV0): ScSpecEntry; + + static scSpecEntryUdtErrorEnumV0(value: ScSpecUdtErrorEnumV0): ScSpecEntry; + + value(): + | ScSpecFunctionV0 + | ScSpecUdtStructV0 + | ScSpecUdtUnionV0 + | ScSpecUdtEnumV0 + | ScSpecUdtErrorEnumV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ScSpecEntry; + + static write(value: ScSpecEntry, io: Buffer): void; + + static isValid(value: ScSpecEntry): boolean; + + static toXDR(value: ScSpecEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ScSpecEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ScSpecEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } + + class ConfigSettingEntry { + switch(): ConfigSettingId; + + contractMaxSizeBytes(value?: number): number; + + contractCompute( + value?: ConfigSettingContractComputeV0, + ): ConfigSettingContractComputeV0; + + contractLedgerCost( + value?: ConfigSettingContractLedgerCostV0, + ): ConfigSettingContractLedgerCostV0; + + contractHistoricalData( + value?: ConfigSettingContractHistoricalDataV0, + ): ConfigSettingContractHistoricalDataV0; + + contractEvents( + value?: ConfigSettingContractEventsV0, + ): ConfigSettingContractEventsV0; + + contractBandwidth( + value?: ConfigSettingContractBandwidthV0, + ): ConfigSettingContractBandwidthV0; + + contractCostParamsCpuInsns( + value?: ContractCostParamEntry[], + ): ContractCostParamEntry[]; + + contractCostParamsMemBytes( + value?: ContractCostParamEntry[], + ): ContractCostParamEntry[]; + + contractDataKeySizeBytes(value?: number): number; + + contractDataEntrySizeBytes(value?: number): number; + + stateArchivalSettings(value?: StateArchivalSettings): StateArchivalSettings; + + contractExecutionLanes( + value?: ConfigSettingContractExecutionLanesV0, + ): ConfigSettingContractExecutionLanesV0; + + bucketListSizeWindow(value?: Uint64[]): Uint64[]; + + evictionIterator(value?: EvictionIterator): EvictionIterator; + + contractParallelCompute( + value?: ConfigSettingContractParallelComputeV0, + ): ConfigSettingContractParallelComputeV0; + + static configSettingContractMaxSizeBytes(value: number): ConfigSettingEntry; + + static configSettingContractComputeV0( + value: ConfigSettingContractComputeV0, + ): ConfigSettingEntry; + + static configSettingContractLedgerCostV0( + value: ConfigSettingContractLedgerCostV0, + ): ConfigSettingEntry; + + static configSettingContractHistoricalDataV0( + value: ConfigSettingContractHistoricalDataV0, + ): ConfigSettingEntry; + + static configSettingContractEventsV0( + value: ConfigSettingContractEventsV0, + ): ConfigSettingEntry; + + static configSettingContractBandwidthV0( + value: ConfigSettingContractBandwidthV0, + ): ConfigSettingEntry; + + static configSettingContractCostParamsCpuInstructions( + value: ContractCostParamEntry[], + ): ConfigSettingEntry; + + static configSettingContractCostParamsMemoryBytes( + value: ContractCostParamEntry[], + ): ConfigSettingEntry; + + static configSettingContractDataKeySizeBytes( + value: number, + ): ConfigSettingEntry; + + static configSettingContractDataEntrySizeBytes( + value: number, + ): ConfigSettingEntry; + + static configSettingStateArchival( + value: StateArchivalSettings, + ): ConfigSettingEntry; + + static configSettingContractExecutionLanes( + value: ConfigSettingContractExecutionLanesV0, + ): ConfigSettingEntry; + + static configSettingBucketlistSizeWindow( + value: Uint64[], + ): ConfigSettingEntry; + + static configSettingEvictionIterator( + value: EvictionIterator, + ): ConfigSettingEntry; + + static configSettingContractParallelComputeV0( + value: ConfigSettingContractParallelComputeV0, + ): ConfigSettingEntry; + + value(): + | number + | ConfigSettingContractComputeV0 + | ConfigSettingContractLedgerCostV0 + | ConfigSettingContractHistoricalDataV0 + | ConfigSettingContractEventsV0 + | ConfigSettingContractBandwidthV0 + | ContractCostParamEntry[] + | ContractCostParamEntry[] + | number + | number + | StateArchivalSettings + | ConfigSettingContractExecutionLanesV0 + | Uint64[] + | EvictionIterator + | ConfigSettingContractParallelComputeV0; + + toXDR(format?: 'raw'): Buffer; + + toXDR(format: 'hex' | 'base64'): string; + + static read(io: Buffer): ConfigSettingEntry; + + static write(value: ConfigSettingEntry, io: Buffer): void; + + static isValid(value: ConfigSettingEntry): boolean; + + static toXDR(value: ConfigSettingEntry): Buffer; + + static fromXDR(input: Buffer, format?: 'raw'): ConfigSettingEntry; + + static fromXDR(input: string, format: 'hex' | 'base64'): ConfigSettingEntry; + + static validateXDR(input: Buffer, format?: 'raw'): boolean; + + static validateXDR(input: string, format: 'hex' | 'base64'): boolean; + } +} diff --git a/node_modules/@stellar/stellar-base/types/xdr.d.ts b/node_modules/@stellar/stellar-base/types/xdr.d.ts new file mode 100644 index 000000000..2eb8791bf --- /dev/null +++ b/node_modules/@stellar/stellar-base/types/xdr.d.ts @@ -0,0 +1 @@ +export * from './curr'; diff --git a/node_modules/@stellar/stellar-sdk/CHANGELOG.md b/node_modules/@stellar/stellar-sdk/CHANGELOG.md new file mode 100644 index 000000000..9567bf7b0 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/CHANGELOG.md @@ -0,0 +1,1739 @@ + +# Changelog + +A breaking change will get clearly marked in this log. + + +## Unreleased + + +## [v13.1.0](https://github.com/stellar/js-stellar-sdk/compare/v13.0.0...v13.1.0) + +### Added +* Added `Horizon.Server.root` to obtain information from the Horizon root endpoint ([#1122](https://github.com/stellar/js-stellar-sdk/pull/1122/)). + +### Fixed +* When using a friendbot that points to a Horizon instance that has ledger metadata disabled, you can no longer extract the account sequence from the response. Instead, we hit RPC directly ([#1107](https://github.com/stellar/js-stellar-sdk/pull/1107/)). +* `rpc.Server.getEvents()` now correctly returns the `cursor` field at the top-level response ([#1124](https://github.com/stellar/js-stellar-sdk/pull/1124)). + + +## [v13.0.0](https://github.com/stellar/js-stellar-sdk/compare/v12.3.0...v13.0.0) +This is a direct re-tag of rc.2 with the only change being an upgrade to the `stellar-base` library to incorporate a patch release. Nonetheless, the entire changelog from the prior major version here is replicated for a comprehensive view on what's broken, added, and fixed. + +### Breaking Changes +- We stopped supporting Node 18 explicitly a while ago, but now the Babelification of the codebase will transform to Node 18 instead of 16. + +#### TypeScript Bindings: the `contract` module. +- `contract.AssembledTransaction#signAuthEntries` now takes an `address` instead of a `publicKey`. This brings the API more inline with its actual functionality: It can be used to sign all the auth entries for a particular _address_, whether that is the address of an account (public key) or a contract. ([#1044](https://github.com/stellar/js-stellar-sdk/pull/1044)). +- The `ClientOptions.signTransaction` type has been updated to reflect the latest [SEP-43](https://stellar.org/protocol/sep-43#wallet-interface-format) protocol, which matches the latest major version of Freighter and other wallets. It now accepts `address`, `submit`, and `submitUrl` options, and it returns a promise containing the `signedTxXdr` and the `signerAddress`. It now also returns an `Error` type if an error occurs during signing. + * `basicNodeSigner` has been updated to reflect this new type. +- `ClientOptions.signAuthEntry` type has been updated to reflect the [SEP-43](https://stellar.org/protocol/sep-43#wallet-interface-format) protocol, which returns a promise containing the `signerAddress` in addition to the `signAuthEntry` that was returned previously. It also can return an `Error` type. +- `SentTransaction.init` and `new SentTransaction` now take _one_ (1) argument instead of _two_ (2). The first argument had previously been deprecated and ignored. To update: +```diff +-SentTransaction(nonsense, realStuff) ++SentTransaction(realStuff) +-new SentTransaction(nonsense, realStuff) ++new SentTransaction(realStuff) +``` + +#### Server APIs: the `rpc` and `Horizon` modules. +- Deprecated RPC APIs have been removed ([#1084](https://github.com/stellar/js-stellar-sdk/pull/1084)): + * `simulateTransaction`'s `cost` field is removed + * `rpc.Server.getEvents`'s `pagingToken` field is deprecated, use `cursor` instead +- Deprecated Horizon APIs have been removed (deprecated since [v10.0.1](https://github.com/stellar/js-stellar-sdk/releases/tag/v10.0.1), []()): + * removed fields `transaction_count`, `base_fee`, and `base_reserve` + * removed fields `num_accounts` and `amount` from assets +- The `SorobanRpc` import, previously deprecated, has been removed. You can import `rpc` instead: +```diff +-import { SorobanRpc } from '@stellar/stellar-sdk' ++import { rpc } from '@stellar/stellar-sdk' +// alternatively, you can also import from the `rpc` entrypoint: +import { Server } from '@stellar/stellar-sdk/rpc' +``` + +### Added + +#### TypeScript Bindings: the `contract` module. +* `contract.Client` now has a static `deploy` method that can be used to deploy a contract instance from an existing uploaded/"installed" Wasm hash. The first arguments to this method are the arguments for the contract's `__constructor` method in accordance with [CAP-42](https://stellar.org/protocol/cap-42) ([#1086](https://github.com/stellar/js-stellar-sdk/pull/1086/)). For example, using the `increment` test contract as modified in https://github.com/stellar/soroban-test-examples/pull/2/files#diff-8734809100be3803c3ce38064730b4578074d7c2dc5fb7c05ca802b2248b18afR10-R45: +```typescript +const tx = await contract.Client.deploy( + { counter: 42 }, + { + networkPassphrase, + rpcUrl, + wasmHash: uploadedWasmHash, + publicKey: someKeypair.publicKey(), + ...basicNodeSigner(someKeypair, networkPassphrase), + }, +); +const { result: client } = await tx.signAndSend(); +const t = await client.get(); +expect(t.result, 42); +``` +* `contract.AssembledTransaction#signAuthEntries` now allows you to override `authorizeEntry`. This can be used to streamline novel workflows using cross-contract auth. ([#1044](https://github.com/stellar/js-stellar-sdk/pull/1044)). + +#### Server modules: the `rpc`, `Horizon`, and `stellartoml` modules. +* `Horizon.ServerApi` now has an `EffectType` exported so that you can compare and infer effect types directly ([#1099](https://github.com/stellar/js-stellar-sdk/pull/1099)). +* `Horizon.ServerApi.Trade` type now has a `type_i` field for type inference ([#1099](https://github.com/stellar/js-stellar-sdk/pull/1099)). +* All effects now expose their type as an exact string ([#947](https://github.com/stellar/js-stellar-sdk/pull/947)). +* `stellartoml.Resolver.resolve` now has a `allowedRedirects` option to configure the number of allowed redirects to follow when resolving a stellar toml file. +* `rpc.Server.getEvents` now returns a `cursor` field that matches `pagingToken` and `id` +* `rpc.Server.getTransactions` now returns a `txHash` field +* `rpc.Server` has two new methods: + - `pollTransaction` to retry transaction retrieval ([#1092]https://github.com/stellar/js-stellar-sdk/pull/1092), and + - `getSACBalance` to fetch the balance of a built-in Stellar Asset Contract token held by a contract ([#1046](https://github.com/stellar/js-stellar-sdk/pull/1046)), returning this schema: +```typescript +export interface BalanceResponse { + latestLedger: number; + /** present only on success, otherwise request malformed or no balance */ + balanceEntry?: { + /** a 64-bit integer */ + amount: string; + authorized: boolean; + clawback: boolean; + + lastModifiedLedgerSeq?: number; + liveUntilLedgerSeq?: number; + }; +} +``` + +#### New bundles without dependencies +- You can now build the browser bundle without various dependencies: + * Set `USE_AXIOS=false` to build without the `axios` dependency: this will build `stellar-sdk-no-axios.js` and `stellar-sdk-no-axios.min.js` in the `dist/` directory, or just run `yarn build:browser:no-axios` to generate these files. + * You can import Node packages without the `axios` dependency via `@stellar/stellar-sdk/no-axios`. For Node environments that don't support modern imports, use `@stellar/stellar-sdk/lib/no-axios/index`. + * Set `USE_EVENTSOURCE=false` to build without the `eventsource` dependency: this will build `stellar-sdk-no-eventsource.js` and `stellar-sdk-no-eventsource.min.js` in the `dist/` directory, or just run `yarn build:browser:no-eventsource` to generate these files. + * You can import Node packages without the `eventsource` dependency via `@stellar/stellar-sdk/no-eventsource`. For Node.js environments that don't support modern imports, use `@stellar/stellar-sdk/lib/no-eventsource/index`. + * To use a minimal build without both Axios and EventSource, use `stellar-sdk-minimal.js` for the browser build and import from `@stellar/stellar-sdk/minimal` for the Node package. + +### Fixed +- `contract.AssembledTransaction#nonInvokerSigningBy` now correctly returns contract addresses, in instances of cross-contract auth, rather than throwing an error. `sign` will ignore these contract addresses, since auth happens via cross-contract call ([#1044](https://github.com/stellar/js-stellar-sdk/pull/1044)). +- `buildInvocationTree` now correctly handles V2 contract creation and displays constructor args ([js-stellar-base#785](https://github.com/stellar/js-stellar-base/pull/785)). + + +## [v13.0.0-rc.2](https://github.com/stellar/js-stellar-sdk/compare/v13.0.0-rc.1...v13.0.0-rc.2) + +### Breaking Changes +- The `ClientOptions.signTransaction` type has been updated to reflect the latest [SEP-43](https://stellar.org/protocol/sep-43#wallet-interface-format) protocol, which matches the latest major version of Freighter and other wallets. It now accepts `address`, `submit`, and `submitUrl` options, and it returns a promise containing the `signedTxXdr` and the `signerAddress`. It now also returns an `Error` type if an error occurs during signing. + * `basicNodeSigner` has been updated to reflect the new type. +- `ClientOptions.signAuthEntry` type has also been updated to reflect the [SEP-43](https://stellar.org/protocol/sep-43#wallet-interface-format) protocol, which also returns a promise containing the `signerAddress` in addition to the `signAuthEntry` that was returned previously. It also can return an `Error` type. + +### Added +* `contract.Client` now has a static `deploy` method that can be used to deploy a contract instance from an existing uploaded/"installed" Wasm hash. The first arguments to this method are the arguments for the contract's `__constructor` method in accordance with CAP-42 ([#1086](https://github.com/stellar/js-stellar-sdk/pull/1086/)). + +For example, using the `increment` test contract as modified in https://github.com/stellar/soroban-test-examples/pull/2/files#diff-8734809100be3803c3ce38064730b4578074d7c2dc5fb7c05ca802b2248b18afR10-R45: +```typescript + const tx = await contract.Client.deploy( + { counter: 42 }, + { + networkPassphrase, + rpcUrl, + wasmHash: uploadedWasmHash, + publicKey: someKeypair.publicKey(), + ...basicNodeSigner(someKeypair, networkPassphrase), + }, + ); + const { result: client } = await tx.signAndSend(); + const t = await client.get(); + expect(t.result, 42); +``` +* `Horizon.ServerApi` now has an `EffectType` exported so that you can compare and infer effect types directly ([#1099](https://github.com/stellar/js-stellar-sdk/pull/1099)). +* `Horizon.ServerApi.Trade` type now has a `type_i` field for type inference. +* All effects now expose their type as an exact string ([#947](https://github.com/stellar/js-stellar-sdk/pull/947)). +* `stellartoml-Resolver.resolve` now has a `allowedRedirects` option to configure the number of allowed redirects to follow when resolving a stellar toml file. + + +## [v13.0.0-rc.1](https://github.com/stellar/js-stellar-sdk/compare/v13.0.0-beta.1...v13.0.0-rc.1) + +### Breaking Changes +- Deprecated RPC APIs have been removed ([#1084](https://github.com/stellar/js-stellar-sdk/pull/1084)): + * `simulateTransaction`'s `cost` field is removed + * `getEvents` returns a `cursor` field that matches `pagingToken` and `id` + * `getTransactions` returns a `txHash` field +- Horizon Server API types: removed fields `transaction_count`, `base_fee`, and `base_reserve` (deprecated since [v10.0.1](https://github.com/stellar/js-stellar-sdk/releases/tag/v10.0.1)) +- `SentTransaction.init` and `new SentTransaction` now take _one_ (1) argument instead of _two_ (2). The first argument had previously been deprecated and ignored. To update: + ```diff + -SentTransaction(nonsense, realStuff) + +SentTransaction(realStuff) + -new SentTransaction(nonsense, realStuff) + +new SentTransaction(realStuff) + ``` +- `SorobanRpc` import, previously deprecated, has been removed. You can import `rpc` instead: + ```diff + -import { SorobanRpc } from '@stellar/stellar-sdk' + +import { rpc } from '@stellar/stellar-sdk' + ``` + + As an alternative, you can also import from the `rpc` entrypoint: + + ```ts + import { Server } from '@stellar/stellar-sdk/rpc' + ``` + + +### Added +- `rpc.Server` now has a `pollTransaction` method to retry transaction retrieval ([#1092]https://github.com/stellar/js-stellar-sdk/pull/1092). + + +## [v13.0.0-beta.1](https://github.com/stellar/js-stellar-sdk/compare/v12.3.0...v13.0.0-beta.1) + +### Breaking Changes +- `contract.AssembledTransaction#signAuthEntries` now takes an `address` instead of a `publicKey`. This brings the API more inline with its actual functionality: It can be used to sign all the auth entries for a particular _address_, whether that is the address of an account (public key) or a contract. ([#1044](https://github.com/stellar/js-stellar-sdk/pull/1044)). +- The Node.js code will now Babelify to Node 18 instead of Node 16, but we stopped supporting Node 16 long ago so this shouldn't be a breaking change. + +### Added +- You can now build the browser bundle without various dependencies: + * Set `USE_AXIOS=false` to build without the `axios` dependency: this will build `stellar-sdk-no-axios.js` and `stellar-sdk-no-axios.min.js` in the `dist/` directory, or just run `yarn build:browser:no-axios` to generate these files. + * You can import Node packages without the `axios` dependency via `@stellar/stellar-sdk/no-axios`. For Node environments that don't support modern imports, use `@stellar/stellar-sdk/lib/no-axios/index`. + * Set `USE_EVENTSOURCE=false` to build without the `eventsource` dependency: this will build `stellar-sdk-no-eventsource.js` and `stellar-sdk-no-eventsource.min.js` in the `dist/` directory, or just run `yarn build:browser:no-eventsource` to generate these files. + * You can import Node packages without the `eventsource` dependency via `@stellar/stellar-sdk/no-eventsource`. For Node.js environments that don't support modern imports, use `@stellar/stellar-sdk/lib/no-eventsource/index`. + * To use a minimal build without both Axios and EventSource, use `stellar-sdk-minimal.js` for the browser build and import from `@stellar/stellar-sdk/minimal` for the Node package. +- `contract.AssembledTransaction#signAuthEntries` now allows you to override `authorizeEntry`. This can be used to streamline novel workflows using cross-contract auth. (#1044) +- `rpc.Server` now has a `getSACBalance` helper which lets you fetch the balance of a built-in Stellar Asset Contract token held by a contract ([#1046](https://github.com/stellar/js-stellar-sdk/pull/1046)): +```typescript +export interface BalanceResponse { + latestLedger: number; + /** present only on success, otherwise request malformed or no balance */ + balanceEntry?: { + /** a 64-bit integer */ + amount: string; + authorized: boolean; + clawback: boolean; + + lastModifiedLedgerSeq?: number; + liveUntilLedgerSeq?: number; + }; +} +``` + +### Fixed +- `contract.AssembledTransaction#nonInvokerSigningBy` now correctly returns contract addresses, in instances of cross-contract auth, rather than throwing an error. `sign` will ignore these contract addresses, since auth happens via cross-contract call ([#1044](https://github.com/stellar/js-stellar-sdk/pull/1044)). + + +## [v12.3.0](https://github.com/stellar/js-stellar-sdk/compare/v12.2.0...v12.3.0) + +### Added +- `rpc.Server` now has a `getTransactions`, which has the same response schema as `getTransactions` except with bundles of transactions ([#1037](https://github.com/stellar/js-stellar-sdk/pull/1037)). +- `rpc.Server` now has a `getVersionInfo` method which reports version information of the RPC instance it is connected to ([#1028](https://github.com/stellar/js-stellar-sdk/issues/1028)): + +```typescript +export interface GetVersionInfoResponse { + version: string; + commit_hash: string; + build_time_stamp: string; + captive_core_version: string; + protocol_version: number; +} +``` + +### Fixed +- Lower authorization entry's default signature expiration to ~8min for security reasons ([#1023](https://github.com/stellar/js-stellar-sdk/pull/1023)). +- Remove `statusText` error check to broaden compatibility ([#1001](https://github.com/stellar/js-stellar-sdk/pull/1001)). +- Upgraded `stellar-base` which includes various fixes ([release notes](https://github.com/stellar/js-stellar-base/releases/tag/v12.1.1), [#1045](https://github.com/stellar/js-stellar-sdk/pull/1045)). + + +## [v12.2.0](https://github.com/stellar/js-stellar-sdk/compare/v12.1.0...v12.2.0) + +### Fixed +- `@stellar/stellar-base` and its underlying dependency `@stellar/js-xdr` have been upgraded to their latest versions; reference their release notes ([v12.1.0](https://github.com/stellar/js-stellar-base/releases/tag/v12.1.0) and [v3.1.2](https://github.com/stellar/js-xdr/releases/tag/v3.1.2), respectively) for details ([#1013](https://github.com/stellar/js-stellar-sdk/pull/1013)). + +### Added +- You can now pass custom headers to both `rpc.Server` and `Horizon.Server` ([#1013](https://github.com/stellar/js-stellar-sdk/pull/1013)): +```typescript +import { Server } from "@stellar/stellar-sdk/rpc"; + +const s = new Server("", { headers: { "X-Custom-Header": "hello" }}) +``` +- `Horizon.Server` now supports the new `POST /transactions_async` endpoint via the `submitAsyncTransaction` method ([#989](https://github.com/stellar/js-stellar-sdk/pull/989)). Its purpose is to provide an immediate response to the submission rather than waiting for Horizon to determine its status. The response schema is as follows: +```typescript +interface SubmitAsyncTransactionResponse { + // the submitted transaction hash + hash: string; + // one of "PENDING", "DUPLICATE", "TRY_AGAIN_LATER", or "ERROR" + tx_status: string; + // a base64-encoded xdr.TransactionResult iff `tx_status` is "ERROR" + error_result_xdr: string; +} +``` +- `rpc.Server` now has a `getFeeStats` method which retrieves fee statistics for a previous chunk of ledgers to provide users with a way to provide informed decisions about getting their transactions included in the following ledgers ([#998](https://github.com/stellar/js-stellar-sdk/issues/998)): +```typescript +export interface GetFeeStatsResponse { + sorobanInclusionFee: FeeDistribution; + inclusionFee: FeeDistribution; + latestLedger: number; // uint32 +} + +interface FeeDistribution { + max: string; // uint64 + min: string; // uint64 + mode: string; // uint64 + p10: string; // uint64 + p20: string; // uint64 + p30: string; // uint64 + p40: string; // uint64 + p50: string; // uint64 + p60: string; // uint64 + p70: string; // uint64 + p80: string; // uint64 + p90: string; // uint64 + p95: string; // uint64 + p99: string; // uint64 + transactionCount: string; // uint32 + ledgerCount: number; // uint32 +} +``` + + +## [v12.1.0](https://github.com/stellar/js-stellar-sdk/compare/v12.0.1...v12.1.0) + +### Added +- `contract` now exports the `DEFAULT_TIMEOUT` ([#984](https://github.com/stellar/js-stellar-sdk/pull/984)). +- `contract.AssembledTransaction` now has: + - `toXDR` and `fromXDR` methods for serializing the transaction to and from XDR. These methods should be used in place of `AssembledTransaction.toJSON` and `AssembledTransaction.fromJSON`for multi-auth signing. The JSON methods are now deprecated. **Note:** you must now call `simulate` on the transaction before the final `signAndSend` call after all required signatures are gathered when using the XDR methods ([#977](https://github.com/stellar/js-stellar-sdk/pull/977)). + - a `restoreFootprint` method which accepts the `restorePreamble` returned when a simulation call fails due to some contract state that has expired. When invoking a contract function, one can now set `restore` to `true` in the `MethodOptions`. When enabled, a `restoreFootprint` transaction will be created and await signing when required ([#991](https://github.com/stellar/js-stellar-sdk/pull/991)). + - separate `sign` and `send` methods so that you can sign a transaction without sending it (`signAndSend` still works as before; [#922](https://github.com/stellar/js-stellar-sdk/pull/992)). +- `contract.Client` now has a `txFromXDR` method which should be used in place of `txFromJSON` for multi-auth signing ([#977](https://github.com/stellar/js-stellar-sdk/pull/977)). + +### Deprecated +- In `contract.AssembledTransaction`, `toJSON` and `fromJSON` should be replaced with `toXDR` and `fromXDR`. +- In `contract.Client`, `txFromJSON` should be replaced with `txFromXDR`. + +### Fixed +- If you edit an `AssembledTransaction` with `tx.raw = cloneFrom(tx.build)`, the `tx.simulationData` will now be updated correctly ([#985](https://github.com/stellar/js-stellar-sdk/pull/985)). + + +## [v12.0.1](https://github.com/stellar/js-stellar-sdk/compare/v11.3.0...v12.0.1) + +- This is a re-tag of `v12.0.0-rc.3` with dependency updates and a single new feature. + +### Added +- `rpc.server.simulateTransaction` now supports an optional `stateChanges?: LedgerEntryChange[]` field ([#963](https://github.com/stellar/js-stellar-sdk/pull/963)): + * If `Before` is omitted, it constitutes a creation, if `After` is omitted, it constitutes a deletions, note that `Before` and `After` cannot be omitted at the same time. Each item follows this schema: + +```typescript +interface LedgerEntryChange { + type: number; + key: xdr.LedgerKey; + before: xdr.LedgerEntry | null; + after: xdr.LedgerEntry | null; +} +``` + + +## [v12.0.0-rc.3](https://github.com/stellar/js-stellar-sdk/compare/v11.3.0...v12.0.0-rc.3) + +### Breaking Changes + +- `ContractClient` functionality previously added in [v11.3.0](https://github.com/stellar/js-stellar-sdk/releases/tag/v11.3.0) was exported in a non-standard way. You can now import it as any other `stellar-sdk` module ([#962](https://github.com/stellar/js-stellar-sdk/pull/962)): + +```diff +-import { ContractClient } from '@stellar/stellar-sdk/lib/contract_client' ++import { contract } from '@stellar/stellar-sdk' ++const { Client } = contract +``` + + Note that this top-level `contract` export is a container for ContractClient and related functionality. The `ContractClient` class is now available at `contract.Client`, as shown. Further note that there is a capitalized `Contract` export as well, which comes [from stellar-base](https://github.com/stellar/js-stellar-base/blob/b96281b9b3f94af23a913f93bdb62477f5434ccc/src/contract.js#L6-L19). You can remember which is which because capital-C `Contract` is a class, whereas lowercase-c `contract` is a container/module with a bunch of classes, functions, and types. + + Additionally, this is available from the `/contract` entrypoint, if your version of Node [and TypeScript](https://stackoverflow.com/a/70020984/249801) support [the `exports` declaration](https://nodejs.org/api/packages.html#exports). Finally, some of its exports have been renamed: + +```diff +import { +- ContractClient, ++ Client, + AssembledTransaction, +- ContractClientOptions, ++ ClientOptions, + SentTransaction, +-} from '@stellar/stellar-sdk/lib/contract_client' ++} from '@stellar/stellar-sdk/contract' +``` + +- The `ContractSpec` class is now nested under the `contract` module, and has been **renamed** to `Spec` ([#962](https://github.com/stellar/js-stellar-sdk/pull/962)). Alternatively, you can import this from the `contract` entrypoint, if your version of Node [and TypeScript](https://stackoverflow.com/a/70020984/249801) support [the `exports` declaration](https://nodejs.org/api/packages.html#exports): + +```diff +-import { ContractSpec } from '@stellar/stellar-sdk' ++import { contract } from '@stellar/stellar-sdk' ++const { Spec } = contract +// OR ++import { Spec } from '@stellar/stellar-sdk/contract' +``` + +- Previously, `AssembledTransaction.signAndSend()` would return a `SentTransaction` even if the transaction was never finalized. That is, if it successfully sent the transaction to the network, but the transaction was still `status: 'PENDING'`, then it would `console.error` an error message, but return the indeterminate transaction anyhow. **It now throws** a `SentTransaction.Errors.TransactionStillPending` error with that error message instead ([#962](https://github.com/stellar/js-stellar-sdk/pull/962)). + +### Deprecated + +- `SorobanRpc` module is now also exported as `rpc` ([#962](https://github.com/stellar/js-stellar-sdk/pull/962)). You can import it with either name for now, but `SorobanRpc` will be removed in a future release: + +```diff +-import { SorobanRpc } from '@stellar/stellar-sdk' ++import { rpc } from '@stellar/stellar-sdk' +``` + + You can also now import it at the `/rpc` entrypoint, if your version of Node [and TypeScript](https://stackoverflow.com/a/70020984/249801) support [the `exports` declaration](https://nodejs.org/api/packages.html#exports). + +```diff +-import { SorobanRpc } from '@stellar/stellar-sdk' +-const { Api } = SorobanRpc ++import { Api } from '@stellar/stellar-sdk/rpc' +``` + +### Added +* New methods on `contract.Client` ([#960](https://github.com/stellar/js-stellar-sdk/pull/960)): + - `from(opts: ContractClientOptions)` instantiates `contract.Client` by fetching the `contractId`'s WASM from the network to fill out the client's `ContractSpec`. + - `fromWasm` and `fromWasmHash` methods to instantiate a `contract.Client` when you already have the WASM bytes or hash alongside the `contract.ClientOptions`. +* New methods on `rpc.Server` ([#960](https://github.com/stellar/js-stellar-sdk/pull/960)): + - `getContractWasmByContractId` and `getContractWasmByHash` to retrieve a contract's WASM bytecode via its `contractId` or `wasmHash`, respectively. + +### Fixed +* The breaking changes above (strictly speaking, they are not breaking changes because importing from the inner guts of the SDK is not supported) enable the `contract` module to be used in non-Node environments. + + +## [v12.0.0-rc.2](https://github.com/stellar/js-stellar-sdk/compare/v11.3.0...v12.0.0-rc.2) + +**This update supports Protocol 21**. It is an additive change to the protocol so there are no true backwards incompatibilities, but your software may break if you encounter new unexpected fields from this Protocol ([#949](https://github.com/stellar/js-stellar-sdk/pull/949)). + +### Breaking Changes +* The **default timeout for transaction calls is now set to 300 seconds (5 minutes)** from the previous default of 10 seconds. 10 seconds is often not enough time to review transactions before signing, especially in Freighter or using a hardware wallet like a Ledger, which would cause a `txTooLate` error response from the server. Five minutes is also the value used by the CLI, so this brings the two into alignment ([#956](https://github.com/stellar/js-stellar-sdk/pull/956)). + +### Fixed +* Dependencies have been properly updated to pull in Protocol 21 XDR ([#959](https://github.com/stellar/js-stellar-sdk/pull/959)). + + +## [v12.0.0-rc.1](https://github.com/stellar/js-stellar-sdk/compare/v11.3.0...v12.0.0-rc.1) + +### Breaking Changes +* **This update supports Protocol 21**. It is an additive change to the protocol so there are no true backwards incompatibilities, but your software may break if you encounter new unexpected fields from this Protocol ([#949](https://github.com/stellar/js-stellar-sdk/pull/949)). + +### Fixed +* Each item in the `GetEventsResponse.events` list will now have a `txHash` item corresponding to the transaction hash that triggered a particular event ([#939](https://github.com/stellar/js-stellar-sdk/pull/939)). +* `ContractClient` now properly handles methods that take no arguments by making `MethodOptions` the only parameter, bringing it inline with the types generated by Soroban CLI's `soroban contract bindings typescript` ([#940](https://github.com/stellar/js-stellar-sdk/pull/940)). +* `ContractClient` now allows `publicKey` to be undefined ([#941](https://github.com/stellar/js-stellar-sdk/pull/941)). +* `SentTransaction` will only pass `allowHttp` if (and only if) its corresponding `AssembledTransaction#options` config allowed it ([#952](https://github.com/stellar/js-stellar-sdk/pull/952)). +* `SentTransaction` will now modify the time bounds of the transaction to be `timeoutInSeconds` seconds after the transaction has been simulated. Previously this was set when the transaction is built, before the simulation. This makes the time bounds line up with the timeout retry logic in `SentTransaction`. + +## [v11.3.0](https://github.com/stellar/js-stellar-sdk/compare/v11.2.2...v11.3.0) + +### Added +* Introduces an entire suite of helpers to assist with interacting with smart contracts ([#929](https://github.com/stellar/js-stellar-sdk/pull/929)): + - `ContractClient`: generate a class from the contract specification where each Rust contract method gets a matching method in this class. Each method returns an `AssembledTransaction` that can be used to modify, simulate, decode results, and possibly sign, & submit the transaction. + - `AssembledTransaction`: used to wrap a transaction-under-construction and provide high-level interfaces to the most common workflows, while still providing access to low-level transaction manipulation. + - `SentTransaction`: transaction sent to the Soroban network, in two steps - initial submission and waiting for it to finalize to get the result (retried with exponential backoff) + +### Fixed +* Upgrade underlying dependencies, including `@stellar/js-xdr` which should broaden compatibility to pre-ES2016 environments ([#932](https://github.com/stellar/js-stellar-sdk/pull/932), [#930](https://github.com/stellar/js-stellar-sdk/pull/930)). + + +### Fixed +* `SorobanRpc`: remove all instances of array-based parsing to conform to future breaking changes in Soroban RPC ([#924](https://github.com/stellar/js-stellar-sdk/pull/924)). + + +## [v11.2.2](https://github.com/stellar/js-stellar-sdk/compare/v11.2.1...v11.2.2) + +### Fixed +* Event streaming tests now pass on Node 20, which seems to have tighter conformance to the spec ([#917](https://github.com/stellar/js-stellar-sdk/pull/917)). +* `@stellar/stellar-base` has been upgraded to its latest major version ([#918](https://github.com/stellar/js-stellar-sdk/pull/918), see [v11.0.0](https://github.com/stellar/js-stellar-base/releases/tag/v11.0.0) for release notes). + + +## [v11.2.1](https://github.com/stellar/js-stellar-sdk/compare/v11.2.0...v11.2.1) + +### Fixed +* An unnecessary dependency has been removed which was causing a TypeScript error in certain environments ([#912](https://github.com/stellar/js-stellar-sdk/pull/912)). +* Dependencies have been upgraded (see [`stellar-base@v10.0.2`](https://github.com/stellar/js-stellar-base/releases/tag/v10.0.2) for release notes, [#913](https://github.com/stellar/js-stellar-sdk/pull/913)). + + +## [v11.2.0](https://github.com/stellar/js-stellar-sdk/compare/v11.1.0...v11.2.0) + +### Added +* Support for the new, optional `diagnosticEventsXdr` field on the `SorobanRpc.Server.sendTransaction` method. The raw field will be present when using the `_sendTransaction` method, while the normal method will have an already-parsed `diagnosticEvents: xdr.DiagnosticEvent[]` field, instead ([#905](https://github.com/stellar/js-stellar-sdk/pull/905)). +* A new exported interface `SorobanRpc.Api.EventResponse` so that developers can type-check individual events ([#904](https://github.com/stellar/js-stellar-sdk/pull/904)). + +### Updated +* Dependencies have been updated to their latest versions ([#906](https://github.com/stellar/js-stellar-sdk/pull/906), [#908](https://github.com/stellar/js-stellar-sdk/pull/908)). + + +## [v11.1.0](https://github.com/stellar/js-stellar-sdk/compare/v11.0.1...v11.1.0) + +### Added +* `SorobanRpc.Server.simulateTransaction` now supports an optional `addlResources` parameter to allow users to specify additional resources that they want to include in a simulation ([#896](https://github.com/stellar/js-stellar-sdk/pull/896)). +* `ContractSpec` now has a `jsonSchema()` method to generate a [JSON Schema](https://json-schema.org/) for a particular contract specification ([#889](https://github.com/stellar/js-stellar-sdk/pull/889)). + +### Fixed +* All dependencies have been updated to their latest versions, including `stellar-base` to [v10.0.1](https://github.com/stellar/js-stellar-base/releases/tag/v10.0.1) which included a small patch ([#897](https://github.com/stellar/js-stellar-sdk/pull/897)). + + +## [v11.0.1](https://github.com/stellar/js-stellar-sdk/compare/v10.2.1...v11.0.0) + +### Fixed +* `SorobanRpc.Server.getEvents` uses the correct type for the start ledger. + + +## [v11.0.0](https://github.com/stellar/js-stellar-sdk/compare/v10.2.1...v11.0.0) + +### Breaking Changes + +* The package has been renamed to `@stellar/stellar-sdk`. +* The new minimum supported version is Node 18. +* The `PaymentCallBuilder` was incorrectly indicating that it would return a collection of `Payment` records, while [in reality](https://developers.stellar.org/api/horizon/resources/list-all-payments) it can return a handful of "payment-like" records ([#885](https://github.com/stellar/js-stellar-sdk/pull/885)). + +### Fixed +* The `SorobanRpc.Server.getEvents` method now correctly parses responses without a `contractId` field set. The `events[i].contractId` field on an event is now optional, omitted if there was no ID for the event (e.g. system events; ([#883](https://github.com/stellar/js-stellar-sdk/pull/883))). + + +## [v11.0.0-beta.6](https://github.com/stellar/js-stellar-sdk/compare/v11.0.0-beta.5...v11.0.0-beta.6) + +### Fixed +* The `stellar-base` library has been upgraded to `beta.4` which contains a bugfix for large sequence numbers ([#877](https://github.com/stellar/js-stellar-sdk/pull/877)). +* The `SorobanRpc.Server.getTransaction()` method will now return the full response when encountering a `FAILED` transaction result ([#872](https://github.com/stellar/js-stellar-sdk/pull/872)). +* The `SorobanRpc.Server.getEvents()` method will correctly parse the event value (which is an `xdr.ScVal` rather than an `xdr.DiagnosticEvent`, see the modified `SorobanRpc.Api.EventResponse.value`; [#876](https://github.com/stellar/js-stellar-sdk/pull/876)). + + +## [v11.0.0-beta.5](https://github.com/stellar/js-stellar-sdk/compare/v11.0.0-beta.4...v11.0.0-beta.5) + +### Breaking Changes +* The `soroban-client` library ([stellar/js-soroban-client](https://github.com/stellar/js-soroban-client)) has been merged into this package, causing significant breaking changes in the module structure ([#860](https://github.com/stellar/js-stellar-sdk/pull/860)): + - The namespaces have changed to move each server-dependent component into its own module. Shared components (e.g. `TransactionBuilder`) are still in the top level, Horizon-specific interactions are in the `Horizon` namespace (i.e. `Server` is now `Horizon.Server`), and new Soroban RPC interactions are in the `SorobanRpc` namespace. + - There is a [detailed migration guide](https://gist.github.com/Shaptic/5ce4f16d9cce7118f391fbde398c2f30) available to outline both the literal (i.e. necessary code changes) and philosophical (i.e. how to find certain functionality) changes needed to adapt to this merge. +* The `SorobanRpc.Server.prepareTransaction` and `SorobanRpc.assembleTransaction` methods no longer need an optional `networkPassphrase` parameter, because it is implicitly part of the transaction already ([#870](https://github.com/stellar/js-stellar-sdk/pull/870)). + + +## [v11.0.0-beta.4](https://github.com/stellar/js-stellar-sdk/compare/v11.0.0-beta.3...v11.0.0-beta.4) + +### Fixed +- The `stellar-base` dependency has been pinned to a specific version to avoid incorrect semver resolution ([#867](https://github.com/stellar/js-stellar-sdk/pull/867)). + + +## [v11.0.0-beta.3](https://github.com/stellar/js-stellar-sdk/compare/v11.0.0-beta.2...v11.0.0-beta.3) + +### Fixed +- Fix a webpack error preventing correct exports of the SDK for browsers ([#862](https://github.com/stellar/js-stellar-sdk/pull/862)). + + +## [v11.0.0-beta.2](https://github.com/stellar/js-stellar-sdk/compare/v11.0.0-beta.1...v11.0.0-beta.2) + +### Breaking Changes +- Certain effects have been renamed to align better with the "tense" that other structures have ([#844](https://github.com/stellar/js-stellar-sdk/pull/844)): + * `DepositLiquidityEffect` -> `LiquidityPoolDeposited` + * `WithdrawLiquidityEffect` -> `LiquidityPoolWithdrew` + * `LiquidityPoolTradeEffect` -> `LiquidityPoolTrade` + * `LiquidityPoolCreatedEffect` -> `LiquidityPoolCreated` + * `LiquidityPoolRevokedEffect` -> `LiquidityPoolRevoked` + * `LiquidityPoolRemovedEffect` -> `LiquidityPoolRemoved` + +### Add +- New effects have been added to support Protocol 20 (Soroban) ([#842](https://github.com/stellar/js-stellar-sdk/pull/842)): + * `ContractCredited` occurs when a Stellar asset moves **into** its corresponding Stellar Asset Contract instance + * `ContractDebited` occurs when a Stellar asset moves **out of** its corresponding Stellar Asset Contract instance +- Asset stat records (`ServerApi.AssetRecord`) contain two new fields to support the Protocol 20 (Soroban) release ([#841](https://github.com/stellar/js-stellar-sdk/pull/841)): + * `num_contracts` - the integer quantity of contracts that hold this asset + * `contracts_amount` - the total units of that asset held by contracts +- New operation responses ([#845](https://github.com/stellar/js-stellar-sdk/pull/845)): + * `invokeHostFunction`: see `Horizon.InvokeHostFunctionOperationResponse` + * `bumpFootprintExpiration`: see `Horizon.BumpFootprintExpirationOperationResponse` + * `restoreFootprint`: see `Horizon.RestoreFootprintOperationResponse` + * You can refer to the actual definitions for details, but the gist of the schemas is below: +```ts +interface InvokeHostFunctionOperationResponse { + function: string; + parameters: { + value: string; + type: string; + }[]; + address: string; + salt: string; + asset_balance_changes: { + type: string; + from: string; + to: string; + amount: string; + }[]; +} +interface BumpFootprintExpirationOperationResponse { + ledgersToExpire: string; +} +interface RestoreFootprintOperationResponse {}; +``` + +### Fixed +- Some effect definitions that were missing have been added ([#842](https://github.com/stellar/js-stellar-sdk/pull/842)): + * `ClaimableBalanceClawedBack` is now defined + * `type EffectRecord` now has all of the effect types +- The `stellar-base` library has been upgraded to support the latest Protocol 20 XDR schema and all Soroban functionality ([]()). + + +## [v11.0.0-beta.1](https://github.com/stellar/js-stellar-sdk/compare/v11.0.0-beta.0...v11.0.0-beta.1) + +### Update + +- Bundle size has decreased by dropping unnecessary dependencies (`lodash`: [#822](https://github.com/stellar/js-stellar-sdk/pull/822), `es6-promise`: [#823](https://github.com/stellar/js-stellar-sdk/pull/823), polyfills: [#825](https://github.com/stellar/js-stellar-sdk/pull/825), `detect-node`: [#831](https://github.com/stellar/js-stellar-sdk/issues/831)). +- Dependencies (including `stellar-base`) have been updated to their latest versions ([#825](https://github.com/stellar/js-stellar-sdk/pull/825), [#827](https://github.com/stellar/js-stellar-sdk/pull/827)). + + +## [v11.0.0-beta.0](https://github.com/stellar/js-stellar-sdk/compare/v10.4.1...v11.0.0-beta.0) + +This version is marked by a major version bump because of the significant upgrades to underlying dependencies. While there should be no noticeable API changes from a downstream perspective, there may be breaking changes in the way that this library is bundled. + +### Update + +- Build system has been overhauled to support Webpack 5 ([#814](https://github.com/stellar/js-stellar-sdk/pull/814)). +- `stellar-base` has been updated to its corresponding overhaul ([#818](https://github.com/stellar/js-stellar-sdk/pull/818)). + +### Fix + +- Missing fields have been added to certain API responses ([#801](https://github.com/stellar/js-stellar-sdk/pull/801) and [#797](https://github.com/stellar/js-stellar-sdk/pull/797)). + + +## [v10.4.1](https://github.com/stellar/js-stellar-sdk/compare/v10.4.0...v10.4.1) + +### Update + +- Bumps `stellar-base` version to [v8.2.2](https://github.com/stellar/js-stellar-base/releases/tag/v8.2.2) to include latest fix: enabling fast signing in service workers ([#806](https://github.com/stellar/js-stellar-sdk/pull/806)). + + +## [v10.4.0](https://github.com/stellar/js-stellar-sdk/compare/v10.3.0...v10.4.0) + +### Add + +- Add [SEP-1](https://stellar.org/protocol/sep-1) fields to `StellarTomlResolver` for type checks ([#794](https://github.com/stellar/js-stellar-sdk/pull/794)). +- Add support for passing `X-Auth-Token` as a custom header ([#795](https://github.com/stellar/js-stellar-sdk/pull/795)). + +### Update + +- Bumps `stellar-base` version to [v8.2.1](https://github.com/stellar/js-stellar-base/releases/tag/v8.2.1) to include latest fixes. + + +## [v10.3.0](https://github.com/stellar/js-stellar-sdk/compare/v10.2.0...v10.3.0) + +### Fix + +- Adds `successful` field to transaction submission response ([#790](https://github.com/stellar/js-stellar-sdk/pull/790)). + +### Update + +- Bumps `stellar-base` version to [v8.2.0](https://github.com/stellar/js-stellar-base/releases/tag/v8.2.0) to include CAP-40 support in `Operation.setOptions`. + + +## [v10.2.0](https://github.com/stellar/js-stellar-sdk/compare/v10.1.2...v10.2.0) + +### Fix + +- Adds the missing `successful` field to transaction responses ([#790](https://github.com/stellar/js-stellar-sdk/pull/790)). + +### Update + +- Bumps `stellar-base` version to [v8.1.0](https://github.com/stellar/js-stellar-base/releases/tag/v8.1.0) to include bug fixes and latest XDR changes. + + +## [v10.1.2](https://github.com/stellar/js-stellar-sdk/compare/v10.1.1...v10.1.2) + +### Fix + +- Upgrades the `eventsource` dependency to fix a critical security vulnerability ([#783](https://github.com/stellar/js-stellar-sdk/pull/783)). + + +## [v10.1.1](https://github.com/stellar/js-stellar-sdk/compare/v10.1.0...v10.1.1) + +### Fix + +- Reverts a change from [v10.1.0](#v10.1.0) which caused streams to die prematurely ([#780](https://github.com/stellar/js-stellar-sdk/pull/780)). +- Bumps `stellar-base` version to [v8.0.1](https://github.com/stellar/js-stellar-base/releases/tag/v8.0.1) to include latest bugfixes. + + +## [v10.1.0](https://github.com/stellar/js-stellar-sdk/compare/v10.0.1...v10.1.0-beta.0) + +This is a promotion from the beta version without changes, besides upgrading the underlying [stellar-base@v8.0.0](https://github.com/stellar/js-stellar-base/releases/tag/v8.0.0) to its stable release. + + +## [v10.1.0-beta.0](https://github.com/stellar/js-stellar-sdk/compare/v10.0.1...v10.1.0-beta.0) + +### Add + +- Add a way to filter offers by seller: `OfferCallBuilder.seller(string)`, corresponding to `GET /offers?seller=` ([#773](https://github.com/stellar/js-stellar-sdk/pull/773)). + +### Add + +- Support for Protocol 19 ([#775](https://github.com/stellar/js-stellar-sdk/pull/775)): + * new precondition fields on a `TransactionResponse` + * new account fields on `AccountResponse` and `AccountRecord` + * bumping `stellar-base` to the latest beta version + +### Fix + +- Add missing field to account responses: `last_modified_time` which is the time equivalent of the existing `last_modified_ledger` ([#770](https://github.com/stellar/js-stellar-sdk/pull/770)). +- Stop opening extra connections when SSE streams receive `event: close` events ([#772](https://github.com/stellar/js-stellar-sdk/pull/772)). +- Fix SSE streams not loading under React Native (thank you, @hunterpetersen!) ([#761](https://github.com/stellar/js-stellar-sdk/pull/761)). + + +## [v10.0.1](https://github.com/stellar/js-stellar-sdk/compare/v10.0.0...v10.0.1) + +### Fix + +- Add missing fields to the `LedgerRecord`: `successful_transaction_count` and `failed_transaction_count` ([#740](https://github.com/stellar/js-stellar-sdk/pull/740)). Note that this also marks several fields as _deprecated_ because they don't actually exist in the Horizon API response: + * `transaction_count`: superceded by the sum of the aforementioned fields + * `base_fee`: superceded by the `base_fee_in_stroops` field + * `base_reserve`: superceded by the `base_reserve_in_stroops` field + +These deprecated fields will be removed in the next major version. It's unlikely that this breaking change should affect anyone, as these fields have likely been missing/invalid for some time. + +### Update +- Update a number of dependencies that needed various security updates: + * several dependencies bumped their patch version ([#736](https://github.com/stellar/js-stellar-sdk/pull/736), [#684](https://github.com/stellar/js-stellar-sdk/pull/684), [#672](https://github.com/stellar/js-stellar-sdk/pull/672), [#666](https://github.com/stellar/js-stellar-sdk/pull/666), [#644](https://github.com/stellar/js-stellar-sdk/pull/644), [#622](https://github.com/stellar/js-stellar-sdk/pull/622)) + * axios has been bumped to 0.25.0 without causing breaking changes ([#742](https://github.com/stellar/js-stellar-sdk/pull/742)) + * the `karma` suite of packages has been updated to the latest major version ([#743](https://github.com/stellar/js-stellar-sdk/pull/743)) + +All of the dependencies in question besides `axios` were _developer_ dependencies, so there never was downstream security impact nor will there be downstream upgrade impact. + + +## [v10.0.0](https://github.com/stellar/js-stellar-sdk/compare/v9.1.0...v10.0.0) + +This release introduces breaking changes from `stellar-base`. It adds **unconditional support for muxed accounts**. Please refer to the corresponding [release notes](https://github.com/stellar/js-stellar-base/releases/tag/v7.0.0) for details on the breaking changes there. + +### Breaking Updates + +- Upgrades the stellar-base library to v7.0.0 ([#735](https://github.com/stellar/js-stellar-sdk/pull/735)). + +- Removes the `AccountResponse.createSubaccount` method since this is also gone from the underlying `Account` interface. The `stellar-base` release notes describe alternative construction methods ([#735](https://github.com/stellar/js-stellar-sdk/pull/735)). + +### Fix + +- Use the right string for liquidity pool trades ([#734](https://github.com/stellar/js-stellar-sdk/pull/734)). + + +## [v9.1.0](https://github.com/stellar/js-stellar-sdk/compare/v9.0.1...v9.1.0) + +### Add + +- Adds a way to filter liquidity pools by participating account: `server.liquidityPools.forAccount(id)` ([#727](https://github.com/stellar/js-stellar-sdk/pull/727)). + +### Updates + +- Updates the following SEP-10 utility functions to include [client domain verification](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0010.md#verifying-the-client-domain) functionality ([#720](https://github.com/stellar/js-stellar-sdk/pull/720)): + - `Utils.buildChallengeTx()` accepts the `clientDomain` and `clientSigningKey` optional parameters + - `Utils.readChallengeTx()` parses challenge transactions containing a `client_domain` ManageData operation + - `Utils.verifyChallengeTxSigners()` verifies an additional signature from the `clientSigningKey` keypair if a `client_domain` Manage Data operation is included in the challenge + +- Bumps `stellar-base` version to [v6.0.6](https://github.com/stellar/js-stellar-base/releases/tag/v6.0.6). + +### Fix + +- Fixes the `type_i` enumeration field to accurately reflect liquidity pool effects ([#723](https://github.com/stellar/js-stellar-sdk/pull/723)). + +- Upgrades axios dependency to v0.21.4 to alleviate security concern ([GHSA-cph5-m8f7-6c5x](https://github.com/advisories/GHSA-cph5-m8f7-6c5x), [#724](https://github.com/stellar/js-stellar-sdk/pull/724)). + +- Publish Bower package to [stellar/bower-js-stellar-sdk](https://github.com/stellar/bower-js-stellar-sdk) ([#725](https://github.com/stellar/js-stellar-sdk/pull/725)). + + +## [v9.0.1](https://github.com/stellar/js-stellar-sdk/compare/v9.0.0-beta.1...v9.0.1) + +This stable release adds **support for Protocol 18**. For details, you can refer to [CAP-38](https://stellar.org/protocol/cap-38) for XDR changes and [this document](https://docs.google.com/document/d/1pXL8kr1a2vfYSap9T67R-g72B_WWbaE1YsLMa04OgoU/view) for changes to the Horizon API. + +Refer to the release notes for the betas (e.g. [v9.0.0-beta.0](https://github.com/stellar/js-stellar-sdk/releases/v9.0.0-beta.0)) for a comprehensive list of changes to this library. + +### Fix + +- Corrects the `reserves` field on `LiquidityPoolRecord`s to be an array ([#715](https://github.com/stellar/js-stellar-sdk/pull/715)). +- Bumps the `stellar-base` dependency to [v6.0.4](https://github.com/stellar/js-stellar-base/releases/tag/v6.0.4) ([#715](https://github.com/stellar/js-stellar-sdk/pull/715)). + + +## [v9.0.0-beta.1](https://github.com/stellar/js-stellar-sdk/compare/v9.0.0-beta.0...v9.0.0-beta.1) + +### Add + +- Add `/liquidity_pools/:id/trades` endpoint ([#710](https://github.com/stellar/js-stellar-sdk/pull/710)) + +### Updates + +- Updates the following SEP-10 utility functions to be compliant with the protocols ([#709](https://github.com/stellar/js-stellar-sdk/pull/709/), [stellar-protocol/#1036](https://github.com/stellar/stellar-protocol/pull/1036)) + - Updated `utils.buildChallengeTx()` to accept muxed accounts (`M...`) for client account IDs + - Updated `utils.buildChallengeTx()` to accept a `memo` parameter to attach to the challenge transaction + - Updated `utils.readChallengeTx()` to provide a `memo` property in the returned object + - Updated `utils.readChallengeTx()` to validate challenge transactions with muxed accounts (`M...`) as the client account ID + +### Fix + +- Drops the `chai-http` dependency to be only for developers ([#707](https://github.com/stellar/js-stellar-sdk/pull/707)). + +## [v9.0.0-beta.0](https://github.com/stellar/js-stellar-sdk/compare/v8.2.5...v9.0.0-beta.0) + +This beta release adds **support for Automated Market Makers**. For details, you can refer to [CAP-38](https://stellar.org/protocol/cap-38) for XDR changes and [this document](https://docs.google.com/document/d/1pXL8kr1a2vfYSap9T67R-g72B_WWbaE1YsLMa04OgoU/view) for detailed changes to the Horizon API. + +### Add + +- Introduced a `LiquidityPoolCallBuilder` to make calls to a new endpoint: + * `/liquidity_pools[?reserves=...]` - a collection of liquidity pools, optionally filtered by one or more assets ([#682](https://github.com/stellar/js-stellar-sdk/pull/682)) + * `/liquidity_pools/:id` - a specific liquidity pool ([#687](https://github.com/stellar/js-stellar-sdk/pull/687)) + +- Expanded the `TransactionCallBuilder`, `OperationCallBuilder`, and `EffectsCallBuilder`s to apply to specific liquidity pools ([#689](https://github.com/stellar/js-stellar-sdk/pull/689)). This corresponds to the following new endpoints: + * `/liquidity_pools/:id/transactions` + * `/liquidity_pools/:id/operations` + * `/liquidity_pools/:id/effects` + +- Expanded the `TradesCallBuilder` to support fetching liquidity pool trades and accepts a new `trade_type` filter ([#685](https://github.com/stellar/js-stellar-sdk/pull/685)): + * `/trades?trade_type={orderbook,liquidity_pools,all}`. By default, the filter is `all`, including both liquidity pool and orderbook records. + * A liquidity pool trade contains the following fields: + - `liquidity_pool_fee_bp`: LP fee expressed in basis points, and *either* + - `base_liquidity_pool_id` or `counter_liquidity_pool_id` + +- Added new effects related to liquidity pools ([#690](https://github.com/stellar/js-stellar-sdk/pull/690)): + * `DepositLiquidityEffect` + * `WithdrawLiquidityEffect` + * `LiquidityPoolTradeEffect` + * `LiquidityPoolCreatedEffect` + * `LiquidityPoolRemovedEffect` + * `LiquidityPoolRevokedEffect` + +- Added new responses related to liquidity pool operations ([#692](https://github.com/stellar/js-stellar-sdk/pull/692)): + * `DepositLiquidityOperationResponse` + * `WithdrawLiquidityOperationResponse` + +### Updates + +- Updated the underlying `stellar-base` library to [v6.0.1](https://github.com/stellar/js-stellar-base/releases/tag/v6.0.1) to include CAP-38 changes ([#681](https://github.com/stellar/js-stellar-sdk/pull/681)). + +- Updated various developer dependencies to secure versions ([#671](https://github.com/stellar/js-stellar-sdk/pull/671)). + +- Updated `AccountResponse` to include liquidity pool shares in its `balances` field ([#688](https://github.com/stellar/js-stellar-sdk/pull/688)). + +- Updated `AccountCallBuilder` to allow filtering based on participation in a certain liquidity pool ([#688](https://github.com/stellar/js-stellar-sdk/pull/688)), corresponding to the following new filter: + * `/accounts?reserves=[...list of assets...]` + +- Updated `RevokeSponsorshipOperationResponse` to contain an optional attribute `trustline_liquidity_pool_id`, for when a liquidity pool trustline is revoked ([#690](https://github.com/stellar/js-stellar-sdk/pull/690)). + +### Breaking changes + +- A `TradeRecord` can now correspond to two different types of trades and has changed ([#685](https://github.com/stellar/js-stellar-sdk/pull/685)): + * `Orderbook` (the existing structure) + - `counter_offer_id` and `base_offer_id` only show up in these records + - the redundant `offer_id` field was removed; it matches `base_offer_id` + * `LiquidityPool` (new) + - `base_account` xor `counter_account` will appear in these records + * `price` fields changed from `number`s to `string`s + * The links to `base` and `counter` can now point to *either* an account or a liquidity pool + +- An account's `balances` array can now include a new type ([#688](https://github.com/stellar/js-stellar-sdk/pull/688)): + * `asset_type` can now be `liquidity_pool_shares` + * The following fields are *not* included in pool share balances: + - `buying_liabilities` + - `selling_liabilities` + - `asset_code` + - `asset_issue` + +- The `ChangeTrustOperationResponse` has changed ([#688](https://github.com/stellar/js-stellar-sdk/pull/688), [#692](https://github.com/stellar/js-stellar-sdk/pull/692)): + * `asset_type` can now be `liquidity_pool_shares` + * `asset_code`, `asset_issuer`, and `trustee` are now optional + * `liquidity_pool_id` is a new optional field + +- The trustline effects (`TrustlineCreated`, `TrustlineUpdated`, `TrustlineRevoked`) have changed ([#690](https://github.com/stellar/js-stellar-sdk/pull/690)): + * the asset type can now be `liquidity_pool_shares` + * they can optionally include a `liquidity_pool_id` + +- Trustline sponsorship effects (`TrustlineSponsorshipCreated`, `TrustlineSponsorshipUpdated`, `TrustlineSponsorshipRemoved`) have been updated ([#690](https://github.com/stellar/js-stellar-sdk/pull/690)): + * the `asset` field is now optional, and is replaced by + * the `liquidity_pool_id` field for liquidity pools + + +## [v8.2.5](https://github.com/stellar/js-stellar-sdk/compare/v8.2.4...v8.2.5) + +### Update +- The `js-stellar-base` library has been updated to [v5.3.2](https://github.com/stellar/js-stellar-base/releases/tag/v5.3.2), which fixes a muxed account bug and updates vulnerable dependencies ([#670](https://github.com/stellar/js-stellar-sdk/pull/670)). + + +## [v8.2.4](https://github.com/stellar/js-stellar-sdk/compare/v8.2.3...v8.2.4) + +### Fix +- Utils.readTransactionTx now checks timebounds with a 5-minute grace period to account for clock drift. + + +## [v8.2.3](https://github.com/stellar/js-stellar-sdk/compare/v8.2.2...v8.2.3) + +### Fix +- Fix server signature verification in `Utils.readChallengeTx`. The function was +not verifying the server account had signed the challenge transaction. + + +## [v8.2.2](https://github.com/stellar/js-stellar-sdk/compare/v8.2.1...v8.2.2) + +### Fix +- Fixes a breaking bug introduced in v8.2.0 in which `AccountResponse` no longer conformed to the `StellarBase.Account` interface, which was updated in [stellar-base@v5.2.0](https://github.com/stellar/js-stellar-base/releases/tag/v5.2.0) [(#655)](https://github.com/stellar/js-stellar-sdk/pull/655). + + +## [v8.2.1](https://github.com/stellar/js-stellar-sdk/compare/v8.2.0...v8.2.1) + +### Fix +- A defunct query paramater (`?c=[...]`) has been removed now that Horizon properly sends Cache-Control headers [(#652)](https://github.com/stellar/js-stellar-sdk/pull/652). + + +## [v8.2.0](https://github.com/stellar/js-stellar-sdk/compare/v8.1.1...v8.2.0) + +### Add +- Added support for querying the relevant transactions and operations for a claimable balance [(#628)](https://github.com/stellar/js-stellar-sdk/pull/628): + * `TransactionCallBuilder.forClaimableBalance()`: builds a query to `/claimable_balances/:id/transactions/` + * `OperationCallBuilder.forClaimableBalance()`: builds a query to `/claimable_balances/:id/operations/` + +- Added support for new stat fields on the `/assets` endpoint [(#628)](https://github.com/stellar/js-stellar-sdk/pull/628): + * `accounts` - a breakdown of accounts using this asset by authorization type + * `balances` - a breakdown of balances by account authorization type + * `num_claimable_balances` - the number of pending claimable balances + * `claimable_balances_amount` - the total balance of pending claimable balances + +- Added types for all Effects supported as an enum, and moved `Trade`, `Asset`, `Offer`, and `Account` types to separate files [(#635)](https://github.com/stellar/js-stellar-sdk/pull/635). + +### Update +- Upgraded `js-stellar-base` package to version `^5.2.1` from `^5.1.0`, refer to its [release notes](https://github.com/stellar/js-stellar-base/releases/tag/v5.2.0) for more [(#639)](https://github.com/stellar/js-stellar-sdk/pull/639): + * opt-in **support for muxed accounts** ([SEP-23](https://stellar.org/protocol/sep-23)) + * exposing the `AuthClawbackEnabled` flag to Typescript to **complete Protocol 17 support** + * fixing a public key parsing regression + +- Exposed more Protocol 17 (CAP-35) operations [(#633)](https://github.com/stellar/js-stellar-sdk/pull/633): + * The `/accounts` endpoint now resolves the `flags.auth_clawback_enabled` field. + * The operation responses for `clawback`, `clawbackClaimableBalance`, and `setTrustLineFlags` are now defined. + * The operation response for `setOptions` has been updated to show `auth_clawback_enabled`. + +## [v8.1.1](https://github.com/stellar/js-stellar-sdk/compare/v8.1.0...v8.1.1) + +### Fix + +- Upgraded `js-stellar-base` package to version `^5.1.0` from `^5.0.0` to expose the Typescript hints for CAP-35 operations [(#629)](https://github.com/stellar/js-stellar-sdk/pull/629). + + +## [v8.1.0](https://github.com/stellar/js-stellar-sdk/compare/v8.0.0...v8.1.0) + +### Update + +- Upgraded `js-stellar-base` package to version `^5.0.0` from `^4.0.3` to support new CAP-35 operations [(#624)](https://github.com/stellar/js-stellar-sdk/pull/624) + + +## [v8.0.0](https://github.com/stellar/js-stellar-sdk/compare/v7.0.0...v8.0.0) + +### Breaking + +- Updates the SEP-10 utility function parameters to support [SEP-10 v3.1](https://github.com/stellar/stellar-protocol/commit/6c8c9cf6685c85509835188a136ffb8cd6b9c11c) [(#607)](https://github.com/stellar/js-stellar-sdk/pull/607) + - A new required `webAuthDomain` parameter was added to the following functions + - `utils.buildChallengeTx()` + - `utils.readChallengeTx()` + - `utils.verifyChallengeTxThreshold()` + - `utils.verifyChallengeTxSigners()` + - The `webAuthDomain` parameter is expected to match the value of the Manage Data operation with the 'web_auth_domain' key, if present + +### Fix + +- Fixes bug where the first Manage Data operation in a challenge transaction could have a null value [(#591)](https://github.com/stellar/js-stellar-sdk/pull/591) + +### Update + +- Upgraded `axios` package to version `^0.21.1` from `^0.19.0` to fix security vulnerabilities [(#608)](https://github.com/stellar/js-stellar-sdk/pull/608) + +- Upgraded `js-stellar-base` package to version `^4.0.3` from `^4.0.0` to allow accounts with a balance of zero [(#616)](https://github.com/stellar/js-stellar-sdk/pull/616) + +## [v7.0.0](https://github.com/stellar/js-stellar-sdk/compare/v6.2.0...v7.0.0) + +This release includes a major-version increase due to breaking changes included. + +### Breaking + +- Updates the SEP-10 utility function parameters and return values to support [SEP-10 v3.0](https://github.com/stellar/stellar-protocol/commit/9d121f98fd2201a5edfe0ed2befe92f4bf88bfe4) + - The following functions replaced the `homeDomain` parameter with `homeDomains` (note: plural): + - `utils.readChallengeTx()` + - `utils.verifyChallengeTxThreshold()` + - `utils.verifyChallengeTxSigners()` + - `utils.readChallengeTx()` now returns an additional object attribute, `matchedHomeDomain` + +### Update + +- Update challenge transaction helpers for SEP0010 v3.0.0. ([#596](https://github.com/stellar/js-stellar-sdk/pull/596)) + * Restore `homeDomain` validation in `readChallengeTx()`. + +## [v6.2.0](https://github.com/stellar/js-stellar-sdk/compare/v6.1.0...v6.2.0) + +### Update + +- Update challenge transaction helpers for SEP0010 v2.1.0. ([#581](https://github.com/stellar/js-stellar-sdk/issues/581)) + * Remove verification of home domain. + * Allow additional manage data operations that have the source account set as the server key. + +## [v6.1.0](https://github.com/stellar/js-stellar-sdk/compare/v6.0.0...v6.1.0) + +### Update + +- Update claim predicate fields to match Horizon 1.9.1 ([#575](https://github.com/stellar/js-stellar-sdk/pull/575)). + +## [v6.0.0](https://github.com/stellar/js-stellar-sdk/compare/v5.0.4...v6.0.0) + +### Add + +- Add support for claimable balances ([#572](https://github.com/stellar/js-stellar-sdk/pull/572)). +Extend server class to allow loading claimable balances from Horizon. The following functions are available: + +``` +server.claimableBalances(); +server.claimableBalances().claimant(claimant); +server.claimableBalances().sponsor(sponsorID); +server.claimableBalances().asset(asset); +server.claimableBalances().claimableBalance(balanceID); +``` +- Add the following attributes to `AccountResponse` ([#572](https://github.com/stellar/js-stellar-sdk/pull/572)): + * `sponsor?: string` + * `num_sponsoring: number` + * `num_sponsored: number` + +- Add the optional attribute `sponsor` to `AccountSigner`, `BalanceLineAsset`, `ClaimableBalanceRecord`, and `OfferRecord` ([#572](https://github.com/stellar/js-stellar-sdk/pull/572)). + +- Add `sponsor` filtering support for `offers` and `accounts` ([#572](https://github.com/stellar/js-stellar-sdk/pull/572)). + * `server.offers().sponsor(accountID)` + * `server.accounts().sponsor(accountID)` + +- Extend operation responses to support new operations ([#572](https://github.com/stellar/js-stellar-sdk/pull/572)). + * `create_claimable_balance` with the following fields: + * `asset` - asset available to be claimed (in canonical form), + * `amount` - amount available to be claimed, + * `claimants` - list of claimants with predicates (see below): + * `destination` - destination account ID, + * `predicate` - predicate required to claim a balance (see below). + * `claim_claimable_balance` with the following fields: + * `balance_id` - unique ID of balance to be claimed, + * `claimant` - account ID of a claimant. + * `begin_sponsoring_future_reserves` with the following fields: + * `sponsored_id` - account ID for which future reserves will be sponsored. + * `end_sponsoring_future_reserves` with the following fields: + * `begin_sponsor` - account sponsoring reserves. + * `revoke_sponsorship` with the following fields: + * `account_id` - if account sponsorship was revoked, + * `claimable_balance_id` - if claimable balance sponsorship was revoked, + * `data_account_id` - if account data sponsorship was revoked, + * `data_name` - if account data sponsorship was revoked, + * `offer_id` - if offer sponsorship was revoked, + * `trustline_account_id` - if trustline sponsorship was revoked, + * `trustline_asset` - if trustline sponsorship was revoked, + * `signer_account_id` - if signer sponsorship was revoked, + * `signer_key` - if signer sponsorship was revoked. + +- Extend effect responses to support new effects ([#572](https://github.com/stellar/js-stellar-sdk/pull/572)). + * `claimable_balance_created` with the following fields: + * `balance_id` - unique ID of claimable balance, + * `asset` - asset available to be claimed (in canonical form), + * `amount` - amount available to be claimed. + * `claimable_balance_claimant_created` with the following fields: + * `balance_id` - unique ID of a claimable balance, + * `asset` - asset available to be claimed (in canonical form), + * `amount` - amount available to be claimed, + * `predicate` - predicate required to claim a balance (see below). + * `claimable_balance_claimed` with the following fields: + * `balance_id` - unique ID of a claimable balance, + * `asset` - asset available to be claimed (in canonical form), + * `amount` - amount available to be claimed, + * `account_sponsorship_created` with the following fields: + * `sponsor` - sponsor of an account. + * `account_sponsorship_updated` with the following fields: + * `new_sponsor` - new sponsor of an account, + * `former_sponsor` - former sponsor of an account. + * `account_sponsorship_removed` with the following fields: + * `former_sponsor` - former sponsor of an account. + * `trustline_sponsorship_created` with the following fields: + * `sponsor` - sponsor of a trustline. + * `trustline_sponsorship_updated` with the following fields: + * `new_sponsor` - new sponsor of a trustline, + * `former_sponsor` - former sponsor of a trustline. + * `trustline_sponsorship_removed` with the following fields: + * `former_sponsor` - former sponsor of a trustline. + * `claimable_balance_sponsorship_created` with the following fields: + * `sponsor` - sponsor of a claimable balance. + * `claimable_balance_sponsorship_updated` with the following fields: + * `new_sponsor` - new sponsor of a claimable balance, + * `former_sponsor` - former sponsor of a claimable balance. + * `claimable_balance_sponsorship_removed` with the following fields: + * `former_sponsor` - former sponsor of a claimable balance. + * `signer_sponsorship_created` with the following fields: + * `signer` - signer being sponsored. + * `sponsor` - signer sponsor. + * `signer_sponsorship_updated` with the following fields: + * `signer` - signer being sponsored. + * `former_sponsor` - the former sponsor of the signer. + * `new_sponsor` - the new sponsor of the signer. + * `signer_sponsorship_removed` with the following fields: + * `former_sponsor` - former sponsor of a signer. + +### Breaking + +- Update `stellar-base` to `v4.0.0` which introduces a breaking change in the internal XDR library. + +The following functions were renamed: + +- `xdr.OperationBody.setOption()` -> `xdr.OperationBody.setOptions()` +- `xdr.OperationBody.manageDatum()` -> `xdr.OperationBody.manageData()` +- `xdr.OperationType.setOption()` -> `xdr.OperationType.setOptions()` +- `xdr.OperationType.manageDatum()` -> `xdr.OperationType.manageData()` + +The following enum values were renamed in `OperationType`: + +- `setOption` -> `setOptions` +- `manageDatum` -> `manageData` + + +## [v5.0.4](https://github.com/stellar/js-stellar-sdk/compare/v5.0.3...v5.0.4) + +### Update +- Add `tx_set_operation_count` to `ledger` resource ([#559](https://github.com/stellar/js-stellar-sdk/pull/559)). + +## [v5.0.3](https://github.com/stellar/js-stellar-sdk/compare/v5.0.2...v5.0.3) + +### Fix +- Fix regression on `server.offer().forAccount()` which wasn't allowing streaming ([#533](https://github.com/stellar/js-stellar-sdk/pull/553)). + +## [v5.0.2](https://github.com/stellar/js-stellar-sdk/compare/v5.0.1...v5.0.2) + +### Update + +- Allow submitTransaction to receive a FeeBumpTransaction ([#548](https://github.com/stellar/js-stellar-sdk/pull/548)). + +## [v5.0.1](https://github.com/stellar/js-stellar-sdk/compare/v5.0.0...v5.0.1) + +### Update + +- Skip SEP0029 (memo required check) for multiplexed accounts ([#538](https://github.com/stellar/js-stellar-sdk/pull/538)). + +### Fix +- Fix missing documentation for `stellar-base` ([#544](https://github.com/stellar/js-stellar-sdk/pull/544)). +- Move dom-monkeypatch to root types and publish to npm ([#543](https://github.com/stellar/js-stellar-sdk/pull/543)). + +## [v5.0.0](https://github.com/stellar/js-stellar-sdk/compare/v4.1.0...v5.0.0) + +### Add +- Add fee bump related attributes to `TransactionResponse` ([#532](https://github.com/stellar/js-stellar-sdk/pull/532)): + - `fee_account: string`. + - `fee_bump_transaction: FeeBumpTransactionResponse`: + ```js + interface FeeBumpTransactionResponse { + hash: string; + signatures: string[]; + } + ``` + - `inner_transaction: InnerTransactionResponse`: + ```js + interface InnerTransactionResponse { + hash: string; + signatures: string[]; + max_fee: string; + } + ``` +- Add `memo_bytes: string` to `TransactionResponse` ([#532](https://github.com/stellar/js-stellar-sdk/pull/532)). +- Add `authorize_to_maintain_liabilities: boolean` to `AllowTrustOperation` ([#532](https://github.com/stellar/js-stellar-sdk/pull/532)). +- Add `is_authorized_to_maintain_liabilities: boolean` to `BalanceLineNative` ([#532](https://github.com/stellar/js-stellar-sdk/pull/532)). +- Add new result codes to `TransactionFailedResultCodes` ([#531](https://github.com/stellar/js-stellar-sdk/pull/531)). + ```js + TX_FEE_BUMP_INNER_SUCCESS = "tx_fee_bump_inner_success", + TX_FEE_BUMP_INNER_FAILED = "tx_fee_bump_inner_failed", + TX_NOT_SUPPORTED = "tx_not_supported", + TX_SUCCESS = "tx_success", + TX_TOO_EARLY = "tx_too_early", + TX_TOO_LATE = "tx_too_late", + TX_MISSING_OPERATION = "tx_missing_operation", + TX_INSUFFICIENT_BALANCE = "tx_insufficient_balance", + TX_NO_SOURCE_ACCOUNT = "tx_no_source_account", + TX_INSUFFICIENT_FEE = "tx_insufficient_fee", + TX_INTERNAL_ERROR = "tx_internal_error", + ``` + +### Breaking changes +- The attributes `max_fee` and `fee_charged` in `TransactionResponse` can be now a `number` or a `string`. + Update your code to handle both types since Horizon will start sending `string` in version `1.3.0` ([#528](https://github.com/stellar/js-stellar-sdk/pull/528)). +- Bump `stellar-base` to `v3.0.0`: This new version of stellar-base brings support for protocol 13, including multiple breaking changes which might affect your code, please review the list of breaking changes in [stellar-base@3.0.0](https://github.com/stellar/js-stellar-base/releases/tag/v3.0.0) release ([#524](https://github.com/stellar/js-stellar-sdk/pull/524)). +- Make `networkPassphrase` a required argument in `Utils.buildChallengeTx` and `Utils.readChallengeTx` ([#524](https://github.com/stellar/js-stellar-sdk/pull/524)). +- Remove `Server.paths` ([#525](https://github.com/stellar/js-stellar-sdk/pull/525)). + +## [v5.0.0-alpha.2](https://github.com/stellar/js-stellar-sdk/compare/v5.0.0-alpha.1..v5.0.0-alpha.2) + +### Update +- Update `stellar-base` to `v3.0.0-alpha-1`. + +## [v5.0.0-alpha.1](https://github.com/stellar/js-stellar-sdk/compare/v4.1.0...v5.0.0-alpha.1) + +### Breaking changes +- Bump `stellar-base` to `v3.0.0-alpha-0`: This new version of stellar-base brings support for protocol 13, including multiple breaking changes which might affect your code, please review the list of breaking changes in [stellar-base@3.0.0-alpha.0](https://github.com/stellar/js-stellar-base/releases/tag/v3.0.0-alpha.0) release ([#524](https://github.com/stellar/js-stellar-sdk/pull/524)). +- Make `networkPassphrase` a required argument in `Utils.buildChallengeTx` and `Utils.readChallengeTx` ([#524](https://github.com/stellar/js-stellar-sdk/pull/524)). +- Remove `Server.paths` ([#525](https://github.com/stellar/js-stellar-sdk/pull/525)). + +## [v4.1.0](https://github.com/stellar/js-stellar-sdk/compare/v4.0.2...v4.1.0) + +### Add +- Add SEP0029 (memo required) support. ([#516](https://github.com/stellar/js-stellar-sdk/issues/516)) + + Extends `server.submitTransaction` to always run a memo required check before + sending the transaction. If any of the destinations require a memo and the + transaction doesn't include one, then an `AccountRequiresMemoError` will be thrown. + + You can skip this check by passing `{skipMemoRequiredCheck: true}` to `server.submitTransaction`: + + ``` + server.submitTransaction(tx, {skipMemoRequiredCheck: true}) + ``` + + The check runs for each operation of type: + - `payment` + - `pathPaymentStrictReceive` + - `pathPaymentStrictSend` + - `mergeAccount` + + If the transaction includes a memo, then memo required checking is skipped. + + See [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md) for more information about memo required check. + +## [v4.0.2](https://github.com/stellar/js-stellar-sdk/compare/v4.0.1...v4.0.2) + +### Fix +- Fix URI TypeScript reference. ([#509](https://github.com/stellar/js-stellar-sdk/issues/509)) +- Fix docs build. ([#503](https://github.com/stellar/js-stellar-sdk/issues/503)) +- Fix documentation for method to filter offers by account. ([#507](https://github.com/stellar/js-stellar-sdk/issues/507)) +- Fix types and add missing attribute to `account_response`. ([#504](https://github.com/stellar/js-stellar-sdk/issues/504)) + +## [v4.0.1](https://github.com/stellar/js-stellar-sdk/compare/v4.0.0...v4.0.1) + +### Add +- Add `.offer` method to `OfferCallBuilder` which allows fetching a single offer by ID. ([#499](https://github.com/stellar/js-stellar-sdk/issues/499)) + +### Fix +- Fix broken link to Stellar logo+wordmark. ([#496](https://github.com/stellar/js-stellar-sdk/issues/496)) +- Fix `_link` omition for AccountResponse class. ([#495](https://github.com/stellar/js-stellar-sdk/issues/495)) + +### Update +- Update challenge transaction helpers for SEP0010. ([#497](https://github.com/stellar/js-stellar-sdk/issues/497)) + +## [v4.0.0](https://github.com/stellar/js-stellar-sdk/compare/v3.3.0...v4.0.0) + +### Added +- Add support for top-level offers endpoint with `seller`, `selling`, and `buying` filter. ([#485](https://github.com/stellar/js-stellar-sdk/issues/485)) + Horizon 1.0 includes a new `/offers` end-point, which allows you to list all offers, supporting filtering by `seller`, `selling`, or `buying` asset. + + You can fetch data from this endpoint by doing `server.offers()` and use any of the following filters: + + - `seller`: `server.offers().forAccount(accountId)` + - `buying`: `server.offers().buying(asset)` + - `selling`: `server.offers().selling(asset)` + + This introduced a breaking change since it modified the signature for the function `server.offers()`. + + Before, if you wanted to list all the offers for a given account, you'd do: + + ``` + server.offers('accounts', accountID) + ``` + + Starting on this version you'll need to do: + + ``` + server.offers().forAccount(accountId) + ``` + + You can do now things that were not possible before, like finding + all offers for an account filtering by the selling or buying asset + + ``` + server.offers().forAccount(accountId).selling(assetA).buying(assetB) + ``` + +- Add support for filtering accounts by `signer` or `asset` ([#474](https://github.com/stellar/js-stellar-sdk/issues/474)) + Horizon 1.0 includes a new `/accounts` end-point, which allows you to list all accounts who have another account as a signer or hold a given asset. + + You can fetch data from this endpoint by doing `server.accounts()` and use any of the following filters: + + - `accountID`: `server.accounts().accountId(accountId)`, returns a single account. + - `forSigner`: `server.accounts().forSigner(accountId)`, returns accounts where `accountId` is a signer. + - `forAsset`: `server.accounts().forAsset(asset)`, returns accounts which hold the `asset`. + +- Add TypeScript typings for new fields in `fee_stats`. ([#462](https://github.com/stellar/js-stellar-sdk/issues/462)) + + +### Changed +- Changed TypeScript typing for multiple operations "type", it will match the new value on Horizon. ([#477](https://github.com/stellar/js-stellar-sdk/issues/477)) + +### Fixed +- Fix fetchTimebounds() ([#487](https://github.com/stellar/js-stellar-sdk/issues/487)) +- Clone the passed URI in CallBuilder constructor, to not mutate the outside ref ([#473](https://github.com/stellar/js-stellar-sdk/issues/473)) +- Use axios CancelToken to ensure timeout ([#482](https://github.com/stellar/js-stellar-sdk/issues/482)) + +### Breaking +- Remove `fee_paid` field from transaction response. ([#476](https://github.com/stellar/js-stellar-sdk/issues/476)) +- Remove all `*_accepted_fee` from FeeStatsResponse. ([#463](https://github.com/stellar/js-stellar-sdk/issues/463)) +- Change function signature for `server.offers`. ([#485](https://github.com/stellar/js-stellar-sdk/issues/485)) + The signature for the function `server.offers()` was changed to bring suppport for other filters. + + Before, if you wanted to list all the offers for a given account, you'd do: + + ``` + server.offers('accounts', accountID) + ``` + + Starting on this version you'll need to do: + + ``` + server.offers().accountId(accountId) + ``` + + +## [v3.3.0](https://github.com/stellar/js-stellar-sdk/compare/v3.2.0...v3.3.0) + +### Deprecated ⚠️ + +- Horizon 0.25.0 will change the data type for multiple attributes from `Int64` to + `string`. When the JSON payload includes an `Int64`, there are + scenarios where large number data can be incorrectly parsed, since JavaScript doesn't support + `Int64` values. You can read more about it in [#1363](https://github.com/stellar/go/issues/1363). + + This release extends the data types for the following attributes to be of type `string` or `number`: + + - `EffectRecord#offer_id` + - `EffectRecord#new_seq` + - `OfferRecord#id` + - `TradeAggregationRecord#timestamp` + - `TradeAggregationRecord#trade_count` + - `ManageOfferOperationResponse#offer_id` + - `PassiveOfferOperationResponse#offer_id` + + We recommend you update your code to handle both `string` or `number` in + the fields listed above, so that once Horizon 0.25.0 is released, your application + will be able to handle the new type without breaking. + +## [v3.2.0](https://github.com/stellar/js-stellar-sdk/compare/v3.1.2...v3.2.0) + +### Add ➕ + +- Add `fee_charged` an `max_fee` to `TransactionResponse` interface. ([455](https://github.com/stellar/js-stellar-sdk/pull/455)) + +### Deprecated ⚠️ + +- Horizon 0.25 will stop sending the property `fee_paid` in the transaction response. Use `fee_charged` and `max_fee`, read more about it in [450](https://github.com/stellar/js-stellar-sdk/issues/450). + +## [v3.1.2](https://github.com/stellar/js-stellar-sdk/compare/v3.1.1...v3.1.2) + +### Change + +- Upgrade `stellar-base` to `v2.1.2`. ([452](https://github.com/stellar/js-stellar-sdk/pull/452)) + +## [v3.1.1](https://github.com/stellar/js-stellar-sdk/compare/v3.1.0...v3.1.1) + +### Change ⚠️ + +- Change arguments on [server.strictReceivePaths](https://stellar.github.io/js-stellar-sdk/Server.html#strictReceivePaths) since we included `destinationAccount` as an argument, but it is not longer required by Horizon. ([477](https://github.com/stellar/js-stellar-sdk/pull/447)) + +## [v3.1.0](https://github.com/stellar/js-stellar-sdk/compare/v3.0.0...v3.1.0) + +### Add ➕ + +- Add `server.strictReceivePaths` which adds support for `/paths/strict-receive`. ([444](https://github.com/stellar/js-stellar-sdk/pull/444)) + This function takes a list of source assets or a source address, a destination + address, a destination asset and a destination amount. + + You can call it passing a list of source assets: + + ``` + server.strictReceivePaths(sourceAssets,destinationAsset, destinationAmount) + ``` + + Or a by passing a Stellar source account address: + + ``` + server.strictReceivePaths(sourceAccount,destinationAsset, destinationAmount) + ``` + + When you call this function with a Stellar account address, it will look at the account’s trustlines and use them to determine all payment paths that can satisfy the desired amount. + +- Add `server.strictSendPaths` which adds support for `/paths/strict-send`. ([444](https://github.com/stellar/js-stellar-sdk/pull/444)) + This function takes the asset you want to send, and the amount of that asset, + along with either a list of destination assets or a destination address. + + You can call it passing a list of destination assets: + + ``` + server.strictSendPaths(sourceAsset, sourceAmount, [destinationAsset]).call() + ``` + + Or a by passing a Stellar account address: + + ``` + server.strictSendPaths(sourceAsset, sourceAmount, "GDRREYWHQWJDICNH4SAH4TT2JRBYRPTDYIMLK4UWBDT3X3ZVVYT6I4UQ").call() + ``` + + When you call this function with a Stellar account address, it will look at the account’s trustlines and use them to determine all payment paths that can satisfy the desired amount. + +### Deprecated ⚠️ + +- [Server#paths](https://stellar.github.io/js-stellar-sdk/Server.html#paths) is deprecated in favor of [Server#strictReceivePaths](https://stellar.github.io/js-stellar-sdk/Server.html#strictReceivePaths). ([444](https://github.com/stellar/js-stellar-sdk/pull/444)) + +## [v3.0.1](https://github.com/stellar/js-stellar-sdk/compare/v3.0.0...v3.0.1) + +### Add +- Add join method to call builder. ([#436](https://github.com/stellar/js-stellar-sdk/issues/436)) + +## [v3.0.0](https://github.com/stellar/js-stellar-sdk/compare/v2.3.0...v3.0.0) + +### BREAKING CHANGES ⚠ + +- Drop Support for Node 6 since it has been end-of-lifed and no longer in LTS. We now require Node 10 which is the current LTS until April 1st, 2021. ([#424](https://github.com/stellar/js-stellar-sdk/pull/424) + +## [v2.3.0](https://github.com/stellar/js-stellar-sdk/compare/v2.2.3...v2.3.0) + +### Add +- Add feeStats support. ([#409](https://github.com/stellar/js-stellar-sdk/issues/409)) + +### Fix +- Fix Util.verifyChallengeTx documentation ([#405](https://github.com/stellar/js-stellar-sdk/issues/405)) +- Fix: listen to stream events with addEventListener ([#408](https://github.com/stellar/js-stellar-sdk/issues/408)) + +## [v2.2.3](https://github.com/stellar/js-stellar-sdk/compare/v2.2.2...v2.2.3) + +### Fix +- Fix ServerApi's OrderbookRecord type ([#401](https://github.com/stellar/js-stellar-sdk/issues/401)) + +### Set +- Set `name` in custom errors ([#403](https://github.com/stellar/js-stellar-sdk/issues/403)) + +## [v2.2.2](https://github.com/stellar/js-stellar-sdk/compare/v2.2.1...v2.2.2) + +### Fix + +- Fix manage data value in SEP0010 challenge builder. ([#396](https://github.com/stellar/js-stellar-sdk/issues/396)) + +### Add + +- Add support for networkPassphrase in SEP0010 challenge builder. ([#397](https://github.com/stellar/js-stellar-sdk/issues/397)) + +## [v2.2.1](https://github.com/stellar/js-stellar-sdk/compare/v2.2.0...v2.2.1) + +### Fix + +- Fix [#391](https://github.com/stellar/js-stellar-sdk/issues/391): Remove instance check for MessageEvent on stream error. ([#392](https://github.com/stellar/js-stellar-sdk/issues/392)) + + +## [v2.2.0](https://github.com/stellar/js-stellar-sdk/compare/v2.1.1...v2.2.0) + +### Add +- Add helper `Utils.verifyChallengeTx` to verify SEP0010 "Challenge" Transaction. ([#388](https://github.com/stellar/js-stellar-sdk/issues/388)) +- Add helper `Utils.verifyTxSignedBy` to verify that a transaction has been signed by a given account. ([#388](https://github.com/stellar/js-stellar-sdk/pull/388/commits/2cbf36891e529f63867d46bcf321b5bb76acef50)) + +### Fix +- Check for a global EventSource before deciding what to use. This allows you to inject polyfills in other environments like react-native. ([#389](https://github.com/stellar/js-stellar-sdk/issues/389)) + +## [v2.1.1](https://github.com/stellar/js-stellar-sdk/compare/v2.1.0...v2.1.1) + +### Fix +- Fix CallBuilder onmessage type ([#385](https://github.com/stellar/js-stellar-sdk/issues/385)) + +## [v2.1.0](https://github.com/stellar/js-stellar-sdk/compare/v2.0.1...v2.1.0) + +### Add +- Add single script to build docs and call it when combined with jsdoc. ([#380](https://github.com/stellar/js-stellar-sdk/issues/380)) +- Add SEP0010 transaction challenge builder. ([#375](https://github.com/stellar/js-stellar-sdk/issues/375)) +- Add `home_domain` to ServerApi.AccountRecord ([#376](https://github.com/stellar/js-stellar-sdk/issues/376)) + +### Bump +- Bump stellar-base to 1.0.3. ([#378](https://github.com/stellar/js-stellar-sdk/issues/378)) +- Bump @stellar/tslint-config ([#377](https://github.com/stellar/js-stellar-sdk/issues/377)) + +### Fix +- Fix jsdoc's build in after_deploy ([#373](https://github.com/stellar/js-stellar-sdk/issues/373)) +- Create new URI instead of passing serverUrl (Fix [#379](https://github.com/stellar/js-stellar-sdk/issues/379)). ([#382](https://github.com/stellar/js-stellar-sdk/issues/382)) + +## [v2.0.1](https://github.com/stellar/js-stellar-sdk/compare/v1.0.2...v2.0.1) + +- **Breaking change** Port stellar-sdk to Typescript. Because we use a slightly + different build process, there could be some unanticipated bugs. Additionally, + some type definitions have changed: + - Types that were once in the `Server` namespace but didn't actually deal with + the `Server` class have been broken out into a new namespace, `ServerApi`. + So, for example, `Server.AccountRecord` -> `ServerApi.AccountRecord`. + - `Server.AccountResponse` is out of the `Server` namespace -> + `AccountResponse` + - `Server.*CallBuilder` is out of the `Server` namespace -> `*CallBuilder` + - `HorizonResponseAccount` is now `Horizon.AccountResponse` +- Upgrade Webpack to v4. +- Add support for providing app name and version to request headers. +- (NPM wouldn't accept the 2.0.0 version, so we're publishing to 2.0.1.) + +Many thanks to @Ffloriel and @Akuukis for their help with this release! + +## [v1.0.5](https://github.com/stellar/js-stellar-sdk/compare/v1.0.4...v1.0.5) + +- Make CallCollectionFunction return a CollectionPage. +- Update Horizon.AccountSigner[] types. + +## [v1.0.4](https://github.com/stellar/js-stellar-sdk/compare/v1.0.3...v1.0.4) + +- Automatically tag alpha / beta releases as "next" in NPM. + +## [v1.0.3](https://github.com/stellar/js-stellar-sdk/compare/v1.0.2...v1.0.3) + +- Upgrade axios to 0.19.0 to close a security vulnerability. +- Some type fixes. + +## [v1.0.2](https://github.com/stellar/js-stellar-sdk/compare/v1.0.1...v1.0.2) + +- Upgrade stellar-base to v1.0.2 to fix a bug with the browser bundle. + +## [v1.0.1](https://github.com/stellar/js-stellar-sdk/compare/v1.0.0...v1.0.1) + +- Upgrade stellar-base to v1.0.1, which makes available again the deprecated + operation functions `Operation.manageOffer` and `Operation.createPassiveOffer` + (with a warning). +- Fix the documentation around timebounds. + +## [v1.0.0](https://github.com/stellar/js-stellar-sdk/compare/v0.15.4...v1.0.0) + +- Upgrade stellar-base to + [v1.0.0](https://github.com/stellar/js-stellar-base/releases/tag/v1.0.0), + which introduces two breaking changes. +- Switch stellar-sdk's versioning to true semver! 🎉 + +## [v0.15.4](https://github.com/stellar/js-stellar-sdk/compare/v0.15.3...v0.15.4) + +- Add types for LedgerCallBuilder.ledger. +- Add types for Server.operationFeeStats. +- Add types for the HorizonAxiosClient export. +- Move @types/\* from devDependencies to dependencies. +- Pass and use a stream response type to CallBuilders if it's different from the + normal call response. +- Upgrade stellar-base to a version that includes types, and remove + @types/stellar-base as a result. + +## [v0.15.3](https://github.com/stellar/js-stellar-sdk/compare/v0.15.2...v0.15.3) + +- In .travis.yml, try to switch from the encrypted API key to an environment + var. + +## [v0.15.2](https://github.com/stellar/js-stellar-sdk/compare/v0.15.1...v0.15.2) + +- Fix Server.transactions and Server.payments definitions to properly return + collections +- Renew the npm publish key + +## [v0.15.1](https://github.com/stellar/js-stellar-sdk/compare/v0.15.0...v0.15.1) + +- Add Typescript type definitions (imported from DefinitelyTyped). +- Make these changes to those definitions: + - Add definitions for Server.fetchBaseFee and Server.fetchTimebounds + - CallBuilder: No long always returns CollectionPaged results. Interfaces that + extend CallBuilder should specify whether their response is a collection or + not + - CallBuilder: Add inflation_destination and last_modified_ledger property + - OfferRecord: Fix the returned properties + - TradeRecord: Fix the returned properties + - TradesCallBuilder: Add forAccount method + - TransactionCallBuilder: Add includeFailed method + - Horizon.BalanceLineNative/Asset: Add buying_liabilities / + selling_liabilities properties +- Fix documentation links. + +## [v0.15.0](https://github.com/stellar/js-stellar-sdk/compare/v0.14.0...v0.15.0) + +- **Breaking change**: `stellar-sdk` no longer ships with an `EventSource` + polyfill. If you plan to support IE11 / Edge, please use + [`event-source-polyfill`](https://www.npmjs.com/package/event-source-polyfill) + to set `window.EventSource`. +- Upgrade `stellar-base` to a version that doesn't use the `crypto` library, + fixing a bug with Angular 6 +- Add `Server.prototype.fetchTimebounds`, a helper function that helps you set + the `timebounds` property when initting `TransactionBuilder`. It bases the + timebounds on server time rather than local time. + +## [v0.14.0](https://github.com/stellar/js-stellar-sdk/compare/v0.13.0...v0.14.0) + +- Updated some out-of-date dependencies +- Update documentation to explicitly set fees +- Add `Server.prototype.fetchBaseFee`, which devs can use to fetch the current + base fee; we plan to add more functions to help suggest fees in future + releases +- Add `includeFailed` to `OperationCallBuilder` for including failed + transactions in calls +- Add `operationFeeStats` to `Server` for the new fee stats endpoint +- After submitting a transaction with a `manageOffer` operation, return a new + property `offerResults`, which explains what happened to the offer. See + [`Server.prototype.submitTransaction`](https://stellar.github.io/js-stellar-sdk/Server.html#submitTransaction) + for documentation. + +## 0.13.0 + +- Update `stellar-base` to `0.11.0` +- Added ESLint and Prettier to enforce code style +- Upgraded dependencies, including Babel to 6 +- Bump local node version to 6.14.0 + +## 0.12.0 + +- Update `stellar-base` to `0.10.0`: + - **Breaking change** Added + [`TransactionBuilder.setTimeout`](https://stellar.github.io/js-stellar-base/TransactionBuilder.html#setTimeout) + method that sets `timebounds.max_time` on a transaction. Because of the + distributed nature of the Stellar network it is possible that the status of + your transaction will be determined after a long time if the network is + highly congested. If you want to be sure to receive the status of the + transaction within a given period you should set the TimeBounds with + `maxTime` on the transaction (this is what `setTimeout` does internally; if + there's `minTime` set but no `maxTime` it will be added). Call to + `TransactionBuilder.setTimeout` is required if Transaction does not have + `max_time` set. If you don't want to set timeout, use `TimeoutInfinite`. In + general you should set `TimeoutInfinite` only in smart contracts. Please + check + [`TransactionBuilder.setTimeout`](https://stellar.github.io/js-stellar-base/TransactionBuilder.html#setTimeout) + docs for more information. + - Fixed decoding empty `homeDomain`. +- Add `offset` parameter to TradeAggregationCallBuilder to reflect new changes + to the endpoint in horizon-0.15.0 + +## 0.11.0 + +- Update `js-xdr` (by updating `stellar-base`) to support unmarshaling non-utf8 + strings. +- String fields returned by `Operation.fromXDRObject()` are of type `Buffer` now + (except `SetOptions.home_domain` and `ManageData.name` - both required to be + ASCII by stellar-core). + +## 0.10.3 + +- Update `stellar-base` and xdr files. + +## 0.10.2 + +- Update `stellar-base` (and `js-xdr`). + +## 0.10.1 + +- Update `stellar-base` to `0.8.1`. + +## 0.10.0 + +- Update `stellar-base` to `0.8.0` with `bump_sequence` support. + +## 0.9.2 + +- Removed `.babelrc` file from the NPM package. + +## 0.9.1 + +### Breaking changes + +- `stellar-sdk` is now using native `Promise` instead of `bluebird`. The `catch` + function is different. Instead of: + + ```js + .catch(StellarSdk.NotFoundError, function (err) { /* ... */ }) + ``` + + please use the following snippet: + + ```js + .catch(function (err) { + if (err instanceof StellarSdk.NotFoundError) { /* ... */ } + }) + ``` + +- We no longer support IE 11, Firefox < 42, Chrome < 49. + +### Changes + +- Fixed `_ is undefined` bug. +- Browser build is around 130 KB smaller! + +## 0.8.2 + +- Added `timeout` option to `StellarTomlResolver` and `FederationServer` calls + (https://github.com/stellar/js-stellar-sdk/issues/158). +- Fixed adding random value to URLs multiple times + (https://github.com/stellar/js-stellar-sdk/issues/169). +- Fixed jsdoc for classes that extend `CallBuilder`. +- Updated dependencies. +- Added `yarn.lock` file to repository. + +## 0.8.1 + +- Add an allowed trade aggregation resolution of one minute +- Various bug fixes +- Improved documentation + +## 0.8.0 + +- Modify `/trades` endpoint to reflect changes in horizon. +- Add `/trade_aggregations` support. +- Add `/assets` support. + +## 0.7.3 + +- Upgrade `stellar-base`. + +## 0.7.2 + +- Allow hex string in setOptions signers. + +## 0.7.1 + +- Upgrade `stellar-base`. + +## 0.7.0 + +- Support for new signer types: `sha256Hash`, `preAuthTx`. +- `StrKey` helper class with `strkey` encoding related methods. +- Removed deprecated methods: `Keypair.isValidPublicKey` (use `StrKey`), + `Keypair.isValidSecretKey` (use `StrKey`), `Keypair.fromSeed`, `Keypair.seed`, + `Keypair.rawSeed`. +- **Breaking changes**: + - `Network` must be explicitly selected. Previously testnet was a default + network. + - `Operation.setOptions()` method `signer` param changed. + - `Keypair.fromAccountId()` renamed to `Keypair.fromPublicKey()`. + - `Keypair.accountId()` renamed to `Keypair.publicKey()`. + - Dropping support for `End-of-Life` node versions. + +## 0.6.2 + +- Updated `stellar.toml` location + +## 0.6.1 + +- `forUpdate` methods of call builders now accept strings and numbers. +- Create a copy of attribute in a response if there is a link with the same name + (ex. `transaction.ledger`, `transaction._links.ledger`). + +## 0.6.0 + +- **Breaking change** `CallBuilder.stream` now reconnects when no data was + received for a long time. This is to prevent permanent disconnects (more in: + [#76](https://github.com/stellar/js-stellar-sdk/pull/76)). Also, this method + now returns `close` callback instead of `EventSource` object. +- **Breaking change** `Server.loadAccount` now returns the `AccountResponse` + object. +- **Breaking change** Upgraded `stellar-base` to `0.6.0`. `ed25519` package is + now an optional dependency. Check `StellarSdk.FastSigning` variable to check + if `ed25519` package is available. More in README file. +- New `StellarTomlResolver` class that allows getting `stellar.toml` file for a + domain. +- New `Config` class to set global config values. + +## 0.5.1 + +- Fixed XDR decoding issue when using firefox + +## 0.5.0 + +- **Breaking change** `Server` and `FederationServer` constructors no longer + accept object in `serverUrl` parameter. +- **Breaking change** Removed `AccountCallBuilder.address` method. Use + `AccountCallBuilder.accountId` instead. +- **Breaking change** It's no longer possible to connect to insecure server in + `Server` or `FederationServer` unless `allowHttp` flag in `opts` is set. +- Updated dependencies. + +## 0.4.3 + +- Updated dependency (`stellar-base`). + +## 0.4.2 + +- Updated dependencies. +- Added tests. +- Added `CHANGELOG.md` file. + +## 0.4.1 + +- `stellar-base` bump. (c90c68f) + +## 0.4.0 + +- **Breaking change** Bumped `stellar-base` to + [0.5.0](https://github.com/stellar/js-stellar-base/blob/master/CHANGELOG.md#050). + (b810aef) diff --git a/node_modules/@stellar/stellar-sdk/LICENSE b/node_modules/@stellar/stellar-sdk/LICENSE new file mode 100644 index 000000000..7939ac6df --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/LICENSE @@ -0,0 +1,228 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015 Stellar Development Foundation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +---- + +Included code for base58 encoding is licensed under the MIT license: + +Copyright (c) 2011 Google Inc +Copyright (c) 2013 BitPay Inc + +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/node_modules/@stellar/stellar-sdk/README.md b/node_modules/@stellar/stellar-sdk/README.md new file mode 100644 index 000000000..073ca7b65 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/README.md @@ -0,0 +1,317 @@ + +
+ Stellar +
+ Creating equitable access to the global financial system +

js-stellar-sdk

+
+ +

+ npm version + + Weekly Downloads + + Test Status +

+ +js-stellar-sdk is a JavaScript library for communicating with a +[Stellar Horizon server](https://github.com/stellar/go/tree/master/services/horizon) and [Soroban RPC](https://developers.stellar.org/docs/data/rpc). +It is used for building Stellar apps either on Node.js or in the browser, though it can be used in other environments with some tinkering. + +It provides: + +- a networking layer API for Horizon endpoints (REST-based), +- a networking layer for Soroban RPC (JSONRPC-based). +- facilities for building and signing transactions, for communicating with a + Stellar Horizon instance, and for submitting transactions or querying network + history. + +**Jump to:** + + * [Installation](#installation): details on hitting the ground running + * [Usage](#usage): links to documentation and a variety of workarounds for non-traditional JavaScript environments + - [...with React Native](#usage-with-react-native) + - [...with Expo](#usage-with-expo-managed-workflows) + - [...with CloudFlare Workers](#usage-with-cloudflare-workers) + * [Developing](#developing): contribute to the project! + * [Understanding `stellar-sdk` vs. `stellar-base`](#stellar-sdk-vs-stellar-base) + * [License](#license) + +## Installation + +Using npm or yarn to include `stellar-sdk` in your own project: + +```shell +npm install --save @stellar/stellar-sdk +# or +yarn add @stellar/stellar-sdk +``` + +Then, require or import it in your JavaScript code: + +```js +var StellarSdk = require('@stellar/stellar-sdk'); +// or +import * as StellarSdk from '@stellar/stellar-sdk'; +``` + +(Preferably, you would only import the pieces you need to enable tree-shaking and lower your final bundle sizes.) + +### Browsers + +You can use a CDN: + +```html + +``` + +Note that this method relies on using a third party to host the JS library. This may not be entirely secure. You can self-host it via [Bower](http://bower.io): + +```shell +bower install @stellar/stellar-sdk +``` + +and include it in the browser: + +```html + + +``` + +If you don't want to use or install Bower, you can copy the packaged JS files from the [Bower repo](https://github.com/stellar/bower-js-stellar-sdk), or just build the package yourself locally (see [Developing :arrow_right: Building](#building)) and copy the bundle. + +| Always make sure that you are using the latest version number. They can be found on the [releases page](https://github.com/stellar/js-stellar-sdk/releases) in GitHub. | +|----| + +### Custom Installation + +You can configure whether or not to build the browser bundle with the axios dependency. In order to turn off the axios dependency, set the USE_AXIOS environment variable to false. You can also turn off the eventsource dependency by setting USE_EVENTSOURCE to false. + +#### Build without Axios +``` +npm run build:browser:no-axios +``` +This will create `stellar-sdk-no-axios.js` in `dist/`. + +#### Build without EventSource +``` +npm run build:browser:no-eventsource +``` +This will create `stellar-sdk-no-eventsource.js` in `dist/`. + +#### Build without Axios and Eventsource +``` +npm run build:browser:minimal +``` +This will create `stellar-sdk-minimal.js` in `dist/`. + +## Usage + +The usage documentation for this library lives in a handful of places: + + * across the [Stellar Developer Docs](https://developers.stellar.org), which includes tutorials and examples, + * within [this repository itself](https://github.com/stellar/js-stellar-sdk/blob/master/docs/reference/readme.md), and + * on the generated [API doc site](https://stellar.github.io/js-stellar-sdk/). + +You can also refer to: + + * the [documentation](https://developers.stellar.org/docs/data/horizon) for the Horizon REST API (if using the `Horizon` module) and + * the [documentation](https://developers.stellar.org/docs/data/rpc) for Soroban RPC's API (if using the `rpc` module) + +### Usage with React-Native + +1. Install `yarn add --dev rn-nodeify` +2. Add the following postinstall script: +``` +yarn rn-nodeify --install url,events,https,http,util,stream,crypto,vm,buffer --hack --yarn +``` +3. Uncomment `require('crypto')` on shim.js +4. `react-native link react-native-randombytes` +5. Create file `rn-cli.config.js` +``` +module.exports = { + resolver: { + extraNodeModules: require("node-libs-react-native"), + }, +}; +``` +6. Add `import "./shim";` to the top of `index.js` +7. `yarn add @stellar/stellar-sdk` + +There is also a [sample](https://github.com/fnando/rn-stellar-sdk-sample) that you can follow. + +**Note**: Only the V8 compiler (on Android) and JSC (on iOS) have proper support for `Buffer` and `Uint8Array` as is needed by this library. Otherwise, you may see bizarre errors when doing XDR encoding/decoding such as `source not specified`. + +#### Usage with Expo managed workflows + +1. Install `yarn add --dev rn-nodeify` +2. Add the following postinstall script: +``` +yarn rn-nodeify --install process,url,events,https,http,util,stream,crypto,vm,buffer --hack --yarn +``` +3. Add `import "./shim";` to your app's entry point (by default `./App.js`) +4. `yarn add @stellar/stellar-sdk` +5. `expo install expo-random` + +At this point, the Stellar SDK will work, except that `StellarSdk.Keypair.random()` will throw an error. To work around this, you can create your own method to generate a random keypair like this: + +```javascript +import * as Random from 'expo-random'; +import { Keypair } from '@stellar/stellar-sdk'; + +const generateRandomKeypair = () => { + const randomBytes = Random.getRandomBytes(32); + return Keypair.fromRawEd25519Seed(Buffer.from(randomBytes)); +}; +``` + +#### Usage with CloudFlare Workers + +Both `eventsource` (needed for streaming) and `axios` (needed for making HTTP requests) are problematic dependencies in the CFW environment. The experimental branch [`make-eventsource-optional`](https://github.com/stellar/js-stellar-sdk/pull/901) is an attempt to resolve these issues. + +It requires the following additional tweaks to your project: + * the `axios-fetch-adapter` lets you use `axios` with `fetch` as a backend, which is available to CF workers + * it only works with `axios@"<= 1.0.0"` versions, so we need to force an override into the underlying dependency + * and this can be problematic with newer `yarn` versions, so we need to force the environment to use Yarn 1 + +In summary, the `package.json` tweaks look something like this: + +```jsonc +"dependencies": { + // ... + "@stellar/stellar-sdk": "git+https://github.com/stellar/js-stellar-sdk#make-eventsource-optional", + "@vespaiach/axios-fetch-adapter": "^0.3.1", + "axios": "^0.26.1" +}, +"overrides": { + "@stellar/stellar-sdk": { + "axios": "$axios" + } +}, +"packageManager": "yarn@1.22.19" +``` + +Then, you need to override the adapter in your codebase: + +```typescript +import { Horizon } from '@stellar/stellar-sdk'; +import fetchAdapter from '@vespaiach/axios-fetch-adapter'; + +Horizon.AxiosClient.defaults.adapter = fetchAdapter as any; + +// then, the rest of your code... +``` + +All HTTP calls will use `fetch`, now, meaning it should work in the CloudFlare Worker environment. + +## Developing + +So you want to contribute to the library: welcome! Whether you're working on a fork or want to make an upstream request, the dev-test loop is pretty straightforward. + +1. Clone the repo: + +```shell +git clone https://github.com/stellar/js-stellar-sdk.git +``` + +2. Install dependencies inside js-stellar-sdk folder: + +```shell +cd js-stellar-sdk +yarn +``` + +3. Install Node 18 + +Because we support the oldest maintenance version of Node, please install and develop on Node 18 so you don't get surprised when your code works locally but breaks in CI. + +Here's how to install `nvm` if you haven't: https://github.com/creationix/nvm + +```shell +nvm install 18 + +# if you've never installed 18 before you'll want to re-install yarn +npm install -g yarn +``` + +If you work on several projects that use different Node versions, you might it helpful to install this automatic version manager: https://github.com/wbyoung/avn + +4. Observe the project's code style + +While you're making changes, make sure to run the linter to catch any linting +errors (in addition to making sure your text editor supports ESLint) and conform to the project's code style. + +```shell +yarn fmt +``` + +### Building +You can build the developer version (unoptimized, commented, with source maps, etc.) or the production bundles: + +```shell +yarn build +# or +yarn build:prod +``` + +### Testing + +To run all tests: + +```shell +yarn test +``` + +To run a specific set of tests: + +```shell +yarn test:node +yarn test:browser +yarn test:integration +``` + +In order to have a faster test loop, these suite-specific commands **do not** build the bundles first (unlike `yarn test`). If you make code changes, you will need to run `yarn build` (or a subset like `yarn build:node` corresponding to the test suite) before running the tests again to see your changes. + +To generate and check the documentation site: + +```shell +# install the `serve` command if you don't have it already +npm i -g serve + +# clone the base library for complete docs +git clone https://github.com/stellar/js-stellar-base + +# generate the docs files +yarn docs + +# get these files working in a browser +cd jsdoc && serve . + +# you'll be able to browse the docs at http://localhost:5000 +``` + +### Publishing + +For information on how to contribute or publish new versions of this software to `npm`, please refer to our [contribution guide](https://github.com/stellar/js-stellar-sdk/blob/master/CONTRIBUTING.md). + +## Miscellaneous + +### `stellar-sdk` vs `stellar-base` + +`stellar-sdk` is a high-level library that serves as client-side API for Horizon and Soroban RPC, while [`stellar-base](https://github.com/stellar/js-stellar-base) is lower-level library for creating Stellar primitive constructs via XDR helpers and wrappers. + +**Most people will want stellar-sdk instead of stellar-base.** You should only use stellar-base if you know what you're doing! + +If you add `stellar-sdk` to a project, **do not add `stellar-base`!** Mismatching versions could cause weird, hard-to-find bugs. `stellar-sdk` automatically installs `stellar-base` and exposes all of its exports in case you need them. + +> **Important!** The Node.js version of the `stellar-base` (`stellar-sdk` dependency) package uses the [`sodium-native`](https://www.npmjs.com/package/sodium-native) package as an [optional dependency](https://docs.npmjs.com/files/package.json#optionaldependencies). `sodium-native` is a low level binding to [libsodium](https://github.com/jedisct1/libsodium), (an implementation of [Ed25519](https://ed25519.cr.yp.to/) signatures). +> If installation of `sodium-native` fails, or it is unavailable, `stellar-base` (and `stellar-sdk`) will fallback to using the [`tweetnacl`](https://www.npmjs.com/package/tweetnacl) package implementation. If you are using them in a browser, you can ignore this. However, for production backend deployments, you should be using `sodium-native`. +> If `sodium-native` is successfully installed and working the `StellarSdk.FastSigning` variable will return `true`. + +### License + +js-stellar-sdk is licensed under an Apache-2.0 license. See the +[LICENSE](https://github.com/stellar/js-stellar-sdk/blob/master/LICENSE) file +for details. diff --git a/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-minimal.js b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-minimal.js new file mode 100644 index 000000000..fac89a4a3 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-minimal.js @@ -0,0 +1,46650 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define("StellarSdk", [], factory); + else if(typeof exports === 'object') + exports["StellarSdk"] = factory(); + else + root["StellarSdk"] = factory(); +})(self, () => { +return /******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 3740: +/***/ (function(module) { + +/*! For license information please see xdr.js.LICENSE.txt */ +!function(t,e){ true?module.exports=e():0}(this,(()=>(()=>{var t={616:(t,e,r)=>{"use strict";r.d(e,{A:()=>i});var n=r(287);n.hp.alloc(1).subarray(0,1)instanceof n.hp||(n.hp.prototype.subarray=function(t,e){const r=Uint8Array.prototype.subarray.call(this,t,e);return Object.setPrototypeOf(r,n.hp.prototype),r});const i=n.hp},281:(t,e,r)=>{const n=r(164);t.exports=n},164:(t,e,r)=>{"use strict";r.r(e),r.d(e,{Array:()=>F,Bool:()=>S,Double:()=>L,Enum:()=>q,Float:()=>O,Hyper:()=>U,Int:()=>v,LargeInt:()=>x,Opaque:()=>D,Option:()=>X,Quadruple:()=>N,Reference:()=>G,String:()=>M,Struct:()=>Y,Union:()=>W,UnsignedHyper:()=>T,UnsignedInt:()=>R,VarArray:()=>P,VarOpaque:()=>z,Void:()=>k,XdrReader:()=>f,XdrWriter:()=>c,config:()=>it});class n extends TypeError{constructor(t){super(`XDR Write Error: ${t}`)}}class i extends TypeError{constructor(t){super(`XDR Read Error: ${t}`)}}class o extends TypeError{constructor(t){super(`XDR Type Definition Error: ${t}`)}}class s extends o{constructor(){super("method not implemented, it should be overloaded in the descendant class.")}}var u=r(616).A;class f{constructor(t){if(!u.isBuffer(t)){if(!(t instanceof Array||Array.isArray(t)||ArrayBuffer.isView(t)))throw new i(`source invalid: ${t}`);t=u.from(t)}this._buffer=t,this._length=t.length,this._index=0}_buffer;_length;_index;get eof(){return this._index===this._length}advance(t){const e=this._index;if(this._index+=t,this._length0){for(let t=0;t0){const t=this.alloc(r);this._buffer.fill(0,t,this._index)}}writeInt32BE(t){const e=this.alloc(4);this._buffer.writeInt32BE(t,e)}writeUInt32BE(t){const e=this.alloc(4);this._buffer.writeUInt32BE(t,e)}writeBigInt64BE(t){const e=this.alloc(8);this._buffer.writeBigInt64BE(t,e)}writeBigUInt64BE(t){const e=this.alloc(8);this._buffer.writeBigUInt64BE(t,e)}writeFloatBE(t){const e=this.alloc(4);this._buffer.writeFloatBE(t,e)}writeDoubleBE(t){const e=this.alloc(8);this._buffer.writeDoubleBE(t,e)}static bufferChunkSize=h}var l=r(616).A;class p{toXDR(t="raw"){if(!this.write)return this.constructor.toXDR(this,t);const e=new c;return this.write(this,e),w(e.finalize(),t)}fromXDR(t,e="raw"){if(!this.read)return this.constructor.fromXDR(t,e);const r=new f(m(t,e)),n=this.read(r);return r.ensureInputConsumed(),n}validateXDR(t,e="raw"){try{return this.fromXDR(t,e),!0}catch(t){return!1}}static toXDR(t,e="raw"){const r=new c;return this.write(t,r),w(r.finalize(),e)}static fromXDR(t,e="raw"){const r=new f(m(t,e)),n=this.read(r);return r.ensureInputConsumed(),n}static validateXDR(t,e="raw"){try{return this.fromXDR(t,e),!0}catch(t){return!1}}}class d extends p{static read(t){throw new s}static write(t,e){throw new s}static isValid(t){return!1}}class g extends p{isValid(t){return!1}}class y extends TypeError{constructor(t){super(`Invalid format ${t}, must be one of "raw", "hex", "base64"`)}}function w(t,e){switch(e){case"raw":return t;case"hex":return t.toString("hex");case"base64":return t.toString("base64");default:throw new y(e)}}function m(t,e){switch(e){case"raw":return t;case"hex":return l.from(t,"hex");case"base64":return l.from(t,"base64");default:throw new y(e)}}function b(t,e){return null!=t&&(t instanceof e||_(t,e)&&"function"==typeof t.constructor.read&&"function"==typeof t.constructor.write&&_(t,"XdrType"))}function _(t,e){do{if(t.constructor.name===e)return!0}while(t=Object.getPrototypeOf(t));return!1}const B=2147483647,E=-2147483648;class v extends d{static read(t){return t.readInt32BE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");if((0|t)!==t)throw new n("invalid i32 value");e.writeInt32BE(t)}static isValid(t){return"number"==typeof t&&(0|t)===t&&(t>=E&&t<=B)}}function A(t,e,r){if("bigint"!=typeof t)throw new TypeError("Expected bigint 'value', got "+typeof t);const n=e/r;if(1===n)return[t];if(r<32||r>128||2!==n&&4!==n&&8!==n)throw new TypeError(`invalid bigint (${t}) and slice size (${e} -> ${r}) combination`);const i=BigInt(r),o=new Array(n);for(let e=0;e>=i;return o}function I(t,e){if(e)return[0n,(1n<=o&&i<=s)return i;throw new TypeError(`bigint values [${t}] for ${function(t,e){return`${e?"u":"i"}${t}`}(e,r)} out of range [${o}, ${s}]: ${i}`)}(t,this.size,this.unsigned)}get unsigned(){throw new s}get size(){throw new s}slice(t){return A(this._value,this.size,t)}toString(){return this._value.toString()}toJSON(){return{_value:this._value.toString()}}toBigInt(){return BigInt(this._value)}static read(t){const{size:e}=this.prototype;return 64===e?new this(t.readBigUInt64BE()):new this(...Array.from({length:e/64},(()=>t.readBigUInt64BE())).reverse())}static write(t,e){if(t instanceof this)t=t._value;else if("bigint"!=typeof t||t>this.MAX_VALUE||t>32n)|0}get size(){return 64}get unsigned(){return!1}static fromBits(t,e){return new this(t,e)}}U.defineIntBoundaries();const $=4294967295;class R extends d{static read(t){return t.readUInt32BE()}static write(t,e){if("number"!=typeof t||!(t>=0&&t<=$)||t%1!=0)throw new n("invalid u32 value");e.writeUInt32BE(t)}static isValid(t){return"number"==typeof t&&t%1==0&&(t>=0&&t<=$)}}R.MAX_VALUE=$,R.MIN_VALUE=0;class T extends x{constructor(...t){super(t)}get low(){return Number(0xffffffffn&this._value)|0}get high(){return Number(this._value>>32n)|0}get size(){return 64}get unsigned(){return!0}static fromBits(t,e){return new this(t,e)}}T.defineIntBoundaries();class O extends d{static read(t){return t.readFloatBE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");e.writeFloatBE(t)}static isValid(t){return"number"==typeof t}}class L extends d{static read(t){return t.readDoubleBE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");e.writeDoubleBE(t)}static isValid(t){return"number"==typeof t}}class N extends d{static read(){throw new o("quadruple not supported")}static write(){throw new o("quadruple not supported")}static isValid(){return!1}}class S extends d{static read(t){const e=v.read(t);switch(e){case 0:return!1;case 1:return!0;default:throw new i(`got ${e} when trying to read a bool`)}}static write(t,e){const r=t?1:0;v.write(r,e)}static isValid(t){return"boolean"==typeof t}}var V=r(616).A;class M extends g{constructor(t=R.MAX_VALUE){super(),this._maxLength=t}read(t){const e=R.read(t);if(e>this._maxLength)throw new i(`saw ${e} length String, max allowed is ${this._maxLength}`);return t.read(e)}readString(t){return this.read(t).toString("utf8")}write(t,e){const r="string"==typeof t?V.byteLength(t,"utf8"):t.length;if(r>this._maxLength)throw new n(`got ${t.length} bytes, max allowed is ${this._maxLength}`);R.write(r,e),e.write(t,r)}isValid(t){return"string"==typeof t?V.byteLength(t,"utf8")<=this._maxLength:!!(t instanceof Array||V.isBuffer(t))&&t.length<=this._maxLength}}var C=r(616).A;class D extends g{constructor(t){super(),this._length=t}read(t){return t.read(this._length)}write(t,e){const{length:r}=t;if(r!==this._length)throw new n(`got ${t.length} bytes, expected ${this._length}`);e.write(t,r)}isValid(t){return C.isBuffer(t)&&t.length===this._length}}var j=r(616).A;class z extends g{constructor(t=R.MAX_VALUE){super(),this._maxLength=t}read(t){const e=R.read(t);if(e>this._maxLength)throw new i(`saw ${e} length VarOpaque, max allowed is ${this._maxLength}`);return t.read(e)}write(t,e){const{length:r}=t;if(t.length>this._maxLength)throw new n(`got ${t.length} bytes, max allowed is ${this._maxLength}`);R.write(r,e),e.write(t,r)}isValid(t){return j.isBuffer(t)&&t.length<=this._maxLength}}class F extends g{constructor(t,e){super(),this._childType=t,this._length=e}read(t){const e=new r.g.Array(this._length);for(let r=0;rthis._maxLength)throw new i(`saw ${e} length VarArray, max allowed is ${this._maxLength}`);const r=new Array(e);for(let n=0;nthis._maxLength)throw new n(`got array of size ${t.length}, max allowed is ${this._maxLength}`);R.write(t.length,e);for(const r of t)this._childType.write(r,e)}isValid(t){if(!(t instanceof Array)||t.length>this._maxLength)return!1;for(const e of t)if(!this._childType.isValid(e))return!1;return!0}}class X extends d{constructor(t){super(),this._childType=t}read(t){if(S.read(t))return this._childType.read(t)}write(t,e){const r=null!=t;S.write(r,e),r&&this._childType.write(t,e)}isValid(t){return null==t||this._childType.isValid(t)}}class k extends d{static read(){}static write(t){if(void 0!==t)throw new n("trying to write value to a void slot")}static isValid(t){return void 0===t}}class q extends d{constructor(t,e){super(),this.name=t,this.value=e}static read(t){const e=v.read(t),r=this._byValue[e];if(void 0===r)throw new i(`unknown ${this.enumName} member for value ${e}`);return r}static write(t,e){if(!this.isValid(t))throw new n(`${t} has enum name ${t?.enumName}, not ${this.enumName}: ${JSON.stringify(t)}`);v.write(t.value,e)}static isValid(t){return t?.constructor?.enumName===this.enumName||b(t,this)}static members(){return this._members}static values(){return Object.values(this._members)}static fromName(t){const e=this._members[t];if(!e)throw new TypeError(`${t} is not a member of ${this.enumName}`);return e}static fromValue(t){const e=this._byValue[t];if(void 0===e)throw new TypeError(`${t} is not a value of any member of ${this.enumName}`);return e}static create(t,e,r){const n=class extends q{};n.enumName=e,t.results[e]=n,n._members={},n._byValue={};for(const[t,e]of Object.entries(r)){const r=new n(t,e);n._members[t]=r,n._byValue[e]=r,n[t]=()=>r}return n}}class G extends d{resolve(){throw new o('"resolve" method should be implemented in the descendant class')}}class Y extends g{constructor(t){super(),this._attributes=t||{}}static read(t){const e={};for(const[r,n]of this._fields)e[r]=n.read(t);return new this(e)}static write(t,e){if(!this.isValid(t))throw new n(`${t} has struct name ${t?.constructor?.structName}, not ${this.structName}: ${JSON.stringify(t)}`);for(const[r,n]of this._fields){const i=t._attributes[r];n.write(i,e)}}static isValid(t){return t?.constructor?.structName===this.structName||b(t,this)}static create(t,e,r){const n=class extends Y{};n.structName=e,t.results[e]=n;const i=new Array(r.length);for(let e=0;e{"use strict";e.byteLength=function(t){var e=u(t),r=e[0],n=e[1];return 3*(r+n)/4-n},e.toByteArray=function(t){var e,r,o=u(t),s=o[0],f=o[1],a=new i(function(t,e,r){return 3*(e+r)/4-r}(0,s,f)),h=0,c=f>0?s-4:s;for(r=0;r>16&255,a[h++]=e>>8&255,a[h++]=255&e;2===f&&(e=n[t.charCodeAt(r)]<<2|n[t.charCodeAt(r+1)]>>4,a[h++]=255&e);1===f&&(e=n[t.charCodeAt(r)]<<10|n[t.charCodeAt(r+1)]<<4|n[t.charCodeAt(r+2)]>>2,a[h++]=e>>8&255,a[h++]=255&e);return a},e.fromByteArray=function(t){for(var e,n=t.length,i=n%3,o=[],s=16383,u=0,a=n-i;ua?a:u+s));1===i?(e=t[n-1],o.push(r[e>>2]+r[e<<4&63]+"==")):2===i&&(e=(t[n-2]<<8)+t[n-1],o.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"="));return o.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)r[s]=o[s],n[o.charCodeAt(s)]=s;function u(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function f(t,e,n){for(var i,o,s=[],u=e;u>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return s.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287:(t,e,r)=>{"use strict";const n=r(526),i=r(251),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.hp=f,e.IS=50;const s=2147483647;function u(t){if(t>s)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,f.prototype),e}function f(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return c(t)}return a(t,e,r)}function a(t,e,r){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!f.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|g(t,e);let n=u(r);const i=n.write(t,e);i!==r&&(n=n.slice(0,i));return n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(W(t,Uint8Array)){const e=new Uint8Array(t);return p(e.buffer,e.byteOffset,e.byteLength)}return l(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(W(t,ArrayBuffer)||t&&W(t.buffer,ArrayBuffer))return p(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(W(t,SharedArrayBuffer)||t&&W(t.buffer,SharedArrayBuffer)))return p(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return f.from(n,e,r);const i=function(t){if(f.isBuffer(t)){const e=0|d(t.length),r=u(e);return 0===r.length||t.copy(r,0,0,e),r}if(void 0!==t.length)return"number"!=typeof t.length||H(t.length)?u(0):l(t);if("Buffer"===t.type&&Array.isArray(t.data))return l(t.data)}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return f.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function h(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function c(t){return h(t),u(t<0?0:0|d(t))}function l(t){const e=t.length<0?0:0|d(t.length),r=u(e);for(let n=0;n=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|t}function g(t,e){if(f.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||W(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return G(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Y(t).length;default:if(i)return n?-1:G(t).length;e=(""+e).toLowerCase(),i=!0}}function y(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return x(this,e,r);case"ascii":return $(this,e,r);case"latin1":case"binary":return R(this,e,r);case"base64":return I(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function w(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function m(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),H(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=f.from(e,n)),f.isBuffer(e))return 0===e.length?-1:b(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):b(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(t,e,r,n,i){let o,s=1,u=t.length,f=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,f/=2,r/=2}function a(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){let n=-1;for(o=r;ou&&(r=u-f),o=r;o>=0;o--){let r=!0;for(let n=0;ni&&(n=i):n=i;const o=e.length;let s;for(n>o/2&&(n=o/2),s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function I(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function x(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+s<=r){let r,n,u,f;switch(s){case 1:e<128&&(o=e);break;case 2:r=t[i+1],128==(192&r)&&(f=(31&e)<<6|63&r,f>127&&(o=f));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(f=(15&e)<<12|(63&r)<<6|63&n,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:r=t[i+1],n=t[i+2],u=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&u)&&(f=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&u,f>65535&&f<1114112&&(o=f))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return function(t){const e=t.length;if(e<=U)return String.fromCharCode.apply(String,t);let r="",n=0;for(;nn.length?(f.isBuffer(e)||(e=f.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!f.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},f.byteLength=g,f.prototype._isBuffer=!0,f.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;er&&(t+=" ... "),""},o&&(f.prototype[o]=f.prototype.inspect),f.prototype.compare=function(t,e,r,n,i){if(W(t,Uint8Array)&&(t=f.from(t,t.offset,t.byteLength)),!f.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0);const u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r);for(let t=0;t>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return _(this,t,e,r);case"utf8":case"utf-8":return B(this,t,e,r);case"ascii":case"latin1":case"binary":return E(this,t,e,r);case"base64":return v(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},f.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const U=4096;function $(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;in)&&(r=n);let i="";for(let n=e;nr)throw new RangeError("Trying to access beyond buffer length")}function N(t,e,r,n,i,o){if(!f.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function S(t,e,r,n,i){P(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,r}function V(t,e,r,n,i){P(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r+7]=o,o>>=8,t[r+6]=o,o>>=8,t[r+5]=o,o>>=8,t[r+4]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=s,s>>=8,t[r+2]=s,s>>=8,t[r+1]=s,s>>=8,t[r]=s,r+8}function M(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function C(t,e,r,n,o){return e=+e,r>>>=0,o||M(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function D(t,e,r,n,o){return e=+e,r>>>=0,o||M(t,0,r,8),i.write(t,e,r,n,52,8),r+8}f.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t],i=1,o=0;for(;++o>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},f.prototype.readUint8=f.prototype.readUInt8=function(t,e){return t>>>=0,e||L(t,1,this.length),this[t]},f.prototype.readUint16LE=f.prototype.readUInt16LE=function(t,e){return t>>>=0,e||L(t,2,this.length),this[t]|this[t+1]<<8},f.prototype.readUint16BE=f.prototype.readUInt16BE=function(t,e){return t>>>=0,e||L(t,2,this.length),this[t]<<8|this[t+1]},f.prototype.readUint32LE=f.prototype.readUInt32LE=function(t,e){return t>>>=0,e||L(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},f.prototype.readUint32BE=f.prototype.readUInt32BE=function(t,e){return t>>>=0,e||L(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},f.prototype.readBigUInt64LE=Z((function(t){X(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t],i=1,o=0;for(;++o=i&&(n-=Math.pow(2,8*e)),n},f.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||L(t,e,this.length);let n=e,i=1,o=this[t+--n];for(;n>0&&(i*=256);)o+=this[t+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*e)),o},f.prototype.readInt8=function(t,e){return t>>>=0,e||L(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},f.prototype.readInt16LE=function(t,e){t>>>=0,e||L(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},f.prototype.readInt16BE=function(t,e){t>>>=0,e||L(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},f.prototype.readInt32LE=function(t,e){return t>>>=0,e||L(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},f.prototype.readInt32BE=function(t,e){return t>>>=0,e||L(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},f.prototype.readBigInt64LE=Z((function(t){X(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<>>=0,e||L(t,4,this.length),i.read(this,t,!0,23,4)},f.prototype.readFloatBE=function(t,e){return t>>>=0,e||L(t,4,this.length),i.read(this,t,!1,23,4)},f.prototype.readDoubleLE=function(t,e){return t>>>=0,e||L(t,8,this.length),i.read(this,t,!0,52,8)},f.prototype.readDoubleBE=function(t,e){return t>>>=0,e||L(t,8,this.length),i.read(this,t,!1,52,8)},f.prototype.writeUintLE=f.prototype.writeUIntLE=function(t,e,r,n){if(t=+t,e>>>=0,r>>>=0,!n){N(this,t,e,r,Math.pow(2,8*r)-1,0)}let i=1,o=0;for(this[e]=255&t;++o>>=0,r>>>=0,!n){N(this,t,e,r,Math.pow(2,8*r)-1,0)}let i=r-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+r},f.prototype.writeUint8=f.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,1,255,0),this[e]=255&t,e+1},f.prototype.writeUint16LE=f.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},f.prototype.writeUint16BE=f.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},f.prototype.writeUint32LE=f.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},f.prototype.writeUint32BE=f.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},f.prototype.writeBigUInt64LE=Z((function(t,e=0){return S(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),f.prototype.writeBigUInt64BE=Z((function(t,e=0){return V(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),f.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);N(this,t,e,r,n-1,-n)}let i=0,o=1,s=0;for(this[e]=255&t;++i>>=0,!n){const n=Math.pow(2,8*r-1);N(this,t,e,r,n-1,-n)}let i=r-1,o=1,s=0;for(this[e+i]=255&t;--i>=0&&(o*=256);)t<0&&0===s&&0!==this[e+i+1]&&(s=1),this[e+i]=(t/o|0)-s&255;return e+r},f.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},f.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},f.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},f.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},f.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},f.prototype.writeBigInt64LE=Z((function(t,e=0){return S(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),f.prototype.writeBigInt64BE=Z((function(t,e=0){return V(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),f.prototype.writeFloatLE=function(t,e,r){return C(this,t,e,!0,r)},f.prototype.writeFloatBE=function(t,e,r){return C(this,t,e,!1,r)},f.prototype.writeDoubleLE=function(t,e,r){return D(this,t,e,!0,r)},f.prototype.writeDoubleBE=function(t,e,r){return D(this,t,e,!1,r)},f.prototype.copy=function(t,e,r,n){if(!f.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function P(t,e,r,n,i,o){if(t>r||t3?0===e||e===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`:`>= ${e}${n} and <= ${r}${n}`,new j.ERR_OUT_OF_RANGE("value",i,t)}!function(t,e,r){X(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||k(e,t.length-(r+1))}(n,i,o)}function X(t,e){if("number"!=typeof t)throw new j.ERR_INVALID_ARG_TYPE(e,"number",t)}function k(t,e,r){if(Math.floor(t)!==t)throw X(t,r),new j.ERR_OUT_OF_RANGE(r||"offset","an integer",t);if(e<0)throw new j.ERR_BUFFER_OUT_OF_BOUNDS;throw new j.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}z("ERR_BUFFER_OUT_OF_BOUNDS",(function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),z("ERR_INVALID_ARG_TYPE",(function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`}),TypeError),z("ERR_OUT_OF_RANGE",(function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=F(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=F(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n}),RangeError);const q=/[^+/0-9A-Za-z-_]/g;function G(t,e){let r;e=e||1/0;const n=t.length;let i=null;const o=[];for(let s=0;s55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function Y(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(q,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function J(t,e,r,n){let i;for(i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function W(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function H(t){return t!=t}const Q=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function Z(t){return"undefined"==typeof BigInt?K:t}function K(){throw new Error("BigInt not supported")}},251:(t,e)=>{e.read=function(t,e,r,n,i){var o,s,u=8*i-n-1,f=(1<>1,h=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-h)-1,p>>=-h,h+=u;h>0;o=256*o+t[e+c],c+=l,h-=8);for(s=o&(1<<-h)-1,o>>=-h,h+=n;h>0;s=256*s+t[e+c],c+=l,h-=8);if(0===o)o=1-a;else{if(o===f)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=a}return(p?-1:1)*s*Math.pow(2,o-n)},e.write=function(t,e,r,n,i,o){var s,u,f,a=8*o-i-1,h=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=h):(s=Math.floor(Math.log(e)/Math.LN2),e*(f=Math.pow(2,-s))<1&&(s--,f*=2),(e+=s+c>=1?l/f:l*Math.pow(2,1-c))*f>=2&&(s++,f/=2),s+c>=h?(u=0,s=h):s+c>=1?(u=(e*f-1)*Math.pow(2,i),s+=c):(u=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,a-=8);t[r+p-d]|=128*g}}},e={};function r(n){var i=e[n];if(void 0!==i)return i.exports;var o=e[n]={exports:{}};return t[n](o,o.exports,r),o.exports}return r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r(281)})())); +//# sourceMappingURL=xdr.js.map + +/***/ }), + +/***/ 2135: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Account = void 0; +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Account object. + * + * `Account` represents a single account in the Stellar network and its sequence + * number. Account tracks the sequence number as it is used by {@link + * TransactionBuilder}. See + * [Accounts](https://developers.stellar.org/docs/glossary/accounts/) for + * more information about how accounts work in Stellar. + * + * @constructor + * + * @param {string} accountId - ID of the account (ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`). If you + * provide a muxed account address, this will throw; use {@link + * MuxedAccount} instead. + * @param {string} sequence - current sequence number of the account + */ +var Account = exports.Account = /*#__PURE__*/function () { + function Account(accountId, sequence) { + _classCallCheck(this, Account); + if (_strkey.StrKey.isValidMed25519PublicKey(accountId)) { + throw new Error('accountId is an M-address; use MuxedAccount instead'); + } + if (!_strkey.StrKey.isValidEd25519PublicKey(accountId)) { + throw new Error('accountId is invalid'); + } + if (!(typeof sequence === 'string')) { + throw new Error('sequence must be of type string'); + } + this._accountId = accountId; + this.sequence = new _bignumber["default"](sequence); + } + + /** + * Returns Stellar account ID, ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`. + * @returns {string} + */ + return _createClass(Account, [{ + key: "accountId", + value: function accountId() { + return this._accountId; + } + + /** + * @returns {string} sequence number for the account as a string + */ + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this.sequence.toString(); + } + + /** + * Increments sequence number in this object by one. + * @returns {void} + */ + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + this.sequence = this.sequence.plus(1); + } + }]); +}(); + +/***/ }), + +/***/ 1180: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Address = void 0; +var _strkey = __webpack_require__(7120); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Address object. + * + * `Address` represents a single address in the Stellar network. An address can + * represent an account or a contract. + * + * @constructor + * + * @param {string} address - ID of the account (ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`). If you + * provide a muxed account address, this will throw; use {@link + * MuxedAccount} instead. + */ +var Address = exports.Address = /*#__PURE__*/function () { + function Address(address) { + _classCallCheck(this, Address); + if (_strkey.StrKey.isValidEd25519PublicKey(address)) { + this._type = 'account'; + this._key = _strkey.StrKey.decodeEd25519PublicKey(address); + } else if (_strkey.StrKey.isValidContract(address)) { + this._type = 'contract'; + this._key = _strkey.StrKey.decodeContract(address); + } else { + throw new Error("Unsupported address type: ".concat(address)); + } + } + + /** + * Parses a string and returns an Address object. + * + * @param {string} address - The address to parse. ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA` + * @returns {Address} + */ + return _createClass(Address, [{ + key: "toString", + value: + /** + * Serialize an address to string. + * + * @returns {string} + */ + function toString() { + switch (this._type) { + case 'account': + return _strkey.StrKey.encodeEd25519PublicKey(this._key); + case 'contract': + return _strkey.StrKey.encodeContract(this._key); + default: + throw new Error('Unsupported address type'); + } + } + + /** + * Convert this Address to an xdr.ScVal type. + * + * @returns {xdr.ScVal} + */ + }, { + key: "toScVal", + value: function toScVal() { + return _xdr["default"].ScVal.scvAddress(this.toScAddress()); + } + + /** + * Convert this Address to an xdr.ScAddress type. + * + * @returns {xdr.ScAddress} + */ + }, { + key: "toScAddress", + value: function toScAddress() { + switch (this._type) { + case 'account': + return _xdr["default"].ScAddress.scAddressTypeAccount(_xdr["default"].PublicKey.publicKeyTypeEd25519(this._key)); + case 'contract': + return _xdr["default"].ScAddress.scAddressTypeContract(this._key); + default: + throw new Error('Unsupported address type'); + } + } + + /** + * Return the raw public key bytes for this address. + * + * @returns {Buffer} + */ + }, { + key: "toBuffer", + value: function toBuffer() { + return this._key; + } + }], [{ + key: "fromString", + value: function fromString(address) { + return new Address(address); + } + + /** + * Creates a new account Address object from a buffer of raw bytes. + * + * @param {Buffer} buffer - The bytes of an address to parse. + * @returns {Address} + */ + }, { + key: "account", + value: function account(buffer) { + return new Address(_strkey.StrKey.encodeEd25519PublicKey(buffer)); + } + + /** + * Creates a new contract Address object from a buffer of raw bytes. + * + * @param {Buffer} buffer - The bytes of an address to parse. + * @returns {Address} + */ + }, { + key: "contract", + value: function contract(buffer) { + return new Address(_strkey.StrKey.encodeContract(buffer)); + } + + /** + * Convert this from an xdr.ScVal type + * + * @param {xdr.ScVal} scVal - The xdr.ScVal type to parse + * @returns {Address} + */ + }, { + key: "fromScVal", + value: function fromScVal(scVal) { + return Address.fromScAddress(scVal.address()); + } + + /** + * Convert this from an xdr.ScAddress type + * + * @param {xdr.ScAddress} scAddress - The xdr.ScAddress type to parse + * @returns {Address} + */ + }, { + key: "fromScAddress", + value: function fromScAddress(scAddress) { + switch (scAddress["switch"]()) { + case _xdr["default"].ScAddressType.scAddressTypeAccount(): + return Address.account(scAddress.accountId().ed25519()); + case _xdr["default"].ScAddressType.scAddressTypeContract(): + return Address.contract(scAddress.contractId()); + default: + throw new Error('Unsupported address type'); + } + } + }]); +}(); + +/***/ }), + +/***/ 1764: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Asset = void 0; +var _util = __webpack_require__(645); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +var _hashing = __webpack_require__(9152); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Asset class represents an asset, either the native asset (`XLM`) + * or an asset code / issuer account ID pair. + * + * An asset code describes an asset code and issuer pair. In the case of the native + * asset XLM, the issuer will be null. + * + * @constructor + * @param {string} code - The asset code. + * @param {string} issuer - The account ID of the issuer. + */ +var Asset = exports.Asset = /*#__PURE__*/function () { + function Asset(code, issuer) { + _classCallCheck(this, Asset); + if (!/^[a-zA-Z0-9]{1,12}$/.test(code)) { + throw new Error('Asset code is invalid (maximum alphanumeric, 12 characters at max)'); + } + if (String(code).toLowerCase() !== 'xlm' && !issuer) { + throw new Error('Issuer cannot be null'); + } + if (issuer && !_strkey.StrKey.isValidEd25519PublicKey(issuer)) { + throw new Error('Issuer is invalid'); + } + if (String(code).toLowerCase() === 'xlm') { + // transform all xLM, Xlm, etc. variants -> XLM + this.code = 'XLM'; + } else { + this.code = code; + } + this.issuer = issuer; + } + + /** + * Returns an asset object for the native asset. + * @Return {Asset} + */ + return _createClass(Asset, [{ + key: "toXDRObject", + value: + /** + * Returns the xdr.Asset object for this asset. + * @returns {xdr.Asset} XDR asset object + */ + function toXDRObject() { + return this._toXDRObject(_xdr["default"].Asset); + } + + /** + * Returns the xdr.ChangeTrustAsset object for this asset. + * @returns {xdr.ChangeTrustAsset} XDR asset object + */ + }, { + key: "toChangeTrustXDRObject", + value: function toChangeTrustXDRObject() { + return this._toXDRObject(_xdr["default"].ChangeTrustAsset); + } + + /** + * Returns the xdr.TrustLineAsset object for this asset. + * @returns {xdr.TrustLineAsset} XDR asset object + */ + }, { + key: "toTrustLineXDRObject", + value: function toTrustLineXDRObject() { + return this._toXDRObject(_xdr["default"].TrustLineAsset); + } + + /** + * Returns the would-be contract ID (`C...` format) for this asset on a given + * network. + * + * @param {string} networkPassphrase indicates which network the contract + * ID should refer to, since every network will have a unique ID for the + * same contract (see {@link Networks} for options) + * + * @returns {string} the strkey-encoded (`C...`) contract ID for this asset + * + * @warning This makes no guarantee that this contract actually *exists*. + */ + }, { + key: "contractId", + value: function contractId(networkPassphrase) { + var networkId = (0, _hashing.hash)(Buffer.from(networkPassphrase)); + var preimage = _xdr["default"].HashIdPreimage.envelopeTypeContractId(new _xdr["default"].HashIdPreimageContractId({ + networkId: networkId, + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAsset(this.toXDRObject()) + })); + return _strkey.StrKey.encodeContract((0, _hashing.hash)(preimage.toXDR())); + } + + /** + * Returns the xdr object for this asset. + * @param {xdr.Asset | xdr.ChangeTrustAsset} xdrAsset - The asset xdr object. + * @returns {xdr.Asset | xdr.ChangeTrustAsset | xdr.TrustLineAsset} XDR Asset object + */ + }, { + key: "_toXDRObject", + value: function _toXDRObject() { + var xdrAsset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _xdr["default"].Asset; + if (this.isNative()) { + return xdrAsset.assetTypeNative(); + } + var xdrType; + var xdrTypeString; + if (this.code.length <= 4) { + xdrType = _xdr["default"].AlphaNum4; + xdrTypeString = 'assetTypeCreditAlphanum4'; + } else { + xdrType = _xdr["default"].AlphaNum12; + xdrTypeString = 'assetTypeCreditAlphanum12'; + } + + // pad code with null bytes if necessary + var padLength = this.code.length <= 4 ? 4 : 12; + var paddedCode = this.code.padEnd(padLength, '\0'); + + // eslint-disable-next-line new-cap + var assetType = new xdrType({ + assetCode: paddedCode, + issuer: _keypair.Keypair.fromPublicKey(this.issuer).xdrAccountId() + }); + return new xdrAsset(xdrTypeString, assetType); + } + + /** + * @returns {string} Asset code + */ + }, { + key: "getCode", + value: function getCode() { + if (this.code === undefined) { + return undefined; + } + return String(this.code); + } + + /** + * @returns {string} Asset issuer + */ + }, { + key: "getIssuer", + value: function getIssuer() { + if (this.issuer === undefined) { + return undefined; + } + return String(this.issuer); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {string} Asset type. Can be one of following types: + * + * - `native`, + * - `credit_alphanum4`, + * - `credit_alphanum12`, or + * - `unknown` as the error case (which should never occur) + */ + }, { + key: "getAssetType", + value: function getAssetType() { + switch (this.getRawAssetType().value) { + case _xdr["default"].AssetType.assetTypeNative().value: + return 'native'; + case _xdr["default"].AssetType.assetTypeCreditAlphanum4().value: + return 'credit_alphanum4'; + case _xdr["default"].AssetType.assetTypeCreditAlphanum12().value: + return 'credit_alphanum12'; + default: + return 'unknown'; + } + } + + /** + * @returns {xdr.AssetType} the raw XDR representation of the asset type + */ + }, { + key: "getRawAssetType", + value: function getRawAssetType() { + if (this.isNative()) { + return _xdr["default"].AssetType.assetTypeNative(); + } + if (this.code.length <= 4) { + return _xdr["default"].AssetType.assetTypeCreditAlphanum4(); + } + return _xdr["default"].AssetType.assetTypeCreditAlphanum12(); + } + + /** + * @returns {boolean} true if this asset object is the native asset. + */ + }, { + key: "isNative", + value: function isNative() { + return !this.issuer; + } + + /** + * @param {Asset} asset Asset to compare + * @returns {boolean} true if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(asset) { + return this.code === asset.getCode() && this.issuer === asset.getIssuer(); + } + }, { + key: "toString", + value: function toString() { + if (this.isNative()) { + return 'native'; + } + return "".concat(this.getCode(), ":").concat(this.getIssuer()); + } + + /** + * Compares two assets according to the criteria: + * + * 1. First compare the type (native < alphanum4 < alphanum12). + * 2. If the types are equal, compare the assets codes. + * 3. If the asset codes are equal, compare the issuers. + * + * @param {Asset} assetA - the first asset + * @param {Asset} assetB - the second asset + * @returns {number} `-1` if assetA < assetB, `0` if assetA == assetB, `1` if assetA > assetB. + * + * @static + * @memberof Asset + */ + }], [{ + key: "native", + value: function _native() { + return new Asset('XLM'); + } + + /** + * Returns an asset object from its XDR object representation. + * @param {xdr.Asset} assetXdr - The asset xdr object. + * @returns {Asset} + */ + }, { + key: "fromOperation", + value: function fromOperation(assetXdr) { + var anum; + var code; + var issuer; + switch (assetXdr["switch"]()) { + case _xdr["default"].AssetType.assetTypeNative(): + return this["native"](); + case _xdr["default"].AssetType.assetTypeCreditAlphanum4(): + anum = assetXdr.alphaNum4(); + /* falls through */ + case _xdr["default"].AssetType.assetTypeCreditAlphanum12(): + anum = anum || assetXdr.alphaNum12(); + issuer = _strkey.StrKey.encodeEd25519PublicKey(anum.issuer().ed25519()); + code = (0, _util.trimEnd)(anum.assetCode(), '\0'); + return new this(code, issuer); + default: + throw new Error("Invalid asset type: ".concat(assetXdr["switch"]().name)); + } + } + }, { + key: "compare", + value: function compare(assetA, assetB) { + if (!assetA || !(assetA instanceof Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof Asset)) { + throw new Error('assetB is invalid'); + } + if (assetA.equals(assetB)) { + return 0; + } + + // Compare asset types. + var xdrAtype = assetA.getRawAssetType().value; + var xdrBtype = assetB.getRawAssetType().value; + if (xdrAtype !== xdrBtype) { + return xdrAtype < xdrBtype ? -1 : 1; + } + + // Compare asset codes. + var result = asciiCompare(assetA.getCode(), assetB.getCode()); + if (result !== 0) { + return result; + } + + // Compare asset issuers. + return asciiCompare(assetA.getIssuer(), assetB.getIssuer()); + } + }]); +}(); +/** + * Compares two ASCII strings in lexographic order with uppercase precedence. + * + * @param {string} a - the first string to compare + * @param {string} b - the second + * @returns {number} like all `compare()`s: + * -1 if `a < b`, 0 if `a == b`, and 1 if `a > b` + * + * @warning No type-checks are done on the parameters + */ +function asciiCompare(a, b) { + return Buffer.compare(Buffer.from(a, 'ascii'), Buffer.from(b, 'ascii')); +} + +/***/ }), + +/***/ 5328: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.authorizeEntry = authorizeEntry; +exports.authorizeInvocation = authorizeInvocation; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +var _network = __webpack_require__(6202); +var _hashing = __webpack_require__(9152); +var _address = __webpack_require__(1180); +var _scval = __webpack_require__(7177); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +/** + * @async + * @callback SigningCallback A callback for signing an XDR structure + * representing all of the details necessary to authorize an invocation tree. + * + * @param {xdr.HashIdPreimage} preimage the entire authorization envelope + * whose hash you should sign, so that you can inspect the entire structure + * if necessary (rather than blindly signing a hash) + * + * @returns {Promise} the signature of the raw payload (which is + * the sha256 hash of the preimage bytes, so `hash(preimage.toXDR())`) signed + * by the key corresponding to the public key in the entry you pass to + * {@link authorizeEntry} (decipherable from its + * `credentials().address().address()`) + */ +/** + * Actually authorizes an existing authorization entry using the given the + * credentials and expiration details, returning a signed copy. + * + * This "fills out" the authorization entry with a signature, indicating to the + * {@link Operation.invokeHostFunction} its attached to that: + * - a particular identity (i.e. signing {@link Keypair} or other signer) + * - approving the execution of an invocation tree (i.e. a simulation-acquired + * {@link xdr.SorobanAuthorizedInvocation} or otherwise built) + * - on a particular network (uniquely identified by its passphrase, see + * {@link Networks}) + * - until a particular ledger sequence is reached. + * + * This one lets you pass a either a {@link Keypair} (or, more accurately, + * anything with a `sign(Buffer): Buffer` method) or a callback function (see + * {@link SigningCallback}) to handle signing the envelope hash. + * + * @param {xdr.SorobanAuthorizationEntry} entry an unsigned authorization entr + * @param {Keypair | SigningCallback} signer either a {@link Keypair} instance + * or a function which takes a payload (a + * {@link xdr.HashIdPreimageSorobanAuthorization} instance) input and returns + * the signature of the hash of the raw payload bytes (where the signing key + * should correspond to the address in the `entry`) + * @param {number} validUntilLedgerSeq the (exclusive) future ledger sequence + * number until which this authorization entry should be valid (if + * `currentLedgerSeq==validUntil`, this is expired)) + * @param {string} [networkPassphrase] the network passphrase is incorprated + * into the signature (see {@link Networks} for options) + * + * @returns {Promise} a promise for an + * authorization entry that you can pass along to + * {@link Operation.invokeHostFunction} + * + * @note If using the `SigningCallback` variation, the signer is assumed to be + * the entry's credential address. If you need a different key to sign the + * entry, you will need to use different method (e.g., fork this code). + * + * @see authorizeInvocation + * @example + * import { + * SorobanRpc, + * Transaction, + * Networks, + * authorizeEntry + * } from '@stellar/stellar-sdk'; + * + * // Assume signPayloadCallback is a well-formed signing callback. + * // + * // It might, for example, pop up a modal from a browser extension, send the + * // transaction to a third-party service for signing, or just do simple + * // signing via Keypair like it does here: + * function signPayloadCallback(payload) { + * return signer.sign(hash(payload.toXDR()); + * } + * + * function multiPartyAuth( + * server: SorobanRpc.Server, + * // assume this involves multi-party auth + * tx: Transaction, + * ) { + * return server + * .simulateTransaction(tx) + * .then((simResult) => { + * tx.operations[0].auth.map(entry => + * authorizeEntry( + * entry, + * signPayloadCallback, + * currentLedger + 1000, + * Networks.TESTNET); + * )); + * + * return server.prepareTransaction(tx, simResult); + * }) + * .then((preppedTx) => { + * preppedTx.sign(source); + * return server.sendTransaction(preppedTx); + * }); + * } + */ +function authorizeEntry(_x, _x2, _x3) { + return _authorizeEntry.apply(this, arguments); +} +/** + * This builds an entry from scratch, allowing you to express authorization as a + * function of: + * - a particular identity (i.e. signing {@link Keypair} or other signer) + * - approving the execution of an invocation tree (i.e. a simulation-acquired + * {@link xdr.SorobanAuthorizedInvocation} or otherwise built) + * - on a particular network (uniquely identified by its passphrase, see + * {@link Networks}) + * - until a particular ledger sequence is reached. + * + * This is in contrast to {@link authorizeEntry}, which signs an existing entry. + * + * @param {Keypair | SigningCallback} signer either a {@link Keypair} instance + * (or anything with a `.sign(buf): Buffer-like` method) or a function which + * takes a payload (a {@link xdr.HashIdPreimageSorobanAuthorization} + * instance) input and returns the signature of the hash of the raw payload + * bytes (where the signing key should correspond to the address in the + * `entry`) + * @param {number} validUntilLedgerSeq the (exclusive) future ledger sequence + * number until which this authorization entry should be valid (if + * `currentLedgerSeq==validUntilLedgerSeq`, this is expired)) + * @param {xdr.SorobanAuthorizedInvocation} invocation the invocation tree that + * we're authorizing (likely, this comes from transaction simulation) + * @param {string} [publicKey] the public identity of the signer (when + * providing a {@link Keypair} to `signer`, this can be omitted, as it just + * uses {@link Keypair.publicKey}) + * @param {string} [networkPassphrase] the network passphrase is incorprated + * into the signature (see {@link Networks} for options, default: + * {@link Networks.FUTURENET}) + * + * @returns {Promise} a promise for an + * authorization entry that you can pass along to + * {@link Operation.invokeHostFunction} + * + * @see authorizeEntry + */ +function _authorizeEntry() { + _authorizeEntry = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(entry, signer, validUntilLedgerSeq) { + var networkPassphrase, + clone, + addrAuth, + networkId, + preimage, + payload, + signature, + publicKey, + sigScVal, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + networkPassphrase = _args.length > 3 && _args[3] !== undefined ? _args[3] : _network.Networks.FUTURENET; + if (!(entry.credentials()["switch"]().value !== _xdr["default"].SorobanCredentialsType.sorobanCredentialsAddress().value)) { + _context.next = 3; + break; + } + return _context.abrupt("return", entry); + case 3: + clone = _xdr["default"].SorobanAuthorizationEntry.fromXDR(entry.toXDR()); + /** @type {xdr.SorobanAddressCredentials} */ + addrAuth = clone.credentials().address(); + addrAuth.signatureExpirationLedger(validUntilLedgerSeq); + networkId = (0, _hashing.hash)(Buffer.from(networkPassphrase)); + preimage = _xdr["default"].HashIdPreimage.envelopeTypeSorobanAuthorization(new _xdr["default"].HashIdPreimageSorobanAuthorization({ + networkId: networkId, + nonce: addrAuth.nonce(), + invocation: clone.rootInvocation(), + signatureExpirationLedger: addrAuth.signatureExpirationLedger() + })); + payload = (0, _hashing.hash)(preimage.toXDR()); + if (!(typeof signer === 'function')) { + _context.next = 18; + break; + } + _context.t0 = Buffer; + _context.next = 13; + return signer(preimage); + case 13: + _context.t1 = _context.sent; + signature = _context.t0.from.call(_context.t0, _context.t1); + publicKey = _address.Address.fromScAddress(addrAuth.address()).toString(); + _context.next = 20; + break; + case 18: + signature = Buffer.from(signer.sign(payload)); + publicKey = signer.publicKey(); + case 20: + if (_keypair.Keypair.fromPublicKey(publicKey).verify(payload, signature)) { + _context.next = 22; + break; + } + throw new Error("signature doesn't match payload"); + case 22: + // This structure is defined here: + // https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#stellar-account-signatures + // + // Encoding a contract structure as an ScVal means the map keys are supposed + // to be symbols, hence the forced typing here. + sigScVal = (0, _scval.nativeToScVal)({ + public_key: _strkey.StrKey.decodeEd25519PublicKey(publicKey), + signature: signature + }, { + type: { + public_key: ['symbol', null], + signature: ['symbol', null] + } + }); + addrAuth.signature(_xdr["default"].ScVal.scvVec([sigScVal])); + return _context.abrupt("return", clone); + case 25: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _authorizeEntry.apply(this, arguments); +} +function authorizeInvocation(signer, validUntilLedgerSeq, invocation) { + var publicKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; + var networkPassphrase = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : _network.Networks.FUTURENET; + // We use keypairs as a source of randomness for the nonce to avoid mucking + // with any crypto dependencies. Note that this just has to be random and + // unique, not cryptographically secure, so it's fine. + var kp = _keypair.Keypair.random().rawPublicKey(); + var nonce = new _xdr["default"].Int64(bytesToInt64(kp)); + var pk = publicKey || signer.publicKey(); + if (!pk) { + throw new Error("authorizeInvocation requires publicKey parameter"); + } + var entry = new _xdr["default"].SorobanAuthorizationEntry({ + rootInvocation: invocation, + credentials: _xdr["default"].SorobanCredentials.sorobanCredentialsAddress(new _xdr["default"].SorobanAddressCredentials({ + address: new _address.Address(pk).toScAddress(), + nonce: nonce, + signatureExpirationLedger: 0, + // replaced + signature: _xdr["default"].ScVal.scvVec([]) // replaced + })) + }); + return authorizeEntry(entry, signer, validUntilLedgerSeq, networkPassphrase); +} +function bytesToInt64(bytes) { + // eslint-disable-next-line no-bitwise + return bytes.subarray(0, 8).reduce(function (accum, b) { + return accum << 8 | b; + }, 0); +} + +/***/ }), + +/***/ 1387: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Claimant = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Claimant class represents an xdr.Claimant + * + * The claim predicate is optional, it defaults to unconditional if none is specified. + * + * @constructor + * @param {string} destination - The destination account ID. + * @param {xdr.ClaimPredicate} [predicate] - The claim predicate. + */ +var Claimant = exports.Claimant = /*#__PURE__*/function () { + function Claimant(destination, predicate) { + _classCallCheck(this, Claimant); + if (destination && !_strkey.StrKey.isValidEd25519PublicKey(destination)) { + throw new Error('Destination is invalid'); + } + this._destination = destination; + if (!predicate) { + this._predicate = _xdr["default"].ClaimPredicate.claimPredicateUnconditional(); + } else if (predicate instanceof _xdr["default"].ClaimPredicate) { + this._predicate = predicate; + } else { + throw new Error('Predicate should be an xdr.ClaimPredicate'); + } + } + + /** + * Returns an unconditional claim predicate + * @Return {xdr.ClaimPredicate} + */ + return _createClass(Claimant, [{ + key: "toXDRObject", + value: + /** + * Returns the xdr object for this claimant. + * @returns {xdr.Claimant} XDR Claimant object + */ + function toXDRObject() { + var claimant = new _xdr["default"].ClaimantV0({ + destination: _keypair.Keypair.fromPublicKey(this._destination).xdrAccountId(), + predicate: this._predicate + }); + return _xdr["default"].Claimant.claimantTypeV0(claimant); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "destination", + get: function get() { + return this._destination; + }, + set: function set(value) { + throw new Error('Claimant is immutable'); + } + + /** + * @type {xdr.ClaimPredicate} + * @readonly + */ + }, { + key: "predicate", + get: function get() { + return this._predicate; + }, + set: function set(value) { + throw new Error('Claimant is immutable'); + } + }], [{ + key: "predicateUnconditional", + value: function predicateUnconditional() { + return _xdr["default"].ClaimPredicate.claimPredicateUnconditional(); + } + + /** + * Returns an `and` claim predicate + * @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate + * @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateAnd", + value: function predicateAnd(left, right) { + if (!(left instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('left Predicate should be an xdr.ClaimPredicate'); + } + if (!(right instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateAnd([left, right]); + } + + /** + * Returns an `or` claim predicate + * @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate + * @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateOr", + value: function predicateOr(left, right) { + if (!(left instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('left Predicate should be an xdr.ClaimPredicate'); + } + if (!(right instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateOr([left, right]); + } + + /** + * Returns a `not` claim predicate + * @param {xdr.ClaimPredicate} predicate an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateNot", + value: function predicateNot(predicate) { + if (!(predicate instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateNot(predicate); + } + + /** + * Returns a `BeforeAbsoluteTime` claim predicate + * + * This predicate will be fulfilled if the closing time of the ledger that + * includes the CreateClaimableBalance operation is less than this (absolute) + * Unix timestamp (expressed in seconds). + * + * @param {string} absBefore Unix epoch (in seconds) as a string + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateBeforeAbsoluteTime", + value: function predicateBeforeAbsoluteTime(absBefore) { + return _xdr["default"].ClaimPredicate.claimPredicateBeforeAbsoluteTime(_xdr["default"].Int64.fromString(absBefore)); + } + + /** + * Returns a `BeforeRelativeTime` claim predicate + * + * This predicate will be fulfilled if the closing time of the ledger that + * includes the CreateClaimableBalance operation plus this relative time delta + * (in seconds) is less than the current time. + * + * @param {strings} seconds seconds since closeTime of the ledger in which the ClaimableBalanceEntry was created (as string) + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateBeforeRelativeTime", + value: function predicateBeforeRelativeTime(seconds) { + return _xdr["default"].ClaimPredicate.claimPredicateBeforeRelativeTime(_xdr["default"].Int64.fromString(seconds)); + } + + /** + * Returns a claimant object from its XDR object representation. + * @param {xdr.Claimant} claimantXdr - The claimant xdr object. + * @returns {Claimant} + */ + }, { + key: "fromXDR", + value: function fromXDR(claimantXdr) { + var value; + switch (claimantXdr["switch"]()) { + case _xdr["default"].ClaimantType.claimantTypeV0(): + value = claimantXdr.v0(); + return new this(_strkey.StrKey.encodeEd25519PublicKey(value.destination().ed25519()), value.predicate()); + default: + throw new Error("Invalid claimant type: ".concat(claimantXdr["switch"]().name)); + } + } + }]); +}(); + +/***/ }), + +/***/ 7452: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Contract = void 0; +var _address = __webpack_require__(1180); +var _operation = __webpack_require__(7237); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Contract object. + * + * `Contract` represents a single contract in the Stellar network, embodying the + * interface of the contract. See + * [Contracts](https://soroban.stellar.org/docs/learn/interacting-with-contracts) + * for more information about how contracts work in Stellar. + * + * @constructor + * + * @param {string} contractId - ID of the contract (ex. + * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`). + */ +var Contract = exports.Contract = /*#__PURE__*/function () { + function Contract(contractId) { + _classCallCheck(this, Contract); + try { + // First, try it as a strkey + this._id = _strkey.StrKey.decodeContract(contractId); + } catch (_) { + throw new Error("Invalid contract ID: ".concat(contractId)); + } + } + + /** + * Returns Stellar contract ID as a strkey, ex. + * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`. + * @returns {string} + */ + return _createClass(Contract, [{ + key: "contractId", + value: function contractId() { + return _strkey.StrKey.encodeContract(this._id); + } + + /** @returns {string} the ID as a strkey (C...) */ + }, { + key: "toString", + value: function toString() { + return this.contractId(); + } + + /** @returns {Address} the wrapped address of this contract */ + }, { + key: "address", + value: function address() { + return _address.Address.contract(this._id); + } + + /** + * Returns an operation that will invoke this contract call. + * + * @param {string} method name of the method to call + * @param {...xdr.ScVal} params arguments to pass to the function call + * + * @returns {xdr.Operation} an InvokeHostFunctionOp operation to call the + * contract with the given method and parameters + * + * @see Operation.invokeHostFunction + * @see Operation.invokeContractFunction + * @see Operation.createCustomContract + * @see Operation.createStellarAssetContract + * @see Operation.uploadContractWasm + */ + }, { + key: "call", + value: function call(method) { + for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + params[_key - 1] = arguments[_key]; + } + return _operation.Operation.invokeContractFunction({ + contract: this.address().toString(), + "function": method, + args: params + }); + } + + /** + * Returns the read-only footprint entries necessary for any invocations to + * this contract, for convenience when manually adding it to your + * transaction's overall footprint or doing bump/restore operations. + * + * @returns {xdr.LedgerKey} the ledger key for the deployed contract instance + */ + }, { + key: "getFootprint", + value: function getFootprint() { + return _xdr["default"].LedgerKey.contractData(new _xdr["default"].LedgerKeyContractData({ + contract: this.address().toScAddress(), + key: _xdr["default"].ScVal.scvLedgerKeyContractInstance(), + durability: _xdr["default"].ContractDataDurability.persistent() + })); + } + }]); +}(); + +/***/ }), + +/***/ 3919: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.humanizeEvents = humanizeEvents; +var _strkey = __webpack_require__(7120); +var _scval = __webpack_require__(7177); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Converts raw diagnostic or contract events into something with a flatter, + * human-readable, and understandable structure. + * + * @param {xdr.DiagnosticEvent[] | xdr.ContractEvent[]} events either contract + * events or diagnostic events to parse into a friendly format + * + * @returns {SorobanEvent[]} a list of human-readable event structures, where + * each element has the following properties: + * - type: a string of one of 'system', 'contract', 'diagnostic + * - contractId?: optionally, a `C...` encoded strkey + * - topics: a list of {@link scValToNative} invocations on the topics + * - data: similarly, a {@link scValToNative} invocation on the raw event data + */ +function humanizeEvents(events) { + return events.map(function (e) { + // A pseudo-instanceof check for xdr.DiagnosticEvent more reliable + // in mixed SDK environments: + if (e.inSuccessfulContractCall) { + return extractEvent(e.event()); + } + return extractEvent(e); + }); +} +function extractEvent(event) { + return _objectSpread(_objectSpread({}, typeof event.contractId === 'function' && event.contractId() != null && { + contractId: _strkey.StrKey.encodeContract(event.contractId()) + }), {}, { + type: event.type().name, + topics: event.body().value().topics().map(function (t) { + return (0, _scval.scValToNative)(t); + }), + data: (0, _scval.scValToNative)(event.body().value().data()) + }); +} + +/***/ }), + +/***/ 9260: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.FeeBumpTransaction = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _hashing = __webpack_require__(9152); +var _transaction = __webpack_require__(380); +var _transaction_base = __webpack_require__(3758); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Use {@link TransactionBuilder.buildFeeBumpTransaction} to build a + * FeeBumpTransaction object. If you have an object or base64-encoded string of + * the transaction envelope XDR use {@link TransactionBuilder.fromXDR}. + * + * Once a {@link FeeBumpTransaction} has been created, its attributes and operations + * should not be changed. You should only add signatures (using {@link FeeBumpTransaction#sign}) before + * submitting to the network or forwarding on to additional signers. + * + * @param {string|xdr.TransactionEnvelope} envelope - transaction envelope + * object or base64 encoded string. + * @param {string} networkPassphrase - passphrase of the target Stellar network + * (e.g. "Public Global Stellar Network ; September 2015"). + * + * @extends TransactionBase + */ +var FeeBumpTransaction = exports.FeeBumpTransaction = /*#__PURE__*/function (_TransactionBase) { + function FeeBumpTransaction(envelope, networkPassphrase) { + var _this; + _classCallCheck(this, FeeBumpTransaction); + if (typeof envelope === 'string') { + var buffer = Buffer.from(envelope, 'base64'); + envelope = _xdr["default"].TransactionEnvelope.fromXDR(buffer); + } + var envelopeType = envelope["switch"](); + if (envelopeType !== _xdr["default"].EnvelopeType.envelopeTypeTxFeeBump()) { + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxFeeBump but received an ".concat(envelopeType.name, ".")); + } + var txEnvelope = envelope.value(); + var tx = txEnvelope.tx(); + var fee = tx.fee().toString(); + // clone signatures + var signatures = (txEnvelope.signatures() || []).slice(); + _this = _callSuper(this, FeeBumpTransaction, [tx, signatures, fee, networkPassphrase]); + var innerTxEnvelope = _xdr["default"].TransactionEnvelope.envelopeTypeTx(tx.innerTx().v1()); + _this._feeSource = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(_this.tx.feeSource()); + _this._innerTransaction = new _transaction.Transaction(innerTxEnvelope, networkPassphrase); + return _this; + } + + /** + * @type {Transaction} + * @readonly + */ + _inherits(FeeBumpTransaction, _TransactionBase); + return _createClass(FeeBumpTransaction, [{ + key: "innerTransaction", + get: function get() { + return this._innerTransaction; + } + + /** + * @type {Operation[]} + * @readonly + */ + }, { + key: "operations", + get: function get() { + return this._innerTransaction.operations; + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "feeSource", + get: function get() { + return this._feeSource; + } + + /** + * Returns the "signature base" of this transaction, which is the value + * that, when hashed, should be signed to create a signature that + * validators on the Stellar Network will accept. + * + * It is composed of a 4 prefix bytes followed by the xdr-encoded form + * of this transaction. + * @returns {Buffer} + */ + }, { + key: "signatureBase", + value: function signatureBase() { + var taggedTransaction = new _xdr["default"].TransactionSignaturePayloadTaggedTransaction.envelopeTypeTxFeeBump(this.tx); + var txSignature = new _xdr["default"].TransactionSignaturePayload({ + networkId: _xdr["default"].Hash.fromXDR((0, _hashing.hash)(this.networkPassphrase)), + taggedTransaction: taggedTransaction + }); + return txSignature.toXDR(); + } + + /** + * To envelope returns a xdr.TransactionEnvelope which can be submitted to the network. + * @returns {xdr.TransactionEnvelope} + */ + }, { + key: "toEnvelope", + value: function toEnvelope() { + var envelope = new _xdr["default"].FeeBumpTransactionEnvelope({ + tx: _xdr["default"].FeeBumpTransaction.fromXDR(this.tx.toXDR()), + // make a copy of the tx + signatures: this.signatures.slice() // make a copy of the signatures + }); + return new _xdr["default"].TransactionEnvelope.envelopeTypeTxFeeBump(envelope); + } + }]); +}(_transaction_base.TransactionBase); + +/***/ }), + +/***/ 7938: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var XDR = _interopRequireWildcard(__webpack_require__(3740)); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +// Automatically generated by xdrgen on 2024-09-12T11:09:00-08:00 +// DO NOT EDIT or your changes may be overwritten + +/* jshint maxstatements:2147483647 */ +/* jshint esnext:true */ + +var types = XDR.config(function (xdr) { + // Workaround for https://github.com/stellar/xdrgen/issues/152 + // + // The "correct" way would be to replace bare instances of each constant with + // xdr.lookup("..."), but that's more error-prone. + var SCSYMBOL_LIMIT = 32; + var SC_SPEC_DOC_LIMIT = 1024; + + // === xdr source ============================================================ + // + // typedef opaque Value<>; + // + // =========================================================================== + xdr.typedef("Value", xdr.varOpaque()); + + // === xdr source ============================================================ + // + // struct SCPBallot + // { + // uint32 counter; // n + // Value value; // x + // }; + // + // =========================================================================== + xdr.struct("ScpBallot", [["counter", xdr.lookup("Uint32")], ["value", xdr.lookup("Value")]]); + + // === xdr source ============================================================ + // + // enum SCPStatementType + // { + // SCP_ST_PREPARE = 0, + // SCP_ST_CONFIRM = 1, + // SCP_ST_EXTERNALIZE = 2, + // SCP_ST_NOMINATE = 3 + // }; + // + // =========================================================================== + xdr["enum"]("ScpStatementType", { + scpStPrepare: 0, + scpStConfirm: 1, + scpStExternalize: 2, + scpStNominate: 3 + }); + + // === xdr source ============================================================ + // + // struct SCPNomination + // { + // Hash quorumSetHash; // D + // Value votes<>; // X + // Value accepted<>; // Y + // }; + // + // =========================================================================== + xdr.struct("ScpNomination", [["quorumSetHash", xdr.lookup("Hash")], ["votes", xdr.varArray(xdr.lookup("Value"), 2147483647)], ["accepted", xdr.varArray(xdr.lookup("Value"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } + // + // =========================================================================== + xdr.struct("ScpStatementPrepare", [["quorumSetHash", xdr.lookup("Hash")], ["ballot", xdr.lookup("ScpBallot")], ["prepared", xdr.option(xdr.lookup("ScpBallot"))], ["preparedPrime", xdr.option(xdr.lookup("ScpBallot"))], ["nC", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } + // + // =========================================================================== + xdr.struct("ScpStatementConfirm", [["ballot", xdr.lookup("ScpBallot")], ["nPrepared", xdr.lookup("Uint32")], ["nCommit", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")], ["quorumSetHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } + // + // =========================================================================== + xdr.struct("ScpStatementExternalize", [["commit", xdr.lookup("ScpBallot")], ["nH", xdr.lookup("Uint32")], ["commitQuorumSetHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union switch (SCPStatementType type) + // { + // case SCP_ST_PREPARE: + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } prepare; + // case SCP_ST_CONFIRM: + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } confirm; + // case SCP_ST_EXTERNALIZE: + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } externalize; + // case SCP_ST_NOMINATE: + // SCPNomination nominate; + // } + // + // =========================================================================== + xdr.union("ScpStatementPledges", { + switchOn: xdr.lookup("ScpStatementType"), + switchName: "type", + switches: [["scpStPrepare", "prepare"], ["scpStConfirm", "confirm"], ["scpStExternalize", "externalize"], ["scpStNominate", "nominate"]], + arms: { + prepare: xdr.lookup("ScpStatementPrepare"), + confirm: xdr.lookup("ScpStatementConfirm"), + externalize: xdr.lookup("ScpStatementExternalize"), + nominate: xdr.lookup("ScpNomination") + } + }); + + // === xdr source ============================================================ + // + // struct SCPStatement + // { + // NodeID nodeID; // v + // uint64 slotIndex; // i + // + // union switch (SCPStatementType type) + // { + // case SCP_ST_PREPARE: + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } prepare; + // case SCP_ST_CONFIRM: + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } confirm; + // case SCP_ST_EXTERNALIZE: + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } externalize; + // case SCP_ST_NOMINATE: + // SCPNomination nominate; + // } + // pledges; + // }; + // + // =========================================================================== + xdr.struct("ScpStatement", [["nodeId", xdr.lookup("NodeId")], ["slotIndex", xdr.lookup("Uint64")], ["pledges", xdr.lookup("ScpStatementPledges")]]); + + // === xdr source ============================================================ + // + // struct SCPEnvelope + // { + // SCPStatement statement; + // Signature signature; + // }; + // + // =========================================================================== + xdr.struct("ScpEnvelope", [["statement", xdr.lookup("ScpStatement")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // struct SCPQuorumSet + // { + // uint32 threshold; + // NodeID validators<>; + // SCPQuorumSet innerSets<>; + // }; + // + // =========================================================================== + xdr.struct("ScpQuorumSet", [["threshold", xdr.lookup("Uint32")], ["validators", xdr.varArray(xdr.lookup("NodeId"), 2147483647)], ["innerSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)]]); + + // === xdr source ============================================================ + // + // typedef opaque Thresholds[4]; + // + // =========================================================================== + xdr.typedef("Thresholds", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef string string32<32>; + // + // =========================================================================== + xdr.typedef("String32", xdr.string(32)); + + // === xdr source ============================================================ + // + // typedef string string64<64>; + // + // =========================================================================== + xdr.typedef("String64", xdr.string(64)); + + // === xdr source ============================================================ + // + // typedef int64 SequenceNumber; + // + // =========================================================================== + xdr.typedef("SequenceNumber", xdr.lookup("Int64")); + + // === xdr source ============================================================ + // + // typedef opaque DataValue<64>; + // + // =========================================================================== + xdr.typedef("DataValue", xdr.varOpaque(64)); + + // === xdr source ============================================================ + // + // typedef Hash PoolID; + // + // =========================================================================== + xdr.typedef("PoolId", xdr.lookup("Hash")); + + // === xdr source ============================================================ + // + // typedef opaque AssetCode4[4]; + // + // =========================================================================== + xdr.typedef("AssetCode4", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef opaque AssetCode12[12]; + // + // =========================================================================== + xdr.typedef("AssetCode12", xdr.opaque(12)); + + // === xdr source ============================================================ + // + // enum AssetType + // { + // ASSET_TYPE_NATIVE = 0, + // ASSET_TYPE_CREDIT_ALPHANUM4 = 1, + // ASSET_TYPE_CREDIT_ALPHANUM12 = 2, + // ASSET_TYPE_POOL_SHARE = 3 + // }; + // + // =========================================================================== + xdr["enum"]("AssetType", { + assetTypeNative: 0, + assetTypeCreditAlphanum4: 1, + assetTypeCreditAlphanum12: 2, + assetTypePoolShare: 3 + }); + + // === xdr source ============================================================ + // + // union AssetCode switch (AssetType type) + // { + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AssetCode4 assetCode4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AssetCode12 assetCode12; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("AssetCode", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeCreditAlphanum4", "assetCode4"], ["assetTypeCreditAlphanum12", "assetCode12"]], + arms: { + assetCode4: xdr.lookup("AssetCode4"), + assetCode12: xdr.lookup("AssetCode12") + } + }); + + // === xdr source ============================================================ + // + // struct AlphaNum4 + // { + // AssetCode4 assetCode; + // AccountID issuer; + // }; + // + // =========================================================================== + xdr.struct("AlphaNum4", [["assetCode", xdr.lookup("AssetCode4")], ["issuer", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // struct AlphaNum12 + // { + // AssetCode12 assetCode; + // AccountID issuer; + // }; + // + // =========================================================================== + xdr.struct("AlphaNum12", [["assetCode", xdr.lookup("AssetCode12")], ["issuer", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // union Asset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("Asset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12") + } + }); + + // === xdr source ============================================================ + // + // struct Price + // { + // int32 n; // numerator + // int32 d; // denominator + // }; + // + // =========================================================================== + xdr.struct("Price", [["n", xdr.lookup("Int32")], ["d", xdr.lookup("Int32")]]); + + // === xdr source ============================================================ + // + // struct Liabilities + // { + // int64 buying; + // int64 selling; + // }; + // + // =========================================================================== + xdr.struct("Liabilities", [["buying", xdr.lookup("Int64")], ["selling", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum ThresholdIndexes + // { + // THRESHOLD_MASTER_WEIGHT = 0, + // THRESHOLD_LOW = 1, + // THRESHOLD_MED = 2, + // THRESHOLD_HIGH = 3 + // }; + // + // =========================================================================== + xdr["enum"]("ThresholdIndices", { + thresholdMasterWeight: 0, + thresholdLow: 1, + thresholdMed: 2, + thresholdHigh: 3 + }); + + // === xdr source ============================================================ + // + // enum LedgerEntryType + // { + // ACCOUNT = 0, + // TRUSTLINE = 1, + // OFFER = 2, + // DATA = 3, + // CLAIMABLE_BALANCE = 4, + // LIQUIDITY_POOL = 5, + // CONTRACT_DATA = 6, + // CONTRACT_CODE = 7, + // CONFIG_SETTING = 8, + // TTL = 9 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerEntryType", { + account: 0, + trustline: 1, + offer: 2, + data: 3, + claimableBalance: 4, + liquidityPool: 5, + contractData: 6, + contractCode: 7, + configSetting: 8, + ttl: 9 + }); + + // === xdr source ============================================================ + // + // struct Signer + // { + // SignerKey key; + // uint32 weight; // really only need 1 byte + // }; + // + // =========================================================================== + xdr.struct("Signer", [["key", xdr.lookup("SignerKey")], ["weight", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // enum AccountFlags + // { // masks for each flag + // + // // Flags set on issuer accounts + // // TrustLines are created with authorized set to "false" requiring + // // the issuer to set it for each TrustLine + // AUTH_REQUIRED_FLAG = 0x1, + // // If set, the authorized flag in TrustLines can be cleared + // // otherwise, authorization cannot be revoked + // AUTH_REVOCABLE_FLAG = 0x2, + // // Once set, causes all AUTH_* flags to be read-only + // AUTH_IMMUTABLE_FLAG = 0x4, + // // Trustlines are created with clawback enabled set to "true", + // // and claimable balances created from those trustlines are created + // // with clawback enabled set to "true" + // AUTH_CLAWBACK_ENABLED_FLAG = 0x8 + // }; + // + // =========================================================================== + xdr["enum"]("AccountFlags", { + authRequiredFlag: 1, + authRevocableFlag: 2, + authImmutableFlag: 4, + authClawbackEnabledFlag: 8 + }); + + // === xdr source ============================================================ + // + // const MASK_ACCOUNT_FLAGS = 0x7; + // + // =========================================================================== + xdr["const"]("MASK_ACCOUNT_FLAGS", 0x7); + + // === xdr source ============================================================ + // + // const MASK_ACCOUNT_FLAGS_V17 = 0xF; + // + // =========================================================================== + xdr["const"]("MASK_ACCOUNT_FLAGS_V17", 0xF); + + // === xdr source ============================================================ + // + // const MAX_SIGNERS = 20; + // + // =========================================================================== + xdr["const"]("MAX_SIGNERS", 20); + + // === xdr source ============================================================ + // + // typedef AccountID* SponsorshipDescriptor; + // + // =========================================================================== + xdr.typedef("SponsorshipDescriptor", xdr.option(xdr.lookup("AccountId"))); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV3 + // { + // // We can use this to add more fields, or because it is first, to + // // change AccountEntryExtensionV3 into a union. + // ExtensionPoint ext; + // + // // Ledger number at which `seqNum` took on its present value. + // uint32 seqLedger; + // + // // Time at which `seqNum` took on its present value. + // TimePoint seqTime; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV3", [["ext", xdr.lookup("ExtensionPoint")], ["seqLedger", xdr.lookup("Uint32")], ["seqTime", xdr.lookup("TimePoint")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 3: + // AccountEntryExtensionV3 v3; + // } + // + // =========================================================================== + xdr.union("AccountEntryExtensionV2Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [3, "v3"]], + arms: { + v3: xdr.lookup("AccountEntryExtensionV3") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV2 + // { + // uint32 numSponsored; + // uint32 numSponsoring; + // SponsorshipDescriptor signerSponsoringIDs; + // + // union switch (int v) + // { + // case 0: + // void; + // case 3: + // AccountEntryExtensionV3 v3; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV2", [["numSponsored", xdr.lookup("Uint32")], ["numSponsoring", xdr.lookup("Uint32")], ["signerSponsoringIDs", xdr.varArray(xdr.lookup("SponsorshipDescriptor"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExtensionV2Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // AccountEntryExtensionV2 v2; + // } + // + // =========================================================================== + xdr.union("AccountEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [2, "v2"]], + arms: { + v2: xdr.lookup("AccountEntryExtensionV2") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV1 + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // AccountEntryExtensionV2 v2; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("AccountEntryExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // AccountEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("AccountEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("AccountEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntry + // { + // AccountID accountID; // master public key for this account + // int64 balance; // in stroops + // SequenceNumber seqNum; // last sequence number used for this account + // uint32 numSubEntries; // number of sub-entries this account has + // // drives the reserve + // AccountID* inflationDest; // Account to vote for during inflation + // uint32 flags; // see AccountFlags + // + // string32 homeDomain; // can be used for reverse federation and memo lookup + // + // // fields used for signatures + // // thresholds stores unsigned bytes: [weight of master|low|medium|high] + // Thresholds thresholds; + // + // Signer signers; // possible signers for this account + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // AccountEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntry", [["accountId", xdr.lookup("AccountId")], ["balance", xdr.lookup("Int64")], ["seqNum", xdr.lookup("SequenceNumber")], ["numSubEntries", xdr.lookup("Uint32")], ["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["flags", xdr.lookup("Uint32")], ["homeDomain", xdr.lookup("String32")], ["thresholds", xdr.lookup("Thresholds")], ["signers", xdr.varArray(xdr.lookup("Signer"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExt")]]); + + // === xdr source ============================================================ + // + // enum TrustLineFlags + // { + // // issuer has authorized account to perform transactions with its credit + // AUTHORIZED_FLAG = 1, + // // issuer has authorized account to maintain and reduce liabilities for its + // // credit + // AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG = 2, + // // issuer has specified that it may clawback its credit, and that claimable + // // balances created with its credit may also be clawed back + // TRUSTLINE_CLAWBACK_ENABLED_FLAG = 4 + // }; + // + // =========================================================================== + xdr["enum"]("TrustLineFlags", { + authorizedFlag: 1, + authorizedToMaintainLiabilitiesFlag: 2, + trustlineClawbackEnabledFlag: 4 + }); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS = 1; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS", 1); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS_V13 = 3; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS_V13", 3); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS_V17 = 7; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS_V17", 7); + + // === xdr source ============================================================ + // + // enum LiquidityPoolType + // { + // LIQUIDITY_POOL_CONSTANT_PRODUCT = 0 + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolType", { + liquidityPoolConstantProduct: 0 + }); + + // === xdr source ============================================================ + // + // union TrustLineAsset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // case ASSET_TYPE_POOL_SHARE: + // PoolID liquidityPoolID; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("TrustLineAsset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPoolId"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12"), + liquidityPoolId: xdr.lookup("PoolId") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryExtensionV2Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TrustLineEntryExtensionV2 + // { + // int32 liquidityPoolUseCount; + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TrustLineEntryExtensionV2", [["liquidityPoolUseCount", xdr.lookup("Int32")], ["ext", xdr.lookup("TrustLineEntryExtensionV2Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [2, "v2"]], + arms: { + v2: xdr.lookup("TrustLineEntryExtensionV2") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } + // + // =========================================================================== + xdr.struct("TrustLineEntryV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("TrustLineEntryV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } v1; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("TrustLineEntryV1") + } + }); + + // === xdr source ============================================================ + // + // struct TrustLineEntry + // { + // AccountID accountID; // account this trustline belongs to + // TrustLineAsset asset; // type of asset (with issuer) + // int64 balance; // how much of this asset the user has. + // // Asset defines the unit for this; + // + // int64 limit; // balance cannot be above this + // uint32 flags; // see TrustLineFlags + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TrustLineEntry", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")], ["balance", xdr.lookup("Int64")], ["limit", xdr.lookup("Int64")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("TrustLineEntryExt")]]); + + // === xdr source ============================================================ + // + // enum OfferEntryFlags + // { + // // an offer with this flag will not act on and take a reverse offer of equal + // // price + // PASSIVE_FLAG = 1 + // }; + // + // =========================================================================== + xdr["enum"]("OfferEntryFlags", { + passiveFlag: 1 + }); + + // === xdr source ============================================================ + // + // const MASK_OFFERENTRY_FLAGS = 1; + // + // =========================================================================== + xdr["const"]("MASK_OFFERENTRY_FLAGS", 1); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("OfferEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct OfferEntry + // { + // AccountID sellerID; + // int64 offerID; + // Asset selling; // A + // Asset buying; // B + // int64 amount; // amount of A + // + // /* price for this offer: + // price of A in terms of B + // price=AmountB/AmountA=priceNumerator/priceDenominator + // price is after fees + // */ + // Price price; + // uint32 flags; // see OfferEntryFlags + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("OfferEntry", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("OfferEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("DataEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct DataEntry + // { + // AccountID accountID; // account this data belongs to + // string64 dataName; + // DataValue dataValue; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("DataEntry", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")], ["dataValue", xdr.lookup("DataValue")], ["ext", xdr.lookup("DataEntryExt")]]); + + // === xdr source ============================================================ + // + // enum ClaimPredicateType + // { + // CLAIM_PREDICATE_UNCONDITIONAL = 0, + // CLAIM_PREDICATE_AND = 1, + // CLAIM_PREDICATE_OR = 2, + // CLAIM_PREDICATE_NOT = 3, + // CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME = 4, + // CLAIM_PREDICATE_BEFORE_RELATIVE_TIME = 5 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimPredicateType", { + claimPredicateUnconditional: 0, + claimPredicateAnd: 1, + claimPredicateOr: 2, + claimPredicateNot: 3, + claimPredicateBeforeAbsoluteTime: 4, + claimPredicateBeforeRelativeTime: 5 + }); + + // === xdr source ============================================================ + // + // union ClaimPredicate switch (ClaimPredicateType type) + // { + // case CLAIM_PREDICATE_UNCONDITIONAL: + // void; + // case CLAIM_PREDICATE_AND: + // ClaimPredicate andPredicates<2>; + // case CLAIM_PREDICATE_OR: + // ClaimPredicate orPredicates<2>; + // case CLAIM_PREDICATE_NOT: + // ClaimPredicate* notPredicate; + // case CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME: + // int64 absBefore; // Predicate will be true if closeTime < absBefore + // case CLAIM_PREDICATE_BEFORE_RELATIVE_TIME: + // int64 relBefore; // Seconds since closeTime of the ledger in which the + // // ClaimableBalanceEntry was created + // }; + // + // =========================================================================== + xdr.union("ClaimPredicate", { + switchOn: xdr.lookup("ClaimPredicateType"), + switchName: "type", + switches: [["claimPredicateUnconditional", xdr["void"]()], ["claimPredicateAnd", "andPredicates"], ["claimPredicateOr", "orPredicates"], ["claimPredicateNot", "notPredicate"], ["claimPredicateBeforeAbsoluteTime", "absBefore"], ["claimPredicateBeforeRelativeTime", "relBefore"]], + arms: { + andPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2), + orPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2), + notPredicate: xdr.option(xdr.lookup("ClaimPredicate")), + absBefore: xdr.lookup("Int64"), + relBefore: xdr.lookup("Int64") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimantType + // { + // CLAIMANT_TYPE_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimantType", { + claimantTypeV0: 0 + }); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID destination; // The account that can use this condition + // ClaimPredicate predicate; // Claimable if predicate is true + // } + // + // =========================================================================== + xdr.struct("ClaimantV0", [["destination", xdr.lookup("AccountId")], ["predicate", xdr.lookup("ClaimPredicate")]]); + + // === xdr source ============================================================ + // + // union Claimant switch (ClaimantType type) + // { + // case CLAIMANT_TYPE_V0: + // struct + // { + // AccountID destination; // The account that can use this condition + // ClaimPredicate predicate; // Claimable if predicate is true + // } v0; + // }; + // + // =========================================================================== + xdr.union("Claimant", { + switchOn: xdr.lookup("ClaimantType"), + switchName: "type", + switches: [["claimantTypeV0", "v0"]], + arms: { + v0: xdr.lookup("ClaimantV0") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimableBalanceIDType + // { + // CLAIMABLE_BALANCE_ID_TYPE_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimableBalanceIdType", { + claimableBalanceIdTypeV0: 0 + }); + + // === xdr source ============================================================ + // + // union ClaimableBalanceID switch (ClaimableBalanceIDType type) + // { + // case CLAIMABLE_BALANCE_ID_TYPE_V0: + // Hash v0; + // }; + // + // =========================================================================== + xdr.union("ClaimableBalanceId", { + switchOn: xdr.lookup("ClaimableBalanceIdType"), + switchName: "type", + switches: [["claimableBalanceIdTypeV0", "v0"]], + arms: { + v0: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimableBalanceFlags + // { + // // If set, the issuer account of the asset held by the claimable balance may + // // clawback the claimable balance + // CLAIMABLE_BALANCE_CLAWBACK_ENABLED_FLAG = 0x1 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimableBalanceFlags", { + claimableBalanceClawbackEnabledFlag: 1 + }); + + // === xdr source ============================================================ + // + // const MASK_CLAIMABLE_BALANCE_FLAGS = 0x1; + // + // =========================================================================== + xdr["const"]("MASK_CLAIMABLE_BALANCE_FLAGS", 0x1); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("ClaimableBalanceEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct ClaimableBalanceEntryExtensionV1 + // { + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // + // uint32 flags; // see ClaimableBalanceFlags + // }; + // + // =========================================================================== + xdr.struct("ClaimableBalanceEntryExtensionV1", [["ext", xdr.lookup("ClaimableBalanceEntryExtensionV1Ext")], ["flags", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ClaimableBalanceEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("ClaimableBalanceEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("ClaimableBalanceEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct ClaimableBalanceEntry + // { + // // Unique identifier for this ClaimableBalanceEntry + // ClaimableBalanceID balanceID; + // + // // List of claimants with associated predicate + // Claimant claimants<10>; + // + // // Any asset including native + // Asset asset; + // + // // Amount of asset + // int64 amount; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ClaimableBalanceEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("ClaimableBalanceEntry", [["balanceId", xdr.lookup("ClaimableBalanceId")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["ext", xdr.lookup("ClaimableBalanceEntryExt")]]); + + // === xdr source ============================================================ + // + // struct LiquidityPoolConstantProductParameters + // { + // Asset assetA; // assetA < assetB + // Asset assetB; + // int32 fee; // Fee is in basis points, so the actual rate is (fee/100)% + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolConstantProductParameters", [["assetA", xdr.lookup("Asset")], ["assetB", xdr.lookup("Asset")], ["fee", xdr.lookup("Int32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } + // + // =========================================================================== + xdr.struct("LiquidityPoolEntryConstantProduct", [["params", xdr.lookup("LiquidityPoolConstantProductParameters")], ["reserveA", xdr.lookup("Int64")], ["reserveB", xdr.lookup("Int64")], ["totalPoolShares", xdr.lookup("Int64")], ["poolSharesTrustLineCount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } constantProduct; + // } + // + // =========================================================================== + xdr.union("LiquidityPoolEntryBody", { + switchOn: xdr.lookup("LiquidityPoolType"), + switchName: "type", + switches: [["liquidityPoolConstantProduct", "constantProduct"]], + arms: { + constantProduct: xdr.lookup("LiquidityPoolEntryConstantProduct") + } + }); + + // === xdr source ============================================================ + // + // struct LiquidityPoolEntry + // { + // PoolID liquidityPoolID; + // + // union switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } constantProduct; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolEntry", [["liquidityPoolId", xdr.lookup("PoolId")], ["body", xdr.lookup("LiquidityPoolEntryBody")]]); + + // === xdr source ============================================================ + // + // enum ContractDataDurability { + // TEMPORARY = 0, + // PERSISTENT = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractDataDurability", { + temporary: 0, + persistent: 1 + }); + + // === xdr source ============================================================ + // + // struct ContractDataEntry { + // ExtensionPoint ext; + // + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // SCVal val; + // }; + // + // =========================================================================== + xdr.struct("ContractDataEntry", [["ext", xdr.lookup("ExtensionPoint")], ["contract", xdr.lookup("ScAddress")], ["key", xdr.lookup("ScVal")], ["durability", xdr.lookup("ContractDataDurability")], ["val", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // struct ContractCodeCostInputs { + // ExtensionPoint ext; + // uint32 nInstructions; + // uint32 nFunctions; + // uint32 nGlobals; + // uint32 nTableEntries; + // uint32 nTypes; + // uint32 nDataSegments; + // uint32 nElemSegments; + // uint32 nImports; + // uint32 nExports; + // uint32 nDataSegmentBytes; + // }; + // + // =========================================================================== + xdr.struct("ContractCodeCostInputs", [["ext", xdr.lookup("ExtensionPoint")], ["nInstructions", xdr.lookup("Uint32")], ["nFunctions", xdr.lookup("Uint32")], ["nGlobals", xdr.lookup("Uint32")], ["nTableEntries", xdr.lookup("Uint32")], ["nTypes", xdr.lookup("Uint32")], ["nDataSegments", xdr.lookup("Uint32")], ["nElemSegments", xdr.lookup("Uint32")], ["nImports", xdr.lookup("Uint32")], ["nExports", xdr.lookup("Uint32")], ["nDataSegmentBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } + // + // =========================================================================== + xdr.struct("ContractCodeEntryV1", [["ext", xdr.lookup("ExtensionPoint")], ["costInputs", xdr.lookup("ContractCodeCostInputs")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } v1; + // } + // + // =========================================================================== + xdr.union("ContractCodeEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("ContractCodeEntryV1") + } + }); + + // === xdr source ============================================================ + // + // struct ContractCodeEntry { + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } v1; + // } ext; + // + // Hash hash; + // opaque code<>; + // }; + // + // =========================================================================== + xdr.struct("ContractCodeEntry", [["ext", xdr.lookup("ContractCodeEntryExt")], ["hash", xdr.lookup("Hash")], ["code", xdr.varOpaque()]]); + + // === xdr source ============================================================ + // + // struct TTLEntry { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // uint32 liveUntilLedgerSeq; + // }; + // + // =========================================================================== + xdr.struct("TtlEntry", [["keyHash", xdr.lookup("Hash")], ["liveUntilLedgerSeq", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerEntryExtensionV1 + // { + // SponsorshipDescriptor sponsoringID; + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerEntryExtensionV1", [["sponsoringId", xdr.lookup("SponsorshipDescriptor")], ["ext", xdr.lookup("LedgerEntryExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (LedgerEntryType type) + // { + // case ACCOUNT: + // AccountEntry account; + // case TRUSTLINE: + // TrustLineEntry trustLine; + // case OFFER: + // OfferEntry offer; + // case DATA: + // DataEntry data; + // case CLAIMABLE_BALANCE: + // ClaimableBalanceEntry claimableBalance; + // case LIQUIDITY_POOL: + // LiquidityPoolEntry liquidityPool; + // case CONTRACT_DATA: + // ContractDataEntry contractData; + // case CONTRACT_CODE: + // ContractCodeEntry contractCode; + // case CONFIG_SETTING: + // ConfigSettingEntry configSetting; + // case TTL: + // TTLEntry ttl; + // } + // + // =========================================================================== + xdr.union("LedgerEntryData", { + switchOn: xdr.lookup("LedgerEntryType"), + switchName: "type", + switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"], ["contractData", "contractData"], ["contractCode", "contractCode"], ["configSetting", "configSetting"], ["ttl", "ttl"]], + arms: { + account: xdr.lookup("AccountEntry"), + trustLine: xdr.lookup("TrustLineEntry"), + offer: xdr.lookup("OfferEntry"), + data: xdr.lookup("DataEntry"), + claimableBalance: xdr.lookup("ClaimableBalanceEntry"), + liquidityPool: xdr.lookup("LiquidityPoolEntry"), + contractData: xdr.lookup("ContractDataEntry"), + contractCode: xdr.lookup("ContractCodeEntry"), + configSetting: xdr.lookup("ConfigSettingEntry"), + ttl: xdr.lookup("TtlEntry") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("LedgerEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerEntry + // { + // uint32 lastModifiedLedgerSeq; // ledger the LedgerEntry was last changed + // + // union switch (LedgerEntryType type) + // { + // case ACCOUNT: + // AccountEntry account; + // case TRUSTLINE: + // TrustLineEntry trustLine; + // case OFFER: + // OfferEntry offer; + // case DATA: + // DataEntry data; + // case CLAIMABLE_BALANCE: + // ClaimableBalanceEntry claimableBalance; + // case LIQUIDITY_POOL: + // LiquidityPoolEntry liquidityPool; + // case CONTRACT_DATA: + // ContractDataEntry contractData; + // case CONTRACT_CODE: + // ContractCodeEntry contractCode; + // case CONFIG_SETTING: + // ConfigSettingEntry configSetting; + // case TTL: + // TTLEntry ttl; + // } + // data; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerEntry", [["lastModifiedLedgerSeq", xdr.lookup("Uint32")], ["data", xdr.lookup("LedgerEntryData")], ["ext", xdr.lookup("LedgerEntryExt")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyAccount", [["accountId", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // TrustLineAsset asset; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyTrustLine", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sellerID; + // int64 offerID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyOffer", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // string64 dataName; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyData", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimableBalanceID balanceID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyClaimableBalance", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // PoolID liquidityPoolID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyLiquidityPool", [["liquidityPoolId", xdr.lookup("PoolId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyContractData", [["contract", xdr.lookup("ScAddress")], ["key", xdr.lookup("ScVal")], ["durability", xdr.lookup("ContractDataDurability")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash hash; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyContractCode", [["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ConfigSettingID configSettingID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyConfigSetting", [["configSettingId", xdr.lookup("ConfigSettingId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyTtl", [["keyHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union LedgerKey switch (LedgerEntryType type) + // { + // case ACCOUNT: + // struct + // { + // AccountID accountID; + // } account; + // + // case TRUSTLINE: + // struct + // { + // AccountID accountID; + // TrustLineAsset asset; + // } trustLine; + // + // case OFFER: + // struct + // { + // AccountID sellerID; + // int64 offerID; + // } offer; + // + // case DATA: + // struct + // { + // AccountID accountID; + // string64 dataName; + // } data; + // + // case CLAIMABLE_BALANCE: + // struct + // { + // ClaimableBalanceID balanceID; + // } claimableBalance; + // + // case LIQUIDITY_POOL: + // struct + // { + // PoolID liquidityPoolID; + // } liquidityPool; + // case CONTRACT_DATA: + // struct + // { + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // } contractData; + // case CONTRACT_CODE: + // struct + // { + // Hash hash; + // } contractCode; + // case CONFIG_SETTING: + // struct + // { + // ConfigSettingID configSettingID; + // } configSetting; + // case TTL: + // struct + // { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // } ttl; + // }; + // + // =========================================================================== + xdr.union("LedgerKey", { + switchOn: xdr.lookup("LedgerEntryType"), + switchName: "type", + switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"], ["contractData", "contractData"], ["contractCode", "contractCode"], ["configSetting", "configSetting"], ["ttl", "ttl"]], + arms: { + account: xdr.lookup("LedgerKeyAccount"), + trustLine: xdr.lookup("LedgerKeyTrustLine"), + offer: xdr.lookup("LedgerKeyOffer"), + data: xdr.lookup("LedgerKeyData"), + claimableBalance: xdr.lookup("LedgerKeyClaimableBalance"), + liquidityPool: xdr.lookup("LedgerKeyLiquidityPool"), + contractData: xdr.lookup("LedgerKeyContractData"), + contractCode: xdr.lookup("LedgerKeyContractCode"), + configSetting: xdr.lookup("LedgerKeyConfigSetting"), + ttl: xdr.lookup("LedgerKeyTtl") + } + }); + + // === xdr source ============================================================ + // + // enum EnvelopeType + // { + // ENVELOPE_TYPE_TX_V0 = 0, + // ENVELOPE_TYPE_SCP = 1, + // ENVELOPE_TYPE_TX = 2, + // ENVELOPE_TYPE_AUTH = 3, + // ENVELOPE_TYPE_SCPVALUE = 4, + // ENVELOPE_TYPE_TX_FEE_BUMP = 5, + // ENVELOPE_TYPE_OP_ID = 6, + // ENVELOPE_TYPE_POOL_REVOKE_OP_ID = 7, + // ENVELOPE_TYPE_CONTRACT_ID = 8, + // ENVELOPE_TYPE_SOROBAN_AUTHORIZATION = 9 + // }; + // + // =========================================================================== + xdr["enum"]("EnvelopeType", { + envelopeTypeTxV0: 0, + envelopeTypeScp: 1, + envelopeTypeTx: 2, + envelopeTypeAuth: 3, + envelopeTypeScpvalue: 4, + envelopeTypeTxFeeBump: 5, + envelopeTypeOpId: 6, + envelopeTypePoolRevokeOpId: 7, + envelopeTypeContractId: 8, + envelopeTypeSorobanAuthorization: 9 + }); + + // === xdr source ============================================================ + // + // enum BucketListType + // { + // LIVE = 0, + // HOT_ARCHIVE = 1, + // COLD_ARCHIVE = 2 + // }; + // + // =========================================================================== + xdr["enum"]("BucketListType", { + live: 0, + hotArchive: 1, + coldArchive: 2 + }); + + // === xdr source ============================================================ + // + // enum BucketEntryType + // { + // METAENTRY = + // -1, // At-and-after protocol 11: bucket metadata, should come first. + // LIVEENTRY = 0, // Before protocol 11: created-or-updated; + // // At-and-after protocol 11: only updated. + // DEADENTRY = 1, + // INITENTRY = 2 // At-and-after protocol 11: only created. + // }; + // + // =========================================================================== + xdr["enum"]("BucketEntryType", { + metaentry: -1, + liveentry: 0, + deadentry: 1, + initentry: 2 + }); + + // === xdr source ============================================================ + // + // enum HotArchiveBucketEntryType + // { + // HOT_ARCHIVE_METAENTRY = -1, // Bucket metadata, should come first. + // HOT_ARCHIVE_ARCHIVED = 0, // Entry is Archived + // HOT_ARCHIVE_LIVE = 1, // Entry was previously HOT_ARCHIVE_ARCHIVED, or HOT_ARCHIVE_DELETED, but + // // has been added back to the live BucketList. + // // Does not need to be persisted. + // HOT_ARCHIVE_DELETED = 2 // Entry deleted (Note: must be persisted in archive) + // }; + // + // =========================================================================== + xdr["enum"]("HotArchiveBucketEntryType", { + hotArchiveMetaentry: -1, + hotArchiveArchived: 0, + hotArchiveLive: 1, + hotArchiveDeleted: 2 + }); + + // === xdr source ============================================================ + // + // enum ColdArchiveBucketEntryType + // { + // COLD_ARCHIVE_METAENTRY = -1, // Bucket metadata, should come first. + // COLD_ARCHIVE_ARCHIVED_LEAF = 0, // Full LedgerEntry that was archived during the epoch + // COLD_ARCHIVE_DELETED_LEAF = 1, // LedgerKey that was deleted during the epoch + // COLD_ARCHIVE_BOUNDARY_LEAF = 2, // Dummy leaf representing low/high bound + // COLD_ARCHIVE_HASH = 3 // Intermediary Merkle hash entry + // }; + // + // =========================================================================== + xdr["enum"]("ColdArchiveBucketEntryType", { + coldArchiveMetaentry: -1, + coldArchiveArchivedLeaf: 0, + coldArchiveDeletedLeaf: 1, + coldArchiveBoundaryLeaf: 2, + coldArchiveHash: 3 + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // BucketListType bucketListType; + // } + // + // =========================================================================== + xdr.union("BucketMetadataExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "bucketListType"]], + arms: { + bucketListType: xdr.lookup("BucketListType") + } + }); + + // === xdr source ============================================================ + // + // struct BucketMetadata + // { + // // Indicates the protocol version used to create / merge this bucket. + // uint32 ledgerVersion; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // BucketListType bucketListType; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("BucketMetadata", [["ledgerVersion", xdr.lookup("Uint32")], ["ext", xdr.lookup("BucketMetadataExt")]]); + + // === xdr source ============================================================ + // + // union BucketEntry switch (BucketEntryType type) + // { + // case LIVEENTRY: + // case INITENTRY: + // LedgerEntry liveEntry; + // + // case DEADENTRY: + // LedgerKey deadEntry; + // case METAENTRY: + // BucketMetadata metaEntry; + // }; + // + // =========================================================================== + xdr.union("BucketEntry", { + switchOn: xdr.lookup("BucketEntryType"), + switchName: "type", + switches: [["liveentry", "liveEntry"], ["initentry", "liveEntry"], ["deadentry", "deadEntry"], ["metaentry", "metaEntry"]], + arms: { + liveEntry: xdr.lookup("LedgerEntry"), + deadEntry: xdr.lookup("LedgerKey"), + metaEntry: xdr.lookup("BucketMetadata") + } + }); + + // === xdr source ============================================================ + // + // union HotArchiveBucketEntry switch (HotArchiveBucketEntryType type) + // { + // case HOT_ARCHIVE_ARCHIVED: + // LedgerEntry archivedEntry; + // + // case HOT_ARCHIVE_LIVE: + // case HOT_ARCHIVE_DELETED: + // LedgerKey key; + // case HOT_ARCHIVE_METAENTRY: + // BucketMetadata metaEntry; + // }; + // + // =========================================================================== + xdr.union("HotArchiveBucketEntry", { + switchOn: xdr.lookup("HotArchiveBucketEntryType"), + switchName: "type", + switches: [["hotArchiveArchived", "archivedEntry"], ["hotArchiveLive", "key"], ["hotArchiveDeleted", "key"], ["hotArchiveMetaentry", "metaEntry"]], + arms: { + archivedEntry: xdr.lookup("LedgerEntry"), + key: xdr.lookup("LedgerKey"), + metaEntry: xdr.lookup("BucketMetadata") + } + }); + + // === xdr source ============================================================ + // + // struct ColdArchiveArchivedLeaf + // { + // uint32 index; + // LedgerEntry archivedEntry; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveArchivedLeaf", [["index", xdr.lookup("Uint32")], ["archivedEntry", xdr.lookup("LedgerEntry")]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveDeletedLeaf + // { + // uint32 index; + // LedgerKey deletedKey; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveDeletedLeaf", [["index", xdr.lookup("Uint32")], ["deletedKey", xdr.lookup("LedgerKey")]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveBoundaryLeaf + // { + // uint32 index; + // bool isLowerBound; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveBoundaryLeaf", [["index", xdr.lookup("Uint32")], ["isLowerBound", xdr.bool()]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveHashEntry + // { + // uint32 index; + // uint32 level; + // Hash hash; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveHashEntry", [["index", xdr.lookup("Uint32")], ["level", xdr.lookup("Uint32")], ["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union ColdArchiveBucketEntry switch (ColdArchiveBucketEntryType type) + // { + // case COLD_ARCHIVE_METAENTRY: + // BucketMetadata metaEntry; + // case COLD_ARCHIVE_ARCHIVED_LEAF: + // ColdArchiveArchivedLeaf archivedLeaf; + // case COLD_ARCHIVE_DELETED_LEAF: + // ColdArchiveDeletedLeaf deletedLeaf; + // case COLD_ARCHIVE_BOUNDARY_LEAF: + // ColdArchiveBoundaryLeaf boundaryLeaf; + // case COLD_ARCHIVE_HASH: + // ColdArchiveHashEntry hashEntry; + // }; + // + // =========================================================================== + xdr.union("ColdArchiveBucketEntry", { + switchOn: xdr.lookup("ColdArchiveBucketEntryType"), + switchName: "type", + switches: [["coldArchiveMetaentry", "metaEntry"], ["coldArchiveArchivedLeaf", "archivedLeaf"], ["coldArchiveDeletedLeaf", "deletedLeaf"], ["coldArchiveBoundaryLeaf", "boundaryLeaf"], ["coldArchiveHash", "hashEntry"]], + arms: { + metaEntry: xdr.lookup("BucketMetadata"), + archivedLeaf: xdr.lookup("ColdArchiveArchivedLeaf"), + deletedLeaf: xdr.lookup("ColdArchiveDeletedLeaf"), + boundaryLeaf: xdr.lookup("ColdArchiveBoundaryLeaf"), + hashEntry: xdr.lookup("ColdArchiveHashEntry") + } + }); + + // === xdr source ============================================================ + // + // typedef opaque UpgradeType<128>; + // + // =========================================================================== + xdr.typedef("UpgradeType", xdr.varOpaque(128)); + + // === xdr source ============================================================ + // + // enum StellarValueType + // { + // STELLAR_VALUE_BASIC = 0, + // STELLAR_VALUE_SIGNED = 1 + // }; + // + // =========================================================================== + xdr["enum"]("StellarValueType", { + stellarValueBasic: 0, + stellarValueSigned: 1 + }); + + // === xdr source ============================================================ + // + // struct LedgerCloseValueSignature + // { + // NodeID nodeID; // which node introduced the value + // Signature signature; // nodeID's signature + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseValueSignature", [["nodeId", xdr.lookup("NodeId")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // union switch (StellarValueType v) + // { + // case STELLAR_VALUE_BASIC: + // void; + // case STELLAR_VALUE_SIGNED: + // LedgerCloseValueSignature lcValueSignature; + // } + // + // =========================================================================== + xdr.union("StellarValueExt", { + switchOn: xdr.lookup("StellarValueType"), + switchName: "v", + switches: [["stellarValueBasic", xdr["void"]()], ["stellarValueSigned", "lcValueSignature"]], + arms: { + lcValueSignature: xdr.lookup("LedgerCloseValueSignature") + } + }); + + // === xdr source ============================================================ + // + // struct StellarValue + // { + // Hash txSetHash; // transaction set to apply to previous ledger + // TimePoint closeTime; // network close time + // + // // upgrades to apply to the previous ledger (usually empty) + // // this is a vector of encoded 'LedgerUpgrade' so that nodes can drop + // // unknown steps during consensus if needed. + // // see notes below on 'LedgerUpgrade' for more detail + // // max size is dictated by number of upgrade types (+ room for future) + // UpgradeType upgrades<6>; + // + // // reserved for future use + // union switch (StellarValueType v) + // { + // case STELLAR_VALUE_BASIC: + // void; + // case STELLAR_VALUE_SIGNED: + // LedgerCloseValueSignature lcValueSignature; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("StellarValue", [["txSetHash", xdr.lookup("Hash")], ["closeTime", xdr.lookup("TimePoint")], ["upgrades", xdr.varArray(xdr.lookup("UpgradeType"), 6)], ["ext", xdr.lookup("StellarValueExt")]]); + + // === xdr source ============================================================ + // + // const MASK_LEDGER_HEADER_FLAGS = 0x7; + // + // =========================================================================== + xdr["const"]("MASK_LEDGER_HEADER_FLAGS", 0x7); + + // === xdr source ============================================================ + // + // enum LedgerHeaderFlags + // { + // DISABLE_LIQUIDITY_POOL_TRADING_FLAG = 0x1, + // DISABLE_LIQUIDITY_POOL_DEPOSIT_FLAG = 0x2, + // DISABLE_LIQUIDITY_POOL_WITHDRAWAL_FLAG = 0x4 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerHeaderFlags", { + disableLiquidityPoolTradingFlag: 1, + disableLiquidityPoolDepositFlag: 2, + disableLiquidityPoolWithdrawalFlag: 4 + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerHeaderExtensionV1 + // { + // uint32 flags; // LedgerHeaderFlags + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeaderExtensionV1", [["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("LedgerHeaderExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerHeaderExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerHeaderExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerHeader + // { + // uint32 ledgerVersion; // the protocol version of the ledger + // Hash previousLedgerHash; // hash of the previous ledger header + // StellarValue scpValue; // what consensus agreed to + // Hash txSetResultHash; // the TransactionResultSet that led to this ledger + // Hash bucketListHash; // hash of the ledger state + // + // uint32 ledgerSeq; // sequence number of this ledger + // + // int64 totalCoins; // total number of stroops in existence. + // // 10,000,000 stroops in 1 XLM + // + // int64 feePool; // fees burned since last inflation run + // uint32 inflationSeq; // inflation sequence number + // + // uint64 idPool; // last used global ID, used for generating objects + // + // uint32 baseFee; // base fee per operation in stroops + // uint32 baseReserve; // account base reserve in stroops + // + // uint32 maxTxSetSize; // maximum size a transaction set can be + // + // Hash skipList[4]; // hashes of ledgers in the past. allows you to jump back + // // in time without walking the chain back ledger by ledger + // // each slot contains the oldest ledger that is mod of + // // either 50 5000 50000 or 500000 depending on index + // // skipList[0] mod(50), skipList[1] mod(5000), etc + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerHeaderExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeader", [["ledgerVersion", xdr.lookup("Uint32")], ["previousLedgerHash", xdr.lookup("Hash")], ["scpValue", xdr.lookup("StellarValue")], ["txSetResultHash", xdr.lookup("Hash")], ["bucketListHash", xdr.lookup("Hash")], ["ledgerSeq", xdr.lookup("Uint32")], ["totalCoins", xdr.lookup("Int64")], ["feePool", xdr.lookup("Int64")], ["inflationSeq", xdr.lookup("Uint32")], ["idPool", xdr.lookup("Uint64")], ["baseFee", xdr.lookup("Uint32")], ["baseReserve", xdr.lookup("Uint32")], ["maxTxSetSize", xdr.lookup("Uint32")], ["skipList", xdr.array(xdr.lookup("Hash"), 4)], ["ext", xdr.lookup("LedgerHeaderExt")]]); + + // === xdr source ============================================================ + // + // enum LedgerUpgradeType + // { + // LEDGER_UPGRADE_VERSION = 1, + // LEDGER_UPGRADE_BASE_FEE = 2, + // LEDGER_UPGRADE_MAX_TX_SET_SIZE = 3, + // LEDGER_UPGRADE_BASE_RESERVE = 4, + // LEDGER_UPGRADE_FLAGS = 5, + // LEDGER_UPGRADE_CONFIG = 6, + // LEDGER_UPGRADE_MAX_SOROBAN_TX_SET_SIZE = 7 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerUpgradeType", { + ledgerUpgradeVersion: 1, + ledgerUpgradeBaseFee: 2, + ledgerUpgradeMaxTxSetSize: 3, + ledgerUpgradeBaseReserve: 4, + ledgerUpgradeFlags: 5, + ledgerUpgradeConfig: 6, + ledgerUpgradeMaxSorobanTxSetSize: 7 + }); + + // === xdr source ============================================================ + // + // struct ConfigUpgradeSetKey { + // Hash contractID; + // Hash contentHash; + // }; + // + // =========================================================================== + xdr.struct("ConfigUpgradeSetKey", [["contractId", xdr.lookup("Hash")], ["contentHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union LedgerUpgrade switch (LedgerUpgradeType type) + // { + // case LEDGER_UPGRADE_VERSION: + // uint32 newLedgerVersion; // update ledgerVersion + // case LEDGER_UPGRADE_BASE_FEE: + // uint32 newBaseFee; // update baseFee + // case LEDGER_UPGRADE_MAX_TX_SET_SIZE: + // uint32 newMaxTxSetSize; // update maxTxSetSize + // case LEDGER_UPGRADE_BASE_RESERVE: + // uint32 newBaseReserve; // update baseReserve + // case LEDGER_UPGRADE_FLAGS: + // uint32 newFlags; // update flags + // case LEDGER_UPGRADE_CONFIG: + // // Update arbitrary `ConfigSetting` entries identified by the key. + // ConfigUpgradeSetKey newConfig; + // case LEDGER_UPGRADE_MAX_SOROBAN_TX_SET_SIZE: + // // Update ConfigSettingContractExecutionLanesV0.ledgerMaxTxCount without + // // using `LEDGER_UPGRADE_CONFIG`. + // uint32 newMaxSorobanTxSetSize; + // }; + // + // =========================================================================== + xdr.union("LedgerUpgrade", { + switchOn: xdr.lookup("LedgerUpgradeType"), + switchName: "type", + switches: [["ledgerUpgradeVersion", "newLedgerVersion"], ["ledgerUpgradeBaseFee", "newBaseFee"], ["ledgerUpgradeMaxTxSetSize", "newMaxTxSetSize"], ["ledgerUpgradeBaseReserve", "newBaseReserve"], ["ledgerUpgradeFlags", "newFlags"], ["ledgerUpgradeConfig", "newConfig"], ["ledgerUpgradeMaxSorobanTxSetSize", "newMaxSorobanTxSetSize"]], + arms: { + newLedgerVersion: xdr.lookup("Uint32"), + newBaseFee: xdr.lookup("Uint32"), + newMaxTxSetSize: xdr.lookup("Uint32"), + newBaseReserve: xdr.lookup("Uint32"), + newFlags: xdr.lookup("Uint32"), + newConfig: xdr.lookup("ConfigUpgradeSetKey"), + newMaxSorobanTxSetSize: xdr.lookup("Uint32") + } + }); + + // === xdr source ============================================================ + // + // struct ConfigUpgradeSet { + // ConfigSettingEntry updatedEntry<>; + // }; + // + // =========================================================================== + xdr.struct("ConfigUpgradeSet", [["updatedEntry", xdr.varArray(xdr.lookup("ConfigSettingEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // enum TxSetComponentType + // { + // // txs with effective fee <= bid derived from a base fee (if any). + // // If base fee is not specified, no discount is applied. + // TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE = 0 + // }; + // + // =========================================================================== + xdr["enum"]("TxSetComponentType", { + txsetCompTxsMaybeDiscountedFee: 0 + }); + + // === xdr source ============================================================ + // + // struct + // { + // int64* baseFee; + // TransactionEnvelope txs<>; + // } + // + // =========================================================================== + xdr.struct("TxSetComponentTxsMaybeDiscountedFee", [["baseFee", xdr.option(xdr.lookup("Int64"))], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union TxSetComponent switch (TxSetComponentType type) + // { + // case TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE: + // struct + // { + // int64* baseFee; + // TransactionEnvelope txs<>; + // } txsMaybeDiscountedFee; + // }; + // + // =========================================================================== + xdr.union("TxSetComponent", { + switchOn: xdr.lookup("TxSetComponentType"), + switchName: "type", + switches: [["txsetCompTxsMaybeDiscountedFee", "txsMaybeDiscountedFee"]], + arms: { + txsMaybeDiscountedFee: xdr.lookup("TxSetComponentTxsMaybeDiscountedFee") + } + }); + + // === xdr source ============================================================ + // + // union TransactionPhase switch (int v) + // { + // case 0: + // TxSetComponent v0Components<>; + // }; + // + // =========================================================================== + xdr.union("TransactionPhase", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0Components"]], + arms: { + v0Components: xdr.varArray(xdr.lookup("TxSetComponent"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // struct TransactionSet + // { + // Hash previousLedgerHash; + // TransactionEnvelope txs<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionSet", [["previousLedgerHash", xdr.lookup("Hash")], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionSetV1 + // { + // Hash previousLedgerHash; + // TransactionPhase phases<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionSetV1", [["previousLedgerHash", xdr.lookup("Hash")], ["phases", xdr.varArray(xdr.lookup("TransactionPhase"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union GeneralizedTransactionSet switch (int v) + // { + // // We consider the legacy TransactionSet to be v0. + // case 1: + // TransactionSetV1 v1TxSet; + // }; + // + // =========================================================================== + xdr.union("GeneralizedTransactionSet", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[1, "v1TxSet"]], + arms: { + v1TxSet: xdr.lookup("TransactionSetV1") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionResultPair + // { + // Hash transactionHash; + // TransactionResult result; // result for the transaction + // }; + // + // =========================================================================== + xdr.struct("TransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("TransactionResult")]]); + + // === xdr source ============================================================ + // + // struct TransactionResultSet + // { + // TransactionResultPair results<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionResultSet", [["results", xdr.varArray(xdr.lookup("TransactionResultPair"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // GeneralizedTransactionSet generalizedTxSet; + // } + // + // =========================================================================== + xdr.union("TransactionHistoryEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "generalizedTxSet"]], + arms: { + generalizedTxSet: xdr.lookup("GeneralizedTransactionSet") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionHistoryEntry + // { + // uint32 ledgerSeq; + // TransactionSet txSet; + // + // // when v != 0, txSet must be empty + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // GeneralizedTransactionSet generalizedTxSet; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionHistoryEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txSet", xdr.lookup("TransactionSet")], ["ext", xdr.lookup("TransactionHistoryEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionHistoryResultEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionHistoryResultEntry + // { + // uint32 ledgerSeq; + // TransactionResultSet txResultSet; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionHistoryResultEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txResultSet", xdr.lookup("TransactionResultSet")], ["ext", xdr.lookup("TransactionHistoryResultEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderHistoryEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerHeaderHistoryEntry + // { + // Hash hash; + // LedgerHeader header; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeaderHistoryEntry", [["hash", xdr.lookup("Hash")], ["header", xdr.lookup("LedgerHeader")], ["ext", xdr.lookup("LedgerHeaderHistoryEntryExt")]]); + + // === xdr source ============================================================ + // + // struct LedgerSCPMessages + // { + // uint32 ledgerSeq; + // SCPEnvelope messages<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerScpMessages", [["ledgerSeq", xdr.lookup("Uint32")], ["messages", xdr.varArray(xdr.lookup("ScpEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct SCPHistoryEntryV0 + // { + // SCPQuorumSet quorumSets<>; // additional quorum sets used by ledgerMessages + // LedgerSCPMessages ledgerMessages; + // }; + // + // =========================================================================== + xdr.struct("ScpHistoryEntryV0", [["quorumSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)], ["ledgerMessages", xdr.lookup("LedgerScpMessages")]]); + + // === xdr source ============================================================ + // + // union SCPHistoryEntry switch (int v) + // { + // case 0: + // SCPHistoryEntryV0 v0; + // }; + // + // =========================================================================== + xdr.union("ScpHistoryEntry", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("ScpHistoryEntryV0") + } + }); + + // === xdr source ============================================================ + // + // enum LedgerEntryChangeType + // { + // LEDGER_ENTRY_CREATED = 0, // entry was added to the ledger + // LEDGER_ENTRY_UPDATED = 1, // entry was modified in the ledger + // LEDGER_ENTRY_REMOVED = 2, // entry was removed from the ledger + // LEDGER_ENTRY_STATE = 3 // value of the entry + // }; + // + // =========================================================================== + xdr["enum"]("LedgerEntryChangeType", { + ledgerEntryCreated: 0, + ledgerEntryUpdated: 1, + ledgerEntryRemoved: 2, + ledgerEntryState: 3 + }); + + // === xdr source ============================================================ + // + // union LedgerEntryChange switch (LedgerEntryChangeType type) + // { + // case LEDGER_ENTRY_CREATED: + // LedgerEntry created; + // case LEDGER_ENTRY_UPDATED: + // LedgerEntry updated; + // case LEDGER_ENTRY_REMOVED: + // LedgerKey removed; + // case LEDGER_ENTRY_STATE: + // LedgerEntry state; + // }; + // + // =========================================================================== + xdr.union("LedgerEntryChange", { + switchOn: xdr.lookup("LedgerEntryChangeType"), + switchName: "type", + switches: [["ledgerEntryCreated", "created"], ["ledgerEntryUpdated", "updated"], ["ledgerEntryRemoved", "removed"], ["ledgerEntryState", "state"]], + arms: { + created: xdr.lookup("LedgerEntry"), + updated: xdr.lookup("LedgerEntry"), + removed: xdr.lookup("LedgerKey"), + state: xdr.lookup("LedgerEntry") + } + }); + + // === xdr source ============================================================ + // + // typedef LedgerEntryChange LedgerEntryChanges<>; + // + // =========================================================================== + xdr.typedef("LedgerEntryChanges", xdr.varArray(xdr.lookup("LedgerEntryChange"), 2147483647)); + + // === xdr source ============================================================ + // + // struct OperationMeta + // { + // LedgerEntryChanges changes; + // }; + // + // =========================================================================== + xdr.struct("OperationMeta", [["changes", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV1 + // { + // LedgerEntryChanges txChanges; // tx level changes if any + // OperationMeta operations<>; // meta for each operation + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV1", [["txChanges", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV2 + // { + // LedgerEntryChanges txChangesBefore; // tx level changes before operations + // // are applied if any + // OperationMeta operations<>; // meta for each operation + // LedgerEntryChanges txChangesAfter; // tx level changes after operations are + // // applied if any + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV2", [["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // enum ContractEventType + // { + // SYSTEM = 0, + // CONTRACT = 1, + // DIAGNOSTIC = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ContractEventType", { + system: 0, + contract: 1, + diagnostic: 2 + }); + + // === xdr source ============================================================ + // + // struct + // { + // SCVal topics<>; + // SCVal data; + // } + // + // =========================================================================== + xdr.struct("ContractEventV0", [["topics", xdr.varArray(xdr.lookup("ScVal"), 2147483647)], ["data", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // struct + // { + // SCVal topics<>; + // SCVal data; + // } v0; + // } + // + // =========================================================================== + xdr.union("ContractEventBody", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("ContractEventV0") + } + }); + + // === xdr source ============================================================ + // + // struct ContractEvent + // { + // // We can use this to add more fields, or because it + // // is first, to change ContractEvent into a union. + // ExtensionPoint ext; + // + // Hash* contractID; + // ContractEventType type; + // + // union switch (int v) + // { + // case 0: + // struct + // { + // SCVal topics<>; + // SCVal data; + // } v0; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("ContractEvent", [["ext", xdr.lookup("ExtensionPoint")], ["contractId", xdr.option(xdr.lookup("Hash"))], ["type", xdr.lookup("ContractEventType")], ["body", xdr.lookup("ContractEventBody")]]); + + // === xdr source ============================================================ + // + // struct DiagnosticEvent + // { + // bool inSuccessfulContractCall; + // ContractEvent event; + // }; + // + // =========================================================================== + xdr.struct("DiagnosticEvent", [["inSuccessfulContractCall", xdr.bool()], ["event", xdr.lookup("ContractEvent")]]); + + // === xdr source ============================================================ + // + // typedef DiagnosticEvent DiagnosticEvents<>; + // + // =========================================================================== + xdr.typedef("DiagnosticEvents", xdr.varArray(xdr.lookup("DiagnosticEvent"), 2147483647)); + + // === xdr source ============================================================ + // + // struct SorobanTransactionMetaExtV1 + // { + // ExtensionPoint ext; + // + // // The following are the components of the overall Soroban resource fee + // // charged for the transaction. + // // The following relation holds: + // // `resourceFeeCharged = totalNonRefundableResourceFeeCharged + totalRefundableResourceFeeCharged` + // // where `resourceFeeCharged` is the overall fee charged for the + // // transaction. Also, `resourceFeeCharged` <= `sorobanData.resourceFee` + // // i.e.we never charge more than the declared resource fee. + // // The inclusion fee for charged the Soroban transaction can be found using + // // the following equation: + // // `result.feeCharged = resourceFeeCharged + inclusionFeeCharged`. + // + // // Total amount (in stroops) that has been charged for non-refundable + // // Soroban resources. + // // Non-refundable resources are charged based on the usage declared in + // // the transaction envelope (such as `instructions`, `readBytes` etc.) and + // // is charged regardless of the success of the transaction. + // int64 totalNonRefundableResourceFeeCharged; + // // Total amount (in stroops) that has been charged for refundable + // // Soroban resource fees. + // // Currently this comprises the rent fee (`rentFeeCharged`) and the + // // fee for the events and return value. + // // Refundable resources are charged based on the actual resources usage. + // // Since currently refundable resources are only used for the successful + // // transactions, this will be `0` for failed transactions. + // int64 totalRefundableResourceFeeCharged; + // // Amount (in stroops) that has been charged for rent. + // // This is a part of `totalNonRefundableResourceFeeCharged`. + // int64 rentFeeCharged; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionMetaExtV1", [["ext", xdr.lookup("ExtensionPoint")], ["totalNonRefundableResourceFeeCharged", xdr.lookup("Int64")], ["totalRefundableResourceFeeCharged", xdr.lookup("Int64")], ["rentFeeCharged", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union SorobanTransactionMetaExt switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionMetaExtV1 v1; + // }; + // + // =========================================================================== + xdr.union("SorobanTransactionMetaExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("SorobanTransactionMetaExtV1") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanTransactionMeta + // { + // SorobanTransactionMetaExt ext; + // + // ContractEvent events<>; // custom events populated by the + // // contracts themselves. + // SCVal returnValue; // return value of the host fn invocation + // + // // Diagnostics events that are not hashed. + // // This will contain all contract and diagnostic events. Even ones + // // that were emitted in a failed contract call. + // DiagnosticEvent diagnosticEvents<>; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionMeta", [["ext", xdr.lookup("SorobanTransactionMetaExt")], ["events", xdr.varArray(xdr.lookup("ContractEvent"), 2147483647)], ["returnValue", xdr.lookup("ScVal")], ["diagnosticEvents", xdr.varArray(xdr.lookup("DiagnosticEvent"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV3 + // { + // ExtensionPoint ext; + // + // LedgerEntryChanges txChangesBefore; // tx level changes before operations + // // are applied if any + // OperationMeta operations<>; // meta for each operation + // LedgerEntryChanges txChangesAfter; // tx level changes after operations are + // // applied if any + // SorobanTransactionMeta* sorobanMeta; // Soroban-specific meta (only for + // // Soroban transactions). + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV3", [["ext", xdr.lookup("ExtensionPoint")], ["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")], ["sorobanMeta", xdr.option(xdr.lookup("SorobanTransactionMeta"))]]); + + // === xdr source ============================================================ + // + // struct InvokeHostFunctionSuccessPreImage + // { + // SCVal returnValue; + // ContractEvent events<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeHostFunctionSuccessPreImage", [["returnValue", xdr.lookup("ScVal")], ["events", xdr.varArray(xdr.lookup("ContractEvent"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union TransactionMeta switch (int v) + // { + // case 0: + // OperationMeta operations<>; + // case 1: + // TransactionMetaV1 v1; + // case 2: + // TransactionMetaV2 v2; + // case 3: + // TransactionMetaV3 v3; + // }; + // + // =========================================================================== + xdr.union("TransactionMeta", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "operations"], [1, "v1"], [2, "v2"], [3, "v3"]], + arms: { + operations: xdr.varArray(xdr.lookup("OperationMeta"), 2147483647), + v1: xdr.lookup("TransactionMetaV1"), + v2: xdr.lookup("TransactionMetaV2"), + v3: xdr.lookup("TransactionMetaV3") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionResultMeta + // { + // TransactionResultPair result; + // LedgerEntryChanges feeProcessing; + // TransactionMeta txApplyProcessing; + // }; + // + // =========================================================================== + xdr.struct("TransactionResultMeta", [["result", xdr.lookup("TransactionResultPair")], ["feeProcessing", xdr.lookup("LedgerEntryChanges")], ["txApplyProcessing", xdr.lookup("TransactionMeta")]]); + + // === xdr source ============================================================ + // + // struct UpgradeEntryMeta + // { + // LedgerUpgrade upgrade; + // LedgerEntryChanges changes; + // }; + // + // =========================================================================== + xdr.struct("UpgradeEntryMeta", [["upgrade", xdr.lookup("LedgerUpgrade")], ["changes", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaV0 + // { + // LedgerHeaderHistoryEntry ledgerHeader; + // // NB: txSet is sorted in "Hash order" + // TransactionSet txSet; + // + // // NB: transactions are sorted in apply order here + // // fees for all transactions are processed first + // // followed by applying transactions + // TransactionResultMeta txProcessing<>; + // + // // upgrades are applied last + // UpgradeEntryMeta upgradesProcessing<>; + // + // // other misc information attached to the ledger close + // SCPHistoryEntry scpInfo<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaV0", [["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("TransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaExtV1 + // { + // ExtensionPoint ext; + // int64 sorobanFeeWrite1KB; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaExtV1", [["ext", xdr.lookup("ExtensionPoint")], ["sorobanFeeWrite1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union LedgerCloseMetaExt switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerCloseMetaExtV1 v1; + // }; + // + // =========================================================================== + xdr.union("LedgerCloseMetaExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerCloseMetaExtV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaV1 + // { + // LedgerCloseMetaExt ext; + // + // LedgerHeaderHistoryEntry ledgerHeader; + // + // GeneralizedTransactionSet txSet; + // + // // NB: transactions are sorted in apply order here + // // fees for all transactions are processed first + // // followed by applying transactions + // TransactionResultMeta txProcessing<>; + // + // // upgrades are applied last + // UpgradeEntryMeta upgradesProcessing<>; + // + // // other misc information attached to the ledger close + // SCPHistoryEntry scpInfo<>; + // + // // Size in bytes of BucketList, to support downstream + // // systems calculating storage fees correctly. + // uint64 totalByteSizeOfBucketList; + // + // // Temp keys that are being evicted at this ledger. + // LedgerKey evictedTemporaryLedgerKeys<>; + // + // // Archived restorable ledger entries that are being + // // evicted at this ledger. + // LedgerEntry evictedPersistentLedgerEntries<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaV1", [["ext", xdr.lookup("LedgerCloseMetaExt")], ["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("GeneralizedTransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)], ["totalByteSizeOfBucketList", xdr.lookup("Uint64")], ["evictedTemporaryLedgerKeys", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["evictedPersistentLedgerEntries", xdr.varArray(xdr.lookup("LedgerEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union LedgerCloseMeta switch (int v) + // { + // case 0: + // LedgerCloseMetaV0 v0; + // case 1: + // LedgerCloseMetaV1 v1; + // }; + // + // =========================================================================== + xdr.union("LedgerCloseMeta", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"], [1, "v1"]], + arms: { + v0: xdr.lookup("LedgerCloseMetaV0"), + v1: xdr.lookup("LedgerCloseMetaV1") + } + }); + + // === xdr source ============================================================ + // + // enum ErrorCode + // { + // ERR_MISC = 0, // Unspecific error + // ERR_DATA = 1, // Malformed data + // ERR_CONF = 2, // Misconfiguration error + // ERR_AUTH = 3, // Authentication failure + // ERR_LOAD = 4 // System overloaded + // }; + // + // =========================================================================== + xdr["enum"]("ErrorCode", { + errMisc: 0, + errData: 1, + errConf: 2, + errAuth: 3, + errLoad: 4 + }); + + // === xdr source ============================================================ + // + // struct Error + // { + // ErrorCode code; + // string msg<100>; + // }; + // + // =========================================================================== + xdr.struct("Error", [["code", xdr.lookup("ErrorCode")], ["msg", xdr.string(100)]]); + + // === xdr source ============================================================ + // + // struct SendMore + // { + // uint32 numMessages; + // }; + // + // =========================================================================== + xdr.struct("SendMore", [["numMessages", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SendMoreExtended + // { + // uint32 numMessages; + // uint32 numBytes; + // }; + // + // =========================================================================== + xdr.struct("SendMoreExtended", [["numMessages", xdr.lookup("Uint32")], ["numBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct AuthCert + // { + // Curve25519Public pubkey; + // uint64 expiration; + // Signature sig; + // }; + // + // =========================================================================== + xdr.struct("AuthCert", [["pubkey", xdr.lookup("Curve25519Public")], ["expiration", xdr.lookup("Uint64")], ["sig", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // struct Hello + // { + // uint32 ledgerVersion; + // uint32 overlayVersion; + // uint32 overlayMinVersion; + // Hash networkID; + // string versionStr<100>; + // int listeningPort; + // NodeID peerID; + // AuthCert cert; + // uint256 nonce; + // }; + // + // =========================================================================== + xdr.struct("Hello", [["ledgerVersion", xdr.lookup("Uint32")], ["overlayVersion", xdr.lookup("Uint32")], ["overlayMinVersion", xdr.lookup("Uint32")], ["networkId", xdr.lookup("Hash")], ["versionStr", xdr.string(100)], ["listeningPort", xdr["int"]()], ["peerId", xdr.lookup("NodeId")], ["cert", xdr.lookup("AuthCert")], ["nonce", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // const AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED = 200; + // + // =========================================================================== + xdr["const"]("AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED", 200); + + // === xdr source ============================================================ + // + // struct Auth + // { + // int flags; + // }; + // + // =========================================================================== + xdr.struct("Auth", [["flags", xdr["int"]()]]); + + // === xdr source ============================================================ + // + // enum IPAddrType + // { + // IPv4 = 0, + // IPv6 = 1 + // }; + // + // =========================================================================== + xdr["enum"]("IpAddrType", { + iPv4: 0, + iPv6: 1 + }); + + // === xdr source ============================================================ + // + // union switch (IPAddrType type) + // { + // case IPv4: + // opaque ipv4[4]; + // case IPv6: + // opaque ipv6[16]; + // } + // + // =========================================================================== + xdr.union("PeerAddressIp", { + switchOn: xdr.lookup("IpAddrType"), + switchName: "type", + switches: [["iPv4", "ipv4"], ["iPv6", "ipv6"]], + arms: { + ipv4: xdr.opaque(4), + ipv6: xdr.opaque(16) + } + }); + + // === xdr source ============================================================ + // + // struct PeerAddress + // { + // union switch (IPAddrType type) + // { + // case IPv4: + // opaque ipv4[4]; + // case IPv6: + // opaque ipv6[16]; + // } + // ip; + // uint32 port; + // uint32 numFailures; + // }; + // + // =========================================================================== + xdr.struct("PeerAddress", [["ip", xdr.lookup("PeerAddressIp")], ["port", xdr.lookup("Uint32")], ["numFailures", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // enum MessageType + // { + // ERROR_MSG = 0, + // AUTH = 2, + // DONT_HAVE = 3, + // + // GET_PEERS = 4, // gets a list of peers this guy knows about + // PEERS = 5, + // + // GET_TX_SET = 6, // gets a particular txset by hash + // TX_SET = 7, + // GENERALIZED_TX_SET = 17, + // + // TRANSACTION = 8, // pass on a tx you have heard about + // + // // SCP + // GET_SCP_QUORUMSET = 9, + // SCP_QUORUMSET = 10, + // SCP_MESSAGE = 11, + // GET_SCP_STATE = 12, + // + // // new messages + // HELLO = 13, + // + // SURVEY_REQUEST = 14, + // SURVEY_RESPONSE = 15, + // + // SEND_MORE = 16, + // SEND_MORE_EXTENDED = 20, + // + // FLOOD_ADVERT = 18, + // FLOOD_DEMAND = 19, + // + // TIME_SLICED_SURVEY_REQUEST = 21, + // TIME_SLICED_SURVEY_RESPONSE = 22, + // TIME_SLICED_SURVEY_START_COLLECTING = 23, + // TIME_SLICED_SURVEY_STOP_COLLECTING = 24 + // }; + // + // =========================================================================== + xdr["enum"]("MessageType", { + errorMsg: 0, + auth: 2, + dontHave: 3, + getPeers: 4, + peers: 5, + getTxSet: 6, + txSet: 7, + generalizedTxSet: 17, + transaction: 8, + getScpQuorumset: 9, + scpQuorumset: 10, + scpMessage: 11, + getScpState: 12, + hello: 13, + surveyRequest: 14, + surveyResponse: 15, + sendMore: 16, + sendMoreExtended: 20, + floodAdvert: 18, + floodDemand: 19, + timeSlicedSurveyRequest: 21, + timeSlicedSurveyResponse: 22, + timeSlicedSurveyStartCollecting: 23, + timeSlicedSurveyStopCollecting: 24 + }); + + // === xdr source ============================================================ + // + // struct DontHave + // { + // MessageType type; + // uint256 reqHash; + // }; + // + // =========================================================================== + xdr.struct("DontHave", [["type", xdr.lookup("MessageType")], ["reqHash", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // enum SurveyMessageCommandType + // { + // SURVEY_TOPOLOGY = 0, + // TIME_SLICED_SURVEY_TOPOLOGY = 1 + // }; + // + // =========================================================================== + xdr["enum"]("SurveyMessageCommandType", { + surveyTopology: 0, + timeSlicedSurveyTopology: 1 + }); + + // === xdr source ============================================================ + // + // enum SurveyMessageResponseType + // { + // SURVEY_TOPOLOGY_RESPONSE_V0 = 0, + // SURVEY_TOPOLOGY_RESPONSE_V1 = 1, + // SURVEY_TOPOLOGY_RESPONSE_V2 = 2 + // }; + // + // =========================================================================== + xdr["enum"]("SurveyMessageResponseType", { + surveyTopologyResponseV0: 0, + surveyTopologyResponseV1: 1, + surveyTopologyResponseV2: 2 + }); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyStartCollectingMessage + // { + // NodeID surveyorID; + // uint32 nonce; + // uint32 ledgerNum; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyStartCollectingMessage", [["surveyorId", xdr.lookup("NodeId")], ["nonce", xdr.lookup("Uint32")], ["ledgerNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyStartCollectingMessage + // { + // Signature signature; + // TimeSlicedSurveyStartCollectingMessage startCollecting; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyStartCollectingMessage", [["signature", xdr.lookup("Signature")], ["startCollecting", xdr.lookup("TimeSlicedSurveyStartCollectingMessage")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyStopCollectingMessage + // { + // NodeID surveyorID; + // uint32 nonce; + // uint32 ledgerNum; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyStopCollectingMessage", [["surveyorId", xdr.lookup("NodeId")], ["nonce", xdr.lookup("Uint32")], ["ledgerNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyStopCollectingMessage + // { + // Signature signature; + // TimeSlicedSurveyStopCollectingMessage stopCollecting; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyStopCollectingMessage", [["signature", xdr.lookup("Signature")], ["stopCollecting", xdr.lookup("TimeSlicedSurveyStopCollectingMessage")]]); + + // === xdr source ============================================================ + // + // struct SurveyRequestMessage + // { + // NodeID surveyorPeerID; + // NodeID surveyedPeerID; + // uint32 ledgerNum; + // Curve25519Public encryptionKey; + // SurveyMessageCommandType commandType; + // }; + // + // =========================================================================== + xdr.struct("SurveyRequestMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["encryptionKey", xdr.lookup("Curve25519Public")], ["commandType", xdr.lookup("SurveyMessageCommandType")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyRequestMessage + // { + // SurveyRequestMessage request; + // uint32 nonce; + // uint32 inboundPeersIndex; + // uint32 outboundPeersIndex; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyRequestMessage", [["request", xdr.lookup("SurveyRequestMessage")], ["nonce", xdr.lookup("Uint32")], ["inboundPeersIndex", xdr.lookup("Uint32")], ["outboundPeersIndex", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedSurveyRequestMessage + // { + // Signature requestSignature; + // SurveyRequestMessage request; + // }; + // + // =========================================================================== + xdr.struct("SignedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("SurveyRequestMessage")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyRequestMessage + // { + // Signature requestSignature; + // TimeSlicedSurveyRequestMessage request; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("TimeSlicedSurveyRequestMessage")]]); + + // === xdr source ============================================================ + // + // typedef opaque EncryptedBody<64000>; + // + // =========================================================================== + xdr.typedef("EncryptedBody", xdr.varOpaque(64000)); + + // === xdr source ============================================================ + // + // struct SurveyResponseMessage + // { + // NodeID surveyorPeerID; + // NodeID surveyedPeerID; + // uint32 ledgerNum; + // SurveyMessageCommandType commandType; + // EncryptedBody encryptedBody; + // }; + // + // =========================================================================== + xdr.struct("SurveyResponseMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["commandType", xdr.lookup("SurveyMessageCommandType")], ["encryptedBody", xdr.lookup("EncryptedBody")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyResponseMessage + // { + // SurveyResponseMessage response; + // uint32 nonce; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyResponseMessage", [["response", xdr.lookup("SurveyResponseMessage")], ["nonce", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedSurveyResponseMessage + // { + // Signature responseSignature; + // SurveyResponseMessage response; + // }; + // + // =========================================================================== + xdr.struct("SignedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("SurveyResponseMessage")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyResponseMessage + // { + // Signature responseSignature; + // TimeSlicedSurveyResponseMessage response; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("TimeSlicedSurveyResponseMessage")]]); + + // === xdr source ============================================================ + // + // struct PeerStats + // { + // NodeID id; + // string versionStr<100>; + // uint64 messagesRead; + // uint64 messagesWritten; + // uint64 bytesRead; + // uint64 bytesWritten; + // uint64 secondsConnected; + // + // uint64 uniqueFloodBytesRecv; + // uint64 duplicateFloodBytesRecv; + // uint64 uniqueFetchBytesRecv; + // uint64 duplicateFetchBytesRecv; + // + // uint64 uniqueFloodMessageRecv; + // uint64 duplicateFloodMessageRecv; + // uint64 uniqueFetchMessageRecv; + // uint64 duplicateFetchMessageRecv; + // }; + // + // =========================================================================== + xdr.struct("PeerStats", [["id", xdr.lookup("NodeId")], ["versionStr", xdr.string(100)], ["messagesRead", xdr.lookup("Uint64")], ["messagesWritten", xdr.lookup("Uint64")], ["bytesRead", xdr.lookup("Uint64")], ["bytesWritten", xdr.lookup("Uint64")], ["secondsConnected", xdr.lookup("Uint64")], ["uniqueFloodBytesRecv", xdr.lookup("Uint64")], ["duplicateFloodBytesRecv", xdr.lookup("Uint64")], ["uniqueFetchBytesRecv", xdr.lookup("Uint64")], ["duplicateFetchBytesRecv", xdr.lookup("Uint64")], ["uniqueFloodMessageRecv", xdr.lookup("Uint64")], ["duplicateFloodMessageRecv", xdr.lookup("Uint64")], ["uniqueFetchMessageRecv", xdr.lookup("Uint64")], ["duplicateFetchMessageRecv", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // typedef PeerStats PeerStatList<25>; + // + // =========================================================================== + xdr.typedef("PeerStatList", xdr.varArray(xdr.lookup("PeerStats"), 25)); + + // === xdr source ============================================================ + // + // struct TimeSlicedNodeData + // { + // uint32 addedAuthenticatedPeers; + // uint32 droppedAuthenticatedPeers; + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // + // // SCP stats + // uint32 p75SCPFirstToSelfLatencyMs; + // uint32 p75SCPSelfToOtherLatencyMs; + // + // // How many times the node lost sync in the time slice + // uint32 lostSyncCount; + // + // // Config data + // bool isValidator; + // uint32 maxInboundPeerCount; + // uint32 maxOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedNodeData", [["addedAuthenticatedPeers", xdr.lookup("Uint32")], ["droppedAuthenticatedPeers", xdr.lookup("Uint32")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")], ["p75ScpFirstToSelfLatencyMs", xdr.lookup("Uint32")], ["p75ScpSelfToOtherLatencyMs", xdr.lookup("Uint32")], ["lostSyncCount", xdr.lookup("Uint32")], ["isValidator", xdr.bool()], ["maxInboundPeerCount", xdr.lookup("Uint32")], ["maxOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedPeerData + // { + // PeerStats peerStats; + // uint32 averageLatencyMs; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedPeerData", [["peerStats", xdr.lookup("PeerStats")], ["averageLatencyMs", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // typedef TimeSlicedPeerData TimeSlicedPeerDataList<25>; + // + // =========================================================================== + xdr.typedef("TimeSlicedPeerDataList", xdr.varArray(xdr.lookup("TimeSlicedPeerData"), 25)); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV0 + // { + // PeerStatList inboundPeers; + // PeerStatList outboundPeers; + // + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV0", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV1 + // { + // PeerStatList inboundPeers; + // PeerStatList outboundPeers; + // + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // + // uint32 maxInboundPeerCount; + // uint32 maxOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV1", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")], ["maxInboundPeerCount", xdr.lookup("Uint32")], ["maxOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV2 + // { + // TimeSlicedPeerDataList inboundPeers; + // TimeSlicedPeerDataList outboundPeers; + // TimeSlicedNodeData nodeData; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV2", [["inboundPeers", xdr.lookup("TimeSlicedPeerDataList")], ["outboundPeers", xdr.lookup("TimeSlicedPeerDataList")], ["nodeData", xdr.lookup("TimeSlicedNodeData")]]); + + // === xdr source ============================================================ + // + // union SurveyResponseBody switch (SurveyMessageResponseType type) + // { + // case SURVEY_TOPOLOGY_RESPONSE_V0: + // TopologyResponseBodyV0 topologyResponseBodyV0; + // case SURVEY_TOPOLOGY_RESPONSE_V1: + // TopologyResponseBodyV1 topologyResponseBodyV1; + // case SURVEY_TOPOLOGY_RESPONSE_V2: + // TopologyResponseBodyV2 topologyResponseBodyV2; + // }; + // + // =========================================================================== + xdr.union("SurveyResponseBody", { + switchOn: xdr.lookup("SurveyMessageResponseType"), + switchName: "type", + switches: [["surveyTopologyResponseV0", "topologyResponseBodyV0"], ["surveyTopologyResponseV1", "topologyResponseBodyV1"], ["surveyTopologyResponseV2", "topologyResponseBodyV2"]], + arms: { + topologyResponseBodyV0: xdr.lookup("TopologyResponseBodyV0"), + topologyResponseBodyV1: xdr.lookup("TopologyResponseBodyV1"), + topologyResponseBodyV2: xdr.lookup("TopologyResponseBodyV2") + } + }); + + // === xdr source ============================================================ + // + // const TX_ADVERT_VECTOR_MAX_SIZE = 1000; + // + // =========================================================================== + xdr["const"]("TX_ADVERT_VECTOR_MAX_SIZE", 1000); + + // === xdr source ============================================================ + // + // typedef Hash TxAdvertVector; + // + // =========================================================================== + xdr.typedef("TxAdvertVector", xdr.varArray(xdr.lookup("Hash"), xdr.lookup("TX_ADVERT_VECTOR_MAX_SIZE"))); + + // === xdr source ============================================================ + // + // struct FloodAdvert + // { + // TxAdvertVector txHashes; + // }; + // + // =========================================================================== + xdr.struct("FloodAdvert", [["txHashes", xdr.lookup("TxAdvertVector")]]); + + // === xdr source ============================================================ + // + // const TX_DEMAND_VECTOR_MAX_SIZE = 1000; + // + // =========================================================================== + xdr["const"]("TX_DEMAND_VECTOR_MAX_SIZE", 1000); + + // === xdr source ============================================================ + // + // typedef Hash TxDemandVector; + // + // =========================================================================== + xdr.typedef("TxDemandVector", xdr.varArray(xdr.lookup("Hash"), xdr.lookup("TX_DEMAND_VECTOR_MAX_SIZE"))); + + // === xdr source ============================================================ + // + // struct FloodDemand + // { + // TxDemandVector txHashes; + // }; + // + // =========================================================================== + xdr.struct("FloodDemand", [["txHashes", xdr.lookup("TxDemandVector")]]); + + // === xdr source ============================================================ + // + // union StellarMessage switch (MessageType type) + // { + // case ERROR_MSG: + // Error error; + // case HELLO: + // Hello hello; + // case AUTH: + // Auth auth; + // case DONT_HAVE: + // DontHave dontHave; + // case GET_PEERS: + // void; + // case PEERS: + // PeerAddress peers<100>; + // + // case GET_TX_SET: + // uint256 txSetHash; + // case TX_SET: + // TransactionSet txSet; + // case GENERALIZED_TX_SET: + // GeneralizedTransactionSet generalizedTxSet; + // + // case TRANSACTION: + // TransactionEnvelope transaction; + // + // case SURVEY_REQUEST: + // SignedSurveyRequestMessage signedSurveyRequestMessage; + // + // case SURVEY_RESPONSE: + // SignedSurveyResponseMessage signedSurveyResponseMessage; + // + // case TIME_SLICED_SURVEY_REQUEST: + // SignedTimeSlicedSurveyRequestMessage signedTimeSlicedSurveyRequestMessage; + // + // case TIME_SLICED_SURVEY_RESPONSE: + // SignedTimeSlicedSurveyResponseMessage signedTimeSlicedSurveyResponseMessage; + // + // case TIME_SLICED_SURVEY_START_COLLECTING: + // SignedTimeSlicedSurveyStartCollectingMessage + // signedTimeSlicedSurveyStartCollectingMessage; + // + // case TIME_SLICED_SURVEY_STOP_COLLECTING: + // SignedTimeSlicedSurveyStopCollectingMessage + // signedTimeSlicedSurveyStopCollectingMessage; + // + // // SCP + // case GET_SCP_QUORUMSET: + // uint256 qSetHash; + // case SCP_QUORUMSET: + // SCPQuorumSet qSet; + // case SCP_MESSAGE: + // SCPEnvelope envelope; + // case GET_SCP_STATE: + // uint32 getSCPLedgerSeq; // ledger seq requested ; if 0, requests the latest + // case SEND_MORE: + // SendMore sendMoreMessage; + // case SEND_MORE_EXTENDED: + // SendMoreExtended sendMoreExtendedMessage; + // // Pull mode + // case FLOOD_ADVERT: + // FloodAdvert floodAdvert; + // case FLOOD_DEMAND: + // FloodDemand floodDemand; + // }; + // + // =========================================================================== + xdr.union("StellarMessage", { + switchOn: xdr.lookup("MessageType"), + switchName: "type", + switches: [["errorMsg", "error"], ["hello", "hello"], ["auth", "auth"], ["dontHave", "dontHave"], ["getPeers", xdr["void"]()], ["peers", "peers"], ["getTxSet", "txSetHash"], ["txSet", "txSet"], ["generalizedTxSet", "generalizedTxSet"], ["transaction", "transaction"], ["surveyRequest", "signedSurveyRequestMessage"], ["surveyResponse", "signedSurveyResponseMessage"], ["timeSlicedSurveyRequest", "signedTimeSlicedSurveyRequestMessage"], ["timeSlicedSurveyResponse", "signedTimeSlicedSurveyResponseMessage"], ["timeSlicedSurveyStartCollecting", "signedTimeSlicedSurveyStartCollectingMessage"], ["timeSlicedSurveyStopCollecting", "signedTimeSlicedSurveyStopCollectingMessage"], ["getScpQuorumset", "qSetHash"], ["scpQuorumset", "qSet"], ["scpMessage", "envelope"], ["getScpState", "getScpLedgerSeq"], ["sendMore", "sendMoreMessage"], ["sendMoreExtended", "sendMoreExtendedMessage"], ["floodAdvert", "floodAdvert"], ["floodDemand", "floodDemand"]], + arms: { + error: xdr.lookup("Error"), + hello: xdr.lookup("Hello"), + auth: xdr.lookup("Auth"), + dontHave: xdr.lookup("DontHave"), + peers: xdr.varArray(xdr.lookup("PeerAddress"), 100), + txSetHash: xdr.lookup("Uint256"), + txSet: xdr.lookup("TransactionSet"), + generalizedTxSet: xdr.lookup("GeneralizedTransactionSet"), + transaction: xdr.lookup("TransactionEnvelope"), + signedSurveyRequestMessage: xdr.lookup("SignedSurveyRequestMessage"), + signedSurveyResponseMessage: xdr.lookup("SignedSurveyResponseMessage"), + signedTimeSlicedSurveyRequestMessage: xdr.lookup("SignedTimeSlicedSurveyRequestMessage"), + signedTimeSlicedSurveyResponseMessage: xdr.lookup("SignedTimeSlicedSurveyResponseMessage"), + signedTimeSlicedSurveyStartCollectingMessage: xdr.lookup("SignedTimeSlicedSurveyStartCollectingMessage"), + signedTimeSlicedSurveyStopCollectingMessage: xdr.lookup("SignedTimeSlicedSurveyStopCollectingMessage"), + qSetHash: xdr.lookup("Uint256"), + qSet: xdr.lookup("ScpQuorumSet"), + envelope: xdr.lookup("ScpEnvelope"), + getScpLedgerSeq: xdr.lookup("Uint32"), + sendMoreMessage: xdr.lookup("SendMore"), + sendMoreExtendedMessage: xdr.lookup("SendMoreExtended"), + floodAdvert: xdr.lookup("FloodAdvert"), + floodDemand: xdr.lookup("FloodDemand") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // uint64 sequence; + // StellarMessage message; + // HmacSha256Mac mac; + // } + // + // =========================================================================== + xdr.struct("AuthenticatedMessageV0", [["sequence", xdr.lookup("Uint64")], ["message", xdr.lookup("StellarMessage")], ["mac", xdr.lookup("HmacSha256Mac")]]); + + // === xdr source ============================================================ + // + // union AuthenticatedMessage switch (uint32 v) + // { + // case 0: + // struct + // { + // uint64 sequence; + // StellarMessage message; + // HmacSha256Mac mac; + // } v0; + // }; + // + // =========================================================================== + xdr.union("AuthenticatedMessage", { + switchOn: xdr.lookup("Uint32"), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("AuthenticatedMessageV0") + } + }); + + // === xdr source ============================================================ + // + // const MAX_OPS_PER_TX = 100; + // + // =========================================================================== + xdr["const"]("MAX_OPS_PER_TX", 100); + + // === xdr source ============================================================ + // + // union LiquidityPoolParameters switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // LiquidityPoolConstantProductParameters constantProduct; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolParameters", { + switchOn: xdr.lookup("LiquidityPoolType"), + switchName: "type", + switches: [["liquidityPoolConstantProduct", "constantProduct"]], + arms: { + constantProduct: xdr.lookup("LiquidityPoolConstantProductParameters") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // uint64 id; + // uint256 ed25519; + // } + // + // =========================================================================== + xdr.struct("MuxedAccountMed25519", [["id", xdr.lookup("Uint64")], ["ed25519", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // union MuxedAccount switch (CryptoKeyType type) + // { + // case KEY_TYPE_ED25519: + // uint256 ed25519; + // case KEY_TYPE_MUXED_ED25519: + // struct + // { + // uint64 id; + // uint256 ed25519; + // } med25519; + // }; + // + // =========================================================================== + xdr.union("MuxedAccount", { + switchOn: xdr.lookup("CryptoKeyType"), + switchName: "type", + switches: [["keyTypeEd25519", "ed25519"], ["keyTypeMuxedEd25519", "med25519"]], + arms: { + ed25519: xdr.lookup("Uint256"), + med25519: xdr.lookup("MuxedAccountMed25519") + } + }); + + // === xdr source ============================================================ + // + // struct DecoratedSignature + // { + // SignatureHint hint; // last 4 bytes of the public key, used as a hint + // Signature signature; // actual signature + // }; + // + // =========================================================================== + xdr.struct("DecoratedSignature", [["hint", xdr.lookup("SignatureHint")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // enum OperationType + // { + // CREATE_ACCOUNT = 0, + // PAYMENT = 1, + // PATH_PAYMENT_STRICT_RECEIVE = 2, + // MANAGE_SELL_OFFER = 3, + // CREATE_PASSIVE_SELL_OFFER = 4, + // SET_OPTIONS = 5, + // CHANGE_TRUST = 6, + // ALLOW_TRUST = 7, + // ACCOUNT_MERGE = 8, + // INFLATION = 9, + // MANAGE_DATA = 10, + // BUMP_SEQUENCE = 11, + // MANAGE_BUY_OFFER = 12, + // PATH_PAYMENT_STRICT_SEND = 13, + // CREATE_CLAIMABLE_BALANCE = 14, + // CLAIM_CLAIMABLE_BALANCE = 15, + // BEGIN_SPONSORING_FUTURE_RESERVES = 16, + // END_SPONSORING_FUTURE_RESERVES = 17, + // REVOKE_SPONSORSHIP = 18, + // CLAWBACK = 19, + // CLAWBACK_CLAIMABLE_BALANCE = 20, + // SET_TRUST_LINE_FLAGS = 21, + // LIQUIDITY_POOL_DEPOSIT = 22, + // LIQUIDITY_POOL_WITHDRAW = 23, + // INVOKE_HOST_FUNCTION = 24, + // EXTEND_FOOTPRINT_TTL = 25, + // RESTORE_FOOTPRINT = 26 + // }; + // + // =========================================================================== + xdr["enum"]("OperationType", { + createAccount: 0, + payment: 1, + pathPaymentStrictReceive: 2, + manageSellOffer: 3, + createPassiveSellOffer: 4, + setOptions: 5, + changeTrust: 6, + allowTrust: 7, + accountMerge: 8, + inflation: 9, + manageData: 10, + bumpSequence: 11, + manageBuyOffer: 12, + pathPaymentStrictSend: 13, + createClaimableBalance: 14, + claimClaimableBalance: 15, + beginSponsoringFutureReserves: 16, + endSponsoringFutureReserves: 17, + revokeSponsorship: 18, + clawback: 19, + clawbackClaimableBalance: 20, + setTrustLineFlags: 21, + liquidityPoolDeposit: 22, + liquidityPoolWithdraw: 23, + invokeHostFunction: 24, + extendFootprintTtl: 25, + restoreFootprint: 26 + }); + + // === xdr source ============================================================ + // + // struct CreateAccountOp + // { + // AccountID destination; // account to create + // int64 startingBalance; // amount they end up with + // }; + // + // =========================================================================== + xdr.struct("CreateAccountOp", [["destination", xdr.lookup("AccountId")], ["startingBalance", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct PaymentOp + // { + // MuxedAccount destination; // recipient of the payment + // Asset asset; // what they end up with + // int64 amount; // amount they end up with + // }; + // + // =========================================================================== + xdr.struct("PaymentOp", [["destination", xdr.lookup("MuxedAccount")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct PathPaymentStrictReceiveOp + // { + // Asset sendAsset; // asset we pay with + // int64 sendMax; // the maximum amount of sendAsset to + // // send (excluding fees). + // // The operation will fail if can't be met + // + // MuxedAccount destination; // recipient of the payment + // Asset destAsset; // what they end up with + // int64 destAmount; // amount they end up with + // + // Asset path<5>; // additional hops it must go through to get there + // }; + // + // =========================================================================== + xdr.struct("PathPaymentStrictReceiveOp", [["sendAsset", xdr.lookup("Asset")], ["sendMax", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destAmount", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]); + + // === xdr source ============================================================ + // + // struct PathPaymentStrictSendOp + // { + // Asset sendAsset; // asset we pay with + // int64 sendAmount; // amount of sendAsset to send (excluding fees) + // + // MuxedAccount destination; // recipient of the payment + // Asset destAsset; // what they end up with + // int64 destMin; // the minimum amount of dest asset to + // // be received + // // The operation will fail if it can't be met + // + // Asset path<5>; // additional hops it must go through to get there + // }; + // + // =========================================================================== + xdr.struct("PathPaymentStrictSendOp", [["sendAsset", xdr.lookup("Asset")], ["sendAmount", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destMin", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]); + + // === xdr source ============================================================ + // + // struct ManageSellOfferOp + // { + // Asset selling; + // Asset buying; + // int64 amount; // amount being sold. if set to 0, delete the offer + // Price price; // price of thing being sold in terms of what you are buying + // + // // 0=create a new offer, otherwise edit an existing offer + // int64 offerID; + // }; + // + // =========================================================================== + xdr.struct("ManageSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ManageBuyOfferOp + // { + // Asset selling; + // Asset buying; + // int64 buyAmount; // amount being bought. if set to 0, delete the offer + // Price price; // price of thing being bought in terms of what you are + // // selling + // + // // 0=create a new offer, otherwise edit an existing offer + // int64 offerID; + // }; + // + // =========================================================================== + xdr.struct("ManageBuyOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["buyAmount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct CreatePassiveSellOfferOp + // { + // Asset selling; // A + // Asset buying; // B + // int64 amount; // amount taker gets + // Price price; // cost of A in terms of B + // }; + // + // =========================================================================== + xdr.struct("CreatePassiveSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")]]); + + // === xdr source ============================================================ + // + // struct SetOptionsOp + // { + // AccountID* inflationDest; // sets the inflation destination + // + // uint32* clearFlags; // which flags to clear + // uint32* setFlags; // which flags to set + // + // // account threshold manipulation + // uint32* masterWeight; // weight of the master account + // uint32* lowThreshold; + // uint32* medThreshold; + // uint32* highThreshold; + // + // string32* homeDomain; // sets the home domain + // + // // Add, update or remove a signer for the account + // // signer is deleted if the weight is 0 + // Signer* signer; + // }; + // + // =========================================================================== + xdr.struct("SetOptionsOp", [["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["clearFlags", xdr.option(xdr.lookup("Uint32"))], ["setFlags", xdr.option(xdr.lookup("Uint32"))], ["masterWeight", xdr.option(xdr.lookup("Uint32"))], ["lowThreshold", xdr.option(xdr.lookup("Uint32"))], ["medThreshold", xdr.option(xdr.lookup("Uint32"))], ["highThreshold", xdr.option(xdr.lookup("Uint32"))], ["homeDomain", xdr.option(xdr.lookup("String32"))], ["signer", xdr.option(xdr.lookup("Signer"))]]); + + // === xdr source ============================================================ + // + // union ChangeTrustAsset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // case ASSET_TYPE_POOL_SHARE: + // LiquidityPoolParameters liquidityPool; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("ChangeTrustAsset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPool"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12"), + liquidityPool: xdr.lookup("LiquidityPoolParameters") + } + }); + + // === xdr source ============================================================ + // + // struct ChangeTrustOp + // { + // ChangeTrustAsset line; + // + // // if limit is set to 0, deletes the trust line + // int64 limit; + // }; + // + // =========================================================================== + xdr.struct("ChangeTrustOp", [["line", xdr.lookup("ChangeTrustAsset")], ["limit", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct AllowTrustOp + // { + // AccountID trustor; + // AssetCode asset; + // + // // One of 0, AUTHORIZED_FLAG, or AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG + // uint32 authorize; + // }; + // + // =========================================================================== + xdr.struct("AllowTrustOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("AssetCode")], ["authorize", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ManageDataOp + // { + // string64 dataName; + // DataValue* dataValue; // set to null to clear + // }; + // + // =========================================================================== + xdr.struct("ManageDataOp", [["dataName", xdr.lookup("String64")], ["dataValue", xdr.option(xdr.lookup("DataValue"))]]); + + // === xdr source ============================================================ + // + // struct BumpSequenceOp + // { + // SequenceNumber bumpTo; + // }; + // + // =========================================================================== + xdr.struct("BumpSequenceOp", [["bumpTo", xdr.lookup("SequenceNumber")]]); + + // === xdr source ============================================================ + // + // struct CreateClaimableBalanceOp + // { + // Asset asset; + // int64 amount; + // Claimant claimants<10>; + // }; + // + // =========================================================================== + xdr.struct("CreateClaimableBalanceOp", [["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)]]); + + // === xdr source ============================================================ + // + // struct ClaimClaimableBalanceOp + // { + // ClaimableBalanceID balanceID; + // }; + // + // =========================================================================== + xdr.struct("ClaimClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct BeginSponsoringFutureReservesOp + // { + // AccountID sponsoredID; + // }; + // + // =========================================================================== + xdr.struct("BeginSponsoringFutureReservesOp", [["sponsoredId", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // enum RevokeSponsorshipType + // { + // REVOKE_SPONSORSHIP_LEDGER_ENTRY = 0, + // REVOKE_SPONSORSHIP_SIGNER = 1 + // }; + // + // =========================================================================== + xdr["enum"]("RevokeSponsorshipType", { + revokeSponsorshipLedgerEntry: 0, + revokeSponsorshipSigner: 1 + }); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // SignerKey signerKey; + // } + // + // =========================================================================== + xdr.struct("RevokeSponsorshipOpSigner", [["accountId", xdr.lookup("AccountId")], ["signerKey", xdr.lookup("SignerKey")]]); + + // === xdr source ============================================================ + // + // union RevokeSponsorshipOp switch (RevokeSponsorshipType type) + // { + // case REVOKE_SPONSORSHIP_LEDGER_ENTRY: + // LedgerKey ledgerKey; + // case REVOKE_SPONSORSHIP_SIGNER: + // struct + // { + // AccountID accountID; + // SignerKey signerKey; + // } signer; + // }; + // + // =========================================================================== + xdr.union("RevokeSponsorshipOp", { + switchOn: xdr.lookup("RevokeSponsorshipType"), + switchName: "type", + switches: [["revokeSponsorshipLedgerEntry", "ledgerKey"], ["revokeSponsorshipSigner", "signer"]], + arms: { + ledgerKey: xdr.lookup("LedgerKey"), + signer: xdr.lookup("RevokeSponsorshipOpSigner") + } + }); + + // === xdr source ============================================================ + // + // struct ClawbackOp + // { + // Asset asset; + // MuxedAccount from; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("ClawbackOp", [["asset", xdr.lookup("Asset")], ["from", xdr.lookup("MuxedAccount")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClawbackClaimableBalanceOp + // { + // ClaimableBalanceID balanceID; + // }; + // + // =========================================================================== + xdr.struct("ClawbackClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct SetTrustLineFlagsOp + // { + // AccountID trustor; + // Asset asset; + // + // uint32 clearFlags; // which flags to clear + // uint32 setFlags; // which flags to set + // }; + // + // =========================================================================== + xdr.struct("SetTrustLineFlagsOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["clearFlags", xdr.lookup("Uint32")], ["setFlags", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // const LIQUIDITY_POOL_FEE_V18 = 30; + // + // =========================================================================== + xdr["const"]("LIQUIDITY_POOL_FEE_V18", 30); + + // === xdr source ============================================================ + // + // struct LiquidityPoolDepositOp + // { + // PoolID liquidityPoolID; + // int64 maxAmountA; // maximum amount of first asset to deposit + // int64 maxAmountB; // maximum amount of second asset to deposit + // Price minPrice; // minimum depositA/depositB + // Price maxPrice; // maximum depositA/depositB + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolDepositOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["maxAmountA", xdr.lookup("Int64")], ["maxAmountB", xdr.lookup("Int64")], ["minPrice", xdr.lookup("Price")], ["maxPrice", xdr.lookup("Price")]]); + + // === xdr source ============================================================ + // + // struct LiquidityPoolWithdrawOp + // { + // PoolID liquidityPoolID; + // int64 amount; // amount of pool shares to withdraw + // int64 minAmountA; // minimum amount of first asset to withdraw + // int64 minAmountB; // minimum amount of second asset to withdraw + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolWithdrawOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["amount", xdr.lookup("Int64")], ["minAmountA", xdr.lookup("Int64")], ["minAmountB", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum HostFunctionType + // { + // HOST_FUNCTION_TYPE_INVOKE_CONTRACT = 0, + // HOST_FUNCTION_TYPE_CREATE_CONTRACT = 1, + // HOST_FUNCTION_TYPE_UPLOAD_CONTRACT_WASM = 2, + // HOST_FUNCTION_TYPE_CREATE_CONTRACT_V2 = 3 + // }; + // + // =========================================================================== + xdr["enum"]("HostFunctionType", { + hostFunctionTypeInvokeContract: 0, + hostFunctionTypeCreateContract: 1, + hostFunctionTypeUploadContractWasm: 2, + hostFunctionTypeCreateContractV2: 3 + }); + + // === xdr source ============================================================ + // + // enum ContractIDPreimageType + // { + // CONTRACT_ID_PREIMAGE_FROM_ADDRESS = 0, + // CONTRACT_ID_PREIMAGE_FROM_ASSET = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractIdPreimageType", { + contractIdPreimageFromAddress: 0, + contractIdPreimageFromAsset: 1 + }); + + // === xdr source ============================================================ + // + // struct + // { + // SCAddress address; + // uint256 salt; + // } + // + // =========================================================================== + xdr.struct("ContractIdPreimageFromAddress", [["address", xdr.lookup("ScAddress")], ["salt", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // union ContractIDPreimage switch (ContractIDPreimageType type) + // { + // case CONTRACT_ID_PREIMAGE_FROM_ADDRESS: + // struct + // { + // SCAddress address; + // uint256 salt; + // } fromAddress; + // case CONTRACT_ID_PREIMAGE_FROM_ASSET: + // Asset fromAsset; + // }; + // + // =========================================================================== + xdr.union("ContractIdPreimage", { + switchOn: xdr.lookup("ContractIdPreimageType"), + switchName: "type", + switches: [["contractIdPreimageFromAddress", "fromAddress"], ["contractIdPreimageFromAsset", "fromAsset"]], + arms: { + fromAddress: xdr.lookup("ContractIdPreimageFromAddress"), + fromAsset: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // struct CreateContractArgs + // { + // ContractIDPreimage contractIDPreimage; + // ContractExecutable executable; + // }; + // + // =========================================================================== + xdr.struct("CreateContractArgs", [["contractIdPreimage", xdr.lookup("ContractIdPreimage")], ["executable", xdr.lookup("ContractExecutable")]]); + + // === xdr source ============================================================ + // + // struct CreateContractArgsV2 + // { + // ContractIDPreimage contractIDPreimage; + // ContractExecutable executable; + // // Arguments of the contract's constructor. + // SCVal constructorArgs<>; + // }; + // + // =========================================================================== + xdr.struct("CreateContractArgsV2", [["contractIdPreimage", xdr.lookup("ContractIdPreimage")], ["executable", xdr.lookup("ContractExecutable")], ["constructorArgs", xdr.varArray(xdr.lookup("ScVal"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct InvokeContractArgs { + // SCAddress contractAddress; + // SCSymbol functionName; + // SCVal args<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeContractArgs", [["contractAddress", xdr.lookup("ScAddress")], ["functionName", xdr.lookup("ScSymbol")], ["args", xdr.varArray(xdr.lookup("ScVal"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union HostFunction switch (HostFunctionType type) + // { + // case HOST_FUNCTION_TYPE_INVOKE_CONTRACT: + // InvokeContractArgs invokeContract; + // case HOST_FUNCTION_TYPE_CREATE_CONTRACT: + // CreateContractArgs createContract; + // case HOST_FUNCTION_TYPE_UPLOAD_CONTRACT_WASM: + // opaque wasm<>; + // case HOST_FUNCTION_TYPE_CREATE_CONTRACT_V2: + // CreateContractArgsV2 createContractV2; + // }; + // + // =========================================================================== + xdr.union("HostFunction", { + switchOn: xdr.lookup("HostFunctionType"), + switchName: "type", + switches: [["hostFunctionTypeInvokeContract", "invokeContract"], ["hostFunctionTypeCreateContract", "createContract"], ["hostFunctionTypeUploadContractWasm", "wasm"], ["hostFunctionTypeCreateContractV2", "createContractV2"]], + arms: { + invokeContract: xdr.lookup("InvokeContractArgs"), + createContract: xdr.lookup("CreateContractArgs"), + wasm: xdr.varOpaque(), + createContractV2: xdr.lookup("CreateContractArgsV2") + } + }); + + // === xdr source ============================================================ + // + // enum SorobanAuthorizedFunctionType + // { + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN = 0, + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_HOST_FN = 1, + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN = 2 + // }; + // + // =========================================================================== + xdr["enum"]("SorobanAuthorizedFunctionType", { + sorobanAuthorizedFunctionTypeContractFn: 0, + sorobanAuthorizedFunctionTypeCreateContractHostFn: 1, + sorobanAuthorizedFunctionTypeCreateContractV2HostFn: 2 + }); + + // === xdr source ============================================================ + // + // union SorobanAuthorizedFunction switch (SorobanAuthorizedFunctionType type) + // { + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN: + // InvokeContractArgs contractFn; + // // This variant of auth payload for creating new contract instances + // // doesn't allow specifying the constructor arguments, creating contracts + // // with constructors that take arguments is only possible by authorizing + // // `SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN` + // // (protocol 22+). + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_HOST_FN: + // CreateContractArgs createContractHostFn; + // // This variant of auth payload for creating new contract instances + // // is only accepted in and after protocol 22. It allows authorizing the + // // contract constructor arguments. + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN: + // CreateContractArgsV2 createContractV2HostFn; + // }; + // + // =========================================================================== + xdr.union("SorobanAuthorizedFunction", { + switchOn: xdr.lookup("SorobanAuthorizedFunctionType"), + switchName: "type", + switches: [["sorobanAuthorizedFunctionTypeContractFn", "contractFn"], ["sorobanAuthorizedFunctionTypeCreateContractHostFn", "createContractHostFn"], ["sorobanAuthorizedFunctionTypeCreateContractV2HostFn", "createContractV2HostFn"]], + arms: { + contractFn: xdr.lookup("InvokeContractArgs"), + createContractHostFn: xdr.lookup("CreateContractArgs"), + createContractV2HostFn: xdr.lookup("CreateContractArgsV2") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanAuthorizedInvocation + // { + // SorobanAuthorizedFunction function; + // SorobanAuthorizedInvocation subInvocations<>; + // }; + // + // =========================================================================== + xdr.struct("SorobanAuthorizedInvocation", [["function", xdr.lookup("SorobanAuthorizedFunction")], ["subInvocations", xdr.varArray(xdr.lookup("SorobanAuthorizedInvocation"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct SorobanAddressCredentials + // { + // SCAddress address; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SCVal signature; + // }; + // + // =========================================================================== + xdr.struct("SorobanAddressCredentials", [["address", xdr.lookup("ScAddress")], ["nonce", xdr.lookup("Int64")], ["signatureExpirationLedger", xdr.lookup("Uint32")], ["signature", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // enum SorobanCredentialsType + // { + // SOROBAN_CREDENTIALS_SOURCE_ACCOUNT = 0, + // SOROBAN_CREDENTIALS_ADDRESS = 1 + // }; + // + // =========================================================================== + xdr["enum"]("SorobanCredentialsType", { + sorobanCredentialsSourceAccount: 0, + sorobanCredentialsAddress: 1 + }); + + // === xdr source ============================================================ + // + // union SorobanCredentials switch (SorobanCredentialsType type) + // { + // case SOROBAN_CREDENTIALS_SOURCE_ACCOUNT: + // void; + // case SOROBAN_CREDENTIALS_ADDRESS: + // SorobanAddressCredentials address; + // }; + // + // =========================================================================== + xdr.union("SorobanCredentials", { + switchOn: xdr.lookup("SorobanCredentialsType"), + switchName: "type", + switches: [["sorobanCredentialsSourceAccount", xdr["void"]()], ["sorobanCredentialsAddress", "address"]], + arms: { + address: xdr.lookup("SorobanAddressCredentials") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanAuthorizationEntry + // { + // SorobanCredentials credentials; + // SorobanAuthorizedInvocation rootInvocation; + // }; + // + // =========================================================================== + xdr.struct("SorobanAuthorizationEntry", [["credentials", xdr.lookup("SorobanCredentials")], ["rootInvocation", xdr.lookup("SorobanAuthorizedInvocation")]]); + + // === xdr source ============================================================ + // + // struct InvokeHostFunctionOp + // { + // // Host function to invoke. + // HostFunction hostFunction; + // // Per-address authorizations for this host function. + // SorobanAuthorizationEntry auth<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeHostFunctionOp", [["hostFunction", xdr.lookup("HostFunction")], ["auth", xdr.varArray(xdr.lookup("SorobanAuthorizationEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct ExtendFootprintTTLOp + // { + // ExtensionPoint ext; + // uint32 extendTo; + // }; + // + // =========================================================================== + xdr.struct("ExtendFootprintTtlOp", [["ext", xdr.lookup("ExtensionPoint")], ["extendTo", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct RestoreFootprintOp + // { + // ExtensionPoint ext; + // }; + // + // =========================================================================== + xdr.struct("RestoreFootprintOp", [["ext", xdr.lookup("ExtensionPoint")]]); + + // === xdr source ============================================================ + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountOp createAccountOp; + // case PAYMENT: + // PaymentOp paymentOp; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp; + // case MANAGE_SELL_OFFER: + // ManageSellOfferOp manageSellOfferOp; + // case CREATE_PASSIVE_SELL_OFFER: + // CreatePassiveSellOfferOp createPassiveSellOfferOp; + // case SET_OPTIONS: + // SetOptionsOp setOptionsOp; + // case CHANGE_TRUST: + // ChangeTrustOp changeTrustOp; + // case ALLOW_TRUST: + // AllowTrustOp allowTrustOp; + // case ACCOUNT_MERGE: + // MuxedAccount destination; + // case INFLATION: + // void; + // case MANAGE_DATA: + // ManageDataOp manageDataOp; + // case BUMP_SEQUENCE: + // BumpSequenceOp bumpSequenceOp; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferOp manageBuyOfferOp; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendOp pathPaymentStrictSendOp; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceOp createClaimableBalanceOp; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceOp claimClaimableBalanceOp; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp; + // case END_SPONSORING_FUTURE_RESERVES: + // void; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipOp revokeSponsorshipOp; + // case CLAWBACK: + // ClawbackOp clawbackOp; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceOp clawbackClaimableBalanceOp; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsOp setTrustLineFlagsOp; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositOp liquidityPoolDepositOp; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawOp liquidityPoolWithdrawOp; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionOp invokeHostFunctionOp; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLOp extendFootprintTTLOp; + // case RESTORE_FOOTPRINT: + // RestoreFootprintOp restoreFootprintOp; + // } + // + // =========================================================================== + xdr.union("OperationBody", { + switchOn: xdr.lookup("OperationType"), + switchName: "type", + switches: [["createAccount", "createAccountOp"], ["payment", "paymentOp"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveOp"], ["manageSellOffer", "manageSellOfferOp"], ["createPassiveSellOffer", "createPassiveSellOfferOp"], ["setOptions", "setOptionsOp"], ["changeTrust", "changeTrustOp"], ["allowTrust", "allowTrustOp"], ["accountMerge", "destination"], ["inflation", xdr["void"]()], ["manageData", "manageDataOp"], ["bumpSequence", "bumpSequenceOp"], ["manageBuyOffer", "manageBuyOfferOp"], ["pathPaymentStrictSend", "pathPaymentStrictSendOp"], ["createClaimableBalance", "createClaimableBalanceOp"], ["claimClaimableBalance", "claimClaimableBalanceOp"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesOp"], ["endSponsoringFutureReserves", xdr["void"]()], ["revokeSponsorship", "revokeSponsorshipOp"], ["clawback", "clawbackOp"], ["clawbackClaimableBalance", "clawbackClaimableBalanceOp"], ["setTrustLineFlags", "setTrustLineFlagsOp"], ["liquidityPoolDeposit", "liquidityPoolDepositOp"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawOp"], ["invokeHostFunction", "invokeHostFunctionOp"], ["extendFootprintTtl", "extendFootprintTtlOp"], ["restoreFootprint", "restoreFootprintOp"]], + arms: { + createAccountOp: xdr.lookup("CreateAccountOp"), + paymentOp: xdr.lookup("PaymentOp"), + pathPaymentStrictReceiveOp: xdr.lookup("PathPaymentStrictReceiveOp"), + manageSellOfferOp: xdr.lookup("ManageSellOfferOp"), + createPassiveSellOfferOp: xdr.lookup("CreatePassiveSellOfferOp"), + setOptionsOp: xdr.lookup("SetOptionsOp"), + changeTrustOp: xdr.lookup("ChangeTrustOp"), + allowTrustOp: xdr.lookup("AllowTrustOp"), + destination: xdr.lookup("MuxedAccount"), + manageDataOp: xdr.lookup("ManageDataOp"), + bumpSequenceOp: xdr.lookup("BumpSequenceOp"), + manageBuyOfferOp: xdr.lookup("ManageBuyOfferOp"), + pathPaymentStrictSendOp: xdr.lookup("PathPaymentStrictSendOp"), + createClaimableBalanceOp: xdr.lookup("CreateClaimableBalanceOp"), + claimClaimableBalanceOp: xdr.lookup("ClaimClaimableBalanceOp"), + beginSponsoringFutureReservesOp: xdr.lookup("BeginSponsoringFutureReservesOp"), + revokeSponsorshipOp: xdr.lookup("RevokeSponsorshipOp"), + clawbackOp: xdr.lookup("ClawbackOp"), + clawbackClaimableBalanceOp: xdr.lookup("ClawbackClaimableBalanceOp"), + setTrustLineFlagsOp: xdr.lookup("SetTrustLineFlagsOp"), + liquidityPoolDepositOp: xdr.lookup("LiquidityPoolDepositOp"), + liquidityPoolWithdrawOp: xdr.lookup("LiquidityPoolWithdrawOp"), + invokeHostFunctionOp: xdr.lookup("InvokeHostFunctionOp"), + extendFootprintTtlOp: xdr.lookup("ExtendFootprintTtlOp"), + restoreFootprintOp: xdr.lookup("RestoreFootprintOp") + } + }); + + // === xdr source ============================================================ + // + // struct Operation + // { + // // sourceAccount is the account used to run the operation + // // if not set, the runtime defaults to "sourceAccount" specified at + // // the transaction level + // MuxedAccount* sourceAccount; + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountOp createAccountOp; + // case PAYMENT: + // PaymentOp paymentOp; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp; + // case MANAGE_SELL_OFFER: + // ManageSellOfferOp manageSellOfferOp; + // case CREATE_PASSIVE_SELL_OFFER: + // CreatePassiveSellOfferOp createPassiveSellOfferOp; + // case SET_OPTIONS: + // SetOptionsOp setOptionsOp; + // case CHANGE_TRUST: + // ChangeTrustOp changeTrustOp; + // case ALLOW_TRUST: + // AllowTrustOp allowTrustOp; + // case ACCOUNT_MERGE: + // MuxedAccount destination; + // case INFLATION: + // void; + // case MANAGE_DATA: + // ManageDataOp manageDataOp; + // case BUMP_SEQUENCE: + // BumpSequenceOp bumpSequenceOp; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferOp manageBuyOfferOp; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendOp pathPaymentStrictSendOp; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceOp createClaimableBalanceOp; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceOp claimClaimableBalanceOp; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp; + // case END_SPONSORING_FUTURE_RESERVES: + // void; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipOp revokeSponsorshipOp; + // case CLAWBACK: + // ClawbackOp clawbackOp; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceOp clawbackClaimableBalanceOp; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsOp setTrustLineFlagsOp; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositOp liquidityPoolDepositOp; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawOp liquidityPoolWithdrawOp; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionOp invokeHostFunctionOp; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLOp extendFootprintTTLOp; + // case RESTORE_FOOTPRINT: + // RestoreFootprintOp restoreFootprintOp; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("Operation", [["sourceAccount", xdr.option(xdr.lookup("MuxedAccount"))], ["body", xdr.lookup("OperationBody")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageOperationId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // PoolID liquidityPoolID; + // Asset asset; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageRevokeId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")], ["liquidityPoolId", xdr.lookup("PoolId")], ["asset", xdr.lookup("Asset")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash networkID; + // ContractIDPreimage contractIDPreimage; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageContractId", [["networkId", xdr.lookup("Hash")], ["contractIdPreimage", xdr.lookup("ContractIdPreimage")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash networkID; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SorobanAuthorizedInvocation invocation; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageSorobanAuthorization", [["networkId", xdr.lookup("Hash")], ["nonce", xdr.lookup("Int64")], ["signatureExpirationLedger", xdr.lookup("Uint32")], ["invocation", xdr.lookup("SorobanAuthorizedInvocation")]]); + + // === xdr source ============================================================ + // + // union HashIDPreimage switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_OP_ID: + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // } operationID; + // case ENVELOPE_TYPE_POOL_REVOKE_OP_ID: + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // PoolID liquidityPoolID; + // Asset asset; + // } revokeID; + // case ENVELOPE_TYPE_CONTRACT_ID: + // struct + // { + // Hash networkID; + // ContractIDPreimage contractIDPreimage; + // } contractID; + // case ENVELOPE_TYPE_SOROBAN_AUTHORIZATION: + // struct + // { + // Hash networkID; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SorobanAuthorizedInvocation invocation; + // } sorobanAuthorization; + // }; + // + // =========================================================================== + xdr.union("HashIdPreimage", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeOpId", "operationId"], ["envelopeTypePoolRevokeOpId", "revokeId"], ["envelopeTypeContractId", "contractId"], ["envelopeTypeSorobanAuthorization", "sorobanAuthorization"]], + arms: { + operationId: xdr.lookup("HashIdPreimageOperationId"), + revokeId: xdr.lookup("HashIdPreimageRevokeId"), + contractId: xdr.lookup("HashIdPreimageContractId"), + sorobanAuthorization: xdr.lookup("HashIdPreimageSorobanAuthorization") + } + }); + + // === xdr source ============================================================ + // + // enum MemoType + // { + // MEMO_NONE = 0, + // MEMO_TEXT = 1, + // MEMO_ID = 2, + // MEMO_HASH = 3, + // MEMO_RETURN = 4 + // }; + // + // =========================================================================== + xdr["enum"]("MemoType", { + memoNone: 0, + memoText: 1, + memoId: 2, + memoHash: 3, + memoReturn: 4 + }); + + // === xdr source ============================================================ + // + // union Memo switch (MemoType type) + // { + // case MEMO_NONE: + // void; + // case MEMO_TEXT: + // string text<28>; + // case MEMO_ID: + // uint64 id; + // case MEMO_HASH: + // Hash hash; // the hash of what to pull from the content server + // case MEMO_RETURN: + // Hash retHash; // the hash of the tx you are rejecting + // }; + // + // =========================================================================== + xdr.union("Memo", { + switchOn: xdr.lookup("MemoType"), + switchName: "type", + switches: [["memoNone", xdr["void"]()], ["memoText", "text"], ["memoId", "id"], ["memoHash", "hash"], ["memoReturn", "retHash"]], + arms: { + text: xdr.string(28), + id: xdr.lookup("Uint64"), + hash: xdr.lookup("Hash"), + retHash: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // struct TimeBounds + // { + // TimePoint minTime; + // TimePoint maxTime; // 0 here means no maxTime + // }; + // + // =========================================================================== + xdr.struct("TimeBounds", [["minTime", xdr.lookup("TimePoint")], ["maxTime", xdr.lookup("TimePoint")]]); + + // === xdr source ============================================================ + // + // struct LedgerBounds + // { + // uint32 minLedger; + // uint32 maxLedger; // 0 here means no maxLedger + // }; + // + // =========================================================================== + xdr.struct("LedgerBounds", [["minLedger", xdr.lookup("Uint32")], ["maxLedger", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct PreconditionsV2 + // { + // TimeBounds* timeBounds; + // + // // Transaction only valid for ledger numbers n such that + // // minLedger <= n < maxLedger (if maxLedger == 0, then + // // only minLedger is checked) + // LedgerBounds* ledgerBounds; + // + // // If NULL, only valid when sourceAccount's sequence number + // // is seqNum - 1. Otherwise, valid when sourceAccount's + // // sequence number n satisfies minSeqNum <= n < tx.seqNum. + // // Note that after execution the account's sequence number + // // is always raised to tx.seqNum, and a transaction is not + // // valid if tx.seqNum is too high to ensure replay protection. + // SequenceNumber* minSeqNum; + // + // // For the transaction to be valid, the current ledger time must + // // be at least minSeqAge greater than sourceAccount's seqTime. + // Duration minSeqAge; + // + // // For the transaction to be valid, the current ledger number + // // must be at least minSeqLedgerGap greater than sourceAccount's + // // seqLedger. + // uint32 minSeqLedgerGap; + // + // // For the transaction to be valid, there must be a signature + // // corresponding to every Signer in this array, even if the + // // signature is not otherwise required by the sourceAccount or + // // operations. + // SignerKey extraSigners<2>; + // }; + // + // =========================================================================== + xdr.struct("PreconditionsV2", [["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["ledgerBounds", xdr.option(xdr.lookup("LedgerBounds"))], ["minSeqNum", xdr.option(xdr.lookup("SequenceNumber"))], ["minSeqAge", xdr.lookup("Duration")], ["minSeqLedgerGap", xdr.lookup("Uint32")], ["extraSigners", xdr.varArray(xdr.lookup("SignerKey"), 2)]]); + + // === xdr source ============================================================ + // + // enum PreconditionType + // { + // PRECOND_NONE = 0, + // PRECOND_TIME = 1, + // PRECOND_V2 = 2 + // }; + // + // =========================================================================== + xdr["enum"]("PreconditionType", { + precondNone: 0, + precondTime: 1, + precondV2: 2 + }); + + // === xdr source ============================================================ + // + // union Preconditions switch (PreconditionType type) + // { + // case PRECOND_NONE: + // void; + // case PRECOND_TIME: + // TimeBounds timeBounds; + // case PRECOND_V2: + // PreconditionsV2 v2; + // }; + // + // =========================================================================== + xdr.union("Preconditions", { + switchOn: xdr.lookup("PreconditionType"), + switchName: "type", + switches: [["precondNone", xdr["void"]()], ["precondTime", "timeBounds"], ["precondV2", "v2"]], + arms: { + timeBounds: xdr.lookup("TimeBounds"), + v2: xdr.lookup("PreconditionsV2") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerFootprint + // { + // LedgerKey readOnly<>; + // LedgerKey readWrite<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerFootprint", [["readOnly", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["readWrite", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)]]); + + // === xdr source ============================================================ + // + // enum ArchivalProofType + // { + // EXISTENCE = 0, + // NONEXISTENCE = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ArchivalProofType", { + existence: 0, + nonexistence: 1 + }); + + // === xdr source ============================================================ + // + // struct ArchivalProofNode + // { + // uint32 index; + // Hash hash; + // }; + // + // =========================================================================== + xdr.struct("ArchivalProofNode", [["index", xdr.lookup("Uint32")], ["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // typedef ArchivalProofNode ProofLevel<>; + // + // =========================================================================== + xdr.typedef("ProofLevel", xdr.varArray(xdr.lookup("ArchivalProofNode"), 2147483647)); + + // === xdr source ============================================================ + // + // struct NonexistenceProofBody + // { + // ColdArchiveBucketEntry entriesToProve<>; + // + // // Vector of vectors, where proofLevels[level] + // // contains all HashNodes that correspond with that level + // ProofLevel proofLevels<>; + // }; + // + // =========================================================================== + xdr.struct("NonexistenceProofBody", [["entriesToProve", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["proofLevels", xdr.varArray(xdr.lookup("ProofLevel"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct ExistenceProofBody + // { + // LedgerKey keysToProve<>; + // + // // Bounds for each key being proved, where bound[n] + // // corresponds to keysToProve[n] + // ColdArchiveBucketEntry lowBoundEntries<>; + // ColdArchiveBucketEntry highBoundEntries<>; + // + // // Vector of vectors, where proofLevels[level] + // // contains all HashNodes that correspond with that level + // ProofLevel proofLevels<>; + // }; + // + // =========================================================================== + xdr.struct("ExistenceProofBody", [["keysToProve", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["lowBoundEntries", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["highBoundEntries", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["proofLevels", xdr.varArray(xdr.lookup("ProofLevel"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union switch (ArchivalProofType t) + // { + // case EXISTENCE: + // NonexistenceProofBody nonexistenceProof; + // case NONEXISTENCE: + // ExistenceProofBody existenceProof; + // } + // + // =========================================================================== + xdr.union("ArchivalProofBody", { + switchOn: xdr.lookup("ArchivalProofType"), + switchName: "t", + switches: [["existence", "nonexistenceProof"], ["nonexistence", "existenceProof"]], + arms: { + nonexistenceProof: xdr.lookup("NonexistenceProofBody"), + existenceProof: xdr.lookup("ExistenceProofBody") + } + }); + + // === xdr source ============================================================ + // + // struct ArchivalProof + // { + // uint32 epoch; // AST Subtree for this proof + // + // union switch (ArchivalProofType t) + // { + // case EXISTENCE: + // NonexistenceProofBody nonexistenceProof; + // case NONEXISTENCE: + // ExistenceProofBody existenceProof; + // } body; + // }; + // + // =========================================================================== + xdr.struct("ArchivalProof", [["epoch", xdr.lookup("Uint32")], ["body", xdr.lookup("ArchivalProofBody")]]); + + // === xdr source ============================================================ + // + // struct SorobanResources + // { + // // The ledger footprint of the transaction. + // LedgerFootprint footprint; + // // The maximum number of instructions this transaction can use + // uint32 instructions; + // + // // The maximum number of bytes this transaction can read from ledger + // uint32 readBytes; + // // The maximum number of bytes this transaction can write to ledger + // uint32 writeBytes; + // }; + // + // =========================================================================== + xdr.struct("SorobanResources", [["footprint", xdr.lookup("LedgerFootprint")], ["instructions", xdr.lookup("Uint32")], ["readBytes", xdr.lookup("Uint32")], ["writeBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SorobanTransactionData + // { + // ExtensionPoint ext; + // SorobanResources resources; + // // Amount of the transaction `fee` allocated to the Soroban resource fees. + // // The fraction of `resourceFee` corresponding to `resources` specified + // // above is *not* refundable (i.e. fees for instructions, ledger I/O), as + // // well as fees for the transaction size. + // // The remaining part of the fee is refundable and the charged value is + // // based on the actual consumption of refundable resources (events, ledger + // // rent bumps). + // // The `inclusionFee` used for prioritization of the transaction is defined + // // as `tx.fee - resourceFee`. + // int64 resourceFee; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionData", [["ext", xdr.lookup("ExtensionPoint")], ["resources", xdr.lookup("SorobanResources")], ["resourceFee", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionV0Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionV0 + // { + // uint256 sourceAccountEd25519; + // uint32 fee; + // SequenceNumber seqNum; + // TimeBounds* timeBounds; + // Memo memo; + // Operation operations; + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionV0", [["sourceAccountEd25519", xdr.lookup("Uint256")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionV0Ext")]]); + + // === xdr source ============================================================ + // + // struct TransactionV0Envelope + // { + // TransactionV0 tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("TransactionV0Envelope", [["tx", xdr.lookup("TransactionV0")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionData sorobanData; + // } + // + // =========================================================================== + xdr.union("TransactionExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "sorobanData"]], + arms: { + sorobanData: xdr.lookup("SorobanTransactionData") + } + }); + + // === xdr source ============================================================ + // + // struct Transaction + // { + // // account used to run the transaction + // MuxedAccount sourceAccount; + // + // // the fee the sourceAccount will pay + // uint32 fee; + // + // // sequence number to consume in the account + // SequenceNumber seqNum; + // + // // validity conditions + // Preconditions cond; + // + // Memo memo; + // + // Operation operations; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionData sorobanData; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("Transaction", [["sourceAccount", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["cond", xdr.lookup("Preconditions")], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionExt")]]); + + // === xdr source ============================================================ + // + // struct TransactionV1Envelope + // { + // Transaction tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("TransactionV1Envelope", [["tx", xdr.lookup("Transaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // } + // + // =========================================================================== + xdr.union("FeeBumpTransactionInnerTx", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTx", "v1"]], + arms: { + v1: xdr.lookup("TransactionV1Envelope") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("FeeBumpTransactionExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct FeeBumpTransaction + // { + // MuxedAccount feeSource; + // int64 fee; + // union switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // } + // innerTx; + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("FeeBumpTransaction", [["feeSource", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Int64")], ["innerTx", xdr.lookup("FeeBumpTransactionInnerTx")], ["ext", xdr.lookup("FeeBumpTransactionExt")]]); + + // === xdr source ============================================================ + // + // struct FeeBumpTransactionEnvelope + // { + // FeeBumpTransaction tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("FeeBumpTransactionEnvelope", [["tx", xdr.lookup("FeeBumpTransaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union TransactionEnvelope switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX_V0: + // TransactionV0Envelope v0; + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransactionEnvelope feeBump; + // }; + // + // =========================================================================== + xdr.union("TransactionEnvelope", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTxV0", "v0"], ["envelopeTypeTx", "v1"], ["envelopeTypeTxFeeBump", "feeBump"]], + arms: { + v0: xdr.lookup("TransactionV0Envelope"), + v1: xdr.lookup("TransactionV1Envelope"), + feeBump: xdr.lookup("FeeBumpTransactionEnvelope") + } + }); + + // === xdr source ============================================================ + // + // union switch (EnvelopeType type) + // { + // // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // case ENVELOPE_TYPE_TX: + // Transaction tx; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransaction feeBump; + // } + // + // =========================================================================== + xdr.union("TransactionSignaturePayloadTaggedTransaction", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTx", "tx"], ["envelopeTypeTxFeeBump", "feeBump"]], + arms: { + tx: xdr.lookup("Transaction"), + feeBump: xdr.lookup("FeeBumpTransaction") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionSignaturePayload + // { + // Hash networkId; + // union switch (EnvelopeType type) + // { + // // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // case ENVELOPE_TYPE_TX: + // Transaction tx; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransaction feeBump; + // } + // taggedTransaction; + // }; + // + // =========================================================================== + xdr.struct("TransactionSignaturePayload", [["networkId", xdr.lookup("Hash")], ["taggedTransaction", xdr.lookup("TransactionSignaturePayloadTaggedTransaction")]]); + + // === xdr source ============================================================ + // + // enum ClaimAtomType + // { + // CLAIM_ATOM_TYPE_V0 = 0, + // CLAIM_ATOM_TYPE_ORDER_BOOK = 1, + // CLAIM_ATOM_TYPE_LIQUIDITY_POOL = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimAtomType", { + claimAtomTypeV0: 0, + claimAtomTypeOrderBook: 1, + claimAtomTypeLiquidityPool: 2 + }); + + // === xdr source ============================================================ + // + // struct ClaimOfferAtomV0 + // { + // // emitted to identify the offer + // uint256 sellerEd25519; // Account that owns the offer + // int64 offerID; + // + // // amount and asset taken from the owner + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the owner + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimOfferAtomV0", [["sellerEd25519", xdr.lookup("Uint256")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClaimOfferAtom + // { + // // emitted to identify the offer + // AccountID sellerID; // Account that owns the offer + // int64 offerID; + // + // // amount and asset taken from the owner + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the owner + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimOfferAtom", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClaimLiquidityAtom + // { + // PoolID liquidityPoolID; + // + // // amount and asset taken from the pool + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the pool + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimLiquidityAtom", [["liquidityPoolId", xdr.lookup("PoolId")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union ClaimAtom switch (ClaimAtomType type) + // { + // case CLAIM_ATOM_TYPE_V0: + // ClaimOfferAtomV0 v0; + // case CLAIM_ATOM_TYPE_ORDER_BOOK: + // ClaimOfferAtom orderBook; + // case CLAIM_ATOM_TYPE_LIQUIDITY_POOL: + // ClaimLiquidityAtom liquidityPool; + // }; + // + // =========================================================================== + xdr.union("ClaimAtom", { + switchOn: xdr.lookup("ClaimAtomType"), + switchName: "type", + switches: [["claimAtomTypeV0", "v0"], ["claimAtomTypeOrderBook", "orderBook"], ["claimAtomTypeLiquidityPool", "liquidityPool"]], + arms: { + v0: xdr.lookup("ClaimOfferAtomV0"), + orderBook: xdr.lookup("ClaimOfferAtom"), + liquidityPool: xdr.lookup("ClaimLiquidityAtom") + } + }); + + // === xdr source ============================================================ + // + // enum CreateAccountResultCode + // { + // // codes considered as "success" for the operation + // CREATE_ACCOUNT_SUCCESS = 0, // account was created + // + // // codes considered as "failure" for the operation + // CREATE_ACCOUNT_MALFORMED = -1, // invalid destination + // CREATE_ACCOUNT_UNDERFUNDED = -2, // not enough funds in source account + // CREATE_ACCOUNT_LOW_RESERVE = + // -3, // would create an account below the min reserve + // CREATE_ACCOUNT_ALREADY_EXIST = -4 // account already exists + // }; + // + // =========================================================================== + xdr["enum"]("CreateAccountResultCode", { + createAccountSuccess: 0, + createAccountMalformed: -1, + createAccountUnderfunded: -2, + createAccountLowReserve: -3, + createAccountAlreadyExist: -4 + }); + + // === xdr source ============================================================ + // + // union CreateAccountResult switch (CreateAccountResultCode code) + // { + // case CREATE_ACCOUNT_SUCCESS: + // void; + // case CREATE_ACCOUNT_MALFORMED: + // case CREATE_ACCOUNT_UNDERFUNDED: + // case CREATE_ACCOUNT_LOW_RESERVE: + // case CREATE_ACCOUNT_ALREADY_EXIST: + // void; + // }; + // + // =========================================================================== + xdr.union("CreateAccountResult", { + switchOn: xdr.lookup("CreateAccountResultCode"), + switchName: "code", + switches: [["createAccountSuccess", xdr["void"]()], ["createAccountMalformed", xdr["void"]()], ["createAccountUnderfunded", xdr["void"]()], ["createAccountLowReserve", xdr["void"]()], ["createAccountAlreadyExist", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum PaymentResultCode + // { + // // codes considered as "success" for the operation + // PAYMENT_SUCCESS = 0, // payment successfully completed + // + // // codes considered as "failure" for the operation + // PAYMENT_MALFORMED = -1, // bad input + // PAYMENT_UNDERFUNDED = -2, // not enough funds in source account + // PAYMENT_SRC_NO_TRUST = -3, // no trust line on source account + // PAYMENT_SRC_NOT_AUTHORIZED = -4, // source not authorized to transfer + // PAYMENT_NO_DESTINATION = -5, // destination account does not exist + // PAYMENT_NO_TRUST = -6, // destination missing a trust line for asset + // PAYMENT_NOT_AUTHORIZED = -7, // destination not authorized to hold asset + // PAYMENT_LINE_FULL = -8, // destination would go above their limit + // PAYMENT_NO_ISSUER = -9 // missing issuer on asset + // }; + // + // =========================================================================== + xdr["enum"]("PaymentResultCode", { + paymentSuccess: 0, + paymentMalformed: -1, + paymentUnderfunded: -2, + paymentSrcNoTrust: -3, + paymentSrcNotAuthorized: -4, + paymentNoDestination: -5, + paymentNoTrust: -6, + paymentNotAuthorized: -7, + paymentLineFull: -8, + paymentNoIssuer: -9 + }); + + // === xdr source ============================================================ + // + // union PaymentResult switch (PaymentResultCode code) + // { + // case PAYMENT_SUCCESS: + // void; + // case PAYMENT_MALFORMED: + // case PAYMENT_UNDERFUNDED: + // case PAYMENT_SRC_NO_TRUST: + // case PAYMENT_SRC_NOT_AUTHORIZED: + // case PAYMENT_NO_DESTINATION: + // case PAYMENT_NO_TRUST: + // case PAYMENT_NOT_AUTHORIZED: + // case PAYMENT_LINE_FULL: + // case PAYMENT_NO_ISSUER: + // void; + // }; + // + // =========================================================================== + xdr.union("PaymentResult", { + switchOn: xdr.lookup("PaymentResultCode"), + switchName: "code", + switches: [["paymentSuccess", xdr["void"]()], ["paymentMalformed", xdr["void"]()], ["paymentUnderfunded", xdr["void"]()], ["paymentSrcNoTrust", xdr["void"]()], ["paymentSrcNotAuthorized", xdr["void"]()], ["paymentNoDestination", xdr["void"]()], ["paymentNoTrust", xdr["void"]()], ["paymentNotAuthorized", xdr["void"]()], ["paymentLineFull", xdr["void"]()], ["paymentNoIssuer", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum PathPaymentStrictReceiveResultCode + // { + // // codes considered as "success" for the operation + // PATH_PAYMENT_STRICT_RECEIVE_SUCCESS = 0, // success + // + // // codes considered as "failure" for the operation + // PATH_PAYMENT_STRICT_RECEIVE_MALFORMED = -1, // bad input + // PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED = + // -2, // not enough funds in source account + // PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST = + // -3, // no trust line on source account + // PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED = + // -4, // source not authorized to transfer + // PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION = + // -5, // destination account does not exist + // PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST = + // -6, // dest missing a trust line for asset + // PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED = + // -7, // dest not authorized to hold asset + // PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL = + // -8, // dest would go above their limit + // PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER = -9, // missing issuer on one asset + // PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS = + // -10, // not enough offers to satisfy path + // PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF = + // -11, // would cross one of its own offers + // PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX = -12 // could not satisfy sendmax + // }; + // + // =========================================================================== + xdr["enum"]("PathPaymentStrictReceiveResultCode", { + pathPaymentStrictReceiveSuccess: 0, + pathPaymentStrictReceiveMalformed: -1, + pathPaymentStrictReceiveUnderfunded: -2, + pathPaymentStrictReceiveSrcNoTrust: -3, + pathPaymentStrictReceiveSrcNotAuthorized: -4, + pathPaymentStrictReceiveNoDestination: -5, + pathPaymentStrictReceiveNoTrust: -6, + pathPaymentStrictReceiveNotAuthorized: -7, + pathPaymentStrictReceiveLineFull: -8, + pathPaymentStrictReceiveNoIssuer: -9, + pathPaymentStrictReceiveTooFewOffers: -10, + pathPaymentStrictReceiveOfferCrossSelf: -11, + pathPaymentStrictReceiveOverSendmax: -12 + }); + + // === xdr source ============================================================ + // + // struct SimplePaymentResult + // { + // AccountID destination; + // Asset asset; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("SimplePaymentResult", [["destination", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } + // + // =========================================================================== + xdr.struct("PathPaymentStrictReceiveResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]); + + // === xdr source ============================================================ + // + // union PathPaymentStrictReceiveResult switch ( + // PathPaymentStrictReceiveResultCode code) + // { + // case PATH_PAYMENT_STRICT_RECEIVE_SUCCESS: + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } success; + // case PATH_PAYMENT_STRICT_RECEIVE_MALFORMED: + // case PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED: + // case PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST: + // case PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION: + // case PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST: + // case PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL: + // void; + // case PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER: + // Asset noIssuer; // the asset that caused the error + // case PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS: + // case PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF: + // case PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX: + // void; + // }; + // + // =========================================================================== + xdr.union("PathPaymentStrictReceiveResult", { + switchOn: xdr.lookup("PathPaymentStrictReceiveResultCode"), + switchName: "code", + switches: [["pathPaymentStrictReceiveSuccess", "success"], ["pathPaymentStrictReceiveMalformed", xdr["void"]()], ["pathPaymentStrictReceiveUnderfunded", xdr["void"]()], ["pathPaymentStrictReceiveSrcNoTrust", xdr["void"]()], ["pathPaymentStrictReceiveSrcNotAuthorized", xdr["void"]()], ["pathPaymentStrictReceiveNoDestination", xdr["void"]()], ["pathPaymentStrictReceiveNoTrust", xdr["void"]()], ["pathPaymentStrictReceiveNotAuthorized", xdr["void"]()], ["pathPaymentStrictReceiveLineFull", xdr["void"]()], ["pathPaymentStrictReceiveNoIssuer", "noIssuer"], ["pathPaymentStrictReceiveTooFewOffers", xdr["void"]()], ["pathPaymentStrictReceiveOfferCrossSelf", xdr["void"]()], ["pathPaymentStrictReceiveOverSendmax", xdr["void"]()]], + arms: { + success: xdr.lookup("PathPaymentStrictReceiveResultSuccess"), + noIssuer: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // enum PathPaymentStrictSendResultCode + // { + // // codes considered as "success" for the operation + // PATH_PAYMENT_STRICT_SEND_SUCCESS = 0, // success + // + // // codes considered as "failure" for the operation + // PATH_PAYMENT_STRICT_SEND_MALFORMED = -1, // bad input + // PATH_PAYMENT_STRICT_SEND_UNDERFUNDED = + // -2, // not enough funds in source account + // PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST = + // -3, // no trust line on source account + // PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED = + // -4, // source not authorized to transfer + // PATH_PAYMENT_STRICT_SEND_NO_DESTINATION = + // -5, // destination account does not exist + // PATH_PAYMENT_STRICT_SEND_NO_TRUST = + // -6, // dest missing a trust line for asset + // PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED = + // -7, // dest not authorized to hold asset + // PATH_PAYMENT_STRICT_SEND_LINE_FULL = -8, // dest would go above their limit + // PATH_PAYMENT_STRICT_SEND_NO_ISSUER = -9, // missing issuer on one asset + // PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS = + // -10, // not enough offers to satisfy path + // PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF = + // -11, // would cross one of its own offers + // PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN = -12 // could not satisfy destMin + // }; + // + // =========================================================================== + xdr["enum"]("PathPaymentStrictSendResultCode", { + pathPaymentStrictSendSuccess: 0, + pathPaymentStrictSendMalformed: -1, + pathPaymentStrictSendUnderfunded: -2, + pathPaymentStrictSendSrcNoTrust: -3, + pathPaymentStrictSendSrcNotAuthorized: -4, + pathPaymentStrictSendNoDestination: -5, + pathPaymentStrictSendNoTrust: -6, + pathPaymentStrictSendNotAuthorized: -7, + pathPaymentStrictSendLineFull: -8, + pathPaymentStrictSendNoIssuer: -9, + pathPaymentStrictSendTooFewOffers: -10, + pathPaymentStrictSendOfferCrossSelf: -11, + pathPaymentStrictSendUnderDestmin: -12 + }); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } + // + // =========================================================================== + xdr.struct("PathPaymentStrictSendResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]); + + // === xdr source ============================================================ + // + // union PathPaymentStrictSendResult switch (PathPaymentStrictSendResultCode code) + // { + // case PATH_PAYMENT_STRICT_SEND_SUCCESS: + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } success; + // case PATH_PAYMENT_STRICT_SEND_MALFORMED: + // case PATH_PAYMENT_STRICT_SEND_UNDERFUNDED: + // case PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST: + // case PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_SEND_NO_DESTINATION: + // case PATH_PAYMENT_STRICT_SEND_NO_TRUST: + // case PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_SEND_LINE_FULL: + // void; + // case PATH_PAYMENT_STRICT_SEND_NO_ISSUER: + // Asset noIssuer; // the asset that caused the error + // case PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS: + // case PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF: + // case PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN: + // void; + // }; + // + // =========================================================================== + xdr.union("PathPaymentStrictSendResult", { + switchOn: xdr.lookup("PathPaymentStrictSendResultCode"), + switchName: "code", + switches: [["pathPaymentStrictSendSuccess", "success"], ["pathPaymentStrictSendMalformed", xdr["void"]()], ["pathPaymentStrictSendUnderfunded", xdr["void"]()], ["pathPaymentStrictSendSrcNoTrust", xdr["void"]()], ["pathPaymentStrictSendSrcNotAuthorized", xdr["void"]()], ["pathPaymentStrictSendNoDestination", xdr["void"]()], ["pathPaymentStrictSendNoTrust", xdr["void"]()], ["pathPaymentStrictSendNotAuthorized", xdr["void"]()], ["pathPaymentStrictSendLineFull", xdr["void"]()], ["pathPaymentStrictSendNoIssuer", "noIssuer"], ["pathPaymentStrictSendTooFewOffers", xdr["void"]()], ["pathPaymentStrictSendOfferCrossSelf", xdr["void"]()], ["pathPaymentStrictSendUnderDestmin", xdr["void"]()]], + arms: { + success: xdr.lookup("PathPaymentStrictSendResultSuccess"), + noIssuer: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // enum ManageSellOfferResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_SELL_OFFER_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // MANAGE_SELL_OFFER_MALFORMED = -1, // generated offer would be invalid + // MANAGE_SELL_OFFER_SELL_NO_TRUST = + // -2, // no trust line for what we're selling + // MANAGE_SELL_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying + // MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell + // MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy + // MANAGE_SELL_OFFER_LINE_FULL = -6, // can't receive more of what it's buying + // MANAGE_SELL_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell + // MANAGE_SELL_OFFER_CROSS_SELF = + // -8, // would cross an offer from the same user + // MANAGE_SELL_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling + // MANAGE_SELL_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying + // + // // update errors + // MANAGE_SELL_OFFER_NOT_FOUND = + // -11, // offerID does not match an existing offer + // + // MANAGE_SELL_OFFER_LOW_RESERVE = + // -12 // not enough funds to create a new Offer + // }; + // + // =========================================================================== + xdr["enum"]("ManageSellOfferResultCode", { + manageSellOfferSuccess: 0, + manageSellOfferMalformed: -1, + manageSellOfferSellNoTrust: -2, + manageSellOfferBuyNoTrust: -3, + manageSellOfferSellNotAuthorized: -4, + manageSellOfferBuyNotAuthorized: -5, + manageSellOfferLineFull: -6, + manageSellOfferUnderfunded: -7, + manageSellOfferCrossSelf: -8, + manageSellOfferSellNoIssuer: -9, + manageSellOfferBuyNoIssuer: -10, + manageSellOfferNotFound: -11, + manageSellOfferLowReserve: -12 + }); + + // === xdr source ============================================================ + // + // enum ManageOfferEffect + // { + // MANAGE_OFFER_CREATED = 0, + // MANAGE_OFFER_UPDATED = 1, + // MANAGE_OFFER_DELETED = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ManageOfferEffect", { + manageOfferCreated: 0, + manageOfferUpdated: 1, + manageOfferDeleted: 2 + }); + + // === xdr source ============================================================ + // + // union switch (ManageOfferEffect effect) + // { + // case MANAGE_OFFER_CREATED: + // case MANAGE_OFFER_UPDATED: + // OfferEntry offer; + // case MANAGE_OFFER_DELETED: + // void; + // } + // + // =========================================================================== + xdr.union("ManageOfferSuccessResultOffer", { + switchOn: xdr.lookup("ManageOfferEffect"), + switchName: "effect", + switches: [["manageOfferCreated", "offer"], ["manageOfferUpdated", "offer"], ["manageOfferDeleted", xdr["void"]()]], + arms: { + offer: xdr.lookup("OfferEntry") + } + }); + + // === xdr source ============================================================ + // + // struct ManageOfferSuccessResult + // { + // // offers that got claimed while creating this offer + // ClaimAtom offersClaimed<>; + // + // union switch (ManageOfferEffect effect) + // { + // case MANAGE_OFFER_CREATED: + // case MANAGE_OFFER_UPDATED: + // OfferEntry offer; + // case MANAGE_OFFER_DELETED: + // void; + // } + // offer; + // }; + // + // =========================================================================== + xdr.struct("ManageOfferSuccessResult", [["offersClaimed", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["offer", xdr.lookup("ManageOfferSuccessResultOffer")]]); + + // === xdr source ============================================================ + // + // union ManageSellOfferResult switch (ManageSellOfferResultCode code) + // { + // case MANAGE_SELL_OFFER_SUCCESS: + // ManageOfferSuccessResult success; + // case MANAGE_SELL_OFFER_MALFORMED: + // case MANAGE_SELL_OFFER_SELL_NO_TRUST: + // case MANAGE_SELL_OFFER_BUY_NO_TRUST: + // case MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED: + // case MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED: + // case MANAGE_SELL_OFFER_LINE_FULL: + // case MANAGE_SELL_OFFER_UNDERFUNDED: + // case MANAGE_SELL_OFFER_CROSS_SELF: + // case MANAGE_SELL_OFFER_SELL_NO_ISSUER: + // case MANAGE_SELL_OFFER_BUY_NO_ISSUER: + // case MANAGE_SELL_OFFER_NOT_FOUND: + // case MANAGE_SELL_OFFER_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageSellOfferResult", { + switchOn: xdr.lookup("ManageSellOfferResultCode"), + switchName: "code", + switches: [["manageSellOfferSuccess", "success"], ["manageSellOfferMalformed", xdr["void"]()], ["manageSellOfferSellNoTrust", xdr["void"]()], ["manageSellOfferBuyNoTrust", xdr["void"]()], ["manageSellOfferSellNotAuthorized", xdr["void"]()], ["manageSellOfferBuyNotAuthorized", xdr["void"]()], ["manageSellOfferLineFull", xdr["void"]()], ["manageSellOfferUnderfunded", xdr["void"]()], ["manageSellOfferCrossSelf", xdr["void"]()], ["manageSellOfferSellNoIssuer", xdr["void"]()], ["manageSellOfferBuyNoIssuer", xdr["void"]()], ["manageSellOfferNotFound", xdr["void"]()], ["manageSellOfferLowReserve", xdr["void"]()]], + arms: { + success: xdr.lookup("ManageOfferSuccessResult") + } + }); + + // === xdr source ============================================================ + // + // enum ManageBuyOfferResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_BUY_OFFER_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // MANAGE_BUY_OFFER_MALFORMED = -1, // generated offer would be invalid + // MANAGE_BUY_OFFER_SELL_NO_TRUST = -2, // no trust line for what we're selling + // MANAGE_BUY_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying + // MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell + // MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy + // MANAGE_BUY_OFFER_LINE_FULL = -6, // can't receive more of what it's buying + // MANAGE_BUY_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell + // MANAGE_BUY_OFFER_CROSS_SELF = -8, // would cross an offer from the same user + // MANAGE_BUY_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling + // MANAGE_BUY_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying + // + // // update errors + // MANAGE_BUY_OFFER_NOT_FOUND = + // -11, // offerID does not match an existing offer + // + // MANAGE_BUY_OFFER_LOW_RESERVE = -12 // not enough funds to create a new Offer + // }; + // + // =========================================================================== + xdr["enum"]("ManageBuyOfferResultCode", { + manageBuyOfferSuccess: 0, + manageBuyOfferMalformed: -1, + manageBuyOfferSellNoTrust: -2, + manageBuyOfferBuyNoTrust: -3, + manageBuyOfferSellNotAuthorized: -4, + manageBuyOfferBuyNotAuthorized: -5, + manageBuyOfferLineFull: -6, + manageBuyOfferUnderfunded: -7, + manageBuyOfferCrossSelf: -8, + manageBuyOfferSellNoIssuer: -9, + manageBuyOfferBuyNoIssuer: -10, + manageBuyOfferNotFound: -11, + manageBuyOfferLowReserve: -12 + }); + + // === xdr source ============================================================ + // + // union ManageBuyOfferResult switch (ManageBuyOfferResultCode code) + // { + // case MANAGE_BUY_OFFER_SUCCESS: + // ManageOfferSuccessResult success; + // case MANAGE_BUY_OFFER_MALFORMED: + // case MANAGE_BUY_OFFER_SELL_NO_TRUST: + // case MANAGE_BUY_OFFER_BUY_NO_TRUST: + // case MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED: + // case MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED: + // case MANAGE_BUY_OFFER_LINE_FULL: + // case MANAGE_BUY_OFFER_UNDERFUNDED: + // case MANAGE_BUY_OFFER_CROSS_SELF: + // case MANAGE_BUY_OFFER_SELL_NO_ISSUER: + // case MANAGE_BUY_OFFER_BUY_NO_ISSUER: + // case MANAGE_BUY_OFFER_NOT_FOUND: + // case MANAGE_BUY_OFFER_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageBuyOfferResult", { + switchOn: xdr.lookup("ManageBuyOfferResultCode"), + switchName: "code", + switches: [["manageBuyOfferSuccess", "success"], ["manageBuyOfferMalformed", xdr["void"]()], ["manageBuyOfferSellNoTrust", xdr["void"]()], ["manageBuyOfferBuyNoTrust", xdr["void"]()], ["manageBuyOfferSellNotAuthorized", xdr["void"]()], ["manageBuyOfferBuyNotAuthorized", xdr["void"]()], ["manageBuyOfferLineFull", xdr["void"]()], ["manageBuyOfferUnderfunded", xdr["void"]()], ["manageBuyOfferCrossSelf", xdr["void"]()], ["manageBuyOfferSellNoIssuer", xdr["void"]()], ["manageBuyOfferBuyNoIssuer", xdr["void"]()], ["manageBuyOfferNotFound", xdr["void"]()], ["manageBuyOfferLowReserve", xdr["void"]()]], + arms: { + success: xdr.lookup("ManageOfferSuccessResult") + } + }); + + // === xdr source ============================================================ + // + // enum SetOptionsResultCode + // { + // // codes considered as "success" for the operation + // SET_OPTIONS_SUCCESS = 0, + // // codes considered as "failure" for the operation + // SET_OPTIONS_LOW_RESERVE = -1, // not enough funds to add a signer + // SET_OPTIONS_TOO_MANY_SIGNERS = -2, // max number of signers already reached + // SET_OPTIONS_BAD_FLAGS = -3, // invalid combination of clear/set flags + // SET_OPTIONS_INVALID_INFLATION = -4, // inflation account does not exist + // SET_OPTIONS_CANT_CHANGE = -5, // can no longer change this option + // SET_OPTIONS_UNKNOWN_FLAG = -6, // can't set an unknown flag + // SET_OPTIONS_THRESHOLD_OUT_OF_RANGE = -7, // bad value for weight/threshold + // SET_OPTIONS_BAD_SIGNER = -8, // signer cannot be masterkey + // SET_OPTIONS_INVALID_HOME_DOMAIN = -9, // malformed home domain + // SET_OPTIONS_AUTH_REVOCABLE_REQUIRED = + // -10 // auth revocable is required for clawback + // }; + // + // =========================================================================== + xdr["enum"]("SetOptionsResultCode", { + setOptionsSuccess: 0, + setOptionsLowReserve: -1, + setOptionsTooManySigners: -2, + setOptionsBadFlags: -3, + setOptionsInvalidInflation: -4, + setOptionsCantChange: -5, + setOptionsUnknownFlag: -6, + setOptionsThresholdOutOfRange: -7, + setOptionsBadSigner: -8, + setOptionsInvalidHomeDomain: -9, + setOptionsAuthRevocableRequired: -10 + }); + + // === xdr source ============================================================ + // + // union SetOptionsResult switch (SetOptionsResultCode code) + // { + // case SET_OPTIONS_SUCCESS: + // void; + // case SET_OPTIONS_LOW_RESERVE: + // case SET_OPTIONS_TOO_MANY_SIGNERS: + // case SET_OPTIONS_BAD_FLAGS: + // case SET_OPTIONS_INVALID_INFLATION: + // case SET_OPTIONS_CANT_CHANGE: + // case SET_OPTIONS_UNKNOWN_FLAG: + // case SET_OPTIONS_THRESHOLD_OUT_OF_RANGE: + // case SET_OPTIONS_BAD_SIGNER: + // case SET_OPTIONS_INVALID_HOME_DOMAIN: + // case SET_OPTIONS_AUTH_REVOCABLE_REQUIRED: + // void; + // }; + // + // =========================================================================== + xdr.union("SetOptionsResult", { + switchOn: xdr.lookup("SetOptionsResultCode"), + switchName: "code", + switches: [["setOptionsSuccess", xdr["void"]()], ["setOptionsLowReserve", xdr["void"]()], ["setOptionsTooManySigners", xdr["void"]()], ["setOptionsBadFlags", xdr["void"]()], ["setOptionsInvalidInflation", xdr["void"]()], ["setOptionsCantChange", xdr["void"]()], ["setOptionsUnknownFlag", xdr["void"]()], ["setOptionsThresholdOutOfRange", xdr["void"]()], ["setOptionsBadSigner", xdr["void"]()], ["setOptionsInvalidHomeDomain", xdr["void"]()], ["setOptionsAuthRevocableRequired", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ChangeTrustResultCode + // { + // // codes considered as "success" for the operation + // CHANGE_TRUST_SUCCESS = 0, + // // codes considered as "failure" for the operation + // CHANGE_TRUST_MALFORMED = -1, // bad input + // CHANGE_TRUST_NO_ISSUER = -2, // could not find issuer + // CHANGE_TRUST_INVALID_LIMIT = -3, // cannot drop limit below balance + // // cannot create with a limit of 0 + // CHANGE_TRUST_LOW_RESERVE = + // -4, // not enough funds to create a new trust line, + // CHANGE_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed + // CHANGE_TRUST_TRUST_LINE_MISSING = -6, // Asset trustline is missing for pool + // CHANGE_TRUST_CANNOT_DELETE = + // -7, // Asset trustline is still referenced in a pool + // CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES = + // -8 // Asset trustline is deauthorized + // }; + // + // =========================================================================== + xdr["enum"]("ChangeTrustResultCode", { + changeTrustSuccess: 0, + changeTrustMalformed: -1, + changeTrustNoIssuer: -2, + changeTrustInvalidLimit: -3, + changeTrustLowReserve: -4, + changeTrustSelfNotAllowed: -5, + changeTrustTrustLineMissing: -6, + changeTrustCannotDelete: -7, + changeTrustNotAuthMaintainLiabilities: -8 + }); + + // === xdr source ============================================================ + // + // union ChangeTrustResult switch (ChangeTrustResultCode code) + // { + // case CHANGE_TRUST_SUCCESS: + // void; + // case CHANGE_TRUST_MALFORMED: + // case CHANGE_TRUST_NO_ISSUER: + // case CHANGE_TRUST_INVALID_LIMIT: + // case CHANGE_TRUST_LOW_RESERVE: + // case CHANGE_TRUST_SELF_NOT_ALLOWED: + // case CHANGE_TRUST_TRUST_LINE_MISSING: + // case CHANGE_TRUST_CANNOT_DELETE: + // case CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES: + // void; + // }; + // + // =========================================================================== + xdr.union("ChangeTrustResult", { + switchOn: xdr.lookup("ChangeTrustResultCode"), + switchName: "code", + switches: [["changeTrustSuccess", xdr["void"]()], ["changeTrustMalformed", xdr["void"]()], ["changeTrustNoIssuer", xdr["void"]()], ["changeTrustInvalidLimit", xdr["void"]()], ["changeTrustLowReserve", xdr["void"]()], ["changeTrustSelfNotAllowed", xdr["void"]()], ["changeTrustTrustLineMissing", xdr["void"]()], ["changeTrustCannotDelete", xdr["void"]()], ["changeTrustNotAuthMaintainLiabilities", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum AllowTrustResultCode + // { + // // codes considered as "success" for the operation + // ALLOW_TRUST_SUCCESS = 0, + // // codes considered as "failure" for the operation + // ALLOW_TRUST_MALFORMED = -1, // asset is not ASSET_TYPE_ALPHANUM + // ALLOW_TRUST_NO_TRUST_LINE = -2, // trustor does not have a trustline + // // source account does not require trust + // ALLOW_TRUST_TRUST_NOT_REQUIRED = -3, + // ALLOW_TRUST_CANT_REVOKE = -4, // source account can't revoke trust, + // ALLOW_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed + // ALLOW_TRUST_LOW_RESERVE = -6 // claimable balances can't be created + // // on revoke due to low reserves + // }; + // + // =========================================================================== + xdr["enum"]("AllowTrustResultCode", { + allowTrustSuccess: 0, + allowTrustMalformed: -1, + allowTrustNoTrustLine: -2, + allowTrustTrustNotRequired: -3, + allowTrustCantRevoke: -4, + allowTrustSelfNotAllowed: -5, + allowTrustLowReserve: -6 + }); + + // === xdr source ============================================================ + // + // union AllowTrustResult switch (AllowTrustResultCode code) + // { + // case ALLOW_TRUST_SUCCESS: + // void; + // case ALLOW_TRUST_MALFORMED: + // case ALLOW_TRUST_NO_TRUST_LINE: + // case ALLOW_TRUST_TRUST_NOT_REQUIRED: + // case ALLOW_TRUST_CANT_REVOKE: + // case ALLOW_TRUST_SELF_NOT_ALLOWED: + // case ALLOW_TRUST_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("AllowTrustResult", { + switchOn: xdr.lookup("AllowTrustResultCode"), + switchName: "code", + switches: [["allowTrustSuccess", xdr["void"]()], ["allowTrustMalformed", xdr["void"]()], ["allowTrustNoTrustLine", xdr["void"]()], ["allowTrustTrustNotRequired", xdr["void"]()], ["allowTrustCantRevoke", xdr["void"]()], ["allowTrustSelfNotAllowed", xdr["void"]()], ["allowTrustLowReserve", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum AccountMergeResultCode + // { + // // codes considered as "success" for the operation + // ACCOUNT_MERGE_SUCCESS = 0, + // // codes considered as "failure" for the operation + // ACCOUNT_MERGE_MALFORMED = -1, // can't merge onto itself + // ACCOUNT_MERGE_NO_ACCOUNT = -2, // destination does not exist + // ACCOUNT_MERGE_IMMUTABLE_SET = -3, // source account has AUTH_IMMUTABLE set + // ACCOUNT_MERGE_HAS_SUB_ENTRIES = -4, // account has trust lines/offers + // ACCOUNT_MERGE_SEQNUM_TOO_FAR = -5, // sequence number is over max allowed + // ACCOUNT_MERGE_DEST_FULL = -6, // can't add source balance to + // // destination balance + // ACCOUNT_MERGE_IS_SPONSOR = -7 // can't merge account that is a sponsor + // }; + // + // =========================================================================== + xdr["enum"]("AccountMergeResultCode", { + accountMergeSuccess: 0, + accountMergeMalformed: -1, + accountMergeNoAccount: -2, + accountMergeImmutableSet: -3, + accountMergeHasSubEntries: -4, + accountMergeSeqnumTooFar: -5, + accountMergeDestFull: -6, + accountMergeIsSponsor: -7 + }); + + // === xdr source ============================================================ + // + // union AccountMergeResult switch (AccountMergeResultCode code) + // { + // case ACCOUNT_MERGE_SUCCESS: + // int64 sourceAccountBalance; // how much got transferred from source account + // case ACCOUNT_MERGE_MALFORMED: + // case ACCOUNT_MERGE_NO_ACCOUNT: + // case ACCOUNT_MERGE_IMMUTABLE_SET: + // case ACCOUNT_MERGE_HAS_SUB_ENTRIES: + // case ACCOUNT_MERGE_SEQNUM_TOO_FAR: + // case ACCOUNT_MERGE_DEST_FULL: + // case ACCOUNT_MERGE_IS_SPONSOR: + // void; + // }; + // + // =========================================================================== + xdr.union("AccountMergeResult", { + switchOn: xdr.lookup("AccountMergeResultCode"), + switchName: "code", + switches: [["accountMergeSuccess", "sourceAccountBalance"], ["accountMergeMalformed", xdr["void"]()], ["accountMergeNoAccount", xdr["void"]()], ["accountMergeImmutableSet", xdr["void"]()], ["accountMergeHasSubEntries", xdr["void"]()], ["accountMergeSeqnumTooFar", xdr["void"]()], ["accountMergeDestFull", xdr["void"]()], ["accountMergeIsSponsor", xdr["void"]()]], + arms: { + sourceAccountBalance: xdr.lookup("Int64") + } + }); + + // === xdr source ============================================================ + // + // enum InflationResultCode + // { + // // codes considered as "success" for the operation + // INFLATION_SUCCESS = 0, + // // codes considered as "failure" for the operation + // INFLATION_NOT_TIME = -1 + // }; + // + // =========================================================================== + xdr["enum"]("InflationResultCode", { + inflationSuccess: 0, + inflationNotTime: -1 + }); + + // === xdr source ============================================================ + // + // struct InflationPayout // or use PaymentResultAtom to limit types? + // { + // AccountID destination; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("InflationPayout", [["destination", xdr.lookup("AccountId")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union InflationResult switch (InflationResultCode code) + // { + // case INFLATION_SUCCESS: + // InflationPayout payouts<>; + // case INFLATION_NOT_TIME: + // void; + // }; + // + // =========================================================================== + xdr.union("InflationResult", { + switchOn: xdr.lookup("InflationResultCode"), + switchName: "code", + switches: [["inflationSuccess", "payouts"], ["inflationNotTime", xdr["void"]()]], + arms: { + payouts: xdr.varArray(xdr.lookup("InflationPayout"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // enum ManageDataResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_DATA_SUCCESS = 0, + // // codes considered as "failure" for the operation + // MANAGE_DATA_NOT_SUPPORTED_YET = + // -1, // The network hasn't moved to this protocol change yet + // MANAGE_DATA_NAME_NOT_FOUND = + // -2, // Trying to remove a Data Entry that isn't there + // MANAGE_DATA_LOW_RESERVE = -3, // not enough funds to create a new Data Entry + // MANAGE_DATA_INVALID_NAME = -4 // Name not a valid string + // }; + // + // =========================================================================== + xdr["enum"]("ManageDataResultCode", { + manageDataSuccess: 0, + manageDataNotSupportedYet: -1, + manageDataNameNotFound: -2, + manageDataLowReserve: -3, + manageDataInvalidName: -4 + }); + + // === xdr source ============================================================ + // + // union ManageDataResult switch (ManageDataResultCode code) + // { + // case MANAGE_DATA_SUCCESS: + // void; + // case MANAGE_DATA_NOT_SUPPORTED_YET: + // case MANAGE_DATA_NAME_NOT_FOUND: + // case MANAGE_DATA_LOW_RESERVE: + // case MANAGE_DATA_INVALID_NAME: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageDataResult", { + switchOn: xdr.lookup("ManageDataResultCode"), + switchName: "code", + switches: [["manageDataSuccess", xdr["void"]()], ["manageDataNotSupportedYet", xdr["void"]()], ["manageDataNameNotFound", xdr["void"]()], ["manageDataLowReserve", xdr["void"]()], ["manageDataInvalidName", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum BumpSequenceResultCode + // { + // // codes considered as "success" for the operation + // BUMP_SEQUENCE_SUCCESS = 0, + // // codes considered as "failure" for the operation + // BUMP_SEQUENCE_BAD_SEQ = -1 // `bumpTo` is not within bounds + // }; + // + // =========================================================================== + xdr["enum"]("BumpSequenceResultCode", { + bumpSequenceSuccess: 0, + bumpSequenceBadSeq: -1 + }); + + // === xdr source ============================================================ + // + // union BumpSequenceResult switch (BumpSequenceResultCode code) + // { + // case BUMP_SEQUENCE_SUCCESS: + // void; + // case BUMP_SEQUENCE_BAD_SEQ: + // void; + // }; + // + // =========================================================================== + xdr.union("BumpSequenceResult", { + switchOn: xdr.lookup("BumpSequenceResultCode"), + switchName: "code", + switches: [["bumpSequenceSuccess", xdr["void"]()], ["bumpSequenceBadSeq", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum CreateClaimableBalanceResultCode + // { + // CREATE_CLAIMABLE_BALANCE_SUCCESS = 0, + // CREATE_CLAIMABLE_BALANCE_MALFORMED = -1, + // CREATE_CLAIMABLE_BALANCE_LOW_RESERVE = -2, + // CREATE_CLAIMABLE_BALANCE_NO_TRUST = -3, + // CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -4, + // CREATE_CLAIMABLE_BALANCE_UNDERFUNDED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("CreateClaimableBalanceResultCode", { + createClaimableBalanceSuccess: 0, + createClaimableBalanceMalformed: -1, + createClaimableBalanceLowReserve: -2, + createClaimableBalanceNoTrust: -3, + createClaimableBalanceNotAuthorized: -4, + createClaimableBalanceUnderfunded: -5 + }); + + // === xdr source ============================================================ + // + // union CreateClaimableBalanceResult switch ( + // CreateClaimableBalanceResultCode code) + // { + // case CREATE_CLAIMABLE_BALANCE_SUCCESS: + // ClaimableBalanceID balanceID; + // case CREATE_CLAIMABLE_BALANCE_MALFORMED: + // case CREATE_CLAIMABLE_BALANCE_LOW_RESERVE: + // case CREATE_CLAIMABLE_BALANCE_NO_TRUST: + // case CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED: + // case CREATE_CLAIMABLE_BALANCE_UNDERFUNDED: + // void; + // }; + // + // =========================================================================== + xdr.union("CreateClaimableBalanceResult", { + switchOn: xdr.lookup("CreateClaimableBalanceResultCode"), + switchName: "code", + switches: [["createClaimableBalanceSuccess", "balanceId"], ["createClaimableBalanceMalformed", xdr["void"]()], ["createClaimableBalanceLowReserve", xdr["void"]()], ["createClaimableBalanceNoTrust", xdr["void"]()], ["createClaimableBalanceNotAuthorized", xdr["void"]()], ["createClaimableBalanceUnderfunded", xdr["void"]()]], + arms: { + balanceId: xdr.lookup("ClaimableBalanceId") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimClaimableBalanceResultCode + // { + // CLAIM_CLAIMABLE_BALANCE_SUCCESS = 0, + // CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1, + // CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM = -2, + // CLAIM_CLAIMABLE_BALANCE_LINE_FULL = -3, + // CLAIM_CLAIMABLE_BALANCE_NO_TRUST = -4, + // CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimClaimableBalanceResultCode", { + claimClaimableBalanceSuccess: 0, + claimClaimableBalanceDoesNotExist: -1, + claimClaimableBalanceCannotClaim: -2, + claimClaimableBalanceLineFull: -3, + claimClaimableBalanceNoTrust: -4, + claimClaimableBalanceNotAuthorized: -5 + }); + + // === xdr source ============================================================ + // + // union ClaimClaimableBalanceResult switch (ClaimClaimableBalanceResultCode code) + // { + // case CLAIM_CLAIMABLE_BALANCE_SUCCESS: + // void; + // case CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST: + // case CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM: + // case CLAIM_CLAIMABLE_BALANCE_LINE_FULL: + // case CLAIM_CLAIMABLE_BALANCE_NO_TRUST: + // case CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClaimClaimableBalanceResult", { + switchOn: xdr.lookup("ClaimClaimableBalanceResultCode"), + switchName: "code", + switches: [["claimClaimableBalanceSuccess", xdr["void"]()], ["claimClaimableBalanceDoesNotExist", xdr["void"]()], ["claimClaimableBalanceCannotClaim", xdr["void"]()], ["claimClaimableBalanceLineFull", xdr["void"]()], ["claimClaimableBalanceNoTrust", xdr["void"]()], ["claimClaimableBalanceNotAuthorized", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum BeginSponsoringFutureReservesResultCode + // { + // // codes considered as "success" for the operation + // BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED = -1, + // BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED = -2, + // BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("BeginSponsoringFutureReservesResultCode", { + beginSponsoringFutureReservesSuccess: 0, + beginSponsoringFutureReservesMalformed: -1, + beginSponsoringFutureReservesAlreadySponsored: -2, + beginSponsoringFutureReservesRecursive: -3 + }); + + // === xdr source ============================================================ + // + // union BeginSponsoringFutureReservesResult switch ( + // BeginSponsoringFutureReservesResultCode code) + // { + // case BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS: + // void; + // case BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED: + // case BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED: + // case BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE: + // void; + // }; + // + // =========================================================================== + xdr.union("BeginSponsoringFutureReservesResult", { + switchOn: xdr.lookup("BeginSponsoringFutureReservesResultCode"), + switchName: "code", + switches: [["beginSponsoringFutureReservesSuccess", xdr["void"]()], ["beginSponsoringFutureReservesMalformed", xdr["void"]()], ["beginSponsoringFutureReservesAlreadySponsored", xdr["void"]()], ["beginSponsoringFutureReservesRecursive", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum EndSponsoringFutureReservesResultCode + // { + // // codes considered as "success" for the operation + // END_SPONSORING_FUTURE_RESERVES_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED = -1 + // }; + // + // =========================================================================== + xdr["enum"]("EndSponsoringFutureReservesResultCode", { + endSponsoringFutureReservesSuccess: 0, + endSponsoringFutureReservesNotSponsored: -1 + }); + + // === xdr source ============================================================ + // + // union EndSponsoringFutureReservesResult switch ( + // EndSponsoringFutureReservesResultCode code) + // { + // case END_SPONSORING_FUTURE_RESERVES_SUCCESS: + // void; + // case END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED: + // void; + // }; + // + // =========================================================================== + xdr.union("EndSponsoringFutureReservesResult", { + switchOn: xdr.lookup("EndSponsoringFutureReservesResultCode"), + switchName: "code", + switches: [["endSponsoringFutureReservesSuccess", xdr["void"]()], ["endSponsoringFutureReservesNotSponsored", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum RevokeSponsorshipResultCode + // { + // // codes considered as "success" for the operation + // REVOKE_SPONSORSHIP_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // REVOKE_SPONSORSHIP_DOES_NOT_EXIST = -1, + // REVOKE_SPONSORSHIP_NOT_SPONSOR = -2, + // REVOKE_SPONSORSHIP_LOW_RESERVE = -3, + // REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE = -4, + // REVOKE_SPONSORSHIP_MALFORMED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("RevokeSponsorshipResultCode", { + revokeSponsorshipSuccess: 0, + revokeSponsorshipDoesNotExist: -1, + revokeSponsorshipNotSponsor: -2, + revokeSponsorshipLowReserve: -3, + revokeSponsorshipOnlyTransferable: -4, + revokeSponsorshipMalformed: -5 + }); + + // === xdr source ============================================================ + // + // union RevokeSponsorshipResult switch (RevokeSponsorshipResultCode code) + // { + // case REVOKE_SPONSORSHIP_SUCCESS: + // void; + // case REVOKE_SPONSORSHIP_DOES_NOT_EXIST: + // case REVOKE_SPONSORSHIP_NOT_SPONSOR: + // case REVOKE_SPONSORSHIP_LOW_RESERVE: + // case REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE: + // case REVOKE_SPONSORSHIP_MALFORMED: + // void; + // }; + // + // =========================================================================== + xdr.union("RevokeSponsorshipResult", { + switchOn: xdr.lookup("RevokeSponsorshipResultCode"), + switchName: "code", + switches: [["revokeSponsorshipSuccess", xdr["void"]()], ["revokeSponsorshipDoesNotExist", xdr["void"]()], ["revokeSponsorshipNotSponsor", xdr["void"]()], ["revokeSponsorshipLowReserve", xdr["void"]()], ["revokeSponsorshipOnlyTransferable", xdr["void"]()], ["revokeSponsorshipMalformed", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ClawbackResultCode + // { + // // codes considered as "success" for the operation + // CLAWBACK_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // CLAWBACK_MALFORMED = -1, + // CLAWBACK_NOT_CLAWBACK_ENABLED = -2, + // CLAWBACK_NO_TRUST = -3, + // CLAWBACK_UNDERFUNDED = -4 + // }; + // + // =========================================================================== + xdr["enum"]("ClawbackResultCode", { + clawbackSuccess: 0, + clawbackMalformed: -1, + clawbackNotClawbackEnabled: -2, + clawbackNoTrust: -3, + clawbackUnderfunded: -4 + }); + + // === xdr source ============================================================ + // + // union ClawbackResult switch (ClawbackResultCode code) + // { + // case CLAWBACK_SUCCESS: + // void; + // case CLAWBACK_MALFORMED: + // case CLAWBACK_NOT_CLAWBACK_ENABLED: + // case CLAWBACK_NO_TRUST: + // case CLAWBACK_UNDERFUNDED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClawbackResult", { + switchOn: xdr.lookup("ClawbackResultCode"), + switchName: "code", + switches: [["clawbackSuccess", xdr["void"]()], ["clawbackMalformed", xdr["void"]()], ["clawbackNotClawbackEnabled", xdr["void"]()], ["clawbackNoTrust", xdr["void"]()], ["clawbackUnderfunded", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ClawbackClaimableBalanceResultCode + // { + // // codes considered as "success" for the operation + // CLAWBACK_CLAIMABLE_BALANCE_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1, + // CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER = -2, + // CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED = -3 + // }; + // + // =========================================================================== + xdr["enum"]("ClawbackClaimableBalanceResultCode", { + clawbackClaimableBalanceSuccess: 0, + clawbackClaimableBalanceDoesNotExist: -1, + clawbackClaimableBalanceNotIssuer: -2, + clawbackClaimableBalanceNotClawbackEnabled: -3 + }); + + // === xdr source ============================================================ + // + // union ClawbackClaimableBalanceResult switch ( + // ClawbackClaimableBalanceResultCode code) + // { + // case CLAWBACK_CLAIMABLE_BALANCE_SUCCESS: + // void; + // case CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST: + // case CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER: + // case CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClawbackClaimableBalanceResult", { + switchOn: xdr.lookup("ClawbackClaimableBalanceResultCode"), + switchName: "code", + switches: [["clawbackClaimableBalanceSuccess", xdr["void"]()], ["clawbackClaimableBalanceDoesNotExist", xdr["void"]()], ["clawbackClaimableBalanceNotIssuer", xdr["void"]()], ["clawbackClaimableBalanceNotClawbackEnabled", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum SetTrustLineFlagsResultCode + // { + // // codes considered as "success" for the operation + // SET_TRUST_LINE_FLAGS_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // SET_TRUST_LINE_FLAGS_MALFORMED = -1, + // SET_TRUST_LINE_FLAGS_NO_TRUST_LINE = -2, + // SET_TRUST_LINE_FLAGS_CANT_REVOKE = -3, + // SET_TRUST_LINE_FLAGS_INVALID_STATE = -4, + // SET_TRUST_LINE_FLAGS_LOW_RESERVE = -5 // claimable balances can't be created + // // on revoke due to low reserves + // }; + // + // =========================================================================== + xdr["enum"]("SetTrustLineFlagsResultCode", { + setTrustLineFlagsSuccess: 0, + setTrustLineFlagsMalformed: -1, + setTrustLineFlagsNoTrustLine: -2, + setTrustLineFlagsCantRevoke: -3, + setTrustLineFlagsInvalidState: -4, + setTrustLineFlagsLowReserve: -5 + }); + + // === xdr source ============================================================ + // + // union SetTrustLineFlagsResult switch (SetTrustLineFlagsResultCode code) + // { + // case SET_TRUST_LINE_FLAGS_SUCCESS: + // void; + // case SET_TRUST_LINE_FLAGS_MALFORMED: + // case SET_TRUST_LINE_FLAGS_NO_TRUST_LINE: + // case SET_TRUST_LINE_FLAGS_CANT_REVOKE: + // case SET_TRUST_LINE_FLAGS_INVALID_STATE: + // case SET_TRUST_LINE_FLAGS_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("SetTrustLineFlagsResult", { + switchOn: xdr.lookup("SetTrustLineFlagsResultCode"), + switchName: "code", + switches: [["setTrustLineFlagsSuccess", xdr["void"]()], ["setTrustLineFlagsMalformed", xdr["void"]()], ["setTrustLineFlagsNoTrustLine", xdr["void"]()], ["setTrustLineFlagsCantRevoke", xdr["void"]()], ["setTrustLineFlagsInvalidState", xdr["void"]()], ["setTrustLineFlagsLowReserve", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum LiquidityPoolDepositResultCode + // { + // // codes considered as "success" for the operation + // LIQUIDITY_POOL_DEPOSIT_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // LIQUIDITY_POOL_DEPOSIT_MALFORMED = -1, // bad input + // LIQUIDITY_POOL_DEPOSIT_NO_TRUST = -2, // no trust line for one of the + // // assets + // LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED = -3, // not authorized for one of the + // // assets + // LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED = -4, // not enough balance for one of + // // the assets + // LIQUIDITY_POOL_DEPOSIT_LINE_FULL = -5, // pool share trust line doesn't + // // have sufficient limit + // LIQUIDITY_POOL_DEPOSIT_BAD_PRICE = -6, // deposit price outside bounds + // LIQUIDITY_POOL_DEPOSIT_POOL_FULL = -7 // pool reserves are full + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolDepositResultCode", { + liquidityPoolDepositSuccess: 0, + liquidityPoolDepositMalformed: -1, + liquidityPoolDepositNoTrust: -2, + liquidityPoolDepositNotAuthorized: -3, + liquidityPoolDepositUnderfunded: -4, + liquidityPoolDepositLineFull: -5, + liquidityPoolDepositBadPrice: -6, + liquidityPoolDepositPoolFull: -7 + }); + + // === xdr source ============================================================ + // + // union LiquidityPoolDepositResult switch (LiquidityPoolDepositResultCode code) + // { + // case LIQUIDITY_POOL_DEPOSIT_SUCCESS: + // void; + // case LIQUIDITY_POOL_DEPOSIT_MALFORMED: + // case LIQUIDITY_POOL_DEPOSIT_NO_TRUST: + // case LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED: + // case LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED: + // case LIQUIDITY_POOL_DEPOSIT_LINE_FULL: + // case LIQUIDITY_POOL_DEPOSIT_BAD_PRICE: + // case LIQUIDITY_POOL_DEPOSIT_POOL_FULL: + // void; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolDepositResult", { + switchOn: xdr.lookup("LiquidityPoolDepositResultCode"), + switchName: "code", + switches: [["liquidityPoolDepositSuccess", xdr["void"]()], ["liquidityPoolDepositMalformed", xdr["void"]()], ["liquidityPoolDepositNoTrust", xdr["void"]()], ["liquidityPoolDepositNotAuthorized", xdr["void"]()], ["liquidityPoolDepositUnderfunded", xdr["void"]()], ["liquidityPoolDepositLineFull", xdr["void"]()], ["liquidityPoolDepositBadPrice", xdr["void"]()], ["liquidityPoolDepositPoolFull", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum LiquidityPoolWithdrawResultCode + // { + // // codes considered as "success" for the operation + // LIQUIDITY_POOL_WITHDRAW_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // LIQUIDITY_POOL_WITHDRAW_MALFORMED = -1, // bad input + // LIQUIDITY_POOL_WITHDRAW_NO_TRUST = -2, // no trust line for one of the + // // assets + // LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED = -3, // not enough balance of the + // // pool share + // LIQUIDITY_POOL_WITHDRAW_LINE_FULL = -4, // would go above limit for one + // // of the assets + // LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM = -5 // didn't withdraw enough + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolWithdrawResultCode", { + liquidityPoolWithdrawSuccess: 0, + liquidityPoolWithdrawMalformed: -1, + liquidityPoolWithdrawNoTrust: -2, + liquidityPoolWithdrawUnderfunded: -3, + liquidityPoolWithdrawLineFull: -4, + liquidityPoolWithdrawUnderMinimum: -5 + }); + + // === xdr source ============================================================ + // + // union LiquidityPoolWithdrawResult switch (LiquidityPoolWithdrawResultCode code) + // { + // case LIQUIDITY_POOL_WITHDRAW_SUCCESS: + // void; + // case LIQUIDITY_POOL_WITHDRAW_MALFORMED: + // case LIQUIDITY_POOL_WITHDRAW_NO_TRUST: + // case LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED: + // case LIQUIDITY_POOL_WITHDRAW_LINE_FULL: + // case LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM: + // void; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolWithdrawResult", { + switchOn: xdr.lookup("LiquidityPoolWithdrawResultCode"), + switchName: "code", + switches: [["liquidityPoolWithdrawSuccess", xdr["void"]()], ["liquidityPoolWithdrawMalformed", xdr["void"]()], ["liquidityPoolWithdrawNoTrust", xdr["void"]()], ["liquidityPoolWithdrawUnderfunded", xdr["void"]()], ["liquidityPoolWithdrawLineFull", xdr["void"]()], ["liquidityPoolWithdrawUnderMinimum", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum InvokeHostFunctionResultCode + // { + // // codes considered as "success" for the operation + // INVOKE_HOST_FUNCTION_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // INVOKE_HOST_FUNCTION_MALFORMED = -1, + // INVOKE_HOST_FUNCTION_TRAPPED = -2, + // INVOKE_HOST_FUNCTION_RESOURCE_LIMIT_EXCEEDED = -3, + // INVOKE_HOST_FUNCTION_ENTRY_ARCHIVED = -4, + // INVOKE_HOST_FUNCTION_INSUFFICIENT_REFUNDABLE_FEE = -5 + // }; + // + // =========================================================================== + xdr["enum"]("InvokeHostFunctionResultCode", { + invokeHostFunctionSuccess: 0, + invokeHostFunctionMalformed: -1, + invokeHostFunctionTrapped: -2, + invokeHostFunctionResourceLimitExceeded: -3, + invokeHostFunctionEntryArchived: -4, + invokeHostFunctionInsufficientRefundableFee: -5 + }); + + // === xdr source ============================================================ + // + // union InvokeHostFunctionResult switch (InvokeHostFunctionResultCode code) + // { + // case INVOKE_HOST_FUNCTION_SUCCESS: + // Hash success; // sha256(InvokeHostFunctionSuccessPreImage) + // case INVOKE_HOST_FUNCTION_MALFORMED: + // case INVOKE_HOST_FUNCTION_TRAPPED: + // case INVOKE_HOST_FUNCTION_RESOURCE_LIMIT_EXCEEDED: + // case INVOKE_HOST_FUNCTION_ENTRY_ARCHIVED: + // case INVOKE_HOST_FUNCTION_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("InvokeHostFunctionResult", { + switchOn: xdr.lookup("InvokeHostFunctionResultCode"), + switchName: "code", + switches: [["invokeHostFunctionSuccess", "success"], ["invokeHostFunctionMalformed", xdr["void"]()], ["invokeHostFunctionTrapped", xdr["void"]()], ["invokeHostFunctionResourceLimitExceeded", xdr["void"]()], ["invokeHostFunctionEntryArchived", xdr["void"]()], ["invokeHostFunctionInsufficientRefundableFee", xdr["void"]()]], + arms: { + success: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum ExtendFootprintTTLResultCode + // { + // // codes considered as "success" for the operation + // EXTEND_FOOTPRINT_TTL_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // EXTEND_FOOTPRINT_TTL_MALFORMED = -1, + // EXTEND_FOOTPRINT_TTL_RESOURCE_LIMIT_EXCEEDED = -2, + // EXTEND_FOOTPRINT_TTL_INSUFFICIENT_REFUNDABLE_FEE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("ExtendFootprintTtlResultCode", { + extendFootprintTtlSuccess: 0, + extendFootprintTtlMalformed: -1, + extendFootprintTtlResourceLimitExceeded: -2, + extendFootprintTtlInsufficientRefundableFee: -3 + }); + + // === xdr source ============================================================ + // + // union ExtendFootprintTTLResult switch (ExtendFootprintTTLResultCode code) + // { + // case EXTEND_FOOTPRINT_TTL_SUCCESS: + // void; + // case EXTEND_FOOTPRINT_TTL_MALFORMED: + // case EXTEND_FOOTPRINT_TTL_RESOURCE_LIMIT_EXCEEDED: + // case EXTEND_FOOTPRINT_TTL_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("ExtendFootprintTtlResult", { + switchOn: xdr.lookup("ExtendFootprintTtlResultCode"), + switchName: "code", + switches: [["extendFootprintTtlSuccess", xdr["void"]()], ["extendFootprintTtlMalformed", xdr["void"]()], ["extendFootprintTtlResourceLimitExceeded", xdr["void"]()], ["extendFootprintTtlInsufficientRefundableFee", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum RestoreFootprintResultCode + // { + // // codes considered as "success" for the operation + // RESTORE_FOOTPRINT_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // RESTORE_FOOTPRINT_MALFORMED = -1, + // RESTORE_FOOTPRINT_RESOURCE_LIMIT_EXCEEDED = -2, + // RESTORE_FOOTPRINT_INSUFFICIENT_REFUNDABLE_FEE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("RestoreFootprintResultCode", { + restoreFootprintSuccess: 0, + restoreFootprintMalformed: -1, + restoreFootprintResourceLimitExceeded: -2, + restoreFootprintInsufficientRefundableFee: -3 + }); + + // === xdr source ============================================================ + // + // union RestoreFootprintResult switch (RestoreFootprintResultCode code) + // { + // case RESTORE_FOOTPRINT_SUCCESS: + // void; + // case RESTORE_FOOTPRINT_MALFORMED: + // case RESTORE_FOOTPRINT_RESOURCE_LIMIT_EXCEEDED: + // case RESTORE_FOOTPRINT_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("RestoreFootprintResult", { + switchOn: xdr.lookup("RestoreFootprintResultCode"), + switchName: "code", + switches: [["restoreFootprintSuccess", xdr["void"]()], ["restoreFootprintMalformed", xdr["void"]()], ["restoreFootprintResourceLimitExceeded", xdr["void"]()], ["restoreFootprintInsufficientRefundableFee", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum OperationResultCode + // { + // opINNER = 0, // inner object result is valid + // + // opBAD_AUTH = -1, // too few valid signatures / wrong network + // opNO_ACCOUNT = -2, // source account was not found + // opNOT_SUPPORTED = -3, // operation not supported at this time + // opTOO_MANY_SUBENTRIES = -4, // max number of subentries already reached + // opEXCEEDED_WORK_LIMIT = -5, // operation did too much work + // opTOO_MANY_SPONSORING = -6 // account is sponsoring too many entries + // }; + // + // =========================================================================== + xdr["enum"]("OperationResultCode", { + opInner: 0, + opBadAuth: -1, + opNoAccount: -2, + opNotSupported: -3, + opTooManySubentries: -4, + opExceededWorkLimit: -5, + opTooManySponsoring: -6 + }); + + // === xdr source ============================================================ + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountResult createAccountResult; + // case PAYMENT: + // PaymentResult paymentResult; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult; + // case MANAGE_SELL_OFFER: + // ManageSellOfferResult manageSellOfferResult; + // case CREATE_PASSIVE_SELL_OFFER: + // ManageSellOfferResult createPassiveSellOfferResult; + // case SET_OPTIONS: + // SetOptionsResult setOptionsResult; + // case CHANGE_TRUST: + // ChangeTrustResult changeTrustResult; + // case ALLOW_TRUST: + // AllowTrustResult allowTrustResult; + // case ACCOUNT_MERGE: + // AccountMergeResult accountMergeResult; + // case INFLATION: + // InflationResult inflationResult; + // case MANAGE_DATA: + // ManageDataResult manageDataResult; + // case BUMP_SEQUENCE: + // BumpSequenceResult bumpSeqResult; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferResult manageBuyOfferResult; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendResult pathPaymentStrictSendResult; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceResult createClaimableBalanceResult; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceResult claimClaimableBalanceResult; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult; + // case END_SPONSORING_FUTURE_RESERVES: + // EndSponsoringFutureReservesResult endSponsoringFutureReservesResult; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipResult revokeSponsorshipResult; + // case CLAWBACK: + // ClawbackResult clawbackResult; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceResult clawbackClaimableBalanceResult; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsResult setTrustLineFlagsResult; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositResult liquidityPoolDepositResult; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawResult liquidityPoolWithdrawResult; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionResult invokeHostFunctionResult; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLResult extendFootprintTTLResult; + // case RESTORE_FOOTPRINT: + // RestoreFootprintResult restoreFootprintResult; + // } + // + // =========================================================================== + xdr.union("OperationResultTr", { + switchOn: xdr.lookup("OperationType"), + switchName: "type", + switches: [["createAccount", "createAccountResult"], ["payment", "paymentResult"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveResult"], ["manageSellOffer", "manageSellOfferResult"], ["createPassiveSellOffer", "createPassiveSellOfferResult"], ["setOptions", "setOptionsResult"], ["changeTrust", "changeTrustResult"], ["allowTrust", "allowTrustResult"], ["accountMerge", "accountMergeResult"], ["inflation", "inflationResult"], ["manageData", "manageDataResult"], ["bumpSequence", "bumpSeqResult"], ["manageBuyOffer", "manageBuyOfferResult"], ["pathPaymentStrictSend", "pathPaymentStrictSendResult"], ["createClaimableBalance", "createClaimableBalanceResult"], ["claimClaimableBalance", "claimClaimableBalanceResult"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesResult"], ["endSponsoringFutureReserves", "endSponsoringFutureReservesResult"], ["revokeSponsorship", "revokeSponsorshipResult"], ["clawback", "clawbackResult"], ["clawbackClaimableBalance", "clawbackClaimableBalanceResult"], ["setTrustLineFlags", "setTrustLineFlagsResult"], ["liquidityPoolDeposit", "liquidityPoolDepositResult"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawResult"], ["invokeHostFunction", "invokeHostFunctionResult"], ["extendFootprintTtl", "extendFootprintTtlResult"], ["restoreFootprint", "restoreFootprintResult"]], + arms: { + createAccountResult: xdr.lookup("CreateAccountResult"), + paymentResult: xdr.lookup("PaymentResult"), + pathPaymentStrictReceiveResult: xdr.lookup("PathPaymentStrictReceiveResult"), + manageSellOfferResult: xdr.lookup("ManageSellOfferResult"), + createPassiveSellOfferResult: xdr.lookup("ManageSellOfferResult"), + setOptionsResult: xdr.lookup("SetOptionsResult"), + changeTrustResult: xdr.lookup("ChangeTrustResult"), + allowTrustResult: xdr.lookup("AllowTrustResult"), + accountMergeResult: xdr.lookup("AccountMergeResult"), + inflationResult: xdr.lookup("InflationResult"), + manageDataResult: xdr.lookup("ManageDataResult"), + bumpSeqResult: xdr.lookup("BumpSequenceResult"), + manageBuyOfferResult: xdr.lookup("ManageBuyOfferResult"), + pathPaymentStrictSendResult: xdr.lookup("PathPaymentStrictSendResult"), + createClaimableBalanceResult: xdr.lookup("CreateClaimableBalanceResult"), + claimClaimableBalanceResult: xdr.lookup("ClaimClaimableBalanceResult"), + beginSponsoringFutureReservesResult: xdr.lookup("BeginSponsoringFutureReservesResult"), + endSponsoringFutureReservesResult: xdr.lookup("EndSponsoringFutureReservesResult"), + revokeSponsorshipResult: xdr.lookup("RevokeSponsorshipResult"), + clawbackResult: xdr.lookup("ClawbackResult"), + clawbackClaimableBalanceResult: xdr.lookup("ClawbackClaimableBalanceResult"), + setTrustLineFlagsResult: xdr.lookup("SetTrustLineFlagsResult"), + liquidityPoolDepositResult: xdr.lookup("LiquidityPoolDepositResult"), + liquidityPoolWithdrawResult: xdr.lookup("LiquidityPoolWithdrawResult"), + invokeHostFunctionResult: xdr.lookup("InvokeHostFunctionResult"), + extendFootprintTtlResult: xdr.lookup("ExtendFootprintTtlResult"), + restoreFootprintResult: xdr.lookup("RestoreFootprintResult") + } + }); + + // === xdr source ============================================================ + // + // union OperationResult switch (OperationResultCode code) + // { + // case opINNER: + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountResult createAccountResult; + // case PAYMENT: + // PaymentResult paymentResult; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult; + // case MANAGE_SELL_OFFER: + // ManageSellOfferResult manageSellOfferResult; + // case CREATE_PASSIVE_SELL_OFFER: + // ManageSellOfferResult createPassiveSellOfferResult; + // case SET_OPTIONS: + // SetOptionsResult setOptionsResult; + // case CHANGE_TRUST: + // ChangeTrustResult changeTrustResult; + // case ALLOW_TRUST: + // AllowTrustResult allowTrustResult; + // case ACCOUNT_MERGE: + // AccountMergeResult accountMergeResult; + // case INFLATION: + // InflationResult inflationResult; + // case MANAGE_DATA: + // ManageDataResult manageDataResult; + // case BUMP_SEQUENCE: + // BumpSequenceResult bumpSeqResult; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferResult manageBuyOfferResult; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendResult pathPaymentStrictSendResult; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceResult createClaimableBalanceResult; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceResult claimClaimableBalanceResult; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult; + // case END_SPONSORING_FUTURE_RESERVES: + // EndSponsoringFutureReservesResult endSponsoringFutureReservesResult; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipResult revokeSponsorshipResult; + // case CLAWBACK: + // ClawbackResult clawbackResult; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceResult clawbackClaimableBalanceResult; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsResult setTrustLineFlagsResult; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositResult liquidityPoolDepositResult; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawResult liquidityPoolWithdrawResult; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionResult invokeHostFunctionResult; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLResult extendFootprintTTLResult; + // case RESTORE_FOOTPRINT: + // RestoreFootprintResult restoreFootprintResult; + // } + // tr; + // case opBAD_AUTH: + // case opNO_ACCOUNT: + // case opNOT_SUPPORTED: + // case opTOO_MANY_SUBENTRIES: + // case opEXCEEDED_WORK_LIMIT: + // case opTOO_MANY_SPONSORING: + // void; + // }; + // + // =========================================================================== + xdr.union("OperationResult", { + switchOn: xdr.lookup("OperationResultCode"), + switchName: "code", + switches: [["opInner", "tr"], ["opBadAuth", xdr["void"]()], ["opNoAccount", xdr["void"]()], ["opNotSupported", xdr["void"]()], ["opTooManySubentries", xdr["void"]()], ["opExceededWorkLimit", xdr["void"]()], ["opTooManySponsoring", xdr["void"]()]], + arms: { + tr: xdr.lookup("OperationResultTr") + } + }); + + // === xdr source ============================================================ + // + // enum TransactionResultCode + // { + // txFEE_BUMP_INNER_SUCCESS = 1, // fee bump inner transaction succeeded + // txSUCCESS = 0, // all operations succeeded + // + // txFAILED = -1, // one of the operations failed (none were applied) + // + // txTOO_EARLY = -2, // ledger closeTime before minTime + // txTOO_LATE = -3, // ledger closeTime after maxTime + // txMISSING_OPERATION = -4, // no operation was specified + // txBAD_SEQ = -5, // sequence number does not match source account + // + // txBAD_AUTH = -6, // too few valid signatures / wrong network + // txINSUFFICIENT_BALANCE = -7, // fee would bring account below reserve + // txNO_ACCOUNT = -8, // source account not found + // txINSUFFICIENT_FEE = -9, // fee is too small + // txBAD_AUTH_EXTRA = -10, // unused signatures attached to transaction + // txINTERNAL_ERROR = -11, // an unknown error occurred + // + // txNOT_SUPPORTED = -12, // transaction type not supported + // txFEE_BUMP_INNER_FAILED = -13, // fee bump inner transaction failed + // txBAD_SPONSORSHIP = -14, // sponsorship not confirmed + // txBAD_MIN_SEQ_AGE_OR_GAP = -15, // minSeqAge or minSeqLedgerGap conditions not met + // txMALFORMED = -16, // precondition is invalid + // txSOROBAN_INVALID = -17 // soroban-specific preconditions were not met + // }; + // + // =========================================================================== + xdr["enum"]("TransactionResultCode", { + txFeeBumpInnerSuccess: 1, + txSuccess: 0, + txFailed: -1, + txTooEarly: -2, + txTooLate: -3, + txMissingOperation: -4, + txBadSeq: -5, + txBadAuth: -6, + txInsufficientBalance: -7, + txNoAccount: -8, + txInsufficientFee: -9, + txBadAuthExtra: -10, + txInternalError: -11, + txNotSupported: -12, + txFeeBumpInnerFailed: -13, + txBadSponsorship: -14, + txBadMinSeqAgeOrGap: -15, + txMalformed: -16, + txSorobanInvalid: -17 + }); + + // === xdr source ============================================================ + // + // union switch (TransactionResultCode code) + // { + // // txFEE_BUMP_INNER_SUCCESS is not included + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // txFEE_BUMP_INNER_FAILED is not included + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // + // =========================================================================== + xdr.union("InnerTransactionResultResult", { + switchOn: xdr.lookup("TransactionResultCode"), + switchName: "code", + switches: [["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr["void"]()], ["txTooLate", xdr["void"]()], ["txMissingOperation", xdr["void"]()], ["txBadSeq", xdr["void"]()], ["txBadAuth", xdr["void"]()], ["txInsufficientBalance", xdr["void"]()], ["txNoAccount", xdr["void"]()], ["txInsufficientFee", xdr["void"]()], ["txBadAuthExtra", xdr["void"]()], ["txInternalError", xdr["void"]()], ["txNotSupported", xdr["void"]()], ["txBadSponsorship", xdr["void"]()], ["txBadMinSeqAgeOrGap", xdr["void"]()], ["txMalformed", xdr["void"]()], ["txSorobanInvalid", xdr["void"]()]], + arms: { + results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("InnerTransactionResultExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct InnerTransactionResult + // { + // // Always 0. Here for binary compatibility. + // int64 feeCharged; + // + // union switch (TransactionResultCode code) + // { + // // txFEE_BUMP_INNER_SUCCESS is not included + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // txFEE_BUMP_INNER_FAILED is not included + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // result; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("InnerTransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("InnerTransactionResultResult")], ["ext", xdr.lookup("InnerTransactionResultExt")]]); + + // === xdr source ============================================================ + // + // struct InnerTransactionResultPair + // { + // Hash transactionHash; // hash of the inner transaction + // InnerTransactionResult result; // result for the inner transaction + // }; + // + // =========================================================================== + xdr.struct("InnerTransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("InnerTransactionResult")]]); + + // === xdr source ============================================================ + // + // union switch (TransactionResultCode code) + // { + // case txFEE_BUMP_INNER_SUCCESS: + // case txFEE_BUMP_INNER_FAILED: + // InnerTransactionResultPair innerResultPair; + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // case txFEE_BUMP_INNER_FAILED: handled above + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionResultResult", { + switchOn: xdr.lookup("TransactionResultCode"), + switchName: "code", + switches: [["txFeeBumpInnerSuccess", "innerResultPair"], ["txFeeBumpInnerFailed", "innerResultPair"], ["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr["void"]()], ["txTooLate", xdr["void"]()], ["txMissingOperation", xdr["void"]()], ["txBadSeq", xdr["void"]()], ["txBadAuth", xdr["void"]()], ["txInsufficientBalance", xdr["void"]()], ["txNoAccount", xdr["void"]()], ["txInsufficientFee", xdr["void"]()], ["txBadAuthExtra", xdr["void"]()], ["txInternalError", xdr["void"]()], ["txNotSupported", xdr["void"]()], ["txBadSponsorship", xdr["void"]()], ["txBadMinSeqAgeOrGap", xdr["void"]()], ["txMalformed", xdr["void"]()], ["txSorobanInvalid", xdr["void"]()]], + arms: { + innerResultPair: xdr.lookup("InnerTransactionResultPair"), + results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionResultExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionResult + // { + // int64 feeCharged; // actual fee charged for the transaction + // + // union switch (TransactionResultCode code) + // { + // case txFEE_BUMP_INNER_SUCCESS: + // case txFEE_BUMP_INNER_FAILED: + // InnerTransactionResultPair innerResultPair; + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // case txFEE_BUMP_INNER_FAILED: handled above + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // result; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("TransactionResultResult")], ["ext", xdr.lookup("TransactionResultExt")]]); + + // === xdr source ============================================================ + // + // typedef opaque Hash[32]; + // + // =========================================================================== + xdr.typedef("Hash", xdr.opaque(32)); + + // === xdr source ============================================================ + // + // typedef opaque uint256[32]; + // + // =========================================================================== + xdr.typedef("Uint256", xdr.opaque(32)); + + // === xdr source ============================================================ + // + // typedef unsigned int uint32; + // + // =========================================================================== + xdr.typedef("Uint32", xdr.uint()); + + // === xdr source ============================================================ + // + // typedef int int32; + // + // =========================================================================== + xdr.typedef("Int32", xdr["int"]()); + + // === xdr source ============================================================ + // + // typedef unsigned hyper uint64; + // + // =========================================================================== + xdr.typedef("Uint64", xdr.uhyper()); + + // === xdr source ============================================================ + // + // typedef hyper int64; + // + // =========================================================================== + xdr.typedef("Int64", xdr.hyper()); + + // === xdr source ============================================================ + // + // typedef uint64 TimePoint; + // + // =========================================================================== + xdr.typedef("TimePoint", xdr.lookup("Uint64")); + + // === xdr source ============================================================ + // + // typedef uint64 Duration; + // + // =========================================================================== + xdr.typedef("Duration", xdr.lookup("Uint64")); + + // === xdr source ============================================================ + // + // union ExtensionPoint switch (int v) + // { + // case 0: + // void; + // }; + // + // =========================================================================== + xdr.union("ExtensionPoint", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum CryptoKeyType + // { + // KEY_TYPE_ED25519 = 0, + // KEY_TYPE_PRE_AUTH_TX = 1, + // KEY_TYPE_HASH_X = 2, + // KEY_TYPE_ED25519_SIGNED_PAYLOAD = 3, + // // MUXED enum values for supported type are derived from the enum values + // // above by ORing them with 0x100 + // KEY_TYPE_MUXED_ED25519 = 0x100 + // }; + // + // =========================================================================== + xdr["enum"]("CryptoKeyType", { + keyTypeEd25519: 0, + keyTypePreAuthTx: 1, + keyTypeHashX: 2, + keyTypeEd25519SignedPayload: 3, + keyTypeMuxedEd25519: 256 + }); + + // === xdr source ============================================================ + // + // enum PublicKeyType + // { + // PUBLIC_KEY_TYPE_ED25519 = KEY_TYPE_ED25519 + // }; + // + // =========================================================================== + xdr["enum"]("PublicKeyType", { + publicKeyTypeEd25519: 0 + }); + + // === xdr source ============================================================ + // + // enum SignerKeyType + // { + // SIGNER_KEY_TYPE_ED25519 = KEY_TYPE_ED25519, + // SIGNER_KEY_TYPE_PRE_AUTH_TX = KEY_TYPE_PRE_AUTH_TX, + // SIGNER_KEY_TYPE_HASH_X = KEY_TYPE_HASH_X, + // SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD = KEY_TYPE_ED25519_SIGNED_PAYLOAD + // }; + // + // =========================================================================== + xdr["enum"]("SignerKeyType", { + signerKeyTypeEd25519: 0, + signerKeyTypePreAuthTx: 1, + signerKeyTypeHashX: 2, + signerKeyTypeEd25519SignedPayload: 3 + }); + + // === xdr source ============================================================ + // + // union PublicKey switch (PublicKeyType type) + // { + // case PUBLIC_KEY_TYPE_ED25519: + // uint256 ed25519; + // }; + // + // =========================================================================== + xdr.union("PublicKey", { + switchOn: xdr.lookup("PublicKeyType"), + switchName: "type", + switches: [["publicKeyTypeEd25519", "ed25519"]], + arms: { + ed25519: xdr.lookup("Uint256") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // /* Public key that must sign the payload. */ + // uint256 ed25519; + // /* Payload to be raw signed by ed25519. */ + // opaque payload<64>; + // } + // + // =========================================================================== + xdr.struct("SignerKeyEd25519SignedPayload", [["ed25519", xdr.lookup("Uint256")], ["payload", xdr.varOpaque(64)]]); + + // === xdr source ============================================================ + // + // union SignerKey switch (SignerKeyType type) + // { + // case SIGNER_KEY_TYPE_ED25519: + // uint256 ed25519; + // case SIGNER_KEY_TYPE_PRE_AUTH_TX: + // /* SHA-256 Hash of TransactionSignaturePayload structure */ + // uint256 preAuthTx; + // case SIGNER_KEY_TYPE_HASH_X: + // /* Hash of random 256 bit preimage X */ + // uint256 hashX; + // case SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD: + // struct + // { + // /* Public key that must sign the payload. */ + // uint256 ed25519; + // /* Payload to be raw signed by ed25519. */ + // opaque payload<64>; + // } ed25519SignedPayload; + // }; + // + // =========================================================================== + xdr.union("SignerKey", { + switchOn: xdr.lookup("SignerKeyType"), + switchName: "type", + switches: [["signerKeyTypeEd25519", "ed25519"], ["signerKeyTypePreAuthTx", "preAuthTx"], ["signerKeyTypeHashX", "hashX"], ["signerKeyTypeEd25519SignedPayload", "ed25519SignedPayload"]], + arms: { + ed25519: xdr.lookup("Uint256"), + preAuthTx: xdr.lookup("Uint256"), + hashX: xdr.lookup("Uint256"), + ed25519SignedPayload: xdr.lookup("SignerKeyEd25519SignedPayload") + } + }); + + // === xdr source ============================================================ + // + // typedef opaque Signature<64>; + // + // =========================================================================== + xdr.typedef("Signature", xdr.varOpaque(64)); + + // === xdr source ============================================================ + // + // typedef opaque SignatureHint[4]; + // + // =========================================================================== + xdr.typedef("SignatureHint", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef PublicKey NodeID; + // + // =========================================================================== + xdr.typedef("NodeId", xdr.lookup("PublicKey")); + + // === xdr source ============================================================ + // + // typedef PublicKey AccountID; + // + // =========================================================================== + xdr.typedef("AccountId", xdr.lookup("PublicKey")); + + // === xdr source ============================================================ + // + // struct Curve25519Secret + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("Curve25519Secret", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct Curve25519Public + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("Curve25519Public", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct HmacSha256Key + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("HmacSha256Key", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct HmacSha256Mac + // { + // opaque mac[32]; + // }; + // + // =========================================================================== + xdr.struct("HmacSha256Mac", [["mac", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct ShortHashSeed + // { + // opaque seed[16]; + // }; + // + // =========================================================================== + xdr.struct("ShortHashSeed", [["seed", xdr.opaque(16)]]); + + // === xdr source ============================================================ + // + // enum BinaryFuseFilterType + // { + // BINARY_FUSE_FILTER_8_BIT = 0, + // BINARY_FUSE_FILTER_16_BIT = 1, + // BINARY_FUSE_FILTER_32_BIT = 2 + // }; + // + // =========================================================================== + xdr["enum"]("BinaryFuseFilterType", { + binaryFuseFilter8Bit: 0, + binaryFuseFilter16Bit: 1, + binaryFuseFilter32Bit: 2 + }); + + // === xdr source ============================================================ + // + // struct SerializedBinaryFuseFilter + // { + // BinaryFuseFilterType type; + // + // // Seed used to hash input to filter + // ShortHashSeed inputHashSeed; + // + // // Seed used for internal filter hash operations + // ShortHashSeed filterSeed; + // uint32 segmentLength; + // uint32 segementLengthMask; + // uint32 segmentCount; + // uint32 segmentCountLength; + // uint32 fingerprintLength; // Length in terms of element count, not bytes + // + // // Array of uint8_t, uint16_t, or uint32_t depending on filter type + // opaque fingerprints<>; + // }; + // + // =========================================================================== + xdr.struct("SerializedBinaryFuseFilter", [["type", xdr.lookup("BinaryFuseFilterType")], ["inputHashSeed", xdr.lookup("ShortHashSeed")], ["filterSeed", xdr.lookup("ShortHashSeed")], ["segmentLength", xdr.lookup("Uint32")], ["segementLengthMask", xdr.lookup("Uint32")], ["segmentCount", xdr.lookup("Uint32")], ["segmentCountLength", xdr.lookup("Uint32")], ["fingerprintLength", xdr.lookup("Uint32")], ["fingerprints", xdr.varOpaque()]]); + + // === xdr source ============================================================ + // + // enum SCValType + // { + // SCV_BOOL = 0, + // SCV_VOID = 1, + // SCV_ERROR = 2, + // + // // 32 bits is the smallest type in WASM or XDR; no need for u8/u16. + // SCV_U32 = 3, + // SCV_I32 = 4, + // + // // 64 bits is naturally supported by both WASM and XDR also. + // SCV_U64 = 5, + // SCV_I64 = 6, + // + // // Time-related u64 subtypes with their own functions and formatting. + // SCV_TIMEPOINT = 7, + // SCV_DURATION = 8, + // + // // 128 bits is naturally supported by Rust and we use it for Soroban + // // fixed-point arithmetic prices / balances / similar "quantities". These + // // are represented in XDR as a pair of 2 u64s. + // SCV_U128 = 9, + // SCV_I128 = 10, + // + // // 256 bits is the size of sha256 output, ed25519 keys, and the EVM machine + // // word, so for interop use we include this even though it requires a small + // // amount of Rust guest and/or host library code. + // SCV_U256 = 11, + // SCV_I256 = 12, + // + // // Bytes come in 3 flavors, 2 of which have meaningfully different + // // formatting and validity-checking / domain-restriction. + // SCV_BYTES = 13, + // SCV_STRING = 14, + // SCV_SYMBOL = 15, + // + // // Vecs and maps are just polymorphic containers of other ScVals. + // SCV_VEC = 16, + // SCV_MAP = 17, + // + // // Address is the universal identifier for contracts and classic + // // accounts. + // SCV_ADDRESS = 18, + // + // // The following are the internal SCVal variants that are not + // // exposed to the contracts. + // SCV_CONTRACT_INSTANCE = 19, + // + // // SCV_LEDGER_KEY_CONTRACT_INSTANCE and SCV_LEDGER_KEY_NONCE are unique + // // symbolic SCVals used as the key for ledger entries for a contract's + // // instance and an address' nonce, respectively. + // SCV_LEDGER_KEY_CONTRACT_INSTANCE = 20, + // SCV_LEDGER_KEY_NONCE = 21 + // }; + // + // =========================================================================== + xdr["enum"]("ScValType", { + scvBool: 0, + scvVoid: 1, + scvError: 2, + scvU32: 3, + scvI32: 4, + scvU64: 5, + scvI64: 6, + scvTimepoint: 7, + scvDuration: 8, + scvU128: 9, + scvI128: 10, + scvU256: 11, + scvI256: 12, + scvBytes: 13, + scvString: 14, + scvSymbol: 15, + scvVec: 16, + scvMap: 17, + scvAddress: 18, + scvContractInstance: 19, + scvLedgerKeyContractInstance: 20, + scvLedgerKeyNonce: 21 + }); + + // === xdr source ============================================================ + // + // enum SCErrorType + // { + // SCE_CONTRACT = 0, // Contract-specific, user-defined codes. + // SCE_WASM_VM = 1, // Errors while interpreting WASM bytecode. + // SCE_CONTEXT = 2, // Errors in the contract's host context. + // SCE_STORAGE = 3, // Errors accessing host storage. + // SCE_OBJECT = 4, // Errors working with host objects. + // SCE_CRYPTO = 5, // Errors in cryptographic operations. + // SCE_EVENTS = 6, // Errors while emitting events. + // SCE_BUDGET = 7, // Errors relating to budget limits. + // SCE_VALUE = 8, // Errors working with host values or SCVals. + // SCE_AUTH = 9 // Errors from the authentication subsystem. + // }; + // + // =========================================================================== + xdr["enum"]("ScErrorType", { + sceContract: 0, + sceWasmVm: 1, + sceContext: 2, + sceStorage: 3, + sceObject: 4, + sceCrypto: 5, + sceEvents: 6, + sceBudget: 7, + sceValue: 8, + sceAuth: 9 + }); + + // === xdr source ============================================================ + // + // enum SCErrorCode + // { + // SCEC_ARITH_DOMAIN = 0, // Some arithmetic was undefined (overflow, divide-by-zero). + // SCEC_INDEX_BOUNDS = 1, // Something was indexed beyond its bounds. + // SCEC_INVALID_INPUT = 2, // User provided some otherwise-bad data. + // SCEC_MISSING_VALUE = 3, // Some value was required but not provided. + // SCEC_EXISTING_VALUE = 4, // Some value was provided where not allowed. + // SCEC_EXCEEDED_LIMIT = 5, // Some arbitrary limit -- gas or otherwise -- was hit. + // SCEC_INVALID_ACTION = 6, // Data was valid but action requested was not. + // SCEC_INTERNAL_ERROR = 7, // The host detected an error in its own logic. + // SCEC_UNEXPECTED_TYPE = 8, // Some type wasn't as expected. + // SCEC_UNEXPECTED_SIZE = 9 // Something's size wasn't as expected. + // }; + // + // =========================================================================== + xdr["enum"]("ScErrorCode", { + scecArithDomain: 0, + scecIndexBounds: 1, + scecInvalidInput: 2, + scecMissingValue: 3, + scecExistingValue: 4, + scecExceededLimit: 5, + scecInvalidAction: 6, + scecInternalError: 7, + scecUnexpectedType: 8, + scecUnexpectedSize: 9 + }); + + // === xdr source ============================================================ + // + // union SCError switch (SCErrorType type) + // { + // case SCE_CONTRACT: + // uint32 contractCode; + // case SCE_WASM_VM: + // case SCE_CONTEXT: + // case SCE_STORAGE: + // case SCE_OBJECT: + // case SCE_CRYPTO: + // case SCE_EVENTS: + // case SCE_BUDGET: + // case SCE_VALUE: + // case SCE_AUTH: + // SCErrorCode code; + // }; + // + // =========================================================================== + xdr.union("ScError", { + switchOn: xdr.lookup("ScErrorType"), + switchName: "type", + switches: [["sceContract", "contractCode"], ["sceWasmVm", "code"], ["sceContext", "code"], ["sceStorage", "code"], ["sceObject", "code"], ["sceCrypto", "code"], ["sceEvents", "code"], ["sceBudget", "code"], ["sceValue", "code"], ["sceAuth", "code"]], + arms: { + contractCode: xdr.lookup("Uint32"), + code: xdr.lookup("ScErrorCode") + } + }); + + // === xdr source ============================================================ + // + // struct UInt128Parts { + // uint64 hi; + // uint64 lo; + // }; + // + // =========================================================================== + xdr.struct("UInt128Parts", [["hi", xdr.lookup("Uint64")], ["lo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct Int128Parts { + // int64 hi; + // uint64 lo; + // }; + // + // =========================================================================== + xdr.struct("Int128Parts", [["hi", xdr.lookup("Int64")], ["lo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct UInt256Parts { + // uint64 hi_hi; + // uint64 hi_lo; + // uint64 lo_hi; + // uint64 lo_lo; + // }; + // + // =========================================================================== + xdr.struct("UInt256Parts", [["hiHi", xdr.lookup("Uint64")], ["hiLo", xdr.lookup("Uint64")], ["loHi", xdr.lookup("Uint64")], ["loLo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct Int256Parts { + // int64 hi_hi; + // uint64 hi_lo; + // uint64 lo_hi; + // uint64 lo_lo; + // }; + // + // =========================================================================== + xdr.struct("Int256Parts", [["hiHi", xdr.lookup("Int64")], ["hiLo", xdr.lookup("Uint64")], ["loHi", xdr.lookup("Uint64")], ["loLo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // enum ContractExecutableType + // { + // CONTRACT_EXECUTABLE_WASM = 0, + // CONTRACT_EXECUTABLE_STELLAR_ASSET = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractExecutableType", { + contractExecutableWasm: 0, + contractExecutableStellarAsset: 1 + }); + + // === xdr source ============================================================ + // + // union ContractExecutable switch (ContractExecutableType type) + // { + // case CONTRACT_EXECUTABLE_WASM: + // Hash wasm_hash; + // case CONTRACT_EXECUTABLE_STELLAR_ASSET: + // void; + // }; + // + // =========================================================================== + xdr.union("ContractExecutable", { + switchOn: xdr.lookup("ContractExecutableType"), + switchName: "type", + switches: [["contractExecutableWasm", "wasmHash"], ["contractExecutableStellarAsset", xdr["void"]()]], + arms: { + wasmHash: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum SCAddressType + // { + // SC_ADDRESS_TYPE_ACCOUNT = 0, + // SC_ADDRESS_TYPE_CONTRACT = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ScAddressType", { + scAddressTypeAccount: 0, + scAddressTypeContract: 1 + }); + + // === xdr source ============================================================ + // + // union SCAddress switch (SCAddressType type) + // { + // case SC_ADDRESS_TYPE_ACCOUNT: + // AccountID accountId; + // case SC_ADDRESS_TYPE_CONTRACT: + // Hash contractId; + // }; + // + // =========================================================================== + xdr.union("ScAddress", { + switchOn: xdr.lookup("ScAddressType"), + switchName: "type", + switches: [["scAddressTypeAccount", "accountId"], ["scAddressTypeContract", "contractId"]], + arms: { + accountId: xdr.lookup("AccountId"), + contractId: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // const SCSYMBOL_LIMIT = 32; + // + // =========================================================================== + xdr["const"]("SCSYMBOL_LIMIT", 32); + + // === xdr source ============================================================ + // + // typedef SCVal SCVec<>; + // + // =========================================================================== + xdr.typedef("ScVec", xdr.varArray(xdr.lookup("ScVal"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef SCMapEntry SCMap<>; + // + // =========================================================================== + xdr.typedef("ScMap", xdr.varArray(xdr.lookup("ScMapEntry"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef opaque SCBytes<>; + // + // =========================================================================== + xdr.typedef("ScBytes", xdr.varOpaque()); + + // === xdr source ============================================================ + // + // typedef string SCString<>; + // + // =========================================================================== + xdr.typedef("ScString", xdr.string()); + + // === xdr source ============================================================ + // + // typedef string SCSymbol; + // + // =========================================================================== + xdr.typedef("ScSymbol", xdr.string(SCSYMBOL_LIMIT)); + + // === xdr source ============================================================ + // + // struct SCNonceKey { + // int64 nonce; + // }; + // + // =========================================================================== + xdr.struct("ScNonceKey", [["nonce", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct SCContractInstance { + // ContractExecutable executable; + // SCMap* storage; + // }; + // + // =========================================================================== + xdr.struct("ScContractInstance", [["executable", xdr.lookup("ContractExecutable")], ["storage", xdr.option(xdr.lookup("ScMap"))]]); + + // === xdr source ============================================================ + // + // union SCVal switch (SCValType type) + // { + // + // case SCV_BOOL: + // bool b; + // case SCV_VOID: + // void; + // case SCV_ERROR: + // SCError error; + // + // case SCV_U32: + // uint32 u32; + // case SCV_I32: + // int32 i32; + // + // case SCV_U64: + // uint64 u64; + // case SCV_I64: + // int64 i64; + // case SCV_TIMEPOINT: + // TimePoint timepoint; + // case SCV_DURATION: + // Duration duration; + // + // case SCV_U128: + // UInt128Parts u128; + // case SCV_I128: + // Int128Parts i128; + // + // case SCV_U256: + // UInt256Parts u256; + // case SCV_I256: + // Int256Parts i256; + // + // case SCV_BYTES: + // SCBytes bytes; + // case SCV_STRING: + // SCString str; + // case SCV_SYMBOL: + // SCSymbol sym; + // + // // Vec and Map are recursive so need to live + // // behind an option, due to xdrpp limitations. + // case SCV_VEC: + // SCVec *vec; + // case SCV_MAP: + // SCMap *map; + // + // case SCV_ADDRESS: + // SCAddress address; + // + // // Special SCVals reserved for system-constructed contract-data + // // ledger keys, not generally usable elsewhere. + // case SCV_LEDGER_KEY_CONTRACT_INSTANCE: + // void; + // case SCV_LEDGER_KEY_NONCE: + // SCNonceKey nonce_key; + // + // case SCV_CONTRACT_INSTANCE: + // SCContractInstance instance; + // }; + // + // =========================================================================== + xdr.union("ScVal", { + switchOn: xdr.lookup("ScValType"), + switchName: "type", + switches: [["scvBool", "b"], ["scvVoid", xdr["void"]()], ["scvError", "error"], ["scvU32", "u32"], ["scvI32", "i32"], ["scvU64", "u64"], ["scvI64", "i64"], ["scvTimepoint", "timepoint"], ["scvDuration", "duration"], ["scvU128", "u128"], ["scvI128", "i128"], ["scvU256", "u256"], ["scvI256", "i256"], ["scvBytes", "bytes"], ["scvString", "str"], ["scvSymbol", "sym"], ["scvVec", "vec"], ["scvMap", "map"], ["scvAddress", "address"], ["scvLedgerKeyContractInstance", xdr["void"]()], ["scvLedgerKeyNonce", "nonceKey"], ["scvContractInstance", "instance"]], + arms: { + b: xdr.bool(), + error: xdr.lookup("ScError"), + u32: xdr.lookup("Uint32"), + i32: xdr.lookup("Int32"), + u64: xdr.lookup("Uint64"), + i64: xdr.lookup("Int64"), + timepoint: xdr.lookup("TimePoint"), + duration: xdr.lookup("Duration"), + u128: xdr.lookup("UInt128Parts"), + i128: xdr.lookup("Int128Parts"), + u256: xdr.lookup("UInt256Parts"), + i256: xdr.lookup("Int256Parts"), + bytes: xdr.lookup("ScBytes"), + str: xdr.lookup("ScString"), + sym: xdr.lookup("ScSymbol"), + vec: xdr.option(xdr.lookup("ScVec")), + map: xdr.option(xdr.lookup("ScMap")), + address: xdr.lookup("ScAddress"), + nonceKey: xdr.lookup("ScNonceKey"), + instance: xdr.lookup("ScContractInstance") + } + }); + + // === xdr source ============================================================ + // + // struct SCMapEntry + // { + // SCVal key; + // SCVal val; + // }; + // + // =========================================================================== + xdr.struct("ScMapEntry", [["key", xdr.lookup("ScVal")], ["val", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // enum SCEnvMetaKind + // { + // SC_ENV_META_KIND_INTERFACE_VERSION = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ScEnvMetaKind", { + scEnvMetaKindInterfaceVersion: 0 + }); + + // === xdr source ============================================================ + // + // struct { + // uint32 protocol; + // uint32 preRelease; + // } + // + // =========================================================================== + xdr.struct("ScEnvMetaEntryInterfaceVersion", [["protocol", xdr.lookup("Uint32")], ["preRelease", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union SCEnvMetaEntry switch (SCEnvMetaKind kind) + // { + // case SC_ENV_META_KIND_INTERFACE_VERSION: + // struct { + // uint32 protocol; + // uint32 preRelease; + // } interfaceVersion; + // }; + // + // =========================================================================== + xdr.union("ScEnvMetaEntry", { + switchOn: xdr.lookup("ScEnvMetaKind"), + switchName: "kind", + switches: [["scEnvMetaKindInterfaceVersion", "interfaceVersion"]], + arms: { + interfaceVersion: xdr.lookup("ScEnvMetaEntryInterfaceVersion") + } + }); + + // === xdr source ============================================================ + // + // struct SCMetaV0 + // { + // string key<>; + // string val<>; + // }; + // + // =========================================================================== + xdr.struct("ScMetaV0", [["key", xdr.string()], ["val", xdr.string()]]); + + // === xdr source ============================================================ + // + // enum SCMetaKind + // { + // SC_META_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ScMetaKind", { + scMetaV0: 0 + }); + + // === xdr source ============================================================ + // + // union SCMetaEntry switch (SCMetaKind kind) + // { + // case SC_META_V0: + // SCMetaV0 v0; + // }; + // + // =========================================================================== + xdr.union("ScMetaEntry", { + switchOn: xdr.lookup("ScMetaKind"), + switchName: "kind", + switches: [["scMetaV0", "v0"]], + arms: { + v0: xdr.lookup("ScMetaV0") + } + }); + + // === xdr source ============================================================ + // + // const SC_SPEC_DOC_LIMIT = 1024; + // + // =========================================================================== + xdr["const"]("SC_SPEC_DOC_LIMIT", 1024); + + // === xdr source ============================================================ + // + // enum SCSpecType + // { + // SC_SPEC_TYPE_VAL = 0, + // + // // Types with no parameters. + // SC_SPEC_TYPE_BOOL = 1, + // SC_SPEC_TYPE_VOID = 2, + // SC_SPEC_TYPE_ERROR = 3, + // SC_SPEC_TYPE_U32 = 4, + // SC_SPEC_TYPE_I32 = 5, + // SC_SPEC_TYPE_U64 = 6, + // SC_SPEC_TYPE_I64 = 7, + // SC_SPEC_TYPE_TIMEPOINT = 8, + // SC_SPEC_TYPE_DURATION = 9, + // SC_SPEC_TYPE_U128 = 10, + // SC_SPEC_TYPE_I128 = 11, + // SC_SPEC_TYPE_U256 = 12, + // SC_SPEC_TYPE_I256 = 13, + // SC_SPEC_TYPE_BYTES = 14, + // SC_SPEC_TYPE_STRING = 16, + // SC_SPEC_TYPE_SYMBOL = 17, + // SC_SPEC_TYPE_ADDRESS = 19, + // + // // Types with parameters. + // SC_SPEC_TYPE_OPTION = 1000, + // SC_SPEC_TYPE_RESULT = 1001, + // SC_SPEC_TYPE_VEC = 1002, + // SC_SPEC_TYPE_MAP = 1004, + // SC_SPEC_TYPE_TUPLE = 1005, + // SC_SPEC_TYPE_BYTES_N = 1006, + // + // // User defined types. + // SC_SPEC_TYPE_UDT = 2000 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecType", { + scSpecTypeVal: 0, + scSpecTypeBool: 1, + scSpecTypeVoid: 2, + scSpecTypeError: 3, + scSpecTypeU32: 4, + scSpecTypeI32: 5, + scSpecTypeU64: 6, + scSpecTypeI64: 7, + scSpecTypeTimepoint: 8, + scSpecTypeDuration: 9, + scSpecTypeU128: 10, + scSpecTypeI128: 11, + scSpecTypeU256: 12, + scSpecTypeI256: 13, + scSpecTypeBytes: 14, + scSpecTypeString: 16, + scSpecTypeSymbol: 17, + scSpecTypeAddress: 19, + scSpecTypeOption: 1000, + scSpecTypeResult: 1001, + scSpecTypeVec: 1002, + scSpecTypeMap: 1004, + scSpecTypeTuple: 1005, + scSpecTypeBytesN: 1006, + scSpecTypeUdt: 2000 + }); + + // === xdr source ============================================================ + // + // struct SCSpecTypeOption + // { + // SCSpecTypeDef valueType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeOption", [["valueType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeResult + // { + // SCSpecTypeDef okType; + // SCSpecTypeDef errorType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeResult", [["okType", xdr.lookup("ScSpecTypeDef")], ["errorType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeVec + // { + // SCSpecTypeDef elementType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeVec", [["elementType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeMap + // { + // SCSpecTypeDef keyType; + // SCSpecTypeDef valueType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeMap", [["keyType", xdr.lookup("ScSpecTypeDef")], ["valueType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeTuple + // { + // SCSpecTypeDef valueTypes<12>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeTuple", [["valueTypes", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 12)]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeBytesN + // { + // uint32 n; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeBytesN", [["n", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeUDT + // { + // string name<60>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeUdt", [["name", xdr.string(60)]]); + + // === xdr source ============================================================ + // + // union SCSpecTypeDef switch (SCSpecType type) + // { + // case SC_SPEC_TYPE_VAL: + // case SC_SPEC_TYPE_BOOL: + // case SC_SPEC_TYPE_VOID: + // case SC_SPEC_TYPE_ERROR: + // case SC_SPEC_TYPE_U32: + // case SC_SPEC_TYPE_I32: + // case SC_SPEC_TYPE_U64: + // case SC_SPEC_TYPE_I64: + // case SC_SPEC_TYPE_TIMEPOINT: + // case SC_SPEC_TYPE_DURATION: + // case SC_SPEC_TYPE_U128: + // case SC_SPEC_TYPE_I128: + // case SC_SPEC_TYPE_U256: + // case SC_SPEC_TYPE_I256: + // case SC_SPEC_TYPE_BYTES: + // case SC_SPEC_TYPE_STRING: + // case SC_SPEC_TYPE_SYMBOL: + // case SC_SPEC_TYPE_ADDRESS: + // void; + // case SC_SPEC_TYPE_OPTION: + // SCSpecTypeOption option; + // case SC_SPEC_TYPE_RESULT: + // SCSpecTypeResult result; + // case SC_SPEC_TYPE_VEC: + // SCSpecTypeVec vec; + // case SC_SPEC_TYPE_MAP: + // SCSpecTypeMap map; + // case SC_SPEC_TYPE_TUPLE: + // SCSpecTypeTuple tuple; + // case SC_SPEC_TYPE_BYTES_N: + // SCSpecTypeBytesN bytesN; + // case SC_SPEC_TYPE_UDT: + // SCSpecTypeUDT udt; + // }; + // + // =========================================================================== + xdr.union("ScSpecTypeDef", { + switchOn: xdr.lookup("ScSpecType"), + switchName: "type", + switches: [["scSpecTypeVal", xdr["void"]()], ["scSpecTypeBool", xdr["void"]()], ["scSpecTypeVoid", xdr["void"]()], ["scSpecTypeError", xdr["void"]()], ["scSpecTypeU32", xdr["void"]()], ["scSpecTypeI32", xdr["void"]()], ["scSpecTypeU64", xdr["void"]()], ["scSpecTypeI64", xdr["void"]()], ["scSpecTypeTimepoint", xdr["void"]()], ["scSpecTypeDuration", xdr["void"]()], ["scSpecTypeU128", xdr["void"]()], ["scSpecTypeI128", xdr["void"]()], ["scSpecTypeU256", xdr["void"]()], ["scSpecTypeI256", xdr["void"]()], ["scSpecTypeBytes", xdr["void"]()], ["scSpecTypeString", xdr["void"]()], ["scSpecTypeSymbol", xdr["void"]()], ["scSpecTypeAddress", xdr["void"]()], ["scSpecTypeOption", "option"], ["scSpecTypeResult", "result"], ["scSpecTypeVec", "vec"], ["scSpecTypeMap", "map"], ["scSpecTypeTuple", "tuple"], ["scSpecTypeBytesN", "bytesN"], ["scSpecTypeUdt", "udt"]], + arms: { + option: xdr.lookup("ScSpecTypeOption"), + result: xdr.lookup("ScSpecTypeResult"), + vec: xdr.lookup("ScSpecTypeVec"), + map: xdr.lookup("ScSpecTypeMap"), + tuple: xdr.lookup("ScSpecTypeTuple"), + bytesN: xdr.lookup("ScSpecTypeBytesN"), + udt: xdr.lookup("ScSpecTypeUdt") + } + }); + + // === xdr source ============================================================ + // + // struct SCSpecUDTStructFieldV0 + // { + // string doc; + // string name<30>; + // SCSpecTypeDef type; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtStructFieldV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(30)], ["type", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTStructV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTStructFieldV0 fields<40>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtStructV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["fields", xdr.varArray(xdr.lookup("ScSpecUdtStructFieldV0"), 40)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionCaseVoidV0 + // { + // string doc; + // string name<60>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionCaseVoidV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionCaseTupleV0 + // { + // string doc; + // string name<60>; + // SCSpecTypeDef type<12>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionCaseTupleV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["type", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 12)]]); + + // === xdr source ============================================================ + // + // enum SCSpecUDTUnionCaseV0Kind + // { + // SC_SPEC_UDT_UNION_CASE_VOID_V0 = 0, + // SC_SPEC_UDT_UNION_CASE_TUPLE_V0 = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecUdtUnionCaseV0Kind", { + scSpecUdtUnionCaseVoidV0: 0, + scSpecUdtUnionCaseTupleV0: 1 + }); + + // === xdr source ============================================================ + // + // union SCSpecUDTUnionCaseV0 switch (SCSpecUDTUnionCaseV0Kind kind) + // { + // case SC_SPEC_UDT_UNION_CASE_VOID_V0: + // SCSpecUDTUnionCaseVoidV0 voidCase; + // case SC_SPEC_UDT_UNION_CASE_TUPLE_V0: + // SCSpecUDTUnionCaseTupleV0 tupleCase; + // }; + // + // =========================================================================== + xdr.union("ScSpecUdtUnionCaseV0", { + switchOn: xdr.lookup("ScSpecUdtUnionCaseV0Kind"), + switchName: "kind", + switches: [["scSpecUdtUnionCaseVoidV0", "voidCase"], ["scSpecUdtUnionCaseTupleV0", "tupleCase"]], + arms: { + voidCase: xdr.lookup("ScSpecUdtUnionCaseVoidV0"), + tupleCase: xdr.lookup("ScSpecUdtUnionCaseTupleV0") + } + }); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTUnionCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtUnionCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTEnumCaseV0 + // { + // string doc; + // string name<60>; + // uint32 value; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtEnumCaseV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["value", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTEnumV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTEnumCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtEnumV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtEnumCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTErrorEnumCaseV0 + // { + // string doc; + // string name<60>; + // uint32 value; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtErrorEnumCaseV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["value", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTErrorEnumV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTErrorEnumCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtErrorEnumV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtErrorEnumCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecFunctionInputV0 + // { + // string doc; + // string name<30>; + // SCSpecTypeDef type; + // }; + // + // =========================================================================== + xdr.struct("ScSpecFunctionInputV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(30)], ["type", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecFunctionV0 + // { + // string doc; + // SCSymbol name; + // SCSpecFunctionInputV0 inputs<10>; + // SCSpecTypeDef outputs<1>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecFunctionV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.lookup("ScSymbol")], ["inputs", xdr.varArray(xdr.lookup("ScSpecFunctionInputV0"), 10)], ["outputs", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 1)]]); + + // === xdr source ============================================================ + // + // enum SCSpecEntryKind + // { + // SC_SPEC_ENTRY_FUNCTION_V0 = 0, + // SC_SPEC_ENTRY_UDT_STRUCT_V0 = 1, + // SC_SPEC_ENTRY_UDT_UNION_V0 = 2, + // SC_SPEC_ENTRY_UDT_ENUM_V0 = 3, + // SC_SPEC_ENTRY_UDT_ERROR_ENUM_V0 = 4 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecEntryKind", { + scSpecEntryFunctionV0: 0, + scSpecEntryUdtStructV0: 1, + scSpecEntryUdtUnionV0: 2, + scSpecEntryUdtEnumV0: 3, + scSpecEntryUdtErrorEnumV0: 4 + }); + + // === xdr source ============================================================ + // + // union SCSpecEntry switch (SCSpecEntryKind kind) + // { + // case SC_SPEC_ENTRY_FUNCTION_V0: + // SCSpecFunctionV0 functionV0; + // case SC_SPEC_ENTRY_UDT_STRUCT_V0: + // SCSpecUDTStructV0 udtStructV0; + // case SC_SPEC_ENTRY_UDT_UNION_V0: + // SCSpecUDTUnionV0 udtUnionV0; + // case SC_SPEC_ENTRY_UDT_ENUM_V0: + // SCSpecUDTEnumV0 udtEnumV0; + // case SC_SPEC_ENTRY_UDT_ERROR_ENUM_V0: + // SCSpecUDTErrorEnumV0 udtErrorEnumV0; + // }; + // + // =========================================================================== + xdr.union("ScSpecEntry", { + switchOn: xdr.lookup("ScSpecEntryKind"), + switchName: "kind", + switches: [["scSpecEntryFunctionV0", "functionV0"], ["scSpecEntryUdtStructV0", "udtStructV0"], ["scSpecEntryUdtUnionV0", "udtUnionV0"], ["scSpecEntryUdtEnumV0", "udtEnumV0"], ["scSpecEntryUdtErrorEnumV0", "udtErrorEnumV0"]], + arms: { + functionV0: xdr.lookup("ScSpecFunctionV0"), + udtStructV0: xdr.lookup("ScSpecUdtStructV0"), + udtUnionV0: xdr.lookup("ScSpecUdtUnionV0"), + udtEnumV0: xdr.lookup("ScSpecUdtEnumV0"), + udtErrorEnumV0: xdr.lookup("ScSpecUdtErrorEnumV0") + } + }); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractExecutionLanesV0 + // { + // // maximum number of Soroban transactions per ledger + // uint32 ledgerMaxTxCount; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractExecutionLanesV0", [["ledgerMaxTxCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractComputeV0 + // { + // // Maximum instructions per ledger + // int64 ledgerMaxInstructions; + // // Maximum instructions per transaction + // int64 txMaxInstructions; + // // Cost of 10000 instructions + // int64 feeRatePerInstructionsIncrement; + // + // // Memory limit per transaction. Unlike instructions, there is no fee + // // for memory, just the limit. + // uint32 txMemoryLimit; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractComputeV0", [["ledgerMaxInstructions", xdr.lookup("Int64")], ["txMaxInstructions", xdr.lookup("Int64")], ["feeRatePerInstructionsIncrement", xdr.lookup("Int64")], ["txMemoryLimit", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractLedgerCostV0 + // { + // // Maximum number of ledger entry read operations per ledger + // uint32 ledgerMaxReadLedgerEntries; + // // Maximum number of bytes that can be read per ledger + // uint32 ledgerMaxReadBytes; + // // Maximum number of ledger entry write operations per ledger + // uint32 ledgerMaxWriteLedgerEntries; + // // Maximum number of bytes that can be written per ledger + // uint32 ledgerMaxWriteBytes; + // + // // Maximum number of ledger entry read operations per transaction + // uint32 txMaxReadLedgerEntries; + // // Maximum number of bytes that can be read per transaction + // uint32 txMaxReadBytes; + // // Maximum number of ledger entry write operations per transaction + // uint32 txMaxWriteLedgerEntries; + // // Maximum number of bytes that can be written per transaction + // uint32 txMaxWriteBytes; + // + // int64 feeReadLedgerEntry; // Fee per ledger entry read + // int64 feeWriteLedgerEntry; // Fee per ledger entry write + // + // int64 feeRead1KB; // Fee for reading 1KB + // + // // The following parameters determine the write fee per 1KB. + // // Write fee grows linearly until bucket list reaches this size + // int64 bucketListTargetSizeBytes; + // // Fee per 1KB write when the bucket list is empty + // int64 writeFee1KBBucketListLow; + // // Fee per 1KB write when the bucket list has reached `bucketListTargetSizeBytes` + // int64 writeFee1KBBucketListHigh; + // // Write fee multiplier for any additional data past the first `bucketListTargetSizeBytes` + // uint32 bucketListWriteFeeGrowthFactor; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractLedgerCostV0", [["ledgerMaxReadLedgerEntries", xdr.lookup("Uint32")], ["ledgerMaxReadBytes", xdr.lookup("Uint32")], ["ledgerMaxWriteLedgerEntries", xdr.lookup("Uint32")], ["ledgerMaxWriteBytes", xdr.lookup("Uint32")], ["txMaxReadLedgerEntries", xdr.lookup("Uint32")], ["txMaxReadBytes", xdr.lookup("Uint32")], ["txMaxWriteLedgerEntries", xdr.lookup("Uint32")], ["txMaxWriteBytes", xdr.lookup("Uint32")], ["feeReadLedgerEntry", xdr.lookup("Int64")], ["feeWriteLedgerEntry", xdr.lookup("Int64")], ["feeRead1Kb", xdr.lookup("Int64")], ["bucketListTargetSizeBytes", xdr.lookup("Int64")], ["writeFee1KbBucketListLow", xdr.lookup("Int64")], ["writeFee1KbBucketListHigh", xdr.lookup("Int64")], ["bucketListWriteFeeGrowthFactor", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractHistoricalDataV0 + // { + // int64 feeHistorical1KB; // Fee for storing 1KB in archives + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractHistoricalDataV0", [["feeHistorical1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractEventsV0 + // { + // // Maximum size of events that a contract call can emit. + // uint32 txMaxContractEventsSizeBytes; + // // Fee for generating 1KB of contract events. + // int64 feeContractEvents1KB; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractEventsV0", [["txMaxContractEventsSizeBytes", xdr.lookup("Uint32")], ["feeContractEvents1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractBandwidthV0 + // { + // // Maximum sum of all transaction sizes in the ledger in bytes + // uint32 ledgerMaxTxsSizeBytes; + // // Maximum size in bytes for a transaction + // uint32 txMaxSizeBytes; + // + // // Fee for 1 KB of transaction size + // int64 feeTxSize1KB; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractBandwidthV0", [["ledgerMaxTxsSizeBytes", xdr.lookup("Uint32")], ["txMaxSizeBytes", xdr.lookup("Uint32")], ["feeTxSize1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum ContractCostType { + // // Cost of running 1 wasm instruction + // WasmInsnExec = 0, + // // Cost of allocating a slice of memory (in bytes) + // MemAlloc = 1, + // // Cost of copying a slice of bytes into a pre-allocated memory + // MemCpy = 2, + // // Cost of comparing two slices of memory + // MemCmp = 3, + // // Cost of a host function dispatch, not including the actual work done by + // // the function nor the cost of VM invocation machinary + // DispatchHostFunction = 4, + // // Cost of visiting a host object from the host object storage. Exists to + // // make sure some baseline cost coverage, i.e. repeatly visiting objects + // // by the guest will always incur some charges. + // VisitObject = 5, + // // Cost of serializing an xdr object to bytes + // ValSer = 6, + // // Cost of deserializing an xdr object from bytes + // ValDeser = 7, + // // Cost of computing the sha256 hash from bytes + // ComputeSha256Hash = 8, + // // Cost of computing the ed25519 pubkey from bytes + // ComputeEd25519PubKey = 9, + // // Cost of verifying ed25519 signature of a payload. + // VerifyEd25519Sig = 10, + // // Cost of instantiation a VM from wasm bytes code. + // VmInstantiation = 11, + // // Cost of instantiation a VM from a cached state. + // VmCachedInstantiation = 12, + // // Cost of invoking a function on the VM. If the function is a host function, + // // additional cost will be covered by `DispatchHostFunction`. + // InvokeVmFunction = 13, + // // Cost of computing a keccak256 hash from bytes. + // ComputeKeccak256Hash = 14, + // // Cost of decoding an ECDSA signature computed from a 256-bit prime modulus + // // curve (e.g. secp256k1 and secp256r1) + // DecodeEcdsaCurve256Sig = 15, + // // Cost of recovering an ECDSA secp256k1 key from a signature. + // RecoverEcdsaSecp256k1Key = 16, + // // Cost of int256 addition (`+`) and subtraction (`-`) operations + // Int256AddSub = 17, + // // Cost of int256 multiplication (`*`) operation + // Int256Mul = 18, + // // Cost of int256 division (`/`) operation + // Int256Div = 19, + // // Cost of int256 power (`exp`) operation + // Int256Pow = 20, + // // Cost of int256 shift (`shl`, `shr`) operation + // Int256Shift = 21, + // // Cost of drawing random bytes using a ChaCha20 PRNG + // ChaCha20DrawBytes = 22, + // + // // Cost of parsing wasm bytes that only encode instructions. + // ParseWasmInstructions = 23, + // // Cost of parsing a known number of wasm functions. + // ParseWasmFunctions = 24, + // // Cost of parsing a known number of wasm globals. + // ParseWasmGlobals = 25, + // // Cost of parsing a known number of wasm table entries. + // ParseWasmTableEntries = 26, + // // Cost of parsing a known number of wasm types. + // ParseWasmTypes = 27, + // // Cost of parsing a known number of wasm data segments. + // ParseWasmDataSegments = 28, + // // Cost of parsing a known number of wasm element segments. + // ParseWasmElemSegments = 29, + // // Cost of parsing a known number of wasm imports. + // ParseWasmImports = 30, + // // Cost of parsing a known number of wasm exports. + // ParseWasmExports = 31, + // // Cost of parsing a known number of data segment bytes. + // ParseWasmDataSegmentBytes = 32, + // + // // Cost of instantiating wasm bytes that only encode instructions. + // InstantiateWasmInstructions = 33, + // // Cost of instantiating a known number of wasm functions. + // InstantiateWasmFunctions = 34, + // // Cost of instantiating a known number of wasm globals. + // InstantiateWasmGlobals = 35, + // // Cost of instantiating a known number of wasm table entries. + // InstantiateWasmTableEntries = 36, + // // Cost of instantiating a known number of wasm types. + // InstantiateWasmTypes = 37, + // // Cost of instantiating a known number of wasm data segments. + // InstantiateWasmDataSegments = 38, + // // Cost of instantiating a known number of wasm element segments. + // InstantiateWasmElemSegments = 39, + // // Cost of instantiating a known number of wasm imports. + // InstantiateWasmImports = 40, + // // Cost of instantiating a known number of wasm exports. + // InstantiateWasmExports = 41, + // // Cost of instantiating a known number of data segment bytes. + // InstantiateWasmDataSegmentBytes = 42, + // + // // Cost of decoding a bytes array representing an uncompressed SEC-1 encoded + // // point on a 256-bit elliptic curve + // Sec1DecodePointUncompressed = 43, + // // Cost of verifying an ECDSA Secp256r1 signature + // VerifyEcdsaSecp256r1Sig = 44, + // + // // Cost of encoding a BLS12-381 Fp (base field element) + // Bls12381EncodeFp = 45, + // // Cost of decoding a BLS12-381 Fp (base field element) + // Bls12381DecodeFp = 46, + // // Cost of checking a G1 point lies on the curve + // Bls12381G1CheckPointOnCurve = 47, + // // Cost of checking a G1 point belongs to the correct subgroup + // Bls12381G1CheckPointInSubgroup = 48, + // // Cost of checking a G2 point lies on the curve + // Bls12381G2CheckPointOnCurve = 49, + // // Cost of checking a G2 point belongs to the correct subgroup + // Bls12381G2CheckPointInSubgroup = 50, + // // Cost of converting a BLS12-381 G1 point from projective to affine coordinates + // Bls12381G1ProjectiveToAffine = 51, + // // Cost of converting a BLS12-381 G2 point from projective to affine coordinates + // Bls12381G2ProjectiveToAffine = 52, + // // Cost of performing BLS12-381 G1 point addition + // Bls12381G1Add = 53, + // // Cost of performing BLS12-381 G1 scalar multiplication + // Bls12381G1Mul = 54, + // // Cost of performing BLS12-381 G1 multi-scalar multiplication (MSM) + // Bls12381G1Msm = 55, + // // Cost of mapping a BLS12-381 Fp field element to a G1 point + // Bls12381MapFpToG1 = 56, + // // Cost of hashing to a BLS12-381 G1 point + // Bls12381HashToG1 = 57, + // // Cost of performing BLS12-381 G2 point addition + // Bls12381G2Add = 58, + // // Cost of performing BLS12-381 G2 scalar multiplication + // Bls12381G2Mul = 59, + // // Cost of performing BLS12-381 G2 multi-scalar multiplication (MSM) + // Bls12381G2Msm = 60, + // // Cost of mapping a BLS12-381 Fp2 field element to a G2 point + // Bls12381MapFp2ToG2 = 61, + // // Cost of hashing to a BLS12-381 G2 point + // Bls12381HashToG2 = 62, + // // Cost of performing BLS12-381 pairing operation + // Bls12381Pairing = 63, + // // Cost of converting a BLS12-381 scalar element from U256 + // Bls12381FrFromU256 = 64, + // // Cost of converting a BLS12-381 scalar element to U256 + // Bls12381FrToU256 = 65, + // // Cost of performing BLS12-381 scalar element addition/subtraction + // Bls12381FrAddSub = 66, + // // Cost of performing BLS12-381 scalar element multiplication + // Bls12381FrMul = 67, + // // Cost of performing BLS12-381 scalar element exponentiation + // Bls12381FrPow = 68, + // // Cost of performing BLS12-381 scalar element inversion + // Bls12381FrInv = 69 + // }; + // + // =========================================================================== + xdr["enum"]("ContractCostType", { + wasmInsnExec: 0, + memAlloc: 1, + memCpy: 2, + memCmp: 3, + dispatchHostFunction: 4, + visitObject: 5, + valSer: 6, + valDeser: 7, + computeSha256Hash: 8, + computeEd25519PubKey: 9, + verifyEd25519Sig: 10, + vmInstantiation: 11, + vmCachedInstantiation: 12, + invokeVmFunction: 13, + computeKeccak256Hash: 14, + decodeEcdsaCurve256Sig: 15, + recoverEcdsaSecp256k1Key: 16, + int256AddSub: 17, + int256Mul: 18, + int256Div: 19, + int256Pow: 20, + int256Shift: 21, + chaCha20DrawBytes: 22, + parseWasmInstructions: 23, + parseWasmFunctions: 24, + parseWasmGlobals: 25, + parseWasmTableEntries: 26, + parseWasmTypes: 27, + parseWasmDataSegments: 28, + parseWasmElemSegments: 29, + parseWasmImports: 30, + parseWasmExports: 31, + parseWasmDataSegmentBytes: 32, + instantiateWasmInstructions: 33, + instantiateWasmFunctions: 34, + instantiateWasmGlobals: 35, + instantiateWasmTableEntries: 36, + instantiateWasmTypes: 37, + instantiateWasmDataSegments: 38, + instantiateWasmElemSegments: 39, + instantiateWasmImports: 40, + instantiateWasmExports: 41, + instantiateWasmDataSegmentBytes: 42, + sec1DecodePointUncompressed: 43, + verifyEcdsaSecp256r1Sig: 44, + bls12381EncodeFp: 45, + bls12381DecodeFp: 46, + bls12381G1CheckPointOnCurve: 47, + bls12381G1CheckPointInSubgroup: 48, + bls12381G2CheckPointOnCurve: 49, + bls12381G2CheckPointInSubgroup: 50, + bls12381G1ProjectiveToAffine: 51, + bls12381G2ProjectiveToAffine: 52, + bls12381G1Add: 53, + bls12381G1Mul: 54, + bls12381G1Msm: 55, + bls12381MapFpToG1: 56, + bls12381HashToG1: 57, + bls12381G2Add: 58, + bls12381G2Mul: 59, + bls12381G2Msm: 60, + bls12381MapFp2ToG2: 61, + bls12381HashToG2: 62, + bls12381Pairing: 63, + bls12381FrFromU256: 64, + bls12381FrToU256: 65, + bls12381FrAddSub: 66, + bls12381FrMul: 67, + bls12381FrPow: 68, + bls12381FrInv: 69 + }); + + // === xdr source ============================================================ + // + // struct ContractCostParamEntry { + // // use `ext` to add more terms (e.g. higher order polynomials) in the future + // ExtensionPoint ext; + // + // int64 constTerm; + // int64 linearTerm; + // }; + // + // =========================================================================== + xdr.struct("ContractCostParamEntry", [["ext", xdr.lookup("ExtensionPoint")], ["constTerm", xdr.lookup("Int64")], ["linearTerm", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct StateArchivalSettings { + // uint32 maxEntryTTL; + // uint32 minTemporaryTTL; + // uint32 minPersistentTTL; + // + // // rent_fee = wfee_rate_average / rent_rate_denominator_for_type + // int64 persistentRentRateDenominator; + // int64 tempRentRateDenominator; + // + // // max number of entries that emit archival meta in a single ledger + // uint32 maxEntriesToArchive; + // + // // Number of snapshots to use when calculating average BucketList size + // uint32 bucketListSizeWindowSampleSize; + // + // // How often to sample the BucketList size for the average, in ledgers + // uint32 bucketListWindowSamplePeriod; + // + // // Maximum number of bytes that we scan for eviction per ledger + // uint32 evictionScanSize; + // + // // Lowest BucketList level to be scanned to evict entries + // uint32 startingEvictionScanLevel; + // }; + // + // =========================================================================== + xdr.struct("StateArchivalSettings", [["maxEntryTtl", xdr.lookup("Uint32")], ["minTemporaryTtl", xdr.lookup("Uint32")], ["minPersistentTtl", xdr.lookup("Uint32")], ["persistentRentRateDenominator", xdr.lookup("Int64")], ["tempRentRateDenominator", xdr.lookup("Int64")], ["maxEntriesToArchive", xdr.lookup("Uint32")], ["bucketListSizeWindowSampleSize", xdr.lookup("Uint32")], ["bucketListWindowSamplePeriod", xdr.lookup("Uint32")], ["evictionScanSize", xdr.lookup("Uint32")], ["startingEvictionScanLevel", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct EvictionIterator { + // uint32 bucketListLevel; + // bool isCurrBucket; + // uint64 bucketFileOffset; + // }; + // + // =========================================================================== + xdr.struct("EvictionIterator", [["bucketListLevel", xdr.lookup("Uint32")], ["isCurrBucket", xdr.bool()], ["bucketFileOffset", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // const CONTRACT_COST_COUNT_LIMIT = 1024; + // + // =========================================================================== + xdr["const"]("CONTRACT_COST_COUNT_LIMIT", 1024); + + // === xdr source ============================================================ + // + // typedef ContractCostParamEntry ContractCostParams; + // + // =========================================================================== + xdr.typedef("ContractCostParams", xdr.varArray(xdr.lookup("ContractCostParamEntry"), xdr.lookup("CONTRACT_COST_COUNT_LIMIT"))); + + // === xdr source ============================================================ + // + // enum ConfigSettingID + // { + // CONFIG_SETTING_CONTRACT_MAX_SIZE_BYTES = 0, + // CONFIG_SETTING_CONTRACT_COMPUTE_V0 = 1, + // CONFIG_SETTING_CONTRACT_LEDGER_COST_V0 = 2, + // CONFIG_SETTING_CONTRACT_HISTORICAL_DATA_V0 = 3, + // CONFIG_SETTING_CONTRACT_EVENTS_V0 = 4, + // CONFIG_SETTING_CONTRACT_BANDWIDTH_V0 = 5, + // CONFIG_SETTING_CONTRACT_COST_PARAMS_CPU_INSTRUCTIONS = 6, + // CONFIG_SETTING_CONTRACT_COST_PARAMS_MEMORY_BYTES = 7, + // CONFIG_SETTING_CONTRACT_DATA_KEY_SIZE_BYTES = 8, + // CONFIG_SETTING_CONTRACT_DATA_ENTRY_SIZE_BYTES = 9, + // CONFIG_SETTING_STATE_ARCHIVAL = 10, + // CONFIG_SETTING_CONTRACT_EXECUTION_LANES = 11, + // CONFIG_SETTING_BUCKETLIST_SIZE_WINDOW = 12, + // CONFIG_SETTING_EVICTION_ITERATOR = 13 + // }; + // + // =========================================================================== + xdr["enum"]("ConfigSettingId", { + configSettingContractMaxSizeBytes: 0, + configSettingContractComputeV0: 1, + configSettingContractLedgerCostV0: 2, + configSettingContractHistoricalDataV0: 3, + configSettingContractEventsV0: 4, + configSettingContractBandwidthV0: 5, + configSettingContractCostParamsCpuInstructions: 6, + configSettingContractCostParamsMemoryBytes: 7, + configSettingContractDataKeySizeBytes: 8, + configSettingContractDataEntrySizeBytes: 9, + configSettingStateArchival: 10, + configSettingContractExecutionLanes: 11, + configSettingBucketlistSizeWindow: 12, + configSettingEvictionIterator: 13 + }); + + // === xdr source ============================================================ + // + // union ConfigSettingEntry switch (ConfigSettingID configSettingID) + // { + // case CONFIG_SETTING_CONTRACT_MAX_SIZE_BYTES: + // uint32 contractMaxSizeBytes; + // case CONFIG_SETTING_CONTRACT_COMPUTE_V0: + // ConfigSettingContractComputeV0 contractCompute; + // case CONFIG_SETTING_CONTRACT_LEDGER_COST_V0: + // ConfigSettingContractLedgerCostV0 contractLedgerCost; + // case CONFIG_SETTING_CONTRACT_HISTORICAL_DATA_V0: + // ConfigSettingContractHistoricalDataV0 contractHistoricalData; + // case CONFIG_SETTING_CONTRACT_EVENTS_V0: + // ConfigSettingContractEventsV0 contractEvents; + // case CONFIG_SETTING_CONTRACT_BANDWIDTH_V0: + // ConfigSettingContractBandwidthV0 contractBandwidth; + // case CONFIG_SETTING_CONTRACT_COST_PARAMS_CPU_INSTRUCTIONS: + // ContractCostParams contractCostParamsCpuInsns; + // case CONFIG_SETTING_CONTRACT_COST_PARAMS_MEMORY_BYTES: + // ContractCostParams contractCostParamsMemBytes; + // case CONFIG_SETTING_CONTRACT_DATA_KEY_SIZE_BYTES: + // uint32 contractDataKeySizeBytes; + // case CONFIG_SETTING_CONTRACT_DATA_ENTRY_SIZE_BYTES: + // uint32 contractDataEntrySizeBytes; + // case CONFIG_SETTING_STATE_ARCHIVAL: + // StateArchivalSettings stateArchivalSettings; + // case CONFIG_SETTING_CONTRACT_EXECUTION_LANES: + // ConfigSettingContractExecutionLanesV0 contractExecutionLanes; + // case CONFIG_SETTING_BUCKETLIST_SIZE_WINDOW: + // uint64 bucketListSizeWindow<>; + // case CONFIG_SETTING_EVICTION_ITERATOR: + // EvictionIterator evictionIterator; + // }; + // + // =========================================================================== + xdr.union("ConfigSettingEntry", { + switchOn: xdr.lookup("ConfigSettingId"), + switchName: "configSettingId", + switches: [["configSettingContractMaxSizeBytes", "contractMaxSizeBytes"], ["configSettingContractComputeV0", "contractCompute"], ["configSettingContractLedgerCostV0", "contractLedgerCost"], ["configSettingContractHistoricalDataV0", "contractHistoricalData"], ["configSettingContractEventsV0", "contractEvents"], ["configSettingContractBandwidthV0", "contractBandwidth"], ["configSettingContractCostParamsCpuInstructions", "contractCostParamsCpuInsns"], ["configSettingContractCostParamsMemoryBytes", "contractCostParamsMemBytes"], ["configSettingContractDataKeySizeBytes", "contractDataKeySizeBytes"], ["configSettingContractDataEntrySizeBytes", "contractDataEntrySizeBytes"], ["configSettingStateArchival", "stateArchivalSettings"], ["configSettingContractExecutionLanes", "contractExecutionLanes"], ["configSettingBucketlistSizeWindow", "bucketListSizeWindow"], ["configSettingEvictionIterator", "evictionIterator"]], + arms: { + contractMaxSizeBytes: xdr.lookup("Uint32"), + contractCompute: xdr.lookup("ConfigSettingContractComputeV0"), + contractLedgerCost: xdr.lookup("ConfigSettingContractLedgerCostV0"), + contractHistoricalData: xdr.lookup("ConfigSettingContractHistoricalDataV0"), + contractEvents: xdr.lookup("ConfigSettingContractEventsV0"), + contractBandwidth: xdr.lookup("ConfigSettingContractBandwidthV0"), + contractCostParamsCpuInsns: xdr.lookup("ContractCostParams"), + contractCostParamsMemBytes: xdr.lookup("ContractCostParams"), + contractDataKeySizeBytes: xdr.lookup("Uint32"), + contractDataEntrySizeBytes: xdr.lookup("Uint32"), + stateArchivalSettings: xdr.lookup("StateArchivalSettings"), + contractExecutionLanes: xdr.lookup("ConfigSettingContractExecutionLanesV0"), + bucketListSizeWindow: xdr.varArray(xdr.lookup("Uint64"), 2147483647), + evictionIterator: xdr.lookup("EvictionIterator") + } + }); +}); +var _default = exports["default"] = types; + +/***/ }), + +/***/ 5578: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LiquidityPoolFeeV18 = void 0; +exports.getLiquidityPoolId = getLiquidityPoolId; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +var _hashing = __webpack_require__(9152); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +// LiquidityPoolFeeV18 is the default liquidity pool fee in protocol v18. It defaults to 30 base points (0.3%). +var LiquidityPoolFeeV18 = exports.LiquidityPoolFeeV18 = 30; + +/** + * getLiquidityPoolId computes the Pool ID for the given assets, fee and pool type. + * + * @see [stellar-core getPoolID](https://github.com/stellar/stellar-core/blob/9f3a48c6a8f1aa77b6043a055d0638661f718080/src/ledger/test/LedgerTxnTests.cpp#L3746-L3751) + * + * @export + * @param {string} liquidityPoolType – A string representing the liquidity pool type. + * @param {object} liquidityPoolParameters – The liquidity pool parameters. + * @param {Asset} liquidityPoolParameters.assetA – The first asset in the Pool, it must respect the rule assetA < assetB. + * @param {Asset} liquidityPoolParameters.assetB – The second asset in the Pool, it must respect the rule assetA < assetB. + * @param {number} liquidityPoolParameters.fee – The liquidity pool fee. For now the only fee supported is `30`. + * + * @return {Buffer} the raw Pool ID buffer, which can be stringfied with `toString('hex')` + */ +function getLiquidityPoolId(liquidityPoolType) { + var liquidityPoolParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (liquidityPoolType !== 'constant_product') { + throw new Error('liquidityPoolType is invalid'); + } + var assetA = liquidityPoolParameters.assetA, + assetB = liquidityPoolParameters.assetB, + fee = liquidityPoolParameters.fee; + if (!assetA || !(assetA instanceof _asset.Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof _asset.Asset)) { + throw new Error('assetB is invalid'); + } + if (!fee || fee !== LiquidityPoolFeeV18) { + throw new Error('fee is invalid'); + } + if (_asset.Asset.compare(assetA, assetB) !== -1) { + throw new Error('Assets are not in lexicographic order'); + } + var lpTypeData = _xdr["default"].LiquidityPoolType.liquidityPoolConstantProduct().toXDR(); + var lpParamsData = new _xdr["default"].LiquidityPoolConstantProductParameters({ + assetA: assetA.toXDRObject(), + assetB: assetB.toXDRObject(), + fee: fee + }).toXDR(); + var payload = Buffer.concat([lpTypeData, lpParamsData]); + return (0, _hashing.hash)(payload); +} + +/***/ }), + +/***/ 9152: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.hash = hash; +var _sha = __webpack_require__(2802); +function hash(data) { + var hasher = new _sha.sha256(); + hasher.update(data, 'utf8'); + return hasher.digest(); +} + +/***/ }), + +/***/ 356: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _exportNames = { + xdr: true, + cereal: true, + hash: true, + sign: true, + verify: true, + FastSigning: true, + getLiquidityPoolId: true, + LiquidityPoolFeeV18: true, + Keypair: true, + UnsignedHyper: true, + Hyper: true, + TransactionBase: true, + Transaction: true, + FeeBumpTransaction: true, + TransactionBuilder: true, + TimeoutInfinite: true, + BASE_FEE: true, + Asset: true, + LiquidityPoolAsset: true, + LiquidityPoolId: true, + Operation: true, + AuthRequiredFlag: true, + AuthRevocableFlag: true, + AuthImmutableFlag: true, + AuthClawbackEnabledFlag: true, + Account: true, + MuxedAccount: true, + Claimant: true, + Networks: true, + StrKey: true, + SignerKey: true, + Soroban: true, + decodeAddressToMuxedAccount: true, + encodeMuxedAccountToAddress: true, + extractBaseAddress: true, + encodeMuxedAccount: true, + Contract: true, + Address: true +}; +Object.defineProperty(exports, "Account", ({ + enumerable: true, + get: function get() { + return _account.Account; + } +})); +Object.defineProperty(exports, "Address", ({ + enumerable: true, + get: function get() { + return _address.Address; + } +})); +Object.defineProperty(exports, "Asset", ({ + enumerable: true, + get: function get() { + return _asset.Asset; + } +})); +Object.defineProperty(exports, "AuthClawbackEnabledFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthClawbackEnabledFlag; + } +})); +Object.defineProperty(exports, "AuthImmutableFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthImmutableFlag; + } +})); +Object.defineProperty(exports, "AuthRequiredFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthRequiredFlag; + } +})); +Object.defineProperty(exports, "AuthRevocableFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthRevocableFlag; + } +})); +Object.defineProperty(exports, "BASE_FEE", ({ + enumerable: true, + get: function get() { + return _transaction_builder.BASE_FEE; + } +})); +Object.defineProperty(exports, "Claimant", ({ + enumerable: true, + get: function get() { + return _claimant.Claimant; + } +})); +Object.defineProperty(exports, "Contract", ({ + enumerable: true, + get: function get() { + return _contract.Contract; + } +})); +Object.defineProperty(exports, "FastSigning", ({ + enumerable: true, + get: function get() { + return _signing.FastSigning; + } +})); +Object.defineProperty(exports, "FeeBumpTransaction", ({ + enumerable: true, + get: function get() { + return _fee_bump_transaction.FeeBumpTransaction; + } +})); +Object.defineProperty(exports, "Hyper", ({ + enumerable: true, + get: function get() { + return _jsXdr.Hyper; + } +})); +Object.defineProperty(exports, "Keypair", ({ + enumerable: true, + get: function get() { + return _keypair.Keypair; + } +})); +Object.defineProperty(exports, "LiquidityPoolAsset", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_asset.LiquidityPoolAsset; + } +})); +Object.defineProperty(exports, "LiquidityPoolFeeV18", ({ + enumerable: true, + get: function get() { + return _get_liquidity_pool_id.LiquidityPoolFeeV18; + } +})); +Object.defineProperty(exports, "LiquidityPoolId", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_id.LiquidityPoolId; + } +})); +Object.defineProperty(exports, "MuxedAccount", ({ + enumerable: true, + get: function get() { + return _muxed_account.MuxedAccount; + } +})); +Object.defineProperty(exports, "Networks", ({ + enumerable: true, + get: function get() { + return _network.Networks; + } +})); +Object.defineProperty(exports, "Operation", ({ + enumerable: true, + get: function get() { + return _operation.Operation; + } +})); +Object.defineProperty(exports, "SignerKey", ({ + enumerable: true, + get: function get() { + return _signerkey.SignerKey; + } +})); +Object.defineProperty(exports, "Soroban", ({ + enumerable: true, + get: function get() { + return _soroban.Soroban; + } +})); +Object.defineProperty(exports, "StrKey", ({ + enumerable: true, + get: function get() { + return _strkey.StrKey; + } +})); +Object.defineProperty(exports, "TimeoutInfinite", ({ + enumerable: true, + get: function get() { + return _transaction_builder.TimeoutInfinite; + } +})); +Object.defineProperty(exports, "Transaction", ({ + enumerable: true, + get: function get() { + return _transaction.Transaction; + } +})); +Object.defineProperty(exports, "TransactionBase", ({ + enumerable: true, + get: function get() { + return _transaction_base.TransactionBase; + } +})); +Object.defineProperty(exports, "TransactionBuilder", ({ + enumerable: true, + get: function get() { + return _transaction_builder.TransactionBuilder; + } +})); +Object.defineProperty(exports, "UnsignedHyper", ({ + enumerable: true, + get: function get() { + return _jsXdr.UnsignedHyper; + } +})); +Object.defineProperty(exports, "cereal", ({ + enumerable: true, + get: function get() { + return _jsxdr["default"]; + } +})); +Object.defineProperty(exports, "decodeAddressToMuxedAccount", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.decodeAddressToMuxedAccount; + } +})); +exports["default"] = void 0; +Object.defineProperty(exports, "encodeMuxedAccount", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.encodeMuxedAccount; + } +})); +Object.defineProperty(exports, "encodeMuxedAccountToAddress", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.encodeMuxedAccountToAddress; + } +})); +Object.defineProperty(exports, "extractBaseAddress", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.extractBaseAddress; + } +})); +Object.defineProperty(exports, "getLiquidityPoolId", ({ + enumerable: true, + get: function get() { + return _get_liquidity_pool_id.getLiquidityPoolId; + } +})); +Object.defineProperty(exports, "hash", ({ + enumerable: true, + get: function get() { + return _hashing.hash; + } +})); +Object.defineProperty(exports, "sign", ({ + enumerable: true, + get: function get() { + return _signing.sign; + } +})); +Object.defineProperty(exports, "verify", ({ + enumerable: true, + get: function get() { + return _signing.verify; + } +})); +Object.defineProperty(exports, "xdr", ({ + enumerable: true, + get: function get() { + return _xdr["default"]; + } +})); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _jsxdr = _interopRequireDefault(__webpack_require__(3335)); +var _hashing = __webpack_require__(9152); +var _signing = __webpack_require__(15); +var _get_liquidity_pool_id = __webpack_require__(5578); +var _keypair = __webpack_require__(6691); +var _jsXdr = __webpack_require__(3740); +var _transaction_base = __webpack_require__(3758); +var _transaction = __webpack_require__(380); +var _fee_bump_transaction = __webpack_require__(9260); +var _transaction_builder = __webpack_require__(6396); +var _asset = __webpack_require__(1764); +var _liquidity_pool_asset = __webpack_require__(2262); +var _liquidity_pool_id = __webpack_require__(9353); +var _operation = __webpack_require__(7237); +var _memo = __webpack_require__(4172); +Object.keys(_memo).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _memo[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _memo[key]; + } + }); +}); +var _account = __webpack_require__(2135); +var _muxed_account = __webpack_require__(2243); +var _claimant = __webpack_require__(1387); +var _network = __webpack_require__(6202); +var _strkey = __webpack_require__(7120); +var _signerkey = __webpack_require__(225); +var _soroban = __webpack_require__(4062); +var _decode_encode_muxed_account = __webpack_require__(6160); +var _contract = __webpack_require__(7452); +var _address = __webpack_require__(1180); +var _numbers = __webpack_require__(8549); +Object.keys(_numbers).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _numbers[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _numbers[key]; + } + }); +}); +var _scval = __webpack_require__(7177); +Object.keys(_scval).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _scval[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _scval[key]; + } + }); +}); +var _events = __webpack_require__(3919); +Object.keys(_events).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _events[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _events[key]; + } + }); +}); +var _sorobandata_builder = __webpack_require__(4842); +Object.keys(_sorobandata_builder).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _sorobandata_builder[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _sorobandata_builder[key]; + } + }); +}); +var _auth = __webpack_require__(5328); +Object.keys(_auth).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _auth[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _auth[key]; + } + }); +}); +var _invocation = __webpack_require__(3564); +Object.keys(_invocation).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _invocation[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _invocation[key]; + } + }); +}); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/* eslint-disable import/no-import-module-exports */ +// +// Soroban +// +var _default = exports["default"] = module.exports; + +/***/ }), + +/***/ 3564: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.buildInvocationTree = buildInvocationTree; +exports.walkInvocationTree = walkInvocationTree; +var _asset = __webpack_require__(1764); +var _address = __webpack_require__(1180); +var _scval = __webpack_require__(7177); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * @typedef CreateInvocation + * + * @prop {'wasm'|'sac'} type a type indicating if this creation was a custom + * contract or a wrapping of an existing Stellar asset + * @prop {string} [token] when `type=='sac'`, the canonical {@link Asset} that + * is being wrapped by this Stellar Asset Contract + * @prop {object} [wasm] when `type=='wasm'`, add'l creation parameters + * + * @prop {string} wasm.hash hex hash of WASM bytecode backing this contract + * @prop {string} wasm.address contract address of this deployment + * @prop {string} wasm.salt hex salt that the user consumed when creating + * this contract (encoded in the resulting address) + * @prop {any[]} [wasm.constructorArgs] a list of natively-represented values + * (see {@link scValToNative}) that are passed to the constructor when + * creating this contract + */ + +/** + * @typedef ExecuteInvocation + * + * @prop {string} source the strkey of the contract (C...) being invoked + * @prop {string} function the name of the function being invoked + * @prop {any[]} args the natively-represented parameters to the function + * invocation (see {@link scValToNative} for rules on how they're + * represented a JS types) + */ + +/** + * @typedef InvocationTree + * @prop {'execute' | 'create'} type the type of invocation occurring, either + * contract creation or host function execution + * @prop {CreateInvocation | ExecuteInvocation} args the parameters to the + * invocation, depending on the type + * @prop {InvocationTree[]} invocations any sub-invocations that (may) occur + * as a result of this invocation (i.e. a tree of call stacks) + */ + +/** + * Turns a raw invocation tree into a human-readable format. + * + * This is designed to make the invocation tree easier to understand in order to + * inform users about the side-effects of their contract calls. This will help + * make informed decisions about whether or not a particular invocation will + * result in what you expect it to. + * + * @param {xdr.SorobanAuthorizedInvocation} root the raw XDR of the invocation, + * likely acquired from transaction simulation. this is either from the + * {@link Operation.invokeHostFunction} itself (the `func` field), or from + * the authorization entries ({@link xdr.SorobanAuthorizationEntry}, the + * `rootInvocation` field) + * + * @returns {InvocationTree} a human-readable version of the invocation tree + * + * @example + * Here, we show a browser modal after simulating an arbitrary transaction, + * `tx`, which we assume has an `Operation.invokeHostFunction` inside of it: + * + * ```typescript + * import { Server, buildInvocationTree } from '@stellar/stellar-sdk'; + * + * const s = new Server("fill in accordingly"); + * + * s.simulateTransaction(tx).then( + * (resp: SorobanRpc.SimulateTransactionResponse) => { + * if (SorobanRpc.isSuccessfulSim(resp) && ) { + * // bold assumption: there's a valid result with an auth entry + * alert( + * "You are authorizing the following invocation:\n" + + * JSON.stringify( + * buildInvocationTree(resp.result!.auth[0].rootInvocation()), + * null, + * 2 + * ) + * ); + * } + * } + * ); + * ``` + */ +function buildInvocationTree(root) { + var fn = root["function"](); + + /** @type {InvocationTree} */ + var output = {}; + + /** @type {xdr.CreateContractArgs|xdr.CreateContractArgsV2|xdr.InvokeContractArgs} */ + var inner = fn.value(); + switch (fn["switch"]().value) { + // sorobanAuthorizedFunctionTypeContractFn + case 0: + output.type = 'execute'; + output.args = { + source: _address.Address.fromScAddress(inner.contractAddress()).toString(), + "function": inner.functionName(), + args: inner.args().map(function (arg) { + return (0, _scval.scValToNative)(arg); + }) + }; + break; + + // sorobanAuthorizedFunctionTypeCreateContractHostFn + // sorobanAuthorizedFunctionTypeCreateContractV2HostFn + case 1: // fallthrough: just no ctor args in V1 + case 2: + { + var createV2 = fn["switch"]().value === 2; + output.type = 'create'; + output.args = {}; + + // If the executable is a WASM, the preimage MUST be an address. If it's a + // token, the preimage MUST be an asset. This is a cheeky way to check + // that, because wasm=0, token=1 and address=0, asset=1 in the XDR switch + // values. + // + // The first part may not be true in V2, but we'd need to update this code + // anyway so it can still be an error. + var _ref = [inner.executable(), inner.contractIdPreimage()], + exec = _ref[0], + preimage = _ref[1]; + if (!!exec["switch"]().value !== !!preimage["switch"]().value) { + throw new Error("creation function appears invalid: ".concat(JSON.stringify(inner), " (should be wasm+address or token+asset)")); + } + switch (exec["switch"]().value) { + // contractExecutableWasm + case 0: + { + /** @type {xdr.ContractIdPreimageFromAddress} */ + var details = preimage.fromAddress(); + output.args.type = 'wasm'; + output.args.wasm = _objectSpread({ + salt: details.salt().toString('hex'), + hash: exec.wasmHash().toString('hex'), + address: _address.Address.fromScAddress(details.address()).toString() + }, createV2 && { + constructorArgs: inner.constructorArgs().map(function (arg) { + return (0, _scval.scValToNative)(arg); + }) + }); + break; + } + + // contractExecutableStellarAsset + case 1: + output.args.type = 'sac'; + output.args.asset = _asset.Asset.fromOperation(preimage.fromAsset()).toString(); + break; + default: + throw new Error("unknown creation type: ".concat(JSON.stringify(exec))); + } + break; + } + default: + throw new Error("unknown invocation type (".concat(fn["switch"](), "): ").concat(JSON.stringify(fn))); + } + output.invocations = root.subInvocations().map(function (i) { + return buildInvocationTree(i); + }); + return output; +} + +/** + * @callback InvocationWalker + * + * @param {xdr.SorobanAuthorizedInvocation} node the currently explored node + * @param {number} depth the depth of the tree this node is occurring at (the + * root starts at a depth of 1) + * @param {xdr.SorobanAuthorizedInvocation} [parent] this `node`s parent node, + * if any (i.e. this doesn't exist at the root) + * + * @returns {boolean|null|void} returning exactly `false` is a hint to stop + * exploring, other values are ignored + */ + +/** + * Executes a callback function on each node in the tree until stopped. + * + * Nodes are walked in a depth-first order. Returning `false` from the callback + * stops further depth exploration at that node, but it does not stop the walk + * in a "global" view. + * + * @param {xdr.SorobanAuthorizedInvocation} root the tree to explore + * @param {InvocationWalker} callback the callback to execute for each node + * @returns {void} + */ +function walkInvocationTree(root, callback) { + walkHelper(root, 1, callback); +} +function walkHelper(node, depth, callback, parent) { + if (callback(node, depth, parent) === false /* allow void rv */) { + return; + } + node.subInvocations().forEach(function (i) { + return walkHelper(i, depth + 1, callback, node); + }); +} + +/***/ }), + +/***/ 3335: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _jsXdr = __webpack_require__(3740); +var cereal = { + XdrWriter: _jsXdr.XdrWriter, + XdrReader: _jsXdr.XdrReader +}; +var _default = exports["default"] = cereal; + +/***/ }), + +/***/ 6691: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Keypair = void 0; +var _tweetnacl = _interopRequireDefault(__webpack_require__(4940)); +var _signing = __webpack_require__(15); +var _strkey = __webpack_require__(7120); +var _hashing = __webpack_require__(9152); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": ["^"]}] */ +/** + * `Keypair` represents public (and secret) keys of the account. + * + * Currently `Keypair` only supports ed25519 but in a future this class can be abstraction layer for other + * public-key signature systems. + * + * Use more convenient methods to create `Keypair` object: + * * `{@link Keypair.fromPublicKey}` + * * `{@link Keypair.fromSecret}` + * * `{@link Keypair.random}` + * + * @constructor + * @param {object} keys At least one of keys must be provided. + * @param {string} keys.type Public-key signature system name. (currently only `ed25519` keys are supported) + * @param {Buffer} [keys.publicKey] Raw public key + * @param {Buffer} [keys.secretKey] Raw secret key (32-byte secret seed in ed25519`) + */ +var Keypair = exports.Keypair = /*#__PURE__*/function () { + function Keypair(keys) { + _classCallCheck(this, Keypair); + if (keys.type !== 'ed25519') { + throw new Error('Invalid keys type'); + } + this.type = keys.type; + if (keys.secretKey) { + keys.secretKey = Buffer.from(keys.secretKey); + if (keys.secretKey.length !== 32) { + throw new Error('secretKey length is invalid'); + } + this._secretSeed = keys.secretKey; + this._publicKey = (0, _signing.generate)(keys.secretKey); + this._secretKey = Buffer.concat([keys.secretKey, this._publicKey]); + if (keys.publicKey && !this._publicKey.equals(Buffer.from(keys.publicKey))) { + throw new Error('secretKey does not match publicKey'); + } + } else { + this._publicKey = Buffer.from(keys.publicKey); + if (this._publicKey.length !== 32) { + throw new Error('publicKey length is invalid'); + } + } + } + + /** + * Creates a new `Keypair` instance from secret. This can either be secret key or secret seed depending + * on underlying public-key signature system. Currently `Keypair` only supports ed25519. + * @param {string} secret secret key (ex. `SDAKFNYEIAORZKKCYRILFQKLLOCNPL5SWJ3YY5NM3ZH6GJSZGXHZEPQS`) + * @returns {Keypair} + */ + return _createClass(Keypair, [{ + key: "xdrAccountId", + value: function xdrAccountId() { + return new _xdr["default"].AccountId.publicKeyTypeEd25519(this._publicKey); + } + }, { + key: "xdrPublicKey", + value: function xdrPublicKey() { + return new _xdr["default"].PublicKey.publicKeyTypeEd25519(this._publicKey); + } + + /** + * Creates a {@link xdr.MuxedAccount} object from the public key. + * + * You will get a different type of muxed account depending on whether or not + * you pass an ID. + * + * @param {string} [id] - stringified integer indicating the underlying muxed + * ID of the new account object + * + * @return {xdr.MuxedAccount} + */ + }, { + key: "xdrMuxedAccount", + value: function xdrMuxedAccount(id) { + if (typeof id !== 'undefined') { + if (typeof id !== 'string') { + throw new TypeError("expected string for ID, got ".concat(_typeof(id))); + } + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromString(id), + ed25519: this._publicKey + })); + } + return new _xdr["default"].MuxedAccount.keyTypeEd25519(this._publicKey); + } + + /** + * Returns raw public key + * @returns {Buffer} + */ + }, { + key: "rawPublicKey", + value: function rawPublicKey() { + return this._publicKey; + } + }, { + key: "signatureHint", + value: function signatureHint() { + var a = this.xdrAccountId().toXDR(); + return a.slice(a.length - 4); + } + + /** + * Returns public key associated with this `Keypair` object. + * @returns {string} + */ + }, { + key: "publicKey", + value: function publicKey() { + return _strkey.StrKey.encodeEd25519PublicKey(this._publicKey); + } + + /** + * Returns secret key associated with this `Keypair` object + * @returns {string} + */ + }, { + key: "secret", + value: function secret() { + if (!this._secretSeed) { + throw new Error('no secret key available'); + } + if (this.type === 'ed25519') { + return _strkey.StrKey.encodeEd25519SecretSeed(this._secretSeed); + } + throw new Error('Invalid Keypair type'); + } + + /** + * Returns raw secret key. + * @returns {Buffer} + */ + }, { + key: "rawSecretKey", + value: function rawSecretKey() { + return this._secretSeed; + } + + /** + * Returns `true` if this `Keypair` object contains secret key and can sign. + * @returns {boolean} + */ + }, { + key: "canSign", + value: function canSign() { + return !!this._secretKey; + } + + /** + * Signs data. + * @param {Buffer} data Data to sign + * @returns {Buffer} + */ + }, { + key: "sign", + value: function sign(data) { + if (!this.canSign()) { + throw new Error('cannot sign: no secret key available'); + } + return (0, _signing.sign)(data, this._secretKey); + } + + /** + * Verifies if `signature` for `data` is valid. + * @param {Buffer} data Signed data + * @param {Buffer} signature Signature + * @returns {boolean} + */ + }, { + key: "verify", + value: function verify(data, signature) { + return (0, _signing.verify)(data, signature, this._publicKey); + } + + /** + * Returns the decorated signature (hint+sig) for arbitrary data. + * + * @param {Buffer} data arbitrary data to sign + * @return {xdr.DecoratedSignature} the raw signature structure which can be + * added directly to a transaction envelope + * + * @see TransactionBase.addDecoratedSignature + */ + }, { + key: "signDecorated", + value: function signDecorated(data) { + var signature = this.sign(data); + var hint = this.signatureHint(); + return new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signature + }); + } + + /** + * Returns the raw decorated signature (hint+sig) for a signed payload signer. + * + * The hint is defined as the last 4 bytes of the signer key XORed with last + * 4 bytes of the payload (zero-left-padded if necessary). + * + * @param {Buffer} data data to both sign and treat as the payload + * @return {xdr.DecoratedSignature} + * + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0040.md#signature-hint + * @see TransactionBase.addDecoratedSignature + */ + }, { + key: "signPayloadDecorated", + value: function signPayloadDecorated(data) { + var signature = this.sign(data); + var keyHint = this.signatureHint(); + var hint = Buffer.from(data.slice(-4)); + if (hint.length < 4) { + // append zeroes as needed + hint = Buffer.concat([hint, Buffer.alloc(4 - data.length, 0)]); + } + return new _xdr["default"].DecoratedSignature({ + hint: hint.map(function (_byte, i) { + return _byte ^ keyHint[i]; + }), + signature: signature + }); + } + }], [{ + key: "fromSecret", + value: function fromSecret(secret) { + var rawSecret = _strkey.StrKey.decodeEd25519SecretSeed(secret); + return this.fromRawEd25519Seed(rawSecret); + } + + /** + * Creates a new `Keypair` object from ed25519 secret key seed raw bytes. + * + * @param {Buffer} rawSeed Raw 32-byte ed25519 secret key seed + * @returns {Keypair} + */ + }, { + key: "fromRawEd25519Seed", + value: function fromRawEd25519Seed(rawSeed) { + return new this({ + type: 'ed25519', + secretKey: rawSeed + }); + } + + /** + * Returns `Keypair` object representing network master key. + * @param {string} networkPassphrase passphrase of the target stellar network (e.g. "Public Global Stellar Network ; September 2015"). + * @returns {Keypair} + */ + }, { + key: "master", + value: function master(networkPassphrase) { + if (!networkPassphrase) { + throw new Error('No network selected. Please pass a network argument, e.g. `Keypair.master(Networks.PUBLIC)`.'); + } + return this.fromRawEd25519Seed((0, _hashing.hash)(networkPassphrase)); + } + + /** + * Creates a new `Keypair` object from public key. + * @param {string} publicKey public key (ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`) + * @returns {Keypair} + */ + }, { + key: "fromPublicKey", + value: function fromPublicKey(publicKey) { + publicKey = _strkey.StrKey.decodeEd25519PublicKey(publicKey); + if (publicKey.length !== 32) { + throw new Error('Invalid Stellar public key'); + } + return new this({ + type: 'ed25519', + publicKey: publicKey + }); + } + + /** + * Create a random `Keypair` object. + * @returns {Keypair} + */ + }, { + key: "random", + value: function random() { + var secret = _tweetnacl["default"].randomBytes(32); + return this.fromRawEd25519Seed(secret); + } + }]); +}(); + +/***/ }), + +/***/ 2262: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LiquidityPoolAsset = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +var _get_liquidity_pool_id = __webpack_require__(5578); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * LiquidityPoolAsset class represents a liquidity pool trustline change. + * + * @constructor + * @param {Asset} assetA – The first asset in the Pool, it must respect the rule assetA < assetB. See {@link Asset.compare} for more details on how assets are sorted. + * @param {Asset} assetB – The second asset in the Pool, it must respect the rule assetA < assetB. See {@link Asset.compare} for more details on how assets are sorted. + * @param {number} fee – The liquidity pool fee. For now the only fee supported is `30`. + */ +var LiquidityPoolAsset = exports.LiquidityPoolAsset = /*#__PURE__*/function () { + function LiquidityPoolAsset(assetA, assetB, fee) { + _classCallCheck(this, LiquidityPoolAsset); + if (!assetA || !(assetA instanceof _asset.Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof _asset.Asset)) { + throw new Error('assetB is invalid'); + } + if (_asset.Asset.compare(assetA, assetB) !== -1) { + throw new Error('Assets are not in lexicographic order'); + } + if (!fee || fee !== _get_liquidity_pool_id.LiquidityPoolFeeV18) { + throw new Error('fee is invalid'); + } + this.assetA = assetA; + this.assetB = assetB; + this.fee = fee; + } + + /** + * Returns a liquidity pool asset object from its XDR ChangeTrustAsset object + * representation. + * @param {xdr.ChangeTrustAsset} ctAssetXdr - The asset XDR object. + * @returns {LiquidityPoolAsset} + */ + return _createClass(LiquidityPoolAsset, [{ + key: "toXDRObject", + value: + /** + * Returns the `xdr.ChangeTrustAsset` object for this liquidity pool asset. + * + * Note: To convert from an {@link Asset `Asset`} to `xdr.ChangeTrustAsset` + * please refer to the + * {@link Asset.toChangeTrustXDRObject `Asset.toChangeTrustXDRObject`} method. + * + * @returns {xdr.ChangeTrustAsset} XDR ChangeTrustAsset object. + */ + function toXDRObject() { + var lpConstantProductParamsXdr = new _xdr["default"].LiquidityPoolConstantProductParameters({ + assetA: this.assetA.toXDRObject(), + assetB: this.assetB.toXDRObject(), + fee: this.fee + }); + var lpParamsXdr = new _xdr["default"].LiquidityPoolParameters('liquidityPoolConstantProduct', lpConstantProductParamsXdr); + return new _xdr["default"].ChangeTrustAsset('assetTypePoolShare', lpParamsXdr); + } + + /** + * @returns {LiquidityPoolParameters} Liquidity pool parameters. + */ + }, { + key: "getLiquidityPoolParameters", + value: function getLiquidityPoolParameters() { + return _objectSpread(_objectSpread({}, this), {}, { + assetA: this.assetA, + assetB: this.assetB, + fee: this.fee + }); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {AssetType.liquidityPoolShares} asset type. Can only be `liquidity_pool_shares`. + */ + }, { + key: "getAssetType", + value: function getAssetType() { + return 'liquidity_pool_shares'; + } + + /** + * @param {LiquidityPoolAsset} other the LiquidityPoolAsset to compare + * @returns {boolean} `true` if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(other) { + return this.assetA.equals(other.assetA) && this.assetB.equals(other.assetB) && this.fee === other.fee; + } + }, { + key: "toString", + value: function toString() { + var poolId = (0, _get_liquidity_pool_id.getLiquidityPoolId)('constant_product', this.getLiquidityPoolParameters()).toString('hex'); + return "liquidity_pool:".concat(poolId); + } + }], [{ + key: "fromOperation", + value: function fromOperation(ctAssetXdr) { + var assetType = ctAssetXdr["switch"](); + if (assetType === _xdr["default"].AssetType.assetTypePoolShare()) { + var liquidityPoolParameters = ctAssetXdr.liquidityPool().constantProduct(); + return new this(_asset.Asset.fromOperation(liquidityPoolParameters.assetA()), _asset.Asset.fromOperation(liquidityPoolParameters.assetB()), liquidityPoolParameters.fee()); + } + throw new Error("Invalid asset type: ".concat(assetType.name)); + } + }]); +}(); + +/***/ }), + +/***/ 9353: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LiquidityPoolId = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * LiquidityPoolId class represents the asset referenced by a trustline to a + * liquidity pool. + * + * @constructor + * @param {string} liquidityPoolId - The ID of the liquidity pool in string 'hex'. + */ +var LiquidityPoolId = exports.LiquidityPoolId = /*#__PURE__*/function () { + function LiquidityPoolId(liquidityPoolId) { + _classCallCheck(this, LiquidityPoolId); + if (!liquidityPoolId) { + throw new Error('liquidityPoolId cannot be empty'); + } + if (!/^[a-f0-9]{64}$/.test(liquidityPoolId)) { + throw new Error('Liquidity pool ID is not a valid hash'); + } + this.liquidityPoolId = liquidityPoolId; + } + + /** + * Returns a liquidity pool ID object from its xdr.TrustLineAsset representation. + * @param {xdr.TrustLineAsset} tlAssetXdr - The asset XDR object. + * @returns {LiquidityPoolId} + */ + return _createClass(LiquidityPoolId, [{ + key: "toXDRObject", + value: + /** + * Returns the `xdr.TrustLineAsset` object for this liquidity pool ID. + * + * Note: To convert from {@link Asset `Asset`} to `xdr.TrustLineAsset` please + * refer to the + * {@link Asset.toTrustLineXDRObject `Asset.toTrustLineXDRObject`} method. + * + * @returns {xdr.TrustLineAsset} XDR LiquidityPoolId object + */ + function toXDRObject() { + var xdrPoolId = _xdr["default"].PoolId.fromXDR(this.liquidityPoolId, 'hex'); + return new _xdr["default"].TrustLineAsset('assetTypePoolShare', xdrPoolId); + } + + /** + * @returns {string} Liquidity pool ID. + */ + }, { + key: "getLiquidityPoolId", + value: function getLiquidityPoolId() { + return String(this.liquidityPoolId); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {AssetType.liquidityPoolShares} asset type. Can only be `liquidity_pool_shares`. + */ + }, { + key: "getAssetType", + value: function getAssetType() { + return 'liquidity_pool_shares'; + } + + /** + * @param {LiquidityPoolId} asset LiquidityPoolId to compare. + * @returns {boolean} `true` if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(asset) { + return this.liquidityPoolId === asset.getLiquidityPoolId(); + } + }, { + key: "toString", + value: function toString() { + return "liquidity_pool:".concat(this.liquidityPoolId); + } + }], [{ + key: "fromOperation", + value: function fromOperation(tlAssetXdr) { + var assetType = tlAssetXdr["switch"](); + if (assetType === _xdr["default"].AssetType.assetTypePoolShare()) { + var liquidityPoolId = tlAssetXdr.liquidityPoolId().toString('hex'); + return new this(liquidityPoolId); + } + throw new Error("Invalid asset type: ".concat(assetType.name)); + } + }]); +}(); + +/***/ }), + +/***/ 4172: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.MemoText = exports.MemoReturn = exports.MemoNone = exports.MemoID = exports.MemoHash = exports.Memo = void 0; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Type of {@link Memo}. + */ +var MemoNone = exports.MemoNone = 'none'; +/** + * Type of {@link Memo}. + */ +var MemoID = exports.MemoID = 'id'; +/** + * Type of {@link Memo}. + */ +var MemoText = exports.MemoText = 'text'; +/** + * Type of {@link Memo}. + */ +var MemoHash = exports.MemoHash = 'hash'; +/** + * Type of {@link Memo}. + */ +var MemoReturn = exports.MemoReturn = 'return'; + +/** + * `Memo` represents memos attached to transactions. + * + * @param {string} type - `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn` + * @param {*} value - `string` for `MemoID`, `MemoText`, buffer of hex string for `MemoHash` or `MemoReturn` + * @see [Transactions concept](https://developers.stellar.org/docs/glossary/transactions/) + * @class Memo + */ +var Memo = exports.Memo = /*#__PURE__*/function () { + function Memo(type) { + var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + _classCallCheck(this, Memo); + this._type = type; + this._value = value; + switch (this._type) { + case MemoNone: + break; + case MemoID: + Memo._validateIdValue(value); + break; + case MemoText: + Memo._validateTextValue(value); + break; + case MemoHash: + case MemoReturn: + Memo._validateHashValue(value); + // We want MemoHash and MemoReturn to have Buffer as a value + if (typeof value === 'string') { + this._value = Buffer.from(value, 'hex'); + } + break; + default: + throw new Error('Invalid memo type'); + } + } + + /** + * Contains memo type: `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn` + */ + return _createClass(Memo, [{ + key: "type", + get: function get() { + return this._type; + }, + set: function set(type) { + throw new Error('Memo is immutable'); + } + + /** + * Contains memo value: + * * `null` for `MemoNone`, + * * `string` for `MemoID`, + * * `Buffer` for `MemoText` after decoding using `fromXDRObject`, original value otherwise, + * * `Buffer` for `MemoHash`, `MemoReturn`. + */ + }, { + key: "value", + get: function get() { + switch (this._type) { + case MemoNone: + return null; + case MemoID: + case MemoText: + return this._value; + case MemoHash: + case MemoReturn: + return Buffer.from(this._value); + default: + throw new Error('Invalid memo type'); + } + }, + set: function set(value) { + throw new Error('Memo is immutable'); + } + }, { + key: "toXDRObject", + value: + /** + * Returns XDR memo object. + * @returns {xdr.Memo} + */ + function toXDRObject() { + switch (this._type) { + case MemoNone: + return _xdr["default"].Memo.memoNone(); + case MemoID: + return _xdr["default"].Memo.memoId(_jsXdr.UnsignedHyper.fromString(this._value)); + case MemoText: + return _xdr["default"].Memo.memoText(this._value); + case MemoHash: + return _xdr["default"].Memo.memoHash(this._value); + case MemoReturn: + return _xdr["default"].Memo.memoReturn(this._value); + default: + return null; + } + } + + /** + * Returns {@link Memo} from XDR memo object. + * @param {xdr.Memo} object XDR memo object + * @returns {Memo} + */ + }], [{ + key: "_validateIdValue", + value: function _validateIdValue(value) { + var error = new Error("Expects a int64 as a string. Got ".concat(value)); + if (typeof value !== 'string') { + throw error; + } + var number; + try { + number = new _bignumber["default"](value); + } catch (e) { + throw error; + } + + // Infinity + if (!number.isFinite()) { + throw error; + } + + // NaN + if (number.isNaN()) { + throw error; + } + } + }, { + key: "_validateTextValue", + value: function _validateTextValue(value) { + if (!_xdr["default"].Memo.armTypeForArm('text').isValid(value)) { + throw new Error('Expects string, array or buffer, max 28 bytes'); + } + } + }, { + key: "_validateHashValue", + value: function _validateHashValue(value) { + var error = new Error("Expects a 32 byte hash value or hex encoded string. Got ".concat(value)); + if (value === null || typeof value === 'undefined') { + throw error; + } + var valueBuffer; + if (typeof value === 'string') { + if (!/^[0-9A-Fa-f]{64}$/g.test(value)) { + throw error; + } + valueBuffer = Buffer.from(value, 'hex'); + } else if (Buffer.isBuffer(value)) { + valueBuffer = Buffer.from(value); + } else { + throw error; + } + if (!valueBuffer.length || valueBuffer.length !== 32) { + throw error; + } + } + + /** + * Returns an empty memo (`MemoNone`). + * @returns {Memo} + */ + }, { + key: "none", + value: function none() { + return new Memo(MemoNone); + } + + /** + * Creates and returns a `MemoText` memo. + * @param {string} text - memo text + * @returns {Memo} + */ + }, { + key: "text", + value: function text(_text) { + return new Memo(MemoText, _text); + } + + /** + * Creates and returns a `MemoID` memo. + * @param {string} id - 64-bit number represented as a string + * @returns {Memo} + */ + }, { + key: "id", + value: function id(_id) { + return new Memo(MemoID, _id); + } + + /** + * Creates and returns a `MemoHash` memo. + * @param {array|string} hash - 32 byte hash or hex encoded string + * @returns {Memo} + */ + }, { + key: "hash", + value: function hash(_hash) { + return new Memo(MemoHash, _hash); + } + + /** + * Creates and returns a `MemoReturn` memo. + * @param {array|string} hash - 32 byte hash or hex encoded string + * @returns {Memo} + */ + }, { + key: "return", + value: function _return(hash) { + return new Memo(MemoReturn, hash); + } + }, { + key: "fromXDRObject", + value: function fromXDRObject(object) { + switch (object.arm()) { + case 'id': + return Memo.id(object.value().toString()); + case 'text': + return Memo.text(object.value()); + case 'hash': + return Memo.hash(object.value()); + case 'retHash': + return Memo["return"](object.value()); + default: + break; + } + if (typeof object.value() === 'undefined') { + return Memo.none(); + } + throw new Error('Unknown type'); + } + }]); +}(); + +/***/ }), + +/***/ 2243: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.MuxedAccount = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _account = __webpack_require__(2135); +var _strkey = __webpack_require__(7120); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Represents a muxed account for transactions and operations. + * + * A muxed (or *multiplexed*) account (defined rigorously in + * [CAP-27](https://stellar.org/protocol/cap-27) and briefly in + * [SEP-23](https://stellar.org/protocol/sep-23)) is one that resolves a single + * Stellar `G...`` account to many different underlying IDs. + * + * For example, you may have a single Stellar address for accounting purposes: + * GA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJVSGZ + * + * Yet would like to use it for 4 different family members: + * 1: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAGZFQ + * 2: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAALIWQ + * 3: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAPYHQ + * 4: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAQLQQ + * + * This object makes it easy to create muxed accounts from regular accounts, + * duplicate them, get/set the underlying IDs, etc. without mucking around with + * the raw XDR. + * + * Because muxed accounts are purely an off-chain convention, they all share the + * sequence number tied to their underlying G... account. Thus, this object + * *requires* an {@link Account} instance to be passed in, so that muxed + * instances of an account can collectively modify the sequence number whenever + * a muxed account is used as the source of a @{link Transaction} with {@link + * TransactionBuilder}. + * + * @constructor + * + * @param {Account} account - the @{link Account} instance representing the + * underlying G... address + * @param {string} id - a stringified uint64 value that represents the + * ID of the muxed account + * + * @link https://developers.stellar.org/docs/glossary/muxed-accounts/ + */ +var MuxedAccount = exports.MuxedAccount = /*#__PURE__*/function () { + function MuxedAccount(baseAccount, id) { + _classCallCheck(this, MuxedAccount); + var accountId = baseAccount.accountId(); + if (!_strkey.StrKey.isValidEd25519PublicKey(accountId)) { + throw new Error('accountId is invalid'); + } + this.account = baseAccount; + this._muxedXdr = (0, _decode_encode_muxed_account.encodeMuxedAccount)(accountId, id); + this._mAddress = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(this._muxedXdr); + this._id = id; + } + + /** + * Parses an M-address into a MuxedAccount object. + * + * @param {string} mAddress - an M-address to transform + * @param {string} sequenceNum - the sequence number of the underlying {@link + * Account}, to use for the underlying base account (@link + * MuxedAccount.baseAccount). If you're using the SDK, you can use + * `server.loadAccount` to fetch this if you don't know it. + * + * @return {MuxedAccount} + */ + return _createClass(MuxedAccount, [{ + key: "baseAccount", + value: + /** + * @return {Account} the underlying account object shared among all muxed + * accounts with this Stellar address + */ + function baseAccount() { + return this.account; + } + + /** + * @return {string} the M-address representing this account's (G-address, ID) + */ + }, { + key: "accountId", + value: function accountId() { + return this._mAddress; + } + }, { + key: "id", + value: function id() { + return this._id; + } + }, { + key: "setId", + value: function setId(id) { + if (typeof id !== 'string') { + throw new Error('id should be a string representing a number (uint64)'); + } + this._muxedXdr.med25519().id(_xdr["default"].Uint64.fromString(id)); + this._mAddress = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(this._muxedXdr); + this._id = id; + return this; + } + + /** + * Accesses the underlying account's sequence number. + * @return {string} strigified sequence number for the underlying account + */ + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this.account.sequenceNumber(); + } + + /** + * Increments the underlying account's sequence number by one. + * @return {void} + */ + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + return this.account.incrementSequenceNumber(); + } + + /** + * @return {xdr.MuxedAccount} the XDR object representing this muxed account's + * G-address and uint64 ID + */ + }, { + key: "toXDRObject", + value: function toXDRObject() { + return this._muxedXdr; + } + }, { + key: "equals", + value: function equals(otherMuxedAccount) { + return this.accountId() === otherMuxedAccount.accountId(); + } + }], [{ + key: "fromAddress", + value: function fromAddress(mAddress, sequenceNum) { + var muxedAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(mAddress); + var gAddress = (0, _decode_encode_muxed_account.extractBaseAddress)(mAddress); + var id = muxedAccount.med25519().id().toString(); + return new MuxedAccount(new _account.Account(gAddress, sequenceNum), id); + } + }]); +}(); + +/***/ }), + +/***/ 6202: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Networks = void 0; +/** + * Contains passphrases for common networks: + * * `Networks.PUBLIC`: `Public Global Stellar Network ; September 2015` + * * `Networks.TESTNET`: `Test SDF Network ; September 2015` + * * `Networks.FUTURENET`: `Test SDF Future Network ; October 2022` + * * `Networks.STANDALONE`: `Standalone Network ; February 2017` + * + * @type {{PUBLIC: string, TESTNET: string, FUTURENET: string, STANDALONE: string }} + */ +var Networks = exports.Networks = { + PUBLIC: 'Public Global Stellar Network ; September 2015', + TESTNET: 'Test SDF Network ; September 2015', + FUTURENET: 'Test SDF Future Network ; October 2022', + SANDBOX: 'Local Sandbox Stellar Network ; September 2022', + STANDALONE: 'Standalone Network ; February 2017' +}; + +/***/ }), + +/***/ 8549: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "Int128", ({ + enumerable: true, + get: function get() { + return _int.Int128; + } +})); +Object.defineProperty(exports, "Int256", ({ + enumerable: true, + get: function get() { + return _int2.Int256; + } +})); +Object.defineProperty(exports, "ScInt", ({ + enumerable: true, + get: function get() { + return _sc_int.ScInt; + } +})); +Object.defineProperty(exports, "Uint128", ({ + enumerable: true, + get: function get() { + return _uint.Uint128; + } +})); +Object.defineProperty(exports, "Uint256", ({ + enumerable: true, + get: function get() { + return _uint2.Uint256; + } +})); +Object.defineProperty(exports, "XdrLargeInt", ({ + enumerable: true, + get: function get() { + return _xdr_large_int.XdrLargeInt; + } +})); +exports.scValToBigInt = scValToBigInt; +var _xdr_large_int = __webpack_require__(7429); +var _uint = __webpack_require__(6272); +var _uint2 = __webpack_require__(8672); +var _int = __webpack_require__(5487); +var _int2 = __webpack_require__(4063); +var _sc_int = __webpack_require__(3317); +/** + * Transforms an opaque {@link xdr.ScVal} into a native bigint, if possible. + * + * If you then want to use this in the abstractions provided by this module, + * you can pass it to the constructor of {@link XdrLargeInt}. + * + * @example + * let scv = contract.call("add", x, y); // assume it returns an xdr.ScVal + * let bigi = scValToBigInt(scv); + * + * new ScInt(bigi); // if you don't care about types, and + * new XdrLargeInt('i128', bigi); // if you do + * + * @param {xdr.ScVal} scv - the raw XDR value to parse into an integer + * @returns {bigint} the native value of this input value + * + * @throws {TypeError} if the `scv` input value doesn't represent an integer + */ +function scValToBigInt(scv) { + var scIntType = _xdr_large_int.XdrLargeInt.getType(scv["switch"]().name); + switch (scv["switch"]().name) { + case 'scvU32': + case 'scvI32': + return BigInt(scv.value()); + case 'scvU64': + case 'scvI64': + return new _xdr_large_int.XdrLargeInt(scIntType, scv.value()).toBigInt(); + case 'scvU128': + case 'scvI128': + return new _xdr_large_int.XdrLargeInt(scIntType, [scv.value().lo(), scv.value().hi()]).toBigInt(); + case 'scvU256': + case 'scvI256': + return new _xdr_large_int.XdrLargeInt(scIntType, [scv.value().loLo(), scv.value().loHi(), scv.value().hiLo(), scv.value().hiHi()]).toBigInt(); + default: + throw TypeError("expected integer type, got ".concat(scv["switch"]())); + } +} + +/***/ }), + +/***/ 5487: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Int128 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Int128 = exports.Int128 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct a signed 128-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Int128() { + _classCallCheck(this, Int128); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Int128, [args]); + } + _inherits(Int128, _LargeInt); + return _createClass(Int128, [{ + key: "unsigned", + get: function get() { + return false; + } + }, { + key: "size", + get: function get() { + return 128; + } + }]); +}(_jsXdr.LargeInt); +Int128.defineIntBoundaries(); + +/***/ }), + +/***/ 4063: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Int256 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Int256 = exports.Int256 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct a signed 256-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Int256() { + _classCallCheck(this, Int256); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Int256, [args]); + } + _inherits(Int256, _LargeInt); + return _createClass(Int256, [{ + key: "unsigned", + get: function get() { + return false; + } + }, { + key: "size", + get: function get() { + return 256; + } + }]); +}(_jsXdr.LargeInt); +Int256.defineIntBoundaries(); + +/***/ }), + +/***/ 3317: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.ScInt = void 0; +var _xdr_large_int = __webpack_require__(7429); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Provides an easier way to manipulate large numbers for Stellar operations. + * + * You can instantiate this "**s**mart **c**ontract integer" value either from + * bigints, strings, or numbers (whole numbers, or this will throw). + * + * If you need to create a native BigInt from a list of integer "parts" (for + * example, you have a series of encoded 32-bit integers that represent a larger + * value), you can use the lower level abstraction {@link XdrLargeInt}. For + * example, you could do `new XdrLargeInt('u128', bytes...).toBigInt()`. + * + * @example + * import { xdr, ScInt, scValToBigInt } from "@stellar/stellar-base"; + * + * // You have an ScVal from a contract and want to parse it into JS native. + * const value = xdr.ScVal.fromXDR(someXdr, "base64"); + * const bigi = scValToBigInt(value); // grab it as a BigInt + * let sci = new ScInt(bigi); + * + * sci.toNumber(); // gives native JS type (w/ size check) + * sci.toBigInt(); // gives the native BigInt value + * sci.toU64(); // gives ScValType-specific XDR constructs (with size checks) + * + * // You have a number and want to shove it into a contract. + * sci = ScInt(0xdeadcafebabe); + * sci.toBigInt() // returns 244838016400062n + * sci.toNumber() // throws: too large + * + * // Pass any to e.g. a Contract.call(), conversion happens automatically + * // regardless of the initial type. + * const scValU128 = sci.toU128(); + * const scValI256 = sci.toI256(); + * const scValU64 = sci.toU64(); + * + * // Lots of ways to initialize: + * ScInt("123456789123456789") + * ScInt(123456789123456789n); + * ScInt(1n << 140n); + * ScInt(-42); + * ScInt(scValToBigInt(scValU128)); // from above + * + * // If you know the type ahead of time (accessing `.raw` is faster than + * // conversions), you can specify the type directly (otherwise, it's + * // interpreted from the numbers you pass in): + * const i = ScInt(123456789n, { type: "u256" }); + * + * // For example, you can use the underlying `sdk.U256` and convert it to an + * // `xdr.ScVal` directly like so: + * const scv = new xdr.ScVal.scvU256(i.raw); + * + * // Or reinterpret it as a different type (size permitting): + * const scv = i.toI64(); + * + * @param {number|bigint|string} value - a single, integer-like value which will + * be interpreted in the smallest appropriate XDR type supported by Stellar + * (64, 128, or 256 bit integer values). signed values are supported, though + * they are sanity-checked against `opts.type`. if you need 32-bit values, + * you can construct them directly without needing this wrapper, e.g. + * `xdr.ScVal.scvU32(1234)`. + * + * @param {object} [opts] - an optional object controlling optional parameters + * @param {string} [opts.type] - force a specific data type. the type choices + * are: 'i64', 'u64', 'i128', 'u128', 'i256', and 'u256' (default: the + * smallest one that fits the `value`) + * + * @throws {RangeError} if the `value` is invalid (e.g. floating point), too + * large (i.e. exceeds a 256-bit value), or doesn't fit in the `opts.type` + * @throws {TypeError} on missing parameters, or if the "signedness" of `opts` + * doesn't match input `value`, e.g. passing `{type: 'u64'}` yet passing -1n + * @throws {SyntaxError} if a string `value` can't be parsed as a big integer + */ +var ScInt = exports.ScInt = /*#__PURE__*/function (_XdrLargeInt) { + function ScInt(value, opts) { + var _opts$type; + _classCallCheck(this, ScInt); + var signed = value < 0; + var type = (_opts$type = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type !== void 0 ? _opts$type : ''; + if (type.startsWith('u') && signed) { + throw TypeError("specified type ".concat(opts.type, " yet negative (").concat(value, ")")); + } + + // If unspecified, we make a best guess at the type based on the bit length + // of the value, treating 64 as a minimum and 256 as a maximum. + if (type === '') { + type = signed ? 'i' : 'u'; + var bitlen = nearestBigIntSize(value); + switch (bitlen) { + case 64: + case 128: + case 256: + type += bitlen.toString(); + break; + default: + throw RangeError("expected 64/128/256 bits for input (".concat(value, "), got ").concat(bitlen)); + } + } + return _callSuper(this, ScInt, [type, value]); + } + _inherits(ScInt, _XdrLargeInt); + return _createClass(ScInt); +}(_xdr_large_int.XdrLargeInt); +function nearestBigIntSize(bigI) { + var _find; + // Note: Even though BigInt.toString(2) includes the negative sign for + // negative values (???), the following is still accurate, because the + // negative sign would be represented by a sign bit. + var bitlen = bigI.toString(2).length; + return (_find = [64, 128, 256].find(function (len) { + return bitlen <= len; + })) !== null && _find !== void 0 ? _find : bitlen; +} + +/***/ }), + +/***/ 6272: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Uint128 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Uint128 = exports.Uint128 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct an unsigned 128-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Uint128() { + _classCallCheck(this, Uint128); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Uint128, [args]); + } + _inherits(Uint128, _LargeInt); + return _createClass(Uint128, [{ + key: "unsigned", + get: function get() { + return true; + } + }, { + key: "size", + get: function get() { + return 128; + } + }]); +}(_jsXdr.LargeInt); +Uint128.defineIntBoundaries(); + +/***/ }), + +/***/ 8672: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Uint256 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Uint256 = exports.Uint256 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct an unsigned 256-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Uint256() { + _classCallCheck(this, Uint256); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Uint256, [args]); + } + _inherits(Uint256, _LargeInt); + return _createClass(Uint256, [{ + key: "unsigned", + get: function get() { + return true; + } + }, { + key: "size", + get: function get() { + return 256; + } + }]); +}(_jsXdr.LargeInt); +Uint256.defineIntBoundaries(); + +/***/ }), + +/***/ 7429: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.XdrLargeInt = void 0; +var _jsXdr = __webpack_require__(3740); +var _uint = __webpack_require__(6272); +var _uint2 = __webpack_require__(8672); +var _int = __webpack_require__(5487); +var _int2 = __webpack_require__(4063); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": [">>"]}] */ +/** + * A wrapper class to represent large XDR-encodable integers. + * + * This operates at a lower level than {@link ScInt} by forcing you to specify + * the type / width / size in bits of the integer you're targeting, regardless + * of the input value(s) you provide. + * + * @param {string} type - force a specific data type. the type choices are: + * 'i64', 'u64', 'i128', 'u128', 'i256', and 'u256' (default: the smallest + * one that fits the `value`) (see {@link XdrLargeInt.isType}) + * @param {number|bigint|string|Array} values a list of + * integer-like values interpreted in big-endian order + */ +var XdrLargeInt = exports.XdrLargeInt = /*#__PURE__*/function () { + function XdrLargeInt(type, values) { + _classCallCheck(this, XdrLargeInt); + /** @type {xdr.LargeInt} */ + _defineProperty(this, "int", void 0); + // child class of a jsXdr.LargeInt + /** @type {string} */ + _defineProperty(this, "type", void 0); + if (!(values instanceof Array)) { + values = [values]; + } + + // normalize values to one type + values = values.map(function (i) { + // micro-optimization to no-op on the likeliest input value: + if (typeof i === 'bigint') { + return i; + } + if (i instanceof XdrLargeInt) { + return i.toBigInt(); + } + return BigInt(i); + }); + switch (type) { + case 'i64': + this["int"] = new _jsXdr.Hyper(values); + break; + case 'i128': + this["int"] = new _int.Int128(values); + break; + case 'i256': + this["int"] = new _int2.Int256(values); + break; + case 'u64': + this["int"] = new _jsXdr.UnsignedHyper(values); + break; + case 'u128': + this["int"] = new _uint.Uint128(values); + break; + case 'u256': + this["int"] = new _uint2.Uint256(values); + break; + default: + throw TypeError("invalid type: ".concat(type)); + } + this.type = type; + } + + /** + * @returns {number} + * @throws {RangeError} if the value can't fit into a Number + */ + return _createClass(XdrLargeInt, [{ + key: "toNumber", + value: function toNumber() { + var bi = this["int"].toBigInt(); + if (bi > Number.MAX_SAFE_INTEGER || bi < Number.MIN_SAFE_INTEGER) { + throw RangeError("value ".concat(bi, " not in range for Number ") + "[".concat(Number.MAX_SAFE_INTEGER, ", ").concat(Number.MIN_SAFE_INTEGER, "]")); + } + return Number(bi); + } + + /** @returns {bigint} */ + }, { + key: "toBigInt", + value: function toBigInt() { + return this["int"].toBigInt(); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = I64` */ + }, { + key: "toI64", + value: function toI64() { + this._sizeCheck(64); + var v = this.toBigInt(); + if (BigInt.asIntN(64, v) !== v) { + throw RangeError("value too large for i64: ".concat(v)); + } + return _xdr["default"].ScVal.scvI64(new _xdr["default"].Int64(v)); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = U64` */ + }, { + key: "toU64", + value: function toU64() { + this._sizeCheck(64); + return _xdr["default"].ScVal.scvU64(new _xdr["default"].Uint64(BigInt.asUintN(64, this.toBigInt())) // reiterpret as unsigned + ); + } + + /** + * @returns {xdr.ScVal} the integer encoded with `ScValType = I128` + * @throws {RangeError} if the value cannot fit in 128 bits + */ + }, { + key: "toI128", + value: function toI128() { + this._sizeCheck(128); + var v = this["int"].toBigInt(); + var hi64 = BigInt.asIntN(64, v >> 64n); // encode top 64 w/ sign bit + var lo64 = BigInt.asUintN(64, v); // grab btm 64, encode sign + + return _xdr["default"].ScVal.scvI128(new _xdr["default"].Int128Parts({ + hi: new _xdr["default"].Int64(hi64), + lo: new _xdr["default"].Uint64(lo64) + })); + } + + /** + * @returns {xdr.ScVal} the integer encoded with `ScValType = U128` + * @throws {RangeError} if the value cannot fit in 128 bits + */ + }, { + key: "toU128", + value: function toU128() { + this._sizeCheck(128); + var v = this["int"].toBigInt(); + return _xdr["default"].ScVal.scvU128(new _xdr["default"].UInt128Parts({ + hi: new _xdr["default"].Uint64(BigInt.asUintN(64, v >> 64n)), + lo: new _xdr["default"].Uint64(BigInt.asUintN(64, v)) + })); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = I256` */ + }, { + key: "toI256", + value: function toI256() { + var v = this["int"].toBigInt(); + var hiHi64 = BigInt.asIntN(64, v >> 192n); // keep sign bit + var hiLo64 = BigInt.asUintN(64, v >> 128n); + var loHi64 = BigInt.asUintN(64, v >> 64n); + var loLo64 = BigInt.asUintN(64, v); + return _xdr["default"].ScVal.scvI256(new _xdr["default"].Int256Parts({ + hiHi: new _xdr["default"].Int64(hiHi64), + hiLo: new _xdr["default"].Uint64(hiLo64), + loHi: new _xdr["default"].Uint64(loHi64), + loLo: new _xdr["default"].Uint64(loLo64) + })); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = U256` */ + }, { + key: "toU256", + value: function toU256() { + var v = this["int"].toBigInt(); + var hiHi64 = BigInt.asUintN(64, v >> 192n); // encode sign bit + var hiLo64 = BigInt.asUintN(64, v >> 128n); + var loHi64 = BigInt.asUintN(64, v >> 64n); + var loLo64 = BigInt.asUintN(64, v); + return _xdr["default"].ScVal.scvU256(new _xdr["default"].UInt256Parts({ + hiHi: new _xdr["default"].Uint64(hiHi64), + hiLo: new _xdr["default"].Uint64(hiLo64), + loHi: new _xdr["default"].Uint64(loHi64), + loLo: new _xdr["default"].Uint64(loLo64) + })); + } + + /** @returns {xdr.ScVal} the smallest interpretation of the stored value */ + }, { + key: "toScVal", + value: function toScVal() { + switch (this.type) { + case 'i64': + return this.toI64(); + case 'i128': + return this.toI128(); + case 'i256': + return this.toI256(); + case 'u64': + return this.toU64(); + case 'u128': + return this.toU128(); + case 'u256': + return this.toU256(); + default: + throw TypeError("invalid type: ".concat(this.type)); + } + } + }, { + key: "valueOf", + value: function valueOf() { + return this["int"].valueOf(); + } + }, { + key: "toString", + value: function toString() { + return this["int"].toString(); + } + }, { + key: "toJSON", + value: function toJSON() { + return { + value: this.toBigInt().toString(), + type: this.type + }; + } + }, { + key: "_sizeCheck", + value: function _sizeCheck(bits) { + if (this["int"].size > bits) { + throw RangeError("value too large for ".concat(bits, " bits (").concat(this.type, ")")); + } + } + }], [{ + key: "isType", + value: function isType(type) { + switch (type) { + case 'i64': + case 'i128': + case 'i256': + case 'u64': + case 'u128': + case 'u256': + return true; + default: + return false; + } + } + + /** + * Convert the raw `ScValType` string (e.g. 'scvI128', generated by the XDR) + * to a type description for {@link XdrLargeInt} construction (e.g. 'i128') + * + * @param {string} scvType the `xdr.ScValType` as a string + * @returns {string} a suitable equivalent type to construct this object + */ + }, { + key: "getType", + value: function getType(scvType) { + return scvType.slice(3).toLowerCase(); + } + }]); +}(); + +/***/ }), + +/***/ 7237: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Operation = exports.AuthRevocableFlag = exports.AuthRequiredFlag = exports.AuthImmutableFlag = exports.AuthClawbackEnabledFlag = void 0; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _util = __webpack_require__(645); +var _continued_fraction = __webpack_require__(4151); +var _asset = __webpack_require__(1764); +var _liquidity_pool_asset = __webpack_require__(2262); +var _claimant = __webpack_require__(1387); +var _strkey = __webpack_require__(7120); +var _liquidity_pool_id = __webpack_require__(9353); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var ops = _interopRequireWildcard(__webpack_require__(7511)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint-disable no-bitwise */ +var ONE = 10000000; +var MAX_INT64 = '9223372036854775807'; + +/** + * When set using `{@link Operation.setOptions}` option, requires the issuing + * account to give other accounts permission before they can hold the issuing + * account’s credit. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthRequiredFlag = exports.AuthRequiredFlag = 1 << 0; +/** + * When set using `{@link Operation.setOptions}` option, allows the issuing + * account to revoke its credit held by other accounts. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthRevocableFlag = exports.AuthRevocableFlag = 1 << 1; +/** + * When set using `{@link Operation.setOptions}` option, then none of the + * authorization flags can be set and the account can never be deleted. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthImmutableFlag = exports.AuthImmutableFlag = 1 << 2; + +/** + * When set using `{@link Operation.setOptions}` option, then any trustlines + * created by this account can have a ClawbackOp operation submitted for the + * corresponding asset. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthClawbackEnabledFlag = exports.AuthClawbackEnabledFlag = 1 << 3; + +/** + * `Operation` class represents + * [operations](https://developers.stellar.org/docs/glossary/operations/) in + * Stellar network. + * + * Use one of static methods to create operations: + * * `{@link Operation.createAccount}` + * * `{@link Operation.payment}` + * * `{@link Operation.pathPaymentStrictReceive}` + * * `{@link Operation.pathPaymentStrictSend}` + * * `{@link Operation.manageSellOffer}` + * * `{@link Operation.manageBuyOffer}` + * * `{@link Operation.createPassiveSellOffer}` + * * `{@link Operation.setOptions}` + * * `{@link Operation.changeTrust}` + * * `{@link Operation.allowTrust}` + * * `{@link Operation.accountMerge}` + * * `{@link Operation.inflation}` + * * `{@link Operation.manageData}` + * * `{@link Operation.bumpSequence}` + * * `{@link Operation.createClaimableBalance}` + * * `{@link Operation.claimClaimableBalance}` + * * `{@link Operation.beginSponsoringFutureReserves}` + * * `{@link Operation.endSponsoringFutureReserves}` + * * `{@link Operation.revokeAccountSponsorship}` + * * `{@link Operation.revokeTrustlineSponsorship}` + * * `{@link Operation.revokeOfferSponsorship}` + * * `{@link Operation.revokeDataSponsorship}` + * * `{@link Operation.revokeClaimableBalanceSponsorship}` + * * `{@link Operation.revokeLiquidityPoolSponsorship}` + * * `{@link Operation.revokeSignerSponsorship}` + * * `{@link Operation.clawback}` + * * `{@link Operation.clawbackClaimableBalance}` + * * `{@link Operation.setTrustLineFlags}` + * * `{@link Operation.liquidityPoolDeposit}` + * * `{@link Operation.liquidityPoolWithdraw}` + * * `{@link Operation.invokeHostFunction}`, which has the following additional + * "pseudo-operations" that make building host functions easier: + * - `{@link Operation.createStellarAssetContract}` + * - `{@link Operation.invokeContractFunction}` + * - `{@link Operation.createCustomContract}` + * - `{@link Operation.uploadContractWasm}` + * * `{@link Operation.extendFootprintTtlOp}` + * * `{@link Operation.restoreFootprint}` + * + * @class Operation + */ +var Operation = exports.Operation = /*#__PURE__*/function () { + function Operation() { + _classCallCheck(this, Operation); + } + return _createClass(Operation, null, [{ + key: "setSourceAccount", + value: function setSourceAccount(opAttributes, opts) { + if (opts.source) { + try { + opAttributes.sourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.source); + } catch (e) { + throw new Error('Source address is invalid'); + } + } + } + + /** + * Deconstructs the raw XDR operation object into the structured object that + * was used to create the operation (i.e. the `opts` parameter to most ops). + * + * @param {xdr.Operation} operation - An XDR Operation. + * @return {Operation} + */ + }, { + key: "fromXDRObject", + value: function fromXDRObject(operation) { + var result = {}; + if (operation.sourceAccount()) { + result.source = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(operation.sourceAccount()); + } + var attrs = operation.body().value(); + var operationName = operation.body()["switch"]().name; + switch (operationName) { + case 'createAccount': + { + result.type = 'createAccount'; + result.destination = accountIdtoAddress(attrs.destination()); + result.startingBalance = this._fromXDRAmount(attrs.startingBalance()); + break; + } + case 'payment': + { + result.type = 'payment'; + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.amount = this._fromXDRAmount(attrs.amount()); + break; + } + case 'pathPaymentStrictReceive': + { + result.type = 'pathPaymentStrictReceive'; + result.sendAsset = _asset.Asset.fromOperation(attrs.sendAsset()); + result.sendMax = this._fromXDRAmount(attrs.sendMax()); + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.destAsset = _asset.Asset.fromOperation(attrs.destAsset()); + result.destAmount = this._fromXDRAmount(attrs.destAmount()); + result.path = []; + var path = attrs.path(); + + // note that Object.values isn't supported by node 6! + Object.keys(path).forEach(function (pathKey) { + result.path.push(_asset.Asset.fromOperation(path[pathKey])); + }); + break; + } + case 'pathPaymentStrictSend': + { + result.type = 'pathPaymentStrictSend'; + result.sendAsset = _asset.Asset.fromOperation(attrs.sendAsset()); + result.sendAmount = this._fromXDRAmount(attrs.sendAmount()); + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.destAsset = _asset.Asset.fromOperation(attrs.destAsset()); + result.destMin = this._fromXDRAmount(attrs.destMin()); + result.path = []; + var _path = attrs.path(); + + // note that Object.values isn't supported by node 6! + Object.keys(_path).forEach(function (pathKey) { + result.path.push(_asset.Asset.fromOperation(_path[pathKey])); + }); + break; + } + case 'changeTrust': + { + result.type = 'changeTrust'; + switch (attrs.line()["switch"]()) { + case _xdr["default"].AssetType.assetTypePoolShare(): + result.line = _liquidity_pool_asset.LiquidityPoolAsset.fromOperation(attrs.line()); + break; + default: + result.line = _asset.Asset.fromOperation(attrs.line()); + break; + } + result.limit = this._fromXDRAmount(attrs.limit()); + break; + } + case 'allowTrust': + { + result.type = 'allowTrust'; + result.trustor = accountIdtoAddress(attrs.trustor()); + result.assetCode = attrs.asset().value().toString(); + result.assetCode = (0, _util.trimEnd)(result.assetCode, '\0'); + result.authorize = attrs.authorize(); + break; + } + case 'setOptions': + { + result.type = 'setOptions'; + if (attrs.inflationDest()) { + result.inflationDest = accountIdtoAddress(attrs.inflationDest()); + } + result.clearFlags = attrs.clearFlags(); + result.setFlags = attrs.setFlags(); + result.masterWeight = attrs.masterWeight(); + result.lowThreshold = attrs.lowThreshold(); + result.medThreshold = attrs.medThreshold(); + result.highThreshold = attrs.highThreshold(); + // home_domain is checked by iscntrl in stellar-core + result.homeDomain = attrs.homeDomain() !== undefined ? attrs.homeDomain().toString('ascii') : undefined; + if (attrs.signer()) { + var signer = {}; + var arm = attrs.signer().key().arm(); + if (arm === 'ed25519') { + signer.ed25519PublicKey = accountIdtoAddress(attrs.signer().key()); + } else if (arm === 'preAuthTx') { + signer.preAuthTx = attrs.signer().key().preAuthTx(); + } else if (arm === 'hashX') { + signer.sha256Hash = attrs.signer().key().hashX(); + } else if (arm === 'ed25519SignedPayload') { + var signedPayload = attrs.signer().key().ed25519SignedPayload(); + signer.ed25519SignedPayload = _strkey.StrKey.encodeSignedPayload(signedPayload.toXDR()); + } + signer.weight = attrs.signer().weight(); + result.signer = signer; + } + break; + } + // the next case intentionally falls through! + case 'manageOffer': + case 'manageSellOffer': + { + result.type = 'manageSellOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.price = this._fromXDRPrice(attrs.price()); + result.offerId = attrs.offerId().toString(); + break; + } + case 'manageBuyOffer': + { + result.type = 'manageBuyOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.buyAmount = this._fromXDRAmount(attrs.buyAmount()); + result.price = this._fromXDRPrice(attrs.price()); + result.offerId = attrs.offerId().toString(); + break; + } + // the next case intentionally falls through! + case 'createPassiveOffer': + case 'createPassiveSellOffer': + { + result.type = 'createPassiveSellOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.price = this._fromXDRPrice(attrs.price()); + break; + } + case 'accountMerge': + { + result.type = 'accountMerge'; + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs); + break; + } + case 'manageData': + { + result.type = 'manageData'; + // manage_data.name is checked by iscntrl in stellar-core + result.name = attrs.dataName().toString('ascii'); + result.value = attrs.dataValue(); + break; + } + case 'inflation': + { + result.type = 'inflation'; + break; + } + case 'bumpSequence': + { + result.type = 'bumpSequence'; + result.bumpTo = attrs.bumpTo().toString(); + break; + } + case 'createClaimableBalance': + { + result.type = 'createClaimableBalance'; + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.claimants = []; + attrs.claimants().forEach(function (claimant) { + result.claimants.push(_claimant.Claimant.fromXDR(claimant)); + }); + break; + } + case 'claimClaimableBalance': + { + result.type = 'claimClaimableBalance'; + result.balanceId = attrs.toXDR('hex'); + break; + } + case 'beginSponsoringFutureReserves': + { + result.type = 'beginSponsoringFutureReserves'; + result.sponsoredId = accountIdtoAddress(attrs.sponsoredId()); + break; + } + case 'endSponsoringFutureReserves': + { + result.type = 'endSponsoringFutureReserves'; + break; + } + case 'revokeSponsorship': + { + extractRevokeSponshipDetails(attrs, result); + break; + } + case 'clawback': + { + result.type = 'clawback'; + result.amount = this._fromXDRAmount(attrs.amount()); + result.from = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.from()); + result.asset = _asset.Asset.fromOperation(attrs.asset()); + break; + } + case 'clawbackClaimableBalance': + { + result.type = 'clawbackClaimableBalance'; + result.balanceId = attrs.toXDR('hex'); + break; + } + case 'setTrustLineFlags': + { + result.type = 'setTrustLineFlags'; + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.trustor = accountIdtoAddress(attrs.trustor()); + + // Convert from the integer-bitwised flag into a sensible object that + // indicates true/false for each flag that's on/off. + var clears = attrs.clearFlags(); + var sets = attrs.setFlags(); + var mapping = { + authorized: _xdr["default"].TrustLineFlags.authorizedFlag(), + authorizedToMaintainLiabilities: _xdr["default"].TrustLineFlags.authorizedToMaintainLiabilitiesFlag(), + clawbackEnabled: _xdr["default"].TrustLineFlags.trustlineClawbackEnabledFlag() + }; + var getFlagValue = function getFlagValue(key) { + var bit = mapping[key].value; + if (sets & bit) { + return true; + } + if (clears & bit) { + return false; + } + return undefined; + }; + result.flags = {}; + Object.keys(mapping).forEach(function (flagName) { + result.flags[flagName] = getFlagValue(flagName); + }); + break; + } + case 'liquidityPoolDeposit': + { + result.type = 'liquidityPoolDeposit'; + result.liquidityPoolId = attrs.liquidityPoolId().toString('hex'); + result.maxAmountA = this._fromXDRAmount(attrs.maxAmountA()); + result.maxAmountB = this._fromXDRAmount(attrs.maxAmountB()); + result.minPrice = this._fromXDRPrice(attrs.minPrice()); + result.maxPrice = this._fromXDRPrice(attrs.maxPrice()); + break; + } + case 'liquidityPoolWithdraw': + { + result.type = 'liquidityPoolWithdraw'; + result.liquidityPoolId = attrs.liquidityPoolId().toString('hex'); + result.amount = this._fromXDRAmount(attrs.amount()); + result.minAmountA = this._fromXDRAmount(attrs.minAmountA()); + result.minAmountB = this._fromXDRAmount(attrs.minAmountB()); + break; + } + case 'invokeHostFunction': + { + var _attrs$auth; + result.type = 'invokeHostFunction'; + result.func = attrs.hostFunction(); + result.auth = (_attrs$auth = attrs.auth()) !== null && _attrs$auth !== void 0 ? _attrs$auth : []; + break; + } + case 'extendFootprintTtl': + { + result.type = 'extendFootprintTtl'; + result.extendTo = attrs.extendTo(); + break; + } + case 'restoreFootprint': + { + result.type = 'restoreFootprint'; + break; + } + default: + { + throw new Error("Unknown operation: ".concat(operationName)); + } + } + return result; + } + + /** + * Validates that a given amount is possible for a Stellar asset. + * + * Specifically, this means that the amount is well, a valid number, but also + * that it is within the int64 range and has no more than 7 decimal levels of + * precision. + * + * Note that while smart contracts allow larger amounts, this is oriented + * towards validating the standard Stellar operations. + * + * @param {string} value the amount to validate + * @param {boolean} allowZero optionally, whether or not zero is valid (default: no) + * + * @returns {boolean} + */ + }, { + key: "isValidAmount", + value: function isValidAmount(value) { + var allowZero = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (typeof value !== 'string') { + return false; + } + var amount; + try { + amount = new _bignumber["default"](value); + } catch (e) { + return false; + } + if ( + // == 0 + !allowZero && amount.isZero() || + // < 0 + amount.isNegative() || + // > Max value + amount.times(ONE).gt(new _bignumber["default"](MAX_INT64).toString()) || + // Decimal places (max 7) + amount.decimalPlaces() > 7 || + // NaN or Infinity + amount.isNaN() || !amount.isFinite()) { + return false; + } + return true; + } + }, { + key: "constructAmountRequirementsError", + value: function constructAmountRequirementsError(arg) { + return "".concat(arg, " argument must be of type String, represent a positive number and have at most 7 digits after the decimal"); + } + + /** + * Returns value converted to uint32 value or undefined. + * If `value` is not `Number`, `String` or `Undefined` then throws an error. + * Used in {@link Operation.setOptions}. + * @private + * @param {string} name Name of the property (used in error message only) + * @param {*} value Value to check + * @param {function(value, name)} isValidFunction Function to check other constraints (the argument will be a `Number`) + * @returns {undefined|Number} + */ + }, { + key: "_checkUnsignedIntValue", + value: function _checkUnsignedIntValue(name, value) { + var isValidFunction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + if (typeof value === 'undefined') { + return undefined; + } + if (typeof value === 'string') { + value = parseFloat(value); + } + switch (true) { + case typeof value !== 'number' || !Number.isFinite(value) || value % 1 !== 0: + throw new Error("".concat(name, " value is invalid")); + case value < 0: + throw new Error("".concat(name, " value must be unsigned")); + case !isValidFunction || isValidFunction && isValidFunction(value, name): + return value; + default: + throw new Error("".concat(name, " value is invalid")); + } + } + /** + * @private + * @param {string|BigNumber} value Value + * @returns {Hyper} XDR amount + */ + }, { + key: "_toXDRAmount", + value: function _toXDRAmount(value) { + var amount = new _bignumber["default"](value).times(ONE); + return _jsXdr.Hyper.fromString(amount.toString()); + } + + /** + * @private + * @param {string|BigNumber} value XDR amount + * @returns {BigNumber} Number + */ + }, { + key: "_fromXDRAmount", + value: function _fromXDRAmount(value) { + return new _bignumber["default"](value).div(ONE).toFixed(7); + } + + /** + * @private + * @param {object} price Price object + * @param {function} price.n numerator function that returns a value + * @param {function} price.d denominator function that returns a value + * @returns {BigNumber} Big string + */ + }, { + key: "_fromXDRPrice", + value: function _fromXDRPrice(price) { + var n = new _bignumber["default"](price.n()); + return n.div(new _bignumber["default"](price.d())).toString(); + } + + /** + * @private + * @param {object} price Price object + * @param {function} price.n numerator function that returns a value + * @param {function} price.d denominator function that returns a value + * @returns {object} XDR price object + */ + }, { + key: "_toXDRPrice", + value: function _toXDRPrice(price) { + var xdrObject; + if (price.n && price.d) { + xdrObject = new _xdr["default"].Price(price); + } else { + var approx = (0, _continued_fraction.best_r)(price); + xdrObject = new _xdr["default"].Price({ + n: parseInt(approx[0], 10), + d: parseInt(approx[1], 10) + }); + } + if (xdrObject.n() < 0 || xdrObject.d() < 0) { + throw new Error('price must be positive'); + } + return xdrObject; + } + }]); +}(); +function extractRevokeSponshipDetails(attrs, result) { + switch (attrs["switch"]().name) { + case 'revokeSponsorshipLedgerEntry': + { + var ledgerKey = attrs.ledgerKey(); + switch (ledgerKey["switch"]().name) { + case _xdr["default"].LedgerEntryType.account().name: + { + result.type = 'revokeAccountSponsorship'; + result.account = accountIdtoAddress(ledgerKey.account().accountId()); + break; + } + case _xdr["default"].LedgerEntryType.trustline().name: + { + result.type = 'revokeTrustlineSponsorship'; + result.account = accountIdtoAddress(ledgerKey.trustLine().accountId()); + var xdrAsset = ledgerKey.trustLine().asset(); + switch (xdrAsset["switch"]()) { + case _xdr["default"].AssetType.assetTypePoolShare(): + result.asset = _liquidity_pool_id.LiquidityPoolId.fromOperation(xdrAsset); + break; + default: + result.asset = _asset.Asset.fromOperation(xdrAsset); + break; + } + break; + } + case _xdr["default"].LedgerEntryType.offer().name: + { + result.type = 'revokeOfferSponsorship'; + result.seller = accountIdtoAddress(ledgerKey.offer().sellerId()); + result.offerId = ledgerKey.offer().offerId().toString(); + break; + } + case _xdr["default"].LedgerEntryType.data().name: + { + result.type = 'revokeDataSponsorship'; + result.account = accountIdtoAddress(ledgerKey.data().accountId()); + result.name = ledgerKey.data().dataName().toString('ascii'); + break; + } + case _xdr["default"].LedgerEntryType.claimableBalance().name: + { + result.type = 'revokeClaimableBalanceSponsorship'; + result.balanceId = ledgerKey.claimableBalance().balanceId().toXDR('hex'); + break; + } + case _xdr["default"].LedgerEntryType.liquidityPool().name: + { + result.type = 'revokeLiquidityPoolSponsorship'; + result.liquidityPoolId = ledgerKey.liquidityPool().liquidityPoolId().toString('hex'); + break; + } + default: + { + throw new Error("Unknown ledgerKey: ".concat(attrs["switch"]().name)); + } + } + break; + } + case 'revokeSponsorshipSigner': + { + result.type = 'revokeSignerSponsorship'; + result.account = accountIdtoAddress(attrs.signer().accountId()); + result.signer = convertXDRSignerKeyToObject(attrs.signer().signerKey()); + break; + } + default: + { + throw new Error("Unknown revokeSponsorship: ".concat(attrs["switch"]().name)); + } + } +} +function convertXDRSignerKeyToObject(signerKey) { + var attrs = {}; + switch (signerKey["switch"]().name) { + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519().name: + { + attrs.ed25519PublicKey = _strkey.StrKey.encodeEd25519PublicKey(signerKey.ed25519()); + break; + } + case _xdr["default"].SignerKeyType.signerKeyTypePreAuthTx().name: + { + attrs.preAuthTx = signerKey.preAuthTx().toString('hex'); + break; + } + case _xdr["default"].SignerKeyType.signerKeyTypeHashX().name: + { + attrs.sha256Hash = signerKey.hashX().toString('hex'); + break; + } + default: + { + throw new Error("Unknown signerKey: ".concat(signerKey["switch"]().name)); + } + } + return attrs; +} +function accountIdtoAddress(accountId) { + return _strkey.StrKey.encodeEd25519PublicKey(accountId.ed25519()); +} + +// Attach all imported operations as static methods on the Operation class +Operation.accountMerge = ops.accountMerge; +Operation.allowTrust = ops.allowTrust; +Operation.bumpSequence = ops.bumpSequence; +Operation.changeTrust = ops.changeTrust; +Operation.createAccount = ops.createAccount; +Operation.createClaimableBalance = ops.createClaimableBalance; +Operation.claimClaimableBalance = ops.claimClaimableBalance; +Operation.clawbackClaimableBalance = ops.clawbackClaimableBalance; +Operation.createPassiveSellOffer = ops.createPassiveSellOffer; +Operation.inflation = ops.inflation; +Operation.manageData = ops.manageData; +Operation.manageSellOffer = ops.manageSellOffer; +Operation.manageBuyOffer = ops.manageBuyOffer; +Operation.pathPaymentStrictReceive = ops.pathPaymentStrictReceive; +Operation.pathPaymentStrictSend = ops.pathPaymentStrictSend; +Operation.payment = ops.payment; +Operation.setOptions = ops.setOptions; +Operation.beginSponsoringFutureReserves = ops.beginSponsoringFutureReserves; +Operation.endSponsoringFutureReserves = ops.endSponsoringFutureReserves; +Operation.revokeAccountSponsorship = ops.revokeAccountSponsorship; +Operation.revokeTrustlineSponsorship = ops.revokeTrustlineSponsorship; +Operation.revokeOfferSponsorship = ops.revokeOfferSponsorship; +Operation.revokeDataSponsorship = ops.revokeDataSponsorship; +Operation.revokeClaimableBalanceSponsorship = ops.revokeClaimableBalanceSponsorship; +Operation.revokeLiquidityPoolSponsorship = ops.revokeLiquidityPoolSponsorship; +Operation.revokeSignerSponsorship = ops.revokeSignerSponsorship; +Operation.clawback = ops.clawback; +Operation.setTrustLineFlags = ops.setTrustLineFlags; +Operation.liquidityPoolDeposit = ops.liquidityPoolDeposit; +Operation.liquidityPoolWithdraw = ops.liquidityPoolWithdraw; +Operation.invokeHostFunction = ops.invokeHostFunction; +Operation.extendFootprintTtl = ops.extendFootprintTtl; +Operation.restoreFootprint = ops.restoreFootprint; + +// these are not `xdr.Operation`s directly, but are proxies for complex but +// common versions of `Operation.invokeHostFunction` +Operation.createStellarAssetContract = ops.createStellarAssetContract; +Operation.invokeContractFunction = ops.invokeContractFunction; +Operation.createCustomContract = ops.createCustomContract; +Operation.uploadContractWasm = ops.uploadContractWasm; + +/***/ }), + +/***/ 4295: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.accountMerge = accountMerge; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Transfers native balance to destination account. + * + * @function + * @alias Operation.accountMerge + * + * @param {object} opts - options object + * @param {string} opts.destination - destination to merge the source account into + * @param {string} [opts.source] - operation source account (defaults to + * transaction source) + * + * @returns {xdr.Operation} an Account Merge operation (xdr.AccountMergeOp) + */ +function accountMerge(opts) { + var opAttributes = {}; + try { + opAttributes.body = _xdr["default"].OperationBody.accountMerge((0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination)); + } catch (e) { + throw new Error('destination is invalid'); + } + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 3683: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.allowTrust = allowTrust; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * @deprecated since v5.0 + * + * Returns an XDR AllowTrustOp. An "allow trust" operation authorizes another + * account to hold your account's credit for a given asset. + * + * @function + * @alias Operation.allowTrust + * + * @param {object} opts Options object + * @param {string} opts.trustor - The trusting account (the one being authorized) + * @param {string} opts.assetCode - The asset code being authorized. + * @param {(0|1|2)} opts.authorize - `1` to authorize, `2` to authorize to maintain liabilities, and `0` to deauthorize. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * + * @returns {xdr.AllowTrustOp} Allow Trust operation + */ +function allowTrust(opts) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.trustor)) { + throw new Error('trustor is invalid'); + } + var attributes = {}; + attributes.trustor = _keypair.Keypair.fromPublicKey(opts.trustor).xdrAccountId(); + if (opts.assetCode.length <= 4) { + var code = opts.assetCode.padEnd(4, '\0'); + attributes.asset = _xdr["default"].AssetCode.assetTypeCreditAlphanum4(code); + } else if (opts.assetCode.length <= 12) { + var _code = opts.assetCode.padEnd(12, '\0'); + attributes.asset = _xdr["default"].AssetCode.assetTypeCreditAlphanum12(_code); + } else { + throw new Error('Asset code must be 12 characters at max.'); + } + if (typeof opts.authorize === 'boolean') { + if (opts.authorize) { + attributes.authorize = _xdr["default"].TrustLineFlags.authorizedFlag().value; + } else { + attributes.authorize = 0; + } + } else { + attributes.authorize = opts.authorize; + } + var allowTrustOp = new _xdr["default"].AllowTrustOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.allowTrust(allowTrustOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7505: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.beginSponsoringFutureReserves = beginSponsoringFutureReserves; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +var _keypair = __webpack_require__(6691); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a "begin sponsoring future reserves" operation. + * @function + * @alias Operation.beginSponsoringFutureReserves + * @param {object} opts Options object + * @param {string} opts.sponsoredId - The sponsored account id. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.beginSponsoringFutureReserves({ + * sponsoredId: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * }); + * + */ +function beginSponsoringFutureReserves() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.sponsoredId)) { + throw new Error('sponsoredId is invalid'); + } + var op = new _xdr["default"].BeginSponsoringFutureReservesOp({ + sponsoredId: _keypair.Keypair.fromPublicKey(opts.sponsoredId).xdrAccountId() + }); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.beginSponsoringFutureReserves(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 6183: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.bumpSequence = bumpSequence; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation bumps sequence number. + * @function + * @alias Operation.bumpSequence + * @param {object} opts Options object + * @param {string} opts.bumpTo - Sequence number to bump to. + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.BumpSequenceOp} Operation + */ +function bumpSequence(opts) { + var attributes = {}; + if (typeof opts.bumpTo !== 'string') { + throw new Error('bumpTo must be a string'); + } + try { + // eslint-disable-next-line no-new + new _bignumber["default"](opts.bumpTo); + } catch (e) { + throw new Error('bumpTo must be a stringified number'); + } + attributes.bumpTo = _jsXdr.Hyper.fromString(opts.bumpTo); + var bumpSequenceOp = new _xdr["default"].BumpSequenceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.bumpSequence(bumpSequenceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2810: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.changeTrust = changeTrust; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +var _liquidity_pool_asset = __webpack_require__(2262); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var MAX_INT64 = '9223372036854775807'; + +/** + * Returns an XDR ChangeTrustOp. A "change trust" operation adds, removes, or updates a + * trust line for a given asset from the source account to another. + * @function + * @alias Operation.changeTrust + * @param {object} opts Options object + * @param {Asset | LiquidityPoolAsset} opts.asset - The asset for the trust line. + * @param {string} [opts.limit] - The limit for the asset, defaults to max int64. + * If the limit is set to "0" it deletes the trustline. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @returns {xdr.ChangeTrustOp} Change Trust operation + */ +function changeTrust(opts) { + var attributes = {}; + if (opts.asset instanceof _asset.Asset) { + attributes.line = opts.asset.toChangeTrustXDRObject(); + } else if (opts.asset instanceof _liquidity_pool_asset.LiquidityPoolAsset) { + attributes.line = opts.asset.toXDRObject(); + } else { + throw new TypeError('asset must be Asset or LiquidityPoolAsset'); + } + if (opts.limit !== undefined && !this.isValidAmount(opts.limit, true)) { + throw new TypeError(this.constructAmountRequirementsError('limit')); + } + if (opts.limit) { + attributes.limit = this._toXDRAmount(opts.limit); + } else { + attributes.limit = _jsXdr.Hyper.fromString(new _bignumber["default"](MAX_INT64).toString()); + } + if (opts.source) { + attributes.source = opts.source.masterKeypair; + } + var changeTrustOP = new _xdr["default"].ChangeTrustOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.changeTrust(changeTrustOP); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7239: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.claimClaimableBalance = claimClaimableBalance; +exports.validateClaimableBalanceId = validateClaimableBalanceId; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a new claim claimable balance operation. + * @function + * @alias Operation.claimClaimableBalance + * @param {object} opts Options object + * @param {string} opts.balanceId - The claimable balance id to be claimed. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} Claim claimable balance operation + * + * @example + * const op = Operation.claimClaimableBalance({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + */ +function claimClaimableBalance() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + validateClaimableBalanceId(opts.balanceId); + var attributes = {}; + attributes.balanceId = _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex'); + var claimClaimableBalanceOp = new _xdr["default"].ClaimClaimableBalanceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.claimClaimableBalance(claimClaimableBalanceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} +function validateClaimableBalanceId(balanceId) { + if (typeof balanceId !== 'string' || balanceId.length !== 8 + 64 /* 8b discriminant + 64b string */) { + throw new Error('must provide a valid claimable balance id'); + } +} + +/***/ }), + +/***/ 7651: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.clawback = clawback; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a clawback operation. + * + * @function + * @alias Operation.clawback + * + * @param {object} opts - Options object + * @param {Asset} opts.asset - The asset being clawed back. + * @param {string} opts.amount - The amount of the asset to claw back. + * @param {string} opts.from - The public key of the (optionally-muxed) + * account to claw back from. + * + * @param {string} [opts.source] - The source account for the operation. + * Defaults to the transaction's source account. + * + * @return {xdr.ClawbackOp} + * + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#clawback-operation + */ +function clawback(opts) { + var attributes = {}; + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + attributes.asset = opts.asset.toXDRObject(); + try { + attributes.from = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.from); + } catch (e) { + throw new Error('from address is invalid'); + } + var opAttributes = { + body: _xdr["default"].OperationBody.clawback(new _xdr["default"].ClawbackOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2203: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.clawbackClaimableBalance = clawbackClaimableBalance; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _claim_claimable_balance = __webpack_require__(7239); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a clawback operation for a claimable balance. + * + * @function + * @alias Operation.clawbackClaimableBalance + * @param {object} opts - Options object + * @param {string} opts.balanceId - The claimable balance ID to be clawed back. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @return {xdr.ClawbackClaimableBalanceOp} + * + * @example + * const op = Operation.clawbackClaimableBalance({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + * @link https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#clawback-claimable-balance-operation + */ +function clawbackClaimableBalance() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + (0, _claim_claimable_balance.validateClaimableBalanceId)(opts.balanceId); + var attributes = { + balanceId: _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex') + }; + var opAttributes = { + body: _xdr["default"].OperationBody.clawbackClaimableBalance(new _xdr["default"].ClawbackClaimableBalanceOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2115: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createAccount = createAccount; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create and fund a non existent account. + * @function + * @alias Operation.createAccount + * @param {object} opts Options object + * @param {string} opts.destination - Destination account ID to create an account for. + * @param {string} opts.startingBalance - Amount in XLM the account should be funded for. Must be greater + * than the [reserve balance amount](https://developers.stellar.org/docs/glossary/fees/). + * @param {string} [opts.source] - The source account for the payment. Defaults to the transaction's source account. + * @returns {xdr.CreateAccountOp} Create account operation + */ +function createAccount(opts) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.destination)) { + throw new Error('destination is invalid'); + } + if (!this.isValidAmount(opts.startingBalance, true)) { + throw new TypeError(this.constructAmountRequirementsError('startingBalance')); + } + var attributes = {}; + attributes.destination = _keypair.Keypair.fromPublicKey(opts.destination).xdrAccountId(); + attributes.startingBalance = this._toXDRAmount(opts.startingBalance); + var createAccountOp = new _xdr["default"].CreateAccountOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createAccount(createAccountOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 4831: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createClaimableBalance = createClaimableBalance; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a new claimable balance operation. + * + * @function + * @alias Operation.createClaimableBalance + * + * @param {object} opts Options object + * @param {Asset} opts.asset - The asset for the claimable balance. + * @param {string} opts.amount - Amount. + * @param {Claimant[]} opts.claimants - An array of Claimants + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} Create claimable balance operation + * + * @example + * const asset = new Asset( + * 'USD', + * 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * ); + * const amount = '100.0000000'; + * const claimants = [ + * new Claimant( + * 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ', + * Claimant.predicateBeforeAbsoluteTime("4102444800000") + * ) + * ]; + * + * const op = Operation.createClaimableBalance({ + * asset, + * amount, + * claimants + * }); + * + */ +function createClaimableBalance(opts) { + if (!(opts.asset instanceof _asset.Asset)) { + throw new Error('must provide an asset for create claimable balance operation'); + } + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + if (!Array.isArray(opts.claimants) || opts.claimants.length === 0) { + throw new Error('must provide at least one claimant'); + } + var attributes = {}; + attributes.asset = opts.asset.toXDRObject(); + attributes.amount = this._toXDRAmount(opts.amount); + attributes.claimants = Object.values(opts.claimants).map(function (c) { + return c.toXDRObject(); + }); + var createClaimableBalanceOp = new _xdr["default"].CreateClaimableBalanceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createClaimableBalance(createClaimableBalanceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 9073: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createPassiveSellOffer = createPassiveSellOffer; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR CreatePasiveSellOfferOp. A "create passive offer" operation creates an + * offer that won't consume a counter offer that exactly matches this offer. This is + * useful for offers just used as 1:1 exchanges for path payments. Use manage offer + * to manage this offer after using this operation to create it. + * @function + * @alias Operation.createPassiveSellOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.CreatePassiveSellOfferOp} Create Passive Sell Offer operation + */ +function createPassiveSellOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + var createPassiveSellOfferOp = new _xdr["default"].CreatePassiveSellOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createPassiveSellOffer(createPassiveSellOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 721: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.endSponsoringFutureReserves = endSponsoringFutureReserves; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create an "end sponsoring future reserves" operation. + * @function + * @alias Operation.endSponsoringFutureReserves + * @param {object} opts Options object + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.endSponsoringFutureReserves(); + * + */ +function endSponsoringFutureReserves() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.endSponsoringFutureReserves(); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 8752: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.extendFootprintTtl = extendFootprintTtl; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Builds an operation to bump the time-to-live (TTL) of the ledger keys. The + * keys for extension have to be provided in the read-only footprint of + * the transaction. + * + * The only parameter of the operation itself is the new minimum TTL for + * all the provided entries. If an entry already has a higher TTL, then it + * will just be skipped. + * + * TTL is the number of ledgers from the current ledger (exclusive) until + * the last ledger the entry is still considered alive (inclusive). Thus + * the exact ledger until the entries will live will only be determined + * when transaction has been applied. + * + * The footprint has to be specified in the transaction. See + * {@link TransactionBuilder}'s `opts.sorobanData` parameter, which is a + * {@link xdr.SorobanTransactionData} instance that contains fee data & resource + * usage as part of {@link xdr.SorobanResources}. + * + * @function + * @alias Operation.extendFootprintTtl + * + * @param {object} opts - object holding operation parameters + * @param {number} opts.extendTo - the minimum TTL that all the entries in + * the read-only footprint will have + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Extend Footprint TTL operation + * (xdr.ExtendFootprintTTLOp) + */ +function extendFootprintTtl(opts) { + var _opts$extendTo; + if (((_opts$extendTo = opts.extendTo) !== null && _opts$extendTo !== void 0 ? _opts$extendTo : -1) <= 0) { + throw new RangeError('extendTo has to be positive'); + } + var extendFootprintOp = new _xdr["default"].ExtendFootprintTtlOp({ + ext: new _xdr["default"].ExtensionPoint(0), + extendTo: opts.extendTo + }); + var opAttributes = { + body: _xdr["default"].OperationBody.extendFootprintTtl(extendFootprintOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7511: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "accountMerge", ({ + enumerable: true, + get: function get() { + return _account_merge.accountMerge; + } +})); +Object.defineProperty(exports, "allowTrust", ({ + enumerable: true, + get: function get() { + return _allow_trust.allowTrust; + } +})); +Object.defineProperty(exports, "beginSponsoringFutureReserves", ({ + enumerable: true, + get: function get() { + return _begin_sponsoring_future_reserves.beginSponsoringFutureReserves; + } +})); +Object.defineProperty(exports, "bumpSequence", ({ + enumerable: true, + get: function get() { + return _bump_sequence.bumpSequence; + } +})); +Object.defineProperty(exports, "changeTrust", ({ + enumerable: true, + get: function get() { + return _change_trust.changeTrust; + } +})); +Object.defineProperty(exports, "claimClaimableBalance", ({ + enumerable: true, + get: function get() { + return _claim_claimable_balance.claimClaimableBalance; + } +})); +Object.defineProperty(exports, "clawback", ({ + enumerable: true, + get: function get() { + return _clawback.clawback; + } +})); +Object.defineProperty(exports, "clawbackClaimableBalance", ({ + enumerable: true, + get: function get() { + return _clawback_claimable_balance.clawbackClaimableBalance; + } +})); +Object.defineProperty(exports, "createAccount", ({ + enumerable: true, + get: function get() { + return _create_account.createAccount; + } +})); +Object.defineProperty(exports, "createClaimableBalance", ({ + enumerable: true, + get: function get() { + return _create_claimable_balance.createClaimableBalance; + } +})); +Object.defineProperty(exports, "createCustomContract", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.createCustomContract; + } +})); +Object.defineProperty(exports, "createPassiveSellOffer", ({ + enumerable: true, + get: function get() { + return _create_passive_sell_offer.createPassiveSellOffer; + } +})); +Object.defineProperty(exports, "createStellarAssetContract", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.createStellarAssetContract; + } +})); +Object.defineProperty(exports, "endSponsoringFutureReserves", ({ + enumerable: true, + get: function get() { + return _end_sponsoring_future_reserves.endSponsoringFutureReserves; + } +})); +Object.defineProperty(exports, "extendFootprintTtl", ({ + enumerable: true, + get: function get() { + return _extend_footprint_ttl.extendFootprintTtl; + } +})); +Object.defineProperty(exports, "inflation", ({ + enumerable: true, + get: function get() { + return _inflation.inflation; + } +})); +Object.defineProperty(exports, "invokeContractFunction", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.invokeContractFunction; + } +})); +Object.defineProperty(exports, "invokeHostFunction", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.invokeHostFunction; + } +})); +Object.defineProperty(exports, "liquidityPoolDeposit", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_deposit.liquidityPoolDeposit; + } +})); +Object.defineProperty(exports, "liquidityPoolWithdraw", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_withdraw.liquidityPoolWithdraw; + } +})); +Object.defineProperty(exports, "manageBuyOffer", ({ + enumerable: true, + get: function get() { + return _manage_buy_offer.manageBuyOffer; + } +})); +Object.defineProperty(exports, "manageData", ({ + enumerable: true, + get: function get() { + return _manage_data.manageData; + } +})); +Object.defineProperty(exports, "manageSellOffer", ({ + enumerable: true, + get: function get() { + return _manage_sell_offer.manageSellOffer; + } +})); +Object.defineProperty(exports, "pathPaymentStrictReceive", ({ + enumerable: true, + get: function get() { + return _path_payment_strict_receive.pathPaymentStrictReceive; + } +})); +Object.defineProperty(exports, "pathPaymentStrictSend", ({ + enumerable: true, + get: function get() { + return _path_payment_strict_send.pathPaymentStrictSend; + } +})); +Object.defineProperty(exports, "payment", ({ + enumerable: true, + get: function get() { + return _payment.payment; + } +})); +Object.defineProperty(exports, "restoreFootprint", ({ + enumerable: true, + get: function get() { + return _restore_footprint.restoreFootprint; + } +})); +Object.defineProperty(exports, "revokeAccountSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeAccountSponsorship; + } +})); +Object.defineProperty(exports, "revokeClaimableBalanceSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeClaimableBalanceSponsorship; + } +})); +Object.defineProperty(exports, "revokeDataSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeDataSponsorship; + } +})); +Object.defineProperty(exports, "revokeLiquidityPoolSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeLiquidityPoolSponsorship; + } +})); +Object.defineProperty(exports, "revokeOfferSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeOfferSponsorship; + } +})); +Object.defineProperty(exports, "revokeSignerSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeSignerSponsorship; + } +})); +Object.defineProperty(exports, "revokeTrustlineSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeTrustlineSponsorship; + } +})); +Object.defineProperty(exports, "setOptions", ({ + enumerable: true, + get: function get() { + return _set_options.setOptions; + } +})); +Object.defineProperty(exports, "setTrustLineFlags", ({ + enumerable: true, + get: function get() { + return _set_trustline_flags.setTrustLineFlags; + } +})); +Object.defineProperty(exports, "uploadContractWasm", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.uploadContractWasm; + } +})); +var _manage_sell_offer = __webpack_require__(862); +var _create_passive_sell_offer = __webpack_require__(9073); +var _account_merge = __webpack_require__(4295); +var _allow_trust = __webpack_require__(3683); +var _bump_sequence = __webpack_require__(6183); +var _change_trust = __webpack_require__(2810); +var _create_account = __webpack_require__(2115); +var _create_claimable_balance = __webpack_require__(4831); +var _claim_claimable_balance = __webpack_require__(7239); +var _clawback_claimable_balance = __webpack_require__(2203); +var _inflation = __webpack_require__(7421); +var _manage_data = __webpack_require__(1411); +var _manage_buy_offer = __webpack_require__(1922); +var _path_payment_strict_receive = __webpack_require__(2075); +var _path_payment_strict_send = __webpack_require__(3874); +var _payment = __webpack_require__(3533); +var _set_options = __webpack_require__(2018); +var _begin_sponsoring_future_reserves = __webpack_require__(7505); +var _end_sponsoring_future_reserves = __webpack_require__(721); +var _revoke_sponsorship = __webpack_require__(7790); +var _clawback = __webpack_require__(7651); +var _set_trustline_flags = __webpack_require__(1804); +var _liquidity_pool_deposit = __webpack_require__(9845); +var _liquidity_pool_withdraw = __webpack_require__(4737); +var _invoke_host_function = __webpack_require__(4403); +var _extend_footprint_ttl = __webpack_require__(8752); +var _restore_footprint = __webpack_require__(149); + +/***/ }), + +/***/ 7421: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.inflation = inflation; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation generates the inflation. + * @function + * @alias Operation.inflation + * @param {object} [opts] Options object + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.InflationOp} Inflation operation + */ +function inflation() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.inflation(); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 4403: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createCustomContract = createCustomContract; +exports.createStellarAssetContract = createStellarAssetContract; +exports.invokeContractFunction = invokeContractFunction; +exports.invokeHostFunction = invokeHostFunction; +exports.uploadContractWasm = uploadContractWasm; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _address = __webpack_require__(1180); +var _asset = __webpack_require__(1764); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +/** + * Invokes a single smart contract host function. + * + * @function + * @alias Operation.invokeHostFunction + * + * @param {object} opts - options object + * @param {xdr.HostFunction} opts.func - host function to execute (with its + * wrapped parameters) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - list outlining the + * tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + * @see Operation.invokeContractFunction + * @see Operation.createCustomContract + * @see Operation.createStellarAssetContract + * @see Operation.uploadContractWasm + * @see Contract.call + */ +function invokeHostFunction(opts) { + if (!opts.func) { + throw new TypeError("host function invocation ('func') required (got ".concat(JSON.stringify(opts), ")")); + } + var invokeHostFunctionOp = new _xdr["default"].InvokeHostFunctionOp({ + hostFunction: opts.func, + auth: opts.auth || [] + }); + var opAttributes = { + body: _xdr["default"].OperationBody.invokeHostFunction(invokeHostFunctionOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Returns an operation that invokes a contract function. + * + * @function + * @alias Operation.invokeContractFunction + * + * @param {any} opts - the set of parameters + * @param {string} opts.contract - a strkey-fied contract address (`C...`) + * @param {string} opts.function - the name of the contract fn to invoke + * @param {xdr.ScVal[]} opts.args - parameters to pass to the function + * invocation (try {@link nativeToScVal} or {@link ScInt} to make building + * these easier) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see Operation.invokeHostFunction + * @see Contract.call + * @see Address + */ +function invokeContractFunction(opts) { + var c = new _address.Address(opts.contract); + if (c._type !== 'contract') { + throw new TypeError("expected contract strkey instance, got ".concat(c)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeInvokeContract(new _xdr["default"].InvokeContractArgs({ + contractAddress: c.toScAddress(), + functionName: opts["function"], + args: opts.args + })) + }); +} + +/** + * Returns an operation that creates a custom WASM contract and atomically + * invokes its constructor. + * + * @function + * @alias Operation.createCustomContract + * + * @param {any} opts - the set of parameters + * @param {Address} opts.address - the contract uploader address + * @param {Uint8Array|Buffer} opts.wasmHash - the SHA-256 hash of the contract + * WASM you're uploading (see {@link hash} and + * {@link Operation.uploadContractWasm}) + * @param {xdr.ScVal[]} [opts.constructorArgs] - the optional parameters to pass + * to the constructor of this contract (see {@link nativeToScVal} for ways to + * easily create these parameters from native JS values) + * @param {Uint8Array|Buffer} [opts.salt] - an optional, 32-byte salt to + * distinguish deployment instances of the same wasm from the same user (if + * omitted, one will be generated for you) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + */ +function createCustomContract(opts) { + var _opts$constructorArgs; + var salt = Buffer.from(opts.salt || getSalty()); + if (!opts.wasmHash || opts.wasmHash.length !== 32) { + throw new TypeError("expected hash(contract WASM) in 'opts.wasmHash', got ".concat(opts.wasmHash)); + } + if (salt.length !== 32) { + throw new TypeError("expected 32-byte salt in 'opts.salt', got ".concat(opts.wasmHash)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeCreateContractV2(new _xdr["default"].CreateContractArgsV2({ + executable: _xdr["default"].ContractExecutable.contractExecutableWasm(Buffer.from(opts.wasmHash)), + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAddress(new _xdr["default"].ContractIdPreimageFromAddress({ + address: opts.address.toScAddress(), + salt: salt + })), + constructorArgs: (_opts$constructorArgs = opts.constructorArgs) !== null && _opts$constructorArgs !== void 0 ? _opts$constructorArgs : [] + })) + }); +} + +/** + * Returns an operation that wraps a Stellar asset into a token contract. + * + * @function + * @alias Operation.createStellarAssetContract + * + * @param {any} opts - the set of parameters + * @param {Asset|string} opts.asset - the Stellar asset to wrap, either as an + * {@link Asset} object or in canonical form (SEP-11, `code:issuer`) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see https://stellar.org/protocol/sep-11#alphanum4-alphanum12 + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions + * @see + * https://soroban.stellar.org/docs/advanced-tutorials/stellar-asset-contract + * @see Operation.invokeHostFunction + */ +function createStellarAssetContract(opts) { + var asset = opts.asset; + if (typeof asset === 'string') { + var _asset$split = asset.split(':'), + _asset$split2 = _slicedToArray(_asset$split, 2), + code = _asset$split2[0], + issuer = _asset$split2[1]; + asset = new _asset.Asset(code, issuer); // handles 'xlm' by default + } + if (!(asset instanceof _asset.Asset)) { + throw new TypeError("expected Asset in 'opts.asset', got ".concat(asset)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeCreateContract(new _xdr["default"].CreateContractArgs({ + executable: _xdr["default"].ContractExecutable.contractExecutableStellarAsset(), + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAsset(asset.toXDRObject()) + })) + }); +} + +/** + * Returns an operation that uploads WASM for a contract. + * + * @function + * @alias Operation.uploadContractWasm + * + * @param {any} opts - the set of parameters + * @param {Uint8Array|Buffer} opts.wasm - a WASM blob to upload to the ledger + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + */ +function uploadContractWasm(opts) { + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeUploadContractWasm(Buffer.from(opts.wasm) // coalesce so we can drop `Buffer` someday + ) + }); +} + +/** @returns {Buffer} a random 256-bit "salt" value. */ +function getSalty() { + return _keypair.Keypair.random().xdrPublicKey().value(); // ed25519 is 256 bits, too +} + +/***/ }), + +/***/ 9845: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.liquidityPoolDeposit = liquidityPoolDeposit; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a liquidity pool deposit operation. + * + * @function + * @alias Operation.liquidityPoolDeposit + * @see https://developers.stellar.org/docs/start/list-of-operations/#liquidity-pool-deposit + * + * @param {object} opts - Options object + * @param {string} opts.liquidityPoolId - The liquidity pool ID. + * @param {string} opts.maxAmountA - Maximum amount of first asset to deposit. + * @param {string} opts.maxAmountB - Maximum amount of second asset to deposit. + * @param {number|string|BigNumber|Object} opts.minPrice - Minimum depositA/depositB price. + * @param {number} opts.minPrice.n - If `opts.minPrice` is an object: the price numerator + * @param {number} opts.minPrice.d - If `opts.minPrice` is an object: the price denominator + * @param {number|string|BigNumber|Object} opts.maxPrice - Maximum depositA/depositB price. + * @param {number} opts.maxPrice.n - If `opts.maxPrice` is an object: the price numerator + * @param {number} opts.maxPrice.d - If `opts.maxPrice` is an object: the price denominator + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting operation (xdr.LiquidityPoolDepositOp). + */ +function liquidityPoolDeposit() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var liquidityPoolId = opts.liquidityPoolId, + maxAmountA = opts.maxAmountA, + maxAmountB = opts.maxAmountB, + minPrice = opts.minPrice, + maxPrice = opts.maxPrice; + var attributes = {}; + if (!liquidityPoolId) { + throw new TypeError('liquidityPoolId argument is required'); + } + attributes.liquidityPoolId = _xdr["default"].PoolId.fromXDR(liquidityPoolId, 'hex'); + if (!this.isValidAmount(maxAmountA, true)) { + throw new TypeError(this.constructAmountRequirementsError('maxAmountA')); + } + attributes.maxAmountA = this._toXDRAmount(maxAmountA); + if (!this.isValidAmount(maxAmountB, true)) { + throw new TypeError(this.constructAmountRequirementsError('maxAmountB')); + } + attributes.maxAmountB = this._toXDRAmount(maxAmountB); + if (minPrice === undefined) { + throw new TypeError('minPrice argument is required'); + } + attributes.minPrice = this._toXDRPrice(minPrice); + if (maxPrice === undefined) { + throw new TypeError('maxPrice argument is required'); + } + attributes.maxPrice = this._toXDRPrice(maxPrice); + var liquidityPoolDepositOp = new _xdr["default"].LiquidityPoolDepositOp(attributes); + var opAttributes = { + body: _xdr["default"].OperationBody.liquidityPoolDeposit(liquidityPoolDepositOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 4737: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.liquidityPoolWithdraw = liquidityPoolWithdraw; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a liquidity pool withdraw operation. + * + * @function + * @alias Operation.liquidityPoolWithdraw + * @see https://developers.stellar.org/docs/start/list-of-operations/#liquidity-pool-withdraw + * + * @param {object} opts - Options object + * @param {string} opts.liquidityPoolId - The liquidity pool ID. + * @param {string} opts.amount - Amount of pool shares to withdraw. + * @param {string} opts.minAmountA - Minimum amount of first asset to withdraw. + * @param {string} opts.minAmountB - Minimum amount of second asset to withdraw. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting operation (xdr.LiquidityPoolWithdrawOp). + */ +function liquidityPoolWithdraw() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var attributes = {}; + if (!opts.liquidityPoolId) { + throw new TypeError('liquidityPoolId argument is required'); + } + attributes.liquidityPoolId = _xdr["default"].PoolId.fromXDR(opts.liquidityPoolId, 'hex'); + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (!this.isValidAmount(opts.minAmountA, true)) { + throw new TypeError(this.constructAmountRequirementsError('minAmountA')); + } + attributes.minAmountA = this._toXDRAmount(opts.minAmountA); + if (!this.isValidAmount(opts.minAmountB, true)) { + throw new TypeError(this.constructAmountRequirementsError('minAmountB')); + } + attributes.minAmountB = this._toXDRAmount(opts.minAmountB); + var liquidityPoolWithdrawOp = new _xdr["default"].LiquidityPoolWithdrawOp(attributes); + var opAttributes = { + body: _xdr["default"].OperationBody.liquidityPoolWithdraw(liquidityPoolWithdrawOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 1922: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.manageBuyOffer = manageBuyOffer; +var _jsXdr = __webpack_require__(3740); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR ManageBuyOfferOp. A "manage buy offer" operation creates, updates, or + * deletes a buy offer. + * @function + * @alias Operation.manageBuyOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.buyAmount - The total amount you're buying. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `buying` in terms of `selling`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.ManageBuyOfferOp} Manage Buy Offer operation + */ +function manageBuyOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.buyAmount, true)) { + throw new TypeError(this.constructAmountRequirementsError('buyAmount')); + } + attributes.buyAmount = this._toXDRAmount(opts.buyAmount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + if (opts.offerId !== undefined) { + opts.offerId = opts.offerId.toString(); + } else { + opts.offerId = '0'; + } + attributes.offerId = _jsXdr.Hyper.fromString(opts.offerId); + var manageBuyOfferOp = new _xdr["default"].ManageBuyOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageBuyOffer(manageBuyOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 1411: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.manageData = manageData; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation adds data entry to the ledger. + * @function + * @alias Operation.manageData + * @param {object} opts Options object + * @param {string} opts.name - The name of the data entry. + * @param {string|Buffer} opts.value - The value of the data entry. + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.ManageDataOp} Manage Data operation + */ +function manageData(opts) { + var attributes = {}; + if (!(typeof opts.name === 'string' && opts.name.length <= 64)) { + throw new Error('name must be a string, up to 64 characters'); + } + attributes.dataName = opts.name; + if (typeof opts.value !== 'string' && !Buffer.isBuffer(opts.value) && opts.value !== null) { + throw new Error('value must be a string, Buffer or null'); + } + if (typeof opts.value === 'string') { + attributes.dataValue = Buffer.from(opts.value); + } else { + attributes.dataValue = opts.value; + } + if (attributes.dataValue !== null && attributes.dataValue.length > 64) { + throw new Error('value cannot be longer that 64 bytes'); + } + var manageDataOp = new _xdr["default"].ManageDataOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageData(manageDataOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 862: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.manageSellOffer = manageSellOffer; +var _jsXdr = __webpack_require__(3740); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR ManageSellOfferOp. A "manage sell offer" operation creates, updates, or + * deletes an offer. + * @function + * @alias Operation.manageSellOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.ManageSellOfferOp} Manage Sell Offer operation + */ +function manageSellOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.amount, true)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + if (opts.offerId !== undefined) { + opts.offerId = opts.offerId.toString(); + } else { + opts.offerId = '0'; + } + attributes.offerId = _jsXdr.Hyper.fromString(opts.offerId); + var manageSellOfferOp = new _xdr["default"].ManageSellOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageSellOffer(manageSellOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2075: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.pathPaymentStrictReceive = pathPaymentStrictReceive; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a PathPaymentStrictReceive operation. + * + * A `PathPaymentStrictReceive` operation sends the specified amount to the + * destination account. It credits the destination with `destAmount` of + * `destAsset`, while debiting at most `sendMax` of `sendAsset` from the source. + * The transfer optionally occurs through a path. XLM payments create the + * destination account if it does not exist. + * + * @function + * @alias Operation.pathPaymentStrictReceive + * @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-receive + * + * @param {object} opts - Options object + * @param {Asset} opts.sendAsset - asset to pay with + * @param {string} opts.sendMax - maximum amount of sendAsset to send + * @param {string} opts.destination - destination account to send to + * @param {Asset} opts.destAsset - asset the destination will receive + * @param {string} opts.destAmount - amount the destination receives + * @param {Asset[]} opts.path - array of Asset objects to use as the path + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.PathPaymentStrictReceiveOp} the resulting path payment op + */ +function pathPaymentStrictReceive(opts) { + switch (true) { + case !opts.sendAsset: + throw new Error('Must specify a send asset'); + case !this.isValidAmount(opts.sendMax): + throw new TypeError(this.constructAmountRequirementsError('sendMax')); + case !opts.destAsset: + throw new Error('Must provide a destAsset for a payment operation'); + case !this.isValidAmount(opts.destAmount): + throw new TypeError(this.constructAmountRequirementsError('destAmount')); + default: + break; + } + var attributes = {}; + attributes.sendAsset = opts.sendAsset.toXDRObject(); + attributes.sendMax = this._toXDRAmount(opts.sendMax); + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.destAsset = opts.destAsset.toXDRObject(); + attributes.destAmount = this._toXDRAmount(opts.destAmount); + var path = opts.path ? opts.path : []; + attributes.path = path.map(function (x) { + return x.toXDRObject(); + }); + var payment = new _xdr["default"].PathPaymentStrictReceiveOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.pathPaymentStrictReceive(payment); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 3874: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.pathPaymentStrictSend = pathPaymentStrictSend; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a PathPaymentStrictSend operation. + * + * A `PathPaymentStrictSend` operation sends the specified amount to the + * destination account crediting at least `destMin` of `destAsset`, optionally + * through a path. XLM payments create the destination account if it does not + * exist. + * + * @function + * @alias Operation.pathPaymentStrictSend + * @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-send + * + * @param {object} opts - Options object + * @param {Asset} opts.sendAsset - asset to pay with + * @param {string} opts.sendAmount - amount of sendAsset to send (excluding fees) + * @param {string} opts.destination - destination account to send to + * @param {Asset} opts.destAsset - asset the destination will receive + * @param {string} opts.destMin - minimum amount of destAsset to be receive + * @param {Asset[]} opts.path - array of Asset objects to use as the path + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.Operation} the resulting path payment operation + * (xdr.PathPaymentStrictSendOp) + */ +function pathPaymentStrictSend(opts) { + switch (true) { + case !opts.sendAsset: + throw new Error('Must specify a send asset'); + case !this.isValidAmount(opts.sendAmount): + throw new TypeError(this.constructAmountRequirementsError('sendAmount')); + case !opts.destAsset: + throw new Error('Must provide a destAsset for a payment operation'); + case !this.isValidAmount(opts.destMin): + throw new TypeError(this.constructAmountRequirementsError('destMin')); + default: + break; + } + var attributes = {}; + attributes.sendAsset = opts.sendAsset.toXDRObject(); + attributes.sendAmount = this._toXDRAmount(opts.sendAmount); + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.destAsset = opts.destAsset.toXDRObject(); + attributes.destMin = this._toXDRAmount(opts.destMin); + var path = opts.path ? opts.path : []; + attributes.path = path.map(function (x) { + return x.toXDRObject(); + }); + var payment = new _xdr["default"].PathPaymentStrictSendOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.pathPaymentStrictSend(payment); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 3533: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.payment = payment; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a payment operation. + * + * @function + * @alias Operation.payment + * @see https://developers.stellar.org/docs/start/list-of-operations/#payment + * + * @param {object} opts - Options object + * @param {string} opts.destination - destination account ID + * @param {Asset} opts.asset - asset to send + * @param {string} opts.amount - amount to send + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting payment operation (xdr.PaymentOp) + */ +function payment(opts) { + if (!opts.asset) { + throw new Error('Must provide an asset for a payment operation'); + } + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + var attributes = {}; + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.asset = opts.asset.toXDRObject(); + attributes.amount = this._toXDRAmount(opts.amount); + var paymentOp = new _xdr["default"].PaymentOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.payment(paymentOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 149: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.restoreFootprint = restoreFootprint; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Builds an operation to restore the archived ledger entries specified + * by the ledger keys. + * + * The ledger keys to restore are specified separately from the operation + * in read-write footprint of the transaction. + * + * It takes no parameters because the relevant footprint is derived from the + * transaction itself. See {@link TransactionBuilder}'s `opts.sorobanData` + * parameter (or {@link TransactionBuilder.setSorobanData} / + * {@link TransactionBuilder.setLedgerKeys}), which is a + * {@link xdr.SorobanTransactionData} instance that contains fee data & resource + * usage as part of {@link xdr.SorobanTransactionData}. + * + * @function + * @alias Operation.restoreFootprint + * + * @param {object} [opts] - an optional set of parameters + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} a Bump Footprint Expiration operation + * (xdr.RestoreFootprintOp) + */ +function restoreFootprint() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var op = new _xdr["default"].RestoreFootprintOp({ + ext: new _xdr["default"].ExtensionPoint(0) + }); + var opAttributes = { + body: _xdr["default"].OperationBody.restoreFootprint(op) + }; + this.setSourceAccount(opAttributes, opts !== null && opts !== void 0 ? opts : {}); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7790: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.revokeAccountSponsorship = revokeAccountSponsorship; +exports.revokeClaimableBalanceSponsorship = revokeClaimableBalanceSponsorship; +exports.revokeDataSponsorship = revokeDataSponsorship; +exports.revokeLiquidityPoolSponsorship = revokeLiquidityPoolSponsorship; +exports.revokeOfferSponsorship = revokeOfferSponsorship; +exports.revokeSignerSponsorship = revokeSignerSponsorship; +exports.revokeTrustlineSponsorship = revokeTrustlineSponsorship; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +var _keypair = __webpack_require__(6691); +var _asset = __webpack_require__(1764); +var _liquidity_pool_id = __webpack_require__(9353); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a "revoke sponsorship" operation for an account. + * + * @function + * @alias Operation.revokeAccountSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The sponsored account ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeAccountSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * }); + * + */ +function revokeAccountSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.account(new _xdr["default"].LedgerKeyAccount({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId() + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a trustline. + * + * @function + * @alias Operation.revokeTrustlineSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID which owns the trustline. + * @param {Asset | LiquidityPoolId} opts.asset - The trustline asset. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeTrustlineSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * asset: new StellarBase.LiquidityPoolId( + * 'USDUSD', + * 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * ) + * }); + * + */ +function revokeTrustlineSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var asset; + if (opts.asset instanceof _asset.Asset) { + asset = opts.asset.toTrustLineXDRObject(); + } else if (opts.asset instanceof _liquidity_pool_id.LiquidityPoolId) { + asset = opts.asset.toXDRObject(); + } else { + throw new TypeError('asset must be an Asset or LiquidityPoolId'); + } + var ledgerKey = _xdr["default"].LedgerKey.trustline(new _xdr["default"].LedgerKeyTrustLine({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + asset: asset + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for an offer. + * + * @function + * @alias Operation.revokeOfferSponsorship + * @param {object} opts Options object + * @param {string} opts.seller - The account ID which created the offer. + * @param {string} opts.offerId - The offer ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeOfferSponsorship({ + * seller: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * offerId: '1234' + * }); + * + */ +function revokeOfferSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.seller)) { + throw new Error('seller is invalid'); + } + if (typeof opts.offerId !== 'string') { + throw new Error('offerId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.offer(new _xdr["default"].LedgerKeyOffer({ + sellerId: _keypair.Keypair.fromPublicKey(opts.seller).xdrAccountId(), + offerId: _xdr["default"].Int64.fromString(opts.offerId) + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a data entry. + * + * @function + * @alias Operation.revokeDataSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID which owns the data entry. + * @param {string} opts.name - The name of the data entry + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeDataSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * name: 'foo' + * }); + * + */ +function revokeDataSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + if (typeof opts.name !== 'string' || opts.name.length > 64) { + throw new Error('name must be a string, up to 64 characters'); + } + var ledgerKey = _xdr["default"].LedgerKey.data(new _xdr["default"].LedgerKeyData({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + dataName: opts.name + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a claimable balance. + * + * @function + * @alias Operation.revokeClaimableBalanceSponsorship + * @param {object} opts Options object + * @param {string} opts.balanceId - The sponsored claimable balance ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeClaimableBalanceSponsorship({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + */ +function revokeClaimableBalanceSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (typeof opts.balanceId !== 'string') { + throw new Error('balanceId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.claimableBalance(new _xdr["default"].LedgerKeyClaimableBalance({ + balanceId: _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex') + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Creates a "revoke sponsorship" operation for a liquidity pool. + * + * @function + * @alias Operation.revokeLiquidityPoolSponsorship + * @param {object} opts – Options object. + * @param {string} opts.liquidityPoolId - The sponsored liquidity pool ID in 'hex' string. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr Operation. + * + * @example + * const op = Operation.revokeLiquidityPoolSponsorship({ + * liquidityPoolId: 'dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7', + * }); + * + */ +function revokeLiquidityPoolSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (typeof opts.liquidityPoolId !== 'string') { + throw new Error('liquidityPoolId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.liquidityPool(new _xdr["default"].LedgerKeyLiquidityPool({ + liquidityPoolId: _xdr["default"].PoolId.fromXDR(opts.liquidityPoolId, 'hex') + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = { + body: _xdr["default"].OperationBody.revokeSponsorship(op) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a signer. + * + * @function + * @alias Operation.revokeSignerSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID where the signer sponsorship is being removed from. + * @param {object} opts.signer - The signer whose sponsorship is being removed. + * @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer. + * @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string). + * @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeSignerSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * signer: { + * ed25519PublicKey: 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ' + * } + * }) + * + */ +function revokeSignerSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var key; + if (opts.signer.ed25519PublicKey) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) { + throw new Error('signer.ed25519PublicKey is invalid.'); + } + var rawKey = _strkey.StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey); + key = new _xdr["default"].SignerKey.signerKeyTypeEd25519(rawKey); + } else if (opts.signer.preAuthTx) { + var buffer; + if (typeof opts.signer.preAuthTx === 'string') { + buffer = Buffer.from(opts.signer.preAuthTx, 'hex'); + } else { + buffer = opts.signer.preAuthTx; + } + if (!(Buffer.isBuffer(buffer) && buffer.length === 32)) { + throw new Error('signer.preAuthTx must be 32 bytes Buffer.'); + } + key = new _xdr["default"].SignerKey.signerKeyTypePreAuthTx(buffer); + } else if (opts.signer.sha256Hash) { + var _buffer; + if (typeof opts.signer.sha256Hash === 'string') { + _buffer = Buffer.from(opts.signer.sha256Hash, 'hex'); + } else { + _buffer = opts.signer.sha256Hash; + } + if (!(Buffer.isBuffer(_buffer) && _buffer.length === 32)) { + throw new Error('signer.sha256Hash must be 32 bytes Buffer.'); + } + key = new _xdr["default"].SignerKey.signerKeyTypeHashX(_buffer); + } else { + throw new Error('signer is invalid'); + } + var signer = new _xdr["default"].RevokeSponsorshipOpSigner({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + signerKey: key + }); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipSigner(signer); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2018: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.setOptions = setOptions; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/* eslint-disable no-param-reassign */ + +function weightCheckFunction(value, name) { + if (value >= 0 && value <= 255) { + return true; + } + throw new Error("".concat(name, " value must be between 0 and 255")); +} + +/** + * Returns an XDR SetOptionsOp. A "set options" operations set or clear account flags, + * set the account's inflation destination, and/or add new signers to the account. + * The flags used in `opts.clearFlags` and `opts.setFlags` can be the following: + * - `{@link AuthRequiredFlag}` + * - `{@link AuthRevocableFlag}` + * - `{@link AuthImmutableFlag}` + * - `{@link AuthClawbackEnabledFlag}` + * + * It's possible to set/clear multiple flags at once using logical or. + * + * @function + * @alias Operation.setOptions + * + * @param {object} opts Options object + * @param {string} [opts.inflationDest] - Set this account ID as the account's inflation destination. + * @param {(number|string)} [opts.clearFlags] - Bitmap integer for which account flags to clear. + * @param {(number|string)} [opts.setFlags] - Bitmap integer for which account flags to set. + * @param {number|string} [opts.masterWeight] - The master key weight. + * @param {number|string} [opts.lowThreshold] - The sum weight for the low threshold. + * @param {number|string} [opts.medThreshold] - The sum weight for the medium threshold. + * @param {number|string} [opts.highThreshold] - The sum weight for the high threshold. + * @param {object} [opts.signer] - Add or remove a signer from the account. The signer is + * deleted if the weight is 0. Only one of `ed25519PublicKey`, `sha256Hash`, `preAuthTx` should be defined. + * @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer. + * @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string) of preimage that will unlock funds. Preimage should be used as signature of future transaction. + * @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction that will unlock funds. + * @param {string} [opts.signer.ed25519SignedPayload] - Signed payload signer (ed25519 public key + raw payload) for atomic transaction signature disclosure. + * @param {number|string} [opts.signer.weight] - The weight of the new signer (0 to delete or 1-255) + * @param {string} [opts.homeDomain] - sets the home domain used for reverse federation lookup. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * + * @returns {xdr.SetOptionsOp} XDR operation + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +function setOptions(opts) { + var attributes = {}; + if (opts.inflationDest) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.inflationDest)) { + throw new Error('inflationDest is invalid'); + } + attributes.inflationDest = _keypair.Keypair.fromPublicKey(opts.inflationDest).xdrAccountId(); + } + attributes.clearFlags = this._checkUnsignedIntValue('clearFlags', opts.clearFlags); + attributes.setFlags = this._checkUnsignedIntValue('setFlags', opts.setFlags); + attributes.masterWeight = this._checkUnsignedIntValue('masterWeight', opts.masterWeight, weightCheckFunction); + attributes.lowThreshold = this._checkUnsignedIntValue('lowThreshold', opts.lowThreshold, weightCheckFunction); + attributes.medThreshold = this._checkUnsignedIntValue('medThreshold', opts.medThreshold, weightCheckFunction); + attributes.highThreshold = this._checkUnsignedIntValue('highThreshold', opts.highThreshold, weightCheckFunction); + if (opts.homeDomain !== undefined && typeof opts.homeDomain !== 'string') { + throw new TypeError('homeDomain argument must be of type String'); + } + attributes.homeDomain = opts.homeDomain; + if (opts.signer) { + var weight = this._checkUnsignedIntValue('signer.weight', opts.signer.weight, weightCheckFunction); + var key; + var setValues = 0; + if (opts.signer.ed25519PublicKey) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) { + throw new Error('signer.ed25519PublicKey is invalid.'); + } + var rawKey = _strkey.StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey); + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypeEd25519(rawKey); + setValues += 1; + } + if (opts.signer.preAuthTx) { + if (typeof opts.signer.preAuthTx === 'string') { + opts.signer.preAuthTx = Buffer.from(opts.signer.preAuthTx, 'hex'); + } + if (!(Buffer.isBuffer(opts.signer.preAuthTx) && opts.signer.preAuthTx.length === 32)) { + throw new Error('signer.preAuthTx must be 32 bytes Buffer.'); + } + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypePreAuthTx(opts.signer.preAuthTx); + setValues += 1; + } + if (opts.signer.sha256Hash) { + if (typeof opts.signer.sha256Hash === 'string') { + opts.signer.sha256Hash = Buffer.from(opts.signer.sha256Hash, 'hex'); + } + if (!(Buffer.isBuffer(opts.signer.sha256Hash) && opts.signer.sha256Hash.length === 32)) { + throw new Error('signer.sha256Hash must be 32 bytes Buffer.'); + } + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypeHashX(opts.signer.sha256Hash); + setValues += 1; + } + if (opts.signer.ed25519SignedPayload) { + if (!_strkey.StrKey.isValidSignedPayload(opts.signer.ed25519SignedPayload)) { + throw new Error('signer.ed25519SignedPayload is invalid.'); + } + var _rawKey = _strkey.StrKey.decodeSignedPayload(opts.signer.ed25519SignedPayload); + var signedPayloadXdr = _xdr["default"].SignerKeyEd25519SignedPayload.fromXDR(_rawKey); + + // eslint-disable-next-line new-cap + key = _xdr["default"].SignerKey.signerKeyTypeEd25519SignedPayload(signedPayloadXdr); + setValues += 1; + } + if (setValues !== 1) { + throw new Error('Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx.'); + } + attributes.signer = new _xdr["default"].Signer({ + key: key, + weight: weight + }); + } + var setOptionsOp = new _xdr["default"].SetOptionsOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.setOptions(setOptionsOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 1804: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.setTrustLineFlags = setTrustLineFlags; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/** + * Creates a trustline flag configuring operation. + * + * For the flags, set them to true to enable them and false to disable them. Any + * unmodified operations will be marked `undefined` in the result. + * + * Note that you can only **clear** the clawbackEnabled flag set; it must be set + * account-wide via operations.SetOptions (setting + * xdr.AccountFlags.clawbackEnabled). + * + * @function + * @alias Operation.setTrustLineFlags + * + * @param {object} opts - Options object + * @param {string} opts.trustor - the account whose trustline this is + * @param {Asset} opts.asset - the asset on the trustline + * @param {object} opts.flags - the set of flags to modify + * + * @param {bool} [opts.flags.authorized] - authorize account to perform + * transactions with its credit + * @param {bool} [opts.flags.authorizedToMaintainLiabilities] - authorize + * account to maintain and reduce liabilities for its credit + * @param {bool} [opts.flags.clawbackEnabled] - stop claimable balances on + * this trustlines from having clawbacks enabled (this flag can only be set + * to false!) + * @param {string} [opts.source] - The source account for the operation. + * Defaults to the transaction's source account. + * + * @note You must include at least one flag. + * + * @return {xdr.SetTrustLineFlagsOp} + * + * @link xdr.AccountFlags + * @link xdr.TrustLineFlags + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#set-trustline-flags-operation + * @see https://developers.stellar.org/docs/start/list-of-operations/#set-options + */ +function setTrustLineFlags() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var attributes = {}; + if (_typeof(opts.flags) !== 'object' || Object.keys(opts.flags).length === 0) { + throw new Error('opts.flags must be a map of boolean flags to modify'); + } + var mapping = { + authorized: _xdr["default"].TrustLineFlags.authorizedFlag(), + authorizedToMaintainLiabilities: _xdr["default"].TrustLineFlags.authorizedToMaintainLiabilitiesFlag(), + clawbackEnabled: _xdr["default"].TrustLineFlags.trustlineClawbackEnabledFlag() + }; + + /* eslint no-bitwise: "off" */ + var clearFlag = 0; + var setFlag = 0; + Object.keys(opts.flags).forEach(function (flagName) { + if (!Object.prototype.hasOwnProperty.call(mapping, flagName)) { + throw new Error("unsupported flag name specified: ".concat(flagName)); + } + var flagValue = opts.flags[flagName]; + var bit = mapping[flagName].value; + if (flagValue === true) { + setFlag |= bit; + } else if (flagValue === false) { + clearFlag |= bit; + } + }); + attributes.trustor = _keypair.Keypair.fromPublicKey(opts.trustor).xdrAccountId(); + attributes.asset = opts.asset.toXDRObject(); + attributes.clearFlags = clearFlag; + attributes.setFlags = setFlag; + var opAttributes = { + body: _xdr["default"].OperationBody.setTrustLineFlags(new _xdr["default"].SetTrustLineFlagsOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7177: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.nativeToScVal = nativeToScVal; +exports.scValToNative = scValToNative; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _address = __webpack_require__(1180); +var _contract = __webpack_require__(7452); +var _index = __webpack_require__(8549); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/** + * Attempts to convert native types into smart contract values + * ({@link xdr.ScVal}). + * + * Provides conversions from smart contract XDR values ({@link xdr.ScVal}) to + * native JavaScript types. + * + * The conversions are as follows: + * + * - xdr.ScVal -> passthrough + * - null/undefined -> scvVoid + * - string -> scvString (a copy is made) + * - UintArray8 -> scvBytes (a copy is made) + * - boolean -> scvBool + * + * - number/bigint -> the smallest possible XDR integer type that will fit the + * input value (if you want a specific type, use {@link ScInt}) + * + * - {@link Address} or {@link Contract} -> scvAddress (for contracts and + * public keys) + * + * - Array -> scvVec after attempting to convert each item of type `T` to an + * xdr.ScVal (recursively). note that all values must be the same type! + * + * - object -> scvMap after attempting to convert each key and value to an + * xdr.ScVal (recursively). note that there is no restriction on types + * matching anywhere (unlike arrays) + * + * When passing an integer-like native value, you can also optionally specify a + * type which will force a particular interpretation of that value. + * + * Note that not all type specifications are compatible with all `ScVal`s, e.g. + * `toScVal("a string", {type: "i256"})` will throw. + * + * @param {any} val - a native (or convertible) input value to wrap + * @param {object} [opts] - an optional set of hints around the type of + * conversion you'd like to see + * @param {string} [opts.type] - there is different behavior for different input + * types for `val`: + * + * - when `val` is an integer-like type (i.e. number|bigint), this will be + * forwarded to {@link ScInt} or forced to be u32/i32. + * + * - when `val` is an array type, this is forwarded to the recursion + * + * - when `val` is an object type (key-value entries), this should be an + * object in which each key has a pair of types (to represent forced types + * for the key and the value), where `null` (or a missing entry) indicates + * the default interpretation(s) (refer to the examples, below) + * + * - when `val` is a string type, this can be 'string' or 'symbol' to force + * a particular interpretation of `val`. + * + * - when `val` is a bytes-like type, this can be 'string', 'symbol', or + * 'bytes' to force a particular interpretation + * + * As a simple example, `nativeToScVal("hello", {type: 'symbol'})` will + * return an `scvSymbol`, whereas without the type it would have been an + * `scvString`. + * + * @returns {xdr.ScVal} a wrapped, smart, XDR version of the input value + * @throws {TypeError} if... + * - there are arrays with more than one type in them + * - there are values that do not have a sensible conversion (e.g. random XDR + * types, custom classes) + * - the type of the input object (or some inner value of said object) cannot + * be determined (via `typeof`) + * - the type you specified (via `opts.type`) is incompatible with the value + * you passed in (`val`), e.g. `nativeToScVal("a string", { type: 'i128' })`, + * though this does not apply for types that ignore `opts` (e.g. addresses). + * @see scValToNative + * + * @example + * nativeToScVal(1000); // gives ScValType === scvU64 + * nativeToScVal(1000n); // gives ScValType === scvU64 + * nativeToScVal(1n << 100n); // gives ScValType === scvU128 + * nativeToScVal(1000, { type: 'u32' }); // gives ScValType === scvU32 + * nativeToScVal(1000, { type: 'i125' }); // gives ScValType === scvI256 + * nativeToScVal("a string"); // gives ScValType === scvString + * nativeToScVal("a string", { type: 'symbol' }); // gives scvSymbol + * nativeToScVal(new Uint8Array(5)); // scvBytes + * nativeToScVal(new Uint8Array(5), { type: 'symbol' }); // scvSymbol + * nativeToScVal(null); // scvVoid + * nativeToScVal(true); // scvBool + * nativeToScVal([1, 2, 3]); // gives scvVec with each element as scvU64 + * nativeToScVal([1, 2, 3], { type: 'i128' }); // scvVec + * nativeToScVal({ 'hello': 1, 'world': [ true, false ] }, { + * type: { + * 'hello': [ 'symbol', 'i128' ], + * } + * }) + * // gives scvMap with entries: [ + * // [ scvSymbol, scvI128 ], + * // [ scvString, scvArray ] + * // ] + * + * @example + * import { + * nativeToScVal, + * scValToNative, + * ScInt, + * xdr + * } from '@stellar/stellar-base'; + * + * let gigaMap = { + * bool: true, + * void: null, + * u32: xdr.ScVal.scvU32(1), + * i32: xdr.ScVal.scvI32(1), + * u64: 1n, + * i64: -1n, + * u128: new ScInt(1).toU128(), + * i128: new ScInt(1).toI128(), + * u256: new ScInt(1).toU256(), + * i256: new ScInt(1).toI256(), + * map: { + * arbitrary: 1n, + * nested: 'values', + * etc: false + * }, + * vec: ['same', 'type', 'list'], + * }; + * + * // then, simply: + * let scv = nativeToScVal(gigaMap); // scv.switch() == xdr.ScValType.scvMap() + * + * // then... + * someContract.call("method", scv); + * + * // Similarly, the inverse should work: + * scValToNative(scv) == gigaMap; // true + */ +function nativeToScVal(val) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + switch (_typeof(val)) { + case 'object': + { + var _val$constructor$name, _val$constructor; + if (val === null) { + return _xdr["default"].ScVal.scvVoid(); + } + if (val instanceof _xdr["default"].ScVal) { + return val; // should we copy? + } + if (val instanceof _address.Address) { + return val.toScVal(); + } + if (val instanceof _contract.Contract) { + return val.address().toScVal(); + } + if (val instanceof Uint8Array || Buffer.isBuffer(val)) { + var _opts$type; + var copy = Uint8Array.from(val); + switch ((_opts$type = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type !== void 0 ? _opts$type : 'bytes') { + case 'bytes': + return _xdr["default"].ScVal.scvBytes(copy); + case 'symbol': + return _xdr["default"].ScVal.scvSymbol(copy); + case 'string': + return _xdr["default"].ScVal.scvString(copy); + default: + throw new TypeError("invalid type (".concat(opts.type, ") specified for bytes-like value")); + } + } + if (Array.isArray(val)) { + if (val.length > 0 && val.some(function (v) { + return _typeof(v) !== _typeof(val[0]); + })) { + throw new TypeError("array values (".concat(val, ") must have the same type (types: ").concat(val.map(function (v) { + return _typeof(v); + }).join(','), ")")); + } + return _xdr["default"].ScVal.scvVec(val.map(function (v) { + return nativeToScVal(v, opts); + })); + } + if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : '') !== 'Object') { + var _val$constructor2; + throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")")); + } + return _xdr["default"].ScVal.scvMap(Object.entries(val) + // The Soroban runtime expects maps to have their keys in sorted + // order, so let's do that here as part of the conversion to prevent + // confusing error messages on execution. + .sort(function (_ref, _ref2) { + var _ref3 = _slicedToArray(_ref, 1), + key1 = _ref3[0]; + var _ref4 = _slicedToArray(_ref2, 1), + key2 = _ref4[0]; + return key1.localeCompare(key2); + }).map(function (_ref5) { + var _k, _opts$type2; + var _ref6 = _slicedToArray(_ref5, 2), + k = _ref6[0], + v = _ref6[1]; + // the type can be specified with an entry for the key and the value, + // e.g. val = { 'hello': 1 } and opts.type = { hello: [ 'symbol', + // 'u128' ]} or you can use `null` for the default interpretation + var _ref7 = (_k = ((_opts$type2 = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type2 !== void 0 ? _opts$type2 : {})[k]) !== null && _k !== void 0 ? _k : [null, null], + _ref8 = _slicedToArray(_ref7, 2), + keyType = _ref8[0], + valType = _ref8[1]; + var keyOpts = keyType ? { + type: keyType + } : {}; + var valOpts = valType ? { + type: valType + } : {}; + return new _xdr["default"].ScMapEntry({ + key: nativeToScVal(k, keyOpts), + val: nativeToScVal(v, valOpts) + }); + })); + } + case 'number': + case 'bigint': + switch (opts === null || opts === void 0 ? void 0 : opts.type) { + case 'u32': + return _xdr["default"].ScVal.scvU32(val); + case 'i32': + return _xdr["default"].ScVal.scvI32(val); + default: + break; + } + return new _index.ScInt(val, { + type: opts === null || opts === void 0 ? void 0 : opts.type + }).toScVal(); + case 'string': + { + var _opts$type3; + var optType = (_opts$type3 = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type3 !== void 0 ? _opts$type3 : 'string'; + switch (optType) { + case 'string': + return _xdr["default"].ScVal.scvString(val); + case 'symbol': + return _xdr["default"].ScVal.scvSymbol(val); + case 'address': + return new _address.Address(val).toScVal(); + case 'u32': + return _xdr["default"].ScVal.scvU32(parseInt(val, 10)); + case 'i32': + return _xdr["default"].ScVal.scvI32(parseInt(val, 10)); + default: + if (_index.XdrLargeInt.isType(optType)) { + return new _index.XdrLargeInt(optType, val).toScVal(); + } + throw new TypeError("invalid type (".concat(opts.type, ") specified for string value")); + } + } + case 'boolean': + return _xdr["default"].ScVal.scvBool(val); + case 'undefined': + return _xdr["default"].ScVal.scvVoid(); + case 'function': + // FIXME: Is this too helpful? + return nativeToScVal(val()); + default: + throw new TypeError("failed to convert typeof ".concat(_typeof(val), " (").concat(val, ")")); + } +} + +/** + * Given a smart contract value, attempt to convert it to a native type. + * Possible conversions include: + * + * - void -> `null` + * - u32, i32 -> `number` + * - u64, i64, u128, i128, u256, i256 -> `bigint` + * - vec -> `Array` of any of the above (via recursion) + * - map -> key-value object of any of the above (via recursion) + * - bool -> `boolean` + * - bytes -> `Uint8Array` + * - symbol -> `string` + * - string -> `string` IF the underlying buffer can be decoded as ascii/utf8, + * `Uint8Array` of the raw contents in any error case + * + * If no viable conversion can be determined, this just "unwraps" the smart + * value to return its underlying XDR value. + * + * @param {xdr.ScVal} scv - the input smart contract value + * + * @returns {any} + * @see nativeToScVal + */ +function scValToNative(scv) { + var _scv$vec, _scv$map; + // we use the verbose xdr.ScValType..value form here because it's faster + // than string comparisons and the underlying constants never need to be + // updated + switch (scv["switch"]().value) { + case _xdr["default"].ScValType.scvVoid().value: + return null; + + // these can be converted to bigints directly + case _xdr["default"].ScValType.scvU64().value: + case _xdr["default"].ScValType.scvI64().value: + return scv.value().toBigInt(); + + // these can be parsed by internal abstractions note that this can also + // handle the above two cases, but it's not as efficient (another + // type-check, parsing, etc.) + case _xdr["default"].ScValType.scvU128().value: + case _xdr["default"].ScValType.scvI128().value: + case _xdr["default"].ScValType.scvU256().value: + case _xdr["default"].ScValType.scvI256().value: + return (0, _index.scValToBigInt)(scv); + case _xdr["default"].ScValType.scvVec().value: + return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(scValToNative); + case _xdr["default"].ScValType.scvAddress().value: + return _address.Address.fromScVal(scv).toString(); + case _xdr["default"].ScValType.scvMap().value: + return Object.fromEntries(((_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []).map(function (entry) { + return [scValToNative(entry.key()), scValToNative(entry.val())]; + })); + + // these return the primitive type directly + case _xdr["default"].ScValType.scvBool().value: + case _xdr["default"].ScValType.scvU32().value: + case _xdr["default"].ScValType.scvI32().value: + case _xdr["default"].ScValType.scvBytes().value: + return scv.value(); + + // Symbols are limited to [a-zA-Z0-9_]+, so we can safely make ascii strings + // + // Strings, however, are "presented" as strings and we treat them as such + // (in other words, string = bytes with a hint that it's text). If the user + // encoded non-printable bytes in their string value, that's on them. + // + // Note that we assume a utf8 encoding (ascii-compatible). For other + // encodings, you should probably use bytes anyway. If it cannot be decoded, + // the raw bytes are returned. + case _xdr["default"].ScValType.scvSymbol().value: + case _xdr["default"].ScValType.scvString().value: + { + var v = scv.value(); // string|Buffer + if (Buffer.isBuffer(v) || ArrayBuffer.isView(v)) { + try { + return new TextDecoder().decode(v); + } catch (e) { + return new Uint8Array(v.buffer); // copy of bytes + } + } + return v; // string already + } + + // these can be converted to bigint + case _xdr["default"].ScValType.scvTimepoint().value: + case _xdr["default"].ScValType.scvDuration().value: + return new _xdr["default"].Uint64(scv.value()).toBigInt(); + case _xdr["default"].ScValType.scvError().value: + switch (scv.error()["switch"]().value) { + // Distinguish errors from the user contract. + case _xdr["default"].ScErrorType.sceContract().value: + return { + type: 'contract', + code: scv.error().contractCode() + }; + default: + { + var err = scv.error(); + return { + type: 'system', + code: err.code().value, + value: err.code().name + }; + } + } + + // in the fallthrough case, just return the underlying value directly + default: + return scv.value(); + } +} + +/***/ }), + +/***/ 225: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.SignerKey = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * A container class with helpers to convert between signer keys + * (`xdr.SignerKey`) and {@link StrKey}s. + * + * It's primarly used for manipulating the `extraSigners` precondition on a + * {@link Transaction}. + * + * @see {@link TransactionBuilder.setExtraSigners} + */ +var SignerKey = exports.SignerKey = /*#__PURE__*/function () { + function SignerKey() { + _classCallCheck(this, SignerKey); + } + return _createClass(SignerKey, null, [{ + key: "decodeAddress", + value: + /** + * Decodes a StrKey address into an xdr.SignerKey instance. + * + * Only ED25519 public keys (G...), pre-auth transactions (T...), hashes + * (H...), and signed payloads (P...) can be signer keys. + * + * @param {string} address a StrKey-encoded signer address + * @returns {xdr.SignerKey} + */ + function decodeAddress(address) { + var signerKeyMap = { + ed25519PublicKey: _xdr["default"].SignerKey.signerKeyTypeEd25519, + preAuthTx: _xdr["default"].SignerKey.signerKeyTypePreAuthTx, + sha256Hash: _xdr["default"].SignerKey.signerKeyTypeHashX, + signedPayload: _xdr["default"].SignerKey.signerKeyTypeEd25519SignedPayload + }; + var vb = _strkey.StrKey.getVersionByteForPrefix(address); + var encoder = signerKeyMap[vb]; + if (!encoder) { + throw new Error("invalid signer key type (".concat(vb, ")")); + } + var raw = (0, _strkey.decodeCheck)(vb, address); + switch (vb) { + case 'signedPayload': + return encoder(new _xdr["default"].SignerKeyEd25519SignedPayload({ + ed25519: raw.slice(0, 32), + payload: raw.slice(32 + 4) + })); + case 'ed25519PublicKey': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + default: + return encoder(raw); + } + } + + /** + * Encodes a signer key into its StrKey equivalent. + * + * @param {xdr.SignerKey} signerKey the signer + * @returns {string} the StrKey representation of the signer + */ + }, { + key: "encodeSignerKey", + value: function encodeSignerKey(signerKey) { + var strkeyType; + var raw; + switch (signerKey["switch"]()) { + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519(): + strkeyType = 'ed25519PublicKey'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypePreAuthTx(): + strkeyType = 'preAuthTx'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypeHashX(): + strkeyType = 'sha256Hash'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519SignedPayload(): + strkeyType = 'signedPayload'; + raw = signerKey.ed25519SignedPayload().toXDR('raw'); + break; + default: + throw new Error("invalid SignerKey (type: ".concat(signerKey["switch"](), ")")); + } + return (0, _strkey.encodeCheck)(strkeyType, raw); + } + }]); +}(); + +/***/ }), + +/***/ 15: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.FastSigning = void 0; +exports.generate = generate; +exports.sign = sign; +exports.verify = verify; +// This module provides the signing functionality used by the stellar network +// The code below may look a little strange... this is because we try to provide +// the most efficient signing method possible. First, we try to load the +// native `sodium-native` package for node.js environments, and if that fails we +// fallback to `tweetnacl` + +var actualMethods = {}; + +/** + * Use this flag to check if fast signing (provided by `sodium-native` package) is available. + * If your app is signing a large number of transaction or verifying a large number + * of signatures make sure `sodium-native` package is installed. + */ +var FastSigning = exports.FastSigning = checkFastSigning(); +function sign(data, secretKey) { + return actualMethods.sign(data, secretKey); +} +function verify(data, signature, publicKey) { + return actualMethods.verify(data, signature, publicKey); +} +function generate(secretKey) { + return actualMethods.generate(secretKey); +} +function checkFastSigning() { + return typeof window === 'undefined' ? checkFastSigningNode() : checkFastSigningBrowser(); +} +function checkFastSigningNode() { + // NOTE: we use commonjs style require here because es6 imports + // can only occur at the top level. thanks, obama. + var sodium; + try { + // eslint-disable-next-line + sodium = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module 'sodium-native'"); e.code = 'MODULE_NOT_FOUND'; throw e; }())); + } catch (err) { + return checkFastSigningBrowser(); + } + if (!Object.keys(sodium).length) { + return checkFastSigningBrowser(); + } + actualMethods.generate = function (secretKey) { + var pk = Buffer.alloc(sodium.crypto_sign_PUBLICKEYBYTES); + var sk = Buffer.alloc(sodium.crypto_sign_SECRETKEYBYTES); + sodium.crypto_sign_seed_keypair(pk, sk, secretKey); + return pk; + }; + actualMethods.sign = function (data, secretKey) { + data = Buffer.from(data); + var signature = Buffer.alloc(sodium.crypto_sign_BYTES); + sodium.crypto_sign_detached(signature, data, secretKey); + return signature; + }; + actualMethods.verify = function (data, signature, publicKey) { + data = Buffer.from(data); + try { + return sodium.crypto_sign_verify_detached(signature, data, publicKey); + } catch (e) { + return false; + } + }; + return true; +} +function checkFastSigningBrowser() { + // fallback to `tweetnacl` if we're in the browser or + // if there was a failure installing `sodium-native` + // eslint-disable-next-line + var nacl = __webpack_require__(4940); + actualMethods.generate = function (secretKey) { + var secretKeyUint8 = new Uint8Array(secretKey); + var naclKeys = nacl.sign.keyPair.fromSeed(secretKeyUint8); + return Buffer.from(naclKeys.publicKey); + }; + actualMethods.sign = function (data, secretKey) { + data = Buffer.from(data); + data = new Uint8Array(data.toJSON().data); + secretKey = new Uint8Array(secretKey.toJSON().data); + var signature = nacl.sign.detached(data, secretKey); + return Buffer.from(signature); + }; + actualMethods.verify = function (data, signature, publicKey) { + data = Buffer.from(data); + data = new Uint8Array(data.toJSON().data); + signature = new Uint8Array(signature.toJSON().data); + publicKey = new Uint8Array(publicKey.toJSON().data); + return nacl.sign.detached.verify(data, signature, publicKey); + }; + return false; +} + +/***/ }), + +/***/ 4062: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Soroban = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/* Helper class to assist with formatting and parsing token amounts. */ +var Soroban = exports.Soroban = /*#__PURE__*/function () { + function Soroban() { + _classCallCheck(this, Soroban); + } + return _createClass(Soroban, null, [{ + key: "formatTokenAmount", + value: + /** + * Given a whole number smart contract amount of a token and an amount of + * decimal places (if the token has any), it returns a "display" value. + * + * All arithmetic inside the contract is performed on integers to avoid + * potential precision and consistency issues of floating-point. + * + * @param {string} amount the token amount you want to display + * @param {number} decimals specify how many decimal places a token has + * + * @returns {string} the display value + * @throws {TypeError} if the given amount has a decimal point already + * @example + * formatTokenAmount("123000", 4) === "12.3"; + */ + function formatTokenAmount(amount, decimals) { + if (amount.includes('.')) { + throw new TypeError('No decimals are allowed'); + } + var formatted = amount; + if (decimals > 0) { + if (decimals > formatted.length) { + formatted = ['0', formatted.toString().padStart(decimals, '0')].join('.'); + } else { + formatted = [formatted.slice(0, -decimals), formatted.slice(-decimals)].join('.'); + } + } + + // remove trailing zero if any + return formatted.replace(/(\.\d*?)0+$/, '$1'); + } + + /** + * Parse a token amount to use it on smart contract + * + * This function takes the display value and its decimals (if the token has + * any) and returns a string that'll be used within the smart contract. + * + * @param {string} value the token amount you want to use it on smart + * contract which you've been displaying in a UI + * @param {number} decimals the number of decimal places expected in the + * display value (different than the "actual" number, because suffix zeroes + * might not be present) + * + * @returns {string} the whole number token amount represented by the display + * value with the decimal places shifted over + * + * @example + * const displayValueAmount = "123.4560" + * const parsedAmtForSmartContract = parseTokenAmount(displayValueAmount, 5); + * parsedAmtForSmartContract === "12345600" + */ + }, { + key: "parseTokenAmount", + value: function parseTokenAmount(value, decimals) { + var _fraction$padEnd; + var _value$split$slice = value.split('.').slice(), + _value$split$slice2 = _toArray(_value$split$slice), + whole = _value$split$slice2[0], + fraction = _value$split$slice2[1], + rest = _value$split$slice2.slice(2); + if (rest.length) { + throw new Error("Invalid decimal value: ".concat(value)); + } + var shifted = BigInt(whole + ((_fraction$padEnd = fraction === null || fraction === void 0 ? void 0 : fraction.padEnd(decimals, '0')) !== null && _fraction$padEnd !== void 0 ? _fraction$padEnd : '0'.repeat(decimals))); + return shifted.toString(); + } + }]); +}(); + +/***/ }), + +/***/ 4842: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.SorobanDataBuilder = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Supports building {@link xdr.SorobanTransactionData} structures with various + * items set to specific values. + * + * This is recommended for when you are building + * {@link Operation.extendFootprintTtl} / {@link Operation.restoreFootprint} + * operations and need to {@link TransactionBuilder.setSorobanData} to avoid + * (re)building the entire data structure from scratch. + * + * @constructor + * + * @param {string | xdr.SorobanTransactionData} [sorobanData] either a + * base64-encoded string that represents an + * {@link xdr.SorobanTransactionData} instance or an XDR instance itself + * (it will be copied); if omitted or "falsy" (e.g. an empty string), it + * starts with an empty instance + * + * @example + * // You want to use an existing data blob but override specific parts. + * const newData = new SorobanDataBuilder(existing) + * .setReadOnly(someLedgerKeys) + * .setRefundableFee("1000") + * .build(); + * + * // You want an instance from scratch + * const newData = new SorobanDataBuilder() + * .setFootprint([someLedgerKey], []) + * .setRefundableFee("1000") + * .build(); + */ +var SorobanDataBuilder = exports.SorobanDataBuilder = /*#__PURE__*/function () { + function SorobanDataBuilder(sorobanData) { + _classCallCheck(this, SorobanDataBuilder); + _defineProperty(this, "_data", void 0); + var data; + if (!sorobanData) { + data = new _xdr["default"].SorobanTransactionData({ + resources: new _xdr["default"].SorobanResources({ + footprint: new _xdr["default"].LedgerFootprint({ + readOnly: [], + readWrite: [] + }), + instructions: 0, + readBytes: 0, + writeBytes: 0 + }), + ext: new _xdr["default"].ExtensionPoint(0), + resourceFee: new _xdr["default"].Int64(0) + }); + } else if (typeof sorobanData === 'string' || ArrayBuffer.isView(sorobanData)) { + data = SorobanDataBuilder.fromXDR(sorobanData); + } else { + data = SorobanDataBuilder.fromXDR(sorobanData.toXDR()); // copy + } + this._data = data; + } + + /** + * Decodes and builds a {@link xdr.SorobanTransactionData} instance. + * @param {Uint8Array|Buffer|string} data raw input to decode + * @returns {xdr.SorobanTransactionData} + */ + return _createClass(SorobanDataBuilder, [{ + key: "setResourceFee", + value: + /** + * Sets the resource fee portion of the Soroban data. + * @param {number | bigint | string} fee the resource fee to set (int64) + * @returns {SorobanDataBuilder} + */ + function setResourceFee(fee) { + this._data.resourceFee(new _xdr["default"].Int64(fee)); + return this; + } + + /** + * Sets up the resource metrics. + * + * You should almost NEVER need this, as its often generated / provided to you + * by transaction simulation/preflight from a Soroban RPC server. + * + * @param {number} cpuInstrs number of CPU instructions + * @param {number} readBytes number of bytes being read + * @param {number} writeBytes number of bytes being written + * + * @returns {SorobanDataBuilder} + */ + }, { + key: "setResources", + value: function setResources(cpuInstrs, readBytes, writeBytes) { + this._data.resources().instructions(cpuInstrs); + this._data.resources().readBytes(readBytes); + this._data.resources().writeBytes(writeBytes); + return this; + } + + /** + * Appends the given ledger keys to the existing storage access footprint. + * @param {xdr.LedgerKey[]} readOnly read-only keys to add + * @param {xdr.LedgerKey[]} readWrite read-write keys to add + * @returns {SorobanDataBuilder} this builder instance + */ + }, { + key: "appendFootprint", + value: function appendFootprint(readOnly, readWrite) { + return this.setFootprint(this.getReadOnly().concat(readOnly), this.getReadWrite().concat(readWrite)); + } + + /** + * Sets the storage access footprint to be a certain set of ledger keys. + * + * You can also set each field explicitly via + * {@link SorobanDataBuilder.setReadOnly} and + * {@link SorobanDataBuilder.setReadWrite} or add to the existing footprint + * via {@link SorobanDataBuilder.appendFootprint}. + * + * Passing `null|undefined` to either parameter will IGNORE the existing + * values. If you want to clear them, pass `[]`, instead. + * + * @param {xdr.LedgerKey[]|null} [readOnly] the set of ledger keys to set in + * the read-only portion of the transaction's `sorobanData`, or `null | + * undefined` to keep the existing keys + * @param {xdr.LedgerKey[]|null} [readWrite] the set of ledger keys to set in + * the read-write portion of the transaction's `sorobanData`, or `null | + * undefined` to keep the existing keys + * @returns {SorobanDataBuilder} this builder instance + */ + }, { + key: "setFootprint", + value: function setFootprint(readOnly, readWrite) { + if (readOnly !== null) { + // null means "leave me alone" + this.setReadOnly(readOnly); + } + if (readWrite !== null) { + this.setReadWrite(readWrite); + } + return this; + } + + /** + * @param {xdr.LedgerKey[]} readOnly read-only keys in the access footprint + * @returns {SorobanDataBuilder} + */ + }, { + key: "setReadOnly", + value: function setReadOnly(readOnly) { + this._data.resources().footprint().readOnly(readOnly !== null && readOnly !== void 0 ? readOnly : []); + return this; + } + + /** + * @param {xdr.LedgerKey[]} readWrite read-write keys in the access footprint + * @returns {SorobanDataBuilder} + */ + }, { + key: "setReadWrite", + value: function setReadWrite(readWrite) { + this._data.resources().footprint().readWrite(readWrite !== null && readWrite !== void 0 ? readWrite : []); + return this; + } + + /** + * @returns {xdr.SorobanTransactionData} a copy of the final data structure + */ + }, { + key: "build", + value: function build() { + return _xdr["default"].SorobanTransactionData.fromXDR(this._data.toXDR()); // clone + } + + // + // getters follow + // + + /** @returns {xdr.LedgerKey[]} the read-only storage access pattern */ + }, { + key: "getReadOnly", + value: function getReadOnly() { + return this.getFootprint().readOnly(); + } + + /** @returns {xdr.LedgerKey[]} the read-write storage access pattern */ + }, { + key: "getReadWrite", + value: function getReadWrite() { + return this.getFootprint().readWrite(); + } + + /** @returns {xdr.LedgerFootprint} the storage access pattern */ + }, { + key: "getFootprint", + value: function getFootprint() { + return this._data.resources().footprint(); + } + }], [{ + key: "fromXDR", + value: function fromXDR(data) { + return _xdr["default"].SorobanTransactionData.fromXDR(data, typeof data === 'string' ? 'base64' : 'raw'); + } + }]); +}(); + +/***/ }), + +/***/ 7120: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.StrKey = void 0; +exports.decodeCheck = decodeCheck; +exports.encodeCheck = encodeCheck; +var _base = _interopRequireDefault(__webpack_require__(5360)); +var _checksum = __webpack_require__(1346); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": ["<<", ">>", "^", "&", "&="]}] */ +var versionBytes = { + ed25519PublicKey: 6 << 3, + // G (when encoded in base32) + ed25519SecretSeed: 18 << 3, + // S + med25519PublicKey: 12 << 3, + // M + preAuthTx: 19 << 3, + // T + sha256Hash: 23 << 3, + // X + signedPayload: 15 << 3, + // P + contract: 2 << 3 // C +}; +var strkeyTypes = { + G: 'ed25519PublicKey', + S: 'ed25519SecretSeed', + M: 'med25519PublicKey', + T: 'preAuthTx', + X: 'sha256Hash', + P: 'signedPayload', + C: 'contract' +}; + +/** + * StrKey is a helper class that allows encoding and decoding Stellar keys + * to/from strings, i.e. between their binary (Buffer, xdr.PublicKey, etc.) and + * string (i.e. "GABCD...", etc.) representations. + */ +var StrKey = exports.StrKey = /*#__PURE__*/function () { + function StrKey() { + _classCallCheck(this, StrKey); + } + return _createClass(StrKey, null, [{ + key: "encodeEd25519PublicKey", + value: + /** + * Encodes `data` to strkey ed25519 public key. + * + * @param {Buffer} data raw data to encode + * @returns {string} "G..." representation of the key + */ + function encodeEd25519PublicKey(data) { + return encodeCheck('ed25519PublicKey', data); + } + + /** + * Decodes strkey ed25519 public key to raw data. + * + * If the parameter is a muxed account key ("M..."), this will only encode it + * as a basic Ed25519 key (as if in "G..." format). + * + * @param {string} data "G..." (or "M...") key representation to decode + * @returns {Buffer} raw key + */ + }, { + key: "decodeEd25519PublicKey", + value: function decodeEd25519PublicKey(data) { + return decodeCheck('ed25519PublicKey', data); + } + + /** + * Returns true if the given Stellar public key is a valid ed25519 public key. + * @param {string} publicKey public key to check + * @returns {boolean} + */ + }, { + key: "isValidEd25519PublicKey", + value: function isValidEd25519PublicKey(publicKey) { + return isValid('ed25519PublicKey', publicKey); + } + + /** + * Encodes data to strkey ed25519 seed. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeEd25519SecretSeed", + value: function encodeEd25519SecretSeed(data) { + return encodeCheck('ed25519SecretSeed', data); + } + + /** + * Decodes strkey ed25519 seed to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeEd25519SecretSeed", + value: function decodeEd25519SecretSeed(address) { + return decodeCheck('ed25519SecretSeed', address); + } + + /** + * Returns true if the given Stellar secret key is a valid ed25519 secret seed. + * @param {string} seed seed to check + * @returns {boolean} + */ + }, { + key: "isValidEd25519SecretSeed", + value: function isValidEd25519SecretSeed(seed) { + return isValid('ed25519SecretSeed', seed); + } + + /** + * Encodes data to strkey med25519 public key. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeMed25519PublicKey", + value: function encodeMed25519PublicKey(data) { + return encodeCheck('med25519PublicKey', data); + } + + /** + * Decodes strkey med25519 public key to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeMed25519PublicKey", + value: function decodeMed25519PublicKey(address) { + return decodeCheck('med25519PublicKey', address); + } + + /** + * Returns true if the given Stellar public key is a valid med25519 public key. + * @param {string} publicKey public key to check + * @returns {boolean} + */ + }, { + key: "isValidMed25519PublicKey", + value: function isValidMed25519PublicKey(publicKey) { + return isValid('med25519PublicKey', publicKey); + } + + /** + * Encodes data to strkey preAuthTx. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodePreAuthTx", + value: function encodePreAuthTx(data) { + return encodeCheck('preAuthTx', data); + } + + /** + * Decodes strkey PreAuthTx to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodePreAuthTx", + value: function decodePreAuthTx(address) { + return decodeCheck('preAuthTx', address); + } + + /** + * Encodes data to strkey sha256 hash. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeSha256Hash", + value: function encodeSha256Hash(data) { + return encodeCheck('sha256Hash', data); + } + + /** + * Decodes strkey sha256 hash to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeSha256Hash", + value: function decodeSha256Hash(address) { + return decodeCheck('sha256Hash', address); + } + + /** + * Encodes raw data to strkey signed payload (P...). + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeSignedPayload", + value: function encodeSignedPayload(data) { + return encodeCheck('signedPayload', data); + } + + /** + * Decodes strkey signed payload (P...) to raw data. + * @param {string} address address to decode + * @returns {Buffer} + */ + }, { + key: "decodeSignedPayload", + value: function decodeSignedPayload(address) { + return decodeCheck('signedPayload', address); + } + + /** + * Checks validity of alleged signed payload (P...) strkey address. + * @param {string} address signer key to check + * @returns {boolean} + */ + }, { + key: "isValidSignedPayload", + value: function isValidSignedPayload(address) { + return isValid('signedPayload', address); + } + + /** + * Encodes raw data to strkey contract (C...). + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeContract", + value: function encodeContract(data) { + return encodeCheck('contract', data); + } + + /** + * Decodes strkey contract (C...) to raw data. + * @param {string} address address to decode + * @returns {Buffer} + */ + }, { + key: "decodeContract", + value: function decodeContract(address) { + return decodeCheck('contract', address); + } + + /** + * Checks validity of alleged contract (C...) strkey address. + * @param {string} address signer key to check + * @returns {boolean} + */ + }, { + key: "isValidContract", + value: function isValidContract(address) { + return isValid('contract', address); + } + }, { + key: "getVersionByteForPrefix", + value: function getVersionByteForPrefix(address) { + return strkeyTypes[address[0]]; + } + }]); +}(); +/** + * Sanity-checks whether or not a strkey *appears* valid. + * + * @param {string} versionByteName the type of strkey to expect in `encoded` + * @param {string} encoded the strkey to validate + * + * @return {Boolean} whether or not the `encoded` strkey appears valid for the + * `versionByteName` strkey type (see `versionBytes`, above). + * + * @note This isn't a *definitive* check of validity, but rather a best-effort + * check based on (a) input length, (b) whether or not it can be decoded, + * and (c) output length. + */ +function isValid(versionByteName, encoded) { + if (typeof encoded !== 'string') { + return false; + } + + // basic length checks on the strkey lengths + switch (versionByteName) { + case 'ed25519PublicKey': // falls through + case 'ed25519SecretSeed': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + case 'contract': + if (encoded.length !== 56) { + return false; + } + break; + case 'med25519PublicKey': + if (encoded.length !== 69) { + return false; + } + break; + case 'signedPayload': + if (encoded.length < 56 || encoded.length > 165) { + return false; + } + break; + default: + return false; + } + var decoded = ''; + try { + decoded = decodeCheck(versionByteName, encoded); + } catch (err) { + return false; + } + + // basic length checks on the resulting buffer sizes + switch (versionByteName) { + case 'ed25519PublicKey': // falls through + case 'ed25519SecretSeed': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + case 'contract': + return decoded.length === 32; + case 'med25519PublicKey': + return decoded.length === 40; + // +8 bytes for the ID + + case 'signedPayload': + return ( + // 32 for the signer, +4 for the payload size, then either +4 for the + // min or +64 for the max payload + decoded.length >= 32 + 4 + 4 && decoded.length <= 32 + 4 + 64 + ); + default: + return false; + } +} +function decodeCheck(versionByteName, encoded) { + if (typeof encoded !== 'string') { + throw new TypeError('encoded argument must be of type String'); + } + var decoded = _base["default"].decode(encoded); + var versionByte = decoded[0]; + var payload = decoded.slice(0, -2); + var data = payload.slice(1); + var checksum = decoded.slice(-2); + if (encoded !== _base["default"].encode(decoded)) { + throw new Error('invalid encoded string'); + } + var expectedVersion = versionBytes[versionByteName]; + if (expectedVersion === undefined) { + throw new Error("".concat(versionByteName, " is not a valid version byte name. ") + "Expected one of ".concat(Object.keys(versionBytes).join(', '))); + } + if (versionByte !== expectedVersion) { + throw new Error("invalid version byte. expected ".concat(expectedVersion, ", got ").concat(versionByte)); + } + var expectedChecksum = calculateChecksum(payload); + if (!(0, _checksum.verifyChecksum)(expectedChecksum, checksum)) { + throw new Error("invalid checksum"); + } + return Buffer.from(data); +} +function encodeCheck(versionByteName, data) { + if (data === null || data === undefined) { + throw new Error('cannot encode null data'); + } + var versionByte = versionBytes[versionByteName]; + if (versionByte === undefined) { + throw new Error("".concat(versionByteName, " is not a valid version byte name. ") + "Expected one of ".concat(Object.keys(versionBytes).join(', '))); + } + data = Buffer.from(data); + var versionBuffer = Buffer.from([versionByte]); + var payload = Buffer.concat([versionBuffer, data]); + var checksum = Buffer.from(calculateChecksum(payload)); + var unencoded = Buffer.concat([payload, checksum]); + return _base["default"].encode(unencoded); +} + +// Computes the CRC16-XModem checksum of `payload` in little-endian order +function calculateChecksum(payload) { + var crcTable = [0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0]; + var crc16 = 0x0; + for (var i = 0; i < payload.length; i += 1) { + var _byte = payload[i]; + var lookupIndex = crc16 >> 8 ^ _byte; + crc16 = crc16 << 8 ^ crcTable[lookupIndex]; + crc16 &= 0xffff; + } + var checksum = new Uint8Array(2); + checksum[0] = crc16 & 0xff; + checksum[1] = crc16 >> 8 & 0xff; + return checksum; +} + +/***/ }), + +/***/ 380: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Transaction = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _hashing = __webpack_require__(9152); +var _strkey = __webpack_require__(7120); +var _operation = __webpack_require__(7237); +var _memo = __webpack_require__(4172); +var _transaction_base = __webpack_require__(3758); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Use {@link TransactionBuilder} to build a transaction object. If you have an + * object or base64-encoded string of the transaction envelope XDR, use {@link + * TransactionBuilder.fromXDR}. + * + * Once a Transaction has been created, its attributes and operations should not + * be changed. You should only add signatures (using {@link Transaction#sign}) + * to a Transaction object before submitting to the network or forwarding on to + * additional signers. + * + * @constructor + * + * @param {string|xdr.TransactionEnvelope} envelope - transaction envelope + * object or base64 encoded string + * @param {string} [networkPassphrase] - passphrase of the target stellar + * network (e.g. "Public Global Stellar Network ; September 2015") + * + * @extends TransactionBase + */ +var Transaction = exports.Transaction = /*#__PURE__*/function (_TransactionBase) { + function Transaction(envelope, networkPassphrase) { + var _this; + _classCallCheck(this, Transaction); + if (typeof envelope === 'string') { + var buffer = Buffer.from(envelope, 'base64'); + envelope = _xdr["default"].TransactionEnvelope.fromXDR(buffer); + } + var envelopeType = envelope["switch"](); + if (!(envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTxV0() || envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTx())) { + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ".concat(envelopeType.name, ".")); + } + var txEnvelope = envelope.value(); + var tx = txEnvelope.tx(); + var fee = tx.fee().toString(); + var signatures = (txEnvelope.signatures() || []).slice(); + _this = _callSuper(this, Transaction, [tx, signatures, fee, networkPassphrase]); + _this._envelopeType = envelopeType; + _this._memo = tx.memo(); + _this._sequence = tx.seqNum().toString(); + switch (_this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + _this._source = _strkey.StrKey.encodeEd25519PublicKey(_this.tx.sourceAccountEd25519()); + break; + default: + _this._source = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(_this.tx.sourceAccount()); + break; + } + var cond = null; + var timeBounds = null; + switch (_this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + timeBounds = tx.timeBounds(); + break; + case _xdr["default"].EnvelopeType.envelopeTypeTx(): + switch (tx.cond()["switch"]()) { + case _xdr["default"].PreconditionType.precondTime(): + timeBounds = tx.cond().timeBounds(); + break; + case _xdr["default"].PreconditionType.precondV2(): + cond = tx.cond().v2(); + timeBounds = cond.timeBounds(); + break; + default: + break; + } + break; + default: + break; + } + if (timeBounds) { + _this._timeBounds = { + minTime: timeBounds.minTime().toString(), + maxTime: timeBounds.maxTime().toString() + }; + } + if (cond) { + var ledgerBounds = cond.ledgerBounds(); + if (ledgerBounds) { + _this._ledgerBounds = { + minLedger: ledgerBounds.minLedger(), + maxLedger: ledgerBounds.maxLedger() + }; + } + var minSeq = cond.minSeqNum(); + if (minSeq) { + _this._minAccountSequence = minSeq.toString(); + } + _this._minAccountSequenceAge = cond.minSeqAge(); + _this._minAccountSequenceLedgerGap = cond.minSeqLedgerGap(); + _this._extraSigners = cond.extraSigners(); + } + var operations = tx.operations() || []; + _this._operations = operations.map(function (op) { + return _operation.Operation.fromXDRObject(op); + }); + return _this; + } + + /** + * @type {object} + * @property {string} 64 bit unix timestamp + * @property {string} 64 bit unix timestamp + * @readonly + */ + _inherits(Transaction, _TransactionBase); + return _createClass(Transaction, [{ + key: "timeBounds", + get: function get() { + return this._timeBounds; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {object} + * @property {number} minLedger - smallest ledger bound (uint32) + * @property {number} maxLedger - largest ledger bound (or 0 for inf) + * @readonly + */ + }, { + key: "ledgerBounds", + get: function get() { + return this._ledgerBounds; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 64 bit account sequence + * @readonly + * @type {string} + */ + }, { + key: "minAccountSequence", + get: function get() { + return this._minAccountSequence; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 64 bit number of seconds + * @type {number} + * @readonly + */ + }, { + key: "minAccountSequenceAge", + get: function get() { + return this._minAccountSequenceAge; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 32 bit number of ledgers + * @type {number} + * @readonly + */ + }, { + key: "minAccountSequenceLedgerGap", + get: function get() { + return this._minAccountSequenceLedgerGap; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * array of extra signers ({@link StrKey}s) + * @type {string[]} + * @readonly + */ + }, { + key: "extraSigners", + get: function get() { + return this._extraSigners; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "sequence", + get: function get() { + return this._sequence; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "source", + get: function get() { + return this._source; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {Array.} + * @readonly + */ + }, { + key: "operations", + get: function get() { + return this._operations; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "memo", + get: function get() { + return _memo.Memo.fromXDRObject(this._memo); + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * Returns the "signature base" of this transaction, which is the value + * that, when hashed, should be signed to create a signature that + * validators on the Stellar Network will accept. + * + * It is composed of a 4 prefix bytes followed by the xdr-encoded form + * of this transaction. + * @returns {Buffer} + */ + }, { + key: "signatureBase", + value: function signatureBase() { + var tx = this.tx; + + // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // we need a Transaction to generate the signature base + if (this._envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTxV0()) { + tx = _xdr["default"].Transaction.fromXDR(Buffer.concat([ + // TransactionV0 is a transaction with the AccountID discriminant + // stripped off, we need to put it back to build a valid transaction + // which we can use to build a TransactionSignaturePayloadTaggedTransaction + _xdr["default"].PublicKeyType.publicKeyTypeEd25519().toXDR(), tx.toXDR()])); + } + var taggedTransaction = new _xdr["default"].TransactionSignaturePayloadTaggedTransaction.envelopeTypeTx(tx); + var txSignature = new _xdr["default"].TransactionSignaturePayload({ + networkId: _xdr["default"].Hash.fromXDR((0, _hashing.hash)(this.networkPassphrase)), + taggedTransaction: taggedTransaction + }); + return txSignature.toXDR(); + } + + /** + * To envelope returns a xdr.TransactionEnvelope which can be submitted to the network. + * @returns {xdr.TransactionEnvelope} + */ + }, { + key: "toEnvelope", + value: function toEnvelope() { + var rawTx = this.tx.toXDR(); + var signatures = this.signatures.slice(); // make a copy of the signatures + + var envelope; + switch (this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTxV0(new _xdr["default"].TransactionV0Envelope({ + tx: _xdr["default"].TransactionV0.fromXDR(rawTx), + // make a copy of tx + signatures: signatures + })); + break; + case _xdr["default"].EnvelopeType.envelopeTypeTx(): + envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: _xdr["default"].Transaction.fromXDR(rawTx), + // make a copy of tx + signatures: signatures + })); + break; + default: + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ".concat(this._envelopeType.name, ".")); + } + return envelope; + } + + /** + * Calculate the claimable balance ID for an operation within the transaction. + * + * @param {integer} opIndex the index of the CreateClaimableBalance op + * @returns {string} a hex string representing the claimable balance ID + * + * @throws {RangeError} for invalid `opIndex` value + * @throws {TypeError} if op at `opIndex` is not `CreateClaimableBalance` + * @throws for general XDR un/marshalling failures + * + * @see https://github.com/stellar/go/blob/d712346e61e288d450b0c08038c158f8848cc3e4/txnbuild/transaction.go#L392-L435 + * + */ + }, { + key: "getClaimableBalanceId", + value: function getClaimableBalanceId(opIndex) { + // Validate and then extract the operation from the transaction. + if (!Number.isInteger(opIndex) || opIndex < 0 || opIndex >= this.operations.length) { + throw new RangeError('invalid operation index'); + } + var op = this.operations[opIndex]; + try { + op = _operation.Operation.createClaimableBalance(op); + } catch (err) { + throw new TypeError("expected createClaimableBalance, got ".concat(op.type, ": ").concat(err)); + } + + // Always use the transaction's *unmuxed* source. + var account = _strkey.StrKey.decodeEd25519PublicKey((0, _decode_encode_muxed_account.extractBaseAddress)(this.source)); + var operationId = _xdr["default"].HashIdPreimage.envelopeTypeOpId(new _xdr["default"].HashIdPreimageOperationId({ + sourceAccount: _xdr["default"].AccountId.publicKeyTypeEd25519(account), + seqNum: _xdr["default"].SequenceNumber.fromString(this.sequence), + opNum: opIndex + })); + var opIdHash = (0, _hashing.hash)(operationId.toXDR('raw')); + var balanceId = _xdr["default"].ClaimableBalanceId.claimableBalanceIdTypeV0(opIdHash); + return balanceId.toXDR('hex'); + } + }]); +}(_transaction_base.TransactionBase); + +/***/ }), + +/***/ 3758: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.TransactionBase = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _hashing = __webpack_require__(9152); +var _keypair = __webpack_require__(6691); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * @ignore + */ +var TransactionBase = exports.TransactionBase = /*#__PURE__*/function () { + function TransactionBase(tx, signatures, fee, networkPassphrase) { + _classCallCheck(this, TransactionBase); + if (typeof networkPassphrase !== 'string') { + throw new Error("Invalid passphrase provided to Transaction: expected a string but got a ".concat(_typeof(networkPassphrase))); + } + this._networkPassphrase = networkPassphrase; + this._tx = tx; + this._signatures = signatures; + this._fee = fee; + } + + /** + * @type {Array.} + * @readonly + */ + return _createClass(TransactionBase, [{ + key: "signatures", + get: function get() { + return this._signatures; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + }, { + key: "tx", + get: function get() { + return this._tx; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "fee", + get: function get() { + return this._fee; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "networkPassphrase", + get: function get() { + return this._networkPassphrase; + }, + set: function set(networkPassphrase) { + this._networkPassphrase = networkPassphrase; + } + + /** + * Signs the transaction with the given {@link Keypair}. + * @param {...Keypair} keypairs Keypairs of signers + * @returns {void} + */ + }, { + key: "sign", + value: function sign() { + var _this = this; + var txHash = this.hash(); + for (var _len = arguments.length, keypairs = new Array(_len), _key = 0; _key < _len; _key++) { + keypairs[_key] = arguments[_key]; + } + keypairs.forEach(function (kp) { + var sig = kp.signDecorated(txHash); + _this.signatures.push(sig); + }); + } + + /** + * Signs a transaction with the given {@link Keypair}. Useful if someone sends + * you a transaction XDR for you to sign and return (see + * [addSignature](#addSignature) for more information). + * + * When you get a transaction XDR to sign.... + * - Instantiate a `Transaction` object with the XDR + * - Use {@link Keypair} to generate a keypair object for your Stellar seed. + * - Run `getKeypairSignature` with that keypair + * - Send back the signature along with your publicKey (not your secret seed!) + * + * Example: + * ```javascript + * // `transactionXDR` is a string from the person generating the transaction + * const transaction = new Transaction(transactionXDR, networkPassphrase); + * const keypair = Keypair.fromSecret(myStellarSeed); + * return transaction.getKeypairSignature(keypair); + * ``` + * + * @param {Keypair} keypair Keypair of signer + * @returns {string} Signature string + */ + }, { + key: "getKeypairSignature", + value: function getKeypairSignature(keypair) { + return keypair.sign(this.hash()).toString('base64'); + } + + /** + * Add a signature to the transaction. Useful when a party wants to pre-sign + * a transaction but doesn't want to give access to their secret keys. + * This will also verify whether the signature is valid. + * + * Here's how you would use this feature to solicit multiple signatures. + * - Use `TransactionBuilder` to build a new transaction. + * - Make sure to set a long enough timeout on that transaction to give your + * signers enough time to sign! + * - Once you build the transaction, use `transaction.toXDR()` to get the + * base64-encoded XDR string. + * - _Warning!_ Once you've built this transaction, don't submit any other + * transactions onto your account! Doing so will invalidate this pre-compiled + * transaction! + * - Send this XDR string to your other parties. They can use the instructions + * for [getKeypairSignature](#getKeypairSignature) to sign the transaction. + * - They should send you back their `publicKey` and the `signature` string + * from [getKeypairSignature](#getKeypairSignature), both of which you pass to + * this function. + * + * @param {string} publicKey The public key of the signer + * @param {string} signature The base64 value of the signature XDR + * @returns {void} + */ + }, { + key: "addSignature", + value: function addSignature() { + var publicKey = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var signature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + if (!signature || typeof signature !== 'string') { + throw new Error('Invalid signature'); + } + if (!publicKey || typeof publicKey !== 'string') { + throw new Error('Invalid publicKey'); + } + var keypair; + var hint; + var signatureBuffer = Buffer.from(signature, 'base64'); + try { + keypair = _keypair.Keypair.fromPublicKey(publicKey); + hint = keypair.signatureHint(); + } catch (e) { + throw new Error('Invalid publicKey'); + } + if (!keypair.verify(this.hash(), signatureBuffer)) { + throw new Error('Invalid signature'); + } + this.signatures.push(new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signatureBuffer + })); + } + + /** + * Add a decorated signature directly to the transaction envelope. + * + * @param {xdr.DecoratedSignature} signature raw signature to add + * @returns {void} + * + * @see Keypair.signDecorated + * @see Keypair.signPayloadDecorated + */ + }, { + key: "addDecoratedSignature", + value: function addDecoratedSignature(signature) { + this.signatures.push(signature); + } + + /** + * Add `hashX` signer preimage as signature. + * @param {Buffer|String} preimage Preimage of hash used as signer + * @returns {void} + */ + }, { + key: "signHashX", + value: function signHashX(preimage) { + if (typeof preimage === 'string') { + preimage = Buffer.from(preimage, 'hex'); + } + if (preimage.length > 64) { + throw new Error('preimage cannnot be longer than 64 bytes'); + } + var signature = preimage; + var hashX = (0, _hashing.hash)(preimage); + var hint = hashX.slice(hashX.length - 4); + this.signatures.push(new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signature + })); + } + + /** + * Returns a hash for this transaction, suitable for signing. + * @returns {Buffer} + */ + }, { + key: "hash", + value: function hash() { + return (0, _hashing.hash)(this.signatureBase()); + } + }, { + key: "signatureBase", + value: function signatureBase() { + throw new Error('Implement in subclass'); + } + }, { + key: "toEnvelope", + value: function toEnvelope() { + throw new Error('Implement in subclass'); + } + + /** + * Get the transaction envelope as a base64-encoded string + * @returns {string} XDR string + */ + }, { + key: "toXDR", + value: function toXDR() { + return this.toEnvelope().toXDR().toString('base64'); + } + }]); +}(); + +/***/ }), + +/***/ 6396: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.TransactionBuilder = exports.TimeoutInfinite = exports.BASE_FEE = void 0; +exports.isValidDate = isValidDate; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _account = __webpack_require__(2135); +var _muxed_account = __webpack_require__(2243); +var _decode_encode_muxed_account = __webpack_require__(6160); +var _transaction = __webpack_require__(380); +var _fee_bump_transaction = __webpack_require__(9260); +var _sorobandata_builder = __webpack_require__(4842); +var _strkey = __webpack_require__(7120); +var _signerkey = __webpack_require__(225); +var _memo = __webpack_require__(4172); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Minimum base fee for transactions. If this fee is below the network + * minimum, the transaction will fail. The more operations in the + * transaction, the greater the required fee. Use {@link + * Server#fetchBaseFee} to get an accurate value of minimum transaction + * fee on the network. + * + * @constant + * @see [Fees](https://developers.stellar.org/docs/glossary/fees/) + */ +var BASE_FEE = exports.BASE_FEE = '100'; // Stroops + +/** + * @constant + * @see {@link TransactionBuilder#setTimeout} + * @see [Timeout](https://developers.stellar.org/api/resources/transactions/post/) + */ +var TimeoutInfinite = exports.TimeoutInfinite = 0; + +/** + *

Transaction builder helps constructs a new `{@link Transaction}` using the + * given {@link Account} as the transaction's "source account". The transaction + * will use the current sequence number of the given account as its sequence + * number and increment the given account's sequence number by one. The given + * source account must include a private key for signing the transaction or an + * error will be thrown.

+ * + *

Operations can be added to the transaction via their corresponding builder + * methods, and each returns the TransactionBuilder object so they can be + * chained together. After adding the desired operations, call the `build()` + * method on the `TransactionBuilder` to return a fully constructed `{@link + * Transaction}` that can be signed. The returned transaction will contain the + * sequence number of the source account and include the signature from the + * source account.

+ * + *

Be careful about unsubmitted transactions! When you build + * a transaction, `stellar-sdk` automatically increments the source account's + * sequence number. If you end up not submitting this transaction and submitting + * another one instead, it'll fail due to the sequence number being wrong. So if + * you decide not to use a built transaction, make sure to update the source + * account's sequence number with + * [Server.loadAccount](https://stellar.github.io/js-stellar-sdk/Server.html#loadAccount) + * before creating another transaction.

+ * + *

The following code example creates a new transaction with {@link + * Operation.createAccount} and {@link Operation.payment} operations. The + * Transaction's source account first funds `destinationA`, then sends a payment + * to `destinationB`. The built transaction is then signed by + * `sourceKeypair`.

+ * + * ``` + * var transaction = new TransactionBuilder(source, { fee, networkPassphrase: Networks.TESTNET }) + * .addOperation(Operation.createAccount({ + * destination: destinationA, + * startingBalance: "20" + * })) // <- funds and creates destinationA + * .addOperation(Operation.payment({ + * destination: destinationB, + * amount: "100", + * asset: Asset.native() + * })) // <- sends 100 XLM to destinationB + * .setTimeout(30) + * .build(); + * + * transaction.sign(sourceKeypair); + * ``` + * + * @constructor + * + * @param {Account} sourceAccount - source account for this transaction + * @param {object} opts - Options object + * @param {string} opts.fee - max fee you're willing to pay per + * operation in this transaction (**in stroops**) + * + * @param {object} [opts.timebounds] - timebounds for the + * validity of this transaction + * @param {number|string|Date} [opts.timebounds.minTime] - 64-bit UNIX + * timestamp or Date object + * @param {number|string|Date} [opts.timebounds.maxTime] - 64-bit UNIX + * timestamp or Date object + * @param {object} [opts.ledgerbounds] - ledger bounds for the + * validity of this transaction + * @param {number} [opts.ledgerbounds.minLedger] - number of the minimum + * ledger sequence + * @param {number} [opts.ledgerbounds.maxLedger] - number of the maximum + * ledger sequence + * @param {string} [opts.minAccountSequence] - number for + * the minimum account sequence + * @param {number} [opts.minAccountSequenceAge] - number of + * seconds for the minimum account sequence age + * @param {number} [opts.minAccountSequenceLedgerGap] - number of + * ledgers for the minimum account sequence ledger gap + * @param {string[]} [opts.extraSigners] - list of the extra signers + * required for this transaction + * @param {Memo} [opts.memo] - memo for the transaction + * @param {string} [opts.networkPassphrase] passphrase of the + * target Stellar network (e.g. "Public Global Stellar Network ; September + * 2015" for the pubnet) + * @param {xdr.SorobanTransactionData | string} [opts.sorobanData] - an + * optional instance of {@link xdr.SorobanTransactionData} to be set as the + * internal `Transaction.Ext.SorobanData` field (either the xdr object or a + * base64 string). In the case of Soroban transactions, this can be obtained + * from a prior simulation of the transaction with a contract invocation and + * provides necessary resource estimations. You can also use + * {@link SorobanDataBuilder} to construct complicated combinations of + * parameters without mucking with XDR directly. **Note:** For + * non-contract(non-Soroban) transactions, this has no effect. + */ +var TransactionBuilder = exports.TransactionBuilder = /*#__PURE__*/function () { + function TransactionBuilder(sourceAccount) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, TransactionBuilder); + if (!sourceAccount) { + throw new Error('must specify source account for the transaction'); + } + if (opts.fee === undefined) { + throw new Error('must specify fee for the transaction (in stroops)'); + } + this.source = sourceAccount; + this.operations = []; + this.baseFee = opts.fee; + this.timebounds = opts.timebounds ? _objectSpread({}, opts.timebounds) : null; + this.ledgerbounds = opts.ledgerbounds ? _objectSpread({}, opts.ledgerbounds) : null; + this.minAccountSequence = opts.minAccountSequence || null; + this.minAccountSequenceAge = opts.minAccountSequenceAge || null; + this.minAccountSequenceLedgerGap = opts.minAccountSequenceLedgerGap || null; + this.extraSigners = opts.extraSigners ? _toConsumableArray(opts.extraSigners) : null; + this.memo = opts.memo || _memo.Memo.none(); + this.networkPassphrase = opts.networkPassphrase || null; + this.sorobanData = opts.sorobanData ? new _sorobandata_builder.SorobanDataBuilder(opts.sorobanData).build() : null; + } + + /** + * Creates a builder instance using an existing {@link Transaction} as a + * template, ignoring any existing envelope signatures. + * + * Note that the sequence number WILL be cloned, so EITHER this transaction or + * the one it was cloned from will be valid. This is useful in situations + * where you are constructing a transaction in pieces and need to make + * adjustments as you go (for example, when filling out Soroban resource + * information). + * + * @param {Transaction} tx a "template" transaction to clone exactly + * @param {object} [opts] additional options to override the clone, e.g. + * {fee: '1000'} will override the existing base fee derived from `tx` (see + * the {@link TransactionBuilder} constructor for detailed options) + * + * @returns {TransactionBuilder} a "prepared" builder instance with the same + * configuration and operations as the given transaction + * + * @warning This does not clone the transaction's + * {@link xdr.SorobanTransactionData} (if applicable), use + * {@link SorobanDataBuilder} and {@link TransactionBuilder.setSorobanData} + * as needed, instead.. + * + * @todo This cannot clone {@link FeeBumpTransaction}s, yet. + */ + return _createClass(TransactionBuilder, [{ + key: "addOperation", + value: + /** + * Adds an operation to the transaction. + * + * @param {xdr.Operation} operation The xdr operation object, use {@link + * Operation} static methods. + * + * @returns {TransactionBuilder} + */ + function addOperation(operation) { + this.operations.push(operation); + return this; + } + + /** + * Adds an operation to the transaction at a specific index. + * + * @param {xdr.Operation} operation - The xdr operation object to add, use {@link Operation} static methods. + * @param {number} index - The index at which to insert the operation. + * + * @returns {TransactionBuilder} - The TransactionBuilder instance for method chaining. + */ + }, { + key: "addOperationAt", + value: function addOperationAt(operation, index) { + this.operations.splice(index, 0, operation); + return this; + } + + /** + * Removes the operations from the builder (useful when cloning). + * @returns {TransactionBuilder} this builder instance + */ + }, { + key: "clearOperations", + value: function clearOperations() { + this.operations = []; + return this; + } + + /** + * Removes the operation at the specified index from the transaction. + * + * @param {number} index - The index of the operation to remove. + * + * @returns {TransactionBuilder} The TransactionBuilder instance for method chaining. + */ + }, { + key: "clearOperationAt", + value: function clearOperationAt(index) { + this.operations.splice(index, 1); + return this; + } + + /** + * Adds a memo to the transaction. + * @param {Memo} memo {@link Memo} object + * @returns {TransactionBuilder} + */ + }, { + key: "addMemo", + value: function addMemo(memo) { + this.memo = memo; + return this; + } + + /** + * Sets a timeout precondition on the transaction. + * + * Because of the distributed nature of the Stellar network it is possible + * that the status of your transaction will be determined after a long time + * if the network is highly congested. If you want to be sure to receive the + * status of the transaction within a given period you should set the {@link + * TimeBounds} with `maxTime` on the transaction (this is what `setTimeout` + * does internally; if there's `minTime` set but no `maxTime` it will be + * added). + * + * A call to `TransactionBuilder.setTimeout` is **required** if Transaction + * does not have `max_time` set. If you don't want to set timeout, use + * `{@link TimeoutInfinite}`. In general you should set `{@link + * TimeoutInfinite}` only in smart contracts. + * + * Please note that Horizon may still return 504 Gateway Timeout + * error, even for short timeouts. In such case you need to resubmit the same + * transaction again without making any changes to receive a status. This + * method is using the machine system time (UTC), make sure it is set + * correctly. + * + * @param {number} timeoutSeconds Number of seconds the transaction is good. + * Can't be negative. If the value is {@link TimeoutInfinite}, the + * transaction is good indefinitely. + * + * @returns {TransactionBuilder} + * + * @see {@link TimeoutInfinite} + * @see https://developers.stellar.org/docs/tutorials/handling-errors/ + */ + }, { + key: "setTimeout", + value: function setTimeout(timeoutSeconds) { + if (this.timebounds !== null && this.timebounds.maxTime > 0) { + throw new Error('TimeBounds.max_time has been already set - setting timeout would overwrite it.'); + } + if (timeoutSeconds < 0) { + throw new Error('timeout cannot be negative'); + } + if (timeoutSeconds > 0) { + var timeoutTimestamp = Math.floor(Date.now() / 1000) + timeoutSeconds; + if (this.timebounds === null) { + this.timebounds = { + minTime: 0, + maxTime: timeoutTimestamp + }; + } else { + this.timebounds = { + minTime: this.timebounds.minTime, + maxTime: timeoutTimestamp + }; + } + } else { + this.timebounds = { + minTime: 0, + maxTime: 0 + }; + } + return this; + } + + /** + * If you want to prepare a transaction which will become valid at some point + * in the future, or be invalid after some time, you can set a timebounds + * precondition. Internally this will set the `minTime`, and `maxTime` + * preconditions. Conflicts with `setTimeout`, so use one or the other. + * + * @param {Date|number} minEpochOrDate Either a JS Date object, or a number + * of UNIX epoch seconds. The transaction is valid after this timestamp. + * Can't be negative. If the value is `0`, the transaction is valid + * immediately. + * @param {Date|number} maxEpochOrDate Either a JS Date object, or a number + * of UNIX epoch seconds. The transaction is valid until this timestamp. + * Can't be negative. If the value is `0`, the transaction is valid + * indefinitely. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setTimebounds", + value: function setTimebounds(minEpochOrDate, maxEpochOrDate) { + // Force it to a date type + if (typeof minEpochOrDate === 'number') { + minEpochOrDate = new Date(minEpochOrDate * 1000); + } + if (typeof maxEpochOrDate === 'number') { + maxEpochOrDate = new Date(maxEpochOrDate * 1000); + } + if (this.timebounds !== null) { + throw new Error('TimeBounds has been already set - setting timebounds would overwrite it.'); + } + + // Convert that date to the epoch seconds + var minTime = Math.floor(minEpochOrDate.valueOf() / 1000); + var maxTime = Math.floor(maxEpochOrDate.valueOf() / 1000); + if (minTime < 0) { + throw new Error('min_time cannot be negative'); + } + if (maxTime < 0) { + throw new Error('max_time cannot be negative'); + } + if (maxTime > 0 && minTime > maxTime) { + throw new Error('min_time cannot be greater than max_time'); + } + this.timebounds = { + minTime: minTime, + maxTime: maxTime + }; + return this; + } + + /** + * If you want to prepare a transaction which will only be valid within some + * range of ledgers, you can set a ledgerbounds precondition. + * Internally this will set the `minLedger` and `maxLedger` preconditions. + * + * @param {number} minLedger The minimum ledger this transaction is valid at + * or after. Cannot be negative. If the value is `0` (the default), the + * transaction is valid immediately. + * + * @param {number} maxLedger The maximum ledger this transaction is valid + * before. Cannot be negative. If the value is `0`, the transaction is + * valid indefinitely. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setLedgerbounds", + value: function setLedgerbounds(minLedger, maxLedger) { + if (this.ledgerbounds !== null) { + throw new Error('LedgerBounds has been already set - setting ledgerbounds would overwrite it.'); + } + if (minLedger < 0) { + throw new Error('min_ledger cannot be negative'); + } + if (maxLedger < 0) { + throw new Error('max_ledger cannot be negative'); + } + if (maxLedger > 0 && minLedger > maxLedger) { + throw new Error('min_ledger cannot be greater than max_ledger'); + } + this.ledgerbounds = { + minLedger: minLedger, + maxLedger: maxLedger + }; + return this; + } + + /** + * If you want to prepare a transaction which will be valid only while the + * account sequence number is + * + * minAccountSequence <= sourceAccountSequence < tx.seqNum + * + * Note that after execution the account's sequence number is always raised to + * `tx.seqNum`. Internally this will set the `minAccountSequence` + * precondition. + * + * @param {string} minAccountSequence The minimum source account sequence + * number this transaction is valid for. If the value is `0` (the + * default), the transaction is valid when `sourceAccount's sequence + * number == tx.seqNum- 1`. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequence", + value: function setMinAccountSequence(minAccountSequence) { + if (this.minAccountSequence !== null) { + throw new Error('min_account_sequence has been already set - setting min_account_sequence would overwrite it.'); + } + this.minAccountSequence = minAccountSequence; + return this; + } + + /** + * For the transaction to be valid, the current ledger time must be at least + * `minAccountSequenceAge` greater than sourceAccount's `sequenceTime`. + * Internally this will set the `minAccountSequenceAge` precondition. + * + * @param {number} durationInSeconds The minimum amount of time between + * source account sequence time and the ledger time when this transaction + * will become valid. If the value is `0`, the transaction is unrestricted + * by the account sequence age. Cannot be negative. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequenceAge", + value: function setMinAccountSequenceAge(durationInSeconds) { + if (typeof durationInSeconds !== 'number') { + throw new Error('min_account_sequence_age must be a number'); + } + if (this.minAccountSequenceAge !== null) { + throw new Error('min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.'); + } + if (durationInSeconds < 0) { + throw new Error('min_account_sequence_age cannot be negative'); + } + this.minAccountSequenceAge = durationInSeconds; + return this; + } + + /** + * For the transaction to be valid, the current ledger number must be at least + * `minAccountSequenceLedgerGap` greater than sourceAccount's ledger sequence. + * Internally this will set the `minAccountSequenceLedgerGap` precondition. + * + * @param {number} gap The minimum number of ledgers between source account + * sequence and the ledger number when this transaction will become valid. + * If the value is `0`, the transaction is unrestricted by the account + * sequence ledger. Cannot be negative. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequenceLedgerGap", + value: function setMinAccountSequenceLedgerGap(gap) { + if (this.minAccountSequenceLedgerGap !== null) { + throw new Error('min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.'); + } + if (gap < 0) { + throw new Error('min_account_sequence_ledger_gap cannot be negative'); + } + this.minAccountSequenceLedgerGap = gap; + return this; + } + + /** + * For the transaction to be valid, there must be a signature corresponding to + * every Signer in this array, even if the signature is not otherwise required + * by the sourceAccount or operations. Internally this will set the + * `extraSigners` precondition. + * + * @param {string[]} extraSigners required extra signers (as {@link StrKey}s) + * + * @returns {TransactionBuilder} + */ + }, { + key: "setExtraSigners", + value: function setExtraSigners(extraSigners) { + if (!Array.isArray(extraSigners)) { + throw new Error('extra_signers must be an array of strings.'); + } + if (this.extraSigners !== null) { + throw new Error('extra_signers has been already set - setting extra_signers would overwrite it.'); + } + if (extraSigners.length > 2) { + throw new Error('extra_signers cannot be longer than 2 elements.'); + } + this.extraSigners = _toConsumableArray(extraSigners); + return this; + } + + /** + * Set network nassphrase for the Transaction that will be built. + * + * @param {string} networkPassphrase passphrase of the target Stellar + * network (e.g. "Public Global Stellar Network ; September 2015"). + * + * @returns {TransactionBuilder} + */ + }, { + key: "setNetworkPassphrase", + value: function setNetworkPassphrase(networkPassphrase) { + this.networkPassphrase = networkPassphrase; + return this; + } + + /** + * Sets the transaction's internal Soroban transaction data (resources, + * footprint, etc.). + * + * For non-contract(non-Soroban) transactions, this setting has no effect. In + * the case of Soroban transactions, this is either an instance of + * {@link xdr.SorobanTransactionData} or a base64-encoded string of said + * structure. This is usually obtained from the simulation response based on a + * transaction with a Soroban operation (e.g. + * {@link Operation.invokeHostFunction}, providing necessary resource + * and storage footprint estimations for contract invocation. + * + * @param {xdr.SorobanTransactionData | string} sorobanData the + * {@link xdr.SorobanTransactionData} as a raw xdr object or a base64 + * string to be decoded + * + * @returns {TransactionBuilder} + * @see {SorobanDataBuilder} + */ + }, { + key: "setSorobanData", + value: function setSorobanData(sorobanData) { + this.sorobanData = new _sorobandata_builder.SorobanDataBuilder(sorobanData).build(); + return this; + } + + /** + * This will build the transaction. + * It will also increment the source account's sequence number by 1. + * @returns {Transaction} This method will return the built {@link Transaction}. + */ + }, { + key: "build", + value: function build() { + var sequenceNumber = new _bignumber["default"](this.source.sequenceNumber()).plus(1); + var fee = new _bignumber["default"](this.baseFee).times(this.operations.length).toNumber(); + var attrs = { + fee: fee, + seqNum: _xdr["default"].SequenceNumber.fromString(sequenceNumber.toString()), + memo: this.memo ? this.memo.toXDRObject() : null + }; + if (this.timebounds === null || typeof this.timebounds.minTime === 'undefined' || typeof this.timebounds.maxTime === 'undefined') { + throw new Error('TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).'); + } + if (isValidDate(this.timebounds.minTime)) { + this.timebounds.minTime = this.timebounds.minTime.getTime() / 1000; + } + if (isValidDate(this.timebounds.maxTime)) { + this.timebounds.maxTime = this.timebounds.maxTime.getTime() / 1000; + } + this.timebounds.minTime = _jsXdr.UnsignedHyper.fromString(this.timebounds.minTime.toString()); + this.timebounds.maxTime = _jsXdr.UnsignedHyper.fromString(this.timebounds.maxTime.toString()); + var timeBounds = new _xdr["default"].TimeBounds(this.timebounds); + if (this.hasV2Preconditions()) { + var ledgerBounds = null; + if (this.ledgerbounds !== null) { + ledgerBounds = new _xdr["default"].LedgerBounds(this.ledgerbounds); + } + var minSeqNum = this.minAccountSequence || '0'; + minSeqNum = _xdr["default"].SequenceNumber.fromString(minSeqNum); + var minSeqAge = _jsXdr.UnsignedHyper.fromString(this.minAccountSequenceAge !== null ? this.minAccountSequenceAge.toString() : '0'); + var minSeqLedgerGap = this.minAccountSequenceLedgerGap || 0; + var extraSigners = this.extraSigners !== null ? this.extraSigners.map(_signerkey.SignerKey.decodeAddress) : []; + attrs.cond = _xdr["default"].Preconditions.precondV2(new _xdr["default"].PreconditionsV2({ + timeBounds: timeBounds, + ledgerBounds: ledgerBounds, + minSeqNum: minSeqNum, + minSeqAge: minSeqAge, + minSeqLedgerGap: minSeqLedgerGap, + extraSigners: extraSigners + })); + } else { + attrs.cond = _xdr["default"].Preconditions.precondTime(timeBounds); + } + attrs.sourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(this.source.accountId()); + + // TODO - remove this workaround for TransactionExt ts constructor + // and use the typescript generated static factory method once fixed + // https://github.com/stellar/dts-xdr/issues/5 + if (this.sorobanData) { + // @ts-ignore + attrs.ext = new _xdr["default"].TransactionExt(1, this.sorobanData); + } else { + // @ts-ignore + attrs.ext = new _xdr["default"].TransactionExt(0, _xdr["default"].Void); + } + var xtx = new _xdr["default"].Transaction(attrs); + xtx.operations(this.operations); + var txEnvelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: xtx + })); + var tx = new _transaction.Transaction(txEnvelope, this.networkPassphrase); + this.source.incrementSequenceNumber(); + return tx; + } + }, { + key: "hasV2Preconditions", + value: function hasV2Preconditions() { + return this.ledgerbounds !== null || this.minAccountSequence !== null || this.minAccountSequenceAge !== null || this.minAccountSequenceLedgerGap !== null || this.extraSigners !== null && this.extraSigners.length > 0; + } + + /** + * Builds a {@link FeeBumpTransaction}, enabling you to resubmit an existing + * transaction with a higher fee. + * + * @param {Keypair|string} feeSource - account paying for the transaction, + * in the form of either a Keypair (only the public key is used) or + * an account ID (in G... or M... form, but refer to `withMuxing`) + * @param {string} baseFee - max fee willing to pay per operation + * in inner transaction (**in stroops**) + * @param {Transaction} innerTx - {@link Transaction} to be bumped by + * the fee bump transaction + * @param {string} networkPassphrase - passphrase of the target + * Stellar network (e.g. "Public Global Stellar Network ; September 2015", + * see {@link Networks}) + * + * @todo Alongside the next major version bump, this type signature can be + * changed to be less awkward: accept a MuxedAccount as the `feeSource` + * rather than a keypair or string. + * + * @note Your fee-bump amount should be >= 10x the original fee. + * @see https://developers.stellar.org/docs/glossary/fee-bumps/#replace-by-fee + * + * @returns {FeeBumpTransaction} + */ + }], [{ + key: "cloneFrom", + value: function cloneFrom(tx) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (!(tx instanceof _transaction.Transaction)) { + throw new TypeError("expected a 'Transaction', got: ".concat(tx)); + } + var sequenceNum = (BigInt(tx.sequence) - 1n).toString(); + var source; + // rebuild the source account based on the strkey + if (_strkey.StrKey.isValidMed25519PublicKey(tx.source)) { + source = _muxed_account.MuxedAccount.fromAddress(tx.source, sequenceNum); + } else if (_strkey.StrKey.isValidEd25519PublicKey(tx.source)) { + source = new _account.Account(tx.source, sequenceNum); + } else { + throw new TypeError("unsupported tx source account: ".concat(tx.source)); + } + + // the initial fee passed to the builder gets scaled up based on the number + // of operations at the end, so we have to down-scale first + var unscaledFee = parseInt(tx.fee, 10) / tx.operations.length; + var builder = new TransactionBuilder(source, _objectSpread({ + fee: (unscaledFee || BASE_FEE).toString(), + memo: tx.memo, + networkPassphrase: tx.networkPassphrase, + timebounds: tx.timeBounds, + ledgerbounds: tx.ledgerBounds, + minAccountSequence: tx.minAccountSequence, + minAccountSequenceAge: tx.minAccountSequenceAge, + minAccountSequenceLedgerGap: tx.minAccountSequenceLedgerGap, + extraSigners: tx.extraSigners + }, opts)); + tx._tx.operations().forEach(function (op) { + return builder.addOperation(op); + }); + return builder; + } + }, { + key: "buildFeeBumpTransaction", + value: function buildFeeBumpTransaction(feeSource, baseFee, innerTx, networkPassphrase) { + var innerOps = innerTx.operations.length; + var innerBaseFeeRate = new _bignumber["default"](innerTx.fee).div(innerOps); + var base = new _bignumber["default"](baseFee); + + // The fee rate for fee bump is at least the fee rate of the inner transaction + if (base.lt(innerBaseFeeRate)) { + throw new Error("Invalid baseFee, it should be at least ".concat(innerBaseFeeRate, " stroops.")); + } + var minBaseFee = new _bignumber["default"](BASE_FEE); + + // The fee rate is at least the minimum fee + if (base.lt(minBaseFee)) { + throw new Error("Invalid baseFee, it should be at least ".concat(minBaseFee, " stroops.")); + } + var innerTxEnvelope = innerTx.toEnvelope(); + if (innerTxEnvelope["switch"]() === _xdr["default"].EnvelopeType.envelopeTypeTxV0()) { + var v0Tx = innerTxEnvelope.v0().tx(); + var v1Tx = new _xdr["default"].Transaction({ + sourceAccount: new _xdr["default"].MuxedAccount.keyTypeEd25519(v0Tx.sourceAccountEd25519()), + fee: v0Tx.fee(), + seqNum: v0Tx.seqNum(), + cond: _xdr["default"].Preconditions.precondTime(v0Tx.timeBounds()), + memo: v0Tx.memo(), + operations: v0Tx.operations(), + ext: new _xdr["default"].TransactionExt(0) + }); + innerTxEnvelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: v1Tx, + signatures: innerTxEnvelope.v0().signatures() + })); + } + var feeSourceAccount; + if (typeof feeSource === 'string') { + feeSourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(feeSource); + } else { + feeSourceAccount = feeSource.xdrMuxedAccount(); + } + var tx = new _xdr["default"].FeeBumpTransaction({ + feeSource: feeSourceAccount, + fee: _xdr["default"].Int64.fromString(base.times(innerOps + 1).toString()), + innerTx: _xdr["default"].FeeBumpTransactionInnerTx.envelopeTypeTx(innerTxEnvelope.v1()), + ext: new _xdr["default"].FeeBumpTransactionExt(0) + }); + var feeBumpTxEnvelope = new _xdr["default"].FeeBumpTransactionEnvelope({ + tx: tx, + signatures: [] + }); + var envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTxFeeBump(feeBumpTxEnvelope); + return new _fee_bump_transaction.FeeBumpTransaction(envelope, networkPassphrase); + } + + /** + * Build a {@link Transaction} or {@link FeeBumpTransaction} from an + * xdr.TransactionEnvelope. + * + * @param {string|xdr.TransactionEnvelope} envelope - The transaction envelope + * object or base64 encoded string. + * @param {string} networkPassphrase - The network passphrase of the target + * Stellar network (e.g. "Public Global Stellar Network ; September + * 2015"), see {@link Networks}. + * + * @returns {Transaction|FeeBumpTransaction} + */ + }, { + key: "fromXDR", + value: function fromXDR(envelope, networkPassphrase) { + if (typeof envelope === 'string') { + envelope = _xdr["default"].TransactionEnvelope.fromXDR(envelope, 'base64'); + } + if (envelope["switch"]() === _xdr["default"].EnvelopeType.envelopeTypeTxFeeBump()) { + return new _fee_bump_transaction.FeeBumpTransaction(envelope, networkPassphrase); + } + return new _transaction.Transaction(envelope, networkPassphrase); + } + }]); +}(); +/** + * Checks whether a provided object is a valid Date. + * @argument {Date} d date object + * @returns {boolean} + */ +function isValidDate(d) { + // isnan is okay here because it correctly checks for invalid date objects + // eslint-disable-next-line no-restricted-globals + return d instanceof Date && !isNaN(d); +} + +/***/ }), + +/***/ 1242: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _bignumber = _interopRequireDefault(__webpack_require__(1594)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var BigNumber = _bignumber["default"].clone(); +BigNumber.DEBUG = true; // gives us exceptions on bad constructor values +var _default = exports["default"] = BigNumber; + +/***/ }), + +/***/ 1346: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.verifyChecksum = verifyChecksum; +function verifyChecksum(expected, actual) { + if (expected.length !== actual.length) { + return false; + } + if (expected.length === 0) { + return true; + } + for (var i = 0; i < expected.length; i += 1) { + if (expected[i] !== actual[i]) { + return false; + } + } + return true; +} + +/***/ }), + +/***/ 4151: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.best_r = best_r; +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +// eslint-disable-next-line no-bitwise +var MAX_INT = (1 << 31 >>> 0) - 1; + +/** + * Calculates and returns the best rational approximation of the given real number. + * @private + * @param {string|number|BigNumber} rawNumber Real number + * @throws Error Throws `Error` when the best rational approximation cannot be found. + * @returns {array} first element is n (numerator), second element is d (denominator) + */ +function best_r(rawNumber) { + var number = new _bignumber["default"](rawNumber); + var a; + var f; + var fractions = [[new _bignumber["default"](0), new _bignumber["default"](1)], [new _bignumber["default"](1), new _bignumber["default"](0)]]; + var i = 2; + + // eslint-disable-next-line no-constant-condition + while (true) { + if (number.gt(MAX_INT)) { + break; + } + a = number.integerValue(_bignumber["default"].ROUND_FLOOR); + f = number.minus(a); + var h = a.times(fractions[i - 1][0]).plus(fractions[i - 2][0]); + var k = a.times(fractions[i - 1][1]).plus(fractions[i - 2][1]); + if (h.gt(MAX_INT) || k.gt(MAX_INT)) { + break; + } + fractions.push([h, k]); + if (f.eq(0)) { + break; + } + number = new _bignumber["default"](1).div(f); + i += 1; + } + var _fractions = _slicedToArray(fractions[fractions.length - 1], 2), + n = _fractions[0], + d = _fractions[1]; + if (n.isZero() || d.isZero()) { + throw new Error("Couldn't find approximation"); + } + return [n.toNumber(), d.toNumber()]; +} + +/***/ }), + +/***/ 6160: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decodeAddressToMuxedAccount = decodeAddressToMuxedAccount; +exports.encodeMuxedAccount = encodeMuxedAccount; +exports.encodeMuxedAccountToAddress = encodeMuxedAccountToAddress; +exports.extractBaseAddress = extractBaseAddress; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Converts a Stellar address (in G... or M... form) to an `xdr.MuxedAccount` + * structure, using the ed25519 representation when possible. + * + * This supports full muxed accounts, where an `M...` address will resolve to + * both its underlying `G...` address and an integer ID. + * + * @param {string} address G... or M... address to encode into XDR + * @returns {xdr.MuxedAccount} a muxed account object for this address string + */ +function decodeAddressToMuxedAccount(address) { + if (_strkey.StrKey.isValidMed25519PublicKey(address)) { + return _decodeAddressFullyToMuxedAccount(address); + } + return _xdr["default"].MuxedAccount.keyTypeEd25519(_strkey.StrKey.decodeEd25519PublicKey(address)); +} + +/** + * Converts an xdr.MuxedAccount to its StrKey representation. + * + * This returns its "M..." string representation if there is a muxing ID within + * the object and returns the "G..." representation otherwise. + * + * @param {xdr.MuxedAccount} muxedAccount Raw account to stringify + * @returns {string} Stringified G... (corresponding to the underlying pubkey) + * or M... address (corresponding to both the key and the muxed ID) + * + * @see https://stellar.org/protocol/sep-23 + */ +function encodeMuxedAccountToAddress(muxedAccount) { + if (muxedAccount["switch"]().value === _xdr["default"].CryptoKeyType.keyTypeMuxedEd25519().value) { + return _encodeMuxedAccountFullyToAddress(muxedAccount); + } + return _strkey.StrKey.encodeEd25519PublicKey(muxedAccount.ed25519()); +} + +/** + * Transform a Stellar address (G...) and an ID into its XDR representation. + * + * @param {string} address - a Stellar G... address + * @param {string} id - a Uint64 ID represented as a string + * + * @return {xdr.MuxedAccount} - XDR representation of the above muxed account + */ +function encodeMuxedAccount(address, id) { + if (!_strkey.StrKey.isValidEd25519PublicKey(address)) { + throw new Error('address should be a Stellar account ID (G...)'); + } + if (typeof id !== 'string') { + throw new Error('id should be a string representing a number (uint64)'); + } + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromString(id), + ed25519: _strkey.StrKey.decodeEd25519PublicKey(address) + })); +} + +/** + * Extracts the underlying base (G...) address from an M-address. + * @param {string} address an account address (either M... or G...) + * @return {string} a Stellar public key address (G...) + */ +function extractBaseAddress(address) { + if (_strkey.StrKey.isValidEd25519PublicKey(address)) { + return address; + } + if (!_strkey.StrKey.isValidMed25519PublicKey(address)) { + throw new TypeError("expected muxed account (M...), got ".concat(address)); + } + var muxedAccount = decodeAddressToMuxedAccount(address); + return _strkey.StrKey.encodeEd25519PublicKey(muxedAccount.med25519().ed25519()); +} + +// Decodes an "M..." account ID into its MuxedAccount object representation. +function _decodeAddressFullyToMuxedAccount(address) { + var rawBytes = _strkey.StrKey.decodeMed25519PublicKey(address); + + // Decoding M... addresses cannot be done through a simple + // MuxedAccountMed25519.fromXDR() call, because the definition is: + // + // constructor(attributes: { id: Uint64; ed25519: Buffer }); + // + // Note the ID is the first attribute. However, the ID comes *last* in the + // stringified (base32-encoded) address itself (it's the last 8-byte suffix). + // The `fromXDR()` method interprets bytes in order, so we need to parse out + // the raw binary into its requisite parts, i.e. use the MuxedAccountMed25519 + // constructor directly. + // + // Refer to https://github.com/stellar/go/blob/master/xdr/muxed_account.go#L26 + // for the Golang implementation of the M... parsing. + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromXDR(rawBytes.subarray(-8)), + ed25519: rawBytes.subarray(0, -8) + })); +} + +// Converts an xdr.MuxedAccount into its *true* "M..." string representation. +function _encodeMuxedAccountFullyToAddress(muxedAccount) { + if (muxedAccount["switch"]() === _xdr["default"].CryptoKeyType.keyTypeEd25519()) { + return encodeMuxedAccountToAddress(muxedAccount); + } + var muxed = muxedAccount.med25519(); + return _strkey.StrKey.encodeMed25519PublicKey(Buffer.concat([muxed.ed25519(), muxed.id().toXDR('raw')])); +} + +/***/ }), + +/***/ 645: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.trimEnd = void 0; +var trimEnd = exports.trimEnd = function trimEnd(input, _char) { + var isNumber = typeof input === 'number'; + var str = String(input); + while (str.endsWith(_char)) { + str = str.slice(0, -1); + } + return isNumber ? Number(str) : str; +}; + +/***/ }), + +/***/ 1918: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _curr_generated = _interopRequireDefault(__webpack_require__(7938)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var _default = exports["default"] = _curr_generated["default"]; + +/***/ }), + +/***/ 4940: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +(function(nacl) { +'use strict'; + +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ + +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; + +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; + +var _0 = new Uint8Array(16); +var _9 = new Uint8Array(32); _9[0] = 9; + +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + +function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; +} + +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; +} + +function crypto_verify_16(x, xi, y, yi) { + return vn(x,xi,y,yi,16); +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); +} + +function core_salsa20(o, p, k, c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; + + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + + o[ 4] = x1 >>> 0 & 0xff; + o[ 5] = x1 >>> 8 & 0xff; + o[ 6] = x1 >>> 16 & 0xff; + o[ 7] = x1 >>> 24 & 0xff; + + o[ 8] = x2 >>> 0 & 0xff; + o[ 9] = x2 >>> 8 & 0xff; + o[10] = x2 >>> 16 & 0xff; + o[11] = x2 >>> 24 & 0xff; + + o[12] = x3 >>> 0 & 0xff; + o[13] = x3 >>> 8 & 0xff; + o[14] = x3 >>> 16 & 0xff; + o[15] = x3 >>> 24 & 0xff; + + o[16] = x4 >>> 0 & 0xff; + o[17] = x4 >>> 8 & 0xff; + o[18] = x4 >>> 16 & 0xff; + o[19] = x4 >>> 24 & 0xff; + + o[20] = x5 >>> 0 & 0xff; + o[21] = x5 >>> 8 & 0xff; + o[22] = x5 >>> 16 & 0xff; + o[23] = x5 >>> 24 & 0xff; + + o[24] = x6 >>> 0 & 0xff; + o[25] = x6 >>> 8 & 0xff; + o[26] = x6 >>> 16 & 0xff; + o[27] = x6 >>> 24 & 0xff; + + o[28] = x7 >>> 0 & 0xff; + o[29] = x7 >>> 8 & 0xff; + o[30] = x7 >>> 16 & 0xff; + o[31] = x7 >>> 24 & 0xff; + + o[32] = x8 >>> 0 & 0xff; + o[33] = x8 >>> 8 & 0xff; + o[34] = x8 >>> 16 & 0xff; + o[35] = x8 >>> 24 & 0xff; + + o[36] = x9 >>> 0 & 0xff; + o[37] = x9 >>> 8 & 0xff; + o[38] = x9 >>> 16 & 0xff; + o[39] = x9 >>> 24 & 0xff; + + o[40] = x10 >>> 0 & 0xff; + o[41] = x10 >>> 8 & 0xff; + o[42] = x10 >>> 16 & 0xff; + o[43] = x10 >>> 24 & 0xff; + + o[44] = x11 >>> 0 & 0xff; + o[45] = x11 >>> 8 & 0xff; + o[46] = x11 >>> 16 & 0xff; + o[47] = x11 >>> 24 & 0xff; + + o[48] = x12 >>> 0 & 0xff; + o[49] = x12 >>> 8 & 0xff; + o[50] = x12 >>> 16 & 0xff; + o[51] = x12 >>> 24 & 0xff; + + o[52] = x13 >>> 0 & 0xff; + o[53] = x13 >>> 8 & 0xff; + o[54] = x13 >>> 16 & 0xff; + o[55] = x13 >>> 24 & 0xff; + + o[56] = x14 >>> 0 & 0xff; + o[57] = x14 >>> 8 & 0xff; + o[58] = x14 >>> 16 & 0xff; + o[59] = x14 >>> 24 & 0xff; + + o[60] = x15 >>> 0 & 0xff; + o[61] = x15 >>> 8 & 0xff; + o[62] = x15 >>> 16 & 0xff; + o[63] = x15 >>> 24 & 0xff; +} + +function core_hsalsa20(o,p,k,c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + + o[ 4] = x5 >>> 0 & 0xff; + o[ 5] = x5 >>> 8 & 0xff; + o[ 6] = x5 >>> 16 & 0xff; + o[ 7] = x5 >>> 24 & 0xff; + + o[ 8] = x10 >>> 0 & 0xff; + o[ 9] = x10 >>> 8 & 0xff; + o[10] = x10 >>> 16 & 0xff; + o[11] = x10 >>> 24 & 0xff; + + o[12] = x15 >>> 0 & 0xff; + o[13] = x15 >>> 8 & 0xff; + o[14] = x15 >>> 16 & 0xff; + o[15] = x15 >>> 24 & 0xff; + + o[16] = x6 >>> 0 & 0xff; + o[17] = x6 >>> 8 & 0xff; + o[18] = x6 >>> 16 & 0xff; + o[19] = x6 >>> 24 & 0xff; + + o[20] = x7 >>> 0 & 0xff; + o[21] = x7 >>> 8 & 0xff; + o[22] = x7 >>> 16 & 0xff; + o[23] = x7 >>> 24 & 0xff; + + o[24] = x8 >>> 0 & 0xff; + o[25] = x8 >>> 8 & 0xff; + o[26] = x8 >>> 16 & 0xff; + o[27] = x8 >>> 24 & 0xff; + + o[28] = x9 >>> 0 & 0xff; + o[29] = x9 >>> 8 & 0xff; + o[30] = x9 >>> 16 & 0xff; + o[31] = x9 >>> 24 & 0xff; +} + +function crypto_core_salsa20(out,inp,k,c) { + core_salsa20(out,inp,k,c); +} + +function crypto_core_hsalsa20(out,inp,k,c) { + core_hsalsa20(out,inp,k,c); +} + +var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); + // "expand 32-byte k" + +function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + mpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + } + return 0; +} + +function crypto_stream_salsa20(c,cpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = x[i]; + } + return 0; +} + +function crypto_stream(c,cpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20(c,cpos,d,sn,s); +} + +function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); +} + +/* +* Port of Andrew Moon's Poly1305-donna-16. Public domain. +* https://github.com/floodyberry/poly1305-donna +*/ + +var poly1305 = function(key) { + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.leftover = 0; + this.fin = 0; + + var t0, t1, t2, t3, t4, t5, t6, t7; + + t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; + t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = ((t4 >>> 1)) & 0x1ffe; + t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = ((t7 >>> 5)) & 0x007f; + + this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; + this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; + this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; + this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; + this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; + this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; + this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; + this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; +}; + +poly1305.prototype.blocks = function(m, mpos, bytes) { + var hibit = this.fin ? 0 : (1 << 11); + var t0, t1, t2, t3, t4, t5, t6, t7, c; + var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; + + var h0 = this.h[0], + h1 = this.h[1], + h2 = this.h[2], + h3 = this.h[3], + h4 = this.h[4], + h5 = this.h[5], + h6 = this.h[6], + h7 = this.h[7], + h8 = this.h[8], + h9 = this.h[9]; + + var r0 = this.r[0], + r1 = this.r[1], + r2 = this.r[2], + r3 = this.r[3], + r4 = this.r[4], + r5 = this.r[5], + r6 = this.r[6], + r7 = this.r[7], + r8 = this.r[8], + r9 = this.r[9]; + + while (bytes >= 16) { + t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; + t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; + t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; + h5 += ((t4 >>> 1)) & 0x1fff; + t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; + t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + h9 += ((t7 >>> 5)) | hibit; + + c = 0; + + d0 = c; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h2 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c = (d0 >>> 13); d0 &= 0x1fff; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c += (d0 >>> 13); d0 &= 0x1fff; + + d1 = c; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h2 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c = (d1 >>> 13); d1 &= 0x1fff; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c += (d1 >>> 13); d1 &= 0x1fff; + + d2 = c; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h2 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c = (d2 >>> 13); d2 &= 0x1fff; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c += (d2 >>> 13); d2 &= 0x1fff; + + d3 = c; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h2 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c = (d3 >>> 13); d3 &= 0x1fff; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c += (d3 >>> 13); d3 &= 0x1fff; + + d4 = c; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h2 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c = (d4 >>> 13); d4 &= 0x1fff; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c += (d4 >>> 13); d4 &= 0x1fff; + + d5 = c; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h2 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c = (d5 >>> 13); d5 &= 0x1fff; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c += (d5 >>> 13); d5 &= 0x1fff; + + d6 = c; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h2 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c = (d6 >>> 13); d6 &= 0x1fff; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c += (d6 >>> 13); d6 &= 0x1fff; + + d7 = c; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h2 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c = (d7 >>> 13); d7 &= 0x1fff; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c += (d7 >>> 13); d7 &= 0x1fff; + + d8 = c; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h2 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c = (d8 >>> 13); d8 &= 0x1fff; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c += (d8 >>> 13); d8 &= 0x1fff; + + d9 = c; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h2 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c = (d9 >>> 13); d9 &= 0x1fff; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c += (d9 >>> 13); d9 &= 0x1fff; + + c = (((c << 2) + c)) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = (c >>> 13); + d1 += c; + + h0 = d0; + h1 = d1; + h2 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; + + mpos += 16; + bytes -= 16; + } + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h2; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; +}; + +poly1305.prototype.finish = function(mac, macpos) { + var g = new Uint16Array(10); + var c, mask, f, i; + + if (this.leftover) { + i = this.leftover; + this.buffer[i++] = 1; + for (; i < 16; i++) this.buffer[i] = 0; + this.fin = 1; + this.blocks(this.buffer, 0, 16); + } + + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + for (i = 2; i < 10; i++) { + this.h[i] += c; + c = this.h[i] >>> 13; + this.h[i] &= 0x1fff; + } + this.h[0] += (c * 5); + c = this.h[0] >>> 13; + this.h[0] &= 0x1fff; + this.h[1] += c; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + this.h[2] += c; + + g[0] = this.h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (i = 1; i < 10; i++) { + g[i] = this.h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= (1 << 13); + + mask = (c ^ 1) - 1; + for (i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; + + this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; + this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; + this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; + this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; + this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; + this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; + this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; + this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; + + f = this.h[0] + this.pad[0]; + this.h[0] = f & 0xffff; + for (i = 1; i < 8; i++) { + f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; + this.h[i] = f & 0xffff; + } + + mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; + mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; + mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; + mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; + mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; + mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; + mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; + mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; + mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; + mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; + mac[macpos+10] = (this.h[5] >>> 0) & 0xff; + mac[macpos+11] = (this.h[5] >>> 8) & 0xff; + mac[macpos+12] = (this.h[6] >>> 0) & 0xff; + mac[macpos+13] = (this.h[6] >>> 8) & 0xff; + mac[macpos+14] = (this.h[7] >>> 0) & 0xff; + mac[macpos+15] = (this.h[7] >>> 8) & 0xff; +}; + +poly1305.prototype.update = function(m, mpos, bytes) { + var i, want; + + if (this.leftover) { + want = (16 - this.leftover); + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) + return; + this.blocks(this.buffer, 0, 16); + this.leftover = 0; + } + + if (bytes >= 16) { + want = bytes - (bytes % 16); + this.blocks(m, mpos, want); + mpos += want; + bytes -= want; + } + + if (bytes) { + for (i = 0; i < bytes; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + this.leftover += bytes; + } +}; + +function crypto_onetimeauth(out, outpos, m, mpos, n, k) { + var s = new poly1305(k); + s.update(m, mpos, n); + s.finish(out, outpos); + return 0; +} + +function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { + var x = new Uint8Array(16); + crypto_onetimeauth(x,0,m,mpos,n,k); + return crypto_verify_16(h,hpos,x,0); +} + +function crypto_secretbox(c,m,d,n,k) { + var i; + if (d < 32) return -1; + crypto_stream_xor(c,0,m,0,d,n,k); + crypto_onetimeauth(c, 16, c, 32, d - 32, c); + for (i = 0; i < 16; i++) c[i] = 0; + return 0; +} + +function crypto_secretbox_open(m,c,d,n,k) { + var i; + var x = new Uint8Array(32); + if (d < 32) return -1; + crypto_stream(x,0,32,n,k); + if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; + crypto_stream_xor(m,0,c,0,d,n,k); + for (i = 0; i < 32; i++) m[i] = 0; + return 0; +} + +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} + +function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c-1 + 37 * (c-1); +} + +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; + } +} + +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} + +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; +} + +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} + +function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +} + +function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +} + +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is + + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} + +function S(o, a) { + M(o, a, a); +} + +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; + } + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); + } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; + } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; +} + +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); +} + +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); +} + +function crypto_box_beforenm(k, y, x) { + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y); + return crypto_core_hsalsa20(k, _0, s, sigma); +} + +var crypto_box_afternm = crypto_secretbox; +var crypto_box_open_afternm = crypto_secretbox_open; + +function crypto_box(c, m, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_afternm(c, m, d, n, k); +} + +function crypto_box_open(m, c, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_open_afternm(m, c, d, n, k); +} + +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 +]; + +function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; + + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; + } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; + + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; + + // add + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // K + h = K[i*2]; + l = K[i*2+1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // w + h = wh[i%16]; + l = wl[i%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; + + // add + h = th; + l = tl; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); + + // add + h = bh3; + l = bl3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = th; + l = tl; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); + + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); + } + } + } + + // add + h = ah0; + l = al0; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[0]; + l = hl[0]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); + + h = ah1; + l = al1; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[1]; + l = hl[1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); + + h = ah2; + l = al2; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[2]; + l = hl[2]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); + + h = ah3; + l = al3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[3]; + l = hl[3]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); + + h = ah4; + l = al4; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[4]; + l = hl[4]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); + + h = ah5; + l = al5; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[5]; + l = hl[5]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); + + h = ah6; + l = al6; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[6]; + l = hl[6]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); + + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[7]; + l = hl[7]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); + + pos += 128; + n -= 128; + } + + return n; +} + +function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; + + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; + + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; + + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; + + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; + + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); + + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); + + return 0; +} + +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } +} + +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} + +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } +} + +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} + +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; + + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + scalarbase(p, d); + pack(pk, p); + + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} + +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); + +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = Math.floor((x[j] + 128) / 256); + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} + +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} + +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; + + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); + + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; + } + } + + modL(sm.subarray(32), x); + return smlen; +} + +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + return 0; +} + +function crypto_sign_open(m, sm, n, pk) { + var i; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; + + if (n < 64) return -1; + + if (unpackneg(q, pk)) return -1; + + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); + + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; + } + + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + return n; +} + +var crypto_secretbox_KEYBYTES = 32, + crypto_secretbox_NONCEBYTES = 24, + crypto_secretbox_ZEROBYTES = 32, + crypto_secretbox_BOXZEROBYTES = 16, + crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_box_BEFORENMBYTES = 32, + crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, + crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, + crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32, + crypto_hash_BYTES = 64; + +nacl.lowlevel = { + crypto_core_hsalsa20: crypto_core_hsalsa20, + crypto_stream_xor: crypto_stream_xor, + crypto_stream: crypto_stream, + crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, + crypto_stream_salsa20: crypto_stream_salsa20, + crypto_onetimeauth: crypto_onetimeauth, + crypto_onetimeauth_verify: crypto_onetimeauth_verify, + crypto_verify_16: crypto_verify_16, + crypto_verify_32: crypto_verify_32, + crypto_secretbox: crypto_secretbox, + crypto_secretbox_open: crypto_secretbox_open, + crypto_scalarmult: crypto_scalarmult, + crypto_scalarmult_base: crypto_scalarmult_base, + crypto_box_beforenm: crypto_box_beforenm, + crypto_box_afternm: crypto_box_afternm, + crypto_box: crypto_box, + crypto_box_open: crypto_box_open, + crypto_box_keypair: crypto_box_keypair, + crypto_hash: crypto_hash, + crypto_sign: crypto_sign, + crypto_sign_keypair: crypto_sign_keypair, + crypto_sign_open: crypto_sign_open, + + crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, + crypto_sign_BYTES: crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, + crypto_hash_BYTES: crypto_hash_BYTES, + + gf: gf, + D: D, + L: L, + pack25519: pack25519, + unpack25519: unpack25519, + M: M, + A: A, + S: S, + Z: Z, + pow2523: pow2523, + add: add, + set25519: set25519, + modL: modL, + scalarmult: scalarmult, + scalarbase: scalarbase, +}; + +/* High-level API */ + +function checkLengths(k, n) { + if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); +} + +function checkBoxLengths(pk, sk) { + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); +} + +function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError('unexpected type, use Uint8Array'); + } +} + +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} + +nacl.randomBytes = function(n) { + var b = new Uint8Array(n); + randombytes(b, n); + return b; +}; + +nacl.secretbox = function(msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c = new Uint8Array(m.length); + for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; + crypto_secretbox(c, m, m.length, nonce, key); + return c.subarray(crypto_secretbox_BOXZEROBYTES); +}; + +nacl.secretbox.open = function(box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m = new Uint8Array(c.length); + for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; + if (c.length < 32) return null; + if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null; + return m.subarray(crypto_secretbox_ZEROBYTES); +}; + +nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; +nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; +nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; + +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; + +nacl.scalarMult.base = function(n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; +}; + +nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; +nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; + +nacl.box = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k); +}; + +nacl.box.before = function(publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k, publicKey, secretKey); + return k; +}; + +nacl.box.after = nacl.secretbox; + +nacl.box.open = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k); +}; + +nacl.box.open.after = nacl.secretbox.open; + +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; +nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; +nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; +nacl.box.nonceLength = crypto_box_NONCEBYTES; +nacl.box.overheadLength = nacl.secretbox.overheadLength; + +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; + +nacl.sign.open = function(signedMsg, publicKey) { + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m = new Uint8Array(mlen); + for (var i = 0; i < m.length; i++) m[i] = tmp[i]; + return m; +}; + +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; + +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; + +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; +nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; +nacl.sign.seedLength = crypto_sign_SEEDBYTES; +nacl.sign.signatureLength = crypto_sign_BYTES; + +nacl.hash = function(msg) { + checkArrayTypes(msg); + var h = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h, msg, msg.length); + return h; +}; + +nacl.hash.hashLength = crypto_hash_BYTES; + +nacl.verify = function(x, y) { + checkArrayTypes(x, y); + // Zero length arguments are considered not equal. + if (x.length === 0 || y.length === 0) return false; + if (x.length !== y.length) return false; + return (vn(x, 0, y, 0, x.length) === 0) ? true : false; +}; + +nacl.setPRNG = function(fn) { + randombytes = fn; +}; + +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; + if (crypto && crypto.getRandomValues) { + // Browsers. + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } else if (true) { + // Node.js. + crypto = __webpack_require__(2894); + if (crypto && crypto.randomBytes) { + nacl.setPRNG(function(x, n) { + var i, v = crypto.randomBytes(n); + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } + } +})(); + +})( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); + + +/***/ }), + +/***/ 1924: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ StellarBase: () => (/* reexport module object */ _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2__), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ httpClient: () => (/* reexport safe */ _http_client__WEBPACK_IMPORTED_MODULE_0__.ok) +/* harmony export */ }); +/* harmony import */ var _http_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6371); +/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4356); +/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {}; +/* harmony reexport (unknown) */ for(const __WEBPACK_IMPORT_KEY__ in _index__WEBPACK_IMPORTED_MODULE_1__) if(["default","StellarBase","httpClient"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = () => _index__WEBPACK_IMPORTED_MODULE_1__[__WEBPACK_IMPORT_KEY__] +/* harmony reexport (unknown) */ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2__); +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (module.exports); + +/***/ }), + +/***/ 8732: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ T: () => (/* binding */ Config) +/* harmony export */ }); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var defaultConfig = { + allowHttp: false, + timeout: 0 +}; +var config = _objectSpread({}, defaultConfig); +var Config = function () { + function Config() { + _classCallCheck(this, Config); + } + return _createClass(Config, null, [{ + key: "setAllowHttp", + value: function setAllowHttp(value) { + config.allowHttp = value; + } + }, { + key: "setTimeout", + value: function setTimeout(value) { + config.timeout = value; + } + }, { + key: "isAllowHttp", + value: function isAllowHttp() { + return config.allowHttp; + } + }, { + key: "getTimeout", + value: function getTimeout() { + return config.timeout; + } + }, { + key: "setDefault", + value: function setDefault() { + config = _objectSpread({}, defaultConfig); + } + }]); +}(); + + +/***/ }), + +/***/ 6299: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + AssembledTransaction: () => (/* reexport */ AssembledTransaction), + Client: () => (/* reexport */ Client), + DEFAULT_TIMEOUT: () => (/* reexport */ DEFAULT_TIMEOUT), + Err: () => (/* reexport */ Err), + NULL_ACCOUNT: () => (/* reexport */ NULL_ACCOUNT), + Ok: () => (/* reexport */ Ok), + SentTransaction: () => (/* reexport */ SentTransaction), + Spec: () => (/* reexport */ Spec), + basicNodeSigner: () => (/* reexport */ basicNodeSigner) +}); + +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./src/rpc/index.ts + 3 modules +var rpc = __webpack_require__(3496); +// EXTERNAL MODULE: ./src/rpc/api.ts +var api = __webpack_require__(4076); +// EXTERNAL MODULE: ./src/rpc/transaction.ts +var transaction = __webpack_require__(8680); +;// ./src/contract/rust_result.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Ok = function () { + function Ok(value) { + _classCallCheck(this, Ok); + this.value = value; + } + return _createClass(Ok, [{ + key: "unwrapErr", + value: function unwrapErr() { + throw new Error("No error"); + } + }, { + key: "unwrap", + value: function unwrap() { + return this.value; + } + }, { + key: "isOk", + value: function isOk() { + return true; + } + }, { + key: "isErr", + value: function isErr() { + return false; + } + }]); +}(); +var Err = function () { + function Err(error) { + _classCallCheck(this, Err); + this.error = error; + } + return _createClass(Err, [{ + key: "unwrapErr", + value: function unwrapErr() { + return this.error; + } + }, { + key: "unwrap", + value: function unwrap() { + throw new Error(this.error.message); + } + }, { + key: "isOk", + value: function isOk() { + return false; + } + }, { + key: "isErr", + value: function isErr() { + return true; + } + }]); +}(); +;// ./src/contract/types.ts + +var DEFAULT_TIMEOUT = 5 * 60; +var NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; +;// ./src/contract/utils.ts +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == utils_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(utils_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function utils_typeof(o) { "@babel/helpers - typeof"; return utils_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, utils_typeof(o); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + + +function withExponentialBackoff(_x, _x2, _x3) { + return _withExponentialBackoff.apply(this, arguments); +} +function _withExponentialBackoff() { + _withExponentialBackoff = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(fn, keepWaitingIf, timeoutInSeconds) { + var exponentialFactor, + verbose, + attempts, + count, + waitUntil, + waitTime, + totalWaitTime, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + exponentialFactor = _args.length > 3 && _args[3] !== undefined ? _args[3] : 1.5; + verbose = _args.length > 4 && _args[4] !== undefined ? _args[4] : false; + attempts = []; + count = 0; + _context.t0 = attempts; + _context.next = 7; + return fn(); + case 7: + _context.t1 = _context.sent; + _context.t0.push.call(_context.t0, _context.t1); + if (keepWaitingIf(attempts[attempts.length - 1])) { + _context.next = 11; + break; + } + return _context.abrupt("return", attempts); + case 11: + waitUntil = new Date(Date.now() + timeoutInSeconds * 1000).valueOf(); + waitTime = 1000; + totalWaitTime = waitTime; + case 14: + if (!(Date.now() < waitUntil && keepWaitingIf(attempts[attempts.length - 1]))) { + _context.next = 30; + break; + } + count += 1; + if (verbose) { + console.info("Waiting ".concat(waitTime, "ms before trying again (bringing the total wait time to ").concat(totalWaitTime, "ms so far, of total ").concat(timeoutInSeconds * 1000, "ms)")); + } + _context.next = 19; + return new Promise(function (res) { + return setTimeout(res, waitTime); + }); + case 19: + waitTime *= exponentialFactor; + if (new Date(Date.now() + waitTime).valueOf() > waitUntil) { + waitTime = waitUntil - Date.now(); + if (verbose) { + console.info("was gonna wait too long; new waitTime: ".concat(waitTime, "ms")); + } + } + totalWaitTime = waitTime + totalWaitTime; + _context.t2 = attempts; + _context.next = 25; + return fn(attempts[attempts.length - 1]); + case 25: + _context.t3 = _context.sent; + _context.t2.push.call(_context.t2, _context.t3); + if (verbose && keepWaitingIf(attempts[attempts.length - 1])) { + console.info("".concat(count, ". Called ").concat(fn, "; ").concat(attempts.length, " prev attempts. Most recent: ").concat(JSON.stringify(attempts[attempts.length - 1], null, 2))); + } + _context.next = 14; + break; + case 30: + return _context.abrupt("return", attempts); + case 31: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _withExponentialBackoff.apply(this, arguments); +} +var contractErrorPattern = /Error\(Contract, #(\d+)\)/; +function implementsToString(obj) { + return utils_typeof(obj) === "object" && obj !== null && "toString" in obj; +} +function processSpecEntryStream(buffer) { + var reader = new lib.cereal.XdrReader(buffer); + var res = []; + while (!reader.eof) { + res.push(lib.xdr.ScSpecEntry.read(reader)); + } + return res; +} +function getAccount(_x4, _x5) { + return _getAccount.apply(this, arguments); +} +function _getAccount() { + _getAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(options, server) { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", options.publicKey ? server.getAccount(options.publicKey) : new lib.Account(NULL_ACCOUNT, "0")); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _getAccount.apply(this, arguments); +} +;// ./src/contract/sent_transaction.ts +var _SentTransaction; +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == sent_transaction_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function sent_transaction_typeof(o) { "@babel/helpers - typeof"; return sent_transaction_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, sent_transaction_typeof(o); } +function sent_transaction_regeneratorRuntime() { "use strict"; sent_transaction_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == sent_transaction_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(sent_transaction_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function sent_transaction_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function sent_transaction_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { sent_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { sent_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function sent_transaction_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function sent_transaction_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, sent_transaction_toPropertyKey(o.key), o); } } +function sent_transaction_createClass(e, r, t) { return r && sent_transaction_defineProperties(e.prototype, r), t && sent_transaction_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = sent_transaction_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function sent_transaction_toPropertyKey(t) { var i = sent_transaction_toPrimitive(t, "string"); return "symbol" == sent_transaction_typeof(i) ? i : i + ""; } +function sent_transaction_toPrimitive(t, r) { if ("object" != sent_transaction_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != sent_transaction_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + +var SentTransaction = function () { + function SentTransaction(assembled) { + var _this = this, + _this$assembled$optio2; + sent_transaction_classCallCheck(this, SentTransaction); + _defineProperty(this, "send", sent_transaction_asyncToGenerator(sent_transaction_regeneratorRuntime().mark(function _callee() { + var _this$assembled$optio; + var hash, timeoutInSeconds; + return sent_transaction_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return _this.server.sendTransaction(_this.assembled.signed); + case 2: + _this.sendTransactionResponse = _context.sent; + if (!(_this.sendTransactionResponse.status !== "PENDING")) { + _context.next = 5; + break; + } + throw new SentTransaction.Errors.SendFailed("Sending the transaction to the network failed!\n".concat(JSON.stringify(_this.sendTransactionResponse, null, 2))); + case 5: + hash = _this.sendTransactionResponse.hash; + timeoutInSeconds = (_this$assembled$optio = _this.assembled.options.timeoutInSeconds) !== null && _this$assembled$optio !== void 0 ? _this$assembled$optio : DEFAULT_TIMEOUT; + _context.next = 9; + return withExponentialBackoff(function () { + return _this.server.getTransaction(hash); + }, function (resp) { + return resp.status === api/* Api */.j.GetTransactionStatus.NOT_FOUND; + }, timeoutInSeconds); + case 9: + _this.getTransactionResponseAll = _context.sent; + _this.getTransactionResponse = _this.getTransactionResponseAll[_this.getTransactionResponseAll.length - 1]; + if (!(_this.getTransactionResponse.status === api/* Api */.j.GetTransactionStatus.NOT_FOUND)) { + _context.next = 13; + break; + } + throw new SentTransaction.Errors.TransactionStillPending("Waited ".concat(timeoutInSeconds, " seconds for transaction to complete, but it did not. ") + "Returning anyway. Check the transaction status manually. " + "Sent transaction: ".concat(JSON.stringify(_this.sendTransactionResponse, null, 2), "\n") + "All attempts to get the result: ".concat(JSON.stringify(_this.getTransactionResponseAll, null, 2))); + case 13: + return _context.abrupt("return", _this); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + }))); + this.assembled = assembled; + this.server = new rpc.Server(this.assembled.options.rpcUrl, { + allowHttp: (_this$assembled$optio2 = this.assembled.options.allowHttp) !== null && _this$assembled$optio2 !== void 0 ? _this$assembled$optio2 : false + }); + } + return sent_transaction_createClass(SentTransaction, [{ + key: "result", + get: function get() { + if ("getTransactionResponse" in this && this.getTransactionResponse) { + if ("returnValue" in this.getTransactionResponse) { + return this.assembled.options.parseResultXdr(this.getTransactionResponse.returnValue); + } + throw new Error("Transaction failed! Cannot parse result."); + } + if (this.sendTransactionResponse) { + var _this$sendTransaction; + var errorResult = (_this$sendTransaction = this.sendTransactionResponse.errorResult) === null || _this$sendTransaction === void 0 ? void 0 : _this$sendTransaction.result(); + if (errorResult) { + throw new SentTransaction.Errors.SendFailed("Transaction simulation looked correct, but attempting to send the transaction failed. Check `simulation` and `sendTransactionResponseAll` to troubleshoot. Decoded `sendTransactionResponse.errorResultXdr`: ".concat(errorResult)); + } + throw new SentTransaction.Errors.SendResultOnly("Transaction was sent to the network, but not yet awaited. No result to show. Await transaction completion with `getTransaction(sendTransactionResponse.hash)`"); + } + throw new Error("Sending transaction failed: ".concat(JSON.stringify(this.assembled.signed))); + } + }]); +}(); +_SentTransaction = SentTransaction; +_defineProperty(SentTransaction, "Errors", { + SendFailed: function (_Error) { + function SendFailedError() { + sent_transaction_classCallCheck(this, SendFailedError); + return _callSuper(this, SendFailedError, arguments); + } + _inherits(SendFailedError, _Error); + return sent_transaction_createClass(SendFailedError); + }(_wrapNativeSuper(Error)), + SendResultOnly: function (_Error2) { + function SendResultOnlyError() { + sent_transaction_classCallCheck(this, SendResultOnlyError); + return _callSuper(this, SendResultOnlyError, arguments); + } + _inherits(SendResultOnlyError, _Error2); + return sent_transaction_createClass(SendResultOnlyError); + }(_wrapNativeSuper(Error)), + TransactionStillPending: function (_Error3) { + function TransactionStillPendingError() { + sent_transaction_classCallCheck(this, TransactionStillPendingError); + return _callSuper(this, TransactionStillPendingError, arguments); + } + _inherits(TransactionStillPendingError, _Error3); + return sent_transaction_createClass(TransactionStillPendingError); + }(_wrapNativeSuper(Error)) +}); +_defineProperty(SentTransaction, "init", function () { + var _ref2 = sent_transaction_asyncToGenerator(sent_transaction_regeneratorRuntime().mark(function _callee2(assembled) { + var tx, sent; + return sent_transaction_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + tx = new _SentTransaction(assembled); + _context2.next = 3; + return tx.send(); + case 3: + sent = _context2.sent; + return _context2.abrupt("return", sent); + case 5: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; +}()); +;// ./src/contract/assembled_transaction.ts +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +function assembled_transaction_callSuper(t, o, e) { return o = assembled_transaction_getPrototypeOf(o), assembled_transaction_possibleConstructorReturn(t, assembled_transaction_isNativeReflectConstruct() ? Reflect.construct(o, e || [], assembled_transaction_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function assembled_transaction_possibleConstructorReturn(t, e) { if (e && ("object" == assembled_transaction_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return assembled_transaction_assertThisInitialized(t); } +function assembled_transaction_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function assembled_transaction_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && assembled_transaction_setPrototypeOf(t, e); } +function assembled_transaction_wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return assembled_transaction_wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !assembled_transaction_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return assembled_transaction_construct(t, arguments, assembled_transaction_getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), assembled_transaction_setPrototypeOf(Wrapper, t); }, assembled_transaction_wrapNativeSuper(t); } +function assembled_transaction_construct(t, e, r) { if (assembled_transaction_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && assembled_transaction_setPrototypeOf(p, r.prototype), p; } +function assembled_transaction_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (assembled_transaction_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function assembled_transaction_isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function assembled_transaction_setPrototypeOf(t, e) { return assembled_transaction_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, assembled_transaction_setPrototypeOf(t, e); } +function assembled_transaction_getPrototypeOf(t) { return assembled_transaction_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, assembled_transaction_getPrototypeOf(t); } +function assembled_transaction_typeof(o) { "@babel/helpers - typeof"; return assembled_transaction_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, assembled_transaction_typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { assembled_transaction_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function assembled_transaction_regeneratorRuntime() { "use strict"; assembled_transaction_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == assembled_transaction_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(assembled_transaction_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function assembled_transaction_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function assembled_transaction_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { assembled_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { assembled_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function assembled_transaction_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function assembled_transaction_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, assembled_transaction_toPropertyKey(o.key), o); } } +function assembled_transaction_createClass(e, r, t) { return r && assembled_transaction_defineProperties(e.prototype, r), t && assembled_transaction_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function assembled_transaction_defineProperty(e, r, t) { return (r = assembled_transaction_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function assembled_transaction_toPropertyKey(t) { var i = assembled_transaction_toPrimitive(t, "string"); return "symbol" == assembled_transaction_typeof(i) ? i : i + ""; } +function assembled_transaction_toPrimitive(t, r) { if ("object" != assembled_transaction_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != assembled_transaction_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + + + +var AssembledTransaction = function () { + function AssembledTransaction(options) { + var _this = this, + _this$options$simulat, + _this$options$allowHt; + assembled_transaction_classCallCheck(this, AssembledTransaction); + assembled_transaction_defineProperty(this, "simulate", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee() { + var _restore; + var _ref2, + restore, + account, + result, + _this$options$fee, + _this$options$args, + _this$options$timeout, + contract, + _args = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _ref2 = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, restore = _ref2.restore; + if (_this.built) { + _context.next = 5; + break; + } + if (_this.raw) { + _context.next = 4; + break; + } + throw new Error("Transaction has not yet been assembled; " + "call `AssembledTransaction.build` first."); + case 4: + _this.built = _this.raw.build(); + case 5: + restore = (_restore = restore) !== null && _restore !== void 0 ? _restore : _this.options.restore; + delete _this.simulationResult; + delete _this.simulationTransactionData; + _context.next = 10; + return _this.server.simulateTransaction(_this.built); + case 10: + _this.simulation = _context.sent; + if (!(restore && api/* Api */.j.isSimulationRestore(_this.simulation))) { + _context.next = 25; + break; + } + _context.next = 14; + return getAccount(_this.options, _this.server); + case 14: + account = _context.sent; + _context.next = 17; + return _this.restoreFootprint(_this.simulation.restorePreamble, account); + case 17: + result = _context.sent; + if (!(result.status === api/* Api */.j.GetTransactionStatus.SUCCESS)) { + _context.next = 24; + break; + } + contract = new lib.Contract(_this.options.contractId); + _this.raw = new lib.TransactionBuilder(account, { + fee: (_this$options$fee = _this.options.fee) !== null && _this$options$fee !== void 0 ? _this$options$fee : lib.BASE_FEE, + networkPassphrase: _this.options.networkPassphrase + }).addOperation(contract.call.apply(contract, [_this.options.method].concat(_toConsumableArray((_this$options$args = _this.options.args) !== null && _this$options$args !== void 0 ? _this$options$args : [])))).setTimeout((_this$options$timeout = _this.options.timeoutInSeconds) !== null && _this$options$timeout !== void 0 ? _this$options$timeout : DEFAULT_TIMEOUT); + _context.next = 23; + return _this.simulate(); + case 23: + return _context.abrupt("return", _this); + case 24: + throw new AssembledTransaction.Errors.RestorationFailure("Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n".concat(JSON.stringify(result))); + case 25: + if (api/* Api */.j.isSimulationSuccess(_this.simulation)) { + _this.built = (0,transaction/* assembleTransaction */.X)(_this.built, _this.simulation).build(); + } + return _context.abrupt("return", _this); + case 27: + case "end": + return _context.stop(); + } + }, _callee); + }))); + assembled_transaction_defineProperty(this, "sign", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee2() { + var _this$options$timeout2; + var _ref4, + _ref4$force, + force, + _ref4$signTransaction, + signTransaction, + sigsNeeded, + timeoutInSeconds, + signOpts, + _yield$signTransactio, + signature, + error, + _args2 = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _ref4 = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref4$force = _ref4.force, force = _ref4$force === void 0 ? false : _ref4$force, _ref4$signTransaction = _ref4.signTransaction, signTransaction = _ref4$signTransaction === void 0 ? _this.options.signTransaction : _ref4$signTransaction; + if (_this.built) { + _context2.next = 3; + break; + } + throw new Error("Transaction has not yet been simulated"); + case 3: + if (!(!force && _this.isReadCall)) { + _context2.next = 5; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("This is a read call. It requires no signature or sending. " + "Use `force: true` to sign and send anyway."); + case 5: + if (signTransaction) { + _context2.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide a signTransaction function, either when calling " + "`signAndSend` or when initializing your Client"); + case 7: + sigsNeeded = _this.needsNonInvokerSigningBy().filter(function (id) { + return !id.startsWith('C'); + }); + if (!sigsNeeded.length) { + _context2.next = 10; + break; + } + throw new AssembledTransaction.Errors.NeedsMoreSignatures("Transaction requires signatures from ".concat(sigsNeeded, ". ") + "See `needsNonInvokerSigningBy` for details."); + case 10: + timeoutInSeconds = (_this$options$timeout2 = _this.options.timeoutInSeconds) !== null && _this$options$timeout2 !== void 0 ? _this$options$timeout2 : DEFAULT_TIMEOUT; + _this.built = lib.TransactionBuilder.cloneFrom(_this.built, { + fee: _this.built.fee, + timebounds: undefined, + sorobanData: _this.simulationData.transactionData + }).setTimeout(timeoutInSeconds).build(); + signOpts = { + networkPassphrase: _this.options.networkPassphrase + }; + if (_this.options.address) signOpts.address = _this.options.address; + if (_this.options.submit !== undefined) signOpts.submit = _this.options.submit; + if (_this.options.submitUrl) signOpts.submitUrl = _this.options.submitUrl; + _context2.next = 18; + return signTransaction(_this.built.toXDR(), signOpts); + case 18: + _yield$signTransactio = _context2.sent; + signature = _yield$signTransactio.signedTxXdr; + error = _yield$signTransactio.error; + _this.handleWalletError(error); + _this.signed = lib.TransactionBuilder.fromXDR(signature, _this.options.networkPassphrase); + case 23: + case "end": + return _context2.stop(); + } + }, _callee2); + }))); + assembled_transaction_defineProperty(this, "signAndSend", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee3() { + var _ref6, + _ref6$force, + force, + _ref6$signTransaction, + signTransaction, + originalSubmit, + _args3 = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _ref6 = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : {}, _ref6$force = _ref6.force, force = _ref6$force === void 0 ? false : _ref6$force, _ref6$signTransaction = _ref6.signTransaction, signTransaction = _ref6$signTransaction === void 0 ? _this.options.signTransaction : _ref6$signTransaction; + if (_this.signed) { + _context3.next = 10; + break; + } + originalSubmit = _this.options.submit; + if (_this.options.submit) { + _this.options.submit = false; + } + _context3.prev = 4; + _context3.next = 7; + return _this.sign({ + force: force, + signTransaction: signTransaction + }); + case 7: + _context3.prev = 7; + _this.options.submit = originalSubmit; + return _context3.finish(7); + case 10: + return _context3.abrupt("return", _this.send()); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3, null, [[4,, 7, 10]]); + }))); + assembled_transaction_defineProperty(this, "needsNonInvokerSigningBy", function () { + var _rawInvokeHostFunctio; + var _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref7$includeAlreadyS = _ref7.includeAlreadySigned, + includeAlreadySigned = _ref7$includeAlreadyS === void 0 ? false : _ref7$includeAlreadyS; + if (!_this.built) { + throw new Error("Transaction has not yet been simulated"); + } + if (!("operations" in _this.built)) { + throw new Error("Unexpected Transaction type; no operations: ".concat(JSON.stringify(_this.built))); + } + var rawInvokeHostFunctionOp = _this.built.operations[0]; + return _toConsumableArray(new Set(((_rawInvokeHostFunctio = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio !== void 0 ? _rawInvokeHostFunctio : []).filter(function (entry) { + return entry.credentials().switch() === lib.xdr.SorobanCredentialsType.sorobanCredentialsAddress() && (includeAlreadySigned || entry.credentials().address().signature().switch().name === "scvVoid"); + }).map(function (entry) { + return lib.Address.fromScAddress(entry.credentials().address().address()).toString(); + }))); + }); + assembled_transaction_defineProperty(this, "signAuthEntries", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee6() { + var _rawInvokeHostFunctio2; + var _ref9, + _ref9$expiration, + expiration, + _ref9$signAuthEntry, + signAuthEntry, + _ref9$address, + address, + _ref9$authorizeEntry, + authorizeEntry, + needsNonInvokerSigningBy, + rawInvokeHostFunctionOp, + authEntries, + _iterator, + _step, + _loop, + _ret, + _args7 = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee6$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _ref9 = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {}, _ref9$expiration = _ref9.expiration, expiration = _ref9$expiration === void 0 ? assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee4() { + return assembled_transaction_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this.server.getLatestLedger(); + case 2: + _context4.t0 = _context4.sent.sequence; + return _context4.abrupt("return", _context4.t0 + 100); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + }))() : _ref9$expiration, _ref9$signAuthEntry = _ref9.signAuthEntry, signAuthEntry = _ref9$signAuthEntry === void 0 ? _this.options.signAuthEntry : _ref9$signAuthEntry, _ref9$address = _ref9.address, address = _ref9$address === void 0 ? _this.options.publicKey : _ref9$address, _ref9$authorizeEntry = _ref9.authorizeEntry, authorizeEntry = _ref9$authorizeEntry === void 0 ? lib.authorizeEntry : _ref9$authorizeEntry; + if (_this.built) { + _context7.next = 3; + break; + } + throw new Error("Transaction has not yet been assembled or simulated"); + case 3: + if (!(authorizeEntry === lib.authorizeEntry)) { + _context7.next = 11; + break; + } + needsNonInvokerSigningBy = _this.needsNonInvokerSigningBy(); + if (!(needsNonInvokerSigningBy.length === 0)) { + _context7.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?"); + case 7: + if (!(needsNonInvokerSigningBy.indexOf(address !== null && address !== void 0 ? address : "") === -1)) { + _context7.next = 9; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("No auth entries for public key \"".concat(address, "\"")); + case 9: + if (signAuthEntry) { + _context7.next = 11; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`"); + case 11: + rawInvokeHostFunctionOp = _this.built.operations[0]; + authEntries = (_rawInvokeHostFunctio2 = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio2 !== void 0 ? _rawInvokeHostFunctio2 : []; + _iterator = _createForOfIteratorHelper(authEntries.entries()); + _context7.prev = 14; + _loop = assembled_transaction_regeneratorRuntime().mark(function _loop() { + var _step$value, i, entry, credentials, authEntryAddress, sign; + return assembled_transaction_regeneratorRuntime().wrap(function _loop$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _step$value = _slicedToArray(_step.value, 2), i = _step$value[0], entry = _step$value[1]; + credentials = lib.xdr.SorobanCredentials.fromXDR(entry.credentials().toXDR()); + if (!(credentials.switch() !== lib.xdr.SorobanCredentialsType.sorobanCredentialsAddress())) { + _context6.next = 4; + break; + } + return _context6.abrupt("return", 0); + case 4: + authEntryAddress = lib.Address.fromScAddress(credentials.address().address()).toString(); + if (!(authEntryAddress !== address)) { + _context6.next = 7; + break; + } + return _context6.abrupt("return", 0); + case 7: + sign = signAuthEntry !== null && signAuthEntry !== void 0 ? signAuthEntry : Promise.resolve; + _context6.t0 = authorizeEntry; + _context6.t1 = entry; + _context6.t2 = function () { + var _ref11 = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee5(preimage) { + var _yield$sign, signedAuthEntry, error; + return assembled_transaction_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return sign(preimage.toXDR("base64"), { + address: address + }); + case 2: + _yield$sign = _context5.sent; + signedAuthEntry = _yield$sign.signedAuthEntry; + error = _yield$sign.error; + _this.handleWalletError(error); + return _context5.abrupt("return", Buffer.from(signedAuthEntry, "base64")); + case 7: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x) { + return _ref11.apply(this, arguments); + }; + }(); + _context6.next = 13; + return expiration; + case 13: + _context6.t3 = _context6.sent; + _context6.t4 = _this.options.networkPassphrase; + _context6.next = 17; + return (0, _context6.t0)(_context6.t1, _context6.t2, _context6.t3, _context6.t4); + case 17: + authEntries[i] = _context6.sent; + case 18: + case "end": + return _context6.stop(); + } + }, _loop); + }); + _iterator.s(); + case 17: + if ((_step = _iterator.n()).done) { + _context7.next = 24; + break; + } + return _context7.delegateYield(_loop(), "t0", 19); + case 19: + _ret = _context7.t0; + if (!(_ret === 0)) { + _context7.next = 22; + break; + } + return _context7.abrupt("continue", 22); + case 22: + _context7.next = 17; + break; + case 24: + _context7.next = 29; + break; + case 26: + _context7.prev = 26; + _context7.t1 = _context7["catch"](14); + _iterator.e(_context7.t1); + case 29: + _context7.prev = 29; + _iterator.f(); + return _context7.finish(29); + case 32: + case "end": + return _context7.stop(); + } + }, _callee6, null, [[14, 26, 29, 32]]); + }))); + this.options = options; + this.options.simulate = (_this$options$simulat = this.options.simulate) !== null && _this$options$simulat !== void 0 ? _this$options$simulat : true; + this.server = new rpc.Server(this.options.rpcUrl, { + allowHttp: (_this$options$allowHt = this.options.allowHttp) !== null && _this$options$allowHt !== void 0 ? _this$options$allowHt : false + }); + } + return assembled_transaction_createClass(AssembledTransaction, [{ + key: "toJSON", + value: function toJSON() { + var _this$built; + return JSON.stringify({ + method: this.options.method, + tx: (_this$built = this.built) === null || _this$built === void 0 ? void 0 : _this$built.toXDR(), + simulationResult: { + auth: this.simulationData.result.auth.map(function (a) { + return a.toXDR("base64"); + }), + retval: this.simulationData.result.retval.toXDR("base64") + }, + simulationTransactionData: this.simulationData.transactionData.toXDR("base64") + }); + } + }, { + key: "toXDR", + value: function toXDR() { + var _this$built2; + if (!this.built) throw new Error("Transaction has not yet been simulated; " + "call `AssembledTransaction.simulate` first."); + return (_this$built2 = this.built) === null || _this$built2 === void 0 ? void 0 : _this$built2.toEnvelope().toXDR('base64'); + } + }, { + key: "handleWalletError", + value: function handleWalletError(error) { + if (!error) return; + var message = error.message, + code = error.code; + var fullMessage = "".concat(message).concat(error.ext ? " (".concat(error.ext.join(', '), ")") : ''); + switch (code) { + case -1: + throw new AssembledTransaction.Errors.InternalWalletError(fullMessage); + case -2: + throw new AssembledTransaction.Errors.ExternalServiceError(fullMessage); + case -3: + throw new AssembledTransaction.Errors.InvalidClientRequest(fullMessage); + case -4: + throw new AssembledTransaction.Errors.UserRejected(fullMessage); + default: + throw new Error("Unhandled error: ".concat(fullMessage)); + } + } + }, { + key: "simulationData", + get: function get() { + var _simulation$result; + if (this.simulationResult && this.simulationTransactionData) { + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + var simulation = this.simulation; + if (!simulation) { + throw new AssembledTransaction.Errors.NotYetSimulated("Transaction has not yet been simulated"); + } + if (api/* Api */.j.isSimulationError(simulation)) { + throw new AssembledTransaction.Errors.SimulationFailed("Transaction simulation failed: \"".concat(simulation.error, "\"")); + } + if (api/* Api */.j.isSimulationRestore(simulation)) { + throw new AssembledTransaction.Errors.ExpiredState("You need to restore some contract state before you can invoke this method.\n" + 'You can set `restore` to true in the method options in order to ' + 'automatically restore the contract state when needed.'); + } + this.simulationResult = (_simulation$result = simulation.result) !== null && _simulation$result !== void 0 ? _simulation$result : { + auth: [], + retval: lib.xdr.ScVal.scvVoid() + }; + this.simulationTransactionData = simulation.transactionData.build(); + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + }, { + key: "result", + get: function get() { + try { + if (!this.simulationData.result) { + throw new Error("No simulation result!"); + } + return this.options.parseResultXdr(this.simulationData.result.retval); + } catch (e) { + if (!implementsToString(e)) throw e; + var err = this.parseError(e.toString()); + if (err) return err; + throw e; + } + } + }, { + key: "parseError", + value: function parseError(errorMessage) { + if (!this.options.errorTypes) return undefined; + var match = errorMessage.match(contractErrorPattern); + if (!match) return undefined; + var i = parseInt(match[1], 10); + var err = this.options.errorTypes[i]; + if (!err) return undefined; + return new Err(err); + } + }, { + key: "send", + value: (function () { + var _send = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee7() { + var sent; + return assembled_transaction_regeneratorRuntime().wrap(function _callee7$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (this.signed) { + _context8.next = 2; + break; + } + throw new Error("The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead."); + case 2: + _context8.next = 4; + return SentTransaction.init(this); + case 4: + sent = _context8.sent; + return _context8.abrupt("return", sent); + case 6: + case "end": + return _context8.stop(); + } + }, _callee7, this); + })); + function send() { + return _send.apply(this, arguments); + } + return send; + }()) + }, { + key: "isReadCall", + get: function get() { + var authsCount = this.simulationData.result.auth.length; + var writeLength = this.simulationData.transactionData.resources().footprint().readWrite().length; + return authsCount === 0 && writeLength === 0; + } + }, { + key: "restoreFootprint", + value: (function () { + var _restoreFootprint = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee8(restorePreamble, account) { + var _account; + var restoreTx, sentTransaction; + return assembled_transaction_regeneratorRuntime().wrap(function _callee8$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + if (this.options.signTransaction) { + _context9.next = 2; + break; + } + throw new Error("For automatic restore to work you must provide a signTransaction function when initializing your Client"); + case 2: + if (!((_account = account) !== null && _account !== void 0)) { + _context9.next = 6; + break; + } + _context9.t0 = _account; + _context9.next = 9; + break; + case 6: + _context9.next = 8; + return getAccount(this.options, this.server); + case 8: + _context9.t0 = _context9.sent; + case 9: + account = _context9.t0; + _context9.next = 12; + return AssembledTransaction.buildFootprintRestoreTransaction(_objectSpread({}, this.options), restorePreamble.transactionData, account, restorePreamble.minResourceFee); + case 12: + restoreTx = _context9.sent; + _context9.next = 15; + return restoreTx.signAndSend(); + case 15: + sentTransaction = _context9.sent; + if (sentTransaction.getTransactionResponse) { + _context9.next = 18; + break; + } + throw new AssembledTransaction.Errors.RestorationFailure("The attempt at automatic restore failed. \n".concat(JSON.stringify(sentTransaction))); + case 18: + return _context9.abrupt("return", sentTransaction.getTransactionResponse); + case 19: + case "end": + return _context9.stop(); + } + }, _callee8, this); + })); + function restoreFootprint(_x2, _x3) { + return _restoreFootprint.apply(this, arguments); + } + return restoreFootprint; + }()) + }], [{ + key: "fromJSON", + value: function fromJSON(options, _ref12) { + var tx = _ref12.tx, + simulationResult = _ref12.simulationResult, + simulationTransactionData = _ref12.simulationTransactionData; + var txn = new AssembledTransaction(options); + txn.built = lib.TransactionBuilder.fromXDR(tx, options.networkPassphrase); + txn.simulationResult = { + auth: simulationResult.auth.map(function (a) { + return lib.xdr.SorobanAuthorizationEntry.fromXDR(a, "base64"); + }), + retval: lib.xdr.ScVal.fromXDR(simulationResult.retval, "base64") + }; + txn.simulationTransactionData = lib.xdr.SorobanTransactionData.fromXDR(simulationTransactionData, "base64"); + return txn; + } + }, { + key: "fromXDR", + value: function fromXDR(options, encodedXDR, spec) { + var _operation$func; + var envelope = lib.xdr.TransactionEnvelope.fromXDR(encodedXDR, "base64"); + var built = lib.TransactionBuilder.fromXDR(envelope, options.networkPassphrase); + var operation = built.operations[0]; + if (!(operation !== null && operation !== void 0 && (_operation$func = operation.func) !== null && _operation$func !== void 0 && _operation$func.value) || typeof operation.func.value !== 'function') { + throw new Error("Could not extract the method from the transaction envelope."); + } + var invokeContractArgs = operation.func.value(); + if (!(invokeContractArgs !== null && invokeContractArgs !== void 0 && invokeContractArgs.functionName)) { + throw new Error("Could not extract the method name from the transaction envelope."); + } + var method = invokeContractArgs.functionName().toString('utf-8'); + var txn = new AssembledTransaction(_objectSpread(_objectSpread({}, options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + txn.built = built; + return txn; + } + }, { + key: "build", + value: function build(options) { + var _options$args; + var contract = new lib.Contract(options.contractId); + return AssembledTransaction.buildWithOp(contract.call.apply(contract, [options.method].concat(_toConsumableArray((_options$args = options.args) !== null && _options$args !== void 0 ? _options$args : []))), options); + } + }, { + key: "buildWithOp", + value: (function () { + var _buildWithOp = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee9(operation, options) { + var _options$fee, _options$timeoutInSec; + var tx, account; + return assembled_transaction_regeneratorRuntime().wrap(function _callee9$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + tx = new AssembledTransaction(options); + _context10.next = 3; + return getAccount(options, tx.server); + case 3: + account = _context10.sent; + tx.raw = new lib.TransactionBuilder(account, { + fee: (_options$fee = options.fee) !== null && _options$fee !== void 0 ? _options$fee : lib.BASE_FEE, + networkPassphrase: options.networkPassphrase + }).setTimeout((_options$timeoutInSec = options.timeoutInSeconds) !== null && _options$timeoutInSec !== void 0 ? _options$timeoutInSec : DEFAULT_TIMEOUT).addOperation(operation); + if (!options.simulate) { + _context10.next = 8; + break; + } + _context10.next = 8; + return tx.simulate(); + case 8: + return _context10.abrupt("return", tx); + case 9: + case "end": + return _context10.stop(); + } + }, _callee9); + })); + function buildWithOp(_x4, _x5) { + return _buildWithOp.apply(this, arguments); + } + return buildWithOp; + }()) + }, { + key: "buildFootprintRestoreTransaction", + value: function () { + var _buildFootprintRestoreTransaction = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee10(options, sorobanData, account, fee) { + var _options$timeoutInSec2; + var tx; + return assembled_transaction_regeneratorRuntime().wrap(function _callee10$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + tx = new AssembledTransaction(options); + tx.raw = new lib.TransactionBuilder(account, { + fee: fee, + networkPassphrase: options.networkPassphrase + }).setSorobanData(sorobanData instanceof lib.SorobanDataBuilder ? sorobanData.build() : sorobanData).addOperation(lib.Operation.restoreFootprint({})).setTimeout((_options$timeoutInSec2 = options.timeoutInSeconds) !== null && _options$timeoutInSec2 !== void 0 ? _options$timeoutInSec2 : DEFAULT_TIMEOUT); + _context11.next = 4; + return tx.simulate({ + restore: false + }); + case 4: + return _context11.abrupt("return", tx); + case 5: + case "end": + return _context11.stop(); + } + }, _callee10); + })); + function buildFootprintRestoreTransaction(_x6, _x7, _x8, _x9) { + return _buildFootprintRestoreTransaction.apply(this, arguments); + } + return buildFootprintRestoreTransaction; + }() + }]); +}(); +assembled_transaction_defineProperty(AssembledTransaction, "Errors", { + ExpiredState: function (_Error) { + function ExpiredStateError() { + assembled_transaction_classCallCheck(this, ExpiredStateError); + return assembled_transaction_callSuper(this, ExpiredStateError, arguments); + } + assembled_transaction_inherits(ExpiredStateError, _Error); + return assembled_transaction_createClass(ExpiredStateError); + }(assembled_transaction_wrapNativeSuper(Error)), + RestorationFailure: function (_Error2) { + function RestoreFailureError() { + assembled_transaction_classCallCheck(this, RestoreFailureError); + return assembled_transaction_callSuper(this, RestoreFailureError, arguments); + } + assembled_transaction_inherits(RestoreFailureError, _Error2); + return assembled_transaction_createClass(RestoreFailureError); + }(assembled_transaction_wrapNativeSuper(Error)), + NeedsMoreSignatures: function (_Error3) { + function NeedsMoreSignaturesError() { + assembled_transaction_classCallCheck(this, NeedsMoreSignaturesError); + return assembled_transaction_callSuper(this, NeedsMoreSignaturesError, arguments); + } + assembled_transaction_inherits(NeedsMoreSignaturesError, _Error3); + return assembled_transaction_createClass(NeedsMoreSignaturesError); + }(assembled_transaction_wrapNativeSuper(Error)), + NoSignatureNeeded: function (_Error4) { + function NoSignatureNeededError() { + assembled_transaction_classCallCheck(this, NoSignatureNeededError); + return assembled_transaction_callSuper(this, NoSignatureNeededError, arguments); + } + assembled_transaction_inherits(NoSignatureNeededError, _Error4); + return assembled_transaction_createClass(NoSignatureNeededError); + }(assembled_transaction_wrapNativeSuper(Error)), + NoUnsignedNonInvokerAuthEntries: function (_Error5) { + function NoUnsignedNonInvokerAuthEntriesError() { + assembled_transaction_classCallCheck(this, NoUnsignedNonInvokerAuthEntriesError); + return assembled_transaction_callSuper(this, NoUnsignedNonInvokerAuthEntriesError, arguments); + } + assembled_transaction_inherits(NoUnsignedNonInvokerAuthEntriesError, _Error5); + return assembled_transaction_createClass(NoUnsignedNonInvokerAuthEntriesError); + }(assembled_transaction_wrapNativeSuper(Error)), + NoSigner: function (_Error6) { + function NoSignerError() { + assembled_transaction_classCallCheck(this, NoSignerError); + return assembled_transaction_callSuper(this, NoSignerError, arguments); + } + assembled_transaction_inherits(NoSignerError, _Error6); + return assembled_transaction_createClass(NoSignerError); + }(assembled_transaction_wrapNativeSuper(Error)), + NotYetSimulated: function (_Error7) { + function NotYetSimulatedError() { + assembled_transaction_classCallCheck(this, NotYetSimulatedError); + return assembled_transaction_callSuper(this, NotYetSimulatedError, arguments); + } + assembled_transaction_inherits(NotYetSimulatedError, _Error7); + return assembled_transaction_createClass(NotYetSimulatedError); + }(assembled_transaction_wrapNativeSuper(Error)), + FakeAccount: function (_Error8) { + function FakeAccountError() { + assembled_transaction_classCallCheck(this, FakeAccountError); + return assembled_transaction_callSuper(this, FakeAccountError, arguments); + } + assembled_transaction_inherits(FakeAccountError, _Error8); + return assembled_transaction_createClass(FakeAccountError); + }(assembled_transaction_wrapNativeSuper(Error)), + SimulationFailed: function (_Error9) { + function SimulationFailedError() { + assembled_transaction_classCallCheck(this, SimulationFailedError); + return assembled_transaction_callSuper(this, SimulationFailedError, arguments); + } + assembled_transaction_inherits(SimulationFailedError, _Error9); + return assembled_transaction_createClass(SimulationFailedError); + }(assembled_transaction_wrapNativeSuper(Error)), + InternalWalletError: function (_Error10) { + function InternalWalletError() { + assembled_transaction_classCallCheck(this, InternalWalletError); + return assembled_transaction_callSuper(this, InternalWalletError, arguments); + } + assembled_transaction_inherits(InternalWalletError, _Error10); + return assembled_transaction_createClass(InternalWalletError); + }(assembled_transaction_wrapNativeSuper(Error)), + ExternalServiceError: function (_Error11) { + function ExternalServiceError() { + assembled_transaction_classCallCheck(this, ExternalServiceError); + return assembled_transaction_callSuper(this, ExternalServiceError, arguments); + } + assembled_transaction_inherits(ExternalServiceError, _Error11); + return assembled_transaction_createClass(ExternalServiceError); + }(assembled_transaction_wrapNativeSuper(Error)), + InvalidClientRequest: function (_Error12) { + function InvalidClientRequestError() { + assembled_transaction_classCallCheck(this, InvalidClientRequestError); + return assembled_transaction_callSuper(this, InvalidClientRequestError, arguments); + } + assembled_transaction_inherits(InvalidClientRequestError, _Error12); + return assembled_transaction_createClass(InvalidClientRequestError); + }(assembled_transaction_wrapNativeSuper(Error)), + UserRejected: function (_Error13) { + function UserRejectedError() { + assembled_transaction_classCallCheck(this, UserRejectedError); + return assembled_transaction_callSuper(this, UserRejectedError, arguments); + } + assembled_transaction_inherits(UserRejectedError, _Error13); + return assembled_transaction_createClass(UserRejectedError); + }(assembled_transaction_wrapNativeSuper(Error)) +}); +;// ./src/contract/basic_node_signer.ts +/* provided dependency */ var basic_node_signer_Buffer = __webpack_require__(8287)["Buffer"]; +function basic_node_signer_typeof(o) { "@babel/helpers - typeof"; return basic_node_signer_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, basic_node_signer_typeof(o); } +function basic_node_signer_regeneratorRuntime() { "use strict"; basic_node_signer_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == basic_node_signer_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(basic_node_signer_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function basic_node_signer_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function basic_node_signer_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { basic_node_signer_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { basic_node_signer_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + +var basicNodeSigner = function basicNodeSigner(keypair, networkPassphrase) { + return { + signTransaction: function () { + var _signTransaction = basic_node_signer_asyncToGenerator(basic_node_signer_regeneratorRuntime().mark(function _callee(xdr, opts) { + var t; + return basic_node_signer_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + t = lib.TransactionBuilder.fromXDR(xdr, (opts === null || opts === void 0 ? void 0 : opts.networkPassphrase) || networkPassphrase); + t.sign(keypair); + return _context.abrupt("return", { + signedTxXdr: t.toXDR(), + signerAddress: keypair.publicKey() + }); + case 3: + case "end": + return _context.stop(); + } + }, _callee); + })); + function signTransaction(_x, _x2) { + return _signTransaction.apply(this, arguments); + } + return signTransaction; + }(), + signAuthEntry: function () { + var _signAuthEntry = basic_node_signer_asyncToGenerator(basic_node_signer_regeneratorRuntime().mark(function _callee2(authEntry) { + var signedAuthEntry; + return basic_node_signer_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + signedAuthEntry = keypair.sign((0,lib.hash)(basic_node_signer_Buffer.from(authEntry, "base64"))).toString("base64"); + return _context2.abrupt("return", { + signedAuthEntry: signedAuthEntry, + signerAddress: keypair.publicKey() + }); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function signAuthEntry(_x3) { + return _signAuthEntry.apply(this, arguments); + } + return signAuthEntry; + }() + }; +}; +;// ./src/contract/spec.ts +/* provided dependency */ var spec_Buffer = __webpack_require__(8287)["Buffer"]; +function spec_ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function spec_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? spec_ownKeys(Object(t), !0).forEach(function (r) { spec_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : spec_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function spec_typeof(o) { "@babel/helpers - typeof"; return spec_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, spec_typeof(o); } +function spec_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function spec_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, spec_toPropertyKey(o.key), o); } } +function spec_createClass(e, r, t) { return r && spec_defineProperties(e.prototype, r), t && spec_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function spec_defineProperty(e, r, t) { return (r = spec_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function spec_toPropertyKey(t) { var i = spec_toPrimitive(t, "string"); return "symbol" == spec_typeof(i) ? i : i + ""; } +function spec_toPrimitive(t, r) { if ("object" != spec_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != spec_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function spec_slicedToArray(r, e) { return spec_arrayWithHoles(r) || spec_iterableToArrayLimit(r, e) || spec_unsupportedIterableToArray(r, e) || spec_nonIterableRest(); } +function spec_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function spec_unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return spec_arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? spec_arrayLikeToArray(r, a) : void 0; } } +function spec_arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function spec_iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function spec_arrayWithHoles(r) { if (Array.isArray(r)) return r; } + + +function enumToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + var title = aCase.name().toString(); + var desc = aCase.doc().toString(); + oneOf.push({ + description: desc, + title: title, + enum: [aCase.value()], + type: "number" + }); + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +function isNumeric(field) { + return /^\d+$/.test(field.name().toString()); +} +function readObj(args, input) { + var inputName = input.name().toString(); + var entry = Object.entries(args).find(function (_ref) { + var _ref2 = spec_slicedToArray(_ref, 1), + name = _ref2[0]; + return name === inputName; + }); + if (!entry) { + throw new Error("Missing field ".concat(inputName)); + } + return entry[1]; +} +function findCase(name) { + return function matches(entry) { + switch (entry.switch().value) { + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var tuple = entry.tupleCase(); + return tuple.name().toString() === name; + } + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var voidCase = entry.voidCase(); + return voidCase.name().toString() === name; + } + default: + return false; + } + }; +} +function stringToScVal(str, ty) { + switch (ty.value) { + case lib.xdr.ScSpecType.scSpecTypeString().value: + return lib.xdr.ScVal.scvString(str); + case lib.xdr.ScSpecType.scSpecTypeSymbol().value: + return lib.xdr.ScVal.scvSymbol(str); + case lib.xdr.ScSpecType.scSpecTypeAddress().value: + { + var addr = lib.Address.fromString(str); + return lib.xdr.ScVal.scvAddress(addr.toScAddress()); + } + case lib.xdr.ScSpecType.scSpecTypeU64().value: + return new lib.XdrLargeInt("u64", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeI64().value: + return new lib.XdrLargeInt("i64", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeU128().value: + return new lib.XdrLargeInt("u128", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeI128().value: + return new lib.XdrLargeInt("i128", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeU256().value: + return new lib.XdrLargeInt("u256", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeI256().value: + return new lib.XdrLargeInt("i256", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeBytes().value: + case lib.xdr.ScSpecType.scSpecTypeBytesN().value: + return lib.xdr.ScVal.scvBytes(spec_Buffer.from(str, "base64")); + default: + throw new TypeError("invalid type ".concat(ty.name, " specified for string value")); + } +} +var PRIMITIVE_DEFINITONS = { + U32: { + type: "integer", + minimum: 0, + maximum: 4294967295 + }, + I32: { + type: "integer", + minimum: -2147483648, + maximum: 2147483647 + }, + U64: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 20 + }, + I64: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 21 + }, + U128: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 39 + }, + I128: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 40 + }, + U256: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 78 + }, + I256: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 79 + }, + Address: { + type: "string", + format: "address", + description: "Address can be a public key or contract id" + }, + ScString: { + type: "string", + description: "ScString is a string" + }, + ScSymbol: { + type: "string", + description: "ScString is a string" + }, + DataUrl: { + type: "string", + pattern: "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$" + } +}; +function typeRef(typeDef) { + var t = typeDef.switch(); + var value = t.value; + var ref; + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVal().value: + { + ref = "Val"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeBool().value: + { + return { + type: "boolean" + }; + } + case lib.xdr.ScSpecType.scSpecTypeVoid().value: + { + return { + type: "null" + }; + } + case lib.xdr.ScSpecType.scSpecTypeError().value: + { + ref = "Error"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU32().value: + { + ref = "U32"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI32().value: + { + ref = "I32"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU64().value: + { + ref = "U64"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI64().value: + { + ref = "I64"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeTimepoint().value: + { + throw new Error("Timepoint type not supported"); + ref = "Timepoint"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeDuration().value: + { + throw new Error("Duration not supported"); + ref = "Duration"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU128().value: + { + ref = "U128"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI128().value: + { + ref = "I128"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU256().value: + { + ref = "U256"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI256().value: + { + ref = "I256"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeBytes().value: + { + ref = "DataUrl"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeString().value: + { + ref = "ScString"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeSymbol().value: + { + ref = "ScSymbol"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeAddress().value: + { + ref = "Address"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeOption().value: + { + var opt = typeDef.option(); + return typeRef(opt.valueType()); + } + case lib.xdr.ScSpecType.scSpecTypeResult().value: + { + break; + } + case lib.xdr.ScSpecType.scSpecTypeVec().value: + { + var arr = typeDef.vec(); + var reference = typeRef(arr.elementType()); + return { + type: "array", + items: reference + }; + } + case lib.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = typeDef.map(); + var items = [typeRef(map.keyType()), typeRef(map.valueType())]; + return { + type: "array", + items: { + type: "array", + items: items, + minItems: 2, + maxItems: 2 + } + }; + } + case lib.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tuple = typeDef.tuple(); + var minItems = tuple.valueTypes().length; + var maxItems = minItems; + var _items = tuple.valueTypes().map(typeRef); + return { + type: "array", + items: _items, + minItems: minItems, + maxItems: maxItems + }; + } + case lib.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var _arr = typeDef.bytesN(); + return { + $ref: "#/definitions/DataUrl", + maxLength: _arr.n() + }; + } + case lib.xdr.ScSpecType.scSpecTypeUdt().value: + { + var udt = typeDef.udt(); + ref = udt.name().toString(); + break; + } + } + return { + $ref: "#/definitions/".concat(ref) + }; +} +function isRequired(typeDef) { + return typeDef.switch().value !== lib.xdr.ScSpecType.scSpecTypeOption().value; +} +function argsAndRequired(input) { + var properties = {}; + var required = []; + input.forEach(function (arg) { + var aType = arg.type(); + var name = arg.name().toString(); + properties[name] = typeRef(aType); + if (isRequired(aType)) { + required.push(name); + } + }); + var res = { + properties: properties + }; + if (required.length > 0) { + res.required = required; + } + return res; +} +function structToJsonSchema(udt) { + var fields = udt.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + var items = fields.map(function (_, i) { + return typeRef(fields[i].type()); + }); + return { + type: "array", + items: items, + minItems: fields.length, + maxItems: fields.length + }; + } + var description = udt.doc().toString(); + var _argsAndRequired = argsAndRequired(fields), + properties = _argsAndRequired.properties, + required = _argsAndRequired.required; + properties.additionalProperties = false; + return { + description: description, + properties: properties, + required: required, + type: "object" + }; +} +function functionToJsonSchema(func) { + var _argsAndRequired2 = argsAndRequired(func.inputs()), + properties = _argsAndRequired2.properties, + required = _argsAndRequired2.required; + var args = { + additionalProperties: false, + properties: properties, + type: "object" + }; + if ((required === null || required === void 0 ? void 0 : required.length) > 0) { + args.required = required; + } + var input = { + properties: { + args: args + } + }; + var outputs = func.outputs(); + var output = outputs.length > 0 ? typeRef(outputs[0]) : typeRef(lib.xdr.ScSpecTypeDef.scSpecTypeVoid()); + var description = func.doc().toString(); + if (description.length > 0) { + input.description = description; + } + input.additionalProperties = false; + output.additionalProperties = false; + return { + input: input, + output: output + }; +} +function unionToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + switch (aCase.switch().value) { + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var c = aCase.voidCase(); + var title = c.name().toString(); + oneOf.push({ + type: "object", + title: title, + properties: { + tag: title + }, + additionalProperties: false, + required: ["tag"] + }); + break; + } + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var _c = aCase.tupleCase(); + var _title = _c.name().toString(); + oneOf.push({ + type: "object", + title: _title, + properties: { + tag: _title, + values: { + type: "array", + items: _c.type().map(typeRef) + } + }, + required: ["tag", "values"], + additionalProperties: false + }); + } + } + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +var Spec = function () { + function Spec(entries) { + spec_classCallCheck(this, Spec); + spec_defineProperty(this, "entries", []); + if (entries.length === 0) { + throw new Error("Contract spec must have at least one entry"); + } + var entry = entries[0]; + if (typeof entry === "string") { + this.entries = entries.map(function (s) { + return lib.xdr.ScSpecEntry.fromXDR(s, "base64"); + }); + } else { + this.entries = entries; + } + } + return spec_createClass(Spec, [{ + key: "funcs", + value: function funcs() { + return this.entries.filter(function (entry) { + return entry.switch().value === lib.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value; + }).map(function (entry) { + return entry.functionV0(); + }); + } + }, { + key: "getFunc", + value: function getFunc(name) { + var entry = this.findEntry(name); + if (entry.switch().value !== lib.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value) { + throw new Error("".concat(name, " is not a function")); + } + return entry.functionV0(); + } + }, { + key: "funcArgsToScVals", + value: function funcArgsToScVals(name, args) { + var _this = this; + var fn = this.getFunc(name); + return fn.inputs().map(function (input) { + return _this.nativeToScVal(readObj(args, input), input.type()); + }); + } + }, { + key: "funcResToNative", + value: function funcResToNative(name, val_or_base64) { + var val = typeof val_or_base64 === "string" ? lib.xdr.ScVal.fromXDR(val_or_base64, "base64") : val_or_base64; + var func = this.getFunc(name); + var outputs = func.outputs(); + if (outputs.length === 0) { + var type = val.switch(); + if (type.value !== lib.xdr.ScValType.scvVoid().value) { + throw new Error("Expected void, got ".concat(type.name)); + } + return null; + } + if (outputs.length > 1) { + throw new Error("Multiple outputs not supported"); + } + var output = outputs[0]; + if (output.switch().value === lib.xdr.ScSpecType.scSpecTypeResult().value) { + return new Ok(this.scValToNative(val, output.result().okType())); + } + return this.scValToNative(val, output); + } + }, { + key: "findEntry", + value: function findEntry(name) { + var entry = this.entries.find(function (e) { + return e.value().name().toString() === name; + }); + if (!entry) { + throw new Error("no such entry: ".concat(name)); + } + return entry; + } + }, { + key: "nativeToScVal", + value: function nativeToScVal(val, ty) { + var _this2 = this; + var t = ty.switch(); + var value = t.value; + if (t.value === lib.xdr.ScSpecType.scSpecTypeUdt().value) { + var udt = ty.udt(); + return this.nativeToUdt(val, udt.name().toString()); + } + if (value === lib.xdr.ScSpecType.scSpecTypeOption().value) { + var opt = ty.option(); + if (val === undefined) { + return lib.xdr.ScVal.scvVoid(); + } + return this.nativeToScVal(val, opt.valueType()); + } + switch (spec_typeof(val)) { + case "object": + { + var _val$constructor$name, _val$constructor; + if (val === null) { + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVoid().value: + return lib.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was null")); + } + } + if (val instanceof lib.xdr.ScVal) { + return val; + } + if (val instanceof lib.Address) { + if (ty.switch().value !== lib.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.toScVal(); + } + if (val instanceof lib.Contract) { + if (ty.switch().value !== lib.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.address().toScVal(); + } + if (val instanceof Uint8Array || spec_Buffer.isBuffer(val)) { + var copy = Uint8Array.from(val); + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var bytesN = ty.bytesN(); + if (copy.length !== bytesN.n()) { + throw new TypeError("expected ".concat(bytesN.n(), " bytes, but got ").concat(copy.length)); + } + return lib.xdr.ScVal.scvBytes(copy); + } + case lib.xdr.ScSpecType.scSpecTypeBytes().value: + return lib.xdr.ScVal.scvBytes(copy); + default: + throw new TypeError("invalid type (".concat(ty, ") specified for Bytes and BytesN")); + } + } + if (Array.isArray(val)) { + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVec().value: + { + var vec = ty.vec(); + var elementType = vec.elementType(); + return lib.xdr.ScVal.scvVec(val.map(function (v) { + return _this2.nativeToScVal(v, elementType); + })); + } + case lib.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tup = ty.tuple(); + var valTypes = tup.valueTypes(); + if (val.length !== valTypes.length) { + throw new TypeError("Tuple expects ".concat(valTypes.length, " values, but ").concat(val.length, " were provided")); + } + return lib.xdr.ScVal.scvVec(val.map(function (v, i) { + return _this2.nativeToScVal(v, valTypes[i]); + })); + } + case lib.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = ty.map(); + var keyType = map.keyType(); + var valueType = map.valueType(); + return lib.xdr.ScVal.scvMap(val.map(function (entry) { + var key = _this2.nativeToScVal(entry[0], keyType); + var mapVal = _this2.nativeToScVal(entry[1], valueType); + return new lib.xdr.ScMapEntry({ + key: key, + val: mapVal + }); + })); + } + default: + throw new TypeError("Type ".concat(ty, " was not vec, but value was Array")); + } + } + if (val.constructor === Map) { + if (value !== lib.xdr.ScSpecType.scSpecTypeMap().value) { + throw new TypeError("Type ".concat(ty, " was not map, but value was Map")); + } + var scMap = ty.map(); + var _map = val; + var entries = []; + var values = _map.entries(); + var res = values.next(); + while (!res.done) { + var _res$value = spec_slicedToArray(res.value, 2), + k = _res$value[0], + v = _res$value[1]; + var key = this.nativeToScVal(k, scMap.keyType()); + var mapval = this.nativeToScVal(v, scMap.valueType()); + entries.push(new lib.xdr.ScMapEntry({ + key: key, + val: mapval + })); + res = values.next(); + } + return lib.xdr.ScVal.scvMap(entries); + } + if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : "") !== "Object") { + var _val$constructor2; + throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")")); + } + throw new TypeError("Received object ".concat(val, " did not match the provided type ").concat(ty)); + } + case "number": + case "bigint": + { + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeU32().value: + return lib.xdr.ScVal.scvU32(val); + case lib.xdr.ScSpecType.scSpecTypeI32().value: + return lib.xdr.ScVal.scvI32(val); + case lib.xdr.ScSpecType.scSpecTypeU64().value: + case lib.xdr.ScSpecType.scSpecTypeI64().value: + case lib.xdr.ScSpecType.scSpecTypeU128().value: + case lib.xdr.ScSpecType.scSpecTypeI128().value: + case lib.xdr.ScSpecType.scSpecTypeU256().value: + case lib.xdr.ScSpecType.scSpecTypeI256().value: + { + var intType = t.name.substring(10).toLowerCase(); + return new lib.XdrLargeInt(intType, val).toScVal(); + } + default: + throw new TypeError("invalid type (".concat(ty, ") specified for integer")); + } + } + case "string": + return stringToScVal(val, t); + case "boolean": + { + if (value !== lib.xdr.ScSpecType.scSpecTypeBool().value) { + throw TypeError("Type ".concat(ty, " was not bool, but value was bool")); + } + return lib.xdr.ScVal.scvBool(val); + } + case "undefined": + { + if (!ty) { + return lib.xdr.ScVal.scvVoid(); + } + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVoid().value: + case lib.xdr.ScSpecType.scSpecTypeOption().value: + return lib.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was undefined")); + } + } + case "function": + return this.nativeToScVal(val(), ty); + default: + throw new TypeError("failed to convert typeof ".concat(spec_typeof(val), " (").concat(val, ")")); + } + } + }, { + key: "nativeToUdt", + value: function nativeToUdt(val, name) { + var entry = this.findEntry(name); + switch (entry.switch()) { + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + if (typeof val !== "number") { + throw new TypeError("expected number for enum ".concat(name, ", but got ").concat(spec_typeof(val))); + } + return this.nativeToEnum(val, entry.udtEnumV0()); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.nativeToStruct(val, entry.udtStructV0()); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.nativeToUnion(val, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(name)); + } + } + }, { + key: "nativeToUnion", + value: function nativeToUnion(val, union_) { + var _this3 = this; + var entryName = val.tag; + var caseFound = union_.cases().find(function (entry) { + var caseN = entry.value().name().toString(); + return caseN === entryName; + }); + if (!caseFound) { + throw new TypeError("no such enum entry: ".concat(entryName, " in ").concat(union_)); + } + var key = lib.xdr.ScVal.scvSymbol(entryName); + switch (caseFound.switch()) { + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0(): + { + return lib.xdr.ScVal.scvVec([key]); + } + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0(): + { + var types = caseFound.tupleCase().type(); + if (Array.isArray(val.values)) { + if (val.values.length !== types.length) { + throw new TypeError("union ".concat(union_, " expects ").concat(types.length, " values, but got ").concat(val.values.length)); + } + var scvals = val.values.map(function (v, i) { + return _this3.nativeToScVal(v, types[i]); + }); + scvals.unshift(key); + return lib.xdr.ScVal.scvVec(scvals); + } + throw new Error("failed to parse union case ".concat(caseFound, " with ").concat(val)); + } + default: + throw new Error("failed to parse union ".concat(union_, " with ").concat(val)); + } + } + }, { + key: "nativeToStruct", + value: function nativeToStruct(val, struct) { + var _this4 = this; + var fields = struct.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + return lib.xdr.ScVal.scvVec(fields.map(function (_, i) { + return _this4.nativeToScVal(val[i], fields[i].type()); + })); + } + return lib.xdr.ScVal.scvMap(fields.map(function (field) { + var name = field.name().toString(); + return new lib.xdr.ScMapEntry({ + key: _this4.nativeToScVal(name, lib.xdr.ScSpecTypeDef.scSpecTypeSymbol()), + val: _this4.nativeToScVal(val[name], field.type()) + }); + })); + } + }, { + key: "nativeToEnum", + value: function nativeToEnum(val, enum_) { + if (enum_.cases().some(function (entry) { + return entry.value() === val; + })) { + return lib.xdr.ScVal.scvU32(val); + } + throw new TypeError("no such enum entry: ".concat(val, " in ").concat(enum_)); + } + }, { + key: "scValStrToNative", + value: function scValStrToNative(scv, typeDef) { + return this.scValToNative(lib.xdr.ScVal.fromXDR(scv, "base64"), typeDef); + } + }, { + key: "scValToNative", + value: function scValToNative(scv, typeDef) { + var _this5 = this; + var t = typeDef.switch(); + var value = t.value; + if (value === lib.xdr.ScSpecType.scSpecTypeUdt().value) { + return this.scValUdtToNative(scv, typeDef.udt()); + } + switch (scv.switch().value) { + case lib.xdr.ScValType.scvVoid().value: + return undefined; + case lib.xdr.ScValType.scvU64().value: + case lib.xdr.ScValType.scvI64().value: + case lib.xdr.ScValType.scvU128().value: + case lib.xdr.ScValType.scvI128().value: + case lib.xdr.ScValType.scvU256().value: + case lib.xdr.ScValType.scvI256().value: + return (0,lib.scValToBigInt)(scv); + case lib.xdr.ScValType.scvVec().value: + { + if (value === lib.xdr.ScSpecType.scSpecTypeVec().value) { + var _scv$vec; + var vec = typeDef.vec(); + return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(function (elm) { + return _this5.scValToNative(elm, vec.elementType()); + }); + } + if (value === lib.xdr.ScSpecType.scSpecTypeTuple().value) { + var _scv$vec2; + var tuple = typeDef.tuple(); + var valTypes = tuple.valueTypes(); + return ((_scv$vec2 = scv.vec()) !== null && _scv$vec2 !== void 0 ? _scv$vec2 : []).map(function (elm, i) { + return _this5.scValToNative(elm, valTypes[i]); + }); + } + throw new TypeError("Type ".concat(typeDef, " was not vec, but ").concat(scv, " is")); + } + case lib.xdr.ScValType.scvAddress().value: + return lib.Address.fromScVal(scv).toString(); + case lib.xdr.ScValType.scvMap().value: + { + var _scv$map; + var map = (_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []; + if (value === lib.xdr.ScSpecType.scSpecTypeMap().value) { + var typed = typeDef.map(); + var keyType = typed.keyType(); + var valueType = typed.valueType(); + var res = map.map(function (entry) { + return [_this5.scValToNative(entry.key(), keyType), _this5.scValToNative(entry.val(), valueType)]; + }); + return res; + } + throw new TypeError("ScSpecType ".concat(t.name, " was not map, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + case lib.xdr.ScValType.scvBool().value: + case lib.xdr.ScValType.scvU32().value: + case lib.xdr.ScValType.scvI32().value: + case lib.xdr.ScValType.scvBytes().value: + return scv.value(); + case lib.xdr.ScValType.scvString().value: + case lib.xdr.ScValType.scvSymbol().value: + { + var _scv$value; + if (value !== lib.xdr.ScSpecType.scSpecTypeString().value && value !== lib.xdr.ScSpecType.scSpecTypeSymbol().value) { + throw new Error("ScSpecType ".concat(t.name, " was not string or symbol, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + return (_scv$value = scv.value()) === null || _scv$value === void 0 ? void 0 : _scv$value.toString(); + } + case lib.xdr.ScValType.scvTimepoint().value: + case lib.xdr.ScValType.scvDuration().value: + return (0,lib.scValToBigInt)(lib.xdr.ScVal.scvU64(scv.u64())); + default: + throw new TypeError("failed to convert ".concat(JSON.stringify(scv, null, 2), " to native type from type ").concat(t.name)); + } + } + }, { + key: "scValUdtToNative", + value: function scValUdtToNative(scv, udt) { + var entry = this.findEntry(udt.name().toString()); + switch (entry.switch()) { + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + return this.enumToNative(scv); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.structToNative(scv, entry.udtStructV0()); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.unionToNative(scv, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(udt.name().toString(), ": ").concat(entry)); + } + } + }, { + key: "unionToNative", + value: function unionToNative(val, udt) { + var _this6 = this; + var vec = val.vec(); + if (!vec) { + throw new Error("".concat(JSON.stringify(val, null, 2), " is not a vec")); + } + if (vec.length === 0 && udt.cases.length !== 0) { + throw new Error("".concat(val, " has length 0, but the there are at least one case in the union")); + } + var name = vec[0].sym().toString(); + if (vec[0].switch().value !== lib.xdr.ScValType.scvSymbol().value) { + throw new Error("{vec[0]} is not a symbol"); + } + var entry = udt.cases().find(findCase(name)); + if (!entry) { + throw new Error("failed to find entry ".concat(name, " in union {udt.name().toString()}")); + } + var res = { + tag: name + }; + if (entry.switch().value === lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value) { + var tuple = entry.tupleCase(); + var ty = tuple.type(); + var values = ty.map(function (e, i) { + return _this6.scValToNative(vec[i + 1], e); + }); + res.values = values; + } + return res; + } + }, { + key: "structToNative", + value: function structToNative(val, udt) { + var _this7 = this, + _val$map; + var res = {}; + var fields = udt.fields(); + if (fields.some(isNumeric)) { + var _val$vec; + var r = (_val$vec = val.vec()) === null || _val$vec === void 0 ? void 0 : _val$vec.map(function (entry, i) { + return _this7.scValToNative(entry, fields[i].type()); + }); + return r; + } + (_val$map = val.map()) === null || _val$map === void 0 || _val$map.forEach(function (entry, i) { + var field = fields[i]; + res[field.name().toString()] = _this7.scValToNative(entry.val(), field.type()); + }); + return res; + } + }, { + key: "enumToNative", + value: function enumToNative(scv) { + if (scv.switch().value !== lib.xdr.ScValType.scvU32().value) { + throw new Error("Enum must have a u32 value"); + } + var num = scv.u32(); + return num; + } + }, { + key: "errorCases", + value: function errorCases() { + return this.entries.filter(function (entry) { + return entry.switch().value === lib.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value; + }).flatMap(function (entry) { + return entry.value().cases(); + }); + } + }, { + key: "jsonSchema", + value: function jsonSchema(funcName) { + var definitions = {}; + this.entries.forEach(function (entry) { + switch (entry.switch().value) { + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0().value: + { + var udt = entry.udtEnumV0(); + definitions[udt.name().toString()] = enumToJsonSchema(udt); + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0().value: + { + var _udt = entry.udtStructV0(); + definitions[_udt.name().toString()] = structToJsonSchema(_udt); + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0().value: + { + var _udt2 = entry.udtUnionV0(); + definitions[_udt2.name().toString()] = unionToJsonSchema(_udt2); + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value: + { + var fn = entry.functionV0(); + var fnName = fn.name().toString(); + var _functionToJsonSchema = functionToJsonSchema(fn), + input = _functionToJsonSchema.input; + definitions[fnName] = input; + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value: + {} + } + }); + var res = { + $schema: "http://json-schema.org/draft-07/schema#", + definitions: spec_objectSpread(spec_objectSpread({}, PRIMITIVE_DEFINITONS), definitions) + }; + if (funcName) { + res.$ref = "#/definitions/".concat(funcName); + } + return res; + } + }]); +}(); +;// ./src/contract/client.ts +/* provided dependency */ var client_Buffer = __webpack_require__(8287)["Buffer"]; +function client_typeof(o) { "@babel/helpers - typeof"; return client_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, client_typeof(o); } +var _excluded = ["method"], + _excluded2 = ["wasmHash", "salt", "format", "fee", "timeoutInSeconds", "simulate"]; +function client_regeneratorRuntime() { "use strict"; client_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == client_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(client_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function client_ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function client_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? client_ownKeys(Object(t), !0).forEach(function (r) { client_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : client_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } +function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; } +function client_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function client_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, client_toPropertyKey(o.key), o); } } +function client_createClass(e, r, t) { return r && client_defineProperties(e.prototype, r), t && client_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function client_defineProperty(e, r, t) { return (r = client_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function client_toPropertyKey(t) { var i = client_toPrimitive(t, "string"); return "symbol" == client_typeof(i) ? i : i + ""; } +function client_toPrimitive(t, r) { if ("object" != client_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != client_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function client_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function client_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { client_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { client_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + + + + + +var CONSTRUCTOR_FUNC = "__constructor"; +function specFromWasm(_x) { + return _specFromWasm.apply(this, arguments); +} +function _specFromWasm() { + _specFromWasm = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee5(wasm) { + var wasmModule, xdrSections, bufferSection, specEntryArray, spec; + return client_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return WebAssembly.compile(wasm); + case 2: + wasmModule = _context5.sent; + xdrSections = WebAssembly.Module.customSections(wasmModule, "contractspecv0"); + if (!(xdrSections.length === 0)) { + _context5.next = 6; + break; + } + throw new Error("Could not obtain contract spec from wasm"); + case 6: + bufferSection = client_Buffer.from(xdrSections[0]); + specEntryArray = processSpecEntryStream(bufferSection); + spec = new Spec(specEntryArray); + return _context5.abrupt("return", spec); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _specFromWasm.apply(this, arguments); +} +function specFromWasmHash(_x2, _x3) { + return _specFromWasmHash.apply(this, arguments); +} +function _specFromWasmHash() { + _specFromWasmHash = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee6(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args6 = arguments; + return client_regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + format = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context6.next = 3; + break; + } + throw new TypeError("options must contain rpcUrl"); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new rpc.Server(rpcUrl, serverOpts); + _context6.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context6.sent; + return _context6.abrupt("return", specFromWasm(wasm)); + case 10: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _specFromWasmHash.apply(this, arguments); +} +var Client = function () { + function Client(spec, options) { + var _this = this; + client_classCallCheck(this, Client); + client_defineProperty(this, "txFromJSON", function (json) { + var _JSON$parse = JSON.parse(json), + method = _JSON$parse.method, + tx = _objectWithoutProperties(_JSON$parse, _excluded); + return AssembledTransaction.fromJSON(client_objectSpread(client_objectSpread({}, _this.options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return _this.spec.funcResToNative(method, result); + } + }), tx); + }); + client_defineProperty(this, "txFromXDR", function (xdrBase64) { + return AssembledTransaction.fromXDR(_this.options, xdrBase64, _this.spec); + }); + this.spec = spec; + this.options = options; + this.spec.funcs().forEach(function (xdrFn) { + var method = xdrFn.name().toString(); + if (method === CONSTRUCTOR_FUNC) { + return; + } + var assembleTransaction = function assembleTransaction(args, methodOptions) { + return AssembledTransaction.build(client_objectSpread(client_objectSpread(client_objectSpread({ + method: method, + args: args && spec.funcArgsToScVals(method, args) + }, options), methodOptions), {}, { + errorTypes: spec.errorCases().reduce(function (acc, curr) { + return client_objectSpread(client_objectSpread({}, acc), {}, client_defineProperty({}, curr.value(), { + message: curr.doc().toString() + })); + }, {}), + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + }; + _this[method] = spec.getFunc(method).inputs().length === 0 ? function (opts) { + return assembleTransaction(undefined, opts); + } : assembleTransaction; + }); + } + return client_createClass(Client, null, [{ + key: "deploy", + value: function () { + var _deploy = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee(args, options) { + var wasmHash, salt, format, fee, timeoutInSeconds, simulate, clientOptions, spec, operation; + return client_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + wasmHash = options.wasmHash, salt = options.salt, format = options.format, fee = options.fee, timeoutInSeconds = options.timeoutInSeconds, simulate = options.simulate, clientOptions = _objectWithoutProperties(options, _excluded2); + _context.next = 3; + return specFromWasmHash(wasmHash, clientOptions, format); + case 3: + spec = _context.sent; + operation = lib.Operation.createCustomContract({ + address: new lib.Address(options.publicKey), + wasmHash: typeof wasmHash === "string" ? client_Buffer.from(wasmHash, format !== null && format !== void 0 ? format : "hex") : wasmHash, + salt: salt, + constructorArgs: args ? spec.funcArgsToScVals(CONSTRUCTOR_FUNC, args) : [] + }); + return _context.abrupt("return", AssembledTransaction.buildWithOp(operation, client_objectSpread(client_objectSpread({ + fee: fee, + timeoutInSeconds: timeoutInSeconds, + simulate: simulate + }, clientOptions), {}, { + contractId: "ignored", + method: CONSTRUCTOR_FUNC, + parseResultXdr: function parseResultXdr(result) { + return new Client(spec, client_objectSpread(client_objectSpread({}, clientOptions), {}, { + contractId: lib.Address.fromScVal(result).toString() + })); + } + }))); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + function deploy(_x4, _x5) { + return _deploy.apply(this, arguments); + } + return deploy; + }() + }, { + key: "fromWasmHash", + value: (function () { + var _fromWasmHash = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee2(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args2 = arguments; + return client_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + format = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context2.next = 3; + break; + } + throw new TypeError('options must contain rpcUrl'); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new rpc.Server(rpcUrl, serverOpts); + _context2.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context2.sent; + return _context2.abrupt("return", Client.fromWasm(wasm, options)); + case 10: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function fromWasmHash(_x6, _x7) { + return _fromWasmHash.apply(this, arguments); + } + return fromWasmHash; + }()) + }, { + key: "fromWasm", + value: (function () { + var _fromWasm = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee3(wasm, options) { + var spec; + return client_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return specFromWasm(wasm); + case 2: + spec = _context3.sent; + return _context3.abrupt("return", new Client(spec, options)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + function fromWasm(_x8, _x9) { + return _fromWasm.apply(this, arguments); + } + return fromWasm; + }()) + }, { + key: "from", + value: (function () { + var _from = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee4(options) { + var rpcUrl, contractId, allowHttp, serverOpts, server, wasm; + return client_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(!options || !options.rpcUrl || !options.contractId)) { + _context4.next = 2; + break; + } + throw new TypeError('options must contain rpcUrl and contractId'); + case 2: + rpcUrl = options.rpcUrl, contractId = options.contractId, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new rpc.Server(rpcUrl, serverOpts); + _context4.next = 7; + return server.getContractWasmByContractId(contractId); + case 7: + wasm = _context4.sent; + return _context4.abrupt("return", Client.fromWasm(wasm, options)); + case 9: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function from(_x10) { + return _from.apply(this, arguments); + } + return from; + }()) + }]); +}(); +;// ./src/contract/index.ts + + + + + + + + +/***/ }), + +/***/ 5976: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Cu: () => (/* reexport */ AccountRequiresMemoError), + v7: () => (/* reexport */ BadRequestError), + nS: () => (/* reexport */ BadResponseError), + Dr: () => (/* reexport */ NetworkError), + m_: () => (/* reexport */ NotFoundError) +}); + +;// ./src/errors/network.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var NetworkError = function (_Error) { + function NetworkError(message, response) { + var _this; + _classCallCheck(this, NetworkError); + var trueProto = (this instanceof NetworkError ? this.constructor : void 0).prototype; + _this = _callSuper(this, NetworkError, [message]); + _this.__proto__ = trueProto; + _this.constructor = NetworkError; + _this.response = response; + return _this; + } + _inherits(NetworkError, _Error); + return _createClass(NetworkError, [{ + key: "getResponse", + value: function getResponse() { + return this.response; + } + }]); +}(_wrapNativeSuper(Error)); +;// ./src/errors/not_found.ts +function not_found_typeof(o) { "@babel/helpers - typeof"; return not_found_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, not_found_typeof(o); } +function not_found_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, not_found_toPropertyKey(o.key), o); } } +function not_found_createClass(e, r, t) { return r && not_found_defineProperties(e.prototype, r), t && not_found_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function not_found_toPropertyKey(t) { var i = not_found_toPrimitive(t, "string"); return "symbol" == not_found_typeof(i) ? i : i + ""; } +function not_found_toPrimitive(t, r) { if ("object" != not_found_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != not_found_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function not_found_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function not_found_callSuper(t, o, e) { return o = not_found_getPrototypeOf(o), not_found_possibleConstructorReturn(t, not_found_isNativeReflectConstruct() ? Reflect.construct(o, e || [], not_found_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function not_found_possibleConstructorReturn(t, e) { if (e && ("object" == not_found_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return not_found_assertThisInitialized(t); } +function not_found_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function not_found_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (not_found_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function not_found_getPrototypeOf(t) { return not_found_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, not_found_getPrototypeOf(t); } +function not_found_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && not_found_setPrototypeOf(t, e); } +function not_found_setPrototypeOf(t, e) { return not_found_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, not_found_setPrototypeOf(t, e); } + +var NotFoundError = function (_NetworkError) { + function NotFoundError(message, response) { + var _this; + not_found_classCallCheck(this, NotFoundError); + var trueProto = (this instanceof NotFoundError ? this.constructor : void 0).prototype; + _this = not_found_callSuper(this, NotFoundError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = NotFoundError; + _this.name = "NotFoundError"; + return _this; + } + not_found_inherits(NotFoundError, _NetworkError); + return not_found_createClass(NotFoundError); +}(NetworkError); +;// ./src/errors/bad_request.ts +function bad_request_typeof(o) { "@babel/helpers - typeof"; return bad_request_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, bad_request_typeof(o); } +function bad_request_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, bad_request_toPropertyKey(o.key), o); } } +function bad_request_createClass(e, r, t) { return r && bad_request_defineProperties(e.prototype, r), t && bad_request_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function bad_request_toPropertyKey(t) { var i = bad_request_toPrimitive(t, "string"); return "symbol" == bad_request_typeof(i) ? i : i + ""; } +function bad_request_toPrimitive(t, r) { if ("object" != bad_request_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != bad_request_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function bad_request_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function bad_request_callSuper(t, o, e) { return o = bad_request_getPrototypeOf(o), bad_request_possibleConstructorReturn(t, bad_request_isNativeReflectConstruct() ? Reflect.construct(o, e || [], bad_request_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function bad_request_possibleConstructorReturn(t, e) { if (e && ("object" == bad_request_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return bad_request_assertThisInitialized(t); } +function bad_request_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function bad_request_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (bad_request_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function bad_request_getPrototypeOf(t) { return bad_request_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, bad_request_getPrototypeOf(t); } +function bad_request_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && bad_request_setPrototypeOf(t, e); } +function bad_request_setPrototypeOf(t, e) { return bad_request_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, bad_request_setPrototypeOf(t, e); } + +var BadRequestError = function (_NetworkError) { + function BadRequestError(message, response) { + var _this; + bad_request_classCallCheck(this, BadRequestError); + var trueProto = (this instanceof BadRequestError ? this.constructor : void 0).prototype; + _this = bad_request_callSuper(this, BadRequestError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadRequestError; + _this.name = "BadRequestError"; + return _this; + } + bad_request_inherits(BadRequestError, _NetworkError); + return bad_request_createClass(BadRequestError); +}(NetworkError); +;// ./src/errors/bad_response.ts +function bad_response_typeof(o) { "@babel/helpers - typeof"; return bad_response_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, bad_response_typeof(o); } +function bad_response_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, bad_response_toPropertyKey(o.key), o); } } +function bad_response_createClass(e, r, t) { return r && bad_response_defineProperties(e.prototype, r), t && bad_response_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function bad_response_toPropertyKey(t) { var i = bad_response_toPrimitive(t, "string"); return "symbol" == bad_response_typeof(i) ? i : i + ""; } +function bad_response_toPrimitive(t, r) { if ("object" != bad_response_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != bad_response_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function bad_response_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function bad_response_callSuper(t, o, e) { return o = bad_response_getPrototypeOf(o), bad_response_possibleConstructorReturn(t, bad_response_isNativeReflectConstruct() ? Reflect.construct(o, e || [], bad_response_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function bad_response_possibleConstructorReturn(t, e) { if (e && ("object" == bad_response_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return bad_response_assertThisInitialized(t); } +function bad_response_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function bad_response_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (bad_response_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function bad_response_getPrototypeOf(t) { return bad_response_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, bad_response_getPrototypeOf(t); } +function bad_response_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && bad_response_setPrototypeOf(t, e); } +function bad_response_setPrototypeOf(t, e) { return bad_response_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, bad_response_setPrototypeOf(t, e); } + +var BadResponseError = function (_NetworkError) { + function BadResponseError(message, response) { + var _this; + bad_response_classCallCheck(this, BadResponseError); + var trueProto = (this instanceof BadResponseError ? this.constructor : void 0).prototype; + _this = bad_response_callSuper(this, BadResponseError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadResponseError; + _this.name = "BadResponseError"; + return _this; + } + bad_response_inherits(BadResponseError, _NetworkError); + return bad_response_createClass(BadResponseError); +}(NetworkError); +;// ./src/errors/account_requires_memo.ts +function account_requires_memo_typeof(o) { "@babel/helpers - typeof"; return account_requires_memo_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, account_requires_memo_typeof(o); } +function account_requires_memo_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, account_requires_memo_toPropertyKey(o.key), o); } } +function account_requires_memo_createClass(e, r, t) { return r && account_requires_memo_defineProperties(e.prototype, r), t && account_requires_memo_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function account_requires_memo_toPropertyKey(t) { var i = account_requires_memo_toPrimitive(t, "string"); return "symbol" == account_requires_memo_typeof(i) ? i : i + ""; } +function account_requires_memo_toPrimitive(t, r) { if ("object" != account_requires_memo_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != account_requires_memo_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function account_requires_memo_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function account_requires_memo_callSuper(t, o, e) { return o = account_requires_memo_getPrototypeOf(o), account_requires_memo_possibleConstructorReturn(t, account_requires_memo_isNativeReflectConstruct() ? Reflect.construct(o, e || [], account_requires_memo_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function account_requires_memo_possibleConstructorReturn(t, e) { if (e && ("object" == account_requires_memo_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return account_requires_memo_assertThisInitialized(t); } +function account_requires_memo_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function account_requires_memo_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && account_requires_memo_setPrototypeOf(t, e); } +function account_requires_memo_wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return account_requires_memo_wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !account_requires_memo_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return account_requires_memo_construct(t, arguments, account_requires_memo_getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), account_requires_memo_setPrototypeOf(Wrapper, t); }, account_requires_memo_wrapNativeSuper(t); } +function account_requires_memo_construct(t, e, r) { if (account_requires_memo_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && account_requires_memo_setPrototypeOf(p, r.prototype), p; } +function account_requires_memo_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (account_requires_memo_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function account_requires_memo_isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function account_requires_memo_setPrototypeOf(t, e) { return account_requires_memo_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, account_requires_memo_setPrototypeOf(t, e); } +function account_requires_memo_getPrototypeOf(t) { return account_requires_memo_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, account_requires_memo_getPrototypeOf(t); } +var AccountRequiresMemoError = function (_Error) { + function AccountRequiresMemoError(message, accountId, operationIndex) { + var _this; + account_requires_memo_classCallCheck(this, AccountRequiresMemoError); + var trueProto = (this instanceof AccountRequiresMemoError ? this.constructor : void 0).prototype; + _this = account_requires_memo_callSuper(this, AccountRequiresMemoError, [message]); + _this.__proto__ = trueProto; + _this.constructor = AccountRequiresMemoError; + _this.name = "AccountRequiresMemoError"; + _this.accountId = accountId; + _this.operationIndex = operationIndex; + return _this; + } + account_requires_memo_inherits(AccountRequiresMemoError, _Error); + return account_requires_memo_createClass(AccountRequiresMemoError); +}(account_requires_memo_wrapNativeSuper(Error)); +;// ./src/errors/index.ts + + + + + + +/***/ }), + +/***/ 7600: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Api: () => (/* reexport */ Api), + FEDERATION_RESPONSE_MAX_SIZE: () => (/* reexport */ FEDERATION_RESPONSE_MAX_SIZE), + Server: () => (/* reexport */ FederationServer) +}); + +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js +var URI = __webpack_require__(4193); +var URI_default = /*#__PURE__*/__webpack_require__.n(URI); +// EXTERNAL MODULE: ./src/config.ts +var config = __webpack_require__(8732); +// EXTERNAL MODULE: ./src/errors/index.ts + 5 modules +var errors = __webpack_require__(5976); +// EXTERNAL MODULE: ./src/stellartoml/index.ts +var stellartoml = __webpack_require__(3898); +// EXTERNAL MODULE: ./src/http-client/index.ts +var http_client = __webpack_require__(6371); +;// ./src/federation/server.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + +var FEDERATION_RESPONSE_MAX_SIZE = 100 * 1024; +var FederationServer = function () { + function FederationServer(serverURL, domain) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + _classCallCheck(this, FederationServer); + this.serverURL = URI_default()(serverURL); + this.domain = domain; + var allowHttp = typeof opts.allowHttp === "undefined" ? config/* Config */.T.isAllowHttp() : opts.allowHttp; + this.timeout = typeof opts.timeout === "undefined" ? config/* Config */.T.getTimeout() : opts.timeout; + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure federation server"); + } + } + return _createClass(FederationServer, [{ + key: "resolveAddress", + value: (function () { + var _resolveAddress = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(address) { + var stellarAddress, url; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + stellarAddress = address; + if (!(address.indexOf("*") < 0)) { + _context.next = 5; + break; + } + if (this.domain) { + _context.next = 4; + break; + } + return _context.abrupt("return", Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object."))); + case 4: + stellarAddress = "".concat(address, "*").concat(this.domain); + case 5: + url = this.serverURL.query({ + type: "name", + q: stellarAddress + }); + return _context.abrupt("return", this._sendRequest(url)); + case 7: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function resolveAddress(_x) { + return _resolveAddress.apply(this, arguments); + } + return resolveAddress; + }()) + }, { + key: "resolveAccountId", + value: (function () { + var _resolveAccountId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(accountId) { + var url; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + url = this.serverURL.query({ + type: "id", + q: accountId + }); + return _context2.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function resolveAccountId(_x2) { + return _resolveAccountId.apply(this, arguments); + } + return resolveAccountId; + }()) + }, { + key: "resolveTransactionId", + value: (function () { + var _resolveTransactionId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(transactionId) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = this.serverURL.query({ + type: "txid", + q: transactionId + }); + return _context3.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function resolveTransactionId(_x3) { + return _resolveTransactionId.apply(this, arguments); + } + return resolveTransactionId; + }()) + }, { + key: "_sendRequest", + value: function () { + var _sendRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(url) { + var timeout; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + timeout = this.timeout; + return _context4.abrupt("return", http_client/* httpClient */.ok.get(url.toString(), { + maxContentLength: FEDERATION_RESPONSE_MAX_SIZE, + timeout: timeout + }).then(function (response) { + if (typeof response.data.memo !== "undefined" && typeof response.data.memo !== "string") { + throw new Error("memo value should be of type string"); + } + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + if (response.message.match(/^maxContentLength size/)) { + throw new Error("federation response exceeds allowed size of ".concat(FEDERATION_RESPONSE_MAX_SIZE)); + } else { + return Promise.reject(response); + } + } else { + return Promise.reject(new errors/* BadResponseError */.nS("Server query failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + } + })); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function _sendRequest(_x4) { + return _sendRequest2.apply(this, arguments); + } + return _sendRequest; + }() + }], [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(value) { + var opts, + addressParts, + _addressParts, + domain, + federationServer, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {}; + if (!(value.indexOf("*") < 0)) { + _context5.next = 5; + break; + } + if (lib.StrKey.isValidEd25519PublicKey(value)) { + _context5.next = 4; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Account ID"))); + case 4: + return _context5.abrupt("return", Promise.resolve({ + account_id: value + })); + case 5: + addressParts = value.split("*"); + _addressParts = _slicedToArray(addressParts, 2), domain = _addressParts[1]; + if (!(addressParts.length !== 2 || !domain)) { + _context5.next = 9; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Stellar address"))); + case 9: + _context5.next = 11; + return FederationServer.createForDomain(domain, opts); + case 11: + federationServer = _context5.sent; + return _context5.abrupt("return", federationServer.resolveAddress(value)); + case 13: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function resolve(_x5) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }, { + key: "createForDomain", + value: (function () { + var _createForDomain = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(domain) { + var opts, + tomlObject, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : {}; + _context6.next = 3; + return stellartoml.Resolver.resolve(domain, opts); + case 3: + tomlObject = _context6.sent; + if (tomlObject.FEDERATION_SERVER) { + _context6.next = 6; + break; + } + return _context6.abrupt("return", Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field"))); + case 6: + return _context6.abrupt("return", new FederationServer(tomlObject.FEDERATION_SERVER, domain, opts)); + case 7: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function createForDomain(_x6) { + return _createForDomain.apply(this, arguments); + } + return createForDomain; + }()) + }]); +}(); +;// ./src/federation/api.ts +var Api; +;// ./src/federation/index.ts + + + +/***/ }), + +/***/ 8242: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Api: () => (/* binding */ Api) +/* harmony export */ }); +var Api; + +/***/ }), + +/***/ 8733: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + AccountResponse: () => (/* reexport */ AccountResponse), + AxiosClient: () => (/* reexport */ horizon_axios_client), + HorizonApi: () => (/* reexport */ HorizonApi), + SERVER_TIME_MAP: () => (/* reexport */ SERVER_TIME_MAP), + Server: () => (/* reexport */ HorizonServer), + ServerApi: () => (/* reexport */ ServerApi), + "default": () => (/* binding */ horizon), + getCurrentServerTime: () => (/* reexport */ getCurrentServerTime) +}); + +;// ./src/horizon/horizon_api.ts +var HorizonApi; +(function (_HorizonApi) { + var LiquidityPoolType = function (LiquidityPoolType) { + LiquidityPoolType["constantProduct"] = "constant_product"; + return LiquidityPoolType; + }({}); + _HorizonApi.LiquidityPoolType = LiquidityPoolType; + var OperationResponseType = function (OperationResponseType) { + OperationResponseType["createAccount"] = "create_account"; + OperationResponseType["payment"] = "payment"; + OperationResponseType["pathPayment"] = "path_payment_strict_receive"; + OperationResponseType["createPassiveOffer"] = "create_passive_sell_offer"; + OperationResponseType["manageOffer"] = "manage_sell_offer"; + OperationResponseType["setOptions"] = "set_options"; + OperationResponseType["changeTrust"] = "change_trust"; + OperationResponseType["allowTrust"] = "allow_trust"; + OperationResponseType["accountMerge"] = "account_merge"; + OperationResponseType["inflation"] = "inflation"; + OperationResponseType["manageData"] = "manage_data"; + OperationResponseType["bumpSequence"] = "bump_sequence"; + OperationResponseType["manageBuyOffer"] = "manage_buy_offer"; + OperationResponseType["pathPaymentStrictSend"] = "path_payment_strict_send"; + OperationResponseType["createClaimableBalance"] = "create_claimable_balance"; + OperationResponseType["claimClaimableBalance"] = "claim_claimable_balance"; + OperationResponseType["beginSponsoringFutureReserves"] = "begin_sponsoring_future_reserves"; + OperationResponseType["endSponsoringFutureReserves"] = "end_sponsoring_future_reserves"; + OperationResponseType["revokeSponsorship"] = "revoke_sponsorship"; + OperationResponseType["clawback"] = "clawback"; + OperationResponseType["clawbackClaimableBalance"] = "clawback_claimable_balance"; + OperationResponseType["setTrustLineFlags"] = "set_trust_line_flags"; + OperationResponseType["liquidityPoolDeposit"] = "liquidity_pool_deposit"; + OperationResponseType["liquidityPoolWithdraw"] = "liquidity_pool_withdraw"; + OperationResponseType["invokeHostFunction"] = "invoke_host_function"; + OperationResponseType["bumpFootprintExpiration"] = "bump_footprint_expiration"; + OperationResponseType["restoreFootprint"] = "restore_footprint"; + return OperationResponseType; + }({}); + _HorizonApi.OperationResponseType = OperationResponseType; + var OperationResponseTypeI = function (OperationResponseTypeI) { + OperationResponseTypeI[OperationResponseTypeI["createAccount"] = 0] = "createAccount"; + OperationResponseTypeI[OperationResponseTypeI["payment"] = 1] = "payment"; + OperationResponseTypeI[OperationResponseTypeI["pathPayment"] = 2] = "pathPayment"; + OperationResponseTypeI[OperationResponseTypeI["createPassiveOffer"] = 3] = "createPassiveOffer"; + OperationResponseTypeI[OperationResponseTypeI["manageOffer"] = 4] = "manageOffer"; + OperationResponseTypeI[OperationResponseTypeI["setOptions"] = 5] = "setOptions"; + OperationResponseTypeI[OperationResponseTypeI["changeTrust"] = 6] = "changeTrust"; + OperationResponseTypeI[OperationResponseTypeI["allowTrust"] = 7] = "allowTrust"; + OperationResponseTypeI[OperationResponseTypeI["accountMerge"] = 8] = "accountMerge"; + OperationResponseTypeI[OperationResponseTypeI["inflation"] = 9] = "inflation"; + OperationResponseTypeI[OperationResponseTypeI["manageData"] = 10] = "manageData"; + OperationResponseTypeI[OperationResponseTypeI["bumpSequence"] = 11] = "bumpSequence"; + OperationResponseTypeI[OperationResponseTypeI["manageBuyOffer"] = 12] = "manageBuyOffer"; + OperationResponseTypeI[OperationResponseTypeI["pathPaymentStrictSend"] = 13] = "pathPaymentStrictSend"; + OperationResponseTypeI[OperationResponseTypeI["createClaimableBalance"] = 14] = "createClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["claimClaimableBalance"] = 15] = "claimClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["beginSponsoringFutureReserves"] = 16] = "beginSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["endSponsoringFutureReserves"] = 17] = "endSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["revokeSponsorship"] = 18] = "revokeSponsorship"; + OperationResponseTypeI[OperationResponseTypeI["clawback"] = 19] = "clawback"; + OperationResponseTypeI[OperationResponseTypeI["clawbackClaimableBalance"] = 20] = "clawbackClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["setTrustLineFlags"] = 21] = "setTrustLineFlags"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolDeposit"] = 22] = "liquidityPoolDeposit"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolWithdraw"] = 23] = "liquidityPoolWithdraw"; + OperationResponseTypeI[OperationResponseTypeI["invokeHostFunction"] = 24] = "invokeHostFunction"; + OperationResponseTypeI[OperationResponseTypeI["bumpFootprintExpiration"] = 25] = "bumpFootprintExpiration"; + OperationResponseTypeI[OperationResponseTypeI["restoreFootprint"] = 26] = "restoreFootprint"; + return OperationResponseTypeI; + }({}); + _HorizonApi.OperationResponseTypeI = OperationResponseTypeI; + ; + var TransactionFailedResultCodes = function (TransactionFailedResultCodes) { + TransactionFailedResultCodes["TX_FAILED"] = "tx_failed"; + TransactionFailedResultCodes["TX_BAD_SEQ"] = "tx_bad_seq"; + TransactionFailedResultCodes["TX_BAD_AUTH"] = "tx_bad_auth"; + TransactionFailedResultCodes["TX_BAD_AUTH_EXTRA"] = "tx_bad_auth_extra"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_SUCCESS"] = "tx_fee_bump_inner_success"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_FAILED"] = "tx_fee_bump_inner_failed"; + TransactionFailedResultCodes["TX_NOT_SUPPORTED"] = "tx_not_supported"; + TransactionFailedResultCodes["TX_SUCCESS"] = "tx_success"; + TransactionFailedResultCodes["TX_TOO_EARLY"] = "tx_too_early"; + TransactionFailedResultCodes["TX_TOO_LATE"] = "tx_too_late"; + TransactionFailedResultCodes["TX_MISSING_OPERATION"] = "tx_missing_operation"; + TransactionFailedResultCodes["TX_INSUFFICIENT_BALANCE"] = "tx_insufficient_balance"; + TransactionFailedResultCodes["TX_NO_SOURCE_ACCOUNT"] = "tx_no_source_account"; + TransactionFailedResultCodes["TX_INSUFFICIENT_FEE"] = "tx_insufficient_fee"; + TransactionFailedResultCodes["TX_INTERNAL_ERROR"] = "tx_internal_error"; + return TransactionFailedResultCodes; + }({}); + _HorizonApi.TransactionFailedResultCodes = TransactionFailedResultCodes; +})(HorizonApi || (HorizonApi = {})); +;// ./src/horizon/types/effects.ts +var effects_EffectType = function (EffectType) { + EffectType[EffectType["account_created"] = 0] = "account_created"; + EffectType[EffectType["account_removed"] = 1] = "account_removed"; + EffectType[EffectType["account_credited"] = 2] = "account_credited"; + EffectType[EffectType["account_debited"] = 3] = "account_debited"; + EffectType[EffectType["account_thresholds_updated"] = 4] = "account_thresholds_updated"; + EffectType[EffectType["account_home_domain_updated"] = 5] = "account_home_domain_updated"; + EffectType[EffectType["account_flags_updated"] = 6] = "account_flags_updated"; + EffectType[EffectType["account_inflation_destination_updated"] = 7] = "account_inflation_destination_updated"; + EffectType[EffectType["signer_created"] = 10] = "signer_created"; + EffectType[EffectType["signer_removed"] = 11] = "signer_removed"; + EffectType[EffectType["signer_updated"] = 12] = "signer_updated"; + EffectType[EffectType["trustline_created"] = 20] = "trustline_created"; + EffectType[EffectType["trustline_removed"] = 21] = "trustline_removed"; + EffectType[EffectType["trustline_updated"] = 22] = "trustline_updated"; + EffectType[EffectType["trustline_authorized"] = 23] = "trustline_authorized"; + EffectType[EffectType["trustline_deauthorized"] = 24] = "trustline_deauthorized"; + EffectType[EffectType["trustline_authorized_to_maintain_liabilities"] = 25] = "trustline_authorized_to_maintain_liabilities"; + EffectType[EffectType["trustline_flags_updated"] = 26] = "trustline_flags_updated"; + EffectType[EffectType["offer_created"] = 30] = "offer_created"; + EffectType[EffectType["offer_removed"] = 31] = "offer_removed"; + EffectType[EffectType["offer_updated"] = 32] = "offer_updated"; + EffectType[EffectType["trade"] = 33] = "trade"; + EffectType[EffectType["data_created"] = 40] = "data_created"; + EffectType[EffectType["data_removed"] = 41] = "data_removed"; + EffectType[EffectType["data_updated"] = 42] = "data_updated"; + EffectType[EffectType["sequence_bumped"] = 43] = "sequence_bumped"; + EffectType[EffectType["claimable_balance_created"] = 50] = "claimable_balance_created"; + EffectType[EffectType["claimable_balance_claimant_created"] = 51] = "claimable_balance_claimant_created"; + EffectType[EffectType["claimable_balance_claimed"] = 52] = "claimable_balance_claimed"; + EffectType[EffectType["account_sponsorship_created"] = 60] = "account_sponsorship_created"; + EffectType[EffectType["account_sponsorship_updated"] = 61] = "account_sponsorship_updated"; + EffectType[EffectType["account_sponsorship_removed"] = 62] = "account_sponsorship_removed"; + EffectType[EffectType["trustline_sponsorship_created"] = 63] = "trustline_sponsorship_created"; + EffectType[EffectType["trustline_sponsorship_updated"] = 64] = "trustline_sponsorship_updated"; + EffectType[EffectType["trustline_sponsorship_removed"] = 65] = "trustline_sponsorship_removed"; + EffectType[EffectType["data_sponsorship_created"] = 66] = "data_sponsorship_created"; + EffectType[EffectType["data_sponsorship_updated"] = 67] = "data_sponsorship_updated"; + EffectType[EffectType["data_sponsorship_removed"] = 68] = "data_sponsorship_removed"; + EffectType[EffectType["claimable_balance_sponsorship_created"] = 69] = "claimable_balance_sponsorship_created"; + EffectType[EffectType["claimable_balance_sponsorship_updated"] = 70] = "claimable_balance_sponsorship_updated"; + EffectType[EffectType["claimable_balance_sponsorship_removed"] = 71] = "claimable_balance_sponsorship_removed"; + EffectType[EffectType["signer_sponsorship_created"] = 72] = "signer_sponsorship_created"; + EffectType[EffectType["signer_sponsorship_updated"] = 73] = "signer_sponsorship_updated"; + EffectType[EffectType["signer_sponsorship_removed"] = 74] = "signer_sponsorship_removed"; + EffectType[EffectType["claimable_balance_clawed_back"] = 80] = "claimable_balance_clawed_back"; + EffectType[EffectType["liquidity_pool_deposited"] = 90] = "liquidity_pool_deposited"; + EffectType[EffectType["liquidity_pool_withdrew"] = 91] = "liquidity_pool_withdrew"; + EffectType[EffectType["liquidity_pool_trade"] = 92] = "liquidity_pool_trade"; + EffectType[EffectType["liquidity_pool_created"] = 93] = "liquidity_pool_created"; + EffectType[EffectType["liquidity_pool_removed"] = 94] = "liquidity_pool_removed"; + EffectType[EffectType["liquidity_pool_revoked"] = 95] = "liquidity_pool_revoked"; + EffectType[EffectType["contract_credited"] = 96] = "contract_credited"; + EffectType[EffectType["contract_debited"] = 97] = "contract_debited"; + return EffectType; +}({}); +;// ./src/horizon/server_api.ts + + +var ServerApi; +(function (_ServerApi) { + var EffectType = _ServerApi.EffectType = effects_EffectType; + var TradeType = function (TradeType) { + TradeType["all"] = "all"; + TradeType["liquidityPools"] = "liquidity_pool"; + TradeType["orderbook"] = "orderbook"; + return TradeType; + }({}); + _ServerApi.TradeType = TradeType; + var OperationResponseType = HorizonApi.OperationResponseType; + var OperationResponseTypeI = HorizonApi.OperationResponseTypeI; +})(ServerApi || (ServerApi = {})); +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +;// ./src/horizon/account_response.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + +var AccountResponse = function () { + function AccountResponse(response) { + var _this = this; + _classCallCheck(this, AccountResponse); + this._baseAccount = new lib.Account(response.account_id, response.sequence); + Object.entries(response).forEach(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + _this[key] = value; + }); + } + return _createClass(AccountResponse, [{ + key: "accountId", + value: function accountId() { + return this._baseAccount.accountId(); + } + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this._baseAccount.sequenceNumber(); + } + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + this._baseAccount.incrementSequenceNumber(); + this.sequence = this._baseAccount.sequenceNumber(); + } + }]); +}(); +;// ./node_modules/bignumber.js/bignumber.mjs +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + +var + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + +/* + * Create and return a BigNumber constructor. + */ +function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + P[Symbol.toStringTag] = 'BigNumber'; + + // Node.js v10.12.0+ + P[Symbol.for('nodejs.util.inspect.custom')] = P.valueOf; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; +} + + +// PRIVATE HELPER FUNCTIONS + +// These functions don't need access to variables, +// e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + +function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; +} + + +// Return a coefficient array as a string of base 10 digits. +function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); +} + + +// Compare the value of BigNumbers x and y. +function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; +} + + +/* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ +function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } +} + + +// Assumes finite n. +function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; +} + + +function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; +} + + +function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; +} + + +// EXPORT + + +var BigNumber = clone(); + +/* harmony default export */ const bignumber = (BigNumber); + +// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js +var URI = __webpack_require__(4193); +var URI_default = /*#__PURE__*/__webpack_require__.n(URI); +// EXTERNAL MODULE: ./node_modules/urijs/src/URITemplate.js +var URITemplate = __webpack_require__(9127); +var URITemplate_default = /*#__PURE__*/__webpack_require__.n(URITemplate); +// EXTERNAL MODULE: ./src/errors/index.ts + 5 modules +var errors = __webpack_require__(5976); +// EXTERNAL MODULE: ./src/http-client/index.ts +var http_client = __webpack_require__(6371); +;// ./src/horizon/horizon_axios_client.ts +function horizon_axios_client_typeof(o) { "@babel/helpers - typeof"; return horizon_axios_client_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, horizon_axios_client_typeof(o); } + + +var version = "13.1.0"; +var SERVER_TIME_MAP = {}; +var AxiosClient = (0,http_client/* create */.vt)({ + headers: { + "X-Client-Name": "js-stellar-sdk", + "X-Client-Version": version + } +}); +function toSeconds(ms) { + return Math.floor(ms / 1000); +} +AxiosClient.interceptors.response.use(function (response) { + var hostname = URI_default()(response.config.url).hostname(); + var serverTime = 0; + if (response.headers instanceof Headers) { + var dateHeader = response.headers.get('date'); + if (dateHeader) { + serverTime = toSeconds(Date.parse(dateHeader)); + } + } else if (horizon_axios_client_typeof(response.headers) === 'object' && 'date' in response.headers) { + var headers = response.headers; + if (typeof headers.date === 'string') { + serverTime = toSeconds(Date.parse(headers.date)); + } + } + var localTimeRecorded = toSeconds(new Date().getTime()); + if (!Number.isNaN(serverTime)) { + SERVER_TIME_MAP[hostname] = { + serverTime: serverTime, + localTimeRecorded: localTimeRecorded + }; + } + return response; +}); +/* harmony default export */ const horizon_axios_client = (AxiosClient); +function getCurrentServerTime(hostname) { + var entry = SERVER_TIME_MAP[hostname]; + if (!entry || !entry.localTimeRecorded || !entry.serverTime) { + return null; + } + var serverTime = entry.serverTime, + localTimeRecorded = entry.localTimeRecorded; + var currentTime = toSeconds(new Date().getTime()); + if (currentTime - localTimeRecorded > 60 * 5) { + return null; + } + return currentTime - localTimeRecorded + serverTime; +} +;// ./src/horizon/call_builder.ts +function call_builder_typeof(o) { "@babel/helpers - typeof"; return call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, call_builder_typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == call_builder_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(call_builder_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, call_builder_toPropertyKey(o.key), o); } } +function call_builder_createClass(e, r, t) { return r && call_builder_defineProperties(e.prototype, r), t && call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function call_builder_toPropertyKey(t) { var i = call_builder_toPrimitive(t, "string"); return "symbol" == call_builder_typeof(i) ? i : i + ""; } +function call_builder_toPrimitive(t, r) { if ("object" != call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + +var JOINABLE = ["transaction"]; +var anyGlobal = (/* unused pure expression or super */ null && (__webpack_require__.g)); +var EventSource; +if (false) { var _ref, _anyGlobal$EventSourc, _anyGlobal$window; } +var CallBuilder = function () { + function CallBuilder(serverUrl) { + var neighborRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; + call_builder_classCallCheck(this, CallBuilder); + this.url = serverUrl.clone(); + this.filter = []; + this.originalSegments = this.url.segment() || []; + this.neighborRoot = neighborRoot; + } + return call_builder_createClass(CallBuilder, [{ + key: "call", + value: function call() { + var _this = this; + this.checkFilter(); + return this._sendNormalRequest(this.url).then(function (r) { + return _this._parseResponse(r); + }); + } + }, { + key: "stream", + value: function stream() { + var _this2 = this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (EventSource === undefined) { + throw new Error("Streaming requires eventsource to be enabled. If you need this functionality, compile with USE_EVENTSOURCE=true."); + } + this.checkFilter(); + this.url.setQuery("X-Client-Name", "js-stellar-sdk"); + this.url.setQuery("X-Client-Version", version); + var es; + var timeout; + var createTimeout = function createTimeout() { + timeout = setTimeout(function () { + var _es; + (_es = es) === null || _es === void 0 || _es.close(); + es = _createEventSource(); + }, options.reconnectTimeout || 15 * 1000); + }; + var _createEventSource = function createEventSource() { + try { + es = new EventSource(_this2.url.toString()); + } catch (err) { + if (options.onerror) { + options.onerror(err); + } + } + createTimeout(); + if (!es) { + return es; + } + var closed = false; + var onClose = function onClose() { + if (closed) { + return; + } + clearTimeout(timeout); + es.close(); + _createEventSource(); + closed = true; + }; + var onMessage = function onMessage(message) { + if (message.type === "close") { + onClose(); + return; + } + var result = message.data ? _this2._parseRecord(JSON.parse(message.data)) : message; + if (result.paging_token) { + _this2.url.setQuery("cursor", result.paging_token); + } + clearTimeout(timeout); + createTimeout(); + if (typeof options.onmessage !== "undefined") { + options.onmessage(result); + } + }; + var onError = function onError(error) { + if (options.onerror) { + options.onerror(error); + } + }; + if (es.addEventListener) { + es.addEventListener("message", onMessage.bind(_this2)); + es.addEventListener("error", onError.bind(_this2)); + es.addEventListener("close", onClose.bind(_this2)); + } else { + es.onmessage = onMessage.bind(_this2); + es.onerror = onError.bind(_this2); + } + return es; + }; + _createEventSource(); + return function () { + var _es2; + clearTimeout(timeout); + (_es2 = es) === null || _es2 === void 0 || _es2.close(); + }; + } + }, { + key: "cursor", + value: function cursor(_cursor) { + this.url.setQuery("cursor", _cursor); + return this; + } + }, { + key: "limit", + value: function limit(recordsNumber) { + this.url.setQuery("limit", recordsNumber.toString()); + return this; + } + }, { + key: "order", + value: function order(direction) { + this.url.setQuery("order", direction); + return this; + } + }, { + key: "join", + value: function join(include) { + this.url.setQuery("join", include); + return this; + } + }, { + key: "forEndpoint", + value: function forEndpoint(endpoint, param) { + if (this.neighborRoot === "") { + throw new Error("Invalid usage: neighborRoot not set in constructor"); + } + this.filter.push([endpoint, param, this.neighborRoot]); + return this; + } + }, { + key: "checkFilter", + value: function checkFilter() { + if (this.filter.length >= 2) { + throw new errors/* BadRequestError */.v7("Too many filters specified", this.filter); + } + if (this.filter.length === 1) { + var newSegment = this.originalSegments.concat(this.filter[0]); + this.url.segment(newSegment); + } + } + }, { + key: "_requestFnForLink", + value: function _requestFnForLink(link) { + var _this3 = this; + return _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var opts, + uri, + template, + r, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}; + if (link.templated) { + template = URITemplate_default()(link.href); + uri = URI_default()(template.expand(opts)); + } else { + uri = URI_default()(link.href); + } + _context.next = 4; + return _this3._sendNormalRequest(uri); + case 4: + r = _context.sent; + return _context.abrupt("return", _this3._parseResponse(r)); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + } + }, { + key: "_parseRecord", + value: function _parseRecord(json) { + var _this4 = this; + if (!json._links) { + return json; + } + Object.keys(json._links).forEach(function (key) { + var n = json._links[key]; + var included = false; + if (typeof json[key] !== "undefined") { + json["".concat(key, "_attr")] = json[key]; + included = true; + } + if (included && JOINABLE.indexOf(key) >= 0) { + var record = _this4._parseRecord(json[key]); + json[key] = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", record); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + } else { + json[key] = _this4._requestFnForLink(n); + } + }); + return json; + } + }, { + key: "_sendNormalRequest", + value: function () { + var _sendNormalRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(initialUrl) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = initialUrl; + if (url.authority() === "") { + url = url.authority(this.url.authority()); + } + if (url.protocol() === "") { + url = url.protocol(this.url.protocol()); + } + return _context3.abrupt("return", AxiosClient.get(url.toString()).then(function (response) { + return response.data; + }).catch(this._handleNetworkError)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function _sendNormalRequest(_x) { + return _sendNormalRequest2.apply(this, arguments); + } + return _sendNormalRequest; + }() + }, { + key: "_parseResponse", + value: function _parseResponse(json) { + if (json._embedded && json._embedded.records) { + return this._toCollectionPage(json); + } + return this._parseRecord(json); + } + }, { + key: "_toCollectionPage", + value: function _toCollectionPage(json) { + var _this5 = this; + for (var i = 0; i < json._embedded.records.length; i += 1) { + json._embedded.records[i] = this._parseRecord(json._embedded.records[i]); + } + return { + records: json._embedded.records, + next: function () { + var _next2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + var r; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this5._sendNormalRequest(URI_default()(json._links.next.href)); + case 2: + r = _context4.sent; + return _context4.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function next() { + return _next2.apply(this, arguments); + } + return next; + }(), + prev: function () { + var _prev = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5() { + var r; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return _this5._sendNormalRequest(URI_default()(json._links.prev.href)); + case 2: + r = _context5.sent; + return _context5.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function prev() { + return _prev.apply(this, arguments); + } + return prev; + }() + }; + } + }, { + key: "_handleNetworkError", + value: (function () { + var _handleNetworkError2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(error) { + var _error$response$statu, _error$response$statu2; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + if (!(error.response && error.response.status)) { + _context6.next = 8; + break; + } + _context6.t0 = error.response.status; + _context6.next = _context6.t0 === 404 ? 4 : 5; + break; + case 4: + return _context6.abrupt("return", Promise.reject(new errors/* NotFoundError */.m_((_error$response$statu = error.response.statusText) !== null && _error$response$statu !== void 0 ? _error$response$statu : "Not Found", error.response.data))); + case 5: + return _context6.abrupt("return", Promise.reject(new errors/* NetworkError */.Dr((_error$response$statu2 = error.response.statusText) !== null && _error$response$statu2 !== void 0 ? _error$response$statu2 : "Unknown", error.response.data))); + case 6: + _context6.next = 9; + break; + case 8: + return _context6.abrupt("return", Promise.reject(new Error(error.message))); + case 9: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function _handleNetworkError(_x2) { + return _handleNetworkError2.apply(this, arguments); + } + return _handleNetworkError; + }()) + }]); +}(); +// EXTERNAL MODULE: ./src/config.ts +var config = __webpack_require__(8732); +;// ./src/horizon/account_call_builder.ts +function account_call_builder_typeof(o) { "@babel/helpers - typeof"; return account_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, account_call_builder_typeof(o); } +function account_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function account_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, account_call_builder_toPropertyKey(o.key), o); } } +function account_call_builder_createClass(e, r, t) { return r && account_call_builder_defineProperties(e.prototype, r), t && account_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function account_call_builder_toPropertyKey(t) { var i = account_call_builder_toPrimitive(t, "string"); return "symbol" == account_call_builder_typeof(i) ? i : i + ""; } +function account_call_builder_toPrimitive(t, r) { if ("object" != account_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != account_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == account_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } + +var AccountCallBuilder = function (_CallBuilder) { + function AccountCallBuilder(serverUrl) { + var _this; + account_call_builder_classCallCheck(this, AccountCallBuilder); + _this = _callSuper(this, AccountCallBuilder, [serverUrl]); + _this.url.segment("accounts"); + return _this; + } + _inherits(AccountCallBuilder, _CallBuilder); + return account_call_builder_createClass(AccountCallBuilder, [{ + key: "accountId", + value: function accountId(id) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([id]); + return builder; + } + }, { + key: "forSigner", + value: function forSigner(id) { + this.url.setQuery("signer", id); + return this; + } + }, { + key: "forAsset", + value: function forAsset(asset) { + this.url.setQuery("asset", "".concat(asset)); + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(id) { + this.url.setQuery("liquidity_pool", id); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/assets_call_builder.ts +function assets_call_builder_typeof(o) { "@babel/helpers - typeof"; return assets_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, assets_call_builder_typeof(o); } +function assets_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function assets_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, assets_call_builder_toPropertyKey(o.key), o); } } +function assets_call_builder_createClass(e, r, t) { return r && assets_call_builder_defineProperties(e.prototype, r), t && assets_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function assets_call_builder_toPropertyKey(t) { var i = assets_call_builder_toPrimitive(t, "string"); return "symbol" == assets_call_builder_typeof(i) ? i : i + ""; } +function assets_call_builder_toPrimitive(t, r) { if ("object" != assets_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != assets_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function assets_call_builder_callSuper(t, o, e) { return o = assets_call_builder_getPrototypeOf(o), assets_call_builder_possibleConstructorReturn(t, assets_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], assets_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function assets_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == assets_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return assets_call_builder_assertThisInitialized(t); } +function assets_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function assets_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (assets_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function assets_call_builder_getPrototypeOf(t) { return assets_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, assets_call_builder_getPrototypeOf(t); } +function assets_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && assets_call_builder_setPrototypeOf(t, e); } +function assets_call_builder_setPrototypeOf(t, e) { return assets_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, assets_call_builder_setPrototypeOf(t, e); } + +var AssetsCallBuilder = function (_CallBuilder) { + function AssetsCallBuilder(serverUrl) { + var _this; + assets_call_builder_classCallCheck(this, AssetsCallBuilder); + _this = assets_call_builder_callSuper(this, AssetsCallBuilder, [serverUrl]); + _this.url.segment("assets"); + return _this; + } + assets_call_builder_inherits(AssetsCallBuilder, _CallBuilder); + return assets_call_builder_createClass(AssetsCallBuilder, [{ + key: "forCode", + value: function forCode(value) { + this.url.setQuery("asset_code", value); + return this; + } + }, { + key: "forIssuer", + value: function forIssuer(value) { + this.url.setQuery("asset_issuer", value); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/claimable_balances_call_builder.ts +function claimable_balances_call_builder_typeof(o) { "@babel/helpers - typeof"; return claimable_balances_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, claimable_balances_call_builder_typeof(o); } +function claimable_balances_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function claimable_balances_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, claimable_balances_call_builder_toPropertyKey(o.key), o); } } +function claimable_balances_call_builder_createClass(e, r, t) { return r && claimable_balances_call_builder_defineProperties(e.prototype, r), t && claimable_balances_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function claimable_balances_call_builder_toPropertyKey(t) { var i = claimable_balances_call_builder_toPrimitive(t, "string"); return "symbol" == claimable_balances_call_builder_typeof(i) ? i : i + ""; } +function claimable_balances_call_builder_toPrimitive(t, r) { if ("object" != claimable_balances_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != claimable_balances_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function claimable_balances_call_builder_callSuper(t, o, e) { return o = claimable_balances_call_builder_getPrototypeOf(o), claimable_balances_call_builder_possibleConstructorReturn(t, claimable_balances_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], claimable_balances_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function claimable_balances_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == claimable_balances_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return claimable_balances_call_builder_assertThisInitialized(t); } +function claimable_balances_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function claimable_balances_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (claimable_balances_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function claimable_balances_call_builder_getPrototypeOf(t) { return claimable_balances_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, claimable_balances_call_builder_getPrototypeOf(t); } +function claimable_balances_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && claimable_balances_call_builder_setPrototypeOf(t, e); } +function claimable_balances_call_builder_setPrototypeOf(t, e) { return claimable_balances_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, claimable_balances_call_builder_setPrototypeOf(t, e); } + +var ClaimableBalanceCallBuilder = function (_CallBuilder) { + function ClaimableBalanceCallBuilder(serverUrl) { + var _this; + claimable_balances_call_builder_classCallCheck(this, ClaimableBalanceCallBuilder); + _this = claimable_balances_call_builder_callSuper(this, ClaimableBalanceCallBuilder, [serverUrl]); + _this.url.segment("claimable_balances"); + return _this; + } + claimable_balances_call_builder_inherits(ClaimableBalanceCallBuilder, _CallBuilder); + return claimable_balances_call_builder_createClass(ClaimableBalanceCallBuilder, [{ + key: "claimableBalance", + value: function claimableBalance(claimableBalanceId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([claimableBalanceId]); + return builder; + } + }, { + key: "sponsor", + value: function sponsor(_sponsor) { + this.url.setQuery("sponsor", _sponsor); + return this; + } + }, { + key: "claimant", + value: function claimant(_claimant) { + this.url.setQuery("claimant", _claimant); + return this; + } + }, { + key: "asset", + value: function asset(_asset) { + this.url.setQuery("asset", _asset.toString()); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/effect_call_builder.ts +function effect_call_builder_typeof(o) { "@babel/helpers - typeof"; return effect_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, effect_call_builder_typeof(o); } +function effect_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function effect_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, effect_call_builder_toPropertyKey(o.key), o); } } +function effect_call_builder_createClass(e, r, t) { return r && effect_call_builder_defineProperties(e.prototype, r), t && effect_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function effect_call_builder_toPropertyKey(t) { var i = effect_call_builder_toPrimitive(t, "string"); return "symbol" == effect_call_builder_typeof(i) ? i : i + ""; } +function effect_call_builder_toPrimitive(t, r) { if ("object" != effect_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != effect_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function effect_call_builder_callSuper(t, o, e) { return o = effect_call_builder_getPrototypeOf(o), effect_call_builder_possibleConstructorReturn(t, effect_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], effect_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function effect_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == effect_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return effect_call_builder_assertThisInitialized(t); } +function effect_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function effect_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (effect_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function effect_call_builder_getPrototypeOf(t) { return effect_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, effect_call_builder_getPrototypeOf(t); } +function effect_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && effect_call_builder_setPrototypeOf(t, e); } +function effect_call_builder_setPrototypeOf(t, e) { return effect_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, effect_call_builder_setPrototypeOf(t, e); } + +var EffectCallBuilder = function (_CallBuilder) { + function EffectCallBuilder(serverUrl) { + var _this; + effect_call_builder_classCallCheck(this, EffectCallBuilder); + _this = effect_call_builder_callSuper(this, EffectCallBuilder, [serverUrl, "effects"]); + _this.url.segment("effects"); + return _this; + } + effect_call_builder_inherits(EffectCallBuilder, _CallBuilder); + return effect_call_builder_createClass(EffectCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forOperation", + value: function forOperation(operationId) { + return this.forEndpoint("operations", operationId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }]); +}(CallBuilder); +;// ./src/horizon/friendbot_builder.ts +function friendbot_builder_typeof(o) { "@babel/helpers - typeof"; return friendbot_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, friendbot_builder_typeof(o); } +function friendbot_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, friendbot_builder_toPropertyKey(o.key), o); } } +function friendbot_builder_createClass(e, r, t) { return r && friendbot_builder_defineProperties(e.prototype, r), t && friendbot_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function friendbot_builder_toPropertyKey(t) { var i = friendbot_builder_toPrimitive(t, "string"); return "symbol" == friendbot_builder_typeof(i) ? i : i + ""; } +function friendbot_builder_toPrimitive(t, r) { if ("object" != friendbot_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != friendbot_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function friendbot_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function friendbot_builder_callSuper(t, o, e) { return o = friendbot_builder_getPrototypeOf(o), friendbot_builder_possibleConstructorReturn(t, friendbot_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], friendbot_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function friendbot_builder_possibleConstructorReturn(t, e) { if (e && ("object" == friendbot_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return friendbot_builder_assertThisInitialized(t); } +function friendbot_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function friendbot_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (friendbot_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function friendbot_builder_getPrototypeOf(t) { return friendbot_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, friendbot_builder_getPrototypeOf(t); } +function friendbot_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && friendbot_builder_setPrototypeOf(t, e); } +function friendbot_builder_setPrototypeOf(t, e) { return friendbot_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, friendbot_builder_setPrototypeOf(t, e); } + +var FriendbotBuilder = function (_CallBuilder) { + function FriendbotBuilder(serverUrl, address) { + var _this; + friendbot_builder_classCallCheck(this, FriendbotBuilder); + _this = friendbot_builder_callSuper(this, FriendbotBuilder, [serverUrl]); + _this.url.segment("friendbot"); + _this.url.setQuery("addr", address); + return _this; + } + friendbot_builder_inherits(FriendbotBuilder, _CallBuilder); + return friendbot_builder_createClass(FriendbotBuilder); +}(CallBuilder); +;// ./src/horizon/ledger_call_builder.ts +function ledger_call_builder_typeof(o) { "@babel/helpers - typeof"; return ledger_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, ledger_call_builder_typeof(o); } +function ledger_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function ledger_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, ledger_call_builder_toPropertyKey(o.key), o); } } +function ledger_call_builder_createClass(e, r, t) { return r && ledger_call_builder_defineProperties(e.prototype, r), t && ledger_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function ledger_call_builder_toPropertyKey(t) { var i = ledger_call_builder_toPrimitive(t, "string"); return "symbol" == ledger_call_builder_typeof(i) ? i : i + ""; } +function ledger_call_builder_toPrimitive(t, r) { if ("object" != ledger_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != ledger_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function ledger_call_builder_callSuper(t, o, e) { return o = ledger_call_builder_getPrototypeOf(o), ledger_call_builder_possibleConstructorReturn(t, ledger_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], ledger_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function ledger_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == ledger_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return ledger_call_builder_assertThisInitialized(t); } +function ledger_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function ledger_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (ledger_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function ledger_call_builder_getPrototypeOf(t) { return ledger_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, ledger_call_builder_getPrototypeOf(t); } +function ledger_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && ledger_call_builder_setPrototypeOf(t, e); } +function ledger_call_builder_setPrototypeOf(t, e) { return ledger_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, ledger_call_builder_setPrototypeOf(t, e); } + +var LedgerCallBuilder = function (_CallBuilder) { + function LedgerCallBuilder(serverUrl) { + var _this; + ledger_call_builder_classCallCheck(this, LedgerCallBuilder); + _this = ledger_call_builder_callSuper(this, LedgerCallBuilder, [serverUrl]); + _this.url.segment("ledgers"); + return _this; + } + ledger_call_builder_inherits(LedgerCallBuilder, _CallBuilder); + return ledger_call_builder_createClass(LedgerCallBuilder, [{ + key: "ledger", + value: function ledger(sequence) { + this.filter.push(["ledgers", sequence.toString()]); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/liquidity_pool_call_builder.ts +function liquidity_pool_call_builder_typeof(o) { "@babel/helpers - typeof"; return liquidity_pool_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, liquidity_pool_call_builder_typeof(o); } +function liquidity_pool_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function liquidity_pool_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, liquidity_pool_call_builder_toPropertyKey(o.key), o); } } +function liquidity_pool_call_builder_createClass(e, r, t) { return r && liquidity_pool_call_builder_defineProperties(e.prototype, r), t && liquidity_pool_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function liquidity_pool_call_builder_toPropertyKey(t) { var i = liquidity_pool_call_builder_toPrimitive(t, "string"); return "symbol" == liquidity_pool_call_builder_typeof(i) ? i : i + ""; } +function liquidity_pool_call_builder_toPrimitive(t, r) { if ("object" != liquidity_pool_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != liquidity_pool_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function liquidity_pool_call_builder_callSuper(t, o, e) { return o = liquidity_pool_call_builder_getPrototypeOf(o), liquidity_pool_call_builder_possibleConstructorReturn(t, liquidity_pool_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], liquidity_pool_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function liquidity_pool_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == liquidity_pool_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return liquidity_pool_call_builder_assertThisInitialized(t); } +function liquidity_pool_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function liquidity_pool_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (liquidity_pool_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function liquidity_pool_call_builder_getPrototypeOf(t) { return liquidity_pool_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, liquidity_pool_call_builder_getPrototypeOf(t); } +function liquidity_pool_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && liquidity_pool_call_builder_setPrototypeOf(t, e); } +function liquidity_pool_call_builder_setPrototypeOf(t, e) { return liquidity_pool_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, liquidity_pool_call_builder_setPrototypeOf(t, e); } + +var LiquidityPoolCallBuilder = function (_CallBuilder) { + function LiquidityPoolCallBuilder(serverUrl) { + var _this; + liquidity_pool_call_builder_classCallCheck(this, LiquidityPoolCallBuilder); + _this = liquidity_pool_call_builder_callSuper(this, LiquidityPoolCallBuilder, [serverUrl]); + _this.url.segment("liquidity_pools"); + return _this; + } + liquidity_pool_call_builder_inherits(LiquidityPoolCallBuilder, _CallBuilder); + return liquidity_pool_call_builder_createClass(LiquidityPoolCallBuilder, [{ + key: "forAssets", + value: function forAssets() { + for (var _len = arguments.length, assets = new Array(_len), _key = 0; _key < _len; _key++) { + assets[_key] = arguments[_key]; + } + var assetList = assets.map(function (asset) { + return asset.toString(); + }).join(","); + this.url.setQuery("reserves", assetList); + return this; + } + }, { + key: "forAccount", + value: function forAccount(id) { + this.url.setQuery("account", id); + return this; + } + }, { + key: "liquidityPoolId", + value: function liquidityPoolId(id) { + if (!id.match(/[a-fA-F0-9]{64}/)) { + throw new TypeError("".concat(id, " does not look like a liquidity pool ID")); + } + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([id.toLowerCase()]); + return builder; + } + }]); +}(CallBuilder); +;// ./src/horizon/offer_call_builder.ts +function offer_call_builder_typeof(o) { "@babel/helpers - typeof"; return offer_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, offer_call_builder_typeof(o); } +function offer_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function offer_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, offer_call_builder_toPropertyKey(o.key), o); } } +function offer_call_builder_createClass(e, r, t) { return r && offer_call_builder_defineProperties(e.prototype, r), t && offer_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function offer_call_builder_toPropertyKey(t) { var i = offer_call_builder_toPrimitive(t, "string"); return "symbol" == offer_call_builder_typeof(i) ? i : i + ""; } +function offer_call_builder_toPrimitive(t, r) { if ("object" != offer_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != offer_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function offer_call_builder_callSuper(t, o, e) { return o = offer_call_builder_getPrototypeOf(o), offer_call_builder_possibleConstructorReturn(t, offer_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], offer_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function offer_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == offer_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return offer_call_builder_assertThisInitialized(t); } +function offer_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function offer_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (offer_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function offer_call_builder_getPrototypeOf(t) { return offer_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, offer_call_builder_getPrototypeOf(t); } +function offer_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && offer_call_builder_setPrototypeOf(t, e); } +function offer_call_builder_setPrototypeOf(t, e) { return offer_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, offer_call_builder_setPrototypeOf(t, e); } + +var OfferCallBuilder = function (_CallBuilder) { + function OfferCallBuilder(serverUrl) { + var _this; + offer_call_builder_classCallCheck(this, OfferCallBuilder); + _this = offer_call_builder_callSuper(this, OfferCallBuilder, [serverUrl, "offers"]); + _this.url.segment("offers"); + return _this; + } + offer_call_builder_inherits(OfferCallBuilder, _CallBuilder); + return offer_call_builder_createClass(OfferCallBuilder, [{ + key: "offer", + value: function offer(offerId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([offerId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(id) { + return this.forEndpoint("accounts", id); + } + }, { + key: "buying", + value: function buying(asset) { + if (!asset.isNative()) { + this.url.setQuery("buying_asset_type", asset.getAssetType()); + this.url.setQuery("buying_asset_code", asset.getCode()); + this.url.setQuery("buying_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("buying_asset_type", "native"); + } + return this; + } + }, { + key: "selling", + value: function selling(asset) { + if (!asset.isNative()) { + this.url.setQuery("selling_asset_type", asset.getAssetType()); + this.url.setQuery("selling_asset_code", asset.getCode()); + this.url.setQuery("selling_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("selling_asset_type", "native"); + } + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "seller", + value: function seller(_seller) { + this.url.setQuery("seller", _seller); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/operation_call_builder.ts +function operation_call_builder_typeof(o) { "@babel/helpers - typeof"; return operation_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, operation_call_builder_typeof(o); } +function operation_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function operation_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, operation_call_builder_toPropertyKey(o.key), o); } } +function operation_call_builder_createClass(e, r, t) { return r && operation_call_builder_defineProperties(e.prototype, r), t && operation_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function operation_call_builder_toPropertyKey(t) { var i = operation_call_builder_toPrimitive(t, "string"); return "symbol" == operation_call_builder_typeof(i) ? i : i + ""; } +function operation_call_builder_toPrimitive(t, r) { if ("object" != operation_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != operation_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function operation_call_builder_callSuper(t, o, e) { return o = operation_call_builder_getPrototypeOf(o), operation_call_builder_possibleConstructorReturn(t, operation_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], operation_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function operation_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == operation_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return operation_call_builder_assertThisInitialized(t); } +function operation_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function operation_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (operation_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function operation_call_builder_getPrototypeOf(t) { return operation_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, operation_call_builder_getPrototypeOf(t); } +function operation_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && operation_call_builder_setPrototypeOf(t, e); } +function operation_call_builder_setPrototypeOf(t, e) { return operation_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, operation_call_builder_setPrototypeOf(t, e); } + +var OperationCallBuilder = function (_CallBuilder) { + function OperationCallBuilder(serverUrl) { + var _this; + operation_call_builder_classCallCheck(this, OperationCallBuilder); + _this = operation_call_builder_callSuper(this, OperationCallBuilder, [serverUrl, "operations"]); + _this.url.segment("operations"); + return _this; + } + operation_call_builder_inherits(OperationCallBuilder, _CallBuilder); + return operation_call_builder_createClass(OperationCallBuilder, [{ + key: "operation", + value: function operation(operationId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([operationId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/orderbook_call_builder.ts +function orderbook_call_builder_typeof(o) { "@babel/helpers - typeof"; return orderbook_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, orderbook_call_builder_typeof(o); } +function orderbook_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, orderbook_call_builder_toPropertyKey(o.key), o); } } +function orderbook_call_builder_createClass(e, r, t) { return r && orderbook_call_builder_defineProperties(e.prototype, r), t && orderbook_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function orderbook_call_builder_toPropertyKey(t) { var i = orderbook_call_builder_toPrimitive(t, "string"); return "symbol" == orderbook_call_builder_typeof(i) ? i : i + ""; } +function orderbook_call_builder_toPrimitive(t, r) { if ("object" != orderbook_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != orderbook_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function orderbook_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function orderbook_call_builder_callSuper(t, o, e) { return o = orderbook_call_builder_getPrototypeOf(o), orderbook_call_builder_possibleConstructorReturn(t, orderbook_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], orderbook_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function orderbook_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == orderbook_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return orderbook_call_builder_assertThisInitialized(t); } +function orderbook_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function orderbook_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (orderbook_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function orderbook_call_builder_getPrototypeOf(t) { return orderbook_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, orderbook_call_builder_getPrototypeOf(t); } +function orderbook_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && orderbook_call_builder_setPrototypeOf(t, e); } +function orderbook_call_builder_setPrototypeOf(t, e) { return orderbook_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, orderbook_call_builder_setPrototypeOf(t, e); } + +var OrderbookCallBuilder = function (_CallBuilder) { + function OrderbookCallBuilder(serverUrl, selling, buying) { + var _this; + orderbook_call_builder_classCallCheck(this, OrderbookCallBuilder); + _this = orderbook_call_builder_callSuper(this, OrderbookCallBuilder, [serverUrl]); + _this.url.segment("order_book"); + if (!selling.isNative()) { + _this.url.setQuery("selling_asset_type", selling.getAssetType()); + _this.url.setQuery("selling_asset_code", selling.getCode()); + _this.url.setQuery("selling_asset_issuer", selling.getIssuer()); + } else { + _this.url.setQuery("selling_asset_type", "native"); + } + if (!buying.isNative()) { + _this.url.setQuery("buying_asset_type", buying.getAssetType()); + _this.url.setQuery("buying_asset_code", buying.getCode()); + _this.url.setQuery("buying_asset_issuer", buying.getIssuer()); + } else { + _this.url.setQuery("buying_asset_type", "native"); + } + return _this; + } + orderbook_call_builder_inherits(OrderbookCallBuilder, _CallBuilder); + return orderbook_call_builder_createClass(OrderbookCallBuilder); +}(CallBuilder); +;// ./src/horizon/payment_call_builder.ts +function payment_call_builder_typeof(o) { "@babel/helpers - typeof"; return payment_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, payment_call_builder_typeof(o); } +function payment_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function payment_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, payment_call_builder_toPropertyKey(o.key), o); } } +function payment_call_builder_createClass(e, r, t) { return r && payment_call_builder_defineProperties(e.prototype, r), t && payment_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function payment_call_builder_toPropertyKey(t) { var i = payment_call_builder_toPrimitive(t, "string"); return "symbol" == payment_call_builder_typeof(i) ? i : i + ""; } +function payment_call_builder_toPrimitive(t, r) { if ("object" != payment_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != payment_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function payment_call_builder_callSuper(t, o, e) { return o = payment_call_builder_getPrototypeOf(o), payment_call_builder_possibleConstructorReturn(t, payment_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], payment_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function payment_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == payment_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return payment_call_builder_assertThisInitialized(t); } +function payment_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function payment_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (payment_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function payment_call_builder_getPrototypeOf(t) { return payment_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, payment_call_builder_getPrototypeOf(t); } +function payment_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && payment_call_builder_setPrototypeOf(t, e); } +function payment_call_builder_setPrototypeOf(t, e) { return payment_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, payment_call_builder_setPrototypeOf(t, e); } + +var PaymentCallBuilder = function (_CallBuilder) { + function PaymentCallBuilder(serverUrl) { + var _this; + payment_call_builder_classCallCheck(this, PaymentCallBuilder); + _this = payment_call_builder_callSuper(this, PaymentCallBuilder, [serverUrl, "payments"]); + _this.url.segment("payments"); + return _this; + } + payment_call_builder_inherits(PaymentCallBuilder, _CallBuilder); + return payment_call_builder_createClass(PaymentCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }]); +}(CallBuilder); +;// ./src/horizon/strict_receive_path_call_builder.ts +function strict_receive_path_call_builder_typeof(o) { "@babel/helpers - typeof"; return strict_receive_path_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, strict_receive_path_call_builder_typeof(o); } +function strict_receive_path_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, strict_receive_path_call_builder_toPropertyKey(o.key), o); } } +function strict_receive_path_call_builder_createClass(e, r, t) { return r && strict_receive_path_call_builder_defineProperties(e.prototype, r), t && strict_receive_path_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function strict_receive_path_call_builder_toPropertyKey(t) { var i = strict_receive_path_call_builder_toPrimitive(t, "string"); return "symbol" == strict_receive_path_call_builder_typeof(i) ? i : i + ""; } +function strict_receive_path_call_builder_toPrimitive(t, r) { if ("object" != strict_receive_path_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != strict_receive_path_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function strict_receive_path_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function strict_receive_path_call_builder_callSuper(t, o, e) { return o = strict_receive_path_call_builder_getPrototypeOf(o), strict_receive_path_call_builder_possibleConstructorReturn(t, strict_receive_path_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], strict_receive_path_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function strict_receive_path_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == strict_receive_path_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return strict_receive_path_call_builder_assertThisInitialized(t); } +function strict_receive_path_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function strict_receive_path_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (strict_receive_path_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function strict_receive_path_call_builder_getPrototypeOf(t) { return strict_receive_path_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, strict_receive_path_call_builder_getPrototypeOf(t); } +function strict_receive_path_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && strict_receive_path_call_builder_setPrototypeOf(t, e); } +function strict_receive_path_call_builder_setPrototypeOf(t, e) { return strict_receive_path_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, strict_receive_path_call_builder_setPrototypeOf(t, e); } + +var StrictReceivePathCallBuilder = function (_CallBuilder) { + function StrictReceivePathCallBuilder(serverUrl, source, destinationAsset, destinationAmount) { + var _this; + strict_receive_path_call_builder_classCallCheck(this, StrictReceivePathCallBuilder); + _this = strict_receive_path_call_builder_callSuper(this, StrictReceivePathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-receive"); + if (typeof source === "string") { + _this.url.setQuery("source_account", source); + } else { + var assets = source.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("source_assets", assets); + } + _this.url.setQuery("destination_amount", destinationAmount); + if (!destinationAsset.isNative()) { + _this.url.setQuery("destination_asset_type", destinationAsset.getAssetType()); + _this.url.setQuery("destination_asset_code", destinationAsset.getCode()); + _this.url.setQuery("destination_asset_issuer", destinationAsset.getIssuer()); + } else { + _this.url.setQuery("destination_asset_type", "native"); + } + return _this; + } + strict_receive_path_call_builder_inherits(StrictReceivePathCallBuilder, _CallBuilder); + return strict_receive_path_call_builder_createClass(StrictReceivePathCallBuilder); +}(CallBuilder); +;// ./src/horizon/strict_send_path_call_builder.ts +function strict_send_path_call_builder_typeof(o) { "@babel/helpers - typeof"; return strict_send_path_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, strict_send_path_call_builder_typeof(o); } +function strict_send_path_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, strict_send_path_call_builder_toPropertyKey(o.key), o); } } +function strict_send_path_call_builder_createClass(e, r, t) { return r && strict_send_path_call_builder_defineProperties(e.prototype, r), t && strict_send_path_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function strict_send_path_call_builder_toPropertyKey(t) { var i = strict_send_path_call_builder_toPrimitive(t, "string"); return "symbol" == strict_send_path_call_builder_typeof(i) ? i : i + ""; } +function strict_send_path_call_builder_toPrimitive(t, r) { if ("object" != strict_send_path_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != strict_send_path_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function strict_send_path_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function strict_send_path_call_builder_callSuper(t, o, e) { return o = strict_send_path_call_builder_getPrototypeOf(o), strict_send_path_call_builder_possibleConstructorReturn(t, strict_send_path_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], strict_send_path_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function strict_send_path_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == strict_send_path_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return strict_send_path_call_builder_assertThisInitialized(t); } +function strict_send_path_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function strict_send_path_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (strict_send_path_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function strict_send_path_call_builder_getPrototypeOf(t) { return strict_send_path_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, strict_send_path_call_builder_getPrototypeOf(t); } +function strict_send_path_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && strict_send_path_call_builder_setPrototypeOf(t, e); } +function strict_send_path_call_builder_setPrototypeOf(t, e) { return strict_send_path_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, strict_send_path_call_builder_setPrototypeOf(t, e); } + +var StrictSendPathCallBuilder = function (_CallBuilder) { + function StrictSendPathCallBuilder(serverUrl, sourceAsset, sourceAmount, destination) { + var _this; + strict_send_path_call_builder_classCallCheck(this, StrictSendPathCallBuilder); + _this = strict_send_path_call_builder_callSuper(this, StrictSendPathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-send"); + if (sourceAsset.isNative()) { + _this.url.setQuery("source_asset_type", "native"); + } else { + _this.url.setQuery("source_asset_type", sourceAsset.getAssetType()); + _this.url.setQuery("source_asset_code", sourceAsset.getCode()); + _this.url.setQuery("source_asset_issuer", sourceAsset.getIssuer()); + } + _this.url.setQuery("source_amount", sourceAmount); + if (typeof destination === "string") { + _this.url.setQuery("destination_account", destination); + } else { + var assets = destination.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("destination_assets", assets); + } + return _this; + } + strict_send_path_call_builder_inherits(StrictSendPathCallBuilder, _CallBuilder); + return strict_send_path_call_builder_createClass(StrictSendPathCallBuilder); +}(CallBuilder); +;// ./src/horizon/trade_aggregation_call_builder.ts +function trade_aggregation_call_builder_typeof(o) { "@babel/helpers - typeof"; return trade_aggregation_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, trade_aggregation_call_builder_typeof(o); } +function trade_aggregation_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function trade_aggregation_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, trade_aggregation_call_builder_toPropertyKey(o.key), o); } } +function trade_aggregation_call_builder_createClass(e, r, t) { return r && trade_aggregation_call_builder_defineProperties(e.prototype, r), t && trade_aggregation_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function trade_aggregation_call_builder_toPropertyKey(t) { var i = trade_aggregation_call_builder_toPrimitive(t, "string"); return "symbol" == trade_aggregation_call_builder_typeof(i) ? i : i + ""; } +function trade_aggregation_call_builder_toPrimitive(t, r) { if ("object" != trade_aggregation_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != trade_aggregation_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function trade_aggregation_call_builder_callSuper(t, o, e) { return o = trade_aggregation_call_builder_getPrototypeOf(o), trade_aggregation_call_builder_possibleConstructorReturn(t, trade_aggregation_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], trade_aggregation_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function trade_aggregation_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == trade_aggregation_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return trade_aggregation_call_builder_assertThisInitialized(t); } +function trade_aggregation_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function trade_aggregation_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (trade_aggregation_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function trade_aggregation_call_builder_getPrototypeOf(t) { return trade_aggregation_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, trade_aggregation_call_builder_getPrototypeOf(t); } +function trade_aggregation_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && trade_aggregation_call_builder_setPrototypeOf(t, e); } +function trade_aggregation_call_builder_setPrototypeOf(t, e) { return trade_aggregation_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, trade_aggregation_call_builder_setPrototypeOf(t, e); } + + +var allowedResolutions = [60000, 300000, 900000, 3600000, 86400000, 604800000]; +var TradeAggregationCallBuilder = function (_CallBuilder) { + function TradeAggregationCallBuilder(serverUrl, base, counter, start_time, end_time, resolution, offset) { + var _this; + trade_aggregation_call_builder_classCallCheck(this, TradeAggregationCallBuilder); + _this = trade_aggregation_call_builder_callSuper(this, TradeAggregationCallBuilder, [serverUrl]); + _this.url.segment("trade_aggregations"); + if (!base.isNative()) { + _this.url.setQuery("base_asset_type", base.getAssetType()); + _this.url.setQuery("base_asset_code", base.getCode()); + _this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + _this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + _this.url.setQuery("counter_asset_type", counter.getAssetType()); + _this.url.setQuery("counter_asset_code", counter.getCode()); + _this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + _this.url.setQuery("counter_asset_type", "native"); + } + if (typeof start_time !== "number" || typeof end_time !== "number") { + throw new errors/* BadRequestError */.v7("Invalid time bounds", [start_time, end_time]); + } else { + _this.url.setQuery("start_time", start_time.toString()); + _this.url.setQuery("end_time", end_time.toString()); + } + if (!_this.isValidResolution(resolution)) { + throw new errors/* BadRequestError */.v7("Invalid resolution", resolution); + } else { + _this.url.setQuery("resolution", resolution.toString()); + } + if (!_this.isValidOffset(offset, resolution)) { + throw new errors/* BadRequestError */.v7("Invalid offset", offset); + } else { + _this.url.setQuery("offset", offset.toString()); + } + return _this; + } + trade_aggregation_call_builder_inherits(TradeAggregationCallBuilder, _CallBuilder); + return trade_aggregation_call_builder_createClass(TradeAggregationCallBuilder, [{ + key: "isValidResolution", + value: function isValidResolution(resolution) { + return allowedResolutions.some(function (allowed) { + return allowed === resolution; + }); + } + }, { + key: "isValidOffset", + value: function isValidOffset(offset, resolution) { + var hour = 3600000; + return !(offset > resolution || offset >= 24 * hour || offset % hour !== 0); + } + }]); +}(CallBuilder); +;// ./src/horizon/trades_call_builder.ts +function trades_call_builder_typeof(o) { "@babel/helpers - typeof"; return trades_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, trades_call_builder_typeof(o); } +function trades_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function trades_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, trades_call_builder_toPropertyKey(o.key), o); } } +function trades_call_builder_createClass(e, r, t) { return r && trades_call_builder_defineProperties(e.prototype, r), t && trades_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function trades_call_builder_toPropertyKey(t) { var i = trades_call_builder_toPrimitive(t, "string"); return "symbol" == trades_call_builder_typeof(i) ? i : i + ""; } +function trades_call_builder_toPrimitive(t, r) { if ("object" != trades_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != trades_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function trades_call_builder_callSuper(t, o, e) { return o = trades_call_builder_getPrototypeOf(o), trades_call_builder_possibleConstructorReturn(t, trades_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], trades_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function trades_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == trades_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return trades_call_builder_assertThisInitialized(t); } +function trades_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function trades_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (trades_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function trades_call_builder_getPrototypeOf(t) { return trades_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, trades_call_builder_getPrototypeOf(t); } +function trades_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && trades_call_builder_setPrototypeOf(t, e); } +function trades_call_builder_setPrototypeOf(t, e) { return trades_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, trades_call_builder_setPrototypeOf(t, e); } + +var TradesCallBuilder = function (_CallBuilder) { + function TradesCallBuilder(serverUrl) { + var _this; + trades_call_builder_classCallCheck(this, TradesCallBuilder); + _this = trades_call_builder_callSuper(this, TradesCallBuilder, [serverUrl, "trades"]); + _this.url.segment("trades"); + return _this; + } + trades_call_builder_inherits(TradesCallBuilder, _CallBuilder); + return trades_call_builder_createClass(TradesCallBuilder, [{ + key: "forAssetPair", + value: function forAssetPair(base, counter) { + if (!base.isNative()) { + this.url.setQuery("base_asset_type", base.getAssetType()); + this.url.setQuery("base_asset_code", base.getCode()); + this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + this.url.setQuery("counter_asset_type", counter.getAssetType()); + this.url.setQuery("counter_asset_code", counter.getCode()); + this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + this.url.setQuery("counter_asset_type", "native"); + } + return this; + } + }, { + key: "forOffer", + value: function forOffer(offerId) { + this.url.setQuery("offer_id", offerId); + return this; + } + }, { + key: "forType", + value: function forType(tradeType) { + this.url.setQuery("trade_type", tradeType); + return this; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(liquidityPoolId) { + return this.forEndpoint("liquidity_pools", liquidityPoolId); + } + }]); +}(CallBuilder); +;// ./src/horizon/transaction_call_builder.ts +function transaction_call_builder_typeof(o) { "@babel/helpers - typeof"; return transaction_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, transaction_call_builder_typeof(o); } +function transaction_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function transaction_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, transaction_call_builder_toPropertyKey(o.key), o); } } +function transaction_call_builder_createClass(e, r, t) { return r && transaction_call_builder_defineProperties(e.prototype, r), t && transaction_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function transaction_call_builder_toPropertyKey(t) { var i = transaction_call_builder_toPrimitive(t, "string"); return "symbol" == transaction_call_builder_typeof(i) ? i : i + ""; } +function transaction_call_builder_toPrimitive(t, r) { if ("object" != transaction_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != transaction_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function transaction_call_builder_callSuper(t, o, e) { return o = transaction_call_builder_getPrototypeOf(o), transaction_call_builder_possibleConstructorReturn(t, transaction_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], transaction_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function transaction_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == transaction_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return transaction_call_builder_assertThisInitialized(t); } +function transaction_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function transaction_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (transaction_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function transaction_call_builder_getPrototypeOf(t) { return transaction_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, transaction_call_builder_getPrototypeOf(t); } +function transaction_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && transaction_call_builder_setPrototypeOf(t, e); } +function transaction_call_builder_setPrototypeOf(t, e) { return transaction_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, transaction_call_builder_setPrototypeOf(t, e); } + +var TransactionCallBuilder = function (_CallBuilder) { + function TransactionCallBuilder(serverUrl) { + var _this; + transaction_call_builder_classCallCheck(this, TransactionCallBuilder); + _this = transaction_call_builder_callSuper(this, TransactionCallBuilder, [serverUrl, "transactions"]); + _this.url.segment("transactions"); + return _this; + } + transaction_call_builder_inherits(TransactionCallBuilder, _CallBuilder); + return transaction_call_builder_createClass(TransactionCallBuilder, [{ + key: "transaction", + value: function transaction(transactionId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([transactionId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/server.ts +function server_typeof(o) { "@babel/helpers - typeof"; return server_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, server_typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = server_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function server_regeneratorRuntime() { "use strict"; server_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == server_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(server_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function server_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function server_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function server_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function server_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, server_toPropertyKey(o.key), o); } } +function server_createClass(e, r, t) { return r && server_defineProperties(e.prototype, r), t && server_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function server_toPropertyKey(t) { var i = server_toPrimitive(t, "string"); return "symbol" == server_typeof(i) ? i : i + ""; } +function server_toPrimitive(t, r) { if ("object" != server_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != server_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + + + + + + + + + + + + + + + + + + + +var SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000; +var STROOPS_IN_LUMEN = 10000000; +var ACCOUNT_REQUIRES_MEMO = "MQ=="; +function getAmountInLumens(amt) { + return new bignumber(amt).div(STROOPS_IN_LUMEN).toString(); +} +var HorizonServer = function () { + function HorizonServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + server_classCallCheck(this, HorizonServer); + this.serverURL = URI_default()(serverURL); + var allowHttp = typeof opts.allowHttp === "undefined" ? config/* Config */.T.isAllowHttp() : opts.allowHttp; + var customHeaders = {}; + if (opts.appName) { + customHeaders["X-App-Name"] = opts.appName; + } + if (opts.appVersion) { + customHeaders["X-App-Version"] = opts.appVersion; + } + if (opts.authToken) { + customHeaders["X-Auth-Token"] = opts.authToken; + } + if (opts.headers) { + Object.assign(customHeaders, opts.headers); + } + if (Object.keys(customHeaders).length > 0) { + horizon_axios_client.interceptors.request.use(function (config) { + config.headers = config.headers || {}; + config.headers = Object.assign(config.headers, customHeaders); + return config; + }); + } + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure horizon server"); + } + } + return server_createClass(HorizonServer, [{ + key: "fetchTimebounds", + value: (function () { + var _fetchTimebounds = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee(seconds) { + var _isRetry, + currentTime, + _args = arguments; + return server_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _isRetry = _args.length > 1 && _args[1] !== undefined ? _args[1] : false; + currentTime = getCurrentServerTime(this.serverURL.hostname()); + if (!currentTime) { + _context.next = 4; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: currentTime + seconds + }); + case 4: + if (!_isRetry) { + _context.next = 6; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: Math.floor(new Date().getTime() / 1000) + seconds + }); + case 6: + _context.next = 8; + return horizon_axios_client.get(URI_default()(this.serverURL).toString()); + case 8: + return _context.abrupt("return", this.fetchTimebounds(seconds, true)); + case 9: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function fetchTimebounds(_x) { + return _fetchTimebounds.apply(this, arguments); + } + return fetchTimebounds; + }()) + }, { + key: "fetchBaseFee", + value: (function () { + var _fetchBaseFee = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee2() { + var response; + return server_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.feeStats(); + case 2: + response = _context2.sent; + return _context2.abrupt("return", parseInt(response.last_ledger_base_fee, 10) || 100); + case 4: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function fetchBaseFee() { + return _fetchBaseFee.apply(this, arguments); + } + return fetchBaseFee; + }()) + }, { + key: "feeStats", + value: (function () { + var _feeStats = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee3() { + var cb; + return server_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + cb = new CallBuilder(URI_default()(this.serverURL)); + cb.filter.push(["fee_stats"]); + return _context3.abrupt("return", cb.call()); + case 3: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function feeStats() { + return _feeStats.apply(this, arguments); + } + return feeStats; + }()) + }, { + key: "root", + value: (function () { + var _root = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee4() { + var cb; + return server_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + cb = new CallBuilder(URI_default()(this.serverURL)); + return _context4.abrupt("return", cb.call()); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function root() { + return _root.apply(this, arguments); + } + return root; + }()) + }, { + key: "submitTransaction", + value: (function () { + var _submitTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee5(transaction) { + var opts, + tx, + _args5 = arguments; + return server_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context5.next = 4; + break; + } + _context5.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context5.abrupt("return", horizon_axios_client.post(URI_default()(this.serverURL).segment("transactions").toString(), "tx=".concat(tx), { + timeout: SUBMIT_TRANSACTION_TIMEOUT + }).then(function (response) { + if (!response.data.result_xdr) { + return response.data; + } + var responseXDR = lib.xdr.TransactionResult.fromXDR(response.data.result_xdr, "base64"); + var results = responseXDR.result().value(); + var offerResults; + var hasManageOffer; + if (results.length) { + offerResults = results.map(function (result, i) { + if (result.value().switch().name !== "manageBuyOffer" && result.value().switch().name !== "manageSellOffer") { + return null; + } + hasManageOffer = true; + var amountBought = new bignumber(0); + var amountSold = new bignumber(0); + var offerSuccess = result.value().value().success(); + var offersClaimed = offerSuccess.offersClaimed().map(function (offerClaimedAtom) { + var offerClaimed = offerClaimedAtom.value(); + var sellerId = ""; + switch (offerClaimedAtom.switch()) { + case lib.xdr.ClaimAtomType.claimAtomTypeV0(): + sellerId = lib.StrKey.encodeEd25519PublicKey(offerClaimed.sellerEd25519()); + break; + case lib.xdr.ClaimAtomType.claimAtomTypeOrderBook(): + sellerId = lib.StrKey.encodeEd25519PublicKey(offerClaimed.sellerId().ed25519()); + break; + default: + throw new Error("Invalid offer result type: ".concat(offerClaimedAtom.switch())); + } + var claimedOfferAmountBought = new bignumber(offerClaimed.amountBought().toString()); + var claimedOfferAmountSold = new bignumber(offerClaimed.amountSold().toString()); + amountBought = amountBought.plus(claimedOfferAmountSold); + amountSold = amountSold.plus(claimedOfferAmountBought); + var sold = lib.Asset.fromOperation(offerClaimed.assetSold()); + var bought = lib.Asset.fromOperation(offerClaimed.assetBought()); + var assetSold = { + type: sold.getAssetType(), + assetCode: sold.getCode(), + issuer: sold.getIssuer() + }; + var assetBought = { + type: bought.getAssetType(), + assetCode: bought.getCode(), + issuer: bought.getIssuer() + }; + return { + sellerId: sellerId, + offerId: offerClaimed.offerId().toString(), + assetSold: assetSold, + amountSold: getAmountInLumens(claimedOfferAmountSold), + assetBought: assetBought, + amountBought: getAmountInLumens(claimedOfferAmountBought) + }; + }); + var effect = offerSuccess.offer().switch().name; + var currentOffer; + if (typeof offerSuccess.offer().value === "function" && offerSuccess.offer().value()) { + var offerXDR = offerSuccess.offer().value(); + currentOffer = { + offerId: offerXDR.offerId().toString(), + selling: {}, + buying: {}, + amount: getAmountInLumens(offerXDR.amount().toString()), + price: { + n: offerXDR.price().n(), + d: offerXDR.price().d() + } + }; + var selling = lib.Asset.fromOperation(offerXDR.selling()); + currentOffer.selling = { + type: selling.getAssetType(), + assetCode: selling.getCode(), + issuer: selling.getIssuer() + }; + var buying = lib.Asset.fromOperation(offerXDR.buying()); + currentOffer.buying = { + type: buying.getAssetType(), + assetCode: buying.getCode(), + issuer: buying.getIssuer() + }; + } + return { + offersClaimed: offersClaimed, + effect: effect, + operationIndex: i, + currentOffer: currentOffer, + amountBought: getAmountInLumens(amountBought), + amountSold: getAmountInLumens(amountSold), + isFullyOpen: !offersClaimed.length && effect !== "manageOfferDeleted", + wasPartiallyFilled: !!offersClaimed.length && effect !== "manageOfferDeleted", + wasImmediatelyFilled: !!offersClaimed.length && effect === "manageOfferDeleted", + wasImmediatelyDeleted: !offersClaimed.length && effect === "manageOfferDeleted" + }; + }).filter(function (result) { + return !!result; + }); + } + return _objectSpread(_objectSpread({}, response.data), {}, { + offerResults: hasManageOffer ? offerResults : undefined + }); + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new errors/* BadResponseError */.nS("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function submitTransaction(_x2) { + return _submitTransaction.apply(this, arguments); + } + return submitTransaction; + }()) + }, { + key: "submitAsyncTransaction", + value: (function () { + var _submitAsyncTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee6(transaction) { + var opts, + tx, + _args6 = arguments; + return server_regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context6.next = 4; + break; + } + _context6.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context6.abrupt("return", horizon_axios_client.post(URI_default()(this.serverURL).segment("transactions_async").toString(), "tx=".concat(tx)).then(function (response) { + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new errors/* BadResponseError */.nS("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function submitAsyncTransaction(_x3) { + return _submitAsyncTransaction.apply(this, arguments); + } + return submitAsyncTransaction; + }()) + }, { + key: "accounts", + value: function accounts() { + return new AccountCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "claimableBalances", + value: function claimableBalances() { + return new ClaimableBalanceCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "ledgers", + value: function ledgers() { + return new LedgerCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "transactions", + value: function transactions() { + return new TransactionCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "offers", + value: function offers() { + return new OfferCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "orderbook", + value: function orderbook(selling, buying) { + return new OrderbookCallBuilder(URI_default()(this.serverURL), selling, buying); + } + }, { + key: "trades", + value: function trades() { + return new TradesCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "operations", + value: function operations() { + return new OperationCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "liquidityPools", + value: function liquidityPools() { + return new LiquidityPoolCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "strictReceivePaths", + value: function strictReceivePaths(source, destinationAsset, destinationAmount) { + return new StrictReceivePathCallBuilder(URI_default()(this.serverURL), source, destinationAsset, destinationAmount); + } + }, { + key: "strictSendPaths", + value: function strictSendPaths(sourceAsset, sourceAmount, destination) { + return new StrictSendPathCallBuilder(URI_default()(this.serverURL), sourceAsset, sourceAmount, destination); + } + }, { + key: "payments", + value: function payments() { + return new PaymentCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "effects", + value: function effects() { + return new EffectCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "friendbot", + value: function friendbot(address) { + return new FriendbotBuilder(URI_default()(this.serverURL), address); + } + }, { + key: "assets", + value: function assets() { + return new AssetsCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "loadAccount", + value: (function () { + var _loadAccount = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee7(accountId) { + var res; + return server_regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.accounts().accountId(accountId).call(); + case 2: + res = _context7.sent; + return _context7.abrupt("return", new AccountResponse(res)); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function loadAccount(_x4) { + return _loadAccount.apply(this, arguments); + } + return loadAccount; + }()) + }, { + key: "tradeAggregation", + value: function tradeAggregation(base, counter, start_time, end_time, resolution, offset) { + return new TradeAggregationCallBuilder(URI_default()(this.serverURL), base, counter, start_time, end_time, resolution, offset); + } + }, { + key: "checkMemoRequired", + value: (function () { + var _checkMemoRequired = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee8(transaction) { + var destinations, i, operation, destination, account; + return server_regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (transaction instanceof lib.FeeBumpTransaction) { + transaction = transaction.innerTransaction; + } + if (!(transaction.memo.type !== "none")) { + _context8.next = 3; + break; + } + return _context8.abrupt("return"); + case 3: + destinations = new Set(); + i = 0; + case 5: + if (!(i < transaction.operations.length)) { + _context8.next = 36; + break; + } + operation = transaction.operations[i]; + _context8.t0 = operation.type; + _context8.next = _context8.t0 === "payment" ? 10 : _context8.t0 === "pathPaymentStrictReceive" ? 10 : _context8.t0 === "pathPaymentStrictSend" ? 10 : _context8.t0 === "accountMerge" ? 10 : 11; + break; + case 10: + return _context8.abrupt("break", 12); + case 11: + return _context8.abrupt("continue", 33); + case 12: + destination = operation.destination; + if (!destinations.has(destination)) { + _context8.next = 15; + break; + } + return _context8.abrupt("continue", 33); + case 15: + destinations.add(destination); + if (!destination.startsWith("M")) { + _context8.next = 18; + break; + } + return _context8.abrupt("continue", 33); + case 18: + _context8.prev = 18; + _context8.next = 21; + return this.loadAccount(destination); + case 21: + account = _context8.sent; + if (!(account.data_attr["config.memo_required"] === ACCOUNT_REQUIRES_MEMO)) { + _context8.next = 24; + break; + } + throw new errors/* AccountRequiresMemoError */.Cu("account requires memo", destination, i); + case 24: + _context8.next = 33; + break; + case 26: + _context8.prev = 26; + _context8.t1 = _context8["catch"](18); + if (!(_context8.t1 instanceof errors/* AccountRequiresMemoError */.Cu)) { + _context8.next = 30; + break; + } + throw _context8.t1; + case 30: + if (_context8.t1 instanceof errors/* NotFoundError */.m_) { + _context8.next = 32; + break; + } + throw _context8.t1; + case 32: + return _context8.abrupt("continue", 33); + case 33: + i += 1; + _context8.next = 5; + break; + case 36: + case "end": + return _context8.stop(); + } + }, _callee8, this, [[18, 26]]); + })); + function checkMemoRequired(_x5) { + return _checkMemoRequired.apply(this, arguments); + } + return checkMemoRequired; + }()) + }]); +}(); +;// ./src/horizon/index.ts +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + +/* harmony default export */ const horizon = (module.exports); + +/***/ }), + +/***/ 8920: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + create: () => (/* binding */ createFetchClient), + fetchClient: () => (/* binding */ fetchClient) +}); + +;// ./node_modules/feaxios/dist/index.mjs +// src/client.ts +async function prepareAxiosResponse(options, res) { + const response = { config: options }; + response.status = res.status; + response.statusText = res.statusText; + response.headers = res.headers; + if (options.responseType === "stream") { + response.data = res.body; + return response; + } + return res[options.responseType || "text"]().then((data) => { + if (options.transformResponse) { + Array.isArray(options.transformResponse) ? options.transformResponse.map( + (fn) => data = fn.call(options, data, res?.headers, res?.status) + ) : data = options.transformResponse(data, res?.headers, res?.status); + response.data = data; + } else { + response.data = data; + response.data = JSON.parse(data); + } + }).catch(Object).then(() => response); +} +async function handleFetch(options, fetchOptions) { + let res = null; + if ("any" in AbortSignal) { + const signals = []; + if (options.timeout) { + signals.push(AbortSignal.timeout(options.timeout)); + } + if (options.signal) { + signals.push(options.signal); + } + if (signals.length > 0) { + fetchOptions.signal = AbortSignal.any(signals); + } + } else { + if (options.timeout) { + fetchOptions.signal = AbortSignal.timeout(options.timeout); + } + } + try { + res = await fetch(options.url, fetchOptions); + const ok = options.validateStatus ? options.validateStatus(res.status) : res.ok; + if (!ok) { + return Promise.reject( + new AxiosError( + `Request failed with status code ${res?.status}`, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(res?.status / 100) - 4], + options, + new Request(options.url, fetchOptions), + await prepareAxiosResponse(options, res) + ) + ); + } + return await prepareAxiosResponse(options, res); + } catch (error) { + if (error.name === "AbortError" || error.name === "TimeoutError") { + const isTimeoutError = error.name === "TimeoutError"; + return Promise.reject( + isTimeoutError ? new AxiosError( + options.timeoutErrorMessage || `timeout of ${options.timeout} ms exceeded`, + AxiosError.ECONNABORTED, + options, + request + ) : new CanceledError(null, options) + ); + } + return Promise.reject( + new AxiosError( + error.message, + void 0, + options, + request, + void 0 + ) + ); + } +} +function buildURL(options) { + let url = options.url || ""; + if (options.baseURL && options.url) { + url = options.url.replace(/^(?!.*\/\/)\/?/, `${options.baseURL}/`); + } + if (options.params && Object.keys(options.params).length > 0 && options.url) { + url += (~options.url.indexOf("?") ? "&" : "?") + (options.paramsSerializer ? options.paramsSerializer(options.params) : new URLSearchParams(options.params)); + } + return url; +} +function mergeAxiosOptions(input, defaults) { + const merged = { + ...defaults, + ...input + }; + if (defaults?.params && input?.params) { + merged.params = { + ...defaults?.params, + ...input?.params + }; + } + if (defaults?.headers && input?.headers) { + merged.headers = new Headers(defaults.headers || {}); + const headers = new Headers(input.headers || {}); + headers.forEach((value, key) => { + merged.headers.set(key, value); + }); + } + return merged; +} +function mergeFetchOptions(input, defaults) { + const merged = { + ...defaults, + ...input + }; + if (defaults?.headers && input?.headers) { + merged.headers = new Headers(defaults.headers || {}); + const headers = new Headers(input.headers || {}); + headers.forEach((value, key) => { + merged.headers.set(key, value); + }); + } + return merged; +} +function defaultTransformer(data, headers) { + const contentType = headers.get("content-type"); + if (!contentType) { + if (typeof data === "string") { + headers.set("content-type", "text/plain"); + } else if (data instanceof URLSearchParams) { + headers.set("content-type", "application/x-www-form-urlencoded"); + } else if (data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data)) { + headers.set("content-type", "application/octet-stream"); + } else if (typeof data === "object" && typeof data.append !== "function" && typeof data.text !== "function") { + data = JSON.stringify(data); + headers.set("content-type", "application/json"); + } + } else { + if (contentType === "application/x-www-form-urlencoded" && !(data instanceof URLSearchParams)) { + data = new URLSearchParams(data); + } else if (contentType === "application/json" && typeof data === "object") { + data = JSON.stringify(data); + } + } + return data; +} +async function request(configOrUrl, config, defaults, method, interceptors, data) { + if (typeof configOrUrl === "string") { + config = config || {}; + config.url = configOrUrl; + } else + config = configOrUrl || {}; + const options = mergeAxiosOptions(config, defaults || {}); + options.fetchOptions = options.fetchOptions || {}; + options.timeout = options.timeout || 0; + options.headers = new Headers(options.headers || {}); + options.transformRequest = options.transformRequest ?? defaultTransformer; + data = data || options.data; + if (options.transformRequest && data) { + Array.isArray(options.transformRequest) ? options.transformRequest.map( + (fn) => data = fn.call(options, data, options.headers) + ) : data = options.transformRequest(data, options.headers); + } + options.url = buildURL(options); + options.method = method || options.method || "get"; + if (interceptors && interceptors.request.handlers.length > 0) { + const chain = interceptors.request.handlers.filter( + (interceptor) => !interceptor?.runWhen || typeof interceptor.runWhen === "function" && interceptor.runWhen(options) + ).flatMap((interceptor) => [interceptor.fulfilled, interceptor.rejected]); + let result = options; + for (let i = 0, len = chain.length; i < len; i += 2) { + const onFulfilled = chain[i]; + const onRejected = chain[i + 1]; + try { + if (onFulfilled) + result = onFulfilled(result); + } catch (error) { + if (onRejected) + onRejected?.(error); + break; + } + } + } + const init = mergeFetchOptions( + { + method: options.method?.toUpperCase(), + body: data, + headers: options.headers, + credentials: options.withCredentials ? "include" : void 0, + signal: options.signal + }, + options.fetchOptions + ); + let resp = handleFetch(options, init); + if (interceptors && interceptors.response.handlers.length > 0) { + const chain = interceptors.response.handlers.flatMap((interceptor) => [ + interceptor.fulfilled, + interceptor.rejected + ]); + for (let i = 0, len = chain.length; i < len; i += 2) { + resp = resp.then(chain[i], chain[i + 1]); + } + } + return resp; +} +var AxiosInterceptorManager = class { + handlers = []; + constructor() { + this.handlers = []; + } + use = (onFulfilled, onRejected, options) => { + this.handlers.push({ + fulfilled: onFulfilled, + rejected: onRejected, + runWhen: options?.runWhen + }); + return this.handlers.length - 1; + }; + eject = (id) => { + if (this.handlers[id]) { + this.handlers[id] = null; + } + }; + clear = () => { + this.handlers = []; + }; +}; +function createAxiosInstance(defaults) { + defaults = defaults || {}; + const interceptors = { + request: new AxiosInterceptorManager(), + response: new AxiosInterceptorManager() + }; + const axios2 = (url, config) => request(url, config, defaults, void 0, interceptors); + axios2.defaults = defaults; + axios2.interceptors = interceptors; + axios2.getUri = (config) => { + const merged = mergeAxiosOptions(config || {}, defaults); + return buildURL(merged); + }; + axios2.request = (config) => request(config, void 0, defaults, void 0, interceptors); + ["get", "delete", "head", "options"].forEach((method) => { + axios2[method] = (url, config) => request(url, config, defaults, method, interceptors); + }); + ["post", "put", "patch"].forEach((method) => { + axios2[method] = (url, data, config) => request(url, config, defaults, method, interceptors, data); + }); + ["postForm", "putForm", "patchForm"].forEach((method) => { + axios2[method] = (url, data, config) => { + config = config || {}; + config.headers = new Headers(config.headers || {}); + config.headers.set("content-type", "application/x-www-form-urlencoded"); + return request( + url, + config, + defaults, + method.replace("Form", ""), + interceptors, + data + ); + }; + }); + return axios2; +} +var AxiosError = class extends Error { + config; + code; + request; + response; + status; + isAxiosError; + constructor(message, code, config, request2, response) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack; + } + this.name = "AxiosError"; + this.code = code; + this.config = config; + this.request = request2; + this.response = response; + this.isAxiosError = true; + } + static ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE"; + static ERR_BAD_OPTION = "ERR_BAD_OPTION"; + static ERR_NETWORK = "ERR_NETWORK"; + static ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE"; + static ERR_BAD_REQUEST = "ERR_BAD_REQUEST"; + static ERR_INVALID_URL = "ERR_INVALID_URL"; + static ERR_CANCELED = "ERR_CANCELED"; + static ECONNABORTED = "ECONNABORTED"; + static ETIMEDOUT = "ETIMEDOUT"; +}; +var CanceledError = class extends AxiosError { + constructor(message, config, request2) { + super( + !message ? "canceled" : message, + AxiosError.ERR_CANCELED, + config, + request2 + ); + this.name = "CanceledError"; + } +}; +function isAxiosError(payload) { + return payload !== null && typeof payload === "object" && payload.isAxiosError; +} +var axios = createAxiosInstance(); +axios.create = (defaults) => createAxiosInstance(defaults); + +// src/index.ts +var src_default = axios; + + + +// EXTERNAL MODULE: ./src/http-client/types.ts +var types = __webpack_require__(5798); +;// ./src/http-client/fetch-client.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + +var InterceptorManager = function () { + function InterceptorManager() { + _classCallCheck(this, InterceptorManager); + _defineProperty(this, "handlers", []); + } + return _createClass(InterceptorManager, [{ + key: "use", + value: function use(fulfilled, rejected) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected + }); + return this.handlers.length - 1; + } + }, { + key: "eject", + value: function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + }, { + key: "forEach", + value: function forEach(fn) { + this.handlers.forEach(function (h) { + if (h !== null) { + fn(h); + } + }); + } + }]); +}(); +function getFormConfig(config) { + var formConfig = config || {}; + formConfig.headers = new Headers(formConfig.headers || {}); + formConfig.headers.set('Content-Type', 'application/x-www-form-urlencoded'); + return formConfig; +} +function createFetchClient() { + var fetchConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var defaults = _objectSpread(_objectSpread({}, fetchConfig), {}, { + headers: fetchConfig.headers || {} + }); + var instance = src_default.create(defaults); + var requestInterceptors = new InterceptorManager(); + var responseInterceptors = new InterceptorManager(); + var httpClient = { + interceptors: { + request: requestInterceptors, + response: responseInterceptors + }, + defaults: _objectSpread(_objectSpread({}, defaults), {}, { + adapter: function adapter(config) { + return instance.request(config); + } + }), + create: function create(config) { + return createFetchClient(_objectSpread(_objectSpread({}, this.defaults), config)); + }, + makeRequest: function makeRequest(config) { + var _this = this; + return new Promise(function (resolve, reject) { + var abortController = new AbortController(); + config.signal = abortController.signal; + if (config.cancelToken) { + config.cancelToken.promise.then(function () { + abortController.abort(); + reject(new Error('Request canceled')); + }); + } + var modifiedConfig = config; + if (requestInterceptors.handlers.length > 0) { + var chain = requestInterceptors.handlers.filter(function (interceptor) { + return interceptor !== null; + }).flatMap(function (interceptor) { + return [interceptor.fulfilled, interceptor.rejected]; + }); + for (var i = 0, len = chain.length; i < len; i += 2) { + var onFulfilled = chain[i]; + var onRejected = chain[i + 1]; + try { + if (onFulfilled) modifiedConfig = onFulfilled(modifiedConfig); + } catch (error) { + if (onRejected) onRejected === null || onRejected === void 0 || onRejected(error); + reject(error); + return; + } + } + } + var adapter = modifiedConfig.adapter || _this.defaults.adapter; + if (!adapter) { + throw new Error('No adapter available'); + } + var responsePromise = adapter(modifiedConfig).then(function (axiosResponse) { + var httpClientResponse = { + data: axiosResponse.data, + headers: axiosResponse.headers, + config: axiosResponse.config, + status: axiosResponse.status, + statusText: axiosResponse.statusText + }; + return httpClientResponse; + }); + if (responseInterceptors.handlers.length > 0) { + var _chain = responseInterceptors.handlers.filter(function (interceptor) { + return interceptor !== null; + }).flatMap(function (interceptor) { + return [interceptor.fulfilled, interceptor.rejected]; + }); + var _loop = function _loop(_i) { + responsePromise = responsePromise.then(function (response) { + var fulfilledInterceptor = _chain[_i]; + if (typeof fulfilledInterceptor === 'function') { + return fulfilledInterceptor(response); + } + return response; + }, function (error) { + var rejectedInterceptor = _chain[_i + 1]; + if (typeof rejectedInterceptor === 'function') { + return rejectedInterceptor(error); + } + throw error; + }).then(function (interceptedResponse) { + return interceptedResponse; + }); + }; + for (var _i = 0, _len = _chain.length; _i < _len; _i += 2) { + _loop(_i); + } + } + responsePromise.then(resolve).catch(reject); + }); + }, + get: function get(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'get' + })); + }, + delete: function _delete(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'delete' + })); + }, + head: function head(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'head' + })); + }, + options: function options(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'options' + })); + }, + post: function post(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'post', + data: data + })); + }, + put: function put(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'put', + data: data + })); + }, + patch: function patch(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'patch', + data: data + })); + }, + postForm: function postForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'post', + data: data + })); + }, + putForm: function putForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'put', + data: data + })); + }, + patchForm: function patchForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'patch', + data: data + })); + }, + CancelToken: types/* CancelToken */.q, + isCancel: function isCancel(value) { + return value instanceof Error && value.message === 'Request canceled'; + } + }; + return httpClient; +} +var fetchClient = createFetchClient(); + + +/***/ }), + +/***/ 6371: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ ok: () => (/* binding */ httpClient), +/* harmony export */ vt: () => (/* binding */ create) +/* harmony export */ }); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5798); +var httpClient; +var create; +if (false) { var axiosModule; } else { + var fetchModule = __webpack_require__(8920); + httpClient = fetchModule.fetchClient; + create = fetchModule.create; +} + + + +/***/ }), + +/***/ 5798: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ q: () => (/* binding */ CancelToken) +/* harmony export */ }); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var CancelToken = function () { + function CancelToken(executor) { + var _this = this; + _classCallCheck(this, CancelToken); + var resolvePromise; + this.promise = new Promise(function (resolve) { + resolvePromise = resolve; + }); + executor(function (reason) { + _this.reason = reason; + resolvePromise(); + }); + } + return _createClass(CancelToken, [{ + key: "throwIfRequested", + value: function throwIfRequested() { + if (this.reason) { + throw new Error(this.reason); + } + } + }]); +}(); + +/***/ }), + +/***/ 4356: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ AccountRequiresMemoError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.Cu), +/* harmony export */ BadRequestError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.v7), +/* harmony export */ BadResponseError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.nS), +/* harmony export */ Config: () => (/* reexport safe */ _config__WEBPACK_IMPORTED_MODULE_1__.T), +/* harmony export */ Federation: () => (/* reexport module object */ _federation__WEBPACK_IMPORTED_MODULE_4__), +/* harmony export */ Friendbot: () => (/* reexport module object */ _friendbot__WEBPACK_IMPORTED_MODULE_6__), +/* harmony export */ Horizon: () => (/* reexport module object */ _horizon__WEBPACK_IMPORTED_MODULE_7__), +/* harmony export */ NetworkError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.Dr), +/* harmony export */ NotFoundError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.m_), +/* harmony export */ StellarToml: () => (/* reexport module object */ _stellartoml__WEBPACK_IMPORTED_MODULE_3__), +/* harmony export */ Utils: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_2__.A), +/* harmony export */ WebAuth: () => (/* reexport module object */ _webauth__WEBPACK_IMPORTED_MODULE_5__), +/* harmony export */ contract: () => (/* reexport module object */ _contract__WEBPACK_IMPORTED_MODULE_9__), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ rpc: () => (/* reexport module object */ _rpc__WEBPACK_IMPORTED_MODULE_8__) +/* harmony export */ }); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5976); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8732); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3121); +/* harmony import */ var _stellartoml__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3898); +/* harmony import */ var _federation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7600); +/* harmony import */ var _webauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(5479); +/* harmony import */ var _friendbot__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(8242); +/* harmony import */ var _horizon__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(8733); +/* harmony import */ var _rpc__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(3496); +/* harmony import */ var _contract__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(6299); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__); +/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {}; +/* harmony reexport (unknown) */ for(const __WEBPACK_IMPORT_KEY__ in _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__) if(["default","Config","Utils","StellarToml","Federation","WebAuth","Friendbot","Horizon","rpc","contract","AccountRequiresMemoError","BadRequestError","BadResponseError","NetworkError","NotFoundError"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = () => _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__[__WEBPACK_IMPORT_KEY__] +/* harmony reexport (unknown) */ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__); +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + + + + + + + + + + + + + + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (module.exports); +if (typeof __webpack_require__.g.__USE_AXIOS__ === 'undefined') { + __webpack_require__.g.__USE_AXIOS__ = true; +} +if (typeof __webpack_require__.g.__USE_EVENTSOURCE__ === 'undefined') { + __webpack_require__.g.__USE_EVENTSOURCE__ = false; +} + +/***/ }), + +/***/ 4076: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ j: () => (/* binding */ Api) +/* harmony export */ }); +var Api; +(function (_Api) { + var GetTransactionStatus = function (GetTransactionStatus) { + GetTransactionStatus["SUCCESS"] = "SUCCESS"; + GetTransactionStatus["NOT_FOUND"] = "NOT_FOUND"; + GetTransactionStatus["FAILED"] = "FAILED"; + return GetTransactionStatus; + }({}); + _Api.GetTransactionStatus = GetTransactionStatus; + function isSimulationError(sim) { + return 'error' in sim; + } + _Api.isSimulationError = isSimulationError; + function isSimulationSuccess(sim) { + return 'transactionData' in sim; + } + _Api.isSimulationSuccess = isSimulationSuccess; + function isSimulationRestore(sim) { + return isSimulationSuccess(sim) && 'restorePreamble' in sim && !!sim.restorePreamble.transactionData; + } + _Api.isSimulationRestore = isSimulationRestore; + function isSimulationRaw(sim) { + return !sim._parsed; + } + _Api.isSimulationRaw = isSimulationRaw; +})(Api || (Api = {})); + +/***/ }), + +/***/ 3496: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Api: () => (/* reexport */ api/* Api */.j), + AxiosClient: () => (/* reexport */ axios), + BasicSleepStrategy: () => (/* reexport */ BasicSleepStrategy), + Durability: () => (/* reexport */ Durability), + LinearSleepStrategy: () => (/* reexport */ LinearSleepStrategy), + Server: () => (/* reexport */ RpcServer), + assembleTransaction: () => (/* reexport */ transaction/* assembleTransaction */.X), + "default": () => (/* binding */ rpc), + parseRawEvents: () => (/* reexport */ parsers/* parseRawEvents */.fG), + parseRawSimulation: () => (/* reexport */ parsers/* parseRawSimulation */.jr) +}); + +// EXTERNAL MODULE: ./src/rpc/api.ts +var api = __webpack_require__(4076); +// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js +var URI = __webpack_require__(4193); +var URI_default = /*#__PURE__*/__webpack_require__.n(URI); +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./src/http-client/index.ts +var http_client = __webpack_require__(6371); +;// ./src/rpc/axios.ts + +var version = "13.1.0"; +var AxiosClient = (0,http_client/* create */.vt)({ + headers: { + 'X-Client-Name': 'js-soroban-client', + 'X-Client-Version': version + } +}); +/* harmony default export */ const axios = (AxiosClient); +;// ./src/rpc/jsonrpc.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + +function jsonrpc_hasOwnProperty(obj, prop) { + return obj.hasOwnProperty(prop); +} +function postObject(_x, _x2) { + return _postObject.apply(this, arguments); +} +function _postObject() { + _postObject = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(url, method) { + var param, + response, + _response$data, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + param = _args.length > 2 && _args[2] !== undefined ? _args[2] : null; + _context.next = 3; + return axios.post(url, { + jsonrpc: "2.0", + id: 1, + method: method, + params: param + }); + case 3: + response = _context.sent; + if (!jsonrpc_hasOwnProperty(response.data, "error")) { + _context.next = 8; + break; + } + throw response.data.error; + case 8: + return _context.abrupt("return", (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.result); + case 9: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _postObject.apply(this, arguments); +} +// EXTERNAL MODULE: ./src/rpc/transaction.ts +var transaction = __webpack_require__(8680); +// EXTERNAL MODULE: ./src/rpc/parsers.ts +var parsers = __webpack_require__(784); +// EXTERNAL MODULE: ./src/utils.ts +var utils = __webpack_require__(3121); +;// ./src/rpc/server.ts +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +function server_typeof(o) { "@babel/helpers - typeof"; return server_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, server_typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function server_regeneratorRuntime() { "use strict"; server_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == server_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(server_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function server_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function server_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == server_typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != server_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != server_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + + + +var SUBMIT_TRANSACTION_TIMEOUT = (/* unused pure expression or super */ null && (60 * 1000)); +var Durability = function (Durability) { + Durability["Temporary"] = "temporary"; + Durability["Persistent"] = "persistent"; + return Durability; +}({}); +var DEFAULT_GET_TRANSACTION_TIMEOUT = 30; +var BasicSleepStrategy = function BasicSleepStrategy(_iter) { + return 1000; +}; +var LinearSleepStrategy = function LinearSleepStrategy(iter) { + return 1000 * iter; +}; +function findCreatedAccountSequenceInTransactionMeta(meta) { + var _operations$flatMap$f; + var operations = []; + switch (meta.switch()) { + case 0: + operations = meta.operations(); + break; + case 1: + case 2: + case 3: + operations = meta.value().operations(); + break; + default: + throw new Error('Unexpected transaction meta switch value'); + } + var sequenceNumber = (_operations$flatMap$f = operations.flatMap(function (op) { + return op.changes(); + }).find(function (c) { + return c.switch() === lib.xdr.LedgerEntryChangeType.ledgerEntryCreated() && c.created().data().switch() === lib.xdr.LedgerEntryType.account(); + })) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.created()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.data()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.account()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.seqNum()) === null || _operations$flatMap$f === void 0 ? void 0 : _operations$flatMap$f.toString(); + if (sequenceNumber) { + return sequenceNumber; + } + throw new Error('No account created in transaction'); +} +var RpcServer = function () { + function RpcServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, RpcServer); + this.serverURL = URI_default()(serverURL); + if (opts.headers && Object.keys(opts.headers).length !== 0) { + axios.interceptors.request.use(function (config) { + config.headers = Object.assign(config.headers, opts.headers); + return config; + }); + } + if (this.serverURL.protocol() !== 'https' && !opts.allowHttp) { + throw new Error("Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set"); + } + } + return _createClass(RpcServer, [{ + key: "getAccount", + value: (function () { + var _getAccount = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee(address) { + var ledgerKey, resp, accountEntry; + return server_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + ledgerKey = lib.xdr.LedgerKey.account(new lib.xdr.LedgerKeyAccount({ + accountId: lib.Keypair.fromPublicKey(address).xdrPublicKey() + })); + _context.next = 3; + return this.getLedgerEntries(ledgerKey); + case 3: + resp = _context.sent; + if (!(resp.entries.length === 0)) { + _context.next = 6; + break; + } + return _context.abrupt("return", Promise.reject({ + code: 404, + message: "Account not found: ".concat(address) + })); + case 6: + accountEntry = resp.entries[0].val.account(); + return _context.abrupt("return", new lib.Account(address, accountEntry.seqNum().toString())); + case 8: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function getAccount(_x) { + return _getAccount.apply(this, arguments); + } + return getAccount; + }()) + }, { + key: "getHealth", + value: (function () { + var _getHealth = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee2() { + return server_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", postObject(this.serverURL.toString(), 'getHealth')); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function getHealth() { + return _getHealth.apply(this, arguments); + } + return getHealth; + }()) + }, { + key: "getContractData", + value: (function () { + var _getContractData = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee3(contract, key) { + var durability, + scAddress, + xdrDurability, + contractKey, + _args3 = arguments; + return server_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + durability = _args3.length > 2 && _args3[2] !== undefined ? _args3[2] : Durability.Persistent; + if (!(typeof contract === 'string')) { + _context3.next = 5; + break; + } + scAddress = new lib.Contract(contract).address().toScAddress(); + _context3.next = 14; + break; + case 5: + if (!(contract instanceof lib.Address)) { + _context3.next = 9; + break; + } + scAddress = contract.toScAddress(); + _context3.next = 14; + break; + case 9: + if (!(contract instanceof lib.Contract)) { + _context3.next = 13; + break; + } + scAddress = contract.address().toScAddress(); + _context3.next = 14; + break; + case 13: + throw new TypeError("unknown contract type: ".concat(contract)); + case 14: + _context3.t0 = durability; + _context3.next = _context3.t0 === Durability.Temporary ? 17 : _context3.t0 === Durability.Persistent ? 19 : 21; + break; + case 17: + xdrDurability = lib.xdr.ContractDataDurability.temporary(); + return _context3.abrupt("break", 22); + case 19: + xdrDurability = lib.xdr.ContractDataDurability.persistent(); + return _context3.abrupt("break", 22); + case 21: + throw new TypeError("invalid durability: ".concat(durability)); + case 22: + contractKey = lib.xdr.LedgerKey.contractData(new lib.xdr.LedgerKeyContractData({ + key: key, + contract: scAddress, + durability: xdrDurability + })); + return _context3.abrupt("return", this.getLedgerEntries(contractKey).then(function (r) { + if (r.entries.length === 0) { + return Promise.reject({ + code: 404, + message: "Contract data not found. Contract: ".concat(lib.Address.fromScAddress(scAddress).toString(), ", Key: ").concat(key.toXDR('base64'), ", Durability: ").concat(durability) + }); + } + return r.entries[0]; + })); + case 24: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function getContractData(_x2, _x3) { + return _getContractData.apply(this, arguments); + } + return getContractData; + }()) + }, { + key: "getContractWasmByContractId", + value: (function () { + var _getContractWasmByContractId = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee4(contractId) { + var _response$entries$; + var contractLedgerKey, response, wasmHash; + return server_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + contractLedgerKey = new lib.Contract(contractId).getFootprint(); + _context4.next = 3; + return this.getLedgerEntries(contractLedgerKey); + case 3: + response = _context4.sent; + if (!(!response.entries.length || !((_response$entries$ = response.entries[0]) !== null && _response$entries$ !== void 0 && _response$entries$.val))) { + _context4.next = 6; + break; + } + return _context4.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract hash from server" + })); + case 6: + wasmHash = response.entries[0].val.contractData().val().instance().executable().wasmHash(); + return _context4.abrupt("return", this.getContractWasmByHash(wasmHash)); + case 8: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function getContractWasmByContractId(_x4) { + return _getContractWasmByContractId.apply(this, arguments); + } + return getContractWasmByContractId; + }()) + }, { + key: "getContractWasmByHash", + value: (function () { + var _getContractWasmByHash = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee5(wasmHash) { + var _responseWasm$entries; + var format, + wasmHashBuffer, + ledgerKeyWasmHash, + responseWasm, + wasmBuffer, + _args5 = arguments; + return server_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + format = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : undefined; + wasmHashBuffer = typeof wasmHash === "string" ? Buffer.from(wasmHash, format) : wasmHash; + ledgerKeyWasmHash = lib.xdr.LedgerKey.contractCode(new lib.xdr.LedgerKeyContractCode({ + hash: wasmHashBuffer + })); + _context5.next = 5; + return this.getLedgerEntries(ledgerKeyWasmHash); + case 5: + responseWasm = _context5.sent; + if (!(!responseWasm.entries.length || !((_responseWasm$entries = responseWasm.entries[0]) !== null && _responseWasm$entries !== void 0 && _responseWasm$entries.val))) { + _context5.next = 8; + break; + } + return _context5.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract wasm from server" + })); + case 8: + wasmBuffer = responseWasm.entries[0].val.contractCode().code(); + return _context5.abrupt("return", wasmBuffer); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function getContractWasmByHash(_x5) { + return _getContractWasmByHash.apply(this, arguments); + } + return getContractWasmByHash; + }()) + }, { + key: "getLedgerEntries", + value: (function () { + var _getLedgerEntries2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee6() { + var _args6 = arguments; + return server_regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + return _context6.abrupt("return", this._getLedgerEntries.apply(this, _args6).then(parsers/* parseRawLedgerEntries */.$D)); + case 1: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function getLedgerEntries() { + return _getLedgerEntries2.apply(this, arguments); + } + return getLedgerEntries; + }()) + }, { + key: "_getLedgerEntries", + value: function () { + var _getLedgerEntries3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee7() { + var _len, + keys, + _key, + _args7 = arguments; + return server_regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + for (_len = _args7.length, keys = new Array(_len), _key = 0; _key < _len; _key++) { + keys[_key] = _args7[_key]; + } + return _context7.abrupt("return", postObject(this.serverURL.toString(), 'getLedgerEntries', { + keys: keys.map(function (k) { + return k.toXDR('base64'); + }) + })); + case 2: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function _getLedgerEntries() { + return _getLedgerEntries3.apply(this, arguments); + } + return _getLedgerEntries; + }() + }, { + key: "pollTransaction", + value: (function () { + var _pollTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee8(hash, opts) { + var _opts$attempts, _opts$attempts2; + var maxAttempts, foundInfo, attempt, _opts$sleepStrategy; + return server_regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + maxAttempts = ((_opts$attempts = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts !== void 0 ? _opts$attempts : 0) < 1 ? DEFAULT_GET_TRANSACTION_TIMEOUT : (_opts$attempts2 = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts2 !== void 0 ? _opts$attempts2 : DEFAULT_GET_TRANSACTION_TIMEOUT; + attempt = 1; + case 2: + if (!(attempt < maxAttempts)) { + _context8.next = 13; + break; + } + _context8.next = 5; + return this.getTransaction(hash); + case 5: + foundInfo = _context8.sent; + if (!(foundInfo.status !== api/* Api */.j.GetTransactionStatus.NOT_FOUND)) { + _context8.next = 8; + break; + } + return _context8.abrupt("return", foundInfo); + case 8: + _context8.next = 10; + return utils/* Utils */.A.sleep(((_opts$sleepStrategy = opts === null || opts === void 0 ? void 0 : opts.sleepStrategy) !== null && _opts$sleepStrategy !== void 0 ? _opts$sleepStrategy : BasicSleepStrategy)(attempt)); + case 10: + attempt++; + _context8.next = 2; + break; + case 13: + return _context8.abrupt("return", foundInfo); + case 14: + case "end": + return _context8.stop(); + } + }, _callee8, this); + })); + function pollTransaction(_x6, _x7) { + return _pollTransaction.apply(this, arguments); + } + return pollTransaction; + }()) + }, { + key: "getTransaction", + value: (function () { + var _getTransaction2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee9(hash) { + return server_regeneratorRuntime().wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + return _context9.abrupt("return", this._getTransaction(hash).then(function (raw) { + var foundInfo = {}; + if (raw.status !== api/* Api */.j.GetTransactionStatus.NOT_FOUND) { + Object.assign(foundInfo, (0,parsers/* parseTransactionInfo */.WC)(raw)); + } + var result = _objectSpread({ + status: raw.status, + txHash: hash, + latestLedger: raw.latestLedger, + latestLedgerCloseTime: raw.latestLedgerCloseTime, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTime: raw.oldestLedgerCloseTime + }, foundInfo); + return result; + })); + case 1: + case "end": + return _context9.stop(); + } + }, _callee9, this); + })); + function getTransaction(_x8) { + return _getTransaction2.apply(this, arguments); + } + return getTransaction; + }()) + }, { + key: "_getTransaction", + value: function () { + var _getTransaction3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee10(hash) { + return server_regeneratorRuntime().wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + return _context10.abrupt("return", postObject(this.serverURL.toString(), 'getTransaction', { + hash: hash + })); + case 1: + case "end": + return _context10.stop(); + } + }, _callee10, this); + })); + function _getTransaction(_x9) { + return _getTransaction3.apply(this, arguments); + } + return _getTransaction; + }() + }, { + key: "getTransactions", + value: (function () { + var _getTransactions2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee11(request) { + return server_regeneratorRuntime().wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + return _context11.abrupt("return", this._getTransactions(request).then(function (raw) { + var result = { + transactions: raw.transactions.map(parsers/* parseRawTransactions */.tR), + latestLedger: raw.latestLedger, + latestLedgerCloseTimestamp: raw.latestLedgerCloseTimestamp, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTimestamp: raw.oldestLedgerCloseTimestamp, + cursor: raw.cursor + }; + return result; + })); + case 1: + case "end": + return _context11.stop(); + } + }, _callee11, this); + })); + function getTransactions(_x10) { + return _getTransactions2.apply(this, arguments); + } + return getTransactions; + }()) + }, { + key: "_getTransactions", + value: function () { + var _getTransactions3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee12(request) { + return server_regeneratorRuntime().wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + return _context12.abrupt("return", postObject(this.serverURL.toString(), 'getTransactions', request)); + case 1: + case "end": + return _context12.stop(); + } + }, _callee12, this); + })); + function _getTransactions(_x11) { + return _getTransactions3.apply(this, arguments); + } + return _getTransactions; + }() + }, { + key: "getEvents", + value: (function () { + var _getEvents2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee13(request) { + return server_regeneratorRuntime().wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + return _context13.abrupt("return", this._getEvents(request).then(parsers/* parseRawEvents */.fG)); + case 1: + case "end": + return _context13.stop(); + } + }, _callee13, this); + })); + function getEvents(_x12) { + return _getEvents2.apply(this, arguments); + } + return getEvents; + }()) + }, { + key: "_getEvents", + value: function () { + var _getEvents3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee14(request) { + var _request$filters; + return server_regeneratorRuntime().wrap(function _callee14$(_context14) { + while (1) switch (_context14.prev = _context14.next) { + case 0: + return _context14.abrupt("return", postObject(this.serverURL.toString(), 'getEvents', _objectSpread(_objectSpread({ + filters: (_request$filters = request.filters) !== null && _request$filters !== void 0 ? _request$filters : [], + pagination: _objectSpread(_objectSpread({}, request.cursor && { + cursor: request.cursor + }), request.limit && { + limit: request.limit + }) + }, request.startLedger && { + startLedger: request.startLedger + }), request.endLedger && { + endLedger: request.endLedger + }))); + case 1: + case "end": + return _context14.stop(); + } + }, _callee14, this); + })); + function _getEvents(_x13) { + return _getEvents3.apply(this, arguments); + } + return _getEvents; + }() + }, { + key: "getNetwork", + value: (function () { + var _getNetwork = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee15() { + return server_regeneratorRuntime().wrap(function _callee15$(_context15) { + while (1) switch (_context15.prev = _context15.next) { + case 0: + return _context15.abrupt("return", postObject(this.serverURL.toString(), 'getNetwork')); + case 1: + case "end": + return _context15.stop(); + } + }, _callee15, this); + })); + function getNetwork() { + return _getNetwork.apply(this, arguments); + } + return getNetwork; + }()) + }, { + key: "getLatestLedger", + value: (function () { + var _getLatestLedger = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee16() { + return server_regeneratorRuntime().wrap(function _callee16$(_context16) { + while (1) switch (_context16.prev = _context16.next) { + case 0: + return _context16.abrupt("return", postObject(this.serverURL.toString(), 'getLatestLedger')); + case 1: + case "end": + return _context16.stop(); + } + }, _callee16, this); + })); + function getLatestLedger() { + return _getLatestLedger.apply(this, arguments); + } + return getLatestLedger; + }()) + }, { + key: "simulateTransaction", + value: (function () { + var _simulateTransaction2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee17(tx, addlResources) { + return server_regeneratorRuntime().wrap(function _callee17$(_context17) { + while (1) switch (_context17.prev = _context17.next) { + case 0: + return _context17.abrupt("return", this._simulateTransaction(tx, addlResources).then(parsers/* parseRawSimulation */.jr)); + case 1: + case "end": + return _context17.stop(); + } + }, _callee17, this); + })); + function simulateTransaction(_x14, _x15) { + return _simulateTransaction2.apply(this, arguments); + } + return simulateTransaction; + }()) + }, { + key: "_simulateTransaction", + value: function () { + var _simulateTransaction3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee18(transaction, addlResources) { + return server_regeneratorRuntime().wrap(function _callee18$(_context18) { + while (1) switch (_context18.prev = _context18.next) { + case 0: + return _context18.abrupt("return", postObject(this.serverURL.toString(), 'simulateTransaction', _objectSpread({ + transaction: transaction.toXDR() + }, addlResources !== undefined && { + resourceConfig: { + instructionLeeway: addlResources.cpuInstructions + } + }))); + case 1: + case "end": + return _context18.stop(); + } + }, _callee18, this); + })); + function _simulateTransaction(_x16, _x17) { + return _simulateTransaction3.apply(this, arguments); + } + return _simulateTransaction; + }() + }, { + key: "prepareTransaction", + value: (function () { + var _prepareTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee19(tx) { + var simResponse; + return server_regeneratorRuntime().wrap(function _callee19$(_context19) { + while (1) switch (_context19.prev = _context19.next) { + case 0: + _context19.next = 2; + return this.simulateTransaction(tx); + case 2: + simResponse = _context19.sent; + if (!api/* Api */.j.isSimulationError(simResponse)) { + _context19.next = 5; + break; + } + throw new Error(simResponse.error); + case 5: + return _context19.abrupt("return", (0,transaction/* assembleTransaction */.X)(tx, simResponse).build()); + case 6: + case "end": + return _context19.stop(); + } + }, _callee19, this); + })); + function prepareTransaction(_x18) { + return _prepareTransaction.apply(this, arguments); + } + return prepareTransaction; + }()) + }, { + key: "sendTransaction", + value: (function () { + var _sendTransaction2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee20(transaction) { + return server_regeneratorRuntime().wrap(function _callee20$(_context20) { + while (1) switch (_context20.prev = _context20.next) { + case 0: + return _context20.abrupt("return", this._sendTransaction(transaction).then(parsers/* parseRawSendTransaction */.Af)); + case 1: + case "end": + return _context20.stop(); + } + }, _callee20, this); + })); + function sendTransaction(_x19) { + return _sendTransaction2.apply(this, arguments); + } + return sendTransaction; + }()) + }, { + key: "_sendTransaction", + value: function () { + var _sendTransaction3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee21(transaction) { + return server_regeneratorRuntime().wrap(function _callee21$(_context21) { + while (1) switch (_context21.prev = _context21.next) { + case 0: + return _context21.abrupt("return", postObject(this.serverURL.toString(), 'sendTransaction', { + transaction: transaction.toXDR() + })); + case 1: + case "end": + return _context21.stop(); + } + }, _callee21, this); + })); + function _sendTransaction(_x20) { + return _sendTransaction3.apply(this, arguments); + } + return _sendTransaction; + }() + }, { + key: "requestAirdrop", + value: (function () { + var _requestAirdrop = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee22(address, friendbotUrl) { + var account, response, meta, txMeta, sequence, _error$response, _error$response$detai; + return server_regeneratorRuntime().wrap(function _callee22$(_context22) { + while (1) switch (_context22.prev = _context22.next) { + case 0: + account = typeof address === 'string' ? address : address.accountId(); + _context22.t0 = friendbotUrl; + if (_context22.t0) { + _context22.next = 6; + break; + } + _context22.next = 5; + return this.getNetwork(); + case 5: + _context22.t0 = _context22.sent.friendbotUrl; + case 6: + friendbotUrl = _context22.t0; + if (friendbotUrl) { + _context22.next = 9; + break; + } + throw new Error('No friendbot URL configured for current network'); + case 9: + _context22.prev = 9; + _context22.next = 12; + return axios.post("".concat(friendbotUrl, "?addr=").concat(encodeURIComponent(account))); + case 12: + response = _context22.sent; + if (response.data.result_meta_xdr) { + _context22.next = 22; + break; + } + _context22.next = 16; + return this.getTransaction(response.data.hash); + case 16: + txMeta = _context22.sent; + if (!(txMeta.status !== api/* Api */.j.GetTransactionStatus.SUCCESS)) { + _context22.next = 19; + break; + } + throw new Error("Funding account ".concat(address, " failed")); + case 19: + meta = txMeta.resultMetaXdr; + _context22.next = 23; + break; + case 22: + meta = lib.xdr.TransactionMeta.fromXDR(response.data.result_meta_xdr, 'base64'); + case 23: + sequence = findCreatedAccountSequenceInTransactionMeta(meta); + return _context22.abrupt("return", new lib.Account(account, sequence)); + case 27: + _context22.prev = 27; + _context22.t1 = _context22["catch"](9); + if (!(((_error$response = _context22.t1.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 400)) { + _context22.next = 32; + break; + } + if (!((_error$response$detai = _context22.t1.response.detail) !== null && _error$response$detai !== void 0 && _error$response$detai.includes('createAccountAlreadyExist'))) { + _context22.next = 32; + break; + } + return _context22.abrupt("return", this.getAccount(account)); + case 32: + throw _context22.t1; + case 33: + case "end": + return _context22.stop(); + } + }, _callee22, this, [[9, 27]]); + })); + function requestAirdrop(_x21, _x22) { + return _requestAirdrop.apply(this, arguments); + } + return requestAirdrop; + }()) + }, { + key: "getFeeStats", + value: (function () { + var _getFeeStats = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee23() { + return server_regeneratorRuntime().wrap(function _callee23$(_context23) { + while (1) switch (_context23.prev = _context23.next) { + case 0: + return _context23.abrupt("return", postObject(this.serverURL.toString(), 'getFeeStats')); + case 1: + case "end": + return _context23.stop(); + } + }, _callee23, this); + })); + function getFeeStats() { + return _getFeeStats.apply(this, arguments); + } + return getFeeStats; + }()) + }, { + key: "getVersionInfo", + value: (function () { + var _getVersionInfo = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee24() { + return server_regeneratorRuntime().wrap(function _callee24$(_context24) { + while (1) switch (_context24.prev = _context24.next) { + case 0: + return _context24.abrupt("return", postObject(this.serverURL.toString(), 'getVersionInfo')); + case 1: + case "end": + return _context24.stop(); + } + }, _callee24, this); + })); + function getVersionInfo() { + return _getVersionInfo.apply(this, arguments); + } + return getVersionInfo; + }()) + }, { + key: "getSACBalance", + value: (function () { + var _getSACBalance = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee25(contractId, sac, networkPassphrase) { + var passphrase, sacId, key, ledgerKey, response, _response$entries$2, lastModifiedLedgerSeq, liveUntilLedgerSeq, val, entry; + return server_regeneratorRuntime().wrap(function _callee25$(_context25) { + while (1) switch (_context25.prev = _context25.next) { + case 0: + if (lib.StrKey.isValidContract(contractId)) { + _context25.next = 2; + break; + } + throw new TypeError("expected contract ID, got ".concat(contractId)); + case 2: + if (!(networkPassphrase !== null && networkPassphrase !== void 0)) { + _context25.next = 6; + break; + } + _context25.t0 = networkPassphrase; + _context25.next = 9; + break; + case 6: + _context25.next = 8; + return this.getNetwork().then(function (n) { + return n.passphrase; + }); + case 8: + _context25.t0 = _context25.sent; + case 9: + passphrase = _context25.t0; + sacId = sac.contractId(passphrase); + key = lib.xdr.ScVal.scvVec([(0,lib.nativeToScVal)("Balance", { + type: "symbol" + }), (0,lib.nativeToScVal)(contractId, { + type: "address" + })]); + ledgerKey = lib.xdr.LedgerKey.contractData(new lib.xdr.LedgerKeyContractData({ + contract: new lib.Address(sacId).toScAddress(), + durability: lib.xdr.ContractDataDurability.persistent(), + key: key + })); + _context25.next = 15; + return this.getLedgerEntries(ledgerKey); + case 15: + response = _context25.sent; + if (!(response.entries.length === 0)) { + _context25.next = 18; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 18: + _response$entries$2 = response.entries[0], lastModifiedLedgerSeq = _response$entries$2.lastModifiedLedgerSeq, liveUntilLedgerSeq = _response$entries$2.liveUntilLedgerSeq, val = _response$entries$2.val; + if (!(val.switch().value !== lib.xdr.LedgerEntryType.contractData().value)) { + _context25.next = 21; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 21: + entry = (0,lib.scValToNative)(val.contractData().val()); + return _context25.abrupt("return", { + latestLedger: response.latestLedger, + balanceEntry: { + liveUntilLedgerSeq: liveUntilLedgerSeq, + lastModifiedLedgerSeq: lastModifiedLedgerSeq, + amount: entry.amount.toString(), + authorized: entry.authorized, + clawback: entry.clawback + } + }); + case 23: + case "end": + return _context25.stop(); + } + }, _callee25, this); + })); + function getSACBalance(_x23, _x24, _x25) { + return _getSACBalance.apply(this, arguments); + } + return getSACBalance; + }()) + }]); +}(); +;// ./src/rpc/index.ts +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + +/* harmony default export */ const rpc = (module.exports); + +/***/ }), + +/***/ 784: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ $D: () => (/* binding */ parseRawLedgerEntries), +/* harmony export */ Af: () => (/* binding */ parseRawSendTransaction), +/* harmony export */ WC: () => (/* binding */ parseTransactionInfo), +/* harmony export */ fG: () => (/* binding */ parseRawEvents), +/* harmony export */ jr: () => (/* binding */ parseRawSimulation), +/* harmony export */ tR: () => (/* binding */ parseRawTransactions) +/* harmony export */ }); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4076); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + +function parseRawSendTransaction(raw) { + var errorResultXdr = raw.errorResultXdr, + diagnosticEventsXdr = raw.diagnosticEventsXdr; + delete raw.errorResultXdr; + delete raw.diagnosticEventsXdr; + if (errorResultXdr) { + return _objectSpread(_objectSpread(_objectSpread({}, raw), diagnosticEventsXdr !== undefined && diagnosticEventsXdr.length > 0 && { + diagnosticEvents: diagnosticEventsXdr.map(function (evt) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + }) + }), {}, { + errorResult: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionResult.fromXDR(errorResultXdr, 'base64') + }); + } + return _objectSpread({}, raw); +} +function parseTransactionInfo(raw) { + var meta = _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionMeta.fromXDR(raw.resultMetaXdr, 'base64'); + var info = { + ledger: raw.ledger, + createdAt: raw.createdAt, + applicationOrder: raw.applicationOrder, + feeBump: raw.feeBump, + envelopeXdr: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionEnvelope.fromXDR(raw.envelopeXdr, 'base64'), + resultXdr: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionResult.fromXDR(raw.resultXdr, 'base64'), + resultMetaXdr: meta + }; + if (meta.switch() === 3 && meta.v3().sorobanMeta() !== null) { + var _meta$v3$sorobanMeta; + info.returnValue = (_meta$v3$sorobanMeta = meta.v3().sorobanMeta()) === null || _meta$v3$sorobanMeta === void 0 ? void 0 : _meta$v3$sorobanMeta.returnValue(); + } + if ('diagnosticEventsXdr' in raw && raw.diagnosticEventsXdr) { + info.diagnosticEventsXdr = raw.diagnosticEventsXdr.map(function (diagnosticEvent) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.DiagnosticEvent.fromXDR(diagnosticEvent, 'base64'); + }); + } + return info; +} +function parseRawTransactions(r) { + return _objectSpread({ + status: r.status, + txHash: r.txHash + }, parseTransactionInfo(r)); +} +function parseRawEvents(raw) { + var _raw$events; + return { + latestLedger: raw.latestLedger, + cursor: raw.cursor, + events: ((_raw$events = raw.events) !== null && _raw$events !== void 0 ? _raw$events : []).map(function (evt) { + var clone = _objectSpread({}, evt); + delete clone.contractId; + return _objectSpread(_objectSpread(_objectSpread({}, clone), evt.contractId !== '' && { + contractId: new _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.Contract(evt.contractId) + }), {}, { + topic: evt.topic.map(function (topic) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.fromXDR(topic, 'base64'); + }), + value: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.fromXDR(evt.value, 'base64') + }); + }) + }; +} +function parseRawLedgerEntries(raw) { + var _raw$entries; + return { + latestLedger: raw.latestLedger, + entries: ((_raw$entries = raw.entries) !== null && _raw$entries !== void 0 ? _raw$entries : []).map(function (rawEntry) { + if (!rawEntry.key || !rawEntry.xdr) { + throw new TypeError("invalid ledger entry: ".concat(JSON.stringify(rawEntry))); + } + return _objectSpread({ + lastModifiedLedgerSeq: rawEntry.lastModifiedLedgerSeq, + key: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerKey.fromXDR(rawEntry.key, 'base64'), + val: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerEntryData.fromXDR(rawEntry.xdr, 'base64') + }, rawEntry.liveUntilLedgerSeq !== undefined && { + liveUntilLedgerSeq: rawEntry.liveUntilLedgerSeq + }); + }) + }; +} +function parseSuccessful(sim, partial) { + var _sim$results$length, _sim$results, _sim$stateChanges$len, _sim$stateChanges, _sim$stateChanges2; + var success = _objectSpread(_objectSpread(_objectSpread({}, partial), {}, { + transactionData: new _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.SorobanDataBuilder(sim.transactionData), + minResourceFee: sim.minResourceFee + }, ((_sim$results$length = (_sim$results = sim.results) === null || _sim$results === void 0 ? void 0 : _sim$results.length) !== null && _sim$results$length !== void 0 ? _sim$results$length : 0 > 0) && { + result: sim.results.map(function (row) { + var _row$auth; + return { + auth: ((_row$auth = row.auth) !== null && _row$auth !== void 0 ? _row$auth : []).map(function (entry) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.SorobanAuthorizationEntry.fromXDR(entry, 'base64'); + }), + retval: row.xdr ? _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.fromXDR(row.xdr, 'base64') : _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.scvVoid() + }; + })[0] + }), ((_sim$stateChanges$len = (_sim$stateChanges = sim.stateChanges) === null || _sim$stateChanges === void 0 ? void 0 : _sim$stateChanges.length) !== null && _sim$stateChanges$len !== void 0 ? _sim$stateChanges$len : 0 > 0) && { + stateChanges: (_sim$stateChanges2 = sim.stateChanges) === null || _sim$stateChanges2 === void 0 ? void 0 : _sim$stateChanges2.map(function (entryChange) { + return { + type: entryChange.type, + key: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerKey.fromXDR(entryChange.key, 'base64'), + before: entryChange.before ? _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerEntry.fromXDR(entryChange.before, 'base64') : null, + after: entryChange.after ? _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerEntry.fromXDR(entryChange.after, 'base64') : null + }; + }) + }); + if (!sim.restorePreamble || sim.restorePreamble.transactionData === '') { + return success; + } + return _objectSpread(_objectSpread({}, success), {}, { + restorePreamble: { + minResourceFee: sim.restorePreamble.minResourceFee, + transactionData: new _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.SorobanDataBuilder(sim.restorePreamble.transactionData) + } + }); +} +function parseRawSimulation(sim) { + var _sim$events$map, _sim$events; + var looksRaw = _api__WEBPACK_IMPORTED_MODULE_1__/* .Api */ .j.isSimulationRaw(sim); + if (!looksRaw) { + return sim; + } + var base = { + _parsed: true, + id: sim.id, + latestLedger: sim.latestLedger, + events: (_sim$events$map = (_sim$events = sim.events) === null || _sim$events === void 0 ? void 0 : _sim$events.map(function (evt) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + })) !== null && _sim$events$map !== void 0 ? _sim$events$map : [] + }; + if (typeof sim.error === 'string') { + return _objectSpread(_objectSpread({}, base), {}, { + error: sim.error + }); + } + return parseSuccessful(sim, base); +} + +/***/ }), + +/***/ 8680: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ X: () => (/* binding */ assembleTransaction) +/* harmony export */ }); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4076); +/* harmony import */ var _parsers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(784); + + + +function isSorobanTransaction(tx) { + if (tx.operations.length !== 1) { + return false; + } + switch (tx.operations[0].type) { + case 'invokeHostFunction': + case 'extendFootprintTtl': + case 'restoreFootprint': + return true; + default: + return false; + } +} +function assembleTransaction(raw, simulation) { + if ('innerTransaction' in raw) { + return assembleTransaction(raw.innerTransaction, simulation); + } + if (!isSorobanTransaction(raw)) { + throw new TypeError('unsupported transaction: must contain exactly one ' + 'invokeHostFunction, extendFootprintTtl, or restoreFootprint ' + 'operation'); + } + var success = (0,_parsers__WEBPACK_IMPORTED_MODULE_2__/* .parseRawSimulation */ .jr)(simulation); + if (!_api__WEBPACK_IMPORTED_MODULE_1__/* .Api */ .j.isSimulationSuccess(success)) { + throw new Error("simulation incorrect: ".concat(JSON.stringify(success))); + } + var classicFeeNum = parseInt(raw.fee) || 0; + var minResourceFeeNum = parseInt(success.minResourceFee) || 0; + var txnBuilder = _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.TransactionBuilder.cloneFrom(raw, { + fee: (classicFeeNum + minResourceFeeNum).toString(), + sorobanData: success.transactionData.build(), + networkPassphrase: raw.networkPassphrase + }); + if (raw.operations[0].type === 'invokeHostFunction') { + var _invokeOp$auth; + txnBuilder.clearOperations(); + var invokeOp = raw.operations[0]; + var existingAuth = (_invokeOp$auth = invokeOp.auth) !== null && _invokeOp$auth !== void 0 ? _invokeOp$auth : []; + txnBuilder.addOperation(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.Operation.invokeHostFunction({ + source: invokeOp.source, + func: invokeOp.func, + auth: existingAuth.length > 0 ? existingAuth : success.result.auth + })); + } + return txnBuilder; +} + +/***/ }), + +/***/ 3898: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Api: () => (/* binding */ Api), +/* harmony export */ Resolver: () => (/* binding */ Resolver), +/* harmony export */ STELLAR_TOML_MAX_SIZE: () => (/* binding */ STELLAR_TOML_MAX_SIZE) +/* harmony export */ }); +/* harmony import */ var toml__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1293); +/* harmony import */ var toml__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(toml__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _http_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6371); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8732); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + +var STELLAR_TOML_MAX_SIZE = 100 * 1024; +var CancelToken = _http_client__WEBPACK_IMPORTED_MODULE_1__/* .httpClient */ .ok.CancelToken; +var Resolver = function () { + function Resolver() { + _classCallCheck(this, Resolver); + } + return _createClass(Resolver, null, [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(domain) { + var _opts$allowedRedirect; + var opts, + allowHttp, + timeout, + protocol, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 1 && _args[1] !== undefined ? _args[1] : {}; + allowHttp = typeof opts.allowHttp === "undefined" ? _config__WEBPACK_IMPORTED_MODULE_2__/* .Config */ .T.isAllowHttp() : opts.allowHttp; + timeout = typeof opts.timeout === "undefined" ? _config__WEBPACK_IMPORTED_MODULE_2__/* .Config */ .T.getTimeout() : opts.timeout; + protocol = allowHttp ? "http" : "https"; + return _context.abrupt("return", _http_client__WEBPACK_IMPORTED_MODULE_1__/* .httpClient */ .ok.get("".concat(protocol, "://").concat(domain, "/.well-known/stellar.toml"), { + maxRedirects: (_opts$allowedRedirect = opts.allowedRedirects) !== null && _opts$allowedRedirect !== void 0 ? _opts$allowedRedirect : 0, + maxContentLength: STELLAR_TOML_MAX_SIZE, + cancelToken: timeout ? new CancelToken(function (cancel) { + return setTimeout(function () { + return cancel("timeout of ".concat(timeout, "ms exceeded")); + }, timeout); + }) : undefined, + timeout: timeout + }).then(function (response) { + try { + var tomlObject = toml__WEBPACK_IMPORTED_MODULE_0___default().parse(response.data); + return Promise.resolve(tomlObject); + } catch (e) { + return Promise.reject(new Error("stellar.toml is invalid - Parsing error on line ".concat(e.line, ", column ").concat(e.column, ": ").concat(e.message))); + } + }).catch(function (err) { + if (err.message.match(/^maxContentLength size/)) { + throw new Error("stellar.toml file exceeds allowed size of ".concat(STELLAR_TOML_MAX_SIZE)); + } else { + throw err; + } + })); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + function resolve(_x) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }]); +}(); +var Api; + +/***/ }), + +/***/ 3121: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ A: () => (/* binding */ Utils) +/* harmony export */ }); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Utils = function () { + function Utils() { + _classCallCheck(this, Utils); + } + return _createClass(Utils, null, [{ + key: "validateTimebounds", + value: function validateTimebounds(transaction) { + var gracePeriod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + if (!transaction.timeBounds) { + return false; + } + var now = Math.floor(Date.now() / 1000); + var _transaction$timeBoun = transaction.timeBounds, + minTime = _transaction$timeBoun.minTime, + maxTime = _transaction$timeBoun.maxTime; + return now >= Number.parseInt(minTime, 10) - gracePeriod && now <= Number.parseInt(maxTime, 10) + gracePeriod; + } + }, { + key: "sleep", + value: function sleep(ms) { + return new Promise(function (resolve) { + return setTimeout(resolve, ms); + }); + } + }]); +}(); + +/***/ }), + +/***/ 5479: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + InvalidChallengeError: () => (/* reexport */ InvalidChallengeError), + buildChallengeTx: () => (/* reexport */ buildChallengeTx), + gatherTxSigners: () => (/* reexport */ gatherTxSigners), + readChallengeTx: () => (/* reexport */ readChallengeTx), + verifyChallengeTxSigners: () => (/* reexport */ verifyChallengeTxSigners), + verifyChallengeTxThreshold: () => (/* reexport */ verifyChallengeTxThreshold), + verifyTxSignedBy: () => (/* reexport */ verifyTxSignedBy) +}); + +// EXTERNAL MODULE: ./node_modules/randombytes/browser.js +var browser = __webpack_require__(3209); +var browser_default = /*#__PURE__*/__webpack_require__.n(browser); +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./src/utils.ts +var utils = __webpack_require__(3121); +;// ./src/webauth/errors.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var InvalidChallengeError = function (_Error) { + function InvalidChallengeError(message) { + var _this; + _classCallCheck(this, InvalidChallengeError); + var trueProto = (this instanceof InvalidChallengeError ? this.constructor : void 0).prototype; + _this = _callSuper(this, InvalidChallengeError, [message]); + _this.__proto__ = trueProto; + _this.constructor = InvalidChallengeError; + _this.name = "InvalidChallengeError"; + return _this; + } + _inherits(InvalidChallengeError, _Error); + return _createClass(InvalidChallengeError); +}(_wrapNativeSuper(Error)); +;// ./src/webauth/utils.ts +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function utils_typeof(o) { "@babel/helpers - typeof"; return utils_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, utils_typeof(o); } +function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } + + + + +function buildChallengeTx(serverKeypair, clientAccountID, homeDomain) { + var timeout = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 300; + var networkPassphrase = arguments.length > 4 ? arguments[4] : undefined; + var webAuthDomain = arguments.length > 5 ? arguments[5] : undefined; + var memo = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var clientDomain = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var clientSigningKey = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; + if (clientAccountID.startsWith("M") && memo) { + throw Error("memo cannot be used if clientAccountID is a muxed account"); + } + var account = new lib.Account(serverKeypair.publicKey(), "-1"); + var now = Math.floor(Date.now() / 1000); + var value = browser_default()(48).toString("base64"); + var builder = new lib.TransactionBuilder(account, { + fee: lib.BASE_FEE, + networkPassphrase: networkPassphrase, + timebounds: { + minTime: now, + maxTime: now + timeout + } + }).addOperation(lib.Operation.manageData({ + name: "".concat(homeDomain, " auth"), + value: value, + source: clientAccountID + })).addOperation(lib.Operation.manageData({ + name: "web_auth_domain", + value: webAuthDomain, + source: account.accountId() + })); + if (clientDomain) { + if (!clientSigningKey) { + throw Error("clientSigningKey is required if clientDomain is provided"); + } + builder.addOperation(lib.Operation.manageData({ + name: "client_domain", + value: clientDomain, + source: clientSigningKey + })); + } + if (memo) { + builder.addMemo(lib.Memo.id(memo)); + } + var transaction = builder.build(); + transaction.sign(serverKeypair); + return transaction.toEnvelope().toXDR("base64").toString(); +} +function readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain) { + var _transaction$timeBoun; + if (serverAccountID.startsWith("M")) { + throw Error("Invalid serverAccountID: multiplexed accounts are not supported."); + } + var transaction; + try { + transaction = new lib.Transaction(challengeTx, networkPassphrase); + } catch (_unused) { + try { + transaction = new lib.FeeBumpTransaction(challengeTx, networkPassphrase); + } catch (_unused2) { + throw new InvalidChallengeError("Invalid challenge: unable to deserialize challengeTx transaction string"); + } + throw new InvalidChallengeError("Invalid challenge: expected a Transaction but received a FeeBumpTransaction"); + } + var sequence = Number.parseInt(transaction.sequence, 10); + if (sequence !== 0) { + throw new InvalidChallengeError("The transaction sequence number should be zero"); + } + if (transaction.source !== serverAccountID) { + throw new InvalidChallengeError("The transaction source account is not equal to the server's account"); + } + if (transaction.operations.length < 1) { + throw new InvalidChallengeError("The transaction should contain at least one operation"); + } + var _transaction$operatio = _toArray(transaction.operations), + operation = _transaction$operatio[0], + subsequentOperations = _transaction$operatio.slice(1); + if (!operation.source) { + throw new InvalidChallengeError("The transaction's operation should contain a source account"); + } + var clientAccountID = operation.source; + var memo = null; + if (transaction.memo.type !== lib.MemoNone) { + if (clientAccountID.startsWith("M")) { + throw new InvalidChallengeError("The transaction has a memo but the client account ID is a muxed account"); + } + if (transaction.memo.type !== lib.MemoID) { + throw new InvalidChallengeError("The transaction's memo must be of type `id`"); + } + memo = transaction.memo.value; + } + if (operation.type !== "manageData") { + throw new InvalidChallengeError("The transaction's operation type should be 'manageData'"); + } + if (transaction.timeBounds && Number.parseInt((_transaction$timeBoun = transaction.timeBounds) === null || _transaction$timeBoun === void 0 ? void 0 : _transaction$timeBoun.maxTime, 10) === lib.TimeoutInfinite) { + throw new InvalidChallengeError("The transaction requires non-infinite timebounds"); + } + if (!utils/* Utils */.A.validateTimebounds(transaction, 60 * 5)) { + throw new InvalidChallengeError("The transaction has expired"); + } + if (operation.value === undefined) { + throw new InvalidChallengeError("The transaction's operation values should not be null"); + } + if (!operation.value) { + throw new InvalidChallengeError("The transaction's operation value should not be null"); + } + if (Buffer.from(operation.value.toString(), "base64").length !== 48) { + throw new InvalidChallengeError("The transaction's operation value should be a 64 bytes base64 random string"); + } + if (!homeDomains) { + throw new InvalidChallengeError("Invalid homeDomains: a home domain must be provided for verification"); + } + var matchedHomeDomain; + if (typeof homeDomains === "string") { + if ("".concat(homeDomains, " auth") === operation.name) { + matchedHomeDomain = homeDomains; + } + } else if (Array.isArray(homeDomains)) { + matchedHomeDomain = homeDomains.find(function (domain) { + return "".concat(domain, " auth") === operation.name; + }); + } else { + throw new InvalidChallengeError("Invalid homeDomains: homeDomains type is ".concat(utils_typeof(homeDomains), " but should be a string or an array")); + } + if (!matchedHomeDomain) { + throw new InvalidChallengeError("Invalid homeDomains: the transaction's operation key name does not match the expected home domain"); + } + var _iterator = _createForOfIteratorHelper(subsequentOperations), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var op = _step.value; + if (op.type !== "manageData") { + throw new InvalidChallengeError("The transaction has operations that are not of type 'manageData'"); + } + if (op.source !== serverAccountID && op.name !== "client_domain") { + throw new InvalidChallengeError("The transaction has operations that are unrecognized"); + } + if (op.name === "web_auth_domain") { + if (op.value === undefined) { + throw new InvalidChallengeError("'web_auth_domain' operation value should not be null"); + } + if (op.value.compare(Buffer.from(webAuthDomain))) { + throw new InvalidChallengeError("'web_auth_domain' operation value does not match ".concat(webAuthDomain)); + } + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + if (!verifyTxSignedBy(transaction, serverAccountID)) { + throw new InvalidChallengeError("Transaction not signed by server: '".concat(serverAccountID, "'")); + } + return { + tx: transaction, + clientAccountID: clientAccountID, + matchedHomeDomain: matchedHomeDomain, + memo: memo + }; +} +function verifyChallengeTxThreshold(challengeTx, serverAccountID, networkPassphrase, threshold, signerSummary, homeDomains, webAuthDomain) { + var signers = signerSummary.map(function (signer) { + return signer.key; + }); + var signersFound = verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain); + var weight = 0; + var _loop = function _loop() { + var _signerSummary$find; + var signer = _signersFound[_i]; + var sigWeight = ((_signerSummary$find = signerSummary.find(function (s) { + return s.key === signer; + })) === null || _signerSummary$find === void 0 ? void 0 : _signerSummary$find.weight) || 0; + weight += sigWeight; + }; + for (var _i = 0, _signersFound = signersFound; _i < _signersFound.length; _i++) { + _loop(); + } + if (weight < threshold) { + throw new InvalidChallengeError("signers with weight ".concat(weight, " do not meet threshold ").concat(threshold, "\"")); + } + return signersFound; +} +function verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain) { + var _readChallengeTx = readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain), + tx = _readChallengeTx.tx; + var serverKP; + try { + serverKP = lib.Keypair.fromPublicKey(serverAccountID); + } catch (err) { + throw new Error("Couldn't infer keypair from the provided 'serverAccountID': ".concat(err.message)); + } + var clientSigners = new Set(); + var _iterator2 = _createForOfIteratorHelper(signers), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var _signer = _step2.value; + if (_signer === serverKP.publicKey()) { + continue; + } + if (_signer.charAt(0) !== "G") { + continue; + } + clientSigners.add(_signer); + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + if (clientSigners.size === 0) { + throw new InvalidChallengeError("No verifiable client signers provided, at least one G... address must be provided"); + } + var clientSigningKey; + var _iterator3 = _createForOfIteratorHelper(tx.operations), + _step3; + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + var op = _step3.value; + if (op.type === "manageData" && op.name === "client_domain") { + if (clientSigningKey) { + throw new InvalidChallengeError("Found more than one client_domain operation"); + } + clientSigningKey = op.source; + } + } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); + } + var allSigners = [serverKP.publicKey()].concat(_toConsumableArray(Array.from(clientSigners))); + if (clientSigningKey) { + allSigners.push(clientSigningKey); + } + var signersFound = gatherTxSigners(tx, allSigners); + var serverSignatureFound = false; + var clientSigningKeySignatureFound = false; + for (var _i2 = 0, _signersFound2 = signersFound; _i2 < _signersFound2.length; _i2++) { + var signer = _signersFound2[_i2]; + if (signer === serverKP.publicKey()) { + serverSignatureFound = true; + } + if (signer === clientSigningKey) { + clientSigningKeySignatureFound = true; + } + } + if (!serverSignatureFound) { + throw new InvalidChallengeError("Transaction not signed by server: '".concat(serverKP.publicKey(), "'")); + } + if (clientSigningKey && !clientSigningKeySignatureFound) { + throw new InvalidChallengeError("Transaction not signed by the source account of the 'client_domain' " + "ManageData operation"); + } + if (signersFound.length === 1) { + throw new InvalidChallengeError("None of the given signers match the transaction signatures"); + } + if (signersFound.length !== tx.signatures.length) { + throw new InvalidChallengeError("Transaction has unrecognized signatures"); + } + signersFound.splice(signersFound.indexOf(serverKP.publicKey()), 1); + if (clientSigningKey) { + signersFound.splice(signersFound.indexOf(clientSigningKey), 1); + } + return signersFound; +} +function verifyTxSignedBy(transaction, accountID) { + return gatherTxSigners(transaction, [accountID]).length !== 0; +} +function gatherTxSigners(transaction, signers) { + var hashedSignatureBase = transaction.hash(); + var txSignatures = _toConsumableArray(transaction.signatures); + var signersFound = new Set(); + var _iterator4 = _createForOfIteratorHelper(signers), + _step4; + try { + for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { + var signer = _step4.value; + if (txSignatures.length === 0) { + break; + } + var keypair = void 0; + try { + keypair = lib.Keypair.fromPublicKey(signer); + } catch (err) { + throw new InvalidChallengeError("Signer is not a valid address: ".concat(err.message)); + } + for (var i = 0; i < txSignatures.length; i++) { + var decSig = txSignatures[i]; + if (!decSig.hint().equals(keypair.signatureHint())) { + continue; + } + if (keypair.verify(hashedSignatureBase, decSig.signature())) { + signersFound.add(signer); + txSignatures.splice(i, 1); + break; + } + } + } + } catch (err) { + _iterator4.e(err); + } finally { + _iterator4.f(); + } + return Array.from(signersFound); +} +;// ./src/webauth/index.ts + + + +/***/ }), + +/***/ 5360: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +/** + * Generate a character map. + * @param {string} alphabet e.g. "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" + * @param {object} mappings map overrides from key to value + * @method + */ + +var charmap = function (alphabet, mappings) { + mappings || (mappings = {}); + alphabet.split("").forEach(function (c, i) { + if (!(c in mappings)) mappings[c] = i; + }); + return mappings; +} + +/** + * The RFC 4648 base 32 alphabet and character map. + * @see {@link https://tools.ietf.org/html/rfc4648} + */ + +var rfc4648 = { + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", + charmap: { + 0: 14, + 1: 8 + } +}; + +rfc4648.charmap = charmap(rfc4648.alphabet, rfc4648.charmap); + +/** + * The Crockford base 32 alphabet and character map. + * @see {@link http://www.crockford.com/wrmg/base32.html} + */ + +var crockford = { + alphabet: "0123456789ABCDEFGHJKMNPQRSTVWXYZ", + charmap: { + O: 0, + I: 1, + L: 1 + } +}; + +crockford.charmap = charmap(crockford.alphabet, crockford.charmap); + +/** + * base32hex + * @see {@link https://en.wikipedia.org/wiki/Base32#base32hex} + */ + +var base32hex = { + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", + charmap: {} +}; + +base32hex.charmap = charmap(base32hex.alphabet, base32hex.charmap); + +/** + * Create a new `Decoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [charmap] Override the character map used in decoding. + * @constructor + */ + +function Decoder (options) { + this.buf = []; + this.shift = 8; + this.carry = 0; + + if (options) { + + switch (options.type) { + case "rfc4648": + this.charmap = exports.rfc4648.charmap; + break; + case "crockford": + this.charmap = exports.crockford.charmap; + break; + case "base32hex": + this.charmap = exports.base32hex.charmap; + break; + default: + throw new Error("invalid type"); + } + + if (options.charmap) this.charmap = options.charmap; + } +} + +/** + * The default character map coresponds to RFC4648. + */ + +Decoder.prototype.charmap = rfc4648.charmap; + +/** + * Decode a string, continuing from the previous state. + * + * @param {string} str + * @return {Decoder} this + */ + +Decoder.prototype.write = function (str) { + var charmap = this.charmap; + var buf = this.buf; + var shift = this.shift; + var carry = this.carry; + + // decode string + str.toUpperCase().split("").forEach(function (char) { + + // ignore padding + if (char == "=") return; + + // lookup symbol + var symbol = charmap[char] & 0xff; + + // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 + + shift -= 5; + if (shift > 0) { + carry |= symbol << shift; + } else if (shift < 0) { + buf.push(carry | (symbol >> -shift)); + shift += 8; + carry = (symbol << shift) & 0xff; + } else { + buf.push(carry | symbol); + shift = 8; + carry = 0; + } + }); + + // save state + this.shift = shift; + this.carry = carry; + + // for chaining + return this; +}; + +/** + * Finish decoding. + * + * @param {string} [str] The final string to decode. + * @return {Array} Decoded byte array. + */ + +Decoder.prototype.finalize = function (str) { + if (str) { + this.write(str); + } + if (this.shift !== 8 && this.carry !== 0) { + this.buf.push(this.carry); + this.shift = 8; + this.carry = 0; + } + return this.buf; +}; + +/** + * Create a new `Encoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [alphabet] Override the alphabet used in encoding. + * @constructor + */ + +function Encoder (options) { + this.buf = ""; + this.shift = 3; + this.carry = 0; + + if (options) { + + switch (options.type) { + case "rfc4648": + this.alphabet = exports.rfc4648.alphabet; + break; + case "crockford": + this.alphabet = exports.crockford.alphabet; + break; + case "base32hex": + this.alphabet = exports.base32hex.alphabet; + break; + default: + throw new Error("invalid type"); + } + + if (options.alphabet) this.alphabet = options.alphabet; + else if (options.lc) this.alphabet = this.alphabet.toLowerCase(); + } +} + +/** + * The default alphabet coresponds to RFC4648. + */ + +Encoder.prototype.alphabet = rfc4648.alphabet; + +/** + * Encode a byte array, continuing from the previous state. + * + * @param {byte[]} buf The byte array to encode. + * @return {Encoder} this + */ + +Encoder.prototype.write = function (buf) { + var shift = this.shift; + var carry = this.carry; + var symbol; + var byte; + var i; + + // encode each byte in buf + for (i = 0; i < buf.length; i++) { + byte = buf[i]; + + // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 + + symbol = carry | (byte >> shift); + this.buf += this.alphabet[symbol & 0x1f]; + + if (shift > 5) { + shift -= 5; + symbol = byte >> shift; + this.buf += this.alphabet[symbol & 0x1f]; + } + + shift = 5 - shift; + carry = byte << shift; + shift = 8 - shift; + } + + // save state + this.shift = shift; + this.carry = carry; + + // for chaining + return this; +}; + +/** + * Finish encoding. + * + * @param {byte[]} [buf] The final byte array to encode. + * @return {string} The encoded byte array. + */ + +Encoder.prototype.finalize = function (buf) { + if (buf) { + this.write(buf); + } + if (this.shift !== 3) { + this.buf += this.alphabet[this.carry & 0x1f]; + this.shift = 3; + this.carry = 0; + } + return this.buf; +}; + +/** + * Convenience encoder. + * + * @param {byte[]} buf The byte array to encode. + * @param {object} [options] Options to pass to the encoder. + * @return {string} The encoded string. + */ + +exports.encode = function (buf, options) { + return new Encoder(options).finalize(buf); +}; + +/** + * Convenience decoder. + * + * @param {string} str The string to decode. + * @param {object} [options] Options to pass to the decoder. + * @return {byte[]} The decoded byte array. + */ + +exports.decode = function (str, options) { + return new Decoder(options).finalize(str); +}; + +// Exports. +exports.Decoder = Decoder; +exports.Encoder = Encoder; +exports.charmap = charmap; +exports.crockford = crockford; +exports.rfc4648 = rfc4648; +exports.base32hex = base32hex; + + +/***/ }), + +/***/ 7526: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + + +/***/ }), + +/***/ 1594: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_RESULT__;;(function (globalObject) { + 'use strict'; + +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + + var BigNumber, + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + + /* + * Create and return a BigNumber constructor. + */ + function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; + } + + + // PRIVATE HELPER FUNCTIONS + + // These functions don't need access to variables, + // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + + function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; + } + + + // Return a coefficient array as a string of base 10 digits. + function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); + } + + + // Compare the value of BigNumbers x and y. + function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; + } + + + /* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ + function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } + } + + + // Assumes finite n. + function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; + } + + + function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; + } + + + function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; + } + + + // EXPORT + + + BigNumber = clone(); + BigNumber['default'] = BigNumber.BigNumber = BigNumber; + + // AMD. + if (true) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return BigNumber; }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + // Node.js and other environments that support module.exports. + } else {} +})(this); + + +/***/ }), + +/***/ 8287: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + + + +const base64 = __webpack_require__(7526) +const ieee754 = __webpack_require__(251) +const customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +const K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + const arr = new Uint8Array(1) + const proto = { foo: function () { return 42 } } + Object.setPrototypeOf(proto, Uint8Array.prototype) + Object.setPrototypeOf(arr, proto) + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + const buf = new Uint8Array(length) + Object.setPrototypeOf(buf, Buffer.prototype) + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + const valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + const b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) +Object.setPrototypeOf(Buffer, Uint8Array) + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + const length = byteLength(string, encoding) | 0 + let buf = createBuffer(length) + + const actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0 + const buf = createBuffer(length) + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView) + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + let buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype) + + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + const len = checked(obj.length) | 0 + const buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + let x = a.length + let y = b.length + + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + let i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + const buffer = Buffer.allocUnsafe(length) + let pos = 0 + for (i = 0; i < list.length; ++i) { + let buf = list[i] + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) + buf.copy(buffer, pos) + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ) + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos) + } + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + const len = string.length + const mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + let loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + let loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + const i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + const len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + const len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + const len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + const length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + let str = '' + const max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + let x = thisEnd - thisStart + let y = end - start + const len = Math.min(x, y) + + const thisCopy = this.slice(thisStart, thisEnd) + const targetCopy = target.slice(start, end) + + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + let indexSize = 1 + let arrLength = arr.length + let valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + let i + if (dir) { + let foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + let found = true + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + const remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + const strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + let i + for (i = 0; i < length; ++i) { + const parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + const remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + let loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + const res = [] + + let i = start + while (i < end) { + const firstByte = buf[i] + let codePoint = null + let bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +const MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + const len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + let res = '' + let i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + const len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + let out = '' + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]] + } + return out +} + +function utf16leSlice (buf, start, end) { + const bytes = buf.slice(start, end) + let res = '' + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + const len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + const newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype) + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + let val = this[offset + --byteLength] + let mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const lo = first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24 + + const hi = this[++offset] + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + last * 2 ** 24 + + return BigInt(lo) + (BigInt(hi) << BigInt(32)) +}) + +Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const hi = first * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + const lo = this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last + + return (BigInt(hi) << BigInt(32)) + BigInt(lo) +}) + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let i = byteLength + let mul = 1 + let val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = this[offset + 4] + + this[offset + 5] * 2 ** 8 + + this[offset + 6] * 2 ** 16 + + (last << 24) // Overflow + + return (BigInt(val) << BigInt(32)) + + BigInt(first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24) +}) + +Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + return (BigInt(val) << BigInt(32)) + + BigInt(this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last) +}) + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let mul = 1 + let i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let i = byteLength - 1 + let mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function wrtBigUInt64LE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + return offset +} + +function wrtBigUInt64BE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset + 7] = lo + lo = lo >> 8 + buf[offset + 6] = lo + lo = lo >> 8 + buf[offset + 5] = lo + lo = lo >> 8 + buf[offset + 4] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset + 3] = hi + hi = hi >> 8 + buf[offset + 2] = hi + hi = hi >> 8 + buf[offset + 1] = hi + hi = hi >> 8 + buf[offset] = hi + return offset + 8 +} + +Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = 0 + let mul = 1 + let sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = byteLength - 1 + let mul = 1 + let sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + const len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + const code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } else if (typeof val === 'boolean') { + val = Number(val) + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + let i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + const bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + const len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// CUSTOM ERRORS +// ============= + +// Simplified versions from Node, changed for Buffer-only usage +const errors = {} +function E (sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor () { + super() + + Object.defineProperty(this, 'message', { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }) + + // Add the error code to the name to include it in the stack trace. + this.name = `${this.name} [${sym}]` + // Access the stack to generate the error message including the error code + // from the name. + this.stack // eslint-disable-line no-unused-expressions + // Reset the name to the actual name. + delete this.name + } + + get code () { + return sym + } + + set code (value) { + Object.defineProperty(this, 'code', { + configurable: true, + enumerable: true, + value, + writable: true + }) + } + + toString () { + return `${this.name} [${sym}]: ${this.message}` + } + } +} + +E('ERR_BUFFER_OUT_OF_BOUNDS', + function (name) { + if (name) { + return `${name} is outside of buffer bounds` + } + + return 'Attempt to access memory outside buffer bounds' + }, RangeError) +E('ERR_INVALID_ARG_TYPE', + function (name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}` + }, TypeError) +E('ERR_OUT_OF_RANGE', + function (str, range, input) { + let msg = `The value of "${str}" is out of range.` + let received = input + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)) + } else if (typeof input === 'bigint') { + received = String(input) + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received) + } + received += 'n' + } + msg += ` It must be ${range}. Received ${received}` + return msg + }, RangeError) + +function addNumericalSeparator (val) { + let res = '' + let i = val.length + const start = val[0] === '-' ? 1 : 0 + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}` + } + return `${val.slice(0, i)}${res}` +} + +// CHECK FUNCTIONS +// =============== + +function checkBounds (buf, offset, byteLength) { + validateNumber(offset, 'offset') + if (buf[offset] === undefined || buf[offset + byteLength] === undefined) { + boundsError(offset, buf.length - (byteLength + 1)) + } +} + +function checkIntBI (value, min, max, buf, offset, byteLength) { + if (value > max || value < min) { + const n = typeof min === 'bigint' ? 'n' : '' + let range + if (byteLength > 3) { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}` + } else { + range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` + + `${(byteLength + 1) * 8 - 1}${n}` + } + } else { + range = `>= ${min}${n} and <= ${max}${n}` + } + throw new errors.ERR_OUT_OF_RANGE('value', range, value) + } + checkBounds(buf, offset, byteLength) +} + +function validateNumber (value, name) { + if (typeof value !== 'number') { + throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value) + } +} + +function boundsError (value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type) + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value) + } + + if (length < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS() + } + + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', + `>= ${type ? 1 : 0} and <= ${length}`, + value) +} + +// HELPER FUNCTIONS +// ================ + +const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function utf8ToBytes (string, units) { + units = units || Infinity + let codePoint + const length = string.length + let leadSurrogate = null + const bytes = [] + + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + let c, hi, lo + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + let i + for (i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +const hexSliceLookupTable = (function () { + const alphabet = '0123456789abcdef' + const table = new Array(256) + for (let i = 0; i < 16; ++i) { + const i16 = i * 16 + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})() + +// Return not function with Error if BigInt not supported +function defineBigIntMethod (fn) { + return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn +} + +function BufferBigIntNotDefined () { + throw new Error('BigInt not supported') +} + + +/***/ }), + +/***/ 251: +/***/ ((__unused_webpack_module, exports) => { + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + + +/***/ }), + +/***/ 6698: +/***/ ((module) => { + +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 + } + } +} + + +/***/ }), + +/***/ 3209: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"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 = (__webpack_require__(2861).Buffer) +var crypto = __webpack_require__.g.crypto || __webpack_require__.g.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 +} + + +/***/ }), + +/***/ 2861: +/***/ ((module, exports, __webpack_require__) => { + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(8287) +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) +} + + +/***/ }), + +/***/ 392: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2802: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +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 = __webpack_require__(7816) +exports.sha1 = __webpack_require__(3737) +exports.sha224 = __webpack_require__(6710) +exports.sha256 = __webpack_require__(4107) +exports.sha384 = __webpack_require__(2827) +exports.sha512 = __webpack_require__(2890) + + +/***/ }), + +/***/ 7816: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 3737: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 6710: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * 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 = __webpack_require__(6698) +var Sha256 = __webpack_require__(4107) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 4107: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2827: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698) +var SHA512 = __webpack_require__(2890) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2890: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 1293: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var parser = __webpack_require__(5546); +var compiler = __webpack_require__(2708); + +module.exports = { + parse: function(input) { + var nodes = parser.parse(input.toString()); + return compiler.compile(nodes); + } +}; + + +/***/ }), + +/***/ 2708: +/***/ ((module) => { + +"use strict"; + +function compile(nodes) { + var assignedPaths = []; + var valueAssignments = []; + var currentPath = ""; + var data = Object.create(null); + var context = data; + var arrayMode = false; + + return reduce(nodes); + + function reduce(nodes) { + var node; + for (var i = 0; i < nodes.length; i++) { + node = nodes[i]; + switch (node.type) { + case "Assign": + assign(node); + break; + case "ObjectPath": + setPath(node); + break; + case "ArrayPath": + addTableArray(node); + break; + } + } + + return data; + } + + function genError(err, line, col) { + var ex = new Error(err); + ex.line = line; + ex.column = col; + throw ex; + } + + function assign(node) { + var key = node.key; + var value = node.value; + var line = node.line; + var column = node.column; + + var fullPath; + if (currentPath) { + fullPath = currentPath + "." + key; + } else { + fullPath = key; + } + if (typeof context[key] !== "undefined") { + genError("Cannot redefine existing key '" + fullPath + "'.", line, column); + } + + context[key] = reduceValueNode(value); + + if (!pathAssigned(fullPath)) { + assignedPaths.push(fullPath); + valueAssignments.push(fullPath); + } + } + + + function pathAssigned(path) { + return assignedPaths.indexOf(path) !== -1; + } + + function reduceValueNode(node) { + if (node.type === "Array") { + return reduceArrayWithTypeChecking(node.value); + } else if (node.type === "InlineTable") { + return reduceInlineTableNode(node.value); + } else { + return node.value; + } + } + + function reduceInlineTableNode(values) { + var obj = Object.create(null); + for (var i = 0; i < values.length; i++) { + var val = values[i]; + if (val.value.type === "InlineTable") { + obj[val.key] = reduceInlineTableNode(val.value.value); + } else if (val.type === "InlineTableValue") { + obj[val.key] = reduceValueNode(val.value); + } + } + + return obj; + } + + function setPath(node) { + var path = node.value; + var quotedPath = path.map(quoteDottedString).join("."); + var line = node.line; + var column = node.column; + + if (pathAssigned(quotedPath)) { + genError("Cannot redefine existing key '" + path + "'.", line, column); + } + assignedPaths.push(quotedPath); + context = deepRef(data, path, Object.create(null), line, column); + currentPath = path; + } + + function addTableArray(node) { + var path = node.value; + var quotedPath = path.map(quoteDottedString).join("."); + var line = node.line; + var column = node.column; + + if (!pathAssigned(quotedPath)) { + assignedPaths.push(quotedPath); + } + assignedPaths = assignedPaths.filter(function(p) { + return p.indexOf(quotedPath) !== 0; + }); + assignedPaths.push(quotedPath); + context = deepRef(data, path, [], line, column); + currentPath = quotedPath; + + if (context instanceof Array) { + var newObj = Object.create(null); + context.push(newObj); + context = newObj; + } else { + genError("Cannot redefine existing key '" + path + "'.", line, column); + } + } + + // Given a path 'a.b.c', create (as necessary) `start.a`, + // `start.a.b`, and `start.a.b.c`, assigning `value` to `start.a.b.c`. + // If `a` or `b` are arrays and have items in them, the last item in the + // array is used as the context for the next sub-path. + function deepRef(start, keys, value, line, column) { + var traversed = []; + var traversedPath = ""; + var path = keys.join("."); + var ctx = start; + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + traversed.push(key); + traversedPath = traversed.join("."); + if (typeof ctx[key] === "undefined") { + if (i === keys.length - 1) { + ctx[key] = value; + } else { + ctx[key] = Object.create(null); + } + } else if (i !== keys.length - 1 && valueAssignments.indexOf(traversedPath) > -1) { + // already a non-object value at key, can't be used as part of a new path + genError("Cannot redefine existing key '" + traversedPath + "'.", line, column); + } + + ctx = ctx[key]; + if (ctx instanceof Array && ctx.length && i < keys.length - 1) { + ctx = ctx[ctx.length - 1]; + } + } + + return ctx; + } + + function reduceArrayWithTypeChecking(array) { + // Ensure that all items in the array are of the same type + var firstType = null; + for (var i = 0; i < array.length; i++) { + var node = array[i]; + if (firstType === null) { + firstType = node.type; + } else { + if (node.type !== firstType) { + genError("Cannot add value of type " + node.type + " to array of type " + + firstType + ".", node.line, node.column); + } + } + } + + // Recursively reduce array of nodes into array of the nodes' values + return array.map(reduceValueNode); + } + + function quoteDottedString(str) { + if (str.indexOf(".") > -1) { + return "\"" + str + "\""; + } else { + return str; + } + } +} + +module.exports = { + compile: compile +}; + + +/***/ }), + +/***/ 5546: +/***/ ((module) => { + +module.exports = (function() { + /* + * Generated by PEG.js 0.8.0. + * + * http://pegjs.majda.cz/ + */ + + function peg$subclass(child, parent) { + function ctor() { this.constructor = child; } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + + function SyntaxError(message, expected, found, offset, line, column) { + this.message = message; + this.expected = expected; + this.found = found; + this.offset = offset; + this.line = line; + this.column = column; + + this.name = "SyntaxError"; + } + + peg$subclass(SyntaxError, Error); + + function parse(input) { + var options = arguments.length > 1 ? arguments[1] : {}, + + peg$FAILED = {}, + + peg$startRuleFunctions = { start: peg$parsestart }, + peg$startRuleFunction = peg$parsestart, + + peg$c0 = [], + peg$c1 = function() { return nodes }, + peg$c2 = peg$FAILED, + peg$c3 = "#", + peg$c4 = { type: "literal", value: "#", description: "\"#\"" }, + peg$c5 = void 0, + peg$c6 = { type: "any", description: "any character" }, + peg$c7 = "[", + peg$c8 = { type: "literal", value: "[", description: "\"[\"" }, + peg$c9 = "]", + peg$c10 = { type: "literal", value: "]", description: "\"]\"" }, + peg$c11 = function(name) { addNode(node('ObjectPath', name, line, column)) }, + peg$c12 = function(name) { addNode(node('ArrayPath', name, line, column)) }, + peg$c13 = function(parts, name) { return parts.concat(name) }, + peg$c14 = function(name) { return [name] }, + peg$c15 = function(name) { return name }, + peg$c16 = ".", + peg$c17 = { type: "literal", value: ".", description: "\".\"" }, + peg$c18 = "=", + peg$c19 = { type: "literal", value: "=", description: "\"=\"" }, + peg$c20 = function(key, value) { addNode(node('Assign', value, line, column, key)) }, + peg$c21 = function(chars) { return chars.join('') }, + peg$c22 = function(node) { return node.value }, + peg$c23 = "\"\"\"", + peg$c24 = { type: "literal", value: "\"\"\"", description: "\"\\\"\\\"\\\"\"" }, + peg$c25 = null, + peg$c26 = function(chars) { return node('String', chars.join(''), line, column) }, + peg$c27 = "\"", + peg$c28 = { type: "literal", value: "\"", description: "\"\\\"\"" }, + peg$c29 = "'''", + peg$c30 = { type: "literal", value: "'''", description: "\"'''\"" }, + peg$c31 = "'", + peg$c32 = { type: "literal", value: "'", description: "\"'\"" }, + peg$c33 = function(char) { return char }, + peg$c34 = function(char) { return char}, + peg$c35 = "\\", + peg$c36 = { type: "literal", value: "\\", description: "\"\\\\\"" }, + peg$c37 = function() { return '' }, + peg$c38 = "e", + peg$c39 = { type: "literal", value: "e", description: "\"e\"" }, + peg$c40 = "E", + peg$c41 = { type: "literal", value: "E", description: "\"E\"" }, + peg$c42 = function(left, right) { return node('Float', parseFloat(left + 'e' + right), line, column) }, + peg$c43 = function(text) { return node('Float', parseFloat(text), line, column) }, + peg$c44 = "+", + peg$c45 = { type: "literal", value: "+", description: "\"+\"" }, + peg$c46 = function(digits) { return digits.join('') }, + peg$c47 = "-", + peg$c48 = { type: "literal", value: "-", description: "\"-\"" }, + peg$c49 = function(digits) { return '-' + digits.join('') }, + peg$c50 = function(text) { return node('Integer', parseInt(text, 10), line, column) }, + peg$c51 = "true", + peg$c52 = { type: "literal", value: "true", description: "\"true\"" }, + peg$c53 = function() { return node('Boolean', true, line, column) }, + peg$c54 = "false", + peg$c55 = { type: "literal", value: "false", description: "\"false\"" }, + peg$c56 = function() { return node('Boolean', false, line, column) }, + peg$c57 = function() { return node('Array', [], line, column) }, + peg$c58 = function(value) { return node('Array', value ? [value] : [], line, column) }, + peg$c59 = function(values) { return node('Array', values, line, column) }, + peg$c60 = function(values, value) { return node('Array', values.concat(value), line, column) }, + peg$c61 = function(value) { return value }, + peg$c62 = ",", + peg$c63 = { type: "literal", value: ",", description: "\",\"" }, + peg$c64 = "{", + peg$c65 = { type: "literal", value: "{", description: "\"{\"" }, + peg$c66 = "}", + peg$c67 = { type: "literal", value: "}", description: "\"}\"" }, + peg$c68 = function(values) { return node('InlineTable', values, line, column) }, + peg$c69 = function(key, value) { return node('InlineTableValue', value, line, column, key) }, + peg$c70 = function(digits) { return "." + digits }, + peg$c71 = function(date) { return date.join('') }, + peg$c72 = ":", + peg$c73 = { type: "literal", value: ":", description: "\":\"" }, + peg$c74 = function(time) { return time.join('') }, + peg$c75 = "T", + peg$c76 = { type: "literal", value: "T", description: "\"T\"" }, + peg$c77 = "Z", + peg$c78 = { type: "literal", value: "Z", description: "\"Z\"" }, + peg$c79 = function(date, time) { return node('Date', new Date(date + "T" + time + "Z"), line, column) }, + peg$c80 = function(date, time) { return node('Date', new Date(date + "T" + time), line, column) }, + peg$c81 = /^[ \t]/, + peg$c82 = { type: "class", value: "[ \\t]", description: "[ \\t]" }, + peg$c83 = "\n", + peg$c84 = { type: "literal", value: "\n", description: "\"\\n\"" }, + peg$c85 = "\r", + peg$c86 = { type: "literal", value: "\r", description: "\"\\r\"" }, + peg$c87 = /^[0-9a-f]/i, + peg$c88 = { type: "class", value: "[0-9a-f]i", description: "[0-9a-f]i" }, + peg$c89 = /^[0-9]/, + peg$c90 = { type: "class", value: "[0-9]", description: "[0-9]" }, + peg$c91 = "_", + peg$c92 = { type: "literal", value: "_", description: "\"_\"" }, + peg$c93 = function() { return "" }, + peg$c94 = /^[A-Za-z0-9_\-]/, + peg$c95 = { type: "class", value: "[A-Za-z0-9_\\-]", description: "[A-Za-z0-9_\\-]" }, + peg$c96 = function(d) { return d.join('') }, + peg$c97 = "\\\"", + peg$c98 = { type: "literal", value: "\\\"", description: "\"\\\\\\\"\"" }, + peg$c99 = function() { return '"' }, + peg$c100 = "\\\\", + peg$c101 = { type: "literal", value: "\\\\", description: "\"\\\\\\\\\"" }, + peg$c102 = function() { return '\\' }, + peg$c103 = "\\b", + peg$c104 = { type: "literal", value: "\\b", description: "\"\\\\b\"" }, + peg$c105 = function() { return '\b' }, + peg$c106 = "\\t", + peg$c107 = { type: "literal", value: "\\t", description: "\"\\\\t\"" }, + peg$c108 = function() { return '\t' }, + peg$c109 = "\\n", + peg$c110 = { type: "literal", value: "\\n", description: "\"\\\\n\"" }, + peg$c111 = function() { return '\n' }, + peg$c112 = "\\f", + peg$c113 = { type: "literal", value: "\\f", description: "\"\\\\f\"" }, + peg$c114 = function() { return '\f' }, + peg$c115 = "\\r", + peg$c116 = { type: "literal", value: "\\r", description: "\"\\\\r\"" }, + peg$c117 = function() { return '\r' }, + peg$c118 = "\\U", + peg$c119 = { type: "literal", value: "\\U", description: "\"\\\\U\"" }, + peg$c120 = function(digits) { return convertCodePoint(digits.join('')) }, + peg$c121 = "\\u", + peg$c122 = { type: "literal", value: "\\u", description: "\"\\\\u\"" }, + + peg$currPos = 0, + peg$reportedPos = 0, + peg$cachedPos = 0, + peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }, + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$silentFails = 0, + + peg$cache = {}, + peg$result; + + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + + function text() { + return input.substring(peg$reportedPos, peg$currPos); + } + + function offset() { + return peg$reportedPos; + } + + function line() { + return peg$computePosDetails(peg$reportedPos).line; + } + + function column() { + return peg$computePosDetails(peg$reportedPos).column; + } + + function expected(description) { + throw peg$buildException( + null, + [{ type: "other", description: description }], + peg$reportedPos + ); + } + + function error(message) { + throw peg$buildException(message, null, peg$reportedPos); + } + + function peg$computePosDetails(pos) { + function advance(details, startPos, endPos) { + var p, ch; + + for (p = startPos; p < endPos; p++) { + ch = input.charAt(p); + if (ch === "\n") { + if (!details.seenCR) { details.line++; } + details.column = 1; + details.seenCR = false; + } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { + details.line++; + details.column = 1; + details.seenCR = true; + } else { + details.column++; + details.seenCR = false; + } + } + } + + if (peg$cachedPos !== pos) { + if (peg$cachedPos > pos) { + peg$cachedPos = 0; + peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }; + } + advance(peg$cachedPosDetails, peg$cachedPos, pos); + peg$cachedPos = pos; + } + + return peg$cachedPosDetails; + } + + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { return; } + + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + + peg$maxFailExpected.push(expected); + } + + function peg$buildException(message, expected, pos) { + function cleanupExpected(expected) { + var i = 1; + + expected.sort(function(a, b) { + if (a.description < b.description) { + return -1; + } else if (a.description > b.description) { + return 1; + } else { + return 0; + } + }); + + while (i < expected.length) { + if (expected[i - 1] === expected[i]) { + expected.splice(i, 1); + } else { + i++; + } + } + } + + function buildMessage(expected, found) { + function stringEscape(s) { + function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } + + return s + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\x08/g, '\\b') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\f/g, '\\f') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); }) + .replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); }) + .replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); }); + } + + var expectedDescs = new Array(expected.length), + expectedDesc, foundDesc, i; + + for (i = 0; i < expected.length; i++) { + expectedDescs[i] = expected[i].description; + } + + expectedDesc = expected.length > 1 + ? expectedDescs.slice(0, -1).join(", ") + + " or " + + expectedDescs[expected.length - 1] + : expectedDescs[0]; + + foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input"; + + return "Expected " + expectedDesc + " but " + foundDesc + " found."; + } + + var posDetails = peg$computePosDetails(pos), + found = pos < input.length ? input.charAt(pos) : null; + + if (expected !== null) { + cleanupExpected(expected); + } + + return new SyntaxError( + message !== null ? message : buildMessage(expected, found), + expected, + found, + pos, + posDetails.line, + posDetails.column + ); + } + + function peg$parsestart() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 0, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseline(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseline(); + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c1(); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseline() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 1, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parseexpression(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parsecomment(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parsecomment(); + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseNL(); + if (s6 !== peg$FAILED) { + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseNL(); + } + } else { + s5 = peg$c2; + } + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseNL(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseNL(); + } + } else { + s2 = peg$c2; + } + if (s2 === peg$FAILED) { + s2 = peg$parseEOF(); + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$parseNL(); + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseexpression() { + var s0; + + var key = peg$currPos * 49 + 2, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsecomment(); + if (s0 === peg$FAILED) { + s0 = peg$parsepath(); + if (s0 === peg$FAILED) { + s0 = peg$parsetablearray(); + if (s0 === peg$FAILED) { + s0 = peg$parseassignment(); + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsecomment() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 3, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c3; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c4); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNL(); + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = peg$c5; + } else { + peg$currPos = s4; + s4 = peg$c2; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } else { + peg$currPos = s3; + s3 = peg$c2; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNL(); + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = peg$c5; + } else { + peg$currPos = s4; + s4 = peg$c2; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsepath() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 4, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetable_key(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s5 = peg$c9; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c11(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetablearray() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + var key = peg$currPos * 49 + 5, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s2 = peg$c7; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parsetable_key(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s6 = peg$c9; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s7 = peg$c9; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s7 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c12(s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetable_key() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 6, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsedot_ended_table_key_part(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsedot_ended_table_key_part(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + s2 = peg$parsetable_key_part(); + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c13(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsetable_key_part(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c14(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetable_key_part() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 7, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsequoted_key(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedot_ended_table_key_part() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 8, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsequoted_key(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseassignment() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 9, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsekey(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c18; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parsevalue(); + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c20(s1, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsequoted_key(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c18; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parsevalue(); + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c20(s1, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsekey() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 10, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseASCII_BASIC(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseASCII_BASIC(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c21(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsequoted_key() { + var s0, s1; + + var key = peg$currPos * 49 + 11, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsedouble_quoted_single_line_string(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c22(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsesingle_quoted_single_line_string(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c22(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsevalue() { + var s0; + + var key = peg$currPos * 49 + 12, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsestring(); + if (s0 === peg$FAILED) { + s0 = peg$parsedatetime(); + if (s0 === peg$FAILED) { + s0 = peg$parsefloat(); + if (s0 === peg$FAILED) { + s0 = peg$parseinteger(); + if (s0 === peg$FAILED) { + s0 = peg$parseboolean(); + if (s0 === peg$FAILED) { + s0 = peg$parsearray(); + if (s0 === peg$FAILED) { + s0 = peg$parseinline_table(); + } + } + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsestring() { + var s0; + + var key = peg$currPos * 49 + 13, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsedouble_quoted_multiline_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsedouble_quoted_single_line_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsesingle_quoted_multiline_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsesingle_quoted_single_line_string(); + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedouble_quoted_multiline_string() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 14, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c23) { + s1 = peg$c23; + peg$currPos += 3; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsemultiline_string_char(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsemultiline_string_char(); + } + if (s3 !== peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c23) { + s4 = peg$c23; + peg$currPos += 3; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedouble_quoted_single_line_string() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 15, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c27; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsestring_char(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsestring_char(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c27; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesingle_quoted_multiline_string() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 16, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c29) { + s1 = peg$c29; + peg$currPos += 3; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsemultiline_literal_char(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsemultiline_literal_char(); + } + if (s3 !== peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c29) { + s4 = peg$c29; + peg$currPos += 3; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesingle_quoted_single_line_string() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 17, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseliteral_char(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseliteral_char(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c31; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsestring_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 18, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseESCAPED(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 34) { + s2 = peg$c27; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseliteral_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 19, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c31; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_string_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 20, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseESCAPED(); + if (s0 === peg$FAILED) { + s0 = peg$parsemultiline_string_delim(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c23) { + s2 = peg$c23; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c34(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_string_delim() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 21, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c35; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c36); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseNLS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseNLS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c37(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_literal_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 22, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c29) { + s2 = peg$c29; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefloat() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 23, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsefloat_text(); + if (s1 === peg$FAILED) { + s1 = peg$parseinteger_text(); + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 101) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 69) { + s2 = peg$c40; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c41); } + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseinteger_text(); + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c42(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsefloat_text(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c43(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefloat_text() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 24, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c44; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + if (s1 === peg$FAILED) { + s1 = peg$c25; + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseDIGITS(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGITS(); + if (s5 !== peg$FAILED) { + s3 = [s3, s4, s5]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c46(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 45) { + s1 = peg$c47; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseDIGITS(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGITS(); + if (s5 !== peg$FAILED) { + s3 = [s3, s4, s5]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c49(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinteger() { + var s0, s1; + + var key = peg$currPos * 49 + 25, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseinteger_text(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c50(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinteger_text() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 26, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c44; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + if (s1 === peg$FAILED) { + s1 = peg$c25; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + peg$silentFails--; + if (s4 === peg$FAILED) { + s3 = peg$c5; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c46(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 45) { + s1 = peg$c47; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + peg$silentFails--; + if (s4 === peg$FAILED) { + s3 = peg$c5; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c49(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseboolean() { + var s0, s1; + + var key = peg$currPos * 49 + 27, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c51) { + s1 = peg$c51; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c52); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c53(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c54) { + s1 = peg$c54; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c55); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c56(); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 28, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_sep(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_sep(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c57(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsearray_value(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c58(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_value_list(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_value_list(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c59(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_value_list(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_value_list(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$parsearray_value(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s4 = peg$c9; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c60(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_value() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 29, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsearray_sep(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsearray_sep(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsevalue(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsearray_sep(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsearray_sep(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c61(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_value_list() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 30, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsearray_sep(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsearray_sep(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsevalue(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsearray_sep(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsearray_sep(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s4 = peg$c62; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c63); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parsearray_sep(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parsearray_sep(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c61(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_sep() { + var s0; + + var key = peg$currPos * 49 + 31, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseS(); + if (s0 === peg$FAILED) { + s0 = peg$parseNL(); + if (s0 === peg$FAILED) { + s0 = peg$parsecomment(); + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinline_table() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 32, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 123) { + s1 = peg$c64; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c65); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseinline_table_assignment(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseinline_table_assignment(); + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s5 = peg$c66; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c67); } + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c68(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinline_table_assignment() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 33, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s4 = peg$c18; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parsevalue(); + if (s6 !== peg$FAILED) { + s7 = []; + s8 = peg$parseS(); + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseS(); + } + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c62; + peg$currPos++; + } else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c63); } + } + if (s8 !== peg$FAILED) { + s9 = []; + s10 = peg$parseS(); + while (s10 !== peg$FAILED) { + s9.push(s10); + s10 = peg$parseS(); + } + if (s9 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c69(s2, s6); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s4 = peg$c18; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parsevalue(); + if (s6 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c69(s2, s6); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesecfragment() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 34, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c16; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDIGITS(); + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c70(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedate() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11; + + var key = peg$currPos * 49 + 35, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT_OR_UNDER(); + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s6 = peg$c47; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseDIGIT_OR_UNDER(); + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s9 = peg$c47; + peg$currPos++; + } else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s9 !== peg$FAILED) { + s10 = peg$parseDIGIT_OR_UNDER(); + if (s10 !== peg$FAILED) { + s11 = peg$parseDIGIT_OR_UNDER(); + if (s11 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c71(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetime() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 36, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c72; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT_OR_UNDER(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c72; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + s9 = peg$parseDIGIT_OR_UNDER(); + if (s9 !== peg$FAILED) { + s10 = peg$parsesecfragment(); + if (s10 === peg$FAILED) { + s10 = peg$c25; + } + if (s10 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c74(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetime_with_offset() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16; + + var key = peg$currPos * 49 + 37, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c72; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT_OR_UNDER(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c72; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + s9 = peg$parseDIGIT_OR_UNDER(); + if (s9 !== peg$FAILED) { + s10 = peg$parsesecfragment(); + if (s10 === peg$FAILED) { + s10 = peg$c25; + } + if (s10 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s11 = peg$c47; + peg$currPos++; + } else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s11 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s11 = peg$c44; + peg$currPos++; + } else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + } + if (s11 !== peg$FAILED) { + s12 = peg$parseDIGIT_OR_UNDER(); + if (s12 !== peg$FAILED) { + s13 = peg$parseDIGIT_OR_UNDER(); + if (s13 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s14 = peg$c72; + peg$currPos++; + } else { + s14 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s14 !== peg$FAILED) { + s15 = peg$parseDIGIT_OR_UNDER(); + if (s15 !== peg$FAILED) { + s16 = peg$parseDIGIT_OR_UNDER(); + if (s16 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c74(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedatetime() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 38, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsedate(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 84) { + s2 = peg$c75; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c76); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetime(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 90) { + s4 = peg$c77; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c78); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c79(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsedate(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 84) { + s2 = peg$c75; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c76); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetime_with_offset(); + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c80(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseS() { + var s0; + + var key = peg$currPos * 49 + 39, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c81.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c82); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseNL() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 40, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (input.charCodeAt(peg$currPos) === 10) { + s0 = peg$c83; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c84); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 13) { + s1 = peg$c85; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c86); } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 10) { + s2 = peg$c83; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c84); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseNLS() { + var s0; + + var key = peg$currPos * 49 + 41, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseNL(); + if (s0 === peg$FAILED) { + s0 = peg$parseS(); + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseEOF() { + var s0, s1; + + var key = peg$currPos * 49 + 42, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + peg$silentFails++; + if (input.length > peg$currPos) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + peg$silentFails--; + if (s1 === peg$FAILED) { + s0 = peg$c5; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseHEX() { + var s0; + + var key = peg$currPos * 49 + 43, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c87.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c88); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseDIGIT_OR_UNDER() { + var s0, s1; + + var key = peg$currPos * 49 + 44, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c89.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c90); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s1 = peg$c91; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c92); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c93(); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseASCII_BASIC() { + var s0; + + var key = peg$currPos * 49 + 45, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c94.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c95); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseDIGITS() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 46, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c96(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseESCAPED() { + var s0, s1; + + var key = peg$currPos * 49 + 47, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c97) { + s1 = peg$c97; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c98); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c99(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c100) { + s1 = peg$c100; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c102(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c103) { + s1 = peg$c103; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c104); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c105(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c106) { + s1 = peg$c106; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c107); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c108(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c109) { + s1 = peg$c109; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c110); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c111(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c112) { + s1 = peg$c112; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c113); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c114(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c115) { + s1 = peg$c115; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c116); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c117(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$parseESCAPED_UNICODE(); + } + } + } + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseESCAPED_UNICODE() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 48, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c118) { + s1 = peg$c118; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c119); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseHEX(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEX(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHEX(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHEX(); + if (s6 !== peg$FAILED) { + s7 = peg$parseHEX(); + if (s7 !== peg$FAILED) { + s8 = peg$parseHEX(); + if (s8 !== peg$FAILED) { + s9 = peg$parseHEX(); + if (s9 !== peg$FAILED) { + s10 = peg$parseHEX(); + if (s10 !== peg$FAILED) { + s3 = [s3, s4, s5, s6, s7, s8, s9, s10]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c120(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c121) { + s1 = peg$c121; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c122); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseHEX(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEX(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHEX(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHEX(); + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c120(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + + var nodes = []; + + function genError(err, line, col) { + var ex = new Error(err); + ex.line = line; + ex.column = col; + throw ex; + } + + function addNode(node) { + nodes.push(node); + } + + function node(type, value, line, column, key) { + var obj = { type: type, value: value, line: line(), column: column() }; + if (key) obj.key = key; + return obj; + } + + function convertCodePoint(str, line, col) { + var num = parseInt("0x" + str); + + if ( + !isFinite(num) || + Math.floor(num) != num || + num < 0 || + num > 0x10FFFF || + (num > 0xD7FF && num < 0xE000) + ) { + genError("Invalid Unicode escape code: " + str, line, col); + } else { + return fromCodePoint(num); + } + } + + function fromCodePoint() { + var MAX_SIZE = 0x4000; + var codeUnits = []; + var highSurrogate; + var lowSurrogate; + var index = -1; + var length = arguments.length; + if (!length) { + return ''; + } + var result = ''; + while (++index < length) { + var codePoint = Number(arguments[index]); + if (codePoint <= 0xFFFF) { // BMP code point + codeUnits.push(codePoint); + } else { // Astral code point; split in surrogate halves + // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + codePoint -= 0x10000; + highSurrogate = (codePoint >> 10) + 0xD800; + lowSurrogate = (codePoint % 0x400) + 0xDC00; + codeUnits.push(highSurrogate, lowSurrogate); + } + if (index + 1 == length || codeUnits.length > MAX_SIZE) { + result += String.fromCharCode.apply(null, codeUnits); + codeUnits.length = 0; + } + } + return result; + } + + + peg$result = peg$startRuleFunction(); + + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail({ type: "end", description: "end of input" }); + } + + throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos); + } + } + + return { + SyntaxError: SyntaxError, + parse: parse + }; +})(); + + +/***/ }), + +/***/ 1430: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * IPv6 Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (root) { + 'use strict'; + + /* + var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156"; + var _out = IPv6.best(_in); + var _expected = "fe80::204:61ff:fe9d:f156"; + + console.log(_in, _out, _expected, _out === _expected); + */ + + // save current IPv6 variable, if any + var _IPv6 = root && root.IPv6; + + function bestPresentation(address) { + // based on: + // Javascript to test an IPv6 address for proper format, and to + // present the "best text representation" according to IETF Draft RFC at + // http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04 + // 8 Feb 2010 Rich Brown, Dartware, LLC + // Please feel free to use this code as long as you provide a link to + // http://www.intermapper.com + // http://intermapper.com/support/tools/IPV6-Validator.aspx + // http://download.dartware.com/thirdparty/ipv6validator.js + + var _address = address.toLowerCase(); + var segments = _address.split(':'); + var length = segments.length; + var total = 8; + + // trim colons (:: or ::a:b:c… or …a:b:c::) + if (segments[0] === '' && segments[1] === '' && segments[2] === '') { + // must have been :: + // remove first two items + segments.shift(); + segments.shift(); + } else if (segments[0] === '' && segments[1] === '') { + // must have been ::xxxx + // remove the first item + segments.shift(); + } else if (segments[length - 1] === '' && segments[length - 2] === '') { + // must have been xxxx:: + segments.pop(); + } + + length = segments.length; + + // adjust total segments for IPv4 trailer + if (segments[length - 1].indexOf('.') !== -1) { + // found a "." which means IPv4 + total = 7; + } + + // fill empty segments them with "0000" + var pos; + for (pos = 0; pos < length; pos++) { + if (segments[pos] === '') { + break; + } + } + + if (pos < total) { + segments.splice(pos, 1, '0000'); + while (segments.length < total) { + segments.splice(pos, 0, '0000'); + } + } + + // strip leading zeros + var _segments; + for (var i = 0; i < total; i++) { + _segments = segments[i].split(''); + for (var j = 0; j < 3 ; j++) { + if (_segments[0] === '0' && _segments.length > 1) { + _segments.splice(0,1); + } else { + break; + } + } + + segments[i] = _segments.join(''); + } + + // find longest sequence of zeroes and coalesce them into one segment + var best = -1; + var _best = 0; + var _current = 0; + var current = -1; + var inzeroes = false; + // i; already declared + + for (i = 0; i < total; i++) { + if (inzeroes) { + if (segments[i] === '0') { + _current += 1; + } else { + inzeroes = false; + if (_current > _best) { + best = current; + _best = _current; + } + } + } else { + if (segments[i] === '0') { + inzeroes = true; + current = i; + _current = 1; + } + } + } + + if (_current > _best) { + best = current; + _best = _current; + } + + if (_best > 1) { + segments.splice(best, _best, ''); + } + + length = segments.length; + + // assemble remaining segments + var result = ''; + if (segments[0] === '') { + result = ':'; + } + + for (i = 0; i < length; i++) { + result += segments[i]; + if (i === length - 1) { + break; + } + + result += ':'; + } + + if (segments[length - 1] === '') { + result += ':'; + } + + return result; + } + + function noConflict() { + /*jshint validthis: true */ + if (root.IPv6 === this) { + root.IPv6 = _IPv6; + } + + return this; + } + + return { + best: bestPresentation, + noConflict: noConflict + }; +})); + + +/***/ }), + +/***/ 4704: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * Second Level Domain (SLD) Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (root) { + 'use strict'; + + // save current SecondLevelDomains variable, if any + var _SecondLevelDomains = root && root.SecondLevelDomains; + + var SLD = { + // list of known Second Level Domains + // converted list of SLDs from https://github.com/gavingmiller/second-level-domains + // ---- + // publicsuffix.org is more current and actually used by a couple of browsers internally. + // downside is it also contains domains like "dyndns.org" - which is fine for the security + // issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js + // ---- + list: { + 'ac':' com gov mil net org ', + 'ae':' ac co gov mil name net org pro sch ', + 'af':' com edu gov net org ', + 'al':' com edu gov mil net org ', + 'ao':' co ed gv it og pb ', + 'ar':' com edu gob gov int mil net org tur ', + 'at':' ac co gv or ', + 'au':' asn com csiro edu gov id net org ', + 'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ', + 'bb':' biz co com edu gov info net org store tv ', + 'bh':' biz cc com edu gov info net org ', + 'bn':' com edu gov net org ', + 'bo':' com edu gob gov int mil net org tv ', + 'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ', + 'bs':' com edu gov net org ', + 'bz':' du et om ov rg ', + 'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ', + 'ck':' biz co edu gen gov info net org ', + 'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ', + 'co':' com edu gov mil net nom org ', + 'cr':' ac c co ed fi go or sa ', + 'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ', + 'do':' art com edu gob gov mil net org sld web ', + 'dz':' art asso com edu gov net org pol ', + 'ec':' com edu fin gov info med mil net org pro ', + 'eg':' com edu eun gov mil name net org sci ', + 'er':' com edu gov ind mil net org rochest w ', + 'es':' com edu gob nom org ', + 'et':' biz com edu gov info name net org ', + 'fj':' ac biz com info mil name net org pro ', + 'fk':' ac co gov net nom org ', + 'fr':' asso com f gouv nom prd presse tm ', + 'gg':' co net org ', + 'gh':' com edu gov mil org ', + 'gn':' ac com gov net org ', + 'gr':' com edu gov mil net org ', + 'gt':' com edu gob ind mil net org ', + 'gu':' com edu gov net org ', + 'hk':' com edu gov idv net org ', + 'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ', + 'id':' ac co go mil net or sch web ', + 'il':' ac co gov idf k12 muni net org ', + 'in':' ac co edu ernet firm gen gov i ind mil net nic org res ', + 'iq':' com edu gov i mil net org ', + 'ir':' ac co dnssec gov i id net org sch ', + 'it':' edu gov ', + 'je':' co net org ', + 'jo':' com edu gov mil name net org sch ', + 'jp':' ac ad co ed go gr lg ne or ', + 'ke':' ac co go info me mobi ne or sc ', + 'kh':' com edu gov mil net org per ', + 'ki':' biz com de edu gov info mob net org tel ', + 'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ', + 'kn':' edu gov net org ', + 'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ', + 'kw':' com edu gov net org ', + 'ky':' com edu gov net org ', + 'kz':' com edu gov mil net org ', + 'lb':' com edu gov net org ', + 'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ', + 'lr':' com edu gov net org ', + 'lv':' asn com conf edu gov id mil net org ', + 'ly':' com edu gov id med net org plc sch ', + 'ma':' ac co gov m net org press ', + 'mc':' asso tm ', + 'me':' ac co edu gov its net org priv ', + 'mg':' com edu gov mil nom org prd tm ', + 'mk':' com edu gov inf name net org pro ', + 'ml':' com edu gov net org presse ', + 'mn':' edu gov org ', + 'mo':' com edu gov net org ', + 'mt':' com edu gov net org ', + 'mv':' aero biz com coop edu gov info int mil museum name net org pro ', + 'mw':' ac co com coop edu gov int museum net org ', + 'mx':' com edu gob net org ', + 'my':' com edu gov mil name net org sch ', + 'nf':' arts com firm info net other per rec store web ', + 'ng':' biz com edu gov mil mobi name net org sch ', + 'ni':' ac co com edu gob mil net nom org ', + 'np':' com edu gov mil net org ', + 'nr':' biz com edu gov info net org ', + 'om':' ac biz co com edu gov med mil museum net org pro sch ', + 'pe':' com edu gob mil net nom org sld ', + 'ph':' com edu gov i mil net ngo org ', + 'pk':' biz com edu fam gob gok gon gop gos gov net org web ', + 'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ', + 'pr':' ac biz com edu est gov info isla name net org pro prof ', + 'ps':' com edu gov net org plo sec ', + 'pw':' belau co ed go ne or ', + 'ro':' arts com firm info nom nt org rec store tm www ', + 'rs':' ac co edu gov in org ', + 'sb':' com edu gov net org ', + 'sc':' com edu gov net org ', + 'sh':' co com edu gov net nom org ', + 'sl':' com edu gov net org ', + 'st':' co com consulado edu embaixada gov mil net org principe saotome store ', + 'sv':' com edu gob org red ', + 'sz':' ac co org ', + 'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ', + 'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ', + 'tw':' club com ebiz edu game gov idv mil net org ', + 'mu':' ac co com gov net or org ', + 'mz':' ac co edu gov org ', + 'na':' co com ', + 'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ', + 'pa':' abo ac com edu gob ing med net nom org sld ', + 'pt':' com edu gov int net nome org publ ', + 'py':' com edu gov mil net org ', + 'qa':' com edu gov mil net org ', + 're':' asso com nom ', + 'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ', + 'rw':' ac co com edu gouv gov int mil net ', + 'sa':' com edu gov med net org pub sch ', + 'sd':' com edu gov info med net org tv ', + 'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ', + 'sg':' com edu gov idn net org per ', + 'sn':' art com edu gouv org perso univ ', + 'sy':' com edu gov mil net news org ', + 'th':' ac co go in mi net or ', + 'tj':' ac biz co com edu go gov info int mil name net nic org test web ', + 'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ', + 'tz':' ac co go ne or ', + 'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ', + 'ug':' ac co go ne or org sc ', + 'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ', + 'us':' dni fed isa kids nsn ', + 'uy':' com edu gub mil net org ', + 've':' co com edu gob info mil net org web ', + 'vi':' co com k12 net org ', + 'vn':' ac biz com edu gov health info int name net org pro ', + 'ye':' co com gov ltd me net org plc ', + 'yu':' ac co edu gov org ', + 'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ', + 'zm':' ac co com edu gov net org sch ', + // https://en.wikipedia.org/wiki/CentralNic#Second-level_domains + 'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ', + 'net': 'gb jp se uk ', + 'org': 'ae', + 'de': 'com ' + }, + // gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost + // in both performance and memory footprint. No initialization required. + // http://jsperf.com/uri-js-sld-regex-vs-binary-search/4 + // Following methods use lastIndexOf() rather than array.split() in order + // to avoid any memory allocations. + has: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return false; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) { + return false; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return false; + } + return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0; + }, + is: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return false; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset >= 0) { + return false; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return false; + } + return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0; + }, + get: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return null; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) { + return null; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return null; + } + if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) { + return null; + } + return domain.slice(sldOffset+1); + }, + noConflict: function(){ + if (root.SecondLevelDomains === this) { + root.SecondLevelDomains = _SecondLevelDomains; + } + return this; + } + }; + + return SLD; +})); + + +/***/ }), + +/***/ 4193: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(__webpack_require__(9340), __webpack_require__(1430), __webpack_require__(4704)); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(9340), __webpack_require__(1430), __webpack_require__(4704)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (punycode, IPv6, SLD, root) { + 'use strict'; + /*global location, escape, unescape */ + // FIXME: v2.0.0 renamce non-camelCase properties to uppercase + /*jshint camelcase: false */ + + // save current URI variable, if any + var _URI = root && root.URI; + + function URI(url, base) { + var _urlSupplied = arguments.length >= 1; + var _baseSupplied = arguments.length >= 2; + + // Allow instantiation without the 'new' keyword + if (!(this instanceof URI)) { + if (_urlSupplied) { + if (_baseSupplied) { + return new URI(url, base); + } + + return new URI(url); + } + + return new URI(); + } + + if (url === undefined) { + if (_urlSupplied) { + throw new TypeError('undefined is not a valid argument for URI'); + } + + if (typeof location !== 'undefined') { + url = location.href + ''; + } else { + url = ''; + } + } + + if (url === null) { + if (_urlSupplied) { + throw new TypeError('null is not a valid argument for URI'); + } + } + + this.href(url); + + // resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor + if (base !== undefined) { + return this.absoluteTo(base); + } + + return this; + } + + function isInteger(value) { + return /^[0-9]+$/.test(value); + } + + URI.version = '1.19.11'; + + var p = URI.prototype; + var hasOwn = Object.prototype.hasOwnProperty; + + function escapeRegEx(string) { + // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963 + return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); + } + + function getType(value) { + // IE8 doesn't return [Object Undefined] but [Object Object] for undefined value + if (value === undefined) { + return 'Undefined'; + } + + return String(Object.prototype.toString.call(value)).slice(8, -1); + } + + function isArray(obj) { + return getType(obj) === 'Array'; + } + + function filterArrayValues(data, value) { + var lookup = {}; + var i, length; + + if (getType(value) === 'RegExp') { + lookup = null; + } else if (isArray(value)) { + for (i = 0, length = value.length; i < length; i++) { + lookup[value[i]] = true; + } + } else { + lookup[value] = true; + } + + for (i = 0, length = data.length; i < length; i++) { + /*jshint laxbreak: true */ + var _match = lookup && lookup[data[i]] !== undefined + || !lookup && value.test(data[i]); + /*jshint laxbreak: false */ + if (_match) { + data.splice(i, 1); + length--; + i--; + } + } + + return data; + } + + function arrayContains(list, value) { + var i, length; + + // value may be string, number, array, regexp + if (isArray(value)) { + // Note: this can be optimized to O(n) (instead of current O(m * n)) + for (i = 0, length = value.length; i < length; i++) { + if (!arrayContains(list, value[i])) { + return false; + } + } + + return true; + } + + var _type = getType(value); + for (i = 0, length = list.length; i < length; i++) { + if (_type === 'RegExp') { + if (typeof list[i] === 'string' && list[i].match(value)) { + return true; + } + } else if (list[i] === value) { + return true; + } + } + + return false; + } + + function arraysEqual(one, two) { + if (!isArray(one) || !isArray(two)) { + return false; + } + + // arrays can't be equal if they have different amount of content + if (one.length !== two.length) { + return false; + } + + one.sort(); + two.sort(); + + for (var i = 0, l = one.length; i < l; i++) { + if (one[i] !== two[i]) { + return false; + } + } + + return true; + } + + function trimSlashes(text) { + var trim_expression = /^\/+|\/+$/g; + return text.replace(trim_expression, ''); + } + + URI._parts = function() { + return { + protocol: null, + username: null, + password: null, + hostname: null, + urn: null, + port: null, + path: null, + query: null, + fragment: null, + // state + preventInvalidHostname: URI.preventInvalidHostname, + duplicateQueryParameters: URI.duplicateQueryParameters, + escapeQuerySpace: URI.escapeQuerySpace + }; + }; + // state: throw on invalid hostname + // see https://github.com/medialize/URI.js/pull/345 + // and https://github.com/medialize/URI.js/issues/354 + URI.preventInvalidHostname = false; + // state: allow duplicate query parameters (a=1&a=1) + URI.duplicateQueryParameters = false; + // state: replaces + with %20 (space in query strings) + URI.escapeQuerySpace = true; + // static properties + URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i; + URI.idn_expression = /[^a-z0-9\._-]/i; + URI.punycode_expression = /(xn--)/i; + // well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care? + URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; + // credits to Rich Brown + // source: http://forums.intermapper.com/viewtopic.php?p=1096#1096 + // specification: http://www.ietf.org/rfc/rfc4291.txt + URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/; + // expression used is "gruber revised" (@gruber v2) determined to be the + // best solution in a regex-golf we did a couple of ages ago at + // * http://mathiasbynens.be/demo/url-regex + // * http://rodneyrehm.de/t/url-regex.html + URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig; + URI.findUri = { + // valid "scheme://" or "www." + start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi, + // everything up to the next whitespace + end: /[\s\r\n]|$/, + // trim trailing punctuation captured by end RegExp + trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/, + // balanced parens inclusion (), [], {}, <> + parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g, + }; + URI.leading_whitespace_expression = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/ + // https://infra.spec.whatwg.org/#ascii-tab-or-newline + URI.ascii_tab_whitespace = /[\u0009\u000A\u000D]+/g + // http://www.iana.org/assignments/uri-schemes.html + // http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports + URI.defaultPorts = { + http: '80', + https: '443', + ftp: '21', + gopher: '70', + ws: '80', + wss: '443' + }; + // list of protocols which always require a hostname + URI.hostProtocols = [ + 'http', + 'https' + ]; + + // allowed hostname characters according to RFC 3986 + // ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded + // I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _ + URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/; + // map DOM Elements to their URI attribute + URI.domAttributes = { + 'a': 'href', + 'blockquote': 'cite', + 'link': 'href', + 'base': 'href', + 'script': 'src', + 'form': 'action', + 'img': 'src', + 'area': 'href', + 'iframe': 'src', + 'embed': 'src', + 'source': 'src', + 'track': 'src', + 'input': 'src', // but only if type="image" + 'audio': 'src', + 'video': 'src' + }; + URI.getDomAttribute = function(node) { + if (!node || !node.nodeName) { + return undefined; + } + + var nodeName = node.nodeName.toLowerCase(); + // should only expose src for type="image" + if (nodeName === 'input' && node.type !== 'image') { + return undefined; + } + + return URI.domAttributes[nodeName]; + }; + + function escapeForDumbFirefox36(value) { + // https://github.com/medialize/URI.js/issues/91 + return escape(value); + } + + // encoding / decoding according to RFC3986 + function strictEncodeURIComponent(string) { + // see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent + return encodeURIComponent(string) + .replace(/[!'()*]/g, escapeForDumbFirefox36) + .replace(/\*/g, '%2A'); + } + URI.encode = strictEncodeURIComponent; + URI.decode = decodeURIComponent; + URI.iso8859 = function() { + URI.encode = escape; + URI.decode = unescape; + }; + URI.unicode = function() { + URI.encode = strictEncodeURIComponent; + URI.decode = decodeURIComponent; + }; + URI.characters = { + pathname: { + encode: { + // RFC3986 2.1: For consistency, URI producers and normalizers should + // use uppercase hexadecimal digits for all percent-encodings. + expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig, + map: { + // -._~!'()* + '%24': '$', + '%26': '&', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=', + '%3A': ':', + '%40': '@' + } + }, + decode: { + expression: /[\/\?#]/g, + map: { + '/': '%2F', + '?': '%3F', + '#': '%23' + } + } + }, + reserved: { + encode: { + // RFC3986 2.1: For consistency, URI producers and normalizers should + // use uppercase hexadecimal digits for all percent-encodings. + expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig, + map: { + // gen-delims + '%3A': ':', + '%2F': '/', + '%3F': '?', + '%23': '#', + '%5B': '[', + '%5D': ']', + '%40': '@', + // sub-delims + '%21': '!', + '%24': '$', + '%26': '&', + '%27': '\'', + '%28': '(', + '%29': ')', + '%2A': '*', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=' + } + } + }, + urnpath: { + // The characters under `encode` are the characters called out by RFC 2141 as being acceptable + // for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but + // these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also + // note that the colon character is not featured in the encoding map; this is because URI.js + // gives the colons in URNs semantic meaning as the delimiters of path segements, and so it + // should not appear unencoded in a segment itself. + // See also the note above about RFC3986 and capitalalized hex digits. + encode: { + expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig, + map: { + '%21': '!', + '%24': '$', + '%27': '\'', + '%28': '(', + '%29': ')', + '%2A': '*', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=', + '%40': '@' + } + }, + // These characters are the characters called out by RFC2141 as "reserved" characters that + // should never appear in a URN, plus the colon character (see note above). + decode: { + expression: /[\/\?#:]/g, + map: { + '/': '%2F', + '?': '%3F', + '#': '%23', + ':': '%3A' + } + } + } + }; + URI.encodeQuery = function(string, escapeQuerySpace) { + var escaped = URI.encode(string + ''); + if (escapeQuerySpace === undefined) { + escapeQuerySpace = URI.escapeQuerySpace; + } + + return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped; + }; + URI.decodeQuery = function(string, escapeQuerySpace) { + string += ''; + if (escapeQuerySpace === undefined) { + escapeQuerySpace = URI.escapeQuerySpace; + } + + try { + return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string); + } catch(e) { + // we're not going to mess with weird encodings, + // give up and return the undecoded original string + // see https://github.com/medialize/URI.js/issues/87 + // see https://github.com/medialize/URI.js/issues/92 + return string; + } + }; + // generate encode/decode path functions + var _parts = {'encode':'encode', 'decode':'decode'}; + var _part; + var generateAccessor = function(_group, _part) { + return function(string) { + try { + return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) { + return URI.characters[_group][_part].map[c]; + }); + } catch (e) { + // we're not going to mess with weird encodings, + // give up and return the undecoded original string + // see https://github.com/medialize/URI.js/issues/87 + // see https://github.com/medialize/URI.js/issues/92 + return string; + } + }; + }; + + for (_part in _parts) { + URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]); + URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]); + } + + var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) { + return function(string) { + // Why pass in names of functions, rather than the function objects themselves? The + // definitions of some functions (but in particular, URI.decode) will occasionally change due + // to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure + // that the functions we use here are "fresh". + var actualCodingFunc; + if (!_innerCodingFuncName) { + actualCodingFunc = URI[_codingFuncName]; + } else { + actualCodingFunc = function(string) { + return URI[_codingFuncName](URI[_innerCodingFuncName](string)); + }; + } + + var segments = (string + '').split(_sep); + + for (var i = 0, length = segments.length; i < length; i++) { + segments[i] = actualCodingFunc(segments[i]); + } + + return segments.join(_sep); + }; + }; + + // This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions. + URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment'); + URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment'); + URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode'); + URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode'); + + URI.encodeReserved = generateAccessor('reserved', 'encode'); + + URI.parse = function(string, parts) { + var pos; + if (!parts) { + parts = { + preventInvalidHostname: URI.preventInvalidHostname + }; + } + + string = string.replace(URI.leading_whitespace_expression, '') + // https://infra.spec.whatwg.org/#ascii-tab-or-newline + string = string.replace(URI.ascii_tab_whitespace, '') + + // [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment] + + // extract fragment + pos = string.indexOf('#'); + if (pos > -1) { + // escaping? + parts.fragment = string.substring(pos + 1) || null; + string = string.substring(0, pos); + } + + // extract query + pos = string.indexOf('?'); + if (pos > -1) { + // escaping? + parts.query = string.substring(pos + 1) || null; + string = string.substring(0, pos); + } + + // slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws) + string = string.replace(/^(https?|ftp|wss?)?:+[/\\]*/i, '$1://'); + // slashes and backslashes have lost all meaning for scheme relative URLs + string = string.replace(/^[/\\]{2,}/i, '//'); + + // extract protocol + if (string.substring(0, 2) === '//') { + // relative-scheme + parts.protocol = null; + string = string.substring(2); + // extract "user:pass@host:port" + string = URI.parseAuthority(string, parts); + } else { + pos = string.indexOf(':'); + if (pos > -1) { + parts.protocol = string.substring(0, pos) || null; + if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) { + // : may be within the path + parts.protocol = undefined; + } else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') { + string = string.substring(pos + 3); + + // extract "user:pass@host:port" + string = URI.parseAuthority(string, parts); + } else { + string = string.substring(pos + 1); + parts.urn = true; + } + } + } + + // what's left must be the path + parts.path = string; + + // and we're done + return parts; + }; + URI.parseHost = function(string, parts) { + if (!string) { + string = ''; + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124 + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + // https://github.com/medialize/URI.js/pull/233 + string = string.replace(/\\/g, '/'); + + // extract host:port + var pos = string.indexOf('/'); + var bracketPos; + var t; + + if (pos === -1) { + pos = string.length; + } + + if (string.charAt(0) === '[') { + // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6 + // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts + // IPv6+port in the format [2001:db8::1]:80 (for the time being) + bracketPos = string.indexOf(']'); + parts.hostname = string.substring(1, bracketPos) || null; + parts.port = string.substring(bracketPos + 2, pos) || null; + if (parts.port === '/') { + parts.port = null; + } + } else { + var firstColon = string.indexOf(':'); + var firstSlash = string.indexOf('/'); + var nextColon = string.indexOf(':', firstColon + 1); + if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) { + // IPv6 host contains multiple colons - but no port + // this notation is actually not allowed by RFC 3986, but we're a liberal parser + parts.hostname = string.substring(0, pos) || null; + parts.port = null; + } else { + t = string.substring(0, pos).split(':'); + parts.hostname = t[0] || null; + parts.port = t[1] || null; + } + } + + if (parts.hostname && string.substring(pos).charAt(0) !== '/') { + pos++; + string = '/' + string; + } + + if (parts.preventInvalidHostname) { + URI.ensureValidHostname(parts.hostname, parts.protocol); + } + + if (parts.port) { + URI.ensureValidPort(parts.port); + } + + return string.substring(pos) || '/'; + }; + URI.parseAuthority = function(string, parts) { + string = URI.parseUserinfo(string, parts); + return URI.parseHost(string, parts); + }; + URI.parseUserinfo = function(string, parts) { + // extract username:password + var _string = string + var firstBackSlash = string.indexOf('\\'); + if (firstBackSlash !== -1) { + string = string.replace(/\\/g, '/') + } + var firstSlash = string.indexOf('/'); + var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1); + var t; + + // authority@ must come before /path or \path + if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) { + t = string.substring(0, pos).split(':'); + parts.username = t[0] ? URI.decode(t[0]) : null; + t.shift(); + parts.password = t[0] ? URI.decode(t.join(':')) : null; + string = _string.substring(pos + 1); + } else { + parts.username = null; + parts.password = null; + } + + return string; + }; + URI.parseQuery = function(string, escapeQuerySpace) { + if (!string) { + return {}; + } + + // throw out the funky business - "?"[name"="value"&"]+ + string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, ''); + + if (!string) { + return {}; + } + + var items = {}; + var splits = string.split('&'); + var length = splits.length; + var v, name, value; + + for (var i = 0; i < length; i++) { + v = splits[i].split('='); + name = URI.decodeQuery(v.shift(), escapeQuerySpace); + // no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters + value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null; + + if (name === '__proto__') { + // ignore attempt at exploiting JavaScript internals + continue; + } else if (hasOwn.call(items, name)) { + if (typeof items[name] === 'string' || items[name] === null) { + items[name] = [items[name]]; + } + + items[name].push(value); + } else { + items[name] = value; + } + } + + return items; + }; + + URI.build = function(parts) { + var t = ''; + var requireAbsolutePath = false + + if (parts.protocol) { + t += parts.protocol + ':'; + } + + if (!parts.urn && (t || parts.hostname)) { + t += '//'; + requireAbsolutePath = true + } + + t += (URI.buildAuthority(parts) || ''); + + if (typeof parts.path === 'string') { + if (parts.path.charAt(0) !== '/' && requireAbsolutePath) { + t += '/'; + } + + t += parts.path; + } + + if (typeof parts.query === 'string' && parts.query) { + t += '?' + parts.query; + } + + if (typeof parts.fragment === 'string' && parts.fragment) { + t += '#' + parts.fragment; + } + return t; + }; + URI.buildHost = function(parts) { + var t = ''; + + if (!parts.hostname) { + return ''; + } else if (URI.ip6_expression.test(parts.hostname)) { + t += '[' + parts.hostname + ']'; + } else { + t += parts.hostname; + } + + if (parts.port) { + t += ':' + parts.port; + } + + return t; + }; + URI.buildAuthority = function(parts) { + return URI.buildUserinfo(parts) + URI.buildHost(parts); + }; + URI.buildUserinfo = function(parts) { + var t = ''; + + if (parts.username) { + t += URI.encode(parts.username); + } + + if (parts.password) { + t += ':' + URI.encode(parts.password); + } + + if (t) { + t += '@'; + } + + return t; + }; + URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) { + // according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html + // being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed + // the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax! + // URI.js treats the query string as being application/x-www-form-urlencoded + // see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type + + var t = ''; + var unique, key, i, length; + for (key in data) { + if (key === '__proto__') { + // ignore attempt at exploiting JavaScript internals + continue; + } else if (hasOwn.call(data, key)) { + if (isArray(data[key])) { + unique = {}; + for (i = 0, length = data[key].length; i < length; i++) { + if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) { + t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace); + if (duplicateQueryParameters !== true) { + unique[data[key][i] + ''] = true; + } + } + } + } else if (data[key] !== undefined) { + t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace); + } + } + } + + return t.substring(1); + }; + URI.buildQueryParameter = function(name, value, escapeQuerySpace) { + // http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded + // don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization + return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : ''); + }; + + URI.addQuery = function(data, name, value) { + if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + URI.addQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + if (data[name] === undefined) { + data[name] = value; + return; + } else if (typeof data[name] === 'string') { + data[name] = [data[name]]; + } + + if (!isArray(value)) { + value = [value]; + } + + data[name] = (data[name] || []).concat(value); + } else { + throw new TypeError('URI.addQuery() accepts an object, string as the name parameter'); + } + }; + + URI.setQuery = function(data, name, value) { + if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + URI.setQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + data[name] = value === undefined ? null : value; + } else { + throw new TypeError('URI.setQuery() accepts an object, string as the name parameter'); + } + }; + + URI.removeQuery = function(data, name, value) { + var i, length, key; + + if (isArray(name)) { + for (i = 0, length = name.length; i < length; i++) { + data[name[i]] = undefined; + } + } else if (getType(name) === 'RegExp') { + for (key in data) { + if (name.test(key)) { + data[key] = undefined; + } + } + } else if (typeof name === 'object') { + for (key in name) { + if (hasOwn.call(name, key)) { + URI.removeQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + if (value !== undefined) { + if (getType(value) === 'RegExp') { + if (!isArray(data[name]) && value.test(data[name])) { + data[name] = undefined; + } else { + data[name] = filterArrayValues(data[name], value); + } + } else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) { + data[name] = undefined; + } else if (isArray(data[name])) { + data[name] = filterArrayValues(data[name], value); + } + } else { + data[name] = undefined; + } + } else { + throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter'); + } + }; + URI.hasQuery = function(data, name, value, withinArray) { + switch (getType(name)) { + case 'String': + // Nothing to do here + break; + + case 'RegExp': + for (var key in data) { + if (hasOwn.call(data, key)) { + if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) { + return true; + } + } + } + + return false; + + case 'Object': + for (var _key in name) { + if (hasOwn.call(name, _key)) { + if (!URI.hasQuery(data, _key, name[_key])) { + return false; + } + } + } + + return true; + + default: + throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter'); + } + + switch (getType(value)) { + case 'Undefined': + // true if exists (but may be empty) + return name in data; // data[name] !== undefined; + + case 'Boolean': + // true if exists and non-empty + var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]); + return value === _booly; + + case 'Function': + // allow complex comparison + return !!value(data[name], name, data); + + case 'Array': + if (!isArray(data[name])) { + return false; + } + + var op = withinArray ? arrayContains : arraysEqual; + return op(data[name], value); + + case 'RegExp': + if (!isArray(data[name])) { + return Boolean(data[name] && data[name].match(value)); + } + + if (!withinArray) { + return false; + } + + return arrayContains(data[name], value); + + case 'Number': + value = String(value); + /* falls through */ + case 'String': + if (!isArray(data[name])) { + return data[name] === value; + } + + if (!withinArray) { + return false; + } + + return arrayContains(data[name], value); + + default: + throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter'); + } + }; + + + URI.joinPaths = function() { + var input = []; + var segments = []; + var nonEmptySegments = 0; + + for (var i = 0; i < arguments.length; i++) { + var url = new URI(arguments[i]); + input.push(url); + var _segments = url.segment(); + for (var s = 0; s < _segments.length; s++) { + if (typeof _segments[s] === 'string') { + segments.push(_segments[s]); + } + + if (_segments[s]) { + nonEmptySegments++; + } + } + } + + if (!segments.length || !nonEmptySegments) { + return new URI(''); + } + + var uri = new URI('').segment(segments); + + if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') { + uri.path('/' + uri.path()); + } + + return uri.normalize(); + }; + + URI.commonPath = function(one, two) { + var length = Math.min(one.length, two.length); + var pos; + + // find first non-matching character + for (pos = 0; pos < length; pos++) { + if (one.charAt(pos) !== two.charAt(pos)) { + pos--; + break; + } + } + + if (pos < 1) { + return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : ''; + } + + // revert to last / + if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') { + pos = one.substring(0, pos).lastIndexOf('/'); + } + + return one.substring(0, pos + 1); + }; + + URI.withinString = function(string, callback, options) { + options || (options = {}); + var _start = options.start || URI.findUri.start; + var _end = options.end || URI.findUri.end; + var _trim = options.trim || URI.findUri.trim; + var _parens = options.parens || URI.findUri.parens; + var _attributeOpen = /[a-z0-9-]=["']?$/i; + + _start.lastIndex = 0; + while (true) { + var match = _start.exec(string); + if (!match) { + break; + } + + var start = match.index; + if (options.ignoreHtml) { + // attribut(e=["']?$) + var attributeOpen = string.slice(Math.max(start - 3, 0), start); + if (attributeOpen && _attributeOpen.test(attributeOpen)) { + continue; + } + } + + var end = start + string.slice(start).search(_end); + var slice = string.slice(start, end); + // make sure we include well balanced parens + var parensEnd = -1; + while (true) { + var parensMatch = _parens.exec(slice); + if (!parensMatch) { + break; + } + + var parensMatchEnd = parensMatch.index + parensMatch[0].length; + parensEnd = Math.max(parensEnd, parensMatchEnd); + } + + if (parensEnd > -1) { + slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, ''); + } else { + slice = slice.replace(_trim, ''); + } + + if (slice.length <= match[0].length) { + // the extract only contains the starting marker of a URI, + // e.g. "www" or "http://" + continue; + } + + if (options.ignore && options.ignore.test(slice)) { + continue; + } + + end = start + slice.length; + var result = callback(slice, start, end, string); + if (result === undefined) { + _start.lastIndex = end; + continue; + } + + result = String(result); + string = string.slice(0, start) + result + string.slice(end); + _start.lastIndex = start + result.length; + } + + _start.lastIndex = 0; + return string; + }; + + URI.ensureValidHostname = function(v, protocol) { + // Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986) + // they are not part of DNS and therefore ignored by URI.js + + var hasHostname = !!v; // not null and not an empty string + var hasProtocol = !!protocol; + var rejectEmptyHostname = false; + + if (hasProtocol) { + rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol); + } + + if (rejectEmptyHostname && !hasHostname) { + throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol); + } else if (v && v.match(URI.invalid_hostname_characters)) { + // test punycode + if (!punycode) { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available'); + } + if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]'); + } + } + }; + + URI.ensureValidPort = function (v) { + if (!v) { + return; + } + + var port = Number(v); + if (isInteger(port) && (port > 0) && (port < 65536)) { + return; + } + + throw new TypeError('Port "' + v + '" is not a valid port'); + }; + + // noConflict + URI.noConflict = function(removeAll) { + if (removeAll) { + var unconflicted = { + URI: this.noConflict() + }; + + if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') { + unconflicted.URITemplate = root.URITemplate.noConflict(); + } + + if (root.IPv6 && typeof root.IPv6.noConflict === 'function') { + unconflicted.IPv6 = root.IPv6.noConflict(); + } + + if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') { + unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict(); + } + + return unconflicted; + } else if (root.URI === this) { + root.URI = _URI; + } + + return this; + }; + + p.build = function(deferBuild) { + if (deferBuild === true) { + this._deferred_build = true; + } else if (deferBuild === undefined || this._deferred_build) { + this._string = URI.build(this._parts); + this._deferred_build = false; + } + + return this; + }; + + p.clone = function() { + return new URI(this); + }; + + p.valueOf = p.toString = function() { + return this.build(false)._string; + }; + + + function generateSimpleAccessor(_part){ + return function(v, build) { + if (v === undefined) { + return this._parts[_part] || ''; + } else { + this._parts[_part] = v || null; + this.build(!build); + return this; + } + }; + } + + function generatePrefixAccessor(_part, _key){ + return function(v, build) { + if (v === undefined) { + return this._parts[_part] || ''; + } else { + if (v !== null) { + v = v + ''; + if (v.charAt(0) === _key) { + v = v.substring(1); + } + } + + this._parts[_part] = v; + this.build(!build); + return this; + } + }; + } + + p.protocol = generateSimpleAccessor('protocol'); + p.username = generateSimpleAccessor('username'); + p.password = generateSimpleAccessor('password'); + p.hostname = generateSimpleAccessor('hostname'); + p.port = generateSimpleAccessor('port'); + p.query = generatePrefixAccessor('query', '?'); + p.fragment = generatePrefixAccessor('fragment', '#'); + + p.search = function(v, build) { + var t = this.query(v, build); + return typeof t === 'string' && t.length ? ('?' + t) : t; + }; + p.hash = function(v, build) { + var t = this.fragment(v, build); + return typeof t === 'string' && t.length ? ('#' + t) : t; + }; + + p.pathname = function(v, build) { + if (v === undefined || v === true) { + var res = this._parts.path || (this._parts.hostname ? '/' : ''); + return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res; + } else { + if (this._parts.urn) { + this._parts.path = v ? URI.recodeUrnPath(v) : ''; + } else { + this._parts.path = v ? URI.recodePath(v) : '/'; + } + this.build(!build); + return this; + } + }; + p.path = p.pathname; + p.href = function(href, build) { + var key; + + if (href === undefined) { + return this.toString(); + } + + this._string = ''; + this._parts = URI._parts(); + + var _URI = href instanceof URI; + var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname); + if (href.nodeName) { + var attribute = URI.getDomAttribute(href); + href = href[attribute] || ''; + _object = false; + } + + // window.location is reported to be an object, but it's not the sort + // of object we're looking for: + // * location.protocol ends with a colon + // * location.query != object.search + // * location.hash != object.fragment + // simply serializing the unknown object should do the trick + // (for location, not for everything...) + if (!_URI && _object && href.pathname !== undefined) { + href = href.toString(); + } + + if (typeof href === 'string' || href instanceof String) { + this._parts = URI.parse(String(href), this._parts); + } else if (_URI || _object) { + var src = _URI ? href._parts : href; + for (key in src) { + if (key === 'query') { continue; } + if (hasOwn.call(this._parts, key)) { + this._parts[key] = src[key]; + } + } + if (src.query) { + this.query(src.query, false); + } + } else { + throw new TypeError('invalid input'); + } + + this.build(!build); + return this; + }; + + // identification accessors + p.is = function(what) { + var ip = false; + var ip4 = false; + var ip6 = false; + var name = false; + var sld = false; + var idn = false; + var punycode = false; + var relative = !this._parts.urn; + + if (this._parts.hostname) { + relative = false; + ip4 = URI.ip4_expression.test(this._parts.hostname); + ip6 = URI.ip6_expression.test(this._parts.hostname); + ip = ip4 || ip6; + name = !ip; + sld = name && SLD && SLD.has(this._parts.hostname); + idn = name && URI.idn_expression.test(this._parts.hostname); + punycode = name && URI.punycode_expression.test(this._parts.hostname); + } + + switch (what.toLowerCase()) { + case 'relative': + return relative; + + case 'absolute': + return !relative; + + // hostname identification + case 'domain': + case 'name': + return name; + + case 'sld': + return sld; + + case 'ip': + return ip; + + case 'ip4': + case 'ipv4': + case 'inet4': + return ip4; + + case 'ip6': + case 'ipv6': + case 'inet6': + return ip6; + + case 'idn': + return idn; + + case 'url': + return !this._parts.urn; + + case 'urn': + return !!this._parts.urn; + + case 'punycode': + return punycode; + } + + return null; + }; + + // component specific input validation + var _protocol = p.protocol; + var _port = p.port; + var _hostname = p.hostname; + + p.protocol = function(v, build) { + if (v) { + // accept trailing :// + v = v.replace(/:(\/\/)?$/, ''); + + if (!v.match(URI.protocol_expression)) { + throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]'); + } + } + + return _protocol.call(this, v, build); + }; + p.scheme = p.protocol; + p.port = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v !== undefined) { + if (v === 0) { + v = null; + } + + if (v) { + v += ''; + if (v.charAt(0) === ':') { + v = v.substring(1); + } + + URI.ensureValidPort(v); + } + } + return _port.call(this, v, build); + }; + p.hostname = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v !== undefined) { + var x = { preventInvalidHostname: this._parts.preventInvalidHostname }; + var res = URI.parseHost(v, x); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + v = x.hostname; + if (this._parts.preventInvalidHostname) { + URI.ensureValidHostname(v, this._parts.protocol); + } + } + + return _hostname.call(this, v, build); + }; + + // compound accessors + p.origin = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + var protocol = this.protocol(); + var authority = this.authority(); + if (!authority) { + return ''; + } + + return (protocol ? protocol + '://' : '') + this.authority(); + } else { + var origin = URI(v); + this + .protocol(origin.protocol()) + .authority(origin.authority()) + .build(!build); + return this; + } + }; + p.host = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + return this._parts.hostname ? URI.buildHost(this._parts) : ''; + } else { + var res = URI.parseHost(v, this._parts); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + this.build(!build); + return this; + } + }; + p.authority = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + return this._parts.hostname ? URI.buildAuthority(this._parts) : ''; + } else { + var res = URI.parseAuthority(v, this._parts); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + this.build(!build); + return this; + } + }; + p.userinfo = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + var t = URI.buildUserinfo(this._parts); + return t ? t.substring(0, t.length -1) : t; + } else { + if (v[v.length-1] !== '@') { + v += '@'; + } + + URI.parseUserinfo(v, this._parts); + this.build(!build); + return this; + } + }; + p.resource = function(v, build) { + var parts; + + if (v === undefined) { + return this.path() + this.search() + this.hash(); + } + + parts = URI.parse(v); + this._parts.path = parts.path; + this._parts.query = parts.query; + this._parts.fragment = parts.fragment; + this.build(!build); + return this; + }; + + // fraction accessors + p.subdomain = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + // convenience, return "www" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + // grab domain and add another segment + var end = this._parts.hostname.length - this.domain().length - 1; + return this._parts.hostname.substring(0, end) || ''; + } else { + var e = this._parts.hostname.length - this.domain().length; + var sub = this._parts.hostname.substring(0, e); + var replace = new RegExp('^' + escapeRegEx(sub)); + + if (v && v.charAt(v.length - 1) !== '.') { + v += '.'; + } + + if (v.indexOf(':') !== -1) { + throw new TypeError('Domains cannot contain colons'); + } + + if (v) { + URI.ensureValidHostname(v, this._parts.protocol); + } + + this._parts.hostname = this._parts.hostname.replace(replace, v); + this.build(!build); + return this; + } + }; + p.domain = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v === 'boolean') { + build = v; + v = undefined; + } + + // convenience, return "example.org" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + // if hostname consists of 1 or 2 segments, it must be the domain + var t = this._parts.hostname.match(/\./g); + if (t && t.length < 2) { + return this._parts.hostname; + } + + // grab tld and add another segment + var end = this._parts.hostname.length - this.tld(build).length - 1; + end = this._parts.hostname.lastIndexOf('.', end -1) + 1; + return this._parts.hostname.substring(end) || ''; + } else { + if (!v) { + throw new TypeError('cannot set domain empty'); + } + + if (v.indexOf(':') !== -1) { + throw new TypeError('Domains cannot contain colons'); + } + + URI.ensureValidHostname(v, this._parts.protocol); + + if (!this._parts.hostname || this.is('IP')) { + this._parts.hostname = v; + } else { + var replace = new RegExp(escapeRegEx(this.domain()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.tld = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v === 'boolean') { + build = v; + v = undefined; + } + + // return "org" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + var pos = this._parts.hostname.lastIndexOf('.'); + var tld = this._parts.hostname.substring(pos + 1); + + if (build !== true && SLD && SLD.list[tld.toLowerCase()]) { + return SLD.get(this._parts.hostname) || tld; + } + + return tld; + } else { + var replace; + + if (!v) { + throw new TypeError('cannot set TLD empty'); + } else if (v.match(/[^a-zA-Z0-9-]/)) { + if (SLD && SLD.is(v)) { + replace = new RegExp(escapeRegEx(this.tld()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } else { + throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]'); + } + } else if (!this._parts.hostname || this.is('IP')) { + throw new ReferenceError('cannot set TLD on non-domain host'); + } else { + replace = new RegExp(escapeRegEx(this.tld()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.directory = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined || v === true) { + if (!this._parts.path && !this._parts.hostname) { + return ''; + } + + if (this._parts.path === '/') { + return '/'; + } + + var end = this._parts.path.length - this.filename().length - 1; + var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : ''); + + return v ? URI.decodePath(res) : res; + + } else { + var e = this._parts.path.length - this.filename().length; + var directory = this._parts.path.substring(0, e); + var replace = new RegExp('^' + escapeRegEx(directory)); + + // fully qualifier directories begin with a slash + if (!this.is('relative')) { + if (!v) { + v = '/'; + } + + if (v.charAt(0) !== '/') { + v = '/' + v; + } + } + + // directories always end with a slash + if (v && v.charAt(v.length - 1) !== '/') { + v += '/'; + } + + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + this.build(!build); + return this; + } + }; + p.filename = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v !== 'string') { + if (!this._parts.path || this._parts.path === '/') { + return ''; + } + + var pos = this._parts.path.lastIndexOf('/'); + var res = this._parts.path.substring(pos+1); + + return v ? URI.decodePathSegment(res) : res; + } else { + var mutatedDirectory = false; + + if (v.charAt(0) === '/') { + v = v.substring(1); + } + + if (v.match(/\.?\//)) { + mutatedDirectory = true; + } + + var replace = new RegExp(escapeRegEx(this.filename()) + '$'); + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + + if (mutatedDirectory) { + this.normalizePath(build); + } else { + this.build(!build); + } + + return this; + } + }; + p.suffix = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined || v === true) { + if (!this._parts.path || this._parts.path === '/') { + return ''; + } + + var filename = this.filename(); + var pos = filename.lastIndexOf('.'); + var s, res; + + if (pos === -1) { + return ''; + } + + // suffix may only contain alnum characters (yup, I made this up.) + s = filename.substring(pos+1); + res = (/^[a-z0-9%]+$/i).test(s) ? s : ''; + return v ? URI.decodePathSegment(res) : res; + } else { + if (v.charAt(0) === '.') { + v = v.substring(1); + } + + var suffix = this.suffix(); + var replace; + + if (!suffix) { + if (!v) { + return this; + } + + this._parts.path += '.' + URI.recodePath(v); + } else if (!v) { + replace = new RegExp(escapeRegEx('.' + suffix) + '$'); + } else { + replace = new RegExp(escapeRegEx(suffix) + '$'); + } + + if (replace) { + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.segment = function(segment, v, build) { + var separator = this._parts.urn ? ':' : '/'; + var path = this.path(); + var absolute = path.substring(0, 1) === '/'; + var segments = path.split(separator); + + if (segment !== undefined && typeof segment !== 'number') { + build = v; + v = segment; + segment = undefined; + } + + if (segment !== undefined && typeof segment !== 'number') { + throw new Error('Bad segment "' + segment + '", must be 0-based integer'); + } + + if (absolute) { + segments.shift(); + } + + if (segment < 0) { + // allow negative indexes to address from the end + segment = Math.max(segments.length + segment, 0); + } + + if (v === undefined) { + /*jshint laxbreak: true */ + return segment === undefined + ? segments + : segments[segment]; + /*jshint laxbreak: false */ + } else if (segment === null || segments[segment] === undefined) { + if (isArray(v)) { + segments = []; + // collapse empty elements within array + for (var i=0, l=v.length; i < l; i++) { + if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) { + continue; + } + + if (segments.length && !segments[segments.length -1].length) { + segments.pop(); + } + + segments.push(trimSlashes(v[i])); + } + } else if (v || typeof v === 'string') { + v = trimSlashes(v); + if (segments[segments.length -1] === '') { + // empty trailing elements have to be overwritten + // to prevent results such as /foo//bar + segments[segments.length -1] = v; + } else { + segments.push(v); + } + } + } else { + if (v) { + segments[segment] = trimSlashes(v); + } else { + segments.splice(segment, 1); + } + } + + if (absolute) { + segments.unshift(''); + } + + return this.path(segments.join(separator), build); + }; + p.segmentCoded = function(segment, v, build) { + var segments, i, l; + + if (typeof segment !== 'number') { + build = v; + v = segment; + segment = undefined; + } + + if (v === undefined) { + segments = this.segment(segment, v, build); + if (!isArray(segments)) { + segments = segments !== undefined ? URI.decode(segments) : undefined; + } else { + for (i = 0, l = segments.length; i < l; i++) { + segments[i] = URI.decode(segments[i]); + } + } + + return segments; + } + + if (!isArray(v)) { + v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v; + } else { + for (i = 0, l = v.length; i < l; i++) { + v[i] = URI.encode(v[i]); + } + } + + return this.segment(segment, v, build); + }; + + // mutating query string + var q = p.query; + p.query = function(v, build) { + if (v === true) { + return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + } else if (typeof v === 'function') { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + var result = v.call(this, data); + this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + this.build(!build); + return this; + } else if (v !== undefined && typeof v !== 'string') { + this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + this.build(!build); + return this; + } else { + return q.call(this, v, build); + } + }; + p.setQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + + if (typeof name === 'string' || name instanceof String) { + data[name] = value !== undefined ? value : null; + } else if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + data[key] = name[key]; + } + } + } else { + throw new TypeError('URI.addQuery() accepts an object, string as the name parameter'); + } + + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.addQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + URI.addQuery(data, name, value === undefined ? null : value); + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.removeQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + URI.removeQuery(data, name, value); + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.hasQuery = function(name, value, withinArray) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + return URI.hasQuery(data, name, value, withinArray); + }; + p.setSearch = p.setQuery; + p.addSearch = p.addQuery; + p.removeSearch = p.removeQuery; + p.hasSearch = p.hasQuery; + + // sanitizing URLs + p.normalize = function() { + if (this._parts.urn) { + return this + .normalizeProtocol(false) + .normalizePath(false) + .normalizeQuery(false) + .normalizeFragment(false) + .build(); + } + + return this + .normalizeProtocol(false) + .normalizeHostname(false) + .normalizePort(false) + .normalizePath(false) + .normalizeQuery(false) + .normalizeFragment(false) + .build(); + }; + p.normalizeProtocol = function(build) { + if (typeof this._parts.protocol === 'string') { + this._parts.protocol = this._parts.protocol.toLowerCase(); + this.build(!build); + } + + return this; + }; + p.normalizeHostname = function(build) { + if (this._parts.hostname) { + if (this.is('IDN') && punycode) { + this._parts.hostname = punycode.toASCII(this._parts.hostname); + } else if (this.is('IPv6') && IPv6) { + this._parts.hostname = IPv6.best(this._parts.hostname); + } + + this._parts.hostname = this._parts.hostname.toLowerCase(); + this.build(!build); + } + + return this; + }; + p.normalizePort = function(build) { + // remove port of it's the protocol's default + if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) { + this._parts.port = null; + this.build(!build); + } + + return this; + }; + p.normalizePath = function(build) { + var _path = this._parts.path; + if (!_path) { + return this; + } + + if (this._parts.urn) { + this._parts.path = URI.recodeUrnPath(this._parts.path); + this.build(!build); + return this; + } + + if (this._parts.path === '/') { + return this; + } + + _path = URI.recodePath(_path); + + var _was_relative; + var _leadingParents = ''; + var _parent, _pos; + + // handle relative paths + if (_path.charAt(0) !== '/') { + _was_relative = true; + _path = '/' + _path; + } + + // handle relative files (as opposed to directories) + if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') { + _path += '/'; + } + + // resolve simples + _path = _path + .replace(/(\/(\.\/)+)|(\/\.$)/g, '/') + .replace(/\/{2,}/g, '/'); + + // remember leading parents + if (_was_relative) { + _leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || ''; + if (_leadingParents) { + _leadingParents = _leadingParents[0]; + } + } + + // resolve parents + while (true) { + _parent = _path.search(/\/\.\.(\/|$)/); + if (_parent === -1) { + // no more ../ to resolve + break; + } else if (_parent === 0) { + // top level cannot be relative, skip it + _path = _path.substring(3); + continue; + } + + _pos = _path.substring(0, _parent).lastIndexOf('/'); + if (_pos === -1) { + _pos = _parent; + } + _path = _path.substring(0, _pos) + _path.substring(_parent + 3); + } + + // revert to relative + if (_was_relative && this.is('relative')) { + _path = _leadingParents + _path.substring(1); + } + + this._parts.path = _path; + this.build(!build); + return this; + }; + p.normalizePathname = p.normalizePath; + p.normalizeQuery = function(build) { + if (typeof this._parts.query === 'string') { + if (!this._parts.query.length) { + this._parts.query = null; + } else { + this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace)); + } + + this.build(!build); + } + + return this; + }; + p.normalizeFragment = function(build) { + if (!this._parts.fragment) { + this._parts.fragment = null; + this.build(!build); + } + + return this; + }; + p.normalizeSearch = p.normalizeQuery; + p.normalizeHash = p.normalizeFragment; + + p.iso8859 = function() { + // expect unicode input, iso8859 output + var e = URI.encode; + var d = URI.decode; + + URI.encode = escape; + URI.decode = decodeURIComponent; + try { + this.normalize(); + } finally { + URI.encode = e; + URI.decode = d; + } + return this; + }; + + p.unicode = function() { + // expect iso8859 input, unicode output + var e = URI.encode; + var d = URI.decode; + + URI.encode = strictEncodeURIComponent; + URI.decode = unescape; + try { + this.normalize(); + } finally { + URI.encode = e; + URI.decode = d; + } + return this; + }; + + p.readable = function() { + var uri = this.clone(); + // removing username, password, because they shouldn't be displayed according to RFC 3986 + uri.username('').password('').normalize(); + var t = ''; + if (uri._parts.protocol) { + t += uri._parts.protocol + '://'; + } + + if (uri._parts.hostname) { + if (uri.is('punycode') && punycode) { + t += punycode.toUnicode(uri._parts.hostname); + if (uri._parts.port) { + t += ':' + uri._parts.port; + } + } else { + t += uri.host(); + } + } + + if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') { + t += '/'; + } + + t += uri.path(true); + if (uri._parts.query) { + var q = ''; + for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) { + var kv = (qp[i] || '').split('='); + q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace) + .replace(/&/g, '%26'); + + if (kv[1] !== undefined) { + q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace) + .replace(/&/g, '%26'); + } + } + t += '?' + q.substring(1); + } + + t += URI.decodeQuery(uri.hash(), true); + return t; + }; + + // resolving relative and absolute URLs + p.absoluteTo = function(base) { + var resolved = this.clone(); + var properties = ['protocol', 'username', 'password', 'hostname', 'port']; + var basedir, i, p; + + if (this._parts.urn) { + throw new Error('URNs do not have any generally defined hierarchical components'); + } + + if (!(base instanceof URI)) { + base = new URI(base); + } + + if (resolved._parts.protocol) { + // Directly returns even if this._parts.hostname is empty. + return resolved; + } else { + resolved._parts.protocol = base._parts.protocol; + } + + if (this._parts.hostname) { + return resolved; + } + + for (i = 0; (p = properties[i]); i++) { + resolved._parts[p] = base._parts[p]; + } + + if (!resolved._parts.path) { + resolved._parts.path = base._parts.path; + if (!resolved._parts.query) { + resolved._parts.query = base._parts.query; + } + } else { + if (resolved._parts.path.substring(-2) === '..') { + resolved._parts.path += '/'; + } + + if (resolved.path().charAt(0) !== '/') { + basedir = base.directory(); + basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : ''; + resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path; + resolved.normalizePath(); + } + } + + resolved.build(); + return resolved; + }; + p.relativeTo = function(base) { + var relative = this.clone().normalize(); + var relativeParts, baseParts, common, relativePath, basePath; + + if (relative._parts.urn) { + throw new Error('URNs do not have any generally defined hierarchical components'); + } + + base = new URI(base).normalize(); + relativeParts = relative._parts; + baseParts = base._parts; + relativePath = relative.path(); + basePath = base.path(); + + if (relativePath.charAt(0) !== '/') { + throw new Error('URI is already relative'); + } + + if (basePath.charAt(0) !== '/') { + throw new Error('Cannot calculate a URI relative to another relative URI'); + } + + if (relativeParts.protocol === baseParts.protocol) { + relativeParts.protocol = null; + } + + if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) { + return relative.build(); + } + + if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) { + return relative.build(); + } + + if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) { + relativeParts.hostname = null; + relativeParts.port = null; + } else { + return relative.build(); + } + + if (relativePath === basePath) { + relativeParts.path = ''; + return relative.build(); + } + + // determine common sub path + common = URI.commonPath(relativePath, basePath); + + // If the paths have nothing in common, return a relative URL with the absolute path. + if (!common) { + return relative.build(); + } + + var parents = baseParts.path + .substring(common.length) + .replace(/[^\/]*$/, '') + .replace(/.*?\//g, '../'); + + relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './'; + + return relative.build(); + }; + + // comparing URIs + p.equals = function(uri) { + var one = this.clone(); + var two = new URI(uri); + var one_map = {}; + var two_map = {}; + var checked = {}; + var one_query, two_query, key; + + one.normalize(); + two.normalize(); + + // exact match + if (one.toString() === two.toString()) { + return true; + } + + // extract query string + one_query = one.query(); + two_query = two.query(); + one.query(''); + two.query(''); + + // definitely not equal if not even non-query parts match + if (one.toString() !== two.toString()) { + return false; + } + + // query parameters have the same length, even if they're permuted + if (one_query.length !== two_query.length) { + return false; + } + + one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace); + two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace); + + for (key in one_map) { + if (hasOwn.call(one_map, key)) { + if (!isArray(one_map[key])) { + if (one_map[key] !== two_map[key]) { + return false; + } + } else if (!arraysEqual(one_map[key], two_map[key])) { + return false; + } + + checked[key] = true; + } + } + + for (key in two_map) { + if (hasOwn.call(two_map, key)) { + if (!checked[key]) { + // two contains a parameter not present in one + return false; + } + } + } + + return true; + }; + + // state + p.preventInvalidHostname = function(v) { + this._parts.preventInvalidHostname = !!v; + return this; + }; + + p.duplicateQueryParameters = function(v) { + this._parts.duplicateQueryParameters = !!v; + return this; + }; + + p.escapeQuerySpace = function(v) { + this._parts.escapeQuerySpace = !!v; + return this; + }; + + return URI; +})); + + +/***/ }), + +/***/ 9127: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * URI Template Support - http://tools.ietf.org/html/rfc6570 + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(__webpack_require__(4193)); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4193)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (URI, root) { + 'use strict'; + // FIXME: v2.0.0 renamce non-camelCase properties to uppercase + /*jshint camelcase: false */ + + // save current URITemplate variable, if any + var _URITemplate = root && root.URITemplate; + + var hasOwn = Object.prototype.hasOwnProperty; + function URITemplate(expression) { + // serve from cache where possible + if (URITemplate._cache[expression]) { + return URITemplate._cache[expression]; + } + + // Allow instantiation without the 'new' keyword + if (!(this instanceof URITemplate)) { + return new URITemplate(expression); + } + + this.expression = expression; + URITemplate._cache[expression] = this; + return this; + } + + function Data(data) { + this.data = data; + this.cache = {}; + } + + var p = URITemplate.prototype; + // list of operators and their defined options + var operators = { + // Simple string expansion + '' : { + prefix: '', + separator: ',', + named: false, + empty_name_separator: false, + encode : 'encode' + }, + // Reserved character strings + '+' : { + prefix: '', + separator: ',', + named: false, + empty_name_separator: false, + encode : 'encodeReserved' + }, + // Fragment identifiers prefixed by '#' + '#' : { + prefix: '#', + separator: ',', + named: false, + empty_name_separator: false, + encode : 'encodeReserved' + }, + // Name labels or extensions prefixed by '.' + '.' : { + prefix: '.', + separator: '.', + named: false, + empty_name_separator: false, + encode : 'encode' + }, + // Path segments prefixed by '/' + '/' : { + prefix: '/', + separator: '/', + named: false, + empty_name_separator: false, + encode : 'encode' + }, + // Path parameter name or name=value pairs prefixed by ';' + ';' : { + prefix: ';', + separator: ';', + named: true, + empty_name_separator: false, + encode : 'encode' + }, + // Query component beginning with '?' and consisting + // of name=value pairs separated by '&'; an + '?' : { + prefix: '?', + separator: '&', + named: true, + empty_name_separator: true, + encode : 'encode' + }, + // Continuation of query-style &name=value pairs + // within a literal query component. + '&' : { + prefix: '&', + separator: '&', + named: true, + empty_name_separator: true, + encode : 'encode' + } + + // The operator characters equals ("="), comma (","), exclamation ("!"), + // at sign ("@"), and pipe ("|") are reserved for future extensions. + }; + + // storage for already parsed templates + URITemplate._cache = {}; + // pattern to identify expressions [operator, variable-list] in template + URITemplate.EXPRESSION_PATTERN = /\{([^a-zA-Z0-9%_]?)([^\}]+)(\}|$)/g; + // pattern to identify variables [name, explode, maxlength] in variable-list + URITemplate.VARIABLE_PATTERN = /^([^*:.](?:\.?[^*:.])*)((\*)|:(\d+))?$/; + // pattern to verify variable name integrity + URITemplate.VARIABLE_NAME_PATTERN = /[^a-zA-Z0-9%_.]/; + // pattern to verify literal integrity + URITemplate.LITERAL_PATTERN = /[<>{}"`^| \\]/; + + // expand parsed expression (expression, not template!) + URITemplate.expand = function(expression, data, opts) { + // container for defined options for the given operator + var options = operators[expression.operator]; + // expansion type (include keys or not) + var type = options.named ? 'Named' : 'Unnamed'; + // list of variables within the expression + var variables = expression.variables; + // result buffer for evaluating the expression + var buffer = []; + var d, variable, i; + + for (i = 0; (variable = variables[i]); i++) { + // fetch simplified data source + d = data.get(variable.name); + if (d.type === 0 && opts && opts.strict) { + throw new Error('Missing expansion value for variable "' + variable.name + '"'); + } + if (!d.val.length) { + if (d.type) { + // empty variables (empty string) + // still lead to a separator being appended! + buffer.push(''); + } + // no data, no action + continue; + } + + if (d.type > 1 && variable.maxlength) { + // composite variable cannot specify maxlength + throw new Error('Invalid expression: Prefix modifier not applicable to variable "' + variable.name + '"'); + } + + // expand the given variable + buffer.push(URITemplate['expand' + type]( + d, + options, + variable.explode, + variable.explode && options.separator || ',', + variable.maxlength, + variable.name + )); + } + + if (buffer.length) { + return options.prefix + buffer.join(options.separator); + } else { + // prefix is not prepended for empty expressions + return ''; + } + }; + // expand a named variable + URITemplate.expandNamed = function(d, options, explode, separator, length, name) { + // variable result buffer + var result = ''; + // peformance crap + var encode = options.encode; + var empty_name_separator = options.empty_name_separator; + // flag noting if values are already encoded + var _encode = !d[encode].length; + // key for named expansion + var _name = d.type === 2 ? '': URI[encode](name); + var _value, i, l; + + // for each found value + for (i = 0, l = d.val.length; i < l; i++) { + if (length) { + // maxlength must be determined before encoding can happen + _value = URI[encode](d.val[i][1].substring(0, length)); + if (d.type === 2) { + // apply maxlength to keys of objects as well + _name = URI[encode](d.val[i][0].substring(0, length)); + } + } else if (_encode) { + // encode value + _value = URI[encode](d.val[i][1]); + if (d.type === 2) { + // encode name and cache encoded value + _name = URI[encode](d.val[i][0]); + d[encode].push([_name, _value]); + } else { + // cache encoded value + d[encode].push([undefined, _value]); + } + } else { + // values are already encoded and can be pulled from cache + _value = d[encode][i][1]; + if (d.type === 2) { + _name = d[encode][i][0]; + } + } + + if (result) { + // unless we're the first value, prepend the separator + result += separator; + } + + if (!explode) { + if (!i) { + // first element, so prepend variable name + result += URI[encode](name) + (empty_name_separator || _value ? '=' : ''); + } + + if (d.type === 2) { + // without explode-modifier, keys of objects are returned comma-separated + result += _name + ','; + } + + result += _value; + } else { + // only add the = if it is either default (?&) or there actually is a value (;) + result += _name + (empty_name_separator || _value ? '=' : '') + _value; + } + } + + return result; + }; + // expand an unnamed variable + URITemplate.expandUnnamed = function(d, options, explode, separator, length) { + // variable result buffer + var result = ''; + // performance crap + var encode = options.encode; + var empty_name_separator = options.empty_name_separator; + // flag noting if values are already encoded + var _encode = !d[encode].length; + var _name, _value, i, l; + + // for each found value + for (i = 0, l = d.val.length; i < l; i++) { + if (length) { + // maxlength must be determined before encoding can happen + _value = URI[encode](d.val[i][1].substring(0, length)); + } else if (_encode) { + // encode and cache value + _value = URI[encode](d.val[i][1]); + d[encode].push([ + d.type === 2 ? URI[encode](d.val[i][0]) : undefined, + _value + ]); + } else { + // value already encoded, pull from cache + _value = d[encode][i][1]; + } + + if (result) { + // unless we're the first value, prepend the separator + result += separator; + } + + if (d.type === 2) { + if (length) { + // maxlength also applies to keys of objects + _name = URI[encode](d.val[i][0].substring(0, length)); + } else { + // at this point the name must already be encoded + _name = d[encode][i][0]; + } + + result += _name; + if (explode) { + // explode-modifier separates name and value by "=" + result += (empty_name_separator || _value ? '=' : ''); + } else { + // no explode-modifier separates name and value by "," + result += ','; + } + } + + result += _value; + } + + return result; + }; + + URITemplate.noConflict = function() { + if (root.URITemplate === URITemplate) { + root.URITemplate = _URITemplate; + } + + return URITemplate; + }; + + // expand template through given data map + p.expand = function(data, opts) { + var result = ''; + + if (!this.parts || !this.parts.length) { + // lazilyy parse the template + this.parse(); + } + + if (!(data instanceof Data)) { + // make given data available through the + // optimized data handling thingie + data = new Data(data); + } + + for (var i = 0, l = this.parts.length; i < l; i++) { + /*jshint laxbreak: true */ + result += typeof this.parts[i] === 'string' + // literal string + ? this.parts[i] + // expression + : URITemplate.expand(this.parts[i], data, opts); + /*jshint laxbreak: false */ + } + + return result; + }; + // parse template into action tokens + p.parse = function() { + // performance crap + var expression = this.expression; + var ePattern = URITemplate.EXPRESSION_PATTERN; + var vPattern = URITemplate.VARIABLE_PATTERN; + var nPattern = URITemplate.VARIABLE_NAME_PATTERN; + var lPattern = URITemplate.LITERAL_PATTERN; + // token result buffer + var parts = []; + // position within source template + var pos = 0; + var variables, eMatch, vMatch; + + var checkLiteral = function(literal) { + if (literal.match(lPattern)) { + throw new Error('Invalid Literal "' + literal + '"'); + } + return literal; + }; + + // RegExp is shared accross all templates, + // which requires a manual reset + ePattern.lastIndex = 0; + // I don't like while(foo = bar()) loops, + // to make things simpler I go while(true) and break when required + while (true) { + eMatch = ePattern.exec(expression); + if (eMatch === null) { + // push trailing literal + parts.push(checkLiteral(expression.substring(pos))); + break; + } else { + // push leading literal + parts.push(checkLiteral(expression.substring(pos, eMatch.index))); + pos = eMatch.index + eMatch[0].length; + } + + if (!operators[eMatch[1]]) { + throw new Error('Unknown Operator "' + eMatch[1] + '" in "' + eMatch[0] + '"'); + } else if (!eMatch[3]) { + throw new Error('Unclosed Expression "' + eMatch[0] + '"'); + } + + // parse variable-list + variables = eMatch[2].split(','); + for (var i = 0, l = variables.length; i < l; i++) { + vMatch = variables[i].match(vPattern); + if (vMatch === null) { + throw new Error('Invalid Variable "' + variables[i] + '" in "' + eMatch[0] + '"'); + } else if (vMatch[1].match(nPattern)) { + throw new Error('Invalid Variable Name "' + vMatch[1] + '" in "' + eMatch[0] + '"'); + } + + variables[i] = { + name: vMatch[1], + explode: !!vMatch[3], + maxlength: vMatch[4] && parseInt(vMatch[4], 10) + }; + } + + if (!variables.length) { + throw new Error('Expression Missing Variable(s) "' + eMatch[0] + '"'); + } + + parts.push({ + expression: eMatch[0], + operator: eMatch[1], + variables: variables + }); + } + + if (!parts.length) { + // template doesn't contain any expressions + // so it is a simple literal string + // this probably should fire a warning or something? + parts.push(checkLiteral(expression)); + } + + this.parts = parts; + return this; + }; + + // simplify data structures + Data.prototype.get = function(key) { + // performance crap + var data = this.data; + // cache for processed data-point + var d = { + // type of data 0: undefined/null, 1: string, 2: object, 3: array + type: 0, + // original values (except undefined/null) + val: [], + // cache for encoded values (only for non-maxlength expansion) + encode: [], + encodeReserved: [] + }; + var i, l, value; + + if (this.cache[key] !== undefined) { + // we've already processed this key + return this.cache[key]; + } + + this.cache[key] = d; + + if (String(Object.prototype.toString.call(data)) === '[object Function]') { + // data itself is a callback (global callback) + value = data(key); + } else if (String(Object.prototype.toString.call(data[key])) === '[object Function]') { + // data is a map of callbacks (local callback) + value = data[key](key); + } else { + // data is a map of data + value = data[key]; + } + + // generalize input into [ [name1, value1], [name2, value2], … ] + // so expansion has to deal with a single data structure only + if (value === undefined || value === null) { + // undefined and null values are to be ignored completely + return d; + } else if (String(Object.prototype.toString.call(value)) === '[object Array]') { + for (i = 0, l = value.length; i < l; i++) { + if (value[i] !== undefined && value[i] !== null) { + // arrays don't have names + d.val.push([undefined, String(value[i])]); + } + } + + if (d.val.length) { + // only treat non-empty arrays as arrays + d.type = 3; // array + } + } else if (String(Object.prototype.toString.call(value)) === '[object Object]') { + for (i in value) { + if (hasOwn.call(value, i) && value[i] !== undefined && value[i] !== null) { + // objects have keys, remember them for named expansion + d.val.push([i, String(value[i])]); + } + } + + if (d.val.length) { + // only treat non-empty objects as objects + d.type = 2; // object + } + } else { + d.type = 1; // primitive string (could've been string, number, boolean and objects with a toString()) + // arrays don't have names + d.val.push([undefined, String(value)]); + } + + return d; + }; + + // hook into URI for fluid access + URI.expand = function(expression, data) { + var template = new URITemplate(expression); + var expansion = template.expand(data); + + return new URI(expansion); + }; + + return URITemplate; +})); + + +/***/ }), + +/***/ 9340: +/***/ (function(module, exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.0 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = true && exports && + !exports.nodeType && exports; + var freeModule = true && module && + !module.nodeType && module; + var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + true + ) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { + return punycode; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} + +}(this)); + + +/***/ }), + +/***/ 2894: +/***/ (() => { + +/* (ignored) */ + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat get default export */ +/******/ (() => { +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = (module) => { +/******/ var getter = module && module.__esModule ? +/******/ () => (module['default']) : +/******/ () => (module); +/******/ __webpack_require__.d(getter, { a: getter }); +/******/ return getter; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/global */ +/******/ (() => { +/******/ __webpack_require__.g = (function() { +/******/ if (typeof globalThis === 'object') return globalThis; +/******/ try { +/******/ return this || new Function('return this')(); +/******/ } catch (e) { +/******/ if (typeof window === 'object') return window; +/******/ } +/******/ })(); +/******/ })(); +/******/ +/******/ /* webpack/runtime/harmony module decorator */ +/******/ (() => { +/******/ __webpack_require__.hmd = (module) => { +/******/ module = Object.create(module); +/******/ if (!module.children) module.children = []; +/******/ Object.defineProperty(module, 'exports', { +/******/ enumerable: true, +/******/ set: () => { +/******/ throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id); +/******/ } +/******/ }); +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __webpack_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/node module decorator */ +/******/ (() => { +/******/ __webpack_require__.nmd = (module) => { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/************************************************************************/ +/******/ +/******/ // startup +/******/ // Load entry module and return exports +/******/ // This entry module is referenced by other modules so it can't be inlined +/******/ var __webpack_exports__ = __webpack_require__(1924); +/******/ +/******/ return __webpack_exports__; +/******/ })() +; +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-minimal.min.js b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-minimal.min.js new file mode 100644 index 000000000..68e1cec53 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-minimal.min.js @@ -0,0 +1,2 @@ +/*! For license information please see stellar-sdk-minimal.min.js.LICENSE.txt */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("StellarSdk",[],t):"object"==typeof exports?exports.StellarSdk=t():e.StellarSdk=t()}(self,(()=>(()=>{var e={3740:function(e){var t;t=()=>(()=>{var e={616:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(287);n.hp.alloc(1).subarray(0,1)instanceof n.hp||(n.hp.prototype.subarray=function(e,t){const r=Uint8Array.prototype.subarray.call(this,e,t);return Object.setPrototypeOf(r,n.hp.prototype),r});const o=n.hp},281:(e,t,r)=>{const n=r(164);e.exports=n},164:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Array:()=>D,Bool:()=>j,Double:()=>R,Enum:()=>H,Float:()=>I,Hyper:()=>O,Int:()=>k,LargeInt:()=>T,Opaque:()=>U,Option:()=>q,Quadruple:()=>C,Reference:()=>z,String:()=>L,Struct:()=>X,Union:()=>$,UnsignedHyper:()=>P,UnsignedInt:()=>A,VarArray:()=>V,VarOpaque:()=>F,Void:()=>K,XdrReader:()=>s,XdrWriter:()=>f,config:()=>ne});class n extends TypeError{constructor(e){super(`XDR Write Error: ${e}`)}}class o extends TypeError{constructor(e){super(`XDR Read Error: ${e}`)}}class i extends TypeError{constructor(e){super(`XDR Type Definition Error: ${e}`)}}class a extends i{constructor(){super("method not implemented, it should be overloaded in the descendant class.")}}var u=r(616).A;class s{constructor(e){if(!u.isBuffer(e)){if(!(e instanceof Array||Array.isArray(e)||ArrayBuffer.isView(e)))throw new o(`source invalid: ${e}`);e=u.from(e)}this._buffer=e,this._length=e.length,this._index=0}_buffer;_length;_index;get eof(){return this._index===this._length}advance(e){const t=this._index;if(this._index+=e,this._length0){for(let e=0;e0){const e=this.alloc(r);this._buffer.fill(0,e,this._index)}}writeInt32BE(e){const t=this.alloc(4);this._buffer.writeInt32BE(e,t)}writeUInt32BE(e){const t=this.alloc(4);this._buffer.writeUInt32BE(e,t)}writeBigInt64BE(e){const t=this.alloc(8);this._buffer.writeBigInt64BE(e,t)}writeBigUInt64BE(e){const t=this.alloc(8);this._buffer.writeBigUInt64BE(e,t)}writeFloatBE(e){const t=this.alloc(4);this._buffer.writeFloatBE(e,t)}writeDoubleBE(e){const t=this.alloc(8);this._buffer.writeDoubleBE(e,t)}static bufferChunkSize=l}var p=r(616).A;class d{toXDR(e="raw"){if(!this.write)return this.constructor.toXDR(this,e);const t=new f;return this.write(this,t),v(t.finalize(),e)}fromXDR(e,t="raw"){if(!this.read)return this.constructor.fromXDR(e,t);const r=new s(g(e,t)),n=this.read(r);return r.ensureInputConsumed(),n}validateXDR(e,t="raw"){try{return this.fromXDR(e,t),!0}catch(e){return!1}}static toXDR(e,t="raw"){const r=new f;return this.write(e,r),v(r.finalize(),t)}static fromXDR(e,t="raw"){const r=new s(g(e,t)),n=this.read(r);return r.ensureInputConsumed(),n}static validateXDR(e,t="raw"){try{return this.fromXDR(e,t),!0}catch(e){return!1}}}class h extends d{static read(e){throw new a}static write(e,t){throw new a}static isValid(e){return!1}}class y extends d{isValid(e){return!1}}class m extends TypeError{constructor(e){super(`Invalid format ${e}, must be one of "raw", "hex", "base64"`)}}function v(e,t){switch(t){case"raw":return e;case"hex":return e.toString("hex");case"base64":return e.toString("base64");default:throw new m(t)}}function g(e,t){switch(t){case"raw":return e;case"hex":return p.from(e,"hex");case"base64":return p.from(e,"base64");default:throw new m(t)}}function b(e,t){return null!=e&&(e instanceof t||w(e,t)&&"function"==typeof e.constructor.read&&"function"==typeof e.constructor.write&&w(e,"XdrType"))}function w(e,t){do{if(e.constructor.name===t)return!0}while(e=Object.getPrototypeOf(e));return!1}const S=2147483647;class k extends h{static read(e){return e.readInt32BE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");if((0|e)!==e)throw new n("invalid i32 value");t.writeInt32BE(e)}static isValid(e){return"number"==typeof e&&(0|e)===e&&e>=-2147483648&&e<=S}}function E(e,t,r){if("bigint"!=typeof e)throw new TypeError("Expected bigint 'value', got "+typeof e);const n=t/r;if(1===n)return[e];if(r<32||r>128||2!==n&&4!==n&&8!==n)throw new TypeError(`invalid bigint (${e}) and slice size (${t} -> ${r}) combination`);const o=BigInt(r),i=new Array(n);for(let t=0;t>=o;return i}function _(e,t){if(t)return[0n,(1n<=i&&o<=a)return o;throw new TypeError(`bigint values [${e}] for ${function(e,t){return`${t?"u":"i"}${e}`}(t,r)} out of range [${i}, ${a}]: ${o}`)}(e,this.size,this.unsigned)}get unsigned(){throw new a}get size(){throw new a}slice(e){return E(this._value,this.size,e)}toString(){return this._value.toString()}toJSON(){return{_value:this._value.toString()}}toBigInt(){return BigInt(this._value)}static read(e){const{size:t}=this.prototype;return 64===t?new this(e.readBigUInt64BE()):new this(...Array.from({length:t/64},(()=>e.readBigUInt64BE())).reverse())}static write(e,t){if(e instanceof this)e=e._value;else if("bigint"!=typeof e||e>this.MAX_VALUE||e>32n)}get size(){return 64}get unsigned(){return!1}static fromBits(e,t){return new this(e,t)}}O.defineIntBoundaries();const x=4294967295;class A extends h{static read(e){return e.readUInt32BE()}static write(e,t){if("number"!=typeof e||!(e>=0&&e<=x)||e%1!=0)throw new n("invalid u32 value");t.writeUInt32BE(e)}static isValid(e){return"number"==typeof e&&e%1==0&&e>=0&&e<=x}}A.MAX_VALUE=x,A.MIN_VALUE=0;class P extends T{constructor(...e){super(e)}get low(){return 0|Number(0xffffffffn&this._value)}get high(){return 0|Number(this._value>>32n)}get size(){return 64}get unsigned(){return!0}static fromBits(e,t){return new this(e,t)}}P.defineIntBoundaries();class I extends h{static read(e){return e.readFloatBE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");t.writeFloatBE(e)}static isValid(e){return"number"==typeof e}}class R extends h{static read(e){return e.readDoubleBE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");t.writeDoubleBE(e)}static isValid(e){return"number"==typeof e}}class C extends h{static read(){throw new i("quadruple not supported")}static write(){throw new i("quadruple not supported")}static isValid(){return!1}}class j extends h{static read(e){const t=k.read(e);switch(t){case 0:return!1;case 1:return!0;default:throw new o(`got ${t} when trying to read a bool`)}}static write(e,t){const r=e?1:0;k.write(r,t)}static isValid(e){return"boolean"==typeof e}}var B=r(616).A;class L extends y{constructor(e=A.MAX_VALUE){super(),this._maxLength=e}read(e){const t=A.read(e);if(t>this._maxLength)throw new o(`saw ${t} length String, max allowed is ${this._maxLength}`);return e.read(t)}readString(e){return this.read(e).toString("utf8")}write(e,t){const r="string"==typeof e?B.byteLength(e,"utf8"):e.length;if(r>this._maxLength)throw new n(`got ${e.length} bytes, max allowed is ${this._maxLength}`);A.write(r,t),t.write(e,r)}isValid(e){return"string"==typeof e?B.byteLength(e,"utf8")<=this._maxLength:!!(e instanceof Array||B.isBuffer(e))&&e.length<=this._maxLength}}var N=r(616).A;class U extends y{constructor(e){super(),this._length=e}read(e){return e.read(this._length)}write(e,t){const{length:r}=e;if(r!==this._length)throw new n(`got ${e.length} bytes, expected ${this._length}`);t.write(e,r)}isValid(e){return N.isBuffer(e)&&e.length===this._length}}var M=r(616).A;class F extends y{constructor(e=A.MAX_VALUE){super(),this._maxLength=e}read(e){const t=A.read(e);if(t>this._maxLength)throw new o(`saw ${t} length VarOpaque, max allowed is ${this._maxLength}`);return e.read(t)}write(e,t){const{length:r}=e;if(e.length>this._maxLength)throw new n(`got ${e.length} bytes, max allowed is ${this._maxLength}`);A.write(r,t),t.write(e,r)}isValid(e){return M.isBuffer(e)&&e.length<=this._maxLength}}class D extends y{constructor(e,t){super(),this._childType=e,this._length=t}read(e){const t=new r.g.Array(this._length);for(let r=0;rthis._maxLength)throw new o(`saw ${t} length VarArray, max allowed is ${this._maxLength}`);const r=new Array(t);for(let n=0;nthis._maxLength)throw new n(`got array of size ${e.length}, max allowed is ${this._maxLength}`);A.write(e.length,t);for(const r of e)this._childType.write(r,t)}isValid(e){if(!(e instanceof Array)||e.length>this._maxLength)return!1;for(const t of e)if(!this._childType.isValid(t))return!1;return!0}}class q extends h{constructor(e){super(),this._childType=e}read(e){if(j.read(e))return this._childType.read(e)}write(e,t){const r=null!=e;j.write(r,t),r&&this._childType.write(e,t)}isValid(e){return null==e||this._childType.isValid(e)}}class K extends h{static read(){}static write(e){if(void 0!==e)throw new n("trying to write value to a void slot")}static isValid(e){return void 0===e}}class H extends h{constructor(e,t){super(),this.name=e,this.value=t}static read(e){const t=k.read(e),r=this._byValue[t];if(void 0===r)throw new o(`unknown ${this.enumName} member for value ${t}`);return r}static write(e,t){if(!this.isValid(e))throw new n(`${e} has enum name ${e?.enumName}, not ${this.enumName}: ${JSON.stringify(e)}`);k.write(e.value,t)}static isValid(e){return e?.constructor?.enumName===this.enumName||b(e,this)}static members(){return this._members}static values(){return Object.values(this._members)}static fromName(e){const t=this._members[e];if(!t)throw new TypeError(`${e} is not a member of ${this.enumName}`);return t}static fromValue(e){const t=this._byValue[e];if(void 0===t)throw new TypeError(`${e} is not a value of any member of ${this.enumName}`);return t}static create(e,t,r){const n=class extends H{};n.enumName=t,e.results[t]=n,n._members={},n._byValue={};for(const[e,t]of Object.entries(r)){const r=new n(e,t);n._members[e]=r,n._byValue[t]=r,n[e]=()=>r}return n}}class z extends h{resolve(){throw new i('"resolve" method should be implemented in the descendant class')}}class X extends y{constructor(e){super(),this._attributes=e||{}}static read(e){const t={};for(const[r,n]of this._fields)t[r]=n.read(e);return new this(t)}static write(e,t){if(!this.isValid(e))throw new n(`${e} has struct name ${e?.constructor?.structName}, not ${this.structName}: ${JSON.stringify(e)}`);for(const[r,n]of this._fields){const o=e._attributes[r];n.write(o,t)}}static isValid(e){return e?.constructor?.structName===this.structName||b(e,this)}static create(e,t,r){const n=class extends X{};n.structName=t,e.results[t]=n;const o=new Array(r.length);for(let t=0;t{"use strict";t.byteLength=function(e){var t=u(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,i=u(e),a=i[0],s=i[1],c=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,s)),l=0,f=s>0?a-4:a;for(r=0;r>16&255,c[l++]=t>>8&255,c[l++]=255&t;return 2===s&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,c[l++]=255&t),1===s&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t),c},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],a=16383,u=0,c=n-o;uc?c:u+a));return 1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),i.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)r[a]=i[a],n[i.charCodeAt(a)]=a;function u(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function s(e,t,n){for(var o,i,a=[],u=t;u>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return a.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287:(e,t,r)=>{"use strict";const n=r(526),o=r(251),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=s,t.IS=50;const a=2147483647;function u(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return f(e)}return c(e,t,r)}function c(e,t,r){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|y(e,t);let n=u(r);const o=n.write(e,t);return o!==r&&(n=n.slice(0,o)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(Q(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return p(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Q(e,ArrayBuffer)||e&&Q(e.buffer,ArrayBuffer))return d(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(Q(e,SharedArrayBuffer)||e&&Q(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return s.from(n,t,r);const o=function(e){if(s.isBuffer(e)){const t=0|h(e.length),r=u(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||W(e.length)?u(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function f(e){return l(e),u(e<0?0:0|h(e))}function p(e){const t=e.length<0?0:0|h(e.length),r=u(t);for(let n=0;n=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function y(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Q(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return X(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(o)return n?-1:X(e).length;t=(""+t).toLowerCase(),o=!0}}function m(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return I(this,t,r);case"utf8":case"utf-8":return O(this,t,r);case"ascii":return A(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return T(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function v(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function g(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),W(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=s.from(t,n)),s.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,o){let i,a=1,u=e.length,s=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,u/=2,s/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){let n=-1;for(i=r;iu&&(r=u-s),i=r;i>=0;i--){let r=!0;for(let n=0;no&&(n=o):n=o;const i=t.length;let a;for(n>i/2&&(n=i/2),a=0;a>8,o=r%256,i.push(o),i.push(n);return i}(t,e.length-r),e,r,n)}function T(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function O(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o239?4:t>223?3:t>191?2:1;if(o+a<=r){let r,n,u,s;switch(a){case 1:t<128&&(i=t);break;case 2:r=e[o+1],128==(192&r)&&(s=(31&t)<<6|63&r,s>127&&(i=s));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(s=(15&t)<<12|(63&r)<<6|63&n,s>2047&&(s<55296||s>57343)&&(i=s));break;case 4:r=e[o+1],n=e[o+2],u=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&u)&&(s=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&u,s>65535&&s<1114112&&(i=s))}}null===i?(i=65533,a=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),o+=a}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},s.byteLength=y,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(e+=" ... "),""},i&&(s.prototype[i]=s.prototype.inspect),s.prototype.compare=function(e,t,r,n,o){if(Q(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let i=(o>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0);const u=Math.min(i,a),c=this.slice(n,o),l=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let i=!1;for(;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":case"latin1":case"binary":return k(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function A(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;on)&&(r=n);let o="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function j(e,t,r,n,o,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function B(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function L(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r+7]=i,i>>=8,e[r+6]=i,i>>=8,e[r+5]=i,i>>=8,e[r+4]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function N(e,t,r,n,o,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function M(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,8),o.write(e,t,r,n,52,8),r+8}s.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e+--t],o=1;for(;t>0&&(o*=256);)n+=this[e+--t]*o;return n},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(o)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i=o&&(n-=Math.pow(2,8*t)),n},s.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=t,o=1,i=this[e+--n];for(;n>0&&(o*=256);)i+=this[e+--n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||C(e,4,this.length),o.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||C(e,4,this.length),o.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||C(e,8,this.length),o.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||C(e,8,this.length),o.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||j(this,e,t,r,Math.pow(2,8*r)-1,0);let o=1,i=0;for(this[t]=255&e;++i>>=0,r>>>=0,n||j(this,e,t,r,Math.pow(2,8*r)-1,0);let o=r-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+r},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigUInt64LE=J((function(e,t=0){return B(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),s.prototype.writeBigUInt64BE=J((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),s.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);j(this,e,t,r,n-1,-n)}let o=0,i=1,a=0;for(this[t]=255&e;++o>>=0,!n){const n=Math.pow(2,8*r-1);j(this,e,t,r,n-1,-n)}let o=r-1,i=1,a=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/i|0)-a&255;return t+r},s.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigInt64LE=J((function(e,t=0){return B(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),s.prototype.writeBigInt64BE=J((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),s.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},s.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},s.prototype.writeDoubleLE=function(e,t,r){return M(this,e,t,!0,r)},s.prototype.writeDoubleBE=function(e,t,r){return M(this,e,t,!1,r)},s.prototype.copy=function(e,t,r,n){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function q(e,t,r,n,o,i){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new F.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){K(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||H(t,e.length-(r+1))}(n,o,i)}function K(e,t){if("number"!=typeof e)throw new F.ERR_INVALID_ARG_TYPE(t,"number",e)}function H(e,t,r){if(Math.floor(e)!==e)throw K(e,r),new F.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new F.ERR_BUFFER_OUT_OF_BOUNDS;throw new F.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}D("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),D("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),D("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=V(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=V(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const z=/[^+/0-9A-Za-z-_]/g;function X(e,t){let r;t=t||1/0;const n=e.length;let o=null;const i=[];for(let a=0;a55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function G(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function $(e,t,r,n){let o;for(o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function Q(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function W(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let o=0;o<16;++o)t[n+o]=e[r]+e[o]}return t}();function J(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},251:(e,t)=>{t.read=function(e,t,r,n,o){var i,a,u=8*o-n-1,s=(1<>1,l=-7,f=r?o-1:0,p=r?-1:1,d=e[t+f];for(f+=p,i=d&(1<<-l)-1,d>>=-l,l+=u;l>0;i=256*i+e[t+f],f+=p,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=p,l-=8);if(0===i)i=1-c;else{if(i===s)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),i-=c}return(d?-1:1)*a*Math.pow(2,i-n)},t.write=function(e,t,r,n,o,i){var a,u,s,c=8*i-o-1,l=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,h=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(u=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(s=Math.pow(2,-a))<1&&(a--,s*=2),(t+=a+f>=1?p/s:p*Math.pow(2,1-f))*s>=2&&(a++,s/=2),a+f>=l?(u=0,a=l):a+f>=1?(u=(t*s-1)*Math.pow(2,o),a+=f):(u=t*Math.pow(2,f-1)*Math.pow(2,o),a=0));o>=8;e[r+d]=255&u,d+=h,u/=256,o-=8);for(a=a<0;e[r+d]=255&a,d+=h,a/=256,c-=8);e[r+d-h]|=128*y}}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}return r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r(281)})(),e.exports=t()},2135:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Account=void 0;var n,o=(n=r(1242))&&n.__esModule?n:{default:n},i=r(7120);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function u(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Address=void 0;var n,o=r(7120),i=(n=r(1918))&&n.__esModule?n:{default:n};function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function u(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;var o,i=r(645),a=(o=r(1918))&&o.__esModule?o:{default:o},u=r(6691),s=r(7120),c=r(9152);function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:a.default.Asset;if(this.isNative())return r.assetTypeNative();this.code.length<=4?(e=a.default.AlphaNum4,t="assetTypeCreditAlphanum4"):(e=a.default.AlphaNum12,t="assetTypeCreditAlphanum12");var n=this.code.length<=4?4:12;return new r(t,new e({assetCode:this.code.padEnd(n,"\0"),issuer:u.Keypair.fromPublicKey(this.issuer).xdrAccountId()}))}},{key:"getCode",value:function(){if(void 0!==this.code)return String(this.code)}},{key:"getIssuer",value:function(){if(void 0!==this.issuer)return String(this.issuer)}},{key:"getAssetType",value:function(){switch(this.getRawAssetType().value){case a.default.AssetType.assetTypeNative().value:return"native";case a.default.AssetType.assetTypeCreditAlphanum4().value:return"credit_alphanum4";case a.default.AssetType.assetTypeCreditAlphanum12().value:return"credit_alphanum12";default:return"unknown"}}},{key:"getRawAssetType",value:function(){return this.isNative()?a.default.AssetType.assetTypeNative():this.code.length<=4?a.default.AssetType.assetTypeCreditAlphanum4():a.default.AssetType.assetTypeCreditAlphanum12()}},{key:"isNative",value:function(){return!this.issuer}},{key:"equals",value:function(e){return this.code===e.getCode()&&this.issuer===e.getIssuer()}},{key:"toString",value:function(){return this.isNative()?"native":"".concat(this.getCode(),":").concat(this.getIssuer())}}],[{key:"native",value:function(){return new e("XLM")}},{key:"fromOperation",value:function(e){var t,r;switch(e.switch()){case a.default.AssetType.assetTypeNative():return this.native();case a.default.AssetType.assetTypeCreditAlphanum4():t=e.alphaNum4();case a.default.AssetType.assetTypeCreditAlphanum12():return t=t||e.alphaNum12(),r=s.StrKey.encodeEd25519PublicKey(t.issuer().ed25519()),new this((0,i.trimEnd)(t.assetCode(),"\0"),r);default:throw new Error("Invalid asset type: ".concat(e.switch().name))}}},{key:"compare",value:function(t,r){if(!(t&&t instanceof e))throw new Error("assetA is invalid");if(!(r&&r instanceof e))throw new Error("assetB is invalid");if(t.equals(r))return 0;var n=t.getRawAssetType().value,o=r.getRawAssetType().value;if(n!==o)return n{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.authorizeEntry=y,t.authorizeInvocation=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:s.Networks.FUTURENET,u=a.Keypair.random().rawPublicKey(),c=new i.default.Int64((p=u,p.subarray(0,8).reduce((function(e,t){return e<<8|t}),0))),f=n||e.publicKey();var p;if(!f)throw new Error("authorizeInvocation requires publicKey parameter");return y(new i.default.SorobanAuthorizationEntry({rootInvocation:r,credentials:i.default.SorobanCredentials.sorobanCredentialsAddress(new i.default.SorobanAddressCredentials({address:new l.Address(f).toScAddress(),nonce:c,signatureExpirationLedger:0,signature:i.default.ScVal.scvVec([])}))}),e,t,o)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(6691),u=r(7120),s=r(6202),c=r(9152),l=r(1180),f=r(7177);function p(e){return p="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},p(e)}function d(){d=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",s=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof b?t:b,a=Object.create(i.prototype),u=new C(n||[]);return o(a,"_invoke",{value:A(e,r,u)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var h="suspendedStart",y="suspendedYield",m="executing",v="completed",g={};function b(){}function w(){}function S(){}var k={};c(k,a,(function(){return this}));var E=Object.getPrototypeOf,_=E&&E(E(j([])));_&&_!==r&&n.call(_,a)&&(k=_);var T=S.prototype=b.prototype=Object.create(k);function O(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function x(e,t){function r(o,i,a,u){var s=f(e[o],e,i);if("throw"!==s.type){var c=s.arg,l=c.value;return l&&"object"==p(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,u)}),(function(e){r("throw",e,a,u)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,u)}))}u(s.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function A(t,r,n){var o=h;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var u=n.delegate;if(u){var s=P(u,n);if(s){if(s===g)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=m;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?v:y,c.arg===g)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=v,n.method="throw",n.arg=c.arg)}}}function P(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,P(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function I(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function R(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(I,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),R(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;R(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function h(e,t,r,n,o,i,a){try{var u=e[i](a),s=u.value}catch(e){return void r(e)}u.done?t(s):Promise.resolve(s).then(n,o)}function y(e,t,r){return m.apply(this,arguments)}function m(){var e;return e=d().mark((function e(t,r,o){var p,h,y,m,v,g,b,w,S,k=arguments;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(p=k.length>3&&void 0!==k[3]?k[3]:s.Networks.FUTURENET,t.credentials().switch().value===i.default.SorobanCredentialsType.sorobanCredentialsAddress().value){e.next=3;break}return e.abrupt("return",t);case 3:if(h=i.default.SorobanAuthorizationEntry.fromXDR(t.toXDR()),(y=h.credentials().address()).signatureExpirationLedger(o),m=(0,c.hash)(n.from(p)),v=i.default.HashIdPreimage.envelopeTypeSorobanAuthorization(new i.default.HashIdPreimageSorobanAuthorization({networkId:m,nonce:y.nonce(),invocation:h.rootInvocation(),signatureExpirationLedger:y.signatureExpirationLedger()})),g=(0,c.hash)(v.toXDR()),"function"!=typeof r){e.next=18;break}return e.t0=n,e.next=13,r(v);case 13:e.t1=e.sent,b=e.t0.from.call(e.t0,e.t1),w=l.Address.fromScAddress(y.address()).toString(),e.next=20;break;case 18:b=n.from(r.sign(g)),w=r.publicKey();case 20:if(a.Keypair.fromPublicKey(w).verify(g,b)){e.next=22;break}throw new Error("signature doesn't match payload");case 22:return S=(0,f.nativeToScVal)({public_key:u.StrKey.decodeEd25519PublicKey(w),signature:b},{type:{public_key:["symbol",null],signature:["symbol",null]}}),y.signature(i.default.ScVal.scvVec([S])),e.abrupt("return",h);case 25:case"end":return e.stop()}}),e)})),m=function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){h(i,n,o,a,u,"next",e)}function u(e){h(i,n,o,a,u,"throw",e)}a(void 0)}))},m.apply(this,arguments)}},1387:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Claimant=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691),a=r(7120);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function s(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Contract=void 0;var n,o=r(1180),i=r(7237),a=(n=r(1918))&&n.__esModule?n:{default:n},u=r(7120);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function c(e,t){for(var r=0;r1?t-1:0),n=1;n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.humanizeEvents=function(e){return e.map((function(e){return e.inSuccessfulContractCall?c(e.event()):c(e)}))};var n=r(7120),o=r(7177);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function u(e){for(var t=1;t{"use strict";var n=r(8287).Buffer;function o(e){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.FeeBumpTransaction=void 0;var i,a=(i=r(1918))&&i.__esModule?i:{default:i},u=r(9152),s=r(380),c=r(3758),l=r(6160);function f(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(o=function(e){return e?r:t})(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=n(e)&&"function"!=typeof e)return{default:e};var r=o(t);if(r&&r.has(e))return r.get(e);var i={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&{}.hasOwnProperty.call(e,u)){var s=a?Object.getOwnPropertyDescriptor(e,u):null;s&&(s.get||s.set)?Object.defineProperty(i,u,s):i[u]=e[u]}return i.default=e,r&&r.set(e,i),i}(r(3740)).config((function(e){var t=1024;e.typedef("Value",e.varOpaque()),e.struct("ScpBallot",[["counter",e.lookup("Uint32")],["value",e.lookup("Value")]]),e.enum("ScpStatementType",{scpStPrepare:0,scpStConfirm:1,scpStExternalize:2,scpStNominate:3}),e.struct("ScpNomination",[["quorumSetHash",e.lookup("Hash")],["votes",e.varArray(e.lookup("Value"),2147483647)],["accepted",e.varArray(e.lookup("Value"),2147483647)]]),e.struct("ScpStatementPrepare",[["quorumSetHash",e.lookup("Hash")],["ballot",e.lookup("ScpBallot")],["prepared",e.option(e.lookup("ScpBallot"))],["preparedPrime",e.option(e.lookup("ScpBallot"))],["nC",e.lookup("Uint32")],["nH",e.lookup("Uint32")]]),e.struct("ScpStatementConfirm",[["ballot",e.lookup("ScpBallot")],["nPrepared",e.lookup("Uint32")],["nCommit",e.lookup("Uint32")],["nH",e.lookup("Uint32")],["quorumSetHash",e.lookup("Hash")]]),e.struct("ScpStatementExternalize",[["commit",e.lookup("ScpBallot")],["nH",e.lookup("Uint32")],["commitQuorumSetHash",e.lookup("Hash")]]),e.union("ScpStatementPledges",{switchOn:e.lookup("ScpStatementType"),switchName:"type",switches:[["scpStPrepare","prepare"],["scpStConfirm","confirm"],["scpStExternalize","externalize"],["scpStNominate","nominate"]],arms:{prepare:e.lookup("ScpStatementPrepare"),confirm:e.lookup("ScpStatementConfirm"),externalize:e.lookup("ScpStatementExternalize"),nominate:e.lookup("ScpNomination")}}),e.struct("ScpStatement",[["nodeId",e.lookup("NodeId")],["slotIndex",e.lookup("Uint64")],["pledges",e.lookup("ScpStatementPledges")]]),e.struct("ScpEnvelope",[["statement",e.lookup("ScpStatement")],["signature",e.lookup("Signature")]]),e.struct("ScpQuorumSet",[["threshold",e.lookup("Uint32")],["validators",e.varArray(e.lookup("NodeId"),2147483647)],["innerSets",e.varArray(e.lookup("ScpQuorumSet"),2147483647)]]),e.typedef("Thresholds",e.opaque(4)),e.typedef("String32",e.string(32)),e.typedef("String64",e.string(64)),e.typedef("SequenceNumber",e.lookup("Int64")),e.typedef("DataValue",e.varOpaque(64)),e.typedef("PoolId",e.lookup("Hash")),e.typedef("AssetCode4",e.opaque(4)),e.typedef("AssetCode12",e.opaque(12)),e.enum("AssetType",{assetTypeNative:0,assetTypeCreditAlphanum4:1,assetTypeCreditAlphanum12:2,assetTypePoolShare:3}),e.union("AssetCode",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeCreditAlphanum4","assetCode4"],["assetTypeCreditAlphanum12","assetCode12"]],arms:{assetCode4:e.lookup("AssetCode4"),assetCode12:e.lookup("AssetCode12")}}),e.struct("AlphaNum4",[["assetCode",e.lookup("AssetCode4")],["issuer",e.lookup("AccountId")]]),e.struct("AlphaNum12",[["assetCode",e.lookup("AssetCode12")],["issuer",e.lookup("AccountId")]]),e.union("Asset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12")}}),e.struct("Price",[["n",e.lookup("Int32")],["d",e.lookup("Int32")]]),e.struct("Liabilities",[["buying",e.lookup("Int64")],["selling",e.lookup("Int64")]]),e.enum("ThresholdIndices",{thresholdMasterWeight:0,thresholdLow:1,thresholdMed:2,thresholdHigh:3}),e.enum("LedgerEntryType",{account:0,trustline:1,offer:2,data:3,claimableBalance:4,liquidityPool:5,contractData:6,contractCode:7,configSetting:8,ttl:9}),e.struct("Signer",[["key",e.lookup("SignerKey")],["weight",e.lookup("Uint32")]]),e.enum("AccountFlags",{authRequiredFlag:1,authRevocableFlag:2,authImmutableFlag:4,authClawbackEnabledFlag:8}),e.const("MASK_ACCOUNT_FLAGS",7),e.const("MASK_ACCOUNT_FLAGS_V17",15),e.const("MAX_SIGNERS",20),e.typedef("SponsorshipDescriptor",e.option(e.lookup("AccountId"))),e.struct("AccountEntryExtensionV3",[["ext",e.lookup("ExtensionPoint")],["seqLedger",e.lookup("Uint32")],["seqTime",e.lookup("TimePoint")]]),e.union("AccountEntryExtensionV2Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[3,"v3"]],arms:{v3:e.lookup("AccountEntryExtensionV3")}}),e.struct("AccountEntryExtensionV2",[["numSponsored",e.lookup("Uint32")],["numSponsoring",e.lookup("Uint32")],["signerSponsoringIDs",e.varArray(e.lookup("SponsorshipDescriptor"),e.lookup("MAX_SIGNERS"))],["ext",e.lookup("AccountEntryExtensionV2Ext")]]),e.union("AccountEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[2,"v2"]],arms:{v2:e.lookup("AccountEntryExtensionV2")}}),e.struct("AccountEntryExtensionV1",[["liabilities",e.lookup("Liabilities")],["ext",e.lookup("AccountEntryExtensionV1Ext")]]),e.union("AccountEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("AccountEntryExtensionV1")}}),e.struct("AccountEntry",[["accountId",e.lookup("AccountId")],["balance",e.lookup("Int64")],["seqNum",e.lookup("SequenceNumber")],["numSubEntries",e.lookup("Uint32")],["inflationDest",e.option(e.lookup("AccountId"))],["flags",e.lookup("Uint32")],["homeDomain",e.lookup("String32")],["thresholds",e.lookup("Thresholds")],["signers",e.varArray(e.lookup("Signer"),e.lookup("MAX_SIGNERS"))],["ext",e.lookup("AccountEntryExt")]]),e.enum("TrustLineFlags",{authorizedFlag:1,authorizedToMaintainLiabilitiesFlag:2,trustlineClawbackEnabledFlag:4}),e.const("MASK_TRUSTLINE_FLAGS",1),e.const("MASK_TRUSTLINE_FLAGS_V13",3),e.const("MASK_TRUSTLINE_FLAGS_V17",7),e.enum("LiquidityPoolType",{liquidityPoolConstantProduct:0}),e.union("TrustLineAsset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"],["assetTypePoolShare","liquidityPoolId"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12"),liquidityPoolId:e.lookup("PoolId")}}),e.union("TrustLineEntryExtensionV2Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TrustLineEntryExtensionV2",[["liquidityPoolUseCount",e.lookup("Int32")],["ext",e.lookup("TrustLineEntryExtensionV2Ext")]]),e.union("TrustLineEntryV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[2,"v2"]],arms:{v2:e.lookup("TrustLineEntryExtensionV2")}}),e.struct("TrustLineEntryV1",[["liabilities",e.lookup("Liabilities")],["ext",e.lookup("TrustLineEntryV1Ext")]]),e.union("TrustLineEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("TrustLineEntryV1")}}),e.struct("TrustLineEntry",[["accountId",e.lookup("AccountId")],["asset",e.lookup("TrustLineAsset")],["balance",e.lookup("Int64")],["limit",e.lookup("Int64")],["flags",e.lookup("Uint32")],["ext",e.lookup("TrustLineEntryExt")]]),e.enum("OfferEntryFlags",{passiveFlag:1}),e.const("MASK_OFFERENTRY_FLAGS",1),e.union("OfferEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("OfferEntry",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")],["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")],["flags",e.lookup("Uint32")],["ext",e.lookup("OfferEntryExt")]]),e.union("DataEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("DataEntry",[["accountId",e.lookup("AccountId")],["dataName",e.lookup("String64")],["dataValue",e.lookup("DataValue")],["ext",e.lookup("DataEntryExt")]]),e.enum("ClaimPredicateType",{claimPredicateUnconditional:0,claimPredicateAnd:1,claimPredicateOr:2,claimPredicateNot:3,claimPredicateBeforeAbsoluteTime:4,claimPredicateBeforeRelativeTime:5}),e.union("ClaimPredicate",{switchOn:e.lookup("ClaimPredicateType"),switchName:"type",switches:[["claimPredicateUnconditional",e.void()],["claimPredicateAnd","andPredicates"],["claimPredicateOr","orPredicates"],["claimPredicateNot","notPredicate"],["claimPredicateBeforeAbsoluteTime","absBefore"],["claimPredicateBeforeRelativeTime","relBefore"]],arms:{andPredicates:e.varArray(e.lookup("ClaimPredicate"),2),orPredicates:e.varArray(e.lookup("ClaimPredicate"),2),notPredicate:e.option(e.lookup("ClaimPredicate")),absBefore:e.lookup("Int64"),relBefore:e.lookup("Int64")}}),e.enum("ClaimantType",{claimantTypeV0:0}),e.struct("ClaimantV0",[["destination",e.lookup("AccountId")],["predicate",e.lookup("ClaimPredicate")]]),e.union("Claimant",{switchOn:e.lookup("ClaimantType"),switchName:"type",switches:[["claimantTypeV0","v0"]],arms:{v0:e.lookup("ClaimantV0")}}),e.enum("ClaimableBalanceIdType",{claimableBalanceIdTypeV0:0}),e.union("ClaimableBalanceId",{switchOn:e.lookup("ClaimableBalanceIdType"),switchName:"type",switches:[["claimableBalanceIdTypeV0","v0"]],arms:{v0:e.lookup("Hash")}}),e.enum("ClaimableBalanceFlags",{claimableBalanceClawbackEnabledFlag:1}),e.const("MASK_CLAIMABLE_BALANCE_FLAGS",1),e.union("ClaimableBalanceEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("ClaimableBalanceEntryExtensionV1",[["ext",e.lookup("ClaimableBalanceEntryExtensionV1Ext")],["flags",e.lookup("Uint32")]]),e.union("ClaimableBalanceEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("ClaimableBalanceEntryExtensionV1")}}),e.struct("ClaimableBalanceEntry",[["balanceId",e.lookup("ClaimableBalanceId")],["claimants",e.varArray(e.lookup("Claimant"),10)],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")],["ext",e.lookup("ClaimableBalanceEntryExt")]]),e.struct("LiquidityPoolConstantProductParameters",[["assetA",e.lookup("Asset")],["assetB",e.lookup("Asset")],["fee",e.lookup("Int32")]]),e.struct("LiquidityPoolEntryConstantProduct",[["params",e.lookup("LiquidityPoolConstantProductParameters")],["reserveA",e.lookup("Int64")],["reserveB",e.lookup("Int64")],["totalPoolShares",e.lookup("Int64")],["poolSharesTrustLineCount",e.lookup("Int64")]]),e.union("LiquidityPoolEntryBody",{switchOn:e.lookup("LiquidityPoolType"),switchName:"type",switches:[["liquidityPoolConstantProduct","constantProduct"]],arms:{constantProduct:e.lookup("LiquidityPoolEntryConstantProduct")}}),e.struct("LiquidityPoolEntry",[["liquidityPoolId",e.lookup("PoolId")],["body",e.lookup("LiquidityPoolEntryBody")]]),e.enum("ContractDataDurability",{temporary:0,persistent:1}),e.struct("ContractDataEntry",[["ext",e.lookup("ExtensionPoint")],["contract",e.lookup("ScAddress")],["key",e.lookup("ScVal")],["durability",e.lookup("ContractDataDurability")],["val",e.lookup("ScVal")]]),e.struct("ContractCodeCostInputs",[["ext",e.lookup("ExtensionPoint")],["nInstructions",e.lookup("Uint32")],["nFunctions",e.lookup("Uint32")],["nGlobals",e.lookup("Uint32")],["nTableEntries",e.lookup("Uint32")],["nTypes",e.lookup("Uint32")],["nDataSegments",e.lookup("Uint32")],["nElemSegments",e.lookup("Uint32")],["nImports",e.lookup("Uint32")],["nExports",e.lookup("Uint32")],["nDataSegmentBytes",e.lookup("Uint32")]]),e.struct("ContractCodeEntryV1",[["ext",e.lookup("ExtensionPoint")],["costInputs",e.lookup("ContractCodeCostInputs")]]),e.union("ContractCodeEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("ContractCodeEntryV1")}}),e.struct("ContractCodeEntry",[["ext",e.lookup("ContractCodeEntryExt")],["hash",e.lookup("Hash")],["code",e.varOpaque()]]),e.struct("TtlEntry",[["keyHash",e.lookup("Hash")],["liveUntilLedgerSeq",e.lookup("Uint32")]]),e.union("LedgerEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerEntryExtensionV1",[["sponsoringId",e.lookup("SponsorshipDescriptor")],["ext",e.lookup("LedgerEntryExtensionV1Ext")]]),e.union("LedgerEntryData",{switchOn:e.lookup("LedgerEntryType"),switchName:"type",switches:[["account","account"],["trustline","trustLine"],["offer","offer"],["data","data"],["claimableBalance","claimableBalance"],["liquidityPool","liquidityPool"],["contractData","contractData"],["contractCode","contractCode"],["configSetting","configSetting"],["ttl","ttl"]],arms:{account:e.lookup("AccountEntry"),trustLine:e.lookup("TrustLineEntry"),offer:e.lookup("OfferEntry"),data:e.lookup("DataEntry"),claimableBalance:e.lookup("ClaimableBalanceEntry"),liquidityPool:e.lookup("LiquidityPoolEntry"),contractData:e.lookup("ContractDataEntry"),contractCode:e.lookup("ContractCodeEntry"),configSetting:e.lookup("ConfigSettingEntry"),ttl:e.lookup("TtlEntry")}}),e.union("LedgerEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerEntryExtensionV1")}}),e.struct("LedgerEntry",[["lastModifiedLedgerSeq",e.lookup("Uint32")],["data",e.lookup("LedgerEntryData")],["ext",e.lookup("LedgerEntryExt")]]),e.struct("LedgerKeyAccount",[["accountId",e.lookup("AccountId")]]),e.struct("LedgerKeyTrustLine",[["accountId",e.lookup("AccountId")],["asset",e.lookup("TrustLineAsset")]]),e.struct("LedgerKeyOffer",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")]]),e.struct("LedgerKeyData",[["accountId",e.lookup("AccountId")],["dataName",e.lookup("String64")]]),e.struct("LedgerKeyClaimableBalance",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("LedgerKeyLiquidityPool",[["liquidityPoolId",e.lookup("PoolId")]]),e.struct("LedgerKeyContractData",[["contract",e.lookup("ScAddress")],["key",e.lookup("ScVal")],["durability",e.lookup("ContractDataDurability")]]),e.struct("LedgerKeyContractCode",[["hash",e.lookup("Hash")]]),e.struct("LedgerKeyConfigSetting",[["configSettingId",e.lookup("ConfigSettingId")]]),e.struct("LedgerKeyTtl",[["keyHash",e.lookup("Hash")]]),e.union("LedgerKey",{switchOn:e.lookup("LedgerEntryType"),switchName:"type",switches:[["account","account"],["trustline","trustLine"],["offer","offer"],["data","data"],["claimableBalance","claimableBalance"],["liquidityPool","liquidityPool"],["contractData","contractData"],["contractCode","contractCode"],["configSetting","configSetting"],["ttl","ttl"]],arms:{account:e.lookup("LedgerKeyAccount"),trustLine:e.lookup("LedgerKeyTrustLine"),offer:e.lookup("LedgerKeyOffer"),data:e.lookup("LedgerKeyData"),claimableBalance:e.lookup("LedgerKeyClaimableBalance"),liquidityPool:e.lookup("LedgerKeyLiquidityPool"),contractData:e.lookup("LedgerKeyContractData"),contractCode:e.lookup("LedgerKeyContractCode"),configSetting:e.lookup("LedgerKeyConfigSetting"),ttl:e.lookup("LedgerKeyTtl")}}),e.enum("EnvelopeType",{envelopeTypeTxV0:0,envelopeTypeScp:1,envelopeTypeTx:2,envelopeTypeAuth:3,envelopeTypeScpvalue:4,envelopeTypeTxFeeBump:5,envelopeTypeOpId:6,envelopeTypePoolRevokeOpId:7,envelopeTypeContractId:8,envelopeTypeSorobanAuthorization:9}),e.enum("BucketListType",{live:0,hotArchive:1,coldArchive:2}),e.enum("BucketEntryType",{metaentry:-1,liveentry:0,deadentry:1,initentry:2}),e.enum("HotArchiveBucketEntryType",{hotArchiveMetaentry:-1,hotArchiveArchived:0,hotArchiveLive:1,hotArchiveDeleted:2}),e.enum("ColdArchiveBucketEntryType",{coldArchiveMetaentry:-1,coldArchiveArchivedLeaf:0,coldArchiveDeletedLeaf:1,coldArchiveBoundaryLeaf:2,coldArchiveHash:3}),e.union("BucketMetadataExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"bucketListType"]],arms:{bucketListType:e.lookup("BucketListType")}}),e.struct("BucketMetadata",[["ledgerVersion",e.lookup("Uint32")],["ext",e.lookup("BucketMetadataExt")]]),e.union("BucketEntry",{switchOn:e.lookup("BucketEntryType"),switchName:"type",switches:[["liveentry","liveEntry"],["initentry","liveEntry"],["deadentry","deadEntry"],["metaentry","metaEntry"]],arms:{liveEntry:e.lookup("LedgerEntry"),deadEntry:e.lookup("LedgerKey"),metaEntry:e.lookup("BucketMetadata")}}),e.union("HotArchiveBucketEntry",{switchOn:e.lookup("HotArchiveBucketEntryType"),switchName:"type",switches:[["hotArchiveArchived","archivedEntry"],["hotArchiveLive","key"],["hotArchiveDeleted","key"],["hotArchiveMetaentry","metaEntry"]],arms:{archivedEntry:e.lookup("LedgerEntry"),key:e.lookup("LedgerKey"),metaEntry:e.lookup("BucketMetadata")}}),e.struct("ColdArchiveArchivedLeaf",[["index",e.lookup("Uint32")],["archivedEntry",e.lookup("LedgerEntry")]]),e.struct("ColdArchiveDeletedLeaf",[["index",e.lookup("Uint32")],["deletedKey",e.lookup("LedgerKey")]]),e.struct("ColdArchiveBoundaryLeaf",[["index",e.lookup("Uint32")],["isLowerBound",e.bool()]]),e.struct("ColdArchiveHashEntry",[["index",e.lookup("Uint32")],["level",e.lookup("Uint32")],["hash",e.lookup("Hash")]]),e.union("ColdArchiveBucketEntry",{switchOn:e.lookup("ColdArchiveBucketEntryType"),switchName:"type",switches:[["coldArchiveMetaentry","metaEntry"],["coldArchiveArchivedLeaf","archivedLeaf"],["coldArchiveDeletedLeaf","deletedLeaf"],["coldArchiveBoundaryLeaf","boundaryLeaf"],["coldArchiveHash","hashEntry"]],arms:{metaEntry:e.lookup("BucketMetadata"),archivedLeaf:e.lookup("ColdArchiveArchivedLeaf"),deletedLeaf:e.lookup("ColdArchiveDeletedLeaf"),boundaryLeaf:e.lookup("ColdArchiveBoundaryLeaf"),hashEntry:e.lookup("ColdArchiveHashEntry")}}),e.typedef("UpgradeType",e.varOpaque(128)),e.enum("StellarValueType",{stellarValueBasic:0,stellarValueSigned:1}),e.struct("LedgerCloseValueSignature",[["nodeId",e.lookup("NodeId")],["signature",e.lookup("Signature")]]),e.union("StellarValueExt",{switchOn:e.lookup("StellarValueType"),switchName:"v",switches:[["stellarValueBasic",e.void()],["stellarValueSigned","lcValueSignature"]],arms:{lcValueSignature:e.lookup("LedgerCloseValueSignature")}}),e.struct("StellarValue",[["txSetHash",e.lookup("Hash")],["closeTime",e.lookup("TimePoint")],["upgrades",e.varArray(e.lookup("UpgradeType"),6)],["ext",e.lookup("StellarValueExt")]]),e.const("MASK_LEDGER_HEADER_FLAGS",7),e.enum("LedgerHeaderFlags",{disableLiquidityPoolTradingFlag:1,disableLiquidityPoolDepositFlag:2,disableLiquidityPoolWithdrawalFlag:4}),e.union("LedgerHeaderExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerHeaderExtensionV1",[["flags",e.lookup("Uint32")],["ext",e.lookup("LedgerHeaderExtensionV1Ext")]]),e.union("LedgerHeaderExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerHeaderExtensionV1")}}),e.struct("LedgerHeader",[["ledgerVersion",e.lookup("Uint32")],["previousLedgerHash",e.lookup("Hash")],["scpValue",e.lookup("StellarValue")],["txSetResultHash",e.lookup("Hash")],["bucketListHash",e.lookup("Hash")],["ledgerSeq",e.lookup("Uint32")],["totalCoins",e.lookup("Int64")],["feePool",e.lookup("Int64")],["inflationSeq",e.lookup("Uint32")],["idPool",e.lookup("Uint64")],["baseFee",e.lookup("Uint32")],["baseReserve",e.lookup("Uint32")],["maxTxSetSize",e.lookup("Uint32")],["skipList",e.array(e.lookup("Hash"),4)],["ext",e.lookup("LedgerHeaderExt")]]),e.enum("LedgerUpgradeType",{ledgerUpgradeVersion:1,ledgerUpgradeBaseFee:2,ledgerUpgradeMaxTxSetSize:3,ledgerUpgradeBaseReserve:4,ledgerUpgradeFlags:5,ledgerUpgradeConfig:6,ledgerUpgradeMaxSorobanTxSetSize:7}),e.struct("ConfigUpgradeSetKey",[["contractId",e.lookup("Hash")],["contentHash",e.lookup("Hash")]]),e.union("LedgerUpgrade",{switchOn:e.lookup("LedgerUpgradeType"),switchName:"type",switches:[["ledgerUpgradeVersion","newLedgerVersion"],["ledgerUpgradeBaseFee","newBaseFee"],["ledgerUpgradeMaxTxSetSize","newMaxTxSetSize"],["ledgerUpgradeBaseReserve","newBaseReserve"],["ledgerUpgradeFlags","newFlags"],["ledgerUpgradeConfig","newConfig"],["ledgerUpgradeMaxSorobanTxSetSize","newMaxSorobanTxSetSize"]],arms:{newLedgerVersion:e.lookup("Uint32"),newBaseFee:e.lookup("Uint32"),newMaxTxSetSize:e.lookup("Uint32"),newBaseReserve:e.lookup("Uint32"),newFlags:e.lookup("Uint32"),newConfig:e.lookup("ConfigUpgradeSetKey"),newMaxSorobanTxSetSize:e.lookup("Uint32")}}),e.struct("ConfigUpgradeSet",[["updatedEntry",e.varArray(e.lookup("ConfigSettingEntry"),2147483647)]]),e.enum("TxSetComponentType",{txsetCompTxsMaybeDiscountedFee:0}),e.struct("TxSetComponentTxsMaybeDiscountedFee",[["baseFee",e.option(e.lookup("Int64"))],["txes",e.varArray(e.lookup("TransactionEnvelope"),2147483647)]]),e.union("TxSetComponent",{switchOn:e.lookup("TxSetComponentType"),switchName:"type",switches:[["txsetCompTxsMaybeDiscountedFee","txsMaybeDiscountedFee"]],arms:{txsMaybeDiscountedFee:e.lookup("TxSetComponentTxsMaybeDiscountedFee")}}),e.union("TransactionPhase",{switchOn:e.int(),switchName:"v",switches:[[0,"v0Components"]],arms:{v0Components:e.varArray(e.lookup("TxSetComponent"),2147483647)}}),e.struct("TransactionSet",[["previousLedgerHash",e.lookup("Hash")],["txes",e.varArray(e.lookup("TransactionEnvelope"),2147483647)]]),e.struct("TransactionSetV1",[["previousLedgerHash",e.lookup("Hash")],["phases",e.varArray(e.lookup("TransactionPhase"),2147483647)]]),e.union("GeneralizedTransactionSet",{switchOn:e.int(),switchName:"v",switches:[[1,"v1TxSet"]],arms:{v1TxSet:e.lookup("TransactionSetV1")}}),e.struct("TransactionResultPair",[["transactionHash",e.lookup("Hash")],["result",e.lookup("TransactionResult")]]),e.struct("TransactionResultSet",[["results",e.varArray(e.lookup("TransactionResultPair"),2147483647)]]),e.union("TransactionHistoryEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"generalizedTxSet"]],arms:{generalizedTxSet:e.lookup("GeneralizedTransactionSet")}}),e.struct("TransactionHistoryEntry",[["ledgerSeq",e.lookup("Uint32")],["txSet",e.lookup("TransactionSet")],["ext",e.lookup("TransactionHistoryEntryExt")]]),e.union("TransactionHistoryResultEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionHistoryResultEntry",[["ledgerSeq",e.lookup("Uint32")],["txResultSet",e.lookup("TransactionResultSet")],["ext",e.lookup("TransactionHistoryResultEntryExt")]]),e.union("LedgerHeaderHistoryEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerHeaderHistoryEntry",[["hash",e.lookup("Hash")],["header",e.lookup("LedgerHeader")],["ext",e.lookup("LedgerHeaderHistoryEntryExt")]]),e.struct("LedgerScpMessages",[["ledgerSeq",e.lookup("Uint32")],["messages",e.varArray(e.lookup("ScpEnvelope"),2147483647)]]),e.struct("ScpHistoryEntryV0",[["quorumSets",e.varArray(e.lookup("ScpQuorumSet"),2147483647)],["ledgerMessages",e.lookup("LedgerScpMessages")]]),e.union("ScpHistoryEntry",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("ScpHistoryEntryV0")}}),e.enum("LedgerEntryChangeType",{ledgerEntryCreated:0,ledgerEntryUpdated:1,ledgerEntryRemoved:2,ledgerEntryState:3}),e.union("LedgerEntryChange",{switchOn:e.lookup("LedgerEntryChangeType"),switchName:"type",switches:[["ledgerEntryCreated","created"],["ledgerEntryUpdated","updated"],["ledgerEntryRemoved","removed"],["ledgerEntryState","state"]],arms:{created:e.lookup("LedgerEntry"),updated:e.lookup("LedgerEntry"),removed:e.lookup("LedgerKey"),state:e.lookup("LedgerEntry")}}),e.typedef("LedgerEntryChanges",e.varArray(e.lookup("LedgerEntryChange"),2147483647)),e.struct("OperationMeta",[["changes",e.lookup("LedgerEntryChanges")]]),e.struct("TransactionMetaV1",[["txChanges",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)]]),e.struct("TransactionMetaV2",[["txChangesBefore",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)],["txChangesAfter",e.lookup("LedgerEntryChanges")]]),e.enum("ContractEventType",{system:0,contract:1,diagnostic:2}),e.struct("ContractEventV0",[["topics",e.varArray(e.lookup("ScVal"),2147483647)],["data",e.lookup("ScVal")]]),e.union("ContractEventBody",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("ContractEventV0")}}),e.struct("ContractEvent",[["ext",e.lookup("ExtensionPoint")],["contractId",e.option(e.lookup("Hash"))],["type",e.lookup("ContractEventType")],["body",e.lookup("ContractEventBody")]]),e.struct("DiagnosticEvent",[["inSuccessfulContractCall",e.bool()],["event",e.lookup("ContractEvent")]]),e.typedef("DiagnosticEvents",e.varArray(e.lookup("DiagnosticEvent"),2147483647)),e.struct("SorobanTransactionMetaExtV1",[["ext",e.lookup("ExtensionPoint")],["totalNonRefundableResourceFeeCharged",e.lookup("Int64")],["totalRefundableResourceFeeCharged",e.lookup("Int64")],["rentFeeCharged",e.lookup("Int64")]]),e.union("SorobanTransactionMetaExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("SorobanTransactionMetaExtV1")}}),e.struct("SorobanTransactionMeta",[["ext",e.lookup("SorobanTransactionMetaExt")],["events",e.varArray(e.lookup("ContractEvent"),2147483647)],["returnValue",e.lookup("ScVal")],["diagnosticEvents",e.varArray(e.lookup("DiagnosticEvent"),2147483647)]]),e.struct("TransactionMetaV3",[["ext",e.lookup("ExtensionPoint")],["txChangesBefore",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)],["txChangesAfter",e.lookup("LedgerEntryChanges")],["sorobanMeta",e.option(e.lookup("SorobanTransactionMeta"))]]),e.struct("InvokeHostFunctionSuccessPreImage",[["returnValue",e.lookup("ScVal")],["events",e.varArray(e.lookup("ContractEvent"),2147483647)]]),e.union("TransactionMeta",{switchOn:e.int(),switchName:"v",switches:[[0,"operations"],[1,"v1"],[2,"v2"],[3,"v3"]],arms:{operations:e.varArray(e.lookup("OperationMeta"),2147483647),v1:e.lookup("TransactionMetaV1"),v2:e.lookup("TransactionMetaV2"),v3:e.lookup("TransactionMetaV3")}}),e.struct("TransactionResultMeta",[["result",e.lookup("TransactionResultPair")],["feeProcessing",e.lookup("LedgerEntryChanges")],["txApplyProcessing",e.lookup("TransactionMeta")]]),e.struct("UpgradeEntryMeta",[["upgrade",e.lookup("LedgerUpgrade")],["changes",e.lookup("LedgerEntryChanges")]]),e.struct("LedgerCloseMetaV0",[["ledgerHeader",e.lookup("LedgerHeaderHistoryEntry")],["txSet",e.lookup("TransactionSet")],["txProcessing",e.varArray(e.lookup("TransactionResultMeta"),2147483647)],["upgradesProcessing",e.varArray(e.lookup("UpgradeEntryMeta"),2147483647)],["scpInfo",e.varArray(e.lookup("ScpHistoryEntry"),2147483647)]]),e.struct("LedgerCloseMetaExtV1",[["ext",e.lookup("ExtensionPoint")],["sorobanFeeWrite1Kb",e.lookup("Int64")]]),e.union("LedgerCloseMetaExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerCloseMetaExtV1")}}),e.struct("LedgerCloseMetaV1",[["ext",e.lookup("LedgerCloseMetaExt")],["ledgerHeader",e.lookup("LedgerHeaderHistoryEntry")],["txSet",e.lookup("GeneralizedTransactionSet")],["txProcessing",e.varArray(e.lookup("TransactionResultMeta"),2147483647)],["upgradesProcessing",e.varArray(e.lookup("UpgradeEntryMeta"),2147483647)],["scpInfo",e.varArray(e.lookup("ScpHistoryEntry"),2147483647)],["totalByteSizeOfBucketList",e.lookup("Uint64")],["evictedTemporaryLedgerKeys",e.varArray(e.lookup("LedgerKey"),2147483647)],["evictedPersistentLedgerEntries",e.varArray(e.lookup("LedgerEntry"),2147483647)]]),e.union("LedgerCloseMeta",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"],[1,"v1"]],arms:{v0:e.lookup("LedgerCloseMetaV0"),v1:e.lookup("LedgerCloseMetaV1")}}),e.enum("ErrorCode",{errMisc:0,errData:1,errConf:2,errAuth:3,errLoad:4}),e.struct("Error",[["code",e.lookup("ErrorCode")],["msg",e.string(100)]]),e.struct("SendMore",[["numMessages",e.lookup("Uint32")]]),e.struct("SendMoreExtended",[["numMessages",e.lookup("Uint32")],["numBytes",e.lookup("Uint32")]]),e.struct("AuthCert",[["pubkey",e.lookup("Curve25519Public")],["expiration",e.lookup("Uint64")],["sig",e.lookup("Signature")]]),e.struct("Hello",[["ledgerVersion",e.lookup("Uint32")],["overlayVersion",e.lookup("Uint32")],["overlayMinVersion",e.lookup("Uint32")],["networkId",e.lookup("Hash")],["versionStr",e.string(100)],["listeningPort",e.int()],["peerId",e.lookup("NodeId")],["cert",e.lookup("AuthCert")],["nonce",e.lookup("Uint256")]]),e.const("AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED",200),e.struct("Auth",[["flags",e.int()]]),e.enum("IpAddrType",{iPv4:0,iPv6:1}),e.union("PeerAddressIp",{switchOn:e.lookup("IpAddrType"),switchName:"type",switches:[["iPv4","ipv4"],["iPv6","ipv6"]],arms:{ipv4:e.opaque(4),ipv6:e.opaque(16)}}),e.struct("PeerAddress",[["ip",e.lookup("PeerAddressIp")],["port",e.lookup("Uint32")],["numFailures",e.lookup("Uint32")]]),e.enum("MessageType",{errorMsg:0,auth:2,dontHave:3,getPeers:4,peers:5,getTxSet:6,txSet:7,generalizedTxSet:17,transaction:8,getScpQuorumset:9,scpQuorumset:10,scpMessage:11,getScpState:12,hello:13,surveyRequest:14,surveyResponse:15,sendMore:16,sendMoreExtended:20,floodAdvert:18,floodDemand:19,timeSlicedSurveyRequest:21,timeSlicedSurveyResponse:22,timeSlicedSurveyStartCollecting:23,timeSlicedSurveyStopCollecting:24}),e.struct("DontHave",[["type",e.lookup("MessageType")],["reqHash",e.lookup("Uint256")]]),e.enum("SurveyMessageCommandType",{surveyTopology:0,timeSlicedSurveyTopology:1}),e.enum("SurveyMessageResponseType",{surveyTopologyResponseV0:0,surveyTopologyResponseV1:1,surveyTopologyResponseV2:2}),e.struct("TimeSlicedSurveyStartCollectingMessage",[["surveyorId",e.lookup("NodeId")],["nonce",e.lookup("Uint32")],["ledgerNum",e.lookup("Uint32")]]),e.struct("SignedTimeSlicedSurveyStartCollectingMessage",[["signature",e.lookup("Signature")],["startCollecting",e.lookup("TimeSlicedSurveyStartCollectingMessage")]]),e.struct("TimeSlicedSurveyStopCollectingMessage",[["surveyorId",e.lookup("NodeId")],["nonce",e.lookup("Uint32")],["ledgerNum",e.lookup("Uint32")]]),e.struct("SignedTimeSlicedSurveyStopCollectingMessage",[["signature",e.lookup("Signature")],["stopCollecting",e.lookup("TimeSlicedSurveyStopCollectingMessage")]]),e.struct("SurveyRequestMessage",[["surveyorPeerId",e.lookup("NodeId")],["surveyedPeerId",e.lookup("NodeId")],["ledgerNum",e.lookup("Uint32")],["encryptionKey",e.lookup("Curve25519Public")],["commandType",e.lookup("SurveyMessageCommandType")]]),e.struct("TimeSlicedSurveyRequestMessage",[["request",e.lookup("SurveyRequestMessage")],["nonce",e.lookup("Uint32")],["inboundPeersIndex",e.lookup("Uint32")],["outboundPeersIndex",e.lookup("Uint32")]]),e.struct("SignedSurveyRequestMessage",[["requestSignature",e.lookup("Signature")],["request",e.lookup("SurveyRequestMessage")]]),e.struct("SignedTimeSlicedSurveyRequestMessage",[["requestSignature",e.lookup("Signature")],["request",e.lookup("TimeSlicedSurveyRequestMessage")]]),e.typedef("EncryptedBody",e.varOpaque(64e3)),e.struct("SurveyResponseMessage",[["surveyorPeerId",e.lookup("NodeId")],["surveyedPeerId",e.lookup("NodeId")],["ledgerNum",e.lookup("Uint32")],["commandType",e.lookup("SurveyMessageCommandType")],["encryptedBody",e.lookup("EncryptedBody")]]),e.struct("TimeSlicedSurveyResponseMessage",[["response",e.lookup("SurveyResponseMessage")],["nonce",e.lookup("Uint32")]]),e.struct("SignedSurveyResponseMessage",[["responseSignature",e.lookup("Signature")],["response",e.lookup("SurveyResponseMessage")]]),e.struct("SignedTimeSlicedSurveyResponseMessage",[["responseSignature",e.lookup("Signature")],["response",e.lookup("TimeSlicedSurveyResponseMessage")]]),e.struct("PeerStats",[["id",e.lookup("NodeId")],["versionStr",e.string(100)],["messagesRead",e.lookup("Uint64")],["messagesWritten",e.lookup("Uint64")],["bytesRead",e.lookup("Uint64")],["bytesWritten",e.lookup("Uint64")],["secondsConnected",e.lookup("Uint64")],["uniqueFloodBytesRecv",e.lookup("Uint64")],["duplicateFloodBytesRecv",e.lookup("Uint64")],["uniqueFetchBytesRecv",e.lookup("Uint64")],["duplicateFetchBytesRecv",e.lookup("Uint64")],["uniqueFloodMessageRecv",e.lookup("Uint64")],["duplicateFloodMessageRecv",e.lookup("Uint64")],["uniqueFetchMessageRecv",e.lookup("Uint64")],["duplicateFetchMessageRecv",e.lookup("Uint64")]]),e.typedef("PeerStatList",e.varArray(e.lookup("PeerStats"),25)),e.struct("TimeSlicedNodeData",[["addedAuthenticatedPeers",e.lookup("Uint32")],["droppedAuthenticatedPeers",e.lookup("Uint32")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")],["p75ScpFirstToSelfLatencyMs",e.lookup("Uint32")],["p75ScpSelfToOtherLatencyMs",e.lookup("Uint32")],["lostSyncCount",e.lookup("Uint32")],["isValidator",e.bool()],["maxInboundPeerCount",e.lookup("Uint32")],["maxOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TimeSlicedPeerData",[["peerStats",e.lookup("PeerStats")],["averageLatencyMs",e.lookup("Uint32")]]),e.typedef("TimeSlicedPeerDataList",e.varArray(e.lookup("TimeSlicedPeerData"),25)),e.struct("TopologyResponseBodyV0",[["inboundPeers",e.lookup("PeerStatList")],["outboundPeers",e.lookup("PeerStatList")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TopologyResponseBodyV1",[["inboundPeers",e.lookup("PeerStatList")],["outboundPeers",e.lookup("PeerStatList")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")],["maxInboundPeerCount",e.lookup("Uint32")],["maxOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TopologyResponseBodyV2",[["inboundPeers",e.lookup("TimeSlicedPeerDataList")],["outboundPeers",e.lookup("TimeSlicedPeerDataList")],["nodeData",e.lookup("TimeSlicedNodeData")]]),e.union("SurveyResponseBody",{switchOn:e.lookup("SurveyMessageResponseType"),switchName:"type",switches:[["surveyTopologyResponseV0","topologyResponseBodyV0"],["surveyTopologyResponseV1","topologyResponseBodyV1"],["surveyTopologyResponseV2","topologyResponseBodyV2"]],arms:{topologyResponseBodyV0:e.lookup("TopologyResponseBodyV0"),topologyResponseBodyV1:e.lookup("TopologyResponseBodyV1"),topologyResponseBodyV2:e.lookup("TopologyResponseBodyV2")}}),e.const("TX_ADVERT_VECTOR_MAX_SIZE",1e3),e.typedef("TxAdvertVector",e.varArray(e.lookup("Hash"),e.lookup("TX_ADVERT_VECTOR_MAX_SIZE"))),e.struct("FloodAdvert",[["txHashes",e.lookup("TxAdvertVector")]]),e.const("TX_DEMAND_VECTOR_MAX_SIZE",1e3),e.typedef("TxDemandVector",e.varArray(e.lookup("Hash"),e.lookup("TX_DEMAND_VECTOR_MAX_SIZE"))),e.struct("FloodDemand",[["txHashes",e.lookup("TxDemandVector")]]),e.union("StellarMessage",{switchOn:e.lookup("MessageType"),switchName:"type",switches:[["errorMsg","error"],["hello","hello"],["auth","auth"],["dontHave","dontHave"],["getPeers",e.void()],["peers","peers"],["getTxSet","txSetHash"],["txSet","txSet"],["generalizedTxSet","generalizedTxSet"],["transaction","transaction"],["surveyRequest","signedSurveyRequestMessage"],["surveyResponse","signedSurveyResponseMessage"],["timeSlicedSurveyRequest","signedTimeSlicedSurveyRequestMessage"],["timeSlicedSurveyResponse","signedTimeSlicedSurveyResponseMessage"],["timeSlicedSurveyStartCollecting","signedTimeSlicedSurveyStartCollectingMessage"],["timeSlicedSurveyStopCollecting","signedTimeSlicedSurveyStopCollectingMessage"],["getScpQuorumset","qSetHash"],["scpQuorumset","qSet"],["scpMessage","envelope"],["getScpState","getScpLedgerSeq"],["sendMore","sendMoreMessage"],["sendMoreExtended","sendMoreExtendedMessage"],["floodAdvert","floodAdvert"],["floodDemand","floodDemand"]],arms:{error:e.lookup("Error"),hello:e.lookup("Hello"),auth:e.lookup("Auth"),dontHave:e.lookup("DontHave"),peers:e.varArray(e.lookup("PeerAddress"),100),txSetHash:e.lookup("Uint256"),txSet:e.lookup("TransactionSet"),generalizedTxSet:e.lookup("GeneralizedTransactionSet"),transaction:e.lookup("TransactionEnvelope"),signedSurveyRequestMessage:e.lookup("SignedSurveyRequestMessage"),signedSurveyResponseMessage:e.lookup("SignedSurveyResponseMessage"),signedTimeSlicedSurveyRequestMessage:e.lookup("SignedTimeSlicedSurveyRequestMessage"),signedTimeSlicedSurveyResponseMessage:e.lookup("SignedTimeSlicedSurveyResponseMessage"),signedTimeSlicedSurveyStartCollectingMessage:e.lookup("SignedTimeSlicedSurveyStartCollectingMessage"),signedTimeSlicedSurveyStopCollectingMessage:e.lookup("SignedTimeSlicedSurveyStopCollectingMessage"),qSetHash:e.lookup("Uint256"),qSet:e.lookup("ScpQuorumSet"),envelope:e.lookup("ScpEnvelope"),getScpLedgerSeq:e.lookup("Uint32"),sendMoreMessage:e.lookup("SendMore"),sendMoreExtendedMessage:e.lookup("SendMoreExtended"),floodAdvert:e.lookup("FloodAdvert"),floodDemand:e.lookup("FloodDemand")}}),e.struct("AuthenticatedMessageV0",[["sequence",e.lookup("Uint64")],["message",e.lookup("StellarMessage")],["mac",e.lookup("HmacSha256Mac")]]),e.union("AuthenticatedMessage",{switchOn:e.lookup("Uint32"),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("AuthenticatedMessageV0")}}),e.const("MAX_OPS_PER_TX",100),e.union("LiquidityPoolParameters",{switchOn:e.lookup("LiquidityPoolType"),switchName:"type",switches:[["liquidityPoolConstantProduct","constantProduct"]],arms:{constantProduct:e.lookup("LiquidityPoolConstantProductParameters")}}),e.struct("MuxedAccountMed25519",[["id",e.lookup("Uint64")],["ed25519",e.lookup("Uint256")]]),e.union("MuxedAccount",{switchOn:e.lookup("CryptoKeyType"),switchName:"type",switches:[["keyTypeEd25519","ed25519"],["keyTypeMuxedEd25519","med25519"]],arms:{ed25519:e.lookup("Uint256"),med25519:e.lookup("MuxedAccountMed25519")}}),e.struct("DecoratedSignature",[["hint",e.lookup("SignatureHint")],["signature",e.lookup("Signature")]]),e.enum("OperationType",{createAccount:0,payment:1,pathPaymentStrictReceive:2,manageSellOffer:3,createPassiveSellOffer:4,setOptions:5,changeTrust:6,allowTrust:7,accountMerge:8,inflation:9,manageData:10,bumpSequence:11,manageBuyOffer:12,pathPaymentStrictSend:13,createClaimableBalance:14,claimClaimableBalance:15,beginSponsoringFutureReserves:16,endSponsoringFutureReserves:17,revokeSponsorship:18,clawback:19,clawbackClaimableBalance:20,setTrustLineFlags:21,liquidityPoolDeposit:22,liquidityPoolWithdraw:23,invokeHostFunction:24,extendFootprintTtl:25,restoreFootprint:26}),e.struct("CreateAccountOp",[["destination",e.lookup("AccountId")],["startingBalance",e.lookup("Int64")]]),e.struct("PaymentOp",[["destination",e.lookup("MuxedAccount")],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")]]),e.struct("PathPaymentStrictReceiveOp",[["sendAsset",e.lookup("Asset")],["sendMax",e.lookup("Int64")],["destination",e.lookup("MuxedAccount")],["destAsset",e.lookup("Asset")],["destAmount",e.lookup("Int64")],["path",e.varArray(e.lookup("Asset"),5)]]),e.struct("PathPaymentStrictSendOp",[["sendAsset",e.lookup("Asset")],["sendAmount",e.lookup("Int64")],["destination",e.lookup("MuxedAccount")],["destAsset",e.lookup("Asset")],["destMin",e.lookup("Int64")],["path",e.varArray(e.lookup("Asset"),5)]]),e.struct("ManageSellOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")],["offerId",e.lookup("Int64")]]),e.struct("ManageBuyOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["buyAmount",e.lookup("Int64")],["price",e.lookup("Price")],["offerId",e.lookup("Int64")]]),e.struct("CreatePassiveSellOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")]]),e.struct("SetOptionsOp",[["inflationDest",e.option(e.lookup("AccountId"))],["clearFlags",e.option(e.lookup("Uint32"))],["setFlags",e.option(e.lookup("Uint32"))],["masterWeight",e.option(e.lookup("Uint32"))],["lowThreshold",e.option(e.lookup("Uint32"))],["medThreshold",e.option(e.lookup("Uint32"))],["highThreshold",e.option(e.lookup("Uint32"))],["homeDomain",e.option(e.lookup("String32"))],["signer",e.option(e.lookup("Signer"))]]),e.union("ChangeTrustAsset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"],["assetTypePoolShare","liquidityPool"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12"),liquidityPool:e.lookup("LiquidityPoolParameters")}}),e.struct("ChangeTrustOp",[["line",e.lookup("ChangeTrustAsset")],["limit",e.lookup("Int64")]]),e.struct("AllowTrustOp",[["trustor",e.lookup("AccountId")],["asset",e.lookup("AssetCode")],["authorize",e.lookup("Uint32")]]),e.struct("ManageDataOp",[["dataName",e.lookup("String64")],["dataValue",e.option(e.lookup("DataValue"))]]),e.struct("BumpSequenceOp",[["bumpTo",e.lookup("SequenceNumber")]]),e.struct("CreateClaimableBalanceOp",[["asset",e.lookup("Asset")],["amount",e.lookup("Int64")],["claimants",e.varArray(e.lookup("Claimant"),10)]]),e.struct("ClaimClaimableBalanceOp",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("BeginSponsoringFutureReservesOp",[["sponsoredId",e.lookup("AccountId")]]),e.enum("RevokeSponsorshipType",{revokeSponsorshipLedgerEntry:0,revokeSponsorshipSigner:1}),e.struct("RevokeSponsorshipOpSigner",[["accountId",e.lookup("AccountId")],["signerKey",e.lookup("SignerKey")]]),e.union("RevokeSponsorshipOp",{switchOn:e.lookup("RevokeSponsorshipType"),switchName:"type",switches:[["revokeSponsorshipLedgerEntry","ledgerKey"],["revokeSponsorshipSigner","signer"]],arms:{ledgerKey:e.lookup("LedgerKey"),signer:e.lookup("RevokeSponsorshipOpSigner")}}),e.struct("ClawbackOp",[["asset",e.lookup("Asset")],["from",e.lookup("MuxedAccount")],["amount",e.lookup("Int64")]]),e.struct("ClawbackClaimableBalanceOp",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("SetTrustLineFlagsOp",[["trustor",e.lookup("AccountId")],["asset",e.lookup("Asset")],["clearFlags",e.lookup("Uint32")],["setFlags",e.lookup("Uint32")]]),e.const("LIQUIDITY_POOL_FEE_V18",30),e.struct("LiquidityPoolDepositOp",[["liquidityPoolId",e.lookup("PoolId")],["maxAmountA",e.lookup("Int64")],["maxAmountB",e.lookup("Int64")],["minPrice",e.lookup("Price")],["maxPrice",e.lookup("Price")]]),e.struct("LiquidityPoolWithdrawOp",[["liquidityPoolId",e.lookup("PoolId")],["amount",e.lookup("Int64")],["minAmountA",e.lookup("Int64")],["minAmountB",e.lookup("Int64")]]),e.enum("HostFunctionType",{hostFunctionTypeInvokeContract:0,hostFunctionTypeCreateContract:1,hostFunctionTypeUploadContractWasm:2,hostFunctionTypeCreateContractV2:3}),e.enum("ContractIdPreimageType",{contractIdPreimageFromAddress:0,contractIdPreimageFromAsset:1}),e.struct("ContractIdPreimageFromAddress",[["address",e.lookup("ScAddress")],["salt",e.lookup("Uint256")]]),e.union("ContractIdPreimage",{switchOn:e.lookup("ContractIdPreimageType"),switchName:"type",switches:[["contractIdPreimageFromAddress","fromAddress"],["contractIdPreimageFromAsset","fromAsset"]],arms:{fromAddress:e.lookup("ContractIdPreimageFromAddress"),fromAsset:e.lookup("Asset")}}),e.struct("CreateContractArgs",[["contractIdPreimage",e.lookup("ContractIdPreimage")],["executable",e.lookup("ContractExecutable")]]),e.struct("CreateContractArgsV2",[["contractIdPreimage",e.lookup("ContractIdPreimage")],["executable",e.lookup("ContractExecutable")],["constructorArgs",e.varArray(e.lookup("ScVal"),2147483647)]]),e.struct("InvokeContractArgs",[["contractAddress",e.lookup("ScAddress")],["functionName",e.lookup("ScSymbol")],["args",e.varArray(e.lookup("ScVal"),2147483647)]]),e.union("HostFunction",{switchOn:e.lookup("HostFunctionType"),switchName:"type",switches:[["hostFunctionTypeInvokeContract","invokeContract"],["hostFunctionTypeCreateContract","createContract"],["hostFunctionTypeUploadContractWasm","wasm"],["hostFunctionTypeCreateContractV2","createContractV2"]],arms:{invokeContract:e.lookup("InvokeContractArgs"),createContract:e.lookup("CreateContractArgs"),wasm:e.varOpaque(),createContractV2:e.lookup("CreateContractArgsV2")}}),e.enum("SorobanAuthorizedFunctionType",{sorobanAuthorizedFunctionTypeContractFn:0,sorobanAuthorizedFunctionTypeCreateContractHostFn:1,sorobanAuthorizedFunctionTypeCreateContractV2HostFn:2}),e.union("SorobanAuthorizedFunction",{switchOn:e.lookup("SorobanAuthorizedFunctionType"),switchName:"type",switches:[["sorobanAuthorizedFunctionTypeContractFn","contractFn"],["sorobanAuthorizedFunctionTypeCreateContractHostFn","createContractHostFn"],["sorobanAuthorizedFunctionTypeCreateContractV2HostFn","createContractV2HostFn"]],arms:{contractFn:e.lookup("InvokeContractArgs"),createContractHostFn:e.lookup("CreateContractArgs"),createContractV2HostFn:e.lookup("CreateContractArgsV2")}}),e.struct("SorobanAuthorizedInvocation",[["function",e.lookup("SorobanAuthorizedFunction")],["subInvocations",e.varArray(e.lookup("SorobanAuthorizedInvocation"),2147483647)]]),e.struct("SorobanAddressCredentials",[["address",e.lookup("ScAddress")],["nonce",e.lookup("Int64")],["signatureExpirationLedger",e.lookup("Uint32")],["signature",e.lookup("ScVal")]]),e.enum("SorobanCredentialsType",{sorobanCredentialsSourceAccount:0,sorobanCredentialsAddress:1}),e.union("SorobanCredentials",{switchOn:e.lookup("SorobanCredentialsType"),switchName:"type",switches:[["sorobanCredentialsSourceAccount",e.void()],["sorobanCredentialsAddress","address"]],arms:{address:e.lookup("SorobanAddressCredentials")}}),e.struct("SorobanAuthorizationEntry",[["credentials",e.lookup("SorobanCredentials")],["rootInvocation",e.lookup("SorobanAuthorizedInvocation")]]),e.struct("InvokeHostFunctionOp",[["hostFunction",e.lookup("HostFunction")],["auth",e.varArray(e.lookup("SorobanAuthorizationEntry"),2147483647)]]),e.struct("ExtendFootprintTtlOp",[["ext",e.lookup("ExtensionPoint")],["extendTo",e.lookup("Uint32")]]),e.struct("RestoreFootprintOp",[["ext",e.lookup("ExtensionPoint")]]),e.union("OperationBody",{switchOn:e.lookup("OperationType"),switchName:"type",switches:[["createAccount","createAccountOp"],["payment","paymentOp"],["pathPaymentStrictReceive","pathPaymentStrictReceiveOp"],["manageSellOffer","manageSellOfferOp"],["createPassiveSellOffer","createPassiveSellOfferOp"],["setOptions","setOptionsOp"],["changeTrust","changeTrustOp"],["allowTrust","allowTrustOp"],["accountMerge","destination"],["inflation",e.void()],["manageData","manageDataOp"],["bumpSequence","bumpSequenceOp"],["manageBuyOffer","manageBuyOfferOp"],["pathPaymentStrictSend","pathPaymentStrictSendOp"],["createClaimableBalance","createClaimableBalanceOp"],["claimClaimableBalance","claimClaimableBalanceOp"],["beginSponsoringFutureReserves","beginSponsoringFutureReservesOp"],["endSponsoringFutureReserves",e.void()],["revokeSponsorship","revokeSponsorshipOp"],["clawback","clawbackOp"],["clawbackClaimableBalance","clawbackClaimableBalanceOp"],["setTrustLineFlags","setTrustLineFlagsOp"],["liquidityPoolDeposit","liquidityPoolDepositOp"],["liquidityPoolWithdraw","liquidityPoolWithdrawOp"],["invokeHostFunction","invokeHostFunctionOp"],["extendFootprintTtl","extendFootprintTtlOp"],["restoreFootprint","restoreFootprintOp"]],arms:{createAccountOp:e.lookup("CreateAccountOp"),paymentOp:e.lookup("PaymentOp"),pathPaymentStrictReceiveOp:e.lookup("PathPaymentStrictReceiveOp"),manageSellOfferOp:e.lookup("ManageSellOfferOp"),createPassiveSellOfferOp:e.lookup("CreatePassiveSellOfferOp"),setOptionsOp:e.lookup("SetOptionsOp"),changeTrustOp:e.lookup("ChangeTrustOp"),allowTrustOp:e.lookup("AllowTrustOp"),destination:e.lookup("MuxedAccount"),manageDataOp:e.lookup("ManageDataOp"),bumpSequenceOp:e.lookup("BumpSequenceOp"),manageBuyOfferOp:e.lookup("ManageBuyOfferOp"),pathPaymentStrictSendOp:e.lookup("PathPaymentStrictSendOp"),createClaimableBalanceOp:e.lookup("CreateClaimableBalanceOp"),claimClaimableBalanceOp:e.lookup("ClaimClaimableBalanceOp"),beginSponsoringFutureReservesOp:e.lookup("BeginSponsoringFutureReservesOp"),revokeSponsorshipOp:e.lookup("RevokeSponsorshipOp"),clawbackOp:e.lookup("ClawbackOp"),clawbackClaimableBalanceOp:e.lookup("ClawbackClaimableBalanceOp"),setTrustLineFlagsOp:e.lookup("SetTrustLineFlagsOp"),liquidityPoolDepositOp:e.lookup("LiquidityPoolDepositOp"),liquidityPoolWithdrawOp:e.lookup("LiquidityPoolWithdrawOp"),invokeHostFunctionOp:e.lookup("InvokeHostFunctionOp"),extendFootprintTtlOp:e.lookup("ExtendFootprintTtlOp"),restoreFootprintOp:e.lookup("RestoreFootprintOp")}}),e.struct("Operation",[["sourceAccount",e.option(e.lookup("MuxedAccount"))],["body",e.lookup("OperationBody")]]),e.struct("HashIdPreimageOperationId",[["sourceAccount",e.lookup("AccountId")],["seqNum",e.lookup("SequenceNumber")],["opNum",e.lookup("Uint32")]]),e.struct("HashIdPreimageRevokeId",[["sourceAccount",e.lookup("AccountId")],["seqNum",e.lookup("SequenceNumber")],["opNum",e.lookup("Uint32")],["liquidityPoolId",e.lookup("PoolId")],["asset",e.lookup("Asset")]]),e.struct("HashIdPreimageContractId",[["networkId",e.lookup("Hash")],["contractIdPreimage",e.lookup("ContractIdPreimage")]]),e.struct("HashIdPreimageSorobanAuthorization",[["networkId",e.lookup("Hash")],["nonce",e.lookup("Int64")],["signatureExpirationLedger",e.lookup("Uint32")],["invocation",e.lookup("SorobanAuthorizedInvocation")]]),e.union("HashIdPreimage",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeOpId","operationId"],["envelopeTypePoolRevokeOpId","revokeId"],["envelopeTypeContractId","contractId"],["envelopeTypeSorobanAuthorization","sorobanAuthorization"]],arms:{operationId:e.lookup("HashIdPreimageOperationId"),revokeId:e.lookup("HashIdPreimageRevokeId"),contractId:e.lookup("HashIdPreimageContractId"),sorobanAuthorization:e.lookup("HashIdPreimageSorobanAuthorization")}}),e.enum("MemoType",{memoNone:0,memoText:1,memoId:2,memoHash:3,memoReturn:4}),e.union("Memo",{switchOn:e.lookup("MemoType"),switchName:"type",switches:[["memoNone",e.void()],["memoText","text"],["memoId","id"],["memoHash","hash"],["memoReturn","retHash"]],arms:{text:e.string(28),id:e.lookup("Uint64"),hash:e.lookup("Hash"),retHash:e.lookup("Hash")}}),e.struct("TimeBounds",[["minTime",e.lookup("TimePoint")],["maxTime",e.lookup("TimePoint")]]),e.struct("LedgerBounds",[["minLedger",e.lookup("Uint32")],["maxLedger",e.lookup("Uint32")]]),e.struct("PreconditionsV2",[["timeBounds",e.option(e.lookup("TimeBounds"))],["ledgerBounds",e.option(e.lookup("LedgerBounds"))],["minSeqNum",e.option(e.lookup("SequenceNumber"))],["minSeqAge",e.lookup("Duration")],["minSeqLedgerGap",e.lookup("Uint32")],["extraSigners",e.varArray(e.lookup("SignerKey"),2)]]),e.enum("PreconditionType",{precondNone:0,precondTime:1,precondV2:2}),e.union("Preconditions",{switchOn:e.lookup("PreconditionType"),switchName:"type",switches:[["precondNone",e.void()],["precondTime","timeBounds"],["precondV2","v2"]],arms:{timeBounds:e.lookup("TimeBounds"),v2:e.lookup("PreconditionsV2")}}),e.struct("LedgerFootprint",[["readOnly",e.varArray(e.lookup("LedgerKey"),2147483647)],["readWrite",e.varArray(e.lookup("LedgerKey"),2147483647)]]),e.enum("ArchivalProofType",{existence:0,nonexistence:1}),e.struct("ArchivalProofNode",[["index",e.lookup("Uint32")],["hash",e.lookup("Hash")]]),e.typedef("ProofLevel",e.varArray(e.lookup("ArchivalProofNode"),2147483647)),e.struct("NonexistenceProofBody",[["entriesToProve",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["proofLevels",e.varArray(e.lookup("ProofLevel"),2147483647)]]),e.struct("ExistenceProofBody",[["keysToProve",e.varArray(e.lookup("LedgerKey"),2147483647)],["lowBoundEntries",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["highBoundEntries",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["proofLevels",e.varArray(e.lookup("ProofLevel"),2147483647)]]),e.union("ArchivalProofBody",{switchOn:e.lookup("ArchivalProofType"),switchName:"t",switches:[["existence","nonexistenceProof"],["nonexistence","existenceProof"]],arms:{nonexistenceProof:e.lookup("NonexistenceProofBody"),existenceProof:e.lookup("ExistenceProofBody")}}),e.struct("ArchivalProof",[["epoch",e.lookup("Uint32")],["body",e.lookup("ArchivalProofBody")]]),e.struct("SorobanResources",[["footprint",e.lookup("LedgerFootprint")],["instructions",e.lookup("Uint32")],["readBytes",e.lookup("Uint32")],["writeBytes",e.lookup("Uint32")]]),e.struct("SorobanTransactionData",[["ext",e.lookup("ExtensionPoint")],["resources",e.lookup("SorobanResources")],["resourceFee",e.lookup("Int64")]]),e.union("TransactionV0Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionV0",[["sourceAccountEd25519",e.lookup("Uint256")],["fee",e.lookup("Uint32")],["seqNum",e.lookup("SequenceNumber")],["timeBounds",e.option(e.lookup("TimeBounds"))],["memo",e.lookup("Memo")],["operations",e.varArray(e.lookup("Operation"),e.lookup("MAX_OPS_PER_TX"))],["ext",e.lookup("TransactionV0Ext")]]),e.struct("TransactionV0Envelope",[["tx",e.lookup("TransactionV0")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("TransactionExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"sorobanData"]],arms:{sorobanData:e.lookup("SorobanTransactionData")}}),e.struct("Transaction",[["sourceAccount",e.lookup("MuxedAccount")],["fee",e.lookup("Uint32")],["seqNum",e.lookup("SequenceNumber")],["cond",e.lookup("Preconditions")],["memo",e.lookup("Memo")],["operations",e.varArray(e.lookup("Operation"),e.lookup("MAX_OPS_PER_TX"))],["ext",e.lookup("TransactionExt")]]),e.struct("TransactionV1Envelope",[["tx",e.lookup("Transaction")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("FeeBumpTransactionInnerTx",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTx","v1"]],arms:{v1:e.lookup("TransactionV1Envelope")}}),e.union("FeeBumpTransactionExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("FeeBumpTransaction",[["feeSource",e.lookup("MuxedAccount")],["fee",e.lookup("Int64")],["innerTx",e.lookup("FeeBumpTransactionInnerTx")],["ext",e.lookup("FeeBumpTransactionExt")]]),e.struct("FeeBumpTransactionEnvelope",[["tx",e.lookup("FeeBumpTransaction")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("TransactionEnvelope",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTxV0","v0"],["envelopeTypeTx","v1"],["envelopeTypeTxFeeBump","feeBump"]],arms:{v0:e.lookup("TransactionV0Envelope"),v1:e.lookup("TransactionV1Envelope"),feeBump:e.lookup("FeeBumpTransactionEnvelope")}}),e.union("TransactionSignaturePayloadTaggedTransaction",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTx","tx"],["envelopeTypeTxFeeBump","feeBump"]],arms:{tx:e.lookup("Transaction"),feeBump:e.lookup("FeeBumpTransaction")}}),e.struct("TransactionSignaturePayload",[["networkId",e.lookup("Hash")],["taggedTransaction",e.lookup("TransactionSignaturePayloadTaggedTransaction")]]),e.enum("ClaimAtomType",{claimAtomTypeV0:0,claimAtomTypeOrderBook:1,claimAtomTypeLiquidityPool:2}),e.struct("ClaimOfferAtomV0",[["sellerEd25519",e.lookup("Uint256")],["offerId",e.lookup("Int64")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.struct("ClaimOfferAtom",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.struct("ClaimLiquidityAtom",[["liquidityPoolId",e.lookup("PoolId")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.union("ClaimAtom",{switchOn:e.lookup("ClaimAtomType"),switchName:"type",switches:[["claimAtomTypeV0","v0"],["claimAtomTypeOrderBook","orderBook"],["claimAtomTypeLiquidityPool","liquidityPool"]],arms:{v0:e.lookup("ClaimOfferAtomV0"),orderBook:e.lookup("ClaimOfferAtom"),liquidityPool:e.lookup("ClaimLiquidityAtom")}}),e.enum("CreateAccountResultCode",{createAccountSuccess:0,createAccountMalformed:-1,createAccountUnderfunded:-2,createAccountLowReserve:-3,createAccountAlreadyExist:-4}),e.union("CreateAccountResult",{switchOn:e.lookup("CreateAccountResultCode"),switchName:"code",switches:[["createAccountSuccess",e.void()],["createAccountMalformed",e.void()],["createAccountUnderfunded",e.void()],["createAccountLowReserve",e.void()],["createAccountAlreadyExist",e.void()]],arms:{}}),e.enum("PaymentResultCode",{paymentSuccess:0,paymentMalformed:-1,paymentUnderfunded:-2,paymentSrcNoTrust:-3,paymentSrcNotAuthorized:-4,paymentNoDestination:-5,paymentNoTrust:-6,paymentNotAuthorized:-7,paymentLineFull:-8,paymentNoIssuer:-9}),e.union("PaymentResult",{switchOn:e.lookup("PaymentResultCode"),switchName:"code",switches:[["paymentSuccess",e.void()],["paymentMalformed",e.void()],["paymentUnderfunded",e.void()],["paymentSrcNoTrust",e.void()],["paymentSrcNotAuthorized",e.void()],["paymentNoDestination",e.void()],["paymentNoTrust",e.void()],["paymentNotAuthorized",e.void()],["paymentLineFull",e.void()],["paymentNoIssuer",e.void()]],arms:{}}),e.enum("PathPaymentStrictReceiveResultCode",{pathPaymentStrictReceiveSuccess:0,pathPaymentStrictReceiveMalformed:-1,pathPaymentStrictReceiveUnderfunded:-2,pathPaymentStrictReceiveSrcNoTrust:-3,pathPaymentStrictReceiveSrcNotAuthorized:-4,pathPaymentStrictReceiveNoDestination:-5,pathPaymentStrictReceiveNoTrust:-6,pathPaymentStrictReceiveNotAuthorized:-7,pathPaymentStrictReceiveLineFull:-8,pathPaymentStrictReceiveNoIssuer:-9,pathPaymentStrictReceiveTooFewOffers:-10,pathPaymentStrictReceiveOfferCrossSelf:-11,pathPaymentStrictReceiveOverSendmax:-12}),e.struct("SimplePaymentResult",[["destination",e.lookup("AccountId")],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")]]),e.struct("PathPaymentStrictReceiveResultSuccess",[["offers",e.varArray(e.lookup("ClaimAtom"),2147483647)],["last",e.lookup("SimplePaymentResult")]]),e.union("PathPaymentStrictReceiveResult",{switchOn:e.lookup("PathPaymentStrictReceiveResultCode"),switchName:"code",switches:[["pathPaymentStrictReceiveSuccess","success"],["pathPaymentStrictReceiveMalformed",e.void()],["pathPaymentStrictReceiveUnderfunded",e.void()],["pathPaymentStrictReceiveSrcNoTrust",e.void()],["pathPaymentStrictReceiveSrcNotAuthorized",e.void()],["pathPaymentStrictReceiveNoDestination",e.void()],["pathPaymentStrictReceiveNoTrust",e.void()],["pathPaymentStrictReceiveNotAuthorized",e.void()],["pathPaymentStrictReceiveLineFull",e.void()],["pathPaymentStrictReceiveNoIssuer","noIssuer"],["pathPaymentStrictReceiveTooFewOffers",e.void()],["pathPaymentStrictReceiveOfferCrossSelf",e.void()],["pathPaymentStrictReceiveOverSendmax",e.void()]],arms:{success:e.lookup("PathPaymentStrictReceiveResultSuccess"),noIssuer:e.lookup("Asset")}}),e.enum("PathPaymentStrictSendResultCode",{pathPaymentStrictSendSuccess:0,pathPaymentStrictSendMalformed:-1,pathPaymentStrictSendUnderfunded:-2,pathPaymentStrictSendSrcNoTrust:-3,pathPaymentStrictSendSrcNotAuthorized:-4,pathPaymentStrictSendNoDestination:-5,pathPaymentStrictSendNoTrust:-6,pathPaymentStrictSendNotAuthorized:-7,pathPaymentStrictSendLineFull:-8,pathPaymentStrictSendNoIssuer:-9,pathPaymentStrictSendTooFewOffers:-10,pathPaymentStrictSendOfferCrossSelf:-11,pathPaymentStrictSendUnderDestmin:-12}),e.struct("PathPaymentStrictSendResultSuccess",[["offers",e.varArray(e.lookup("ClaimAtom"),2147483647)],["last",e.lookup("SimplePaymentResult")]]),e.union("PathPaymentStrictSendResult",{switchOn:e.lookup("PathPaymentStrictSendResultCode"),switchName:"code",switches:[["pathPaymentStrictSendSuccess","success"],["pathPaymentStrictSendMalformed",e.void()],["pathPaymentStrictSendUnderfunded",e.void()],["pathPaymentStrictSendSrcNoTrust",e.void()],["pathPaymentStrictSendSrcNotAuthorized",e.void()],["pathPaymentStrictSendNoDestination",e.void()],["pathPaymentStrictSendNoTrust",e.void()],["pathPaymentStrictSendNotAuthorized",e.void()],["pathPaymentStrictSendLineFull",e.void()],["pathPaymentStrictSendNoIssuer","noIssuer"],["pathPaymentStrictSendTooFewOffers",e.void()],["pathPaymentStrictSendOfferCrossSelf",e.void()],["pathPaymentStrictSendUnderDestmin",e.void()]],arms:{success:e.lookup("PathPaymentStrictSendResultSuccess"),noIssuer:e.lookup("Asset")}}),e.enum("ManageSellOfferResultCode",{manageSellOfferSuccess:0,manageSellOfferMalformed:-1,manageSellOfferSellNoTrust:-2,manageSellOfferBuyNoTrust:-3,manageSellOfferSellNotAuthorized:-4,manageSellOfferBuyNotAuthorized:-5,manageSellOfferLineFull:-6,manageSellOfferUnderfunded:-7,manageSellOfferCrossSelf:-8,manageSellOfferSellNoIssuer:-9,manageSellOfferBuyNoIssuer:-10,manageSellOfferNotFound:-11,manageSellOfferLowReserve:-12}),e.enum("ManageOfferEffect",{manageOfferCreated:0,manageOfferUpdated:1,manageOfferDeleted:2}),e.union("ManageOfferSuccessResultOffer",{switchOn:e.lookup("ManageOfferEffect"),switchName:"effect",switches:[["manageOfferCreated","offer"],["manageOfferUpdated","offer"],["manageOfferDeleted",e.void()]],arms:{offer:e.lookup("OfferEntry")}}),e.struct("ManageOfferSuccessResult",[["offersClaimed",e.varArray(e.lookup("ClaimAtom"),2147483647)],["offer",e.lookup("ManageOfferSuccessResultOffer")]]),e.union("ManageSellOfferResult",{switchOn:e.lookup("ManageSellOfferResultCode"),switchName:"code",switches:[["manageSellOfferSuccess","success"],["manageSellOfferMalformed",e.void()],["manageSellOfferSellNoTrust",e.void()],["manageSellOfferBuyNoTrust",e.void()],["manageSellOfferSellNotAuthorized",e.void()],["manageSellOfferBuyNotAuthorized",e.void()],["manageSellOfferLineFull",e.void()],["manageSellOfferUnderfunded",e.void()],["manageSellOfferCrossSelf",e.void()],["manageSellOfferSellNoIssuer",e.void()],["manageSellOfferBuyNoIssuer",e.void()],["manageSellOfferNotFound",e.void()],["manageSellOfferLowReserve",e.void()]],arms:{success:e.lookup("ManageOfferSuccessResult")}}),e.enum("ManageBuyOfferResultCode",{manageBuyOfferSuccess:0,manageBuyOfferMalformed:-1,manageBuyOfferSellNoTrust:-2,manageBuyOfferBuyNoTrust:-3,manageBuyOfferSellNotAuthorized:-4,manageBuyOfferBuyNotAuthorized:-5,manageBuyOfferLineFull:-6,manageBuyOfferUnderfunded:-7,manageBuyOfferCrossSelf:-8,manageBuyOfferSellNoIssuer:-9,manageBuyOfferBuyNoIssuer:-10,manageBuyOfferNotFound:-11,manageBuyOfferLowReserve:-12}),e.union("ManageBuyOfferResult",{switchOn:e.lookup("ManageBuyOfferResultCode"),switchName:"code",switches:[["manageBuyOfferSuccess","success"],["manageBuyOfferMalformed",e.void()],["manageBuyOfferSellNoTrust",e.void()],["manageBuyOfferBuyNoTrust",e.void()],["manageBuyOfferSellNotAuthorized",e.void()],["manageBuyOfferBuyNotAuthorized",e.void()],["manageBuyOfferLineFull",e.void()],["manageBuyOfferUnderfunded",e.void()],["manageBuyOfferCrossSelf",e.void()],["manageBuyOfferSellNoIssuer",e.void()],["manageBuyOfferBuyNoIssuer",e.void()],["manageBuyOfferNotFound",e.void()],["manageBuyOfferLowReserve",e.void()]],arms:{success:e.lookup("ManageOfferSuccessResult")}}),e.enum("SetOptionsResultCode",{setOptionsSuccess:0,setOptionsLowReserve:-1,setOptionsTooManySigners:-2,setOptionsBadFlags:-3,setOptionsInvalidInflation:-4,setOptionsCantChange:-5,setOptionsUnknownFlag:-6,setOptionsThresholdOutOfRange:-7,setOptionsBadSigner:-8,setOptionsInvalidHomeDomain:-9,setOptionsAuthRevocableRequired:-10}),e.union("SetOptionsResult",{switchOn:e.lookup("SetOptionsResultCode"),switchName:"code",switches:[["setOptionsSuccess",e.void()],["setOptionsLowReserve",e.void()],["setOptionsTooManySigners",e.void()],["setOptionsBadFlags",e.void()],["setOptionsInvalidInflation",e.void()],["setOptionsCantChange",e.void()],["setOptionsUnknownFlag",e.void()],["setOptionsThresholdOutOfRange",e.void()],["setOptionsBadSigner",e.void()],["setOptionsInvalidHomeDomain",e.void()],["setOptionsAuthRevocableRequired",e.void()]],arms:{}}),e.enum("ChangeTrustResultCode",{changeTrustSuccess:0,changeTrustMalformed:-1,changeTrustNoIssuer:-2,changeTrustInvalidLimit:-3,changeTrustLowReserve:-4,changeTrustSelfNotAllowed:-5,changeTrustTrustLineMissing:-6,changeTrustCannotDelete:-7,changeTrustNotAuthMaintainLiabilities:-8}),e.union("ChangeTrustResult",{switchOn:e.lookup("ChangeTrustResultCode"),switchName:"code",switches:[["changeTrustSuccess",e.void()],["changeTrustMalformed",e.void()],["changeTrustNoIssuer",e.void()],["changeTrustInvalidLimit",e.void()],["changeTrustLowReserve",e.void()],["changeTrustSelfNotAllowed",e.void()],["changeTrustTrustLineMissing",e.void()],["changeTrustCannotDelete",e.void()],["changeTrustNotAuthMaintainLiabilities",e.void()]],arms:{}}),e.enum("AllowTrustResultCode",{allowTrustSuccess:0,allowTrustMalformed:-1,allowTrustNoTrustLine:-2,allowTrustTrustNotRequired:-3,allowTrustCantRevoke:-4,allowTrustSelfNotAllowed:-5,allowTrustLowReserve:-6}),e.union("AllowTrustResult",{switchOn:e.lookup("AllowTrustResultCode"),switchName:"code",switches:[["allowTrustSuccess",e.void()],["allowTrustMalformed",e.void()],["allowTrustNoTrustLine",e.void()],["allowTrustTrustNotRequired",e.void()],["allowTrustCantRevoke",e.void()],["allowTrustSelfNotAllowed",e.void()],["allowTrustLowReserve",e.void()]],arms:{}}),e.enum("AccountMergeResultCode",{accountMergeSuccess:0,accountMergeMalformed:-1,accountMergeNoAccount:-2,accountMergeImmutableSet:-3,accountMergeHasSubEntries:-4,accountMergeSeqnumTooFar:-5,accountMergeDestFull:-6,accountMergeIsSponsor:-7}),e.union("AccountMergeResult",{switchOn:e.lookup("AccountMergeResultCode"),switchName:"code",switches:[["accountMergeSuccess","sourceAccountBalance"],["accountMergeMalformed",e.void()],["accountMergeNoAccount",e.void()],["accountMergeImmutableSet",e.void()],["accountMergeHasSubEntries",e.void()],["accountMergeSeqnumTooFar",e.void()],["accountMergeDestFull",e.void()],["accountMergeIsSponsor",e.void()]],arms:{sourceAccountBalance:e.lookup("Int64")}}),e.enum("InflationResultCode",{inflationSuccess:0,inflationNotTime:-1}),e.struct("InflationPayout",[["destination",e.lookup("AccountId")],["amount",e.lookup("Int64")]]),e.union("InflationResult",{switchOn:e.lookup("InflationResultCode"),switchName:"code",switches:[["inflationSuccess","payouts"],["inflationNotTime",e.void()]],arms:{payouts:e.varArray(e.lookup("InflationPayout"),2147483647)}}),e.enum("ManageDataResultCode",{manageDataSuccess:0,manageDataNotSupportedYet:-1,manageDataNameNotFound:-2,manageDataLowReserve:-3,manageDataInvalidName:-4}),e.union("ManageDataResult",{switchOn:e.lookup("ManageDataResultCode"),switchName:"code",switches:[["manageDataSuccess",e.void()],["manageDataNotSupportedYet",e.void()],["manageDataNameNotFound",e.void()],["manageDataLowReserve",e.void()],["manageDataInvalidName",e.void()]],arms:{}}),e.enum("BumpSequenceResultCode",{bumpSequenceSuccess:0,bumpSequenceBadSeq:-1}),e.union("BumpSequenceResult",{switchOn:e.lookup("BumpSequenceResultCode"),switchName:"code",switches:[["bumpSequenceSuccess",e.void()],["bumpSequenceBadSeq",e.void()]],arms:{}}),e.enum("CreateClaimableBalanceResultCode",{createClaimableBalanceSuccess:0,createClaimableBalanceMalformed:-1,createClaimableBalanceLowReserve:-2,createClaimableBalanceNoTrust:-3,createClaimableBalanceNotAuthorized:-4,createClaimableBalanceUnderfunded:-5}),e.union("CreateClaimableBalanceResult",{switchOn:e.lookup("CreateClaimableBalanceResultCode"),switchName:"code",switches:[["createClaimableBalanceSuccess","balanceId"],["createClaimableBalanceMalformed",e.void()],["createClaimableBalanceLowReserve",e.void()],["createClaimableBalanceNoTrust",e.void()],["createClaimableBalanceNotAuthorized",e.void()],["createClaimableBalanceUnderfunded",e.void()]],arms:{balanceId:e.lookup("ClaimableBalanceId")}}),e.enum("ClaimClaimableBalanceResultCode",{claimClaimableBalanceSuccess:0,claimClaimableBalanceDoesNotExist:-1,claimClaimableBalanceCannotClaim:-2,claimClaimableBalanceLineFull:-3,claimClaimableBalanceNoTrust:-4,claimClaimableBalanceNotAuthorized:-5}),e.union("ClaimClaimableBalanceResult",{switchOn:e.lookup("ClaimClaimableBalanceResultCode"),switchName:"code",switches:[["claimClaimableBalanceSuccess",e.void()],["claimClaimableBalanceDoesNotExist",e.void()],["claimClaimableBalanceCannotClaim",e.void()],["claimClaimableBalanceLineFull",e.void()],["claimClaimableBalanceNoTrust",e.void()],["claimClaimableBalanceNotAuthorized",e.void()]],arms:{}}),e.enum("BeginSponsoringFutureReservesResultCode",{beginSponsoringFutureReservesSuccess:0,beginSponsoringFutureReservesMalformed:-1,beginSponsoringFutureReservesAlreadySponsored:-2,beginSponsoringFutureReservesRecursive:-3}),e.union("BeginSponsoringFutureReservesResult",{switchOn:e.lookup("BeginSponsoringFutureReservesResultCode"),switchName:"code",switches:[["beginSponsoringFutureReservesSuccess",e.void()],["beginSponsoringFutureReservesMalformed",e.void()],["beginSponsoringFutureReservesAlreadySponsored",e.void()],["beginSponsoringFutureReservesRecursive",e.void()]],arms:{}}),e.enum("EndSponsoringFutureReservesResultCode",{endSponsoringFutureReservesSuccess:0,endSponsoringFutureReservesNotSponsored:-1}),e.union("EndSponsoringFutureReservesResult",{switchOn:e.lookup("EndSponsoringFutureReservesResultCode"),switchName:"code",switches:[["endSponsoringFutureReservesSuccess",e.void()],["endSponsoringFutureReservesNotSponsored",e.void()]],arms:{}}),e.enum("RevokeSponsorshipResultCode",{revokeSponsorshipSuccess:0,revokeSponsorshipDoesNotExist:-1,revokeSponsorshipNotSponsor:-2,revokeSponsorshipLowReserve:-3,revokeSponsorshipOnlyTransferable:-4,revokeSponsorshipMalformed:-5}),e.union("RevokeSponsorshipResult",{switchOn:e.lookup("RevokeSponsorshipResultCode"),switchName:"code",switches:[["revokeSponsorshipSuccess",e.void()],["revokeSponsorshipDoesNotExist",e.void()],["revokeSponsorshipNotSponsor",e.void()],["revokeSponsorshipLowReserve",e.void()],["revokeSponsorshipOnlyTransferable",e.void()],["revokeSponsorshipMalformed",e.void()]],arms:{}}),e.enum("ClawbackResultCode",{clawbackSuccess:0,clawbackMalformed:-1,clawbackNotClawbackEnabled:-2,clawbackNoTrust:-3,clawbackUnderfunded:-4}),e.union("ClawbackResult",{switchOn:e.lookup("ClawbackResultCode"),switchName:"code",switches:[["clawbackSuccess",e.void()],["clawbackMalformed",e.void()],["clawbackNotClawbackEnabled",e.void()],["clawbackNoTrust",e.void()],["clawbackUnderfunded",e.void()]],arms:{}}),e.enum("ClawbackClaimableBalanceResultCode",{clawbackClaimableBalanceSuccess:0,clawbackClaimableBalanceDoesNotExist:-1,clawbackClaimableBalanceNotIssuer:-2,clawbackClaimableBalanceNotClawbackEnabled:-3}),e.union("ClawbackClaimableBalanceResult",{switchOn:e.lookup("ClawbackClaimableBalanceResultCode"),switchName:"code",switches:[["clawbackClaimableBalanceSuccess",e.void()],["clawbackClaimableBalanceDoesNotExist",e.void()],["clawbackClaimableBalanceNotIssuer",e.void()],["clawbackClaimableBalanceNotClawbackEnabled",e.void()]],arms:{}}),e.enum("SetTrustLineFlagsResultCode",{setTrustLineFlagsSuccess:0,setTrustLineFlagsMalformed:-1,setTrustLineFlagsNoTrustLine:-2,setTrustLineFlagsCantRevoke:-3,setTrustLineFlagsInvalidState:-4,setTrustLineFlagsLowReserve:-5}),e.union("SetTrustLineFlagsResult",{switchOn:e.lookup("SetTrustLineFlagsResultCode"),switchName:"code",switches:[["setTrustLineFlagsSuccess",e.void()],["setTrustLineFlagsMalformed",e.void()],["setTrustLineFlagsNoTrustLine",e.void()],["setTrustLineFlagsCantRevoke",e.void()],["setTrustLineFlagsInvalidState",e.void()],["setTrustLineFlagsLowReserve",e.void()]],arms:{}}),e.enum("LiquidityPoolDepositResultCode",{liquidityPoolDepositSuccess:0,liquidityPoolDepositMalformed:-1,liquidityPoolDepositNoTrust:-2,liquidityPoolDepositNotAuthorized:-3,liquidityPoolDepositUnderfunded:-4,liquidityPoolDepositLineFull:-5,liquidityPoolDepositBadPrice:-6,liquidityPoolDepositPoolFull:-7}),e.union("LiquidityPoolDepositResult",{switchOn:e.lookup("LiquidityPoolDepositResultCode"),switchName:"code",switches:[["liquidityPoolDepositSuccess",e.void()],["liquidityPoolDepositMalformed",e.void()],["liquidityPoolDepositNoTrust",e.void()],["liquidityPoolDepositNotAuthorized",e.void()],["liquidityPoolDepositUnderfunded",e.void()],["liquidityPoolDepositLineFull",e.void()],["liquidityPoolDepositBadPrice",e.void()],["liquidityPoolDepositPoolFull",e.void()]],arms:{}}),e.enum("LiquidityPoolWithdrawResultCode",{liquidityPoolWithdrawSuccess:0,liquidityPoolWithdrawMalformed:-1,liquidityPoolWithdrawNoTrust:-2,liquidityPoolWithdrawUnderfunded:-3,liquidityPoolWithdrawLineFull:-4,liquidityPoolWithdrawUnderMinimum:-5}),e.union("LiquidityPoolWithdrawResult",{switchOn:e.lookup("LiquidityPoolWithdrawResultCode"),switchName:"code",switches:[["liquidityPoolWithdrawSuccess",e.void()],["liquidityPoolWithdrawMalformed",e.void()],["liquidityPoolWithdrawNoTrust",e.void()],["liquidityPoolWithdrawUnderfunded",e.void()],["liquidityPoolWithdrawLineFull",e.void()],["liquidityPoolWithdrawUnderMinimum",e.void()]],arms:{}}),e.enum("InvokeHostFunctionResultCode",{invokeHostFunctionSuccess:0,invokeHostFunctionMalformed:-1,invokeHostFunctionTrapped:-2,invokeHostFunctionResourceLimitExceeded:-3,invokeHostFunctionEntryArchived:-4,invokeHostFunctionInsufficientRefundableFee:-5}),e.union("InvokeHostFunctionResult",{switchOn:e.lookup("InvokeHostFunctionResultCode"),switchName:"code",switches:[["invokeHostFunctionSuccess","success"],["invokeHostFunctionMalformed",e.void()],["invokeHostFunctionTrapped",e.void()],["invokeHostFunctionResourceLimitExceeded",e.void()],["invokeHostFunctionEntryArchived",e.void()],["invokeHostFunctionInsufficientRefundableFee",e.void()]],arms:{success:e.lookup("Hash")}}),e.enum("ExtendFootprintTtlResultCode",{extendFootprintTtlSuccess:0,extendFootprintTtlMalformed:-1,extendFootprintTtlResourceLimitExceeded:-2,extendFootprintTtlInsufficientRefundableFee:-3}),e.union("ExtendFootprintTtlResult",{switchOn:e.lookup("ExtendFootprintTtlResultCode"),switchName:"code",switches:[["extendFootprintTtlSuccess",e.void()],["extendFootprintTtlMalformed",e.void()],["extendFootprintTtlResourceLimitExceeded",e.void()],["extendFootprintTtlInsufficientRefundableFee",e.void()]],arms:{}}),e.enum("RestoreFootprintResultCode",{restoreFootprintSuccess:0,restoreFootprintMalformed:-1,restoreFootprintResourceLimitExceeded:-2,restoreFootprintInsufficientRefundableFee:-3}),e.union("RestoreFootprintResult",{switchOn:e.lookup("RestoreFootprintResultCode"),switchName:"code",switches:[["restoreFootprintSuccess",e.void()],["restoreFootprintMalformed",e.void()],["restoreFootprintResourceLimitExceeded",e.void()],["restoreFootprintInsufficientRefundableFee",e.void()]],arms:{}}),e.enum("OperationResultCode",{opInner:0,opBadAuth:-1,opNoAccount:-2,opNotSupported:-3,opTooManySubentries:-4,opExceededWorkLimit:-5,opTooManySponsoring:-6}),e.union("OperationResultTr",{switchOn:e.lookup("OperationType"),switchName:"type",switches:[["createAccount","createAccountResult"],["payment","paymentResult"],["pathPaymentStrictReceive","pathPaymentStrictReceiveResult"],["manageSellOffer","manageSellOfferResult"],["createPassiveSellOffer","createPassiveSellOfferResult"],["setOptions","setOptionsResult"],["changeTrust","changeTrustResult"],["allowTrust","allowTrustResult"],["accountMerge","accountMergeResult"],["inflation","inflationResult"],["manageData","manageDataResult"],["bumpSequence","bumpSeqResult"],["manageBuyOffer","manageBuyOfferResult"],["pathPaymentStrictSend","pathPaymentStrictSendResult"],["createClaimableBalance","createClaimableBalanceResult"],["claimClaimableBalance","claimClaimableBalanceResult"],["beginSponsoringFutureReserves","beginSponsoringFutureReservesResult"],["endSponsoringFutureReserves","endSponsoringFutureReservesResult"],["revokeSponsorship","revokeSponsorshipResult"],["clawback","clawbackResult"],["clawbackClaimableBalance","clawbackClaimableBalanceResult"],["setTrustLineFlags","setTrustLineFlagsResult"],["liquidityPoolDeposit","liquidityPoolDepositResult"],["liquidityPoolWithdraw","liquidityPoolWithdrawResult"],["invokeHostFunction","invokeHostFunctionResult"],["extendFootprintTtl","extendFootprintTtlResult"],["restoreFootprint","restoreFootprintResult"]],arms:{createAccountResult:e.lookup("CreateAccountResult"),paymentResult:e.lookup("PaymentResult"),pathPaymentStrictReceiveResult:e.lookup("PathPaymentStrictReceiveResult"),manageSellOfferResult:e.lookup("ManageSellOfferResult"),createPassiveSellOfferResult:e.lookup("ManageSellOfferResult"),setOptionsResult:e.lookup("SetOptionsResult"),changeTrustResult:e.lookup("ChangeTrustResult"),allowTrustResult:e.lookup("AllowTrustResult"),accountMergeResult:e.lookup("AccountMergeResult"),inflationResult:e.lookup("InflationResult"),manageDataResult:e.lookup("ManageDataResult"),bumpSeqResult:e.lookup("BumpSequenceResult"),manageBuyOfferResult:e.lookup("ManageBuyOfferResult"),pathPaymentStrictSendResult:e.lookup("PathPaymentStrictSendResult"),createClaimableBalanceResult:e.lookup("CreateClaimableBalanceResult"),claimClaimableBalanceResult:e.lookup("ClaimClaimableBalanceResult"),beginSponsoringFutureReservesResult:e.lookup("BeginSponsoringFutureReservesResult"),endSponsoringFutureReservesResult:e.lookup("EndSponsoringFutureReservesResult"),revokeSponsorshipResult:e.lookup("RevokeSponsorshipResult"),clawbackResult:e.lookup("ClawbackResult"),clawbackClaimableBalanceResult:e.lookup("ClawbackClaimableBalanceResult"),setTrustLineFlagsResult:e.lookup("SetTrustLineFlagsResult"),liquidityPoolDepositResult:e.lookup("LiquidityPoolDepositResult"),liquidityPoolWithdrawResult:e.lookup("LiquidityPoolWithdrawResult"),invokeHostFunctionResult:e.lookup("InvokeHostFunctionResult"),extendFootprintTtlResult:e.lookup("ExtendFootprintTtlResult"),restoreFootprintResult:e.lookup("RestoreFootprintResult")}}),e.union("OperationResult",{switchOn:e.lookup("OperationResultCode"),switchName:"code",switches:[["opInner","tr"],["opBadAuth",e.void()],["opNoAccount",e.void()],["opNotSupported",e.void()],["opTooManySubentries",e.void()],["opExceededWorkLimit",e.void()],["opTooManySponsoring",e.void()]],arms:{tr:e.lookup("OperationResultTr")}}),e.enum("TransactionResultCode",{txFeeBumpInnerSuccess:1,txSuccess:0,txFailed:-1,txTooEarly:-2,txTooLate:-3,txMissingOperation:-4,txBadSeq:-5,txBadAuth:-6,txInsufficientBalance:-7,txNoAccount:-8,txInsufficientFee:-9,txBadAuthExtra:-10,txInternalError:-11,txNotSupported:-12,txFeeBumpInnerFailed:-13,txBadSponsorship:-14,txBadMinSeqAgeOrGap:-15,txMalformed:-16,txSorobanInvalid:-17}),e.union("InnerTransactionResultResult",{switchOn:e.lookup("TransactionResultCode"),switchName:"code",switches:[["txSuccess","results"],["txFailed","results"],["txTooEarly",e.void()],["txTooLate",e.void()],["txMissingOperation",e.void()],["txBadSeq",e.void()],["txBadAuth",e.void()],["txInsufficientBalance",e.void()],["txNoAccount",e.void()],["txInsufficientFee",e.void()],["txBadAuthExtra",e.void()],["txInternalError",e.void()],["txNotSupported",e.void()],["txBadSponsorship",e.void()],["txBadMinSeqAgeOrGap",e.void()],["txMalformed",e.void()],["txSorobanInvalid",e.void()]],arms:{results:e.varArray(e.lookup("OperationResult"),2147483647)}}),e.union("InnerTransactionResultExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("InnerTransactionResult",[["feeCharged",e.lookup("Int64")],["result",e.lookup("InnerTransactionResultResult")],["ext",e.lookup("InnerTransactionResultExt")]]),e.struct("InnerTransactionResultPair",[["transactionHash",e.lookup("Hash")],["result",e.lookup("InnerTransactionResult")]]),e.union("TransactionResultResult",{switchOn:e.lookup("TransactionResultCode"),switchName:"code",switches:[["txFeeBumpInnerSuccess","innerResultPair"],["txFeeBumpInnerFailed","innerResultPair"],["txSuccess","results"],["txFailed","results"],["txTooEarly",e.void()],["txTooLate",e.void()],["txMissingOperation",e.void()],["txBadSeq",e.void()],["txBadAuth",e.void()],["txInsufficientBalance",e.void()],["txNoAccount",e.void()],["txInsufficientFee",e.void()],["txBadAuthExtra",e.void()],["txInternalError",e.void()],["txNotSupported",e.void()],["txBadSponsorship",e.void()],["txBadMinSeqAgeOrGap",e.void()],["txMalformed",e.void()],["txSorobanInvalid",e.void()]],arms:{innerResultPair:e.lookup("InnerTransactionResultPair"),results:e.varArray(e.lookup("OperationResult"),2147483647)}}),e.union("TransactionResultExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionResult",[["feeCharged",e.lookup("Int64")],["result",e.lookup("TransactionResultResult")],["ext",e.lookup("TransactionResultExt")]]),e.typedef("Hash",e.opaque(32)),e.typedef("Uint256",e.opaque(32)),e.typedef("Uint32",e.uint()),e.typedef("Int32",e.int()),e.typedef("Uint64",e.uhyper()),e.typedef("Int64",e.hyper()),e.typedef("TimePoint",e.lookup("Uint64")),e.typedef("Duration",e.lookup("Uint64")),e.union("ExtensionPoint",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.enum("CryptoKeyType",{keyTypeEd25519:0,keyTypePreAuthTx:1,keyTypeHashX:2,keyTypeEd25519SignedPayload:3,keyTypeMuxedEd25519:256}),e.enum("PublicKeyType",{publicKeyTypeEd25519:0}),e.enum("SignerKeyType",{signerKeyTypeEd25519:0,signerKeyTypePreAuthTx:1,signerKeyTypeHashX:2,signerKeyTypeEd25519SignedPayload:3}),e.union("PublicKey",{switchOn:e.lookup("PublicKeyType"),switchName:"type",switches:[["publicKeyTypeEd25519","ed25519"]],arms:{ed25519:e.lookup("Uint256")}}),e.struct("SignerKeyEd25519SignedPayload",[["ed25519",e.lookup("Uint256")],["payload",e.varOpaque(64)]]),e.union("SignerKey",{switchOn:e.lookup("SignerKeyType"),switchName:"type",switches:[["signerKeyTypeEd25519","ed25519"],["signerKeyTypePreAuthTx","preAuthTx"],["signerKeyTypeHashX","hashX"],["signerKeyTypeEd25519SignedPayload","ed25519SignedPayload"]],arms:{ed25519:e.lookup("Uint256"),preAuthTx:e.lookup("Uint256"),hashX:e.lookup("Uint256"),ed25519SignedPayload:e.lookup("SignerKeyEd25519SignedPayload")}}),e.typedef("Signature",e.varOpaque(64)),e.typedef("SignatureHint",e.opaque(4)),e.typedef("NodeId",e.lookup("PublicKey")),e.typedef("AccountId",e.lookup("PublicKey")),e.struct("Curve25519Secret",[["key",e.opaque(32)]]),e.struct("Curve25519Public",[["key",e.opaque(32)]]),e.struct("HmacSha256Key",[["key",e.opaque(32)]]),e.struct("HmacSha256Mac",[["mac",e.opaque(32)]]),e.struct("ShortHashSeed",[["seed",e.opaque(16)]]),e.enum("BinaryFuseFilterType",{binaryFuseFilter8Bit:0,binaryFuseFilter16Bit:1,binaryFuseFilter32Bit:2}),e.struct("SerializedBinaryFuseFilter",[["type",e.lookup("BinaryFuseFilterType")],["inputHashSeed",e.lookup("ShortHashSeed")],["filterSeed",e.lookup("ShortHashSeed")],["segmentLength",e.lookup("Uint32")],["segementLengthMask",e.lookup("Uint32")],["segmentCount",e.lookup("Uint32")],["segmentCountLength",e.lookup("Uint32")],["fingerprintLength",e.lookup("Uint32")],["fingerprints",e.varOpaque()]]),e.enum("ScValType",{scvBool:0,scvVoid:1,scvError:2,scvU32:3,scvI32:4,scvU64:5,scvI64:6,scvTimepoint:7,scvDuration:8,scvU128:9,scvI128:10,scvU256:11,scvI256:12,scvBytes:13,scvString:14,scvSymbol:15,scvVec:16,scvMap:17,scvAddress:18,scvContractInstance:19,scvLedgerKeyContractInstance:20,scvLedgerKeyNonce:21}),e.enum("ScErrorType",{sceContract:0,sceWasmVm:1,sceContext:2,sceStorage:3,sceObject:4,sceCrypto:5,sceEvents:6,sceBudget:7,sceValue:8,sceAuth:9}),e.enum("ScErrorCode",{scecArithDomain:0,scecIndexBounds:1,scecInvalidInput:2,scecMissingValue:3,scecExistingValue:4,scecExceededLimit:5,scecInvalidAction:6,scecInternalError:7,scecUnexpectedType:8,scecUnexpectedSize:9}),e.union("ScError",{switchOn:e.lookup("ScErrorType"),switchName:"type",switches:[["sceContract","contractCode"],["sceWasmVm","code"],["sceContext","code"],["sceStorage","code"],["sceObject","code"],["sceCrypto","code"],["sceEvents","code"],["sceBudget","code"],["sceValue","code"],["sceAuth","code"]],arms:{contractCode:e.lookup("Uint32"),code:e.lookup("ScErrorCode")}}),e.struct("UInt128Parts",[["hi",e.lookup("Uint64")],["lo",e.lookup("Uint64")]]),e.struct("Int128Parts",[["hi",e.lookup("Int64")],["lo",e.lookup("Uint64")]]),e.struct("UInt256Parts",[["hiHi",e.lookup("Uint64")],["hiLo",e.lookup("Uint64")],["loHi",e.lookup("Uint64")],["loLo",e.lookup("Uint64")]]),e.struct("Int256Parts",[["hiHi",e.lookup("Int64")],["hiLo",e.lookup("Uint64")],["loHi",e.lookup("Uint64")],["loLo",e.lookup("Uint64")]]),e.enum("ContractExecutableType",{contractExecutableWasm:0,contractExecutableStellarAsset:1}),e.union("ContractExecutable",{switchOn:e.lookup("ContractExecutableType"),switchName:"type",switches:[["contractExecutableWasm","wasmHash"],["contractExecutableStellarAsset",e.void()]],arms:{wasmHash:e.lookup("Hash")}}),e.enum("ScAddressType",{scAddressTypeAccount:0,scAddressTypeContract:1}),e.union("ScAddress",{switchOn:e.lookup("ScAddressType"),switchName:"type",switches:[["scAddressTypeAccount","accountId"],["scAddressTypeContract","contractId"]],arms:{accountId:e.lookup("AccountId"),contractId:e.lookup("Hash")}}),e.const("SCSYMBOL_LIMIT",32),e.typedef("ScVec",e.varArray(e.lookup("ScVal"),2147483647)),e.typedef("ScMap",e.varArray(e.lookup("ScMapEntry"),2147483647)),e.typedef("ScBytes",e.varOpaque()),e.typedef("ScString",e.string()),e.typedef("ScSymbol",e.string(32)),e.struct("ScNonceKey",[["nonce",e.lookup("Int64")]]),e.struct("ScContractInstance",[["executable",e.lookup("ContractExecutable")],["storage",e.option(e.lookup("ScMap"))]]),e.union("ScVal",{switchOn:e.lookup("ScValType"),switchName:"type",switches:[["scvBool","b"],["scvVoid",e.void()],["scvError","error"],["scvU32","u32"],["scvI32","i32"],["scvU64","u64"],["scvI64","i64"],["scvTimepoint","timepoint"],["scvDuration","duration"],["scvU128","u128"],["scvI128","i128"],["scvU256","u256"],["scvI256","i256"],["scvBytes","bytes"],["scvString","str"],["scvSymbol","sym"],["scvVec","vec"],["scvMap","map"],["scvAddress","address"],["scvLedgerKeyContractInstance",e.void()],["scvLedgerKeyNonce","nonceKey"],["scvContractInstance","instance"]],arms:{b:e.bool(),error:e.lookup("ScError"),u32:e.lookup("Uint32"),i32:e.lookup("Int32"),u64:e.lookup("Uint64"),i64:e.lookup("Int64"),timepoint:e.lookup("TimePoint"),duration:e.lookup("Duration"),u128:e.lookup("UInt128Parts"),i128:e.lookup("Int128Parts"),u256:e.lookup("UInt256Parts"),i256:e.lookup("Int256Parts"),bytes:e.lookup("ScBytes"),str:e.lookup("ScString"),sym:e.lookup("ScSymbol"),vec:e.option(e.lookup("ScVec")),map:e.option(e.lookup("ScMap")),address:e.lookup("ScAddress"),nonceKey:e.lookup("ScNonceKey"),instance:e.lookup("ScContractInstance")}}),e.struct("ScMapEntry",[["key",e.lookup("ScVal")],["val",e.lookup("ScVal")]]),e.enum("ScEnvMetaKind",{scEnvMetaKindInterfaceVersion:0}),e.struct("ScEnvMetaEntryInterfaceVersion",[["protocol",e.lookup("Uint32")],["preRelease",e.lookup("Uint32")]]),e.union("ScEnvMetaEntry",{switchOn:e.lookup("ScEnvMetaKind"),switchName:"kind",switches:[["scEnvMetaKindInterfaceVersion","interfaceVersion"]],arms:{interfaceVersion:e.lookup("ScEnvMetaEntryInterfaceVersion")}}),e.struct("ScMetaV0",[["key",e.string()],["val",e.string()]]),e.enum("ScMetaKind",{scMetaV0:0}),e.union("ScMetaEntry",{switchOn:e.lookup("ScMetaKind"),switchName:"kind",switches:[["scMetaV0","v0"]],arms:{v0:e.lookup("ScMetaV0")}}),e.const("SC_SPEC_DOC_LIMIT",1024),e.enum("ScSpecType",{scSpecTypeVal:0,scSpecTypeBool:1,scSpecTypeVoid:2,scSpecTypeError:3,scSpecTypeU32:4,scSpecTypeI32:5,scSpecTypeU64:6,scSpecTypeI64:7,scSpecTypeTimepoint:8,scSpecTypeDuration:9,scSpecTypeU128:10,scSpecTypeI128:11,scSpecTypeU256:12,scSpecTypeI256:13,scSpecTypeBytes:14,scSpecTypeString:16,scSpecTypeSymbol:17,scSpecTypeAddress:19,scSpecTypeOption:1e3,scSpecTypeResult:1001,scSpecTypeVec:1002,scSpecTypeMap:1004,scSpecTypeTuple:1005,scSpecTypeBytesN:1006,scSpecTypeUdt:2e3}),e.struct("ScSpecTypeOption",[["valueType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeResult",[["okType",e.lookup("ScSpecTypeDef")],["errorType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeVec",[["elementType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeMap",[["keyType",e.lookup("ScSpecTypeDef")],["valueType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeTuple",[["valueTypes",e.varArray(e.lookup("ScSpecTypeDef"),12)]]),e.struct("ScSpecTypeBytesN",[["n",e.lookup("Uint32")]]),e.struct("ScSpecTypeUdt",[["name",e.string(60)]]),e.union("ScSpecTypeDef",{switchOn:e.lookup("ScSpecType"),switchName:"type",switches:[["scSpecTypeVal",e.void()],["scSpecTypeBool",e.void()],["scSpecTypeVoid",e.void()],["scSpecTypeError",e.void()],["scSpecTypeU32",e.void()],["scSpecTypeI32",e.void()],["scSpecTypeU64",e.void()],["scSpecTypeI64",e.void()],["scSpecTypeTimepoint",e.void()],["scSpecTypeDuration",e.void()],["scSpecTypeU128",e.void()],["scSpecTypeI128",e.void()],["scSpecTypeU256",e.void()],["scSpecTypeI256",e.void()],["scSpecTypeBytes",e.void()],["scSpecTypeString",e.void()],["scSpecTypeSymbol",e.void()],["scSpecTypeAddress",e.void()],["scSpecTypeOption","option"],["scSpecTypeResult","result"],["scSpecTypeVec","vec"],["scSpecTypeMap","map"],["scSpecTypeTuple","tuple"],["scSpecTypeBytesN","bytesN"],["scSpecTypeUdt","udt"]],arms:{option:e.lookup("ScSpecTypeOption"),result:e.lookup("ScSpecTypeResult"),vec:e.lookup("ScSpecTypeVec"),map:e.lookup("ScSpecTypeMap"),tuple:e.lookup("ScSpecTypeTuple"),bytesN:e.lookup("ScSpecTypeBytesN"),udt:e.lookup("ScSpecTypeUdt")}}),e.struct("ScSpecUdtStructFieldV0",[["doc",e.string(t)],["name",e.string(30)],["type",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecUdtStructV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["fields",e.varArray(e.lookup("ScSpecUdtStructFieldV0"),40)]]),e.struct("ScSpecUdtUnionCaseVoidV0",[["doc",e.string(t)],["name",e.string(60)]]),e.struct("ScSpecUdtUnionCaseTupleV0",[["doc",e.string(t)],["name",e.string(60)],["type",e.varArray(e.lookup("ScSpecTypeDef"),12)]]),e.enum("ScSpecUdtUnionCaseV0Kind",{scSpecUdtUnionCaseVoidV0:0,scSpecUdtUnionCaseTupleV0:1}),e.union("ScSpecUdtUnionCaseV0",{switchOn:e.lookup("ScSpecUdtUnionCaseV0Kind"),switchName:"kind",switches:[["scSpecUdtUnionCaseVoidV0","voidCase"],["scSpecUdtUnionCaseTupleV0","tupleCase"]],arms:{voidCase:e.lookup("ScSpecUdtUnionCaseVoidV0"),tupleCase:e.lookup("ScSpecUdtUnionCaseTupleV0")}}),e.struct("ScSpecUdtUnionV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtUnionCaseV0"),50)]]),e.struct("ScSpecUdtEnumCaseV0",[["doc",e.string(t)],["name",e.string(60)],["value",e.lookup("Uint32")]]),e.struct("ScSpecUdtEnumV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtEnumCaseV0"),50)]]),e.struct("ScSpecUdtErrorEnumCaseV0",[["doc",e.string(t)],["name",e.string(60)],["value",e.lookup("Uint32")]]),e.struct("ScSpecUdtErrorEnumV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtErrorEnumCaseV0"),50)]]),e.struct("ScSpecFunctionInputV0",[["doc",e.string(t)],["name",e.string(30)],["type",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecFunctionV0",[["doc",e.string(t)],["name",e.lookup("ScSymbol")],["inputs",e.varArray(e.lookup("ScSpecFunctionInputV0"),10)],["outputs",e.varArray(e.lookup("ScSpecTypeDef"),1)]]),e.enum("ScSpecEntryKind",{scSpecEntryFunctionV0:0,scSpecEntryUdtStructV0:1,scSpecEntryUdtUnionV0:2,scSpecEntryUdtEnumV0:3,scSpecEntryUdtErrorEnumV0:4}),e.union("ScSpecEntry",{switchOn:e.lookup("ScSpecEntryKind"),switchName:"kind",switches:[["scSpecEntryFunctionV0","functionV0"],["scSpecEntryUdtStructV0","udtStructV0"],["scSpecEntryUdtUnionV0","udtUnionV0"],["scSpecEntryUdtEnumV0","udtEnumV0"],["scSpecEntryUdtErrorEnumV0","udtErrorEnumV0"]],arms:{functionV0:e.lookup("ScSpecFunctionV0"),udtStructV0:e.lookup("ScSpecUdtStructV0"),udtUnionV0:e.lookup("ScSpecUdtUnionV0"),udtEnumV0:e.lookup("ScSpecUdtEnumV0"),udtErrorEnumV0:e.lookup("ScSpecUdtErrorEnumV0")}}),e.struct("ConfigSettingContractExecutionLanesV0",[["ledgerMaxTxCount",e.lookup("Uint32")]]),e.struct("ConfigSettingContractComputeV0",[["ledgerMaxInstructions",e.lookup("Int64")],["txMaxInstructions",e.lookup("Int64")],["feeRatePerInstructionsIncrement",e.lookup("Int64")],["txMemoryLimit",e.lookup("Uint32")]]),e.struct("ConfigSettingContractLedgerCostV0",[["ledgerMaxReadLedgerEntries",e.lookup("Uint32")],["ledgerMaxReadBytes",e.lookup("Uint32")],["ledgerMaxWriteLedgerEntries",e.lookup("Uint32")],["ledgerMaxWriteBytes",e.lookup("Uint32")],["txMaxReadLedgerEntries",e.lookup("Uint32")],["txMaxReadBytes",e.lookup("Uint32")],["txMaxWriteLedgerEntries",e.lookup("Uint32")],["txMaxWriteBytes",e.lookup("Uint32")],["feeReadLedgerEntry",e.lookup("Int64")],["feeWriteLedgerEntry",e.lookup("Int64")],["feeRead1Kb",e.lookup("Int64")],["bucketListTargetSizeBytes",e.lookup("Int64")],["writeFee1KbBucketListLow",e.lookup("Int64")],["writeFee1KbBucketListHigh",e.lookup("Int64")],["bucketListWriteFeeGrowthFactor",e.lookup("Uint32")]]),e.struct("ConfigSettingContractHistoricalDataV0",[["feeHistorical1Kb",e.lookup("Int64")]]),e.struct("ConfigSettingContractEventsV0",[["txMaxContractEventsSizeBytes",e.lookup("Uint32")],["feeContractEvents1Kb",e.lookup("Int64")]]),e.struct("ConfigSettingContractBandwidthV0",[["ledgerMaxTxsSizeBytes",e.lookup("Uint32")],["txMaxSizeBytes",e.lookup("Uint32")],["feeTxSize1Kb",e.lookup("Int64")]]),e.enum("ContractCostType",{wasmInsnExec:0,memAlloc:1,memCpy:2,memCmp:3,dispatchHostFunction:4,visitObject:5,valSer:6,valDeser:7,computeSha256Hash:8,computeEd25519PubKey:9,verifyEd25519Sig:10,vmInstantiation:11,vmCachedInstantiation:12,invokeVmFunction:13,computeKeccak256Hash:14,decodeEcdsaCurve256Sig:15,recoverEcdsaSecp256k1Key:16,int256AddSub:17,int256Mul:18,int256Div:19,int256Pow:20,int256Shift:21,chaCha20DrawBytes:22,parseWasmInstructions:23,parseWasmFunctions:24,parseWasmGlobals:25,parseWasmTableEntries:26,parseWasmTypes:27,parseWasmDataSegments:28,parseWasmElemSegments:29,parseWasmImports:30,parseWasmExports:31,parseWasmDataSegmentBytes:32,instantiateWasmInstructions:33,instantiateWasmFunctions:34,instantiateWasmGlobals:35,instantiateWasmTableEntries:36,instantiateWasmTypes:37,instantiateWasmDataSegments:38,instantiateWasmElemSegments:39,instantiateWasmImports:40,instantiateWasmExports:41,instantiateWasmDataSegmentBytes:42,sec1DecodePointUncompressed:43,verifyEcdsaSecp256r1Sig:44,bls12381EncodeFp:45,bls12381DecodeFp:46,bls12381G1CheckPointOnCurve:47,bls12381G1CheckPointInSubgroup:48,bls12381G2CheckPointOnCurve:49,bls12381G2CheckPointInSubgroup:50,bls12381G1ProjectiveToAffine:51,bls12381G2ProjectiveToAffine:52,bls12381G1Add:53,bls12381G1Mul:54,bls12381G1Msm:55,bls12381MapFpToG1:56,bls12381HashToG1:57,bls12381G2Add:58,bls12381G2Mul:59,bls12381G2Msm:60,bls12381MapFp2ToG2:61,bls12381HashToG2:62,bls12381Pairing:63,bls12381FrFromU256:64,bls12381FrToU256:65,bls12381FrAddSub:66,bls12381FrMul:67,bls12381FrPow:68,bls12381FrInv:69}),e.struct("ContractCostParamEntry",[["ext",e.lookup("ExtensionPoint")],["constTerm",e.lookup("Int64")],["linearTerm",e.lookup("Int64")]]),e.struct("StateArchivalSettings",[["maxEntryTtl",e.lookup("Uint32")],["minTemporaryTtl",e.lookup("Uint32")],["minPersistentTtl",e.lookup("Uint32")],["persistentRentRateDenominator",e.lookup("Int64")],["tempRentRateDenominator",e.lookup("Int64")],["maxEntriesToArchive",e.lookup("Uint32")],["bucketListSizeWindowSampleSize",e.lookup("Uint32")],["bucketListWindowSamplePeriod",e.lookup("Uint32")],["evictionScanSize",e.lookup("Uint32")],["startingEvictionScanLevel",e.lookup("Uint32")]]),e.struct("EvictionIterator",[["bucketListLevel",e.lookup("Uint32")],["isCurrBucket",e.bool()],["bucketFileOffset",e.lookup("Uint64")]]),e.const("CONTRACT_COST_COUNT_LIMIT",1024),e.typedef("ContractCostParams",e.varArray(e.lookup("ContractCostParamEntry"),e.lookup("CONTRACT_COST_COUNT_LIMIT"))),e.enum("ConfigSettingId",{configSettingContractMaxSizeBytes:0,configSettingContractComputeV0:1,configSettingContractLedgerCostV0:2,configSettingContractHistoricalDataV0:3,configSettingContractEventsV0:4,configSettingContractBandwidthV0:5,configSettingContractCostParamsCpuInstructions:6,configSettingContractCostParamsMemoryBytes:7,configSettingContractDataKeySizeBytes:8,configSettingContractDataEntrySizeBytes:9,configSettingStateArchival:10,configSettingContractExecutionLanes:11,configSettingBucketlistSizeWindow:12,configSettingEvictionIterator:13}),e.union("ConfigSettingEntry",{switchOn:e.lookup("ConfigSettingId"),switchName:"configSettingId",switches:[["configSettingContractMaxSizeBytes","contractMaxSizeBytes"],["configSettingContractComputeV0","contractCompute"],["configSettingContractLedgerCostV0","contractLedgerCost"],["configSettingContractHistoricalDataV0","contractHistoricalData"],["configSettingContractEventsV0","contractEvents"],["configSettingContractBandwidthV0","contractBandwidth"],["configSettingContractCostParamsCpuInstructions","contractCostParamsCpuInsns"],["configSettingContractCostParamsMemoryBytes","contractCostParamsMemBytes"],["configSettingContractDataKeySizeBytes","contractDataKeySizeBytes"],["configSettingContractDataEntrySizeBytes","contractDataEntrySizeBytes"],["configSettingStateArchival","stateArchivalSettings"],["configSettingContractExecutionLanes","contractExecutionLanes"],["configSettingBucketlistSizeWindow","bucketListSizeWindow"],["configSettingEvictionIterator","evictionIterator"]],arms:{contractMaxSizeBytes:e.lookup("Uint32"),contractCompute:e.lookup("ConfigSettingContractComputeV0"),contractLedgerCost:e.lookup("ConfigSettingContractLedgerCostV0"),contractHistoricalData:e.lookup("ConfigSettingContractHistoricalDataV0"),contractEvents:e.lookup("ConfigSettingContractEventsV0"),contractBandwidth:e.lookup("ConfigSettingContractBandwidthV0"),contractCostParamsCpuInsns:e.lookup("ContractCostParams"),contractCostParamsMemBytes:e.lookup("ContractCostParams"),contractDataKeySizeBytes:e.lookup("Uint32"),contractDataEntrySizeBytes:e.lookup("Uint32"),stateArchivalSettings:e.lookup("StateArchivalSettings"),contractExecutionLanes:e.lookup("ConfigSettingContractExecutionLanesV0"),bucketListSizeWindow:e.varArray(e.lookup("Uint64"),2147483647),evictionIterator:e.lookup("EvictionIterator")}})}));t.default=i},5578:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.LiquidityPoolFeeV18=void 0,t.getLiquidityPoolId=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("constant_product"!==e)throw new Error("liquidityPoolType is invalid");var r=t.assetA,o=t.assetB,c=t.fee;if(!(r&&r instanceof a.Asset))throw new Error("assetA is invalid");if(!(o&&o instanceof a.Asset))throw new Error("assetB is invalid");if(!c||c!==s)throw new Error("fee is invalid");if(-1!==a.Asset.compare(r,o))throw new Error("Assets are not in lexicographic order");var l=i.default.LiquidityPoolType.liquidityPoolConstantProduct().toXDR(),f=new i.default.LiquidityPoolConstantProductParameters({assetA:r.toXDRObject(),assetB:o.toXDRObject(),fee:c}).toXDR(),p=n.concat([l,f]);return(0,u.hash)(p)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(1764),u=r(9152);var s=t.LiquidityPoolFeeV18=30},9152:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hash=function(e){var t=new n.sha256;return t.update(e,"utf8"),t.digest()};var n=r(2802)},356:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={xdr:!0,cereal:!0,hash:!0,sign:!0,verify:!0,FastSigning:!0,getLiquidityPoolId:!0,LiquidityPoolFeeV18:!0,Keypair:!0,UnsignedHyper:!0,Hyper:!0,TransactionBase:!0,Transaction:!0,FeeBumpTransaction:!0,TransactionBuilder:!0,TimeoutInfinite:!0,BASE_FEE:!0,Asset:!0,LiquidityPoolAsset:!0,LiquidityPoolId:!0,Operation:!0,AuthRequiredFlag:!0,AuthRevocableFlag:!0,AuthImmutableFlag:!0,AuthClawbackEnabledFlag:!0,Account:!0,MuxedAccount:!0,Claimant:!0,Networks:!0,StrKey:!0,SignerKey:!0,Soroban:!0,decodeAddressToMuxedAccount:!0,encodeMuxedAccountToAddress:!0,extractBaseAddress:!0,encodeMuxedAccount:!0,Contract:!0,Address:!0};Object.defineProperty(t,"Account",{enumerable:!0,get:function(){return w.Account}}),Object.defineProperty(t,"Address",{enumerable:!0,get:function(){return P.Address}}),Object.defineProperty(t,"Asset",{enumerable:!0,get:function(){return y.Asset}}),Object.defineProperty(t,"AuthClawbackEnabledFlag",{enumerable:!0,get:function(){return g.AuthClawbackEnabledFlag}}),Object.defineProperty(t,"AuthImmutableFlag",{enumerable:!0,get:function(){return g.AuthImmutableFlag}}),Object.defineProperty(t,"AuthRequiredFlag",{enumerable:!0,get:function(){return g.AuthRequiredFlag}}),Object.defineProperty(t,"AuthRevocableFlag",{enumerable:!0,get:function(){return g.AuthRevocableFlag}}),Object.defineProperty(t,"BASE_FEE",{enumerable:!0,get:function(){return h.BASE_FEE}}),Object.defineProperty(t,"Claimant",{enumerable:!0,get:function(){return k.Claimant}}),Object.defineProperty(t,"Contract",{enumerable:!0,get:function(){return A.Contract}}),Object.defineProperty(t,"FastSigning",{enumerable:!0,get:function(){return u.FastSigning}}),Object.defineProperty(t,"FeeBumpTransaction",{enumerable:!0,get:function(){return d.FeeBumpTransaction}}),Object.defineProperty(t,"Hyper",{enumerable:!0,get:function(){return l.Hyper}}),Object.defineProperty(t,"Keypair",{enumerable:!0,get:function(){return c.Keypair}}),Object.defineProperty(t,"LiquidityPoolAsset",{enumerable:!0,get:function(){return m.LiquidityPoolAsset}}),Object.defineProperty(t,"LiquidityPoolFeeV18",{enumerable:!0,get:function(){return s.LiquidityPoolFeeV18}}),Object.defineProperty(t,"LiquidityPoolId",{enumerable:!0,get:function(){return v.LiquidityPoolId}}),Object.defineProperty(t,"MuxedAccount",{enumerable:!0,get:function(){return S.MuxedAccount}}),Object.defineProperty(t,"Networks",{enumerable:!0,get:function(){return E.Networks}}),Object.defineProperty(t,"Operation",{enumerable:!0,get:function(){return g.Operation}}),Object.defineProperty(t,"SignerKey",{enumerable:!0,get:function(){return T.SignerKey}}),Object.defineProperty(t,"Soroban",{enumerable:!0,get:function(){return O.Soroban}}),Object.defineProperty(t,"StrKey",{enumerable:!0,get:function(){return _.StrKey}}),Object.defineProperty(t,"TimeoutInfinite",{enumerable:!0,get:function(){return h.TimeoutInfinite}}),Object.defineProperty(t,"Transaction",{enumerable:!0,get:function(){return p.Transaction}}),Object.defineProperty(t,"TransactionBase",{enumerable:!0,get:function(){return f.TransactionBase}}),Object.defineProperty(t,"TransactionBuilder",{enumerable:!0,get:function(){return h.TransactionBuilder}}),Object.defineProperty(t,"UnsignedHyper",{enumerable:!0,get:function(){return l.UnsignedHyper}}),Object.defineProperty(t,"cereal",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(t,"decodeAddressToMuxedAccount",{enumerable:!0,get:function(){return x.decodeAddressToMuxedAccount}}),t.default=void 0,Object.defineProperty(t,"encodeMuxedAccount",{enumerable:!0,get:function(){return x.encodeMuxedAccount}}),Object.defineProperty(t,"encodeMuxedAccountToAddress",{enumerable:!0,get:function(){return x.encodeMuxedAccountToAddress}}),Object.defineProperty(t,"extractBaseAddress",{enumerable:!0,get:function(){return x.extractBaseAddress}}),Object.defineProperty(t,"getLiquidityPoolId",{enumerable:!0,get:function(){return s.getLiquidityPoolId}}),Object.defineProperty(t,"hash",{enumerable:!0,get:function(){return a.hash}}),Object.defineProperty(t,"sign",{enumerable:!0,get:function(){return u.sign}}),Object.defineProperty(t,"verify",{enumerable:!0,get:function(){return u.verify}}),Object.defineProperty(t,"xdr",{enumerable:!0,get:function(){return o.default}});var o=N(r(1918)),i=N(r(3335)),a=r(9152),u=r(15),s=r(5578),c=r(6691),l=r(3740),f=r(3758),p=r(380),d=r(9260),h=r(6396),y=r(1764),m=r(2262),v=r(9353),g=r(7237),b=r(4172);Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===b[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return b[e]}}))}));var w=r(2135),S=r(2243),k=r(1387),E=r(6202),_=r(7120),T=r(225),O=r(4062),x=r(6160),A=r(7452),P=r(1180),I=r(8549);Object.keys(I).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===I[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return I[e]}}))}));var R=r(7177);Object.keys(R).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===R[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return R[e]}}))}));var C=r(3919);Object.keys(C).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===C[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return C[e]}}))}));var j=r(4842);Object.keys(j).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===j[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return j[e]}}))}));var B=r(5328);Object.keys(B).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===B[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return B[e]}}))}));var L=r(3564);function N(e){return e&&e.__esModule?e:{default:e}}Object.keys(L).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===L[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return L[e]}}))}));t.default=e.exports},3564:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildInvocationTree=function e(t){var r=t.function(),a={},c=r.value();switch(r.switch().value){case 0:a.type="execute",a.args={source:o.Address.fromScAddress(c.contractAddress()).toString(),function:c.functionName(),args:c.args().map((function(e){return(0,i.scValToNative)(e)}))};break;case 1:case 2:var l=2===r.switch().value;a.type="create",a.args={};var f=[c.executable(),c.contractIdPreimage()],p=f[0],d=f[1];if(!!p.switch().value!=!!d.switch().value)throw new Error("creation function appears invalid: ".concat(JSON.stringify(c)," (should be wasm+address or token+asset)"));switch(p.switch().value){case 0:var h=d.fromAddress();a.args.type="wasm",a.args.wasm=function(e){for(var t=1;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(3740),o={XdrWriter:n.XdrWriter,XdrReader:n.XdrReader};t.default=o},6691:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.Keypair=void 0;var o=c(r(4940)),i=r(15),a=r(7120),u=r(9152),s=c(r(1918));function c(e){return e&&e.__esModule?e:{default:e}}function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LiquidityPoolAsset=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(1764),a=r(5578);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function s(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function c(e){for(var t=1;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LiquidityPoolId=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n};function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.MemoText=t.MemoReturn=t.MemoNone=t.MemoID=t.MemoHash=t.Memo=void 0;var o=r(3740),i=u(r(1242)),a=u(r(1918));function u(e){return e&&e.__esModule?e:{default:e}}function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function c(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:null;switch(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._type=t,this._value=r,this._type){case f:break;case p:e._validateIdValue(r);break;case d:e._validateTextValue(r);break;case h:case y:e._validateHashValue(r),"string"==typeof r&&(this._value=n.from(r,"hex"));break;default:throw new Error("Invalid memo type")}}return t=e,u=[{key:"_validateIdValue",value:function(e){var t,r=new Error("Expects a int64 as a string. Got ".concat(e));if("string"!=typeof e)throw r;try{t=new i.default(e)}catch(e){throw r}if(!t.isFinite())throw r;if(t.isNaN())throw r}},{key:"_validateTextValue",value:function(e){if(!a.default.Memo.armTypeForArm("text").isValid(e))throw new Error("Expects string, array or buffer, max 28 bytes")}},{key:"_validateHashValue",value:function(e){var t,r=new Error("Expects a 32 byte hash value or hex encoded string. Got ".concat(e));if(null==e)throw r;if("string"==typeof e){if(!/^[0-9A-Fa-f]{64}$/g.test(e))throw r;t=n.from(e,"hex")}else{if(!n.isBuffer(e))throw r;t=n.from(e)}if(!t.length||32!==t.length)throw r}},{key:"none",value:function(){return new e(f)}},{key:"text",value:function(t){return new e(d,t)}},{key:"id",value:function(t){return new e(p,t)}},{key:"hash",value:function(t){return new e(h,t)}},{key:"return",value:function(t){return new e(y,t)}},{key:"fromXDRObject",value:function(t){switch(t.arm()){case"id":return e.id(t.value().toString());case"text":return e.text(t.value());case"hash":return e.hash(t.value());case"retHash":return e.return(t.value())}if(void 0===t.value())return e.none();throw new Error("Unknown type")}}],(r=[{key:"type",get:function(){return this._type},set:function(e){throw new Error("Memo is immutable")}},{key:"value",get:function(){switch(this._type){case f:return null;case p:case d:return this._value;case h:case y:return n.from(this._value);default:throw new Error("Invalid memo type")}},set:function(e){throw new Error("Memo is immutable")}},{key:"toXDRObject",value:function(){switch(this._type){case f:return a.default.Memo.memoNone();case p:return a.default.Memo.memoId(o.UnsignedHyper.fromString(this._value));case d:return a.default.Memo.memoText(this._value);case h:return a.default.Memo.memoHash(this._value);case y:return a.default.Memo.memoReturn(this._value);default:return null}}}])&&c(t.prototype,r),u&&c(t,u),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,u}()},2243:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MuxedAccount=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(2135),a=r(7120),u=r(6160);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function c(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Networks=void 0;t.Networks={PUBLIC:"Public Global Stellar Network ; September 2015",TESTNET:"Test SDF Network ; September 2015",FUTURENET:"Test SDF Future Network ; October 2022",SANDBOX:"Local Sandbox Stellar Network ; September 2022",STANDALONE:"Standalone Network ; February 2017"}},8549:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Int128",{enumerable:!0,get:function(){return a.Int128}}),Object.defineProperty(t,"Int256",{enumerable:!0,get:function(){return u.Int256}}),Object.defineProperty(t,"ScInt",{enumerable:!0,get:function(){return s.ScInt}}),Object.defineProperty(t,"Uint128",{enumerable:!0,get:function(){return o.Uint128}}),Object.defineProperty(t,"Uint256",{enumerable:!0,get:function(){return i.Uint256}}),Object.defineProperty(t,"XdrLargeInt",{enumerable:!0,get:function(){return n.XdrLargeInt}}),t.scValToBigInt=function(e){var t=n.XdrLargeInt.getType(e.switch().name);switch(e.switch().name){case"scvU32":case"scvI32":return BigInt(e.value());case"scvU64":case"scvI64":return new n.XdrLargeInt(t,e.value()).toBigInt();case"scvU128":case"scvI128":return new n.XdrLargeInt(t,[e.value().lo(),e.value().hi()]).toBigInt();case"scvU256":case"scvI256":return new n.XdrLargeInt(t,[e.value().loLo(),e.value().loHi(),e.value().hiLo(),e.value().hiHi()]).toBigInt();default:throw TypeError("expected integer type, got ".concat(e.switch()))}};var n=r(7429),o=r(6272),i=r(8672),a=r(5487),u=r(4063),s=r(3317)},5487:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Int128=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Int256=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.ScInt=void 0;var o=r(7429);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Uint128=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Uint256=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.XdrLargeInt=void 0;var n,o=r(3740),i=r(6272),a=r(8672),u=r(5487),s=r(4063),c=(n=r(1918))&&n.__esModule?n:{default:n};function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){for(var r=0;rNumber.MAX_SAFE_INTEGER||e>64n),r=BigInt.asUintN(64,e);return c.default.ScVal.scvI128(new c.default.Int128Parts({hi:new c.default.Int64(t),lo:new c.default.Uint64(r)}))}},{key:"toU128",value:function(){this._sizeCheck(128);var e=this.int.toBigInt();return c.default.ScVal.scvU128(new c.default.UInt128Parts({hi:new c.default.Uint64(BigInt.asUintN(64,e>>64n)),lo:new c.default.Uint64(BigInt.asUintN(64,e))}))}},{key:"toI256",value:function(){var e=this.int.toBigInt(),t=BigInt.asIntN(64,e>>192n),r=BigInt.asUintN(64,e>>128n),n=BigInt.asUintN(64,e>>64n),o=BigInt.asUintN(64,e);return c.default.ScVal.scvI256(new c.default.Int256Parts({hiHi:new c.default.Int64(t),hiLo:new c.default.Uint64(r),loHi:new c.default.Uint64(n),loLo:new c.default.Uint64(o)}))}},{key:"toU256",value:function(){var e=this.int.toBigInt(),t=BigInt.asUintN(64,e>>192n),r=BigInt.asUintN(64,e>>128n),n=BigInt.asUintN(64,e>>64n),o=BigInt.asUintN(64,e);return c.default.ScVal.scvU256(new c.default.UInt256Parts({hiHi:new c.default.Uint64(t),hiLo:new c.default.Uint64(r),loHi:new c.default.Uint64(n),loLo:new c.default.Uint64(o)}))}},{key:"toScVal",value:function(){switch(this.type){case"i64":return this.toI64();case"i128":return this.toI128();case"i256":return this.toI256();case"u64":return this.toU64();case"u128":return this.toU128();case"u256":return this.toU256();default:throw TypeError("invalid type: ".concat(this.type))}}},{key:"valueOf",value:function(){return this.int.valueOf()}},{key:"toString",value:function(){return this.int.toString()}},{key:"toJSON",value:function(){return{value:this.toBigInt().toString(),type:this.type}}},{key:"_sizeCheck",value:function(e){if(this.int.size>e)throw RangeError("value too large for ".concat(e," bits (").concat(this.type,")"))}}],[{key:"isType",value:function(e){switch(e){case"i64":case"i128":case"i256":case"u64":case"u128":case"u256":return!0;default:return!1}}},{key:"getType",value:function(e){return e.slice(3).toLowerCase()}}])}()},7237:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.AuthRevocableFlag=t.AuthRequiredFlag=t.AuthImmutableFlag=t.AuthClawbackEnabledFlag=void 0;var n=r(3740),o=m(r(1242)),i=r(645),a=r(4151),u=r(1764),s=r(2262),c=r(1387),l=r(7120),f=r(9353),p=m(r(1918)),d=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=v(e)&&"function"!=typeof e)return{default:e};var r=y(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in e)if("default"!==i&&{}.hasOwnProperty.call(e,i)){var a=o?Object.getOwnPropertyDescriptor(e,i):null;a&&(a.get||a.set)?Object.defineProperty(n,i,a):n[i]=e[i]}return n.default=e,r&&r.set(e,n),n}(r(7511)),h=r(6160);function y(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(y=function(e){return e?r:t})(e)}function m(e){return e&&e.__esModule?e:{default:e}}function v(e){return v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},v(e)}function g(e,t){for(var r=0;r1&&void 0!==arguments[1]&&arguments[1];if("string"!=typeof e)return!1;try{t=new o.default(e)}catch(e){return!1}return!(!r&&t.isZero()||t.isNegative()||t.times(w).gt(new o.default("9223372036854775807").toString())||t.decimalPlaces()>7||t.isNaN()||!t.isFinite())}},{key:"constructAmountRequirementsError",value:function(e){return"".concat(e," argument must be of type String, represent a positive number and have at most 7 digits after the decimal")}},{key:"_checkUnsignedIntValue",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;if(void 0!==t)switch("string"==typeof t&&(t=parseFloat(t)),!0){case"number"!=typeof t||!Number.isFinite(t)||t%1!=0:throw new Error("".concat(e," value is invalid"));case t<0:throw new Error("".concat(e," value must be unsigned"));case!r||r&&r(t,e):return t;default:throw new Error("".concat(e," value is invalid"))}}},{key:"_toXDRAmount",value:function(e){var t=new o.default(e).times(w);return n.Hyper.fromString(t.toString())}},{key:"_fromXDRAmount",value:function(e){return new o.default(e).div(w).toFixed(7)}},{key:"_fromXDRPrice",value:function(e){return new o.default(e.n()).div(new o.default(e.d())).toString()}},{key:"_toXDRPrice",value:function(e){var t;if(e.n&&e.d)t=new p.default.Price(e);else{var r=(0,a.best_r)(e);t=new p.default.Price({n:parseInt(r[0],10),d:parseInt(r[1],10)})}if(t.n()<0||t.d()<0)throw new Error("price must be positive");return t}}],(t=null)&&g(e.prototype,t),r&&g(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,r}());function k(e){return l.StrKey.encodeEd25519PublicKey(e.ed25519())}S.accountMerge=d.accountMerge,S.allowTrust=d.allowTrust,S.bumpSequence=d.bumpSequence,S.changeTrust=d.changeTrust,S.createAccount=d.createAccount,S.createClaimableBalance=d.createClaimableBalance,S.claimClaimableBalance=d.claimClaimableBalance,S.clawbackClaimableBalance=d.clawbackClaimableBalance,S.createPassiveSellOffer=d.createPassiveSellOffer,S.inflation=d.inflation,S.manageData=d.manageData,S.manageSellOffer=d.manageSellOffer,S.manageBuyOffer=d.manageBuyOffer,S.pathPaymentStrictReceive=d.pathPaymentStrictReceive,S.pathPaymentStrictSend=d.pathPaymentStrictSend,S.payment=d.payment,S.setOptions=d.setOptions,S.beginSponsoringFutureReserves=d.beginSponsoringFutureReserves,S.endSponsoringFutureReserves=d.endSponsoringFutureReserves,S.revokeAccountSponsorship=d.revokeAccountSponsorship,S.revokeTrustlineSponsorship=d.revokeTrustlineSponsorship,S.revokeOfferSponsorship=d.revokeOfferSponsorship,S.revokeDataSponsorship=d.revokeDataSponsorship,S.revokeClaimableBalanceSponsorship=d.revokeClaimableBalanceSponsorship,S.revokeLiquidityPoolSponsorship=d.revokeLiquidityPoolSponsorship,S.revokeSignerSponsorship=d.revokeSignerSponsorship,S.clawback=d.clawback,S.setTrustLineFlags=d.setTrustLineFlags,S.liquidityPoolDeposit=d.liquidityPoolDeposit,S.liquidityPoolWithdraw=d.liquidityPoolWithdraw,S.invokeHostFunction=d.invokeHostFunction,S.extendFootprintTtl=d.extendFootprintTtl,S.restoreFootprint=d.restoreFootprint,S.createStellarAssetContract=d.createStellarAssetContract,S.invokeContractFunction=d.invokeContractFunction,S.createCustomContract=d.createCustomContract,S.uploadContractWasm=d.uploadContractWasm},4295:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.accountMerge=function(e){var t={};try{t.body=o.default.OperationBody.accountMerge((0,i.decodeAddressToMuxedAccount)(e.destination))}catch(e){throw new Error("destination is invalid")}return this.setSourceAccount(t,e),new o.default.Operation(t)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},3683:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allowTrust=function(e){if(!a.StrKey.isValidEd25519PublicKey(e.trustor))throw new Error("trustor is invalid");var t={};if(t.trustor=i.Keypair.fromPublicKey(e.trustor).xdrAccountId(),e.assetCode.length<=4){var r=e.assetCode.padEnd(4,"\0");t.asset=o.default.AssetCode.assetTypeCreditAlphanum4(r)}else{if(!(e.assetCode.length<=12))throw new Error("Asset code must be 12 characters at max.");var n=e.assetCode.padEnd(12,"\0");t.asset=o.default.AssetCode.assetTypeCreditAlphanum12(n)}"boolean"==typeof e.authorize?e.authorize?t.authorize=o.default.TrustLineFlags.authorizedFlag().value:t.authorize=0:t.authorize=e.authorize;var u=new o.default.AllowTrustOp(t),s={};return s.body=o.default.OperationBody.allowTrust(u),this.setSourceAccount(s,e),new o.default.Operation(s)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691),a=r(7120)},7505:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.beginSponsoringFutureReserves=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!i.StrKey.isValidEd25519PublicKey(e.sponsoredId))throw new Error("sponsoredId is invalid");var t=new o.default.BeginSponsoringFutureReservesOp({sponsoredId:a.Keypair.fromPublicKey(e.sponsoredId).xdrAccountId()}),r={};return r.body=o.default.OperationBody.beginSponsoringFutureReserves(t),this.setSourceAccount(r,e),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(7120),a=r(6691)},6183:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bumpSequence=function(e){var t={};if("string"!=typeof e.bumpTo)throw new Error("bumpTo must be a string");try{new o.default(e.bumpTo)}catch(e){throw new Error("bumpTo must be a stringified number")}t.bumpTo=n.Hyper.fromString(e.bumpTo);var r=new i.default.BumpSequenceOp(t),a={};return a.body=i.default.OperationBody.bumpSequence(r),this.setSourceAccount(a,e),new i.default.Operation(a)};var n=r(3740),o=a(r(1242)),i=a(r(1918));function a(e){return e&&e.__esModule?e:{default:e}}},2810:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.changeTrust=function(e){var t={};if(e.asset instanceof a.Asset)t.line=e.asset.toChangeTrustXDRObject();else{if(!(e.asset instanceof u.LiquidityPoolAsset))throw new TypeError("asset must be Asset or LiquidityPoolAsset");t.line=e.asset.toXDRObject()}if(void 0!==e.limit&&!this.isValidAmount(e.limit,!0))throw new TypeError(this.constructAmountRequirementsError("limit"));e.limit?t.limit=this._toXDRAmount(e.limit):t.limit=n.Hyper.fromString(new o.default(c).toString());e.source&&(t.source=e.source.masterKeypair);var r=new i.default.ChangeTrustOp(t),s={};return s.body=i.default.OperationBody.changeTrust(r),this.setSourceAccount(s,e),new i.default.Operation(s)};var n=r(3740),o=s(r(1242)),i=s(r(1918)),a=r(1764),u=r(2262);function s(e){return e&&e.__esModule?e:{default:e}}var c="9223372036854775807"},7239:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.claimClaimableBalance=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};i(e.balanceId);var t={};t.balanceId=o.default.ClaimableBalanceId.fromXDR(e.balanceId,"hex");var r=new o.default.ClaimClaimableBalanceOp(t),n={};return n.body=o.default.OperationBody.claimClaimableBalance(r),this.setSourceAccount(n,e),new o.default.Operation(n)},t.validateClaimableBalanceId=i;var n,o=(n=r(1918))&&n.__esModule?n:{default:n};function i(e){if("string"!=typeof e||72!==e.length)throw new Error("must provide a valid claimable balance id")}},7651:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clawback=function(e){var t={};if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));t.amount=this._toXDRAmount(e.amount),t.asset=e.asset.toXDRObject();try{t.from=(0,i.decodeAddressToMuxedAccount)(e.from)}catch(e){throw new Error("from address is invalid")}var r={body:o.default.OperationBody.clawback(new o.default.ClawbackOp(t))};return this.setSourceAccount(r,e),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},2203:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clawbackClaimableBalance=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(0,i.validateClaimableBalanceId)(e.balanceId);var t={balanceId:o.default.ClaimableBalanceId.fromXDR(e.balanceId,"hex")},r={body:o.default.OperationBody.clawbackClaimableBalance(new o.default.ClawbackClaimableBalanceOp(t))};return this.setSourceAccount(r,e),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(7239)},2115:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createAccount=function(e){if(!a.StrKey.isValidEd25519PublicKey(e.destination))throw new Error("destination is invalid");if(!this.isValidAmount(e.startingBalance,!0))throw new TypeError(this.constructAmountRequirementsError("startingBalance"));var t={};t.destination=i.Keypair.fromPublicKey(e.destination).xdrAccountId(),t.startingBalance=this._toXDRAmount(e.startingBalance);var r=new o.default.CreateAccountOp(t),n={};return n.body=o.default.OperationBody.createAccount(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691),a=r(7120)},4831:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createClaimableBalance=function(e){if(!(e.asset instanceof i.Asset))throw new Error("must provide an asset for create claimable balance operation");if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(!Array.isArray(e.claimants)||0===e.claimants.length)throw new Error("must provide at least one claimant");var t={};t.asset=e.asset.toXDRObject(),t.amount=this._toXDRAmount(e.amount),t.claimants=Object.values(e.claimants).map((function(e){return e.toXDRObject()}));var r=new o.default.CreateClaimableBalanceOp(t),n={};return n.body=o.default.OperationBody.createClaimableBalance(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(1764)},9073:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createPassiveSellOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price);var r=new o.default.CreatePassiveSellOfferOp(t),n={};return n.body=o.default.OperationBody.createPassiveSellOffer(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},721:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endSponsoringFutureReserves=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};return t.body=o.default.OperationBody.endSponsoringFutureReserves(),this.setSourceAccount(t,e),new o.default.Operation(t)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},8752:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extendFootprintTtl=function(e){var t;if((null!==(t=e.extendTo)&&void 0!==t?t:-1)<=0)throw new RangeError("extendTo has to be positive");var r=new o.default.ExtendFootprintTtlOp({ext:new o.default.ExtensionPoint(0),extendTo:e.extendTo}),n={body:o.default.OperationBody.extendFootprintTtl(r)};return this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},7511:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"accountMerge",{enumerable:!0,get:function(){return i.accountMerge}}),Object.defineProperty(t,"allowTrust",{enumerable:!0,get:function(){return a.allowTrust}}),Object.defineProperty(t,"beginSponsoringFutureReserves",{enumerable:!0,get:function(){return w.beginSponsoringFutureReserves}}),Object.defineProperty(t,"bumpSequence",{enumerable:!0,get:function(){return u.bumpSequence}}),Object.defineProperty(t,"changeTrust",{enumerable:!0,get:function(){return s.changeTrust}}),Object.defineProperty(t,"claimClaimableBalance",{enumerable:!0,get:function(){return f.claimClaimableBalance}}),Object.defineProperty(t,"clawback",{enumerable:!0,get:function(){return E.clawback}}),Object.defineProperty(t,"clawbackClaimableBalance",{enumerable:!0,get:function(){return p.clawbackClaimableBalance}}),Object.defineProperty(t,"createAccount",{enumerable:!0,get:function(){return c.createAccount}}),Object.defineProperty(t,"createClaimableBalance",{enumerable:!0,get:function(){return l.createClaimableBalance}}),Object.defineProperty(t,"createCustomContract",{enumerable:!0,get:function(){return x.createCustomContract}}),Object.defineProperty(t,"createPassiveSellOffer",{enumerable:!0,get:function(){return o.createPassiveSellOffer}}),Object.defineProperty(t,"createStellarAssetContract",{enumerable:!0,get:function(){return x.createStellarAssetContract}}),Object.defineProperty(t,"endSponsoringFutureReserves",{enumerable:!0,get:function(){return S.endSponsoringFutureReserves}}),Object.defineProperty(t,"extendFootprintTtl",{enumerable:!0,get:function(){return A.extendFootprintTtl}}),Object.defineProperty(t,"inflation",{enumerable:!0,get:function(){return d.inflation}}),Object.defineProperty(t,"invokeContractFunction",{enumerable:!0,get:function(){return x.invokeContractFunction}}),Object.defineProperty(t,"invokeHostFunction",{enumerable:!0,get:function(){return x.invokeHostFunction}}),Object.defineProperty(t,"liquidityPoolDeposit",{enumerable:!0,get:function(){return T.liquidityPoolDeposit}}),Object.defineProperty(t,"liquidityPoolWithdraw",{enumerable:!0,get:function(){return O.liquidityPoolWithdraw}}),Object.defineProperty(t,"manageBuyOffer",{enumerable:!0,get:function(){return y.manageBuyOffer}}),Object.defineProperty(t,"manageData",{enumerable:!0,get:function(){return h.manageData}}),Object.defineProperty(t,"manageSellOffer",{enumerable:!0,get:function(){return n.manageSellOffer}}),Object.defineProperty(t,"pathPaymentStrictReceive",{enumerable:!0,get:function(){return m.pathPaymentStrictReceive}}),Object.defineProperty(t,"pathPaymentStrictSend",{enumerable:!0,get:function(){return v.pathPaymentStrictSend}}),Object.defineProperty(t,"payment",{enumerable:!0,get:function(){return g.payment}}),Object.defineProperty(t,"restoreFootprint",{enumerable:!0,get:function(){return P.restoreFootprint}}),Object.defineProperty(t,"revokeAccountSponsorship",{enumerable:!0,get:function(){return k.revokeAccountSponsorship}}),Object.defineProperty(t,"revokeClaimableBalanceSponsorship",{enumerable:!0,get:function(){return k.revokeClaimableBalanceSponsorship}}),Object.defineProperty(t,"revokeDataSponsorship",{enumerable:!0,get:function(){return k.revokeDataSponsorship}}),Object.defineProperty(t,"revokeLiquidityPoolSponsorship",{enumerable:!0,get:function(){return k.revokeLiquidityPoolSponsorship}}),Object.defineProperty(t,"revokeOfferSponsorship",{enumerable:!0,get:function(){return k.revokeOfferSponsorship}}),Object.defineProperty(t,"revokeSignerSponsorship",{enumerable:!0,get:function(){return k.revokeSignerSponsorship}}),Object.defineProperty(t,"revokeTrustlineSponsorship",{enumerable:!0,get:function(){return k.revokeTrustlineSponsorship}}),Object.defineProperty(t,"setOptions",{enumerable:!0,get:function(){return b.setOptions}}),Object.defineProperty(t,"setTrustLineFlags",{enumerable:!0,get:function(){return _.setTrustLineFlags}}),Object.defineProperty(t,"uploadContractWasm",{enumerable:!0,get:function(){return x.uploadContractWasm}});var n=r(862),o=r(9073),i=r(4295),a=r(3683),u=r(6183),s=r(2810),c=r(2115),l=r(4831),f=r(7239),p=r(2203),d=r(7421),h=r(1411),y=r(1922),m=r(2075),v=r(3874),g=r(3533),b=r(2018),w=r(7505),S=r(721),k=r(7790),E=r(7651),_=r(1804),T=r(9845),O=r(4737),x=r(4403),A=r(8752),P=r(149)},7421:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inflation=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};return t.body=o.default.OperationBody.inflation(),this.setSourceAccount(t,e),new o.default.Operation(t)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},4403:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.createCustomContract=function(e){var t,r=n.from(e.salt||a.Keypair.random().xdrPublicKey().value());if(!e.wasmHash||32!==e.wasmHash.length)throw new TypeError("expected hash(contract WASM) in 'opts.wasmHash', got ".concat(e.wasmHash));if(32!==r.length)throw new TypeError("expected 32-byte salt in 'opts.salt', got ".concat(e.wasmHash));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeCreateContractV2(new i.default.CreateContractArgsV2({executable:i.default.ContractExecutable.contractExecutableWasm(n.from(e.wasmHash)),contractIdPreimage:i.default.ContractIdPreimage.contractIdPreimageFromAddress(new i.default.ContractIdPreimageFromAddress({address:e.address.toScAddress(),salt:r})),constructorArgs:null!==(t=e.constructorArgs)&&void 0!==t?t:[]}))})},t.createStellarAssetContract=function(e){var t=e.asset;if("string"==typeof t){var r=t.split(":"),n=(l=2,function(e){if(Array.isArray(e))return e}(u=r)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,u=[],s=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=i.call(r)).done)&&(u.push(n.value),u.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return u}}(u,l)||function(e,t){if(e){if("string"==typeof e)return c(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?c(e,t):void 0}}(u,l)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),o=n[0],a=n[1];t=new s.Asset(o,a)}var u,l;if(!(t instanceof s.Asset))throw new TypeError("expected Asset in 'opts.asset', got ".concat(t));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeCreateContract(new i.default.CreateContractArgs({executable:i.default.ContractExecutable.contractExecutableStellarAsset(),contractIdPreimage:i.default.ContractIdPreimage.contractIdPreimageFromAsset(t.toXDRObject())}))})},t.invokeContractFunction=function(e){var t=new u.Address(e.contract);if("contract"!==t._type)throw new TypeError("expected contract strkey instance, got ".concat(t));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeInvokeContract(new i.default.InvokeContractArgs({contractAddress:t.toScAddress(),functionName:e.function,args:e.args}))})},t.invokeHostFunction=function(e){if(!e.func)throw new TypeError("host function invocation ('func') required (got ".concat(JSON.stringify(e),")"));var t=new i.default.InvokeHostFunctionOp({hostFunction:e.func,auth:e.auth||[]}),r={body:i.default.OperationBody.invokeHostFunction(t)};return this.setSourceAccount(r,e),new i.default.Operation(r)},t.uploadContractWasm=function(e){return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeUploadContractWasm(n.from(e.wasm))})};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(6691),u=r(1180),s=r(1764);function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.liquidityPoolDeposit=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.liquidityPoolId,r=e.maxAmountA,n=e.maxAmountB,i=e.minPrice,a=e.maxPrice,u={};if(!t)throw new TypeError("liquidityPoolId argument is required");if(u.liquidityPoolId=o.default.PoolId.fromXDR(t,"hex"),!this.isValidAmount(r,!0))throw new TypeError(this.constructAmountRequirementsError("maxAmountA"));if(u.maxAmountA=this._toXDRAmount(r),!this.isValidAmount(n,!0))throw new TypeError(this.constructAmountRequirementsError("maxAmountB"));if(u.maxAmountB=this._toXDRAmount(n),void 0===i)throw new TypeError("minPrice argument is required");if(u.minPrice=this._toXDRPrice(i),void 0===a)throw new TypeError("maxPrice argument is required");u.maxPrice=this._toXDRPrice(a);var s=new o.default.LiquidityPoolDepositOp(u),c={body:o.default.OperationBody.liquidityPoolDeposit(s)};return this.setSourceAccount(c,e),new o.default.Operation(c)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},4737:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.liquidityPoolWithdraw=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};if(!e.liquidityPoolId)throw new TypeError("liquidityPoolId argument is required");if(t.liquidityPoolId=o.default.PoolId.fromXDR(e.liquidityPoolId,"hex"),!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),!this.isValidAmount(e.minAmountA,!0))throw new TypeError(this.constructAmountRequirementsError("minAmountA"));if(t.minAmountA=this._toXDRAmount(e.minAmountA),!this.isValidAmount(e.minAmountB,!0))throw new TypeError(this.constructAmountRequirementsError("minAmountB"));t.minAmountB=this._toXDRAmount(e.minAmountB);var r=new o.default.LiquidityPoolWithdrawOp(t),n={body:o.default.OperationBody.liquidityPoolWithdraw(r)};return this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},1922:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.manageBuyOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.buyAmount,!0))throw new TypeError(this.constructAmountRequirementsError("buyAmount"));if(t.buyAmount=this._toXDRAmount(e.buyAmount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price),void 0!==e.offerId?e.offerId=e.offerId.toString():e.offerId="0";t.offerId=o.Hyper.fromString(e.offerId);var r=new i.default.ManageBuyOfferOp(t),n={};return n.body=i.default.OperationBody.manageBuyOffer(r),this.setSourceAccount(n,e),new i.default.Operation(n)};var n,o=r(3740),i=(n=r(1918))&&n.__esModule?n:{default:n}},1411:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.manageData=function(e){var t={};if(!("string"==typeof e.name&&e.name.length<=64))throw new Error("name must be a string, up to 64 characters");if(t.dataName=e.name,"string"!=typeof e.value&&!n.isBuffer(e.value)&&null!==e.value)throw new Error("value must be a string, Buffer or null");"string"==typeof e.value?t.dataValue=n.from(e.value):t.dataValue=e.value;if(null!==t.dataValue&&t.dataValue.length>64)throw new Error("value cannot be longer that 64 bytes");var r=new i.default.ManageDataOp(t),o={};return o.body=i.default.OperationBody.manageData(r),this.setSourceAccount(o,e),new i.default.Operation(o)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o}},862:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.manageSellOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.amount,!0))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price),void 0!==e.offerId?e.offerId=e.offerId.toString():e.offerId="0";t.offerId=o.Hyper.fromString(e.offerId);var r=new i.default.ManageSellOfferOp(t),n={};return n.body=i.default.OperationBody.manageSellOffer(r),this.setSourceAccount(n,e),new i.default.Operation(n)};var n,o=r(3740),i=(n=r(1918))&&n.__esModule?n:{default:n}},2075:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathPaymentStrictReceive=function(e){switch(!0){case!e.sendAsset:throw new Error("Must specify a send asset");case!this.isValidAmount(e.sendMax):throw new TypeError(this.constructAmountRequirementsError("sendMax"));case!e.destAsset:throw new Error("Must provide a destAsset for a payment operation");case!this.isValidAmount(e.destAmount):throw new TypeError(this.constructAmountRequirementsError("destAmount"))}var t={};t.sendAsset=e.sendAsset.toXDRObject(),t.sendMax=this._toXDRAmount(e.sendMax);try{t.destination=(0,i.decodeAddressToMuxedAccount)(e.destination)}catch(e){throw new Error("destination is invalid")}t.destAsset=e.destAsset.toXDRObject(),t.destAmount=this._toXDRAmount(e.destAmount);var r=e.path?e.path:[];t.path=r.map((function(e){return e.toXDRObject()}));var n=new o.default.PathPaymentStrictReceiveOp(t),a={};return a.body=o.default.OperationBody.pathPaymentStrictReceive(n),this.setSourceAccount(a,e),new o.default.Operation(a)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},3874:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathPaymentStrictSend=function(e){switch(!0){case!e.sendAsset:throw new Error("Must specify a send asset");case!this.isValidAmount(e.sendAmount):throw new TypeError(this.constructAmountRequirementsError("sendAmount"));case!e.destAsset:throw new Error("Must provide a destAsset for a payment operation");case!this.isValidAmount(e.destMin):throw new TypeError(this.constructAmountRequirementsError("destMin"))}var t={};t.sendAsset=e.sendAsset.toXDRObject(),t.sendAmount=this._toXDRAmount(e.sendAmount);try{t.destination=(0,i.decodeAddressToMuxedAccount)(e.destination)}catch(e){throw new Error("destination is invalid")}t.destAsset=e.destAsset.toXDRObject(),t.destMin=this._toXDRAmount(e.destMin);var r=e.path?e.path:[];t.path=r.map((function(e){return e.toXDRObject()}));var n=new o.default.PathPaymentStrictSendOp(t),a={};return a.body=o.default.OperationBody.pathPaymentStrictSend(n),this.setSourceAccount(a,e),new o.default.Operation(a)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},3533:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.payment=function(e){if(!e.asset)throw new Error("Must provide an asset for a payment operation");if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));var t={};try{t.destination=(0,i.decodeAddressToMuxedAccount)(e.destination)}catch(e){throw new Error("destination is invalid")}t.asset=e.asset.toXDRObject(),t.amount=this._toXDRAmount(e.amount);var r=new o.default.PaymentOp(t),n={};return n.body=o.default.OperationBody.payment(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},149:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restoreFootprint=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=new o.default.RestoreFootprintOp({ext:new o.default.ExtensionPoint(0)}),r={body:o.default.OperationBody.restoreFootprint(t)};return this.setSourceAccount(r,null!=e?e:{}),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},7790:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.revokeAccountSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");var t=i.default.LedgerKey.account(new i.default.LedgerKeyAccount({accountId:u.Keypair.fromPublicKey(e.account).xdrAccountId()})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeClaimableBalanceSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if("string"!=typeof e.balanceId)throw new Error("balanceId is invalid");var t=i.default.LedgerKey.claimableBalance(new i.default.LedgerKeyClaimableBalance({balanceId:i.default.ClaimableBalanceId.fromXDR(e.balanceId,"hex")})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeDataSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");if("string"!=typeof e.name||e.name.length>64)throw new Error("name must be a string, up to 64 characters");var t=i.default.LedgerKey.data(new i.default.LedgerKeyData({accountId:u.Keypair.fromPublicKey(e.account).xdrAccountId(),dataName:e.name})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeLiquidityPoolSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if("string"!=typeof e.liquidityPoolId)throw new Error("liquidityPoolId is invalid");var t=i.default.LedgerKey.liquidityPool(new i.default.LedgerKeyLiquidityPool({liquidityPoolId:i.default.PoolId.fromXDR(e.liquidityPoolId,"hex")})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={body:i.default.OperationBody.revokeSponsorship(r)};return this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeOfferSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(e.seller))throw new Error("seller is invalid");if("string"!=typeof e.offerId)throw new Error("offerId is invalid");var t=i.default.LedgerKey.offer(new i.default.LedgerKeyOffer({sellerId:u.Keypair.fromPublicKey(e.seller).xdrAccountId(),offerId:i.default.Int64.fromString(e.offerId)})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeSignerSponsorship=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(t.account))throw new Error("account is invalid");if(t.signer.ed25519PublicKey){if(!a.StrKey.isValidEd25519PublicKey(t.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");var r=a.StrKey.decodeEd25519PublicKey(t.signer.ed25519PublicKey);e=new i.default.SignerKey.signerKeyTypeEd25519(r)}else if(t.signer.preAuthTx){var o;if(o="string"==typeof t.signer.preAuthTx?n.from(t.signer.preAuthTx,"hex"):t.signer.preAuthTx,!n.isBuffer(o)||32!==o.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");e=new i.default.SignerKey.signerKeyTypePreAuthTx(o)}else{if(!t.signer.sha256Hash)throw new Error("signer is invalid");var s;if(s="string"==typeof t.signer.sha256Hash?n.from(t.signer.sha256Hash,"hex"):t.signer.sha256Hash,!n.isBuffer(s)||32!==s.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");e=new i.default.SignerKey.signerKeyTypeHashX(s)}var c=new i.default.RevokeSponsorshipOpSigner({accountId:u.Keypair.fromPublicKey(t.account).xdrAccountId(),signerKey:e}),l=i.default.RevokeSponsorshipOp.revokeSponsorshipSigner(c),f={};return f.body=i.default.OperationBody.revokeSponsorship(l),this.setSourceAccount(f,t),new i.default.Operation(f)},t.revokeTrustlineSponsorship=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(t.account))throw new Error("account is invalid");if(t.asset instanceof s.Asset)e=t.asset.toTrustLineXDRObject();else{if(!(t.asset instanceof c.LiquidityPoolId))throw new TypeError("asset must be an Asset or LiquidityPoolId");e=t.asset.toXDRObject()}var r=i.default.LedgerKey.trustline(new i.default.LedgerKeyTrustLine({accountId:u.Keypair.fromPublicKey(t.account).xdrAccountId(),asset:e})),n=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(r),o={};return o.body=i.default.OperationBody.revokeSponsorship(n),this.setSourceAccount(o,t),new i.default.Operation(o)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(7120),u=r(6691),s=r(1764),c=r(9353)},2018:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.setOptions=function(e){var t={};if(e.inflationDest){if(!u.StrKey.isValidEd25519PublicKey(e.inflationDest))throw new Error("inflationDest is invalid");t.inflationDest=a.Keypair.fromPublicKey(e.inflationDest).xdrAccountId()}if(t.clearFlags=this._checkUnsignedIntValue("clearFlags",e.clearFlags),t.setFlags=this._checkUnsignedIntValue("setFlags",e.setFlags),t.masterWeight=this._checkUnsignedIntValue("masterWeight",e.masterWeight,s),t.lowThreshold=this._checkUnsignedIntValue("lowThreshold",e.lowThreshold,s),t.medThreshold=this._checkUnsignedIntValue("medThreshold",e.medThreshold,s),t.highThreshold=this._checkUnsignedIntValue("highThreshold",e.highThreshold,s),void 0!==e.homeDomain&&"string"!=typeof e.homeDomain)throw new TypeError("homeDomain argument must be of type String");if(t.homeDomain=e.homeDomain,e.signer){var r,o=this._checkUnsignedIntValue("signer.weight",e.signer.weight,s),c=0;if(e.signer.ed25519PublicKey){if(!u.StrKey.isValidEd25519PublicKey(e.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");var l=u.StrKey.decodeEd25519PublicKey(e.signer.ed25519PublicKey);r=new i.default.SignerKey.signerKeyTypeEd25519(l),c+=1}if(e.signer.preAuthTx){if("string"==typeof e.signer.preAuthTx&&(e.signer.preAuthTx=n.from(e.signer.preAuthTx,"hex")),!n.isBuffer(e.signer.preAuthTx)||32!==e.signer.preAuthTx.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");r=new i.default.SignerKey.signerKeyTypePreAuthTx(e.signer.preAuthTx),c+=1}if(e.signer.sha256Hash){if("string"==typeof e.signer.sha256Hash&&(e.signer.sha256Hash=n.from(e.signer.sha256Hash,"hex")),!n.isBuffer(e.signer.sha256Hash)||32!==e.signer.sha256Hash.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");r=new i.default.SignerKey.signerKeyTypeHashX(e.signer.sha256Hash),c+=1}if(e.signer.ed25519SignedPayload){if(!u.StrKey.isValidSignedPayload(e.signer.ed25519SignedPayload))throw new Error("signer.ed25519SignedPayload is invalid.");var f=u.StrKey.decodeSignedPayload(e.signer.ed25519SignedPayload),p=i.default.SignerKeyEd25519SignedPayload.fromXDR(f);r=i.default.SignerKey.signerKeyTypeEd25519SignedPayload(p),c+=1}if(1!==c)throw new Error("Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx.");t.signer=new i.default.Signer({key:r,weight:o})}var d=new i.default.SetOptionsOp(t),h={};return h.body=i.default.OperationBody.setOptions(d),this.setSourceAccount(h,e),new i.default.Operation(h)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(6691),u=r(7120);function s(e,t){if(e>=0&&e<=255)return!0;throw new Error("".concat(t," value must be between 0 and 255"))}},1804:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setTrustLineFlags=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};if("object"!==a(e.flags)||0===Object.keys(e.flags).length)throw new Error("opts.flags must be a map of boolean flags to modify");var r={authorized:o.default.TrustLineFlags.authorizedFlag(),authorizedToMaintainLiabilities:o.default.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),clawbackEnabled:o.default.TrustLineFlags.trustlineClawbackEnabledFlag()},n=0,u=0;Object.keys(e.flags).forEach((function(t){if(!Object.prototype.hasOwnProperty.call(r,t))throw new Error("unsupported flag name specified: ".concat(t));var o=e.flags[t],i=r[t].value;!0===o?u|=i:!1===o&&(n|=i)})),t.trustor=i.Keypair.fromPublicKey(e.trustor).xdrAccountId(),t.asset=e.asset.toXDRObject(),t.clearFlags=n,t.setFlags=u;var s={body:o.default.OperationBody.setTrustLineFlags(new o.default.SetTrustLineFlagsOp(t))};return this.setSourceAccount(s,e),new o.default.Operation(s)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}},7177:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.nativeToScVal=function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(f(t)){case"object":var o,l,p;if(null===t)return i.default.ScVal.scvVoid();if(t instanceof i.default.ScVal)return t;if(t instanceof a.Address)return t.toScVal();if(t instanceof u.Contract)return t.address().toScVal();if(t instanceof Uint8Array||n.isBuffer(t)){var d,h=Uint8Array.from(t);switch(null!==(d=null==r?void 0:r.type)&&void 0!==d?d:"bytes"){case"bytes":return i.default.ScVal.scvBytes(h);case"symbol":return i.default.ScVal.scvSymbol(h);case"string":return i.default.ScVal.scvString(h);default:throw new TypeError("invalid type (".concat(r.type,") specified for bytes-like value"))}}if(Array.isArray(t)){if(t.length>0&&t.some((function(e){return f(e)!==f(t[0])})))throw new TypeError("array values (".concat(t,") must have the same type (types: ").concat(t.map((function(e){return f(e)})).join(","),")"));return i.default.ScVal.scvVec(t.map((function(t){return e(t,r)})))}if("Object"!==(null!==(o=null===(l=t.constructor)||void 0===l?void 0:l.name)&&void 0!==o?o:""))throw new TypeError("cannot interpret ".concat(null===(p=t.constructor)||void 0===p?void 0:p.name," value as ScVal (").concat(JSON.stringify(t),")"));return i.default.ScVal.scvMap(Object.entries(t).sort((function(e,t){var r=c(e,1)[0],n=c(t,1)[0];return r.localeCompare(n)})).map((function(t){var n,o,a=c(t,2),u=a[0],s=a[1],l=c(null!==(n=(null!==(o=null==r?void 0:r.type)&&void 0!==o?o:{})[u])&&void 0!==n?n:[null,null],2),f=l[0],p=l[1],d=f?{type:f}:{},h=p?{type:p}:{};return new i.default.ScMapEntry({key:e(u,d),val:e(s,h)})})));case"number":case"bigint":switch(null==r?void 0:r.type){case"u32":return i.default.ScVal.scvU32(t);case"i32":return i.default.ScVal.scvI32(t)}return new s.ScInt(t,{type:null==r?void 0:r.type}).toScVal();case"string":var y,m=null!==(y=null==r?void 0:r.type)&&void 0!==y?y:"string";switch(m){case"string":return i.default.ScVal.scvString(t);case"symbol":return i.default.ScVal.scvSymbol(t);case"address":return new a.Address(t).toScVal();case"u32":return i.default.ScVal.scvU32(parseInt(t,10));case"i32":return i.default.ScVal.scvI32(parseInt(t,10));default:if(s.XdrLargeInt.isType(m))return new s.XdrLargeInt(m,t).toScVal();throw new TypeError("invalid type (".concat(r.type,") specified for string value"))}case"boolean":return i.default.ScVal.scvBool(t);case"undefined":return i.default.ScVal.scvVoid();case"function":return e(t());default:throw new TypeError("failed to convert typeof ".concat(f(t)," (").concat(t,")"))}},t.scValToNative=function e(t){var r,o;switch(t.switch().value){case i.default.ScValType.scvVoid().value:return null;case i.default.ScValType.scvU64().value:case i.default.ScValType.scvI64().value:return t.value().toBigInt();case i.default.ScValType.scvU128().value:case i.default.ScValType.scvI128().value:case i.default.ScValType.scvU256().value:case i.default.ScValType.scvI256().value:return(0,s.scValToBigInt)(t);case i.default.ScValType.scvVec().value:return(null!==(r=t.vec())&&void 0!==r?r:[]).map(e);case i.default.ScValType.scvAddress().value:return a.Address.fromScVal(t).toString();case i.default.ScValType.scvMap().value:return Object.fromEntries((null!==(o=t.map())&&void 0!==o?o:[]).map((function(t){return[e(t.key()),e(t.val())]})));case i.default.ScValType.scvBool().value:case i.default.ScValType.scvU32().value:case i.default.ScValType.scvI32().value:case i.default.ScValType.scvBytes().value:return t.value();case i.default.ScValType.scvSymbol().value:case i.default.ScValType.scvString().value:var u=t.value();if(n.isBuffer(u)||ArrayBuffer.isView(u))try{return(new TextDecoder).decode(u)}catch(e){return new Uint8Array(u.buffer)}return u;case i.default.ScValType.scvTimepoint().value:case i.default.ScValType.scvDuration().value:return new i.default.Uint64(t.value()).toBigInt();case i.default.ScValType.scvError().value:if(t.error().switch().value===i.default.ScErrorType.sceContract().value)return{type:"contract",code:t.error().contractCode()};var c=t.error();return{type:"system",code:c.code().value,value:c.code().name};default:return t.value()}};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(1180),u=r(7452),s=r(8549);function c(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,u=[],s=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=i.call(r)).done)&&(u.push(n.value),u.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return u}}(e,t)||function(e,t){if(e){if("string"==typeof e)return l(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?l(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignerKey=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(7120);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function u(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.FastSigning=void 0,t.generate=function(e){return o.generate(e)},t.sign=function(e,t){return o.sign(e,t)},t.verify=function(e,t,r){return o.verify(e,t,r)};var o={};t.FastSigning="undefined"==typeof window?function(){var e;try{e=r(Object(function(){var e=new Error("Cannot find module 'sodium-native'");throw e.code="MODULE_NOT_FOUND",e}()))}catch(e){return i()}return Object.keys(e).length?(o.generate=function(t){var r=n.alloc(e.crypto_sign_PUBLICKEYBYTES),o=n.alloc(e.crypto_sign_SECRETKEYBYTES);return e.crypto_sign_seed_keypair(r,o,t),r},o.sign=function(t,r){t=n.from(t);var o=n.alloc(e.crypto_sign_BYTES);return e.crypto_sign_detached(o,t,r),o},o.verify=function(t,r,o){t=n.from(t);try{return e.crypto_sign_verify_detached(r,t,o)}catch(e){return!1}},!0):i()}():i();function i(){var e=r(4940);return o.generate=function(t){var r=new Uint8Array(t),o=e.sign.keyPair.fromSeed(r);return n.from(o.publicKey)},o.sign=function(t,r){t=n.from(t),t=new Uint8Array(t.toJSON().data),r=new Uint8Array(r.toJSON().data);var o=e.sign.detached(t,r);return n.from(o)},o.verify=function(t,r,o){return t=n.from(t),t=new Uint8Array(t.toJSON().data),r=new Uint8Array(r.toJSON().data),o=new Uint8Array(o.toJSON().data),e.sign.detached.verify(t,r,o)},!1}},4062:(e,t)=>{"use strict";function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}function n(e){return function(e){if(Array.isArray(e))return e}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return o(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?o(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r0&&(r=t>r.length?["0",r.toString().padStart(t,"0")].join("."):[r.slice(0,-t),r.slice(-t)].join(".")),r.replace(/(\.\d*?)0+$/,"$1")}},{key:"parseTokenAmount",value:function(e,t){var r,o=n(e.split(".").slice()),i=o[0],a=o[1];if(o.slice(2).length)throw new Error("Invalid decimal value: ".concat(e));return BigInt(i+(null!==(r=null==a?void 0:a.padEnd(t,"0"))&&void 0!==r?r:"0".repeat(t))).toString()}}],(t=null)&&i(e.prototype,t),r&&i(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,r}()},4842:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SorobanDataBuilder=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n};function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.StrKey=void 0,t.decodeCheck=d,t.encodeCheck=h;var o,i=(o=r(5360))&&o.__esModule?o:{default:o},a=r(1346);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function s(e,t){for(var r=0;r165)return!1;break;default:return!1}var r="";try{r=d(e,t)}catch(e){return!1}switch(e){case"ed25519PublicKey":case"ed25519SecretSeed":case"preAuthTx":case"sha256Hash":case"contract":return 32===r.length;case"med25519PublicKey":return 40===r.length;case"signedPayload":return r.length>=40&&r.length<=100;default:return!1}}function d(e,t){if("string"!=typeof t)throw new TypeError("encoded argument must be of type String");var r=i.default.decode(t),o=r[0],u=r.slice(0,-2),s=u.slice(1),c=r.slice(-2);if(t!==i.default.encode(r))throw new Error("invalid encoded string");var f=l[e];if(void 0===f)throw new Error("".concat(e," is not a valid version byte name. ")+"Expected one of ".concat(Object.keys(l).join(", ")));if(o!==f)throw new Error("invalid version byte. expected ".concat(f,", got ").concat(o));var p=y(u);if(!(0,a.verifyChecksum)(p,c))throw new Error("invalid checksum");return n.from(s)}function h(e,t){if(null==t)throw new Error("cannot encode null data");var r=l[e];if(void 0===r)throw new Error("".concat(e," is not a valid version byte name. ")+"Expected one of ".concat(Object.keys(l).join(", ")));t=n.from(t);var o=n.from([r]),a=n.concat([o,t]),u=n.from(y(a)),s=n.concat([a,u]);return i.default.encode(s)}function y(e){for(var t=[0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920],r=0,n=0;n>8^e[n]],r&=65535}var o=new Uint8Array(2);return o[0]=255&r,o[1]=r>>8&255,o}},380:(e,t,r)=>{"use strict";var n=r(8287).Buffer;function o(e){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Transaction=void 0;var i,a=(i=r(1918))&&i.__esModule?i:{default:i},u=r(9152),s=r(7120),c=r(7237),l=r(4172),f=r(3758),p=r(6160);function d(e,t){for(var r=0;r=this.operations.length)throw new RangeError("invalid operation index");var t=this.operations[e];try{t=c.Operation.createClaimableBalance(t)}catch(e){throw new TypeError("expected createClaimableBalance, got ".concat(t.type,": ").concat(e))}var r=s.StrKey.decodeEd25519PublicKey((0,p.extractBaseAddress)(this.source)),n=a.default.HashIdPreimage.envelopeTypeOpId(new a.default.HashIdPreimageOperationId({sourceAccount:a.default.AccountId.publicKeyTypeEd25519(r),seqNum:a.default.SequenceNumber.fromString(this.sequence),opNum:e})),o=(0,u.hash)(n.toXDR("raw"));return a.default.ClaimableBalanceId.claimableBalanceIdTypeV0(o).toXDR("hex")}}])}(f.TransactionBase)},3758:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionBase=void 0;var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(9152),u=r(6691);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function c(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:"",o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(!o||"string"!=typeof o)throw new Error("Invalid signature");if(!r||"string"!=typeof r)throw new Error("Invalid publicKey");var a=n.from(o,"base64");try{t=(e=u.Keypair.fromPublicKey(r)).signatureHint()}catch(e){throw new Error("Invalid publicKey")}if(!e.verify(this.hash(),a))throw new Error("Invalid signature");this.signatures.push(new i.default.DecoratedSignature({hint:t,signature:a}))}},{key:"addDecoratedSignature",value:function(e){this.signatures.push(e)}},{key:"signHashX",value:function(e){if("string"==typeof e&&(e=n.from(e,"hex")),e.length>64)throw new Error("preimage cannnot be longer than 64 bytes");var t=e,r=(0,a.hash)(e),o=r.slice(r.length-4);this.signatures.push(new i.default.DecoratedSignature({hint:o,signature:t}))}},{key:"hash",value:function(){return(0,a.hash)(this.signatureBase())}},{key:"signatureBase",value:function(){throw new Error("Implement in subclass")}},{key:"toEnvelope",value:function(){throw new Error("Implement in subclass")}},{key:"toXDR",value:function(){return this.toEnvelope().toXDR().toString("base64")}}])}()},6396:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionBuilder=t.TimeoutInfinite=t.BASE_FEE=void 0,t.isValidDate=T;var n=r(3740),o=y(r(1242)),i=y(r(1918)),a=r(2135),u=r(2243),s=r(6160),c=r(380),l=r(9260),f=r(4842),p=r(7120),d=r(225),h=r(4172);function y(e){return e&&e.__esModule?e:{default:e}}function m(e){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},m(e)}function v(e){return function(e){if(Array.isArray(e))return g(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return g(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?g(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function g(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r1&&void 0!==arguments[1]?arguments[1]:{};if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw new Error("must specify source account for the transaction");if(void 0===r.fee)throw new Error("must specify fee for the transaction (in stroops)");this.source=t,this.operations=[],this.baseFee=r.fee,this.timebounds=r.timebounds?w({},r.timebounds):null,this.ledgerbounds=r.ledgerbounds?w({},r.ledgerbounds):null,this.minAccountSequence=r.minAccountSequence||null,this.minAccountSequenceAge=r.minAccountSequenceAge||null,this.minAccountSequenceLedgerGap=r.minAccountSequenceLedgerGap||null,this.extraSigners=r.extraSigners?v(r.extraSigners):null,this.memo=r.memo||h.Memo.none(),this.networkPassphrase=r.networkPassphrase||null,this.sorobanData=r.sorobanData?new f.SorobanDataBuilder(r.sorobanData).build():null}return t=e,y=[{key:"cloneFrom",value:function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!(t instanceof c.Transaction))throw new TypeError("expected a 'Transaction', got: ".concat(t));var n,o=(BigInt(t.sequence)-1n).toString();if(p.StrKey.isValidMed25519PublicKey(t.source))n=u.MuxedAccount.fromAddress(t.source,o);else{if(!p.StrKey.isValidEd25519PublicKey(t.source))throw new TypeError("unsupported tx source account: ".concat(t.source));n=new a.Account(t.source,o)}var i=new e(n,w({fee:(parseInt(t.fee,10)/t.operations.length||_).toString(),memo:t.memo,networkPassphrase:t.networkPassphrase,timebounds:t.timeBounds,ledgerbounds:t.ledgerBounds,minAccountSequence:t.minAccountSequence,minAccountSequenceAge:t.minAccountSequenceAge,minAccountSequenceLedgerGap:t.minAccountSequenceLedgerGap,extraSigners:t.extraSigners},r));return t._tx.operations().forEach((function(e){return i.addOperation(e)})),i}},{key:"buildFeeBumpTransaction",value:function(e,t,r,n){var a=r.operations.length,u=new o.default(r.fee).div(a),c=new o.default(t);if(c.lt(u))throw new Error("Invalid baseFee, it should be at least ".concat(u," stroops."));var f=new o.default(_);if(c.lt(f))throw new Error("Invalid baseFee, it should be at least ".concat(f," stroops."));var p,d=r.toEnvelope();if(d.switch()===i.default.EnvelopeType.envelopeTypeTxV0()){var h=d.v0().tx(),y=new i.default.Transaction({sourceAccount:new i.default.MuxedAccount.keyTypeEd25519(h.sourceAccountEd25519()),fee:h.fee(),seqNum:h.seqNum(),cond:i.default.Preconditions.precondTime(h.timeBounds()),memo:h.memo(),operations:h.operations(),ext:new i.default.TransactionExt(0)});d=new i.default.TransactionEnvelope.envelopeTypeTx(new i.default.TransactionV1Envelope({tx:y,signatures:d.v0().signatures()}))}p="string"==typeof e?(0,s.decodeAddressToMuxedAccount)(e):e.xdrMuxedAccount();var m=new i.default.FeeBumpTransaction({feeSource:p,fee:i.default.Int64.fromString(c.times(a+1).toString()),innerTx:i.default.FeeBumpTransactionInnerTx.envelopeTypeTx(d.v1()),ext:new i.default.FeeBumpTransactionExt(0)}),v=new i.default.FeeBumpTransactionEnvelope({tx:m,signatures:[]}),g=new i.default.TransactionEnvelope.envelopeTypeTxFeeBump(v);return new l.FeeBumpTransaction(g,n)}},{key:"fromXDR",value:function(e,t){return"string"==typeof e&&(e=i.default.TransactionEnvelope.fromXDR(e,"base64")),e.switch()===i.default.EnvelopeType.envelopeTypeTxFeeBump()?new l.FeeBumpTransaction(e,t):new c.Transaction(e,t)}}],(r=[{key:"addOperation",value:function(e){return this.operations.push(e),this}},{key:"addOperationAt",value:function(e,t){return this.operations.splice(t,0,e),this}},{key:"clearOperations",value:function(){return this.operations=[],this}},{key:"clearOperationAt",value:function(e){return this.operations.splice(e,1),this}},{key:"addMemo",value:function(e){return this.memo=e,this}},{key:"setTimeout",value:function(e){if(null!==this.timebounds&&this.timebounds.maxTime>0)throw new Error("TimeBounds.max_time has been already set - setting timeout would overwrite it.");if(e<0)throw new Error("timeout cannot be negative");if(e>0){var t=Math.floor(Date.now()/1e3)+e;null===this.timebounds?this.timebounds={minTime:0,maxTime:t}:this.timebounds={minTime:this.timebounds.minTime,maxTime:t}}else this.timebounds={minTime:0,maxTime:0};return this}},{key:"setTimebounds",value:function(e,t){if("number"==typeof e&&(e=new Date(1e3*e)),"number"==typeof t&&(t=new Date(1e3*t)),null!==this.timebounds)throw new Error("TimeBounds has been already set - setting timebounds would overwrite it.");var r=Math.floor(e.valueOf()/1e3),n=Math.floor(t.valueOf()/1e3);if(r<0)throw new Error("min_time cannot be negative");if(n<0)throw new Error("max_time cannot be negative");if(n>0&&r>n)throw new Error("min_time cannot be greater than max_time");return this.timebounds={minTime:r,maxTime:n},this}},{key:"setLedgerbounds",value:function(e,t){if(null!==this.ledgerbounds)throw new Error("LedgerBounds has been already set - setting ledgerbounds would overwrite it.");if(e<0)throw new Error("min_ledger cannot be negative");if(t<0)throw new Error("max_ledger cannot be negative");if(t>0&&e>t)throw new Error("min_ledger cannot be greater than max_ledger");return this.ledgerbounds={minLedger:e,maxLedger:t},this}},{key:"setMinAccountSequence",value:function(e){if(null!==this.minAccountSequence)throw new Error("min_account_sequence has been already set - setting min_account_sequence would overwrite it.");return this.minAccountSequence=e,this}},{key:"setMinAccountSequenceAge",value:function(e){if("number"!=typeof e)throw new Error("min_account_sequence_age must be a number");if(null!==this.minAccountSequenceAge)throw new Error("min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.");if(e<0)throw new Error("min_account_sequence_age cannot be negative");return this.minAccountSequenceAge=e,this}},{key:"setMinAccountSequenceLedgerGap",value:function(e){if(null!==this.minAccountSequenceLedgerGap)throw new Error("min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.");if(e<0)throw new Error("min_account_sequence_ledger_gap cannot be negative");return this.minAccountSequenceLedgerGap=e,this}},{key:"setExtraSigners",value:function(e){if(!Array.isArray(e))throw new Error("extra_signers must be an array of strings.");if(null!==this.extraSigners)throw new Error("extra_signers has been already set - setting extra_signers would overwrite it.");if(e.length>2)throw new Error("extra_signers cannot be longer than 2 elements.");return this.extraSigners=v(e),this}},{key:"setNetworkPassphrase",value:function(e){return this.networkPassphrase=e,this}},{key:"setSorobanData",value:function(e){return this.sorobanData=new f.SorobanDataBuilder(e).build(),this}},{key:"build",value:function(){var e=new o.default(this.source.sequenceNumber()).plus(1),t={fee:new o.default(this.baseFee).times(this.operations.length).toNumber(),seqNum:i.default.SequenceNumber.fromString(e.toString()),memo:this.memo?this.memo.toXDRObject():null};if(null===this.timebounds||void 0===this.timebounds.minTime||void 0===this.timebounds.maxTime)throw new Error("TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).");T(this.timebounds.minTime)&&(this.timebounds.minTime=this.timebounds.minTime.getTime()/1e3),T(this.timebounds.maxTime)&&(this.timebounds.maxTime=this.timebounds.maxTime.getTime()/1e3),this.timebounds.minTime=n.UnsignedHyper.fromString(this.timebounds.minTime.toString()),this.timebounds.maxTime=n.UnsignedHyper.fromString(this.timebounds.maxTime.toString());var r=new i.default.TimeBounds(this.timebounds);if(this.hasV2Preconditions()){var a=null;null!==this.ledgerbounds&&(a=new i.default.LedgerBounds(this.ledgerbounds));var u=this.minAccountSequence||"0";u=i.default.SequenceNumber.fromString(u);var l=n.UnsignedHyper.fromString(null!==this.minAccountSequenceAge?this.minAccountSequenceAge.toString():"0"),f=this.minAccountSequenceLedgerGap||0,p=null!==this.extraSigners?this.extraSigners.map(d.SignerKey.decodeAddress):[];t.cond=i.default.Preconditions.precondV2(new i.default.PreconditionsV2({timeBounds:r,ledgerBounds:a,minSeqNum:u,minSeqAge:l,minSeqLedgerGap:f,extraSigners:p}))}else t.cond=i.default.Preconditions.precondTime(r);t.sourceAccount=(0,s.decodeAddressToMuxedAccount)(this.source.accountId()),this.sorobanData?t.ext=new i.default.TransactionExt(1,this.sorobanData):t.ext=new i.default.TransactionExt(0,i.default.Void);var h=new i.default.Transaction(t);h.operations(this.operations);var y=new i.default.TransactionEnvelope.envelopeTypeTx(new i.default.TransactionV1Envelope({tx:h})),m=new c.Transaction(y,this.networkPassphrase);return this.source.incrementSequenceNumber(),m}},{key:"hasV2Preconditions",value:function(){return null!==this.ledgerbounds||null!==this.minAccountSequence||null!==this.minAccountSequenceAge||null!==this.minAccountSequenceLedgerGap||null!==this.extraSigners&&this.extraSigners.length>0}}])&&k(t.prototype,r),y&&k(t,y),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,y}();function T(e){return e instanceof Date&&!isNaN(e)}},1242:(e,t,r)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=((n=r(1594))&&n.__esModule?n:{default:n}).default.clone();o.DEBUG=!0;t.default=o},1346:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyChecksum=function(e,t){if(e.length!==t.length)return!1;if(0===e.length)return!0;for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.best_r=function(e){var t,r,n=new o.default(e),u=[[new o.default(0),new o.default(1)],[new o.default(1),new o.default(0)]],s=2;for(;!n.gt(a);){t=n.integerValue(o.default.ROUND_FLOOR),r=n.minus(t);var c=t.times(u[s-1][0]).plus(u[s-2][0]),l=t.times(u[s-1][1]).plus(u[s-2][1]);if(c.gt(a)||l.gt(a))break;if(u.push([c,l]),r.eq(0))break;n=new o.default(1).div(r),s+=1}var f=(h=u[u.length-1],y=2,function(e){if(Array.isArray(e))return e}(h)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,u=[],s=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=i.call(r)).done)&&(u.push(n.value),u.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return u}}(h,y)||function(e,t){if(e){if("string"==typeof e)return i(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(e,t):void 0}}(h,y)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),p=f[0],d=f[1];var h,y;if(p.isZero()||d.isZero())throw new Error("Couldn't find approximation");return[p.toNumber(),d.toNumber()]};var n,o=(n=r(1242))&&n.__esModule?n:{default:n};function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.decodeAddressToMuxedAccount=u,t.encodeMuxedAccount=function(e,t){if(!a.StrKey.isValidEd25519PublicKey(e))throw new Error("address should be a Stellar account ID (G...)");if("string"!=typeof t)throw new Error("id should be a string representing a number (uint64)");return i.default.MuxedAccount.keyTypeMuxedEd25519(new i.default.MuxedAccountMed25519({id:i.default.Uint64.fromString(t),ed25519:a.StrKey.decodeEd25519PublicKey(e)}))},t.encodeMuxedAccountToAddress=s,t.extractBaseAddress=function(e){if(a.StrKey.isValidEd25519PublicKey(e))return e;if(!a.StrKey.isValidMed25519PublicKey(e))throw new TypeError("expected muxed account (M...), got ".concat(e));var t=u(e);return a.StrKey.encodeEd25519PublicKey(t.med25519().ed25519())};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(7120);function u(e){return a.StrKey.isValidMed25519PublicKey(e)?function(e){var t=a.StrKey.decodeMed25519PublicKey(e);return i.default.MuxedAccount.keyTypeMuxedEd25519(new i.default.MuxedAccountMed25519({id:i.default.Uint64.fromXDR(t.subarray(-8)),ed25519:t.subarray(0,-8)}))}(e):i.default.MuxedAccount.keyTypeEd25519(a.StrKey.decodeEd25519PublicKey(e))}function s(e){return e.switch().value===i.default.CryptoKeyType.keyTypeMuxedEd25519().value?function(e){if(e.switch()===i.default.CryptoKeyType.keyTypeEd25519())return s(e);var t=e.med25519();return a.StrKey.encodeMed25519PublicKey(n.concat([t.ed25519(),t.id().toXDR("raw")]))}(e):a.StrKey.encodeEd25519PublicKey(e.ed25519())}},645:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.trimEnd=void 0;t.trimEnd=function(e,t){for(var r="number"==typeof e,n=String(e);n.endsWith(t);)n=n.slice(0,-1);return r?Number(n):n}},1918:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,o=(n=r(7938))&&n.__esModule?n:{default:n};t.default=o.default},4940:(e,t,r)=>{!function(e){"use strict";var t=function(e){var t,r=new Float64Array(16);if(e)for(t=0;t>24&255,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r,e[t+4]=n>>24&255,e[t+5]=n>>16&255,e[t+6]=n>>8&255,e[t+7]=255&n}function y(e,t,r,n,o){var i,a=0;for(i=0;i>>8)-1}function m(e,t,r,n){return y(e,t,r,n,16)}function v(e,t,r,n){return y(e,t,r,n,32)}function g(e,t,r,n){!function(e,t,r,n){for(var o,i=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,u=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,s=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,c=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,l=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,p=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,h=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,y=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,m=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,v=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,g=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,b=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,w=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,S=i,k=a,E=u,_=s,T=c,O=l,x=f,A=p,P=d,I=h,R=y,C=m,j=v,B=g,L=b,N=w,U=0;U<20;U+=2)S^=(o=(j^=(o=(P^=(o=(T^=(o=S+j|0)<<7|o>>>25)+S|0)<<9|o>>>23)+T|0)<<13|o>>>19)+P|0)<<18|o>>>14,O^=(o=(k^=(o=(B^=(o=(I^=(o=O+k|0)<<7|o>>>25)+O|0)<<9|o>>>23)+I|0)<<13|o>>>19)+B|0)<<18|o>>>14,R^=(o=(x^=(o=(E^=(o=(L^=(o=R+x|0)<<7|o>>>25)+R|0)<<9|o>>>23)+L|0)<<13|o>>>19)+E|0)<<18|o>>>14,N^=(o=(C^=(o=(A^=(o=(_^=(o=N+C|0)<<7|o>>>25)+N|0)<<9|o>>>23)+_|0)<<13|o>>>19)+A|0)<<18|o>>>14,S^=(o=(_^=(o=(E^=(o=(k^=(o=S+_|0)<<7|o>>>25)+S|0)<<9|o>>>23)+k|0)<<13|o>>>19)+E|0)<<18|o>>>14,O^=(o=(T^=(o=(A^=(o=(x^=(o=O+T|0)<<7|o>>>25)+O|0)<<9|o>>>23)+x|0)<<13|o>>>19)+A|0)<<18|o>>>14,R^=(o=(I^=(o=(P^=(o=(C^=(o=R+I|0)<<7|o>>>25)+R|0)<<9|o>>>23)+C|0)<<13|o>>>19)+P|0)<<18|o>>>14,N^=(o=(L^=(o=(B^=(o=(j^=(o=N+L|0)<<7|o>>>25)+N|0)<<9|o>>>23)+j|0)<<13|o>>>19)+B|0)<<18|o>>>14;S=S+i|0,k=k+a|0,E=E+u|0,_=_+s|0,T=T+c|0,O=O+l|0,x=x+f|0,A=A+p|0,P=P+d|0,I=I+h|0,R=R+y|0,C=C+m|0,j=j+v|0,B=B+g|0,L=L+b|0,N=N+w|0,e[0]=S>>>0&255,e[1]=S>>>8&255,e[2]=S>>>16&255,e[3]=S>>>24&255,e[4]=k>>>0&255,e[5]=k>>>8&255,e[6]=k>>>16&255,e[7]=k>>>24&255,e[8]=E>>>0&255,e[9]=E>>>8&255,e[10]=E>>>16&255,e[11]=E>>>24&255,e[12]=_>>>0&255,e[13]=_>>>8&255,e[14]=_>>>16&255,e[15]=_>>>24&255,e[16]=T>>>0&255,e[17]=T>>>8&255,e[18]=T>>>16&255,e[19]=T>>>24&255,e[20]=O>>>0&255,e[21]=O>>>8&255,e[22]=O>>>16&255,e[23]=O>>>24&255,e[24]=x>>>0&255,e[25]=x>>>8&255,e[26]=x>>>16&255,e[27]=x>>>24&255,e[28]=A>>>0&255,e[29]=A>>>8&255,e[30]=A>>>16&255,e[31]=A>>>24&255,e[32]=P>>>0&255,e[33]=P>>>8&255,e[34]=P>>>16&255,e[35]=P>>>24&255,e[36]=I>>>0&255,e[37]=I>>>8&255,e[38]=I>>>16&255,e[39]=I>>>24&255,e[40]=R>>>0&255,e[41]=R>>>8&255,e[42]=R>>>16&255,e[43]=R>>>24&255,e[44]=C>>>0&255,e[45]=C>>>8&255,e[46]=C>>>16&255,e[47]=C>>>24&255,e[48]=j>>>0&255,e[49]=j>>>8&255,e[50]=j>>>16&255,e[51]=j>>>24&255,e[52]=B>>>0&255,e[53]=B>>>8&255,e[54]=B>>>16&255,e[55]=B>>>24&255,e[56]=L>>>0&255,e[57]=L>>>8&255,e[58]=L>>>16&255,e[59]=L>>>24&255,e[60]=N>>>0&255,e[61]=N>>>8&255,e[62]=N>>>16&255,e[63]=N>>>24&255}(e,t,r,n)}function b(e,t,r,n){!function(e,t,r,n){for(var o,i=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,u=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,s=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,c=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,l=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,p=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,h=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,y=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,m=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,v=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,g=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,b=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,w=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,S=0;S<20;S+=2)i^=(o=(v^=(o=(d^=(o=(c^=(o=i+v|0)<<7|o>>>25)+i|0)<<9|o>>>23)+c|0)<<13|o>>>19)+d|0)<<18|o>>>14,l^=(o=(a^=(o=(g^=(o=(h^=(o=l+a|0)<<7|o>>>25)+l|0)<<9|o>>>23)+h|0)<<13|o>>>19)+g|0)<<18|o>>>14,y^=(o=(f^=(o=(u^=(o=(b^=(o=y+f|0)<<7|o>>>25)+y|0)<<9|o>>>23)+b|0)<<13|o>>>19)+u|0)<<18|o>>>14,w^=(o=(m^=(o=(p^=(o=(s^=(o=w+m|0)<<7|o>>>25)+w|0)<<9|o>>>23)+s|0)<<13|o>>>19)+p|0)<<18|o>>>14,i^=(o=(s^=(o=(u^=(o=(a^=(o=i+s|0)<<7|o>>>25)+i|0)<<9|o>>>23)+a|0)<<13|o>>>19)+u|0)<<18|o>>>14,l^=(o=(c^=(o=(p^=(o=(f^=(o=l+c|0)<<7|o>>>25)+l|0)<<9|o>>>23)+f|0)<<13|o>>>19)+p|0)<<18|o>>>14,y^=(o=(h^=(o=(d^=(o=(m^=(o=y+h|0)<<7|o>>>25)+y|0)<<9|o>>>23)+m|0)<<13|o>>>19)+d|0)<<18|o>>>14,w^=(o=(b^=(o=(g^=(o=(v^=(o=w+b|0)<<7|o>>>25)+w|0)<<9|o>>>23)+v|0)<<13|o>>>19)+g|0)<<18|o>>>14;e[0]=i>>>0&255,e[1]=i>>>8&255,e[2]=i>>>16&255,e[3]=i>>>24&255,e[4]=l>>>0&255,e[5]=l>>>8&255,e[6]=l>>>16&255,e[7]=l>>>24&255,e[8]=y>>>0&255,e[9]=y>>>8&255,e[10]=y>>>16&255,e[11]=y>>>24&255,e[12]=w>>>0&255,e[13]=w>>>8&255,e[14]=w>>>16&255,e[15]=w>>>24&255,e[16]=f>>>0&255,e[17]=f>>>8&255,e[18]=f>>>16&255,e[19]=f>>>24&255,e[20]=p>>>0&255,e[21]=p>>>8&255,e[22]=p>>>16&255,e[23]=p>>>24&255,e[24]=d>>>0&255,e[25]=d>>>8&255,e[26]=d>>>16&255,e[27]=d>>>24&255,e[28]=h>>>0&255,e[29]=h>>>8&255,e[30]=h>>>16&255,e[31]=h>>>24&255}(e,t,r,n)}var w=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function S(e,t,r,n,o,i,a){var u,s,c=new Uint8Array(16),l=new Uint8Array(64);for(s=0;s<16;s++)c[s]=0;for(s=0;s<8;s++)c[s]=i[s];for(;o>=64;){for(g(l,c,a,w),s=0;s<64;s++)e[t+s]=r[n+s]^l[s];for(u=1,s=8;s<16;s++)u=u+(255&c[s])|0,c[s]=255&u,u>>>=8;o-=64,t+=64,n+=64}if(o>0)for(g(l,c,a,w),s=0;s=64;){for(g(s,u,o,w),a=0;a<64;a++)e[t+a]=s[a];for(i=1,a=8;a<16;a++)i=i+(255&u[a])|0,u[a]=255&i,i>>>=8;r-=64,t+=64}if(r>0)for(g(s,u,o,w),a=0;a>>13|r<<3),n=255&e[4]|(255&e[5])<<8,this.r[2]=7939&(r>>>10|n<<6),o=255&e[6]|(255&e[7])<<8,this.r[3]=8191&(n>>>7|o<<9),i=255&e[8]|(255&e[9])<<8,this.r[4]=255&(o>>>4|i<<12),this.r[5]=i>>>1&8190,a=255&e[10]|(255&e[11])<<8,this.r[6]=8191&(i>>>14|a<<2),u=255&e[12]|(255&e[13])<<8,this.r[7]=8065&(a>>>11|u<<5),s=255&e[14]|(255&e[15])<<8,this.r[8]=8191&(u>>>8|s<<8),this.r[9]=s>>>5&127,this.pad[0]=255&e[16]|(255&e[17])<<8,this.pad[1]=255&e[18]|(255&e[19])<<8,this.pad[2]=255&e[20]|(255&e[21])<<8,this.pad[3]=255&e[22]|(255&e[23])<<8,this.pad[4]=255&e[24]|(255&e[25])<<8,this.pad[5]=255&e[26]|(255&e[27])<<8,this.pad[6]=255&e[28]|(255&e[29])<<8,this.pad[7]=255&e[30]|(255&e[31])<<8};function O(e,t,r,n,o,i){var a=new T(i);return a.update(r,n,o),a.finish(e,t),0}function x(e,t,r,n,o,i){var a=new Uint8Array(16);return O(a,0,r,n,o,i),m(e,t,a,0)}function A(e,t,r,n,o){var i;if(r<32)return-1;for(_(e,0,t,0,r,n,o),O(e,16,e,32,r-32,e),i=0;i<16;i++)e[i]=0;return 0}function P(e,t,r,n,o){var i,a=new Uint8Array(32);if(r<32)return-1;if(E(a,0,32,n,o),0!==x(t,16,t,32,r-32,a))return-1;for(_(e,0,t,0,r,n,o),i=0;i<32;i++)e[i]=0;return 0}function I(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function R(e){var t,r,n=1;for(t=0;t<16;t++)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function C(e,t,r){for(var n,o=~(r-1),i=0;i<16;i++)n=o&(e[i]^t[i]),e[i]^=n,t[i]^=n}function j(e,r){var n,o,i,a=t(),u=t();for(n=0;n<16;n++)u[n]=r[n];for(R(u),R(u),R(u),o=0;o<2;o++){for(a[0]=u[0]-65517,n=1;n<15;n++)a[n]=u[n]-65535-(a[n-1]>>16&1),a[n-1]&=65535;a[15]=u[15]-32767-(a[14]>>16&1),i=a[15]>>16&1,a[14]&=65535,C(u,a,1-i)}for(n=0;n<16;n++)e[2*n]=255&u[n],e[2*n+1]=u[n]>>8}function B(e,t){var r=new Uint8Array(32),n=new Uint8Array(32);return j(r,e),j(n,t),v(r,0,n,0)}function L(e){var t=new Uint8Array(32);return j(t,e),1&t[0]}function N(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function U(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]+r[n]}function M(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]-r[n]}function F(e,t,r){var n,o,i=0,a=0,u=0,s=0,c=0,l=0,f=0,p=0,d=0,h=0,y=0,m=0,v=0,g=0,b=0,w=0,S=0,k=0,E=0,_=0,T=0,O=0,x=0,A=0,P=0,I=0,R=0,C=0,j=0,B=0,L=0,N=r[0],U=r[1],M=r[2],F=r[3],D=r[4],V=r[5],q=r[6],K=r[7],H=r[8],z=r[9],X=r[10],G=r[11],$=r[12],Q=r[13],W=r[14],Y=r[15];i+=(n=t[0])*N,a+=n*U,u+=n*M,s+=n*F,c+=n*D,l+=n*V,f+=n*q,p+=n*K,d+=n*H,h+=n*z,y+=n*X,m+=n*G,v+=n*$,g+=n*Q,b+=n*W,w+=n*Y,a+=(n=t[1])*N,u+=n*U,s+=n*M,c+=n*F,l+=n*D,f+=n*V,p+=n*q,d+=n*K,h+=n*H,y+=n*z,m+=n*X,v+=n*G,g+=n*$,b+=n*Q,w+=n*W,S+=n*Y,u+=(n=t[2])*N,s+=n*U,c+=n*M,l+=n*F,f+=n*D,p+=n*V,d+=n*q,h+=n*K,y+=n*H,m+=n*z,v+=n*X,g+=n*G,b+=n*$,w+=n*Q,S+=n*W,k+=n*Y,s+=(n=t[3])*N,c+=n*U,l+=n*M,f+=n*F,p+=n*D,d+=n*V,h+=n*q,y+=n*K,m+=n*H,v+=n*z,g+=n*X,b+=n*G,w+=n*$,S+=n*Q,k+=n*W,E+=n*Y,c+=(n=t[4])*N,l+=n*U,f+=n*M,p+=n*F,d+=n*D,h+=n*V,y+=n*q,m+=n*K,v+=n*H,g+=n*z,b+=n*X,w+=n*G,S+=n*$,k+=n*Q,E+=n*W,_+=n*Y,l+=(n=t[5])*N,f+=n*U,p+=n*M,d+=n*F,h+=n*D,y+=n*V,m+=n*q,v+=n*K,g+=n*H,b+=n*z,w+=n*X,S+=n*G,k+=n*$,E+=n*Q,_+=n*W,T+=n*Y,f+=(n=t[6])*N,p+=n*U,d+=n*M,h+=n*F,y+=n*D,m+=n*V,v+=n*q,g+=n*K,b+=n*H,w+=n*z,S+=n*X,k+=n*G,E+=n*$,_+=n*Q,T+=n*W,O+=n*Y,p+=(n=t[7])*N,d+=n*U,h+=n*M,y+=n*F,m+=n*D,v+=n*V,g+=n*q,b+=n*K,w+=n*H,S+=n*z,k+=n*X,E+=n*G,_+=n*$,T+=n*Q,O+=n*W,x+=n*Y,d+=(n=t[8])*N,h+=n*U,y+=n*M,m+=n*F,v+=n*D,g+=n*V,b+=n*q,w+=n*K,S+=n*H,k+=n*z,E+=n*X,_+=n*G,T+=n*$,O+=n*Q,x+=n*W,A+=n*Y,h+=(n=t[9])*N,y+=n*U,m+=n*M,v+=n*F,g+=n*D,b+=n*V,w+=n*q,S+=n*K,k+=n*H,E+=n*z,_+=n*X,T+=n*G,O+=n*$,x+=n*Q,A+=n*W,P+=n*Y,y+=(n=t[10])*N,m+=n*U,v+=n*M,g+=n*F,b+=n*D,w+=n*V,S+=n*q,k+=n*K,E+=n*H,_+=n*z,T+=n*X,O+=n*G,x+=n*$,A+=n*Q,P+=n*W,I+=n*Y,m+=(n=t[11])*N,v+=n*U,g+=n*M,b+=n*F,w+=n*D,S+=n*V,k+=n*q,E+=n*K,_+=n*H,T+=n*z,O+=n*X,x+=n*G,A+=n*$,P+=n*Q,I+=n*W,R+=n*Y,v+=(n=t[12])*N,g+=n*U,b+=n*M,w+=n*F,S+=n*D,k+=n*V,E+=n*q,_+=n*K,T+=n*H,O+=n*z,x+=n*X,A+=n*G,P+=n*$,I+=n*Q,R+=n*W,C+=n*Y,g+=(n=t[13])*N,b+=n*U,w+=n*M,S+=n*F,k+=n*D,E+=n*V,_+=n*q,T+=n*K,O+=n*H,x+=n*z,A+=n*X,P+=n*G,I+=n*$,R+=n*Q,C+=n*W,j+=n*Y,b+=(n=t[14])*N,w+=n*U,S+=n*M,k+=n*F,E+=n*D,_+=n*V,T+=n*q,O+=n*K,x+=n*H,A+=n*z,P+=n*X,I+=n*G,R+=n*$,C+=n*Q,j+=n*W,B+=n*Y,w+=(n=t[15])*N,a+=38*(k+=n*M),u+=38*(E+=n*F),s+=38*(_+=n*D),c+=38*(T+=n*V),l+=38*(O+=n*q),f+=38*(x+=n*K),p+=38*(A+=n*H),d+=38*(P+=n*z),h+=38*(I+=n*X),y+=38*(R+=n*G),m+=38*(C+=n*$),v+=38*(j+=n*Q),g+=38*(B+=n*W),b+=38*(L+=n*Y),i=(n=(i+=38*(S+=n*U))+(o=1)+65535)-65536*(o=Math.floor(n/65536)),a=(n=a+o+65535)-65536*(o=Math.floor(n/65536)),u=(n=u+o+65535)-65536*(o=Math.floor(n/65536)),s=(n=s+o+65535)-65536*(o=Math.floor(n/65536)),c=(n=c+o+65535)-65536*(o=Math.floor(n/65536)),l=(n=l+o+65535)-65536*(o=Math.floor(n/65536)),f=(n=f+o+65535)-65536*(o=Math.floor(n/65536)),p=(n=p+o+65535)-65536*(o=Math.floor(n/65536)),d=(n=d+o+65535)-65536*(o=Math.floor(n/65536)),h=(n=h+o+65535)-65536*(o=Math.floor(n/65536)),y=(n=y+o+65535)-65536*(o=Math.floor(n/65536)),m=(n=m+o+65535)-65536*(o=Math.floor(n/65536)),v=(n=v+o+65535)-65536*(o=Math.floor(n/65536)),g=(n=g+o+65535)-65536*(o=Math.floor(n/65536)),b=(n=b+o+65535)-65536*(o=Math.floor(n/65536)),w=(n=w+o+65535)-65536*(o=Math.floor(n/65536)),i=(n=(i+=o-1+37*(o-1))+(o=1)+65535)-65536*(o=Math.floor(n/65536)),a=(n=a+o+65535)-65536*(o=Math.floor(n/65536)),u=(n=u+o+65535)-65536*(o=Math.floor(n/65536)),s=(n=s+o+65535)-65536*(o=Math.floor(n/65536)),c=(n=c+o+65535)-65536*(o=Math.floor(n/65536)),l=(n=l+o+65535)-65536*(o=Math.floor(n/65536)),f=(n=f+o+65535)-65536*(o=Math.floor(n/65536)),p=(n=p+o+65535)-65536*(o=Math.floor(n/65536)),d=(n=d+o+65535)-65536*(o=Math.floor(n/65536)),h=(n=h+o+65535)-65536*(o=Math.floor(n/65536)),y=(n=y+o+65535)-65536*(o=Math.floor(n/65536)),m=(n=m+o+65535)-65536*(o=Math.floor(n/65536)),v=(n=v+o+65535)-65536*(o=Math.floor(n/65536)),g=(n=g+o+65535)-65536*(o=Math.floor(n/65536)),b=(n=b+o+65535)-65536*(o=Math.floor(n/65536)),w=(n=w+o+65535)-65536*(o=Math.floor(n/65536)),i+=o-1+37*(o-1),e[0]=i,e[1]=a,e[2]=u,e[3]=s,e[4]=c,e[5]=l,e[6]=f,e[7]=p,e[8]=d,e[9]=h,e[10]=y,e[11]=m,e[12]=v,e[13]=g,e[14]=b,e[15]=w}function D(e,t){F(e,t,t)}function V(e,r){var n,o=t();for(n=0;n<16;n++)o[n]=r[n];for(n=253;n>=0;n--)D(o,o),2!==n&&4!==n&&F(o,o,r);for(n=0;n<16;n++)e[n]=o[n]}function q(e,r){var n,o=t();for(n=0;n<16;n++)o[n]=r[n];for(n=250;n>=0;n--)D(o,o),1!==n&&F(o,o,r);for(n=0;n<16;n++)e[n]=o[n]}function K(e,r,n){var o,i,a=new Uint8Array(32),u=new Float64Array(80),c=t(),l=t(),f=t(),p=t(),d=t(),h=t();for(i=0;i<31;i++)a[i]=r[i];for(a[31]=127&r[31]|64,a[0]&=248,N(u,n),i=0;i<16;i++)l[i]=u[i],p[i]=c[i]=f[i]=0;for(c[0]=p[0]=1,i=254;i>=0;--i)C(c,l,o=a[i>>>3]>>>(7&i)&1),C(f,p,o),U(d,c,f),M(c,c,f),U(f,l,p),M(l,l,p),D(p,d),D(h,c),F(c,f,c),F(f,l,d),U(d,c,f),M(c,c,f),D(l,c),M(f,p,h),F(c,f,s),U(c,c,p),F(f,f,c),F(c,p,h),F(p,l,u),D(l,d),C(c,l,o),C(f,p,o);for(i=0;i<16;i++)u[i+16]=c[i],u[i+32]=f[i],u[i+48]=l[i],u[i+64]=p[i];var y=u.subarray(32),m=u.subarray(16);return V(y,y),F(m,m,y),j(e,m),0}function H(e,t){return K(e,t,i)}function z(e,t){return n(t,32),H(e,t)}function X(e,t,r){var n=new Uint8Array(32);return K(n,r,t),b(e,o,n,w)}T.prototype.blocks=function(e,t,r){for(var n,o,i,a,u,s,c,l,f,p,d,h,y,m,v,g,b,w,S,k=this.fin?0:2048,E=this.h[0],_=this.h[1],T=this.h[2],O=this.h[3],x=this.h[4],A=this.h[5],P=this.h[6],I=this.h[7],R=this.h[8],C=this.h[9],j=this.r[0],B=this.r[1],L=this.r[2],N=this.r[3],U=this.r[4],M=this.r[5],F=this.r[6],D=this.r[7],V=this.r[8],q=this.r[9];r>=16;)p=f=0,p+=(E+=8191&(n=255&e[t+0]|(255&e[t+1])<<8))*j,p+=(_+=8191&(n>>>13|(o=255&e[t+2]|(255&e[t+3])<<8)<<3))*(5*q),p+=(T+=8191&(o>>>10|(i=255&e[t+4]|(255&e[t+5])<<8)<<6))*(5*V),p+=(O+=8191&(i>>>7|(a=255&e[t+6]|(255&e[t+7])<<8)<<9))*(5*D),f=(p+=(x+=8191&(a>>>4|(u=255&e[t+8]|(255&e[t+9])<<8)<<12))*(5*F))>>>13,p&=8191,p+=(A+=u>>>1&8191)*(5*M),p+=(P+=8191&(u>>>14|(s=255&e[t+10]|(255&e[t+11])<<8)<<2))*(5*U),p+=(I+=8191&(s>>>11|(c=255&e[t+12]|(255&e[t+13])<<8)<<5))*(5*N),p+=(R+=8191&(c>>>8|(l=255&e[t+14]|(255&e[t+15])<<8)<<8))*(5*L),d=f+=(p+=(C+=l>>>5|k)*(5*B))>>>13,d+=E*B,d+=_*j,d+=T*(5*q),d+=O*(5*V),f=(d+=x*(5*D))>>>13,d&=8191,d+=A*(5*F),d+=P*(5*M),d+=I*(5*U),d+=R*(5*N),f+=(d+=C*(5*L))>>>13,d&=8191,h=f,h+=E*L,h+=_*B,h+=T*j,h+=O*(5*q),f=(h+=x*(5*V))>>>13,h&=8191,h+=A*(5*D),h+=P*(5*F),h+=I*(5*M),h+=R*(5*U),y=f+=(h+=C*(5*N))>>>13,y+=E*N,y+=_*L,y+=T*B,y+=O*j,f=(y+=x*(5*q))>>>13,y&=8191,y+=A*(5*V),y+=P*(5*D),y+=I*(5*F),y+=R*(5*M),m=f+=(y+=C*(5*U))>>>13,m+=E*U,m+=_*N,m+=T*L,m+=O*B,f=(m+=x*j)>>>13,m&=8191,m+=A*(5*q),m+=P*(5*V),m+=I*(5*D),m+=R*(5*F),v=f+=(m+=C*(5*M))>>>13,v+=E*M,v+=_*U,v+=T*N,v+=O*L,f=(v+=x*B)>>>13,v&=8191,v+=A*j,v+=P*(5*q),v+=I*(5*V),v+=R*(5*D),g=f+=(v+=C*(5*F))>>>13,g+=E*F,g+=_*M,g+=T*U,g+=O*N,f=(g+=x*L)>>>13,g&=8191,g+=A*B,g+=P*j,g+=I*(5*q),g+=R*(5*V),b=f+=(g+=C*(5*D))>>>13,b+=E*D,b+=_*F,b+=T*M,b+=O*U,f=(b+=x*N)>>>13,b&=8191,b+=A*L,b+=P*B,b+=I*j,b+=R*(5*q),w=f+=(b+=C*(5*V))>>>13,w+=E*V,w+=_*D,w+=T*F,w+=O*M,f=(w+=x*U)>>>13,w&=8191,w+=A*N,w+=P*L,w+=I*B,w+=R*j,S=f+=(w+=C*(5*q))>>>13,S+=E*q,S+=_*V,S+=T*D,S+=O*F,f=(S+=x*M)>>>13,S&=8191,S+=A*U,S+=P*N,S+=I*L,S+=R*B,E=p=8191&(f=(f=((f+=(S+=C*j)>>>13)<<2)+f|0)+(p&=8191)|0),_=d+=f>>>=13,T=h&=8191,O=y&=8191,x=m&=8191,A=v&=8191,P=g&=8191,I=b&=8191,R=w&=8191,C=S&=8191,t+=16,r-=16;this.h[0]=E,this.h[1]=_,this.h[2]=T,this.h[3]=O,this.h[4]=x,this.h[5]=A,this.h[6]=P,this.h[7]=I,this.h[8]=R,this.h[9]=C},T.prototype.finish=function(e,t){var r,n,o,i,a=new Uint16Array(10);if(this.leftover){for(i=this.leftover,this.buffer[i++]=1;i<16;i++)this.buffer[i]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(r=this.h[1]>>>13,this.h[1]&=8191,i=2;i<10;i++)this.h[i]+=r,r=this.h[i]>>>13,this.h[i]&=8191;for(this.h[0]+=5*r,r=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=r,r=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=r,a[0]=this.h[0]+5,r=a[0]>>>13,a[0]&=8191,i=1;i<10;i++)a[i]=this.h[i]+r,r=a[i]>>>13,a[i]&=8191;for(a[9]-=8192,n=(1^r)-1,i=0;i<10;i++)a[i]&=n;for(n=~n,i=0;i<10;i++)this.h[i]=this.h[i]&n|a[i];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),o=this.h[0]+this.pad[0],this.h[0]=65535&o,i=1;i<8;i++)o=(this.h[i]+this.pad[i]|0)+(o>>>16)|0,this.h[i]=65535&o;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},T.prototype.update=function(e,t,r){var n,o;if(this.leftover){for((o=16-this.leftover)>r&&(o=r),n=0;n=16&&(o=r-r%16,this.blocks(e,t,o),t+=o,r-=o),r){for(n=0;n=128;){for(k=0;k<16;k++)E=8*k+$,I[k]=r[E+0]<<24|r[E+1]<<16|r[E+2]<<8|r[E+3],R[k]=r[E+4]<<24|r[E+5]<<16|r[E+6]<<8|r[E+7];for(k=0;k<80;k++)if(o=C,i=j,a=B,u=L,s=N,c=U,l=M,F,p=D,d=V,h=q,y=K,m=H,v=z,g=X,G,O=65535&(T=G),x=T>>>16,A=65535&(_=F),P=_>>>16,O+=65535&(T=(H>>>14|N<<18)^(H>>>18|N<<14)^(N>>>9|H<<23)),x+=T>>>16,A+=65535&(_=(N>>>14|H<<18)^(N>>>18|H<<14)^(H>>>9|N<<23)),P+=_>>>16,O+=65535&(T=H&z^~H&X),x+=T>>>16,A+=65535&(_=N&U^~N&M),P+=_>>>16,O+=65535&(T=Q[2*k+1]),x+=T>>>16,A+=65535&(_=Q[2*k]),P+=_>>>16,_=I[k%16],x+=(T=R[k%16])>>>16,A+=65535&_,P+=_>>>16,A+=(x+=(O+=65535&T)>>>16)>>>16,O=65535&(T=S=65535&O|x<<16),x=T>>>16,A=65535&(_=w=65535&A|(P+=A>>>16)<<16),P=_>>>16,O+=65535&(T=(D>>>28|C<<4)^(C>>>2|D<<30)^(C>>>7|D<<25)),x+=T>>>16,A+=65535&(_=(C>>>28|D<<4)^(D>>>2|C<<30)^(D>>>7|C<<25)),P+=_>>>16,x+=(T=D&V^D&q^V&q)>>>16,A+=65535&(_=C&j^C&B^j&B),P+=_>>>16,f=65535&(A+=(x+=(O+=65535&T)>>>16)>>>16)|(P+=A>>>16)<<16,b=65535&O|x<<16,O=65535&(T=y),x=T>>>16,A=65535&(_=u),P=_>>>16,x+=(T=S)>>>16,A+=65535&(_=w),P+=_>>>16,j=o,B=i,L=a,N=u=65535&(A+=(x+=(O+=65535&T)>>>16)>>>16)|(P+=A>>>16)<<16,U=s,M=c,F=l,C=f,V=p,q=d,K=h,H=y=65535&O|x<<16,z=m,X=v,G=g,D=b,k%16==15)for(E=0;E<16;E++)_=I[E],O=65535&(T=R[E]),x=T>>>16,A=65535&_,P=_>>>16,_=I[(E+9)%16],O+=65535&(T=R[(E+9)%16]),x+=T>>>16,A+=65535&_,P+=_>>>16,w=I[(E+1)%16],O+=65535&(T=((S=R[(E+1)%16])>>>1|w<<31)^(S>>>8|w<<24)^(S>>>7|w<<25)),x+=T>>>16,A+=65535&(_=(w>>>1|S<<31)^(w>>>8|S<<24)^w>>>7),P+=_>>>16,w=I[(E+14)%16],x+=(T=((S=R[(E+14)%16])>>>19|w<<13)^(w>>>29|S<<3)^(S>>>6|w<<26))>>>16,A+=65535&(_=(w>>>19|S<<13)^(S>>>29|w<<3)^w>>>6),P+=_>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,I[E]=65535&A|P<<16,R[E]=65535&O|x<<16;O=65535&(T=D),x=T>>>16,A=65535&(_=C),P=_>>>16,_=e[0],x+=(T=t[0])>>>16,A+=65535&_,P+=_>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[0]=C=65535&A|P<<16,t[0]=D=65535&O|x<<16,O=65535&(T=V),x=T>>>16,A=65535&(_=j),P=_>>>16,_=e[1],x+=(T=t[1])>>>16,A+=65535&_,P+=_>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[1]=j=65535&A|P<<16,t[1]=V=65535&O|x<<16,O=65535&(T=q),x=T>>>16,A=65535&(_=B),P=_>>>16,_=e[2],x+=(T=t[2])>>>16,A+=65535&_,P+=_>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[2]=B=65535&A|P<<16,t[2]=q=65535&O|x<<16,O=65535&(T=K),x=T>>>16,A=65535&(_=L),P=_>>>16,_=e[3],x+=(T=t[3])>>>16,A+=65535&_,P+=_>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[3]=L=65535&A|P<<16,t[3]=K=65535&O|x<<16,O=65535&(T=H),x=T>>>16,A=65535&(_=N),P=_>>>16,_=e[4],x+=(T=t[4])>>>16,A+=65535&_,P+=_>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[4]=N=65535&A|P<<16,t[4]=H=65535&O|x<<16,O=65535&(T=z),x=T>>>16,A=65535&(_=U),P=_>>>16,_=e[5],x+=(T=t[5])>>>16,A+=65535&_,P+=_>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[5]=U=65535&A|P<<16,t[5]=z=65535&O|x<<16,O=65535&(T=X),x=T>>>16,A=65535&(_=M),P=_>>>16,_=e[6],x+=(T=t[6])>>>16,A+=65535&_,P+=_>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[6]=M=65535&A|P<<16,t[6]=X=65535&O|x<<16,O=65535&(T=G),x=T>>>16,A=65535&(_=F),P=_>>>16,_=e[7],x+=(T=t[7])>>>16,A+=65535&_,P+=_>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[7]=F=65535&A|P<<16,t[7]=G=65535&O|x<<16,$+=128,n-=128}return n}function Y(e,t,r){var n,o=new Int32Array(8),i=new Int32Array(8),a=new Uint8Array(256),u=r;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,i[0]=4089235720,i[1]=2227873595,i[2]=4271175723,i[3]=1595750129,i[4]=2917565137,i[5]=725511199,i[6]=4215389547,i[7]=327033209,W(o,i,t,r),r%=128,n=0;n=0;--o)Z(e,t,n=r[o/8|0]>>(7&o)&1),J(t,e),J(e,e),Z(e,t,n)}function re(e,r){var n=[t(),t(),t(),t()];I(n[0],f),I(n[1],p),I(n[2],u),F(n[3],f,p),te(e,n,r)}function ne(e,r,o){var i,a=new Uint8Array(64),u=[t(),t(),t(),t()];for(o||n(r,32),Y(a,r,32),a[0]&=248,a[31]&=127,a[31]|=64,re(u,a),ee(e,u),i=0;i<32;i++)r[i+32]=e[i];return 0}var oe=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function ie(e,t){var r,n,o,i;for(n=63;n>=32;--n){for(r=0,o=n-32,i=n-12;o>4)*oe[o],r=t[o]>>8,t[o]&=255;for(o=0;o<32;o++)t[o]-=r*oe[o];for(n=0;n<32;n++)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function ae(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;ie(e,r)}function ue(e,r,n,o){var i,a,u=new Uint8Array(64),s=new Uint8Array(64),c=new Uint8Array(64),l=new Float64Array(64),f=[t(),t(),t(),t()];Y(u,o,32),u[0]&=248,u[31]&=127,u[31]|=64;var p=n+64;for(i=0;i>7&&M(e[0],a,e[0]),F(e[3],e[0],e[1]),0)}(p,o))return-1;for(i=0;i=0},e.sign.keyPair=function(){var e=new Uint8Array(fe),t=new Uint8Array(pe);return ne(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(he(e),e.length!==pe)throw new Error("bad secret key size");for(var t=new Uint8Array(fe),r=0;r{"use strict";r.r(t),r.d(t,{StellarBase:()=>a,default:()=>u,httpClient:()=>n.ok});var n=r(6371),o=r(4356),i={};for(const e in o)["default","StellarBase","httpClient"].indexOf(e)<0&&(i[e]=()=>o[e]);r.d(t,i);var a=r(356);const u=(e=r.hmd(e)).exports},8732:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rh});var c,l,f,p={allowHttp:!1,timeout:0},d=a({},p),h=(c=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},f=[{key:"setAllowHttp",value:function(e){d.allowHttp=e}},{key:"setTimeout",value:function(e){d.timeout=e}},{key:"isAllowHttp",value:function(){return d.allowHttp}},{key:"getTimeout",value:function(){return d.timeout}},{key:"setDefault",value:function(){d=a({},p)}}],(l=null)&&o(c.prototype,l),f&&o(c,f),Object.defineProperty(c,"prototype",{writable:!1}),c)},6299:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AssembledTransaction:()=>de,Client:()=>tt,DEFAULT_TIMEOUT:()=>h,Err:()=>d,NULL_ACCOUNT:()=>y,Ok:()=>p,SentTransaction:()=>K,Spec:()=>Ne,basicNodeSigner:()=>be});var n=r(356),o=r(3496),i=r(4076),a=r(8680);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function c(e,t){for(var r=0;r=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),R(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;R(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function v(e){return v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},v(e)}function g(e,t,r,n,o,i,a){try{var u=e[i](a),s=u.value}catch(e){return void r(e)}u.done?t(s):Promise.resolve(s).then(n,o)}function b(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){g(i,n,o,a,u,"next",e)}function u(e){g(i,n,o,a,u,"throw",e)}a(void 0)}))}}function w(e,t,r){return S.apply(this,arguments)}function S(){return S=b(m().mark((function e(t,r,n){var o,i,a,u,s,c,l,f=arguments;return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=f.length>3&&void 0!==f[3]?f[3]:1.5,i=f.length>4&&void 0!==f[4]&&f[4],a=[],u=0,e.t0=a,e.next=7,t();case 7:if(e.t1=e.sent,e.t0.push.call(e.t0,e.t1),r(a[a.length-1])){e.next=11;break}return e.abrupt("return",a);case 11:s=new Date(Date.now()+1e3*n).valueOf(),l=c=1e3;case 14:if(!(Date.now()s&&(c=s-Date.now(),i&&console.info("was gonna wait too long; new waitTime: ".concat(c,"ms"))),l=c+l,e.t2=a,e.next=25,t(a[a.length-1]);case 25:e.t3=e.sent,e.t2.push.call(e.t2,e.t3),i&&r(a[a.length-1])&&console.info("".concat(u,". Called ").concat(t,"; ").concat(a.length," prev attempts. Most recent: ").concat(JSON.stringify(a[a.length-1],null,2))),e.next=14;break;case 30:return e.abrupt("return",a);case 31:case"end":return e.stop()}}),e)}))),S.apply(this,arguments)}var k,E=/Error\(Contract, #(\d+)\)/;function _(e){for(var t=new n.cereal.XdrReader(e),r=[];!t.eof;)r.push(n.xdr.ScSpecEntry.read(t));return r}function T(e,t){return O.apply(this,arguments)}function O(){return(O=b(m().mark((function e(t,r){return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.publicKey?r.getAccount(t.publicKey):new n.Account(y,"0"));case 1:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function x(e,t,r){return t=C(t),function(e,t){if(t&&("object"==j(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,I()?Reflect.construct(t,r||[],C(e).constructor):t.apply(e,r))}function A(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&R(e,t)}function P(e){var t="function"==typeof Map?new Map:void 0;return P=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(I())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var o=new(e.bind.apply(e,n));return r&&R(o,r.prototype),o}(e,arguments,C(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),R(r,e)},P(e)}function I(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(I=function(){return!!e})()}function R(e,t){return R=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},R(e,t)}function C(e){return C=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},C(e)}function j(e){return j="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},j(e)}function B(){B=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",s=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),u=new I(n||[]);return o(a,"_invoke",{value:O(e,r,u)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,k=S&&S(S(R([])));k&&k!==r&&n.call(k,a)&&(w=k);var E=b.prototype=v.prototype=Object.create(w);function _(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,u){var s=f(e[o],e,i);if("throw"!==s.type){var c=s.arg,l=c.value;return l&&"object"==j(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,u)}),(function(e){r("throw",e,a,u)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,u)}))}u(s.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var u=n.delegate;if(u){var s=x(u,n);if(s){if(s===m)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function I(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function R(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:R(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function L(e,t,r,n,o,i,a){try{var u=e[i](a),s=u.value}catch(e){return void r(e)}u.done?t(s):Promise.resolve(s).then(n,o)}function N(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){L(i,n,o,a,u,"next",e)}function u(e){L(i,n,o,a,u,"throw",e)}a(void 0)}))}}function U(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function M(e,t){for(var r=0;r=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,u=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){u=!0,i=e},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw i}}}}function re(){re=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",s=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),u=new I(n||[]);return o(a,"_invoke",{value:O(e,r,u)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,k=S&&S(S(R([])));k&&k!==r&&n.call(k,a)&&(w=k);var E=b.prototype=v.prototype=Object.create(w);function _(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,u){var s=f(e[o],e,i);if("throw"!==s.type){var c=s.arg,l=c.value;return l&&"object"==Y(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,u)}),(function(e){r("throw",e,a,u)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,u)}))}u(s.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var u=n.delegate;if(u){var s=x(u,n);if(s){if(s===m)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function I(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function R(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:R(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function ne(e){return function(e){if(Array.isArray(e))return ie(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||oe(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function oe(e,t){if(e){if("string"==typeof e)return ie(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ie(e,t):void 0}}function ie(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r0&&void 0!==y[0]?y[0]:{}).restore,s.built){t.next=5;break}if(s.raw){t.next=4;break}throw new Error("Transaction has not yet been assembled; call `AssembledTransaction.build` first.");case 4:s.built=s.raw.build();case 5:return o=null!==(r=o)&&void 0!==r?r:s.options.restore,delete s.simulationResult,delete s.simulationTransactionData,t.next=10,s.server.simulateTransaction(s.built);case 10:if(s.simulation=t.sent,!o||!i.j.isSimulationRestore(s.simulation)){t.next=25;break}return t.next=14,T(s.options,s.server);case 14:return u=t.sent,t.next=17,s.restoreFootprint(s.simulation.restorePreamble,u);case 17:if((c=t.sent).status!==i.j.GetTransactionStatus.SUCCESS){t.next=24;break}return d=new n.Contract(s.options.contractId),s.raw=new n.TransactionBuilder(u,{fee:null!==(l=s.options.fee)&&void 0!==l?l:n.BASE_FEE,networkPassphrase:s.options.networkPassphrase}).addOperation(d.call.apply(d,[s.options.method].concat(ne(null!==(f=s.options.args)&&void 0!==f?f:[])))).setTimeout(null!==(p=s.options.timeoutInSeconds)&&void 0!==p?p:h),t.next=23,s.simulate();case 23:return t.abrupt("return",s);case 24:throw new e.Errors.RestorationFailure("Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n".concat(JSON.stringify(c)));case 25:return i.j.isSimulationSuccess(s.simulation)&&(s.built=(0,a.X)(s.built,s.simulation).build()),t.abrupt("return",s);case 27:case"end":return t.stop()}}),t)})))),fe(this,"sign",ue(re().mark((function t(){var r,o,i,a,u,c,l,f,p,d,y,m,v=arguments;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i=(o=v.length>0&&void 0!==v[0]?v[0]:{}).force,a=void 0!==i&&i,u=o.signTransaction,c=void 0===u?s.options.signTransaction:u,s.built){t.next=3;break}throw new Error("Transaction has not yet been simulated");case 3:if(a||!s.isReadCall){t.next=5;break}throw new e.Errors.NoSignatureNeeded("This is a read call. It requires no signature or sending. Use `force: true` to sign and send anyway.");case 5:if(c){t.next=7;break}throw new e.Errors.NoSigner("You must provide a signTransaction function, either when calling `signAndSend` or when initializing your Client");case 7:if(!(l=s.needsNonInvokerSigningBy().filter((function(e){return!e.startsWith("C")}))).length){t.next=10;break}throw new e.Errors.NeedsMoreSignatures("Transaction requires signatures from ".concat(l,". ")+"See `needsNonInvokerSigningBy` for details.");case 10:return f=null!==(r=s.options.timeoutInSeconds)&&void 0!==r?r:h,s.built=n.TransactionBuilder.cloneFrom(s.built,{fee:s.built.fee,timebounds:void 0,sorobanData:s.simulationData.transactionData}).setTimeout(f).build(),p={networkPassphrase:s.options.networkPassphrase},s.options.address&&(p.address=s.options.address),void 0!==s.options.submit&&(p.submit=s.options.submit),s.options.submitUrl&&(p.submitUrl=s.options.submitUrl),t.next=18,c(s.built.toXDR(),p);case 18:d=t.sent,y=d.signedTxXdr,m=d.error,s.handleWalletError(m),s.signed=n.TransactionBuilder.fromXDR(y,s.options.networkPassphrase);case 23:case"end":return t.stop()}}),t)})))),fe(this,"signAndSend",ue(re().mark((function e(){var t,r,n,o,i,a,u=arguments;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=(t=u.length>0&&void 0!==u[0]?u[0]:{}).force,n=void 0!==r&&r,o=t.signTransaction,i=void 0===o?s.options.signTransaction:o,s.signed){e.next=10;break}return a=s.options.submit,s.options.submit&&(s.options.submit=!1),e.prev=4,e.next=7,s.sign({force:n,signTransaction:i});case 7:return e.prev=7,s.options.submit=a,e.finish(7);case 10:return e.abrupt("return",s.send());case 11:case"end":return e.stop()}}),e,null,[[4,,7,10]])})))),fe(this,"needsNonInvokerSigningBy",(function(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).includeAlreadySigned,r=void 0!==t&&t;if(!s.built)throw new Error("Transaction has not yet been simulated");if(!("operations"in s.built))throw new Error("Unexpected Transaction type; no operations: ".concat(JSON.stringify(s.built)));var o=s.built.operations[0];return ne(new Set((null!==(e=o.auth)&&void 0!==e?e:[]).filter((function(e){return e.credentials().switch()===n.xdr.SorobanCredentialsType.sorobanCredentialsAddress()&&(r||"scvVoid"===e.credentials().address().signature().switch().name)})).map((function(e){return n.Address.fromScAddress(e.credentials().address().address()).toString()}))))})),fe(this,"signAuthEntries",ue(re().mark((function t(){var r,o,i,a,u,c,l,f,p,d,h,y,m,v,g,b,w=arguments;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i=(o=w.length>0&&void 0!==w[0]?w[0]:{}).expiration,a=void 0===i?ue(re().mark((function e(){return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,s.server.getLatestLedger();case 2:return e.t0=e.sent.sequence,e.abrupt("return",e.t0+100);case 4:case"end":return e.stop()}}),e)})))():i,u=o.signAuthEntry,c=void 0===u?s.options.signAuthEntry:u,l=o.address,f=void 0===l?s.options.publicKey:l,p=o.authorizeEntry,d=void 0===p?n.authorizeEntry:p,s.built){t.next=3;break}throw new Error("Transaction has not yet been assembled or simulated");case 3:if(d!==n.authorizeEntry){t.next=11;break}if(0!==(h=s.needsNonInvokerSigningBy()).length){t.next=7;break}throw new e.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?");case 7:if(-1!==h.indexOf(null!=f?f:"")){t.next=9;break}throw new e.Errors.NoSignatureNeeded('No auth entries for public key "'.concat(f,'"'));case 9:if(c){t.next=11;break}throw new e.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`");case 11:y=s.built.operations[0],m=null!==(r=y.auth)&&void 0!==r?r:[],v=te(m.entries()),t.prev=14,b=re().mark((function e(){var t,r,o,i,u;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=ee(g.value,2),r=t[0],o=t[1],(i=n.xdr.SorobanCredentials.fromXDR(o.credentials().toXDR())).switch()===n.xdr.SorobanCredentialsType.sorobanCredentialsAddress()){e.next=4;break}return e.abrupt("return",0);case 4:if(n.Address.fromScAddress(i.address().address()).toString()===f){e.next=7;break}return e.abrupt("return",0);case 7:return u=null!=c?c:Promise.resolve,e.t0=d,e.t1=o,e.t2=function(){var e=ue(re().mark((function e(t){var r,n,o;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,u(t.toXDR("base64"),{address:f});case 2:return r=e.sent,n=r.signedAuthEntry,o=r.error,s.handleWalletError(o),e.abrupt("return",H.from(n,"base64"));case 7:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),e.next=13,a;case 13:return e.t3=e.sent,e.t4=s.options.networkPassphrase,e.next=17,(0,e.t0)(e.t1,e.t2,e.t3,e.t4);case 17:m[r]=e.sent;case 18:case"end":return e.stop()}}),e)})),v.s();case 17:if((g=v.n()).done){t.next=24;break}return t.delegateYield(b(),"t0",19);case 19:if(0!==t.t0){t.next=22;break}return t.abrupt("continue",22);case 22:t.next=17;break;case 24:t.next=29;break;case 26:t.prev=26,t.t1=t.catch(14),v.e(t.t1);case 29:return t.prev=29,v.f(),t.finish(29);case 32:case"end":return t.stop()}}),t,null,[[14,26,29,32]])})))),this.options=t,this.options.simulate=null===(r=this.options.simulate)||void 0===r||r,this.server=new o.Server(this.options.rpcUrl,{allowHttp:null!==(u=this.options.allowHttp)&&void 0!==u&&u})}return le(e,[{key:"toJSON",value:function(){var e;return JSON.stringify({method:this.options.method,tx:null===(e=this.built)||void 0===e?void 0:e.toXDR(),simulationResult:{auth:this.simulationData.result.auth.map((function(e){return e.toXDR("base64")})),retval:this.simulationData.result.retval.toXDR("base64")},simulationTransactionData:this.simulationData.transactionData.toXDR("base64")})}},{key:"toXDR",value:function(){var e;if(!this.built)throw new Error("Transaction has not yet been simulated; call `AssembledTransaction.simulate` first.");return null===(e=this.built)||void 0===e?void 0:e.toEnvelope().toXDR("base64")}},{key:"handleWalletError",value:function(t){if(t){var r=t.message,n=t.code,o="".concat(r).concat(t.ext?" (".concat(t.ext.join(", "),")"):"");switch(n){case-1:throw new e.Errors.InternalWalletError(o);case-2:throw new e.Errors.ExternalServiceError(o);case-3:throw new e.Errors.InvalidClientRequest(o);case-4:throw new e.Errors.UserRejected(o);default:throw new Error("Unhandled error: ".concat(o))}}}},{key:"simulationData",get:function(){var t;if(this.simulationResult&&this.simulationTransactionData)return{result:this.simulationResult,transactionData:this.simulationTransactionData};var r=this.simulation;if(!r)throw new e.Errors.NotYetSimulated("Transaction has not yet been simulated");if(i.j.isSimulationError(r))throw new e.Errors.SimulationFailed('Transaction simulation failed: "'.concat(r.error,'"'));if(i.j.isSimulationRestore(r))throw new e.Errors.ExpiredState("You need to restore some contract state before you can invoke this method.\nYou can set `restore` to true in the method options in order to automatically restore the contract state when needed.");return this.simulationResult=null!==(t=r.result)&&void 0!==t?t:{auth:[],retval:n.xdr.ScVal.scvVoid()},this.simulationTransactionData=r.transactionData.build(),{result:this.simulationResult,transactionData:this.simulationTransactionData}}},{key:"result",get:function(){try{if(!this.simulationData.result)throw new Error("No simulation result!");return this.options.parseResultXdr(this.simulationData.result.retval)}catch(r){if("object"!==v(t=r)||null===t||!("toString"in t))throw r;var e=this.parseError(r.toString());if(e)return e;throw r}var t}},{key:"parseError",value:function(e){if(this.options.errorTypes){var t=e.match(E);if(t){var r=parseInt(t[1],10),n=this.options.errorTypes[r];if(n)return new d(n)}}}},{key:"send",value:(s=ue(re().mark((function e(){var t;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.signed){e.next=2;break}throw new Error("The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead.");case 2:return e.next=4,K.init(this);case 4:return t=e.sent,e.abrupt("return",t);case 6:case"end":return e.stop()}}),e,this)}))),function(){return s.apply(this,arguments)})},{key:"isReadCall",get:function(){var e=this.simulationData.result.auth.length,t=this.simulationData.transactionData.resources().footprint().readWrite().length;return 0===e&&0===t}},{key:"restoreFootprint",value:(u=ue(re().mark((function t(r,n){var o,i,a;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this.options.signTransaction){t.next=2;break}throw new Error("For automatic restore to work you must provide a signTransaction function when initializing your Client");case 2:if(null===(o=n)||void 0===o){t.next=6;break}t.t0=o,t.next=9;break;case 6:return t.next=8,T(this.options,this.server);case 8:t.t0=t.sent;case 9:return n=t.t0,t.next=12,e.buildFootprintRestoreTransaction(Z({},this.options),r.transactionData,n,r.minResourceFee);case 12:return i=t.sent,t.next=15,i.signAndSend();case 15:if((a=t.sent).getTransactionResponse){t.next=18;break}throw new e.Errors.RestorationFailure("The attempt at automatic restore failed. \n".concat(JSON.stringify(a)));case 18:return t.abrupt("return",a.getTransactionResponse);case 19:case"end":return t.stop()}}),t,this)}))),function(e,t){return u.apply(this,arguments)})}],[{key:"fromJSON",value:function(t,r){var o=r.tx,i=r.simulationResult,a=r.simulationTransactionData,u=new e(t);return u.built=n.TransactionBuilder.fromXDR(o,t.networkPassphrase),u.simulationResult={auth:i.auth.map((function(e){return n.xdr.SorobanAuthorizationEntry.fromXDR(e,"base64")})),retval:n.xdr.ScVal.fromXDR(i.retval,"base64")},u.simulationTransactionData=n.xdr.SorobanTransactionData.fromXDR(a,"base64"),u}},{key:"fromXDR",value:function(t,r,o){var i,a=n.xdr.TransactionEnvelope.fromXDR(r,"base64"),u=n.TransactionBuilder.fromXDR(a,t.networkPassphrase),s=u.operations[0];if(null==s||null===(i=s.func)||void 0===i||!i.value||"function"!=typeof s.func.value)throw new Error("Could not extract the method from the transaction envelope.");var c=s.func.value();if(null==c||!c.functionName)throw new Error("Could not extract the method name from the transaction envelope.");var l=c.functionName().toString("utf-8"),f=new e(Z(Z({},t),{},{method:l,parseResultXdr:function(e){return o.funcResToNative(l,e)}}));return f.built=u,f}},{key:"build",value:function(t){var r,o=new n.Contract(t.contractId);return e.buildWithOp(o.call.apply(o,[t.method].concat(ne(null!==(r=t.args)&&void 0!==r?r:[]))),t)}},{key:"buildWithOp",value:(r=ue(re().mark((function t(r,o){var i,a,u,s;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return u=new e(o),t.next=3,T(o,u.server);case 3:if(s=t.sent,u.raw=new n.TransactionBuilder(s,{fee:null!==(i=o.fee)&&void 0!==i?i:n.BASE_FEE,networkPassphrase:o.networkPassphrase}).setTimeout(null!==(a=o.timeoutInSeconds)&&void 0!==a?a:h).addOperation(r),!o.simulate){t.next=8;break}return t.next=8,u.simulate();case 8:return t.abrupt("return",u);case 9:case"end":return t.stop()}}),t)}))),function(e,t){return r.apply(this,arguments)})},{key:"buildFootprintRestoreTransaction",value:(t=ue(re().mark((function t(r,o,i,a){var u,s;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return(s=new e(r)).raw=new n.TransactionBuilder(i,{fee:a,networkPassphrase:r.networkPassphrase}).setSorobanData(o instanceof n.SorobanDataBuilder?o.build():o).addOperation(n.Operation.restoreFootprint({})).setTimeout(null!==(u=r.timeoutInSeconds)&&void 0!==u?u:h),t.next=4,s.simulate({restore:!1});case 4:return t.abrupt("return",s);case 5:case"end":return t.stop()}}),t)}))),function(e,r,n,o){return t.apply(this,arguments)})}]);var t,r,u,s}();fe(de,"Errors",{ExpiredState:function(e){function t(){return se(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),RestorationFailure:function(e){function t(){return se(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NeedsMoreSignatures:function(e){function t(){return se(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NoSignatureNeeded:function(e){function t(){return se(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NoUnsignedNonInvokerAuthEntries:function(e){function t(){return se(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NoSigner:function(e){function t(){return se(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NotYetSimulated:function(e){function t(){return se(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),FakeAccount:function(e){function t(){return se(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),SimulationFailed:function(e){function t(){return se(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),InternalWalletError:function(e){function t(){return se(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),ExternalServiceError:function(e){function t(){return se(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),InvalidClientRequest:function(e){function t(){return se(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),UserRejected:function(e){function t(){return se(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error))});var he=r(8287).Buffer;function ye(e){return ye="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ye(e)}function me(){me=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",s=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),u=new I(n||[]);return o(a,"_invoke",{value:O(e,r,u)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,k=S&&S(S(R([])));k&&k!==r&&n.call(k,a)&&(w=k);var E=b.prototype=v.prototype=Object.create(w);function _(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,u){var s=f(e[o],e,i);if("throw"!==s.type){var c=s.arg,l=c.value;return l&&"object"==ye(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,u)}),(function(e){r("throw",e,a,u)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,u)}))}u(s.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var u=n.delegate;if(u){var s=x(u,n);if(s){if(s===m)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function I(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function R(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:R(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function ve(e,t,r,n,o,i,a){try{var u=e[i](a),s=u.value}catch(e){return void r(e)}u.done?t(s):Promise.resolve(s).then(n,o)}function ge(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){ve(i,n,o,a,u,"next",e)}function u(e){ve(i,n,o,a,u,"throw",e)}a(void 0)}))}}var be=function(e,t){return{signTransaction:(o=ge(me().mark((function r(o,i){var a;return me().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return(a=n.TransactionBuilder.fromXDR(o,(null==i?void 0:i.networkPassphrase)||t)).sign(e),r.abrupt("return",{signedTxXdr:a.toXDR(),signerAddress:e.publicKey()});case 3:case"end":return r.stop()}}),r)}))),function(e,t){return o.apply(this,arguments)}),signAuthEntry:(r=ge(me().mark((function t(r){var o;return me().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return o=e.sign((0,n.hash)(he.from(r,"base64"))).toString("base64"),t.abrupt("return",{signedAuthEntry:o,signerAddress:e.publicKey()});case 2:case"end":return t.stop()}}),t)}))),function(e){return r.apply(this,arguments)})};var r,o},we=r(8287).Buffer;function Se(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function ke(e){for(var t=1;te.length)&&(t=e.length);for(var r=0,n=Array(t);r0&&(o.required=r),o}var je,Be,Le,Ne=(je=function e(t){if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Te(this,"entries",[]),0===t.length)throw new Error("Contract spec must have at least one entry");var r=t[0];this.entries="string"==typeof r?t.map((function(e){return n.xdr.ScSpecEntry.fromXDR(e,"base64")})):t},Be=[{key:"funcs",value:function(){return this.entries.filter((function(e){return e.switch().value===n.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value})).map((function(e){return e.functionV0()}))}},{key:"getFunc",value:function(e){var t=this.findEntry(e);if(t.switch().value!==n.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value)throw new Error("".concat(e," is not a function"));return t.functionV0()}},{key:"funcArgsToScVals",value:function(e,t){var r=this;return this.getFunc(e).inputs().map((function(e){return r.nativeToScVal(function(e,t){var r=t.name().toString(),n=Object.entries(e).find((function(e){return xe(e,1)[0]===r}));if(!n)throw new Error("Missing field ".concat(r));return n[1]}(t,e),e.type())}))}},{key:"funcResToNative",value:function(e,t){var r="string"==typeof t?n.xdr.ScVal.fromXDR(t,"base64"):t,o=this.getFunc(e).outputs();if(0===o.length){var i=r.switch();if(i.value!==n.xdr.ScValType.scvVoid().value)throw new Error("Expected void, got ".concat(i.name));return null}if(o.length>1)throw new Error("Multiple outputs not supported");var a=o[0];return a.switch().value===n.xdr.ScSpecType.scSpecTypeResult().value?new p(this.scValToNative(r,a.result().okType())):this.scValToNative(r,a)}},{key:"findEntry",value:function(e){var t=this.entries.find((function(t){return t.value().name().toString()===e}));if(!t)throw new Error("no such entry: ".concat(e));return t}},{key:"nativeToScVal",value:function(e,t){var r=this,o=t.switch(),i=o.value;if(o.value===n.xdr.ScSpecType.scSpecTypeUdt().value){var a=t.udt();return this.nativeToUdt(e,a.name().toString())}if(i===n.xdr.ScSpecType.scSpecTypeOption().value){var u=t.option();return void 0===e?n.xdr.ScVal.scvVoid():this.nativeToScVal(e,u.valueType())}switch(Ee(e)){case"object":var s,c,l;if(null===e){if(i===n.xdr.ScSpecType.scSpecTypeVoid().value)return n.xdr.ScVal.scvVoid();throw new TypeError("Type ".concat(t," was not void, but value was null"))}if(e instanceof n.xdr.ScVal)return e;if(e instanceof n.Address){if(t.switch().value!==n.xdr.ScSpecType.scSpecTypeAddress().value)throw new TypeError("Type ".concat(t," was not address, but value was Address"));return e.toScVal()}if(e instanceof n.Contract){if(t.switch().value!==n.xdr.ScSpecType.scSpecTypeAddress().value)throw new TypeError("Type ".concat(t," was not address, but value was Address"));return e.address().toScVal()}if(e instanceof Uint8Array||we.isBuffer(e)){var f=Uint8Array.from(e);switch(i){case n.xdr.ScSpecType.scSpecTypeBytesN().value:var p=t.bytesN();if(f.length!==p.n())throw new TypeError("expected ".concat(p.n()," bytes, but got ").concat(f.length));return n.xdr.ScVal.scvBytes(f);case n.xdr.ScSpecType.scSpecTypeBytes().value:return n.xdr.ScVal.scvBytes(f);default:throw new TypeError("invalid type (".concat(t,") specified for Bytes and BytesN"))}}if(Array.isArray(e))switch(i){case n.xdr.ScSpecType.scSpecTypeVec().value:var d=t.vec().elementType();return n.xdr.ScVal.scvVec(e.map((function(e){return r.nativeToScVal(e,d)})));case n.xdr.ScSpecType.scSpecTypeTuple().value:var h=t.tuple().valueTypes();if(e.length!==h.length)throw new TypeError("Tuple expects ".concat(h.length," values, but ").concat(e.length," were provided"));return n.xdr.ScVal.scvVec(e.map((function(e,t){return r.nativeToScVal(e,h[t])})));case n.xdr.ScSpecType.scSpecTypeMap().value:var y=t.map(),m=y.keyType(),v=y.valueType();return n.xdr.ScVal.scvMap(e.map((function(e){var t=r.nativeToScVal(e[0],m),o=r.nativeToScVal(e[1],v);return new n.xdr.ScMapEntry({key:t,val:o})})));default:throw new TypeError("Type ".concat(t," was not vec, but value was Array"))}if(e.constructor===Map){if(i!==n.xdr.ScSpecType.scSpecTypeMap().value)throw new TypeError("Type ".concat(t," was not map, but value was Map"));for(var g=t.map(),b=[],w=e.entries(),S=w.next();!S.done;){var k=xe(S.value,2),E=k[0],_=k[1],T=this.nativeToScVal(E,g.keyType()),O=this.nativeToScVal(_,g.valueType());b.push(new n.xdr.ScMapEntry({key:T,val:O})),S=w.next()}return n.xdr.ScVal.scvMap(b)}if("Object"!==(null!==(s=null===(c=e.constructor)||void 0===c?void 0:c.name)&&void 0!==s?s:""))throw new TypeError("cannot interpret ".concat(null===(l=e.constructor)||void 0===l?void 0:l.name," value as ScVal (").concat(JSON.stringify(e),")"));throw new TypeError("Received object ".concat(e," did not match the provided type ").concat(t));case"number":case"bigint":switch(i){case n.xdr.ScSpecType.scSpecTypeU32().value:return n.xdr.ScVal.scvU32(e);case n.xdr.ScSpecType.scSpecTypeI32().value:return n.xdr.ScVal.scvI32(e);case n.xdr.ScSpecType.scSpecTypeU64().value:case n.xdr.ScSpecType.scSpecTypeI64().value:case n.xdr.ScSpecType.scSpecTypeU128().value:case n.xdr.ScSpecType.scSpecTypeI128().value:case n.xdr.ScSpecType.scSpecTypeU256().value:case n.xdr.ScSpecType.scSpecTypeI256().value:var x=o.name.substring(10).toLowerCase();return new n.XdrLargeInt(x,e).toScVal();default:throw new TypeError("invalid type (".concat(t,") specified for integer"))}case"string":return function(e,t){switch(t.value){case n.xdr.ScSpecType.scSpecTypeString().value:return n.xdr.ScVal.scvString(e);case n.xdr.ScSpecType.scSpecTypeSymbol().value:return n.xdr.ScVal.scvSymbol(e);case n.xdr.ScSpecType.scSpecTypeAddress().value:var r=n.Address.fromString(e);return n.xdr.ScVal.scvAddress(r.toScAddress());case n.xdr.ScSpecType.scSpecTypeU64().value:return new n.XdrLargeInt("u64",e).toScVal();case n.xdr.ScSpecType.scSpecTypeI64().value:return new n.XdrLargeInt("i64",e).toScVal();case n.xdr.ScSpecType.scSpecTypeU128().value:return new n.XdrLargeInt("u128",e).toScVal();case n.xdr.ScSpecType.scSpecTypeI128().value:return new n.XdrLargeInt("i128",e).toScVal();case n.xdr.ScSpecType.scSpecTypeU256().value:return new n.XdrLargeInt("u256",e).toScVal();case n.xdr.ScSpecType.scSpecTypeI256().value:return new n.XdrLargeInt("i256",e).toScVal();case n.xdr.ScSpecType.scSpecTypeBytes().value:case n.xdr.ScSpecType.scSpecTypeBytesN().value:return n.xdr.ScVal.scvBytes(we.from(e,"base64"));default:throw new TypeError("invalid type ".concat(t.name," specified for string value"))}}(e,o);case"boolean":if(i!==n.xdr.ScSpecType.scSpecTypeBool().value)throw TypeError("Type ".concat(t," was not bool, but value was bool"));return n.xdr.ScVal.scvBool(e);case"undefined":if(!t)return n.xdr.ScVal.scvVoid();switch(i){case n.xdr.ScSpecType.scSpecTypeVoid().value:case n.xdr.ScSpecType.scSpecTypeOption().value:return n.xdr.ScVal.scvVoid();default:throw new TypeError("Type ".concat(t," was not void, but value was undefined"))}case"function":return this.nativeToScVal(e(),t);default:throw new TypeError("failed to convert typeof ".concat(Ee(e)," (").concat(e,")"))}}},{key:"nativeToUdt",value:function(e,t){var r=this.findEntry(t);switch(r.switch()){case n.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0():if("number"!=typeof e)throw new TypeError("expected number for enum ".concat(t,", but got ").concat(Ee(e)));return this.nativeToEnum(e,r.udtEnumV0());case n.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.nativeToStruct(e,r.udtStructV0());case n.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.nativeToUnion(e,r.udtUnionV0());default:throw new Error("failed to parse udt ".concat(t))}}},{key:"nativeToUnion",value:function(e,t){var r=this,o=e.tag,i=t.cases().find((function(e){return e.value().name().toString()===o}));if(!i)throw new TypeError("no such enum entry: ".concat(o," in ").concat(t));var a=n.xdr.ScVal.scvSymbol(o);switch(i.switch()){case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0():return n.xdr.ScVal.scvVec([a]);case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0():var u=i.tupleCase().type();if(Array.isArray(e.values)){if(e.values.length!==u.length)throw new TypeError("union ".concat(t," expects ").concat(u.length," values, but got ").concat(e.values.length));var s=e.values.map((function(e,t){return r.nativeToScVal(e,u[t])}));return s.unshift(a),n.xdr.ScVal.scvVec(s)}throw new Error("failed to parse union case ".concat(i," with ").concat(e));default:throw new Error("failed to parse union ".concat(t," with ").concat(e))}}},{key:"nativeToStruct",value:function(e,t){var r=this,o=t.fields();if(o.some(Pe)){if(!o.every(Pe))throw new Error("mixed numeric and non-numeric field names are not allowed");return n.xdr.ScVal.scvVec(o.map((function(t,n){return r.nativeToScVal(e[n],o[n].type())})))}return n.xdr.ScVal.scvMap(o.map((function(t){var o=t.name().toString();return new n.xdr.ScMapEntry({key:r.nativeToScVal(o,n.xdr.ScSpecTypeDef.scSpecTypeSymbol()),val:r.nativeToScVal(e[o],t.type())})})))}},{key:"nativeToEnum",value:function(e,t){if(t.cases().some((function(t){return t.value()===e})))return n.xdr.ScVal.scvU32(e);throw new TypeError("no such enum entry: ".concat(e," in ").concat(t))}},{key:"scValStrToNative",value:function(e,t){return this.scValToNative(n.xdr.ScVal.fromXDR(e,"base64"),t)}},{key:"scValToNative",value:function(e,t){var r=this,o=t.switch(),i=o.value;if(i===n.xdr.ScSpecType.scSpecTypeUdt().value)return this.scValUdtToNative(e,t.udt());switch(e.switch().value){case n.xdr.ScValType.scvVoid().value:return;case n.xdr.ScValType.scvU64().value:case n.xdr.ScValType.scvI64().value:case n.xdr.ScValType.scvU128().value:case n.xdr.ScValType.scvI128().value:case n.xdr.ScValType.scvU256().value:case n.xdr.ScValType.scvI256().value:return(0,n.scValToBigInt)(e);case n.xdr.ScValType.scvVec().value:if(i===n.xdr.ScSpecType.scSpecTypeVec().value){var a,u=t.vec();return(null!==(a=e.vec())&&void 0!==a?a:[]).map((function(e){return r.scValToNative(e,u.elementType())}))}if(i===n.xdr.ScSpecType.scSpecTypeTuple().value){var s,c=t.tuple().valueTypes();return(null!==(s=e.vec())&&void 0!==s?s:[]).map((function(e,t){return r.scValToNative(e,c[t])}))}throw new TypeError("Type ".concat(t," was not vec, but ").concat(e," is"));case n.xdr.ScValType.scvAddress().value:return n.Address.fromScVal(e).toString();case n.xdr.ScValType.scvMap().value:var l,f=null!==(l=e.map())&&void 0!==l?l:[];if(i===n.xdr.ScSpecType.scSpecTypeMap().value){var p=t.map(),d=p.keyType(),h=p.valueType();return f.map((function(e){return[r.scValToNative(e.key(),d),r.scValToNative(e.val(),h)]}))}throw new TypeError("ScSpecType ".concat(o.name," was not map, but ").concat(JSON.stringify(e,null,2)," is"));case n.xdr.ScValType.scvBool().value:case n.xdr.ScValType.scvU32().value:case n.xdr.ScValType.scvI32().value:case n.xdr.ScValType.scvBytes().value:return e.value();case n.xdr.ScValType.scvString().value:case n.xdr.ScValType.scvSymbol().value:var y;if(i!==n.xdr.ScSpecType.scSpecTypeString().value&&i!==n.xdr.ScSpecType.scSpecTypeSymbol().value)throw new Error("ScSpecType ".concat(o.name," was not string or symbol, but ").concat(JSON.stringify(e,null,2)," is"));return null===(y=e.value())||void 0===y?void 0:y.toString();case n.xdr.ScValType.scvTimepoint().value:case n.xdr.ScValType.scvDuration().value:return(0,n.scValToBigInt)(n.xdr.ScVal.scvU64(e.u64()));default:throw new TypeError("failed to convert ".concat(JSON.stringify(e,null,2)," to native type from type ").concat(o.name))}}},{key:"scValUdtToNative",value:function(e,t){var r=this.findEntry(t.name().toString());switch(r.switch()){case n.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0():return this.enumToNative(e);case n.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.structToNative(e,r.udtStructV0());case n.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.unionToNative(e,r.udtUnionV0());default:throw new Error("failed to parse udt ".concat(t.name().toString(),": ").concat(r))}}},{key:"unionToNative",value:function(e,t){var r=this,o=e.vec();if(!o)throw new Error("".concat(JSON.stringify(e,null,2)," is not a vec"));if(0===o.length&&0!==t.cases.length)throw new Error("".concat(e," has length 0, but the there are at least one case in the union"));var i=o[0].sym().toString();if(o[0].switch().value!==n.xdr.ScValType.scvSymbol().value)throw new Error("{vec[0]} is not a symbol");var a=t.cases().find(function(e){return function(t){switch(t.switch().value){case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value:return t.tupleCase().name().toString()===e;case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value:return t.voidCase().name().toString()===e;default:return!1}}}(i));if(!a)throw new Error("failed to find entry ".concat(i," in union {udt.name().toString()}"));var u={tag:i};if(a.switch().value===n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value){var s=a.tupleCase().type().map((function(e,t){return r.scValToNative(o[t+1],e)}));u.values=s}return u}},{key:"structToNative",value:function(e,t){var r,n,o=this,i={},a=t.fields();return a.some(Pe)?null===(n=e.vec())||void 0===n?void 0:n.map((function(e,t){return o.scValToNative(e,a[t].type())})):(null===(r=e.map())||void 0===r||r.forEach((function(e,t){var r=a[t];i[r.name().toString()]=o.scValToNative(e.val(),r.type())})),i)}},{key:"enumToNative",value:function(e){if(e.switch().value!==n.xdr.ScValType.scvU32().value)throw new Error("Enum must have a u32 value");return e.u32()}},{key:"errorCases",value:function(){return this.entries.filter((function(e){return e.switch().value===n.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value})).flatMap((function(e){return e.value().cases()}))}},{key:"jsonSchema",value:function(e){var t={};this.entries.forEach((function(e){switch(e.switch().value){case n.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0().value:var r=e.udtEnumV0();t[r.name().toString()]=function(e){var t=e.doc().toString(),r=e.cases(),n=[];r.forEach((function(e){var t=e.name().toString(),r=e.doc().toString();n.push({description:r,title:t,enum:[e.value()],type:"number"})}));var o={oneOf:n};return t.length>0&&(o.description=t),o}(r);break;case n.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0().value:var o=e.udtStructV0();t[o.name().toString()]=function(e){var t=e.fields();if(t.some(Pe)){if(!t.every(Pe))throw new Error("mixed numeric and non-numeric field names are not allowed");return{type:"array",items:t.map((function(e,r){return Re(t[r].type())})),minItems:t.length,maxItems:t.length}}var r=e.doc().toString(),n=Ce(t),o=n.properties,i=n.required;return o.additionalProperties=!1,{description:r,properties:o,required:i,type:"object"}}(o);break;case n.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0().value:var i=e.udtUnionV0();t[i.name().toString()]=function(e){var t=e.doc().toString(),r=e.cases(),o=[];r.forEach((function(e){switch(e.switch().value){case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value:var t=e.voidCase().name().toString();o.push({type:"object",title:t,properties:{tag:t},additionalProperties:!1,required:["tag"]});break;case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value:var r=e.tupleCase(),i=r.name().toString();o.push({type:"object",title:i,properties:{tag:i,values:{type:"array",items:r.type().map(Re)}},required:["tag","values"],additionalProperties:!1})}}));var i={oneOf:o};return t.length>0&&(i.description=t),i}(i);break;case n.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value:var a=e.functionV0(),u=a.name().toString(),s=function(e){var t=Ce(e.inputs()),r=t.properties,o=t.required,i={additionalProperties:!1,properties:r,type:"object"};(null==o?void 0:o.length)>0&&(i.required=o);var a={properties:{args:i}},u=e.outputs(),s=u.length>0?Re(u[0]):Re(n.xdr.ScSpecTypeDef.scSpecTypeVoid()),c=e.doc().toString();return c.length>0&&(a.description=c),a.additionalProperties=!1,s.additionalProperties=!1,{input:a,output:s}}(a),c=s.input;t[u]=c;case n.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value:}}));var r={$schema:"http://json-schema.org/draft-07/schema#",definitions:ke(ke({},Ie),t)};return e&&(r.$ref="#/definitions/".concat(e)),r}}],Be&&_e(je.prototype,Be),Le&&_e(je,Le),Object.defineProperty(je,"prototype",{writable:!1}),je),Ue=r(8287).Buffer;function Me(e){return Me="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Me(e)}var Fe=["method"],De=["wasmHash","salt","format","fee","timeoutInSeconds","simulate"];function Ve(){Ve=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",s=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),u=new I(n||[]);return o(a,"_invoke",{value:O(e,r,u)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,k=S&&S(S(R([])));k&&k!==r&&n.call(k,a)&&(w=k);var E=b.prototype=v.prototype=Object.create(w);function _(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,u){var s=f(e[o],e,i);if("throw"!==s.type){var c=s.arg,l=c.value;return l&&"object"==Me(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,u)}),(function(e){r("throw",e,a,u)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,u)}))}u(s.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var u=n.delegate;if(u){var s=x(u,n);if(s){if(s===m)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function I(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function R(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:R(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function qe(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Ke(e){for(var t=1;t2&&void 0!==l[2]?l[2]:"hex",r&&r.rpcUrl){e.next=3;break}throw new TypeError("options must contain rpcUrl");case 3:return i=r.rpcUrl,a=r.allowHttp,u={allowHttp:a},s=new o.Server(i,u),e.next=8,s.getContractWasmByHash(t,n);case 8:return c=e.sent,e.abrupt("return",Ye(c));case 10:case"end":return e.stop()}}),e)}))),et.apply(this,arguments)}var tt=function(){function e(t,r){var n=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Xe(this,"txFromJSON",(function(e){var t=JSON.parse(e),r=t.method,o=He(t,Fe);return de.fromJSON(Ke(Ke({},n.options),{},{method:r,parseResultXdr:function(e){return n.spec.funcResToNative(r,e)}}),o)})),Xe(this,"txFromXDR",(function(e){return de.fromXDR(n.options,e,n.spec)})),this.spec=t,this.options=r,this.spec.funcs().forEach((function(e){var o=e.name().toString();if(o!==We){var i=function(e,n){return de.build(Ke(Ke(Ke({method:o,args:e&&t.funcArgsToScVals(o,e)},r),n),{},{errorTypes:t.errorCases().reduce((function(e,t){return Ke(Ke({},e),{},Xe({},t.value(),{message:t.doc().toString()}))}),{}),parseResultXdr:function(e){return t.funcResToNative(o,e)}}))};n[o]=0===t.getFunc(o).inputs().length?function(e){return i(void 0,e)}:i}}))}return function(e,t,r){return t&&ze(e.prototype,t),r&&ze(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}(e,null,[{key:"deploy",value:(a=Qe(Ve().mark((function t(r,o){var i,a,u,s,c,l,f,p,d;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=o.wasmHash,a=o.salt,u=o.format,s=o.fee,c=o.timeoutInSeconds,l=o.simulate,f=He(o,De),t.next=3,Ze(i,f,u);case 3:return p=t.sent,d=n.Operation.createCustomContract({address:new n.Address(o.publicKey),wasmHash:"string"==typeof i?Ue.from(i,null!=u?u:"hex"):i,salt:a,constructorArgs:r?p.funcArgsToScVals(We,r):[]}),t.abrupt("return",de.buildWithOp(d,Ke(Ke({fee:s,timeoutInSeconds:c,simulate:l},f),{},{contractId:"ignored",method:We,parseResultXdr:function(t){return new e(p,Ke(Ke({},f),{},{contractId:n.Address.fromScVal(t).toString()}))}})));case 6:case"end":return t.stop()}}),t)}))),function(e,t){return a.apply(this,arguments)})},{key:"fromWasmHash",value:(i=Qe(Ve().mark((function t(r,n){var i,a,u,s,c,l,f=arguments;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i=f.length>2&&void 0!==f[2]?f[2]:"hex",n&&n.rpcUrl){t.next=3;break}throw new TypeError("options must contain rpcUrl");case 3:return a=n.rpcUrl,u=n.allowHttp,s={allowHttp:u},c=new o.Server(a,s),t.next=8,c.getContractWasmByHash(r,i);case 8:return l=t.sent,t.abrupt("return",e.fromWasm(l,n));case 10:case"end":return t.stop()}}),t)}))),function(e,t){return i.apply(this,arguments)})},{key:"fromWasm",value:(r=Qe(Ve().mark((function t(r,n){var o;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,Ye(r);case 2:return o=t.sent,t.abrupt("return",new e(o,n));case 4:case"end":return t.stop()}}),t)}))),function(e,t){return r.apply(this,arguments)})},{key:"from",value:(t=Qe(Ve().mark((function t(r){var n,i,a,u,s,c;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(r&&r.rpcUrl&&r.contractId){t.next=2;break}throw new TypeError("options must contain rpcUrl and contractId");case 2:return n=r.rpcUrl,i=r.contractId,a=r.allowHttp,u={allowHttp:a},s=new o.Server(n,u),t.next=7,s.getContractWasmByContractId(i);case 7:return c=t.sent,t.abrupt("return",e.fromWasm(c,r));case 9:case"end":return t.stop()}}),t)}))),function(e){return t.apply(this,arguments)})}]);var t,r,i,a}()},5976:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rH,v7:()=>x,nS:()=>L,Dr:()=>f,m_:()=>b});var f=function(e){function t(e,r){var n;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var o=(this instanceof t?this.constructor:void 0).prototype;return(n=a(this,t,[e])).__proto__=o,n.constructor=t,n.response=r,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&c(e,t)}(t,e),r=t,(n=[{key:"getResponse",value:function(){return this.response}}])&&o(r.prototype,n),i&&o(r,i),Object.defineProperty(r,"prototype",{writable:!1}),r;var r,n,i}(u(Error));function p(e){return p="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},p(e)}function d(e,t){for(var r=0;r{"use strict";r.r(t),r.d(t,{Api:()=>{},FEDERATION_RESPONSE_MAX_SIZE:()=>g,Server:()=>b});var n=r(356),o=r(4193),i=r.n(o),a=r(8732),u=r(5976),s=r(3898),c=r(6371);function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,u=[],s=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=i.call(r)).done)&&(u.push(n.value),u.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return u}}(e,t)||function(e,t){if(e){if("string"==typeof e)return p(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?p(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),R(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;R(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function h(e,t,r,n,o,i,a){try{var u=e[i](a),s=u.value}catch(e){return void r(e)}u.done?t(s):Promise.resolve(s).then(n,o)}function y(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){h(i,n,o,a,u,"next",e)}function u(e){h(i,n,o,a,u,"throw",e)}a(void 0)}))}}function m(e,t){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.serverURL=i()(t),this.domain=r;var o=void 0===n.allowHttp?a.T.isAllowHttp():n.allowHttp;if(this.timeout=void 0===n.timeout?a.T.getTimeout():n.timeout,"https"!==this.serverURL.protocol()&&!o)throw new Error("Cannot connect to insecure federation server")}return t=e,r=[{key:"resolveAddress",value:(w=y(d().mark((function e(t){var r,n;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t,!(t.indexOf("*")<0)){e.next=5;break}if(this.domain){e.next=4;break}return e.abrupt("return",Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object.")));case 4:r="".concat(t,"*").concat(this.domain);case 5:return n=this.serverURL.query({type:"name",q:r}),e.abrupt("return",this._sendRequest(n));case 7:case"end":return e.stop()}}),e,this)}))),function(e){return w.apply(this,arguments)})},{key:"resolveAccountId",value:(b=y(d().mark((function e(t){var r;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.serverURL.query({type:"id",q:t}),e.abrupt("return",this._sendRequest(r));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return b.apply(this,arguments)})},{key:"resolveTransactionId",value:(v=y(d().mark((function e(t){var r;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.serverURL.query({type:"txid",q:t}),e.abrupt("return",this._sendRequest(r));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return v.apply(this,arguments)})},{key:"_sendRequest",value:(h=y(d().mark((function e(t){var r;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.timeout,e.abrupt("return",c.ok.get(t.toString(),{maxContentLength:g,timeout:r}).then((function(e){if(void 0!==e.data.memo&&"string"!=typeof e.data.memo)throw new Error("memo value should be of type string");return e.data})).catch((function(e){if(e instanceof Error){if(e.message.match(/^maxContentLength size/))throw new Error("federation response exceeds allowed size of ".concat(g));return Promise.reject(e)}return Promise.reject(new u.nS("Server query failed. Server responded: ".concat(e.status," ").concat(e.statusText),e.data))})));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return h.apply(this,arguments)})}],o=[{key:"resolve",value:(p=y(d().mark((function t(r){var o,i,a,u,s,c=arguments;return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(o=c.length>1&&void 0!==c[1]?c[1]:{},!(r.indexOf("*")<0)){t.next=5;break}if(n.StrKey.isValidEd25519PublicKey(r)){t.next=4;break}return t.abrupt("return",Promise.reject(new Error("Invalid Account ID")));case 4:return t.abrupt("return",Promise.resolve({account_id:r}));case 5:if(i=r.split("*"),a=f(i,2),u=a[1],2===i.length&&u){t.next=9;break}return t.abrupt("return",Promise.reject(new Error("Invalid Stellar address")));case 9:return t.next=11,e.createForDomain(u,o);case 11:return s=t.sent,t.abrupt("return",s.resolveAddress(r));case 13:case"end":return t.stop()}}),t)}))),function(e){return p.apply(this,arguments)})},{key:"createForDomain",value:(l=y(d().mark((function t(r){var n,o,i=arguments;return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=i.length>1&&void 0!==i[1]?i[1]:{},t.next=3,s.Resolver.resolve(r,n);case 3:if((o=t.sent).FEDERATION_SERVER){t.next=6;break}return t.abrupt("return",Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field")));case 6:return t.abrupt("return",new e(o.FEDERATION_SERVER,r,n));case 7:case"end":return t.stop()}}),t)}))),function(e){return l.apply(this,arguments)})}],r&&m(t.prototype,r),o&&m(t,o),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,o,l,p,h,v,b,w}()},8242:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Api:()=>{}})},8733:(e,t,r)=>{"use strict";var n;r.r(t),r.d(t,{AccountResponse:()=>m,AxiosClient:()=>$,HorizonApi:()=>n,SERVER_TIME_MAP:()=>z,Server:()=>Xr,ServerApi:()=>i,default:()=>Gr,getCurrentServerTime:()=>Q}),function(e){var t=function(e){return e.constantProduct="constant_product",e}({});e.LiquidityPoolType=t;var r=function(e){return e.createAccount="create_account",e.payment="payment",e.pathPayment="path_payment_strict_receive",e.createPassiveOffer="create_passive_sell_offer",e.manageOffer="manage_sell_offer",e.setOptions="set_options",e.changeTrust="change_trust",e.allowTrust="allow_trust",e.accountMerge="account_merge",e.inflation="inflation",e.manageData="manage_data",e.bumpSequence="bump_sequence",e.manageBuyOffer="manage_buy_offer",e.pathPaymentStrictSend="path_payment_strict_send",e.createClaimableBalance="create_claimable_balance",e.claimClaimableBalance="claim_claimable_balance",e.beginSponsoringFutureReserves="begin_sponsoring_future_reserves",e.endSponsoringFutureReserves="end_sponsoring_future_reserves",e.revokeSponsorship="revoke_sponsorship",e.clawback="clawback",e.clawbackClaimableBalance="clawback_claimable_balance",e.setTrustLineFlags="set_trust_line_flags",e.liquidityPoolDeposit="liquidity_pool_deposit",e.liquidityPoolWithdraw="liquidity_pool_withdraw",e.invokeHostFunction="invoke_host_function",e.bumpFootprintExpiration="bump_footprint_expiration",e.restoreFootprint="restore_footprint",e}({});e.OperationResponseType=r;var n=function(e){return e[e.createAccount=0]="createAccount",e[e.payment=1]="payment",e[e.pathPayment=2]="pathPayment",e[e.createPassiveOffer=3]="createPassiveOffer",e[e.manageOffer=4]="manageOffer",e[e.setOptions=5]="setOptions",e[e.changeTrust=6]="changeTrust",e[e.allowTrust=7]="allowTrust",e[e.accountMerge=8]="accountMerge",e[e.inflation=9]="inflation",e[e.manageData=10]="manageData",e[e.bumpSequence=11]="bumpSequence",e[e.manageBuyOffer=12]="manageBuyOffer",e[e.pathPaymentStrictSend=13]="pathPaymentStrictSend",e[e.createClaimableBalance=14]="createClaimableBalance",e[e.claimClaimableBalance=15]="claimClaimableBalance",e[e.beginSponsoringFutureReserves=16]="beginSponsoringFutureReserves",e[e.endSponsoringFutureReserves=17]="endSponsoringFutureReserves",e[e.revokeSponsorship=18]="revokeSponsorship",e[e.clawback=19]="clawback",e[e.clawbackClaimableBalance=20]="clawbackClaimableBalance",e[e.setTrustLineFlags=21]="setTrustLineFlags",e[e.liquidityPoolDeposit=22]="liquidityPoolDeposit",e[e.liquidityPoolWithdraw=23]="liquidityPoolWithdraw",e[e.invokeHostFunction=24]="invokeHostFunction",e[e.bumpFootprintExpiration=25]="bumpFootprintExpiration",e[e.restoreFootprint=26]="restoreFootprint",e}({});e.OperationResponseTypeI=n;var o=function(e){return e.TX_FAILED="tx_failed",e.TX_BAD_SEQ="tx_bad_seq",e.TX_BAD_AUTH="tx_bad_auth",e.TX_BAD_AUTH_EXTRA="tx_bad_auth_extra",e.TX_FEE_BUMP_INNER_SUCCESS="tx_fee_bump_inner_success",e.TX_FEE_BUMP_INNER_FAILED="tx_fee_bump_inner_failed",e.TX_NOT_SUPPORTED="tx_not_supported",e.TX_SUCCESS="tx_success",e.TX_TOO_EARLY="tx_too_early",e.TX_TOO_LATE="tx_too_late",e.TX_MISSING_OPERATION="tx_missing_operation",e.TX_INSUFFICIENT_BALANCE="tx_insufficient_balance",e.TX_NO_SOURCE_ACCOUNT="tx_no_source_account",e.TX_INSUFFICIENT_FEE="tx_insufficient_fee",e.TX_INTERNAL_ERROR="tx_internal_error",e}({});e.TransactionFailedResultCodes=o}(n||(n={}));var o,i,a=((o={})[o.account_created=0]="account_created",o[o.account_removed=1]="account_removed",o[o.account_credited=2]="account_credited",o[o.account_debited=3]="account_debited",o[o.account_thresholds_updated=4]="account_thresholds_updated",o[o.account_home_domain_updated=5]="account_home_domain_updated",o[o.account_flags_updated=6]="account_flags_updated",o[o.account_inflation_destination_updated=7]="account_inflation_destination_updated",o[o.signer_created=10]="signer_created",o[o.signer_removed=11]="signer_removed",o[o.signer_updated=12]="signer_updated",o[o.trustline_created=20]="trustline_created",o[o.trustline_removed=21]="trustline_removed",o[o.trustline_updated=22]="trustline_updated",o[o.trustline_authorized=23]="trustline_authorized",o[o.trustline_deauthorized=24]="trustline_deauthorized",o[o.trustline_authorized_to_maintain_liabilities=25]="trustline_authorized_to_maintain_liabilities",o[o.trustline_flags_updated=26]="trustline_flags_updated",o[o.offer_created=30]="offer_created",o[o.offer_removed=31]="offer_removed",o[o.offer_updated=32]="offer_updated",o[o.trade=33]="trade",o[o.data_created=40]="data_created",o[o.data_removed=41]="data_removed",o[o.data_updated=42]="data_updated",o[o.sequence_bumped=43]="sequence_bumped",o[o.claimable_balance_created=50]="claimable_balance_created",o[o.claimable_balance_claimant_created=51]="claimable_balance_claimant_created",o[o.claimable_balance_claimed=52]="claimable_balance_claimed",o[o.account_sponsorship_created=60]="account_sponsorship_created",o[o.account_sponsorship_updated=61]="account_sponsorship_updated",o[o.account_sponsorship_removed=62]="account_sponsorship_removed",o[o.trustline_sponsorship_created=63]="trustline_sponsorship_created",o[o.trustline_sponsorship_updated=64]="trustline_sponsorship_updated",o[o.trustline_sponsorship_removed=65]="trustline_sponsorship_removed",o[o.data_sponsorship_created=66]="data_sponsorship_created",o[o.data_sponsorship_updated=67]="data_sponsorship_updated",o[o.data_sponsorship_removed=68]="data_sponsorship_removed",o[o.claimable_balance_sponsorship_created=69]="claimable_balance_sponsorship_created",o[o.claimable_balance_sponsorship_updated=70]="claimable_balance_sponsorship_updated",o[o.claimable_balance_sponsorship_removed=71]="claimable_balance_sponsorship_removed",o[o.signer_sponsorship_created=72]="signer_sponsorship_created",o[o.signer_sponsorship_updated=73]="signer_sponsorship_updated",o[o.signer_sponsorship_removed=74]="signer_sponsorship_removed",o[o.claimable_balance_clawed_back=80]="claimable_balance_clawed_back",o[o.liquidity_pool_deposited=90]="liquidity_pool_deposited",o[o.liquidity_pool_withdrew=91]="liquidity_pool_withdrew",o[o.liquidity_pool_trade=92]="liquidity_pool_trade",o[o.liquidity_pool_created=93]="liquidity_pool_created",o[o.liquidity_pool_removed=94]="liquidity_pool_removed",o[o.liquidity_pool_revoked=95]="liquidity_pool_revoked",o[o.contract_credited=96]="contract_credited",o[o.contract_debited=97]="contract_debited",o);!function(e){e.EffectType=a;var t=function(e){return e.all="all",e.liquidityPools="liquidity_pool",e.orderbook="orderbook",e}({});e.TradeType=t;n.OperationResponseType,n.OperationResponseTypeI}(i||(i={}));var u=r(356);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function c(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,u=[],s=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=i.call(r)).done)&&(u.push(n.value),u.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return u}}(e,t)||function(e,t){if(e){if("string"==typeof e)return l(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?l(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r0||e===t?t:t-1}function P(e){for(var t,r,n=1,o=e.length,i=e[0]+"";nc^r?1:-1;for(u=(s=o.length)<(c=i.length)?s:c,a=0;ai[a]^r?1:-1;return s==c?0:s>c^r?1:-1}function R(e,t,r,n){if(er||e!==b(e))throw Error(w+(n||"Argument")+("number"==typeof e?er?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function C(e){var t=e.c.length-1;return A(e.e/E)==t&&e.c[t]%2!=0}function j(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function B(e,t,r){var n,o;if(t<0){for(o=r+".";++t;o+=r);e=o+e}else if(++t>(n=e.length)){for(o=r,t-=n;--t;o+=r);e+=o}else tU?p.c=p.e=null:e.e=10;s/=10,u++);return void(u>U?p.c=p.e=null:(p.e=u,p.c=[e]))}f=String(e)}else{if(!v.test(f=String(e)))return o(p,f,c);p.s=45==f.charCodeAt(0)?(f=f.slice(1),-1):1}(u=f.indexOf("."))>-1&&(f=f.replace(".","")),(s=f.search(/e/i))>0?(u<0&&(u=s),u+=+f.slice(s+1),f=f.substring(0,s)):u<0&&(u=f.length)}else{if(R(t,2,q.length,"Base"),10==t&&K)return $(p=new H(e),h+p.e+1,y);if(f=String(e),c="number"==typeof e){if(0*e!=0)return o(p,f,c,t);if(p.s=1/e<0?(f=f.slice(1),-1):1,H.DEBUG&&f.replace(/^0\.0*|\./,"").length>15)throw Error(S+e)}else p.s=45===f.charCodeAt(0)?(f=f.slice(1),-1):1;for(r=q.slice(0,t),u=s=0,l=f.length;su){u=l;continue}}else if(!a&&(f==f.toUpperCase()&&(f=f.toLowerCase())||f==f.toLowerCase()&&(f=f.toUpperCase()))){a=!0,s=-1,u=0;continue}return o(p,String(e),c,t)}c=!1,(u=(f=n(f,t,10,p.s)).indexOf("."))>-1?f=f.replace(".",""):u=f.length}for(s=0;48===f.charCodeAt(s);s++);for(l=f.length;48===f.charCodeAt(--l););if(f=f.slice(s,++l)){if(l-=s,c&&H.DEBUG&&l>15&&(e>_||e!==b(e)))throw Error(S+p.s*e);if((u=u-s-1)>U)p.c=p.e=null;else if(u=L)?j(s,a):B(s,a,"0");else if(i=(e=$(new H(e),t,r)).e,u=(s=P(e.c)).length,1==n||2==n&&(t<=i||i<=m)){for(;uu){if(--t>0)for(s+=".";t--;s+="0");}else if((t+=i-u)>0)for(i+1==u&&(s+=".");t--;s+="0");return e.s<0&&o?"-"+s:s}function X(e,t){for(var r,n,o=1,i=new H(e[0]);o=10;o/=10,n++);return(r=n+r*E-1)>U?e.c=e.e=null:r=10;u/=10,o++);if((i=t-o)<0)i+=E,a=t,s=f[c=0],l=b(s/p[o-a-1]%10);else if((c=g((i+1)/E))>=f.length){if(!n)break e;for(;f.length<=c;f.push(0));s=l=0,o=1,a=(i%=E)-E+1}else{for(s=u=f[c],o=1;u>=10;u/=10,o++);l=(a=(i%=E)-E+o)<0?0:b(s/p[o-a-1]%10)}if(n=n||t<0||null!=f[c+1]||(a<0?s:s%p[o-a-1]),n=r<4?(l||n)&&(0==r||r==(e.s<0?3:2)):l>5||5==l&&(4==r||n||6==r&&(i>0?a>0?s/p[o-a]:0:f[c-1])%10&1||r==(e.s<0?8:7)),t<1||!f[0])return f.length=0,n?(t-=e.e+1,f[0]=p[(E-t%E)%E],e.e=-t||0):f[0]=e.e=0,e;if(0==i?(f.length=c,u=1,c--):(f.length=c+1,u=p[E-i],f[c]=a>0?b(s/p[o-a]%p[a])*u:0),n)for(;;){if(0==c){for(i=1,a=f[0];a>=10;a/=10,i++);for(a=f[0]+=u,u=1;a>=10;a/=10,u++);i!=u&&(e.e++,f[0]==k&&(f[0]=1));break}if(f[c]+=u,f[c]!=k)break;f[c--]=0,u=1}for(i=f.length;0===f[--i];f.pop());}e.e>U?e.c=e.e=null:e.e=L?j(t,r):B(t,r,"0"),e.s<0?"-"+t:t)}return H.clone=e,H.ROUND_UP=0,H.ROUND_DOWN=1,H.ROUND_CEIL=2,H.ROUND_FLOOR=3,H.ROUND_HALF_UP=4,H.ROUND_HALF_DOWN=5,H.ROUND_HALF_EVEN=6,H.ROUND_HALF_CEIL=7,H.ROUND_HALF_FLOOR=8,H.EUCLID=9,H.config=H.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(w+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(R(r=e[t],0,x,t),h=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(R(r=e[t],0,8,t),y=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(R(r[0],-x,0,t),R(r[1],0,x,t),m=r[0],L=r[1]):(R(r,-x,x,t),m=-(L=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)R(r[0],-x,-1,t),R(r[1],1,x,t),N=r[0],U=r[1];else{if(R(r,-x,x,t),!r)throw Error(w+t+" cannot be zero: "+r);N=-(U=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(w+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw M=!r,Error(w+"crypto unavailable");M=r}else M=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(R(r=e[t],0,9,t),F=r),e.hasOwnProperty(t="POW_PRECISION")&&(R(r=e[t],0,x,t),D=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(w+t+" not an object: "+r);V=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(w+t+" invalid: "+r);K="0123456789"==r.slice(0,10),q=r}}return{DECIMAL_PLACES:h,ROUNDING_MODE:y,EXPONENTIAL_AT:[m,L],RANGE:[N,U],CRYPTO:M,MODULO_MODE:F,POW_PRECISION:D,FORMAT:V,ALPHABET:q}},H.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!H.DEBUG)return!0;var t,r,n=e.c,o=e.e,i=e.s;e:if("[object Array]"=={}.toString.call(n)){if((1===i||-1===i)&&o>=-x&&o<=x&&o===b(o)){if(0===n[0]){if(0===o&&1===n.length)return!0;break e}if((t=(o+1)%E)<1&&(t+=E),String(n[0]).length==t){for(t=0;t=k||r!==b(r))break e;if(0!==r)return!0}}}else if(null===n&&null===o&&(null===i||1===i||-1===i))return!0;throw Error(w+"Invalid BigNumber: "+e)},H.maximum=H.max=function(){return X(arguments,-1)},H.minimum=H.min=function(){return X(arguments,1)},H.random=(i=9007199254740992,a=Math.random()*i&2097151?function(){return b(Math.random()*i)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,n,o,i,u=0,s=[],c=new H(d);if(null==e?e=h:R(e,0,x),o=g(e/E),M)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(o*=2));u>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[u]=r[0],t[u+1]=r[1]):(s.push(i%1e14),u+=2);u=o/2}else{if(!crypto.randomBytes)throw M=!1,Error(w+"crypto unavailable");for(t=crypto.randomBytes(o*=7);u=9e15?crypto.randomBytes(7).copy(t,u):(s.push(i%1e14),u+=7);u=o/7}if(!M)for(;u=10;i/=10,u++);ur-1&&(null==a[o+1]&&(a[o+1]=0),a[o+1]+=a[o]/r|0,a[o]%=r)}return a.reverse()}return function(n,o,i,a,u){var s,c,l,f,p,d,m,v,g=n.indexOf("."),b=h,w=y;for(g>=0&&(f=D,D=0,n=n.replace(".",""),d=(v=new H(o)).pow(n.length-g),D=f,v.c=t(B(P(d.c),d.e,"0"),10,i,e),v.e=v.c.length),l=f=(m=t(n,o,i,u?(s=q,e):(s=e,q))).length;0==m[--f];m.pop());if(!m[0])return s.charAt(0);if(g<0?--l:(d.c=m,d.e=l,d.s=a,m=(d=r(d,v,b,w,i)).c,p=d.r,l=d.e),g=m[c=l+b+1],f=i/2,p=p||c<0||null!=m[c+1],p=w<4?(null!=g||p)&&(0==w||w==(d.s<0?3:2)):g>f||g==f&&(4==w||p||6==w&&1&m[c-1]||w==(d.s<0?8:7)),c<1||!m[0])n=p?B(s.charAt(1),-b,s.charAt(0)):s.charAt(0);else{if(m.length=c,p)for(--i;++m[--c]>i;)m[c]=0,c||(++l,m=[1].concat(m));for(f=m.length;!m[--f];);for(g=0,n="";g<=f;n+=s.charAt(m[g++]));n=B(n,l,s.charAt(0))}return n}}(),r=function(){function e(e,t,r){var n,o,i,a,u=0,s=e.length,c=t%O,l=t/O|0;for(e=e.slice();s--;)u=((o=c*(i=e[s]%O)+(n=l*i+(a=e[s]/O|0)*c)%O*O+u)/r|0)+(n/O|0)+l*a,e[s]=o%r;return u&&(e=[u].concat(e)),e}function t(e,t,r,n){var o,i;if(r!=n)i=r>n?1:-1;else for(o=i=0;ot[o]?1:-1;break}return i}function r(e,t,r,n){for(var o=0;r--;)e[r]-=o,o=e[r]1;e.splice(0,1));}return function(n,o,i,a,u){var s,c,l,f,p,d,h,y,m,v,g,w,S,_,T,O,x,P=n.s==o.s?1:-1,I=n.c,R=o.c;if(!(I&&I[0]&&R&&R[0]))return new H(n.s&&o.s&&(I?!R||I[0]!=R[0]:R)?I&&0==I[0]||!R?0*P:P/0:NaN);for(m=(y=new H(P)).c=[],P=i+(c=n.e-o.e)+1,u||(u=k,c=A(n.e/E)-A(o.e/E),P=P/E|0),l=0;R[l]==(I[l]||0);l++);if(R[l]>(I[l]||0)&&c--,P<0)m.push(1),f=!0;else{for(_=I.length,O=R.length,l=0,P+=2,(p=b(u/(R[0]+1)))>1&&(R=e(R,p,u),I=e(I,p,u),O=R.length,_=I.length),S=O,g=(v=I.slice(0,O)).length;g=u/2&&T++;do{if(p=0,(s=t(R,v,O,g))<0){if(w=v[0],O!=g&&(w=w*u+(v[1]||0)),(p=b(w/T))>1)for(p>=u&&(p=u-1),h=(d=e(R,p,u)).length,g=v.length;1==t(d,v,h,g);)p--,r(d,O=10;P/=10,l++);$(y,i+(y.e=l+c*E-1)+1,a,f)}else y.e=c,y.r=+f;return y}}(),u=/^(-?)0([xbo])(?=\w[\w.]*$)/i,s=/^([^.]+)\.$/,c=/^\.([^.]+)$/,l=/^-?(Infinity|NaN)$/,f=/^\s*\+(?=[\w.])|^\s+|\s+$/g,o=function(e,t,r,n){var o,i=r?t:t.replace(f,"");if(l.test(i))e.s=isNaN(i)?null:i<0?-1:1;else{if(!r&&(i=i.replace(u,(function(e,t,r){return o="x"==(r=r.toLowerCase())?16:"b"==r?2:8,n&&n!=o?e:t})),n&&(o=n,i=i.replace(s,"$1").replace(c,"0.$1")),t!=i))return new H(i,o);if(H.DEBUG)throw Error(w+"Not a"+(n?" base "+n:"")+" number: "+t);e.s=null}e.c=e.e=null},p.absoluteValue=p.abs=function(){var e=new H(this);return e.s<0&&(e.s=1),e},p.comparedTo=function(e,t){return I(this,new H(e,t))},p.decimalPlaces=p.dp=function(e,t){var r,n,o,i=this;if(null!=e)return R(e,0,x),null==t?t=y:R(t,0,8),$(new H(i),e+i.e+1,t);if(!(r=i.c))return null;if(n=((o=r.length-1)-A(this.e/E))*E,o=r[o])for(;o%10==0;o/=10,n--);return n<0&&(n=0),n},p.dividedBy=p.div=function(e,t){return r(this,new H(e,t),h,y)},p.dividedToIntegerBy=p.idiv=function(e,t){return r(this,new H(e,t),0,1)},p.exponentiatedBy=p.pow=function(e,t){var r,n,o,i,a,u,s,c,l=this;if((e=new H(e)).c&&!e.isInteger())throw Error(w+"Exponent not an integer: "+Q(e));if(null!=t&&(t=new H(t)),a=e.e>14,!l.c||!l.c[0]||1==l.c[0]&&!l.e&&1==l.c.length||!e.c||!e.c[0])return c=new H(Math.pow(+Q(l),a?e.s*(2-C(e)):+Q(e))),t?c.mod(t):c;if(u=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new H(NaN);(n=!u&&l.isInteger()&&t.isInteger())&&(l=l.mod(t))}else{if(e.e>9&&(l.e>0||l.e<-1||(0==l.e?l.c[0]>1||a&&l.c[1]>=24e7:l.c[0]<8e13||a&&l.c[0]<=9999975e7)))return i=l.s<0&&C(e)?-0:0,l.e>-1&&(i=1/i),new H(u?1/i:i);D&&(i=g(D/E+2))}for(a?(r=new H(.5),u&&(e.s=1),s=C(e)):s=(o=Math.abs(+Q(e)))%2,c=new H(d);;){if(s){if(!(c=c.times(l)).c)break;i?c.c.length>i&&(c.c.length=i):n&&(c=c.mod(t))}if(o){if(0===(o=b(o/2)))break;s=o%2}else if($(e=e.times(r),e.e+1,1),e.e>14)s=C(e);else{if(0===(o=+Q(e)))break;s=o%2}l=l.times(l),i?l.c&&l.c.length>i&&(l.c.length=i):n&&(l=l.mod(t))}return n?c:(u&&(c=d.div(c)),t?c.mod(t):i?$(c,D,y,undefined):c)},p.integerValue=function(e){var t=new H(this);return null==e?e=y:R(e,0,8),$(t,t.e+1,e)},p.isEqualTo=p.eq=function(e,t){return 0===I(this,new H(e,t))},p.isFinite=function(){return!!this.c},p.isGreaterThan=p.gt=function(e,t){return I(this,new H(e,t))>0},p.isGreaterThanOrEqualTo=p.gte=function(e,t){return 1===(t=I(this,new H(e,t)))||0===t},p.isInteger=function(){return!!this.c&&A(this.e/E)>this.c.length-2},p.isLessThan=p.lt=function(e,t){return I(this,new H(e,t))<0},p.isLessThanOrEqualTo=p.lte=function(e,t){return-1===(t=I(this,new H(e,t)))||0===t},p.isNaN=function(){return!this.s},p.isNegative=function(){return this.s<0},p.isPositive=function(){return this.s>0},p.isZero=function(){return!!this.c&&0==this.c[0]},p.minus=function(e,t){var r,n,o,i,a=this,u=a.s;if(t=(e=new H(e,t)).s,!u||!t)return new H(NaN);if(u!=t)return e.s=-t,a.plus(e);var s=a.e/E,c=e.e/E,l=a.c,f=e.c;if(!s||!c){if(!l||!f)return l?(e.s=-t,e):new H(f?a:NaN);if(!l[0]||!f[0])return f[0]?(e.s=-t,e):new H(l[0]?a:3==y?-0:0)}if(s=A(s),c=A(c),l=l.slice(),u=s-c){for((i=u<0)?(u=-u,o=l):(c=s,o=f),o.reverse(),t=u;t--;o.push(0));o.reverse()}else for(n=(i=(u=l.length)<(t=f.length))?u:t,u=t=0;t0)for(;t--;l[r++]=0);for(t=k-1;n>u;){if(l[--n]=0;){for(r=0,p=b[o]%m,d=b[o]/m|0,i=o+(a=s);i>o;)r=((c=p*(c=g[--a]%m)+(u=d*c+(l=g[a]/m|0)*p)%m*m+h[i]+r)/y|0)+(u/m|0)+d*l,h[i--]=c%y;h[i]=r}return r?++n:h.splice(0,1),G(e,h,n)},p.negated=function(){var e=new H(this);return e.s=-e.s||null,e},p.plus=function(e,t){var r,n=this,o=n.s;if(t=(e=new H(e,t)).s,!o||!t)return new H(NaN);if(o!=t)return e.s=-t,n.minus(e);var i=n.e/E,a=e.e/E,u=n.c,s=e.c;if(!i||!a){if(!u||!s)return new H(o/0);if(!u[0]||!s[0])return s[0]?e:new H(u[0]?n:0*o)}if(i=A(i),a=A(a),u=u.slice(),o=i-a){for(o>0?(a=i,r=s):(o=-o,r=u),r.reverse();o--;r.push(0));r.reverse()}for((o=u.length)-(t=s.length)<0&&(r=s,s=u,u=r,t=o),o=0;t;)o=(u[--t]=u[t]+s[t]+o)/k|0,u[t]=k===u[t]?0:u[t]%k;return o&&(u=[o].concat(u),++a),G(e,u,a)},p.precision=p.sd=function(e,t){var r,n,o,i=this;if(null!=e&&e!==!!e)return R(e,1,x),null==t?t=y:R(t,0,8),$(new H(i),e,t);if(!(r=i.c))return null;if(n=(o=r.length-1)*E+1,o=r[o]){for(;o%10==0;o/=10,n--);for(o=r[0];o>=10;o/=10,n++);}return e&&i.e+1>n&&(n=i.e+1),n},p.shiftedBy=function(e){return R(e,-9007199254740991,_),this.times("1e"+e)},p.squareRoot=p.sqrt=function(){var e,t,n,o,i,a=this,u=a.c,s=a.s,c=a.e,l=h+4,f=new H("0.5");if(1!==s||!u||!u[0])return new H(!s||s<0&&(!u||u[0])?NaN:u?a:1/0);if(0==(s=Math.sqrt(+Q(a)))||s==1/0?(((t=P(u)).length+c)%2==0&&(t+="0"),s=Math.sqrt(+t),c=A((c+1)/2)-(c<0||c%2),n=new H(t=s==1/0?"5e"+c:(t=s.toExponential()).slice(0,t.indexOf("e")+1)+c)):n=new H(s+""),n.c[0])for((s=(c=n.e)+l)<3&&(s=0);;)if(i=n,n=f.times(i.plus(r(a,i,l,1))),P(i.c).slice(0,s)===(t=P(n.c)).slice(0,s)){if(n.e0&&h>0){for(i=h%u||u,l=d.substr(0,i);i0&&(l+=c+d.slice(i)),p&&(l="-"+l)}n=f?l+(r.decimalSeparator||"")+((s=+r.fractionGroupSize)?f.replace(new RegExp("\\d{"+s+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):f):l}return(r.prefix||"")+n+(r.suffix||"")},p.toFraction=function(e){var t,n,o,i,a,u,s,c,l,f,p,h,m=this,v=m.c;if(null!=e&&(!(s=new H(e)).isInteger()&&(s.c||1!==s.s)||s.lt(d)))throw Error(w+"Argument "+(s.isInteger()?"out of range: ":"not an integer: ")+Q(s));if(!v)return new H(m);for(t=new H(d),l=n=new H(d),o=c=new H(d),h=P(v),a=t.e=h.length-m.e-1,t.c[0]=T[(u=a%E)<0?E+u:u],e=!e||s.comparedTo(t)>0?a>0?t:l:s,u=U,U=1/0,s=new H(h),c.c[0]=0;f=r(s,t,0,1),1!=(i=n.plus(f.times(o))).comparedTo(e);)n=o,o=i,l=c.plus(f.times(i=l)),c=i,t=s.minus(f.times(i=t)),s=i;return i=r(e.minus(n),o,0,1),c=c.plus(i.times(l)),n=n.plus(i.times(o)),c.s=l.s=m.s,p=r(l,o,a*=2,y).minus(m).abs().comparedTo(r(c,n,a,y).minus(m).abs())<1?[l,o]:[c,n],U=u,p},p.toNumber=function(){return+Q(this)},p.toPrecision=function(e,t){return null!=e&&R(e,1,x),z(this,e,t,2)},p.toString=function(e){var t,r=this,o=r.s,i=r.e;return null===i?o?(t="Infinity",o<0&&(t="-"+t)):t="NaN":(null==e?t=i<=m||i>=L?j(P(r.c),i):B(P(r.c),i,"0"):10===e&&K?t=B(P((r=$(new H(r),h+i+1,y)).c),r.e,"0"):(R(e,2,q.length,"Base"),t=n(B(P(r.c),i,"0"),10,e,o,!0)),o<0&&r.c[0]&&(t="-"+t)),t},p.valueOf=p.toJSON=function(){return Q(this)},p._isBigNumber=!0,p[Symbol.toStringTag]="BigNumber",p[Symbol.for("nodejs.util.inspect.custom")]=p.valueOf,null!=t&&H.set(t),H}();const N=L;var U=r(4193),M=r.n(U),F=r(9127),D=r.n(F),V=r(5976),q=r(6371);function K(e){return K="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},K(e)}var H="13.1.0",z={},X=(0,q.vt)({headers:{"X-Client-Name":"js-stellar-sdk","X-Client-Version":H}});function G(e){return Math.floor(e/1e3)}X.interceptors.response.use((function(e){var t=M()(e.config.url).hostname(),r=0;if(e.headers instanceof Headers){var n=e.headers.get("date");n&&(r=G(Date.parse(n)))}else if("object"===K(e.headers)&&"date"in e.headers){var o=e.headers;"string"==typeof o.date&&(r=G(Date.parse(o.date)))}var i=G((new Date).getTime());return Number.isNaN(r)||(z[t]={serverTime:r,localTimeRecorded:i}),e}));const $=X;function Q(e){var t=z[e];if(!t||!t.localTimeRecorded||!t.serverTime)return null;var r=t.serverTime,n=t.localTimeRecorded,o=G((new Date).getTime());return o-n>300?null:o-n+r}function W(e){return W="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},W(e)}function Y(){Y=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",s=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),u=new I(n||[]);return o(a,"_invoke",{value:O(e,r,u)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,k=S&&S(S(R([])));k&&k!==r&&n.call(k,a)&&(w=k);var E=b.prototype=v.prototype=Object.create(w);function _(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,u){var s=f(e[o],e,i);if("throw"!==s.type){var c=s.arg,l=c.value;return l&&"object"==W(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,u)}),(function(e){r("throw",e,a,u)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,u)}))}u(s.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var u=n.delegate;if(u){var s=x(u,n);if(s){if(s===m)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function I(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function R(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:R(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function J(e,t,r,n,o,i,a){try{var u=e[i](a),s=u.value}catch(e){return void r(e)}u.done?t(s):Promise.resolve(s).then(n,o)}function Z(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){J(i,n,o,a,u,"next",e)}function u(e){J(i,n,o,a,u,"throw",e)}a(void 0)}))}}function ee(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:"";!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.url=t.clone(),this.filter=[],this.originalSegments=this.url.segment()||[],this.neighborRoot=r}),[{key:"call",value:function(){var e=this;return this.checkFilter(),this._sendNormalRequest(this.url).then((function(t){return e._parseResponse(t)}))}},{key:"stream",value:function(){throw new Error("Streaming requires eventsource to be enabled. If you need this functionality, compile with USE_EVENTSOURCE=true.")}},{key:"cursor",value:function(e){return this.url.setQuery("cursor",e),this}},{key:"limit",value:function(e){return this.url.setQuery("limit",e.toString()),this}},{key:"order",value:function(e){return this.url.setQuery("order",e),this}},{key:"join",value:function(e){return this.url.setQuery("join",e),this}},{key:"forEndpoint",value:function(e,t){if(""===this.neighborRoot)throw new Error("Invalid usage: neighborRoot not set in constructor");return this.filter.push([e,t,this.neighborRoot]),this}},{key:"checkFilter",value:function(){if(this.filter.length>=2)throw new V.v7("Too many filters specified",this.filter);if(1===this.filter.length){var e=this.originalSegments.concat(this.filter[0]);this.url.segment(e)}}},{key:"_requestFnForLink",value:function(e){var t=this;return Z(Y().mark((function r(){var n,o,i,a,u=arguments;return Y().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return n=u.length>0&&void 0!==u[0]?u[0]:{},e.templated?(i=D()(e.href),o=M()(i.expand(n))):o=M()(e.href),r.next=4,t._sendNormalRequest(o);case 4:return a=r.sent,r.abrupt("return",t._parseResponse(a));case 6:case"end":return r.stop()}}),r)})))}},{key:"_parseRecord",value:function(e){var t=this;return e._links?(Object.keys(e._links).forEach((function(r){var n=e._links[r],o=!1;if(void 0!==e[r]&&(e["".concat(r,"_attr")]=e[r],o=!0),o&&oe.indexOf(r)>=0){var i=t._parseRecord(e[r]);e[r]=Z(Y().mark((function e(){return Y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",i);case 1:case"end":return e.stop()}}),e)})))}else e[r]=t._requestFnForLink(n)})),e):e}},{key:"_sendNormalRequest",value:(ne=Z(Y().mark((function e(t){var r;return Y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return""===(r=t).authority()&&(r=r.authority(this.url.authority())),""===r.protocol()&&(r=r.protocol(this.url.protocol())),e.abrupt("return",X.get(r.toString()).then((function(e){return e.data})).catch(this._handleNetworkError));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return ne.apply(this,arguments)})},{key:"_parseResponse",value:function(e){return e._embedded&&e._embedded.records?this._toCollectionPage(e):this._parseRecord(e)}},{key:"_toCollectionPage",value:function(e){for(var t,r,n=this,o=0;ot||e>=24*r||e%r!=0)}}])}(ie);function pr(e){return pr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},pr(e)}function dr(e,t){for(var r=0;r=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:R(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function jr(e,t,r,n,o,i,a){try{var u=e[i](a),s=u.value}catch(e){return void r(e)}u.done?t(s):Promise.resolve(s).then(n,o)}function Br(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){jr(i,n,o,a,u,"next",e)}function u(e){jr(i,n,o,a,u,"throw",e)}a(void 0)}))}}function Lr(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.serverURL=M()(t);var n=void 0===r.allowHttp?ae.T.isAllowHttp():r.allowHttp,o={};if(r.appName&&(o["X-App-Name"]=r.appName),r.appVersion&&(o["X-App-Version"]=r.appVersion),r.authToken&&(o["X-Auth-Token"]=r.authToken),r.headers&&Object.assign(o,r.headers),Object.keys(o).length>0&&$.interceptors.request.use((function(e){return e.headers=e.headers||{},e.headers=Object.assign(e.headers,o),e})),"https"!==this.serverURL.protocol()&&!n)throw new Error("Cannot connect to insecure horizon server")}),[{key:"fetchTimebounds",value:(zr=Br(Cr().mark((function e(t){var r,n,o=arguments;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=o.length>1&&void 0!==o[1]&&o[1],!(n=Q(this.serverURL.hostname()))){e.next=4;break}return e.abrupt("return",{minTime:0,maxTime:n+t});case 4:if(!r){e.next=6;break}return e.abrupt("return",{minTime:0,maxTime:Math.floor((new Date).getTime()/1e3)+t});case 6:return e.next=8,$.get(M()(this.serverURL).toString());case 8:return e.abrupt("return",this.fetchTimebounds(t,!0));case 9:case"end":return e.stop()}}),e,this)}))),function(e){return zr.apply(this,arguments)})},{key:"fetchBaseFee",value:(Hr=Br(Cr().mark((function e(){var t;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.feeStats();case 2:return t=e.sent,e.abrupt("return",parseInt(t.last_ledger_base_fee,10)||100);case 4:case"end":return e.stop()}}),e,this)}))),function(){return Hr.apply(this,arguments)})},{key:"feeStats",value:(Kr=Br(Cr().mark((function e(){var t;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(t=new ie(M()(this.serverURL))).filter.push(["fee_stats"]),e.abrupt("return",t.call());case 3:case"end":return e.stop()}}),e,this)}))),function(){return Kr.apply(this,arguments)})},{key:"root",value:(qr=Br(Cr().mark((function e(){var t;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=new ie(M()(this.serverURL)),e.abrupt("return",t.call());case 2:case"end":return e.stop()}}),e,this)}))),function(){return qr.apply(this,arguments)})},{key:"submitTransaction",value:(Vr=Br(Cr().mark((function e(t){var r,n=arguments;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((n.length>1&&void 0!==n[1]?n[1]:{skipMemoRequiredCheck:!1}).skipMemoRequiredCheck){e.next=4;break}return e.next=4,this.checkMemoRequired(t);case 4:return r=encodeURIComponent(t.toEnvelope().toXDR().toString("base64")),e.abrupt("return",$.post(M()(this.serverURL).segment("transactions").toString(),"tx=".concat(r),{timeout:6e4}).then((function(e){if(!e.data.result_xdr)return e.data;var t,r,n=u.xdr.TransactionResult.fromXDR(e.data.result_xdr,"base64").result().value();return n.length&&(t=n.map((function(e,t){if("manageBuyOffer"!==e.value().switch().name&&"manageSellOffer"!==e.value().switch().name)return null;r=!0;var n,o=new N(0),i=new N(0),a=e.value().value().success(),s=a.offersClaimed().map((function(e){var t=e.value(),r="";switch(e.switch()){case u.xdr.ClaimAtomType.claimAtomTypeV0():r=u.StrKey.encodeEd25519PublicKey(t.sellerEd25519());break;case u.xdr.ClaimAtomType.claimAtomTypeOrderBook():r=u.StrKey.encodeEd25519PublicKey(t.sellerId().ed25519());break;default:throw new Error("Invalid offer result type: ".concat(e.switch()))}var n=new N(t.amountBought().toString()),a=new N(t.amountSold().toString());o=o.plus(a),i=i.plus(n);var s=u.Asset.fromOperation(t.assetSold()),c=u.Asset.fromOperation(t.assetBought()),l={type:s.getAssetType(),assetCode:s.getCode(),issuer:s.getIssuer()},f={type:c.getAssetType(),assetCode:c.getCode(),issuer:c.getIssuer()};return{sellerId:r,offerId:t.offerId().toString(),assetSold:l,amountSold:Ur(a),assetBought:f,amountBought:Ur(n)}})),c=a.offer().switch().name;if("function"==typeof a.offer().value&&a.offer().value()){var l=a.offer().value();n={offerId:l.offerId().toString(),selling:{},buying:{},amount:Ur(l.amount().toString()),price:{n:l.price().n(),d:l.price().d()}};var f=u.Asset.fromOperation(l.selling());n.selling={type:f.getAssetType(),assetCode:f.getCode(),issuer:f.getIssuer()};var p=u.Asset.fromOperation(l.buying());n.buying={type:p.getAssetType(),assetCode:p.getCode(),issuer:p.getIssuer()}}return{offersClaimed:s,effect:c,operationIndex:t,currentOffer:n,amountBought:Ur(o),amountSold:Ur(i),isFullyOpen:!s.length&&"manageOfferDeleted"!==c,wasPartiallyFilled:!!s.length&&"manageOfferDeleted"!==c,wasImmediatelyFilled:!!s.length&&"manageOfferDeleted"===c,wasImmediatelyDeleted:!s.length&&"manageOfferDeleted"===c}})).filter((function(e){return!!e}))),Ir(Ir({},e.data),{},{offerResults:r?t:void 0})})).catch((function(e){return e instanceof Error?Promise.reject(e):Promise.reject(new V.nS("Transaction submission failed. Server responded: ".concat(e.status," ").concat(e.statusText),e.data))})));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return Vr.apply(this,arguments)})},{key:"submitAsyncTransaction",value:(Dr=Br(Cr().mark((function e(t){var r,n=arguments;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((n.length>1&&void 0!==n[1]?n[1]:{skipMemoRequiredCheck:!1}).skipMemoRequiredCheck){e.next=4;break}return e.next=4,this.checkMemoRequired(t);case 4:return r=encodeURIComponent(t.toEnvelope().toXDR().toString("base64")),e.abrupt("return",$.post(M()(this.serverURL).segment("transactions_async").toString(),"tx=".concat(r)).then((function(e){return e.data})).catch((function(e){return e instanceof Error?Promise.reject(e):Promise.reject(new V.nS("Transaction submission failed. Server responded: ".concat(e.status," ").concat(e.statusText),e.data))})));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return Dr.apply(this,arguments)})},{key:"accounts",value:function(){return new he(M()(this.serverURL))}},{key:"claimableBalances",value:function(){return new Ie(M()(this.serverURL))}},{key:"ledgers",value:function(){return new et(M()(this.serverURL))}},{key:"transactions",value:function(){return new xr(M()(this.serverURL))}},{key:"offers",value:function(){return new mt(M()(this.serverURL))}},{key:"orderbook",value:function(e,t){return new Ct(M()(this.serverURL),e,t)}},{key:"trades",value:function(){return new br(M()(this.serverURL))}},{key:"operations",value:function(){return new _t(M()(this.serverURL))}},{key:"liquidityPools",value:function(){return new st(M()(this.serverURL))}},{key:"strictReceivePaths",value:function(e,t,r){return new $t(M()(this.serverURL),e,t,r)}},{key:"strictSendPaths",value:function(e,t,r){return new rr(M()(this.serverURL),e,t,r)}},{key:"payments",value:function(){return new Dt(M()(this.serverURL))}},{key:"effects",value:function(){return new Me(M()(this.serverURL))}},{key:"friendbot",value:function(e){return new Xe(M()(this.serverURL),e)}},{key:"assets",value:function(){return new ke(M()(this.serverURL))}},{key:"loadAccount",value:(Fr=Br(Cr().mark((function e(t){var r;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.accounts().accountId(t).call();case 2:return r=e.sent,e.abrupt("return",new m(r));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return Fr.apply(this,arguments)})},{key:"tradeAggregation",value:function(e,t,r,n,o,i){return new fr(M()(this.serverURL),e,t,r,n,o,i)}},{key:"checkMemoRequired",value:(Mr=Br(Cr().mark((function e(t){var r,n,o,i;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t instanceof u.FeeBumpTransaction&&(t=t.innerTransaction),"none"===t.memo.type){e.next=3;break}return e.abrupt("return");case 3:r=new Set,n=0;case 5:if(!(n{"use strict";async function n(e,t){const r={config:e};return r.status=t.status,r.statusText=t.statusText,r.headers=t.headers,"stream"===e.responseType?(r.data=t.body,r):t[e.responseType||"text"]().then((n=>{e.transformResponse?(Array.isArray(e.transformResponse)?e.transformResponse.map((r=>n=r.call(e,n,t?.headers,t?.status))):n=e.transformResponse(n,t?.headers,t?.status),r.data=n):(r.data=n,r.data=JSON.parse(n))})).catch(Object).then((()=>r))}function o(e){let t=e.url||"";return e.baseURL&&e.url&&(t=e.url.replace(/^(?!.*\/\/)\/?/,`${e.baseURL}/`)),e.params&&Object.keys(e.params).length>0&&e.url&&(t+=(~e.url.indexOf("?")?"&":"?")+(e.paramsSerializer?e.paramsSerializer(e.params):new URLSearchParams(e.params))),t}function i(e,t){const r={...t,...e};if(t?.params&&e?.params&&(r.params={...t?.params,...e?.params}),t?.headers&&e?.headers){r.headers=new Headers(t.headers||{});new Headers(e.headers||{}).forEach(((e,t)=>{r.headers.set(t,e)}))}return r}function a(e,t){const r=t.get("content-type");return r?"application/x-www-form-urlencoded"!==r||e instanceof URLSearchParams?"application/json"===r&&"object"==typeof e&&(e=JSON.stringify(e)):e=new URLSearchParams(e):"string"==typeof e?t.set("content-type","text/plain"):e instanceof URLSearchParams?t.set("content-type","application/x-www-form-urlencoded"):e instanceof Blob||e instanceof ArrayBuffer||ArrayBuffer.isView(e)?t.set("content-type","application/octet-stream"):"object"==typeof e&&"function"!=typeof e.append&&"function"!=typeof e.text&&(e=JSON.stringify(e),t.set("content-type","application/json")),e}async function u(e,t,r,s,c,p){"string"==typeof e?(t=t||{}).url=e:t=e||{};const d=i(t,r||{});if(d.fetchOptions=d.fetchOptions||{},d.timeout=d.timeout||0,d.headers=new Headers(d.headers||{}),d.transformRequest=d.transformRequest??a,p=p||d.data,d.transformRequest&&p&&(Array.isArray(d.transformRequest)?d.transformRequest.map((e=>p=e.call(d,p,d.headers))):p=d.transformRequest(p,d.headers)),d.url=o(d),d.method=s||d.method||"get",c&&c.request.handlers.length>0){const e=c.request.handlers.filter((e=>!e?.runWhen||"function"==typeof e.runWhen&&e.runWhen(d))).flatMap((e=>[e.fulfilled,e.rejected]));let t=d;for(let r=0,n=e.length;r{r.headers.set(t,e)})));return r}({method:d.method?.toUpperCase(),body:p,headers:d.headers,credentials:d.withCredentials?"include":void 0,signal:d.signal},d.fetchOptions);let y=async function(e,t){let r=null;if("any"in AbortSignal){const r=[];e.timeout&&r.push(AbortSignal.timeout(e.timeout)),e.signal&&r.push(e.signal),r.length>0&&(t.signal=AbortSignal.any(r))}else e.timeout&&(t.signal=AbortSignal.timeout(e.timeout));try{return r=await fetch(e.url,t),(e.validateStatus?e.validateStatus(r.status):r.ok)?await n(e,r):Promise.reject(new l(`Request failed with status code ${r?.status}`,[l.ERR_BAD_REQUEST,l.ERR_BAD_RESPONSE][Math.floor(r?.status/100)-4],e,new Request(e.url,t),await n(e,r)))}catch(t){if("AbortError"===t.name||"TimeoutError"===t.name){const r="TimeoutError"===t.name;return Promise.reject(r?new l(e.timeoutErrorMessage||`timeout of ${e.timeout} ms exceeded`,l.ECONNABORTED,e,u):new f(null,e))}return Promise.reject(new l(t.message,void 0,e,u,void 0))}}(d,h);if(c&&c.response.handlers.length>0){const e=c.response.handlers.flatMap((e=>[e.fulfilled,e.rejected]));for(let t=0,r=e.length;tO,fetchClient:()=>x});var s=class{handlers=[];constructor(){this.handlers=[]}use=(e,t,r)=>(this.handlers.push({fulfilled:e,rejected:t,runWhen:r?.runWhen}),this.handlers.length-1);eject=e=>{this.handlers[e]&&(this.handlers[e]=null)};clear=()=>{this.handlers=[]}};function c(e){e=e||{};const t={request:new s,response:new s},r=(r,n)=>u(r,n,e,void 0,t);return r.defaults=e,r.interceptors=t,r.getUri=t=>o(i(t||{},e)),r.request=r=>u(r,void 0,e,void 0,t),["get","delete","head","options"].forEach((n=>{r[n]=(r,o)=>u(r,o,e,n,t)})),["post","put","patch"].forEach((n=>{r[n]=(r,o,i)=>u(r,i,e,n,t,o)})),["postForm","putForm","patchForm"].forEach((n=>{r[n]=(r,o,i)=>((i=i||{}).headers=new Headers(i.headers||{}),i.headers.set("content-type","application/x-www-form-urlencoded"),u(r,i,e,n.replace("Form",""),t,o))})),r}var l=class extends Error{config;code;request;response;status;isAxiosError;constructor(e,t,r,n,o){super(e),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.name="AxiosError",this.code=t,this.config=r,this.request=n,this.response=o,this.isAxiosError=!0}static ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";static ERR_BAD_OPTION="ERR_BAD_OPTION";static ERR_NETWORK="ERR_NETWORK";static ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";static ERR_BAD_REQUEST="ERR_BAD_REQUEST";static ERR_INVALID_URL="ERR_INVALID_URL";static ERR_CANCELED="ERR_CANCELED";static ECONNABORTED="ECONNABORTED";static ETIMEDOUT="ETIMEDOUT"},f=class extends l{constructor(e,t,r){super(e||"canceled",l.ERR_CANCELED,t,r),this.name="CanceledError"}};var p=c();p.create=e=>c(e);var d=p,h=r(5798);function y(e){return y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},y(e)}function m(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t0&&void 0!==arguments[0]?arguments[0]:{},t=v(v({},e),{},{headers:e.headers||{}}),r=d.create(t),n=new _,o=new _;return{interceptors:{request:n,response:o},defaults:v(v({},t),{},{adapter:function(e){return r.request(e)}}),create:function(e){return O(v(v({},this.defaults),e))},makeRequest:function(e){var t=this;return new Promise((function(r,i){var a=new AbortController;e.signal=a.signal,e.cancelToken&&e.cancelToken.promise.then((function(){a.abort(),i(new Error("Request canceled"))}));var u=e;if(n.handlers.length>0)for(var s=n.handlers.filter((function(e){return null!==e})).flatMap((function(e){return[e.fulfilled,e.rejected]})),c=0,l=s.length;c0)for(var y=o.handlers.filter((function(e){return null!==e})).flatMap((function(e){return[e.fulfilled,e.rejected]})),m=function(e){h=h.then((function(t){var r=y[e];return"function"==typeof r?r(t):t}),(function(t){var r=y[e+1];if("function"==typeof r)return r(t);throw t})).then((function(e){return e}))},v=0,g=y.length;v{"use strict";r.d(t,{ok:()=>n,vt:()=>o});r(5798);var n,o,i=r(8920);n=i.fetchClient,o=i.create},5798:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rc});var a,u,s,c=(a=function e(t){var r,n=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.promise=new Promise((function(e){r=e})),t((function(e){n.reason=e,r()}))},(u=[{key:"throwIfRequested",value:function(){if(this.reason)throw new Error(this.reason)}}])&&o(a.prototype,u),s&&o(a,s),Object.defineProperty(a,"prototype",{writable:!1}),a)},4356:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AccountRequiresMemoError:()=>n.Cu,BadRequestError:()=>n.v7,BadResponseError:()=>n.nS,Config:()=>o.T,Federation:()=>u,Friendbot:()=>c,Horizon:()=>l,NetworkError:()=>n.Dr,NotFoundError:()=>n.m_,StellarToml:()=>a,Utils:()=>i.A,WebAuth:()=>s,contract:()=>p,default:()=>y,rpc:()=>f});var n=r(5976),o=r(8732),i=r(3121),a=r(3898),u=r(7600),s=r(5479),c=r(8242),l=r(8733),f=r(3496),p=r(6299),d=r(356),h={};for(const e in d)["default","Config","Utils","StellarToml","Federation","WebAuth","Friendbot","Horizon","rpc","contract","AccountRequiresMemoError","BadRequestError","BadResponseError","NetworkError","NotFoundError"].indexOf(e)<0&&(h[e]=()=>d[e]);r.d(t,h);const y=(e=r.hmd(e)).exports;void 0===r.g.__USE_AXIOS__&&(r.g.__USE_AXIOS__=!0),void 0===r.g.__USE_EVENTSOURCE__&&(r.g.__USE_EVENTSOURCE__=!1)},4076:(e,t,r)=>{"use strict";var n;r.d(t,{j:()=>n}),function(e){var t=function(e){return e.SUCCESS="SUCCESS",e.NOT_FOUND="NOT_FOUND",e.FAILED="FAILED",e}({});function r(e){return"transactionData"in e}e.GetTransactionStatus=t,e.isSimulationError=function(e){return"error"in e},e.isSimulationSuccess=r,e.isSimulationRestore=function(e){return r(e)&&"restorePreamble"in e&&!!e.restorePreamble.transactionData},e.isSimulationRaw=function(e){return!e._parsed}}(n||(n={}))},3496:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Api:()=>n.j,AxiosClient:()=>u,BasicSleepStrategy:()=>x,Durability:()=>O,LinearSleepStrategy:()=>A,Server:()=>oe,assembleTransaction:()=>d.X,default:()=>ie,parseRawEvents:()=>h.fG,parseRawSimulation:()=>h.jr});var n=r(4076),o=r(4193),i=r.n(o),a=r(356);const u=(0,r(6371).vt)({headers:{"X-Client-Name":"js-soroban-client","X-Client-Version":"13.1.0"}});function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function c(){c=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",u=i.asyncIterator||"@@asyncIterator",l=i.toStringTag||"@@toStringTag";function f(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{f({},"")}catch(e){f=function(e,t,r){return e[t]=r}}function p(e,t,r,n){var i=t&&t.prototype instanceof b?t:b,a=Object.create(i.prototype),u=new C(n||[]);return o(a,"_invoke",{value:A(e,r,u)}),a}function d(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=p;var h="suspendedStart",y="suspendedYield",m="executing",v="completed",g={};function b(){}function w(){}function S(){}var k={};f(k,a,(function(){return this}));var E=Object.getPrototypeOf,_=E&&E(E(j([])));_&&_!==r&&n.call(_,a)&&(k=_);var T=S.prototype=b.prototype=Object.create(k);function O(e){["next","throw","return"].forEach((function(t){f(e,t,(function(e){return this._invoke(t,e)}))}))}function x(e,t){function r(o,i,a,u){var c=d(e[o],e,i);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==s(f)&&n.call(f,"__await")?t.resolve(f.__await).then((function(e){r("next",e,a,u)}),(function(e){r("throw",e,a,u)})):t.resolve(f).then((function(e){l.value=e,a(l)}),(function(e){return r("throw",e,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function A(t,r,n){var o=h;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var u=n.delegate;if(u){var s=P(u,n);if(s){if(s===g)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=m;var c=d(t,r,n);if("normal"===c.type){if(o=n.done?v:y,c.arg===g)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=v,n.method="throw",n.arg=c.arg)}}}function P(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,P(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=d(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function I(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function R(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(I,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),R(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;R(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function l(e,t,r,n,o,i,a){try{var u=e[i](a),s=u.value}catch(e){return void r(e)}u.done?t(s):Promise.resolve(s).then(n,o)}function f(e,t){return p.apply(this,arguments)}function p(){var e;return e=c().mark((function e(t,r){var n,o,i,a=arguments;return c().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=a.length>2&&void 0!==a[2]?a[2]:null,e.next=3,u.post(t,{jsonrpc:"2.0",id:1,method:r,params:n});case 3:if(o=e.sent,s=o.data,c="error",!s.hasOwnProperty(c)){e.next=8;break}throw o.data.error;case 8:return e.abrupt("return",null===(i=o.data)||void 0===i?void 0:i.result);case 9:case"end":return e.stop()}var s,c}),e)})),p=function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){l(i,n,o,a,u,"next",e)}function u(e){l(i,n,o,a,u,"throw",e)}a(void 0)}))},p.apply(this,arguments)}var d=r(8680),h=r(784),y=r(3121),m=r(8287).Buffer;function v(e){return v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},v(e)}function g(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function b(e){for(var t=1;t=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),R(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;R(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function k(e,t,r,n,o,i,a){try{var u=e[i](a),s=u.value}catch(e){return void r(e)}u.done?t(s):Promise.resolve(s).then(n,o)}function E(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){k(i,n,o,a,u,"next",e)}function u(e){k(i,n,o,a,u,"throw",e)}a(void 0)}))}}function _(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:{};if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.serverURL=i()(t),r.headers&&0!==Object.keys(r.headers).length&&u.interceptors.request.use((function(e){return e.headers=Object.assign(e.headers,r.headers),e})),"https"!==this.serverURL.protocol()&&!r.allowHttp)throw new Error("Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set")},R=[{key:"getAccount",value:(ne=E(S().mark((function e(t){var r,n,o;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=a.xdr.LedgerKey.account(new a.xdr.LedgerKeyAccount({accountId:a.Keypair.fromPublicKey(t).xdrPublicKey()})),e.next=3,this.getLedgerEntries(r);case 3:if(0!==(n=e.sent).entries.length){e.next=6;break}return e.abrupt("return",Promise.reject({code:404,message:"Account not found: ".concat(t)}));case 6:return o=n.entries[0].val.account(),e.abrupt("return",new a.Account(t,o.seqNum().toString()));case 8:case"end":return e.stop()}}),e,this)}))),function(e){return ne.apply(this,arguments)})},{key:"getHealth",value:(re=E(S().mark((function e(){return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",f(this.serverURL.toString(),"getHealth"));case 1:case"end":return e.stop()}}),e,this)}))),function(){return re.apply(this,arguments)})},{key:"getContractData",value:(te=E(S().mark((function e(t,r){var n,o,i,u,s=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=s.length>2&&void 0!==s[2]?s[2]:O.Persistent,"string"!=typeof t){e.next=5;break}o=new a.Contract(t).address().toScAddress(),e.next=14;break;case 5:if(!(t instanceof a.Address)){e.next=9;break}o=t.toScAddress(),e.next=14;break;case 9:if(!(t instanceof a.Contract)){e.next=13;break}o=t.address().toScAddress(),e.next=14;break;case 13:throw new TypeError("unknown contract type: ".concat(t));case 14:e.t0=n,e.next=e.t0===O.Temporary?17:e.t0===O.Persistent?19:21;break;case 17:return i=a.xdr.ContractDataDurability.temporary(),e.abrupt("break",22);case 19:return i=a.xdr.ContractDataDurability.persistent(),e.abrupt("break",22);case 21:throw new TypeError("invalid durability: ".concat(n));case 22:return u=a.xdr.LedgerKey.contractData(new a.xdr.LedgerKeyContractData({key:r,contract:o,durability:i})),e.abrupt("return",this.getLedgerEntries(u).then((function(e){return 0===e.entries.length?Promise.reject({code:404,message:"Contract data not found. Contract: ".concat(a.Address.fromScAddress(o).toString(),", Key: ").concat(r.toXDR("base64"),", Durability: ").concat(n)}):e.entries[0]})));case 24:case"end":return e.stop()}}),e,this)}))),function(e,t){return te.apply(this,arguments)})},{key:"getContractWasmByContractId",value:(ee=E(S().mark((function e(t){var r,n,o,i;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=new a.Contract(t).getFootprint(),e.next=3,this.getLedgerEntries(n);case 3:if((o=e.sent).entries.length&&null!==(r=o.entries[0])&&void 0!==r&&r.val){e.next=6;break}return e.abrupt("return",Promise.reject({code:404,message:"Could not obtain contract hash from server"}));case 6:return i=o.entries[0].val.contractData().val().instance().executable().wasmHash(),e.abrupt("return",this.getContractWasmByHash(i));case 8:case"end":return e.stop()}}),e,this)}))),function(e){return ee.apply(this,arguments)})},{key:"getContractWasmByHash",value:(Z=E(S().mark((function e(t){var r,n,o,i,u,s,c=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=c.length>1&&void 0!==c[1]?c[1]:void 0,o="string"==typeof t?m.from(t,n):t,i=a.xdr.LedgerKey.contractCode(new a.xdr.LedgerKeyContractCode({hash:o})),e.next=5,this.getLedgerEntries(i);case 5:if((u=e.sent).entries.length&&null!==(r=u.entries[0])&&void 0!==r&&r.val){e.next=8;break}return e.abrupt("return",Promise.reject({code:404,message:"Could not obtain contract wasm from server"}));case 8:return s=u.entries[0].val.contractCode().code(),e.abrupt("return",s);case 10:case"end":return e.stop()}}),e,this)}))),function(e){return Z.apply(this,arguments)})},{key:"getLedgerEntries",value:(J=E(S().mark((function e(){var t=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this._getLedgerEntries.apply(this,t).then(h.$D));case 1:case"end":return e.stop()}}),e,this)}))),function(){return J.apply(this,arguments)})},{key:"_getLedgerEntries",value:(Y=E(S().mark((function e(){var t,r,n,o=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(t=o.length,r=new Array(t),n=0;n{"use strict";r.d(t,{$D:()=>d,Af:()=>c,WC:()=>l,fG:()=>p,jr:()=>h,tR:()=>f});var n=r(356),o=r(4076);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function u(e){for(var t=1;t0&&{diagnosticEvents:r.map((function(e){return n.xdr.DiagnosticEvent.fromXDR(e,"base64")}))}),{},{errorResult:n.xdr.TransactionResult.fromXDR(t,"base64")}):u({},e)}function l(e){var t,r=n.xdr.TransactionMeta.fromXDR(e.resultMetaXdr,"base64"),o={ledger:e.ledger,createdAt:e.createdAt,applicationOrder:e.applicationOrder,feeBump:e.feeBump,envelopeXdr:n.xdr.TransactionEnvelope.fromXDR(e.envelopeXdr,"base64"),resultXdr:n.xdr.TransactionResult.fromXDR(e.resultXdr,"base64"),resultMetaXdr:r};3===r.switch()&&null!==r.v3().sorobanMeta()&&(o.returnValue=null===(t=r.v3().sorobanMeta())||void 0===t?void 0:t.returnValue());return"diagnosticEventsXdr"in e&&e.diagnosticEventsXdr&&(o.diagnosticEventsXdr=e.diagnosticEventsXdr.map((function(e){return n.xdr.DiagnosticEvent.fromXDR(e,"base64")}))),o}function f(e){return u({status:e.status,txHash:e.txHash},l(e))}function p(e){var t;return{latestLedger:e.latestLedger,cursor:e.cursor,events:(null!==(t=e.events)&&void 0!==t?t:[]).map((function(e){var t=u({},e);return delete t.contractId,u(u(u({},t),""!==e.contractId&&{contractId:new n.Contract(e.contractId)}),{},{topic:e.topic.map((function(e){return n.xdr.ScVal.fromXDR(e,"base64")})),value:n.xdr.ScVal.fromXDR(e.value,"base64")})}))}}function d(e){var t;return{latestLedger:e.latestLedger,entries:(null!==(t=e.entries)&&void 0!==t?t:[]).map((function(e){if(!e.key||!e.xdr)throw new TypeError("invalid ledger entry: ".concat(JSON.stringify(e)));return u({lastModifiedLedgerSeq:e.lastModifiedLedgerSeq,key:n.xdr.LedgerKey.fromXDR(e.key,"base64"),val:n.xdr.LedgerEntryData.fromXDR(e.xdr,"base64")},void 0!==e.liveUntilLedgerSeq&&{liveUntilLedgerSeq:e.liveUntilLedgerSeq})}))}}function h(e){var t,r;if(!o.j.isSimulationRaw(e))return e;var i={_parsed:!0,id:e.id,latestLedger:e.latestLedger,events:null!==(t=null===(r=e.events)||void 0===r?void 0:r.map((function(e){return n.xdr.DiagnosticEvent.fromXDR(e,"base64")})))&&void 0!==t?t:[]};return"string"==typeof e.error?u(u({},i),{},{error:e.error}):function(e,t){var r,o,i,a,s,c=u(u(u({},t),{},{transactionData:new n.SorobanDataBuilder(e.transactionData),minResourceFee:e.minResourceFee},null!==(r=null===(o=e.results)||void 0===o?void 0:o.length)&&void 0!==r&&r&&{result:e.results.map((function(e){var t;return{auth:(null!==(t=e.auth)&&void 0!==t?t:[]).map((function(e){return n.xdr.SorobanAuthorizationEntry.fromXDR(e,"base64")})),retval:e.xdr?n.xdr.ScVal.fromXDR(e.xdr,"base64"):n.xdr.ScVal.scvVoid()}}))[0]}),null!==(i=null===(a=e.stateChanges)||void 0===a?void 0:a.length)&&void 0!==i&&i&&{stateChanges:null===(s=e.stateChanges)||void 0===s?void 0:s.map((function(e){return{type:e.type,key:n.xdr.LedgerKey.fromXDR(e.key,"base64"),before:e.before?n.xdr.LedgerEntry.fromXDR(e.before,"base64"):null,after:e.after?n.xdr.LedgerEntry.fromXDR(e.after,"base64"):null}}))});return e.restorePreamble&&""!==e.restorePreamble.transactionData?u(u({},c),{},{restorePreamble:{minResourceFee:e.restorePreamble.minResourceFee,transactionData:new n.SorobanDataBuilder(e.restorePreamble.transactionData)}}):c}(e,i)}},8680:(e,t,r)=>{"use strict";r.d(t,{X:()=>a});var n=r(356),o=r(4076),i=r(784);function a(e,t){if("innerTransaction"in e)return a(e.innerTransaction,t);if(!function(e){if(1!==e.operations.length)return!1;switch(e.operations[0].type){case"invokeHostFunction":case"extendFootprintTtl":case"restoreFootprint":return!0;default:return!1}}(e))throw new TypeError("unsupported transaction: must contain exactly one invokeHostFunction, extendFootprintTtl, or restoreFootprint operation");var r=(0,i.jr)(t);if(!o.j.isSimulationSuccess(r))throw new Error("simulation incorrect: ".concat(JSON.stringify(r)));var u=parseInt(e.fee)||0,s=parseInt(r.minResourceFee)||0,c=n.TransactionBuilder.cloneFrom(e,{fee:(u+s).toString(),sorobanData:r.transactionData.build(),networkPassphrase:e.networkPassphrase});if("invokeHostFunction"===e.operations[0].type){var l;c.clearOperations();var f=e.operations[0],p=null!==(l=f.auth)&&void 0!==l?l:[];c.addOperation(n.Operation.invokeHostFunction({source:f.source,func:f.func,auth:p.length>0?p:r.result.auth}))}return c}},3898:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Api:()=>{},Resolver:()=>b,STELLAR_TOML_MAX_SIZE:()=>v});var n=r(1293),o=r.n(n),i=r(6371),a=r(8732);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function s(){s=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",l=i.toStringTag||"@@toStringTag";function f(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{f({},"")}catch(e){f=function(e,t,r){return e[t]=r}}function p(e,t,r,n){var i=t&&t.prototype instanceof b?t:b,a=Object.create(i.prototype),u=new C(n||[]);return o(a,"_invoke",{value:A(e,r,u)}),a}function d(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=p;var h="suspendedStart",y="suspendedYield",m="executing",v="completed",g={};function b(){}function w(){}function S(){}var k={};f(k,a,(function(){return this}));var E=Object.getPrototypeOf,_=E&&E(E(j([])));_&&_!==r&&n.call(_,a)&&(k=_);var T=S.prototype=b.prototype=Object.create(k);function O(e){["next","throw","return"].forEach((function(t){f(e,t,(function(e){return this._invoke(t,e)}))}))}function x(e,t){function r(o,i,a,s){var c=d(e[o],e,i);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==u(f)&&n.call(f,"__await")?t.resolve(f.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(f).then((function(e){l.value=e,a(l)}),(function(e){return r("throw",e,a,s)}))}s(c.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function A(t,r,n){var o=h;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var u=n.delegate;if(u){var s=P(u,n);if(s){if(s===g)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=m;var c=d(t,r,n);if("normal"===c.type){if(o=n.done?v:y,c.arg===g)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=v,n.method="throw",n.arg=c.arg)}}}function P(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,P(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=d(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function I(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function R(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(I,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),R(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;R(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function c(e,t,r,n,o,i,a){try{var u=e[i](a),s=u.value}catch(e){return void r(e)}u.done?t(s):Promise.resolve(s).then(n,o)}function l(e,t){for(var r=0;r1&&void 0!==f[1]?f[1]:{}).allowHttp?a.T.isAllowHttp():n.allowHttp,c=void 0===n.timeout?a.T.getTimeout():n.timeout,l=u?"http":"https",e.abrupt("return",i.ok.get("".concat(l,"://").concat(t,"/.well-known/stellar.toml"),{maxRedirects:null!==(r=n.allowedRedirects)&&void 0!==r?r:0,maxContentLength:v,cancelToken:c?new g((function(e){return setTimeout((function(){return e("timeout of ".concat(c,"ms exceeded"))}),c)})):void 0,timeout:c}).then((function(e){try{var t=o().parse(e.data);return Promise.resolve(t)}catch(e){return Promise.reject(new Error("stellar.toml is invalid - Parsing error on line ".concat(e.line,", column ").concat(e.column,": ").concat(e.message)))}})).catch((function(e){throw e.message.match(/^maxContentLength size/)?new Error("stellar.toml file exceeds allowed size of ".concat(v)):e})));case 5:case"end":return e.stop()}}),e)})),m=function(){var e=this,t=arguments;return new Promise((function(r,n){var o=y.apply(e,t);function i(e){c(o,r,n,i,a,"next",e)}function a(e){c(o,r,n,i,a,"throw",e)}i(void 0)}))},function(e){return m.apply(this,arguments)})}],d&&l(p.prototype,d),h&&l(p,h),Object.defineProperty(p,"prototype",{writable:!1}),p)},3121:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rc});var a,u,s,c=(a=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},s=[{key:"validateTimebounds",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!e.timeBounds)return!1;var r=Math.floor(Date.now()/1e3),n=e.timeBounds,o=n.minTime,i=n.maxTime;return r>=Number.parseInt(o,10)-t&&r<=Number.parseInt(i,10)+t}},{key:"sleep",value:function(e){return new Promise((function(t){return setTimeout(t,e)}))}}],(u=null)&&o(a.prototype,u),s&&o(a,s),Object.defineProperty(a,"prototype",{writable:!1}),a)},5479:(e,t,r)=>{"use strict";r.r(t),r.d(t,{InvalidChallengeError:()=>y,buildChallengeTx:()=>_,gatherTxSigners:()=>P,readChallengeTx:()=>T,verifyChallengeTxSigners:()=>x,verifyChallengeTxThreshold:()=>O,verifyTxSignedBy:()=>A});var n=r(3209),o=r.n(n),i=r(356),a=r(3121);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function s(e,t){for(var r=0;r=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,u=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){u=!0,i=e},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw i}}}}function b(e){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},b(e)}function w(e){return function(e){if(Array.isArray(e))return e}(e)||E(e)||S(e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function S(e,t){if(e){if("string"==typeof e)return k(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?k(e,t):void 0}}function k(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r3&&void 0!==arguments[3]?arguments[3]:300,a=arguments.length>4?arguments[4]:void 0,u=arguments.length>5?arguments[5]:void 0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,c=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null,l=arguments.length>8&&void 0!==arguments[8]?arguments[8]:null;if(t.startsWith("M")&&s)throw Error("memo cannot be used if clientAccountID is a muxed account");var f=new i.Account(e.publicKey(),"-1"),p=Math.floor(Date.now()/1e3),d=o()(48).toString("base64"),h=new i.TransactionBuilder(f,{fee:i.BASE_FEE,networkPassphrase:a,timebounds:{minTime:p,maxTime:p+n}}).addOperation(i.Operation.manageData({name:"".concat(r," auth"),value:d,source:t})).addOperation(i.Operation.manageData({name:"web_auth_domain",value:u,source:f.accountId()}));if(c){if(!l)throw Error("clientSigningKey is required if clientDomain is provided");h.addOperation(i.Operation.manageData({name:"client_domain",value:c,source:l}))}s&&h.addMemo(i.Memo.id(s));var y=h.build();return y.sign(e),y.toEnvelope().toXDR("base64").toString()}function T(e,t,r,n,o){var u,s;if(t.startsWith("M"))throw Error("Invalid serverAccountID: multiplexed accounts are not supported.");try{s=new i.Transaction(e,r)}catch(t){try{s=new i.FeeBumpTransaction(e,r)}catch(e){throw new y("Invalid challenge: unable to deserialize challengeTx transaction string")}throw new y("Invalid challenge: expected a Transaction but received a FeeBumpTransaction")}if(0!==Number.parseInt(s.sequence,10))throw new y("The transaction sequence number should be zero");if(s.source!==t)throw new y("The transaction source account is not equal to the server's account");if(s.operations.length<1)throw new y("The transaction should contain at least one operation");var c=w(s.operations),l=c[0],f=c.slice(1);if(!l.source)throw new y("The transaction's operation should contain a source account");var p,d=l.source,h=null;if(s.memo.type!==i.MemoNone){if(d.startsWith("M"))throw new y("The transaction has a memo but the client account ID is a muxed account");if(s.memo.type!==i.MemoID)throw new y("The transaction's memo must be of type `id`");h=s.memo.value}if("manageData"!==l.type)throw new y("The transaction's operation type should be 'manageData'");if(s.timeBounds&&Number.parseInt(null===(u=s.timeBounds)||void 0===u?void 0:u.maxTime,10)===i.TimeoutInfinite)throw new y("The transaction requires non-infinite timebounds");if(!a.A.validateTimebounds(s,300))throw new y("The transaction has expired");if(void 0===l.value)throw new y("The transaction's operation values should not be null");if(!l.value)throw new y("The transaction's operation value should not be null");if(48!==m.from(l.value.toString(),"base64").length)throw new y("The transaction's operation value should be a 64 bytes base64 random string");if(!n)throw new y("Invalid homeDomains: a home domain must be provided for verification");if("string"==typeof n)"".concat(n," auth")===l.name&&(p=n);else{if(!Array.isArray(n))throw new y("Invalid homeDomains: homeDomains type is ".concat(b(n)," but should be a string or an array"));p=n.find((function(e){return"".concat(e," auth")===l.name}))}if(!p)throw new y("Invalid homeDomains: the transaction's operation key name does not match the expected home domain");var v,S=g(f);try{for(S.s();!(v=S.n()).done;){var k=v.value;if("manageData"!==k.type)throw new y("The transaction has operations that are not of type 'manageData'");if(k.source!==t&&"client_domain"!==k.name)throw new y("The transaction has operations that are unrecognized");if("web_auth_domain"===k.name){if(void 0===k.value)throw new y("'web_auth_domain' operation value should not be null");if(k.value.compare(m.from(o)))throw new y("'web_auth_domain' operation value does not match ".concat(o))}}}catch(e){S.e(e)}finally{S.f()}if(!A(s,t))throw new y("Transaction not signed by server: '".concat(t,"'"));return{tx:s,clientAccountID:d,matchedHomeDomain:p,memo:h}}function O(e,t,r,n,o,i,a){for(var u=x(e,t,r,o.map((function(e){return e.key})),i,a),s=0,c=function(){var e,t=f[l],r=(null===(e=o.find((function(e){return e.key===t})))||void 0===e?void 0:e.weight)||0;s+=r},l=0,f=u;l{"use strict";var r=function(e,t){return t||(t={}),e.split("").forEach((function(e,r){e in t||(t[e]=r)})),t},n={alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",charmap:{0:14,1:8}};n.charmap=r(n.alphabet,n.charmap);var o={alphabet:"0123456789ABCDEFGHJKMNPQRSTVWXYZ",charmap:{O:0,I:1,L:1}};o.charmap=r(o.alphabet,o.charmap);var i={alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",charmap:{}};function a(e){if(this.buf=[],this.shift=8,this.carry=0,e){switch(e.type){case"rfc4648":this.charmap=t.rfc4648.charmap;break;case"crockford":this.charmap=t.crockford.charmap;break;case"base32hex":this.charmap=t.base32hex.charmap;break;default:throw new Error("invalid type")}e.charmap&&(this.charmap=e.charmap)}}function u(e){if(this.buf="",this.shift=3,this.carry=0,e){switch(e.type){case"rfc4648":this.alphabet=t.rfc4648.alphabet;break;case"crockford":this.alphabet=t.crockford.alphabet;break;case"base32hex":this.alphabet=t.base32hex.alphabet;break;default:throw new Error("invalid type")}e.alphabet?this.alphabet=e.alphabet:e.lc&&(this.alphabet=this.alphabet.toLowerCase())}}i.charmap=r(i.alphabet,i.charmap),a.prototype.charmap=n.charmap,a.prototype.write=function(e){var t=this.charmap,r=this.buf,n=this.shift,o=this.carry;return e.toUpperCase().split("").forEach((function(e){if("="!=e){var i=255&t[e];(n-=5)>0?o|=i<>-n),o=i<<(n+=8)&255):(r.push(o|i),n=8,o=0)}})),this.shift=n,this.carry=o,this},a.prototype.finalize=function(e){return e&&this.write(e),8!==this.shift&&0!==this.carry&&(this.buf.push(this.carry),this.shift=8,this.carry=0),this.buf},u.prototype.alphabet=n.alphabet,u.prototype.write=function(e){var t,r,n,o=this.shift,i=this.carry;for(n=0;n>o,this.buf+=this.alphabet[31&t],o>5&&(t=r>>(o-=5),this.buf+=this.alphabet[31&t]),i=r<<(o=5-o),o=8-o;return this.shift=o,this.carry=i,this},u.prototype.finalize=function(e){return e&&this.write(e),3!==this.shift&&(this.buf+=this.alphabet[31&this.carry],this.shift=3,this.carry=0),this.buf},t.encode=function(e,t){return new u(t).finalize(e)},t.decode=function(e,t){return new a(t).finalize(e)},t.Decoder=a,t.Encoder=u,t.charmap=r,t.crockford=o,t.rfc4648=n,t.base32hex=i},7526:(e,t)=>{"use strict";t.byteLength=function(e){var t=u(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,i=u(e),a=i[0],s=i[1],c=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,s)),l=0,f=s>0?a-4:a;for(r=0;r>16&255,c[l++]=t>>8&255,c[l++]=255&t;2===s&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,c[l++]=255&t);1===s&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t);return c},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],a=16383,u=0,c=n-o;uc?c:u+a));1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return i.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)r[a]=i[a],n[i.charCodeAt(a)]=a;function u(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function s(e,t,n){for(var o,i,a=[],u=t;u>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return a.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},1594:function(e,t,r){var n;!function(){"use strict";var o,i=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,a=Math.ceil,u=Math.floor,s="[BigNumber Error] ",c=s+"Number primitive has more than 15 significant digits: ",l=1e14,f=14,p=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],h=1e7,y=1e9;function m(e){var t=0|e;return e>0||e===t?t:t-1}function v(e){for(var t,r,n=1,o=e.length,i=e[0]+"";nc^r?1:-1;for(u=(s=o.length)<(c=i.length)?s:c,a=0;ai[a]^r?1:-1;return s==c?0:s>c^r?1:-1}function b(e,t,r,n){if(er||e!==u(e))throw Error(s+(n||"Argument")+("number"==typeof e?er?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function w(e){var t=e.c.length-1;return m(e.e/f)==t&&e.c[t]%2!=0}function S(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function k(e,t,r){var n,o;if(t<0){for(o=r+".";++t;o+=r);e=o+e}else if(++t>(n=e.length)){for(o=r,t-=n;--t;o+=r);e+=o}else tU?v.c=v.e=null:e.e=10;d/=10,l++);return void(l>U?v.c=v.e=null:(v.e=l,v.c=[e]))}m=String(e)}else{if(!i.test(m=String(e)))return o(v,m,h);v.s=45==m.charCodeAt(0)?(m=m.slice(1),-1):1}(l=m.indexOf("."))>-1&&(m=m.replace(".","")),(d=m.search(/e/i))>0?(l<0&&(l=d),l+=+m.slice(d+1),m=m.substring(0,d)):l<0&&(l=m.length)}else{if(b(t,2,q.length,"Base"),10==t&&K)return $(v=new H(e),C+v.e+1,j);if(m=String(e),h="number"==typeof e){if(0*e!=0)return o(v,m,h,t);if(v.s=1/e<0?(m=m.slice(1),-1):1,H.DEBUG&&m.replace(/^0\.0*|\./,"").length>15)throw Error(c+e)}else v.s=45===m.charCodeAt(0)?(m=m.slice(1),-1):1;for(r=q.slice(0,t),l=d=0,y=m.length;dl){l=y;continue}}else if(!s&&(m==m.toUpperCase()&&(m=m.toLowerCase())||m==m.toLowerCase()&&(m=m.toUpperCase()))){s=!0,d=-1,l=0;continue}return o(v,String(e),h,t)}h=!1,(l=(m=n(m,t,10,v.s)).indexOf("."))>-1?m=m.replace(".",""):l=m.length}for(d=0;48===m.charCodeAt(d);d++);for(y=m.length;48===m.charCodeAt(--y););if(m=m.slice(d,++y)){if(y-=d,h&&H.DEBUG&&y>15&&(e>p||e!==u(e)))throw Error(c+v.s*e);if((l=l-d-1)>U)v.c=v.e=null;else if(l=L)?S(s,a):k(s,a,"0");else if(i=(e=$(new H(e),t,r)).e,u=(s=v(e.c)).length,1==n||2==n&&(t<=i||i<=B)){for(;uu){if(--t>0)for(s+=".";t--;s+="0");}else if((t+=i-u)>0)for(i+1==u&&(s+=".");t--;s+="0");return e.s<0&&o?"-"+s:s}function X(e,t){for(var r,n,o=1,i=new H(e[0]);o=10;o/=10,n++);return(r=n+r*f-1)>U?e.c=e.e=null:r=10;c/=10,o++);if((i=t-o)<0)i+=f,s=t,p=m[h=0],y=u(p/v[o-s-1]%10);else if((h=a((i+1)/f))>=m.length){if(!n)break e;for(;m.length<=h;m.push(0));p=y=0,o=1,s=(i%=f)-f+1}else{for(p=c=m[h],o=1;c>=10;c/=10,o++);y=(s=(i%=f)-f+o)<0?0:u(p/v[o-s-1]%10)}if(n=n||t<0||null!=m[h+1]||(s<0?p:p%v[o-s-1]),n=r<4?(y||n)&&(0==r||r==(e.s<0?3:2)):y>5||5==y&&(4==r||n||6==r&&(i>0?s>0?p/v[o-s]:0:m[h-1])%10&1||r==(e.s<0?8:7)),t<1||!m[0])return m.length=0,n?(t-=e.e+1,m[0]=v[(f-t%f)%f],e.e=-t||0):m[0]=e.e=0,e;if(0==i?(m.length=h,c=1,h--):(m.length=h+1,c=v[f-i],m[h]=s>0?u(p/v[o-s]%v[s])*c:0),n)for(;;){if(0==h){for(i=1,s=m[0];s>=10;s/=10,i++);for(s=m[0]+=c,c=1;s>=10;s/=10,c++);i!=c&&(e.e++,m[0]==l&&(m[0]=1));break}if(m[h]+=c,m[h]!=l)break;m[h--]=0,c=1}for(i=m.length;0===m[--i];m.pop());}e.e>U?e.c=e.e=null:e.e=L?S(t,r):k(t,r,"0"),e.s<0?"-"+t:t)}return H.clone=e,H.ROUND_UP=0,H.ROUND_DOWN=1,H.ROUND_CEIL=2,H.ROUND_FLOOR=3,H.ROUND_HALF_UP=4,H.ROUND_HALF_DOWN=5,H.ROUND_HALF_EVEN=6,H.ROUND_HALF_CEIL=7,H.ROUND_HALF_FLOOR=8,H.EUCLID=9,H.config=H.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(s+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(b(r=e[t],0,y,t),C=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(b(r=e[t],0,8,t),j=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(b(r[0],-y,0,t),b(r[1],0,y,t),B=r[0],L=r[1]):(b(r,-y,y,t),B=-(L=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)b(r[0],-y,-1,t),b(r[1],1,y,t),N=r[0],U=r[1];else{if(b(r,-y,y,t),!r)throw Error(s+t+" cannot be zero: "+r);N=-(U=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(s+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw M=!r,Error(s+"crypto unavailable");M=r}else M=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(b(r=e[t],0,9,t),F=r),e.hasOwnProperty(t="POW_PRECISION")&&(b(r=e[t],0,y,t),D=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(s+t+" not an object: "+r);V=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(s+t+" invalid: "+r);K="0123456789"==r.slice(0,10),q=r}}return{DECIMAL_PLACES:C,ROUNDING_MODE:j,EXPONENTIAL_AT:[B,L],RANGE:[N,U],CRYPTO:M,MODULO_MODE:F,POW_PRECISION:D,FORMAT:V,ALPHABET:q}},H.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!H.DEBUG)return!0;var t,r,n=e.c,o=e.e,i=e.s;e:if("[object Array]"=={}.toString.call(n)){if((1===i||-1===i)&&o>=-y&&o<=y&&o===u(o)){if(0===n[0]){if(0===o&&1===n.length)return!0;break e}if((t=(o+1)%f)<1&&(t+=f),String(n[0]).length==t){for(t=0;t=l||r!==u(r))break e;if(0!==r)return!0}}}else if(null===n&&null===o&&(null===i||1===i||-1===i))return!0;throw Error(s+"Invalid BigNumber: "+e)},H.maximum=H.max=function(){return X(arguments,-1)},H.minimum=H.min=function(){return X(arguments,1)},H.random=(E=9007199254740992,_=Math.random()*E&2097151?function(){return u(Math.random()*E)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,n,o,i,c=0,l=[],p=new H(R);if(null==e?e=C:b(e,0,y),o=a(e/f),M)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(o*=2));c>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[c]=r[0],t[c+1]=r[1]):(l.push(i%1e14),c+=2);c=o/2}else{if(!crypto.randomBytes)throw M=!1,Error(s+"crypto unavailable");for(t=crypto.randomBytes(o*=7);c=9e15?crypto.randomBytes(7).copy(t,c):(l.push(i%1e14),c+=7);c=o/7}if(!M)for(;c=10;i/=10,c++);cr-1&&(null==a[o+1]&&(a[o+1]=0),a[o+1]+=a[o]/r|0,a[o]%=r)}return a.reverse()}return function(n,o,i,a,u){var s,c,l,f,p,d,h,y,m=n.indexOf("."),g=C,b=j;for(m>=0&&(f=D,D=0,n=n.replace(".",""),d=(y=new H(o)).pow(n.length-m),D=f,y.c=t(k(v(d.c),d.e,"0"),10,i,e),y.e=y.c.length),l=f=(h=t(n,o,i,u?(s=q,e):(s=e,q))).length;0==h[--f];h.pop());if(!h[0])return s.charAt(0);if(m<0?--l:(d.c=h,d.e=l,d.s=a,h=(d=r(d,y,g,b,i)).c,p=d.r,l=d.e),m=h[c=l+g+1],f=i/2,p=p||c<0||null!=h[c+1],p=b<4?(null!=m||p)&&(0==b||b==(d.s<0?3:2)):m>f||m==f&&(4==b||p||6==b&&1&h[c-1]||b==(d.s<0?8:7)),c<1||!h[0])n=p?k(s.charAt(1),-g,s.charAt(0)):s.charAt(0);else{if(h.length=c,p)for(--i;++h[--c]>i;)h[c]=0,c||(++l,h=[1].concat(h));for(f=h.length;!h[--f];);for(m=0,n="";m<=f;n+=s.charAt(h[m++]));n=k(n,l,s.charAt(0))}return n}}(),r=function(){function e(e,t,r){var n,o,i,a,u=0,s=e.length,c=t%h,l=t/h|0;for(e=e.slice();s--;)u=((o=c*(i=e[s]%h)+(n=l*i+(a=e[s]/h|0)*c)%h*h+u)/r|0)+(n/h|0)+l*a,e[s]=o%r;return u&&(e=[u].concat(e)),e}function t(e,t,r,n){var o,i;if(r!=n)i=r>n?1:-1;else for(o=i=0;ot[o]?1:-1;break}return i}function r(e,t,r,n){for(var o=0;r--;)e[r]-=o,o=e[r]1;e.splice(0,1));}return function(n,o,i,a,s){var c,p,d,h,y,v,g,b,w,S,k,E,_,T,O,x,A,P=n.s==o.s?1:-1,I=n.c,R=o.c;if(!(I&&I[0]&&R&&R[0]))return new H(n.s&&o.s&&(I?!R||I[0]!=R[0]:R)?I&&0==I[0]||!R?0*P:P/0:NaN);for(w=(b=new H(P)).c=[],P=i+(p=n.e-o.e)+1,s||(s=l,p=m(n.e/f)-m(o.e/f),P=P/f|0),d=0;R[d]==(I[d]||0);d++);if(R[d]>(I[d]||0)&&p--,P<0)w.push(1),h=!0;else{for(T=I.length,x=R.length,d=0,P+=2,(y=u(s/(R[0]+1)))>1&&(R=e(R,y,s),I=e(I,y,s),x=R.length,T=I.length),_=x,k=(S=I.slice(0,x)).length;k=s/2&&O++;do{if(y=0,(c=t(R,S,x,k))<0){if(E=S[0],x!=k&&(E=E*s+(S[1]||0)),(y=u(E/O))>1)for(y>=s&&(y=s-1),g=(v=e(R,y,s)).length,k=S.length;1==t(v,S,g,k);)y--,r(v,x=10;P/=10,d++);$(b,i+(b.e=d+p*f-1)+1,a,h)}else b.e=p,b.r=+h;return b}}(),T=/^(-?)0([xbo])(?=\w[\w.]*$)/i,O=/^([^.]+)\.$/,x=/^\.([^.]+)$/,A=/^-?(Infinity|NaN)$/,P=/^\s*\+(?=[\w.])|^\s+|\s+$/g,o=function(e,t,r,n){var o,i=r?t:t.replace(P,"");if(A.test(i))e.s=isNaN(i)?null:i<0?-1:1;else{if(!r&&(i=i.replace(T,(function(e,t,r){return o="x"==(r=r.toLowerCase())?16:"b"==r?2:8,n&&n!=o?e:t})),n&&(o=n,i=i.replace(O,"$1").replace(x,"0.$1")),t!=i))return new H(i,o);if(H.DEBUG)throw Error(s+"Not a"+(n?" base "+n:"")+" number: "+t);e.s=null}e.c=e.e=null},I.absoluteValue=I.abs=function(){var e=new H(this);return e.s<0&&(e.s=1),e},I.comparedTo=function(e,t){return g(this,new H(e,t))},I.decimalPlaces=I.dp=function(e,t){var r,n,o,i=this;if(null!=e)return b(e,0,y),null==t?t=j:b(t,0,8),$(new H(i),e+i.e+1,t);if(!(r=i.c))return null;if(n=((o=r.length-1)-m(this.e/f))*f,o=r[o])for(;o%10==0;o/=10,n--);return n<0&&(n=0),n},I.dividedBy=I.div=function(e,t){return r(this,new H(e,t),C,j)},I.dividedToIntegerBy=I.idiv=function(e,t){return r(this,new H(e,t),0,1)},I.exponentiatedBy=I.pow=function(e,t){var r,n,o,i,c,l,p,d,h=this;if((e=new H(e)).c&&!e.isInteger())throw Error(s+"Exponent not an integer: "+Q(e));if(null!=t&&(t=new H(t)),c=e.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!e.c||!e.c[0])return d=new H(Math.pow(+Q(h),c?e.s*(2-w(e)):+Q(e))),t?d.mod(t):d;if(l=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new H(NaN);(n=!l&&h.isInteger()&&t.isInteger())&&(h=h.mod(t))}else{if(e.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||c&&h.c[1]>=24e7:h.c[0]<8e13||c&&h.c[0]<=9999975e7)))return i=h.s<0&&w(e)?-0:0,h.e>-1&&(i=1/i),new H(l?1/i:i);D&&(i=a(D/f+2))}for(c?(r=new H(.5),l&&(e.s=1),p=w(e)):p=(o=Math.abs(+Q(e)))%2,d=new H(R);;){if(p){if(!(d=d.times(h)).c)break;i?d.c.length>i&&(d.c.length=i):n&&(d=d.mod(t))}if(o){if(0===(o=u(o/2)))break;p=o%2}else if($(e=e.times(r),e.e+1,1),e.e>14)p=w(e);else{if(0===(o=+Q(e)))break;p=o%2}h=h.times(h),i?h.c&&h.c.length>i&&(h.c.length=i):n&&(h=h.mod(t))}return n?d:(l&&(d=R.div(d)),t?d.mod(t):i?$(d,D,j,undefined):d)},I.integerValue=function(e){var t=new H(this);return null==e?e=j:b(e,0,8),$(t,t.e+1,e)},I.isEqualTo=I.eq=function(e,t){return 0===g(this,new H(e,t))},I.isFinite=function(){return!!this.c},I.isGreaterThan=I.gt=function(e,t){return g(this,new H(e,t))>0},I.isGreaterThanOrEqualTo=I.gte=function(e,t){return 1===(t=g(this,new H(e,t)))||0===t},I.isInteger=function(){return!!this.c&&m(this.e/f)>this.c.length-2},I.isLessThan=I.lt=function(e,t){return g(this,new H(e,t))<0},I.isLessThanOrEqualTo=I.lte=function(e,t){return-1===(t=g(this,new H(e,t)))||0===t},I.isNaN=function(){return!this.s},I.isNegative=function(){return this.s<0},I.isPositive=function(){return this.s>0},I.isZero=function(){return!!this.c&&0==this.c[0]},I.minus=function(e,t){var r,n,o,i,a=this,u=a.s;if(t=(e=new H(e,t)).s,!u||!t)return new H(NaN);if(u!=t)return e.s=-t,a.plus(e);var s=a.e/f,c=e.e/f,p=a.c,d=e.c;if(!s||!c){if(!p||!d)return p?(e.s=-t,e):new H(d?a:NaN);if(!p[0]||!d[0])return d[0]?(e.s=-t,e):new H(p[0]?a:3==j?-0:0)}if(s=m(s),c=m(c),p=p.slice(),u=s-c){for((i=u<0)?(u=-u,o=p):(c=s,o=d),o.reverse(),t=u;t--;o.push(0));o.reverse()}else for(n=(i=(u=p.length)<(t=d.length))?u:t,u=t=0;t0)for(;t--;p[r++]=0);for(t=l-1;n>u;){if(p[--n]=0;){for(r=0,y=E[o]%w,v=E[o]/w|0,i=o+(a=s);i>o;)r=((c=y*(c=k[--a]%w)+(u=v*c+(p=k[a]/w|0)*y)%w*w+g[i]+r)/b|0)+(u/w|0)+v*p,g[i--]=c%b;g[i]=r}return r?++n:g.splice(0,1),G(e,g,n)},I.negated=function(){var e=new H(this);return e.s=-e.s||null,e},I.plus=function(e,t){var r,n=this,o=n.s;if(t=(e=new H(e,t)).s,!o||!t)return new H(NaN);if(o!=t)return e.s=-t,n.minus(e);var i=n.e/f,a=e.e/f,u=n.c,s=e.c;if(!i||!a){if(!u||!s)return new H(o/0);if(!u[0]||!s[0])return s[0]?e:new H(u[0]?n:0*o)}if(i=m(i),a=m(a),u=u.slice(),o=i-a){for(o>0?(a=i,r=s):(o=-o,r=u),r.reverse();o--;r.push(0));r.reverse()}for((o=u.length)-(t=s.length)<0&&(r=s,s=u,u=r,t=o),o=0;t;)o=(u[--t]=u[t]+s[t]+o)/l|0,u[t]=l===u[t]?0:u[t]%l;return o&&(u=[o].concat(u),++a),G(e,u,a)},I.precision=I.sd=function(e,t){var r,n,o,i=this;if(null!=e&&e!==!!e)return b(e,1,y),null==t?t=j:b(t,0,8),$(new H(i),e,t);if(!(r=i.c))return null;if(n=(o=r.length-1)*f+1,o=r[o]){for(;o%10==0;o/=10,n--);for(o=r[0];o>=10;o/=10,n++);}return e&&i.e+1>n&&(n=i.e+1),n},I.shiftedBy=function(e){return b(e,-9007199254740991,p),this.times("1e"+e)},I.squareRoot=I.sqrt=function(){var e,t,n,o,i,a=this,u=a.c,s=a.s,c=a.e,l=C+4,f=new H("0.5");if(1!==s||!u||!u[0])return new H(!s||s<0&&(!u||u[0])?NaN:u?a:1/0);if(0==(s=Math.sqrt(+Q(a)))||s==1/0?(((t=v(u)).length+c)%2==0&&(t+="0"),s=Math.sqrt(+t),c=m((c+1)/2)-(c<0||c%2),n=new H(t=s==1/0?"5e"+c:(t=s.toExponential()).slice(0,t.indexOf("e")+1)+c)):n=new H(s+""),n.c[0])for((s=(c=n.e)+l)<3&&(s=0);;)if(i=n,n=f.times(i.plus(r(a,i,l,1))),v(i.c).slice(0,s)===(t=v(n.c)).slice(0,s)){if(n.e0&&y>0){for(i=y%u||u,f=h.substr(0,i);i0&&(f+=l+h.slice(i)),d&&(f="-"+f)}n=p?f+(r.decimalSeparator||"")+((c=+r.fractionGroupSize)?p.replace(new RegExp("\\d{"+c+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):p):f}return(r.prefix||"")+n+(r.suffix||"")},I.toFraction=function(e){var t,n,o,i,a,u,c,l,p,h,y,m,g=this,b=g.c;if(null!=e&&(!(c=new H(e)).isInteger()&&(c.c||1!==c.s)||c.lt(R)))throw Error(s+"Argument "+(c.isInteger()?"out of range: ":"not an integer: ")+Q(c));if(!b)return new H(g);for(t=new H(R),p=n=new H(R),o=l=new H(R),m=v(b),a=t.e=m.length-g.e-1,t.c[0]=d[(u=a%f)<0?f+u:u],e=!e||c.comparedTo(t)>0?a>0?t:p:c,u=U,U=1/0,c=new H(m),l.c[0]=0;h=r(c,t,0,1),1!=(i=n.plus(h.times(o))).comparedTo(e);)n=o,o=i,p=l.plus(h.times(i=p)),l=i,t=c.minus(h.times(i=t)),c=i;return i=r(e.minus(n),o,0,1),l=l.plus(i.times(p)),n=n.plus(i.times(o)),l.s=p.s=g.s,y=r(p,o,a*=2,j).minus(g).abs().comparedTo(r(l,n,a,j).minus(g).abs())<1?[p,o]:[l,n],U=u,y},I.toNumber=function(){return+Q(this)},I.toPrecision=function(e,t){return null!=e&&b(e,1,y),z(this,e,t,2)},I.toString=function(e){var t,r=this,o=r.s,i=r.e;return null===i?o?(t="Infinity",o<0&&(t="-"+t)):t="NaN":(null==e?t=i<=B||i>=L?S(v(r.c),i):k(v(r.c),i,"0"):10===e&&K?t=k(v((r=$(new H(r),C+i+1,j)).c),r.e,"0"):(b(e,2,q.length,"Base"),t=n(k(v(r.c),i,"0"),10,e,o,!0)),o<0&&r.c[0]&&(t="-"+t)),t},I.valueOf=I.toJSON=function(){return Q(this)},I._isBigNumber=!0,null!=t&&H.set(t),H}(),o.default=o.BigNumber=o,void 0===(n=function(){return o}.call(t,r,t,e))||(e.exports=n)}()},8287:(e,t,r)=>{"use strict";const n=r(7526),o=r(251),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=s,t.SlowBuffer=function(e){+e!=e&&(e=0);return s.alloc(+e)},t.INSPECT_MAX_BYTES=50;const a=2147483647;function u(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return f(e)}return c(e,t,r)}function c(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|y(e,t);let n=u(r);const o=n.write(e,t);o!==r&&(n=n.slice(0,o));return n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(Q(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return p(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Q(e,ArrayBuffer)||e&&Q(e.buffer,ArrayBuffer))return d(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(Q(e,SharedArrayBuffer)||e&&Q(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return s.from(n,t,r);const o=function(e){if(s.isBuffer(e)){const t=0|h(e.length),r=u(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||W(e.length)?u(0):p(e);if("Buffer"===e.type&&Array.isArray(e.data))return p(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function f(e){return l(e),u(e<0?0:0|h(e))}function p(e){const t=e.length<0?0:0|h(e.length),r=u(t);for(let n=0;n=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function y(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Q(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return X(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(o)return n?-1:X(e).length;t=(""+t).toLowerCase(),o=!0}}function m(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return I(this,t,r);case"utf8":case"utf-8":return O(this,t,r);case"ascii":return A(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return T(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function v(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function g(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),W(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=s.from(t,n)),s.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,o){let i,a=1,u=e.length,s=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,u/=2,s/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){let n=-1;for(i=r;iu&&(r=u-s),i=r;i>=0;i--){let r=!0;for(let n=0;no&&(n=o):n=o;const i=t.length;let a;for(n>i/2&&(n=i/2),a=0;a>8,o=r%256,i.push(o),i.push(n);return i}(t,e.length-r),e,r,n)}function T(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function O(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o239?4:t>223?3:t>191?2:1;if(o+a<=r){let r,n,u,s;switch(a){case 1:t<128&&(i=t);break;case 2:r=e[o+1],128==(192&r)&&(s=(31&t)<<6|63&r,s>127&&(i=s));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(s=(15&t)<<12|(63&r)<<6|63&n,s>2047&&(s<55296||s>57343)&&(i=s));break;case 4:r=e[o+1],n=e[o+2],u=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&u)&&(s=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&u,s>65535&&s<1114112&&(i=s))}}null===i?(i=65533,a=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),o+=a}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},s.byteLength=y,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(e+=" ... "),""},i&&(s.prototype[i]=s.prototype.inspect),s.prototype.compare=function(e,t,r,n,o){if(Q(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let i=(o>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0);const u=Math.min(i,a),c=this.slice(n,o),l=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let i=!1;for(;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":case"latin1":case"binary":return k(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function A(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;on)&&(r=n);let o="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function j(e,t,r,n,o,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function B(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function L(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r+7]=i,i>>=8,e[r+6]=i,i>>=8,e[r+5]=i,i>>=8,e[r+4]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function N(e,t,r,n,o,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function M(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,8),o.write(e,t,r,n,52,8),r+8}s.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e+--t],o=1;for(;t>0&&(o*=256);)n+=this[e+--t]*o;return n},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(o)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i=o&&(n-=Math.pow(2,8*t)),n},s.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=t,o=1,i=this[e+--n];for(;n>0&&(o*=256);)i+=this[e+--n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||C(e,4,this.length),o.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||C(e,4,this.length),o.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||C(e,8,this.length),o.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||C(e,8,this.length),o.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){j(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=1,i=0;for(this[t]=255&e;++i>>=0,r>>>=0,!n){j(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=r-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+r},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigUInt64LE=J((function(e,t=0){return B(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),s.prototype.writeBigUInt64BE=J((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),s.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);j(this,e,t,r,n-1,-n)}let o=0,i=1,a=0;for(this[t]=255&e;++o>>=0,!n){const n=Math.pow(2,8*r-1);j(this,e,t,r,n-1,-n)}let o=r-1,i=1,a=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/i|0)-a&255;return t+r},s.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigInt64LE=J((function(e,t=0){return B(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),s.prototype.writeBigInt64BE=J((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),s.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},s.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},s.prototype.writeDoubleLE=function(e,t,r){return M(this,e,t,!0,r)},s.prototype.writeDoubleBE=function(e,t,r){return M(this,e,t,!1,r)},s.prototype.copy=function(e,t,r,n){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function q(e,t,r,n,o,i){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new F.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){K(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||H(t,e.length-(r+1))}(n,o,i)}function K(e,t){if("number"!=typeof e)throw new F.ERR_INVALID_ARG_TYPE(t,"number",e)}function H(e,t,r){if(Math.floor(e)!==e)throw K(e,r),new F.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new F.ERR_BUFFER_OUT_OF_BOUNDS;throw new F.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}D("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),D("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),D("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=V(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=V(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const z=/[^+/0-9A-Za-z-_]/g;function X(e,t){let r;t=t||1/0;const n=e.length;let o=null;const i=[];for(let a=0;a55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function G(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function $(e,t,r,n){let o;for(o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function Q(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function W(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let o=0;o<16;++o)t[n+o]=e[r]+e[o]}return t}();function J(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},251:(e,t)=>{t.read=function(e,t,r,n,o){var i,a,u=8*o-n-1,s=(1<>1,l=-7,f=r?o-1:0,p=r?-1:1,d=e[t+f];for(f+=p,i=d&(1<<-l)-1,d>>=-l,l+=u;l>0;i=256*i+e[t+f],f+=p,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=p,l-=8);if(0===i)i=1-c;else{if(i===s)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),i-=c}return(d?-1:1)*a*Math.pow(2,i-n)},t.write=function(e,t,r,n,o,i){var a,u,s,c=8*i-o-1,l=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,h=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(u=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(s=Math.pow(2,-a))<1&&(a--,s*=2),(t+=a+f>=1?p/s:p*Math.pow(2,1-f))*s>=2&&(a++,s/=2),a+f>=l?(u=0,a=l):a+f>=1?(u=(t*s-1)*Math.pow(2,o),a+=f):(u=t*Math.pow(2,f-1)*Math.pow(2,o),a=0));o>=8;e[r+d]=255&u,d+=h,u/=256,o-=8);for(a=a<0;e[r+d]=255&a,d+=h,a/=256,c-=8);e[r+d-h]|=128*y}},6698:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},3209:(e,t,r)=>{"use strict";var n=65536,o=4294967295;var i=r(2861).Buffer,a=r.g.crypto||r.g.msCrypto;a&&a.getRandomValues?e.exports=function(e,t){if(e>o)throw new RangeError("requested too many random bytes");var r=i.allocUnsafe(e);if(e>0)if(e>n)for(var u=0;u{var n=r(8287),o=n.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return o(e,t,r)}o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=a),a.prototype=Object.create(o.prototype),i(o,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=o(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},392:(e,t,r)=>{var n=r(2861).Buffer;function o(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}o.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=n.from(e,t));for(var r=this._block,o=this._blockSize,i=e.length,a=this._len,u=0;u=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,o=(r-n)/4294967296;this._block.writeUInt32BE(o,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var i=this._hash();return e?i.toString(e):i},o.prototype._update=function(){throw new Error("_update must be implemented by subclass")},e.exports=o},2802:(e,t,r)=>{var n=e.exports=function(e){e=e.toLowerCase();var t=n[e];if(!t)throw new Error(e+" is not supported (we accept pull requests)");return new t};n.sha=r(7816),n.sha1=r(3737),n.sha224=r(6710),n.sha256=r(4107),n.sha384=r(2827),n.sha512=r(2890)},7816:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1518500249,1859775393,-1894007588,-899497514],u=new Array(80);function s(){this.init(),this._w=u,o.call(this,64,56)}function c(e){return e<<30|e>>>2}function l(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(s,o),s.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},s.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,u=0|this._d,s=0|this._e,f=0;f<16;++f)r[f]=e.readInt32BE(4*f);for(;f<80;++f)r[f]=r[f-3]^r[f-8]^r[f-14]^r[f-16];for(var p=0;p<80;++p){var d=~~(p/20),h=0|((t=n)<<5|t>>>27)+l(d,o,i,u)+s+r[p]+a[d];s=u,u=i,i=c(o),o=n,n=h}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=u+this._d|0,this._e=s+this._e|0},s.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},e.exports=s},3737:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1518500249,1859775393,-1894007588,-899497514],u=new Array(80);function s(){this.init(),this._w=u,o.call(this,64,56)}function c(e){return e<<5|e>>>27}function l(e){return e<<30|e>>>2}function f(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(s,o),s.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},s.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,u=0|this._d,s=0|this._e,p=0;p<16;++p)r[p]=e.readInt32BE(4*p);for(;p<80;++p)r[p]=(t=r[p-3]^r[p-8]^r[p-14]^r[p-16])<<1|t>>>31;for(var d=0;d<80;++d){var h=~~(d/20),y=c(n)+f(h,o,i,u)+s+r[d]+a[h]|0;s=u,u=i,i=l(o),o=n,n=y}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=u+this._d|0,this._e=s+this._e|0},s.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},e.exports=s},6710:(e,t,r)=>{var n=r(6698),o=r(4107),i=r(392),a=r(2861).Buffer,u=new Array(64);function s(){this.init(),this._w=u,i.call(this,64,56)}n(s,o),s.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},s.prototype._hash=function(){var e=a.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e},e.exports=s},4107:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],u=new Array(64);function s(){this.init(),this._w=u,o.call(this,64,56)}function c(e,t,r){return r^e&(t^r)}function l(e,t,r){return e&t|r&(e|t)}function f(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function p(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function d(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}n(s,o),s.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},s.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,u=0|this._d,s=0|this._e,h=0|this._f,y=0|this._g,m=0|this._h,v=0;v<16;++v)r[v]=e.readInt32BE(4*v);for(;v<64;++v)r[v]=0|(((t=r[v-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+r[v-7]+d(r[v-15])+r[v-16];for(var g=0;g<64;++g){var b=m+p(s)+c(s,h,y)+a[g]+r[g]|0,w=f(n)+l(n,o,i)|0;m=y,y=h,h=s,s=u+b|0,u=i,i=o,o=n,n=b+w|0}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=u+this._d|0,this._e=s+this._e|0,this._f=h+this._f|0,this._g=y+this._g|0,this._h=m+this._h|0},s.prototype._hash=function(){var e=i.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},e.exports=s},2827:(e,t,r)=>{var n=r(6698),o=r(2890),i=r(392),a=r(2861).Buffer,u=new Array(160);function s(){this.init(),this._w=u,i.call(this,128,112)}n(s,o),s.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},s.prototype._hash=function(){var e=a.allocUnsafe(48);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},e.exports=s},2890:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],u=new Array(160);function s(){this.init(),this._w=u,o.call(this,128,112)}function c(e,t,r){return r^e&(t^r)}function l(e,t,r){return e&t|r&(e|t)}function f(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function p(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function d(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function h(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function y(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function m(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function v(e,t){return e>>>0>>0?1:0}n(s,o),s.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},s.prototype._update=function(e){for(var t=this._w,r=0|this._ah,n=0|this._bh,o=0|this._ch,i=0|this._dh,u=0|this._eh,s=0|this._fh,g=0|this._gh,b=0|this._hh,w=0|this._al,S=0|this._bl,k=0|this._cl,E=0|this._dl,_=0|this._el,T=0|this._fl,O=0|this._gl,x=0|this._hl,A=0;A<32;A+=2)t[A]=e.readInt32BE(4*A),t[A+1]=e.readInt32BE(4*A+4);for(;A<160;A+=2){var P=t[A-30],I=t[A-30+1],R=d(P,I),C=h(I,P),j=y(P=t[A-4],I=t[A-4+1]),B=m(I,P),L=t[A-14],N=t[A-14+1],U=t[A-32],M=t[A-32+1],F=C+N|0,D=R+L+v(F,C)|0;D=(D=D+j+v(F=F+B|0,B)|0)+U+v(F=F+M|0,M)|0,t[A]=D,t[A+1]=F}for(var V=0;V<160;V+=2){D=t[V],F=t[V+1];var q=l(r,n,o),K=l(w,S,k),H=f(r,w),z=f(w,r),X=p(u,_),G=p(_,u),$=a[V],Q=a[V+1],W=c(u,s,g),Y=c(_,T,O),J=x+G|0,Z=b+X+v(J,x)|0;Z=(Z=(Z=Z+W+v(J=J+Y|0,Y)|0)+$+v(J=J+Q|0,Q)|0)+D+v(J=J+F|0,F)|0;var ee=z+K|0,te=H+q+v(ee,z)|0;b=g,x=O,g=s,O=T,s=u,T=_,u=i+Z+v(_=E+J|0,E)|0,i=o,E=k,o=n,k=S,n=r,S=w,r=Z+te+v(w=J+ee|0,J)|0}this._al=this._al+w|0,this._bl=this._bl+S|0,this._cl=this._cl+k|0,this._dl=this._dl+E|0,this._el=this._el+_|0,this._fl=this._fl+T|0,this._gl=this._gl+O|0,this._hl=this._hl+x|0,this._ah=this._ah+r+v(this._al,w)|0,this._bh=this._bh+n+v(this._bl,S)|0,this._ch=this._ch+o+v(this._cl,k)|0,this._dh=this._dh+i+v(this._dl,E)|0,this._eh=this._eh+u+v(this._el,_)|0,this._fh=this._fh+s+v(this._fl,T)|0,this._gh=this._gh+g+v(this._gl,O)|0,this._hh=this._hh+b+v(this._hl,x)|0},s.prototype._hash=function(){var e=i.allocUnsafe(64);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},e.exports=s},1293:(e,t,r)=>{var n=r(5546),o=r(2708);e.exports={parse:function(e){var t=n.parse(e.toString());return o.compile(t)}}},2708:e=>{"use strict";e.exports={compile:function(e){var t=[],r=[],n="",o=Object.create(null),i=o;return function(e){for(var t,r=0;r-1&&a("Cannot redefine existing key '"+s+"'.",o,i),(c=c[f])instanceof Array&&c.length&&l-1?'"'+e+'"':e}}}},5546:e=>{e.exports=function(){function e(e,t,r,n,o,i){this.message=e,this.expected=t,this.found=r,this.offset=n,this.line=o,this.column=i,this.name="SyntaxError"}return function(e,t){function r(){this.constructor=e}r.prototype=t.prototype,e.prototype=new r}(e,Error),{SyntaxError:e,parse:function(t){var r,n=arguments.length>1?arguments[1]:{},o={},i={start:Bt},a=Bt,u=function(){return pr},s=o,c="#",l={type:"literal",value:"#",description:'"#"'},f=void 0,p={type:"any",description:"any character"},d="[",h={type:"literal",value:"[",description:'"["'},y="]",m={type:"literal",value:"]",description:'"]"'},v=function(e){dr(hr("ObjectPath",e,Pt,It))},g=function(e){dr(hr("ArrayPath",e,Pt,It))},b=function(e,t){return e.concat(t)},w=function(e){return[e]},S=function(e){return e},k=".",E={type:"literal",value:".",description:'"."'},_="=",T={type:"literal",value:"=",description:'"="'},O=function(e,t){dr(hr("Assign",t,Pt,It,e))},x=function(e){return e.join("")},A=function(e){return e.value},P='"""',I={type:"literal",value:'"""',description:'"\\"\\"\\""'},R=null,C=function(e){return hr("String",e.join(""),Pt,It)},j='"',B={type:"literal",value:'"',description:'"\\""'},L="'''",N={type:"literal",value:"'''",description:"\"'''\""},U="'",M={type:"literal",value:"'",description:'"\'"'},F=function(e){return e},D=function(e){return e},V="\\",q={type:"literal",value:"\\",description:'"\\\\"'},K=function(){return""},H="e",z={type:"literal",value:"e",description:'"e"'},X="E",G={type:"literal",value:"E",description:'"E"'},$=function(e,t){return hr("Float",parseFloat(e+"e"+t),Pt,It)},Q=function(e){return hr("Float",parseFloat(e),Pt,It)},W="+",Y={type:"literal",value:"+",description:'"+"'},J=function(e){return e.join("")},Z="-",ee={type:"literal",value:"-",description:'"-"'},te=function(e){return"-"+e.join("")},re=function(e){return hr("Integer",parseInt(e,10),Pt,It)},ne="true",oe={type:"literal",value:"true",description:'"true"'},ie=function(){return hr("Boolean",!0,Pt,It)},ae="false",ue={type:"literal",value:"false",description:'"false"'},se=function(){return hr("Boolean",!1,Pt,It)},ce=function(){return hr("Array",[],Pt,It)},le=function(e){return hr("Array",e?[e]:[],Pt,It)},fe=function(e){return hr("Array",e,Pt,It)},pe=function(e,t){return hr("Array",e.concat(t),Pt,It)},de=function(e){return e},he=",",ye={type:"literal",value:",",description:'","'},me="{",ve={type:"literal",value:"{",description:'"{"'},ge="}",be={type:"literal",value:"}",description:'"}"'},we=function(e){return hr("InlineTable",e,Pt,It)},Se=function(e,t){return hr("InlineTableValue",t,Pt,It,e)},ke=function(e){return"."+e},Ee=function(e){return e.join("")},_e=":",Te={type:"literal",value:":",description:'":"'},Oe=function(e){return e.join("")},xe="T",Ae={type:"literal",value:"T",description:'"T"'},Pe="Z",Ie={type:"literal",value:"Z",description:'"Z"'},Re=function(e,t){return hr("Date",new Date(e+"T"+t+"Z"),Pt,It)},Ce=function(e,t){return hr("Date",new Date(e+"T"+t),Pt,It)},je=/^[ \t]/,Be={type:"class",value:"[ \\t]",description:"[ \\t]"},Le="\n",Ne={type:"literal",value:"\n",description:'"\\n"'},Ue="\r",Me={type:"literal",value:"\r",description:'"\\r"'},Fe=/^[0-9a-f]/i,De={type:"class",value:"[0-9a-f]i",description:"[0-9a-f]i"},Ve=/^[0-9]/,qe={type:"class",value:"[0-9]",description:"[0-9]"},Ke="_",He={type:"literal",value:"_",description:'"_"'},ze=function(){return""},Xe=/^[A-Za-z0-9_\-]/,Ge={type:"class",value:"[A-Za-z0-9_\\-]",description:"[A-Za-z0-9_\\-]"},$e=function(e){return e.join("")},Qe='\\"',We={type:"literal",value:'\\"',description:'"\\\\\\""'},Ye=function(){return'"'},Je="\\\\",Ze={type:"literal",value:"\\\\",description:'"\\\\\\\\"'},et=function(){return"\\"},tt="\\b",rt={type:"literal",value:"\\b",description:'"\\\\b"'},nt=function(){return"\b"},ot="\\t",it={type:"literal",value:"\\t",description:'"\\\\t"'},at=function(){return"\t"},ut="\\n",st={type:"literal",value:"\\n",description:'"\\\\n"'},ct=function(){return"\n"},lt="\\f",ft={type:"literal",value:"\\f",description:'"\\\\f"'},pt=function(){return"\f"},dt="\\r",ht={type:"literal",value:"\\r",description:'"\\\\r"'},yt=function(){return"\r"},mt="\\U",vt={type:"literal",value:"\\U",description:'"\\\\U"'},gt=function(e){return function(e,t,r){var n=parseInt("0x"+e);if(!(!isFinite(n)||Math.floor(n)!=n||n<0||n>1114111||n>55295&&n<57344))return function(){var e,t,r=16384,n=[],o=-1,i=arguments.length;if(!i)return"";var a="";for(;++o>10),t=u%1024+56320,n.push(e,t)),(o+1==i||n.length>r)&&(a+=String.fromCharCode.apply(null,n),n.length=0)}return a}(n);!function(e,t,r){var n=new Error(e);throw n.line=t,n.column=r,n}("Invalid Unicode escape code: "+e,t,r)}(e.join(""))},bt="\\u",wt={type:"literal",value:"\\u",description:'"\\\\u"'},St=0,kt=0,Et=0,_t={line:1,column:1,seenCR:!1},Tt=0,Ot=[],xt=0,At={};if("startRule"in n){if(!(n.startRule in i))throw new Error("Can't start parsing from rule \""+n.startRule+'".');a=i[n.startRule]}function Pt(){return Rt(kt).line}function It(){return Rt(kt).column}function Rt(e){return Et!==e&&(Et>e&&(Et=0,_t={line:1,column:1,seenCR:!1}),function(e,r,n){var o,i;for(o=r;oTt&&(Tt=St,Ot=[]),Ot.push(e))}function jt(r,n,o){var i=Rt(o),a=ot.description?1:0}));t1?n.slice(0,-1).join(", ")+" or "+n[e.length-1]:n[0])+" but "+(t?'"'+function(e){function t(e){return e.charCodeAt(0).toString(16).toUpperCase()}return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E\x0F]/g,(function(e){return"\\x0"+t(e)})).replace(/[\x10-\x1F\x80-\xFF]/g,(function(e){return"\\x"+t(e)})).replace(/[\u0180-\u0FFF]/g,(function(e){return"\\u0"+t(e)})).replace(/[\u1080-\uFFFF]/g,(function(e){return"\\u"+t(e)}))}(t)+'"':"end of input")+" found."}(n,a),n,a,o,i.line,i.column)}function Bt(){var e,t,r,n=49*St+0,i=At[n];if(i)return St=i.nextPos,i.result;for(e=St,t=[],r=Lt();r!==o;)t.push(r),r=Lt();return t!==o&&(kt=e,t=u()),e=t,At[n]={nextPos:St,result:e},e}function Lt(){var e,r,n,i,a,u,c,l=49*St+1,f=At[l];if(f)return St=f.nextPos,f.result;for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if(n=function(){var e,r=49*St+2,n=At[r];if(n)return St=n.nextPos,n.result;e=Nt(),e===o&&(e=function(){var e,r,n,i,a,u,c=49*St+4,l=At[c];if(l)return St=l.nextPos,l.result;e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h));if(r!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o)if((i=Ut())!==o){for(a=[],u=nr();u!==o;)a.push(u),u=nr();a!==o?(93===t.charCodeAt(St)?(u=y,St++):(u=o,0===xt&&Ct(m)),u!==o?(kt=e,e=r=v(i)):(St=e,e=s)):(St=e,e=s)}else St=e,e=s;else St=e,e=s}else St=e,e=s;return At[c]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,u,c,l,f=49*St+5,p=At[f];if(p)return St=p.nextPos,p.result;e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h));if(r!==o)if(91===t.charCodeAt(St)?(n=d,St++):(n=o,0===xt&&Ct(h)),n!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if((a=Ut())!==o){for(u=[],c=nr();c!==o;)u.push(c),c=nr();u!==o?(93===t.charCodeAt(St)?(c=y,St++):(c=o,0===xt&&Ct(m)),c!==o?(93===t.charCodeAt(St)?(l=y,St++):(l=o,0===xt&&Ct(m)),l!==o?(kt=e,e=r=g(a)):(St=e,e=s)):(St=e,e=s)):(St=e,e=s)}else St=e,e=s;else St=e,e=s}else St=e,e=s;else St=e,e=s;return At[f]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,u,c=49*St+9,l=At[c];if(l)return St=l.nextPos,l.result;if(e=St,r=Dt(),r!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o)if(61===t.charCodeAt(St)?(i=_,St++):(i=o,0===xt&&Ct(T)),i!==o){for(a=[],u=nr();u!==o;)a.push(u),u=nr();a!==o&&(u=qt())!==o?(kt=e,e=r=O(r,u)):(St=e,e=s)}else St=e,e=s;else St=e,e=s}else St=e,e=s;if(e===o)if(e=St,(r=Vt())!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o)if(61===t.charCodeAt(St)?(i=_,St++):(i=o,0===xt&&Ct(T)),i!==o){for(a=[],u=nr();u!==o;)a.push(u),u=nr();a!==o&&(u=qt())!==o?(kt=e,e=r=O(r,u)):(St=e,e=s)}else St=e,e=s;else St=e,e=s}else St=e,e=s;return At[c]={nextPos:St,result:e},e}())));return At[r]={nextPos:St,result:e},e}(),n!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o){for(a=[],u=Nt();u!==o;)a.push(u),u=Nt();if(a!==o){if(u=[],(c=or())!==o)for(;c!==o;)u.push(c),c=or();else u=s;u===o&&(u=ar()),u!==o?e=r=[r,n,i,a,u]:(St=e,e=s)}else St=e,e=s}else St=e,e=s}else St=e,e=s;else St=e,e=s;if(e===o){if(e=St,r=[],(n=nr())!==o)for(;n!==o;)r.push(n),n=nr();else r=s;if(r!==o){if(n=[],(i=or())!==o)for(;i!==o;)n.push(i),i=or();else n=s;n===o&&(n=ar()),n!==o?e=r=[r,n]:(St=e,e=s)}else St=e,e=s;e===o&&(e=or())}return At[l]={nextPos:St,result:e},e}function Nt(){var e,r,n,i,a,u,d=49*St+3,h=At[d];if(h)return St=h.nextPos,h.result;if(e=St,35===t.charCodeAt(St)?(r=c,St++):(r=o,0===xt&&Ct(l)),r!==o){for(n=[],i=St,a=St,xt++,(u=or())===o&&(u=ar()),xt--,u===o?a=f:(St=a,a=s),a!==o?(t.length>St?(u=t.charAt(St),St++):(u=o,0===xt&&Ct(p)),u!==o?i=a=[a,u]:(St=i,i=s)):(St=i,i=s);i!==o;)n.push(i),i=St,a=St,xt++,(u=or())===o&&(u=ar()),xt--,u===o?a=f:(St=a,a=s),a!==o?(t.length>St?(u=t.charAt(St),St++):(u=o,0===xt&&Ct(p)),u!==o?i=a=[a,u]:(St=i,i=s)):(St=i,i=s);n!==o?e=r=[r,n]:(St=e,e=s)}else St=e,e=s;return At[d]={nextPos:St,result:e},e}function Ut(){var e,t,r,n=49*St+6,i=At[n];if(i)return St=i.nextPos,i.result;if(e=St,t=[],(r=Ft())!==o)for(;r!==o;)t.push(r),r=Ft();else t=s;return t!==o&&(r=Mt())!==o?(kt=e,e=t=b(t,r)):(St=e,e=s),e===o&&(e=St,(t=Mt())!==o&&(kt=e,t=w(t)),e=t),At[n]={nextPos:St,result:e},e}function Mt(){var e,t,r,n,i,a=49*St+7,u=At[a];if(u)return St=u.nextPos,u.result;for(e=St,t=[],r=nr();r!==o;)t.push(r),r=nr();if(t!==o)if((r=Dt())!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();n!==o?(kt=e,e=t=S(r)):(St=e,e=s)}else St=e,e=s;else St=e,e=s;if(e===o){for(e=St,t=[],r=nr();r!==o;)t.push(r),r=nr();if(t!==o)if((r=Vt())!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();n!==o?(kt=e,e=t=S(r)):(St=e,e=s)}else St=e,e=s;else St=e,e=s}return At[a]={nextPos:St,result:e},e}function Ft(){var e,r,n,i,a,u,c,l=49*St+8,f=At[l];if(f)return St=f.nextPos,f.result;for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Dt())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(46===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&Ct(E)),a!==o){for(u=[],c=nr();c!==o;)u.push(c),c=nr();u!==o?(kt=e,e=r=S(n)):(St=e,e=s)}else St=e,e=s;else St=e,e=s}else St=e,e=s;else St=e,e=s;if(e===o){for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Vt())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(46===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&Ct(E)),a!==o){for(u=[],c=nr();c!==o;)u.push(c),c=nr();u!==o?(kt=e,e=r=S(n)):(St=e,e=s)}else St=e,e=s;else St=e,e=s}else St=e,e=s;else St=e,e=s}return At[l]={nextPos:St,result:e},e}function Dt(){var e,t,r,n=49*St+10,i=At[n];if(i)return St=i.nextPos,i.result;if(e=St,t=[],(r=cr())!==o)for(;r!==o;)t.push(r),r=cr();else t=s;return t!==o&&(kt=e,t=x(t)),e=t,At[n]={nextPos:St,result:e},e}function Vt(){var e,t,r=49*St+11,n=At[r];return n?(St=n.nextPos,n.result):(e=St,(t=Kt())!==o&&(kt=e,t=A(t)),(e=t)===o&&(e=St,(t=Ht())!==o&&(kt=e,t=A(t)),e=t),At[r]={nextPos:St,result:e},e)}function qt(){var e,r=49*St+12,n=At[r];return n?(St=n.nextPos,n.result):(e=function(){var e,r=49*St+13,n=At[r];if(n)return St=n.nextPos,n.result;e=function(){var e,r,n,i,a,u=49*St+14,c=At[u];if(c)return St=c.nextPos,c.result;e=St,t.substr(St,3)===P?(r=P,St+=3):(r=o,0===xt&&Ct(I));if(r!==o)if((n=or())===o&&(n=R),n!==o){for(i=[],a=Gt();a!==o;)i.push(a),a=Gt();i!==o?(t.substr(St,3)===P?(a=P,St+=3):(a=o,0===xt&&Ct(I)),a!==o?(kt=e,e=r=C(i)):(St=e,e=s)):(St=e,e=s)}else St=e,e=s;else St=e,e=s;return At[u]={nextPos:St,result:e},e}(),e===o&&(e=Kt())===o&&(e=function(){var e,r,n,i,a,u=49*St+16,c=At[u];if(c)return St=c.nextPos,c.result;e=St,t.substr(St,3)===L?(r=L,St+=3):(r=o,0===xt&&Ct(N));if(r!==o)if((n=or())===o&&(n=R),n!==o){for(i=[],a=$t();a!==o;)i.push(a),a=$t();i!==o?(t.substr(St,3)===L?(a=L,St+=3):(a=o,0===xt&&Ct(N)),a!==o?(kt=e,e=r=C(i)):(St=e,e=s)):(St=e,e=s)}else St=e,e=s;else St=e,e=s;return At[u]={nextPos:St,result:e},e}(),e===o&&(e=Ht()));return At[r]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,u=49*St+38,c=At[u];if(c)return St=c.nextPos,c.result;e=St,(r=rr())!==o?(84===t.charCodeAt(St)?(n=xe,St++):(n=o,0===xt&&Ct(Ae)),n!==o?(i=function(){var e,r,n,i,a,u,c,l,f,p,d,h=49*St+36,y=At[h];if(y)return St=y.nextPos,y.result;e=St,r=St,n=sr(),n!==o&&(i=sr())!==o?(58===t.charCodeAt(St)?(a=_e,St++):(a=o,0===xt&&Ct(Te)),a!==o&&(u=sr())!==o&&(c=sr())!==o?(58===t.charCodeAt(St)?(l=_e,St++):(l=o,0===xt&&Ct(Te)),l!==o&&(f=sr())!==o&&(p=sr())!==o?((d=tr())===o&&(d=R),d!==o?r=n=[n,i,a,u,c,l,f,p,d]:(St=r,r=s)):(St=r,r=s)):(St=r,r=s)):(St=r,r=s);r!==o&&(kt=e,r=Oe(r));return e=r,At[h]={nextPos:St,result:e},e}(),i!==o?(90===t.charCodeAt(St)?(a=Pe,St++):(a=o,0===xt&&Ct(Ie)),a!==o?(kt=e,e=r=Re(r,i)):(St=e,e=s)):(St=e,e=s)):(St=e,e=s)):(St=e,e=s);e===o&&(e=St,(r=rr())!==o?(84===t.charCodeAt(St)?(n=xe,St++):(n=o,0===xt&&Ct(Ae)),n!==o?(i=function(){var e,r,n,i,a,u,c,l,f,p,d,h,y,m,v,g,b,w=49*St+37,S=At[w];if(S)return St=S.nextPos,S.result;e=St,r=St,n=sr(),n!==o&&(i=sr())!==o?(58===t.charCodeAt(St)?(a=_e,St++):(a=o,0===xt&&Ct(Te)),a!==o&&(u=sr())!==o&&(c=sr())!==o?(58===t.charCodeAt(St)?(l=_e,St++):(l=o,0===xt&&Ct(Te)),l!==o&&(f=sr())!==o&&(p=sr())!==o?((d=tr())===o&&(d=R),d!==o?(45===t.charCodeAt(St)?(h=Z,St++):(h=o,0===xt&&Ct(ee)),h===o&&(43===t.charCodeAt(St)?(h=W,St++):(h=o,0===xt&&Ct(Y))),h!==o&&(y=sr())!==o&&(m=sr())!==o?(58===t.charCodeAt(St)?(v=_e,St++):(v=o,0===xt&&Ct(Te)),v!==o&&(g=sr())!==o&&(b=sr())!==o?r=n=[n,i,a,u,c,l,f,p,d,h,y,m,v,g,b]:(St=r,r=s)):(St=r,r=s)):(St=r,r=s)):(St=r,r=s)):(St=r,r=s)):(St=r,r=s);r!==o&&(kt=e,r=Oe(r));return e=r,At[w]={nextPos:St,result:e},e}(),i!==o?(kt=e,e=r=Ce(r,i)):(St=e,e=s)):(St=e,e=s)):(St=e,e=s));return At[u]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a=49*St+23,u=At[a];if(u)return St=u.nextPos,u.result;e=St,(r=Qt())===o&&(r=Wt());r!==o?(101===t.charCodeAt(St)?(n=H,St++):(n=o,0===xt&&Ct(z)),n===o&&(69===t.charCodeAt(St)?(n=X,St++):(n=o,0===xt&&Ct(G))),n!==o&&(i=Wt())!==o?(kt=e,e=r=$(r,i)):(St=e,e=s)):(St=e,e=s);e===o&&(e=St,(r=Qt())!==o&&(kt=e,r=Q(r)),e=r);return At[a]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,t,r=49*St+25,n=At[r];if(n)return St=n.nextPos,n.result;e=St,(t=Wt())!==o&&(kt=e,t=re(t));return e=t,At[r]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n=49*St+27,i=At[n];if(i)return St=i.nextPos,i.result;e=St,t.substr(St,4)===ne?(r=ne,St+=4):(r=o,0===xt&&Ct(oe));r!==o&&(kt=e,r=ie());e=r,e===o&&(e=St,t.substr(St,5)===ae?(r=ae,St+=5):(r=o,0===xt&&Ct(ue)),r!==o&&(kt=e,r=se()),e=r);return At[n]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,u=49*St+28,c=At[u];if(c)return St=c.nextPos,c.result;e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h));if(r!==o){for(n=[],i=Zt();i!==o;)n.push(i),i=Zt();n!==o?(93===t.charCodeAt(St)?(i=y,St++):(i=o,0===xt&&Ct(m)),i!==o?(kt=e,e=r=ce()):(St=e,e=s)):(St=e,e=s)}else St=e,e=s;if(e===o&&(e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h)),r!==o?((n=Yt())===o&&(n=R),n!==o?(93===t.charCodeAt(St)?(i=y,St++):(i=o,0===xt&&Ct(m)),i!==o?(kt=e,e=r=le(n)):(St=e,e=s)):(St=e,e=s)):(St=e,e=s),e===o)){if(e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h)),r!==o){if(n=[],(i=Jt())!==o)for(;i!==o;)n.push(i),i=Jt();else n=s;n!==o?(93===t.charCodeAt(St)?(i=y,St++):(i=o,0===xt&&Ct(m)),i!==o?(kt=e,e=r=fe(n)):(St=e,e=s)):(St=e,e=s)}else St=e,e=s;if(e===o)if(e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h)),r!==o){if(n=[],(i=Jt())!==o)for(;i!==o;)n.push(i),i=Jt();else n=s;n!==o&&(i=Yt())!==o?(93===t.charCodeAt(St)?(a=y,St++):(a=o,0===xt&&Ct(m)),a!==o?(kt=e,e=r=pe(n,i)):(St=e,e=s)):(St=e,e=s)}else St=e,e=s}return At[u]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,u,c=49*St+32,l=At[c];if(l)return St=l.nextPos,l.result;e=St,123===t.charCodeAt(St)?(r=me,St++):(r=o,0===xt&&Ct(ve));if(r!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o){for(i=[],a=er();a!==o;)i.push(a),a=er();if(i!==o){for(a=[],u=nr();u!==o;)a.push(u),u=nr();a!==o?(125===t.charCodeAt(St)?(u=ge,St++):(u=o,0===xt&&Ct(be)),u!==o?(kt=e,e=r=we(i)):(St=e,e=s)):(St=e,e=s)}else St=e,e=s}else St=e,e=s}else St=e,e=s;return At[c]={nextPos:St,result:e},e}())))))),At[r]={nextPos:St,result:e},e)}function Kt(){var e,r,n,i,a=49*St+15,u=At[a];if(u)return St=u.nextPos,u.result;if(e=St,34===t.charCodeAt(St)?(r=j,St++):(r=o,0===xt&&Ct(B)),r!==o){for(n=[],i=zt();i!==o;)n.push(i),i=zt();n!==o?(34===t.charCodeAt(St)?(i=j,St++):(i=o,0===xt&&Ct(B)),i!==o?(kt=e,e=r=C(n)):(St=e,e=s)):(St=e,e=s)}else St=e,e=s;return At[a]={nextPos:St,result:e},e}function Ht(){var e,r,n,i,a=49*St+17,u=At[a];if(u)return St=u.nextPos,u.result;if(e=St,39===t.charCodeAt(St)?(r=U,St++):(r=o,0===xt&&Ct(M)),r!==o){for(n=[],i=Xt();i!==o;)n.push(i),i=Xt();n!==o?(39===t.charCodeAt(St)?(i=U,St++):(i=o,0===xt&&Ct(M)),i!==o?(kt=e,e=r=C(n)):(St=e,e=s)):(St=e,e=s)}else St=e,e=s;return At[a]={nextPos:St,result:e},e}function zt(){var e,r,n,i=49*St+18,a=At[i];return a?(St=a.nextPos,a.result):((e=fr())===o&&(e=St,r=St,xt++,34===t.charCodeAt(St)?(n=j,St++):(n=o,0===xt&&Ct(B)),xt--,n===o?r=f:(St=r,r=s),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&Ct(p)),n!==o?(kt=e,e=r=F(n)):(St=e,e=s)):(St=e,e=s)),At[i]={nextPos:St,result:e},e)}function Xt(){var e,r,n,i=49*St+19,a=At[i];return a?(St=a.nextPos,a.result):(e=St,r=St,xt++,39===t.charCodeAt(St)?(n=U,St++):(n=o,0===xt&&Ct(M)),xt--,n===o?r=f:(St=r,r=s),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&Ct(p)),n!==o?(kt=e,e=r=F(n)):(St=e,e=s)):(St=e,e=s),At[i]={nextPos:St,result:e},e)}function Gt(){var e,r,n,i=49*St+20,a=At[i];return a?(St=a.nextPos,a.result):((e=fr())===o&&(e=function(){var e,r,n,i,a=49*St+21,u=At[a];if(u)return St=u.nextPos,u.result;e=St,92===t.charCodeAt(St)?(r=V,St++):(r=o,0===xt&&Ct(q));if(r!==o)if(or()!==o){for(n=[],i=ir();i!==o;)n.push(i),i=ir();n!==o?(kt=e,e=r=K()):(St=e,e=s)}else St=e,e=s;else St=e,e=s;return At[a]={nextPos:St,result:e},e}(),e===o&&(e=St,r=St,xt++,t.substr(St,3)===P?(n=P,St+=3):(n=o,0===xt&&Ct(I)),xt--,n===o?r=f:(St=r,r=s),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&Ct(p)),n!==o?(kt=e,e=r=D(n)):(St=e,e=s)):(St=e,e=s))),At[i]={nextPos:St,result:e},e)}function $t(){var e,r,n,i=49*St+22,a=At[i];return a?(St=a.nextPos,a.result):(e=St,r=St,xt++,t.substr(St,3)===L?(n=L,St+=3):(n=o,0===xt&&Ct(N)),xt--,n===o?r=f:(St=r,r=s),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&Ct(p)),n!==o?(kt=e,e=r=F(n)):(St=e,e=s)):(St=e,e=s),At[i]={nextPos:St,result:e},e)}function Qt(){var e,r,n,i,a,u,c=49*St+24,l=At[c];return l?(St=l.nextPos,l.result):(e=St,43===t.charCodeAt(St)?(r=W,St++):(r=o,0===xt&&Ct(Y)),r===o&&(r=R),r!==o?(n=St,(i=lr())!==o?(46===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&Ct(E)),a!==o&&(u=lr())!==o?n=i=[i,a,u]:(St=n,n=s)):(St=n,n=s),n!==o?(kt=e,e=r=J(n)):(St=e,e=s)):(St=e,e=s),e===o&&(e=St,45===t.charCodeAt(St)?(r=Z,St++):(r=o,0===xt&&Ct(ee)),r!==o?(n=St,(i=lr())!==o?(46===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&Ct(E)),a!==o&&(u=lr())!==o?n=i=[i,a,u]:(St=n,n=s)):(St=n,n=s),n!==o?(kt=e,e=r=te(n)):(St=e,e=s)):(St=e,e=s)),At[c]={nextPos:St,result:e},e)}function Wt(){var e,r,n,i,a,u=49*St+26,c=At[u];if(c)return St=c.nextPos,c.result;if(e=St,43===t.charCodeAt(St)?(r=W,St++):(r=o,0===xt&&Ct(Y)),r===o&&(r=R),r!==o){if(n=[],(i=sr())!==o)for(;i!==o;)n.push(i),i=sr();else n=s;n!==o?(i=St,xt++,46===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&Ct(E)),xt--,a===o?i=f:(St=i,i=s),i!==o?(kt=e,e=r=J(n)):(St=e,e=s)):(St=e,e=s)}else St=e,e=s;if(e===o)if(e=St,45===t.charCodeAt(St)?(r=Z,St++):(r=o,0===xt&&Ct(ee)),r!==o){if(n=[],(i=sr())!==o)for(;i!==o;)n.push(i),i=sr();else n=s;n!==o?(i=St,xt++,46===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&Ct(E)),xt--,a===o?i=f:(St=i,i=s),i!==o?(kt=e,e=r=te(n)):(St=e,e=s)):(St=e,e=s)}else St=e,e=s;return At[u]={nextPos:St,result:e},e}function Yt(){var e,t,r,n,i,a=49*St+29,u=At[a];if(u)return St=u.nextPos,u.result;for(e=St,t=[],r=Zt();r!==o;)t.push(r),r=Zt();if(t!==o)if((r=qt())!==o){for(n=[],i=Zt();i!==o;)n.push(i),i=Zt();n!==o?(kt=e,e=t=de(r)):(St=e,e=s)}else St=e,e=s;else St=e,e=s;return At[a]={nextPos:St,result:e},e}function Jt(){var e,r,n,i,a,u,c,l=49*St+30,f=At[l];if(f)return St=f.nextPos,f.result;for(e=St,r=[],n=Zt();n!==o;)r.push(n),n=Zt();if(r!==o)if((n=qt())!==o){for(i=[],a=Zt();a!==o;)i.push(a),a=Zt();if(i!==o)if(44===t.charCodeAt(St)?(a=he,St++):(a=o,0===xt&&Ct(ye)),a!==o){for(u=[],c=Zt();c!==o;)u.push(c),c=Zt();u!==o?(kt=e,e=r=de(n)):(St=e,e=s)}else St=e,e=s;else St=e,e=s}else St=e,e=s;else St=e,e=s;return At[l]={nextPos:St,result:e},e}function Zt(){var e,t=49*St+31,r=At[t];return r?(St=r.nextPos,r.result):((e=nr())===o&&(e=or())===o&&(e=Nt()),At[t]={nextPos:St,result:e},e)}function er(){var e,r,n,i,a,u,c,l,f,p,d,h=49*St+33,y=At[h];if(y)return St=y.nextPos,y.result;for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Dt())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(61===t.charCodeAt(St)?(a=_,St++):(a=o,0===xt&&Ct(T)),a!==o){for(u=[],c=nr();c!==o;)u.push(c),c=nr();if(u!==o)if((c=qt())!==o){for(l=[],f=nr();f!==o;)l.push(f),f=nr();if(l!==o)if(44===t.charCodeAt(St)?(f=he,St++):(f=o,0===xt&&Ct(ye)),f!==o){for(p=[],d=nr();d!==o;)p.push(d),d=nr();p!==o?(kt=e,e=r=Se(n,c)):(St=e,e=s)}else St=e,e=s;else St=e,e=s}else St=e,e=s;else St=e,e=s}else St=e,e=s;else St=e,e=s}else St=e,e=s;else St=e,e=s;if(e===o){for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Dt())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(61===t.charCodeAt(St)?(a=_,St++):(a=o,0===xt&&Ct(T)),a!==o){for(u=[],c=nr();c!==o;)u.push(c),c=nr();u!==o&&(c=qt())!==o?(kt=e,e=r=Se(n,c)):(St=e,e=s)}else St=e,e=s;else St=e,e=s}else St=e,e=s;else St=e,e=s}return At[h]={nextPos:St,result:e},e}function tr(){var e,r,n,i=49*St+34,a=At[i];return a?(St=a.nextPos,a.result):(e=St,46===t.charCodeAt(St)?(r=k,St++):(r=o,0===xt&&Ct(E)),r!==o&&(n=lr())!==o?(kt=e,e=r=ke(n)):(St=e,e=s),At[i]={nextPos:St,result:e},e)}function rr(){var e,r,n,i,a,u,c,l,f,p,d,h,y=49*St+35,m=At[y];return m?(St=m.nextPos,m.result):(e=St,r=St,(n=sr())!==o&&(i=sr())!==o&&(a=sr())!==o&&(u=sr())!==o?(45===t.charCodeAt(St)?(c=Z,St++):(c=o,0===xt&&Ct(ee)),c!==o&&(l=sr())!==o&&(f=sr())!==o?(45===t.charCodeAt(St)?(p=Z,St++):(p=o,0===xt&&Ct(ee)),p!==o&&(d=sr())!==o&&(h=sr())!==o?r=n=[n,i,a,u,c,l,f,p,d,h]:(St=r,r=s)):(St=r,r=s)):(St=r,r=s),r!==o&&(kt=e,r=Ee(r)),e=r,At[y]={nextPos:St,result:e},e)}function nr(){var e,r=49*St+39,n=At[r];return n?(St=n.nextPos,n.result):(je.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&Ct(Be)),At[r]={nextPos:St,result:e},e)}function or(){var e,r,n,i=49*St+40,a=At[i];return a?(St=a.nextPos,a.result):(10===t.charCodeAt(St)?(e=Le,St++):(e=o,0===xt&&Ct(Ne)),e===o&&(e=St,13===t.charCodeAt(St)?(r=Ue,St++):(r=o,0===xt&&Ct(Me)),r!==o?(10===t.charCodeAt(St)?(n=Le,St++):(n=o,0===xt&&Ct(Ne)),n!==o?e=r=[r,n]:(St=e,e=s)):(St=e,e=s)),At[i]={nextPos:St,result:e},e)}function ir(){var e,t=49*St+41,r=At[t];return r?(St=r.nextPos,r.result):((e=or())===o&&(e=nr()),At[t]={nextPos:St,result:e},e)}function ar(){var e,r,n=49*St+42,i=At[n];return i?(St=i.nextPos,i.result):(e=St,xt++,t.length>St?(r=t.charAt(St),St++):(r=o,0===xt&&Ct(p)),xt--,r===o?e=f:(St=e,e=s),At[n]={nextPos:St,result:e},e)}function ur(){var e,r=49*St+43,n=At[r];return n?(St=n.nextPos,n.result):(Fe.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&Ct(De)),At[r]={nextPos:St,result:e},e)}function sr(){var e,r,n=49*St+44,i=At[n];return i?(St=i.nextPos,i.result):(Ve.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&Ct(qe)),e===o&&(e=St,95===t.charCodeAt(St)?(r=Ke,St++):(r=o,0===xt&&Ct(He)),r!==o&&(kt=e,r=ze()),e=r),At[n]={nextPos:St,result:e},e)}function cr(){var e,r=49*St+45,n=At[r];return n?(St=n.nextPos,n.result):(Xe.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&Ct(Ge)),At[r]={nextPos:St,result:e},e)}function lr(){var e,t,r,n=49*St+46,i=At[n];if(i)return St=i.nextPos,i.result;if(e=St,t=[],(r=sr())!==o)for(;r!==o;)t.push(r),r=sr();else t=s;return t!==o&&(kt=e,t=$e(t)),e=t,At[n]={nextPos:St,result:e},e}function fr(){var e,r,n=49*St+47,i=At[n];return i?(St=i.nextPos,i.result):(e=St,t.substr(St,2)===Qe?(r=Qe,St+=2):(r=o,0===xt&&Ct(We)),r!==o&&(kt=e,r=Ye()),(e=r)===o&&(e=St,t.substr(St,2)===Je?(r=Je,St+=2):(r=o,0===xt&&Ct(Ze)),r!==o&&(kt=e,r=et()),(e=r)===o&&(e=St,t.substr(St,2)===tt?(r=tt,St+=2):(r=o,0===xt&&Ct(rt)),r!==o&&(kt=e,r=nt()),(e=r)===o&&(e=St,t.substr(St,2)===ot?(r=ot,St+=2):(r=o,0===xt&&Ct(it)),r!==o&&(kt=e,r=at()),(e=r)===o&&(e=St,t.substr(St,2)===ut?(r=ut,St+=2):(r=o,0===xt&&Ct(st)),r!==o&&(kt=e,r=ct()),(e=r)===o&&(e=St,t.substr(St,2)===lt?(r=lt,St+=2):(r=o,0===xt&&Ct(ft)),r!==o&&(kt=e,r=pt()),(e=r)===o&&(e=St,t.substr(St,2)===dt?(r=dt,St+=2):(r=o,0===xt&&Ct(ht)),r!==o&&(kt=e,r=yt()),(e=r)===o&&(e=function(){var e,r,n,i,a,u,c,l,f,p,d,h=49*St+48,y=At[h];if(y)return St=y.nextPos,y.result;e=St,t.substr(St,2)===mt?(r=mt,St+=2):(r=o,0===xt&&Ct(vt));r!==o?(n=St,(i=ur())!==o&&(a=ur())!==o&&(u=ur())!==o&&(c=ur())!==o&&(l=ur())!==o&&(f=ur())!==o&&(p=ur())!==o&&(d=ur())!==o?n=i=[i,a,u,c,l,f,p,d]:(St=n,n=s),n!==o?(kt=e,e=r=gt(n)):(St=e,e=s)):(St=e,e=s);e===o&&(e=St,t.substr(St,2)===bt?(r=bt,St+=2):(r=o,0===xt&&Ct(wt)),r!==o?(n=St,(i=ur())!==o&&(a=ur())!==o&&(u=ur())!==o&&(c=ur())!==o?n=i=[i,a,u,c]:(St=n,n=s),n!==o?(kt=e,e=r=gt(n)):(St=e,e=s)):(St=e,e=s));return At[h]={nextPos:St,result:e},e}()))))))),At[n]={nextPos:St,result:e},e)}var pr=[];function dr(e){pr.push(e)}function hr(e,t,r,n,o){var i={type:e,value:t,line:r(),column:n()};return o&&(i.key=o),i}if((r=a())!==o&&St===t.length)return r;throw r!==o&&St1);u++)r.splice(0,1);n[a]=r.join("")}var s=-1,c=0,l=0,f=-1,p=!1;for(a=0;ac&&(s=f,c=l)):"0"===n[a]&&(p=!0,f=a,l=1);l>c&&(s=f,c=l),c>1&&n.splice(s,c,""),o=n.length;var d="";for(""===n[0]&&(d=":"),a=0;a=e.length-1)return!1;var n=e.lastIndexOf(".",t-1);if(n<=0||n>=t-1)return!1;var o=r.list[e.slice(t+1)];return!!o&&o.indexOf(" "+e.slice(n+1,t)+" ")>=0},is:function(e){var t=e.lastIndexOf(".");if(t<=0||t>=e.length-1)return!1;if(e.lastIndexOf(".",t-1)>=0)return!1;var n=r.list[e.slice(t+1)];return!!n&&n.indexOf(" "+e.slice(0,t)+" ")>=0},get:function(e){var t=e.lastIndexOf(".");if(t<=0||t>=e.length-1)return null;var n=e.lastIndexOf(".",t-1);if(n<=0||n>=t-1)return null;var o=r.list[e.slice(t+1)];return o?o.indexOf(" "+e.slice(n+1,t)+" ")<0?null:e.slice(n+1):null},noConflict:function(){return e.SecondLevelDomains===this&&(e.SecondLevelDomains=t),this}};return r}))},4193:function(e,t,r){var n,o,i;!function(a,u){"use strict";e.exports?e.exports=u(r(9340),r(1430),r(4704)):(o=[r(9340),r(1430),r(4704)],void 0===(i="function"==typeof(n=u)?n.apply(t,o):n)||(e.exports=i))}(0,(function(e,t,r,n){"use strict";var o=n&&n.URI;function i(e,t){var r=arguments.length>=1;if(!(this instanceof i))return r?arguments.length>=2?new i(e,t):new i(e):new i;if(void 0===e){if(r)throw new TypeError("undefined is not a valid argument for URI");e="undefined"!=typeof location?location.href+"":""}if(null===e&&r)throw new TypeError("null is not a valid argument for URI");return this.href(e),void 0!==t?this.absoluteTo(t):this}i.version="1.19.11";var a=i.prototype,u=Object.prototype.hasOwnProperty;function s(e){return e.replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")}function c(e){return void 0===e?"Undefined":String(Object.prototype.toString.call(e)).slice(8,-1)}function l(e){return"Array"===c(e)}function f(e,t){var r,n,o={};if("RegExp"===c(t))o=null;else if(l(t))for(r=0,n=t.length;r]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?\xab\xbb\u201c\u201d\u2018\u2019]))/gi,i.findUri={start:/\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,end:/[\s\r\n]|$/,trim:/[`!()\[\]{};:'".,<>?\xab\xbb\u201c\u201d\u201e\u2018\u2019]+$/,parens:/(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g},i.leading_whitespace_expression=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,i.ascii_tab_whitespace=/[\u0009\u000A\u000D]+/g,i.defaultPorts={http:"80",https:"443",ftp:"21",gopher:"70",ws:"80",wss:"443"},i.hostProtocols=["http","https"],i.invalid_hostname_characters=/[^a-zA-Z0-9\.\-:_]/,i.domAttributes={a:"href",blockquote:"cite",link:"href",base:"href",script:"src",form:"action",img:"src",area:"href",iframe:"src",embed:"src",source:"src",track:"src",input:"src",audio:"src",video:"src"},i.getDomAttribute=function(e){if(e&&e.nodeName){var t=e.nodeName.toLowerCase();if("input"!==t||"image"===e.type)return i.domAttributes[t]}},i.encode=m,i.decode=decodeURIComponent,i.iso8859=function(){i.encode=escape,i.decode=unescape},i.unicode=function(){i.encode=m,i.decode=decodeURIComponent},i.characters={pathname:{encode:{expression:/%(24|26|2B|2C|3B|3D|3A|40)/gi,map:{"%24":"$","%26":"&","%2B":"+","%2C":",","%3B":";","%3D":"=","%3A":":","%40":"@"}},decode:{expression:/[\/\?#]/g,map:{"/":"%2F","?":"%3F","#":"%23"}}},reserved:{encode:{expression:/%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/gi,map:{"%3A":":","%2F":"/","%3F":"?","%23":"#","%5B":"[","%5D":"]","%40":"@","%21":"!","%24":"$","%26":"&","%27":"'","%28":"(","%29":")","%2A":"*","%2B":"+","%2C":",","%3B":";","%3D":"="}}},urnpath:{encode:{expression:/%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/gi,map:{"%21":"!","%24":"$","%27":"'","%28":"(","%29":")","%2A":"*","%2B":"+","%2C":",","%3B":";","%3D":"=","%40":"@"}},decode:{expression:/[\/\?#:]/g,map:{"/":"%2F","?":"%3F","#":"%23",":":"%3A"}}}},i.encodeQuery=function(e,t){var r=i.encode(e+"");return void 0===t&&(t=i.escapeQuerySpace),t?r.replace(/%20/g,"+"):r},i.decodeQuery=function(e,t){e+="",void 0===t&&(t=i.escapeQuerySpace);try{return i.decode(t?e.replace(/\+/g,"%20"):e)}catch(t){return e}};var v,g={encode:"encode",decode:"decode"},b=function(e,t){return function(r){try{return i[t](r+"").replace(i.characters[e][t].expression,(function(r){return i.characters[e][t].map[r]}))}catch(e){return r}}};for(v in g)i[v+"PathSegment"]=b("pathname",g[v]),i[v+"UrnPathSegment"]=b("urnpath",g[v]);var w=function(e,t,r){return function(n){var o;o=r?function(e){return i[t](i[r](e))}:i[t];for(var a=(n+"").split(e),u=0,s=a.length;u-1&&(t.fragment=e.substring(r+1)||null,e=e.substring(0,r)),(r=e.indexOf("?"))>-1&&(t.query=e.substring(r+1)||null,e=e.substring(0,r)),"//"===(e=(e=e.replace(/^(https?|ftp|wss?)?:+[/\\]*/i,"$1://")).replace(/^[/\\]{2,}/i,"//")).substring(0,2)?(t.protocol=null,e=e.substring(2),e=i.parseAuthority(e,t)):(r=e.indexOf(":"))>-1&&(t.protocol=e.substring(0,r)||null,t.protocol&&!t.protocol.match(i.protocol_expression)?t.protocol=void 0:"//"===e.substring(r+1,r+3).replace(/\\/g,"/")?(e=e.substring(r+3),e=i.parseAuthority(e,t)):(e=e.substring(r+1),t.urn=!0)),t.path=e,t},i.parseHost=function(e,t){e||(e="");var r,n,o=(e=e.replace(/\\/g,"/")).indexOf("/");if(-1===o&&(o=e.length),"["===e.charAt(0))r=e.indexOf("]"),t.hostname=e.substring(1,r)||null,t.port=e.substring(r+2,o)||null,"/"===t.port&&(t.port=null);else{var a=e.indexOf(":"),u=e.indexOf("/"),s=e.indexOf(":",a+1);-1!==s&&(-1===u||s-1?o:e.length-1);return a>-1&&(-1===o||a-1?d.slice(0,h)+d.slice(h).replace(a,""):d.replace(a,"")).length<=c[0].length||r.ignore&&r.ignore.test(d))){var v=t(d,l,p=l+d.length,e);void 0!==v?(v=String(v),e=e.slice(0,l)+v+e.slice(p),n.lastIndex=l+v.length):n.lastIndex=p}}return n.lastIndex=0,e},i.ensureValidHostname=function(t,r){var n=!!t,o=!1;if(!!r&&(o=p(i.hostProtocols,r)),o&&!n)throw new TypeError("Hostname cannot be empty, if protocol is "+r);if(t&&t.match(i.invalid_hostname_characters)){if(!e)throw new TypeError('Hostname "'+t+'" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');if(e.toASCII(t).match(i.invalid_hostname_characters))throw new TypeError('Hostname "'+t+'" contains characters other than [A-Z0-9.-:_]')}},i.ensureValidPort=function(e){if(e){var t=Number(e);if(!(/^[0-9]+$/.test(t)&&t>0&&t<65536))throw new TypeError('Port "'+e+'" is not a valid port')}},i.noConflict=function(e){if(e){var t={URI:this.noConflict()};return n.URITemplate&&"function"==typeof n.URITemplate.noConflict&&(t.URITemplate=n.URITemplate.noConflict()),n.IPv6&&"function"==typeof n.IPv6.noConflict&&(t.IPv6=n.IPv6.noConflict()),n.SecondLevelDomains&&"function"==typeof n.SecondLevelDomains.noConflict&&(t.SecondLevelDomains=n.SecondLevelDomains.noConflict()),t}return n.URI===this&&(n.URI=o),this},a.build=function(e){return!0===e?this._deferred_build=!0:(void 0===e||this._deferred_build)&&(this._string=i.build(this._parts),this._deferred_build=!1),this},a.clone=function(){return new i(this)},a.valueOf=a.toString=function(){return this.build(!1)._string},a.protocol=S("protocol"),a.username=S("username"),a.password=S("password"),a.hostname=S("hostname"),a.port=S("port"),a.query=k("query","?"),a.fragment=k("fragment","#"),a.search=function(e,t){var r=this.query(e,t);return"string"==typeof r&&r.length?"?"+r:r},a.hash=function(e,t){var r=this.fragment(e,t);return"string"==typeof r&&r.length?"#"+r:r},a.pathname=function(e,t){if(void 0===e||!0===e){var r=this._parts.path||(this._parts.hostname?"/":"");return e?(this._parts.urn?i.decodeUrnPath:i.decodePath)(r):r}return this._parts.urn?this._parts.path=e?i.recodeUrnPath(e):"":this._parts.path=e?i.recodePath(e):"/",this.build(!t),this},a.path=a.pathname,a.href=function(e,t){var r;if(void 0===e)return this.toString();this._string="",this._parts=i._parts();var n=e instanceof i,o="object"==typeof e&&(e.hostname||e.path||e.pathname);e.nodeName&&(e=e[i.getDomAttribute(e)]||"",o=!1);if(!n&&o&&void 0!==e.pathname&&(e=e.toString()),"string"==typeof e||e instanceof String)this._parts=i.parse(String(e),this._parts);else{if(!n&&!o)throw new TypeError("invalid input");var a=n?e._parts:e;for(r in a)"query"!==r&&u.call(this._parts,r)&&(this._parts[r]=a[r]);a.query&&this.query(a.query,!1)}return this.build(!t),this},a.is=function(e){var t=!1,n=!1,o=!1,a=!1,u=!1,s=!1,c=!1,l=!this._parts.urn;switch(this._parts.hostname&&(l=!1,n=i.ip4_expression.test(this._parts.hostname),o=i.ip6_expression.test(this._parts.hostname),u=(a=!(t=n||o))&&r&&r.has(this._parts.hostname),s=a&&i.idn_expression.test(this._parts.hostname),c=a&&i.punycode_expression.test(this._parts.hostname)),e.toLowerCase()){case"relative":return l;case"absolute":return!l;case"domain":case"name":return a;case"sld":return u;case"ip":return t;case"ip4":case"ipv4":case"inet4":return n;case"ip6":case"ipv6":case"inet6":return o;case"idn":return s;case"url":return!this._parts.urn;case"urn":return!!this._parts.urn;case"punycode":return c}return null};var E=a.protocol,_=a.port,T=a.hostname;a.protocol=function(e,t){if(e&&!(e=e.replace(/:(\/\/)?$/,"")).match(i.protocol_expression))throw new TypeError('Protocol "'+e+"\" contains characters other than [A-Z0-9.+-] or doesn't start with [A-Z]");return E.call(this,e,t)},a.scheme=a.protocol,a.port=function(e,t){return this._parts.urn?void 0===e?"":this:(void 0!==e&&(0===e&&(e=null),e&&(":"===(e+="").charAt(0)&&(e=e.substring(1)),i.ensureValidPort(e))),_.call(this,e,t))},a.hostname=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0!==e){var r={preventInvalidHostname:this._parts.preventInvalidHostname};if("/"!==i.parseHost(e,r))throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');e=r.hostname,this._parts.preventInvalidHostname&&i.ensureValidHostname(e,this._parts.protocol)}return T.call(this,e,t)},a.origin=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e){var r=this.protocol();return this.authority()?(r?r+"://":"")+this.authority():""}var n=i(e);return this.protocol(n.protocol()).authority(n.authority()).build(!t),this},a.host=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e)return this._parts.hostname?i.buildHost(this._parts):"";if("/"!==i.parseHost(e,this._parts))throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');return this.build(!t),this},a.authority=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e)return this._parts.hostname?i.buildAuthority(this._parts):"";if("/"!==i.parseAuthority(e,this._parts))throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');return this.build(!t),this},a.userinfo=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e){var r=i.buildUserinfo(this._parts);return r?r.substring(0,r.length-1):r}return"@"!==e[e.length-1]&&(e+="@"),i.parseUserinfo(e,this._parts),this.build(!t),this},a.resource=function(e,t){var r;return void 0===e?this.path()+this.search()+this.hash():(r=i.parse(e),this._parts.path=r.path,this._parts.query=r.query,this._parts.fragment=r.fragment,this.build(!t),this)},a.subdomain=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e){if(!this._parts.hostname||this.is("IP"))return"";var r=this._parts.hostname.length-this.domain().length-1;return this._parts.hostname.substring(0,r)||""}var n=this._parts.hostname.length-this.domain().length,o=this._parts.hostname.substring(0,n),a=new RegExp("^"+s(o));if(e&&"."!==e.charAt(e.length-1)&&(e+="."),-1!==e.indexOf(":"))throw new TypeError("Domains cannot contain colons");return e&&i.ensureValidHostname(e,this._parts.protocol),this._parts.hostname=this._parts.hostname.replace(a,e),this.build(!t),this},a.domain=function(e,t){if(this._parts.urn)return void 0===e?"":this;if("boolean"==typeof e&&(t=e,e=void 0),void 0===e){if(!this._parts.hostname||this.is("IP"))return"";var r=this._parts.hostname.match(/\./g);if(r&&r.length<2)return this._parts.hostname;var n=this._parts.hostname.length-this.tld(t).length-1;return n=this._parts.hostname.lastIndexOf(".",n-1)+1,this._parts.hostname.substring(n)||""}if(!e)throw new TypeError("cannot set domain empty");if(-1!==e.indexOf(":"))throw new TypeError("Domains cannot contain colons");if(i.ensureValidHostname(e,this._parts.protocol),!this._parts.hostname||this.is("IP"))this._parts.hostname=e;else{var o=new RegExp(s(this.domain())+"$");this._parts.hostname=this._parts.hostname.replace(o,e)}return this.build(!t),this},a.tld=function(e,t){if(this._parts.urn)return void 0===e?"":this;if("boolean"==typeof e&&(t=e,e=void 0),void 0===e){if(!this._parts.hostname||this.is("IP"))return"";var n=this._parts.hostname.lastIndexOf("."),o=this._parts.hostname.substring(n+1);return!0!==t&&r&&r.list[o.toLowerCase()]&&r.get(this._parts.hostname)||o}var i;if(!e)throw new TypeError("cannot set TLD empty");if(e.match(/[^a-zA-Z0-9-]/)){if(!r||!r.is(e))throw new TypeError('TLD "'+e+'" contains characters other than [A-Z0-9]');i=new RegExp(s(this.tld())+"$"),this._parts.hostname=this._parts.hostname.replace(i,e)}else{if(!this._parts.hostname||this.is("IP"))throw new ReferenceError("cannot set TLD on non-domain host");i=new RegExp(s(this.tld())+"$"),this._parts.hostname=this._parts.hostname.replace(i,e)}return this.build(!t),this},a.directory=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e||!0===e){if(!this._parts.path&&!this._parts.hostname)return"";if("/"===this._parts.path)return"/";var r=this._parts.path.length-this.filename().length-1,n=this._parts.path.substring(0,r)||(this._parts.hostname?"/":"");return e?i.decodePath(n):n}var o=this._parts.path.length-this.filename().length,a=this._parts.path.substring(0,o),u=new RegExp("^"+s(a));return this.is("relative")||(e||(e="/"),"/"!==e.charAt(0)&&(e="/"+e)),e&&"/"!==e.charAt(e.length-1)&&(e+="/"),e=i.recodePath(e),this._parts.path=this._parts.path.replace(u,e),this.build(!t),this},a.filename=function(e,t){if(this._parts.urn)return void 0===e?"":this;if("string"!=typeof e){if(!this._parts.path||"/"===this._parts.path)return"";var r=this._parts.path.lastIndexOf("/"),n=this._parts.path.substring(r+1);return e?i.decodePathSegment(n):n}var o=!1;"/"===e.charAt(0)&&(e=e.substring(1)),e.match(/\.?\//)&&(o=!0);var a=new RegExp(s(this.filename())+"$");return e=i.recodePath(e),this._parts.path=this._parts.path.replace(a,e),o?this.normalizePath(t):this.build(!t),this},a.suffix=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e||!0===e){if(!this._parts.path||"/"===this._parts.path)return"";var r,n,o=this.filename(),a=o.lastIndexOf(".");return-1===a?"":(r=o.substring(a+1),n=/^[a-z0-9%]+$/i.test(r)?r:"",e?i.decodePathSegment(n):n)}"."===e.charAt(0)&&(e=e.substring(1));var u,c=this.suffix();if(c)u=e?new RegExp(s(c)+"$"):new RegExp(s("."+c)+"$");else{if(!e)return this;this._parts.path+="."+i.recodePath(e)}return u&&(e=i.recodePath(e),this._parts.path=this._parts.path.replace(u,e)),this.build(!t),this},a.segment=function(e,t,r){var n=this._parts.urn?":":"/",o=this.path(),i="/"===o.substring(0,1),a=o.split(n);if(void 0!==e&&"number"!=typeof e&&(r=t,t=e,e=void 0),void 0!==e&&"number"!=typeof e)throw new Error('Bad segment "'+e+'", must be 0-based integer');if(i&&a.shift(),e<0&&(e=Math.max(a.length+e,0)),void 0===t)return void 0===e?a:a[e];if(null===e||void 0===a[e])if(l(t)){a=[];for(var u=0,s=t.length;u{}"`^| \\]/,o.expand=function(e,t,r){var n,i,a,s=u[e.operator],c=s.named?"Named":"Unnamed",l=e.variables,f=[];for(a=0;i=l[a];a++){if(0===(n=t.get(i.name)).type&&r&&r.strict)throw new Error('Missing expansion value for variable "'+i.name+'"');if(n.val.length){if(n.type>1&&i.maxlength)throw new Error('Invalid expression: Prefix modifier not applicable to variable "'+i.name+'"');f.push(o["expand"+c](n,s,i.explode,i.explode&&s.separator||",",i.maxlength,i.name))}else n.type&&f.push("")}return f.length?s.prefix+f.join(s.separator):""},o.expandNamed=function(t,r,n,o,i,a){var u,s,c,l="",f=r.encode,p=r.empty_name_separator,d=!t[f].length,h=2===t.type?"":e[f](a);for(s=0,c=t.val.length;s= 0x80 (not a basic code point)","invalid-input":"Invalid input"},p=Math.floor,d=String.fromCharCode;function h(e){throw new RangeError(f[e])}function y(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function m(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+y((e=e.replace(l,".")).split("."),t).join(".")}function v(e){for(var t,r,n=[],o=0,i=e.length;o=55296&&t<=56319&&o65535&&(t+=d((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=d(e)})).join("")}function b(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function w(e,t,r){var n=0;for(e=r?p(e/700):e>>1,e+=p(e/t);e>455;n+=u)e=p(e/35);return p(n+36*e/(e+38))}function S(e){var t,r,n,o,i,s,c,l,f,d,y,m=[],v=e.length,b=0,S=128,k=72;for((r=e.lastIndexOf("-"))<0&&(r=0),n=0;n=128&&h("not-basic"),m.push(e.charCodeAt(n));for(o=r>0?r+1:0;o=v&&h("invalid-input"),((l=(y=e.charCodeAt(o++))-48<10?y-22:y-65<26?y-65:y-97<26?y-97:u)>=u||l>p((a-b)/s))&&h("overflow"),b+=l*s,!(l<(f=c<=k?1:c>=k+26?26:c-k));c+=u)s>p(a/(d=u-f))&&h("overflow"),s*=d;k=w(b-i,t=m.length+1,0==i),p(b/t)>a-S&&h("overflow"),S+=p(b/t),b%=t,m.splice(b++,0,S)}return g(m)}function k(e){var t,r,n,o,i,s,c,l,f,y,m,g,S,k,E,_=[];for(g=(e=v(e)).length,t=128,r=0,i=72,s=0;s=t&&mp((a-r)/(S=n+1))&&h("overflow"),r+=(c-t)*S,t=c,s=0;sa&&h("overflow"),m==t){for(l=r,f=u;!(l<(y=f<=i?1:f>=i+26?26:f-i));f+=u)E=l-y,k=u-y,_.push(d(b(y+E%k,0))),l=p(E/k);_.push(d(b(l,0))),i=w(r,S,n==o),r=0,++n}++r,++t}return _.join("")}i={version:"1.3.2",ucs2:{decode:v,encode:g},decode:S,encode:k,toASCII:function(e){return m(e,(function(e){return c.test(e)?"xn--"+k(e):e}))},toUnicode:function(e){return m(e,(function(e){return s.test(e)?S(e.slice(4).toLowerCase()):e}))}},void 0===(n=function(){return i}.call(t,r,t,e))||(e.exports=n)}()},2894:()=>{}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={id:n,loaded:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.loaded=!0,i.exports}return r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),r(1924)})())); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-minimal.min.js.LICENSE.txt b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-minimal.min.js.LICENSE.txt new file mode 100644 index 000000000..291e51292 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-minimal.min.js.LICENSE.txt @@ -0,0 +1,69 @@ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +/*! + * URI.js - Mutating URLs + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! + * URI.js - Mutating URLs + * IPv6 Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! + * URI.js - Mutating URLs + * Second Level Domain (SLD) Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! + * URI.js - Mutating URLs + * URI Template Support - http://tools.ietf.org/html/rfc6570 + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! https://mths.be/punycode v1.4.0 by @mathias */ + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + +/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ diff --git a/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-axios.js b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-axios.js new file mode 100644 index 000000000..89fccab9b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-axios.js @@ -0,0 +1,57742 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define("StellarSdk", [], factory); + else if(typeof exports === 'object') + exports["StellarSdk"] = factory(); + else + root["StellarSdk"] = factory(); +})(self, () => { +return /******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 3740: +/***/ (function(module) { + +/*! For license information please see xdr.js.LICENSE.txt */ +!function(t,e){ true?module.exports=e():0}(this,(()=>(()=>{var t={616:(t,e,r)=>{"use strict";r.d(e,{A:()=>i});var n=r(287);n.hp.alloc(1).subarray(0,1)instanceof n.hp||(n.hp.prototype.subarray=function(t,e){const r=Uint8Array.prototype.subarray.call(this,t,e);return Object.setPrototypeOf(r,n.hp.prototype),r});const i=n.hp},281:(t,e,r)=>{const n=r(164);t.exports=n},164:(t,e,r)=>{"use strict";r.r(e),r.d(e,{Array:()=>F,Bool:()=>S,Double:()=>L,Enum:()=>q,Float:()=>O,Hyper:()=>U,Int:()=>v,LargeInt:()=>x,Opaque:()=>D,Option:()=>X,Quadruple:()=>N,Reference:()=>G,String:()=>M,Struct:()=>Y,Union:()=>W,UnsignedHyper:()=>T,UnsignedInt:()=>R,VarArray:()=>P,VarOpaque:()=>z,Void:()=>k,XdrReader:()=>f,XdrWriter:()=>c,config:()=>it});class n extends TypeError{constructor(t){super(`XDR Write Error: ${t}`)}}class i extends TypeError{constructor(t){super(`XDR Read Error: ${t}`)}}class o extends TypeError{constructor(t){super(`XDR Type Definition Error: ${t}`)}}class s extends o{constructor(){super("method not implemented, it should be overloaded in the descendant class.")}}var u=r(616).A;class f{constructor(t){if(!u.isBuffer(t)){if(!(t instanceof Array||Array.isArray(t)||ArrayBuffer.isView(t)))throw new i(`source invalid: ${t}`);t=u.from(t)}this._buffer=t,this._length=t.length,this._index=0}_buffer;_length;_index;get eof(){return this._index===this._length}advance(t){const e=this._index;if(this._index+=t,this._length0){for(let t=0;t0){const t=this.alloc(r);this._buffer.fill(0,t,this._index)}}writeInt32BE(t){const e=this.alloc(4);this._buffer.writeInt32BE(t,e)}writeUInt32BE(t){const e=this.alloc(4);this._buffer.writeUInt32BE(t,e)}writeBigInt64BE(t){const e=this.alloc(8);this._buffer.writeBigInt64BE(t,e)}writeBigUInt64BE(t){const e=this.alloc(8);this._buffer.writeBigUInt64BE(t,e)}writeFloatBE(t){const e=this.alloc(4);this._buffer.writeFloatBE(t,e)}writeDoubleBE(t){const e=this.alloc(8);this._buffer.writeDoubleBE(t,e)}static bufferChunkSize=h}var l=r(616).A;class p{toXDR(t="raw"){if(!this.write)return this.constructor.toXDR(this,t);const e=new c;return this.write(this,e),w(e.finalize(),t)}fromXDR(t,e="raw"){if(!this.read)return this.constructor.fromXDR(t,e);const r=new f(m(t,e)),n=this.read(r);return r.ensureInputConsumed(),n}validateXDR(t,e="raw"){try{return this.fromXDR(t,e),!0}catch(t){return!1}}static toXDR(t,e="raw"){const r=new c;return this.write(t,r),w(r.finalize(),e)}static fromXDR(t,e="raw"){const r=new f(m(t,e)),n=this.read(r);return r.ensureInputConsumed(),n}static validateXDR(t,e="raw"){try{return this.fromXDR(t,e),!0}catch(t){return!1}}}class d extends p{static read(t){throw new s}static write(t,e){throw new s}static isValid(t){return!1}}class g extends p{isValid(t){return!1}}class y extends TypeError{constructor(t){super(`Invalid format ${t}, must be one of "raw", "hex", "base64"`)}}function w(t,e){switch(e){case"raw":return t;case"hex":return t.toString("hex");case"base64":return t.toString("base64");default:throw new y(e)}}function m(t,e){switch(e){case"raw":return t;case"hex":return l.from(t,"hex");case"base64":return l.from(t,"base64");default:throw new y(e)}}function b(t,e){return null!=t&&(t instanceof e||_(t,e)&&"function"==typeof t.constructor.read&&"function"==typeof t.constructor.write&&_(t,"XdrType"))}function _(t,e){do{if(t.constructor.name===e)return!0}while(t=Object.getPrototypeOf(t));return!1}const B=2147483647,E=-2147483648;class v extends d{static read(t){return t.readInt32BE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");if((0|t)!==t)throw new n("invalid i32 value");e.writeInt32BE(t)}static isValid(t){return"number"==typeof t&&(0|t)===t&&(t>=E&&t<=B)}}function A(t,e,r){if("bigint"!=typeof t)throw new TypeError("Expected bigint 'value', got "+typeof t);const n=e/r;if(1===n)return[t];if(r<32||r>128||2!==n&&4!==n&&8!==n)throw new TypeError(`invalid bigint (${t}) and slice size (${e} -> ${r}) combination`);const i=BigInt(r),o=new Array(n);for(let e=0;e>=i;return o}function I(t,e){if(e)return[0n,(1n<=o&&i<=s)return i;throw new TypeError(`bigint values [${t}] for ${function(t,e){return`${e?"u":"i"}${t}`}(e,r)} out of range [${o}, ${s}]: ${i}`)}(t,this.size,this.unsigned)}get unsigned(){throw new s}get size(){throw new s}slice(t){return A(this._value,this.size,t)}toString(){return this._value.toString()}toJSON(){return{_value:this._value.toString()}}toBigInt(){return BigInt(this._value)}static read(t){const{size:e}=this.prototype;return 64===e?new this(t.readBigUInt64BE()):new this(...Array.from({length:e/64},(()=>t.readBigUInt64BE())).reverse())}static write(t,e){if(t instanceof this)t=t._value;else if("bigint"!=typeof t||t>this.MAX_VALUE||t>32n)|0}get size(){return 64}get unsigned(){return!1}static fromBits(t,e){return new this(t,e)}}U.defineIntBoundaries();const $=4294967295;class R extends d{static read(t){return t.readUInt32BE()}static write(t,e){if("number"!=typeof t||!(t>=0&&t<=$)||t%1!=0)throw new n("invalid u32 value");e.writeUInt32BE(t)}static isValid(t){return"number"==typeof t&&t%1==0&&(t>=0&&t<=$)}}R.MAX_VALUE=$,R.MIN_VALUE=0;class T extends x{constructor(...t){super(t)}get low(){return Number(0xffffffffn&this._value)|0}get high(){return Number(this._value>>32n)|0}get size(){return 64}get unsigned(){return!0}static fromBits(t,e){return new this(t,e)}}T.defineIntBoundaries();class O extends d{static read(t){return t.readFloatBE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");e.writeFloatBE(t)}static isValid(t){return"number"==typeof t}}class L extends d{static read(t){return t.readDoubleBE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");e.writeDoubleBE(t)}static isValid(t){return"number"==typeof t}}class N extends d{static read(){throw new o("quadruple not supported")}static write(){throw new o("quadruple not supported")}static isValid(){return!1}}class S extends d{static read(t){const e=v.read(t);switch(e){case 0:return!1;case 1:return!0;default:throw new i(`got ${e} when trying to read a bool`)}}static write(t,e){const r=t?1:0;v.write(r,e)}static isValid(t){return"boolean"==typeof t}}var V=r(616).A;class M extends g{constructor(t=R.MAX_VALUE){super(),this._maxLength=t}read(t){const e=R.read(t);if(e>this._maxLength)throw new i(`saw ${e} length String, max allowed is ${this._maxLength}`);return t.read(e)}readString(t){return this.read(t).toString("utf8")}write(t,e){const r="string"==typeof t?V.byteLength(t,"utf8"):t.length;if(r>this._maxLength)throw new n(`got ${t.length} bytes, max allowed is ${this._maxLength}`);R.write(r,e),e.write(t,r)}isValid(t){return"string"==typeof t?V.byteLength(t,"utf8")<=this._maxLength:!!(t instanceof Array||V.isBuffer(t))&&t.length<=this._maxLength}}var C=r(616).A;class D extends g{constructor(t){super(),this._length=t}read(t){return t.read(this._length)}write(t,e){const{length:r}=t;if(r!==this._length)throw new n(`got ${t.length} bytes, expected ${this._length}`);e.write(t,r)}isValid(t){return C.isBuffer(t)&&t.length===this._length}}var j=r(616).A;class z extends g{constructor(t=R.MAX_VALUE){super(),this._maxLength=t}read(t){const e=R.read(t);if(e>this._maxLength)throw new i(`saw ${e} length VarOpaque, max allowed is ${this._maxLength}`);return t.read(e)}write(t,e){const{length:r}=t;if(t.length>this._maxLength)throw new n(`got ${t.length} bytes, max allowed is ${this._maxLength}`);R.write(r,e),e.write(t,r)}isValid(t){return j.isBuffer(t)&&t.length<=this._maxLength}}class F extends g{constructor(t,e){super(),this._childType=t,this._length=e}read(t){const e=new r.g.Array(this._length);for(let r=0;rthis._maxLength)throw new i(`saw ${e} length VarArray, max allowed is ${this._maxLength}`);const r=new Array(e);for(let n=0;nthis._maxLength)throw new n(`got array of size ${t.length}, max allowed is ${this._maxLength}`);R.write(t.length,e);for(const r of t)this._childType.write(r,e)}isValid(t){if(!(t instanceof Array)||t.length>this._maxLength)return!1;for(const e of t)if(!this._childType.isValid(e))return!1;return!0}}class X extends d{constructor(t){super(),this._childType=t}read(t){if(S.read(t))return this._childType.read(t)}write(t,e){const r=null!=t;S.write(r,e),r&&this._childType.write(t,e)}isValid(t){return null==t||this._childType.isValid(t)}}class k extends d{static read(){}static write(t){if(void 0!==t)throw new n("trying to write value to a void slot")}static isValid(t){return void 0===t}}class q extends d{constructor(t,e){super(),this.name=t,this.value=e}static read(t){const e=v.read(t),r=this._byValue[e];if(void 0===r)throw new i(`unknown ${this.enumName} member for value ${e}`);return r}static write(t,e){if(!this.isValid(t))throw new n(`${t} has enum name ${t?.enumName}, not ${this.enumName}: ${JSON.stringify(t)}`);v.write(t.value,e)}static isValid(t){return t?.constructor?.enumName===this.enumName||b(t,this)}static members(){return this._members}static values(){return Object.values(this._members)}static fromName(t){const e=this._members[t];if(!e)throw new TypeError(`${t} is not a member of ${this.enumName}`);return e}static fromValue(t){const e=this._byValue[t];if(void 0===e)throw new TypeError(`${t} is not a value of any member of ${this.enumName}`);return e}static create(t,e,r){const n=class extends q{};n.enumName=e,t.results[e]=n,n._members={},n._byValue={};for(const[t,e]of Object.entries(r)){const r=new n(t,e);n._members[t]=r,n._byValue[e]=r,n[t]=()=>r}return n}}class G extends d{resolve(){throw new o('"resolve" method should be implemented in the descendant class')}}class Y extends g{constructor(t){super(),this._attributes=t||{}}static read(t){const e={};for(const[r,n]of this._fields)e[r]=n.read(t);return new this(e)}static write(t,e){if(!this.isValid(t))throw new n(`${t} has struct name ${t?.constructor?.structName}, not ${this.structName}: ${JSON.stringify(t)}`);for(const[r,n]of this._fields){const i=t._attributes[r];n.write(i,e)}}static isValid(t){return t?.constructor?.structName===this.structName||b(t,this)}static create(t,e,r){const n=class extends Y{};n.structName=e,t.results[e]=n;const i=new Array(r.length);for(let e=0;e{"use strict";e.byteLength=function(t){var e=u(t),r=e[0],n=e[1];return 3*(r+n)/4-n},e.toByteArray=function(t){var e,r,o=u(t),s=o[0],f=o[1],a=new i(function(t,e,r){return 3*(e+r)/4-r}(0,s,f)),h=0,c=f>0?s-4:s;for(r=0;r>16&255,a[h++]=e>>8&255,a[h++]=255&e;2===f&&(e=n[t.charCodeAt(r)]<<2|n[t.charCodeAt(r+1)]>>4,a[h++]=255&e);1===f&&(e=n[t.charCodeAt(r)]<<10|n[t.charCodeAt(r+1)]<<4|n[t.charCodeAt(r+2)]>>2,a[h++]=e>>8&255,a[h++]=255&e);return a},e.fromByteArray=function(t){for(var e,n=t.length,i=n%3,o=[],s=16383,u=0,a=n-i;ua?a:u+s));1===i?(e=t[n-1],o.push(r[e>>2]+r[e<<4&63]+"==")):2===i&&(e=(t[n-2]<<8)+t[n-1],o.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"="));return o.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)r[s]=o[s],n[o.charCodeAt(s)]=s;function u(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function f(t,e,n){for(var i,o,s=[],u=e;u>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return s.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287:(t,e,r)=>{"use strict";const n=r(526),i=r(251),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.hp=f,e.IS=50;const s=2147483647;function u(t){if(t>s)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,f.prototype),e}function f(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return c(t)}return a(t,e,r)}function a(t,e,r){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!f.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|g(t,e);let n=u(r);const i=n.write(t,e);i!==r&&(n=n.slice(0,i));return n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(W(t,Uint8Array)){const e=new Uint8Array(t);return p(e.buffer,e.byteOffset,e.byteLength)}return l(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(W(t,ArrayBuffer)||t&&W(t.buffer,ArrayBuffer))return p(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(W(t,SharedArrayBuffer)||t&&W(t.buffer,SharedArrayBuffer)))return p(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return f.from(n,e,r);const i=function(t){if(f.isBuffer(t)){const e=0|d(t.length),r=u(e);return 0===r.length||t.copy(r,0,0,e),r}if(void 0!==t.length)return"number"!=typeof t.length||H(t.length)?u(0):l(t);if("Buffer"===t.type&&Array.isArray(t.data))return l(t.data)}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return f.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function h(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function c(t){return h(t),u(t<0?0:0|d(t))}function l(t){const e=t.length<0?0:0|d(t.length),r=u(e);for(let n=0;n=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|t}function g(t,e){if(f.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||W(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return G(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Y(t).length;default:if(i)return n?-1:G(t).length;e=(""+e).toLowerCase(),i=!0}}function y(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return x(this,e,r);case"ascii":return $(this,e,r);case"latin1":case"binary":return R(this,e,r);case"base64":return I(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function w(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function m(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),H(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=f.from(e,n)),f.isBuffer(e))return 0===e.length?-1:b(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):b(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(t,e,r,n,i){let o,s=1,u=t.length,f=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,f/=2,r/=2}function a(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){let n=-1;for(o=r;ou&&(r=u-f),o=r;o>=0;o--){let r=!0;for(let n=0;ni&&(n=i):n=i;const o=e.length;let s;for(n>o/2&&(n=o/2),s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function I(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function x(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+s<=r){let r,n,u,f;switch(s){case 1:e<128&&(o=e);break;case 2:r=t[i+1],128==(192&r)&&(f=(31&e)<<6|63&r,f>127&&(o=f));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(f=(15&e)<<12|(63&r)<<6|63&n,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:r=t[i+1],n=t[i+2],u=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&u)&&(f=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&u,f>65535&&f<1114112&&(o=f))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return function(t){const e=t.length;if(e<=U)return String.fromCharCode.apply(String,t);let r="",n=0;for(;nn.length?(f.isBuffer(e)||(e=f.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!f.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},f.byteLength=g,f.prototype._isBuffer=!0,f.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;er&&(t+=" ... "),""},o&&(f.prototype[o]=f.prototype.inspect),f.prototype.compare=function(t,e,r,n,i){if(W(t,Uint8Array)&&(t=f.from(t,t.offset,t.byteLength)),!f.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0);const u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r);for(let t=0;t>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return _(this,t,e,r);case"utf8":case"utf-8":return B(this,t,e,r);case"ascii":case"latin1":case"binary":return E(this,t,e,r);case"base64":return v(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},f.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const U=4096;function $(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;in)&&(r=n);let i="";for(let n=e;nr)throw new RangeError("Trying to access beyond buffer length")}function N(t,e,r,n,i,o){if(!f.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function S(t,e,r,n,i){P(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,r}function V(t,e,r,n,i){P(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r+7]=o,o>>=8,t[r+6]=o,o>>=8,t[r+5]=o,o>>=8,t[r+4]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=s,s>>=8,t[r+2]=s,s>>=8,t[r+1]=s,s>>=8,t[r]=s,r+8}function M(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function C(t,e,r,n,o){return e=+e,r>>>=0,o||M(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function D(t,e,r,n,o){return e=+e,r>>>=0,o||M(t,0,r,8),i.write(t,e,r,n,52,8),r+8}f.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t],i=1,o=0;for(;++o>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},f.prototype.readUint8=f.prototype.readUInt8=function(t,e){return t>>>=0,e||L(t,1,this.length),this[t]},f.prototype.readUint16LE=f.prototype.readUInt16LE=function(t,e){return t>>>=0,e||L(t,2,this.length),this[t]|this[t+1]<<8},f.prototype.readUint16BE=f.prototype.readUInt16BE=function(t,e){return t>>>=0,e||L(t,2,this.length),this[t]<<8|this[t+1]},f.prototype.readUint32LE=f.prototype.readUInt32LE=function(t,e){return t>>>=0,e||L(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},f.prototype.readUint32BE=f.prototype.readUInt32BE=function(t,e){return t>>>=0,e||L(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},f.prototype.readBigUInt64LE=Z((function(t){X(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t],i=1,o=0;for(;++o=i&&(n-=Math.pow(2,8*e)),n},f.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||L(t,e,this.length);let n=e,i=1,o=this[t+--n];for(;n>0&&(i*=256);)o+=this[t+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*e)),o},f.prototype.readInt8=function(t,e){return t>>>=0,e||L(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},f.prototype.readInt16LE=function(t,e){t>>>=0,e||L(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},f.prototype.readInt16BE=function(t,e){t>>>=0,e||L(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},f.prototype.readInt32LE=function(t,e){return t>>>=0,e||L(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},f.prototype.readInt32BE=function(t,e){return t>>>=0,e||L(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},f.prototype.readBigInt64LE=Z((function(t){X(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<>>=0,e||L(t,4,this.length),i.read(this,t,!0,23,4)},f.prototype.readFloatBE=function(t,e){return t>>>=0,e||L(t,4,this.length),i.read(this,t,!1,23,4)},f.prototype.readDoubleLE=function(t,e){return t>>>=0,e||L(t,8,this.length),i.read(this,t,!0,52,8)},f.prototype.readDoubleBE=function(t,e){return t>>>=0,e||L(t,8,this.length),i.read(this,t,!1,52,8)},f.prototype.writeUintLE=f.prototype.writeUIntLE=function(t,e,r,n){if(t=+t,e>>>=0,r>>>=0,!n){N(this,t,e,r,Math.pow(2,8*r)-1,0)}let i=1,o=0;for(this[e]=255&t;++o>>=0,r>>>=0,!n){N(this,t,e,r,Math.pow(2,8*r)-1,0)}let i=r-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+r},f.prototype.writeUint8=f.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,1,255,0),this[e]=255&t,e+1},f.prototype.writeUint16LE=f.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},f.prototype.writeUint16BE=f.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},f.prototype.writeUint32LE=f.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},f.prototype.writeUint32BE=f.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},f.prototype.writeBigUInt64LE=Z((function(t,e=0){return S(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),f.prototype.writeBigUInt64BE=Z((function(t,e=0){return V(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),f.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);N(this,t,e,r,n-1,-n)}let i=0,o=1,s=0;for(this[e]=255&t;++i>>=0,!n){const n=Math.pow(2,8*r-1);N(this,t,e,r,n-1,-n)}let i=r-1,o=1,s=0;for(this[e+i]=255&t;--i>=0&&(o*=256);)t<0&&0===s&&0!==this[e+i+1]&&(s=1),this[e+i]=(t/o|0)-s&255;return e+r},f.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},f.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},f.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},f.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},f.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},f.prototype.writeBigInt64LE=Z((function(t,e=0){return S(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),f.prototype.writeBigInt64BE=Z((function(t,e=0){return V(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),f.prototype.writeFloatLE=function(t,e,r){return C(this,t,e,!0,r)},f.prototype.writeFloatBE=function(t,e,r){return C(this,t,e,!1,r)},f.prototype.writeDoubleLE=function(t,e,r){return D(this,t,e,!0,r)},f.prototype.writeDoubleBE=function(t,e,r){return D(this,t,e,!1,r)},f.prototype.copy=function(t,e,r,n){if(!f.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function P(t,e,r,n,i,o){if(t>r||t3?0===e||e===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`:`>= ${e}${n} and <= ${r}${n}`,new j.ERR_OUT_OF_RANGE("value",i,t)}!function(t,e,r){X(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||k(e,t.length-(r+1))}(n,i,o)}function X(t,e){if("number"!=typeof t)throw new j.ERR_INVALID_ARG_TYPE(e,"number",t)}function k(t,e,r){if(Math.floor(t)!==t)throw X(t,r),new j.ERR_OUT_OF_RANGE(r||"offset","an integer",t);if(e<0)throw new j.ERR_BUFFER_OUT_OF_BOUNDS;throw new j.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}z("ERR_BUFFER_OUT_OF_BOUNDS",(function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),z("ERR_INVALID_ARG_TYPE",(function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`}),TypeError),z("ERR_OUT_OF_RANGE",(function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=F(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=F(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n}),RangeError);const q=/[^+/0-9A-Za-z-_]/g;function G(t,e){let r;e=e||1/0;const n=t.length;let i=null;const o=[];for(let s=0;s55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function Y(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(q,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function J(t,e,r,n){let i;for(i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function W(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function H(t){return t!=t}const Q=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function Z(t){return"undefined"==typeof BigInt?K:t}function K(){throw new Error("BigInt not supported")}},251:(t,e)=>{e.read=function(t,e,r,n,i){var o,s,u=8*i-n-1,f=(1<>1,h=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-h)-1,p>>=-h,h+=u;h>0;o=256*o+t[e+c],c+=l,h-=8);for(s=o&(1<<-h)-1,o>>=-h,h+=n;h>0;s=256*s+t[e+c],c+=l,h-=8);if(0===o)o=1-a;else{if(o===f)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=a}return(p?-1:1)*s*Math.pow(2,o-n)},e.write=function(t,e,r,n,i,o){var s,u,f,a=8*o-i-1,h=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=h):(s=Math.floor(Math.log(e)/Math.LN2),e*(f=Math.pow(2,-s))<1&&(s--,f*=2),(e+=s+c>=1?l/f:l*Math.pow(2,1-c))*f>=2&&(s++,f/=2),s+c>=h?(u=0,s=h):s+c>=1?(u=(e*f-1)*Math.pow(2,i),s+=c):(u=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,a-=8);t[r+p-d]|=128*g}}},e={};function r(n){var i=e[n];if(void 0!==i)return i.exports;var o=e[n]={exports:{}};return t[n](o,o.exports,r),o.exports}return r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r(281)})())); +//# sourceMappingURL=xdr.js.map + +/***/ }), + +/***/ 2135: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Account = void 0; +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Account object. + * + * `Account` represents a single account in the Stellar network and its sequence + * number. Account tracks the sequence number as it is used by {@link + * TransactionBuilder}. See + * [Accounts](https://developers.stellar.org/docs/glossary/accounts/) for + * more information about how accounts work in Stellar. + * + * @constructor + * + * @param {string} accountId - ID of the account (ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`). If you + * provide a muxed account address, this will throw; use {@link + * MuxedAccount} instead. + * @param {string} sequence - current sequence number of the account + */ +var Account = exports.Account = /*#__PURE__*/function () { + function Account(accountId, sequence) { + _classCallCheck(this, Account); + if (_strkey.StrKey.isValidMed25519PublicKey(accountId)) { + throw new Error('accountId is an M-address; use MuxedAccount instead'); + } + if (!_strkey.StrKey.isValidEd25519PublicKey(accountId)) { + throw new Error('accountId is invalid'); + } + if (!(typeof sequence === 'string')) { + throw new Error('sequence must be of type string'); + } + this._accountId = accountId; + this.sequence = new _bignumber["default"](sequence); + } + + /** + * Returns Stellar account ID, ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`. + * @returns {string} + */ + return _createClass(Account, [{ + key: "accountId", + value: function accountId() { + return this._accountId; + } + + /** + * @returns {string} sequence number for the account as a string + */ + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this.sequence.toString(); + } + + /** + * Increments sequence number in this object by one. + * @returns {void} + */ + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + this.sequence = this.sequence.plus(1); + } + }]); +}(); + +/***/ }), + +/***/ 1180: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Address = void 0; +var _strkey = __webpack_require__(7120); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Address object. + * + * `Address` represents a single address in the Stellar network. An address can + * represent an account or a contract. + * + * @constructor + * + * @param {string} address - ID of the account (ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`). If you + * provide a muxed account address, this will throw; use {@link + * MuxedAccount} instead. + */ +var Address = exports.Address = /*#__PURE__*/function () { + function Address(address) { + _classCallCheck(this, Address); + if (_strkey.StrKey.isValidEd25519PublicKey(address)) { + this._type = 'account'; + this._key = _strkey.StrKey.decodeEd25519PublicKey(address); + } else if (_strkey.StrKey.isValidContract(address)) { + this._type = 'contract'; + this._key = _strkey.StrKey.decodeContract(address); + } else { + throw new Error("Unsupported address type: ".concat(address)); + } + } + + /** + * Parses a string and returns an Address object. + * + * @param {string} address - The address to parse. ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA` + * @returns {Address} + */ + return _createClass(Address, [{ + key: "toString", + value: + /** + * Serialize an address to string. + * + * @returns {string} + */ + function toString() { + switch (this._type) { + case 'account': + return _strkey.StrKey.encodeEd25519PublicKey(this._key); + case 'contract': + return _strkey.StrKey.encodeContract(this._key); + default: + throw new Error('Unsupported address type'); + } + } + + /** + * Convert this Address to an xdr.ScVal type. + * + * @returns {xdr.ScVal} + */ + }, { + key: "toScVal", + value: function toScVal() { + return _xdr["default"].ScVal.scvAddress(this.toScAddress()); + } + + /** + * Convert this Address to an xdr.ScAddress type. + * + * @returns {xdr.ScAddress} + */ + }, { + key: "toScAddress", + value: function toScAddress() { + switch (this._type) { + case 'account': + return _xdr["default"].ScAddress.scAddressTypeAccount(_xdr["default"].PublicKey.publicKeyTypeEd25519(this._key)); + case 'contract': + return _xdr["default"].ScAddress.scAddressTypeContract(this._key); + default: + throw new Error('Unsupported address type'); + } + } + + /** + * Return the raw public key bytes for this address. + * + * @returns {Buffer} + */ + }, { + key: "toBuffer", + value: function toBuffer() { + return this._key; + } + }], [{ + key: "fromString", + value: function fromString(address) { + return new Address(address); + } + + /** + * Creates a new account Address object from a buffer of raw bytes. + * + * @param {Buffer} buffer - The bytes of an address to parse. + * @returns {Address} + */ + }, { + key: "account", + value: function account(buffer) { + return new Address(_strkey.StrKey.encodeEd25519PublicKey(buffer)); + } + + /** + * Creates a new contract Address object from a buffer of raw bytes. + * + * @param {Buffer} buffer - The bytes of an address to parse. + * @returns {Address} + */ + }, { + key: "contract", + value: function contract(buffer) { + return new Address(_strkey.StrKey.encodeContract(buffer)); + } + + /** + * Convert this from an xdr.ScVal type + * + * @param {xdr.ScVal} scVal - The xdr.ScVal type to parse + * @returns {Address} + */ + }, { + key: "fromScVal", + value: function fromScVal(scVal) { + return Address.fromScAddress(scVal.address()); + } + + /** + * Convert this from an xdr.ScAddress type + * + * @param {xdr.ScAddress} scAddress - The xdr.ScAddress type to parse + * @returns {Address} + */ + }, { + key: "fromScAddress", + value: function fromScAddress(scAddress) { + switch (scAddress["switch"]()) { + case _xdr["default"].ScAddressType.scAddressTypeAccount(): + return Address.account(scAddress.accountId().ed25519()); + case _xdr["default"].ScAddressType.scAddressTypeContract(): + return Address.contract(scAddress.contractId()); + default: + throw new Error('Unsupported address type'); + } + } + }]); +}(); + +/***/ }), + +/***/ 1764: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Asset = void 0; +var _util = __webpack_require__(645); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +var _hashing = __webpack_require__(9152); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Asset class represents an asset, either the native asset (`XLM`) + * or an asset code / issuer account ID pair. + * + * An asset code describes an asset code and issuer pair. In the case of the native + * asset XLM, the issuer will be null. + * + * @constructor + * @param {string} code - The asset code. + * @param {string} issuer - The account ID of the issuer. + */ +var Asset = exports.Asset = /*#__PURE__*/function () { + function Asset(code, issuer) { + _classCallCheck(this, Asset); + if (!/^[a-zA-Z0-9]{1,12}$/.test(code)) { + throw new Error('Asset code is invalid (maximum alphanumeric, 12 characters at max)'); + } + if (String(code).toLowerCase() !== 'xlm' && !issuer) { + throw new Error('Issuer cannot be null'); + } + if (issuer && !_strkey.StrKey.isValidEd25519PublicKey(issuer)) { + throw new Error('Issuer is invalid'); + } + if (String(code).toLowerCase() === 'xlm') { + // transform all xLM, Xlm, etc. variants -> XLM + this.code = 'XLM'; + } else { + this.code = code; + } + this.issuer = issuer; + } + + /** + * Returns an asset object for the native asset. + * @Return {Asset} + */ + return _createClass(Asset, [{ + key: "toXDRObject", + value: + /** + * Returns the xdr.Asset object for this asset. + * @returns {xdr.Asset} XDR asset object + */ + function toXDRObject() { + return this._toXDRObject(_xdr["default"].Asset); + } + + /** + * Returns the xdr.ChangeTrustAsset object for this asset. + * @returns {xdr.ChangeTrustAsset} XDR asset object + */ + }, { + key: "toChangeTrustXDRObject", + value: function toChangeTrustXDRObject() { + return this._toXDRObject(_xdr["default"].ChangeTrustAsset); + } + + /** + * Returns the xdr.TrustLineAsset object for this asset. + * @returns {xdr.TrustLineAsset} XDR asset object + */ + }, { + key: "toTrustLineXDRObject", + value: function toTrustLineXDRObject() { + return this._toXDRObject(_xdr["default"].TrustLineAsset); + } + + /** + * Returns the would-be contract ID (`C...` format) for this asset on a given + * network. + * + * @param {string} networkPassphrase indicates which network the contract + * ID should refer to, since every network will have a unique ID for the + * same contract (see {@link Networks} for options) + * + * @returns {string} the strkey-encoded (`C...`) contract ID for this asset + * + * @warning This makes no guarantee that this contract actually *exists*. + */ + }, { + key: "contractId", + value: function contractId(networkPassphrase) { + var networkId = (0, _hashing.hash)(Buffer.from(networkPassphrase)); + var preimage = _xdr["default"].HashIdPreimage.envelopeTypeContractId(new _xdr["default"].HashIdPreimageContractId({ + networkId: networkId, + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAsset(this.toXDRObject()) + })); + return _strkey.StrKey.encodeContract((0, _hashing.hash)(preimage.toXDR())); + } + + /** + * Returns the xdr object for this asset. + * @param {xdr.Asset | xdr.ChangeTrustAsset} xdrAsset - The asset xdr object. + * @returns {xdr.Asset | xdr.ChangeTrustAsset | xdr.TrustLineAsset} XDR Asset object + */ + }, { + key: "_toXDRObject", + value: function _toXDRObject() { + var xdrAsset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _xdr["default"].Asset; + if (this.isNative()) { + return xdrAsset.assetTypeNative(); + } + var xdrType; + var xdrTypeString; + if (this.code.length <= 4) { + xdrType = _xdr["default"].AlphaNum4; + xdrTypeString = 'assetTypeCreditAlphanum4'; + } else { + xdrType = _xdr["default"].AlphaNum12; + xdrTypeString = 'assetTypeCreditAlphanum12'; + } + + // pad code with null bytes if necessary + var padLength = this.code.length <= 4 ? 4 : 12; + var paddedCode = this.code.padEnd(padLength, '\0'); + + // eslint-disable-next-line new-cap + var assetType = new xdrType({ + assetCode: paddedCode, + issuer: _keypair.Keypair.fromPublicKey(this.issuer).xdrAccountId() + }); + return new xdrAsset(xdrTypeString, assetType); + } + + /** + * @returns {string} Asset code + */ + }, { + key: "getCode", + value: function getCode() { + if (this.code === undefined) { + return undefined; + } + return String(this.code); + } + + /** + * @returns {string} Asset issuer + */ + }, { + key: "getIssuer", + value: function getIssuer() { + if (this.issuer === undefined) { + return undefined; + } + return String(this.issuer); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {string} Asset type. Can be one of following types: + * + * - `native`, + * - `credit_alphanum4`, + * - `credit_alphanum12`, or + * - `unknown` as the error case (which should never occur) + */ + }, { + key: "getAssetType", + value: function getAssetType() { + switch (this.getRawAssetType().value) { + case _xdr["default"].AssetType.assetTypeNative().value: + return 'native'; + case _xdr["default"].AssetType.assetTypeCreditAlphanum4().value: + return 'credit_alphanum4'; + case _xdr["default"].AssetType.assetTypeCreditAlphanum12().value: + return 'credit_alphanum12'; + default: + return 'unknown'; + } + } + + /** + * @returns {xdr.AssetType} the raw XDR representation of the asset type + */ + }, { + key: "getRawAssetType", + value: function getRawAssetType() { + if (this.isNative()) { + return _xdr["default"].AssetType.assetTypeNative(); + } + if (this.code.length <= 4) { + return _xdr["default"].AssetType.assetTypeCreditAlphanum4(); + } + return _xdr["default"].AssetType.assetTypeCreditAlphanum12(); + } + + /** + * @returns {boolean} true if this asset object is the native asset. + */ + }, { + key: "isNative", + value: function isNative() { + return !this.issuer; + } + + /** + * @param {Asset} asset Asset to compare + * @returns {boolean} true if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(asset) { + return this.code === asset.getCode() && this.issuer === asset.getIssuer(); + } + }, { + key: "toString", + value: function toString() { + if (this.isNative()) { + return 'native'; + } + return "".concat(this.getCode(), ":").concat(this.getIssuer()); + } + + /** + * Compares two assets according to the criteria: + * + * 1. First compare the type (native < alphanum4 < alphanum12). + * 2. If the types are equal, compare the assets codes. + * 3. If the asset codes are equal, compare the issuers. + * + * @param {Asset} assetA - the first asset + * @param {Asset} assetB - the second asset + * @returns {number} `-1` if assetA < assetB, `0` if assetA == assetB, `1` if assetA > assetB. + * + * @static + * @memberof Asset + */ + }], [{ + key: "native", + value: function _native() { + return new Asset('XLM'); + } + + /** + * Returns an asset object from its XDR object representation. + * @param {xdr.Asset} assetXdr - The asset xdr object. + * @returns {Asset} + */ + }, { + key: "fromOperation", + value: function fromOperation(assetXdr) { + var anum; + var code; + var issuer; + switch (assetXdr["switch"]()) { + case _xdr["default"].AssetType.assetTypeNative(): + return this["native"](); + case _xdr["default"].AssetType.assetTypeCreditAlphanum4(): + anum = assetXdr.alphaNum4(); + /* falls through */ + case _xdr["default"].AssetType.assetTypeCreditAlphanum12(): + anum = anum || assetXdr.alphaNum12(); + issuer = _strkey.StrKey.encodeEd25519PublicKey(anum.issuer().ed25519()); + code = (0, _util.trimEnd)(anum.assetCode(), '\0'); + return new this(code, issuer); + default: + throw new Error("Invalid asset type: ".concat(assetXdr["switch"]().name)); + } + } + }, { + key: "compare", + value: function compare(assetA, assetB) { + if (!assetA || !(assetA instanceof Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof Asset)) { + throw new Error('assetB is invalid'); + } + if (assetA.equals(assetB)) { + return 0; + } + + // Compare asset types. + var xdrAtype = assetA.getRawAssetType().value; + var xdrBtype = assetB.getRawAssetType().value; + if (xdrAtype !== xdrBtype) { + return xdrAtype < xdrBtype ? -1 : 1; + } + + // Compare asset codes. + var result = asciiCompare(assetA.getCode(), assetB.getCode()); + if (result !== 0) { + return result; + } + + // Compare asset issuers. + return asciiCompare(assetA.getIssuer(), assetB.getIssuer()); + } + }]); +}(); +/** + * Compares two ASCII strings in lexographic order with uppercase precedence. + * + * @param {string} a - the first string to compare + * @param {string} b - the second + * @returns {number} like all `compare()`s: + * -1 if `a < b`, 0 if `a == b`, and 1 if `a > b` + * + * @warning No type-checks are done on the parameters + */ +function asciiCompare(a, b) { + return Buffer.compare(Buffer.from(a, 'ascii'), Buffer.from(b, 'ascii')); +} + +/***/ }), + +/***/ 5328: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.authorizeEntry = authorizeEntry; +exports.authorizeInvocation = authorizeInvocation; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +var _network = __webpack_require__(6202); +var _hashing = __webpack_require__(9152); +var _address = __webpack_require__(1180); +var _scval = __webpack_require__(7177); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +/** + * @async + * @callback SigningCallback A callback for signing an XDR structure + * representing all of the details necessary to authorize an invocation tree. + * + * @param {xdr.HashIdPreimage} preimage the entire authorization envelope + * whose hash you should sign, so that you can inspect the entire structure + * if necessary (rather than blindly signing a hash) + * + * @returns {Promise} the signature of the raw payload (which is + * the sha256 hash of the preimage bytes, so `hash(preimage.toXDR())`) signed + * by the key corresponding to the public key in the entry you pass to + * {@link authorizeEntry} (decipherable from its + * `credentials().address().address()`) + */ +/** + * Actually authorizes an existing authorization entry using the given the + * credentials and expiration details, returning a signed copy. + * + * This "fills out" the authorization entry with a signature, indicating to the + * {@link Operation.invokeHostFunction} its attached to that: + * - a particular identity (i.e. signing {@link Keypair} or other signer) + * - approving the execution of an invocation tree (i.e. a simulation-acquired + * {@link xdr.SorobanAuthorizedInvocation} or otherwise built) + * - on a particular network (uniquely identified by its passphrase, see + * {@link Networks}) + * - until a particular ledger sequence is reached. + * + * This one lets you pass a either a {@link Keypair} (or, more accurately, + * anything with a `sign(Buffer): Buffer` method) or a callback function (see + * {@link SigningCallback}) to handle signing the envelope hash. + * + * @param {xdr.SorobanAuthorizationEntry} entry an unsigned authorization entr + * @param {Keypair | SigningCallback} signer either a {@link Keypair} instance + * or a function which takes a payload (a + * {@link xdr.HashIdPreimageSorobanAuthorization} instance) input and returns + * the signature of the hash of the raw payload bytes (where the signing key + * should correspond to the address in the `entry`) + * @param {number} validUntilLedgerSeq the (exclusive) future ledger sequence + * number until which this authorization entry should be valid (if + * `currentLedgerSeq==validUntil`, this is expired)) + * @param {string} [networkPassphrase] the network passphrase is incorprated + * into the signature (see {@link Networks} for options) + * + * @returns {Promise} a promise for an + * authorization entry that you can pass along to + * {@link Operation.invokeHostFunction} + * + * @note If using the `SigningCallback` variation, the signer is assumed to be + * the entry's credential address. If you need a different key to sign the + * entry, you will need to use different method (e.g., fork this code). + * + * @see authorizeInvocation + * @example + * import { + * SorobanRpc, + * Transaction, + * Networks, + * authorizeEntry + * } from '@stellar/stellar-sdk'; + * + * // Assume signPayloadCallback is a well-formed signing callback. + * // + * // It might, for example, pop up a modal from a browser extension, send the + * // transaction to a third-party service for signing, or just do simple + * // signing via Keypair like it does here: + * function signPayloadCallback(payload) { + * return signer.sign(hash(payload.toXDR()); + * } + * + * function multiPartyAuth( + * server: SorobanRpc.Server, + * // assume this involves multi-party auth + * tx: Transaction, + * ) { + * return server + * .simulateTransaction(tx) + * .then((simResult) => { + * tx.operations[0].auth.map(entry => + * authorizeEntry( + * entry, + * signPayloadCallback, + * currentLedger + 1000, + * Networks.TESTNET); + * )); + * + * return server.prepareTransaction(tx, simResult); + * }) + * .then((preppedTx) => { + * preppedTx.sign(source); + * return server.sendTransaction(preppedTx); + * }); + * } + */ +function authorizeEntry(_x, _x2, _x3) { + return _authorizeEntry.apply(this, arguments); +} +/** + * This builds an entry from scratch, allowing you to express authorization as a + * function of: + * - a particular identity (i.e. signing {@link Keypair} or other signer) + * - approving the execution of an invocation tree (i.e. a simulation-acquired + * {@link xdr.SorobanAuthorizedInvocation} or otherwise built) + * - on a particular network (uniquely identified by its passphrase, see + * {@link Networks}) + * - until a particular ledger sequence is reached. + * + * This is in contrast to {@link authorizeEntry}, which signs an existing entry. + * + * @param {Keypair | SigningCallback} signer either a {@link Keypair} instance + * (or anything with a `.sign(buf): Buffer-like` method) or a function which + * takes a payload (a {@link xdr.HashIdPreimageSorobanAuthorization} + * instance) input and returns the signature of the hash of the raw payload + * bytes (where the signing key should correspond to the address in the + * `entry`) + * @param {number} validUntilLedgerSeq the (exclusive) future ledger sequence + * number until which this authorization entry should be valid (if + * `currentLedgerSeq==validUntilLedgerSeq`, this is expired)) + * @param {xdr.SorobanAuthorizedInvocation} invocation the invocation tree that + * we're authorizing (likely, this comes from transaction simulation) + * @param {string} [publicKey] the public identity of the signer (when + * providing a {@link Keypair} to `signer`, this can be omitted, as it just + * uses {@link Keypair.publicKey}) + * @param {string} [networkPassphrase] the network passphrase is incorprated + * into the signature (see {@link Networks} for options, default: + * {@link Networks.FUTURENET}) + * + * @returns {Promise} a promise for an + * authorization entry that you can pass along to + * {@link Operation.invokeHostFunction} + * + * @see authorizeEntry + */ +function _authorizeEntry() { + _authorizeEntry = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(entry, signer, validUntilLedgerSeq) { + var networkPassphrase, + clone, + addrAuth, + networkId, + preimage, + payload, + signature, + publicKey, + sigScVal, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + networkPassphrase = _args.length > 3 && _args[3] !== undefined ? _args[3] : _network.Networks.FUTURENET; + if (!(entry.credentials()["switch"]().value !== _xdr["default"].SorobanCredentialsType.sorobanCredentialsAddress().value)) { + _context.next = 3; + break; + } + return _context.abrupt("return", entry); + case 3: + clone = _xdr["default"].SorobanAuthorizationEntry.fromXDR(entry.toXDR()); + /** @type {xdr.SorobanAddressCredentials} */ + addrAuth = clone.credentials().address(); + addrAuth.signatureExpirationLedger(validUntilLedgerSeq); + networkId = (0, _hashing.hash)(Buffer.from(networkPassphrase)); + preimage = _xdr["default"].HashIdPreimage.envelopeTypeSorobanAuthorization(new _xdr["default"].HashIdPreimageSorobanAuthorization({ + networkId: networkId, + nonce: addrAuth.nonce(), + invocation: clone.rootInvocation(), + signatureExpirationLedger: addrAuth.signatureExpirationLedger() + })); + payload = (0, _hashing.hash)(preimage.toXDR()); + if (!(typeof signer === 'function')) { + _context.next = 18; + break; + } + _context.t0 = Buffer; + _context.next = 13; + return signer(preimage); + case 13: + _context.t1 = _context.sent; + signature = _context.t0.from.call(_context.t0, _context.t1); + publicKey = _address.Address.fromScAddress(addrAuth.address()).toString(); + _context.next = 20; + break; + case 18: + signature = Buffer.from(signer.sign(payload)); + publicKey = signer.publicKey(); + case 20: + if (_keypair.Keypair.fromPublicKey(publicKey).verify(payload, signature)) { + _context.next = 22; + break; + } + throw new Error("signature doesn't match payload"); + case 22: + // This structure is defined here: + // https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#stellar-account-signatures + // + // Encoding a contract structure as an ScVal means the map keys are supposed + // to be symbols, hence the forced typing here. + sigScVal = (0, _scval.nativeToScVal)({ + public_key: _strkey.StrKey.decodeEd25519PublicKey(publicKey), + signature: signature + }, { + type: { + public_key: ['symbol', null], + signature: ['symbol', null] + } + }); + addrAuth.signature(_xdr["default"].ScVal.scvVec([sigScVal])); + return _context.abrupt("return", clone); + case 25: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _authorizeEntry.apply(this, arguments); +} +function authorizeInvocation(signer, validUntilLedgerSeq, invocation) { + var publicKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; + var networkPassphrase = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : _network.Networks.FUTURENET; + // We use keypairs as a source of randomness for the nonce to avoid mucking + // with any crypto dependencies. Note that this just has to be random and + // unique, not cryptographically secure, so it's fine. + var kp = _keypair.Keypair.random().rawPublicKey(); + var nonce = new _xdr["default"].Int64(bytesToInt64(kp)); + var pk = publicKey || signer.publicKey(); + if (!pk) { + throw new Error("authorizeInvocation requires publicKey parameter"); + } + var entry = new _xdr["default"].SorobanAuthorizationEntry({ + rootInvocation: invocation, + credentials: _xdr["default"].SorobanCredentials.sorobanCredentialsAddress(new _xdr["default"].SorobanAddressCredentials({ + address: new _address.Address(pk).toScAddress(), + nonce: nonce, + signatureExpirationLedger: 0, + // replaced + signature: _xdr["default"].ScVal.scvVec([]) // replaced + })) + }); + return authorizeEntry(entry, signer, validUntilLedgerSeq, networkPassphrase); +} +function bytesToInt64(bytes) { + // eslint-disable-next-line no-bitwise + return bytes.subarray(0, 8).reduce(function (accum, b) { + return accum << 8 | b; + }, 0); +} + +/***/ }), + +/***/ 1387: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Claimant = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Claimant class represents an xdr.Claimant + * + * The claim predicate is optional, it defaults to unconditional if none is specified. + * + * @constructor + * @param {string} destination - The destination account ID. + * @param {xdr.ClaimPredicate} [predicate] - The claim predicate. + */ +var Claimant = exports.Claimant = /*#__PURE__*/function () { + function Claimant(destination, predicate) { + _classCallCheck(this, Claimant); + if (destination && !_strkey.StrKey.isValidEd25519PublicKey(destination)) { + throw new Error('Destination is invalid'); + } + this._destination = destination; + if (!predicate) { + this._predicate = _xdr["default"].ClaimPredicate.claimPredicateUnconditional(); + } else if (predicate instanceof _xdr["default"].ClaimPredicate) { + this._predicate = predicate; + } else { + throw new Error('Predicate should be an xdr.ClaimPredicate'); + } + } + + /** + * Returns an unconditional claim predicate + * @Return {xdr.ClaimPredicate} + */ + return _createClass(Claimant, [{ + key: "toXDRObject", + value: + /** + * Returns the xdr object for this claimant. + * @returns {xdr.Claimant} XDR Claimant object + */ + function toXDRObject() { + var claimant = new _xdr["default"].ClaimantV0({ + destination: _keypair.Keypair.fromPublicKey(this._destination).xdrAccountId(), + predicate: this._predicate + }); + return _xdr["default"].Claimant.claimantTypeV0(claimant); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "destination", + get: function get() { + return this._destination; + }, + set: function set(value) { + throw new Error('Claimant is immutable'); + } + + /** + * @type {xdr.ClaimPredicate} + * @readonly + */ + }, { + key: "predicate", + get: function get() { + return this._predicate; + }, + set: function set(value) { + throw new Error('Claimant is immutable'); + } + }], [{ + key: "predicateUnconditional", + value: function predicateUnconditional() { + return _xdr["default"].ClaimPredicate.claimPredicateUnconditional(); + } + + /** + * Returns an `and` claim predicate + * @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate + * @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateAnd", + value: function predicateAnd(left, right) { + if (!(left instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('left Predicate should be an xdr.ClaimPredicate'); + } + if (!(right instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateAnd([left, right]); + } + + /** + * Returns an `or` claim predicate + * @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate + * @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateOr", + value: function predicateOr(left, right) { + if (!(left instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('left Predicate should be an xdr.ClaimPredicate'); + } + if (!(right instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateOr([left, right]); + } + + /** + * Returns a `not` claim predicate + * @param {xdr.ClaimPredicate} predicate an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateNot", + value: function predicateNot(predicate) { + if (!(predicate instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateNot(predicate); + } + + /** + * Returns a `BeforeAbsoluteTime` claim predicate + * + * This predicate will be fulfilled if the closing time of the ledger that + * includes the CreateClaimableBalance operation is less than this (absolute) + * Unix timestamp (expressed in seconds). + * + * @param {string} absBefore Unix epoch (in seconds) as a string + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateBeforeAbsoluteTime", + value: function predicateBeforeAbsoluteTime(absBefore) { + return _xdr["default"].ClaimPredicate.claimPredicateBeforeAbsoluteTime(_xdr["default"].Int64.fromString(absBefore)); + } + + /** + * Returns a `BeforeRelativeTime` claim predicate + * + * This predicate will be fulfilled if the closing time of the ledger that + * includes the CreateClaimableBalance operation plus this relative time delta + * (in seconds) is less than the current time. + * + * @param {strings} seconds seconds since closeTime of the ledger in which the ClaimableBalanceEntry was created (as string) + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateBeforeRelativeTime", + value: function predicateBeforeRelativeTime(seconds) { + return _xdr["default"].ClaimPredicate.claimPredicateBeforeRelativeTime(_xdr["default"].Int64.fromString(seconds)); + } + + /** + * Returns a claimant object from its XDR object representation. + * @param {xdr.Claimant} claimantXdr - The claimant xdr object. + * @returns {Claimant} + */ + }, { + key: "fromXDR", + value: function fromXDR(claimantXdr) { + var value; + switch (claimantXdr["switch"]()) { + case _xdr["default"].ClaimantType.claimantTypeV0(): + value = claimantXdr.v0(); + return new this(_strkey.StrKey.encodeEd25519PublicKey(value.destination().ed25519()), value.predicate()); + default: + throw new Error("Invalid claimant type: ".concat(claimantXdr["switch"]().name)); + } + } + }]); +}(); + +/***/ }), + +/***/ 7452: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Contract = void 0; +var _address = __webpack_require__(1180); +var _operation = __webpack_require__(7237); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Contract object. + * + * `Contract` represents a single contract in the Stellar network, embodying the + * interface of the contract. See + * [Contracts](https://soroban.stellar.org/docs/learn/interacting-with-contracts) + * for more information about how contracts work in Stellar. + * + * @constructor + * + * @param {string} contractId - ID of the contract (ex. + * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`). + */ +var Contract = exports.Contract = /*#__PURE__*/function () { + function Contract(contractId) { + _classCallCheck(this, Contract); + try { + // First, try it as a strkey + this._id = _strkey.StrKey.decodeContract(contractId); + } catch (_) { + throw new Error("Invalid contract ID: ".concat(contractId)); + } + } + + /** + * Returns Stellar contract ID as a strkey, ex. + * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`. + * @returns {string} + */ + return _createClass(Contract, [{ + key: "contractId", + value: function contractId() { + return _strkey.StrKey.encodeContract(this._id); + } + + /** @returns {string} the ID as a strkey (C...) */ + }, { + key: "toString", + value: function toString() { + return this.contractId(); + } + + /** @returns {Address} the wrapped address of this contract */ + }, { + key: "address", + value: function address() { + return _address.Address.contract(this._id); + } + + /** + * Returns an operation that will invoke this contract call. + * + * @param {string} method name of the method to call + * @param {...xdr.ScVal} params arguments to pass to the function call + * + * @returns {xdr.Operation} an InvokeHostFunctionOp operation to call the + * contract with the given method and parameters + * + * @see Operation.invokeHostFunction + * @see Operation.invokeContractFunction + * @see Operation.createCustomContract + * @see Operation.createStellarAssetContract + * @see Operation.uploadContractWasm + */ + }, { + key: "call", + value: function call(method) { + for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + params[_key - 1] = arguments[_key]; + } + return _operation.Operation.invokeContractFunction({ + contract: this.address().toString(), + "function": method, + args: params + }); + } + + /** + * Returns the read-only footprint entries necessary for any invocations to + * this contract, for convenience when manually adding it to your + * transaction's overall footprint or doing bump/restore operations. + * + * @returns {xdr.LedgerKey} the ledger key for the deployed contract instance + */ + }, { + key: "getFootprint", + value: function getFootprint() { + return _xdr["default"].LedgerKey.contractData(new _xdr["default"].LedgerKeyContractData({ + contract: this.address().toScAddress(), + key: _xdr["default"].ScVal.scvLedgerKeyContractInstance(), + durability: _xdr["default"].ContractDataDurability.persistent() + })); + } + }]); +}(); + +/***/ }), + +/***/ 3919: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.humanizeEvents = humanizeEvents; +var _strkey = __webpack_require__(7120); +var _scval = __webpack_require__(7177); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Converts raw diagnostic or contract events into something with a flatter, + * human-readable, and understandable structure. + * + * @param {xdr.DiagnosticEvent[] | xdr.ContractEvent[]} events either contract + * events or diagnostic events to parse into a friendly format + * + * @returns {SorobanEvent[]} a list of human-readable event structures, where + * each element has the following properties: + * - type: a string of one of 'system', 'contract', 'diagnostic + * - contractId?: optionally, a `C...` encoded strkey + * - topics: a list of {@link scValToNative} invocations on the topics + * - data: similarly, a {@link scValToNative} invocation on the raw event data + */ +function humanizeEvents(events) { + return events.map(function (e) { + // A pseudo-instanceof check for xdr.DiagnosticEvent more reliable + // in mixed SDK environments: + if (e.inSuccessfulContractCall) { + return extractEvent(e.event()); + } + return extractEvent(e); + }); +} +function extractEvent(event) { + return _objectSpread(_objectSpread({}, typeof event.contractId === 'function' && event.contractId() != null && { + contractId: _strkey.StrKey.encodeContract(event.contractId()) + }), {}, { + type: event.type().name, + topics: event.body().value().topics().map(function (t) { + return (0, _scval.scValToNative)(t); + }), + data: (0, _scval.scValToNative)(event.body().value().data()) + }); +} + +/***/ }), + +/***/ 9260: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.FeeBumpTransaction = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _hashing = __webpack_require__(9152); +var _transaction = __webpack_require__(380); +var _transaction_base = __webpack_require__(3758); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Use {@link TransactionBuilder.buildFeeBumpTransaction} to build a + * FeeBumpTransaction object. If you have an object or base64-encoded string of + * the transaction envelope XDR use {@link TransactionBuilder.fromXDR}. + * + * Once a {@link FeeBumpTransaction} has been created, its attributes and operations + * should not be changed. You should only add signatures (using {@link FeeBumpTransaction#sign}) before + * submitting to the network or forwarding on to additional signers. + * + * @param {string|xdr.TransactionEnvelope} envelope - transaction envelope + * object or base64 encoded string. + * @param {string} networkPassphrase - passphrase of the target Stellar network + * (e.g. "Public Global Stellar Network ; September 2015"). + * + * @extends TransactionBase + */ +var FeeBumpTransaction = exports.FeeBumpTransaction = /*#__PURE__*/function (_TransactionBase) { + function FeeBumpTransaction(envelope, networkPassphrase) { + var _this; + _classCallCheck(this, FeeBumpTransaction); + if (typeof envelope === 'string') { + var buffer = Buffer.from(envelope, 'base64'); + envelope = _xdr["default"].TransactionEnvelope.fromXDR(buffer); + } + var envelopeType = envelope["switch"](); + if (envelopeType !== _xdr["default"].EnvelopeType.envelopeTypeTxFeeBump()) { + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxFeeBump but received an ".concat(envelopeType.name, ".")); + } + var txEnvelope = envelope.value(); + var tx = txEnvelope.tx(); + var fee = tx.fee().toString(); + // clone signatures + var signatures = (txEnvelope.signatures() || []).slice(); + _this = _callSuper(this, FeeBumpTransaction, [tx, signatures, fee, networkPassphrase]); + var innerTxEnvelope = _xdr["default"].TransactionEnvelope.envelopeTypeTx(tx.innerTx().v1()); + _this._feeSource = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(_this.tx.feeSource()); + _this._innerTransaction = new _transaction.Transaction(innerTxEnvelope, networkPassphrase); + return _this; + } + + /** + * @type {Transaction} + * @readonly + */ + _inherits(FeeBumpTransaction, _TransactionBase); + return _createClass(FeeBumpTransaction, [{ + key: "innerTransaction", + get: function get() { + return this._innerTransaction; + } + + /** + * @type {Operation[]} + * @readonly + */ + }, { + key: "operations", + get: function get() { + return this._innerTransaction.operations; + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "feeSource", + get: function get() { + return this._feeSource; + } + + /** + * Returns the "signature base" of this transaction, which is the value + * that, when hashed, should be signed to create a signature that + * validators on the Stellar Network will accept. + * + * It is composed of a 4 prefix bytes followed by the xdr-encoded form + * of this transaction. + * @returns {Buffer} + */ + }, { + key: "signatureBase", + value: function signatureBase() { + var taggedTransaction = new _xdr["default"].TransactionSignaturePayloadTaggedTransaction.envelopeTypeTxFeeBump(this.tx); + var txSignature = new _xdr["default"].TransactionSignaturePayload({ + networkId: _xdr["default"].Hash.fromXDR((0, _hashing.hash)(this.networkPassphrase)), + taggedTransaction: taggedTransaction + }); + return txSignature.toXDR(); + } + + /** + * To envelope returns a xdr.TransactionEnvelope which can be submitted to the network. + * @returns {xdr.TransactionEnvelope} + */ + }, { + key: "toEnvelope", + value: function toEnvelope() { + var envelope = new _xdr["default"].FeeBumpTransactionEnvelope({ + tx: _xdr["default"].FeeBumpTransaction.fromXDR(this.tx.toXDR()), + // make a copy of the tx + signatures: this.signatures.slice() // make a copy of the signatures + }); + return new _xdr["default"].TransactionEnvelope.envelopeTypeTxFeeBump(envelope); + } + }]); +}(_transaction_base.TransactionBase); + +/***/ }), + +/***/ 7938: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var XDR = _interopRequireWildcard(__webpack_require__(3740)); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +// Automatically generated by xdrgen on 2024-09-12T11:09:00-08:00 +// DO NOT EDIT or your changes may be overwritten + +/* jshint maxstatements:2147483647 */ +/* jshint esnext:true */ + +var types = XDR.config(function (xdr) { + // Workaround for https://github.com/stellar/xdrgen/issues/152 + // + // The "correct" way would be to replace bare instances of each constant with + // xdr.lookup("..."), but that's more error-prone. + var SCSYMBOL_LIMIT = 32; + var SC_SPEC_DOC_LIMIT = 1024; + + // === xdr source ============================================================ + // + // typedef opaque Value<>; + // + // =========================================================================== + xdr.typedef("Value", xdr.varOpaque()); + + // === xdr source ============================================================ + // + // struct SCPBallot + // { + // uint32 counter; // n + // Value value; // x + // }; + // + // =========================================================================== + xdr.struct("ScpBallot", [["counter", xdr.lookup("Uint32")], ["value", xdr.lookup("Value")]]); + + // === xdr source ============================================================ + // + // enum SCPStatementType + // { + // SCP_ST_PREPARE = 0, + // SCP_ST_CONFIRM = 1, + // SCP_ST_EXTERNALIZE = 2, + // SCP_ST_NOMINATE = 3 + // }; + // + // =========================================================================== + xdr["enum"]("ScpStatementType", { + scpStPrepare: 0, + scpStConfirm: 1, + scpStExternalize: 2, + scpStNominate: 3 + }); + + // === xdr source ============================================================ + // + // struct SCPNomination + // { + // Hash quorumSetHash; // D + // Value votes<>; // X + // Value accepted<>; // Y + // }; + // + // =========================================================================== + xdr.struct("ScpNomination", [["quorumSetHash", xdr.lookup("Hash")], ["votes", xdr.varArray(xdr.lookup("Value"), 2147483647)], ["accepted", xdr.varArray(xdr.lookup("Value"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } + // + // =========================================================================== + xdr.struct("ScpStatementPrepare", [["quorumSetHash", xdr.lookup("Hash")], ["ballot", xdr.lookup("ScpBallot")], ["prepared", xdr.option(xdr.lookup("ScpBallot"))], ["preparedPrime", xdr.option(xdr.lookup("ScpBallot"))], ["nC", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } + // + // =========================================================================== + xdr.struct("ScpStatementConfirm", [["ballot", xdr.lookup("ScpBallot")], ["nPrepared", xdr.lookup("Uint32")], ["nCommit", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")], ["quorumSetHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } + // + // =========================================================================== + xdr.struct("ScpStatementExternalize", [["commit", xdr.lookup("ScpBallot")], ["nH", xdr.lookup("Uint32")], ["commitQuorumSetHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union switch (SCPStatementType type) + // { + // case SCP_ST_PREPARE: + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } prepare; + // case SCP_ST_CONFIRM: + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } confirm; + // case SCP_ST_EXTERNALIZE: + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } externalize; + // case SCP_ST_NOMINATE: + // SCPNomination nominate; + // } + // + // =========================================================================== + xdr.union("ScpStatementPledges", { + switchOn: xdr.lookup("ScpStatementType"), + switchName: "type", + switches: [["scpStPrepare", "prepare"], ["scpStConfirm", "confirm"], ["scpStExternalize", "externalize"], ["scpStNominate", "nominate"]], + arms: { + prepare: xdr.lookup("ScpStatementPrepare"), + confirm: xdr.lookup("ScpStatementConfirm"), + externalize: xdr.lookup("ScpStatementExternalize"), + nominate: xdr.lookup("ScpNomination") + } + }); + + // === xdr source ============================================================ + // + // struct SCPStatement + // { + // NodeID nodeID; // v + // uint64 slotIndex; // i + // + // union switch (SCPStatementType type) + // { + // case SCP_ST_PREPARE: + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } prepare; + // case SCP_ST_CONFIRM: + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } confirm; + // case SCP_ST_EXTERNALIZE: + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } externalize; + // case SCP_ST_NOMINATE: + // SCPNomination nominate; + // } + // pledges; + // }; + // + // =========================================================================== + xdr.struct("ScpStatement", [["nodeId", xdr.lookup("NodeId")], ["slotIndex", xdr.lookup("Uint64")], ["pledges", xdr.lookup("ScpStatementPledges")]]); + + // === xdr source ============================================================ + // + // struct SCPEnvelope + // { + // SCPStatement statement; + // Signature signature; + // }; + // + // =========================================================================== + xdr.struct("ScpEnvelope", [["statement", xdr.lookup("ScpStatement")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // struct SCPQuorumSet + // { + // uint32 threshold; + // NodeID validators<>; + // SCPQuorumSet innerSets<>; + // }; + // + // =========================================================================== + xdr.struct("ScpQuorumSet", [["threshold", xdr.lookup("Uint32")], ["validators", xdr.varArray(xdr.lookup("NodeId"), 2147483647)], ["innerSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)]]); + + // === xdr source ============================================================ + // + // typedef opaque Thresholds[4]; + // + // =========================================================================== + xdr.typedef("Thresholds", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef string string32<32>; + // + // =========================================================================== + xdr.typedef("String32", xdr.string(32)); + + // === xdr source ============================================================ + // + // typedef string string64<64>; + // + // =========================================================================== + xdr.typedef("String64", xdr.string(64)); + + // === xdr source ============================================================ + // + // typedef int64 SequenceNumber; + // + // =========================================================================== + xdr.typedef("SequenceNumber", xdr.lookup("Int64")); + + // === xdr source ============================================================ + // + // typedef opaque DataValue<64>; + // + // =========================================================================== + xdr.typedef("DataValue", xdr.varOpaque(64)); + + // === xdr source ============================================================ + // + // typedef Hash PoolID; + // + // =========================================================================== + xdr.typedef("PoolId", xdr.lookup("Hash")); + + // === xdr source ============================================================ + // + // typedef opaque AssetCode4[4]; + // + // =========================================================================== + xdr.typedef("AssetCode4", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef opaque AssetCode12[12]; + // + // =========================================================================== + xdr.typedef("AssetCode12", xdr.opaque(12)); + + // === xdr source ============================================================ + // + // enum AssetType + // { + // ASSET_TYPE_NATIVE = 0, + // ASSET_TYPE_CREDIT_ALPHANUM4 = 1, + // ASSET_TYPE_CREDIT_ALPHANUM12 = 2, + // ASSET_TYPE_POOL_SHARE = 3 + // }; + // + // =========================================================================== + xdr["enum"]("AssetType", { + assetTypeNative: 0, + assetTypeCreditAlphanum4: 1, + assetTypeCreditAlphanum12: 2, + assetTypePoolShare: 3 + }); + + // === xdr source ============================================================ + // + // union AssetCode switch (AssetType type) + // { + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AssetCode4 assetCode4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AssetCode12 assetCode12; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("AssetCode", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeCreditAlphanum4", "assetCode4"], ["assetTypeCreditAlphanum12", "assetCode12"]], + arms: { + assetCode4: xdr.lookup("AssetCode4"), + assetCode12: xdr.lookup("AssetCode12") + } + }); + + // === xdr source ============================================================ + // + // struct AlphaNum4 + // { + // AssetCode4 assetCode; + // AccountID issuer; + // }; + // + // =========================================================================== + xdr.struct("AlphaNum4", [["assetCode", xdr.lookup("AssetCode4")], ["issuer", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // struct AlphaNum12 + // { + // AssetCode12 assetCode; + // AccountID issuer; + // }; + // + // =========================================================================== + xdr.struct("AlphaNum12", [["assetCode", xdr.lookup("AssetCode12")], ["issuer", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // union Asset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("Asset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12") + } + }); + + // === xdr source ============================================================ + // + // struct Price + // { + // int32 n; // numerator + // int32 d; // denominator + // }; + // + // =========================================================================== + xdr.struct("Price", [["n", xdr.lookup("Int32")], ["d", xdr.lookup("Int32")]]); + + // === xdr source ============================================================ + // + // struct Liabilities + // { + // int64 buying; + // int64 selling; + // }; + // + // =========================================================================== + xdr.struct("Liabilities", [["buying", xdr.lookup("Int64")], ["selling", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum ThresholdIndexes + // { + // THRESHOLD_MASTER_WEIGHT = 0, + // THRESHOLD_LOW = 1, + // THRESHOLD_MED = 2, + // THRESHOLD_HIGH = 3 + // }; + // + // =========================================================================== + xdr["enum"]("ThresholdIndices", { + thresholdMasterWeight: 0, + thresholdLow: 1, + thresholdMed: 2, + thresholdHigh: 3 + }); + + // === xdr source ============================================================ + // + // enum LedgerEntryType + // { + // ACCOUNT = 0, + // TRUSTLINE = 1, + // OFFER = 2, + // DATA = 3, + // CLAIMABLE_BALANCE = 4, + // LIQUIDITY_POOL = 5, + // CONTRACT_DATA = 6, + // CONTRACT_CODE = 7, + // CONFIG_SETTING = 8, + // TTL = 9 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerEntryType", { + account: 0, + trustline: 1, + offer: 2, + data: 3, + claimableBalance: 4, + liquidityPool: 5, + contractData: 6, + contractCode: 7, + configSetting: 8, + ttl: 9 + }); + + // === xdr source ============================================================ + // + // struct Signer + // { + // SignerKey key; + // uint32 weight; // really only need 1 byte + // }; + // + // =========================================================================== + xdr.struct("Signer", [["key", xdr.lookup("SignerKey")], ["weight", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // enum AccountFlags + // { // masks for each flag + // + // // Flags set on issuer accounts + // // TrustLines are created with authorized set to "false" requiring + // // the issuer to set it for each TrustLine + // AUTH_REQUIRED_FLAG = 0x1, + // // If set, the authorized flag in TrustLines can be cleared + // // otherwise, authorization cannot be revoked + // AUTH_REVOCABLE_FLAG = 0x2, + // // Once set, causes all AUTH_* flags to be read-only + // AUTH_IMMUTABLE_FLAG = 0x4, + // // Trustlines are created with clawback enabled set to "true", + // // and claimable balances created from those trustlines are created + // // with clawback enabled set to "true" + // AUTH_CLAWBACK_ENABLED_FLAG = 0x8 + // }; + // + // =========================================================================== + xdr["enum"]("AccountFlags", { + authRequiredFlag: 1, + authRevocableFlag: 2, + authImmutableFlag: 4, + authClawbackEnabledFlag: 8 + }); + + // === xdr source ============================================================ + // + // const MASK_ACCOUNT_FLAGS = 0x7; + // + // =========================================================================== + xdr["const"]("MASK_ACCOUNT_FLAGS", 0x7); + + // === xdr source ============================================================ + // + // const MASK_ACCOUNT_FLAGS_V17 = 0xF; + // + // =========================================================================== + xdr["const"]("MASK_ACCOUNT_FLAGS_V17", 0xF); + + // === xdr source ============================================================ + // + // const MAX_SIGNERS = 20; + // + // =========================================================================== + xdr["const"]("MAX_SIGNERS", 20); + + // === xdr source ============================================================ + // + // typedef AccountID* SponsorshipDescriptor; + // + // =========================================================================== + xdr.typedef("SponsorshipDescriptor", xdr.option(xdr.lookup("AccountId"))); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV3 + // { + // // We can use this to add more fields, or because it is first, to + // // change AccountEntryExtensionV3 into a union. + // ExtensionPoint ext; + // + // // Ledger number at which `seqNum` took on its present value. + // uint32 seqLedger; + // + // // Time at which `seqNum` took on its present value. + // TimePoint seqTime; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV3", [["ext", xdr.lookup("ExtensionPoint")], ["seqLedger", xdr.lookup("Uint32")], ["seqTime", xdr.lookup("TimePoint")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 3: + // AccountEntryExtensionV3 v3; + // } + // + // =========================================================================== + xdr.union("AccountEntryExtensionV2Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [3, "v3"]], + arms: { + v3: xdr.lookup("AccountEntryExtensionV3") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV2 + // { + // uint32 numSponsored; + // uint32 numSponsoring; + // SponsorshipDescriptor signerSponsoringIDs; + // + // union switch (int v) + // { + // case 0: + // void; + // case 3: + // AccountEntryExtensionV3 v3; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV2", [["numSponsored", xdr.lookup("Uint32")], ["numSponsoring", xdr.lookup("Uint32")], ["signerSponsoringIDs", xdr.varArray(xdr.lookup("SponsorshipDescriptor"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExtensionV2Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // AccountEntryExtensionV2 v2; + // } + // + // =========================================================================== + xdr.union("AccountEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [2, "v2"]], + arms: { + v2: xdr.lookup("AccountEntryExtensionV2") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV1 + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // AccountEntryExtensionV2 v2; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("AccountEntryExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // AccountEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("AccountEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("AccountEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntry + // { + // AccountID accountID; // master public key for this account + // int64 balance; // in stroops + // SequenceNumber seqNum; // last sequence number used for this account + // uint32 numSubEntries; // number of sub-entries this account has + // // drives the reserve + // AccountID* inflationDest; // Account to vote for during inflation + // uint32 flags; // see AccountFlags + // + // string32 homeDomain; // can be used for reverse federation and memo lookup + // + // // fields used for signatures + // // thresholds stores unsigned bytes: [weight of master|low|medium|high] + // Thresholds thresholds; + // + // Signer signers; // possible signers for this account + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // AccountEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntry", [["accountId", xdr.lookup("AccountId")], ["balance", xdr.lookup("Int64")], ["seqNum", xdr.lookup("SequenceNumber")], ["numSubEntries", xdr.lookup("Uint32")], ["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["flags", xdr.lookup("Uint32")], ["homeDomain", xdr.lookup("String32")], ["thresholds", xdr.lookup("Thresholds")], ["signers", xdr.varArray(xdr.lookup("Signer"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExt")]]); + + // === xdr source ============================================================ + // + // enum TrustLineFlags + // { + // // issuer has authorized account to perform transactions with its credit + // AUTHORIZED_FLAG = 1, + // // issuer has authorized account to maintain and reduce liabilities for its + // // credit + // AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG = 2, + // // issuer has specified that it may clawback its credit, and that claimable + // // balances created with its credit may also be clawed back + // TRUSTLINE_CLAWBACK_ENABLED_FLAG = 4 + // }; + // + // =========================================================================== + xdr["enum"]("TrustLineFlags", { + authorizedFlag: 1, + authorizedToMaintainLiabilitiesFlag: 2, + trustlineClawbackEnabledFlag: 4 + }); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS = 1; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS", 1); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS_V13 = 3; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS_V13", 3); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS_V17 = 7; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS_V17", 7); + + // === xdr source ============================================================ + // + // enum LiquidityPoolType + // { + // LIQUIDITY_POOL_CONSTANT_PRODUCT = 0 + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolType", { + liquidityPoolConstantProduct: 0 + }); + + // === xdr source ============================================================ + // + // union TrustLineAsset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // case ASSET_TYPE_POOL_SHARE: + // PoolID liquidityPoolID; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("TrustLineAsset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPoolId"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12"), + liquidityPoolId: xdr.lookup("PoolId") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryExtensionV2Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TrustLineEntryExtensionV2 + // { + // int32 liquidityPoolUseCount; + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TrustLineEntryExtensionV2", [["liquidityPoolUseCount", xdr.lookup("Int32")], ["ext", xdr.lookup("TrustLineEntryExtensionV2Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [2, "v2"]], + arms: { + v2: xdr.lookup("TrustLineEntryExtensionV2") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } + // + // =========================================================================== + xdr.struct("TrustLineEntryV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("TrustLineEntryV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } v1; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("TrustLineEntryV1") + } + }); + + // === xdr source ============================================================ + // + // struct TrustLineEntry + // { + // AccountID accountID; // account this trustline belongs to + // TrustLineAsset asset; // type of asset (with issuer) + // int64 balance; // how much of this asset the user has. + // // Asset defines the unit for this; + // + // int64 limit; // balance cannot be above this + // uint32 flags; // see TrustLineFlags + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TrustLineEntry", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")], ["balance", xdr.lookup("Int64")], ["limit", xdr.lookup("Int64")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("TrustLineEntryExt")]]); + + // === xdr source ============================================================ + // + // enum OfferEntryFlags + // { + // // an offer with this flag will not act on and take a reverse offer of equal + // // price + // PASSIVE_FLAG = 1 + // }; + // + // =========================================================================== + xdr["enum"]("OfferEntryFlags", { + passiveFlag: 1 + }); + + // === xdr source ============================================================ + // + // const MASK_OFFERENTRY_FLAGS = 1; + // + // =========================================================================== + xdr["const"]("MASK_OFFERENTRY_FLAGS", 1); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("OfferEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct OfferEntry + // { + // AccountID sellerID; + // int64 offerID; + // Asset selling; // A + // Asset buying; // B + // int64 amount; // amount of A + // + // /* price for this offer: + // price of A in terms of B + // price=AmountB/AmountA=priceNumerator/priceDenominator + // price is after fees + // */ + // Price price; + // uint32 flags; // see OfferEntryFlags + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("OfferEntry", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("OfferEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("DataEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct DataEntry + // { + // AccountID accountID; // account this data belongs to + // string64 dataName; + // DataValue dataValue; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("DataEntry", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")], ["dataValue", xdr.lookup("DataValue")], ["ext", xdr.lookup("DataEntryExt")]]); + + // === xdr source ============================================================ + // + // enum ClaimPredicateType + // { + // CLAIM_PREDICATE_UNCONDITIONAL = 0, + // CLAIM_PREDICATE_AND = 1, + // CLAIM_PREDICATE_OR = 2, + // CLAIM_PREDICATE_NOT = 3, + // CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME = 4, + // CLAIM_PREDICATE_BEFORE_RELATIVE_TIME = 5 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimPredicateType", { + claimPredicateUnconditional: 0, + claimPredicateAnd: 1, + claimPredicateOr: 2, + claimPredicateNot: 3, + claimPredicateBeforeAbsoluteTime: 4, + claimPredicateBeforeRelativeTime: 5 + }); + + // === xdr source ============================================================ + // + // union ClaimPredicate switch (ClaimPredicateType type) + // { + // case CLAIM_PREDICATE_UNCONDITIONAL: + // void; + // case CLAIM_PREDICATE_AND: + // ClaimPredicate andPredicates<2>; + // case CLAIM_PREDICATE_OR: + // ClaimPredicate orPredicates<2>; + // case CLAIM_PREDICATE_NOT: + // ClaimPredicate* notPredicate; + // case CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME: + // int64 absBefore; // Predicate will be true if closeTime < absBefore + // case CLAIM_PREDICATE_BEFORE_RELATIVE_TIME: + // int64 relBefore; // Seconds since closeTime of the ledger in which the + // // ClaimableBalanceEntry was created + // }; + // + // =========================================================================== + xdr.union("ClaimPredicate", { + switchOn: xdr.lookup("ClaimPredicateType"), + switchName: "type", + switches: [["claimPredicateUnconditional", xdr["void"]()], ["claimPredicateAnd", "andPredicates"], ["claimPredicateOr", "orPredicates"], ["claimPredicateNot", "notPredicate"], ["claimPredicateBeforeAbsoluteTime", "absBefore"], ["claimPredicateBeforeRelativeTime", "relBefore"]], + arms: { + andPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2), + orPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2), + notPredicate: xdr.option(xdr.lookup("ClaimPredicate")), + absBefore: xdr.lookup("Int64"), + relBefore: xdr.lookup("Int64") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimantType + // { + // CLAIMANT_TYPE_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimantType", { + claimantTypeV0: 0 + }); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID destination; // The account that can use this condition + // ClaimPredicate predicate; // Claimable if predicate is true + // } + // + // =========================================================================== + xdr.struct("ClaimantV0", [["destination", xdr.lookup("AccountId")], ["predicate", xdr.lookup("ClaimPredicate")]]); + + // === xdr source ============================================================ + // + // union Claimant switch (ClaimantType type) + // { + // case CLAIMANT_TYPE_V0: + // struct + // { + // AccountID destination; // The account that can use this condition + // ClaimPredicate predicate; // Claimable if predicate is true + // } v0; + // }; + // + // =========================================================================== + xdr.union("Claimant", { + switchOn: xdr.lookup("ClaimantType"), + switchName: "type", + switches: [["claimantTypeV0", "v0"]], + arms: { + v0: xdr.lookup("ClaimantV0") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimableBalanceIDType + // { + // CLAIMABLE_BALANCE_ID_TYPE_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimableBalanceIdType", { + claimableBalanceIdTypeV0: 0 + }); + + // === xdr source ============================================================ + // + // union ClaimableBalanceID switch (ClaimableBalanceIDType type) + // { + // case CLAIMABLE_BALANCE_ID_TYPE_V0: + // Hash v0; + // }; + // + // =========================================================================== + xdr.union("ClaimableBalanceId", { + switchOn: xdr.lookup("ClaimableBalanceIdType"), + switchName: "type", + switches: [["claimableBalanceIdTypeV0", "v0"]], + arms: { + v0: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimableBalanceFlags + // { + // // If set, the issuer account of the asset held by the claimable balance may + // // clawback the claimable balance + // CLAIMABLE_BALANCE_CLAWBACK_ENABLED_FLAG = 0x1 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimableBalanceFlags", { + claimableBalanceClawbackEnabledFlag: 1 + }); + + // === xdr source ============================================================ + // + // const MASK_CLAIMABLE_BALANCE_FLAGS = 0x1; + // + // =========================================================================== + xdr["const"]("MASK_CLAIMABLE_BALANCE_FLAGS", 0x1); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("ClaimableBalanceEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct ClaimableBalanceEntryExtensionV1 + // { + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // + // uint32 flags; // see ClaimableBalanceFlags + // }; + // + // =========================================================================== + xdr.struct("ClaimableBalanceEntryExtensionV1", [["ext", xdr.lookup("ClaimableBalanceEntryExtensionV1Ext")], ["flags", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ClaimableBalanceEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("ClaimableBalanceEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("ClaimableBalanceEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct ClaimableBalanceEntry + // { + // // Unique identifier for this ClaimableBalanceEntry + // ClaimableBalanceID balanceID; + // + // // List of claimants with associated predicate + // Claimant claimants<10>; + // + // // Any asset including native + // Asset asset; + // + // // Amount of asset + // int64 amount; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ClaimableBalanceEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("ClaimableBalanceEntry", [["balanceId", xdr.lookup("ClaimableBalanceId")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["ext", xdr.lookup("ClaimableBalanceEntryExt")]]); + + // === xdr source ============================================================ + // + // struct LiquidityPoolConstantProductParameters + // { + // Asset assetA; // assetA < assetB + // Asset assetB; + // int32 fee; // Fee is in basis points, so the actual rate is (fee/100)% + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolConstantProductParameters", [["assetA", xdr.lookup("Asset")], ["assetB", xdr.lookup("Asset")], ["fee", xdr.lookup("Int32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } + // + // =========================================================================== + xdr.struct("LiquidityPoolEntryConstantProduct", [["params", xdr.lookup("LiquidityPoolConstantProductParameters")], ["reserveA", xdr.lookup("Int64")], ["reserveB", xdr.lookup("Int64")], ["totalPoolShares", xdr.lookup("Int64")], ["poolSharesTrustLineCount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } constantProduct; + // } + // + // =========================================================================== + xdr.union("LiquidityPoolEntryBody", { + switchOn: xdr.lookup("LiquidityPoolType"), + switchName: "type", + switches: [["liquidityPoolConstantProduct", "constantProduct"]], + arms: { + constantProduct: xdr.lookup("LiquidityPoolEntryConstantProduct") + } + }); + + // === xdr source ============================================================ + // + // struct LiquidityPoolEntry + // { + // PoolID liquidityPoolID; + // + // union switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } constantProduct; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolEntry", [["liquidityPoolId", xdr.lookup("PoolId")], ["body", xdr.lookup("LiquidityPoolEntryBody")]]); + + // === xdr source ============================================================ + // + // enum ContractDataDurability { + // TEMPORARY = 0, + // PERSISTENT = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractDataDurability", { + temporary: 0, + persistent: 1 + }); + + // === xdr source ============================================================ + // + // struct ContractDataEntry { + // ExtensionPoint ext; + // + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // SCVal val; + // }; + // + // =========================================================================== + xdr.struct("ContractDataEntry", [["ext", xdr.lookup("ExtensionPoint")], ["contract", xdr.lookup("ScAddress")], ["key", xdr.lookup("ScVal")], ["durability", xdr.lookup("ContractDataDurability")], ["val", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // struct ContractCodeCostInputs { + // ExtensionPoint ext; + // uint32 nInstructions; + // uint32 nFunctions; + // uint32 nGlobals; + // uint32 nTableEntries; + // uint32 nTypes; + // uint32 nDataSegments; + // uint32 nElemSegments; + // uint32 nImports; + // uint32 nExports; + // uint32 nDataSegmentBytes; + // }; + // + // =========================================================================== + xdr.struct("ContractCodeCostInputs", [["ext", xdr.lookup("ExtensionPoint")], ["nInstructions", xdr.lookup("Uint32")], ["nFunctions", xdr.lookup("Uint32")], ["nGlobals", xdr.lookup("Uint32")], ["nTableEntries", xdr.lookup("Uint32")], ["nTypes", xdr.lookup("Uint32")], ["nDataSegments", xdr.lookup("Uint32")], ["nElemSegments", xdr.lookup("Uint32")], ["nImports", xdr.lookup("Uint32")], ["nExports", xdr.lookup("Uint32")], ["nDataSegmentBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } + // + // =========================================================================== + xdr.struct("ContractCodeEntryV1", [["ext", xdr.lookup("ExtensionPoint")], ["costInputs", xdr.lookup("ContractCodeCostInputs")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } v1; + // } + // + // =========================================================================== + xdr.union("ContractCodeEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("ContractCodeEntryV1") + } + }); + + // === xdr source ============================================================ + // + // struct ContractCodeEntry { + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } v1; + // } ext; + // + // Hash hash; + // opaque code<>; + // }; + // + // =========================================================================== + xdr.struct("ContractCodeEntry", [["ext", xdr.lookup("ContractCodeEntryExt")], ["hash", xdr.lookup("Hash")], ["code", xdr.varOpaque()]]); + + // === xdr source ============================================================ + // + // struct TTLEntry { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // uint32 liveUntilLedgerSeq; + // }; + // + // =========================================================================== + xdr.struct("TtlEntry", [["keyHash", xdr.lookup("Hash")], ["liveUntilLedgerSeq", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerEntryExtensionV1 + // { + // SponsorshipDescriptor sponsoringID; + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerEntryExtensionV1", [["sponsoringId", xdr.lookup("SponsorshipDescriptor")], ["ext", xdr.lookup("LedgerEntryExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (LedgerEntryType type) + // { + // case ACCOUNT: + // AccountEntry account; + // case TRUSTLINE: + // TrustLineEntry trustLine; + // case OFFER: + // OfferEntry offer; + // case DATA: + // DataEntry data; + // case CLAIMABLE_BALANCE: + // ClaimableBalanceEntry claimableBalance; + // case LIQUIDITY_POOL: + // LiquidityPoolEntry liquidityPool; + // case CONTRACT_DATA: + // ContractDataEntry contractData; + // case CONTRACT_CODE: + // ContractCodeEntry contractCode; + // case CONFIG_SETTING: + // ConfigSettingEntry configSetting; + // case TTL: + // TTLEntry ttl; + // } + // + // =========================================================================== + xdr.union("LedgerEntryData", { + switchOn: xdr.lookup("LedgerEntryType"), + switchName: "type", + switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"], ["contractData", "contractData"], ["contractCode", "contractCode"], ["configSetting", "configSetting"], ["ttl", "ttl"]], + arms: { + account: xdr.lookup("AccountEntry"), + trustLine: xdr.lookup("TrustLineEntry"), + offer: xdr.lookup("OfferEntry"), + data: xdr.lookup("DataEntry"), + claimableBalance: xdr.lookup("ClaimableBalanceEntry"), + liquidityPool: xdr.lookup("LiquidityPoolEntry"), + contractData: xdr.lookup("ContractDataEntry"), + contractCode: xdr.lookup("ContractCodeEntry"), + configSetting: xdr.lookup("ConfigSettingEntry"), + ttl: xdr.lookup("TtlEntry") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("LedgerEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerEntry + // { + // uint32 lastModifiedLedgerSeq; // ledger the LedgerEntry was last changed + // + // union switch (LedgerEntryType type) + // { + // case ACCOUNT: + // AccountEntry account; + // case TRUSTLINE: + // TrustLineEntry trustLine; + // case OFFER: + // OfferEntry offer; + // case DATA: + // DataEntry data; + // case CLAIMABLE_BALANCE: + // ClaimableBalanceEntry claimableBalance; + // case LIQUIDITY_POOL: + // LiquidityPoolEntry liquidityPool; + // case CONTRACT_DATA: + // ContractDataEntry contractData; + // case CONTRACT_CODE: + // ContractCodeEntry contractCode; + // case CONFIG_SETTING: + // ConfigSettingEntry configSetting; + // case TTL: + // TTLEntry ttl; + // } + // data; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerEntry", [["lastModifiedLedgerSeq", xdr.lookup("Uint32")], ["data", xdr.lookup("LedgerEntryData")], ["ext", xdr.lookup("LedgerEntryExt")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyAccount", [["accountId", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // TrustLineAsset asset; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyTrustLine", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sellerID; + // int64 offerID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyOffer", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // string64 dataName; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyData", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimableBalanceID balanceID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyClaimableBalance", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // PoolID liquidityPoolID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyLiquidityPool", [["liquidityPoolId", xdr.lookup("PoolId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyContractData", [["contract", xdr.lookup("ScAddress")], ["key", xdr.lookup("ScVal")], ["durability", xdr.lookup("ContractDataDurability")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash hash; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyContractCode", [["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ConfigSettingID configSettingID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyConfigSetting", [["configSettingId", xdr.lookup("ConfigSettingId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyTtl", [["keyHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union LedgerKey switch (LedgerEntryType type) + // { + // case ACCOUNT: + // struct + // { + // AccountID accountID; + // } account; + // + // case TRUSTLINE: + // struct + // { + // AccountID accountID; + // TrustLineAsset asset; + // } trustLine; + // + // case OFFER: + // struct + // { + // AccountID sellerID; + // int64 offerID; + // } offer; + // + // case DATA: + // struct + // { + // AccountID accountID; + // string64 dataName; + // } data; + // + // case CLAIMABLE_BALANCE: + // struct + // { + // ClaimableBalanceID balanceID; + // } claimableBalance; + // + // case LIQUIDITY_POOL: + // struct + // { + // PoolID liquidityPoolID; + // } liquidityPool; + // case CONTRACT_DATA: + // struct + // { + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // } contractData; + // case CONTRACT_CODE: + // struct + // { + // Hash hash; + // } contractCode; + // case CONFIG_SETTING: + // struct + // { + // ConfigSettingID configSettingID; + // } configSetting; + // case TTL: + // struct + // { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // } ttl; + // }; + // + // =========================================================================== + xdr.union("LedgerKey", { + switchOn: xdr.lookup("LedgerEntryType"), + switchName: "type", + switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"], ["contractData", "contractData"], ["contractCode", "contractCode"], ["configSetting", "configSetting"], ["ttl", "ttl"]], + arms: { + account: xdr.lookup("LedgerKeyAccount"), + trustLine: xdr.lookup("LedgerKeyTrustLine"), + offer: xdr.lookup("LedgerKeyOffer"), + data: xdr.lookup("LedgerKeyData"), + claimableBalance: xdr.lookup("LedgerKeyClaimableBalance"), + liquidityPool: xdr.lookup("LedgerKeyLiquidityPool"), + contractData: xdr.lookup("LedgerKeyContractData"), + contractCode: xdr.lookup("LedgerKeyContractCode"), + configSetting: xdr.lookup("LedgerKeyConfigSetting"), + ttl: xdr.lookup("LedgerKeyTtl") + } + }); + + // === xdr source ============================================================ + // + // enum EnvelopeType + // { + // ENVELOPE_TYPE_TX_V0 = 0, + // ENVELOPE_TYPE_SCP = 1, + // ENVELOPE_TYPE_TX = 2, + // ENVELOPE_TYPE_AUTH = 3, + // ENVELOPE_TYPE_SCPVALUE = 4, + // ENVELOPE_TYPE_TX_FEE_BUMP = 5, + // ENVELOPE_TYPE_OP_ID = 6, + // ENVELOPE_TYPE_POOL_REVOKE_OP_ID = 7, + // ENVELOPE_TYPE_CONTRACT_ID = 8, + // ENVELOPE_TYPE_SOROBAN_AUTHORIZATION = 9 + // }; + // + // =========================================================================== + xdr["enum"]("EnvelopeType", { + envelopeTypeTxV0: 0, + envelopeTypeScp: 1, + envelopeTypeTx: 2, + envelopeTypeAuth: 3, + envelopeTypeScpvalue: 4, + envelopeTypeTxFeeBump: 5, + envelopeTypeOpId: 6, + envelopeTypePoolRevokeOpId: 7, + envelopeTypeContractId: 8, + envelopeTypeSorobanAuthorization: 9 + }); + + // === xdr source ============================================================ + // + // enum BucketListType + // { + // LIVE = 0, + // HOT_ARCHIVE = 1, + // COLD_ARCHIVE = 2 + // }; + // + // =========================================================================== + xdr["enum"]("BucketListType", { + live: 0, + hotArchive: 1, + coldArchive: 2 + }); + + // === xdr source ============================================================ + // + // enum BucketEntryType + // { + // METAENTRY = + // -1, // At-and-after protocol 11: bucket metadata, should come first. + // LIVEENTRY = 0, // Before protocol 11: created-or-updated; + // // At-and-after protocol 11: only updated. + // DEADENTRY = 1, + // INITENTRY = 2 // At-and-after protocol 11: only created. + // }; + // + // =========================================================================== + xdr["enum"]("BucketEntryType", { + metaentry: -1, + liveentry: 0, + deadentry: 1, + initentry: 2 + }); + + // === xdr source ============================================================ + // + // enum HotArchiveBucketEntryType + // { + // HOT_ARCHIVE_METAENTRY = -1, // Bucket metadata, should come first. + // HOT_ARCHIVE_ARCHIVED = 0, // Entry is Archived + // HOT_ARCHIVE_LIVE = 1, // Entry was previously HOT_ARCHIVE_ARCHIVED, or HOT_ARCHIVE_DELETED, but + // // has been added back to the live BucketList. + // // Does not need to be persisted. + // HOT_ARCHIVE_DELETED = 2 // Entry deleted (Note: must be persisted in archive) + // }; + // + // =========================================================================== + xdr["enum"]("HotArchiveBucketEntryType", { + hotArchiveMetaentry: -1, + hotArchiveArchived: 0, + hotArchiveLive: 1, + hotArchiveDeleted: 2 + }); + + // === xdr source ============================================================ + // + // enum ColdArchiveBucketEntryType + // { + // COLD_ARCHIVE_METAENTRY = -1, // Bucket metadata, should come first. + // COLD_ARCHIVE_ARCHIVED_LEAF = 0, // Full LedgerEntry that was archived during the epoch + // COLD_ARCHIVE_DELETED_LEAF = 1, // LedgerKey that was deleted during the epoch + // COLD_ARCHIVE_BOUNDARY_LEAF = 2, // Dummy leaf representing low/high bound + // COLD_ARCHIVE_HASH = 3 // Intermediary Merkle hash entry + // }; + // + // =========================================================================== + xdr["enum"]("ColdArchiveBucketEntryType", { + coldArchiveMetaentry: -1, + coldArchiveArchivedLeaf: 0, + coldArchiveDeletedLeaf: 1, + coldArchiveBoundaryLeaf: 2, + coldArchiveHash: 3 + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // BucketListType bucketListType; + // } + // + // =========================================================================== + xdr.union("BucketMetadataExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "bucketListType"]], + arms: { + bucketListType: xdr.lookup("BucketListType") + } + }); + + // === xdr source ============================================================ + // + // struct BucketMetadata + // { + // // Indicates the protocol version used to create / merge this bucket. + // uint32 ledgerVersion; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // BucketListType bucketListType; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("BucketMetadata", [["ledgerVersion", xdr.lookup("Uint32")], ["ext", xdr.lookup("BucketMetadataExt")]]); + + // === xdr source ============================================================ + // + // union BucketEntry switch (BucketEntryType type) + // { + // case LIVEENTRY: + // case INITENTRY: + // LedgerEntry liveEntry; + // + // case DEADENTRY: + // LedgerKey deadEntry; + // case METAENTRY: + // BucketMetadata metaEntry; + // }; + // + // =========================================================================== + xdr.union("BucketEntry", { + switchOn: xdr.lookup("BucketEntryType"), + switchName: "type", + switches: [["liveentry", "liveEntry"], ["initentry", "liveEntry"], ["deadentry", "deadEntry"], ["metaentry", "metaEntry"]], + arms: { + liveEntry: xdr.lookup("LedgerEntry"), + deadEntry: xdr.lookup("LedgerKey"), + metaEntry: xdr.lookup("BucketMetadata") + } + }); + + // === xdr source ============================================================ + // + // union HotArchiveBucketEntry switch (HotArchiveBucketEntryType type) + // { + // case HOT_ARCHIVE_ARCHIVED: + // LedgerEntry archivedEntry; + // + // case HOT_ARCHIVE_LIVE: + // case HOT_ARCHIVE_DELETED: + // LedgerKey key; + // case HOT_ARCHIVE_METAENTRY: + // BucketMetadata metaEntry; + // }; + // + // =========================================================================== + xdr.union("HotArchiveBucketEntry", { + switchOn: xdr.lookup("HotArchiveBucketEntryType"), + switchName: "type", + switches: [["hotArchiveArchived", "archivedEntry"], ["hotArchiveLive", "key"], ["hotArchiveDeleted", "key"], ["hotArchiveMetaentry", "metaEntry"]], + arms: { + archivedEntry: xdr.lookup("LedgerEntry"), + key: xdr.lookup("LedgerKey"), + metaEntry: xdr.lookup("BucketMetadata") + } + }); + + // === xdr source ============================================================ + // + // struct ColdArchiveArchivedLeaf + // { + // uint32 index; + // LedgerEntry archivedEntry; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveArchivedLeaf", [["index", xdr.lookup("Uint32")], ["archivedEntry", xdr.lookup("LedgerEntry")]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveDeletedLeaf + // { + // uint32 index; + // LedgerKey deletedKey; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveDeletedLeaf", [["index", xdr.lookup("Uint32")], ["deletedKey", xdr.lookup("LedgerKey")]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveBoundaryLeaf + // { + // uint32 index; + // bool isLowerBound; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveBoundaryLeaf", [["index", xdr.lookup("Uint32")], ["isLowerBound", xdr.bool()]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveHashEntry + // { + // uint32 index; + // uint32 level; + // Hash hash; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveHashEntry", [["index", xdr.lookup("Uint32")], ["level", xdr.lookup("Uint32")], ["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union ColdArchiveBucketEntry switch (ColdArchiveBucketEntryType type) + // { + // case COLD_ARCHIVE_METAENTRY: + // BucketMetadata metaEntry; + // case COLD_ARCHIVE_ARCHIVED_LEAF: + // ColdArchiveArchivedLeaf archivedLeaf; + // case COLD_ARCHIVE_DELETED_LEAF: + // ColdArchiveDeletedLeaf deletedLeaf; + // case COLD_ARCHIVE_BOUNDARY_LEAF: + // ColdArchiveBoundaryLeaf boundaryLeaf; + // case COLD_ARCHIVE_HASH: + // ColdArchiveHashEntry hashEntry; + // }; + // + // =========================================================================== + xdr.union("ColdArchiveBucketEntry", { + switchOn: xdr.lookup("ColdArchiveBucketEntryType"), + switchName: "type", + switches: [["coldArchiveMetaentry", "metaEntry"], ["coldArchiveArchivedLeaf", "archivedLeaf"], ["coldArchiveDeletedLeaf", "deletedLeaf"], ["coldArchiveBoundaryLeaf", "boundaryLeaf"], ["coldArchiveHash", "hashEntry"]], + arms: { + metaEntry: xdr.lookup("BucketMetadata"), + archivedLeaf: xdr.lookup("ColdArchiveArchivedLeaf"), + deletedLeaf: xdr.lookup("ColdArchiveDeletedLeaf"), + boundaryLeaf: xdr.lookup("ColdArchiveBoundaryLeaf"), + hashEntry: xdr.lookup("ColdArchiveHashEntry") + } + }); + + // === xdr source ============================================================ + // + // typedef opaque UpgradeType<128>; + // + // =========================================================================== + xdr.typedef("UpgradeType", xdr.varOpaque(128)); + + // === xdr source ============================================================ + // + // enum StellarValueType + // { + // STELLAR_VALUE_BASIC = 0, + // STELLAR_VALUE_SIGNED = 1 + // }; + // + // =========================================================================== + xdr["enum"]("StellarValueType", { + stellarValueBasic: 0, + stellarValueSigned: 1 + }); + + // === xdr source ============================================================ + // + // struct LedgerCloseValueSignature + // { + // NodeID nodeID; // which node introduced the value + // Signature signature; // nodeID's signature + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseValueSignature", [["nodeId", xdr.lookup("NodeId")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // union switch (StellarValueType v) + // { + // case STELLAR_VALUE_BASIC: + // void; + // case STELLAR_VALUE_SIGNED: + // LedgerCloseValueSignature lcValueSignature; + // } + // + // =========================================================================== + xdr.union("StellarValueExt", { + switchOn: xdr.lookup("StellarValueType"), + switchName: "v", + switches: [["stellarValueBasic", xdr["void"]()], ["stellarValueSigned", "lcValueSignature"]], + arms: { + lcValueSignature: xdr.lookup("LedgerCloseValueSignature") + } + }); + + // === xdr source ============================================================ + // + // struct StellarValue + // { + // Hash txSetHash; // transaction set to apply to previous ledger + // TimePoint closeTime; // network close time + // + // // upgrades to apply to the previous ledger (usually empty) + // // this is a vector of encoded 'LedgerUpgrade' so that nodes can drop + // // unknown steps during consensus if needed. + // // see notes below on 'LedgerUpgrade' for more detail + // // max size is dictated by number of upgrade types (+ room for future) + // UpgradeType upgrades<6>; + // + // // reserved for future use + // union switch (StellarValueType v) + // { + // case STELLAR_VALUE_BASIC: + // void; + // case STELLAR_VALUE_SIGNED: + // LedgerCloseValueSignature lcValueSignature; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("StellarValue", [["txSetHash", xdr.lookup("Hash")], ["closeTime", xdr.lookup("TimePoint")], ["upgrades", xdr.varArray(xdr.lookup("UpgradeType"), 6)], ["ext", xdr.lookup("StellarValueExt")]]); + + // === xdr source ============================================================ + // + // const MASK_LEDGER_HEADER_FLAGS = 0x7; + // + // =========================================================================== + xdr["const"]("MASK_LEDGER_HEADER_FLAGS", 0x7); + + // === xdr source ============================================================ + // + // enum LedgerHeaderFlags + // { + // DISABLE_LIQUIDITY_POOL_TRADING_FLAG = 0x1, + // DISABLE_LIQUIDITY_POOL_DEPOSIT_FLAG = 0x2, + // DISABLE_LIQUIDITY_POOL_WITHDRAWAL_FLAG = 0x4 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerHeaderFlags", { + disableLiquidityPoolTradingFlag: 1, + disableLiquidityPoolDepositFlag: 2, + disableLiquidityPoolWithdrawalFlag: 4 + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerHeaderExtensionV1 + // { + // uint32 flags; // LedgerHeaderFlags + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeaderExtensionV1", [["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("LedgerHeaderExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerHeaderExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerHeaderExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerHeader + // { + // uint32 ledgerVersion; // the protocol version of the ledger + // Hash previousLedgerHash; // hash of the previous ledger header + // StellarValue scpValue; // what consensus agreed to + // Hash txSetResultHash; // the TransactionResultSet that led to this ledger + // Hash bucketListHash; // hash of the ledger state + // + // uint32 ledgerSeq; // sequence number of this ledger + // + // int64 totalCoins; // total number of stroops in existence. + // // 10,000,000 stroops in 1 XLM + // + // int64 feePool; // fees burned since last inflation run + // uint32 inflationSeq; // inflation sequence number + // + // uint64 idPool; // last used global ID, used for generating objects + // + // uint32 baseFee; // base fee per operation in stroops + // uint32 baseReserve; // account base reserve in stroops + // + // uint32 maxTxSetSize; // maximum size a transaction set can be + // + // Hash skipList[4]; // hashes of ledgers in the past. allows you to jump back + // // in time without walking the chain back ledger by ledger + // // each slot contains the oldest ledger that is mod of + // // either 50 5000 50000 or 500000 depending on index + // // skipList[0] mod(50), skipList[1] mod(5000), etc + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerHeaderExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeader", [["ledgerVersion", xdr.lookup("Uint32")], ["previousLedgerHash", xdr.lookup("Hash")], ["scpValue", xdr.lookup("StellarValue")], ["txSetResultHash", xdr.lookup("Hash")], ["bucketListHash", xdr.lookup("Hash")], ["ledgerSeq", xdr.lookup("Uint32")], ["totalCoins", xdr.lookup("Int64")], ["feePool", xdr.lookup("Int64")], ["inflationSeq", xdr.lookup("Uint32")], ["idPool", xdr.lookup("Uint64")], ["baseFee", xdr.lookup("Uint32")], ["baseReserve", xdr.lookup("Uint32")], ["maxTxSetSize", xdr.lookup("Uint32")], ["skipList", xdr.array(xdr.lookup("Hash"), 4)], ["ext", xdr.lookup("LedgerHeaderExt")]]); + + // === xdr source ============================================================ + // + // enum LedgerUpgradeType + // { + // LEDGER_UPGRADE_VERSION = 1, + // LEDGER_UPGRADE_BASE_FEE = 2, + // LEDGER_UPGRADE_MAX_TX_SET_SIZE = 3, + // LEDGER_UPGRADE_BASE_RESERVE = 4, + // LEDGER_UPGRADE_FLAGS = 5, + // LEDGER_UPGRADE_CONFIG = 6, + // LEDGER_UPGRADE_MAX_SOROBAN_TX_SET_SIZE = 7 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerUpgradeType", { + ledgerUpgradeVersion: 1, + ledgerUpgradeBaseFee: 2, + ledgerUpgradeMaxTxSetSize: 3, + ledgerUpgradeBaseReserve: 4, + ledgerUpgradeFlags: 5, + ledgerUpgradeConfig: 6, + ledgerUpgradeMaxSorobanTxSetSize: 7 + }); + + // === xdr source ============================================================ + // + // struct ConfigUpgradeSetKey { + // Hash contractID; + // Hash contentHash; + // }; + // + // =========================================================================== + xdr.struct("ConfigUpgradeSetKey", [["contractId", xdr.lookup("Hash")], ["contentHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union LedgerUpgrade switch (LedgerUpgradeType type) + // { + // case LEDGER_UPGRADE_VERSION: + // uint32 newLedgerVersion; // update ledgerVersion + // case LEDGER_UPGRADE_BASE_FEE: + // uint32 newBaseFee; // update baseFee + // case LEDGER_UPGRADE_MAX_TX_SET_SIZE: + // uint32 newMaxTxSetSize; // update maxTxSetSize + // case LEDGER_UPGRADE_BASE_RESERVE: + // uint32 newBaseReserve; // update baseReserve + // case LEDGER_UPGRADE_FLAGS: + // uint32 newFlags; // update flags + // case LEDGER_UPGRADE_CONFIG: + // // Update arbitrary `ConfigSetting` entries identified by the key. + // ConfigUpgradeSetKey newConfig; + // case LEDGER_UPGRADE_MAX_SOROBAN_TX_SET_SIZE: + // // Update ConfigSettingContractExecutionLanesV0.ledgerMaxTxCount without + // // using `LEDGER_UPGRADE_CONFIG`. + // uint32 newMaxSorobanTxSetSize; + // }; + // + // =========================================================================== + xdr.union("LedgerUpgrade", { + switchOn: xdr.lookup("LedgerUpgradeType"), + switchName: "type", + switches: [["ledgerUpgradeVersion", "newLedgerVersion"], ["ledgerUpgradeBaseFee", "newBaseFee"], ["ledgerUpgradeMaxTxSetSize", "newMaxTxSetSize"], ["ledgerUpgradeBaseReserve", "newBaseReserve"], ["ledgerUpgradeFlags", "newFlags"], ["ledgerUpgradeConfig", "newConfig"], ["ledgerUpgradeMaxSorobanTxSetSize", "newMaxSorobanTxSetSize"]], + arms: { + newLedgerVersion: xdr.lookup("Uint32"), + newBaseFee: xdr.lookup("Uint32"), + newMaxTxSetSize: xdr.lookup("Uint32"), + newBaseReserve: xdr.lookup("Uint32"), + newFlags: xdr.lookup("Uint32"), + newConfig: xdr.lookup("ConfigUpgradeSetKey"), + newMaxSorobanTxSetSize: xdr.lookup("Uint32") + } + }); + + // === xdr source ============================================================ + // + // struct ConfigUpgradeSet { + // ConfigSettingEntry updatedEntry<>; + // }; + // + // =========================================================================== + xdr.struct("ConfigUpgradeSet", [["updatedEntry", xdr.varArray(xdr.lookup("ConfigSettingEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // enum TxSetComponentType + // { + // // txs with effective fee <= bid derived from a base fee (if any). + // // If base fee is not specified, no discount is applied. + // TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE = 0 + // }; + // + // =========================================================================== + xdr["enum"]("TxSetComponentType", { + txsetCompTxsMaybeDiscountedFee: 0 + }); + + // === xdr source ============================================================ + // + // struct + // { + // int64* baseFee; + // TransactionEnvelope txs<>; + // } + // + // =========================================================================== + xdr.struct("TxSetComponentTxsMaybeDiscountedFee", [["baseFee", xdr.option(xdr.lookup("Int64"))], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union TxSetComponent switch (TxSetComponentType type) + // { + // case TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE: + // struct + // { + // int64* baseFee; + // TransactionEnvelope txs<>; + // } txsMaybeDiscountedFee; + // }; + // + // =========================================================================== + xdr.union("TxSetComponent", { + switchOn: xdr.lookup("TxSetComponentType"), + switchName: "type", + switches: [["txsetCompTxsMaybeDiscountedFee", "txsMaybeDiscountedFee"]], + arms: { + txsMaybeDiscountedFee: xdr.lookup("TxSetComponentTxsMaybeDiscountedFee") + } + }); + + // === xdr source ============================================================ + // + // union TransactionPhase switch (int v) + // { + // case 0: + // TxSetComponent v0Components<>; + // }; + // + // =========================================================================== + xdr.union("TransactionPhase", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0Components"]], + arms: { + v0Components: xdr.varArray(xdr.lookup("TxSetComponent"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // struct TransactionSet + // { + // Hash previousLedgerHash; + // TransactionEnvelope txs<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionSet", [["previousLedgerHash", xdr.lookup("Hash")], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionSetV1 + // { + // Hash previousLedgerHash; + // TransactionPhase phases<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionSetV1", [["previousLedgerHash", xdr.lookup("Hash")], ["phases", xdr.varArray(xdr.lookup("TransactionPhase"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union GeneralizedTransactionSet switch (int v) + // { + // // We consider the legacy TransactionSet to be v0. + // case 1: + // TransactionSetV1 v1TxSet; + // }; + // + // =========================================================================== + xdr.union("GeneralizedTransactionSet", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[1, "v1TxSet"]], + arms: { + v1TxSet: xdr.lookup("TransactionSetV1") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionResultPair + // { + // Hash transactionHash; + // TransactionResult result; // result for the transaction + // }; + // + // =========================================================================== + xdr.struct("TransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("TransactionResult")]]); + + // === xdr source ============================================================ + // + // struct TransactionResultSet + // { + // TransactionResultPair results<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionResultSet", [["results", xdr.varArray(xdr.lookup("TransactionResultPair"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // GeneralizedTransactionSet generalizedTxSet; + // } + // + // =========================================================================== + xdr.union("TransactionHistoryEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "generalizedTxSet"]], + arms: { + generalizedTxSet: xdr.lookup("GeneralizedTransactionSet") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionHistoryEntry + // { + // uint32 ledgerSeq; + // TransactionSet txSet; + // + // // when v != 0, txSet must be empty + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // GeneralizedTransactionSet generalizedTxSet; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionHistoryEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txSet", xdr.lookup("TransactionSet")], ["ext", xdr.lookup("TransactionHistoryEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionHistoryResultEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionHistoryResultEntry + // { + // uint32 ledgerSeq; + // TransactionResultSet txResultSet; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionHistoryResultEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txResultSet", xdr.lookup("TransactionResultSet")], ["ext", xdr.lookup("TransactionHistoryResultEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderHistoryEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerHeaderHistoryEntry + // { + // Hash hash; + // LedgerHeader header; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeaderHistoryEntry", [["hash", xdr.lookup("Hash")], ["header", xdr.lookup("LedgerHeader")], ["ext", xdr.lookup("LedgerHeaderHistoryEntryExt")]]); + + // === xdr source ============================================================ + // + // struct LedgerSCPMessages + // { + // uint32 ledgerSeq; + // SCPEnvelope messages<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerScpMessages", [["ledgerSeq", xdr.lookup("Uint32")], ["messages", xdr.varArray(xdr.lookup("ScpEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct SCPHistoryEntryV0 + // { + // SCPQuorumSet quorumSets<>; // additional quorum sets used by ledgerMessages + // LedgerSCPMessages ledgerMessages; + // }; + // + // =========================================================================== + xdr.struct("ScpHistoryEntryV0", [["quorumSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)], ["ledgerMessages", xdr.lookup("LedgerScpMessages")]]); + + // === xdr source ============================================================ + // + // union SCPHistoryEntry switch (int v) + // { + // case 0: + // SCPHistoryEntryV0 v0; + // }; + // + // =========================================================================== + xdr.union("ScpHistoryEntry", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("ScpHistoryEntryV0") + } + }); + + // === xdr source ============================================================ + // + // enum LedgerEntryChangeType + // { + // LEDGER_ENTRY_CREATED = 0, // entry was added to the ledger + // LEDGER_ENTRY_UPDATED = 1, // entry was modified in the ledger + // LEDGER_ENTRY_REMOVED = 2, // entry was removed from the ledger + // LEDGER_ENTRY_STATE = 3 // value of the entry + // }; + // + // =========================================================================== + xdr["enum"]("LedgerEntryChangeType", { + ledgerEntryCreated: 0, + ledgerEntryUpdated: 1, + ledgerEntryRemoved: 2, + ledgerEntryState: 3 + }); + + // === xdr source ============================================================ + // + // union LedgerEntryChange switch (LedgerEntryChangeType type) + // { + // case LEDGER_ENTRY_CREATED: + // LedgerEntry created; + // case LEDGER_ENTRY_UPDATED: + // LedgerEntry updated; + // case LEDGER_ENTRY_REMOVED: + // LedgerKey removed; + // case LEDGER_ENTRY_STATE: + // LedgerEntry state; + // }; + // + // =========================================================================== + xdr.union("LedgerEntryChange", { + switchOn: xdr.lookup("LedgerEntryChangeType"), + switchName: "type", + switches: [["ledgerEntryCreated", "created"], ["ledgerEntryUpdated", "updated"], ["ledgerEntryRemoved", "removed"], ["ledgerEntryState", "state"]], + arms: { + created: xdr.lookup("LedgerEntry"), + updated: xdr.lookup("LedgerEntry"), + removed: xdr.lookup("LedgerKey"), + state: xdr.lookup("LedgerEntry") + } + }); + + // === xdr source ============================================================ + // + // typedef LedgerEntryChange LedgerEntryChanges<>; + // + // =========================================================================== + xdr.typedef("LedgerEntryChanges", xdr.varArray(xdr.lookup("LedgerEntryChange"), 2147483647)); + + // === xdr source ============================================================ + // + // struct OperationMeta + // { + // LedgerEntryChanges changes; + // }; + // + // =========================================================================== + xdr.struct("OperationMeta", [["changes", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV1 + // { + // LedgerEntryChanges txChanges; // tx level changes if any + // OperationMeta operations<>; // meta for each operation + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV1", [["txChanges", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV2 + // { + // LedgerEntryChanges txChangesBefore; // tx level changes before operations + // // are applied if any + // OperationMeta operations<>; // meta for each operation + // LedgerEntryChanges txChangesAfter; // tx level changes after operations are + // // applied if any + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV2", [["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // enum ContractEventType + // { + // SYSTEM = 0, + // CONTRACT = 1, + // DIAGNOSTIC = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ContractEventType", { + system: 0, + contract: 1, + diagnostic: 2 + }); + + // === xdr source ============================================================ + // + // struct + // { + // SCVal topics<>; + // SCVal data; + // } + // + // =========================================================================== + xdr.struct("ContractEventV0", [["topics", xdr.varArray(xdr.lookup("ScVal"), 2147483647)], ["data", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // struct + // { + // SCVal topics<>; + // SCVal data; + // } v0; + // } + // + // =========================================================================== + xdr.union("ContractEventBody", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("ContractEventV0") + } + }); + + // === xdr source ============================================================ + // + // struct ContractEvent + // { + // // We can use this to add more fields, or because it + // // is first, to change ContractEvent into a union. + // ExtensionPoint ext; + // + // Hash* contractID; + // ContractEventType type; + // + // union switch (int v) + // { + // case 0: + // struct + // { + // SCVal topics<>; + // SCVal data; + // } v0; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("ContractEvent", [["ext", xdr.lookup("ExtensionPoint")], ["contractId", xdr.option(xdr.lookup("Hash"))], ["type", xdr.lookup("ContractEventType")], ["body", xdr.lookup("ContractEventBody")]]); + + // === xdr source ============================================================ + // + // struct DiagnosticEvent + // { + // bool inSuccessfulContractCall; + // ContractEvent event; + // }; + // + // =========================================================================== + xdr.struct("DiagnosticEvent", [["inSuccessfulContractCall", xdr.bool()], ["event", xdr.lookup("ContractEvent")]]); + + // === xdr source ============================================================ + // + // typedef DiagnosticEvent DiagnosticEvents<>; + // + // =========================================================================== + xdr.typedef("DiagnosticEvents", xdr.varArray(xdr.lookup("DiagnosticEvent"), 2147483647)); + + // === xdr source ============================================================ + // + // struct SorobanTransactionMetaExtV1 + // { + // ExtensionPoint ext; + // + // // The following are the components of the overall Soroban resource fee + // // charged for the transaction. + // // The following relation holds: + // // `resourceFeeCharged = totalNonRefundableResourceFeeCharged + totalRefundableResourceFeeCharged` + // // where `resourceFeeCharged` is the overall fee charged for the + // // transaction. Also, `resourceFeeCharged` <= `sorobanData.resourceFee` + // // i.e.we never charge more than the declared resource fee. + // // The inclusion fee for charged the Soroban transaction can be found using + // // the following equation: + // // `result.feeCharged = resourceFeeCharged + inclusionFeeCharged`. + // + // // Total amount (in stroops) that has been charged for non-refundable + // // Soroban resources. + // // Non-refundable resources are charged based on the usage declared in + // // the transaction envelope (such as `instructions`, `readBytes` etc.) and + // // is charged regardless of the success of the transaction. + // int64 totalNonRefundableResourceFeeCharged; + // // Total amount (in stroops) that has been charged for refundable + // // Soroban resource fees. + // // Currently this comprises the rent fee (`rentFeeCharged`) and the + // // fee for the events and return value. + // // Refundable resources are charged based on the actual resources usage. + // // Since currently refundable resources are only used for the successful + // // transactions, this will be `0` for failed transactions. + // int64 totalRefundableResourceFeeCharged; + // // Amount (in stroops) that has been charged for rent. + // // This is a part of `totalNonRefundableResourceFeeCharged`. + // int64 rentFeeCharged; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionMetaExtV1", [["ext", xdr.lookup("ExtensionPoint")], ["totalNonRefundableResourceFeeCharged", xdr.lookup("Int64")], ["totalRefundableResourceFeeCharged", xdr.lookup("Int64")], ["rentFeeCharged", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union SorobanTransactionMetaExt switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionMetaExtV1 v1; + // }; + // + // =========================================================================== + xdr.union("SorobanTransactionMetaExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("SorobanTransactionMetaExtV1") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanTransactionMeta + // { + // SorobanTransactionMetaExt ext; + // + // ContractEvent events<>; // custom events populated by the + // // contracts themselves. + // SCVal returnValue; // return value of the host fn invocation + // + // // Diagnostics events that are not hashed. + // // This will contain all contract and diagnostic events. Even ones + // // that were emitted in a failed contract call. + // DiagnosticEvent diagnosticEvents<>; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionMeta", [["ext", xdr.lookup("SorobanTransactionMetaExt")], ["events", xdr.varArray(xdr.lookup("ContractEvent"), 2147483647)], ["returnValue", xdr.lookup("ScVal")], ["diagnosticEvents", xdr.varArray(xdr.lookup("DiagnosticEvent"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV3 + // { + // ExtensionPoint ext; + // + // LedgerEntryChanges txChangesBefore; // tx level changes before operations + // // are applied if any + // OperationMeta operations<>; // meta for each operation + // LedgerEntryChanges txChangesAfter; // tx level changes after operations are + // // applied if any + // SorobanTransactionMeta* sorobanMeta; // Soroban-specific meta (only for + // // Soroban transactions). + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV3", [["ext", xdr.lookup("ExtensionPoint")], ["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")], ["sorobanMeta", xdr.option(xdr.lookup("SorobanTransactionMeta"))]]); + + // === xdr source ============================================================ + // + // struct InvokeHostFunctionSuccessPreImage + // { + // SCVal returnValue; + // ContractEvent events<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeHostFunctionSuccessPreImage", [["returnValue", xdr.lookup("ScVal")], ["events", xdr.varArray(xdr.lookup("ContractEvent"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union TransactionMeta switch (int v) + // { + // case 0: + // OperationMeta operations<>; + // case 1: + // TransactionMetaV1 v1; + // case 2: + // TransactionMetaV2 v2; + // case 3: + // TransactionMetaV3 v3; + // }; + // + // =========================================================================== + xdr.union("TransactionMeta", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "operations"], [1, "v1"], [2, "v2"], [3, "v3"]], + arms: { + operations: xdr.varArray(xdr.lookup("OperationMeta"), 2147483647), + v1: xdr.lookup("TransactionMetaV1"), + v2: xdr.lookup("TransactionMetaV2"), + v3: xdr.lookup("TransactionMetaV3") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionResultMeta + // { + // TransactionResultPair result; + // LedgerEntryChanges feeProcessing; + // TransactionMeta txApplyProcessing; + // }; + // + // =========================================================================== + xdr.struct("TransactionResultMeta", [["result", xdr.lookup("TransactionResultPair")], ["feeProcessing", xdr.lookup("LedgerEntryChanges")], ["txApplyProcessing", xdr.lookup("TransactionMeta")]]); + + // === xdr source ============================================================ + // + // struct UpgradeEntryMeta + // { + // LedgerUpgrade upgrade; + // LedgerEntryChanges changes; + // }; + // + // =========================================================================== + xdr.struct("UpgradeEntryMeta", [["upgrade", xdr.lookup("LedgerUpgrade")], ["changes", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaV0 + // { + // LedgerHeaderHistoryEntry ledgerHeader; + // // NB: txSet is sorted in "Hash order" + // TransactionSet txSet; + // + // // NB: transactions are sorted in apply order here + // // fees for all transactions are processed first + // // followed by applying transactions + // TransactionResultMeta txProcessing<>; + // + // // upgrades are applied last + // UpgradeEntryMeta upgradesProcessing<>; + // + // // other misc information attached to the ledger close + // SCPHistoryEntry scpInfo<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaV0", [["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("TransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaExtV1 + // { + // ExtensionPoint ext; + // int64 sorobanFeeWrite1KB; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaExtV1", [["ext", xdr.lookup("ExtensionPoint")], ["sorobanFeeWrite1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union LedgerCloseMetaExt switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerCloseMetaExtV1 v1; + // }; + // + // =========================================================================== + xdr.union("LedgerCloseMetaExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerCloseMetaExtV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaV1 + // { + // LedgerCloseMetaExt ext; + // + // LedgerHeaderHistoryEntry ledgerHeader; + // + // GeneralizedTransactionSet txSet; + // + // // NB: transactions are sorted in apply order here + // // fees for all transactions are processed first + // // followed by applying transactions + // TransactionResultMeta txProcessing<>; + // + // // upgrades are applied last + // UpgradeEntryMeta upgradesProcessing<>; + // + // // other misc information attached to the ledger close + // SCPHistoryEntry scpInfo<>; + // + // // Size in bytes of BucketList, to support downstream + // // systems calculating storage fees correctly. + // uint64 totalByteSizeOfBucketList; + // + // // Temp keys that are being evicted at this ledger. + // LedgerKey evictedTemporaryLedgerKeys<>; + // + // // Archived restorable ledger entries that are being + // // evicted at this ledger. + // LedgerEntry evictedPersistentLedgerEntries<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaV1", [["ext", xdr.lookup("LedgerCloseMetaExt")], ["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("GeneralizedTransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)], ["totalByteSizeOfBucketList", xdr.lookup("Uint64")], ["evictedTemporaryLedgerKeys", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["evictedPersistentLedgerEntries", xdr.varArray(xdr.lookup("LedgerEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union LedgerCloseMeta switch (int v) + // { + // case 0: + // LedgerCloseMetaV0 v0; + // case 1: + // LedgerCloseMetaV1 v1; + // }; + // + // =========================================================================== + xdr.union("LedgerCloseMeta", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"], [1, "v1"]], + arms: { + v0: xdr.lookup("LedgerCloseMetaV0"), + v1: xdr.lookup("LedgerCloseMetaV1") + } + }); + + // === xdr source ============================================================ + // + // enum ErrorCode + // { + // ERR_MISC = 0, // Unspecific error + // ERR_DATA = 1, // Malformed data + // ERR_CONF = 2, // Misconfiguration error + // ERR_AUTH = 3, // Authentication failure + // ERR_LOAD = 4 // System overloaded + // }; + // + // =========================================================================== + xdr["enum"]("ErrorCode", { + errMisc: 0, + errData: 1, + errConf: 2, + errAuth: 3, + errLoad: 4 + }); + + // === xdr source ============================================================ + // + // struct Error + // { + // ErrorCode code; + // string msg<100>; + // }; + // + // =========================================================================== + xdr.struct("Error", [["code", xdr.lookup("ErrorCode")], ["msg", xdr.string(100)]]); + + // === xdr source ============================================================ + // + // struct SendMore + // { + // uint32 numMessages; + // }; + // + // =========================================================================== + xdr.struct("SendMore", [["numMessages", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SendMoreExtended + // { + // uint32 numMessages; + // uint32 numBytes; + // }; + // + // =========================================================================== + xdr.struct("SendMoreExtended", [["numMessages", xdr.lookup("Uint32")], ["numBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct AuthCert + // { + // Curve25519Public pubkey; + // uint64 expiration; + // Signature sig; + // }; + // + // =========================================================================== + xdr.struct("AuthCert", [["pubkey", xdr.lookup("Curve25519Public")], ["expiration", xdr.lookup("Uint64")], ["sig", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // struct Hello + // { + // uint32 ledgerVersion; + // uint32 overlayVersion; + // uint32 overlayMinVersion; + // Hash networkID; + // string versionStr<100>; + // int listeningPort; + // NodeID peerID; + // AuthCert cert; + // uint256 nonce; + // }; + // + // =========================================================================== + xdr.struct("Hello", [["ledgerVersion", xdr.lookup("Uint32")], ["overlayVersion", xdr.lookup("Uint32")], ["overlayMinVersion", xdr.lookup("Uint32")], ["networkId", xdr.lookup("Hash")], ["versionStr", xdr.string(100)], ["listeningPort", xdr["int"]()], ["peerId", xdr.lookup("NodeId")], ["cert", xdr.lookup("AuthCert")], ["nonce", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // const AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED = 200; + // + // =========================================================================== + xdr["const"]("AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED", 200); + + // === xdr source ============================================================ + // + // struct Auth + // { + // int flags; + // }; + // + // =========================================================================== + xdr.struct("Auth", [["flags", xdr["int"]()]]); + + // === xdr source ============================================================ + // + // enum IPAddrType + // { + // IPv4 = 0, + // IPv6 = 1 + // }; + // + // =========================================================================== + xdr["enum"]("IpAddrType", { + iPv4: 0, + iPv6: 1 + }); + + // === xdr source ============================================================ + // + // union switch (IPAddrType type) + // { + // case IPv4: + // opaque ipv4[4]; + // case IPv6: + // opaque ipv6[16]; + // } + // + // =========================================================================== + xdr.union("PeerAddressIp", { + switchOn: xdr.lookup("IpAddrType"), + switchName: "type", + switches: [["iPv4", "ipv4"], ["iPv6", "ipv6"]], + arms: { + ipv4: xdr.opaque(4), + ipv6: xdr.opaque(16) + } + }); + + // === xdr source ============================================================ + // + // struct PeerAddress + // { + // union switch (IPAddrType type) + // { + // case IPv4: + // opaque ipv4[4]; + // case IPv6: + // opaque ipv6[16]; + // } + // ip; + // uint32 port; + // uint32 numFailures; + // }; + // + // =========================================================================== + xdr.struct("PeerAddress", [["ip", xdr.lookup("PeerAddressIp")], ["port", xdr.lookup("Uint32")], ["numFailures", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // enum MessageType + // { + // ERROR_MSG = 0, + // AUTH = 2, + // DONT_HAVE = 3, + // + // GET_PEERS = 4, // gets a list of peers this guy knows about + // PEERS = 5, + // + // GET_TX_SET = 6, // gets a particular txset by hash + // TX_SET = 7, + // GENERALIZED_TX_SET = 17, + // + // TRANSACTION = 8, // pass on a tx you have heard about + // + // // SCP + // GET_SCP_QUORUMSET = 9, + // SCP_QUORUMSET = 10, + // SCP_MESSAGE = 11, + // GET_SCP_STATE = 12, + // + // // new messages + // HELLO = 13, + // + // SURVEY_REQUEST = 14, + // SURVEY_RESPONSE = 15, + // + // SEND_MORE = 16, + // SEND_MORE_EXTENDED = 20, + // + // FLOOD_ADVERT = 18, + // FLOOD_DEMAND = 19, + // + // TIME_SLICED_SURVEY_REQUEST = 21, + // TIME_SLICED_SURVEY_RESPONSE = 22, + // TIME_SLICED_SURVEY_START_COLLECTING = 23, + // TIME_SLICED_SURVEY_STOP_COLLECTING = 24 + // }; + // + // =========================================================================== + xdr["enum"]("MessageType", { + errorMsg: 0, + auth: 2, + dontHave: 3, + getPeers: 4, + peers: 5, + getTxSet: 6, + txSet: 7, + generalizedTxSet: 17, + transaction: 8, + getScpQuorumset: 9, + scpQuorumset: 10, + scpMessage: 11, + getScpState: 12, + hello: 13, + surveyRequest: 14, + surveyResponse: 15, + sendMore: 16, + sendMoreExtended: 20, + floodAdvert: 18, + floodDemand: 19, + timeSlicedSurveyRequest: 21, + timeSlicedSurveyResponse: 22, + timeSlicedSurveyStartCollecting: 23, + timeSlicedSurveyStopCollecting: 24 + }); + + // === xdr source ============================================================ + // + // struct DontHave + // { + // MessageType type; + // uint256 reqHash; + // }; + // + // =========================================================================== + xdr.struct("DontHave", [["type", xdr.lookup("MessageType")], ["reqHash", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // enum SurveyMessageCommandType + // { + // SURVEY_TOPOLOGY = 0, + // TIME_SLICED_SURVEY_TOPOLOGY = 1 + // }; + // + // =========================================================================== + xdr["enum"]("SurveyMessageCommandType", { + surveyTopology: 0, + timeSlicedSurveyTopology: 1 + }); + + // === xdr source ============================================================ + // + // enum SurveyMessageResponseType + // { + // SURVEY_TOPOLOGY_RESPONSE_V0 = 0, + // SURVEY_TOPOLOGY_RESPONSE_V1 = 1, + // SURVEY_TOPOLOGY_RESPONSE_V2 = 2 + // }; + // + // =========================================================================== + xdr["enum"]("SurveyMessageResponseType", { + surveyTopologyResponseV0: 0, + surveyTopologyResponseV1: 1, + surveyTopologyResponseV2: 2 + }); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyStartCollectingMessage + // { + // NodeID surveyorID; + // uint32 nonce; + // uint32 ledgerNum; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyStartCollectingMessage", [["surveyorId", xdr.lookup("NodeId")], ["nonce", xdr.lookup("Uint32")], ["ledgerNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyStartCollectingMessage + // { + // Signature signature; + // TimeSlicedSurveyStartCollectingMessage startCollecting; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyStartCollectingMessage", [["signature", xdr.lookup("Signature")], ["startCollecting", xdr.lookup("TimeSlicedSurveyStartCollectingMessage")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyStopCollectingMessage + // { + // NodeID surveyorID; + // uint32 nonce; + // uint32 ledgerNum; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyStopCollectingMessage", [["surveyorId", xdr.lookup("NodeId")], ["nonce", xdr.lookup("Uint32")], ["ledgerNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyStopCollectingMessage + // { + // Signature signature; + // TimeSlicedSurveyStopCollectingMessage stopCollecting; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyStopCollectingMessage", [["signature", xdr.lookup("Signature")], ["stopCollecting", xdr.lookup("TimeSlicedSurveyStopCollectingMessage")]]); + + // === xdr source ============================================================ + // + // struct SurveyRequestMessage + // { + // NodeID surveyorPeerID; + // NodeID surveyedPeerID; + // uint32 ledgerNum; + // Curve25519Public encryptionKey; + // SurveyMessageCommandType commandType; + // }; + // + // =========================================================================== + xdr.struct("SurveyRequestMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["encryptionKey", xdr.lookup("Curve25519Public")], ["commandType", xdr.lookup("SurveyMessageCommandType")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyRequestMessage + // { + // SurveyRequestMessage request; + // uint32 nonce; + // uint32 inboundPeersIndex; + // uint32 outboundPeersIndex; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyRequestMessage", [["request", xdr.lookup("SurveyRequestMessage")], ["nonce", xdr.lookup("Uint32")], ["inboundPeersIndex", xdr.lookup("Uint32")], ["outboundPeersIndex", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedSurveyRequestMessage + // { + // Signature requestSignature; + // SurveyRequestMessage request; + // }; + // + // =========================================================================== + xdr.struct("SignedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("SurveyRequestMessage")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyRequestMessage + // { + // Signature requestSignature; + // TimeSlicedSurveyRequestMessage request; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("TimeSlicedSurveyRequestMessage")]]); + + // === xdr source ============================================================ + // + // typedef opaque EncryptedBody<64000>; + // + // =========================================================================== + xdr.typedef("EncryptedBody", xdr.varOpaque(64000)); + + // === xdr source ============================================================ + // + // struct SurveyResponseMessage + // { + // NodeID surveyorPeerID; + // NodeID surveyedPeerID; + // uint32 ledgerNum; + // SurveyMessageCommandType commandType; + // EncryptedBody encryptedBody; + // }; + // + // =========================================================================== + xdr.struct("SurveyResponseMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["commandType", xdr.lookup("SurveyMessageCommandType")], ["encryptedBody", xdr.lookup("EncryptedBody")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyResponseMessage + // { + // SurveyResponseMessage response; + // uint32 nonce; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyResponseMessage", [["response", xdr.lookup("SurveyResponseMessage")], ["nonce", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedSurveyResponseMessage + // { + // Signature responseSignature; + // SurveyResponseMessage response; + // }; + // + // =========================================================================== + xdr.struct("SignedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("SurveyResponseMessage")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyResponseMessage + // { + // Signature responseSignature; + // TimeSlicedSurveyResponseMessage response; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("TimeSlicedSurveyResponseMessage")]]); + + // === xdr source ============================================================ + // + // struct PeerStats + // { + // NodeID id; + // string versionStr<100>; + // uint64 messagesRead; + // uint64 messagesWritten; + // uint64 bytesRead; + // uint64 bytesWritten; + // uint64 secondsConnected; + // + // uint64 uniqueFloodBytesRecv; + // uint64 duplicateFloodBytesRecv; + // uint64 uniqueFetchBytesRecv; + // uint64 duplicateFetchBytesRecv; + // + // uint64 uniqueFloodMessageRecv; + // uint64 duplicateFloodMessageRecv; + // uint64 uniqueFetchMessageRecv; + // uint64 duplicateFetchMessageRecv; + // }; + // + // =========================================================================== + xdr.struct("PeerStats", [["id", xdr.lookup("NodeId")], ["versionStr", xdr.string(100)], ["messagesRead", xdr.lookup("Uint64")], ["messagesWritten", xdr.lookup("Uint64")], ["bytesRead", xdr.lookup("Uint64")], ["bytesWritten", xdr.lookup("Uint64")], ["secondsConnected", xdr.lookup("Uint64")], ["uniqueFloodBytesRecv", xdr.lookup("Uint64")], ["duplicateFloodBytesRecv", xdr.lookup("Uint64")], ["uniqueFetchBytesRecv", xdr.lookup("Uint64")], ["duplicateFetchBytesRecv", xdr.lookup("Uint64")], ["uniqueFloodMessageRecv", xdr.lookup("Uint64")], ["duplicateFloodMessageRecv", xdr.lookup("Uint64")], ["uniqueFetchMessageRecv", xdr.lookup("Uint64")], ["duplicateFetchMessageRecv", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // typedef PeerStats PeerStatList<25>; + // + // =========================================================================== + xdr.typedef("PeerStatList", xdr.varArray(xdr.lookup("PeerStats"), 25)); + + // === xdr source ============================================================ + // + // struct TimeSlicedNodeData + // { + // uint32 addedAuthenticatedPeers; + // uint32 droppedAuthenticatedPeers; + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // + // // SCP stats + // uint32 p75SCPFirstToSelfLatencyMs; + // uint32 p75SCPSelfToOtherLatencyMs; + // + // // How many times the node lost sync in the time slice + // uint32 lostSyncCount; + // + // // Config data + // bool isValidator; + // uint32 maxInboundPeerCount; + // uint32 maxOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedNodeData", [["addedAuthenticatedPeers", xdr.lookup("Uint32")], ["droppedAuthenticatedPeers", xdr.lookup("Uint32")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")], ["p75ScpFirstToSelfLatencyMs", xdr.lookup("Uint32")], ["p75ScpSelfToOtherLatencyMs", xdr.lookup("Uint32")], ["lostSyncCount", xdr.lookup("Uint32")], ["isValidator", xdr.bool()], ["maxInboundPeerCount", xdr.lookup("Uint32")], ["maxOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedPeerData + // { + // PeerStats peerStats; + // uint32 averageLatencyMs; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedPeerData", [["peerStats", xdr.lookup("PeerStats")], ["averageLatencyMs", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // typedef TimeSlicedPeerData TimeSlicedPeerDataList<25>; + // + // =========================================================================== + xdr.typedef("TimeSlicedPeerDataList", xdr.varArray(xdr.lookup("TimeSlicedPeerData"), 25)); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV0 + // { + // PeerStatList inboundPeers; + // PeerStatList outboundPeers; + // + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV0", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV1 + // { + // PeerStatList inboundPeers; + // PeerStatList outboundPeers; + // + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // + // uint32 maxInboundPeerCount; + // uint32 maxOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV1", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")], ["maxInboundPeerCount", xdr.lookup("Uint32")], ["maxOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV2 + // { + // TimeSlicedPeerDataList inboundPeers; + // TimeSlicedPeerDataList outboundPeers; + // TimeSlicedNodeData nodeData; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV2", [["inboundPeers", xdr.lookup("TimeSlicedPeerDataList")], ["outboundPeers", xdr.lookup("TimeSlicedPeerDataList")], ["nodeData", xdr.lookup("TimeSlicedNodeData")]]); + + // === xdr source ============================================================ + // + // union SurveyResponseBody switch (SurveyMessageResponseType type) + // { + // case SURVEY_TOPOLOGY_RESPONSE_V0: + // TopologyResponseBodyV0 topologyResponseBodyV0; + // case SURVEY_TOPOLOGY_RESPONSE_V1: + // TopologyResponseBodyV1 topologyResponseBodyV1; + // case SURVEY_TOPOLOGY_RESPONSE_V2: + // TopologyResponseBodyV2 topologyResponseBodyV2; + // }; + // + // =========================================================================== + xdr.union("SurveyResponseBody", { + switchOn: xdr.lookup("SurveyMessageResponseType"), + switchName: "type", + switches: [["surveyTopologyResponseV0", "topologyResponseBodyV0"], ["surveyTopologyResponseV1", "topologyResponseBodyV1"], ["surveyTopologyResponseV2", "topologyResponseBodyV2"]], + arms: { + topologyResponseBodyV0: xdr.lookup("TopologyResponseBodyV0"), + topologyResponseBodyV1: xdr.lookup("TopologyResponseBodyV1"), + topologyResponseBodyV2: xdr.lookup("TopologyResponseBodyV2") + } + }); + + // === xdr source ============================================================ + // + // const TX_ADVERT_VECTOR_MAX_SIZE = 1000; + // + // =========================================================================== + xdr["const"]("TX_ADVERT_VECTOR_MAX_SIZE", 1000); + + // === xdr source ============================================================ + // + // typedef Hash TxAdvertVector; + // + // =========================================================================== + xdr.typedef("TxAdvertVector", xdr.varArray(xdr.lookup("Hash"), xdr.lookup("TX_ADVERT_VECTOR_MAX_SIZE"))); + + // === xdr source ============================================================ + // + // struct FloodAdvert + // { + // TxAdvertVector txHashes; + // }; + // + // =========================================================================== + xdr.struct("FloodAdvert", [["txHashes", xdr.lookup("TxAdvertVector")]]); + + // === xdr source ============================================================ + // + // const TX_DEMAND_VECTOR_MAX_SIZE = 1000; + // + // =========================================================================== + xdr["const"]("TX_DEMAND_VECTOR_MAX_SIZE", 1000); + + // === xdr source ============================================================ + // + // typedef Hash TxDemandVector; + // + // =========================================================================== + xdr.typedef("TxDemandVector", xdr.varArray(xdr.lookup("Hash"), xdr.lookup("TX_DEMAND_VECTOR_MAX_SIZE"))); + + // === xdr source ============================================================ + // + // struct FloodDemand + // { + // TxDemandVector txHashes; + // }; + // + // =========================================================================== + xdr.struct("FloodDemand", [["txHashes", xdr.lookup("TxDemandVector")]]); + + // === xdr source ============================================================ + // + // union StellarMessage switch (MessageType type) + // { + // case ERROR_MSG: + // Error error; + // case HELLO: + // Hello hello; + // case AUTH: + // Auth auth; + // case DONT_HAVE: + // DontHave dontHave; + // case GET_PEERS: + // void; + // case PEERS: + // PeerAddress peers<100>; + // + // case GET_TX_SET: + // uint256 txSetHash; + // case TX_SET: + // TransactionSet txSet; + // case GENERALIZED_TX_SET: + // GeneralizedTransactionSet generalizedTxSet; + // + // case TRANSACTION: + // TransactionEnvelope transaction; + // + // case SURVEY_REQUEST: + // SignedSurveyRequestMessage signedSurveyRequestMessage; + // + // case SURVEY_RESPONSE: + // SignedSurveyResponseMessage signedSurveyResponseMessage; + // + // case TIME_SLICED_SURVEY_REQUEST: + // SignedTimeSlicedSurveyRequestMessage signedTimeSlicedSurveyRequestMessage; + // + // case TIME_SLICED_SURVEY_RESPONSE: + // SignedTimeSlicedSurveyResponseMessage signedTimeSlicedSurveyResponseMessage; + // + // case TIME_SLICED_SURVEY_START_COLLECTING: + // SignedTimeSlicedSurveyStartCollectingMessage + // signedTimeSlicedSurveyStartCollectingMessage; + // + // case TIME_SLICED_SURVEY_STOP_COLLECTING: + // SignedTimeSlicedSurveyStopCollectingMessage + // signedTimeSlicedSurveyStopCollectingMessage; + // + // // SCP + // case GET_SCP_QUORUMSET: + // uint256 qSetHash; + // case SCP_QUORUMSET: + // SCPQuorumSet qSet; + // case SCP_MESSAGE: + // SCPEnvelope envelope; + // case GET_SCP_STATE: + // uint32 getSCPLedgerSeq; // ledger seq requested ; if 0, requests the latest + // case SEND_MORE: + // SendMore sendMoreMessage; + // case SEND_MORE_EXTENDED: + // SendMoreExtended sendMoreExtendedMessage; + // // Pull mode + // case FLOOD_ADVERT: + // FloodAdvert floodAdvert; + // case FLOOD_DEMAND: + // FloodDemand floodDemand; + // }; + // + // =========================================================================== + xdr.union("StellarMessage", { + switchOn: xdr.lookup("MessageType"), + switchName: "type", + switches: [["errorMsg", "error"], ["hello", "hello"], ["auth", "auth"], ["dontHave", "dontHave"], ["getPeers", xdr["void"]()], ["peers", "peers"], ["getTxSet", "txSetHash"], ["txSet", "txSet"], ["generalizedTxSet", "generalizedTxSet"], ["transaction", "transaction"], ["surveyRequest", "signedSurveyRequestMessage"], ["surveyResponse", "signedSurveyResponseMessage"], ["timeSlicedSurveyRequest", "signedTimeSlicedSurveyRequestMessage"], ["timeSlicedSurveyResponse", "signedTimeSlicedSurveyResponseMessage"], ["timeSlicedSurveyStartCollecting", "signedTimeSlicedSurveyStartCollectingMessage"], ["timeSlicedSurveyStopCollecting", "signedTimeSlicedSurveyStopCollectingMessage"], ["getScpQuorumset", "qSetHash"], ["scpQuorumset", "qSet"], ["scpMessage", "envelope"], ["getScpState", "getScpLedgerSeq"], ["sendMore", "sendMoreMessage"], ["sendMoreExtended", "sendMoreExtendedMessage"], ["floodAdvert", "floodAdvert"], ["floodDemand", "floodDemand"]], + arms: { + error: xdr.lookup("Error"), + hello: xdr.lookup("Hello"), + auth: xdr.lookup("Auth"), + dontHave: xdr.lookup("DontHave"), + peers: xdr.varArray(xdr.lookup("PeerAddress"), 100), + txSetHash: xdr.lookup("Uint256"), + txSet: xdr.lookup("TransactionSet"), + generalizedTxSet: xdr.lookup("GeneralizedTransactionSet"), + transaction: xdr.lookup("TransactionEnvelope"), + signedSurveyRequestMessage: xdr.lookup("SignedSurveyRequestMessage"), + signedSurveyResponseMessage: xdr.lookup("SignedSurveyResponseMessage"), + signedTimeSlicedSurveyRequestMessage: xdr.lookup("SignedTimeSlicedSurveyRequestMessage"), + signedTimeSlicedSurveyResponseMessage: xdr.lookup("SignedTimeSlicedSurveyResponseMessage"), + signedTimeSlicedSurveyStartCollectingMessage: xdr.lookup("SignedTimeSlicedSurveyStartCollectingMessage"), + signedTimeSlicedSurveyStopCollectingMessage: xdr.lookup("SignedTimeSlicedSurveyStopCollectingMessage"), + qSetHash: xdr.lookup("Uint256"), + qSet: xdr.lookup("ScpQuorumSet"), + envelope: xdr.lookup("ScpEnvelope"), + getScpLedgerSeq: xdr.lookup("Uint32"), + sendMoreMessage: xdr.lookup("SendMore"), + sendMoreExtendedMessage: xdr.lookup("SendMoreExtended"), + floodAdvert: xdr.lookup("FloodAdvert"), + floodDemand: xdr.lookup("FloodDemand") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // uint64 sequence; + // StellarMessage message; + // HmacSha256Mac mac; + // } + // + // =========================================================================== + xdr.struct("AuthenticatedMessageV0", [["sequence", xdr.lookup("Uint64")], ["message", xdr.lookup("StellarMessage")], ["mac", xdr.lookup("HmacSha256Mac")]]); + + // === xdr source ============================================================ + // + // union AuthenticatedMessage switch (uint32 v) + // { + // case 0: + // struct + // { + // uint64 sequence; + // StellarMessage message; + // HmacSha256Mac mac; + // } v0; + // }; + // + // =========================================================================== + xdr.union("AuthenticatedMessage", { + switchOn: xdr.lookup("Uint32"), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("AuthenticatedMessageV0") + } + }); + + // === xdr source ============================================================ + // + // const MAX_OPS_PER_TX = 100; + // + // =========================================================================== + xdr["const"]("MAX_OPS_PER_TX", 100); + + // === xdr source ============================================================ + // + // union LiquidityPoolParameters switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // LiquidityPoolConstantProductParameters constantProduct; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolParameters", { + switchOn: xdr.lookup("LiquidityPoolType"), + switchName: "type", + switches: [["liquidityPoolConstantProduct", "constantProduct"]], + arms: { + constantProduct: xdr.lookup("LiquidityPoolConstantProductParameters") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // uint64 id; + // uint256 ed25519; + // } + // + // =========================================================================== + xdr.struct("MuxedAccountMed25519", [["id", xdr.lookup("Uint64")], ["ed25519", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // union MuxedAccount switch (CryptoKeyType type) + // { + // case KEY_TYPE_ED25519: + // uint256 ed25519; + // case KEY_TYPE_MUXED_ED25519: + // struct + // { + // uint64 id; + // uint256 ed25519; + // } med25519; + // }; + // + // =========================================================================== + xdr.union("MuxedAccount", { + switchOn: xdr.lookup("CryptoKeyType"), + switchName: "type", + switches: [["keyTypeEd25519", "ed25519"], ["keyTypeMuxedEd25519", "med25519"]], + arms: { + ed25519: xdr.lookup("Uint256"), + med25519: xdr.lookup("MuxedAccountMed25519") + } + }); + + // === xdr source ============================================================ + // + // struct DecoratedSignature + // { + // SignatureHint hint; // last 4 bytes of the public key, used as a hint + // Signature signature; // actual signature + // }; + // + // =========================================================================== + xdr.struct("DecoratedSignature", [["hint", xdr.lookup("SignatureHint")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // enum OperationType + // { + // CREATE_ACCOUNT = 0, + // PAYMENT = 1, + // PATH_PAYMENT_STRICT_RECEIVE = 2, + // MANAGE_SELL_OFFER = 3, + // CREATE_PASSIVE_SELL_OFFER = 4, + // SET_OPTIONS = 5, + // CHANGE_TRUST = 6, + // ALLOW_TRUST = 7, + // ACCOUNT_MERGE = 8, + // INFLATION = 9, + // MANAGE_DATA = 10, + // BUMP_SEQUENCE = 11, + // MANAGE_BUY_OFFER = 12, + // PATH_PAYMENT_STRICT_SEND = 13, + // CREATE_CLAIMABLE_BALANCE = 14, + // CLAIM_CLAIMABLE_BALANCE = 15, + // BEGIN_SPONSORING_FUTURE_RESERVES = 16, + // END_SPONSORING_FUTURE_RESERVES = 17, + // REVOKE_SPONSORSHIP = 18, + // CLAWBACK = 19, + // CLAWBACK_CLAIMABLE_BALANCE = 20, + // SET_TRUST_LINE_FLAGS = 21, + // LIQUIDITY_POOL_DEPOSIT = 22, + // LIQUIDITY_POOL_WITHDRAW = 23, + // INVOKE_HOST_FUNCTION = 24, + // EXTEND_FOOTPRINT_TTL = 25, + // RESTORE_FOOTPRINT = 26 + // }; + // + // =========================================================================== + xdr["enum"]("OperationType", { + createAccount: 0, + payment: 1, + pathPaymentStrictReceive: 2, + manageSellOffer: 3, + createPassiveSellOffer: 4, + setOptions: 5, + changeTrust: 6, + allowTrust: 7, + accountMerge: 8, + inflation: 9, + manageData: 10, + bumpSequence: 11, + manageBuyOffer: 12, + pathPaymentStrictSend: 13, + createClaimableBalance: 14, + claimClaimableBalance: 15, + beginSponsoringFutureReserves: 16, + endSponsoringFutureReserves: 17, + revokeSponsorship: 18, + clawback: 19, + clawbackClaimableBalance: 20, + setTrustLineFlags: 21, + liquidityPoolDeposit: 22, + liquidityPoolWithdraw: 23, + invokeHostFunction: 24, + extendFootprintTtl: 25, + restoreFootprint: 26 + }); + + // === xdr source ============================================================ + // + // struct CreateAccountOp + // { + // AccountID destination; // account to create + // int64 startingBalance; // amount they end up with + // }; + // + // =========================================================================== + xdr.struct("CreateAccountOp", [["destination", xdr.lookup("AccountId")], ["startingBalance", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct PaymentOp + // { + // MuxedAccount destination; // recipient of the payment + // Asset asset; // what they end up with + // int64 amount; // amount they end up with + // }; + // + // =========================================================================== + xdr.struct("PaymentOp", [["destination", xdr.lookup("MuxedAccount")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct PathPaymentStrictReceiveOp + // { + // Asset sendAsset; // asset we pay with + // int64 sendMax; // the maximum amount of sendAsset to + // // send (excluding fees). + // // The operation will fail if can't be met + // + // MuxedAccount destination; // recipient of the payment + // Asset destAsset; // what they end up with + // int64 destAmount; // amount they end up with + // + // Asset path<5>; // additional hops it must go through to get there + // }; + // + // =========================================================================== + xdr.struct("PathPaymentStrictReceiveOp", [["sendAsset", xdr.lookup("Asset")], ["sendMax", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destAmount", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]); + + // === xdr source ============================================================ + // + // struct PathPaymentStrictSendOp + // { + // Asset sendAsset; // asset we pay with + // int64 sendAmount; // amount of sendAsset to send (excluding fees) + // + // MuxedAccount destination; // recipient of the payment + // Asset destAsset; // what they end up with + // int64 destMin; // the minimum amount of dest asset to + // // be received + // // The operation will fail if it can't be met + // + // Asset path<5>; // additional hops it must go through to get there + // }; + // + // =========================================================================== + xdr.struct("PathPaymentStrictSendOp", [["sendAsset", xdr.lookup("Asset")], ["sendAmount", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destMin", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]); + + // === xdr source ============================================================ + // + // struct ManageSellOfferOp + // { + // Asset selling; + // Asset buying; + // int64 amount; // amount being sold. if set to 0, delete the offer + // Price price; // price of thing being sold in terms of what you are buying + // + // // 0=create a new offer, otherwise edit an existing offer + // int64 offerID; + // }; + // + // =========================================================================== + xdr.struct("ManageSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ManageBuyOfferOp + // { + // Asset selling; + // Asset buying; + // int64 buyAmount; // amount being bought. if set to 0, delete the offer + // Price price; // price of thing being bought in terms of what you are + // // selling + // + // // 0=create a new offer, otherwise edit an existing offer + // int64 offerID; + // }; + // + // =========================================================================== + xdr.struct("ManageBuyOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["buyAmount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct CreatePassiveSellOfferOp + // { + // Asset selling; // A + // Asset buying; // B + // int64 amount; // amount taker gets + // Price price; // cost of A in terms of B + // }; + // + // =========================================================================== + xdr.struct("CreatePassiveSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")]]); + + // === xdr source ============================================================ + // + // struct SetOptionsOp + // { + // AccountID* inflationDest; // sets the inflation destination + // + // uint32* clearFlags; // which flags to clear + // uint32* setFlags; // which flags to set + // + // // account threshold manipulation + // uint32* masterWeight; // weight of the master account + // uint32* lowThreshold; + // uint32* medThreshold; + // uint32* highThreshold; + // + // string32* homeDomain; // sets the home domain + // + // // Add, update or remove a signer for the account + // // signer is deleted if the weight is 0 + // Signer* signer; + // }; + // + // =========================================================================== + xdr.struct("SetOptionsOp", [["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["clearFlags", xdr.option(xdr.lookup("Uint32"))], ["setFlags", xdr.option(xdr.lookup("Uint32"))], ["masterWeight", xdr.option(xdr.lookup("Uint32"))], ["lowThreshold", xdr.option(xdr.lookup("Uint32"))], ["medThreshold", xdr.option(xdr.lookup("Uint32"))], ["highThreshold", xdr.option(xdr.lookup("Uint32"))], ["homeDomain", xdr.option(xdr.lookup("String32"))], ["signer", xdr.option(xdr.lookup("Signer"))]]); + + // === xdr source ============================================================ + // + // union ChangeTrustAsset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // case ASSET_TYPE_POOL_SHARE: + // LiquidityPoolParameters liquidityPool; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("ChangeTrustAsset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPool"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12"), + liquidityPool: xdr.lookup("LiquidityPoolParameters") + } + }); + + // === xdr source ============================================================ + // + // struct ChangeTrustOp + // { + // ChangeTrustAsset line; + // + // // if limit is set to 0, deletes the trust line + // int64 limit; + // }; + // + // =========================================================================== + xdr.struct("ChangeTrustOp", [["line", xdr.lookup("ChangeTrustAsset")], ["limit", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct AllowTrustOp + // { + // AccountID trustor; + // AssetCode asset; + // + // // One of 0, AUTHORIZED_FLAG, or AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG + // uint32 authorize; + // }; + // + // =========================================================================== + xdr.struct("AllowTrustOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("AssetCode")], ["authorize", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ManageDataOp + // { + // string64 dataName; + // DataValue* dataValue; // set to null to clear + // }; + // + // =========================================================================== + xdr.struct("ManageDataOp", [["dataName", xdr.lookup("String64")], ["dataValue", xdr.option(xdr.lookup("DataValue"))]]); + + // === xdr source ============================================================ + // + // struct BumpSequenceOp + // { + // SequenceNumber bumpTo; + // }; + // + // =========================================================================== + xdr.struct("BumpSequenceOp", [["bumpTo", xdr.lookup("SequenceNumber")]]); + + // === xdr source ============================================================ + // + // struct CreateClaimableBalanceOp + // { + // Asset asset; + // int64 amount; + // Claimant claimants<10>; + // }; + // + // =========================================================================== + xdr.struct("CreateClaimableBalanceOp", [["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)]]); + + // === xdr source ============================================================ + // + // struct ClaimClaimableBalanceOp + // { + // ClaimableBalanceID balanceID; + // }; + // + // =========================================================================== + xdr.struct("ClaimClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct BeginSponsoringFutureReservesOp + // { + // AccountID sponsoredID; + // }; + // + // =========================================================================== + xdr.struct("BeginSponsoringFutureReservesOp", [["sponsoredId", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // enum RevokeSponsorshipType + // { + // REVOKE_SPONSORSHIP_LEDGER_ENTRY = 0, + // REVOKE_SPONSORSHIP_SIGNER = 1 + // }; + // + // =========================================================================== + xdr["enum"]("RevokeSponsorshipType", { + revokeSponsorshipLedgerEntry: 0, + revokeSponsorshipSigner: 1 + }); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // SignerKey signerKey; + // } + // + // =========================================================================== + xdr.struct("RevokeSponsorshipOpSigner", [["accountId", xdr.lookup("AccountId")], ["signerKey", xdr.lookup("SignerKey")]]); + + // === xdr source ============================================================ + // + // union RevokeSponsorshipOp switch (RevokeSponsorshipType type) + // { + // case REVOKE_SPONSORSHIP_LEDGER_ENTRY: + // LedgerKey ledgerKey; + // case REVOKE_SPONSORSHIP_SIGNER: + // struct + // { + // AccountID accountID; + // SignerKey signerKey; + // } signer; + // }; + // + // =========================================================================== + xdr.union("RevokeSponsorshipOp", { + switchOn: xdr.lookup("RevokeSponsorshipType"), + switchName: "type", + switches: [["revokeSponsorshipLedgerEntry", "ledgerKey"], ["revokeSponsorshipSigner", "signer"]], + arms: { + ledgerKey: xdr.lookup("LedgerKey"), + signer: xdr.lookup("RevokeSponsorshipOpSigner") + } + }); + + // === xdr source ============================================================ + // + // struct ClawbackOp + // { + // Asset asset; + // MuxedAccount from; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("ClawbackOp", [["asset", xdr.lookup("Asset")], ["from", xdr.lookup("MuxedAccount")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClawbackClaimableBalanceOp + // { + // ClaimableBalanceID balanceID; + // }; + // + // =========================================================================== + xdr.struct("ClawbackClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct SetTrustLineFlagsOp + // { + // AccountID trustor; + // Asset asset; + // + // uint32 clearFlags; // which flags to clear + // uint32 setFlags; // which flags to set + // }; + // + // =========================================================================== + xdr.struct("SetTrustLineFlagsOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["clearFlags", xdr.lookup("Uint32")], ["setFlags", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // const LIQUIDITY_POOL_FEE_V18 = 30; + // + // =========================================================================== + xdr["const"]("LIQUIDITY_POOL_FEE_V18", 30); + + // === xdr source ============================================================ + // + // struct LiquidityPoolDepositOp + // { + // PoolID liquidityPoolID; + // int64 maxAmountA; // maximum amount of first asset to deposit + // int64 maxAmountB; // maximum amount of second asset to deposit + // Price minPrice; // minimum depositA/depositB + // Price maxPrice; // maximum depositA/depositB + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolDepositOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["maxAmountA", xdr.lookup("Int64")], ["maxAmountB", xdr.lookup("Int64")], ["minPrice", xdr.lookup("Price")], ["maxPrice", xdr.lookup("Price")]]); + + // === xdr source ============================================================ + // + // struct LiquidityPoolWithdrawOp + // { + // PoolID liquidityPoolID; + // int64 amount; // amount of pool shares to withdraw + // int64 minAmountA; // minimum amount of first asset to withdraw + // int64 minAmountB; // minimum amount of second asset to withdraw + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolWithdrawOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["amount", xdr.lookup("Int64")], ["minAmountA", xdr.lookup("Int64")], ["minAmountB", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum HostFunctionType + // { + // HOST_FUNCTION_TYPE_INVOKE_CONTRACT = 0, + // HOST_FUNCTION_TYPE_CREATE_CONTRACT = 1, + // HOST_FUNCTION_TYPE_UPLOAD_CONTRACT_WASM = 2, + // HOST_FUNCTION_TYPE_CREATE_CONTRACT_V2 = 3 + // }; + // + // =========================================================================== + xdr["enum"]("HostFunctionType", { + hostFunctionTypeInvokeContract: 0, + hostFunctionTypeCreateContract: 1, + hostFunctionTypeUploadContractWasm: 2, + hostFunctionTypeCreateContractV2: 3 + }); + + // === xdr source ============================================================ + // + // enum ContractIDPreimageType + // { + // CONTRACT_ID_PREIMAGE_FROM_ADDRESS = 0, + // CONTRACT_ID_PREIMAGE_FROM_ASSET = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractIdPreimageType", { + contractIdPreimageFromAddress: 0, + contractIdPreimageFromAsset: 1 + }); + + // === xdr source ============================================================ + // + // struct + // { + // SCAddress address; + // uint256 salt; + // } + // + // =========================================================================== + xdr.struct("ContractIdPreimageFromAddress", [["address", xdr.lookup("ScAddress")], ["salt", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // union ContractIDPreimage switch (ContractIDPreimageType type) + // { + // case CONTRACT_ID_PREIMAGE_FROM_ADDRESS: + // struct + // { + // SCAddress address; + // uint256 salt; + // } fromAddress; + // case CONTRACT_ID_PREIMAGE_FROM_ASSET: + // Asset fromAsset; + // }; + // + // =========================================================================== + xdr.union("ContractIdPreimage", { + switchOn: xdr.lookup("ContractIdPreimageType"), + switchName: "type", + switches: [["contractIdPreimageFromAddress", "fromAddress"], ["contractIdPreimageFromAsset", "fromAsset"]], + arms: { + fromAddress: xdr.lookup("ContractIdPreimageFromAddress"), + fromAsset: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // struct CreateContractArgs + // { + // ContractIDPreimage contractIDPreimage; + // ContractExecutable executable; + // }; + // + // =========================================================================== + xdr.struct("CreateContractArgs", [["contractIdPreimage", xdr.lookup("ContractIdPreimage")], ["executable", xdr.lookup("ContractExecutable")]]); + + // === xdr source ============================================================ + // + // struct CreateContractArgsV2 + // { + // ContractIDPreimage contractIDPreimage; + // ContractExecutable executable; + // // Arguments of the contract's constructor. + // SCVal constructorArgs<>; + // }; + // + // =========================================================================== + xdr.struct("CreateContractArgsV2", [["contractIdPreimage", xdr.lookup("ContractIdPreimage")], ["executable", xdr.lookup("ContractExecutable")], ["constructorArgs", xdr.varArray(xdr.lookup("ScVal"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct InvokeContractArgs { + // SCAddress contractAddress; + // SCSymbol functionName; + // SCVal args<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeContractArgs", [["contractAddress", xdr.lookup("ScAddress")], ["functionName", xdr.lookup("ScSymbol")], ["args", xdr.varArray(xdr.lookup("ScVal"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union HostFunction switch (HostFunctionType type) + // { + // case HOST_FUNCTION_TYPE_INVOKE_CONTRACT: + // InvokeContractArgs invokeContract; + // case HOST_FUNCTION_TYPE_CREATE_CONTRACT: + // CreateContractArgs createContract; + // case HOST_FUNCTION_TYPE_UPLOAD_CONTRACT_WASM: + // opaque wasm<>; + // case HOST_FUNCTION_TYPE_CREATE_CONTRACT_V2: + // CreateContractArgsV2 createContractV2; + // }; + // + // =========================================================================== + xdr.union("HostFunction", { + switchOn: xdr.lookup("HostFunctionType"), + switchName: "type", + switches: [["hostFunctionTypeInvokeContract", "invokeContract"], ["hostFunctionTypeCreateContract", "createContract"], ["hostFunctionTypeUploadContractWasm", "wasm"], ["hostFunctionTypeCreateContractV2", "createContractV2"]], + arms: { + invokeContract: xdr.lookup("InvokeContractArgs"), + createContract: xdr.lookup("CreateContractArgs"), + wasm: xdr.varOpaque(), + createContractV2: xdr.lookup("CreateContractArgsV2") + } + }); + + // === xdr source ============================================================ + // + // enum SorobanAuthorizedFunctionType + // { + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN = 0, + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_HOST_FN = 1, + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN = 2 + // }; + // + // =========================================================================== + xdr["enum"]("SorobanAuthorizedFunctionType", { + sorobanAuthorizedFunctionTypeContractFn: 0, + sorobanAuthorizedFunctionTypeCreateContractHostFn: 1, + sorobanAuthorizedFunctionTypeCreateContractV2HostFn: 2 + }); + + // === xdr source ============================================================ + // + // union SorobanAuthorizedFunction switch (SorobanAuthorizedFunctionType type) + // { + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN: + // InvokeContractArgs contractFn; + // // This variant of auth payload for creating new contract instances + // // doesn't allow specifying the constructor arguments, creating contracts + // // with constructors that take arguments is only possible by authorizing + // // `SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN` + // // (protocol 22+). + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_HOST_FN: + // CreateContractArgs createContractHostFn; + // // This variant of auth payload for creating new contract instances + // // is only accepted in and after protocol 22. It allows authorizing the + // // contract constructor arguments. + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN: + // CreateContractArgsV2 createContractV2HostFn; + // }; + // + // =========================================================================== + xdr.union("SorobanAuthorizedFunction", { + switchOn: xdr.lookup("SorobanAuthorizedFunctionType"), + switchName: "type", + switches: [["sorobanAuthorizedFunctionTypeContractFn", "contractFn"], ["sorobanAuthorizedFunctionTypeCreateContractHostFn", "createContractHostFn"], ["sorobanAuthorizedFunctionTypeCreateContractV2HostFn", "createContractV2HostFn"]], + arms: { + contractFn: xdr.lookup("InvokeContractArgs"), + createContractHostFn: xdr.lookup("CreateContractArgs"), + createContractV2HostFn: xdr.lookup("CreateContractArgsV2") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanAuthorizedInvocation + // { + // SorobanAuthorizedFunction function; + // SorobanAuthorizedInvocation subInvocations<>; + // }; + // + // =========================================================================== + xdr.struct("SorobanAuthorizedInvocation", [["function", xdr.lookup("SorobanAuthorizedFunction")], ["subInvocations", xdr.varArray(xdr.lookup("SorobanAuthorizedInvocation"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct SorobanAddressCredentials + // { + // SCAddress address; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SCVal signature; + // }; + // + // =========================================================================== + xdr.struct("SorobanAddressCredentials", [["address", xdr.lookup("ScAddress")], ["nonce", xdr.lookup("Int64")], ["signatureExpirationLedger", xdr.lookup("Uint32")], ["signature", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // enum SorobanCredentialsType + // { + // SOROBAN_CREDENTIALS_SOURCE_ACCOUNT = 0, + // SOROBAN_CREDENTIALS_ADDRESS = 1 + // }; + // + // =========================================================================== + xdr["enum"]("SorobanCredentialsType", { + sorobanCredentialsSourceAccount: 0, + sorobanCredentialsAddress: 1 + }); + + // === xdr source ============================================================ + // + // union SorobanCredentials switch (SorobanCredentialsType type) + // { + // case SOROBAN_CREDENTIALS_SOURCE_ACCOUNT: + // void; + // case SOROBAN_CREDENTIALS_ADDRESS: + // SorobanAddressCredentials address; + // }; + // + // =========================================================================== + xdr.union("SorobanCredentials", { + switchOn: xdr.lookup("SorobanCredentialsType"), + switchName: "type", + switches: [["sorobanCredentialsSourceAccount", xdr["void"]()], ["sorobanCredentialsAddress", "address"]], + arms: { + address: xdr.lookup("SorobanAddressCredentials") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanAuthorizationEntry + // { + // SorobanCredentials credentials; + // SorobanAuthorizedInvocation rootInvocation; + // }; + // + // =========================================================================== + xdr.struct("SorobanAuthorizationEntry", [["credentials", xdr.lookup("SorobanCredentials")], ["rootInvocation", xdr.lookup("SorobanAuthorizedInvocation")]]); + + // === xdr source ============================================================ + // + // struct InvokeHostFunctionOp + // { + // // Host function to invoke. + // HostFunction hostFunction; + // // Per-address authorizations for this host function. + // SorobanAuthorizationEntry auth<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeHostFunctionOp", [["hostFunction", xdr.lookup("HostFunction")], ["auth", xdr.varArray(xdr.lookup("SorobanAuthorizationEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct ExtendFootprintTTLOp + // { + // ExtensionPoint ext; + // uint32 extendTo; + // }; + // + // =========================================================================== + xdr.struct("ExtendFootprintTtlOp", [["ext", xdr.lookup("ExtensionPoint")], ["extendTo", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct RestoreFootprintOp + // { + // ExtensionPoint ext; + // }; + // + // =========================================================================== + xdr.struct("RestoreFootprintOp", [["ext", xdr.lookup("ExtensionPoint")]]); + + // === xdr source ============================================================ + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountOp createAccountOp; + // case PAYMENT: + // PaymentOp paymentOp; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp; + // case MANAGE_SELL_OFFER: + // ManageSellOfferOp manageSellOfferOp; + // case CREATE_PASSIVE_SELL_OFFER: + // CreatePassiveSellOfferOp createPassiveSellOfferOp; + // case SET_OPTIONS: + // SetOptionsOp setOptionsOp; + // case CHANGE_TRUST: + // ChangeTrustOp changeTrustOp; + // case ALLOW_TRUST: + // AllowTrustOp allowTrustOp; + // case ACCOUNT_MERGE: + // MuxedAccount destination; + // case INFLATION: + // void; + // case MANAGE_DATA: + // ManageDataOp manageDataOp; + // case BUMP_SEQUENCE: + // BumpSequenceOp bumpSequenceOp; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferOp manageBuyOfferOp; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendOp pathPaymentStrictSendOp; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceOp createClaimableBalanceOp; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceOp claimClaimableBalanceOp; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp; + // case END_SPONSORING_FUTURE_RESERVES: + // void; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipOp revokeSponsorshipOp; + // case CLAWBACK: + // ClawbackOp clawbackOp; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceOp clawbackClaimableBalanceOp; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsOp setTrustLineFlagsOp; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositOp liquidityPoolDepositOp; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawOp liquidityPoolWithdrawOp; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionOp invokeHostFunctionOp; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLOp extendFootprintTTLOp; + // case RESTORE_FOOTPRINT: + // RestoreFootprintOp restoreFootprintOp; + // } + // + // =========================================================================== + xdr.union("OperationBody", { + switchOn: xdr.lookup("OperationType"), + switchName: "type", + switches: [["createAccount", "createAccountOp"], ["payment", "paymentOp"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveOp"], ["manageSellOffer", "manageSellOfferOp"], ["createPassiveSellOffer", "createPassiveSellOfferOp"], ["setOptions", "setOptionsOp"], ["changeTrust", "changeTrustOp"], ["allowTrust", "allowTrustOp"], ["accountMerge", "destination"], ["inflation", xdr["void"]()], ["manageData", "manageDataOp"], ["bumpSequence", "bumpSequenceOp"], ["manageBuyOffer", "manageBuyOfferOp"], ["pathPaymentStrictSend", "pathPaymentStrictSendOp"], ["createClaimableBalance", "createClaimableBalanceOp"], ["claimClaimableBalance", "claimClaimableBalanceOp"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesOp"], ["endSponsoringFutureReserves", xdr["void"]()], ["revokeSponsorship", "revokeSponsorshipOp"], ["clawback", "clawbackOp"], ["clawbackClaimableBalance", "clawbackClaimableBalanceOp"], ["setTrustLineFlags", "setTrustLineFlagsOp"], ["liquidityPoolDeposit", "liquidityPoolDepositOp"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawOp"], ["invokeHostFunction", "invokeHostFunctionOp"], ["extendFootprintTtl", "extendFootprintTtlOp"], ["restoreFootprint", "restoreFootprintOp"]], + arms: { + createAccountOp: xdr.lookup("CreateAccountOp"), + paymentOp: xdr.lookup("PaymentOp"), + pathPaymentStrictReceiveOp: xdr.lookup("PathPaymentStrictReceiveOp"), + manageSellOfferOp: xdr.lookup("ManageSellOfferOp"), + createPassiveSellOfferOp: xdr.lookup("CreatePassiveSellOfferOp"), + setOptionsOp: xdr.lookup("SetOptionsOp"), + changeTrustOp: xdr.lookup("ChangeTrustOp"), + allowTrustOp: xdr.lookup("AllowTrustOp"), + destination: xdr.lookup("MuxedAccount"), + manageDataOp: xdr.lookup("ManageDataOp"), + bumpSequenceOp: xdr.lookup("BumpSequenceOp"), + manageBuyOfferOp: xdr.lookup("ManageBuyOfferOp"), + pathPaymentStrictSendOp: xdr.lookup("PathPaymentStrictSendOp"), + createClaimableBalanceOp: xdr.lookup("CreateClaimableBalanceOp"), + claimClaimableBalanceOp: xdr.lookup("ClaimClaimableBalanceOp"), + beginSponsoringFutureReservesOp: xdr.lookup("BeginSponsoringFutureReservesOp"), + revokeSponsorshipOp: xdr.lookup("RevokeSponsorshipOp"), + clawbackOp: xdr.lookup("ClawbackOp"), + clawbackClaimableBalanceOp: xdr.lookup("ClawbackClaimableBalanceOp"), + setTrustLineFlagsOp: xdr.lookup("SetTrustLineFlagsOp"), + liquidityPoolDepositOp: xdr.lookup("LiquidityPoolDepositOp"), + liquidityPoolWithdrawOp: xdr.lookup("LiquidityPoolWithdrawOp"), + invokeHostFunctionOp: xdr.lookup("InvokeHostFunctionOp"), + extendFootprintTtlOp: xdr.lookup("ExtendFootprintTtlOp"), + restoreFootprintOp: xdr.lookup("RestoreFootprintOp") + } + }); + + // === xdr source ============================================================ + // + // struct Operation + // { + // // sourceAccount is the account used to run the operation + // // if not set, the runtime defaults to "sourceAccount" specified at + // // the transaction level + // MuxedAccount* sourceAccount; + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountOp createAccountOp; + // case PAYMENT: + // PaymentOp paymentOp; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp; + // case MANAGE_SELL_OFFER: + // ManageSellOfferOp manageSellOfferOp; + // case CREATE_PASSIVE_SELL_OFFER: + // CreatePassiveSellOfferOp createPassiveSellOfferOp; + // case SET_OPTIONS: + // SetOptionsOp setOptionsOp; + // case CHANGE_TRUST: + // ChangeTrustOp changeTrustOp; + // case ALLOW_TRUST: + // AllowTrustOp allowTrustOp; + // case ACCOUNT_MERGE: + // MuxedAccount destination; + // case INFLATION: + // void; + // case MANAGE_DATA: + // ManageDataOp manageDataOp; + // case BUMP_SEQUENCE: + // BumpSequenceOp bumpSequenceOp; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferOp manageBuyOfferOp; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendOp pathPaymentStrictSendOp; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceOp createClaimableBalanceOp; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceOp claimClaimableBalanceOp; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp; + // case END_SPONSORING_FUTURE_RESERVES: + // void; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipOp revokeSponsorshipOp; + // case CLAWBACK: + // ClawbackOp clawbackOp; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceOp clawbackClaimableBalanceOp; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsOp setTrustLineFlagsOp; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositOp liquidityPoolDepositOp; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawOp liquidityPoolWithdrawOp; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionOp invokeHostFunctionOp; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLOp extendFootprintTTLOp; + // case RESTORE_FOOTPRINT: + // RestoreFootprintOp restoreFootprintOp; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("Operation", [["sourceAccount", xdr.option(xdr.lookup("MuxedAccount"))], ["body", xdr.lookup("OperationBody")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageOperationId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // PoolID liquidityPoolID; + // Asset asset; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageRevokeId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")], ["liquidityPoolId", xdr.lookup("PoolId")], ["asset", xdr.lookup("Asset")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash networkID; + // ContractIDPreimage contractIDPreimage; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageContractId", [["networkId", xdr.lookup("Hash")], ["contractIdPreimage", xdr.lookup("ContractIdPreimage")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash networkID; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SorobanAuthorizedInvocation invocation; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageSorobanAuthorization", [["networkId", xdr.lookup("Hash")], ["nonce", xdr.lookup("Int64")], ["signatureExpirationLedger", xdr.lookup("Uint32")], ["invocation", xdr.lookup("SorobanAuthorizedInvocation")]]); + + // === xdr source ============================================================ + // + // union HashIDPreimage switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_OP_ID: + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // } operationID; + // case ENVELOPE_TYPE_POOL_REVOKE_OP_ID: + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // PoolID liquidityPoolID; + // Asset asset; + // } revokeID; + // case ENVELOPE_TYPE_CONTRACT_ID: + // struct + // { + // Hash networkID; + // ContractIDPreimage contractIDPreimage; + // } contractID; + // case ENVELOPE_TYPE_SOROBAN_AUTHORIZATION: + // struct + // { + // Hash networkID; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SorobanAuthorizedInvocation invocation; + // } sorobanAuthorization; + // }; + // + // =========================================================================== + xdr.union("HashIdPreimage", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeOpId", "operationId"], ["envelopeTypePoolRevokeOpId", "revokeId"], ["envelopeTypeContractId", "contractId"], ["envelopeTypeSorobanAuthorization", "sorobanAuthorization"]], + arms: { + operationId: xdr.lookup("HashIdPreimageOperationId"), + revokeId: xdr.lookup("HashIdPreimageRevokeId"), + contractId: xdr.lookup("HashIdPreimageContractId"), + sorobanAuthorization: xdr.lookup("HashIdPreimageSorobanAuthorization") + } + }); + + // === xdr source ============================================================ + // + // enum MemoType + // { + // MEMO_NONE = 0, + // MEMO_TEXT = 1, + // MEMO_ID = 2, + // MEMO_HASH = 3, + // MEMO_RETURN = 4 + // }; + // + // =========================================================================== + xdr["enum"]("MemoType", { + memoNone: 0, + memoText: 1, + memoId: 2, + memoHash: 3, + memoReturn: 4 + }); + + // === xdr source ============================================================ + // + // union Memo switch (MemoType type) + // { + // case MEMO_NONE: + // void; + // case MEMO_TEXT: + // string text<28>; + // case MEMO_ID: + // uint64 id; + // case MEMO_HASH: + // Hash hash; // the hash of what to pull from the content server + // case MEMO_RETURN: + // Hash retHash; // the hash of the tx you are rejecting + // }; + // + // =========================================================================== + xdr.union("Memo", { + switchOn: xdr.lookup("MemoType"), + switchName: "type", + switches: [["memoNone", xdr["void"]()], ["memoText", "text"], ["memoId", "id"], ["memoHash", "hash"], ["memoReturn", "retHash"]], + arms: { + text: xdr.string(28), + id: xdr.lookup("Uint64"), + hash: xdr.lookup("Hash"), + retHash: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // struct TimeBounds + // { + // TimePoint minTime; + // TimePoint maxTime; // 0 here means no maxTime + // }; + // + // =========================================================================== + xdr.struct("TimeBounds", [["minTime", xdr.lookup("TimePoint")], ["maxTime", xdr.lookup("TimePoint")]]); + + // === xdr source ============================================================ + // + // struct LedgerBounds + // { + // uint32 minLedger; + // uint32 maxLedger; // 0 here means no maxLedger + // }; + // + // =========================================================================== + xdr.struct("LedgerBounds", [["minLedger", xdr.lookup("Uint32")], ["maxLedger", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct PreconditionsV2 + // { + // TimeBounds* timeBounds; + // + // // Transaction only valid for ledger numbers n such that + // // minLedger <= n < maxLedger (if maxLedger == 0, then + // // only minLedger is checked) + // LedgerBounds* ledgerBounds; + // + // // If NULL, only valid when sourceAccount's sequence number + // // is seqNum - 1. Otherwise, valid when sourceAccount's + // // sequence number n satisfies minSeqNum <= n < tx.seqNum. + // // Note that after execution the account's sequence number + // // is always raised to tx.seqNum, and a transaction is not + // // valid if tx.seqNum is too high to ensure replay protection. + // SequenceNumber* minSeqNum; + // + // // For the transaction to be valid, the current ledger time must + // // be at least minSeqAge greater than sourceAccount's seqTime. + // Duration minSeqAge; + // + // // For the transaction to be valid, the current ledger number + // // must be at least minSeqLedgerGap greater than sourceAccount's + // // seqLedger. + // uint32 minSeqLedgerGap; + // + // // For the transaction to be valid, there must be a signature + // // corresponding to every Signer in this array, even if the + // // signature is not otherwise required by the sourceAccount or + // // operations. + // SignerKey extraSigners<2>; + // }; + // + // =========================================================================== + xdr.struct("PreconditionsV2", [["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["ledgerBounds", xdr.option(xdr.lookup("LedgerBounds"))], ["minSeqNum", xdr.option(xdr.lookup("SequenceNumber"))], ["minSeqAge", xdr.lookup("Duration")], ["minSeqLedgerGap", xdr.lookup("Uint32")], ["extraSigners", xdr.varArray(xdr.lookup("SignerKey"), 2)]]); + + // === xdr source ============================================================ + // + // enum PreconditionType + // { + // PRECOND_NONE = 0, + // PRECOND_TIME = 1, + // PRECOND_V2 = 2 + // }; + // + // =========================================================================== + xdr["enum"]("PreconditionType", { + precondNone: 0, + precondTime: 1, + precondV2: 2 + }); + + // === xdr source ============================================================ + // + // union Preconditions switch (PreconditionType type) + // { + // case PRECOND_NONE: + // void; + // case PRECOND_TIME: + // TimeBounds timeBounds; + // case PRECOND_V2: + // PreconditionsV2 v2; + // }; + // + // =========================================================================== + xdr.union("Preconditions", { + switchOn: xdr.lookup("PreconditionType"), + switchName: "type", + switches: [["precondNone", xdr["void"]()], ["precondTime", "timeBounds"], ["precondV2", "v2"]], + arms: { + timeBounds: xdr.lookup("TimeBounds"), + v2: xdr.lookup("PreconditionsV2") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerFootprint + // { + // LedgerKey readOnly<>; + // LedgerKey readWrite<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerFootprint", [["readOnly", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["readWrite", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)]]); + + // === xdr source ============================================================ + // + // enum ArchivalProofType + // { + // EXISTENCE = 0, + // NONEXISTENCE = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ArchivalProofType", { + existence: 0, + nonexistence: 1 + }); + + // === xdr source ============================================================ + // + // struct ArchivalProofNode + // { + // uint32 index; + // Hash hash; + // }; + // + // =========================================================================== + xdr.struct("ArchivalProofNode", [["index", xdr.lookup("Uint32")], ["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // typedef ArchivalProofNode ProofLevel<>; + // + // =========================================================================== + xdr.typedef("ProofLevel", xdr.varArray(xdr.lookup("ArchivalProofNode"), 2147483647)); + + // === xdr source ============================================================ + // + // struct NonexistenceProofBody + // { + // ColdArchiveBucketEntry entriesToProve<>; + // + // // Vector of vectors, where proofLevels[level] + // // contains all HashNodes that correspond with that level + // ProofLevel proofLevels<>; + // }; + // + // =========================================================================== + xdr.struct("NonexistenceProofBody", [["entriesToProve", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["proofLevels", xdr.varArray(xdr.lookup("ProofLevel"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct ExistenceProofBody + // { + // LedgerKey keysToProve<>; + // + // // Bounds for each key being proved, where bound[n] + // // corresponds to keysToProve[n] + // ColdArchiveBucketEntry lowBoundEntries<>; + // ColdArchiveBucketEntry highBoundEntries<>; + // + // // Vector of vectors, where proofLevels[level] + // // contains all HashNodes that correspond with that level + // ProofLevel proofLevels<>; + // }; + // + // =========================================================================== + xdr.struct("ExistenceProofBody", [["keysToProve", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["lowBoundEntries", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["highBoundEntries", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["proofLevels", xdr.varArray(xdr.lookup("ProofLevel"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union switch (ArchivalProofType t) + // { + // case EXISTENCE: + // NonexistenceProofBody nonexistenceProof; + // case NONEXISTENCE: + // ExistenceProofBody existenceProof; + // } + // + // =========================================================================== + xdr.union("ArchivalProofBody", { + switchOn: xdr.lookup("ArchivalProofType"), + switchName: "t", + switches: [["existence", "nonexistenceProof"], ["nonexistence", "existenceProof"]], + arms: { + nonexistenceProof: xdr.lookup("NonexistenceProofBody"), + existenceProof: xdr.lookup("ExistenceProofBody") + } + }); + + // === xdr source ============================================================ + // + // struct ArchivalProof + // { + // uint32 epoch; // AST Subtree for this proof + // + // union switch (ArchivalProofType t) + // { + // case EXISTENCE: + // NonexistenceProofBody nonexistenceProof; + // case NONEXISTENCE: + // ExistenceProofBody existenceProof; + // } body; + // }; + // + // =========================================================================== + xdr.struct("ArchivalProof", [["epoch", xdr.lookup("Uint32")], ["body", xdr.lookup("ArchivalProofBody")]]); + + // === xdr source ============================================================ + // + // struct SorobanResources + // { + // // The ledger footprint of the transaction. + // LedgerFootprint footprint; + // // The maximum number of instructions this transaction can use + // uint32 instructions; + // + // // The maximum number of bytes this transaction can read from ledger + // uint32 readBytes; + // // The maximum number of bytes this transaction can write to ledger + // uint32 writeBytes; + // }; + // + // =========================================================================== + xdr.struct("SorobanResources", [["footprint", xdr.lookup("LedgerFootprint")], ["instructions", xdr.lookup("Uint32")], ["readBytes", xdr.lookup("Uint32")], ["writeBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SorobanTransactionData + // { + // ExtensionPoint ext; + // SorobanResources resources; + // // Amount of the transaction `fee` allocated to the Soroban resource fees. + // // The fraction of `resourceFee` corresponding to `resources` specified + // // above is *not* refundable (i.e. fees for instructions, ledger I/O), as + // // well as fees for the transaction size. + // // The remaining part of the fee is refundable and the charged value is + // // based on the actual consumption of refundable resources (events, ledger + // // rent bumps). + // // The `inclusionFee` used for prioritization of the transaction is defined + // // as `tx.fee - resourceFee`. + // int64 resourceFee; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionData", [["ext", xdr.lookup("ExtensionPoint")], ["resources", xdr.lookup("SorobanResources")], ["resourceFee", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionV0Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionV0 + // { + // uint256 sourceAccountEd25519; + // uint32 fee; + // SequenceNumber seqNum; + // TimeBounds* timeBounds; + // Memo memo; + // Operation operations; + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionV0", [["sourceAccountEd25519", xdr.lookup("Uint256")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionV0Ext")]]); + + // === xdr source ============================================================ + // + // struct TransactionV0Envelope + // { + // TransactionV0 tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("TransactionV0Envelope", [["tx", xdr.lookup("TransactionV0")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionData sorobanData; + // } + // + // =========================================================================== + xdr.union("TransactionExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "sorobanData"]], + arms: { + sorobanData: xdr.lookup("SorobanTransactionData") + } + }); + + // === xdr source ============================================================ + // + // struct Transaction + // { + // // account used to run the transaction + // MuxedAccount sourceAccount; + // + // // the fee the sourceAccount will pay + // uint32 fee; + // + // // sequence number to consume in the account + // SequenceNumber seqNum; + // + // // validity conditions + // Preconditions cond; + // + // Memo memo; + // + // Operation operations; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionData sorobanData; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("Transaction", [["sourceAccount", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["cond", xdr.lookup("Preconditions")], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionExt")]]); + + // === xdr source ============================================================ + // + // struct TransactionV1Envelope + // { + // Transaction tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("TransactionV1Envelope", [["tx", xdr.lookup("Transaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // } + // + // =========================================================================== + xdr.union("FeeBumpTransactionInnerTx", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTx", "v1"]], + arms: { + v1: xdr.lookup("TransactionV1Envelope") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("FeeBumpTransactionExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct FeeBumpTransaction + // { + // MuxedAccount feeSource; + // int64 fee; + // union switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // } + // innerTx; + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("FeeBumpTransaction", [["feeSource", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Int64")], ["innerTx", xdr.lookup("FeeBumpTransactionInnerTx")], ["ext", xdr.lookup("FeeBumpTransactionExt")]]); + + // === xdr source ============================================================ + // + // struct FeeBumpTransactionEnvelope + // { + // FeeBumpTransaction tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("FeeBumpTransactionEnvelope", [["tx", xdr.lookup("FeeBumpTransaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union TransactionEnvelope switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX_V0: + // TransactionV0Envelope v0; + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransactionEnvelope feeBump; + // }; + // + // =========================================================================== + xdr.union("TransactionEnvelope", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTxV0", "v0"], ["envelopeTypeTx", "v1"], ["envelopeTypeTxFeeBump", "feeBump"]], + arms: { + v0: xdr.lookup("TransactionV0Envelope"), + v1: xdr.lookup("TransactionV1Envelope"), + feeBump: xdr.lookup("FeeBumpTransactionEnvelope") + } + }); + + // === xdr source ============================================================ + // + // union switch (EnvelopeType type) + // { + // // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // case ENVELOPE_TYPE_TX: + // Transaction tx; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransaction feeBump; + // } + // + // =========================================================================== + xdr.union("TransactionSignaturePayloadTaggedTransaction", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTx", "tx"], ["envelopeTypeTxFeeBump", "feeBump"]], + arms: { + tx: xdr.lookup("Transaction"), + feeBump: xdr.lookup("FeeBumpTransaction") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionSignaturePayload + // { + // Hash networkId; + // union switch (EnvelopeType type) + // { + // // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // case ENVELOPE_TYPE_TX: + // Transaction tx; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransaction feeBump; + // } + // taggedTransaction; + // }; + // + // =========================================================================== + xdr.struct("TransactionSignaturePayload", [["networkId", xdr.lookup("Hash")], ["taggedTransaction", xdr.lookup("TransactionSignaturePayloadTaggedTransaction")]]); + + // === xdr source ============================================================ + // + // enum ClaimAtomType + // { + // CLAIM_ATOM_TYPE_V0 = 0, + // CLAIM_ATOM_TYPE_ORDER_BOOK = 1, + // CLAIM_ATOM_TYPE_LIQUIDITY_POOL = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimAtomType", { + claimAtomTypeV0: 0, + claimAtomTypeOrderBook: 1, + claimAtomTypeLiquidityPool: 2 + }); + + // === xdr source ============================================================ + // + // struct ClaimOfferAtomV0 + // { + // // emitted to identify the offer + // uint256 sellerEd25519; // Account that owns the offer + // int64 offerID; + // + // // amount and asset taken from the owner + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the owner + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimOfferAtomV0", [["sellerEd25519", xdr.lookup("Uint256")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClaimOfferAtom + // { + // // emitted to identify the offer + // AccountID sellerID; // Account that owns the offer + // int64 offerID; + // + // // amount and asset taken from the owner + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the owner + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimOfferAtom", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClaimLiquidityAtom + // { + // PoolID liquidityPoolID; + // + // // amount and asset taken from the pool + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the pool + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimLiquidityAtom", [["liquidityPoolId", xdr.lookup("PoolId")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union ClaimAtom switch (ClaimAtomType type) + // { + // case CLAIM_ATOM_TYPE_V0: + // ClaimOfferAtomV0 v0; + // case CLAIM_ATOM_TYPE_ORDER_BOOK: + // ClaimOfferAtom orderBook; + // case CLAIM_ATOM_TYPE_LIQUIDITY_POOL: + // ClaimLiquidityAtom liquidityPool; + // }; + // + // =========================================================================== + xdr.union("ClaimAtom", { + switchOn: xdr.lookup("ClaimAtomType"), + switchName: "type", + switches: [["claimAtomTypeV0", "v0"], ["claimAtomTypeOrderBook", "orderBook"], ["claimAtomTypeLiquidityPool", "liquidityPool"]], + arms: { + v0: xdr.lookup("ClaimOfferAtomV0"), + orderBook: xdr.lookup("ClaimOfferAtom"), + liquidityPool: xdr.lookup("ClaimLiquidityAtom") + } + }); + + // === xdr source ============================================================ + // + // enum CreateAccountResultCode + // { + // // codes considered as "success" for the operation + // CREATE_ACCOUNT_SUCCESS = 0, // account was created + // + // // codes considered as "failure" for the operation + // CREATE_ACCOUNT_MALFORMED = -1, // invalid destination + // CREATE_ACCOUNT_UNDERFUNDED = -2, // not enough funds in source account + // CREATE_ACCOUNT_LOW_RESERVE = + // -3, // would create an account below the min reserve + // CREATE_ACCOUNT_ALREADY_EXIST = -4 // account already exists + // }; + // + // =========================================================================== + xdr["enum"]("CreateAccountResultCode", { + createAccountSuccess: 0, + createAccountMalformed: -1, + createAccountUnderfunded: -2, + createAccountLowReserve: -3, + createAccountAlreadyExist: -4 + }); + + // === xdr source ============================================================ + // + // union CreateAccountResult switch (CreateAccountResultCode code) + // { + // case CREATE_ACCOUNT_SUCCESS: + // void; + // case CREATE_ACCOUNT_MALFORMED: + // case CREATE_ACCOUNT_UNDERFUNDED: + // case CREATE_ACCOUNT_LOW_RESERVE: + // case CREATE_ACCOUNT_ALREADY_EXIST: + // void; + // }; + // + // =========================================================================== + xdr.union("CreateAccountResult", { + switchOn: xdr.lookup("CreateAccountResultCode"), + switchName: "code", + switches: [["createAccountSuccess", xdr["void"]()], ["createAccountMalformed", xdr["void"]()], ["createAccountUnderfunded", xdr["void"]()], ["createAccountLowReserve", xdr["void"]()], ["createAccountAlreadyExist", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum PaymentResultCode + // { + // // codes considered as "success" for the operation + // PAYMENT_SUCCESS = 0, // payment successfully completed + // + // // codes considered as "failure" for the operation + // PAYMENT_MALFORMED = -1, // bad input + // PAYMENT_UNDERFUNDED = -2, // not enough funds in source account + // PAYMENT_SRC_NO_TRUST = -3, // no trust line on source account + // PAYMENT_SRC_NOT_AUTHORIZED = -4, // source not authorized to transfer + // PAYMENT_NO_DESTINATION = -5, // destination account does not exist + // PAYMENT_NO_TRUST = -6, // destination missing a trust line for asset + // PAYMENT_NOT_AUTHORIZED = -7, // destination not authorized to hold asset + // PAYMENT_LINE_FULL = -8, // destination would go above their limit + // PAYMENT_NO_ISSUER = -9 // missing issuer on asset + // }; + // + // =========================================================================== + xdr["enum"]("PaymentResultCode", { + paymentSuccess: 0, + paymentMalformed: -1, + paymentUnderfunded: -2, + paymentSrcNoTrust: -3, + paymentSrcNotAuthorized: -4, + paymentNoDestination: -5, + paymentNoTrust: -6, + paymentNotAuthorized: -7, + paymentLineFull: -8, + paymentNoIssuer: -9 + }); + + // === xdr source ============================================================ + // + // union PaymentResult switch (PaymentResultCode code) + // { + // case PAYMENT_SUCCESS: + // void; + // case PAYMENT_MALFORMED: + // case PAYMENT_UNDERFUNDED: + // case PAYMENT_SRC_NO_TRUST: + // case PAYMENT_SRC_NOT_AUTHORIZED: + // case PAYMENT_NO_DESTINATION: + // case PAYMENT_NO_TRUST: + // case PAYMENT_NOT_AUTHORIZED: + // case PAYMENT_LINE_FULL: + // case PAYMENT_NO_ISSUER: + // void; + // }; + // + // =========================================================================== + xdr.union("PaymentResult", { + switchOn: xdr.lookup("PaymentResultCode"), + switchName: "code", + switches: [["paymentSuccess", xdr["void"]()], ["paymentMalformed", xdr["void"]()], ["paymentUnderfunded", xdr["void"]()], ["paymentSrcNoTrust", xdr["void"]()], ["paymentSrcNotAuthorized", xdr["void"]()], ["paymentNoDestination", xdr["void"]()], ["paymentNoTrust", xdr["void"]()], ["paymentNotAuthorized", xdr["void"]()], ["paymentLineFull", xdr["void"]()], ["paymentNoIssuer", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum PathPaymentStrictReceiveResultCode + // { + // // codes considered as "success" for the operation + // PATH_PAYMENT_STRICT_RECEIVE_SUCCESS = 0, // success + // + // // codes considered as "failure" for the operation + // PATH_PAYMENT_STRICT_RECEIVE_MALFORMED = -1, // bad input + // PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED = + // -2, // not enough funds in source account + // PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST = + // -3, // no trust line on source account + // PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED = + // -4, // source not authorized to transfer + // PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION = + // -5, // destination account does not exist + // PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST = + // -6, // dest missing a trust line for asset + // PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED = + // -7, // dest not authorized to hold asset + // PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL = + // -8, // dest would go above their limit + // PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER = -9, // missing issuer on one asset + // PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS = + // -10, // not enough offers to satisfy path + // PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF = + // -11, // would cross one of its own offers + // PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX = -12 // could not satisfy sendmax + // }; + // + // =========================================================================== + xdr["enum"]("PathPaymentStrictReceiveResultCode", { + pathPaymentStrictReceiveSuccess: 0, + pathPaymentStrictReceiveMalformed: -1, + pathPaymentStrictReceiveUnderfunded: -2, + pathPaymentStrictReceiveSrcNoTrust: -3, + pathPaymentStrictReceiveSrcNotAuthorized: -4, + pathPaymentStrictReceiveNoDestination: -5, + pathPaymentStrictReceiveNoTrust: -6, + pathPaymentStrictReceiveNotAuthorized: -7, + pathPaymentStrictReceiveLineFull: -8, + pathPaymentStrictReceiveNoIssuer: -9, + pathPaymentStrictReceiveTooFewOffers: -10, + pathPaymentStrictReceiveOfferCrossSelf: -11, + pathPaymentStrictReceiveOverSendmax: -12 + }); + + // === xdr source ============================================================ + // + // struct SimplePaymentResult + // { + // AccountID destination; + // Asset asset; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("SimplePaymentResult", [["destination", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } + // + // =========================================================================== + xdr.struct("PathPaymentStrictReceiveResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]); + + // === xdr source ============================================================ + // + // union PathPaymentStrictReceiveResult switch ( + // PathPaymentStrictReceiveResultCode code) + // { + // case PATH_PAYMENT_STRICT_RECEIVE_SUCCESS: + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } success; + // case PATH_PAYMENT_STRICT_RECEIVE_MALFORMED: + // case PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED: + // case PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST: + // case PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION: + // case PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST: + // case PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL: + // void; + // case PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER: + // Asset noIssuer; // the asset that caused the error + // case PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS: + // case PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF: + // case PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX: + // void; + // }; + // + // =========================================================================== + xdr.union("PathPaymentStrictReceiveResult", { + switchOn: xdr.lookup("PathPaymentStrictReceiveResultCode"), + switchName: "code", + switches: [["pathPaymentStrictReceiveSuccess", "success"], ["pathPaymentStrictReceiveMalformed", xdr["void"]()], ["pathPaymentStrictReceiveUnderfunded", xdr["void"]()], ["pathPaymentStrictReceiveSrcNoTrust", xdr["void"]()], ["pathPaymentStrictReceiveSrcNotAuthorized", xdr["void"]()], ["pathPaymentStrictReceiveNoDestination", xdr["void"]()], ["pathPaymentStrictReceiveNoTrust", xdr["void"]()], ["pathPaymentStrictReceiveNotAuthorized", xdr["void"]()], ["pathPaymentStrictReceiveLineFull", xdr["void"]()], ["pathPaymentStrictReceiveNoIssuer", "noIssuer"], ["pathPaymentStrictReceiveTooFewOffers", xdr["void"]()], ["pathPaymentStrictReceiveOfferCrossSelf", xdr["void"]()], ["pathPaymentStrictReceiveOverSendmax", xdr["void"]()]], + arms: { + success: xdr.lookup("PathPaymentStrictReceiveResultSuccess"), + noIssuer: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // enum PathPaymentStrictSendResultCode + // { + // // codes considered as "success" for the operation + // PATH_PAYMENT_STRICT_SEND_SUCCESS = 0, // success + // + // // codes considered as "failure" for the operation + // PATH_PAYMENT_STRICT_SEND_MALFORMED = -1, // bad input + // PATH_PAYMENT_STRICT_SEND_UNDERFUNDED = + // -2, // not enough funds in source account + // PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST = + // -3, // no trust line on source account + // PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED = + // -4, // source not authorized to transfer + // PATH_PAYMENT_STRICT_SEND_NO_DESTINATION = + // -5, // destination account does not exist + // PATH_PAYMENT_STRICT_SEND_NO_TRUST = + // -6, // dest missing a trust line for asset + // PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED = + // -7, // dest not authorized to hold asset + // PATH_PAYMENT_STRICT_SEND_LINE_FULL = -8, // dest would go above their limit + // PATH_PAYMENT_STRICT_SEND_NO_ISSUER = -9, // missing issuer on one asset + // PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS = + // -10, // not enough offers to satisfy path + // PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF = + // -11, // would cross one of its own offers + // PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN = -12 // could not satisfy destMin + // }; + // + // =========================================================================== + xdr["enum"]("PathPaymentStrictSendResultCode", { + pathPaymentStrictSendSuccess: 0, + pathPaymentStrictSendMalformed: -1, + pathPaymentStrictSendUnderfunded: -2, + pathPaymentStrictSendSrcNoTrust: -3, + pathPaymentStrictSendSrcNotAuthorized: -4, + pathPaymentStrictSendNoDestination: -5, + pathPaymentStrictSendNoTrust: -6, + pathPaymentStrictSendNotAuthorized: -7, + pathPaymentStrictSendLineFull: -8, + pathPaymentStrictSendNoIssuer: -9, + pathPaymentStrictSendTooFewOffers: -10, + pathPaymentStrictSendOfferCrossSelf: -11, + pathPaymentStrictSendUnderDestmin: -12 + }); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } + // + // =========================================================================== + xdr.struct("PathPaymentStrictSendResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]); + + // === xdr source ============================================================ + // + // union PathPaymentStrictSendResult switch (PathPaymentStrictSendResultCode code) + // { + // case PATH_PAYMENT_STRICT_SEND_SUCCESS: + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } success; + // case PATH_PAYMENT_STRICT_SEND_MALFORMED: + // case PATH_PAYMENT_STRICT_SEND_UNDERFUNDED: + // case PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST: + // case PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_SEND_NO_DESTINATION: + // case PATH_PAYMENT_STRICT_SEND_NO_TRUST: + // case PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_SEND_LINE_FULL: + // void; + // case PATH_PAYMENT_STRICT_SEND_NO_ISSUER: + // Asset noIssuer; // the asset that caused the error + // case PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS: + // case PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF: + // case PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN: + // void; + // }; + // + // =========================================================================== + xdr.union("PathPaymentStrictSendResult", { + switchOn: xdr.lookup("PathPaymentStrictSendResultCode"), + switchName: "code", + switches: [["pathPaymentStrictSendSuccess", "success"], ["pathPaymentStrictSendMalformed", xdr["void"]()], ["pathPaymentStrictSendUnderfunded", xdr["void"]()], ["pathPaymentStrictSendSrcNoTrust", xdr["void"]()], ["pathPaymentStrictSendSrcNotAuthorized", xdr["void"]()], ["pathPaymentStrictSendNoDestination", xdr["void"]()], ["pathPaymentStrictSendNoTrust", xdr["void"]()], ["pathPaymentStrictSendNotAuthorized", xdr["void"]()], ["pathPaymentStrictSendLineFull", xdr["void"]()], ["pathPaymentStrictSendNoIssuer", "noIssuer"], ["pathPaymentStrictSendTooFewOffers", xdr["void"]()], ["pathPaymentStrictSendOfferCrossSelf", xdr["void"]()], ["pathPaymentStrictSendUnderDestmin", xdr["void"]()]], + arms: { + success: xdr.lookup("PathPaymentStrictSendResultSuccess"), + noIssuer: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // enum ManageSellOfferResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_SELL_OFFER_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // MANAGE_SELL_OFFER_MALFORMED = -1, // generated offer would be invalid + // MANAGE_SELL_OFFER_SELL_NO_TRUST = + // -2, // no trust line for what we're selling + // MANAGE_SELL_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying + // MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell + // MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy + // MANAGE_SELL_OFFER_LINE_FULL = -6, // can't receive more of what it's buying + // MANAGE_SELL_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell + // MANAGE_SELL_OFFER_CROSS_SELF = + // -8, // would cross an offer from the same user + // MANAGE_SELL_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling + // MANAGE_SELL_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying + // + // // update errors + // MANAGE_SELL_OFFER_NOT_FOUND = + // -11, // offerID does not match an existing offer + // + // MANAGE_SELL_OFFER_LOW_RESERVE = + // -12 // not enough funds to create a new Offer + // }; + // + // =========================================================================== + xdr["enum"]("ManageSellOfferResultCode", { + manageSellOfferSuccess: 0, + manageSellOfferMalformed: -1, + manageSellOfferSellNoTrust: -2, + manageSellOfferBuyNoTrust: -3, + manageSellOfferSellNotAuthorized: -4, + manageSellOfferBuyNotAuthorized: -5, + manageSellOfferLineFull: -6, + manageSellOfferUnderfunded: -7, + manageSellOfferCrossSelf: -8, + manageSellOfferSellNoIssuer: -9, + manageSellOfferBuyNoIssuer: -10, + manageSellOfferNotFound: -11, + manageSellOfferLowReserve: -12 + }); + + // === xdr source ============================================================ + // + // enum ManageOfferEffect + // { + // MANAGE_OFFER_CREATED = 0, + // MANAGE_OFFER_UPDATED = 1, + // MANAGE_OFFER_DELETED = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ManageOfferEffect", { + manageOfferCreated: 0, + manageOfferUpdated: 1, + manageOfferDeleted: 2 + }); + + // === xdr source ============================================================ + // + // union switch (ManageOfferEffect effect) + // { + // case MANAGE_OFFER_CREATED: + // case MANAGE_OFFER_UPDATED: + // OfferEntry offer; + // case MANAGE_OFFER_DELETED: + // void; + // } + // + // =========================================================================== + xdr.union("ManageOfferSuccessResultOffer", { + switchOn: xdr.lookup("ManageOfferEffect"), + switchName: "effect", + switches: [["manageOfferCreated", "offer"], ["manageOfferUpdated", "offer"], ["manageOfferDeleted", xdr["void"]()]], + arms: { + offer: xdr.lookup("OfferEntry") + } + }); + + // === xdr source ============================================================ + // + // struct ManageOfferSuccessResult + // { + // // offers that got claimed while creating this offer + // ClaimAtom offersClaimed<>; + // + // union switch (ManageOfferEffect effect) + // { + // case MANAGE_OFFER_CREATED: + // case MANAGE_OFFER_UPDATED: + // OfferEntry offer; + // case MANAGE_OFFER_DELETED: + // void; + // } + // offer; + // }; + // + // =========================================================================== + xdr.struct("ManageOfferSuccessResult", [["offersClaimed", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["offer", xdr.lookup("ManageOfferSuccessResultOffer")]]); + + // === xdr source ============================================================ + // + // union ManageSellOfferResult switch (ManageSellOfferResultCode code) + // { + // case MANAGE_SELL_OFFER_SUCCESS: + // ManageOfferSuccessResult success; + // case MANAGE_SELL_OFFER_MALFORMED: + // case MANAGE_SELL_OFFER_SELL_NO_TRUST: + // case MANAGE_SELL_OFFER_BUY_NO_TRUST: + // case MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED: + // case MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED: + // case MANAGE_SELL_OFFER_LINE_FULL: + // case MANAGE_SELL_OFFER_UNDERFUNDED: + // case MANAGE_SELL_OFFER_CROSS_SELF: + // case MANAGE_SELL_OFFER_SELL_NO_ISSUER: + // case MANAGE_SELL_OFFER_BUY_NO_ISSUER: + // case MANAGE_SELL_OFFER_NOT_FOUND: + // case MANAGE_SELL_OFFER_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageSellOfferResult", { + switchOn: xdr.lookup("ManageSellOfferResultCode"), + switchName: "code", + switches: [["manageSellOfferSuccess", "success"], ["manageSellOfferMalformed", xdr["void"]()], ["manageSellOfferSellNoTrust", xdr["void"]()], ["manageSellOfferBuyNoTrust", xdr["void"]()], ["manageSellOfferSellNotAuthorized", xdr["void"]()], ["manageSellOfferBuyNotAuthorized", xdr["void"]()], ["manageSellOfferLineFull", xdr["void"]()], ["manageSellOfferUnderfunded", xdr["void"]()], ["manageSellOfferCrossSelf", xdr["void"]()], ["manageSellOfferSellNoIssuer", xdr["void"]()], ["manageSellOfferBuyNoIssuer", xdr["void"]()], ["manageSellOfferNotFound", xdr["void"]()], ["manageSellOfferLowReserve", xdr["void"]()]], + arms: { + success: xdr.lookup("ManageOfferSuccessResult") + } + }); + + // === xdr source ============================================================ + // + // enum ManageBuyOfferResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_BUY_OFFER_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // MANAGE_BUY_OFFER_MALFORMED = -1, // generated offer would be invalid + // MANAGE_BUY_OFFER_SELL_NO_TRUST = -2, // no trust line for what we're selling + // MANAGE_BUY_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying + // MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell + // MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy + // MANAGE_BUY_OFFER_LINE_FULL = -6, // can't receive more of what it's buying + // MANAGE_BUY_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell + // MANAGE_BUY_OFFER_CROSS_SELF = -8, // would cross an offer from the same user + // MANAGE_BUY_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling + // MANAGE_BUY_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying + // + // // update errors + // MANAGE_BUY_OFFER_NOT_FOUND = + // -11, // offerID does not match an existing offer + // + // MANAGE_BUY_OFFER_LOW_RESERVE = -12 // not enough funds to create a new Offer + // }; + // + // =========================================================================== + xdr["enum"]("ManageBuyOfferResultCode", { + manageBuyOfferSuccess: 0, + manageBuyOfferMalformed: -1, + manageBuyOfferSellNoTrust: -2, + manageBuyOfferBuyNoTrust: -3, + manageBuyOfferSellNotAuthorized: -4, + manageBuyOfferBuyNotAuthorized: -5, + manageBuyOfferLineFull: -6, + manageBuyOfferUnderfunded: -7, + manageBuyOfferCrossSelf: -8, + manageBuyOfferSellNoIssuer: -9, + manageBuyOfferBuyNoIssuer: -10, + manageBuyOfferNotFound: -11, + manageBuyOfferLowReserve: -12 + }); + + // === xdr source ============================================================ + // + // union ManageBuyOfferResult switch (ManageBuyOfferResultCode code) + // { + // case MANAGE_BUY_OFFER_SUCCESS: + // ManageOfferSuccessResult success; + // case MANAGE_BUY_OFFER_MALFORMED: + // case MANAGE_BUY_OFFER_SELL_NO_TRUST: + // case MANAGE_BUY_OFFER_BUY_NO_TRUST: + // case MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED: + // case MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED: + // case MANAGE_BUY_OFFER_LINE_FULL: + // case MANAGE_BUY_OFFER_UNDERFUNDED: + // case MANAGE_BUY_OFFER_CROSS_SELF: + // case MANAGE_BUY_OFFER_SELL_NO_ISSUER: + // case MANAGE_BUY_OFFER_BUY_NO_ISSUER: + // case MANAGE_BUY_OFFER_NOT_FOUND: + // case MANAGE_BUY_OFFER_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageBuyOfferResult", { + switchOn: xdr.lookup("ManageBuyOfferResultCode"), + switchName: "code", + switches: [["manageBuyOfferSuccess", "success"], ["manageBuyOfferMalformed", xdr["void"]()], ["manageBuyOfferSellNoTrust", xdr["void"]()], ["manageBuyOfferBuyNoTrust", xdr["void"]()], ["manageBuyOfferSellNotAuthorized", xdr["void"]()], ["manageBuyOfferBuyNotAuthorized", xdr["void"]()], ["manageBuyOfferLineFull", xdr["void"]()], ["manageBuyOfferUnderfunded", xdr["void"]()], ["manageBuyOfferCrossSelf", xdr["void"]()], ["manageBuyOfferSellNoIssuer", xdr["void"]()], ["manageBuyOfferBuyNoIssuer", xdr["void"]()], ["manageBuyOfferNotFound", xdr["void"]()], ["manageBuyOfferLowReserve", xdr["void"]()]], + arms: { + success: xdr.lookup("ManageOfferSuccessResult") + } + }); + + // === xdr source ============================================================ + // + // enum SetOptionsResultCode + // { + // // codes considered as "success" for the operation + // SET_OPTIONS_SUCCESS = 0, + // // codes considered as "failure" for the operation + // SET_OPTIONS_LOW_RESERVE = -1, // not enough funds to add a signer + // SET_OPTIONS_TOO_MANY_SIGNERS = -2, // max number of signers already reached + // SET_OPTIONS_BAD_FLAGS = -3, // invalid combination of clear/set flags + // SET_OPTIONS_INVALID_INFLATION = -4, // inflation account does not exist + // SET_OPTIONS_CANT_CHANGE = -5, // can no longer change this option + // SET_OPTIONS_UNKNOWN_FLAG = -6, // can't set an unknown flag + // SET_OPTIONS_THRESHOLD_OUT_OF_RANGE = -7, // bad value for weight/threshold + // SET_OPTIONS_BAD_SIGNER = -8, // signer cannot be masterkey + // SET_OPTIONS_INVALID_HOME_DOMAIN = -9, // malformed home domain + // SET_OPTIONS_AUTH_REVOCABLE_REQUIRED = + // -10 // auth revocable is required for clawback + // }; + // + // =========================================================================== + xdr["enum"]("SetOptionsResultCode", { + setOptionsSuccess: 0, + setOptionsLowReserve: -1, + setOptionsTooManySigners: -2, + setOptionsBadFlags: -3, + setOptionsInvalidInflation: -4, + setOptionsCantChange: -5, + setOptionsUnknownFlag: -6, + setOptionsThresholdOutOfRange: -7, + setOptionsBadSigner: -8, + setOptionsInvalidHomeDomain: -9, + setOptionsAuthRevocableRequired: -10 + }); + + // === xdr source ============================================================ + // + // union SetOptionsResult switch (SetOptionsResultCode code) + // { + // case SET_OPTIONS_SUCCESS: + // void; + // case SET_OPTIONS_LOW_RESERVE: + // case SET_OPTIONS_TOO_MANY_SIGNERS: + // case SET_OPTIONS_BAD_FLAGS: + // case SET_OPTIONS_INVALID_INFLATION: + // case SET_OPTIONS_CANT_CHANGE: + // case SET_OPTIONS_UNKNOWN_FLAG: + // case SET_OPTIONS_THRESHOLD_OUT_OF_RANGE: + // case SET_OPTIONS_BAD_SIGNER: + // case SET_OPTIONS_INVALID_HOME_DOMAIN: + // case SET_OPTIONS_AUTH_REVOCABLE_REQUIRED: + // void; + // }; + // + // =========================================================================== + xdr.union("SetOptionsResult", { + switchOn: xdr.lookup("SetOptionsResultCode"), + switchName: "code", + switches: [["setOptionsSuccess", xdr["void"]()], ["setOptionsLowReserve", xdr["void"]()], ["setOptionsTooManySigners", xdr["void"]()], ["setOptionsBadFlags", xdr["void"]()], ["setOptionsInvalidInflation", xdr["void"]()], ["setOptionsCantChange", xdr["void"]()], ["setOptionsUnknownFlag", xdr["void"]()], ["setOptionsThresholdOutOfRange", xdr["void"]()], ["setOptionsBadSigner", xdr["void"]()], ["setOptionsInvalidHomeDomain", xdr["void"]()], ["setOptionsAuthRevocableRequired", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ChangeTrustResultCode + // { + // // codes considered as "success" for the operation + // CHANGE_TRUST_SUCCESS = 0, + // // codes considered as "failure" for the operation + // CHANGE_TRUST_MALFORMED = -1, // bad input + // CHANGE_TRUST_NO_ISSUER = -2, // could not find issuer + // CHANGE_TRUST_INVALID_LIMIT = -3, // cannot drop limit below balance + // // cannot create with a limit of 0 + // CHANGE_TRUST_LOW_RESERVE = + // -4, // not enough funds to create a new trust line, + // CHANGE_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed + // CHANGE_TRUST_TRUST_LINE_MISSING = -6, // Asset trustline is missing for pool + // CHANGE_TRUST_CANNOT_DELETE = + // -7, // Asset trustline is still referenced in a pool + // CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES = + // -8 // Asset trustline is deauthorized + // }; + // + // =========================================================================== + xdr["enum"]("ChangeTrustResultCode", { + changeTrustSuccess: 0, + changeTrustMalformed: -1, + changeTrustNoIssuer: -2, + changeTrustInvalidLimit: -3, + changeTrustLowReserve: -4, + changeTrustSelfNotAllowed: -5, + changeTrustTrustLineMissing: -6, + changeTrustCannotDelete: -7, + changeTrustNotAuthMaintainLiabilities: -8 + }); + + // === xdr source ============================================================ + // + // union ChangeTrustResult switch (ChangeTrustResultCode code) + // { + // case CHANGE_TRUST_SUCCESS: + // void; + // case CHANGE_TRUST_MALFORMED: + // case CHANGE_TRUST_NO_ISSUER: + // case CHANGE_TRUST_INVALID_LIMIT: + // case CHANGE_TRUST_LOW_RESERVE: + // case CHANGE_TRUST_SELF_NOT_ALLOWED: + // case CHANGE_TRUST_TRUST_LINE_MISSING: + // case CHANGE_TRUST_CANNOT_DELETE: + // case CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES: + // void; + // }; + // + // =========================================================================== + xdr.union("ChangeTrustResult", { + switchOn: xdr.lookup("ChangeTrustResultCode"), + switchName: "code", + switches: [["changeTrustSuccess", xdr["void"]()], ["changeTrustMalformed", xdr["void"]()], ["changeTrustNoIssuer", xdr["void"]()], ["changeTrustInvalidLimit", xdr["void"]()], ["changeTrustLowReserve", xdr["void"]()], ["changeTrustSelfNotAllowed", xdr["void"]()], ["changeTrustTrustLineMissing", xdr["void"]()], ["changeTrustCannotDelete", xdr["void"]()], ["changeTrustNotAuthMaintainLiabilities", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum AllowTrustResultCode + // { + // // codes considered as "success" for the operation + // ALLOW_TRUST_SUCCESS = 0, + // // codes considered as "failure" for the operation + // ALLOW_TRUST_MALFORMED = -1, // asset is not ASSET_TYPE_ALPHANUM + // ALLOW_TRUST_NO_TRUST_LINE = -2, // trustor does not have a trustline + // // source account does not require trust + // ALLOW_TRUST_TRUST_NOT_REQUIRED = -3, + // ALLOW_TRUST_CANT_REVOKE = -4, // source account can't revoke trust, + // ALLOW_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed + // ALLOW_TRUST_LOW_RESERVE = -6 // claimable balances can't be created + // // on revoke due to low reserves + // }; + // + // =========================================================================== + xdr["enum"]("AllowTrustResultCode", { + allowTrustSuccess: 0, + allowTrustMalformed: -1, + allowTrustNoTrustLine: -2, + allowTrustTrustNotRequired: -3, + allowTrustCantRevoke: -4, + allowTrustSelfNotAllowed: -5, + allowTrustLowReserve: -6 + }); + + // === xdr source ============================================================ + // + // union AllowTrustResult switch (AllowTrustResultCode code) + // { + // case ALLOW_TRUST_SUCCESS: + // void; + // case ALLOW_TRUST_MALFORMED: + // case ALLOW_TRUST_NO_TRUST_LINE: + // case ALLOW_TRUST_TRUST_NOT_REQUIRED: + // case ALLOW_TRUST_CANT_REVOKE: + // case ALLOW_TRUST_SELF_NOT_ALLOWED: + // case ALLOW_TRUST_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("AllowTrustResult", { + switchOn: xdr.lookup("AllowTrustResultCode"), + switchName: "code", + switches: [["allowTrustSuccess", xdr["void"]()], ["allowTrustMalformed", xdr["void"]()], ["allowTrustNoTrustLine", xdr["void"]()], ["allowTrustTrustNotRequired", xdr["void"]()], ["allowTrustCantRevoke", xdr["void"]()], ["allowTrustSelfNotAllowed", xdr["void"]()], ["allowTrustLowReserve", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum AccountMergeResultCode + // { + // // codes considered as "success" for the operation + // ACCOUNT_MERGE_SUCCESS = 0, + // // codes considered as "failure" for the operation + // ACCOUNT_MERGE_MALFORMED = -1, // can't merge onto itself + // ACCOUNT_MERGE_NO_ACCOUNT = -2, // destination does not exist + // ACCOUNT_MERGE_IMMUTABLE_SET = -3, // source account has AUTH_IMMUTABLE set + // ACCOUNT_MERGE_HAS_SUB_ENTRIES = -4, // account has trust lines/offers + // ACCOUNT_MERGE_SEQNUM_TOO_FAR = -5, // sequence number is over max allowed + // ACCOUNT_MERGE_DEST_FULL = -6, // can't add source balance to + // // destination balance + // ACCOUNT_MERGE_IS_SPONSOR = -7 // can't merge account that is a sponsor + // }; + // + // =========================================================================== + xdr["enum"]("AccountMergeResultCode", { + accountMergeSuccess: 0, + accountMergeMalformed: -1, + accountMergeNoAccount: -2, + accountMergeImmutableSet: -3, + accountMergeHasSubEntries: -4, + accountMergeSeqnumTooFar: -5, + accountMergeDestFull: -6, + accountMergeIsSponsor: -7 + }); + + // === xdr source ============================================================ + // + // union AccountMergeResult switch (AccountMergeResultCode code) + // { + // case ACCOUNT_MERGE_SUCCESS: + // int64 sourceAccountBalance; // how much got transferred from source account + // case ACCOUNT_MERGE_MALFORMED: + // case ACCOUNT_MERGE_NO_ACCOUNT: + // case ACCOUNT_MERGE_IMMUTABLE_SET: + // case ACCOUNT_MERGE_HAS_SUB_ENTRIES: + // case ACCOUNT_MERGE_SEQNUM_TOO_FAR: + // case ACCOUNT_MERGE_DEST_FULL: + // case ACCOUNT_MERGE_IS_SPONSOR: + // void; + // }; + // + // =========================================================================== + xdr.union("AccountMergeResult", { + switchOn: xdr.lookup("AccountMergeResultCode"), + switchName: "code", + switches: [["accountMergeSuccess", "sourceAccountBalance"], ["accountMergeMalformed", xdr["void"]()], ["accountMergeNoAccount", xdr["void"]()], ["accountMergeImmutableSet", xdr["void"]()], ["accountMergeHasSubEntries", xdr["void"]()], ["accountMergeSeqnumTooFar", xdr["void"]()], ["accountMergeDestFull", xdr["void"]()], ["accountMergeIsSponsor", xdr["void"]()]], + arms: { + sourceAccountBalance: xdr.lookup("Int64") + } + }); + + // === xdr source ============================================================ + // + // enum InflationResultCode + // { + // // codes considered as "success" for the operation + // INFLATION_SUCCESS = 0, + // // codes considered as "failure" for the operation + // INFLATION_NOT_TIME = -1 + // }; + // + // =========================================================================== + xdr["enum"]("InflationResultCode", { + inflationSuccess: 0, + inflationNotTime: -1 + }); + + // === xdr source ============================================================ + // + // struct InflationPayout // or use PaymentResultAtom to limit types? + // { + // AccountID destination; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("InflationPayout", [["destination", xdr.lookup("AccountId")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union InflationResult switch (InflationResultCode code) + // { + // case INFLATION_SUCCESS: + // InflationPayout payouts<>; + // case INFLATION_NOT_TIME: + // void; + // }; + // + // =========================================================================== + xdr.union("InflationResult", { + switchOn: xdr.lookup("InflationResultCode"), + switchName: "code", + switches: [["inflationSuccess", "payouts"], ["inflationNotTime", xdr["void"]()]], + arms: { + payouts: xdr.varArray(xdr.lookup("InflationPayout"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // enum ManageDataResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_DATA_SUCCESS = 0, + // // codes considered as "failure" for the operation + // MANAGE_DATA_NOT_SUPPORTED_YET = + // -1, // The network hasn't moved to this protocol change yet + // MANAGE_DATA_NAME_NOT_FOUND = + // -2, // Trying to remove a Data Entry that isn't there + // MANAGE_DATA_LOW_RESERVE = -3, // not enough funds to create a new Data Entry + // MANAGE_DATA_INVALID_NAME = -4 // Name not a valid string + // }; + // + // =========================================================================== + xdr["enum"]("ManageDataResultCode", { + manageDataSuccess: 0, + manageDataNotSupportedYet: -1, + manageDataNameNotFound: -2, + manageDataLowReserve: -3, + manageDataInvalidName: -4 + }); + + // === xdr source ============================================================ + // + // union ManageDataResult switch (ManageDataResultCode code) + // { + // case MANAGE_DATA_SUCCESS: + // void; + // case MANAGE_DATA_NOT_SUPPORTED_YET: + // case MANAGE_DATA_NAME_NOT_FOUND: + // case MANAGE_DATA_LOW_RESERVE: + // case MANAGE_DATA_INVALID_NAME: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageDataResult", { + switchOn: xdr.lookup("ManageDataResultCode"), + switchName: "code", + switches: [["manageDataSuccess", xdr["void"]()], ["manageDataNotSupportedYet", xdr["void"]()], ["manageDataNameNotFound", xdr["void"]()], ["manageDataLowReserve", xdr["void"]()], ["manageDataInvalidName", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum BumpSequenceResultCode + // { + // // codes considered as "success" for the operation + // BUMP_SEQUENCE_SUCCESS = 0, + // // codes considered as "failure" for the operation + // BUMP_SEQUENCE_BAD_SEQ = -1 // `bumpTo` is not within bounds + // }; + // + // =========================================================================== + xdr["enum"]("BumpSequenceResultCode", { + bumpSequenceSuccess: 0, + bumpSequenceBadSeq: -1 + }); + + // === xdr source ============================================================ + // + // union BumpSequenceResult switch (BumpSequenceResultCode code) + // { + // case BUMP_SEQUENCE_SUCCESS: + // void; + // case BUMP_SEQUENCE_BAD_SEQ: + // void; + // }; + // + // =========================================================================== + xdr.union("BumpSequenceResult", { + switchOn: xdr.lookup("BumpSequenceResultCode"), + switchName: "code", + switches: [["bumpSequenceSuccess", xdr["void"]()], ["bumpSequenceBadSeq", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum CreateClaimableBalanceResultCode + // { + // CREATE_CLAIMABLE_BALANCE_SUCCESS = 0, + // CREATE_CLAIMABLE_BALANCE_MALFORMED = -1, + // CREATE_CLAIMABLE_BALANCE_LOW_RESERVE = -2, + // CREATE_CLAIMABLE_BALANCE_NO_TRUST = -3, + // CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -4, + // CREATE_CLAIMABLE_BALANCE_UNDERFUNDED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("CreateClaimableBalanceResultCode", { + createClaimableBalanceSuccess: 0, + createClaimableBalanceMalformed: -1, + createClaimableBalanceLowReserve: -2, + createClaimableBalanceNoTrust: -3, + createClaimableBalanceNotAuthorized: -4, + createClaimableBalanceUnderfunded: -5 + }); + + // === xdr source ============================================================ + // + // union CreateClaimableBalanceResult switch ( + // CreateClaimableBalanceResultCode code) + // { + // case CREATE_CLAIMABLE_BALANCE_SUCCESS: + // ClaimableBalanceID balanceID; + // case CREATE_CLAIMABLE_BALANCE_MALFORMED: + // case CREATE_CLAIMABLE_BALANCE_LOW_RESERVE: + // case CREATE_CLAIMABLE_BALANCE_NO_TRUST: + // case CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED: + // case CREATE_CLAIMABLE_BALANCE_UNDERFUNDED: + // void; + // }; + // + // =========================================================================== + xdr.union("CreateClaimableBalanceResult", { + switchOn: xdr.lookup("CreateClaimableBalanceResultCode"), + switchName: "code", + switches: [["createClaimableBalanceSuccess", "balanceId"], ["createClaimableBalanceMalformed", xdr["void"]()], ["createClaimableBalanceLowReserve", xdr["void"]()], ["createClaimableBalanceNoTrust", xdr["void"]()], ["createClaimableBalanceNotAuthorized", xdr["void"]()], ["createClaimableBalanceUnderfunded", xdr["void"]()]], + arms: { + balanceId: xdr.lookup("ClaimableBalanceId") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimClaimableBalanceResultCode + // { + // CLAIM_CLAIMABLE_BALANCE_SUCCESS = 0, + // CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1, + // CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM = -2, + // CLAIM_CLAIMABLE_BALANCE_LINE_FULL = -3, + // CLAIM_CLAIMABLE_BALANCE_NO_TRUST = -4, + // CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimClaimableBalanceResultCode", { + claimClaimableBalanceSuccess: 0, + claimClaimableBalanceDoesNotExist: -1, + claimClaimableBalanceCannotClaim: -2, + claimClaimableBalanceLineFull: -3, + claimClaimableBalanceNoTrust: -4, + claimClaimableBalanceNotAuthorized: -5 + }); + + // === xdr source ============================================================ + // + // union ClaimClaimableBalanceResult switch (ClaimClaimableBalanceResultCode code) + // { + // case CLAIM_CLAIMABLE_BALANCE_SUCCESS: + // void; + // case CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST: + // case CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM: + // case CLAIM_CLAIMABLE_BALANCE_LINE_FULL: + // case CLAIM_CLAIMABLE_BALANCE_NO_TRUST: + // case CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClaimClaimableBalanceResult", { + switchOn: xdr.lookup("ClaimClaimableBalanceResultCode"), + switchName: "code", + switches: [["claimClaimableBalanceSuccess", xdr["void"]()], ["claimClaimableBalanceDoesNotExist", xdr["void"]()], ["claimClaimableBalanceCannotClaim", xdr["void"]()], ["claimClaimableBalanceLineFull", xdr["void"]()], ["claimClaimableBalanceNoTrust", xdr["void"]()], ["claimClaimableBalanceNotAuthorized", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum BeginSponsoringFutureReservesResultCode + // { + // // codes considered as "success" for the operation + // BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED = -1, + // BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED = -2, + // BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("BeginSponsoringFutureReservesResultCode", { + beginSponsoringFutureReservesSuccess: 0, + beginSponsoringFutureReservesMalformed: -1, + beginSponsoringFutureReservesAlreadySponsored: -2, + beginSponsoringFutureReservesRecursive: -3 + }); + + // === xdr source ============================================================ + // + // union BeginSponsoringFutureReservesResult switch ( + // BeginSponsoringFutureReservesResultCode code) + // { + // case BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS: + // void; + // case BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED: + // case BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED: + // case BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE: + // void; + // }; + // + // =========================================================================== + xdr.union("BeginSponsoringFutureReservesResult", { + switchOn: xdr.lookup("BeginSponsoringFutureReservesResultCode"), + switchName: "code", + switches: [["beginSponsoringFutureReservesSuccess", xdr["void"]()], ["beginSponsoringFutureReservesMalformed", xdr["void"]()], ["beginSponsoringFutureReservesAlreadySponsored", xdr["void"]()], ["beginSponsoringFutureReservesRecursive", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum EndSponsoringFutureReservesResultCode + // { + // // codes considered as "success" for the operation + // END_SPONSORING_FUTURE_RESERVES_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED = -1 + // }; + // + // =========================================================================== + xdr["enum"]("EndSponsoringFutureReservesResultCode", { + endSponsoringFutureReservesSuccess: 0, + endSponsoringFutureReservesNotSponsored: -1 + }); + + // === xdr source ============================================================ + // + // union EndSponsoringFutureReservesResult switch ( + // EndSponsoringFutureReservesResultCode code) + // { + // case END_SPONSORING_FUTURE_RESERVES_SUCCESS: + // void; + // case END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED: + // void; + // }; + // + // =========================================================================== + xdr.union("EndSponsoringFutureReservesResult", { + switchOn: xdr.lookup("EndSponsoringFutureReservesResultCode"), + switchName: "code", + switches: [["endSponsoringFutureReservesSuccess", xdr["void"]()], ["endSponsoringFutureReservesNotSponsored", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum RevokeSponsorshipResultCode + // { + // // codes considered as "success" for the operation + // REVOKE_SPONSORSHIP_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // REVOKE_SPONSORSHIP_DOES_NOT_EXIST = -1, + // REVOKE_SPONSORSHIP_NOT_SPONSOR = -2, + // REVOKE_SPONSORSHIP_LOW_RESERVE = -3, + // REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE = -4, + // REVOKE_SPONSORSHIP_MALFORMED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("RevokeSponsorshipResultCode", { + revokeSponsorshipSuccess: 0, + revokeSponsorshipDoesNotExist: -1, + revokeSponsorshipNotSponsor: -2, + revokeSponsorshipLowReserve: -3, + revokeSponsorshipOnlyTransferable: -4, + revokeSponsorshipMalformed: -5 + }); + + // === xdr source ============================================================ + // + // union RevokeSponsorshipResult switch (RevokeSponsorshipResultCode code) + // { + // case REVOKE_SPONSORSHIP_SUCCESS: + // void; + // case REVOKE_SPONSORSHIP_DOES_NOT_EXIST: + // case REVOKE_SPONSORSHIP_NOT_SPONSOR: + // case REVOKE_SPONSORSHIP_LOW_RESERVE: + // case REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE: + // case REVOKE_SPONSORSHIP_MALFORMED: + // void; + // }; + // + // =========================================================================== + xdr.union("RevokeSponsorshipResult", { + switchOn: xdr.lookup("RevokeSponsorshipResultCode"), + switchName: "code", + switches: [["revokeSponsorshipSuccess", xdr["void"]()], ["revokeSponsorshipDoesNotExist", xdr["void"]()], ["revokeSponsorshipNotSponsor", xdr["void"]()], ["revokeSponsorshipLowReserve", xdr["void"]()], ["revokeSponsorshipOnlyTransferable", xdr["void"]()], ["revokeSponsorshipMalformed", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ClawbackResultCode + // { + // // codes considered as "success" for the operation + // CLAWBACK_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // CLAWBACK_MALFORMED = -1, + // CLAWBACK_NOT_CLAWBACK_ENABLED = -2, + // CLAWBACK_NO_TRUST = -3, + // CLAWBACK_UNDERFUNDED = -4 + // }; + // + // =========================================================================== + xdr["enum"]("ClawbackResultCode", { + clawbackSuccess: 0, + clawbackMalformed: -1, + clawbackNotClawbackEnabled: -2, + clawbackNoTrust: -3, + clawbackUnderfunded: -4 + }); + + // === xdr source ============================================================ + // + // union ClawbackResult switch (ClawbackResultCode code) + // { + // case CLAWBACK_SUCCESS: + // void; + // case CLAWBACK_MALFORMED: + // case CLAWBACK_NOT_CLAWBACK_ENABLED: + // case CLAWBACK_NO_TRUST: + // case CLAWBACK_UNDERFUNDED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClawbackResult", { + switchOn: xdr.lookup("ClawbackResultCode"), + switchName: "code", + switches: [["clawbackSuccess", xdr["void"]()], ["clawbackMalformed", xdr["void"]()], ["clawbackNotClawbackEnabled", xdr["void"]()], ["clawbackNoTrust", xdr["void"]()], ["clawbackUnderfunded", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ClawbackClaimableBalanceResultCode + // { + // // codes considered as "success" for the operation + // CLAWBACK_CLAIMABLE_BALANCE_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1, + // CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER = -2, + // CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED = -3 + // }; + // + // =========================================================================== + xdr["enum"]("ClawbackClaimableBalanceResultCode", { + clawbackClaimableBalanceSuccess: 0, + clawbackClaimableBalanceDoesNotExist: -1, + clawbackClaimableBalanceNotIssuer: -2, + clawbackClaimableBalanceNotClawbackEnabled: -3 + }); + + // === xdr source ============================================================ + // + // union ClawbackClaimableBalanceResult switch ( + // ClawbackClaimableBalanceResultCode code) + // { + // case CLAWBACK_CLAIMABLE_BALANCE_SUCCESS: + // void; + // case CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST: + // case CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER: + // case CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClawbackClaimableBalanceResult", { + switchOn: xdr.lookup("ClawbackClaimableBalanceResultCode"), + switchName: "code", + switches: [["clawbackClaimableBalanceSuccess", xdr["void"]()], ["clawbackClaimableBalanceDoesNotExist", xdr["void"]()], ["clawbackClaimableBalanceNotIssuer", xdr["void"]()], ["clawbackClaimableBalanceNotClawbackEnabled", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum SetTrustLineFlagsResultCode + // { + // // codes considered as "success" for the operation + // SET_TRUST_LINE_FLAGS_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // SET_TRUST_LINE_FLAGS_MALFORMED = -1, + // SET_TRUST_LINE_FLAGS_NO_TRUST_LINE = -2, + // SET_TRUST_LINE_FLAGS_CANT_REVOKE = -3, + // SET_TRUST_LINE_FLAGS_INVALID_STATE = -4, + // SET_TRUST_LINE_FLAGS_LOW_RESERVE = -5 // claimable balances can't be created + // // on revoke due to low reserves + // }; + // + // =========================================================================== + xdr["enum"]("SetTrustLineFlagsResultCode", { + setTrustLineFlagsSuccess: 0, + setTrustLineFlagsMalformed: -1, + setTrustLineFlagsNoTrustLine: -2, + setTrustLineFlagsCantRevoke: -3, + setTrustLineFlagsInvalidState: -4, + setTrustLineFlagsLowReserve: -5 + }); + + // === xdr source ============================================================ + // + // union SetTrustLineFlagsResult switch (SetTrustLineFlagsResultCode code) + // { + // case SET_TRUST_LINE_FLAGS_SUCCESS: + // void; + // case SET_TRUST_LINE_FLAGS_MALFORMED: + // case SET_TRUST_LINE_FLAGS_NO_TRUST_LINE: + // case SET_TRUST_LINE_FLAGS_CANT_REVOKE: + // case SET_TRUST_LINE_FLAGS_INVALID_STATE: + // case SET_TRUST_LINE_FLAGS_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("SetTrustLineFlagsResult", { + switchOn: xdr.lookup("SetTrustLineFlagsResultCode"), + switchName: "code", + switches: [["setTrustLineFlagsSuccess", xdr["void"]()], ["setTrustLineFlagsMalformed", xdr["void"]()], ["setTrustLineFlagsNoTrustLine", xdr["void"]()], ["setTrustLineFlagsCantRevoke", xdr["void"]()], ["setTrustLineFlagsInvalidState", xdr["void"]()], ["setTrustLineFlagsLowReserve", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum LiquidityPoolDepositResultCode + // { + // // codes considered as "success" for the operation + // LIQUIDITY_POOL_DEPOSIT_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // LIQUIDITY_POOL_DEPOSIT_MALFORMED = -1, // bad input + // LIQUIDITY_POOL_DEPOSIT_NO_TRUST = -2, // no trust line for one of the + // // assets + // LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED = -3, // not authorized for one of the + // // assets + // LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED = -4, // not enough balance for one of + // // the assets + // LIQUIDITY_POOL_DEPOSIT_LINE_FULL = -5, // pool share trust line doesn't + // // have sufficient limit + // LIQUIDITY_POOL_DEPOSIT_BAD_PRICE = -6, // deposit price outside bounds + // LIQUIDITY_POOL_DEPOSIT_POOL_FULL = -7 // pool reserves are full + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolDepositResultCode", { + liquidityPoolDepositSuccess: 0, + liquidityPoolDepositMalformed: -1, + liquidityPoolDepositNoTrust: -2, + liquidityPoolDepositNotAuthorized: -3, + liquidityPoolDepositUnderfunded: -4, + liquidityPoolDepositLineFull: -5, + liquidityPoolDepositBadPrice: -6, + liquidityPoolDepositPoolFull: -7 + }); + + // === xdr source ============================================================ + // + // union LiquidityPoolDepositResult switch (LiquidityPoolDepositResultCode code) + // { + // case LIQUIDITY_POOL_DEPOSIT_SUCCESS: + // void; + // case LIQUIDITY_POOL_DEPOSIT_MALFORMED: + // case LIQUIDITY_POOL_DEPOSIT_NO_TRUST: + // case LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED: + // case LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED: + // case LIQUIDITY_POOL_DEPOSIT_LINE_FULL: + // case LIQUIDITY_POOL_DEPOSIT_BAD_PRICE: + // case LIQUIDITY_POOL_DEPOSIT_POOL_FULL: + // void; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolDepositResult", { + switchOn: xdr.lookup("LiquidityPoolDepositResultCode"), + switchName: "code", + switches: [["liquidityPoolDepositSuccess", xdr["void"]()], ["liquidityPoolDepositMalformed", xdr["void"]()], ["liquidityPoolDepositNoTrust", xdr["void"]()], ["liquidityPoolDepositNotAuthorized", xdr["void"]()], ["liquidityPoolDepositUnderfunded", xdr["void"]()], ["liquidityPoolDepositLineFull", xdr["void"]()], ["liquidityPoolDepositBadPrice", xdr["void"]()], ["liquidityPoolDepositPoolFull", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum LiquidityPoolWithdrawResultCode + // { + // // codes considered as "success" for the operation + // LIQUIDITY_POOL_WITHDRAW_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // LIQUIDITY_POOL_WITHDRAW_MALFORMED = -1, // bad input + // LIQUIDITY_POOL_WITHDRAW_NO_TRUST = -2, // no trust line for one of the + // // assets + // LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED = -3, // not enough balance of the + // // pool share + // LIQUIDITY_POOL_WITHDRAW_LINE_FULL = -4, // would go above limit for one + // // of the assets + // LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM = -5 // didn't withdraw enough + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolWithdrawResultCode", { + liquidityPoolWithdrawSuccess: 0, + liquidityPoolWithdrawMalformed: -1, + liquidityPoolWithdrawNoTrust: -2, + liquidityPoolWithdrawUnderfunded: -3, + liquidityPoolWithdrawLineFull: -4, + liquidityPoolWithdrawUnderMinimum: -5 + }); + + // === xdr source ============================================================ + // + // union LiquidityPoolWithdrawResult switch (LiquidityPoolWithdrawResultCode code) + // { + // case LIQUIDITY_POOL_WITHDRAW_SUCCESS: + // void; + // case LIQUIDITY_POOL_WITHDRAW_MALFORMED: + // case LIQUIDITY_POOL_WITHDRAW_NO_TRUST: + // case LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED: + // case LIQUIDITY_POOL_WITHDRAW_LINE_FULL: + // case LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM: + // void; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolWithdrawResult", { + switchOn: xdr.lookup("LiquidityPoolWithdrawResultCode"), + switchName: "code", + switches: [["liquidityPoolWithdrawSuccess", xdr["void"]()], ["liquidityPoolWithdrawMalformed", xdr["void"]()], ["liquidityPoolWithdrawNoTrust", xdr["void"]()], ["liquidityPoolWithdrawUnderfunded", xdr["void"]()], ["liquidityPoolWithdrawLineFull", xdr["void"]()], ["liquidityPoolWithdrawUnderMinimum", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum InvokeHostFunctionResultCode + // { + // // codes considered as "success" for the operation + // INVOKE_HOST_FUNCTION_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // INVOKE_HOST_FUNCTION_MALFORMED = -1, + // INVOKE_HOST_FUNCTION_TRAPPED = -2, + // INVOKE_HOST_FUNCTION_RESOURCE_LIMIT_EXCEEDED = -3, + // INVOKE_HOST_FUNCTION_ENTRY_ARCHIVED = -4, + // INVOKE_HOST_FUNCTION_INSUFFICIENT_REFUNDABLE_FEE = -5 + // }; + // + // =========================================================================== + xdr["enum"]("InvokeHostFunctionResultCode", { + invokeHostFunctionSuccess: 0, + invokeHostFunctionMalformed: -1, + invokeHostFunctionTrapped: -2, + invokeHostFunctionResourceLimitExceeded: -3, + invokeHostFunctionEntryArchived: -4, + invokeHostFunctionInsufficientRefundableFee: -5 + }); + + // === xdr source ============================================================ + // + // union InvokeHostFunctionResult switch (InvokeHostFunctionResultCode code) + // { + // case INVOKE_HOST_FUNCTION_SUCCESS: + // Hash success; // sha256(InvokeHostFunctionSuccessPreImage) + // case INVOKE_HOST_FUNCTION_MALFORMED: + // case INVOKE_HOST_FUNCTION_TRAPPED: + // case INVOKE_HOST_FUNCTION_RESOURCE_LIMIT_EXCEEDED: + // case INVOKE_HOST_FUNCTION_ENTRY_ARCHIVED: + // case INVOKE_HOST_FUNCTION_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("InvokeHostFunctionResult", { + switchOn: xdr.lookup("InvokeHostFunctionResultCode"), + switchName: "code", + switches: [["invokeHostFunctionSuccess", "success"], ["invokeHostFunctionMalformed", xdr["void"]()], ["invokeHostFunctionTrapped", xdr["void"]()], ["invokeHostFunctionResourceLimitExceeded", xdr["void"]()], ["invokeHostFunctionEntryArchived", xdr["void"]()], ["invokeHostFunctionInsufficientRefundableFee", xdr["void"]()]], + arms: { + success: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum ExtendFootprintTTLResultCode + // { + // // codes considered as "success" for the operation + // EXTEND_FOOTPRINT_TTL_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // EXTEND_FOOTPRINT_TTL_MALFORMED = -1, + // EXTEND_FOOTPRINT_TTL_RESOURCE_LIMIT_EXCEEDED = -2, + // EXTEND_FOOTPRINT_TTL_INSUFFICIENT_REFUNDABLE_FEE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("ExtendFootprintTtlResultCode", { + extendFootprintTtlSuccess: 0, + extendFootprintTtlMalformed: -1, + extendFootprintTtlResourceLimitExceeded: -2, + extendFootprintTtlInsufficientRefundableFee: -3 + }); + + // === xdr source ============================================================ + // + // union ExtendFootprintTTLResult switch (ExtendFootprintTTLResultCode code) + // { + // case EXTEND_FOOTPRINT_TTL_SUCCESS: + // void; + // case EXTEND_FOOTPRINT_TTL_MALFORMED: + // case EXTEND_FOOTPRINT_TTL_RESOURCE_LIMIT_EXCEEDED: + // case EXTEND_FOOTPRINT_TTL_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("ExtendFootprintTtlResult", { + switchOn: xdr.lookup("ExtendFootprintTtlResultCode"), + switchName: "code", + switches: [["extendFootprintTtlSuccess", xdr["void"]()], ["extendFootprintTtlMalformed", xdr["void"]()], ["extendFootprintTtlResourceLimitExceeded", xdr["void"]()], ["extendFootprintTtlInsufficientRefundableFee", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum RestoreFootprintResultCode + // { + // // codes considered as "success" for the operation + // RESTORE_FOOTPRINT_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // RESTORE_FOOTPRINT_MALFORMED = -1, + // RESTORE_FOOTPRINT_RESOURCE_LIMIT_EXCEEDED = -2, + // RESTORE_FOOTPRINT_INSUFFICIENT_REFUNDABLE_FEE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("RestoreFootprintResultCode", { + restoreFootprintSuccess: 0, + restoreFootprintMalformed: -1, + restoreFootprintResourceLimitExceeded: -2, + restoreFootprintInsufficientRefundableFee: -3 + }); + + // === xdr source ============================================================ + // + // union RestoreFootprintResult switch (RestoreFootprintResultCode code) + // { + // case RESTORE_FOOTPRINT_SUCCESS: + // void; + // case RESTORE_FOOTPRINT_MALFORMED: + // case RESTORE_FOOTPRINT_RESOURCE_LIMIT_EXCEEDED: + // case RESTORE_FOOTPRINT_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("RestoreFootprintResult", { + switchOn: xdr.lookup("RestoreFootprintResultCode"), + switchName: "code", + switches: [["restoreFootprintSuccess", xdr["void"]()], ["restoreFootprintMalformed", xdr["void"]()], ["restoreFootprintResourceLimitExceeded", xdr["void"]()], ["restoreFootprintInsufficientRefundableFee", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum OperationResultCode + // { + // opINNER = 0, // inner object result is valid + // + // opBAD_AUTH = -1, // too few valid signatures / wrong network + // opNO_ACCOUNT = -2, // source account was not found + // opNOT_SUPPORTED = -3, // operation not supported at this time + // opTOO_MANY_SUBENTRIES = -4, // max number of subentries already reached + // opEXCEEDED_WORK_LIMIT = -5, // operation did too much work + // opTOO_MANY_SPONSORING = -6 // account is sponsoring too many entries + // }; + // + // =========================================================================== + xdr["enum"]("OperationResultCode", { + opInner: 0, + opBadAuth: -1, + opNoAccount: -2, + opNotSupported: -3, + opTooManySubentries: -4, + opExceededWorkLimit: -5, + opTooManySponsoring: -6 + }); + + // === xdr source ============================================================ + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountResult createAccountResult; + // case PAYMENT: + // PaymentResult paymentResult; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult; + // case MANAGE_SELL_OFFER: + // ManageSellOfferResult manageSellOfferResult; + // case CREATE_PASSIVE_SELL_OFFER: + // ManageSellOfferResult createPassiveSellOfferResult; + // case SET_OPTIONS: + // SetOptionsResult setOptionsResult; + // case CHANGE_TRUST: + // ChangeTrustResult changeTrustResult; + // case ALLOW_TRUST: + // AllowTrustResult allowTrustResult; + // case ACCOUNT_MERGE: + // AccountMergeResult accountMergeResult; + // case INFLATION: + // InflationResult inflationResult; + // case MANAGE_DATA: + // ManageDataResult manageDataResult; + // case BUMP_SEQUENCE: + // BumpSequenceResult bumpSeqResult; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferResult manageBuyOfferResult; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendResult pathPaymentStrictSendResult; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceResult createClaimableBalanceResult; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceResult claimClaimableBalanceResult; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult; + // case END_SPONSORING_FUTURE_RESERVES: + // EndSponsoringFutureReservesResult endSponsoringFutureReservesResult; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipResult revokeSponsorshipResult; + // case CLAWBACK: + // ClawbackResult clawbackResult; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceResult clawbackClaimableBalanceResult; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsResult setTrustLineFlagsResult; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositResult liquidityPoolDepositResult; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawResult liquidityPoolWithdrawResult; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionResult invokeHostFunctionResult; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLResult extendFootprintTTLResult; + // case RESTORE_FOOTPRINT: + // RestoreFootprintResult restoreFootprintResult; + // } + // + // =========================================================================== + xdr.union("OperationResultTr", { + switchOn: xdr.lookup("OperationType"), + switchName: "type", + switches: [["createAccount", "createAccountResult"], ["payment", "paymentResult"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveResult"], ["manageSellOffer", "manageSellOfferResult"], ["createPassiveSellOffer", "createPassiveSellOfferResult"], ["setOptions", "setOptionsResult"], ["changeTrust", "changeTrustResult"], ["allowTrust", "allowTrustResult"], ["accountMerge", "accountMergeResult"], ["inflation", "inflationResult"], ["manageData", "manageDataResult"], ["bumpSequence", "bumpSeqResult"], ["manageBuyOffer", "manageBuyOfferResult"], ["pathPaymentStrictSend", "pathPaymentStrictSendResult"], ["createClaimableBalance", "createClaimableBalanceResult"], ["claimClaimableBalance", "claimClaimableBalanceResult"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesResult"], ["endSponsoringFutureReserves", "endSponsoringFutureReservesResult"], ["revokeSponsorship", "revokeSponsorshipResult"], ["clawback", "clawbackResult"], ["clawbackClaimableBalance", "clawbackClaimableBalanceResult"], ["setTrustLineFlags", "setTrustLineFlagsResult"], ["liquidityPoolDeposit", "liquidityPoolDepositResult"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawResult"], ["invokeHostFunction", "invokeHostFunctionResult"], ["extendFootprintTtl", "extendFootprintTtlResult"], ["restoreFootprint", "restoreFootprintResult"]], + arms: { + createAccountResult: xdr.lookup("CreateAccountResult"), + paymentResult: xdr.lookup("PaymentResult"), + pathPaymentStrictReceiveResult: xdr.lookup("PathPaymentStrictReceiveResult"), + manageSellOfferResult: xdr.lookup("ManageSellOfferResult"), + createPassiveSellOfferResult: xdr.lookup("ManageSellOfferResult"), + setOptionsResult: xdr.lookup("SetOptionsResult"), + changeTrustResult: xdr.lookup("ChangeTrustResult"), + allowTrustResult: xdr.lookup("AllowTrustResult"), + accountMergeResult: xdr.lookup("AccountMergeResult"), + inflationResult: xdr.lookup("InflationResult"), + manageDataResult: xdr.lookup("ManageDataResult"), + bumpSeqResult: xdr.lookup("BumpSequenceResult"), + manageBuyOfferResult: xdr.lookup("ManageBuyOfferResult"), + pathPaymentStrictSendResult: xdr.lookup("PathPaymentStrictSendResult"), + createClaimableBalanceResult: xdr.lookup("CreateClaimableBalanceResult"), + claimClaimableBalanceResult: xdr.lookup("ClaimClaimableBalanceResult"), + beginSponsoringFutureReservesResult: xdr.lookup("BeginSponsoringFutureReservesResult"), + endSponsoringFutureReservesResult: xdr.lookup("EndSponsoringFutureReservesResult"), + revokeSponsorshipResult: xdr.lookup("RevokeSponsorshipResult"), + clawbackResult: xdr.lookup("ClawbackResult"), + clawbackClaimableBalanceResult: xdr.lookup("ClawbackClaimableBalanceResult"), + setTrustLineFlagsResult: xdr.lookup("SetTrustLineFlagsResult"), + liquidityPoolDepositResult: xdr.lookup("LiquidityPoolDepositResult"), + liquidityPoolWithdrawResult: xdr.lookup("LiquidityPoolWithdrawResult"), + invokeHostFunctionResult: xdr.lookup("InvokeHostFunctionResult"), + extendFootprintTtlResult: xdr.lookup("ExtendFootprintTtlResult"), + restoreFootprintResult: xdr.lookup("RestoreFootprintResult") + } + }); + + // === xdr source ============================================================ + // + // union OperationResult switch (OperationResultCode code) + // { + // case opINNER: + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountResult createAccountResult; + // case PAYMENT: + // PaymentResult paymentResult; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult; + // case MANAGE_SELL_OFFER: + // ManageSellOfferResult manageSellOfferResult; + // case CREATE_PASSIVE_SELL_OFFER: + // ManageSellOfferResult createPassiveSellOfferResult; + // case SET_OPTIONS: + // SetOptionsResult setOptionsResult; + // case CHANGE_TRUST: + // ChangeTrustResult changeTrustResult; + // case ALLOW_TRUST: + // AllowTrustResult allowTrustResult; + // case ACCOUNT_MERGE: + // AccountMergeResult accountMergeResult; + // case INFLATION: + // InflationResult inflationResult; + // case MANAGE_DATA: + // ManageDataResult manageDataResult; + // case BUMP_SEQUENCE: + // BumpSequenceResult bumpSeqResult; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferResult manageBuyOfferResult; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendResult pathPaymentStrictSendResult; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceResult createClaimableBalanceResult; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceResult claimClaimableBalanceResult; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult; + // case END_SPONSORING_FUTURE_RESERVES: + // EndSponsoringFutureReservesResult endSponsoringFutureReservesResult; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipResult revokeSponsorshipResult; + // case CLAWBACK: + // ClawbackResult clawbackResult; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceResult clawbackClaimableBalanceResult; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsResult setTrustLineFlagsResult; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositResult liquidityPoolDepositResult; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawResult liquidityPoolWithdrawResult; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionResult invokeHostFunctionResult; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLResult extendFootprintTTLResult; + // case RESTORE_FOOTPRINT: + // RestoreFootprintResult restoreFootprintResult; + // } + // tr; + // case opBAD_AUTH: + // case opNO_ACCOUNT: + // case opNOT_SUPPORTED: + // case opTOO_MANY_SUBENTRIES: + // case opEXCEEDED_WORK_LIMIT: + // case opTOO_MANY_SPONSORING: + // void; + // }; + // + // =========================================================================== + xdr.union("OperationResult", { + switchOn: xdr.lookup("OperationResultCode"), + switchName: "code", + switches: [["opInner", "tr"], ["opBadAuth", xdr["void"]()], ["opNoAccount", xdr["void"]()], ["opNotSupported", xdr["void"]()], ["opTooManySubentries", xdr["void"]()], ["opExceededWorkLimit", xdr["void"]()], ["opTooManySponsoring", xdr["void"]()]], + arms: { + tr: xdr.lookup("OperationResultTr") + } + }); + + // === xdr source ============================================================ + // + // enum TransactionResultCode + // { + // txFEE_BUMP_INNER_SUCCESS = 1, // fee bump inner transaction succeeded + // txSUCCESS = 0, // all operations succeeded + // + // txFAILED = -1, // one of the operations failed (none were applied) + // + // txTOO_EARLY = -2, // ledger closeTime before minTime + // txTOO_LATE = -3, // ledger closeTime after maxTime + // txMISSING_OPERATION = -4, // no operation was specified + // txBAD_SEQ = -5, // sequence number does not match source account + // + // txBAD_AUTH = -6, // too few valid signatures / wrong network + // txINSUFFICIENT_BALANCE = -7, // fee would bring account below reserve + // txNO_ACCOUNT = -8, // source account not found + // txINSUFFICIENT_FEE = -9, // fee is too small + // txBAD_AUTH_EXTRA = -10, // unused signatures attached to transaction + // txINTERNAL_ERROR = -11, // an unknown error occurred + // + // txNOT_SUPPORTED = -12, // transaction type not supported + // txFEE_BUMP_INNER_FAILED = -13, // fee bump inner transaction failed + // txBAD_SPONSORSHIP = -14, // sponsorship not confirmed + // txBAD_MIN_SEQ_AGE_OR_GAP = -15, // minSeqAge or minSeqLedgerGap conditions not met + // txMALFORMED = -16, // precondition is invalid + // txSOROBAN_INVALID = -17 // soroban-specific preconditions were not met + // }; + // + // =========================================================================== + xdr["enum"]("TransactionResultCode", { + txFeeBumpInnerSuccess: 1, + txSuccess: 0, + txFailed: -1, + txTooEarly: -2, + txTooLate: -3, + txMissingOperation: -4, + txBadSeq: -5, + txBadAuth: -6, + txInsufficientBalance: -7, + txNoAccount: -8, + txInsufficientFee: -9, + txBadAuthExtra: -10, + txInternalError: -11, + txNotSupported: -12, + txFeeBumpInnerFailed: -13, + txBadSponsorship: -14, + txBadMinSeqAgeOrGap: -15, + txMalformed: -16, + txSorobanInvalid: -17 + }); + + // === xdr source ============================================================ + // + // union switch (TransactionResultCode code) + // { + // // txFEE_BUMP_INNER_SUCCESS is not included + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // txFEE_BUMP_INNER_FAILED is not included + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // + // =========================================================================== + xdr.union("InnerTransactionResultResult", { + switchOn: xdr.lookup("TransactionResultCode"), + switchName: "code", + switches: [["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr["void"]()], ["txTooLate", xdr["void"]()], ["txMissingOperation", xdr["void"]()], ["txBadSeq", xdr["void"]()], ["txBadAuth", xdr["void"]()], ["txInsufficientBalance", xdr["void"]()], ["txNoAccount", xdr["void"]()], ["txInsufficientFee", xdr["void"]()], ["txBadAuthExtra", xdr["void"]()], ["txInternalError", xdr["void"]()], ["txNotSupported", xdr["void"]()], ["txBadSponsorship", xdr["void"]()], ["txBadMinSeqAgeOrGap", xdr["void"]()], ["txMalformed", xdr["void"]()], ["txSorobanInvalid", xdr["void"]()]], + arms: { + results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("InnerTransactionResultExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct InnerTransactionResult + // { + // // Always 0. Here for binary compatibility. + // int64 feeCharged; + // + // union switch (TransactionResultCode code) + // { + // // txFEE_BUMP_INNER_SUCCESS is not included + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // txFEE_BUMP_INNER_FAILED is not included + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // result; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("InnerTransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("InnerTransactionResultResult")], ["ext", xdr.lookup("InnerTransactionResultExt")]]); + + // === xdr source ============================================================ + // + // struct InnerTransactionResultPair + // { + // Hash transactionHash; // hash of the inner transaction + // InnerTransactionResult result; // result for the inner transaction + // }; + // + // =========================================================================== + xdr.struct("InnerTransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("InnerTransactionResult")]]); + + // === xdr source ============================================================ + // + // union switch (TransactionResultCode code) + // { + // case txFEE_BUMP_INNER_SUCCESS: + // case txFEE_BUMP_INNER_FAILED: + // InnerTransactionResultPair innerResultPair; + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // case txFEE_BUMP_INNER_FAILED: handled above + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionResultResult", { + switchOn: xdr.lookup("TransactionResultCode"), + switchName: "code", + switches: [["txFeeBumpInnerSuccess", "innerResultPair"], ["txFeeBumpInnerFailed", "innerResultPair"], ["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr["void"]()], ["txTooLate", xdr["void"]()], ["txMissingOperation", xdr["void"]()], ["txBadSeq", xdr["void"]()], ["txBadAuth", xdr["void"]()], ["txInsufficientBalance", xdr["void"]()], ["txNoAccount", xdr["void"]()], ["txInsufficientFee", xdr["void"]()], ["txBadAuthExtra", xdr["void"]()], ["txInternalError", xdr["void"]()], ["txNotSupported", xdr["void"]()], ["txBadSponsorship", xdr["void"]()], ["txBadMinSeqAgeOrGap", xdr["void"]()], ["txMalformed", xdr["void"]()], ["txSorobanInvalid", xdr["void"]()]], + arms: { + innerResultPair: xdr.lookup("InnerTransactionResultPair"), + results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionResultExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionResult + // { + // int64 feeCharged; // actual fee charged for the transaction + // + // union switch (TransactionResultCode code) + // { + // case txFEE_BUMP_INNER_SUCCESS: + // case txFEE_BUMP_INNER_FAILED: + // InnerTransactionResultPair innerResultPair; + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // case txFEE_BUMP_INNER_FAILED: handled above + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // result; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("TransactionResultResult")], ["ext", xdr.lookup("TransactionResultExt")]]); + + // === xdr source ============================================================ + // + // typedef opaque Hash[32]; + // + // =========================================================================== + xdr.typedef("Hash", xdr.opaque(32)); + + // === xdr source ============================================================ + // + // typedef opaque uint256[32]; + // + // =========================================================================== + xdr.typedef("Uint256", xdr.opaque(32)); + + // === xdr source ============================================================ + // + // typedef unsigned int uint32; + // + // =========================================================================== + xdr.typedef("Uint32", xdr.uint()); + + // === xdr source ============================================================ + // + // typedef int int32; + // + // =========================================================================== + xdr.typedef("Int32", xdr["int"]()); + + // === xdr source ============================================================ + // + // typedef unsigned hyper uint64; + // + // =========================================================================== + xdr.typedef("Uint64", xdr.uhyper()); + + // === xdr source ============================================================ + // + // typedef hyper int64; + // + // =========================================================================== + xdr.typedef("Int64", xdr.hyper()); + + // === xdr source ============================================================ + // + // typedef uint64 TimePoint; + // + // =========================================================================== + xdr.typedef("TimePoint", xdr.lookup("Uint64")); + + // === xdr source ============================================================ + // + // typedef uint64 Duration; + // + // =========================================================================== + xdr.typedef("Duration", xdr.lookup("Uint64")); + + // === xdr source ============================================================ + // + // union ExtensionPoint switch (int v) + // { + // case 0: + // void; + // }; + // + // =========================================================================== + xdr.union("ExtensionPoint", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum CryptoKeyType + // { + // KEY_TYPE_ED25519 = 0, + // KEY_TYPE_PRE_AUTH_TX = 1, + // KEY_TYPE_HASH_X = 2, + // KEY_TYPE_ED25519_SIGNED_PAYLOAD = 3, + // // MUXED enum values for supported type are derived from the enum values + // // above by ORing them with 0x100 + // KEY_TYPE_MUXED_ED25519 = 0x100 + // }; + // + // =========================================================================== + xdr["enum"]("CryptoKeyType", { + keyTypeEd25519: 0, + keyTypePreAuthTx: 1, + keyTypeHashX: 2, + keyTypeEd25519SignedPayload: 3, + keyTypeMuxedEd25519: 256 + }); + + // === xdr source ============================================================ + // + // enum PublicKeyType + // { + // PUBLIC_KEY_TYPE_ED25519 = KEY_TYPE_ED25519 + // }; + // + // =========================================================================== + xdr["enum"]("PublicKeyType", { + publicKeyTypeEd25519: 0 + }); + + // === xdr source ============================================================ + // + // enum SignerKeyType + // { + // SIGNER_KEY_TYPE_ED25519 = KEY_TYPE_ED25519, + // SIGNER_KEY_TYPE_PRE_AUTH_TX = KEY_TYPE_PRE_AUTH_TX, + // SIGNER_KEY_TYPE_HASH_X = KEY_TYPE_HASH_X, + // SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD = KEY_TYPE_ED25519_SIGNED_PAYLOAD + // }; + // + // =========================================================================== + xdr["enum"]("SignerKeyType", { + signerKeyTypeEd25519: 0, + signerKeyTypePreAuthTx: 1, + signerKeyTypeHashX: 2, + signerKeyTypeEd25519SignedPayload: 3 + }); + + // === xdr source ============================================================ + // + // union PublicKey switch (PublicKeyType type) + // { + // case PUBLIC_KEY_TYPE_ED25519: + // uint256 ed25519; + // }; + // + // =========================================================================== + xdr.union("PublicKey", { + switchOn: xdr.lookup("PublicKeyType"), + switchName: "type", + switches: [["publicKeyTypeEd25519", "ed25519"]], + arms: { + ed25519: xdr.lookup("Uint256") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // /* Public key that must sign the payload. */ + // uint256 ed25519; + // /* Payload to be raw signed by ed25519. */ + // opaque payload<64>; + // } + // + // =========================================================================== + xdr.struct("SignerKeyEd25519SignedPayload", [["ed25519", xdr.lookup("Uint256")], ["payload", xdr.varOpaque(64)]]); + + // === xdr source ============================================================ + // + // union SignerKey switch (SignerKeyType type) + // { + // case SIGNER_KEY_TYPE_ED25519: + // uint256 ed25519; + // case SIGNER_KEY_TYPE_PRE_AUTH_TX: + // /* SHA-256 Hash of TransactionSignaturePayload structure */ + // uint256 preAuthTx; + // case SIGNER_KEY_TYPE_HASH_X: + // /* Hash of random 256 bit preimage X */ + // uint256 hashX; + // case SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD: + // struct + // { + // /* Public key that must sign the payload. */ + // uint256 ed25519; + // /* Payload to be raw signed by ed25519. */ + // opaque payload<64>; + // } ed25519SignedPayload; + // }; + // + // =========================================================================== + xdr.union("SignerKey", { + switchOn: xdr.lookup("SignerKeyType"), + switchName: "type", + switches: [["signerKeyTypeEd25519", "ed25519"], ["signerKeyTypePreAuthTx", "preAuthTx"], ["signerKeyTypeHashX", "hashX"], ["signerKeyTypeEd25519SignedPayload", "ed25519SignedPayload"]], + arms: { + ed25519: xdr.lookup("Uint256"), + preAuthTx: xdr.lookup("Uint256"), + hashX: xdr.lookup("Uint256"), + ed25519SignedPayload: xdr.lookup("SignerKeyEd25519SignedPayload") + } + }); + + // === xdr source ============================================================ + // + // typedef opaque Signature<64>; + // + // =========================================================================== + xdr.typedef("Signature", xdr.varOpaque(64)); + + // === xdr source ============================================================ + // + // typedef opaque SignatureHint[4]; + // + // =========================================================================== + xdr.typedef("SignatureHint", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef PublicKey NodeID; + // + // =========================================================================== + xdr.typedef("NodeId", xdr.lookup("PublicKey")); + + // === xdr source ============================================================ + // + // typedef PublicKey AccountID; + // + // =========================================================================== + xdr.typedef("AccountId", xdr.lookup("PublicKey")); + + // === xdr source ============================================================ + // + // struct Curve25519Secret + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("Curve25519Secret", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct Curve25519Public + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("Curve25519Public", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct HmacSha256Key + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("HmacSha256Key", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct HmacSha256Mac + // { + // opaque mac[32]; + // }; + // + // =========================================================================== + xdr.struct("HmacSha256Mac", [["mac", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct ShortHashSeed + // { + // opaque seed[16]; + // }; + // + // =========================================================================== + xdr.struct("ShortHashSeed", [["seed", xdr.opaque(16)]]); + + // === xdr source ============================================================ + // + // enum BinaryFuseFilterType + // { + // BINARY_FUSE_FILTER_8_BIT = 0, + // BINARY_FUSE_FILTER_16_BIT = 1, + // BINARY_FUSE_FILTER_32_BIT = 2 + // }; + // + // =========================================================================== + xdr["enum"]("BinaryFuseFilterType", { + binaryFuseFilter8Bit: 0, + binaryFuseFilter16Bit: 1, + binaryFuseFilter32Bit: 2 + }); + + // === xdr source ============================================================ + // + // struct SerializedBinaryFuseFilter + // { + // BinaryFuseFilterType type; + // + // // Seed used to hash input to filter + // ShortHashSeed inputHashSeed; + // + // // Seed used for internal filter hash operations + // ShortHashSeed filterSeed; + // uint32 segmentLength; + // uint32 segementLengthMask; + // uint32 segmentCount; + // uint32 segmentCountLength; + // uint32 fingerprintLength; // Length in terms of element count, not bytes + // + // // Array of uint8_t, uint16_t, or uint32_t depending on filter type + // opaque fingerprints<>; + // }; + // + // =========================================================================== + xdr.struct("SerializedBinaryFuseFilter", [["type", xdr.lookup("BinaryFuseFilterType")], ["inputHashSeed", xdr.lookup("ShortHashSeed")], ["filterSeed", xdr.lookup("ShortHashSeed")], ["segmentLength", xdr.lookup("Uint32")], ["segementLengthMask", xdr.lookup("Uint32")], ["segmentCount", xdr.lookup("Uint32")], ["segmentCountLength", xdr.lookup("Uint32")], ["fingerprintLength", xdr.lookup("Uint32")], ["fingerprints", xdr.varOpaque()]]); + + // === xdr source ============================================================ + // + // enum SCValType + // { + // SCV_BOOL = 0, + // SCV_VOID = 1, + // SCV_ERROR = 2, + // + // // 32 bits is the smallest type in WASM or XDR; no need for u8/u16. + // SCV_U32 = 3, + // SCV_I32 = 4, + // + // // 64 bits is naturally supported by both WASM and XDR also. + // SCV_U64 = 5, + // SCV_I64 = 6, + // + // // Time-related u64 subtypes with their own functions and formatting. + // SCV_TIMEPOINT = 7, + // SCV_DURATION = 8, + // + // // 128 bits is naturally supported by Rust and we use it for Soroban + // // fixed-point arithmetic prices / balances / similar "quantities". These + // // are represented in XDR as a pair of 2 u64s. + // SCV_U128 = 9, + // SCV_I128 = 10, + // + // // 256 bits is the size of sha256 output, ed25519 keys, and the EVM machine + // // word, so for interop use we include this even though it requires a small + // // amount of Rust guest and/or host library code. + // SCV_U256 = 11, + // SCV_I256 = 12, + // + // // Bytes come in 3 flavors, 2 of which have meaningfully different + // // formatting and validity-checking / domain-restriction. + // SCV_BYTES = 13, + // SCV_STRING = 14, + // SCV_SYMBOL = 15, + // + // // Vecs and maps are just polymorphic containers of other ScVals. + // SCV_VEC = 16, + // SCV_MAP = 17, + // + // // Address is the universal identifier for contracts and classic + // // accounts. + // SCV_ADDRESS = 18, + // + // // The following are the internal SCVal variants that are not + // // exposed to the contracts. + // SCV_CONTRACT_INSTANCE = 19, + // + // // SCV_LEDGER_KEY_CONTRACT_INSTANCE and SCV_LEDGER_KEY_NONCE are unique + // // symbolic SCVals used as the key for ledger entries for a contract's + // // instance and an address' nonce, respectively. + // SCV_LEDGER_KEY_CONTRACT_INSTANCE = 20, + // SCV_LEDGER_KEY_NONCE = 21 + // }; + // + // =========================================================================== + xdr["enum"]("ScValType", { + scvBool: 0, + scvVoid: 1, + scvError: 2, + scvU32: 3, + scvI32: 4, + scvU64: 5, + scvI64: 6, + scvTimepoint: 7, + scvDuration: 8, + scvU128: 9, + scvI128: 10, + scvU256: 11, + scvI256: 12, + scvBytes: 13, + scvString: 14, + scvSymbol: 15, + scvVec: 16, + scvMap: 17, + scvAddress: 18, + scvContractInstance: 19, + scvLedgerKeyContractInstance: 20, + scvLedgerKeyNonce: 21 + }); + + // === xdr source ============================================================ + // + // enum SCErrorType + // { + // SCE_CONTRACT = 0, // Contract-specific, user-defined codes. + // SCE_WASM_VM = 1, // Errors while interpreting WASM bytecode. + // SCE_CONTEXT = 2, // Errors in the contract's host context. + // SCE_STORAGE = 3, // Errors accessing host storage. + // SCE_OBJECT = 4, // Errors working with host objects. + // SCE_CRYPTO = 5, // Errors in cryptographic operations. + // SCE_EVENTS = 6, // Errors while emitting events. + // SCE_BUDGET = 7, // Errors relating to budget limits. + // SCE_VALUE = 8, // Errors working with host values or SCVals. + // SCE_AUTH = 9 // Errors from the authentication subsystem. + // }; + // + // =========================================================================== + xdr["enum"]("ScErrorType", { + sceContract: 0, + sceWasmVm: 1, + sceContext: 2, + sceStorage: 3, + sceObject: 4, + sceCrypto: 5, + sceEvents: 6, + sceBudget: 7, + sceValue: 8, + sceAuth: 9 + }); + + // === xdr source ============================================================ + // + // enum SCErrorCode + // { + // SCEC_ARITH_DOMAIN = 0, // Some arithmetic was undefined (overflow, divide-by-zero). + // SCEC_INDEX_BOUNDS = 1, // Something was indexed beyond its bounds. + // SCEC_INVALID_INPUT = 2, // User provided some otherwise-bad data. + // SCEC_MISSING_VALUE = 3, // Some value was required but not provided. + // SCEC_EXISTING_VALUE = 4, // Some value was provided where not allowed. + // SCEC_EXCEEDED_LIMIT = 5, // Some arbitrary limit -- gas or otherwise -- was hit. + // SCEC_INVALID_ACTION = 6, // Data was valid but action requested was not. + // SCEC_INTERNAL_ERROR = 7, // The host detected an error in its own logic. + // SCEC_UNEXPECTED_TYPE = 8, // Some type wasn't as expected. + // SCEC_UNEXPECTED_SIZE = 9 // Something's size wasn't as expected. + // }; + // + // =========================================================================== + xdr["enum"]("ScErrorCode", { + scecArithDomain: 0, + scecIndexBounds: 1, + scecInvalidInput: 2, + scecMissingValue: 3, + scecExistingValue: 4, + scecExceededLimit: 5, + scecInvalidAction: 6, + scecInternalError: 7, + scecUnexpectedType: 8, + scecUnexpectedSize: 9 + }); + + // === xdr source ============================================================ + // + // union SCError switch (SCErrorType type) + // { + // case SCE_CONTRACT: + // uint32 contractCode; + // case SCE_WASM_VM: + // case SCE_CONTEXT: + // case SCE_STORAGE: + // case SCE_OBJECT: + // case SCE_CRYPTO: + // case SCE_EVENTS: + // case SCE_BUDGET: + // case SCE_VALUE: + // case SCE_AUTH: + // SCErrorCode code; + // }; + // + // =========================================================================== + xdr.union("ScError", { + switchOn: xdr.lookup("ScErrorType"), + switchName: "type", + switches: [["sceContract", "contractCode"], ["sceWasmVm", "code"], ["sceContext", "code"], ["sceStorage", "code"], ["sceObject", "code"], ["sceCrypto", "code"], ["sceEvents", "code"], ["sceBudget", "code"], ["sceValue", "code"], ["sceAuth", "code"]], + arms: { + contractCode: xdr.lookup("Uint32"), + code: xdr.lookup("ScErrorCode") + } + }); + + // === xdr source ============================================================ + // + // struct UInt128Parts { + // uint64 hi; + // uint64 lo; + // }; + // + // =========================================================================== + xdr.struct("UInt128Parts", [["hi", xdr.lookup("Uint64")], ["lo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct Int128Parts { + // int64 hi; + // uint64 lo; + // }; + // + // =========================================================================== + xdr.struct("Int128Parts", [["hi", xdr.lookup("Int64")], ["lo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct UInt256Parts { + // uint64 hi_hi; + // uint64 hi_lo; + // uint64 lo_hi; + // uint64 lo_lo; + // }; + // + // =========================================================================== + xdr.struct("UInt256Parts", [["hiHi", xdr.lookup("Uint64")], ["hiLo", xdr.lookup("Uint64")], ["loHi", xdr.lookup("Uint64")], ["loLo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct Int256Parts { + // int64 hi_hi; + // uint64 hi_lo; + // uint64 lo_hi; + // uint64 lo_lo; + // }; + // + // =========================================================================== + xdr.struct("Int256Parts", [["hiHi", xdr.lookup("Int64")], ["hiLo", xdr.lookup("Uint64")], ["loHi", xdr.lookup("Uint64")], ["loLo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // enum ContractExecutableType + // { + // CONTRACT_EXECUTABLE_WASM = 0, + // CONTRACT_EXECUTABLE_STELLAR_ASSET = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractExecutableType", { + contractExecutableWasm: 0, + contractExecutableStellarAsset: 1 + }); + + // === xdr source ============================================================ + // + // union ContractExecutable switch (ContractExecutableType type) + // { + // case CONTRACT_EXECUTABLE_WASM: + // Hash wasm_hash; + // case CONTRACT_EXECUTABLE_STELLAR_ASSET: + // void; + // }; + // + // =========================================================================== + xdr.union("ContractExecutable", { + switchOn: xdr.lookup("ContractExecutableType"), + switchName: "type", + switches: [["contractExecutableWasm", "wasmHash"], ["contractExecutableStellarAsset", xdr["void"]()]], + arms: { + wasmHash: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum SCAddressType + // { + // SC_ADDRESS_TYPE_ACCOUNT = 0, + // SC_ADDRESS_TYPE_CONTRACT = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ScAddressType", { + scAddressTypeAccount: 0, + scAddressTypeContract: 1 + }); + + // === xdr source ============================================================ + // + // union SCAddress switch (SCAddressType type) + // { + // case SC_ADDRESS_TYPE_ACCOUNT: + // AccountID accountId; + // case SC_ADDRESS_TYPE_CONTRACT: + // Hash contractId; + // }; + // + // =========================================================================== + xdr.union("ScAddress", { + switchOn: xdr.lookup("ScAddressType"), + switchName: "type", + switches: [["scAddressTypeAccount", "accountId"], ["scAddressTypeContract", "contractId"]], + arms: { + accountId: xdr.lookup("AccountId"), + contractId: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // const SCSYMBOL_LIMIT = 32; + // + // =========================================================================== + xdr["const"]("SCSYMBOL_LIMIT", 32); + + // === xdr source ============================================================ + // + // typedef SCVal SCVec<>; + // + // =========================================================================== + xdr.typedef("ScVec", xdr.varArray(xdr.lookup("ScVal"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef SCMapEntry SCMap<>; + // + // =========================================================================== + xdr.typedef("ScMap", xdr.varArray(xdr.lookup("ScMapEntry"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef opaque SCBytes<>; + // + // =========================================================================== + xdr.typedef("ScBytes", xdr.varOpaque()); + + // === xdr source ============================================================ + // + // typedef string SCString<>; + // + // =========================================================================== + xdr.typedef("ScString", xdr.string()); + + // === xdr source ============================================================ + // + // typedef string SCSymbol; + // + // =========================================================================== + xdr.typedef("ScSymbol", xdr.string(SCSYMBOL_LIMIT)); + + // === xdr source ============================================================ + // + // struct SCNonceKey { + // int64 nonce; + // }; + // + // =========================================================================== + xdr.struct("ScNonceKey", [["nonce", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct SCContractInstance { + // ContractExecutable executable; + // SCMap* storage; + // }; + // + // =========================================================================== + xdr.struct("ScContractInstance", [["executable", xdr.lookup("ContractExecutable")], ["storage", xdr.option(xdr.lookup("ScMap"))]]); + + // === xdr source ============================================================ + // + // union SCVal switch (SCValType type) + // { + // + // case SCV_BOOL: + // bool b; + // case SCV_VOID: + // void; + // case SCV_ERROR: + // SCError error; + // + // case SCV_U32: + // uint32 u32; + // case SCV_I32: + // int32 i32; + // + // case SCV_U64: + // uint64 u64; + // case SCV_I64: + // int64 i64; + // case SCV_TIMEPOINT: + // TimePoint timepoint; + // case SCV_DURATION: + // Duration duration; + // + // case SCV_U128: + // UInt128Parts u128; + // case SCV_I128: + // Int128Parts i128; + // + // case SCV_U256: + // UInt256Parts u256; + // case SCV_I256: + // Int256Parts i256; + // + // case SCV_BYTES: + // SCBytes bytes; + // case SCV_STRING: + // SCString str; + // case SCV_SYMBOL: + // SCSymbol sym; + // + // // Vec and Map are recursive so need to live + // // behind an option, due to xdrpp limitations. + // case SCV_VEC: + // SCVec *vec; + // case SCV_MAP: + // SCMap *map; + // + // case SCV_ADDRESS: + // SCAddress address; + // + // // Special SCVals reserved for system-constructed contract-data + // // ledger keys, not generally usable elsewhere. + // case SCV_LEDGER_KEY_CONTRACT_INSTANCE: + // void; + // case SCV_LEDGER_KEY_NONCE: + // SCNonceKey nonce_key; + // + // case SCV_CONTRACT_INSTANCE: + // SCContractInstance instance; + // }; + // + // =========================================================================== + xdr.union("ScVal", { + switchOn: xdr.lookup("ScValType"), + switchName: "type", + switches: [["scvBool", "b"], ["scvVoid", xdr["void"]()], ["scvError", "error"], ["scvU32", "u32"], ["scvI32", "i32"], ["scvU64", "u64"], ["scvI64", "i64"], ["scvTimepoint", "timepoint"], ["scvDuration", "duration"], ["scvU128", "u128"], ["scvI128", "i128"], ["scvU256", "u256"], ["scvI256", "i256"], ["scvBytes", "bytes"], ["scvString", "str"], ["scvSymbol", "sym"], ["scvVec", "vec"], ["scvMap", "map"], ["scvAddress", "address"], ["scvLedgerKeyContractInstance", xdr["void"]()], ["scvLedgerKeyNonce", "nonceKey"], ["scvContractInstance", "instance"]], + arms: { + b: xdr.bool(), + error: xdr.lookup("ScError"), + u32: xdr.lookup("Uint32"), + i32: xdr.lookup("Int32"), + u64: xdr.lookup("Uint64"), + i64: xdr.lookup("Int64"), + timepoint: xdr.lookup("TimePoint"), + duration: xdr.lookup("Duration"), + u128: xdr.lookup("UInt128Parts"), + i128: xdr.lookup("Int128Parts"), + u256: xdr.lookup("UInt256Parts"), + i256: xdr.lookup("Int256Parts"), + bytes: xdr.lookup("ScBytes"), + str: xdr.lookup("ScString"), + sym: xdr.lookup("ScSymbol"), + vec: xdr.option(xdr.lookup("ScVec")), + map: xdr.option(xdr.lookup("ScMap")), + address: xdr.lookup("ScAddress"), + nonceKey: xdr.lookup("ScNonceKey"), + instance: xdr.lookup("ScContractInstance") + } + }); + + // === xdr source ============================================================ + // + // struct SCMapEntry + // { + // SCVal key; + // SCVal val; + // }; + // + // =========================================================================== + xdr.struct("ScMapEntry", [["key", xdr.lookup("ScVal")], ["val", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // enum SCEnvMetaKind + // { + // SC_ENV_META_KIND_INTERFACE_VERSION = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ScEnvMetaKind", { + scEnvMetaKindInterfaceVersion: 0 + }); + + // === xdr source ============================================================ + // + // struct { + // uint32 protocol; + // uint32 preRelease; + // } + // + // =========================================================================== + xdr.struct("ScEnvMetaEntryInterfaceVersion", [["protocol", xdr.lookup("Uint32")], ["preRelease", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union SCEnvMetaEntry switch (SCEnvMetaKind kind) + // { + // case SC_ENV_META_KIND_INTERFACE_VERSION: + // struct { + // uint32 protocol; + // uint32 preRelease; + // } interfaceVersion; + // }; + // + // =========================================================================== + xdr.union("ScEnvMetaEntry", { + switchOn: xdr.lookup("ScEnvMetaKind"), + switchName: "kind", + switches: [["scEnvMetaKindInterfaceVersion", "interfaceVersion"]], + arms: { + interfaceVersion: xdr.lookup("ScEnvMetaEntryInterfaceVersion") + } + }); + + // === xdr source ============================================================ + // + // struct SCMetaV0 + // { + // string key<>; + // string val<>; + // }; + // + // =========================================================================== + xdr.struct("ScMetaV0", [["key", xdr.string()], ["val", xdr.string()]]); + + // === xdr source ============================================================ + // + // enum SCMetaKind + // { + // SC_META_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ScMetaKind", { + scMetaV0: 0 + }); + + // === xdr source ============================================================ + // + // union SCMetaEntry switch (SCMetaKind kind) + // { + // case SC_META_V0: + // SCMetaV0 v0; + // }; + // + // =========================================================================== + xdr.union("ScMetaEntry", { + switchOn: xdr.lookup("ScMetaKind"), + switchName: "kind", + switches: [["scMetaV0", "v0"]], + arms: { + v0: xdr.lookup("ScMetaV0") + } + }); + + // === xdr source ============================================================ + // + // const SC_SPEC_DOC_LIMIT = 1024; + // + // =========================================================================== + xdr["const"]("SC_SPEC_DOC_LIMIT", 1024); + + // === xdr source ============================================================ + // + // enum SCSpecType + // { + // SC_SPEC_TYPE_VAL = 0, + // + // // Types with no parameters. + // SC_SPEC_TYPE_BOOL = 1, + // SC_SPEC_TYPE_VOID = 2, + // SC_SPEC_TYPE_ERROR = 3, + // SC_SPEC_TYPE_U32 = 4, + // SC_SPEC_TYPE_I32 = 5, + // SC_SPEC_TYPE_U64 = 6, + // SC_SPEC_TYPE_I64 = 7, + // SC_SPEC_TYPE_TIMEPOINT = 8, + // SC_SPEC_TYPE_DURATION = 9, + // SC_SPEC_TYPE_U128 = 10, + // SC_SPEC_TYPE_I128 = 11, + // SC_SPEC_TYPE_U256 = 12, + // SC_SPEC_TYPE_I256 = 13, + // SC_SPEC_TYPE_BYTES = 14, + // SC_SPEC_TYPE_STRING = 16, + // SC_SPEC_TYPE_SYMBOL = 17, + // SC_SPEC_TYPE_ADDRESS = 19, + // + // // Types with parameters. + // SC_SPEC_TYPE_OPTION = 1000, + // SC_SPEC_TYPE_RESULT = 1001, + // SC_SPEC_TYPE_VEC = 1002, + // SC_SPEC_TYPE_MAP = 1004, + // SC_SPEC_TYPE_TUPLE = 1005, + // SC_SPEC_TYPE_BYTES_N = 1006, + // + // // User defined types. + // SC_SPEC_TYPE_UDT = 2000 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecType", { + scSpecTypeVal: 0, + scSpecTypeBool: 1, + scSpecTypeVoid: 2, + scSpecTypeError: 3, + scSpecTypeU32: 4, + scSpecTypeI32: 5, + scSpecTypeU64: 6, + scSpecTypeI64: 7, + scSpecTypeTimepoint: 8, + scSpecTypeDuration: 9, + scSpecTypeU128: 10, + scSpecTypeI128: 11, + scSpecTypeU256: 12, + scSpecTypeI256: 13, + scSpecTypeBytes: 14, + scSpecTypeString: 16, + scSpecTypeSymbol: 17, + scSpecTypeAddress: 19, + scSpecTypeOption: 1000, + scSpecTypeResult: 1001, + scSpecTypeVec: 1002, + scSpecTypeMap: 1004, + scSpecTypeTuple: 1005, + scSpecTypeBytesN: 1006, + scSpecTypeUdt: 2000 + }); + + // === xdr source ============================================================ + // + // struct SCSpecTypeOption + // { + // SCSpecTypeDef valueType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeOption", [["valueType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeResult + // { + // SCSpecTypeDef okType; + // SCSpecTypeDef errorType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeResult", [["okType", xdr.lookup("ScSpecTypeDef")], ["errorType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeVec + // { + // SCSpecTypeDef elementType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeVec", [["elementType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeMap + // { + // SCSpecTypeDef keyType; + // SCSpecTypeDef valueType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeMap", [["keyType", xdr.lookup("ScSpecTypeDef")], ["valueType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeTuple + // { + // SCSpecTypeDef valueTypes<12>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeTuple", [["valueTypes", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 12)]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeBytesN + // { + // uint32 n; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeBytesN", [["n", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeUDT + // { + // string name<60>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeUdt", [["name", xdr.string(60)]]); + + // === xdr source ============================================================ + // + // union SCSpecTypeDef switch (SCSpecType type) + // { + // case SC_SPEC_TYPE_VAL: + // case SC_SPEC_TYPE_BOOL: + // case SC_SPEC_TYPE_VOID: + // case SC_SPEC_TYPE_ERROR: + // case SC_SPEC_TYPE_U32: + // case SC_SPEC_TYPE_I32: + // case SC_SPEC_TYPE_U64: + // case SC_SPEC_TYPE_I64: + // case SC_SPEC_TYPE_TIMEPOINT: + // case SC_SPEC_TYPE_DURATION: + // case SC_SPEC_TYPE_U128: + // case SC_SPEC_TYPE_I128: + // case SC_SPEC_TYPE_U256: + // case SC_SPEC_TYPE_I256: + // case SC_SPEC_TYPE_BYTES: + // case SC_SPEC_TYPE_STRING: + // case SC_SPEC_TYPE_SYMBOL: + // case SC_SPEC_TYPE_ADDRESS: + // void; + // case SC_SPEC_TYPE_OPTION: + // SCSpecTypeOption option; + // case SC_SPEC_TYPE_RESULT: + // SCSpecTypeResult result; + // case SC_SPEC_TYPE_VEC: + // SCSpecTypeVec vec; + // case SC_SPEC_TYPE_MAP: + // SCSpecTypeMap map; + // case SC_SPEC_TYPE_TUPLE: + // SCSpecTypeTuple tuple; + // case SC_SPEC_TYPE_BYTES_N: + // SCSpecTypeBytesN bytesN; + // case SC_SPEC_TYPE_UDT: + // SCSpecTypeUDT udt; + // }; + // + // =========================================================================== + xdr.union("ScSpecTypeDef", { + switchOn: xdr.lookup("ScSpecType"), + switchName: "type", + switches: [["scSpecTypeVal", xdr["void"]()], ["scSpecTypeBool", xdr["void"]()], ["scSpecTypeVoid", xdr["void"]()], ["scSpecTypeError", xdr["void"]()], ["scSpecTypeU32", xdr["void"]()], ["scSpecTypeI32", xdr["void"]()], ["scSpecTypeU64", xdr["void"]()], ["scSpecTypeI64", xdr["void"]()], ["scSpecTypeTimepoint", xdr["void"]()], ["scSpecTypeDuration", xdr["void"]()], ["scSpecTypeU128", xdr["void"]()], ["scSpecTypeI128", xdr["void"]()], ["scSpecTypeU256", xdr["void"]()], ["scSpecTypeI256", xdr["void"]()], ["scSpecTypeBytes", xdr["void"]()], ["scSpecTypeString", xdr["void"]()], ["scSpecTypeSymbol", xdr["void"]()], ["scSpecTypeAddress", xdr["void"]()], ["scSpecTypeOption", "option"], ["scSpecTypeResult", "result"], ["scSpecTypeVec", "vec"], ["scSpecTypeMap", "map"], ["scSpecTypeTuple", "tuple"], ["scSpecTypeBytesN", "bytesN"], ["scSpecTypeUdt", "udt"]], + arms: { + option: xdr.lookup("ScSpecTypeOption"), + result: xdr.lookup("ScSpecTypeResult"), + vec: xdr.lookup("ScSpecTypeVec"), + map: xdr.lookup("ScSpecTypeMap"), + tuple: xdr.lookup("ScSpecTypeTuple"), + bytesN: xdr.lookup("ScSpecTypeBytesN"), + udt: xdr.lookup("ScSpecTypeUdt") + } + }); + + // === xdr source ============================================================ + // + // struct SCSpecUDTStructFieldV0 + // { + // string doc; + // string name<30>; + // SCSpecTypeDef type; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtStructFieldV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(30)], ["type", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTStructV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTStructFieldV0 fields<40>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtStructV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["fields", xdr.varArray(xdr.lookup("ScSpecUdtStructFieldV0"), 40)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionCaseVoidV0 + // { + // string doc; + // string name<60>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionCaseVoidV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionCaseTupleV0 + // { + // string doc; + // string name<60>; + // SCSpecTypeDef type<12>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionCaseTupleV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["type", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 12)]]); + + // === xdr source ============================================================ + // + // enum SCSpecUDTUnionCaseV0Kind + // { + // SC_SPEC_UDT_UNION_CASE_VOID_V0 = 0, + // SC_SPEC_UDT_UNION_CASE_TUPLE_V0 = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecUdtUnionCaseV0Kind", { + scSpecUdtUnionCaseVoidV0: 0, + scSpecUdtUnionCaseTupleV0: 1 + }); + + // === xdr source ============================================================ + // + // union SCSpecUDTUnionCaseV0 switch (SCSpecUDTUnionCaseV0Kind kind) + // { + // case SC_SPEC_UDT_UNION_CASE_VOID_V0: + // SCSpecUDTUnionCaseVoidV0 voidCase; + // case SC_SPEC_UDT_UNION_CASE_TUPLE_V0: + // SCSpecUDTUnionCaseTupleV0 tupleCase; + // }; + // + // =========================================================================== + xdr.union("ScSpecUdtUnionCaseV0", { + switchOn: xdr.lookup("ScSpecUdtUnionCaseV0Kind"), + switchName: "kind", + switches: [["scSpecUdtUnionCaseVoidV0", "voidCase"], ["scSpecUdtUnionCaseTupleV0", "tupleCase"]], + arms: { + voidCase: xdr.lookup("ScSpecUdtUnionCaseVoidV0"), + tupleCase: xdr.lookup("ScSpecUdtUnionCaseTupleV0") + } + }); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTUnionCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtUnionCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTEnumCaseV0 + // { + // string doc; + // string name<60>; + // uint32 value; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtEnumCaseV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["value", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTEnumV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTEnumCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtEnumV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtEnumCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTErrorEnumCaseV0 + // { + // string doc; + // string name<60>; + // uint32 value; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtErrorEnumCaseV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["value", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTErrorEnumV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTErrorEnumCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtErrorEnumV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtErrorEnumCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecFunctionInputV0 + // { + // string doc; + // string name<30>; + // SCSpecTypeDef type; + // }; + // + // =========================================================================== + xdr.struct("ScSpecFunctionInputV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(30)], ["type", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecFunctionV0 + // { + // string doc; + // SCSymbol name; + // SCSpecFunctionInputV0 inputs<10>; + // SCSpecTypeDef outputs<1>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecFunctionV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.lookup("ScSymbol")], ["inputs", xdr.varArray(xdr.lookup("ScSpecFunctionInputV0"), 10)], ["outputs", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 1)]]); + + // === xdr source ============================================================ + // + // enum SCSpecEntryKind + // { + // SC_SPEC_ENTRY_FUNCTION_V0 = 0, + // SC_SPEC_ENTRY_UDT_STRUCT_V0 = 1, + // SC_SPEC_ENTRY_UDT_UNION_V0 = 2, + // SC_SPEC_ENTRY_UDT_ENUM_V0 = 3, + // SC_SPEC_ENTRY_UDT_ERROR_ENUM_V0 = 4 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecEntryKind", { + scSpecEntryFunctionV0: 0, + scSpecEntryUdtStructV0: 1, + scSpecEntryUdtUnionV0: 2, + scSpecEntryUdtEnumV0: 3, + scSpecEntryUdtErrorEnumV0: 4 + }); + + // === xdr source ============================================================ + // + // union SCSpecEntry switch (SCSpecEntryKind kind) + // { + // case SC_SPEC_ENTRY_FUNCTION_V0: + // SCSpecFunctionV0 functionV0; + // case SC_SPEC_ENTRY_UDT_STRUCT_V0: + // SCSpecUDTStructV0 udtStructV0; + // case SC_SPEC_ENTRY_UDT_UNION_V0: + // SCSpecUDTUnionV0 udtUnionV0; + // case SC_SPEC_ENTRY_UDT_ENUM_V0: + // SCSpecUDTEnumV0 udtEnumV0; + // case SC_SPEC_ENTRY_UDT_ERROR_ENUM_V0: + // SCSpecUDTErrorEnumV0 udtErrorEnumV0; + // }; + // + // =========================================================================== + xdr.union("ScSpecEntry", { + switchOn: xdr.lookup("ScSpecEntryKind"), + switchName: "kind", + switches: [["scSpecEntryFunctionV0", "functionV0"], ["scSpecEntryUdtStructV0", "udtStructV0"], ["scSpecEntryUdtUnionV0", "udtUnionV0"], ["scSpecEntryUdtEnumV0", "udtEnumV0"], ["scSpecEntryUdtErrorEnumV0", "udtErrorEnumV0"]], + arms: { + functionV0: xdr.lookup("ScSpecFunctionV0"), + udtStructV0: xdr.lookup("ScSpecUdtStructV0"), + udtUnionV0: xdr.lookup("ScSpecUdtUnionV0"), + udtEnumV0: xdr.lookup("ScSpecUdtEnumV0"), + udtErrorEnumV0: xdr.lookup("ScSpecUdtErrorEnumV0") + } + }); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractExecutionLanesV0 + // { + // // maximum number of Soroban transactions per ledger + // uint32 ledgerMaxTxCount; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractExecutionLanesV0", [["ledgerMaxTxCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractComputeV0 + // { + // // Maximum instructions per ledger + // int64 ledgerMaxInstructions; + // // Maximum instructions per transaction + // int64 txMaxInstructions; + // // Cost of 10000 instructions + // int64 feeRatePerInstructionsIncrement; + // + // // Memory limit per transaction. Unlike instructions, there is no fee + // // for memory, just the limit. + // uint32 txMemoryLimit; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractComputeV0", [["ledgerMaxInstructions", xdr.lookup("Int64")], ["txMaxInstructions", xdr.lookup("Int64")], ["feeRatePerInstructionsIncrement", xdr.lookup("Int64")], ["txMemoryLimit", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractLedgerCostV0 + // { + // // Maximum number of ledger entry read operations per ledger + // uint32 ledgerMaxReadLedgerEntries; + // // Maximum number of bytes that can be read per ledger + // uint32 ledgerMaxReadBytes; + // // Maximum number of ledger entry write operations per ledger + // uint32 ledgerMaxWriteLedgerEntries; + // // Maximum number of bytes that can be written per ledger + // uint32 ledgerMaxWriteBytes; + // + // // Maximum number of ledger entry read operations per transaction + // uint32 txMaxReadLedgerEntries; + // // Maximum number of bytes that can be read per transaction + // uint32 txMaxReadBytes; + // // Maximum number of ledger entry write operations per transaction + // uint32 txMaxWriteLedgerEntries; + // // Maximum number of bytes that can be written per transaction + // uint32 txMaxWriteBytes; + // + // int64 feeReadLedgerEntry; // Fee per ledger entry read + // int64 feeWriteLedgerEntry; // Fee per ledger entry write + // + // int64 feeRead1KB; // Fee for reading 1KB + // + // // The following parameters determine the write fee per 1KB. + // // Write fee grows linearly until bucket list reaches this size + // int64 bucketListTargetSizeBytes; + // // Fee per 1KB write when the bucket list is empty + // int64 writeFee1KBBucketListLow; + // // Fee per 1KB write when the bucket list has reached `bucketListTargetSizeBytes` + // int64 writeFee1KBBucketListHigh; + // // Write fee multiplier for any additional data past the first `bucketListTargetSizeBytes` + // uint32 bucketListWriteFeeGrowthFactor; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractLedgerCostV0", [["ledgerMaxReadLedgerEntries", xdr.lookup("Uint32")], ["ledgerMaxReadBytes", xdr.lookup("Uint32")], ["ledgerMaxWriteLedgerEntries", xdr.lookup("Uint32")], ["ledgerMaxWriteBytes", xdr.lookup("Uint32")], ["txMaxReadLedgerEntries", xdr.lookup("Uint32")], ["txMaxReadBytes", xdr.lookup("Uint32")], ["txMaxWriteLedgerEntries", xdr.lookup("Uint32")], ["txMaxWriteBytes", xdr.lookup("Uint32")], ["feeReadLedgerEntry", xdr.lookup("Int64")], ["feeWriteLedgerEntry", xdr.lookup("Int64")], ["feeRead1Kb", xdr.lookup("Int64")], ["bucketListTargetSizeBytes", xdr.lookup("Int64")], ["writeFee1KbBucketListLow", xdr.lookup("Int64")], ["writeFee1KbBucketListHigh", xdr.lookup("Int64")], ["bucketListWriteFeeGrowthFactor", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractHistoricalDataV0 + // { + // int64 feeHistorical1KB; // Fee for storing 1KB in archives + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractHistoricalDataV0", [["feeHistorical1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractEventsV0 + // { + // // Maximum size of events that a contract call can emit. + // uint32 txMaxContractEventsSizeBytes; + // // Fee for generating 1KB of contract events. + // int64 feeContractEvents1KB; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractEventsV0", [["txMaxContractEventsSizeBytes", xdr.lookup("Uint32")], ["feeContractEvents1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractBandwidthV0 + // { + // // Maximum sum of all transaction sizes in the ledger in bytes + // uint32 ledgerMaxTxsSizeBytes; + // // Maximum size in bytes for a transaction + // uint32 txMaxSizeBytes; + // + // // Fee for 1 KB of transaction size + // int64 feeTxSize1KB; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractBandwidthV0", [["ledgerMaxTxsSizeBytes", xdr.lookup("Uint32")], ["txMaxSizeBytes", xdr.lookup("Uint32")], ["feeTxSize1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum ContractCostType { + // // Cost of running 1 wasm instruction + // WasmInsnExec = 0, + // // Cost of allocating a slice of memory (in bytes) + // MemAlloc = 1, + // // Cost of copying a slice of bytes into a pre-allocated memory + // MemCpy = 2, + // // Cost of comparing two slices of memory + // MemCmp = 3, + // // Cost of a host function dispatch, not including the actual work done by + // // the function nor the cost of VM invocation machinary + // DispatchHostFunction = 4, + // // Cost of visiting a host object from the host object storage. Exists to + // // make sure some baseline cost coverage, i.e. repeatly visiting objects + // // by the guest will always incur some charges. + // VisitObject = 5, + // // Cost of serializing an xdr object to bytes + // ValSer = 6, + // // Cost of deserializing an xdr object from bytes + // ValDeser = 7, + // // Cost of computing the sha256 hash from bytes + // ComputeSha256Hash = 8, + // // Cost of computing the ed25519 pubkey from bytes + // ComputeEd25519PubKey = 9, + // // Cost of verifying ed25519 signature of a payload. + // VerifyEd25519Sig = 10, + // // Cost of instantiation a VM from wasm bytes code. + // VmInstantiation = 11, + // // Cost of instantiation a VM from a cached state. + // VmCachedInstantiation = 12, + // // Cost of invoking a function on the VM. If the function is a host function, + // // additional cost will be covered by `DispatchHostFunction`. + // InvokeVmFunction = 13, + // // Cost of computing a keccak256 hash from bytes. + // ComputeKeccak256Hash = 14, + // // Cost of decoding an ECDSA signature computed from a 256-bit prime modulus + // // curve (e.g. secp256k1 and secp256r1) + // DecodeEcdsaCurve256Sig = 15, + // // Cost of recovering an ECDSA secp256k1 key from a signature. + // RecoverEcdsaSecp256k1Key = 16, + // // Cost of int256 addition (`+`) and subtraction (`-`) operations + // Int256AddSub = 17, + // // Cost of int256 multiplication (`*`) operation + // Int256Mul = 18, + // // Cost of int256 division (`/`) operation + // Int256Div = 19, + // // Cost of int256 power (`exp`) operation + // Int256Pow = 20, + // // Cost of int256 shift (`shl`, `shr`) operation + // Int256Shift = 21, + // // Cost of drawing random bytes using a ChaCha20 PRNG + // ChaCha20DrawBytes = 22, + // + // // Cost of parsing wasm bytes that only encode instructions. + // ParseWasmInstructions = 23, + // // Cost of parsing a known number of wasm functions. + // ParseWasmFunctions = 24, + // // Cost of parsing a known number of wasm globals. + // ParseWasmGlobals = 25, + // // Cost of parsing a known number of wasm table entries. + // ParseWasmTableEntries = 26, + // // Cost of parsing a known number of wasm types. + // ParseWasmTypes = 27, + // // Cost of parsing a known number of wasm data segments. + // ParseWasmDataSegments = 28, + // // Cost of parsing a known number of wasm element segments. + // ParseWasmElemSegments = 29, + // // Cost of parsing a known number of wasm imports. + // ParseWasmImports = 30, + // // Cost of parsing a known number of wasm exports. + // ParseWasmExports = 31, + // // Cost of parsing a known number of data segment bytes. + // ParseWasmDataSegmentBytes = 32, + // + // // Cost of instantiating wasm bytes that only encode instructions. + // InstantiateWasmInstructions = 33, + // // Cost of instantiating a known number of wasm functions. + // InstantiateWasmFunctions = 34, + // // Cost of instantiating a known number of wasm globals. + // InstantiateWasmGlobals = 35, + // // Cost of instantiating a known number of wasm table entries. + // InstantiateWasmTableEntries = 36, + // // Cost of instantiating a known number of wasm types. + // InstantiateWasmTypes = 37, + // // Cost of instantiating a known number of wasm data segments. + // InstantiateWasmDataSegments = 38, + // // Cost of instantiating a known number of wasm element segments. + // InstantiateWasmElemSegments = 39, + // // Cost of instantiating a known number of wasm imports. + // InstantiateWasmImports = 40, + // // Cost of instantiating a known number of wasm exports. + // InstantiateWasmExports = 41, + // // Cost of instantiating a known number of data segment bytes. + // InstantiateWasmDataSegmentBytes = 42, + // + // // Cost of decoding a bytes array representing an uncompressed SEC-1 encoded + // // point on a 256-bit elliptic curve + // Sec1DecodePointUncompressed = 43, + // // Cost of verifying an ECDSA Secp256r1 signature + // VerifyEcdsaSecp256r1Sig = 44, + // + // // Cost of encoding a BLS12-381 Fp (base field element) + // Bls12381EncodeFp = 45, + // // Cost of decoding a BLS12-381 Fp (base field element) + // Bls12381DecodeFp = 46, + // // Cost of checking a G1 point lies on the curve + // Bls12381G1CheckPointOnCurve = 47, + // // Cost of checking a G1 point belongs to the correct subgroup + // Bls12381G1CheckPointInSubgroup = 48, + // // Cost of checking a G2 point lies on the curve + // Bls12381G2CheckPointOnCurve = 49, + // // Cost of checking a G2 point belongs to the correct subgroup + // Bls12381G2CheckPointInSubgroup = 50, + // // Cost of converting a BLS12-381 G1 point from projective to affine coordinates + // Bls12381G1ProjectiveToAffine = 51, + // // Cost of converting a BLS12-381 G2 point from projective to affine coordinates + // Bls12381G2ProjectiveToAffine = 52, + // // Cost of performing BLS12-381 G1 point addition + // Bls12381G1Add = 53, + // // Cost of performing BLS12-381 G1 scalar multiplication + // Bls12381G1Mul = 54, + // // Cost of performing BLS12-381 G1 multi-scalar multiplication (MSM) + // Bls12381G1Msm = 55, + // // Cost of mapping a BLS12-381 Fp field element to a G1 point + // Bls12381MapFpToG1 = 56, + // // Cost of hashing to a BLS12-381 G1 point + // Bls12381HashToG1 = 57, + // // Cost of performing BLS12-381 G2 point addition + // Bls12381G2Add = 58, + // // Cost of performing BLS12-381 G2 scalar multiplication + // Bls12381G2Mul = 59, + // // Cost of performing BLS12-381 G2 multi-scalar multiplication (MSM) + // Bls12381G2Msm = 60, + // // Cost of mapping a BLS12-381 Fp2 field element to a G2 point + // Bls12381MapFp2ToG2 = 61, + // // Cost of hashing to a BLS12-381 G2 point + // Bls12381HashToG2 = 62, + // // Cost of performing BLS12-381 pairing operation + // Bls12381Pairing = 63, + // // Cost of converting a BLS12-381 scalar element from U256 + // Bls12381FrFromU256 = 64, + // // Cost of converting a BLS12-381 scalar element to U256 + // Bls12381FrToU256 = 65, + // // Cost of performing BLS12-381 scalar element addition/subtraction + // Bls12381FrAddSub = 66, + // // Cost of performing BLS12-381 scalar element multiplication + // Bls12381FrMul = 67, + // // Cost of performing BLS12-381 scalar element exponentiation + // Bls12381FrPow = 68, + // // Cost of performing BLS12-381 scalar element inversion + // Bls12381FrInv = 69 + // }; + // + // =========================================================================== + xdr["enum"]("ContractCostType", { + wasmInsnExec: 0, + memAlloc: 1, + memCpy: 2, + memCmp: 3, + dispatchHostFunction: 4, + visitObject: 5, + valSer: 6, + valDeser: 7, + computeSha256Hash: 8, + computeEd25519PubKey: 9, + verifyEd25519Sig: 10, + vmInstantiation: 11, + vmCachedInstantiation: 12, + invokeVmFunction: 13, + computeKeccak256Hash: 14, + decodeEcdsaCurve256Sig: 15, + recoverEcdsaSecp256k1Key: 16, + int256AddSub: 17, + int256Mul: 18, + int256Div: 19, + int256Pow: 20, + int256Shift: 21, + chaCha20DrawBytes: 22, + parseWasmInstructions: 23, + parseWasmFunctions: 24, + parseWasmGlobals: 25, + parseWasmTableEntries: 26, + parseWasmTypes: 27, + parseWasmDataSegments: 28, + parseWasmElemSegments: 29, + parseWasmImports: 30, + parseWasmExports: 31, + parseWasmDataSegmentBytes: 32, + instantiateWasmInstructions: 33, + instantiateWasmFunctions: 34, + instantiateWasmGlobals: 35, + instantiateWasmTableEntries: 36, + instantiateWasmTypes: 37, + instantiateWasmDataSegments: 38, + instantiateWasmElemSegments: 39, + instantiateWasmImports: 40, + instantiateWasmExports: 41, + instantiateWasmDataSegmentBytes: 42, + sec1DecodePointUncompressed: 43, + verifyEcdsaSecp256r1Sig: 44, + bls12381EncodeFp: 45, + bls12381DecodeFp: 46, + bls12381G1CheckPointOnCurve: 47, + bls12381G1CheckPointInSubgroup: 48, + bls12381G2CheckPointOnCurve: 49, + bls12381G2CheckPointInSubgroup: 50, + bls12381G1ProjectiveToAffine: 51, + bls12381G2ProjectiveToAffine: 52, + bls12381G1Add: 53, + bls12381G1Mul: 54, + bls12381G1Msm: 55, + bls12381MapFpToG1: 56, + bls12381HashToG1: 57, + bls12381G2Add: 58, + bls12381G2Mul: 59, + bls12381G2Msm: 60, + bls12381MapFp2ToG2: 61, + bls12381HashToG2: 62, + bls12381Pairing: 63, + bls12381FrFromU256: 64, + bls12381FrToU256: 65, + bls12381FrAddSub: 66, + bls12381FrMul: 67, + bls12381FrPow: 68, + bls12381FrInv: 69 + }); + + // === xdr source ============================================================ + // + // struct ContractCostParamEntry { + // // use `ext` to add more terms (e.g. higher order polynomials) in the future + // ExtensionPoint ext; + // + // int64 constTerm; + // int64 linearTerm; + // }; + // + // =========================================================================== + xdr.struct("ContractCostParamEntry", [["ext", xdr.lookup("ExtensionPoint")], ["constTerm", xdr.lookup("Int64")], ["linearTerm", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct StateArchivalSettings { + // uint32 maxEntryTTL; + // uint32 minTemporaryTTL; + // uint32 minPersistentTTL; + // + // // rent_fee = wfee_rate_average / rent_rate_denominator_for_type + // int64 persistentRentRateDenominator; + // int64 tempRentRateDenominator; + // + // // max number of entries that emit archival meta in a single ledger + // uint32 maxEntriesToArchive; + // + // // Number of snapshots to use when calculating average BucketList size + // uint32 bucketListSizeWindowSampleSize; + // + // // How often to sample the BucketList size for the average, in ledgers + // uint32 bucketListWindowSamplePeriod; + // + // // Maximum number of bytes that we scan for eviction per ledger + // uint32 evictionScanSize; + // + // // Lowest BucketList level to be scanned to evict entries + // uint32 startingEvictionScanLevel; + // }; + // + // =========================================================================== + xdr.struct("StateArchivalSettings", [["maxEntryTtl", xdr.lookup("Uint32")], ["minTemporaryTtl", xdr.lookup("Uint32")], ["minPersistentTtl", xdr.lookup("Uint32")], ["persistentRentRateDenominator", xdr.lookup("Int64")], ["tempRentRateDenominator", xdr.lookup("Int64")], ["maxEntriesToArchive", xdr.lookup("Uint32")], ["bucketListSizeWindowSampleSize", xdr.lookup("Uint32")], ["bucketListWindowSamplePeriod", xdr.lookup("Uint32")], ["evictionScanSize", xdr.lookup("Uint32")], ["startingEvictionScanLevel", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct EvictionIterator { + // uint32 bucketListLevel; + // bool isCurrBucket; + // uint64 bucketFileOffset; + // }; + // + // =========================================================================== + xdr.struct("EvictionIterator", [["bucketListLevel", xdr.lookup("Uint32")], ["isCurrBucket", xdr.bool()], ["bucketFileOffset", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // const CONTRACT_COST_COUNT_LIMIT = 1024; + // + // =========================================================================== + xdr["const"]("CONTRACT_COST_COUNT_LIMIT", 1024); + + // === xdr source ============================================================ + // + // typedef ContractCostParamEntry ContractCostParams; + // + // =========================================================================== + xdr.typedef("ContractCostParams", xdr.varArray(xdr.lookup("ContractCostParamEntry"), xdr.lookup("CONTRACT_COST_COUNT_LIMIT"))); + + // === xdr source ============================================================ + // + // enum ConfigSettingID + // { + // CONFIG_SETTING_CONTRACT_MAX_SIZE_BYTES = 0, + // CONFIG_SETTING_CONTRACT_COMPUTE_V0 = 1, + // CONFIG_SETTING_CONTRACT_LEDGER_COST_V0 = 2, + // CONFIG_SETTING_CONTRACT_HISTORICAL_DATA_V0 = 3, + // CONFIG_SETTING_CONTRACT_EVENTS_V0 = 4, + // CONFIG_SETTING_CONTRACT_BANDWIDTH_V0 = 5, + // CONFIG_SETTING_CONTRACT_COST_PARAMS_CPU_INSTRUCTIONS = 6, + // CONFIG_SETTING_CONTRACT_COST_PARAMS_MEMORY_BYTES = 7, + // CONFIG_SETTING_CONTRACT_DATA_KEY_SIZE_BYTES = 8, + // CONFIG_SETTING_CONTRACT_DATA_ENTRY_SIZE_BYTES = 9, + // CONFIG_SETTING_STATE_ARCHIVAL = 10, + // CONFIG_SETTING_CONTRACT_EXECUTION_LANES = 11, + // CONFIG_SETTING_BUCKETLIST_SIZE_WINDOW = 12, + // CONFIG_SETTING_EVICTION_ITERATOR = 13 + // }; + // + // =========================================================================== + xdr["enum"]("ConfigSettingId", { + configSettingContractMaxSizeBytes: 0, + configSettingContractComputeV0: 1, + configSettingContractLedgerCostV0: 2, + configSettingContractHistoricalDataV0: 3, + configSettingContractEventsV0: 4, + configSettingContractBandwidthV0: 5, + configSettingContractCostParamsCpuInstructions: 6, + configSettingContractCostParamsMemoryBytes: 7, + configSettingContractDataKeySizeBytes: 8, + configSettingContractDataEntrySizeBytes: 9, + configSettingStateArchival: 10, + configSettingContractExecutionLanes: 11, + configSettingBucketlistSizeWindow: 12, + configSettingEvictionIterator: 13 + }); + + // === xdr source ============================================================ + // + // union ConfigSettingEntry switch (ConfigSettingID configSettingID) + // { + // case CONFIG_SETTING_CONTRACT_MAX_SIZE_BYTES: + // uint32 contractMaxSizeBytes; + // case CONFIG_SETTING_CONTRACT_COMPUTE_V0: + // ConfigSettingContractComputeV0 contractCompute; + // case CONFIG_SETTING_CONTRACT_LEDGER_COST_V0: + // ConfigSettingContractLedgerCostV0 contractLedgerCost; + // case CONFIG_SETTING_CONTRACT_HISTORICAL_DATA_V0: + // ConfigSettingContractHistoricalDataV0 contractHistoricalData; + // case CONFIG_SETTING_CONTRACT_EVENTS_V0: + // ConfigSettingContractEventsV0 contractEvents; + // case CONFIG_SETTING_CONTRACT_BANDWIDTH_V0: + // ConfigSettingContractBandwidthV0 contractBandwidth; + // case CONFIG_SETTING_CONTRACT_COST_PARAMS_CPU_INSTRUCTIONS: + // ContractCostParams contractCostParamsCpuInsns; + // case CONFIG_SETTING_CONTRACT_COST_PARAMS_MEMORY_BYTES: + // ContractCostParams contractCostParamsMemBytes; + // case CONFIG_SETTING_CONTRACT_DATA_KEY_SIZE_BYTES: + // uint32 contractDataKeySizeBytes; + // case CONFIG_SETTING_CONTRACT_DATA_ENTRY_SIZE_BYTES: + // uint32 contractDataEntrySizeBytes; + // case CONFIG_SETTING_STATE_ARCHIVAL: + // StateArchivalSettings stateArchivalSettings; + // case CONFIG_SETTING_CONTRACT_EXECUTION_LANES: + // ConfigSettingContractExecutionLanesV0 contractExecutionLanes; + // case CONFIG_SETTING_BUCKETLIST_SIZE_WINDOW: + // uint64 bucketListSizeWindow<>; + // case CONFIG_SETTING_EVICTION_ITERATOR: + // EvictionIterator evictionIterator; + // }; + // + // =========================================================================== + xdr.union("ConfigSettingEntry", { + switchOn: xdr.lookup("ConfigSettingId"), + switchName: "configSettingId", + switches: [["configSettingContractMaxSizeBytes", "contractMaxSizeBytes"], ["configSettingContractComputeV0", "contractCompute"], ["configSettingContractLedgerCostV0", "contractLedgerCost"], ["configSettingContractHistoricalDataV0", "contractHistoricalData"], ["configSettingContractEventsV0", "contractEvents"], ["configSettingContractBandwidthV0", "contractBandwidth"], ["configSettingContractCostParamsCpuInstructions", "contractCostParamsCpuInsns"], ["configSettingContractCostParamsMemoryBytes", "contractCostParamsMemBytes"], ["configSettingContractDataKeySizeBytes", "contractDataKeySizeBytes"], ["configSettingContractDataEntrySizeBytes", "contractDataEntrySizeBytes"], ["configSettingStateArchival", "stateArchivalSettings"], ["configSettingContractExecutionLanes", "contractExecutionLanes"], ["configSettingBucketlistSizeWindow", "bucketListSizeWindow"], ["configSettingEvictionIterator", "evictionIterator"]], + arms: { + contractMaxSizeBytes: xdr.lookup("Uint32"), + contractCompute: xdr.lookup("ConfigSettingContractComputeV0"), + contractLedgerCost: xdr.lookup("ConfigSettingContractLedgerCostV0"), + contractHistoricalData: xdr.lookup("ConfigSettingContractHistoricalDataV0"), + contractEvents: xdr.lookup("ConfigSettingContractEventsV0"), + contractBandwidth: xdr.lookup("ConfigSettingContractBandwidthV0"), + contractCostParamsCpuInsns: xdr.lookup("ContractCostParams"), + contractCostParamsMemBytes: xdr.lookup("ContractCostParams"), + contractDataKeySizeBytes: xdr.lookup("Uint32"), + contractDataEntrySizeBytes: xdr.lookup("Uint32"), + stateArchivalSettings: xdr.lookup("StateArchivalSettings"), + contractExecutionLanes: xdr.lookup("ConfigSettingContractExecutionLanesV0"), + bucketListSizeWindow: xdr.varArray(xdr.lookup("Uint64"), 2147483647), + evictionIterator: xdr.lookup("EvictionIterator") + } + }); +}); +var _default = exports["default"] = types; + +/***/ }), + +/***/ 5578: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LiquidityPoolFeeV18 = void 0; +exports.getLiquidityPoolId = getLiquidityPoolId; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +var _hashing = __webpack_require__(9152); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +// LiquidityPoolFeeV18 is the default liquidity pool fee in protocol v18. It defaults to 30 base points (0.3%). +var LiquidityPoolFeeV18 = exports.LiquidityPoolFeeV18 = 30; + +/** + * getLiquidityPoolId computes the Pool ID for the given assets, fee and pool type. + * + * @see [stellar-core getPoolID](https://github.com/stellar/stellar-core/blob/9f3a48c6a8f1aa77b6043a055d0638661f718080/src/ledger/test/LedgerTxnTests.cpp#L3746-L3751) + * + * @export + * @param {string} liquidityPoolType – A string representing the liquidity pool type. + * @param {object} liquidityPoolParameters – The liquidity pool parameters. + * @param {Asset} liquidityPoolParameters.assetA – The first asset in the Pool, it must respect the rule assetA < assetB. + * @param {Asset} liquidityPoolParameters.assetB – The second asset in the Pool, it must respect the rule assetA < assetB. + * @param {number} liquidityPoolParameters.fee – The liquidity pool fee. For now the only fee supported is `30`. + * + * @return {Buffer} the raw Pool ID buffer, which can be stringfied with `toString('hex')` + */ +function getLiquidityPoolId(liquidityPoolType) { + var liquidityPoolParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (liquidityPoolType !== 'constant_product') { + throw new Error('liquidityPoolType is invalid'); + } + var assetA = liquidityPoolParameters.assetA, + assetB = liquidityPoolParameters.assetB, + fee = liquidityPoolParameters.fee; + if (!assetA || !(assetA instanceof _asset.Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof _asset.Asset)) { + throw new Error('assetB is invalid'); + } + if (!fee || fee !== LiquidityPoolFeeV18) { + throw new Error('fee is invalid'); + } + if (_asset.Asset.compare(assetA, assetB) !== -1) { + throw new Error('Assets are not in lexicographic order'); + } + var lpTypeData = _xdr["default"].LiquidityPoolType.liquidityPoolConstantProduct().toXDR(); + var lpParamsData = new _xdr["default"].LiquidityPoolConstantProductParameters({ + assetA: assetA.toXDRObject(), + assetB: assetB.toXDRObject(), + fee: fee + }).toXDR(); + var payload = Buffer.concat([lpTypeData, lpParamsData]); + return (0, _hashing.hash)(payload); +} + +/***/ }), + +/***/ 9152: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.hash = hash; +var _sha = __webpack_require__(2802); +function hash(data) { + var hasher = new _sha.sha256(); + hasher.update(data, 'utf8'); + return hasher.digest(); +} + +/***/ }), + +/***/ 356: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _exportNames = { + xdr: true, + cereal: true, + hash: true, + sign: true, + verify: true, + FastSigning: true, + getLiquidityPoolId: true, + LiquidityPoolFeeV18: true, + Keypair: true, + UnsignedHyper: true, + Hyper: true, + TransactionBase: true, + Transaction: true, + FeeBumpTransaction: true, + TransactionBuilder: true, + TimeoutInfinite: true, + BASE_FEE: true, + Asset: true, + LiquidityPoolAsset: true, + LiquidityPoolId: true, + Operation: true, + AuthRequiredFlag: true, + AuthRevocableFlag: true, + AuthImmutableFlag: true, + AuthClawbackEnabledFlag: true, + Account: true, + MuxedAccount: true, + Claimant: true, + Networks: true, + StrKey: true, + SignerKey: true, + Soroban: true, + decodeAddressToMuxedAccount: true, + encodeMuxedAccountToAddress: true, + extractBaseAddress: true, + encodeMuxedAccount: true, + Contract: true, + Address: true +}; +Object.defineProperty(exports, "Account", ({ + enumerable: true, + get: function get() { + return _account.Account; + } +})); +Object.defineProperty(exports, "Address", ({ + enumerable: true, + get: function get() { + return _address.Address; + } +})); +Object.defineProperty(exports, "Asset", ({ + enumerable: true, + get: function get() { + return _asset.Asset; + } +})); +Object.defineProperty(exports, "AuthClawbackEnabledFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthClawbackEnabledFlag; + } +})); +Object.defineProperty(exports, "AuthImmutableFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthImmutableFlag; + } +})); +Object.defineProperty(exports, "AuthRequiredFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthRequiredFlag; + } +})); +Object.defineProperty(exports, "AuthRevocableFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthRevocableFlag; + } +})); +Object.defineProperty(exports, "BASE_FEE", ({ + enumerable: true, + get: function get() { + return _transaction_builder.BASE_FEE; + } +})); +Object.defineProperty(exports, "Claimant", ({ + enumerable: true, + get: function get() { + return _claimant.Claimant; + } +})); +Object.defineProperty(exports, "Contract", ({ + enumerable: true, + get: function get() { + return _contract.Contract; + } +})); +Object.defineProperty(exports, "FastSigning", ({ + enumerable: true, + get: function get() { + return _signing.FastSigning; + } +})); +Object.defineProperty(exports, "FeeBumpTransaction", ({ + enumerable: true, + get: function get() { + return _fee_bump_transaction.FeeBumpTransaction; + } +})); +Object.defineProperty(exports, "Hyper", ({ + enumerable: true, + get: function get() { + return _jsXdr.Hyper; + } +})); +Object.defineProperty(exports, "Keypair", ({ + enumerable: true, + get: function get() { + return _keypair.Keypair; + } +})); +Object.defineProperty(exports, "LiquidityPoolAsset", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_asset.LiquidityPoolAsset; + } +})); +Object.defineProperty(exports, "LiquidityPoolFeeV18", ({ + enumerable: true, + get: function get() { + return _get_liquidity_pool_id.LiquidityPoolFeeV18; + } +})); +Object.defineProperty(exports, "LiquidityPoolId", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_id.LiquidityPoolId; + } +})); +Object.defineProperty(exports, "MuxedAccount", ({ + enumerable: true, + get: function get() { + return _muxed_account.MuxedAccount; + } +})); +Object.defineProperty(exports, "Networks", ({ + enumerable: true, + get: function get() { + return _network.Networks; + } +})); +Object.defineProperty(exports, "Operation", ({ + enumerable: true, + get: function get() { + return _operation.Operation; + } +})); +Object.defineProperty(exports, "SignerKey", ({ + enumerable: true, + get: function get() { + return _signerkey.SignerKey; + } +})); +Object.defineProperty(exports, "Soroban", ({ + enumerable: true, + get: function get() { + return _soroban.Soroban; + } +})); +Object.defineProperty(exports, "StrKey", ({ + enumerable: true, + get: function get() { + return _strkey.StrKey; + } +})); +Object.defineProperty(exports, "TimeoutInfinite", ({ + enumerable: true, + get: function get() { + return _transaction_builder.TimeoutInfinite; + } +})); +Object.defineProperty(exports, "Transaction", ({ + enumerable: true, + get: function get() { + return _transaction.Transaction; + } +})); +Object.defineProperty(exports, "TransactionBase", ({ + enumerable: true, + get: function get() { + return _transaction_base.TransactionBase; + } +})); +Object.defineProperty(exports, "TransactionBuilder", ({ + enumerable: true, + get: function get() { + return _transaction_builder.TransactionBuilder; + } +})); +Object.defineProperty(exports, "UnsignedHyper", ({ + enumerable: true, + get: function get() { + return _jsXdr.UnsignedHyper; + } +})); +Object.defineProperty(exports, "cereal", ({ + enumerable: true, + get: function get() { + return _jsxdr["default"]; + } +})); +Object.defineProperty(exports, "decodeAddressToMuxedAccount", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.decodeAddressToMuxedAccount; + } +})); +exports["default"] = void 0; +Object.defineProperty(exports, "encodeMuxedAccount", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.encodeMuxedAccount; + } +})); +Object.defineProperty(exports, "encodeMuxedAccountToAddress", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.encodeMuxedAccountToAddress; + } +})); +Object.defineProperty(exports, "extractBaseAddress", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.extractBaseAddress; + } +})); +Object.defineProperty(exports, "getLiquidityPoolId", ({ + enumerable: true, + get: function get() { + return _get_liquidity_pool_id.getLiquidityPoolId; + } +})); +Object.defineProperty(exports, "hash", ({ + enumerable: true, + get: function get() { + return _hashing.hash; + } +})); +Object.defineProperty(exports, "sign", ({ + enumerable: true, + get: function get() { + return _signing.sign; + } +})); +Object.defineProperty(exports, "verify", ({ + enumerable: true, + get: function get() { + return _signing.verify; + } +})); +Object.defineProperty(exports, "xdr", ({ + enumerable: true, + get: function get() { + return _xdr["default"]; + } +})); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _jsxdr = _interopRequireDefault(__webpack_require__(3335)); +var _hashing = __webpack_require__(9152); +var _signing = __webpack_require__(15); +var _get_liquidity_pool_id = __webpack_require__(5578); +var _keypair = __webpack_require__(6691); +var _jsXdr = __webpack_require__(3740); +var _transaction_base = __webpack_require__(3758); +var _transaction = __webpack_require__(380); +var _fee_bump_transaction = __webpack_require__(9260); +var _transaction_builder = __webpack_require__(6396); +var _asset = __webpack_require__(1764); +var _liquidity_pool_asset = __webpack_require__(2262); +var _liquidity_pool_id = __webpack_require__(9353); +var _operation = __webpack_require__(7237); +var _memo = __webpack_require__(4172); +Object.keys(_memo).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _memo[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _memo[key]; + } + }); +}); +var _account = __webpack_require__(2135); +var _muxed_account = __webpack_require__(2243); +var _claimant = __webpack_require__(1387); +var _network = __webpack_require__(6202); +var _strkey = __webpack_require__(7120); +var _signerkey = __webpack_require__(225); +var _soroban = __webpack_require__(4062); +var _decode_encode_muxed_account = __webpack_require__(6160); +var _contract = __webpack_require__(7452); +var _address = __webpack_require__(1180); +var _numbers = __webpack_require__(8549); +Object.keys(_numbers).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _numbers[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _numbers[key]; + } + }); +}); +var _scval = __webpack_require__(7177); +Object.keys(_scval).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _scval[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _scval[key]; + } + }); +}); +var _events = __webpack_require__(3919); +Object.keys(_events).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _events[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _events[key]; + } + }); +}); +var _sorobandata_builder = __webpack_require__(4842); +Object.keys(_sorobandata_builder).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _sorobandata_builder[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _sorobandata_builder[key]; + } + }); +}); +var _auth = __webpack_require__(5328); +Object.keys(_auth).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _auth[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _auth[key]; + } + }); +}); +var _invocation = __webpack_require__(3564); +Object.keys(_invocation).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _invocation[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _invocation[key]; + } + }); +}); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/* eslint-disable import/no-import-module-exports */ +// +// Soroban +// +var _default = exports["default"] = module.exports; + +/***/ }), + +/***/ 3564: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.buildInvocationTree = buildInvocationTree; +exports.walkInvocationTree = walkInvocationTree; +var _asset = __webpack_require__(1764); +var _address = __webpack_require__(1180); +var _scval = __webpack_require__(7177); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * @typedef CreateInvocation + * + * @prop {'wasm'|'sac'} type a type indicating if this creation was a custom + * contract or a wrapping of an existing Stellar asset + * @prop {string} [token] when `type=='sac'`, the canonical {@link Asset} that + * is being wrapped by this Stellar Asset Contract + * @prop {object} [wasm] when `type=='wasm'`, add'l creation parameters + * + * @prop {string} wasm.hash hex hash of WASM bytecode backing this contract + * @prop {string} wasm.address contract address of this deployment + * @prop {string} wasm.salt hex salt that the user consumed when creating + * this contract (encoded in the resulting address) + * @prop {any[]} [wasm.constructorArgs] a list of natively-represented values + * (see {@link scValToNative}) that are passed to the constructor when + * creating this contract + */ + +/** + * @typedef ExecuteInvocation + * + * @prop {string} source the strkey of the contract (C...) being invoked + * @prop {string} function the name of the function being invoked + * @prop {any[]} args the natively-represented parameters to the function + * invocation (see {@link scValToNative} for rules on how they're + * represented a JS types) + */ + +/** + * @typedef InvocationTree + * @prop {'execute' | 'create'} type the type of invocation occurring, either + * contract creation or host function execution + * @prop {CreateInvocation | ExecuteInvocation} args the parameters to the + * invocation, depending on the type + * @prop {InvocationTree[]} invocations any sub-invocations that (may) occur + * as a result of this invocation (i.e. a tree of call stacks) + */ + +/** + * Turns a raw invocation tree into a human-readable format. + * + * This is designed to make the invocation tree easier to understand in order to + * inform users about the side-effects of their contract calls. This will help + * make informed decisions about whether or not a particular invocation will + * result in what you expect it to. + * + * @param {xdr.SorobanAuthorizedInvocation} root the raw XDR of the invocation, + * likely acquired from transaction simulation. this is either from the + * {@link Operation.invokeHostFunction} itself (the `func` field), or from + * the authorization entries ({@link xdr.SorobanAuthorizationEntry}, the + * `rootInvocation` field) + * + * @returns {InvocationTree} a human-readable version of the invocation tree + * + * @example + * Here, we show a browser modal after simulating an arbitrary transaction, + * `tx`, which we assume has an `Operation.invokeHostFunction` inside of it: + * + * ```typescript + * import { Server, buildInvocationTree } from '@stellar/stellar-sdk'; + * + * const s = new Server("fill in accordingly"); + * + * s.simulateTransaction(tx).then( + * (resp: SorobanRpc.SimulateTransactionResponse) => { + * if (SorobanRpc.isSuccessfulSim(resp) && ) { + * // bold assumption: there's a valid result with an auth entry + * alert( + * "You are authorizing the following invocation:\n" + + * JSON.stringify( + * buildInvocationTree(resp.result!.auth[0].rootInvocation()), + * null, + * 2 + * ) + * ); + * } + * } + * ); + * ``` + */ +function buildInvocationTree(root) { + var fn = root["function"](); + + /** @type {InvocationTree} */ + var output = {}; + + /** @type {xdr.CreateContractArgs|xdr.CreateContractArgsV2|xdr.InvokeContractArgs} */ + var inner = fn.value(); + switch (fn["switch"]().value) { + // sorobanAuthorizedFunctionTypeContractFn + case 0: + output.type = 'execute'; + output.args = { + source: _address.Address.fromScAddress(inner.contractAddress()).toString(), + "function": inner.functionName(), + args: inner.args().map(function (arg) { + return (0, _scval.scValToNative)(arg); + }) + }; + break; + + // sorobanAuthorizedFunctionTypeCreateContractHostFn + // sorobanAuthorizedFunctionTypeCreateContractV2HostFn + case 1: // fallthrough: just no ctor args in V1 + case 2: + { + var createV2 = fn["switch"]().value === 2; + output.type = 'create'; + output.args = {}; + + // If the executable is a WASM, the preimage MUST be an address. If it's a + // token, the preimage MUST be an asset. This is a cheeky way to check + // that, because wasm=0, token=1 and address=0, asset=1 in the XDR switch + // values. + // + // The first part may not be true in V2, but we'd need to update this code + // anyway so it can still be an error. + var _ref = [inner.executable(), inner.contractIdPreimage()], + exec = _ref[0], + preimage = _ref[1]; + if (!!exec["switch"]().value !== !!preimage["switch"]().value) { + throw new Error("creation function appears invalid: ".concat(JSON.stringify(inner), " (should be wasm+address or token+asset)")); + } + switch (exec["switch"]().value) { + // contractExecutableWasm + case 0: + { + /** @type {xdr.ContractIdPreimageFromAddress} */ + var details = preimage.fromAddress(); + output.args.type = 'wasm'; + output.args.wasm = _objectSpread({ + salt: details.salt().toString('hex'), + hash: exec.wasmHash().toString('hex'), + address: _address.Address.fromScAddress(details.address()).toString() + }, createV2 && { + constructorArgs: inner.constructorArgs().map(function (arg) { + return (0, _scval.scValToNative)(arg); + }) + }); + break; + } + + // contractExecutableStellarAsset + case 1: + output.args.type = 'sac'; + output.args.asset = _asset.Asset.fromOperation(preimage.fromAsset()).toString(); + break; + default: + throw new Error("unknown creation type: ".concat(JSON.stringify(exec))); + } + break; + } + default: + throw new Error("unknown invocation type (".concat(fn["switch"](), "): ").concat(JSON.stringify(fn))); + } + output.invocations = root.subInvocations().map(function (i) { + return buildInvocationTree(i); + }); + return output; +} + +/** + * @callback InvocationWalker + * + * @param {xdr.SorobanAuthorizedInvocation} node the currently explored node + * @param {number} depth the depth of the tree this node is occurring at (the + * root starts at a depth of 1) + * @param {xdr.SorobanAuthorizedInvocation} [parent] this `node`s parent node, + * if any (i.e. this doesn't exist at the root) + * + * @returns {boolean|null|void} returning exactly `false` is a hint to stop + * exploring, other values are ignored + */ + +/** + * Executes a callback function on each node in the tree until stopped. + * + * Nodes are walked in a depth-first order. Returning `false` from the callback + * stops further depth exploration at that node, but it does not stop the walk + * in a "global" view. + * + * @param {xdr.SorobanAuthorizedInvocation} root the tree to explore + * @param {InvocationWalker} callback the callback to execute for each node + * @returns {void} + */ +function walkInvocationTree(root, callback) { + walkHelper(root, 1, callback); +} +function walkHelper(node, depth, callback, parent) { + if (callback(node, depth, parent) === false /* allow void rv */) { + return; + } + node.subInvocations().forEach(function (i) { + return walkHelper(i, depth + 1, callback, node); + }); +} + +/***/ }), + +/***/ 3335: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _jsXdr = __webpack_require__(3740); +var cereal = { + XdrWriter: _jsXdr.XdrWriter, + XdrReader: _jsXdr.XdrReader +}; +var _default = exports["default"] = cereal; + +/***/ }), + +/***/ 6691: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Keypair = void 0; +var _tweetnacl = _interopRequireDefault(__webpack_require__(4940)); +var _signing = __webpack_require__(15); +var _strkey = __webpack_require__(7120); +var _hashing = __webpack_require__(9152); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": ["^"]}] */ +/** + * `Keypair` represents public (and secret) keys of the account. + * + * Currently `Keypair` only supports ed25519 but in a future this class can be abstraction layer for other + * public-key signature systems. + * + * Use more convenient methods to create `Keypair` object: + * * `{@link Keypair.fromPublicKey}` + * * `{@link Keypair.fromSecret}` + * * `{@link Keypair.random}` + * + * @constructor + * @param {object} keys At least one of keys must be provided. + * @param {string} keys.type Public-key signature system name. (currently only `ed25519` keys are supported) + * @param {Buffer} [keys.publicKey] Raw public key + * @param {Buffer} [keys.secretKey] Raw secret key (32-byte secret seed in ed25519`) + */ +var Keypair = exports.Keypair = /*#__PURE__*/function () { + function Keypair(keys) { + _classCallCheck(this, Keypair); + if (keys.type !== 'ed25519') { + throw new Error('Invalid keys type'); + } + this.type = keys.type; + if (keys.secretKey) { + keys.secretKey = Buffer.from(keys.secretKey); + if (keys.secretKey.length !== 32) { + throw new Error('secretKey length is invalid'); + } + this._secretSeed = keys.secretKey; + this._publicKey = (0, _signing.generate)(keys.secretKey); + this._secretKey = Buffer.concat([keys.secretKey, this._publicKey]); + if (keys.publicKey && !this._publicKey.equals(Buffer.from(keys.publicKey))) { + throw new Error('secretKey does not match publicKey'); + } + } else { + this._publicKey = Buffer.from(keys.publicKey); + if (this._publicKey.length !== 32) { + throw new Error('publicKey length is invalid'); + } + } + } + + /** + * Creates a new `Keypair` instance from secret. This can either be secret key or secret seed depending + * on underlying public-key signature system. Currently `Keypair` only supports ed25519. + * @param {string} secret secret key (ex. `SDAKFNYEIAORZKKCYRILFQKLLOCNPL5SWJ3YY5NM3ZH6GJSZGXHZEPQS`) + * @returns {Keypair} + */ + return _createClass(Keypair, [{ + key: "xdrAccountId", + value: function xdrAccountId() { + return new _xdr["default"].AccountId.publicKeyTypeEd25519(this._publicKey); + } + }, { + key: "xdrPublicKey", + value: function xdrPublicKey() { + return new _xdr["default"].PublicKey.publicKeyTypeEd25519(this._publicKey); + } + + /** + * Creates a {@link xdr.MuxedAccount} object from the public key. + * + * You will get a different type of muxed account depending on whether or not + * you pass an ID. + * + * @param {string} [id] - stringified integer indicating the underlying muxed + * ID of the new account object + * + * @return {xdr.MuxedAccount} + */ + }, { + key: "xdrMuxedAccount", + value: function xdrMuxedAccount(id) { + if (typeof id !== 'undefined') { + if (typeof id !== 'string') { + throw new TypeError("expected string for ID, got ".concat(_typeof(id))); + } + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromString(id), + ed25519: this._publicKey + })); + } + return new _xdr["default"].MuxedAccount.keyTypeEd25519(this._publicKey); + } + + /** + * Returns raw public key + * @returns {Buffer} + */ + }, { + key: "rawPublicKey", + value: function rawPublicKey() { + return this._publicKey; + } + }, { + key: "signatureHint", + value: function signatureHint() { + var a = this.xdrAccountId().toXDR(); + return a.slice(a.length - 4); + } + + /** + * Returns public key associated with this `Keypair` object. + * @returns {string} + */ + }, { + key: "publicKey", + value: function publicKey() { + return _strkey.StrKey.encodeEd25519PublicKey(this._publicKey); + } + + /** + * Returns secret key associated with this `Keypair` object + * @returns {string} + */ + }, { + key: "secret", + value: function secret() { + if (!this._secretSeed) { + throw new Error('no secret key available'); + } + if (this.type === 'ed25519') { + return _strkey.StrKey.encodeEd25519SecretSeed(this._secretSeed); + } + throw new Error('Invalid Keypair type'); + } + + /** + * Returns raw secret key. + * @returns {Buffer} + */ + }, { + key: "rawSecretKey", + value: function rawSecretKey() { + return this._secretSeed; + } + + /** + * Returns `true` if this `Keypair` object contains secret key and can sign. + * @returns {boolean} + */ + }, { + key: "canSign", + value: function canSign() { + return !!this._secretKey; + } + + /** + * Signs data. + * @param {Buffer} data Data to sign + * @returns {Buffer} + */ + }, { + key: "sign", + value: function sign(data) { + if (!this.canSign()) { + throw new Error('cannot sign: no secret key available'); + } + return (0, _signing.sign)(data, this._secretKey); + } + + /** + * Verifies if `signature` for `data` is valid. + * @param {Buffer} data Signed data + * @param {Buffer} signature Signature + * @returns {boolean} + */ + }, { + key: "verify", + value: function verify(data, signature) { + return (0, _signing.verify)(data, signature, this._publicKey); + } + + /** + * Returns the decorated signature (hint+sig) for arbitrary data. + * + * @param {Buffer} data arbitrary data to sign + * @return {xdr.DecoratedSignature} the raw signature structure which can be + * added directly to a transaction envelope + * + * @see TransactionBase.addDecoratedSignature + */ + }, { + key: "signDecorated", + value: function signDecorated(data) { + var signature = this.sign(data); + var hint = this.signatureHint(); + return new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signature + }); + } + + /** + * Returns the raw decorated signature (hint+sig) for a signed payload signer. + * + * The hint is defined as the last 4 bytes of the signer key XORed with last + * 4 bytes of the payload (zero-left-padded if necessary). + * + * @param {Buffer} data data to both sign and treat as the payload + * @return {xdr.DecoratedSignature} + * + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0040.md#signature-hint + * @see TransactionBase.addDecoratedSignature + */ + }, { + key: "signPayloadDecorated", + value: function signPayloadDecorated(data) { + var signature = this.sign(data); + var keyHint = this.signatureHint(); + var hint = Buffer.from(data.slice(-4)); + if (hint.length < 4) { + // append zeroes as needed + hint = Buffer.concat([hint, Buffer.alloc(4 - data.length, 0)]); + } + return new _xdr["default"].DecoratedSignature({ + hint: hint.map(function (_byte, i) { + return _byte ^ keyHint[i]; + }), + signature: signature + }); + } + }], [{ + key: "fromSecret", + value: function fromSecret(secret) { + var rawSecret = _strkey.StrKey.decodeEd25519SecretSeed(secret); + return this.fromRawEd25519Seed(rawSecret); + } + + /** + * Creates a new `Keypair` object from ed25519 secret key seed raw bytes. + * + * @param {Buffer} rawSeed Raw 32-byte ed25519 secret key seed + * @returns {Keypair} + */ + }, { + key: "fromRawEd25519Seed", + value: function fromRawEd25519Seed(rawSeed) { + return new this({ + type: 'ed25519', + secretKey: rawSeed + }); + } + + /** + * Returns `Keypair` object representing network master key. + * @param {string} networkPassphrase passphrase of the target stellar network (e.g. "Public Global Stellar Network ; September 2015"). + * @returns {Keypair} + */ + }, { + key: "master", + value: function master(networkPassphrase) { + if (!networkPassphrase) { + throw new Error('No network selected. Please pass a network argument, e.g. `Keypair.master(Networks.PUBLIC)`.'); + } + return this.fromRawEd25519Seed((0, _hashing.hash)(networkPassphrase)); + } + + /** + * Creates a new `Keypair` object from public key. + * @param {string} publicKey public key (ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`) + * @returns {Keypair} + */ + }, { + key: "fromPublicKey", + value: function fromPublicKey(publicKey) { + publicKey = _strkey.StrKey.decodeEd25519PublicKey(publicKey); + if (publicKey.length !== 32) { + throw new Error('Invalid Stellar public key'); + } + return new this({ + type: 'ed25519', + publicKey: publicKey + }); + } + + /** + * Create a random `Keypair` object. + * @returns {Keypair} + */ + }, { + key: "random", + value: function random() { + var secret = _tweetnacl["default"].randomBytes(32); + return this.fromRawEd25519Seed(secret); + } + }]); +}(); + +/***/ }), + +/***/ 2262: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LiquidityPoolAsset = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +var _get_liquidity_pool_id = __webpack_require__(5578); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * LiquidityPoolAsset class represents a liquidity pool trustline change. + * + * @constructor + * @param {Asset} assetA – The first asset in the Pool, it must respect the rule assetA < assetB. See {@link Asset.compare} for more details on how assets are sorted. + * @param {Asset} assetB – The second asset in the Pool, it must respect the rule assetA < assetB. See {@link Asset.compare} for more details on how assets are sorted. + * @param {number} fee – The liquidity pool fee. For now the only fee supported is `30`. + */ +var LiquidityPoolAsset = exports.LiquidityPoolAsset = /*#__PURE__*/function () { + function LiquidityPoolAsset(assetA, assetB, fee) { + _classCallCheck(this, LiquidityPoolAsset); + if (!assetA || !(assetA instanceof _asset.Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof _asset.Asset)) { + throw new Error('assetB is invalid'); + } + if (_asset.Asset.compare(assetA, assetB) !== -1) { + throw new Error('Assets are not in lexicographic order'); + } + if (!fee || fee !== _get_liquidity_pool_id.LiquidityPoolFeeV18) { + throw new Error('fee is invalid'); + } + this.assetA = assetA; + this.assetB = assetB; + this.fee = fee; + } + + /** + * Returns a liquidity pool asset object from its XDR ChangeTrustAsset object + * representation. + * @param {xdr.ChangeTrustAsset} ctAssetXdr - The asset XDR object. + * @returns {LiquidityPoolAsset} + */ + return _createClass(LiquidityPoolAsset, [{ + key: "toXDRObject", + value: + /** + * Returns the `xdr.ChangeTrustAsset` object for this liquidity pool asset. + * + * Note: To convert from an {@link Asset `Asset`} to `xdr.ChangeTrustAsset` + * please refer to the + * {@link Asset.toChangeTrustXDRObject `Asset.toChangeTrustXDRObject`} method. + * + * @returns {xdr.ChangeTrustAsset} XDR ChangeTrustAsset object. + */ + function toXDRObject() { + var lpConstantProductParamsXdr = new _xdr["default"].LiquidityPoolConstantProductParameters({ + assetA: this.assetA.toXDRObject(), + assetB: this.assetB.toXDRObject(), + fee: this.fee + }); + var lpParamsXdr = new _xdr["default"].LiquidityPoolParameters('liquidityPoolConstantProduct', lpConstantProductParamsXdr); + return new _xdr["default"].ChangeTrustAsset('assetTypePoolShare', lpParamsXdr); + } + + /** + * @returns {LiquidityPoolParameters} Liquidity pool parameters. + */ + }, { + key: "getLiquidityPoolParameters", + value: function getLiquidityPoolParameters() { + return _objectSpread(_objectSpread({}, this), {}, { + assetA: this.assetA, + assetB: this.assetB, + fee: this.fee + }); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {AssetType.liquidityPoolShares} asset type. Can only be `liquidity_pool_shares`. + */ + }, { + key: "getAssetType", + value: function getAssetType() { + return 'liquidity_pool_shares'; + } + + /** + * @param {LiquidityPoolAsset} other the LiquidityPoolAsset to compare + * @returns {boolean} `true` if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(other) { + return this.assetA.equals(other.assetA) && this.assetB.equals(other.assetB) && this.fee === other.fee; + } + }, { + key: "toString", + value: function toString() { + var poolId = (0, _get_liquidity_pool_id.getLiquidityPoolId)('constant_product', this.getLiquidityPoolParameters()).toString('hex'); + return "liquidity_pool:".concat(poolId); + } + }], [{ + key: "fromOperation", + value: function fromOperation(ctAssetXdr) { + var assetType = ctAssetXdr["switch"](); + if (assetType === _xdr["default"].AssetType.assetTypePoolShare()) { + var liquidityPoolParameters = ctAssetXdr.liquidityPool().constantProduct(); + return new this(_asset.Asset.fromOperation(liquidityPoolParameters.assetA()), _asset.Asset.fromOperation(liquidityPoolParameters.assetB()), liquidityPoolParameters.fee()); + } + throw new Error("Invalid asset type: ".concat(assetType.name)); + } + }]); +}(); + +/***/ }), + +/***/ 9353: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LiquidityPoolId = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * LiquidityPoolId class represents the asset referenced by a trustline to a + * liquidity pool. + * + * @constructor + * @param {string} liquidityPoolId - The ID of the liquidity pool in string 'hex'. + */ +var LiquidityPoolId = exports.LiquidityPoolId = /*#__PURE__*/function () { + function LiquidityPoolId(liquidityPoolId) { + _classCallCheck(this, LiquidityPoolId); + if (!liquidityPoolId) { + throw new Error('liquidityPoolId cannot be empty'); + } + if (!/^[a-f0-9]{64}$/.test(liquidityPoolId)) { + throw new Error('Liquidity pool ID is not a valid hash'); + } + this.liquidityPoolId = liquidityPoolId; + } + + /** + * Returns a liquidity pool ID object from its xdr.TrustLineAsset representation. + * @param {xdr.TrustLineAsset} tlAssetXdr - The asset XDR object. + * @returns {LiquidityPoolId} + */ + return _createClass(LiquidityPoolId, [{ + key: "toXDRObject", + value: + /** + * Returns the `xdr.TrustLineAsset` object for this liquidity pool ID. + * + * Note: To convert from {@link Asset `Asset`} to `xdr.TrustLineAsset` please + * refer to the + * {@link Asset.toTrustLineXDRObject `Asset.toTrustLineXDRObject`} method. + * + * @returns {xdr.TrustLineAsset} XDR LiquidityPoolId object + */ + function toXDRObject() { + var xdrPoolId = _xdr["default"].PoolId.fromXDR(this.liquidityPoolId, 'hex'); + return new _xdr["default"].TrustLineAsset('assetTypePoolShare', xdrPoolId); + } + + /** + * @returns {string} Liquidity pool ID. + */ + }, { + key: "getLiquidityPoolId", + value: function getLiquidityPoolId() { + return String(this.liquidityPoolId); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {AssetType.liquidityPoolShares} asset type. Can only be `liquidity_pool_shares`. + */ + }, { + key: "getAssetType", + value: function getAssetType() { + return 'liquidity_pool_shares'; + } + + /** + * @param {LiquidityPoolId} asset LiquidityPoolId to compare. + * @returns {boolean} `true` if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(asset) { + return this.liquidityPoolId === asset.getLiquidityPoolId(); + } + }, { + key: "toString", + value: function toString() { + return "liquidity_pool:".concat(this.liquidityPoolId); + } + }], [{ + key: "fromOperation", + value: function fromOperation(tlAssetXdr) { + var assetType = tlAssetXdr["switch"](); + if (assetType === _xdr["default"].AssetType.assetTypePoolShare()) { + var liquidityPoolId = tlAssetXdr.liquidityPoolId().toString('hex'); + return new this(liquidityPoolId); + } + throw new Error("Invalid asset type: ".concat(assetType.name)); + } + }]); +}(); + +/***/ }), + +/***/ 4172: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.MemoText = exports.MemoReturn = exports.MemoNone = exports.MemoID = exports.MemoHash = exports.Memo = void 0; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Type of {@link Memo}. + */ +var MemoNone = exports.MemoNone = 'none'; +/** + * Type of {@link Memo}. + */ +var MemoID = exports.MemoID = 'id'; +/** + * Type of {@link Memo}. + */ +var MemoText = exports.MemoText = 'text'; +/** + * Type of {@link Memo}. + */ +var MemoHash = exports.MemoHash = 'hash'; +/** + * Type of {@link Memo}. + */ +var MemoReturn = exports.MemoReturn = 'return'; + +/** + * `Memo` represents memos attached to transactions. + * + * @param {string} type - `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn` + * @param {*} value - `string` for `MemoID`, `MemoText`, buffer of hex string for `MemoHash` or `MemoReturn` + * @see [Transactions concept](https://developers.stellar.org/docs/glossary/transactions/) + * @class Memo + */ +var Memo = exports.Memo = /*#__PURE__*/function () { + function Memo(type) { + var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + _classCallCheck(this, Memo); + this._type = type; + this._value = value; + switch (this._type) { + case MemoNone: + break; + case MemoID: + Memo._validateIdValue(value); + break; + case MemoText: + Memo._validateTextValue(value); + break; + case MemoHash: + case MemoReturn: + Memo._validateHashValue(value); + // We want MemoHash and MemoReturn to have Buffer as a value + if (typeof value === 'string') { + this._value = Buffer.from(value, 'hex'); + } + break; + default: + throw new Error('Invalid memo type'); + } + } + + /** + * Contains memo type: `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn` + */ + return _createClass(Memo, [{ + key: "type", + get: function get() { + return this._type; + }, + set: function set(type) { + throw new Error('Memo is immutable'); + } + + /** + * Contains memo value: + * * `null` for `MemoNone`, + * * `string` for `MemoID`, + * * `Buffer` for `MemoText` after decoding using `fromXDRObject`, original value otherwise, + * * `Buffer` for `MemoHash`, `MemoReturn`. + */ + }, { + key: "value", + get: function get() { + switch (this._type) { + case MemoNone: + return null; + case MemoID: + case MemoText: + return this._value; + case MemoHash: + case MemoReturn: + return Buffer.from(this._value); + default: + throw new Error('Invalid memo type'); + } + }, + set: function set(value) { + throw new Error('Memo is immutable'); + } + }, { + key: "toXDRObject", + value: + /** + * Returns XDR memo object. + * @returns {xdr.Memo} + */ + function toXDRObject() { + switch (this._type) { + case MemoNone: + return _xdr["default"].Memo.memoNone(); + case MemoID: + return _xdr["default"].Memo.memoId(_jsXdr.UnsignedHyper.fromString(this._value)); + case MemoText: + return _xdr["default"].Memo.memoText(this._value); + case MemoHash: + return _xdr["default"].Memo.memoHash(this._value); + case MemoReturn: + return _xdr["default"].Memo.memoReturn(this._value); + default: + return null; + } + } + + /** + * Returns {@link Memo} from XDR memo object. + * @param {xdr.Memo} object XDR memo object + * @returns {Memo} + */ + }], [{ + key: "_validateIdValue", + value: function _validateIdValue(value) { + var error = new Error("Expects a int64 as a string. Got ".concat(value)); + if (typeof value !== 'string') { + throw error; + } + var number; + try { + number = new _bignumber["default"](value); + } catch (e) { + throw error; + } + + // Infinity + if (!number.isFinite()) { + throw error; + } + + // NaN + if (number.isNaN()) { + throw error; + } + } + }, { + key: "_validateTextValue", + value: function _validateTextValue(value) { + if (!_xdr["default"].Memo.armTypeForArm('text').isValid(value)) { + throw new Error('Expects string, array or buffer, max 28 bytes'); + } + } + }, { + key: "_validateHashValue", + value: function _validateHashValue(value) { + var error = new Error("Expects a 32 byte hash value or hex encoded string. Got ".concat(value)); + if (value === null || typeof value === 'undefined') { + throw error; + } + var valueBuffer; + if (typeof value === 'string') { + if (!/^[0-9A-Fa-f]{64}$/g.test(value)) { + throw error; + } + valueBuffer = Buffer.from(value, 'hex'); + } else if (Buffer.isBuffer(value)) { + valueBuffer = Buffer.from(value); + } else { + throw error; + } + if (!valueBuffer.length || valueBuffer.length !== 32) { + throw error; + } + } + + /** + * Returns an empty memo (`MemoNone`). + * @returns {Memo} + */ + }, { + key: "none", + value: function none() { + return new Memo(MemoNone); + } + + /** + * Creates and returns a `MemoText` memo. + * @param {string} text - memo text + * @returns {Memo} + */ + }, { + key: "text", + value: function text(_text) { + return new Memo(MemoText, _text); + } + + /** + * Creates and returns a `MemoID` memo. + * @param {string} id - 64-bit number represented as a string + * @returns {Memo} + */ + }, { + key: "id", + value: function id(_id) { + return new Memo(MemoID, _id); + } + + /** + * Creates and returns a `MemoHash` memo. + * @param {array|string} hash - 32 byte hash or hex encoded string + * @returns {Memo} + */ + }, { + key: "hash", + value: function hash(_hash) { + return new Memo(MemoHash, _hash); + } + + /** + * Creates and returns a `MemoReturn` memo. + * @param {array|string} hash - 32 byte hash or hex encoded string + * @returns {Memo} + */ + }, { + key: "return", + value: function _return(hash) { + return new Memo(MemoReturn, hash); + } + }, { + key: "fromXDRObject", + value: function fromXDRObject(object) { + switch (object.arm()) { + case 'id': + return Memo.id(object.value().toString()); + case 'text': + return Memo.text(object.value()); + case 'hash': + return Memo.hash(object.value()); + case 'retHash': + return Memo["return"](object.value()); + default: + break; + } + if (typeof object.value() === 'undefined') { + return Memo.none(); + } + throw new Error('Unknown type'); + } + }]); +}(); + +/***/ }), + +/***/ 2243: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.MuxedAccount = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _account = __webpack_require__(2135); +var _strkey = __webpack_require__(7120); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Represents a muxed account for transactions and operations. + * + * A muxed (or *multiplexed*) account (defined rigorously in + * [CAP-27](https://stellar.org/protocol/cap-27) and briefly in + * [SEP-23](https://stellar.org/protocol/sep-23)) is one that resolves a single + * Stellar `G...`` account to many different underlying IDs. + * + * For example, you may have a single Stellar address for accounting purposes: + * GA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJVSGZ + * + * Yet would like to use it for 4 different family members: + * 1: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAGZFQ + * 2: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAALIWQ + * 3: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAPYHQ + * 4: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAQLQQ + * + * This object makes it easy to create muxed accounts from regular accounts, + * duplicate them, get/set the underlying IDs, etc. without mucking around with + * the raw XDR. + * + * Because muxed accounts are purely an off-chain convention, they all share the + * sequence number tied to their underlying G... account. Thus, this object + * *requires* an {@link Account} instance to be passed in, so that muxed + * instances of an account can collectively modify the sequence number whenever + * a muxed account is used as the source of a @{link Transaction} with {@link + * TransactionBuilder}. + * + * @constructor + * + * @param {Account} account - the @{link Account} instance representing the + * underlying G... address + * @param {string} id - a stringified uint64 value that represents the + * ID of the muxed account + * + * @link https://developers.stellar.org/docs/glossary/muxed-accounts/ + */ +var MuxedAccount = exports.MuxedAccount = /*#__PURE__*/function () { + function MuxedAccount(baseAccount, id) { + _classCallCheck(this, MuxedAccount); + var accountId = baseAccount.accountId(); + if (!_strkey.StrKey.isValidEd25519PublicKey(accountId)) { + throw new Error('accountId is invalid'); + } + this.account = baseAccount; + this._muxedXdr = (0, _decode_encode_muxed_account.encodeMuxedAccount)(accountId, id); + this._mAddress = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(this._muxedXdr); + this._id = id; + } + + /** + * Parses an M-address into a MuxedAccount object. + * + * @param {string} mAddress - an M-address to transform + * @param {string} sequenceNum - the sequence number of the underlying {@link + * Account}, to use for the underlying base account (@link + * MuxedAccount.baseAccount). If you're using the SDK, you can use + * `server.loadAccount` to fetch this if you don't know it. + * + * @return {MuxedAccount} + */ + return _createClass(MuxedAccount, [{ + key: "baseAccount", + value: + /** + * @return {Account} the underlying account object shared among all muxed + * accounts with this Stellar address + */ + function baseAccount() { + return this.account; + } + + /** + * @return {string} the M-address representing this account's (G-address, ID) + */ + }, { + key: "accountId", + value: function accountId() { + return this._mAddress; + } + }, { + key: "id", + value: function id() { + return this._id; + } + }, { + key: "setId", + value: function setId(id) { + if (typeof id !== 'string') { + throw new Error('id should be a string representing a number (uint64)'); + } + this._muxedXdr.med25519().id(_xdr["default"].Uint64.fromString(id)); + this._mAddress = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(this._muxedXdr); + this._id = id; + return this; + } + + /** + * Accesses the underlying account's sequence number. + * @return {string} strigified sequence number for the underlying account + */ + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this.account.sequenceNumber(); + } + + /** + * Increments the underlying account's sequence number by one. + * @return {void} + */ + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + return this.account.incrementSequenceNumber(); + } + + /** + * @return {xdr.MuxedAccount} the XDR object representing this muxed account's + * G-address and uint64 ID + */ + }, { + key: "toXDRObject", + value: function toXDRObject() { + return this._muxedXdr; + } + }, { + key: "equals", + value: function equals(otherMuxedAccount) { + return this.accountId() === otherMuxedAccount.accountId(); + } + }], [{ + key: "fromAddress", + value: function fromAddress(mAddress, sequenceNum) { + var muxedAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(mAddress); + var gAddress = (0, _decode_encode_muxed_account.extractBaseAddress)(mAddress); + var id = muxedAccount.med25519().id().toString(); + return new MuxedAccount(new _account.Account(gAddress, sequenceNum), id); + } + }]); +}(); + +/***/ }), + +/***/ 6202: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Networks = void 0; +/** + * Contains passphrases for common networks: + * * `Networks.PUBLIC`: `Public Global Stellar Network ; September 2015` + * * `Networks.TESTNET`: `Test SDF Network ; September 2015` + * * `Networks.FUTURENET`: `Test SDF Future Network ; October 2022` + * * `Networks.STANDALONE`: `Standalone Network ; February 2017` + * + * @type {{PUBLIC: string, TESTNET: string, FUTURENET: string, STANDALONE: string }} + */ +var Networks = exports.Networks = { + PUBLIC: 'Public Global Stellar Network ; September 2015', + TESTNET: 'Test SDF Network ; September 2015', + FUTURENET: 'Test SDF Future Network ; October 2022', + SANDBOX: 'Local Sandbox Stellar Network ; September 2022', + STANDALONE: 'Standalone Network ; February 2017' +}; + +/***/ }), + +/***/ 8549: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "Int128", ({ + enumerable: true, + get: function get() { + return _int.Int128; + } +})); +Object.defineProperty(exports, "Int256", ({ + enumerable: true, + get: function get() { + return _int2.Int256; + } +})); +Object.defineProperty(exports, "ScInt", ({ + enumerable: true, + get: function get() { + return _sc_int.ScInt; + } +})); +Object.defineProperty(exports, "Uint128", ({ + enumerable: true, + get: function get() { + return _uint.Uint128; + } +})); +Object.defineProperty(exports, "Uint256", ({ + enumerable: true, + get: function get() { + return _uint2.Uint256; + } +})); +Object.defineProperty(exports, "XdrLargeInt", ({ + enumerable: true, + get: function get() { + return _xdr_large_int.XdrLargeInt; + } +})); +exports.scValToBigInt = scValToBigInt; +var _xdr_large_int = __webpack_require__(7429); +var _uint = __webpack_require__(6272); +var _uint2 = __webpack_require__(8672); +var _int = __webpack_require__(5487); +var _int2 = __webpack_require__(4063); +var _sc_int = __webpack_require__(3317); +/** + * Transforms an opaque {@link xdr.ScVal} into a native bigint, if possible. + * + * If you then want to use this in the abstractions provided by this module, + * you can pass it to the constructor of {@link XdrLargeInt}. + * + * @example + * let scv = contract.call("add", x, y); // assume it returns an xdr.ScVal + * let bigi = scValToBigInt(scv); + * + * new ScInt(bigi); // if you don't care about types, and + * new XdrLargeInt('i128', bigi); // if you do + * + * @param {xdr.ScVal} scv - the raw XDR value to parse into an integer + * @returns {bigint} the native value of this input value + * + * @throws {TypeError} if the `scv` input value doesn't represent an integer + */ +function scValToBigInt(scv) { + var scIntType = _xdr_large_int.XdrLargeInt.getType(scv["switch"]().name); + switch (scv["switch"]().name) { + case 'scvU32': + case 'scvI32': + return BigInt(scv.value()); + case 'scvU64': + case 'scvI64': + return new _xdr_large_int.XdrLargeInt(scIntType, scv.value()).toBigInt(); + case 'scvU128': + case 'scvI128': + return new _xdr_large_int.XdrLargeInt(scIntType, [scv.value().lo(), scv.value().hi()]).toBigInt(); + case 'scvU256': + case 'scvI256': + return new _xdr_large_int.XdrLargeInt(scIntType, [scv.value().loLo(), scv.value().loHi(), scv.value().hiLo(), scv.value().hiHi()]).toBigInt(); + default: + throw TypeError("expected integer type, got ".concat(scv["switch"]())); + } +} + +/***/ }), + +/***/ 5487: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Int128 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Int128 = exports.Int128 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct a signed 128-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Int128() { + _classCallCheck(this, Int128); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Int128, [args]); + } + _inherits(Int128, _LargeInt); + return _createClass(Int128, [{ + key: "unsigned", + get: function get() { + return false; + } + }, { + key: "size", + get: function get() { + return 128; + } + }]); +}(_jsXdr.LargeInt); +Int128.defineIntBoundaries(); + +/***/ }), + +/***/ 4063: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Int256 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Int256 = exports.Int256 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct a signed 256-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Int256() { + _classCallCheck(this, Int256); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Int256, [args]); + } + _inherits(Int256, _LargeInt); + return _createClass(Int256, [{ + key: "unsigned", + get: function get() { + return false; + } + }, { + key: "size", + get: function get() { + return 256; + } + }]); +}(_jsXdr.LargeInt); +Int256.defineIntBoundaries(); + +/***/ }), + +/***/ 3317: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.ScInt = void 0; +var _xdr_large_int = __webpack_require__(7429); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Provides an easier way to manipulate large numbers for Stellar operations. + * + * You can instantiate this "**s**mart **c**ontract integer" value either from + * bigints, strings, or numbers (whole numbers, or this will throw). + * + * If you need to create a native BigInt from a list of integer "parts" (for + * example, you have a series of encoded 32-bit integers that represent a larger + * value), you can use the lower level abstraction {@link XdrLargeInt}. For + * example, you could do `new XdrLargeInt('u128', bytes...).toBigInt()`. + * + * @example + * import { xdr, ScInt, scValToBigInt } from "@stellar/stellar-base"; + * + * // You have an ScVal from a contract and want to parse it into JS native. + * const value = xdr.ScVal.fromXDR(someXdr, "base64"); + * const bigi = scValToBigInt(value); // grab it as a BigInt + * let sci = new ScInt(bigi); + * + * sci.toNumber(); // gives native JS type (w/ size check) + * sci.toBigInt(); // gives the native BigInt value + * sci.toU64(); // gives ScValType-specific XDR constructs (with size checks) + * + * // You have a number and want to shove it into a contract. + * sci = ScInt(0xdeadcafebabe); + * sci.toBigInt() // returns 244838016400062n + * sci.toNumber() // throws: too large + * + * // Pass any to e.g. a Contract.call(), conversion happens automatically + * // regardless of the initial type. + * const scValU128 = sci.toU128(); + * const scValI256 = sci.toI256(); + * const scValU64 = sci.toU64(); + * + * // Lots of ways to initialize: + * ScInt("123456789123456789") + * ScInt(123456789123456789n); + * ScInt(1n << 140n); + * ScInt(-42); + * ScInt(scValToBigInt(scValU128)); // from above + * + * // If you know the type ahead of time (accessing `.raw` is faster than + * // conversions), you can specify the type directly (otherwise, it's + * // interpreted from the numbers you pass in): + * const i = ScInt(123456789n, { type: "u256" }); + * + * // For example, you can use the underlying `sdk.U256` and convert it to an + * // `xdr.ScVal` directly like so: + * const scv = new xdr.ScVal.scvU256(i.raw); + * + * // Or reinterpret it as a different type (size permitting): + * const scv = i.toI64(); + * + * @param {number|bigint|string} value - a single, integer-like value which will + * be interpreted in the smallest appropriate XDR type supported by Stellar + * (64, 128, or 256 bit integer values). signed values are supported, though + * they are sanity-checked against `opts.type`. if you need 32-bit values, + * you can construct them directly without needing this wrapper, e.g. + * `xdr.ScVal.scvU32(1234)`. + * + * @param {object} [opts] - an optional object controlling optional parameters + * @param {string} [opts.type] - force a specific data type. the type choices + * are: 'i64', 'u64', 'i128', 'u128', 'i256', and 'u256' (default: the + * smallest one that fits the `value`) + * + * @throws {RangeError} if the `value` is invalid (e.g. floating point), too + * large (i.e. exceeds a 256-bit value), or doesn't fit in the `opts.type` + * @throws {TypeError} on missing parameters, or if the "signedness" of `opts` + * doesn't match input `value`, e.g. passing `{type: 'u64'}` yet passing -1n + * @throws {SyntaxError} if a string `value` can't be parsed as a big integer + */ +var ScInt = exports.ScInt = /*#__PURE__*/function (_XdrLargeInt) { + function ScInt(value, opts) { + var _opts$type; + _classCallCheck(this, ScInt); + var signed = value < 0; + var type = (_opts$type = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type !== void 0 ? _opts$type : ''; + if (type.startsWith('u') && signed) { + throw TypeError("specified type ".concat(opts.type, " yet negative (").concat(value, ")")); + } + + // If unspecified, we make a best guess at the type based on the bit length + // of the value, treating 64 as a minimum and 256 as a maximum. + if (type === '') { + type = signed ? 'i' : 'u'; + var bitlen = nearestBigIntSize(value); + switch (bitlen) { + case 64: + case 128: + case 256: + type += bitlen.toString(); + break; + default: + throw RangeError("expected 64/128/256 bits for input (".concat(value, "), got ").concat(bitlen)); + } + } + return _callSuper(this, ScInt, [type, value]); + } + _inherits(ScInt, _XdrLargeInt); + return _createClass(ScInt); +}(_xdr_large_int.XdrLargeInt); +function nearestBigIntSize(bigI) { + var _find; + // Note: Even though BigInt.toString(2) includes the negative sign for + // negative values (???), the following is still accurate, because the + // negative sign would be represented by a sign bit. + var bitlen = bigI.toString(2).length; + return (_find = [64, 128, 256].find(function (len) { + return bitlen <= len; + })) !== null && _find !== void 0 ? _find : bitlen; +} + +/***/ }), + +/***/ 6272: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Uint128 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Uint128 = exports.Uint128 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct an unsigned 128-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Uint128() { + _classCallCheck(this, Uint128); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Uint128, [args]); + } + _inherits(Uint128, _LargeInt); + return _createClass(Uint128, [{ + key: "unsigned", + get: function get() { + return true; + } + }, { + key: "size", + get: function get() { + return 128; + } + }]); +}(_jsXdr.LargeInt); +Uint128.defineIntBoundaries(); + +/***/ }), + +/***/ 8672: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Uint256 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Uint256 = exports.Uint256 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct an unsigned 256-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Uint256() { + _classCallCheck(this, Uint256); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Uint256, [args]); + } + _inherits(Uint256, _LargeInt); + return _createClass(Uint256, [{ + key: "unsigned", + get: function get() { + return true; + } + }, { + key: "size", + get: function get() { + return 256; + } + }]); +}(_jsXdr.LargeInt); +Uint256.defineIntBoundaries(); + +/***/ }), + +/***/ 7429: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.XdrLargeInt = void 0; +var _jsXdr = __webpack_require__(3740); +var _uint = __webpack_require__(6272); +var _uint2 = __webpack_require__(8672); +var _int = __webpack_require__(5487); +var _int2 = __webpack_require__(4063); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": [">>"]}] */ +/** + * A wrapper class to represent large XDR-encodable integers. + * + * This operates at a lower level than {@link ScInt} by forcing you to specify + * the type / width / size in bits of the integer you're targeting, regardless + * of the input value(s) you provide. + * + * @param {string} type - force a specific data type. the type choices are: + * 'i64', 'u64', 'i128', 'u128', 'i256', and 'u256' (default: the smallest + * one that fits the `value`) (see {@link XdrLargeInt.isType}) + * @param {number|bigint|string|Array} values a list of + * integer-like values interpreted in big-endian order + */ +var XdrLargeInt = exports.XdrLargeInt = /*#__PURE__*/function () { + function XdrLargeInt(type, values) { + _classCallCheck(this, XdrLargeInt); + /** @type {xdr.LargeInt} */ + _defineProperty(this, "int", void 0); + // child class of a jsXdr.LargeInt + /** @type {string} */ + _defineProperty(this, "type", void 0); + if (!(values instanceof Array)) { + values = [values]; + } + + // normalize values to one type + values = values.map(function (i) { + // micro-optimization to no-op on the likeliest input value: + if (typeof i === 'bigint') { + return i; + } + if (i instanceof XdrLargeInt) { + return i.toBigInt(); + } + return BigInt(i); + }); + switch (type) { + case 'i64': + this["int"] = new _jsXdr.Hyper(values); + break; + case 'i128': + this["int"] = new _int.Int128(values); + break; + case 'i256': + this["int"] = new _int2.Int256(values); + break; + case 'u64': + this["int"] = new _jsXdr.UnsignedHyper(values); + break; + case 'u128': + this["int"] = new _uint.Uint128(values); + break; + case 'u256': + this["int"] = new _uint2.Uint256(values); + break; + default: + throw TypeError("invalid type: ".concat(type)); + } + this.type = type; + } + + /** + * @returns {number} + * @throws {RangeError} if the value can't fit into a Number + */ + return _createClass(XdrLargeInt, [{ + key: "toNumber", + value: function toNumber() { + var bi = this["int"].toBigInt(); + if (bi > Number.MAX_SAFE_INTEGER || bi < Number.MIN_SAFE_INTEGER) { + throw RangeError("value ".concat(bi, " not in range for Number ") + "[".concat(Number.MAX_SAFE_INTEGER, ", ").concat(Number.MIN_SAFE_INTEGER, "]")); + } + return Number(bi); + } + + /** @returns {bigint} */ + }, { + key: "toBigInt", + value: function toBigInt() { + return this["int"].toBigInt(); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = I64` */ + }, { + key: "toI64", + value: function toI64() { + this._sizeCheck(64); + var v = this.toBigInt(); + if (BigInt.asIntN(64, v) !== v) { + throw RangeError("value too large for i64: ".concat(v)); + } + return _xdr["default"].ScVal.scvI64(new _xdr["default"].Int64(v)); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = U64` */ + }, { + key: "toU64", + value: function toU64() { + this._sizeCheck(64); + return _xdr["default"].ScVal.scvU64(new _xdr["default"].Uint64(BigInt.asUintN(64, this.toBigInt())) // reiterpret as unsigned + ); + } + + /** + * @returns {xdr.ScVal} the integer encoded with `ScValType = I128` + * @throws {RangeError} if the value cannot fit in 128 bits + */ + }, { + key: "toI128", + value: function toI128() { + this._sizeCheck(128); + var v = this["int"].toBigInt(); + var hi64 = BigInt.asIntN(64, v >> 64n); // encode top 64 w/ sign bit + var lo64 = BigInt.asUintN(64, v); // grab btm 64, encode sign + + return _xdr["default"].ScVal.scvI128(new _xdr["default"].Int128Parts({ + hi: new _xdr["default"].Int64(hi64), + lo: new _xdr["default"].Uint64(lo64) + })); + } + + /** + * @returns {xdr.ScVal} the integer encoded with `ScValType = U128` + * @throws {RangeError} if the value cannot fit in 128 bits + */ + }, { + key: "toU128", + value: function toU128() { + this._sizeCheck(128); + var v = this["int"].toBigInt(); + return _xdr["default"].ScVal.scvU128(new _xdr["default"].UInt128Parts({ + hi: new _xdr["default"].Uint64(BigInt.asUintN(64, v >> 64n)), + lo: new _xdr["default"].Uint64(BigInt.asUintN(64, v)) + })); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = I256` */ + }, { + key: "toI256", + value: function toI256() { + var v = this["int"].toBigInt(); + var hiHi64 = BigInt.asIntN(64, v >> 192n); // keep sign bit + var hiLo64 = BigInt.asUintN(64, v >> 128n); + var loHi64 = BigInt.asUintN(64, v >> 64n); + var loLo64 = BigInt.asUintN(64, v); + return _xdr["default"].ScVal.scvI256(new _xdr["default"].Int256Parts({ + hiHi: new _xdr["default"].Int64(hiHi64), + hiLo: new _xdr["default"].Uint64(hiLo64), + loHi: new _xdr["default"].Uint64(loHi64), + loLo: new _xdr["default"].Uint64(loLo64) + })); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = U256` */ + }, { + key: "toU256", + value: function toU256() { + var v = this["int"].toBigInt(); + var hiHi64 = BigInt.asUintN(64, v >> 192n); // encode sign bit + var hiLo64 = BigInt.asUintN(64, v >> 128n); + var loHi64 = BigInt.asUintN(64, v >> 64n); + var loLo64 = BigInt.asUintN(64, v); + return _xdr["default"].ScVal.scvU256(new _xdr["default"].UInt256Parts({ + hiHi: new _xdr["default"].Uint64(hiHi64), + hiLo: new _xdr["default"].Uint64(hiLo64), + loHi: new _xdr["default"].Uint64(loHi64), + loLo: new _xdr["default"].Uint64(loLo64) + })); + } + + /** @returns {xdr.ScVal} the smallest interpretation of the stored value */ + }, { + key: "toScVal", + value: function toScVal() { + switch (this.type) { + case 'i64': + return this.toI64(); + case 'i128': + return this.toI128(); + case 'i256': + return this.toI256(); + case 'u64': + return this.toU64(); + case 'u128': + return this.toU128(); + case 'u256': + return this.toU256(); + default: + throw TypeError("invalid type: ".concat(this.type)); + } + } + }, { + key: "valueOf", + value: function valueOf() { + return this["int"].valueOf(); + } + }, { + key: "toString", + value: function toString() { + return this["int"].toString(); + } + }, { + key: "toJSON", + value: function toJSON() { + return { + value: this.toBigInt().toString(), + type: this.type + }; + } + }, { + key: "_sizeCheck", + value: function _sizeCheck(bits) { + if (this["int"].size > bits) { + throw RangeError("value too large for ".concat(bits, " bits (").concat(this.type, ")")); + } + } + }], [{ + key: "isType", + value: function isType(type) { + switch (type) { + case 'i64': + case 'i128': + case 'i256': + case 'u64': + case 'u128': + case 'u256': + return true; + default: + return false; + } + } + + /** + * Convert the raw `ScValType` string (e.g. 'scvI128', generated by the XDR) + * to a type description for {@link XdrLargeInt} construction (e.g. 'i128') + * + * @param {string} scvType the `xdr.ScValType` as a string + * @returns {string} a suitable equivalent type to construct this object + */ + }, { + key: "getType", + value: function getType(scvType) { + return scvType.slice(3).toLowerCase(); + } + }]); +}(); + +/***/ }), + +/***/ 7237: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Operation = exports.AuthRevocableFlag = exports.AuthRequiredFlag = exports.AuthImmutableFlag = exports.AuthClawbackEnabledFlag = void 0; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _util = __webpack_require__(645); +var _continued_fraction = __webpack_require__(4151); +var _asset = __webpack_require__(1764); +var _liquidity_pool_asset = __webpack_require__(2262); +var _claimant = __webpack_require__(1387); +var _strkey = __webpack_require__(7120); +var _liquidity_pool_id = __webpack_require__(9353); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var ops = _interopRequireWildcard(__webpack_require__(7511)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint-disable no-bitwise */ +var ONE = 10000000; +var MAX_INT64 = '9223372036854775807'; + +/** + * When set using `{@link Operation.setOptions}` option, requires the issuing + * account to give other accounts permission before they can hold the issuing + * account’s credit. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthRequiredFlag = exports.AuthRequiredFlag = 1 << 0; +/** + * When set using `{@link Operation.setOptions}` option, allows the issuing + * account to revoke its credit held by other accounts. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthRevocableFlag = exports.AuthRevocableFlag = 1 << 1; +/** + * When set using `{@link Operation.setOptions}` option, then none of the + * authorization flags can be set and the account can never be deleted. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthImmutableFlag = exports.AuthImmutableFlag = 1 << 2; + +/** + * When set using `{@link Operation.setOptions}` option, then any trustlines + * created by this account can have a ClawbackOp operation submitted for the + * corresponding asset. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthClawbackEnabledFlag = exports.AuthClawbackEnabledFlag = 1 << 3; + +/** + * `Operation` class represents + * [operations](https://developers.stellar.org/docs/glossary/operations/) in + * Stellar network. + * + * Use one of static methods to create operations: + * * `{@link Operation.createAccount}` + * * `{@link Operation.payment}` + * * `{@link Operation.pathPaymentStrictReceive}` + * * `{@link Operation.pathPaymentStrictSend}` + * * `{@link Operation.manageSellOffer}` + * * `{@link Operation.manageBuyOffer}` + * * `{@link Operation.createPassiveSellOffer}` + * * `{@link Operation.setOptions}` + * * `{@link Operation.changeTrust}` + * * `{@link Operation.allowTrust}` + * * `{@link Operation.accountMerge}` + * * `{@link Operation.inflation}` + * * `{@link Operation.manageData}` + * * `{@link Operation.bumpSequence}` + * * `{@link Operation.createClaimableBalance}` + * * `{@link Operation.claimClaimableBalance}` + * * `{@link Operation.beginSponsoringFutureReserves}` + * * `{@link Operation.endSponsoringFutureReserves}` + * * `{@link Operation.revokeAccountSponsorship}` + * * `{@link Operation.revokeTrustlineSponsorship}` + * * `{@link Operation.revokeOfferSponsorship}` + * * `{@link Operation.revokeDataSponsorship}` + * * `{@link Operation.revokeClaimableBalanceSponsorship}` + * * `{@link Operation.revokeLiquidityPoolSponsorship}` + * * `{@link Operation.revokeSignerSponsorship}` + * * `{@link Operation.clawback}` + * * `{@link Operation.clawbackClaimableBalance}` + * * `{@link Operation.setTrustLineFlags}` + * * `{@link Operation.liquidityPoolDeposit}` + * * `{@link Operation.liquidityPoolWithdraw}` + * * `{@link Operation.invokeHostFunction}`, which has the following additional + * "pseudo-operations" that make building host functions easier: + * - `{@link Operation.createStellarAssetContract}` + * - `{@link Operation.invokeContractFunction}` + * - `{@link Operation.createCustomContract}` + * - `{@link Operation.uploadContractWasm}` + * * `{@link Operation.extendFootprintTtlOp}` + * * `{@link Operation.restoreFootprint}` + * + * @class Operation + */ +var Operation = exports.Operation = /*#__PURE__*/function () { + function Operation() { + _classCallCheck(this, Operation); + } + return _createClass(Operation, null, [{ + key: "setSourceAccount", + value: function setSourceAccount(opAttributes, opts) { + if (opts.source) { + try { + opAttributes.sourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.source); + } catch (e) { + throw new Error('Source address is invalid'); + } + } + } + + /** + * Deconstructs the raw XDR operation object into the structured object that + * was used to create the operation (i.e. the `opts` parameter to most ops). + * + * @param {xdr.Operation} operation - An XDR Operation. + * @return {Operation} + */ + }, { + key: "fromXDRObject", + value: function fromXDRObject(operation) { + var result = {}; + if (operation.sourceAccount()) { + result.source = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(operation.sourceAccount()); + } + var attrs = operation.body().value(); + var operationName = operation.body()["switch"]().name; + switch (operationName) { + case 'createAccount': + { + result.type = 'createAccount'; + result.destination = accountIdtoAddress(attrs.destination()); + result.startingBalance = this._fromXDRAmount(attrs.startingBalance()); + break; + } + case 'payment': + { + result.type = 'payment'; + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.amount = this._fromXDRAmount(attrs.amount()); + break; + } + case 'pathPaymentStrictReceive': + { + result.type = 'pathPaymentStrictReceive'; + result.sendAsset = _asset.Asset.fromOperation(attrs.sendAsset()); + result.sendMax = this._fromXDRAmount(attrs.sendMax()); + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.destAsset = _asset.Asset.fromOperation(attrs.destAsset()); + result.destAmount = this._fromXDRAmount(attrs.destAmount()); + result.path = []; + var path = attrs.path(); + + // note that Object.values isn't supported by node 6! + Object.keys(path).forEach(function (pathKey) { + result.path.push(_asset.Asset.fromOperation(path[pathKey])); + }); + break; + } + case 'pathPaymentStrictSend': + { + result.type = 'pathPaymentStrictSend'; + result.sendAsset = _asset.Asset.fromOperation(attrs.sendAsset()); + result.sendAmount = this._fromXDRAmount(attrs.sendAmount()); + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.destAsset = _asset.Asset.fromOperation(attrs.destAsset()); + result.destMin = this._fromXDRAmount(attrs.destMin()); + result.path = []; + var _path = attrs.path(); + + // note that Object.values isn't supported by node 6! + Object.keys(_path).forEach(function (pathKey) { + result.path.push(_asset.Asset.fromOperation(_path[pathKey])); + }); + break; + } + case 'changeTrust': + { + result.type = 'changeTrust'; + switch (attrs.line()["switch"]()) { + case _xdr["default"].AssetType.assetTypePoolShare(): + result.line = _liquidity_pool_asset.LiquidityPoolAsset.fromOperation(attrs.line()); + break; + default: + result.line = _asset.Asset.fromOperation(attrs.line()); + break; + } + result.limit = this._fromXDRAmount(attrs.limit()); + break; + } + case 'allowTrust': + { + result.type = 'allowTrust'; + result.trustor = accountIdtoAddress(attrs.trustor()); + result.assetCode = attrs.asset().value().toString(); + result.assetCode = (0, _util.trimEnd)(result.assetCode, '\0'); + result.authorize = attrs.authorize(); + break; + } + case 'setOptions': + { + result.type = 'setOptions'; + if (attrs.inflationDest()) { + result.inflationDest = accountIdtoAddress(attrs.inflationDest()); + } + result.clearFlags = attrs.clearFlags(); + result.setFlags = attrs.setFlags(); + result.masterWeight = attrs.masterWeight(); + result.lowThreshold = attrs.lowThreshold(); + result.medThreshold = attrs.medThreshold(); + result.highThreshold = attrs.highThreshold(); + // home_domain is checked by iscntrl in stellar-core + result.homeDomain = attrs.homeDomain() !== undefined ? attrs.homeDomain().toString('ascii') : undefined; + if (attrs.signer()) { + var signer = {}; + var arm = attrs.signer().key().arm(); + if (arm === 'ed25519') { + signer.ed25519PublicKey = accountIdtoAddress(attrs.signer().key()); + } else if (arm === 'preAuthTx') { + signer.preAuthTx = attrs.signer().key().preAuthTx(); + } else if (arm === 'hashX') { + signer.sha256Hash = attrs.signer().key().hashX(); + } else if (arm === 'ed25519SignedPayload') { + var signedPayload = attrs.signer().key().ed25519SignedPayload(); + signer.ed25519SignedPayload = _strkey.StrKey.encodeSignedPayload(signedPayload.toXDR()); + } + signer.weight = attrs.signer().weight(); + result.signer = signer; + } + break; + } + // the next case intentionally falls through! + case 'manageOffer': + case 'manageSellOffer': + { + result.type = 'manageSellOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.price = this._fromXDRPrice(attrs.price()); + result.offerId = attrs.offerId().toString(); + break; + } + case 'manageBuyOffer': + { + result.type = 'manageBuyOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.buyAmount = this._fromXDRAmount(attrs.buyAmount()); + result.price = this._fromXDRPrice(attrs.price()); + result.offerId = attrs.offerId().toString(); + break; + } + // the next case intentionally falls through! + case 'createPassiveOffer': + case 'createPassiveSellOffer': + { + result.type = 'createPassiveSellOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.price = this._fromXDRPrice(attrs.price()); + break; + } + case 'accountMerge': + { + result.type = 'accountMerge'; + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs); + break; + } + case 'manageData': + { + result.type = 'manageData'; + // manage_data.name is checked by iscntrl in stellar-core + result.name = attrs.dataName().toString('ascii'); + result.value = attrs.dataValue(); + break; + } + case 'inflation': + { + result.type = 'inflation'; + break; + } + case 'bumpSequence': + { + result.type = 'bumpSequence'; + result.bumpTo = attrs.bumpTo().toString(); + break; + } + case 'createClaimableBalance': + { + result.type = 'createClaimableBalance'; + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.claimants = []; + attrs.claimants().forEach(function (claimant) { + result.claimants.push(_claimant.Claimant.fromXDR(claimant)); + }); + break; + } + case 'claimClaimableBalance': + { + result.type = 'claimClaimableBalance'; + result.balanceId = attrs.toXDR('hex'); + break; + } + case 'beginSponsoringFutureReserves': + { + result.type = 'beginSponsoringFutureReserves'; + result.sponsoredId = accountIdtoAddress(attrs.sponsoredId()); + break; + } + case 'endSponsoringFutureReserves': + { + result.type = 'endSponsoringFutureReserves'; + break; + } + case 'revokeSponsorship': + { + extractRevokeSponshipDetails(attrs, result); + break; + } + case 'clawback': + { + result.type = 'clawback'; + result.amount = this._fromXDRAmount(attrs.amount()); + result.from = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.from()); + result.asset = _asset.Asset.fromOperation(attrs.asset()); + break; + } + case 'clawbackClaimableBalance': + { + result.type = 'clawbackClaimableBalance'; + result.balanceId = attrs.toXDR('hex'); + break; + } + case 'setTrustLineFlags': + { + result.type = 'setTrustLineFlags'; + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.trustor = accountIdtoAddress(attrs.trustor()); + + // Convert from the integer-bitwised flag into a sensible object that + // indicates true/false for each flag that's on/off. + var clears = attrs.clearFlags(); + var sets = attrs.setFlags(); + var mapping = { + authorized: _xdr["default"].TrustLineFlags.authorizedFlag(), + authorizedToMaintainLiabilities: _xdr["default"].TrustLineFlags.authorizedToMaintainLiabilitiesFlag(), + clawbackEnabled: _xdr["default"].TrustLineFlags.trustlineClawbackEnabledFlag() + }; + var getFlagValue = function getFlagValue(key) { + var bit = mapping[key].value; + if (sets & bit) { + return true; + } + if (clears & bit) { + return false; + } + return undefined; + }; + result.flags = {}; + Object.keys(mapping).forEach(function (flagName) { + result.flags[flagName] = getFlagValue(flagName); + }); + break; + } + case 'liquidityPoolDeposit': + { + result.type = 'liquidityPoolDeposit'; + result.liquidityPoolId = attrs.liquidityPoolId().toString('hex'); + result.maxAmountA = this._fromXDRAmount(attrs.maxAmountA()); + result.maxAmountB = this._fromXDRAmount(attrs.maxAmountB()); + result.minPrice = this._fromXDRPrice(attrs.minPrice()); + result.maxPrice = this._fromXDRPrice(attrs.maxPrice()); + break; + } + case 'liquidityPoolWithdraw': + { + result.type = 'liquidityPoolWithdraw'; + result.liquidityPoolId = attrs.liquidityPoolId().toString('hex'); + result.amount = this._fromXDRAmount(attrs.amount()); + result.minAmountA = this._fromXDRAmount(attrs.minAmountA()); + result.minAmountB = this._fromXDRAmount(attrs.minAmountB()); + break; + } + case 'invokeHostFunction': + { + var _attrs$auth; + result.type = 'invokeHostFunction'; + result.func = attrs.hostFunction(); + result.auth = (_attrs$auth = attrs.auth()) !== null && _attrs$auth !== void 0 ? _attrs$auth : []; + break; + } + case 'extendFootprintTtl': + { + result.type = 'extendFootprintTtl'; + result.extendTo = attrs.extendTo(); + break; + } + case 'restoreFootprint': + { + result.type = 'restoreFootprint'; + break; + } + default: + { + throw new Error("Unknown operation: ".concat(operationName)); + } + } + return result; + } + + /** + * Validates that a given amount is possible for a Stellar asset. + * + * Specifically, this means that the amount is well, a valid number, but also + * that it is within the int64 range and has no more than 7 decimal levels of + * precision. + * + * Note that while smart contracts allow larger amounts, this is oriented + * towards validating the standard Stellar operations. + * + * @param {string} value the amount to validate + * @param {boolean} allowZero optionally, whether or not zero is valid (default: no) + * + * @returns {boolean} + */ + }, { + key: "isValidAmount", + value: function isValidAmount(value) { + var allowZero = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (typeof value !== 'string') { + return false; + } + var amount; + try { + amount = new _bignumber["default"](value); + } catch (e) { + return false; + } + if ( + // == 0 + !allowZero && amount.isZero() || + // < 0 + amount.isNegative() || + // > Max value + amount.times(ONE).gt(new _bignumber["default"](MAX_INT64).toString()) || + // Decimal places (max 7) + amount.decimalPlaces() > 7 || + // NaN or Infinity + amount.isNaN() || !amount.isFinite()) { + return false; + } + return true; + } + }, { + key: "constructAmountRequirementsError", + value: function constructAmountRequirementsError(arg) { + return "".concat(arg, " argument must be of type String, represent a positive number and have at most 7 digits after the decimal"); + } + + /** + * Returns value converted to uint32 value or undefined. + * If `value` is not `Number`, `String` or `Undefined` then throws an error. + * Used in {@link Operation.setOptions}. + * @private + * @param {string} name Name of the property (used in error message only) + * @param {*} value Value to check + * @param {function(value, name)} isValidFunction Function to check other constraints (the argument will be a `Number`) + * @returns {undefined|Number} + */ + }, { + key: "_checkUnsignedIntValue", + value: function _checkUnsignedIntValue(name, value) { + var isValidFunction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + if (typeof value === 'undefined') { + return undefined; + } + if (typeof value === 'string') { + value = parseFloat(value); + } + switch (true) { + case typeof value !== 'number' || !Number.isFinite(value) || value % 1 !== 0: + throw new Error("".concat(name, " value is invalid")); + case value < 0: + throw new Error("".concat(name, " value must be unsigned")); + case !isValidFunction || isValidFunction && isValidFunction(value, name): + return value; + default: + throw new Error("".concat(name, " value is invalid")); + } + } + /** + * @private + * @param {string|BigNumber} value Value + * @returns {Hyper} XDR amount + */ + }, { + key: "_toXDRAmount", + value: function _toXDRAmount(value) { + var amount = new _bignumber["default"](value).times(ONE); + return _jsXdr.Hyper.fromString(amount.toString()); + } + + /** + * @private + * @param {string|BigNumber} value XDR amount + * @returns {BigNumber} Number + */ + }, { + key: "_fromXDRAmount", + value: function _fromXDRAmount(value) { + return new _bignumber["default"](value).div(ONE).toFixed(7); + } + + /** + * @private + * @param {object} price Price object + * @param {function} price.n numerator function that returns a value + * @param {function} price.d denominator function that returns a value + * @returns {BigNumber} Big string + */ + }, { + key: "_fromXDRPrice", + value: function _fromXDRPrice(price) { + var n = new _bignumber["default"](price.n()); + return n.div(new _bignumber["default"](price.d())).toString(); + } + + /** + * @private + * @param {object} price Price object + * @param {function} price.n numerator function that returns a value + * @param {function} price.d denominator function that returns a value + * @returns {object} XDR price object + */ + }, { + key: "_toXDRPrice", + value: function _toXDRPrice(price) { + var xdrObject; + if (price.n && price.d) { + xdrObject = new _xdr["default"].Price(price); + } else { + var approx = (0, _continued_fraction.best_r)(price); + xdrObject = new _xdr["default"].Price({ + n: parseInt(approx[0], 10), + d: parseInt(approx[1], 10) + }); + } + if (xdrObject.n() < 0 || xdrObject.d() < 0) { + throw new Error('price must be positive'); + } + return xdrObject; + } + }]); +}(); +function extractRevokeSponshipDetails(attrs, result) { + switch (attrs["switch"]().name) { + case 'revokeSponsorshipLedgerEntry': + { + var ledgerKey = attrs.ledgerKey(); + switch (ledgerKey["switch"]().name) { + case _xdr["default"].LedgerEntryType.account().name: + { + result.type = 'revokeAccountSponsorship'; + result.account = accountIdtoAddress(ledgerKey.account().accountId()); + break; + } + case _xdr["default"].LedgerEntryType.trustline().name: + { + result.type = 'revokeTrustlineSponsorship'; + result.account = accountIdtoAddress(ledgerKey.trustLine().accountId()); + var xdrAsset = ledgerKey.trustLine().asset(); + switch (xdrAsset["switch"]()) { + case _xdr["default"].AssetType.assetTypePoolShare(): + result.asset = _liquidity_pool_id.LiquidityPoolId.fromOperation(xdrAsset); + break; + default: + result.asset = _asset.Asset.fromOperation(xdrAsset); + break; + } + break; + } + case _xdr["default"].LedgerEntryType.offer().name: + { + result.type = 'revokeOfferSponsorship'; + result.seller = accountIdtoAddress(ledgerKey.offer().sellerId()); + result.offerId = ledgerKey.offer().offerId().toString(); + break; + } + case _xdr["default"].LedgerEntryType.data().name: + { + result.type = 'revokeDataSponsorship'; + result.account = accountIdtoAddress(ledgerKey.data().accountId()); + result.name = ledgerKey.data().dataName().toString('ascii'); + break; + } + case _xdr["default"].LedgerEntryType.claimableBalance().name: + { + result.type = 'revokeClaimableBalanceSponsorship'; + result.balanceId = ledgerKey.claimableBalance().balanceId().toXDR('hex'); + break; + } + case _xdr["default"].LedgerEntryType.liquidityPool().name: + { + result.type = 'revokeLiquidityPoolSponsorship'; + result.liquidityPoolId = ledgerKey.liquidityPool().liquidityPoolId().toString('hex'); + break; + } + default: + { + throw new Error("Unknown ledgerKey: ".concat(attrs["switch"]().name)); + } + } + break; + } + case 'revokeSponsorshipSigner': + { + result.type = 'revokeSignerSponsorship'; + result.account = accountIdtoAddress(attrs.signer().accountId()); + result.signer = convertXDRSignerKeyToObject(attrs.signer().signerKey()); + break; + } + default: + { + throw new Error("Unknown revokeSponsorship: ".concat(attrs["switch"]().name)); + } + } +} +function convertXDRSignerKeyToObject(signerKey) { + var attrs = {}; + switch (signerKey["switch"]().name) { + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519().name: + { + attrs.ed25519PublicKey = _strkey.StrKey.encodeEd25519PublicKey(signerKey.ed25519()); + break; + } + case _xdr["default"].SignerKeyType.signerKeyTypePreAuthTx().name: + { + attrs.preAuthTx = signerKey.preAuthTx().toString('hex'); + break; + } + case _xdr["default"].SignerKeyType.signerKeyTypeHashX().name: + { + attrs.sha256Hash = signerKey.hashX().toString('hex'); + break; + } + default: + { + throw new Error("Unknown signerKey: ".concat(signerKey["switch"]().name)); + } + } + return attrs; +} +function accountIdtoAddress(accountId) { + return _strkey.StrKey.encodeEd25519PublicKey(accountId.ed25519()); +} + +// Attach all imported operations as static methods on the Operation class +Operation.accountMerge = ops.accountMerge; +Operation.allowTrust = ops.allowTrust; +Operation.bumpSequence = ops.bumpSequence; +Operation.changeTrust = ops.changeTrust; +Operation.createAccount = ops.createAccount; +Operation.createClaimableBalance = ops.createClaimableBalance; +Operation.claimClaimableBalance = ops.claimClaimableBalance; +Operation.clawbackClaimableBalance = ops.clawbackClaimableBalance; +Operation.createPassiveSellOffer = ops.createPassiveSellOffer; +Operation.inflation = ops.inflation; +Operation.manageData = ops.manageData; +Operation.manageSellOffer = ops.manageSellOffer; +Operation.manageBuyOffer = ops.manageBuyOffer; +Operation.pathPaymentStrictReceive = ops.pathPaymentStrictReceive; +Operation.pathPaymentStrictSend = ops.pathPaymentStrictSend; +Operation.payment = ops.payment; +Operation.setOptions = ops.setOptions; +Operation.beginSponsoringFutureReserves = ops.beginSponsoringFutureReserves; +Operation.endSponsoringFutureReserves = ops.endSponsoringFutureReserves; +Operation.revokeAccountSponsorship = ops.revokeAccountSponsorship; +Operation.revokeTrustlineSponsorship = ops.revokeTrustlineSponsorship; +Operation.revokeOfferSponsorship = ops.revokeOfferSponsorship; +Operation.revokeDataSponsorship = ops.revokeDataSponsorship; +Operation.revokeClaimableBalanceSponsorship = ops.revokeClaimableBalanceSponsorship; +Operation.revokeLiquidityPoolSponsorship = ops.revokeLiquidityPoolSponsorship; +Operation.revokeSignerSponsorship = ops.revokeSignerSponsorship; +Operation.clawback = ops.clawback; +Operation.setTrustLineFlags = ops.setTrustLineFlags; +Operation.liquidityPoolDeposit = ops.liquidityPoolDeposit; +Operation.liquidityPoolWithdraw = ops.liquidityPoolWithdraw; +Operation.invokeHostFunction = ops.invokeHostFunction; +Operation.extendFootprintTtl = ops.extendFootprintTtl; +Operation.restoreFootprint = ops.restoreFootprint; + +// these are not `xdr.Operation`s directly, but are proxies for complex but +// common versions of `Operation.invokeHostFunction` +Operation.createStellarAssetContract = ops.createStellarAssetContract; +Operation.invokeContractFunction = ops.invokeContractFunction; +Operation.createCustomContract = ops.createCustomContract; +Operation.uploadContractWasm = ops.uploadContractWasm; + +/***/ }), + +/***/ 4295: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.accountMerge = accountMerge; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Transfers native balance to destination account. + * + * @function + * @alias Operation.accountMerge + * + * @param {object} opts - options object + * @param {string} opts.destination - destination to merge the source account into + * @param {string} [opts.source] - operation source account (defaults to + * transaction source) + * + * @returns {xdr.Operation} an Account Merge operation (xdr.AccountMergeOp) + */ +function accountMerge(opts) { + var opAttributes = {}; + try { + opAttributes.body = _xdr["default"].OperationBody.accountMerge((0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination)); + } catch (e) { + throw new Error('destination is invalid'); + } + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 3683: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.allowTrust = allowTrust; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * @deprecated since v5.0 + * + * Returns an XDR AllowTrustOp. An "allow trust" operation authorizes another + * account to hold your account's credit for a given asset. + * + * @function + * @alias Operation.allowTrust + * + * @param {object} opts Options object + * @param {string} opts.trustor - The trusting account (the one being authorized) + * @param {string} opts.assetCode - The asset code being authorized. + * @param {(0|1|2)} opts.authorize - `1` to authorize, `2` to authorize to maintain liabilities, and `0` to deauthorize. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * + * @returns {xdr.AllowTrustOp} Allow Trust operation + */ +function allowTrust(opts) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.trustor)) { + throw new Error('trustor is invalid'); + } + var attributes = {}; + attributes.trustor = _keypair.Keypair.fromPublicKey(opts.trustor).xdrAccountId(); + if (opts.assetCode.length <= 4) { + var code = opts.assetCode.padEnd(4, '\0'); + attributes.asset = _xdr["default"].AssetCode.assetTypeCreditAlphanum4(code); + } else if (opts.assetCode.length <= 12) { + var _code = opts.assetCode.padEnd(12, '\0'); + attributes.asset = _xdr["default"].AssetCode.assetTypeCreditAlphanum12(_code); + } else { + throw new Error('Asset code must be 12 characters at max.'); + } + if (typeof opts.authorize === 'boolean') { + if (opts.authorize) { + attributes.authorize = _xdr["default"].TrustLineFlags.authorizedFlag().value; + } else { + attributes.authorize = 0; + } + } else { + attributes.authorize = opts.authorize; + } + var allowTrustOp = new _xdr["default"].AllowTrustOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.allowTrust(allowTrustOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7505: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.beginSponsoringFutureReserves = beginSponsoringFutureReserves; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +var _keypair = __webpack_require__(6691); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a "begin sponsoring future reserves" operation. + * @function + * @alias Operation.beginSponsoringFutureReserves + * @param {object} opts Options object + * @param {string} opts.sponsoredId - The sponsored account id. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.beginSponsoringFutureReserves({ + * sponsoredId: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * }); + * + */ +function beginSponsoringFutureReserves() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.sponsoredId)) { + throw new Error('sponsoredId is invalid'); + } + var op = new _xdr["default"].BeginSponsoringFutureReservesOp({ + sponsoredId: _keypair.Keypair.fromPublicKey(opts.sponsoredId).xdrAccountId() + }); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.beginSponsoringFutureReserves(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 6183: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.bumpSequence = bumpSequence; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation bumps sequence number. + * @function + * @alias Operation.bumpSequence + * @param {object} opts Options object + * @param {string} opts.bumpTo - Sequence number to bump to. + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.BumpSequenceOp} Operation + */ +function bumpSequence(opts) { + var attributes = {}; + if (typeof opts.bumpTo !== 'string') { + throw new Error('bumpTo must be a string'); + } + try { + // eslint-disable-next-line no-new + new _bignumber["default"](opts.bumpTo); + } catch (e) { + throw new Error('bumpTo must be a stringified number'); + } + attributes.bumpTo = _jsXdr.Hyper.fromString(opts.bumpTo); + var bumpSequenceOp = new _xdr["default"].BumpSequenceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.bumpSequence(bumpSequenceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2810: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.changeTrust = changeTrust; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +var _liquidity_pool_asset = __webpack_require__(2262); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var MAX_INT64 = '9223372036854775807'; + +/** + * Returns an XDR ChangeTrustOp. A "change trust" operation adds, removes, or updates a + * trust line for a given asset from the source account to another. + * @function + * @alias Operation.changeTrust + * @param {object} opts Options object + * @param {Asset | LiquidityPoolAsset} opts.asset - The asset for the trust line. + * @param {string} [opts.limit] - The limit for the asset, defaults to max int64. + * If the limit is set to "0" it deletes the trustline. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @returns {xdr.ChangeTrustOp} Change Trust operation + */ +function changeTrust(opts) { + var attributes = {}; + if (opts.asset instanceof _asset.Asset) { + attributes.line = opts.asset.toChangeTrustXDRObject(); + } else if (opts.asset instanceof _liquidity_pool_asset.LiquidityPoolAsset) { + attributes.line = opts.asset.toXDRObject(); + } else { + throw new TypeError('asset must be Asset or LiquidityPoolAsset'); + } + if (opts.limit !== undefined && !this.isValidAmount(opts.limit, true)) { + throw new TypeError(this.constructAmountRequirementsError('limit')); + } + if (opts.limit) { + attributes.limit = this._toXDRAmount(opts.limit); + } else { + attributes.limit = _jsXdr.Hyper.fromString(new _bignumber["default"](MAX_INT64).toString()); + } + if (opts.source) { + attributes.source = opts.source.masterKeypair; + } + var changeTrustOP = new _xdr["default"].ChangeTrustOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.changeTrust(changeTrustOP); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7239: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.claimClaimableBalance = claimClaimableBalance; +exports.validateClaimableBalanceId = validateClaimableBalanceId; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a new claim claimable balance operation. + * @function + * @alias Operation.claimClaimableBalance + * @param {object} opts Options object + * @param {string} opts.balanceId - The claimable balance id to be claimed. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} Claim claimable balance operation + * + * @example + * const op = Operation.claimClaimableBalance({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + */ +function claimClaimableBalance() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + validateClaimableBalanceId(opts.balanceId); + var attributes = {}; + attributes.balanceId = _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex'); + var claimClaimableBalanceOp = new _xdr["default"].ClaimClaimableBalanceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.claimClaimableBalance(claimClaimableBalanceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} +function validateClaimableBalanceId(balanceId) { + if (typeof balanceId !== 'string' || balanceId.length !== 8 + 64 /* 8b discriminant + 64b string */) { + throw new Error('must provide a valid claimable balance id'); + } +} + +/***/ }), + +/***/ 7651: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.clawback = clawback; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a clawback operation. + * + * @function + * @alias Operation.clawback + * + * @param {object} opts - Options object + * @param {Asset} opts.asset - The asset being clawed back. + * @param {string} opts.amount - The amount of the asset to claw back. + * @param {string} opts.from - The public key of the (optionally-muxed) + * account to claw back from. + * + * @param {string} [opts.source] - The source account for the operation. + * Defaults to the transaction's source account. + * + * @return {xdr.ClawbackOp} + * + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#clawback-operation + */ +function clawback(opts) { + var attributes = {}; + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + attributes.asset = opts.asset.toXDRObject(); + try { + attributes.from = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.from); + } catch (e) { + throw new Error('from address is invalid'); + } + var opAttributes = { + body: _xdr["default"].OperationBody.clawback(new _xdr["default"].ClawbackOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2203: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.clawbackClaimableBalance = clawbackClaimableBalance; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _claim_claimable_balance = __webpack_require__(7239); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a clawback operation for a claimable balance. + * + * @function + * @alias Operation.clawbackClaimableBalance + * @param {object} opts - Options object + * @param {string} opts.balanceId - The claimable balance ID to be clawed back. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @return {xdr.ClawbackClaimableBalanceOp} + * + * @example + * const op = Operation.clawbackClaimableBalance({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + * @link https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#clawback-claimable-balance-operation + */ +function clawbackClaimableBalance() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + (0, _claim_claimable_balance.validateClaimableBalanceId)(opts.balanceId); + var attributes = { + balanceId: _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex') + }; + var opAttributes = { + body: _xdr["default"].OperationBody.clawbackClaimableBalance(new _xdr["default"].ClawbackClaimableBalanceOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2115: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createAccount = createAccount; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create and fund a non existent account. + * @function + * @alias Operation.createAccount + * @param {object} opts Options object + * @param {string} opts.destination - Destination account ID to create an account for. + * @param {string} opts.startingBalance - Amount in XLM the account should be funded for. Must be greater + * than the [reserve balance amount](https://developers.stellar.org/docs/glossary/fees/). + * @param {string} [opts.source] - The source account for the payment. Defaults to the transaction's source account. + * @returns {xdr.CreateAccountOp} Create account operation + */ +function createAccount(opts) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.destination)) { + throw new Error('destination is invalid'); + } + if (!this.isValidAmount(opts.startingBalance, true)) { + throw new TypeError(this.constructAmountRequirementsError('startingBalance')); + } + var attributes = {}; + attributes.destination = _keypair.Keypair.fromPublicKey(opts.destination).xdrAccountId(); + attributes.startingBalance = this._toXDRAmount(opts.startingBalance); + var createAccountOp = new _xdr["default"].CreateAccountOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createAccount(createAccountOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 4831: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createClaimableBalance = createClaimableBalance; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a new claimable balance operation. + * + * @function + * @alias Operation.createClaimableBalance + * + * @param {object} opts Options object + * @param {Asset} opts.asset - The asset for the claimable balance. + * @param {string} opts.amount - Amount. + * @param {Claimant[]} opts.claimants - An array of Claimants + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} Create claimable balance operation + * + * @example + * const asset = new Asset( + * 'USD', + * 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * ); + * const amount = '100.0000000'; + * const claimants = [ + * new Claimant( + * 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ', + * Claimant.predicateBeforeAbsoluteTime("4102444800000") + * ) + * ]; + * + * const op = Operation.createClaimableBalance({ + * asset, + * amount, + * claimants + * }); + * + */ +function createClaimableBalance(opts) { + if (!(opts.asset instanceof _asset.Asset)) { + throw new Error('must provide an asset for create claimable balance operation'); + } + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + if (!Array.isArray(opts.claimants) || opts.claimants.length === 0) { + throw new Error('must provide at least one claimant'); + } + var attributes = {}; + attributes.asset = opts.asset.toXDRObject(); + attributes.amount = this._toXDRAmount(opts.amount); + attributes.claimants = Object.values(opts.claimants).map(function (c) { + return c.toXDRObject(); + }); + var createClaimableBalanceOp = new _xdr["default"].CreateClaimableBalanceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createClaimableBalance(createClaimableBalanceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 9073: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createPassiveSellOffer = createPassiveSellOffer; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR CreatePasiveSellOfferOp. A "create passive offer" operation creates an + * offer that won't consume a counter offer that exactly matches this offer. This is + * useful for offers just used as 1:1 exchanges for path payments. Use manage offer + * to manage this offer after using this operation to create it. + * @function + * @alias Operation.createPassiveSellOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.CreatePassiveSellOfferOp} Create Passive Sell Offer operation + */ +function createPassiveSellOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + var createPassiveSellOfferOp = new _xdr["default"].CreatePassiveSellOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createPassiveSellOffer(createPassiveSellOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 721: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.endSponsoringFutureReserves = endSponsoringFutureReserves; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create an "end sponsoring future reserves" operation. + * @function + * @alias Operation.endSponsoringFutureReserves + * @param {object} opts Options object + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.endSponsoringFutureReserves(); + * + */ +function endSponsoringFutureReserves() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.endSponsoringFutureReserves(); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 8752: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.extendFootprintTtl = extendFootprintTtl; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Builds an operation to bump the time-to-live (TTL) of the ledger keys. The + * keys for extension have to be provided in the read-only footprint of + * the transaction. + * + * The only parameter of the operation itself is the new minimum TTL for + * all the provided entries. If an entry already has a higher TTL, then it + * will just be skipped. + * + * TTL is the number of ledgers from the current ledger (exclusive) until + * the last ledger the entry is still considered alive (inclusive). Thus + * the exact ledger until the entries will live will only be determined + * when transaction has been applied. + * + * The footprint has to be specified in the transaction. See + * {@link TransactionBuilder}'s `opts.sorobanData` parameter, which is a + * {@link xdr.SorobanTransactionData} instance that contains fee data & resource + * usage as part of {@link xdr.SorobanResources}. + * + * @function + * @alias Operation.extendFootprintTtl + * + * @param {object} opts - object holding operation parameters + * @param {number} opts.extendTo - the minimum TTL that all the entries in + * the read-only footprint will have + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Extend Footprint TTL operation + * (xdr.ExtendFootprintTTLOp) + */ +function extendFootprintTtl(opts) { + var _opts$extendTo; + if (((_opts$extendTo = opts.extendTo) !== null && _opts$extendTo !== void 0 ? _opts$extendTo : -1) <= 0) { + throw new RangeError('extendTo has to be positive'); + } + var extendFootprintOp = new _xdr["default"].ExtendFootprintTtlOp({ + ext: new _xdr["default"].ExtensionPoint(0), + extendTo: opts.extendTo + }); + var opAttributes = { + body: _xdr["default"].OperationBody.extendFootprintTtl(extendFootprintOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7511: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "accountMerge", ({ + enumerable: true, + get: function get() { + return _account_merge.accountMerge; + } +})); +Object.defineProperty(exports, "allowTrust", ({ + enumerable: true, + get: function get() { + return _allow_trust.allowTrust; + } +})); +Object.defineProperty(exports, "beginSponsoringFutureReserves", ({ + enumerable: true, + get: function get() { + return _begin_sponsoring_future_reserves.beginSponsoringFutureReserves; + } +})); +Object.defineProperty(exports, "bumpSequence", ({ + enumerable: true, + get: function get() { + return _bump_sequence.bumpSequence; + } +})); +Object.defineProperty(exports, "changeTrust", ({ + enumerable: true, + get: function get() { + return _change_trust.changeTrust; + } +})); +Object.defineProperty(exports, "claimClaimableBalance", ({ + enumerable: true, + get: function get() { + return _claim_claimable_balance.claimClaimableBalance; + } +})); +Object.defineProperty(exports, "clawback", ({ + enumerable: true, + get: function get() { + return _clawback.clawback; + } +})); +Object.defineProperty(exports, "clawbackClaimableBalance", ({ + enumerable: true, + get: function get() { + return _clawback_claimable_balance.clawbackClaimableBalance; + } +})); +Object.defineProperty(exports, "createAccount", ({ + enumerable: true, + get: function get() { + return _create_account.createAccount; + } +})); +Object.defineProperty(exports, "createClaimableBalance", ({ + enumerable: true, + get: function get() { + return _create_claimable_balance.createClaimableBalance; + } +})); +Object.defineProperty(exports, "createCustomContract", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.createCustomContract; + } +})); +Object.defineProperty(exports, "createPassiveSellOffer", ({ + enumerable: true, + get: function get() { + return _create_passive_sell_offer.createPassiveSellOffer; + } +})); +Object.defineProperty(exports, "createStellarAssetContract", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.createStellarAssetContract; + } +})); +Object.defineProperty(exports, "endSponsoringFutureReserves", ({ + enumerable: true, + get: function get() { + return _end_sponsoring_future_reserves.endSponsoringFutureReserves; + } +})); +Object.defineProperty(exports, "extendFootprintTtl", ({ + enumerable: true, + get: function get() { + return _extend_footprint_ttl.extendFootprintTtl; + } +})); +Object.defineProperty(exports, "inflation", ({ + enumerable: true, + get: function get() { + return _inflation.inflation; + } +})); +Object.defineProperty(exports, "invokeContractFunction", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.invokeContractFunction; + } +})); +Object.defineProperty(exports, "invokeHostFunction", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.invokeHostFunction; + } +})); +Object.defineProperty(exports, "liquidityPoolDeposit", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_deposit.liquidityPoolDeposit; + } +})); +Object.defineProperty(exports, "liquidityPoolWithdraw", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_withdraw.liquidityPoolWithdraw; + } +})); +Object.defineProperty(exports, "manageBuyOffer", ({ + enumerable: true, + get: function get() { + return _manage_buy_offer.manageBuyOffer; + } +})); +Object.defineProperty(exports, "manageData", ({ + enumerable: true, + get: function get() { + return _manage_data.manageData; + } +})); +Object.defineProperty(exports, "manageSellOffer", ({ + enumerable: true, + get: function get() { + return _manage_sell_offer.manageSellOffer; + } +})); +Object.defineProperty(exports, "pathPaymentStrictReceive", ({ + enumerable: true, + get: function get() { + return _path_payment_strict_receive.pathPaymentStrictReceive; + } +})); +Object.defineProperty(exports, "pathPaymentStrictSend", ({ + enumerable: true, + get: function get() { + return _path_payment_strict_send.pathPaymentStrictSend; + } +})); +Object.defineProperty(exports, "payment", ({ + enumerable: true, + get: function get() { + return _payment.payment; + } +})); +Object.defineProperty(exports, "restoreFootprint", ({ + enumerable: true, + get: function get() { + return _restore_footprint.restoreFootprint; + } +})); +Object.defineProperty(exports, "revokeAccountSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeAccountSponsorship; + } +})); +Object.defineProperty(exports, "revokeClaimableBalanceSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeClaimableBalanceSponsorship; + } +})); +Object.defineProperty(exports, "revokeDataSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeDataSponsorship; + } +})); +Object.defineProperty(exports, "revokeLiquidityPoolSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeLiquidityPoolSponsorship; + } +})); +Object.defineProperty(exports, "revokeOfferSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeOfferSponsorship; + } +})); +Object.defineProperty(exports, "revokeSignerSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeSignerSponsorship; + } +})); +Object.defineProperty(exports, "revokeTrustlineSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeTrustlineSponsorship; + } +})); +Object.defineProperty(exports, "setOptions", ({ + enumerable: true, + get: function get() { + return _set_options.setOptions; + } +})); +Object.defineProperty(exports, "setTrustLineFlags", ({ + enumerable: true, + get: function get() { + return _set_trustline_flags.setTrustLineFlags; + } +})); +Object.defineProperty(exports, "uploadContractWasm", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.uploadContractWasm; + } +})); +var _manage_sell_offer = __webpack_require__(862); +var _create_passive_sell_offer = __webpack_require__(9073); +var _account_merge = __webpack_require__(4295); +var _allow_trust = __webpack_require__(3683); +var _bump_sequence = __webpack_require__(6183); +var _change_trust = __webpack_require__(2810); +var _create_account = __webpack_require__(2115); +var _create_claimable_balance = __webpack_require__(4831); +var _claim_claimable_balance = __webpack_require__(7239); +var _clawback_claimable_balance = __webpack_require__(2203); +var _inflation = __webpack_require__(7421); +var _manage_data = __webpack_require__(1411); +var _manage_buy_offer = __webpack_require__(1922); +var _path_payment_strict_receive = __webpack_require__(2075); +var _path_payment_strict_send = __webpack_require__(3874); +var _payment = __webpack_require__(3533); +var _set_options = __webpack_require__(2018); +var _begin_sponsoring_future_reserves = __webpack_require__(7505); +var _end_sponsoring_future_reserves = __webpack_require__(721); +var _revoke_sponsorship = __webpack_require__(7790); +var _clawback = __webpack_require__(7651); +var _set_trustline_flags = __webpack_require__(1804); +var _liquidity_pool_deposit = __webpack_require__(9845); +var _liquidity_pool_withdraw = __webpack_require__(4737); +var _invoke_host_function = __webpack_require__(4403); +var _extend_footprint_ttl = __webpack_require__(8752); +var _restore_footprint = __webpack_require__(149); + +/***/ }), + +/***/ 7421: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.inflation = inflation; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation generates the inflation. + * @function + * @alias Operation.inflation + * @param {object} [opts] Options object + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.InflationOp} Inflation operation + */ +function inflation() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.inflation(); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 4403: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createCustomContract = createCustomContract; +exports.createStellarAssetContract = createStellarAssetContract; +exports.invokeContractFunction = invokeContractFunction; +exports.invokeHostFunction = invokeHostFunction; +exports.uploadContractWasm = uploadContractWasm; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _address = __webpack_require__(1180); +var _asset = __webpack_require__(1764); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +/** + * Invokes a single smart contract host function. + * + * @function + * @alias Operation.invokeHostFunction + * + * @param {object} opts - options object + * @param {xdr.HostFunction} opts.func - host function to execute (with its + * wrapped parameters) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - list outlining the + * tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + * @see Operation.invokeContractFunction + * @see Operation.createCustomContract + * @see Operation.createStellarAssetContract + * @see Operation.uploadContractWasm + * @see Contract.call + */ +function invokeHostFunction(opts) { + if (!opts.func) { + throw new TypeError("host function invocation ('func') required (got ".concat(JSON.stringify(opts), ")")); + } + var invokeHostFunctionOp = new _xdr["default"].InvokeHostFunctionOp({ + hostFunction: opts.func, + auth: opts.auth || [] + }); + var opAttributes = { + body: _xdr["default"].OperationBody.invokeHostFunction(invokeHostFunctionOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Returns an operation that invokes a contract function. + * + * @function + * @alias Operation.invokeContractFunction + * + * @param {any} opts - the set of parameters + * @param {string} opts.contract - a strkey-fied contract address (`C...`) + * @param {string} opts.function - the name of the contract fn to invoke + * @param {xdr.ScVal[]} opts.args - parameters to pass to the function + * invocation (try {@link nativeToScVal} or {@link ScInt} to make building + * these easier) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see Operation.invokeHostFunction + * @see Contract.call + * @see Address + */ +function invokeContractFunction(opts) { + var c = new _address.Address(opts.contract); + if (c._type !== 'contract') { + throw new TypeError("expected contract strkey instance, got ".concat(c)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeInvokeContract(new _xdr["default"].InvokeContractArgs({ + contractAddress: c.toScAddress(), + functionName: opts["function"], + args: opts.args + })) + }); +} + +/** + * Returns an operation that creates a custom WASM contract and atomically + * invokes its constructor. + * + * @function + * @alias Operation.createCustomContract + * + * @param {any} opts - the set of parameters + * @param {Address} opts.address - the contract uploader address + * @param {Uint8Array|Buffer} opts.wasmHash - the SHA-256 hash of the contract + * WASM you're uploading (see {@link hash} and + * {@link Operation.uploadContractWasm}) + * @param {xdr.ScVal[]} [opts.constructorArgs] - the optional parameters to pass + * to the constructor of this contract (see {@link nativeToScVal} for ways to + * easily create these parameters from native JS values) + * @param {Uint8Array|Buffer} [opts.salt] - an optional, 32-byte salt to + * distinguish deployment instances of the same wasm from the same user (if + * omitted, one will be generated for you) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + */ +function createCustomContract(opts) { + var _opts$constructorArgs; + var salt = Buffer.from(opts.salt || getSalty()); + if (!opts.wasmHash || opts.wasmHash.length !== 32) { + throw new TypeError("expected hash(contract WASM) in 'opts.wasmHash', got ".concat(opts.wasmHash)); + } + if (salt.length !== 32) { + throw new TypeError("expected 32-byte salt in 'opts.salt', got ".concat(opts.wasmHash)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeCreateContractV2(new _xdr["default"].CreateContractArgsV2({ + executable: _xdr["default"].ContractExecutable.contractExecutableWasm(Buffer.from(opts.wasmHash)), + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAddress(new _xdr["default"].ContractIdPreimageFromAddress({ + address: opts.address.toScAddress(), + salt: salt + })), + constructorArgs: (_opts$constructorArgs = opts.constructorArgs) !== null && _opts$constructorArgs !== void 0 ? _opts$constructorArgs : [] + })) + }); +} + +/** + * Returns an operation that wraps a Stellar asset into a token contract. + * + * @function + * @alias Operation.createStellarAssetContract + * + * @param {any} opts - the set of parameters + * @param {Asset|string} opts.asset - the Stellar asset to wrap, either as an + * {@link Asset} object or in canonical form (SEP-11, `code:issuer`) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see https://stellar.org/protocol/sep-11#alphanum4-alphanum12 + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions + * @see + * https://soroban.stellar.org/docs/advanced-tutorials/stellar-asset-contract + * @see Operation.invokeHostFunction + */ +function createStellarAssetContract(opts) { + var asset = opts.asset; + if (typeof asset === 'string') { + var _asset$split = asset.split(':'), + _asset$split2 = _slicedToArray(_asset$split, 2), + code = _asset$split2[0], + issuer = _asset$split2[1]; + asset = new _asset.Asset(code, issuer); // handles 'xlm' by default + } + if (!(asset instanceof _asset.Asset)) { + throw new TypeError("expected Asset in 'opts.asset', got ".concat(asset)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeCreateContract(new _xdr["default"].CreateContractArgs({ + executable: _xdr["default"].ContractExecutable.contractExecutableStellarAsset(), + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAsset(asset.toXDRObject()) + })) + }); +} + +/** + * Returns an operation that uploads WASM for a contract. + * + * @function + * @alias Operation.uploadContractWasm + * + * @param {any} opts - the set of parameters + * @param {Uint8Array|Buffer} opts.wasm - a WASM blob to upload to the ledger + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + */ +function uploadContractWasm(opts) { + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeUploadContractWasm(Buffer.from(opts.wasm) // coalesce so we can drop `Buffer` someday + ) + }); +} + +/** @returns {Buffer} a random 256-bit "salt" value. */ +function getSalty() { + return _keypair.Keypair.random().xdrPublicKey().value(); // ed25519 is 256 bits, too +} + +/***/ }), + +/***/ 9845: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.liquidityPoolDeposit = liquidityPoolDeposit; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a liquidity pool deposit operation. + * + * @function + * @alias Operation.liquidityPoolDeposit + * @see https://developers.stellar.org/docs/start/list-of-operations/#liquidity-pool-deposit + * + * @param {object} opts - Options object + * @param {string} opts.liquidityPoolId - The liquidity pool ID. + * @param {string} opts.maxAmountA - Maximum amount of first asset to deposit. + * @param {string} opts.maxAmountB - Maximum amount of second asset to deposit. + * @param {number|string|BigNumber|Object} opts.minPrice - Minimum depositA/depositB price. + * @param {number} opts.minPrice.n - If `opts.minPrice` is an object: the price numerator + * @param {number} opts.minPrice.d - If `opts.minPrice` is an object: the price denominator + * @param {number|string|BigNumber|Object} opts.maxPrice - Maximum depositA/depositB price. + * @param {number} opts.maxPrice.n - If `opts.maxPrice` is an object: the price numerator + * @param {number} opts.maxPrice.d - If `opts.maxPrice` is an object: the price denominator + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting operation (xdr.LiquidityPoolDepositOp). + */ +function liquidityPoolDeposit() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var liquidityPoolId = opts.liquidityPoolId, + maxAmountA = opts.maxAmountA, + maxAmountB = opts.maxAmountB, + minPrice = opts.minPrice, + maxPrice = opts.maxPrice; + var attributes = {}; + if (!liquidityPoolId) { + throw new TypeError('liquidityPoolId argument is required'); + } + attributes.liquidityPoolId = _xdr["default"].PoolId.fromXDR(liquidityPoolId, 'hex'); + if (!this.isValidAmount(maxAmountA, true)) { + throw new TypeError(this.constructAmountRequirementsError('maxAmountA')); + } + attributes.maxAmountA = this._toXDRAmount(maxAmountA); + if (!this.isValidAmount(maxAmountB, true)) { + throw new TypeError(this.constructAmountRequirementsError('maxAmountB')); + } + attributes.maxAmountB = this._toXDRAmount(maxAmountB); + if (minPrice === undefined) { + throw new TypeError('minPrice argument is required'); + } + attributes.minPrice = this._toXDRPrice(minPrice); + if (maxPrice === undefined) { + throw new TypeError('maxPrice argument is required'); + } + attributes.maxPrice = this._toXDRPrice(maxPrice); + var liquidityPoolDepositOp = new _xdr["default"].LiquidityPoolDepositOp(attributes); + var opAttributes = { + body: _xdr["default"].OperationBody.liquidityPoolDeposit(liquidityPoolDepositOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 4737: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.liquidityPoolWithdraw = liquidityPoolWithdraw; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a liquidity pool withdraw operation. + * + * @function + * @alias Operation.liquidityPoolWithdraw + * @see https://developers.stellar.org/docs/start/list-of-operations/#liquidity-pool-withdraw + * + * @param {object} opts - Options object + * @param {string} opts.liquidityPoolId - The liquidity pool ID. + * @param {string} opts.amount - Amount of pool shares to withdraw. + * @param {string} opts.minAmountA - Minimum amount of first asset to withdraw. + * @param {string} opts.minAmountB - Minimum amount of second asset to withdraw. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting operation (xdr.LiquidityPoolWithdrawOp). + */ +function liquidityPoolWithdraw() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var attributes = {}; + if (!opts.liquidityPoolId) { + throw new TypeError('liquidityPoolId argument is required'); + } + attributes.liquidityPoolId = _xdr["default"].PoolId.fromXDR(opts.liquidityPoolId, 'hex'); + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (!this.isValidAmount(opts.minAmountA, true)) { + throw new TypeError(this.constructAmountRequirementsError('minAmountA')); + } + attributes.minAmountA = this._toXDRAmount(opts.minAmountA); + if (!this.isValidAmount(opts.minAmountB, true)) { + throw new TypeError(this.constructAmountRequirementsError('minAmountB')); + } + attributes.minAmountB = this._toXDRAmount(opts.minAmountB); + var liquidityPoolWithdrawOp = new _xdr["default"].LiquidityPoolWithdrawOp(attributes); + var opAttributes = { + body: _xdr["default"].OperationBody.liquidityPoolWithdraw(liquidityPoolWithdrawOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 1922: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.manageBuyOffer = manageBuyOffer; +var _jsXdr = __webpack_require__(3740); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR ManageBuyOfferOp. A "manage buy offer" operation creates, updates, or + * deletes a buy offer. + * @function + * @alias Operation.manageBuyOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.buyAmount - The total amount you're buying. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `buying` in terms of `selling`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.ManageBuyOfferOp} Manage Buy Offer operation + */ +function manageBuyOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.buyAmount, true)) { + throw new TypeError(this.constructAmountRequirementsError('buyAmount')); + } + attributes.buyAmount = this._toXDRAmount(opts.buyAmount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + if (opts.offerId !== undefined) { + opts.offerId = opts.offerId.toString(); + } else { + opts.offerId = '0'; + } + attributes.offerId = _jsXdr.Hyper.fromString(opts.offerId); + var manageBuyOfferOp = new _xdr["default"].ManageBuyOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageBuyOffer(manageBuyOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 1411: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.manageData = manageData; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation adds data entry to the ledger. + * @function + * @alias Operation.manageData + * @param {object} opts Options object + * @param {string} opts.name - The name of the data entry. + * @param {string|Buffer} opts.value - The value of the data entry. + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.ManageDataOp} Manage Data operation + */ +function manageData(opts) { + var attributes = {}; + if (!(typeof opts.name === 'string' && opts.name.length <= 64)) { + throw new Error('name must be a string, up to 64 characters'); + } + attributes.dataName = opts.name; + if (typeof opts.value !== 'string' && !Buffer.isBuffer(opts.value) && opts.value !== null) { + throw new Error('value must be a string, Buffer or null'); + } + if (typeof opts.value === 'string') { + attributes.dataValue = Buffer.from(opts.value); + } else { + attributes.dataValue = opts.value; + } + if (attributes.dataValue !== null && attributes.dataValue.length > 64) { + throw new Error('value cannot be longer that 64 bytes'); + } + var manageDataOp = new _xdr["default"].ManageDataOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageData(manageDataOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 862: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.manageSellOffer = manageSellOffer; +var _jsXdr = __webpack_require__(3740); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR ManageSellOfferOp. A "manage sell offer" operation creates, updates, or + * deletes an offer. + * @function + * @alias Operation.manageSellOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.ManageSellOfferOp} Manage Sell Offer operation + */ +function manageSellOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.amount, true)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + if (opts.offerId !== undefined) { + opts.offerId = opts.offerId.toString(); + } else { + opts.offerId = '0'; + } + attributes.offerId = _jsXdr.Hyper.fromString(opts.offerId); + var manageSellOfferOp = new _xdr["default"].ManageSellOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageSellOffer(manageSellOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2075: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.pathPaymentStrictReceive = pathPaymentStrictReceive; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a PathPaymentStrictReceive operation. + * + * A `PathPaymentStrictReceive` operation sends the specified amount to the + * destination account. It credits the destination with `destAmount` of + * `destAsset`, while debiting at most `sendMax` of `sendAsset` from the source. + * The transfer optionally occurs through a path. XLM payments create the + * destination account if it does not exist. + * + * @function + * @alias Operation.pathPaymentStrictReceive + * @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-receive + * + * @param {object} opts - Options object + * @param {Asset} opts.sendAsset - asset to pay with + * @param {string} opts.sendMax - maximum amount of sendAsset to send + * @param {string} opts.destination - destination account to send to + * @param {Asset} opts.destAsset - asset the destination will receive + * @param {string} opts.destAmount - amount the destination receives + * @param {Asset[]} opts.path - array of Asset objects to use as the path + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.PathPaymentStrictReceiveOp} the resulting path payment op + */ +function pathPaymentStrictReceive(opts) { + switch (true) { + case !opts.sendAsset: + throw new Error('Must specify a send asset'); + case !this.isValidAmount(opts.sendMax): + throw new TypeError(this.constructAmountRequirementsError('sendMax')); + case !opts.destAsset: + throw new Error('Must provide a destAsset for a payment operation'); + case !this.isValidAmount(opts.destAmount): + throw new TypeError(this.constructAmountRequirementsError('destAmount')); + default: + break; + } + var attributes = {}; + attributes.sendAsset = opts.sendAsset.toXDRObject(); + attributes.sendMax = this._toXDRAmount(opts.sendMax); + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.destAsset = opts.destAsset.toXDRObject(); + attributes.destAmount = this._toXDRAmount(opts.destAmount); + var path = opts.path ? opts.path : []; + attributes.path = path.map(function (x) { + return x.toXDRObject(); + }); + var payment = new _xdr["default"].PathPaymentStrictReceiveOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.pathPaymentStrictReceive(payment); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 3874: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.pathPaymentStrictSend = pathPaymentStrictSend; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a PathPaymentStrictSend operation. + * + * A `PathPaymentStrictSend` operation sends the specified amount to the + * destination account crediting at least `destMin` of `destAsset`, optionally + * through a path. XLM payments create the destination account if it does not + * exist. + * + * @function + * @alias Operation.pathPaymentStrictSend + * @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-send + * + * @param {object} opts - Options object + * @param {Asset} opts.sendAsset - asset to pay with + * @param {string} opts.sendAmount - amount of sendAsset to send (excluding fees) + * @param {string} opts.destination - destination account to send to + * @param {Asset} opts.destAsset - asset the destination will receive + * @param {string} opts.destMin - minimum amount of destAsset to be receive + * @param {Asset[]} opts.path - array of Asset objects to use as the path + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.Operation} the resulting path payment operation + * (xdr.PathPaymentStrictSendOp) + */ +function pathPaymentStrictSend(opts) { + switch (true) { + case !opts.sendAsset: + throw new Error('Must specify a send asset'); + case !this.isValidAmount(opts.sendAmount): + throw new TypeError(this.constructAmountRequirementsError('sendAmount')); + case !opts.destAsset: + throw new Error('Must provide a destAsset for a payment operation'); + case !this.isValidAmount(opts.destMin): + throw new TypeError(this.constructAmountRequirementsError('destMin')); + default: + break; + } + var attributes = {}; + attributes.sendAsset = opts.sendAsset.toXDRObject(); + attributes.sendAmount = this._toXDRAmount(opts.sendAmount); + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.destAsset = opts.destAsset.toXDRObject(); + attributes.destMin = this._toXDRAmount(opts.destMin); + var path = opts.path ? opts.path : []; + attributes.path = path.map(function (x) { + return x.toXDRObject(); + }); + var payment = new _xdr["default"].PathPaymentStrictSendOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.pathPaymentStrictSend(payment); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 3533: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.payment = payment; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a payment operation. + * + * @function + * @alias Operation.payment + * @see https://developers.stellar.org/docs/start/list-of-operations/#payment + * + * @param {object} opts - Options object + * @param {string} opts.destination - destination account ID + * @param {Asset} opts.asset - asset to send + * @param {string} opts.amount - amount to send + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting payment operation (xdr.PaymentOp) + */ +function payment(opts) { + if (!opts.asset) { + throw new Error('Must provide an asset for a payment operation'); + } + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + var attributes = {}; + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.asset = opts.asset.toXDRObject(); + attributes.amount = this._toXDRAmount(opts.amount); + var paymentOp = new _xdr["default"].PaymentOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.payment(paymentOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 149: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.restoreFootprint = restoreFootprint; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Builds an operation to restore the archived ledger entries specified + * by the ledger keys. + * + * The ledger keys to restore are specified separately from the operation + * in read-write footprint of the transaction. + * + * It takes no parameters because the relevant footprint is derived from the + * transaction itself. See {@link TransactionBuilder}'s `opts.sorobanData` + * parameter (or {@link TransactionBuilder.setSorobanData} / + * {@link TransactionBuilder.setLedgerKeys}), which is a + * {@link xdr.SorobanTransactionData} instance that contains fee data & resource + * usage as part of {@link xdr.SorobanTransactionData}. + * + * @function + * @alias Operation.restoreFootprint + * + * @param {object} [opts] - an optional set of parameters + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} a Bump Footprint Expiration operation + * (xdr.RestoreFootprintOp) + */ +function restoreFootprint() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var op = new _xdr["default"].RestoreFootprintOp({ + ext: new _xdr["default"].ExtensionPoint(0) + }); + var opAttributes = { + body: _xdr["default"].OperationBody.restoreFootprint(op) + }; + this.setSourceAccount(opAttributes, opts !== null && opts !== void 0 ? opts : {}); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7790: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.revokeAccountSponsorship = revokeAccountSponsorship; +exports.revokeClaimableBalanceSponsorship = revokeClaimableBalanceSponsorship; +exports.revokeDataSponsorship = revokeDataSponsorship; +exports.revokeLiquidityPoolSponsorship = revokeLiquidityPoolSponsorship; +exports.revokeOfferSponsorship = revokeOfferSponsorship; +exports.revokeSignerSponsorship = revokeSignerSponsorship; +exports.revokeTrustlineSponsorship = revokeTrustlineSponsorship; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +var _keypair = __webpack_require__(6691); +var _asset = __webpack_require__(1764); +var _liquidity_pool_id = __webpack_require__(9353); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a "revoke sponsorship" operation for an account. + * + * @function + * @alias Operation.revokeAccountSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The sponsored account ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeAccountSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * }); + * + */ +function revokeAccountSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.account(new _xdr["default"].LedgerKeyAccount({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId() + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a trustline. + * + * @function + * @alias Operation.revokeTrustlineSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID which owns the trustline. + * @param {Asset | LiquidityPoolId} opts.asset - The trustline asset. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeTrustlineSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * asset: new StellarBase.LiquidityPoolId( + * 'USDUSD', + * 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * ) + * }); + * + */ +function revokeTrustlineSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var asset; + if (opts.asset instanceof _asset.Asset) { + asset = opts.asset.toTrustLineXDRObject(); + } else if (opts.asset instanceof _liquidity_pool_id.LiquidityPoolId) { + asset = opts.asset.toXDRObject(); + } else { + throw new TypeError('asset must be an Asset or LiquidityPoolId'); + } + var ledgerKey = _xdr["default"].LedgerKey.trustline(new _xdr["default"].LedgerKeyTrustLine({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + asset: asset + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for an offer. + * + * @function + * @alias Operation.revokeOfferSponsorship + * @param {object} opts Options object + * @param {string} opts.seller - The account ID which created the offer. + * @param {string} opts.offerId - The offer ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeOfferSponsorship({ + * seller: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * offerId: '1234' + * }); + * + */ +function revokeOfferSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.seller)) { + throw new Error('seller is invalid'); + } + if (typeof opts.offerId !== 'string') { + throw new Error('offerId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.offer(new _xdr["default"].LedgerKeyOffer({ + sellerId: _keypair.Keypair.fromPublicKey(opts.seller).xdrAccountId(), + offerId: _xdr["default"].Int64.fromString(opts.offerId) + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a data entry. + * + * @function + * @alias Operation.revokeDataSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID which owns the data entry. + * @param {string} opts.name - The name of the data entry + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeDataSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * name: 'foo' + * }); + * + */ +function revokeDataSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + if (typeof opts.name !== 'string' || opts.name.length > 64) { + throw new Error('name must be a string, up to 64 characters'); + } + var ledgerKey = _xdr["default"].LedgerKey.data(new _xdr["default"].LedgerKeyData({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + dataName: opts.name + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a claimable balance. + * + * @function + * @alias Operation.revokeClaimableBalanceSponsorship + * @param {object} opts Options object + * @param {string} opts.balanceId - The sponsored claimable balance ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeClaimableBalanceSponsorship({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + */ +function revokeClaimableBalanceSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (typeof opts.balanceId !== 'string') { + throw new Error('balanceId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.claimableBalance(new _xdr["default"].LedgerKeyClaimableBalance({ + balanceId: _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex') + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Creates a "revoke sponsorship" operation for a liquidity pool. + * + * @function + * @alias Operation.revokeLiquidityPoolSponsorship + * @param {object} opts – Options object. + * @param {string} opts.liquidityPoolId - The sponsored liquidity pool ID in 'hex' string. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr Operation. + * + * @example + * const op = Operation.revokeLiquidityPoolSponsorship({ + * liquidityPoolId: 'dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7', + * }); + * + */ +function revokeLiquidityPoolSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (typeof opts.liquidityPoolId !== 'string') { + throw new Error('liquidityPoolId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.liquidityPool(new _xdr["default"].LedgerKeyLiquidityPool({ + liquidityPoolId: _xdr["default"].PoolId.fromXDR(opts.liquidityPoolId, 'hex') + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = { + body: _xdr["default"].OperationBody.revokeSponsorship(op) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a signer. + * + * @function + * @alias Operation.revokeSignerSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID where the signer sponsorship is being removed from. + * @param {object} opts.signer - The signer whose sponsorship is being removed. + * @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer. + * @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string). + * @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeSignerSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * signer: { + * ed25519PublicKey: 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ' + * } + * }) + * + */ +function revokeSignerSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var key; + if (opts.signer.ed25519PublicKey) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) { + throw new Error('signer.ed25519PublicKey is invalid.'); + } + var rawKey = _strkey.StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey); + key = new _xdr["default"].SignerKey.signerKeyTypeEd25519(rawKey); + } else if (opts.signer.preAuthTx) { + var buffer; + if (typeof opts.signer.preAuthTx === 'string') { + buffer = Buffer.from(opts.signer.preAuthTx, 'hex'); + } else { + buffer = opts.signer.preAuthTx; + } + if (!(Buffer.isBuffer(buffer) && buffer.length === 32)) { + throw new Error('signer.preAuthTx must be 32 bytes Buffer.'); + } + key = new _xdr["default"].SignerKey.signerKeyTypePreAuthTx(buffer); + } else if (opts.signer.sha256Hash) { + var _buffer; + if (typeof opts.signer.sha256Hash === 'string') { + _buffer = Buffer.from(opts.signer.sha256Hash, 'hex'); + } else { + _buffer = opts.signer.sha256Hash; + } + if (!(Buffer.isBuffer(_buffer) && _buffer.length === 32)) { + throw new Error('signer.sha256Hash must be 32 bytes Buffer.'); + } + key = new _xdr["default"].SignerKey.signerKeyTypeHashX(_buffer); + } else { + throw new Error('signer is invalid'); + } + var signer = new _xdr["default"].RevokeSponsorshipOpSigner({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + signerKey: key + }); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipSigner(signer); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2018: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.setOptions = setOptions; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/* eslint-disable no-param-reassign */ + +function weightCheckFunction(value, name) { + if (value >= 0 && value <= 255) { + return true; + } + throw new Error("".concat(name, " value must be between 0 and 255")); +} + +/** + * Returns an XDR SetOptionsOp. A "set options" operations set or clear account flags, + * set the account's inflation destination, and/or add new signers to the account. + * The flags used in `opts.clearFlags` and `opts.setFlags` can be the following: + * - `{@link AuthRequiredFlag}` + * - `{@link AuthRevocableFlag}` + * - `{@link AuthImmutableFlag}` + * - `{@link AuthClawbackEnabledFlag}` + * + * It's possible to set/clear multiple flags at once using logical or. + * + * @function + * @alias Operation.setOptions + * + * @param {object} opts Options object + * @param {string} [opts.inflationDest] - Set this account ID as the account's inflation destination. + * @param {(number|string)} [opts.clearFlags] - Bitmap integer for which account flags to clear. + * @param {(number|string)} [opts.setFlags] - Bitmap integer for which account flags to set. + * @param {number|string} [opts.masterWeight] - The master key weight. + * @param {number|string} [opts.lowThreshold] - The sum weight for the low threshold. + * @param {number|string} [opts.medThreshold] - The sum weight for the medium threshold. + * @param {number|string} [opts.highThreshold] - The sum weight for the high threshold. + * @param {object} [opts.signer] - Add or remove a signer from the account. The signer is + * deleted if the weight is 0. Only one of `ed25519PublicKey`, `sha256Hash`, `preAuthTx` should be defined. + * @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer. + * @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string) of preimage that will unlock funds. Preimage should be used as signature of future transaction. + * @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction that will unlock funds. + * @param {string} [opts.signer.ed25519SignedPayload] - Signed payload signer (ed25519 public key + raw payload) for atomic transaction signature disclosure. + * @param {number|string} [opts.signer.weight] - The weight of the new signer (0 to delete or 1-255) + * @param {string} [opts.homeDomain] - sets the home domain used for reverse federation lookup. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * + * @returns {xdr.SetOptionsOp} XDR operation + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +function setOptions(opts) { + var attributes = {}; + if (opts.inflationDest) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.inflationDest)) { + throw new Error('inflationDest is invalid'); + } + attributes.inflationDest = _keypair.Keypair.fromPublicKey(opts.inflationDest).xdrAccountId(); + } + attributes.clearFlags = this._checkUnsignedIntValue('clearFlags', opts.clearFlags); + attributes.setFlags = this._checkUnsignedIntValue('setFlags', opts.setFlags); + attributes.masterWeight = this._checkUnsignedIntValue('masterWeight', opts.masterWeight, weightCheckFunction); + attributes.lowThreshold = this._checkUnsignedIntValue('lowThreshold', opts.lowThreshold, weightCheckFunction); + attributes.medThreshold = this._checkUnsignedIntValue('medThreshold', opts.medThreshold, weightCheckFunction); + attributes.highThreshold = this._checkUnsignedIntValue('highThreshold', opts.highThreshold, weightCheckFunction); + if (opts.homeDomain !== undefined && typeof opts.homeDomain !== 'string') { + throw new TypeError('homeDomain argument must be of type String'); + } + attributes.homeDomain = opts.homeDomain; + if (opts.signer) { + var weight = this._checkUnsignedIntValue('signer.weight', opts.signer.weight, weightCheckFunction); + var key; + var setValues = 0; + if (opts.signer.ed25519PublicKey) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) { + throw new Error('signer.ed25519PublicKey is invalid.'); + } + var rawKey = _strkey.StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey); + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypeEd25519(rawKey); + setValues += 1; + } + if (opts.signer.preAuthTx) { + if (typeof opts.signer.preAuthTx === 'string') { + opts.signer.preAuthTx = Buffer.from(opts.signer.preAuthTx, 'hex'); + } + if (!(Buffer.isBuffer(opts.signer.preAuthTx) && opts.signer.preAuthTx.length === 32)) { + throw new Error('signer.preAuthTx must be 32 bytes Buffer.'); + } + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypePreAuthTx(opts.signer.preAuthTx); + setValues += 1; + } + if (opts.signer.sha256Hash) { + if (typeof opts.signer.sha256Hash === 'string') { + opts.signer.sha256Hash = Buffer.from(opts.signer.sha256Hash, 'hex'); + } + if (!(Buffer.isBuffer(opts.signer.sha256Hash) && opts.signer.sha256Hash.length === 32)) { + throw new Error('signer.sha256Hash must be 32 bytes Buffer.'); + } + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypeHashX(opts.signer.sha256Hash); + setValues += 1; + } + if (opts.signer.ed25519SignedPayload) { + if (!_strkey.StrKey.isValidSignedPayload(opts.signer.ed25519SignedPayload)) { + throw new Error('signer.ed25519SignedPayload is invalid.'); + } + var _rawKey = _strkey.StrKey.decodeSignedPayload(opts.signer.ed25519SignedPayload); + var signedPayloadXdr = _xdr["default"].SignerKeyEd25519SignedPayload.fromXDR(_rawKey); + + // eslint-disable-next-line new-cap + key = _xdr["default"].SignerKey.signerKeyTypeEd25519SignedPayload(signedPayloadXdr); + setValues += 1; + } + if (setValues !== 1) { + throw new Error('Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx.'); + } + attributes.signer = new _xdr["default"].Signer({ + key: key, + weight: weight + }); + } + var setOptionsOp = new _xdr["default"].SetOptionsOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.setOptions(setOptionsOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 1804: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.setTrustLineFlags = setTrustLineFlags; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/** + * Creates a trustline flag configuring operation. + * + * For the flags, set them to true to enable them and false to disable them. Any + * unmodified operations will be marked `undefined` in the result. + * + * Note that you can only **clear** the clawbackEnabled flag set; it must be set + * account-wide via operations.SetOptions (setting + * xdr.AccountFlags.clawbackEnabled). + * + * @function + * @alias Operation.setTrustLineFlags + * + * @param {object} opts - Options object + * @param {string} opts.trustor - the account whose trustline this is + * @param {Asset} opts.asset - the asset on the trustline + * @param {object} opts.flags - the set of flags to modify + * + * @param {bool} [opts.flags.authorized] - authorize account to perform + * transactions with its credit + * @param {bool} [opts.flags.authorizedToMaintainLiabilities] - authorize + * account to maintain and reduce liabilities for its credit + * @param {bool} [opts.flags.clawbackEnabled] - stop claimable balances on + * this trustlines from having clawbacks enabled (this flag can only be set + * to false!) + * @param {string} [opts.source] - The source account for the operation. + * Defaults to the transaction's source account. + * + * @note You must include at least one flag. + * + * @return {xdr.SetTrustLineFlagsOp} + * + * @link xdr.AccountFlags + * @link xdr.TrustLineFlags + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#set-trustline-flags-operation + * @see https://developers.stellar.org/docs/start/list-of-operations/#set-options + */ +function setTrustLineFlags() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var attributes = {}; + if (_typeof(opts.flags) !== 'object' || Object.keys(opts.flags).length === 0) { + throw new Error('opts.flags must be a map of boolean flags to modify'); + } + var mapping = { + authorized: _xdr["default"].TrustLineFlags.authorizedFlag(), + authorizedToMaintainLiabilities: _xdr["default"].TrustLineFlags.authorizedToMaintainLiabilitiesFlag(), + clawbackEnabled: _xdr["default"].TrustLineFlags.trustlineClawbackEnabledFlag() + }; + + /* eslint no-bitwise: "off" */ + var clearFlag = 0; + var setFlag = 0; + Object.keys(opts.flags).forEach(function (flagName) { + if (!Object.prototype.hasOwnProperty.call(mapping, flagName)) { + throw new Error("unsupported flag name specified: ".concat(flagName)); + } + var flagValue = opts.flags[flagName]; + var bit = mapping[flagName].value; + if (flagValue === true) { + setFlag |= bit; + } else if (flagValue === false) { + clearFlag |= bit; + } + }); + attributes.trustor = _keypair.Keypair.fromPublicKey(opts.trustor).xdrAccountId(); + attributes.asset = opts.asset.toXDRObject(); + attributes.clearFlags = clearFlag; + attributes.setFlags = setFlag; + var opAttributes = { + body: _xdr["default"].OperationBody.setTrustLineFlags(new _xdr["default"].SetTrustLineFlagsOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7177: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.nativeToScVal = nativeToScVal; +exports.scValToNative = scValToNative; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _address = __webpack_require__(1180); +var _contract = __webpack_require__(7452); +var _index = __webpack_require__(8549); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/** + * Attempts to convert native types into smart contract values + * ({@link xdr.ScVal}). + * + * Provides conversions from smart contract XDR values ({@link xdr.ScVal}) to + * native JavaScript types. + * + * The conversions are as follows: + * + * - xdr.ScVal -> passthrough + * - null/undefined -> scvVoid + * - string -> scvString (a copy is made) + * - UintArray8 -> scvBytes (a copy is made) + * - boolean -> scvBool + * + * - number/bigint -> the smallest possible XDR integer type that will fit the + * input value (if you want a specific type, use {@link ScInt}) + * + * - {@link Address} or {@link Contract} -> scvAddress (for contracts and + * public keys) + * + * - Array -> scvVec after attempting to convert each item of type `T` to an + * xdr.ScVal (recursively). note that all values must be the same type! + * + * - object -> scvMap after attempting to convert each key and value to an + * xdr.ScVal (recursively). note that there is no restriction on types + * matching anywhere (unlike arrays) + * + * When passing an integer-like native value, you can also optionally specify a + * type which will force a particular interpretation of that value. + * + * Note that not all type specifications are compatible with all `ScVal`s, e.g. + * `toScVal("a string", {type: "i256"})` will throw. + * + * @param {any} val - a native (or convertible) input value to wrap + * @param {object} [opts] - an optional set of hints around the type of + * conversion you'd like to see + * @param {string} [opts.type] - there is different behavior for different input + * types for `val`: + * + * - when `val` is an integer-like type (i.e. number|bigint), this will be + * forwarded to {@link ScInt} or forced to be u32/i32. + * + * - when `val` is an array type, this is forwarded to the recursion + * + * - when `val` is an object type (key-value entries), this should be an + * object in which each key has a pair of types (to represent forced types + * for the key and the value), where `null` (or a missing entry) indicates + * the default interpretation(s) (refer to the examples, below) + * + * - when `val` is a string type, this can be 'string' or 'symbol' to force + * a particular interpretation of `val`. + * + * - when `val` is a bytes-like type, this can be 'string', 'symbol', or + * 'bytes' to force a particular interpretation + * + * As a simple example, `nativeToScVal("hello", {type: 'symbol'})` will + * return an `scvSymbol`, whereas without the type it would have been an + * `scvString`. + * + * @returns {xdr.ScVal} a wrapped, smart, XDR version of the input value + * @throws {TypeError} if... + * - there are arrays with more than one type in them + * - there are values that do not have a sensible conversion (e.g. random XDR + * types, custom classes) + * - the type of the input object (or some inner value of said object) cannot + * be determined (via `typeof`) + * - the type you specified (via `opts.type`) is incompatible with the value + * you passed in (`val`), e.g. `nativeToScVal("a string", { type: 'i128' })`, + * though this does not apply for types that ignore `opts` (e.g. addresses). + * @see scValToNative + * + * @example + * nativeToScVal(1000); // gives ScValType === scvU64 + * nativeToScVal(1000n); // gives ScValType === scvU64 + * nativeToScVal(1n << 100n); // gives ScValType === scvU128 + * nativeToScVal(1000, { type: 'u32' }); // gives ScValType === scvU32 + * nativeToScVal(1000, { type: 'i125' }); // gives ScValType === scvI256 + * nativeToScVal("a string"); // gives ScValType === scvString + * nativeToScVal("a string", { type: 'symbol' }); // gives scvSymbol + * nativeToScVal(new Uint8Array(5)); // scvBytes + * nativeToScVal(new Uint8Array(5), { type: 'symbol' }); // scvSymbol + * nativeToScVal(null); // scvVoid + * nativeToScVal(true); // scvBool + * nativeToScVal([1, 2, 3]); // gives scvVec with each element as scvU64 + * nativeToScVal([1, 2, 3], { type: 'i128' }); // scvVec + * nativeToScVal({ 'hello': 1, 'world': [ true, false ] }, { + * type: { + * 'hello': [ 'symbol', 'i128' ], + * } + * }) + * // gives scvMap with entries: [ + * // [ scvSymbol, scvI128 ], + * // [ scvString, scvArray ] + * // ] + * + * @example + * import { + * nativeToScVal, + * scValToNative, + * ScInt, + * xdr + * } from '@stellar/stellar-base'; + * + * let gigaMap = { + * bool: true, + * void: null, + * u32: xdr.ScVal.scvU32(1), + * i32: xdr.ScVal.scvI32(1), + * u64: 1n, + * i64: -1n, + * u128: new ScInt(1).toU128(), + * i128: new ScInt(1).toI128(), + * u256: new ScInt(1).toU256(), + * i256: new ScInt(1).toI256(), + * map: { + * arbitrary: 1n, + * nested: 'values', + * etc: false + * }, + * vec: ['same', 'type', 'list'], + * }; + * + * // then, simply: + * let scv = nativeToScVal(gigaMap); // scv.switch() == xdr.ScValType.scvMap() + * + * // then... + * someContract.call("method", scv); + * + * // Similarly, the inverse should work: + * scValToNative(scv) == gigaMap; // true + */ +function nativeToScVal(val) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + switch (_typeof(val)) { + case 'object': + { + var _val$constructor$name, _val$constructor; + if (val === null) { + return _xdr["default"].ScVal.scvVoid(); + } + if (val instanceof _xdr["default"].ScVal) { + return val; // should we copy? + } + if (val instanceof _address.Address) { + return val.toScVal(); + } + if (val instanceof _contract.Contract) { + return val.address().toScVal(); + } + if (val instanceof Uint8Array || Buffer.isBuffer(val)) { + var _opts$type; + var copy = Uint8Array.from(val); + switch ((_opts$type = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type !== void 0 ? _opts$type : 'bytes') { + case 'bytes': + return _xdr["default"].ScVal.scvBytes(copy); + case 'symbol': + return _xdr["default"].ScVal.scvSymbol(copy); + case 'string': + return _xdr["default"].ScVal.scvString(copy); + default: + throw new TypeError("invalid type (".concat(opts.type, ") specified for bytes-like value")); + } + } + if (Array.isArray(val)) { + if (val.length > 0 && val.some(function (v) { + return _typeof(v) !== _typeof(val[0]); + })) { + throw new TypeError("array values (".concat(val, ") must have the same type (types: ").concat(val.map(function (v) { + return _typeof(v); + }).join(','), ")")); + } + return _xdr["default"].ScVal.scvVec(val.map(function (v) { + return nativeToScVal(v, opts); + })); + } + if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : '') !== 'Object') { + var _val$constructor2; + throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")")); + } + return _xdr["default"].ScVal.scvMap(Object.entries(val) + // The Soroban runtime expects maps to have their keys in sorted + // order, so let's do that here as part of the conversion to prevent + // confusing error messages on execution. + .sort(function (_ref, _ref2) { + var _ref3 = _slicedToArray(_ref, 1), + key1 = _ref3[0]; + var _ref4 = _slicedToArray(_ref2, 1), + key2 = _ref4[0]; + return key1.localeCompare(key2); + }).map(function (_ref5) { + var _k, _opts$type2; + var _ref6 = _slicedToArray(_ref5, 2), + k = _ref6[0], + v = _ref6[1]; + // the type can be specified with an entry for the key and the value, + // e.g. val = { 'hello': 1 } and opts.type = { hello: [ 'symbol', + // 'u128' ]} or you can use `null` for the default interpretation + var _ref7 = (_k = ((_opts$type2 = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type2 !== void 0 ? _opts$type2 : {})[k]) !== null && _k !== void 0 ? _k : [null, null], + _ref8 = _slicedToArray(_ref7, 2), + keyType = _ref8[0], + valType = _ref8[1]; + var keyOpts = keyType ? { + type: keyType + } : {}; + var valOpts = valType ? { + type: valType + } : {}; + return new _xdr["default"].ScMapEntry({ + key: nativeToScVal(k, keyOpts), + val: nativeToScVal(v, valOpts) + }); + })); + } + case 'number': + case 'bigint': + switch (opts === null || opts === void 0 ? void 0 : opts.type) { + case 'u32': + return _xdr["default"].ScVal.scvU32(val); + case 'i32': + return _xdr["default"].ScVal.scvI32(val); + default: + break; + } + return new _index.ScInt(val, { + type: opts === null || opts === void 0 ? void 0 : opts.type + }).toScVal(); + case 'string': + { + var _opts$type3; + var optType = (_opts$type3 = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type3 !== void 0 ? _opts$type3 : 'string'; + switch (optType) { + case 'string': + return _xdr["default"].ScVal.scvString(val); + case 'symbol': + return _xdr["default"].ScVal.scvSymbol(val); + case 'address': + return new _address.Address(val).toScVal(); + case 'u32': + return _xdr["default"].ScVal.scvU32(parseInt(val, 10)); + case 'i32': + return _xdr["default"].ScVal.scvI32(parseInt(val, 10)); + default: + if (_index.XdrLargeInt.isType(optType)) { + return new _index.XdrLargeInt(optType, val).toScVal(); + } + throw new TypeError("invalid type (".concat(opts.type, ") specified for string value")); + } + } + case 'boolean': + return _xdr["default"].ScVal.scvBool(val); + case 'undefined': + return _xdr["default"].ScVal.scvVoid(); + case 'function': + // FIXME: Is this too helpful? + return nativeToScVal(val()); + default: + throw new TypeError("failed to convert typeof ".concat(_typeof(val), " (").concat(val, ")")); + } +} + +/** + * Given a smart contract value, attempt to convert it to a native type. + * Possible conversions include: + * + * - void -> `null` + * - u32, i32 -> `number` + * - u64, i64, u128, i128, u256, i256 -> `bigint` + * - vec -> `Array` of any of the above (via recursion) + * - map -> key-value object of any of the above (via recursion) + * - bool -> `boolean` + * - bytes -> `Uint8Array` + * - symbol -> `string` + * - string -> `string` IF the underlying buffer can be decoded as ascii/utf8, + * `Uint8Array` of the raw contents in any error case + * + * If no viable conversion can be determined, this just "unwraps" the smart + * value to return its underlying XDR value. + * + * @param {xdr.ScVal} scv - the input smart contract value + * + * @returns {any} + * @see nativeToScVal + */ +function scValToNative(scv) { + var _scv$vec, _scv$map; + // we use the verbose xdr.ScValType..value form here because it's faster + // than string comparisons and the underlying constants never need to be + // updated + switch (scv["switch"]().value) { + case _xdr["default"].ScValType.scvVoid().value: + return null; + + // these can be converted to bigints directly + case _xdr["default"].ScValType.scvU64().value: + case _xdr["default"].ScValType.scvI64().value: + return scv.value().toBigInt(); + + // these can be parsed by internal abstractions note that this can also + // handle the above two cases, but it's not as efficient (another + // type-check, parsing, etc.) + case _xdr["default"].ScValType.scvU128().value: + case _xdr["default"].ScValType.scvI128().value: + case _xdr["default"].ScValType.scvU256().value: + case _xdr["default"].ScValType.scvI256().value: + return (0, _index.scValToBigInt)(scv); + case _xdr["default"].ScValType.scvVec().value: + return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(scValToNative); + case _xdr["default"].ScValType.scvAddress().value: + return _address.Address.fromScVal(scv).toString(); + case _xdr["default"].ScValType.scvMap().value: + return Object.fromEntries(((_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []).map(function (entry) { + return [scValToNative(entry.key()), scValToNative(entry.val())]; + })); + + // these return the primitive type directly + case _xdr["default"].ScValType.scvBool().value: + case _xdr["default"].ScValType.scvU32().value: + case _xdr["default"].ScValType.scvI32().value: + case _xdr["default"].ScValType.scvBytes().value: + return scv.value(); + + // Symbols are limited to [a-zA-Z0-9_]+, so we can safely make ascii strings + // + // Strings, however, are "presented" as strings and we treat them as such + // (in other words, string = bytes with a hint that it's text). If the user + // encoded non-printable bytes in their string value, that's on them. + // + // Note that we assume a utf8 encoding (ascii-compatible). For other + // encodings, you should probably use bytes anyway. If it cannot be decoded, + // the raw bytes are returned. + case _xdr["default"].ScValType.scvSymbol().value: + case _xdr["default"].ScValType.scvString().value: + { + var v = scv.value(); // string|Buffer + if (Buffer.isBuffer(v) || ArrayBuffer.isView(v)) { + try { + return new TextDecoder().decode(v); + } catch (e) { + return new Uint8Array(v.buffer); // copy of bytes + } + } + return v; // string already + } + + // these can be converted to bigint + case _xdr["default"].ScValType.scvTimepoint().value: + case _xdr["default"].ScValType.scvDuration().value: + return new _xdr["default"].Uint64(scv.value()).toBigInt(); + case _xdr["default"].ScValType.scvError().value: + switch (scv.error()["switch"]().value) { + // Distinguish errors from the user contract. + case _xdr["default"].ScErrorType.sceContract().value: + return { + type: 'contract', + code: scv.error().contractCode() + }; + default: + { + var err = scv.error(); + return { + type: 'system', + code: err.code().value, + value: err.code().name + }; + } + } + + // in the fallthrough case, just return the underlying value directly + default: + return scv.value(); + } +} + +/***/ }), + +/***/ 225: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.SignerKey = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * A container class with helpers to convert between signer keys + * (`xdr.SignerKey`) and {@link StrKey}s. + * + * It's primarly used for manipulating the `extraSigners` precondition on a + * {@link Transaction}. + * + * @see {@link TransactionBuilder.setExtraSigners} + */ +var SignerKey = exports.SignerKey = /*#__PURE__*/function () { + function SignerKey() { + _classCallCheck(this, SignerKey); + } + return _createClass(SignerKey, null, [{ + key: "decodeAddress", + value: + /** + * Decodes a StrKey address into an xdr.SignerKey instance. + * + * Only ED25519 public keys (G...), pre-auth transactions (T...), hashes + * (H...), and signed payloads (P...) can be signer keys. + * + * @param {string} address a StrKey-encoded signer address + * @returns {xdr.SignerKey} + */ + function decodeAddress(address) { + var signerKeyMap = { + ed25519PublicKey: _xdr["default"].SignerKey.signerKeyTypeEd25519, + preAuthTx: _xdr["default"].SignerKey.signerKeyTypePreAuthTx, + sha256Hash: _xdr["default"].SignerKey.signerKeyTypeHashX, + signedPayload: _xdr["default"].SignerKey.signerKeyTypeEd25519SignedPayload + }; + var vb = _strkey.StrKey.getVersionByteForPrefix(address); + var encoder = signerKeyMap[vb]; + if (!encoder) { + throw new Error("invalid signer key type (".concat(vb, ")")); + } + var raw = (0, _strkey.decodeCheck)(vb, address); + switch (vb) { + case 'signedPayload': + return encoder(new _xdr["default"].SignerKeyEd25519SignedPayload({ + ed25519: raw.slice(0, 32), + payload: raw.slice(32 + 4) + })); + case 'ed25519PublicKey': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + default: + return encoder(raw); + } + } + + /** + * Encodes a signer key into its StrKey equivalent. + * + * @param {xdr.SignerKey} signerKey the signer + * @returns {string} the StrKey representation of the signer + */ + }, { + key: "encodeSignerKey", + value: function encodeSignerKey(signerKey) { + var strkeyType; + var raw; + switch (signerKey["switch"]()) { + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519(): + strkeyType = 'ed25519PublicKey'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypePreAuthTx(): + strkeyType = 'preAuthTx'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypeHashX(): + strkeyType = 'sha256Hash'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519SignedPayload(): + strkeyType = 'signedPayload'; + raw = signerKey.ed25519SignedPayload().toXDR('raw'); + break; + default: + throw new Error("invalid SignerKey (type: ".concat(signerKey["switch"](), ")")); + } + return (0, _strkey.encodeCheck)(strkeyType, raw); + } + }]); +}(); + +/***/ }), + +/***/ 15: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.FastSigning = void 0; +exports.generate = generate; +exports.sign = sign; +exports.verify = verify; +// This module provides the signing functionality used by the stellar network +// The code below may look a little strange... this is because we try to provide +// the most efficient signing method possible. First, we try to load the +// native `sodium-native` package for node.js environments, and if that fails we +// fallback to `tweetnacl` + +var actualMethods = {}; + +/** + * Use this flag to check if fast signing (provided by `sodium-native` package) is available. + * If your app is signing a large number of transaction or verifying a large number + * of signatures make sure `sodium-native` package is installed. + */ +var FastSigning = exports.FastSigning = checkFastSigning(); +function sign(data, secretKey) { + return actualMethods.sign(data, secretKey); +} +function verify(data, signature, publicKey) { + return actualMethods.verify(data, signature, publicKey); +} +function generate(secretKey) { + return actualMethods.generate(secretKey); +} +function checkFastSigning() { + return typeof window === 'undefined' ? checkFastSigningNode() : checkFastSigningBrowser(); +} +function checkFastSigningNode() { + // NOTE: we use commonjs style require here because es6 imports + // can only occur at the top level. thanks, obama. + var sodium; + try { + // eslint-disable-next-line + sodium = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module 'sodium-native'"); e.code = 'MODULE_NOT_FOUND'; throw e; }())); + } catch (err) { + return checkFastSigningBrowser(); + } + if (!Object.keys(sodium).length) { + return checkFastSigningBrowser(); + } + actualMethods.generate = function (secretKey) { + var pk = Buffer.alloc(sodium.crypto_sign_PUBLICKEYBYTES); + var sk = Buffer.alloc(sodium.crypto_sign_SECRETKEYBYTES); + sodium.crypto_sign_seed_keypair(pk, sk, secretKey); + return pk; + }; + actualMethods.sign = function (data, secretKey) { + data = Buffer.from(data); + var signature = Buffer.alloc(sodium.crypto_sign_BYTES); + sodium.crypto_sign_detached(signature, data, secretKey); + return signature; + }; + actualMethods.verify = function (data, signature, publicKey) { + data = Buffer.from(data); + try { + return sodium.crypto_sign_verify_detached(signature, data, publicKey); + } catch (e) { + return false; + } + }; + return true; +} +function checkFastSigningBrowser() { + // fallback to `tweetnacl` if we're in the browser or + // if there was a failure installing `sodium-native` + // eslint-disable-next-line + var nacl = __webpack_require__(4940); + actualMethods.generate = function (secretKey) { + var secretKeyUint8 = new Uint8Array(secretKey); + var naclKeys = nacl.sign.keyPair.fromSeed(secretKeyUint8); + return Buffer.from(naclKeys.publicKey); + }; + actualMethods.sign = function (data, secretKey) { + data = Buffer.from(data); + data = new Uint8Array(data.toJSON().data); + secretKey = new Uint8Array(secretKey.toJSON().data); + var signature = nacl.sign.detached(data, secretKey); + return Buffer.from(signature); + }; + actualMethods.verify = function (data, signature, publicKey) { + data = Buffer.from(data); + data = new Uint8Array(data.toJSON().data); + signature = new Uint8Array(signature.toJSON().data); + publicKey = new Uint8Array(publicKey.toJSON().data); + return nacl.sign.detached.verify(data, signature, publicKey); + }; + return false; +} + +/***/ }), + +/***/ 4062: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Soroban = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/* Helper class to assist with formatting and parsing token amounts. */ +var Soroban = exports.Soroban = /*#__PURE__*/function () { + function Soroban() { + _classCallCheck(this, Soroban); + } + return _createClass(Soroban, null, [{ + key: "formatTokenAmount", + value: + /** + * Given a whole number smart contract amount of a token and an amount of + * decimal places (if the token has any), it returns a "display" value. + * + * All arithmetic inside the contract is performed on integers to avoid + * potential precision and consistency issues of floating-point. + * + * @param {string} amount the token amount you want to display + * @param {number} decimals specify how many decimal places a token has + * + * @returns {string} the display value + * @throws {TypeError} if the given amount has a decimal point already + * @example + * formatTokenAmount("123000", 4) === "12.3"; + */ + function formatTokenAmount(amount, decimals) { + if (amount.includes('.')) { + throw new TypeError('No decimals are allowed'); + } + var formatted = amount; + if (decimals > 0) { + if (decimals > formatted.length) { + formatted = ['0', formatted.toString().padStart(decimals, '0')].join('.'); + } else { + formatted = [formatted.slice(0, -decimals), formatted.slice(-decimals)].join('.'); + } + } + + // remove trailing zero if any + return formatted.replace(/(\.\d*?)0+$/, '$1'); + } + + /** + * Parse a token amount to use it on smart contract + * + * This function takes the display value and its decimals (if the token has + * any) and returns a string that'll be used within the smart contract. + * + * @param {string} value the token amount you want to use it on smart + * contract which you've been displaying in a UI + * @param {number} decimals the number of decimal places expected in the + * display value (different than the "actual" number, because suffix zeroes + * might not be present) + * + * @returns {string} the whole number token amount represented by the display + * value with the decimal places shifted over + * + * @example + * const displayValueAmount = "123.4560" + * const parsedAmtForSmartContract = parseTokenAmount(displayValueAmount, 5); + * parsedAmtForSmartContract === "12345600" + */ + }, { + key: "parseTokenAmount", + value: function parseTokenAmount(value, decimals) { + var _fraction$padEnd; + var _value$split$slice = value.split('.').slice(), + _value$split$slice2 = _toArray(_value$split$slice), + whole = _value$split$slice2[0], + fraction = _value$split$slice2[1], + rest = _value$split$slice2.slice(2); + if (rest.length) { + throw new Error("Invalid decimal value: ".concat(value)); + } + var shifted = BigInt(whole + ((_fraction$padEnd = fraction === null || fraction === void 0 ? void 0 : fraction.padEnd(decimals, '0')) !== null && _fraction$padEnd !== void 0 ? _fraction$padEnd : '0'.repeat(decimals))); + return shifted.toString(); + } + }]); +}(); + +/***/ }), + +/***/ 4842: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.SorobanDataBuilder = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Supports building {@link xdr.SorobanTransactionData} structures with various + * items set to specific values. + * + * This is recommended for when you are building + * {@link Operation.extendFootprintTtl} / {@link Operation.restoreFootprint} + * operations and need to {@link TransactionBuilder.setSorobanData} to avoid + * (re)building the entire data structure from scratch. + * + * @constructor + * + * @param {string | xdr.SorobanTransactionData} [sorobanData] either a + * base64-encoded string that represents an + * {@link xdr.SorobanTransactionData} instance or an XDR instance itself + * (it will be copied); if omitted or "falsy" (e.g. an empty string), it + * starts with an empty instance + * + * @example + * // You want to use an existing data blob but override specific parts. + * const newData = new SorobanDataBuilder(existing) + * .setReadOnly(someLedgerKeys) + * .setRefundableFee("1000") + * .build(); + * + * // You want an instance from scratch + * const newData = new SorobanDataBuilder() + * .setFootprint([someLedgerKey], []) + * .setRefundableFee("1000") + * .build(); + */ +var SorobanDataBuilder = exports.SorobanDataBuilder = /*#__PURE__*/function () { + function SorobanDataBuilder(sorobanData) { + _classCallCheck(this, SorobanDataBuilder); + _defineProperty(this, "_data", void 0); + var data; + if (!sorobanData) { + data = new _xdr["default"].SorobanTransactionData({ + resources: new _xdr["default"].SorobanResources({ + footprint: new _xdr["default"].LedgerFootprint({ + readOnly: [], + readWrite: [] + }), + instructions: 0, + readBytes: 0, + writeBytes: 0 + }), + ext: new _xdr["default"].ExtensionPoint(0), + resourceFee: new _xdr["default"].Int64(0) + }); + } else if (typeof sorobanData === 'string' || ArrayBuffer.isView(sorobanData)) { + data = SorobanDataBuilder.fromXDR(sorobanData); + } else { + data = SorobanDataBuilder.fromXDR(sorobanData.toXDR()); // copy + } + this._data = data; + } + + /** + * Decodes and builds a {@link xdr.SorobanTransactionData} instance. + * @param {Uint8Array|Buffer|string} data raw input to decode + * @returns {xdr.SorobanTransactionData} + */ + return _createClass(SorobanDataBuilder, [{ + key: "setResourceFee", + value: + /** + * Sets the resource fee portion of the Soroban data. + * @param {number | bigint | string} fee the resource fee to set (int64) + * @returns {SorobanDataBuilder} + */ + function setResourceFee(fee) { + this._data.resourceFee(new _xdr["default"].Int64(fee)); + return this; + } + + /** + * Sets up the resource metrics. + * + * You should almost NEVER need this, as its often generated / provided to you + * by transaction simulation/preflight from a Soroban RPC server. + * + * @param {number} cpuInstrs number of CPU instructions + * @param {number} readBytes number of bytes being read + * @param {number} writeBytes number of bytes being written + * + * @returns {SorobanDataBuilder} + */ + }, { + key: "setResources", + value: function setResources(cpuInstrs, readBytes, writeBytes) { + this._data.resources().instructions(cpuInstrs); + this._data.resources().readBytes(readBytes); + this._data.resources().writeBytes(writeBytes); + return this; + } + + /** + * Appends the given ledger keys to the existing storage access footprint. + * @param {xdr.LedgerKey[]} readOnly read-only keys to add + * @param {xdr.LedgerKey[]} readWrite read-write keys to add + * @returns {SorobanDataBuilder} this builder instance + */ + }, { + key: "appendFootprint", + value: function appendFootprint(readOnly, readWrite) { + return this.setFootprint(this.getReadOnly().concat(readOnly), this.getReadWrite().concat(readWrite)); + } + + /** + * Sets the storage access footprint to be a certain set of ledger keys. + * + * You can also set each field explicitly via + * {@link SorobanDataBuilder.setReadOnly} and + * {@link SorobanDataBuilder.setReadWrite} or add to the existing footprint + * via {@link SorobanDataBuilder.appendFootprint}. + * + * Passing `null|undefined` to either parameter will IGNORE the existing + * values. If you want to clear them, pass `[]`, instead. + * + * @param {xdr.LedgerKey[]|null} [readOnly] the set of ledger keys to set in + * the read-only portion of the transaction's `sorobanData`, or `null | + * undefined` to keep the existing keys + * @param {xdr.LedgerKey[]|null} [readWrite] the set of ledger keys to set in + * the read-write portion of the transaction's `sorobanData`, or `null | + * undefined` to keep the existing keys + * @returns {SorobanDataBuilder} this builder instance + */ + }, { + key: "setFootprint", + value: function setFootprint(readOnly, readWrite) { + if (readOnly !== null) { + // null means "leave me alone" + this.setReadOnly(readOnly); + } + if (readWrite !== null) { + this.setReadWrite(readWrite); + } + return this; + } + + /** + * @param {xdr.LedgerKey[]} readOnly read-only keys in the access footprint + * @returns {SorobanDataBuilder} + */ + }, { + key: "setReadOnly", + value: function setReadOnly(readOnly) { + this._data.resources().footprint().readOnly(readOnly !== null && readOnly !== void 0 ? readOnly : []); + return this; + } + + /** + * @param {xdr.LedgerKey[]} readWrite read-write keys in the access footprint + * @returns {SorobanDataBuilder} + */ + }, { + key: "setReadWrite", + value: function setReadWrite(readWrite) { + this._data.resources().footprint().readWrite(readWrite !== null && readWrite !== void 0 ? readWrite : []); + return this; + } + + /** + * @returns {xdr.SorobanTransactionData} a copy of the final data structure + */ + }, { + key: "build", + value: function build() { + return _xdr["default"].SorobanTransactionData.fromXDR(this._data.toXDR()); // clone + } + + // + // getters follow + // + + /** @returns {xdr.LedgerKey[]} the read-only storage access pattern */ + }, { + key: "getReadOnly", + value: function getReadOnly() { + return this.getFootprint().readOnly(); + } + + /** @returns {xdr.LedgerKey[]} the read-write storage access pattern */ + }, { + key: "getReadWrite", + value: function getReadWrite() { + return this.getFootprint().readWrite(); + } + + /** @returns {xdr.LedgerFootprint} the storage access pattern */ + }, { + key: "getFootprint", + value: function getFootprint() { + return this._data.resources().footprint(); + } + }], [{ + key: "fromXDR", + value: function fromXDR(data) { + return _xdr["default"].SorobanTransactionData.fromXDR(data, typeof data === 'string' ? 'base64' : 'raw'); + } + }]); +}(); + +/***/ }), + +/***/ 7120: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.StrKey = void 0; +exports.decodeCheck = decodeCheck; +exports.encodeCheck = encodeCheck; +var _base = _interopRequireDefault(__webpack_require__(5360)); +var _checksum = __webpack_require__(1346); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": ["<<", ">>", "^", "&", "&="]}] */ +var versionBytes = { + ed25519PublicKey: 6 << 3, + // G (when encoded in base32) + ed25519SecretSeed: 18 << 3, + // S + med25519PublicKey: 12 << 3, + // M + preAuthTx: 19 << 3, + // T + sha256Hash: 23 << 3, + // X + signedPayload: 15 << 3, + // P + contract: 2 << 3 // C +}; +var strkeyTypes = { + G: 'ed25519PublicKey', + S: 'ed25519SecretSeed', + M: 'med25519PublicKey', + T: 'preAuthTx', + X: 'sha256Hash', + P: 'signedPayload', + C: 'contract' +}; + +/** + * StrKey is a helper class that allows encoding and decoding Stellar keys + * to/from strings, i.e. between their binary (Buffer, xdr.PublicKey, etc.) and + * string (i.e. "GABCD...", etc.) representations. + */ +var StrKey = exports.StrKey = /*#__PURE__*/function () { + function StrKey() { + _classCallCheck(this, StrKey); + } + return _createClass(StrKey, null, [{ + key: "encodeEd25519PublicKey", + value: + /** + * Encodes `data` to strkey ed25519 public key. + * + * @param {Buffer} data raw data to encode + * @returns {string} "G..." representation of the key + */ + function encodeEd25519PublicKey(data) { + return encodeCheck('ed25519PublicKey', data); + } + + /** + * Decodes strkey ed25519 public key to raw data. + * + * If the parameter is a muxed account key ("M..."), this will only encode it + * as a basic Ed25519 key (as if in "G..." format). + * + * @param {string} data "G..." (or "M...") key representation to decode + * @returns {Buffer} raw key + */ + }, { + key: "decodeEd25519PublicKey", + value: function decodeEd25519PublicKey(data) { + return decodeCheck('ed25519PublicKey', data); + } + + /** + * Returns true if the given Stellar public key is a valid ed25519 public key. + * @param {string} publicKey public key to check + * @returns {boolean} + */ + }, { + key: "isValidEd25519PublicKey", + value: function isValidEd25519PublicKey(publicKey) { + return isValid('ed25519PublicKey', publicKey); + } + + /** + * Encodes data to strkey ed25519 seed. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeEd25519SecretSeed", + value: function encodeEd25519SecretSeed(data) { + return encodeCheck('ed25519SecretSeed', data); + } + + /** + * Decodes strkey ed25519 seed to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeEd25519SecretSeed", + value: function decodeEd25519SecretSeed(address) { + return decodeCheck('ed25519SecretSeed', address); + } + + /** + * Returns true if the given Stellar secret key is a valid ed25519 secret seed. + * @param {string} seed seed to check + * @returns {boolean} + */ + }, { + key: "isValidEd25519SecretSeed", + value: function isValidEd25519SecretSeed(seed) { + return isValid('ed25519SecretSeed', seed); + } + + /** + * Encodes data to strkey med25519 public key. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeMed25519PublicKey", + value: function encodeMed25519PublicKey(data) { + return encodeCheck('med25519PublicKey', data); + } + + /** + * Decodes strkey med25519 public key to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeMed25519PublicKey", + value: function decodeMed25519PublicKey(address) { + return decodeCheck('med25519PublicKey', address); + } + + /** + * Returns true if the given Stellar public key is a valid med25519 public key. + * @param {string} publicKey public key to check + * @returns {boolean} + */ + }, { + key: "isValidMed25519PublicKey", + value: function isValidMed25519PublicKey(publicKey) { + return isValid('med25519PublicKey', publicKey); + } + + /** + * Encodes data to strkey preAuthTx. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodePreAuthTx", + value: function encodePreAuthTx(data) { + return encodeCheck('preAuthTx', data); + } + + /** + * Decodes strkey PreAuthTx to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodePreAuthTx", + value: function decodePreAuthTx(address) { + return decodeCheck('preAuthTx', address); + } + + /** + * Encodes data to strkey sha256 hash. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeSha256Hash", + value: function encodeSha256Hash(data) { + return encodeCheck('sha256Hash', data); + } + + /** + * Decodes strkey sha256 hash to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeSha256Hash", + value: function decodeSha256Hash(address) { + return decodeCheck('sha256Hash', address); + } + + /** + * Encodes raw data to strkey signed payload (P...). + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeSignedPayload", + value: function encodeSignedPayload(data) { + return encodeCheck('signedPayload', data); + } + + /** + * Decodes strkey signed payload (P...) to raw data. + * @param {string} address address to decode + * @returns {Buffer} + */ + }, { + key: "decodeSignedPayload", + value: function decodeSignedPayload(address) { + return decodeCheck('signedPayload', address); + } + + /** + * Checks validity of alleged signed payload (P...) strkey address. + * @param {string} address signer key to check + * @returns {boolean} + */ + }, { + key: "isValidSignedPayload", + value: function isValidSignedPayload(address) { + return isValid('signedPayload', address); + } + + /** + * Encodes raw data to strkey contract (C...). + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeContract", + value: function encodeContract(data) { + return encodeCheck('contract', data); + } + + /** + * Decodes strkey contract (C...) to raw data. + * @param {string} address address to decode + * @returns {Buffer} + */ + }, { + key: "decodeContract", + value: function decodeContract(address) { + return decodeCheck('contract', address); + } + + /** + * Checks validity of alleged contract (C...) strkey address. + * @param {string} address signer key to check + * @returns {boolean} + */ + }, { + key: "isValidContract", + value: function isValidContract(address) { + return isValid('contract', address); + } + }, { + key: "getVersionByteForPrefix", + value: function getVersionByteForPrefix(address) { + return strkeyTypes[address[0]]; + } + }]); +}(); +/** + * Sanity-checks whether or not a strkey *appears* valid. + * + * @param {string} versionByteName the type of strkey to expect in `encoded` + * @param {string} encoded the strkey to validate + * + * @return {Boolean} whether or not the `encoded` strkey appears valid for the + * `versionByteName` strkey type (see `versionBytes`, above). + * + * @note This isn't a *definitive* check of validity, but rather a best-effort + * check based on (a) input length, (b) whether or not it can be decoded, + * and (c) output length. + */ +function isValid(versionByteName, encoded) { + if (typeof encoded !== 'string') { + return false; + } + + // basic length checks on the strkey lengths + switch (versionByteName) { + case 'ed25519PublicKey': // falls through + case 'ed25519SecretSeed': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + case 'contract': + if (encoded.length !== 56) { + return false; + } + break; + case 'med25519PublicKey': + if (encoded.length !== 69) { + return false; + } + break; + case 'signedPayload': + if (encoded.length < 56 || encoded.length > 165) { + return false; + } + break; + default: + return false; + } + var decoded = ''; + try { + decoded = decodeCheck(versionByteName, encoded); + } catch (err) { + return false; + } + + // basic length checks on the resulting buffer sizes + switch (versionByteName) { + case 'ed25519PublicKey': // falls through + case 'ed25519SecretSeed': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + case 'contract': + return decoded.length === 32; + case 'med25519PublicKey': + return decoded.length === 40; + // +8 bytes for the ID + + case 'signedPayload': + return ( + // 32 for the signer, +4 for the payload size, then either +4 for the + // min or +64 for the max payload + decoded.length >= 32 + 4 + 4 && decoded.length <= 32 + 4 + 64 + ); + default: + return false; + } +} +function decodeCheck(versionByteName, encoded) { + if (typeof encoded !== 'string') { + throw new TypeError('encoded argument must be of type String'); + } + var decoded = _base["default"].decode(encoded); + var versionByte = decoded[0]; + var payload = decoded.slice(0, -2); + var data = payload.slice(1); + var checksum = decoded.slice(-2); + if (encoded !== _base["default"].encode(decoded)) { + throw new Error('invalid encoded string'); + } + var expectedVersion = versionBytes[versionByteName]; + if (expectedVersion === undefined) { + throw new Error("".concat(versionByteName, " is not a valid version byte name. ") + "Expected one of ".concat(Object.keys(versionBytes).join(', '))); + } + if (versionByte !== expectedVersion) { + throw new Error("invalid version byte. expected ".concat(expectedVersion, ", got ").concat(versionByte)); + } + var expectedChecksum = calculateChecksum(payload); + if (!(0, _checksum.verifyChecksum)(expectedChecksum, checksum)) { + throw new Error("invalid checksum"); + } + return Buffer.from(data); +} +function encodeCheck(versionByteName, data) { + if (data === null || data === undefined) { + throw new Error('cannot encode null data'); + } + var versionByte = versionBytes[versionByteName]; + if (versionByte === undefined) { + throw new Error("".concat(versionByteName, " is not a valid version byte name. ") + "Expected one of ".concat(Object.keys(versionBytes).join(', '))); + } + data = Buffer.from(data); + var versionBuffer = Buffer.from([versionByte]); + var payload = Buffer.concat([versionBuffer, data]); + var checksum = Buffer.from(calculateChecksum(payload)); + var unencoded = Buffer.concat([payload, checksum]); + return _base["default"].encode(unencoded); +} + +// Computes the CRC16-XModem checksum of `payload` in little-endian order +function calculateChecksum(payload) { + var crcTable = [0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0]; + var crc16 = 0x0; + for (var i = 0; i < payload.length; i += 1) { + var _byte = payload[i]; + var lookupIndex = crc16 >> 8 ^ _byte; + crc16 = crc16 << 8 ^ crcTable[lookupIndex]; + crc16 &= 0xffff; + } + var checksum = new Uint8Array(2); + checksum[0] = crc16 & 0xff; + checksum[1] = crc16 >> 8 & 0xff; + return checksum; +} + +/***/ }), + +/***/ 380: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Transaction = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _hashing = __webpack_require__(9152); +var _strkey = __webpack_require__(7120); +var _operation = __webpack_require__(7237); +var _memo = __webpack_require__(4172); +var _transaction_base = __webpack_require__(3758); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Use {@link TransactionBuilder} to build a transaction object. If you have an + * object or base64-encoded string of the transaction envelope XDR, use {@link + * TransactionBuilder.fromXDR}. + * + * Once a Transaction has been created, its attributes and operations should not + * be changed. You should only add signatures (using {@link Transaction#sign}) + * to a Transaction object before submitting to the network or forwarding on to + * additional signers. + * + * @constructor + * + * @param {string|xdr.TransactionEnvelope} envelope - transaction envelope + * object or base64 encoded string + * @param {string} [networkPassphrase] - passphrase of the target stellar + * network (e.g. "Public Global Stellar Network ; September 2015") + * + * @extends TransactionBase + */ +var Transaction = exports.Transaction = /*#__PURE__*/function (_TransactionBase) { + function Transaction(envelope, networkPassphrase) { + var _this; + _classCallCheck(this, Transaction); + if (typeof envelope === 'string') { + var buffer = Buffer.from(envelope, 'base64'); + envelope = _xdr["default"].TransactionEnvelope.fromXDR(buffer); + } + var envelopeType = envelope["switch"](); + if (!(envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTxV0() || envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTx())) { + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ".concat(envelopeType.name, ".")); + } + var txEnvelope = envelope.value(); + var tx = txEnvelope.tx(); + var fee = tx.fee().toString(); + var signatures = (txEnvelope.signatures() || []).slice(); + _this = _callSuper(this, Transaction, [tx, signatures, fee, networkPassphrase]); + _this._envelopeType = envelopeType; + _this._memo = tx.memo(); + _this._sequence = tx.seqNum().toString(); + switch (_this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + _this._source = _strkey.StrKey.encodeEd25519PublicKey(_this.tx.sourceAccountEd25519()); + break; + default: + _this._source = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(_this.tx.sourceAccount()); + break; + } + var cond = null; + var timeBounds = null; + switch (_this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + timeBounds = tx.timeBounds(); + break; + case _xdr["default"].EnvelopeType.envelopeTypeTx(): + switch (tx.cond()["switch"]()) { + case _xdr["default"].PreconditionType.precondTime(): + timeBounds = tx.cond().timeBounds(); + break; + case _xdr["default"].PreconditionType.precondV2(): + cond = tx.cond().v2(); + timeBounds = cond.timeBounds(); + break; + default: + break; + } + break; + default: + break; + } + if (timeBounds) { + _this._timeBounds = { + minTime: timeBounds.minTime().toString(), + maxTime: timeBounds.maxTime().toString() + }; + } + if (cond) { + var ledgerBounds = cond.ledgerBounds(); + if (ledgerBounds) { + _this._ledgerBounds = { + minLedger: ledgerBounds.minLedger(), + maxLedger: ledgerBounds.maxLedger() + }; + } + var minSeq = cond.minSeqNum(); + if (minSeq) { + _this._minAccountSequence = minSeq.toString(); + } + _this._minAccountSequenceAge = cond.minSeqAge(); + _this._minAccountSequenceLedgerGap = cond.minSeqLedgerGap(); + _this._extraSigners = cond.extraSigners(); + } + var operations = tx.operations() || []; + _this._operations = operations.map(function (op) { + return _operation.Operation.fromXDRObject(op); + }); + return _this; + } + + /** + * @type {object} + * @property {string} 64 bit unix timestamp + * @property {string} 64 bit unix timestamp + * @readonly + */ + _inherits(Transaction, _TransactionBase); + return _createClass(Transaction, [{ + key: "timeBounds", + get: function get() { + return this._timeBounds; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {object} + * @property {number} minLedger - smallest ledger bound (uint32) + * @property {number} maxLedger - largest ledger bound (or 0 for inf) + * @readonly + */ + }, { + key: "ledgerBounds", + get: function get() { + return this._ledgerBounds; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 64 bit account sequence + * @readonly + * @type {string} + */ + }, { + key: "minAccountSequence", + get: function get() { + return this._minAccountSequence; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 64 bit number of seconds + * @type {number} + * @readonly + */ + }, { + key: "minAccountSequenceAge", + get: function get() { + return this._minAccountSequenceAge; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 32 bit number of ledgers + * @type {number} + * @readonly + */ + }, { + key: "minAccountSequenceLedgerGap", + get: function get() { + return this._minAccountSequenceLedgerGap; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * array of extra signers ({@link StrKey}s) + * @type {string[]} + * @readonly + */ + }, { + key: "extraSigners", + get: function get() { + return this._extraSigners; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "sequence", + get: function get() { + return this._sequence; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "source", + get: function get() { + return this._source; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {Array.} + * @readonly + */ + }, { + key: "operations", + get: function get() { + return this._operations; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "memo", + get: function get() { + return _memo.Memo.fromXDRObject(this._memo); + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * Returns the "signature base" of this transaction, which is the value + * that, when hashed, should be signed to create a signature that + * validators on the Stellar Network will accept. + * + * It is composed of a 4 prefix bytes followed by the xdr-encoded form + * of this transaction. + * @returns {Buffer} + */ + }, { + key: "signatureBase", + value: function signatureBase() { + var tx = this.tx; + + // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // we need a Transaction to generate the signature base + if (this._envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTxV0()) { + tx = _xdr["default"].Transaction.fromXDR(Buffer.concat([ + // TransactionV0 is a transaction with the AccountID discriminant + // stripped off, we need to put it back to build a valid transaction + // which we can use to build a TransactionSignaturePayloadTaggedTransaction + _xdr["default"].PublicKeyType.publicKeyTypeEd25519().toXDR(), tx.toXDR()])); + } + var taggedTransaction = new _xdr["default"].TransactionSignaturePayloadTaggedTransaction.envelopeTypeTx(tx); + var txSignature = new _xdr["default"].TransactionSignaturePayload({ + networkId: _xdr["default"].Hash.fromXDR((0, _hashing.hash)(this.networkPassphrase)), + taggedTransaction: taggedTransaction + }); + return txSignature.toXDR(); + } + + /** + * To envelope returns a xdr.TransactionEnvelope which can be submitted to the network. + * @returns {xdr.TransactionEnvelope} + */ + }, { + key: "toEnvelope", + value: function toEnvelope() { + var rawTx = this.tx.toXDR(); + var signatures = this.signatures.slice(); // make a copy of the signatures + + var envelope; + switch (this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTxV0(new _xdr["default"].TransactionV0Envelope({ + tx: _xdr["default"].TransactionV0.fromXDR(rawTx), + // make a copy of tx + signatures: signatures + })); + break; + case _xdr["default"].EnvelopeType.envelopeTypeTx(): + envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: _xdr["default"].Transaction.fromXDR(rawTx), + // make a copy of tx + signatures: signatures + })); + break; + default: + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ".concat(this._envelopeType.name, ".")); + } + return envelope; + } + + /** + * Calculate the claimable balance ID for an operation within the transaction. + * + * @param {integer} opIndex the index of the CreateClaimableBalance op + * @returns {string} a hex string representing the claimable balance ID + * + * @throws {RangeError} for invalid `opIndex` value + * @throws {TypeError} if op at `opIndex` is not `CreateClaimableBalance` + * @throws for general XDR un/marshalling failures + * + * @see https://github.com/stellar/go/blob/d712346e61e288d450b0c08038c158f8848cc3e4/txnbuild/transaction.go#L392-L435 + * + */ + }, { + key: "getClaimableBalanceId", + value: function getClaimableBalanceId(opIndex) { + // Validate and then extract the operation from the transaction. + if (!Number.isInteger(opIndex) || opIndex < 0 || opIndex >= this.operations.length) { + throw new RangeError('invalid operation index'); + } + var op = this.operations[opIndex]; + try { + op = _operation.Operation.createClaimableBalance(op); + } catch (err) { + throw new TypeError("expected createClaimableBalance, got ".concat(op.type, ": ").concat(err)); + } + + // Always use the transaction's *unmuxed* source. + var account = _strkey.StrKey.decodeEd25519PublicKey((0, _decode_encode_muxed_account.extractBaseAddress)(this.source)); + var operationId = _xdr["default"].HashIdPreimage.envelopeTypeOpId(new _xdr["default"].HashIdPreimageOperationId({ + sourceAccount: _xdr["default"].AccountId.publicKeyTypeEd25519(account), + seqNum: _xdr["default"].SequenceNumber.fromString(this.sequence), + opNum: opIndex + })); + var opIdHash = (0, _hashing.hash)(operationId.toXDR('raw')); + var balanceId = _xdr["default"].ClaimableBalanceId.claimableBalanceIdTypeV0(opIdHash); + return balanceId.toXDR('hex'); + } + }]); +}(_transaction_base.TransactionBase); + +/***/ }), + +/***/ 3758: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.TransactionBase = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _hashing = __webpack_require__(9152); +var _keypair = __webpack_require__(6691); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * @ignore + */ +var TransactionBase = exports.TransactionBase = /*#__PURE__*/function () { + function TransactionBase(tx, signatures, fee, networkPassphrase) { + _classCallCheck(this, TransactionBase); + if (typeof networkPassphrase !== 'string') { + throw new Error("Invalid passphrase provided to Transaction: expected a string but got a ".concat(_typeof(networkPassphrase))); + } + this._networkPassphrase = networkPassphrase; + this._tx = tx; + this._signatures = signatures; + this._fee = fee; + } + + /** + * @type {Array.} + * @readonly + */ + return _createClass(TransactionBase, [{ + key: "signatures", + get: function get() { + return this._signatures; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + }, { + key: "tx", + get: function get() { + return this._tx; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "fee", + get: function get() { + return this._fee; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "networkPassphrase", + get: function get() { + return this._networkPassphrase; + }, + set: function set(networkPassphrase) { + this._networkPassphrase = networkPassphrase; + } + + /** + * Signs the transaction with the given {@link Keypair}. + * @param {...Keypair} keypairs Keypairs of signers + * @returns {void} + */ + }, { + key: "sign", + value: function sign() { + var _this = this; + var txHash = this.hash(); + for (var _len = arguments.length, keypairs = new Array(_len), _key = 0; _key < _len; _key++) { + keypairs[_key] = arguments[_key]; + } + keypairs.forEach(function (kp) { + var sig = kp.signDecorated(txHash); + _this.signatures.push(sig); + }); + } + + /** + * Signs a transaction with the given {@link Keypair}. Useful if someone sends + * you a transaction XDR for you to sign and return (see + * [addSignature](#addSignature) for more information). + * + * When you get a transaction XDR to sign.... + * - Instantiate a `Transaction` object with the XDR + * - Use {@link Keypair} to generate a keypair object for your Stellar seed. + * - Run `getKeypairSignature` with that keypair + * - Send back the signature along with your publicKey (not your secret seed!) + * + * Example: + * ```javascript + * // `transactionXDR` is a string from the person generating the transaction + * const transaction = new Transaction(transactionXDR, networkPassphrase); + * const keypair = Keypair.fromSecret(myStellarSeed); + * return transaction.getKeypairSignature(keypair); + * ``` + * + * @param {Keypair} keypair Keypair of signer + * @returns {string} Signature string + */ + }, { + key: "getKeypairSignature", + value: function getKeypairSignature(keypair) { + return keypair.sign(this.hash()).toString('base64'); + } + + /** + * Add a signature to the transaction. Useful when a party wants to pre-sign + * a transaction but doesn't want to give access to their secret keys. + * This will also verify whether the signature is valid. + * + * Here's how you would use this feature to solicit multiple signatures. + * - Use `TransactionBuilder` to build a new transaction. + * - Make sure to set a long enough timeout on that transaction to give your + * signers enough time to sign! + * - Once you build the transaction, use `transaction.toXDR()` to get the + * base64-encoded XDR string. + * - _Warning!_ Once you've built this transaction, don't submit any other + * transactions onto your account! Doing so will invalidate this pre-compiled + * transaction! + * - Send this XDR string to your other parties. They can use the instructions + * for [getKeypairSignature](#getKeypairSignature) to sign the transaction. + * - They should send you back their `publicKey` and the `signature` string + * from [getKeypairSignature](#getKeypairSignature), both of which you pass to + * this function. + * + * @param {string} publicKey The public key of the signer + * @param {string} signature The base64 value of the signature XDR + * @returns {void} + */ + }, { + key: "addSignature", + value: function addSignature() { + var publicKey = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var signature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + if (!signature || typeof signature !== 'string') { + throw new Error('Invalid signature'); + } + if (!publicKey || typeof publicKey !== 'string') { + throw new Error('Invalid publicKey'); + } + var keypair; + var hint; + var signatureBuffer = Buffer.from(signature, 'base64'); + try { + keypair = _keypair.Keypair.fromPublicKey(publicKey); + hint = keypair.signatureHint(); + } catch (e) { + throw new Error('Invalid publicKey'); + } + if (!keypair.verify(this.hash(), signatureBuffer)) { + throw new Error('Invalid signature'); + } + this.signatures.push(new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signatureBuffer + })); + } + + /** + * Add a decorated signature directly to the transaction envelope. + * + * @param {xdr.DecoratedSignature} signature raw signature to add + * @returns {void} + * + * @see Keypair.signDecorated + * @see Keypair.signPayloadDecorated + */ + }, { + key: "addDecoratedSignature", + value: function addDecoratedSignature(signature) { + this.signatures.push(signature); + } + + /** + * Add `hashX` signer preimage as signature. + * @param {Buffer|String} preimage Preimage of hash used as signer + * @returns {void} + */ + }, { + key: "signHashX", + value: function signHashX(preimage) { + if (typeof preimage === 'string') { + preimage = Buffer.from(preimage, 'hex'); + } + if (preimage.length > 64) { + throw new Error('preimage cannnot be longer than 64 bytes'); + } + var signature = preimage; + var hashX = (0, _hashing.hash)(preimage); + var hint = hashX.slice(hashX.length - 4); + this.signatures.push(new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signature + })); + } + + /** + * Returns a hash for this transaction, suitable for signing. + * @returns {Buffer} + */ + }, { + key: "hash", + value: function hash() { + return (0, _hashing.hash)(this.signatureBase()); + } + }, { + key: "signatureBase", + value: function signatureBase() { + throw new Error('Implement in subclass'); + } + }, { + key: "toEnvelope", + value: function toEnvelope() { + throw new Error('Implement in subclass'); + } + + /** + * Get the transaction envelope as a base64-encoded string + * @returns {string} XDR string + */ + }, { + key: "toXDR", + value: function toXDR() { + return this.toEnvelope().toXDR().toString('base64'); + } + }]); +}(); + +/***/ }), + +/***/ 6396: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.TransactionBuilder = exports.TimeoutInfinite = exports.BASE_FEE = void 0; +exports.isValidDate = isValidDate; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _account = __webpack_require__(2135); +var _muxed_account = __webpack_require__(2243); +var _decode_encode_muxed_account = __webpack_require__(6160); +var _transaction = __webpack_require__(380); +var _fee_bump_transaction = __webpack_require__(9260); +var _sorobandata_builder = __webpack_require__(4842); +var _strkey = __webpack_require__(7120); +var _signerkey = __webpack_require__(225); +var _memo = __webpack_require__(4172); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Minimum base fee for transactions. If this fee is below the network + * minimum, the transaction will fail. The more operations in the + * transaction, the greater the required fee. Use {@link + * Server#fetchBaseFee} to get an accurate value of minimum transaction + * fee on the network. + * + * @constant + * @see [Fees](https://developers.stellar.org/docs/glossary/fees/) + */ +var BASE_FEE = exports.BASE_FEE = '100'; // Stroops + +/** + * @constant + * @see {@link TransactionBuilder#setTimeout} + * @see [Timeout](https://developers.stellar.org/api/resources/transactions/post/) + */ +var TimeoutInfinite = exports.TimeoutInfinite = 0; + +/** + *

Transaction builder helps constructs a new `{@link Transaction}` using the + * given {@link Account} as the transaction's "source account". The transaction + * will use the current sequence number of the given account as its sequence + * number and increment the given account's sequence number by one. The given + * source account must include a private key for signing the transaction or an + * error will be thrown.

+ * + *

Operations can be added to the transaction via their corresponding builder + * methods, and each returns the TransactionBuilder object so they can be + * chained together. After adding the desired operations, call the `build()` + * method on the `TransactionBuilder` to return a fully constructed `{@link + * Transaction}` that can be signed. The returned transaction will contain the + * sequence number of the source account and include the signature from the + * source account.

+ * + *

Be careful about unsubmitted transactions! When you build + * a transaction, `stellar-sdk` automatically increments the source account's + * sequence number. If you end up not submitting this transaction and submitting + * another one instead, it'll fail due to the sequence number being wrong. So if + * you decide not to use a built transaction, make sure to update the source + * account's sequence number with + * [Server.loadAccount](https://stellar.github.io/js-stellar-sdk/Server.html#loadAccount) + * before creating another transaction.

+ * + *

The following code example creates a new transaction with {@link + * Operation.createAccount} and {@link Operation.payment} operations. The + * Transaction's source account first funds `destinationA`, then sends a payment + * to `destinationB`. The built transaction is then signed by + * `sourceKeypair`.

+ * + * ``` + * var transaction = new TransactionBuilder(source, { fee, networkPassphrase: Networks.TESTNET }) + * .addOperation(Operation.createAccount({ + * destination: destinationA, + * startingBalance: "20" + * })) // <- funds and creates destinationA + * .addOperation(Operation.payment({ + * destination: destinationB, + * amount: "100", + * asset: Asset.native() + * })) // <- sends 100 XLM to destinationB + * .setTimeout(30) + * .build(); + * + * transaction.sign(sourceKeypair); + * ``` + * + * @constructor + * + * @param {Account} sourceAccount - source account for this transaction + * @param {object} opts - Options object + * @param {string} opts.fee - max fee you're willing to pay per + * operation in this transaction (**in stroops**) + * + * @param {object} [opts.timebounds] - timebounds for the + * validity of this transaction + * @param {number|string|Date} [opts.timebounds.minTime] - 64-bit UNIX + * timestamp or Date object + * @param {number|string|Date} [opts.timebounds.maxTime] - 64-bit UNIX + * timestamp or Date object + * @param {object} [opts.ledgerbounds] - ledger bounds for the + * validity of this transaction + * @param {number} [opts.ledgerbounds.minLedger] - number of the minimum + * ledger sequence + * @param {number} [opts.ledgerbounds.maxLedger] - number of the maximum + * ledger sequence + * @param {string} [opts.minAccountSequence] - number for + * the minimum account sequence + * @param {number} [opts.minAccountSequenceAge] - number of + * seconds for the minimum account sequence age + * @param {number} [opts.minAccountSequenceLedgerGap] - number of + * ledgers for the minimum account sequence ledger gap + * @param {string[]} [opts.extraSigners] - list of the extra signers + * required for this transaction + * @param {Memo} [opts.memo] - memo for the transaction + * @param {string} [opts.networkPassphrase] passphrase of the + * target Stellar network (e.g. "Public Global Stellar Network ; September + * 2015" for the pubnet) + * @param {xdr.SorobanTransactionData | string} [opts.sorobanData] - an + * optional instance of {@link xdr.SorobanTransactionData} to be set as the + * internal `Transaction.Ext.SorobanData` field (either the xdr object or a + * base64 string). In the case of Soroban transactions, this can be obtained + * from a prior simulation of the transaction with a contract invocation and + * provides necessary resource estimations. You can also use + * {@link SorobanDataBuilder} to construct complicated combinations of + * parameters without mucking with XDR directly. **Note:** For + * non-contract(non-Soroban) transactions, this has no effect. + */ +var TransactionBuilder = exports.TransactionBuilder = /*#__PURE__*/function () { + function TransactionBuilder(sourceAccount) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, TransactionBuilder); + if (!sourceAccount) { + throw new Error('must specify source account for the transaction'); + } + if (opts.fee === undefined) { + throw new Error('must specify fee for the transaction (in stroops)'); + } + this.source = sourceAccount; + this.operations = []; + this.baseFee = opts.fee; + this.timebounds = opts.timebounds ? _objectSpread({}, opts.timebounds) : null; + this.ledgerbounds = opts.ledgerbounds ? _objectSpread({}, opts.ledgerbounds) : null; + this.minAccountSequence = opts.minAccountSequence || null; + this.minAccountSequenceAge = opts.minAccountSequenceAge || null; + this.minAccountSequenceLedgerGap = opts.minAccountSequenceLedgerGap || null; + this.extraSigners = opts.extraSigners ? _toConsumableArray(opts.extraSigners) : null; + this.memo = opts.memo || _memo.Memo.none(); + this.networkPassphrase = opts.networkPassphrase || null; + this.sorobanData = opts.sorobanData ? new _sorobandata_builder.SorobanDataBuilder(opts.sorobanData).build() : null; + } + + /** + * Creates a builder instance using an existing {@link Transaction} as a + * template, ignoring any existing envelope signatures. + * + * Note that the sequence number WILL be cloned, so EITHER this transaction or + * the one it was cloned from will be valid. This is useful in situations + * where you are constructing a transaction in pieces and need to make + * adjustments as you go (for example, when filling out Soroban resource + * information). + * + * @param {Transaction} tx a "template" transaction to clone exactly + * @param {object} [opts] additional options to override the clone, e.g. + * {fee: '1000'} will override the existing base fee derived from `tx` (see + * the {@link TransactionBuilder} constructor for detailed options) + * + * @returns {TransactionBuilder} a "prepared" builder instance with the same + * configuration and operations as the given transaction + * + * @warning This does not clone the transaction's + * {@link xdr.SorobanTransactionData} (if applicable), use + * {@link SorobanDataBuilder} and {@link TransactionBuilder.setSorobanData} + * as needed, instead.. + * + * @todo This cannot clone {@link FeeBumpTransaction}s, yet. + */ + return _createClass(TransactionBuilder, [{ + key: "addOperation", + value: + /** + * Adds an operation to the transaction. + * + * @param {xdr.Operation} operation The xdr operation object, use {@link + * Operation} static methods. + * + * @returns {TransactionBuilder} + */ + function addOperation(operation) { + this.operations.push(operation); + return this; + } + + /** + * Adds an operation to the transaction at a specific index. + * + * @param {xdr.Operation} operation - The xdr operation object to add, use {@link Operation} static methods. + * @param {number} index - The index at which to insert the operation. + * + * @returns {TransactionBuilder} - The TransactionBuilder instance for method chaining. + */ + }, { + key: "addOperationAt", + value: function addOperationAt(operation, index) { + this.operations.splice(index, 0, operation); + return this; + } + + /** + * Removes the operations from the builder (useful when cloning). + * @returns {TransactionBuilder} this builder instance + */ + }, { + key: "clearOperations", + value: function clearOperations() { + this.operations = []; + return this; + } + + /** + * Removes the operation at the specified index from the transaction. + * + * @param {number} index - The index of the operation to remove. + * + * @returns {TransactionBuilder} The TransactionBuilder instance for method chaining. + */ + }, { + key: "clearOperationAt", + value: function clearOperationAt(index) { + this.operations.splice(index, 1); + return this; + } + + /** + * Adds a memo to the transaction. + * @param {Memo} memo {@link Memo} object + * @returns {TransactionBuilder} + */ + }, { + key: "addMemo", + value: function addMemo(memo) { + this.memo = memo; + return this; + } + + /** + * Sets a timeout precondition on the transaction. + * + * Because of the distributed nature of the Stellar network it is possible + * that the status of your transaction will be determined after a long time + * if the network is highly congested. If you want to be sure to receive the + * status of the transaction within a given period you should set the {@link + * TimeBounds} with `maxTime` on the transaction (this is what `setTimeout` + * does internally; if there's `minTime` set but no `maxTime` it will be + * added). + * + * A call to `TransactionBuilder.setTimeout` is **required** if Transaction + * does not have `max_time` set. If you don't want to set timeout, use + * `{@link TimeoutInfinite}`. In general you should set `{@link + * TimeoutInfinite}` only in smart contracts. + * + * Please note that Horizon may still return 504 Gateway Timeout + * error, even for short timeouts. In such case you need to resubmit the same + * transaction again without making any changes to receive a status. This + * method is using the machine system time (UTC), make sure it is set + * correctly. + * + * @param {number} timeoutSeconds Number of seconds the transaction is good. + * Can't be negative. If the value is {@link TimeoutInfinite}, the + * transaction is good indefinitely. + * + * @returns {TransactionBuilder} + * + * @see {@link TimeoutInfinite} + * @see https://developers.stellar.org/docs/tutorials/handling-errors/ + */ + }, { + key: "setTimeout", + value: function setTimeout(timeoutSeconds) { + if (this.timebounds !== null && this.timebounds.maxTime > 0) { + throw new Error('TimeBounds.max_time has been already set - setting timeout would overwrite it.'); + } + if (timeoutSeconds < 0) { + throw new Error('timeout cannot be negative'); + } + if (timeoutSeconds > 0) { + var timeoutTimestamp = Math.floor(Date.now() / 1000) + timeoutSeconds; + if (this.timebounds === null) { + this.timebounds = { + minTime: 0, + maxTime: timeoutTimestamp + }; + } else { + this.timebounds = { + minTime: this.timebounds.minTime, + maxTime: timeoutTimestamp + }; + } + } else { + this.timebounds = { + minTime: 0, + maxTime: 0 + }; + } + return this; + } + + /** + * If you want to prepare a transaction which will become valid at some point + * in the future, or be invalid after some time, you can set a timebounds + * precondition. Internally this will set the `minTime`, and `maxTime` + * preconditions. Conflicts with `setTimeout`, so use one or the other. + * + * @param {Date|number} minEpochOrDate Either a JS Date object, or a number + * of UNIX epoch seconds. The transaction is valid after this timestamp. + * Can't be negative. If the value is `0`, the transaction is valid + * immediately. + * @param {Date|number} maxEpochOrDate Either a JS Date object, or a number + * of UNIX epoch seconds. The transaction is valid until this timestamp. + * Can't be negative. If the value is `0`, the transaction is valid + * indefinitely. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setTimebounds", + value: function setTimebounds(minEpochOrDate, maxEpochOrDate) { + // Force it to a date type + if (typeof minEpochOrDate === 'number') { + minEpochOrDate = new Date(minEpochOrDate * 1000); + } + if (typeof maxEpochOrDate === 'number') { + maxEpochOrDate = new Date(maxEpochOrDate * 1000); + } + if (this.timebounds !== null) { + throw new Error('TimeBounds has been already set - setting timebounds would overwrite it.'); + } + + // Convert that date to the epoch seconds + var minTime = Math.floor(minEpochOrDate.valueOf() / 1000); + var maxTime = Math.floor(maxEpochOrDate.valueOf() / 1000); + if (minTime < 0) { + throw new Error('min_time cannot be negative'); + } + if (maxTime < 0) { + throw new Error('max_time cannot be negative'); + } + if (maxTime > 0 && minTime > maxTime) { + throw new Error('min_time cannot be greater than max_time'); + } + this.timebounds = { + minTime: minTime, + maxTime: maxTime + }; + return this; + } + + /** + * If you want to prepare a transaction which will only be valid within some + * range of ledgers, you can set a ledgerbounds precondition. + * Internally this will set the `minLedger` and `maxLedger` preconditions. + * + * @param {number} minLedger The minimum ledger this transaction is valid at + * or after. Cannot be negative. If the value is `0` (the default), the + * transaction is valid immediately. + * + * @param {number} maxLedger The maximum ledger this transaction is valid + * before. Cannot be negative. If the value is `0`, the transaction is + * valid indefinitely. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setLedgerbounds", + value: function setLedgerbounds(minLedger, maxLedger) { + if (this.ledgerbounds !== null) { + throw new Error('LedgerBounds has been already set - setting ledgerbounds would overwrite it.'); + } + if (minLedger < 0) { + throw new Error('min_ledger cannot be negative'); + } + if (maxLedger < 0) { + throw new Error('max_ledger cannot be negative'); + } + if (maxLedger > 0 && minLedger > maxLedger) { + throw new Error('min_ledger cannot be greater than max_ledger'); + } + this.ledgerbounds = { + minLedger: minLedger, + maxLedger: maxLedger + }; + return this; + } + + /** + * If you want to prepare a transaction which will be valid only while the + * account sequence number is + * + * minAccountSequence <= sourceAccountSequence < tx.seqNum + * + * Note that after execution the account's sequence number is always raised to + * `tx.seqNum`. Internally this will set the `minAccountSequence` + * precondition. + * + * @param {string} minAccountSequence The minimum source account sequence + * number this transaction is valid for. If the value is `0` (the + * default), the transaction is valid when `sourceAccount's sequence + * number == tx.seqNum- 1`. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequence", + value: function setMinAccountSequence(minAccountSequence) { + if (this.minAccountSequence !== null) { + throw new Error('min_account_sequence has been already set - setting min_account_sequence would overwrite it.'); + } + this.minAccountSequence = minAccountSequence; + return this; + } + + /** + * For the transaction to be valid, the current ledger time must be at least + * `minAccountSequenceAge` greater than sourceAccount's `sequenceTime`. + * Internally this will set the `minAccountSequenceAge` precondition. + * + * @param {number} durationInSeconds The minimum amount of time between + * source account sequence time and the ledger time when this transaction + * will become valid. If the value is `0`, the transaction is unrestricted + * by the account sequence age. Cannot be negative. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequenceAge", + value: function setMinAccountSequenceAge(durationInSeconds) { + if (typeof durationInSeconds !== 'number') { + throw new Error('min_account_sequence_age must be a number'); + } + if (this.minAccountSequenceAge !== null) { + throw new Error('min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.'); + } + if (durationInSeconds < 0) { + throw new Error('min_account_sequence_age cannot be negative'); + } + this.minAccountSequenceAge = durationInSeconds; + return this; + } + + /** + * For the transaction to be valid, the current ledger number must be at least + * `minAccountSequenceLedgerGap` greater than sourceAccount's ledger sequence. + * Internally this will set the `minAccountSequenceLedgerGap` precondition. + * + * @param {number} gap The minimum number of ledgers between source account + * sequence and the ledger number when this transaction will become valid. + * If the value is `0`, the transaction is unrestricted by the account + * sequence ledger. Cannot be negative. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequenceLedgerGap", + value: function setMinAccountSequenceLedgerGap(gap) { + if (this.minAccountSequenceLedgerGap !== null) { + throw new Error('min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.'); + } + if (gap < 0) { + throw new Error('min_account_sequence_ledger_gap cannot be negative'); + } + this.minAccountSequenceLedgerGap = gap; + return this; + } + + /** + * For the transaction to be valid, there must be a signature corresponding to + * every Signer in this array, even if the signature is not otherwise required + * by the sourceAccount or operations. Internally this will set the + * `extraSigners` precondition. + * + * @param {string[]} extraSigners required extra signers (as {@link StrKey}s) + * + * @returns {TransactionBuilder} + */ + }, { + key: "setExtraSigners", + value: function setExtraSigners(extraSigners) { + if (!Array.isArray(extraSigners)) { + throw new Error('extra_signers must be an array of strings.'); + } + if (this.extraSigners !== null) { + throw new Error('extra_signers has been already set - setting extra_signers would overwrite it.'); + } + if (extraSigners.length > 2) { + throw new Error('extra_signers cannot be longer than 2 elements.'); + } + this.extraSigners = _toConsumableArray(extraSigners); + return this; + } + + /** + * Set network nassphrase for the Transaction that will be built. + * + * @param {string} networkPassphrase passphrase of the target Stellar + * network (e.g. "Public Global Stellar Network ; September 2015"). + * + * @returns {TransactionBuilder} + */ + }, { + key: "setNetworkPassphrase", + value: function setNetworkPassphrase(networkPassphrase) { + this.networkPassphrase = networkPassphrase; + return this; + } + + /** + * Sets the transaction's internal Soroban transaction data (resources, + * footprint, etc.). + * + * For non-contract(non-Soroban) transactions, this setting has no effect. In + * the case of Soroban transactions, this is either an instance of + * {@link xdr.SorobanTransactionData} or a base64-encoded string of said + * structure. This is usually obtained from the simulation response based on a + * transaction with a Soroban operation (e.g. + * {@link Operation.invokeHostFunction}, providing necessary resource + * and storage footprint estimations for contract invocation. + * + * @param {xdr.SorobanTransactionData | string} sorobanData the + * {@link xdr.SorobanTransactionData} as a raw xdr object or a base64 + * string to be decoded + * + * @returns {TransactionBuilder} + * @see {SorobanDataBuilder} + */ + }, { + key: "setSorobanData", + value: function setSorobanData(sorobanData) { + this.sorobanData = new _sorobandata_builder.SorobanDataBuilder(sorobanData).build(); + return this; + } + + /** + * This will build the transaction. + * It will also increment the source account's sequence number by 1. + * @returns {Transaction} This method will return the built {@link Transaction}. + */ + }, { + key: "build", + value: function build() { + var sequenceNumber = new _bignumber["default"](this.source.sequenceNumber()).plus(1); + var fee = new _bignumber["default"](this.baseFee).times(this.operations.length).toNumber(); + var attrs = { + fee: fee, + seqNum: _xdr["default"].SequenceNumber.fromString(sequenceNumber.toString()), + memo: this.memo ? this.memo.toXDRObject() : null + }; + if (this.timebounds === null || typeof this.timebounds.minTime === 'undefined' || typeof this.timebounds.maxTime === 'undefined') { + throw new Error('TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).'); + } + if (isValidDate(this.timebounds.minTime)) { + this.timebounds.minTime = this.timebounds.minTime.getTime() / 1000; + } + if (isValidDate(this.timebounds.maxTime)) { + this.timebounds.maxTime = this.timebounds.maxTime.getTime() / 1000; + } + this.timebounds.minTime = _jsXdr.UnsignedHyper.fromString(this.timebounds.minTime.toString()); + this.timebounds.maxTime = _jsXdr.UnsignedHyper.fromString(this.timebounds.maxTime.toString()); + var timeBounds = new _xdr["default"].TimeBounds(this.timebounds); + if (this.hasV2Preconditions()) { + var ledgerBounds = null; + if (this.ledgerbounds !== null) { + ledgerBounds = new _xdr["default"].LedgerBounds(this.ledgerbounds); + } + var minSeqNum = this.minAccountSequence || '0'; + minSeqNum = _xdr["default"].SequenceNumber.fromString(minSeqNum); + var minSeqAge = _jsXdr.UnsignedHyper.fromString(this.minAccountSequenceAge !== null ? this.minAccountSequenceAge.toString() : '0'); + var minSeqLedgerGap = this.minAccountSequenceLedgerGap || 0; + var extraSigners = this.extraSigners !== null ? this.extraSigners.map(_signerkey.SignerKey.decodeAddress) : []; + attrs.cond = _xdr["default"].Preconditions.precondV2(new _xdr["default"].PreconditionsV2({ + timeBounds: timeBounds, + ledgerBounds: ledgerBounds, + minSeqNum: minSeqNum, + minSeqAge: minSeqAge, + minSeqLedgerGap: minSeqLedgerGap, + extraSigners: extraSigners + })); + } else { + attrs.cond = _xdr["default"].Preconditions.precondTime(timeBounds); + } + attrs.sourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(this.source.accountId()); + + // TODO - remove this workaround for TransactionExt ts constructor + // and use the typescript generated static factory method once fixed + // https://github.com/stellar/dts-xdr/issues/5 + if (this.sorobanData) { + // @ts-ignore + attrs.ext = new _xdr["default"].TransactionExt(1, this.sorobanData); + } else { + // @ts-ignore + attrs.ext = new _xdr["default"].TransactionExt(0, _xdr["default"].Void); + } + var xtx = new _xdr["default"].Transaction(attrs); + xtx.operations(this.operations); + var txEnvelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: xtx + })); + var tx = new _transaction.Transaction(txEnvelope, this.networkPassphrase); + this.source.incrementSequenceNumber(); + return tx; + } + }, { + key: "hasV2Preconditions", + value: function hasV2Preconditions() { + return this.ledgerbounds !== null || this.minAccountSequence !== null || this.minAccountSequenceAge !== null || this.minAccountSequenceLedgerGap !== null || this.extraSigners !== null && this.extraSigners.length > 0; + } + + /** + * Builds a {@link FeeBumpTransaction}, enabling you to resubmit an existing + * transaction with a higher fee. + * + * @param {Keypair|string} feeSource - account paying for the transaction, + * in the form of either a Keypair (only the public key is used) or + * an account ID (in G... or M... form, but refer to `withMuxing`) + * @param {string} baseFee - max fee willing to pay per operation + * in inner transaction (**in stroops**) + * @param {Transaction} innerTx - {@link Transaction} to be bumped by + * the fee bump transaction + * @param {string} networkPassphrase - passphrase of the target + * Stellar network (e.g. "Public Global Stellar Network ; September 2015", + * see {@link Networks}) + * + * @todo Alongside the next major version bump, this type signature can be + * changed to be less awkward: accept a MuxedAccount as the `feeSource` + * rather than a keypair or string. + * + * @note Your fee-bump amount should be >= 10x the original fee. + * @see https://developers.stellar.org/docs/glossary/fee-bumps/#replace-by-fee + * + * @returns {FeeBumpTransaction} + */ + }], [{ + key: "cloneFrom", + value: function cloneFrom(tx) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (!(tx instanceof _transaction.Transaction)) { + throw new TypeError("expected a 'Transaction', got: ".concat(tx)); + } + var sequenceNum = (BigInt(tx.sequence) - 1n).toString(); + var source; + // rebuild the source account based on the strkey + if (_strkey.StrKey.isValidMed25519PublicKey(tx.source)) { + source = _muxed_account.MuxedAccount.fromAddress(tx.source, sequenceNum); + } else if (_strkey.StrKey.isValidEd25519PublicKey(tx.source)) { + source = new _account.Account(tx.source, sequenceNum); + } else { + throw new TypeError("unsupported tx source account: ".concat(tx.source)); + } + + // the initial fee passed to the builder gets scaled up based on the number + // of operations at the end, so we have to down-scale first + var unscaledFee = parseInt(tx.fee, 10) / tx.operations.length; + var builder = new TransactionBuilder(source, _objectSpread({ + fee: (unscaledFee || BASE_FEE).toString(), + memo: tx.memo, + networkPassphrase: tx.networkPassphrase, + timebounds: tx.timeBounds, + ledgerbounds: tx.ledgerBounds, + minAccountSequence: tx.minAccountSequence, + minAccountSequenceAge: tx.minAccountSequenceAge, + minAccountSequenceLedgerGap: tx.minAccountSequenceLedgerGap, + extraSigners: tx.extraSigners + }, opts)); + tx._tx.operations().forEach(function (op) { + return builder.addOperation(op); + }); + return builder; + } + }, { + key: "buildFeeBumpTransaction", + value: function buildFeeBumpTransaction(feeSource, baseFee, innerTx, networkPassphrase) { + var innerOps = innerTx.operations.length; + var innerBaseFeeRate = new _bignumber["default"](innerTx.fee).div(innerOps); + var base = new _bignumber["default"](baseFee); + + // The fee rate for fee bump is at least the fee rate of the inner transaction + if (base.lt(innerBaseFeeRate)) { + throw new Error("Invalid baseFee, it should be at least ".concat(innerBaseFeeRate, " stroops.")); + } + var minBaseFee = new _bignumber["default"](BASE_FEE); + + // The fee rate is at least the minimum fee + if (base.lt(minBaseFee)) { + throw new Error("Invalid baseFee, it should be at least ".concat(minBaseFee, " stroops.")); + } + var innerTxEnvelope = innerTx.toEnvelope(); + if (innerTxEnvelope["switch"]() === _xdr["default"].EnvelopeType.envelopeTypeTxV0()) { + var v0Tx = innerTxEnvelope.v0().tx(); + var v1Tx = new _xdr["default"].Transaction({ + sourceAccount: new _xdr["default"].MuxedAccount.keyTypeEd25519(v0Tx.sourceAccountEd25519()), + fee: v0Tx.fee(), + seqNum: v0Tx.seqNum(), + cond: _xdr["default"].Preconditions.precondTime(v0Tx.timeBounds()), + memo: v0Tx.memo(), + operations: v0Tx.operations(), + ext: new _xdr["default"].TransactionExt(0) + }); + innerTxEnvelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: v1Tx, + signatures: innerTxEnvelope.v0().signatures() + })); + } + var feeSourceAccount; + if (typeof feeSource === 'string') { + feeSourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(feeSource); + } else { + feeSourceAccount = feeSource.xdrMuxedAccount(); + } + var tx = new _xdr["default"].FeeBumpTransaction({ + feeSource: feeSourceAccount, + fee: _xdr["default"].Int64.fromString(base.times(innerOps + 1).toString()), + innerTx: _xdr["default"].FeeBumpTransactionInnerTx.envelopeTypeTx(innerTxEnvelope.v1()), + ext: new _xdr["default"].FeeBumpTransactionExt(0) + }); + var feeBumpTxEnvelope = new _xdr["default"].FeeBumpTransactionEnvelope({ + tx: tx, + signatures: [] + }); + var envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTxFeeBump(feeBumpTxEnvelope); + return new _fee_bump_transaction.FeeBumpTransaction(envelope, networkPassphrase); + } + + /** + * Build a {@link Transaction} or {@link FeeBumpTransaction} from an + * xdr.TransactionEnvelope. + * + * @param {string|xdr.TransactionEnvelope} envelope - The transaction envelope + * object or base64 encoded string. + * @param {string} networkPassphrase - The network passphrase of the target + * Stellar network (e.g. "Public Global Stellar Network ; September + * 2015"), see {@link Networks}. + * + * @returns {Transaction|FeeBumpTransaction} + */ + }, { + key: "fromXDR", + value: function fromXDR(envelope, networkPassphrase) { + if (typeof envelope === 'string') { + envelope = _xdr["default"].TransactionEnvelope.fromXDR(envelope, 'base64'); + } + if (envelope["switch"]() === _xdr["default"].EnvelopeType.envelopeTypeTxFeeBump()) { + return new _fee_bump_transaction.FeeBumpTransaction(envelope, networkPassphrase); + } + return new _transaction.Transaction(envelope, networkPassphrase); + } + }]); +}(); +/** + * Checks whether a provided object is a valid Date. + * @argument {Date} d date object + * @returns {boolean} + */ +function isValidDate(d) { + // isnan is okay here because it correctly checks for invalid date objects + // eslint-disable-next-line no-restricted-globals + return d instanceof Date && !isNaN(d); +} + +/***/ }), + +/***/ 1242: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _bignumber = _interopRequireDefault(__webpack_require__(1594)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var BigNumber = _bignumber["default"].clone(); +BigNumber.DEBUG = true; // gives us exceptions on bad constructor values +var _default = exports["default"] = BigNumber; + +/***/ }), + +/***/ 1346: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.verifyChecksum = verifyChecksum; +function verifyChecksum(expected, actual) { + if (expected.length !== actual.length) { + return false; + } + if (expected.length === 0) { + return true; + } + for (var i = 0; i < expected.length; i += 1) { + if (expected[i] !== actual[i]) { + return false; + } + } + return true; +} + +/***/ }), + +/***/ 4151: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.best_r = best_r; +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +// eslint-disable-next-line no-bitwise +var MAX_INT = (1 << 31 >>> 0) - 1; + +/** + * Calculates and returns the best rational approximation of the given real number. + * @private + * @param {string|number|BigNumber} rawNumber Real number + * @throws Error Throws `Error` when the best rational approximation cannot be found. + * @returns {array} first element is n (numerator), second element is d (denominator) + */ +function best_r(rawNumber) { + var number = new _bignumber["default"](rawNumber); + var a; + var f; + var fractions = [[new _bignumber["default"](0), new _bignumber["default"](1)], [new _bignumber["default"](1), new _bignumber["default"](0)]]; + var i = 2; + + // eslint-disable-next-line no-constant-condition + while (true) { + if (number.gt(MAX_INT)) { + break; + } + a = number.integerValue(_bignumber["default"].ROUND_FLOOR); + f = number.minus(a); + var h = a.times(fractions[i - 1][0]).plus(fractions[i - 2][0]); + var k = a.times(fractions[i - 1][1]).plus(fractions[i - 2][1]); + if (h.gt(MAX_INT) || k.gt(MAX_INT)) { + break; + } + fractions.push([h, k]); + if (f.eq(0)) { + break; + } + number = new _bignumber["default"](1).div(f); + i += 1; + } + var _fractions = _slicedToArray(fractions[fractions.length - 1], 2), + n = _fractions[0], + d = _fractions[1]; + if (n.isZero() || d.isZero()) { + throw new Error("Couldn't find approximation"); + } + return [n.toNumber(), d.toNumber()]; +} + +/***/ }), + +/***/ 6160: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decodeAddressToMuxedAccount = decodeAddressToMuxedAccount; +exports.encodeMuxedAccount = encodeMuxedAccount; +exports.encodeMuxedAccountToAddress = encodeMuxedAccountToAddress; +exports.extractBaseAddress = extractBaseAddress; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Converts a Stellar address (in G... or M... form) to an `xdr.MuxedAccount` + * structure, using the ed25519 representation when possible. + * + * This supports full muxed accounts, where an `M...` address will resolve to + * both its underlying `G...` address and an integer ID. + * + * @param {string} address G... or M... address to encode into XDR + * @returns {xdr.MuxedAccount} a muxed account object for this address string + */ +function decodeAddressToMuxedAccount(address) { + if (_strkey.StrKey.isValidMed25519PublicKey(address)) { + return _decodeAddressFullyToMuxedAccount(address); + } + return _xdr["default"].MuxedAccount.keyTypeEd25519(_strkey.StrKey.decodeEd25519PublicKey(address)); +} + +/** + * Converts an xdr.MuxedAccount to its StrKey representation. + * + * This returns its "M..." string representation if there is a muxing ID within + * the object and returns the "G..." representation otherwise. + * + * @param {xdr.MuxedAccount} muxedAccount Raw account to stringify + * @returns {string} Stringified G... (corresponding to the underlying pubkey) + * or M... address (corresponding to both the key and the muxed ID) + * + * @see https://stellar.org/protocol/sep-23 + */ +function encodeMuxedAccountToAddress(muxedAccount) { + if (muxedAccount["switch"]().value === _xdr["default"].CryptoKeyType.keyTypeMuxedEd25519().value) { + return _encodeMuxedAccountFullyToAddress(muxedAccount); + } + return _strkey.StrKey.encodeEd25519PublicKey(muxedAccount.ed25519()); +} + +/** + * Transform a Stellar address (G...) and an ID into its XDR representation. + * + * @param {string} address - a Stellar G... address + * @param {string} id - a Uint64 ID represented as a string + * + * @return {xdr.MuxedAccount} - XDR representation of the above muxed account + */ +function encodeMuxedAccount(address, id) { + if (!_strkey.StrKey.isValidEd25519PublicKey(address)) { + throw new Error('address should be a Stellar account ID (G...)'); + } + if (typeof id !== 'string') { + throw new Error('id should be a string representing a number (uint64)'); + } + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromString(id), + ed25519: _strkey.StrKey.decodeEd25519PublicKey(address) + })); +} + +/** + * Extracts the underlying base (G...) address from an M-address. + * @param {string} address an account address (either M... or G...) + * @return {string} a Stellar public key address (G...) + */ +function extractBaseAddress(address) { + if (_strkey.StrKey.isValidEd25519PublicKey(address)) { + return address; + } + if (!_strkey.StrKey.isValidMed25519PublicKey(address)) { + throw new TypeError("expected muxed account (M...), got ".concat(address)); + } + var muxedAccount = decodeAddressToMuxedAccount(address); + return _strkey.StrKey.encodeEd25519PublicKey(muxedAccount.med25519().ed25519()); +} + +// Decodes an "M..." account ID into its MuxedAccount object representation. +function _decodeAddressFullyToMuxedAccount(address) { + var rawBytes = _strkey.StrKey.decodeMed25519PublicKey(address); + + // Decoding M... addresses cannot be done through a simple + // MuxedAccountMed25519.fromXDR() call, because the definition is: + // + // constructor(attributes: { id: Uint64; ed25519: Buffer }); + // + // Note the ID is the first attribute. However, the ID comes *last* in the + // stringified (base32-encoded) address itself (it's the last 8-byte suffix). + // The `fromXDR()` method interprets bytes in order, so we need to parse out + // the raw binary into its requisite parts, i.e. use the MuxedAccountMed25519 + // constructor directly. + // + // Refer to https://github.com/stellar/go/blob/master/xdr/muxed_account.go#L26 + // for the Golang implementation of the M... parsing. + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromXDR(rawBytes.subarray(-8)), + ed25519: rawBytes.subarray(0, -8) + })); +} + +// Converts an xdr.MuxedAccount into its *true* "M..." string representation. +function _encodeMuxedAccountFullyToAddress(muxedAccount) { + if (muxedAccount["switch"]() === _xdr["default"].CryptoKeyType.keyTypeEd25519()) { + return encodeMuxedAccountToAddress(muxedAccount); + } + var muxed = muxedAccount.med25519(); + return _strkey.StrKey.encodeMed25519PublicKey(Buffer.concat([muxed.ed25519(), muxed.id().toXDR('raw')])); +} + +/***/ }), + +/***/ 645: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.trimEnd = void 0; +var trimEnd = exports.trimEnd = function trimEnd(input, _char) { + var isNumber = typeof input === 'number'; + var str = String(input); + while (str.endsWith(_char)) { + str = str.slice(0, -1); + } + return isNumber ? Number(str) : str; +}; + +/***/ }), + +/***/ 1918: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _curr_generated = _interopRequireDefault(__webpack_require__(7938)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var _default = exports["default"] = _curr_generated["default"]; + +/***/ }), + +/***/ 4940: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +(function(nacl) { +'use strict'; + +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ + +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; + +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; + +var _0 = new Uint8Array(16); +var _9 = new Uint8Array(32); _9[0] = 9; + +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + +function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; +} + +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; +} + +function crypto_verify_16(x, xi, y, yi) { + return vn(x,xi,y,yi,16); +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); +} + +function core_salsa20(o, p, k, c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; + + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + + o[ 4] = x1 >>> 0 & 0xff; + o[ 5] = x1 >>> 8 & 0xff; + o[ 6] = x1 >>> 16 & 0xff; + o[ 7] = x1 >>> 24 & 0xff; + + o[ 8] = x2 >>> 0 & 0xff; + o[ 9] = x2 >>> 8 & 0xff; + o[10] = x2 >>> 16 & 0xff; + o[11] = x2 >>> 24 & 0xff; + + o[12] = x3 >>> 0 & 0xff; + o[13] = x3 >>> 8 & 0xff; + o[14] = x3 >>> 16 & 0xff; + o[15] = x3 >>> 24 & 0xff; + + o[16] = x4 >>> 0 & 0xff; + o[17] = x4 >>> 8 & 0xff; + o[18] = x4 >>> 16 & 0xff; + o[19] = x4 >>> 24 & 0xff; + + o[20] = x5 >>> 0 & 0xff; + o[21] = x5 >>> 8 & 0xff; + o[22] = x5 >>> 16 & 0xff; + o[23] = x5 >>> 24 & 0xff; + + o[24] = x6 >>> 0 & 0xff; + o[25] = x6 >>> 8 & 0xff; + o[26] = x6 >>> 16 & 0xff; + o[27] = x6 >>> 24 & 0xff; + + o[28] = x7 >>> 0 & 0xff; + o[29] = x7 >>> 8 & 0xff; + o[30] = x7 >>> 16 & 0xff; + o[31] = x7 >>> 24 & 0xff; + + o[32] = x8 >>> 0 & 0xff; + o[33] = x8 >>> 8 & 0xff; + o[34] = x8 >>> 16 & 0xff; + o[35] = x8 >>> 24 & 0xff; + + o[36] = x9 >>> 0 & 0xff; + o[37] = x9 >>> 8 & 0xff; + o[38] = x9 >>> 16 & 0xff; + o[39] = x9 >>> 24 & 0xff; + + o[40] = x10 >>> 0 & 0xff; + o[41] = x10 >>> 8 & 0xff; + o[42] = x10 >>> 16 & 0xff; + o[43] = x10 >>> 24 & 0xff; + + o[44] = x11 >>> 0 & 0xff; + o[45] = x11 >>> 8 & 0xff; + o[46] = x11 >>> 16 & 0xff; + o[47] = x11 >>> 24 & 0xff; + + o[48] = x12 >>> 0 & 0xff; + o[49] = x12 >>> 8 & 0xff; + o[50] = x12 >>> 16 & 0xff; + o[51] = x12 >>> 24 & 0xff; + + o[52] = x13 >>> 0 & 0xff; + o[53] = x13 >>> 8 & 0xff; + o[54] = x13 >>> 16 & 0xff; + o[55] = x13 >>> 24 & 0xff; + + o[56] = x14 >>> 0 & 0xff; + o[57] = x14 >>> 8 & 0xff; + o[58] = x14 >>> 16 & 0xff; + o[59] = x14 >>> 24 & 0xff; + + o[60] = x15 >>> 0 & 0xff; + o[61] = x15 >>> 8 & 0xff; + o[62] = x15 >>> 16 & 0xff; + o[63] = x15 >>> 24 & 0xff; +} + +function core_hsalsa20(o,p,k,c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + + o[ 4] = x5 >>> 0 & 0xff; + o[ 5] = x5 >>> 8 & 0xff; + o[ 6] = x5 >>> 16 & 0xff; + o[ 7] = x5 >>> 24 & 0xff; + + o[ 8] = x10 >>> 0 & 0xff; + o[ 9] = x10 >>> 8 & 0xff; + o[10] = x10 >>> 16 & 0xff; + o[11] = x10 >>> 24 & 0xff; + + o[12] = x15 >>> 0 & 0xff; + o[13] = x15 >>> 8 & 0xff; + o[14] = x15 >>> 16 & 0xff; + o[15] = x15 >>> 24 & 0xff; + + o[16] = x6 >>> 0 & 0xff; + o[17] = x6 >>> 8 & 0xff; + o[18] = x6 >>> 16 & 0xff; + o[19] = x6 >>> 24 & 0xff; + + o[20] = x7 >>> 0 & 0xff; + o[21] = x7 >>> 8 & 0xff; + o[22] = x7 >>> 16 & 0xff; + o[23] = x7 >>> 24 & 0xff; + + o[24] = x8 >>> 0 & 0xff; + o[25] = x8 >>> 8 & 0xff; + o[26] = x8 >>> 16 & 0xff; + o[27] = x8 >>> 24 & 0xff; + + o[28] = x9 >>> 0 & 0xff; + o[29] = x9 >>> 8 & 0xff; + o[30] = x9 >>> 16 & 0xff; + o[31] = x9 >>> 24 & 0xff; +} + +function crypto_core_salsa20(out,inp,k,c) { + core_salsa20(out,inp,k,c); +} + +function crypto_core_hsalsa20(out,inp,k,c) { + core_hsalsa20(out,inp,k,c); +} + +var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); + // "expand 32-byte k" + +function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + mpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + } + return 0; +} + +function crypto_stream_salsa20(c,cpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = x[i]; + } + return 0; +} + +function crypto_stream(c,cpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20(c,cpos,d,sn,s); +} + +function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); +} + +/* +* Port of Andrew Moon's Poly1305-donna-16. Public domain. +* https://github.com/floodyberry/poly1305-donna +*/ + +var poly1305 = function(key) { + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.leftover = 0; + this.fin = 0; + + var t0, t1, t2, t3, t4, t5, t6, t7; + + t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; + t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = ((t4 >>> 1)) & 0x1ffe; + t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = ((t7 >>> 5)) & 0x007f; + + this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; + this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; + this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; + this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; + this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; + this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; + this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; + this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; +}; + +poly1305.prototype.blocks = function(m, mpos, bytes) { + var hibit = this.fin ? 0 : (1 << 11); + var t0, t1, t2, t3, t4, t5, t6, t7, c; + var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; + + var h0 = this.h[0], + h1 = this.h[1], + h2 = this.h[2], + h3 = this.h[3], + h4 = this.h[4], + h5 = this.h[5], + h6 = this.h[6], + h7 = this.h[7], + h8 = this.h[8], + h9 = this.h[9]; + + var r0 = this.r[0], + r1 = this.r[1], + r2 = this.r[2], + r3 = this.r[3], + r4 = this.r[4], + r5 = this.r[5], + r6 = this.r[6], + r7 = this.r[7], + r8 = this.r[8], + r9 = this.r[9]; + + while (bytes >= 16) { + t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; + t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; + t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; + h5 += ((t4 >>> 1)) & 0x1fff; + t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; + t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + h9 += ((t7 >>> 5)) | hibit; + + c = 0; + + d0 = c; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h2 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c = (d0 >>> 13); d0 &= 0x1fff; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c += (d0 >>> 13); d0 &= 0x1fff; + + d1 = c; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h2 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c = (d1 >>> 13); d1 &= 0x1fff; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c += (d1 >>> 13); d1 &= 0x1fff; + + d2 = c; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h2 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c = (d2 >>> 13); d2 &= 0x1fff; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c += (d2 >>> 13); d2 &= 0x1fff; + + d3 = c; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h2 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c = (d3 >>> 13); d3 &= 0x1fff; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c += (d3 >>> 13); d3 &= 0x1fff; + + d4 = c; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h2 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c = (d4 >>> 13); d4 &= 0x1fff; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c += (d4 >>> 13); d4 &= 0x1fff; + + d5 = c; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h2 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c = (d5 >>> 13); d5 &= 0x1fff; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c += (d5 >>> 13); d5 &= 0x1fff; + + d6 = c; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h2 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c = (d6 >>> 13); d6 &= 0x1fff; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c += (d6 >>> 13); d6 &= 0x1fff; + + d7 = c; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h2 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c = (d7 >>> 13); d7 &= 0x1fff; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c += (d7 >>> 13); d7 &= 0x1fff; + + d8 = c; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h2 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c = (d8 >>> 13); d8 &= 0x1fff; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c += (d8 >>> 13); d8 &= 0x1fff; + + d9 = c; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h2 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c = (d9 >>> 13); d9 &= 0x1fff; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c += (d9 >>> 13); d9 &= 0x1fff; + + c = (((c << 2) + c)) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = (c >>> 13); + d1 += c; + + h0 = d0; + h1 = d1; + h2 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; + + mpos += 16; + bytes -= 16; + } + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h2; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; +}; + +poly1305.prototype.finish = function(mac, macpos) { + var g = new Uint16Array(10); + var c, mask, f, i; + + if (this.leftover) { + i = this.leftover; + this.buffer[i++] = 1; + for (; i < 16; i++) this.buffer[i] = 0; + this.fin = 1; + this.blocks(this.buffer, 0, 16); + } + + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + for (i = 2; i < 10; i++) { + this.h[i] += c; + c = this.h[i] >>> 13; + this.h[i] &= 0x1fff; + } + this.h[0] += (c * 5); + c = this.h[0] >>> 13; + this.h[0] &= 0x1fff; + this.h[1] += c; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + this.h[2] += c; + + g[0] = this.h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (i = 1; i < 10; i++) { + g[i] = this.h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= (1 << 13); + + mask = (c ^ 1) - 1; + for (i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; + + this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; + this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; + this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; + this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; + this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; + this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; + this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; + this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; + + f = this.h[0] + this.pad[0]; + this.h[0] = f & 0xffff; + for (i = 1; i < 8; i++) { + f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; + this.h[i] = f & 0xffff; + } + + mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; + mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; + mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; + mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; + mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; + mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; + mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; + mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; + mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; + mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; + mac[macpos+10] = (this.h[5] >>> 0) & 0xff; + mac[macpos+11] = (this.h[5] >>> 8) & 0xff; + mac[macpos+12] = (this.h[6] >>> 0) & 0xff; + mac[macpos+13] = (this.h[6] >>> 8) & 0xff; + mac[macpos+14] = (this.h[7] >>> 0) & 0xff; + mac[macpos+15] = (this.h[7] >>> 8) & 0xff; +}; + +poly1305.prototype.update = function(m, mpos, bytes) { + var i, want; + + if (this.leftover) { + want = (16 - this.leftover); + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) + return; + this.blocks(this.buffer, 0, 16); + this.leftover = 0; + } + + if (bytes >= 16) { + want = bytes - (bytes % 16); + this.blocks(m, mpos, want); + mpos += want; + bytes -= want; + } + + if (bytes) { + for (i = 0; i < bytes; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + this.leftover += bytes; + } +}; + +function crypto_onetimeauth(out, outpos, m, mpos, n, k) { + var s = new poly1305(k); + s.update(m, mpos, n); + s.finish(out, outpos); + return 0; +} + +function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { + var x = new Uint8Array(16); + crypto_onetimeauth(x,0,m,mpos,n,k); + return crypto_verify_16(h,hpos,x,0); +} + +function crypto_secretbox(c,m,d,n,k) { + var i; + if (d < 32) return -1; + crypto_stream_xor(c,0,m,0,d,n,k); + crypto_onetimeauth(c, 16, c, 32, d - 32, c); + for (i = 0; i < 16; i++) c[i] = 0; + return 0; +} + +function crypto_secretbox_open(m,c,d,n,k) { + var i; + var x = new Uint8Array(32); + if (d < 32) return -1; + crypto_stream(x,0,32,n,k); + if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; + crypto_stream_xor(m,0,c,0,d,n,k); + for (i = 0; i < 32; i++) m[i] = 0; + return 0; +} + +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} + +function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c-1 + 37 * (c-1); +} + +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; + } +} + +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} + +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; +} + +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} + +function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +} + +function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +} + +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is + + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} + +function S(o, a) { + M(o, a, a); +} + +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; + } + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); + } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; + } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; +} + +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); +} + +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); +} + +function crypto_box_beforenm(k, y, x) { + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y); + return crypto_core_hsalsa20(k, _0, s, sigma); +} + +var crypto_box_afternm = crypto_secretbox; +var crypto_box_open_afternm = crypto_secretbox_open; + +function crypto_box(c, m, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_afternm(c, m, d, n, k); +} + +function crypto_box_open(m, c, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_open_afternm(m, c, d, n, k); +} + +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 +]; + +function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; + + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; + } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; + + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; + + // add + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // K + h = K[i*2]; + l = K[i*2+1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // w + h = wh[i%16]; + l = wl[i%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; + + // add + h = th; + l = tl; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); + + // add + h = bh3; + l = bl3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = th; + l = tl; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); + + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); + } + } + } + + // add + h = ah0; + l = al0; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[0]; + l = hl[0]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); + + h = ah1; + l = al1; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[1]; + l = hl[1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); + + h = ah2; + l = al2; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[2]; + l = hl[2]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); + + h = ah3; + l = al3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[3]; + l = hl[3]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); + + h = ah4; + l = al4; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[4]; + l = hl[4]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); + + h = ah5; + l = al5; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[5]; + l = hl[5]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); + + h = ah6; + l = al6; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[6]; + l = hl[6]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); + + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[7]; + l = hl[7]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); + + pos += 128; + n -= 128; + } + + return n; +} + +function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; + + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; + + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; + + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; + + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; + + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); + + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); + + return 0; +} + +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } +} + +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} + +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } +} + +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} + +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; + + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + scalarbase(p, d); + pack(pk, p); + + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} + +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); + +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = Math.floor((x[j] + 128) / 256); + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} + +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} + +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; + + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); + + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; + } + } + + modL(sm.subarray(32), x); + return smlen; +} + +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + return 0; +} + +function crypto_sign_open(m, sm, n, pk) { + var i; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; + + if (n < 64) return -1; + + if (unpackneg(q, pk)) return -1; + + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); + + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; + } + + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + return n; +} + +var crypto_secretbox_KEYBYTES = 32, + crypto_secretbox_NONCEBYTES = 24, + crypto_secretbox_ZEROBYTES = 32, + crypto_secretbox_BOXZEROBYTES = 16, + crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_box_BEFORENMBYTES = 32, + crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, + crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, + crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32, + crypto_hash_BYTES = 64; + +nacl.lowlevel = { + crypto_core_hsalsa20: crypto_core_hsalsa20, + crypto_stream_xor: crypto_stream_xor, + crypto_stream: crypto_stream, + crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, + crypto_stream_salsa20: crypto_stream_salsa20, + crypto_onetimeauth: crypto_onetimeauth, + crypto_onetimeauth_verify: crypto_onetimeauth_verify, + crypto_verify_16: crypto_verify_16, + crypto_verify_32: crypto_verify_32, + crypto_secretbox: crypto_secretbox, + crypto_secretbox_open: crypto_secretbox_open, + crypto_scalarmult: crypto_scalarmult, + crypto_scalarmult_base: crypto_scalarmult_base, + crypto_box_beforenm: crypto_box_beforenm, + crypto_box_afternm: crypto_box_afternm, + crypto_box: crypto_box, + crypto_box_open: crypto_box_open, + crypto_box_keypair: crypto_box_keypair, + crypto_hash: crypto_hash, + crypto_sign: crypto_sign, + crypto_sign_keypair: crypto_sign_keypair, + crypto_sign_open: crypto_sign_open, + + crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, + crypto_sign_BYTES: crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, + crypto_hash_BYTES: crypto_hash_BYTES, + + gf: gf, + D: D, + L: L, + pack25519: pack25519, + unpack25519: unpack25519, + M: M, + A: A, + S: S, + Z: Z, + pow2523: pow2523, + add: add, + set25519: set25519, + modL: modL, + scalarmult: scalarmult, + scalarbase: scalarbase, +}; + +/* High-level API */ + +function checkLengths(k, n) { + if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); +} + +function checkBoxLengths(pk, sk) { + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); +} + +function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError('unexpected type, use Uint8Array'); + } +} + +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} + +nacl.randomBytes = function(n) { + var b = new Uint8Array(n); + randombytes(b, n); + return b; +}; + +nacl.secretbox = function(msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c = new Uint8Array(m.length); + for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; + crypto_secretbox(c, m, m.length, nonce, key); + return c.subarray(crypto_secretbox_BOXZEROBYTES); +}; + +nacl.secretbox.open = function(box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m = new Uint8Array(c.length); + for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; + if (c.length < 32) return null; + if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null; + return m.subarray(crypto_secretbox_ZEROBYTES); +}; + +nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; +nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; +nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; + +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; + +nacl.scalarMult.base = function(n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; +}; + +nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; +nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; + +nacl.box = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k); +}; + +nacl.box.before = function(publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k, publicKey, secretKey); + return k; +}; + +nacl.box.after = nacl.secretbox; + +nacl.box.open = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k); +}; + +nacl.box.open.after = nacl.secretbox.open; + +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; +nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; +nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; +nacl.box.nonceLength = crypto_box_NONCEBYTES; +nacl.box.overheadLength = nacl.secretbox.overheadLength; + +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; + +nacl.sign.open = function(signedMsg, publicKey) { + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m = new Uint8Array(mlen); + for (var i = 0; i < m.length; i++) m[i] = tmp[i]; + return m; +}; + +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; + +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; + +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; +nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; +nacl.sign.seedLength = crypto_sign_SEEDBYTES; +nacl.sign.signatureLength = crypto_sign_BYTES; + +nacl.hash = function(msg) { + checkArrayTypes(msg); + var h = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h, msg, msg.length); + return h; +}; + +nacl.hash.hashLength = crypto_hash_BYTES; + +nacl.verify = function(x, y) { + checkArrayTypes(x, y); + // Zero length arguments are considered not equal. + if (x.length === 0 || y.length === 0) return false; + if (x.length !== y.length) return false; + return (vn(x, 0, y, 0, x.length) === 0) ? true : false; +}; + +nacl.setPRNG = function(fn) { + randombytes = fn; +}; + +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; + if (crypto && crypto.getRandomValues) { + // Browsers. + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } else if (true) { + // Node.js. + crypto = __webpack_require__(2894); + if (crypto && crypto.randomBytes) { + nacl.setPRNG(function(x, n) { + var i, v = crypto.randomBytes(n); + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } + } +})(); + +})( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); + + +/***/ }), + +/***/ 1924: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ StellarBase: () => (/* reexport module object */ _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2__), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ httpClient: () => (/* reexport safe */ _http_client__WEBPACK_IMPORTED_MODULE_0__.ok) +/* harmony export */ }); +/* harmony import */ var _http_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6371); +/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4356); +/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {}; +/* harmony reexport (unknown) */ for(const __WEBPACK_IMPORT_KEY__ in _index__WEBPACK_IMPORTED_MODULE_1__) if(["default","StellarBase","httpClient"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = () => _index__WEBPACK_IMPORTED_MODULE_1__[__WEBPACK_IMPORT_KEY__] +/* harmony reexport (unknown) */ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2__); +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (module.exports); + +/***/ }), + +/***/ 8732: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ T: () => (/* binding */ Config) +/* harmony export */ }); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var defaultConfig = { + allowHttp: false, + timeout: 0 +}; +var config = _objectSpread({}, defaultConfig); +var Config = function () { + function Config() { + _classCallCheck(this, Config); + } + return _createClass(Config, null, [{ + key: "setAllowHttp", + value: function setAllowHttp(value) { + config.allowHttp = value; + } + }, { + key: "setTimeout", + value: function setTimeout(value) { + config.timeout = value; + } + }, { + key: "isAllowHttp", + value: function isAllowHttp() { + return config.allowHttp; + } + }, { + key: "getTimeout", + value: function getTimeout() { + return config.timeout; + } + }, { + key: "setDefault", + value: function setDefault() { + config = _objectSpread({}, defaultConfig); + } + }]); +}(); + + +/***/ }), + +/***/ 6299: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + AssembledTransaction: () => (/* reexport */ AssembledTransaction), + Client: () => (/* reexport */ Client), + DEFAULT_TIMEOUT: () => (/* reexport */ DEFAULT_TIMEOUT), + Err: () => (/* reexport */ Err), + NULL_ACCOUNT: () => (/* reexport */ NULL_ACCOUNT), + Ok: () => (/* reexport */ Ok), + SentTransaction: () => (/* reexport */ SentTransaction), + Spec: () => (/* reexport */ Spec), + basicNodeSigner: () => (/* reexport */ basicNodeSigner) +}); + +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./src/rpc/index.ts + 3 modules +var rpc = __webpack_require__(3496); +// EXTERNAL MODULE: ./src/rpc/api.ts +var api = __webpack_require__(4076); +// EXTERNAL MODULE: ./src/rpc/transaction.ts +var transaction = __webpack_require__(8680); +;// ./src/contract/rust_result.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Ok = function () { + function Ok(value) { + _classCallCheck(this, Ok); + this.value = value; + } + return _createClass(Ok, [{ + key: "unwrapErr", + value: function unwrapErr() { + throw new Error("No error"); + } + }, { + key: "unwrap", + value: function unwrap() { + return this.value; + } + }, { + key: "isOk", + value: function isOk() { + return true; + } + }, { + key: "isErr", + value: function isErr() { + return false; + } + }]); +}(); +var Err = function () { + function Err(error) { + _classCallCheck(this, Err); + this.error = error; + } + return _createClass(Err, [{ + key: "unwrapErr", + value: function unwrapErr() { + return this.error; + } + }, { + key: "unwrap", + value: function unwrap() { + throw new Error(this.error.message); + } + }, { + key: "isOk", + value: function isOk() { + return false; + } + }, { + key: "isErr", + value: function isErr() { + return true; + } + }]); +}(); +;// ./src/contract/types.ts + +var DEFAULT_TIMEOUT = 5 * 60; +var NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; +;// ./src/contract/utils.ts +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == utils_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(utils_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function utils_typeof(o) { "@babel/helpers - typeof"; return utils_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, utils_typeof(o); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + + +function withExponentialBackoff(_x, _x2, _x3) { + return _withExponentialBackoff.apply(this, arguments); +} +function _withExponentialBackoff() { + _withExponentialBackoff = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(fn, keepWaitingIf, timeoutInSeconds) { + var exponentialFactor, + verbose, + attempts, + count, + waitUntil, + waitTime, + totalWaitTime, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + exponentialFactor = _args.length > 3 && _args[3] !== undefined ? _args[3] : 1.5; + verbose = _args.length > 4 && _args[4] !== undefined ? _args[4] : false; + attempts = []; + count = 0; + _context.t0 = attempts; + _context.next = 7; + return fn(); + case 7: + _context.t1 = _context.sent; + _context.t0.push.call(_context.t0, _context.t1); + if (keepWaitingIf(attempts[attempts.length - 1])) { + _context.next = 11; + break; + } + return _context.abrupt("return", attempts); + case 11: + waitUntil = new Date(Date.now() + timeoutInSeconds * 1000).valueOf(); + waitTime = 1000; + totalWaitTime = waitTime; + case 14: + if (!(Date.now() < waitUntil && keepWaitingIf(attempts[attempts.length - 1]))) { + _context.next = 30; + break; + } + count += 1; + if (verbose) { + console.info("Waiting ".concat(waitTime, "ms before trying again (bringing the total wait time to ").concat(totalWaitTime, "ms so far, of total ").concat(timeoutInSeconds * 1000, "ms)")); + } + _context.next = 19; + return new Promise(function (res) { + return setTimeout(res, waitTime); + }); + case 19: + waitTime *= exponentialFactor; + if (new Date(Date.now() + waitTime).valueOf() > waitUntil) { + waitTime = waitUntil - Date.now(); + if (verbose) { + console.info("was gonna wait too long; new waitTime: ".concat(waitTime, "ms")); + } + } + totalWaitTime = waitTime + totalWaitTime; + _context.t2 = attempts; + _context.next = 25; + return fn(attempts[attempts.length - 1]); + case 25: + _context.t3 = _context.sent; + _context.t2.push.call(_context.t2, _context.t3); + if (verbose && keepWaitingIf(attempts[attempts.length - 1])) { + console.info("".concat(count, ". Called ").concat(fn, "; ").concat(attempts.length, " prev attempts. Most recent: ").concat(JSON.stringify(attempts[attempts.length - 1], null, 2))); + } + _context.next = 14; + break; + case 30: + return _context.abrupt("return", attempts); + case 31: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _withExponentialBackoff.apply(this, arguments); +} +var contractErrorPattern = /Error\(Contract, #(\d+)\)/; +function implementsToString(obj) { + return utils_typeof(obj) === "object" && obj !== null && "toString" in obj; +} +function processSpecEntryStream(buffer) { + var reader = new lib.cereal.XdrReader(buffer); + var res = []; + while (!reader.eof) { + res.push(lib.xdr.ScSpecEntry.read(reader)); + } + return res; +} +function getAccount(_x4, _x5) { + return _getAccount.apply(this, arguments); +} +function _getAccount() { + _getAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(options, server) { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", options.publicKey ? server.getAccount(options.publicKey) : new lib.Account(NULL_ACCOUNT, "0")); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _getAccount.apply(this, arguments); +} +;// ./src/contract/sent_transaction.ts +var _SentTransaction; +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == sent_transaction_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function sent_transaction_typeof(o) { "@babel/helpers - typeof"; return sent_transaction_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, sent_transaction_typeof(o); } +function sent_transaction_regeneratorRuntime() { "use strict"; sent_transaction_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == sent_transaction_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(sent_transaction_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function sent_transaction_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function sent_transaction_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { sent_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { sent_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function sent_transaction_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function sent_transaction_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, sent_transaction_toPropertyKey(o.key), o); } } +function sent_transaction_createClass(e, r, t) { return r && sent_transaction_defineProperties(e.prototype, r), t && sent_transaction_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = sent_transaction_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function sent_transaction_toPropertyKey(t) { var i = sent_transaction_toPrimitive(t, "string"); return "symbol" == sent_transaction_typeof(i) ? i : i + ""; } +function sent_transaction_toPrimitive(t, r) { if ("object" != sent_transaction_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != sent_transaction_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + +var SentTransaction = function () { + function SentTransaction(assembled) { + var _this = this, + _this$assembled$optio2; + sent_transaction_classCallCheck(this, SentTransaction); + _defineProperty(this, "send", sent_transaction_asyncToGenerator(sent_transaction_regeneratorRuntime().mark(function _callee() { + var _this$assembled$optio; + var hash, timeoutInSeconds; + return sent_transaction_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return _this.server.sendTransaction(_this.assembled.signed); + case 2: + _this.sendTransactionResponse = _context.sent; + if (!(_this.sendTransactionResponse.status !== "PENDING")) { + _context.next = 5; + break; + } + throw new SentTransaction.Errors.SendFailed("Sending the transaction to the network failed!\n".concat(JSON.stringify(_this.sendTransactionResponse, null, 2))); + case 5: + hash = _this.sendTransactionResponse.hash; + timeoutInSeconds = (_this$assembled$optio = _this.assembled.options.timeoutInSeconds) !== null && _this$assembled$optio !== void 0 ? _this$assembled$optio : DEFAULT_TIMEOUT; + _context.next = 9; + return withExponentialBackoff(function () { + return _this.server.getTransaction(hash); + }, function (resp) { + return resp.status === api/* Api */.j.GetTransactionStatus.NOT_FOUND; + }, timeoutInSeconds); + case 9: + _this.getTransactionResponseAll = _context.sent; + _this.getTransactionResponse = _this.getTransactionResponseAll[_this.getTransactionResponseAll.length - 1]; + if (!(_this.getTransactionResponse.status === api/* Api */.j.GetTransactionStatus.NOT_FOUND)) { + _context.next = 13; + break; + } + throw new SentTransaction.Errors.TransactionStillPending("Waited ".concat(timeoutInSeconds, " seconds for transaction to complete, but it did not. ") + "Returning anyway. Check the transaction status manually. " + "Sent transaction: ".concat(JSON.stringify(_this.sendTransactionResponse, null, 2), "\n") + "All attempts to get the result: ".concat(JSON.stringify(_this.getTransactionResponseAll, null, 2))); + case 13: + return _context.abrupt("return", _this); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + }))); + this.assembled = assembled; + this.server = new rpc.Server(this.assembled.options.rpcUrl, { + allowHttp: (_this$assembled$optio2 = this.assembled.options.allowHttp) !== null && _this$assembled$optio2 !== void 0 ? _this$assembled$optio2 : false + }); + } + return sent_transaction_createClass(SentTransaction, [{ + key: "result", + get: function get() { + if ("getTransactionResponse" in this && this.getTransactionResponse) { + if ("returnValue" in this.getTransactionResponse) { + return this.assembled.options.parseResultXdr(this.getTransactionResponse.returnValue); + } + throw new Error("Transaction failed! Cannot parse result."); + } + if (this.sendTransactionResponse) { + var _this$sendTransaction; + var errorResult = (_this$sendTransaction = this.sendTransactionResponse.errorResult) === null || _this$sendTransaction === void 0 ? void 0 : _this$sendTransaction.result(); + if (errorResult) { + throw new SentTransaction.Errors.SendFailed("Transaction simulation looked correct, but attempting to send the transaction failed. Check `simulation` and `sendTransactionResponseAll` to troubleshoot. Decoded `sendTransactionResponse.errorResultXdr`: ".concat(errorResult)); + } + throw new SentTransaction.Errors.SendResultOnly("Transaction was sent to the network, but not yet awaited. No result to show. Await transaction completion with `getTransaction(sendTransactionResponse.hash)`"); + } + throw new Error("Sending transaction failed: ".concat(JSON.stringify(this.assembled.signed))); + } + }]); +}(); +_SentTransaction = SentTransaction; +_defineProperty(SentTransaction, "Errors", { + SendFailed: function (_Error) { + function SendFailedError() { + sent_transaction_classCallCheck(this, SendFailedError); + return _callSuper(this, SendFailedError, arguments); + } + _inherits(SendFailedError, _Error); + return sent_transaction_createClass(SendFailedError); + }(_wrapNativeSuper(Error)), + SendResultOnly: function (_Error2) { + function SendResultOnlyError() { + sent_transaction_classCallCheck(this, SendResultOnlyError); + return _callSuper(this, SendResultOnlyError, arguments); + } + _inherits(SendResultOnlyError, _Error2); + return sent_transaction_createClass(SendResultOnlyError); + }(_wrapNativeSuper(Error)), + TransactionStillPending: function (_Error3) { + function TransactionStillPendingError() { + sent_transaction_classCallCheck(this, TransactionStillPendingError); + return _callSuper(this, TransactionStillPendingError, arguments); + } + _inherits(TransactionStillPendingError, _Error3); + return sent_transaction_createClass(TransactionStillPendingError); + }(_wrapNativeSuper(Error)) +}); +_defineProperty(SentTransaction, "init", function () { + var _ref2 = sent_transaction_asyncToGenerator(sent_transaction_regeneratorRuntime().mark(function _callee2(assembled) { + var tx, sent; + return sent_transaction_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + tx = new _SentTransaction(assembled); + _context2.next = 3; + return tx.send(); + case 3: + sent = _context2.sent; + return _context2.abrupt("return", sent); + case 5: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; +}()); +;// ./src/contract/assembled_transaction.ts +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +function assembled_transaction_callSuper(t, o, e) { return o = assembled_transaction_getPrototypeOf(o), assembled_transaction_possibleConstructorReturn(t, assembled_transaction_isNativeReflectConstruct() ? Reflect.construct(o, e || [], assembled_transaction_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function assembled_transaction_possibleConstructorReturn(t, e) { if (e && ("object" == assembled_transaction_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return assembled_transaction_assertThisInitialized(t); } +function assembled_transaction_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function assembled_transaction_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && assembled_transaction_setPrototypeOf(t, e); } +function assembled_transaction_wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return assembled_transaction_wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !assembled_transaction_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return assembled_transaction_construct(t, arguments, assembled_transaction_getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), assembled_transaction_setPrototypeOf(Wrapper, t); }, assembled_transaction_wrapNativeSuper(t); } +function assembled_transaction_construct(t, e, r) { if (assembled_transaction_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && assembled_transaction_setPrototypeOf(p, r.prototype), p; } +function assembled_transaction_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (assembled_transaction_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function assembled_transaction_isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function assembled_transaction_setPrototypeOf(t, e) { return assembled_transaction_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, assembled_transaction_setPrototypeOf(t, e); } +function assembled_transaction_getPrototypeOf(t) { return assembled_transaction_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, assembled_transaction_getPrototypeOf(t); } +function assembled_transaction_typeof(o) { "@babel/helpers - typeof"; return assembled_transaction_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, assembled_transaction_typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { assembled_transaction_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function assembled_transaction_regeneratorRuntime() { "use strict"; assembled_transaction_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == assembled_transaction_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(assembled_transaction_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function assembled_transaction_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function assembled_transaction_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { assembled_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { assembled_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function assembled_transaction_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function assembled_transaction_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, assembled_transaction_toPropertyKey(o.key), o); } } +function assembled_transaction_createClass(e, r, t) { return r && assembled_transaction_defineProperties(e.prototype, r), t && assembled_transaction_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function assembled_transaction_defineProperty(e, r, t) { return (r = assembled_transaction_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function assembled_transaction_toPropertyKey(t) { var i = assembled_transaction_toPrimitive(t, "string"); return "symbol" == assembled_transaction_typeof(i) ? i : i + ""; } +function assembled_transaction_toPrimitive(t, r) { if ("object" != assembled_transaction_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != assembled_transaction_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + + + +var AssembledTransaction = function () { + function AssembledTransaction(options) { + var _this = this, + _this$options$simulat, + _this$options$allowHt; + assembled_transaction_classCallCheck(this, AssembledTransaction); + assembled_transaction_defineProperty(this, "simulate", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee() { + var _restore; + var _ref2, + restore, + account, + result, + _this$options$fee, + _this$options$args, + _this$options$timeout, + contract, + _args = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _ref2 = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, restore = _ref2.restore; + if (_this.built) { + _context.next = 5; + break; + } + if (_this.raw) { + _context.next = 4; + break; + } + throw new Error("Transaction has not yet been assembled; " + "call `AssembledTransaction.build` first."); + case 4: + _this.built = _this.raw.build(); + case 5: + restore = (_restore = restore) !== null && _restore !== void 0 ? _restore : _this.options.restore; + delete _this.simulationResult; + delete _this.simulationTransactionData; + _context.next = 10; + return _this.server.simulateTransaction(_this.built); + case 10: + _this.simulation = _context.sent; + if (!(restore && api/* Api */.j.isSimulationRestore(_this.simulation))) { + _context.next = 25; + break; + } + _context.next = 14; + return getAccount(_this.options, _this.server); + case 14: + account = _context.sent; + _context.next = 17; + return _this.restoreFootprint(_this.simulation.restorePreamble, account); + case 17: + result = _context.sent; + if (!(result.status === api/* Api */.j.GetTransactionStatus.SUCCESS)) { + _context.next = 24; + break; + } + contract = new lib.Contract(_this.options.contractId); + _this.raw = new lib.TransactionBuilder(account, { + fee: (_this$options$fee = _this.options.fee) !== null && _this$options$fee !== void 0 ? _this$options$fee : lib.BASE_FEE, + networkPassphrase: _this.options.networkPassphrase + }).addOperation(contract.call.apply(contract, [_this.options.method].concat(_toConsumableArray((_this$options$args = _this.options.args) !== null && _this$options$args !== void 0 ? _this$options$args : [])))).setTimeout((_this$options$timeout = _this.options.timeoutInSeconds) !== null && _this$options$timeout !== void 0 ? _this$options$timeout : DEFAULT_TIMEOUT); + _context.next = 23; + return _this.simulate(); + case 23: + return _context.abrupt("return", _this); + case 24: + throw new AssembledTransaction.Errors.RestorationFailure("Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n".concat(JSON.stringify(result))); + case 25: + if (api/* Api */.j.isSimulationSuccess(_this.simulation)) { + _this.built = (0,transaction/* assembleTransaction */.X)(_this.built, _this.simulation).build(); + } + return _context.abrupt("return", _this); + case 27: + case "end": + return _context.stop(); + } + }, _callee); + }))); + assembled_transaction_defineProperty(this, "sign", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee2() { + var _this$options$timeout2; + var _ref4, + _ref4$force, + force, + _ref4$signTransaction, + signTransaction, + sigsNeeded, + timeoutInSeconds, + signOpts, + _yield$signTransactio, + signature, + error, + _args2 = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _ref4 = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref4$force = _ref4.force, force = _ref4$force === void 0 ? false : _ref4$force, _ref4$signTransaction = _ref4.signTransaction, signTransaction = _ref4$signTransaction === void 0 ? _this.options.signTransaction : _ref4$signTransaction; + if (_this.built) { + _context2.next = 3; + break; + } + throw new Error("Transaction has not yet been simulated"); + case 3: + if (!(!force && _this.isReadCall)) { + _context2.next = 5; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("This is a read call. It requires no signature or sending. " + "Use `force: true` to sign and send anyway."); + case 5: + if (signTransaction) { + _context2.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide a signTransaction function, either when calling " + "`signAndSend` or when initializing your Client"); + case 7: + sigsNeeded = _this.needsNonInvokerSigningBy().filter(function (id) { + return !id.startsWith('C'); + }); + if (!sigsNeeded.length) { + _context2.next = 10; + break; + } + throw new AssembledTransaction.Errors.NeedsMoreSignatures("Transaction requires signatures from ".concat(sigsNeeded, ". ") + "See `needsNonInvokerSigningBy` for details."); + case 10: + timeoutInSeconds = (_this$options$timeout2 = _this.options.timeoutInSeconds) !== null && _this$options$timeout2 !== void 0 ? _this$options$timeout2 : DEFAULT_TIMEOUT; + _this.built = lib.TransactionBuilder.cloneFrom(_this.built, { + fee: _this.built.fee, + timebounds: undefined, + sorobanData: _this.simulationData.transactionData + }).setTimeout(timeoutInSeconds).build(); + signOpts = { + networkPassphrase: _this.options.networkPassphrase + }; + if (_this.options.address) signOpts.address = _this.options.address; + if (_this.options.submit !== undefined) signOpts.submit = _this.options.submit; + if (_this.options.submitUrl) signOpts.submitUrl = _this.options.submitUrl; + _context2.next = 18; + return signTransaction(_this.built.toXDR(), signOpts); + case 18: + _yield$signTransactio = _context2.sent; + signature = _yield$signTransactio.signedTxXdr; + error = _yield$signTransactio.error; + _this.handleWalletError(error); + _this.signed = lib.TransactionBuilder.fromXDR(signature, _this.options.networkPassphrase); + case 23: + case "end": + return _context2.stop(); + } + }, _callee2); + }))); + assembled_transaction_defineProperty(this, "signAndSend", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee3() { + var _ref6, + _ref6$force, + force, + _ref6$signTransaction, + signTransaction, + originalSubmit, + _args3 = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _ref6 = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : {}, _ref6$force = _ref6.force, force = _ref6$force === void 0 ? false : _ref6$force, _ref6$signTransaction = _ref6.signTransaction, signTransaction = _ref6$signTransaction === void 0 ? _this.options.signTransaction : _ref6$signTransaction; + if (_this.signed) { + _context3.next = 10; + break; + } + originalSubmit = _this.options.submit; + if (_this.options.submit) { + _this.options.submit = false; + } + _context3.prev = 4; + _context3.next = 7; + return _this.sign({ + force: force, + signTransaction: signTransaction + }); + case 7: + _context3.prev = 7; + _this.options.submit = originalSubmit; + return _context3.finish(7); + case 10: + return _context3.abrupt("return", _this.send()); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3, null, [[4,, 7, 10]]); + }))); + assembled_transaction_defineProperty(this, "needsNonInvokerSigningBy", function () { + var _rawInvokeHostFunctio; + var _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref7$includeAlreadyS = _ref7.includeAlreadySigned, + includeAlreadySigned = _ref7$includeAlreadyS === void 0 ? false : _ref7$includeAlreadyS; + if (!_this.built) { + throw new Error("Transaction has not yet been simulated"); + } + if (!("operations" in _this.built)) { + throw new Error("Unexpected Transaction type; no operations: ".concat(JSON.stringify(_this.built))); + } + var rawInvokeHostFunctionOp = _this.built.operations[0]; + return _toConsumableArray(new Set(((_rawInvokeHostFunctio = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio !== void 0 ? _rawInvokeHostFunctio : []).filter(function (entry) { + return entry.credentials().switch() === lib.xdr.SorobanCredentialsType.sorobanCredentialsAddress() && (includeAlreadySigned || entry.credentials().address().signature().switch().name === "scvVoid"); + }).map(function (entry) { + return lib.Address.fromScAddress(entry.credentials().address().address()).toString(); + }))); + }); + assembled_transaction_defineProperty(this, "signAuthEntries", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee6() { + var _rawInvokeHostFunctio2; + var _ref9, + _ref9$expiration, + expiration, + _ref9$signAuthEntry, + signAuthEntry, + _ref9$address, + address, + _ref9$authorizeEntry, + authorizeEntry, + needsNonInvokerSigningBy, + rawInvokeHostFunctionOp, + authEntries, + _iterator, + _step, + _loop, + _ret, + _args7 = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee6$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _ref9 = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {}, _ref9$expiration = _ref9.expiration, expiration = _ref9$expiration === void 0 ? assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee4() { + return assembled_transaction_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this.server.getLatestLedger(); + case 2: + _context4.t0 = _context4.sent.sequence; + return _context4.abrupt("return", _context4.t0 + 100); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + }))() : _ref9$expiration, _ref9$signAuthEntry = _ref9.signAuthEntry, signAuthEntry = _ref9$signAuthEntry === void 0 ? _this.options.signAuthEntry : _ref9$signAuthEntry, _ref9$address = _ref9.address, address = _ref9$address === void 0 ? _this.options.publicKey : _ref9$address, _ref9$authorizeEntry = _ref9.authorizeEntry, authorizeEntry = _ref9$authorizeEntry === void 0 ? lib.authorizeEntry : _ref9$authorizeEntry; + if (_this.built) { + _context7.next = 3; + break; + } + throw new Error("Transaction has not yet been assembled or simulated"); + case 3: + if (!(authorizeEntry === lib.authorizeEntry)) { + _context7.next = 11; + break; + } + needsNonInvokerSigningBy = _this.needsNonInvokerSigningBy(); + if (!(needsNonInvokerSigningBy.length === 0)) { + _context7.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?"); + case 7: + if (!(needsNonInvokerSigningBy.indexOf(address !== null && address !== void 0 ? address : "") === -1)) { + _context7.next = 9; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("No auth entries for public key \"".concat(address, "\"")); + case 9: + if (signAuthEntry) { + _context7.next = 11; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`"); + case 11: + rawInvokeHostFunctionOp = _this.built.operations[0]; + authEntries = (_rawInvokeHostFunctio2 = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio2 !== void 0 ? _rawInvokeHostFunctio2 : []; + _iterator = _createForOfIteratorHelper(authEntries.entries()); + _context7.prev = 14; + _loop = assembled_transaction_regeneratorRuntime().mark(function _loop() { + var _step$value, i, entry, credentials, authEntryAddress, sign; + return assembled_transaction_regeneratorRuntime().wrap(function _loop$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _step$value = _slicedToArray(_step.value, 2), i = _step$value[0], entry = _step$value[1]; + credentials = lib.xdr.SorobanCredentials.fromXDR(entry.credentials().toXDR()); + if (!(credentials.switch() !== lib.xdr.SorobanCredentialsType.sorobanCredentialsAddress())) { + _context6.next = 4; + break; + } + return _context6.abrupt("return", 0); + case 4: + authEntryAddress = lib.Address.fromScAddress(credentials.address().address()).toString(); + if (!(authEntryAddress !== address)) { + _context6.next = 7; + break; + } + return _context6.abrupt("return", 0); + case 7: + sign = signAuthEntry !== null && signAuthEntry !== void 0 ? signAuthEntry : Promise.resolve; + _context6.t0 = authorizeEntry; + _context6.t1 = entry; + _context6.t2 = function () { + var _ref11 = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee5(preimage) { + var _yield$sign, signedAuthEntry, error; + return assembled_transaction_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return sign(preimage.toXDR("base64"), { + address: address + }); + case 2: + _yield$sign = _context5.sent; + signedAuthEntry = _yield$sign.signedAuthEntry; + error = _yield$sign.error; + _this.handleWalletError(error); + return _context5.abrupt("return", Buffer.from(signedAuthEntry, "base64")); + case 7: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x) { + return _ref11.apply(this, arguments); + }; + }(); + _context6.next = 13; + return expiration; + case 13: + _context6.t3 = _context6.sent; + _context6.t4 = _this.options.networkPassphrase; + _context6.next = 17; + return (0, _context6.t0)(_context6.t1, _context6.t2, _context6.t3, _context6.t4); + case 17: + authEntries[i] = _context6.sent; + case 18: + case "end": + return _context6.stop(); + } + }, _loop); + }); + _iterator.s(); + case 17: + if ((_step = _iterator.n()).done) { + _context7.next = 24; + break; + } + return _context7.delegateYield(_loop(), "t0", 19); + case 19: + _ret = _context7.t0; + if (!(_ret === 0)) { + _context7.next = 22; + break; + } + return _context7.abrupt("continue", 22); + case 22: + _context7.next = 17; + break; + case 24: + _context7.next = 29; + break; + case 26: + _context7.prev = 26; + _context7.t1 = _context7["catch"](14); + _iterator.e(_context7.t1); + case 29: + _context7.prev = 29; + _iterator.f(); + return _context7.finish(29); + case 32: + case "end": + return _context7.stop(); + } + }, _callee6, null, [[14, 26, 29, 32]]); + }))); + this.options = options; + this.options.simulate = (_this$options$simulat = this.options.simulate) !== null && _this$options$simulat !== void 0 ? _this$options$simulat : true; + this.server = new rpc.Server(this.options.rpcUrl, { + allowHttp: (_this$options$allowHt = this.options.allowHttp) !== null && _this$options$allowHt !== void 0 ? _this$options$allowHt : false + }); + } + return assembled_transaction_createClass(AssembledTransaction, [{ + key: "toJSON", + value: function toJSON() { + var _this$built; + return JSON.stringify({ + method: this.options.method, + tx: (_this$built = this.built) === null || _this$built === void 0 ? void 0 : _this$built.toXDR(), + simulationResult: { + auth: this.simulationData.result.auth.map(function (a) { + return a.toXDR("base64"); + }), + retval: this.simulationData.result.retval.toXDR("base64") + }, + simulationTransactionData: this.simulationData.transactionData.toXDR("base64") + }); + } + }, { + key: "toXDR", + value: function toXDR() { + var _this$built2; + if (!this.built) throw new Error("Transaction has not yet been simulated; " + "call `AssembledTransaction.simulate` first."); + return (_this$built2 = this.built) === null || _this$built2 === void 0 ? void 0 : _this$built2.toEnvelope().toXDR('base64'); + } + }, { + key: "handleWalletError", + value: function handleWalletError(error) { + if (!error) return; + var message = error.message, + code = error.code; + var fullMessage = "".concat(message).concat(error.ext ? " (".concat(error.ext.join(', '), ")") : ''); + switch (code) { + case -1: + throw new AssembledTransaction.Errors.InternalWalletError(fullMessage); + case -2: + throw new AssembledTransaction.Errors.ExternalServiceError(fullMessage); + case -3: + throw new AssembledTransaction.Errors.InvalidClientRequest(fullMessage); + case -4: + throw new AssembledTransaction.Errors.UserRejected(fullMessage); + default: + throw new Error("Unhandled error: ".concat(fullMessage)); + } + } + }, { + key: "simulationData", + get: function get() { + var _simulation$result; + if (this.simulationResult && this.simulationTransactionData) { + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + var simulation = this.simulation; + if (!simulation) { + throw new AssembledTransaction.Errors.NotYetSimulated("Transaction has not yet been simulated"); + } + if (api/* Api */.j.isSimulationError(simulation)) { + throw new AssembledTransaction.Errors.SimulationFailed("Transaction simulation failed: \"".concat(simulation.error, "\"")); + } + if (api/* Api */.j.isSimulationRestore(simulation)) { + throw new AssembledTransaction.Errors.ExpiredState("You need to restore some contract state before you can invoke this method.\n" + 'You can set `restore` to true in the method options in order to ' + 'automatically restore the contract state when needed.'); + } + this.simulationResult = (_simulation$result = simulation.result) !== null && _simulation$result !== void 0 ? _simulation$result : { + auth: [], + retval: lib.xdr.ScVal.scvVoid() + }; + this.simulationTransactionData = simulation.transactionData.build(); + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + }, { + key: "result", + get: function get() { + try { + if (!this.simulationData.result) { + throw new Error("No simulation result!"); + } + return this.options.parseResultXdr(this.simulationData.result.retval); + } catch (e) { + if (!implementsToString(e)) throw e; + var err = this.parseError(e.toString()); + if (err) return err; + throw e; + } + } + }, { + key: "parseError", + value: function parseError(errorMessage) { + if (!this.options.errorTypes) return undefined; + var match = errorMessage.match(contractErrorPattern); + if (!match) return undefined; + var i = parseInt(match[1], 10); + var err = this.options.errorTypes[i]; + if (!err) return undefined; + return new Err(err); + } + }, { + key: "send", + value: (function () { + var _send = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee7() { + var sent; + return assembled_transaction_regeneratorRuntime().wrap(function _callee7$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (this.signed) { + _context8.next = 2; + break; + } + throw new Error("The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead."); + case 2: + _context8.next = 4; + return SentTransaction.init(this); + case 4: + sent = _context8.sent; + return _context8.abrupt("return", sent); + case 6: + case "end": + return _context8.stop(); + } + }, _callee7, this); + })); + function send() { + return _send.apply(this, arguments); + } + return send; + }()) + }, { + key: "isReadCall", + get: function get() { + var authsCount = this.simulationData.result.auth.length; + var writeLength = this.simulationData.transactionData.resources().footprint().readWrite().length; + return authsCount === 0 && writeLength === 0; + } + }, { + key: "restoreFootprint", + value: (function () { + var _restoreFootprint = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee8(restorePreamble, account) { + var _account; + var restoreTx, sentTransaction; + return assembled_transaction_regeneratorRuntime().wrap(function _callee8$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + if (this.options.signTransaction) { + _context9.next = 2; + break; + } + throw new Error("For automatic restore to work you must provide a signTransaction function when initializing your Client"); + case 2: + if (!((_account = account) !== null && _account !== void 0)) { + _context9.next = 6; + break; + } + _context9.t0 = _account; + _context9.next = 9; + break; + case 6: + _context9.next = 8; + return getAccount(this.options, this.server); + case 8: + _context9.t0 = _context9.sent; + case 9: + account = _context9.t0; + _context9.next = 12; + return AssembledTransaction.buildFootprintRestoreTransaction(_objectSpread({}, this.options), restorePreamble.transactionData, account, restorePreamble.minResourceFee); + case 12: + restoreTx = _context9.sent; + _context9.next = 15; + return restoreTx.signAndSend(); + case 15: + sentTransaction = _context9.sent; + if (sentTransaction.getTransactionResponse) { + _context9.next = 18; + break; + } + throw new AssembledTransaction.Errors.RestorationFailure("The attempt at automatic restore failed. \n".concat(JSON.stringify(sentTransaction))); + case 18: + return _context9.abrupt("return", sentTransaction.getTransactionResponse); + case 19: + case "end": + return _context9.stop(); + } + }, _callee8, this); + })); + function restoreFootprint(_x2, _x3) { + return _restoreFootprint.apply(this, arguments); + } + return restoreFootprint; + }()) + }], [{ + key: "fromJSON", + value: function fromJSON(options, _ref12) { + var tx = _ref12.tx, + simulationResult = _ref12.simulationResult, + simulationTransactionData = _ref12.simulationTransactionData; + var txn = new AssembledTransaction(options); + txn.built = lib.TransactionBuilder.fromXDR(tx, options.networkPassphrase); + txn.simulationResult = { + auth: simulationResult.auth.map(function (a) { + return lib.xdr.SorobanAuthorizationEntry.fromXDR(a, "base64"); + }), + retval: lib.xdr.ScVal.fromXDR(simulationResult.retval, "base64") + }; + txn.simulationTransactionData = lib.xdr.SorobanTransactionData.fromXDR(simulationTransactionData, "base64"); + return txn; + } + }, { + key: "fromXDR", + value: function fromXDR(options, encodedXDR, spec) { + var _operation$func; + var envelope = lib.xdr.TransactionEnvelope.fromXDR(encodedXDR, "base64"); + var built = lib.TransactionBuilder.fromXDR(envelope, options.networkPassphrase); + var operation = built.operations[0]; + if (!(operation !== null && operation !== void 0 && (_operation$func = operation.func) !== null && _operation$func !== void 0 && _operation$func.value) || typeof operation.func.value !== 'function') { + throw new Error("Could not extract the method from the transaction envelope."); + } + var invokeContractArgs = operation.func.value(); + if (!(invokeContractArgs !== null && invokeContractArgs !== void 0 && invokeContractArgs.functionName)) { + throw new Error("Could not extract the method name from the transaction envelope."); + } + var method = invokeContractArgs.functionName().toString('utf-8'); + var txn = new AssembledTransaction(_objectSpread(_objectSpread({}, options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + txn.built = built; + return txn; + } + }, { + key: "build", + value: function build(options) { + var _options$args; + var contract = new lib.Contract(options.contractId); + return AssembledTransaction.buildWithOp(contract.call.apply(contract, [options.method].concat(_toConsumableArray((_options$args = options.args) !== null && _options$args !== void 0 ? _options$args : []))), options); + } + }, { + key: "buildWithOp", + value: (function () { + var _buildWithOp = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee9(operation, options) { + var _options$fee, _options$timeoutInSec; + var tx, account; + return assembled_transaction_regeneratorRuntime().wrap(function _callee9$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + tx = new AssembledTransaction(options); + _context10.next = 3; + return getAccount(options, tx.server); + case 3: + account = _context10.sent; + tx.raw = new lib.TransactionBuilder(account, { + fee: (_options$fee = options.fee) !== null && _options$fee !== void 0 ? _options$fee : lib.BASE_FEE, + networkPassphrase: options.networkPassphrase + }).setTimeout((_options$timeoutInSec = options.timeoutInSeconds) !== null && _options$timeoutInSec !== void 0 ? _options$timeoutInSec : DEFAULT_TIMEOUT).addOperation(operation); + if (!options.simulate) { + _context10.next = 8; + break; + } + _context10.next = 8; + return tx.simulate(); + case 8: + return _context10.abrupt("return", tx); + case 9: + case "end": + return _context10.stop(); + } + }, _callee9); + })); + function buildWithOp(_x4, _x5) { + return _buildWithOp.apply(this, arguments); + } + return buildWithOp; + }()) + }, { + key: "buildFootprintRestoreTransaction", + value: function () { + var _buildFootprintRestoreTransaction = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee10(options, sorobanData, account, fee) { + var _options$timeoutInSec2; + var tx; + return assembled_transaction_regeneratorRuntime().wrap(function _callee10$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + tx = new AssembledTransaction(options); + tx.raw = new lib.TransactionBuilder(account, { + fee: fee, + networkPassphrase: options.networkPassphrase + }).setSorobanData(sorobanData instanceof lib.SorobanDataBuilder ? sorobanData.build() : sorobanData).addOperation(lib.Operation.restoreFootprint({})).setTimeout((_options$timeoutInSec2 = options.timeoutInSeconds) !== null && _options$timeoutInSec2 !== void 0 ? _options$timeoutInSec2 : DEFAULT_TIMEOUT); + _context11.next = 4; + return tx.simulate({ + restore: false + }); + case 4: + return _context11.abrupt("return", tx); + case 5: + case "end": + return _context11.stop(); + } + }, _callee10); + })); + function buildFootprintRestoreTransaction(_x6, _x7, _x8, _x9) { + return _buildFootprintRestoreTransaction.apply(this, arguments); + } + return buildFootprintRestoreTransaction; + }() + }]); +}(); +assembled_transaction_defineProperty(AssembledTransaction, "Errors", { + ExpiredState: function (_Error) { + function ExpiredStateError() { + assembled_transaction_classCallCheck(this, ExpiredStateError); + return assembled_transaction_callSuper(this, ExpiredStateError, arguments); + } + assembled_transaction_inherits(ExpiredStateError, _Error); + return assembled_transaction_createClass(ExpiredStateError); + }(assembled_transaction_wrapNativeSuper(Error)), + RestorationFailure: function (_Error2) { + function RestoreFailureError() { + assembled_transaction_classCallCheck(this, RestoreFailureError); + return assembled_transaction_callSuper(this, RestoreFailureError, arguments); + } + assembled_transaction_inherits(RestoreFailureError, _Error2); + return assembled_transaction_createClass(RestoreFailureError); + }(assembled_transaction_wrapNativeSuper(Error)), + NeedsMoreSignatures: function (_Error3) { + function NeedsMoreSignaturesError() { + assembled_transaction_classCallCheck(this, NeedsMoreSignaturesError); + return assembled_transaction_callSuper(this, NeedsMoreSignaturesError, arguments); + } + assembled_transaction_inherits(NeedsMoreSignaturesError, _Error3); + return assembled_transaction_createClass(NeedsMoreSignaturesError); + }(assembled_transaction_wrapNativeSuper(Error)), + NoSignatureNeeded: function (_Error4) { + function NoSignatureNeededError() { + assembled_transaction_classCallCheck(this, NoSignatureNeededError); + return assembled_transaction_callSuper(this, NoSignatureNeededError, arguments); + } + assembled_transaction_inherits(NoSignatureNeededError, _Error4); + return assembled_transaction_createClass(NoSignatureNeededError); + }(assembled_transaction_wrapNativeSuper(Error)), + NoUnsignedNonInvokerAuthEntries: function (_Error5) { + function NoUnsignedNonInvokerAuthEntriesError() { + assembled_transaction_classCallCheck(this, NoUnsignedNonInvokerAuthEntriesError); + return assembled_transaction_callSuper(this, NoUnsignedNonInvokerAuthEntriesError, arguments); + } + assembled_transaction_inherits(NoUnsignedNonInvokerAuthEntriesError, _Error5); + return assembled_transaction_createClass(NoUnsignedNonInvokerAuthEntriesError); + }(assembled_transaction_wrapNativeSuper(Error)), + NoSigner: function (_Error6) { + function NoSignerError() { + assembled_transaction_classCallCheck(this, NoSignerError); + return assembled_transaction_callSuper(this, NoSignerError, arguments); + } + assembled_transaction_inherits(NoSignerError, _Error6); + return assembled_transaction_createClass(NoSignerError); + }(assembled_transaction_wrapNativeSuper(Error)), + NotYetSimulated: function (_Error7) { + function NotYetSimulatedError() { + assembled_transaction_classCallCheck(this, NotYetSimulatedError); + return assembled_transaction_callSuper(this, NotYetSimulatedError, arguments); + } + assembled_transaction_inherits(NotYetSimulatedError, _Error7); + return assembled_transaction_createClass(NotYetSimulatedError); + }(assembled_transaction_wrapNativeSuper(Error)), + FakeAccount: function (_Error8) { + function FakeAccountError() { + assembled_transaction_classCallCheck(this, FakeAccountError); + return assembled_transaction_callSuper(this, FakeAccountError, arguments); + } + assembled_transaction_inherits(FakeAccountError, _Error8); + return assembled_transaction_createClass(FakeAccountError); + }(assembled_transaction_wrapNativeSuper(Error)), + SimulationFailed: function (_Error9) { + function SimulationFailedError() { + assembled_transaction_classCallCheck(this, SimulationFailedError); + return assembled_transaction_callSuper(this, SimulationFailedError, arguments); + } + assembled_transaction_inherits(SimulationFailedError, _Error9); + return assembled_transaction_createClass(SimulationFailedError); + }(assembled_transaction_wrapNativeSuper(Error)), + InternalWalletError: function (_Error10) { + function InternalWalletError() { + assembled_transaction_classCallCheck(this, InternalWalletError); + return assembled_transaction_callSuper(this, InternalWalletError, arguments); + } + assembled_transaction_inherits(InternalWalletError, _Error10); + return assembled_transaction_createClass(InternalWalletError); + }(assembled_transaction_wrapNativeSuper(Error)), + ExternalServiceError: function (_Error11) { + function ExternalServiceError() { + assembled_transaction_classCallCheck(this, ExternalServiceError); + return assembled_transaction_callSuper(this, ExternalServiceError, arguments); + } + assembled_transaction_inherits(ExternalServiceError, _Error11); + return assembled_transaction_createClass(ExternalServiceError); + }(assembled_transaction_wrapNativeSuper(Error)), + InvalidClientRequest: function (_Error12) { + function InvalidClientRequestError() { + assembled_transaction_classCallCheck(this, InvalidClientRequestError); + return assembled_transaction_callSuper(this, InvalidClientRequestError, arguments); + } + assembled_transaction_inherits(InvalidClientRequestError, _Error12); + return assembled_transaction_createClass(InvalidClientRequestError); + }(assembled_transaction_wrapNativeSuper(Error)), + UserRejected: function (_Error13) { + function UserRejectedError() { + assembled_transaction_classCallCheck(this, UserRejectedError); + return assembled_transaction_callSuper(this, UserRejectedError, arguments); + } + assembled_transaction_inherits(UserRejectedError, _Error13); + return assembled_transaction_createClass(UserRejectedError); + }(assembled_transaction_wrapNativeSuper(Error)) +}); +;// ./src/contract/basic_node_signer.ts +/* provided dependency */ var basic_node_signer_Buffer = __webpack_require__(8287)["Buffer"]; +function basic_node_signer_typeof(o) { "@babel/helpers - typeof"; return basic_node_signer_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, basic_node_signer_typeof(o); } +function basic_node_signer_regeneratorRuntime() { "use strict"; basic_node_signer_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == basic_node_signer_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(basic_node_signer_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function basic_node_signer_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function basic_node_signer_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { basic_node_signer_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { basic_node_signer_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + +var basicNodeSigner = function basicNodeSigner(keypair, networkPassphrase) { + return { + signTransaction: function () { + var _signTransaction = basic_node_signer_asyncToGenerator(basic_node_signer_regeneratorRuntime().mark(function _callee(xdr, opts) { + var t; + return basic_node_signer_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + t = lib.TransactionBuilder.fromXDR(xdr, (opts === null || opts === void 0 ? void 0 : opts.networkPassphrase) || networkPassphrase); + t.sign(keypair); + return _context.abrupt("return", { + signedTxXdr: t.toXDR(), + signerAddress: keypair.publicKey() + }); + case 3: + case "end": + return _context.stop(); + } + }, _callee); + })); + function signTransaction(_x, _x2) { + return _signTransaction.apply(this, arguments); + } + return signTransaction; + }(), + signAuthEntry: function () { + var _signAuthEntry = basic_node_signer_asyncToGenerator(basic_node_signer_regeneratorRuntime().mark(function _callee2(authEntry) { + var signedAuthEntry; + return basic_node_signer_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + signedAuthEntry = keypair.sign((0,lib.hash)(basic_node_signer_Buffer.from(authEntry, "base64"))).toString("base64"); + return _context2.abrupt("return", { + signedAuthEntry: signedAuthEntry, + signerAddress: keypair.publicKey() + }); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function signAuthEntry(_x3) { + return _signAuthEntry.apply(this, arguments); + } + return signAuthEntry; + }() + }; +}; +;// ./src/contract/spec.ts +/* provided dependency */ var spec_Buffer = __webpack_require__(8287)["Buffer"]; +function spec_ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function spec_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? spec_ownKeys(Object(t), !0).forEach(function (r) { spec_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : spec_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function spec_typeof(o) { "@babel/helpers - typeof"; return spec_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, spec_typeof(o); } +function spec_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function spec_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, spec_toPropertyKey(o.key), o); } } +function spec_createClass(e, r, t) { return r && spec_defineProperties(e.prototype, r), t && spec_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function spec_defineProperty(e, r, t) { return (r = spec_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function spec_toPropertyKey(t) { var i = spec_toPrimitive(t, "string"); return "symbol" == spec_typeof(i) ? i : i + ""; } +function spec_toPrimitive(t, r) { if ("object" != spec_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != spec_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function spec_slicedToArray(r, e) { return spec_arrayWithHoles(r) || spec_iterableToArrayLimit(r, e) || spec_unsupportedIterableToArray(r, e) || spec_nonIterableRest(); } +function spec_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function spec_unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return spec_arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? spec_arrayLikeToArray(r, a) : void 0; } } +function spec_arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function spec_iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function spec_arrayWithHoles(r) { if (Array.isArray(r)) return r; } + + +function enumToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + var title = aCase.name().toString(); + var desc = aCase.doc().toString(); + oneOf.push({ + description: desc, + title: title, + enum: [aCase.value()], + type: "number" + }); + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +function isNumeric(field) { + return /^\d+$/.test(field.name().toString()); +} +function readObj(args, input) { + var inputName = input.name().toString(); + var entry = Object.entries(args).find(function (_ref) { + var _ref2 = spec_slicedToArray(_ref, 1), + name = _ref2[0]; + return name === inputName; + }); + if (!entry) { + throw new Error("Missing field ".concat(inputName)); + } + return entry[1]; +} +function findCase(name) { + return function matches(entry) { + switch (entry.switch().value) { + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var tuple = entry.tupleCase(); + return tuple.name().toString() === name; + } + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var voidCase = entry.voidCase(); + return voidCase.name().toString() === name; + } + default: + return false; + } + }; +} +function stringToScVal(str, ty) { + switch (ty.value) { + case lib.xdr.ScSpecType.scSpecTypeString().value: + return lib.xdr.ScVal.scvString(str); + case lib.xdr.ScSpecType.scSpecTypeSymbol().value: + return lib.xdr.ScVal.scvSymbol(str); + case lib.xdr.ScSpecType.scSpecTypeAddress().value: + { + var addr = lib.Address.fromString(str); + return lib.xdr.ScVal.scvAddress(addr.toScAddress()); + } + case lib.xdr.ScSpecType.scSpecTypeU64().value: + return new lib.XdrLargeInt("u64", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeI64().value: + return new lib.XdrLargeInt("i64", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeU128().value: + return new lib.XdrLargeInt("u128", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeI128().value: + return new lib.XdrLargeInt("i128", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeU256().value: + return new lib.XdrLargeInt("u256", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeI256().value: + return new lib.XdrLargeInt("i256", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeBytes().value: + case lib.xdr.ScSpecType.scSpecTypeBytesN().value: + return lib.xdr.ScVal.scvBytes(spec_Buffer.from(str, "base64")); + default: + throw new TypeError("invalid type ".concat(ty.name, " specified for string value")); + } +} +var PRIMITIVE_DEFINITONS = { + U32: { + type: "integer", + minimum: 0, + maximum: 4294967295 + }, + I32: { + type: "integer", + minimum: -2147483648, + maximum: 2147483647 + }, + U64: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 20 + }, + I64: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 21 + }, + U128: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 39 + }, + I128: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 40 + }, + U256: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 78 + }, + I256: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 79 + }, + Address: { + type: "string", + format: "address", + description: "Address can be a public key or contract id" + }, + ScString: { + type: "string", + description: "ScString is a string" + }, + ScSymbol: { + type: "string", + description: "ScString is a string" + }, + DataUrl: { + type: "string", + pattern: "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$" + } +}; +function typeRef(typeDef) { + var t = typeDef.switch(); + var value = t.value; + var ref; + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVal().value: + { + ref = "Val"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeBool().value: + { + return { + type: "boolean" + }; + } + case lib.xdr.ScSpecType.scSpecTypeVoid().value: + { + return { + type: "null" + }; + } + case lib.xdr.ScSpecType.scSpecTypeError().value: + { + ref = "Error"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU32().value: + { + ref = "U32"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI32().value: + { + ref = "I32"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU64().value: + { + ref = "U64"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI64().value: + { + ref = "I64"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeTimepoint().value: + { + throw new Error("Timepoint type not supported"); + ref = "Timepoint"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeDuration().value: + { + throw new Error("Duration not supported"); + ref = "Duration"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU128().value: + { + ref = "U128"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI128().value: + { + ref = "I128"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU256().value: + { + ref = "U256"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI256().value: + { + ref = "I256"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeBytes().value: + { + ref = "DataUrl"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeString().value: + { + ref = "ScString"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeSymbol().value: + { + ref = "ScSymbol"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeAddress().value: + { + ref = "Address"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeOption().value: + { + var opt = typeDef.option(); + return typeRef(opt.valueType()); + } + case lib.xdr.ScSpecType.scSpecTypeResult().value: + { + break; + } + case lib.xdr.ScSpecType.scSpecTypeVec().value: + { + var arr = typeDef.vec(); + var reference = typeRef(arr.elementType()); + return { + type: "array", + items: reference + }; + } + case lib.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = typeDef.map(); + var items = [typeRef(map.keyType()), typeRef(map.valueType())]; + return { + type: "array", + items: { + type: "array", + items: items, + minItems: 2, + maxItems: 2 + } + }; + } + case lib.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tuple = typeDef.tuple(); + var minItems = tuple.valueTypes().length; + var maxItems = minItems; + var _items = tuple.valueTypes().map(typeRef); + return { + type: "array", + items: _items, + minItems: minItems, + maxItems: maxItems + }; + } + case lib.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var _arr = typeDef.bytesN(); + return { + $ref: "#/definitions/DataUrl", + maxLength: _arr.n() + }; + } + case lib.xdr.ScSpecType.scSpecTypeUdt().value: + { + var udt = typeDef.udt(); + ref = udt.name().toString(); + break; + } + } + return { + $ref: "#/definitions/".concat(ref) + }; +} +function isRequired(typeDef) { + return typeDef.switch().value !== lib.xdr.ScSpecType.scSpecTypeOption().value; +} +function argsAndRequired(input) { + var properties = {}; + var required = []; + input.forEach(function (arg) { + var aType = arg.type(); + var name = arg.name().toString(); + properties[name] = typeRef(aType); + if (isRequired(aType)) { + required.push(name); + } + }); + var res = { + properties: properties + }; + if (required.length > 0) { + res.required = required; + } + return res; +} +function structToJsonSchema(udt) { + var fields = udt.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + var items = fields.map(function (_, i) { + return typeRef(fields[i].type()); + }); + return { + type: "array", + items: items, + minItems: fields.length, + maxItems: fields.length + }; + } + var description = udt.doc().toString(); + var _argsAndRequired = argsAndRequired(fields), + properties = _argsAndRequired.properties, + required = _argsAndRequired.required; + properties.additionalProperties = false; + return { + description: description, + properties: properties, + required: required, + type: "object" + }; +} +function functionToJsonSchema(func) { + var _argsAndRequired2 = argsAndRequired(func.inputs()), + properties = _argsAndRequired2.properties, + required = _argsAndRequired2.required; + var args = { + additionalProperties: false, + properties: properties, + type: "object" + }; + if ((required === null || required === void 0 ? void 0 : required.length) > 0) { + args.required = required; + } + var input = { + properties: { + args: args + } + }; + var outputs = func.outputs(); + var output = outputs.length > 0 ? typeRef(outputs[0]) : typeRef(lib.xdr.ScSpecTypeDef.scSpecTypeVoid()); + var description = func.doc().toString(); + if (description.length > 0) { + input.description = description; + } + input.additionalProperties = false; + output.additionalProperties = false; + return { + input: input, + output: output + }; +} +function unionToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + switch (aCase.switch().value) { + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var c = aCase.voidCase(); + var title = c.name().toString(); + oneOf.push({ + type: "object", + title: title, + properties: { + tag: title + }, + additionalProperties: false, + required: ["tag"] + }); + break; + } + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var _c = aCase.tupleCase(); + var _title = _c.name().toString(); + oneOf.push({ + type: "object", + title: _title, + properties: { + tag: _title, + values: { + type: "array", + items: _c.type().map(typeRef) + } + }, + required: ["tag", "values"], + additionalProperties: false + }); + } + } + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +var Spec = function () { + function Spec(entries) { + spec_classCallCheck(this, Spec); + spec_defineProperty(this, "entries", []); + if (entries.length === 0) { + throw new Error("Contract spec must have at least one entry"); + } + var entry = entries[0]; + if (typeof entry === "string") { + this.entries = entries.map(function (s) { + return lib.xdr.ScSpecEntry.fromXDR(s, "base64"); + }); + } else { + this.entries = entries; + } + } + return spec_createClass(Spec, [{ + key: "funcs", + value: function funcs() { + return this.entries.filter(function (entry) { + return entry.switch().value === lib.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value; + }).map(function (entry) { + return entry.functionV0(); + }); + } + }, { + key: "getFunc", + value: function getFunc(name) { + var entry = this.findEntry(name); + if (entry.switch().value !== lib.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value) { + throw new Error("".concat(name, " is not a function")); + } + return entry.functionV0(); + } + }, { + key: "funcArgsToScVals", + value: function funcArgsToScVals(name, args) { + var _this = this; + var fn = this.getFunc(name); + return fn.inputs().map(function (input) { + return _this.nativeToScVal(readObj(args, input), input.type()); + }); + } + }, { + key: "funcResToNative", + value: function funcResToNative(name, val_or_base64) { + var val = typeof val_or_base64 === "string" ? lib.xdr.ScVal.fromXDR(val_or_base64, "base64") : val_or_base64; + var func = this.getFunc(name); + var outputs = func.outputs(); + if (outputs.length === 0) { + var type = val.switch(); + if (type.value !== lib.xdr.ScValType.scvVoid().value) { + throw new Error("Expected void, got ".concat(type.name)); + } + return null; + } + if (outputs.length > 1) { + throw new Error("Multiple outputs not supported"); + } + var output = outputs[0]; + if (output.switch().value === lib.xdr.ScSpecType.scSpecTypeResult().value) { + return new Ok(this.scValToNative(val, output.result().okType())); + } + return this.scValToNative(val, output); + } + }, { + key: "findEntry", + value: function findEntry(name) { + var entry = this.entries.find(function (e) { + return e.value().name().toString() === name; + }); + if (!entry) { + throw new Error("no such entry: ".concat(name)); + } + return entry; + } + }, { + key: "nativeToScVal", + value: function nativeToScVal(val, ty) { + var _this2 = this; + var t = ty.switch(); + var value = t.value; + if (t.value === lib.xdr.ScSpecType.scSpecTypeUdt().value) { + var udt = ty.udt(); + return this.nativeToUdt(val, udt.name().toString()); + } + if (value === lib.xdr.ScSpecType.scSpecTypeOption().value) { + var opt = ty.option(); + if (val === undefined) { + return lib.xdr.ScVal.scvVoid(); + } + return this.nativeToScVal(val, opt.valueType()); + } + switch (spec_typeof(val)) { + case "object": + { + var _val$constructor$name, _val$constructor; + if (val === null) { + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVoid().value: + return lib.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was null")); + } + } + if (val instanceof lib.xdr.ScVal) { + return val; + } + if (val instanceof lib.Address) { + if (ty.switch().value !== lib.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.toScVal(); + } + if (val instanceof lib.Contract) { + if (ty.switch().value !== lib.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.address().toScVal(); + } + if (val instanceof Uint8Array || spec_Buffer.isBuffer(val)) { + var copy = Uint8Array.from(val); + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var bytesN = ty.bytesN(); + if (copy.length !== bytesN.n()) { + throw new TypeError("expected ".concat(bytesN.n(), " bytes, but got ").concat(copy.length)); + } + return lib.xdr.ScVal.scvBytes(copy); + } + case lib.xdr.ScSpecType.scSpecTypeBytes().value: + return lib.xdr.ScVal.scvBytes(copy); + default: + throw new TypeError("invalid type (".concat(ty, ") specified for Bytes and BytesN")); + } + } + if (Array.isArray(val)) { + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVec().value: + { + var vec = ty.vec(); + var elementType = vec.elementType(); + return lib.xdr.ScVal.scvVec(val.map(function (v) { + return _this2.nativeToScVal(v, elementType); + })); + } + case lib.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tup = ty.tuple(); + var valTypes = tup.valueTypes(); + if (val.length !== valTypes.length) { + throw new TypeError("Tuple expects ".concat(valTypes.length, " values, but ").concat(val.length, " were provided")); + } + return lib.xdr.ScVal.scvVec(val.map(function (v, i) { + return _this2.nativeToScVal(v, valTypes[i]); + })); + } + case lib.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = ty.map(); + var keyType = map.keyType(); + var valueType = map.valueType(); + return lib.xdr.ScVal.scvMap(val.map(function (entry) { + var key = _this2.nativeToScVal(entry[0], keyType); + var mapVal = _this2.nativeToScVal(entry[1], valueType); + return new lib.xdr.ScMapEntry({ + key: key, + val: mapVal + }); + })); + } + default: + throw new TypeError("Type ".concat(ty, " was not vec, but value was Array")); + } + } + if (val.constructor === Map) { + if (value !== lib.xdr.ScSpecType.scSpecTypeMap().value) { + throw new TypeError("Type ".concat(ty, " was not map, but value was Map")); + } + var scMap = ty.map(); + var _map = val; + var entries = []; + var values = _map.entries(); + var res = values.next(); + while (!res.done) { + var _res$value = spec_slicedToArray(res.value, 2), + k = _res$value[0], + v = _res$value[1]; + var key = this.nativeToScVal(k, scMap.keyType()); + var mapval = this.nativeToScVal(v, scMap.valueType()); + entries.push(new lib.xdr.ScMapEntry({ + key: key, + val: mapval + })); + res = values.next(); + } + return lib.xdr.ScVal.scvMap(entries); + } + if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : "") !== "Object") { + var _val$constructor2; + throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")")); + } + throw new TypeError("Received object ".concat(val, " did not match the provided type ").concat(ty)); + } + case "number": + case "bigint": + { + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeU32().value: + return lib.xdr.ScVal.scvU32(val); + case lib.xdr.ScSpecType.scSpecTypeI32().value: + return lib.xdr.ScVal.scvI32(val); + case lib.xdr.ScSpecType.scSpecTypeU64().value: + case lib.xdr.ScSpecType.scSpecTypeI64().value: + case lib.xdr.ScSpecType.scSpecTypeU128().value: + case lib.xdr.ScSpecType.scSpecTypeI128().value: + case lib.xdr.ScSpecType.scSpecTypeU256().value: + case lib.xdr.ScSpecType.scSpecTypeI256().value: + { + var intType = t.name.substring(10).toLowerCase(); + return new lib.XdrLargeInt(intType, val).toScVal(); + } + default: + throw new TypeError("invalid type (".concat(ty, ") specified for integer")); + } + } + case "string": + return stringToScVal(val, t); + case "boolean": + { + if (value !== lib.xdr.ScSpecType.scSpecTypeBool().value) { + throw TypeError("Type ".concat(ty, " was not bool, but value was bool")); + } + return lib.xdr.ScVal.scvBool(val); + } + case "undefined": + { + if (!ty) { + return lib.xdr.ScVal.scvVoid(); + } + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVoid().value: + case lib.xdr.ScSpecType.scSpecTypeOption().value: + return lib.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was undefined")); + } + } + case "function": + return this.nativeToScVal(val(), ty); + default: + throw new TypeError("failed to convert typeof ".concat(spec_typeof(val), " (").concat(val, ")")); + } + } + }, { + key: "nativeToUdt", + value: function nativeToUdt(val, name) { + var entry = this.findEntry(name); + switch (entry.switch()) { + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + if (typeof val !== "number") { + throw new TypeError("expected number for enum ".concat(name, ", but got ").concat(spec_typeof(val))); + } + return this.nativeToEnum(val, entry.udtEnumV0()); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.nativeToStruct(val, entry.udtStructV0()); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.nativeToUnion(val, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(name)); + } + } + }, { + key: "nativeToUnion", + value: function nativeToUnion(val, union_) { + var _this3 = this; + var entryName = val.tag; + var caseFound = union_.cases().find(function (entry) { + var caseN = entry.value().name().toString(); + return caseN === entryName; + }); + if (!caseFound) { + throw new TypeError("no such enum entry: ".concat(entryName, " in ").concat(union_)); + } + var key = lib.xdr.ScVal.scvSymbol(entryName); + switch (caseFound.switch()) { + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0(): + { + return lib.xdr.ScVal.scvVec([key]); + } + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0(): + { + var types = caseFound.tupleCase().type(); + if (Array.isArray(val.values)) { + if (val.values.length !== types.length) { + throw new TypeError("union ".concat(union_, " expects ").concat(types.length, " values, but got ").concat(val.values.length)); + } + var scvals = val.values.map(function (v, i) { + return _this3.nativeToScVal(v, types[i]); + }); + scvals.unshift(key); + return lib.xdr.ScVal.scvVec(scvals); + } + throw new Error("failed to parse union case ".concat(caseFound, " with ").concat(val)); + } + default: + throw new Error("failed to parse union ".concat(union_, " with ").concat(val)); + } + } + }, { + key: "nativeToStruct", + value: function nativeToStruct(val, struct) { + var _this4 = this; + var fields = struct.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + return lib.xdr.ScVal.scvVec(fields.map(function (_, i) { + return _this4.nativeToScVal(val[i], fields[i].type()); + })); + } + return lib.xdr.ScVal.scvMap(fields.map(function (field) { + var name = field.name().toString(); + return new lib.xdr.ScMapEntry({ + key: _this4.nativeToScVal(name, lib.xdr.ScSpecTypeDef.scSpecTypeSymbol()), + val: _this4.nativeToScVal(val[name], field.type()) + }); + })); + } + }, { + key: "nativeToEnum", + value: function nativeToEnum(val, enum_) { + if (enum_.cases().some(function (entry) { + return entry.value() === val; + })) { + return lib.xdr.ScVal.scvU32(val); + } + throw new TypeError("no such enum entry: ".concat(val, " in ").concat(enum_)); + } + }, { + key: "scValStrToNative", + value: function scValStrToNative(scv, typeDef) { + return this.scValToNative(lib.xdr.ScVal.fromXDR(scv, "base64"), typeDef); + } + }, { + key: "scValToNative", + value: function scValToNative(scv, typeDef) { + var _this5 = this; + var t = typeDef.switch(); + var value = t.value; + if (value === lib.xdr.ScSpecType.scSpecTypeUdt().value) { + return this.scValUdtToNative(scv, typeDef.udt()); + } + switch (scv.switch().value) { + case lib.xdr.ScValType.scvVoid().value: + return undefined; + case lib.xdr.ScValType.scvU64().value: + case lib.xdr.ScValType.scvI64().value: + case lib.xdr.ScValType.scvU128().value: + case lib.xdr.ScValType.scvI128().value: + case lib.xdr.ScValType.scvU256().value: + case lib.xdr.ScValType.scvI256().value: + return (0,lib.scValToBigInt)(scv); + case lib.xdr.ScValType.scvVec().value: + { + if (value === lib.xdr.ScSpecType.scSpecTypeVec().value) { + var _scv$vec; + var vec = typeDef.vec(); + return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(function (elm) { + return _this5.scValToNative(elm, vec.elementType()); + }); + } + if (value === lib.xdr.ScSpecType.scSpecTypeTuple().value) { + var _scv$vec2; + var tuple = typeDef.tuple(); + var valTypes = tuple.valueTypes(); + return ((_scv$vec2 = scv.vec()) !== null && _scv$vec2 !== void 0 ? _scv$vec2 : []).map(function (elm, i) { + return _this5.scValToNative(elm, valTypes[i]); + }); + } + throw new TypeError("Type ".concat(typeDef, " was not vec, but ").concat(scv, " is")); + } + case lib.xdr.ScValType.scvAddress().value: + return lib.Address.fromScVal(scv).toString(); + case lib.xdr.ScValType.scvMap().value: + { + var _scv$map; + var map = (_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []; + if (value === lib.xdr.ScSpecType.scSpecTypeMap().value) { + var typed = typeDef.map(); + var keyType = typed.keyType(); + var valueType = typed.valueType(); + var res = map.map(function (entry) { + return [_this5.scValToNative(entry.key(), keyType), _this5.scValToNative(entry.val(), valueType)]; + }); + return res; + } + throw new TypeError("ScSpecType ".concat(t.name, " was not map, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + case lib.xdr.ScValType.scvBool().value: + case lib.xdr.ScValType.scvU32().value: + case lib.xdr.ScValType.scvI32().value: + case lib.xdr.ScValType.scvBytes().value: + return scv.value(); + case lib.xdr.ScValType.scvString().value: + case lib.xdr.ScValType.scvSymbol().value: + { + var _scv$value; + if (value !== lib.xdr.ScSpecType.scSpecTypeString().value && value !== lib.xdr.ScSpecType.scSpecTypeSymbol().value) { + throw new Error("ScSpecType ".concat(t.name, " was not string or symbol, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + return (_scv$value = scv.value()) === null || _scv$value === void 0 ? void 0 : _scv$value.toString(); + } + case lib.xdr.ScValType.scvTimepoint().value: + case lib.xdr.ScValType.scvDuration().value: + return (0,lib.scValToBigInt)(lib.xdr.ScVal.scvU64(scv.u64())); + default: + throw new TypeError("failed to convert ".concat(JSON.stringify(scv, null, 2), " to native type from type ").concat(t.name)); + } + } + }, { + key: "scValUdtToNative", + value: function scValUdtToNative(scv, udt) { + var entry = this.findEntry(udt.name().toString()); + switch (entry.switch()) { + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + return this.enumToNative(scv); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.structToNative(scv, entry.udtStructV0()); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.unionToNative(scv, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(udt.name().toString(), ": ").concat(entry)); + } + } + }, { + key: "unionToNative", + value: function unionToNative(val, udt) { + var _this6 = this; + var vec = val.vec(); + if (!vec) { + throw new Error("".concat(JSON.stringify(val, null, 2), " is not a vec")); + } + if (vec.length === 0 && udt.cases.length !== 0) { + throw new Error("".concat(val, " has length 0, but the there are at least one case in the union")); + } + var name = vec[0].sym().toString(); + if (vec[0].switch().value !== lib.xdr.ScValType.scvSymbol().value) { + throw new Error("{vec[0]} is not a symbol"); + } + var entry = udt.cases().find(findCase(name)); + if (!entry) { + throw new Error("failed to find entry ".concat(name, " in union {udt.name().toString()}")); + } + var res = { + tag: name + }; + if (entry.switch().value === lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value) { + var tuple = entry.tupleCase(); + var ty = tuple.type(); + var values = ty.map(function (e, i) { + return _this6.scValToNative(vec[i + 1], e); + }); + res.values = values; + } + return res; + } + }, { + key: "structToNative", + value: function structToNative(val, udt) { + var _this7 = this, + _val$map; + var res = {}; + var fields = udt.fields(); + if (fields.some(isNumeric)) { + var _val$vec; + var r = (_val$vec = val.vec()) === null || _val$vec === void 0 ? void 0 : _val$vec.map(function (entry, i) { + return _this7.scValToNative(entry, fields[i].type()); + }); + return r; + } + (_val$map = val.map()) === null || _val$map === void 0 || _val$map.forEach(function (entry, i) { + var field = fields[i]; + res[field.name().toString()] = _this7.scValToNative(entry.val(), field.type()); + }); + return res; + } + }, { + key: "enumToNative", + value: function enumToNative(scv) { + if (scv.switch().value !== lib.xdr.ScValType.scvU32().value) { + throw new Error("Enum must have a u32 value"); + } + var num = scv.u32(); + return num; + } + }, { + key: "errorCases", + value: function errorCases() { + return this.entries.filter(function (entry) { + return entry.switch().value === lib.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value; + }).flatMap(function (entry) { + return entry.value().cases(); + }); + } + }, { + key: "jsonSchema", + value: function jsonSchema(funcName) { + var definitions = {}; + this.entries.forEach(function (entry) { + switch (entry.switch().value) { + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0().value: + { + var udt = entry.udtEnumV0(); + definitions[udt.name().toString()] = enumToJsonSchema(udt); + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0().value: + { + var _udt = entry.udtStructV0(); + definitions[_udt.name().toString()] = structToJsonSchema(_udt); + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0().value: + { + var _udt2 = entry.udtUnionV0(); + definitions[_udt2.name().toString()] = unionToJsonSchema(_udt2); + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value: + { + var fn = entry.functionV0(); + var fnName = fn.name().toString(); + var _functionToJsonSchema = functionToJsonSchema(fn), + input = _functionToJsonSchema.input; + definitions[fnName] = input; + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value: + {} + } + }); + var res = { + $schema: "http://json-schema.org/draft-07/schema#", + definitions: spec_objectSpread(spec_objectSpread({}, PRIMITIVE_DEFINITONS), definitions) + }; + if (funcName) { + res.$ref = "#/definitions/".concat(funcName); + } + return res; + } + }]); +}(); +;// ./src/contract/client.ts +/* provided dependency */ var client_Buffer = __webpack_require__(8287)["Buffer"]; +function client_typeof(o) { "@babel/helpers - typeof"; return client_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, client_typeof(o); } +var _excluded = ["method"], + _excluded2 = ["wasmHash", "salt", "format", "fee", "timeoutInSeconds", "simulate"]; +function client_regeneratorRuntime() { "use strict"; client_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == client_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(client_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function client_ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function client_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? client_ownKeys(Object(t), !0).forEach(function (r) { client_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : client_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } +function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; } +function client_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function client_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, client_toPropertyKey(o.key), o); } } +function client_createClass(e, r, t) { return r && client_defineProperties(e.prototype, r), t && client_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function client_defineProperty(e, r, t) { return (r = client_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function client_toPropertyKey(t) { var i = client_toPrimitive(t, "string"); return "symbol" == client_typeof(i) ? i : i + ""; } +function client_toPrimitive(t, r) { if ("object" != client_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != client_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function client_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function client_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { client_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { client_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + + + + + +var CONSTRUCTOR_FUNC = "__constructor"; +function specFromWasm(_x) { + return _specFromWasm.apply(this, arguments); +} +function _specFromWasm() { + _specFromWasm = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee5(wasm) { + var wasmModule, xdrSections, bufferSection, specEntryArray, spec; + return client_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return WebAssembly.compile(wasm); + case 2: + wasmModule = _context5.sent; + xdrSections = WebAssembly.Module.customSections(wasmModule, "contractspecv0"); + if (!(xdrSections.length === 0)) { + _context5.next = 6; + break; + } + throw new Error("Could not obtain contract spec from wasm"); + case 6: + bufferSection = client_Buffer.from(xdrSections[0]); + specEntryArray = processSpecEntryStream(bufferSection); + spec = new Spec(specEntryArray); + return _context5.abrupt("return", spec); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _specFromWasm.apply(this, arguments); +} +function specFromWasmHash(_x2, _x3) { + return _specFromWasmHash.apply(this, arguments); +} +function _specFromWasmHash() { + _specFromWasmHash = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee6(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args6 = arguments; + return client_regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + format = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context6.next = 3; + break; + } + throw new TypeError("options must contain rpcUrl"); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new rpc.Server(rpcUrl, serverOpts); + _context6.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context6.sent; + return _context6.abrupt("return", specFromWasm(wasm)); + case 10: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _specFromWasmHash.apply(this, arguments); +} +var Client = function () { + function Client(spec, options) { + var _this = this; + client_classCallCheck(this, Client); + client_defineProperty(this, "txFromJSON", function (json) { + var _JSON$parse = JSON.parse(json), + method = _JSON$parse.method, + tx = _objectWithoutProperties(_JSON$parse, _excluded); + return AssembledTransaction.fromJSON(client_objectSpread(client_objectSpread({}, _this.options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return _this.spec.funcResToNative(method, result); + } + }), tx); + }); + client_defineProperty(this, "txFromXDR", function (xdrBase64) { + return AssembledTransaction.fromXDR(_this.options, xdrBase64, _this.spec); + }); + this.spec = spec; + this.options = options; + this.spec.funcs().forEach(function (xdrFn) { + var method = xdrFn.name().toString(); + if (method === CONSTRUCTOR_FUNC) { + return; + } + var assembleTransaction = function assembleTransaction(args, methodOptions) { + return AssembledTransaction.build(client_objectSpread(client_objectSpread(client_objectSpread({ + method: method, + args: args && spec.funcArgsToScVals(method, args) + }, options), methodOptions), {}, { + errorTypes: spec.errorCases().reduce(function (acc, curr) { + return client_objectSpread(client_objectSpread({}, acc), {}, client_defineProperty({}, curr.value(), { + message: curr.doc().toString() + })); + }, {}), + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + }; + _this[method] = spec.getFunc(method).inputs().length === 0 ? function (opts) { + return assembleTransaction(undefined, opts); + } : assembleTransaction; + }); + } + return client_createClass(Client, null, [{ + key: "deploy", + value: function () { + var _deploy = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee(args, options) { + var wasmHash, salt, format, fee, timeoutInSeconds, simulate, clientOptions, spec, operation; + return client_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + wasmHash = options.wasmHash, salt = options.salt, format = options.format, fee = options.fee, timeoutInSeconds = options.timeoutInSeconds, simulate = options.simulate, clientOptions = _objectWithoutProperties(options, _excluded2); + _context.next = 3; + return specFromWasmHash(wasmHash, clientOptions, format); + case 3: + spec = _context.sent; + operation = lib.Operation.createCustomContract({ + address: new lib.Address(options.publicKey), + wasmHash: typeof wasmHash === "string" ? client_Buffer.from(wasmHash, format !== null && format !== void 0 ? format : "hex") : wasmHash, + salt: salt, + constructorArgs: args ? spec.funcArgsToScVals(CONSTRUCTOR_FUNC, args) : [] + }); + return _context.abrupt("return", AssembledTransaction.buildWithOp(operation, client_objectSpread(client_objectSpread({ + fee: fee, + timeoutInSeconds: timeoutInSeconds, + simulate: simulate + }, clientOptions), {}, { + contractId: "ignored", + method: CONSTRUCTOR_FUNC, + parseResultXdr: function parseResultXdr(result) { + return new Client(spec, client_objectSpread(client_objectSpread({}, clientOptions), {}, { + contractId: lib.Address.fromScVal(result).toString() + })); + } + }))); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + function deploy(_x4, _x5) { + return _deploy.apply(this, arguments); + } + return deploy; + }() + }, { + key: "fromWasmHash", + value: (function () { + var _fromWasmHash = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee2(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args2 = arguments; + return client_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + format = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context2.next = 3; + break; + } + throw new TypeError('options must contain rpcUrl'); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new rpc.Server(rpcUrl, serverOpts); + _context2.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context2.sent; + return _context2.abrupt("return", Client.fromWasm(wasm, options)); + case 10: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function fromWasmHash(_x6, _x7) { + return _fromWasmHash.apply(this, arguments); + } + return fromWasmHash; + }()) + }, { + key: "fromWasm", + value: (function () { + var _fromWasm = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee3(wasm, options) { + var spec; + return client_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return specFromWasm(wasm); + case 2: + spec = _context3.sent; + return _context3.abrupt("return", new Client(spec, options)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + function fromWasm(_x8, _x9) { + return _fromWasm.apply(this, arguments); + } + return fromWasm; + }()) + }, { + key: "from", + value: (function () { + var _from = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee4(options) { + var rpcUrl, contractId, allowHttp, serverOpts, server, wasm; + return client_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(!options || !options.rpcUrl || !options.contractId)) { + _context4.next = 2; + break; + } + throw new TypeError('options must contain rpcUrl and contractId'); + case 2: + rpcUrl = options.rpcUrl, contractId = options.contractId, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new rpc.Server(rpcUrl, serverOpts); + _context4.next = 7; + return server.getContractWasmByContractId(contractId); + case 7: + wasm = _context4.sent; + return _context4.abrupt("return", Client.fromWasm(wasm, options)); + case 9: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function from(_x10) { + return _from.apply(this, arguments); + } + return from; + }()) + }]); +}(); +;// ./src/contract/index.ts + + + + + + + + +/***/ }), + +/***/ 5976: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Cu: () => (/* reexport */ AccountRequiresMemoError), + v7: () => (/* reexport */ BadRequestError), + nS: () => (/* reexport */ BadResponseError), + Dr: () => (/* reexport */ NetworkError), + m_: () => (/* reexport */ NotFoundError) +}); + +;// ./src/errors/network.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var NetworkError = function (_Error) { + function NetworkError(message, response) { + var _this; + _classCallCheck(this, NetworkError); + var trueProto = (this instanceof NetworkError ? this.constructor : void 0).prototype; + _this = _callSuper(this, NetworkError, [message]); + _this.__proto__ = trueProto; + _this.constructor = NetworkError; + _this.response = response; + return _this; + } + _inherits(NetworkError, _Error); + return _createClass(NetworkError, [{ + key: "getResponse", + value: function getResponse() { + return this.response; + } + }]); +}(_wrapNativeSuper(Error)); +;// ./src/errors/not_found.ts +function not_found_typeof(o) { "@babel/helpers - typeof"; return not_found_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, not_found_typeof(o); } +function not_found_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, not_found_toPropertyKey(o.key), o); } } +function not_found_createClass(e, r, t) { return r && not_found_defineProperties(e.prototype, r), t && not_found_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function not_found_toPropertyKey(t) { var i = not_found_toPrimitive(t, "string"); return "symbol" == not_found_typeof(i) ? i : i + ""; } +function not_found_toPrimitive(t, r) { if ("object" != not_found_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != not_found_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function not_found_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function not_found_callSuper(t, o, e) { return o = not_found_getPrototypeOf(o), not_found_possibleConstructorReturn(t, not_found_isNativeReflectConstruct() ? Reflect.construct(o, e || [], not_found_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function not_found_possibleConstructorReturn(t, e) { if (e && ("object" == not_found_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return not_found_assertThisInitialized(t); } +function not_found_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function not_found_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (not_found_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function not_found_getPrototypeOf(t) { return not_found_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, not_found_getPrototypeOf(t); } +function not_found_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && not_found_setPrototypeOf(t, e); } +function not_found_setPrototypeOf(t, e) { return not_found_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, not_found_setPrototypeOf(t, e); } + +var NotFoundError = function (_NetworkError) { + function NotFoundError(message, response) { + var _this; + not_found_classCallCheck(this, NotFoundError); + var trueProto = (this instanceof NotFoundError ? this.constructor : void 0).prototype; + _this = not_found_callSuper(this, NotFoundError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = NotFoundError; + _this.name = "NotFoundError"; + return _this; + } + not_found_inherits(NotFoundError, _NetworkError); + return not_found_createClass(NotFoundError); +}(NetworkError); +;// ./src/errors/bad_request.ts +function bad_request_typeof(o) { "@babel/helpers - typeof"; return bad_request_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, bad_request_typeof(o); } +function bad_request_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, bad_request_toPropertyKey(o.key), o); } } +function bad_request_createClass(e, r, t) { return r && bad_request_defineProperties(e.prototype, r), t && bad_request_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function bad_request_toPropertyKey(t) { var i = bad_request_toPrimitive(t, "string"); return "symbol" == bad_request_typeof(i) ? i : i + ""; } +function bad_request_toPrimitive(t, r) { if ("object" != bad_request_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != bad_request_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function bad_request_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function bad_request_callSuper(t, o, e) { return o = bad_request_getPrototypeOf(o), bad_request_possibleConstructorReturn(t, bad_request_isNativeReflectConstruct() ? Reflect.construct(o, e || [], bad_request_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function bad_request_possibleConstructorReturn(t, e) { if (e && ("object" == bad_request_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return bad_request_assertThisInitialized(t); } +function bad_request_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function bad_request_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (bad_request_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function bad_request_getPrototypeOf(t) { return bad_request_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, bad_request_getPrototypeOf(t); } +function bad_request_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && bad_request_setPrototypeOf(t, e); } +function bad_request_setPrototypeOf(t, e) { return bad_request_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, bad_request_setPrototypeOf(t, e); } + +var BadRequestError = function (_NetworkError) { + function BadRequestError(message, response) { + var _this; + bad_request_classCallCheck(this, BadRequestError); + var trueProto = (this instanceof BadRequestError ? this.constructor : void 0).prototype; + _this = bad_request_callSuper(this, BadRequestError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadRequestError; + _this.name = "BadRequestError"; + return _this; + } + bad_request_inherits(BadRequestError, _NetworkError); + return bad_request_createClass(BadRequestError); +}(NetworkError); +;// ./src/errors/bad_response.ts +function bad_response_typeof(o) { "@babel/helpers - typeof"; return bad_response_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, bad_response_typeof(o); } +function bad_response_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, bad_response_toPropertyKey(o.key), o); } } +function bad_response_createClass(e, r, t) { return r && bad_response_defineProperties(e.prototype, r), t && bad_response_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function bad_response_toPropertyKey(t) { var i = bad_response_toPrimitive(t, "string"); return "symbol" == bad_response_typeof(i) ? i : i + ""; } +function bad_response_toPrimitive(t, r) { if ("object" != bad_response_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != bad_response_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function bad_response_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function bad_response_callSuper(t, o, e) { return o = bad_response_getPrototypeOf(o), bad_response_possibleConstructorReturn(t, bad_response_isNativeReflectConstruct() ? Reflect.construct(o, e || [], bad_response_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function bad_response_possibleConstructorReturn(t, e) { if (e && ("object" == bad_response_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return bad_response_assertThisInitialized(t); } +function bad_response_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function bad_response_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (bad_response_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function bad_response_getPrototypeOf(t) { return bad_response_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, bad_response_getPrototypeOf(t); } +function bad_response_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && bad_response_setPrototypeOf(t, e); } +function bad_response_setPrototypeOf(t, e) { return bad_response_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, bad_response_setPrototypeOf(t, e); } + +var BadResponseError = function (_NetworkError) { + function BadResponseError(message, response) { + var _this; + bad_response_classCallCheck(this, BadResponseError); + var trueProto = (this instanceof BadResponseError ? this.constructor : void 0).prototype; + _this = bad_response_callSuper(this, BadResponseError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadResponseError; + _this.name = "BadResponseError"; + return _this; + } + bad_response_inherits(BadResponseError, _NetworkError); + return bad_response_createClass(BadResponseError); +}(NetworkError); +;// ./src/errors/account_requires_memo.ts +function account_requires_memo_typeof(o) { "@babel/helpers - typeof"; return account_requires_memo_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, account_requires_memo_typeof(o); } +function account_requires_memo_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, account_requires_memo_toPropertyKey(o.key), o); } } +function account_requires_memo_createClass(e, r, t) { return r && account_requires_memo_defineProperties(e.prototype, r), t && account_requires_memo_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function account_requires_memo_toPropertyKey(t) { var i = account_requires_memo_toPrimitive(t, "string"); return "symbol" == account_requires_memo_typeof(i) ? i : i + ""; } +function account_requires_memo_toPrimitive(t, r) { if ("object" != account_requires_memo_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != account_requires_memo_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function account_requires_memo_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function account_requires_memo_callSuper(t, o, e) { return o = account_requires_memo_getPrototypeOf(o), account_requires_memo_possibleConstructorReturn(t, account_requires_memo_isNativeReflectConstruct() ? Reflect.construct(o, e || [], account_requires_memo_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function account_requires_memo_possibleConstructorReturn(t, e) { if (e && ("object" == account_requires_memo_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return account_requires_memo_assertThisInitialized(t); } +function account_requires_memo_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function account_requires_memo_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && account_requires_memo_setPrototypeOf(t, e); } +function account_requires_memo_wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return account_requires_memo_wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !account_requires_memo_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return account_requires_memo_construct(t, arguments, account_requires_memo_getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), account_requires_memo_setPrototypeOf(Wrapper, t); }, account_requires_memo_wrapNativeSuper(t); } +function account_requires_memo_construct(t, e, r) { if (account_requires_memo_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && account_requires_memo_setPrototypeOf(p, r.prototype), p; } +function account_requires_memo_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (account_requires_memo_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function account_requires_memo_isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function account_requires_memo_setPrototypeOf(t, e) { return account_requires_memo_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, account_requires_memo_setPrototypeOf(t, e); } +function account_requires_memo_getPrototypeOf(t) { return account_requires_memo_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, account_requires_memo_getPrototypeOf(t); } +var AccountRequiresMemoError = function (_Error) { + function AccountRequiresMemoError(message, accountId, operationIndex) { + var _this; + account_requires_memo_classCallCheck(this, AccountRequiresMemoError); + var trueProto = (this instanceof AccountRequiresMemoError ? this.constructor : void 0).prototype; + _this = account_requires_memo_callSuper(this, AccountRequiresMemoError, [message]); + _this.__proto__ = trueProto; + _this.constructor = AccountRequiresMemoError; + _this.name = "AccountRequiresMemoError"; + _this.accountId = accountId; + _this.operationIndex = operationIndex; + return _this; + } + account_requires_memo_inherits(AccountRequiresMemoError, _Error); + return account_requires_memo_createClass(AccountRequiresMemoError); +}(account_requires_memo_wrapNativeSuper(Error)); +;// ./src/errors/index.ts + + + + + + +/***/ }), + +/***/ 7600: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Api: () => (/* reexport */ Api), + FEDERATION_RESPONSE_MAX_SIZE: () => (/* reexport */ FEDERATION_RESPONSE_MAX_SIZE), + Server: () => (/* reexport */ FederationServer) +}); + +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js +var URI = __webpack_require__(4193); +var URI_default = /*#__PURE__*/__webpack_require__.n(URI); +// EXTERNAL MODULE: ./src/config.ts +var config = __webpack_require__(8732); +// EXTERNAL MODULE: ./src/errors/index.ts + 5 modules +var errors = __webpack_require__(5976); +// EXTERNAL MODULE: ./src/stellartoml/index.ts +var stellartoml = __webpack_require__(3898); +// EXTERNAL MODULE: ./src/http-client/index.ts +var http_client = __webpack_require__(6371); +;// ./src/federation/server.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + +var FEDERATION_RESPONSE_MAX_SIZE = 100 * 1024; +var FederationServer = function () { + function FederationServer(serverURL, domain) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + _classCallCheck(this, FederationServer); + this.serverURL = URI_default()(serverURL); + this.domain = domain; + var allowHttp = typeof opts.allowHttp === "undefined" ? config/* Config */.T.isAllowHttp() : opts.allowHttp; + this.timeout = typeof opts.timeout === "undefined" ? config/* Config */.T.getTimeout() : opts.timeout; + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure federation server"); + } + } + return _createClass(FederationServer, [{ + key: "resolveAddress", + value: (function () { + var _resolveAddress = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(address) { + var stellarAddress, url; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + stellarAddress = address; + if (!(address.indexOf("*") < 0)) { + _context.next = 5; + break; + } + if (this.domain) { + _context.next = 4; + break; + } + return _context.abrupt("return", Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object."))); + case 4: + stellarAddress = "".concat(address, "*").concat(this.domain); + case 5: + url = this.serverURL.query({ + type: "name", + q: stellarAddress + }); + return _context.abrupt("return", this._sendRequest(url)); + case 7: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function resolveAddress(_x) { + return _resolveAddress.apply(this, arguments); + } + return resolveAddress; + }()) + }, { + key: "resolveAccountId", + value: (function () { + var _resolveAccountId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(accountId) { + var url; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + url = this.serverURL.query({ + type: "id", + q: accountId + }); + return _context2.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function resolveAccountId(_x2) { + return _resolveAccountId.apply(this, arguments); + } + return resolveAccountId; + }()) + }, { + key: "resolveTransactionId", + value: (function () { + var _resolveTransactionId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(transactionId) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = this.serverURL.query({ + type: "txid", + q: transactionId + }); + return _context3.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function resolveTransactionId(_x3) { + return _resolveTransactionId.apply(this, arguments); + } + return resolveTransactionId; + }()) + }, { + key: "_sendRequest", + value: function () { + var _sendRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(url) { + var timeout; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + timeout = this.timeout; + return _context4.abrupt("return", http_client/* httpClient */.ok.get(url.toString(), { + maxContentLength: FEDERATION_RESPONSE_MAX_SIZE, + timeout: timeout + }).then(function (response) { + if (typeof response.data.memo !== "undefined" && typeof response.data.memo !== "string") { + throw new Error("memo value should be of type string"); + } + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + if (response.message.match(/^maxContentLength size/)) { + throw new Error("federation response exceeds allowed size of ".concat(FEDERATION_RESPONSE_MAX_SIZE)); + } else { + return Promise.reject(response); + } + } else { + return Promise.reject(new errors/* BadResponseError */.nS("Server query failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + } + })); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function _sendRequest(_x4) { + return _sendRequest2.apply(this, arguments); + } + return _sendRequest; + }() + }], [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(value) { + var opts, + addressParts, + _addressParts, + domain, + federationServer, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {}; + if (!(value.indexOf("*") < 0)) { + _context5.next = 5; + break; + } + if (lib.StrKey.isValidEd25519PublicKey(value)) { + _context5.next = 4; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Account ID"))); + case 4: + return _context5.abrupt("return", Promise.resolve({ + account_id: value + })); + case 5: + addressParts = value.split("*"); + _addressParts = _slicedToArray(addressParts, 2), domain = _addressParts[1]; + if (!(addressParts.length !== 2 || !domain)) { + _context5.next = 9; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Stellar address"))); + case 9: + _context5.next = 11; + return FederationServer.createForDomain(domain, opts); + case 11: + federationServer = _context5.sent; + return _context5.abrupt("return", federationServer.resolveAddress(value)); + case 13: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function resolve(_x5) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }, { + key: "createForDomain", + value: (function () { + var _createForDomain = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(domain) { + var opts, + tomlObject, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : {}; + _context6.next = 3; + return stellartoml.Resolver.resolve(domain, opts); + case 3: + tomlObject = _context6.sent; + if (tomlObject.FEDERATION_SERVER) { + _context6.next = 6; + break; + } + return _context6.abrupt("return", Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field"))); + case 6: + return _context6.abrupt("return", new FederationServer(tomlObject.FEDERATION_SERVER, domain, opts)); + case 7: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function createForDomain(_x6) { + return _createForDomain.apply(this, arguments); + } + return createForDomain; + }()) + }]); +}(); +;// ./src/federation/api.ts +var Api; +;// ./src/federation/index.ts + + + +/***/ }), + +/***/ 8242: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Api: () => (/* binding */ Api) +/* harmony export */ }); +var Api; + +/***/ }), + +/***/ 8733: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + AccountResponse: () => (/* reexport */ AccountResponse), + AxiosClient: () => (/* reexport */ horizon_axios_client), + HorizonApi: () => (/* reexport */ HorizonApi), + SERVER_TIME_MAP: () => (/* reexport */ SERVER_TIME_MAP), + Server: () => (/* reexport */ HorizonServer), + ServerApi: () => (/* reexport */ ServerApi), + "default": () => (/* binding */ horizon), + getCurrentServerTime: () => (/* reexport */ getCurrentServerTime) +}); + +;// ./src/horizon/horizon_api.ts +var HorizonApi; +(function (_HorizonApi) { + var LiquidityPoolType = function (LiquidityPoolType) { + LiquidityPoolType["constantProduct"] = "constant_product"; + return LiquidityPoolType; + }({}); + _HorizonApi.LiquidityPoolType = LiquidityPoolType; + var OperationResponseType = function (OperationResponseType) { + OperationResponseType["createAccount"] = "create_account"; + OperationResponseType["payment"] = "payment"; + OperationResponseType["pathPayment"] = "path_payment_strict_receive"; + OperationResponseType["createPassiveOffer"] = "create_passive_sell_offer"; + OperationResponseType["manageOffer"] = "manage_sell_offer"; + OperationResponseType["setOptions"] = "set_options"; + OperationResponseType["changeTrust"] = "change_trust"; + OperationResponseType["allowTrust"] = "allow_trust"; + OperationResponseType["accountMerge"] = "account_merge"; + OperationResponseType["inflation"] = "inflation"; + OperationResponseType["manageData"] = "manage_data"; + OperationResponseType["bumpSequence"] = "bump_sequence"; + OperationResponseType["manageBuyOffer"] = "manage_buy_offer"; + OperationResponseType["pathPaymentStrictSend"] = "path_payment_strict_send"; + OperationResponseType["createClaimableBalance"] = "create_claimable_balance"; + OperationResponseType["claimClaimableBalance"] = "claim_claimable_balance"; + OperationResponseType["beginSponsoringFutureReserves"] = "begin_sponsoring_future_reserves"; + OperationResponseType["endSponsoringFutureReserves"] = "end_sponsoring_future_reserves"; + OperationResponseType["revokeSponsorship"] = "revoke_sponsorship"; + OperationResponseType["clawback"] = "clawback"; + OperationResponseType["clawbackClaimableBalance"] = "clawback_claimable_balance"; + OperationResponseType["setTrustLineFlags"] = "set_trust_line_flags"; + OperationResponseType["liquidityPoolDeposit"] = "liquidity_pool_deposit"; + OperationResponseType["liquidityPoolWithdraw"] = "liquidity_pool_withdraw"; + OperationResponseType["invokeHostFunction"] = "invoke_host_function"; + OperationResponseType["bumpFootprintExpiration"] = "bump_footprint_expiration"; + OperationResponseType["restoreFootprint"] = "restore_footprint"; + return OperationResponseType; + }({}); + _HorizonApi.OperationResponseType = OperationResponseType; + var OperationResponseTypeI = function (OperationResponseTypeI) { + OperationResponseTypeI[OperationResponseTypeI["createAccount"] = 0] = "createAccount"; + OperationResponseTypeI[OperationResponseTypeI["payment"] = 1] = "payment"; + OperationResponseTypeI[OperationResponseTypeI["pathPayment"] = 2] = "pathPayment"; + OperationResponseTypeI[OperationResponseTypeI["createPassiveOffer"] = 3] = "createPassiveOffer"; + OperationResponseTypeI[OperationResponseTypeI["manageOffer"] = 4] = "manageOffer"; + OperationResponseTypeI[OperationResponseTypeI["setOptions"] = 5] = "setOptions"; + OperationResponseTypeI[OperationResponseTypeI["changeTrust"] = 6] = "changeTrust"; + OperationResponseTypeI[OperationResponseTypeI["allowTrust"] = 7] = "allowTrust"; + OperationResponseTypeI[OperationResponseTypeI["accountMerge"] = 8] = "accountMerge"; + OperationResponseTypeI[OperationResponseTypeI["inflation"] = 9] = "inflation"; + OperationResponseTypeI[OperationResponseTypeI["manageData"] = 10] = "manageData"; + OperationResponseTypeI[OperationResponseTypeI["bumpSequence"] = 11] = "bumpSequence"; + OperationResponseTypeI[OperationResponseTypeI["manageBuyOffer"] = 12] = "manageBuyOffer"; + OperationResponseTypeI[OperationResponseTypeI["pathPaymentStrictSend"] = 13] = "pathPaymentStrictSend"; + OperationResponseTypeI[OperationResponseTypeI["createClaimableBalance"] = 14] = "createClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["claimClaimableBalance"] = 15] = "claimClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["beginSponsoringFutureReserves"] = 16] = "beginSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["endSponsoringFutureReserves"] = 17] = "endSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["revokeSponsorship"] = 18] = "revokeSponsorship"; + OperationResponseTypeI[OperationResponseTypeI["clawback"] = 19] = "clawback"; + OperationResponseTypeI[OperationResponseTypeI["clawbackClaimableBalance"] = 20] = "clawbackClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["setTrustLineFlags"] = 21] = "setTrustLineFlags"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolDeposit"] = 22] = "liquidityPoolDeposit"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolWithdraw"] = 23] = "liquidityPoolWithdraw"; + OperationResponseTypeI[OperationResponseTypeI["invokeHostFunction"] = 24] = "invokeHostFunction"; + OperationResponseTypeI[OperationResponseTypeI["bumpFootprintExpiration"] = 25] = "bumpFootprintExpiration"; + OperationResponseTypeI[OperationResponseTypeI["restoreFootprint"] = 26] = "restoreFootprint"; + return OperationResponseTypeI; + }({}); + _HorizonApi.OperationResponseTypeI = OperationResponseTypeI; + ; + var TransactionFailedResultCodes = function (TransactionFailedResultCodes) { + TransactionFailedResultCodes["TX_FAILED"] = "tx_failed"; + TransactionFailedResultCodes["TX_BAD_SEQ"] = "tx_bad_seq"; + TransactionFailedResultCodes["TX_BAD_AUTH"] = "tx_bad_auth"; + TransactionFailedResultCodes["TX_BAD_AUTH_EXTRA"] = "tx_bad_auth_extra"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_SUCCESS"] = "tx_fee_bump_inner_success"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_FAILED"] = "tx_fee_bump_inner_failed"; + TransactionFailedResultCodes["TX_NOT_SUPPORTED"] = "tx_not_supported"; + TransactionFailedResultCodes["TX_SUCCESS"] = "tx_success"; + TransactionFailedResultCodes["TX_TOO_EARLY"] = "tx_too_early"; + TransactionFailedResultCodes["TX_TOO_LATE"] = "tx_too_late"; + TransactionFailedResultCodes["TX_MISSING_OPERATION"] = "tx_missing_operation"; + TransactionFailedResultCodes["TX_INSUFFICIENT_BALANCE"] = "tx_insufficient_balance"; + TransactionFailedResultCodes["TX_NO_SOURCE_ACCOUNT"] = "tx_no_source_account"; + TransactionFailedResultCodes["TX_INSUFFICIENT_FEE"] = "tx_insufficient_fee"; + TransactionFailedResultCodes["TX_INTERNAL_ERROR"] = "tx_internal_error"; + return TransactionFailedResultCodes; + }({}); + _HorizonApi.TransactionFailedResultCodes = TransactionFailedResultCodes; +})(HorizonApi || (HorizonApi = {})); +;// ./src/horizon/types/effects.ts +var effects_EffectType = function (EffectType) { + EffectType[EffectType["account_created"] = 0] = "account_created"; + EffectType[EffectType["account_removed"] = 1] = "account_removed"; + EffectType[EffectType["account_credited"] = 2] = "account_credited"; + EffectType[EffectType["account_debited"] = 3] = "account_debited"; + EffectType[EffectType["account_thresholds_updated"] = 4] = "account_thresholds_updated"; + EffectType[EffectType["account_home_domain_updated"] = 5] = "account_home_domain_updated"; + EffectType[EffectType["account_flags_updated"] = 6] = "account_flags_updated"; + EffectType[EffectType["account_inflation_destination_updated"] = 7] = "account_inflation_destination_updated"; + EffectType[EffectType["signer_created"] = 10] = "signer_created"; + EffectType[EffectType["signer_removed"] = 11] = "signer_removed"; + EffectType[EffectType["signer_updated"] = 12] = "signer_updated"; + EffectType[EffectType["trustline_created"] = 20] = "trustline_created"; + EffectType[EffectType["trustline_removed"] = 21] = "trustline_removed"; + EffectType[EffectType["trustline_updated"] = 22] = "trustline_updated"; + EffectType[EffectType["trustline_authorized"] = 23] = "trustline_authorized"; + EffectType[EffectType["trustline_deauthorized"] = 24] = "trustline_deauthorized"; + EffectType[EffectType["trustline_authorized_to_maintain_liabilities"] = 25] = "trustline_authorized_to_maintain_liabilities"; + EffectType[EffectType["trustline_flags_updated"] = 26] = "trustline_flags_updated"; + EffectType[EffectType["offer_created"] = 30] = "offer_created"; + EffectType[EffectType["offer_removed"] = 31] = "offer_removed"; + EffectType[EffectType["offer_updated"] = 32] = "offer_updated"; + EffectType[EffectType["trade"] = 33] = "trade"; + EffectType[EffectType["data_created"] = 40] = "data_created"; + EffectType[EffectType["data_removed"] = 41] = "data_removed"; + EffectType[EffectType["data_updated"] = 42] = "data_updated"; + EffectType[EffectType["sequence_bumped"] = 43] = "sequence_bumped"; + EffectType[EffectType["claimable_balance_created"] = 50] = "claimable_balance_created"; + EffectType[EffectType["claimable_balance_claimant_created"] = 51] = "claimable_balance_claimant_created"; + EffectType[EffectType["claimable_balance_claimed"] = 52] = "claimable_balance_claimed"; + EffectType[EffectType["account_sponsorship_created"] = 60] = "account_sponsorship_created"; + EffectType[EffectType["account_sponsorship_updated"] = 61] = "account_sponsorship_updated"; + EffectType[EffectType["account_sponsorship_removed"] = 62] = "account_sponsorship_removed"; + EffectType[EffectType["trustline_sponsorship_created"] = 63] = "trustline_sponsorship_created"; + EffectType[EffectType["trustline_sponsorship_updated"] = 64] = "trustline_sponsorship_updated"; + EffectType[EffectType["trustline_sponsorship_removed"] = 65] = "trustline_sponsorship_removed"; + EffectType[EffectType["data_sponsorship_created"] = 66] = "data_sponsorship_created"; + EffectType[EffectType["data_sponsorship_updated"] = 67] = "data_sponsorship_updated"; + EffectType[EffectType["data_sponsorship_removed"] = 68] = "data_sponsorship_removed"; + EffectType[EffectType["claimable_balance_sponsorship_created"] = 69] = "claimable_balance_sponsorship_created"; + EffectType[EffectType["claimable_balance_sponsorship_updated"] = 70] = "claimable_balance_sponsorship_updated"; + EffectType[EffectType["claimable_balance_sponsorship_removed"] = 71] = "claimable_balance_sponsorship_removed"; + EffectType[EffectType["signer_sponsorship_created"] = 72] = "signer_sponsorship_created"; + EffectType[EffectType["signer_sponsorship_updated"] = 73] = "signer_sponsorship_updated"; + EffectType[EffectType["signer_sponsorship_removed"] = 74] = "signer_sponsorship_removed"; + EffectType[EffectType["claimable_balance_clawed_back"] = 80] = "claimable_balance_clawed_back"; + EffectType[EffectType["liquidity_pool_deposited"] = 90] = "liquidity_pool_deposited"; + EffectType[EffectType["liquidity_pool_withdrew"] = 91] = "liquidity_pool_withdrew"; + EffectType[EffectType["liquidity_pool_trade"] = 92] = "liquidity_pool_trade"; + EffectType[EffectType["liquidity_pool_created"] = 93] = "liquidity_pool_created"; + EffectType[EffectType["liquidity_pool_removed"] = 94] = "liquidity_pool_removed"; + EffectType[EffectType["liquidity_pool_revoked"] = 95] = "liquidity_pool_revoked"; + EffectType[EffectType["contract_credited"] = 96] = "contract_credited"; + EffectType[EffectType["contract_debited"] = 97] = "contract_debited"; + return EffectType; +}({}); +;// ./src/horizon/server_api.ts + + +var ServerApi; +(function (_ServerApi) { + var EffectType = _ServerApi.EffectType = effects_EffectType; + var TradeType = function (TradeType) { + TradeType["all"] = "all"; + TradeType["liquidityPools"] = "liquidity_pool"; + TradeType["orderbook"] = "orderbook"; + return TradeType; + }({}); + _ServerApi.TradeType = TradeType; + var OperationResponseType = HorizonApi.OperationResponseType; + var OperationResponseTypeI = HorizonApi.OperationResponseTypeI; +})(ServerApi || (ServerApi = {})); +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +;// ./src/horizon/account_response.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + +var AccountResponse = function () { + function AccountResponse(response) { + var _this = this; + _classCallCheck(this, AccountResponse); + this._baseAccount = new lib.Account(response.account_id, response.sequence); + Object.entries(response).forEach(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + _this[key] = value; + }); + } + return _createClass(AccountResponse, [{ + key: "accountId", + value: function accountId() { + return this._baseAccount.accountId(); + } + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this._baseAccount.sequenceNumber(); + } + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + this._baseAccount.incrementSequenceNumber(); + this.sequence = this._baseAccount.sequenceNumber(); + } + }]); +}(); +;// ./node_modules/bignumber.js/bignumber.mjs +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + +var + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + +/* + * Create and return a BigNumber constructor. + */ +function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + P[Symbol.toStringTag] = 'BigNumber'; + + // Node.js v10.12.0+ + P[Symbol.for('nodejs.util.inspect.custom')] = P.valueOf; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; +} + + +// PRIVATE HELPER FUNCTIONS + +// These functions don't need access to variables, +// e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + +function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; +} + + +// Return a coefficient array as a string of base 10 digits. +function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); +} + + +// Compare the value of BigNumbers x and y. +function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; +} + + +/* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ +function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } +} + + +// Assumes finite n. +function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; +} + + +function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; +} + + +function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; +} + + +// EXPORT + + +var BigNumber = clone(); + +/* harmony default export */ const bignumber = (BigNumber); + +// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js +var URI = __webpack_require__(4193); +var URI_default = /*#__PURE__*/__webpack_require__.n(URI); +// EXTERNAL MODULE: ./node_modules/urijs/src/URITemplate.js +var URITemplate = __webpack_require__(9127); +var URITemplate_default = /*#__PURE__*/__webpack_require__.n(URITemplate); +// EXTERNAL MODULE: ./src/errors/index.ts + 5 modules +var errors = __webpack_require__(5976); +// EXTERNAL MODULE: ./src/http-client/index.ts +var http_client = __webpack_require__(6371); +;// ./src/horizon/horizon_axios_client.ts +function horizon_axios_client_typeof(o) { "@babel/helpers - typeof"; return horizon_axios_client_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, horizon_axios_client_typeof(o); } + + +var version = "13.1.0"; +var SERVER_TIME_MAP = {}; +var AxiosClient = (0,http_client/* create */.vt)({ + headers: { + "X-Client-Name": "js-stellar-sdk", + "X-Client-Version": version + } +}); +function toSeconds(ms) { + return Math.floor(ms / 1000); +} +AxiosClient.interceptors.response.use(function (response) { + var hostname = URI_default()(response.config.url).hostname(); + var serverTime = 0; + if (response.headers instanceof Headers) { + var dateHeader = response.headers.get('date'); + if (dateHeader) { + serverTime = toSeconds(Date.parse(dateHeader)); + } + } else if (horizon_axios_client_typeof(response.headers) === 'object' && 'date' in response.headers) { + var headers = response.headers; + if (typeof headers.date === 'string') { + serverTime = toSeconds(Date.parse(headers.date)); + } + } + var localTimeRecorded = toSeconds(new Date().getTime()); + if (!Number.isNaN(serverTime)) { + SERVER_TIME_MAP[hostname] = { + serverTime: serverTime, + localTimeRecorded: localTimeRecorded + }; + } + return response; +}); +/* harmony default export */ const horizon_axios_client = (AxiosClient); +function getCurrentServerTime(hostname) { + var entry = SERVER_TIME_MAP[hostname]; + if (!entry || !entry.localTimeRecorded || !entry.serverTime) { + return null; + } + var serverTime = entry.serverTime, + localTimeRecorded = entry.localTimeRecorded; + var currentTime = toSeconds(new Date().getTime()); + if (currentTime - localTimeRecorded > 60 * 5) { + return null; + } + return currentTime - localTimeRecorded + serverTime; +} +;// ./src/horizon/call_builder.ts +function call_builder_typeof(o) { "@babel/helpers - typeof"; return call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, call_builder_typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == call_builder_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(call_builder_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, call_builder_toPropertyKey(o.key), o); } } +function call_builder_createClass(e, r, t) { return r && call_builder_defineProperties(e.prototype, r), t && call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function call_builder_toPropertyKey(t) { var i = call_builder_toPrimitive(t, "string"); return "symbol" == call_builder_typeof(i) ? i : i + ""; } +function call_builder_toPrimitive(t, r) { if ("object" != call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + +var JOINABLE = ["transaction"]; +var anyGlobal = __webpack_require__.g; +var EventSource; +if (true) { + var _ref, _anyGlobal$EventSourc, _anyGlobal$window; + EventSource = (_ref = (_anyGlobal$EventSourc = anyGlobal.EventSource) !== null && _anyGlobal$EventSourc !== void 0 ? _anyGlobal$EventSourc : (_anyGlobal$window = anyGlobal.window) === null || _anyGlobal$window === void 0 ? void 0 : _anyGlobal$window.EventSource) !== null && _ref !== void 0 ? _ref : __webpack_require__(1731); +} +var CallBuilder = function () { + function CallBuilder(serverUrl) { + var neighborRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; + call_builder_classCallCheck(this, CallBuilder); + this.url = serverUrl.clone(); + this.filter = []; + this.originalSegments = this.url.segment() || []; + this.neighborRoot = neighborRoot; + } + return call_builder_createClass(CallBuilder, [{ + key: "call", + value: function call() { + var _this = this; + this.checkFilter(); + return this._sendNormalRequest(this.url).then(function (r) { + return _this._parseResponse(r); + }); + } + }, { + key: "stream", + value: function stream() { + var _this2 = this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (EventSource === undefined) { + throw new Error("Streaming requires eventsource to be enabled. If you need this functionality, compile with USE_EVENTSOURCE=true."); + } + this.checkFilter(); + this.url.setQuery("X-Client-Name", "js-stellar-sdk"); + this.url.setQuery("X-Client-Version", version); + var es; + var timeout; + var createTimeout = function createTimeout() { + timeout = setTimeout(function () { + var _es; + (_es = es) === null || _es === void 0 || _es.close(); + es = _createEventSource(); + }, options.reconnectTimeout || 15 * 1000); + }; + var _createEventSource = function createEventSource() { + try { + es = new EventSource(_this2.url.toString()); + } catch (err) { + if (options.onerror) { + options.onerror(err); + } + } + createTimeout(); + if (!es) { + return es; + } + var closed = false; + var onClose = function onClose() { + if (closed) { + return; + } + clearTimeout(timeout); + es.close(); + _createEventSource(); + closed = true; + }; + var onMessage = function onMessage(message) { + if (message.type === "close") { + onClose(); + return; + } + var result = message.data ? _this2._parseRecord(JSON.parse(message.data)) : message; + if (result.paging_token) { + _this2.url.setQuery("cursor", result.paging_token); + } + clearTimeout(timeout); + createTimeout(); + if (typeof options.onmessage !== "undefined") { + options.onmessage(result); + } + }; + var onError = function onError(error) { + if (options.onerror) { + options.onerror(error); + } + }; + if (es.addEventListener) { + es.addEventListener("message", onMessage.bind(_this2)); + es.addEventListener("error", onError.bind(_this2)); + es.addEventListener("close", onClose.bind(_this2)); + } else { + es.onmessage = onMessage.bind(_this2); + es.onerror = onError.bind(_this2); + } + return es; + }; + _createEventSource(); + return function () { + var _es2; + clearTimeout(timeout); + (_es2 = es) === null || _es2 === void 0 || _es2.close(); + }; + } + }, { + key: "cursor", + value: function cursor(_cursor) { + this.url.setQuery("cursor", _cursor); + return this; + } + }, { + key: "limit", + value: function limit(recordsNumber) { + this.url.setQuery("limit", recordsNumber.toString()); + return this; + } + }, { + key: "order", + value: function order(direction) { + this.url.setQuery("order", direction); + return this; + } + }, { + key: "join", + value: function join(include) { + this.url.setQuery("join", include); + return this; + } + }, { + key: "forEndpoint", + value: function forEndpoint(endpoint, param) { + if (this.neighborRoot === "") { + throw new Error("Invalid usage: neighborRoot not set in constructor"); + } + this.filter.push([endpoint, param, this.neighborRoot]); + return this; + } + }, { + key: "checkFilter", + value: function checkFilter() { + if (this.filter.length >= 2) { + throw new errors/* BadRequestError */.v7("Too many filters specified", this.filter); + } + if (this.filter.length === 1) { + var newSegment = this.originalSegments.concat(this.filter[0]); + this.url.segment(newSegment); + } + } + }, { + key: "_requestFnForLink", + value: function _requestFnForLink(link) { + var _this3 = this; + return _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var opts, + uri, + template, + r, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}; + if (link.templated) { + template = URITemplate_default()(link.href); + uri = URI_default()(template.expand(opts)); + } else { + uri = URI_default()(link.href); + } + _context.next = 4; + return _this3._sendNormalRequest(uri); + case 4: + r = _context.sent; + return _context.abrupt("return", _this3._parseResponse(r)); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + } + }, { + key: "_parseRecord", + value: function _parseRecord(json) { + var _this4 = this; + if (!json._links) { + return json; + } + Object.keys(json._links).forEach(function (key) { + var n = json._links[key]; + var included = false; + if (typeof json[key] !== "undefined") { + json["".concat(key, "_attr")] = json[key]; + included = true; + } + if (included && JOINABLE.indexOf(key) >= 0) { + var record = _this4._parseRecord(json[key]); + json[key] = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", record); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + } else { + json[key] = _this4._requestFnForLink(n); + } + }); + return json; + } + }, { + key: "_sendNormalRequest", + value: function () { + var _sendNormalRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(initialUrl) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = initialUrl; + if (url.authority() === "") { + url = url.authority(this.url.authority()); + } + if (url.protocol() === "") { + url = url.protocol(this.url.protocol()); + } + return _context3.abrupt("return", AxiosClient.get(url.toString()).then(function (response) { + return response.data; + }).catch(this._handleNetworkError)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function _sendNormalRequest(_x) { + return _sendNormalRequest2.apply(this, arguments); + } + return _sendNormalRequest; + }() + }, { + key: "_parseResponse", + value: function _parseResponse(json) { + if (json._embedded && json._embedded.records) { + return this._toCollectionPage(json); + } + return this._parseRecord(json); + } + }, { + key: "_toCollectionPage", + value: function _toCollectionPage(json) { + var _this5 = this; + for (var i = 0; i < json._embedded.records.length; i += 1) { + json._embedded.records[i] = this._parseRecord(json._embedded.records[i]); + } + return { + records: json._embedded.records, + next: function () { + var _next2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + var r; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this5._sendNormalRequest(URI_default()(json._links.next.href)); + case 2: + r = _context4.sent; + return _context4.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function next() { + return _next2.apply(this, arguments); + } + return next; + }(), + prev: function () { + var _prev = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5() { + var r; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return _this5._sendNormalRequest(URI_default()(json._links.prev.href)); + case 2: + r = _context5.sent; + return _context5.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function prev() { + return _prev.apply(this, arguments); + } + return prev; + }() + }; + } + }, { + key: "_handleNetworkError", + value: (function () { + var _handleNetworkError2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(error) { + var _error$response$statu, _error$response$statu2; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + if (!(error.response && error.response.status)) { + _context6.next = 8; + break; + } + _context6.t0 = error.response.status; + _context6.next = _context6.t0 === 404 ? 4 : 5; + break; + case 4: + return _context6.abrupt("return", Promise.reject(new errors/* NotFoundError */.m_((_error$response$statu = error.response.statusText) !== null && _error$response$statu !== void 0 ? _error$response$statu : "Not Found", error.response.data))); + case 5: + return _context6.abrupt("return", Promise.reject(new errors/* NetworkError */.Dr((_error$response$statu2 = error.response.statusText) !== null && _error$response$statu2 !== void 0 ? _error$response$statu2 : "Unknown", error.response.data))); + case 6: + _context6.next = 9; + break; + case 8: + return _context6.abrupt("return", Promise.reject(new Error(error.message))); + case 9: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function _handleNetworkError(_x2) { + return _handleNetworkError2.apply(this, arguments); + } + return _handleNetworkError; + }()) + }]); +}(); +// EXTERNAL MODULE: ./src/config.ts +var config = __webpack_require__(8732); +;// ./src/horizon/account_call_builder.ts +function account_call_builder_typeof(o) { "@babel/helpers - typeof"; return account_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, account_call_builder_typeof(o); } +function account_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function account_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, account_call_builder_toPropertyKey(o.key), o); } } +function account_call_builder_createClass(e, r, t) { return r && account_call_builder_defineProperties(e.prototype, r), t && account_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function account_call_builder_toPropertyKey(t) { var i = account_call_builder_toPrimitive(t, "string"); return "symbol" == account_call_builder_typeof(i) ? i : i + ""; } +function account_call_builder_toPrimitive(t, r) { if ("object" != account_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != account_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == account_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } + +var AccountCallBuilder = function (_CallBuilder) { + function AccountCallBuilder(serverUrl) { + var _this; + account_call_builder_classCallCheck(this, AccountCallBuilder); + _this = _callSuper(this, AccountCallBuilder, [serverUrl]); + _this.url.segment("accounts"); + return _this; + } + _inherits(AccountCallBuilder, _CallBuilder); + return account_call_builder_createClass(AccountCallBuilder, [{ + key: "accountId", + value: function accountId(id) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([id]); + return builder; + } + }, { + key: "forSigner", + value: function forSigner(id) { + this.url.setQuery("signer", id); + return this; + } + }, { + key: "forAsset", + value: function forAsset(asset) { + this.url.setQuery("asset", "".concat(asset)); + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(id) { + this.url.setQuery("liquidity_pool", id); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/assets_call_builder.ts +function assets_call_builder_typeof(o) { "@babel/helpers - typeof"; return assets_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, assets_call_builder_typeof(o); } +function assets_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function assets_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, assets_call_builder_toPropertyKey(o.key), o); } } +function assets_call_builder_createClass(e, r, t) { return r && assets_call_builder_defineProperties(e.prototype, r), t && assets_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function assets_call_builder_toPropertyKey(t) { var i = assets_call_builder_toPrimitive(t, "string"); return "symbol" == assets_call_builder_typeof(i) ? i : i + ""; } +function assets_call_builder_toPrimitive(t, r) { if ("object" != assets_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != assets_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function assets_call_builder_callSuper(t, o, e) { return o = assets_call_builder_getPrototypeOf(o), assets_call_builder_possibleConstructorReturn(t, assets_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], assets_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function assets_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == assets_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return assets_call_builder_assertThisInitialized(t); } +function assets_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function assets_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (assets_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function assets_call_builder_getPrototypeOf(t) { return assets_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, assets_call_builder_getPrototypeOf(t); } +function assets_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && assets_call_builder_setPrototypeOf(t, e); } +function assets_call_builder_setPrototypeOf(t, e) { return assets_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, assets_call_builder_setPrototypeOf(t, e); } + +var AssetsCallBuilder = function (_CallBuilder) { + function AssetsCallBuilder(serverUrl) { + var _this; + assets_call_builder_classCallCheck(this, AssetsCallBuilder); + _this = assets_call_builder_callSuper(this, AssetsCallBuilder, [serverUrl]); + _this.url.segment("assets"); + return _this; + } + assets_call_builder_inherits(AssetsCallBuilder, _CallBuilder); + return assets_call_builder_createClass(AssetsCallBuilder, [{ + key: "forCode", + value: function forCode(value) { + this.url.setQuery("asset_code", value); + return this; + } + }, { + key: "forIssuer", + value: function forIssuer(value) { + this.url.setQuery("asset_issuer", value); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/claimable_balances_call_builder.ts +function claimable_balances_call_builder_typeof(o) { "@babel/helpers - typeof"; return claimable_balances_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, claimable_balances_call_builder_typeof(o); } +function claimable_balances_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function claimable_balances_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, claimable_balances_call_builder_toPropertyKey(o.key), o); } } +function claimable_balances_call_builder_createClass(e, r, t) { return r && claimable_balances_call_builder_defineProperties(e.prototype, r), t && claimable_balances_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function claimable_balances_call_builder_toPropertyKey(t) { var i = claimable_balances_call_builder_toPrimitive(t, "string"); return "symbol" == claimable_balances_call_builder_typeof(i) ? i : i + ""; } +function claimable_balances_call_builder_toPrimitive(t, r) { if ("object" != claimable_balances_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != claimable_balances_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function claimable_balances_call_builder_callSuper(t, o, e) { return o = claimable_balances_call_builder_getPrototypeOf(o), claimable_balances_call_builder_possibleConstructorReturn(t, claimable_balances_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], claimable_balances_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function claimable_balances_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == claimable_balances_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return claimable_balances_call_builder_assertThisInitialized(t); } +function claimable_balances_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function claimable_balances_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (claimable_balances_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function claimable_balances_call_builder_getPrototypeOf(t) { return claimable_balances_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, claimable_balances_call_builder_getPrototypeOf(t); } +function claimable_balances_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && claimable_balances_call_builder_setPrototypeOf(t, e); } +function claimable_balances_call_builder_setPrototypeOf(t, e) { return claimable_balances_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, claimable_balances_call_builder_setPrototypeOf(t, e); } + +var ClaimableBalanceCallBuilder = function (_CallBuilder) { + function ClaimableBalanceCallBuilder(serverUrl) { + var _this; + claimable_balances_call_builder_classCallCheck(this, ClaimableBalanceCallBuilder); + _this = claimable_balances_call_builder_callSuper(this, ClaimableBalanceCallBuilder, [serverUrl]); + _this.url.segment("claimable_balances"); + return _this; + } + claimable_balances_call_builder_inherits(ClaimableBalanceCallBuilder, _CallBuilder); + return claimable_balances_call_builder_createClass(ClaimableBalanceCallBuilder, [{ + key: "claimableBalance", + value: function claimableBalance(claimableBalanceId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([claimableBalanceId]); + return builder; + } + }, { + key: "sponsor", + value: function sponsor(_sponsor) { + this.url.setQuery("sponsor", _sponsor); + return this; + } + }, { + key: "claimant", + value: function claimant(_claimant) { + this.url.setQuery("claimant", _claimant); + return this; + } + }, { + key: "asset", + value: function asset(_asset) { + this.url.setQuery("asset", _asset.toString()); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/effect_call_builder.ts +function effect_call_builder_typeof(o) { "@babel/helpers - typeof"; return effect_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, effect_call_builder_typeof(o); } +function effect_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function effect_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, effect_call_builder_toPropertyKey(o.key), o); } } +function effect_call_builder_createClass(e, r, t) { return r && effect_call_builder_defineProperties(e.prototype, r), t && effect_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function effect_call_builder_toPropertyKey(t) { var i = effect_call_builder_toPrimitive(t, "string"); return "symbol" == effect_call_builder_typeof(i) ? i : i + ""; } +function effect_call_builder_toPrimitive(t, r) { if ("object" != effect_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != effect_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function effect_call_builder_callSuper(t, o, e) { return o = effect_call_builder_getPrototypeOf(o), effect_call_builder_possibleConstructorReturn(t, effect_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], effect_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function effect_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == effect_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return effect_call_builder_assertThisInitialized(t); } +function effect_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function effect_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (effect_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function effect_call_builder_getPrototypeOf(t) { return effect_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, effect_call_builder_getPrototypeOf(t); } +function effect_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && effect_call_builder_setPrototypeOf(t, e); } +function effect_call_builder_setPrototypeOf(t, e) { return effect_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, effect_call_builder_setPrototypeOf(t, e); } + +var EffectCallBuilder = function (_CallBuilder) { + function EffectCallBuilder(serverUrl) { + var _this; + effect_call_builder_classCallCheck(this, EffectCallBuilder); + _this = effect_call_builder_callSuper(this, EffectCallBuilder, [serverUrl, "effects"]); + _this.url.segment("effects"); + return _this; + } + effect_call_builder_inherits(EffectCallBuilder, _CallBuilder); + return effect_call_builder_createClass(EffectCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forOperation", + value: function forOperation(operationId) { + return this.forEndpoint("operations", operationId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }]); +}(CallBuilder); +;// ./src/horizon/friendbot_builder.ts +function friendbot_builder_typeof(o) { "@babel/helpers - typeof"; return friendbot_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, friendbot_builder_typeof(o); } +function friendbot_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, friendbot_builder_toPropertyKey(o.key), o); } } +function friendbot_builder_createClass(e, r, t) { return r && friendbot_builder_defineProperties(e.prototype, r), t && friendbot_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function friendbot_builder_toPropertyKey(t) { var i = friendbot_builder_toPrimitive(t, "string"); return "symbol" == friendbot_builder_typeof(i) ? i : i + ""; } +function friendbot_builder_toPrimitive(t, r) { if ("object" != friendbot_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != friendbot_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function friendbot_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function friendbot_builder_callSuper(t, o, e) { return o = friendbot_builder_getPrototypeOf(o), friendbot_builder_possibleConstructorReturn(t, friendbot_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], friendbot_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function friendbot_builder_possibleConstructorReturn(t, e) { if (e && ("object" == friendbot_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return friendbot_builder_assertThisInitialized(t); } +function friendbot_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function friendbot_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (friendbot_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function friendbot_builder_getPrototypeOf(t) { return friendbot_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, friendbot_builder_getPrototypeOf(t); } +function friendbot_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && friendbot_builder_setPrototypeOf(t, e); } +function friendbot_builder_setPrototypeOf(t, e) { return friendbot_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, friendbot_builder_setPrototypeOf(t, e); } + +var FriendbotBuilder = function (_CallBuilder) { + function FriendbotBuilder(serverUrl, address) { + var _this; + friendbot_builder_classCallCheck(this, FriendbotBuilder); + _this = friendbot_builder_callSuper(this, FriendbotBuilder, [serverUrl]); + _this.url.segment("friendbot"); + _this.url.setQuery("addr", address); + return _this; + } + friendbot_builder_inherits(FriendbotBuilder, _CallBuilder); + return friendbot_builder_createClass(FriendbotBuilder); +}(CallBuilder); +;// ./src/horizon/ledger_call_builder.ts +function ledger_call_builder_typeof(o) { "@babel/helpers - typeof"; return ledger_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, ledger_call_builder_typeof(o); } +function ledger_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function ledger_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, ledger_call_builder_toPropertyKey(o.key), o); } } +function ledger_call_builder_createClass(e, r, t) { return r && ledger_call_builder_defineProperties(e.prototype, r), t && ledger_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function ledger_call_builder_toPropertyKey(t) { var i = ledger_call_builder_toPrimitive(t, "string"); return "symbol" == ledger_call_builder_typeof(i) ? i : i + ""; } +function ledger_call_builder_toPrimitive(t, r) { if ("object" != ledger_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != ledger_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function ledger_call_builder_callSuper(t, o, e) { return o = ledger_call_builder_getPrototypeOf(o), ledger_call_builder_possibleConstructorReturn(t, ledger_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], ledger_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function ledger_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == ledger_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return ledger_call_builder_assertThisInitialized(t); } +function ledger_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function ledger_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (ledger_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function ledger_call_builder_getPrototypeOf(t) { return ledger_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, ledger_call_builder_getPrototypeOf(t); } +function ledger_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && ledger_call_builder_setPrototypeOf(t, e); } +function ledger_call_builder_setPrototypeOf(t, e) { return ledger_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, ledger_call_builder_setPrototypeOf(t, e); } + +var LedgerCallBuilder = function (_CallBuilder) { + function LedgerCallBuilder(serverUrl) { + var _this; + ledger_call_builder_classCallCheck(this, LedgerCallBuilder); + _this = ledger_call_builder_callSuper(this, LedgerCallBuilder, [serverUrl]); + _this.url.segment("ledgers"); + return _this; + } + ledger_call_builder_inherits(LedgerCallBuilder, _CallBuilder); + return ledger_call_builder_createClass(LedgerCallBuilder, [{ + key: "ledger", + value: function ledger(sequence) { + this.filter.push(["ledgers", sequence.toString()]); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/liquidity_pool_call_builder.ts +function liquidity_pool_call_builder_typeof(o) { "@babel/helpers - typeof"; return liquidity_pool_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, liquidity_pool_call_builder_typeof(o); } +function liquidity_pool_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function liquidity_pool_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, liquidity_pool_call_builder_toPropertyKey(o.key), o); } } +function liquidity_pool_call_builder_createClass(e, r, t) { return r && liquidity_pool_call_builder_defineProperties(e.prototype, r), t && liquidity_pool_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function liquidity_pool_call_builder_toPropertyKey(t) { var i = liquidity_pool_call_builder_toPrimitive(t, "string"); return "symbol" == liquidity_pool_call_builder_typeof(i) ? i : i + ""; } +function liquidity_pool_call_builder_toPrimitive(t, r) { if ("object" != liquidity_pool_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != liquidity_pool_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function liquidity_pool_call_builder_callSuper(t, o, e) { return o = liquidity_pool_call_builder_getPrototypeOf(o), liquidity_pool_call_builder_possibleConstructorReturn(t, liquidity_pool_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], liquidity_pool_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function liquidity_pool_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == liquidity_pool_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return liquidity_pool_call_builder_assertThisInitialized(t); } +function liquidity_pool_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function liquidity_pool_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (liquidity_pool_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function liquidity_pool_call_builder_getPrototypeOf(t) { return liquidity_pool_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, liquidity_pool_call_builder_getPrototypeOf(t); } +function liquidity_pool_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && liquidity_pool_call_builder_setPrototypeOf(t, e); } +function liquidity_pool_call_builder_setPrototypeOf(t, e) { return liquidity_pool_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, liquidity_pool_call_builder_setPrototypeOf(t, e); } + +var LiquidityPoolCallBuilder = function (_CallBuilder) { + function LiquidityPoolCallBuilder(serverUrl) { + var _this; + liquidity_pool_call_builder_classCallCheck(this, LiquidityPoolCallBuilder); + _this = liquidity_pool_call_builder_callSuper(this, LiquidityPoolCallBuilder, [serverUrl]); + _this.url.segment("liquidity_pools"); + return _this; + } + liquidity_pool_call_builder_inherits(LiquidityPoolCallBuilder, _CallBuilder); + return liquidity_pool_call_builder_createClass(LiquidityPoolCallBuilder, [{ + key: "forAssets", + value: function forAssets() { + for (var _len = arguments.length, assets = new Array(_len), _key = 0; _key < _len; _key++) { + assets[_key] = arguments[_key]; + } + var assetList = assets.map(function (asset) { + return asset.toString(); + }).join(","); + this.url.setQuery("reserves", assetList); + return this; + } + }, { + key: "forAccount", + value: function forAccount(id) { + this.url.setQuery("account", id); + return this; + } + }, { + key: "liquidityPoolId", + value: function liquidityPoolId(id) { + if (!id.match(/[a-fA-F0-9]{64}/)) { + throw new TypeError("".concat(id, " does not look like a liquidity pool ID")); + } + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([id.toLowerCase()]); + return builder; + } + }]); +}(CallBuilder); +;// ./src/horizon/offer_call_builder.ts +function offer_call_builder_typeof(o) { "@babel/helpers - typeof"; return offer_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, offer_call_builder_typeof(o); } +function offer_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function offer_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, offer_call_builder_toPropertyKey(o.key), o); } } +function offer_call_builder_createClass(e, r, t) { return r && offer_call_builder_defineProperties(e.prototype, r), t && offer_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function offer_call_builder_toPropertyKey(t) { var i = offer_call_builder_toPrimitive(t, "string"); return "symbol" == offer_call_builder_typeof(i) ? i : i + ""; } +function offer_call_builder_toPrimitive(t, r) { if ("object" != offer_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != offer_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function offer_call_builder_callSuper(t, o, e) { return o = offer_call_builder_getPrototypeOf(o), offer_call_builder_possibleConstructorReturn(t, offer_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], offer_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function offer_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == offer_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return offer_call_builder_assertThisInitialized(t); } +function offer_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function offer_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (offer_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function offer_call_builder_getPrototypeOf(t) { return offer_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, offer_call_builder_getPrototypeOf(t); } +function offer_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && offer_call_builder_setPrototypeOf(t, e); } +function offer_call_builder_setPrototypeOf(t, e) { return offer_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, offer_call_builder_setPrototypeOf(t, e); } + +var OfferCallBuilder = function (_CallBuilder) { + function OfferCallBuilder(serverUrl) { + var _this; + offer_call_builder_classCallCheck(this, OfferCallBuilder); + _this = offer_call_builder_callSuper(this, OfferCallBuilder, [serverUrl, "offers"]); + _this.url.segment("offers"); + return _this; + } + offer_call_builder_inherits(OfferCallBuilder, _CallBuilder); + return offer_call_builder_createClass(OfferCallBuilder, [{ + key: "offer", + value: function offer(offerId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([offerId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(id) { + return this.forEndpoint("accounts", id); + } + }, { + key: "buying", + value: function buying(asset) { + if (!asset.isNative()) { + this.url.setQuery("buying_asset_type", asset.getAssetType()); + this.url.setQuery("buying_asset_code", asset.getCode()); + this.url.setQuery("buying_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("buying_asset_type", "native"); + } + return this; + } + }, { + key: "selling", + value: function selling(asset) { + if (!asset.isNative()) { + this.url.setQuery("selling_asset_type", asset.getAssetType()); + this.url.setQuery("selling_asset_code", asset.getCode()); + this.url.setQuery("selling_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("selling_asset_type", "native"); + } + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "seller", + value: function seller(_seller) { + this.url.setQuery("seller", _seller); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/operation_call_builder.ts +function operation_call_builder_typeof(o) { "@babel/helpers - typeof"; return operation_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, operation_call_builder_typeof(o); } +function operation_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function operation_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, operation_call_builder_toPropertyKey(o.key), o); } } +function operation_call_builder_createClass(e, r, t) { return r && operation_call_builder_defineProperties(e.prototype, r), t && operation_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function operation_call_builder_toPropertyKey(t) { var i = operation_call_builder_toPrimitive(t, "string"); return "symbol" == operation_call_builder_typeof(i) ? i : i + ""; } +function operation_call_builder_toPrimitive(t, r) { if ("object" != operation_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != operation_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function operation_call_builder_callSuper(t, o, e) { return o = operation_call_builder_getPrototypeOf(o), operation_call_builder_possibleConstructorReturn(t, operation_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], operation_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function operation_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == operation_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return operation_call_builder_assertThisInitialized(t); } +function operation_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function operation_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (operation_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function operation_call_builder_getPrototypeOf(t) { return operation_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, operation_call_builder_getPrototypeOf(t); } +function operation_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && operation_call_builder_setPrototypeOf(t, e); } +function operation_call_builder_setPrototypeOf(t, e) { return operation_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, operation_call_builder_setPrototypeOf(t, e); } + +var OperationCallBuilder = function (_CallBuilder) { + function OperationCallBuilder(serverUrl) { + var _this; + operation_call_builder_classCallCheck(this, OperationCallBuilder); + _this = operation_call_builder_callSuper(this, OperationCallBuilder, [serverUrl, "operations"]); + _this.url.segment("operations"); + return _this; + } + operation_call_builder_inherits(OperationCallBuilder, _CallBuilder); + return operation_call_builder_createClass(OperationCallBuilder, [{ + key: "operation", + value: function operation(operationId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([operationId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/orderbook_call_builder.ts +function orderbook_call_builder_typeof(o) { "@babel/helpers - typeof"; return orderbook_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, orderbook_call_builder_typeof(o); } +function orderbook_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, orderbook_call_builder_toPropertyKey(o.key), o); } } +function orderbook_call_builder_createClass(e, r, t) { return r && orderbook_call_builder_defineProperties(e.prototype, r), t && orderbook_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function orderbook_call_builder_toPropertyKey(t) { var i = orderbook_call_builder_toPrimitive(t, "string"); return "symbol" == orderbook_call_builder_typeof(i) ? i : i + ""; } +function orderbook_call_builder_toPrimitive(t, r) { if ("object" != orderbook_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != orderbook_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function orderbook_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function orderbook_call_builder_callSuper(t, o, e) { return o = orderbook_call_builder_getPrototypeOf(o), orderbook_call_builder_possibleConstructorReturn(t, orderbook_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], orderbook_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function orderbook_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == orderbook_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return orderbook_call_builder_assertThisInitialized(t); } +function orderbook_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function orderbook_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (orderbook_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function orderbook_call_builder_getPrototypeOf(t) { return orderbook_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, orderbook_call_builder_getPrototypeOf(t); } +function orderbook_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && orderbook_call_builder_setPrototypeOf(t, e); } +function orderbook_call_builder_setPrototypeOf(t, e) { return orderbook_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, orderbook_call_builder_setPrototypeOf(t, e); } + +var OrderbookCallBuilder = function (_CallBuilder) { + function OrderbookCallBuilder(serverUrl, selling, buying) { + var _this; + orderbook_call_builder_classCallCheck(this, OrderbookCallBuilder); + _this = orderbook_call_builder_callSuper(this, OrderbookCallBuilder, [serverUrl]); + _this.url.segment("order_book"); + if (!selling.isNative()) { + _this.url.setQuery("selling_asset_type", selling.getAssetType()); + _this.url.setQuery("selling_asset_code", selling.getCode()); + _this.url.setQuery("selling_asset_issuer", selling.getIssuer()); + } else { + _this.url.setQuery("selling_asset_type", "native"); + } + if (!buying.isNative()) { + _this.url.setQuery("buying_asset_type", buying.getAssetType()); + _this.url.setQuery("buying_asset_code", buying.getCode()); + _this.url.setQuery("buying_asset_issuer", buying.getIssuer()); + } else { + _this.url.setQuery("buying_asset_type", "native"); + } + return _this; + } + orderbook_call_builder_inherits(OrderbookCallBuilder, _CallBuilder); + return orderbook_call_builder_createClass(OrderbookCallBuilder); +}(CallBuilder); +;// ./src/horizon/payment_call_builder.ts +function payment_call_builder_typeof(o) { "@babel/helpers - typeof"; return payment_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, payment_call_builder_typeof(o); } +function payment_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function payment_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, payment_call_builder_toPropertyKey(o.key), o); } } +function payment_call_builder_createClass(e, r, t) { return r && payment_call_builder_defineProperties(e.prototype, r), t && payment_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function payment_call_builder_toPropertyKey(t) { var i = payment_call_builder_toPrimitive(t, "string"); return "symbol" == payment_call_builder_typeof(i) ? i : i + ""; } +function payment_call_builder_toPrimitive(t, r) { if ("object" != payment_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != payment_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function payment_call_builder_callSuper(t, o, e) { return o = payment_call_builder_getPrototypeOf(o), payment_call_builder_possibleConstructorReturn(t, payment_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], payment_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function payment_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == payment_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return payment_call_builder_assertThisInitialized(t); } +function payment_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function payment_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (payment_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function payment_call_builder_getPrototypeOf(t) { return payment_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, payment_call_builder_getPrototypeOf(t); } +function payment_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && payment_call_builder_setPrototypeOf(t, e); } +function payment_call_builder_setPrototypeOf(t, e) { return payment_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, payment_call_builder_setPrototypeOf(t, e); } + +var PaymentCallBuilder = function (_CallBuilder) { + function PaymentCallBuilder(serverUrl) { + var _this; + payment_call_builder_classCallCheck(this, PaymentCallBuilder); + _this = payment_call_builder_callSuper(this, PaymentCallBuilder, [serverUrl, "payments"]); + _this.url.segment("payments"); + return _this; + } + payment_call_builder_inherits(PaymentCallBuilder, _CallBuilder); + return payment_call_builder_createClass(PaymentCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }]); +}(CallBuilder); +;// ./src/horizon/strict_receive_path_call_builder.ts +function strict_receive_path_call_builder_typeof(o) { "@babel/helpers - typeof"; return strict_receive_path_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, strict_receive_path_call_builder_typeof(o); } +function strict_receive_path_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, strict_receive_path_call_builder_toPropertyKey(o.key), o); } } +function strict_receive_path_call_builder_createClass(e, r, t) { return r && strict_receive_path_call_builder_defineProperties(e.prototype, r), t && strict_receive_path_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function strict_receive_path_call_builder_toPropertyKey(t) { var i = strict_receive_path_call_builder_toPrimitive(t, "string"); return "symbol" == strict_receive_path_call_builder_typeof(i) ? i : i + ""; } +function strict_receive_path_call_builder_toPrimitive(t, r) { if ("object" != strict_receive_path_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != strict_receive_path_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function strict_receive_path_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function strict_receive_path_call_builder_callSuper(t, o, e) { return o = strict_receive_path_call_builder_getPrototypeOf(o), strict_receive_path_call_builder_possibleConstructorReturn(t, strict_receive_path_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], strict_receive_path_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function strict_receive_path_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == strict_receive_path_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return strict_receive_path_call_builder_assertThisInitialized(t); } +function strict_receive_path_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function strict_receive_path_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (strict_receive_path_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function strict_receive_path_call_builder_getPrototypeOf(t) { return strict_receive_path_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, strict_receive_path_call_builder_getPrototypeOf(t); } +function strict_receive_path_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && strict_receive_path_call_builder_setPrototypeOf(t, e); } +function strict_receive_path_call_builder_setPrototypeOf(t, e) { return strict_receive_path_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, strict_receive_path_call_builder_setPrototypeOf(t, e); } + +var StrictReceivePathCallBuilder = function (_CallBuilder) { + function StrictReceivePathCallBuilder(serverUrl, source, destinationAsset, destinationAmount) { + var _this; + strict_receive_path_call_builder_classCallCheck(this, StrictReceivePathCallBuilder); + _this = strict_receive_path_call_builder_callSuper(this, StrictReceivePathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-receive"); + if (typeof source === "string") { + _this.url.setQuery("source_account", source); + } else { + var assets = source.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("source_assets", assets); + } + _this.url.setQuery("destination_amount", destinationAmount); + if (!destinationAsset.isNative()) { + _this.url.setQuery("destination_asset_type", destinationAsset.getAssetType()); + _this.url.setQuery("destination_asset_code", destinationAsset.getCode()); + _this.url.setQuery("destination_asset_issuer", destinationAsset.getIssuer()); + } else { + _this.url.setQuery("destination_asset_type", "native"); + } + return _this; + } + strict_receive_path_call_builder_inherits(StrictReceivePathCallBuilder, _CallBuilder); + return strict_receive_path_call_builder_createClass(StrictReceivePathCallBuilder); +}(CallBuilder); +;// ./src/horizon/strict_send_path_call_builder.ts +function strict_send_path_call_builder_typeof(o) { "@babel/helpers - typeof"; return strict_send_path_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, strict_send_path_call_builder_typeof(o); } +function strict_send_path_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, strict_send_path_call_builder_toPropertyKey(o.key), o); } } +function strict_send_path_call_builder_createClass(e, r, t) { return r && strict_send_path_call_builder_defineProperties(e.prototype, r), t && strict_send_path_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function strict_send_path_call_builder_toPropertyKey(t) { var i = strict_send_path_call_builder_toPrimitive(t, "string"); return "symbol" == strict_send_path_call_builder_typeof(i) ? i : i + ""; } +function strict_send_path_call_builder_toPrimitive(t, r) { if ("object" != strict_send_path_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != strict_send_path_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function strict_send_path_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function strict_send_path_call_builder_callSuper(t, o, e) { return o = strict_send_path_call_builder_getPrototypeOf(o), strict_send_path_call_builder_possibleConstructorReturn(t, strict_send_path_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], strict_send_path_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function strict_send_path_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == strict_send_path_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return strict_send_path_call_builder_assertThisInitialized(t); } +function strict_send_path_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function strict_send_path_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (strict_send_path_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function strict_send_path_call_builder_getPrototypeOf(t) { return strict_send_path_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, strict_send_path_call_builder_getPrototypeOf(t); } +function strict_send_path_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && strict_send_path_call_builder_setPrototypeOf(t, e); } +function strict_send_path_call_builder_setPrototypeOf(t, e) { return strict_send_path_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, strict_send_path_call_builder_setPrototypeOf(t, e); } + +var StrictSendPathCallBuilder = function (_CallBuilder) { + function StrictSendPathCallBuilder(serverUrl, sourceAsset, sourceAmount, destination) { + var _this; + strict_send_path_call_builder_classCallCheck(this, StrictSendPathCallBuilder); + _this = strict_send_path_call_builder_callSuper(this, StrictSendPathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-send"); + if (sourceAsset.isNative()) { + _this.url.setQuery("source_asset_type", "native"); + } else { + _this.url.setQuery("source_asset_type", sourceAsset.getAssetType()); + _this.url.setQuery("source_asset_code", sourceAsset.getCode()); + _this.url.setQuery("source_asset_issuer", sourceAsset.getIssuer()); + } + _this.url.setQuery("source_amount", sourceAmount); + if (typeof destination === "string") { + _this.url.setQuery("destination_account", destination); + } else { + var assets = destination.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("destination_assets", assets); + } + return _this; + } + strict_send_path_call_builder_inherits(StrictSendPathCallBuilder, _CallBuilder); + return strict_send_path_call_builder_createClass(StrictSendPathCallBuilder); +}(CallBuilder); +;// ./src/horizon/trade_aggregation_call_builder.ts +function trade_aggregation_call_builder_typeof(o) { "@babel/helpers - typeof"; return trade_aggregation_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, trade_aggregation_call_builder_typeof(o); } +function trade_aggregation_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function trade_aggregation_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, trade_aggregation_call_builder_toPropertyKey(o.key), o); } } +function trade_aggregation_call_builder_createClass(e, r, t) { return r && trade_aggregation_call_builder_defineProperties(e.prototype, r), t && trade_aggregation_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function trade_aggregation_call_builder_toPropertyKey(t) { var i = trade_aggregation_call_builder_toPrimitive(t, "string"); return "symbol" == trade_aggregation_call_builder_typeof(i) ? i : i + ""; } +function trade_aggregation_call_builder_toPrimitive(t, r) { if ("object" != trade_aggregation_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != trade_aggregation_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function trade_aggregation_call_builder_callSuper(t, o, e) { return o = trade_aggregation_call_builder_getPrototypeOf(o), trade_aggregation_call_builder_possibleConstructorReturn(t, trade_aggregation_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], trade_aggregation_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function trade_aggregation_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == trade_aggregation_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return trade_aggregation_call_builder_assertThisInitialized(t); } +function trade_aggregation_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function trade_aggregation_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (trade_aggregation_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function trade_aggregation_call_builder_getPrototypeOf(t) { return trade_aggregation_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, trade_aggregation_call_builder_getPrototypeOf(t); } +function trade_aggregation_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && trade_aggregation_call_builder_setPrototypeOf(t, e); } +function trade_aggregation_call_builder_setPrototypeOf(t, e) { return trade_aggregation_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, trade_aggregation_call_builder_setPrototypeOf(t, e); } + + +var allowedResolutions = [60000, 300000, 900000, 3600000, 86400000, 604800000]; +var TradeAggregationCallBuilder = function (_CallBuilder) { + function TradeAggregationCallBuilder(serverUrl, base, counter, start_time, end_time, resolution, offset) { + var _this; + trade_aggregation_call_builder_classCallCheck(this, TradeAggregationCallBuilder); + _this = trade_aggregation_call_builder_callSuper(this, TradeAggregationCallBuilder, [serverUrl]); + _this.url.segment("trade_aggregations"); + if (!base.isNative()) { + _this.url.setQuery("base_asset_type", base.getAssetType()); + _this.url.setQuery("base_asset_code", base.getCode()); + _this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + _this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + _this.url.setQuery("counter_asset_type", counter.getAssetType()); + _this.url.setQuery("counter_asset_code", counter.getCode()); + _this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + _this.url.setQuery("counter_asset_type", "native"); + } + if (typeof start_time !== "number" || typeof end_time !== "number") { + throw new errors/* BadRequestError */.v7("Invalid time bounds", [start_time, end_time]); + } else { + _this.url.setQuery("start_time", start_time.toString()); + _this.url.setQuery("end_time", end_time.toString()); + } + if (!_this.isValidResolution(resolution)) { + throw new errors/* BadRequestError */.v7("Invalid resolution", resolution); + } else { + _this.url.setQuery("resolution", resolution.toString()); + } + if (!_this.isValidOffset(offset, resolution)) { + throw new errors/* BadRequestError */.v7("Invalid offset", offset); + } else { + _this.url.setQuery("offset", offset.toString()); + } + return _this; + } + trade_aggregation_call_builder_inherits(TradeAggregationCallBuilder, _CallBuilder); + return trade_aggregation_call_builder_createClass(TradeAggregationCallBuilder, [{ + key: "isValidResolution", + value: function isValidResolution(resolution) { + return allowedResolutions.some(function (allowed) { + return allowed === resolution; + }); + } + }, { + key: "isValidOffset", + value: function isValidOffset(offset, resolution) { + var hour = 3600000; + return !(offset > resolution || offset >= 24 * hour || offset % hour !== 0); + } + }]); +}(CallBuilder); +;// ./src/horizon/trades_call_builder.ts +function trades_call_builder_typeof(o) { "@babel/helpers - typeof"; return trades_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, trades_call_builder_typeof(o); } +function trades_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function trades_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, trades_call_builder_toPropertyKey(o.key), o); } } +function trades_call_builder_createClass(e, r, t) { return r && trades_call_builder_defineProperties(e.prototype, r), t && trades_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function trades_call_builder_toPropertyKey(t) { var i = trades_call_builder_toPrimitive(t, "string"); return "symbol" == trades_call_builder_typeof(i) ? i : i + ""; } +function trades_call_builder_toPrimitive(t, r) { if ("object" != trades_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != trades_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function trades_call_builder_callSuper(t, o, e) { return o = trades_call_builder_getPrototypeOf(o), trades_call_builder_possibleConstructorReturn(t, trades_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], trades_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function trades_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == trades_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return trades_call_builder_assertThisInitialized(t); } +function trades_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function trades_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (trades_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function trades_call_builder_getPrototypeOf(t) { return trades_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, trades_call_builder_getPrototypeOf(t); } +function trades_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && trades_call_builder_setPrototypeOf(t, e); } +function trades_call_builder_setPrototypeOf(t, e) { return trades_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, trades_call_builder_setPrototypeOf(t, e); } + +var TradesCallBuilder = function (_CallBuilder) { + function TradesCallBuilder(serverUrl) { + var _this; + trades_call_builder_classCallCheck(this, TradesCallBuilder); + _this = trades_call_builder_callSuper(this, TradesCallBuilder, [serverUrl, "trades"]); + _this.url.segment("trades"); + return _this; + } + trades_call_builder_inherits(TradesCallBuilder, _CallBuilder); + return trades_call_builder_createClass(TradesCallBuilder, [{ + key: "forAssetPair", + value: function forAssetPair(base, counter) { + if (!base.isNative()) { + this.url.setQuery("base_asset_type", base.getAssetType()); + this.url.setQuery("base_asset_code", base.getCode()); + this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + this.url.setQuery("counter_asset_type", counter.getAssetType()); + this.url.setQuery("counter_asset_code", counter.getCode()); + this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + this.url.setQuery("counter_asset_type", "native"); + } + return this; + } + }, { + key: "forOffer", + value: function forOffer(offerId) { + this.url.setQuery("offer_id", offerId); + return this; + } + }, { + key: "forType", + value: function forType(tradeType) { + this.url.setQuery("trade_type", tradeType); + return this; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(liquidityPoolId) { + return this.forEndpoint("liquidity_pools", liquidityPoolId); + } + }]); +}(CallBuilder); +;// ./src/horizon/transaction_call_builder.ts +function transaction_call_builder_typeof(o) { "@babel/helpers - typeof"; return transaction_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, transaction_call_builder_typeof(o); } +function transaction_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function transaction_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, transaction_call_builder_toPropertyKey(o.key), o); } } +function transaction_call_builder_createClass(e, r, t) { return r && transaction_call_builder_defineProperties(e.prototype, r), t && transaction_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function transaction_call_builder_toPropertyKey(t) { var i = transaction_call_builder_toPrimitive(t, "string"); return "symbol" == transaction_call_builder_typeof(i) ? i : i + ""; } +function transaction_call_builder_toPrimitive(t, r) { if ("object" != transaction_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != transaction_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function transaction_call_builder_callSuper(t, o, e) { return o = transaction_call_builder_getPrototypeOf(o), transaction_call_builder_possibleConstructorReturn(t, transaction_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], transaction_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function transaction_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == transaction_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return transaction_call_builder_assertThisInitialized(t); } +function transaction_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function transaction_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (transaction_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function transaction_call_builder_getPrototypeOf(t) { return transaction_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, transaction_call_builder_getPrototypeOf(t); } +function transaction_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && transaction_call_builder_setPrototypeOf(t, e); } +function transaction_call_builder_setPrototypeOf(t, e) { return transaction_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, transaction_call_builder_setPrototypeOf(t, e); } + +var TransactionCallBuilder = function (_CallBuilder) { + function TransactionCallBuilder(serverUrl) { + var _this; + transaction_call_builder_classCallCheck(this, TransactionCallBuilder); + _this = transaction_call_builder_callSuper(this, TransactionCallBuilder, [serverUrl, "transactions"]); + _this.url.segment("transactions"); + return _this; + } + transaction_call_builder_inherits(TransactionCallBuilder, _CallBuilder); + return transaction_call_builder_createClass(TransactionCallBuilder, [{ + key: "transaction", + value: function transaction(transactionId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([transactionId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/server.ts +function server_typeof(o) { "@babel/helpers - typeof"; return server_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, server_typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = server_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function server_regeneratorRuntime() { "use strict"; server_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == server_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(server_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function server_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function server_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function server_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function server_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, server_toPropertyKey(o.key), o); } } +function server_createClass(e, r, t) { return r && server_defineProperties(e.prototype, r), t && server_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function server_toPropertyKey(t) { var i = server_toPrimitive(t, "string"); return "symbol" == server_typeof(i) ? i : i + ""; } +function server_toPrimitive(t, r) { if ("object" != server_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != server_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + + + + + + + + + + + + + + + + + + + +var SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000; +var STROOPS_IN_LUMEN = 10000000; +var ACCOUNT_REQUIRES_MEMO = "MQ=="; +function getAmountInLumens(amt) { + return new bignumber(amt).div(STROOPS_IN_LUMEN).toString(); +} +var HorizonServer = function () { + function HorizonServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + server_classCallCheck(this, HorizonServer); + this.serverURL = URI_default()(serverURL); + var allowHttp = typeof opts.allowHttp === "undefined" ? config/* Config */.T.isAllowHttp() : opts.allowHttp; + var customHeaders = {}; + if (opts.appName) { + customHeaders["X-App-Name"] = opts.appName; + } + if (opts.appVersion) { + customHeaders["X-App-Version"] = opts.appVersion; + } + if (opts.authToken) { + customHeaders["X-Auth-Token"] = opts.authToken; + } + if (opts.headers) { + Object.assign(customHeaders, opts.headers); + } + if (Object.keys(customHeaders).length > 0) { + horizon_axios_client.interceptors.request.use(function (config) { + config.headers = config.headers || {}; + config.headers = Object.assign(config.headers, customHeaders); + return config; + }); + } + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure horizon server"); + } + } + return server_createClass(HorizonServer, [{ + key: "fetchTimebounds", + value: (function () { + var _fetchTimebounds = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee(seconds) { + var _isRetry, + currentTime, + _args = arguments; + return server_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _isRetry = _args.length > 1 && _args[1] !== undefined ? _args[1] : false; + currentTime = getCurrentServerTime(this.serverURL.hostname()); + if (!currentTime) { + _context.next = 4; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: currentTime + seconds + }); + case 4: + if (!_isRetry) { + _context.next = 6; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: Math.floor(new Date().getTime() / 1000) + seconds + }); + case 6: + _context.next = 8; + return horizon_axios_client.get(URI_default()(this.serverURL).toString()); + case 8: + return _context.abrupt("return", this.fetchTimebounds(seconds, true)); + case 9: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function fetchTimebounds(_x) { + return _fetchTimebounds.apply(this, arguments); + } + return fetchTimebounds; + }()) + }, { + key: "fetchBaseFee", + value: (function () { + var _fetchBaseFee = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee2() { + var response; + return server_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.feeStats(); + case 2: + response = _context2.sent; + return _context2.abrupt("return", parseInt(response.last_ledger_base_fee, 10) || 100); + case 4: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function fetchBaseFee() { + return _fetchBaseFee.apply(this, arguments); + } + return fetchBaseFee; + }()) + }, { + key: "feeStats", + value: (function () { + var _feeStats = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee3() { + var cb; + return server_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + cb = new CallBuilder(URI_default()(this.serverURL)); + cb.filter.push(["fee_stats"]); + return _context3.abrupt("return", cb.call()); + case 3: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function feeStats() { + return _feeStats.apply(this, arguments); + } + return feeStats; + }()) + }, { + key: "root", + value: (function () { + var _root = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee4() { + var cb; + return server_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + cb = new CallBuilder(URI_default()(this.serverURL)); + return _context4.abrupt("return", cb.call()); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function root() { + return _root.apply(this, arguments); + } + return root; + }()) + }, { + key: "submitTransaction", + value: (function () { + var _submitTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee5(transaction) { + var opts, + tx, + _args5 = arguments; + return server_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context5.next = 4; + break; + } + _context5.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context5.abrupt("return", horizon_axios_client.post(URI_default()(this.serverURL).segment("transactions").toString(), "tx=".concat(tx), { + timeout: SUBMIT_TRANSACTION_TIMEOUT + }).then(function (response) { + if (!response.data.result_xdr) { + return response.data; + } + var responseXDR = lib.xdr.TransactionResult.fromXDR(response.data.result_xdr, "base64"); + var results = responseXDR.result().value(); + var offerResults; + var hasManageOffer; + if (results.length) { + offerResults = results.map(function (result, i) { + if (result.value().switch().name !== "manageBuyOffer" && result.value().switch().name !== "manageSellOffer") { + return null; + } + hasManageOffer = true; + var amountBought = new bignumber(0); + var amountSold = new bignumber(0); + var offerSuccess = result.value().value().success(); + var offersClaimed = offerSuccess.offersClaimed().map(function (offerClaimedAtom) { + var offerClaimed = offerClaimedAtom.value(); + var sellerId = ""; + switch (offerClaimedAtom.switch()) { + case lib.xdr.ClaimAtomType.claimAtomTypeV0(): + sellerId = lib.StrKey.encodeEd25519PublicKey(offerClaimed.sellerEd25519()); + break; + case lib.xdr.ClaimAtomType.claimAtomTypeOrderBook(): + sellerId = lib.StrKey.encodeEd25519PublicKey(offerClaimed.sellerId().ed25519()); + break; + default: + throw new Error("Invalid offer result type: ".concat(offerClaimedAtom.switch())); + } + var claimedOfferAmountBought = new bignumber(offerClaimed.amountBought().toString()); + var claimedOfferAmountSold = new bignumber(offerClaimed.amountSold().toString()); + amountBought = amountBought.plus(claimedOfferAmountSold); + amountSold = amountSold.plus(claimedOfferAmountBought); + var sold = lib.Asset.fromOperation(offerClaimed.assetSold()); + var bought = lib.Asset.fromOperation(offerClaimed.assetBought()); + var assetSold = { + type: sold.getAssetType(), + assetCode: sold.getCode(), + issuer: sold.getIssuer() + }; + var assetBought = { + type: bought.getAssetType(), + assetCode: bought.getCode(), + issuer: bought.getIssuer() + }; + return { + sellerId: sellerId, + offerId: offerClaimed.offerId().toString(), + assetSold: assetSold, + amountSold: getAmountInLumens(claimedOfferAmountSold), + assetBought: assetBought, + amountBought: getAmountInLumens(claimedOfferAmountBought) + }; + }); + var effect = offerSuccess.offer().switch().name; + var currentOffer; + if (typeof offerSuccess.offer().value === "function" && offerSuccess.offer().value()) { + var offerXDR = offerSuccess.offer().value(); + currentOffer = { + offerId: offerXDR.offerId().toString(), + selling: {}, + buying: {}, + amount: getAmountInLumens(offerXDR.amount().toString()), + price: { + n: offerXDR.price().n(), + d: offerXDR.price().d() + } + }; + var selling = lib.Asset.fromOperation(offerXDR.selling()); + currentOffer.selling = { + type: selling.getAssetType(), + assetCode: selling.getCode(), + issuer: selling.getIssuer() + }; + var buying = lib.Asset.fromOperation(offerXDR.buying()); + currentOffer.buying = { + type: buying.getAssetType(), + assetCode: buying.getCode(), + issuer: buying.getIssuer() + }; + } + return { + offersClaimed: offersClaimed, + effect: effect, + operationIndex: i, + currentOffer: currentOffer, + amountBought: getAmountInLumens(amountBought), + amountSold: getAmountInLumens(amountSold), + isFullyOpen: !offersClaimed.length && effect !== "manageOfferDeleted", + wasPartiallyFilled: !!offersClaimed.length && effect !== "manageOfferDeleted", + wasImmediatelyFilled: !!offersClaimed.length && effect === "manageOfferDeleted", + wasImmediatelyDeleted: !offersClaimed.length && effect === "manageOfferDeleted" + }; + }).filter(function (result) { + return !!result; + }); + } + return _objectSpread(_objectSpread({}, response.data), {}, { + offerResults: hasManageOffer ? offerResults : undefined + }); + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new errors/* BadResponseError */.nS("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function submitTransaction(_x2) { + return _submitTransaction.apply(this, arguments); + } + return submitTransaction; + }()) + }, { + key: "submitAsyncTransaction", + value: (function () { + var _submitAsyncTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee6(transaction) { + var opts, + tx, + _args6 = arguments; + return server_regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context6.next = 4; + break; + } + _context6.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context6.abrupt("return", horizon_axios_client.post(URI_default()(this.serverURL).segment("transactions_async").toString(), "tx=".concat(tx)).then(function (response) { + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new errors/* BadResponseError */.nS("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function submitAsyncTransaction(_x3) { + return _submitAsyncTransaction.apply(this, arguments); + } + return submitAsyncTransaction; + }()) + }, { + key: "accounts", + value: function accounts() { + return new AccountCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "claimableBalances", + value: function claimableBalances() { + return new ClaimableBalanceCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "ledgers", + value: function ledgers() { + return new LedgerCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "transactions", + value: function transactions() { + return new TransactionCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "offers", + value: function offers() { + return new OfferCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "orderbook", + value: function orderbook(selling, buying) { + return new OrderbookCallBuilder(URI_default()(this.serverURL), selling, buying); + } + }, { + key: "trades", + value: function trades() { + return new TradesCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "operations", + value: function operations() { + return new OperationCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "liquidityPools", + value: function liquidityPools() { + return new LiquidityPoolCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "strictReceivePaths", + value: function strictReceivePaths(source, destinationAsset, destinationAmount) { + return new StrictReceivePathCallBuilder(URI_default()(this.serverURL), source, destinationAsset, destinationAmount); + } + }, { + key: "strictSendPaths", + value: function strictSendPaths(sourceAsset, sourceAmount, destination) { + return new StrictSendPathCallBuilder(URI_default()(this.serverURL), sourceAsset, sourceAmount, destination); + } + }, { + key: "payments", + value: function payments() { + return new PaymentCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "effects", + value: function effects() { + return new EffectCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "friendbot", + value: function friendbot(address) { + return new FriendbotBuilder(URI_default()(this.serverURL), address); + } + }, { + key: "assets", + value: function assets() { + return new AssetsCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "loadAccount", + value: (function () { + var _loadAccount = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee7(accountId) { + var res; + return server_regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.accounts().accountId(accountId).call(); + case 2: + res = _context7.sent; + return _context7.abrupt("return", new AccountResponse(res)); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function loadAccount(_x4) { + return _loadAccount.apply(this, arguments); + } + return loadAccount; + }()) + }, { + key: "tradeAggregation", + value: function tradeAggregation(base, counter, start_time, end_time, resolution, offset) { + return new TradeAggregationCallBuilder(URI_default()(this.serverURL), base, counter, start_time, end_time, resolution, offset); + } + }, { + key: "checkMemoRequired", + value: (function () { + var _checkMemoRequired = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee8(transaction) { + var destinations, i, operation, destination, account; + return server_regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (transaction instanceof lib.FeeBumpTransaction) { + transaction = transaction.innerTransaction; + } + if (!(transaction.memo.type !== "none")) { + _context8.next = 3; + break; + } + return _context8.abrupt("return"); + case 3: + destinations = new Set(); + i = 0; + case 5: + if (!(i < transaction.operations.length)) { + _context8.next = 36; + break; + } + operation = transaction.operations[i]; + _context8.t0 = operation.type; + _context8.next = _context8.t0 === "payment" ? 10 : _context8.t0 === "pathPaymentStrictReceive" ? 10 : _context8.t0 === "pathPaymentStrictSend" ? 10 : _context8.t0 === "accountMerge" ? 10 : 11; + break; + case 10: + return _context8.abrupt("break", 12); + case 11: + return _context8.abrupt("continue", 33); + case 12: + destination = operation.destination; + if (!destinations.has(destination)) { + _context8.next = 15; + break; + } + return _context8.abrupt("continue", 33); + case 15: + destinations.add(destination); + if (!destination.startsWith("M")) { + _context8.next = 18; + break; + } + return _context8.abrupt("continue", 33); + case 18: + _context8.prev = 18; + _context8.next = 21; + return this.loadAccount(destination); + case 21: + account = _context8.sent; + if (!(account.data_attr["config.memo_required"] === ACCOUNT_REQUIRES_MEMO)) { + _context8.next = 24; + break; + } + throw new errors/* AccountRequiresMemoError */.Cu("account requires memo", destination, i); + case 24: + _context8.next = 33; + break; + case 26: + _context8.prev = 26; + _context8.t1 = _context8["catch"](18); + if (!(_context8.t1 instanceof errors/* AccountRequiresMemoError */.Cu)) { + _context8.next = 30; + break; + } + throw _context8.t1; + case 30: + if (_context8.t1 instanceof errors/* NotFoundError */.m_) { + _context8.next = 32; + break; + } + throw _context8.t1; + case 32: + return _context8.abrupt("continue", 33); + case 33: + i += 1; + _context8.next = 5; + break; + case 36: + case "end": + return _context8.stop(); + } + }, _callee8, this, [[18, 26]]); + })); + function checkMemoRequired(_x5) { + return _checkMemoRequired.apply(this, arguments); + } + return checkMemoRequired; + }()) + }]); +}(); +;// ./src/horizon/index.ts +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + +/* harmony default export */ const horizon = (module.exports); + +/***/ }), + +/***/ 8920: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + create: () => (/* binding */ createFetchClient), + fetchClient: () => (/* binding */ fetchClient) +}); + +;// ./node_modules/feaxios/dist/index.mjs +// src/client.ts +async function prepareAxiosResponse(options, res) { + const response = { config: options }; + response.status = res.status; + response.statusText = res.statusText; + response.headers = res.headers; + if (options.responseType === "stream") { + response.data = res.body; + return response; + } + return res[options.responseType || "text"]().then((data) => { + if (options.transformResponse) { + Array.isArray(options.transformResponse) ? options.transformResponse.map( + (fn) => data = fn.call(options, data, res?.headers, res?.status) + ) : data = options.transformResponse(data, res?.headers, res?.status); + response.data = data; + } else { + response.data = data; + response.data = JSON.parse(data); + } + }).catch(Object).then(() => response); +} +async function handleFetch(options, fetchOptions) { + let res = null; + if ("any" in AbortSignal) { + const signals = []; + if (options.timeout) { + signals.push(AbortSignal.timeout(options.timeout)); + } + if (options.signal) { + signals.push(options.signal); + } + if (signals.length > 0) { + fetchOptions.signal = AbortSignal.any(signals); + } + } else { + if (options.timeout) { + fetchOptions.signal = AbortSignal.timeout(options.timeout); + } + } + try { + res = await fetch(options.url, fetchOptions); + const ok = options.validateStatus ? options.validateStatus(res.status) : res.ok; + if (!ok) { + return Promise.reject( + new AxiosError( + `Request failed with status code ${res?.status}`, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(res?.status / 100) - 4], + options, + new Request(options.url, fetchOptions), + await prepareAxiosResponse(options, res) + ) + ); + } + return await prepareAxiosResponse(options, res); + } catch (error) { + if (error.name === "AbortError" || error.name === "TimeoutError") { + const isTimeoutError = error.name === "TimeoutError"; + return Promise.reject( + isTimeoutError ? new AxiosError( + options.timeoutErrorMessage || `timeout of ${options.timeout} ms exceeded`, + AxiosError.ECONNABORTED, + options, + request + ) : new CanceledError(null, options) + ); + } + return Promise.reject( + new AxiosError( + error.message, + void 0, + options, + request, + void 0 + ) + ); + } +} +function buildURL(options) { + let url = options.url || ""; + if (options.baseURL && options.url) { + url = options.url.replace(/^(?!.*\/\/)\/?/, `${options.baseURL}/`); + } + if (options.params && Object.keys(options.params).length > 0 && options.url) { + url += (~options.url.indexOf("?") ? "&" : "?") + (options.paramsSerializer ? options.paramsSerializer(options.params) : new URLSearchParams(options.params)); + } + return url; +} +function mergeAxiosOptions(input, defaults) { + const merged = { + ...defaults, + ...input + }; + if (defaults?.params && input?.params) { + merged.params = { + ...defaults?.params, + ...input?.params + }; + } + if (defaults?.headers && input?.headers) { + merged.headers = new Headers(defaults.headers || {}); + const headers = new Headers(input.headers || {}); + headers.forEach((value, key) => { + merged.headers.set(key, value); + }); + } + return merged; +} +function mergeFetchOptions(input, defaults) { + const merged = { + ...defaults, + ...input + }; + if (defaults?.headers && input?.headers) { + merged.headers = new Headers(defaults.headers || {}); + const headers = new Headers(input.headers || {}); + headers.forEach((value, key) => { + merged.headers.set(key, value); + }); + } + return merged; +} +function defaultTransformer(data, headers) { + const contentType = headers.get("content-type"); + if (!contentType) { + if (typeof data === "string") { + headers.set("content-type", "text/plain"); + } else if (data instanceof URLSearchParams) { + headers.set("content-type", "application/x-www-form-urlencoded"); + } else if (data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data)) { + headers.set("content-type", "application/octet-stream"); + } else if (typeof data === "object" && typeof data.append !== "function" && typeof data.text !== "function") { + data = JSON.stringify(data); + headers.set("content-type", "application/json"); + } + } else { + if (contentType === "application/x-www-form-urlencoded" && !(data instanceof URLSearchParams)) { + data = new URLSearchParams(data); + } else if (contentType === "application/json" && typeof data === "object") { + data = JSON.stringify(data); + } + } + return data; +} +async function request(configOrUrl, config, defaults, method, interceptors, data) { + if (typeof configOrUrl === "string") { + config = config || {}; + config.url = configOrUrl; + } else + config = configOrUrl || {}; + const options = mergeAxiosOptions(config, defaults || {}); + options.fetchOptions = options.fetchOptions || {}; + options.timeout = options.timeout || 0; + options.headers = new Headers(options.headers || {}); + options.transformRequest = options.transformRequest ?? defaultTransformer; + data = data || options.data; + if (options.transformRequest && data) { + Array.isArray(options.transformRequest) ? options.transformRequest.map( + (fn) => data = fn.call(options, data, options.headers) + ) : data = options.transformRequest(data, options.headers); + } + options.url = buildURL(options); + options.method = method || options.method || "get"; + if (interceptors && interceptors.request.handlers.length > 0) { + const chain = interceptors.request.handlers.filter( + (interceptor) => !interceptor?.runWhen || typeof interceptor.runWhen === "function" && interceptor.runWhen(options) + ).flatMap((interceptor) => [interceptor.fulfilled, interceptor.rejected]); + let result = options; + for (let i = 0, len = chain.length; i < len; i += 2) { + const onFulfilled = chain[i]; + const onRejected = chain[i + 1]; + try { + if (onFulfilled) + result = onFulfilled(result); + } catch (error) { + if (onRejected) + onRejected?.(error); + break; + } + } + } + const init = mergeFetchOptions( + { + method: options.method?.toUpperCase(), + body: data, + headers: options.headers, + credentials: options.withCredentials ? "include" : void 0, + signal: options.signal + }, + options.fetchOptions + ); + let resp = handleFetch(options, init); + if (interceptors && interceptors.response.handlers.length > 0) { + const chain = interceptors.response.handlers.flatMap((interceptor) => [ + interceptor.fulfilled, + interceptor.rejected + ]); + for (let i = 0, len = chain.length; i < len; i += 2) { + resp = resp.then(chain[i], chain[i + 1]); + } + } + return resp; +} +var AxiosInterceptorManager = class { + handlers = []; + constructor() { + this.handlers = []; + } + use = (onFulfilled, onRejected, options) => { + this.handlers.push({ + fulfilled: onFulfilled, + rejected: onRejected, + runWhen: options?.runWhen + }); + return this.handlers.length - 1; + }; + eject = (id) => { + if (this.handlers[id]) { + this.handlers[id] = null; + } + }; + clear = () => { + this.handlers = []; + }; +}; +function createAxiosInstance(defaults) { + defaults = defaults || {}; + const interceptors = { + request: new AxiosInterceptorManager(), + response: new AxiosInterceptorManager() + }; + const axios2 = (url, config) => request(url, config, defaults, void 0, interceptors); + axios2.defaults = defaults; + axios2.interceptors = interceptors; + axios2.getUri = (config) => { + const merged = mergeAxiosOptions(config || {}, defaults); + return buildURL(merged); + }; + axios2.request = (config) => request(config, void 0, defaults, void 0, interceptors); + ["get", "delete", "head", "options"].forEach((method) => { + axios2[method] = (url, config) => request(url, config, defaults, method, interceptors); + }); + ["post", "put", "patch"].forEach((method) => { + axios2[method] = (url, data, config) => request(url, config, defaults, method, interceptors, data); + }); + ["postForm", "putForm", "patchForm"].forEach((method) => { + axios2[method] = (url, data, config) => { + config = config || {}; + config.headers = new Headers(config.headers || {}); + config.headers.set("content-type", "application/x-www-form-urlencoded"); + return request( + url, + config, + defaults, + method.replace("Form", ""), + interceptors, + data + ); + }; + }); + return axios2; +} +var AxiosError = class extends Error { + config; + code; + request; + response; + status; + isAxiosError; + constructor(message, code, config, request2, response) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack; + } + this.name = "AxiosError"; + this.code = code; + this.config = config; + this.request = request2; + this.response = response; + this.isAxiosError = true; + } + static ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE"; + static ERR_BAD_OPTION = "ERR_BAD_OPTION"; + static ERR_NETWORK = "ERR_NETWORK"; + static ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE"; + static ERR_BAD_REQUEST = "ERR_BAD_REQUEST"; + static ERR_INVALID_URL = "ERR_INVALID_URL"; + static ERR_CANCELED = "ERR_CANCELED"; + static ECONNABORTED = "ECONNABORTED"; + static ETIMEDOUT = "ETIMEDOUT"; +}; +var CanceledError = class extends AxiosError { + constructor(message, config, request2) { + super( + !message ? "canceled" : message, + AxiosError.ERR_CANCELED, + config, + request2 + ); + this.name = "CanceledError"; + } +}; +function isAxiosError(payload) { + return payload !== null && typeof payload === "object" && payload.isAxiosError; +} +var axios = createAxiosInstance(); +axios.create = (defaults) => createAxiosInstance(defaults); + +// src/index.ts +var src_default = axios; + + + +// EXTERNAL MODULE: ./src/http-client/types.ts +var types = __webpack_require__(5798); +;// ./src/http-client/fetch-client.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + +var InterceptorManager = function () { + function InterceptorManager() { + _classCallCheck(this, InterceptorManager); + _defineProperty(this, "handlers", []); + } + return _createClass(InterceptorManager, [{ + key: "use", + value: function use(fulfilled, rejected) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected + }); + return this.handlers.length - 1; + } + }, { + key: "eject", + value: function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + }, { + key: "forEach", + value: function forEach(fn) { + this.handlers.forEach(function (h) { + if (h !== null) { + fn(h); + } + }); + } + }]); +}(); +function getFormConfig(config) { + var formConfig = config || {}; + formConfig.headers = new Headers(formConfig.headers || {}); + formConfig.headers.set('Content-Type', 'application/x-www-form-urlencoded'); + return formConfig; +} +function createFetchClient() { + var fetchConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var defaults = _objectSpread(_objectSpread({}, fetchConfig), {}, { + headers: fetchConfig.headers || {} + }); + var instance = src_default.create(defaults); + var requestInterceptors = new InterceptorManager(); + var responseInterceptors = new InterceptorManager(); + var httpClient = { + interceptors: { + request: requestInterceptors, + response: responseInterceptors + }, + defaults: _objectSpread(_objectSpread({}, defaults), {}, { + adapter: function adapter(config) { + return instance.request(config); + } + }), + create: function create(config) { + return createFetchClient(_objectSpread(_objectSpread({}, this.defaults), config)); + }, + makeRequest: function makeRequest(config) { + var _this = this; + return new Promise(function (resolve, reject) { + var abortController = new AbortController(); + config.signal = abortController.signal; + if (config.cancelToken) { + config.cancelToken.promise.then(function () { + abortController.abort(); + reject(new Error('Request canceled')); + }); + } + var modifiedConfig = config; + if (requestInterceptors.handlers.length > 0) { + var chain = requestInterceptors.handlers.filter(function (interceptor) { + return interceptor !== null; + }).flatMap(function (interceptor) { + return [interceptor.fulfilled, interceptor.rejected]; + }); + for (var i = 0, len = chain.length; i < len; i += 2) { + var onFulfilled = chain[i]; + var onRejected = chain[i + 1]; + try { + if (onFulfilled) modifiedConfig = onFulfilled(modifiedConfig); + } catch (error) { + if (onRejected) onRejected === null || onRejected === void 0 || onRejected(error); + reject(error); + return; + } + } + } + var adapter = modifiedConfig.adapter || _this.defaults.adapter; + if (!adapter) { + throw new Error('No adapter available'); + } + var responsePromise = adapter(modifiedConfig).then(function (axiosResponse) { + var httpClientResponse = { + data: axiosResponse.data, + headers: axiosResponse.headers, + config: axiosResponse.config, + status: axiosResponse.status, + statusText: axiosResponse.statusText + }; + return httpClientResponse; + }); + if (responseInterceptors.handlers.length > 0) { + var _chain = responseInterceptors.handlers.filter(function (interceptor) { + return interceptor !== null; + }).flatMap(function (interceptor) { + return [interceptor.fulfilled, interceptor.rejected]; + }); + var _loop = function _loop(_i) { + responsePromise = responsePromise.then(function (response) { + var fulfilledInterceptor = _chain[_i]; + if (typeof fulfilledInterceptor === 'function') { + return fulfilledInterceptor(response); + } + return response; + }, function (error) { + var rejectedInterceptor = _chain[_i + 1]; + if (typeof rejectedInterceptor === 'function') { + return rejectedInterceptor(error); + } + throw error; + }).then(function (interceptedResponse) { + return interceptedResponse; + }); + }; + for (var _i = 0, _len = _chain.length; _i < _len; _i += 2) { + _loop(_i); + } + } + responsePromise.then(resolve).catch(reject); + }); + }, + get: function get(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'get' + })); + }, + delete: function _delete(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'delete' + })); + }, + head: function head(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'head' + })); + }, + options: function options(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'options' + })); + }, + post: function post(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'post', + data: data + })); + }, + put: function put(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'put', + data: data + })); + }, + patch: function patch(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'patch', + data: data + })); + }, + postForm: function postForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'post', + data: data + })); + }, + putForm: function putForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'put', + data: data + })); + }, + patchForm: function patchForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'patch', + data: data + })); + }, + CancelToken: types/* CancelToken */.q, + isCancel: function isCancel(value) { + return value instanceof Error && value.message === 'Request canceled'; + } + }; + return httpClient; +} +var fetchClient = createFetchClient(); + + +/***/ }), + +/***/ 6371: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ ok: () => (/* binding */ httpClient), +/* harmony export */ vt: () => (/* binding */ create) +/* harmony export */ }); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5798); +var httpClient; +var create; +if (false) { var axiosModule; } else { + var fetchModule = __webpack_require__(8920); + httpClient = fetchModule.fetchClient; + create = fetchModule.create; +} + + + +/***/ }), + +/***/ 5798: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ q: () => (/* binding */ CancelToken) +/* harmony export */ }); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var CancelToken = function () { + function CancelToken(executor) { + var _this = this; + _classCallCheck(this, CancelToken); + var resolvePromise; + this.promise = new Promise(function (resolve) { + resolvePromise = resolve; + }); + executor(function (reason) { + _this.reason = reason; + resolvePromise(); + }); + } + return _createClass(CancelToken, [{ + key: "throwIfRequested", + value: function throwIfRequested() { + if (this.reason) { + throw new Error(this.reason); + } + } + }]); +}(); + +/***/ }), + +/***/ 4356: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ AccountRequiresMemoError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.Cu), +/* harmony export */ BadRequestError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.v7), +/* harmony export */ BadResponseError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.nS), +/* harmony export */ Config: () => (/* reexport safe */ _config__WEBPACK_IMPORTED_MODULE_1__.T), +/* harmony export */ Federation: () => (/* reexport module object */ _federation__WEBPACK_IMPORTED_MODULE_4__), +/* harmony export */ Friendbot: () => (/* reexport module object */ _friendbot__WEBPACK_IMPORTED_MODULE_6__), +/* harmony export */ Horizon: () => (/* reexport module object */ _horizon__WEBPACK_IMPORTED_MODULE_7__), +/* harmony export */ NetworkError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.Dr), +/* harmony export */ NotFoundError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.m_), +/* harmony export */ StellarToml: () => (/* reexport module object */ _stellartoml__WEBPACK_IMPORTED_MODULE_3__), +/* harmony export */ Utils: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_2__.A), +/* harmony export */ WebAuth: () => (/* reexport module object */ _webauth__WEBPACK_IMPORTED_MODULE_5__), +/* harmony export */ contract: () => (/* reexport module object */ _contract__WEBPACK_IMPORTED_MODULE_9__), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ rpc: () => (/* reexport module object */ _rpc__WEBPACK_IMPORTED_MODULE_8__) +/* harmony export */ }); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5976); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8732); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3121); +/* harmony import */ var _stellartoml__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3898); +/* harmony import */ var _federation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7600); +/* harmony import */ var _webauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(5479); +/* harmony import */ var _friendbot__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(8242); +/* harmony import */ var _horizon__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(8733); +/* harmony import */ var _rpc__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(3496); +/* harmony import */ var _contract__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(6299); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__); +/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {}; +/* harmony reexport (unknown) */ for(const __WEBPACK_IMPORT_KEY__ in _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__) if(["default","Config","Utils","StellarToml","Federation","WebAuth","Friendbot","Horizon","rpc","contract","AccountRequiresMemoError","BadRequestError","BadResponseError","NetworkError","NotFoundError"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = () => _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__[__WEBPACK_IMPORT_KEY__] +/* harmony reexport (unknown) */ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__); +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + + + + + + + + + + + + + + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (module.exports); +if (typeof __webpack_require__.g.__USE_AXIOS__ === 'undefined') { + __webpack_require__.g.__USE_AXIOS__ = true; +} +if (typeof __webpack_require__.g.__USE_EVENTSOURCE__ === 'undefined') { + __webpack_require__.g.__USE_EVENTSOURCE__ = false; +} + +/***/ }), + +/***/ 4076: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ j: () => (/* binding */ Api) +/* harmony export */ }); +var Api; +(function (_Api) { + var GetTransactionStatus = function (GetTransactionStatus) { + GetTransactionStatus["SUCCESS"] = "SUCCESS"; + GetTransactionStatus["NOT_FOUND"] = "NOT_FOUND"; + GetTransactionStatus["FAILED"] = "FAILED"; + return GetTransactionStatus; + }({}); + _Api.GetTransactionStatus = GetTransactionStatus; + function isSimulationError(sim) { + return 'error' in sim; + } + _Api.isSimulationError = isSimulationError; + function isSimulationSuccess(sim) { + return 'transactionData' in sim; + } + _Api.isSimulationSuccess = isSimulationSuccess; + function isSimulationRestore(sim) { + return isSimulationSuccess(sim) && 'restorePreamble' in sim && !!sim.restorePreamble.transactionData; + } + _Api.isSimulationRestore = isSimulationRestore; + function isSimulationRaw(sim) { + return !sim._parsed; + } + _Api.isSimulationRaw = isSimulationRaw; +})(Api || (Api = {})); + +/***/ }), + +/***/ 3496: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Api: () => (/* reexport */ api/* Api */.j), + AxiosClient: () => (/* reexport */ axios), + BasicSleepStrategy: () => (/* reexport */ BasicSleepStrategy), + Durability: () => (/* reexport */ Durability), + LinearSleepStrategy: () => (/* reexport */ LinearSleepStrategy), + Server: () => (/* reexport */ RpcServer), + assembleTransaction: () => (/* reexport */ transaction/* assembleTransaction */.X), + "default": () => (/* binding */ rpc), + parseRawEvents: () => (/* reexport */ parsers/* parseRawEvents */.fG), + parseRawSimulation: () => (/* reexport */ parsers/* parseRawSimulation */.jr) +}); + +// EXTERNAL MODULE: ./src/rpc/api.ts +var api = __webpack_require__(4076); +// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js +var URI = __webpack_require__(4193); +var URI_default = /*#__PURE__*/__webpack_require__.n(URI); +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./src/http-client/index.ts +var http_client = __webpack_require__(6371); +;// ./src/rpc/axios.ts + +var version = "13.1.0"; +var AxiosClient = (0,http_client/* create */.vt)({ + headers: { + 'X-Client-Name': 'js-soroban-client', + 'X-Client-Version': version + } +}); +/* harmony default export */ const axios = (AxiosClient); +;// ./src/rpc/jsonrpc.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + +function jsonrpc_hasOwnProperty(obj, prop) { + return obj.hasOwnProperty(prop); +} +function postObject(_x, _x2) { + return _postObject.apply(this, arguments); +} +function _postObject() { + _postObject = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(url, method) { + var param, + response, + _response$data, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + param = _args.length > 2 && _args[2] !== undefined ? _args[2] : null; + _context.next = 3; + return axios.post(url, { + jsonrpc: "2.0", + id: 1, + method: method, + params: param + }); + case 3: + response = _context.sent; + if (!jsonrpc_hasOwnProperty(response.data, "error")) { + _context.next = 8; + break; + } + throw response.data.error; + case 8: + return _context.abrupt("return", (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.result); + case 9: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _postObject.apply(this, arguments); +} +// EXTERNAL MODULE: ./src/rpc/transaction.ts +var transaction = __webpack_require__(8680); +// EXTERNAL MODULE: ./src/rpc/parsers.ts +var parsers = __webpack_require__(784); +// EXTERNAL MODULE: ./src/utils.ts +var utils = __webpack_require__(3121); +;// ./src/rpc/server.ts +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +function server_typeof(o) { "@babel/helpers - typeof"; return server_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, server_typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function server_regeneratorRuntime() { "use strict"; server_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == server_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(server_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function server_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function server_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == server_typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != server_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != server_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + + + +var SUBMIT_TRANSACTION_TIMEOUT = (/* unused pure expression or super */ null && (60 * 1000)); +var Durability = function (Durability) { + Durability["Temporary"] = "temporary"; + Durability["Persistent"] = "persistent"; + return Durability; +}({}); +var DEFAULT_GET_TRANSACTION_TIMEOUT = 30; +var BasicSleepStrategy = function BasicSleepStrategy(_iter) { + return 1000; +}; +var LinearSleepStrategy = function LinearSleepStrategy(iter) { + return 1000 * iter; +}; +function findCreatedAccountSequenceInTransactionMeta(meta) { + var _operations$flatMap$f; + var operations = []; + switch (meta.switch()) { + case 0: + operations = meta.operations(); + break; + case 1: + case 2: + case 3: + operations = meta.value().operations(); + break; + default: + throw new Error('Unexpected transaction meta switch value'); + } + var sequenceNumber = (_operations$flatMap$f = operations.flatMap(function (op) { + return op.changes(); + }).find(function (c) { + return c.switch() === lib.xdr.LedgerEntryChangeType.ledgerEntryCreated() && c.created().data().switch() === lib.xdr.LedgerEntryType.account(); + })) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.created()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.data()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.account()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.seqNum()) === null || _operations$flatMap$f === void 0 ? void 0 : _operations$flatMap$f.toString(); + if (sequenceNumber) { + return sequenceNumber; + } + throw new Error('No account created in transaction'); +} +var RpcServer = function () { + function RpcServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, RpcServer); + this.serverURL = URI_default()(serverURL); + if (opts.headers && Object.keys(opts.headers).length !== 0) { + axios.interceptors.request.use(function (config) { + config.headers = Object.assign(config.headers, opts.headers); + return config; + }); + } + if (this.serverURL.protocol() !== 'https' && !opts.allowHttp) { + throw new Error("Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set"); + } + } + return _createClass(RpcServer, [{ + key: "getAccount", + value: (function () { + var _getAccount = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee(address) { + var ledgerKey, resp, accountEntry; + return server_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + ledgerKey = lib.xdr.LedgerKey.account(new lib.xdr.LedgerKeyAccount({ + accountId: lib.Keypair.fromPublicKey(address).xdrPublicKey() + })); + _context.next = 3; + return this.getLedgerEntries(ledgerKey); + case 3: + resp = _context.sent; + if (!(resp.entries.length === 0)) { + _context.next = 6; + break; + } + return _context.abrupt("return", Promise.reject({ + code: 404, + message: "Account not found: ".concat(address) + })); + case 6: + accountEntry = resp.entries[0].val.account(); + return _context.abrupt("return", new lib.Account(address, accountEntry.seqNum().toString())); + case 8: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function getAccount(_x) { + return _getAccount.apply(this, arguments); + } + return getAccount; + }()) + }, { + key: "getHealth", + value: (function () { + var _getHealth = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee2() { + return server_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", postObject(this.serverURL.toString(), 'getHealth')); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function getHealth() { + return _getHealth.apply(this, arguments); + } + return getHealth; + }()) + }, { + key: "getContractData", + value: (function () { + var _getContractData = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee3(contract, key) { + var durability, + scAddress, + xdrDurability, + contractKey, + _args3 = arguments; + return server_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + durability = _args3.length > 2 && _args3[2] !== undefined ? _args3[2] : Durability.Persistent; + if (!(typeof contract === 'string')) { + _context3.next = 5; + break; + } + scAddress = new lib.Contract(contract).address().toScAddress(); + _context3.next = 14; + break; + case 5: + if (!(contract instanceof lib.Address)) { + _context3.next = 9; + break; + } + scAddress = contract.toScAddress(); + _context3.next = 14; + break; + case 9: + if (!(contract instanceof lib.Contract)) { + _context3.next = 13; + break; + } + scAddress = contract.address().toScAddress(); + _context3.next = 14; + break; + case 13: + throw new TypeError("unknown contract type: ".concat(contract)); + case 14: + _context3.t0 = durability; + _context3.next = _context3.t0 === Durability.Temporary ? 17 : _context3.t0 === Durability.Persistent ? 19 : 21; + break; + case 17: + xdrDurability = lib.xdr.ContractDataDurability.temporary(); + return _context3.abrupt("break", 22); + case 19: + xdrDurability = lib.xdr.ContractDataDurability.persistent(); + return _context3.abrupt("break", 22); + case 21: + throw new TypeError("invalid durability: ".concat(durability)); + case 22: + contractKey = lib.xdr.LedgerKey.contractData(new lib.xdr.LedgerKeyContractData({ + key: key, + contract: scAddress, + durability: xdrDurability + })); + return _context3.abrupt("return", this.getLedgerEntries(contractKey).then(function (r) { + if (r.entries.length === 0) { + return Promise.reject({ + code: 404, + message: "Contract data not found. Contract: ".concat(lib.Address.fromScAddress(scAddress).toString(), ", Key: ").concat(key.toXDR('base64'), ", Durability: ").concat(durability) + }); + } + return r.entries[0]; + })); + case 24: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function getContractData(_x2, _x3) { + return _getContractData.apply(this, arguments); + } + return getContractData; + }()) + }, { + key: "getContractWasmByContractId", + value: (function () { + var _getContractWasmByContractId = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee4(contractId) { + var _response$entries$; + var contractLedgerKey, response, wasmHash; + return server_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + contractLedgerKey = new lib.Contract(contractId).getFootprint(); + _context4.next = 3; + return this.getLedgerEntries(contractLedgerKey); + case 3: + response = _context4.sent; + if (!(!response.entries.length || !((_response$entries$ = response.entries[0]) !== null && _response$entries$ !== void 0 && _response$entries$.val))) { + _context4.next = 6; + break; + } + return _context4.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract hash from server" + })); + case 6: + wasmHash = response.entries[0].val.contractData().val().instance().executable().wasmHash(); + return _context4.abrupt("return", this.getContractWasmByHash(wasmHash)); + case 8: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function getContractWasmByContractId(_x4) { + return _getContractWasmByContractId.apply(this, arguments); + } + return getContractWasmByContractId; + }()) + }, { + key: "getContractWasmByHash", + value: (function () { + var _getContractWasmByHash = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee5(wasmHash) { + var _responseWasm$entries; + var format, + wasmHashBuffer, + ledgerKeyWasmHash, + responseWasm, + wasmBuffer, + _args5 = arguments; + return server_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + format = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : undefined; + wasmHashBuffer = typeof wasmHash === "string" ? Buffer.from(wasmHash, format) : wasmHash; + ledgerKeyWasmHash = lib.xdr.LedgerKey.contractCode(new lib.xdr.LedgerKeyContractCode({ + hash: wasmHashBuffer + })); + _context5.next = 5; + return this.getLedgerEntries(ledgerKeyWasmHash); + case 5: + responseWasm = _context5.sent; + if (!(!responseWasm.entries.length || !((_responseWasm$entries = responseWasm.entries[0]) !== null && _responseWasm$entries !== void 0 && _responseWasm$entries.val))) { + _context5.next = 8; + break; + } + return _context5.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract wasm from server" + })); + case 8: + wasmBuffer = responseWasm.entries[0].val.contractCode().code(); + return _context5.abrupt("return", wasmBuffer); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function getContractWasmByHash(_x5) { + return _getContractWasmByHash.apply(this, arguments); + } + return getContractWasmByHash; + }()) + }, { + key: "getLedgerEntries", + value: (function () { + var _getLedgerEntries2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee6() { + var _args6 = arguments; + return server_regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + return _context6.abrupt("return", this._getLedgerEntries.apply(this, _args6).then(parsers/* parseRawLedgerEntries */.$D)); + case 1: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function getLedgerEntries() { + return _getLedgerEntries2.apply(this, arguments); + } + return getLedgerEntries; + }()) + }, { + key: "_getLedgerEntries", + value: function () { + var _getLedgerEntries3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee7() { + var _len, + keys, + _key, + _args7 = arguments; + return server_regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + for (_len = _args7.length, keys = new Array(_len), _key = 0; _key < _len; _key++) { + keys[_key] = _args7[_key]; + } + return _context7.abrupt("return", postObject(this.serverURL.toString(), 'getLedgerEntries', { + keys: keys.map(function (k) { + return k.toXDR('base64'); + }) + })); + case 2: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function _getLedgerEntries() { + return _getLedgerEntries3.apply(this, arguments); + } + return _getLedgerEntries; + }() + }, { + key: "pollTransaction", + value: (function () { + var _pollTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee8(hash, opts) { + var _opts$attempts, _opts$attempts2; + var maxAttempts, foundInfo, attempt, _opts$sleepStrategy; + return server_regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + maxAttempts = ((_opts$attempts = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts !== void 0 ? _opts$attempts : 0) < 1 ? DEFAULT_GET_TRANSACTION_TIMEOUT : (_opts$attempts2 = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts2 !== void 0 ? _opts$attempts2 : DEFAULT_GET_TRANSACTION_TIMEOUT; + attempt = 1; + case 2: + if (!(attempt < maxAttempts)) { + _context8.next = 13; + break; + } + _context8.next = 5; + return this.getTransaction(hash); + case 5: + foundInfo = _context8.sent; + if (!(foundInfo.status !== api/* Api */.j.GetTransactionStatus.NOT_FOUND)) { + _context8.next = 8; + break; + } + return _context8.abrupt("return", foundInfo); + case 8: + _context8.next = 10; + return utils/* Utils */.A.sleep(((_opts$sleepStrategy = opts === null || opts === void 0 ? void 0 : opts.sleepStrategy) !== null && _opts$sleepStrategy !== void 0 ? _opts$sleepStrategy : BasicSleepStrategy)(attempt)); + case 10: + attempt++; + _context8.next = 2; + break; + case 13: + return _context8.abrupt("return", foundInfo); + case 14: + case "end": + return _context8.stop(); + } + }, _callee8, this); + })); + function pollTransaction(_x6, _x7) { + return _pollTransaction.apply(this, arguments); + } + return pollTransaction; + }()) + }, { + key: "getTransaction", + value: (function () { + var _getTransaction2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee9(hash) { + return server_regeneratorRuntime().wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + return _context9.abrupt("return", this._getTransaction(hash).then(function (raw) { + var foundInfo = {}; + if (raw.status !== api/* Api */.j.GetTransactionStatus.NOT_FOUND) { + Object.assign(foundInfo, (0,parsers/* parseTransactionInfo */.WC)(raw)); + } + var result = _objectSpread({ + status: raw.status, + txHash: hash, + latestLedger: raw.latestLedger, + latestLedgerCloseTime: raw.latestLedgerCloseTime, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTime: raw.oldestLedgerCloseTime + }, foundInfo); + return result; + })); + case 1: + case "end": + return _context9.stop(); + } + }, _callee9, this); + })); + function getTransaction(_x8) { + return _getTransaction2.apply(this, arguments); + } + return getTransaction; + }()) + }, { + key: "_getTransaction", + value: function () { + var _getTransaction3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee10(hash) { + return server_regeneratorRuntime().wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + return _context10.abrupt("return", postObject(this.serverURL.toString(), 'getTransaction', { + hash: hash + })); + case 1: + case "end": + return _context10.stop(); + } + }, _callee10, this); + })); + function _getTransaction(_x9) { + return _getTransaction3.apply(this, arguments); + } + return _getTransaction; + }() + }, { + key: "getTransactions", + value: (function () { + var _getTransactions2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee11(request) { + return server_regeneratorRuntime().wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + return _context11.abrupt("return", this._getTransactions(request).then(function (raw) { + var result = { + transactions: raw.transactions.map(parsers/* parseRawTransactions */.tR), + latestLedger: raw.latestLedger, + latestLedgerCloseTimestamp: raw.latestLedgerCloseTimestamp, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTimestamp: raw.oldestLedgerCloseTimestamp, + cursor: raw.cursor + }; + return result; + })); + case 1: + case "end": + return _context11.stop(); + } + }, _callee11, this); + })); + function getTransactions(_x10) { + return _getTransactions2.apply(this, arguments); + } + return getTransactions; + }()) + }, { + key: "_getTransactions", + value: function () { + var _getTransactions3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee12(request) { + return server_regeneratorRuntime().wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + return _context12.abrupt("return", postObject(this.serverURL.toString(), 'getTransactions', request)); + case 1: + case "end": + return _context12.stop(); + } + }, _callee12, this); + })); + function _getTransactions(_x11) { + return _getTransactions3.apply(this, arguments); + } + return _getTransactions; + }() + }, { + key: "getEvents", + value: (function () { + var _getEvents2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee13(request) { + return server_regeneratorRuntime().wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + return _context13.abrupt("return", this._getEvents(request).then(parsers/* parseRawEvents */.fG)); + case 1: + case "end": + return _context13.stop(); + } + }, _callee13, this); + })); + function getEvents(_x12) { + return _getEvents2.apply(this, arguments); + } + return getEvents; + }()) + }, { + key: "_getEvents", + value: function () { + var _getEvents3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee14(request) { + var _request$filters; + return server_regeneratorRuntime().wrap(function _callee14$(_context14) { + while (1) switch (_context14.prev = _context14.next) { + case 0: + return _context14.abrupt("return", postObject(this.serverURL.toString(), 'getEvents', _objectSpread(_objectSpread({ + filters: (_request$filters = request.filters) !== null && _request$filters !== void 0 ? _request$filters : [], + pagination: _objectSpread(_objectSpread({}, request.cursor && { + cursor: request.cursor + }), request.limit && { + limit: request.limit + }) + }, request.startLedger && { + startLedger: request.startLedger + }), request.endLedger && { + endLedger: request.endLedger + }))); + case 1: + case "end": + return _context14.stop(); + } + }, _callee14, this); + })); + function _getEvents(_x13) { + return _getEvents3.apply(this, arguments); + } + return _getEvents; + }() + }, { + key: "getNetwork", + value: (function () { + var _getNetwork = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee15() { + return server_regeneratorRuntime().wrap(function _callee15$(_context15) { + while (1) switch (_context15.prev = _context15.next) { + case 0: + return _context15.abrupt("return", postObject(this.serverURL.toString(), 'getNetwork')); + case 1: + case "end": + return _context15.stop(); + } + }, _callee15, this); + })); + function getNetwork() { + return _getNetwork.apply(this, arguments); + } + return getNetwork; + }()) + }, { + key: "getLatestLedger", + value: (function () { + var _getLatestLedger = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee16() { + return server_regeneratorRuntime().wrap(function _callee16$(_context16) { + while (1) switch (_context16.prev = _context16.next) { + case 0: + return _context16.abrupt("return", postObject(this.serverURL.toString(), 'getLatestLedger')); + case 1: + case "end": + return _context16.stop(); + } + }, _callee16, this); + })); + function getLatestLedger() { + return _getLatestLedger.apply(this, arguments); + } + return getLatestLedger; + }()) + }, { + key: "simulateTransaction", + value: (function () { + var _simulateTransaction2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee17(tx, addlResources) { + return server_regeneratorRuntime().wrap(function _callee17$(_context17) { + while (1) switch (_context17.prev = _context17.next) { + case 0: + return _context17.abrupt("return", this._simulateTransaction(tx, addlResources).then(parsers/* parseRawSimulation */.jr)); + case 1: + case "end": + return _context17.stop(); + } + }, _callee17, this); + })); + function simulateTransaction(_x14, _x15) { + return _simulateTransaction2.apply(this, arguments); + } + return simulateTransaction; + }()) + }, { + key: "_simulateTransaction", + value: function () { + var _simulateTransaction3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee18(transaction, addlResources) { + return server_regeneratorRuntime().wrap(function _callee18$(_context18) { + while (1) switch (_context18.prev = _context18.next) { + case 0: + return _context18.abrupt("return", postObject(this.serverURL.toString(), 'simulateTransaction', _objectSpread({ + transaction: transaction.toXDR() + }, addlResources !== undefined && { + resourceConfig: { + instructionLeeway: addlResources.cpuInstructions + } + }))); + case 1: + case "end": + return _context18.stop(); + } + }, _callee18, this); + })); + function _simulateTransaction(_x16, _x17) { + return _simulateTransaction3.apply(this, arguments); + } + return _simulateTransaction; + }() + }, { + key: "prepareTransaction", + value: (function () { + var _prepareTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee19(tx) { + var simResponse; + return server_regeneratorRuntime().wrap(function _callee19$(_context19) { + while (1) switch (_context19.prev = _context19.next) { + case 0: + _context19.next = 2; + return this.simulateTransaction(tx); + case 2: + simResponse = _context19.sent; + if (!api/* Api */.j.isSimulationError(simResponse)) { + _context19.next = 5; + break; + } + throw new Error(simResponse.error); + case 5: + return _context19.abrupt("return", (0,transaction/* assembleTransaction */.X)(tx, simResponse).build()); + case 6: + case "end": + return _context19.stop(); + } + }, _callee19, this); + })); + function prepareTransaction(_x18) { + return _prepareTransaction.apply(this, arguments); + } + return prepareTransaction; + }()) + }, { + key: "sendTransaction", + value: (function () { + var _sendTransaction2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee20(transaction) { + return server_regeneratorRuntime().wrap(function _callee20$(_context20) { + while (1) switch (_context20.prev = _context20.next) { + case 0: + return _context20.abrupt("return", this._sendTransaction(transaction).then(parsers/* parseRawSendTransaction */.Af)); + case 1: + case "end": + return _context20.stop(); + } + }, _callee20, this); + })); + function sendTransaction(_x19) { + return _sendTransaction2.apply(this, arguments); + } + return sendTransaction; + }()) + }, { + key: "_sendTransaction", + value: function () { + var _sendTransaction3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee21(transaction) { + return server_regeneratorRuntime().wrap(function _callee21$(_context21) { + while (1) switch (_context21.prev = _context21.next) { + case 0: + return _context21.abrupt("return", postObject(this.serverURL.toString(), 'sendTransaction', { + transaction: transaction.toXDR() + })); + case 1: + case "end": + return _context21.stop(); + } + }, _callee21, this); + })); + function _sendTransaction(_x20) { + return _sendTransaction3.apply(this, arguments); + } + return _sendTransaction; + }() + }, { + key: "requestAirdrop", + value: (function () { + var _requestAirdrop = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee22(address, friendbotUrl) { + var account, response, meta, txMeta, sequence, _error$response, _error$response$detai; + return server_regeneratorRuntime().wrap(function _callee22$(_context22) { + while (1) switch (_context22.prev = _context22.next) { + case 0: + account = typeof address === 'string' ? address : address.accountId(); + _context22.t0 = friendbotUrl; + if (_context22.t0) { + _context22.next = 6; + break; + } + _context22.next = 5; + return this.getNetwork(); + case 5: + _context22.t0 = _context22.sent.friendbotUrl; + case 6: + friendbotUrl = _context22.t0; + if (friendbotUrl) { + _context22.next = 9; + break; + } + throw new Error('No friendbot URL configured for current network'); + case 9: + _context22.prev = 9; + _context22.next = 12; + return axios.post("".concat(friendbotUrl, "?addr=").concat(encodeURIComponent(account))); + case 12: + response = _context22.sent; + if (response.data.result_meta_xdr) { + _context22.next = 22; + break; + } + _context22.next = 16; + return this.getTransaction(response.data.hash); + case 16: + txMeta = _context22.sent; + if (!(txMeta.status !== api/* Api */.j.GetTransactionStatus.SUCCESS)) { + _context22.next = 19; + break; + } + throw new Error("Funding account ".concat(address, " failed")); + case 19: + meta = txMeta.resultMetaXdr; + _context22.next = 23; + break; + case 22: + meta = lib.xdr.TransactionMeta.fromXDR(response.data.result_meta_xdr, 'base64'); + case 23: + sequence = findCreatedAccountSequenceInTransactionMeta(meta); + return _context22.abrupt("return", new lib.Account(account, sequence)); + case 27: + _context22.prev = 27; + _context22.t1 = _context22["catch"](9); + if (!(((_error$response = _context22.t1.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 400)) { + _context22.next = 32; + break; + } + if (!((_error$response$detai = _context22.t1.response.detail) !== null && _error$response$detai !== void 0 && _error$response$detai.includes('createAccountAlreadyExist'))) { + _context22.next = 32; + break; + } + return _context22.abrupt("return", this.getAccount(account)); + case 32: + throw _context22.t1; + case 33: + case "end": + return _context22.stop(); + } + }, _callee22, this, [[9, 27]]); + })); + function requestAirdrop(_x21, _x22) { + return _requestAirdrop.apply(this, arguments); + } + return requestAirdrop; + }()) + }, { + key: "getFeeStats", + value: (function () { + var _getFeeStats = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee23() { + return server_regeneratorRuntime().wrap(function _callee23$(_context23) { + while (1) switch (_context23.prev = _context23.next) { + case 0: + return _context23.abrupt("return", postObject(this.serverURL.toString(), 'getFeeStats')); + case 1: + case "end": + return _context23.stop(); + } + }, _callee23, this); + })); + function getFeeStats() { + return _getFeeStats.apply(this, arguments); + } + return getFeeStats; + }()) + }, { + key: "getVersionInfo", + value: (function () { + var _getVersionInfo = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee24() { + return server_regeneratorRuntime().wrap(function _callee24$(_context24) { + while (1) switch (_context24.prev = _context24.next) { + case 0: + return _context24.abrupt("return", postObject(this.serverURL.toString(), 'getVersionInfo')); + case 1: + case "end": + return _context24.stop(); + } + }, _callee24, this); + })); + function getVersionInfo() { + return _getVersionInfo.apply(this, arguments); + } + return getVersionInfo; + }()) + }, { + key: "getSACBalance", + value: (function () { + var _getSACBalance = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee25(contractId, sac, networkPassphrase) { + var passphrase, sacId, key, ledgerKey, response, _response$entries$2, lastModifiedLedgerSeq, liveUntilLedgerSeq, val, entry; + return server_regeneratorRuntime().wrap(function _callee25$(_context25) { + while (1) switch (_context25.prev = _context25.next) { + case 0: + if (lib.StrKey.isValidContract(contractId)) { + _context25.next = 2; + break; + } + throw new TypeError("expected contract ID, got ".concat(contractId)); + case 2: + if (!(networkPassphrase !== null && networkPassphrase !== void 0)) { + _context25.next = 6; + break; + } + _context25.t0 = networkPassphrase; + _context25.next = 9; + break; + case 6: + _context25.next = 8; + return this.getNetwork().then(function (n) { + return n.passphrase; + }); + case 8: + _context25.t0 = _context25.sent; + case 9: + passphrase = _context25.t0; + sacId = sac.contractId(passphrase); + key = lib.xdr.ScVal.scvVec([(0,lib.nativeToScVal)("Balance", { + type: "symbol" + }), (0,lib.nativeToScVal)(contractId, { + type: "address" + })]); + ledgerKey = lib.xdr.LedgerKey.contractData(new lib.xdr.LedgerKeyContractData({ + contract: new lib.Address(sacId).toScAddress(), + durability: lib.xdr.ContractDataDurability.persistent(), + key: key + })); + _context25.next = 15; + return this.getLedgerEntries(ledgerKey); + case 15: + response = _context25.sent; + if (!(response.entries.length === 0)) { + _context25.next = 18; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 18: + _response$entries$2 = response.entries[0], lastModifiedLedgerSeq = _response$entries$2.lastModifiedLedgerSeq, liveUntilLedgerSeq = _response$entries$2.liveUntilLedgerSeq, val = _response$entries$2.val; + if (!(val.switch().value !== lib.xdr.LedgerEntryType.contractData().value)) { + _context25.next = 21; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 21: + entry = (0,lib.scValToNative)(val.contractData().val()); + return _context25.abrupt("return", { + latestLedger: response.latestLedger, + balanceEntry: { + liveUntilLedgerSeq: liveUntilLedgerSeq, + lastModifiedLedgerSeq: lastModifiedLedgerSeq, + amount: entry.amount.toString(), + authorized: entry.authorized, + clawback: entry.clawback + } + }); + case 23: + case "end": + return _context25.stop(); + } + }, _callee25, this); + })); + function getSACBalance(_x23, _x24, _x25) { + return _getSACBalance.apply(this, arguments); + } + return getSACBalance; + }()) + }]); +}(); +;// ./src/rpc/index.ts +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + +/* harmony default export */ const rpc = (module.exports); + +/***/ }), + +/***/ 784: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ $D: () => (/* binding */ parseRawLedgerEntries), +/* harmony export */ Af: () => (/* binding */ parseRawSendTransaction), +/* harmony export */ WC: () => (/* binding */ parseTransactionInfo), +/* harmony export */ fG: () => (/* binding */ parseRawEvents), +/* harmony export */ jr: () => (/* binding */ parseRawSimulation), +/* harmony export */ tR: () => (/* binding */ parseRawTransactions) +/* harmony export */ }); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4076); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + +function parseRawSendTransaction(raw) { + var errorResultXdr = raw.errorResultXdr, + diagnosticEventsXdr = raw.diagnosticEventsXdr; + delete raw.errorResultXdr; + delete raw.diagnosticEventsXdr; + if (errorResultXdr) { + return _objectSpread(_objectSpread(_objectSpread({}, raw), diagnosticEventsXdr !== undefined && diagnosticEventsXdr.length > 0 && { + diagnosticEvents: diagnosticEventsXdr.map(function (evt) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + }) + }), {}, { + errorResult: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionResult.fromXDR(errorResultXdr, 'base64') + }); + } + return _objectSpread({}, raw); +} +function parseTransactionInfo(raw) { + var meta = _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionMeta.fromXDR(raw.resultMetaXdr, 'base64'); + var info = { + ledger: raw.ledger, + createdAt: raw.createdAt, + applicationOrder: raw.applicationOrder, + feeBump: raw.feeBump, + envelopeXdr: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionEnvelope.fromXDR(raw.envelopeXdr, 'base64'), + resultXdr: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionResult.fromXDR(raw.resultXdr, 'base64'), + resultMetaXdr: meta + }; + if (meta.switch() === 3 && meta.v3().sorobanMeta() !== null) { + var _meta$v3$sorobanMeta; + info.returnValue = (_meta$v3$sorobanMeta = meta.v3().sorobanMeta()) === null || _meta$v3$sorobanMeta === void 0 ? void 0 : _meta$v3$sorobanMeta.returnValue(); + } + if ('diagnosticEventsXdr' in raw && raw.diagnosticEventsXdr) { + info.diagnosticEventsXdr = raw.diagnosticEventsXdr.map(function (diagnosticEvent) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.DiagnosticEvent.fromXDR(diagnosticEvent, 'base64'); + }); + } + return info; +} +function parseRawTransactions(r) { + return _objectSpread({ + status: r.status, + txHash: r.txHash + }, parseTransactionInfo(r)); +} +function parseRawEvents(raw) { + var _raw$events; + return { + latestLedger: raw.latestLedger, + cursor: raw.cursor, + events: ((_raw$events = raw.events) !== null && _raw$events !== void 0 ? _raw$events : []).map(function (evt) { + var clone = _objectSpread({}, evt); + delete clone.contractId; + return _objectSpread(_objectSpread(_objectSpread({}, clone), evt.contractId !== '' && { + contractId: new _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.Contract(evt.contractId) + }), {}, { + topic: evt.topic.map(function (topic) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.fromXDR(topic, 'base64'); + }), + value: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.fromXDR(evt.value, 'base64') + }); + }) + }; +} +function parseRawLedgerEntries(raw) { + var _raw$entries; + return { + latestLedger: raw.latestLedger, + entries: ((_raw$entries = raw.entries) !== null && _raw$entries !== void 0 ? _raw$entries : []).map(function (rawEntry) { + if (!rawEntry.key || !rawEntry.xdr) { + throw new TypeError("invalid ledger entry: ".concat(JSON.stringify(rawEntry))); + } + return _objectSpread({ + lastModifiedLedgerSeq: rawEntry.lastModifiedLedgerSeq, + key: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerKey.fromXDR(rawEntry.key, 'base64'), + val: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerEntryData.fromXDR(rawEntry.xdr, 'base64') + }, rawEntry.liveUntilLedgerSeq !== undefined && { + liveUntilLedgerSeq: rawEntry.liveUntilLedgerSeq + }); + }) + }; +} +function parseSuccessful(sim, partial) { + var _sim$results$length, _sim$results, _sim$stateChanges$len, _sim$stateChanges, _sim$stateChanges2; + var success = _objectSpread(_objectSpread(_objectSpread({}, partial), {}, { + transactionData: new _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.SorobanDataBuilder(sim.transactionData), + minResourceFee: sim.minResourceFee + }, ((_sim$results$length = (_sim$results = sim.results) === null || _sim$results === void 0 ? void 0 : _sim$results.length) !== null && _sim$results$length !== void 0 ? _sim$results$length : 0 > 0) && { + result: sim.results.map(function (row) { + var _row$auth; + return { + auth: ((_row$auth = row.auth) !== null && _row$auth !== void 0 ? _row$auth : []).map(function (entry) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.SorobanAuthorizationEntry.fromXDR(entry, 'base64'); + }), + retval: row.xdr ? _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.fromXDR(row.xdr, 'base64') : _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.scvVoid() + }; + })[0] + }), ((_sim$stateChanges$len = (_sim$stateChanges = sim.stateChanges) === null || _sim$stateChanges === void 0 ? void 0 : _sim$stateChanges.length) !== null && _sim$stateChanges$len !== void 0 ? _sim$stateChanges$len : 0 > 0) && { + stateChanges: (_sim$stateChanges2 = sim.stateChanges) === null || _sim$stateChanges2 === void 0 ? void 0 : _sim$stateChanges2.map(function (entryChange) { + return { + type: entryChange.type, + key: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerKey.fromXDR(entryChange.key, 'base64'), + before: entryChange.before ? _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerEntry.fromXDR(entryChange.before, 'base64') : null, + after: entryChange.after ? _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerEntry.fromXDR(entryChange.after, 'base64') : null + }; + }) + }); + if (!sim.restorePreamble || sim.restorePreamble.transactionData === '') { + return success; + } + return _objectSpread(_objectSpread({}, success), {}, { + restorePreamble: { + minResourceFee: sim.restorePreamble.minResourceFee, + transactionData: new _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.SorobanDataBuilder(sim.restorePreamble.transactionData) + } + }); +} +function parseRawSimulation(sim) { + var _sim$events$map, _sim$events; + var looksRaw = _api__WEBPACK_IMPORTED_MODULE_1__/* .Api */ .j.isSimulationRaw(sim); + if (!looksRaw) { + return sim; + } + var base = { + _parsed: true, + id: sim.id, + latestLedger: sim.latestLedger, + events: (_sim$events$map = (_sim$events = sim.events) === null || _sim$events === void 0 ? void 0 : _sim$events.map(function (evt) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + })) !== null && _sim$events$map !== void 0 ? _sim$events$map : [] + }; + if (typeof sim.error === 'string') { + return _objectSpread(_objectSpread({}, base), {}, { + error: sim.error + }); + } + return parseSuccessful(sim, base); +} + +/***/ }), + +/***/ 8680: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ X: () => (/* binding */ assembleTransaction) +/* harmony export */ }); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4076); +/* harmony import */ var _parsers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(784); + + + +function isSorobanTransaction(tx) { + if (tx.operations.length !== 1) { + return false; + } + switch (tx.operations[0].type) { + case 'invokeHostFunction': + case 'extendFootprintTtl': + case 'restoreFootprint': + return true; + default: + return false; + } +} +function assembleTransaction(raw, simulation) { + if ('innerTransaction' in raw) { + return assembleTransaction(raw.innerTransaction, simulation); + } + if (!isSorobanTransaction(raw)) { + throw new TypeError('unsupported transaction: must contain exactly one ' + 'invokeHostFunction, extendFootprintTtl, or restoreFootprint ' + 'operation'); + } + var success = (0,_parsers__WEBPACK_IMPORTED_MODULE_2__/* .parseRawSimulation */ .jr)(simulation); + if (!_api__WEBPACK_IMPORTED_MODULE_1__/* .Api */ .j.isSimulationSuccess(success)) { + throw new Error("simulation incorrect: ".concat(JSON.stringify(success))); + } + var classicFeeNum = parseInt(raw.fee) || 0; + var minResourceFeeNum = parseInt(success.minResourceFee) || 0; + var txnBuilder = _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.TransactionBuilder.cloneFrom(raw, { + fee: (classicFeeNum + minResourceFeeNum).toString(), + sorobanData: success.transactionData.build(), + networkPassphrase: raw.networkPassphrase + }); + if (raw.operations[0].type === 'invokeHostFunction') { + var _invokeOp$auth; + txnBuilder.clearOperations(); + var invokeOp = raw.operations[0]; + var existingAuth = (_invokeOp$auth = invokeOp.auth) !== null && _invokeOp$auth !== void 0 ? _invokeOp$auth : []; + txnBuilder.addOperation(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.Operation.invokeHostFunction({ + source: invokeOp.source, + func: invokeOp.func, + auth: existingAuth.length > 0 ? existingAuth : success.result.auth + })); + } + return txnBuilder; +} + +/***/ }), + +/***/ 3898: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Api: () => (/* binding */ Api), +/* harmony export */ Resolver: () => (/* binding */ Resolver), +/* harmony export */ STELLAR_TOML_MAX_SIZE: () => (/* binding */ STELLAR_TOML_MAX_SIZE) +/* harmony export */ }); +/* harmony import */ var toml__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1293); +/* harmony import */ var toml__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(toml__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _http_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6371); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8732); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + +var STELLAR_TOML_MAX_SIZE = 100 * 1024; +var CancelToken = _http_client__WEBPACK_IMPORTED_MODULE_1__/* .httpClient */ .ok.CancelToken; +var Resolver = function () { + function Resolver() { + _classCallCheck(this, Resolver); + } + return _createClass(Resolver, null, [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(domain) { + var _opts$allowedRedirect; + var opts, + allowHttp, + timeout, + protocol, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 1 && _args[1] !== undefined ? _args[1] : {}; + allowHttp = typeof opts.allowHttp === "undefined" ? _config__WEBPACK_IMPORTED_MODULE_2__/* .Config */ .T.isAllowHttp() : opts.allowHttp; + timeout = typeof opts.timeout === "undefined" ? _config__WEBPACK_IMPORTED_MODULE_2__/* .Config */ .T.getTimeout() : opts.timeout; + protocol = allowHttp ? "http" : "https"; + return _context.abrupt("return", _http_client__WEBPACK_IMPORTED_MODULE_1__/* .httpClient */ .ok.get("".concat(protocol, "://").concat(domain, "/.well-known/stellar.toml"), { + maxRedirects: (_opts$allowedRedirect = opts.allowedRedirects) !== null && _opts$allowedRedirect !== void 0 ? _opts$allowedRedirect : 0, + maxContentLength: STELLAR_TOML_MAX_SIZE, + cancelToken: timeout ? new CancelToken(function (cancel) { + return setTimeout(function () { + return cancel("timeout of ".concat(timeout, "ms exceeded")); + }, timeout); + }) : undefined, + timeout: timeout + }).then(function (response) { + try { + var tomlObject = toml__WEBPACK_IMPORTED_MODULE_0___default().parse(response.data); + return Promise.resolve(tomlObject); + } catch (e) { + return Promise.reject(new Error("stellar.toml is invalid - Parsing error on line ".concat(e.line, ", column ").concat(e.column, ": ").concat(e.message))); + } + }).catch(function (err) { + if (err.message.match(/^maxContentLength size/)) { + throw new Error("stellar.toml file exceeds allowed size of ".concat(STELLAR_TOML_MAX_SIZE)); + } else { + throw err; + } + })); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + function resolve(_x) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }]); +}(); +var Api; + +/***/ }), + +/***/ 3121: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ A: () => (/* binding */ Utils) +/* harmony export */ }); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Utils = function () { + function Utils() { + _classCallCheck(this, Utils); + } + return _createClass(Utils, null, [{ + key: "validateTimebounds", + value: function validateTimebounds(transaction) { + var gracePeriod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + if (!transaction.timeBounds) { + return false; + } + var now = Math.floor(Date.now() / 1000); + var _transaction$timeBoun = transaction.timeBounds, + minTime = _transaction$timeBoun.minTime, + maxTime = _transaction$timeBoun.maxTime; + return now >= Number.parseInt(minTime, 10) - gracePeriod && now <= Number.parseInt(maxTime, 10) + gracePeriod; + } + }, { + key: "sleep", + value: function sleep(ms) { + return new Promise(function (resolve) { + return setTimeout(resolve, ms); + }); + } + }]); +}(); + +/***/ }), + +/***/ 5479: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + InvalidChallengeError: () => (/* reexport */ InvalidChallengeError), + buildChallengeTx: () => (/* reexport */ buildChallengeTx), + gatherTxSigners: () => (/* reexport */ gatherTxSigners), + readChallengeTx: () => (/* reexport */ readChallengeTx), + verifyChallengeTxSigners: () => (/* reexport */ verifyChallengeTxSigners), + verifyChallengeTxThreshold: () => (/* reexport */ verifyChallengeTxThreshold), + verifyTxSignedBy: () => (/* reexport */ verifyTxSignedBy) +}); + +// EXTERNAL MODULE: ./node_modules/randombytes/browser.js +var browser = __webpack_require__(3209); +var browser_default = /*#__PURE__*/__webpack_require__.n(browser); +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./src/utils.ts +var utils = __webpack_require__(3121); +;// ./src/webauth/errors.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var InvalidChallengeError = function (_Error) { + function InvalidChallengeError(message) { + var _this; + _classCallCheck(this, InvalidChallengeError); + var trueProto = (this instanceof InvalidChallengeError ? this.constructor : void 0).prototype; + _this = _callSuper(this, InvalidChallengeError, [message]); + _this.__proto__ = trueProto; + _this.constructor = InvalidChallengeError; + _this.name = "InvalidChallengeError"; + return _this; + } + _inherits(InvalidChallengeError, _Error); + return _createClass(InvalidChallengeError); +}(_wrapNativeSuper(Error)); +;// ./src/webauth/utils.ts +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function utils_typeof(o) { "@babel/helpers - typeof"; return utils_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, utils_typeof(o); } +function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } + + + + +function buildChallengeTx(serverKeypair, clientAccountID, homeDomain) { + var timeout = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 300; + var networkPassphrase = arguments.length > 4 ? arguments[4] : undefined; + var webAuthDomain = arguments.length > 5 ? arguments[5] : undefined; + var memo = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var clientDomain = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var clientSigningKey = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; + if (clientAccountID.startsWith("M") && memo) { + throw Error("memo cannot be used if clientAccountID is a muxed account"); + } + var account = new lib.Account(serverKeypair.publicKey(), "-1"); + var now = Math.floor(Date.now() / 1000); + var value = browser_default()(48).toString("base64"); + var builder = new lib.TransactionBuilder(account, { + fee: lib.BASE_FEE, + networkPassphrase: networkPassphrase, + timebounds: { + minTime: now, + maxTime: now + timeout + } + }).addOperation(lib.Operation.manageData({ + name: "".concat(homeDomain, " auth"), + value: value, + source: clientAccountID + })).addOperation(lib.Operation.manageData({ + name: "web_auth_domain", + value: webAuthDomain, + source: account.accountId() + })); + if (clientDomain) { + if (!clientSigningKey) { + throw Error("clientSigningKey is required if clientDomain is provided"); + } + builder.addOperation(lib.Operation.manageData({ + name: "client_domain", + value: clientDomain, + source: clientSigningKey + })); + } + if (memo) { + builder.addMemo(lib.Memo.id(memo)); + } + var transaction = builder.build(); + transaction.sign(serverKeypair); + return transaction.toEnvelope().toXDR("base64").toString(); +} +function readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain) { + var _transaction$timeBoun; + if (serverAccountID.startsWith("M")) { + throw Error("Invalid serverAccountID: multiplexed accounts are not supported."); + } + var transaction; + try { + transaction = new lib.Transaction(challengeTx, networkPassphrase); + } catch (_unused) { + try { + transaction = new lib.FeeBumpTransaction(challengeTx, networkPassphrase); + } catch (_unused2) { + throw new InvalidChallengeError("Invalid challenge: unable to deserialize challengeTx transaction string"); + } + throw new InvalidChallengeError("Invalid challenge: expected a Transaction but received a FeeBumpTransaction"); + } + var sequence = Number.parseInt(transaction.sequence, 10); + if (sequence !== 0) { + throw new InvalidChallengeError("The transaction sequence number should be zero"); + } + if (transaction.source !== serverAccountID) { + throw new InvalidChallengeError("The transaction source account is not equal to the server's account"); + } + if (transaction.operations.length < 1) { + throw new InvalidChallengeError("The transaction should contain at least one operation"); + } + var _transaction$operatio = _toArray(transaction.operations), + operation = _transaction$operatio[0], + subsequentOperations = _transaction$operatio.slice(1); + if (!operation.source) { + throw new InvalidChallengeError("The transaction's operation should contain a source account"); + } + var clientAccountID = operation.source; + var memo = null; + if (transaction.memo.type !== lib.MemoNone) { + if (clientAccountID.startsWith("M")) { + throw new InvalidChallengeError("The transaction has a memo but the client account ID is a muxed account"); + } + if (transaction.memo.type !== lib.MemoID) { + throw new InvalidChallengeError("The transaction's memo must be of type `id`"); + } + memo = transaction.memo.value; + } + if (operation.type !== "manageData") { + throw new InvalidChallengeError("The transaction's operation type should be 'manageData'"); + } + if (transaction.timeBounds && Number.parseInt((_transaction$timeBoun = transaction.timeBounds) === null || _transaction$timeBoun === void 0 ? void 0 : _transaction$timeBoun.maxTime, 10) === lib.TimeoutInfinite) { + throw new InvalidChallengeError("The transaction requires non-infinite timebounds"); + } + if (!utils/* Utils */.A.validateTimebounds(transaction, 60 * 5)) { + throw new InvalidChallengeError("The transaction has expired"); + } + if (operation.value === undefined) { + throw new InvalidChallengeError("The transaction's operation values should not be null"); + } + if (!operation.value) { + throw new InvalidChallengeError("The transaction's operation value should not be null"); + } + if (Buffer.from(operation.value.toString(), "base64").length !== 48) { + throw new InvalidChallengeError("The transaction's operation value should be a 64 bytes base64 random string"); + } + if (!homeDomains) { + throw new InvalidChallengeError("Invalid homeDomains: a home domain must be provided for verification"); + } + var matchedHomeDomain; + if (typeof homeDomains === "string") { + if ("".concat(homeDomains, " auth") === operation.name) { + matchedHomeDomain = homeDomains; + } + } else if (Array.isArray(homeDomains)) { + matchedHomeDomain = homeDomains.find(function (domain) { + return "".concat(domain, " auth") === operation.name; + }); + } else { + throw new InvalidChallengeError("Invalid homeDomains: homeDomains type is ".concat(utils_typeof(homeDomains), " but should be a string or an array")); + } + if (!matchedHomeDomain) { + throw new InvalidChallengeError("Invalid homeDomains: the transaction's operation key name does not match the expected home domain"); + } + var _iterator = _createForOfIteratorHelper(subsequentOperations), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var op = _step.value; + if (op.type !== "manageData") { + throw new InvalidChallengeError("The transaction has operations that are not of type 'manageData'"); + } + if (op.source !== serverAccountID && op.name !== "client_domain") { + throw new InvalidChallengeError("The transaction has operations that are unrecognized"); + } + if (op.name === "web_auth_domain") { + if (op.value === undefined) { + throw new InvalidChallengeError("'web_auth_domain' operation value should not be null"); + } + if (op.value.compare(Buffer.from(webAuthDomain))) { + throw new InvalidChallengeError("'web_auth_domain' operation value does not match ".concat(webAuthDomain)); + } + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + if (!verifyTxSignedBy(transaction, serverAccountID)) { + throw new InvalidChallengeError("Transaction not signed by server: '".concat(serverAccountID, "'")); + } + return { + tx: transaction, + clientAccountID: clientAccountID, + matchedHomeDomain: matchedHomeDomain, + memo: memo + }; +} +function verifyChallengeTxThreshold(challengeTx, serverAccountID, networkPassphrase, threshold, signerSummary, homeDomains, webAuthDomain) { + var signers = signerSummary.map(function (signer) { + return signer.key; + }); + var signersFound = verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain); + var weight = 0; + var _loop = function _loop() { + var _signerSummary$find; + var signer = _signersFound[_i]; + var sigWeight = ((_signerSummary$find = signerSummary.find(function (s) { + return s.key === signer; + })) === null || _signerSummary$find === void 0 ? void 0 : _signerSummary$find.weight) || 0; + weight += sigWeight; + }; + for (var _i = 0, _signersFound = signersFound; _i < _signersFound.length; _i++) { + _loop(); + } + if (weight < threshold) { + throw new InvalidChallengeError("signers with weight ".concat(weight, " do not meet threshold ").concat(threshold, "\"")); + } + return signersFound; +} +function verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain) { + var _readChallengeTx = readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain), + tx = _readChallengeTx.tx; + var serverKP; + try { + serverKP = lib.Keypair.fromPublicKey(serverAccountID); + } catch (err) { + throw new Error("Couldn't infer keypair from the provided 'serverAccountID': ".concat(err.message)); + } + var clientSigners = new Set(); + var _iterator2 = _createForOfIteratorHelper(signers), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var _signer = _step2.value; + if (_signer === serverKP.publicKey()) { + continue; + } + if (_signer.charAt(0) !== "G") { + continue; + } + clientSigners.add(_signer); + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + if (clientSigners.size === 0) { + throw new InvalidChallengeError("No verifiable client signers provided, at least one G... address must be provided"); + } + var clientSigningKey; + var _iterator3 = _createForOfIteratorHelper(tx.operations), + _step3; + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + var op = _step3.value; + if (op.type === "manageData" && op.name === "client_domain") { + if (clientSigningKey) { + throw new InvalidChallengeError("Found more than one client_domain operation"); + } + clientSigningKey = op.source; + } + } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); + } + var allSigners = [serverKP.publicKey()].concat(_toConsumableArray(Array.from(clientSigners))); + if (clientSigningKey) { + allSigners.push(clientSigningKey); + } + var signersFound = gatherTxSigners(tx, allSigners); + var serverSignatureFound = false; + var clientSigningKeySignatureFound = false; + for (var _i2 = 0, _signersFound2 = signersFound; _i2 < _signersFound2.length; _i2++) { + var signer = _signersFound2[_i2]; + if (signer === serverKP.publicKey()) { + serverSignatureFound = true; + } + if (signer === clientSigningKey) { + clientSigningKeySignatureFound = true; + } + } + if (!serverSignatureFound) { + throw new InvalidChallengeError("Transaction not signed by server: '".concat(serverKP.publicKey(), "'")); + } + if (clientSigningKey && !clientSigningKeySignatureFound) { + throw new InvalidChallengeError("Transaction not signed by the source account of the 'client_domain' " + "ManageData operation"); + } + if (signersFound.length === 1) { + throw new InvalidChallengeError("None of the given signers match the transaction signatures"); + } + if (signersFound.length !== tx.signatures.length) { + throw new InvalidChallengeError("Transaction has unrecognized signatures"); + } + signersFound.splice(signersFound.indexOf(serverKP.publicKey()), 1); + if (clientSigningKey) { + signersFound.splice(signersFound.indexOf(clientSigningKey), 1); + } + return signersFound; +} +function verifyTxSignedBy(transaction, accountID) { + return gatherTxSigners(transaction, [accountID]).length !== 0; +} +function gatherTxSigners(transaction, signers) { + var hashedSignatureBase = transaction.hash(); + var txSignatures = _toConsumableArray(transaction.signatures); + var signersFound = new Set(); + var _iterator4 = _createForOfIteratorHelper(signers), + _step4; + try { + for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { + var signer = _step4.value; + if (txSignatures.length === 0) { + break; + } + var keypair = void 0; + try { + keypair = lib.Keypair.fromPublicKey(signer); + } catch (err) { + throw new InvalidChallengeError("Signer is not a valid address: ".concat(err.message)); + } + for (var i = 0; i < txSignatures.length; i++) { + var decSig = txSignatures[i]; + if (!decSig.hint().equals(keypair.signatureHint())) { + continue; + } + if (keypair.verify(hashedSignatureBase, decSig.signature())) { + signersFound.add(signer); + txSignatures.splice(i, 1); + break; + } + } + } + } catch (err) { + _iterator4.e(err); + } finally { + _iterator4.f(); + } + return Array.from(signersFound); +} +;// ./src/webauth/index.ts + + + +/***/ }), + +/***/ 5360: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +/** + * Generate a character map. + * @param {string} alphabet e.g. "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" + * @param {object} mappings map overrides from key to value + * @method + */ + +var charmap = function (alphabet, mappings) { + mappings || (mappings = {}); + alphabet.split("").forEach(function (c, i) { + if (!(c in mappings)) mappings[c] = i; + }); + return mappings; +} + +/** + * The RFC 4648 base 32 alphabet and character map. + * @see {@link https://tools.ietf.org/html/rfc4648} + */ + +var rfc4648 = { + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", + charmap: { + 0: 14, + 1: 8 + } +}; + +rfc4648.charmap = charmap(rfc4648.alphabet, rfc4648.charmap); + +/** + * The Crockford base 32 alphabet and character map. + * @see {@link http://www.crockford.com/wrmg/base32.html} + */ + +var crockford = { + alphabet: "0123456789ABCDEFGHJKMNPQRSTVWXYZ", + charmap: { + O: 0, + I: 1, + L: 1 + } +}; + +crockford.charmap = charmap(crockford.alphabet, crockford.charmap); + +/** + * base32hex + * @see {@link https://en.wikipedia.org/wiki/Base32#base32hex} + */ + +var base32hex = { + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", + charmap: {} +}; + +base32hex.charmap = charmap(base32hex.alphabet, base32hex.charmap); + +/** + * Create a new `Decoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [charmap] Override the character map used in decoding. + * @constructor + */ + +function Decoder (options) { + this.buf = []; + this.shift = 8; + this.carry = 0; + + if (options) { + + switch (options.type) { + case "rfc4648": + this.charmap = exports.rfc4648.charmap; + break; + case "crockford": + this.charmap = exports.crockford.charmap; + break; + case "base32hex": + this.charmap = exports.base32hex.charmap; + break; + default: + throw new Error("invalid type"); + } + + if (options.charmap) this.charmap = options.charmap; + } +} + +/** + * The default character map coresponds to RFC4648. + */ + +Decoder.prototype.charmap = rfc4648.charmap; + +/** + * Decode a string, continuing from the previous state. + * + * @param {string} str + * @return {Decoder} this + */ + +Decoder.prototype.write = function (str) { + var charmap = this.charmap; + var buf = this.buf; + var shift = this.shift; + var carry = this.carry; + + // decode string + str.toUpperCase().split("").forEach(function (char) { + + // ignore padding + if (char == "=") return; + + // lookup symbol + var symbol = charmap[char] & 0xff; + + // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 + + shift -= 5; + if (shift > 0) { + carry |= symbol << shift; + } else if (shift < 0) { + buf.push(carry | (symbol >> -shift)); + shift += 8; + carry = (symbol << shift) & 0xff; + } else { + buf.push(carry | symbol); + shift = 8; + carry = 0; + } + }); + + // save state + this.shift = shift; + this.carry = carry; + + // for chaining + return this; +}; + +/** + * Finish decoding. + * + * @param {string} [str] The final string to decode. + * @return {Array} Decoded byte array. + */ + +Decoder.prototype.finalize = function (str) { + if (str) { + this.write(str); + } + if (this.shift !== 8 && this.carry !== 0) { + this.buf.push(this.carry); + this.shift = 8; + this.carry = 0; + } + return this.buf; +}; + +/** + * Create a new `Encoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [alphabet] Override the alphabet used in encoding. + * @constructor + */ + +function Encoder (options) { + this.buf = ""; + this.shift = 3; + this.carry = 0; + + if (options) { + + switch (options.type) { + case "rfc4648": + this.alphabet = exports.rfc4648.alphabet; + break; + case "crockford": + this.alphabet = exports.crockford.alphabet; + break; + case "base32hex": + this.alphabet = exports.base32hex.alphabet; + break; + default: + throw new Error("invalid type"); + } + + if (options.alphabet) this.alphabet = options.alphabet; + else if (options.lc) this.alphabet = this.alphabet.toLowerCase(); + } +} + +/** + * The default alphabet coresponds to RFC4648. + */ + +Encoder.prototype.alphabet = rfc4648.alphabet; + +/** + * Encode a byte array, continuing from the previous state. + * + * @param {byte[]} buf The byte array to encode. + * @return {Encoder} this + */ + +Encoder.prototype.write = function (buf) { + var shift = this.shift; + var carry = this.carry; + var symbol; + var byte; + var i; + + // encode each byte in buf + for (i = 0; i < buf.length; i++) { + byte = buf[i]; + + // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 + + symbol = carry | (byte >> shift); + this.buf += this.alphabet[symbol & 0x1f]; + + if (shift > 5) { + shift -= 5; + symbol = byte >> shift; + this.buf += this.alphabet[symbol & 0x1f]; + } + + shift = 5 - shift; + carry = byte << shift; + shift = 8 - shift; + } + + // save state + this.shift = shift; + this.carry = carry; + + // for chaining + return this; +}; + +/** + * Finish encoding. + * + * @param {byte[]} [buf] The final byte array to encode. + * @return {string} The encoded byte array. + */ + +Encoder.prototype.finalize = function (buf) { + if (buf) { + this.write(buf); + } + if (this.shift !== 3) { + this.buf += this.alphabet[this.carry & 0x1f]; + this.shift = 3; + this.carry = 0; + } + return this.buf; +}; + +/** + * Convenience encoder. + * + * @param {byte[]} buf The byte array to encode. + * @param {object} [options] Options to pass to the encoder. + * @return {string} The encoded string. + */ + +exports.encode = function (buf, options) { + return new Encoder(options).finalize(buf); +}; + +/** + * Convenience decoder. + * + * @param {string} str The string to decode. + * @param {object} [options] Options to pass to the decoder. + * @return {byte[]} The decoded byte array. + */ + +exports.decode = function (str, options) { + return new Decoder(options).finalize(str); +}; + +// Exports. +exports.Decoder = Decoder; +exports.Encoder = Encoder; +exports.charmap = charmap; +exports.crockford = crockford; +exports.rfc4648 = rfc4648; +exports.base32hex = base32hex; + + +/***/ }), + +/***/ 7526: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + + +/***/ }), + +/***/ 1594: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_RESULT__;;(function (globalObject) { + 'use strict'; + +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + + var BigNumber, + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + + /* + * Create and return a BigNumber constructor. + */ + function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; + } + + + // PRIVATE HELPER FUNCTIONS + + // These functions don't need access to variables, + // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + + function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; + } + + + // Return a coefficient array as a string of base 10 digits. + function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); + } + + + // Compare the value of BigNumbers x and y. + function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; + } + + + /* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ + function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } + } + + + // Assumes finite n. + function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; + } + + + function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; + } + + + function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; + } + + + // EXPORT + + + BigNumber = clone(); + BigNumber['default'] = BigNumber.BigNumber = BigNumber; + + // AMD. + if (true) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return BigNumber; }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + // Node.js and other environments that support module.exports. + } else {} +})(this); + + +/***/ }), + +/***/ 8287: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + + + +const base64 = __webpack_require__(7526) +const ieee754 = __webpack_require__(251) +const customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +const K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + const arr = new Uint8Array(1) + const proto = { foo: function () { return 42 } } + Object.setPrototypeOf(proto, Uint8Array.prototype) + Object.setPrototypeOf(arr, proto) + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + const buf = new Uint8Array(length) + Object.setPrototypeOf(buf, Buffer.prototype) + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + const valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + const b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) +Object.setPrototypeOf(Buffer, Uint8Array) + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + const length = byteLength(string, encoding) | 0 + let buf = createBuffer(length) + + const actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0 + const buf = createBuffer(length) + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView) + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + let buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype) + + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + const len = checked(obj.length) | 0 + const buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + let x = a.length + let y = b.length + + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + let i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + const buffer = Buffer.allocUnsafe(length) + let pos = 0 + for (i = 0; i < list.length; ++i) { + let buf = list[i] + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) + buf.copy(buffer, pos) + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ) + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos) + } + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + const len = string.length + const mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + let loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + let loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + const i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + const len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + const len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + const len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + const length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + let str = '' + const max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + let x = thisEnd - thisStart + let y = end - start + const len = Math.min(x, y) + + const thisCopy = this.slice(thisStart, thisEnd) + const targetCopy = target.slice(start, end) + + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + let indexSize = 1 + let arrLength = arr.length + let valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + let i + if (dir) { + let foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + let found = true + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + const remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + const strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + let i + for (i = 0; i < length; ++i) { + const parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + const remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + let loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + const res = [] + + let i = start + while (i < end) { + const firstByte = buf[i] + let codePoint = null + let bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +const MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + const len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + let res = '' + let i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + const len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + let out = '' + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]] + } + return out +} + +function utf16leSlice (buf, start, end) { + const bytes = buf.slice(start, end) + let res = '' + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + const len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + const newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype) + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + let val = this[offset + --byteLength] + let mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const lo = first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24 + + const hi = this[++offset] + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + last * 2 ** 24 + + return BigInt(lo) + (BigInt(hi) << BigInt(32)) +}) + +Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const hi = first * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + const lo = this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last + + return (BigInt(hi) << BigInt(32)) + BigInt(lo) +}) + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let i = byteLength + let mul = 1 + let val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = this[offset + 4] + + this[offset + 5] * 2 ** 8 + + this[offset + 6] * 2 ** 16 + + (last << 24) // Overflow + + return (BigInt(val) << BigInt(32)) + + BigInt(first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24) +}) + +Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + return (BigInt(val) << BigInt(32)) + + BigInt(this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last) +}) + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let mul = 1 + let i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let i = byteLength - 1 + let mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function wrtBigUInt64LE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + return offset +} + +function wrtBigUInt64BE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset + 7] = lo + lo = lo >> 8 + buf[offset + 6] = lo + lo = lo >> 8 + buf[offset + 5] = lo + lo = lo >> 8 + buf[offset + 4] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset + 3] = hi + hi = hi >> 8 + buf[offset + 2] = hi + hi = hi >> 8 + buf[offset + 1] = hi + hi = hi >> 8 + buf[offset] = hi + return offset + 8 +} + +Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = 0 + let mul = 1 + let sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = byteLength - 1 + let mul = 1 + let sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + const len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + const code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } else if (typeof val === 'boolean') { + val = Number(val) + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + let i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + const bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + const len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// CUSTOM ERRORS +// ============= + +// Simplified versions from Node, changed for Buffer-only usage +const errors = {} +function E (sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor () { + super() + + Object.defineProperty(this, 'message', { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }) + + // Add the error code to the name to include it in the stack trace. + this.name = `${this.name} [${sym}]` + // Access the stack to generate the error message including the error code + // from the name. + this.stack // eslint-disable-line no-unused-expressions + // Reset the name to the actual name. + delete this.name + } + + get code () { + return sym + } + + set code (value) { + Object.defineProperty(this, 'code', { + configurable: true, + enumerable: true, + value, + writable: true + }) + } + + toString () { + return `${this.name} [${sym}]: ${this.message}` + } + } +} + +E('ERR_BUFFER_OUT_OF_BOUNDS', + function (name) { + if (name) { + return `${name} is outside of buffer bounds` + } + + return 'Attempt to access memory outside buffer bounds' + }, RangeError) +E('ERR_INVALID_ARG_TYPE', + function (name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}` + }, TypeError) +E('ERR_OUT_OF_RANGE', + function (str, range, input) { + let msg = `The value of "${str}" is out of range.` + let received = input + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)) + } else if (typeof input === 'bigint') { + received = String(input) + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received) + } + received += 'n' + } + msg += ` It must be ${range}. Received ${received}` + return msg + }, RangeError) + +function addNumericalSeparator (val) { + let res = '' + let i = val.length + const start = val[0] === '-' ? 1 : 0 + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}` + } + return `${val.slice(0, i)}${res}` +} + +// CHECK FUNCTIONS +// =============== + +function checkBounds (buf, offset, byteLength) { + validateNumber(offset, 'offset') + if (buf[offset] === undefined || buf[offset + byteLength] === undefined) { + boundsError(offset, buf.length - (byteLength + 1)) + } +} + +function checkIntBI (value, min, max, buf, offset, byteLength) { + if (value > max || value < min) { + const n = typeof min === 'bigint' ? 'n' : '' + let range + if (byteLength > 3) { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}` + } else { + range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` + + `${(byteLength + 1) * 8 - 1}${n}` + } + } else { + range = `>= ${min}${n} and <= ${max}${n}` + } + throw new errors.ERR_OUT_OF_RANGE('value', range, value) + } + checkBounds(buf, offset, byteLength) +} + +function validateNumber (value, name) { + if (typeof value !== 'number') { + throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value) + } +} + +function boundsError (value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type) + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value) + } + + if (length < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS() + } + + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', + `>= ${type ? 1 : 0} and <= ${length}`, + value) +} + +// HELPER FUNCTIONS +// ================ + +const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function utf8ToBytes (string, units) { + units = units || Infinity + let codePoint + const length = string.length + let leadSurrogate = null + const bytes = [] + + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + let c, hi, lo + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + let i + for (i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +const hexSliceLookupTable = (function () { + const alphabet = '0123456789abcdef' + const table = new Array(256) + for (let i = 0; i < 16; ++i) { + const i16 = i * 16 + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})() + +// Return not function with Error if BigInt not supported +function defineBigIntMethod (fn) { + return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn +} + +function BufferBigIntNotDefined () { + throw new Error('BigInt not supported') +} + + +/***/ }), + +/***/ 6866: +/***/ ((module) => { + +module.exports = { + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} + + +/***/ }), + +/***/ 3144: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var bind = __webpack_require__(6743); + +var $apply = __webpack_require__(1002); +var $call = __webpack_require__(76); +var $reflectApply = __webpack_require__(7119); + +/** @type {import('./actualApply')} */ +module.exports = $reflectApply || bind.call($call, $apply); + + +/***/ }), + +/***/ 2205: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var bind = __webpack_require__(6743); +var $apply = __webpack_require__(1002); +var actualApply = __webpack_require__(3144); + +/** @type {import('./applyBind')} */ +module.exports = function applyBind() { + return actualApply(bind, $apply, arguments); +}; + + +/***/ }), + +/***/ 1002: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./functionApply')} */ +module.exports = Function.prototype.apply; + + +/***/ }), + +/***/ 76: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./functionCall')} */ +module.exports = Function.prototype.call; + + +/***/ }), + +/***/ 3126: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var bind = __webpack_require__(6743); +var $TypeError = __webpack_require__(9675); + +var $call = __webpack_require__(76); +var $actualApply = __webpack_require__(3144); + +/** @type {import('.')} */ +module.exports = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== 'function') { + throw new $TypeError('a function is required'); + } + return $actualApply(bind, $call, args); +}; + + +/***/ }), + +/***/ 7119: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./reflectApply')} */ +module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; + + +/***/ }), + +/***/ 8075: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); + +var callBind = __webpack_require__(487); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; + + +/***/ }), + +/***/ 487: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var setFunctionLength = __webpack_require__(6897); + +var $defineProperty = __webpack_require__(655); + +var callBindBasic = __webpack_require__(3126); +var applyBind = __webpack_require__(2205); + +module.exports = function callBind(originalFunction) { + var func = callBindBasic(arguments); + var adjustedLength = originalFunction.length - (arguments.length - 1); + return setFunctionLength( + func, + 1 + (adjustedLength > 0 ? adjustedLength : 0), + true + ); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} + + +/***/ }), + +/***/ 6556: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); + +var callBindBasic = __webpack_require__(3126); + +/** @type {(thisArg: string, searchString: string, position?: number) => number} */ +var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]); + +/** @type {import('.')} */ +module.exports = function callBoundIntrinsic(name, allowMissing) { + // eslint-disable-next-line no-extra-parens + var intrinsic = /** @type {Parameters[0][0]} */ (GetIntrinsic(name, !!allowMissing)); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBindBasic([intrinsic]); + } + return intrinsic; +}; + + +/***/ }), + +/***/ 41: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var $defineProperty = __webpack_require__(655); + +var $SyntaxError = __webpack_require__(8068); +var $TypeError = __webpack_require__(9675); + +var gopd = __webpack_require__(5795); + +/** @type {import('.')} */ +module.exports = function defineDataProperty( + obj, + property, + value +) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new $TypeError('`obj` must be an object or a function`'); + } + if (typeof property !== 'string' && typeof property !== 'symbol') { + throw new $TypeError('`property` must be a string or a symbol`'); + } + if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { + throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null'); + } + if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { + throw new $TypeError('`nonWritable`, if provided, must be a boolean or null'); + } + if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { + throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null'); + } + if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { + throw new $TypeError('`loose`, if provided, must be a boolean'); + } + + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + + /* @type {false | TypedPropertyDescriptor} */ + var desc = !!gopd && gopd(obj, property); + + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value: value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { + // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable + obj[property] = value; // eslint-disable-line no-param-reassign + } else { + throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); + } +}; + + +/***/ }), + +/***/ 7176: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var callBind = __webpack_require__(3126); +var gOPD = __webpack_require__(5795); + +// eslint-disable-next-line no-extra-parens, no-proto +var hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; + +// eslint-disable-next-line no-extra-parens +var desc = hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); + +var $Object = Object; +var $getPrototypeOf = $Object.getPrototypeOf; + +/** @type {import('./get')} */ +module.exports = desc && typeof desc.get === 'function' + ? callBind([desc.get]) + : typeof $getPrototypeOf === 'function' + ? /** @type {import('./get')} */ function getDunder(value) { + // eslint-disable-next-line eqeqeq + return $getPrototypeOf(value == null ? value : $Object(value)); + } + : false; + + +/***/ }), + +/***/ 655: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +var $defineProperty = Object.defineProperty || false; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} + +module.exports = $defineProperty; + + +/***/ }), + +/***/ 1237: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./eval')} */ +module.exports = EvalError; + + +/***/ }), + +/***/ 9383: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +module.exports = Error; + + +/***/ }), + +/***/ 9290: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./range')} */ +module.exports = RangeError; + + +/***/ }), + +/***/ 9538: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./ref')} */ +module.exports = ReferenceError; + + +/***/ }), + +/***/ 8068: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./syntax')} */ +module.exports = SyntaxError; + + +/***/ }), + +/***/ 9675: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./type')} */ +module.exports = TypeError; + + +/***/ }), + +/***/ 5345: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./uri')} */ +module.exports = URIError; + + +/***/ }), + +/***/ 9612: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +module.exports = Object; + + +/***/ }), + +/***/ 7007: +/***/ ((module) => { + +"use strict"; +// 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. + + + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; +module.exports.once = once; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + checkListener(listener); + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + checkListener(listener); + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function once(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } + + function resolver() { + if (typeof emitter.removeListener === 'function') { + emitter.removeListener('error', errorListener); + } + resolve([].slice.call(arguments)); + }; + + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== 'error') { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); +} + +function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + } +} + +function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === 'function') { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === 'function') { + // EventTarget does not have `error` event semantics like Node + // EventEmitters, we do not listen for `error` events here. + emitter.addEventListener(name, function wrapListener(arg) { + // IE does not have builtin `{ once: true }` support so we + // have to do it manually. + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } +} + + +/***/ }), + +/***/ 1731: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +var parse = (__webpack_require__(8835).parse) +var events = __webpack_require__(7007) +var https = __webpack_require__(1083) +var http = __webpack_require__(1568) +var util = __webpack_require__(537) + +var httpsOptions = [ + 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers', + 'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity' +] + +var bom = [239, 187, 191] +var colon = 58 +var space = 32 +var lineFeed = 10 +var carriageReturn = 13 +// Beyond 256KB we could not observe any gain in performance +var maxBufferAheadAllocation = 1024 * 256 +// Headers matching the pattern should be removed when redirecting to different origin +var reUnsafeHeader = /^(cookie|authorization)$/i + +function hasBom (buf) { + return bom.every(function (charCode, index) { + return buf[index] === charCode + }) +} + +/** + * Creates a new EventSource object + * + * @param {String} url the URL to which to connect + * @param {Object} [eventSourceInitDict] extra init params. See README for details. + * @api public + **/ +function EventSource (url, eventSourceInitDict) { + var readyState = EventSource.CONNECTING + var headers = eventSourceInitDict && eventSourceInitDict.headers + var hasNewOrigin = false + Object.defineProperty(this, 'readyState', { + get: function () { + return readyState + } + }) + + Object.defineProperty(this, 'url', { + get: function () { + return url + } + }) + + var self = this + self.reconnectInterval = 1000 + self.connectionInProgress = false + + function onConnectionClosed (message) { + if (readyState === EventSource.CLOSED) return + readyState = EventSource.CONNECTING + _emit('error', new Event('error', {message: message})) + + // The url may have been changed by a temporary redirect. If that's the case, + // revert it now, and flag that we are no longer pointing to a new origin + if (reconnectUrl) { + url = reconnectUrl + reconnectUrl = null + hasNewOrigin = false + } + setTimeout(function () { + if (readyState !== EventSource.CONNECTING || self.connectionInProgress) { + return + } + self.connectionInProgress = true + connect() + }, self.reconnectInterval) + } + + var req + var lastEventId = '' + if (headers && headers['Last-Event-ID']) { + lastEventId = headers['Last-Event-ID'] + delete headers['Last-Event-ID'] + } + + var discardTrailingNewline = false + var data = '' + var eventName = '' + + var reconnectUrl = null + + function connect () { + var options = parse(url) + var isSecure = options.protocol === 'https:' + options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' } + if (lastEventId) options.headers['Last-Event-ID'] = lastEventId + if (headers) { + var reqHeaders = hasNewOrigin ? removeUnsafeHeaders(headers) : headers + for (var i in reqHeaders) { + var header = reqHeaders[i] + if (header) { + options.headers[i] = header + } + } + } + + // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`, + // but for now exists as a backwards-compatibility layer + options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized) + + if (eventSourceInitDict && eventSourceInitDict.createConnection !== undefined) { + options.createConnection = eventSourceInitDict.createConnection + } + + // If specify http proxy, make the request to sent to the proxy server, + // and include the original url in path and Host headers + var useProxy = eventSourceInitDict && eventSourceInitDict.proxy + if (useProxy) { + var proxy = parse(eventSourceInitDict.proxy) + isSecure = proxy.protocol === 'https:' + + options.protocol = isSecure ? 'https:' : 'http:' + options.path = url + options.headers.Host = options.host + options.hostname = proxy.hostname + options.host = proxy.host + options.port = proxy.port + } + + // If https options are specified, merge them into the request options + if (eventSourceInitDict && eventSourceInitDict.https) { + for (var optName in eventSourceInitDict.https) { + if (httpsOptions.indexOf(optName) === -1) { + continue + } + + var option = eventSourceInitDict.https[optName] + if (option !== undefined) { + options[optName] = option + } + } + } + + // Pass this on to the XHR + if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) { + options.withCredentials = eventSourceInitDict.withCredentials + } + + req = (isSecure ? https : http).request(options, function (res) { + self.connectionInProgress = false + // Handle HTTP errors + if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) { + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + onConnectionClosed() + return + } + + // Handle HTTP redirects + if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) { + var location = res.headers.location + if (!location) { + // Server sent redirect response without Location header. + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + return + } + var prevOrigin = new URL(url).origin + var nextOrigin = new URL(location).origin + hasNewOrigin = prevOrigin !== nextOrigin + if (res.statusCode === 307) reconnectUrl = url + url = location + process.nextTick(connect) + return + } + + if (res.statusCode !== 200) { + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + return self.close() + } + + readyState = EventSource.OPEN + res.on('close', function () { + res.removeAllListeners('close') + res.removeAllListeners('end') + onConnectionClosed() + }) + + res.on('end', function () { + res.removeAllListeners('close') + res.removeAllListeners('end') + onConnectionClosed() + }) + _emit('open', new Event('open')) + + // text/event-stream parser adapted from webkit's + // Source/WebCore/page/EventSource.cpp + var buf + var newBuffer + var startingPos = 0 + var startingFieldLength = -1 + var newBufferSize = 0 + var bytesUsed = 0 + + res.on('data', function (chunk) { + if (!buf) { + buf = chunk + if (hasBom(buf)) { + buf = buf.slice(bom.length) + } + bytesUsed = buf.length + } else { + if (chunk.length > buf.length - bytesUsed) { + newBufferSize = (buf.length * 2) + chunk.length + if (newBufferSize > maxBufferAheadAllocation) { + newBufferSize = buf.length + chunk.length + maxBufferAheadAllocation + } + newBuffer = Buffer.alloc(newBufferSize) + buf.copy(newBuffer, 0, 0, bytesUsed) + buf = newBuffer + } + chunk.copy(buf, bytesUsed) + bytesUsed += chunk.length + } + + var pos = 0 + var length = bytesUsed + + while (pos < length) { + if (discardTrailingNewline) { + if (buf[pos] === lineFeed) { + ++pos + } + discardTrailingNewline = false + } + + var lineLength = -1 + var fieldLength = startingFieldLength + var c + + for (var i = startingPos; lineLength < 0 && i < length; ++i) { + c = buf[i] + if (c === colon) { + if (fieldLength < 0) { + fieldLength = i - pos + } + } else if (c === carriageReturn) { + discardTrailingNewline = true + lineLength = i - pos + } else if (c === lineFeed) { + lineLength = i - pos + } + } + + if (lineLength < 0) { + startingPos = length - pos + startingFieldLength = fieldLength + break + } else { + startingPos = 0 + startingFieldLength = -1 + } + + parseEventStreamLine(buf, pos, fieldLength, lineLength) + + pos += lineLength + 1 + } + + if (pos === length) { + buf = void 0 + bytesUsed = 0 + } else if (pos > 0) { + buf = buf.slice(pos, bytesUsed) + bytesUsed = buf.length + } + }) + }) + + req.on('error', function (err) { + self.connectionInProgress = false + onConnectionClosed(err.message) + }) + + if (req.setNoDelay) req.setNoDelay(true) + req.end() + } + + connect() + + function _emit () { + if (self.listeners(arguments[0]).length > 0) { + self.emit.apply(self, arguments) + } + } + + this._close = function () { + if (readyState === EventSource.CLOSED) return + readyState = EventSource.CLOSED + if (req.abort) req.abort() + if (req.xhr && req.xhr.abort) req.xhr.abort() + } + + function parseEventStreamLine (buf, pos, fieldLength, lineLength) { + if (lineLength === 0) { + if (data.length > 0) { + var type = eventName || 'message' + _emit(type, new MessageEvent(type, { + data: data.slice(0, -1), // remove trailing newline + lastEventId: lastEventId, + origin: new URL(url).origin + })) + data = '' + } + eventName = void 0 + } else if (fieldLength > 0) { + var noValue = fieldLength < 0 + var step = 0 + var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString() + + if (noValue) { + step = lineLength + } else if (buf[pos + fieldLength + 1] !== space) { + step = fieldLength + 1 + } else { + step = fieldLength + 2 + } + pos += step + + var valueLength = lineLength - step + var value = buf.slice(pos, pos + valueLength).toString() + + if (field === 'data') { + data += value + '\n' + } else if (field === 'event') { + eventName = value + } else if (field === 'id') { + lastEventId = value + } else if (field === 'retry') { + var retry = parseInt(value, 10) + if (!Number.isNaN(retry)) { + self.reconnectInterval = retry + } + } + } + } +} + +module.exports = EventSource + +util.inherits(EventSource, events.EventEmitter) +EventSource.prototype.constructor = EventSource; // make stacktraces readable + +['open', 'error', 'message'].forEach(function (method) { + Object.defineProperty(EventSource.prototype, 'on' + method, { + /** + * Returns the current listener + * + * @return {Mixed} the set function or undefined + * @api private + */ + get: function get () { + var listener = this.listeners(method)[0] + return listener ? (listener._listener ? listener._listener : listener) : undefined + }, + + /** + * Start listening for events + * + * @param {Function} listener the listener + * @return {Mixed} the set function or undefined + * @api private + */ + set: function set (listener) { + this.removeAllListeners(method) + this.addEventListener(method, listener) + } + }) +}) + +/** + * Ready states + */ +Object.defineProperty(EventSource, 'CONNECTING', {enumerable: true, value: 0}) +Object.defineProperty(EventSource, 'OPEN', {enumerable: true, value: 1}) +Object.defineProperty(EventSource, 'CLOSED', {enumerable: true, value: 2}) + +EventSource.prototype.CONNECTING = 0 +EventSource.prototype.OPEN = 1 +EventSource.prototype.CLOSED = 2 + +/** + * Closes the connection, if one is made, and sets the readyState attribute to 2 (closed) + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close + * @api public + */ +EventSource.prototype.close = function () { + this._close() +} + +/** + * Emulates the W3C Browser based WebSocket interface using addEventListener. + * + * @param {String} type A string representing the event type to listen out for + * @param {Function} listener callback + * @see https://developer.mozilla.org/en/DOM/element.addEventListener + * @see http://dev.w3.org/html5/websockets/#the-websocket-interface + * @api public + */ +EventSource.prototype.addEventListener = function addEventListener (type, listener) { + if (typeof listener === 'function') { + // store a reference so we can return the original function again + listener._listener = listener + this.on(type, listener) + } +} + +/** + * Emulates the W3C Browser based WebSocket interface using dispatchEvent. + * + * @param {Event} event An event to be dispatched + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent + * @api public + */ +EventSource.prototype.dispatchEvent = function dispatchEvent (event) { + if (!event.type) { + throw new Error('UNSPECIFIED_EVENT_TYPE_ERR') + } + // if event is instance of an CustomEvent (or has 'details' property), + // send the detail object as the payload for the event + this.emit(event.type, event.detail) +} + +/** + * Emulates the W3C Browser based WebSocket interface using removeEventListener. + * + * @param {String} type A string representing the event type to remove + * @param {Function} listener callback + * @see https://developer.mozilla.org/en/DOM/element.removeEventListener + * @see http://dev.w3.org/html5/websockets/#the-websocket-interface + * @api public + */ +EventSource.prototype.removeEventListener = function removeEventListener (type, listener) { + if (typeof listener === 'function') { + listener._listener = undefined + this.removeListener(type, listener) + } +} + +/** + * W3C Event + * + * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event + * @api private + */ +function Event (type, optionalProperties) { + Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) + if (optionalProperties) { + for (var f in optionalProperties) { + if (optionalProperties.hasOwnProperty(f)) { + Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true }) + } + } + } +} + +/** + * W3C MessageEvent + * + * @see http://www.w3.org/TR/webmessaging/#event-definitions + * @api private + */ +function MessageEvent (type, eventInitDict) { + Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) + for (var f in eventInitDict) { + if (eventInitDict.hasOwnProperty(f)) { + Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true }) + } + } +} + +/** + * Returns a new object of headers that does not include any authorization and cookie headers + * + * @param {Object} headers An object of headers ({[headerName]: headerValue}) + * @return {Object} a new object of headers + * @api private + */ +function removeUnsafeHeaders (headers) { + var safe = {} + for (var key in headers) { + if (reUnsafeHeader.test(key)) { + continue + } + + safe[key] = headers[key] + } + + return safe +} + + +/***/ }), + +/***/ 2682: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isCallable = __webpack_require__(9600); + +var toStr = Object.prototype.toString; +var hasOwnProperty = Object.prototype.hasOwnProperty; + +var forEachArray = function forEachArray(array, iterator, receiver) { + for (var i = 0, len = array.length; i < len; i++) { + if (hasOwnProperty.call(array, i)) { + if (receiver == null) { + iterator(array[i], i, array); + } else { + iterator.call(receiver, array[i], i, array); + } + } + } +}; + +var forEachString = function forEachString(string, iterator, receiver) { + for (var i = 0, len = string.length; i < len; i++) { + // no such thing as a sparse string. + if (receiver == null) { + iterator(string.charAt(i), i, string); + } else { + iterator.call(receiver, string.charAt(i), i, string); + } + } +}; + +var forEachObject = function forEachObject(object, iterator, receiver) { + for (var k in object) { + if (hasOwnProperty.call(object, k)) { + if (receiver == null) { + iterator(object[k], k, object); + } else { + iterator.call(receiver, object[k], k, object); + } + } + } +}; + +var forEach = function forEach(list, iterator, thisArg) { + if (!isCallable(iterator)) { + throw new TypeError('iterator must be a function'); + } + + var receiver; + if (arguments.length >= 3) { + receiver = thisArg; + } + + if (toStr.call(list) === '[object Array]') { + forEachArray(list, iterator, receiver); + } else if (typeof list === 'string') { + forEachString(list, iterator, receiver); + } else { + forEachObject(list, iterator, receiver); + } +}; + +module.exports = forEach; + + +/***/ }), + +/***/ 1734: +/***/ ((module) => { + +"use strict"; + + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + + +/***/ }), + +/***/ 6743: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var implementation = __webpack_require__(1734); + +module.exports = Function.prototype.bind || implementation; + + +/***/ }), + +/***/ 453: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var undefined; + +var $Object = __webpack_require__(9612); + +var $Error = __webpack_require__(9383); +var $EvalError = __webpack_require__(1237); +var $RangeError = __webpack_require__(9290); +var $ReferenceError = __webpack_require__(9538); +var $SyntaxError = __webpack_require__(8068); +var $TypeError = __webpack_require__(9675); +var $URIError = __webpack_require__(5345); + +var abs = __webpack_require__(1514); +var floor = __webpack_require__(8968); +var max = __webpack_require__(6188); +var min = __webpack_require__(8002); +var pow = __webpack_require__(5880); + +var $Function = Function; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = __webpack_require__(5795); +var $defineProperty = __webpack_require__(655); + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = __webpack_require__(4039)(); +var getDunderProto = __webpack_require__(7176); + +var getProto = (typeof Reflect === 'function' && Reflect.getPrototypeOf) + || $Object.getPrototypeOf + || getDunderProto; + +var $apply = __webpack_require__(1002); +var $call = __webpack_require__(76); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': $Object, + '%Object.getOwnPropertyDescriptor%': $gOPD, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, + + '%Function.prototype.call%': $call, + '%Function.prototype.apply%': $apply, + '%Object.defineProperty%': $defineProperty, + '%Math.abs%': abs, + '%Math.floor%': floor, + '%Math.max%': max, + '%Math.min%': min, + '%Math.pow%': pow +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = __webpack_require__(6743); +var hasOwn = __webpack_require__(9957); +var $concat = bind.call($call, Array.prototype.concat); +var $spliceApply = bind.call($apply, Array.prototype.splice); +var $replace = bind.call($call, String.prototype.replace); +var $strSlice = bind.call($call, String.prototype.slice); +var $exec = bind.call($call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; + + +/***/ }), + +/***/ 6549: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./gOPD')} */ +module.exports = Object.getOwnPropertyDescriptor; + + +/***/ }), + +/***/ 5795: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/** @type {import('.')} */ +var $gOPD = __webpack_require__(6549); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; + + +/***/ }), + +/***/ 592: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var $defineProperty = __webpack_require__(655); + +var hasPropertyDescriptors = function hasPropertyDescriptors() { + return !!$defineProperty; +}; + +hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + // node v0.6 has a bug where array lengths can be Set but not Defined + if (!$defineProperty) { + return null; + } + try { + return $defineProperty([], 'length', { value: 1 }).length !== 1; + } catch (e) { + // In Firefox 4-22, defining length on an array throws an exception. + return true; + } +}; + +module.exports = hasPropertyDescriptors; + + +/***/ }), + +/***/ 4039: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = __webpack_require__(1333); + +/** @type {import('.')} */ +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; + + +/***/ }), + +/***/ 1333: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./shams')} */ +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + /** @type {{ [k in symbol]?: unknown }} */ + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + // eslint-disable-next-line no-extra-parens + var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; + + +/***/ }), + +/***/ 9092: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hasSymbols = __webpack_require__(1333); + +/** @type {import('.')} */ +module.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; +}; + + +/***/ }), + +/***/ 9957: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = __webpack_require__(6743); + +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); + + +/***/ }), + +/***/ 1083: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var http = __webpack_require__(1568) +var url = __webpack_require__(8835) + +var https = module.exports + +for (var key in http) { + if (http.hasOwnProperty(key)) https[key] = http[key] +} + +https.request = function (params, cb) { + params = validateParams(params) + return http.request.call(this, params, cb) +} + +https.get = function (params, cb) { + params = validateParams(params) + return http.get.call(this, params, cb) +} + +function validateParams (params) { + if (typeof params === 'string') { + params = url.parse(params) + } + if (!params.protocol) { + params.protocol = 'https:' + } + if (params.protocol !== 'https:') { + throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"') + } + return params +} + + +/***/ }), + +/***/ 251: +/***/ ((__unused_webpack_module, exports) => { + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + + +/***/ }), + +/***/ 6698: +/***/ ((module) => { + +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 + } + } +} + + +/***/ }), + +/***/ 7244: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hasToStringTag = __webpack_require__(9092)(); +var callBound = __webpack_require__(6556); + +var $toString = callBound('Object.prototype.toString'); + +/** @type {import('.')} */ +var isStandardArguments = function isArguments(value) { + if ( + hasToStringTag + && value + && typeof value === 'object' + && Symbol.toStringTag in value + ) { + return false; + } + return $toString(value) === '[object Arguments]'; +}; + +/** @type {import('.')} */ +var isLegacyArguments = function isArguments(value) { + if (isStandardArguments(value)) { + return true; + } + return value !== null + && typeof value === 'object' + && 'length' in value + && typeof value.length === 'number' + && value.length >= 0 + && $toString(value) !== '[object Array]' + && 'callee' in value + && $toString(value.callee) === '[object Function]'; +}; + +var supportsStandardArguments = (function () { + return isStandardArguments(arguments); +}()); + +// @ts-expect-error TODO make this not error +isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests + +/** @type {import('.')} */ +module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; + + +/***/ }), + +/***/ 9600: +/***/ ((module) => { + +"use strict"; + + +var fnToStr = Function.prototype.toString; +var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply; +var badArrayLike; +var isCallableMarker; +if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') { + try { + badArrayLike = Object.defineProperty({}, 'length', { + get: function () { + throw isCallableMarker; + } + }); + isCallableMarker = {}; + // eslint-disable-next-line no-throw-literal + reflectApply(function () { throw 42; }, null, badArrayLike); + } catch (_) { + if (_ !== isCallableMarker) { + reflectApply = null; + } + } +} else { + reflectApply = null; +} + +var constructorRegex = /^\s*class\b/; +var isES6ClassFn = function isES6ClassFunction(value) { + try { + var fnStr = fnToStr.call(value); + return constructorRegex.test(fnStr); + } catch (e) { + return false; // not a function + } +}; + +var tryFunctionObject = function tryFunctionToStr(value) { + try { + if (isES6ClassFn(value)) { return false; } + fnToStr.call(value); + return true; + } catch (e) { + return false; + } +}; +var toStr = Object.prototype.toString; +var objectClass = '[object Object]'; +var fnClass = '[object Function]'; +var genClass = '[object GeneratorFunction]'; +var ddaClass = '[object HTMLAllCollection]'; // IE 11 +var ddaClass2 = '[object HTML document.all class]'; +var ddaClass3 = '[object HTMLCollection]'; // IE 9-10 +var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag` + +var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing + +var isDDA = function isDocumentDotAll() { return false; }; +if (typeof document === 'object') { + // Firefox 3 canonicalizes DDA to undefined when it's not accessed directly + var all = document.all; + if (toStr.call(all) === toStr.call(document.all)) { + isDDA = function isDocumentDotAll(value) { + /* globals document: false */ + // in IE 6-8, typeof document.all is "object" and it's truthy + if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) { + try { + var str = toStr.call(value); + return ( + str === ddaClass + || str === ddaClass2 + || str === ddaClass3 // opera 12.16 + || str === objectClass // IE 6-8 + ) && value('') == null; // eslint-disable-line eqeqeq + } catch (e) { /**/ } + } + return false; + }; + } +} + +module.exports = reflectApply + ? function isCallable(value) { + if (isDDA(value)) { return true; } + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + try { + reflectApply(value, null, badArrayLike); + } catch (e) { + if (e !== isCallableMarker) { return false; } + } + return !isES6ClassFn(value) && tryFunctionObject(value); + } + : function isCallable(value) { + if (isDDA(value)) { return true; } + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + if (hasToStringTag) { return tryFunctionObject(value); } + if (isES6ClassFn(value)) { return false; } + var strClass = toStr.call(value); + if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; } + return tryFunctionObject(value); + }; + + +/***/ }), + +/***/ 8184: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var toStr = Object.prototype.toString; +var fnToStr = Function.prototype.toString; +var isFnRegex = /^\s*(?:function)?\*/; +var hasToStringTag = __webpack_require__(9092)(); +var getProto = Object.getPrototypeOf; +var getGeneratorFunc = function () { // eslint-disable-line consistent-return + if (!hasToStringTag) { + return false; + } + try { + return Function('return function*() {}')(); + } catch (e) { + } +}; +var GeneratorFunction; + +module.exports = function isGeneratorFunction(fn) { + if (typeof fn !== 'function') { + return false; + } + if (isFnRegex.test(fnToStr.call(fn))) { + return true; + } + if (!hasToStringTag) { + var str = toStr.call(fn); + return str === '[object GeneratorFunction]'; + } + if (!getProto) { + return false; + } + if (typeof GeneratorFunction === 'undefined') { + var generatorFunc = getGeneratorFunc(); + GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; + } + return getProto(fn) === GeneratorFunction; +}; + + +/***/ }), + +/***/ 5680: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var whichTypedArray = __webpack_require__(5767); + +/** @type {import('.')} */ +module.exports = function isTypedArray(value) { + return !!whichTypedArray(value); +}; + + +/***/ }), + +/***/ 1514: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./abs')} */ +module.exports = Math.abs; + + +/***/ }), + +/***/ 8968: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./abs')} */ +module.exports = Math.floor; + + +/***/ }), + +/***/ 6188: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./max')} */ +module.exports = Math.max; + + +/***/ }), + +/***/ 8002: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./min')} */ +module.exports = Math.min; + + +/***/ }), + +/***/ 5880: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./pow')} */ +module.exports = Math.pow; + + +/***/ }), + +/***/ 8859: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var hasMap = typeof Map === 'function' && Map.prototype; +var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; +var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; +var mapForEach = hasMap && Map.prototype.forEach; +var hasSet = typeof Set === 'function' && Set.prototype; +var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; +var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; +var setForEach = hasSet && Set.prototype.forEach; +var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; +var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; +var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; +var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; +var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; +var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; +var booleanValueOf = Boolean.prototype.valueOf; +var objectToString = Object.prototype.toString; +var functionToString = Function.prototype.toString; +var $match = String.prototype.match; +var $slice = String.prototype.slice; +var $replace = String.prototype.replace; +var $toUpperCase = String.prototype.toUpperCase; +var $toLowerCase = String.prototype.toLowerCase; +var $test = RegExp.prototype.test; +var $concat = Array.prototype.concat; +var $join = Array.prototype.join; +var $arrSlice = Array.prototype.slice; +var $floor = Math.floor; +var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; +var gOPS = Object.getOwnPropertySymbols; +var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; +var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; +// ie, `has-tostringtag/shams +var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') + ? Symbol.toStringTag + : null; +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( + [].__proto__ === Array.prototype // eslint-disable-line no-proto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null +); + +function addNumericSeparator(num, str) { + if ( + num === Infinity + || num === -Infinity + || num !== num + || (num && num > -1000 && num < 1000) + || $test.call(/e/, str) + ) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); +} + +var utilInspect = __webpack_require__(2634); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + +var quotes = { + __proto__: null, + 'double': '"', + single: "'" +}; +var quoteREs = { + __proto__: null, + 'double': /(["\\])/g, + single: /(['\\])/g +}; + +module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + + if (has(opts, 'quoteStyle') && !has(quotes, opts.quoteStyle)) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if ( + has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' + ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity + : opts.maxStringLength !== null + ) + ) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } + + if ( + has(opts, 'indent') + && opts.indent !== null + && opts.indent !== '\t' + && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) + ) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { depth = 0; } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray(obj) ? '[Array]' : '[Object]'; + } + + var indent = getIndent(opts, depth); + + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { s += '...'; } + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { return '[]'; } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { return '[' + String(obj) + ']'; } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + } + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + // note: in IE 8, sometimes `global !== window` but both are the prototypes of each other + /* eslint-env browser */ + if (typeof window !== 'undefined' && obj === window) { + return '{ [object Window] }'; + } + if ( + (typeof globalThis !== 'undefined' && obj === globalThis) + || (typeof __webpack_require__.g !== 'undefined' && obj === __webpack_require__.g) + ) { + return '{ [object globalThis] }'; + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { return tag + '{}'; } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); +}; + +function wrapQuotes(s, defaultStyle, opts) { + var style = opts.quoteStyle || defaultStyle; + var quoteChar = quotes[style]; + return quoteChar + s + quoteChar; +} + +function quote(s) { + return $replace.call(String(s), /"/g, '"'); +} + +function isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } + +// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives +function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; +} + +function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; +} + +var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; +function has(obj, key) { + return hasOwn.call(obj, key); +} + +function toStr(obj) { + return objectToString.call(obj); +} + +function nameOf(f) { + if (f.name) { return f.name; } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { return m[1]; } + return null; +} + +function indexOf(xs, x) { + if (xs.indexOf) { return xs.indexOf(x); } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { return i; } + } + return -1; +} + +function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; +} + +function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isElement(x) { + if (!x || typeof x !== 'object') { return false; } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; +} + +function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + var quoteRE = quoteREs[opts.quoteStyle || 'single']; + quoteRE.lastIndex = 0; + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, quoteRE, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} + +function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { return '\\' + x; } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); +} + +function markBoxed(str) { + return 'Object(' + str + ')'; +} + +function weakCollectionOf(type) { + return type + ' { ? }'; +} + +function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; +} + +function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; +} + +function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; +} + +function indentedJoin(xs, indent) { + if (xs.length === 0) { return ''; } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; +} + +function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; +} + + +/***/ }), + +/***/ 6578: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +module.exports = [ + 'Float32Array', + 'Float64Array', + 'Int8Array', + 'Int16Array', + 'Int32Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Uint16Array', + 'Uint32Array', + 'BigInt64Array', + 'BigUint64Array' +]; + + +/***/ }), + +/***/ 4765: +/***/ ((module) => { + +"use strict"; + + +var replace = String.prototype.replace; +var percentTwenties = /%20/g; + +var Format = { + RFC1738: 'RFC1738', + RFC3986: 'RFC3986' +}; + +module.exports = { + 'default': Format.RFC3986, + formatters: { + RFC1738: function (value) { + return replace.call(value, percentTwenties, '+'); + }, + RFC3986: function (value) { + return String(value); + } + }, + RFC1738: Format.RFC1738, + RFC3986: Format.RFC3986 +}; + + +/***/ }), + +/***/ 5373: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var stringify = __webpack_require__(8636); +var parse = __webpack_require__(2642); +var formats = __webpack_require__(4765); + +module.exports = { + formats: formats, + parse: parse, + stringify: stringify +}; + + +/***/ }), + +/***/ 2642: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(7720); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var defaults = { + allowDots: false, + allowEmptyArrays: false, + allowPrototypes: false, + allowSparse: false, + arrayLimit: 20, + charset: 'utf-8', + charsetSentinel: false, + comma: false, + decodeDotInKeys: false, + decoder: utils.decode, + delimiter: '&', + depth: 5, + duplicates: 'combine', + ignoreQueryPrefix: false, + interpretNumericEntities: false, + parameterLimit: 1000, + parseArrays: true, + plainObjects: false, + strictDepth: false, + strictNullHandling: false +}; + +var interpretNumericEntities = function (str) { + return str.replace(/&#(\d+);/g, function ($0, numberStr) { + return String.fromCharCode(parseInt(numberStr, 10)); + }); +}; + +var parseArrayValue = function (val, options) { + if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { + return val.split(','); + } + + return val; +}; + +// This is what browsers will submit when the ✓ character occurs in an +// application/x-www-form-urlencoded body and the encoding of the page containing +// the form is iso-8859-1, or when the submitted form has an accept-charset +// attribute of iso-8859-1. Presumably also with other charsets that do not contain +// the ✓ character, such as us-ascii. +var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') + +// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. +var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') + +var parseValues = function parseQueryStringValues(str, options) { + var obj = { __proto__: null }; + + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + cleanStr = cleanStr.replace(/%5B/gi, '[').replace(/%5D/gi, ']'); + var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; + var parts = cleanStr.split(options.delimiter, limit); + var skipIndex = -1; // Keep track of where the utf8 sentinel was found + var i; + + var charset = options.charset; + if (options.charsetSentinel) { + for (i = 0; i < parts.length; ++i) { + if (parts[i].indexOf('utf8=') === 0) { + if (parts[i] === charsetSentinel) { + charset = 'utf-8'; + } else if (parts[i] === isoSentinel) { + charset = 'iso-8859-1'; + } + skipIndex = i; + i = parts.length; // The eslint settings do not allow break; + } + } + } + + for (i = 0; i < parts.length; ++i) { + if (i === skipIndex) { + continue; + } + var part = parts[i]; + + var bracketEqualsPos = part.indexOf(']='); + var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; + + var key; + var val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset, 'key'); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); + val = utils.maybeMap( + parseArrayValue(part.slice(pos + 1), options), + function (encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, 'value'); + } + ); + } + + if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { + val = interpretNumericEntities(String(val)); + } + + if (part.indexOf('[]=') > -1) { + val = isArray(val) ? [val] : val; + } + + var existing = has.call(obj, key); + if (existing && options.duplicates === 'combine') { + obj[key] = utils.combine(obj[key], val); + } else if (!existing || options.duplicates === 'last') { + obj[key] = val; + } + } + + return obj; +}; + +var parseObject = function (chain, val, options, valuesParsed) { + var leaf = valuesParsed ? val : parseArrayValue(val, options); + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]' && options.parseArrays) { + obj = options.allowEmptyArrays && (leaf === '' || (options.strictNullHandling && leaf === null)) + ? [] + : [].concat(leaf); + } else { + obj = options.plainObjects ? { __proto__: null } : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, '.') : cleanRoot; + var index = parseInt(decodedRoot, 10); + if (!options.parseArrays && decodedRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== decodedRoot + && String(index) === decodedRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else if (decodedRoot !== '__proto__') { + obj[decodedRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = options.depth > 0 && brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, check strictDepth option for throw, else just add whatever is left + + if (segment) { + if (options.strictDepth === true) { + throw new RangeError('Input depth exceeded depth option of ' + options.depth + ' and strictDepth is true'); + } + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options, valuesParsed); +}; + +var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } + + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); + } + + if (typeof opts.decodeDotInKeys !== 'undefined' && typeof opts.decodeDotInKeys !== 'boolean') { + throw new TypeError('`decodeDotInKeys` option can only be `true` or `false`, when provided'); + } + + if (opts.decoder !== null && typeof opts.decoder !== 'undefined' && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; + + var duplicates = typeof opts.duplicates === 'undefined' ? defaults.duplicates : opts.duplicates; + + if (duplicates !== 'combine' && duplicates !== 'first' && duplicates !== 'last') { + throw new TypeError('The duplicates option must be either combine, first, or last'); + } + + var allowDots = typeof opts.allowDots === 'undefined' ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + + return { + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, + decodeDotInKeys: typeof opts.decodeDotInKeys === 'boolean' ? opts.decodeDotInKeys : defaults.decodeDotInKeys, + decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, + duplicates: duplicates, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, + strictDepth: typeof opts.strictDepth === 'boolean' ? !!opts.strictDepth : defaults.strictDepth, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (str, opts) { + var options = normalizeParseOptions(opts); + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? { __proto__: null } : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? { __proto__: null } : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); + obj = utils.merge(obj, newObj, options); + } + + if (options.allowSparse === true) { + return obj; + } + + return utils.compact(obj); +}; + + +/***/ }), + +/***/ 8636: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var getSideChannel = __webpack_require__(920); +var utils = __webpack_require__(7720); +var formats = __webpack_require__(4765); +var has = Object.prototype.hasOwnProperty; + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { + return prefix; + } +}; + +var isArray = Array.isArray; +var push = Array.prototype.push; +var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); +}; + +var toISO = Date.prototype.toISOString; + +var defaultFormat = formats['default']; +var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: 'indices', + charset: 'utf-8', + charsetSentinel: false, + commaRoundTrip: false, + delimiter: '&', + encode: true, + encodeDotInKeys: false, + encoder: utils.encode, + encodeValuesOnly: false, + filter: void undefined, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var isNonNullishPrimitive = function isNonNullishPrimitive(v) { + return typeof v === 'string' + || typeof v === 'number' + || typeof v === 'boolean' + || typeof v === 'symbol' + || typeof v === 'bigint'; +}; + +var sentinel = {}; + +var stringify = function stringify( + object, + prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + sideChannel +) { + var obj = object; + + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { + // Where object last appeared in the ref tree + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } else { + findFlag = true; // Break while + } + } + if (typeof tmpSc.get(sentinel) === 'undefined') { + step = 0; + } + } + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = utils.maybeMap(obj, function (value) { + if (value instanceof Date) { + return serializeDate(value); + } + return value; + }); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix; + } + + obj = ''; + } + + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (generateArrayPrefix === 'comma' && isArray(obj)) { + // we need to join elements in + if (encodeValuesOnly && encoder) { + obj = utils.maybeMap(obj, encoder); + } + objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; + } else if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + var encodedPrefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); + + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + '[]' : encodedPrefix; + + if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + return adjustedPrefix + '[]'; + } + + for (var j = 0; j < objKeys.length; ++j) { + var key = objKeys[j]; + var value = typeof key === 'object' && key && typeof key.value !== 'undefined' + ? key.value + : obj[key]; + + if (skipNulls && value === null) { + continue; + } + + var encodedKey = allowDots && encodeDotInKeys ? String(key).replace(/\./g, '%2E') : String(key); + var keyPrefix = isArray(obj) + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + encodedKey : '[' + encodedKey + ']'); + + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values, stringify( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + + return values; +}; + +var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; + } + + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); + } + + if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { + throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); + } + + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + var format = formats['default']; + if (typeof opts.format !== 'undefined') { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + var arrayFormat; + if (opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if ('indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = defaults.arrayFormat; + } + + if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + + var allowDots = typeof opts.allowDots === 'undefined' ? opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat: arrayFormat, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat]; + var commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (options.sort) { + objKeys.sort(options.sort); + } + + var sideChannel = getSideChannel(); + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + var value = obj[key]; + + if (options.skipNulls && value === null) { + continue; + } + pushToArray(keys, stringify( + value, + key, + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + + return joined.length > 0 ? prefix + joined : ''; +}; + + +/***/ }), + +/***/ 7720: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var formats = __webpack_require__(4765); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } +}; + +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? { __proto__: null } : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +var merge = function merge(target, source, options) { + /* eslint no-param-reassign: 0 */ + if (!source) { + return target; + } + + if (typeof source !== 'object' && typeof source !== 'function') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ( + (options && (options.plainObjects || options.allowPrototypes)) + || !has.call(Object.prototype, source) + ) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +var decode = function (str, defaultDecoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } +}; + +var limit = 1024; + +/* eslint operator-linebreak: [2, "before"] */ + +var encode = function encode(str, defaultEncoder, charset, kind, format) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== 'string') { + string = String(str); + } + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var j = 0; j < string.length; j += limit) { + var segment = string.length >= limit ? string.slice(j, j + limit) : string; + var arr = []; + + for (var i = 0; i < segment.length; ++i) { + var c = segment.charCodeAt(i); + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + arr[arr.length] = segment.charAt(i); + continue; + } + + if (c < 0x80) { + arr[arr.length] = hexTable[c]; + continue; + } + + if (c < 0x800) { + arr[arr.length] = hexTable[0xC0 | (c >> 6)] + + hexTable[0x80 | (c & 0x3F)]; + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + arr[arr.length] = hexTable[0xE0 | (c >> 12)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (segment.charCodeAt(i) & 0x3FF)); + + arr[arr.length] = hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + out += arr.join(''); + } + + return out; +}; + +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + compactQueue(queue); + + return value; +}; + +var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +var isBuffer = function isBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +var combine = function combine(a, b) { + return [].concat(a, b); +}; + +var maybeMap = function maybeMap(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +}; + +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isRegExp: isRegExp, + maybeMap: maybeMap, + merge: merge +}; + + +/***/ }), + +/***/ 3209: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"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 = (__webpack_require__(2861).Buffer) +var crypto = __webpack_require__.g.crypto || __webpack_require__.g.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 +} + + +/***/ }), + +/***/ 6048: +/***/ ((module) => { + +"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.F = codes; + + +/***/ }), + +/***/ 5382: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// 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. + + + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; +/**/ + +module.exports = Duplex; +var Readable = __webpack_require__(5412); +var Writable = __webpack_require__(6708); +__webpack_require__(6698)(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; + } +}); + +/***/ }), + +/***/ 3600: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// 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. + + + +module.exports = PassThrough; +var Transform = __webpack_require__(4610); +__webpack_require__(6698)(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); +}; + +/***/ }), + +/***/ 5412: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// 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. + + + +module.exports = Readable; + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = (__webpack_require__(7007).EventEmitter); +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = __webpack_require__(345); +/**/ + +var Buffer = (__webpack_require__(8287).Buffer); +var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : 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 = __webpack_require__(9838); +var debug; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + +var BufferList = __webpack_require__(2726); +var destroyImpl = __webpack_require__(5896); +var _require = __webpack_require__(5291), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = (__webpack_require__(6048)/* .codes */ .F), + 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; +__webpack_require__(6698)(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 || __webpack_require__(5382); + 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 = (__webpack_require__(3141)/* .StringDecoder */ .I); + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || __webpack_require__(5382); + 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 = (__webpack_require__(3141)/* .StringDecoder */ .I); + 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 = __webpack_require__(2955); + } + 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 = __webpack_require__(5157); + } + 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; +} + +/***/ }), + +/***/ 4610: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// 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. + + + +module.exports = Transform; +var _require$codes = (__webpack_require__(6048)/* .codes */ .F), + 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 = __webpack_require__(5382); +__webpack_require__(6698)(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); +} + +/***/ }), + +/***/ 6708: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// 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. + + + +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: __webpack_require__(4643) +}; +/**/ + +/**/ +var Stream = __webpack_require__(345); +/**/ + +var Buffer = (__webpack_require__(8287).Buffer); +var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : 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 = __webpack_require__(5896); +var _require = __webpack_require__(5291), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = (__webpack_require__(6048)/* .codes */ .F), + 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; +__webpack_require__(6698)(Writable, Stream); +function nop() {} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || __webpack_require__(5382); + 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 || __webpack_require__(5382); + + // 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); +}; + +/***/ }), + +/***/ 2955: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"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 = __webpack_require__(6238); +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; + +/***/ }), + +/***/ 2726: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"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 = __webpack_require__(8287), + Buffer = _require.Buffer; +var _require2 = __webpack_require__(5340), + 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; +}(); + +/***/ }), + +/***/ 5896: +/***/ ((module) => { + +"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 +}; + +/***/ }), + +/***/ 6238: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + + + +var ERR_STREAM_PREMATURE_CLOSE = (__webpack_require__(6048)/* .codes */ .F).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; + +/***/ }), + +/***/ 5157: +/***/ ((module) => { + +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; + + +/***/ }), + +/***/ 7758: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + + + +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} +var _require$codes = (__webpack_require__(6048)/* .codes */ .F), + 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 = __webpack_require__(6238); + 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; + +/***/ }), + +/***/ 5291: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var ERR_INVALID_OPT_VALUE = (__webpack_require__(6048)/* .codes */ .F).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 +}; + +/***/ }), + +/***/ 345: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(7007).EventEmitter; + + +/***/ }), + +/***/ 8399: +/***/ ((module, exports, __webpack_require__) => { + +exports = module.exports = __webpack_require__(5412); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = __webpack_require__(6708); +exports.Duplex = __webpack_require__(5382); +exports.Transform = __webpack_require__(4610); +exports.PassThrough = __webpack_require__(3600); +exports.finished = __webpack_require__(6238); +exports.pipeline = __webpack_require__(7758); + + +/***/ }), + +/***/ 2861: +/***/ ((module, exports, __webpack_require__) => { + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(8287) +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) +} + + +/***/ }), + +/***/ 6897: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); +var define = __webpack_require__(41); +var hasDescriptors = __webpack_require__(592)(); +var gOPD = __webpack_require__(5795); + +var $TypeError = __webpack_require__(9675); +var $floor = GetIntrinsic('%Math.floor%'); + +/** @type {import('.')} */ +module.exports = function setFunctionLength(fn, length) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { + throw new $TypeError('`length` must be a positive 32-bit integer'); + } + + var loose = arguments.length > 2 && !!arguments[2]; + + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ('length' in fn && gOPD) { + var desc = gOPD(fn, 'length'); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define(/** @type {Parameters[0]} */ (fn), 'length', length, true, true); + } else { + define(/** @type {Parameters[0]} */ (fn), 'length', length); + } + } + return fn; +}; + + +/***/ }), + +/***/ 392: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2802: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +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 = __webpack_require__(7816) +exports.sha1 = __webpack_require__(3737) +exports.sha224 = __webpack_require__(6710) +exports.sha256 = __webpack_require__(4107) +exports.sha384 = __webpack_require__(2827) +exports.sha512 = __webpack_require__(2890) + + +/***/ }), + +/***/ 7816: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 3737: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 6710: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * 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 = __webpack_require__(6698) +var Sha256 = __webpack_require__(4107) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 4107: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2827: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698) +var SHA512 = __webpack_require__(2890) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2890: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 4803: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var inspect = __webpack_require__(8859); + +var $TypeError = __webpack_require__(9675); + +/* +* This function traverses the list returning the node corresponding to the given key. +* +* That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. +* By doing so, all the recently used nodes can be accessed relatively quickly. +*/ +/** @type {import('./list.d.ts').listGetNode} */ +// eslint-disable-next-line consistent-return +var listGetNode = function (list, key, isDelete) { + /** @type {typeof list | NonNullable<(typeof list)['next']>} */ + var prev = list; + /** @type {(typeof list)['next']} */ + var curr; + // eslint-disable-next-line eqeqeq + for (; (curr = prev.next) != null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + if (!isDelete) { + // eslint-disable-next-line no-extra-parens + curr.next = /** @type {NonNullable} */ (list.next); + list.next = curr; // eslint-disable-line no-param-reassign + } + return curr; + } + } +}; + +/** @type {import('./list.d.ts').listGet} */ +var listGet = function (objects, key) { + if (!objects) { + return void undefined; + } + var node = listGetNode(objects, key); + return node && node.value; +}; +/** @type {import('./list.d.ts').listSet} */ +var listSet = function (objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + // Prepend the new node to the beginning of the list + objects.next = /** @type {import('./list.d.ts').ListNode} */ ({ // eslint-disable-line no-param-reassign, no-extra-parens + key: key, + next: objects.next, + value: value + }); + } +}; +/** @type {import('./list.d.ts').listHas} */ +var listHas = function (objects, key) { + if (!objects) { + return false; + } + return !!listGetNode(objects, key); +}; +/** @type {import('./list.d.ts').listDelete} */ +// eslint-disable-next-line consistent-return +var listDelete = function (objects, key) { + if (objects) { + return listGetNode(objects, key, true); + } +}; + +/** @type {import('.')} */ +module.exports = function getSideChannelList() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {import('./list.d.ts').RootNode | undefined} */ var $o; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + var root = $o && $o.next; + var deletedNode = listDelete($o, key); + if (deletedNode && root && root === deletedNode) { + $o = void undefined; + } + return !!deletedNode; + }, + get: function (key) { + return listGet($o, key); + }, + has: function (key) { + return listHas($o, key); + }, + set: function (key, value) { + if (!$o) { + // Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head + $o = { + next: void undefined + }; + } + // eslint-disable-next-line no-extra-parens + listSet(/** @type {NonNullable} */ ($o), key, value); + } + }; + // @ts-expect-error TODO: figure out why this is erroring + return channel; +}; + + +/***/ }), + +/***/ 507: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); +var callBound = __webpack_require__(6556); +var inspect = __webpack_require__(8859); + +var $TypeError = __webpack_require__(9675); +var $Map = GetIntrinsic('%Map%', true); + +/** @type {(thisArg: Map, key: K) => V} */ +var $mapGet = callBound('Map.prototype.get', true); +/** @type {(thisArg: Map, key: K, value: V) => void} */ +var $mapSet = callBound('Map.prototype.set', true); +/** @type {(thisArg: Map, key: K) => boolean} */ +var $mapHas = callBound('Map.prototype.has', true); +/** @type {(thisArg: Map, key: K) => boolean} */ +var $mapDelete = callBound('Map.prototype.delete', true); +/** @type {(thisArg: Map) => number} */ +var $mapSize = callBound('Map.prototype.size', true); + +/** @type {import('.')} */ +module.exports = !!$Map && /** @type {Exclude} */ function getSideChannelMap() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {Map | undefined} */ var $m; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + if ($m) { + var result = $mapDelete($m, key); + if ($mapSize($m) === 0) { + $m = void undefined; + } + return result; + } + return false; + }, + get: function (key) { // eslint-disable-line consistent-return + if ($m) { + return $mapGet($m, key); + } + }, + has: function (key) { + if ($m) { + return $mapHas($m, key); + } + return false; + }, + set: function (key, value) { + if (!$m) { + // @ts-expect-error TS can't handle narrowing a variable inside a closure + $m = new $Map(); + } + $mapSet($m, key, value); + } + }; + + // @ts-expect-error TODO: figure out why TS is erroring here + return channel; +}; + + +/***/ }), + +/***/ 2271: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); +var callBound = __webpack_require__(6556); +var inspect = __webpack_require__(8859); +var getSideChannelMap = __webpack_require__(507); + +var $TypeError = __webpack_require__(9675); +var $WeakMap = GetIntrinsic('%WeakMap%', true); + +/** @type {(thisArg: WeakMap, key: K) => V} */ +var $weakMapGet = callBound('WeakMap.prototype.get', true); +/** @type {(thisArg: WeakMap, key: K, value: V) => void} */ +var $weakMapSet = callBound('WeakMap.prototype.set', true); +/** @type {(thisArg: WeakMap, key: K) => boolean} */ +var $weakMapHas = callBound('WeakMap.prototype.has', true); +/** @type {(thisArg: WeakMap, key: K) => boolean} */ +var $weakMapDelete = callBound('WeakMap.prototype.delete', true); + +/** @type {import('.')} */ +module.exports = $WeakMap + ? /** @type {Exclude} */ function getSideChannelWeakMap() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {WeakMap | undefined} */ var $wm; + /** @type {Channel | undefined} */ var $m; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapDelete($wm, key); + } + } else if (getSideChannelMap) { + if ($m) { + return $m['delete'](key); + } + } + return false; + }, + get: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } + return $m && $m.get(key); + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } + return !!$m && $m.has(key); + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if (getSideChannelMap) { + if (!$m) { + $m = getSideChannelMap(); + } + // eslint-disable-next-line no-extra-parens + /** @type {NonNullable} */ ($m).set(key, value); + } + } + }; + + // @ts-expect-error TODO: figure out why this is erroring + return channel; + } + : getSideChannelMap; + + +/***/ }), + +/***/ 920: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var $TypeError = __webpack_require__(9675); +var inspect = __webpack_require__(8859); +var getSideChannelList = __webpack_require__(4803); +var getSideChannelMap = __webpack_require__(507); +var getSideChannelWeakMap = __webpack_require__(2271); + +var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList; + +/** @type {import('.')} */ +module.exports = function getSideChannel() { + /** @typedef {ReturnType} Channel */ + + /** @type {Channel | undefined} */ var $channelData; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + return !!$channelData && $channelData['delete'](key); + }, + get: function (key) { + return $channelData && $channelData.get(key); + }, + has: function (key) { + return !!$channelData && $channelData.has(key); + }, + set: function (key, value) { + if (!$channelData) { + $channelData = makeChannel(); + } + + $channelData.set(key, value); + } + }; + // @ts-expect-error TODO: figure out why this is erroring + return channel; +}; + + +/***/ }), + +/***/ 1568: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var ClientRequest = __webpack_require__(5537) +var response = __webpack_require__(6917) +var extend = __webpack_require__(7510) +var statusCodes = __webpack_require__(6866) +var url = __webpack_require__(8835) + +var http = exports + +http.request = function (opts, cb) { + if (typeof opts === 'string') + opts = url.parse(opts) + else + opts = extend(opts) + + // Normally, the page is loaded from http or https, so not specifying a protocol + // will result in a (valid) protocol-relative url. However, this won't work if + // the protocol is something else, like 'file:' + var defaultProtocol = __webpack_require__.g.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' + + var protocol = opts.protocol || defaultProtocol + var host = opts.hostname || opts.host + var port = opts.port + var path = opts.path || '/' + + // Necessary for IPv6 addresses + if (host && host.indexOf(':') !== -1) + host = '[' + host + ']' + + // This may be a relative url. The browser should always be able to interpret it correctly. + opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path + opts.method = (opts.method || 'GET').toUpperCase() + opts.headers = opts.headers || {} + + // Also valid opts.auth, opts.mode + + var req = new ClientRequest(opts) + if (cb) + req.on('response', cb) + return req +} + +http.get = function get (opts, cb) { + var req = http.request(opts, cb) + req.end() + return req +} + +http.ClientRequest = ClientRequest +http.IncomingMessage = response.IncomingMessage + +http.Agent = function () {} +http.Agent.defaultMaxSockets = 4 + +http.globalAgent = new http.Agent() + +http.STATUS_CODES = statusCodes + +http.METHODS = [ + 'CHECKOUT', + 'CONNECT', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LOCK', + 'M-SEARCH', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MOVE', + 'NOTIFY', + 'OPTIONS', + 'PATCH', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PURGE', + 'PUT', + 'REPORT', + 'SEARCH', + 'SUBSCRIBE', + 'TRACE', + 'UNLOCK', + 'UNSUBSCRIBE' +] + +/***/ }), + +/***/ 6688: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +exports.fetch = isFunction(__webpack_require__.g.fetch) && isFunction(__webpack_require__.g.ReadableStream) + +exports.writableStream = isFunction(__webpack_require__.g.WritableStream) + +exports.abortController = isFunction(__webpack_require__.g.AbortController) + +// The xhr request to example.com may violate some restrictive CSP configurations, +// so if we're running in a browser that supports `fetch`, avoid calling getXHR() +// and assume support for certain features below. +var xhr +function getXHR () { + // Cache the xhr value + if (xhr !== undefined) return xhr + + if (__webpack_require__.g.XMLHttpRequest) { + xhr = new __webpack_require__.g.XMLHttpRequest() + // If XDomainRequest is available (ie only, where xhr might not work + // cross domain), use the page location. Otherwise use example.com + // Note: this doesn't actually make an http request. + try { + xhr.open('GET', __webpack_require__.g.XDomainRequest ? '/' : 'https://example.com') + } catch(e) { + xhr = null + } + } else { + // Service workers don't have XHR + xhr = null + } + return xhr +} + +function checkTypeSupport (type) { + var xhr = getXHR() + if (!xhr) return false + try { + xhr.responseType = type + return xhr.responseType === type + } catch (e) {} + return false +} + +// If fetch is supported, then arraybuffer will be supported too. Skip calling +// checkTypeSupport(), since that calls getXHR(). +exports.arraybuffer = exports.fetch || checkTypeSupport('arraybuffer') + +// These next two tests unavoidably show warnings in Chrome. Since fetch will always +// be used if it's available, just return false for these to avoid the warnings. +exports.msstream = !exports.fetch && checkTypeSupport('ms-stream') +exports.mozchunkedarraybuffer = !exports.fetch && checkTypeSupport('moz-chunked-arraybuffer') + +// If fetch is supported, then overrideMimeType will be supported too. Skip calling +// getXHR(). +exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false) + +function isFunction (value) { + return typeof value === 'function' +} + +xhr = null // Help gc + + +/***/ }), + +/***/ 5537: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +var capability = __webpack_require__(6688) +var inherits = __webpack_require__(6698) +var response = __webpack_require__(6917) +var stream = __webpack_require__(8399) + +var IncomingMessage = response.IncomingMessage +var rStates = response.readyStates + +function decideMode (preferBinary, useFetch) { + if (capability.fetch && useFetch) { + return 'fetch' + } else if (capability.mozchunkedarraybuffer) { + return 'moz-chunked-arraybuffer' + } else if (capability.msstream) { + return 'ms-stream' + } else if (capability.arraybuffer && preferBinary) { + return 'arraybuffer' + } else { + return 'text' + } +} + +var ClientRequest = module.exports = function (opts) { + var self = this + stream.Writable.call(self) + + self._opts = opts + self._body = [] + self._headers = {} + if (opts.auth) + self.setHeader('Authorization', 'Basic ' + Buffer.from(opts.auth).toString('base64')) + Object.keys(opts.headers).forEach(function (name) { + self.setHeader(name, opts.headers[name]) + }) + + var preferBinary + var useFetch = true + if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) { + // If the use of XHR should be preferred. Not typically needed. + useFetch = false + preferBinary = true + } else if (opts.mode === 'prefer-streaming') { + // If streaming is a high priority but binary compatibility and + // the accuracy of the 'content-type' header aren't + preferBinary = false + } else if (opts.mode === 'allow-wrong-content-type') { + // If streaming is more important than preserving the 'content-type' header + preferBinary = !capability.overrideMimeType + } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { + // Use binary if text streaming may corrupt data or the content-type header, or for speed + preferBinary = true + } else { + throw new Error('Invalid value for opts.mode') + } + self._mode = decideMode(preferBinary, useFetch) + self._fetchTimer = null + self._socketTimeout = null + self._socketTimer = null + + self.on('finish', function () { + self._onFinish() + }) +} + +inherits(ClientRequest, stream.Writable) + +ClientRequest.prototype.setHeader = function (name, value) { + var self = this + var lowerName = name.toLowerCase() + // This check is not necessary, but it prevents warnings from browsers about setting unsafe + // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but + // http-browserify did it, so I will too. + if (unsafeHeaders.indexOf(lowerName) !== -1) + return + + self._headers[lowerName] = { + name: name, + value: value + } +} + +ClientRequest.prototype.getHeader = function (name) { + var header = this._headers[name.toLowerCase()] + if (header) + return header.value + return null +} + +ClientRequest.prototype.removeHeader = function (name) { + var self = this + delete self._headers[name.toLowerCase()] +} + +ClientRequest.prototype._onFinish = function () { + var self = this + + if (self._destroyed) + return + var opts = self._opts + + if ('timeout' in opts && opts.timeout !== 0) { + self.setTimeout(opts.timeout) + } + + var headersObj = self._headers + var body = null + if (opts.method !== 'GET' && opts.method !== 'HEAD') { + body = new Blob(self._body, { + type: (headersObj['content-type'] || {}).value || '' + }); + } + + // create flattened list of headers + var headersList = [] + Object.keys(headersObj).forEach(function (keyName) { + var name = headersObj[keyName].name + var value = headersObj[keyName].value + if (Array.isArray(value)) { + value.forEach(function (v) { + headersList.push([name, v]) + }) + } else { + headersList.push([name, value]) + } + }) + + if (self._mode === 'fetch') { + var signal = null + if (capability.abortController) { + var controller = new AbortController() + signal = controller.signal + self._fetchAbortController = controller + + if ('requestTimeout' in opts && opts.requestTimeout !== 0) { + self._fetchTimer = __webpack_require__.g.setTimeout(function () { + self.emit('requestTimeout') + if (self._fetchAbortController) + self._fetchAbortController.abort() + }, opts.requestTimeout) + } + } + + __webpack_require__.g.fetch(self._opts.url, { + method: self._opts.method, + headers: headersList, + body: body || undefined, + mode: 'cors', + credentials: opts.withCredentials ? 'include' : 'same-origin', + signal: signal + }).then(function (response) { + self._fetchResponse = response + self._resetTimers(false) + self._connect() + }, function (reason) { + self._resetTimers(true) + if (!self._destroyed) + self.emit('error', reason) + }) + } else { + var xhr = self._xhr = new __webpack_require__.g.XMLHttpRequest() + try { + xhr.open(self._opts.method, self._opts.url, true) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + + // Can't set responseType on really old browsers + if ('responseType' in xhr) + xhr.responseType = self._mode + + if ('withCredentials' in xhr) + xhr.withCredentials = !!opts.withCredentials + + if (self._mode === 'text' && 'overrideMimeType' in xhr) + xhr.overrideMimeType('text/plain; charset=x-user-defined') + + if ('requestTimeout' in opts) { + xhr.timeout = opts.requestTimeout + xhr.ontimeout = function () { + self.emit('requestTimeout') + } + } + + headersList.forEach(function (header) { + xhr.setRequestHeader(header[0], header[1]) + }) + + self._response = null + xhr.onreadystatechange = function () { + switch (xhr.readyState) { + case rStates.LOADING: + case rStates.DONE: + self._onXHRProgress() + break + } + } + // Necessary for streaming in Firefox, since xhr.response is ONLY defined + // in onprogress, not in onreadystatechange with xhr.readyState = 3 + if (self._mode === 'moz-chunked-arraybuffer') { + xhr.onprogress = function () { + self._onXHRProgress() + } + } + + xhr.onerror = function () { + if (self._destroyed) + return + self._resetTimers(true) + self.emit('error', new Error('XHR error')) + } + + try { + xhr.send(body) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + } +} + +/** + * Checks if xhr.status is readable and non-zero, indicating no error. + * Even though the spec says it should be available in readyState 3, + * accessing it throws an exception in IE8 + */ +function statusValid (xhr) { + try { + var status = xhr.status + return (status !== null && status !== 0) + } catch (e) { + return false + } +} + +ClientRequest.prototype._onXHRProgress = function () { + var self = this + + self._resetTimers(false) + + if (!statusValid(self._xhr) || self._destroyed) + return + + if (!self._response) + self._connect() + + self._response._onXHRProgress(self._resetTimers.bind(self)) +} + +ClientRequest.prototype._connect = function () { + var self = this + + if (self._destroyed) + return + + self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._resetTimers.bind(self)) + self._response.on('error', function(err) { + self.emit('error', err) + }) + + self.emit('response', self._response) +} + +ClientRequest.prototype._write = function (chunk, encoding, cb) { + var self = this + + self._body.push(chunk) + cb() +} + +ClientRequest.prototype._resetTimers = function (done) { + var self = this + + __webpack_require__.g.clearTimeout(self._socketTimer) + self._socketTimer = null + + if (done) { + __webpack_require__.g.clearTimeout(self._fetchTimer) + self._fetchTimer = null + } else if (self._socketTimeout) { + self._socketTimer = __webpack_require__.g.setTimeout(function () { + self.emit('timeout') + }, self._socketTimeout) + } +} + +ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function (err) { + var self = this + self._destroyed = true + self._resetTimers(true) + if (self._response) + self._response._destroyed = true + if (self._xhr) + self._xhr.abort() + else if (self._fetchAbortController) + self._fetchAbortController.abort() + + if (err) + self.emit('error', err) +} + +ClientRequest.prototype.end = function (data, encoding, cb) { + var self = this + if (typeof data === 'function') { + cb = data + data = undefined + } + + stream.Writable.prototype.end.call(self, data, encoding, cb) +} + +ClientRequest.prototype.setTimeout = function (timeout, cb) { + var self = this + + if (cb) + self.once('timeout', cb) + + self._socketTimeout = timeout + self._resetTimers(false) +} + +ClientRequest.prototype.flushHeaders = function () {} +ClientRequest.prototype.setNoDelay = function () {} +ClientRequest.prototype.setSocketKeepAlive = function () {} + +// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method +var unsafeHeaders = [ + 'accept-charset', + 'accept-encoding', + 'access-control-request-headers', + 'access-control-request-method', + 'connection', + 'content-length', + 'cookie', + 'cookie2', + 'date', + 'dnt', + 'expect', + 'host', + 'keep-alive', + 'origin', + 'referer', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'via' +] + + +/***/ }), + +/***/ 6917: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +var capability = __webpack_require__(6688) +var inherits = __webpack_require__(6698) +var stream = __webpack_require__(8399) + +var rStates = exports.readyStates = { + UNSENT: 0, + OPENED: 1, + HEADERS_RECEIVED: 2, + LOADING: 3, + DONE: 4 +} + +var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, resetTimers) { + var self = this + stream.Readable.call(self) + + self._mode = mode + self.headers = {} + self.rawHeaders = [] + self.trailers = {} + self.rawTrailers = [] + + // Fake the 'close' event, but only once 'end' fires + self.on('end', function () { + // The nextTick is necessary to prevent the 'request' module from causing an infinite loop + process.nextTick(function () { + self.emit('close') + }) + }) + + if (mode === 'fetch') { + self._fetchResponse = response + + self.url = response.url + self.statusCode = response.status + self.statusMessage = response.statusText + + response.headers.forEach(function (header, key){ + self.headers[key.toLowerCase()] = header + self.rawHeaders.push(key, header) + }) + + if (capability.writableStream) { + var writable = new WritableStream({ + write: function (chunk) { + resetTimers(false) + return new Promise(function (resolve, reject) { + if (self._destroyed) { + reject() + } else if(self.push(Buffer.from(chunk))) { + resolve() + } else { + self._resumeFetch = resolve + } + }) + }, + close: function () { + resetTimers(true) + if (!self._destroyed) + self.push(null) + }, + abort: function (err) { + resetTimers(true) + if (!self._destroyed) + self.emit('error', err) + } + }) + + try { + response.body.pipeTo(writable).catch(function (err) { + resetTimers(true) + if (!self._destroyed) + self.emit('error', err) + }) + return + } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this + } + // fallback for when writableStream or pipeTo aren't available + var reader = response.body.getReader() + function read () { + reader.read().then(function (result) { + if (self._destroyed) + return + resetTimers(result.done) + if (result.done) { + self.push(null) + return + } + self.push(Buffer.from(result.value)) + read() + }).catch(function (err) { + resetTimers(true) + if (!self._destroyed) + self.emit('error', err) + }) + } + read() + } else { + self._xhr = xhr + self._pos = 0 + + self.url = xhr.responseURL + self.statusCode = xhr.status + self.statusMessage = xhr.statusText + var headers = xhr.getAllResponseHeaders().split(/\r?\n/) + headers.forEach(function (header) { + var matches = header.match(/^([^:]+):\s*(.*)/) + if (matches) { + var key = matches[1].toLowerCase() + if (key === 'set-cookie') { + if (self.headers[key] === undefined) { + self.headers[key] = [] + } + self.headers[key].push(matches[2]) + } else if (self.headers[key] !== undefined) { + self.headers[key] += ', ' + matches[2] + } else { + self.headers[key] = matches[2] + } + self.rawHeaders.push(matches[1], matches[2]) + } + }) + + self._charset = 'x-user-defined' + if (!capability.overrideMimeType) { + var mimeType = self.rawHeaders['mime-type'] + if (mimeType) { + var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) + if (charsetMatch) { + self._charset = charsetMatch[1].toLowerCase() + } + } + if (!self._charset) + self._charset = 'utf-8' // best guess + } + } +} + +inherits(IncomingMessage, stream.Readable) + +IncomingMessage.prototype._read = function () { + var self = this + + var resolve = self._resumeFetch + if (resolve) { + self._resumeFetch = null + resolve() + } +} + +IncomingMessage.prototype._onXHRProgress = function (resetTimers) { + var self = this + + var xhr = self._xhr + + var response = null + switch (self._mode) { + case 'text': + response = xhr.responseText + if (response.length > self._pos) { + var newData = response.substr(self._pos) + if (self._charset === 'x-user-defined') { + var buffer = Buffer.alloc(newData.length) + for (var i = 0; i < newData.length; i++) + buffer[i] = newData.charCodeAt(i) & 0xff + + self.push(buffer) + } else { + self.push(newData, self._charset) + } + self._pos = response.length + } + break + case 'arraybuffer': + if (xhr.readyState !== rStates.DONE || !xhr.response) + break + response = xhr.response + self.push(Buffer.from(new Uint8Array(response))) + break + case 'moz-chunked-arraybuffer': // take whole + response = xhr.response + if (xhr.readyState !== rStates.LOADING || !response) + break + self.push(Buffer.from(new Uint8Array(response))) + break + case 'ms-stream': + response = xhr.response + if (xhr.readyState !== rStates.LOADING) + break + var reader = new __webpack_require__.g.MSStreamReader() + reader.onprogress = function () { + if (reader.result.byteLength > self._pos) { + self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos)))) + self._pos = reader.result.byteLength + } + } + reader.onload = function () { + resetTimers(true) + self.push(null) + } + // reader.onerror = ??? // TODO: this + reader.readAsArrayBuffer(response) + break + } + + // The ms-stream case handles end separately in reader.onload() + if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { + resetTimers(true) + self.push(null) + } +} + + +/***/ }), + +/***/ 3141: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// 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. + + + +/**/ + +var Buffer = (__webpack_require__(2861).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.I = 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) : ''; +} + +/***/ }), + +/***/ 1293: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var parser = __webpack_require__(5546); +var compiler = __webpack_require__(2708); + +module.exports = { + parse: function(input) { + var nodes = parser.parse(input.toString()); + return compiler.compile(nodes); + } +}; + + +/***/ }), + +/***/ 2708: +/***/ ((module) => { + +"use strict"; + +function compile(nodes) { + var assignedPaths = []; + var valueAssignments = []; + var currentPath = ""; + var data = Object.create(null); + var context = data; + var arrayMode = false; + + return reduce(nodes); + + function reduce(nodes) { + var node; + for (var i = 0; i < nodes.length; i++) { + node = nodes[i]; + switch (node.type) { + case "Assign": + assign(node); + break; + case "ObjectPath": + setPath(node); + break; + case "ArrayPath": + addTableArray(node); + break; + } + } + + return data; + } + + function genError(err, line, col) { + var ex = new Error(err); + ex.line = line; + ex.column = col; + throw ex; + } + + function assign(node) { + var key = node.key; + var value = node.value; + var line = node.line; + var column = node.column; + + var fullPath; + if (currentPath) { + fullPath = currentPath + "." + key; + } else { + fullPath = key; + } + if (typeof context[key] !== "undefined") { + genError("Cannot redefine existing key '" + fullPath + "'.", line, column); + } + + context[key] = reduceValueNode(value); + + if (!pathAssigned(fullPath)) { + assignedPaths.push(fullPath); + valueAssignments.push(fullPath); + } + } + + + function pathAssigned(path) { + return assignedPaths.indexOf(path) !== -1; + } + + function reduceValueNode(node) { + if (node.type === "Array") { + return reduceArrayWithTypeChecking(node.value); + } else if (node.type === "InlineTable") { + return reduceInlineTableNode(node.value); + } else { + return node.value; + } + } + + function reduceInlineTableNode(values) { + var obj = Object.create(null); + for (var i = 0; i < values.length; i++) { + var val = values[i]; + if (val.value.type === "InlineTable") { + obj[val.key] = reduceInlineTableNode(val.value.value); + } else if (val.type === "InlineTableValue") { + obj[val.key] = reduceValueNode(val.value); + } + } + + return obj; + } + + function setPath(node) { + var path = node.value; + var quotedPath = path.map(quoteDottedString).join("."); + var line = node.line; + var column = node.column; + + if (pathAssigned(quotedPath)) { + genError("Cannot redefine existing key '" + path + "'.", line, column); + } + assignedPaths.push(quotedPath); + context = deepRef(data, path, Object.create(null), line, column); + currentPath = path; + } + + function addTableArray(node) { + var path = node.value; + var quotedPath = path.map(quoteDottedString).join("."); + var line = node.line; + var column = node.column; + + if (!pathAssigned(quotedPath)) { + assignedPaths.push(quotedPath); + } + assignedPaths = assignedPaths.filter(function(p) { + return p.indexOf(quotedPath) !== 0; + }); + assignedPaths.push(quotedPath); + context = deepRef(data, path, [], line, column); + currentPath = quotedPath; + + if (context instanceof Array) { + var newObj = Object.create(null); + context.push(newObj); + context = newObj; + } else { + genError("Cannot redefine existing key '" + path + "'.", line, column); + } + } + + // Given a path 'a.b.c', create (as necessary) `start.a`, + // `start.a.b`, and `start.a.b.c`, assigning `value` to `start.a.b.c`. + // If `a` or `b` are arrays and have items in them, the last item in the + // array is used as the context for the next sub-path. + function deepRef(start, keys, value, line, column) { + var traversed = []; + var traversedPath = ""; + var path = keys.join("."); + var ctx = start; + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + traversed.push(key); + traversedPath = traversed.join("."); + if (typeof ctx[key] === "undefined") { + if (i === keys.length - 1) { + ctx[key] = value; + } else { + ctx[key] = Object.create(null); + } + } else if (i !== keys.length - 1 && valueAssignments.indexOf(traversedPath) > -1) { + // already a non-object value at key, can't be used as part of a new path + genError("Cannot redefine existing key '" + traversedPath + "'.", line, column); + } + + ctx = ctx[key]; + if (ctx instanceof Array && ctx.length && i < keys.length - 1) { + ctx = ctx[ctx.length - 1]; + } + } + + return ctx; + } + + function reduceArrayWithTypeChecking(array) { + // Ensure that all items in the array are of the same type + var firstType = null; + for (var i = 0; i < array.length; i++) { + var node = array[i]; + if (firstType === null) { + firstType = node.type; + } else { + if (node.type !== firstType) { + genError("Cannot add value of type " + node.type + " to array of type " + + firstType + ".", node.line, node.column); + } + } + } + + // Recursively reduce array of nodes into array of the nodes' values + return array.map(reduceValueNode); + } + + function quoteDottedString(str) { + if (str.indexOf(".") > -1) { + return "\"" + str + "\""; + } else { + return str; + } + } +} + +module.exports = { + compile: compile +}; + + +/***/ }), + +/***/ 5546: +/***/ ((module) => { + +module.exports = (function() { + /* + * Generated by PEG.js 0.8.0. + * + * http://pegjs.majda.cz/ + */ + + function peg$subclass(child, parent) { + function ctor() { this.constructor = child; } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + + function SyntaxError(message, expected, found, offset, line, column) { + this.message = message; + this.expected = expected; + this.found = found; + this.offset = offset; + this.line = line; + this.column = column; + + this.name = "SyntaxError"; + } + + peg$subclass(SyntaxError, Error); + + function parse(input) { + var options = arguments.length > 1 ? arguments[1] : {}, + + peg$FAILED = {}, + + peg$startRuleFunctions = { start: peg$parsestart }, + peg$startRuleFunction = peg$parsestart, + + peg$c0 = [], + peg$c1 = function() { return nodes }, + peg$c2 = peg$FAILED, + peg$c3 = "#", + peg$c4 = { type: "literal", value: "#", description: "\"#\"" }, + peg$c5 = void 0, + peg$c6 = { type: "any", description: "any character" }, + peg$c7 = "[", + peg$c8 = { type: "literal", value: "[", description: "\"[\"" }, + peg$c9 = "]", + peg$c10 = { type: "literal", value: "]", description: "\"]\"" }, + peg$c11 = function(name) { addNode(node('ObjectPath', name, line, column)) }, + peg$c12 = function(name) { addNode(node('ArrayPath', name, line, column)) }, + peg$c13 = function(parts, name) { return parts.concat(name) }, + peg$c14 = function(name) { return [name] }, + peg$c15 = function(name) { return name }, + peg$c16 = ".", + peg$c17 = { type: "literal", value: ".", description: "\".\"" }, + peg$c18 = "=", + peg$c19 = { type: "literal", value: "=", description: "\"=\"" }, + peg$c20 = function(key, value) { addNode(node('Assign', value, line, column, key)) }, + peg$c21 = function(chars) { return chars.join('') }, + peg$c22 = function(node) { return node.value }, + peg$c23 = "\"\"\"", + peg$c24 = { type: "literal", value: "\"\"\"", description: "\"\\\"\\\"\\\"\"" }, + peg$c25 = null, + peg$c26 = function(chars) { return node('String', chars.join(''), line, column) }, + peg$c27 = "\"", + peg$c28 = { type: "literal", value: "\"", description: "\"\\\"\"" }, + peg$c29 = "'''", + peg$c30 = { type: "literal", value: "'''", description: "\"'''\"" }, + peg$c31 = "'", + peg$c32 = { type: "literal", value: "'", description: "\"'\"" }, + peg$c33 = function(char) { return char }, + peg$c34 = function(char) { return char}, + peg$c35 = "\\", + peg$c36 = { type: "literal", value: "\\", description: "\"\\\\\"" }, + peg$c37 = function() { return '' }, + peg$c38 = "e", + peg$c39 = { type: "literal", value: "e", description: "\"e\"" }, + peg$c40 = "E", + peg$c41 = { type: "literal", value: "E", description: "\"E\"" }, + peg$c42 = function(left, right) { return node('Float', parseFloat(left + 'e' + right), line, column) }, + peg$c43 = function(text) { return node('Float', parseFloat(text), line, column) }, + peg$c44 = "+", + peg$c45 = { type: "literal", value: "+", description: "\"+\"" }, + peg$c46 = function(digits) { return digits.join('') }, + peg$c47 = "-", + peg$c48 = { type: "literal", value: "-", description: "\"-\"" }, + peg$c49 = function(digits) { return '-' + digits.join('') }, + peg$c50 = function(text) { return node('Integer', parseInt(text, 10), line, column) }, + peg$c51 = "true", + peg$c52 = { type: "literal", value: "true", description: "\"true\"" }, + peg$c53 = function() { return node('Boolean', true, line, column) }, + peg$c54 = "false", + peg$c55 = { type: "literal", value: "false", description: "\"false\"" }, + peg$c56 = function() { return node('Boolean', false, line, column) }, + peg$c57 = function() { return node('Array', [], line, column) }, + peg$c58 = function(value) { return node('Array', value ? [value] : [], line, column) }, + peg$c59 = function(values) { return node('Array', values, line, column) }, + peg$c60 = function(values, value) { return node('Array', values.concat(value), line, column) }, + peg$c61 = function(value) { return value }, + peg$c62 = ",", + peg$c63 = { type: "literal", value: ",", description: "\",\"" }, + peg$c64 = "{", + peg$c65 = { type: "literal", value: "{", description: "\"{\"" }, + peg$c66 = "}", + peg$c67 = { type: "literal", value: "}", description: "\"}\"" }, + peg$c68 = function(values) { return node('InlineTable', values, line, column) }, + peg$c69 = function(key, value) { return node('InlineTableValue', value, line, column, key) }, + peg$c70 = function(digits) { return "." + digits }, + peg$c71 = function(date) { return date.join('') }, + peg$c72 = ":", + peg$c73 = { type: "literal", value: ":", description: "\":\"" }, + peg$c74 = function(time) { return time.join('') }, + peg$c75 = "T", + peg$c76 = { type: "literal", value: "T", description: "\"T\"" }, + peg$c77 = "Z", + peg$c78 = { type: "literal", value: "Z", description: "\"Z\"" }, + peg$c79 = function(date, time) { return node('Date', new Date(date + "T" + time + "Z"), line, column) }, + peg$c80 = function(date, time) { return node('Date', new Date(date + "T" + time), line, column) }, + peg$c81 = /^[ \t]/, + peg$c82 = { type: "class", value: "[ \\t]", description: "[ \\t]" }, + peg$c83 = "\n", + peg$c84 = { type: "literal", value: "\n", description: "\"\\n\"" }, + peg$c85 = "\r", + peg$c86 = { type: "literal", value: "\r", description: "\"\\r\"" }, + peg$c87 = /^[0-9a-f]/i, + peg$c88 = { type: "class", value: "[0-9a-f]i", description: "[0-9a-f]i" }, + peg$c89 = /^[0-9]/, + peg$c90 = { type: "class", value: "[0-9]", description: "[0-9]" }, + peg$c91 = "_", + peg$c92 = { type: "literal", value: "_", description: "\"_\"" }, + peg$c93 = function() { return "" }, + peg$c94 = /^[A-Za-z0-9_\-]/, + peg$c95 = { type: "class", value: "[A-Za-z0-9_\\-]", description: "[A-Za-z0-9_\\-]" }, + peg$c96 = function(d) { return d.join('') }, + peg$c97 = "\\\"", + peg$c98 = { type: "literal", value: "\\\"", description: "\"\\\\\\\"\"" }, + peg$c99 = function() { return '"' }, + peg$c100 = "\\\\", + peg$c101 = { type: "literal", value: "\\\\", description: "\"\\\\\\\\\"" }, + peg$c102 = function() { return '\\' }, + peg$c103 = "\\b", + peg$c104 = { type: "literal", value: "\\b", description: "\"\\\\b\"" }, + peg$c105 = function() { return '\b' }, + peg$c106 = "\\t", + peg$c107 = { type: "literal", value: "\\t", description: "\"\\\\t\"" }, + peg$c108 = function() { return '\t' }, + peg$c109 = "\\n", + peg$c110 = { type: "literal", value: "\\n", description: "\"\\\\n\"" }, + peg$c111 = function() { return '\n' }, + peg$c112 = "\\f", + peg$c113 = { type: "literal", value: "\\f", description: "\"\\\\f\"" }, + peg$c114 = function() { return '\f' }, + peg$c115 = "\\r", + peg$c116 = { type: "literal", value: "\\r", description: "\"\\\\r\"" }, + peg$c117 = function() { return '\r' }, + peg$c118 = "\\U", + peg$c119 = { type: "literal", value: "\\U", description: "\"\\\\U\"" }, + peg$c120 = function(digits) { return convertCodePoint(digits.join('')) }, + peg$c121 = "\\u", + peg$c122 = { type: "literal", value: "\\u", description: "\"\\\\u\"" }, + + peg$currPos = 0, + peg$reportedPos = 0, + peg$cachedPos = 0, + peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }, + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$silentFails = 0, + + peg$cache = {}, + peg$result; + + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + + function text() { + return input.substring(peg$reportedPos, peg$currPos); + } + + function offset() { + return peg$reportedPos; + } + + function line() { + return peg$computePosDetails(peg$reportedPos).line; + } + + function column() { + return peg$computePosDetails(peg$reportedPos).column; + } + + function expected(description) { + throw peg$buildException( + null, + [{ type: "other", description: description }], + peg$reportedPos + ); + } + + function error(message) { + throw peg$buildException(message, null, peg$reportedPos); + } + + function peg$computePosDetails(pos) { + function advance(details, startPos, endPos) { + var p, ch; + + for (p = startPos; p < endPos; p++) { + ch = input.charAt(p); + if (ch === "\n") { + if (!details.seenCR) { details.line++; } + details.column = 1; + details.seenCR = false; + } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { + details.line++; + details.column = 1; + details.seenCR = true; + } else { + details.column++; + details.seenCR = false; + } + } + } + + if (peg$cachedPos !== pos) { + if (peg$cachedPos > pos) { + peg$cachedPos = 0; + peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }; + } + advance(peg$cachedPosDetails, peg$cachedPos, pos); + peg$cachedPos = pos; + } + + return peg$cachedPosDetails; + } + + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { return; } + + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + + peg$maxFailExpected.push(expected); + } + + function peg$buildException(message, expected, pos) { + function cleanupExpected(expected) { + var i = 1; + + expected.sort(function(a, b) { + if (a.description < b.description) { + return -1; + } else if (a.description > b.description) { + return 1; + } else { + return 0; + } + }); + + while (i < expected.length) { + if (expected[i - 1] === expected[i]) { + expected.splice(i, 1); + } else { + i++; + } + } + } + + function buildMessage(expected, found) { + function stringEscape(s) { + function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } + + return s + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\x08/g, '\\b') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\f/g, '\\f') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); }) + .replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); }) + .replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); }); + } + + var expectedDescs = new Array(expected.length), + expectedDesc, foundDesc, i; + + for (i = 0; i < expected.length; i++) { + expectedDescs[i] = expected[i].description; + } + + expectedDesc = expected.length > 1 + ? expectedDescs.slice(0, -1).join(", ") + + " or " + + expectedDescs[expected.length - 1] + : expectedDescs[0]; + + foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input"; + + return "Expected " + expectedDesc + " but " + foundDesc + " found."; + } + + var posDetails = peg$computePosDetails(pos), + found = pos < input.length ? input.charAt(pos) : null; + + if (expected !== null) { + cleanupExpected(expected); + } + + return new SyntaxError( + message !== null ? message : buildMessage(expected, found), + expected, + found, + pos, + posDetails.line, + posDetails.column + ); + } + + function peg$parsestart() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 0, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseline(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseline(); + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c1(); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseline() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 1, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parseexpression(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parsecomment(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parsecomment(); + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseNL(); + if (s6 !== peg$FAILED) { + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseNL(); + } + } else { + s5 = peg$c2; + } + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseNL(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseNL(); + } + } else { + s2 = peg$c2; + } + if (s2 === peg$FAILED) { + s2 = peg$parseEOF(); + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$parseNL(); + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseexpression() { + var s0; + + var key = peg$currPos * 49 + 2, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsecomment(); + if (s0 === peg$FAILED) { + s0 = peg$parsepath(); + if (s0 === peg$FAILED) { + s0 = peg$parsetablearray(); + if (s0 === peg$FAILED) { + s0 = peg$parseassignment(); + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsecomment() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 3, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c3; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c4); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNL(); + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = peg$c5; + } else { + peg$currPos = s4; + s4 = peg$c2; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } else { + peg$currPos = s3; + s3 = peg$c2; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNL(); + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = peg$c5; + } else { + peg$currPos = s4; + s4 = peg$c2; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsepath() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 4, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetable_key(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s5 = peg$c9; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c11(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetablearray() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + var key = peg$currPos * 49 + 5, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s2 = peg$c7; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parsetable_key(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s6 = peg$c9; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s7 = peg$c9; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s7 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c12(s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetable_key() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 6, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsedot_ended_table_key_part(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsedot_ended_table_key_part(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + s2 = peg$parsetable_key_part(); + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c13(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsetable_key_part(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c14(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetable_key_part() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 7, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsequoted_key(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedot_ended_table_key_part() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 8, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsequoted_key(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseassignment() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 9, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsekey(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c18; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parsevalue(); + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c20(s1, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsequoted_key(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c18; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parsevalue(); + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c20(s1, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsekey() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 10, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseASCII_BASIC(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseASCII_BASIC(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c21(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsequoted_key() { + var s0, s1; + + var key = peg$currPos * 49 + 11, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsedouble_quoted_single_line_string(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c22(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsesingle_quoted_single_line_string(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c22(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsevalue() { + var s0; + + var key = peg$currPos * 49 + 12, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsestring(); + if (s0 === peg$FAILED) { + s0 = peg$parsedatetime(); + if (s0 === peg$FAILED) { + s0 = peg$parsefloat(); + if (s0 === peg$FAILED) { + s0 = peg$parseinteger(); + if (s0 === peg$FAILED) { + s0 = peg$parseboolean(); + if (s0 === peg$FAILED) { + s0 = peg$parsearray(); + if (s0 === peg$FAILED) { + s0 = peg$parseinline_table(); + } + } + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsestring() { + var s0; + + var key = peg$currPos * 49 + 13, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsedouble_quoted_multiline_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsedouble_quoted_single_line_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsesingle_quoted_multiline_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsesingle_quoted_single_line_string(); + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedouble_quoted_multiline_string() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 14, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c23) { + s1 = peg$c23; + peg$currPos += 3; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsemultiline_string_char(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsemultiline_string_char(); + } + if (s3 !== peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c23) { + s4 = peg$c23; + peg$currPos += 3; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedouble_quoted_single_line_string() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 15, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c27; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsestring_char(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsestring_char(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c27; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesingle_quoted_multiline_string() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 16, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c29) { + s1 = peg$c29; + peg$currPos += 3; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsemultiline_literal_char(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsemultiline_literal_char(); + } + if (s3 !== peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c29) { + s4 = peg$c29; + peg$currPos += 3; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesingle_quoted_single_line_string() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 17, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseliteral_char(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseliteral_char(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c31; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsestring_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 18, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseESCAPED(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 34) { + s2 = peg$c27; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseliteral_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 19, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c31; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_string_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 20, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseESCAPED(); + if (s0 === peg$FAILED) { + s0 = peg$parsemultiline_string_delim(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c23) { + s2 = peg$c23; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c34(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_string_delim() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 21, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c35; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c36); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseNLS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseNLS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c37(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_literal_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 22, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c29) { + s2 = peg$c29; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefloat() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 23, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsefloat_text(); + if (s1 === peg$FAILED) { + s1 = peg$parseinteger_text(); + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 101) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 69) { + s2 = peg$c40; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c41); } + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseinteger_text(); + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c42(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsefloat_text(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c43(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefloat_text() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 24, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c44; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + if (s1 === peg$FAILED) { + s1 = peg$c25; + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseDIGITS(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGITS(); + if (s5 !== peg$FAILED) { + s3 = [s3, s4, s5]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c46(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 45) { + s1 = peg$c47; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseDIGITS(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGITS(); + if (s5 !== peg$FAILED) { + s3 = [s3, s4, s5]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c49(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinteger() { + var s0, s1; + + var key = peg$currPos * 49 + 25, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseinteger_text(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c50(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinteger_text() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 26, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c44; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + if (s1 === peg$FAILED) { + s1 = peg$c25; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + peg$silentFails--; + if (s4 === peg$FAILED) { + s3 = peg$c5; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c46(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 45) { + s1 = peg$c47; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + peg$silentFails--; + if (s4 === peg$FAILED) { + s3 = peg$c5; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c49(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseboolean() { + var s0, s1; + + var key = peg$currPos * 49 + 27, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c51) { + s1 = peg$c51; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c52); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c53(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c54) { + s1 = peg$c54; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c55); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c56(); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 28, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_sep(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_sep(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c57(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsearray_value(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c58(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_value_list(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_value_list(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c59(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_value_list(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_value_list(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$parsearray_value(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s4 = peg$c9; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c60(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_value() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 29, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsearray_sep(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsearray_sep(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsevalue(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsearray_sep(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsearray_sep(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c61(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_value_list() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 30, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsearray_sep(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsearray_sep(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsevalue(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsearray_sep(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsearray_sep(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s4 = peg$c62; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c63); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parsearray_sep(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parsearray_sep(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c61(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_sep() { + var s0; + + var key = peg$currPos * 49 + 31, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseS(); + if (s0 === peg$FAILED) { + s0 = peg$parseNL(); + if (s0 === peg$FAILED) { + s0 = peg$parsecomment(); + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinline_table() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 32, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 123) { + s1 = peg$c64; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c65); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseinline_table_assignment(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseinline_table_assignment(); + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s5 = peg$c66; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c67); } + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c68(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinline_table_assignment() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 33, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s4 = peg$c18; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parsevalue(); + if (s6 !== peg$FAILED) { + s7 = []; + s8 = peg$parseS(); + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseS(); + } + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c62; + peg$currPos++; + } else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c63); } + } + if (s8 !== peg$FAILED) { + s9 = []; + s10 = peg$parseS(); + while (s10 !== peg$FAILED) { + s9.push(s10); + s10 = peg$parseS(); + } + if (s9 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c69(s2, s6); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s4 = peg$c18; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parsevalue(); + if (s6 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c69(s2, s6); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesecfragment() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 34, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c16; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDIGITS(); + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c70(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedate() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11; + + var key = peg$currPos * 49 + 35, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT_OR_UNDER(); + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s6 = peg$c47; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseDIGIT_OR_UNDER(); + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s9 = peg$c47; + peg$currPos++; + } else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s9 !== peg$FAILED) { + s10 = peg$parseDIGIT_OR_UNDER(); + if (s10 !== peg$FAILED) { + s11 = peg$parseDIGIT_OR_UNDER(); + if (s11 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c71(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetime() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 36, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c72; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT_OR_UNDER(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c72; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + s9 = peg$parseDIGIT_OR_UNDER(); + if (s9 !== peg$FAILED) { + s10 = peg$parsesecfragment(); + if (s10 === peg$FAILED) { + s10 = peg$c25; + } + if (s10 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c74(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetime_with_offset() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16; + + var key = peg$currPos * 49 + 37, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c72; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT_OR_UNDER(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c72; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + s9 = peg$parseDIGIT_OR_UNDER(); + if (s9 !== peg$FAILED) { + s10 = peg$parsesecfragment(); + if (s10 === peg$FAILED) { + s10 = peg$c25; + } + if (s10 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s11 = peg$c47; + peg$currPos++; + } else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s11 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s11 = peg$c44; + peg$currPos++; + } else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + } + if (s11 !== peg$FAILED) { + s12 = peg$parseDIGIT_OR_UNDER(); + if (s12 !== peg$FAILED) { + s13 = peg$parseDIGIT_OR_UNDER(); + if (s13 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s14 = peg$c72; + peg$currPos++; + } else { + s14 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s14 !== peg$FAILED) { + s15 = peg$parseDIGIT_OR_UNDER(); + if (s15 !== peg$FAILED) { + s16 = peg$parseDIGIT_OR_UNDER(); + if (s16 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c74(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedatetime() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 38, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsedate(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 84) { + s2 = peg$c75; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c76); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetime(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 90) { + s4 = peg$c77; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c78); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c79(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsedate(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 84) { + s2 = peg$c75; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c76); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetime_with_offset(); + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c80(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseS() { + var s0; + + var key = peg$currPos * 49 + 39, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c81.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c82); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseNL() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 40, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (input.charCodeAt(peg$currPos) === 10) { + s0 = peg$c83; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c84); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 13) { + s1 = peg$c85; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c86); } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 10) { + s2 = peg$c83; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c84); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseNLS() { + var s0; + + var key = peg$currPos * 49 + 41, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseNL(); + if (s0 === peg$FAILED) { + s0 = peg$parseS(); + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseEOF() { + var s0, s1; + + var key = peg$currPos * 49 + 42, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + peg$silentFails++; + if (input.length > peg$currPos) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + peg$silentFails--; + if (s1 === peg$FAILED) { + s0 = peg$c5; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseHEX() { + var s0; + + var key = peg$currPos * 49 + 43, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c87.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c88); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseDIGIT_OR_UNDER() { + var s0, s1; + + var key = peg$currPos * 49 + 44, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c89.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c90); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s1 = peg$c91; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c92); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c93(); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseASCII_BASIC() { + var s0; + + var key = peg$currPos * 49 + 45, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c94.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c95); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseDIGITS() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 46, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c96(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseESCAPED() { + var s0, s1; + + var key = peg$currPos * 49 + 47, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c97) { + s1 = peg$c97; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c98); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c99(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c100) { + s1 = peg$c100; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c102(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c103) { + s1 = peg$c103; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c104); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c105(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c106) { + s1 = peg$c106; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c107); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c108(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c109) { + s1 = peg$c109; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c110); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c111(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c112) { + s1 = peg$c112; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c113); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c114(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c115) { + s1 = peg$c115; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c116); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c117(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$parseESCAPED_UNICODE(); + } + } + } + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseESCAPED_UNICODE() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 48, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c118) { + s1 = peg$c118; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c119); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseHEX(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEX(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHEX(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHEX(); + if (s6 !== peg$FAILED) { + s7 = peg$parseHEX(); + if (s7 !== peg$FAILED) { + s8 = peg$parseHEX(); + if (s8 !== peg$FAILED) { + s9 = peg$parseHEX(); + if (s9 !== peg$FAILED) { + s10 = peg$parseHEX(); + if (s10 !== peg$FAILED) { + s3 = [s3, s4, s5, s6, s7, s8, s9, s10]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c120(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c121) { + s1 = peg$c121; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c122); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseHEX(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEX(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHEX(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHEX(); + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c120(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + + var nodes = []; + + function genError(err, line, col) { + var ex = new Error(err); + ex.line = line; + ex.column = col; + throw ex; + } + + function addNode(node) { + nodes.push(node); + } + + function node(type, value, line, column, key) { + var obj = { type: type, value: value, line: line(), column: column() }; + if (key) obj.key = key; + return obj; + } + + function convertCodePoint(str, line, col) { + var num = parseInt("0x" + str); + + if ( + !isFinite(num) || + Math.floor(num) != num || + num < 0 || + num > 0x10FFFF || + (num > 0xD7FF && num < 0xE000) + ) { + genError("Invalid Unicode escape code: " + str, line, col); + } else { + return fromCodePoint(num); + } + } + + function fromCodePoint() { + var MAX_SIZE = 0x4000; + var codeUnits = []; + var highSurrogate; + var lowSurrogate; + var index = -1; + var length = arguments.length; + if (!length) { + return ''; + } + var result = ''; + while (++index < length) { + var codePoint = Number(arguments[index]); + if (codePoint <= 0xFFFF) { // BMP code point + codeUnits.push(codePoint); + } else { // Astral code point; split in surrogate halves + // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + codePoint -= 0x10000; + highSurrogate = (codePoint >> 10) + 0xD800; + lowSurrogate = (codePoint % 0x400) + 0xDC00; + codeUnits.push(highSurrogate, lowSurrogate); + } + if (index + 1 == length || codeUnits.length > MAX_SIZE) { + result += String.fromCharCode.apply(null, codeUnits); + codeUnits.length = 0; + } + } + return result; + } + + + peg$result = peg$startRuleFunction(); + + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail({ type: "end", description: "end of input" }); + } + + throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos); + } + } + + return { + SyntaxError: SyntaxError, + parse: parse + }; +})(); + + +/***/ }), + +/***/ 1430: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * IPv6 Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (root) { + 'use strict'; + + /* + var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156"; + var _out = IPv6.best(_in); + var _expected = "fe80::204:61ff:fe9d:f156"; + + console.log(_in, _out, _expected, _out === _expected); + */ + + // save current IPv6 variable, if any + var _IPv6 = root && root.IPv6; + + function bestPresentation(address) { + // based on: + // Javascript to test an IPv6 address for proper format, and to + // present the "best text representation" according to IETF Draft RFC at + // http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04 + // 8 Feb 2010 Rich Brown, Dartware, LLC + // Please feel free to use this code as long as you provide a link to + // http://www.intermapper.com + // http://intermapper.com/support/tools/IPV6-Validator.aspx + // http://download.dartware.com/thirdparty/ipv6validator.js + + var _address = address.toLowerCase(); + var segments = _address.split(':'); + var length = segments.length; + var total = 8; + + // trim colons (:: or ::a:b:c… or …a:b:c::) + if (segments[0] === '' && segments[1] === '' && segments[2] === '') { + // must have been :: + // remove first two items + segments.shift(); + segments.shift(); + } else if (segments[0] === '' && segments[1] === '') { + // must have been ::xxxx + // remove the first item + segments.shift(); + } else if (segments[length - 1] === '' && segments[length - 2] === '') { + // must have been xxxx:: + segments.pop(); + } + + length = segments.length; + + // adjust total segments for IPv4 trailer + if (segments[length - 1].indexOf('.') !== -1) { + // found a "." which means IPv4 + total = 7; + } + + // fill empty segments them with "0000" + var pos; + for (pos = 0; pos < length; pos++) { + if (segments[pos] === '') { + break; + } + } + + if (pos < total) { + segments.splice(pos, 1, '0000'); + while (segments.length < total) { + segments.splice(pos, 0, '0000'); + } + } + + // strip leading zeros + var _segments; + for (var i = 0; i < total; i++) { + _segments = segments[i].split(''); + for (var j = 0; j < 3 ; j++) { + if (_segments[0] === '0' && _segments.length > 1) { + _segments.splice(0,1); + } else { + break; + } + } + + segments[i] = _segments.join(''); + } + + // find longest sequence of zeroes and coalesce them into one segment + var best = -1; + var _best = 0; + var _current = 0; + var current = -1; + var inzeroes = false; + // i; already declared + + for (i = 0; i < total; i++) { + if (inzeroes) { + if (segments[i] === '0') { + _current += 1; + } else { + inzeroes = false; + if (_current > _best) { + best = current; + _best = _current; + } + } + } else { + if (segments[i] === '0') { + inzeroes = true; + current = i; + _current = 1; + } + } + } + + if (_current > _best) { + best = current; + _best = _current; + } + + if (_best > 1) { + segments.splice(best, _best, ''); + } + + length = segments.length; + + // assemble remaining segments + var result = ''; + if (segments[0] === '') { + result = ':'; + } + + for (i = 0; i < length; i++) { + result += segments[i]; + if (i === length - 1) { + break; + } + + result += ':'; + } + + if (segments[length - 1] === '') { + result += ':'; + } + + return result; + } + + function noConflict() { + /*jshint validthis: true */ + if (root.IPv6 === this) { + root.IPv6 = _IPv6; + } + + return this; + } + + return { + best: bestPresentation, + noConflict: noConflict + }; +})); + + +/***/ }), + +/***/ 4704: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * Second Level Domain (SLD) Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (root) { + 'use strict'; + + // save current SecondLevelDomains variable, if any + var _SecondLevelDomains = root && root.SecondLevelDomains; + + var SLD = { + // list of known Second Level Domains + // converted list of SLDs from https://github.com/gavingmiller/second-level-domains + // ---- + // publicsuffix.org is more current and actually used by a couple of browsers internally. + // downside is it also contains domains like "dyndns.org" - which is fine for the security + // issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js + // ---- + list: { + 'ac':' com gov mil net org ', + 'ae':' ac co gov mil name net org pro sch ', + 'af':' com edu gov net org ', + 'al':' com edu gov mil net org ', + 'ao':' co ed gv it og pb ', + 'ar':' com edu gob gov int mil net org tur ', + 'at':' ac co gv or ', + 'au':' asn com csiro edu gov id net org ', + 'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ', + 'bb':' biz co com edu gov info net org store tv ', + 'bh':' biz cc com edu gov info net org ', + 'bn':' com edu gov net org ', + 'bo':' com edu gob gov int mil net org tv ', + 'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ', + 'bs':' com edu gov net org ', + 'bz':' du et om ov rg ', + 'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ', + 'ck':' biz co edu gen gov info net org ', + 'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ', + 'co':' com edu gov mil net nom org ', + 'cr':' ac c co ed fi go or sa ', + 'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ', + 'do':' art com edu gob gov mil net org sld web ', + 'dz':' art asso com edu gov net org pol ', + 'ec':' com edu fin gov info med mil net org pro ', + 'eg':' com edu eun gov mil name net org sci ', + 'er':' com edu gov ind mil net org rochest w ', + 'es':' com edu gob nom org ', + 'et':' biz com edu gov info name net org ', + 'fj':' ac biz com info mil name net org pro ', + 'fk':' ac co gov net nom org ', + 'fr':' asso com f gouv nom prd presse tm ', + 'gg':' co net org ', + 'gh':' com edu gov mil org ', + 'gn':' ac com gov net org ', + 'gr':' com edu gov mil net org ', + 'gt':' com edu gob ind mil net org ', + 'gu':' com edu gov net org ', + 'hk':' com edu gov idv net org ', + 'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ', + 'id':' ac co go mil net or sch web ', + 'il':' ac co gov idf k12 muni net org ', + 'in':' ac co edu ernet firm gen gov i ind mil net nic org res ', + 'iq':' com edu gov i mil net org ', + 'ir':' ac co dnssec gov i id net org sch ', + 'it':' edu gov ', + 'je':' co net org ', + 'jo':' com edu gov mil name net org sch ', + 'jp':' ac ad co ed go gr lg ne or ', + 'ke':' ac co go info me mobi ne or sc ', + 'kh':' com edu gov mil net org per ', + 'ki':' biz com de edu gov info mob net org tel ', + 'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ', + 'kn':' edu gov net org ', + 'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ', + 'kw':' com edu gov net org ', + 'ky':' com edu gov net org ', + 'kz':' com edu gov mil net org ', + 'lb':' com edu gov net org ', + 'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ', + 'lr':' com edu gov net org ', + 'lv':' asn com conf edu gov id mil net org ', + 'ly':' com edu gov id med net org plc sch ', + 'ma':' ac co gov m net org press ', + 'mc':' asso tm ', + 'me':' ac co edu gov its net org priv ', + 'mg':' com edu gov mil nom org prd tm ', + 'mk':' com edu gov inf name net org pro ', + 'ml':' com edu gov net org presse ', + 'mn':' edu gov org ', + 'mo':' com edu gov net org ', + 'mt':' com edu gov net org ', + 'mv':' aero biz com coop edu gov info int mil museum name net org pro ', + 'mw':' ac co com coop edu gov int museum net org ', + 'mx':' com edu gob net org ', + 'my':' com edu gov mil name net org sch ', + 'nf':' arts com firm info net other per rec store web ', + 'ng':' biz com edu gov mil mobi name net org sch ', + 'ni':' ac co com edu gob mil net nom org ', + 'np':' com edu gov mil net org ', + 'nr':' biz com edu gov info net org ', + 'om':' ac biz co com edu gov med mil museum net org pro sch ', + 'pe':' com edu gob mil net nom org sld ', + 'ph':' com edu gov i mil net ngo org ', + 'pk':' biz com edu fam gob gok gon gop gos gov net org web ', + 'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ', + 'pr':' ac biz com edu est gov info isla name net org pro prof ', + 'ps':' com edu gov net org plo sec ', + 'pw':' belau co ed go ne or ', + 'ro':' arts com firm info nom nt org rec store tm www ', + 'rs':' ac co edu gov in org ', + 'sb':' com edu gov net org ', + 'sc':' com edu gov net org ', + 'sh':' co com edu gov net nom org ', + 'sl':' com edu gov net org ', + 'st':' co com consulado edu embaixada gov mil net org principe saotome store ', + 'sv':' com edu gob org red ', + 'sz':' ac co org ', + 'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ', + 'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ', + 'tw':' club com ebiz edu game gov idv mil net org ', + 'mu':' ac co com gov net or org ', + 'mz':' ac co edu gov org ', + 'na':' co com ', + 'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ', + 'pa':' abo ac com edu gob ing med net nom org sld ', + 'pt':' com edu gov int net nome org publ ', + 'py':' com edu gov mil net org ', + 'qa':' com edu gov mil net org ', + 're':' asso com nom ', + 'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ', + 'rw':' ac co com edu gouv gov int mil net ', + 'sa':' com edu gov med net org pub sch ', + 'sd':' com edu gov info med net org tv ', + 'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ', + 'sg':' com edu gov idn net org per ', + 'sn':' art com edu gouv org perso univ ', + 'sy':' com edu gov mil net news org ', + 'th':' ac co go in mi net or ', + 'tj':' ac biz co com edu go gov info int mil name net nic org test web ', + 'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ', + 'tz':' ac co go ne or ', + 'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ', + 'ug':' ac co go ne or org sc ', + 'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ', + 'us':' dni fed isa kids nsn ', + 'uy':' com edu gub mil net org ', + 've':' co com edu gob info mil net org web ', + 'vi':' co com k12 net org ', + 'vn':' ac biz com edu gov health info int name net org pro ', + 'ye':' co com gov ltd me net org plc ', + 'yu':' ac co edu gov org ', + 'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ', + 'zm':' ac co com edu gov net org sch ', + // https://en.wikipedia.org/wiki/CentralNic#Second-level_domains + 'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ', + 'net': 'gb jp se uk ', + 'org': 'ae', + 'de': 'com ' + }, + // gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost + // in both performance and memory footprint. No initialization required. + // http://jsperf.com/uri-js-sld-regex-vs-binary-search/4 + // Following methods use lastIndexOf() rather than array.split() in order + // to avoid any memory allocations. + has: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return false; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) { + return false; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return false; + } + return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0; + }, + is: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return false; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset >= 0) { + return false; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return false; + } + return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0; + }, + get: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return null; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) { + return null; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return null; + } + if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) { + return null; + } + return domain.slice(sldOffset+1); + }, + noConflict: function(){ + if (root.SecondLevelDomains === this) { + root.SecondLevelDomains = _SecondLevelDomains; + } + return this; + } + }; + + return SLD; +})); + + +/***/ }), + +/***/ 4193: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(__webpack_require__(9340), __webpack_require__(1430), __webpack_require__(4704)); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(9340), __webpack_require__(1430), __webpack_require__(4704)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (punycode, IPv6, SLD, root) { + 'use strict'; + /*global location, escape, unescape */ + // FIXME: v2.0.0 renamce non-camelCase properties to uppercase + /*jshint camelcase: false */ + + // save current URI variable, if any + var _URI = root && root.URI; + + function URI(url, base) { + var _urlSupplied = arguments.length >= 1; + var _baseSupplied = arguments.length >= 2; + + // Allow instantiation without the 'new' keyword + if (!(this instanceof URI)) { + if (_urlSupplied) { + if (_baseSupplied) { + return new URI(url, base); + } + + return new URI(url); + } + + return new URI(); + } + + if (url === undefined) { + if (_urlSupplied) { + throw new TypeError('undefined is not a valid argument for URI'); + } + + if (typeof location !== 'undefined') { + url = location.href + ''; + } else { + url = ''; + } + } + + if (url === null) { + if (_urlSupplied) { + throw new TypeError('null is not a valid argument for URI'); + } + } + + this.href(url); + + // resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor + if (base !== undefined) { + return this.absoluteTo(base); + } + + return this; + } + + function isInteger(value) { + return /^[0-9]+$/.test(value); + } + + URI.version = '1.19.11'; + + var p = URI.prototype; + var hasOwn = Object.prototype.hasOwnProperty; + + function escapeRegEx(string) { + // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963 + return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); + } + + function getType(value) { + // IE8 doesn't return [Object Undefined] but [Object Object] for undefined value + if (value === undefined) { + return 'Undefined'; + } + + return String(Object.prototype.toString.call(value)).slice(8, -1); + } + + function isArray(obj) { + return getType(obj) === 'Array'; + } + + function filterArrayValues(data, value) { + var lookup = {}; + var i, length; + + if (getType(value) === 'RegExp') { + lookup = null; + } else if (isArray(value)) { + for (i = 0, length = value.length; i < length; i++) { + lookup[value[i]] = true; + } + } else { + lookup[value] = true; + } + + for (i = 0, length = data.length; i < length; i++) { + /*jshint laxbreak: true */ + var _match = lookup && lookup[data[i]] !== undefined + || !lookup && value.test(data[i]); + /*jshint laxbreak: false */ + if (_match) { + data.splice(i, 1); + length--; + i--; + } + } + + return data; + } + + function arrayContains(list, value) { + var i, length; + + // value may be string, number, array, regexp + if (isArray(value)) { + // Note: this can be optimized to O(n) (instead of current O(m * n)) + for (i = 0, length = value.length; i < length; i++) { + if (!arrayContains(list, value[i])) { + return false; + } + } + + return true; + } + + var _type = getType(value); + for (i = 0, length = list.length; i < length; i++) { + if (_type === 'RegExp') { + if (typeof list[i] === 'string' && list[i].match(value)) { + return true; + } + } else if (list[i] === value) { + return true; + } + } + + return false; + } + + function arraysEqual(one, two) { + if (!isArray(one) || !isArray(two)) { + return false; + } + + // arrays can't be equal if they have different amount of content + if (one.length !== two.length) { + return false; + } + + one.sort(); + two.sort(); + + for (var i = 0, l = one.length; i < l; i++) { + if (one[i] !== two[i]) { + return false; + } + } + + return true; + } + + function trimSlashes(text) { + var trim_expression = /^\/+|\/+$/g; + return text.replace(trim_expression, ''); + } + + URI._parts = function() { + return { + protocol: null, + username: null, + password: null, + hostname: null, + urn: null, + port: null, + path: null, + query: null, + fragment: null, + // state + preventInvalidHostname: URI.preventInvalidHostname, + duplicateQueryParameters: URI.duplicateQueryParameters, + escapeQuerySpace: URI.escapeQuerySpace + }; + }; + // state: throw on invalid hostname + // see https://github.com/medialize/URI.js/pull/345 + // and https://github.com/medialize/URI.js/issues/354 + URI.preventInvalidHostname = false; + // state: allow duplicate query parameters (a=1&a=1) + URI.duplicateQueryParameters = false; + // state: replaces + with %20 (space in query strings) + URI.escapeQuerySpace = true; + // static properties + URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i; + URI.idn_expression = /[^a-z0-9\._-]/i; + URI.punycode_expression = /(xn--)/i; + // well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care? + URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; + // credits to Rich Brown + // source: http://forums.intermapper.com/viewtopic.php?p=1096#1096 + // specification: http://www.ietf.org/rfc/rfc4291.txt + URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/; + // expression used is "gruber revised" (@gruber v2) determined to be the + // best solution in a regex-golf we did a couple of ages ago at + // * http://mathiasbynens.be/demo/url-regex + // * http://rodneyrehm.de/t/url-regex.html + URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig; + URI.findUri = { + // valid "scheme://" or "www." + start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi, + // everything up to the next whitespace + end: /[\s\r\n]|$/, + // trim trailing punctuation captured by end RegExp + trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/, + // balanced parens inclusion (), [], {}, <> + parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g, + }; + URI.leading_whitespace_expression = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/ + // https://infra.spec.whatwg.org/#ascii-tab-or-newline + URI.ascii_tab_whitespace = /[\u0009\u000A\u000D]+/g + // http://www.iana.org/assignments/uri-schemes.html + // http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports + URI.defaultPorts = { + http: '80', + https: '443', + ftp: '21', + gopher: '70', + ws: '80', + wss: '443' + }; + // list of protocols which always require a hostname + URI.hostProtocols = [ + 'http', + 'https' + ]; + + // allowed hostname characters according to RFC 3986 + // ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded + // I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _ + URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/; + // map DOM Elements to their URI attribute + URI.domAttributes = { + 'a': 'href', + 'blockquote': 'cite', + 'link': 'href', + 'base': 'href', + 'script': 'src', + 'form': 'action', + 'img': 'src', + 'area': 'href', + 'iframe': 'src', + 'embed': 'src', + 'source': 'src', + 'track': 'src', + 'input': 'src', // but only if type="image" + 'audio': 'src', + 'video': 'src' + }; + URI.getDomAttribute = function(node) { + if (!node || !node.nodeName) { + return undefined; + } + + var nodeName = node.nodeName.toLowerCase(); + // should only expose src for type="image" + if (nodeName === 'input' && node.type !== 'image') { + return undefined; + } + + return URI.domAttributes[nodeName]; + }; + + function escapeForDumbFirefox36(value) { + // https://github.com/medialize/URI.js/issues/91 + return escape(value); + } + + // encoding / decoding according to RFC3986 + function strictEncodeURIComponent(string) { + // see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent + return encodeURIComponent(string) + .replace(/[!'()*]/g, escapeForDumbFirefox36) + .replace(/\*/g, '%2A'); + } + URI.encode = strictEncodeURIComponent; + URI.decode = decodeURIComponent; + URI.iso8859 = function() { + URI.encode = escape; + URI.decode = unescape; + }; + URI.unicode = function() { + URI.encode = strictEncodeURIComponent; + URI.decode = decodeURIComponent; + }; + URI.characters = { + pathname: { + encode: { + // RFC3986 2.1: For consistency, URI producers and normalizers should + // use uppercase hexadecimal digits for all percent-encodings. + expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig, + map: { + // -._~!'()* + '%24': '$', + '%26': '&', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=', + '%3A': ':', + '%40': '@' + } + }, + decode: { + expression: /[\/\?#]/g, + map: { + '/': '%2F', + '?': '%3F', + '#': '%23' + } + } + }, + reserved: { + encode: { + // RFC3986 2.1: For consistency, URI producers and normalizers should + // use uppercase hexadecimal digits for all percent-encodings. + expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig, + map: { + // gen-delims + '%3A': ':', + '%2F': '/', + '%3F': '?', + '%23': '#', + '%5B': '[', + '%5D': ']', + '%40': '@', + // sub-delims + '%21': '!', + '%24': '$', + '%26': '&', + '%27': '\'', + '%28': '(', + '%29': ')', + '%2A': '*', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=' + } + } + }, + urnpath: { + // The characters under `encode` are the characters called out by RFC 2141 as being acceptable + // for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but + // these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also + // note that the colon character is not featured in the encoding map; this is because URI.js + // gives the colons in URNs semantic meaning as the delimiters of path segements, and so it + // should not appear unencoded in a segment itself. + // See also the note above about RFC3986 and capitalalized hex digits. + encode: { + expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig, + map: { + '%21': '!', + '%24': '$', + '%27': '\'', + '%28': '(', + '%29': ')', + '%2A': '*', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=', + '%40': '@' + } + }, + // These characters are the characters called out by RFC2141 as "reserved" characters that + // should never appear in a URN, plus the colon character (see note above). + decode: { + expression: /[\/\?#:]/g, + map: { + '/': '%2F', + '?': '%3F', + '#': '%23', + ':': '%3A' + } + } + } + }; + URI.encodeQuery = function(string, escapeQuerySpace) { + var escaped = URI.encode(string + ''); + if (escapeQuerySpace === undefined) { + escapeQuerySpace = URI.escapeQuerySpace; + } + + return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped; + }; + URI.decodeQuery = function(string, escapeQuerySpace) { + string += ''; + if (escapeQuerySpace === undefined) { + escapeQuerySpace = URI.escapeQuerySpace; + } + + try { + return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string); + } catch(e) { + // we're not going to mess with weird encodings, + // give up and return the undecoded original string + // see https://github.com/medialize/URI.js/issues/87 + // see https://github.com/medialize/URI.js/issues/92 + return string; + } + }; + // generate encode/decode path functions + var _parts = {'encode':'encode', 'decode':'decode'}; + var _part; + var generateAccessor = function(_group, _part) { + return function(string) { + try { + return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) { + return URI.characters[_group][_part].map[c]; + }); + } catch (e) { + // we're not going to mess with weird encodings, + // give up and return the undecoded original string + // see https://github.com/medialize/URI.js/issues/87 + // see https://github.com/medialize/URI.js/issues/92 + return string; + } + }; + }; + + for (_part in _parts) { + URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]); + URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]); + } + + var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) { + return function(string) { + // Why pass in names of functions, rather than the function objects themselves? The + // definitions of some functions (but in particular, URI.decode) will occasionally change due + // to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure + // that the functions we use here are "fresh". + var actualCodingFunc; + if (!_innerCodingFuncName) { + actualCodingFunc = URI[_codingFuncName]; + } else { + actualCodingFunc = function(string) { + return URI[_codingFuncName](URI[_innerCodingFuncName](string)); + }; + } + + var segments = (string + '').split(_sep); + + for (var i = 0, length = segments.length; i < length; i++) { + segments[i] = actualCodingFunc(segments[i]); + } + + return segments.join(_sep); + }; + }; + + // This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions. + URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment'); + URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment'); + URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode'); + URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode'); + + URI.encodeReserved = generateAccessor('reserved', 'encode'); + + URI.parse = function(string, parts) { + var pos; + if (!parts) { + parts = { + preventInvalidHostname: URI.preventInvalidHostname + }; + } + + string = string.replace(URI.leading_whitespace_expression, '') + // https://infra.spec.whatwg.org/#ascii-tab-or-newline + string = string.replace(URI.ascii_tab_whitespace, '') + + // [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment] + + // extract fragment + pos = string.indexOf('#'); + if (pos > -1) { + // escaping? + parts.fragment = string.substring(pos + 1) || null; + string = string.substring(0, pos); + } + + // extract query + pos = string.indexOf('?'); + if (pos > -1) { + // escaping? + parts.query = string.substring(pos + 1) || null; + string = string.substring(0, pos); + } + + // slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws) + string = string.replace(/^(https?|ftp|wss?)?:+[/\\]*/i, '$1://'); + // slashes and backslashes have lost all meaning for scheme relative URLs + string = string.replace(/^[/\\]{2,}/i, '//'); + + // extract protocol + if (string.substring(0, 2) === '//') { + // relative-scheme + parts.protocol = null; + string = string.substring(2); + // extract "user:pass@host:port" + string = URI.parseAuthority(string, parts); + } else { + pos = string.indexOf(':'); + if (pos > -1) { + parts.protocol = string.substring(0, pos) || null; + if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) { + // : may be within the path + parts.protocol = undefined; + } else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') { + string = string.substring(pos + 3); + + // extract "user:pass@host:port" + string = URI.parseAuthority(string, parts); + } else { + string = string.substring(pos + 1); + parts.urn = true; + } + } + } + + // what's left must be the path + parts.path = string; + + // and we're done + return parts; + }; + URI.parseHost = function(string, parts) { + if (!string) { + string = ''; + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124 + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + // https://github.com/medialize/URI.js/pull/233 + string = string.replace(/\\/g, '/'); + + // extract host:port + var pos = string.indexOf('/'); + var bracketPos; + var t; + + if (pos === -1) { + pos = string.length; + } + + if (string.charAt(0) === '[') { + // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6 + // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts + // IPv6+port in the format [2001:db8::1]:80 (for the time being) + bracketPos = string.indexOf(']'); + parts.hostname = string.substring(1, bracketPos) || null; + parts.port = string.substring(bracketPos + 2, pos) || null; + if (parts.port === '/') { + parts.port = null; + } + } else { + var firstColon = string.indexOf(':'); + var firstSlash = string.indexOf('/'); + var nextColon = string.indexOf(':', firstColon + 1); + if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) { + // IPv6 host contains multiple colons - but no port + // this notation is actually not allowed by RFC 3986, but we're a liberal parser + parts.hostname = string.substring(0, pos) || null; + parts.port = null; + } else { + t = string.substring(0, pos).split(':'); + parts.hostname = t[0] || null; + parts.port = t[1] || null; + } + } + + if (parts.hostname && string.substring(pos).charAt(0) !== '/') { + pos++; + string = '/' + string; + } + + if (parts.preventInvalidHostname) { + URI.ensureValidHostname(parts.hostname, parts.protocol); + } + + if (parts.port) { + URI.ensureValidPort(parts.port); + } + + return string.substring(pos) || '/'; + }; + URI.parseAuthority = function(string, parts) { + string = URI.parseUserinfo(string, parts); + return URI.parseHost(string, parts); + }; + URI.parseUserinfo = function(string, parts) { + // extract username:password + var _string = string + var firstBackSlash = string.indexOf('\\'); + if (firstBackSlash !== -1) { + string = string.replace(/\\/g, '/') + } + var firstSlash = string.indexOf('/'); + var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1); + var t; + + // authority@ must come before /path or \path + if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) { + t = string.substring(0, pos).split(':'); + parts.username = t[0] ? URI.decode(t[0]) : null; + t.shift(); + parts.password = t[0] ? URI.decode(t.join(':')) : null; + string = _string.substring(pos + 1); + } else { + parts.username = null; + parts.password = null; + } + + return string; + }; + URI.parseQuery = function(string, escapeQuerySpace) { + if (!string) { + return {}; + } + + // throw out the funky business - "?"[name"="value"&"]+ + string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, ''); + + if (!string) { + return {}; + } + + var items = {}; + var splits = string.split('&'); + var length = splits.length; + var v, name, value; + + for (var i = 0; i < length; i++) { + v = splits[i].split('='); + name = URI.decodeQuery(v.shift(), escapeQuerySpace); + // no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters + value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null; + + if (name === '__proto__') { + // ignore attempt at exploiting JavaScript internals + continue; + } else if (hasOwn.call(items, name)) { + if (typeof items[name] === 'string' || items[name] === null) { + items[name] = [items[name]]; + } + + items[name].push(value); + } else { + items[name] = value; + } + } + + return items; + }; + + URI.build = function(parts) { + var t = ''; + var requireAbsolutePath = false + + if (parts.protocol) { + t += parts.protocol + ':'; + } + + if (!parts.urn && (t || parts.hostname)) { + t += '//'; + requireAbsolutePath = true + } + + t += (URI.buildAuthority(parts) || ''); + + if (typeof parts.path === 'string') { + if (parts.path.charAt(0) !== '/' && requireAbsolutePath) { + t += '/'; + } + + t += parts.path; + } + + if (typeof parts.query === 'string' && parts.query) { + t += '?' + parts.query; + } + + if (typeof parts.fragment === 'string' && parts.fragment) { + t += '#' + parts.fragment; + } + return t; + }; + URI.buildHost = function(parts) { + var t = ''; + + if (!parts.hostname) { + return ''; + } else if (URI.ip6_expression.test(parts.hostname)) { + t += '[' + parts.hostname + ']'; + } else { + t += parts.hostname; + } + + if (parts.port) { + t += ':' + parts.port; + } + + return t; + }; + URI.buildAuthority = function(parts) { + return URI.buildUserinfo(parts) + URI.buildHost(parts); + }; + URI.buildUserinfo = function(parts) { + var t = ''; + + if (parts.username) { + t += URI.encode(parts.username); + } + + if (parts.password) { + t += ':' + URI.encode(parts.password); + } + + if (t) { + t += '@'; + } + + return t; + }; + URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) { + // according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html + // being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed + // the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax! + // URI.js treats the query string as being application/x-www-form-urlencoded + // see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type + + var t = ''; + var unique, key, i, length; + for (key in data) { + if (key === '__proto__') { + // ignore attempt at exploiting JavaScript internals + continue; + } else if (hasOwn.call(data, key)) { + if (isArray(data[key])) { + unique = {}; + for (i = 0, length = data[key].length; i < length; i++) { + if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) { + t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace); + if (duplicateQueryParameters !== true) { + unique[data[key][i] + ''] = true; + } + } + } + } else if (data[key] !== undefined) { + t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace); + } + } + } + + return t.substring(1); + }; + URI.buildQueryParameter = function(name, value, escapeQuerySpace) { + // http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded + // don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization + return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : ''); + }; + + URI.addQuery = function(data, name, value) { + if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + URI.addQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + if (data[name] === undefined) { + data[name] = value; + return; + } else if (typeof data[name] === 'string') { + data[name] = [data[name]]; + } + + if (!isArray(value)) { + value = [value]; + } + + data[name] = (data[name] || []).concat(value); + } else { + throw new TypeError('URI.addQuery() accepts an object, string as the name parameter'); + } + }; + + URI.setQuery = function(data, name, value) { + if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + URI.setQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + data[name] = value === undefined ? null : value; + } else { + throw new TypeError('URI.setQuery() accepts an object, string as the name parameter'); + } + }; + + URI.removeQuery = function(data, name, value) { + var i, length, key; + + if (isArray(name)) { + for (i = 0, length = name.length; i < length; i++) { + data[name[i]] = undefined; + } + } else if (getType(name) === 'RegExp') { + for (key in data) { + if (name.test(key)) { + data[key] = undefined; + } + } + } else if (typeof name === 'object') { + for (key in name) { + if (hasOwn.call(name, key)) { + URI.removeQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + if (value !== undefined) { + if (getType(value) === 'RegExp') { + if (!isArray(data[name]) && value.test(data[name])) { + data[name] = undefined; + } else { + data[name] = filterArrayValues(data[name], value); + } + } else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) { + data[name] = undefined; + } else if (isArray(data[name])) { + data[name] = filterArrayValues(data[name], value); + } + } else { + data[name] = undefined; + } + } else { + throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter'); + } + }; + URI.hasQuery = function(data, name, value, withinArray) { + switch (getType(name)) { + case 'String': + // Nothing to do here + break; + + case 'RegExp': + for (var key in data) { + if (hasOwn.call(data, key)) { + if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) { + return true; + } + } + } + + return false; + + case 'Object': + for (var _key in name) { + if (hasOwn.call(name, _key)) { + if (!URI.hasQuery(data, _key, name[_key])) { + return false; + } + } + } + + return true; + + default: + throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter'); + } + + switch (getType(value)) { + case 'Undefined': + // true if exists (but may be empty) + return name in data; // data[name] !== undefined; + + case 'Boolean': + // true if exists and non-empty + var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]); + return value === _booly; + + case 'Function': + // allow complex comparison + return !!value(data[name], name, data); + + case 'Array': + if (!isArray(data[name])) { + return false; + } + + var op = withinArray ? arrayContains : arraysEqual; + return op(data[name], value); + + case 'RegExp': + if (!isArray(data[name])) { + return Boolean(data[name] && data[name].match(value)); + } + + if (!withinArray) { + return false; + } + + return arrayContains(data[name], value); + + case 'Number': + value = String(value); + /* falls through */ + case 'String': + if (!isArray(data[name])) { + return data[name] === value; + } + + if (!withinArray) { + return false; + } + + return arrayContains(data[name], value); + + default: + throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter'); + } + }; + + + URI.joinPaths = function() { + var input = []; + var segments = []; + var nonEmptySegments = 0; + + for (var i = 0; i < arguments.length; i++) { + var url = new URI(arguments[i]); + input.push(url); + var _segments = url.segment(); + for (var s = 0; s < _segments.length; s++) { + if (typeof _segments[s] === 'string') { + segments.push(_segments[s]); + } + + if (_segments[s]) { + nonEmptySegments++; + } + } + } + + if (!segments.length || !nonEmptySegments) { + return new URI(''); + } + + var uri = new URI('').segment(segments); + + if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') { + uri.path('/' + uri.path()); + } + + return uri.normalize(); + }; + + URI.commonPath = function(one, two) { + var length = Math.min(one.length, two.length); + var pos; + + // find first non-matching character + for (pos = 0; pos < length; pos++) { + if (one.charAt(pos) !== two.charAt(pos)) { + pos--; + break; + } + } + + if (pos < 1) { + return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : ''; + } + + // revert to last / + if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') { + pos = one.substring(0, pos).lastIndexOf('/'); + } + + return one.substring(0, pos + 1); + }; + + URI.withinString = function(string, callback, options) { + options || (options = {}); + var _start = options.start || URI.findUri.start; + var _end = options.end || URI.findUri.end; + var _trim = options.trim || URI.findUri.trim; + var _parens = options.parens || URI.findUri.parens; + var _attributeOpen = /[a-z0-9-]=["']?$/i; + + _start.lastIndex = 0; + while (true) { + var match = _start.exec(string); + if (!match) { + break; + } + + var start = match.index; + if (options.ignoreHtml) { + // attribut(e=["']?$) + var attributeOpen = string.slice(Math.max(start - 3, 0), start); + if (attributeOpen && _attributeOpen.test(attributeOpen)) { + continue; + } + } + + var end = start + string.slice(start).search(_end); + var slice = string.slice(start, end); + // make sure we include well balanced parens + var parensEnd = -1; + while (true) { + var parensMatch = _parens.exec(slice); + if (!parensMatch) { + break; + } + + var parensMatchEnd = parensMatch.index + parensMatch[0].length; + parensEnd = Math.max(parensEnd, parensMatchEnd); + } + + if (parensEnd > -1) { + slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, ''); + } else { + slice = slice.replace(_trim, ''); + } + + if (slice.length <= match[0].length) { + // the extract only contains the starting marker of a URI, + // e.g. "www" or "http://" + continue; + } + + if (options.ignore && options.ignore.test(slice)) { + continue; + } + + end = start + slice.length; + var result = callback(slice, start, end, string); + if (result === undefined) { + _start.lastIndex = end; + continue; + } + + result = String(result); + string = string.slice(0, start) + result + string.slice(end); + _start.lastIndex = start + result.length; + } + + _start.lastIndex = 0; + return string; + }; + + URI.ensureValidHostname = function(v, protocol) { + // Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986) + // they are not part of DNS and therefore ignored by URI.js + + var hasHostname = !!v; // not null and not an empty string + var hasProtocol = !!protocol; + var rejectEmptyHostname = false; + + if (hasProtocol) { + rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol); + } + + if (rejectEmptyHostname && !hasHostname) { + throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol); + } else if (v && v.match(URI.invalid_hostname_characters)) { + // test punycode + if (!punycode) { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available'); + } + if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]'); + } + } + }; + + URI.ensureValidPort = function (v) { + if (!v) { + return; + } + + var port = Number(v); + if (isInteger(port) && (port > 0) && (port < 65536)) { + return; + } + + throw new TypeError('Port "' + v + '" is not a valid port'); + }; + + // noConflict + URI.noConflict = function(removeAll) { + if (removeAll) { + var unconflicted = { + URI: this.noConflict() + }; + + if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') { + unconflicted.URITemplate = root.URITemplate.noConflict(); + } + + if (root.IPv6 && typeof root.IPv6.noConflict === 'function') { + unconflicted.IPv6 = root.IPv6.noConflict(); + } + + if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') { + unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict(); + } + + return unconflicted; + } else if (root.URI === this) { + root.URI = _URI; + } + + return this; + }; + + p.build = function(deferBuild) { + if (deferBuild === true) { + this._deferred_build = true; + } else if (deferBuild === undefined || this._deferred_build) { + this._string = URI.build(this._parts); + this._deferred_build = false; + } + + return this; + }; + + p.clone = function() { + return new URI(this); + }; + + p.valueOf = p.toString = function() { + return this.build(false)._string; + }; + + + function generateSimpleAccessor(_part){ + return function(v, build) { + if (v === undefined) { + return this._parts[_part] || ''; + } else { + this._parts[_part] = v || null; + this.build(!build); + return this; + } + }; + } + + function generatePrefixAccessor(_part, _key){ + return function(v, build) { + if (v === undefined) { + return this._parts[_part] || ''; + } else { + if (v !== null) { + v = v + ''; + if (v.charAt(0) === _key) { + v = v.substring(1); + } + } + + this._parts[_part] = v; + this.build(!build); + return this; + } + }; + } + + p.protocol = generateSimpleAccessor('protocol'); + p.username = generateSimpleAccessor('username'); + p.password = generateSimpleAccessor('password'); + p.hostname = generateSimpleAccessor('hostname'); + p.port = generateSimpleAccessor('port'); + p.query = generatePrefixAccessor('query', '?'); + p.fragment = generatePrefixAccessor('fragment', '#'); + + p.search = function(v, build) { + var t = this.query(v, build); + return typeof t === 'string' && t.length ? ('?' + t) : t; + }; + p.hash = function(v, build) { + var t = this.fragment(v, build); + return typeof t === 'string' && t.length ? ('#' + t) : t; + }; + + p.pathname = function(v, build) { + if (v === undefined || v === true) { + var res = this._parts.path || (this._parts.hostname ? '/' : ''); + return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res; + } else { + if (this._parts.urn) { + this._parts.path = v ? URI.recodeUrnPath(v) : ''; + } else { + this._parts.path = v ? URI.recodePath(v) : '/'; + } + this.build(!build); + return this; + } + }; + p.path = p.pathname; + p.href = function(href, build) { + var key; + + if (href === undefined) { + return this.toString(); + } + + this._string = ''; + this._parts = URI._parts(); + + var _URI = href instanceof URI; + var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname); + if (href.nodeName) { + var attribute = URI.getDomAttribute(href); + href = href[attribute] || ''; + _object = false; + } + + // window.location is reported to be an object, but it's not the sort + // of object we're looking for: + // * location.protocol ends with a colon + // * location.query != object.search + // * location.hash != object.fragment + // simply serializing the unknown object should do the trick + // (for location, not for everything...) + if (!_URI && _object && href.pathname !== undefined) { + href = href.toString(); + } + + if (typeof href === 'string' || href instanceof String) { + this._parts = URI.parse(String(href), this._parts); + } else if (_URI || _object) { + var src = _URI ? href._parts : href; + for (key in src) { + if (key === 'query') { continue; } + if (hasOwn.call(this._parts, key)) { + this._parts[key] = src[key]; + } + } + if (src.query) { + this.query(src.query, false); + } + } else { + throw new TypeError('invalid input'); + } + + this.build(!build); + return this; + }; + + // identification accessors + p.is = function(what) { + var ip = false; + var ip4 = false; + var ip6 = false; + var name = false; + var sld = false; + var idn = false; + var punycode = false; + var relative = !this._parts.urn; + + if (this._parts.hostname) { + relative = false; + ip4 = URI.ip4_expression.test(this._parts.hostname); + ip6 = URI.ip6_expression.test(this._parts.hostname); + ip = ip4 || ip6; + name = !ip; + sld = name && SLD && SLD.has(this._parts.hostname); + idn = name && URI.idn_expression.test(this._parts.hostname); + punycode = name && URI.punycode_expression.test(this._parts.hostname); + } + + switch (what.toLowerCase()) { + case 'relative': + return relative; + + case 'absolute': + return !relative; + + // hostname identification + case 'domain': + case 'name': + return name; + + case 'sld': + return sld; + + case 'ip': + return ip; + + case 'ip4': + case 'ipv4': + case 'inet4': + return ip4; + + case 'ip6': + case 'ipv6': + case 'inet6': + return ip6; + + case 'idn': + return idn; + + case 'url': + return !this._parts.urn; + + case 'urn': + return !!this._parts.urn; + + case 'punycode': + return punycode; + } + + return null; + }; + + // component specific input validation + var _protocol = p.protocol; + var _port = p.port; + var _hostname = p.hostname; + + p.protocol = function(v, build) { + if (v) { + // accept trailing :// + v = v.replace(/:(\/\/)?$/, ''); + + if (!v.match(URI.protocol_expression)) { + throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]'); + } + } + + return _protocol.call(this, v, build); + }; + p.scheme = p.protocol; + p.port = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v !== undefined) { + if (v === 0) { + v = null; + } + + if (v) { + v += ''; + if (v.charAt(0) === ':') { + v = v.substring(1); + } + + URI.ensureValidPort(v); + } + } + return _port.call(this, v, build); + }; + p.hostname = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v !== undefined) { + var x = { preventInvalidHostname: this._parts.preventInvalidHostname }; + var res = URI.parseHost(v, x); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + v = x.hostname; + if (this._parts.preventInvalidHostname) { + URI.ensureValidHostname(v, this._parts.protocol); + } + } + + return _hostname.call(this, v, build); + }; + + // compound accessors + p.origin = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + var protocol = this.protocol(); + var authority = this.authority(); + if (!authority) { + return ''; + } + + return (protocol ? protocol + '://' : '') + this.authority(); + } else { + var origin = URI(v); + this + .protocol(origin.protocol()) + .authority(origin.authority()) + .build(!build); + return this; + } + }; + p.host = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + return this._parts.hostname ? URI.buildHost(this._parts) : ''; + } else { + var res = URI.parseHost(v, this._parts); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + this.build(!build); + return this; + } + }; + p.authority = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + return this._parts.hostname ? URI.buildAuthority(this._parts) : ''; + } else { + var res = URI.parseAuthority(v, this._parts); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + this.build(!build); + return this; + } + }; + p.userinfo = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + var t = URI.buildUserinfo(this._parts); + return t ? t.substring(0, t.length -1) : t; + } else { + if (v[v.length-1] !== '@') { + v += '@'; + } + + URI.parseUserinfo(v, this._parts); + this.build(!build); + return this; + } + }; + p.resource = function(v, build) { + var parts; + + if (v === undefined) { + return this.path() + this.search() + this.hash(); + } + + parts = URI.parse(v); + this._parts.path = parts.path; + this._parts.query = parts.query; + this._parts.fragment = parts.fragment; + this.build(!build); + return this; + }; + + // fraction accessors + p.subdomain = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + // convenience, return "www" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + // grab domain and add another segment + var end = this._parts.hostname.length - this.domain().length - 1; + return this._parts.hostname.substring(0, end) || ''; + } else { + var e = this._parts.hostname.length - this.domain().length; + var sub = this._parts.hostname.substring(0, e); + var replace = new RegExp('^' + escapeRegEx(sub)); + + if (v && v.charAt(v.length - 1) !== '.') { + v += '.'; + } + + if (v.indexOf(':') !== -1) { + throw new TypeError('Domains cannot contain colons'); + } + + if (v) { + URI.ensureValidHostname(v, this._parts.protocol); + } + + this._parts.hostname = this._parts.hostname.replace(replace, v); + this.build(!build); + return this; + } + }; + p.domain = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v === 'boolean') { + build = v; + v = undefined; + } + + // convenience, return "example.org" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + // if hostname consists of 1 or 2 segments, it must be the domain + var t = this._parts.hostname.match(/\./g); + if (t && t.length < 2) { + return this._parts.hostname; + } + + // grab tld and add another segment + var end = this._parts.hostname.length - this.tld(build).length - 1; + end = this._parts.hostname.lastIndexOf('.', end -1) + 1; + return this._parts.hostname.substring(end) || ''; + } else { + if (!v) { + throw new TypeError('cannot set domain empty'); + } + + if (v.indexOf(':') !== -1) { + throw new TypeError('Domains cannot contain colons'); + } + + URI.ensureValidHostname(v, this._parts.protocol); + + if (!this._parts.hostname || this.is('IP')) { + this._parts.hostname = v; + } else { + var replace = new RegExp(escapeRegEx(this.domain()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.tld = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v === 'boolean') { + build = v; + v = undefined; + } + + // return "org" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + var pos = this._parts.hostname.lastIndexOf('.'); + var tld = this._parts.hostname.substring(pos + 1); + + if (build !== true && SLD && SLD.list[tld.toLowerCase()]) { + return SLD.get(this._parts.hostname) || tld; + } + + return tld; + } else { + var replace; + + if (!v) { + throw new TypeError('cannot set TLD empty'); + } else if (v.match(/[^a-zA-Z0-9-]/)) { + if (SLD && SLD.is(v)) { + replace = new RegExp(escapeRegEx(this.tld()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } else { + throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]'); + } + } else if (!this._parts.hostname || this.is('IP')) { + throw new ReferenceError('cannot set TLD on non-domain host'); + } else { + replace = new RegExp(escapeRegEx(this.tld()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.directory = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined || v === true) { + if (!this._parts.path && !this._parts.hostname) { + return ''; + } + + if (this._parts.path === '/') { + return '/'; + } + + var end = this._parts.path.length - this.filename().length - 1; + var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : ''); + + return v ? URI.decodePath(res) : res; + + } else { + var e = this._parts.path.length - this.filename().length; + var directory = this._parts.path.substring(0, e); + var replace = new RegExp('^' + escapeRegEx(directory)); + + // fully qualifier directories begin with a slash + if (!this.is('relative')) { + if (!v) { + v = '/'; + } + + if (v.charAt(0) !== '/') { + v = '/' + v; + } + } + + // directories always end with a slash + if (v && v.charAt(v.length - 1) !== '/') { + v += '/'; + } + + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + this.build(!build); + return this; + } + }; + p.filename = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v !== 'string') { + if (!this._parts.path || this._parts.path === '/') { + return ''; + } + + var pos = this._parts.path.lastIndexOf('/'); + var res = this._parts.path.substring(pos+1); + + return v ? URI.decodePathSegment(res) : res; + } else { + var mutatedDirectory = false; + + if (v.charAt(0) === '/') { + v = v.substring(1); + } + + if (v.match(/\.?\//)) { + mutatedDirectory = true; + } + + var replace = new RegExp(escapeRegEx(this.filename()) + '$'); + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + + if (mutatedDirectory) { + this.normalizePath(build); + } else { + this.build(!build); + } + + return this; + } + }; + p.suffix = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined || v === true) { + if (!this._parts.path || this._parts.path === '/') { + return ''; + } + + var filename = this.filename(); + var pos = filename.lastIndexOf('.'); + var s, res; + + if (pos === -1) { + return ''; + } + + // suffix may only contain alnum characters (yup, I made this up.) + s = filename.substring(pos+1); + res = (/^[a-z0-9%]+$/i).test(s) ? s : ''; + return v ? URI.decodePathSegment(res) : res; + } else { + if (v.charAt(0) === '.') { + v = v.substring(1); + } + + var suffix = this.suffix(); + var replace; + + if (!suffix) { + if (!v) { + return this; + } + + this._parts.path += '.' + URI.recodePath(v); + } else if (!v) { + replace = new RegExp(escapeRegEx('.' + suffix) + '$'); + } else { + replace = new RegExp(escapeRegEx(suffix) + '$'); + } + + if (replace) { + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.segment = function(segment, v, build) { + var separator = this._parts.urn ? ':' : '/'; + var path = this.path(); + var absolute = path.substring(0, 1) === '/'; + var segments = path.split(separator); + + if (segment !== undefined && typeof segment !== 'number') { + build = v; + v = segment; + segment = undefined; + } + + if (segment !== undefined && typeof segment !== 'number') { + throw new Error('Bad segment "' + segment + '", must be 0-based integer'); + } + + if (absolute) { + segments.shift(); + } + + if (segment < 0) { + // allow negative indexes to address from the end + segment = Math.max(segments.length + segment, 0); + } + + if (v === undefined) { + /*jshint laxbreak: true */ + return segment === undefined + ? segments + : segments[segment]; + /*jshint laxbreak: false */ + } else if (segment === null || segments[segment] === undefined) { + if (isArray(v)) { + segments = []; + // collapse empty elements within array + for (var i=0, l=v.length; i < l; i++) { + if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) { + continue; + } + + if (segments.length && !segments[segments.length -1].length) { + segments.pop(); + } + + segments.push(trimSlashes(v[i])); + } + } else if (v || typeof v === 'string') { + v = trimSlashes(v); + if (segments[segments.length -1] === '') { + // empty trailing elements have to be overwritten + // to prevent results such as /foo//bar + segments[segments.length -1] = v; + } else { + segments.push(v); + } + } + } else { + if (v) { + segments[segment] = trimSlashes(v); + } else { + segments.splice(segment, 1); + } + } + + if (absolute) { + segments.unshift(''); + } + + return this.path(segments.join(separator), build); + }; + p.segmentCoded = function(segment, v, build) { + var segments, i, l; + + if (typeof segment !== 'number') { + build = v; + v = segment; + segment = undefined; + } + + if (v === undefined) { + segments = this.segment(segment, v, build); + if (!isArray(segments)) { + segments = segments !== undefined ? URI.decode(segments) : undefined; + } else { + for (i = 0, l = segments.length; i < l; i++) { + segments[i] = URI.decode(segments[i]); + } + } + + return segments; + } + + if (!isArray(v)) { + v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v; + } else { + for (i = 0, l = v.length; i < l; i++) { + v[i] = URI.encode(v[i]); + } + } + + return this.segment(segment, v, build); + }; + + // mutating query string + var q = p.query; + p.query = function(v, build) { + if (v === true) { + return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + } else if (typeof v === 'function') { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + var result = v.call(this, data); + this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + this.build(!build); + return this; + } else if (v !== undefined && typeof v !== 'string') { + this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + this.build(!build); + return this; + } else { + return q.call(this, v, build); + } + }; + p.setQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + + if (typeof name === 'string' || name instanceof String) { + data[name] = value !== undefined ? value : null; + } else if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + data[key] = name[key]; + } + } + } else { + throw new TypeError('URI.addQuery() accepts an object, string as the name parameter'); + } + + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.addQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + URI.addQuery(data, name, value === undefined ? null : value); + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.removeQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + URI.removeQuery(data, name, value); + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.hasQuery = function(name, value, withinArray) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + return URI.hasQuery(data, name, value, withinArray); + }; + p.setSearch = p.setQuery; + p.addSearch = p.addQuery; + p.removeSearch = p.removeQuery; + p.hasSearch = p.hasQuery; + + // sanitizing URLs + p.normalize = function() { + if (this._parts.urn) { + return this + .normalizeProtocol(false) + .normalizePath(false) + .normalizeQuery(false) + .normalizeFragment(false) + .build(); + } + + return this + .normalizeProtocol(false) + .normalizeHostname(false) + .normalizePort(false) + .normalizePath(false) + .normalizeQuery(false) + .normalizeFragment(false) + .build(); + }; + p.normalizeProtocol = function(build) { + if (typeof this._parts.protocol === 'string') { + this._parts.protocol = this._parts.protocol.toLowerCase(); + this.build(!build); + } + + return this; + }; + p.normalizeHostname = function(build) { + if (this._parts.hostname) { + if (this.is('IDN') && punycode) { + this._parts.hostname = punycode.toASCII(this._parts.hostname); + } else if (this.is('IPv6') && IPv6) { + this._parts.hostname = IPv6.best(this._parts.hostname); + } + + this._parts.hostname = this._parts.hostname.toLowerCase(); + this.build(!build); + } + + return this; + }; + p.normalizePort = function(build) { + // remove port of it's the protocol's default + if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) { + this._parts.port = null; + this.build(!build); + } + + return this; + }; + p.normalizePath = function(build) { + var _path = this._parts.path; + if (!_path) { + return this; + } + + if (this._parts.urn) { + this._parts.path = URI.recodeUrnPath(this._parts.path); + this.build(!build); + return this; + } + + if (this._parts.path === '/') { + return this; + } + + _path = URI.recodePath(_path); + + var _was_relative; + var _leadingParents = ''; + var _parent, _pos; + + // handle relative paths + if (_path.charAt(0) !== '/') { + _was_relative = true; + _path = '/' + _path; + } + + // handle relative files (as opposed to directories) + if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') { + _path += '/'; + } + + // resolve simples + _path = _path + .replace(/(\/(\.\/)+)|(\/\.$)/g, '/') + .replace(/\/{2,}/g, '/'); + + // remember leading parents + if (_was_relative) { + _leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || ''; + if (_leadingParents) { + _leadingParents = _leadingParents[0]; + } + } + + // resolve parents + while (true) { + _parent = _path.search(/\/\.\.(\/|$)/); + if (_parent === -1) { + // no more ../ to resolve + break; + } else if (_parent === 0) { + // top level cannot be relative, skip it + _path = _path.substring(3); + continue; + } + + _pos = _path.substring(0, _parent).lastIndexOf('/'); + if (_pos === -1) { + _pos = _parent; + } + _path = _path.substring(0, _pos) + _path.substring(_parent + 3); + } + + // revert to relative + if (_was_relative && this.is('relative')) { + _path = _leadingParents + _path.substring(1); + } + + this._parts.path = _path; + this.build(!build); + return this; + }; + p.normalizePathname = p.normalizePath; + p.normalizeQuery = function(build) { + if (typeof this._parts.query === 'string') { + if (!this._parts.query.length) { + this._parts.query = null; + } else { + this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace)); + } + + this.build(!build); + } + + return this; + }; + p.normalizeFragment = function(build) { + if (!this._parts.fragment) { + this._parts.fragment = null; + this.build(!build); + } + + return this; + }; + p.normalizeSearch = p.normalizeQuery; + p.normalizeHash = p.normalizeFragment; + + p.iso8859 = function() { + // expect unicode input, iso8859 output + var e = URI.encode; + var d = URI.decode; + + URI.encode = escape; + URI.decode = decodeURIComponent; + try { + this.normalize(); + } finally { + URI.encode = e; + URI.decode = d; + } + return this; + }; + + p.unicode = function() { + // expect iso8859 input, unicode output + var e = URI.encode; + var d = URI.decode; + + URI.encode = strictEncodeURIComponent; + URI.decode = unescape; + try { + this.normalize(); + } finally { + URI.encode = e; + URI.decode = d; + } + return this; + }; + + p.readable = function() { + var uri = this.clone(); + // removing username, password, because they shouldn't be displayed according to RFC 3986 + uri.username('').password('').normalize(); + var t = ''; + if (uri._parts.protocol) { + t += uri._parts.protocol + '://'; + } + + if (uri._parts.hostname) { + if (uri.is('punycode') && punycode) { + t += punycode.toUnicode(uri._parts.hostname); + if (uri._parts.port) { + t += ':' + uri._parts.port; + } + } else { + t += uri.host(); + } + } + + if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') { + t += '/'; + } + + t += uri.path(true); + if (uri._parts.query) { + var q = ''; + for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) { + var kv = (qp[i] || '').split('='); + q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace) + .replace(/&/g, '%26'); + + if (kv[1] !== undefined) { + q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace) + .replace(/&/g, '%26'); + } + } + t += '?' + q.substring(1); + } + + t += URI.decodeQuery(uri.hash(), true); + return t; + }; + + // resolving relative and absolute URLs + p.absoluteTo = function(base) { + var resolved = this.clone(); + var properties = ['protocol', 'username', 'password', 'hostname', 'port']; + var basedir, i, p; + + if (this._parts.urn) { + throw new Error('URNs do not have any generally defined hierarchical components'); + } + + if (!(base instanceof URI)) { + base = new URI(base); + } + + if (resolved._parts.protocol) { + // Directly returns even if this._parts.hostname is empty. + return resolved; + } else { + resolved._parts.protocol = base._parts.protocol; + } + + if (this._parts.hostname) { + return resolved; + } + + for (i = 0; (p = properties[i]); i++) { + resolved._parts[p] = base._parts[p]; + } + + if (!resolved._parts.path) { + resolved._parts.path = base._parts.path; + if (!resolved._parts.query) { + resolved._parts.query = base._parts.query; + } + } else { + if (resolved._parts.path.substring(-2) === '..') { + resolved._parts.path += '/'; + } + + if (resolved.path().charAt(0) !== '/') { + basedir = base.directory(); + basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : ''; + resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path; + resolved.normalizePath(); + } + } + + resolved.build(); + return resolved; + }; + p.relativeTo = function(base) { + var relative = this.clone().normalize(); + var relativeParts, baseParts, common, relativePath, basePath; + + if (relative._parts.urn) { + throw new Error('URNs do not have any generally defined hierarchical components'); + } + + base = new URI(base).normalize(); + relativeParts = relative._parts; + baseParts = base._parts; + relativePath = relative.path(); + basePath = base.path(); + + if (relativePath.charAt(0) !== '/') { + throw new Error('URI is already relative'); + } + + if (basePath.charAt(0) !== '/') { + throw new Error('Cannot calculate a URI relative to another relative URI'); + } + + if (relativeParts.protocol === baseParts.protocol) { + relativeParts.protocol = null; + } + + if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) { + return relative.build(); + } + + if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) { + return relative.build(); + } + + if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) { + relativeParts.hostname = null; + relativeParts.port = null; + } else { + return relative.build(); + } + + if (relativePath === basePath) { + relativeParts.path = ''; + return relative.build(); + } + + // determine common sub path + common = URI.commonPath(relativePath, basePath); + + // If the paths have nothing in common, return a relative URL with the absolute path. + if (!common) { + return relative.build(); + } + + var parents = baseParts.path + .substring(common.length) + .replace(/[^\/]*$/, '') + .replace(/.*?\//g, '../'); + + relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './'; + + return relative.build(); + }; + + // comparing URIs + p.equals = function(uri) { + var one = this.clone(); + var two = new URI(uri); + var one_map = {}; + var two_map = {}; + var checked = {}; + var one_query, two_query, key; + + one.normalize(); + two.normalize(); + + // exact match + if (one.toString() === two.toString()) { + return true; + } + + // extract query string + one_query = one.query(); + two_query = two.query(); + one.query(''); + two.query(''); + + // definitely not equal if not even non-query parts match + if (one.toString() !== two.toString()) { + return false; + } + + // query parameters have the same length, even if they're permuted + if (one_query.length !== two_query.length) { + return false; + } + + one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace); + two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace); + + for (key in one_map) { + if (hasOwn.call(one_map, key)) { + if (!isArray(one_map[key])) { + if (one_map[key] !== two_map[key]) { + return false; + } + } else if (!arraysEqual(one_map[key], two_map[key])) { + return false; + } + + checked[key] = true; + } + } + + for (key in two_map) { + if (hasOwn.call(two_map, key)) { + if (!checked[key]) { + // two contains a parameter not present in one + return false; + } + } + } + + return true; + }; + + // state + p.preventInvalidHostname = function(v) { + this._parts.preventInvalidHostname = !!v; + return this; + }; + + p.duplicateQueryParameters = function(v) { + this._parts.duplicateQueryParameters = !!v; + return this; + }; + + p.escapeQuerySpace = function(v) { + this._parts.escapeQuerySpace = !!v; + return this; + }; + + return URI; +})); + + +/***/ }), + +/***/ 9127: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * URI Template Support - http://tools.ietf.org/html/rfc6570 + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(__webpack_require__(4193)); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4193)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (URI, root) { + 'use strict'; + // FIXME: v2.0.0 renamce non-camelCase properties to uppercase + /*jshint camelcase: false */ + + // save current URITemplate variable, if any + var _URITemplate = root && root.URITemplate; + + var hasOwn = Object.prototype.hasOwnProperty; + function URITemplate(expression) { + // serve from cache where possible + if (URITemplate._cache[expression]) { + return URITemplate._cache[expression]; + } + + // Allow instantiation without the 'new' keyword + if (!(this instanceof URITemplate)) { + return new URITemplate(expression); + } + + this.expression = expression; + URITemplate._cache[expression] = this; + return this; + } + + function Data(data) { + this.data = data; + this.cache = {}; + } + + var p = URITemplate.prototype; + // list of operators and their defined options + var operators = { + // Simple string expansion + '' : { + prefix: '', + separator: ',', + named: false, + empty_name_separator: false, + encode : 'encode' + }, + // Reserved character strings + '+' : { + prefix: '', + separator: ',', + named: false, + empty_name_separator: false, + encode : 'encodeReserved' + }, + // Fragment identifiers prefixed by '#' + '#' : { + prefix: '#', + separator: ',', + named: false, + empty_name_separator: false, + encode : 'encodeReserved' + }, + // Name labels or extensions prefixed by '.' + '.' : { + prefix: '.', + separator: '.', + named: false, + empty_name_separator: false, + encode : 'encode' + }, + // Path segments prefixed by '/' + '/' : { + prefix: '/', + separator: '/', + named: false, + empty_name_separator: false, + encode : 'encode' + }, + // Path parameter name or name=value pairs prefixed by ';' + ';' : { + prefix: ';', + separator: ';', + named: true, + empty_name_separator: false, + encode : 'encode' + }, + // Query component beginning with '?' and consisting + // of name=value pairs separated by '&'; an + '?' : { + prefix: '?', + separator: '&', + named: true, + empty_name_separator: true, + encode : 'encode' + }, + // Continuation of query-style &name=value pairs + // within a literal query component. + '&' : { + prefix: '&', + separator: '&', + named: true, + empty_name_separator: true, + encode : 'encode' + } + + // The operator characters equals ("="), comma (","), exclamation ("!"), + // at sign ("@"), and pipe ("|") are reserved for future extensions. + }; + + // storage for already parsed templates + URITemplate._cache = {}; + // pattern to identify expressions [operator, variable-list] in template + URITemplate.EXPRESSION_PATTERN = /\{([^a-zA-Z0-9%_]?)([^\}]+)(\}|$)/g; + // pattern to identify variables [name, explode, maxlength] in variable-list + URITemplate.VARIABLE_PATTERN = /^([^*:.](?:\.?[^*:.])*)((\*)|:(\d+))?$/; + // pattern to verify variable name integrity + URITemplate.VARIABLE_NAME_PATTERN = /[^a-zA-Z0-9%_.]/; + // pattern to verify literal integrity + URITemplate.LITERAL_PATTERN = /[<>{}"`^| \\]/; + + // expand parsed expression (expression, not template!) + URITemplate.expand = function(expression, data, opts) { + // container for defined options for the given operator + var options = operators[expression.operator]; + // expansion type (include keys or not) + var type = options.named ? 'Named' : 'Unnamed'; + // list of variables within the expression + var variables = expression.variables; + // result buffer for evaluating the expression + var buffer = []; + var d, variable, i; + + for (i = 0; (variable = variables[i]); i++) { + // fetch simplified data source + d = data.get(variable.name); + if (d.type === 0 && opts && opts.strict) { + throw new Error('Missing expansion value for variable "' + variable.name + '"'); + } + if (!d.val.length) { + if (d.type) { + // empty variables (empty string) + // still lead to a separator being appended! + buffer.push(''); + } + // no data, no action + continue; + } + + if (d.type > 1 && variable.maxlength) { + // composite variable cannot specify maxlength + throw new Error('Invalid expression: Prefix modifier not applicable to variable "' + variable.name + '"'); + } + + // expand the given variable + buffer.push(URITemplate['expand' + type]( + d, + options, + variable.explode, + variable.explode && options.separator || ',', + variable.maxlength, + variable.name + )); + } + + if (buffer.length) { + return options.prefix + buffer.join(options.separator); + } else { + // prefix is not prepended for empty expressions + return ''; + } + }; + // expand a named variable + URITemplate.expandNamed = function(d, options, explode, separator, length, name) { + // variable result buffer + var result = ''; + // peformance crap + var encode = options.encode; + var empty_name_separator = options.empty_name_separator; + // flag noting if values are already encoded + var _encode = !d[encode].length; + // key for named expansion + var _name = d.type === 2 ? '': URI[encode](name); + var _value, i, l; + + // for each found value + for (i = 0, l = d.val.length; i < l; i++) { + if (length) { + // maxlength must be determined before encoding can happen + _value = URI[encode](d.val[i][1].substring(0, length)); + if (d.type === 2) { + // apply maxlength to keys of objects as well + _name = URI[encode](d.val[i][0].substring(0, length)); + } + } else if (_encode) { + // encode value + _value = URI[encode](d.val[i][1]); + if (d.type === 2) { + // encode name and cache encoded value + _name = URI[encode](d.val[i][0]); + d[encode].push([_name, _value]); + } else { + // cache encoded value + d[encode].push([undefined, _value]); + } + } else { + // values are already encoded and can be pulled from cache + _value = d[encode][i][1]; + if (d.type === 2) { + _name = d[encode][i][0]; + } + } + + if (result) { + // unless we're the first value, prepend the separator + result += separator; + } + + if (!explode) { + if (!i) { + // first element, so prepend variable name + result += URI[encode](name) + (empty_name_separator || _value ? '=' : ''); + } + + if (d.type === 2) { + // without explode-modifier, keys of objects are returned comma-separated + result += _name + ','; + } + + result += _value; + } else { + // only add the = if it is either default (?&) or there actually is a value (;) + result += _name + (empty_name_separator || _value ? '=' : '') + _value; + } + } + + return result; + }; + // expand an unnamed variable + URITemplate.expandUnnamed = function(d, options, explode, separator, length) { + // variable result buffer + var result = ''; + // performance crap + var encode = options.encode; + var empty_name_separator = options.empty_name_separator; + // flag noting if values are already encoded + var _encode = !d[encode].length; + var _name, _value, i, l; + + // for each found value + for (i = 0, l = d.val.length; i < l; i++) { + if (length) { + // maxlength must be determined before encoding can happen + _value = URI[encode](d.val[i][1].substring(0, length)); + } else if (_encode) { + // encode and cache value + _value = URI[encode](d.val[i][1]); + d[encode].push([ + d.type === 2 ? URI[encode](d.val[i][0]) : undefined, + _value + ]); + } else { + // value already encoded, pull from cache + _value = d[encode][i][1]; + } + + if (result) { + // unless we're the first value, prepend the separator + result += separator; + } + + if (d.type === 2) { + if (length) { + // maxlength also applies to keys of objects + _name = URI[encode](d.val[i][0].substring(0, length)); + } else { + // at this point the name must already be encoded + _name = d[encode][i][0]; + } + + result += _name; + if (explode) { + // explode-modifier separates name and value by "=" + result += (empty_name_separator || _value ? '=' : ''); + } else { + // no explode-modifier separates name and value by "," + result += ','; + } + } + + result += _value; + } + + return result; + }; + + URITemplate.noConflict = function() { + if (root.URITemplate === URITemplate) { + root.URITemplate = _URITemplate; + } + + return URITemplate; + }; + + // expand template through given data map + p.expand = function(data, opts) { + var result = ''; + + if (!this.parts || !this.parts.length) { + // lazilyy parse the template + this.parse(); + } + + if (!(data instanceof Data)) { + // make given data available through the + // optimized data handling thingie + data = new Data(data); + } + + for (var i = 0, l = this.parts.length; i < l; i++) { + /*jshint laxbreak: true */ + result += typeof this.parts[i] === 'string' + // literal string + ? this.parts[i] + // expression + : URITemplate.expand(this.parts[i], data, opts); + /*jshint laxbreak: false */ + } + + return result; + }; + // parse template into action tokens + p.parse = function() { + // performance crap + var expression = this.expression; + var ePattern = URITemplate.EXPRESSION_PATTERN; + var vPattern = URITemplate.VARIABLE_PATTERN; + var nPattern = URITemplate.VARIABLE_NAME_PATTERN; + var lPattern = URITemplate.LITERAL_PATTERN; + // token result buffer + var parts = []; + // position within source template + var pos = 0; + var variables, eMatch, vMatch; + + var checkLiteral = function(literal) { + if (literal.match(lPattern)) { + throw new Error('Invalid Literal "' + literal + '"'); + } + return literal; + }; + + // RegExp is shared accross all templates, + // which requires a manual reset + ePattern.lastIndex = 0; + // I don't like while(foo = bar()) loops, + // to make things simpler I go while(true) and break when required + while (true) { + eMatch = ePattern.exec(expression); + if (eMatch === null) { + // push trailing literal + parts.push(checkLiteral(expression.substring(pos))); + break; + } else { + // push leading literal + parts.push(checkLiteral(expression.substring(pos, eMatch.index))); + pos = eMatch.index + eMatch[0].length; + } + + if (!operators[eMatch[1]]) { + throw new Error('Unknown Operator "' + eMatch[1] + '" in "' + eMatch[0] + '"'); + } else if (!eMatch[3]) { + throw new Error('Unclosed Expression "' + eMatch[0] + '"'); + } + + // parse variable-list + variables = eMatch[2].split(','); + for (var i = 0, l = variables.length; i < l; i++) { + vMatch = variables[i].match(vPattern); + if (vMatch === null) { + throw new Error('Invalid Variable "' + variables[i] + '" in "' + eMatch[0] + '"'); + } else if (vMatch[1].match(nPattern)) { + throw new Error('Invalid Variable Name "' + vMatch[1] + '" in "' + eMatch[0] + '"'); + } + + variables[i] = { + name: vMatch[1], + explode: !!vMatch[3], + maxlength: vMatch[4] && parseInt(vMatch[4], 10) + }; + } + + if (!variables.length) { + throw new Error('Expression Missing Variable(s) "' + eMatch[0] + '"'); + } + + parts.push({ + expression: eMatch[0], + operator: eMatch[1], + variables: variables + }); + } + + if (!parts.length) { + // template doesn't contain any expressions + // so it is a simple literal string + // this probably should fire a warning or something? + parts.push(checkLiteral(expression)); + } + + this.parts = parts; + return this; + }; + + // simplify data structures + Data.prototype.get = function(key) { + // performance crap + var data = this.data; + // cache for processed data-point + var d = { + // type of data 0: undefined/null, 1: string, 2: object, 3: array + type: 0, + // original values (except undefined/null) + val: [], + // cache for encoded values (only for non-maxlength expansion) + encode: [], + encodeReserved: [] + }; + var i, l, value; + + if (this.cache[key] !== undefined) { + // we've already processed this key + return this.cache[key]; + } + + this.cache[key] = d; + + if (String(Object.prototype.toString.call(data)) === '[object Function]') { + // data itself is a callback (global callback) + value = data(key); + } else if (String(Object.prototype.toString.call(data[key])) === '[object Function]') { + // data is a map of callbacks (local callback) + value = data[key](key); + } else { + // data is a map of data + value = data[key]; + } + + // generalize input into [ [name1, value1], [name2, value2], … ] + // so expansion has to deal with a single data structure only + if (value === undefined || value === null) { + // undefined and null values are to be ignored completely + return d; + } else if (String(Object.prototype.toString.call(value)) === '[object Array]') { + for (i = 0, l = value.length; i < l; i++) { + if (value[i] !== undefined && value[i] !== null) { + // arrays don't have names + d.val.push([undefined, String(value[i])]); + } + } + + if (d.val.length) { + // only treat non-empty arrays as arrays + d.type = 3; // array + } + } else if (String(Object.prototype.toString.call(value)) === '[object Object]') { + for (i in value) { + if (hasOwn.call(value, i) && value[i] !== undefined && value[i] !== null) { + // objects have keys, remember them for named expansion + d.val.push([i, String(value[i])]); + } + } + + if (d.val.length) { + // only treat non-empty objects as objects + d.type = 2; // object + } + } else { + d.type = 1; // primitive string (could've been string, number, boolean and objects with a toString()) + // arrays don't have names + d.val.push([undefined, String(value)]); + } + + return d; + }; + + // hook into URI for fluid access + URI.expand = function(expression, data) { + var template = new URITemplate(expression); + var expansion = template.expand(data); + + return new URI(expansion); + }; + + return URITemplate; +})); + + +/***/ }), + +/***/ 9340: +/***/ (function(module, exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.0 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = true && exports && + !exports.nodeType && exports; + var freeModule = true && module && + !module.nodeType && module; + var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + true + ) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { + return punycode; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} + +}(this)); + + +/***/ }), + +/***/ 1270: +/***/ (function(module, exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = true && exports && + !exports.nodeType && exports; + var freeModule = true && module && + !module.nodeType && module; + var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + true + ) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { + return punycode; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} + +}(this)); + + +/***/ }), + +/***/ 8835: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* + * 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. + */ + + + +var punycode = __webpack_require__(1270); + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +/* + * define these here so at least they only have to be + * compiled once on the first module load. + */ +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/, + + /* + * RFC 2396: characters reserved for delimiting URLs. + * We actually just auto-escape these. + */ + delims = [ + '<', '>', '"', '`', ' ', '\r', '\n', '\t' + ], + + // RFC 2396: characters not allowed for various reasons. + unwise = [ + '{', '}', '|', '\\', '^', '`' + ].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + /* + * Characters that are never ever allowed in a hostname. + * Note that any invalid chars are also handled, but these + * are the ones that are *expected* to be seen, so we fast-path + * them. + */ + nonHostChars = [ + '%', '/', '?', ';', '#' + ].concat(autoEscape), + hostEndingChars = [ + '/', '?', '#' + ], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + javascript: true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + javascript: true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + http: true, + https: true, + ftp: true, + gopher: true, + file: true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = __webpack_require__(5373); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && typeof url === 'object' && url instanceof Url) { return url; } + + var u = new Url(); + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) { + if (typeof url !== 'string') { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + /* + * Copy chrome, IE, opera backslash-handling behavior. + * Back slashes before the query string get converted to forward slashes + * See: https://code.google.com/p/chromium/issues/detail?id=25916 + */ + var queryIndex = url.indexOf('?'), + splitter = queryIndex !== -1 && queryIndex < url.indexOf('#') ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + /* + * trim before proceeding. + * This is to support parse stuff like " http://foo.com \n" + */ + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + /* + * figure out if it's got a host + * user@server is *always* interpreted as a hostname, and url + * resolution will treat //foo/bar as host=foo,path=bar because that's + * how the browser resolves relative URLs. + */ + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@/]+@[^@/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { + + /* + * there's a hostname. + * the first instance of /, ?, ;, or # ends the host. + * + * If there is an @ in the hostname, then non-host chars *are* allowed + * to the left of the last @ sign, unless some host-ending character + * comes *before* the @-sign. + * URLs are obnoxious. + * + * ex: + * http://a@b@c/ => user:a@b host:c + * http://a@b?@c => user:a host:c path:/?@c + */ + + /* + * v0.12 TODO(isaacs): This is not quite how Chrome does things. + * Review our test case against browsers more comprehensively. + */ + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; } + } + + /* + * at this point, either we have an explicit point where the + * auth portion cannot go past, or the last @ char is the decider. + */ + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + /* + * atSign must be in auth portion. + * http://a@b/c@d => host:b auth:a path:/c@d + */ + atSign = rest.lastIndexOf('@', hostEnd); + } + + /* + * Now we have a portion which is definitely the auth. + * Pull that off. + */ + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; } + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) { hostEnd = rest.length; } + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + /* + * we've indicated that there is a hostname, + * so even if it's empty, it has to be present. + */ + this.hostname = this.hostname || ''; + + /* + * if hostname begins with [ and ends with ] + * assume that it's an IPv6 address. + */ + var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) { continue; } + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + /* + * we replace non-ASCII char with a temporary placeholder + * we need this to make sure size of hostname is not + * broken by replacing non-ASCII by nothing + */ + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + /* + * IDNA Support: Returns a punycoded representation of "domain". + * It only converts parts of the domain name that + * have non-ASCII characters, i.e. it doesn't matter if + * you call it with a domain that already is ASCII-only. + */ + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + /* + * strip [ and ] from the hostname + * the host field still retains them, though + */ + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + /* + * now rest is set to the post-host stuff. + * chop off any delim chars. + */ + if (!unsafeProtocol[lowerProto]) { + + /* + * First, make 100% sure that any "autoEscape" chars get + * escaped, even if encodeURIComponent doesn't think they + * need to be. + */ + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) { continue; } + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) { this.pathname = rest; } + if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { + this.pathname = '/'; + } + + // to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + /* + * ensure it's an object, and not a string url. + * If it's an obj, this is a no-op. + * this way, you can call url_format() on strings + * to clean up potentially wonky urls. + */ + if (typeof obj === 'string') { obj = urlParse(obj); } + if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); } + return obj.format(); +} + +Url.prototype.format = function () { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && typeof this.query === 'object' && Object.keys(this.query).length) { + query = querystring.stringify(this.query, { + arrayFormat: 'repeat', + addQueryPrefix: false + }); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; } + + /* + * only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + * unless they had them to begin with. + */ + if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; } + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; } + if (search && search.charAt(0) !== '?') { search = '?' + search; } + + pathname = pathname.replace(/[?#]/g, function (match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function (relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) { return relative; } + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function (relative) { + if (typeof relative === 'string') { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + /* + * hash is always overridden, no matter what. + * even href="" will remove it. + */ + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') { result[rkey] = relative[rkey]; } + } + + // urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { + result.pathname = '/'; + result.path = result.pathname; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + /* + * if it's a known url protocol, then changing + * the protocol does weird things + * first, if it's not file:, then we MUST have a host, + * and if there was a path + * to begin with, then we MUST have a path. + * if it is file:, then the host is dropped, + * because that's known to be hostless. + * anything else is assumed to be absolute. + */ + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())) { } + if (!relative.host) { relative.host = ''; } + if (!relative.hostname) { relative.hostname = ''; } + if (relPath[0] !== '') { relPath.unshift(''); } + if (relPath.length < 2) { relPath.unshift(''); } + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = result.pathname && result.pathname.charAt(0) === '/', + isRelAbs = relative.host || relative.pathname && relative.pathname.charAt(0) === '/', + mustEndAbs = isRelAbs || isSourceAbs || (result.host && relative.pathname), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + /* + * if the url is a non-slashed url, then relative + * links like ../.. should be able + * to crawl up to the hostname, as well. This is strange. + * result.protocol has already been set by now. + * Later on, put the first path part into the host field. + */ + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') { srcPath[0] = result.host; } else { srcPath.unshift(result.host); } + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') { relPath[0] = relative.host; } else { relPath.unshift(relative.host); } + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = relative.host || relative.host === '' ? relative.host : result.host; + result.hostname = relative.hostname || relative.hostname === '' ? relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + /* + * it's relative + * throw away the existing file, and take the new path instead. + */ + if (!srcPath) { srcPath = []; } + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (relative.search != null) { + /* + * just pull out the search. + * like href='?foo'. + * Put this after the other two cases because it simplifies the booleans + */ + if (psychotic) { + result.host = srcPath.shift(); + result.hostname = result.host; + /* + * occationaly the auth can get stuck only in host + * this especially happens in cases like + * url.resolveObject('mailto:local1@domain1', 'local2@domain2') + */ + var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.hostname = authInHost.shift(); + result.host = result.hostname; + } + } + result.search = relative.search; + result.query = relative.query; + // to support http.request + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + /* + * no path at all. easy. + * we've already handled the other stuff above. + */ + result.pathname = null; + // to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + /* + * if a url ENDs in . or .., then it must get a trailing slash. + * however, if it ends in anything else non-slashy, + * then it must NOT get a trailing slash. + */ + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''; + + /* + * strip single dots, resolve double dots to parent dir + * if the path tries to go above the root, `up` ends up > 0 + */ + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; + result.host = result.hostname; + /* + * occationaly the auth can get stuck only in host + * this especially happens in cases like + * url.resolveObject('mailto:local1@domain1', 'local2@domain2') + */ + var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.hostname = authInHost.shift(); + result.host = result.hostname; + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (srcPath.length > 0) { + result.pathname = srcPath.join('/'); + } else { + result.pathname = null; + result.path = null; + } + + // to support request.http + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function () { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) { this.hostname = host; } +}; + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + + +/***/ }), + +/***/ 4643: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + +/** + * 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 (!__webpack_require__.g.localStorage) return false; + } catch (_) { + return false; + } + var val = __webpack_require__.g.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} + + +/***/ }), + +/***/ 1135: +/***/ ((module) => { + +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} + +/***/ }), + +/***/ 9032: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Currently in sync with Node.js lib/internal/util/types.js +// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 + + + +var isArgumentsObject = __webpack_require__(7244); +var isGeneratorFunction = __webpack_require__(8184); +var whichTypedArray = __webpack_require__(5767); +var isTypedArray = __webpack_require__(5680); + +function uncurryThis(f) { + return f.call.bind(f); +} + +var BigIntSupported = typeof BigInt !== 'undefined'; +var SymbolSupported = typeof Symbol !== 'undefined'; + +var ObjectToString = uncurryThis(Object.prototype.toString); + +var numberValue = uncurryThis(Number.prototype.valueOf); +var stringValue = uncurryThis(String.prototype.valueOf); +var booleanValue = uncurryThis(Boolean.prototype.valueOf); + +if (BigIntSupported) { + var bigIntValue = uncurryThis(BigInt.prototype.valueOf); +} + +if (SymbolSupported) { + var symbolValue = uncurryThis(Symbol.prototype.valueOf); +} + +function checkBoxedPrimitive(value, prototypeValueOf) { + if (typeof value !== 'object') { + return false; + } + try { + prototypeValueOf(value); + return true; + } catch(e) { + return false; + } +} + +exports.isArgumentsObject = isArgumentsObject; +exports.isGeneratorFunction = isGeneratorFunction; +exports.isTypedArray = isTypedArray; + +// Taken from here and modified for better browser support +// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js +function isPromise(input) { + return ( + ( + typeof Promise !== 'undefined' && + input instanceof Promise + ) || + ( + input !== null && + typeof input === 'object' && + typeof input.then === 'function' && + typeof input.catch === 'function' + ) + ); +} +exports.isPromise = isPromise; + +function isArrayBufferView(value) { + if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { + return ArrayBuffer.isView(value); + } + + return ( + isTypedArray(value) || + isDataView(value) + ); +} +exports.isArrayBufferView = isArrayBufferView; + + +function isUint8Array(value) { + return whichTypedArray(value) === 'Uint8Array'; +} +exports.isUint8Array = isUint8Array; + +function isUint8ClampedArray(value) { + return whichTypedArray(value) === 'Uint8ClampedArray'; +} +exports.isUint8ClampedArray = isUint8ClampedArray; + +function isUint16Array(value) { + return whichTypedArray(value) === 'Uint16Array'; +} +exports.isUint16Array = isUint16Array; + +function isUint32Array(value) { + return whichTypedArray(value) === 'Uint32Array'; +} +exports.isUint32Array = isUint32Array; + +function isInt8Array(value) { + return whichTypedArray(value) === 'Int8Array'; +} +exports.isInt8Array = isInt8Array; + +function isInt16Array(value) { + return whichTypedArray(value) === 'Int16Array'; +} +exports.isInt16Array = isInt16Array; + +function isInt32Array(value) { + return whichTypedArray(value) === 'Int32Array'; +} +exports.isInt32Array = isInt32Array; + +function isFloat32Array(value) { + return whichTypedArray(value) === 'Float32Array'; +} +exports.isFloat32Array = isFloat32Array; + +function isFloat64Array(value) { + return whichTypedArray(value) === 'Float64Array'; +} +exports.isFloat64Array = isFloat64Array; + +function isBigInt64Array(value) { + return whichTypedArray(value) === 'BigInt64Array'; +} +exports.isBigInt64Array = isBigInt64Array; + +function isBigUint64Array(value) { + return whichTypedArray(value) === 'BigUint64Array'; +} +exports.isBigUint64Array = isBigUint64Array; + +function isMapToString(value) { + return ObjectToString(value) === '[object Map]'; +} +isMapToString.working = ( + typeof Map !== 'undefined' && + isMapToString(new Map()) +); + +function isMap(value) { + if (typeof Map === 'undefined') { + return false; + } + + return isMapToString.working + ? isMapToString(value) + : value instanceof Map; +} +exports.isMap = isMap; + +function isSetToString(value) { + return ObjectToString(value) === '[object Set]'; +} +isSetToString.working = ( + typeof Set !== 'undefined' && + isSetToString(new Set()) +); +function isSet(value) { + if (typeof Set === 'undefined') { + return false; + } + + return isSetToString.working + ? isSetToString(value) + : value instanceof Set; +} +exports.isSet = isSet; + +function isWeakMapToString(value) { + return ObjectToString(value) === '[object WeakMap]'; +} +isWeakMapToString.working = ( + typeof WeakMap !== 'undefined' && + isWeakMapToString(new WeakMap()) +); +function isWeakMap(value) { + if (typeof WeakMap === 'undefined') { + return false; + } + + return isWeakMapToString.working + ? isWeakMapToString(value) + : value instanceof WeakMap; +} +exports.isWeakMap = isWeakMap; + +function isWeakSetToString(value) { + return ObjectToString(value) === '[object WeakSet]'; +} +isWeakSetToString.working = ( + typeof WeakSet !== 'undefined' && + isWeakSetToString(new WeakSet()) +); +function isWeakSet(value) { + return isWeakSetToString(value); +} +exports.isWeakSet = isWeakSet; + +function isArrayBufferToString(value) { + return ObjectToString(value) === '[object ArrayBuffer]'; +} +isArrayBufferToString.working = ( + typeof ArrayBuffer !== 'undefined' && + isArrayBufferToString(new ArrayBuffer()) +); +function isArrayBuffer(value) { + if (typeof ArrayBuffer === 'undefined') { + return false; + } + + return isArrayBufferToString.working + ? isArrayBufferToString(value) + : value instanceof ArrayBuffer; +} +exports.isArrayBuffer = isArrayBuffer; + +function isDataViewToString(value) { + return ObjectToString(value) === '[object DataView]'; +} +isDataViewToString.working = ( + typeof ArrayBuffer !== 'undefined' && + typeof DataView !== 'undefined' && + isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) +); +function isDataView(value) { + if (typeof DataView === 'undefined') { + return false; + } + + return isDataViewToString.working + ? isDataViewToString(value) + : value instanceof DataView; +} +exports.isDataView = isDataView; + +// Store a copy of SharedArrayBuffer in case it's deleted elsewhere +var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; +function isSharedArrayBufferToString(value) { + return ObjectToString(value) === '[object SharedArrayBuffer]'; +} +function isSharedArrayBuffer(value) { + if (typeof SharedArrayBufferCopy === 'undefined') { + return false; + } + + if (typeof isSharedArrayBufferToString.working === 'undefined') { + isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); + } + + return isSharedArrayBufferToString.working + ? isSharedArrayBufferToString(value) + : value instanceof SharedArrayBufferCopy; +} +exports.isSharedArrayBuffer = isSharedArrayBuffer; + +function isAsyncFunction(value) { + return ObjectToString(value) === '[object AsyncFunction]'; +} +exports.isAsyncFunction = isAsyncFunction; + +function isMapIterator(value) { + return ObjectToString(value) === '[object Map Iterator]'; +} +exports.isMapIterator = isMapIterator; + +function isSetIterator(value) { + return ObjectToString(value) === '[object Set Iterator]'; +} +exports.isSetIterator = isSetIterator; + +function isGeneratorObject(value) { + return ObjectToString(value) === '[object Generator]'; +} +exports.isGeneratorObject = isGeneratorObject; + +function isWebAssemblyCompiledModule(value) { + return ObjectToString(value) === '[object WebAssembly.Module]'; +} +exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; + +function isNumberObject(value) { + return checkBoxedPrimitive(value, numberValue); +} +exports.isNumberObject = isNumberObject; + +function isStringObject(value) { + return checkBoxedPrimitive(value, stringValue); +} +exports.isStringObject = isStringObject; + +function isBooleanObject(value) { + return checkBoxedPrimitive(value, booleanValue); +} +exports.isBooleanObject = isBooleanObject; + +function isBigIntObject(value) { + return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); +} +exports.isBigIntObject = isBigIntObject; + +function isSymbolObject(value) { + return SymbolSupported && checkBoxedPrimitive(value, symbolValue); +} +exports.isSymbolObject = isSymbolObject; + +function isBoxedPrimitive(value) { + return ( + isNumberObject(value) || + isStringObject(value) || + isBooleanObject(value) || + isBigIntObject(value) || + isSymbolObject(value) + ); +} +exports.isBoxedPrimitive = isBoxedPrimitive; + +function isAnyArrayBuffer(value) { + return typeof Uint8Array !== 'undefined' && ( + isArrayBuffer(value) || + isSharedArrayBuffer(value) + ); +} +exports.isAnyArrayBuffer = isAnyArrayBuffer; + +['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { + Object.defineProperty(exports, method, { + enumerable: false, + value: function() { + throw new Error(method + ' is not supported in userland'); + } + }); +}); + + +/***/ }), + +/***/ 537: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +// 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. + +var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || + function getOwnPropertyDescriptors(obj) { + var keys = Object.keys(obj); + var descriptors = {}; + for (var i = 0; i < keys.length; i++) { + descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); + } + return descriptors; + }; + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + if (typeof process !== 'undefined' && process.noDeprecation === true) { + return fn; + } + + // Allow for deprecating things in the process of starting up. + if (typeof process === 'undefined') { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnvRegex = /^$/; + +if (process.env.NODE_DEBUG) { + var debugEnv = process.env.NODE_DEBUG; + debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/,/g, '$|^') + .toUpperCase(); + debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); +} +exports.debuglog = function(set) { + set = set.toUpperCase(); + if (!debugs[set]) { + if (debugEnvRegex.test(set)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').slice(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.slice(1, -1); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +exports.types = __webpack_require__(9032); + +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; +exports.types.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; +exports.types.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; +exports.types.isNativeError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = __webpack_require__(1135); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = __webpack_require__(6698); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; + +exports.promisify = function promisify(original) { + if (typeof original !== 'function') + throw new TypeError('The "original" argument must be of type Function'); + + if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { + var fn = original[kCustomPromisifiedSymbol]; + if (typeof fn !== 'function') { + throw new TypeError('The "util.promisify.custom" argument must be of type Function'); + } + Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return fn; + } + + function fn() { + var promiseResolve, promiseReject; + var promise = new Promise(function (resolve, reject) { + promiseResolve = resolve; + promiseReject = reject; + }); + + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + args.push(function (err, value) { + if (err) { + promiseReject(err); + } else { + promiseResolve(value); + } + }); + + try { + original.apply(this, args); + } catch (err) { + promiseReject(err); + } + + return promise; + } + + Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); + + if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return Object.defineProperties( + fn, + getOwnPropertyDescriptors(original) + ); +} + +exports.promisify.custom = kCustomPromisifiedSymbol + +function callbackifyOnRejected(reason, cb) { + // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). + // Because `null` is a special error value in callbacks which means "no error + // occurred", we error-wrap so the callback consumer can distinguish between + // "the promise rejected with null" or "the promise fulfilled with undefined". + if (!reason) { + var newReason = new Error('Promise was rejected with a falsy value'); + newReason.reason = reason; + reason = newReason; + } + return cb(reason); +} + +function callbackify(original) { + if (typeof original !== 'function') { + throw new TypeError('The "original" argument must be of type Function'); + } + + // We DO NOT return the promise as it gives the user a false sense that + // the promise is actually somehow related to the callback's execution + // and that the callback throwing will reject the promise. + function callbackified() { + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + + var maybeCb = args.pop(); + if (typeof maybeCb !== 'function') { + throw new TypeError('The last argument must be of type Function'); + } + var self = this; + var cb = function() { + return maybeCb.apply(self, arguments); + }; + // In true node style we process the callback on `nextTick` with all the + // implications (stack, `uncaughtException`, `async_hooks`) + original.apply(this, args) + .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, + function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); + } + + Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); + Object.defineProperties(callbackified, + getOwnPropertyDescriptors(original)); + return callbackified; +} +exports.callbackify = callbackify; + + +/***/ }), + +/***/ 5767: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var forEach = __webpack_require__(2682); +var availableTypedArrays = __webpack_require__(9209); +var callBind = __webpack_require__(487); +var callBound = __webpack_require__(8075); +var gOPD = __webpack_require__(5795); + +/** @type {(O: object) => string} */ +var $toString = callBound('Object.prototype.toString'); +var hasToStringTag = __webpack_require__(9092)(); + +var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; +var typedArrays = availableTypedArrays(); + +var $slice = callBound('String.prototype.slice'); +var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); + +/** @type {(array: readonly T[], value: unknown) => number} */ +var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { + for (var i = 0; i < array.length; i += 1) { + if (array[i] === value) { + return i; + } + } + return -1; +}; + +/** @typedef {(receiver: import('.').TypedArray) => string | typeof Uint8Array.prototype.slice.call | typeof Uint8Array.prototype.set.call} Getter */ +/** @type {{ [k in `\$${import('.').TypedArrayName}`]?: Getter } & { __proto__: null }} */ +var cache = { __proto__: null }; +if (hasToStringTag && gOPD && getPrototypeOf) { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + if (Symbol.toStringTag in arr) { + var proto = getPrototypeOf(arr); + // @ts-expect-error TS won't narrow inside a closure + var descriptor = gOPD(proto, Symbol.toStringTag); + if (!descriptor) { + var superProto = getPrototypeOf(proto); + // @ts-expect-error TS won't narrow inside a closure + descriptor = gOPD(superProto, Symbol.toStringTag); + } + // @ts-expect-error TODO: fix + cache['$' + typedArray] = callBind(descriptor.get); + } + }); +} else { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + var fn = arr.slice || arr.set; + if (fn) { + // @ts-expect-error TODO: fix + cache['$' + typedArray] = callBind(fn); + } + }); +} + +/** @type {(value: object) => false | import('.').TypedArrayName} */ +var tryTypedArrays = function tryAllTypedArrays(value) { + /** @type {ReturnType} */ var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), + /** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */ + function (getter, typedArray) { + if (!found) { + try { + // @ts-expect-error TODO: fix + if ('$' + getter(value) === typedArray) { + found = $slice(typedArray, 1); + } + } catch (e) { /**/ } + } + } + ); + return found; +}; + +/** @type {(value: object) => false | import('.').TypedArrayName} */ +var trySlices = function tryAllSlices(value) { + /** @type {ReturnType} */ var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), + /** @type {(getter: typeof cache, name: `\$${import('.').TypedArrayName}`) => void} */ function (getter, name) { + if (!found) { + try { + // @ts-expect-error TODO: fix + getter(value); + found = $slice(name, 1); + } catch (e) { /**/ } + } + } + ); + return found; +}; + +/** @type {import('.')} */ +module.exports = function whichTypedArray(value) { + if (!value || typeof value !== 'object') { return false; } + if (!hasToStringTag) { + /** @type {string} */ + var tag = $slice($toString(value), 8, -1); + if ($indexOf(typedArrays, tag) > -1) { + return tag; + } + if (tag !== 'Object') { + return false; + } + // node < 0.6 hits here on real Typed Arrays + return trySlices(value); + } + if (!gOPD) { return null; } // unknown engine + return tryTypedArrays(value); +}; + + +/***/ }), + +/***/ 7510: +/***/ ((module) => { + +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} + + +/***/ }), + +/***/ 2894: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 2634: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 5340: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 9838: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 9209: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var possibleNames = __webpack_require__(6578); + +var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; + +/** @type {import('.')} */ +module.exports = function availableTypedArrays() { + var /** @type {ReturnType} */ out = []; + for (var i = 0; i < possibleNames.length; i++) { + if (typeof g[possibleNames[i]] === 'function') { + // @ts-expect-error + out[out.length] = possibleNames[i]; + } + } + return out; +}; + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat get default export */ +/******/ (() => { +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = (module) => { +/******/ var getter = module && module.__esModule ? +/******/ () => (module['default']) : +/******/ () => (module); +/******/ __webpack_require__.d(getter, { a: getter }); +/******/ return getter; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/global */ +/******/ (() => { +/******/ __webpack_require__.g = (function() { +/******/ if (typeof globalThis === 'object') return globalThis; +/******/ try { +/******/ return this || new Function('return this')(); +/******/ } catch (e) { +/******/ if (typeof window === 'object') return window; +/******/ } +/******/ })(); +/******/ })(); +/******/ +/******/ /* webpack/runtime/harmony module decorator */ +/******/ (() => { +/******/ __webpack_require__.hmd = (module) => { +/******/ module = Object.create(module); +/******/ if (!module.children) module.children = []; +/******/ Object.defineProperty(module, 'exports', { +/******/ enumerable: true, +/******/ set: () => { +/******/ throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id); +/******/ } +/******/ }); +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __webpack_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/node module decorator */ +/******/ (() => { +/******/ __webpack_require__.nmd = (module) => { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/************************************************************************/ +/******/ +/******/ // startup +/******/ // Load entry module and return exports +/******/ // This entry module is referenced by other modules so it can't be inlined +/******/ var __webpack_exports__ = __webpack_require__(1924); +/******/ +/******/ return __webpack_exports__; +/******/ })() +; +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-axios.min.js b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-axios.min.js new file mode 100644 index 000000000..e91aa36c6 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-axios.min.js @@ -0,0 +1,2 @@ +/*! For license information please see stellar-sdk-no-axios.min.js.LICENSE.txt */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("StellarSdk",[],t):"object"==typeof exports?exports.StellarSdk=t():e.StellarSdk=t()}(self,(()=>(()=>{var e={3740:function(e){var t;t=()=>(()=>{var e={616:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(287);n.hp.alloc(1).subarray(0,1)instanceof n.hp||(n.hp.prototype.subarray=function(e,t){const r=Uint8Array.prototype.subarray.call(this,e,t);return Object.setPrototypeOf(r,n.hp.prototype),r});const o=n.hp},281:(e,t,r)=>{const n=r(164);e.exports=n},164:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Array:()=>F,Bool:()=>C,Double:()=>j,Enum:()=>H,Float:()=>R,Hyper:()=>O,Int:()=>_,LargeInt:()=>T,Opaque:()=>U,Option:()=>q,Quadruple:()=>I,Reference:()=>z,String:()=>B,Struct:()=>X,Union:()=>W,UnsignedHyper:()=>P,UnsignedInt:()=>A,VarArray:()=>V,VarOpaque:()=>D,Void:()=>K,XdrReader:()=>u,XdrWriter:()=>f,config:()=>ne});class n extends TypeError{constructor(e){super(`XDR Write Error: ${e}`)}}class o extends TypeError{constructor(e){super(`XDR Read Error: ${e}`)}}class i extends TypeError{constructor(e){super(`XDR Type Definition Error: ${e}`)}}class a extends i{constructor(){super("method not implemented, it should be overloaded in the descendant class.")}}var s=r(616).A;class u{constructor(e){if(!s.isBuffer(e)){if(!(e instanceof Array||Array.isArray(e)||ArrayBuffer.isView(e)))throw new o(`source invalid: ${e}`);e=s.from(e)}this._buffer=e,this._length=e.length,this._index=0}_buffer;_length;_index;get eof(){return this._index===this._length}advance(e){const t=this._index;if(this._index+=e,this._length0){for(let e=0;e0){const e=this.alloc(r);this._buffer.fill(0,e,this._index)}}writeInt32BE(e){const t=this.alloc(4);this._buffer.writeInt32BE(e,t)}writeUInt32BE(e){const t=this.alloc(4);this._buffer.writeUInt32BE(e,t)}writeBigInt64BE(e){const t=this.alloc(8);this._buffer.writeBigInt64BE(e,t)}writeBigUInt64BE(e){const t=this.alloc(8);this._buffer.writeBigUInt64BE(e,t)}writeFloatBE(e){const t=this.alloc(4);this._buffer.writeFloatBE(e,t)}writeDoubleBE(e){const t=this.alloc(8);this._buffer.writeDoubleBE(e,t)}static bufferChunkSize=l}var p=r(616).A;class d{toXDR(e="raw"){if(!this.write)return this.constructor.toXDR(this,e);const t=new f;return this.write(this,t),v(t.finalize(),e)}fromXDR(e,t="raw"){if(!this.read)return this.constructor.fromXDR(e,t);const r=new u(g(e,t)),n=this.read(r);return r.ensureInputConsumed(),n}validateXDR(e,t="raw"){try{return this.fromXDR(e,t),!0}catch(e){return!1}}static toXDR(e,t="raw"){const r=new f;return this.write(e,r),v(r.finalize(),t)}static fromXDR(e,t="raw"){const r=new u(g(e,t)),n=this.read(r);return r.ensureInputConsumed(),n}static validateXDR(e,t="raw"){try{return this.fromXDR(e,t),!0}catch(e){return!1}}}class h extends d{static read(e){throw new a}static write(e,t){throw new a}static isValid(e){return!1}}class y extends d{isValid(e){return!1}}class m extends TypeError{constructor(e){super(`Invalid format ${e}, must be one of "raw", "hex", "base64"`)}}function v(e,t){switch(t){case"raw":return e;case"hex":return e.toString("hex");case"base64":return e.toString("base64");default:throw new m(t)}}function g(e,t){switch(t){case"raw":return e;case"hex":return p.from(e,"hex");case"base64":return p.from(e,"base64");default:throw new m(t)}}function b(e,t){return null!=e&&(e instanceof t||w(e,t)&&"function"==typeof e.constructor.read&&"function"==typeof e.constructor.write&&w(e,"XdrType"))}function w(e,t){do{if(e.constructor.name===t)return!0}while(e=Object.getPrototypeOf(e));return!1}const S=2147483647;class _ extends h{static read(e){return e.readInt32BE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");if((0|e)!==e)throw new n("invalid i32 value");t.writeInt32BE(e)}static isValid(e){return"number"==typeof e&&(0|e)===e&&e>=-2147483648&&e<=S}}function E(e,t,r){if("bigint"!=typeof e)throw new TypeError("Expected bigint 'value', got "+typeof e);const n=t/r;if(1===n)return[e];if(r<32||r>128||2!==n&&4!==n&&8!==n)throw new TypeError(`invalid bigint (${e}) and slice size (${t} -> ${r}) combination`);const o=BigInt(r),i=new Array(n);for(let t=0;t>=o;return i}function k(e,t){if(t)return[0n,(1n<=i&&o<=a)return o;throw new TypeError(`bigint values [${e}] for ${function(e,t){return`${t?"u":"i"}${e}`}(t,r)} out of range [${i}, ${a}]: ${o}`)}(e,this.size,this.unsigned)}get unsigned(){throw new a}get size(){throw new a}slice(e){return E(this._value,this.size,e)}toString(){return this._value.toString()}toJSON(){return{_value:this._value.toString()}}toBigInt(){return BigInt(this._value)}static read(e){const{size:t}=this.prototype;return 64===t?new this(e.readBigUInt64BE()):new this(...Array.from({length:t/64},(()=>e.readBigUInt64BE())).reverse())}static write(e,t){if(e instanceof this)e=e._value;else if("bigint"!=typeof e||e>this.MAX_VALUE||e>32n)}get size(){return 64}get unsigned(){return!1}static fromBits(e,t){return new this(e,t)}}O.defineIntBoundaries();const x=4294967295;class A extends h{static read(e){return e.readUInt32BE()}static write(e,t){if("number"!=typeof e||!(e>=0&&e<=x)||e%1!=0)throw new n("invalid u32 value");t.writeUInt32BE(e)}static isValid(e){return"number"==typeof e&&e%1==0&&e>=0&&e<=x}}A.MAX_VALUE=x,A.MIN_VALUE=0;class P extends T{constructor(...e){super(e)}get low(){return 0|Number(0xffffffffn&this._value)}get high(){return 0|Number(this._value>>32n)}get size(){return 64}get unsigned(){return!0}static fromBits(e,t){return new this(e,t)}}P.defineIntBoundaries();class R extends h{static read(e){return e.readFloatBE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");t.writeFloatBE(e)}static isValid(e){return"number"==typeof e}}class j extends h{static read(e){return e.readDoubleBE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");t.writeDoubleBE(e)}static isValid(e){return"number"==typeof e}}class I extends h{static read(){throw new i("quadruple not supported")}static write(){throw new i("quadruple not supported")}static isValid(){return!1}}class C extends h{static read(e){const t=_.read(e);switch(t){case 0:return!1;case 1:return!0;default:throw new o(`got ${t} when trying to read a bool`)}}static write(e,t){const r=e?1:0;_.write(r,t)}static isValid(e){return"boolean"==typeof e}}var L=r(616).A;class B extends y{constructor(e=A.MAX_VALUE){super(),this._maxLength=e}read(e){const t=A.read(e);if(t>this._maxLength)throw new o(`saw ${t} length String, max allowed is ${this._maxLength}`);return e.read(t)}readString(e){return this.read(e).toString("utf8")}write(e,t){const r="string"==typeof e?L.byteLength(e,"utf8"):e.length;if(r>this._maxLength)throw new n(`got ${e.length} bytes, max allowed is ${this._maxLength}`);A.write(r,t),t.write(e,r)}isValid(e){return"string"==typeof e?L.byteLength(e,"utf8")<=this._maxLength:!!(e instanceof Array||L.isBuffer(e))&&e.length<=this._maxLength}}var N=r(616).A;class U extends y{constructor(e){super(),this._length=e}read(e){return e.read(this._length)}write(e,t){const{length:r}=e;if(r!==this._length)throw new n(`got ${e.length} bytes, expected ${this._length}`);t.write(e,r)}isValid(e){return N.isBuffer(e)&&e.length===this._length}}var M=r(616).A;class D extends y{constructor(e=A.MAX_VALUE){super(),this._maxLength=e}read(e){const t=A.read(e);if(t>this._maxLength)throw new o(`saw ${t} length VarOpaque, max allowed is ${this._maxLength}`);return e.read(t)}write(e,t){const{length:r}=e;if(e.length>this._maxLength)throw new n(`got ${e.length} bytes, max allowed is ${this._maxLength}`);A.write(r,t),t.write(e,r)}isValid(e){return M.isBuffer(e)&&e.length<=this._maxLength}}class F extends y{constructor(e,t){super(),this._childType=e,this._length=t}read(e){const t=new r.g.Array(this._length);for(let r=0;rthis._maxLength)throw new o(`saw ${t} length VarArray, max allowed is ${this._maxLength}`);const r=new Array(t);for(let n=0;nthis._maxLength)throw new n(`got array of size ${e.length}, max allowed is ${this._maxLength}`);A.write(e.length,t);for(const r of e)this._childType.write(r,t)}isValid(e){if(!(e instanceof Array)||e.length>this._maxLength)return!1;for(const t of e)if(!this._childType.isValid(t))return!1;return!0}}class q extends h{constructor(e){super(),this._childType=e}read(e){if(C.read(e))return this._childType.read(e)}write(e,t){const r=null!=e;C.write(r,t),r&&this._childType.write(e,t)}isValid(e){return null==e||this._childType.isValid(e)}}class K extends h{static read(){}static write(e){if(void 0!==e)throw new n("trying to write value to a void slot")}static isValid(e){return void 0===e}}class H extends h{constructor(e,t){super(),this.name=e,this.value=t}static read(e){const t=_.read(e),r=this._byValue[t];if(void 0===r)throw new o(`unknown ${this.enumName} member for value ${t}`);return r}static write(e,t){if(!this.isValid(e))throw new n(`${e} has enum name ${e?.enumName}, not ${this.enumName}: ${JSON.stringify(e)}`);_.write(e.value,t)}static isValid(e){return e?.constructor?.enumName===this.enumName||b(e,this)}static members(){return this._members}static values(){return Object.values(this._members)}static fromName(e){const t=this._members[e];if(!t)throw new TypeError(`${e} is not a member of ${this.enumName}`);return t}static fromValue(e){const t=this._byValue[e];if(void 0===t)throw new TypeError(`${e} is not a value of any member of ${this.enumName}`);return t}static create(e,t,r){const n=class extends H{};n.enumName=t,e.results[t]=n,n._members={},n._byValue={};for(const[e,t]of Object.entries(r)){const r=new n(e,t);n._members[e]=r,n._byValue[t]=r,n[e]=()=>r}return n}}class z extends h{resolve(){throw new i('"resolve" method should be implemented in the descendant class')}}class X extends y{constructor(e){super(),this._attributes=e||{}}static read(e){const t={};for(const[r,n]of this._fields)t[r]=n.read(e);return new this(t)}static write(e,t){if(!this.isValid(e))throw new n(`${e} has struct name ${e?.constructor?.structName}, not ${this.structName}: ${JSON.stringify(e)}`);for(const[r,n]of this._fields){const o=e._attributes[r];n.write(o,t)}}static isValid(e){return e?.constructor?.structName===this.structName||b(e,this)}static create(e,t,r){const n=class extends X{};n.structName=t,e.results[t]=n;const o=new Array(r.length);for(let t=0;t{"use strict";t.byteLength=function(e){var t=s(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,i=s(e),a=i[0],u=i[1],c=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,u)),l=0,f=u>0?a-4:a;for(r=0;r>16&255,c[l++]=t>>8&255,c[l++]=255&t;return 2===u&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,c[l++]=255&t),1===u&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t),c},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],a=16383,s=0,c=n-o;sc?c:s+a));return 1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),i.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)r[a]=i[a],n[i.charCodeAt(a)]=a;function s(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,n){for(var o,i,a=[],s=t;s>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return a.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287:(e,t,r)=>{"use strict";const n=r(526),o=r(251),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=u,t.IS=50;const a=2147483647;function s(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,u.prototype),t}function u(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return f(e)}return c(e,t,r)}function c(e,t,r){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!u.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|y(e,t);let n=s(r);const o=n.write(e,t);return o!==r&&(n=n.slice(0,o)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if($(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return p(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if($(e,ArrayBuffer)||e&&$(e.buffer,ArrayBuffer))return d(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&($(e,SharedArrayBuffer)||e&&$(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return u.from(n,t,r);const o=function(e){if(u.isBuffer(e)){const t=0|h(e.length),r=s(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||Q(e.length)?s(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return u.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function f(e){return l(e),s(e<0?0:0|h(e))}function p(e){const t=e.length<0?0:0|h(e.length),r=s(t);for(let n=0;n=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function y(e,t){if(u.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||$(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return X(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(o)return n?-1:X(e).length;t=(""+t).toLowerCase(),o=!0}}function m(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return R(this,t,r);case"utf8":case"utf-8":return O(this,t,r);case"ascii":return A(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return T(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function v(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function g(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Q(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,o){let i,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){let n=-1;for(i=r;is&&(r=s-u),i=r;i>=0;i--){let r=!0;for(let n=0;no&&(n=o):n=o;const i=t.length;let a;for(n>i/2&&(n=i/2),a=0;a>8,o=r%256,i.push(o),i.push(n);return i}(t,e.length-r),e,r,n)}function T(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function O(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o239?4:t>223?3:t>191?2:1;if(o+a<=r){let r,n,s,u;switch(a){case 1:t<128&&(i=t);break;case 2:r=e[o+1],128==(192&r)&&(u=(31&t)<<6|63&r,u>127&&(i=u));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(u=(15&t)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:r=e[o+1],n=e[o+2],s=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(u=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,u>65535&&u<1114112&&(i=u))}}null===i?(i=65533,a=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),o+=a}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(u.isBuffer(t)||(t=u.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!u.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},u.byteLength=y,u.prototype._isBuffer=!0,u.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(e+=" ... "),""},i&&(u.prototype[i]=u.prototype.inspect),u.prototype.compare=function(e,t,r,n,o){if($(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let i=(o>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0);const s=Math.min(i,a),c=this.slice(n,o),l=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let i=!1;for(;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":case"latin1":case"binary":return _(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function A(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;on)&&(r=n);let o="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function C(e,t,r,n,o,i){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function L(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function B(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r+7]=i,i>>=8,e[r+6]=i,i>>=8,e[r+5]=i,i>>=8,e[r+4]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function N(e,t,r,n,o,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function M(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,8),o.write(e,t,r,n,52,8),r+8}u.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||I(e,t,this.length);let n=this[e],o=1,i=0;for(;++i>>=0,t>>>=0,r||I(e,t,this.length);let n=this[e+--t],o=1;for(;t>0&&(o*=256);)n+=this[e+--t]*o;return n},u.prototype.readUint8=u.prototype.readUInt8=function(e,t){return e>>>=0,t||I(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||I(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||I(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||I(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||I(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(o)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||I(e,t,this.length);let n=this[e],o=1,i=0;for(;++i=o&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||I(e,t,this.length);let n=t,o=1,i=this[e+--n];for(;n>0&&(o*=256);)i+=this[e+--n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},u.prototype.readInt8=function(e,t){return e>>>=0,t||I(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||I(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){e>>>=0,t||I(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||I(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||I(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||I(e,4,this.length),o.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||I(e,4,this.length),o.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||I(e,8,this.length),o.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||I(e,8,this.length),o.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||C(this,e,t,r,Math.pow(2,8*r)-1,0);let o=1,i=0;for(this[t]=255&e;++i>>=0,r>>>=0,n||C(this,e,t,r,Math.pow(2,8*r)-1,0);let o=r-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigUInt64LE=J((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeBigUInt64BE=J((function(e,t=0){return B(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);C(this,e,t,r,n-1,-n)}let o=0,i=1,a=0;for(this[t]=255&e;++o>>=0,!n){const n=Math.pow(2,8*r-1);C(this,e,t,r,n-1,-n)}let o=r-1,i=1,a=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/i|0)-a&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigInt64LE=J((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeBigInt64BE=J((function(e,t=0){return B(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return M(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return M(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function q(e,t,r,n,o,i){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new D.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){K(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||H(t,e.length-(r+1))}(n,o,i)}function K(e,t){if("number"!=typeof e)throw new D.ERR_INVALID_ARG_TYPE(t,"number",e)}function H(e,t,r){if(Math.floor(e)!==e)throw K(e,r),new D.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new D.ERR_BUFFER_OUT_OF_BOUNDS;throw new D.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}F("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),F("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),F("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=V(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=V(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const z=/[^+/0-9A-Za-z-_]/g;function X(e,t){let r;t=t||1/0;const n=e.length;let o=null;const i=[];for(let a=0;a55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function G(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function W(e,t,r,n){let o;for(o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function $(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Q(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let o=0;o<16;++o)t[n+o]=e[r]+e[o]}return t}();function J(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},251:(e,t)=>{t.read=function(e,t,r,n,o){var i,a,s=8*o-n-1,u=(1<>1,l=-7,f=r?o-1:0,p=r?-1:1,d=e[t+f];for(f+=p,i=d&(1<<-l)-1,d>>=-l,l+=s;l>0;i=256*i+e[t+f],f+=p,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=p,l-=8);if(0===i)i=1-c;else{if(i===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),i-=c}return(d?-1:1)*a*Math.pow(2,i-n)},t.write=function(e,t,r,n,o,i){var a,s,u,c=8*i-o-1,l=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,h=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?p/u:p*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=l?(s=0,a=l):a+f>=1?(s=(t*u-1)*Math.pow(2,o),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,o),a=0));o>=8;e[r+d]=255&s,d+=h,s/=256,o-=8);for(a=a<0;e[r+d]=255&a,d+=h,a/=256,c-=8);e[r+d-h]|=128*y}}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}return r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r(281)})(),e.exports=t()},2135:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Account=void 0;var n,o=(n=r(1242))&&n.__esModule?n:{default:n},i=r(7120);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function s(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Address=void 0;var n,o=r(7120),i=(n=r(1918))&&n.__esModule?n:{default:n};function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function s(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;var o,i=r(645),a=(o=r(1918))&&o.__esModule?o:{default:o},s=r(6691),u=r(7120),c=r(9152);function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:a.default.Asset;if(this.isNative())return r.assetTypeNative();this.code.length<=4?(e=a.default.AlphaNum4,t="assetTypeCreditAlphanum4"):(e=a.default.AlphaNum12,t="assetTypeCreditAlphanum12");var n=this.code.length<=4?4:12;return new r(t,new e({assetCode:this.code.padEnd(n,"\0"),issuer:s.Keypair.fromPublicKey(this.issuer).xdrAccountId()}))}},{key:"getCode",value:function(){if(void 0!==this.code)return String(this.code)}},{key:"getIssuer",value:function(){if(void 0!==this.issuer)return String(this.issuer)}},{key:"getAssetType",value:function(){switch(this.getRawAssetType().value){case a.default.AssetType.assetTypeNative().value:return"native";case a.default.AssetType.assetTypeCreditAlphanum4().value:return"credit_alphanum4";case a.default.AssetType.assetTypeCreditAlphanum12().value:return"credit_alphanum12";default:return"unknown"}}},{key:"getRawAssetType",value:function(){return this.isNative()?a.default.AssetType.assetTypeNative():this.code.length<=4?a.default.AssetType.assetTypeCreditAlphanum4():a.default.AssetType.assetTypeCreditAlphanum12()}},{key:"isNative",value:function(){return!this.issuer}},{key:"equals",value:function(e){return this.code===e.getCode()&&this.issuer===e.getIssuer()}},{key:"toString",value:function(){return this.isNative()?"native":"".concat(this.getCode(),":").concat(this.getIssuer())}}],[{key:"native",value:function(){return new e("XLM")}},{key:"fromOperation",value:function(e){var t,r;switch(e.switch()){case a.default.AssetType.assetTypeNative():return this.native();case a.default.AssetType.assetTypeCreditAlphanum4():t=e.alphaNum4();case a.default.AssetType.assetTypeCreditAlphanum12():return t=t||e.alphaNum12(),r=u.StrKey.encodeEd25519PublicKey(t.issuer().ed25519()),new this((0,i.trimEnd)(t.assetCode(),"\0"),r);default:throw new Error("Invalid asset type: ".concat(e.switch().name))}}},{key:"compare",value:function(t,r){if(!(t&&t instanceof e))throw new Error("assetA is invalid");if(!(r&&r instanceof e))throw new Error("assetB is invalid");if(t.equals(r))return 0;var n=t.getRawAssetType().value,o=r.getRawAssetType().value;if(n!==o)return n{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.authorizeEntry=y,t.authorizeInvocation=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:u.Networks.FUTURENET,s=a.Keypair.random().rawPublicKey(),c=new i.default.Int64((p=s,p.subarray(0,8).reduce((function(e,t){return e<<8|t}),0))),f=n||e.publicKey();var p;if(!f)throw new Error("authorizeInvocation requires publicKey parameter");return y(new i.default.SorobanAuthorizationEntry({rootInvocation:r,credentials:i.default.SorobanCredentials.sorobanCredentialsAddress(new i.default.SorobanAddressCredentials({address:new l.Address(f).toScAddress(),nonce:c,signatureExpirationLedger:0,signature:i.default.ScVal.scvVec([])}))}),e,t,o)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(6691),s=r(7120),u=r(6202),c=r(9152),l=r(1180),f=r(7177);function p(e){return p="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},p(e)}function d(){d=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof b?t:b,a=Object.create(i.prototype),s=new I(n||[]);return o(a,"_invoke",{value:A(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var h="suspendedStart",y="suspendedYield",m="executing",v="completed",g={};function b(){}function w(){}function S(){}var _={};c(_,a,(function(){return this}));var E=Object.getPrototypeOf,k=E&&E(E(C([])));k&&k!==r&&n.call(k,a)&&(_=k);var T=S.prototype=b.prototype=Object.create(_);function O(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function x(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==p(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function A(t,r,n){var o=h;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=P(s,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=m;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?v:y,c.arg===g)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=v,n.method="throw",n.arg=c.arg)}}}function P(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,P(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function R(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function j(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function I(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(R,this),this.reset(!0)}function C(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),j(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:C(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function h(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function y(e,t,r){return m.apply(this,arguments)}function m(){var e;return e=d().mark((function e(t,r,o){var p,h,y,m,v,g,b,w,S,_=arguments;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(p=_.length>3&&void 0!==_[3]?_[3]:u.Networks.FUTURENET,t.credentials().switch().value===i.default.SorobanCredentialsType.sorobanCredentialsAddress().value){e.next=3;break}return e.abrupt("return",t);case 3:if(h=i.default.SorobanAuthorizationEntry.fromXDR(t.toXDR()),(y=h.credentials().address()).signatureExpirationLedger(o),m=(0,c.hash)(n.from(p)),v=i.default.HashIdPreimage.envelopeTypeSorobanAuthorization(new i.default.HashIdPreimageSorobanAuthorization({networkId:m,nonce:y.nonce(),invocation:h.rootInvocation(),signatureExpirationLedger:y.signatureExpirationLedger()})),g=(0,c.hash)(v.toXDR()),"function"!=typeof r){e.next=18;break}return e.t0=n,e.next=13,r(v);case 13:e.t1=e.sent,b=e.t0.from.call(e.t0,e.t1),w=l.Address.fromScAddress(y.address()).toString(),e.next=20;break;case 18:b=n.from(r.sign(g)),w=r.publicKey();case 20:if(a.Keypair.fromPublicKey(w).verify(g,b)){e.next=22;break}throw new Error("signature doesn't match payload");case 22:return S=(0,f.nativeToScVal)({public_key:s.StrKey.decodeEd25519PublicKey(w),signature:b},{type:{public_key:["symbol",null],signature:["symbol",null]}}),y.signature(i.default.ScVal.scvVec([S])),e.abrupt("return",h);case 25:case"end":return e.stop()}}),e)})),m=function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){h(i,n,o,a,s,"next",e)}function s(e){h(i,n,o,a,s,"throw",e)}a(void 0)}))},m.apply(this,arguments)}},1387:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Claimant=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691),a=r(7120);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Contract=void 0;var n,o=r(1180),i=r(7237),a=(n=r(1918))&&n.__esModule?n:{default:n},s=r(7120);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){for(var r=0;r1?t-1:0),n=1;n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.humanizeEvents=function(e){return e.map((function(e){return e.inSuccessfulContractCall?c(e.event()):c(e)}))};var n=r(7120),o=r(7177);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function s(e){for(var t=1;t{"use strict";var n=r(8287).Buffer;function o(e){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.FeeBumpTransaction=void 0;var i,a=(i=r(1918))&&i.__esModule?i:{default:i},s=r(9152),u=r(380),c=r(3758),l=r(6160);function f(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(o=function(e){return e?r:t})(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=n(e)&&"function"!=typeof e)return{default:e};var r=o(t);if(r&&r.has(e))return r.get(e);var i={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&{}.hasOwnProperty.call(e,s)){var u=a?Object.getOwnPropertyDescriptor(e,s):null;u&&(u.get||u.set)?Object.defineProperty(i,s,u):i[s]=e[s]}return i.default=e,r&&r.set(e,i),i}(r(3740)).config((function(e){var t=1024;e.typedef("Value",e.varOpaque()),e.struct("ScpBallot",[["counter",e.lookup("Uint32")],["value",e.lookup("Value")]]),e.enum("ScpStatementType",{scpStPrepare:0,scpStConfirm:1,scpStExternalize:2,scpStNominate:3}),e.struct("ScpNomination",[["quorumSetHash",e.lookup("Hash")],["votes",e.varArray(e.lookup("Value"),2147483647)],["accepted",e.varArray(e.lookup("Value"),2147483647)]]),e.struct("ScpStatementPrepare",[["quorumSetHash",e.lookup("Hash")],["ballot",e.lookup("ScpBallot")],["prepared",e.option(e.lookup("ScpBallot"))],["preparedPrime",e.option(e.lookup("ScpBallot"))],["nC",e.lookup("Uint32")],["nH",e.lookup("Uint32")]]),e.struct("ScpStatementConfirm",[["ballot",e.lookup("ScpBallot")],["nPrepared",e.lookup("Uint32")],["nCommit",e.lookup("Uint32")],["nH",e.lookup("Uint32")],["quorumSetHash",e.lookup("Hash")]]),e.struct("ScpStatementExternalize",[["commit",e.lookup("ScpBallot")],["nH",e.lookup("Uint32")],["commitQuorumSetHash",e.lookup("Hash")]]),e.union("ScpStatementPledges",{switchOn:e.lookup("ScpStatementType"),switchName:"type",switches:[["scpStPrepare","prepare"],["scpStConfirm","confirm"],["scpStExternalize","externalize"],["scpStNominate","nominate"]],arms:{prepare:e.lookup("ScpStatementPrepare"),confirm:e.lookup("ScpStatementConfirm"),externalize:e.lookup("ScpStatementExternalize"),nominate:e.lookup("ScpNomination")}}),e.struct("ScpStatement",[["nodeId",e.lookup("NodeId")],["slotIndex",e.lookup("Uint64")],["pledges",e.lookup("ScpStatementPledges")]]),e.struct("ScpEnvelope",[["statement",e.lookup("ScpStatement")],["signature",e.lookup("Signature")]]),e.struct("ScpQuorumSet",[["threshold",e.lookup("Uint32")],["validators",e.varArray(e.lookup("NodeId"),2147483647)],["innerSets",e.varArray(e.lookup("ScpQuorumSet"),2147483647)]]),e.typedef("Thresholds",e.opaque(4)),e.typedef("String32",e.string(32)),e.typedef("String64",e.string(64)),e.typedef("SequenceNumber",e.lookup("Int64")),e.typedef("DataValue",e.varOpaque(64)),e.typedef("PoolId",e.lookup("Hash")),e.typedef("AssetCode4",e.opaque(4)),e.typedef("AssetCode12",e.opaque(12)),e.enum("AssetType",{assetTypeNative:0,assetTypeCreditAlphanum4:1,assetTypeCreditAlphanum12:2,assetTypePoolShare:3}),e.union("AssetCode",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeCreditAlphanum4","assetCode4"],["assetTypeCreditAlphanum12","assetCode12"]],arms:{assetCode4:e.lookup("AssetCode4"),assetCode12:e.lookup("AssetCode12")}}),e.struct("AlphaNum4",[["assetCode",e.lookup("AssetCode4")],["issuer",e.lookup("AccountId")]]),e.struct("AlphaNum12",[["assetCode",e.lookup("AssetCode12")],["issuer",e.lookup("AccountId")]]),e.union("Asset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12")}}),e.struct("Price",[["n",e.lookup("Int32")],["d",e.lookup("Int32")]]),e.struct("Liabilities",[["buying",e.lookup("Int64")],["selling",e.lookup("Int64")]]),e.enum("ThresholdIndices",{thresholdMasterWeight:0,thresholdLow:1,thresholdMed:2,thresholdHigh:3}),e.enum("LedgerEntryType",{account:0,trustline:1,offer:2,data:3,claimableBalance:4,liquidityPool:5,contractData:6,contractCode:7,configSetting:8,ttl:9}),e.struct("Signer",[["key",e.lookup("SignerKey")],["weight",e.lookup("Uint32")]]),e.enum("AccountFlags",{authRequiredFlag:1,authRevocableFlag:2,authImmutableFlag:4,authClawbackEnabledFlag:8}),e.const("MASK_ACCOUNT_FLAGS",7),e.const("MASK_ACCOUNT_FLAGS_V17",15),e.const("MAX_SIGNERS",20),e.typedef("SponsorshipDescriptor",e.option(e.lookup("AccountId"))),e.struct("AccountEntryExtensionV3",[["ext",e.lookup("ExtensionPoint")],["seqLedger",e.lookup("Uint32")],["seqTime",e.lookup("TimePoint")]]),e.union("AccountEntryExtensionV2Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[3,"v3"]],arms:{v3:e.lookup("AccountEntryExtensionV3")}}),e.struct("AccountEntryExtensionV2",[["numSponsored",e.lookup("Uint32")],["numSponsoring",e.lookup("Uint32")],["signerSponsoringIDs",e.varArray(e.lookup("SponsorshipDescriptor"),e.lookup("MAX_SIGNERS"))],["ext",e.lookup("AccountEntryExtensionV2Ext")]]),e.union("AccountEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[2,"v2"]],arms:{v2:e.lookup("AccountEntryExtensionV2")}}),e.struct("AccountEntryExtensionV1",[["liabilities",e.lookup("Liabilities")],["ext",e.lookup("AccountEntryExtensionV1Ext")]]),e.union("AccountEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("AccountEntryExtensionV1")}}),e.struct("AccountEntry",[["accountId",e.lookup("AccountId")],["balance",e.lookup("Int64")],["seqNum",e.lookup("SequenceNumber")],["numSubEntries",e.lookup("Uint32")],["inflationDest",e.option(e.lookup("AccountId"))],["flags",e.lookup("Uint32")],["homeDomain",e.lookup("String32")],["thresholds",e.lookup("Thresholds")],["signers",e.varArray(e.lookup("Signer"),e.lookup("MAX_SIGNERS"))],["ext",e.lookup("AccountEntryExt")]]),e.enum("TrustLineFlags",{authorizedFlag:1,authorizedToMaintainLiabilitiesFlag:2,trustlineClawbackEnabledFlag:4}),e.const("MASK_TRUSTLINE_FLAGS",1),e.const("MASK_TRUSTLINE_FLAGS_V13",3),e.const("MASK_TRUSTLINE_FLAGS_V17",7),e.enum("LiquidityPoolType",{liquidityPoolConstantProduct:0}),e.union("TrustLineAsset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"],["assetTypePoolShare","liquidityPoolId"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12"),liquidityPoolId:e.lookup("PoolId")}}),e.union("TrustLineEntryExtensionV2Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TrustLineEntryExtensionV2",[["liquidityPoolUseCount",e.lookup("Int32")],["ext",e.lookup("TrustLineEntryExtensionV2Ext")]]),e.union("TrustLineEntryV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[2,"v2"]],arms:{v2:e.lookup("TrustLineEntryExtensionV2")}}),e.struct("TrustLineEntryV1",[["liabilities",e.lookup("Liabilities")],["ext",e.lookup("TrustLineEntryV1Ext")]]),e.union("TrustLineEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("TrustLineEntryV1")}}),e.struct("TrustLineEntry",[["accountId",e.lookup("AccountId")],["asset",e.lookup("TrustLineAsset")],["balance",e.lookup("Int64")],["limit",e.lookup("Int64")],["flags",e.lookup("Uint32")],["ext",e.lookup("TrustLineEntryExt")]]),e.enum("OfferEntryFlags",{passiveFlag:1}),e.const("MASK_OFFERENTRY_FLAGS",1),e.union("OfferEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("OfferEntry",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")],["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")],["flags",e.lookup("Uint32")],["ext",e.lookup("OfferEntryExt")]]),e.union("DataEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("DataEntry",[["accountId",e.lookup("AccountId")],["dataName",e.lookup("String64")],["dataValue",e.lookup("DataValue")],["ext",e.lookup("DataEntryExt")]]),e.enum("ClaimPredicateType",{claimPredicateUnconditional:0,claimPredicateAnd:1,claimPredicateOr:2,claimPredicateNot:3,claimPredicateBeforeAbsoluteTime:4,claimPredicateBeforeRelativeTime:5}),e.union("ClaimPredicate",{switchOn:e.lookup("ClaimPredicateType"),switchName:"type",switches:[["claimPredicateUnconditional",e.void()],["claimPredicateAnd","andPredicates"],["claimPredicateOr","orPredicates"],["claimPredicateNot","notPredicate"],["claimPredicateBeforeAbsoluteTime","absBefore"],["claimPredicateBeforeRelativeTime","relBefore"]],arms:{andPredicates:e.varArray(e.lookup("ClaimPredicate"),2),orPredicates:e.varArray(e.lookup("ClaimPredicate"),2),notPredicate:e.option(e.lookup("ClaimPredicate")),absBefore:e.lookup("Int64"),relBefore:e.lookup("Int64")}}),e.enum("ClaimantType",{claimantTypeV0:0}),e.struct("ClaimantV0",[["destination",e.lookup("AccountId")],["predicate",e.lookup("ClaimPredicate")]]),e.union("Claimant",{switchOn:e.lookup("ClaimantType"),switchName:"type",switches:[["claimantTypeV0","v0"]],arms:{v0:e.lookup("ClaimantV0")}}),e.enum("ClaimableBalanceIdType",{claimableBalanceIdTypeV0:0}),e.union("ClaimableBalanceId",{switchOn:e.lookup("ClaimableBalanceIdType"),switchName:"type",switches:[["claimableBalanceIdTypeV0","v0"]],arms:{v0:e.lookup("Hash")}}),e.enum("ClaimableBalanceFlags",{claimableBalanceClawbackEnabledFlag:1}),e.const("MASK_CLAIMABLE_BALANCE_FLAGS",1),e.union("ClaimableBalanceEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("ClaimableBalanceEntryExtensionV1",[["ext",e.lookup("ClaimableBalanceEntryExtensionV1Ext")],["flags",e.lookup("Uint32")]]),e.union("ClaimableBalanceEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("ClaimableBalanceEntryExtensionV1")}}),e.struct("ClaimableBalanceEntry",[["balanceId",e.lookup("ClaimableBalanceId")],["claimants",e.varArray(e.lookup("Claimant"),10)],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")],["ext",e.lookup("ClaimableBalanceEntryExt")]]),e.struct("LiquidityPoolConstantProductParameters",[["assetA",e.lookup("Asset")],["assetB",e.lookup("Asset")],["fee",e.lookup("Int32")]]),e.struct("LiquidityPoolEntryConstantProduct",[["params",e.lookup("LiquidityPoolConstantProductParameters")],["reserveA",e.lookup("Int64")],["reserveB",e.lookup("Int64")],["totalPoolShares",e.lookup("Int64")],["poolSharesTrustLineCount",e.lookup("Int64")]]),e.union("LiquidityPoolEntryBody",{switchOn:e.lookup("LiquidityPoolType"),switchName:"type",switches:[["liquidityPoolConstantProduct","constantProduct"]],arms:{constantProduct:e.lookup("LiquidityPoolEntryConstantProduct")}}),e.struct("LiquidityPoolEntry",[["liquidityPoolId",e.lookup("PoolId")],["body",e.lookup("LiquidityPoolEntryBody")]]),e.enum("ContractDataDurability",{temporary:0,persistent:1}),e.struct("ContractDataEntry",[["ext",e.lookup("ExtensionPoint")],["contract",e.lookup("ScAddress")],["key",e.lookup("ScVal")],["durability",e.lookup("ContractDataDurability")],["val",e.lookup("ScVal")]]),e.struct("ContractCodeCostInputs",[["ext",e.lookup("ExtensionPoint")],["nInstructions",e.lookup("Uint32")],["nFunctions",e.lookup("Uint32")],["nGlobals",e.lookup("Uint32")],["nTableEntries",e.lookup("Uint32")],["nTypes",e.lookup("Uint32")],["nDataSegments",e.lookup("Uint32")],["nElemSegments",e.lookup("Uint32")],["nImports",e.lookup("Uint32")],["nExports",e.lookup("Uint32")],["nDataSegmentBytes",e.lookup("Uint32")]]),e.struct("ContractCodeEntryV1",[["ext",e.lookup("ExtensionPoint")],["costInputs",e.lookup("ContractCodeCostInputs")]]),e.union("ContractCodeEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("ContractCodeEntryV1")}}),e.struct("ContractCodeEntry",[["ext",e.lookup("ContractCodeEntryExt")],["hash",e.lookup("Hash")],["code",e.varOpaque()]]),e.struct("TtlEntry",[["keyHash",e.lookup("Hash")],["liveUntilLedgerSeq",e.lookup("Uint32")]]),e.union("LedgerEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerEntryExtensionV1",[["sponsoringId",e.lookup("SponsorshipDescriptor")],["ext",e.lookup("LedgerEntryExtensionV1Ext")]]),e.union("LedgerEntryData",{switchOn:e.lookup("LedgerEntryType"),switchName:"type",switches:[["account","account"],["trustline","trustLine"],["offer","offer"],["data","data"],["claimableBalance","claimableBalance"],["liquidityPool","liquidityPool"],["contractData","contractData"],["contractCode","contractCode"],["configSetting","configSetting"],["ttl","ttl"]],arms:{account:e.lookup("AccountEntry"),trustLine:e.lookup("TrustLineEntry"),offer:e.lookup("OfferEntry"),data:e.lookup("DataEntry"),claimableBalance:e.lookup("ClaimableBalanceEntry"),liquidityPool:e.lookup("LiquidityPoolEntry"),contractData:e.lookup("ContractDataEntry"),contractCode:e.lookup("ContractCodeEntry"),configSetting:e.lookup("ConfigSettingEntry"),ttl:e.lookup("TtlEntry")}}),e.union("LedgerEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerEntryExtensionV1")}}),e.struct("LedgerEntry",[["lastModifiedLedgerSeq",e.lookup("Uint32")],["data",e.lookup("LedgerEntryData")],["ext",e.lookup("LedgerEntryExt")]]),e.struct("LedgerKeyAccount",[["accountId",e.lookup("AccountId")]]),e.struct("LedgerKeyTrustLine",[["accountId",e.lookup("AccountId")],["asset",e.lookup("TrustLineAsset")]]),e.struct("LedgerKeyOffer",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")]]),e.struct("LedgerKeyData",[["accountId",e.lookup("AccountId")],["dataName",e.lookup("String64")]]),e.struct("LedgerKeyClaimableBalance",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("LedgerKeyLiquidityPool",[["liquidityPoolId",e.lookup("PoolId")]]),e.struct("LedgerKeyContractData",[["contract",e.lookup("ScAddress")],["key",e.lookup("ScVal")],["durability",e.lookup("ContractDataDurability")]]),e.struct("LedgerKeyContractCode",[["hash",e.lookup("Hash")]]),e.struct("LedgerKeyConfigSetting",[["configSettingId",e.lookup("ConfigSettingId")]]),e.struct("LedgerKeyTtl",[["keyHash",e.lookup("Hash")]]),e.union("LedgerKey",{switchOn:e.lookup("LedgerEntryType"),switchName:"type",switches:[["account","account"],["trustline","trustLine"],["offer","offer"],["data","data"],["claimableBalance","claimableBalance"],["liquidityPool","liquidityPool"],["contractData","contractData"],["contractCode","contractCode"],["configSetting","configSetting"],["ttl","ttl"]],arms:{account:e.lookup("LedgerKeyAccount"),trustLine:e.lookup("LedgerKeyTrustLine"),offer:e.lookup("LedgerKeyOffer"),data:e.lookup("LedgerKeyData"),claimableBalance:e.lookup("LedgerKeyClaimableBalance"),liquidityPool:e.lookup("LedgerKeyLiquidityPool"),contractData:e.lookup("LedgerKeyContractData"),contractCode:e.lookup("LedgerKeyContractCode"),configSetting:e.lookup("LedgerKeyConfigSetting"),ttl:e.lookup("LedgerKeyTtl")}}),e.enum("EnvelopeType",{envelopeTypeTxV0:0,envelopeTypeScp:1,envelopeTypeTx:2,envelopeTypeAuth:3,envelopeTypeScpvalue:4,envelopeTypeTxFeeBump:5,envelopeTypeOpId:6,envelopeTypePoolRevokeOpId:7,envelopeTypeContractId:8,envelopeTypeSorobanAuthorization:9}),e.enum("BucketListType",{live:0,hotArchive:1,coldArchive:2}),e.enum("BucketEntryType",{metaentry:-1,liveentry:0,deadentry:1,initentry:2}),e.enum("HotArchiveBucketEntryType",{hotArchiveMetaentry:-1,hotArchiveArchived:0,hotArchiveLive:1,hotArchiveDeleted:2}),e.enum("ColdArchiveBucketEntryType",{coldArchiveMetaentry:-1,coldArchiveArchivedLeaf:0,coldArchiveDeletedLeaf:1,coldArchiveBoundaryLeaf:2,coldArchiveHash:3}),e.union("BucketMetadataExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"bucketListType"]],arms:{bucketListType:e.lookup("BucketListType")}}),e.struct("BucketMetadata",[["ledgerVersion",e.lookup("Uint32")],["ext",e.lookup("BucketMetadataExt")]]),e.union("BucketEntry",{switchOn:e.lookup("BucketEntryType"),switchName:"type",switches:[["liveentry","liveEntry"],["initentry","liveEntry"],["deadentry","deadEntry"],["metaentry","metaEntry"]],arms:{liveEntry:e.lookup("LedgerEntry"),deadEntry:e.lookup("LedgerKey"),metaEntry:e.lookup("BucketMetadata")}}),e.union("HotArchiveBucketEntry",{switchOn:e.lookup("HotArchiveBucketEntryType"),switchName:"type",switches:[["hotArchiveArchived","archivedEntry"],["hotArchiveLive","key"],["hotArchiveDeleted","key"],["hotArchiveMetaentry","metaEntry"]],arms:{archivedEntry:e.lookup("LedgerEntry"),key:e.lookup("LedgerKey"),metaEntry:e.lookup("BucketMetadata")}}),e.struct("ColdArchiveArchivedLeaf",[["index",e.lookup("Uint32")],["archivedEntry",e.lookup("LedgerEntry")]]),e.struct("ColdArchiveDeletedLeaf",[["index",e.lookup("Uint32")],["deletedKey",e.lookup("LedgerKey")]]),e.struct("ColdArchiveBoundaryLeaf",[["index",e.lookup("Uint32")],["isLowerBound",e.bool()]]),e.struct("ColdArchiveHashEntry",[["index",e.lookup("Uint32")],["level",e.lookup("Uint32")],["hash",e.lookup("Hash")]]),e.union("ColdArchiveBucketEntry",{switchOn:e.lookup("ColdArchiveBucketEntryType"),switchName:"type",switches:[["coldArchiveMetaentry","metaEntry"],["coldArchiveArchivedLeaf","archivedLeaf"],["coldArchiveDeletedLeaf","deletedLeaf"],["coldArchiveBoundaryLeaf","boundaryLeaf"],["coldArchiveHash","hashEntry"]],arms:{metaEntry:e.lookup("BucketMetadata"),archivedLeaf:e.lookup("ColdArchiveArchivedLeaf"),deletedLeaf:e.lookup("ColdArchiveDeletedLeaf"),boundaryLeaf:e.lookup("ColdArchiveBoundaryLeaf"),hashEntry:e.lookup("ColdArchiveHashEntry")}}),e.typedef("UpgradeType",e.varOpaque(128)),e.enum("StellarValueType",{stellarValueBasic:0,stellarValueSigned:1}),e.struct("LedgerCloseValueSignature",[["nodeId",e.lookup("NodeId")],["signature",e.lookup("Signature")]]),e.union("StellarValueExt",{switchOn:e.lookup("StellarValueType"),switchName:"v",switches:[["stellarValueBasic",e.void()],["stellarValueSigned","lcValueSignature"]],arms:{lcValueSignature:e.lookup("LedgerCloseValueSignature")}}),e.struct("StellarValue",[["txSetHash",e.lookup("Hash")],["closeTime",e.lookup("TimePoint")],["upgrades",e.varArray(e.lookup("UpgradeType"),6)],["ext",e.lookup("StellarValueExt")]]),e.const("MASK_LEDGER_HEADER_FLAGS",7),e.enum("LedgerHeaderFlags",{disableLiquidityPoolTradingFlag:1,disableLiquidityPoolDepositFlag:2,disableLiquidityPoolWithdrawalFlag:4}),e.union("LedgerHeaderExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerHeaderExtensionV1",[["flags",e.lookup("Uint32")],["ext",e.lookup("LedgerHeaderExtensionV1Ext")]]),e.union("LedgerHeaderExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerHeaderExtensionV1")}}),e.struct("LedgerHeader",[["ledgerVersion",e.lookup("Uint32")],["previousLedgerHash",e.lookup("Hash")],["scpValue",e.lookup("StellarValue")],["txSetResultHash",e.lookup("Hash")],["bucketListHash",e.lookup("Hash")],["ledgerSeq",e.lookup("Uint32")],["totalCoins",e.lookup("Int64")],["feePool",e.lookup("Int64")],["inflationSeq",e.lookup("Uint32")],["idPool",e.lookup("Uint64")],["baseFee",e.lookup("Uint32")],["baseReserve",e.lookup("Uint32")],["maxTxSetSize",e.lookup("Uint32")],["skipList",e.array(e.lookup("Hash"),4)],["ext",e.lookup("LedgerHeaderExt")]]),e.enum("LedgerUpgradeType",{ledgerUpgradeVersion:1,ledgerUpgradeBaseFee:2,ledgerUpgradeMaxTxSetSize:3,ledgerUpgradeBaseReserve:4,ledgerUpgradeFlags:5,ledgerUpgradeConfig:6,ledgerUpgradeMaxSorobanTxSetSize:7}),e.struct("ConfigUpgradeSetKey",[["contractId",e.lookup("Hash")],["contentHash",e.lookup("Hash")]]),e.union("LedgerUpgrade",{switchOn:e.lookup("LedgerUpgradeType"),switchName:"type",switches:[["ledgerUpgradeVersion","newLedgerVersion"],["ledgerUpgradeBaseFee","newBaseFee"],["ledgerUpgradeMaxTxSetSize","newMaxTxSetSize"],["ledgerUpgradeBaseReserve","newBaseReserve"],["ledgerUpgradeFlags","newFlags"],["ledgerUpgradeConfig","newConfig"],["ledgerUpgradeMaxSorobanTxSetSize","newMaxSorobanTxSetSize"]],arms:{newLedgerVersion:e.lookup("Uint32"),newBaseFee:e.lookup("Uint32"),newMaxTxSetSize:e.lookup("Uint32"),newBaseReserve:e.lookup("Uint32"),newFlags:e.lookup("Uint32"),newConfig:e.lookup("ConfigUpgradeSetKey"),newMaxSorobanTxSetSize:e.lookup("Uint32")}}),e.struct("ConfigUpgradeSet",[["updatedEntry",e.varArray(e.lookup("ConfigSettingEntry"),2147483647)]]),e.enum("TxSetComponentType",{txsetCompTxsMaybeDiscountedFee:0}),e.struct("TxSetComponentTxsMaybeDiscountedFee",[["baseFee",e.option(e.lookup("Int64"))],["txes",e.varArray(e.lookup("TransactionEnvelope"),2147483647)]]),e.union("TxSetComponent",{switchOn:e.lookup("TxSetComponentType"),switchName:"type",switches:[["txsetCompTxsMaybeDiscountedFee","txsMaybeDiscountedFee"]],arms:{txsMaybeDiscountedFee:e.lookup("TxSetComponentTxsMaybeDiscountedFee")}}),e.union("TransactionPhase",{switchOn:e.int(),switchName:"v",switches:[[0,"v0Components"]],arms:{v0Components:e.varArray(e.lookup("TxSetComponent"),2147483647)}}),e.struct("TransactionSet",[["previousLedgerHash",e.lookup("Hash")],["txes",e.varArray(e.lookup("TransactionEnvelope"),2147483647)]]),e.struct("TransactionSetV1",[["previousLedgerHash",e.lookup("Hash")],["phases",e.varArray(e.lookup("TransactionPhase"),2147483647)]]),e.union("GeneralizedTransactionSet",{switchOn:e.int(),switchName:"v",switches:[[1,"v1TxSet"]],arms:{v1TxSet:e.lookup("TransactionSetV1")}}),e.struct("TransactionResultPair",[["transactionHash",e.lookup("Hash")],["result",e.lookup("TransactionResult")]]),e.struct("TransactionResultSet",[["results",e.varArray(e.lookup("TransactionResultPair"),2147483647)]]),e.union("TransactionHistoryEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"generalizedTxSet"]],arms:{generalizedTxSet:e.lookup("GeneralizedTransactionSet")}}),e.struct("TransactionHistoryEntry",[["ledgerSeq",e.lookup("Uint32")],["txSet",e.lookup("TransactionSet")],["ext",e.lookup("TransactionHistoryEntryExt")]]),e.union("TransactionHistoryResultEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionHistoryResultEntry",[["ledgerSeq",e.lookup("Uint32")],["txResultSet",e.lookup("TransactionResultSet")],["ext",e.lookup("TransactionHistoryResultEntryExt")]]),e.union("LedgerHeaderHistoryEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerHeaderHistoryEntry",[["hash",e.lookup("Hash")],["header",e.lookup("LedgerHeader")],["ext",e.lookup("LedgerHeaderHistoryEntryExt")]]),e.struct("LedgerScpMessages",[["ledgerSeq",e.lookup("Uint32")],["messages",e.varArray(e.lookup("ScpEnvelope"),2147483647)]]),e.struct("ScpHistoryEntryV0",[["quorumSets",e.varArray(e.lookup("ScpQuorumSet"),2147483647)],["ledgerMessages",e.lookup("LedgerScpMessages")]]),e.union("ScpHistoryEntry",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("ScpHistoryEntryV0")}}),e.enum("LedgerEntryChangeType",{ledgerEntryCreated:0,ledgerEntryUpdated:1,ledgerEntryRemoved:2,ledgerEntryState:3}),e.union("LedgerEntryChange",{switchOn:e.lookup("LedgerEntryChangeType"),switchName:"type",switches:[["ledgerEntryCreated","created"],["ledgerEntryUpdated","updated"],["ledgerEntryRemoved","removed"],["ledgerEntryState","state"]],arms:{created:e.lookup("LedgerEntry"),updated:e.lookup("LedgerEntry"),removed:e.lookup("LedgerKey"),state:e.lookup("LedgerEntry")}}),e.typedef("LedgerEntryChanges",e.varArray(e.lookup("LedgerEntryChange"),2147483647)),e.struct("OperationMeta",[["changes",e.lookup("LedgerEntryChanges")]]),e.struct("TransactionMetaV1",[["txChanges",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)]]),e.struct("TransactionMetaV2",[["txChangesBefore",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)],["txChangesAfter",e.lookup("LedgerEntryChanges")]]),e.enum("ContractEventType",{system:0,contract:1,diagnostic:2}),e.struct("ContractEventV0",[["topics",e.varArray(e.lookup("ScVal"),2147483647)],["data",e.lookup("ScVal")]]),e.union("ContractEventBody",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("ContractEventV0")}}),e.struct("ContractEvent",[["ext",e.lookup("ExtensionPoint")],["contractId",e.option(e.lookup("Hash"))],["type",e.lookup("ContractEventType")],["body",e.lookup("ContractEventBody")]]),e.struct("DiagnosticEvent",[["inSuccessfulContractCall",e.bool()],["event",e.lookup("ContractEvent")]]),e.typedef("DiagnosticEvents",e.varArray(e.lookup("DiagnosticEvent"),2147483647)),e.struct("SorobanTransactionMetaExtV1",[["ext",e.lookup("ExtensionPoint")],["totalNonRefundableResourceFeeCharged",e.lookup("Int64")],["totalRefundableResourceFeeCharged",e.lookup("Int64")],["rentFeeCharged",e.lookup("Int64")]]),e.union("SorobanTransactionMetaExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("SorobanTransactionMetaExtV1")}}),e.struct("SorobanTransactionMeta",[["ext",e.lookup("SorobanTransactionMetaExt")],["events",e.varArray(e.lookup("ContractEvent"),2147483647)],["returnValue",e.lookup("ScVal")],["diagnosticEvents",e.varArray(e.lookup("DiagnosticEvent"),2147483647)]]),e.struct("TransactionMetaV3",[["ext",e.lookup("ExtensionPoint")],["txChangesBefore",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)],["txChangesAfter",e.lookup("LedgerEntryChanges")],["sorobanMeta",e.option(e.lookup("SorobanTransactionMeta"))]]),e.struct("InvokeHostFunctionSuccessPreImage",[["returnValue",e.lookup("ScVal")],["events",e.varArray(e.lookup("ContractEvent"),2147483647)]]),e.union("TransactionMeta",{switchOn:e.int(),switchName:"v",switches:[[0,"operations"],[1,"v1"],[2,"v2"],[3,"v3"]],arms:{operations:e.varArray(e.lookup("OperationMeta"),2147483647),v1:e.lookup("TransactionMetaV1"),v2:e.lookup("TransactionMetaV2"),v3:e.lookup("TransactionMetaV3")}}),e.struct("TransactionResultMeta",[["result",e.lookup("TransactionResultPair")],["feeProcessing",e.lookup("LedgerEntryChanges")],["txApplyProcessing",e.lookup("TransactionMeta")]]),e.struct("UpgradeEntryMeta",[["upgrade",e.lookup("LedgerUpgrade")],["changes",e.lookup("LedgerEntryChanges")]]),e.struct("LedgerCloseMetaV0",[["ledgerHeader",e.lookup("LedgerHeaderHistoryEntry")],["txSet",e.lookup("TransactionSet")],["txProcessing",e.varArray(e.lookup("TransactionResultMeta"),2147483647)],["upgradesProcessing",e.varArray(e.lookup("UpgradeEntryMeta"),2147483647)],["scpInfo",e.varArray(e.lookup("ScpHistoryEntry"),2147483647)]]),e.struct("LedgerCloseMetaExtV1",[["ext",e.lookup("ExtensionPoint")],["sorobanFeeWrite1Kb",e.lookup("Int64")]]),e.union("LedgerCloseMetaExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerCloseMetaExtV1")}}),e.struct("LedgerCloseMetaV1",[["ext",e.lookup("LedgerCloseMetaExt")],["ledgerHeader",e.lookup("LedgerHeaderHistoryEntry")],["txSet",e.lookup("GeneralizedTransactionSet")],["txProcessing",e.varArray(e.lookup("TransactionResultMeta"),2147483647)],["upgradesProcessing",e.varArray(e.lookup("UpgradeEntryMeta"),2147483647)],["scpInfo",e.varArray(e.lookup("ScpHistoryEntry"),2147483647)],["totalByteSizeOfBucketList",e.lookup("Uint64")],["evictedTemporaryLedgerKeys",e.varArray(e.lookup("LedgerKey"),2147483647)],["evictedPersistentLedgerEntries",e.varArray(e.lookup("LedgerEntry"),2147483647)]]),e.union("LedgerCloseMeta",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"],[1,"v1"]],arms:{v0:e.lookup("LedgerCloseMetaV0"),v1:e.lookup("LedgerCloseMetaV1")}}),e.enum("ErrorCode",{errMisc:0,errData:1,errConf:2,errAuth:3,errLoad:4}),e.struct("Error",[["code",e.lookup("ErrorCode")],["msg",e.string(100)]]),e.struct("SendMore",[["numMessages",e.lookup("Uint32")]]),e.struct("SendMoreExtended",[["numMessages",e.lookup("Uint32")],["numBytes",e.lookup("Uint32")]]),e.struct("AuthCert",[["pubkey",e.lookup("Curve25519Public")],["expiration",e.lookup("Uint64")],["sig",e.lookup("Signature")]]),e.struct("Hello",[["ledgerVersion",e.lookup("Uint32")],["overlayVersion",e.lookup("Uint32")],["overlayMinVersion",e.lookup("Uint32")],["networkId",e.lookup("Hash")],["versionStr",e.string(100)],["listeningPort",e.int()],["peerId",e.lookup("NodeId")],["cert",e.lookup("AuthCert")],["nonce",e.lookup("Uint256")]]),e.const("AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED",200),e.struct("Auth",[["flags",e.int()]]),e.enum("IpAddrType",{iPv4:0,iPv6:1}),e.union("PeerAddressIp",{switchOn:e.lookup("IpAddrType"),switchName:"type",switches:[["iPv4","ipv4"],["iPv6","ipv6"]],arms:{ipv4:e.opaque(4),ipv6:e.opaque(16)}}),e.struct("PeerAddress",[["ip",e.lookup("PeerAddressIp")],["port",e.lookup("Uint32")],["numFailures",e.lookup("Uint32")]]),e.enum("MessageType",{errorMsg:0,auth:2,dontHave:3,getPeers:4,peers:5,getTxSet:6,txSet:7,generalizedTxSet:17,transaction:8,getScpQuorumset:9,scpQuorumset:10,scpMessage:11,getScpState:12,hello:13,surveyRequest:14,surveyResponse:15,sendMore:16,sendMoreExtended:20,floodAdvert:18,floodDemand:19,timeSlicedSurveyRequest:21,timeSlicedSurveyResponse:22,timeSlicedSurveyStartCollecting:23,timeSlicedSurveyStopCollecting:24}),e.struct("DontHave",[["type",e.lookup("MessageType")],["reqHash",e.lookup("Uint256")]]),e.enum("SurveyMessageCommandType",{surveyTopology:0,timeSlicedSurveyTopology:1}),e.enum("SurveyMessageResponseType",{surveyTopologyResponseV0:0,surveyTopologyResponseV1:1,surveyTopologyResponseV2:2}),e.struct("TimeSlicedSurveyStartCollectingMessage",[["surveyorId",e.lookup("NodeId")],["nonce",e.lookup("Uint32")],["ledgerNum",e.lookup("Uint32")]]),e.struct("SignedTimeSlicedSurveyStartCollectingMessage",[["signature",e.lookup("Signature")],["startCollecting",e.lookup("TimeSlicedSurveyStartCollectingMessage")]]),e.struct("TimeSlicedSurveyStopCollectingMessage",[["surveyorId",e.lookup("NodeId")],["nonce",e.lookup("Uint32")],["ledgerNum",e.lookup("Uint32")]]),e.struct("SignedTimeSlicedSurveyStopCollectingMessage",[["signature",e.lookup("Signature")],["stopCollecting",e.lookup("TimeSlicedSurveyStopCollectingMessage")]]),e.struct("SurveyRequestMessage",[["surveyorPeerId",e.lookup("NodeId")],["surveyedPeerId",e.lookup("NodeId")],["ledgerNum",e.lookup("Uint32")],["encryptionKey",e.lookup("Curve25519Public")],["commandType",e.lookup("SurveyMessageCommandType")]]),e.struct("TimeSlicedSurveyRequestMessage",[["request",e.lookup("SurveyRequestMessage")],["nonce",e.lookup("Uint32")],["inboundPeersIndex",e.lookup("Uint32")],["outboundPeersIndex",e.lookup("Uint32")]]),e.struct("SignedSurveyRequestMessage",[["requestSignature",e.lookup("Signature")],["request",e.lookup("SurveyRequestMessage")]]),e.struct("SignedTimeSlicedSurveyRequestMessage",[["requestSignature",e.lookup("Signature")],["request",e.lookup("TimeSlicedSurveyRequestMessage")]]),e.typedef("EncryptedBody",e.varOpaque(64e3)),e.struct("SurveyResponseMessage",[["surveyorPeerId",e.lookup("NodeId")],["surveyedPeerId",e.lookup("NodeId")],["ledgerNum",e.lookup("Uint32")],["commandType",e.lookup("SurveyMessageCommandType")],["encryptedBody",e.lookup("EncryptedBody")]]),e.struct("TimeSlicedSurveyResponseMessage",[["response",e.lookup("SurveyResponseMessage")],["nonce",e.lookup("Uint32")]]),e.struct("SignedSurveyResponseMessage",[["responseSignature",e.lookup("Signature")],["response",e.lookup("SurveyResponseMessage")]]),e.struct("SignedTimeSlicedSurveyResponseMessage",[["responseSignature",e.lookup("Signature")],["response",e.lookup("TimeSlicedSurveyResponseMessage")]]),e.struct("PeerStats",[["id",e.lookup("NodeId")],["versionStr",e.string(100)],["messagesRead",e.lookup("Uint64")],["messagesWritten",e.lookup("Uint64")],["bytesRead",e.lookup("Uint64")],["bytesWritten",e.lookup("Uint64")],["secondsConnected",e.lookup("Uint64")],["uniqueFloodBytesRecv",e.lookup("Uint64")],["duplicateFloodBytesRecv",e.lookup("Uint64")],["uniqueFetchBytesRecv",e.lookup("Uint64")],["duplicateFetchBytesRecv",e.lookup("Uint64")],["uniqueFloodMessageRecv",e.lookup("Uint64")],["duplicateFloodMessageRecv",e.lookup("Uint64")],["uniqueFetchMessageRecv",e.lookup("Uint64")],["duplicateFetchMessageRecv",e.lookup("Uint64")]]),e.typedef("PeerStatList",e.varArray(e.lookup("PeerStats"),25)),e.struct("TimeSlicedNodeData",[["addedAuthenticatedPeers",e.lookup("Uint32")],["droppedAuthenticatedPeers",e.lookup("Uint32")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")],["p75ScpFirstToSelfLatencyMs",e.lookup("Uint32")],["p75ScpSelfToOtherLatencyMs",e.lookup("Uint32")],["lostSyncCount",e.lookup("Uint32")],["isValidator",e.bool()],["maxInboundPeerCount",e.lookup("Uint32")],["maxOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TimeSlicedPeerData",[["peerStats",e.lookup("PeerStats")],["averageLatencyMs",e.lookup("Uint32")]]),e.typedef("TimeSlicedPeerDataList",e.varArray(e.lookup("TimeSlicedPeerData"),25)),e.struct("TopologyResponseBodyV0",[["inboundPeers",e.lookup("PeerStatList")],["outboundPeers",e.lookup("PeerStatList")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TopologyResponseBodyV1",[["inboundPeers",e.lookup("PeerStatList")],["outboundPeers",e.lookup("PeerStatList")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")],["maxInboundPeerCount",e.lookup("Uint32")],["maxOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TopologyResponseBodyV2",[["inboundPeers",e.lookup("TimeSlicedPeerDataList")],["outboundPeers",e.lookup("TimeSlicedPeerDataList")],["nodeData",e.lookup("TimeSlicedNodeData")]]),e.union("SurveyResponseBody",{switchOn:e.lookup("SurveyMessageResponseType"),switchName:"type",switches:[["surveyTopologyResponseV0","topologyResponseBodyV0"],["surveyTopologyResponseV1","topologyResponseBodyV1"],["surveyTopologyResponseV2","topologyResponseBodyV2"]],arms:{topologyResponseBodyV0:e.lookup("TopologyResponseBodyV0"),topologyResponseBodyV1:e.lookup("TopologyResponseBodyV1"),topologyResponseBodyV2:e.lookup("TopologyResponseBodyV2")}}),e.const("TX_ADVERT_VECTOR_MAX_SIZE",1e3),e.typedef("TxAdvertVector",e.varArray(e.lookup("Hash"),e.lookup("TX_ADVERT_VECTOR_MAX_SIZE"))),e.struct("FloodAdvert",[["txHashes",e.lookup("TxAdvertVector")]]),e.const("TX_DEMAND_VECTOR_MAX_SIZE",1e3),e.typedef("TxDemandVector",e.varArray(e.lookup("Hash"),e.lookup("TX_DEMAND_VECTOR_MAX_SIZE"))),e.struct("FloodDemand",[["txHashes",e.lookup("TxDemandVector")]]),e.union("StellarMessage",{switchOn:e.lookup("MessageType"),switchName:"type",switches:[["errorMsg","error"],["hello","hello"],["auth","auth"],["dontHave","dontHave"],["getPeers",e.void()],["peers","peers"],["getTxSet","txSetHash"],["txSet","txSet"],["generalizedTxSet","generalizedTxSet"],["transaction","transaction"],["surveyRequest","signedSurveyRequestMessage"],["surveyResponse","signedSurveyResponseMessage"],["timeSlicedSurveyRequest","signedTimeSlicedSurveyRequestMessage"],["timeSlicedSurveyResponse","signedTimeSlicedSurveyResponseMessage"],["timeSlicedSurveyStartCollecting","signedTimeSlicedSurveyStartCollectingMessage"],["timeSlicedSurveyStopCollecting","signedTimeSlicedSurveyStopCollectingMessage"],["getScpQuorumset","qSetHash"],["scpQuorumset","qSet"],["scpMessage","envelope"],["getScpState","getScpLedgerSeq"],["sendMore","sendMoreMessage"],["sendMoreExtended","sendMoreExtendedMessage"],["floodAdvert","floodAdvert"],["floodDemand","floodDemand"]],arms:{error:e.lookup("Error"),hello:e.lookup("Hello"),auth:e.lookup("Auth"),dontHave:e.lookup("DontHave"),peers:e.varArray(e.lookup("PeerAddress"),100),txSetHash:e.lookup("Uint256"),txSet:e.lookup("TransactionSet"),generalizedTxSet:e.lookup("GeneralizedTransactionSet"),transaction:e.lookup("TransactionEnvelope"),signedSurveyRequestMessage:e.lookup("SignedSurveyRequestMessage"),signedSurveyResponseMessage:e.lookup("SignedSurveyResponseMessage"),signedTimeSlicedSurveyRequestMessage:e.lookup("SignedTimeSlicedSurveyRequestMessage"),signedTimeSlicedSurveyResponseMessage:e.lookup("SignedTimeSlicedSurveyResponseMessage"),signedTimeSlicedSurveyStartCollectingMessage:e.lookup("SignedTimeSlicedSurveyStartCollectingMessage"),signedTimeSlicedSurveyStopCollectingMessage:e.lookup("SignedTimeSlicedSurveyStopCollectingMessage"),qSetHash:e.lookup("Uint256"),qSet:e.lookup("ScpQuorumSet"),envelope:e.lookup("ScpEnvelope"),getScpLedgerSeq:e.lookup("Uint32"),sendMoreMessage:e.lookup("SendMore"),sendMoreExtendedMessage:e.lookup("SendMoreExtended"),floodAdvert:e.lookup("FloodAdvert"),floodDemand:e.lookup("FloodDemand")}}),e.struct("AuthenticatedMessageV0",[["sequence",e.lookup("Uint64")],["message",e.lookup("StellarMessage")],["mac",e.lookup("HmacSha256Mac")]]),e.union("AuthenticatedMessage",{switchOn:e.lookup("Uint32"),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("AuthenticatedMessageV0")}}),e.const("MAX_OPS_PER_TX",100),e.union("LiquidityPoolParameters",{switchOn:e.lookup("LiquidityPoolType"),switchName:"type",switches:[["liquidityPoolConstantProduct","constantProduct"]],arms:{constantProduct:e.lookup("LiquidityPoolConstantProductParameters")}}),e.struct("MuxedAccountMed25519",[["id",e.lookup("Uint64")],["ed25519",e.lookup("Uint256")]]),e.union("MuxedAccount",{switchOn:e.lookup("CryptoKeyType"),switchName:"type",switches:[["keyTypeEd25519","ed25519"],["keyTypeMuxedEd25519","med25519"]],arms:{ed25519:e.lookup("Uint256"),med25519:e.lookup("MuxedAccountMed25519")}}),e.struct("DecoratedSignature",[["hint",e.lookup("SignatureHint")],["signature",e.lookup("Signature")]]),e.enum("OperationType",{createAccount:0,payment:1,pathPaymentStrictReceive:2,manageSellOffer:3,createPassiveSellOffer:4,setOptions:5,changeTrust:6,allowTrust:7,accountMerge:8,inflation:9,manageData:10,bumpSequence:11,manageBuyOffer:12,pathPaymentStrictSend:13,createClaimableBalance:14,claimClaimableBalance:15,beginSponsoringFutureReserves:16,endSponsoringFutureReserves:17,revokeSponsorship:18,clawback:19,clawbackClaimableBalance:20,setTrustLineFlags:21,liquidityPoolDeposit:22,liquidityPoolWithdraw:23,invokeHostFunction:24,extendFootprintTtl:25,restoreFootprint:26}),e.struct("CreateAccountOp",[["destination",e.lookup("AccountId")],["startingBalance",e.lookup("Int64")]]),e.struct("PaymentOp",[["destination",e.lookup("MuxedAccount")],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")]]),e.struct("PathPaymentStrictReceiveOp",[["sendAsset",e.lookup("Asset")],["sendMax",e.lookup("Int64")],["destination",e.lookup("MuxedAccount")],["destAsset",e.lookup("Asset")],["destAmount",e.lookup("Int64")],["path",e.varArray(e.lookup("Asset"),5)]]),e.struct("PathPaymentStrictSendOp",[["sendAsset",e.lookup("Asset")],["sendAmount",e.lookup("Int64")],["destination",e.lookup("MuxedAccount")],["destAsset",e.lookup("Asset")],["destMin",e.lookup("Int64")],["path",e.varArray(e.lookup("Asset"),5)]]),e.struct("ManageSellOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")],["offerId",e.lookup("Int64")]]),e.struct("ManageBuyOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["buyAmount",e.lookup("Int64")],["price",e.lookup("Price")],["offerId",e.lookup("Int64")]]),e.struct("CreatePassiveSellOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")]]),e.struct("SetOptionsOp",[["inflationDest",e.option(e.lookup("AccountId"))],["clearFlags",e.option(e.lookup("Uint32"))],["setFlags",e.option(e.lookup("Uint32"))],["masterWeight",e.option(e.lookup("Uint32"))],["lowThreshold",e.option(e.lookup("Uint32"))],["medThreshold",e.option(e.lookup("Uint32"))],["highThreshold",e.option(e.lookup("Uint32"))],["homeDomain",e.option(e.lookup("String32"))],["signer",e.option(e.lookup("Signer"))]]),e.union("ChangeTrustAsset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"],["assetTypePoolShare","liquidityPool"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12"),liquidityPool:e.lookup("LiquidityPoolParameters")}}),e.struct("ChangeTrustOp",[["line",e.lookup("ChangeTrustAsset")],["limit",e.lookup("Int64")]]),e.struct("AllowTrustOp",[["trustor",e.lookup("AccountId")],["asset",e.lookup("AssetCode")],["authorize",e.lookup("Uint32")]]),e.struct("ManageDataOp",[["dataName",e.lookup("String64")],["dataValue",e.option(e.lookup("DataValue"))]]),e.struct("BumpSequenceOp",[["bumpTo",e.lookup("SequenceNumber")]]),e.struct("CreateClaimableBalanceOp",[["asset",e.lookup("Asset")],["amount",e.lookup("Int64")],["claimants",e.varArray(e.lookup("Claimant"),10)]]),e.struct("ClaimClaimableBalanceOp",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("BeginSponsoringFutureReservesOp",[["sponsoredId",e.lookup("AccountId")]]),e.enum("RevokeSponsorshipType",{revokeSponsorshipLedgerEntry:0,revokeSponsorshipSigner:1}),e.struct("RevokeSponsorshipOpSigner",[["accountId",e.lookup("AccountId")],["signerKey",e.lookup("SignerKey")]]),e.union("RevokeSponsorshipOp",{switchOn:e.lookup("RevokeSponsorshipType"),switchName:"type",switches:[["revokeSponsorshipLedgerEntry","ledgerKey"],["revokeSponsorshipSigner","signer"]],arms:{ledgerKey:e.lookup("LedgerKey"),signer:e.lookup("RevokeSponsorshipOpSigner")}}),e.struct("ClawbackOp",[["asset",e.lookup("Asset")],["from",e.lookup("MuxedAccount")],["amount",e.lookup("Int64")]]),e.struct("ClawbackClaimableBalanceOp",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("SetTrustLineFlagsOp",[["trustor",e.lookup("AccountId")],["asset",e.lookup("Asset")],["clearFlags",e.lookup("Uint32")],["setFlags",e.lookup("Uint32")]]),e.const("LIQUIDITY_POOL_FEE_V18",30),e.struct("LiquidityPoolDepositOp",[["liquidityPoolId",e.lookup("PoolId")],["maxAmountA",e.lookup("Int64")],["maxAmountB",e.lookup("Int64")],["minPrice",e.lookup("Price")],["maxPrice",e.lookup("Price")]]),e.struct("LiquidityPoolWithdrawOp",[["liquidityPoolId",e.lookup("PoolId")],["amount",e.lookup("Int64")],["minAmountA",e.lookup("Int64")],["minAmountB",e.lookup("Int64")]]),e.enum("HostFunctionType",{hostFunctionTypeInvokeContract:0,hostFunctionTypeCreateContract:1,hostFunctionTypeUploadContractWasm:2,hostFunctionTypeCreateContractV2:3}),e.enum("ContractIdPreimageType",{contractIdPreimageFromAddress:0,contractIdPreimageFromAsset:1}),e.struct("ContractIdPreimageFromAddress",[["address",e.lookup("ScAddress")],["salt",e.lookup("Uint256")]]),e.union("ContractIdPreimage",{switchOn:e.lookup("ContractIdPreimageType"),switchName:"type",switches:[["contractIdPreimageFromAddress","fromAddress"],["contractIdPreimageFromAsset","fromAsset"]],arms:{fromAddress:e.lookup("ContractIdPreimageFromAddress"),fromAsset:e.lookup("Asset")}}),e.struct("CreateContractArgs",[["contractIdPreimage",e.lookup("ContractIdPreimage")],["executable",e.lookup("ContractExecutable")]]),e.struct("CreateContractArgsV2",[["contractIdPreimage",e.lookup("ContractIdPreimage")],["executable",e.lookup("ContractExecutable")],["constructorArgs",e.varArray(e.lookup("ScVal"),2147483647)]]),e.struct("InvokeContractArgs",[["contractAddress",e.lookup("ScAddress")],["functionName",e.lookup("ScSymbol")],["args",e.varArray(e.lookup("ScVal"),2147483647)]]),e.union("HostFunction",{switchOn:e.lookup("HostFunctionType"),switchName:"type",switches:[["hostFunctionTypeInvokeContract","invokeContract"],["hostFunctionTypeCreateContract","createContract"],["hostFunctionTypeUploadContractWasm","wasm"],["hostFunctionTypeCreateContractV2","createContractV2"]],arms:{invokeContract:e.lookup("InvokeContractArgs"),createContract:e.lookup("CreateContractArgs"),wasm:e.varOpaque(),createContractV2:e.lookup("CreateContractArgsV2")}}),e.enum("SorobanAuthorizedFunctionType",{sorobanAuthorizedFunctionTypeContractFn:0,sorobanAuthorizedFunctionTypeCreateContractHostFn:1,sorobanAuthorizedFunctionTypeCreateContractV2HostFn:2}),e.union("SorobanAuthorizedFunction",{switchOn:e.lookup("SorobanAuthorizedFunctionType"),switchName:"type",switches:[["sorobanAuthorizedFunctionTypeContractFn","contractFn"],["sorobanAuthorizedFunctionTypeCreateContractHostFn","createContractHostFn"],["sorobanAuthorizedFunctionTypeCreateContractV2HostFn","createContractV2HostFn"]],arms:{contractFn:e.lookup("InvokeContractArgs"),createContractHostFn:e.lookup("CreateContractArgs"),createContractV2HostFn:e.lookup("CreateContractArgsV2")}}),e.struct("SorobanAuthorizedInvocation",[["function",e.lookup("SorobanAuthorizedFunction")],["subInvocations",e.varArray(e.lookup("SorobanAuthorizedInvocation"),2147483647)]]),e.struct("SorobanAddressCredentials",[["address",e.lookup("ScAddress")],["nonce",e.lookup("Int64")],["signatureExpirationLedger",e.lookup("Uint32")],["signature",e.lookup("ScVal")]]),e.enum("SorobanCredentialsType",{sorobanCredentialsSourceAccount:0,sorobanCredentialsAddress:1}),e.union("SorobanCredentials",{switchOn:e.lookup("SorobanCredentialsType"),switchName:"type",switches:[["sorobanCredentialsSourceAccount",e.void()],["sorobanCredentialsAddress","address"]],arms:{address:e.lookup("SorobanAddressCredentials")}}),e.struct("SorobanAuthorizationEntry",[["credentials",e.lookup("SorobanCredentials")],["rootInvocation",e.lookup("SorobanAuthorizedInvocation")]]),e.struct("InvokeHostFunctionOp",[["hostFunction",e.lookup("HostFunction")],["auth",e.varArray(e.lookup("SorobanAuthorizationEntry"),2147483647)]]),e.struct("ExtendFootprintTtlOp",[["ext",e.lookup("ExtensionPoint")],["extendTo",e.lookup("Uint32")]]),e.struct("RestoreFootprintOp",[["ext",e.lookup("ExtensionPoint")]]),e.union("OperationBody",{switchOn:e.lookup("OperationType"),switchName:"type",switches:[["createAccount","createAccountOp"],["payment","paymentOp"],["pathPaymentStrictReceive","pathPaymentStrictReceiveOp"],["manageSellOffer","manageSellOfferOp"],["createPassiveSellOffer","createPassiveSellOfferOp"],["setOptions","setOptionsOp"],["changeTrust","changeTrustOp"],["allowTrust","allowTrustOp"],["accountMerge","destination"],["inflation",e.void()],["manageData","manageDataOp"],["bumpSequence","bumpSequenceOp"],["manageBuyOffer","manageBuyOfferOp"],["pathPaymentStrictSend","pathPaymentStrictSendOp"],["createClaimableBalance","createClaimableBalanceOp"],["claimClaimableBalance","claimClaimableBalanceOp"],["beginSponsoringFutureReserves","beginSponsoringFutureReservesOp"],["endSponsoringFutureReserves",e.void()],["revokeSponsorship","revokeSponsorshipOp"],["clawback","clawbackOp"],["clawbackClaimableBalance","clawbackClaimableBalanceOp"],["setTrustLineFlags","setTrustLineFlagsOp"],["liquidityPoolDeposit","liquidityPoolDepositOp"],["liquidityPoolWithdraw","liquidityPoolWithdrawOp"],["invokeHostFunction","invokeHostFunctionOp"],["extendFootprintTtl","extendFootprintTtlOp"],["restoreFootprint","restoreFootprintOp"]],arms:{createAccountOp:e.lookup("CreateAccountOp"),paymentOp:e.lookup("PaymentOp"),pathPaymentStrictReceiveOp:e.lookup("PathPaymentStrictReceiveOp"),manageSellOfferOp:e.lookup("ManageSellOfferOp"),createPassiveSellOfferOp:e.lookup("CreatePassiveSellOfferOp"),setOptionsOp:e.lookup("SetOptionsOp"),changeTrustOp:e.lookup("ChangeTrustOp"),allowTrustOp:e.lookup("AllowTrustOp"),destination:e.lookup("MuxedAccount"),manageDataOp:e.lookup("ManageDataOp"),bumpSequenceOp:e.lookup("BumpSequenceOp"),manageBuyOfferOp:e.lookup("ManageBuyOfferOp"),pathPaymentStrictSendOp:e.lookup("PathPaymentStrictSendOp"),createClaimableBalanceOp:e.lookup("CreateClaimableBalanceOp"),claimClaimableBalanceOp:e.lookup("ClaimClaimableBalanceOp"),beginSponsoringFutureReservesOp:e.lookup("BeginSponsoringFutureReservesOp"),revokeSponsorshipOp:e.lookup("RevokeSponsorshipOp"),clawbackOp:e.lookup("ClawbackOp"),clawbackClaimableBalanceOp:e.lookup("ClawbackClaimableBalanceOp"),setTrustLineFlagsOp:e.lookup("SetTrustLineFlagsOp"),liquidityPoolDepositOp:e.lookup("LiquidityPoolDepositOp"),liquidityPoolWithdrawOp:e.lookup("LiquidityPoolWithdrawOp"),invokeHostFunctionOp:e.lookup("InvokeHostFunctionOp"),extendFootprintTtlOp:e.lookup("ExtendFootprintTtlOp"),restoreFootprintOp:e.lookup("RestoreFootprintOp")}}),e.struct("Operation",[["sourceAccount",e.option(e.lookup("MuxedAccount"))],["body",e.lookup("OperationBody")]]),e.struct("HashIdPreimageOperationId",[["sourceAccount",e.lookup("AccountId")],["seqNum",e.lookup("SequenceNumber")],["opNum",e.lookup("Uint32")]]),e.struct("HashIdPreimageRevokeId",[["sourceAccount",e.lookup("AccountId")],["seqNum",e.lookup("SequenceNumber")],["opNum",e.lookup("Uint32")],["liquidityPoolId",e.lookup("PoolId")],["asset",e.lookup("Asset")]]),e.struct("HashIdPreimageContractId",[["networkId",e.lookup("Hash")],["contractIdPreimage",e.lookup("ContractIdPreimage")]]),e.struct("HashIdPreimageSorobanAuthorization",[["networkId",e.lookup("Hash")],["nonce",e.lookup("Int64")],["signatureExpirationLedger",e.lookup("Uint32")],["invocation",e.lookup("SorobanAuthorizedInvocation")]]),e.union("HashIdPreimage",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeOpId","operationId"],["envelopeTypePoolRevokeOpId","revokeId"],["envelopeTypeContractId","contractId"],["envelopeTypeSorobanAuthorization","sorobanAuthorization"]],arms:{operationId:e.lookup("HashIdPreimageOperationId"),revokeId:e.lookup("HashIdPreimageRevokeId"),contractId:e.lookup("HashIdPreimageContractId"),sorobanAuthorization:e.lookup("HashIdPreimageSorobanAuthorization")}}),e.enum("MemoType",{memoNone:0,memoText:1,memoId:2,memoHash:3,memoReturn:4}),e.union("Memo",{switchOn:e.lookup("MemoType"),switchName:"type",switches:[["memoNone",e.void()],["memoText","text"],["memoId","id"],["memoHash","hash"],["memoReturn","retHash"]],arms:{text:e.string(28),id:e.lookup("Uint64"),hash:e.lookup("Hash"),retHash:e.lookup("Hash")}}),e.struct("TimeBounds",[["minTime",e.lookup("TimePoint")],["maxTime",e.lookup("TimePoint")]]),e.struct("LedgerBounds",[["minLedger",e.lookup("Uint32")],["maxLedger",e.lookup("Uint32")]]),e.struct("PreconditionsV2",[["timeBounds",e.option(e.lookup("TimeBounds"))],["ledgerBounds",e.option(e.lookup("LedgerBounds"))],["minSeqNum",e.option(e.lookup("SequenceNumber"))],["minSeqAge",e.lookup("Duration")],["minSeqLedgerGap",e.lookup("Uint32")],["extraSigners",e.varArray(e.lookup("SignerKey"),2)]]),e.enum("PreconditionType",{precondNone:0,precondTime:1,precondV2:2}),e.union("Preconditions",{switchOn:e.lookup("PreconditionType"),switchName:"type",switches:[["precondNone",e.void()],["precondTime","timeBounds"],["precondV2","v2"]],arms:{timeBounds:e.lookup("TimeBounds"),v2:e.lookup("PreconditionsV2")}}),e.struct("LedgerFootprint",[["readOnly",e.varArray(e.lookup("LedgerKey"),2147483647)],["readWrite",e.varArray(e.lookup("LedgerKey"),2147483647)]]),e.enum("ArchivalProofType",{existence:0,nonexistence:1}),e.struct("ArchivalProofNode",[["index",e.lookup("Uint32")],["hash",e.lookup("Hash")]]),e.typedef("ProofLevel",e.varArray(e.lookup("ArchivalProofNode"),2147483647)),e.struct("NonexistenceProofBody",[["entriesToProve",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["proofLevels",e.varArray(e.lookup("ProofLevel"),2147483647)]]),e.struct("ExistenceProofBody",[["keysToProve",e.varArray(e.lookup("LedgerKey"),2147483647)],["lowBoundEntries",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["highBoundEntries",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["proofLevels",e.varArray(e.lookup("ProofLevel"),2147483647)]]),e.union("ArchivalProofBody",{switchOn:e.lookup("ArchivalProofType"),switchName:"t",switches:[["existence","nonexistenceProof"],["nonexistence","existenceProof"]],arms:{nonexistenceProof:e.lookup("NonexistenceProofBody"),existenceProof:e.lookup("ExistenceProofBody")}}),e.struct("ArchivalProof",[["epoch",e.lookup("Uint32")],["body",e.lookup("ArchivalProofBody")]]),e.struct("SorobanResources",[["footprint",e.lookup("LedgerFootprint")],["instructions",e.lookup("Uint32")],["readBytes",e.lookup("Uint32")],["writeBytes",e.lookup("Uint32")]]),e.struct("SorobanTransactionData",[["ext",e.lookup("ExtensionPoint")],["resources",e.lookup("SorobanResources")],["resourceFee",e.lookup("Int64")]]),e.union("TransactionV0Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionV0",[["sourceAccountEd25519",e.lookup("Uint256")],["fee",e.lookup("Uint32")],["seqNum",e.lookup("SequenceNumber")],["timeBounds",e.option(e.lookup("TimeBounds"))],["memo",e.lookup("Memo")],["operations",e.varArray(e.lookup("Operation"),e.lookup("MAX_OPS_PER_TX"))],["ext",e.lookup("TransactionV0Ext")]]),e.struct("TransactionV0Envelope",[["tx",e.lookup("TransactionV0")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("TransactionExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"sorobanData"]],arms:{sorobanData:e.lookup("SorobanTransactionData")}}),e.struct("Transaction",[["sourceAccount",e.lookup("MuxedAccount")],["fee",e.lookup("Uint32")],["seqNum",e.lookup("SequenceNumber")],["cond",e.lookup("Preconditions")],["memo",e.lookup("Memo")],["operations",e.varArray(e.lookup("Operation"),e.lookup("MAX_OPS_PER_TX"))],["ext",e.lookup("TransactionExt")]]),e.struct("TransactionV1Envelope",[["tx",e.lookup("Transaction")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("FeeBumpTransactionInnerTx",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTx","v1"]],arms:{v1:e.lookup("TransactionV1Envelope")}}),e.union("FeeBumpTransactionExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("FeeBumpTransaction",[["feeSource",e.lookup("MuxedAccount")],["fee",e.lookup("Int64")],["innerTx",e.lookup("FeeBumpTransactionInnerTx")],["ext",e.lookup("FeeBumpTransactionExt")]]),e.struct("FeeBumpTransactionEnvelope",[["tx",e.lookup("FeeBumpTransaction")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("TransactionEnvelope",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTxV0","v0"],["envelopeTypeTx","v1"],["envelopeTypeTxFeeBump","feeBump"]],arms:{v0:e.lookup("TransactionV0Envelope"),v1:e.lookup("TransactionV1Envelope"),feeBump:e.lookup("FeeBumpTransactionEnvelope")}}),e.union("TransactionSignaturePayloadTaggedTransaction",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTx","tx"],["envelopeTypeTxFeeBump","feeBump"]],arms:{tx:e.lookup("Transaction"),feeBump:e.lookup("FeeBumpTransaction")}}),e.struct("TransactionSignaturePayload",[["networkId",e.lookup("Hash")],["taggedTransaction",e.lookup("TransactionSignaturePayloadTaggedTransaction")]]),e.enum("ClaimAtomType",{claimAtomTypeV0:0,claimAtomTypeOrderBook:1,claimAtomTypeLiquidityPool:2}),e.struct("ClaimOfferAtomV0",[["sellerEd25519",e.lookup("Uint256")],["offerId",e.lookup("Int64")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.struct("ClaimOfferAtom",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.struct("ClaimLiquidityAtom",[["liquidityPoolId",e.lookup("PoolId")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.union("ClaimAtom",{switchOn:e.lookup("ClaimAtomType"),switchName:"type",switches:[["claimAtomTypeV0","v0"],["claimAtomTypeOrderBook","orderBook"],["claimAtomTypeLiquidityPool","liquidityPool"]],arms:{v0:e.lookup("ClaimOfferAtomV0"),orderBook:e.lookup("ClaimOfferAtom"),liquidityPool:e.lookup("ClaimLiquidityAtom")}}),e.enum("CreateAccountResultCode",{createAccountSuccess:0,createAccountMalformed:-1,createAccountUnderfunded:-2,createAccountLowReserve:-3,createAccountAlreadyExist:-4}),e.union("CreateAccountResult",{switchOn:e.lookup("CreateAccountResultCode"),switchName:"code",switches:[["createAccountSuccess",e.void()],["createAccountMalformed",e.void()],["createAccountUnderfunded",e.void()],["createAccountLowReserve",e.void()],["createAccountAlreadyExist",e.void()]],arms:{}}),e.enum("PaymentResultCode",{paymentSuccess:0,paymentMalformed:-1,paymentUnderfunded:-2,paymentSrcNoTrust:-3,paymentSrcNotAuthorized:-4,paymentNoDestination:-5,paymentNoTrust:-6,paymentNotAuthorized:-7,paymentLineFull:-8,paymentNoIssuer:-9}),e.union("PaymentResult",{switchOn:e.lookup("PaymentResultCode"),switchName:"code",switches:[["paymentSuccess",e.void()],["paymentMalformed",e.void()],["paymentUnderfunded",e.void()],["paymentSrcNoTrust",e.void()],["paymentSrcNotAuthorized",e.void()],["paymentNoDestination",e.void()],["paymentNoTrust",e.void()],["paymentNotAuthorized",e.void()],["paymentLineFull",e.void()],["paymentNoIssuer",e.void()]],arms:{}}),e.enum("PathPaymentStrictReceiveResultCode",{pathPaymentStrictReceiveSuccess:0,pathPaymentStrictReceiveMalformed:-1,pathPaymentStrictReceiveUnderfunded:-2,pathPaymentStrictReceiveSrcNoTrust:-3,pathPaymentStrictReceiveSrcNotAuthorized:-4,pathPaymentStrictReceiveNoDestination:-5,pathPaymentStrictReceiveNoTrust:-6,pathPaymentStrictReceiveNotAuthorized:-7,pathPaymentStrictReceiveLineFull:-8,pathPaymentStrictReceiveNoIssuer:-9,pathPaymentStrictReceiveTooFewOffers:-10,pathPaymentStrictReceiveOfferCrossSelf:-11,pathPaymentStrictReceiveOverSendmax:-12}),e.struct("SimplePaymentResult",[["destination",e.lookup("AccountId")],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")]]),e.struct("PathPaymentStrictReceiveResultSuccess",[["offers",e.varArray(e.lookup("ClaimAtom"),2147483647)],["last",e.lookup("SimplePaymentResult")]]),e.union("PathPaymentStrictReceiveResult",{switchOn:e.lookup("PathPaymentStrictReceiveResultCode"),switchName:"code",switches:[["pathPaymentStrictReceiveSuccess","success"],["pathPaymentStrictReceiveMalformed",e.void()],["pathPaymentStrictReceiveUnderfunded",e.void()],["pathPaymentStrictReceiveSrcNoTrust",e.void()],["pathPaymentStrictReceiveSrcNotAuthorized",e.void()],["pathPaymentStrictReceiveNoDestination",e.void()],["pathPaymentStrictReceiveNoTrust",e.void()],["pathPaymentStrictReceiveNotAuthorized",e.void()],["pathPaymentStrictReceiveLineFull",e.void()],["pathPaymentStrictReceiveNoIssuer","noIssuer"],["pathPaymentStrictReceiveTooFewOffers",e.void()],["pathPaymentStrictReceiveOfferCrossSelf",e.void()],["pathPaymentStrictReceiveOverSendmax",e.void()]],arms:{success:e.lookup("PathPaymentStrictReceiveResultSuccess"),noIssuer:e.lookup("Asset")}}),e.enum("PathPaymentStrictSendResultCode",{pathPaymentStrictSendSuccess:0,pathPaymentStrictSendMalformed:-1,pathPaymentStrictSendUnderfunded:-2,pathPaymentStrictSendSrcNoTrust:-3,pathPaymentStrictSendSrcNotAuthorized:-4,pathPaymentStrictSendNoDestination:-5,pathPaymentStrictSendNoTrust:-6,pathPaymentStrictSendNotAuthorized:-7,pathPaymentStrictSendLineFull:-8,pathPaymentStrictSendNoIssuer:-9,pathPaymentStrictSendTooFewOffers:-10,pathPaymentStrictSendOfferCrossSelf:-11,pathPaymentStrictSendUnderDestmin:-12}),e.struct("PathPaymentStrictSendResultSuccess",[["offers",e.varArray(e.lookup("ClaimAtom"),2147483647)],["last",e.lookup("SimplePaymentResult")]]),e.union("PathPaymentStrictSendResult",{switchOn:e.lookup("PathPaymentStrictSendResultCode"),switchName:"code",switches:[["pathPaymentStrictSendSuccess","success"],["pathPaymentStrictSendMalformed",e.void()],["pathPaymentStrictSendUnderfunded",e.void()],["pathPaymentStrictSendSrcNoTrust",e.void()],["pathPaymentStrictSendSrcNotAuthorized",e.void()],["pathPaymentStrictSendNoDestination",e.void()],["pathPaymentStrictSendNoTrust",e.void()],["pathPaymentStrictSendNotAuthorized",e.void()],["pathPaymentStrictSendLineFull",e.void()],["pathPaymentStrictSendNoIssuer","noIssuer"],["pathPaymentStrictSendTooFewOffers",e.void()],["pathPaymentStrictSendOfferCrossSelf",e.void()],["pathPaymentStrictSendUnderDestmin",e.void()]],arms:{success:e.lookup("PathPaymentStrictSendResultSuccess"),noIssuer:e.lookup("Asset")}}),e.enum("ManageSellOfferResultCode",{manageSellOfferSuccess:0,manageSellOfferMalformed:-1,manageSellOfferSellNoTrust:-2,manageSellOfferBuyNoTrust:-3,manageSellOfferSellNotAuthorized:-4,manageSellOfferBuyNotAuthorized:-5,manageSellOfferLineFull:-6,manageSellOfferUnderfunded:-7,manageSellOfferCrossSelf:-8,manageSellOfferSellNoIssuer:-9,manageSellOfferBuyNoIssuer:-10,manageSellOfferNotFound:-11,manageSellOfferLowReserve:-12}),e.enum("ManageOfferEffect",{manageOfferCreated:0,manageOfferUpdated:1,manageOfferDeleted:2}),e.union("ManageOfferSuccessResultOffer",{switchOn:e.lookup("ManageOfferEffect"),switchName:"effect",switches:[["manageOfferCreated","offer"],["manageOfferUpdated","offer"],["manageOfferDeleted",e.void()]],arms:{offer:e.lookup("OfferEntry")}}),e.struct("ManageOfferSuccessResult",[["offersClaimed",e.varArray(e.lookup("ClaimAtom"),2147483647)],["offer",e.lookup("ManageOfferSuccessResultOffer")]]),e.union("ManageSellOfferResult",{switchOn:e.lookup("ManageSellOfferResultCode"),switchName:"code",switches:[["manageSellOfferSuccess","success"],["manageSellOfferMalformed",e.void()],["manageSellOfferSellNoTrust",e.void()],["manageSellOfferBuyNoTrust",e.void()],["manageSellOfferSellNotAuthorized",e.void()],["manageSellOfferBuyNotAuthorized",e.void()],["manageSellOfferLineFull",e.void()],["manageSellOfferUnderfunded",e.void()],["manageSellOfferCrossSelf",e.void()],["manageSellOfferSellNoIssuer",e.void()],["manageSellOfferBuyNoIssuer",e.void()],["manageSellOfferNotFound",e.void()],["manageSellOfferLowReserve",e.void()]],arms:{success:e.lookup("ManageOfferSuccessResult")}}),e.enum("ManageBuyOfferResultCode",{manageBuyOfferSuccess:0,manageBuyOfferMalformed:-1,manageBuyOfferSellNoTrust:-2,manageBuyOfferBuyNoTrust:-3,manageBuyOfferSellNotAuthorized:-4,manageBuyOfferBuyNotAuthorized:-5,manageBuyOfferLineFull:-6,manageBuyOfferUnderfunded:-7,manageBuyOfferCrossSelf:-8,manageBuyOfferSellNoIssuer:-9,manageBuyOfferBuyNoIssuer:-10,manageBuyOfferNotFound:-11,manageBuyOfferLowReserve:-12}),e.union("ManageBuyOfferResult",{switchOn:e.lookup("ManageBuyOfferResultCode"),switchName:"code",switches:[["manageBuyOfferSuccess","success"],["manageBuyOfferMalformed",e.void()],["manageBuyOfferSellNoTrust",e.void()],["manageBuyOfferBuyNoTrust",e.void()],["manageBuyOfferSellNotAuthorized",e.void()],["manageBuyOfferBuyNotAuthorized",e.void()],["manageBuyOfferLineFull",e.void()],["manageBuyOfferUnderfunded",e.void()],["manageBuyOfferCrossSelf",e.void()],["manageBuyOfferSellNoIssuer",e.void()],["manageBuyOfferBuyNoIssuer",e.void()],["manageBuyOfferNotFound",e.void()],["manageBuyOfferLowReserve",e.void()]],arms:{success:e.lookup("ManageOfferSuccessResult")}}),e.enum("SetOptionsResultCode",{setOptionsSuccess:0,setOptionsLowReserve:-1,setOptionsTooManySigners:-2,setOptionsBadFlags:-3,setOptionsInvalidInflation:-4,setOptionsCantChange:-5,setOptionsUnknownFlag:-6,setOptionsThresholdOutOfRange:-7,setOptionsBadSigner:-8,setOptionsInvalidHomeDomain:-9,setOptionsAuthRevocableRequired:-10}),e.union("SetOptionsResult",{switchOn:e.lookup("SetOptionsResultCode"),switchName:"code",switches:[["setOptionsSuccess",e.void()],["setOptionsLowReserve",e.void()],["setOptionsTooManySigners",e.void()],["setOptionsBadFlags",e.void()],["setOptionsInvalidInflation",e.void()],["setOptionsCantChange",e.void()],["setOptionsUnknownFlag",e.void()],["setOptionsThresholdOutOfRange",e.void()],["setOptionsBadSigner",e.void()],["setOptionsInvalidHomeDomain",e.void()],["setOptionsAuthRevocableRequired",e.void()]],arms:{}}),e.enum("ChangeTrustResultCode",{changeTrustSuccess:0,changeTrustMalformed:-1,changeTrustNoIssuer:-2,changeTrustInvalidLimit:-3,changeTrustLowReserve:-4,changeTrustSelfNotAllowed:-5,changeTrustTrustLineMissing:-6,changeTrustCannotDelete:-7,changeTrustNotAuthMaintainLiabilities:-8}),e.union("ChangeTrustResult",{switchOn:e.lookup("ChangeTrustResultCode"),switchName:"code",switches:[["changeTrustSuccess",e.void()],["changeTrustMalformed",e.void()],["changeTrustNoIssuer",e.void()],["changeTrustInvalidLimit",e.void()],["changeTrustLowReserve",e.void()],["changeTrustSelfNotAllowed",e.void()],["changeTrustTrustLineMissing",e.void()],["changeTrustCannotDelete",e.void()],["changeTrustNotAuthMaintainLiabilities",e.void()]],arms:{}}),e.enum("AllowTrustResultCode",{allowTrustSuccess:0,allowTrustMalformed:-1,allowTrustNoTrustLine:-2,allowTrustTrustNotRequired:-3,allowTrustCantRevoke:-4,allowTrustSelfNotAllowed:-5,allowTrustLowReserve:-6}),e.union("AllowTrustResult",{switchOn:e.lookup("AllowTrustResultCode"),switchName:"code",switches:[["allowTrustSuccess",e.void()],["allowTrustMalformed",e.void()],["allowTrustNoTrustLine",e.void()],["allowTrustTrustNotRequired",e.void()],["allowTrustCantRevoke",e.void()],["allowTrustSelfNotAllowed",e.void()],["allowTrustLowReserve",e.void()]],arms:{}}),e.enum("AccountMergeResultCode",{accountMergeSuccess:0,accountMergeMalformed:-1,accountMergeNoAccount:-2,accountMergeImmutableSet:-3,accountMergeHasSubEntries:-4,accountMergeSeqnumTooFar:-5,accountMergeDestFull:-6,accountMergeIsSponsor:-7}),e.union("AccountMergeResult",{switchOn:e.lookup("AccountMergeResultCode"),switchName:"code",switches:[["accountMergeSuccess","sourceAccountBalance"],["accountMergeMalformed",e.void()],["accountMergeNoAccount",e.void()],["accountMergeImmutableSet",e.void()],["accountMergeHasSubEntries",e.void()],["accountMergeSeqnumTooFar",e.void()],["accountMergeDestFull",e.void()],["accountMergeIsSponsor",e.void()]],arms:{sourceAccountBalance:e.lookup("Int64")}}),e.enum("InflationResultCode",{inflationSuccess:0,inflationNotTime:-1}),e.struct("InflationPayout",[["destination",e.lookup("AccountId")],["amount",e.lookup("Int64")]]),e.union("InflationResult",{switchOn:e.lookup("InflationResultCode"),switchName:"code",switches:[["inflationSuccess","payouts"],["inflationNotTime",e.void()]],arms:{payouts:e.varArray(e.lookup("InflationPayout"),2147483647)}}),e.enum("ManageDataResultCode",{manageDataSuccess:0,manageDataNotSupportedYet:-1,manageDataNameNotFound:-2,manageDataLowReserve:-3,manageDataInvalidName:-4}),e.union("ManageDataResult",{switchOn:e.lookup("ManageDataResultCode"),switchName:"code",switches:[["manageDataSuccess",e.void()],["manageDataNotSupportedYet",e.void()],["manageDataNameNotFound",e.void()],["manageDataLowReserve",e.void()],["manageDataInvalidName",e.void()]],arms:{}}),e.enum("BumpSequenceResultCode",{bumpSequenceSuccess:0,bumpSequenceBadSeq:-1}),e.union("BumpSequenceResult",{switchOn:e.lookup("BumpSequenceResultCode"),switchName:"code",switches:[["bumpSequenceSuccess",e.void()],["bumpSequenceBadSeq",e.void()]],arms:{}}),e.enum("CreateClaimableBalanceResultCode",{createClaimableBalanceSuccess:0,createClaimableBalanceMalformed:-1,createClaimableBalanceLowReserve:-2,createClaimableBalanceNoTrust:-3,createClaimableBalanceNotAuthorized:-4,createClaimableBalanceUnderfunded:-5}),e.union("CreateClaimableBalanceResult",{switchOn:e.lookup("CreateClaimableBalanceResultCode"),switchName:"code",switches:[["createClaimableBalanceSuccess","balanceId"],["createClaimableBalanceMalformed",e.void()],["createClaimableBalanceLowReserve",e.void()],["createClaimableBalanceNoTrust",e.void()],["createClaimableBalanceNotAuthorized",e.void()],["createClaimableBalanceUnderfunded",e.void()]],arms:{balanceId:e.lookup("ClaimableBalanceId")}}),e.enum("ClaimClaimableBalanceResultCode",{claimClaimableBalanceSuccess:0,claimClaimableBalanceDoesNotExist:-1,claimClaimableBalanceCannotClaim:-2,claimClaimableBalanceLineFull:-3,claimClaimableBalanceNoTrust:-4,claimClaimableBalanceNotAuthorized:-5}),e.union("ClaimClaimableBalanceResult",{switchOn:e.lookup("ClaimClaimableBalanceResultCode"),switchName:"code",switches:[["claimClaimableBalanceSuccess",e.void()],["claimClaimableBalanceDoesNotExist",e.void()],["claimClaimableBalanceCannotClaim",e.void()],["claimClaimableBalanceLineFull",e.void()],["claimClaimableBalanceNoTrust",e.void()],["claimClaimableBalanceNotAuthorized",e.void()]],arms:{}}),e.enum("BeginSponsoringFutureReservesResultCode",{beginSponsoringFutureReservesSuccess:0,beginSponsoringFutureReservesMalformed:-1,beginSponsoringFutureReservesAlreadySponsored:-2,beginSponsoringFutureReservesRecursive:-3}),e.union("BeginSponsoringFutureReservesResult",{switchOn:e.lookup("BeginSponsoringFutureReservesResultCode"),switchName:"code",switches:[["beginSponsoringFutureReservesSuccess",e.void()],["beginSponsoringFutureReservesMalformed",e.void()],["beginSponsoringFutureReservesAlreadySponsored",e.void()],["beginSponsoringFutureReservesRecursive",e.void()]],arms:{}}),e.enum("EndSponsoringFutureReservesResultCode",{endSponsoringFutureReservesSuccess:0,endSponsoringFutureReservesNotSponsored:-1}),e.union("EndSponsoringFutureReservesResult",{switchOn:e.lookup("EndSponsoringFutureReservesResultCode"),switchName:"code",switches:[["endSponsoringFutureReservesSuccess",e.void()],["endSponsoringFutureReservesNotSponsored",e.void()]],arms:{}}),e.enum("RevokeSponsorshipResultCode",{revokeSponsorshipSuccess:0,revokeSponsorshipDoesNotExist:-1,revokeSponsorshipNotSponsor:-2,revokeSponsorshipLowReserve:-3,revokeSponsorshipOnlyTransferable:-4,revokeSponsorshipMalformed:-5}),e.union("RevokeSponsorshipResult",{switchOn:e.lookup("RevokeSponsorshipResultCode"),switchName:"code",switches:[["revokeSponsorshipSuccess",e.void()],["revokeSponsorshipDoesNotExist",e.void()],["revokeSponsorshipNotSponsor",e.void()],["revokeSponsorshipLowReserve",e.void()],["revokeSponsorshipOnlyTransferable",e.void()],["revokeSponsorshipMalformed",e.void()]],arms:{}}),e.enum("ClawbackResultCode",{clawbackSuccess:0,clawbackMalformed:-1,clawbackNotClawbackEnabled:-2,clawbackNoTrust:-3,clawbackUnderfunded:-4}),e.union("ClawbackResult",{switchOn:e.lookup("ClawbackResultCode"),switchName:"code",switches:[["clawbackSuccess",e.void()],["clawbackMalformed",e.void()],["clawbackNotClawbackEnabled",e.void()],["clawbackNoTrust",e.void()],["clawbackUnderfunded",e.void()]],arms:{}}),e.enum("ClawbackClaimableBalanceResultCode",{clawbackClaimableBalanceSuccess:0,clawbackClaimableBalanceDoesNotExist:-1,clawbackClaimableBalanceNotIssuer:-2,clawbackClaimableBalanceNotClawbackEnabled:-3}),e.union("ClawbackClaimableBalanceResult",{switchOn:e.lookup("ClawbackClaimableBalanceResultCode"),switchName:"code",switches:[["clawbackClaimableBalanceSuccess",e.void()],["clawbackClaimableBalanceDoesNotExist",e.void()],["clawbackClaimableBalanceNotIssuer",e.void()],["clawbackClaimableBalanceNotClawbackEnabled",e.void()]],arms:{}}),e.enum("SetTrustLineFlagsResultCode",{setTrustLineFlagsSuccess:0,setTrustLineFlagsMalformed:-1,setTrustLineFlagsNoTrustLine:-2,setTrustLineFlagsCantRevoke:-3,setTrustLineFlagsInvalidState:-4,setTrustLineFlagsLowReserve:-5}),e.union("SetTrustLineFlagsResult",{switchOn:e.lookup("SetTrustLineFlagsResultCode"),switchName:"code",switches:[["setTrustLineFlagsSuccess",e.void()],["setTrustLineFlagsMalformed",e.void()],["setTrustLineFlagsNoTrustLine",e.void()],["setTrustLineFlagsCantRevoke",e.void()],["setTrustLineFlagsInvalidState",e.void()],["setTrustLineFlagsLowReserve",e.void()]],arms:{}}),e.enum("LiquidityPoolDepositResultCode",{liquidityPoolDepositSuccess:0,liquidityPoolDepositMalformed:-1,liquidityPoolDepositNoTrust:-2,liquidityPoolDepositNotAuthorized:-3,liquidityPoolDepositUnderfunded:-4,liquidityPoolDepositLineFull:-5,liquidityPoolDepositBadPrice:-6,liquidityPoolDepositPoolFull:-7}),e.union("LiquidityPoolDepositResult",{switchOn:e.lookup("LiquidityPoolDepositResultCode"),switchName:"code",switches:[["liquidityPoolDepositSuccess",e.void()],["liquidityPoolDepositMalformed",e.void()],["liquidityPoolDepositNoTrust",e.void()],["liquidityPoolDepositNotAuthorized",e.void()],["liquidityPoolDepositUnderfunded",e.void()],["liquidityPoolDepositLineFull",e.void()],["liquidityPoolDepositBadPrice",e.void()],["liquidityPoolDepositPoolFull",e.void()]],arms:{}}),e.enum("LiquidityPoolWithdrawResultCode",{liquidityPoolWithdrawSuccess:0,liquidityPoolWithdrawMalformed:-1,liquidityPoolWithdrawNoTrust:-2,liquidityPoolWithdrawUnderfunded:-3,liquidityPoolWithdrawLineFull:-4,liquidityPoolWithdrawUnderMinimum:-5}),e.union("LiquidityPoolWithdrawResult",{switchOn:e.lookup("LiquidityPoolWithdrawResultCode"),switchName:"code",switches:[["liquidityPoolWithdrawSuccess",e.void()],["liquidityPoolWithdrawMalformed",e.void()],["liquidityPoolWithdrawNoTrust",e.void()],["liquidityPoolWithdrawUnderfunded",e.void()],["liquidityPoolWithdrawLineFull",e.void()],["liquidityPoolWithdrawUnderMinimum",e.void()]],arms:{}}),e.enum("InvokeHostFunctionResultCode",{invokeHostFunctionSuccess:0,invokeHostFunctionMalformed:-1,invokeHostFunctionTrapped:-2,invokeHostFunctionResourceLimitExceeded:-3,invokeHostFunctionEntryArchived:-4,invokeHostFunctionInsufficientRefundableFee:-5}),e.union("InvokeHostFunctionResult",{switchOn:e.lookup("InvokeHostFunctionResultCode"),switchName:"code",switches:[["invokeHostFunctionSuccess","success"],["invokeHostFunctionMalformed",e.void()],["invokeHostFunctionTrapped",e.void()],["invokeHostFunctionResourceLimitExceeded",e.void()],["invokeHostFunctionEntryArchived",e.void()],["invokeHostFunctionInsufficientRefundableFee",e.void()]],arms:{success:e.lookup("Hash")}}),e.enum("ExtendFootprintTtlResultCode",{extendFootprintTtlSuccess:0,extendFootprintTtlMalformed:-1,extendFootprintTtlResourceLimitExceeded:-2,extendFootprintTtlInsufficientRefundableFee:-3}),e.union("ExtendFootprintTtlResult",{switchOn:e.lookup("ExtendFootprintTtlResultCode"),switchName:"code",switches:[["extendFootprintTtlSuccess",e.void()],["extendFootprintTtlMalformed",e.void()],["extendFootprintTtlResourceLimitExceeded",e.void()],["extendFootprintTtlInsufficientRefundableFee",e.void()]],arms:{}}),e.enum("RestoreFootprintResultCode",{restoreFootprintSuccess:0,restoreFootprintMalformed:-1,restoreFootprintResourceLimitExceeded:-2,restoreFootprintInsufficientRefundableFee:-3}),e.union("RestoreFootprintResult",{switchOn:e.lookup("RestoreFootprintResultCode"),switchName:"code",switches:[["restoreFootprintSuccess",e.void()],["restoreFootprintMalformed",e.void()],["restoreFootprintResourceLimitExceeded",e.void()],["restoreFootprintInsufficientRefundableFee",e.void()]],arms:{}}),e.enum("OperationResultCode",{opInner:0,opBadAuth:-1,opNoAccount:-2,opNotSupported:-3,opTooManySubentries:-4,opExceededWorkLimit:-5,opTooManySponsoring:-6}),e.union("OperationResultTr",{switchOn:e.lookup("OperationType"),switchName:"type",switches:[["createAccount","createAccountResult"],["payment","paymentResult"],["pathPaymentStrictReceive","pathPaymentStrictReceiveResult"],["manageSellOffer","manageSellOfferResult"],["createPassiveSellOffer","createPassiveSellOfferResult"],["setOptions","setOptionsResult"],["changeTrust","changeTrustResult"],["allowTrust","allowTrustResult"],["accountMerge","accountMergeResult"],["inflation","inflationResult"],["manageData","manageDataResult"],["bumpSequence","bumpSeqResult"],["manageBuyOffer","manageBuyOfferResult"],["pathPaymentStrictSend","pathPaymentStrictSendResult"],["createClaimableBalance","createClaimableBalanceResult"],["claimClaimableBalance","claimClaimableBalanceResult"],["beginSponsoringFutureReserves","beginSponsoringFutureReservesResult"],["endSponsoringFutureReserves","endSponsoringFutureReservesResult"],["revokeSponsorship","revokeSponsorshipResult"],["clawback","clawbackResult"],["clawbackClaimableBalance","clawbackClaimableBalanceResult"],["setTrustLineFlags","setTrustLineFlagsResult"],["liquidityPoolDeposit","liquidityPoolDepositResult"],["liquidityPoolWithdraw","liquidityPoolWithdrawResult"],["invokeHostFunction","invokeHostFunctionResult"],["extendFootprintTtl","extendFootprintTtlResult"],["restoreFootprint","restoreFootprintResult"]],arms:{createAccountResult:e.lookup("CreateAccountResult"),paymentResult:e.lookup("PaymentResult"),pathPaymentStrictReceiveResult:e.lookup("PathPaymentStrictReceiveResult"),manageSellOfferResult:e.lookup("ManageSellOfferResult"),createPassiveSellOfferResult:e.lookup("ManageSellOfferResult"),setOptionsResult:e.lookup("SetOptionsResult"),changeTrustResult:e.lookup("ChangeTrustResult"),allowTrustResult:e.lookup("AllowTrustResult"),accountMergeResult:e.lookup("AccountMergeResult"),inflationResult:e.lookup("InflationResult"),manageDataResult:e.lookup("ManageDataResult"),bumpSeqResult:e.lookup("BumpSequenceResult"),manageBuyOfferResult:e.lookup("ManageBuyOfferResult"),pathPaymentStrictSendResult:e.lookup("PathPaymentStrictSendResult"),createClaimableBalanceResult:e.lookup("CreateClaimableBalanceResult"),claimClaimableBalanceResult:e.lookup("ClaimClaimableBalanceResult"),beginSponsoringFutureReservesResult:e.lookup("BeginSponsoringFutureReservesResult"),endSponsoringFutureReservesResult:e.lookup("EndSponsoringFutureReservesResult"),revokeSponsorshipResult:e.lookup("RevokeSponsorshipResult"),clawbackResult:e.lookup("ClawbackResult"),clawbackClaimableBalanceResult:e.lookup("ClawbackClaimableBalanceResult"),setTrustLineFlagsResult:e.lookup("SetTrustLineFlagsResult"),liquidityPoolDepositResult:e.lookup("LiquidityPoolDepositResult"),liquidityPoolWithdrawResult:e.lookup("LiquidityPoolWithdrawResult"),invokeHostFunctionResult:e.lookup("InvokeHostFunctionResult"),extendFootprintTtlResult:e.lookup("ExtendFootprintTtlResult"),restoreFootprintResult:e.lookup("RestoreFootprintResult")}}),e.union("OperationResult",{switchOn:e.lookup("OperationResultCode"),switchName:"code",switches:[["opInner","tr"],["opBadAuth",e.void()],["opNoAccount",e.void()],["opNotSupported",e.void()],["opTooManySubentries",e.void()],["opExceededWorkLimit",e.void()],["opTooManySponsoring",e.void()]],arms:{tr:e.lookup("OperationResultTr")}}),e.enum("TransactionResultCode",{txFeeBumpInnerSuccess:1,txSuccess:0,txFailed:-1,txTooEarly:-2,txTooLate:-3,txMissingOperation:-4,txBadSeq:-5,txBadAuth:-6,txInsufficientBalance:-7,txNoAccount:-8,txInsufficientFee:-9,txBadAuthExtra:-10,txInternalError:-11,txNotSupported:-12,txFeeBumpInnerFailed:-13,txBadSponsorship:-14,txBadMinSeqAgeOrGap:-15,txMalformed:-16,txSorobanInvalid:-17}),e.union("InnerTransactionResultResult",{switchOn:e.lookup("TransactionResultCode"),switchName:"code",switches:[["txSuccess","results"],["txFailed","results"],["txTooEarly",e.void()],["txTooLate",e.void()],["txMissingOperation",e.void()],["txBadSeq",e.void()],["txBadAuth",e.void()],["txInsufficientBalance",e.void()],["txNoAccount",e.void()],["txInsufficientFee",e.void()],["txBadAuthExtra",e.void()],["txInternalError",e.void()],["txNotSupported",e.void()],["txBadSponsorship",e.void()],["txBadMinSeqAgeOrGap",e.void()],["txMalformed",e.void()],["txSorobanInvalid",e.void()]],arms:{results:e.varArray(e.lookup("OperationResult"),2147483647)}}),e.union("InnerTransactionResultExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("InnerTransactionResult",[["feeCharged",e.lookup("Int64")],["result",e.lookup("InnerTransactionResultResult")],["ext",e.lookup("InnerTransactionResultExt")]]),e.struct("InnerTransactionResultPair",[["transactionHash",e.lookup("Hash")],["result",e.lookup("InnerTransactionResult")]]),e.union("TransactionResultResult",{switchOn:e.lookup("TransactionResultCode"),switchName:"code",switches:[["txFeeBumpInnerSuccess","innerResultPair"],["txFeeBumpInnerFailed","innerResultPair"],["txSuccess","results"],["txFailed","results"],["txTooEarly",e.void()],["txTooLate",e.void()],["txMissingOperation",e.void()],["txBadSeq",e.void()],["txBadAuth",e.void()],["txInsufficientBalance",e.void()],["txNoAccount",e.void()],["txInsufficientFee",e.void()],["txBadAuthExtra",e.void()],["txInternalError",e.void()],["txNotSupported",e.void()],["txBadSponsorship",e.void()],["txBadMinSeqAgeOrGap",e.void()],["txMalformed",e.void()],["txSorobanInvalid",e.void()]],arms:{innerResultPair:e.lookup("InnerTransactionResultPair"),results:e.varArray(e.lookup("OperationResult"),2147483647)}}),e.union("TransactionResultExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionResult",[["feeCharged",e.lookup("Int64")],["result",e.lookup("TransactionResultResult")],["ext",e.lookup("TransactionResultExt")]]),e.typedef("Hash",e.opaque(32)),e.typedef("Uint256",e.opaque(32)),e.typedef("Uint32",e.uint()),e.typedef("Int32",e.int()),e.typedef("Uint64",e.uhyper()),e.typedef("Int64",e.hyper()),e.typedef("TimePoint",e.lookup("Uint64")),e.typedef("Duration",e.lookup("Uint64")),e.union("ExtensionPoint",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.enum("CryptoKeyType",{keyTypeEd25519:0,keyTypePreAuthTx:1,keyTypeHashX:2,keyTypeEd25519SignedPayload:3,keyTypeMuxedEd25519:256}),e.enum("PublicKeyType",{publicKeyTypeEd25519:0}),e.enum("SignerKeyType",{signerKeyTypeEd25519:0,signerKeyTypePreAuthTx:1,signerKeyTypeHashX:2,signerKeyTypeEd25519SignedPayload:3}),e.union("PublicKey",{switchOn:e.lookup("PublicKeyType"),switchName:"type",switches:[["publicKeyTypeEd25519","ed25519"]],arms:{ed25519:e.lookup("Uint256")}}),e.struct("SignerKeyEd25519SignedPayload",[["ed25519",e.lookup("Uint256")],["payload",e.varOpaque(64)]]),e.union("SignerKey",{switchOn:e.lookup("SignerKeyType"),switchName:"type",switches:[["signerKeyTypeEd25519","ed25519"],["signerKeyTypePreAuthTx","preAuthTx"],["signerKeyTypeHashX","hashX"],["signerKeyTypeEd25519SignedPayload","ed25519SignedPayload"]],arms:{ed25519:e.lookup("Uint256"),preAuthTx:e.lookup("Uint256"),hashX:e.lookup("Uint256"),ed25519SignedPayload:e.lookup("SignerKeyEd25519SignedPayload")}}),e.typedef("Signature",e.varOpaque(64)),e.typedef("SignatureHint",e.opaque(4)),e.typedef("NodeId",e.lookup("PublicKey")),e.typedef("AccountId",e.lookup("PublicKey")),e.struct("Curve25519Secret",[["key",e.opaque(32)]]),e.struct("Curve25519Public",[["key",e.opaque(32)]]),e.struct("HmacSha256Key",[["key",e.opaque(32)]]),e.struct("HmacSha256Mac",[["mac",e.opaque(32)]]),e.struct("ShortHashSeed",[["seed",e.opaque(16)]]),e.enum("BinaryFuseFilterType",{binaryFuseFilter8Bit:0,binaryFuseFilter16Bit:1,binaryFuseFilter32Bit:2}),e.struct("SerializedBinaryFuseFilter",[["type",e.lookup("BinaryFuseFilterType")],["inputHashSeed",e.lookup("ShortHashSeed")],["filterSeed",e.lookup("ShortHashSeed")],["segmentLength",e.lookup("Uint32")],["segementLengthMask",e.lookup("Uint32")],["segmentCount",e.lookup("Uint32")],["segmentCountLength",e.lookup("Uint32")],["fingerprintLength",e.lookup("Uint32")],["fingerprints",e.varOpaque()]]),e.enum("ScValType",{scvBool:0,scvVoid:1,scvError:2,scvU32:3,scvI32:4,scvU64:5,scvI64:6,scvTimepoint:7,scvDuration:8,scvU128:9,scvI128:10,scvU256:11,scvI256:12,scvBytes:13,scvString:14,scvSymbol:15,scvVec:16,scvMap:17,scvAddress:18,scvContractInstance:19,scvLedgerKeyContractInstance:20,scvLedgerKeyNonce:21}),e.enum("ScErrorType",{sceContract:0,sceWasmVm:1,sceContext:2,sceStorage:3,sceObject:4,sceCrypto:5,sceEvents:6,sceBudget:7,sceValue:8,sceAuth:9}),e.enum("ScErrorCode",{scecArithDomain:0,scecIndexBounds:1,scecInvalidInput:2,scecMissingValue:3,scecExistingValue:4,scecExceededLimit:5,scecInvalidAction:6,scecInternalError:7,scecUnexpectedType:8,scecUnexpectedSize:9}),e.union("ScError",{switchOn:e.lookup("ScErrorType"),switchName:"type",switches:[["sceContract","contractCode"],["sceWasmVm","code"],["sceContext","code"],["sceStorage","code"],["sceObject","code"],["sceCrypto","code"],["sceEvents","code"],["sceBudget","code"],["sceValue","code"],["sceAuth","code"]],arms:{contractCode:e.lookup("Uint32"),code:e.lookup("ScErrorCode")}}),e.struct("UInt128Parts",[["hi",e.lookup("Uint64")],["lo",e.lookup("Uint64")]]),e.struct("Int128Parts",[["hi",e.lookup("Int64")],["lo",e.lookup("Uint64")]]),e.struct("UInt256Parts",[["hiHi",e.lookup("Uint64")],["hiLo",e.lookup("Uint64")],["loHi",e.lookup("Uint64")],["loLo",e.lookup("Uint64")]]),e.struct("Int256Parts",[["hiHi",e.lookup("Int64")],["hiLo",e.lookup("Uint64")],["loHi",e.lookup("Uint64")],["loLo",e.lookup("Uint64")]]),e.enum("ContractExecutableType",{contractExecutableWasm:0,contractExecutableStellarAsset:1}),e.union("ContractExecutable",{switchOn:e.lookup("ContractExecutableType"),switchName:"type",switches:[["contractExecutableWasm","wasmHash"],["contractExecutableStellarAsset",e.void()]],arms:{wasmHash:e.lookup("Hash")}}),e.enum("ScAddressType",{scAddressTypeAccount:0,scAddressTypeContract:1}),e.union("ScAddress",{switchOn:e.lookup("ScAddressType"),switchName:"type",switches:[["scAddressTypeAccount","accountId"],["scAddressTypeContract","contractId"]],arms:{accountId:e.lookup("AccountId"),contractId:e.lookup("Hash")}}),e.const("SCSYMBOL_LIMIT",32),e.typedef("ScVec",e.varArray(e.lookup("ScVal"),2147483647)),e.typedef("ScMap",e.varArray(e.lookup("ScMapEntry"),2147483647)),e.typedef("ScBytes",e.varOpaque()),e.typedef("ScString",e.string()),e.typedef("ScSymbol",e.string(32)),e.struct("ScNonceKey",[["nonce",e.lookup("Int64")]]),e.struct("ScContractInstance",[["executable",e.lookup("ContractExecutable")],["storage",e.option(e.lookup("ScMap"))]]),e.union("ScVal",{switchOn:e.lookup("ScValType"),switchName:"type",switches:[["scvBool","b"],["scvVoid",e.void()],["scvError","error"],["scvU32","u32"],["scvI32","i32"],["scvU64","u64"],["scvI64","i64"],["scvTimepoint","timepoint"],["scvDuration","duration"],["scvU128","u128"],["scvI128","i128"],["scvU256","u256"],["scvI256","i256"],["scvBytes","bytes"],["scvString","str"],["scvSymbol","sym"],["scvVec","vec"],["scvMap","map"],["scvAddress","address"],["scvLedgerKeyContractInstance",e.void()],["scvLedgerKeyNonce","nonceKey"],["scvContractInstance","instance"]],arms:{b:e.bool(),error:e.lookup("ScError"),u32:e.lookup("Uint32"),i32:e.lookup("Int32"),u64:e.lookup("Uint64"),i64:e.lookup("Int64"),timepoint:e.lookup("TimePoint"),duration:e.lookup("Duration"),u128:e.lookup("UInt128Parts"),i128:e.lookup("Int128Parts"),u256:e.lookup("UInt256Parts"),i256:e.lookup("Int256Parts"),bytes:e.lookup("ScBytes"),str:e.lookup("ScString"),sym:e.lookup("ScSymbol"),vec:e.option(e.lookup("ScVec")),map:e.option(e.lookup("ScMap")),address:e.lookup("ScAddress"),nonceKey:e.lookup("ScNonceKey"),instance:e.lookup("ScContractInstance")}}),e.struct("ScMapEntry",[["key",e.lookup("ScVal")],["val",e.lookup("ScVal")]]),e.enum("ScEnvMetaKind",{scEnvMetaKindInterfaceVersion:0}),e.struct("ScEnvMetaEntryInterfaceVersion",[["protocol",e.lookup("Uint32")],["preRelease",e.lookup("Uint32")]]),e.union("ScEnvMetaEntry",{switchOn:e.lookup("ScEnvMetaKind"),switchName:"kind",switches:[["scEnvMetaKindInterfaceVersion","interfaceVersion"]],arms:{interfaceVersion:e.lookup("ScEnvMetaEntryInterfaceVersion")}}),e.struct("ScMetaV0",[["key",e.string()],["val",e.string()]]),e.enum("ScMetaKind",{scMetaV0:0}),e.union("ScMetaEntry",{switchOn:e.lookup("ScMetaKind"),switchName:"kind",switches:[["scMetaV0","v0"]],arms:{v0:e.lookup("ScMetaV0")}}),e.const("SC_SPEC_DOC_LIMIT",1024),e.enum("ScSpecType",{scSpecTypeVal:0,scSpecTypeBool:1,scSpecTypeVoid:2,scSpecTypeError:3,scSpecTypeU32:4,scSpecTypeI32:5,scSpecTypeU64:6,scSpecTypeI64:7,scSpecTypeTimepoint:8,scSpecTypeDuration:9,scSpecTypeU128:10,scSpecTypeI128:11,scSpecTypeU256:12,scSpecTypeI256:13,scSpecTypeBytes:14,scSpecTypeString:16,scSpecTypeSymbol:17,scSpecTypeAddress:19,scSpecTypeOption:1e3,scSpecTypeResult:1001,scSpecTypeVec:1002,scSpecTypeMap:1004,scSpecTypeTuple:1005,scSpecTypeBytesN:1006,scSpecTypeUdt:2e3}),e.struct("ScSpecTypeOption",[["valueType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeResult",[["okType",e.lookup("ScSpecTypeDef")],["errorType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeVec",[["elementType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeMap",[["keyType",e.lookup("ScSpecTypeDef")],["valueType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeTuple",[["valueTypes",e.varArray(e.lookup("ScSpecTypeDef"),12)]]),e.struct("ScSpecTypeBytesN",[["n",e.lookup("Uint32")]]),e.struct("ScSpecTypeUdt",[["name",e.string(60)]]),e.union("ScSpecTypeDef",{switchOn:e.lookup("ScSpecType"),switchName:"type",switches:[["scSpecTypeVal",e.void()],["scSpecTypeBool",e.void()],["scSpecTypeVoid",e.void()],["scSpecTypeError",e.void()],["scSpecTypeU32",e.void()],["scSpecTypeI32",e.void()],["scSpecTypeU64",e.void()],["scSpecTypeI64",e.void()],["scSpecTypeTimepoint",e.void()],["scSpecTypeDuration",e.void()],["scSpecTypeU128",e.void()],["scSpecTypeI128",e.void()],["scSpecTypeU256",e.void()],["scSpecTypeI256",e.void()],["scSpecTypeBytes",e.void()],["scSpecTypeString",e.void()],["scSpecTypeSymbol",e.void()],["scSpecTypeAddress",e.void()],["scSpecTypeOption","option"],["scSpecTypeResult","result"],["scSpecTypeVec","vec"],["scSpecTypeMap","map"],["scSpecTypeTuple","tuple"],["scSpecTypeBytesN","bytesN"],["scSpecTypeUdt","udt"]],arms:{option:e.lookup("ScSpecTypeOption"),result:e.lookup("ScSpecTypeResult"),vec:e.lookup("ScSpecTypeVec"),map:e.lookup("ScSpecTypeMap"),tuple:e.lookup("ScSpecTypeTuple"),bytesN:e.lookup("ScSpecTypeBytesN"),udt:e.lookup("ScSpecTypeUdt")}}),e.struct("ScSpecUdtStructFieldV0",[["doc",e.string(t)],["name",e.string(30)],["type",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecUdtStructV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["fields",e.varArray(e.lookup("ScSpecUdtStructFieldV0"),40)]]),e.struct("ScSpecUdtUnionCaseVoidV0",[["doc",e.string(t)],["name",e.string(60)]]),e.struct("ScSpecUdtUnionCaseTupleV0",[["doc",e.string(t)],["name",e.string(60)],["type",e.varArray(e.lookup("ScSpecTypeDef"),12)]]),e.enum("ScSpecUdtUnionCaseV0Kind",{scSpecUdtUnionCaseVoidV0:0,scSpecUdtUnionCaseTupleV0:1}),e.union("ScSpecUdtUnionCaseV0",{switchOn:e.lookup("ScSpecUdtUnionCaseV0Kind"),switchName:"kind",switches:[["scSpecUdtUnionCaseVoidV0","voidCase"],["scSpecUdtUnionCaseTupleV0","tupleCase"]],arms:{voidCase:e.lookup("ScSpecUdtUnionCaseVoidV0"),tupleCase:e.lookup("ScSpecUdtUnionCaseTupleV0")}}),e.struct("ScSpecUdtUnionV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtUnionCaseV0"),50)]]),e.struct("ScSpecUdtEnumCaseV0",[["doc",e.string(t)],["name",e.string(60)],["value",e.lookup("Uint32")]]),e.struct("ScSpecUdtEnumV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtEnumCaseV0"),50)]]),e.struct("ScSpecUdtErrorEnumCaseV0",[["doc",e.string(t)],["name",e.string(60)],["value",e.lookup("Uint32")]]),e.struct("ScSpecUdtErrorEnumV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtErrorEnumCaseV0"),50)]]),e.struct("ScSpecFunctionInputV0",[["doc",e.string(t)],["name",e.string(30)],["type",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecFunctionV0",[["doc",e.string(t)],["name",e.lookup("ScSymbol")],["inputs",e.varArray(e.lookup("ScSpecFunctionInputV0"),10)],["outputs",e.varArray(e.lookup("ScSpecTypeDef"),1)]]),e.enum("ScSpecEntryKind",{scSpecEntryFunctionV0:0,scSpecEntryUdtStructV0:1,scSpecEntryUdtUnionV0:2,scSpecEntryUdtEnumV0:3,scSpecEntryUdtErrorEnumV0:4}),e.union("ScSpecEntry",{switchOn:e.lookup("ScSpecEntryKind"),switchName:"kind",switches:[["scSpecEntryFunctionV0","functionV0"],["scSpecEntryUdtStructV0","udtStructV0"],["scSpecEntryUdtUnionV0","udtUnionV0"],["scSpecEntryUdtEnumV0","udtEnumV0"],["scSpecEntryUdtErrorEnumV0","udtErrorEnumV0"]],arms:{functionV0:e.lookup("ScSpecFunctionV0"),udtStructV0:e.lookup("ScSpecUdtStructV0"),udtUnionV0:e.lookup("ScSpecUdtUnionV0"),udtEnumV0:e.lookup("ScSpecUdtEnumV0"),udtErrorEnumV0:e.lookup("ScSpecUdtErrorEnumV0")}}),e.struct("ConfigSettingContractExecutionLanesV0",[["ledgerMaxTxCount",e.lookup("Uint32")]]),e.struct("ConfigSettingContractComputeV0",[["ledgerMaxInstructions",e.lookup("Int64")],["txMaxInstructions",e.lookup("Int64")],["feeRatePerInstructionsIncrement",e.lookup("Int64")],["txMemoryLimit",e.lookup("Uint32")]]),e.struct("ConfigSettingContractLedgerCostV0",[["ledgerMaxReadLedgerEntries",e.lookup("Uint32")],["ledgerMaxReadBytes",e.lookup("Uint32")],["ledgerMaxWriteLedgerEntries",e.lookup("Uint32")],["ledgerMaxWriteBytes",e.lookup("Uint32")],["txMaxReadLedgerEntries",e.lookup("Uint32")],["txMaxReadBytes",e.lookup("Uint32")],["txMaxWriteLedgerEntries",e.lookup("Uint32")],["txMaxWriteBytes",e.lookup("Uint32")],["feeReadLedgerEntry",e.lookup("Int64")],["feeWriteLedgerEntry",e.lookup("Int64")],["feeRead1Kb",e.lookup("Int64")],["bucketListTargetSizeBytes",e.lookup("Int64")],["writeFee1KbBucketListLow",e.lookup("Int64")],["writeFee1KbBucketListHigh",e.lookup("Int64")],["bucketListWriteFeeGrowthFactor",e.lookup("Uint32")]]),e.struct("ConfigSettingContractHistoricalDataV0",[["feeHistorical1Kb",e.lookup("Int64")]]),e.struct("ConfigSettingContractEventsV0",[["txMaxContractEventsSizeBytes",e.lookup("Uint32")],["feeContractEvents1Kb",e.lookup("Int64")]]),e.struct("ConfigSettingContractBandwidthV0",[["ledgerMaxTxsSizeBytes",e.lookup("Uint32")],["txMaxSizeBytes",e.lookup("Uint32")],["feeTxSize1Kb",e.lookup("Int64")]]),e.enum("ContractCostType",{wasmInsnExec:0,memAlloc:1,memCpy:2,memCmp:3,dispatchHostFunction:4,visitObject:5,valSer:6,valDeser:7,computeSha256Hash:8,computeEd25519PubKey:9,verifyEd25519Sig:10,vmInstantiation:11,vmCachedInstantiation:12,invokeVmFunction:13,computeKeccak256Hash:14,decodeEcdsaCurve256Sig:15,recoverEcdsaSecp256k1Key:16,int256AddSub:17,int256Mul:18,int256Div:19,int256Pow:20,int256Shift:21,chaCha20DrawBytes:22,parseWasmInstructions:23,parseWasmFunctions:24,parseWasmGlobals:25,parseWasmTableEntries:26,parseWasmTypes:27,parseWasmDataSegments:28,parseWasmElemSegments:29,parseWasmImports:30,parseWasmExports:31,parseWasmDataSegmentBytes:32,instantiateWasmInstructions:33,instantiateWasmFunctions:34,instantiateWasmGlobals:35,instantiateWasmTableEntries:36,instantiateWasmTypes:37,instantiateWasmDataSegments:38,instantiateWasmElemSegments:39,instantiateWasmImports:40,instantiateWasmExports:41,instantiateWasmDataSegmentBytes:42,sec1DecodePointUncompressed:43,verifyEcdsaSecp256r1Sig:44,bls12381EncodeFp:45,bls12381DecodeFp:46,bls12381G1CheckPointOnCurve:47,bls12381G1CheckPointInSubgroup:48,bls12381G2CheckPointOnCurve:49,bls12381G2CheckPointInSubgroup:50,bls12381G1ProjectiveToAffine:51,bls12381G2ProjectiveToAffine:52,bls12381G1Add:53,bls12381G1Mul:54,bls12381G1Msm:55,bls12381MapFpToG1:56,bls12381HashToG1:57,bls12381G2Add:58,bls12381G2Mul:59,bls12381G2Msm:60,bls12381MapFp2ToG2:61,bls12381HashToG2:62,bls12381Pairing:63,bls12381FrFromU256:64,bls12381FrToU256:65,bls12381FrAddSub:66,bls12381FrMul:67,bls12381FrPow:68,bls12381FrInv:69}),e.struct("ContractCostParamEntry",[["ext",e.lookup("ExtensionPoint")],["constTerm",e.lookup("Int64")],["linearTerm",e.lookup("Int64")]]),e.struct("StateArchivalSettings",[["maxEntryTtl",e.lookup("Uint32")],["minTemporaryTtl",e.lookup("Uint32")],["minPersistentTtl",e.lookup("Uint32")],["persistentRentRateDenominator",e.lookup("Int64")],["tempRentRateDenominator",e.lookup("Int64")],["maxEntriesToArchive",e.lookup("Uint32")],["bucketListSizeWindowSampleSize",e.lookup("Uint32")],["bucketListWindowSamplePeriod",e.lookup("Uint32")],["evictionScanSize",e.lookup("Uint32")],["startingEvictionScanLevel",e.lookup("Uint32")]]),e.struct("EvictionIterator",[["bucketListLevel",e.lookup("Uint32")],["isCurrBucket",e.bool()],["bucketFileOffset",e.lookup("Uint64")]]),e.const("CONTRACT_COST_COUNT_LIMIT",1024),e.typedef("ContractCostParams",e.varArray(e.lookup("ContractCostParamEntry"),e.lookup("CONTRACT_COST_COUNT_LIMIT"))),e.enum("ConfigSettingId",{configSettingContractMaxSizeBytes:0,configSettingContractComputeV0:1,configSettingContractLedgerCostV0:2,configSettingContractHistoricalDataV0:3,configSettingContractEventsV0:4,configSettingContractBandwidthV0:5,configSettingContractCostParamsCpuInstructions:6,configSettingContractCostParamsMemoryBytes:7,configSettingContractDataKeySizeBytes:8,configSettingContractDataEntrySizeBytes:9,configSettingStateArchival:10,configSettingContractExecutionLanes:11,configSettingBucketlistSizeWindow:12,configSettingEvictionIterator:13}),e.union("ConfigSettingEntry",{switchOn:e.lookup("ConfigSettingId"),switchName:"configSettingId",switches:[["configSettingContractMaxSizeBytes","contractMaxSizeBytes"],["configSettingContractComputeV0","contractCompute"],["configSettingContractLedgerCostV0","contractLedgerCost"],["configSettingContractHistoricalDataV0","contractHistoricalData"],["configSettingContractEventsV0","contractEvents"],["configSettingContractBandwidthV0","contractBandwidth"],["configSettingContractCostParamsCpuInstructions","contractCostParamsCpuInsns"],["configSettingContractCostParamsMemoryBytes","contractCostParamsMemBytes"],["configSettingContractDataKeySizeBytes","contractDataKeySizeBytes"],["configSettingContractDataEntrySizeBytes","contractDataEntrySizeBytes"],["configSettingStateArchival","stateArchivalSettings"],["configSettingContractExecutionLanes","contractExecutionLanes"],["configSettingBucketlistSizeWindow","bucketListSizeWindow"],["configSettingEvictionIterator","evictionIterator"]],arms:{contractMaxSizeBytes:e.lookup("Uint32"),contractCompute:e.lookup("ConfigSettingContractComputeV0"),contractLedgerCost:e.lookup("ConfigSettingContractLedgerCostV0"),contractHistoricalData:e.lookup("ConfigSettingContractHistoricalDataV0"),contractEvents:e.lookup("ConfigSettingContractEventsV0"),contractBandwidth:e.lookup("ConfigSettingContractBandwidthV0"),contractCostParamsCpuInsns:e.lookup("ContractCostParams"),contractCostParamsMemBytes:e.lookup("ContractCostParams"),contractDataKeySizeBytes:e.lookup("Uint32"),contractDataEntrySizeBytes:e.lookup("Uint32"),stateArchivalSettings:e.lookup("StateArchivalSettings"),contractExecutionLanes:e.lookup("ConfigSettingContractExecutionLanesV0"),bucketListSizeWindow:e.varArray(e.lookup("Uint64"),2147483647),evictionIterator:e.lookup("EvictionIterator")}})}));t.default=i},5578:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.LiquidityPoolFeeV18=void 0,t.getLiquidityPoolId=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("constant_product"!==e)throw new Error("liquidityPoolType is invalid");var r=t.assetA,o=t.assetB,c=t.fee;if(!(r&&r instanceof a.Asset))throw new Error("assetA is invalid");if(!(o&&o instanceof a.Asset))throw new Error("assetB is invalid");if(!c||c!==u)throw new Error("fee is invalid");if(-1!==a.Asset.compare(r,o))throw new Error("Assets are not in lexicographic order");var l=i.default.LiquidityPoolType.liquidityPoolConstantProduct().toXDR(),f=new i.default.LiquidityPoolConstantProductParameters({assetA:r.toXDRObject(),assetB:o.toXDRObject(),fee:c}).toXDR(),p=n.concat([l,f]);return(0,s.hash)(p)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(1764),s=r(9152);var u=t.LiquidityPoolFeeV18=30},9152:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hash=function(e){var t=new n.sha256;return t.update(e,"utf8"),t.digest()};var n=r(2802)},356:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={xdr:!0,cereal:!0,hash:!0,sign:!0,verify:!0,FastSigning:!0,getLiquidityPoolId:!0,LiquidityPoolFeeV18:!0,Keypair:!0,UnsignedHyper:!0,Hyper:!0,TransactionBase:!0,Transaction:!0,FeeBumpTransaction:!0,TransactionBuilder:!0,TimeoutInfinite:!0,BASE_FEE:!0,Asset:!0,LiquidityPoolAsset:!0,LiquidityPoolId:!0,Operation:!0,AuthRequiredFlag:!0,AuthRevocableFlag:!0,AuthImmutableFlag:!0,AuthClawbackEnabledFlag:!0,Account:!0,MuxedAccount:!0,Claimant:!0,Networks:!0,StrKey:!0,SignerKey:!0,Soroban:!0,decodeAddressToMuxedAccount:!0,encodeMuxedAccountToAddress:!0,extractBaseAddress:!0,encodeMuxedAccount:!0,Contract:!0,Address:!0};Object.defineProperty(t,"Account",{enumerable:!0,get:function(){return w.Account}}),Object.defineProperty(t,"Address",{enumerable:!0,get:function(){return P.Address}}),Object.defineProperty(t,"Asset",{enumerable:!0,get:function(){return y.Asset}}),Object.defineProperty(t,"AuthClawbackEnabledFlag",{enumerable:!0,get:function(){return g.AuthClawbackEnabledFlag}}),Object.defineProperty(t,"AuthImmutableFlag",{enumerable:!0,get:function(){return g.AuthImmutableFlag}}),Object.defineProperty(t,"AuthRequiredFlag",{enumerable:!0,get:function(){return g.AuthRequiredFlag}}),Object.defineProperty(t,"AuthRevocableFlag",{enumerable:!0,get:function(){return g.AuthRevocableFlag}}),Object.defineProperty(t,"BASE_FEE",{enumerable:!0,get:function(){return h.BASE_FEE}}),Object.defineProperty(t,"Claimant",{enumerable:!0,get:function(){return _.Claimant}}),Object.defineProperty(t,"Contract",{enumerable:!0,get:function(){return A.Contract}}),Object.defineProperty(t,"FastSigning",{enumerable:!0,get:function(){return s.FastSigning}}),Object.defineProperty(t,"FeeBumpTransaction",{enumerable:!0,get:function(){return d.FeeBumpTransaction}}),Object.defineProperty(t,"Hyper",{enumerable:!0,get:function(){return l.Hyper}}),Object.defineProperty(t,"Keypair",{enumerable:!0,get:function(){return c.Keypair}}),Object.defineProperty(t,"LiquidityPoolAsset",{enumerable:!0,get:function(){return m.LiquidityPoolAsset}}),Object.defineProperty(t,"LiquidityPoolFeeV18",{enumerable:!0,get:function(){return u.LiquidityPoolFeeV18}}),Object.defineProperty(t,"LiquidityPoolId",{enumerable:!0,get:function(){return v.LiquidityPoolId}}),Object.defineProperty(t,"MuxedAccount",{enumerable:!0,get:function(){return S.MuxedAccount}}),Object.defineProperty(t,"Networks",{enumerable:!0,get:function(){return E.Networks}}),Object.defineProperty(t,"Operation",{enumerable:!0,get:function(){return g.Operation}}),Object.defineProperty(t,"SignerKey",{enumerable:!0,get:function(){return T.SignerKey}}),Object.defineProperty(t,"Soroban",{enumerable:!0,get:function(){return O.Soroban}}),Object.defineProperty(t,"StrKey",{enumerable:!0,get:function(){return k.StrKey}}),Object.defineProperty(t,"TimeoutInfinite",{enumerable:!0,get:function(){return h.TimeoutInfinite}}),Object.defineProperty(t,"Transaction",{enumerable:!0,get:function(){return p.Transaction}}),Object.defineProperty(t,"TransactionBase",{enumerable:!0,get:function(){return f.TransactionBase}}),Object.defineProperty(t,"TransactionBuilder",{enumerable:!0,get:function(){return h.TransactionBuilder}}),Object.defineProperty(t,"UnsignedHyper",{enumerable:!0,get:function(){return l.UnsignedHyper}}),Object.defineProperty(t,"cereal",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(t,"decodeAddressToMuxedAccount",{enumerable:!0,get:function(){return x.decodeAddressToMuxedAccount}}),t.default=void 0,Object.defineProperty(t,"encodeMuxedAccount",{enumerable:!0,get:function(){return x.encodeMuxedAccount}}),Object.defineProperty(t,"encodeMuxedAccountToAddress",{enumerable:!0,get:function(){return x.encodeMuxedAccountToAddress}}),Object.defineProperty(t,"extractBaseAddress",{enumerable:!0,get:function(){return x.extractBaseAddress}}),Object.defineProperty(t,"getLiquidityPoolId",{enumerable:!0,get:function(){return u.getLiquidityPoolId}}),Object.defineProperty(t,"hash",{enumerable:!0,get:function(){return a.hash}}),Object.defineProperty(t,"sign",{enumerable:!0,get:function(){return s.sign}}),Object.defineProperty(t,"verify",{enumerable:!0,get:function(){return s.verify}}),Object.defineProperty(t,"xdr",{enumerable:!0,get:function(){return o.default}});var o=N(r(1918)),i=N(r(3335)),a=r(9152),s=r(15),u=r(5578),c=r(6691),l=r(3740),f=r(3758),p=r(380),d=r(9260),h=r(6396),y=r(1764),m=r(2262),v=r(9353),g=r(7237),b=r(4172);Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===b[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return b[e]}}))}));var w=r(2135),S=r(2243),_=r(1387),E=r(6202),k=r(7120),T=r(225),O=r(4062),x=r(6160),A=r(7452),P=r(1180),R=r(8549);Object.keys(R).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===R[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return R[e]}}))}));var j=r(7177);Object.keys(j).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===j[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return j[e]}}))}));var I=r(3919);Object.keys(I).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===I[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return I[e]}}))}));var C=r(4842);Object.keys(C).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===C[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return C[e]}}))}));var L=r(5328);Object.keys(L).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===L[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return L[e]}}))}));var B=r(3564);function N(e){return e&&e.__esModule?e:{default:e}}Object.keys(B).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===B[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return B[e]}}))}));t.default=e.exports},3564:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildInvocationTree=function e(t){var r=t.function(),a={},c=r.value();switch(r.switch().value){case 0:a.type="execute",a.args={source:o.Address.fromScAddress(c.contractAddress()).toString(),function:c.functionName(),args:c.args().map((function(e){return(0,i.scValToNative)(e)}))};break;case 1:case 2:var l=2===r.switch().value;a.type="create",a.args={};var f=[c.executable(),c.contractIdPreimage()],p=f[0],d=f[1];if(!!p.switch().value!=!!d.switch().value)throw new Error("creation function appears invalid: ".concat(JSON.stringify(c)," (should be wasm+address or token+asset)"));switch(p.switch().value){case 0:var h=d.fromAddress();a.args.type="wasm",a.args.wasm=function(e){for(var t=1;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(3740),o={XdrWriter:n.XdrWriter,XdrReader:n.XdrReader};t.default=o},6691:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.Keypair=void 0;var o=c(r(4940)),i=r(15),a=r(7120),s=r(9152),u=c(r(1918));function c(e){return e&&e.__esModule?e:{default:e}}function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LiquidityPoolAsset=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(1764),a=r(5578);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function c(e){for(var t=1;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LiquidityPoolId=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n};function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.MemoText=t.MemoReturn=t.MemoNone=t.MemoID=t.MemoHash=t.Memo=void 0;var o=r(3740),i=s(r(1242)),a=s(r(1918));function s(e){return e&&e.__esModule?e:{default:e}}function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:null;switch(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._type=t,this._value=r,this._type){case f:break;case p:e._validateIdValue(r);break;case d:e._validateTextValue(r);break;case h:case y:e._validateHashValue(r),"string"==typeof r&&(this._value=n.from(r,"hex"));break;default:throw new Error("Invalid memo type")}}return t=e,s=[{key:"_validateIdValue",value:function(e){var t,r=new Error("Expects a int64 as a string. Got ".concat(e));if("string"!=typeof e)throw r;try{t=new i.default(e)}catch(e){throw r}if(!t.isFinite())throw r;if(t.isNaN())throw r}},{key:"_validateTextValue",value:function(e){if(!a.default.Memo.armTypeForArm("text").isValid(e))throw new Error("Expects string, array or buffer, max 28 bytes")}},{key:"_validateHashValue",value:function(e){var t,r=new Error("Expects a 32 byte hash value or hex encoded string. Got ".concat(e));if(null==e)throw r;if("string"==typeof e){if(!/^[0-9A-Fa-f]{64}$/g.test(e))throw r;t=n.from(e,"hex")}else{if(!n.isBuffer(e))throw r;t=n.from(e)}if(!t.length||32!==t.length)throw r}},{key:"none",value:function(){return new e(f)}},{key:"text",value:function(t){return new e(d,t)}},{key:"id",value:function(t){return new e(p,t)}},{key:"hash",value:function(t){return new e(h,t)}},{key:"return",value:function(t){return new e(y,t)}},{key:"fromXDRObject",value:function(t){switch(t.arm()){case"id":return e.id(t.value().toString());case"text":return e.text(t.value());case"hash":return e.hash(t.value());case"retHash":return e.return(t.value())}if(void 0===t.value())return e.none();throw new Error("Unknown type")}}],(r=[{key:"type",get:function(){return this._type},set:function(e){throw new Error("Memo is immutable")}},{key:"value",get:function(){switch(this._type){case f:return null;case p:case d:return this._value;case h:case y:return n.from(this._value);default:throw new Error("Invalid memo type")}},set:function(e){throw new Error("Memo is immutable")}},{key:"toXDRObject",value:function(){switch(this._type){case f:return a.default.Memo.memoNone();case p:return a.default.Memo.memoId(o.UnsignedHyper.fromString(this._value));case d:return a.default.Memo.memoText(this._value);case h:return a.default.Memo.memoHash(this._value);case y:return a.default.Memo.memoReturn(this._value);default:return null}}}])&&c(t.prototype,r),s&&c(t,s),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,s}()},2243:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MuxedAccount=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(2135),a=r(7120),s=r(6160);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Networks=void 0;t.Networks={PUBLIC:"Public Global Stellar Network ; September 2015",TESTNET:"Test SDF Network ; September 2015",FUTURENET:"Test SDF Future Network ; October 2022",SANDBOX:"Local Sandbox Stellar Network ; September 2022",STANDALONE:"Standalone Network ; February 2017"}},8549:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Int128",{enumerable:!0,get:function(){return a.Int128}}),Object.defineProperty(t,"Int256",{enumerable:!0,get:function(){return s.Int256}}),Object.defineProperty(t,"ScInt",{enumerable:!0,get:function(){return u.ScInt}}),Object.defineProperty(t,"Uint128",{enumerable:!0,get:function(){return o.Uint128}}),Object.defineProperty(t,"Uint256",{enumerable:!0,get:function(){return i.Uint256}}),Object.defineProperty(t,"XdrLargeInt",{enumerable:!0,get:function(){return n.XdrLargeInt}}),t.scValToBigInt=function(e){var t=n.XdrLargeInt.getType(e.switch().name);switch(e.switch().name){case"scvU32":case"scvI32":return BigInt(e.value());case"scvU64":case"scvI64":return new n.XdrLargeInt(t,e.value()).toBigInt();case"scvU128":case"scvI128":return new n.XdrLargeInt(t,[e.value().lo(),e.value().hi()]).toBigInt();case"scvU256":case"scvI256":return new n.XdrLargeInt(t,[e.value().loLo(),e.value().loHi(),e.value().hiLo(),e.value().hiHi()]).toBigInt();default:throw TypeError("expected integer type, got ".concat(e.switch()))}};var n=r(7429),o=r(6272),i=r(8672),a=r(5487),s=r(4063),u=r(3317)},5487:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Int128=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Int256=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.ScInt=void 0;var o=r(7429);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Uint128=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Uint256=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.XdrLargeInt=void 0;var n,o=r(3740),i=r(6272),a=r(8672),s=r(5487),u=r(4063),c=(n=r(1918))&&n.__esModule?n:{default:n};function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){for(var r=0;rNumber.MAX_SAFE_INTEGER||e>64n),r=BigInt.asUintN(64,e);return c.default.ScVal.scvI128(new c.default.Int128Parts({hi:new c.default.Int64(t),lo:new c.default.Uint64(r)}))}},{key:"toU128",value:function(){this._sizeCheck(128);var e=this.int.toBigInt();return c.default.ScVal.scvU128(new c.default.UInt128Parts({hi:new c.default.Uint64(BigInt.asUintN(64,e>>64n)),lo:new c.default.Uint64(BigInt.asUintN(64,e))}))}},{key:"toI256",value:function(){var e=this.int.toBigInt(),t=BigInt.asIntN(64,e>>192n),r=BigInt.asUintN(64,e>>128n),n=BigInt.asUintN(64,e>>64n),o=BigInt.asUintN(64,e);return c.default.ScVal.scvI256(new c.default.Int256Parts({hiHi:new c.default.Int64(t),hiLo:new c.default.Uint64(r),loHi:new c.default.Uint64(n),loLo:new c.default.Uint64(o)}))}},{key:"toU256",value:function(){var e=this.int.toBigInt(),t=BigInt.asUintN(64,e>>192n),r=BigInt.asUintN(64,e>>128n),n=BigInt.asUintN(64,e>>64n),o=BigInt.asUintN(64,e);return c.default.ScVal.scvU256(new c.default.UInt256Parts({hiHi:new c.default.Uint64(t),hiLo:new c.default.Uint64(r),loHi:new c.default.Uint64(n),loLo:new c.default.Uint64(o)}))}},{key:"toScVal",value:function(){switch(this.type){case"i64":return this.toI64();case"i128":return this.toI128();case"i256":return this.toI256();case"u64":return this.toU64();case"u128":return this.toU128();case"u256":return this.toU256();default:throw TypeError("invalid type: ".concat(this.type))}}},{key:"valueOf",value:function(){return this.int.valueOf()}},{key:"toString",value:function(){return this.int.toString()}},{key:"toJSON",value:function(){return{value:this.toBigInt().toString(),type:this.type}}},{key:"_sizeCheck",value:function(e){if(this.int.size>e)throw RangeError("value too large for ".concat(e," bits (").concat(this.type,")"))}}],[{key:"isType",value:function(e){switch(e){case"i64":case"i128":case"i256":case"u64":case"u128":case"u256":return!0;default:return!1}}},{key:"getType",value:function(e){return e.slice(3).toLowerCase()}}])}()},7237:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.AuthRevocableFlag=t.AuthRequiredFlag=t.AuthImmutableFlag=t.AuthClawbackEnabledFlag=void 0;var n=r(3740),o=m(r(1242)),i=r(645),a=r(4151),s=r(1764),u=r(2262),c=r(1387),l=r(7120),f=r(9353),p=m(r(1918)),d=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=v(e)&&"function"!=typeof e)return{default:e};var r=y(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in e)if("default"!==i&&{}.hasOwnProperty.call(e,i)){var a=o?Object.getOwnPropertyDescriptor(e,i):null;a&&(a.get||a.set)?Object.defineProperty(n,i,a):n[i]=e[i]}return n.default=e,r&&r.set(e,n),n}(r(7511)),h=r(6160);function y(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(y=function(e){return e?r:t})(e)}function m(e){return e&&e.__esModule?e:{default:e}}function v(e){return v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},v(e)}function g(e,t){for(var r=0;r1&&void 0!==arguments[1]&&arguments[1];if("string"!=typeof e)return!1;try{t=new o.default(e)}catch(e){return!1}return!(!r&&t.isZero()||t.isNegative()||t.times(w).gt(new o.default("9223372036854775807").toString())||t.decimalPlaces()>7||t.isNaN()||!t.isFinite())}},{key:"constructAmountRequirementsError",value:function(e){return"".concat(e," argument must be of type String, represent a positive number and have at most 7 digits after the decimal")}},{key:"_checkUnsignedIntValue",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;if(void 0!==t)switch("string"==typeof t&&(t=parseFloat(t)),!0){case"number"!=typeof t||!Number.isFinite(t)||t%1!=0:throw new Error("".concat(e," value is invalid"));case t<0:throw new Error("".concat(e," value must be unsigned"));case!r||r&&r(t,e):return t;default:throw new Error("".concat(e," value is invalid"))}}},{key:"_toXDRAmount",value:function(e){var t=new o.default(e).times(w);return n.Hyper.fromString(t.toString())}},{key:"_fromXDRAmount",value:function(e){return new o.default(e).div(w).toFixed(7)}},{key:"_fromXDRPrice",value:function(e){return new o.default(e.n()).div(new o.default(e.d())).toString()}},{key:"_toXDRPrice",value:function(e){var t;if(e.n&&e.d)t=new p.default.Price(e);else{var r=(0,a.best_r)(e);t=new p.default.Price({n:parseInt(r[0],10),d:parseInt(r[1],10)})}if(t.n()<0||t.d()<0)throw new Error("price must be positive");return t}}],(t=null)&&g(e.prototype,t),r&&g(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,r}());function _(e){return l.StrKey.encodeEd25519PublicKey(e.ed25519())}S.accountMerge=d.accountMerge,S.allowTrust=d.allowTrust,S.bumpSequence=d.bumpSequence,S.changeTrust=d.changeTrust,S.createAccount=d.createAccount,S.createClaimableBalance=d.createClaimableBalance,S.claimClaimableBalance=d.claimClaimableBalance,S.clawbackClaimableBalance=d.clawbackClaimableBalance,S.createPassiveSellOffer=d.createPassiveSellOffer,S.inflation=d.inflation,S.manageData=d.manageData,S.manageSellOffer=d.manageSellOffer,S.manageBuyOffer=d.manageBuyOffer,S.pathPaymentStrictReceive=d.pathPaymentStrictReceive,S.pathPaymentStrictSend=d.pathPaymentStrictSend,S.payment=d.payment,S.setOptions=d.setOptions,S.beginSponsoringFutureReserves=d.beginSponsoringFutureReserves,S.endSponsoringFutureReserves=d.endSponsoringFutureReserves,S.revokeAccountSponsorship=d.revokeAccountSponsorship,S.revokeTrustlineSponsorship=d.revokeTrustlineSponsorship,S.revokeOfferSponsorship=d.revokeOfferSponsorship,S.revokeDataSponsorship=d.revokeDataSponsorship,S.revokeClaimableBalanceSponsorship=d.revokeClaimableBalanceSponsorship,S.revokeLiquidityPoolSponsorship=d.revokeLiquidityPoolSponsorship,S.revokeSignerSponsorship=d.revokeSignerSponsorship,S.clawback=d.clawback,S.setTrustLineFlags=d.setTrustLineFlags,S.liquidityPoolDeposit=d.liquidityPoolDeposit,S.liquidityPoolWithdraw=d.liquidityPoolWithdraw,S.invokeHostFunction=d.invokeHostFunction,S.extendFootprintTtl=d.extendFootprintTtl,S.restoreFootprint=d.restoreFootprint,S.createStellarAssetContract=d.createStellarAssetContract,S.invokeContractFunction=d.invokeContractFunction,S.createCustomContract=d.createCustomContract,S.uploadContractWasm=d.uploadContractWasm},4295:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.accountMerge=function(e){var t={};try{t.body=o.default.OperationBody.accountMerge((0,i.decodeAddressToMuxedAccount)(e.destination))}catch(e){throw new Error("destination is invalid")}return this.setSourceAccount(t,e),new o.default.Operation(t)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},3683:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allowTrust=function(e){if(!a.StrKey.isValidEd25519PublicKey(e.trustor))throw new Error("trustor is invalid");var t={};if(t.trustor=i.Keypair.fromPublicKey(e.trustor).xdrAccountId(),e.assetCode.length<=4){var r=e.assetCode.padEnd(4,"\0");t.asset=o.default.AssetCode.assetTypeCreditAlphanum4(r)}else{if(!(e.assetCode.length<=12))throw new Error("Asset code must be 12 characters at max.");var n=e.assetCode.padEnd(12,"\0");t.asset=o.default.AssetCode.assetTypeCreditAlphanum12(n)}"boolean"==typeof e.authorize?e.authorize?t.authorize=o.default.TrustLineFlags.authorizedFlag().value:t.authorize=0:t.authorize=e.authorize;var s=new o.default.AllowTrustOp(t),u={};return u.body=o.default.OperationBody.allowTrust(s),this.setSourceAccount(u,e),new o.default.Operation(u)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691),a=r(7120)},7505:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.beginSponsoringFutureReserves=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!i.StrKey.isValidEd25519PublicKey(e.sponsoredId))throw new Error("sponsoredId is invalid");var t=new o.default.BeginSponsoringFutureReservesOp({sponsoredId:a.Keypair.fromPublicKey(e.sponsoredId).xdrAccountId()}),r={};return r.body=o.default.OperationBody.beginSponsoringFutureReserves(t),this.setSourceAccount(r,e),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(7120),a=r(6691)},6183:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bumpSequence=function(e){var t={};if("string"!=typeof e.bumpTo)throw new Error("bumpTo must be a string");try{new o.default(e.bumpTo)}catch(e){throw new Error("bumpTo must be a stringified number")}t.bumpTo=n.Hyper.fromString(e.bumpTo);var r=new i.default.BumpSequenceOp(t),a={};return a.body=i.default.OperationBody.bumpSequence(r),this.setSourceAccount(a,e),new i.default.Operation(a)};var n=r(3740),o=a(r(1242)),i=a(r(1918));function a(e){return e&&e.__esModule?e:{default:e}}},2810:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.changeTrust=function(e){var t={};if(e.asset instanceof a.Asset)t.line=e.asset.toChangeTrustXDRObject();else{if(!(e.asset instanceof s.LiquidityPoolAsset))throw new TypeError("asset must be Asset or LiquidityPoolAsset");t.line=e.asset.toXDRObject()}if(void 0!==e.limit&&!this.isValidAmount(e.limit,!0))throw new TypeError(this.constructAmountRequirementsError("limit"));e.limit?t.limit=this._toXDRAmount(e.limit):t.limit=n.Hyper.fromString(new o.default(c).toString());e.source&&(t.source=e.source.masterKeypair);var r=new i.default.ChangeTrustOp(t),u={};return u.body=i.default.OperationBody.changeTrust(r),this.setSourceAccount(u,e),new i.default.Operation(u)};var n=r(3740),o=u(r(1242)),i=u(r(1918)),a=r(1764),s=r(2262);function u(e){return e&&e.__esModule?e:{default:e}}var c="9223372036854775807"},7239:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.claimClaimableBalance=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};i(e.balanceId);var t={};t.balanceId=o.default.ClaimableBalanceId.fromXDR(e.balanceId,"hex");var r=new o.default.ClaimClaimableBalanceOp(t),n={};return n.body=o.default.OperationBody.claimClaimableBalance(r),this.setSourceAccount(n,e),new o.default.Operation(n)},t.validateClaimableBalanceId=i;var n,o=(n=r(1918))&&n.__esModule?n:{default:n};function i(e){if("string"!=typeof e||72!==e.length)throw new Error("must provide a valid claimable balance id")}},7651:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clawback=function(e){var t={};if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));t.amount=this._toXDRAmount(e.amount),t.asset=e.asset.toXDRObject();try{t.from=(0,i.decodeAddressToMuxedAccount)(e.from)}catch(e){throw new Error("from address is invalid")}var r={body:o.default.OperationBody.clawback(new o.default.ClawbackOp(t))};return this.setSourceAccount(r,e),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},2203:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clawbackClaimableBalance=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(0,i.validateClaimableBalanceId)(e.balanceId);var t={balanceId:o.default.ClaimableBalanceId.fromXDR(e.balanceId,"hex")},r={body:o.default.OperationBody.clawbackClaimableBalance(new o.default.ClawbackClaimableBalanceOp(t))};return this.setSourceAccount(r,e),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(7239)},2115:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createAccount=function(e){if(!a.StrKey.isValidEd25519PublicKey(e.destination))throw new Error("destination is invalid");if(!this.isValidAmount(e.startingBalance,!0))throw new TypeError(this.constructAmountRequirementsError("startingBalance"));var t={};t.destination=i.Keypair.fromPublicKey(e.destination).xdrAccountId(),t.startingBalance=this._toXDRAmount(e.startingBalance);var r=new o.default.CreateAccountOp(t),n={};return n.body=o.default.OperationBody.createAccount(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691),a=r(7120)},4831:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createClaimableBalance=function(e){if(!(e.asset instanceof i.Asset))throw new Error("must provide an asset for create claimable balance operation");if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(!Array.isArray(e.claimants)||0===e.claimants.length)throw new Error("must provide at least one claimant");var t={};t.asset=e.asset.toXDRObject(),t.amount=this._toXDRAmount(e.amount),t.claimants=Object.values(e.claimants).map((function(e){return e.toXDRObject()}));var r=new o.default.CreateClaimableBalanceOp(t),n={};return n.body=o.default.OperationBody.createClaimableBalance(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(1764)},9073:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createPassiveSellOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price);var r=new o.default.CreatePassiveSellOfferOp(t),n={};return n.body=o.default.OperationBody.createPassiveSellOffer(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},721:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endSponsoringFutureReserves=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};return t.body=o.default.OperationBody.endSponsoringFutureReserves(),this.setSourceAccount(t,e),new o.default.Operation(t)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},8752:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extendFootprintTtl=function(e){var t;if((null!==(t=e.extendTo)&&void 0!==t?t:-1)<=0)throw new RangeError("extendTo has to be positive");var r=new o.default.ExtendFootprintTtlOp({ext:new o.default.ExtensionPoint(0),extendTo:e.extendTo}),n={body:o.default.OperationBody.extendFootprintTtl(r)};return this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},7511:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"accountMerge",{enumerable:!0,get:function(){return i.accountMerge}}),Object.defineProperty(t,"allowTrust",{enumerable:!0,get:function(){return a.allowTrust}}),Object.defineProperty(t,"beginSponsoringFutureReserves",{enumerable:!0,get:function(){return w.beginSponsoringFutureReserves}}),Object.defineProperty(t,"bumpSequence",{enumerable:!0,get:function(){return s.bumpSequence}}),Object.defineProperty(t,"changeTrust",{enumerable:!0,get:function(){return u.changeTrust}}),Object.defineProperty(t,"claimClaimableBalance",{enumerable:!0,get:function(){return f.claimClaimableBalance}}),Object.defineProperty(t,"clawback",{enumerable:!0,get:function(){return E.clawback}}),Object.defineProperty(t,"clawbackClaimableBalance",{enumerable:!0,get:function(){return p.clawbackClaimableBalance}}),Object.defineProperty(t,"createAccount",{enumerable:!0,get:function(){return c.createAccount}}),Object.defineProperty(t,"createClaimableBalance",{enumerable:!0,get:function(){return l.createClaimableBalance}}),Object.defineProperty(t,"createCustomContract",{enumerable:!0,get:function(){return x.createCustomContract}}),Object.defineProperty(t,"createPassiveSellOffer",{enumerable:!0,get:function(){return o.createPassiveSellOffer}}),Object.defineProperty(t,"createStellarAssetContract",{enumerable:!0,get:function(){return x.createStellarAssetContract}}),Object.defineProperty(t,"endSponsoringFutureReserves",{enumerable:!0,get:function(){return S.endSponsoringFutureReserves}}),Object.defineProperty(t,"extendFootprintTtl",{enumerable:!0,get:function(){return A.extendFootprintTtl}}),Object.defineProperty(t,"inflation",{enumerable:!0,get:function(){return d.inflation}}),Object.defineProperty(t,"invokeContractFunction",{enumerable:!0,get:function(){return x.invokeContractFunction}}),Object.defineProperty(t,"invokeHostFunction",{enumerable:!0,get:function(){return x.invokeHostFunction}}),Object.defineProperty(t,"liquidityPoolDeposit",{enumerable:!0,get:function(){return T.liquidityPoolDeposit}}),Object.defineProperty(t,"liquidityPoolWithdraw",{enumerable:!0,get:function(){return O.liquidityPoolWithdraw}}),Object.defineProperty(t,"manageBuyOffer",{enumerable:!0,get:function(){return y.manageBuyOffer}}),Object.defineProperty(t,"manageData",{enumerable:!0,get:function(){return h.manageData}}),Object.defineProperty(t,"manageSellOffer",{enumerable:!0,get:function(){return n.manageSellOffer}}),Object.defineProperty(t,"pathPaymentStrictReceive",{enumerable:!0,get:function(){return m.pathPaymentStrictReceive}}),Object.defineProperty(t,"pathPaymentStrictSend",{enumerable:!0,get:function(){return v.pathPaymentStrictSend}}),Object.defineProperty(t,"payment",{enumerable:!0,get:function(){return g.payment}}),Object.defineProperty(t,"restoreFootprint",{enumerable:!0,get:function(){return P.restoreFootprint}}),Object.defineProperty(t,"revokeAccountSponsorship",{enumerable:!0,get:function(){return _.revokeAccountSponsorship}}),Object.defineProperty(t,"revokeClaimableBalanceSponsorship",{enumerable:!0,get:function(){return _.revokeClaimableBalanceSponsorship}}),Object.defineProperty(t,"revokeDataSponsorship",{enumerable:!0,get:function(){return _.revokeDataSponsorship}}),Object.defineProperty(t,"revokeLiquidityPoolSponsorship",{enumerable:!0,get:function(){return _.revokeLiquidityPoolSponsorship}}),Object.defineProperty(t,"revokeOfferSponsorship",{enumerable:!0,get:function(){return _.revokeOfferSponsorship}}),Object.defineProperty(t,"revokeSignerSponsorship",{enumerable:!0,get:function(){return _.revokeSignerSponsorship}}),Object.defineProperty(t,"revokeTrustlineSponsorship",{enumerable:!0,get:function(){return _.revokeTrustlineSponsorship}}),Object.defineProperty(t,"setOptions",{enumerable:!0,get:function(){return b.setOptions}}),Object.defineProperty(t,"setTrustLineFlags",{enumerable:!0,get:function(){return k.setTrustLineFlags}}),Object.defineProperty(t,"uploadContractWasm",{enumerable:!0,get:function(){return x.uploadContractWasm}});var n=r(862),o=r(9073),i=r(4295),a=r(3683),s=r(6183),u=r(2810),c=r(2115),l=r(4831),f=r(7239),p=r(2203),d=r(7421),h=r(1411),y=r(1922),m=r(2075),v=r(3874),g=r(3533),b=r(2018),w=r(7505),S=r(721),_=r(7790),E=r(7651),k=r(1804),T=r(9845),O=r(4737),x=r(4403),A=r(8752),P=r(149)},7421:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inflation=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};return t.body=o.default.OperationBody.inflation(),this.setSourceAccount(t,e),new o.default.Operation(t)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},4403:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.createCustomContract=function(e){var t,r=n.from(e.salt||a.Keypair.random().xdrPublicKey().value());if(!e.wasmHash||32!==e.wasmHash.length)throw new TypeError("expected hash(contract WASM) in 'opts.wasmHash', got ".concat(e.wasmHash));if(32!==r.length)throw new TypeError("expected 32-byte salt in 'opts.salt', got ".concat(e.wasmHash));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeCreateContractV2(new i.default.CreateContractArgsV2({executable:i.default.ContractExecutable.contractExecutableWasm(n.from(e.wasmHash)),contractIdPreimage:i.default.ContractIdPreimage.contractIdPreimageFromAddress(new i.default.ContractIdPreimageFromAddress({address:e.address.toScAddress(),salt:r})),constructorArgs:null!==(t=e.constructorArgs)&&void 0!==t?t:[]}))})},t.createStellarAssetContract=function(e){var t=e.asset;if("string"==typeof t){var r=t.split(":"),n=(l=2,function(e){if(Array.isArray(e))return e}(s=r)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(s,l)||function(e,t){if(e){if("string"==typeof e)return c(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?c(e,t):void 0}}(s,l)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),o=n[0],a=n[1];t=new u.Asset(o,a)}var s,l;if(!(t instanceof u.Asset))throw new TypeError("expected Asset in 'opts.asset', got ".concat(t));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeCreateContract(new i.default.CreateContractArgs({executable:i.default.ContractExecutable.contractExecutableStellarAsset(),contractIdPreimage:i.default.ContractIdPreimage.contractIdPreimageFromAsset(t.toXDRObject())}))})},t.invokeContractFunction=function(e){var t=new s.Address(e.contract);if("contract"!==t._type)throw new TypeError("expected contract strkey instance, got ".concat(t));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeInvokeContract(new i.default.InvokeContractArgs({contractAddress:t.toScAddress(),functionName:e.function,args:e.args}))})},t.invokeHostFunction=function(e){if(!e.func)throw new TypeError("host function invocation ('func') required (got ".concat(JSON.stringify(e),")"));var t=new i.default.InvokeHostFunctionOp({hostFunction:e.func,auth:e.auth||[]}),r={body:i.default.OperationBody.invokeHostFunction(t)};return this.setSourceAccount(r,e),new i.default.Operation(r)},t.uploadContractWasm=function(e){return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeUploadContractWasm(n.from(e.wasm))})};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(6691),s=r(1180),u=r(1764);function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.liquidityPoolDeposit=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.liquidityPoolId,r=e.maxAmountA,n=e.maxAmountB,i=e.minPrice,a=e.maxPrice,s={};if(!t)throw new TypeError("liquidityPoolId argument is required");if(s.liquidityPoolId=o.default.PoolId.fromXDR(t,"hex"),!this.isValidAmount(r,!0))throw new TypeError(this.constructAmountRequirementsError("maxAmountA"));if(s.maxAmountA=this._toXDRAmount(r),!this.isValidAmount(n,!0))throw new TypeError(this.constructAmountRequirementsError("maxAmountB"));if(s.maxAmountB=this._toXDRAmount(n),void 0===i)throw new TypeError("minPrice argument is required");if(s.minPrice=this._toXDRPrice(i),void 0===a)throw new TypeError("maxPrice argument is required");s.maxPrice=this._toXDRPrice(a);var u=new o.default.LiquidityPoolDepositOp(s),c={body:o.default.OperationBody.liquidityPoolDeposit(u)};return this.setSourceAccount(c,e),new o.default.Operation(c)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},4737:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.liquidityPoolWithdraw=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};if(!e.liquidityPoolId)throw new TypeError("liquidityPoolId argument is required");if(t.liquidityPoolId=o.default.PoolId.fromXDR(e.liquidityPoolId,"hex"),!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),!this.isValidAmount(e.minAmountA,!0))throw new TypeError(this.constructAmountRequirementsError("minAmountA"));if(t.minAmountA=this._toXDRAmount(e.minAmountA),!this.isValidAmount(e.minAmountB,!0))throw new TypeError(this.constructAmountRequirementsError("minAmountB"));t.minAmountB=this._toXDRAmount(e.minAmountB);var r=new o.default.LiquidityPoolWithdrawOp(t),n={body:o.default.OperationBody.liquidityPoolWithdraw(r)};return this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},1922:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.manageBuyOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.buyAmount,!0))throw new TypeError(this.constructAmountRequirementsError("buyAmount"));if(t.buyAmount=this._toXDRAmount(e.buyAmount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price),void 0!==e.offerId?e.offerId=e.offerId.toString():e.offerId="0";t.offerId=o.Hyper.fromString(e.offerId);var r=new i.default.ManageBuyOfferOp(t),n={};return n.body=i.default.OperationBody.manageBuyOffer(r),this.setSourceAccount(n,e),new i.default.Operation(n)};var n,o=r(3740),i=(n=r(1918))&&n.__esModule?n:{default:n}},1411:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.manageData=function(e){var t={};if(!("string"==typeof e.name&&e.name.length<=64))throw new Error("name must be a string, up to 64 characters");if(t.dataName=e.name,"string"!=typeof e.value&&!n.isBuffer(e.value)&&null!==e.value)throw new Error("value must be a string, Buffer or null");"string"==typeof e.value?t.dataValue=n.from(e.value):t.dataValue=e.value;if(null!==t.dataValue&&t.dataValue.length>64)throw new Error("value cannot be longer that 64 bytes");var r=new i.default.ManageDataOp(t),o={};return o.body=i.default.OperationBody.manageData(r),this.setSourceAccount(o,e),new i.default.Operation(o)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o}},862:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.manageSellOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.amount,!0))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price),void 0!==e.offerId?e.offerId=e.offerId.toString():e.offerId="0";t.offerId=o.Hyper.fromString(e.offerId);var r=new i.default.ManageSellOfferOp(t),n={};return n.body=i.default.OperationBody.manageSellOffer(r),this.setSourceAccount(n,e),new i.default.Operation(n)};var n,o=r(3740),i=(n=r(1918))&&n.__esModule?n:{default:n}},2075:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathPaymentStrictReceive=function(e){switch(!0){case!e.sendAsset:throw new Error("Must specify a send asset");case!this.isValidAmount(e.sendMax):throw new TypeError(this.constructAmountRequirementsError("sendMax"));case!e.destAsset:throw new Error("Must provide a destAsset for a payment operation");case!this.isValidAmount(e.destAmount):throw new TypeError(this.constructAmountRequirementsError("destAmount"))}var t={};t.sendAsset=e.sendAsset.toXDRObject(),t.sendMax=this._toXDRAmount(e.sendMax);try{t.destination=(0,i.decodeAddressToMuxedAccount)(e.destination)}catch(e){throw new Error("destination is invalid")}t.destAsset=e.destAsset.toXDRObject(),t.destAmount=this._toXDRAmount(e.destAmount);var r=e.path?e.path:[];t.path=r.map((function(e){return e.toXDRObject()}));var n=new o.default.PathPaymentStrictReceiveOp(t),a={};return a.body=o.default.OperationBody.pathPaymentStrictReceive(n),this.setSourceAccount(a,e),new o.default.Operation(a)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},3874:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathPaymentStrictSend=function(e){switch(!0){case!e.sendAsset:throw new Error("Must specify a send asset");case!this.isValidAmount(e.sendAmount):throw new TypeError(this.constructAmountRequirementsError("sendAmount"));case!e.destAsset:throw new Error("Must provide a destAsset for a payment operation");case!this.isValidAmount(e.destMin):throw new TypeError(this.constructAmountRequirementsError("destMin"))}var t={};t.sendAsset=e.sendAsset.toXDRObject(),t.sendAmount=this._toXDRAmount(e.sendAmount);try{t.destination=(0,i.decodeAddressToMuxedAccount)(e.destination)}catch(e){throw new Error("destination is invalid")}t.destAsset=e.destAsset.toXDRObject(),t.destMin=this._toXDRAmount(e.destMin);var r=e.path?e.path:[];t.path=r.map((function(e){return e.toXDRObject()}));var n=new o.default.PathPaymentStrictSendOp(t),a={};return a.body=o.default.OperationBody.pathPaymentStrictSend(n),this.setSourceAccount(a,e),new o.default.Operation(a)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},3533:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.payment=function(e){if(!e.asset)throw new Error("Must provide an asset for a payment operation");if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));var t={};try{t.destination=(0,i.decodeAddressToMuxedAccount)(e.destination)}catch(e){throw new Error("destination is invalid")}t.asset=e.asset.toXDRObject(),t.amount=this._toXDRAmount(e.amount);var r=new o.default.PaymentOp(t),n={};return n.body=o.default.OperationBody.payment(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},149:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restoreFootprint=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=new o.default.RestoreFootprintOp({ext:new o.default.ExtensionPoint(0)}),r={body:o.default.OperationBody.restoreFootprint(t)};return this.setSourceAccount(r,null!=e?e:{}),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},7790:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.revokeAccountSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");var t=i.default.LedgerKey.account(new i.default.LedgerKeyAccount({accountId:s.Keypair.fromPublicKey(e.account).xdrAccountId()})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeClaimableBalanceSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if("string"!=typeof e.balanceId)throw new Error("balanceId is invalid");var t=i.default.LedgerKey.claimableBalance(new i.default.LedgerKeyClaimableBalance({balanceId:i.default.ClaimableBalanceId.fromXDR(e.balanceId,"hex")})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeDataSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");if("string"!=typeof e.name||e.name.length>64)throw new Error("name must be a string, up to 64 characters");var t=i.default.LedgerKey.data(new i.default.LedgerKeyData({accountId:s.Keypair.fromPublicKey(e.account).xdrAccountId(),dataName:e.name})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeLiquidityPoolSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if("string"!=typeof e.liquidityPoolId)throw new Error("liquidityPoolId is invalid");var t=i.default.LedgerKey.liquidityPool(new i.default.LedgerKeyLiquidityPool({liquidityPoolId:i.default.PoolId.fromXDR(e.liquidityPoolId,"hex")})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={body:i.default.OperationBody.revokeSponsorship(r)};return this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeOfferSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(e.seller))throw new Error("seller is invalid");if("string"!=typeof e.offerId)throw new Error("offerId is invalid");var t=i.default.LedgerKey.offer(new i.default.LedgerKeyOffer({sellerId:s.Keypair.fromPublicKey(e.seller).xdrAccountId(),offerId:i.default.Int64.fromString(e.offerId)})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeSignerSponsorship=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(t.account))throw new Error("account is invalid");if(t.signer.ed25519PublicKey){if(!a.StrKey.isValidEd25519PublicKey(t.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");var r=a.StrKey.decodeEd25519PublicKey(t.signer.ed25519PublicKey);e=new i.default.SignerKey.signerKeyTypeEd25519(r)}else if(t.signer.preAuthTx){var o;if(o="string"==typeof t.signer.preAuthTx?n.from(t.signer.preAuthTx,"hex"):t.signer.preAuthTx,!n.isBuffer(o)||32!==o.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");e=new i.default.SignerKey.signerKeyTypePreAuthTx(o)}else{if(!t.signer.sha256Hash)throw new Error("signer is invalid");var u;if(u="string"==typeof t.signer.sha256Hash?n.from(t.signer.sha256Hash,"hex"):t.signer.sha256Hash,!n.isBuffer(u)||32!==u.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");e=new i.default.SignerKey.signerKeyTypeHashX(u)}var c=new i.default.RevokeSponsorshipOpSigner({accountId:s.Keypair.fromPublicKey(t.account).xdrAccountId(),signerKey:e}),l=i.default.RevokeSponsorshipOp.revokeSponsorshipSigner(c),f={};return f.body=i.default.OperationBody.revokeSponsorship(l),this.setSourceAccount(f,t),new i.default.Operation(f)},t.revokeTrustlineSponsorship=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(t.account))throw new Error("account is invalid");if(t.asset instanceof u.Asset)e=t.asset.toTrustLineXDRObject();else{if(!(t.asset instanceof c.LiquidityPoolId))throw new TypeError("asset must be an Asset or LiquidityPoolId");e=t.asset.toXDRObject()}var r=i.default.LedgerKey.trustline(new i.default.LedgerKeyTrustLine({accountId:s.Keypair.fromPublicKey(t.account).xdrAccountId(),asset:e})),n=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(r),o={};return o.body=i.default.OperationBody.revokeSponsorship(n),this.setSourceAccount(o,t),new i.default.Operation(o)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(7120),s=r(6691),u=r(1764),c=r(9353)},2018:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.setOptions=function(e){var t={};if(e.inflationDest){if(!s.StrKey.isValidEd25519PublicKey(e.inflationDest))throw new Error("inflationDest is invalid");t.inflationDest=a.Keypair.fromPublicKey(e.inflationDest).xdrAccountId()}if(t.clearFlags=this._checkUnsignedIntValue("clearFlags",e.clearFlags),t.setFlags=this._checkUnsignedIntValue("setFlags",e.setFlags),t.masterWeight=this._checkUnsignedIntValue("masterWeight",e.masterWeight,u),t.lowThreshold=this._checkUnsignedIntValue("lowThreshold",e.lowThreshold,u),t.medThreshold=this._checkUnsignedIntValue("medThreshold",e.medThreshold,u),t.highThreshold=this._checkUnsignedIntValue("highThreshold",e.highThreshold,u),void 0!==e.homeDomain&&"string"!=typeof e.homeDomain)throw new TypeError("homeDomain argument must be of type String");if(t.homeDomain=e.homeDomain,e.signer){var r,o=this._checkUnsignedIntValue("signer.weight",e.signer.weight,u),c=0;if(e.signer.ed25519PublicKey){if(!s.StrKey.isValidEd25519PublicKey(e.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");var l=s.StrKey.decodeEd25519PublicKey(e.signer.ed25519PublicKey);r=new i.default.SignerKey.signerKeyTypeEd25519(l),c+=1}if(e.signer.preAuthTx){if("string"==typeof e.signer.preAuthTx&&(e.signer.preAuthTx=n.from(e.signer.preAuthTx,"hex")),!n.isBuffer(e.signer.preAuthTx)||32!==e.signer.preAuthTx.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");r=new i.default.SignerKey.signerKeyTypePreAuthTx(e.signer.preAuthTx),c+=1}if(e.signer.sha256Hash){if("string"==typeof e.signer.sha256Hash&&(e.signer.sha256Hash=n.from(e.signer.sha256Hash,"hex")),!n.isBuffer(e.signer.sha256Hash)||32!==e.signer.sha256Hash.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");r=new i.default.SignerKey.signerKeyTypeHashX(e.signer.sha256Hash),c+=1}if(e.signer.ed25519SignedPayload){if(!s.StrKey.isValidSignedPayload(e.signer.ed25519SignedPayload))throw new Error("signer.ed25519SignedPayload is invalid.");var f=s.StrKey.decodeSignedPayload(e.signer.ed25519SignedPayload),p=i.default.SignerKeyEd25519SignedPayload.fromXDR(f);r=i.default.SignerKey.signerKeyTypeEd25519SignedPayload(p),c+=1}if(1!==c)throw new Error("Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx.");t.signer=new i.default.Signer({key:r,weight:o})}var d=new i.default.SetOptionsOp(t),h={};return h.body=i.default.OperationBody.setOptions(d),this.setSourceAccount(h,e),new i.default.Operation(h)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(6691),s=r(7120);function u(e,t){if(e>=0&&e<=255)return!0;throw new Error("".concat(t," value must be between 0 and 255"))}},1804:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setTrustLineFlags=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};if("object"!==a(e.flags)||0===Object.keys(e.flags).length)throw new Error("opts.flags must be a map of boolean flags to modify");var r={authorized:o.default.TrustLineFlags.authorizedFlag(),authorizedToMaintainLiabilities:o.default.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),clawbackEnabled:o.default.TrustLineFlags.trustlineClawbackEnabledFlag()},n=0,s=0;Object.keys(e.flags).forEach((function(t){if(!Object.prototype.hasOwnProperty.call(r,t))throw new Error("unsupported flag name specified: ".concat(t));var o=e.flags[t],i=r[t].value;!0===o?s|=i:!1===o&&(n|=i)})),t.trustor=i.Keypair.fromPublicKey(e.trustor).xdrAccountId(),t.asset=e.asset.toXDRObject(),t.clearFlags=n,t.setFlags=s;var u={body:o.default.OperationBody.setTrustLineFlags(new o.default.SetTrustLineFlagsOp(t))};return this.setSourceAccount(u,e),new o.default.Operation(u)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}},7177:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.nativeToScVal=function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(f(t)){case"object":var o,l,p;if(null===t)return i.default.ScVal.scvVoid();if(t instanceof i.default.ScVal)return t;if(t instanceof a.Address)return t.toScVal();if(t instanceof s.Contract)return t.address().toScVal();if(t instanceof Uint8Array||n.isBuffer(t)){var d,h=Uint8Array.from(t);switch(null!==(d=null==r?void 0:r.type)&&void 0!==d?d:"bytes"){case"bytes":return i.default.ScVal.scvBytes(h);case"symbol":return i.default.ScVal.scvSymbol(h);case"string":return i.default.ScVal.scvString(h);default:throw new TypeError("invalid type (".concat(r.type,") specified for bytes-like value"))}}if(Array.isArray(t)){if(t.length>0&&t.some((function(e){return f(e)!==f(t[0])})))throw new TypeError("array values (".concat(t,") must have the same type (types: ").concat(t.map((function(e){return f(e)})).join(","),")"));return i.default.ScVal.scvVec(t.map((function(t){return e(t,r)})))}if("Object"!==(null!==(o=null===(l=t.constructor)||void 0===l?void 0:l.name)&&void 0!==o?o:""))throw new TypeError("cannot interpret ".concat(null===(p=t.constructor)||void 0===p?void 0:p.name," value as ScVal (").concat(JSON.stringify(t),")"));return i.default.ScVal.scvMap(Object.entries(t).sort((function(e,t){var r=c(e,1)[0],n=c(t,1)[0];return r.localeCompare(n)})).map((function(t){var n,o,a=c(t,2),s=a[0],u=a[1],l=c(null!==(n=(null!==(o=null==r?void 0:r.type)&&void 0!==o?o:{})[s])&&void 0!==n?n:[null,null],2),f=l[0],p=l[1],d=f?{type:f}:{},h=p?{type:p}:{};return new i.default.ScMapEntry({key:e(s,d),val:e(u,h)})})));case"number":case"bigint":switch(null==r?void 0:r.type){case"u32":return i.default.ScVal.scvU32(t);case"i32":return i.default.ScVal.scvI32(t)}return new u.ScInt(t,{type:null==r?void 0:r.type}).toScVal();case"string":var y,m=null!==(y=null==r?void 0:r.type)&&void 0!==y?y:"string";switch(m){case"string":return i.default.ScVal.scvString(t);case"symbol":return i.default.ScVal.scvSymbol(t);case"address":return new a.Address(t).toScVal();case"u32":return i.default.ScVal.scvU32(parseInt(t,10));case"i32":return i.default.ScVal.scvI32(parseInt(t,10));default:if(u.XdrLargeInt.isType(m))return new u.XdrLargeInt(m,t).toScVal();throw new TypeError("invalid type (".concat(r.type,") specified for string value"))}case"boolean":return i.default.ScVal.scvBool(t);case"undefined":return i.default.ScVal.scvVoid();case"function":return e(t());default:throw new TypeError("failed to convert typeof ".concat(f(t)," (").concat(t,")"))}},t.scValToNative=function e(t){var r,o;switch(t.switch().value){case i.default.ScValType.scvVoid().value:return null;case i.default.ScValType.scvU64().value:case i.default.ScValType.scvI64().value:return t.value().toBigInt();case i.default.ScValType.scvU128().value:case i.default.ScValType.scvI128().value:case i.default.ScValType.scvU256().value:case i.default.ScValType.scvI256().value:return(0,u.scValToBigInt)(t);case i.default.ScValType.scvVec().value:return(null!==(r=t.vec())&&void 0!==r?r:[]).map(e);case i.default.ScValType.scvAddress().value:return a.Address.fromScVal(t).toString();case i.default.ScValType.scvMap().value:return Object.fromEntries((null!==(o=t.map())&&void 0!==o?o:[]).map((function(t){return[e(t.key()),e(t.val())]})));case i.default.ScValType.scvBool().value:case i.default.ScValType.scvU32().value:case i.default.ScValType.scvI32().value:case i.default.ScValType.scvBytes().value:return t.value();case i.default.ScValType.scvSymbol().value:case i.default.ScValType.scvString().value:var s=t.value();if(n.isBuffer(s)||ArrayBuffer.isView(s))try{return(new TextDecoder).decode(s)}catch(e){return new Uint8Array(s.buffer)}return s;case i.default.ScValType.scvTimepoint().value:case i.default.ScValType.scvDuration().value:return new i.default.Uint64(t.value()).toBigInt();case i.default.ScValType.scvError().value:if(t.error().switch().value===i.default.ScErrorType.sceContract().value)return{type:"contract",code:t.error().contractCode()};var c=t.error();return{type:"system",code:c.code().value,value:c.code().name};default:return t.value()}};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(1180),s=r(7452),u=r(8549);function c(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return l(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?l(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignerKey=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(7120);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function s(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.FastSigning=void 0,t.generate=function(e){return o.generate(e)},t.sign=function(e,t){return o.sign(e,t)},t.verify=function(e,t,r){return o.verify(e,t,r)};var o={};t.FastSigning="undefined"==typeof window?function(){var e;try{e=r(Object(function(){var e=new Error("Cannot find module 'sodium-native'");throw e.code="MODULE_NOT_FOUND",e}()))}catch(e){return i()}return Object.keys(e).length?(o.generate=function(t){var r=n.alloc(e.crypto_sign_PUBLICKEYBYTES),o=n.alloc(e.crypto_sign_SECRETKEYBYTES);return e.crypto_sign_seed_keypair(r,o,t),r},o.sign=function(t,r){t=n.from(t);var o=n.alloc(e.crypto_sign_BYTES);return e.crypto_sign_detached(o,t,r),o},o.verify=function(t,r,o){t=n.from(t);try{return e.crypto_sign_verify_detached(r,t,o)}catch(e){return!1}},!0):i()}():i();function i(){var e=r(4940);return o.generate=function(t){var r=new Uint8Array(t),o=e.sign.keyPair.fromSeed(r);return n.from(o.publicKey)},o.sign=function(t,r){t=n.from(t),t=new Uint8Array(t.toJSON().data),r=new Uint8Array(r.toJSON().data);var o=e.sign.detached(t,r);return n.from(o)},o.verify=function(t,r,o){return t=n.from(t),t=new Uint8Array(t.toJSON().data),r=new Uint8Array(r.toJSON().data),o=new Uint8Array(o.toJSON().data),e.sign.detached.verify(t,r,o)},!1}},4062:(e,t)=>{"use strict";function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}function n(e){return function(e){if(Array.isArray(e))return e}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return o(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?o(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r0&&(r=t>r.length?["0",r.toString().padStart(t,"0")].join("."):[r.slice(0,-t),r.slice(-t)].join(".")),r.replace(/(\.\d*?)0+$/,"$1")}},{key:"parseTokenAmount",value:function(e,t){var r,o=n(e.split(".").slice()),i=o[0],a=o[1];if(o.slice(2).length)throw new Error("Invalid decimal value: ".concat(e));return BigInt(i+(null!==(r=null==a?void 0:a.padEnd(t,"0"))&&void 0!==r?r:"0".repeat(t))).toString()}}],(t=null)&&i(e.prototype,t),r&&i(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,r}()},4842:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SorobanDataBuilder=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n};function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.StrKey=void 0,t.decodeCheck=d,t.encodeCheck=h;var o,i=(o=r(5360))&&o.__esModule?o:{default:o},a=r(1346);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){for(var r=0;r165)return!1;break;default:return!1}var r="";try{r=d(e,t)}catch(e){return!1}switch(e){case"ed25519PublicKey":case"ed25519SecretSeed":case"preAuthTx":case"sha256Hash":case"contract":return 32===r.length;case"med25519PublicKey":return 40===r.length;case"signedPayload":return r.length>=40&&r.length<=100;default:return!1}}function d(e,t){if("string"!=typeof t)throw new TypeError("encoded argument must be of type String");var r=i.default.decode(t),o=r[0],s=r.slice(0,-2),u=s.slice(1),c=r.slice(-2);if(t!==i.default.encode(r))throw new Error("invalid encoded string");var f=l[e];if(void 0===f)throw new Error("".concat(e," is not a valid version byte name. ")+"Expected one of ".concat(Object.keys(l).join(", ")));if(o!==f)throw new Error("invalid version byte. expected ".concat(f,", got ").concat(o));var p=y(s);if(!(0,a.verifyChecksum)(p,c))throw new Error("invalid checksum");return n.from(u)}function h(e,t){if(null==t)throw new Error("cannot encode null data");var r=l[e];if(void 0===r)throw new Error("".concat(e," is not a valid version byte name. ")+"Expected one of ".concat(Object.keys(l).join(", ")));t=n.from(t);var o=n.from([r]),a=n.concat([o,t]),s=n.from(y(a)),u=n.concat([a,s]);return i.default.encode(u)}function y(e){for(var t=[0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920],r=0,n=0;n>8^e[n]],r&=65535}var o=new Uint8Array(2);return o[0]=255&r,o[1]=r>>8&255,o}},380:(e,t,r)=>{"use strict";var n=r(8287).Buffer;function o(e){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Transaction=void 0;var i,a=(i=r(1918))&&i.__esModule?i:{default:i},s=r(9152),u=r(7120),c=r(7237),l=r(4172),f=r(3758),p=r(6160);function d(e,t){for(var r=0;r=this.operations.length)throw new RangeError("invalid operation index");var t=this.operations[e];try{t=c.Operation.createClaimableBalance(t)}catch(e){throw new TypeError("expected createClaimableBalance, got ".concat(t.type,": ").concat(e))}var r=u.StrKey.decodeEd25519PublicKey((0,p.extractBaseAddress)(this.source)),n=a.default.HashIdPreimage.envelopeTypeOpId(new a.default.HashIdPreimageOperationId({sourceAccount:a.default.AccountId.publicKeyTypeEd25519(r),seqNum:a.default.SequenceNumber.fromString(this.sequence),opNum:e})),o=(0,s.hash)(n.toXDR("raw"));return a.default.ClaimableBalanceId.claimableBalanceIdTypeV0(o).toXDR("hex")}}])}(f.TransactionBase)},3758:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionBase=void 0;var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(9152),s=r(6691);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:"",o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(!o||"string"!=typeof o)throw new Error("Invalid signature");if(!r||"string"!=typeof r)throw new Error("Invalid publicKey");var a=n.from(o,"base64");try{t=(e=s.Keypair.fromPublicKey(r)).signatureHint()}catch(e){throw new Error("Invalid publicKey")}if(!e.verify(this.hash(),a))throw new Error("Invalid signature");this.signatures.push(new i.default.DecoratedSignature({hint:t,signature:a}))}},{key:"addDecoratedSignature",value:function(e){this.signatures.push(e)}},{key:"signHashX",value:function(e){if("string"==typeof e&&(e=n.from(e,"hex")),e.length>64)throw new Error("preimage cannnot be longer than 64 bytes");var t=e,r=(0,a.hash)(e),o=r.slice(r.length-4);this.signatures.push(new i.default.DecoratedSignature({hint:o,signature:t}))}},{key:"hash",value:function(){return(0,a.hash)(this.signatureBase())}},{key:"signatureBase",value:function(){throw new Error("Implement in subclass")}},{key:"toEnvelope",value:function(){throw new Error("Implement in subclass")}},{key:"toXDR",value:function(){return this.toEnvelope().toXDR().toString("base64")}}])}()},6396:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionBuilder=t.TimeoutInfinite=t.BASE_FEE=void 0,t.isValidDate=T;var n=r(3740),o=y(r(1242)),i=y(r(1918)),a=r(2135),s=r(2243),u=r(6160),c=r(380),l=r(9260),f=r(4842),p=r(7120),d=r(225),h=r(4172);function y(e){return e&&e.__esModule?e:{default:e}}function m(e){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},m(e)}function v(e){return function(e){if(Array.isArray(e))return g(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return g(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?g(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function g(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r1&&void 0!==arguments[1]?arguments[1]:{};if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw new Error("must specify source account for the transaction");if(void 0===r.fee)throw new Error("must specify fee for the transaction (in stroops)");this.source=t,this.operations=[],this.baseFee=r.fee,this.timebounds=r.timebounds?w({},r.timebounds):null,this.ledgerbounds=r.ledgerbounds?w({},r.ledgerbounds):null,this.minAccountSequence=r.minAccountSequence||null,this.minAccountSequenceAge=r.minAccountSequenceAge||null,this.minAccountSequenceLedgerGap=r.minAccountSequenceLedgerGap||null,this.extraSigners=r.extraSigners?v(r.extraSigners):null,this.memo=r.memo||h.Memo.none(),this.networkPassphrase=r.networkPassphrase||null,this.sorobanData=r.sorobanData?new f.SorobanDataBuilder(r.sorobanData).build():null}return t=e,y=[{key:"cloneFrom",value:function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!(t instanceof c.Transaction))throw new TypeError("expected a 'Transaction', got: ".concat(t));var n,o=(BigInt(t.sequence)-1n).toString();if(p.StrKey.isValidMed25519PublicKey(t.source))n=s.MuxedAccount.fromAddress(t.source,o);else{if(!p.StrKey.isValidEd25519PublicKey(t.source))throw new TypeError("unsupported tx source account: ".concat(t.source));n=new a.Account(t.source,o)}var i=new e(n,w({fee:(parseInt(t.fee,10)/t.operations.length||k).toString(),memo:t.memo,networkPassphrase:t.networkPassphrase,timebounds:t.timeBounds,ledgerbounds:t.ledgerBounds,minAccountSequence:t.minAccountSequence,minAccountSequenceAge:t.minAccountSequenceAge,minAccountSequenceLedgerGap:t.minAccountSequenceLedgerGap,extraSigners:t.extraSigners},r));return t._tx.operations().forEach((function(e){return i.addOperation(e)})),i}},{key:"buildFeeBumpTransaction",value:function(e,t,r,n){var a=r.operations.length,s=new o.default(r.fee).div(a),c=new o.default(t);if(c.lt(s))throw new Error("Invalid baseFee, it should be at least ".concat(s," stroops."));var f=new o.default(k);if(c.lt(f))throw new Error("Invalid baseFee, it should be at least ".concat(f," stroops."));var p,d=r.toEnvelope();if(d.switch()===i.default.EnvelopeType.envelopeTypeTxV0()){var h=d.v0().tx(),y=new i.default.Transaction({sourceAccount:new i.default.MuxedAccount.keyTypeEd25519(h.sourceAccountEd25519()),fee:h.fee(),seqNum:h.seqNum(),cond:i.default.Preconditions.precondTime(h.timeBounds()),memo:h.memo(),operations:h.operations(),ext:new i.default.TransactionExt(0)});d=new i.default.TransactionEnvelope.envelopeTypeTx(new i.default.TransactionV1Envelope({tx:y,signatures:d.v0().signatures()}))}p="string"==typeof e?(0,u.decodeAddressToMuxedAccount)(e):e.xdrMuxedAccount();var m=new i.default.FeeBumpTransaction({feeSource:p,fee:i.default.Int64.fromString(c.times(a+1).toString()),innerTx:i.default.FeeBumpTransactionInnerTx.envelopeTypeTx(d.v1()),ext:new i.default.FeeBumpTransactionExt(0)}),v=new i.default.FeeBumpTransactionEnvelope({tx:m,signatures:[]}),g=new i.default.TransactionEnvelope.envelopeTypeTxFeeBump(v);return new l.FeeBumpTransaction(g,n)}},{key:"fromXDR",value:function(e,t){return"string"==typeof e&&(e=i.default.TransactionEnvelope.fromXDR(e,"base64")),e.switch()===i.default.EnvelopeType.envelopeTypeTxFeeBump()?new l.FeeBumpTransaction(e,t):new c.Transaction(e,t)}}],(r=[{key:"addOperation",value:function(e){return this.operations.push(e),this}},{key:"addOperationAt",value:function(e,t){return this.operations.splice(t,0,e),this}},{key:"clearOperations",value:function(){return this.operations=[],this}},{key:"clearOperationAt",value:function(e){return this.operations.splice(e,1),this}},{key:"addMemo",value:function(e){return this.memo=e,this}},{key:"setTimeout",value:function(e){if(null!==this.timebounds&&this.timebounds.maxTime>0)throw new Error("TimeBounds.max_time has been already set - setting timeout would overwrite it.");if(e<0)throw new Error("timeout cannot be negative");if(e>0){var t=Math.floor(Date.now()/1e3)+e;null===this.timebounds?this.timebounds={minTime:0,maxTime:t}:this.timebounds={minTime:this.timebounds.minTime,maxTime:t}}else this.timebounds={minTime:0,maxTime:0};return this}},{key:"setTimebounds",value:function(e,t){if("number"==typeof e&&(e=new Date(1e3*e)),"number"==typeof t&&(t=new Date(1e3*t)),null!==this.timebounds)throw new Error("TimeBounds has been already set - setting timebounds would overwrite it.");var r=Math.floor(e.valueOf()/1e3),n=Math.floor(t.valueOf()/1e3);if(r<0)throw new Error("min_time cannot be negative");if(n<0)throw new Error("max_time cannot be negative");if(n>0&&r>n)throw new Error("min_time cannot be greater than max_time");return this.timebounds={minTime:r,maxTime:n},this}},{key:"setLedgerbounds",value:function(e,t){if(null!==this.ledgerbounds)throw new Error("LedgerBounds has been already set - setting ledgerbounds would overwrite it.");if(e<0)throw new Error("min_ledger cannot be negative");if(t<0)throw new Error("max_ledger cannot be negative");if(t>0&&e>t)throw new Error("min_ledger cannot be greater than max_ledger");return this.ledgerbounds={minLedger:e,maxLedger:t},this}},{key:"setMinAccountSequence",value:function(e){if(null!==this.minAccountSequence)throw new Error("min_account_sequence has been already set - setting min_account_sequence would overwrite it.");return this.minAccountSequence=e,this}},{key:"setMinAccountSequenceAge",value:function(e){if("number"!=typeof e)throw new Error("min_account_sequence_age must be a number");if(null!==this.minAccountSequenceAge)throw new Error("min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.");if(e<0)throw new Error("min_account_sequence_age cannot be negative");return this.minAccountSequenceAge=e,this}},{key:"setMinAccountSequenceLedgerGap",value:function(e){if(null!==this.minAccountSequenceLedgerGap)throw new Error("min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.");if(e<0)throw new Error("min_account_sequence_ledger_gap cannot be negative");return this.minAccountSequenceLedgerGap=e,this}},{key:"setExtraSigners",value:function(e){if(!Array.isArray(e))throw new Error("extra_signers must be an array of strings.");if(null!==this.extraSigners)throw new Error("extra_signers has been already set - setting extra_signers would overwrite it.");if(e.length>2)throw new Error("extra_signers cannot be longer than 2 elements.");return this.extraSigners=v(e),this}},{key:"setNetworkPassphrase",value:function(e){return this.networkPassphrase=e,this}},{key:"setSorobanData",value:function(e){return this.sorobanData=new f.SorobanDataBuilder(e).build(),this}},{key:"build",value:function(){var e=new o.default(this.source.sequenceNumber()).plus(1),t={fee:new o.default(this.baseFee).times(this.operations.length).toNumber(),seqNum:i.default.SequenceNumber.fromString(e.toString()),memo:this.memo?this.memo.toXDRObject():null};if(null===this.timebounds||void 0===this.timebounds.minTime||void 0===this.timebounds.maxTime)throw new Error("TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).");T(this.timebounds.minTime)&&(this.timebounds.minTime=this.timebounds.minTime.getTime()/1e3),T(this.timebounds.maxTime)&&(this.timebounds.maxTime=this.timebounds.maxTime.getTime()/1e3),this.timebounds.minTime=n.UnsignedHyper.fromString(this.timebounds.minTime.toString()),this.timebounds.maxTime=n.UnsignedHyper.fromString(this.timebounds.maxTime.toString());var r=new i.default.TimeBounds(this.timebounds);if(this.hasV2Preconditions()){var a=null;null!==this.ledgerbounds&&(a=new i.default.LedgerBounds(this.ledgerbounds));var s=this.minAccountSequence||"0";s=i.default.SequenceNumber.fromString(s);var l=n.UnsignedHyper.fromString(null!==this.minAccountSequenceAge?this.minAccountSequenceAge.toString():"0"),f=this.minAccountSequenceLedgerGap||0,p=null!==this.extraSigners?this.extraSigners.map(d.SignerKey.decodeAddress):[];t.cond=i.default.Preconditions.precondV2(new i.default.PreconditionsV2({timeBounds:r,ledgerBounds:a,minSeqNum:s,minSeqAge:l,minSeqLedgerGap:f,extraSigners:p}))}else t.cond=i.default.Preconditions.precondTime(r);t.sourceAccount=(0,u.decodeAddressToMuxedAccount)(this.source.accountId()),this.sorobanData?t.ext=new i.default.TransactionExt(1,this.sorobanData):t.ext=new i.default.TransactionExt(0,i.default.Void);var h=new i.default.Transaction(t);h.operations(this.operations);var y=new i.default.TransactionEnvelope.envelopeTypeTx(new i.default.TransactionV1Envelope({tx:h})),m=new c.Transaction(y,this.networkPassphrase);return this.source.incrementSequenceNumber(),m}},{key:"hasV2Preconditions",value:function(){return null!==this.ledgerbounds||null!==this.minAccountSequence||null!==this.minAccountSequenceAge||null!==this.minAccountSequenceLedgerGap||null!==this.extraSigners&&this.extraSigners.length>0}}])&&_(t.prototype,r),y&&_(t,y),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,y}();function T(e){return e instanceof Date&&!isNaN(e)}},1242:(e,t,r)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=((n=r(1594))&&n.__esModule?n:{default:n}).default.clone();o.DEBUG=!0;t.default=o},1346:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyChecksum=function(e,t){if(e.length!==t.length)return!1;if(0===e.length)return!0;for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.best_r=function(e){var t,r,n=new o.default(e),s=[[new o.default(0),new o.default(1)],[new o.default(1),new o.default(0)]],u=2;for(;!n.gt(a);){t=n.integerValue(o.default.ROUND_FLOOR),r=n.minus(t);var c=t.times(s[u-1][0]).plus(s[u-2][0]),l=t.times(s[u-1][1]).plus(s[u-2][1]);if(c.gt(a)||l.gt(a))break;if(s.push([c,l]),r.eq(0))break;n=new o.default(1).div(r),u+=1}var f=(h=s[s.length-1],y=2,function(e){if(Array.isArray(e))return e}(h)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(h,y)||function(e,t){if(e){if("string"==typeof e)return i(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(e,t):void 0}}(h,y)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),p=f[0],d=f[1];var h,y;if(p.isZero()||d.isZero())throw new Error("Couldn't find approximation");return[p.toNumber(),d.toNumber()]};var n,o=(n=r(1242))&&n.__esModule?n:{default:n};function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.decodeAddressToMuxedAccount=s,t.encodeMuxedAccount=function(e,t){if(!a.StrKey.isValidEd25519PublicKey(e))throw new Error("address should be a Stellar account ID (G...)");if("string"!=typeof t)throw new Error("id should be a string representing a number (uint64)");return i.default.MuxedAccount.keyTypeMuxedEd25519(new i.default.MuxedAccountMed25519({id:i.default.Uint64.fromString(t),ed25519:a.StrKey.decodeEd25519PublicKey(e)}))},t.encodeMuxedAccountToAddress=u,t.extractBaseAddress=function(e){if(a.StrKey.isValidEd25519PublicKey(e))return e;if(!a.StrKey.isValidMed25519PublicKey(e))throw new TypeError("expected muxed account (M...), got ".concat(e));var t=s(e);return a.StrKey.encodeEd25519PublicKey(t.med25519().ed25519())};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(7120);function s(e){return a.StrKey.isValidMed25519PublicKey(e)?function(e){var t=a.StrKey.decodeMed25519PublicKey(e);return i.default.MuxedAccount.keyTypeMuxedEd25519(new i.default.MuxedAccountMed25519({id:i.default.Uint64.fromXDR(t.subarray(-8)),ed25519:t.subarray(0,-8)}))}(e):i.default.MuxedAccount.keyTypeEd25519(a.StrKey.decodeEd25519PublicKey(e))}function u(e){return e.switch().value===i.default.CryptoKeyType.keyTypeMuxedEd25519().value?function(e){if(e.switch()===i.default.CryptoKeyType.keyTypeEd25519())return u(e);var t=e.med25519();return a.StrKey.encodeMed25519PublicKey(n.concat([t.ed25519(),t.id().toXDR("raw")]))}(e):a.StrKey.encodeEd25519PublicKey(e.ed25519())}},645:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.trimEnd=void 0;t.trimEnd=function(e,t){for(var r="number"==typeof e,n=String(e);n.endsWith(t);)n=n.slice(0,-1);return r?Number(n):n}},1918:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,o=(n=r(7938))&&n.__esModule?n:{default:n};t.default=o.default},4940:(e,t,r)=>{!function(e){"use strict";var t=function(e){var t,r=new Float64Array(16);if(e)for(t=0;t>24&255,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r,e[t+4]=n>>24&255,e[t+5]=n>>16&255,e[t+6]=n>>8&255,e[t+7]=255&n}function y(e,t,r,n,o){var i,a=0;for(i=0;i>>8)-1}function m(e,t,r,n){return y(e,t,r,n,16)}function v(e,t,r,n){return y(e,t,r,n,32)}function g(e,t,r,n){!function(e,t,r,n){for(var o,i=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,s=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,c=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,l=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,p=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,h=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,y=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,m=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,v=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,g=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,b=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,w=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,S=i,_=a,E=s,k=u,T=c,O=l,x=f,A=p,P=d,R=h,j=y,I=m,C=v,L=g,B=b,N=w,U=0;U<20;U+=2)S^=(o=(C^=(o=(P^=(o=(T^=(o=S+C|0)<<7|o>>>25)+S|0)<<9|o>>>23)+T|0)<<13|o>>>19)+P|0)<<18|o>>>14,O^=(o=(_^=(o=(L^=(o=(R^=(o=O+_|0)<<7|o>>>25)+O|0)<<9|o>>>23)+R|0)<<13|o>>>19)+L|0)<<18|o>>>14,j^=(o=(x^=(o=(E^=(o=(B^=(o=j+x|0)<<7|o>>>25)+j|0)<<9|o>>>23)+B|0)<<13|o>>>19)+E|0)<<18|o>>>14,N^=(o=(I^=(o=(A^=(o=(k^=(o=N+I|0)<<7|o>>>25)+N|0)<<9|o>>>23)+k|0)<<13|o>>>19)+A|0)<<18|o>>>14,S^=(o=(k^=(o=(E^=(o=(_^=(o=S+k|0)<<7|o>>>25)+S|0)<<9|o>>>23)+_|0)<<13|o>>>19)+E|0)<<18|o>>>14,O^=(o=(T^=(o=(A^=(o=(x^=(o=O+T|0)<<7|o>>>25)+O|0)<<9|o>>>23)+x|0)<<13|o>>>19)+A|0)<<18|o>>>14,j^=(o=(R^=(o=(P^=(o=(I^=(o=j+R|0)<<7|o>>>25)+j|0)<<9|o>>>23)+I|0)<<13|o>>>19)+P|0)<<18|o>>>14,N^=(o=(B^=(o=(L^=(o=(C^=(o=N+B|0)<<7|o>>>25)+N|0)<<9|o>>>23)+C|0)<<13|o>>>19)+L|0)<<18|o>>>14;S=S+i|0,_=_+a|0,E=E+s|0,k=k+u|0,T=T+c|0,O=O+l|0,x=x+f|0,A=A+p|0,P=P+d|0,R=R+h|0,j=j+y|0,I=I+m|0,C=C+v|0,L=L+g|0,B=B+b|0,N=N+w|0,e[0]=S>>>0&255,e[1]=S>>>8&255,e[2]=S>>>16&255,e[3]=S>>>24&255,e[4]=_>>>0&255,e[5]=_>>>8&255,e[6]=_>>>16&255,e[7]=_>>>24&255,e[8]=E>>>0&255,e[9]=E>>>8&255,e[10]=E>>>16&255,e[11]=E>>>24&255,e[12]=k>>>0&255,e[13]=k>>>8&255,e[14]=k>>>16&255,e[15]=k>>>24&255,e[16]=T>>>0&255,e[17]=T>>>8&255,e[18]=T>>>16&255,e[19]=T>>>24&255,e[20]=O>>>0&255,e[21]=O>>>8&255,e[22]=O>>>16&255,e[23]=O>>>24&255,e[24]=x>>>0&255,e[25]=x>>>8&255,e[26]=x>>>16&255,e[27]=x>>>24&255,e[28]=A>>>0&255,e[29]=A>>>8&255,e[30]=A>>>16&255,e[31]=A>>>24&255,e[32]=P>>>0&255,e[33]=P>>>8&255,e[34]=P>>>16&255,e[35]=P>>>24&255,e[36]=R>>>0&255,e[37]=R>>>8&255,e[38]=R>>>16&255,e[39]=R>>>24&255,e[40]=j>>>0&255,e[41]=j>>>8&255,e[42]=j>>>16&255,e[43]=j>>>24&255,e[44]=I>>>0&255,e[45]=I>>>8&255,e[46]=I>>>16&255,e[47]=I>>>24&255,e[48]=C>>>0&255,e[49]=C>>>8&255,e[50]=C>>>16&255,e[51]=C>>>24&255,e[52]=L>>>0&255,e[53]=L>>>8&255,e[54]=L>>>16&255,e[55]=L>>>24&255,e[56]=B>>>0&255,e[57]=B>>>8&255,e[58]=B>>>16&255,e[59]=B>>>24&255,e[60]=N>>>0&255,e[61]=N>>>8&255,e[62]=N>>>16&255,e[63]=N>>>24&255}(e,t,r,n)}function b(e,t,r,n){!function(e,t,r,n){for(var o,i=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,s=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,c=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,l=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,p=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,h=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,y=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,m=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,v=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,g=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,b=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,w=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,S=0;S<20;S+=2)i^=(o=(v^=(o=(d^=(o=(c^=(o=i+v|0)<<7|o>>>25)+i|0)<<9|o>>>23)+c|0)<<13|o>>>19)+d|0)<<18|o>>>14,l^=(o=(a^=(o=(g^=(o=(h^=(o=l+a|0)<<7|o>>>25)+l|0)<<9|o>>>23)+h|0)<<13|o>>>19)+g|0)<<18|o>>>14,y^=(o=(f^=(o=(s^=(o=(b^=(o=y+f|0)<<7|o>>>25)+y|0)<<9|o>>>23)+b|0)<<13|o>>>19)+s|0)<<18|o>>>14,w^=(o=(m^=(o=(p^=(o=(u^=(o=w+m|0)<<7|o>>>25)+w|0)<<9|o>>>23)+u|0)<<13|o>>>19)+p|0)<<18|o>>>14,i^=(o=(u^=(o=(s^=(o=(a^=(o=i+u|0)<<7|o>>>25)+i|0)<<9|o>>>23)+a|0)<<13|o>>>19)+s|0)<<18|o>>>14,l^=(o=(c^=(o=(p^=(o=(f^=(o=l+c|0)<<7|o>>>25)+l|0)<<9|o>>>23)+f|0)<<13|o>>>19)+p|0)<<18|o>>>14,y^=(o=(h^=(o=(d^=(o=(m^=(o=y+h|0)<<7|o>>>25)+y|0)<<9|o>>>23)+m|0)<<13|o>>>19)+d|0)<<18|o>>>14,w^=(o=(b^=(o=(g^=(o=(v^=(o=w+b|0)<<7|o>>>25)+w|0)<<9|o>>>23)+v|0)<<13|o>>>19)+g|0)<<18|o>>>14;e[0]=i>>>0&255,e[1]=i>>>8&255,e[2]=i>>>16&255,e[3]=i>>>24&255,e[4]=l>>>0&255,e[5]=l>>>8&255,e[6]=l>>>16&255,e[7]=l>>>24&255,e[8]=y>>>0&255,e[9]=y>>>8&255,e[10]=y>>>16&255,e[11]=y>>>24&255,e[12]=w>>>0&255,e[13]=w>>>8&255,e[14]=w>>>16&255,e[15]=w>>>24&255,e[16]=f>>>0&255,e[17]=f>>>8&255,e[18]=f>>>16&255,e[19]=f>>>24&255,e[20]=p>>>0&255,e[21]=p>>>8&255,e[22]=p>>>16&255,e[23]=p>>>24&255,e[24]=d>>>0&255,e[25]=d>>>8&255,e[26]=d>>>16&255,e[27]=d>>>24&255,e[28]=h>>>0&255,e[29]=h>>>8&255,e[30]=h>>>16&255,e[31]=h>>>24&255}(e,t,r,n)}var w=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function S(e,t,r,n,o,i,a){var s,u,c=new Uint8Array(16),l=new Uint8Array(64);for(u=0;u<16;u++)c[u]=0;for(u=0;u<8;u++)c[u]=i[u];for(;o>=64;){for(g(l,c,a,w),u=0;u<64;u++)e[t+u]=r[n+u]^l[u];for(s=1,u=8;u<16;u++)s=s+(255&c[u])|0,c[u]=255&s,s>>>=8;o-=64,t+=64,n+=64}if(o>0)for(g(l,c,a,w),u=0;u=64;){for(g(u,s,o,w),a=0;a<64;a++)e[t+a]=u[a];for(i=1,a=8;a<16;a++)i=i+(255&s[a])|0,s[a]=255&i,i>>>=8;r-=64,t+=64}if(r>0)for(g(u,s,o,w),a=0;a>>13|r<<3),n=255&e[4]|(255&e[5])<<8,this.r[2]=7939&(r>>>10|n<<6),o=255&e[6]|(255&e[7])<<8,this.r[3]=8191&(n>>>7|o<<9),i=255&e[8]|(255&e[9])<<8,this.r[4]=255&(o>>>4|i<<12),this.r[5]=i>>>1&8190,a=255&e[10]|(255&e[11])<<8,this.r[6]=8191&(i>>>14|a<<2),s=255&e[12]|(255&e[13])<<8,this.r[7]=8065&(a>>>11|s<<5),u=255&e[14]|(255&e[15])<<8,this.r[8]=8191&(s>>>8|u<<8),this.r[9]=u>>>5&127,this.pad[0]=255&e[16]|(255&e[17])<<8,this.pad[1]=255&e[18]|(255&e[19])<<8,this.pad[2]=255&e[20]|(255&e[21])<<8,this.pad[3]=255&e[22]|(255&e[23])<<8,this.pad[4]=255&e[24]|(255&e[25])<<8,this.pad[5]=255&e[26]|(255&e[27])<<8,this.pad[6]=255&e[28]|(255&e[29])<<8,this.pad[7]=255&e[30]|(255&e[31])<<8};function O(e,t,r,n,o,i){var a=new T(i);return a.update(r,n,o),a.finish(e,t),0}function x(e,t,r,n,o,i){var a=new Uint8Array(16);return O(a,0,r,n,o,i),m(e,t,a,0)}function A(e,t,r,n,o){var i;if(r<32)return-1;for(k(e,0,t,0,r,n,o),O(e,16,e,32,r-32,e),i=0;i<16;i++)e[i]=0;return 0}function P(e,t,r,n,o){var i,a=new Uint8Array(32);if(r<32)return-1;if(E(a,0,32,n,o),0!==x(t,16,t,32,r-32,a))return-1;for(k(e,0,t,0,r,n,o),i=0;i<32;i++)e[i]=0;return 0}function R(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function j(e){var t,r,n=1;for(t=0;t<16;t++)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function I(e,t,r){for(var n,o=~(r-1),i=0;i<16;i++)n=o&(e[i]^t[i]),e[i]^=n,t[i]^=n}function C(e,r){var n,o,i,a=t(),s=t();for(n=0;n<16;n++)s[n]=r[n];for(j(s),j(s),j(s),o=0;o<2;o++){for(a[0]=s[0]-65517,n=1;n<15;n++)a[n]=s[n]-65535-(a[n-1]>>16&1),a[n-1]&=65535;a[15]=s[15]-32767-(a[14]>>16&1),i=a[15]>>16&1,a[14]&=65535,I(s,a,1-i)}for(n=0;n<16;n++)e[2*n]=255&s[n],e[2*n+1]=s[n]>>8}function L(e,t){var r=new Uint8Array(32),n=new Uint8Array(32);return C(r,e),C(n,t),v(r,0,n,0)}function B(e){var t=new Uint8Array(32);return C(t,e),1&t[0]}function N(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function U(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]+r[n]}function M(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]-r[n]}function D(e,t,r){var n,o,i=0,a=0,s=0,u=0,c=0,l=0,f=0,p=0,d=0,h=0,y=0,m=0,v=0,g=0,b=0,w=0,S=0,_=0,E=0,k=0,T=0,O=0,x=0,A=0,P=0,R=0,j=0,I=0,C=0,L=0,B=0,N=r[0],U=r[1],M=r[2],D=r[3],F=r[4],V=r[5],q=r[6],K=r[7],H=r[8],z=r[9],X=r[10],G=r[11],W=r[12],$=r[13],Q=r[14],Y=r[15];i+=(n=t[0])*N,a+=n*U,s+=n*M,u+=n*D,c+=n*F,l+=n*V,f+=n*q,p+=n*K,d+=n*H,h+=n*z,y+=n*X,m+=n*G,v+=n*W,g+=n*$,b+=n*Q,w+=n*Y,a+=(n=t[1])*N,s+=n*U,u+=n*M,c+=n*D,l+=n*F,f+=n*V,p+=n*q,d+=n*K,h+=n*H,y+=n*z,m+=n*X,v+=n*G,g+=n*W,b+=n*$,w+=n*Q,S+=n*Y,s+=(n=t[2])*N,u+=n*U,c+=n*M,l+=n*D,f+=n*F,p+=n*V,d+=n*q,h+=n*K,y+=n*H,m+=n*z,v+=n*X,g+=n*G,b+=n*W,w+=n*$,S+=n*Q,_+=n*Y,u+=(n=t[3])*N,c+=n*U,l+=n*M,f+=n*D,p+=n*F,d+=n*V,h+=n*q,y+=n*K,m+=n*H,v+=n*z,g+=n*X,b+=n*G,w+=n*W,S+=n*$,_+=n*Q,E+=n*Y,c+=(n=t[4])*N,l+=n*U,f+=n*M,p+=n*D,d+=n*F,h+=n*V,y+=n*q,m+=n*K,v+=n*H,g+=n*z,b+=n*X,w+=n*G,S+=n*W,_+=n*$,E+=n*Q,k+=n*Y,l+=(n=t[5])*N,f+=n*U,p+=n*M,d+=n*D,h+=n*F,y+=n*V,m+=n*q,v+=n*K,g+=n*H,b+=n*z,w+=n*X,S+=n*G,_+=n*W,E+=n*$,k+=n*Q,T+=n*Y,f+=(n=t[6])*N,p+=n*U,d+=n*M,h+=n*D,y+=n*F,m+=n*V,v+=n*q,g+=n*K,b+=n*H,w+=n*z,S+=n*X,_+=n*G,E+=n*W,k+=n*$,T+=n*Q,O+=n*Y,p+=(n=t[7])*N,d+=n*U,h+=n*M,y+=n*D,m+=n*F,v+=n*V,g+=n*q,b+=n*K,w+=n*H,S+=n*z,_+=n*X,E+=n*G,k+=n*W,T+=n*$,O+=n*Q,x+=n*Y,d+=(n=t[8])*N,h+=n*U,y+=n*M,m+=n*D,v+=n*F,g+=n*V,b+=n*q,w+=n*K,S+=n*H,_+=n*z,E+=n*X,k+=n*G,T+=n*W,O+=n*$,x+=n*Q,A+=n*Y,h+=(n=t[9])*N,y+=n*U,m+=n*M,v+=n*D,g+=n*F,b+=n*V,w+=n*q,S+=n*K,_+=n*H,E+=n*z,k+=n*X,T+=n*G,O+=n*W,x+=n*$,A+=n*Q,P+=n*Y,y+=(n=t[10])*N,m+=n*U,v+=n*M,g+=n*D,b+=n*F,w+=n*V,S+=n*q,_+=n*K,E+=n*H,k+=n*z,T+=n*X,O+=n*G,x+=n*W,A+=n*$,P+=n*Q,R+=n*Y,m+=(n=t[11])*N,v+=n*U,g+=n*M,b+=n*D,w+=n*F,S+=n*V,_+=n*q,E+=n*K,k+=n*H,T+=n*z,O+=n*X,x+=n*G,A+=n*W,P+=n*$,R+=n*Q,j+=n*Y,v+=(n=t[12])*N,g+=n*U,b+=n*M,w+=n*D,S+=n*F,_+=n*V,E+=n*q,k+=n*K,T+=n*H,O+=n*z,x+=n*X,A+=n*G,P+=n*W,R+=n*$,j+=n*Q,I+=n*Y,g+=(n=t[13])*N,b+=n*U,w+=n*M,S+=n*D,_+=n*F,E+=n*V,k+=n*q,T+=n*K,O+=n*H,x+=n*z,A+=n*X,P+=n*G,R+=n*W,j+=n*$,I+=n*Q,C+=n*Y,b+=(n=t[14])*N,w+=n*U,S+=n*M,_+=n*D,E+=n*F,k+=n*V,T+=n*q,O+=n*K,x+=n*H,A+=n*z,P+=n*X,R+=n*G,j+=n*W,I+=n*$,C+=n*Q,L+=n*Y,w+=(n=t[15])*N,a+=38*(_+=n*M),s+=38*(E+=n*D),u+=38*(k+=n*F),c+=38*(T+=n*V),l+=38*(O+=n*q),f+=38*(x+=n*K),p+=38*(A+=n*H),d+=38*(P+=n*z),h+=38*(R+=n*X),y+=38*(j+=n*G),m+=38*(I+=n*W),v+=38*(C+=n*$),g+=38*(L+=n*Q),b+=38*(B+=n*Y),i=(n=(i+=38*(S+=n*U))+(o=1)+65535)-65536*(o=Math.floor(n/65536)),a=(n=a+o+65535)-65536*(o=Math.floor(n/65536)),s=(n=s+o+65535)-65536*(o=Math.floor(n/65536)),u=(n=u+o+65535)-65536*(o=Math.floor(n/65536)),c=(n=c+o+65535)-65536*(o=Math.floor(n/65536)),l=(n=l+o+65535)-65536*(o=Math.floor(n/65536)),f=(n=f+o+65535)-65536*(o=Math.floor(n/65536)),p=(n=p+o+65535)-65536*(o=Math.floor(n/65536)),d=(n=d+o+65535)-65536*(o=Math.floor(n/65536)),h=(n=h+o+65535)-65536*(o=Math.floor(n/65536)),y=(n=y+o+65535)-65536*(o=Math.floor(n/65536)),m=(n=m+o+65535)-65536*(o=Math.floor(n/65536)),v=(n=v+o+65535)-65536*(o=Math.floor(n/65536)),g=(n=g+o+65535)-65536*(o=Math.floor(n/65536)),b=(n=b+o+65535)-65536*(o=Math.floor(n/65536)),w=(n=w+o+65535)-65536*(o=Math.floor(n/65536)),i=(n=(i+=o-1+37*(o-1))+(o=1)+65535)-65536*(o=Math.floor(n/65536)),a=(n=a+o+65535)-65536*(o=Math.floor(n/65536)),s=(n=s+o+65535)-65536*(o=Math.floor(n/65536)),u=(n=u+o+65535)-65536*(o=Math.floor(n/65536)),c=(n=c+o+65535)-65536*(o=Math.floor(n/65536)),l=(n=l+o+65535)-65536*(o=Math.floor(n/65536)),f=(n=f+o+65535)-65536*(o=Math.floor(n/65536)),p=(n=p+o+65535)-65536*(o=Math.floor(n/65536)),d=(n=d+o+65535)-65536*(o=Math.floor(n/65536)),h=(n=h+o+65535)-65536*(o=Math.floor(n/65536)),y=(n=y+o+65535)-65536*(o=Math.floor(n/65536)),m=(n=m+o+65535)-65536*(o=Math.floor(n/65536)),v=(n=v+o+65535)-65536*(o=Math.floor(n/65536)),g=(n=g+o+65535)-65536*(o=Math.floor(n/65536)),b=(n=b+o+65535)-65536*(o=Math.floor(n/65536)),w=(n=w+o+65535)-65536*(o=Math.floor(n/65536)),i+=o-1+37*(o-1),e[0]=i,e[1]=a,e[2]=s,e[3]=u,e[4]=c,e[5]=l,e[6]=f,e[7]=p,e[8]=d,e[9]=h,e[10]=y,e[11]=m,e[12]=v,e[13]=g,e[14]=b,e[15]=w}function F(e,t){D(e,t,t)}function V(e,r){var n,o=t();for(n=0;n<16;n++)o[n]=r[n];for(n=253;n>=0;n--)F(o,o),2!==n&&4!==n&&D(o,o,r);for(n=0;n<16;n++)e[n]=o[n]}function q(e,r){var n,o=t();for(n=0;n<16;n++)o[n]=r[n];for(n=250;n>=0;n--)F(o,o),1!==n&&D(o,o,r);for(n=0;n<16;n++)e[n]=o[n]}function K(e,r,n){var o,i,a=new Uint8Array(32),s=new Float64Array(80),c=t(),l=t(),f=t(),p=t(),d=t(),h=t();for(i=0;i<31;i++)a[i]=r[i];for(a[31]=127&r[31]|64,a[0]&=248,N(s,n),i=0;i<16;i++)l[i]=s[i],p[i]=c[i]=f[i]=0;for(c[0]=p[0]=1,i=254;i>=0;--i)I(c,l,o=a[i>>>3]>>>(7&i)&1),I(f,p,o),U(d,c,f),M(c,c,f),U(f,l,p),M(l,l,p),F(p,d),F(h,c),D(c,f,c),D(f,l,d),U(d,c,f),M(c,c,f),F(l,c),M(f,p,h),D(c,f,u),U(c,c,p),D(f,f,c),D(c,p,h),D(p,l,s),F(l,d),I(c,l,o),I(f,p,o);for(i=0;i<16;i++)s[i+16]=c[i],s[i+32]=f[i],s[i+48]=l[i],s[i+64]=p[i];var y=s.subarray(32),m=s.subarray(16);return V(y,y),D(m,m,y),C(e,m),0}function H(e,t){return K(e,t,i)}function z(e,t){return n(t,32),H(e,t)}function X(e,t,r){var n=new Uint8Array(32);return K(n,r,t),b(e,o,n,w)}T.prototype.blocks=function(e,t,r){for(var n,o,i,a,s,u,c,l,f,p,d,h,y,m,v,g,b,w,S,_=this.fin?0:2048,E=this.h[0],k=this.h[1],T=this.h[2],O=this.h[3],x=this.h[4],A=this.h[5],P=this.h[6],R=this.h[7],j=this.h[8],I=this.h[9],C=this.r[0],L=this.r[1],B=this.r[2],N=this.r[3],U=this.r[4],M=this.r[5],D=this.r[6],F=this.r[7],V=this.r[8],q=this.r[9];r>=16;)p=f=0,p+=(E+=8191&(n=255&e[t+0]|(255&e[t+1])<<8))*C,p+=(k+=8191&(n>>>13|(o=255&e[t+2]|(255&e[t+3])<<8)<<3))*(5*q),p+=(T+=8191&(o>>>10|(i=255&e[t+4]|(255&e[t+5])<<8)<<6))*(5*V),p+=(O+=8191&(i>>>7|(a=255&e[t+6]|(255&e[t+7])<<8)<<9))*(5*F),f=(p+=(x+=8191&(a>>>4|(s=255&e[t+8]|(255&e[t+9])<<8)<<12))*(5*D))>>>13,p&=8191,p+=(A+=s>>>1&8191)*(5*M),p+=(P+=8191&(s>>>14|(u=255&e[t+10]|(255&e[t+11])<<8)<<2))*(5*U),p+=(R+=8191&(u>>>11|(c=255&e[t+12]|(255&e[t+13])<<8)<<5))*(5*N),p+=(j+=8191&(c>>>8|(l=255&e[t+14]|(255&e[t+15])<<8)<<8))*(5*B),d=f+=(p+=(I+=l>>>5|_)*(5*L))>>>13,d+=E*L,d+=k*C,d+=T*(5*q),d+=O*(5*V),f=(d+=x*(5*F))>>>13,d&=8191,d+=A*(5*D),d+=P*(5*M),d+=R*(5*U),d+=j*(5*N),f+=(d+=I*(5*B))>>>13,d&=8191,h=f,h+=E*B,h+=k*L,h+=T*C,h+=O*(5*q),f=(h+=x*(5*V))>>>13,h&=8191,h+=A*(5*F),h+=P*(5*D),h+=R*(5*M),h+=j*(5*U),y=f+=(h+=I*(5*N))>>>13,y+=E*N,y+=k*B,y+=T*L,y+=O*C,f=(y+=x*(5*q))>>>13,y&=8191,y+=A*(5*V),y+=P*(5*F),y+=R*(5*D),y+=j*(5*M),m=f+=(y+=I*(5*U))>>>13,m+=E*U,m+=k*N,m+=T*B,m+=O*L,f=(m+=x*C)>>>13,m&=8191,m+=A*(5*q),m+=P*(5*V),m+=R*(5*F),m+=j*(5*D),v=f+=(m+=I*(5*M))>>>13,v+=E*M,v+=k*U,v+=T*N,v+=O*B,f=(v+=x*L)>>>13,v&=8191,v+=A*C,v+=P*(5*q),v+=R*(5*V),v+=j*(5*F),g=f+=(v+=I*(5*D))>>>13,g+=E*D,g+=k*M,g+=T*U,g+=O*N,f=(g+=x*B)>>>13,g&=8191,g+=A*L,g+=P*C,g+=R*(5*q),g+=j*(5*V),b=f+=(g+=I*(5*F))>>>13,b+=E*F,b+=k*D,b+=T*M,b+=O*U,f=(b+=x*N)>>>13,b&=8191,b+=A*B,b+=P*L,b+=R*C,b+=j*(5*q),w=f+=(b+=I*(5*V))>>>13,w+=E*V,w+=k*F,w+=T*D,w+=O*M,f=(w+=x*U)>>>13,w&=8191,w+=A*N,w+=P*B,w+=R*L,w+=j*C,S=f+=(w+=I*(5*q))>>>13,S+=E*q,S+=k*V,S+=T*F,S+=O*D,f=(S+=x*M)>>>13,S&=8191,S+=A*U,S+=P*N,S+=R*B,S+=j*L,E=p=8191&(f=(f=((f+=(S+=I*C)>>>13)<<2)+f|0)+(p&=8191)|0),k=d+=f>>>=13,T=h&=8191,O=y&=8191,x=m&=8191,A=v&=8191,P=g&=8191,R=b&=8191,j=w&=8191,I=S&=8191,t+=16,r-=16;this.h[0]=E,this.h[1]=k,this.h[2]=T,this.h[3]=O,this.h[4]=x,this.h[5]=A,this.h[6]=P,this.h[7]=R,this.h[8]=j,this.h[9]=I},T.prototype.finish=function(e,t){var r,n,o,i,a=new Uint16Array(10);if(this.leftover){for(i=this.leftover,this.buffer[i++]=1;i<16;i++)this.buffer[i]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(r=this.h[1]>>>13,this.h[1]&=8191,i=2;i<10;i++)this.h[i]+=r,r=this.h[i]>>>13,this.h[i]&=8191;for(this.h[0]+=5*r,r=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=r,r=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=r,a[0]=this.h[0]+5,r=a[0]>>>13,a[0]&=8191,i=1;i<10;i++)a[i]=this.h[i]+r,r=a[i]>>>13,a[i]&=8191;for(a[9]-=8192,n=(1^r)-1,i=0;i<10;i++)a[i]&=n;for(n=~n,i=0;i<10;i++)this.h[i]=this.h[i]&n|a[i];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),o=this.h[0]+this.pad[0],this.h[0]=65535&o,i=1;i<8;i++)o=(this.h[i]+this.pad[i]|0)+(o>>>16)|0,this.h[i]=65535&o;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},T.prototype.update=function(e,t,r){var n,o;if(this.leftover){for((o=16-this.leftover)>r&&(o=r),n=0;n=16&&(o=r-r%16,this.blocks(e,t,o),t+=o,r-=o),r){for(n=0;n=128;){for(_=0;_<16;_++)E=8*_+W,R[_]=r[E+0]<<24|r[E+1]<<16|r[E+2]<<8|r[E+3],j[_]=r[E+4]<<24|r[E+5]<<16|r[E+6]<<8|r[E+7];for(_=0;_<80;_++)if(o=I,i=C,a=L,s=B,u=N,c=U,l=M,D,p=F,d=V,h=q,y=K,m=H,v=z,g=X,G,O=65535&(T=G),x=T>>>16,A=65535&(k=D),P=k>>>16,O+=65535&(T=(H>>>14|N<<18)^(H>>>18|N<<14)^(N>>>9|H<<23)),x+=T>>>16,A+=65535&(k=(N>>>14|H<<18)^(N>>>18|H<<14)^(H>>>9|N<<23)),P+=k>>>16,O+=65535&(T=H&z^~H&X),x+=T>>>16,A+=65535&(k=N&U^~N&M),P+=k>>>16,O+=65535&(T=$[2*_+1]),x+=T>>>16,A+=65535&(k=$[2*_]),P+=k>>>16,k=R[_%16],x+=(T=j[_%16])>>>16,A+=65535&k,P+=k>>>16,A+=(x+=(O+=65535&T)>>>16)>>>16,O=65535&(T=S=65535&O|x<<16),x=T>>>16,A=65535&(k=w=65535&A|(P+=A>>>16)<<16),P=k>>>16,O+=65535&(T=(F>>>28|I<<4)^(I>>>2|F<<30)^(I>>>7|F<<25)),x+=T>>>16,A+=65535&(k=(I>>>28|F<<4)^(F>>>2|I<<30)^(F>>>7|I<<25)),P+=k>>>16,x+=(T=F&V^F&q^V&q)>>>16,A+=65535&(k=I&C^I&L^C&L),P+=k>>>16,f=65535&(A+=(x+=(O+=65535&T)>>>16)>>>16)|(P+=A>>>16)<<16,b=65535&O|x<<16,O=65535&(T=y),x=T>>>16,A=65535&(k=s),P=k>>>16,x+=(T=S)>>>16,A+=65535&(k=w),P+=k>>>16,C=o,L=i,B=a,N=s=65535&(A+=(x+=(O+=65535&T)>>>16)>>>16)|(P+=A>>>16)<<16,U=u,M=c,D=l,I=f,V=p,q=d,K=h,H=y=65535&O|x<<16,z=m,X=v,G=g,F=b,_%16==15)for(E=0;E<16;E++)k=R[E],O=65535&(T=j[E]),x=T>>>16,A=65535&k,P=k>>>16,k=R[(E+9)%16],O+=65535&(T=j[(E+9)%16]),x+=T>>>16,A+=65535&k,P+=k>>>16,w=R[(E+1)%16],O+=65535&(T=((S=j[(E+1)%16])>>>1|w<<31)^(S>>>8|w<<24)^(S>>>7|w<<25)),x+=T>>>16,A+=65535&(k=(w>>>1|S<<31)^(w>>>8|S<<24)^w>>>7),P+=k>>>16,w=R[(E+14)%16],x+=(T=((S=j[(E+14)%16])>>>19|w<<13)^(w>>>29|S<<3)^(S>>>6|w<<26))>>>16,A+=65535&(k=(w>>>19|S<<13)^(S>>>29|w<<3)^w>>>6),P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,R[E]=65535&A|P<<16,j[E]=65535&O|x<<16;O=65535&(T=F),x=T>>>16,A=65535&(k=I),P=k>>>16,k=e[0],x+=(T=t[0])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[0]=I=65535&A|P<<16,t[0]=F=65535&O|x<<16,O=65535&(T=V),x=T>>>16,A=65535&(k=C),P=k>>>16,k=e[1],x+=(T=t[1])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[1]=C=65535&A|P<<16,t[1]=V=65535&O|x<<16,O=65535&(T=q),x=T>>>16,A=65535&(k=L),P=k>>>16,k=e[2],x+=(T=t[2])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[2]=L=65535&A|P<<16,t[2]=q=65535&O|x<<16,O=65535&(T=K),x=T>>>16,A=65535&(k=B),P=k>>>16,k=e[3],x+=(T=t[3])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[3]=B=65535&A|P<<16,t[3]=K=65535&O|x<<16,O=65535&(T=H),x=T>>>16,A=65535&(k=N),P=k>>>16,k=e[4],x+=(T=t[4])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[4]=N=65535&A|P<<16,t[4]=H=65535&O|x<<16,O=65535&(T=z),x=T>>>16,A=65535&(k=U),P=k>>>16,k=e[5],x+=(T=t[5])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[5]=U=65535&A|P<<16,t[5]=z=65535&O|x<<16,O=65535&(T=X),x=T>>>16,A=65535&(k=M),P=k>>>16,k=e[6],x+=(T=t[6])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[6]=M=65535&A|P<<16,t[6]=X=65535&O|x<<16,O=65535&(T=G),x=T>>>16,A=65535&(k=D),P=k>>>16,k=e[7],x+=(T=t[7])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[7]=D=65535&A|P<<16,t[7]=G=65535&O|x<<16,W+=128,n-=128}return n}function Y(e,t,r){var n,o=new Int32Array(8),i=new Int32Array(8),a=new Uint8Array(256),s=r;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,i[0]=4089235720,i[1]=2227873595,i[2]=4271175723,i[3]=1595750129,i[4]=2917565137,i[5]=725511199,i[6]=4215389547,i[7]=327033209,Q(o,i,t,r),r%=128,n=0;n=0;--o)Z(e,t,n=r[o/8|0]>>(7&o)&1),J(t,e),J(e,e),Z(e,t,n)}function re(e,r){var n=[t(),t(),t(),t()];R(n[0],f),R(n[1],p),R(n[2],s),D(n[3],f,p),te(e,n,r)}function ne(e,r,o){var i,a=new Uint8Array(64),s=[t(),t(),t(),t()];for(o||n(r,32),Y(a,r,32),a[0]&=248,a[31]&=127,a[31]|=64,re(s,a),ee(e,s),i=0;i<32;i++)r[i+32]=e[i];return 0}var oe=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function ie(e,t){var r,n,o,i;for(n=63;n>=32;--n){for(r=0,o=n-32,i=n-12;o>4)*oe[o],r=t[o]>>8,t[o]&=255;for(o=0;o<32;o++)t[o]-=r*oe[o];for(n=0;n<32;n++)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function ae(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;ie(e,r)}function se(e,r,n,o){var i,a,s=new Uint8Array(64),u=new Uint8Array(64),c=new Uint8Array(64),l=new Float64Array(64),f=[t(),t(),t(),t()];Y(s,o,32),s[0]&=248,s[31]&=127,s[31]|=64;var p=n+64;for(i=0;i>7&&M(e[0],a,e[0]),D(e[3],e[0],e[1]),0)}(p,o))return-1;for(i=0;i=0},e.sign.keyPair=function(){var e=new Uint8Array(fe),t=new Uint8Array(pe);return ne(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(he(e),e.length!==pe)throw new Error("bad secret key size");for(var t=new Uint8Array(fe),r=0;r{"use strict";r.r(t),r.d(t,{StellarBase:()=>a,default:()=>s,httpClient:()=>n.ok});var n=r(6371),o=r(4356),i={};for(const e in o)["default","StellarBase","httpClient"].indexOf(e)<0&&(i[e]=()=>o[e]);r.d(t,i);var a=r(356);const s=(e=r.hmd(e)).exports},8732:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rh});var c,l,f,p={allowHttp:!1,timeout:0},d=a({},p),h=(c=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},f=[{key:"setAllowHttp",value:function(e){d.allowHttp=e}},{key:"setTimeout",value:function(e){d.timeout=e}},{key:"isAllowHttp",value:function(){return d.allowHttp}},{key:"getTimeout",value:function(){return d.timeout}},{key:"setDefault",value:function(){d=a({},p)}}],(l=null)&&o(c.prototype,l),f&&o(c,f),Object.defineProperty(c,"prototype",{writable:!1}),c)},6299:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AssembledTransaction:()=>de,Client:()=>tt,DEFAULT_TIMEOUT:()=>h,Err:()=>d,NULL_ACCOUNT:()=>y,Ok:()=>p,SentTransaction:()=>K,Spec:()=>Ne,basicNodeSigner:()=>be});var n=r(356),o=r(3496),i=r(4076),a=r(8680);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function c(e,t){for(var r=0;r=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),j(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:C(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function v(e){return v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},v(e)}function g(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function b(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){g(i,n,o,a,s,"next",e)}function s(e){g(i,n,o,a,s,"throw",e)}a(void 0)}))}}function w(e,t,r){return S.apply(this,arguments)}function S(){return S=b(m().mark((function e(t,r,n){var o,i,a,s,u,c,l,f=arguments;return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=f.length>3&&void 0!==f[3]?f[3]:1.5,i=f.length>4&&void 0!==f[4]&&f[4],a=[],s=0,e.t0=a,e.next=7,t();case 7:if(e.t1=e.sent,e.t0.push.call(e.t0,e.t1),r(a[a.length-1])){e.next=11;break}return e.abrupt("return",a);case 11:u=new Date(Date.now()+1e3*n).valueOf(),l=c=1e3;case 14:if(!(Date.now()u&&(c=u-Date.now(),i&&console.info("was gonna wait too long; new waitTime: ".concat(c,"ms"))),l=c+l,e.t2=a,e.next=25,t(a[a.length-1]);case 25:e.t3=e.sent,e.t2.push.call(e.t2,e.t3),i&&r(a[a.length-1])&&console.info("".concat(s,". Called ").concat(t,"; ").concat(a.length," prev attempts. Most recent: ").concat(JSON.stringify(a[a.length-1],null,2))),e.next=14;break;case 30:return e.abrupt("return",a);case 31:case"end":return e.stop()}}),e)}))),S.apply(this,arguments)}var _,E=/Error\(Contract, #(\d+)\)/;function k(e){for(var t=new n.cereal.XdrReader(e),r=[];!t.eof;)r.push(n.xdr.ScSpecEntry.read(t));return r}function T(e,t){return O.apply(this,arguments)}function O(){return(O=b(m().mark((function e(t,r){return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.publicKey?r.getAccount(t.publicKey):new n.Account(y,"0"));case 1:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function x(e,t,r){return t=I(t),function(e,t){if(t&&("object"==C(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,R()?Reflect.construct(t,r||[],I(e).constructor):t.apply(e,r))}function A(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&j(e,t)}function P(e){var t="function"==typeof Map?new Map:void 0;return P=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(R())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var o=new(e.bind.apply(e,n));return r&&j(o,r.prototype),o}(e,arguments,I(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),j(r,e)},P(e)}function R(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(R=function(){return!!e})()}function j(e,t){return j=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},j(e,t)}function I(e){return I=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},I(e)}function C(e){return C="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},C(e)}function L(){L=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,_=S&&S(S(j([])));_&&_!==r&&n.call(_,a)&&(w=_);var E=b.prototype=v.prototype=Object.create(w);function k(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==C(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function B(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function N(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){B(i,n,o,a,s,"next",e)}function s(e){B(i,n,o,a,s,"throw",e)}a(void 0)}))}}function U(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function M(e,t){for(var r=0;r=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,i=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw i}}}}function re(){re=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,_=S&&S(S(j([])));_&&_!==r&&n.call(_,a)&&(w=_);var E=b.prototype=v.prototype=Object.create(w);function k(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==Y(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function ne(e){return function(e){if(Array.isArray(e))return ie(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||oe(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function oe(e,t){if(e){if("string"==typeof e)return ie(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ie(e,t):void 0}}function ie(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r0&&void 0!==y[0]?y[0]:{}).restore,u.built){t.next=5;break}if(u.raw){t.next=4;break}throw new Error("Transaction has not yet been assembled; call `AssembledTransaction.build` first.");case 4:u.built=u.raw.build();case 5:return o=null!==(r=o)&&void 0!==r?r:u.options.restore,delete u.simulationResult,delete u.simulationTransactionData,t.next=10,u.server.simulateTransaction(u.built);case 10:if(u.simulation=t.sent,!o||!i.j.isSimulationRestore(u.simulation)){t.next=25;break}return t.next=14,T(u.options,u.server);case 14:return s=t.sent,t.next=17,u.restoreFootprint(u.simulation.restorePreamble,s);case 17:if((c=t.sent).status!==i.j.GetTransactionStatus.SUCCESS){t.next=24;break}return d=new n.Contract(u.options.contractId),u.raw=new n.TransactionBuilder(s,{fee:null!==(l=u.options.fee)&&void 0!==l?l:n.BASE_FEE,networkPassphrase:u.options.networkPassphrase}).addOperation(d.call.apply(d,[u.options.method].concat(ne(null!==(f=u.options.args)&&void 0!==f?f:[])))).setTimeout(null!==(p=u.options.timeoutInSeconds)&&void 0!==p?p:h),t.next=23,u.simulate();case 23:return t.abrupt("return",u);case 24:throw new e.Errors.RestorationFailure("Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n".concat(JSON.stringify(c)));case 25:return i.j.isSimulationSuccess(u.simulation)&&(u.built=(0,a.X)(u.built,u.simulation).build()),t.abrupt("return",u);case 27:case"end":return t.stop()}}),t)})))),fe(this,"sign",se(re().mark((function t(){var r,o,i,a,s,c,l,f,p,d,y,m,v=arguments;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i=(o=v.length>0&&void 0!==v[0]?v[0]:{}).force,a=void 0!==i&&i,s=o.signTransaction,c=void 0===s?u.options.signTransaction:s,u.built){t.next=3;break}throw new Error("Transaction has not yet been simulated");case 3:if(a||!u.isReadCall){t.next=5;break}throw new e.Errors.NoSignatureNeeded("This is a read call. It requires no signature or sending. Use `force: true` to sign and send anyway.");case 5:if(c){t.next=7;break}throw new e.Errors.NoSigner("You must provide a signTransaction function, either when calling `signAndSend` or when initializing your Client");case 7:if(!(l=u.needsNonInvokerSigningBy().filter((function(e){return!e.startsWith("C")}))).length){t.next=10;break}throw new e.Errors.NeedsMoreSignatures("Transaction requires signatures from ".concat(l,". ")+"See `needsNonInvokerSigningBy` for details.");case 10:return f=null!==(r=u.options.timeoutInSeconds)&&void 0!==r?r:h,u.built=n.TransactionBuilder.cloneFrom(u.built,{fee:u.built.fee,timebounds:void 0,sorobanData:u.simulationData.transactionData}).setTimeout(f).build(),p={networkPassphrase:u.options.networkPassphrase},u.options.address&&(p.address=u.options.address),void 0!==u.options.submit&&(p.submit=u.options.submit),u.options.submitUrl&&(p.submitUrl=u.options.submitUrl),t.next=18,c(u.built.toXDR(),p);case 18:d=t.sent,y=d.signedTxXdr,m=d.error,u.handleWalletError(m),u.signed=n.TransactionBuilder.fromXDR(y,u.options.networkPassphrase);case 23:case"end":return t.stop()}}),t)})))),fe(this,"signAndSend",se(re().mark((function e(){var t,r,n,o,i,a,s=arguments;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=(t=s.length>0&&void 0!==s[0]?s[0]:{}).force,n=void 0!==r&&r,o=t.signTransaction,i=void 0===o?u.options.signTransaction:o,u.signed){e.next=10;break}return a=u.options.submit,u.options.submit&&(u.options.submit=!1),e.prev=4,e.next=7,u.sign({force:n,signTransaction:i});case 7:return e.prev=7,u.options.submit=a,e.finish(7);case 10:return e.abrupt("return",u.send());case 11:case"end":return e.stop()}}),e,null,[[4,,7,10]])})))),fe(this,"needsNonInvokerSigningBy",(function(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).includeAlreadySigned,r=void 0!==t&&t;if(!u.built)throw new Error("Transaction has not yet been simulated");if(!("operations"in u.built))throw new Error("Unexpected Transaction type; no operations: ".concat(JSON.stringify(u.built)));var o=u.built.operations[0];return ne(new Set((null!==(e=o.auth)&&void 0!==e?e:[]).filter((function(e){return e.credentials().switch()===n.xdr.SorobanCredentialsType.sorobanCredentialsAddress()&&(r||"scvVoid"===e.credentials().address().signature().switch().name)})).map((function(e){return n.Address.fromScAddress(e.credentials().address().address()).toString()}))))})),fe(this,"signAuthEntries",se(re().mark((function t(){var r,o,i,a,s,c,l,f,p,d,h,y,m,v,g,b,w=arguments;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i=(o=w.length>0&&void 0!==w[0]?w[0]:{}).expiration,a=void 0===i?se(re().mark((function e(){return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,u.server.getLatestLedger();case 2:return e.t0=e.sent.sequence,e.abrupt("return",e.t0+100);case 4:case"end":return e.stop()}}),e)})))():i,s=o.signAuthEntry,c=void 0===s?u.options.signAuthEntry:s,l=o.address,f=void 0===l?u.options.publicKey:l,p=o.authorizeEntry,d=void 0===p?n.authorizeEntry:p,u.built){t.next=3;break}throw new Error("Transaction has not yet been assembled or simulated");case 3:if(d!==n.authorizeEntry){t.next=11;break}if(0!==(h=u.needsNonInvokerSigningBy()).length){t.next=7;break}throw new e.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?");case 7:if(-1!==h.indexOf(null!=f?f:"")){t.next=9;break}throw new e.Errors.NoSignatureNeeded('No auth entries for public key "'.concat(f,'"'));case 9:if(c){t.next=11;break}throw new e.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`");case 11:y=u.built.operations[0],m=null!==(r=y.auth)&&void 0!==r?r:[],v=te(m.entries()),t.prev=14,b=re().mark((function e(){var t,r,o,i,s;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=ee(g.value,2),r=t[0],o=t[1],(i=n.xdr.SorobanCredentials.fromXDR(o.credentials().toXDR())).switch()===n.xdr.SorobanCredentialsType.sorobanCredentialsAddress()){e.next=4;break}return e.abrupt("return",0);case 4:if(n.Address.fromScAddress(i.address().address()).toString()===f){e.next=7;break}return e.abrupt("return",0);case 7:return s=null!=c?c:Promise.resolve,e.t0=d,e.t1=o,e.t2=function(){var e=se(re().mark((function e(t){var r,n,o;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,s(t.toXDR("base64"),{address:f});case 2:return r=e.sent,n=r.signedAuthEntry,o=r.error,u.handleWalletError(o),e.abrupt("return",H.from(n,"base64"));case 7:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),e.next=13,a;case 13:return e.t3=e.sent,e.t4=u.options.networkPassphrase,e.next=17,(0,e.t0)(e.t1,e.t2,e.t3,e.t4);case 17:m[r]=e.sent;case 18:case"end":return e.stop()}}),e)})),v.s();case 17:if((g=v.n()).done){t.next=24;break}return t.delegateYield(b(),"t0",19);case 19:if(0!==t.t0){t.next=22;break}return t.abrupt("continue",22);case 22:t.next=17;break;case 24:t.next=29;break;case 26:t.prev=26,t.t1=t.catch(14),v.e(t.t1);case 29:return t.prev=29,v.f(),t.finish(29);case 32:case"end":return t.stop()}}),t,null,[[14,26,29,32]])})))),this.options=t,this.options.simulate=null===(r=this.options.simulate)||void 0===r||r,this.server=new o.Server(this.options.rpcUrl,{allowHttp:null!==(s=this.options.allowHttp)&&void 0!==s&&s})}return le(e,[{key:"toJSON",value:function(){var e;return JSON.stringify({method:this.options.method,tx:null===(e=this.built)||void 0===e?void 0:e.toXDR(),simulationResult:{auth:this.simulationData.result.auth.map((function(e){return e.toXDR("base64")})),retval:this.simulationData.result.retval.toXDR("base64")},simulationTransactionData:this.simulationData.transactionData.toXDR("base64")})}},{key:"toXDR",value:function(){var e;if(!this.built)throw new Error("Transaction has not yet been simulated; call `AssembledTransaction.simulate` first.");return null===(e=this.built)||void 0===e?void 0:e.toEnvelope().toXDR("base64")}},{key:"handleWalletError",value:function(t){if(t){var r=t.message,n=t.code,o="".concat(r).concat(t.ext?" (".concat(t.ext.join(", "),")"):"");switch(n){case-1:throw new e.Errors.InternalWalletError(o);case-2:throw new e.Errors.ExternalServiceError(o);case-3:throw new e.Errors.InvalidClientRequest(o);case-4:throw new e.Errors.UserRejected(o);default:throw new Error("Unhandled error: ".concat(o))}}}},{key:"simulationData",get:function(){var t;if(this.simulationResult&&this.simulationTransactionData)return{result:this.simulationResult,transactionData:this.simulationTransactionData};var r=this.simulation;if(!r)throw new e.Errors.NotYetSimulated("Transaction has not yet been simulated");if(i.j.isSimulationError(r))throw new e.Errors.SimulationFailed('Transaction simulation failed: "'.concat(r.error,'"'));if(i.j.isSimulationRestore(r))throw new e.Errors.ExpiredState("You need to restore some contract state before you can invoke this method.\nYou can set `restore` to true in the method options in order to automatically restore the contract state when needed.");return this.simulationResult=null!==(t=r.result)&&void 0!==t?t:{auth:[],retval:n.xdr.ScVal.scvVoid()},this.simulationTransactionData=r.transactionData.build(),{result:this.simulationResult,transactionData:this.simulationTransactionData}}},{key:"result",get:function(){try{if(!this.simulationData.result)throw new Error("No simulation result!");return this.options.parseResultXdr(this.simulationData.result.retval)}catch(r){if("object"!==v(t=r)||null===t||!("toString"in t))throw r;var e=this.parseError(r.toString());if(e)return e;throw r}var t}},{key:"parseError",value:function(e){if(this.options.errorTypes){var t=e.match(E);if(t){var r=parseInt(t[1],10),n=this.options.errorTypes[r];if(n)return new d(n)}}}},{key:"send",value:(u=se(re().mark((function e(){var t;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.signed){e.next=2;break}throw new Error("The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead.");case 2:return e.next=4,K.init(this);case 4:return t=e.sent,e.abrupt("return",t);case 6:case"end":return e.stop()}}),e,this)}))),function(){return u.apply(this,arguments)})},{key:"isReadCall",get:function(){var e=this.simulationData.result.auth.length,t=this.simulationData.transactionData.resources().footprint().readWrite().length;return 0===e&&0===t}},{key:"restoreFootprint",value:(s=se(re().mark((function t(r,n){var o,i,a;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this.options.signTransaction){t.next=2;break}throw new Error("For automatic restore to work you must provide a signTransaction function when initializing your Client");case 2:if(null===(o=n)||void 0===o){t.next=6;break}t.t0=o,t.next=9;break;case 6:return t.next=8,T(this.options,this.server);case 8:t.t0=t.sent;case 9:return n=t.t0,t.next=12,e.buildFootprintRestoreTransaction(Z({},this.options),r.transactionData,n,r.minResourceFee);case 12:return i=t.sent,t.next=15,i.signAndSend();case 15:if((a=t.sent).getTransactionResponse){t.next=18;break}throw new e.Errors.RestorationFailure("The attempt at automatic restore failed. \n".concat(JSON.stringify(a)));case 18:return t.abrupt("return",a.getTransactionResponse);case 19:case"end":return t.stop()}}),t,this)}))),function(e,t){return s.apply(this,arguments)})}],[{key:"fromJSON",value:function(t,r){var o=r.tx,i=r.simulationResult,a=r.simulationTransactionData,s=new e(t);return s.built=n.TransactionBuilder.fromXDR(o,t.networkPassphrase),s.simulationResult={auth:i.auth.map((function(e){return n.xdr.SorobanAuthorizationEntry.fromXDR(e,"base64")})),retval:n.xdr.ScVal.fromXDR(i.retval,"base64")},s.simulationTransactionData=n.xdr.SorobanTransactionData.fromXDR(a,"base64"),s}},{key:"fromXDR",value:function(t,r,o){var i,a=n.xdr.TransactionEnvelope.fromXDR(r,"base64"),s=n.TransactionBuilder.fromXDR(a,t.networkPassphrase),u=s.operations[0];if(null==u||null===(i=u.func)||void 0===i||!i.value||"function"!=typeof u.func.value)throw new Error("Could not extract the method from the transaction envelope.");var c=u.func.value();if(null==c||!c.functionName)throw new Error("Could not extract the method name from the transaction envelope.");var l=c.functionName().toString("utf-8"),f=new e(Z(Z({},t),{},{method:l,parseResultXdr:function(e){return o.funcResToNative(l,e)}}));return f.built=s,f}},{key:"build",value:function(t){var r,o=new n.Contract(t.contractId);return e.buildWithOp(o.call.apply(o,[t.method].concat(ne(null!==(r=t.args)&&void 0!==r?r:[]))),t)}},{key:"buildWithOp",value:(r=se(re().mark((function t(r,o){var i,a,s,u;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return s=new e(o),t.next=3,T(o,s.server);case 3:if(u=t.sent,s.raw=new n.TransactionBuilder(u,{fee:null!==(i=o.fee)&&void 0!==i?i:n.BASE_FEE,networkPassphrase:o.networkPassphrase}).setTimeout(null!==(a=o.timeoutInSeconds)&&void 0!==a?a:h).addOperation(r),!o.simulate){t.next=8;break}return t.next=8,s.simulate();case 8:return t.abrupt("return",s);case 9:case"end":return t.stop()}}),t)}))),function(e,t){return r.apply(this,arguments)})},{key:"buildFootprintRestoreTransaction",value:(t=se(re().mark((function t(r,o,i,a){var s,u;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return(u=new e(r)).raw=new n.TransactionBuilder(i,{fee:a,networkPassphrase:r.networkPassphrase}).setSorobanData(o instanceof n.SorobanDataBuilder?o.build():o).addOperation(n.Operation.restoreFootprint({})).setTimeout(null!==(s=r.timeoutInSeconds)&&void 0!==s?s:h),t.next=4,u.simulate({restore:!1});case 4:return t.abrupt("return",u);case 5:case"end":return t.stop()}}),t)}))),function(e,r,n,o){return t.apply(this,arguments)})}]);var t,r,s,u}();fe(de,"Errors",{ExpiredState:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),RestorationFailure:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NeedsMoreSignatures:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NoSignatureNeeded:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NoUnsignedNonInvokerAuthEntries:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NoSigner:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NotYetSimulated:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),FakeAccount:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),SimulationFailed:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),InternalWalletError:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),ExternalServiceError:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),InvalidClientRequest:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),UserRejected:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error))});var he=r(8287).Buffer;function ye(e){return ye="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ye(e)}function me(){me=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,_=S&&S(S(j([])));_&&_!==r&&n.call(_,a)&&(w=_);var E=b.prototype=v.prototype=Object.create(w);function k(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==ye(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function ve(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function ge(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){ve(i,n,o,a,s,"next",e)}function s(e){ve(i,n,o,a,s,"throw",e)}a(void 0)}))}}var be=function(e,t){return{signTransaction:(o=ge(me().mark((function r(o,i){var a;return me().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return(a=n.TransactionBuilder.fromXDR(o,(null==i?void 0:i.networkPassphrase)||t)).sign(e),r.abrupt("return",{signedTxXdr:a.toXDR(),signerAddress:e.publicKey()});case 3:case"end":return r.stop()}}),r)}))),function(e,t){return o.apply(this,arguments)}),signAuthEntry:(r=ge(me().mark((function t(r){var o;return me().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return o=e.sign((0,n.hash)(he.from(r,"base64"))).toString("base64"),t.abrupt("return",{signedAuthEntry:o,signerAddress:e.publicKey()});case 2:case"end":return t.stop()}}),t)}))),function(e){return r.apply(this,arguments)})};var r,o},we=r(8287).Buffer;function Se(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _e(e){for(var t=1;te.length)&&(t=e.length);for(var r=0,n=Array(t);r0&&(o.required=r),o}var Ce,Le,Be,Ne=(Ce=function e(t){if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Te(this,"entries",[]),0===t.length)throw new Error("Contract spec must have at least one entry");var r=t[0];this.entries="string"==typeof r?t.map((function(e){return n.xdr.ScSpecEntry.fromXDR(e,"base64")})):t},Le=[{key:"funcs",value:function(){return this.entries.filter((function(e){return e.switch().value===n.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value})).map((function(e){return e.functionV0()}))}},{key:"getFunc",value:function(e){var t=this.findEntry(e);if(t.switch().value!==n.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value)throw new Error("".concat(e," is not a function"));return t.functionV0()}},{key:"funcArgsToScVals",value:function(e,t){var r=this;return this.getFunc(e).inputs().map((function(e){return r.nativeToScVal(function(e,t){var r=t.name().toString(),n=Object.entries(e).find((function(e){return xe(e,1)[0]===r}));if(!n)throw new Error("Missing field ".concat(r));return n[1]}(t,e),e.type())}))}},{key:"funcResToNative",value:function(e,t){var r="string"==typeof t?n.xdr.ScVal.fromXDR(t,"base64"):t,o=this.getFunc(e).outputs();if(0===o.length){var i=r.switch();if(i.value!==n.xdr.ScValType.scvVoid().value)throw new Error("Expected void, got ".concat(i.name));return null}if(o.length>1)throw new Error("Multiple outputs not supported");var a=o[0];return a.switch().value===n.xdr.ScSpecType.scSpecTypeResult().value?new p(this.scValToNative(r,a.result().okType())):this.scValToNative(r,a)}},{key:"findEntry",value:function(e){var t=this.entries.find((function(t){return t.value().name().toString()===e}));if(!t)throw new Error("no such entry: ".concat(e));return t}},{key:"nativeToScVal",value:function(e,t){var r=this,o=t.switch(),i=o.value;if(o.value===n.xdr.ScSpecType.scSpecTypeUdt().value){var a=t.udt();return this.nativeToUdt(e,a.name().toString())}if(i===n.xdr.ScSpecType.scSpecTypeOption().value){var s=t.option();return void 0===e?n.xdr.ScVal.scvVoid():this.nativeToScVal(e,s.valueType())}switch(Ee(e)){case"object":var u,c,l;if(null===e){if(i===n.xdr.ScSpecType.scSpecTypeVoid().value)return n.xdr.ScVal.scvVoid();throw new TypeError("Type ".concat(t," was not void, but value was null"))}if(e instanceof n.xdr.ScVal)return e;if(e instanceof n.Address){if(t.switch().value!==n.xdr.ScSpecType.scSpecTypeAddress().value)throw new TypeError("Type ".concat(t," was not address, but value was Address"));return e.toScVal()}if(e instanceof n.Contract){if(t.switch().value!==n.xdr.ScSpecType.scSpecTypeAddress().value)throw new TypeError("Type ".concat(t," was not address, but value was Address"));return e.address().toScVal()}if(e instanceof Uint8Array||we.isBuffer(e)){var f=Uint8Array.from(e);switch(i){case n.xdr.ScSpecType.scSpecTypeBytesN().value:var p=t.bytesN();if(f.length!==p.n())throw new TypeError("expected ".concat(p.n()," bytes, but got ").concat(f.length));return n.xdr.ScVal.scvBytes(f);case n.xdr.ScSpecType.scSpecTypeBytes().value:return n.xdr.ScVal.scvBytes(f);default:throw new TypeError("invalid type (".concat(t,") specified for Bytes and BytesN"))}}if(Array.isArray(e))switch(i){case n.xdr.ScSpecType.scSpecTypeVec().value:var d=t.vec().elementType();return n.xdr.ScVal.scvVec(e.map((function(e){return r.nativeToScVal(e,d)})));case n.xdr.ScSpecType.scSpecTypeTuple().value:var h=t.tuple().valueTypes();if(e.length!==h.length)throw new TypeError("Tuple expects ".concat(h.length," values, but ").concat(e.length," were provided"));return n.xdr.ScVal.scvVec(e.map((function(e,t){return r.nativeToScVal(e,h[t])})));case n.xdr.ScSpecType.scSpecTypeMap().value:var y=t.map(),m=y.keyType(),v=y.valueType();return n.xdr.ScVal.scvMap(e.map((function(e){var t=r.nativeToScVal(e[0],m),o=r.nativeToScVal(e[1],v);return new n.xdr.ScMapEntry({key:t,val:o})})));default:throw new TypeError("Type ".concat(t," was not vec, but value was Array"))}if(e.constructor===Map){if(i!==n.xdr.ScSpecType.scSpecTypeMap().value)throw new TypeError("Type ".concat(t," was not map, but value was Map"));for(var g=t.map(),b=[],w=e.entries(),S=w.next();!S.done;){var _=xe(S.value,2),E=_[0],k=_[1],T=this.nativeToScVal(E,g.keyType()),O=this.nativeToScVal(k,g.valueType());b.push(new n.xdr.ScMapEntry({key:T,val:O})),S=w.next()}return n.xdr.ScVal.scvMap(b)}if("Object"!==(null!==(u=null===(c=e.constructor)||void 0===c?void 0:c.name)&&void 0!==u?u:""))throw new TypeError("cannot interpret ".concat(null===(l=e.constructor)||void 0===l?void 0:l.name," value as ScVal (").concat(JSON.stringify(e),")"));throw new TypeError("Received object ".concat(e," did not match the provided type ").concat(t));case"number":case"bigint":switch(i){case n.xdr.ScSpecType.scSpecTypeU32().value:return n.xdr.ScVal.scvU32(e);case n.xdr.ScSpecType.scSpecTypeI32().value:return n.xdr.ScVal.scvI32(e);case n.xdr.ScSpecType.scSpecTypeU64().value:case n.xdr.ScSpecType.scSpecTypeI64().value:case n.xdr.ScSpecType.scSpecTypeU128().value:case n.xdr.ScSpecType.scSpecTypeI128().value:case n.xdr.ScSpecType.scSpecTypeU256().value:case n.xdr.ScSpecType.scSpecTypeI256().value:var x=o.name.substring(10).toLowerCase();return new n.XdrLargeInt(x,e).toScVal();default:throw new TypeError("invalid type (".concat(t,") specified for integer"))}case"string":return function(e,t){switch(t.value){case n.xdr.ScSpecType.scSpecTypeString().value:return n.xdr.ScVal.scvString(e);case n.xdr.ScSpecType.scSpecTypeSymbol().value:return n.xdr.ScVal.scvSymbol(e);case n.xdr.ScSpecType.scSpecTypeAddress().value:var r=n.Address.fromString(e);return n.xdr.ScVal.scvAddress(r.toScAddress());case n.xdr.ScSpecType.scSpecTypeU64().value:return new n.XdrLargeInt("u64",e).toScVal();case n.xdr.ScSpecType.scSpecTypeI64().value:return new n.XdrLargeInt("i64",e).toScVal();case n.xdr.ScSpecType.scSpecTypeU128().value:return new n.XdrLargeInt("u128",e).toScVal();case n.xdr.ScSpecType.scSpecTypeI128().value:return new n.XdrLargeInt("i128",e).toScVal();case n.xdr.ScSpecType.scSpecTypeU256().value:return new n.XdrLargeInt("u256",e).toScVal();case n.xdr.ScSpecType.scSpecTypeI256().value:return new n.XdrLargeInt("i256",e).toScVal();case n.xdr.ScSpecType.scSpecTypeBytes().value:case n.xdr.ScSpecType.scSpecTypeBytesN().value:return n.xdr.ScVal.scvBytes(we.from(e,"base64"));default:throw new TypeError("invalid type ".concat(t.name," specified for string value"))}}(e,o);case"boolean":if(i!==n.xdr.ScSpecType.scSpecTypeBool().value)throw TypeError("Type ".concat(t," was not bool, but value was bool"));return n.xdr.ScVal.scvBool(e);case"undefined":if(!t)return n.xdr.ScVal.scvVoid();switch(i){case n.xdr.ScSpecType.scSpecTypeVoid().value:case n.xdr.ScSpecType.scSpecTypeOption().value:return n.xdr.ScVal.scvVoid();default:throw new TypeError("Type ".concat(t," was not void, but value was undefined"))}case"function":return this.nativeToScVal(e(),t);default:throw new TypeError("failed to convert typeof ".concat(Ee(e)," (").concat(e,")"))}}},{key:"nativeToUdt",value:function(e,t){var r=this.findEntry(t);switch(r.switch()){case n.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0():if("number"!=typeof e)throw new TypeError("expected number for enum ".concat(t,", but got ").concat(Ee(e)));return this.nativeToEnum(e,r.udtEnumV0());case n.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.nativeToStruct(e,r.udtStructV0());case n.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.nativeToUnion(e,r.udtUnionV0());default:throw new Error("failed to parse udt ".concat(t))}}},{key:"nativeToUnion",value:function(e,t){var r=this,o=e.tag,i=t.cases().find((function(e){return e.value().name().toString()===o}));if(!i)throw new TypeError("no such enum entry: ".concat(o," in ").concat(t));var a=n.xdr.ScVal.scvSymbol(o);switch(i.switch()){case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0():return n.xdr.ScVal.scvVec([a]);case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0():var s=i.tupleCase().type();if(Array.isArray(e.values)){if(e.values.length!==s.length)throw new TypeError("union ".concat(t," expects ").concat(s.length," values, but got ").concat(e.values.length));var u=e.values.map((function(e,t){return r.nativeToScVal(e,s[t])}));return u.unshift(a),n.xdr.ScVal.scvVec(u)}throw new Error("failed to parse union case ".concat(i," with ").concat(e));default:throw new Error("failed to parse union ".concat(t," with ").concat(e))}}},{key:"nativeToStruct",value:function(e,t){var r=this,o=t.fields();if(o.some(Pe)){if(!o.every(Pe))throw new Error("mixed numeric and non-numeric field names are not allowed");return n.xdr.ScVal.scvVec(o.map((function(t,n){return r.nativeToScVal(e[n],o[n].type())})))}return n.xdr.ScVal.scvMap(o.map((function(t){var o=t.name().toString();return new n.xdr.ScMapEntry({key:r.nativeToScVal(o,n.xdr.ScSpecTypeDef.scSpecTypeSymbol()),val:r.nativeToScVal(e[o],t.type())})})))}},{key:"nativeToEnum",value:function(e,t){if(t.cases().some((function(t){return t.value()===e})))return n.xdr.ScVal.scvU32(e);throw new TypeError("no such enum entry: ".concat(e," in ").concat(t))}},{key:"scValStrToNative",value:function(e,t){return this.scValToNative(n.xdr.ScVal.fromXDR(e,"base64"),t)}},{key:"scValToNative",value:function(e,t){var r=this,o=t.switch(),i=o.value;if(i===n.xdr.ScSpecType.scSpecTypeUdt().value)return this.scValUdtToNative(e,t.udt());switch(e.switch().value){case n.xdr.ScValType.scvVoid().value:return;case n.xdr.ScValType.scvU64().value:case n.xdr.ScValType.scvI64().value:case n.xdr.ScValType.scvU128().value:case n.xdr.ScValType.scvI128().value:case n.xdr.ScValType.scvU256().value:case n.xdr.ScValType.scvI256().value:return(0,n.scValToBigInt)(e);case n.xdr.ScValType.scvVec().value:if(i===n.xdr.ScSpecType.scSpecTypeVec().value){var a,s=t.vec();return(null!==(a=e.vec())&&void 0!==a?a:[]).map((function(e){return r.scValToNative(e,s.elementType())}))}if(i===n.xdr.ScSpecType.scSpecTypeTuple().value){var u,c=t.tuple().valueTypes();return(null!==(u=e.vec())&&void 0!==u?u:[]).map((function(e,t){return r.scValToNative(e,c[t])}))}throw new TypeError("Type ".concat(t," was not vec, but ").concat(e," is"));case n.xdr.ScValType.scvAddress().value:return n.Address.fromScVal(e).toString();case n.xdr.ScValType.scvMap().value:var l,f=null!==(l=e.map())&&void 0!==l?l:[];if(i===n.xdr.ScSpecType.scSpecTypeMap().value){var p=t.map(),d=p.keyType(),h=p.valueType();return f.map((function(e){return[r.scValToNative(e.key(),d),r.scValToNative(e.val(),h)]}))}throw new TypeError("ScSpecType ".concat(o.name," was not map, but ").concat(JSON.stringify(e,null,2)," is"));case n.xdr.ScValType.scvBool().value:case n.xdr.ScValType.scvU32().value:case n.xdr.ScValType.scvI32().value:case n.xdr.ScValType.scvBytes().value:return e.value();case n.xdr.ScValType.scvString().value:case n.xdr.ScValType.scvSymbol().value:var y;if(i!==n.xdr.ScSpecType.scSpecTypeString().value&&i!==n.xdr.ScSpecType.scSpecTypeSymbol().value)throw new Error("ScSpecType ".concat(o.name," was not string or symbol, but ").concat(JSON.stringify(e,null,2)," is"));return null===(y=e.value())||void 0===y?void 0:y.toString();case n.xdr.ScValType.scvTimepoint().value:case n.xdr.ScValType.scvDuration().value:return(0,n.scValToBigInt)(n.xdr.ScVal.scvU64(e.u64()));default:throw new TypeError("failed to convert ".concat(JSON.stringify(e,null,2)," to native type from type ").concat(o.name))}}},{key:"scValUdtToNative",value:function(e,t){var r=this.findEntry(t.name().toString());switch(r.switch()){case n.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0():return this.enumToNative(e);case n.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.structToNative(e,r.udtStructV0());case n.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.unionToNative(e,r.udtUnionV0());default:throw new Error("failed to parse udt ".concat(t.name().toString(),": ").concat(r))}}},{key:"unionToNative",value:function(e,t){var r=this,o=e.vec();if(!o)throw new Error("".concat(JSON.stringify(e,null,2)," is not a vec"));if(0===o.length&&0!==t.cases.length)throw new Error("".concat(e," has length 0, but the there are at least one case in the union"));var i=o[0].sym().toString();if(o[0].switch().value!==n.xdr.ScValType.scvSymbol().value)throw new Error("{vec[0]} is not a symbol");var a=t.cases().find(function(e){return function(t){switch(t.switch().value){case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value:return t.tupleCase().name().toString()===e;case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value:return t.voidCase().name().toString()===e;default:return!1}}}(i));if(!a)throw new Error("failed to find entry ".concat(i," in union {udt.name().toString()}"));var s={tag:i};if(a.switch().value===n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value){var u=a.tupleCase().type().map((function(e,t){return r.scValToNative(o[t+1],e)}));s.values=u}return s}},{key:"structToNative",value:function(e,t){var r,n,o=this,i={},a=t.fields();return a.some(Pe)?null===(n=e.vec())||void 0===n?void 0:n.map((function(e,t){return o.scValToNative(e,a[t].type())})):(null===(r=e.map())||void 0===r||r.forEach((function(e,t){var r=a[t];i[r.name().toString()]=o.scValToNative(e.val(),r.type())})),i)}},{key:"enumToNative",value:function(e){if(e.switch().value!==n.xdr.ScValType.scvU32().value)throw new Error("Enum must have a u32 value");return e.u32()}},{key:"errorCases",value:function(){return this.entries.filter((function(e){return e.switch().value===n.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value})).flatMap((function(e){return e.value().cases()}))}},{key:"jsonSchema",value:function(e){var t={};this.entries.forEach((function(e){switch(e.switch().value){case n.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0().value:var r=e.udtEnumV0();t[r.name().toString()]=function(e){var t=e.doc().toString(),r=e.cases(),n=[];r.forEach((function(e){var t=e.name().toString(),r=e.doc().toString();n.push({description:r,title:t,enum:[e.value()],type:"number"})}));var o={oneOf:n};return t.length>0&&(o.description=t),o}(r);break;case n.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0().value:var o=e.udtStructV0();t[o.name().toString()]=function(e){var t=e.fields();if(t.some(Pe)){if(!t.every(Pe))throw new Error("mixed numeric and non-numeric field names are not allowed");return{type:"array",items:t.map((function(e,r){return je(t[r].type())})),minItems:t.length,maxItems:t.length}}var r=e.doc().toString(),n=Ie(t),o=n.properties,i=n.required;return o.additionalProperties=!1,{description:r,properties:o,required:i,type:"object"}}(o);break;case n.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0().value:var i=e.udtUnionV0();t[i.name().toString()]=function(e){var t=e.doc().toString(),r=e.cases(),o=[];r.forEach((function(e){switch(e.switch().value){case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value:var t=e.voidCase().name().toString();o.push({type:"object",title:t,properties:{tag:t},additionalProperties:!1,required:["tag"]});break;case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value:var r=e.tupleCase(),i=r.name().toString();o.push({type:"object",title:i,properties:{tag:i,values:{type:"array",items:r.type().map(je)}},required:["tag","values"],additionalProperties:!1})}}));var i={oneOf:o};return t.length>0&&(i.description=t),i}(i);break;case n.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value:var a=e.functionV0(),s=a.name().toString(),u=function(e){var t=Ie(e.inputs()),r=t.properties,o=t.required,i={additionalProperties:!1,properties:r,type:"object"};(null==o?void 0:o.length)>0&&(i.required=o);var a={properties:{args:i}},s=e.outputs(),u=s.length>0?je(s[0]):je(n.xdr.ScSpecTypeDef.scSpecTypeVoid()),c=e.doc().toString();return c.length>0&&(a.description=c),a.additionalProperties=!1,u.additionalProperties=!1,{input:a,output:u}}(a),c=u.input;t[s]=c;case n.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value:}}));var r={$schema:"http://json-schema.org/draft-07/schema#",definitions:_e(_e({},Re),t)};return e&&(r.$ref="#/definitions/".concat(e)),r}}],Le&&ke(Ce.prototype,Le),Be&&ke(Ce,Be),Object.defineProperty(Ce,"prototype",{writable:!1}),Ce),Ue=r(8287).Buffer;function Me(e){return Me="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Me(e)}var De=["method"],Fe=["wasmHash","salt","format","fee","timeoutInSeconds","simulate"];function Ve(){Ve=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,_=S&&S(S(j([])));_&&_!==r&&n.call(_,a)&&(w=_);var E=b.prototype=v.prototype=Object.create(w);function k(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==Me(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function qe(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Ke(e){for(var t=1;t2&&void 0!==l[2]?l[2]:"hex",r&&r.rpcUrl){e.next=3;break}throw new TypeError("options must contain rpcUrl");case 3:return i=r.rpcUrl,a=r.allowHttp,s={allowHttp:a},u=new o.Server(i,s),e.next=8,u.getContractWasmByHash(t,n);case 8:return c=e.sent,e.abrupt("return",Ye(c));case 10:case"end":return e.stop()}}),e)}))),et.apply(this,arguments)}var tt=function(){function e(t,r){var n=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Xe(this,"txFromJSON",(function(e){var t=JSON.parse(e),r=t.method,o=He(t,De);return de.fromJSON(Ke(Ke({},n.options),{},{method:r,parseResultXdr:function(e){return n.spec.funcResToNative(r,e)}}),o)})),Xe(this,"txFromXDR",(function(e){return de.fromXDR(n.options,e,n.spec)})),this.spec=t,this.options=r,this.spec.funcs().forEach((function(e){var o=e.name().toString();if(o!==Qe){var i=function(e,n){return de.build(Ke(Ke(Ke({method:o,args:e&&t.funcArgsToScVals(o,e)},r),n),{},{errorTypes:t.errorCases().reduce((function(e,t){return Ke(Ke({},e),{},Xe({},t.value(),{message:t.doc().toString()}))}),{}),parseResultXdr:function(e){return t.funcResToNative(o,e)}}))};n[o]=0===t.getFunc(o).inputs().length?function(e){return i(void 0,e)}:i}}))}return function(e,t,r){return t&&ze(e.prototype,t),r&&ze(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}(e,null,[{key:"deploy",value:(a=$e(Ve().mark((function t(r,o){var i,a,s,u,c,l,f,p,d;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=o.wasmHash,a=o.salt,s=o.format,u=o.fee,c=o.timeoutInSeconds,l=o.simulate,f=He(o,Fe),t.next=3,Ze(i,f,s);case 3:return p=t.sent,d=n.Operation.createCustomContract({address:new n.Address(o.publicKey),wasmHash:"string"==typeof i?Ue.from(i,null!=s?s:"hex"):i,salt:a,constructorArgs:r?p.funcArgsToScVals(Qe,r):[]}),t.abrupt("return",de.buildWithOp(d,Ke(Ke({fee:u,timeoutInSeconds:c,simulate:l},f),{},{contractId:"ignored",method:Qe,parseResultXdr:function(t){return new e(p,Ke(Ke({},f),{},{contractId:n.Address.fromScVal(t).toString()}))}})));case 6:case"end":return t.stop()}}),t)}))),function(e,t){return a.apply(this,arguments)})},{key:"fromWasmHash",value:(i=$e(Ve().mark((function t(r,n){var i,a,s,u,c,l,f=arguments;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i=f.length>2&&void 0!==f[2]?f[2]:"hex",n&&n.rpcUrl){t.next=3;break}throw new TypeError("options must contain rpcUrl");case 3:return a=n.rpcUrl,s=n.allowHttp,u={allowHttp:s},c=new o.Server(a,u),t.next=8,c.getContractWasmByHash(r,i);case 8:return l=t.sent,t.abrupt("return",e.fromWasm(l,n));case 10:case"end":return t.stop()}}),t)}))),function(e,t){return i.apply(this,arguments)})},{key:"fromWasm",value:(r=$e(Ve().mark((function t(r,n){var o;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,Ye(r);case 2:return o=t.sent,t.abrupt("return",new e(o,n));case 4:case"end":return t.stop()}}),t)}))),function(e,t){return r.apply(this,arguments)})},{key:"from",value:(t=$e(Ve().mark((function t(r){var n,i,a,s,u,c;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(r&&r.rpcUrl&&r.contractId){t.next=2;break}throw new TypeError("options must contain rpcUrl and contractId");case 2:return n=r.rpcUrl,i=r.contractId,a=r.allowHttp,s={allowHttp:a},u=new o.Server(n,s),t.next=7,u.getContractWasmByContractId(i);case 7:return c=t.sent,t.abrupt("return",e.fromWasm(c,r));case 9:case"end":return t.stop()}}),t)}))),function(e){return t.apply(this,arguments)})}]);var t,r,i,a}()},5976:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rH,v7:()=>x,nS:()=>B,Dr:()=>f,m_:()=>b});var f=function(e){function t(e,r){var n;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var o=(this instanceof t?this.constructor:void 0).prototype;return(n=a(this,t,[e])).__proto__=o,n.constructor=t,n.response=r,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&c(e,t)}(t,e),r=t,(n=[{key:"getResponse",value:function(){return this.response}}])&&o(r.prototype,n),i&&o(r,i),Object.defineProperty(r,"prototype",{writable:!1}),r;var r,n,i}(s(Error));function p(e){return p="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},p(e)}function d(e,t){for(var r=0;r{"use strict";r.r(t),r.d(t,{Api:()=>{},FEDERATION_RESPONSE_MAX_SIZE:()=>g,Server:()=>b});var n=r(356),o=r(4193),i=r.n(o),a=r(8732),s=r(5976),u=r(3898),c=r(6371);function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return p(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?p(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),j(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:C(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function h(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function y(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){h(i,n,o,a,s,"next",e)}function s(e){h(i,n,o,a,s,"throw",e)}a(void 0)}))}}function m(e,t){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.serverURL=i()(t),this.domain=r;var o=void 0===n.allowHttp?a.T.isAllowHttp():n.allowHttp;if(this.timeout=void 0===n.timeout?a.T.getTimeout():n.timeout,"https"!==this.serverURL.protocol()&&!o)throw new Error("Cannot connect to insecure federation server")}return t=e,r=[{key:"resolveAddress",value:(w=y(d().mark((function e(t){var r,n;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t,!(t.indexOf("*")<0)){e.next=5;break}if(this.domain){e.next=4;break}return e.abrupt("return",Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object.")));case 4:r="".concat(t,"*").concat(this.domain);case 5:return n=this.serverURL.query({type:"name",q:r}),e.abrupt("return",this._sendRequest(n));case 7:case"end":return e.stop()}}),e,this)}))),function(e){return w.apply(this,arguments)})},{key:"resolveAccountId",value:(b=y(d().mark((function e(t){var r;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.serverURL.query({type:"id",q:t}),e.abrupt("return",this._sendRequest(r));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return b.apply(this,arguments)})},{key:"resolveTransactionId",value:(v=y(d().mark((function e(t){var r;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.serverURL.query({type:"txid",q:t}),e.abrupt("return",this._sendRequest(r));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return v.apply(this,arguments)})},{key:"_sendRequest",value:(h=y(d().mark((function e(t){var r;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.timeout,e.abrupt("return",c.ok.get(t.toString(),{maxContentLength:g,timeout:r}).then((function(e){if(void 0!==e.data.memo&&"string"!=typeof e.data.memo)throw new Error("memo value should be of type string");return e.data})).catch((function(e){if(e instanceof Error){if(e.message.match(/^maxContentLength size/))throw new Error("federation response exceeds allowed size of ".concat(g));return Promise.reject(e)}return Promise.reject(new s.nS("Server query failed. Server responded: ".concat(e.status," ").concat(e.statusText),e.data))})));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return h.apply(this,arguments)})}],o=[{key:"resolve",value:(p=y(d().mark((function t(r){var o,i,a,s,u,c=arguments;return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(o=c.length>1&&void 0!==c[1]?c[1]:{},!(r.indexOf("*")<0)){t.next=5;break}if(n.StrKey.isValidEd25519PublicKey(r)){t.next=4;break}return t.abrupt("return",Promise.reject(new Error("Invalid Account ID")));case 4:return t.abrupt("return",Promise.resolve({account_id:r}));case 5:if(i=r.split("*"),a=f(i,2),s=a[1],2===i.length&&s){t.next=9;break}return t.abrupt("return",Promise.reject(new Error("Invalid Stellar address")));case 9:return t.next=11,e.createForDomain(s,o);case 11:return u=t.sent,t.abrupt("return",u.resolveAddress(r));case 13:case"end":return t.stop()}}),t)}))),function(e){return p.apply(this,arguments)})},{key:"createForDomain",value:(l=y(d().mark((function t(r){var n,o,i=arguments;return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=i.length>1&&void 0!==i[1]?i[1]:{},t.next=3,u.Resolver.resolve(r,n);case 3:if((o=t.sent).FEDERATION_SERVER){t.next=6;break}return t.abrupt("return",Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field")));case 6:return t.abrupt("return",new e(o.FEDERATION_SERVER,r,n));case 7:case"end":return t.stop()}}),t)}))),function(e){return l.apply(this,arguments)})}],r&&m(t.prototype,r),o&&m(t,o),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,o,l,p,h,v,b,w}()},8242:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Api:()=>{}})},8733:(e,t,r)=>{"use strict";var n;r.r(t),r.d(t,{AccountResponse:()=>m,AxiosClient:()=>W,HorizonApi:()=>n,SERVER_TIME_MAP:()=>z,Server:()=>Yr,ServerApi:()=>i,default:()=>Jr,getCurrentServerTime:()=>$}),function(e){var t=function(e){return e.constantProduct="constant_product",e}({});e.LiquidityPoolType=t;var r=function(e){return e.createAccount="create_account",e.payment="payment",e.pathPayment="path_payment_strict_receive",e.createPassiveOffer="create_passive_sell_offer",e.manageOffer="manage_sell_offer",e.setOptions="set_options",e.changeTrust="change_trust",e.allowTrust="allow_trust",e.accountMerge="account_merge",e.inflation="inflation",e.manageData="manage_data",e.bumpSequence="bump_sequence",e.manageBuyOffer="manage_buy_offer",e.pathPaymentStrictSend="path_payment_strict_send",e.createClaimableBalance="create_claimable_balance",e.claimClaimableBalance="claim_claimable_balance",e.beginSponsoringFutureReserves="begin_sponsoring_future_reserves",e.endSponsoringFutureReserves="end_sponsoring_future_reserves",e.revokeSponsorship="revoke_sponsorship",e.clawback="clawback",e.clawbackClaimableBalance="clawback_claimable_balance",e.setTrustLineFlags="set_trust_line_flags",e.liquidityPoolDeposit="liquidity_pool_deposit",e.liquidityPoolWithdraw="liquidity_pool_withdraw",e.invokeHostFunction="invoke_host_function",e.bumpFootprintExpiration="bump_footprint_expiration",e.restoreFootprint="restore_footprint",e}({});e.OperationResponseType=r;var n=function(e){return e[e.createAccount=0]="createAccount",e[e.payment=1]="payment",e[e.pathPayment=2]="pathPayment",e[e.createPassiveOffer=3]="createPassiveOffer",e[e.manageOffer=4]="manageOffer",e[e.setOptions=5]="setOptions",e[e.changeTrust=6]="changeTrust",e[e.allowTrust=7]="allowTrust",e[e.accountMerge=8]="accountMerge",e[e.inflation=9]="inflation",e[e.manageData=10]="manageData",e[e.bumpSequence=11]="bumpSequence",e[e.manageBuyOffer=12]="manageBuyOffer",e[e.pathPaymentStrictSend=13]="pathPaymentStrictSend",e[e.createClaimableBalance=14]="createClaimableBalance",e[e.claimClaimableBalance=15]="claimClaimableBalance",e[e.beginSponsoringFutureReserves=16]="beginSponsoringFutureReserves",e[e.endSponsoringFutureReserves=17]="endSponsoringFutureReserves",e[e.revokeSponsorship=18]="revokeSponsorship",e[e.clawback=19]="clawback",e[e.clawbackClaimableBalance=20]="clawbackClaimableBalance",e[e.setTrustLineFlags=21]="setTrustLineFlags",e[e.liquidityPoolDeposit=22]="liquidityPoolDeposit",e[e.liquidityPoolWithdraw=23]="liquidityPoolWithdraw",e[e.invokeHostFunction=24]="invokeHostFunction",e[e.bumpFootprintExpiration=25]="bumpFootprintExpiration",e[e.restoreFootprint=26]="restoreFootprint",e}({});e.OperationResponseTypeI=n;var o=function(e){return e.TX_FAILED="tx_failed",e.TX_BAD_SEQ="tx_bad_seq",e.TX_BAD_AUTH="tx_bad_auth",e.TX_BAD_AUTH_EXTRA="tx_bad_auth_extra",e.TX_FEE_BUMP_INNER_SUCCESS="tx_fee_bump_inner_success",e.TX_FEE_BUMP_INNER_FAILED="tx_fee_bump_inner_failed",e.TX_NOT_SUPPORTED="tx_not_supported",e.TX_SUCCESS="tx_success",e.TX_TOO_EARLY="tx_too_early",e.TX_TOO_LATE="tx_too_late",e.TX_MISSING_OPERATION="tx_missing_operation",e.TX_INSUFFICIENT_BALANCE="tx_insufficient_balance",e.TX_NO_SOURCE_ACCOUNT="tx_no_source_account",e.TX_INSUFFICIENT_FEE="tx_insufficient_fee",e.TX_INTERNAL_ERROR="tx_internal_error",e}({});e.TransactionFailedResultCodes=o}(n||(n={}));var o,i,a=((o={})[o.account_created=0]="account_created",o[o.account_removed=1]="account_removed",o[o.account_credited=2]="account_credited",o[o.account_debited=3]="account_debited",o[o.account_thresholds_updated=4]="account_thresholds_updated",o[o.account_home_domain_updated=5]="account_home_domain_updated",o[o.account_flags_updated=6]="account_flags_updated",o[o.account_inflation_destination_updated=7]="account_inflation_destination_updated",o[o.signer_created=10]="signer_created",o[o.signer_removed=11]="signer_removed",o[o.signer_updated=12]="signer_updated",o[o.trustline_created=20]="trustline_created",o[o.trustline_removed=21]="trustline_removed",o[o.trustline_updated=22]="trustline_updated",o[o.trustline_authorized=23]="trustline_authorized",o[o.trustline_deauthorized=24]="trustline_deauthorized",o[o.trustline_authorized_to_maintain_liabilities=25]="trustline_authorized_to_maintain_liabilities",o[o.trustline_flags_updated=26]="trustline_flags_updated",o[o.offer_created=30]="offer_created",o[o.offer_removed=31]="offer_removed",o[o.offer_updated=32]="offer_updated",o[o.trade=33]="trade",o[o.data_created=40]="data_created",o[o.data_removed=41]="data_removed",o[o.data_updated=42]="data_updated",o[o.sequence_bumped=43]="sequence_bumped",o[o.claimable_balance_created=50]="claimable_balance_created",o[o.claimable_balance_claimant_created=51]="claimable_balance_claimant_created",o[o.claimable_balance_claimed=52]="claimable_balance_claimed",o[o.account_sponsorship_created=60]="account_sponsorship_created",o[o.account_sponsorship_updated=61]="account_sponsorship_updated",o[o.account_sponsorship_removed=62]="account_sponsorship_removed",o[o.trustline_sponsorship_created=63]="trustline_sponsorship_created",o[o.trustline_sponsorship_updated=64]="trustline_sponsorship_updated",o[o.trustline_sponsorship_removed=65]="trustline_sponsorship_removed",o[o.data_sponsorship_created=66]="data_sponsorship_created",o[o.data_sponsorship_updated=67]="data_sponsorship_updated",o[o.data_sponsorship_removed=68]="data_sponsorship_removed",o[o.claimable_balance_sponsorship_created=69]="claimable_balance_sponsorship_created",o[o.claimable_balance_sponsorship_updated=70]="claimable_balance_sponsorship_updated",o[o.claimable_balance_sponsorship_removed=71]="claimable_balance_sponsorship_removed",o[o.signer_sponsorship_created=72]="signer_sponsorship_created",o[o.signer_sponsorship_updated=73]="signer_sponsorship_updated",o[o.signer_sponsorship_removed=74]="signer_sponsorship_removed",o[o.claimable_balance_clawed_back=80]="claimable_balance_clawed_back",o[o.liquidity_pool_deposited=90]="liquidity_pool_deposited",o[o.liquidity_pool_withdrew=91]="liquidity_pool_withdrew",o[o.liquidity_pool_trade=92]="liquidity_pool_trade",o[o.liquidity_pool_created=93]="liquidity_pool_created",o[o.liquidity_pool_removed=94]="liquidity_pool_removed",o[o.liquidity_pool_revoked=95]="liquidity_pool_revoked",o[o.contract_credited=96]="contract_credited",o[o.contract_debited=97]="contract_debited",o);!function(e){e.EffectType=a;var t=function(e){return e.all="all",e.liquidityPools="liquidity_pool",e.orderbook="orderbook",e}({});e.TradeType=t;n.OperationResponseType,n.OperationResponseTypeI}(i||(i={}));var s=r(356);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return l(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?l(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r0||e===t?t:t-1}function P(e){for(var t,r,n=1,o=e.length,i=e[0]+"";nc^r?1:-1;for(s=(u=o.length)<(c=i.length)?u:c,a=0;ai[a]^r?1:-1;return u==c?0:u>c^r?1:-1}function j(e,t,r,n){if(er||e!==b(e))throw Error(w+(n||"Argument")+("number"==typeof e?er?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function I(e){var t=e.c.length-1;return A(e.e/E)==t&&e.c[t]%2!=0}function C(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function L(e,t,r){var n,o;if(t<0){for(o=r+".";++t;o+=r);e=o+e}else if(++t>(n=e.length)){for(o=r,t-=n;--t;o+=r);e+=o}else tU?p.c=p.e=null:e.e=10;u/=10,s++);return void(s>U?p.c=p.e=null:(p.e=s,p.c=[e]))}f=String(e)}else{if(!v.test(f=String(e)))return o(p,f,c);p.s=45==f.charCodeAt(0)?(f=f.slice(1),-1):1}(s=f.indexOf("."))>-1&&(f=f.replace(".","")),(u=f.search(/e/i))>0?(s<0&&(s=u),s+=+f.slice(u+1),f=f.substring(0,u)):s<0&&(s=f.length)}else{if(j(t,2,q.length,"Base"),10==t&&K)return W(p=new H(e),h+p.e+1,y);if(f=String(e),c="number"==typeof e){if(0*e!=0)return o(p,f,c,t);if(p.s=1/e<0?(f=f.slice(1),-1):1,H.DEBUG&&f.replace(/^0\.0*|\./,"").length>15)throw Error(S+e)}else p.s=45===f.charCodeAt(0)?(f=f.slice(1),-1):1;for(r=q.slice(0,t),s=u=0,l=f.length;us){s=l;continue}}else if(!a&&(f==f.toUpperCase()&&(f=f.toLowerCase())||f==f.toLowerCase()&&(f=f.toUpperCase()))){a=!0,u=-1,s=0;continue}return o(p,String(e),c,t)}c=!1,(s=(f=n(f,t,10,p.s)).indexOf("."))>-1?f=f.replace(".",""):s=f.length}for(u=0;48===f.charCodeAt(u);u++);for(l=f.length;48===f.charCodeAt(--l););if(f=f.slice(u,++l)){if(l-=u,c&&H.DEBUG&&l>15&&(e>k||e!==b(e)))throw Error(S+p.s*e);if((s=s-u-1)>U)p.c=p.e=null;else if(s=B)?C(u,a):L(u,a,"0");else if(i=(e=W(new H(e),t,r)).e,s=(u=P(e.c)).length,1==n||2==n&&(t<=i||i<=m)){for(;ss){if(--t>0)for(u+=".";t--;u+="0");}else if((t+=i-s)>0)for(i+1==s&&(u+=".");t--;u+="0");return e.s<0&&o?"-"+u:u}function X(e,t){for(var r,n,o=1,i=new H(e[0]);o=10;o/=10,n++);return(r=n+r*E-1)>U?e.c=e.e=null:r=10;s/=10,o++);if((i=t-o)<0)i+=E,a=t,u=f[c=0],l=b(u/p[o-a-1]%10);else if((c=g((i+1)/E))>=f.length){if(!n)break e;for(;f.length<=c;f.push(0));u=l=0,o=1,a=(i%=E)-E+1}else{for(u=s=f[c],o=1;s>=10;s/=10,o++);l=(a=(i%=E)-E+o)<0?0:b(u/p[o-a-1]%10)}if(n=n||t<0||null!=f[c+1]||(a<0?u:u%p[o-a-1]),n=r<4?(l||n)&&(0==r||r==(e.s<0?3:2)):l>5||5==l&&(4==r||n||6==r&&(i>0?a>0?u/p[o-a]:0:f[c-1])%10&1||r==(e.s<0?8:7)),t<1||!f[0])return f.length=0,n?(t-=e.e+1,f[0]=p[(E-t%E)%E],e.e=-t||0):f[0]=e.e=0,e;if(0==i?(f.length=c,s=1,c--):(f.length=c+1,s=p[E-i],f[c]=a>0?b(u/p[o-a]%p[a])*s:0),n)for(;;){if(0==c){for(i=1,a=f[0];a>=10;a/=10,i++);for(a=f[0]+=s,s=1;a>=10;a/=10,s++);i!=s&&(e.e++,f[0]==_&&(f[0]=1));break}if(f[c]+=s,f[c]!=_)break;f[c--]=0,s=1}for(i=f.length;0===f[--i];f.pop());}e.e>U?e.c=e.e=null:e.e=B?C(t,r):L(t,r,"0"),e.s<0?"-"+t:t)}return H.clone=e,H.ROUND_UP=0,H.ROUND_DOWN=1,H.ROUND_CEIL=2,H.ROUND_FLOOR=3,H.ROUND_HALF_UP=4,H.ROUND_HALF_DOWN=5,H.ROUND_HALF_EVEN=6,H.ROUND_HALF_CEIL=7,H.ROUND_HALF_FLOOR=8,H.EUCLID=9,H.config=H.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(w+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(j(r=e[t],0,x,t),h=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(j(r=e[t],0,8,t),y=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(j(r[0],-x,0,t),j(r[1],0,x,t),m=r[0],B=r[1]):(j(r,-x,x,t),m=-(B=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)j(r[0],-x,-1,t),j(r[1],1,x,t),N=r[0],U=r[1];else{if(j(r,-x,x,t),!r)throw Error(w+t+" cannot be zero: "+r);N=-(U=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(w+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw M=!r,Error(w+"crypto unavailable");M=r}else M=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(j(r=e[t],0,9,t),D=r),e.hasOwnProperty(t="POW_PRECISION")&&(j(r=e[t],0,x,t),F=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(w+t+" not an object: "+r);V=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(w+t+" invalid: "+r);K="0123456789"==r.slice(0,10),q=r}}return{DECIMAL_PLACES:h,ROUNDING_MODE:y,EXPONENTIAL_AT:[m,B],RANGE:[N,U],CRYPTO:M,MODULO_MODE:D,POW_PRECISION:F,FORMAT:V,ALPHABET:q}},H.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!H.DEBUG)return!0;var t,r,n=e.c,o=e.e,i=e.s;e:if("[object Array]"=={}.toString.call(n)){if((1===i||-1===i)&&o>=-x&&o<=x&&o===b(o)){if(0===n[0]){if(0===o&&1===n.length)return!0;break e}if((t=(o+1)%E)<1&&(t+=E),String(n[0]).length==t){for(t=0;t=_||r!==b(r))break e;if(0!==r)return!0}}}else if(null===n&&null===o&&(null===i||1===i||-1===i))return!0;throw Error(w+"Invalid BigNumber: "+e)},H.maximum=H.max=function(){return X(arguments,-1)},H.minimum=H.min=function(){return X(arguments,1)},H.random=(i=9007199254740992,a=Math.random()*i&2097151?function(){return b(Math.random()*i)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,n,o,i,s=0,u=[],c=new H(d);if(null==e?e=h:j(e,0,x),o=g(e/E),M)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(o*=2));s>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[s]=r[0],t[s+1]=r[1]):(u.push(i%1e14),s+=2);s=o/2}else{if(!crypto.randomBytes)throw M=!1,Error(w+"crypto unavailable");for(t=crypto.randomBytes(o*=7);s=9e15?crypto.randomBytes(7).copy(t,s):(u.push(i%1e14),s+=7);s=o/7}if(!M)for(;s=10;i/=10,s++);sr-1&&(null==a[o+1]&&(a[o+1]=0),a[o+1]+=a[o]/r|0,a[o]%=r)}return a.reverse()}return function(n,o,i,a,s){var u,c,l,f,p,d,m,v,g=n.indexOf("."),b=h,w=y;for(g>=0&&(f=F,F=0,n=n.replace(".",""),d=(v=new H(o)).pow(n.length-g),F=f,v.c=t(L(P(d.c),d.e,"0"),10,i,e),v.e=v.c.length),l=f=(m=t(n,o,i,s?(u=q,e):(u=e,q))).length;0==m[--f];m.pop());if(!m[0])return u.charAt(0);if(g<0?--l:(d.c=m,d.e=l,d.s=a,m=(d=r(d,v,b,w,i)).c,p=d.r,l=d.e),g=m[c=l+b+1],f=i/2,p=p||c<0||null!=m[c+1],p=w<4?(null!=g||p)&&(0==w||w==(d.s<0?3:2)):g>f||g==f&&(4==w||p||6==w&&1&m[c-1]||w==(d.s<0?8:7)),c<1||!m[0])n=p?L(u.charAt(1),-b,u.charAt(0)):u.charAt(0);else{if(m.length=c,p)for(--i;++m[--c]>i;)m[c]=0,c||(++l,m=[1].concat(m));for(f=m.length;!m[--f];);for(g=0,n="";g<=f;n+=u.charAt(m[g++]));n=L(n,l,u.charAt(0))}return n}}(),r=function(){function e(e,t,r){var n,o,i,a,s=0,u=e.length,c=t%O,l=t/O|0;for(e=e.slice();u--;)s=((o=c*(i=e[u]%O)+(n=l*i+(a=e[u]/O|0)*c)%O*O+s)/r|0)+(n/O|0)+l*a,e[u]=o%r;return s&&(e=[s].concat(e)),e}function t(e,t,r,n){var o,i;if(r!=n)i=r>n?1:-1;else for(o=i=0;ot[o]?1:-1;break}return i}function r(e,t,r,n){for(var o=0;r--;)e[r]-=o,o=e[r]1;e.splice(0,1));}return function(n,o,i,a,s){var u,c,l,f,p,d,h,y,m,v,g,w,S,k,T,O,x,P=n.s==o.s?1:-1,R=n.c,j=o.c;if(!(R&&R[0]&&j&&j[0]))return new H(n.s&&o.s&&(R?!j||R[0]!=j[0]:j)?R&&0==R[0]||!j?0*P:P/0:NaN);for(m=(y=new H(P)).c=[],P=i+(c=n.e-o.e)+1,s||(s=_,c=A(n.e/E)-A(o.e/E),P=P/E|0),l=0;j[l]==(R[l]||0);l++);if(j[l]>(R[l]||0)&&c--,P<0)m.push(1),f=!0;else{for(k=R.length,O=j.length,l=0,P+=2,(p=b(s/(j[0]+1)))>1&&(j=e(j,p,s),R=e(R,p,s),O=j.length,k=R.length),S=O,g=(v=R.slice(0,O)).length;g=s/2&&T++;do{if(p=0,(u=t(j,v,O,g))<0){if(w=v[0],O!=g&&(w=w*s+(v[1]||0)),(p=b(w/T))>1)for(p>=s&&(p=s-1),h=(d=e(j,p,s)).length,g=v.length;1==t(d,v,h,g);)p--,r(d,O=10;P/=10,l++);W(y,i+(y.e=l+c*E-1)+1,a,f)}else y.e=c,y.r=+f;return y}}(),s=/^(-?)0([xbo])(?=\w[\w.]*$)/i,u=/^([^.]+)\.$/,c=/^\.([^.]+)$/,l=/^-?(Infinity|NaN)$/,f=/^\s*\+(?=[\w.])|^\s+|\s+$/g,o=function(e,t,r,n){var o,i=r?t:t.replace(f,"");if(l.test(i))e.s=isNaN(i)?null:i<0?-1:1;else{if(!r&&(i=i.replace(s,(function(e,t,r){return o="x"==(r=r.toLowerCase())?16:"b"==r?2:8,n&&n!=o?e:t})),n&&(o=n,i=i.replace(u,"$1").replace(c,"0.$1")),t!=i))return new H(i,o);if(H.DEBUG)throw Error(w+"Not a"+(n?" base "+n:"")+" number: "+t);e.s=null}e.c=e.e=null},p.absoluteValue=p.abs=function(){var e=new H(this);return e.s<0&&(e.s=1),e},p.comparedTo=function(e,t){return R(this,new H(e,t))},p.decimalPlaces=p.dp=function(e,t){var r,n,o,i=this;if(null!=e)return j(e,0,x),null==t?t=y:j(t,0,8),W(new H(i),e+i.e+1,t);if(!(r=i.c))return null;if(n=((o=r.length-1)-A(this.e/E))*E,o=r[o])for(;o%10==0;o/=10,n--);return n<0&&(n=0),n},p.dividedBy=p.div=function(e,t){return r(this,new H(e,t),h,y)},p.dividedToIntegerBy=p.idiv=function(e,t){return r(this,new H(e,t),0,1)},p.exponentiatedBy=p.pow=function(e,t){var r,n,o,i,a,s,u,c,l=this;if((e=new H(e)).c&&!e.isInteger())throw Error(w+"Exponent not an integer: "+$(e));if(null!=t&&(t=new H(t)),a=e.e>14,!l.c||!l.c[0]||1==l.c[0]&&!l.e&&1==l.c.length||!e.c||!e.c[0])return c=new H(Math.pow(+$(l),a?e.s*(2-I(e)):+$(e))),t?c.mod(t):c;if(s=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new H(NaN);(n=!s&&l.isInteger()&&t.isInteger())&&(l=l.mod(t))}else{if(e.e>9&&(l.e>0||l.e<-1||(0==l.e?l.c[0]>1||a&&l.c[1]>=24e7:l.c[0]<8e13||a&&l.c[0]<=9999975e7)))return i=l.s<0&&I(e)?-0:0,l.e>-1&&(i=1/i),new H(s?1/i:i);F&&(i=g(F/E+2))}for(a?(r=new H(.5),s&&(e.s=1),u=I(e)):u=(o=Math.abs(+$(e)))%2,c=new H(d);;){if(u){if(!(c=c.times(l)).c)break;i?c.c.length>i&&(c.c.length=i):n&&(c=c.mod(t))}if(o){if(0===(o=b(o/2)))break;u=o%2}else if(W(e=e.times(r),e.e+1,1),e.e>14)u=I(e);else{if(0===(o=+$(e)))break;u=o%2}l=l.times(l),i?l.c&&l.c.length>i&&(l.c.length=i):n&&(l=l.mod(t))}return n?c:(s&&(c=d.div(c)),t?c.mod(t):i?W(c,F,y,undefined):c)},p.integerValue=function(e){var t=new H(this);return null==e?e=y:j(e,0,8),W(t,t.e+1,e)},p.isEqualTo=p.eq=function(e,t){return 0===R(this,new H(e,t))},p.isFinite=function(){return!!this.c},p.isGreaterThan=p.gt=function(e,t){return R(this,new H(e,t))>0},p.isGreaterThanOrEqualTo=p.gte=function(e,t){return 1===(t=R(this,new H(e,t)))||0===t},p.isInteger=function(){return!!this.c&&A(this.e/E)>this.c.length-2},p.isLessThan=p.lt=function(e,t){return R(this,new H(e,t))<0},p.isLessThanOrEqualTo=p.lte=function(e,t){return-1===(t=R(this,new H(e,t)))||0===t},p.isNaN=function(){return!this.s},p.isNegative=function(){return this.s<0},p.isPositive=function(){return this.s>0},p.isZero=function(){return!!this.c&&0==this.c[0]},p.minus=function(e,t){var r,n,o,i,a=this,s=a.s;if(t=(e=new H(e,t)).s,!s||!t)return new H(NaN);if(s!=t)return e.s=-t,a.plus(e);var u=a.e/E,c=e.e/E,l=a.c,f=e.c;if(!u||!c){if(!l||!f)return l?(e.s=-t,e):new H(f?a:NaN);if(!l[0]||!f[0])return f[0]?(e.s=-t,e):new H(l[0]?a:3==y?-0:0)}if(u=A(u),c=A(c),l=l.slice(),s=u-c){for((i=s<0)?(s=-s,o=l):(c=u,o=f),o.reverse(),t=s;t--;o.push(0));o.reverse()}else for(n=(i=(s=l.length)<(t=f.length))?s:t,s=t=0;t0)for(;t--;l[r++]=0);for(t=_-1;n>s;){if(l[--n]=0;){for(r=0,p=b[o]%m,d=b[o]/m|0,i=o+(a=u);i>o;)r=((c=p*(c=g[--a]%m)+(s=d*c+(l=g[a]/m|0)*p)%m*m+h[i]+r)/y|0)+(s/m|0)+d*l,h[i--]=c%y;h[i]=r}return r?++n:h.splice(0,1),G(e,h,n)},p.negated=function(){var e=new H(this);return e.s=-e.s||null,e},p.plus=function(e,t){var r,n=this,o=n.s;if(t=(e=new H(e,t)).s,!o||!t)return new H(NaN);if(o!=t)return e.s=-t,n.minus(e);var i=n.e/E,a=e.e/E,s=n.c,u=e.c;if(!i||!a){if(!s||!u)return new H(o/0);if(!s[0]||!u[0])return u[0]?e:new H(s[0]?n:0*o)}if(i=A(i),a=A(a),s=s.slice(),o=i-a){for(o>0?(a=i,r=u):(o=-o,r=s),r.reverse();o--;r.push(0));r.reverse()}for((o=s.length)-(t=u.length)<0&&(r=u,u=s,s=r,t=o),o=0;t;)o=(s[--t]=s[t]+u[t]+o)/_|0,s[t]=_===s[t]?0:s[t]%_;return o&&(s=[o].concat(s),++a),G(e,s,a)},p.precision=p.sd=function(e,t){var r,n,o,i=this;if(null!=e&&e!==!!e)return j(e,1,x),null==t?t=y:j(t,0,8),W(new H(i),e,t);if(!(r=i.c))return null;if(n=(o=r.length-1)*E+1,o=r[o]){for(;o%10==0;o/=10,n--);for(o=r[0];o>=10;o/=10,n++);}return e&&i.e+1>n&&(n=i.e+1),n},p.shiftedBy=function(e){return j(e,-9007199254740991,k),this.times("1e"+e)},p.squareRoot=p.sqrt=function(){var e,t,n,o,i,a=this,s=a.c,u=a.s,c=a.e,l=h+4,f=new H("0.5");if(1!==u||!s||!s[0])return new H(!u||u<0&&(!s||s[0])?NaN:s?a:1/0);if(0==(u=Math.sqrt(+$(a)))||u==1/0?(((t=P(s)).length+c)%2==0&&(t+="0"),u=Math.sqrt(+t),c=A((c+1)/2)-(c<0||c%2),n=new H(t=u==1/0?"5e"+c:(t=u.toExponential()).slice(0,t.indexOf("e")+1)+c)):n=new H(u+""),n.c[0])for((u=(c=n.e)+l)<3&&(u=0);;)if(i=n,n=f.times(i.plus(r(a,i,l,1))),P(i.c).slice(0,u)===(t=P(n.c)).slice(0,u)){if(n.e0&&h>0){for(i=h%s||s,l=d.substr(0,i);i0&&(l+=c+d.slice(i)),p&&(l="-"+l)}n=f?l+(r.decimalSeparator||"")+((u=+r.fractionGroupSize)?f.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):f):l}return(r.prefix||"")+n+(r.suffix||"")},p.toFraction=function(e){var t,n,o,i,a,s,u,c,l,f,p,h,m=this,v=m.c;if(null!=e&&(!(u=new H(e)).isInteger()&&(u.c||1!==u.s)||u.lt(d)))throw Error(w+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+$(u));if(!v)return new H(m);for(t=new H(d),l=n=new H(d),o=c=new H(d),h=P(v),a=t.e=h.length-m.e-1,t.c[0]=T[(s=a%E)<0?E+s:s],e=!e||u.comparedTo(t)>0?a>0?t:l:u,s=U,U=1/0,u=new H(h),c.c[0]=0;f=r(u,t,0,1),1!=(i=n.plus(f.times(o))).comparedTo(e);)n=o,o=i,l=c.plus(f.times(i=l)),c=i,t=u.minus(f.times(i=t)),u=i;return i=r(e.minus(n),o,0,1),c=c.plus(i.times(l)),n=n.plus(i.times(o)),c.s=l.s=m.s,p=r(l,o,a*=2,y).minus(m).abs().comparedTo(r(c,n,a,y).minus(m).abs())<1?[l,o]:[c,n],U=s,p},p.toNumber=function(){return+$(this)},p.toPrecision=function(e,t){return null!=e&&j(e,1,x),z(this,e,t,2)},p.toString=function(e){var t,r=this,o=r.s,i=r.e;return null===i?o?(t="Infinity",o<0&&(t="-"+t)):t="NaN":(null==e?t=i<=m||i>=B?C(P(r.c),i):L(P(r.c),i,"0"):10===e&&K?t=L(P((r=W(new H(r),h+i+1,y)).c),r.e,"0"):(j(e,2,q.length,"Base"),t=n(L(P(r.c),i,"0"),10,e,o,!0)),o<0&&r.c[0]&&(t="-"+t)),t},p.valueOf=p.toJSON=function(){return $(this)},p._isBigNumber=!0,p[Symbol.toStringTag]="BigNumber",p[Symbol.for("nodejs.util.inspect.custom")]=p.valueOf,null!=t&&H.set(t),H}();const N=B;var U=r(4193),M=r.n(U),D=r(9127),F=r.n(D),V=r(5976),q=r(6371);function K(e){return K="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},K(e)}var H="13.1.0",z={},X=(0,q.vt)({headers:{"X-Client-Name":"js-stellar-sdk","X-Client-Version":H}});function G(e){return Math.floor(e/1e3)}X.interceptors.response.use((function(e){var t=M()(e.config.url).hostname(),r=0;if(e.headers instanceof Headers){var n=e.headers.get("date");n&&(r=G(Date.parse(n)))}else if("object"===K(e.headers)&&"date"in e.headers){var o=e.headers;"string"==typeof o.date&&(r=G(Date.parse(o.date)))}var i=G((new Date).getTime());return Number.isNaN(r)||(z[t]={serverTime:r,localTimeRecorded:i}),e}));const W=X;function $(e){var t=z[e];if(!t||!t.localTimeRecorded||!t.serverTime)return null;var r=t.serverTime,n=t.localTimeRecorded,o=G((new Date).getTime());return o-n>300?null:o-n+r}function Q(e){return Q="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Q(e)}function Y(){Y=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,_=S&&S(S(j([])));_&&_!==r&&n.call(_,a)&&(w=_);var E=b.prototype=v.prototype=Object.create(w);function k(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==Q(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function J(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function Z(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){J(i,n,o,a,s,"next",e)}function s(e){J(i,n,o,a,s,"throw",e)}a(void 0)}))}}function ee(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:"";!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.url=t.clone(),this.filter=[],this.originalSegments=this.url.segment()||[],this.neighborRoot=r}),[{key:"call",value:function(){var e=this;return this.checkFilter(),this._sendNormalRequest(this.url).then((function(t){return e._parseResponse(t)}))}},{key:"stream",value:function(){var e,t,r=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(void 0===re)throw new Error("Streaming requires eventsource to be enabled. If you need this functionality, compile with USE_EVENTSOURCE=true.");this.checkFilter(),this.url.setQuery("X-Client-Name","js-stellar-sdk"),this.url.setQuery("X-Client-Version",H);var o=function(){t=setTimeout((function(){var t;null===(t=e)||void 0===t||t.close(),e=i()}),n.reconnectTimeout||15e3)},i=function(){try{e=new re(r.url.toString())}catch(e){n.onerror&&n.onerror(e)}if(o(),!e)return e;var a=!1,s=function(){a||(clearTimeout(t),e.close(),i(),a=!0)},u=function(e){if("close"!==e.type){var i=e.data?r._parseRecord(JSON.parse(e.data)):e;i.paging_token&&r.url.setQuery("cursor",i.paging_token),clearTimeout(t),o(),void 0!==n.onmessage&&n.onmessage(i)}else s()},c=function(e){n.onerror&&n.onerror(e)};return e.addEventListener?(e.addEventListener("message",u.bind(r)),e.addEventListener("error",c.bind(r)),e.addEventListener("close",s.bind(r))):(e.onmessage=u.bind(r),e.onerror=c.bind(r)),e};return i(),function(){var r;clearTimeout(t),null===(r=e)||void 0===r||r.close()}}},{key:"cursor",value:function(e){return this.url.setQuery("cursor",e),this}},{key:"limit",value:function(e){return this.url.setQuery("limit",e.toString()),this}},{key:"order",value:function(e){return this.url.setQuery("order",e),this}},{key:"join",value:function(e){return this.url.setQuery("join",e),this}},{key:"forEndpoint",value:function(e,t){if(""===this.neighborRoot)throw new Error("Invalid usage: neighborRoot not set in constructor");return this.filter.push([e,t,this.neighborRoot]),this}},{key:"checkFilter",value:function(){if(this.filter.length>=2)throw new V.v7("Too many filters specified",this.filter);if(1===this.filter.length){var e=this.originalSegments.concat(this.filter[0]);this.url.segment(e)}}},{key:"_requestFnForLink",value:function(e){var t=this;return Z(Y().mark((function r(){var n,o,i,a,s=arguments;return Y().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return n=s.length>0&&void 0!==s[0]?s[0]:{},e.templated?(i=F()(e.href),o=M()(i.expand(n))):o=M()(e.href),r.next=4,t._sendNormalRequest(o);case 4:return a=r.sent,r.abrupt("return",t._parseResponse(a));case 6:case"end":return r.stop()}}),r)})))}},{key:"_parseRecord",value:function(e){var t=this;return e._links?(Object.keys(e._links).forEach((function(r){var n=e._links[r],o=!1;if(void 0!==e[r]&&(e["".concat(r,"_attr")]=e[r],o=!0),o&&ae.indexOf(r)>=0){var i=t._parseRecord(e[r]);e[r]=Z(Y().mark((function e(){return Y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",i);case 1:case"end":return e.stop()}}),e)})))}else e[r]=t._requestFnForLink(n)})),e):e}},{key:"_sendNormalRequest",value:(ce=Z(Y().mark((function e(t){var r;return Y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return""===(r=t).authority()&&(r=r.authority(this.url.authority())),""===r.protocol()&&(r=r.protocol(this.url.protocol())),e.abrupt("return",X.get(r.toString()).then((function(e){return e.data})).catch(this._handleNetworkError));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return ce.apply(this,arguments)})},{key:"_parseResponse",value:function(e){return e._embedded&&e._embedded.records?this._toCollectionPage(e):this._parseRecord(e)}},{key:"_toCollectionPage",value:function(e){for(var t,r,n=this,o=0;ot||e>=24*r||e%r!=0)}}])}(le);function vr(e){return vr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},vr(e)}function gr(e,t){for(var r=0;r=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function Mr(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function Dr(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){Mr(i,n,o,a,s,"next",e)}function s(e){Mr(i,n,o,a,s,"throw",e)}a(void 0)}))}}function Fr(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.serverURL=M()(t);var n=void 0===r.allowHttp?fe.T.isAllowHttp():r.allowHttp,o={};if(r.appName&&(o["X-App-Name"]=r.appName),r.appVersion&&(o["X-App-Version"]=r.appVersion),r.authToken&&(o["X-Auth-Token"]=r.authToken),r.headers&&Object.assign(o,r.headers),Object.keys(o).length>0&&W.interceptors.request.use((function(e){return e.headers=e.headers||{},e.headers=Object.assign(e.headers,o),e})),"https"!==this.serverURL.protocol()&&!n)throw new Error("Cannot connect to insecure horizon server")}),[{key:"fetchTimebounds",value:(Qr=Dr(Ur().mark((function e(t){var r,n,o=arguments;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=o.length>1&&void 0!==o[1]&&o[1],!(n=$(this.serverURL.hostname()))){e.next=4;break}return e.abrupt("return",{minTime:0,maxTime:n+t});case 4:if(!r){e.next=6;break}return e.abrupt("return",{minTime:0,maxTime:Math.floor((new Date).getTime()/1e3)+t});case 6:return e.next=8,W.get(M()(this.serverURL).toString());case 8:return e.abrupt("return",this.fetchTimebounds(t,!0));case 9:case"end":return e.stop()}}),e,this)}))),function(e){return Qr.apply(this,arguments)})},{key:"fetchBaseFee",value:($r=Dr(Ur().mark((function e(){var t;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.feeStats();case 2:return t=e.sent,e.abrupt("return",parseInt(t.last_ledger_base_fee,10)||100);case 4:case"end":return e.stop()}}),e,this)}))),function(){return $r.apply(this,arguments)})},{key:"feeStats",value:(Wr=Dr(Ur().mark((function e(){var t;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(t=new le(M()(this.serverURL))).filter.push(["fee_stats"]),e.abrupt("return",t.call());case 3:case"end":return e.stop()}}),e,this)}))),function(){return Wr.apply(this,arguments)})},{key:"root",value:(Gr=Dr(Ur().mark((function e(){var t;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=new le(M()(this.serverURL)),e.abrupt("return",t.call());case 2:case"end":return e.stop()}}),e,this)}))),function(){return Gr.apply(this,arguments)})},{key:"submitTransaction",value:(Xr=Dr(Ur().mark((function e(t){var r,n=arguments;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((n.length>1&&void 0!==n[1]?n[1]:{skipMemoRequiredCheck:!1}).skipMemoRequiredCheck){e.next=4;break}return e.next=4,this.checkMemoRequired(t);case 4:return r=encodeURIComponent(t.toEnvelope().toXDR().toString("base64")),e.abrupt("return",W.post(M()(this.serverURL).segment("transactions").toString(),"tx=".concat(r),{timeout:6e4}).then((function(e){if(!e.data.result_xdr)return e.data;var t,r,n=s.xdr.TransactionResult.fromXDR(e.data.result_xdr,"base64").result().value();return n.length&&(t=n.map((function(e,t){if("manageBuyOffer"!==e.value().switch().name&&"manageSellOffer"!==e.value().switch().name)return null;r=!0;var n,o=new N(0),i=new N(0),a=e.value().value().success(),u=a.offersClaimed().map((function(e){var t=e.value(),r="";switch(e.switch()){case s.xdr.ClaimAtomType.claimAtomTypeV0():r=s.StrKey.encodeEd25519PublicKey(t.sellerEd25519());break;case s.xdr.ClaimAtomType.claimAtomTypeOrderBook():r=s.StrKey.encodeEd25519PublicKey(t.sellerId().ed25519());break;default:throw new Error("Invalid offer result type: ".concat(e.switch()))}var n=new N(t.amountBought().toString()),a=new N(t.amountSold().toString());o=o.plus(a),i=i.plus(n);var u=s.Asset.fromOperation(t.assetSold()),c=s.Asset.fromOperation(t.assetBought()),l={type:u.getAssetType(),assetCode:u.getCode(),issuer:u.getIssuer()},f={type:c.getAssetType(),assetCode:c.getCode(),issuer:c.getIssuer()};return{sellerId:r,offerId:t.offerId().toString(),assetSold:l,amountSold:qr(a),assetBought:f,amountBought:qr(n)}})),c=a.offer().switch().name;if("function"==typeof a.offer().value&&a.offer().value()){var l=a.offer().value();n={offerId:l.offerId().toString(),selling:{},buying:{},amount:qr(l.amount().toString()),price:{n:l.price().n(),d:l.price().d()}};var f=s.Asset.fromOperation(l.selling());n.selling={type:f.getAssetType(),assetCode:f.getCode(),issuer:f.getIssuer()};var p=s.Asset.fromOperation(l.buying());n.buying={type:p.getAssetType(),assetCode:p.getCode(),issuer:p.getIssuer()}}return{offersClaimed:u,effect:c,operationIndex:t,currentOffer:n,amountBought:qr(o),amountSold:qr(i),isFullyOpen:!u.length&&"manageOfferDeleted"!==c,wasPartiallyFilled:!!u.length&&"manageOfferDeleted"!==c,wasImmediatelyFilled:!!u.length&&"manageOfferDeleted"===c,wasImmediatelyDeleted:!u.length&&"manageOfferDeleted"===c}})).filter((function(e){return!!e}))),Br(Br({},e.data),{},{offerResults:r?t:void 0})})).catch((function(e){return e instanceof Error?Promise.reject(e):Promise.reject(new V.nS("Transaction submission failed. Server responded: ".concat(e.status," ").concat(e.statusText),e.data))})));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return Xr.apply(this,arguments)})},{key:"submitAsyncTransaction",value:(zr=Dr(Ur().mark((function e(t){var r,n=arguments;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((n.length>1&&void 0!==n[1]?n[1]:{skipMemoRequiredCheck:!1}).skipMemoRequiredCheck){e.next=4;break}return e.next=4,this.checkMemoRequired(t);case 4:return r=encodeURIComponent(t.toEnvelope().toXDR().toString("base64")),e.abrupt("return",W.post(M()(this.serverURL).segment("transactions_async").toString(),"tx=".concat(r)).then((function(e){return e.data})).catch((function(e){return e instanceof Error?Promise.reject(e):Promise.reject(new V.nS("Transaction submission failed. Server responded: ".concat(e.status," ").concat(e.statusText),e.data))})));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return zr.apply(this,arguments)})},{key:"accounts",value:function(){return new be(M()(this.serverURL))}},{key:"claimableBalances",value:function(){return new Be(M()(this.serverURL))}},{key:"ledgers",value:function(){return new it(M()(this.serverURL))}},{key:"transactions",value:function(){return new Ir(M()(this.serverURL))}},{key:"offers",value:function(){return new St(M()(this.serverURL))}},{key:"orderbook",value:function(e,t){return new Ut(M()(this.serverURL),e,t)}},{key:"trades",value:function(){return new kr(M()(this.serverURL))}},{key:"operations",value:function(){return new Pt(M()(this.serverURL))}},{key:"liquidityPools",value:function(){return new dt(M()(this.serverURL))}},{key:"strictReceivePaths",value:function(e,t,r){return new Zt(M()(this.serverURL),e,t,r)}},{key:"strictSendPaths",value:function(e,t,r){return new sr(M()(this.serverURL),e,t,r)}},{key:"payments",value:function(){return new zt(M()(this.serverURL))}},{key:"effects",value:function(){return new Ke(M()(this.serverURL))}},{key:"friendbot",value:function(e){return new Ye(M()(this.serverURL),e)}},{key:"assets",value:function(){return new xe(M()(this.serverURL))}},{key:"loadAccount",value:(Hr=Dr(Ur().mark((function e(t){var r;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.accounts().accountId(t).call();case 2:return r=e.sent,e.abrupt("return",new m(r));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return Hr.apply(this,arguments)})},{key:"tradeAggregation",value:function(e,t,r,n,o,i){return new mr(M()(this.serverURL),e,t,r,n,o,i)}},{key:"checkMemoRequired",value:(Kr=Dr(Ur().mark((function e(t){var r,n,o,i;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t instanceof s.FeeBumpTransaction&&(t=t.innerTransaction),"none"===t.memo.type){e.next=3;break}return e.abrupt("return");case 3:r=new Set,n=0;case 5:if(!(n{"use strict";async function n(e,t){const r={config:e};return r.status=t.status,r.statusText=t.statusText,r.headers=t.headers,"stream"===e.responseType?(r.data=t.body,r):t[e.responseType||"text"]().then((n=>{e.transformResponse?(Array.isArray(e.transformResponse)?e.transformResponse.map((r=>n=r.call(e,n,t?.headers,t?.status))):n=e.transformResponse(n,t?.headers,t?.status),r.data=n):(r.data=n,r.data=JSON.parse(n))})).catch(Object).then((()=>r))}function o(e){let t=e.url||"";return e.baseURL&&e.url&&(t=e.url.replace(/^(?!.*\/\/)\/?/,`${e.baseURL}/`)),e.params&&Object.keys(e.params).length>0&&e.url&&(t+=(~e.url.indexOf("?")?"&":"?")+(e.paramsSerializer?e.paramsSerializer(e.params):new URLSearchParams(e.params))),t}function i(e,t){const r={...t,...e};if(t?.params&&e?.params&&(r.params={...t?.params,...e?.params}),t?.headers&&e?.headers){r.headers=new Headers(t.headers||{});new Headers(e.headers||{}).forEach(((e,t)=>{r.headers.set(t,e)}))}return r}function a(e,t){const r=t.get("content-type");return r?"application/x-www-form-urlencoded"!==r||e instanceof URLSearchParams?"application/json"===r&&"object"==typeof e&&(e=JSON.stringify(e)):e=new URLSearchParams(e):"string"==typeof e?t.set("content-type","text/plain"):e instanceof URLSearchParams?t.set("content-type","application/x-www-form-urlencoded"):e instanceof Blob||e instanceof ArrayBuffer||ArrayBuffer.isView(e)?t.set("content-type","application/octet-stream"):"object"==typeof e&&"function"!=typeof e.append&&"function"!=typeof e.text&&(e=JSON.stringify(e),t.set("content-type","application/json")),e}async function s(e,t,r,u,c,p){"string"==typeof e?(t=t||{}).url=e:t=e||{};const d=i(t,r||{});if(d.fetchOptions=d.fetchOptions||{},d.timeout=d.timeout||0,d.headers=new Headers(d.headers||{}),d.transformRequest=d.transformRequest??a,p=p||d.data,d.transformRequest&&p&&(Array.isArray(d.transformRequest)?d.transformRequest.map((e=>p=e.call(d,p,d.headers))):p=d.transformRequest(p,d.headers)),d.url=o(d),d.method=u||d.method||"get",c&&c.request.handlers.length>0){const e=c.request.handlers.filter((e=>!e?.runWhen||"function"==typeof e.runWhen&&e.runWhen(d))).flatMap((e=>[e.fulfilled,e.rejected]));let t=d;for(let r=0,n=e.length;r{r.headers.set(t,e)})));return r}({method:d.method?.toUpperCase(),body:p,headers:d.headers,credentials:d.withCredentials?"include":void 0,signal:d.signal},d.fetchOptions);let y=async function(e,t){let r=null;if("any"in AbortSignal){const r=[];e.timeout&&r.push(AbortSignal.timeout(e.timeout)),e.signal&&r.push(e.signal),r.length>0&&(t.signal=AbortSignal.any(r))}else e.timeout&&(t.signal=AbortSignal.timeout(e.timeout));try{return r=await fetch(e.url,t),(e.validateStatus?e.validateStatus(r.status):r.ok)?await n(e,r):Promise.reject(new l(`Request failed with status code ${r?.status}`,[l.ERR_BAD_REQUEST,l.ERR_BAD_RESPONSE][Math.floor(r?.status/100)-4],e,new Request(e.url,t),await n(e,r)))}catch(t){if("AbortError"===t.name||"TimeoutError"===t.name){const r="TimeoutError"===t.name;return Promise.reject(r?new l(e.timeoutErrorMessage||`timeout of ${e.timeout} ms exceeded`,l.ECONNABORTED,e,s):new f(null,e))}return Promise.reject(new l(t.message,void 0,e,s,void 0))}}(d,h);if(c&&c.response.handlers.length>0){const e=c.response.handlers.flatMap((e=>[e.fulfilled,e.rejected]));for(let t=0,r=e.length;tO,fetchClient:()=>x});var u=class{handlers=[];constructor(){this.handlers=[]}use=(e,t,r)=>(this.handlers.push({fulfilled:e,rejected:t,runWhen:r?.runWhen}),this.handlers.length-1);eject=e=>{this.handlers[e]&&(this.handlers[e]=null)};clear=()=>{this.handlers=[]}};function c(e){e=e||{};const t={request:new u,response:new u},r=(r,n)=>s(r,n,e,void 0,t);return r.defaults=e,r.interceptors=t,r.getUri=t=>o(i(t||{},e)),r.request=r=>s(r,void 0,e,void 0,t),["get","delete","head","options"].forEach((n=>{r[n]=(r,o)=>s(r,o,e,n,t)})),["post","put","patch"].forEach((n=>{r[n]=(r,o,i)=>s(r,i,e,n,t,o)})),["postForm","putForm","patchForm"].forEach((n=>{r[n]=(r,o,i)=>((i=i||{}).headers=new Headers(i.headers||{}),i.headers.set("content-type","application/x-www-form-urlencoded"),s(r,i,e,n.replace("Form",""),t,o))})),r}var l=class extends Error{config;code;request;response;status;isAxiosError;constructor(e,t,r,n,o){super(e),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.name="AxiosError",this.code=t,this.config=r,this.request=n,this.response=o,this.isAxiosError=!0}static ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";static ERR_BAD_OPTION="ERR_BAD_OPTION";static ERR_NETWORK="ERR_NETWORK";static ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";static ERR_BAD_REQUEST="ERR_BAD_REQUEST";static ERR_INVALID_URL="ERR_INVALID_URL";static ERR_CANCELED="ERR_CANCELED";static ECONNABORTED="ECONNABORTED";static ETIMEDOUT="ETIMEDOUT"},f=class extends l{constructor(e,t,r){super(e||"canceled",l.ERR_CANCELED,t,r),this.name="CanceledError"}};var p=c();p.create=e=>c(e);var d=p,h=r(5798);function y(e){return y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},y(e)}function m(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t0&&void 0!==arguments[0]?arguments[0]:{},t=v(v({},e),{},{headers:e.headers||{}}),r=d.create(t),n=new k,o=new k;return{interceptors:{request:n,response:o},defaults:v(v({},t),{},{adapter:function(e){return r.request(e)}}),create:function(e){return O(v(v({},this.defaults),e))},makeRequest:function(e){var t=this;return new Promise((function(r,i){var a=new AbortController;e.signal=a.signal,e.cancelToken&&e.cancelToken.promise.then((function(){a.abort(),i(new Error("Request canceled"))}));var s=e;if(n.handlers.length>0)for(var u=n.handlers.filter((function(e){return null!==e})).flatMap((function(e){return[e.fulfilled,e.rejected]})),c=0,l=u.length;c0)for(var y=o.handlers.filter((function(e){return null!==e})).flatMap((function(e){return[e.fulfilled,e.rejected]})),m=function(e){h=h.then((function(t){var r=y[e];return"function"==typeof r?r(t):t}),(function(t){var r=y[e+1];if("function"==typeof r)return r(t);throw t})).then((function(e){return e}))},v=0,g=y.length;v{"use strict";r.d(t,{ok:()=>n,vt:()=>o});r(5798);var n,o,i=r(8920);n=i.fetchClient,o=i.create},5798:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rc});var a,s,u,c=(a=function e(t){var r,n=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.promise=new Promise((function(e){r=e})),t((function(e){n.reason=e,r()}))},(s=[{key:"throwIfRequested",value:function(){if(this.reason)throw new Error(this.reason)}}])&&o(a.prototype,s),u&&o(a,u),Object.defineProperty(a,"prototype",{writable:!1}),a)},4356:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AccountRequiresMemoError:()=>n.Cu,BadRequestError:()=>n.v7,BadResponseError:()=>n.nS,Config:()=>o.T,Federation:()=>s,Friendbot:()=>c,Horizon:()=>l,NetworkError:()=>n.Dr,NotFoundError:()=>n.m_,StellarToml:()=>a,Utils:()=>i.A,WebAuth:()=>u,contract:()=>p,default:()=>y,rpc:()=>f});var n=r(5976),o=r(8732),i=r(3121),a=r(3898),s=r(7600),u=r(5479),c=r(8242),l=r(8733),f=r(3496),p=r(6299),d=r(356),h={};for(const e in d)["default","Config","Utils","StellarToml","Federation","WebAuth","Friendbot","Horizon","rpc","contract","AccountRequiresMemoError","BadRequestError","BadResponseError","NetworkError","NotFoundError"].indexOf(e)<0&&(h[e]=()=>d[e]);r.d(t,h);const y=(e=r.hmd(e)).exports;void 0===r.g.__USE_AXIOS__&&(r.g.__USE_AXIOS__=!0),void 0===r.g.__USE_EVENTSOURCE__&&(r.g.__USE_EVENTSOURCE__=!1)},4076:(e,t,r)=>{"use strict";var n;r.d(t,{j:()=>n}),function(e){var t=function(e){return e.SUCCESS="SUCCESS",e.NOT_FOUND="NOT_FOUND",e.FAILED="FAILED",e}({});function r(e){return"transactionData"in e}e.GetTransactionStatus=t,e.isSimulationError=function(e){return"error"in e},e.isSimulationSuccess=r,e.isSimulationRestore=function(e){return r(e)&&"restorePreamble"in e&&!!e.restorePreamble.transactionData},e.isSimulationRaw=function(e){return!e._parsed}}(n||(n={}))},3496:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Api:()=>n.j,AxiosClient:()=>s,BasicSleepStrategy:()=>x,Durability:()=>O,LinearSleepStrategy:()=>A,Server:()=>oe,assembleTransaction:()=>d.X,default:()=>ie,parseRawEvents:()=>h.fG,parseRawSimulation:()=>h.jr});var n=r(4076),o=r(4193),i=r.n(o),a=r(356);const s=(0,r(6371).vt)({headers:{"X-Client-Name":"js-soroban-client","X-Client-Version":"13.1.0"}});function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(){c=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",l=i.toStringTag||"@@toStringTag";function f(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{f({},"")}catch(e){f=function(e,t,r){return e[t]=r}}function p(e,t,r,n){var i=t&&t.prototype instanceof b?t:b,a=Object.create(i.prototype),s=new I(n||[]);return o(a,"_invoke",{value:A(e,r,s)}),a}function d(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=p;var h="suspendedStart",y="suspendedYield",m="executing",v="completed",g={};function b(){}function w(){}function S(){}var _={};f(_,a,(function(){return this}));var E=Object.getPrototypeOf,k=E&&E(E(C([])));k&&k!==r&&n.call(k,a)&&(_=k);var T=S.prototype=b.prototype=Object.create(_);function O(e){["next","throw","return"].forEach((function(t){f(e,t,(function(e){return this._invoke(t,e)}))}))}function x(e,t){function r(o,i,a,s){var c=d(e[o],e,i);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==u(f)&&n.call(f,"__await")?t.resolve(f.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(f).then((function(e){l.value=e,a(l)}),(function(e){return r("throw",e,a,s)}))}s(c.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function A(t,r,n){var o=h;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=P(s,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=m;var c=d(t,r,n);if("normal"===c.type){if(o=n.done?v:y,c.arg===g)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=v,n.method="throw",n.arg=c.arg)}}}function P(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,P(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=d(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function R(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function j(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function I(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(R,this),this.reset(!0)}function C(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),j(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:C(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function l(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function f(e,t){return p.apply(this,arguments)}function p(){var e;return e=c().mark((function e(t,r){var n,o,i,a=arguments;return c().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=a.length>2&&void 0!==a[2]?a[2]:null,e.next=3,s.post(t,{jsonrpc:"2.0",id:1,method:r,params:n});case 3:if(o=e.sent,u=o.data,c="error",!u.hasOwnProperty(c)){e.next=8;break}throw o.data.error;case 8:return e.abrupt("return",null===(i=o.data)||void 0===i?void 0:i.result);case 9:case"end":return e.stop()}var u,c}),e)})),p=function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){l(i,n,o,a,s,"next",e)}function s(e){l(i,n,o,a,s,"throw",e)}a(void 0)}))},p.apply(this,arguments)}var d=r(8680),h=r(784),y=r(3121),m=r(8287).Buffer;function v(e){return v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},v(e)}function g(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function b(e){for(var t=1;t=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),j(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:C(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function _(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function E(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){_(i,n,o,a,s,"next",e)}function s(e){_(i,n,o,a,s,"throw",e)}a(void 0)}))}}function k(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:{};if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.serverURL=i()(t),r.headers&&0!==Object.keys(r.headers).length&&s.interceptors.request.use((function(e){return e.headers=Object.assign(e.headers,r.headers),e})),"https"!==this.serverURL.protocol()&&!r.allowHttp)throw new Error("Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set")},j=[{key:"getAccount",value:(ne=E(S().mark((function e(t){var r,n,o;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=a.xdr.LedgerKey.account(new a.xdr.LedgerKeyAccount({accountId:a.Keypair.fromPublicKey(t).xdrPublicKey()})),e.next=3,this.getLedgerEntries(r);case 3:if(0!==(n=e.sent).entries.length){e.next=6;break}return e.abrupt("return",Promise.reject({code:404,message:"Account not found: ".concat(t)}));case 6:return o=n.entries[0].val.account(),e.abrupt("return",new a.Account(t,o.seqNum().toString()));case 8:case"end":return e.stop()}}),e,this)}))),function(e){return ne.apply(this,arguments)})},{key:"getHealth",value:(re=E(S().mark((function e(){return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",f(this.serverURL.toString(),"getHealth"));case 1:case"end":return e.stop()}}),e,this)}))),function(){return re.apply(this,arguments)})},{key:"getContractData",value:(te=E(S().mark((function e(t,r){var n,o,i,s,u=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=u.length>2&&void 0!==u[2]?u[2]:O.Persistent,"string"!=typeof t){e.next=5;break}o=new a.Contract(t).address().toScAddress(),e.next=14;break;case 5:if(!(t instanceof a.Address)){e.next=9;break}o=t.toScAddress(),e.next=14;break;case 9:if(!(t instanceof a.Contract)){e.next=13;break}o=t.address().toScAddress(),e.next=14;break;case 13:throw new TypeError("unknown contract type: ".concat(t));case 14:e.t0=n,e.next=e.t0===O.Temporary?17:e.t0===O.Persistent?19:21;break;case 17:return i=a.xdr.ContractDataDurability.temporary(),e.abrupt("break",22);case 19:return i=a.xdr.ContractDataDurability.persistent(),e.abrupt("break",22);case 21:throw new TypeError("invalid durability: ".concat(n));case 22:return s=a.xdr.LedgerKey.contractData(new a.xdr.LedgerKeyContractData({key:r,contract:o,durability:i})),e.abrupt("return",this.getLedgerEntries(s).then((function(e){return 0===e.entries.length?Promise.reject({code:404,message:"Contract data not found. Contract: ".concat(a.Address.fromScAddress(o).toString(),", Key: ").concat(r.toXDR("base64"),", Durability: ").concat(n)}):e.entries[0]})));case 24:case"end":return e.stop()}}),e,this)}))),function(e,t){return te.apply(this,arguments)})},{key:"getContractWasmByContractId",value:(ee=E(S().mark((function e(t){var r,n,o,i;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=new a.Contract(t).getFootprint(),e.next=3,this.getLedgerEntries(n);case 3:if((o=e.sent).entries.length&&null!==(r=o.entries[0])&&void 0!==r&&r.val){e.next=6;break}return e.abrupt("return",Promise.reject({code:404,message:"Could not obtain contract hash from server"}));case 6:return i=o.entries[0].val.contractData().val().instance().executable().wasmHash(),e.abrupt("return",this.getContractWasmByHash(i));case 8:case"end":return e.stop()}}),e,this)}))),function(e){return ee.apply(this,arguments)})},{key:"getContractWasmByHash",value:(Z=E(S().mark((function e(t){var r,n,o,i,s,u,c=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=c.length>1&&void 0!==c[1]?c[1]:void 0,o="string"==typeof t?m.from(t,n):t,i=a.xdr.LedgerKey.contractCode(new a.xdr.LedgerKeyContractCode({hash:o})),e.next=5,this.getLedgerEntries(i);case 5:if((s=e.sent).entries.length&&null!==(r=s.entries[0])&&void 0!==r&&r.val){e.next=8;break}return e.abrupt("return",Promise.reject({code:404,message:"Could not obtain contract wasm from server"}));case 8:return u=s.entries[0].val.contractCode().code(),e.abrupt("return",u);case 10:case"end":return e.stop()}}),e,this)}))),function(e){return Z.apply(this,arguments)})},{key:"getLedgerEntries",value:(J=E(S().mark((function e(){var t=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this._getLedgerEntries.apply(this,t).then(h.$D));case 1:case"end":return e.stop()}}),e,this)}))),function(){return J.apply(this,arguments)})},{key:"_getLedgerEntries",value:(Y=E(S().mark((function e(){var t,r,n,o=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(t=o.length,r=new Array(t),n=0;n{"use strict";r.d(t,{$D:()=>d,Af:()=>c,WC:()=>l,fG:()=>p,jr:()=>h,tR:()=>f});var n=r(356),o=r(4076);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function s(e){for(var t=1;t0&&{diagnosticEvents:r.map((function(e){return n.xdr.DiagnosticEvent.fromXDR(e,"base64")}))}),{},{errorResult:n.xdr.TransactionResult.fromXDR(t,"base64")}):s({},e)}function l(e){var t,r=n.xdr.TransactionMeta.fromXDR(e.resultMetaXdr,"base64"),o={ledger:e.ledger,createdAt:e.createdAt,applicationOrder:e.applicationOrder,feeBump:e.feeBump,envelopeXdr:n.xdr.TransactionEnvelope.fromXDR(e.envelopeXdr,"base64"),resultXdr:n.xdr.TransactionResult.fromXDR(e.resultXdr,"base64"),resultMetaXdr:r};3===r.switch()&&null!==r.v3().sorobanMeta()&&(o.returnValue=null===(t=r.v3().sorobanMeta())||void 0===t?void 0:t.returnValue());return"diagnosticEventsXdr"in e&&e.diagnosticEventsXdr&&(o.diagnosticEventsXdr=e.diagnosticEventsXdr.map((function(e){return n.xdr.DiagnosticEvent.fromXDR(e,"base64")}))),o}function f(e){return s({status:e.status,txHash:e.txHash},l(e))}function p(e){var t;return{latestLedger:e.latestLedger,cursor:e.cursor,events:(null!==(t=e.events)&&void 0!==t?t:[]).map((function(e){var t=s({},e);return delete t.contractId,s(s(s({},t),""!==e.contractId&&{contractId:new n.Contract(e.contractId)}),{},{topic:e.topic.map((function(e){return n.xdr.ScVal.fromXDR(e,"base64")})),value:n.xdr.ScVal.fromXDR(e.value,"base64")})}))}}function d(e){var t;return{latestLedger:e.latestLedger,entries:(null!==(t=e.entries)&&void 0!==t?t:[]).map((function(e){if(!e.key||!e.xdr)throw new TypeError("invalid ledger entry: ".concat(JSON.stringify(e)));return s({lastModifiedLedgerSeq:e.lastModifiedLedgerSeq,key:n.xdr.LedgerKey.fromXDR(e.key,"base64"),val:n.xdr.LedgerEntryData.fromXDR(e.xdr,"base64")},void 0!==e.liveUntilLedgerSeq&&{liveUntilLedgerSeq:e.liveUntilLedgerSeq})}))}}function h(e){var t,r;if(!o.j.isSimulationRaw(e))return e;var i={_parsed:!0,id:e.id,latestLedger:e.latestLedger,events:null!==(t=null===(r=e.events)||void 0===r?void 0:r.map((function(e){return n.xdr.DiagnosticEvent.fromXDR(e,"base64")})))&&void 0!==t?t:[]};return"string"==typeof e.error?s(s({},i),{},{error:e.error}):function(e,t){var r,o,i,a,u,c=s(s(s({},t),{},{transactionData:new n.SorobanDataBuilder(e.transactionData),minResourceFee:e.minResourceFee},null!==(r=null===(o=e.results)||void 0===o?void 0:o.length)&&void 0!==r&&r&&{result:e.results.map((function(e){var t;return{auth:(null!==(t=e.auth)&&void 0!==t?t:[]).map((function(e){return n.xdr.SorobanAuthorizationEntry.fromXDR(e,"base64")})),retval:e.xdr?n.xdr.ScVal.fromXDR(e.xdr,"base64"):n.xdr.ScVal.scvVoid()}}))[0]}),null!==(i=null===(a=e.stateChanges)||void 0===a?void 0:a.length)&&void 0!==i&&i&&{stateChanges:null===(u=e.stateChanges)||void 0===u?void 0:u.map((function(e){return{type:e.type,key:n.xdr.LedgerKey.fromXDR(e.key,"base64"),before:e.before?n.xdr.LedgerEntry.fromXDR(e.before,"base64"):null,after:e.after?n.xdr.LedgerEntry.fromXDR(e.after,"base64"):null}}))});return e.restorePreamble&&""!==e.restorePreamble.transactionData?s(s({},c),{},{restorePreamble:{minResourceFee:e.restorePreamble.minResourceFee,transactionData:new n.SorobanDataBuilder(e.restorePreamble.transactionData)}}):c}(e,i)}},8680:(e,t,r)=>{"use strict";r.d(t,{X:()=>a});var n=r(356),o=r(4076),i=r(784);function a(e,t){if("innerTransaction"in e)return a(e.innerTransaction,t);if(!function(e){if(1!==e.operations.length)return!1;switch(e.operations[0].type){case"invokeHostFunction":case"extendFootprintTtl":case"restoreFootprint":return!0;default:return!1}}(e))throw new TypeError("unsupported transaction: must contain exactly one invokeHostFunction, extendFootprintTtl, or restoreFootprint operation");var r=(0,i.jr)(t);if(!o.j.isSimulationSuccess(r))throw new Error("simulation incorrect: ".concat(JSON.stringify(r)));var s=parseInt(e.fee)||0,u=parseInt(r.minResourceFee)||0,c=n.TransactionBuilder.cloneFrom(e,{fee:(s+u).toString(),sorobanData:r.transactionData.build(),networkPassphrase:e.networkPassphrase});if("invokeHostFunction"===e.operations[0].type){var l;c.clearOperations();var f=e.operations[0],p=null!==(l=f.auth)&&void 0!==l?l:[];c.addOperation(n.Operation.invokeHostFunction({source:f.source,func:f.func,auth:p.length>0?p:r.result.auth}))}return c}},3898:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Api:()=>{},Resolver:()=>b,STELLAR_TOML_MAX_SIZE:()=>v});var n=r(1293),o=r.n(n),i=r(6371),a=r(8732);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(){u=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",l=i.toStringTag||"@@toStringTag";function f(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{f({},"")}catch(e){f=function(e,t,r){return e[t]=r}}function p(e,t,r,n){var i=t&&t.prototype instanceof b?t:b,a=Object.create(i.prototype),s=new I(n||[]);return o(a,"_invoke",{value:A(e,r,s)}),a}function d(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=p;var h="suspendedStart",y="suspendedYield",m="executing",v="completed",g={};function b(){}function w(){}function S(){}var _={};f(_,a,(function(){return this}));var E=Object.getPrototypeOf,k=E&&E(E(C([])));k&&k!==r&&n.call(k,a)&&(_=k);var T=S.prototype=b.prototype=Object.create(_);function O(e){["next","throw","return"].forEach((function(t){f(e,t,(function(e){return this._invoke(t,e)}))}))}function x(e,t){function r(o,i,a,u){var c=d(e[o],e,i);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==s(f)&&n.call(f,"__await")?t.resolve(f.__await).then((function(e){r("next",e,a,u)}),(function(e){r("throw",e,a,u)})):t.resolve(f).then((function(e){l.value=e,a(l)}),(function(e){return r("throw",e,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function A(t,r,n){var o=h;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=P(s,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=m;var c=d(t,r,n);if("normal"===c.type){if(o=n.done?v:y,c.arg===g)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=v,n.method="throw",n.arg=c.arg)}}}function P(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,P(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=d(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function R(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function j(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function I(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(R,this),this.reset(!0)}function C(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),j(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:C(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function c(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function l(e,t){for(var r=0;r1&&void 0!==f[1]?f[1]:{}).allowHttp?a.T.isAllowHttp():n.allowHttp,c=void 0===n.timeout?a.T.getTimeout():n.timeout,l=s?"http":"https",e.abrupt("return",i.ok.get("".concat(l,"://").concat(t,"/.well-known/stellar.toml"),{maxRedirects:null!==(r=n.allowedRedirects)&&void 0!==r?r:0,maxContentLength:v,cancelToken:c?new g((function(e){return setTimeout((function(){return e("timeout of ".concat(c,"ms exceeded"))}),c)})):void 0,timeout:c}).then((function(e){try{var t=o().parse(e.data);return Promise.resolve(t)}catch(e){return Promise.reject(new Error("stellar.toml is invalid - Parsing error on line ".concat(e.line,", column ").concat(e.column,": ").concat(e.message)))}})).catch((function(e){throw e.message.match(/^maxContentLength size/)?new Error("stellar.toml file exceeds allowed size of ".concat(v)):e})));case 5:case"end":return e.stop()}}),e)})),m=function(){var e=this,t=arguments;return new Promise((function(r,n){var o=y.apply(e,t);function i(e){c(o,r,n,i,a,"next",e)}function a(e){c(o,r,n,i,a,"throw",e)}i(void 0)}))},function(e){return m.apply(this,arguments)})}],d&&l(p.prototype,d),h&&l(p,h),Object.defineProperty(p,"prototype",{writable:!1}),p)},3121:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rc});var a,s,u,c=(a=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},u=[{key:"validateTimebounds",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!e.timeBounds)return!1;var r=Math.floor(Date.now()/1e3),n=e.timeBounds,o=n.minTime,i=n.maxTime;return r>=Number.parseInt(o,10)-t&&r<=Number.parseInt(i,10)+t}},{key:"sleep",value:function(e){return new Promise((function(t){return setTimeout(t,e)}))}}],(s=null)&&o(a.prototype,s),u&&o(a,u),Object.defineProperty(a,"prototype",{writable:!1}),a)},5479:(e,t,r)=>{"use strict";r.r(t),r.d(t,{InvalidChallengeError:()=>y,buildChallengeTx:()=>k,gatherTxSigners:()=>P,readChallengeTx:()=>T,verifyChallengeTxSigners:()=>x,verifyChallengeTxThreshold:()=>O,verifyTxSignedBy:()=>A});var n=r(3209),o=r.n(n),i=r(356),a=r(3121);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){for(var r=0;r=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,i=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw i}}}}function b(e){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},b(e)}function w(e){return function(e){if(Array.isArray(e))return e}(e)||E(e)||S(e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function S(e,t){if(e){if("string"==typeof e)return _(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_(e,t):void 0}}function _(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r3&&void 0!==arguments[3]?arguments[3]:300,a=arguments.length>4?arguments[4]:void 0,s=arguments.length>5?arguments[5]:void 0,u=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,c=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null,l=arguments.length>8&&void 0!==arguments[8]?arguments[8]:null;if(t.startsWith("M")&&u)throw Error("memo cannot be used if clientAccountID is a muxed account");var f=new i.Account(e.publicKey(),"-1"),p=Math.floor(Date.now()/1e3),d=o()(48).toString("base64"),h=new i.TransactionBuilder(f,{fee:i.BASE_FEE,networkPassphrase:a,timebounds:{minTime:p,maxTime:p+n}}).addOperation(i.Operation.manageData({name:"".concat(r," auth"),value:d,source:t})).addOperation(i.Operation.manageData({name:"web_auth_domain",value:s,source:f.accountId()}));if(c){if(!l)throw Error("clientSigningKey is required if clientDomain is provided");h.addOperation(i.Operation.manageData({name:"client_domain",value:c,source:l}))}u&&h.addMemo(i.Memo.id(u));var y=h.build();return y.sign(e),y.toEnvelope().toXDR("base64").toString()}function T(e,t,r,n,o){var s,u;if(t.startsWith("M"))throw Error("Invalid serverAccountID: multiplexed accounts are not supported.");try{u=new i.Transaction(e,r)}catch(t){try{u=new i.FeeBumpTransaction(e,r)}catch(e){throw new y("Invalid challenge: unable to deserialize challengeTx transaction string")}throw new y("Invalid challenge: expected a Transaction but received a FeeBumpTransaction")}if(0!==Number.parseInt(u.sequence,10))throw new y("The transaction sequence number should be zero");if(u.source!==t)throw new y("The transaction source account is not equal to the server's account");if(u.operations.length<1)throw new y("The transaction should contain at least one operation");var c=w(u.operations),l=c[0],f=c.slice(1);if(!l.source)throw new y("The transaction's operation should contain a source account");var p,d=l.source,h=null;if(u.memo.type!==i.MemoNone){if(d.startsWith("M"))throw new y("The transaction has a memo but the client account ID is a muxed account");if(u.memo.type!==i.MemoID)throw new y("The transaction's memo must be of type `id`");h=u.memo.value}if("manageData"!==l.type)throw new y("The transaction's operation type should be 'manageData'");if(u.timeBounds&&Number.parseInt(null===(s=u.timeBounds)||void 0===s?void 0:s.maxTime,10)===i.TimeoutInfinite)throw new y("The transaction requires non-infinite timebounds");if(!a.A.validateTimebounds(u,300))throw new y("The transaction has expired");if(void 0===l.value)throw new y("The transaction's operation values should not be null");if(!l.value)throw new y("The transaction's operation value should not be null");if(48!==m.from(l.value.toString(),"base64").length)throw new y("The transaction's operation value should be a 64 bytes base64 random string");if(!n)throw new y("Invalid homeDomains: a home domain must be provided for verification");if("string"==typeof n)"".concat(n," auth")===l.name&&(p=n);else{if(!Array.isArray(n))throw new y("Invalid homeDomains: homeDomains type is ".concat(b(n)," but should be a string or an array"));p=n.find((function(e){return"".concat(e," auth")===l.name}))}if(!p)throw new y("Invalid homeDomains: the transaction's operation key name does not match the expected home domain");var v,S=g(f);try{for(S.s();!(v=S.n()).done;){var _=v.value;if("manageData"!==_.type)throw new y("The transaction has operations that are not of type 'manageData'");if(_.source!==t&&"client_domain"!==_.name)throw new y("The transaction has operations that are unrecognized");if("web_auth_domain"===_.name){if(void 0===_.value)throw new y("'web_auth_domain' operation value should not be null");if(_.value.compare(m.from(o)))throw new y("'web_auth_domain' operation value does not match ".concat(o))}}}catch(e){S.e(e)}finally{S.f()}if(!A(u,t))throw new y("Transaction not signed by server: '".concat(t,"'"));return{tx:u,clientAccountID:d,matchedHomeDomain:p,memo:h}}function O(e,t,r,n,o,i,a){for(var s=x(e,t,r,o.map((function(e){return e.key})),i,a),u=0,c=function(){var e,t=f[l],r=(null===(e=o.find((function(e){return e.key===t})))||void 0===e?void 0:e.weight)||0;u+=r},l=0,f=s;l{"use strict";var r=function(e,t){return t||(t={}),e.split("").forEach((function(e,r){e in t||(t[e]=r)})),t},n={alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",charmap:{0:14,1:8}};n.charmap=r(n.alphabet,n.charmap);var o={alphabet:"0123456789ABCDEFGHJKMNPQRSTVWXYZ",charmap:{O:0,I:1,L:1}};o.charmap=r(o.alphabet,o.charmap);var i={alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",charmap:{}};function a(e){if(this.buf=[],this.shift=8,this.carry=0,e){switch(e.type){case"rfc4648":this.charmap=t.rfc4648.charmap;break;case"crockford":this.charmap=t.crockford.charmap;break;case"base32hex":this.charmap=t.base32hex.charmap;break;default:throw new Error("invalid type")}e.charmap&&(this.charmap=e.charmap)}}function s(e){if(this.buf="",this.shift=3,this.carry=0,e){switch(e.type){case"rfc4648":this.alphabet=t.rfc4648.alphabet;break;case"crockford":this.alphabet=t.crockford.alphabet;break;case"base32hex":this.alphabet=t.base32hex.alphabet;break;default:throw new Error("invalid type")}e.alphabet?this.alphabet=e.alphabet:e.lc&&(this.alphabet=this.alphabet.toLowerCase())}}i.charmap=r(i.alphabet,i.charmap),a.prototype.charmap=n.charmap,a.prototype.write=function(e){var t=this.charmap,r=this.buf,n=this.shift,o=this.carry;return e.toUpperCase().split("").forEach((function(e){if("="!=e){var i=255&t[e];(n-=5)>0?o|=i<>-n),o=i<<(n+=8)&255):(r.push(o|i),n=8,o=0)}})),this.shift=n,this.carry=o,this},a.prototype.finalize=function(e){return e&&this.write(e),8!==this.shift&&0!==this.carry&&(this.buf.push(this.carry),this.shift=8,this.carry=0),this.buf},s.prototype.alphabet=n.alphabet,s.prototype.write=function(e){var t,r,n,o=this.shift,i=this.carry;for(n=0;n>o,this.buf+=this.alphabet[31&t],o>5&&(t=r>>(o-=5),this.buf+=this.alphabet[31&t]),i=r<<(o=5-o),o=8-o;return this.shift=o,this.carry=i,this},s.prototype.finalize=function(e){return e&&this.write(e),3!==this.shift&&(this.buf+=this.alphabet[31&this.carry],this.shift=3,this.carry=0),this.buf},t.encode=function(e,t){return new s(t).finalize(e)},t.decode=function(e,t){return new a(t).finalize(e)},t.Decoder=a,t.Encoder=s,t.charmap=r,t.crockford=o,t.rfc4648=n,t.base32hex=i},7526:(e,t)=>{"use strict";t.byteLength=function(e){var t=s(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,i=s(e),a=i[0],u=i[1],c=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,u)),l=0,f=u>0?a-4:a;for(r=0;r>16&255,c[l++]=t>>8&255,c[l++]=255&t;2===u&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,c[l++]=255&t);1===u&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t);return c},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],a=16383,s=0,c=n-o;sc?c:s+a));1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return i.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)r[a]=i[a],n[i.charCodeAt(a)]=a;function s(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,n){for(var o,i,a=[],s=t;s>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return a.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},1594:function(e,t,r){var n;!function(){"use strict";var o,i=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,a=Math.ceil,s=Math.floor,u="[BigNumber Error] ",c=u+"Number primitive has more than 15 significant digits: ",l=1e14,f=14,p=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],h=1e7,y=1e9;function m(e){var t=0|e;return e>0||e===t?t:t-1}function v(e){for(var t,r,n=1,o=e.length,i=e[0]+"";nc^r?1:-1;for(s=(u=o.length)<(c=i.length)?u:c,a=0;ai[a]^r?1:-1;return u==c?0:u>c^r?1:-1}function b(e,t,r,n){if(er||e!==s(e))throw Error(u+(n||"Argument")+("number"==typeof e?er?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function w(e){var t=e.c.length-1;return m(e.e/f)==t&&e.c[t]%2!=0}function S(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function _(e,t,r){var n,o;if(t<0){for(o=r+".";++t;o+=r);e=o+e}else if(++t>(n=e.length)){for(o=r,t-=n;--t;o+=r);e+=o}else tU?v.c=v.e=null:e.e=10;d/=10,l++);return void(l>U?v.c=v.e=null:(v.e=l,v.c=[e]))}m=String(e)}else{if(!i.test(m=String(e)))return o(v,m,h);v.s=45==m.charCodeAt(0)?(m=m.slice(1),-1):1}(l=m.indexOf("."))>-1&&(m=m.replace(".","")),(d=m.search(/e/i))>0?(l<0&&(l=d),l+=+m.slice(d+1),m=m.substring(0,d)):l<0&&(l=m.length)}else{if(b(t,2,q.length,"Base"),10==t&&K)return W(v=new H(e),I+v.e+1,C);if(m=String(e),h="number"==typeof e){if(0*e!=0)return o(v,m,h,t);if(v.s=1/e<0?(m=m.slice(1),-1):1,H.DEBUG&&m.replace(/^0\.0*|\./,"").length>15)throw Error(c+e)}else v.s=45===m.charCodeAt(0)?(m=m.slice(1),-1):1;for(r=q.slice(0,t),l=d=0,y=m.length;dl){l=y;continue}}else if(!u&&(m==m.toUpperCase()&&(m=m.toLowerCase())||m==m.toLowerCase()&&(m=m.toUpperCase()))){u=!0,d=-1,l=0;continue}return o(v,String(e),h,t)}h=!1,(l=(m=n(m,t,10,v.s)).indexOf("."))>-1?m=m.replace(".",""):l=m.length}for(d=0;48===m.charCodeAt(d);d++);for(y=m.length;48===m.charCodeAt(--y););if(m=m.slice(d,++y)){if(y-=d,h&&H.DEBUG&&y>15&&(e>p||e!==s(e)))throw Error(c+v.s*e);if((l=l-d-1)>U)v.c=v.e=null;else if(l=B)?S(u,a):_(u,a,"0");else if(i=(e=W(new H(e),t,r)).e,s=(u=v(e.c)).length,1==n||2==n&&(t<=i||i<=L)){for(;ss){if(--t>0)for(u+=".";t--;u+="0");}else if((t+=i-s)>0)for(i+1==s&&(u+=".");t--;u+="0");return e.s<0&&o?"-"+u:u}function X(e,t){for(var r,n,o=1,i=new H(e[0]);o=10;o/=10,n++);return(r=n+r*f-1)>U?e.c=e.e=null:r=10;c/=10,o++);if((i=t-o)<0)i+=f,u=t,p=m[h=0],y=s(p/v[o-u-1]%10);else if((h=a((i+1)/f))>=m.length){if(!n)break e;for(;m.length<=h;m.push(0));p=y=0,o=1,u=(i%=f)-f+1}else{for(p=c=m[h],o=1;c>=10;c/=10,o++);y=(u=(i%=f)-f+o)<0?0:s(p/v[o-u-1]%10)}if(n=n||t<0||null!=m[h+1]||(u<0?p:p%v[o-u-1]),n=r<4?(y||n)&&(0==r||r==(e.s<0?3:2)):y>5||5==y&&(4==r||n||6==r&&(i>0?u>0?p/v[o-u]:0:m[h-1])%10&1||r==(e.s<0?8:7)),t<1||!m[0])return m.length=0,n?(t-=e.e+1,m[0]=v[(f-t%f)%f],e.e=-t||0):m[0]=e.e=0,e;if(0==i?(m.length=h,c=1,h--):(m.length=h+1,c=v[f-i],m[h]=u>0?s(p/v[o-u]%v[u])*c:0),n)for(;;){if(0==h){for(i=1,u=m[0];u>=10;u/=10,i++);for(u=m[0]+=c,c=1;u>=10;u/=10,c++);i!=c&&(e.e++,m[0]==l&&(m[0]=1));break}if(m[h]+=c,m[h]!=l)break;m[h--]=0,c=1}for(i=m.length;0===m[--i];m.pop());}e.e>U?e.c=e.e=null:e.e=B?S(t,r):_(t,r,"0"),e.s<0?"-"+t:t)}return H.clone=e,H.ROUND_UP=0,H.ROUND_DOWN=1,H.ROUND_CEIL=2,H.ROUND_FLOOR=3,H.ROUND_HALF_UP=4,H.ROUND_HALF_DOWN=5,H.ROUND_HALF_EVEN=6,H.ROUND_HALF_CEIL=7,H.ROUND_HALF_FLOOR=8,H.EUCLID=9,H.config=H.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(u+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(b(r=e[t],0,y,t),I=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(b(r=e[t],0,8,t),C=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(b(r[0],-y,0,t),b(r[1],0,y,t),L=r[0],B=r[1]):(b(r,-y,y,t),L=-(B=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)b(r[0],-y,-1,t),b(r[1],1,y,t),N=r[0],U=r[1];else{if(b(r,-y,y,t),!r)throw Error(u+t+" cannot be zero: "+r);N=-(U=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(u+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw M=!r,Error(u+"crypto unavailable");M=r}else M=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(b(r=e[t],0,9,t),D=r),e.hasOwnProperty(t="POW_PRECISION")&&(b(r=e[t],0,y,t),F=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(u+t+" not an object: "+r);V=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(u+t+" invalid: "+r);K="0123456789"==r.slice(0,10),q=r}}return{DECIMAL_PLACES:I,ROUNDING_MODE:C,EXPONENTIAL_AT:[L,B],RANGE:[N,U],CRYPTO:M,MODULO_MODE:D,POW_PRECISION:F,FORMAT:V,ALPHABET:q}},H.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!H.DEBUG)return!0;var t,r,n=e.c,o=e.e,i=e.s;e:if("[object Array]"=={}.toString.call(n)){if((1===i||-1===i)&&o>=-y&&o<=y&&o===s(o)){if(0===n[0]){if(0===o&&1===n.length)return!0;break e}if((t=(o+1)%f)<1&&(t+=f),String(n[0]).length==t){for(t=0;t=l||r!==s(r))break e;if(0!==r)return!0}}}else if(null===n&&null===o&&(null===i||1===i||-1===i))return!0;throw Error(u+"Invalid BigNumber: "+e)},H.maximum=H.max=function(){return X(arguments,-1)},H.minimum=H.min=function(){return X(arguments,1)},H.random=(E=9007199254740992,k=Math.random()*E&2097151?function(){return s(Math.random()*E)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,n,o,i,c=0,l=[],p=new H(j);if(null==e?e=I:b(e,0,y),o=a(e/f),M)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(o*=2));c>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[c]=r[0],t[c+1]=r[1]):(l.push(i%1e14),c+=2);c=o/2}else{if(!crypto.randomBytes)throw M=!1,Error(u+"crypto unavailable");for(t=crypto.randomBytes(o*=7);c=9e15?crypto.randomBytes(7).copy(t,c):(l.push(i%1e14),c+=7);c=o/7}if(!M)for(;c=10;i/=10,c++);cr-1&&(null==a[o+1]&&(a[o+1]=0),a[o+1]+=a[o]/r|0,a[o]%=r)}return a.reverse()}return function(n,o,i,a,s){var u,c,l,f,p,d,h,y,m=n.indexOf("."),g=I,b=C;for(m>=0&&(f=F,F=0,n=n.replace(".",""),d=(y=new H(o)).pow(n.length-m),F=f,y.c=t(_(v(d.c),d.e,"0"),10,i,e),y.e=y.c.length),l=f=(h=t(n,o,i,s?(u=q,e):(u=e,q))).length;0==h[--f];h.pop());if(!h[0])return u.charAt(0);if(m<0?--l:(d.c=h,d.e=l,d.s=a,h=(d=r(d,y,g,b,i)).c,p=d.r,l=d.e),m=h[c=l+g+1],f=i/2,p=p||c<0||null!=h[c+1],p=b<4?(null!=m||p)&&(0==b||b==(d.s<0?3:2)):m>f||m==f&&(4==b||p||6==b&&1&h[c-1]||b==(d.s<0?8:7)),c<1||!h[0])n=p?_(u.charAt(1),-g,u.charAt(0)):u.charAt(0);else{if(h.length=c,p)for(--i;++h[--c]>i;)h[c]=0,c||(++l,h=[1].concat(h));for(f=h.length;!h[--f];);for(m=0,n="";m<=f;n+=u.charAt(h[m++]));n=_(n,l,u.charAt(0))}return n}}(),r=function(){function e(e,t,r){var n,o,i,a,s=0,u=e.length,c=t%h,l=t/h|0;for(e=e.slice();u--;)s=((o=c*(i=e[u]%h)+(n=l*i+(a=e[u]/h|0)*c)%h*h+s)/r|0)+(n/h|0)+l*a,e[u]=o%r;return s&&(e=[s].concat(e)),e}function t(e,t,r,n){var o,i;if(r!=n)i=r>n?1:-1;else for(o=i=0;ot[o]?1:-1;break}return i}function r(e,t,r,n){for(var o=0;r--;)e[r]-=o,o=e[r]1;e.splice(0,1));}return function(n,o,i,a,u){var c,p,d,h,y,v,g,b,w,S,_,E,k,T,O,x,A,P=n.s==o.s?1:-1,R=n.c,j=o.c;if(!(R&&R[0]&&j&&j[0]))return new H(n.s&&o.s&&(R?!j||R[0]!=j[0]:j)?R&&0==R[0]||!j?0*P:P/0:NaN);for(w=(b=new H(P)).c=[],P=i+(p=n.e-o.e)+1,u||(u=l,p=m(n.e/f)-m(o.e/f),P=P/f|0),d=0;j[d]==(R[d]||0);d++);if(j[d]>(R[d]||0)&&p--,P<0)w.push(1),h=!0;else{for(T=R.length,x=j.length,d=0,P+=2,(y=s(u/(j[0]+1)))>1&&(j=e(j,y,u),R=e(R,y,u),x=j.length,T=R.length),k=x,_=(S=R.slice(0,x)).length;_=u/2&&O++;do{if(y=0,(c=t(j,S,x,_))<0){if(E=S[0],x!=_&&(E=E*u+(S[1]||0)),(y=s(E/O))>1)for(y>=u&&(y=u-1),g=(v=e(j,y,u)).length,_=S.length;1==t(v,S,g,_);)y--,r(v,x=10;P/=10,d++);W(b,i+(b.e=d+p*f-1)+1,a,h)}else b.e=p,b.r=+h;return b}}(),T=/^(-?)0([xbo])(?=\w[\w.]*$)/i,O=/^([^.]+)\.$/,x=/^\.([^.]+)$/,A=/^-?(Infinity|NaN)$/,P=/^\s*\+(?=[\w.])|^\s+|\s+$/g,o=function(e,t,r,n){var o,i=r?t:t.replace(P,"");if(A.test(i))e.s=isNaN(i)?null:i<0?-1:1;else{if(!r&&(i=i.replace(T,(function(e,t,r){return o="x"==(r=r.toLowerCase())?16:"b"==r?2:8,n&&n!=o?e:t})),n&&(o=n,i=i.replace(O,"$1").replace(x,"0.$1")),t!=i))return new H(i,o);if(H.DEBUG)throw Error(u+"Not a"+(n?" base "+n:"")+" number: "+t);e.s=null}e.c=e.e=null},R.absoluteValue=R.abs=function(){var e=new H(this);return e.s<0&&(e.s=1),e},R.comparedTo=function(e,t){return g(this,new H(e,t))},R.decimalPlaces=R.dp=function(e,t){var r,n,o,i=this;if(null!=e)return b(e,0,y),null==t?t=C:b(t,0,8),W(new H(i),e+i.e+1,t);if(!(r=i.c))return null;if(n=((o=r.length-1)-m(this.e/f))*f,o=r[o])for(;o%10==0;o/=10,n--);return n<0&&(n=0),n},R.dividedBy=R.div=function(e,t){return r(this,new H(e,t),I,C)},R.dividedToIntegerBy=R.idiv=function(e,t){return r(this,new H(e,t),0,1)},R.exponentiatedBy=R.pow=function(e,t){var r,n,o,i,c,l,p,d,h=this;if((e=new H(e)).c&&!e.isInteger())throw Error(u+"Exponent not an integer: "+$(e));if(null!=t&&(t=new H(t)),c=e.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!e.c||!e.c[0])return d=new H(Math.pow(+$(h),c?e.s*(2-w(e)):+$(e))),t?d.mod(t):d;if(l=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new H(NaN);(n=!l&&h.isInteger()&&t.isInteger())&&(h=h.mod(t))}else{if(e.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||c&&h.c[1]>=24e7:h.c[0]<8e13||c&&h.c[0]<=9999975e7)))return i=h.s<0&&w(e)?-0:0,h.e>-1&&(i=1/i),new H(l?1/i:i);F&&(i=a(F/f+2))}for(c?(r=new H(.5),l&&(e.s=1),p=w(e)):p=(o=Math.abs(+$(e)))%2,d=new H(j);;){if(p){if(!(d=d.times(h)).c)break;i?d.c.length>i&&(d.c.length=i):n&&(d=d.mod(t))}if(o){if(0===(o=s(o/2)))break;p=o%2}else if(W(e=e.times(r),e.e+1,1),e.e>14)p=w(e);else{if(0===(o=+$(e)))break;p=o%2}h=h.times(h),i?h.c&&h.c.length>i&&(h.c.length=i):n&&(h=h.mod(t))}return n?d:(l&&(d=j.div(d)),t?d.mod(t):i?W(d,F,C,undefined):d)},R.integerValue=function(e){var t=new H(this);return null==e?e=C:b(e,0,8),W(t,t.e+1,e)},R.isEqualTo=R.eq=function(e,t){return 0===g(this,new H(e,t))},R.isFinite=function(){return!!this.c},R.isGreaterThan=R.gt=function(e,t){return g(this,new H(e,t))>0},R.isGreaterThanOrEqualTo=R.gte=function(e,t){return 1===(t=g(this,new H(e,t)))||0===t},R.isInteger=function(){return!!this.c&&m(this.e/f)>this.c.length-2},R.isLessThan=R.lt=function(e,t){return g(this,new H(e,t))<0},R.isLessThanOrEqualTo=R.lte=function(e,t){return-1===(t=g(this,new H(e,t)))||0===t},R.isNaN=function(){return!this.s},R.isNegative=function(){return this.s<0},R.isPositive=function(){return this.s>0},R.isZero=function(){return!!this.c&&0==this.c[0]},R.minus=function(e,t){var r,n,o,i,a=this,s=a.s;if(t=(e=new H(e,t)).s,!s||!t)return new H(NaN);if(s!=t)return e.s=-t,a.plus(e);var u=a.e/f,c=e.e/f,p=a.c,d=e.c;if(!u||!c){if(!p||!d)return p?(e.s=-t,e):new H(d?a:NaN);if(!p[0]||!d[0])return d[0]?(e.s=-t,e):new H(p[0]?a:3==C?-0:0)}if(u=m(u),c=m(c),p=p.slice(),s=u-c){for((i=s<0)?(s=-s,o=p):(c=u,o=d),o.reverse(),t=s;t--;o.push(0));o.reverse()}else for(n=(i=(s=p.length)<(t=d.length))?s:t,s=t=0;t0)for(;t--;p[r++]=0);for(t=l-1;n>s;){if(p[--n]=0;){for(r=0,y=E[o]%w,v=E[o]/w|0,i=o+(a=u);i>o;)r=((c=y*(c=_[--a]%w)+(s=v*c+(p=_[a]/w|0)*y)%w*w+g[i]+r)/b|0)+(s/w|0)+v*p,g[i--]=c%b;g[i]=r}return r?++n:g.splice(0,1),G(e,g,n)},R.negated=function(){var e=new H(this);return e.s=-e.s||null,e},R.plus=function(e,t){var r,n=this,o=n.s;if(t=(e=new H(e,t)).s,!o||!t)return new H(NaN);if(o!=t)return e.s=-t,n.minus(e);var i=n.e/f,a=e.e/f,s=n.c,u=e.c;if(!i||!a){if(!s||!u)return new H(o/0);if(!s[0]||!u[0])return u[0]?e:new H(s[0]?n:0*o)}if(i=m(i),a=m(a),s=s.slice(),o=i-a){for(o>0?(a=i,r=u):(o=-o,r=s),r.reverse();o--;r.push(0));r.reverse()}for((o=s.length)-(t=u.length)<0&&(r=u,u=s,s=r,t=o),o=0;t;)o=(s[--t]=s[t]+u[t]+o)/l|0,s[t]=l===s[t]?0:s[t]%l;return o&&(s=[o].concat(s),++a),G(e,s,a)},R.precision=R.sd=function(e,t){var r,n,o,i=this;if(null!=e&&e!==!!e)return b(e,1,y),null==t?t=C:b(t,0,8),W(new H(i),e,t);if(!(r=i.c))return null;if(n=(o=r.length-1)*f+1,o=r[o]){for(;o%10==0;o/=10,n--);for(o=r[0];o>=10;o/=10,n++);}return e&&i.e+1>n&&(n=i.e+1),n},R.shiftedBy=function(e){return b(e,-9007199254740991,p),this.times("1e"+e)},R.squareRoot=R.sqrt=function(){var e,t,n,o,i,a=this,s=a.c,u=a.s,c=a.e,l=I+4,f=new H("0.5");if(1!==u||!s||!s[0])return new H(!u||u<0&&(!s||s[0])?NaN:s?a:1/0);if(0==(u=Math.sqrt(+$(a)))||u==1/0?(((t=v(s)).length+c)%2==0&&(t+="0"),u=Math.sqrt(+t),c=m((c+1)/2)-(c<0||c%2),n=new H(t=u==1/0?"5e"+c:(t=u.toExponential()).slice(0,t.indexOf("e")+1)+c)):n=new H(u+""),n.c[0])for((u=(c=n.e)+l)<3&&(u=0);;)if(i=n,n=f.times(i.plus(r(a,i,l,1))),v(i.c).slice(0,u)===(t=v(n.c)).slice(0,u)){if(n.e0&&y>0){for(i=y%s||s,f=h.substr(0,i);i0&&(f+=l+h.slice(i)),d&&(f="-"+f)}n=p?f+(r.decimalSeparator||"")+((c=+r.fractionGroupSize)?p.replace(new RegExp("\\d{"+c+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):p):f}return(r.prefix||"")+n+(r.suffix||"")},R.toFraction=function(e){var t,n,o,i,a,s,c,l,p,h,y,m,g=this,b=g.c;if(null!=e&&(!(c=new H(e)).isInteger()&&(c.c||1!==c.s)||c.lt(j)))throw Error(u+"Argument "+(c.isInteger()?"out of range: ":"not an integer: ")+$(c));if(!b)return new H(g);for(t=new H(j),p=n=new H(j),o=l=new H(j),m=v(b),a=t.e=m.length-g.e-1,t.c[0]=d[(s=a%f)<0?f+s:s],e=!e||c.comparedTo(t)>0?a>0?t:p:c,s=U,U=1/0,c=new H(m),l.c[0]=0;h=r(c,t,0,1),1!=(i=n.plus(h.times(o))).comparedTo(e);)n=o,o=i,p=l.plus(h.times(i=p)),l=i,t=c.minus(h.times(i=t)),c=i;return i=r(e.minus(n),o,0,1),l=l.plus(i.times(p)),n=n.plus(i.times(o)),l.s=p.s=g.s,y=r(p,o,a*=2,C).minus(g).abs().comparedTo(r(l,n,a,C).minus(g).abs())<1?[p,o]:[l,n],U=s,y},R.toNumber=function(){return+$(this)},R.toPrecision=function(e,t){return null!=e&&b(e,1,y),z(this,e,t,2)},R.toString=function(e){var t,r=this,o=r.s,i=r.e;return null===i?o?(t="Infinity",o<0&&(t="-"+t)):t="NaN":(null==e?t=i<=L||i>=B?S(v(r.c),i):_(v(r.c),i,"0"):10===e&&K?t=_(v((r=W(new H(r),I+i+1,C)).c),r.e,"0"):(b(e,2,q.length,"Base"),t=n(_(v(r.c),i,"0"),10,e,o,!0)),o<0&&r.c[0]&&(t="-"+t)),t},R.valueOf=R.toJSON=function(){return $(this)},R._isBigNumber=!0,null!=t&&H.set(t),H}(),o.default=o.BigNumber=o,void 0===(n=function(){return o}.call(t,r,t,e))||(e.exports=n)}()},8287:(e,t,r)=>{"use strict";const n=r(7526),o=r(251),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=u,t.SlowBuffer=function(e){+e!=e&&(e=0);return u.alloc(+e)},t.INSPECT_MAX_BYTES=50;const a=2147483647;function s(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,u.prototype),t}function u(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return f(e)}return c(e,t,r)}function c(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!u.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|y(e,t);let n=s(r);const o=n.write(e,t);o!==r&&(n=n.slice(0,o));return n}(e,t);if(ArrayBuffer.isView(e))return function(e){if($(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return p(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if($(e,ArrayBuffer)||e&&$(e.buffer,ArrayBuffer))return d(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&($(e,SharedArrayBuffer)||e&&$(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return u.from(n,t,r);const o=function(e){if(u.isBuffer(e)){const t=0|h(e.length),r=s(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||Q(e.length)?s(0):p(e);if("Buffer"===e.type&&Array.isArray(e.data))return p(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return u.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function f(e){return l(e),s(e<0?0:0|h(e))}function p(e){const t=e.length<0?0:0|h(e.length),r=s(t);for(let n=0;n=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function y(e,t){if(u.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||$(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return X(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(o)return n?-1:X(e).length;t=(""+t).toLowerCase(),o=!0}}function m(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return R(this,t,r);case"utf8":case"utf-8":return O(this,t,r);case"ascii":return A(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return T(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function v(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function g(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Q(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,o){let i,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){let n=-1;for(i=r;is&&(r=s-u),i=r;i>=0;i--){let r=!0;for(let n=0;no&&(n=o):n=o;const i=t.length;let a;for(n>i/2&&(n=i/2),a=0;a>8,o=r%256,i.push(o),i.push(n);return i}(t,e.length-r),e,r,n)}function T(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function O(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o239?4:t>223?3:t>191?2:1;if(o+a<=r){let r,n,s,u;switch(a){case 1:t<128&&(i=t);break;case 2:r=e[o+1],128==(192&r)&&(u=(31&t)<<6|63&r,u>127&&(i=u));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(u=(15&t)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:r=e[o+1],n=e[o+2],s=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(u=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,u>65535&&u<1114112&&(i=u))}}null===i?(i=65533,a=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),o+=a}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(u.isBuffer(t)||(t=u.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!u.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},u.byteLength=y,u.prototype._isBuffer=!0,u.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(e+=" ... "),""},i&&(u.prototype[i]=u.prototype.inspect),u.prototype.compare=function(e,t,r,n,o){if($(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let i=(o>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0);const s=Math.min(i,a),c=this.slice(n,o),l=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let i=!1;for(;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":case"latin1":case"binary":return _(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function A(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;on)&&(r=n);let o="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function C(e,t,r,n,o,i){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function L(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function B(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r+7]=i,i>>=8,e[r+6]=i,i>>=8,e[r+5]=i,i>>=8,e[r+4]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function N(e,t,r,n,o,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function M(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,8),o.write(e,t,r,n,52,8),r+8}u.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||I(e,t,this.length);let n=this[e],o=1,i=0;for(;++i>>=0,t>>>=0,r||I(e,t,this.length);let n=this[e+--t],o=1;for(;t>0&&(o*=256);)n+=this[e+--t]*o;return n},u.prototype.readUint8=u.prototype.readUInt8=function(e,t){return e>>>=0,t||I(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||I(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||I(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||I(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||I(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(o)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||I(e,t,this.length);let n=this[e],o=1,i=0;for(;++i=o&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||I(e,t,this.length);let n=t,o=1,i=this[e+--n];for(;n>0&&(o*=256);)i+=this[e+--n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},u.prototype.readInt8=function(e,t){return e>>>=0,t||I(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||I(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){e>>>=0,t||I(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||I(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||I(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||I(e,4,this.length),o.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||I(e,4,this.length),o.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||I(e,8,this.length),o.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||I(e,8,this.length),o.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){C(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=1,i=0;for(this[t]=255&e;++i>>=0,r>>>=0,!n){C(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=r-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigUInt64LE=J((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeBigUInt64BE=J((function(e,t=0){return B(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);C(this,e,t,r,n-1,-n)}let o=0,i=1,a=0;for(this[t]=255&e;++o>>=0,!n){const n=Math.pow(2,8*r-1);C(this,e,t,r,n-1,-n)}let o=r-1,i=1,a=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/i|0)-a&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigInt64LE=J((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeBigInt64BE=J((function(e,t=0){return B(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return M(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return M(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function q(e,t,r,n,o,i){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new D.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){K(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||H(t,e.length-(r+1))}(n,o,i)}function K(e,t){if("number"!=typeof e)throw new D.ERR_INVALID_ARG_TYPE(t,"number",e)}function H(e,t,r){if(Math.floor(e)!==e)throw K(e,r),new D.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new D.ERR_BUFFER_OUT_OF_BOUNDS;throw new D.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}F("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),F("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),F("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=V(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=V(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const z=/[^+/0-9A-Za-z-_]/g;function X(e,t){let r;t=t||1/0;const n=e.length;let o=null;const i=[];for(let a=0;a55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function G(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function W(e,t,r,n){let o;for(o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function $(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Q(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let o=0;o<16;++o)t[n+o]=e[r]+e[o]}return t}();function J(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},6866:e=>{e.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},3144:(e,t,r)=>{"use strict";var n=r(6743),o=r(1002),i=r(76),a=r(7119);e.exports=a||n.call(i,o)},2205:(e,t,r)=>{"use strict";var n=r(6743),o=r(1002),i=r(3144);e.exports=function(){return i(n,o,arguments)}},1002:e=>{"use strict";e.exports=Function.prototype.apply},76:e=>{"use strict";e.exports=Function.prototype.call},3126:(e,t,r)=>{"use strict";var n=r(6743),o=r(9675),i=r(76),a=r(3144);e.exports=function(e){if(e.length<1||"function"!=typeof e[0])throw new o("a function is required");return a(n,i,e)}},7119:e=>{"use strict";e.exports="undefined"!=typeof Reflect&&Reflect&&Reflect.apply},8075:(e,t,r)=>{"use strict";var n=r(453),o=r(487),i=o(n("String.prototype.indexOf"));e.exports=function(e,t){var r=n(e,!!t);return"function"==typeof r&&i(e,".prototype.")>-1?o(r):r}},487:(e,t,r)=>{"use strict";var n=r(6897),o=r(655),i=r(3126),a=r(2205);e.exports=function(e){var t=i(arguments),r=e.length-(arguments.length-1);return n(t,1+(r>0?r:0),!0)},o?o(e.exports,"apply",{value:a}):e.exports.apply=a},6556:(e,t,r)=>{"use strict";var n=r(453),o=r(3126),i=o([n("%String.prototype.indexOf%")]);e.exports=function(e,t){var r=n(e,!!t);return"function"==typeof r&&i(e,".prototype.")>-1?o([r]):r}},41:(e,t,r)=>{"use strict";var n=r(655),o=r(8068),i=r(9675),a=r(5795);e.exports=function(e,t,r){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new i("`obj` must be an object or a function`");if("string"!=typeof t&&"symbol"!=typeof t)throw new i("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new i("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new i("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new i("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new i("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,u=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,l=arguments.length>6&&arguments[6],f=!!a&&a(e,t);if(n)n(e,t,{configurable:null===c&&f?f.configurable:!c,enumerable:null===s&&f?f.enumerable:!s,value:r,writable:null===u&&f?f.writable:!u});else{if(!l&&(s||u||c))throw new o("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");e[t]=r}}},7176:(e,t,r)=>{"use strict";var n=r(3126),o=r(5795),i=[].__proto__===Array.prototype&&o&&o(Object.prototype,"__proto__"),a=Object,s=a.getPrototypeOf;e.exports=i&&"function"==typeof i.get?n([i.get]):"function"==typeof s&&function(e){return s(null==e?e:a(e))}},655:e=>{"use strict";var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch(e){t=!1}e.exports=t},1237:e=>{"use strict";e.exports=EvalError},9383:e=>{"use strict";e.exports=Error},9290:e=>{"use strict";e.exports=RangeError},9538:e=>{"use strict";e.exports=ReferenceError},8068:e=>{"use strict";e.exports=SyntaxError},9675:e=>{"use strict";e.exports=TypeError},5345:e=>{"use strict";e.exports=URIError},9612:e=>{"use strict";e.exports=Object},7007:e=>{"use strict";var t,r="object"==typeof Reflect?Reflect:null,n=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var o=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}e.exports=i,e.exports.once=function(e,t){return new Promise((function(r,n){function o(r){e.removeListener(t,i),n(r)}function i(){"function"==typeof e.removeListener&&e.removeListener("error",o),r([].slice.call(arguments))}y(e,t,i,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&y(e,"error",t,r)}(e,o,{once:!0})}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var a=10;function s(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function u(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,r,n){var o,i,a,c;if(s(r),void 0===(i=e._events)?(i=e._events=Object.create(null),e._eventsCount=0):(void 0!==i.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),i=e._events),a=i[t]),void 0===a)a=i[t]=r,++e._eventsCount;else if("function"==typeof a?a=i[t]=n?[r,a]:[a,r]:n?a.unshift(r):a.push(r),(o=u(e))>0&&a.length>o&&!a.warned){a.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=a.length,c=l,console&&console.warn&&console.warn(c)}return e}function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function f(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},o=l.bind(n);return o.listener=r,n.wrapFn=o,o}function p(e,t,r){var n=e._events;if(void 0===n)return[];var o=n[t];return void 0===o?[]:"function"==typeof o?r?[o.listener||o]:[o]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var u=i[e];if(void 0===u)return!1;if("function"==typeof u)n(u,this,t);else{var c=u.length,l=h(u,c);for(r=0;r=0;i--)if(r[i]===t||r[i].listener===t){a=r[i].listener,o=i;break}if(o<0)return this;0===o?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},i.prototype.listeners=function(e){return p(this,e,!0)},i.prototype.rawListeners=function(e){return p(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):d.call(e,t)},i.prototype.listenerCount=d,i.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},1731:(e,t,r)=>{var n=r(8287).Buffer,o=r(8835).parse,i=r(7007),a=r(1083),s=r(1568),u=r(537),c=["pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","secureProtocol","servername","checkServerIdentity"],l=[239,187,191],f=262144,p=/^(cookie|authorization)$/i;function d(e,t){var r=d.CONNECTING,i=t&&t.headers,u=!1;Object.defineProperty(this,"readyState",{get:function(){return r}}),Object.defineProperty(this,"url",{get:function(){return e}});var m,v=this;function g(t){r!==d.CLOSED&&(r=d.CONNECTING,T("error",new h("error",{message:t})),E&&(e=E,E=null,u=!1),setTimeout((function(){r!==d.CONNECTING||v.connectionInProgress||(v.connectionInProgress=!0,k())}),v.reconnectInterval))}v.reconnectInterval=1e3,v.connectionInProgress=!1;var b="";i&&i["Last-Event-ID"]&&(b=i["Last-Event-ID"],delete i["Last-Event-ID"]);var w=!1,S="",_="",E=null;function k(){var y=o(e),S="https:"===y.protocol;if(y.headers={"Cache-Control":"no-cache",Accept:"text/event-stream"},b&&(y.headers["Last-Event-ID"]=b),i){var _=u?function(e){var t={};for(var r in e)p.test(r)||(t[r]=e[r]);return t}(i):i;for(var x in _){var A=_[x];A&&(y.headers[x]=A)}}if(y.rejectUnauthorized=!(t&&!t.rejectUnauthorized),t&&void 0!==t.createConnection&&(y.createConnection=t.createConnection),t&&t.proxy){var P=o(t.proxy);S="https:"===P.protocol,y.protocol=S?"https:":"http:",y.path=e,y.headers.Host=y.host,y.hostname=P.hostname,y.host=P.host,y.port=P.port}if(t&&t.https)for(var R in t.https)if(-1!==c.indexOf(R)){var j=t.https[R];void 0!==j&&(y[R]=j)}t&&void 0!==t.withCredentials&&(y.withCredentials=t.withCredentials),m=(S?a:s).request(y,(function(t){if(v.connectionInProgress=!1,500===t.statusCode||502===t.statusCode||503===t.statusCode||504===t.statusCode)return T("error",new h("error",{status:t.statusCode,message:t.statusMessage})),void g();if(301===t.statusCode||302===t.statusCode||307===t.statusCode){var o=t.headers.location;if(!o)return void T("error",new h("error",{status:t.statusCode,message:t.statusMessage}));var i=new URL(e).origin,a=new URL(o).origin;return u=i!==a,307===t.statusCode&&(E=e),e=o,void process.nextTick(k)}if(200!==t.statusCode)return T("error",new h("error",{status:t.statusCode,message:t.statusMessage})),v.close();var s,c;r=d.OPEN,t.on("close",(function(){t.removeAllListeners("close"),t.removeAllListeners("end"),g()})),t.on("end",(function(){t.removeAllListeners("close"),t.removeAllListeners("end"),g()})),T("open",new h("open"));var p=0,y=-1,m=0,b=0;t.on("data",(function(e){s?(e.length>s.length-b&&((m=2*s.length+e.length)>f&&(m=s.length+e.length+f),c=n.alloc(m),s.copy(c,0,0,b),s=c),e.copy(s,b),b+=e.length):(function(e){return l.every((function(t,r){return e[r]===t}))}(s=e)&&(s=s.slice(l.length)),b=s.length);for(var t=0,r=b;t0&&(s=s.slice(t,b),b=s.length)}))})),m.on("error",(function(e){v.connectionInProgress=!1,g(e.message)})),m.setNoDelay&&m.setNoDelay(!0),m.end()}function T(){v.listeners(arguments[0]).length>0&&v.emit.apply(v,arguments)}function O(t,r,n,o){if(0===o){if(S.length>0){var i=_||"message";T(i,new y(i,{data:S.slice(0,-1),lastEventId:b,origin:new URL(e).origin})),S=""}_=void 0}else if(n>0){var a=n<0,s=0,u=t.slice(r,r+(a?o:n)).toString();r+=s=a?o:32!==t[r+n+1]?n+1:n+2;var c=o-s,l=t.slice(r,r+c).toString();if("data"===u)S+=l+"\n";else if("event"===u)_=l;else if("id"===u)b=l;else if("retry"===u){var f=parseInt(l,10);Number.isNaN(f)||(v.reconnectInterval=f)}}}k(),this._close=function(){r!==d.CLOSED&&(r=d.CLOSED,m.abort&&m.abort(),m.xhr&&m.xhr.abort&&m.xhr.abort())}}function h(e,t){if(Object.defineProperty(this,"type",{writable:!1,value:e,enumerable:!0}),t)for(var r in t)t.hasOwnProperty(r)&&Object.defineProperty(this,r,{writable:!1,value:t[r],enumerable:!0})}function y(e,t){for(var r in Object.defineProperty(this,"type",{writable:!1,value:e,enumerable:!0}),t)t.hasOwnProperty(r)&&Object.defineProperty(this,r,{writable:!1,value:t[r],enumerable:!0})}e.exports=d,u.inherits(d,i.EventEmitter),d.prototype.constructor=d,["open","error","message"].forEach((function(e){Object.defineProperty(d.prototype,"on"+e,{get:function(){var t=this.listeners(e)[0];return t?t._listener?t._listener:t:void 0},set:function(t){this.removeAllListeners(e),this.addEventListener(e,t)}})})),Object.defineProperty(d,"CONNECTING",{enumerable:!0,value:0}),Object.defineProperty(d,"OPEN",{enumerable:!0,value:1}),Object.defineProperty(d,"CLOSED",{enumerable:!0,value:2}),d.prototype.CONNECTING=0,d.prototype.OPEN=1,d.prototype.CLOSED=2,d.prototype.close=function(){this._close()},d.prototype.addEventListener=function(e,t){"function"==typeof t&&(t._listener=t,this.on(e,t))},d.prototype.dispatchEvent=function(e){if(!e.type)throw new Error("UNSPECIFIED_EVENT_TYPE_ERR");this.emit(e.type,e.detail)},d.prototype.removeEventListener=function(e,t){"function"==typeof t&&(t._listener=void 0,this.removeListener(e,t))}},2682:(e,t,r)=>{"use strict";var n=r(9600),o=Object.prototype.toString,i=Object.prototype.hasOwnProperty;e.exports=function(e,t,r){if(!n(t))throw new TypeError("iterator must be a function");var a;arguments.length>=3&&(a=r),"[object Array]"===o.call(e)?function(e,t,r){for(var n=0,o=e.length;n{"use strict";var t=Object.prototype.toString,r=Math.max,n=function(e,t){for(var r=[],n=0;n{"use strict";var n=r(1734);e.exports=Function.prototype.bind||n},453:(e,t,r)=>{"use strict";var n,o=r(9612),i=r(9383),a=r(1237),s=r(9290),u=r(9538),c=r(8068),l=r(9675),f=r(5345),p=r(1514),d=r(8968),h=r(6188),y=r(8002),m=r(5880),v=Function,g=function(e){try{return v('"use strict"; return ('+e+").constructor;")()}catch(e){}},b=r(5795),w=r(655),S=function(){throw new l},_=b?function(){try{return S}catch(e){try{return b(arguments,"callee").get}catch(e){return S}}}():S,E=r(4039)(),k=r(7176),T="function"==typeof Reflect&&Reflect.getPrototypeOf||o.getPrototypeOf||k,O=r(1002),x=r(76),A={},P="undefined"!=typeof Uint8Array&&T?T(Uint8Array):n,R={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?n:ArrayBuffer,"%ArrayIteratorPrototype%":E&&T?T([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":A,"%AsyncGenerator%":A,"%AsyncGeneratorFunction%":A,"%AsyncIteratorPrototype%":A,"%Atomics%":"undefined"==typeof Atomics?n:Atomics,"%BigInt%":"undefined"==typeof BigInt?n:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?n:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":a,"%Float32Array%":"undefined"==typeof Float32Array?n:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?n:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?n:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":A,"%Int8Array%":"undefined"==typeof Int8Array?n:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?n:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":E&&T?T(T([][Symbol.iterator]())):n,"%JSON%":"object"==typeof JSON?JSON:n,"%Map%":"undefined"==typeof Map?n:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&E&&T?T((new Map)[Symbol.iterator]()):n,"%Math%":Math,"%Number%":Number,"%Object%":o,"%Object.getOwnPropertyDescriptor%":b,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?n:Promise,"%Proxy%":"undefined"==typeof Proxy?n:Proxy,"%RangeError%":s,"%ReferenceError%":u,"%Reflect%":"undefined"==typeof Reflect?n:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?n:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&E&&T?T((new Set)[Symbol.iterator]()):n,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":E&&T?T(""[Symbol.iterator]()):n,"%Symbol%":E?Symbol:n,"%SyntaxError%":c,"%ThrowTypeError%":_,"%TypedArray%":P,"%TypeError%":l,"%Uint8Array%":"undefined"==typeof Uint8Array?n:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?n:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?n:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?n:Uint32Array,"%URIError%":f,"%WeakMap%":"undefined"==typeof WeakMap?n:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?n:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?n:WeakSet,"%Function.prototype.call%":x,"%Function.prototype.apply%":O,"%Object.defineProperty%":w,"%Math.abs%":p,"%Math.floor%":d,"%Math.max%":h,"%Math.min%":y,"%Math.pow%":m};if(T)try{null.error}catch(e){var j=T(T(e));R["%Error.prototype%"]=j}var I=function e(t){var r;if("%AsyncFunction%"===t)r=g("async function () {}");else if("%GeneratorFunction%"===t)r=g("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=g("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var o=e("%AsyncGenerator%");o&&T&&(r=T(o.prototype))}return R[t]=r,r},C={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},L=r(6743),B=r(9957),N=L.call(x,Array.prototype.concat),U=L.call(O,Array.prototype.splice),M=L.call(x,String.prototype.replace),D=L.call(x,String.prototype.slice),F=L.call(x,RegExp.prototype.exec),V=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,q=/\\(\\)?/g,K=function(e,t){var r,n=e;if(B(C,n)&&(n="%"+(r=C[n])[0]+"%"),B(R,n)){var o=R[n];if(o===A&&(o=I(n)),void 0===o&&!t)throw new l("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:o}}throw new c("intrinsic "+e+" does not exist!")};e.exports=function(e,t){if("string"!=typeof e||0===e.length)throw new l("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new l('"allowMissing" argument must be a boolean');if(null===F(/^%?[^%]*%?$/,e))throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=function(e){var t=D(e,0,1),r=D(e,-1);if("%"===t&&"%"!==r)throw new c("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new c("invalid intrinsic syntax, expected opening `%`");var n=[];return M(e,V,(function(e,t,r,o){n[n.length]=r?M(o,q,"$1"):t||e})),n}(e),n=r.length>0?r[0]:"",o=K("%"+n+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(n=u[0],U(r,N([0,1],u)));for(var f=1,p=!0;f=r.length){var m=b(a,d);a=(p=!!m)&&"get"in m&&!("originalValue"in m.get)?m.get:a[d]}else p=B(a,d),a=a[d];p&&!s&&(R[i]=a)}}return a}},6549:e=>{"use strict";e.exports=Object.getOwnPropertyDescriptor},5795:(e,t,r)=>{"use strict";var n=r(6549);if(n)try{n([],"length")}catch(e){n=null}e.exports=n},592:(e,t,r)=>{"use strict";var n=r(655),o=function(){return!!n};o.hasArrayLengthDefineBug=function(){if(!n)return null;try{return 1!==n([],"length",{value:1}).length}catch(e){return!0}},e.exports=o},4039:(e,t,r)=>{"use strict";var n="undefined"!=typeof Symbol&&Symbol,o=r(1333);e.exports=function(){return"function"==typeof n&&("function"==typeof Symbol&&("symbol"==typeof n("foo")&&("symbol"==typeof Symbol("bar")&&o())))}},1333:e=>{"use strict";e.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(var n in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var o=Object.getOwnPropertySymbols(e);if(1!==o.length||o[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(e,t);if(42!==i.value||!0!==i.enumerable)return!1}return!0}},9092:(e,t,r)=>{"use strict";var n=r(1333);e.exports=function(){return n()&&!!Symbol.toStringTag}},9957:(e,t,r)=>{"use strict";var n=Function.prototype.call,o=Object.prototype.hasOwnProperty,i=r(6743);e.exports=i.call(n,o)},1083:(e,t,r)=>{var n=r(1568),o=r(8835),i=e.exports;for(var a in n)n.hasOwnProperty(a)&&(i[a]=n[a]);function s(e){if("string"==typeof e&&(e=o.parse(e)),e.protocol||(e.protocol="https:"),"https:"!==e.protocol)throw new Error('Protocol "'+e.protocol+'" not supported. Expected "https:"');return e}i.request=function(e,t){return e=s(e),n.request.call(this,e,t)},i.get=function(e,t){return e=s(e),n.get.call(this,e,t)}},251:(e,t)=>{t.read=function(e,t,r,n,o){var i,a,s=8*o-n-1,u=(1<>1,l=-7,f=r?o-1:0,p=r?-1:1,d=e[t+f];for(f+=p,i=d&(1<<-l)-1,d>>=-l,l+=s;l>0;i=256*i+e[t+f],f+=p,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=p,l-=8);if(0===i)i=1-c;else{if(i===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),i-=c}return(d?-1:1)*a*Math.pow(2,i-n)},t.write=function(e,t,r,n,o,i){var a,s,u,c=8*i-o-1,l=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,h=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?p/u:p*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=l?(s=0,a=l):a+f>=1?(s=(t*u-1)*Math.pow(2,o),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,o),a=0));o>=8;e[r+d]=255&s,d+=h,s/=256,o-=8);for(a=a<0;e[r+d]=255&a,d+=h,a/=256,c-=8);e[r+d-h]|=128*y}},6698:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},7244:(e,t,r)=>{"use strict";var n=r(9092)(),o=r(6556)("Object.prototype.toString"),i=function(e){return!(n&&e&&"object"==typeof e&&Symbol.toStringTag in e)&&"[object Arguments]"===o(e)},a=function(e){return!!i(e)||null!==e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==o(e)&&"callee"in e&&"[object Function]"===o(e.callee)},s=function(){return i(arguments)}();i.isLegacyArguments=a,e.exports=s?i:a},9600:e=>{"use strict";var t,r,n=Function.prototype.toString,o="object"==typeof Reflect&&null!==Reflect&&Reflect.apply;if("function"==typeof o&&"function"==typeof Object.defineProperty)try{t=Object.defineProperty({},"length",{get:function(){throw r}}),r={},o((function(){throw 42}),null,t)}catch(e){e!==r&&(o=null)}else o=null;var i=/^\s*class\b/,a=function(e){try{var t=n.call(e);return i.test(t)}catch(e){return!1}},s=function(e){try{return!a(e)&&(n.call(e),!0)}catch(e){return!1}},u=Object.prototype.toString,c="function"==typeof Symbol&&!!Symbol.toStringTag,l=!(0 in[,]),f=function(){return!1};if("object"==typeof document){var p=document.all;u.call(p)===u.call(document.all)&&(f=function(e){if((l||!e)&&(void 0===e||"object"==typeof e))try{var t=u.call(e);return("[object HTMLAllCollection]"===t||"[object HTML document.all class]"===t||"[object HTMLCollection]"===t||"[object Object]"===t)&&null==e("")}catch(e){}return!1})}e.exports=o?function(e){if(f(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;try{o(e,null,t)}catch(e){if(e!==r)return!1}return!a(e)&&s(e)}:function(e){if(f(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;if(c)return s(e);if(a(e))return!1;var t=u.call(e);return!("[object Function]"!==t&&"[object GeneratorFunction]"!==t&&!/^\[object HTML/.test(t))&&s(e)}},8184:(e,t,r)=>{"use strict";var n,o=Object.prototype.toString,i=Function.prototype.toString,a=/^\s*(?:function)?\*/,s=r(9092)(),u=Object.getPrototypeOf;e.exports=function(e){if("function"!=typeof e)return!1;if(a.test(i.call(e)))return!0;if(!s)return"[object GeneratorFunction]"===o.call(e);if(!u)return!1;if(void 0===n){var t=function(){if(!s)return!1;try{return Function("return function*() {}")()}catch(e){}}();n=!!t&&u(t)}return u(e)===n}},5680:(e,t,r)=>{"use strict";var n=r(5767);e.exports=function(e){return!!n(e)}},1514:e=>{"use strict";e.exports=Math.abs},8968:e=>{"use strict";e.exports=Math.floor},6188:e=>{"use strict";e.exports=Math.max},8002:e=>{"use strict";e.exports=Math.min},5880:e=>{"use strict";e.exports=Math.pow},8859:(e,t,r)=>{var n="function"==typeof Map&&Map.prototype,o=Object.getOwnPropertyDescriptor&&n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,i=n&&o&&"function"==typeof o.get?o.get:null,a=n&&Map.prototype.forEach,s="function"==typeof Set&&Set.prototype,u=Object.getOwnPropertyDescriptor&&s?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,c=s&&u&&"function"==typeof u.get?u.get:null,l=s&&Set.prototype.forEach,f="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,p="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,d="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,h=Boolean.prototype.valueOf,y=Object.prototype.toString,m=Function.prototype.toString,v=String.prototype.match,g=String.prototype.slice,b=String.prototype.replace,w=String.prototype.toUpperCase,S=String.prototype.toLowerCase,_=RegExp.prototype.test,E=Array.prototype.concat,k=Array.prototype.join,T=Array.prototype.slice,O=Math.floor,x="function"==typeof BigInt?BigInt.prototype.valueOf:null,A=Object.getOwnPropertySymbols,P="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,R="function"==typeof Symbol&&"object"==typeof Symbol.iterator,j="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===R||"symbol")?Symbol.toStringTag:null,I=Object.prototype.propertyIsEnumerable,C=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function L(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||_.call(/e/,t))return t;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var n=e<0?-O(-e):O(e);if(n!==e){var o=String(n),i=g.call(t,o.length+1);return b.call(o,r,"$&_")+"."+b.call(b.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return b.call(t,r,"$&_")}var B=r(2634),N=B.custom,U=H(N)?N:null,M={__proto__:null,double:'"',single:"'"},D={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};function F(e,t,r){var n=r.quoteStyle||t,o=M[n];return o+e+o}function V(e){return b.call(String(e),/"/g,""")}function q(e){return!("[object Array]"!==G(e)||j&&"object"==typeof e&&j in e)}function K(e){return!("[object RegExp]"!==G(e)||j&&"object"==typeof e&&j in e)}function H(e){if(R)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!P)return!1;try{return P.call(e),!0}catch(e){}return!1}e.exports=function e(t,n,o,s){var u=n||{};if(X(u,"quoteStyle")&&!X(M,u.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(X(u,"maxStringLength")&&("number"==typeof u.maxStringLength?u.maxStringLength<0&&u.maxStringLength!==1/0:null!==u.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var y=!X(u,"customInspect")||u.customInspect;if("boolean"!=typeof y&&"symbol"!==y)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(X(u,"indent")&&null!==u.indent&&"\t"!==u.indent&&!(parseInt(u.indent,10)===u.indent&&u.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(X(u,"numericSeparator")&&"boolean"!=typeof u.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var w=u.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return $(t,u);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var _=String(t);return w?L(t,_):_}if("bigint"==typeof t){var O=String(t)+"n";return w?L(t,O):O}var A=void 0===u.depth?5:u.depth;if(void 0===o&&(o=0),o>=A&&A>0&&"object"==typeof t)return q(t)?"[Array]":"[Object]";var N=function(e,t){var r;if("\t"===e.indent)r="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;r=k.call(Array(e.indent+1)," ")}return{base:r,prev:k.call(Array(t+1),r)}}(u,o);if(void 0===s)s=[];else if(W(s,t)>=0)return"[Circular]";function D(t,r,n){if(r&&(s=T.call(s)).push(r),n){var i={depth:u.depth};return X(u,"quoteStyle")&&(i.quoteStyle=u.quoteStyle),e(t,i,o+1,s)}return e(t,u,o+1,s)}if("function"==typeof t&&!K(t)){var z=function(e){if(e.name)return e.name;var t=v.call(m.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),Q=te(t,D);return"[Function"+(z?": "+z:" (anonymous)")+"]"+(Q.length>0?" { "+k.call(Q,", ")+" }":"")}if(H(t)){var re=R?b.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):P.call(t);return"object"!=typeof t||R?re:Y(re)}if(function(e){if(!e||"object"!=typeof e)return!1;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;return"string"==typeof e.nodeName&&"function"==typeof e.getAttribute}(t)){for(var ne="<"+S.call(String(t.nodeName)),oe=t.attributes||[],ie=0;ie"}if(q(t)){if(0===t.length)return"[]";var ae=te(t,D);return N&&!function(e){for(var t=0;t=0)return!1;return!0}(ae)?"["+ee(ae,N)+"]":"[ "+k.call(ae,", ")+" ]"}if(function(e){return!("[object Error]"!==G(e)||j&&"object"==typeof e&&j in e)}(t)){var se=te(t,D);return"cause"in Error.prototype||!("cause"in t)||I.call(t,"cause")?0===se.length?"["+String(t)+"]":"{ ["+String(t)+"] "+k.call(se,", ")+" }":"{ ["+String(t)+"] "+k.call(E.call("[cause]: "+D(t.cause),se),", ")+" }"}if("object"==typeof t&&y){if(U&&"function"==typeof t[U]&&B)return B(t,{depth:A-o});if("symbol"!==y&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!i||!e||"object"!=typeof e)return!1;try{i.call(e);try{c.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var ue=[];return a&&a.call(t,(function(e,r){ue.push(D(r,t,!0)+" => "+D(e,t))})),Z("Map",i.call(t),ue,N)}if(function(e){if(!c||!e||"object"!=typeof e)return!1;try{c.call(e);try{i.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var ce=[];return l&&l.call(t,(function(e){ce.push(D(e,t))})),Z("Set",c.call(t),ce,N)}if(function(e){if(!f||!e||"object"!=typeof e)return!1;try{f.call(e,f);try{p.call(e,p)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return J("WeakMap");if(function(e){if(!p||!e||"object"!=typeof e)return!1;try{p.call(e,p);try{f.call(e,f)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return J("WeakSet");if(function(e){if(!d||!e||"object"!=typeof e)return!1;try{return d.call(e),!0}catch(e){}return!1}(t))return J("WeakRef");if(function(e){return!("[object Number]"!==G(e)||j&&"object"==typeof e&&j in e)}(t))return Y(D(Number(t)));if(function(e){if(!e||"object"!=typeof e||!x)return!1;try{return x.call(e),!0}catch(e){}return!1}(t))return Y(D(x.call(t)));if(function(e){return!("[object Boolean]"!==G(e)||j&&"object"==typeof e&&j in e)}(t))return Y(h.call(t));if(function(e){return!("[object String]"!==G(e)||j&&"object"==typeof e&&j in e)}(t))return Y(D(String(t)));if("undefined"!=typeof window&&t===window)return"{ [object Window] }";if("undefined"!=typeof globalThis&&t===globalThis||void 0!==r.g&&t===r.g)return"{ [object globalThis] }";if(!function(e){return!("[object Date]"!==G(e)||j&&"object"==typeof e&&j in e)}(t)&&!K(t)){var le=te(t,D),fe=C?C(t)===Object.prototype:t instanceof Object||t.constructor===Object,pe=t instanceof Object?"":"null prototype",de=!fe&&j&&Object(t)===t&&j in t?g.call(G(t),8,-1):pe?"Object":"",he=(fe||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(de||pe?"["+k.call(E.call([],de||[],pe||[]),": ")+"] ":"");return 0===le.length?he+"{}":N?he+"{"+ee(le,N)+"}":he+"{ "+k.call(le,", ")+" }"}return String(t)};var z=Object.prototype.hasOwnProperty||function(e){return e in this};function X(e,t){return z.call(e,t)}function G(e){return y.call(e)}function W(e,t){if(e.indexOf)return e.indexOf(t);for(var r=0,n=e.length;rt.maxStringLength){var r=e.length-t.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return $(g.call(e,0,t.maxStringLength),t)+n}var o=D[t.quoteStyle||"single"];return o.lastIndex=0,F(b.call(b.call(e,o,"\\$1"),/[\x00-\x1f]/g,Q),"single",t)}function Q(e){var t=e.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return r?"\\"+r:"\\x"+(t<16?"0":"")+w.call(t.toString(16))}function Y(e){return"Object("+e+")"}function J(e){return e+" { ? }"}function Z(e,t,r,n){return e+" ("+t+") {"+(n?ee(r,n):k.call(r,", "))+"}"}function ee(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+k.call(e,","+r)+"\n"+t.prev}function te(e,t){var r=q(e),n=[];if(r){n.length=e.length;for(var o=0;o{"use strict";e.exports=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]},4765:e=>{"use strict";var t=String.prototype.replace,r=/%20/g,n="RFC1738",o="RFC3986";e.exports={default:o,formatters:{RFC1738:function(e){return t.call(e,r,"+")},RFC3986:function(e){return String(e)}},RFC1738:n,RFC3986:o}},5373:(e,t,r)=>{"use strict";var n=r(8636),o=r(2642),i=r(4765);e.exports={formats:i,parse:o,stringify:n}},2642:(e,t,r)=>{"use strict";var n=r(7720),o=Object.prototype.hasOwnProperty,i=Array.isArray,a={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:n.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},s=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},u=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},c=function(e,t,r,n){if(e){var i=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,a=/(\[[^[\]]*])/g,s=r.depth>0&&/(\[[^[\]]*])/.exec(i),c=s?i.slice(0,s.index):i,l=[];if(c){if(!r.plainObjects&&o.call(Object.prototype,c)&&!r.allowPrototypes)return;l.push(c)}for(var f=0;r.depth>0&&null!==(s=a.exec(i))&&f=0;--i){var a,s=e[i];if("[]"===s&&r.parseArrays)a=r.allowEmptyArrays&&(""===o||r.strictNullHandling&&null===o)?[]:[].concat(o);else{a=r.plainObjects?{__proto__:null}:{};var c="["===s.charAt(0)&&"]"===s.charAt(s.length-1)?s.slice(1,-1):s,l=r.decodeDotInKeys?c.replace(/%2E/g,"."):c,f=parseInt(l,10);r.parseArrays||""!==l?!isNaN(f)&&s!==l&&String(f)===l&&f>=0&&r.parseArrays&&f<=r.arrayLimit?(a=[])[f]=o:"__proto__"!==l&&(a[l]=o):a={0:o}}o=a}return o}(l,t,r,n)}};e.exports=function(e,t){var r=function(e){if(!e)return a;if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.decodeDotInKeys&&"boolean"!=typeof e.decodeDotInKeys)throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?a.charset:e.charset,r=void 0===e.duplicates?a.duplicates:e.duplicates;if("combine"!==r&&"first"!==r&&"last"!==r)throw new TypeError("The duplicates option must be either combine, first, or last");return{allowDots:void 0===e.allowDots?!0===e.decodeDotInKeys||a.allowDots:!!e.allowDots,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:a.allowEmptyArrays,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:a.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:a.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:a.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:a.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:a.comma,decodeDotInKeys:"boolean"==typeof e.decodeDotInKeys?e.decodeDotInKeys:a.decodeDotInKeys,decoder:"function"==typeof e.decoder?e.decoder:a.decoder,delimiter:"string"==typeof e.delimiter||n.isRegExp(e.delimiter)?e.delimiter:a.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:a.depth,duplicates:r,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:a.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:a.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:a.plainObjects,strictDepth:"boolean"==typeof e.strictDepth?!!e.strictDepth:a.strictDepth,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:a.strictNullHandling}}(t);if(""===e||null==e)return r.plainObjects?{__proto__:null}:{};for(var l="string"==typeof e?function(e,t){var r={__proto__:null},c=t.ignoreQueryPrefix?e.replace(/^\?/,""):e;c=c.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var l,f=t.parameterLimit===1/0?void 0:t.parameterLimit,p=c.split(t.delimiter,f),d=-1,h=t.charset;if(t.charsetSentinel)for(l=0;l-1&&(m=i(m)?[m]:m);var w=o.call(r,y);w&&"combine"===t.duplicates?r[y]=n.combine(r[y],m):w&&"last"!==t.duplicates||(r[y]=m)}return r}(e,r):e,f=r.plainObjects?{__proto__:null}:{},p=Object.keys(l),d=0;d{"use strict";var n=r(920),o=r(7720),i=r(4765),a=Object.prototype.hasOwnProperty,s={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},u=Array.isArray,c=Array.prototype.push,l=function(e,t){c.apply(e,u(t)?t:[t])},f=Date.prototype.toISOString,p=i.default,d={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,commaRoundTrip:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:o.encode,encodeValuesOnly:!1,filter:void 0,format:p,formatter:i.formatters[p],indices:!1,serializeDate:function(e){return f.call(e)},skipNulls:!1,strictNullHandling:!1},h={},y=function e(t,r,i,a,s,c,f,p,y,m,v,g,b,w,S,_,E,k){for(var T,O=t,x=k,A=0,P=!1;void 0!==(x=x.get(h))&&!P;){var R=x.get(t);if(A+=1,void 0!==R){if(R===A)throw new RangeError("Cyclic object value");P=!0}void 0===x.get(h)&&(A=0)}if("function"==typeof m?O=m(r,O):O instanceof Date?O=b(O):"comma"===i&&u(O)&&(O=o.maybeMap(O,(function(e){return e instanceof Date?b(e):e}))),null===O){if(c)return y&&!_?y(r,d.encoder,E,"key",w):r;O=""}if("string"==typeof(T=O)||"number"==typeof T||"boolean"==typeof T||"symbol"==typeof T||"bigint"==typeof T||o.isBuffer(O))return y?[S(_?r:y(r,d.encoder,E,"key",w))+"="+S(y(O,d.encoder,E,"value",w))]:[S(r)+"="+S(String(O))];var j,I=[];if(void 0===O)return I;if("comma"===i&&u(O))_&&y&&(O=o.maybeMap(O,y)),j=[{value:O.length>0?O.join(",")||null:void 0}];else if(u(m))j=m;else{var C=Object.keys(O);j=v?C.sort(v):C}var L=p?String(r).replace(/\./g,"%2E"):String(r),B=a&&u(O)&&1===O.length?L+"[]":L;if(s&&u(O)&&0===O.length)return B+"[]";for(var N=0;N0?S+w:""}},7720:(e,t,r)=>{"use strict";var n=r(4765),o=Object.prototype.hasOwnProperty,i=Array.isArray,a=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),s=function(e,t){for(var r=t&&t.plainObjects?{__proto__:null}:{},n=0;n1;){var t=e.pop(),r=t.obj[t.prop];if(i(r)){for(var n=[],o=0;o=u?s.slice(l,l+u):s,p=[],d=0;d=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||i===n.RFC1738&&(40===h||41===h)?p[p.length]=f.charAt(d):h<128?p[p.length]=a[h]:h<2048?p[p.length]=a[192|h>>6]+a[128|63&h]:h<55296||h>=57344?p[p.length]=a[224|h>>12]+a[128|h>>6&63]+a[128|63&h]:(d+=1,h=65536+((1023&h)<<10|1023&f.charCodeAt(d)),p[p.length]=a[240|h>>18]+a[128|h>>12&63]+a[128|h>>6&63]+a[128|63&h])}c+=p.join("")}return c},isBuffer:function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(i(e)){for(var r=[],n=0;n{"use strict";var n=65536,o=4294967295;var i=r(2861).Buffer,a=r.g.crypto||r.g.msCrypto;a&&a.getRandomValues?e.exports=function(e,t){if(e>o)throw new RangeError("requested too many random bytes");var r=i.allocUnsafe(e);if(e>0)if(e>n)for(var s=0;s{"use strict";var t={};function r(e,r,n){n||(n=Error);var o=function(e){var t,n;function o(t,n,o){return e.call(this,function(e,t,n){return"string"==typeof r?r:r(e,t,n)}(t,n,o))||this}return n=e,(t=o).prototype=Object.create(n.prototype),t.prototype.constructor=t,t.__proto__=n,o}(n);o.prototype.name=n.name,o.prototype.code=e,t[e]=o}function n(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map((function(e){return String(e)})),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:2===r?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}r("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),r("ERR_INVALID_ARG_TYPE",(function(e,t,r){var o,i,a,s;if("string"==typeof t&&(i="not ",t.substr(!a||a<0?0:+a,i.length)===i)?(o="must not be",t=t.replace(/^not /,"")):o="must be",function(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}(e," argument"))s="The ".concat(e," ").concat(o," ").concat(n(t,"type"));else{var u=function(e,t,r){return"number"!=typeof r&&(r=0),!(r+t.length>e.length)&&-1!==e.indexOf(t,r)}(e,".")?"property":"argument";s='The "'.concat(e,'" ').concat(u," ").concat(o," ").concat(n(t,"type"))}return s+=". Received type ".concat(typeof r)}),TypeError),r("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),r("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),r("ERR_STREAM_PREMATURE_CLOSE","Premature close"),r("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),r("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),r("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),r("ERR_STREAM_WRITE_AFTER_END","write after end"),r("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),r("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),r("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),e.exports.F=t},5382:(e,t,r)=>{"use strict";var n=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};e.exports=c;var o=r(5412),i=r(6708);r(6698)(c,o);for(var a=n(i.prototype),s=0;s{"use strict";e.exports=o;var n=r(4610);function o(e){if(!(this instanceof o))return new o(e);n.call(this,e)}r(6698)(o,n),o.prototype._transform=function(e,t,r){r(null,e)}},5412:(e,t,r)=>{"use strict";var n;e.exports=k,k.ReadableState=E;r(7007).EventEmitter;var o=function(e,t){return e.listeners(t).length},i=r(345),a=r(8287).Buffer,s=(void 0!==r.g?r.g:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var u,c=r(9838);u=c&&c.debuglog?c.debuglog("stream"):function(){};var l,f,p,d=r(2726),h=r(5896),y=r(5291).getHighWaterMark,m=r(6048).F,v=m.ERR_INVALID_ARG_TYPE,g=m.ERR_STREAM_PUSH_AFTER_EOF,b=m.ERR_METHOD_NOT_IMPLEMENTED,w=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;r(6698)(k,i);var S=h.errorOrDestroy,_=["error","close","destroy","pause","resume"];function E(e,t,o){n=n||r(5382),e=e||{},"boolean"!=typeof o&&(o=t instanceof n),this.objectMode=!!e.objectMode,o&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=y(this,e,"readableHighWaterMark",o),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==e.emitClose,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(l||(l=r(3141).I),this.decoder=new l(e.encoding),this.encoding=e.encoding)}function k(e){if(n=n||r(5382),!(this instanceof k))return new k(e);var t=this instanceof n;this._readableState=new E(e,this,t),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),i.call(this)}function T(e,t,r,n,o){u("readableAddChunk",t);var i,c=e._readableState;if(null===t)c.reading=!1,function(e,t){if(u("onEofChunk"),t.ended)return;if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,t.sync?P(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,R(e)))}(e,c);else if(o||(i=function(e,t){var r;n=t,a.isBuffer(n)||n instanceof s||"string"==typeof t||void 0===t||e.objectMode||(r=new v("chunk",["string","Buffer","Uint8Array"],t));var n;return r}(c,t)),i)S(e,i);else if(c.objectMode||t&&t.length>0)if("string"==typeof t||c.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=function(e){return a.from(e)}(t)),n)c.endEmitted?S(e,new w):O(e,c,t,!0);else if(c.ended)S(e,new g);else{if(c.destroyed)return!1;c.reading=!1,c.decoder&&!r?(t=c.decoder.write(t),c.objectMode||0!==t.length?O(e,c,t,!1):j(e,c)):O(e,c,t,!1)}else n||(c.reading=!1,j(e,c));return!c.ended&&(c.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=x?e=x:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function P(e){var t=e._readableState;u("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u("emitReadable",t.flowing),t.emittedReadable=!0,process.nextTick(R,e))}function R(e){var t=e._readableState;u("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,N(e)}function j(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(I,e,t))}function I(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function L(e){u("readable nexttick read 0"),e.read(0)}function B(e,t){u("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),N(e),t.flowing&&!t.reading&&e.read(0)}function N(e){var t=e._readableState;for(u("flow",t.flowing);t.flowing&&null!==e.read(););}function U(e,t){return 0===t.length?null:(t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r);var r}function M(e){var t=e._readableState;u("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(D,t,e))}function D(e,t){if(u("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy()}}function F(e,t){for(var r=0,n=e.length;r=t.highWaterMark:t.length>0)||t.ended))return u("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?M(this):P(this),null;if(0===(e=A(e,t))&&t.ended)return 0===t.length&&M(this),null;var n,o=t.needReadable;return u("need readable",o),(0===t.length||t.length-e0?U(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&M(this)),null!==n&&this.emit("data",n),n},k.prototype._read=function(e){S(this,new b("_read()"))},k.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e)}n.pipesCount+=1,u("pipe count=%d opts=%j",n.pipesCount,t);var i=(!t||!1!==t.end)&&e!==process.stdout&&e!==process.stderr?s:y;function a(t,o){u("onunpipe"),t===r&&o&&!1===o.hasUnpiped&&(o.hasUnpiped=!0,u("cleanup"),e.removeListener("close",d),e.removeListener("finish",h),e.removeListener("drain",c),e.removeListener("error",p),e.removeListener("unpipe",a),r.removeListener("end",s),r.removeListener("end",y),r.removeListener("data",f),l=!0,!n.awaitDrain||e._writableState&&!e._writableState.needDrain||c())}function s(){u("onend"),e.end()}n.endEmitted?process.nextTick(i):r.once("end",i),e.on("unpipe",a);var c=function(e){return function(){var t=e._readableState;u("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,N(e))}}(r);e.on("drain",c);var l=!1;function f(t){u("ondata");var o=e.write(t);u("dest.write",o),!1===o&&((1===n.pipesCount&&n.pipes===e||n.pipesCount>1&&-1!==F(n.pipes,e))&&!l&&(u("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function p(t){u("onerror",t),y(),e.removeListener("error",p),0===o(e,"error")&&S(e,t)}function d(){e.removeListener("finish",h),y()}function h(){u("onfinish"),e.removeListener("close",d),y()}function y(){u("unpipe"),r.unpipe(e)}return r.on("data",f),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",p),e.once("close",d),e.once("finish",h),e.emit("pipe",r),n.flowing||(u("pipe resume"),r.resume()),e},k.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r)),this;if(!e){var n=t.pipes,o=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i0,!1!==n.flowing&&this.resume()):"readable"===e&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,u("on readable",n.length,n.reading),n.length?P(this):n.reading||process.nextTick(L,this))),r},k.prototype.addListener=k.prototype.on,k.prototype.removeListener=function(e,t){var r=i.prototype.removeListener.call(this,e,t);return"readable"===e&&process.nextTick(C,this),r},k.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||process.nextTick(C,this),t},k.prototype.resume=function(){var e=this._readableState;return e.flowing||(u("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(B,e,t))}(this,e)),e.paused=!1,this},k.prototype.pause=function(){return u("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(u("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},k.prototype.wrap=function(e){var t=this,r=this._readableState,n=!1;for(var o in e.on("end",(function(){if(u("wrapped end"),r.decoder&&!r.ended){var e=r.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(o){(u("wrapped data"),r.decoder&&(o=r.decoder.write(o)),r.objectMode&&null==o)||(r.objectMode||o&&o.length)&&(t.push(o)||(n=!0,e.pause()))})),e)void 0===this[o]&&"function"==typeof e[o]&&(this[o]=function(t){return function(){return e[t].apply(e,arguments)}}(o));for(var i=0;i<_.length;i++)e.on(_[i],this.emit.bind(this,_[i]));return this._read=function(t){u("wrapped _read",t),n&&(n=!1,e.resume())},this},"function"==typeof Symbol&&(k.prototype[Symbol.asyncIterator]=function(){return void 0===f&&(f=r(2955)),f(this)}),Object.defineProperty(k.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(k.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(k.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),k._fromList=U,Object.defineProperty(k.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(k.from=function(e,t){return void 0===p&&(p=r(5157)),p(k,e,t)})},4610:(e,t,r)=>{"use strict";e.exports=l;var n=r(6048).F,o=n.ERR_METHOD_NOT_IMPLEMENTED,i=n.ERR_MULTIPLE_CALLBACK,a=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,s=n.ERR_TRANSFORM_WITH_LENGTH_0,u=r(5382);function c(e,t){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(null===n)return this.emit("error",new i);r.writechunk=null,r.writecb=null,null!=t&&this.push(t),n(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length{"use strict";function n(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,r){var n=e.entry;e.entry=null;for(;n;){var o=n.callback;t.pendingcb--,o(r),n=n.next}t.corkedRequestsFree.next=e}(t,e)}}var o;e.exports=k,k.WritableState=E;var i={deprecate:r(4643)},a=r(345),s=r(8287).Buffer,u=(void 0!==r.g?r.g:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var c,l=r(5896),f=r(5291).getHighWaterMark,p=r(6048).F,d=p.ERR_INVALID_ARG_TYPE,h=p.ERR_METHOD_NOT_IMPLEMENTED,y=p.ERR_MULTIPLE_CALLBACK,m=p.ERR_STREAM_CANNOT_PIPE,v=p.ERR_STREAM_DESTROYED,g=p.ERR_STREAM_NULL_VALUES,b=p.ERR_STREAM_WRITE_AFTER_END,w=p.ERR_UNKNOWN_ENCODING,S=l.errorOrDestroy;function _(){}function E(e,t,i){o=o||r(5382),e=e||{},"boolean"!=typeof i&&(i=t instanceof o),this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=f(this,e,"writableHighWaterMark",i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=!1===e.decodeStrings;this.decodeStrings=!a,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,n=r.sync,o=r.writecb;if("function"!=typeof o)throw new y;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,n,o){--t.pendingcb,r?(process.nextTick(o,n),process.nextTick(R,e,t),e._writableState.errorEmitted=!0,S(e,n)):(o(n),e._writableState.errorEmitted=!0,S(e,n),R(e,t))}(e,r,n,t,o);else{var i=A(r)||e.destroyed;i||r.corked||r.bufferProcessing||!r.bufferedRequest||x(e,r),n?process.nextTick(O,e,r,i,o):O(e,r,i,o)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==e.emitClose,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new n(this)}function k(e){var t=this instanceof(o=o||r(5382));if(!t&&!c.call(k,this))return new k(e);this._writableState=new E(e,this,t),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),a.call(this)}function T(e,t,r,n,o,i,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new v("write")):r?e._writev(o,t.onwrite):e._write(o,i,t.onwrite),t.sync=!1}function O(e,t,r,n){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),R(e,t)}function x(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var o=t.bufferedRequestCount,i=new Array(o),a=t.corkedRequestsFree;a.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,T(e,t,!0,t.length,i,"",a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new n(t),t.bufferedRequestCount=0}else{for(;r;){var c=r.chunk,l=r.encoding,f=r.callback;if(T(e,t,!1,t.objectMode?1:c.length,c,l,f),r=r.next,t.bufferedRequestCount--,t.writing)break}null===r&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}function A(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function P(e,t){e._final((function(r){t.pendingcb--,r&&S(e,r),t.prefinished=!0,e.emit("prefinish"),R(e,t)}))}function R(e,t){var r=A(t);if(r&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,process.nextTick(P,e,t)))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var n=e._readableState;(!n||n.autoDestroy&&n.endEmitted)&&e.destroy()}return r}r(6698)(k,a),E.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(E.prototype,"buffer",{get:i.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(c=Function.prototype[Symbol.hasInstance],Object.defineProperty(k,Symbol.hasInstance,{value:function(e){return!!c.call(this,e)||this===k&&(e&&e._writableState instanceof E)}})):c=function(e){return e instanceof this},k.prototype.pipe=function(){S(this,new m)},k.prototype.write=function(e,t,r){var n,o=this._writableState,i=!1,a=!o.objectMode&&(n=e,s.isBuffer(n)||n instanceof u);return a&&!s.isBuffer(e)&&(e=function(e){return s.from(e)}(e)),"function"==typeof t&&(r=t,t=null),a?t="buffer":t||(t=o.defaultEncoding),"function"!=typeof r&&(r=_),o.ending?function(e,t){var r=new b;S(e,r),process.nextTick(t,r)}(this,r):(a||function(e,t,r,n){var o;return null===r?o=new g:"string"==typeof r||t.objectMode||(o=new d("chunk",["string","Buffer"],r)),!o||(S(e,o),process.nextTick(n,o),!1)}(this,o,e,r))&&(o.pendingcb++,i=function(e,t,r,n,o,i){if(!r){var a=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=s.from(t,r));return t}(t,n,o);n!==a&&(r=!0,o="buffer",n=a)}var u=t.objectMode?1:n.length;t.length+=u;var c=t.length-1))throw new w(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(k.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(k.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),k.prototype._write=function(e,t,r){r(new h("_write()"))},k.prototype._writev=null,k.prototype.end=function(e,t,r){var n=this._writableState;return"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||function(e,t,r){t.ending=!0,R(e,t),r&&(t.finished?process.nextTick(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r),this},Object.defineProperty(k.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(k.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),k.prototype.destroy=l.destroy,k.prototype._undestroy=l.undestroy,k.prototype._destroy=function(e,t){t(e)}},2955:(e,t,r)=>{"use strict";var n;function o(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var i=r(6238),a=Symbol("lastResolve"),s=Symbol("lastReject"),u=Symbol("error"),c=Symbol("ended"),l=Symbol("lastPromise"),f=Symbol("handlePromise"),p=Symbol("stream");function d(e,t){return{value:e,done:t}}function h(e){var t=e[a];if(null!==t){var r=e[p].read();null!==r&&(e[l]=null,e[a]=null,e[s]=null,t(d(r,!1)))}}function y(e){process.nextTick(h,e)}var m=Object.getPrototypeOf((function(){})),v=Object.setPrototypeOf((o(n={get stream(){return this[p]},next:function(){var e=this,t=this[u];if(null!==t)return Promise.reject(t);if(this[c])return Promise.resolve(d(void 0,!0));if(this[p].destroyed)return new Promise((function(t,r){process.nextTick((function(){e[u]?r(e[u]):t(d(void 0,!0))}))}));var r,n=this[l];if(n)r=new Promise(function(e,t){return function(r,n){e.then((function(){t[c]?r(d(void 0,!0)):t[f](r,n)}),n)}}(n,this));else{var o=this[p].read();if(null!==o)return Promise.resolve(d(o,!1));r=new Promise(this[f])}return this[l]=r,r}},Symbol.asyncIterator,(function(){return this})),o(n,"return",(function(){var e=this;return new Promise((function(t,r){e[p].destroy(null,(function(e){e?r(e):t(d(void 0,!0))}))}))})),n),m);e.exports=function(e){var t,r=Object.create(v,(o(t={},p,{value:e,writable:!0}),o(t,a,{value:null,writable:!0}),o(t,s,{value:null,writable:!0}),o(t,u,{value:null,writable:!0}),o(t,c,{value:e._readableState.endEmitted,writable:!0}),o(t,f,{value:function(e,t){var n=r[p].read();n?(r[l]=null,r[a]=null,r[s]=null,e(d(n,!1))):(r[a]=e,r[s]=t)},writable:!0}),t));return r[l]=null,i(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=r[s];return null!==t&&(r[l]=null,r[a]=null,r[s]=null,t(e)),void(r[u]=e)}var n=r[a];null!==n&&(r[l]=null,r[a]=null,r[s]=null,n(d(void 0,!0))),r[c]=!0})),e.on("readable",y.bind(null,r)),r}},2726:(e,t,r)=>{"use strict";function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function o(e){for(var t=1;t0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r}},{key:"concat",value:function(e){if(0===this.length)return u.alloc(0);for(var t,r,n,o=u.allocUnsafe(e>>>0),i=this.head,a=0;i;)t=i.data,r=o,n=a,u.prototype.copy.call(t,r,n),a+=i.data.length,i=i.next;return o}},{key:"consume",value:function(e,t){var r;return eo.length?o.length:e;if(i===o.length?n+=o:n+=o.slice(0,e),0==(e-=i)){i===o.length?(++r,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=o.slice(i));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(e){var t=u.allocUnsafe(e),r=this.head,n=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var o=r.data,i=e>o.length?o.length:e;if(o.copy(t,t.length-e,0,i),0==(e-=i)){i===o.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=o.slice(i));break}++n}return this.length-=n,t}},{key:l,value:function(e,t){return c(this,o(o({},t),{},{depth:0,customInspect:!1}))}}])&&a(t.prototype,r),n&&a(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}()},5896:e=>{"use strict";function t(e,t){n(e,t),r(e)}function r(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function n(e,t){e.emit("error",t)}e.exports={destroy:function(e,o){var i=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(o?o(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(n,this,e)):process.nextTick(n,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,(function(e){!o&&e?i._writableState?i._writableState.errorEmitted?process.nextTick(r,i):(i._writableState.errorEmitted=!0,process.nextTick(t,i,e)):process.nextTick(t,i,e):o?(process.nextTick(r,i),o(e)):process.nextTick(r,i)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var r=e._readableState,n=e._writableState;r&&r.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}}},6238:(e,t,r)=>{"use strict";var n=r(6048).F.ERR_STREAM_PREMATURE_CLOSE;function o(){}e.exports=function e(t,r,i){if("function"==typeof r)return e(t,null,r);r||(r={}),i=function(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,n=new Array(r),o=0;o{e.exports=function(){throw new Error("Readable.from is not available in the browser")}},7758:(e,t,r)=>{"use strict";var n;var o=r(6048).F,i=o.ERR_MISSING_ARGS,a=o.ERR_STREAM_DESTROYED;function s(e){if(e)throw e}function u(e){e()}function c(e,t){return e.pipe(t)}e.exports=function(){for(var e=arguments.length,t=new Array(e),o=0;o0,(function(e){l||(l=e),e&&p.forEach(u),i||(p.forEach(u),f(l))}))}));return t.reduce(c)}},5291:(e,t,r)=>{"use strict";var n=r(6048).F.ERR_INVALID_OPT_VALUE;e.exports={getHighWaterMark:function(e,t,r,o){var i=function(e,t,r){return null!=e.highWaterMark?e.highWaterMark:t?e[r]:null}(t,o,r);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new n(o?r:"highWaterMark",i);return Math.floor(i)}return e.objectMode?16:16384}}},345:(e,t,r)=>{e.exports=r(7007).EventEmitter},8399:(e,t,r)=>{(t=e.exports=r(5412)).Stream=t,t.Readable=t,t.Writable=r(6708),t.Duplex=r(5382),t.Transform=r(4610),t.PassThrough=r(3600),t.finished=r(6238),t.pipeline=r(7758)},2861:(e,t,r)=>{var n=r(8287),o=n.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return o(e,t,r)}o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=a),a.prototype=Object.create(o.prototype),i(o,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=o(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},6897:(e,t,r)=>{"use strict";var n=r(453),o=r(41),i=r(592)(),a=r(5795),s=r(9675),u=n("%Math.floor%");e.exports=function(e,t){if("function"!=typeof e)throw new s("`fn` is not a function");if("number"!=typeof t||t<0||t>4294967295||u(t)!==t)throw new s("`length` must be a positive 32-bit integer");var r=arguments.length>2&&!!arguments[2],n=!0,c=!0;if("length"in e&&a){var l=a(e,"length");l&&!l.configurable&&(n=!1),l&&!l.writable&&(c=!1)}return(n||c||!r)&&(i?o(e,"length",t,!0,!0):o(e,"length",t)),e}},392:(e,t,r)=>{var n=r(2861).Buffer;function o(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}o.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=n.from(e,t));for(var r=this._block,o=this._blockSize,i=e.length,a=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,o=(r-n)/4294967296;this._block.writeUInt32BE(o,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var i=this._hash();return e?i.toString(e):i},o.prototype._update=function(){throw new Error("_update must be implemented by subclass")},e.exports=o},2802:(e,t,r)=>{var n=e.exports=function(e){e=e.toLowerCase();var t=n[e];if(!t)throw new Error(e+" is not supported (we accept pull requests)");return new t};n.sha=r(7816),n.sha1=r(3737),n.sha224=r(6710),n.sha256=r(4107),n.sha384=r(2827),n.sha512=r(2890)},7816:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,o.call(this,64,56)}function c(e){return e<<30|e>>>2}function l(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,o),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,s=0|this._d,u=0|this._e,f=0;f<16;++f)r[f]=e.readInt32BE(4*f);for(;f<80;++f)r[f]=r[f-3]^r[f-8]^r[f-14]^r[f-16];for(var p=0;p<80;++p){var d=~~(p/20),h=0|((t=n)<<5|t>>>27)+l(d,o,i,s)+u+r[p]+a[d];u=s,s=i,i=c(o),o=n,n=h}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},e.exports=u},3737:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,o.call(this,64,56)}function c(e){return e<<5|e>>>27}function l(e){return e<<30|e>>>2}function f(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,o),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,s=0|this._d,u=0|this._e,p=0;p<16;++p)r[p]=e.readInt32BE(4*p);for(;p<80;++p)r[p]=(t=r[p-3]^r[p-8]^r[p-14]^r[p-16])<<1|t>>>31;for(var d=0;d<80;++d){var h=~~(d/20),y=c(n)+f(h,o,i,s)+u+r[d]+a[h]|0;u=s,s=i,i=l(o),o=n,n=y}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},e.exports=u},6710:(e,t,r)=>{var n=r(6698),o=r(4107),i=r(392),a=r(2861).Buffer,s=new Array(64);function u(){this.init(),this._w=s,i.call(this,64,56)}n(u,o),u.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e},e.exports=u},4107:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],s=new Array(64);function u(){this.init(),this._w=s,o.call(this,64,56)}function c(e,t,r){return r^e&(t^r)}function l(e,t,r){return e&t|r&(e|t)}function f(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function p(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function d(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}n(u,o),u.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,s=0|this._d,u=0|this._e,h=0|this._f,y=0|this._g,m=0|this._h,v=0;v<16;++v)r[v]=e.readInt32BE(4*v);for(;v<64;++v)r[v]=0|(((t=r[v-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+r[v-7]+d(r[v-15])+r[v-16];for(var g=0;g<64;++g){var b=m+p(u)+c(u,h,y)+a[g]+r[g]|0,w=f(n)+l(n,o,i)|0;m=y,y=h,h=u,u=s+b|0,s=i,i=o,o=n,n=b+w|0}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0,this._f=h+this._f|0,this._g=y+this._g|0,this._h=m+this._h|0},u.prototype._hash=function(){var e=i.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},e.exports=u},2827:(e,t,r)=>{var n=r(6698),o=r(2890),i=r(392),a=r(2861).Buffer,s=new Array(160);function u(){this.init(),this._w=s,i.call(this,128,112)}n(u,o),u.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(48);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},e.exports=u},2890:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],s=new Array(160);function u(){this.init(),this._w=s,o.call(this,128,112)}function c(e,t,r){return r^e&(t^r)}function l(e,t,r){return e&t|r&(e|t)}function f(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function p(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function d(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function h(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function y(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function m(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function v(e,t){return e>>>0>>0?1:0}n(u,o),u.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},u.prototype._update=function(e){for(var t=this._w,r=0|this._ah,n=0|this._bh,o=0|this._ch,i=0|this._dh,s=0|this._eh,u=0|this._fh,g=0|this._gh,b=0|this._hh,w=0|this._al,S=0|this._bl,_=0|this._cl,E=0|this._dl,k=0|this._el,T=0|this._fl,O=0|this._gl,x=0|this._hl,A=0;A<32;A+=2)t[A]=e.readInt32BE(4*A),t[A+1]=e.readInt32BE(4*A+4);for(;A<160;A+=2){var P=t[A-30],R=t[A-30+1],j=d(P,R),I=h(R,P),C=y(P=t[A-4],R=t[A-4+1]),L=m(R,P),B=t[A-14],N=t[A-14+1],U=t[A-32],M=t[A-32+1],D=I+N|0,F=j+B+v(D,I)|0;F=(F=F+C+v(D=D+L|0,L)|0)+U+v(D=D+M|0,M)|0,t[A]=F,t[A+1]=D}for(var V=0;V<160;V+=2){F=t[V],D=t[V+1];var q=l(r,n,o),K=l(w,S,_),H=f(r,w),z=f(w,r),X=p(s,k),G=p(k,s),W=a[V],$=a[V+1],Q=c(s,u,g),Y=c(k,T,O),J=x+G|0,Z=b+X+v(J,x)|0;Z=(Z=(Z=Z+Q+v(J=J+Y|0,Y)|0)+W+v(J=J+$|0,$)|0)+F+v(J=J+D|0,D)|0;var ee=z+K|0,te=H+q+v(ee,z)|0;b=g,x=O,g=u,O=T,u=s,T=k,s=i+Z+v(k=E+J|0,E)|0,i=o,E=_,o=n,_=S,n=r,S=w,r=Z+te+v(w=J+ee|0,J)|0}this._al=this._al+w|0,this._bl=this._bl+S|0,this._cl=this._cl+_|0,this._dl=this._dl+E|0,this._el=this._el+k|0,this._fl=this._fl+T|0,this._gl=this._gl+O|0,this._hl=this._hl+x|0,this._ah=this._ah+r+v(this._al,w)|0,this._bh=this._bh+n+v(this._bl,S)|0,this._ch=this._ch+o+v(this._cl,_)|0,this._dh=this._dh+i+v(this._dl,E)|0,this._eh=this._eh+s+v(this._el,k)|0,this._fh=this._fh+u+v(this._fl,T)|0,this._gh=this._gh+g+v(this._gl,O)|0,this._hh=this._hh+b+v(this._hl,x)|0},u.prototype._hash=function(){var e=i.allocUnsafe(64);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},e.exports=u},4803:(e,t,r)=>{"use strict";var n=r(8859),o=r(9675),i=function(e,t,r){for(var n,o=e;null!=(n=o.next);o=n)if(n.key===t)return o.next=n.next,r||(n.next=e.next,e.next=n),n};e.exports=function(){var e,t={assert:function(e){if(!t.has(e))throw new o("Side channel does not contain "+n(e))},delete:function(t){var r=e&&e.next,n=function(e,t){if(e)return i(e,t,!0)}(e,t);return n&&r&&r===n&&(e=void 0),!!n},get:function(t){return function(e,t){if(e){var r=i(e,t);return r&&r.value}}(e,t)},has:function(t){return function(e,t){return!!e&&!!i(e,t)}(e,t)},set:function(t,r){e||(e={next:void 0}),function(e,t,r){var n=i(e,t);n?n.value=r:e.next={key:t,next:e.next,value:r}}(e,t,r)}};return t}},507:(e,t,r)=>{"use strict";var n=r(453),o=r(6556),i=r(8859),a=r(9675),s=n("%Map%",!0),u=o("Map.prototype.get",!0),c=o("Map.prototype.set",!0),l=o("Map.prototype.has",!0),f=o("Map.prototype.delete",!0),p=o("Map.prototype.size",!0);e.exports=!!s&&function(){var e,t={assert:function(e){if(!t.has(e))throw new a("Side channel does not contain "+i(e))},delete:function(t){if(e){var r=f(e,t);return 0===p(e)&&(e=void 0),r}return!1},get:function(t){if(e)return u(e,t)},has:function(t){return!!e&&l(e,t)},set:function(t,r){e||(e=new s),c(e,t,r)}};return t}},2271:(e,t,r)=>{"use strict";var n=r(453),o=r(6556),i=r(8859),a=r(507),s=r(9675),u=n("%WeakMap%",!0),c=o("WeakMap.prototype.get",!0),l=o("WeakMap.prototype.set",!0),f=o("WeakMap.prototype.has",!0),p=o("WeakMap.prototype.delete",!0);e.exports=u?function(){var e,t,r={assert:function(e){if(!r.has(e))throw new s("Side channel does not contain "+i(e))},delete:function(r){if(u&&r&&("object"==typeof r||"function"==typeof r)){if(e)return p(e,r)}else if(a&&t)return t.delete(r);return!1},get:function(r){return u&&r&&("object"==typeof r||"function"==typeof r)&&e?c(e,r):t&&t.get(r)},has:function(r){return u&&r&&("object"==typeof r||"function"==typeof r)&&e?f(e,r):!!t&&t.has(r)},set:function(r,n){u&&r&&("object"==typeof r||"function"==typeof r)?(e||(e=new u),l(e,r,n)):a&&(t||(t=a()),t.set(r,n))}};return r}:a},920:(e,t,r)=>{"use strict";var n=r(9675),o=r(8859),i=r(4803),a=r(507),s=r(2271)||a||i;e.exports=function(){var e,t={assert:function(e){if(!t.has(e))throw new n("Side channel does not contain "+o(e))},delete:function(t){return!!e&&e.delete(t)},get:function(t){return e&&e.get(t)},has:function(t){return!!e&&e.has(t)},set:function(t,r){e||(e=s()),e.set(t,r)}};return t}},1568:(e,t,r)=>{var n=r(5537),o=r(6917),i=r(7510),a=r(6866),s=r(8835),u=t;u.request=function(e,t){e="string"==typeof e?s.parse(e):i(e);var o=-1===r.g.location.protocol.search(/^https?:$/)?"http:":"",a=e.protocol||o,u=e.hostname||e.host,c=e.port,l=e.path||"/";u&&-1!==u.indexOf(":")&&(u="["+u+"]"),e.url=(u?a+"//"+u:"")+(c?":"+c:"")+l,e.method=(e.method||"GET").toUpperCase(),e.headers=e.headers||{};var f=new n(e);return t&&f.on("response",t),f},u.get=function(e,t){var r=u.request(e,t);return r.end(),r},u.ClientRequest=n,u.IncomingMessage=o.IncomingMessage,u.Agent=function(){},u.Agent.defaultMaxSockets=4,u.globalAgent=new u.Agent,u.STATUS_CODES=a,u.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]},6688:(e,t,r)=>{var n;function o(){if(void 0!==n)return n;if(r.g.XMLHttpRequest){n=new r.g.XMLHttpRequest;try{n.open("GET",r.g.XDomainRequest?"/":"https://example.com")}catch(e){n=null}}else n=null;return n}function i(e){var t=o();if(!t)return!1;try{return t.responseType=e,t.responseType===e}catch(e){}return!1}function a(e){return"function"==typeof e}t.fetch=a(r.g.fetch)&&a(r.g.ReadableStream),t.writableStream=a(r.g.WritableStream),t.abortController=a(r.g.AbortController),t.arraybuffer=t.fetch||i("arraybuffer"),t.msstream=!t.fetch&&i("ms-stream"),t.mozchunkedarraybuffer=!t.fetch&&i("moz-chunked-arraybuffer"),t.overrideMimeType=t.fetch||!!o()&&a(o().overrideMimeType),n=null},5537:(e,t,r)=>{var n=r(8287).Buffer,o=r(6688),i=r(6698),a=r(6917),s=r(8399),u=a.IncomingMessage,c=a.readyStates;var l=e.exports=function(e){var t,r=this;s.Writable.call(r),r._opts=e,r._body=[],r._headers={},e.auth&&r.setHeader("Authorization","Basic "+n.from(e.auth).toString("base64")),Object.keys(e.headers).forEach((function(t){r.setHeader(t,e.headers[t])}));var i=!0;if("disable-fetch"===e.mode||"requestTimeout"in e&&!o.abortController)i=!1,t=!0;else if("prefer-streaming"===e.mode)t=!1;else if("allow-wrong-content-type"===e.mode)t=!o.overrideMimeType;else{if(e.mode&&"default"!==e.mode&&"prefer-fast"!==e.mode)throw new Error("Invalid value for opts.mode");t=!0}r._mode=function(e,t){return o.fetch&&t?"fetch":o.mozchunkedarraybuffer?"moz-chunked-arraybuffer":o.msstream?"ms-stream":o.arraybuffer&&e?"arraybuffer":"text"}(t,i),r._fetchTimer=null,r._socketTimeout=null,r._socketTimer=null,r.on("finish",(function(){r._onFinish()}))};i(l,s.Writable),l.prototype.setHeader=function(e,t){var r=e.toLowerCase();-1===f.indexOf(r)&&(this._headers[r]={name:e,value:t})},l.prototype.getHeader=function(e){var t=this._headers[e.toLowerCase()];return t?t.value:null},l.prototype.removeHeader=function(e){delete this._headers[e.toLowerCase()]},l.prototype._onFinish=function(){var e=this;if(!e._destroyed){var t=e._opts;"timeout"in t&&0!==t.timeout&&e.setTimeout(t.timeout);var n=e._headers,i=null;"GET"!==t.method&&"HEAD"!==t.method&&(i=new Blob(e._body,{type:(n["content-type"]||{}).value||""}));var a=[];if(Object.keys(n).forEach((function(e){var t=n[e].name,r=n[e].value;Array.isArray(r)?r.forEach((function(e){a.push([t,e])})):a.push([t,r])})),"fetch"===e._mode){var s=null;if(o.abortController){var u=new AbortController;s=u.signal,e._fetchAbortController=u,"requestTimeout"in t&&0!==t.requestTimeout&&(e._fetchTimer=r.g.setTimeout((function(){e.emit("requestTimeout"),e._fetchAbortController&&e._fetchAbortController.abort()}),t.requestTimeout))}r.g.fetch(e._opts.url,{method:e._opts.method,headers:a,body:i||void 0,mode:"cors",credentials:t.withCredentials?"include":"same-origin",signal:s}).then((function(t){e._fetchResponse=t,e._resetTimers(!1),e._connect()}),(function(t){e._resetTimers(!0),e._destroyed||e.emit("error",t)}))}else{var l=e._xhr=new r.g.XMLHttpRequest;try{l.open(e._opts.method,e._opts.url,!0)}catch(t){return void process.nextTick((function(){e.emit("error",t)}))}"responseType"in l&&(l.responseType=e._mode),"withCredentials"in l&&(l.withCredentials=!!t.withCredentials),"text"===e._mode&&"overrideMimeType"in l&&l.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in t&&(l.timeout=t.requestTimeout,l.ontimeout=function(){e.emit("requestTimeout")}),a.forEach((function(e){l.setRequestHeader(e[0],e[1])})),e._response=null,l.onreadystatechange=function(){switch(l.readyState){case c.LOADING:case c.DONE:e._onXHRProgress()}},"moz-chunked-arraybuffer"===e._mode&&(l.onprogress=function(){e._onXHRProgress()}),l.onerror=function(){e._destroyed||(e._resetTimers(!0),e.emit("error",new Error("XHR error")))};try{l.send(i)}catch(t){return void process.nextTick((function(){e.emit("error",t)}))}}}},l.prototype._onXHRProgress=function(){var e=this;e._resetTimers(!1),function(e){try{var t=e.status;return null!==t&&0!==t}catch(e){return!1}}(e._xhr)&&!e._destroyed&&(e._response||e._connect(),e._response._onXHRProgress(e._resetTimers.bind(e)))},l.prototype._connect=function(){var e=this;e._destroyed||(e._response=new u(e._xhr,e._fetchResponse,e._mode,e._resetTimers.bind(e)),e._response.on("error",(function(t){e.emit("error",t)})),e.emit("response",e._response))},l.prototype._write=function(e,t,r){this._body.push(e),r()},l.prototype._resetTimers=function(e){var t=this;r.g.clearTimeout(t._socketTimer),t._socketTimer=null,e?(r.g.clearTimeout(t._fetchTimer),t._fetchTimer=null):t._socketTimeout&&(t._socketTimer=r.g.setTimeout((function(){t.emit("timeout")}),t._socketTimeout))},l.prototype.abort=l.prototype.destroy=function(e){var t=this;t._destroyed=!0,t._resetTimers(!0),t._response&&(t._response._destroyed=!0),t._xhr?t._xhr.abort():t._fetchAbortController&&t._fetchAbortController.abort(),e&&t.emit("error",e)},l.prototype.end=function(e,t,r){"function"==typeof e&&(r=e,e=void 0),s.Writable.prototype.end.call(this,e,t,r)},l.prototype.setTimeout=function(e,t){var r=this;t&&r.once("timeout",t),r._socketTimeout=e,r._resetTimers(!1)},l.prototype.flushHeaders=function(){},l.prototype.setNoDelay=function(){},l.prototype.setSocketKeepAlive=function(){};var f=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]},6917:(e,t,r)=>{var n=r(8287).Buffer,o=r(6688),i=r(6698),a=r(8399),s=t.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},u=t.IncomingMessage=function(e,t,r,i){var s=this;if(a.Readable.call(s),s._mode=r,s.headers={},s.rawHeaders=[],s.trailers={},s.rawTrailers=[],s.on("end",(function(){process.nextTick((function(){s.emit("close")}))})),"fetch"===r){if(s._fetchResponse=t,s.url=t.url,s.statusCode=t.status,s.statusMessage=t.statusText,t.headers.forEach((function(e,t){s.headers[t.toLowerCase()]=e,s.rawHeaders.push(t,e)})),o.writableStream){var u=new WritableStream({write:function(e){return i(!1),new Promise((function(t,r){s._destroyed?r():s.push(n.from(e))?t():s._resumeFetch=t}))},close:function(){i(!0),s._destroyed||s.push(null)},abort:function(e){i(!0),s._destroyed||s.emit("error",e)}});try{return void t.body.pipeTo(u).catch((function(e){i(!0),s._destroyed||s.emit("error",e)}))}catch(e){}}var c=t.body.getReader();!function e(){c.read().then((function(t){s._destroyed||(i(t.done),t.done?s.push(null):(s.push(n.from(t.value)),e()))})).catch((function(e){i(!0),s._destroyed||s.emit("error",e)}))}()}else{if(s._xhr=e,s._pos=0,s.url=e.responseURL,s.statusCode=e.status,s.statusMessage=e.statusText,e.getAllResponseHeaders().split(/\r?\n/).forEach((function(e){var t=e.match(/^([^:]+):\s*(.*)/);if(t){var r=t[1].toLowerCase();"set-cookie"===r?(void 0===s.headers[r]&&(s.headers[r]=[]),s.headers[r].push(t[2])):void 0!==s.headers[r]?s.headers[r]+=", "+t[2]:s.headers[r]=t[2],s.rawHeaders.push(t[1],t[2])}})),s._charset="x-user-defined",!o.overrideMimeType){var l=s.rawHeaders["mime-type"];if(l){var f=l.match(/;\s*charset=([^;])(;|$)/);f&&(s._charset=f[1].toLowerCase())}s._charset||(s._charset="utf-8")}}};i(u,a.Readable),u.prototype._read=function(){var e=this._resumeFetch;e&&(this._resumeFetch=null,e())},u.prototype._onXHRProgress=function(e){var t=this,o=t._xhr,i=null;switch(t._mode){case"text":if((i=o.responseText).length>t._pos){var a=i.substr(t._pos);if("x-user-defined"===t._charset){for(var u=n.alloc(a.length),c=0;ct._pos&&(t.push(n.from(new Uint8Array(l.result.slice(t._pos)))),t._pos=l.result.byteLength)},l.onload=function(){e(!0),t.push(null)},l.readAsArrayBuffer(i)}t._xhr.readyState===s.DONE&&"ms-stream"!==t._mode&&(e(!0),t.push(null))}},3141:(e,t,r)=>{"use strict";var n=r(2861).Buffer,o=n.isEncoding||function(e){switch((e=""+e)&&e.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!0;default:return!1}};function i(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){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 e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=u,this.end=c,t=4;break;case"utf8":this.fillLast=s,t=4;break;case"base64":this.text=l,this.end=f,t=3;break;default:return this.write=p,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function a(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e){var t=this.lastTotal-this.lastNeed,r=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"\ufffd";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"\ufffd";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"\ufffd"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function u(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function c(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function l(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function f(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function p(e){return e.toString(this.encoding)}function d(e){return e&&e.length?this.write(e):""}t.I=i,i.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return o>0&&(e.lastNeed=o-1),o;if(--n=0)return o>0&&(e.lastNeed=o-2),o;if(--n=0)return o>0&&(2===o?o=0:e.lastNeed=o-3),o;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},i.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},1293:(e,t,r)=>{var n=r(5546),o=r(2708);e.exports={parse:function(e){var t=n.parse(e.toString());return o.compile(t)}}},2708:e=>{"use strict";e.exports={compile:function(e){var t=[],r=[],n="",o=Object.create(null),i=o;return function(e){for(var t,r=0;r-1&&a("Cannot redefine existing key '"+u+"'.",o,i),(c=c[f])instanceof Array&&c.length&&l-1?'"'+e+'"':e}}}},5546:e=>{e.exports=function(){function e(e,t,r,n,o,i){this.message=e,this.expected=t,this.found=r,this.offset=n,this.line=o,this.column=i,this.name="SyntaxError"}return function(e,t){function r(){this.constructor=e}r.prototype=t.prototype,e.prototype=new r}(e,Error),{SyntaxError:e,parse:function(t){var r,n=arguments.length>1?arguments[1]:{},o={},i={start:Lt},a=Lt,s=function(){return pr},u=o,c="#",l={type:"literal",value:"#",description:'"#"'},f=void 0,p={type:"any",description:"any character"},d="[",h={type:"literal",value:"[",description:'"["'},y="]",m={type:"literal",value:"]",description:'"]"'},v=function(e){dr(hr("ObjectPath",e,Pt,Rt))},g=function(e){dr(hr("ArrayPath",e,Pt,Rt))},b=function(e,t){return e.concat(t)},w=function(e){return[e]},S=function(e){return e},_=".",E={type:"literal",value:".",description:'"."'},k="=",T={type:"literal",value:"=",description:'"="'},O=function(e,t){dr(hr("Assign",t,Pt,Rt,e))},x=function(e){return e.join("")},A=function(e){return e.value},P='"""',R={type:"literal",value:'"""',description:'"\\"\\"\\""'},j=null,I=function(e){return hr("String",e.join(""),Pt,Rt)},C='"',L={type:"literal",value:'"',description:'"\\""'},B="'''",N={type:"literal",value:"'''",description:"\"'''\""},U="'",M={type:"literal",value:"'",description:'"\'"'},D=function(e){return e},F=function(e){return e},V="\\",q={type:"literal",value:"\\",description:'"\\\\"'},K=function(){return""},H="e",z={type:"literal",value:"e",description:'"e"'},X="E",G={type:"literal",value:"E",description:'"E"'},W=function(e,t){return hr("Float",parseFloat(e+"e"+t),Pt,Rt)},$=function(e){return hr("Float",parseFloat(e),Pt,Rt)},Q="+",Y={type:"literal",value:"+",description:'"+"'},J=function(e){return e.join("")},Z="-",ee={type:"literal",value:"-",description:'"-"'},te=function(e){return"-"+e.join("")},re=function(e){return hr("Integer",parseInt(e,10),Pt,Rt)},ne="true",oe={type:"literal",value:"true",description:'"true"'},ie=function(){return hr("Boolean",!0,Pt,Rt)},ae="false",se={type:"literal",value:"false",description:'"false"'},ue=function(){return hr("Boolean",!1,Pt,Rt)},ce=function(){return hr("Array",[],Pt,Rt)},le=function(e){return hr("Array",e?[e]:[],Pt,Rt)},fe=function(e){return hr("Array",e,Pt,Rt)},pe=function(e,t){return hr("Array",e.concat(t),Pt,Rt)},de=function(e){return e},he=",",ye={type:"literal",value:",",description:'","'},me="{",ve={type:"literal",value:"{",description:'"{"'},ge="}",be={type:"literal",value:"}",description:'"}"'},we=function(e){return hr("InlineTable",e,Pt,Rt)},Se=function(e,t){return hr("InlineTableValue",t,Pt,Rt,e)},_e=function(e){return"."+e},Ee=function(e){return e.join("")},ke=":",Te={type:"literal",value:":",description:'":"'},Oe=function(e){return e.join("")},xe="T",Ae={type:"literal",value:"T",description:'"T"'},Pe="Z",Re={type:"literal",value:"Z",description:'"Z"'},je=function(e,t){return hr("Date",new Date(e+"T"+t+"Z"),Pt,Rt)},Ie=function(e,t){return hr("Date",new Date(e+"T"+t),Pt,Rt)},Ce=/^[ \t]/,Le={type:"class",value:"[ \\t]",description:"[ \\t]"},Be="\n",Ne={type:"literal",value:"\n",description:'"\\n"'},Ue="\r",Me={type:"literal",value:"\r",description:'"\\r"'},De=/^[0-9a-f]/i,Fe={type:"class",value:"[0-9a-f]i",description:"[0-9a-f]i"},Ve=/^[0-9]/,qe={type:"class",value:"[0-9]",description:"[0-9]"},Ke="_",He={type:"literal",value:"_",description:'"_"'},ze=function(){return""},Xe=/^[A-Za-z0-9_\-]/,Ge={type:"class",value:"[A-Za-z0-9_\\-]",description:"[A-Za-z0-9_\\-]"},We=function(e){return e.join("")},$e='\\"',Qe={type:"literal",value:'\\"',description:'"\\\\\\""'},Ye=function(){return'"'},Je="\\\\",Ze={type:"literal",value:"\\\\",description:'"\\\\\\\\"'},et=function(){return"\\"},tt="\\b",rt={type:"literal",value:"\\b",description:'"\\\\b"'},nt=function(){return"\b"},ot="\\t",it={type:"literal",value:"\\t",description:'"\\\\t"'},at=function(){return"\t"},st="\\n",ut={type:"literal",value:"\\n",description:'"\\\\n"'},ct=function(){return"\n"},lt="\\f",ft={type:"literal",value:"\\f",description:'"\\\\f"'},pt=function(){return"\f"},dt="\\r",ht={type:"literal",value:"\\r",description:'"\\\\r"'},yt=function(){return"\r"},mt="\\U",vt={type:"literal",value:"\\U",description:'"\\\\U"'},gt=function(e){return function(e,t,r){var n=parseInt("0x"+e);if(!(!isFinite(n)||Math.floor(n)!=n||n<0||n>1114111||n>55295&&n<57344))return function(){var e,t,r=16384,n=[],o=-1,i=arguments.length;if(!i)return"";var a="";for(;++o>10),t=s%1024+56320,n.push(e,t)),(o+1==i||n.length>r)&&(a+=String.fromCharCode.apply(null,n),n.length=0)}return a}(n);!function(e,t,r){var n=new Error(e);throw n.line=t,n.column=r,n}("Invalid Unicode escape code: "+e,t,r)}(e.join(""))},bt="\\u",wt={type:"literal",value:"\\u",description:'"\\\\u"'},St=0,_t=0,Et=0,kt={line:1,column:1,seenCR:!1},Tt=0,Ot=[],xt=0,At={};if("startRule"in n){if(!(n.startRule in i))throw new Error("Can't start parsing from rule \""+n.startRule+'".');a=i[n.startRule]}function Pt(){return jt(_t).line}function Rt(){return jt(_t).column}function jt(e){return Et!==e&&(Et>e&&(Et=0,kt={line:1,column:1,seenCR:!1}),function(e,r,n){var o,i;for(o=r;oTt&&(Tt=St,Ot=[]),Ot.push(e))}function Ct(r,n,o){var i=jt(o),a=ot.description?1:0}));t1?n.slice(0,-1).join(", ")+" or "+n[e.length-1]:n[0])+" but "+(t?'"'+function(e){function t(e){return e.charCodeAt(0).toString(16).toUpperCase()}return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E\x0F]/g,(function(e){return"\\x0"+t(e)})).replace(/[\x10-\x1F\x80-\xFF]/g,(function(e){return"\\x"+t(e)})).replace(/[\u0180-\u0FFF]/g,(function(e){return"\\u0"+t(e)})).replace(/[\u1080-\uFFFF]/g,(function(e){return"\\u"+t(e)}))}(t)+'"':"end of input")+" found."}(n,a),n,a,o,i.line,i.column)}function Lt(){var e,t,r,n=49*St+0,i=At[n];if(i)return St=i.nextPos,i.result;for(e=St,t=[],r=Bt();r!==o;)t.push(r),r=Bt();return t!==o&&(_t=e,t=s()),e=t,At[n]={nextPos:St,result:e},e}function Bt(){var e,r,n,i,a,s,c,l=49*St+1,f=At[l];if(f)return St=f.nextPos,f.result;for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if(n=function(){var e,r=49*St+2,n=At[r];if(n)return St=n.nextPos,n.result;e=Nt(),e===o&&(e=function(){var e,r,n,i,a,s,c=49*St+4,l=At[c];if(l)return St=l.nextPos,l.result;e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&It(h));if(r!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o)if((i=Ut())!==o){for(a=[],s=nr();s!==o;)a.push(s),s=nr();a!==o?(93===t.charCodeAt(St)?(s=y,St++):(s=o,0===xt&&It(m)),s!==o?(_t=e,e=r=v(i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;return At[c]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s,c,l,f=49*St+5,p=At[f];if(p)return St=p.nextPos,p.result;e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&It(h));if(r!==o)if(91===t.charCodeAt(St)?(n=d,St++):(n=o,0===xt&&It(h)),n!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if((a=Ut())!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();s!==o?(93===t.charCodeAt(St)?(c=y,St++):(c=o,0===xt&&It(m)),c!==o?(93===t.charCodeAt(St)?(l=y,St++):(l=o,0===xt&&It(m)),l!==o?(_t=e,e=r=g(a)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u;return At[f]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s,c=49*St+9,l=At[c];if(l)return St=l.nextPos,l.result;if(e=St,r=Ft(),r!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o)if(61===t.charCodeAt(St)?(i=k,St++):(i=o,0===xt&&It(T)),i!==o){for(a=[],s=nr();s!==o;)a.push(s),s=nr();a!==o&&(s=qt())!==o?(_t=e,e=r=O(r,s)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;if(e===o)if(e=St,(r=Vt())!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o)if(61===t.charCodeAt(St)?(i=k,St++):(i=o,0===xt&&It(T)),i!==o){for(a=[],s=nr();s!==o;)a.push(s),s=nr();a!==o&&(s=qt())!==o?(_t=e,e=r=O(r,s)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;return At[c]={nextPos:St,result:e},e}())));return At[r]={nextPos:St,result:e},e}(),n!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o){for(a=[],s=Nt();s!==o;)a.push(s),s=Nt();if(a!==o){if(s=[],(c=or())!==o)for(;c!==o;)s.push(c),c=or();else s=u;s===o&&(s=ar()),s!==o?e=r=[r,n,i,a,s]:(St=e,e=u)}else St=e,e=u}else St=e,e=u}else St=e,e=u;else St=e,e=u;if(e===o){if(e=St,r=[],(n=nr())!==o)for(;n!==o;)r.push(n),n=nr();else r=u;if(r!==o){if(n=[],(i=or())!==o)for(;i!==o;)n.push(i),i=or();else n=u;n===o&&(n=ar()),n!==o?e=r=[r,n]:(St=e,e=u)}else St=e,e=u;e===o&&(e=or())}return At[l]={nextPos:St,result:e},e}function Nt(){var e,r,n,i,a,s,d=49*St+3,h=At[d];if(h)return St=h.nextPos,h.result;if(e=St,35===t.charCodeAt(St)?(r=c,St++):(r=o,0===xt&&It(l)),r!==o){for(n=[],i=St,a=St,xt++,(s=or())===o&&(s=ar()),xt--,s===o?a=f:(St=a,a=u),a!==o?(t.length>St?(s=t.charAt(St),St++):(s=o,0===xt&&It(p)),s!==o?i=a=[a,s]:(St=i,i=u)):(St=i,i=u);i!==o;)n.push(i),i=St,a=St,xt++,(s=or())===o&&(s=ar()),xt--,s===o?a=f:(St=a,a=u),a!==o?(t.length>St?(s=t.charAt(St),St++):(s=o,0===xt&&It(p)),s!==o?i=a=[a,s]:(St=i,i=u)):(St=i,i=u);n!==o?e=r=[r,n]:(St=e,e=u)}else St=e,e=u;return At[d]={nextPos:St,result:e},e}function Ut(){var e,t,r,n=49*St+6,i=At[n];if(i)return St=i.nextPos,i.result;if(e=St,t=[],(r=Dt())!==o)for(;r!==o;)t.push(r),r=Dt();else t=u;return t!==o&&(r=Mt())!==o?(_t=e,e=t=b(t,r)):(St=e,e=u),e===o&&(e=St,(t=Mt())!==o&&(_t=e,t=w(t)),e=t),At[n]={nextPos:St,result:e},e}function Mt(){var e,t,r,n,i,a=49*St+7,s=At[a];if(s)return St=s.nextPos,s.result;for(e=St,t=[],r=nr();r!==o;)t.push(r),r=nr();if(t!==o)if((r=Ft())!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();n!==o?(_t=e,e=t=S(r)):(St=e,e=u)}else St=e,e=u;else St=e,e=u;if(e===o){for(e=St,t=[],r=nr();r!==o;)t.push(r),r=nr();if(t!==o)if((r=Vt())!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();n!==o?(_t=e,e=t=S(r)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}return At[a]={nextPos:St,result:e},e}function Dt(){var e,r,n,i,a,s,c,l=49*St+8,f=At[l];if(f)return St=f.nextPos,f.result;for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Ft())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(46===t.charCodeAt(St)?(a=_,St++):(a=o,0===xt&&It(E)),a!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();s!==o?(_t=e,e=r=S(n)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u;if(e===o){for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Vt())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(46===t.charCodeAt(St)?(a=_,St++):(a=o,0===xt&&It(E)),a!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();s!==o?(_t=e,e=r=S(n)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u}return At[l]={nextPos:St,result:e},e}function Ft(){var e,t,r,n=49*St+10,i=At[n];if(i)return St=i.nextPos,i.result;if(e=St,t=[],(r=cr())!==o)for(;r!==o;)t.push(r),r=cr();else t=u;return t!==o&&(_t=e,t=x(t)),e=t,At[n]={nextPos:St,result:e},e}function Vt(){var e,t,r=49*St+11,n=At[r];return n?(St=n.nextPos,n.result):(e=St,(t=Kt())!==o&&(_t=e,t=A(t)),(e=t)===o&&(e=St,(t=Ht())!==o&&(_t=e,t=A(t)),e=t),At[r]={nextPos:St,result:e},e)}function qt(){var e,r=49*St+12,n=At[r];return n?(St=n.nextPos,n.result):(e=function(){var e,r=49*St+13,n=At[r];if(n)return St=n.nextPos,n.result;e=function(){var e,r,n,i,a,s=49*St+14,c=At[s];if(c)return St=c.nextPos,c.result;e=St,t.substr(St,3)===P?(r=P,St+=3):(r=o,0===xt&&It(R));if(r!==o)if((n=or())===o&&(n=j),n!==o){for(i=[],a=Gt();a!==o;)i.push(a),a=Gt();i!==o?(t.substr(St,3)===P?(a=P,St+=3):(a=o,0===xt&&It(R)),a!==o?(_t=e,e=r=I(i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;else St=e,e=u;return At[s]={nextPos:St,result:e},e}(),e===o&&(e=Kt())===o&&(e=function(){var e,r,n,i,a,s=49*St+16,c=At[s];if(c)return St=c.nextPos,c.result;e=St,t.substr(St,3)===B?(r=B,St+=3):(r=o,0===xt&&It(N));if(r!==o)if((n=or())===o&&(n=j),n!==o){for(i=[],a=Wt();a!==o;)i.push(a),a=Wt();i!==o?(t.substr(St,3)===B?(a=B,St+=3):(a=o,0===xt&&It(N)),a!==o?(_t=e,e=r=I(i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;else St=e,e=u;return At[s]={nextPos:St,result:e},e}(),e===o&&(e=Ht()));return At[r]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s=49*St+38,c=At[s];if(c)return St=c.nextPos,c.result;e=St,(r=rr())!==o?(84===t.charCodeAt(St)?(n=xe,St++):(n=o,0===xt&&It(Ae)),n!==o?(i=function(){var e,r,n,i,a,s,c,l,f,p,d,h=49*St+36,y=At[h];if(y)return St=y.nextPos,y.result;e=St,r=St,n=ur(),n!==o&&(i=ur())!==o?(58===t.charCodeAt(St)?(a=ke,St++):(a=o,0===xt&&It(Te)),a!==o&&(s=ur())!==o&&(c=ur())!==o?(58===t.charCodeAt(St)?(l=ke,St++):(l=o,0===xt&&It(Te)),l!==o&&(f=ur())!==o&&(p=ur())!==o?((d=tr())===o&&(d=j),d!==o?r=n=[n,i,a,s,c,l,f,p,d]:(St=r,r=u)):(St=r,r=u)):(St=r,r=u)):(St=r,r=u);r!==o&&(_t=e,r=Oe(r));return e=r,At[h]={nextPos:St,result:e},e}(),i!==o?(90===t.charCodeAt(St)?(a=Pe,St++):(a=o,0===xt&&It(Re)),a!==o?(_t=e,e=r=je(r,i)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u);e===o&&(e=St,(r=rr())!==o?(84===t.charCodeAt(St)?(n=xe,St++):(n=o,0===xt&&It(Ae)),n!==o?(i=function(){var e,r,n,i,a,s,c,l,f,p,d,h,y,m,v,g,b,w=49*St+37,S=At[w];if(S)return St=S.nextPos,S.result;e=St,r=St,n=ur(),n!==o&&(i=ur())!==o?(58===t.charCodeAt(St)?(a=ke,St++):(a=o,0===xt&&It(Te)),a!==o&&(s=ur())!==o&&(c=ur())!==o?(58===t.charCodeAt(St)?(l=ke,St++):(l=o,0===xt&&It(Te)),l!==o&&(f=ur())!==o&&(p=ur())!==o?((d=tr())===o&&(d=j),d!==o?(45===t.charCodeAt(St)?(h=Z,St++):(h=o,0===xt&&It(ee)),h===o&&(43===t.charCodeAt(St)?(h=Q,St++):(h=o,0===xt&&It(Y))),h!==o&&(y=ur())!==o&&(m=ur())!==o?(58===t.charCodeAt(St)?(v=ke,St++):(v=o,0===xt&&It(Te)),v!==o&&(g=ur())!==o&&(b=ur())!==o?r=n=[n,i,a,s,c,l,f,p,d,h,y,m,v,g,b]:(St=r,r=u)):(St=r,r=u)):(St=r,r=u)):(St=r,r=u)):(St=r,r=u)):(St=r,r=u);r!==o&&(_t=e,r=Oe(r));return e=r,At[w]={nextPos:St,result:e},e}(),i!==o?(_t=e,e=r=Ie(r,i)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u));return At[s]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a=49*St+23,s=At[a];if(s)return St=s.nextPos,s.result;e=St,(r=$t())===o&&(r=Qt());r!==o?(101===t.charCodeAt(St)?(n=H,St++):(n=o,0===xt&&It(z)),n===o&&(69===t.charCodeAt(St)?(n=X,St++):(n=o,0===xt&&It(G))),n!==o&&(i=Qt())!==o?(_t=e,e=r=W(r,i)):(St=e,e=u)):(St=e,e=u);e===o&&(e=St,(r=$t())!==o&&(_t=e,r=$(r)),e=r);return At[a]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,t,r=49*St+25,n=At[r];if(n)return St=n.nextPos,n.result;e=St,(t=Qt())!==o&&(_t=e,t=re(t));return e=t,At[r]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n=49*St+27,i=At[n];if(i)return St=i.nextPos,i.result;e=St,t.substr(St,4)===ne?(r=ne,St+=4):(r=o,0===xt&&It(oe));r!==o&&(_t=e,r=ie());e=r,e===o&&(e=St,t.substr(St,5)===ae?(r=ae,St+=5):(r=o,0===xt&&It(se)),r!==o&&(_t=e,r=ue()),e=r);return At[n]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s=49*St+28,c=At[s];if(c)return St=c.nextPos,c.result;e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&It(h));if(r!==o){for(n=[],i=Zt();i!==o;)n.push(i),i=Zt();n!==o?(93===t.charCodeAt(St)?(i=y,St++):(i=o,0===xt&&It(m)),i!==o?(_t=e,e=r=ce()):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;if(e===o&&(e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&It(h)),r!==o?((n=Yt())===o&&(n=j),n!==o?(93===t.charCodeAt(St)?(i=y,St++):(i=o,0===xt&&It(m)),i!==o?(_t=e,e=r=le(n)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u),e===o)){if(e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&It(h)),r!==o){if(n=[],(i=Jt())!==o)for(;i!==o;)n.push(i),i=Jt();else n=u;n!==o?(93===t.charCodeAt(St)?(i=y,St++):(i=o,0===xt&&It(m)),i!==o?(_t=e,e=r=fe(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;if(e===o)if(e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&It(h)),r!==o){if(n=[],(i=Jt())!==o)for(;i!==o;)n.push(i),i=Jt();else n=u;n!==o&&(i=Yt())!==o?(93===t.charCodeAt(St)?(a=y,St++):(a=o,0===xt&&It(m)),a!==o?(_t=e,e=r=pe(n,i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u}return At[s]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s,c=49*St+32,l=At[c];if(l)return St=l.nextPos,l.result;e=St,123===t.charCodeAt(St)?(r=me,St++):(r=o,0===xt&&It(ve));if(r!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o){for(i=[],a=er();a!==o;)i.push(a),a=er();if(i!==o){for(a=[],s=nr();s!==o;)a.push(s),s=nr();a!==o?(125===t.charCodeAt(St)?(s=ge,St++):(s=o,0===xt&&It(be)),s!==o?(_t=e,e=r=we(i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u}else St=e,e=u}else St=e,e=u;return At[c]={nextPos:St,result:e},e}())))))),At[r]={nextPos:St,result:e},e)}function Kt(){var e,r,n,i,a=49*St+15,s=At[a];if(s)return St=s.nextPos,s.result;if(e=St,34===t.charCodeAt(St)?(r=C,St++):(r=o,0===xt&&It(L)),r!==o){for(n=[],i=zt();i!==o;)n.push(i),i=zt();n!==o?(34===t.charCodeAt(St)?(i=C,St++):(i=o,0===xt&&It(L)),i!==o?(_t=e,e=r=I(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;return At[a]={nextPos:St,result:e},e}function Ht(){var e,r,n,i,a=49*St+17,s=At[a];if(s)return St=s.nextPos,s.result;if(e=St,39===t.charCodeAt(St)?(r=U,St++):(r=o,0===xt&&It(M)),r!==o){for(n=[],i=Xt();i!==o;)n.push(i),i=Xt();n!==o?(39===t.charCodeAt(St)?(i=U,St++):(i=o,0===xt&&It(M)),i!==o?(_t=e,e=r=I(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;return At[a]={nextPos:St,result:e},e}function zt(){var e,r,n,i=49*St+18,a=At[i];return a?(St=a.nextPos,a.result):((e=fr())===o&&(e=St,r=St,xt++,34===t.charCodeAt(St)?(n=C,St++):(n=o,0===xt&&It(L)),xt--,n===o?r=f:(St=r,r=u),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&It(p)),n!==o?(_t=e,e=r=D(n)):(St=e,e=u)):(St=e,e=u)),At[i]={nextPos:St,result:e},e)}function Xt(){var e,r,n,i=49*St+19,a=At[i];return a?(St=a.nextPos,a.result):(e=St,r=St,xt++,39===t.charCodeAt(St)?(n=U,St++):(n=o,0===xt&&It(M)),xt--,n===o?r=f:(St=r,r=u),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&It(p)),n!==o?(_t=e,e=r=D(n)):(St=e,e=u)):(St=e,e=u),At[i]={nextPos:St,result:e},e)}function Gt(){var e,r,n,i=49*St+20,a=At[i];return a?(St=a.nextPos,a.result):((e=fr())===o&&(e=function(){var e,r,n,i,a=49*St+21,s=At[a];if(s)return St=s.nextPos,s.result;e=St,92===t.charCodeAt(St)?(r=V,St++):(r=o,0===xt&&It(q));if(r!==o)if(or()!==o){for(n=[],i=ir();i!==o;)n.push(i),i=ir();n!==o?(_t=e,e=r=K()):(St=e,e=u)}else St=e,e=u;else St=e,e=u;return At[a]={nextPos:St,result:e},e}(),e===o&&(e=St,r=St,xt++,t.substr(St,3)===P?(n=P,St+=3):(n=o,0===xt&&It(R)),xt--,n===o?r=f:(St=r,r=u),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&It(p)),n!==o?(_t=e,e=r=F(n)):(St=e,e=u)):(St=e,e=u))),At[i]={nextPos:St,result:e},e)}function Wt(){var e,r,n,i=49*St+22,a=At[i];return a?(St=a.nextPos,a.result):(e=St,r=St,xt++,t.substr(St,3)===B?(n=B,St+=3):(n=o,0===xt&&It(N)),xt--,n===o?r=f:(St=r,r=u),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&It(p)),n!==o?(_t=e,e=r=D(n)):(St=e,e=u)):(St=e,e=u),At[i]={nextPos:St,result:e},e)}function $t(){var e,r,n,i,a,s,c=49*St+24,l=At[c];return l?(St=l.nextPos,l.result):(e=St,43===t.charCodeAt(St)?(r=Q,St++):(r=o,0===xt&&It(Y)),r===o&&(r=j),r!==o?(n=St,(i=lr())!==o?(46===t.charCodeAt(St)?(a=_,St++):(a=o,0===xt&&It(E)),a!==o&&(s=lr())!==o?n=i=[i,a,s]:(St=n,n=u)):(St=n,n=u),n!==o?(_t=e,e=r=J(n)):(St=e,e=u)):(St=e,e=u),e===o&&(e=St,45===t.charCodeAt(St)?(r=Z,St++):(r=o,0===xt&&It(ee)),r!==o?(n=St,(i=lr())!==o?(46===t.charCodeAt(St)?(a=_,St++):(a=o,0===xt&&It(E)),a!==o&&(s=lr())!==o?n=i=[i,a,s]:(St=n,n=u)):(St=n,n=u),n!==o?(_t=e,e=r=te(n)):(St=e,e=u)):(St=e,e=u)),At[c]={nextPos:St,result:e},e)}function Qt(){var e,r,n,i,a,s=49*St+26,c=At[s];if(c)return St=c.nextPos,c.result;if(e=St,43===t.charCodeAt(St)?(r=Q,St++):(r=o,0===xt&&It(Y)),r===o&&(r=j),r!==o){if(n=[],(i=ur())!==o)for(;i!==o;)n.push(i),i=ur();else n=u;n!==o?(i=St,xt++,46===t.charCodeAt(St)?(a=_,St++):(a=o,0===xt&&It(E)),xt--,a===o?i=f:(St=i,i=u),i!==o?(_t=e,e=r=J(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;if(e===o)if(e=St,45===t.charCodeAt(St)?(r=Z,St++):(r=o,0===xt&&It(ee)),r!==o){if(n=[],(i=ur())!==o)for(;i!==o;)n.push(i),i=ur();else n=u;n!==o?(i=St,xt++,46===t.charCodeAt(St)?(a=_,St++):(a=o,0===xt&&It(E)),xt--,a===o?i=f:(St=i,i=u),i!==o?(_t=e,e=r=te(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;return At[s]={nextPos:St,result:e},e}function Yt(){var e,t,r,n,i,a=49*St+29,s=At[a];if(s)return St=s.nextPos,s.result;for(e=St,t=[],r=Zt();r!==o;)t.push(r),r=Zt();if(t!==o)if((r=qt())!==o){for(n=[],i=Zt();i!==o;)n.push(i),i=Zt();n!==o?(_t=e,e=t=de(r)):(St=e,e=u)}else St=e,e=u;else St=e,e=u;return At[a]={nextPos:St,result:e},e}function Jt(){var e,r,n,i,a,s,c,l=49*St+30,f=At[l];if(f)return St=f.nextPos,f.result;for(e=St,r=[],n=Zt();n!==o;)r.push(n),n=Zt();if(r!==o)if((n=qt())!==o){for(i=[],a=Zt();a!==o;)i.push(a),a=Zt();if(i!==o)if(44===t.charCodeAt(St)?(a=he,St++):(a=o,0===xt&&It(ye)),a!==o){for(s=[],c=Zt();c!==o;)s.push(c),c=Zt();s!==o?(_t=e,e=r=de(n)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u;return At[l]={nextPos:St,result:e},e}function Zt(){var e,t=49*St+31,r=At[t];return r?(St=r.nextPos,r.result):((e=nr())===o&&(e=or())===o&&(e=Nt()),At[t]={nextPos:St,result:e},e)}function er(){var e,r,n,i,a,s,c,l,f,p,d,h=49*St+33,y=At[h];if(y)return St=y.nextPos,y.result;for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Ft())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(61===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&It(T)),a!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();if(s!==o)if((c=qt())!==o){for(l=[],f=nr();f!==o;)l.push(f),f=nr();if(l!==o)if(44===t.charCodeAt(St)?(f=he,St++):(f=o,0===xt&&It(ye)),f!==o){for(p=[],d=nr();d!==o;)p.push(d),d=nr();p!==o?(_t=e,e=r=Se(n,c)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u;if(e===o){for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Ft())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(61===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&It(T)),a!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();s!==o&&(c=qt())!==o?(_t=e,e=r=Se(n,c)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u}return At[h]={nextPos:St,result:e},e}function tr(){var e,r,n,i=49*St+34,a=At[i];return a?(St=a.nextPos,a.result):(e=St,46===t.charCodeAt(St)?(r=_,St++):(r=o,0===xt&&It(E)),r!==o&&(n=lr())!==o?(_t=e,e=r=_e(n)):(St=e,e=u),At[i]={nextPos:St,result:e},e)}function rr(){var e,r,n,i,a,s,c,l,f,p,d,h,y=49*St+35,m=At[y];return m?(St=m.nextPos,m.result):(e=St,r=St,(n=ur())!==o&&(i=ur())!==o&&(a=ur())!==o&&(s=ur())!==o?(45===t.charCodeAt(St)?(c=Z,St++):(c=o,0===xt&&It(ee)),c!==o&&(l=ur())!==o&&(f=ur())!==o?(45===t.charCodeAt(St)?(p=Z,St++):(p=o,0===xt&&It(ee)),p!==o&&(d=ur())!==o&&(h=ur())!==o?r=n=[n,i,a,s,c,l,f,p,d,h]:(St=r,r=u)):(St=r,r=u)):(St=r,r=u),r!==o&&(_t=e,r=Ee(r)),e=r,At[y]={nextPos:St,result:e},e)}function nr(){var e,r=49*St+39,n=At[r];return n?(St=n.nextPos,n.result):(Ce.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&It(Le)),At[r]={nextPos:St,result:e},e)}function or(){var e,r,n,i=49*St+40,a=At[i];return a?(St=a.nextPos,a.result):(10===t.charCodeAt(St)?(e=Be,St++):(e=o,0===xt&&It(Ne)),e===o&&(e=St,13===t.charCodeAt(St)?(r=Ue,St++):(r=o,0===xt&&It(Me)),r!==o?(10===t.charCodeAt(St)?(n=Be,St++):(n=o,0===xt&&It(Ne)),n!==o?e=r=[r,n]:(St=e,e=u)):(St=e,e=u)),At[i]={nextPos:St,result:e},e)}function ir(){var e,t=49*St+41,r=At[t];return r?(St=r.nextPos,r.result):((e=or())===o&&(e=nr()),At[t]={nextPos:St,result:e},e)}function ar(){var e,r,n=49*St+42,i=At[n];return i?(St=i.nextPos,i.result):(e=St,xt++,t.length>St?(r=t.charAt(St),St++):(r=o,0===xt&&It(p)),xt--,r===o?e=f:(St=e,e=u),At[n]={nextPos:St,result:e},e)}function sr(){var e,r=49*St+43,n=At[r];return n?(St=n.nextPos,n.result):(De.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&It(Fe)),At[r]={nextPos:St,result:e},e)}function ur(){var e,r,n=49*St+44,i=At[n];return i?(St=i.nextPos,i.result):(Ve.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&It(qe)),e===o&&(e=St,95===t.charCodeAt(St)?(r=Ke,St++):(r=o,0===xt&&It(He)),r!==o&&(_t=e,r=ze()),e=r),At[n]={nextPos:St,result:e},e)}function cr(){var e,r=49*St+45,n=At[r];return n?(St=n.nextPos,n.result):(Xe.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&It(Ge)),At[r]={nextPos:St,result:e},e)}function lr(){var e,t,r,n=49*St+46,i=At[n];if(i)return St=i.nextPos,i.result;if(e=St,t=[],(r=ur())!==o)for(;r!==o;)t.push(r),r=ur();else t=u;return t!==o&&(_t=e,t=We(t)),e=t,At[n]={nextPos:St,result:e},e}function fr(){var e,r,n=49*St+47,i=At[n];return i?(St=i.nextPos,i.result):(e=St,t.substr(St,2)===$e?(r=$e,St+=2):(r=o,0===xt&&It(Qe)),r!==o&&(_t=e,r=Ye()),(e=r)===o&&(e=St,t.substr(St,2)===Je?(r=Je,St+=2):(r=o,0===xt&&It(Ze)),r!==o&&(_t=e,r=et()),(e=r)===o&&(e=St,t.substr(St,2)===tt?(r=tt,St+=2):(r=o,0===xt&&It(rt)),r!==o&&(_t=e,r=nt()),(e=r)===o&&(e=St,t.substr(St,2)===ot?(r=ot,St+=2):(r=o,0===xt&&It(it)),r!==o&&(_t=e,r=at()),(e=r)===o&&(e=St,t.substr(St,2)===st?(r=st,St+=2):(r=o,0===xt&&It(ut)),r!==o&&(_t=e,r=ct()),(e=r)===o&&(e=St,t.substr(St,2)===lt?(r=lt,St+=2):(r=o,0===xt&&It(ft)),r!==o&&(_t=e,r=pt()),(e=r)===o&&(e=St,t.substr(St,2)===dt?(r=dt,St+=2):(r=o,0===xt&&It(ht)),r!==o&&(_t=e,r=yt()),(e=r)===o&&(e=function(){var e,r,n,i,a,s,c,l,f,p,d,h=49*St+48,y=At[h];if(y)return St=y.nextPos,y.result;e=St,t.substr(St,2)===mt?(r=mt,St+=2):(r=o,0===xt&&It(vt));r!==o?(n=St,(i=sr())!==o&&(a=sr())!==o&&(s=sr())!==o&&(c=sr())!==o&&(l=sr())!==o&&(f=sr())!==o&&(p=sr())!==o&&(d=sr())!==o?n=i=[i,a,s,c,l,f,p,d]:(St=n,n=u),n!==o?(_t=e,e=r=gt(n)):(St=e,e=u)):(St=e,e=u);e===o&&(e=St,t.substr(St,2)===bt?(r=bt,St+=2):(r=o,0===xt&&It(wt)),r!==o?(n=St,(i=sr())!==o&&(a=sr())!==o&&(s=sr())!==o&&(c=sr())!==o?n=i=[i,a,s,c]:(St=n,n=u),n!==o?(_t=e,e=r=gt(n)):(St=e,e=u)):(St=e,e=u));return At[h]={nextPos:St,result:e},e}()))))))),At[n]={nextPos:St,result:e},e)}var pr=[];function dr(e){pr.push(e)}function hr(e,t,r,n,o){var i={type:e,value:t,line:r(),column:n()};return o&&(i.key=o),i}if((r=a())!==o&&St===t.length)return r;throw r!==o&&St1);s++)r.splice(0,1);n[a]=r.join("")}var u=-1,c=0,l=0,f=-1,p=!1;for(a=0;ac&&(u=f,c=l)):"0"===n[a]&&(p=!0,f=a,l=1);l>c&&(u=f,c=l),c>1&&n.splice(u,c,""),o=n.length;var d="";for(""===n[0]&&(d=":"),a=0;a=e.length-1)return!1;var n=e.lastIndexOf(".",t-1);if(n<=0||n>=t-1)return!1;var o=r.list[e.slice(t+1)];return!!o&&o.indexOf(" "+e.slice(n+1,t)+" ")>=0},is:function(e){var t=e.lastIndexOf(".");if(t<=0||t>=e.length-1)return!1;if(e.lastIndexOf(".",t-1)>=0)return!1;var n=r.list[e.slice(t+1)];return!!n&&n.indexOf(" "+e.slice(0,t)+" ")>=0},get:function(e){var t=e.lastIndexOf(".");if(t<=0||t>=e.length-1)return null;var n=e.lastIndexOf(".",t-1);if(n<=0||n>=t-1)return null;var o=r.list[e.slice(t+1)];return o?o.indexOf(" "+e.slice(n+1,t)+" ")<0?null:e.slice(n+1):null},noConflict:function(){return e.SecondLevelDomains===this&&(e.SecondLevelDomains=t),this}};return r}))},4193:function(e,t,r){var n,o,i;!function(a,s){"use strict";e.exports?e.exports=s(r(9340),r(1430),r(4704)):(o=[r(9340),r(1430),r(4704)],void 0===(i="function"==typeof(n=s)?n.apply(t,o):n)||(e.exports=i))}(0,(function(e,t,r,n){"use strict";var o=n&&n.URI;function i(e,t){var r=arguments.length>=1;if(!(this instanceof i))return r?arguments.length>=2?new i(e,t):new i(e):new i;if(void 0===e){if(r)throw new TypeError("undefined is not a valid argument for URI");e="undefined"!=typeof location?location.href+"":""}if(null===e&&r)throw new TypeError("null is not a valid argument for URI");return this.href(e),void 0!==t?this.absoluteTo(t):this}i.version="1.19.11";var a=i.prototype,s=Object.prototype.hasOwnProperty;function u(e){return e.replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")}function c(e){return void 0===e?"Undefined":String(Object.prototype.toString.call(e)).slice(8,-1)}function l(e){return"Array"===c(e)}function f(e,t){var r,n,o={};if("RegExp"===c(t))o=null;else if(l(t))for(r=0,n=t.length;r]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?\xab\xbb\u201c\u201d\u2018\u2019]))/gi,i.findUri={start:/\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,end:/[\s\r\n]|$/,trim:/[`!()\[\]{};:'".,<>?\xab\xbb\u201c\u201d\u201e\u2018\u2019]+$/,parens:/(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g},i.leading_whitespace_expression=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,i.ascii_tab_whitespace=/[\u0009\u000A\u000D]+/g,i.defaultPorts={http:"80",https:"443",ftp:"21",gopher:"70",ws:"80",wss:"443"},i.hostProtocols=["http","https"],i.invalid_hostname_characters=/[^a-zA-Z0-9\.\-:_]/,i.domAttributes={a:"href",blockquote:"cite",link:"href",base:"href",script:"src",form:"action",img:"src",area:"href",iframe:"src",embed:"src",source:"src",track:"src",input:"src",audio:"src",video:"src"},i.getDomAttribute=function(e){if(e&&e.nodeName){var t=e.nodeName.toLowerCase();if("input"!==t||"image"===e.type)return i.domAttributes[t]}},i.encode=m,i.decode=decodeURIComponent,i.iso8859=function(){i.encode=escape,i.decode=unescape},i.unicode=function(){i.encode=m,i.decode=decodeURIComponent},i.characters={pathname:{encode:{expression:/%(24|26|2B|2C|3B|3D|3A|40)/gi,map:{"%24":"$","%26":"&","%2B":"+","%2C":",","%3B":";","%3D":"=","%3A":":","%40":"@"}},decode:{expression:/[\/\?#]/g,map:{"/":"%2F","?":"%3F","#":"%23"}}},reserved:{encode:{expression:/%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/gi,map:{"%3A":":","%2F":"/","%3F":"?","%23":"#","%5B":"[","%5D":"]","%40":"@","%21":"!","%24":"$","%26":"&","%27":"'","%28":"(","%29":")","%2A":"*","%2B":"+","%2C":",","%3B":";","%3D":"="}}},urnpath:{encode:{expression:/%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/gi,map:{"%21":"!","%24":"$","%27":"'","%28":"(","%29":")","%2A":"*","%2B":"+","%2C":",","%3B":";","%3D":"=","%40":"@"}},decode:{expression:/[\/\?#:]/g,map:{"/":"%2F","?":"%3F","#":"%23",":":"%3A"}}}},i.encodeQuery=function(e,t){var r=i.encode(e+"");return void 0===t&&(t=i.escapeQuerySpace),t?r.replace(/%20/g,"+"):r},i.decodeQuery=function(e,t){e+="",void 0===t&&(t=i.escapeQuerySpace);try{return i.decode(t?e.replace(/\+/g,"%20"):e)}catch(t){return e}};var v,g={encode:"encode",decode:"decode"},b=function(e,t){return function(r){try{return i[t](r+"").replace(i.characters[e][t].expression,(function(r){return i.characters[e][t].map[r]}))}catch(e){return r}}};for(v in g)i[v+"PathSegment"]=b("pathname",g[v]),i[v+"UrnPathSegment"]=b("urnpath",g[v]);var w=function(e,t,r){return function(n){var o;o=r?function(e){return i[t](i[r](e))}:i[t];for(var a=(n+"").split(e),s=0,u=a.length;s-1&&(t.fragment=e.substring(r+1)||null,e=e.substring(0,r)),(r=e.indexOf("?"))>-1&&(t.query=e.substring(r+1)||null,e=e.substring(0,r)),"//"===(e=(e=e.replace(/^(https?|ftp|wss?)?:+[/\\]*/i,"$1://")).replace(/^[/\\]{2,}/i,"//")).substring(0,2)?(t.protocol=null,e=e.substring(2),e=i.parseAuthority(e,t)):(r=e.indexOf(":"))>-1&&(t.protocol=e.substring(0,r)||null,t.protocol&&!t.protocol.match(i.protocol_expression)?t.protocol=void 0:"//"===e.substring(r+1,r+3).replace(/\\/g,"/")?(e=e.substring(r+3),e=i.parseAuthority(e,t)):(e=e.substring(r+1),t.urn=!0)),t.path=e,t},i.parseHost=function(e,t){e||(e="");var r,n,o=(e=e.replace(/\\/g,"/")).indexOf("/");if(-1===o&&(o=e.length),"["===e.charAt(0))r=e.indexOf("]"),t.hostname=e.substring(1,r)||null,t.port=e.substring(r+2,o)||null,"/"===t.port&&(t.port=null);else{var a=e.indexOf(":"),s=e.indexOf("/"),u=e.indexOf(":",a+1);-1!==u&&(-1===s||u-1?o:e.length-1);return a>-1&&(-1===o||a-1?d.slice(0,h)+d.slice(h).replace(a,""):d.replace(a,"")).length<=c[0].length||r.ignore&&r.ignore.test(d))){var v=t(d,l,p=l+d.length,e);void 0!==v?(v=String(v),e=e.slice(0,l)+v+e.slice(p),n.lastIndex=l+v.length):n.lastIndex=p}}return n.lastIndex=0,e},i.ensureValidHostname=function(t,r){var n=!!t,o=!1;if(!!r&&(o=p(i.hostProtocols,r)),o&&!n)throw new TypeError("Hostname cannot be empty, if protocol is "+r);if(t&&t.match(i.invalid_hostname_characters)){if(!e)throw new TypeError('Hostname "'+t+'" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');if(e.toASCII(t).match(i.invalid_hostname_characters))throw new TypeError('Hostname "'+t+'" contains characters other than [A-Z0-9.-:_]')}},i.ensureValidPort=function(e){if(e){var t=Number(e);if(!(/^[0-9]+$/.test(t)&&t>0&&t<65536))throw new TypeError('Port "'+e+'" is not a valid port')}},i.noConflict=function(e){if(e){var t={URI:this.noConflict()};return n.URITemplate&&"function"==typeof n.URITemplate.noConflict&&(t.URITemplate=n.URITemplate.noConflict()),n.IPv6&&"function"==typeof n.IPv6.noConflict&&(t.IPv6=n.IPv6.noConflict()),n.SecondLevelDomains&&"function"==typeof n.SecondLevelDomains.noConflict&&(t.SecondLevelDomains=n.SecondLevelDomains.noConflict()),t}return n.URI===this&&(n.URI=o),this},a.build=function(e){return!0===e?this._deferred_build=!0:(void 0===e||this._deferred_build)&&(this._string=i.build(this._parts),this._deferred_build=!1),this},a.clone=function(){return new i(this)},a.valueOf=a.toString=function(){return this.build(!1)._string},a.protocol=S("protocol"),a.username=S("username"),a.password=S("password"),a.hostname=S("hostname"),a.port=S("port"),a.query=_("query","?"),a.fragment=_("fragment","#"),a.search=function(e,t){var r=this.query(e,t);return"string"==typeof r&&r.length?"?"+r:r},a.hash=function(e,t){var r=this.fragment(e,t);return"string"==typeof r&&r.length?"#"+r:r},a.pathname=function(e,t){if(void 0===e||!0===e){var r=this._parts.path||(this._parts.hostname?"/":"");return e?(this._parts.urn?i.decodeUrnPath:i.decodePath)(r):r}return this._parts.urn?this._parts.path=e?i.recodeUrnPath(e):"":this._parts.path=e?i.recodePath(e):"/",this.build(!t),this},a.path=a.pathname,a.href=function(e,t){var r;if(void 0===e)return this.toString();this._string="",this._parts=i._parts();var n=e instanceof i,o="object"==typeof e&&(e.hostname||e.path||e.pathname);e.nodeName&&(e=e[i.getDomAttribute(e)]||"",o=!1);if(!n&&o&&void 0!==e.pathname&&(e=e.toString()),"string"==typeof e||e instanceof String)this._parts=i.parse(String(e),this._parts);else{if(!n&&!o)throw new TypeError("invalid input");var a=n?e._parts:e;for(r in a)"query"!==r&&s.call(this._parts,r)&&(this._parts[r]=a[r]);a.query&&this.query(a.query,!1)}return this.build(!t),this},a.is=function(e){var t=!1,n=!1,o=!1,a=!1,s=!1,u=!1,c=!1,l=!this._parts.urn;switch(this._parts.hostname&&(l=!1,n=i.ip4_expression.test(this._parts.hostname),o=i.ip6_expression.test(this._parts.hostname),s=(a=!(t=n||o))&&r&&r.has(this._parts.hostname),u=a&&i.idn_expression.test(this._parts.hostname),c=a&&i.punycode_expression.test(this._parts.hostname)),e.toLowerCase()){case"relative":return l;case"absolute":return!l;case"domain":case"name":return a;case"sld":return s;case"ip":return t;case"ip4":case"ipv4":case"inet4":return n;case"ip6":case"ipv6":case"inet6":return o;case"idn":return u;case"url":return!this._parts.urn;case"urn":return!!this._parts.urn;case"punycode":return c}return null};var E=a.protocol,k=a.port,T=a.hostname;a.protocol=function(e,t){if(e&&!(e=e.replace(/:(\/\/)?$/,"")).match(i.protocol_expression))throw new TypeError('Protocol "'+e+"\" contains characters other than [A-Z0-9.+-] or doesn't start with [A-Z]");return E.call(this,e,t)},a.scheme=a.protocol,a.port=function(e,t){return this._parts.urn?void 0===e?"":this:(void 0!==e&&(0===e&&(e=null),e&&(":"===(e+="").charAt(0)&&(e=e.substring(1)),i.ensureValidPort(e))),k.call(this,e,t))},a.hostname=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0!==e){var r={preventInvalidHostname:this._parts.preventInvalidHostname};if("/"!==i.parseHost(e,r))throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');e=r.hostname,this._parts.preventInvalidHostname&&i.ensureValidHostname(e,this._parts.protocol)}return T.call(this,e,t)},a.origin=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e){var r=this.protocol();return this.authority()?(r?r+"://":"")+this.authority():""}var n=i(e);return this.protocol(n.protocol()).authority(n.authority()).build(!t),this},a.host=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e)return this._parts.hostname?i.buildHost(this._parts):"";if("/"!==i.parseHost(e,this._parts))throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');return this.build(!t),this},a.authority=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e)return this._parts.hostname?i.buildAuthority(this._parts):"";if("/"!==i.parseAuthority(e,this._parts))throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');return this.build(!t),this},a.userinfo=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e){var r=i.buildUserinfo(this._parts);return r?r.substring(0,r.length-1):r}return"@"!==e[e.length-1]&&(e+="@"),i.parseUserinfo(e,this._parts),this.build(!t),this},a.resource=function(e,t){var r;return void 0===e?this.path()+this.search()+this.hash():(r=i.parse(e),this._parts.path=r.path,this._parts.query=r.query,this._parts.fragment=r.fragment,this.build(!t),this)},a.subdomain=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e){if(!this._parts.hostname||this.is("IP"))return"";var r=this._parts.hostname.length-this.domain().length-1;return this._parts.hostname.substring(0,r)||""}var n=this._parts.hostname.length-this.domain().length,o=this._parts.hostname.substring(0,n),a=new RegExp("^"+u(o));if(e&&"."!==e.charAt(e.length-1)&&(e+="."),-1!==e.indexOf(":"))throw new TypeError("Domains cannot contain colons");return e&&i.ensureValidHostname(e,this._parts.protocol),this._parts.hostname=this._parts.hostname.replace(a,e),this.build(!t),this},a.domain=function(e,t){if(this._parts.urn)return void 0===e?"":this;if("boolean"==typeof e&&(t=e,e=void 0),void 0===e){if(!this._parts.hostname||this.is("IP"))return"";var r=this._parts.hostname.match(/\./g);if(r&&r.length<2)return this._parts.hostname;var n=this._parts.hostname.length-this.tld(t).length-1;return n=this._parts.hostname.lastIndexOf(".",n-1)+1,this._parts.hostname.substring(n)||""}if(!e)throw new TypeError("cannot set domain empty");if(-1!==e.indexOf(":"))throw new TypeError("Domains cannot contain colons");if(i.ensureValidHostname(e,this._parts.protocol),!this._parts.hostname||this.is("IP"))this._parts.hostname=e;else{var o=new RegExp(u(this.domain())+"$");this._parts.hostname=this._parts.hostname.replace(o,e)}return this.build(!t),this},a.tld=function(e,t){if(this._parts.urn)return void 0===e?"":this;if("boolean"==typeof e&&(t=e,e=void 0),void 0===e){if(!this._parts.hostname||this.is("IP"))return"";var n=this._parts.hostname.lastIndexOf("."),o=this._parts.hostname.substring(n+1);return!0!==t&&r&&r.list[o.toLowerCase()]&&r.get(this._parts.hostname)||o}var i;if(!e)throw new TypeError("cannot set TLD empty");if(e.match(/[^a-zA-Z0-9-]/)){if(!r||!r.is(e))throw new TypeError('TLD "'+e+'" contains characters other than [A-Z0-9]');i=new RegExp(u(this.tld())+"$"),this._parts.hostname=this._parts.hostname.replace(i,e)}else{if(!this._parts.hostname||this.is("IP"))throw new ReferenceError("cannot set TLD on non-domain host");i=new RegExp(u(this.tld())+"$"),this._parts.hostname=this._parts.hostname.replace(i,e)}return this.build(!t),this},a.directory=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e||!0===e){if(!this._parts.path&&!this._parts.hostname)return"";if("/"===this._parts.path)return"/";var r=this._parts.path.length-this.filename().length-1,n=this._parts.path.substring(0,r)||(this._parts.hostname?"/":"");return e?i.decodePath(n):n}var o=this._parts.path.length-this.filename().length,a=this._parts.path.substring(0,o),s=new RegExp("^"+u(a));return this.is("relative")||(e||(e="/"),"/"!==e.charAt(0)&&(e="/"+e)),e&&"/"!==e.charAt(e.length-1)&&(e+="/"),e=i.recodePath(e),this._parts.path=this._parts.path.replace(s,e),this.build(!t),this},a.filename=function(e,t){if(this._parts.urn)return void 0===e?"":this;if("string"!=typeof e){if(!this._parts.path||"/"===this._parts.path)return"";var r=this._parts.path.lastIndexOf("/"),n=this._parts.path.substring(r+1);return e?i.decodePathSegment(n):n}var o=!1;"/"===e.charAt(0)&&(e=e.substring(1)),e.match(/\.?\//)&&(o=!0);var a=new RegExp(u(this.filename())+"$");return e=i.recodePath(e),this._parts.path=this._parts.path.replace(a,e),o?this.normalizePath(t):this.build(!t),this},a.suffix=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e||!0===e){if(!this._parts.path||"/"===this._parts.path)return"";var r,n,o=this.filename(),a=o.lastIndexOf(".");return-1===a?"":(r=o.substring(a+1),n=/^[a-z0-9%]+$/i.test(r)?r:"",e?i.decodePathSegment(n):n)}"."===e.charAt(0)&&(e=e.substring(1));var s,c=this.suffix();if(c)s=e?new RegExp(u(c)+"$"):new RegExp(u("."+c)+"$");else{if(!e)return this;this._parts.path+="."+i.recodePath(e)}return s&&(e=i.recodePath(e),this._parts.path=this._parts.path.replace(s,e)),this.build(!t),this},a.segment=function(e,t,r){var n=this._parts.urn?":":"/",o=this.path(),i="/"===o.substring(0,1),a=o.split(n);if(void 0!==e&&"number"!=typeof e&&(r=t,t=e,e=void 0),void 0!==e&&"number"!=typeof e)throw new Error('Bad segment "'+e+'", must be 0-based integer');if(i&&a.shift(),e<0&&(e=Math.max(a.length+e,0)),void 0===t)return void 0===e?a:a[e];if(null===e||void 0===a[e])if(l(t)){a=[];for(var s=0,u=t.length;s{}"`^| \\]/,o.expand=function(e,t,r){var n,i,a,u=s[e.operator],c=u.named?"Named":"Unnamed",l=e.variables,f=[];for(a=0;i=l[a];a++){if(0===(n=t.get(i.name)).type&&r&&r.strict)throw new Error('Missing expansion value for variable "'+i.name+'"');if(n.val.length){if(n.type>1&&i.maxlength)throw new Error('Invalid expression: Prefix modifier not applicable to variable "'+i.name+'"');f.push(o["expand"+c](n,u,i.explode,i.explode&&u.separator||",",i.maxlength,i.name))}else n.type&&f.push("")}return f.length?u.prefix+f.join(u.separator):""},o.expandNamed=function(t,r,n,o,i,a){var s,u,c,l="",f=r.encode,p=r.empty_name_separator,d=!t[f].length,h=2===t.type?"":e[f](a);for(u=0,c=t.val.length;u= 0x80 (not a basic code point)","invalid-input":"Invalid input"},p=Math.floor,d=String.fromCharCode;function h(e){throw new RangeError(f[e])}function y(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function m(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+y((e=e.replace(l,".")).split("."),t).join(".")}function v(e){for(var t,r,n=[],o=0,i=e.length;o=55296&&t<=56319&&o65535&&(t+=d((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=d(e)})).join("")}function b(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function w(e,t,r){var n=0;for(e=r?p(e/700):e>>1,e+=p(e/t);e>455;n+=s)e=p(e/35);return p(n+36*e/(e+38))}function S(e){var t,r,n,o,i,u,c,l,f,d,y,m=[],v=e.length,b=0,S=128,_=72;for((r=e.lastIndexOf("-"))<0&&(r=0),n=0;n=128&&h("not-basic"),m.push(e.charCodeAt(n));for(o=r>0?r+1:0;o=v&&h("invalid-input"),((l=(y=e.charCodeAt(o++))-48<10?y-22:y-65<26?y-65:y-97<26?y-97:s)>=s||l>p((a-b)/u))&&h("overflow"),b+=l*u,!(l<(f=c<=_?1:c>=_+26?26:c-_));c+=s)u>p(a/(d=s-f))&&h("overflow"),u*=d;_=w(b-i,t=m.length+1,0==i),p(b/t)>a-S&&h("overflow"),S+=p(b/t),b%=t,m.splice(b++,0,S)}return g(m)}function _(e){var t,r,n,o,i,u,c,l,f,y,m,g,S,_,E,k=[];for(g=(e=v(e)).length,t=128,r=0,i=72,u=0;u=t&&mp((a-r)/(S=n+1))&&h("overflow"),r+=(c-t)*S,t=c,u=0;ua&&h("overflow"),m==t){for(l=r,f=s;!(l<(y=f<=i?1:f>=i+26?26:f-i));f+=s)E=l-y,_=s-y,k.push(d(b(y+E%_,0))),l=p(E/_);k.push(d(b(l,0))),i=w(r,S,n==o),r=0,++n}++r,++t}return k.join("")}i={version:"1.3.2",ucs2:{decode:v,encode:g},decode:S,encode:_,toASCII:function(e){return m(e,(function(e){return c.test(e)?"xn--"+_(e):e}))},toUnicode:function(e){return m(e,(function(e){return u.test(e)?S(e.slice(4).toLowerCase()):e}))}},void 0===(n=function(){return i}.call(t,r,t,e))||(e.exports=n)}()},1270:function(e,t,r){var n;e=r.nmd(e),function(){t&&t.nodeType,e&&e.nodeType;var o="object"==typeof r.g&&r.g;o.global!==o&&o.window!==o&&o.self;var i,a=2147483647,s=36,u=/^xn--/,c=/[^\x20-\x7E]/,l=/[\x2E\u3002\uFF0E\uFF61]/g,f={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},p=Math.floor,d=String.fromCharCode;function h(e){throw new RangeError(f[e])}function y(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function m(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+y((e=e.replace(l,".")).split("."),t).join(".")}function v(e){for(var t,r,n=[],o=0,i=e.length;o=55296&&t<=56319&&o65535&&(t+=d((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=d(e)})).join("")}function b(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function w(e,t,r){var n=0;for(e=r?p(e/700):e>>1,e+=p(e/t);e>455;n+=s)e=p(e/35);return p(n+36*e/(e+38))}function S(e){var t,r,n,o,i,u,c,l,f,d,y,m=[],v=e.length,b=0,S=128,_=72;for((r=e.lastIndexOf("-"))<0&&(r=0),n=0;n=128&&h("not-basic"),m.push(e.charCodeAt(n));for(o=r>0?r+1:0;o=v&&h("invalid-input"),((l=(y=e.charCodeAt(o++))-48<10?y-22:y-65<26?y-65:y-97<26?y-97:s)>=s||l>p((a-b)/u))&&h("overflow"),b+=l*u,!(l<(f=c<=_?1:c>=_+26?26:c-_));c+=s)u>p(a/(d=s-f))&&h("overflow"),u*=d;_=w(b-i,t=m.length+1,0==i),p(b/t)>a-S&&h("overflow"),S+=p(b/t),b%=t,m.splice(b++,0,S)}return g(m)}function _(e){var t,r,n,o,i,u,c,l,f,y,m,g,S,_,E,k=[];for(g=(e=v(e)).length,t=128,r=0,i=72,u=0;u=t&&mp((a-r)/(S=n+1))&&h("overflow"),r+=(c-t)*S,t=c,u=0;ua&&h("overflow"),m==t){for(l=r,f=s;!(l<(y=f<=i?1:f>=i+26?26:f-i));f+=s)E=l-y,_=s-y,k.push(d(b(y+E%_,0))),l=p(E/_);k.push(d(b(l,0))),i=w(r,S,n==o),r=0,++n}++r,++t}return k.join("")}i={version:"1.4.1",ucs2:{decode:v,encode:g},decode:S,encode:_,toASCII:function(e){return m(e,(function(e){return c.test(e)?"xn--"+_(e):e}))},toUnicode:function(e){return m(e,(function(e){return u.test(e)?S(e.slice(4).toLowerCase()):e}))}},void 0===(n=function(){return i}.call(t,r,t,e))||(e.exports=n)}()},8835:(e,t,r)=>{"use strict";var n=r(1270);function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var i=/^([a-z0-9.+-]+:)/i,a=/:[0-9]*$/,s=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,u=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),c=["'"].concat(u),l=["%","/","?",";","#"].concat(c),f=["/","?","#"],p=/^[+a-z0-9A-Z_-]{0,63}$/,d=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,h={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},m={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},v=r(5373);function g(e,t,r){if(e&&"object"==typeof e&&e instanceof o)return e;var n=new o;return n.parse(e,t,r),n}o.prototype.parse=function(e,t,r){if("string"!=typeof e)throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o=e.indexOf("?"),a=-1!==o&&o127?I+="x":I+=j[C];if(!I.match(p)){var B=P.slice(0,O),N=P.slice(O+1),U=j.match(d);U&&(B.push(U[1]),N.unshift(U[2])),N.length&&(g="/"+N.join(".")+g),this.hostname=B.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),A||(this.hostname=n.toASCII(this.hostname));var M=this.port?":"+this.port:"",D=this.hostname||"";this.host=D+M,this.href+=this.host,A&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==g[0]&&(g="/"+g))}if(!h[S])for(O=0,R=c.length;O0)&&r.host.split("@"))&&(r.auth=A.shift(),r.hostname=A.shift(),r.host=r.hostname);return r.search=e.search,r.query=e.query,null===r.pathname&&null===r.search||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!_.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var k=_.slice(-1)[0],T=(r.host||e.host||_.length>1)&&("."===k||".."===k)||""===k,O=0,x=_.length;x>=0;x--)"."===(k=_[x])?_.splice(x,1):".."===k?(_.splice(x,1),O++):O&&(_.splice(x,1),O--);if(!w&&!S)for(;O--;O)_.unshift("..");!w||""===_[0]||_[0]&&"/"===_[0].charAt(0)||_.unshift(""),T&&"/"!==_.join("/").substr(-1)&&_.push("");var A,P=""===_[0]||_[0]&&"/"===_[0].charAt(0);E&&(r.hostname=P?"":_.length?_.shift():"",r.host=r.hostname,(A=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=A.shift(),r.hostname=A.shift(),r.host=r.hostname));return(w=w||r.host&&_.length)&&!P&&_.unshift(""),_.length>0?r.pathname=_.join("/"):(r.pathname=null,r.path=null),null===r.pathname&&null===r.search||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=e.auth||r.auth,r.slashes=r.slashes||e.slashes,r.href=r.format(),r},o.prototype.parseHost=function(){var e=this.host,t=a.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)},t.parse=g,t.resolve=function(e,t){return g(e,!1,!0).resolve(t)},t.resolveObject=function(e,t){return e?g(e,!1,!0).resolveObject(t):t},t.format=function(e){return"string"==typeof e&&(e=g(e)),e instanceof o?e.format():o.prototype.format.call(e)},t.Url=o},4643:(e,t,r)=>{function n(e){try{if(!r.g.localStorage)return!1}catch(e){return!1}var t=r.g.localStorage[e];return null!=t&&"true"===String(t).toLowerCase()}e.exports=function(e,t){if(n("noDeprecation"))return e;var r=!1;return function(){if(!r){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}}},1135:e=>{e.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},9032:(e,t,r)=>{"use strict";var n=r(7244),o=r(8184),i=r(5767),a=r(5680);function s(e){return e.call.bind(e)}var u="undefined"!=typeof BigInt,c="undefined"!=typeof Symbol,l=s(Object.prototype.toString),f=s(Number.prototype.valueOf),p=s(String.prototype.valueOf),d=s(Boolean.prototype.valueOf);if(u)var h=s(BigInt.prototype.valueOf);if(c)var y=s(Symbol.prototype.valueOf);function m(e,t){if("object"!=typeof e)return!1;try{return t(e),!0}catch(e){return!1}}function v(e){return"[object Map]"===l(e)}function g(e){return"[object Set]"===l(e)}function b(e){return"[object WeakMap]"===l(e)}function w(e){return"[object WeakSet]"===l(e)}function S(e){return"[object ArrayBuffer]"===l(e)}function _(e){return"undefined"!=typeof ArrayBuffer&&(S.working?S(e):e instanceof ArrayBuffer)}function E(e){return"[object DataView]"===l(e)}function k(e){return"undefined"!=typeof DataView&&(E.working?E(e):e instanceof DataView)}t.isArgumentsObject=n,t.isGeneratorFunction=o,t.isTypedArray=a,t.isPromise=function(e){return"undefined"!=typeof Promise&&e instanceof Promise||null!==e&&"object"==typeof e&&"function"==typeof e.then&&"function"==typeof e.catch},t.isArrayBufferView=function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):a(e)||k(e)},t.isUint8Array=function(e){return"Uint8Array"===i(e)},t.isUint8ClampedArray=function(e){return"Uint8ClampedArray"===i(e)},t.isUint16Array=function(e){return"Uint16Array"===i(e)},t.isUint32Array=function(e){return"Uint32Array"===i(e)},t.isInt8Array=function(e){return"Int8Array"===i(e)},t.isInt16Array=function(e){return"Int16Array"===i(e)},t.isInt32Array=function(e){return"Int32Array"===i(e)},t.isFloat32Array=function(e){return"Float32Array"===i(e)},t.isFloat64Array=function(e){return"Float64Array"===i(e)},t.isBigInt64Array=function(e){return"BigInt64Array"===i(e)},t.isBigUint64Array=function(e){return"BigUint64Array"===i(e)},v.working="undefined"!=typeof Map&&v(new Map),t.isMap=function(e){return"undefined"!=typeof Map&&(v.working?v(e):e instanceof Map)},g.working="undefined"!=typeof Set&&g(new Set),t.isSet=function(e){return"undefined"!=typeof Set&&(g.working?g(e):e instanceof Set)},b.working="undefined"!=typeof WeakMap&&b(new WeakMap),t.isWeakMap=function(e){return"undefined"!=typeof WeakMap&&(b.working?b(e):e instanceof WeakMap)},w.working="undefined"!=typeof WeakSet&&w(new WeakSet),t.isWeakSet=function(e){return w(e)},S.working="undefined"!=typeof ArrayBuffer&&S(new ArrayBuffer),t.isArrayBuffer=_,E.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&E(new DataView(new ArrayBuffer(1),0,1)),t.isDataView=k;var T="undefined"!=typeof SharedArrayBuffer?SharedArrayBuffer:void 0;function O(e){return"[object SharedArrayBuffer]"===l(e)}function x(e){return void 0!==T&&(void 0===O.working&&(O.working=O(new T)),O.working?O(e):e instanceof T)}function A(e){return m(e,f)}function P(e){return m(e,p)}function R(e){return m(e,d)}function j(e){return u&&m(e,h)}function I(e){return c&&m(e,y)}t.isSharedArrayBuffer=x,t.isAsyncFunction=function(e){return"[object AsyncFunction]"===l(e)},t.isMapIterator=function(e){return"[object Map Iterator]"===l(e)},t.isSetIterator=function(e){return"[object Set Iterator]"===l(e)},t.isGeneratorObject=function(e){return"[object Generator]"===l(e)},t.isWebAssemblyCompiledModule=function(e){return"[object WebAssembly.Module]"===l(e)},t.isNumberObject=A,t.isStringObject=P,t.isBooleanObject=R,t.isBigIntObject=j,t.isSymbolObject=I,t.isBoxedPrimitive=function(e){return A(e)||P(e)||R(e)||j(e)||I(e)},t.isAnyArrayBuffer=function(e){return"undefined"!=typeof Uint8Array&&(_(e)||x(e))},["isProxy","isExternal","isModuleNamespaceObject"].forEach((function(e){Object.defineProperty(t,e,{enumerable:!1,value:function(){throw new Error(e+" is not supported in userland")}})}))},537:(e,t,r)=>{var n=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),r={},n=0;n=i)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}})),s=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),y(r)?n.showHidden=r:r&&t._extend(n,r),b(n.showHidden)&&(n.showHidden=!1),b(n.depth)&&(n.depth=2),b(n.colors)&&(n.colors=!1),b(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=c),f(n,e,n.depth)}function c(e,t){var r=u.styles[t];return r?"\x1b["+u.colors[r][0]+"m"+e+"\x1b["+u.colors[r][1]+"m":e}function l(e,t){return e}function f(e,r,n){if(e.customInspect&&r&&k(r.inspect)&&r.inspect!==t.inspect&&(!r.constructor||r.constructor.prototype!==r)){var o=r.inspect(n,e);return g(o)||(o=f(e,o,n)),o}var i=function(e,t){if(b(t))return e.stylize("undefined","undefined");if(g(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(v(t))return e.stylize(""+t,"number");if(y(t))return e.stylize(""+t,"boolean");if(m(t))return e.stylize("null","null")}(e,r);if(i)return i;var a=Object.keys(r),s=function(e){var t={};return e.forEach((function(e,r){t[e]=!0})),t}(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(r)),E(r)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return p(r);if(0===a.length){if(k(r)){var u=r.name?": "+r.name:"";return e.stylize("[Function"+u+"]","special")}if(w(r))return e.stylize(RegExp.prototype.toString.call(r),"regexp");if(_(r))return e.stylize(Date.prototype.toString.call(r),"date");if(E(r))return p(r)}var c,l="",S=!1,T=["{","}"];(h(r)&&(S=!0,T=["[","]"]),k(r))&&(l=" [Function"+(r.name?": "+r.name:"")+"]");return w(r)&&(l=" "+RegExp.prototype.toString.call(r)),_(r)&&(l=" "+Date.prototype.toUTCString.call(r)),E(r)&&(l=" "+p(r)),0!==a.length||S&&0!=r.length?n<0?w(r)?e.stylize(RegExp.prototype.toString.call(r),"regexp"):e.stylize("[Object]","special"):(e.seen.push(r),c=S?function(e,t,r,n,o){for(var i=[],a=0,s=t.length;a=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1}),0);if(n>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(c,l,T)):T[0]+l+T[1]}function p(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,r,n,o,i){var a,s,u;if((u=Object.getOwnPropertyDescriptor(t,o)||{value:t[o]}).get?s=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(s=e.stylize("[Setter]","special")),A(n,o)||(a="["+o+"]"),s||(e.seen.indexOf(u.value)<0?(s=m(r)?f(e,u.value,null):f(e,u.value,r-1)).indexOf("\n")>-1&&(s=i?s.split("\n").map((function(e){return" "+e})).join("\n").slice(2):"\n"+s.split("\n").map((function(e){return" "+e})).join("\n")):s=e.stylize("[Circular]","special")),b(a)){if(i&&o.match(/^\d+$/))return s;(a=JSON.stringify(""+o)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.slice(1,-1),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function h(e){return Array.isArray(e)}function y(e){return"boolean"==typeof e}function m(e){return null===e}function v(e){return"number"==typeof e}function g(e){return"string"==typeof e}function b(e){return void 0===e}function w(e){return S(e)&&"[object RegExp]"===T(e)}function S(e){return"object"==typeof e&&null!==e}function _(e){return S(e)&&"[object Date]"===T(e)}function E(e){return S(e)&&("[object Error]"===T(e)||e instanceof Error)}function k(e){return"function"==typeof e}function T(e){return Object.prototype.toString.call(e)}function O(e){return e<10?"0"+e.toString(10):e.toString(10)}t.debuglog=function(e){if(e=e.toUpperCase(),!i[e])if(a.test(e)){var r=process.pid;i[e]=function(){var n=t.format.apply(t,arguments);console.error("%s %d: %s",e,r,n)}}else i[e]=function(){};return i[e]},t.inspect=u,u.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},u.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},t.types=r(9032),t.isArray=h,t.isBoolean=y,t.isNull=m,t.isNullOrUndefined=function(e){return null==e},t.isNumber=v,t.isString=g,t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=b,t.isRegExp=w,t.types.isRegExp=w,t.isObject=S,t.isDate=_,t.types.isDate=_,t.isError=E,t.types.isNativeError=E,t.isFunction=k,t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=r(1135);var x=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function A(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.log=function(){var e,r;console.log("%s - %s",(e=new Date,r=[O(e.getHours()),O(e.getMinutes()),O(e.getSeconds())].join(":"),[e.getDate(),x[e.getMonth()],r].join(" ")),t.format.apply(t,arguments))},t.inherits=r(6698),t._extend=function(e,t){if(!t||!S(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e};var P="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function R(e,t){if(!e){var r=new Error("Promise was rejected with a falsy value");r.reason=e,e=r}return t(e)}t.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(P&&e[P]){var t;if("function"!=typeof(t=e[P]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(t,P,{value:t,enumerable:!1,writable:!1,configurable:!0}),t}function t(){for(var t,r,n=new Promise((function(e,n){t=e,r=n})),o=[],i=0;i{"use strict";var n=r(2682),o=r(9209),i=r(487),a=r(8075),s=r(5795),u=a("Object.prototype.toString"),c=r(9092)(),l="undefined"==typeof globalThis?r.g:globalThis,f=o(),p=a("String.prototype.slice"),d=Object.getPrototypeOf,h=a("Array.prototype.indexOf",!0)||function(e,t){for(var r=0;r-1?t:"Object"===t&&function(e){var t=!1;return n(y,(function(r,n){if(!t)try{r(e),t=p(n,1)}catch(e){}})),t}(e)}return s?function(e){var t=!1;return n(y,(function(r,n){if(!t)try{"$"+r(e)===n&&(t=p(n,1))}catch(e){}})),t}(e):null}},7510:e=>{e.exports=function(){for(var e={},r=0;r{},2634:()=>{},5340:()=>{},9838:()=>{},9209:(e,t,r)=>{"use strict";var n=r(6578),o="undefined"==typeof globalThis?r.g:globalThis;e.exports=function(){for(var e=[],t=0;t{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),r(1924)})())); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-axios.min.js.LICENSE.txt b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-axios.min.js.LICENSE.txt new file mode 100644 index 000000000..35726554b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-axios.min.js.LICENSE.txt @@ -0,0 +1,71 @@ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +/*! + * URI.js - Mutating URLs + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! + * URI.js - Mutating URLs + * IPv6 Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! + * URI.js - Mutating URLs + * Second Level Domain (SLD) Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! + * URI.js - Mutating URLs + * URI Template Support - http://tools.ietf.org/html/rfc6570 + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! https://mths.be/punycode v1.4.0 by @mathias */ + +/*! https://mths.be/punycode v1.4.1 by @mathias */ + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + +/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ diff --git a/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-eventsource.js b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-eventsource.js new file mode 100644 index 000000000..4b354944b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-eventsource.js @@ -0,0 +1,50115 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define("StellarSdk", [], factory); + else if(typeof exports === 'object') + exports["StellarSdk"] = factory(); + else + root["StellarSdk"] = factory(); +})(self, () => { +return /******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 3740: +/***/ (function(module) { + +/*! For license information please see xdr.js.LICENSE.txt */ +!function(t,e){ true?module.exports=e():0}(this,(()=>(()=>{var t={616:(t,e,r)=>{"use strict";r.d(e,{A:()=>i});var n=r(287);n.hp.alloc(1).subarray(0,1)instanceof n.hp||(n.hp.prototype.subarray=function(t,e){const r=Uint8Array.prototype.subarray.call(this,t,e);return Object.setPrototypeOf(r,n.hp.prototype),r});const i=n.hp},281:(t,e,r)=>{const n=r(164);t.exports=n},164:(t,e,r)=>{"use strict";r.r(e),r.d(e,{Array:()=>F,Bool:()=>S,Double:()=>L,Enum:()=>q,Float:()=>O,Hyper:()=>U,Int:()=>v,LargeInt:()=>x,Opaque:()=>D,Option:()=>X,Quadruple:()=>N,Reference:()=>G,String:()=>M,Struct:()=>Y,Union:()=>W,UnsignedHyper:()=>T,UnsignedInt:()=>R,VarArray:()=>P,VarOpaque:()=>z,Void:()=>k,XdrReader:()=>f,XdrWriter:()=>c,config:()=>it});class n extends TypeError{constructor(t){super(`XDR Write Error: ${t}`)}}class i extends TypeError{constructor(t){super(`XDR Read Error: ${t}`)}}class o extends TypeError{constructor(t){super(`XDR Type Definition Error: ${t}`)}}class s extends o{constructor(){super("method not implemented, it should be overloaded in the descendant class.")}}var u=r(616).A;class f{constructor(t){if(!u.isBuffer(t)){if(!(t instanceof Array||Array.isArray(t)||ArrayBuffer.isView(t)))throw new i(`source invalid: ${t}`);t=u.from(t)}this._buffer=t,this._length=t.length,this._index=0}_buffer;_length;_index;get eof(){return this._index===this._length}advance(t){const e=this._index;if(this._index+=t,this._length0){for(let t=0;t0){const t=this.alloc(r);this._buffer.fill(0,t,this._index)}}writeInt32BE(t){const e=this.alloc(4);this._buffer.writeInt32BE(t,e)}writeUInt32BE(t){const e=this.alloc(4);this._buffer.writeUInt32BE(t,e)}writeBigInt64BE(t){const e=this.alloc(8);this._buffer.writeBigInt64BE(t,e)}writeBigUInt64BE(t){const e=this.alloc(8);this._buffer.writeBigUInt64BE(t,e)}writeFloatBE(t){const e=this.alloc(4);this._buffer.writeFloatBE(t,e)}writeDoubleBE(t){const e=this.alloc(8);this._buffer.writeDoubleBE(t,e)}static bufferChunkSize=h}var l=r(616).A;class p{toXDR(t="raw"){if(!this.write)return this.constructor.toXDR(this,t);const e=new c;return this.write(this,e),w(e.finalize(),t)}fromXDR(t,e="raw"){if(!this.read)return this.constructor.fromXDR(t,e);const r=new f(m(t,e)),n=this.read(r);return r.ensureInputConsumed(),n}validateXDR(t,e="raw"){try{return this.fromXDR(t,e),!0}catch(t){return!1}}static toXDR(t,e="raw"){const r=new c;return this.write(t,r),w(r.finalize(),e)}static fromXDR(t,e="raw"){const r=new f(m(t,e)),n=this.read(r);return r.ensureInputConsumed(),n}static validateXDR(t,e="raw"){try{return this.fromXDR(t,e),!0}catch(t){return!1}}}class d extends p{static read(t){throw new s}static write(t,e){throw new s}static isValid(t){return!1}}class g extends p{isValid(t){return!1}}class y extends TypeError{constructor(t){super(`Invalid format ${t}, must be one of "raw", "hex", "base64"`)}}function w(t,e){switch(e){case"raw":return t;case"hex":return t.toString("hex");case"base64":return t.toString("base64");default:throw new y(e)}}function m(t,e){switch(e){case"raw":return t;case"hex":return l.from(t,"hex");case"base64":return l.from(t,"base64");default:throw new y(e)}}function b(t,e){return null!=t&&(t instanceof e||_(t,e)&&"function"==typeof t.constructor.read&&"function"==typeof t.constructor.write&&_(t,"XdrType"))}function _(t,e){do{if(t.constructor.name===e)return!0}while(t=Object.getPrototypeOf(t));return!1}const B=2147483647,E=-2147483648;class v extends d{static read(t){return t.readInt32BE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");if((0|t)!==t)throw new n("invalid i32 value");e.writeInt32BE(t)}static isValid(t){return"number"==typeof t&&(0|t)===t&&(t>=E&&t<=B)}}function A(t,e,r){if("bigint"!=typeof t)throw new TypeError("Expected bigint 'value', got "+typeof t);const n=e/r;if(1===n)return[t];if(r<32||r>128||2!==n&&4!==n&&8!==n)throw new TypeError(`invalid bigint (${t}) and slice size (${e} -> ${r}) combination`);const i=BigInt(r),o=new Array(n);for(let e=0;e>=i;return o}function I(t,e){if(e)return[0n,(1n<=o&&i<=s)return i;throw new TypeError(`bigint values [${t}] for ${function(t,e){return`${e?"u":"i"}${t}`}(e,r)} out of range [${o}, ${s}]: ${i}`)}(t,this.size,this.unsigned)}get unsigned(){throw new s}get size(){throw new s}slice(t){return A(this._value,this.size,t)}toString(){return this._value.toString()}toJSON(){return{_value:this._value.toString()}}toBigInt(){return BigInt(this._value)}static read(t){const{size:e}=this.prototype;return 64===e?new this(t.readBigUInt64BE()):new this(...Array.from({length:e/64},(()=>t.readBigUInt64BE())).reverse())}static write(t,e){if(t instanceof this)t=t._value;else if("bigint"!=typeof t||t>this.MAX_VALUE||t>32n)|0}get size(){return 64}get unsigned(){return!1}static fromBits(t,e){return new this(t,e)}}U.defineIntBoundaries();const $=4294967295;class R extends d{static read(t){return t.readUInt32BE()}static write(t,e){if("number"!=typeof t||!(t>=0&&t<=$)||t%1!=0)throw new n("invalid u32 value");e.writeUInt32BE(t)}static isValid(t){return"number"==typeof t&&t%1==0&&(t>=0&&t<=$)}}R.MAX_VALUE=$,R.MIN_VALUE=0;class T extends x{constructor(...t){super(t)}get low(){return Number(0xffffffffn&this._value)|0}get high(){return Number(this._value>>32n)|0}get size(){return 64}get unsigned(){return!0}static fromBits(t,e){return new this(t,e)}}T.defineIntBoundaries();class O extends d{static read(t){return t.readFloatBE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");e.writeFloatBE(t)}static isValid(t){return"number"==typeof t}}class L extends d{static read(t){return t.readDoubleBE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");e.writeDoubleBE(t)}static isValid(t){return"number"==typeof t}}class N extends d{static read(){throw new o("quadruple not supported")}static write(){throw new o("quadruple not supported")}static isValid(){return!1}}class S extends d{static read(t){const e=v.read(t);switch(e){case 0:return!1;case 1:return!0;default:throw new i(`got ${e} when trying to read a bool`)}}static write(t,e){const r=t?1:0;v.write(r,e)}static isValid(t){return"boolean"==typeof t}}var V=r(616).A;class M extends g{constructor(t=R.MAX_VALUE){super(),this._maxLength=t}read(t){const e=R.read(t);if(e>this._maxLength)throw new i(`saw ${e} length String, max allowed is ${this._maxLength}`);return t.read(e)}readString(t){return this.read(t).toString("utf8")}write(t,e){const r="string"==typeof t?V.byteLength(t,"utf8"):t.length;if(r>this._maxLength)throw new n(`got ${t.length} bytes, max allowed is ${this._maxLength}`);R.write(r,e),e.write(t,r)}isValid(t){return"string"==typeof t?V.byteLength(t,"utf8")<=this._maxLength:!!(t instanceof Array||V.isBuffer(t))&&t.length<=this._maxLength}}var C=r(616).A;class D extends g{constructor(t){super(),this._length=t}read(t){return t.read(this._length)}write(t,e){const{length:r}=t;if(r!==this._length)throw new n(`got ${t.length} bytes, expected ${this._length}`);e.write(t,r)}isValid(t){return C.isBuffer(t)&&t.length===this._length}}var j=r(616).A;class z extends g{constructor(t=R.MAX_VALUE){super(),this._maxLength=t}read(t){const e=R.read(t);if(e>this._maxLength)throw new i(`saw ${e} length VarOpaque, max allowed is ${this._maxLength}`);return t.read(e)}write(t,e){const{length:r}=t;if(t.length>this._maxLength)throw new n(`got ${t.length} bytes, max allowed is ${this._maxLength}`);R.write(r,e),e.write(t,r)}isValid(t){return j.isBuffer(t)&&t.length<=this._maxLength}}class F extends g{constructor(t,e){super(),this._childType=t,this._length=e}read(t){const e=new r.g.Array(this._length);for(let r=0;rthis._maxLength)throw new i(`saw ${e} length VarArray, max allowed is ${this._maxLength}`);const r=new Array(e);for(let n=0;nthis._maxLength)throw new n(`got array of size ${t.length}, max allowed is ${this._maxLength}`);R.write(t.length,e);for(const r of t)this._childType.write(r,e)}isValid(t){if(!(t instanceof Array)||t.length>this._maxLength)return!1;for(const e of t)if(!this._childType.isValid(e))return!1;return!0}}class X extends d{constructor(t){super(),this._childType=t}read(t){if(S.read(t))return this._childType.read(t)}write(t,e){const r=null!=t;S.write(r,e),r&&this._childType.write(t,e)}isValid(t){return null==t||this._childType.isValid(t)}}class k extends d{static read(){}static write(t){if(void 0!==t)throw new n("trying to write value to a void slot")}static isValid(t){return void 0===t}}class q extends d{constructor(t,e){super(),this.name=t,this.value=e}static read(t){const e=v.read(t),r=this._byValue[e];if(void 0===r)throw new i(`unknown ${this.enumName} member for value ${e}`);return r}static write(t,e){if(!this.isValid(t))throw new n(`${t} has enum name ${t?.enumName}, not ${this.enumName}: ${JSON.stringify(t)}`);v.write(t.value,e)}static isValid(t){return t?.constructor?.enumName===this.enumName||b(t,this)}static members(){return this._members}static values(){return Object.values(this._members)}static fromName(t){const e=this._members[t];if(!e)throw new TypeError(`${t} is not a member of ${this.enumName}`);return e}static fromValue(t){const e=this._byValue[t];if(void 0===e)throw new TypeError(`${t} is not a value of any member of ${this.enumName}`);return e}static create(t,e,r){const n=class extends q{};n.enumName=e,t.results[e]=n,n._members={},n._byValue={};for(const[t,e]of Object.entries(r)){const r=new n(t,e);n._members[t]=r,n._byValue[e]=r,n[t]=()=>r}return n}}class G extends d{resolve(){throw new o('"resolve" method should be implemented in the descendant class')}}class Y extends g{constructor(t){super(),this._attributes=t||{}}static read(t){const e={};for(const[r,n]of this._fields)e[r]=n.read(t);return new this(e)}static write(t,e){if(!this.isValid(t))throw new n(`${t} has struct name ${t?.constructor?.structName}, not ${this.structName}: ${JSON.stringify(t)}`);for(const[r,n]of this._fields){const i=t._attributes[r];n.write(i,e)}}static isValid(t){return t?.constructor?.structName===this.structName||b(t,this)}static create(t,e,r){const n=class extends Y{};n.structName=e,t.results[e]=n;const i=new Array(r.length);for(let e=0;e{"use strict";e.byteLength=function(t){var e=u(t),r=e[0],n=e[1];return 3*(r+n)/4-n},e.toByteArray=function(t){var e,r,o=u(t),s=o[0],f=o[1],a=new i(function(t,e,r){return 3*(e+r)/4-r}(0,s,f)),h=0,c=f>0?s-4:s;for(r=0;r>16&255,a[h++]=e>>8&255,a[h++]=255&e;2===f&&(e=n[t.charCodeAt(r)]<<2|n[t.charCodeAt(r+1)]>>4,a[h++]=255&e);1===f&&(e=n[t.charCodeAt(r)]<<10|n[t.charCodeAt(r+1)]<<4|n[t.charCodeAt(r+2)]>>2,a[h++]=e>>8&255,a[h++]=255&e);return a},e.fromByteArray=function(t){for(var e,n=t.length,i=n%3,o=[],s=16383,u=0,a=n-i;ua?a:u+s));1===i?(e=t[n-1],o.push(r[e>>2]+r[e<<4&63]+"==")):2===i&&(e=(t[n-2]<<8)+t[n-1],o.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"="));return o.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)r[s]=o[s],n[o.charCodeAt(s)]=s;function u(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function f(t,e,n){for(var i,o,s=[],u=e;u>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return s.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287:(t,e,r)=>{"use strict";const n=r(526),i=r(251),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.hp=f,e.IS=50;const s=2147483647;function u(t){if(t>s)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,f.prototype),e}function f(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return c(t)}return a(t,e,r)}function a(t,e,r){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!f.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|g(t,e);let n=u(r);const i=n.write(t,e);i!==r&&(n=n.slice(0,i));return n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(W(t,Uint8Array)){const e=new Uint8Array(t);return p(e.buffer,e.byteOffset,e.byteLength)}return l(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(W(t,ArrayBuffer)||t&&W(t.buffer,ArrayBuffer))return p(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(W(t,SharedArrayBuffer)||t&&W(t.buffer,SharedArrayBuffer)))return p(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return f.from(n,e,r);const i=function(t){if(f.isBuffer(t)){const e=0|d(t.length),r=u(e);return 0===r.length||t.copy(r,0,0,e),r}if(void 0!==t.length)return"number"!=typeof t.length||H(t.length)?u(0):l(t);if("Buffer"===t.type&&Array.isArray(t.data))return l(t.data)}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return f.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function h(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function c(t){return h(t),u(t<0?0:0|d(t))}function l(t){const e=t.length<0?0:0|d(t.length),r=u(e);for(let n=0;n=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|t}function g(t,e){if(f.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||W(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return G(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Y(t).length;default:if(i)return n?-1:G(t).length;e=(""+e).toLowerCase(),i=!0}}function y(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return x(this,e,r);case"ascii":return $(this,e,r);case"latin1":case"binary":return R(this,e,r);case"base64":return I(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function w(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function m(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),H(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=f.from(e,n)),f.isBuffer(e))return 0===e.length?-1:b(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):b(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(t,e,r,n,i){let o,s=1,u=t.length,f=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,f/=2,r/=2}function a(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){let n=-1;for(o=r;ou&&(r=u-f),o=r;o>=0;o--){let r=!0;for(let n=0;ni&&(n=i):n=i;const o=e.length;let s;for(n>o/2&&(n=o/2),s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function I(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function x(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+s<=r){let r,n,u,f;switch(s){case 1:e<128&&(o=e);break;case 2:r=t[i+1],128==(192&r)&&(f=(31&e)<<6|63&r,f>127&&(o=f));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(f=(15&e)<<12|(63&r)<<6|63&n,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:r=t[i+1],n=t[i+2],u=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&u)&&(f=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&u,f>65535&&f<1114112&&(o=f))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return function(t){const e=t.length;if(e<=U)return String.fromCharCode.apply(String,t);let r="",n=0;for(;nn.length?(f.isBuffer(e)||(e=f.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!f.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},f.byteLength=g,f.prototype._isBuffer=!0,f.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;er&&(t+=" ... "),""},o&&(f.prototype[o]=f.prototype.inspect),f.prototype.compare=function(t,e,r,n,i){if(W(t,Uint8Array)&&(t=f.from(t,t.offset,t.byteLength)),!f.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0);const u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r);for(let t=0;t>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return _(this,t,e,r);case"utf8":case"utf-8":return B(this,t,e,r);case"ascii":case"latin1":case"binary":return E(this,t,e,r);case"base64":return v(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},f.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const U=4096;function $(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;in)&&(r=n);let i="";for(let n=e;nr)throw new RangeError("Trying to access beyond buffer length")}function N(t,e,r,n,i,o){if(!f.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function S(t,e,r,n,i){P(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,r}function V(t,e,r,n,i){P(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r+7]=o,o>>=8,t[r+6]=o,o>>=8,t[r+5]=o,o>>=8,t[r+4]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=s,s>>=8,t[r+2]=s,s>>=8,t[r+1]=s,s>>=8,t[r]=s,r+8}function M(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function C(t,e,r,n,o){return e=+e,r>>>=0,o||M(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function D(t,e,r,n,o){return e=+e,r>>>=0,o||M(t,0,r,8),i.write(t,e,r,n,52,8),r+8}f.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t],i=1,o=0;for(;++o>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},f.prototype.readUint8=f.prototype.readUInt8=function(t,e){return t>>>=0,e||L(t,1,this.length),this[t]},f.prototype.readUint16LE=f.prototype.readUInt16LE=function(t,e){return t>>>=0,e||L(t,2,this.length),this[t]|this[t+1]<<8},f.prototype.readUint16BE=f.prototype.readUInt16BE=function(t,e){return t>>>=0,e||L(t,2,this.length),this[t]<<8|this[t+1]},f.prototype.readUint32LE=f.prototype.readUInt32LE=function(t,e){return t>>>=0,e||L(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},f.prototype.readUint32BE=f.prototype.readUInt32BE=function(t,e){return t>>>=0,e||L(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},f.prototype.readBigUInt64LE=Z((function(t){X(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t],i=1,o=0;for(;++o=i&&(n-=Math.pow(2,8*e)),n},f.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||L(t,e,this.length);let n=e,i=1,o=this[t+--n];for(;n>0&&(i*=256);)o+=this[t+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*e)),o},f.prototype.readInt8=function(t,e){return t>>>=0,e||L(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},f.prototype.readInt16LE=function(t,e){t>>>=0,e||L(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},f.prototype.readInt16BE=function(t,e){t>>>=0,e||L(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},f.prototype.readInt32LE=function(t,e){return t>>>=0,e||L(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},f.prototype.readInt32BE=function(t,e){return t>>>=0,e||L(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},f.prototype.readBigInt64LE=Z((function(t){X(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<>>=0,e||L(t,4,this.length),i.read(this,t,!0,23,4)},f.prototype.readFloatBE=function(t,e){return t>>>=0,e||L(t,4,this.length),i.read(this,t,!1,23,4)},f.prototype.readDoubleLE=function(t,e){return t>>>=0,e||L(t,8,this.length),i.read(this,t,!0,52,8)},f.prototype.readDoubleBE=function(t,e){return t>>>=0,e||L(t,8,this.length),i.read(this,t,!1,52,8)},f.prototype.writeUintLE=f.prototype.writeUIntLE=function(t,e,r,n){if(t=+t,e>>>=0,r>>>=0,!n){N(this,t,e,r,Math.pow(2,8*r)-1,0)}let i=1,o=0;for(this[e]=255&t;++o>>=0,r>>>=0,!n){N(this,t,e,r,Math.pow(2,8*r)-1,0)}let i=r-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+r},f.prototype.writeUint8=f.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,1,255,0),this[e]=255&t,e+1},f.prototype.writeUint16LE=f.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},f.prototype.writeUint16BE=f.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},f.prototype.writeUint32LE=f.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},f.prototype.writeUint32BE=f.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},f.prototype.writeBigUInt64LE=Z((function(t,e=0){return S(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),f.prototype.writeBigUInt64BE=Z((function(t,e=0){return V(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),f.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);N(this,t,e,r,n-1,-n)}let i=0,o=1,s=0;for(this[e]=255&t;++i>>=0,!n){const n=Math.pow(2,8*r-1);N(this,t,e,r,n-1,-n)}let i=r-1,o=1,s=0;for(this[e+i]=255&t;--i>=0&&(o*=256);)t<0&&0===s&&0!==this[e+i+1]&&(s=1),this[e+i]=(t/o|0)-s&255;return e+r},f.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},f.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},f.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},f.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},f.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},f.prototype.writeBigInt64LE=Z((function(t,e=0){return S(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),f.prototype.writeBigInt64BE=Z((function(t,e=0){return V(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),f.prototype.writeFloatLE=function(t,e,r){return C(this,t,e,!0,r)},f.prototype.writeFloatBE=function(t,e,r){return C(this,t,e,!1,r)},f.prototype.writeDoubleLE=function(t,e,r){return D(this,t,e,!0,r)},f.prototype.writeDoubleBE=function(t,e,r){return D(this,t,e,!1,r)},f.prototype.copy=function(t,e,r,n){if(!f.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function P(t,e,r,n,i,o){if(t>r||t3?0===e||e===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`:`>= ${e}${n} and <= ${r}${n}`,new j.ERR_OUT_OF_RANGE("value",i,t)}!function(t,e,r){X(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||k(e,t.length-(r+1))}(n,i,o)}function X(t,e){if("number"!=typeof t)throw new j.ERR_INVALID_ARG_TYPE(e,"number",t)}function k(t,e,r){if(Math.floor(t)!==t)throw X(t,r),new j.ERR_OUT_OF_RANGE(r||"offset","an integer",t);if(e<0)throw new j.ERR_BUFFER_OUT_OF_BOUNDS;throw new j.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}z("ERR_BUFFER_OUT_OF_BOUNDS",(function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),z("ERR_INVALID_ARG_TYPE",(function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`}),TypeError),z("ERR_OUT_OF_RANGE",(function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=F(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=F(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n}),RangeError);const q=/[^+/0-9A-Za-z-_]/g;function G(t,e){let r;e=e||1/0;const n=t.length;let i=null;const o=[];for(let s=0;s55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function Y(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(q,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function J(t,e,r,n){let i;for(i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function W(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function H(t){return t!=t}const Q=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function Z(t){return"undefined"==typeof BigInt?K:t}function K(){throw new Error("BigInt not supported")}},251:(t,e)=>{e.read=function(t,e,r,n,i){var o,s,u=8*i-n-1,f=(1<>1,h=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-h)-1,p>>=-h,h+=u;h>0;o=256*o+t[e+c],c+=l,h-=8);for(s=o&(1<<-h)-1,o>>=-h,h+=n;h>0;s=256*s+t[e+c],c+=l,h-=8);if(0===o)o=1-a;else{if(o===f)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=a}return(p?-1:1)*s*Math.pow(2,o-n)},e.write=function(t,e,r,n,i,o){var s,u,f,a=8*o-i-1,h=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=h):(s=Math.floor(Math.log(e)/Math.LN2),e*(f=Math.pow(2,-s))<1&&(s--,f*=2),(e+=s+c>=1?l/f:l*Math.pow(2,1-c))*f>=2&&(s++,f/=2),s+c>=h?(u=0,s=h):s+c>=1?(u=(e*f-1)*Math.pow(2,i),s+=c):(u=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,a-=8);t[r+p-d]|=128*g}}},e={};function r(n){var i=e[n];if(void 0!==i)return i.exports;var o=e[n]={exports:{}};return t[n](o,o.exports,r),o.exports}return r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r(281)})())); +//# sourceMappingURL=xdr.js.map + +/***/ }), + +/***/ 2135: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Account = void 0; +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Account object. + * + * `Account` represents a single account in the Stellar network and its sequence + * number. Account tracks the sequence number as it is used by {@link + * TransactionBuilder}. See + * [Accounts](https://developers.stellar.org/docs/glossary/accounts/) for + * more information about how accounts work in Stellar. + * + * @constructor + * + * @param {string} accountId - ID of the account (ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`). If you + * provide a muxed account address, this will throw; use {@link + * MuxedAccount} instead. + * @param {string} sequence - current sequence number of the account + */ +var Account = exports.Account = /*#__PURE__*/function () { + function Account(accountId, sequence) { + _classCallCheck(this, Account); + if (_strkey.StrKey.isValidMed25519PublicKey(accountId)) { + throw new Error('accountId is an M-address; use MuxedAccount instead'); + } + if (!_strkey.StrKey.isValidEd25519PublicKey(accountId)) { + throw new Error('accountId is invalid'); + } + if (!(typeof sequence === 'string')) { + throw new Error('sequence must be of type string'); + } + this._accountId = accountId; + this.sequence = new _bignumber["default"](sequence); + } + + /** + * Returns Stellar account ID, ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`. + * @returns {string} + */ + return _createClass(Account, [{ + key: "accountId", + value: function accountId() { + return this._accountId; + } + + /** + * @returns {string} sequence number for the account as a string + */ + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this.sequence.toString(); + } + + /** + * Increments sequence number in this object by one. + * @returns {void} + */ + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + this.sequence = this.sequence.plus(1); + } + }]); +}(); + +/***/ }), + +/***/ 1180: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Address = void 0; +var _strkey = __webpack_require__(7120); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Address object. + * + * `Address` represents a single address in the Stellar network. An address can + * represent an account or a contract. + * + * @constructor + * + * @param {string} address - ID of the account (ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`). If you + * provide a muxed account address, this will throw; use {@link + * MuxedAccount} instead. + */ +var Address = exports.Address = /*#__PURE__*/function () { + function Address(address) { + _classCallCheck(this, Address); + if (_strkey.StrKey.isValidEd25519PublicKey(address)) { + this._type = 'account'; + this._key = _strkey.StrKey.decodeEd25519PublicKey(address); + } else if (_strkey.StrKey.isValidContract(address)) { + this._type = 'contract'; + this._key = _strkey.StrKey.decodeContract(address); + } else { + throw new Error("Unsupported address type: ".concat(address)); + } + } + + /** + * Parses a string and returns an Address object. + * + * @param {string} address - The address to parse. ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA` + * @returns {Address} + */ + return _createClass(Address, [{ + key: "toString", + value: + /** + * Serialize an address to string. + * + * @returns {string} + */ + function toString() { + switch (this._type) { + case 'account': + return _strkey.StrKey.encodeEd25519PublicKey(this._key); + case 'contract': + return _strkey.StrKey.encodeContract(this._key); + default: + throw new Error('Unsupported address type'); + } + } + + /** + * Convert this Address to an xdr.ScVal type. + * + * @returns {xdr.ScVal} + */ + }, { + key: "toScVal", + value: function toScVal() { + return _xdr["default"].ScVal.scvAddress(this.toScAddress()); + } + + /** + * Convert this Address to an xdr.ScAddress type. + * + * @returns {xdr.ScAddress} + */ + }, { + key: "toScAddress", + value: function toScAddress() { + switch (this._type) { + case 'account': + return _xdr["default"].ScAddress.scAddressTypeAccount(_xdr["default"].PublicKey.publicKeyTypeEd25519(this._key)); + case 'contract': + return _xdr["default"].ScAddress.scAddressTypeContract(this._key); + default: + throw new Error('Unsupported address type'); + } + } + + /** + * Return the raw public key bytes for this address. + * + * @returns {Buffer} + */ + }, { + key: "toBuffer", + value: function toBuffer() { + return this._key; + } + }], [{ + key: "fromString", + value: function fromString(address) { + return new Address(address); + } + + /** + * Creates a new account Address object from a buffer of raw bytes. + * + * @param {Buffer} buffer - The bytes of an address to parse. + * @returns {Address} + */ + }, { + key: "account", + value: function account(buffer) { + return new Address(_strkey.StrKey.encodeEd25519PublicKey(buffer)); + } + + /** + * Creates a new contract Address object from a buffer of raw bytes. + * + * @param {Buffer} buffer - The bytes of an address to parse. + * @returns {Address} + */ + }, { + key: "contract", + value: function contract(buffer) { + return new Address(_strkey.StrKey.encodeContract(buffer)); + } + + /** + * Convert this from an xdr.ScVal type + * + * @param {xdr.ScVal} scVal - The xdr.ScVal type to parse + * @returns {Address} + */ + }, { + key: "fromScVal", + value: function fromScVal(scVal) { + return Address.fromScAddress(scVal.address()); + } + + /** + * Convert this from an xdr.ScAddress type + * + * @param {xdr.ScAddress} scAddress - The xdr.ScAddress type to parse + * @returns {Address} + */ + }, { + key: "fromScAddress", + value: function fromScAddress(scAddress) { + switch (scAddress["switch"]()) { + case _xdr["default"].ScAddressType.scAddressTypeAccount(): + return Address.account(scAddress.accountId().ed25519()); + case _xdr["default"].ScAddressType.scAddressTypeContract(): + return Address.contract(scAddress.contractId()); + default: + throw new Error('Unsupported address type'); + } + } + }]); +}(); + +/***/ }), + +/***/ 1764: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Asset = void 0; +var _util = __webpack_require__(645); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +var _hashing = __webpack_require__(9152); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Asset class represents an asset, either the native asset (`XLM`) + * or an asset code / issuer account ID pair. + * + * An asset code describes an asset code and issuer pair. In the case of the native + * asset XLM, the issuer will be null. + * + * @constructor + * @param {string} code - The asset code. + * @param {string} issuer - The account ID of the issuer. + */ +var Asset = exports.Asset = /*#__PURE__*/function () { + function Asset(code, issuer) { + _classCallCheck(this, Asset); + if (!/^[a-zA-Z0-9]{1,12}$/.test(code)) { + throw new Error('Asset code is invalid (maximum alphanumeric, 12 characters at max)'); + } + if (String(code).toLowerCase() !== 'xlm' && !issuer) { + throw new Error('Issuer cannot be null'); + } + if (issuer && !_strkey.StrKey.isValidEd25519PublicKey(issuer)) { + throw new Error('Issuer is invalid'); + } + if (String(code).toLowerCase() === 'xlm') { + // transform all xLM, Xlm, etc. variants -> XLM + this.code = 'XLM'; + } else { + this.code = code; + } + this.issuer = issuer; + } + + /** + * Returns an asset object for the native asset. + * @Return {Asset} + */ + return _createClass(Asset, [{ + key: "toXDRObject", + value: + /** + * Returns the xdr.Asset object for this asset. + * @returns {xdr.Asset} XDR asset object + */ + function toXDRObject() { + return this._toXDRObject(_xdr["default"].Asset); + } + + /** + * Returns the xdr.ChangeTrustAsset object for this asset. + * @returns {xdr.ChangeTrustAsset} XDR asset object + */ + }, { + key: "toChangeTrustXDRObject", + value: function toChangeTrustXDRObject() { + return this._toXDRObject(_xdr["default"].ChangeTrustAsset); + } + + /** + * Returns the xdr.TrustLineAsset object for this asset. + * @returns {xdr.TrustLineAsset} XDR asset object + */ + }, { + key: "toTrustLineXDRObject", + value: function toTrustLineXDRObject() { + return this._toXDRObject(_xdr["default"].TrustLineAsset); + } + + /** + * Returns the would-be contract ID (`C...` format) for this asset on a given + * network. + * + * @param {string} networkPassphrase indicates which network the contract + * ID should refer to, since every network will have a unique ID for the + * same contract (see {@link Networks} for options) + * + * @returns {string} the strkey-encoded (`C...`) contract ID for this asset + * + * @warning This makes no guarantee that this contract actually *exists*. + */ + }, { + key: "contractId", + value: function contractId(networkPassphrase) { + var networkId = (0, _hashing.hash)(Buffer.from(networkPassphrase)); + var preimage = _xdr["default"].HashIdPreimage.envelopeTypeContractId(new _xdr["default"].HashIdPreimageContractId({ + networkId: networkId, + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAsset(this.toXDRObject()) + })); + return _strkey.StrKey.encodeContract((0, _hashing.hash)(preimage.toXDR())); + } + + /** + * Returns the xdr object for this asset. + * @param {xdr.Asset | xdr.ChangeTrustAsset} xdrAsset - The asset xdr object. + * @returns {xdr.Asset | xdr.ChangeTrustAsset | xdr.TrustLineAsset} XDR Asset object + */ + }, { + key: "_toXDRObject", + value: function _toXDRObject() { + var xdrAsset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _xdr["default"].Asset; + if (this.isNative()) { + return xdrAsset.assetTypeNative(); + } + var xdrType; + var xdrTypeString; + if (this.code.length <= 4) { + xdrType = _xdr["default"].AlphaNum4; + xdrTypeString = 'assetTypeCreditAlphanum4'; + } else { + xdrType = _xdr["default"].AlphaNum12; + xdrTypeString = 'assetTypeCreditAlphanum12'; + } + + // pad code with null bytes if necessary + var padLength = this.code.length <= 4 ? 4 : 12; + var paddedCode = this.code.padEnd(padLength, '\0'); + + // eslint-disable-next-line new-cap + var assetType = new xdrType({ + assetCode: paddedCode, + issuer: _keypair.Keypair.fromPublicKey(this.issuer).xdrAccountId() + }); + return new xdrAsset(xdrTypeString, assetType); + } + + /** + * @returns {string} Asset code + */ + }, { + key: "getCode", + value: function getCode() { + if (this.code === undefined) { + return undefined; + } + return String(this.code); + } + + /** + * @returns {string} Asset issuer + */ + }, { + key: "getIssuer", + value: function getIssuer() { + if (this.issuer === undefined) { + return undefined; + } + return String(this.issuer); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {string} Asset type. Can be one of following types: + * + * - `native`, + * - `credit_alphanum4`, + * - `credit_alphanum12`, or + * - `unknown` as the error case (which should never occur) + */ + }, { + key: "getAssetType", + value: function getAssetType() { + switch (this.getRawAssetType().value) { + case _xdr["default"].AssetType.assetTypeNative().value: + return 'native'; + case _xdr["default"].AssetType.assetTypeCreditAlphanum4().value: + return 'credit_alphanum4'; + case _xdr["default"].AssetType.assetTypeCreditAlphanum12().value: + return 'credit_alphanum12'; + default: + return 'unknown'; + } + } + + /** + * @returns {xdr.AssetType} the raw XDR representation of the asset type + */ + }, { + key: "getRawAssetType", + value: function getRawAssetType() { + if (this.isNative()) { + return _xdr["default"].AssetType.assetTypeNative(); + } + if (this.code.length <= 4) { + return _xdr["default"].AssetType.assetTypeCreditAlphanum4(); + } + return _xdr["default"].AssetType.assetTypeCreditAlphanum12(); + } + + /** + * @returns {boolean} true if this asset object is the native asset. + */ + }, { + key: "isNative", + value: function isNative() { + return !this.issuer; + } + + /** + * @param {Asset} asset Asset to compare + * @returns {boolean} true if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(asset) { + return this.code === asset.getCode() && this.issuer === asset.getIssuer(); + } + }, { + key: "toString", + value: function toString() { + if (this.isNative()) { + return 'native'; + } + return "".concat(this.getCode(), ":").concat(this.getIssuer()); + } + + /** + * Compares two assets according to the criteria: + * + * 1. First compare the type (native < alphanum4 < alphanum12). + * 2. If the types are equal, compare the assets codes. + * 3. If the asset codes are equal, compare the issuers. + * + * @param {Asset} assetA - the first asset + * @param {Asset} assetB - the second asset + * @returns {number} `-1` if assetA < assetB, `0` if assetA == assetB, `1` if assetA > assetB. + * + * @static + * @memberof Asset + */ + }], [{ + key: "native", + value: function _native() { + return new Asset('XLM'); + } + + /** + * Returns an asset object from its XDR object representation. + * @param {xdr.Asset} assetXdr - The asset xdr object. + * @returns {Asset} + */ + }, { + key: "fromOperation", + value: function fromOperation(assetXdr) { + var anum; + var code; + var issuer; + switch (assetXdr["switch"]()) { + case _xdr["default"].AssetType.assetTypeNative(): + return this["native"](); + case _xdr["default"].AssetType.assetTypeCreditAlphanum4(): + anum = assetXdr.alphaNum4(); + /* falls through */ + case _xdr["default"].AssetType.assetTypeCreditAlphanum12(): + anum = anum || assetXdr.alphaNum12(); + issuer = _strkey.StrKey.encodeEd25519PublicKey(anum.issuer().ed25519()); + code = (0, _util.trimEnd)(anum.assetCode(), '\0'); + return new this(code, issuer); + default: + throw new Error("Invalid asset type: ".concat(assetXdr["switch"]().name)); + } + } + }, { + key: "compare", + value: function compare(assetA, assetB) { + if (!assetA || !(assetA instanceof Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof Asset)) { + throw new Error('assetB is invalid'); + } + if (assetA.equals(assetB)) { + return 0; + } + + // Compare asset types. + var xdrAtype = assetA.getRawAssetType().value; + var xdrBtype = assetB.getRawAssetType().value; + if (xdrAtype !== xdrBtype) { + return xdrAtype < xdrBtype ? -1 : 1; + } + + // Compare asset codes. + var result = asciiCompare(assetA.getCode(), assetB.getCode()); + if (result !== 0) { + return result; + } + + // Compare asset issuers. + return asciiCompare(assetA.getIssuer(), assetB.getIssuer()); + } + }]); +}(); +/** + * Compares two ASCII strings in lexographic order with uppercase precedence. + * + * @param {string} a - the first string to compare + * @param {string} b - the second + * @returns {number} like all `compare()`s: + * -1 if `a < b`, 0 if `a == b`, and 1 if `a > b` + * + * @warning No type-checks are done on the parameters + */ +function asciiCompare(a, b) { + return Buffer.compare(Buffer.from(a, 'ascii'), Buffer.from(b, 'ascii')); +} + +/***/ }), + +/***/ 5328: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.authorizeEntry = authorizeEntry; +exports.authorizeInvocation = authorizeInvocation; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +var _network = __webpack_require__(6202); +var _hashing = __webpack_require__(9152); +var _address = __webpack_require__(1180); +var _scval = __webpack_require__(7177); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +/** + * @async + * @callback SigningCallback A callback for signing an XDR structure + * representing all of the details necessary to authorize an invocation tree. + * + * @param {xdr.HashIdPreimage} preimage the entire authorization envelope + * whose hash you should sign, so that you can inspect the entire structure + * if necessary (rather than blindly signing a hash) + * + * @returns {Promise} the signature of the raw payload (which is + * the sha256 hash of the preimage bytes, so `hash(preimage.toXDR())`) signed + * by the key corresponding to the public key in the entry you pass to + * {@link authorizeEntry} (decipherable from its + * `credentials().address().address()`) + */ +/** + * Actually authorizes an existing authorization entry using the given the + * credentials and expiration details, returning a signed copy. + * + * This "fills out" the authorization entry with a signature, indicating to the + * {@link Operation.invokeHostFunction} its attached to that: + * - a particular identity (i.e. signing {@link Keypair} or other signer) + * - approving the execution of an invocation tree (i.e. a simulation-acquired + * {@link xdr.SorobanAuthorizedInvocation} or otherwise built) + * - on a particular network (uniquely identified by its passphrase, see + * {@link Networks}) + * - until a particular ledger sequence is reached. + * + * This one lets you pass a either a {@link Keypair} (or, more accurately, + * anything with a `sign(Buffer): Buffer` method) or a callback function (see + * {@link SigningCallback}) to handle signing the envelope hash. + * + * @param {xdr.SorobanAuthorizationEntry} entry an unsigned authorization entr + * @param {Keypair | SigningCallback} signer either a {@link Keypair} instance + * or a function which takes a payload (a + * {@link xdr.HashIdPreimageSorobanAuthorization} instance) input and returns + * the signature of the hash of the raw payload bytes (where the signing key + * should correspond to the address in the `entry`) + * @param {number} validUntilLedgerSeq the (exclusive) future ledger sequence + * number until which this authorization entry should be valid (if + * `currentLedgerSeq==validUntil`, this is expired)) + * @param {string} [networkPassphrase] the network passphrase is incorprated + * into the signature (see {@link Networks} for options) + * + * @returns {Promise} a promise for an + * authorization entry that you can pass along to + * {@link Operation.invokeHostFunction} + * + * @note If using the `SigningCallback` variation, the signer is assumed to be + * the entry's credential address. If you need a different key to sign the + * entry, you will need to use different method (e.g., fork this code). + * + * @see authorizeInvocation + * @example + * import { + * SorobanRpc, + * Transaction, + * Networks, + * authorizeEntry + * } from '@stellar/stellar-sdk'; + * + * // Assume signPayloadCallback is a well-formed signing callback. + * // + * // It might, for example, pop up a modal from a browser extension, send the + * // transaction to a third-party service for signing, or just do simple + * // signing via Keypair like it does here: + * function signPayloadCallback(payload) { + * return signer.sign(hash(payload.toXDR()); + * } + * + * function multiPartyAuth( + * server: SorobanRpc.Server, + * // assume this involves multi-party auth + * tx: Transaction, + * ) { + * return server + * .simulateTransaction(tx) + * .then((simResult) => { + * tx.operations[0].auth.map(entry => + * authorizeEntry( + * entry, + * signPayloadCallback, + * currentLedger + 1000, + * Networks.TESTNET); + * )); + * + * return server.prepareTransaction(tx, simResult); + * }) + * .then((preppedTx) => { + * preppedTx.sign(source); + * return server.sendTransaction(preppedTx); + * }); + * } + */ +function authorizeEntry(_x, _x2, _x3) { + return _authorizeEntry.apply(this, arguments); +} +/** + * This builds an entry from scratch, allowing you to express authorization as a + * function of: + * - a particular identity (i.e. signing {@link Keypair} or other signer) + * - approving the execution of an invocation tree (i.e. a simulation-acquired + * {@link xdr.SorobanAuthorizedInvocation} or otherwise built) + * - on a particular network (uniquely identified by its passphrase, see + * {@link Networks}) + * - until a particular ledger sequence is reached. + * + * This is in contrast to {@link authorizeEntry}, which signs an existing entry. + * + * @param {Keypair | SigningCallback} signer either a {@link Keypair} instance + * (or anything with a `.sign(buf): Buffer-like` method) or a function which + * takes a payload (a {@link xdr.HashIdPreimageSorobanAuthorization} + * instance) input and returns the signature of the hash of the raw payload + * bytes (where the signing key should correspond to the address in the + * `entry`) + * @param {number} validUntilLedgerSeq the (exclusive) future ledger sequence + * number until which this authorization entry should be valid (if + * `currentLedgerSeq==validUntilLedgerSeq`, this is expired)) + * @param {xdr.SorobanAuthorizedInvocation} invocation the invocation tree that + * we're authorizing (likely, this comes from transaction simulation) + * @param {string} [publicKey] the public identity of the signer (when + * providing a {@link Keypair} to `signer`, this can be omitted, as it just + * uses {@link Keypair.publicKey}) + * @param {string} [networkPassphrase] the network passphrase is incorprated + * into the signature (see {@link Networks} for options, default: + * {@link Networks.FUTURENET}) + * + * @returns {Promise} a promise for an + * authorization entry that you can pass along to + * {@link Operation.invokeHostFunction} + * + * @see authorizeEntry + */ +function _authorizeEntry() { + _authorizeEntry = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(entry, signer, validUntilLedgerSeq) { + var networkPassphrase, + clone, + addrAuth, + networkId, + preimage, + payload, + signature, + publicKey, + sigScVal, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + networkPassphrase = _args.length > 3 && _args[3] !== undefined ? _args[3] : _network.Networks.FUTURENET; + if (!(entry.credentials()["switch"]().value !== _xdr["default"].SorobanCredentialsType.sorobanCredentialsAddress().value)) { + _context.next = 3; + break; + } + return _context.abrupt("return", entry); + case 3: + clone = _xdr["default"].SorobanAuthorizationEntry.fromXDR(entry.toXDR()); + /** @type {xdr.SorobanAddressCredentials} */ + addrAuth = clone.credentials().address(); + addrAuth.signatureExpirationLedger(validUntilLedgerSeq); + networkId = (0, _hashing.hash)(Buffer.from(networkPassphrase)); + preimage = _xdr["default"].HashIdPreimage.envelopeTypeSorobanAuthorization(new _xdr["default"].HashIdPreimageSorobanAuthorization({ + networkId: networkId, + nonce: addrAuth.nonce(), + invocation: clone.rootInvocation(), + signatureExpirationLedger: addrAuth.signatureExpirationLedger() + })); + payload = (0, _hashing.hash)(preimage.toXDR()); + if (!(typeof signer === 'function')) { + _context.next = 18; + break; + } + _context.t0 = Buffer; + _context.next = 13; + return signer(preimage); + case 13: + _context.t1 = _context.sent; + signature = _context.t0.from.call(_context.t0, _context.t1); + publicKey = _address.Address.fromScAddress(addrAuth.address()).toString(); + _context.next = 20; + break; + case 18: + signature = Buffer.from(signer.sign(payload)); + publicKey = signer.publicKey(); + case 20: + if (_keypair.Keypair.fromPublicKey(publicKey).verify(payload, signature)) { + _context.next = 22; + break; + } + throw new Error("signature doesn't match payload"); + case 22: + // This structure is defined here: + // https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#stellar-account-signatures + // + // Encoding a contract structure as an ScVal means the map keys are supposed + // to be symbols, hence the forced typing here. + sigScVal = (0, _scval.nativeToScVal)({ + public_key: _strkey.StrKey.decodeEd25519PublicKey(publicKey), + signature: signature + }, { + type: { + public_key: ['symbol', null], + signature: ['symbol', null] + } + }); + addrAuth.signature(_xdr["default"].ScVal.scvVec([sigScVal])); + return _context.abrupt("return", clone); + case 25: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _authorizeEntry.apply(this, arguments); +} +function authorizeInvocation(signer, validUntilLedgerSeq, invocation) { + var publicKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; + var networkPassphrase = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : _network.Networks.FUTURENET; + // We use keypairs as a source of randomness for the nonce to avoid mucking + // with any crypto dependencies. Note that this just has to be random and + // unique, not cryptographically secure, so it's fine. + var kp = _keypair.Keypair.random().rawPublicKey(); + var nonce = new _xdr["default"].Int64(bytesToInt64(kp)); + var pk = publicKey || signer.publicKey(); + if (!pk) { + throw new Error("authorizeInvocation requires publicKey parameter"); + } + var entry = new _xdr["default"].SorobanAuthorizationEntry({ + rootInvocation: invocation, + credentials: _xdr["default"].SorobanCredentials.sorobanCredentialsAddress(new _xdr["default"].SorobanAddressCredentials({ + address: new _address.Address(pk).toScAddress(), + nonce: nonce, + signatureExpirationLedger: 0, + // replaced + signature: _xdr["default"].ScVal.scvVec([]) // replaced + })) + }); + return authorizeEntry(entry, signer, validUntilLedgerSeq, networkPassphrase); +} +function bytesToInt64(bytes) { + // eslint-disable-next-line no-bitwise + return bytes.subarray(0, 8).reduce(function (accum, b) { + return accum << 8 | b; + }, 0); +} + +/***/ }), + +/***/ 1387: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Claimant = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Claimant class represents an xdr.Claimant + * + * The claim predicate is optional, it defaults to unconditional if none is specified. + * + * @constructor + * @param {string} destination - The destination account ID. + * @param {xdr.ClaimPredicate} [predicate] - The claim predicate. + */ +var Claimant = exports.Claimant = /*#__PURE__*/function () { + function Claimant(destination, predicate) { + _classCallCheck(this, Claimant); + if (destination && !_strkey.StrKey.isValidEd25519PublicKey(destination)) { + throw new Error('Destination is invalid'); + } + this._destination = destination; + if (!predicate) { + this._predicate = _xdr["default"].ClaimPredicate.claimPredicateUnconditional(); + } else if (predicate instanceof _xdr["default"].ClaimPredicate) { + this._predicate = predicate; + } else { + throw new Error('Predicate should be an xdr.ClaimPredicate'); + } + } + + /** + * Returns an unconditional claim predicate + * @Return {xdr.ClaimPredicate} + */ + return _createClass(Claimant, [{ + key: "toXDRObject", + value: + /** + * Returns the xdr object for this claimant. + * @returns {xdr.Claimant} XDR Claimant object + */ + function toXDRObject() { + var claimant = new _xdr["default"].ClaimantV0({ + destination: _keypair.Keypair.fromPublicKey(this._destination).xdrAccountId(), + predicate: this._predicate + }); + return _xdr["default"].Claimant.claimantTypeV0(claimant); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "destination", + get: function get() { + return this._destination; + }, + set: function set(value) { + throw new Error('Claimant is immutable'); + } + + /** + * @type {xdr.ClaimPredicate} + * @readonly + */ + }, { + key: "predicate", + get: function get() { + return this._predicate; + }, + set: function set(value) { + throw new Error('Claimant is immutable'); + } + }], [{ + key: "predicateUnconditional", + value: function predicateUnconditional() { + return _xdr["default"].ClaimPredicate.claimPredicateUnconditional(); + } + + /** + * Returns an `and` claim predicate + * @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate + * @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateAnd", + value: function predicateAnd(left, right) { + if (!(left instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('left Predicate should be an xdr.ClaimPredicate'); + } + if (!(right instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateAnd([left, right]); + } + + /** + * Returns an `or` claim predicate + * @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate + * @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateOr", + value: function predicateOr(left, right) { + if (!(left instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('left Predicate should be an xdr.ClaimPredicate'); + } + if (!(right instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateOr([left, right]); + } + + /** + * Returns a `not` claim predicate + * @param {xdr.ClaimPredicate} predicate an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateNot", + value: function predicateNot(predicate) { + if (!(predicate instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateNot(predicate); + } + + /** + * Returns a `BeforeAbsoluteTime` claim predicate + * + * This predicate will be fulfilled if the closing time of the ledger that + * includes the CreateClaimableBalance operation is less than this (absolute) + * Unix timestamp (expressed in seconds). + * + * @param {string} absBefore Unix epoch (in seconds) as a string + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateBeforeAbsoluteTime", + value: function predicateBeforeAbsoluteTime(absBefore) { + return _xdr["default"].ClaimPredicate.claimPredicateBeforeAbsoluteTime(_xdr["default"].Int64.fromString(absBefore)); + } + + /** + * Returns a `BeforeRelativeTime` claim predicate + * + * This predicate will be fulfilled if the closing time of the ledger that + * includes the CreateClaimableBalance operation plus this relative time delta + * (in seconds) is less than the current time. + * + * @param {strings} seconds seconds since closeTime of the ledger in which the ClaimableBalanceEntry was created (as string) + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateBeforeRelativeTime", + value: function predicateBeforeRelativeTime(seconds) { + return _xdr["default"].ClaimPredicate.claimPredicateBeforeRelativeTime(_xdr["default"].Int64.fromString(seconds)); + } + + /** + * Returns a claimant object from its XDR object representation. + * @param {xdr.Claimant} claimantXdr - The claimant xdr object. + * @returns {Claimant} + */ + }, { + key: "fromXDR", + value: function fromXDR(claimantXdr) { + var value; + switch (claimantXdr["switch"]()) { + case _xdr["default"].ClaimantType.claimantTypeV0(): + value = claimantXdr.v0(); + return new this(_strkey.StrKey.encodeEd25519PublicKey(value.destination().ed25519()), value.predicate()); + default: + throw new Error("Invalid claimant type: ".concat(claimantXdr["switch"]().name)); + } + } + }]); +}(); + +/***/ }), + +/***/ 7452: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Contract = void 0; +var _address = __webpack_require__(1180); +var _operation = __webpack_require__(7237); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Contract object. + * + * `Contract` represents a single contract in the Stellar network, embodying the + * interface of the contract. See + * [Contracts](https://soroban.stellar.org/docs/learn/interacting-with-contracts) + * for more information about how contracts work in Stellar. + * + * @constructor + * + * @param {string} contractId - ID of the contract (ex. + * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`). + */ +var Contract = exports.Contract = /*#__PURE__*/function () { + function Contract(contractId) { + _classCallCheck(this, Contract); + try { + // First, try it as a strkey + this._id = _strkey.StrKey.decodeContract(contractId); + } catch (_) { + throw new Error("Invalid contract ID: ".concat(contractId)); + } + } + + /** + * Returns Stellar contract ID as a strkey, ex. + * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`. + * @returns {string} + */ + return _createClass(Contract, [{ + key: "contractId", + value: function contractId() { + return _strkey.StrKey.encodeContract(this._id); + } + + /** @returns {string} the ID as a strkey (C...) */ + }, { + key: "toString", + value: function toString() { + return this.contractId(); + } + + /** @returns {Address} the wrapped address of this contract */ + }, { + key: "address", + value: function address() { + return _address.Address.contract(this._id); + } + + /** + * Returns an operation that will invoke this contract call. + * + * @param {string} method name of the method to call + * @param {...xdr.ScVal} params arguments to pass to the function call + * + * @returns {xdr.Operation} an InvokeHostFunctionOp operation to call the + * contract with the given method and parameters + * + * @see Operation.invokeHostFunction + * @see Operation.invokeContractFunction + * @see Operation.createCustomContract + * @see Operation.createStellarAssetContract + * @see Operation.uploadContractWasm + */ + }, { + key: "call", + value: function call(method) { + for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + params[_key - 1] = arguments[_key]; + } + return _operation.Operation.invokeContractFunction({ + contract: this.address().toString(), + "function": method, + args: params + }); + } + + /** + * Returns the read-only footprint entries necessary for any invocations to + * this contract, for convenience when manually adding it to your + * transaction's overall footprint or doing bump/restore operations. + * + * @returns {xdr.LedgerKey} the ledger key for the deployed contract instance + */ + }, { + key: "getFootprint", + value: function getFootprint() { + return _xdr["default"].LedgerKey.contractData(new _xdr["default"].LedgerKeyContractData({ + contract: this.address().toScAddress(), + key: _xdr["default"].ScVal.scvLedgerKeyContractInstance(), + durability: _xdr["default"].ContractDataDurability.persistent() + })); + } + }]); +}(); + +/***/ }), + +/***/ 3919: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.humanizeEvents = humanizeEvents; +var _strkey = __webpack_require__(7120); +var _scval = __webpack_require__(7177); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Converts raw diagnostic or contract events into something with a flatter, + * human-readable, and understandable structure. + * + * @param {xdr.DiagnosticEvent[] | xdr.ContractEvent[]} events either contract + * events or diagnostic events to parse into a friendly format + * + * @returns {SorobanEvent[]} a list of human-readable event structures, where + * each element has the following properties: + * - type: a string of one of 'system', 'contract', 'diagnostic + * - contractId?: optionally, a `C...` encoded strkey + * - topics: a list of {@link scValToNative} invocations on the topics + * - data: similarly, a {@link scValToNative} invocation on the raw event data + */ +function humanizeEvents(events) { + return events.map(function (e) { + // A pseudo-instanceof check for xdr.DiagnosticEvent more reliable + // in mixed SDK environments: + if (e.inSuccessfulContractCall) { + return extractEvent(e.event()); + } + return extractEvent(e); + }); +} +function extractEvent(event) { + return _objectSpread(_objectSpread({}, typeof event.contractId === 'function' && event.contractId() != null && { + contractId: _strkey.StrKey.encodeContract(event.contractId()) + }), {}, { + type: event.type().name, + topics: event.body().value().topics().map(function (t) { + return (0, _scval.scValToNative)(t); + }), + data: (0, _scval.scValToNative)(event.body().value().data()) + }); +} + +/***/ }), + +/***/ 9260: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.FeeBumpTransaction = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _hashing = __webpack_require__(9152); +var _transaction = __webpack_require__(380); +var _transaction_base = __webpack_require__(3758); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Use {@link TransactionBuilder.buildFeeBumpTransaction} to build a + * FeeBumpTransaction object. If you have an object or base64-encoded string of + * the transaction envelope XDR use {@link TransactionBuilder.fromXDR}. + * + * Once a {@link FeeBumpTransaction} has been created, its attributes and operations + * should not be changed. You should only add signatures (using {@link FeeBumpTransaction#sign}) before + * submitting to the network or forwarding on to additional signers. + * + * @param {string|xdr.TransactionEnvelope} envelope - transaction envelope + * object or base64 encoded string. + * @param {string} networkPassphrase - passphrase of the target Stellar network + * (e.g. "Public Global Stellar Network ; September 2015"). + * + * @extends TransactionBase + */ +var FeeBumpTransaction = exports.FeeBumpTransaction = /*#__PURE__*/function (_TransactionBase) { + function FeeBumpTransaction(envelope, networkPassphrase) { + var _this; + _classCallCheck(this, FeeBumpTransaction); + if (typeof envelope === 'string') { + var buffer = Buffer.from(envelope, 'base64'); + envelope = _xdr["default"].TransactionEnvelope.fromXDR(buffer); + } + var envelopeType = envelope["switch"](); + if (envelopeType !== _xdr["default"].EnvelopeType.envelopeTypeTxFeeBump()) { + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxFeeBump but received an ".concat(envelopeType.name, ".")); + } + var txEnvelope = envelope.value(); + var tx = txEnvelope.tx(); + var fee = tx.fee().toString(); + // clone signatures + var signatures = (txEnvelope.signatures() || []).slice(); + _this = _callSuper(this, FeeBumpTransaction, [tx, signatures, fee, networkPassphrase]); + var innerTxEnvelope = _xdr["default"].TransactionEnvelope.envelopeTypeTx(tx.innerTx().v1()); + _this._feeSource = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(_this.tx.feeSource()); + _this._innerTransaction = new _transaction.Transaction(innerTxEnvelope, networkPassphrase); + return _this; + } + + /** + * @type {Transaction} + * @readonly + */ + _inherits(FeeBumpTransaction, _TransactionBase); + return _createClass(FeeBumpTransaction, [{ + key: "innerTransaction", + get: function get() { + return this._innerTransaction; + } + + /** + * @type {Operation[]} + * @readonly + */ + }, { + key: "operations", + get: function get() { + return this._innerTransaction.operations; + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "feeSource", + get: function get() { + return this._feeSource; + } + + /** + * Returns the "signature base" of this transaction, which is the value + * that, when hashed, should be signed to create a signature that + * validators on the Stellar Network will accept. + * + * It is composed of a 4 prefix bytes followed by the xdr-encoded form + * of this transaction. + * @returns {Buffer} + */ + }, { + key: "signatureBase", + value: function signatureBase() { + var taggedTransaction = new _xdr["default"].TransactionSignaturePayloadTaggedTransaction.envelopeTypeTxFeeBump(this.tx); + var txSignature = new _xdr["default"].TransactionSignaturePayload({ + networkId: _xdr["default"].Hash.fromXDR((0, _hashing.hash)(this.networkPassphrase)), + taggedTransaction: taggedTransaction + }); + return txSignature.toXDR(); + } + + /** + * To envelope returns a xdr.TransactionEnvelope which can be submitted to the network. + * @returns {xdr.TransactionEnvelope} + */ + }, { + key: "toEnvelope", + value: function toEnvelope() { + var envelope = new _xdr["default"].FeeBumpTransactionEnvelope({ + tx: _xdr["default"].FeeBumpTransaction.fromXDR(this.tx.toXDR()), + // make a copy of the tx + signatures: this.signatures.slice() // make a copy of the signatures + }); + return new _xdr["default"].TransactionEnvelope.envelopeTypeTxFeeBump(envelope); + } + }]); +}(_transaction_base.TransactionBase); + +/***/ }), + +/***/ 7938: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var XDR = _interopRequireWildcard(__webpack_require__(3740)); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +// Automatically generated by xdrgen on 2024-09-12T11:09:00-08:00 +// DO NOT EDIT or your changes may be overwritten + +/* jshint maxstatements:2147483647 */ +/* jshint esnext:true */ + +var types = XDR.config(function (xdr) { + // Workaround for https://github.com/stellar/xdrgen/issues/152 + // + // The "correct" way would be to replace bare instances of each constant with + // xdr.lookup("..."), but that's more error-prone. + var SCSYMBOL_LIMIT = 32; + var SC_SPEC_DOC_LIMIT = 1024; + + // === xdr source ============================================================ + // + // typedef opaque Value<>; + // + // =========================================================================== + xdr.typedef("Value", xdr.varOpaque()); + + // === xdr source ============================================================ + // + // struct SCPBallot + // { + // uint32 counter; // n + // Value value; // x + // }; + // + // =========================================================================== + xdr.struct("ScpBallot", [["counter", xdr.lookup("Uint32")], ["value", xdr.lookup("Value")]]); + + // === xdr source ============================================================ + // + // enum SCPStatementType + // { + // SCP_ST_PREPARE = 0, + // SCP_ST_CONFIRM = 1, + // SCP_ST_EXTERNALIZE = 2, + // SCP_ST_NOMINATE = 3 + // }; + // + // =========================================================================== + xdr["enum"]("ScpStatementType", { + scpStPrepare: 0, + scpStConfirm: 1, + scpStExternalize: 2, + scpStNominate: 3 + }); + + // === xdr source ============================================================ + // + // struct SCPNomination + // { + // Hash quorumSetHash; // D + // Value votes<>; // X + // Value accepted<>; // Y + // }; + // + // =========================================================================== + xdr.struct("ScpNomination", [["quorumSetHash", xdr.lookup("Hash")], ["votes", xdr.varArray(xdr.lookup("Value"), 2147483647)], ["accepted", xdr.varArray(xdr.lookup("Value"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } + // + // =========================================================================== + xdr.struct("ScpStatementPrepare", [["quorumSetHash", xdr.lookup("Hash")], ["ballot", xdr.lookup("ScpBallot")], ["prepared", xdr.option(xdr.lookup("ScpBallot"))], ["preparedPrime", xdr.option(xdr.lookup("ScpBallot"))], ["nC", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } + // + // =========================================================================== + xdr.struct("ScpStatementConfirm", [["ballot", xdr.lookup("ScpBallot")], ["nPrepared", xdr.lookup("Uint32")], ["nCommit", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")], ["quorumSetHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } + // + // =========================================================================== + xdr.struct("ScpStatementExternalize", [["commit", xdr.lookup("ScpBallot")], ["nH", xdr.lookup("Uint32")], ["commitQuorumSetHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union switch (SCPStatementType type) + // { + // case SCP_ST_PREPARE: + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } prepare; + // case SCP_ST_CONFIRM: + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } confirm; + // case SCP_ST_EXTERNALIZE: + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } externalize; + // case SCP_ST_NOMINATE: + // SCPNomination nominate; + // } + // + // =========================================================================== + xdr.union("ScpStatementPledges", { + switchOn: xdr.lookup("ScpStatementType"), + switchName: "type", + switches: [["scpStPrepare", "prepare"], ["scpStConfirm", "confirm"], ["scpStExternalize", "externalize"], ["scpStNominate", "nominate"]], + arms: { + prepare: xdr.lookup("ScpStatementPrepare"), + confirm: xdr.lookup("ScpStatementConfirm"), + externalize: xdr.lookup("ScpStatementExternalize"), + nominate: xdr.lookup("ScpNomination") + } + }); + + // === xdr source ============================================================ + // + // struct SCPStatement + // { + // NodeID nodeID; // v + // uint64 slotIndex; // i + // + // union switch (SCPStatementType type) + // { + // case SCP_ST_PREPARE: + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } prepare; + // case SCP_ST_CONFIRM: + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } confirm; + // case SCP_ST_EXTERNALIZE: + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } externalize; + // case SCP_ST_NOMINATE: + // SCPNomination nominate; + // } + // pledges; + // }; + // + // =========================================================================== + xdr.struct("ScpStatement", [["nodeId", xdr.lookup("NodeId")], ["slotIndex", xdr.lookup("Uint64")], ["pledges", xdr.lookup("ScpStatementPledges")]]); + + // === xdr source ============================================================ + // + // struct SCPEnvelope + // { + // SCPStatement statement; + // Signature signature; + // }; + // + // =========================================================================== + xdr.struct("ScpEnvelope", [["statement", xdr.lookup("ScpStatement")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // struct SCPQuorumSet + // { + // uint32 threshold; + // NodeID validators<>; + // SCPQuorumSet innerSets<>; + // }; + // + // =========================================================================== + xdr.struct("ScpQuorumSet", [["threshold", xdr.lookup("Uint32")], ["validators", xdr.varArray(xdr.lookup("NodeId"), 2147483647)], ["innerSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)]]); + + // === xdr source ============================================================ + // + // typedef opaque Thresholds[4]; + // + // =========================================================================== + xdr.typedef("Thresholds", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef string string32<32>; + // + // =========================================================================== + xdr.typedef("String32", xdr.string(32)); + + // === xdr source ============================================================ + // + // typedef string string64<64>; + // + // =========================================================================== + xdr.typedef("String64", xdr.string(64)); + + // === xdr source ============================================================ + // + // typedef int64 SequenceNumber; + // + // =========================================================================== + xdr.typedef("SequenceNumber", xdr.lookup("Int64")); + + // === xdr source ============================================================ + // + // typedef opaque DataValue<64>; + // + // =========================================================================== + xdr.typedef("DataValue", xdr.varOpaque(64)); + + // === xdr source ============================================================ + // + // typedef Hash PoolID; + // + // =========================================================================== + xdr.typedef("PoolId", xdr.lookup("Hash")); + + // === xdr source ============================================================ + // + // typedef opaque AssetCode4[4]; + // + // =========================================================================== + xdr.typedef("AssetCode4", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef opaque AssetCode12[12]; + // + // =========================================================================== + xdr.typedef("AssetCode12", xdr.opaque(12)); + + // === xdr source ============================================================ + // + // enum AssetType + // { + // ASSET_TYPE_NATIVE = 0, + // ASSET_TYPE_CREDIT_ALPHANUM4 = 1, + // ASSET_TYPE_CREDIT_ALPHANUM12 = 2, + // ASSET_TYPE_POOL_SHARE = 3 + // }; + // + // =========================================================================== + xdr["enum"]("AssetType", { + assetTypeNative: 0, + assetTypeCreditAlphanum4: 1, + assetTypeCreditAlphanum12: 2, + assetTypePoolShare: 3 + }); + + // === xdr source ============================================================ + // + // union AssetCode switch (AssetType type) + // { + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AssetCode4 assetCode4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AssetCode12 assetCode12; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("AssetCode", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeCreditAlphanum4", "assetCode4"], ["assetTypeCreditAlphanum12", "assetCode12"]], + arms: { + assetCode4: xdr.lookup("AssetCode4"), + assetCode12: xdr.lookup("AssetCode12") + } + }); + + // === xdr source ============================================================ + // + // struct AlphaNum4 + // { + // AssetCode4 assetCode; + // AccountID issuer; + // }; + // + // =========================================================================== + xdr.struct("AlphaNum4", [["assetCode", xdr.lookup("AssetCode4")], ["issuer", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // struct AlphaNum12 + // { + // AssetCode12 assetCode; + // AccountID issuer; + // }; + // + // =========================================================================== + xdr.struct("AlphaNum12", [["assetCode", xdr.lookup("AssetCode12")], ["issuer", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // union Asset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("Asset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12") + } + }); + + // === xdr source ============================================================ + // + // struct Price + // { + // int32 n; // numerator + // int32 d; // denominator + // }; + // + // =========================================================================== + xdr.struct("Price", [["n", xdr.lookup("Int32")], ["d", xdr.lookup("Int32")]]); + + // === xdr source ============================================================ + // + // struct Liabilities + // { + // int64 buying; + // int64 selling; + // }; + // + // =========================================================================== + xdr.struct("Liabilities", [["buying", xdr.lookup("Int64")], ["selling", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum ThresholdIndexes + // { + // THRESHOLD_MASTER_WEIGHT = 0, + // THRESHOLD_LOW = 1, + // THRESHOLD_MED = 2, + // THRESHOLD_HIGH = 3 + // }; + // + // =========================================================================== + xdr["enum"]("ThresholdIndices", { + thresholdMasterWeight: 0, + thresholdLow: 1, + thresholdMed: 2, + thresholdHigh: 3 + }); + + // === xdr source ============================================================ + // + // enum LedgerEntryType + // { + // ACCOUNT = 0, + // TRUSTLINE = 1, + // OFFER = 2, + // DATA = 3, + // CLAIMABLE_BALANCE = 4, + // LIQUIDITY_POOL = 5, + // CONTRACT_DATA = 6, + // CONTRACT_CODE = 7, + // CONFIG_SETTING = 8, + // TTL = 9 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerEntryType", { + account: 0, + trustline: 1, + offer: 2, + data: 3, + claimableBalance: 4, + liquidityPool: 5, + contractData: 6, + contractCode: 7, + configSetting: 8, + ttl: 9 + }); + + // === xdr source ============================================================ + // + // struct Signer + // { + // SignerKey key; + // uint32 weight; // really only need 1 byte + // }; + // + // =========================================================================== + xdr.struct("Signer", [["key", xdr.lookup("SignerKey")], ["weight", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // enum AccountFlags + // { // masks for each flag + // + // // Flags set on issuer accounts + // // TrustLines are created with authorized set to "false" requiring + // // the issuer to set it for each TrustLine + // AUTH_REQUIRED_FLAG = 0x1, + // // If set, the authorized flag in TrustLines can be cleared + // // otherwise, authorization cannot be revoked + // AUTH_REVOCABLE_FLAG = 0x2, + // // Once set, causes all AUTH_* flags to be read-only + // AUTH_IMMUTABLE_FLAG = 0x4, + // // Trustlines are created with clawback enabled set to "true", + // // and claimable balances created from those trustlines are created + // // with clawback enabled set to "true" + // AUTH_CLAWBACK_ENABLED_FLAG = 0x8 + // }; + // + // =========================================================================== + xdr["enum"]("AccountFlags", { + authRequiredFlag: 1, + authRevocableFlag: 2, + authImmutableFlag: 4, + authClawbackEnabledFlag: 8 + }); + + // === xdr source ============================================================ + // + // const MASK_ACCOUNT_FLAGS = 0x7; + // + // =========================================================================== + xdr["const"]("MASK_ACCOUNT_FLAGS", 0x7); + + // === xdr source ============================================================ + // + // const MASK_ACCOUNT_FLAGS_V17 = 0xF; + // + // =========================================================================== + xdr["const"]("MASK_ACCOUNT_FLAGS_V17", 0xF); + + // === xdr source ============================================================ + // + // const MAX_SIGNERS = 20; + // + // =========================================================================== + xdr["const"]("MAX_SIGNERS", 20); + + // === xdr source ============================================================ + // + // typedef AccountID* SponsorshipDescriptor; + // + // =========================================================================== + xdr.typedef("SponsorshipDescriptor", xdr.option(xdr.lookup("AccountId"))); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV3 + // { + // // We can use this to add more fields, or because it is first, to + // // change AccountEntryExtensionV3 into a union. + // ExtensionPoint ext; + // + // // Ledger number at which `seqNum` took on its present value. + // uint32 seqLedger; + // + // // Time at which `seqNum` took on its present value. + // TimePoint seqTime; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV3", [["ext", xdr.lookup("ExtensionPoint")], ["seqLedger", xdr.lookup("Uint32")], ["seqTime", xdr.lookup("TimePoint")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 3: + // AccountEntryExtensionV3 v3; + // } + // + // =========================================================================== + xdr.union("AccountEntryExtensionV2Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [3, "v3"]], + arms: { + v3: xdr.lookup("AccountEntryExtensionV3") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV2 + // { + // uint32 numSponsored; + // uint32 numSponsoring; + // SponsorshipDescriptor signerSponsoringIDs; + // + // union switch (int v) + // { + // case 0: + // void; + // case 3: + // AccountEntryExtensionV3 v3; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV2", [["numSponsored", xdr.lookup("Uint32")], ["numSponsoring", xdr.lookup("Uint32")], ["signerSponsoringIDs", xdr.varArray(xdr.lookup("SponsorshipDescriptor"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExtensionV2Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // AccountEntryExtensionV2 v2; + // } + // + // =========================================================================== + xdr.union("AccountEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [2, "v2"]], + arms: { + v2: xdr.lookup("AccountEntryExtensionV2") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV1 + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // AccountEntryExtensionV2 v2; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("AccountEntryExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // AccountEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("AccountEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("AccountEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntry + // { + // AccountID accountID; // master public key for this account + // int64 balance; // in stroops + // SequenceNumber seqNum; // last sequence number used for this account + // uint32 numSubEntries; // number of sub-entries this account has + // // drives the reserve + // AccountID* inflationDest; // Account to vote for during inflation + // uint32 flags; // see AccountFlags + // + // string32 homeDomain; // can be used for reverse federation and memo lookup + // + // // fields used for signatures + // // thresholds stores unsigned bytes: [weight of master|low|medium|high] + // Thresholds thresholds; + // + // Signer signers; // possible signers for this account + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // AccountEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntry", [["accountId", xdr.lookup("AccountId")], ["balance", xdr.lookup("Int64")], ["seqNum", xdr.lookup("SequenceNumber")], ["numSubEntries", xdr.lookup("Uint32")], ["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["flags", xdr.lookup("Uint32")], ["homeDomain", xdr.lookup("String32")], ["thresholds", xdr.lookup("Thresholds")], ["signers", xdr.varArray(xdr.lookup("Signer"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExt")]]); + + // === xdr source ============================================================ + // + // enum TrustLineFlags + // { + // // issuer has authorized account to perform transactions with its credit + // AUTHORIZED_FLAG = 1, + // // issuer has authorized account to maintain and reduce liabilities for its + // // credit + // AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG = 2, + // // issuer has specified that it may clawback its credit, and that claimable + // // balances created with its credit may also be clawed back + // TRUSTLINE_CLAWBACK_ENABLED_FLAG = 4 + // }; + // + // =========================================================================== + xdr["enum"]("TrustLineFlags", { + authorizedFlag: 1, + authorizedToMaintainLiabilitiesFlag: 2, + trustlineClawbackEnabledFlag: 4 + }); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS = 1; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS", 1); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS_V13 = 3; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS_V13", 3); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS_V17 = 7; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS_V17", 7); + + // === xdr source ============================================================ + // + // enum LiquidityPoolType + // { + // LIQUIDITY_POOL_CONSTANT_PRODUCT = 0 + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolType", { + liquidityPoolConstantProduct: 0 + }); + + // === xdr source ============================================================ + // + // union TrustLineAsset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // case ASSET_TYPE_POOL_SHARE: + // PoolID liquidityPoolID; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("TrustLineAsset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPoolId"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12"), + liquidityPoolId: xdr.lookup("PoolId") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryExtensionV2Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TrustLineEntryExtensionV2 + // { + // int32 liquidityPoolUseCount; + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TrustLineEntryExtensionV2", [["liquidityPoolUseCount", xdr.lookup("Int32")], ["ext", xdr.lookup("TrustLineEntryExtensionV2Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [2, "v2"]], + arms: { + v2: xdr.lookup("TrustLineEntryExtensionV2") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } + // + // =========================================================================== + xdr.struct("TrustLineEntryV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("TrustLineEntryV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } v1; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("TrustLineEntryV1") + } + }); + + // === xdr source ============================================================ + // + // struct TrustLineEntry + // { + // AccountID accountID; // account this trustline belongs to + // TrustLineAsset asset; // type of asset (with issuer) + // int64 balance; // how much of this asset the user has. + // // Asset defines the unit for this; + // + // int64 limit; // balance cannot be above this + // uint32 flags; // see TrustLineFlags + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TrustLineEntry", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")], ["balance", xdr.lookup("Int64")], ["limit", xdr.lookup("Int64")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("TrustLineEntryExt")]]); + + // === xdr source ============================================================ + // + // enum OfferEntryFlags + // { + // // an offer with this flag will not act on and take a reverse offer of equal + // // price + // PASSIVE_FLAG = 1 + // }; + // + // =========================================================================== + xdr["enum"]("OfferEntryFlags", { + passiveFlag: 1 + }); + + // === xdr source ============================================================ + // + // const MASK_OFFERENTRY_FLAGS = 1; + // + // =========================================================================== + xdr["const"]("MASK_OFFERENTRY_FLAGS", 1); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("OfferEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct OfferEntry + // { + // AccountID sellerID; + // int64 offerID; + // Asset selling; // A + // Asset buying; // B + // int64 amount; // amount of A + // + // /* price for this offer: + // price of A in terms of B + // price=AmountB/AmountA=priceNumerator/priceDenominator + // price is after fees + // */ + // Price price; + // uint32 flags; // see OfferEntryFlags + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("OfferEntry", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("OfferEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("DataEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct DataEntry + // { + // AccountID accountID; // account this data belongs to + // string64 dataName; + // DataValue dataValue; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("DataEntry", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")], ["dataValue", xdr.lookup("DataValue")], ["ext", xdr.lookup("DataEntryExt")]]); + + // === xdr source ============================================================ + // + // enum ClaimPredicateType + // { + // CLAIM_PREDICATE_UNCONDITIONAL = 0, + // CLAIM_PREDICATE_AND = 1, + // CLAIM_PREDICATE_OR = 2, + // CLAIM_PREDICATE_NOT = 3, + // CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME = 4, + // CLAIM_PREDICATE_BEFORE_RELATIVE_TIME = 5 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimPredicateType", { + claimPredicateUnconditional: 0, + claimPredicateAnd: 1, + claimPredicateOr: 2, + claimPredicateNot: 3, + claimPredicateBeforeAbsoluteTime: 4, + claimPredicateBeforeRelativeTime: 5 + }); + + // === xdr source ============================================================ + // + // union ClaimPredicate switch (ClaimPredicateType type) + // { + // case CLAIM_PREDICATE_UNCONDITIONAL: + // void; + // case CLAIM_PREDICATE_AND: + // ClaimPredicate andPredicates<2>; + // case CLAIM_PREDICATE_OR: + // ClaimPredicate orPredicates<2>; + // case CLAIM_PREDICATE_NOT: + // ClaimPredicate* notPredicate; + // case CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME: + // int64 absBefore; // Predicate will be true if closeTime < absBefore + // case CLAIM_PREDICATE_BEFORE_RELATIVE_TIME: + // int64 relBefore; // Seconds since closeTime of the ledger in which the + // // ClaimableBalanceEntry was created + // }; + // + // =========================================================================== + xdr.union("ClaimPredicate", { + switchOn: xdr.lookup("ClaimPredicateType"), + switchName: "type", + switches: [["claimPredicateUnconditional", xdr["void"]()], ["claimPredicateAnd", "andPredicates"], ["claimPredicateOr", "orPredicates"], ["claimPredicateNot", "notPredicate"], ["claimPredicateBeforeAbsoluteTime", "absBefore"], ["claimPredicateBeforeRelativeTime", "relBefore"]], + arms: { + andPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2), + orPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2), + notPredicate: xdr.option(xdr.lookup("ClaimPredicate")), + absBefore: xdr.lookup("Int64"), + relBefore: xdr.lookup("Int64") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimantType + // { + // CLAIMANT_TYPE_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimantType", { + claimantTypeV0: 0 + }); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID destination; // The account that can use this condition + // ClaimPredicate predicate; // Claimable if predicate is true + // } + // + // =========================================================================== + xdr.struct("ClaimantV0", [["destination", xdr.lookup("AccountId")], ["predicate", xdr.lookup("ClaimPredicate")]]); + + // === xdr source ============================================================ + // + // union Claimant switch (ClaimantType type) + // { + // case CLAIMANT_TYPE_V0: + // struct + // { + // AccountID destination; // The account that can use this condition + // ClaimPredicate predicate; // Claimable if predicate is true + // } v0; + // }; + // + // =========================================================================== + xdr.union("Claimant", { + switchOn: xdr.lookup("ClaimantType"), + switchName: "type", + switches: [["claimantTypeV0", "v0"]], + arms: { + v0: xdr.lookup("ClaimantV0") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimableBalanceIDType + // { + // CLAIMABLE_BALANCE_ID_TYPE_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimableBalanceIdType", { + claimableBalanceIdTypeV0: 0 + }); + + // === xdr source ============================================================ + // + // union ClaimableBalanceID switch (ClaimableBalanceIDType type) + // { + // case CLAIMABLE_BALANCE_ID_TYPE_V0: + // Hash v0; + // }; + // + // =========================================================================== + xdr.union("ClaimableBalanceId", { + switchOn: xdr.lookup("ClaimableBalanceIdType"), + switchName: "type", + switches: [["claimableBalanceIdTypeV0", "v0"]], + arms: { + v0: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimableBalanceFlags + // { + // // If set, the issuer account of the asset held by the claimable balance may + // // clawback the claimable balance + // CLAIMABLE_BALANCE_CLAWBACK_ENABLED_FLAG = 0x1 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimableBalanceFlags", { + claimableBalanceClawbackEnabledFlag: 1 + }); + + // === xdr source ============================================================ + // + // const MASK_CLAIMABLE_BALANCE_FLAGS = 0x1; + // + // =========================================================================== + xdr["const"]("MASK_CLAIMABLE_BALANCE_FLAGS", 0x1); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("ClaimableBalanceEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct ClaimableBalanceEntryExtensionV1 + // { + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // + // uint32 flags; // see ClaimableBalanceFlags + // }; + // + // =========================================================================== + xdr.struct("ClaimableBalanceEntryExtensionV1", [["ext", xdr.lookup("ClaimableBalanceEntryExtensionV1Ext")], ["flags", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ClaimableBalanceEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("ClaimableBalanceEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("ClaimableBalanceEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct ClaimableBalanceEntry + // { + // // Unique identifier for this ClaimableBalanceEntry + // ClaimableBalanceID balanceID; + // + // // List of claimants with associated predicate + // Claimant claimants<10>; + // + // // Any asset including native + // Asset asset; + // + // // Amount of asset + // int64 amount; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ClaimableBalanceEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("ClaimableBalanceEntry", [["balanceId", xdr.lookup("ClaimableBalanceId")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["ext", xdr.lookup("ClaimableBalanceEntryExt")]]); + + // === xdr source ============================================================ + // + // struct LiquidityPoolConstantProductParameters + // { + // Asset assetA; // assetA < assetB + // Asset assetB; + // int32 fee; // Fee is in basis points, so the actual rate is (fee/100)% + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolConstantProductParameters", [["assetA", xdr.lookup("Asset")], ["assetB", xdr.lookup("Asset")], ["fee", xdr.lookup("Int32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } + // + // =========================================================================== + xdr.struct("LiquidityPoolEntryConstantProduct", [["params", xdr.lookup("LiquidityPoolConstantProductParameters")], ["reserveA", xdr.lookup("Int64")], ["reserveB", xdr.lookup("Int64")], ["totalPoolShares", xdr.lookup("Int64")], ["poolSharesTrustLineCount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } constantProduct; + // } + // + // =========================================================================== + xdr.union("LiquidityPoolEntryBody", { + switchOn: xdr.lookup("LiquidityPoolType"), + switchName: "type", + switches: [["liquidityPoolConstantProduct", "constantProduct"]], + arms: { + constantProduct: xdr.lookup("LiquidityPoolEntryConstantProduct") + } + }); + + // === xdr source ============================================================ + // + // struct LiquidityPoolEntry + // { + // PoolID liquidityPoolID; + // + // union switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } constantProduct; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolEntry", [["liquidityPoolId", xdr.lookup("PoolId")], ["body", xdr.lookup("LiquidityPoolEntryBody")]]); + + // === xdr source ============================================================ + // + // enum ContractDataDurability { + // TEMPORARY = 0, + // PERSISTENT = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractDataDurability", { + temporary: 0, + persistent: 1 + }); + + // === xdr source ============================================================ + // + // struct ContractDataEntry { + // ExtensionPoint ext; + // + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // SCVal val; + // }; + // + // =========================================================================== + xdr.struct("ContractDataEntry", [["ext", xdr.lookup("ExtensionPoint")], ["contract", xdr.lookup("ScAddress")], ["key", xdr.lookup("ScVal")], ["durability", xdr.lookup("ContractDataDurability")], ["val", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // struct ContractCodeCostInputs { + // ExtensionPoint ext; + // uint32 nInstructions; + // uint32 nFunctions; + // uint32 nGlobals; + // uint32 nTableEntries; + // uint32 nTypes; + // uint32 nDataSegments; + // uint32 nElemSegments; + // uint32 nImports; + // uint32 nExports; + // uint32 nDataSegmentBytes; + // }; + // + // =========================================================================== + xdr.struct("ContractCodeCostInputs", [["ext", xdr.lookup("ExtensionPoint")], ["nInstructions", xdr.lookup("Uint32")], ["nFunctions", xdr.lookup("Uint32")], ["nGlobals", xdr.lookup("Uint32")], ["nTableEntries", xdr.lookup("Uint32")], ["nTypes", xdr.lookup("Uint32")], ["nDataSegments", xdr.lookup("Uint32")], ["nElemSegments", xdr.lookup("Uint32")], ["nImports", xdr.lookup("Uint32")], ["nExports", xdr.lookup("Uint32")], ["nDataSegmentBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } + // + // =========================================================================== + xdr.struct("ContractCodeEntryV1", [["ext", xdr.lookup("ExtensionPoint")], ["costInputs", xdr.lookup("ContractCodeCostInputs")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } v1; + // } + // + // =========================================================================== + xdr.union("ContractCodeEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("ContractCodeEntryV1") + } + }); + + // === xdr source ============================================================ + // + // struct ContractCodeEntry { + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } v1; + // } ext; + // + // Hash hash; + // opaque code<>; + // }; + // + // =========================================================================== + xdr.struct("ContractCodeEntry", [["ext", xdr.lookup("ContractCodeEntryExt")], ["hash", xdr.lookup("Hash")], ["code", xdr.varOpaque()]]); + + // === xdr source ============================================================ + // + // struct TTLEntry { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // uint32 liveUntilLedgerSeq; + // }; + // + // =========================================================================== + xdr.struct("TtlEntry", [["keyHash", xdr.lookup("Hash")], ["liveUntilLedgerSeq", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerEntryExtensionV1 + // { + // SponsorshipDescriptor sponsoringID; + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerEntryExtensionV1", [["sponsoringId", xdr.lookup("SponsorshipDescriptor")], ["ext", xdr.lookup("LedgerEntryExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (LedgerEntryType type) + // { + // case ACCOUNT: + // AccountEntry account; + // case TRUSTLINE: + // TrustLineEntry trustLine; + // case OFFER: + // OfferEntry offer; + // case DATA: + // DataEntry data; + // case CLAIMABLE_BALANCE: + // ClaimableBalanceEntry claimableBalance; + // case LIQUIDITY_POOL: + // LiquidityPoolEntry liquidityPool; + // case CONTRACT_DATA: + // ContractDataEntry contractData; + // case CONTRACT_CODE: + // ContractCodeEntry contractCode; + // case CONFIG_SETTING: + // ConfigSettingEntry configSetting; + // case TTL: + // TTLEntry ttl; + // } + // + // =========================================================================== + xdr.union("LedgerEntryData", { + switchOn: xdr.lookup("LedgerEntryType"), + switchName: "type", + switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"], ["contractData", "contractData"], ["contractCode", "contractCode"], ["configSetting", "configSetting"], ["ttl", "ttl"]], + arms: { + account: xdr.lookup("AccountEntry"), + trustLine: xdr.lookup("TrustLineEntry"), + offer: xdr.lookup("OfferEntry"), + data: xdr.lookup("DataEntry"), + claimableBalance: xdr.lookup("ClaimableBalanceEntry"), + liquidityPool: xdr.lookup("LiquidityPoolEntry"), + contractData: xdr.lookup("ContractDataEntry"), + contractCode: xdr.lookup("ContractCodeEntry"), + configSetting: xdr.lookup("ConfigSettingEntry"), + ttl: xdr.lookup("TtlEntry") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("LedgerEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerEntry + // { + // uint32 lastModifiedLedgerSeq; // ledger the LedgerEntry was last changed + // + // union switch (LedgerEntryType type) + // { + // case ACCOUNT: + // AccountEntry account; + // case TRUSTLINE: + // TrustLineEntry trustLine; + // case OFFER: + // OfferEntry offer; + // case DATA: + // DataEntry data; + // case CLAIMABLE_BALANCE: + // ClaimableBalanceEntry claimableBalance; + // case LIQUIDITY_POOL: + // LiquidityPoolEntry liquidityPool; + // case CONTRACT_DATA: + // ContractDataEntry contractData; + // case CONTRACT_CODE: + // ContractCodeEntry contractCode; + // case CONFIG_SETTING: + // ConfigSettingEntry configSetting; + // case TTL: + // TTLEntry ttl; + // } + // data; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerEntry", [["lastModifiedLedgerSeq", xdr.lookup("Uint32")], ["data", xdr.lookup("LedgerEntryData")], ["ext", xdr.lookup("LedgerEntryExt")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyAccount", [["accountId", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // TrustLineAsset asset; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyTrustLine", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sellerID; + // int64 offerID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyOffer", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // string64 dataName; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyData", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimableBalanceID balanceID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyClaimableBalance", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // PoolID liquidityPoolID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyLiquidityPool", [["liquidityPoolId", xdr.lookup("PoolId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyContractData", [["contract", xdr.lookup("ScAddress")], ["key", xdr.lookup("ScVal")], ["durability", xdr.lookup("ContractDataDurability")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash hash; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyContractCode", [["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ConfigSettingID configSettingID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyConfigSetting", [["configSettingId", xdr.lookup("ConfigSettingId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyTtl", [["keyHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union LedgerKey switch (LedgerEntryType type) + // { + // case ACCOUNT: + // struct + // { + // AccountID accountID; + // } account; + // + // case TRUSTLINE: + // struct + // { + // AccountID accountID; + // TrustLineAsset asset; + // } trustLine; + // + // case OFFER: + // struct + // { + // AccountID sellerID; + // int64 offerID; + // } offer; + // + // case DATA: + // struct + // { + // AccountID accountID; + // string64 dataName; + // } data; + // + // case CLAIMABLE_BALANCE: + // struct + // { + // ClaimableBalanceID balanceID; + // } claimableBalance; + // + // case LIQUIDITY_POOL: + // struct + // { + // PoolID liquidityPoolID; + // } liquidityPool; + // case CONTRACT_DATA: + // struct + // { + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // } contractData; + // case CONTRACT_CODE: + // struct + // { + // Hash hash; + // } contractCode; + // case CONFIG_SETTING: + // struct + // { + // ConfigSettingID configSettingID; + // } configSetting; + // case TTL: + // struct + // { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // } ttl; + // }; + // + // =========================================================================== + xdr.union("LedgerKey", { + switchOn: xdr.lookup("LedgerEntryType"), + switchName: "type", + switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"], ["contractData", "contractData"], ["contractCode", "contractCode"], ["configSetting", "configSetting"], ["ttl", "ttl"]], + arms: { + account: xdr.lookup("LedgerKeyAccount"), + trustLine: xdr.lookup("LedgerKeyTrustLine"), + offer: xdr.lookup("LedgerKeyOffer"), + data: xdr.lookup("LedgerKeyData"), + claimableBalance: xdr.lookup("LedgerKeyClaimableBalance"), + liquidityPool: xdr.lookup("LedgerKeyLiquidityPool"), + contractData: xdr.lookup("LedgerKeyContractData"), + contractCode: xdr.lookup("LedgerKeyContractCode"), + configSetting: xdr.lookup("LedgerKeyConfigSetting"), + ttl: xdr.lookup("LedgerKeyTtl") + } + }); + + // === xdr source ============================================================ + // + // enum EnvelopeType + // { + // ENVELOPE_TYPE_TX_V0 = 0, + // ENVELOPE_TYPE_SCP = 1, + // ENVELOPE_TYPE_TX = 2, + // ENVELOPE_TYPE_AUTH = 3, + // ENVELOPE_TYPE_SCPVALUE = 4, + // ENVELOPE_TYPE_TX_FEE_BUMP = 5, + // ENVELOPE_TYPE_OP_ID = 6, + // ENVELOPE_TYPE_POOL_REVOKE_OP_ID = 7, + // ENVELOPE_TYPE_CONTRACT_ID = 8, + // ENVELOPE_TYPE_SOROBAN_AUTHORIZATION = 9 + // }; + // + // =========================================================================== + xdr["enum"]("EnvelopeType", { + envelopeTypeTxV0: 0, + envelopeTypeScp: 1, + envelopeTypeTx: 2, + envelopeTypeAuth: 3, + envelopeTypeScpvalue: 4, + envelopeTypeTxFeeBump: 5, + envelopeTypeOpId: 6, + envelopeTypePoolRevokeOpId: 7, + envelopeTypeContractId: 8, + envelopeTypeSorobanAuthorization: 9 + }); + + // === xdr source ============================================================ + // + // enum BucketListType + // { + // LIVE = 0, + // HOT_ARCHIVE = 1, + // COLD_ARCHIVE = 2 + // }; + // + // =========================================================================== + xdr["enum"]("BucketListType", { + live: 0, + hotArchive: 1, + coldArchive: 2 + }); + + // === xdr source ============================================================ + // + // enum BucketEntryType + // { + // METAENTRY = + // -1, // At-and-after protocol 11: bucket metadata, should come first. + // LIVEENTRY = 0, // Before protocol 11: created-or-updated; + // // At-and-after protocol 11: only updated. + // DEADENTRY = 1, + // INITENTRY = 2 // At-and-after protocol 11: only created. + // }; + // + // =========================================================================== + xdr["enum"]("BucketEntryType", { + metaentry: -1, + liveentry: 0, + deadentry: 1, + initentry: 2 + }); + + // === xdr source ============================================================ + // + // enum HotArchiveBucketEntryType + // { + // HOT_ARCHIVE_METAENTRY = -1, // Bucket metadata, should come first. + // HOT_ARCHIVE_ARCHIVED = 0, // Entry is Archived + // HOT_ARCHIVE_LIVE = 1, // Entry was previously HOT_ARCHIVE_ARCHIVED, or HOT_ARCHIVE_DELETED, but + // // has been added back to the live BucketList. + // // Does not need to be persisted. + // HOT_ARCHIVE_DELETED = 2 // Entry deleted (Note: must be persisted in archive) + // }; + // + // =========================================================================== + xdr["enum"]("HotArchiveBucketEntryType", { + hotArchiveMetaentry: -1, + hotArchiveArchived: 0, + hotArchiveLive: 1, + hotArchiveDeleted: 2 + }); + + // === xdr source ============================================================ + // + // enum ColdArchiveBucketEntryType + // { + // COLD_ARCHIVE_METAENTRY = -1, // Bucket metadata, should come first. + // COLD_ARCHIVE_ARCHIVED_LEAF = 0, // Full LedgerEntry that was archived during the epoch + // COLD_ARCHIVE_DELETED_LEAF = 1, // LedgerKey that was deleted during the epoch + // COLD_ARCHIVE_BOUNDARY_LEAF = 2, // Dummy leaf representing low/high bound + // COLD_ARCHIVE_HASH = 3 // Intermediary Merkle hash entry + // }; + // + // =========================================================================== + xdr["enum"]("ColdArchiveBucketEntryType", { + coldArchiveMetaentry: -1, + coldArchiveArchivedLeaf: 0, + coldArchiveDeletedLeaf: 1, + coldArchiveBoundaryLeaf: 2, + coldArchiveHash: 3 + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // BucketListType bucketListType; + // } + // + // =========================================================================== + xdr.union("BucketMetadataExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "bucketListType"]], + arms: { + bucketListType: xdr.lookup("BucketListType") + } + }); + + // === xdr source ============================================================ + // + // struct BucketMetadata + // { + // // Indicates the protocol version used to create / merge this bucket. + // uint32 ledgerVersion; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // BucketListType bucketListType; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("BucketMetadata", [["ledgerVersion", xdr.lookup("Uint32")], ["ext", xdr.lookup("BucketMetadataExt")]]); + + // === xdr source ============================================================ + // + // union BucketEntry switch (BucketEntryType type) + // { + // case LIVEENTRY: + // case INITENTRY: + // LedgerEntry liveEntry; + // + // case DEADENTRY: + // LedgerKey deadEntry; + // case METAENTRY: + // BucketMetadata metaEntry; + // }; + // + // =========================================================================== + xdr.union("BucketEntry", { + switchOn: xdr.lookup("BucketEntryType"), + switchName: "type", + switches: [["liveentry", "liveEntry"], ["initentry", "liveEntry"], ["deadentry", "deadEntry"], ["metaentry", "metaEntry"]], + arms: { + liveEntry: xdr.lookup("LedgerEntry"), + deadEntry: xdr.lookup("LedgerKey"), + metaEntry: xdr.lookup("BucketMetadata") + } + }); + + // === xdr source ============================================================ + // + // union HotArchiveBucketEntry switch (HotArchiveBucketEntryType type) + // { + // case HOT_ARCHIVE_ARCHIVED: + // LedgerEntry archivedEntry; + // + // case HOT_ARCHIVE_LIVE: + // case HOT_ARCHIVE_DELETED: + // LedgerKey key; + // case HOT_ARCHIVE_METAENTRY: + // BucketMetadata metaEntry; + // }; + // + // =========================================================================== + xdr.union("HotArchiveBucketEntry", { + switchOn: xdr.lookup("HotArchiveBucketEntryType"), + switchName: "type", + switches: [["hotArchiveArchived", "archivedEntry"], ["hotArchiveLive", "key"], ["hotArchiveDeleted", "key"], ["hotArchiveMetaentry", "metaEntry"]], + arms: { + archivedEntry: xdr.lookup("LedgerEntry"), + key: xdr.lookup("LedgerKey"), + metaEntry: xdr.lookup("BucketMetadata") + } + }); + + // === xdr source ============================================================ + // + // struct ColdArchiveArchivedLeaf + // { + // uint32 index; + // LedgerEntry archivedEntry; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveArchivedLeaf", [["index", xdr.lookup("Uint32")], ["archivedEntry", xdr.lookup("LedgerEntry")]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveDeletedLeaf + // { + // uint32 index; + // LedgerKey deletedKey; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveDeletedLeaf", [["index", xdr.lookup("Uint32")], ["deletedKey", xdr.lookup("LedgerKey")]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveBoundaryLeaf + // { + // uint32 index; + // bool isLowerBound; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveBoundaryLeaf", [["index", xdr.lookup("Uint32")], ["isLowerBound", xdr.bool()]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveHashEntry + // { + // uint32 index; + // uint32 level; + // Hash hash; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveHashEntry", [["index", xdr.lookup("Uint32")], ["level", xdr.lookup("Uint32")], ["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union ColdArchiveBucketEntry switch (ColdArchiveBucketEntryType type) + // { + // case COLD_ARCHIVE_METAENTRY: + // BucketMetadata metaEntry; + // case COLD_ARCHIVE_ARCHIVED_LEAF: + // ColdArchiveArchivedLeaf archivedLeaf; + // case COLD_ARCHIVE_DELETED_LEAF: + // ColdArchiveDeletedLeaf deletedLeaf; + // case COLD_ARCHIVE_BOUNDARY_LEAF: + // ColdArchiveBoundaryLeaf boundaryLeaf; + // case COLD_ARCHIVE_HASH: + // ColdArchiveHashEntry hashEntry; + // }; + // + // =========================================================================== + xdr.union("ColdArchiveBucketEntry", { + switchOn: xdr.lookup("ColdArchiveBucketEntryType"), + switchName: "type", + switches: [["coldArchiveMetaentry", "metaEntry"], ["coldArchiveArchivedLeaf", "archivedLeaf"], ["coldArchiveDeletedLeaf", "deletedLeaf"], ["coldArchiveBoundaryLeaf", "boundaryLeaf"], ["coldArchiveHash", "hashEntry"]], + arms: { + metaEntry: xdr.lookup("BucketMetadata"), + archivedLeaf: xdr.lookup("ColdArchiveArchivedLeaf"), + deletedLeaf: xdr.lookup("ColdArchiveDeletedLeaf"), + boundaryLeaf: xdr.lookup("ColdArchiveBoundaryLeaf"), + hashEntry: xdr.lookup("ColdArchiveHashEntry") + } + }); + + // === xdr source ============================================================ + // + // typedef opaque UpgradeType<128>; + // + // =========================================================================== + xdr.typedef("UpgradeType", xdr.varOpaque(128)); + + // === xdr source ============================================================ + // + // enum StellarValueType + // { + // STELLAR_VALUE_BASIC = 0, + // STELLAR_VALUE_SIGNED = 1 + // }; + // + // =========================================================================== + xdr["enum"]("StellarValueType", { + stellarValueBasic: 0, + stellarValueSigned: 1 + }); + + // === xdr source ============================================================ + // + // struct LedgerCloseValueSignature + // { + // NodeID nodeID; // which node introduced the value + // Signature signature; // nodeID's signature + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseValueSignature", [["nodeId", xdr.lookup("NodeId")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // union switch (StellarValueType v) + // { + // case STELLAR_VALUE_BASIC: + // void; + // case STELLAR_VALUE_SIGNED: + // LedgerCloseValueSignature lcValueSignature; + // } + // + // =========================================================================== + xdr.union("StellarValueExt", { + switchOn: xdr.lookup("StellarValueType"), + switchName: "v", + switches: [["stellarValueBasic", xdr["void"]()], ["stellarValueSigned", "lcValueSignature"]], + arms: { + lcValueSignature: xdr.lookup("LedgerCloseValueSignature") + } + }); + + // === xdr source ============================================================ + // + // struct StellarValue + // { + // Hash txSetHash; // transaction set to apply to previous ledger + // TimePoint closeTime; // network close time + // + // // upgrades to apply to the previous ledger (usually empty) + // // this is a vector of encoded 'LedgerUpgrade' so that nodes can drop + // // unknown steps during consensus if needed. + // // see notes below on 'LedgerUpgrade' for more detail + // // max size is dictated by number of upgrade types (+ room for future) + // UpgradeType upgrades<6>; + // + // // reserved for future use + // union switch (StellarValueType v) + // { + // case STELLAR_VALUE_BASIC: + // void; + // case STELLAR_VALUE_SIGNED: + // LedgerCloseValueSignature lcValueSignature; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("StellarValue", [["txSetHash", xdr.lookup("Hash")], ["closeTime", xdr.lookup("TimePoint")], ["upgrades", xdr.varArray(xdr.lookup("UpgradeType"), 6)], ["ext", xdr.lookup("StellarValueExt")]]); + + // === xdr source ============================================================ + // + // const MASK_LEDGER_HEADER_FLAGS = 0x7; + // + // =========================================================================== + xdr["const"]("MASK_LEDGER_HEADER_FLAGS", 0x7); + + // === xdr source ============================================================ + // + // enum LedgerHeaderFlags + // { + // DISABLE_LIQUIDITY_POOL_TRADING_FLAG = 0x1, + // DISABLE_LIQUIDITY_POOL_DEPOSIT_FLAG = 0x2, + // DISABLE_LIQUIDITY_POOL_WITHDRAWAL_FLAG = 0x4 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerHeaderFlags", { + disableLiquidityPoolTradingFlag: 1, + disableLiquidityPoolDepositFlag: 2, + disableLiquidityPoolWithdrawalFlag: 4 + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerHeaderExtensionV1 + // { + // uint32 flags; // LedgerHeaderFlags + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeaderExtensionV1", [["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("LedgerHeaderExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerHeaderExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerHeaderExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerHeader + // { + // uint32 ledgerVersion; // the protocol version of the ledger + // Hash previousLedgerHash; // hash of the previous ledger header + // StellarValue scpValue; // what consensus agreed to + // Hash txSetResultHash; // the TransactionResultSet that led to this ledger + // Hash bucketListHash; // hash of the ledger state + // + // uint32 ledgerSeq; // sequence number of this ledger + // + // int64 totalCoins; // total number of stroops in existence. + // // 10,000,000 stroops in 1 XLM + // + // int64 feePool; // fees burned since last inflation run + // uint32 inflationSeq; // inflation sequence number + // + // uint64 idPool; // last used global ID, used for generating objects + // + // uint32 baseFee; // base fee per operation in stroops + // uint32 baseReserve; // account base reserve in stroops + // + // uint32 maxTxSetSize; // maximum size a transaction set can be + // + // Hash skipList[4]; // hashes of ledgers in the past. allows you to jump back + // // in time without walking the chain back ledger by ledger + // // each slot contains the oldest ledger that is mod of + // // either 50 5000 50000 or 500000 depending on index + // // skipList[0] mod(50), skipList[1] mod(5000), etc + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerHeaderExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeader", [["ledgerVersion", xdr.lookup("Uint32")], ["previousLedgerHash", xdr.lookup("Hash")], ["scpValue", xdr.lookup("StellarValue")], ["txSetResultHash", xdr.lookup("Hash")], ["bucketListHash", xdr.lookup("Hash")], ["ledgerSeq", xdr.lookup("Uint32")], ["totalCoins", xdr.lookup("Int64")], ["feePool", xdr.lookup("Int64")], ["inflationSeq", xdr.lookup("Uint32")], ["idPool", xdr.lookup("Uint64")], ["baseFee", xdr.lookup("Uint32")], ["baseReserve", xdr.lookup("Uint32")], ["maxTxSetSize", xdr.lookup("Uint32")], ["skipList", xdr.array(xdr.lookup("Hash"), 4)], ["ext", xdr.lookup("LedgerHeaderExt")]]); + + // === xdr source ============================================================ + // + // enum LedgerUpgradeType + // { + // LEDGER_UPGRADE_VERSION = 1, + // LEDGER_UPGRADE_BASE_FEE = 2, + // LEDGER_UPGRADE_MAX_TX_SET_SIZE = 3, + // LEDGER_UPGRADE_BASE_RESERVE = 4, + // LEDGER_UPGRADE_FLAGS = 5, + // LEDGER_UPGRADE_CONFIG = 6, + // LEDGER_UPGRADE_MAX_SOROBAN_TX_SET_SIZE = 7 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerUpgradeType", { + ledgerUpgradeVersion: 1, + ledgerUpgradeBaseFee: 2, + ledgerUpgradeMaxTxSetSize: 3, + ledgerUpgradeBaseReserve: 4, + ledgerUpgradeFlags: 5, + ledgerUpgradeConfig: 6, + ledgerUpgradeMaxSorobanTxSetSize: 7 + }); + + // === xdr source ============================================================ + // + // struct ConfigUpgradeSetKey { + // Hash contractID; + // Hash contentHash; + // }; + // + // =========================================================================== + xdr.struct("ConfigUpgradeSetKey", [["contractId", xdr.lookup("Hash")], ["contentHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union LedgerUpgrade switch (LedgerUpgradeType type) + // { + // case LEDGER_UPGRADE_VERSION: + // uint32 newLedgerVersion; // update ledgerVersion + // case LEDGER_UPGRADE_BASE_FEE: + // uint32 newBaseFee; // update baseFee + // case LEDGER_UPGRADE_MAX_TX_SET_SIZE: + // uint32 newMaxTxSetSize; // update maxTxSetSize + // case LEDGER_UPGRADE_BASE_RESERVE: + // uint32 newBaseReserve; // update baseReserve + // case LEDGER_UPGRADE_FLAGS: + // uint32 newFlags; // update flags + // case LEDGER_UPGRADE_CONFIG: + // // Update arbitrary `ConfigSetting` entries identified by the key. + // ConfigUpgradeSetKey newConfig; + // case LEDGER_UPGRADE_MAX_SOROBAN_TX_SET_SIZE: + // // Update ConfigSettingContractExecutionLanesV0.ledgerMaxTxCount without + // // using `LEDGER_UPGRADE_CONFIG`. + // uint32 newMaxSorobanTxSetSize; + // }; + // + // =========================================================================== + xdr.union("LedgerUpgrade", { + switchOn: xdr.lookup("LedgerUpgradeType"), + switchName: "type", + switches: [["ledgerUpgradeVersion", "newLedgerVersion"], ["ledgerUpgradeBaseFee", "newBaseFee"], ["ledgerUpgradeMaxTxSetSize", "newMaxTxSetSize"], ["ledgerUpgradeBaseReserve", "newBaseReserve"], ["ledgerUpgradeFlags", "newFlags"], ["ledgerUpgradeConfig", "newConfig"], ["ledgerUpgradeMaxSorobanTxSetSize", "newMaxSorobanTxSetSize"]], + arms: { + newLedgerVersion: xdr.lookup("Uint32"), + newBaseFee: xdr.lookup("Uint32"), + newMaxTxSetSize: xdr.lookup("Uint32"), + newBaseReserve: xdr.lookup("Uint32"), + newFlags: xdr.lookup("Uint32"), + newConfig: xdr.lookup("ConfigUpgradeSetKey"), + newMaxSorobanTxSetSize: xdr.lookup("Uint32") + } + }); + + // === xdr source ============================================================ + // + // struct ConfigUpgradeSet { + // ConfigSettingEntry updatedEntry<>; + // }; + // + // =========================================================================== + xdr.struct("ConfigUpgradeSet", [["updatedEntry", xdr.varArray(xdr.lookup("ConfigSettingEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // enum TxSetComponentType + // { + // // txs with effective fee <= bid derived from a base fee (if any). + // // If base fee is not specified, no discount is applied. + // TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE = 0 + // }; + // + // =========================================================================== + xdr["enum"]("TxSetComponentType", { + txsetCompTxsMaybeDiscountedFee: 0 + }); + + // === xdr source ============================================================ + // + // struct + // { + // int64* baseFee; + // TransactionEnvelope txs<>; + // } + // + // =========================================================================== + xdr.struct("TxSetComponentTxsMaybeDiscountedFee", [["baseFee", xdr.option(xdr.lookup("Int64"))], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union TxSetComponent switch (TxSetComponentType type) + // { + // case TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE: + // struct + // { + // int64* baseFee; + // TransactionEnvelope txs<>; + // } txsMaybeDiscountedFee; + // }; + // + // =========================================================================== + xdr.union("TxSetComponent", { + switchOn: xdr.lookup("TxSetComponentType"), + switchName: "type", + switches: [["txsetCompTxsMaybeDiscountedFee", "txsMaybeDiscountedFee"]], + arms: { + txsMaybeDiscountedFee: xdr.lookup("TxSetComponentTxsMaybeDiscountedFee") + } + }); + + // === xdr source ============================================================ + // + // union TransactionPhase switch (int v) + // { + // case 0: + // TxSetComponent v0Components<>; + // }; + // + // =========================================================================== + xdr.union("TransactionPhase", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0Components"]], + arms: { + v0Components: xdr.varArray(xdr.lookup("TxSetComponent"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // struct TransactionSet + // { + // Hash previousLedgerHash; + // TransactionEnvelope txs<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionSet", [["previousLedgerHash", xdr.lookup("Hash")], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionSetV1 + // { + // Hash previousLedgerHash; + // TransactionPhase phases<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionSetV1", [["previousLedgerHash", xdr.lookup("Hash")], ["phases", xdr.varArray(xdr.lookup("TransactionPhase"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union GeneralizedTransactionSet switch (int v) + // { + // // We consider the legacy TransactionSet to be v0. + // case 1: + // TransactionSetV1 v1TxSet; + // }; + // + // =========================================================================== + xdr.union("GeneralizedTransactionSet", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[1, "v1TxSet"]], + arms: { + v1TxSet: xdr.lookup("TransactionSetV1") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionResultPair + // { + // Hash transactionHash; + // TransactionResult result; // result for the transaction + // }; + // + // =========================================================================== + xdr.struct("TransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("TransactionResult")]]); + + // === xdr source ============================================================ + // + // struct TransactionResultSet + // { + // TransactionResultPair results<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionResultSet", [["results", xdr.varArray(xdr.lookup("TransactionResultPair"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // GeneralizedTransactionSet generalizedTxSet; + // } + // + // =========================================================================== + xdr.union("TransactionHistoryEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "generalizedTxSet"]], + arms: { + generalizedTxSet: xdr.lookup("GeneralizedTransactionSet") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionHistoryEntry + // { + // uint32 ledgerSeq; + // TransactionSet txSet; + // + // // when v != 0, txSet must be empty + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // GeneralizedTransactionSet generalizedTxSet; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionHistoryEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txSet", xdr.lookup("TransactionSet")], ["ext", xdr.lookup("TransactionHistoryEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionHistoryResultEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionHistoryResultEntry + // { + // uint32 ledgerSeq; + // TransactionResultSet txResultSet; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionHistoryResultEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txResultSet", xdr.lookup("TransactionResultSet")], ["ext", xdr.lookup("TransactionHistoryResultEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderHistoryEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerHeaderHistoryEntry + // { + // Hash hash; + // LedgerHeader header; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeaderHistoryEntry", [["hash", xdr.lookup("Hash")], ["header", xdr.lookup("LedgerHeader")], ["ext", xdr.lookup("LedgerHeaderHistoryEntryExt")]]); + + // === xdr source ============================================================ + // + // struct LedgerSCPMessages + // { + // uint32 ledgerSeq; + // SCPEnvelope messages<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerScpMessages", [["ledgerSeq", xdr.lookup("Uint32")], ["messages", xdr.varArray(xdr.lookup("ScpEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct SCPHistoryEntryV0 + // { + // SCPQuorumSet quorumSets<>; // additional quorum sets used by ledgerMessages + // LedgerSCPMessages ledgerMessages; + // }; + // + // =========================================================================== + xdr.struct("ScpHistoryEntryV0", [["quorumSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)], ["ledgerMessages", xdr.lookup("LedgerScpMessages")]]); + + // === xdr source ============================================================ + // + // union SCPHistoryEntry switch (int v) + // { + // case 0: + // SCPHistoryEntryV0 v0; + // }; + // + // =========================================================================== + xdr.union("ScpHistoryEntry", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("ScpHistoryEntryV0") + } + }); + + // === xdr source ============================================================ + // + // enum LedgerEntryChangeType + // { + // LEDGER_ENTRY_CREATED = 0, // entry was added to the ledger + // LEDGER_ENTRY_UPDATED = 1, // entry was modified in the ledger + // LEDGER_ENTRY_REMOVED = 2, // entry was removed from the ledger + // LEDGER_ENTRY_STATE = 3 // value of the entry + // }; + // + // =========================================================================== + xdr["enum"]("LedgerEntryChangeType", { + ledgerEntryCreated: 0, + ledgerEntryUpdated: 1, + ledgerEntryRemoved: 2, + ledgerEntryState: 3 + }); + + // === xdr source ============================================================ + // + // union LedgerEntryChange switch (LedgerEntryChangeType type) + // { + // case LEDGER_ENTRY_CREATED: + // LedgerEntry created; + // case LEDGER_ENTRY_UPDATED: + // LedgerEntry updated; + // case LEDGER_ENTRY_REMOVED: + // LedgerKey removed; + // case LEDGER_ENTRY_STATE: + // LedgerEntry state; + // }; + // + // =========================================================================== + xdr.union("LedgerEntryChange", { + switchOn: xdr.lookup("LedgerEntryChangeType"), + switchName: "type", + switches: [["ledgerEntryCreated", "created"], ["ledgerEntryUpdated", "updated"], ["ledgerEntryRemoved", "removed"], ["ledgerEntryState", "state"]], + arms: { + created: xdr.lookup("LedgerEntry"), + updated: xdr.lookup("LedgerEntry"), + removed: xdr.lookup("LedgerKey"), + state: xdr.lookup("LedgerEntry") + } + }); + + // === xdr source ============================================================ + // + // typedef LedgerEntryChange LedgerEntryChanges<>; + // + // =========================================================================== + xdr.typedef("LedgerEntryChanges", xdr.varArray(xdr.lookup("LedgerEntryChange"), 2147483647)); + + // === xdr source ============================================================ + // + // struct OperationMeta + // { + // LedgerEntryChanges changes; + // }; + // + // =========================================================================== + xdr.struct("OperationMeta", [["changes", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV1 + // { + // LedgerEntryChanges txChanges; // tx level changes if any + // OperationMeta operations<>; // meta for each operation + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV1", [["txChanges", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV2 + // { + // LedgerEntryChanges txChangesBefore; // tx level changes before operations + // // are applied if any + // OperationMeta operations<>; // meta for each operation + // LedgerEntryChanges txChangesAfter; // tx level changes after operations are + // // applied if any + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV2", [["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // enum ContractEventType + // { + // SYSTEM = 0, + // CONTRACT = 1, + // DIAGNOSTIC = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ContractEventType", { + system: 0, + contract: 1, + diagnostic: 2 + }); + + // === xdr source ============================================================ + // + // struct + // { + // SCVal topics<>; + // SCVal data; + // } + // + // =========================================================================== + xdr.struct("ContractEventV0", [["topics", xdr.varArray(xdr.lookup("ScVal"), 2147483647)], ["data", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // struct + // { + // SCVal topics<>; + // SCVal data; + // } v0; + // } + // + // =========================================================================== + xdr.union("ContractEventBody", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("ContractEventV0") + } + }); + + // === xdr source ============================================================ + // + // struct ContractEvent + // { + // // We can use this to add more fields, or because it + // // is first, to change ContractEvent into a union. + // ExtensionPoint ext; + // + // Hash* contractID; + // ContractEventType type; + // + // union switch (int v) + // { + // case 0: + // struct + // { + // SCVal topics<>; + // SCVal data; + // } v0; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("ContractEvent", [["ext", xdr.lookup("ExtensionPoint")], ["contractId", xdr.option(xdr.lookup("Hash"))], ["type", xdr.lookup("ContractEventType")], ["body", xdr.lookup("ContractEventBody")]]); + + // === xdr source ============================================================ + // + // struct DiagnosticEvent + // { + // bool inSuccessfulContractCall; + // ContractEvent event; + // }; + // + // =========================================================================== + xdr.struct("DiagnosticEvent", [["inSuccessfulContractCall", xdr.bool()], ["event", xdr.lookup("ContractEvent")]]); + + // === xdr source ============================================================ + // + // typedef DiagnosticEvent DiagnosticEvents<>; + // + // =========================================================================== + xdr.typedef("DiagnosticEvents", xdr.varArray(xdr.lookup("DiagnosticEvent"), 2147483647)); + + // === xdr source ============================================================ + // + // struct SorobanTransactionMetaExtV1 + // { + // ExtensionPoint ext; + // + // // The following are the components of the overall Soroban resource fee + // // charged for the transaction. + // // The following relation holds: + // // `resourceFeeCharged = totalNonRefundableResourceFeeCharged + totalRefundableResourceFeeCharged` + // // where `resourceFeeCharged` is the overall fee charged for the + // // transaction. Also, `resourceFeeCharged` <= `sorobanData.resourceFee` + // // i.e.we never charge more than the declared resource fee. + // // The inclusion fee for charged the Soroban transaction can be found using + // // the following equation: + // // `result.feeCharged = resourceFeeCharged + inclusionFeeCharged`. + // + // // Total amount (in stroops) that has been charged for non-refundable + // // Soroban resources. + // // Non-refundable resources are charged based on the usage declared in + // // the transaction envelope (such as `instructions`, `readBytes` etc.) and + // // is charged regardless of the success of the transaction. + // int64 totalNonRefundableResourceFeeCharged; + // // Total amount (in stroops) that has been charged for refundable + // // Soroban resource fees. + // // Currently this comprises the rent fee (`rentFeeCharged`) and the + // // fee for the events and return value. + // // Refundable resources are charged based on the actual resources usage. + // // Since currently refundable resources are only used for the successful + // // transactions, this will be `0` for failed transactions. + // int64 totalRefundableResourceFeeCharged; + // // Amount (in stroops) that has been charged for rent. + // // This is a part of `totalNonRefundableResourceFeeCharged`. + // int64 rentFeeCharged; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionMetaExtV1", [["ext", xdr.lookup("ExtensionPoint")], ["totalNonRefundableResourceFeeCharged", xdr.lookup("Int64")], ["totalRefundableResourceFeeCharged", xdr.lookup("Int64")], ["rentFeeCharged", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union SorobanTransactionMetaExt switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionMetaExtV1 v1; + // }; + // + // =========================================================================== + xdr.union("SorobanTransactionMetaExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("SorobanTransactionMetaExtV1") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanTransactionMeta + // { + // SorobanTransactionMetaExt ext; + // + // ContractEvent events<>; // custom events populated by the + // // contracts themselves. + // SCVal returnValue; // return value of the host fn invocation + // + // // Diagnostics events that are not hashed. + // // This will contain all contract and diagnostic events. Even ones + // // that were emitted in a failed contract call. + // DiagnosticEvent diagnosticEvents<>; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionMeta", [["ext", xdr.lookup("SorobanTransactionMetaExt")], ["events", xdr.varArray(xdr.lookup("ContractEvent"), 2147483647)], ["returnValue", xdr.lookup("ScVal")], ["diagnosticEvents", xdr.varArray(xdr.lookup("DiagnosticEvent"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV3 + // { + // ExtensionPoint ext; + // + // LedgerEntryChanges txChangesBefore; // tx level changes before operations + // // are applied if any + // OperationMeta operations<>; // meta for each operation + // LedgerEntryChanges txChangesAfter; // tx level changes after operations are + // // applied if any + // SorobanTransactionMeta* sorobanMeta; // Soroban-specific meta (only for + // // Soroban transactions). + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV3", [["ext", xdr.lookup("ExtensionPoint")], ["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")], ["sorobanMeta", xdr.option(xdr.lookup("SorobanTransactionMeta"))]]); + + // === xdr source ============================================================ + // + // struct InvokeHostFunctionSuccessPreImage + // { + // SCVal returnValue; + // ContractEvent events<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeHostFunctionSuccessPreImage", [["returnValue", xdr.lookup("ScVal")], ["events", xdr.varArray(xdr.lookup("ContractEvent"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union TransactionMeta switch (int v) + // { + // case 0: + // OperationMeta operations<>; + // case 1: + // TransactionMetaV1 v1; + // case 2: + // TransactionMetaV2 v2; + // case 3: + // TransactionMetaV3 v3; + // }; + // + // =========================================================================== + xdr.union("TransactionMeta", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "operations"], [1, "v1"], [2, "v2"], [3, "v3"]], + arms: { + operations: xdr.varArray(xdr.lookup("OperationMeta"), 2147483647), + v1: xdr.lookup("TransactionMetaV1"), + v2: xdr.lookup("TransactionMetaV2"), + v3: xdr.lookup("TransactionMetaV3") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionResultMeta + // { + // TransactionResultPair result; + // LedgerEntryChanges feeProcessing; + // TransactionMeta txApplyProcessing; + // }; + // + // =========================================================================== + xdr.struct("TransactionResultMeta", [["result", xdr.lookup("TransactionResultPair")], ["feeProcessing", xdr.lookup("LedgerEntryChanges")], ["txApplyProcessing", xdr.lookup("TransactionMeta")]]); + + // === xdr source ============================================================ + // + // struct UpgradeEntryMeta + // { + // LedgerUpgrade upgrade; + // LedgerEntryChanges changes; + // }; + // + // =========================================================================== + xdr.struct("UpgradeEntryMeta", [["upgrade", xdr.lookup("LedgerUpgrade")], ["changes", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaV0 + // { + // LedgerHeaderHistoryEntry ledgerHeader; + // // NB: txSet is sorted in "Hash order" + // TransactionSet txSet; + // + // // NB: transactions are sorted in apply order here + // // fees for all transactions are processed first + // // followed by applying transactions + // TransactionResultMeta txProcessing<>; + // + // // upgrades are applied last + // UpgradeEntryMeta upgradesProcessing<>; + // + // // other misc information attached to the ledger close + // SCPHistoryEntry scpInfo<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaV0", [["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("TransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaExtV1 + // { + // ExtensionPoint ext; + // int64 sorobanFeeWrite1KB; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaExtV1", [["ext", xdr.lookup("ExtensionPoint")], ["sorobanFeeWrite1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union LedgerCloseMetaExt switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerCloseMetaExtV1 v1; + // }; + // + // =========================================================================== + xdr.union("LedgerCloseMetaExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerCloseMetaExtV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaV1 + // { + // LedgerCloseMetaExt ext; + // + // LedgerHeaderHistoryEntry ledgerHeader; + // + // GeneralizedTransactionSet txSet; + // + // // NB: transactions are sorted in apply order here + // // fees for all transactions are processed first + // // followed by applying transactions + // TransactionResultMeta txProcessing<>; + // + // // upgrades are applied last + // UpgradeEntryMeta upgradesProcessing<>; + // + // // other misc information attached to the ledger close + // SCPHistoryEntry scpInfo<>; + // + // // Size in bytes of BucketList, to support downstream + // // systems calculating storage fees correctly. + // uint64 totalByteSizeOfBucketList; + // + // // Temp keys that are being evicted at this ledger. + // LedgerKey evictedTemporaryLedgerKeys<>; + // + // // Archived restorable ledger entries that are being + // // evicted at this ledger. + // LedgerEntry evictedPersistentLedgerEntries<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaV1", [["ext", xdr.lookup("LedgerCloseMetaExt")], ["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("GeneralizedTransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)], ["totalByteSizeOfBucketList", xdr.lookup("Uint64")], ["evictedTemporaryLedgerKeys", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["evictedPersistentLedgerEntries", xdr.varArray(xdr.lookup("LedgerEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union LedgerCloseMeta switch (int v) + // { + // case 0: + // LedgerCloseMetaV0 v0; + // case 1: + // LedgerCloseMetaV1 v1; + // }; + // + // =========================================================================== + xdr.union("LedgerCloseMeta", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"], [1, "v1"]], + arms: { + v0: xdr.lookup("LedgerCloseMetaV0"), + v1: xdr.lookup("LedgerCloseMetaV1") + } + }); + + // === xdr source ============================================================ + // + // enum ErrorCode + // { + // ERR_MISC = 0, // Unspecific error + // ERR_DATA = 1, // Malformed data + // ERR_CONF = 2, // Misconfiguration error + // ERR_AUTH = 3, // Authentication failure + // ERR_LOAD = 4 // System overloaded + // }; + // + // =========================================================================== + xdr["enum"]("ErrorCode", { + errMisc: 0, + errData: 1, + errConf: 2, + errAuth: 3, + errLoad: 4 + }); + + // === xdr source ============================================================ + // + // struct Error + // { + // ErrorCode code; + // string msg<100>; + // }; + // + // =========================================================================== + xdr.struct("Error", [["code", xdr.lookup("ErrorCode")], ["msg", xdr.string(100)]]); + + // === xdr source ============================================================ + // + // struct SendMore + // { + // uint32 numMessages; + // }; + // + // =========================================================================== + xdr.struct("SendMore", [["numMessages", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SendMoreExtended + // { + // uint32 numMessages; + // uint32 numBytes; + // }; + // + // =========================================================================== + xdr.struct("SendMoreExtended", [["numMessages", xdr.lookup("Uint32")], ["numBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct AuthCert + // { + // Curve25519Public pubkey; + // uint64 expiration; + // Signature sig; + // }; + // + // =========================================================================== + xdr.struct("AuthCert", [["pubkey", xdr.lookup("Curve25519Public")], ["expiration", xdr.lookup("Uint64")], ["sig", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // struct Hello + // { + // uint32 ledgerVersion; + // uint32 overlayVersion; + // uint32 overlayMinVersion; + // Hash networkID; + // string versionStr<100>; + // int listeningPort; + // NodeID peerID; + // AuthCert cert; + // uint256 nonce; + // }; + // + // =========================================================================== + xdr.struct("Hello", [["ledgerVersion", xdr.lookup("Uint32")], ["overlayVersion", xdr.lookup("Uint32")], ["overlayMinVersion", xdr.lookup("Uint32")], ["networkId", xdr.lookup("Hash")], ["versionStr", xdr.string(100)], ["listeningPort", xdr["int"]()], ["peerId", xdr.lookup("NodeId")], ["cert", xdr.lookup("AuthCert")], ["nonce", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // const AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED = 200; + // + // =========================================================================== + xdr["const"]("AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED", 200); + + // === xdr source ============================================================ + // + // struct Auth + // { + // int flags; + // }; + // + // =========================================================================== + xdr.struct("Auth", [["flags", xdr["int"]()]]); + + // === xdr source ============================================================ + // + // enum IPAddrType + // { + // IPv4 = 0, + // IPv6 = 1 + // }; + // + // =========================================================================== + xdr["enum"]("IpAddrType", { + iPv4: 0, + iPv6: 1 + }); + + // === xdr source ============================================================ + // + // union switch (IPAddrType type) + // { + // case IPv4: + // opaque ipv4[4]; + // case IPv6: + // opaque ipv6[16]; + // } + // + // =========================================================================== + xdr.union("PeerAddressIp", { + switchOn: xdr.lookup("IpAddrType"), + switchName: "type", + switches: [["iPv4", "ipv4"], ["iPv6", "ipv6"]], + arms: { + ipv4: xdr.opaque(4), + ipv6: xdr.opaque(16) + } + }); + + // === xdr source ============================================================ + // + // struct PeerAddress + // { + // union switch (IPAddrType type) + // { + // case IPv4: + // opaque ipv4[4]; + // case IPv6: + // opaque ipv6[16]; + // } + // ip; + // uint32 port; + // uint32 numFailures; + // }; + // + // =========================================================================== + xdr.struct("PeerAddress", [["ip", xdr.lookup("PeerAddressIp")], ["port", xdr.lookup("Uint32")], ["numFailures", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // enum MessageType + // { + // ERROR_MSG = 0, + // AUTH = 2, + // DONT_HAVE = 3, + // + // GET_PEERS = 4, // gets a list of peers this guy knows about + // PEERS = 5, + // + // GET_TX_SET = 6, // gets a particular txset by hash + // TX_SET = 7, + // GENERALIZED_TX_SET = 17, + // + // TRANSACTION = 8, // pass on a tx you have heard about + // + // // SCP + // GET_SCP_QUORUMSET = 9, + // SCP_QUORUMSET = 10, + // SCP_MESSAGE = 11, + // GET_SCP_STATE = 12, + // + // // new messages + // HELLO = 13, + // + // SURVEY_REQUEST = 14, + // SURVEY_RESPONSE = 15, + // + // SEND_MORE = 16, + // SEND_MORE_EXTENDED = 20, + // + // FLOOD_ADVERT = 18, + // FLOOD_DEMAND = 19, + // + // TIME_SLICED_SURVEY_REQUEST = 21, + // TIME_SLICED_SURVEY_RESPONSE = 22, + // TIME_SLICED_SURVEY_START_COLLECTING = 23, + // TIME_SLICED_SURVEY_STOP_COLLECTING = 24 + // }; + // + // =========================================================================== + xdr["enum"]("MessageType", { + errorMsg: 0, + auth: 2, + dontHave: 3, + getPeers: 4, + peers: 5, + getTxSet: 6, + txSet: 7, + generalizedTxSet: 17, + transaction: 8, + getScpQuorumset: 9, + scpQuorumset: 10, + scpMessage: 11, + getScpState: 12, + hello: 13, + surveyRequest: 14, + surveyResponse: 15, + sendMore: 16, + sendMoreExtended: 20, + floodAdvert: 18, + floodDemand: 19, + timeSlicedSurveyRequest: 21, + timeSlicedSurveyResponse: 22, + timeSlicedSurveyStartCollecting: 23, + timeSlicedSurveyStopCollecting: 24 + }); + + // === xdr source ============================================================ + // + // struct DontHave + // { + // MessageType type; + // uint256 reqHash; + // }; + // + // =========================================================================== + xdr.struct("DontHave", [["type", xdr.lookup("MessageType")], ["reqHash", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // enum SurveyMessageCommandType + // { + // SURVEY_TOPOLOGY = 0, + // TIME_SLICED_SURVEY_TOPOLOGY = 1 + // }; + // + // =========================================================================== + xdr["enum"]("SurveyMessageCommandType", { + surveyTopology: 0, + timeSlicedSurveyTopology: 1 + }); + + // === xdr source ============================================================ + // + // enum SurveyMessageResponseType + // { + // SURVEY_TOPOLOGY_RESPONSE_V0 = 0, + // SURVEY_TOPOLOGY_RESPONSE_V1 = 1, + // SURVEY_TOPOLOGY_RESPONSE_V2 = 2 + // }; + // + // =========================================================================== + xdr["enum"]("SurveyMessageResponseType", { + surveyTopologyResponseV0: 0, + surveyTopologyResponseV1: 1, + surveyTopologyResponseV2: 2 + }); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyStartCollectingMessage + // { + // NodeID surveyorID; + // uint32 nonce; + // uint32 ledgerNum; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyStartCollectingMessage", [["surveyorId", xdr.lookup("NodeId")], ["nonce", xdr.lookup("Uint32")], ["ledgerNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyStartCollectingMessage + // { + // Signature signature; + // TimeSlicedSurveyStartCollectingMessage startCollecting; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyStartCollectingMessage", [["signature", xdr.lookup("Signature")], ["startCollecting", xdr.lookup("TimeSlicedSurveyStartCollectingMessage")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyStopCollectingMessage + // { + // NodeID surveyorID; + // uint32 nonce; + // uint32 ledgerNum; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyStopCollectingMessage", [["surveyorId", xdr.lookup("NodeId")], ["nonce", xdr.lookup("Uint32")], ["ledgerNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyStopCollectingMessage + // { + // Signature signature; + // TimeSlicedSurveyStopCollectingMessage stopCollecting; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyStopCollectingMessage", [["signature", xdr.lookup("Signature")], ["stopCollecting", xdr.lookup("TimeSlicedSurveyStopCollectingMessage")]]); + + // === xdr source ============================================================ + // + // struct SurveyRequestMessage + // { + // NodeID surveyorPeerID; + // NodeID surveyedPeerID; + // uint32 ledgerNum; + // Curve25519Public encryptionKey; + // SurveyMessageCommandType commandType; + // }; + // + // =========================================================================== + xdr.struct("SurveyRequestMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["encryptionKey", xdr.lookup("Curve25519Public")], ["commandType", xdr.lookup("SurveyMessageCommandType")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyRequestMessage + // { + // SurveyRequestMessage request; + // uint32 nonce; + // uint32 inboundPeersIndex; + // uint32 outboundPeersIndex; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyRequestMessage", [["request", xdr.lookup("SurveyRequestMessage")], ["nonce", xdr.lookup("Uint32")], ["inboundPeersIndex", xdr.lookup("Uint32")], ["outboundPeersIndex", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedSurveyRequestMessage + // { + // Signature requestSignature; + // SurveyRequestMessage request; + // }; + // + // =========================================================================== + xdr.struct("SignedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("SurveyRequestMessage")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyRequestMessage + // { + // Signature requestSignature; + // TimeSlicedSurveyRequestMessage request; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("TimeSlicedSurveyRequestMessage")]]); + + // === xdr source ============================================================ + // + // typedef opaque EncryptedBody<64000>; + // + // =========================================================================== + xdr.typedef("EncryptedBody", xdr.varOpaque(64000)); + + // === xdr source ============================================================ + // + // struct SurveyResponseMessage + // { + // NodeID surveyorPeerID; + // NodeID surveyedPeerID; + // uint32 ledgerNum; + // SurveyMessageCommandType commandType; + // EncryptedBody encryptedBody; + // }; + // + // =========================================================================== + xdr.struct("SurveyResponseMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["commandType", xdr.lookup("SurveyMessageCommandType")], ["encryptedBody", xdr.lookup("EncryptedBody")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyResponseMessage + // { + // SurveyResponseMessage response; + // uint32 nonce; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyResponseMessage", [["response", xdr.lookup("SurveyResponseMessage")], ["nonce", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedSurveyResponseMessage + // { + // Signature responseSignature; + // SurveyResponseMessage response; + // }; + // + // =========================================================================== + xdr.struct("SignedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("SurveyResponseMessage")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyResponseMessage + // { + // Signature responseSignature; + // TimeSlicedSurveyResponseMessage response; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("TimeSlicedSurveyResponseMessage")]]); + + // === xdr source ============================================================ + // + // struct PeerStats + // { + // NodeID id; + // string versionStr<100>; + // uint64 messagesRead; + // uint64 messagesWritten; + // uint64 bytesRead; + // uint64 bytesWritten; + // uint64 secondsConnected; + // + // uint64 uniqueFloodBytesRecv; + // uint64 duplicateFloodBytesRecv; + // uint64 uniqueFetchBytesRecv; + // uint64 duplicateFetchBytesRecv; + // + // uint64 uniqueFloodMessageRecv; + // uint64 duplicateFloodMessageRecv; + // uint64 uniqueFetchMessageRecv; + // uint64 duplicateFetchMessageRecv; + // }; + // + // =========================================================================== + xdr.struct("PeerStats", [["id", xdr.lookup("NodeId")], ["versionStr", xdr.string(100)], ["messagesRead", xdr.lookup("Uint64")], ["messagesWritten", xdr.lookup("Uint64")], ["bytesRead", xdr.lookup("Uint64")], ["bytesWritten", xdr.lookup("Uint64")], ["secondsConnected", xdr.lookup("Uint64")], ["uniqueFloodBytesRecv", xdr.lookup("Uint64")], ["duplicateFloodBytesRecv", xdr.lookup("Uint64")], ["uniqueFetchBytesRecv", xdr.lookup("Uint64")], ["duplicateFetchBytesRecv", xdr.lookup("Uint64")], ["uniqueFloodMessageRecv", xdr.lookup("Uint64")], ["duplicateFloodMessageRecv", xdr.lookup("Uint64")], ["uniqueFetchMessageRecv", xdr.lookup("Uint64")], ["duplicateFetchMessageRecv", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // typedef PeerStats PeerStatList<25>; + // + // =========================================================================== + xdr.typedef("PeerStatList", xdr.varArray(xdr.lookup("PeerStats"), 25)); + + // === xdr source ============================================================ + // + // struct TimeSlicedNodeData + // { + // uint32 addedAuthenticatedPeers; + // uint32 droppedAuthenticatedPeers; + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // + // // SCP stats + // uint32 p75SCPFirstToSelfLatencyMs; + // uint32 p75SCPSelfToOtherLatencyMs; + // + // // How many times the node lost sync in the time slice + // uint32 lostSyncCount; + // + // // Config data + // bool isValidator; + // uint32 maxInboundPeerCount; + // uint32 maxOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedNodeData", [["addedAuthenticatedPeers", xdr.lookup("Uint32")], ["droppedAuthenticatedPeers", xdr.lookup("Uint32")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")], ["p75ScpFirstToSelfLatencyMs", xdr.lookup("Uint32")], ["p75ScpSelfToOtherLatencyMs", xdr.lookup("Uint32")], ["lostSyncCount", xdr.lookup("Uint32")], ["isValidator", xdr.bool()], ["maxInboundPeerCount", xdr.lookup("Uint32")], ["maxOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedPeerData + // { + // PeerStats peerStats; + // uint32 averageLatencyMs; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedPeerData", [["peerStats", xdr.lookup("PeerStats")], ["averageLatencyMs", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // typedef TimeSlicedPeerData TimeSlicedPeerDataList<25>; + // + // =========================================================================== + xdr.typedef("TimeSlicedPeerDataList", xdr.varArray(xdr.lookup("TimeSlicedPeerData"), 25)); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV0 + // { + // PeerStatList inboundPeers; + // PeerStatList outboundPeers; + // + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV0", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV1 + // { + // PeerStatList inboundPeers; + // PeerStatList outboundPeers; + // + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // + // uint32 maxInboundPeerCount; + // uint32 maxOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV1", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")], ["maxInboundPeerCount", xdr.lookup("Uint32")], ["maxOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV2 + // { + // TimeSlicedPeerDataList inboundPeers; + // TimeSlicedPeerDataList outboundPeers; + // TimeSlicedNodeData nodeData; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV2", [["inboundPeers", xdr.lookup("TimeSlicedPeerDataList")], ["outboundPeers", xdr.lookup("TimeSlicedPeerDataList")], ["nodeData", xdr.lookup("TimeSlicedNodeData")]]); + + // === xdr source ============================================================ + // + // union SurveyResponseBody switch (SurveyMessageResponseType type) + // { + // case SURVEY_TOPOLOGY_RESPONSE_V0: + // TopologyResponseBodyV0 topologyResponseBodyV0; + // case SURVEY_TOPOLOGY_RESPONSE_V1: + // TopologyResponseBodyV1 topologyResponseBodyV1; + // case SURVEY_TOPOLOGY_RESPONSE_V2: + // TopologyResponseBodyV2 topologyResponseBodyV2; + // }; + // + // =========================================================================== + xdr.union("SurveyResponseBody", { + switchOn: xdr.lookup("SurveyMessageResponseType"), + switchName: "type", + switches: [["surveyTopologyResponseV0", "topologyResponseBodyV0"], ["surveyTopologyResponseV1", "topologyResponseBodyV1"], ["surveyTopologyResponseV2", "topologyResponseBodyV2"]], + arms: { + topologyResponseBodyV0: xdr.lookup("TopologyResponseBodyV0"), + topologyResponseBodyV1: xdr.lookup("TopologyResponseBodyV1"), + topologyResponseBodyV2: xdr.lookup("TopologyResponseBodyV2") + } + }); + + // === xdr source ============================================================ + // + // const TX_ADVERT_VECTOR_MAX_SIZE = 1000; + // + // =========================================================================== + xdr["const"]("TX_ADVERT_VECTOR_MAX_SIZE", 1000); + + // === xdr source ============================================================ + // + // typedef Hash TxAdvertVector; + // + // =========================================================================== + xdr.typedef("TxAdvertVector", xdr.varArray(xdr.lookup("Hash"), xdr.lookup("TX_ADVERT_VECTOR_MAX_SIZE"))); + + // === xdr source ============================================================ + // + // struct FloodAdvert + // { + // TxAdvertVector txHashes; + // }; + // + // =========================================================================== + xdr.struct("FloodAdvert", [["txHashes", xdr.lookup("TxAdvertVector")]]); + + // === xdr source ============================================================ + // + // const TX_DEMAND_VECTOR_MAX_SIZE = 1000; + // + // =========================================================================== + xdr["const"]("TX_DEMAND_VECTOR_MAX_SIZE", 1000); + + // === xdr source ============================================================ + // + // typedef Hash TxDemandVector; + // + // =========================================================================== + xdr.typedef("TxDemandVector", xdr.varArray(xdr.lookup("Hash"), xdr.lookup("TX_DEMAND_VECTOR_MAX_SIZE"))); + + // === xdr source ============================================================ + // + // struct FloodDemand + // { + // TxDemandVector txHashes; + // }; + // + // =========================================================================== + xdr.struct("FloodDemand", [["txHashes", xdr.lookup("TxDemandVector")]]); + + // === xdr source ============================================================ + // + // union StellarMessage switch (MessageType type) + // { + // case ERROR_MSG: + // Error error; + // case HELLO: + // Hello hello; + // case AUTH: + // Auth auth; + // case DONT_HAVE: + // DontHave dontHave; + // case GET_PEERS: + // void; + // case PEERS: + // PeerAddress peers<100>; + // + // case GET_TX_SET: + // uint256 txSetHash; + // case TX_SET: + // TransactionSet txSet; + // case GENERALIZED_TX_SET: + // GeneralizedTransactionSet generalizedTxSet; + // + // case TRANSACTION: + // TransactionEnvelope transaction; + // + // case SURVEY_REQUEST: + // SignedSurveyRequestMessage signedSurveyRequestMessage; + // + // case SURVEY_RESPONSE: + // SignedSurveyResponseMessage signedSurveyResponseMessage; + // + // case TIME_SLICED_SURVEY_REQUEST: + // SignedTimeSlicedSurveyRequestMessage signedTimeSlicedSurveyRequestMessage; + // + // case TIME_SLICED_SURVEY_RESPONSE: + // SignedTimeSlicedSurveyResponseMessage signedTimeSlicedSurveyResponseMessage; + // + // case TIME_SLICED_SURVEY_START_COLLECTING: + // SignedTimeSlicedSurveyStartCollectingMessage + // signedTimeSlicedSurveyStartCollectingMessage; + // + // case TIME_SLICED_SURVEY_STOP_COLLECTING: + // SignedTimeSlicedSurveyStopCollectingMessage + // signedTimeSlicedSurveyStopCollectingMessage; + // + // // SCP + // case GET_SCP_QUORUMSET: + // uint256 qSetHash; + // case SCP_QUORUMSET: + // SCPQuorumSet qSet; + // case SCP_MESSAGE: + // SCPEnvelope envelope; + // case GET_SCP_STATE: + // uint32 getSCPLedgerSeq; // ledger seq requested ; if 0, requests the latest + // case SEND_MORE: + // SendMore sendMoreMessage; + // case SEND_MORE_EXTENDED: + // SendMoreExtended sendMoreExtendedMessage; + // // Pull mode + // case FLOOD_ADVERT: + // FloodAdvert floodAdvert; + // case FLOOD_DEMAND: + // FloodDemand floodDemand; + // }; + // + // =========================================================================== + xdr.union("StellarMessage", { + switchOn: xdr.lookup("MessageType"), + switchName: "type", + switches: [["errorMsg", "error"], ["hello", "hello"], ["auth", "auth"], ["dontHave", "dontHave"], ["getPeers", xdr["void"]()], ["peers", "peers"], ["getTxSet", "txSetHash"], ["txSet", "txSet"], ["generalizedTxSet", "generalizedTxSet"], ["transaction", "transaction"], ["surveyRequest", "signedSurveyRequestMessage"], ["surveyResponse", "signedSurveyResponseMessage"], ["timeSlicedSurveyRequest", "signedTimeSlicedSurveyRequestMessage"], ["timeSlicedSurveyResponse", "signedTimeSlicedSurveyResponseMessage"], ["timeSlicedSurveyStartCollecting", "signedTimeSlicedSurveyStartCollectingMessage"], ["timeSlicedSurveyStopCollecting", "signedTimeSlicedSurveyStopCollectingMessage"], ["getScpQuorumset", "qSetHash"], ["scpQuorumset", "qSet"], ["scpMessage", "envelope"], ["getScpState", "getScpLedgerSeq"], ["sendMore", "sendMoreMessage"], ["sendMoreExtended", "sendMoreExtendedMessage"], ["floodAdvert", "floodAdvert"], ["floodDemand", "floodDemand"]], + arms: { + error: xdr.lookup("Error"), + hello: xdr.lookup("Hello"), + auth: xdr.lookup("Auth"), + dontHave: xdr.lookup("DontHave"), + peers: xdr.varArray(xdr.lookup("PeerAddress"), 100), + txSetHash: xdr.lookup("Uint256"), + txSet: xdr.lookup("TransactionSet"), + generalizedTxSet: xdr.lookup("GeneralizedTransactionSet"), + transaction: xdr.lookup("TransactionEnvelope"), + signedSurveyRequestMessage: xdr.lookup("SignedSurveyRequestMessage"), + signedSurveyResponseMessage: xdr.lookup("SignedSurveyResponseMessage"), + signedTimeSlicedSurveyRequestMessage: xdr.lookup("SignedTimeSlicedSurveyRequestMessage"), + signedTimeSlicedSurveyResponseMessage: xdr.lookup("SignedTimeSlicedSurveyResponseMessage"), + signedTimeSlicedSurveyStartCollectingMessage: xdr.lookup("SignedTimeSlicedSurveyStartCollectingMessage"), + signedTimeSlicedSurveyStopCollectingMessage: xdr.lookup("SignedTimeSlicedSurveyStopCollectingMessage"), + qSetHash: xdr.lookup("Uint256"), + qSet: xdr.lookup("ScpQuorumSet"), + envelope: xdr.lookup("ScpEnvelope"), + getScpLedgerSeq: xdr.lookup("Uint32"), + sendMoreMessage: xdr.lookup("SendMore"), + sendMoreExtendedMessage: xdr.lookup("SendMoreExtended"), + floodAdvert: xdr.lookup("FloodAdvert"), + floodDemand: xdr.lookup("FloodDemand") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // uint64 sequence; + // StellarMessage message; + // HmacSha256Mac mac; + // } + // + // =========================================================================== + xdr.struct("AuthenticatedMessageV0", [["sequence", xdr.lookup("Uint64")], ["message", xdr.lookup("StellarMessage")], ["mac", xdr.lookup("HmacSha256Mac")]]); + + // === xdr source ============================================================ + // + // union AuthenticatedMessage switch (uint32 v) + // { + // case 0: + // struct + // { + // uint64 sequence; + // StellarMessage message; + // HmacSha256Mac mac; + // } v0; + // }; + // + // =========================================================================== + xdr.union("AuthenticatedMessage", { + switchOn: xdr.lookup("Uint32"), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("AuthenticatedMessageV0") + } + }); + + // === xdr source ============================================================ + // + // const MAX_OPS_PER_TX = 100; + // + // =========================================================================== + xdr["const"]("MAX_OPS_PER_TX", 100); + + // === xdr source ============================================================ + // + // union LiquidityPoolParameters switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // LiquidityPoolConstantProductParameters constantProduct; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolParameters", { + switchOn: xdr.lookup("LiquidityPoolType"), + switchName: "type", + switches: [["liquidityPoolConstantProduct", "constantProduct"]], + arms: { + constantProduct: xdr.lookup("LiquidityPoolConstantProductParameters") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // uint64 id; + // uint256 ed25519; + // } + // + // =========================================================================== + xdr.struct("MuxedAccountMed25519", [["id", xdr.lookup("Uint64")], ["ed25519", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // union MuxedAccount switch (CryptoKeyType type) + // { + // case KEY_TYPE_ED25519: + // uint256 ed25519; + // case KEY_TYPE_MUXED_ED25519: + // struct + // { + // uint64 id; + // uint256 ed25519; + // } med25519; + // }; + // + // =========================================================================== + xdr.union("MuxedAccount", { + switchOn: xdr.lookup("CryptoKeyType"), + switchName: "type", + switches: [["keyTypeEd25519", "ed25519"], ["keyTypeMuxedEd25519", "med25519"]], + arms: { + ed25519: xdr.lookup("Uint256"), + med25519: xdr.lookup("MuxedAccountMed25519") + } + }); + + // === xdr source ============================================================ + // + // struct DecoratedSignature + // { + // SignatureHint hint; // last 4 bytes of the public key, used as a hint + // Signature signature; // actual signature + // }; + // + // =========================================================================== + xdr.struct("DecoratedSignature", [["hint", xdr.lookup("SignatureHint")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // enum OperationType + // { + // CREATE_ACCOUNT = 0, + // PAYMENT = 1, + // PATH_PAYMENT_STRICT_RECEIVE = 2, + // MANAGE_SELL_OFFER = 3, + // CREATE_PASSIVE_SELL_OFFER = 4, + // SET_OPTIONS = 5, + // CHANGE_TRUST = 6, + // ALLOW_TRUST = 7, + // ACCOUNT_MERGE = 8, + // INFLATION = 9, + // MANAGE_DATA = 10, + // BUMP_SEQUENCE = 11, + // MANAGE_BUY_OFFER = 12, + // PATH_PAYMENT_STRICT_SEND = 13, + // CREATE_CLAIMABLE_BALANCE = 14, + // CLAIM_CLAIMABLE_BALANCE = 15, + // BEGIN_SPONSORING_FUTURE_RESERVES = 16, + // END_SPONSORING_FUTURE_RESERVES = 17, + // REVOKE_SPONSORSHIP = 18, + // CLAWBACK = 19, + // CLAWBACK_CLAIMABLE_BALANCE = 20, + // SET_TRUST_LINE_FLAGS = 21, + // LIQUIDITY_POOL_DEPOSIT = 22, + // LIQUIDITY_POOL_WITHDRAW = 23, + // INVOKE_HOST_FUNCTION = 24, + // EXTEND_FOOTPRINT_TTL = 25, + // RESTORE_FOOTPRINT = 26 + // }; + // + // =========================================================================== + xdr["enum"]("OperationType", { + createAccount: 0, + payment: 1, + pathPaymentStrictReceive: 2, + manageSellOffer: 3, + createPassiveSellOffer: 4, + setOptions: 5, + changeTrust: 6, + allowTrust: 7, + accountMerge: 8, + inflation: 9, + manageData: 10, + bumpSequence: 11, + manageBuyOffer: 12, + pathPaymentStrictSend: 13, + createClaimableBalance: 14, + claimClaimableBalance: 15, + beginSponsoringFutureReserves: 16, + endSponsoringFutureReserves: 17, + revokeSponsorship: 18, + clawback: 19, + clawbackClaimableBalance: 20, + setTrustLineFlags: 21, + liquidityPoolDeposit: 22, + liquidityPoolWithdraw: 23, + invokeHostFunction: 24, + extendFootprintTtl: 25, + restoreFootprint: 26 + }); + + // === xdr source ============================================================ + // + // struct CreateAccountOp + // { + // AccountID destination; // account to create + // int64 startingBalance; // amount they end up with + // }; + // + // =========================================================================== + xdr.struct("CreateAccountOp", [["destination", xdr.lookup("AccountId")], ["startingBalance", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct PaymentOp + // { + // MuxedAccount destination; // recipient of the payment + // Asset asset; // what they end up with + // int64 amount; // amount they end up with + // }; + // + // =========================================================================== + xdr.struct("PaymentOp", [["destination", xdr.lookup("MuxedAccount")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct PathPaymentStrictReceiveOp + // { + // Asset sendAsset; // asset we pay with + // int64 sendMax; // the maximum amount of sendAsset to + // // send (excluding fees). + // // The operation will fail if can't be met + // + // MuxedAccount destination; // recipient of the payment + // Asset destAsset; // what they end up with + // int64 destAmount; // amount they end up with + // + // Asset path<5>; // additional hops it must go through to get there + // }; + // + // =========================================================================== + xdr.struct("PathPaymentStrictReceiveOp", [["sendAsset", xdr.lookup("Asset")], ["sendMax", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destAmount", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]); + + // === xdr source ============================================================ + // + // struct PathPaymentStrictSendOp + // { + // Asset sendAsset; // asset we pay with + // int64 sendAmount; // amount of sendAsset to send (excluding fees) + // + // MuxedAccount destination; // recipient of the payment + // Asset destAsset; // what they end up with + // int64 destMin; // the minimum amount of dest asset to + // // be received + // // The operation will fail if it can't be met + // + // Asset path<5>; // additional hops it must go through to get there + // }; + // + // =========================================================================== + xdr.struct("PathPaymentStrictSendOp", [["sendAsset", xdr.lookup("Asset")], ["sendAmount", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destMin", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]); + + // === xdr source ============================================================ + // + // struct ManageSellOfferOp + // { + // Asset selling; + // Asset buying; + // int64 amount; // amount being sold. if set to 0, delete the offer + // Price price; // price of thing being sold in terms of what you are buying + // + // // 0=create a new offer, otherwise edit an existing offer + // int64 offerID; + // }; + // + // =========================================================================== + xdr.struct("ManageSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ManageBuyOfferOp + // { + // Asset selling; + // Asset buying; + // int64 buyAmount; // amount being bought. if set to 0, delete the offer + // Price price; // price of thing being bought in terms of what you are + // // selling + // + // // 0=create a new offer, otherwise edit an existing offer + // int64 offerID; + // }; + // + // =========================================================================== + xdr.struct("ManageBuyOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["buyAmount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct CreatePassiveSellOfferOp + // { + // Asset selling; // A + // Asset buying; // B + // int64 amount; // amount taker gets + // Price price; // cost of A in terms of B + // }; + // + // =========================================================================== + xdr.struct("CreatePassiveSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")]]); + + // === xdr source ============================================================ + // + // struct SetOptionsOp + // { + // AccountID* inflationDest; // sets the inflation destination + // + // uint32* clearFlags; // which flags to clear + // uint32* setFlags; // which flags to set + // + // // account threshold manipulation + // uint32* masterWeight; // weight of the master account + // uint32* lowThreshold; + // uint32* medThreshold; + // uint32* highThreshold; + // + // string32* homeDomain; // sets the home domain + // + // // Add, update or remove a signer for the account + // // signer is deleted if the weight is 0 + // Signer* signer; + // }; + // + // =========================================================================== + xdr.struct("SetOptionsOp", [["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["clearFlags", xdr.option(xdr.lookup("Uint32"))], ["setFlags", xdr.option(xdr.lookup("Uint32"))], ["masterWeight", xdr.option(xdr.lookup("Uint32"))], ["lowThreshold", xdr.option(xdr.lookup("Uint32"))], ["medThreshold", xdr.option(xdr.lookup("Uint32"))], ["highThreshold", xdr.option(xdr.lookup("Uint32"))], ["homeDomain", xdr.option(xdr.lookup("String32"))], ["signer", xdr.option(xdr.lookup("Signer"))]]); + + // === xdr source ============================================================ + // + // union ChangeTrustAsset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // case ASSET_TYPE_POOL_SHARE: + // LiquidityPoolParameters liquidityPool; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("ChangeTrustAsset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPool"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12"), + liquidityPool: xdr.lookup("LiquidityPoolParameters") + } + }); + + // === xdr source ============================================================ + // + // struct ChangeTrustOp + // { + // ChangeTrustAsset line; + // + // // if limit is set to 0, deletes the trust line + // int64 limit; + // }; + // + // =========================================================================== + xdr.struct("ChangeTrustOp", [["line", xdr.lookup("ChangeTrustAsset")], ["limit", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct AllowTrustOp + // { + // AccountID trustor; + // AssetCode asset; + // + // // One of 0, AUTHORIZED_FLAG, or AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG + // uint32 authorize; + // }; + // + // =========================================================================== + xdr.struct("AllowTrustOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("AssetCode")], ["authorize", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ManageDataOp + // { + // string64 dataName; + // DataValue* dataValue; // set to null to clear + // }; + // + // =========================================================================== + xdr.struct("ManageDataOp", [["dataName", xdr.lookup("String64")], ["dataValue", xdr.option(xdr.lookup("DataValue"))]]); + + // === xdr source ============================================================ + // + // struct BumpSequenceOp + // { + // SequenceNumber bumpTo; + // }; + // + // =========================================================================== + xdr.struct("BumpSequenceOp", [["bumpTo", xdr.lookup("SequenceNumber")]]); + + // === xdr source ============================================================ + // + // struct CreateClaimableBalanceOp + // { + // Asset asset; + // int64 amount; + // Claimant claimants<10>; + // }; + // + // =========================================================================== + xdr.struct("CreateClaimableBalanceOp", [["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)]]); + + // === xdr source ============================================================ + // + // struct ClaimClaimableBalanceOp + // { + // ClaimableBalanceID balanceID; + // }; + // + // =========================================================================== + xdr.struct("ClaimClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct BeginSponsoringFutureReservesOp + // { + // AccountID sponsoredID; + // }; + // + // =========================================================================== + xdr.struct("BeginSponsoringFutureReservesOp", [["sponsoredId", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // enum RevokeSponsorshipType + // { + // REVOKE_SPONSORSHIP_LEDGER_ENTRY = 0, + // REVOKE_SPONSORSHIP_SIGNER = 1 + // }; + // + // =========================================================================== + xdr["enum"]("RevokeSponsorshipType", { + revokeSponsorshipLedgerEntry: 0, + revokeSponsorshipSigner: 1 + }); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // SignerKey signerKey; + // } + // + // =========================================================================== + xdr.struct("RevokeSponsorshipOpSigner", [["accountId", xdr.lookup("AccountId")], ["signerKey", xdr.lookup("SignerKey")]]); + + // === xdr source ============================================================ + // + // union RevokeSponsorshipOp switch (RevokeSponsorshipType type) + // { + // case REVOKE_SPONSORSHIP_LEDGER_ENTRY: + // LedgerKey ledgerKey; + // case REVOKE_SPONSORSHIP_SIGNER: + // struct + // { + // AccountID accountID; + // SignerKey signerKey; + // } signer; + // }; + // + // =========================================================================== + xdr.union("RevokeSponsorshipOp", { + switchOn: xdr.lookup("RevokeSponsorshipType"), + switchName: "type", + switches: [["revokeSponsorshipLedgerEntry", "ledgerKey"], ["revokeSponsorshipSigner", "signer"]], + arms: { + ledgerKey: xdr.lookup("LedgerKey"), + signer: xdr.lookup("RevokeSponsorshipOpSigner") + } + }); + + // === xdr source ============================================================ + // + // struct ClawbackOp + // { + // Asset asset; + // MuxedAccount from; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("ClawbackOp", [["asset", xdr.lookup("Asset")], ["from", xdr.lookup("MuxedAccount")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClawbackClaimableBalanceOp + // { + // ClaimableBalanceID balanceID; + // }; + // + // =========================================================================== + xdr.struct("ClawbackClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct SetTrustLineFlagsOp + // { + // AccountID trustor; + // Asset asset; + // + // uint32 clearFlags; // which flags to clear + // uint32 setFlags; // which flags to set + // }; + // + // =========================================================================== + xdr.struct("SetTrustLineFlagsOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["clearFlags", xdr.lookup("Uint32")], ["setFlags", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // const LIQUIDITY_POOL_FEE_V18 = 30; + // + // =========================================================================== + xdr["const"]("LIQUIDITY_POOL_FEE_V18", 30); + + // === xdr source ============================================================ + // + // struct LiquidityPoolDepositOp + // { + // PoolID liquidityPoolID; + // int64 maxAmountA; // maximum amount of first asset to deposit + // int64 maxAmountB; // maximum amount of second asset to deposit + // Price minPrice; // minimum depositA/depositB + // Price maxPrice; // maximum depositA/depositB + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolDepositOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["maxAmountA", xdr.lookup("Int64")], ["maxAmountB", xdr.lookup("Int64")], ["minPrice", xdr.lookup("Price")], ["maxPrice", xdr.lookup("Price")]]); + + // === xdr source ============================================================ + // + // struct LiquidityPoolWithdrawOp + // { + // PoolID liquidityPoolID; + // int64 amount; // amount of pool shares to withdraw + // int64 minAmountA; // minimum amount of first asset to withdraw + // int64 minAmountB; // minimum amount of second asset to withdraw + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolWithdrawOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["amount", xdr.lookup("Int64")], ["minAmountA", xdr.lookup("Int64")], ["minAmountB", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum HostFunctionType + // { + // HOST_FUNCTION_TYPE_INVOKE_CONTRACT = 0, + // HOST_FUNCTION_TYPE_CREATE_CONTRACT = 1, + // HOST_FUNCTION_TYPE_UPLOAD_CONTRACT_WASM = 2, + // HOST_FUNCTION_TYPE_CREATE_CONTRACT_V2 = 3 + // }; + // + // =========================================================================== + xdr["enum"]("HostFunctionType", { + hostFunctionTypeInvokeContract: 0, + hostFunctionTypeCreateContract: 1, + hostFunctionTypeUploadContractWasm: 2, + hostFunctionTypeCreateContractV2: 3 + }); + + // === xdr source ============================================================ + // + // enum ContractIDPreimageType + // { + // CONTRACT_ID_PREIMAGE_FROM_ADDRESS = 0, + // CONTRACT_ID_PREIMAGE_FROM_ASSET = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractIdPreimageType", { + contractIdPreimageFromAddress: 0, + contractIdPreimageFromAsset: 1 + }); + + // === xdr source ============================================================ + // + // struct + // { + // SCAddress address; + // uint256 salt; + // } + // + // =========================================================================== + xdr.struct("ContractIdPreimageFromAddress", [["address", xdr.lookup("ScAddress")], ["salt", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // union ContractIDPreimage switch (ContractIDPreimageType type) + // { + // case CONTRACT_ID_PREIMAGE_FROM_ADDRESS: + // struct + // { + // SCAddress address; + // uint256 salt; + // } fromAddress; + // case CONTRACT_ID_PREIMAGE_FROM_ASSET: + // Asset fromAsset; + // }; + // + // =========================================================================== + xdr.union("ContractIdPreimage", { + switchOn: xdr.lookup("ContractIdPreimageType"), + switchName: "type", + switches: [["contractIdPreimageFromAddress", "fromAddress"], ["contractIdPreimageFromAsset", "fromAsset"]], + arms: { + fromAddress: xdr.lookup("ContractIdPreimageFromAddress"), + fromAsset: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // struct CreateContractArgs + // { + // ContractIDPreimage contractIDPreimage; + // ContractExecutable executable; + // }; + // + // =========================================================================== + xdr.struct("CreateContractArgs", [["contractIdPreimage", xdr.lookup("ContractIdPreimage")], ["executable", xdr.lookup("ContractExecutable")]]); + + // === xdr source ============================================================ + // + // struct CreateContractArgsV2 + // { + // ContractIDPreimage contractIDPreimage; + // ContractExecutable executable; + // // Arguments of the contract's constructor. + // SCVal constructorArgs<>; + // }; + // + // =========================================================================== + xdr.struct("CreateContractArgsV2", [["contractIdPreimage", xdr.lookup("ContractIdPreimage")], ["executable", xdr.lookup("ContractExecutable")], ["constructorArgs", xdr.varArray(xdr.lookup("ScVal"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct InvokeContractArgs { + // SCAddress contractAddress; + // SCSymbol functionName; + // SCVal args<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeContractArgs", [["contractAddress", xdr.lookup("ScAddress")], ["functionName", xdr.lookup("ScSymbol")], ["args", xdr.varArray(xdr.lookup("ScVal"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union HostFunction switch (HostFunctionType type) + // { + // case HOST_FUNCTION_TYPE_INVOKE_CONTRACT: + // InvokeContractArgs invokeContract; + // case HOST_FUNCTION_TYPE_CREATE_CONTRACT: + // CreateContractArgs createContract; + // case HOST_FUNCTION_TYPE_UPLOAD_CONTRACT_WASM: + // opaque wasm<>; + // case HOST_FUNCTION_TYPE_CREATE_CONTRACT_V2: + // CreateContractArgsV2 createContractV2; + // }; + // + // =========================================================================== + xdr.union("HostFunction", { + switchOn: xdr.lookup("HostFunctionType"), + switchName: "type", + switches: [["hostFunctionTypeInvokeContract", "invokeContract"], ["hostFunctionTypeCreateContract", "createContract"], ["hostFunctionTypeUploadContractWasm", "wasm"], ["hostFunctionTypeCreateContractV2", "createContractV2"]], + arms: { + invokeContract: xdr.lookup("InvokeContractArgs"), + createContract: xdr.lookup("CreateContractArgs"), + wasm: xdr.varOpaque(), + createContractV2: xdr.lookup("CreateContractArgsV2") + } + }); + + // === xdr source ============================================================ + // + // enum SorobanAuthorizedFunctionType + // { + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN = 0, + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_HOST_FN = 1, + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN = 2 + // }; + // + // =========================================================================== + xdr["enum"]("SorobanAuthorizedFunctionType", { + sorobanAuthorizedFunctionTypeContractFn: 0, + sorobanAuthorizedFunctionTypeCreateContractHostFn: 1, + sorobanAuthorizedFunctionTypeCreateContractV2HostFn: 2 + }); + + // === xdr source ============================================================ + // + // union SorobanAuthorizedFunction switch (SorobanAuthorizedFunctionType type) + // { + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN: + // InvokeContractArgs contractFn; + // // This variant of auth payload for creating new contract instances + // // doesn't allow specifying the constructor arguments, creating contracts + // // with constructors that take arguments is only possible by authorizing + // // `SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN` + // // (protocol 22+). + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_HOST_FN: + // CreateContractArgs createContractHostFn; + // // This variant of auth payload for creating new contract instances + // // is only accepted in and after protocol 22. It allows authorizing the + // // contract constructor arguments. + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN: + // CreateContractArgsV2 createContractV2HostFn; + // }; + // + // =========================================================================== + xdr.union("SorobanAuthorizedFunction", { + switchOn: xdr.lookup("SorobanAuthorizedFunctionType"), + switchName: "type", + switches: [["sorobanAuthorizedFunctionTypeContractFn", "contractFn"], ["sorobanAuthorizedFunctionTypeCreateContractHostFn", "createContractHostFn"], ["sorobanAuthorizedFunctionTypeCreateContractV2HostFn", "createContractV2HostFn"]], + arms: { + contractFn: xdr.lookup("InvokeContractArgs"), + createContractHostFn: xdr.lookup("CreateContractArgs"), + createContractV2HostFn: xdr.lookup("CreateContractArgsV2") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanAuthorizedInvocation + // { + // SorobanAuthorizedFunction function; + // SorobanAuthorizedInvocation subInvocations<>; + // }; + // + // =========================================================================== + xdr.struct("SorobanAuthorizedInvocation", [["function", xdr.lookup("SorobanAuthorizedFunction")], ["subInvocations", xdr.varArray(xdr.lookup("SorobanAuthorizedInvocation"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct SorobanAddressCredentials + // { + // SCAddress address; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SCVal signature; + // }; + // + // =========================================================================== + xdr.struct("SorobanAddressCredentials", [["address", xdr.lookup("ScAddress")], ["nonce", xdr.lookup("Int64")], ["signatureExpirationLedger", xdr.lookup("Uint32")], ["signature", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // enum SorobanCredentialsType + // { + // SOROBAN_CREDENTIALS_SOURCE_ACCOUNT = 0, + // SOROBAN_CREDENTIALS_ADDRESS = 1 + // }; + // + // =========================================================================== + xdr["enum"]("SorobanCredentialsType", { + sorobanCredentialsSourceAccount: 0, + sorobanCredentialsAddress: 1 + }); + + // === xdr source ============================================================ + // + // union SorobanCredentials switch (SorobanCredentialsType type) + // { + // case SOROBAN_CREDENTIALS_SOURCE_ACCOUNT: + // void; + // case SOROBAN_CREDENTIALS_ADDRESS: + // SorobanAddressCredentials address; + // }; + // + // =========================================================================== + xdr.union("SorobanCredentials", { + switchOn: xdr.lookup("SorobanCredentialsType"), + switchName: "type", + switches: [["sorobanCredentialsSourceAccount", xdr["void"]()], ["sorobanCredentialsAddress", "address"]], + arms: { + address: xdr.lookup("SorobanAddressCredentials") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanAuthorizationEntry + // { + // SorobanCredentials credentials; + // SorobanAuthorizedInvocation rootInvocation; + // }; + // + // =========================================================================== + xdr.struct("SorobanAuthorizationEntry", [["credentials", xdr.lookup("SorobanCredentials")], ["rootInvocation", xdr.lookup("SorobanAuthorizedInvocation")]]); + + // === xdr source ============================================================ + // + // struct InvokeHostFunctionOp + // { + // // Host function to invoke. + // HostFunction hostFunction; + // // Per-address authorizations for this host function. + // SorobanAuthorizationEntry auth<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeHostFunctionOp", [["hostFunction", xdr.lookup("HostFunction")], ["auth", xdr.varArray(xdr.lookup("SorobanAuthorizationEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct ExtendFootprintTTLOp + // { + // ExtensionPoint ext; + // uint32 extendTo; + // }; + // + // =========================================================================== + xdr.struct("ExtendFootprintTtlOp", [["ext", xdr.lookup("ExtensionPoint")], ["extendTo", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct RestoreFootprintOp + // { + // ExtensionPoint ext; + // }; + // + // =========================================================================== + xdr.struct("RestoreFootprintOp", [["ext", xdr.lookup("ExtensionPoint")]]); + + // === xdr source ============================================================ + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountOp createAccountOp; + // case PAYMENT: + // PaymentOp paymentOp; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp; + // case MANAGE_SELL_OFFER: + // ManageSellOfferOp manageSellOfferOp; + // case CREATE_PASSIVE_SELL_OFFER: + // CreatePassiveSellOfferOp createPassiveSellOfferOp; + // case SET_OPTIONS: + // SetOptionsOp setOptionsOp; + // case CHANGE_TRUST: + // ChangeTrustOp changeTrustOp; + // case ALLOW_TRUST: + // AllowTrustOp allowTrustOp; + // case ACCOUNT_MERGE: + // MuxedAccount destination; + // case INFLATION: + // void; + // case MANAGE_DATA: + // ManageDataOp manageDataOp; + // case BUMP_SEQUENCE: + // BumpSequenceOp bumpSequenceOp; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferOp manageBuyOfferOp; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendOp pathPaymentStrictSendOp; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceOp createClaimableBalanceOp; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceOp claimClaimableBalanceOp; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp; + // case END_SPONSORING_FUTURE_RESERVES: + // void; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipOp revokeSponsorshipOp; + // case CLAWBACK: + // ClawbackOp clawbackOp; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceOp clawbackClaimableBalanceOp; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsOp setTrustLineFlagsOp; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositOp liquidityPoolDepositOp; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawOp liquidityPoolWithdrawOp; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionOp invokeHostFunctionOp; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLOp extendFootprintTTLOp; + // case RESTORE_FOOTPRINT: + // RestoreFootprintOp restoreFootprintOp; + // } + // + // =========================================================================== + xdr.union("OperationBody", { + switchOn: xdr.lookup("OperationType"), + switchName: "type", + switches: [["createAccount", "createAccountOp"], ["payment", "paymentOp"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveOp"], ["manageSellOffer", "manageSellOfferOp"], ["createPassiveSellOffer", "createPassiveSellOfferOp"], ["setOptions", "setOptionsOp"], ["changeTrust", "changeTrustOp"], ["allowTrust", "allowTrustOp"], ["accountMerge", "destination"], ["inflation", xdr["void"]()], ["manageData", "manageDataOp"], ["bumpSequence", "bumpSequenceOp"], ["manageBuyOffer", "manageBuyOfferOp"], ["pathPaymentStrictSend", "pathPaymentStrictSendOp"], ["createClaimableBalance", "createClaimableBalanceOp"], ["claimClaimableBalance", "claimClaimableBalanceOp"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesOp"], ["endSponsoringFutureReserves", xdr["void"]()], ["revokeSponsorship", "revokeSponsorshipOp"], ["clawback", "clawbackOp"], ["clawbackClaimableBalance", "clawbackClaimableBalanceOp"], ["setTrustLineFlags", "setTrustLineFlagsOp"], ["liquidityPoolDeposit", "liquidityPoolDepositOp"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawOp"], ["invokeHostFunction", "invokeHostFunctionOp"], ["extendFootprintTtl", "extendFootprintTtlOp"], ["restoreFootprint", "restoreFootprintOp"]], + arms: { + createAccountOp: xdr.lookup("CreateAccountOp"), + paymentOp: xdr.lookup("PaymentOp"), + pathPaymentStrictReceiveOp: xdr.lookup("PathPaymentStrictReceiveOp"), + manageSellOfferOp: xdr.lookup("ManageSellOfferOp"), + createPassiveSellOfferOp: xdr.lookup("CreatePassiveSellOfferOp"), + setOptionsOp: xdr.lookup("SetOptionsOp"), + changeTrustOp: xdr.lookup("ChangeTrustOp"), + allowTrustOp: xdr.lookup("AllowTrustOp"), + destination: xdr.lookup("MuxedAccount"), + manageDataOp: xdr.lookup("ManageDataOp"), + bumpSequenceOp: xdr.lookup("BumpSequenceOp"), + manageBuyOfferOp: xdr.lookup("ManageBuyOfferOp"), + pathPaymentStrictSendOp: xdr.lookup("PathPaymentStrictSendOp"), + createClaimableBalanceOp: xdr.lookup("CreateClaimableBalanceOp"), + claimClaimableBalanceOp: xdr.lookup("ClaimClaimableBalanceOp"), + beginSponsoringFutureReservesOp: xdr.lookup("BeginSponsoringFutureReservesOp"), + revokeSponsorshipOp: xdr.lookup("RevokeSponsorshipOp"), + clawbackOp: xdr.lookup("ClawbackOp"), + clawbackClaimableBalanceOp: xdr.lookup("ClawbackClaimableBalanceOp"), + setTrustLineFlagsOp: xdr.lookup("SetTrustLineFlagsOp"), + liquidityPoolDepositOp: xdr.lookup("LiquidityPoolDepositOp"), + liquidityPoolWithdrawOp: xdr.lookup("LiquidityPoolWithdrawOp"), + invokeHostFunctionOp: xdr.lookup("InvokeHostFunctionOp"), + extendFootprintTtlOp: xdr.lookup("ExtendFootprintTtlOp"), + restoreFootprintOp: xdr.lookup("RestoreFootprintOp") + } + }); + + // === xdr source ============================================================ + // + // struct Operation + // { + // // sourceAccount is the account used to run the operation + // // if not set, the runtime defaults to "sourceAccount" specified at + // // the transaction level + // MuxedAccount* sourceAccount; + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountOp createAccountOp; + // case PAYMENT: + // PaymentOp paymentOp; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp; + // case MANAGE_SELL_OFFER: + // ManageSellOfferOp manageSellOfferOp; + // case CREATE_PASSIVE_SELL_OFFER: + // CreatePassiveSellOfferOp createPassiveSellOfferOp; + // case SET_OPTIONS: + // SetOptionsOp setOptionsOp; + // case CHANGE_TRUST: + // ChangeTrustOp changeTrustOp; + // case ALLOW_TRUST: + // AllowTrustOp allowTrustOp; + // case ACCOUNT_MERGE: + // MuxedAccount destination; + // case INFLATION: + // void; + // case MANAGE_DATA: + // ManageDataOp manageDataOp; + // case BUMP_SEQUENCE: + // BumpSequenceOp bumpSequenceOp; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferOp manageBuyOfferOp; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendOp pathPaymentStrictSendOp; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceOp createClaimableBalanceOp; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceOp claimClaimableBalanceOp; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp; + // case END_SPONSORING_FUTURE_RESERVES: + // void; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipOp revokeSponsorshipOp; + // case CLAWBACK: + // ClawbackOp clawbackOp; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceOp clawbackClaimableBalanceOp; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsOp setTrustLineFlagsOp; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositOp liquidityPoolDepositOp; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawOp liquidityPoolWithdrawOp; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionOp invokeHostFunctionOp; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLOp extendFootprintTTLOp; + // case RESTORE_FOOTPRINT: + // RestoreFootprintOp restoreFootprintOp; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("Operation", [["sourceAccount", xdr.option(xdr.lookup("MuxedAccount"))], ["body", xdr.lookup("OperationBody")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageOperationId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // PoolID liquidityPoolID; + // Asset asset; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageRevokeId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")], ["liquidityPoolId", xdr.lookup("PoolId")], ["asset", xdr.lookup("Asset")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash networkID; + // ContractIDPreimage contractIDPreimage; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageContractId", [["networkId", xdr.lookup("Hash")], ["contractIdPreimage", xdr.lookup("ContractIdPreimage")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash networkID; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SorobanAuthorizedInvocation invocation; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageSorobanAuthorization", [["networkId", xdr.lookup("Hash")], ["nonce", xdr.lookup("Int64")], ["signatureExpirationLedger", xdr.lookup("Uint32")], ["invocation", xdr.lookup("SorobanAuthorizedInvocation")]]); + + // === xdr source ============================================================ + // + // union HashIDPreimage switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_OP_ID: + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // } operationID; + // case ENVELOPE_TYPE_POOL_REVOKE_OP_ID: + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // PoolID liquidityPoolID; + // Asset asset; + // } revokeID; + // case ENVELOPE_TYPE_CONTRACT_ID: + // struct + // { + // Hash networkID; + // ContractIDPreimage contractIDPreimage; + // } contractID; + // case ENVELOPE_TYPE_SOROBAN_AUTHORIZATION: + // struct + // { + // Hash networkID; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SorobanAuthorizedInvocation invocation; + // } sorobanAuthorization; + // }; + // + // =========================================================================== + xdr.union("HashIdPreimage", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeOpId", "operationId"], ["envelopeTypePoolRevokeOpId", "revokeId"], ["envelopeTypeContractId", "contractId"], ["envelopeTypeSorobanAuthorization", "sorobanAuthorization"]], + arms: { + operationId: xdr.lookup("HashIdPreimageOperationId"), + revokeId: xdr.lookup("HashIdPreimageRevokeId"), + contractId: xdr.lookup("HashIdPreimageContractId"), + sorobanAuthorization: xdr.lookup("HashIdPreimageSorobanAuthorization") + } + }); + + // === xdr source ============================================================ + // + // enum MemoType + // { + // MEMO_NONE = 0, + // MEMO_TEXT = 1, + // MEMO_ID = 2, + // MEMO_HASH = 3, + // MEMO_RETURN = 4 + // }; + // + // =========================================================================== + xdr["enum"]("MemoType", { + memoNone: 0, + memoText: 1, + memoId: 2, + memoHash: 3, + memoReturn: 4 + }); + + // === xdr source ============================================================ + // + // union Memo switch (MemoType type) + // { + // case MEMO_NONE: + // void; + // case MEMO_TEXT: + // string text<28>; + // case MEMO_ID: + // uint64 id; + // case MEMO_HASH: + // Hash hash; // the hash of what to pull from the content server + // case MEMO_RETURN: + // Hash retHash; // the hash of the tx you are rejecting + // }; + // + // =========================================================================== + xdr.union("Memo", { + switchOn: xdr.lookup("MemoType"), + switchName: "type", + switches: [["memoNone", xdr["void"]()], ["memoText", "text"], ["memoId", "id"], ["memoHash", "hash"], ["memoReturn", "retHash"]], + arms: { + text: xdr.string(28), + id: xdr.lookup("Uint64"), + hash: xdr.lookup("Hash"), + retHash: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // struct TimeBounds + // { + // TimePoint minTime; + // TimePoint maxTime; // 0 here means no maxTime + // }; + // + // =========================================================================== + xdr.struct("TimeBounds", [["minTime", xdr.lookup("TimePoint")], ["maxTime", xdr.lookup("TimePoint")]]); + + // === xdr source ============================================================ + // + // struct LedgerBounds + // { + // uint32 minLedger; + // uint32 maxLedger; // 0 here means no maxLedger + // }; + // + // =========================================================================== + xdr.struct("LedgerBounds", [["minLedger", xdr.lookup("Uint32")], ["maxLedger", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct PreconditionsV2 + // { + // TimeBounds* timeBounds; + // + // // Transaction only valid for ledger numbers n such that + // // minLedger <= n < maxLedger (if maxLedger == 0, then + // // only minLedger is checked) + // LedgerBounds* ledgerBounds; + // + // // If NULL, only valid when sourceAccount's sequence number + // // is seqNum - 1. Otherwise, valid when sourceAccount's + // // sequence number n satisfies minSeqNum <= n < tx.seqNum. + // // Note that after execution the account's sequence number + // // is always raised to tx.seqNum, and a transaction is not + // // valid if tx.seqNum is too high to ensure replay protection. + // SequenceNumber* minSeqNum; + // + // // For the transaction to be valid, the current ledger time must + // // be at least minSeqAge greater than sourceAccount's seqTime. + // Duration minSeqAge; + // + // // For the transaction to be valid, the current ledger number + // // must be at least minSeqLedgerGap greater than sourceAccount's + // // seqLedger. + // uint32 minSeqLedgerGap; + // + // // For the transaction to be valid, there must be a signature + // // corresponding to every Signer in this array, even if the + // // signature is not otherwise required by the sourceAccount or + // // operations. + // SignerKey extraSigners<2>; + // }; + // + // =========================================================================== + xdr.struct("PreconditionsV2", [["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["ledgerBounds", xdr.option(xdr.lookup("LedgerBounds"))], ["minSeqNum", xdr.option(xdr.lookup("SequenceNumber"))], ["minSeqAge", xdr.lookup("Duration")], ["minSeqLedgerGap", xdr.lookup("Uint32")], ["extraSigners", xdr.varArray(xdr.lookup("SignerKey"), 2)]]); + + // === xdr source ============================================================ + // + // enum PreconditionType + // { + // PRECOND_NONE = 0, + // PRECOND_TIME = 1, + // PRECOND_V2 = 2 + // }; + // + // =========================================================================== + xdr["enum"]("PreconditionType", { + precondNone: 0, + precondTime: 1, + precondV2: 2 + }); + + // === xdr source ============================================================ + // + // union Preconditions switch (PreconditionType type) + // { + // case PRECOND_NONE: + // void; + // case PRECOND_TIME: + // TimeBounds timeBounds; + // case PRECOND_V2: + // PreconditionsV2 v2; + // }; + // + // =========================================================================== + xdr.union("Preconditions", { + switchOn: xdr.lookup("PreconditionType"), + switchName: "type", + switches: [["precondNone", xdr["void"]()], ["precondTime", "timeBounds"], ["precondV2", "v2"]], + arms: { + timeBounds: xdr.lookup("TimeBounds"), + v2: xdr.lookup("PreconditionsV2") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerFootprint + // { + // LedgerKey readOnly<>; + // LedgerKey readWrite<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerFootprint", [["readOnly", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["readWrite", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)]]); + + // === xdr source ============================================================ + // + // enum ArchivalProofType + // { + // EXISTENCE = 0, + // NONEXISTENCE = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ArchivalProofType", { + existence: 0, + nonexistence: 1 + }); + + // === xdr source ============================================================ + // + // struct ArchivalProofNode + // { + // uint32 index; + // Hash hash; + // }; + // + // =========================================================================== + xdr.struct("ArchivalProofNode", [["index", xdr.lookup("Uint32")], ["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // typedef ArchivalProofNode ProofLevel<>; + // + // =========================================================================== + xdr.typedef("ProofLevel", xdr.varArray(xdr.lookup("ArchivalProofNode"), 2147483647)); + + // === xdr source ============================================================ + // + // struct NonexistenceProofBody + // { + // ColdArchiveBucketEntry entriesToProve<>; + // + // // Vector of vectors, where proofLevels[level] + // // contains all HashNodes that correspond with that level + // ProofLevel proofLevels<>; + // }; + // + // =========================================================================== + xdr.struct("NonexistenceProofBody", [["entriesToProve", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["proofLevels", xdr.varArray(xdr.lookup("ProofLevel"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct ExistenceProofBody + // { + // LedgerKey keysToProve<>; + // + // // Bounds for each key being proved, where bound[n] + // // corresponds to keysToProve[n] + // ColdArchiveBucketEntry lowBoundEntries<>; + // ColdArchiveBucketEntry highBoundEntries<>; + // + // // Vector of vectors, where proofLevels[level] + // // contains all HashNodes that correspond with that level + // ProofLevel proofLevels<>; + // }; + // + // =========================================================================== + xdr.struct("ExistenceProofBody", [["keysToProve", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["lowBoundEntries", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["highBoundEntries", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["proofLevels", xdr.varArray(xdr.lookup("ProofLevel"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union switch (ArchivalProofType t) + // { + // case EXISTENCE: + // NonexistenceProofBody nonexistenceProof; + // case NONEXISTENCE: + // ExistenceProofBody existenceProof; + // } + // + // =========================================================================== + xdr.union("ArchivalProofBody", { + switchOn: xdr.lookup("ArchivalProofType"), + switchName: "t", + switches: [["existence", "nonexistenceProof"], ["nonexistence", "existenceProof"]], + arms: { + nonexistenceProof: xdr.lookup("NonexistenceProofBody"), + existenceProof: xdr.lookup("ExistenceProofBody") + } + }); + + // === xdr source ============================================================ + // + // struct ArchivalProof + // { + // uint32 epoch; // AST Subtree for this proof + // + // union switch (ArchivalProofType t) + // { + // case EXISTENCE: + // NonexistenceProofBody nonexistenceProof; + // case NONEXISTENCE: + // ExistenceProofBody existenceProof; + // } body; + // }; + // + // =========================================================================== + xdr.struct("ArchivalProof", [["epoch", xdr.lookup("Uint32")], ["body", xdr.lookup("ArchivalProofBody")]]); + + // === xdr source ============================================================ + // + // struct SorobanResources + // { + // // The ledger footprint of the transaction. + // LedgerFootprint footprint; + // // The maximum number of instructions this transaction can use + // uint32 instructions; + // + // // The maximum number of bytes this transaction can read from ledger + // uint32 readBytes; + // // The maximum number of bytes this transaction can write to ledger + // uint32 writeBytes; + // }; + // + // =========================================================================== + xdr.struct("SorobanResources", [["footprint", xdr.lookup("LedgerFootprint")], ["instructions", xdr.lookup("Uint32")], ["readBytes", xdr.lookup("Uint32")], ["writeBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SorobanTransactionData + // { + // ExtensionPoint ext; + // SorobanResources resources; + // // Amount of the transaction `fee` allocated to the Soroban resource fees. + // // The fraction of `resourceFee` corresponding to `resources` specified + // // above is *not* refundable (i.e. fees for instructions, ledger I/O), as + // // well as fees for the transaction size. + // // The remaining part of the fee is refundable and the charged value is + // // based on the actual consumption of refundable resources (events, ledger + // // rent bumps). + // // The `inclusionFee` used for prioritization of the transaction is defined + // // as `tx.fee - resourceFee`. + // int64 resourceFee; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionData", [["ext", xdr.lookup("ExtensionPoint")], ["resources", xdr.lookup("SorobanResources")], ["resourceFee", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionV0Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionV0 + // { + // uint256 sourceAccountEd25519; + // uint32 fee; + // SequenceNumber seqNum; + // TimeBounds* timeBounds; + // Memo memo; + // Operation operations; + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionV0", [["sourceAccountEd25519", xdr.lookup("Uint256")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionV0Ext")]]); + + // === xdr source ============================================================ + // + // struct TransactionV0Envelope + // { + // TransactionV0 tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("TransactionV0Envelope", [["tx", xdr.lookup("TransactionV0")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionData sorobanData; + // } + // + // =========================================================================== + xdr.union("TransactionExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "sorobanData"]], + arms: { + sorobanData: xdr.lookup("SorobanTransactionData") + } + }); + + // === xdr source ============================================================ + // + // struct Transaction + // { + // // account used to run the transaction + // MuxedAccount sourceAccount; + // + // // the fee the sourceAccount will pay + // uint32 fee; + // + // // sequence number to consume in the account + // SequenceNumber seqNum; + // + // // validity conditions + // Preconditions cond; + // + // Memo memo; + // + // Operation operations; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionData sorobanData; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("Transaction", [["sourceAccount", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["cond", xdr.lookup("Preconditions")], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionExt")]]); + + // === xdr source ============================================================ + // + // struct TransactionV1Envelope + // { + // Transaction tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("TransactionV1Envelope", [["tx", xdr.lookup("Transaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // } + // + // =========================================================================== + xdr.union("FeeBumpTransactionInnerTx", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTx", "v1"]], + arms: { + v1: xdr.lookup("TransactionV1Envelope") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("FeeBumpTransactionExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct FeeBumpTransaction + // { + // MuxedAccount feeSource; + // int64 fee; + // union switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // } + // innerTx; + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("FeeBumpTransaction", [["feeSource", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Int64")], ["innerTx", xdr.lookup("FeeBumpTransactionInnerTx")], ["ext", xdr.lookup("FeeBumpTransactionExt")]]); + + // === xdr source ============================================================ + // + // struct FeeBumpTransactionEnvelope + // { + // FeeBumpTransaction tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("FeeBumpTransactionEnvelope", [["tx", xdr.lookup("FeeBumpTransaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union TransactionEnvelope switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX_V0: + // TransactionV0Envelope v0; + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransactionEnvelope feeBump; + // }; + // + // =========================================================================== + xdr.union("TransactionEnvelope", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTxV0", "v0"], ["envelopeTypeTx", "v1"], ["envelopeTypeTxFeeBump", "feeBump"]], + arms: { + v0: xdr.lookup("TransactionV0Envelope"), + v1: xdr.lookup("TransactionV1Envelope"), + feeBump: xdr.lookup("FeeBumpTransactionEnvelope") + } + }); + + // === xdr source ============================================================ + // + // union switch (EnvelopeType type) + // { + // // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // case ENVELOPE_TYPE_TX: + // Transaction tx; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransaction feeBump; + // } + // + // =========================================================================== + xdr.union("TransactionSignaturePayloadTaggedTransaction", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTx", "tx"], ["envelopeTypeTxFeeBump", "feeBump"]], + arms: { + tx: xdr.lookup("Transaction"), + feeBump: xdr.lookup("FeeBumpTransaction") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionSignaturePayload + // { + // Hash networkId; + // union switch (EnvelopeType type) + // { + // // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // case ENVELOPE_TYPE_TX: + // Transaction tx; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransaction feeBump; + // } + // taggedTransaction; + // }; + // + // =========================================================================== + xdr.struct("TransactionSignaturePayload", [["networkId", xdr.lookup("Hash")], ["taggedTransaction", xdr.lookup("TransactionSignaturePayloadTaggedTransaction")]]); + + // === xdr source ============================================================ + // + // enum ClaimAtomType + // { + // CLAIM_ATOM_TYPE_V0 = 0, + // CLAIM_ATOM_TYPE_ORDER_BOOK = 1, + // CLAIM_ATOM_TYPE_LIQUIDITY_POOL = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimAtomType", { + claimAtomTypeV0: 0, + claimAtomTypeOrderBook: 1, + claimAtomTypeLiquidityPool: 2 + }); + + // === xdr source ============================================================ + // + // struct ClaimOfferAtomV0 + // { + // // emitted to identify the offer + // uint256 sellerEd25519; // Account that owns the offer + // int64 offerID; + // + // // amount and asset taken from the owner + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the owner + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimOfferAtomV0", [["sellerEd25519", xdr.lookup("Uint256")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClaimOfferAtom + // { + // // emitted to identify the offer + // AccountID sellerID; // Account that owns the offer + // int64 offerID; + // + // // amount and asset taken from the owner + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the owner + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimOfferAtom", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClaimLiquidityAtom + // { + // PoolID liquidityPoolID; + // + // // amount and asset taken from the pool + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the pool + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimLiquidityAtom", [["liquidityPoolId", xdr.lookup("PoolId")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union ClaimAtom switch (ClaimAtomType type) + // { + // case CLAIM_ATOM_TYPE_V0: + // ClaimOfferAtomV0 v0; + // case CLAIM_ATOM_TYPE_ORDER_BOOK: + // ClaimOfferAtom orderBook; + // case CLAIM_ATOM_TYPE_LIQUIDITY_POOL: + // ClaimLiquidityAtom liquidityPool; + // }; + // + // =========================================================================== + xdr.union("ClaimAtom", { + switchOn: xdr.lookup("ClaimAtomType"), + switchName: "type", + switches: [["claimAtomTypeV0", "v0"], ["claimAtomTypeOrderBook", "orderBook"], ["claimAtomTypeLiquidityPool", "liquidityPool"]], + arms: { + v0: xdr.lookup("ClaimOfferAtomV0"), + orderBook: xdr.lookup("ClaimOfferAtom"), + liquidityPool: xdr.lookup("ClaimLiquidityAtom") + } + }); + + // === xdr source ============================================================ + // + // enum CreateAccountResultCode + // { + // // codes considered as "success" for the operation + // CREATE_ACCOUNT_SUCCESS = 0, // account was created + // + // // codes considered as "failure" for the operation + // CREATE_ACCOUNT_MALFORMED = -1, // invalid destination + // CREATE_ACCOUNT_UNDERFUNDED = -2, // not enough funds in source account + // CREATE_ACCOUNT_LOW_RESERVE = + // -3, // would create an account below the min reserve + // CREATE_ACCOUNT_ALREADY_EXIST = -4 // account already exists + // }; + // + // =========================================================================== + xdr["enum"]("CreateAccountResultCode", { + createAccountSuccess: 0, + createAccountMalformed: -1, + createAccountUnderfunded: -2, + createAccountLowReserve: -3, + createAccountAlreadyExist: -4 + }); + + // === xdr source ============================================================ + // + // union CreateAccountResult switch (CreateAccountResultCode code) + // { + // case CREATE_ACCOUNT_SUCCESS: + // void; + // case CREATE_ACCOUNT_MALFORMED: + // case CREATE_ACCOUNT_UNDERFUNDED: + // case CREATE_ACCOUNT_LOW_RESERVE: + // case CREATE_ACCOUNT_ALREADY_EXIST: + // void; + // }; + // + // =========================================================================== + xdr.union("CreateAccountResult", { + switchOn: xdr.lookup("CreateAccountResultCode"), + switchName: "code", + switches: [["createAccountSuccess", xdr["void"]()], ["createAccountMalformed", xdr["void"]()], ["createAccountUnderfunded", xdr["void"]()], ["createAccountLowReserve", xdr["void"]()], ["createAccountAlreadyExist", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum PaymentResultCode + // { + // // codes considered as "success" for the operation + // PAYMENT_SUCCESS = 0, // payment successfully completed + // + // // codes considered as "failure" for the operation + // PAYMENT_MALFORMED = -1, // bad input + // PAYMENT_UNDERFUNDED = -2, // not enough funds in source account + // PAYMENT_SRC_NO_TRUST = -3, // no trust line on source account + // PAYMENT_SRC_NOT_AUTHORIZED = -4, // source not authorized to transfer + // PAYMENT_NO_DESTINATION = -5, // destination account does not exist + // PAYMENT_NO_TRUST = -6, // destination missing a trust line for asset + // PAYMENT_NOT_AUTHORIZED = -7, // destination not authorized to hold asset + // PAYMENT_LINE_FULL = -8, // destination would go above their limit + // PAYMENT_NO_ISSUER = -9 // missing issuer on asset + // }; + // + // =========================================================================== + xdr["enum"]("PaymentResultCode", { + paymentSuccess: 0, + paymentMalformed: -1, + paymentUnderfunded: -2, + paymentSrcNoTrust: -3, + paymentSrcNotAuthorized: -4, + paymentNoDestination: -5, + paymentNoTrust: -6, + paymentNotAuthorized: -7, + paymentLineFull: -8, + paymentNoIssuer: -9 + }); + + // === xdr source ============================================================ + // + // union PaymentResult switch (PaymentResultCode code) + // { + // case PAYMENT_SUCCESS: + // void; + // case PAYMENT_MALFORMED: + // case PAYMENT_UNDERFUNDED: + // case PAYMENT_SRC_NO_TRUST: + // case PAYMENT_SRC_NOT_AUTHORIZED: + // case PAYMENT_NO_DESTINATION: + // case PAYMENT_NO_TRUST: + // case PAYMENT_NOT_AUTHORIZED: + // case PAYMENT_LINE_FULL: + // case PAYMENT_NO_ISSUER: + // void; + // }; + // + // =========================================================================== + xdr.union("PaymentResult", { + switchOn: xdr.lookup("PaymentResultCode"), + switchName: "code", + switches: [["paymentSuccess", xdr["void"]()], ["paymentMalformed", xdr["void"]()], ["paymentUnderfunded", xdr["void"]()], ["paymentSrcNoTrust", xdr["void"]()], ["paymentSrcNotAuthorized", xdr["void"]()], ["paymentNoDestination", xdr["void"]()], ["paymentNoTrust", xdr["void"]()], ["paymentNotAuthorized", xdr["void"]()], ["paymentLineFull", xdr["void"]()], ["paymentNoIssuer", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum PathPaymentStrictReceiveResultCode + // { + // // codes considered as "success" for the operation + // PATH_PAYMENT_STRICT_RECEIVE_SUCCESS = 0, // success + // + // // codes considered as "failure" for the operation + // PATH_PAYMENT_STRICT_RECEIVE_MALFORMED = -1, // bad input + // PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED = + // -2, // not enough funds in source account + // PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST = + // -3, // no trust line on source account + // PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED = + // -4, // source not authorized to transfer + // PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION = + // -5, // destination account does not exist + // PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST = + // -6, // dest missing a trust line for asset + // PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED = + // -7, // dest not authorized to hold asset + // PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL = + // -8, // dest would go above their limit + // PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER = -9, // missing issuer on one asset + // PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS = + // -10, // not enough offers to satisfy path + // PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF = + // -11, // would cross one of its own offers + // PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX = -12 // could not satisfy sendmax + // }; + // + // =========================================================================== + xdr["enum"]("PathPaymentStrictReceiveResultCode", { + pathPaymentStrictReceiveSuccess: 0, + pathPaymentStrictReceiveMalformed: -1, + pathPaymentStrictReceiveUnderfunded: -2, + pathPaymentStrictReceiveSrcNoTrust: -3, + pathPaymentStrictReceiveSrcNotAuthorized: -4, + pathPaymentStrictReceiveNoDestination: -5, + pathPaymentStrictReceiveNoTrust: -6, + pathPaymentStrictReceiveNotAuthorized: -7, + pathPaymentStrictReceiveLineFull: -8, + pathPaymentStrictReceiveNoIssuer: -9, + pathPaymentStrictReceiveTooFewOffers: -10, + pathPaymentStrictReceiveOfferCrossSelf: -11, + pathPaymentStrictReceiveOverSendmax: -12 + }); + + // === xdr source ============================================================ + // + // struct SimplePaymentResult + // { + // AccountID destination; + // Asset asset; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("SimplePaymentResult", [["destination", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } + // + // =========================================================================== + xdr.struct("PathPaymentStrictReceiveResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]); + + // === xdr source ============================================================ + // + // union PathPaymentStrictReceiveResult switch ( + // PathPaymentStrictReceiveResultCode code) + // { + // case PATH_PAYMENT_STRICT_RECEIVE_SUCCESS: + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } success; + // case PATH_PAYMENT_STRICT_RECEIVE_MALFORMED: + // case PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED: + // case PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST: + // case PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION: + // case PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST: + // case PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL: + // void; + // case PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER: + // Asset noIssuer; // the asset that caused the error + // case PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS: + // case PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF: + // case PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX: + // void; + // }; + // + // =========================================================================== + xdr.union("PathPaymentStrictReceiveResult", { + switchOn: xdr.lookup("PathPaymentStrictReceiveResultCode"), + switchName: "code", + switches: [["pathPaymentStrictReceiveSuccess", "success"], ["pathPaymentStrictReceiveMalformed", xdr["void"]()], ["pathPaymentStrictReceiveUnderfunded", xdr["void"]()], ["pathPaymentStrictReceiveSrcNoTrust", xdr["void"]()], ["pathPaymentStrictReceiveSrcNotAuthorized", xdr["void"]()], ["pathPaymentStrictReceiveNoDestination", xdr["void"]()], ["pathPaymentStrictReceiveNoTrust", xdr["void"]()], ["pathPaymentStrictReceiveNotAuthorized", xdr["void"]()], ["pathPaymentStrictReceiveLineFull", xdr["void"]()], ["pathPaymentStrictReceiveNoIssuer", "noIssuer"], ["pathPaymentStrictReceiveTooFewOffers", xdr["void"]()], ["pathPaymentStrictReceiveOfferCrossSelf", xdr["void"]()], ["pathPaymentStrictReceiveOverSendmax", xdr["void"]()]], + arms: { + success: xdr.lookup("PathPaymentStrictReceiveResultSuccess"), + noIssuer: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // enum PathPaymentStrictSendResultCode + // { + // // codes considered as "success" for the operation + // PATH_PAYMENT_STRICT_SEND_SUCCESS = 0, // success + // + // // codes considered as "failure" for the operation + // PATH_PAYMENT_STRICT_SEND_MALFORMED = -1, // bad input + // PATH_PAYMENT_STRICT_SEND_UNDERFUNDED = + // -2, // not enough funds in source account + // PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST = + // -3, // no trust line on source account + // PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED = + // -4, // source not authorized to transfer + // PATH_PAYMENT_STRICT_SEND_NO_DESTINATION = + // -5, // destination account does not exist + // PATH_PAYMENT_STRICT_SEND_NO_TRUST = + // -6, // dest missing a trust line for asset + // PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED = + // -7, // dest not authorized to hold asset + // PATH_PAYMENT_STRICT_SEND_LINE_FULL = -8, // dest would go above their limit + // PATH_PAYMENT_STRICT_SEND_NO_ISSUER = -9, // missing issuer on one asset + // PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS = + // -10, // not enough offers to satisfy path + // PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF = + // -11, // would cross one of its own offers + // PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN = -12 // could not satisfy destMin + // }; + // + // =========================================================================== + xdr["enum"]("PathPaymentStrictSendResultCode", { + pathPaymentStrictSendSuccess: 0, + pathPaymentStrictSendMalformed: -1, + pathPaymentStrictSendUnderfunded: -2, + pathPaymentStrictSendSrcNoTrust: -3, + pathPaymentStrictSendSrcNotAuthorized: -4, + pathPaymentStrictSendNoDestination: -5, + pathPaymentStrictSendNoTrust: -6, + pathPaymentStrictSendNotAuthorized: -7, + pathPaymentStrictSendLineFull: -8, + pathPaymentStrictSendNoIssuer: -9, + pathPaymentStrictSendTooFewOffers: -10, + pathPaymentStrictSendOfferCrossSelf: -11, + pathPaymentStrictSendUnderDestmin: -12 + }); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } + // + // =========================================================================== + xdr.struct("PathPaymentStrictSendResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]); + + // === xdr source ============================================================ + // + // union PathPaymentStrictSendResult switch (PathPaymentStrictSendResultCode code) + // { + // case PATH_PAYMENT_STRICT_SEND_SUCCESS: + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } success; + // case PATH_PAYMENT_STRICT_SEND_MALFORMED: + // case PATH_PAYMENT_STRICT_SEND_UNDERFUNDED: + // case PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST: + // case PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_SEND_NO_DESTINATION: + // case PATH_PAYMENT_STRICT_SEND_NO_TRUST: + // case PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_SEND_LINE_FULL: + // void; + // case PATH_PAYMENT_STRICT_SEND_NO_ISSUER: + // Asset noIssuer; // the asset that caused the error + // case PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS: + // case PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF: + // case PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN: + // void; + // }; + // + // =========================================================================== + xdr.union("PathPaymentStrictSendResult", { + switchOn: xdr.lookup("PathPaymentStrictSendResultCode"), + switchName: "code", + switches: [["pathPaymentStrictSendSuccess", "success"], ["pathPaymentStrictSendMalformed", xdr["void"]()], ["pathPaymentStrictSendUnderfunded", xdr["void"]()], ["pathPaymentStrictSendSrcNoTrust", xdr["void"]()], ["pathPaymentStrictSendSrcNotAuthorized", xdr["void"]()], ["pathPaymentStrictSendNoDestination", xdr["void"]()], ["pathPaymentStrictSendNoTrust", xdr["void"]()], ["pathPaymentStrictSendNotAuthorized", xdr["void"]()], ["pathPaymentStrictSendLineFull", xdr["void"]()], ["pathPaymentStrictSendNoIssuer", "noIssuer"], ["pathPaymentStrictSendTooFewOffers", xdr["void"]()], ["pathPaymentStrictSendOfferCrossSelf", xdr["void"]()], ["pathPaymentStrictSendUnderDestmin", xdr["void"]()]], + arms: { + success: xdr.lookup("PathPaymentStrictSendResultSuccess"), + noIssuer: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // enum ManageSellOfferResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_SELL_OFFER_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // MANAGE_SELL_OFFER_MALFORMED = -1, // generated offer would be invalid + // MANAGE_SELL_OFFER_SELL_NO_TRUST = + // -2, // no trust line for what we're selling + // MANAGE_SELL_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying + // MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell + // MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy + // MANAGE_SELL_OFFER_LINE_FULL = -6, // can't receive more of what it's buying + // MANAGE_SELL_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell + // MANAGE_SELL_OFFER_CROSS_SELF = + // -8, // would cross an offer from the same user + // MANAGE_SELL_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling + // MANAGE_SELL_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying + // + // // update errors + // MANAGE_SELL_OFFER_NOT_FOUND = + // -11, // offerID does not match an existing offer + // + // MANAGE_SELL_OFFER_LOW_RESERVE = + // -12 // not enough funds to create a new Offer + // }; + // + // =========================================================================== + xdr["enum"]("ManageSellOfferResultCode", { + manageSellOfferSuccess: 0, + manageSellOfferMalformed: -1, + manageSellOfferSellNoTrust: -2, + manageSellOfferBuyNoTrust: -3, + manageSellOfferSellNotAuthorized: -4, + manageSellOfferBuyNotAuthorized: -5, + manageSellOfferLineFull: -6, + manageSellOfferUnderfunded: -7, + manageSellOfferCrossSelf: -8, + manageSellOfferSellNoIssuer: -9, + manageSellOfferBuyNoIssuer: -10, + manageSellOfferNotFound: -11, + manageSellOfferLowReserve: -12 + }); + + // === xdr source ============================================================ + // + // enum ManageOfferEffect + // { + // MANAGE_OFFER_CREATED = 0, + // MANAGE_OFFER_UPDATED = 1, + // MANAGE_OFFER_DELETED = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ManageOfferEffect", { + manageOfferCreated: 0, + manageOfferUpdated: 1, + manageOfferDeleted: 2 + }); + + // === xdr source ============================================================ + // + // union switch (ManageOfferEffect effect) + // { + // case MANAGE_OFFER_CREATED: + // case MANAGE_OFFER_UPDATED: + // OfferEntry offer; + // case MANAGE_OFFER_DELETED: + // void; + // } + // + // =========================================================================== + xdr.union("ManageOfferSuccessResultOffer", { + switchOn: xdr.lookup("ManageOfferEffect"), + switchName: "effect", + switches: [["manageOfferCreated", "offer"], ["manageOfferUpdated", "offer"], ["manageOfferDeleted", xdr["void"]()]], + arms: { + offer: xdr.lookup("OfferEntry") + } + }); + + // === xdr source ============================================================ + // + // struct ManageOfferSuccessResult + // { + // // offers that got claimed while creating this offer + // ClaimAtom offersClaimed<>; + // + // union switch (ManageOfferEffect effect) + // { + // case MANAGE_OFFER_CREATED: + // case MANAGE_OFFER_UPDATED: + // OfferEntry offer; + // case MANAGE_OFFER_DELETED: + // void; + // } + // offer; + // }; + // + // =========================================================================== + xdr.struct("ManageOfferSuccessResult", [["offersClaimed", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["offer", xdr.lookup("ManageOfferSuccessResultOffer")]]); + + // === xdr source ============================================================ + // + // union ManageSellOfferResult switch (ManageSellOfferResultCode code) + // { + // case MANAGE_SELL_OFFER_SUCCESS: + // ManageOfferSuccessResult success; + // case MANAGE_SELL_OFFER_MALFORMED: + // case MANAGE_SELL_OFFER_SELL_NO_TRUST: + // case MANAGE_SELL_OFFER_BUY_NO_TRUST: + // case MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED: + // case MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED: + // case MANAGE_SELL_OFFER_LINE_FULL: + // case MANAGE_SELL_OFFER_UNDERFUNDED: + // case MANAGE_SELL_OFFER_CROSS_SELF: + // case MANAGE_SELL_OFFER_SELL_NO_ISSUER: + // case MANAGE_SELL_OFFER_BUY_NO_ISSUER: + // case MANAGE_SELL_OFFER_NOT_FOUND: + // case MANAGE_SELL_OFFER_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageSellOfferResult", { + switchOn: xdr.lookup("ManageSellOfferResultCode"), + switchName: "code", + switches: [["manageSellOfferSuccess", "success"], ["manageSellOfferMalformed", xdr["void"]()], ["manageSellOfferSellNoTrust", xdr["void"]()], ["manageSellOfferBuyNoTrust", xdr["void"]()], ["manageSellOfferSellNotAuthorized", xdr["void"]()], ["manageSellOfferBuyNotAuthorized", xdr["void"]()], ["manageSellOfferLineFull", xdr["void"]()], ["manageSellOfferUnderfunded", xdr["void"]()], ["manageSellOfferCrossSelf", xdr["void"]()], ["manageSellOfferSellNoIssuer", xdr["void"]()], ["manageSellOfferBuyNoIssuer", xdr["void"]()], ["manageSellOfferNotFound", xdr["void"]()], ["manageSellOfferLowReserve", xdr["void"]()]], + arms: { + success: xdr.lookup("ManageOfferSuccessResult") + } + }); + + // === xdr source ============================================================ + // + // enum ManageBuyOfferResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_BUY_OFFER_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // MANAGE_BUY_OFFER_MALFORMED = -1, // generated offer would be invalid + // MANAGE_BUY_OFFER_SELL_NO_TRUST = -2, // no trust line for what we're selling + // MANAGE_BUY_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying + // MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell + // MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy + // MANAGE_BUY_OFFER_LINE_FULL = -6, // can't receive more of what it's buying + // MANAGE_BUY_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell + // MANAGE_BUY_OFFER_CROSS_SELF = -8, // would cross an offer from the same user + // MANAGE_BUY_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling + // MANAGE_BUY_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying + // + // // update errors + // MANAGE_BUY_OFFER_NOT_FOUND = + // -11, // offerID does not match an existing offer + // + // MANAGE_BUY_OFFER_LOW_RESERVE = -12 // not enough funds to create a new Offer + // }; + // + // =========================================================================== + xdr["enum"]("ManageBuyOfferResultCode", { + manageBuyOfferSuccess: 0, + manageBuyOfferMalformed: -1, + manageBuyOfferSellNoTrust: -2, + manageBuyOfferBuyNoTrust: -3, + manageBuyOfferSellNotAuthorized: -4, + manageBuyOfferBuyNotAuthorized: -5, + manageBuyOfferLineFull: -6, + manageBuyOfferUnderfunded: -7, + manageBuyOfferCrossSelf: -8, + manageBuyOfferSellNoIssuer: -9, + manageBuyOfferBuyNoIssuer: -10, + manageBuyOfferNotFound: -11, + manageBuyOfferLowReserve: -12 + }); + + // === xdr source ============================================================ + // + // union ManageBuyOfferResult switch (ManageBuyOfferResultCode code) + // { + // case MANAGE_BUY_OFFER_SUCCESS: + // ManageOfferSuccessResult success; + // case MANAGE_BUY_OFFER_MALFORMED: + // case MANAGE_BUY_OFFER_SELL_NO_TRUST: + // case MANAGE_BUY_OFFER_BUY_NO_TRUST: + // case MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED: + // case MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED: + // case MANAGE_BUY_OFFER_LINE_FULL: + // case MANAGE_BUY_OFFER_UNDERFUNDED: + // case MANAGE_BUY_OFFER_CROSS_SELF: + // case MANAGE_BUY_OFFER_SELL_NO_ISSUER: + // case MANAGE_BUY_OFFER_BUY_NO_ISSUER: + // case MANAGE_BUY_OFFER_NOT_FOUND: + // case MANAGE_BUY_OFFER_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageBuyOfferResult", { + switchOn: xdr.lookup("ManageBuyOfferResultCode"), + switchName: "code", + switches: [["manageBuyOfferSuccess", "success"], ["manageBuyOfferMalformed", xdr["void"]()], ["manageBuyOfferSellNoTrust", xdr["void"]()], ["manageBuyOfferBuyNoTrust", xdr["void"]()], ["manageBuyOfferSellNotAuthorized", xdr["void"]()], ["manageBuyOfferBuyNotAuthorized", xdr["void"]()], ["manageBuyOfferLineFull", xdr["void"]()], ["manageBuyOfferUnderfunded", xdr["void"]()], ["manageBuyOfferCrossSelf", xdr["void"]()], ["manageBuyOfferSellNoIssuer", xdr["void"]()], ["manageBuyOfferBuyNoIssuer", xdr["void"]()], ["manageBuyOfferNotFound", xdr["void"]()], ["manageBuyOfferLowReserve", xdr["void"]()]], + arms: { + success: xdr.lookup("ManageOfferSuccessResult") + } + }); + + // === xdr source ============================================================ + // + // enum SetOptionsResultCode + // { + // // codes considered as "success" for the operation + // SET_OPTIONS_SUCCESS = 0, + // // codes considered as "failure" for the operation + // SET_OPTIONS_LOW_RESERVE = -1, // not enough funds to add a signer + // SET_OPTIONS_TOO_MANY_SIGNERS = -2, // max number of signers already reached + // SET_OPTIONS_BAD_FLAGS = -3, // invalid combination of clear/set flags + // SET_OPTIONS_INVALID_INFLATION = -4, // inflation account does not exist + // SET_OPTIONS_CANT_CHANGE = -5, // can no longer change this option + // SET_OPTIONS_UNKNOWN_FLAG = -6, // can't set an unknown flag + // SET_OPTIONS_THRESHOLD_OUT_OF_RANGE = -7, // bad value for weight/threshold + // SET_OPTIONS_BAD_SIGNER = -8, // signer cannot be masterkey + // SET_OPTIONS_INVALID_HOME_DOMAIN = -9, // malformed home domain + // SET_OPTIONS_AUTH_REVOCABLE_REQUIRED = + // -10 // auth revocable is required for clawback + // }; + // + // =========================================================================== + xdr["enum"]("SetOptionsResultCode", { + setOptionsSuccess: 0, + setOptionsLowReserve: -1, + setOptionsTooManySigners: -2, + setOptionsBadFlags: -3, + setOptionsInvalidInflation: -4, + setOptionsCantChange: -5, + setOptionsUnknownFlag: -6, + setOptionsThresholdOutOfRange: -7, + setOptionsBadSigner: -8, + setOptionsInvalidHomeDomain: -9, + setOptionsAuthRevocableRequired: -10 + }); + + // === xdr source ============================================================ + // + // union SetOptionsResult switch (SetOptionsResultCode code) + // { + // case SET_OPTIONS_SUCCESS: + // void; + // case SET_OPTIONS_LOW_RESERVE: + // case SET_OPTIONS_TOO_MANY_SIGNERS: + // case SET_OPTIONS_BAD_FLAGS: + // case SET_OPTIONS_INVALID_INFLATION: + // case SET_OPTIONS_CANT_CHANGE: + // case SET_OPTIONS_UNKNOWN_FLAG: + // case SET_OPTIONS_THRESHOLD_OUT_OF_RANGE: + // case SET_OPTIONS_BAD_SIGNER: + // case SET_OPTIONS_INVALID_HOME_DOMAIN: + // case SET_OPTIONS_AUTH_REVOCABLE_REQUIRED: + // void; + // }; + // + // =========================================================================== + xdr.union("SetOptionsResult", { + switchOn: xdr.lookup("SetOptionsResultCode"), + switchName: "code", + switches: [["setOptionsSuccess", xdr["void"]()], ["setOptionsLowReserve", xdr["void"]()], ["setOptionsTooManySigners", xdr["void"]()], ["setOptionsBadFlags", xdr["void"]()], ["setOptionsInvalidInflation", xdr["void"]()], ["setOptionsCantChange", xdr["void"]()], ["setOptionsUnknownFlag", xdr["void"]()], ["setOptionsThresholdOutOfRange", xdr["void"]()], ["setOptionsBadSigner", xdr["void"]()], ["setOptionsInvalidHomeDomain", xdr["void"]()], ["setOptionsAuthRevocableRequired", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ChangeTrustResultCode + // { + // // codes considered as "success" for the operation + // CHANGE_TRUST_SUCCESS = 0, + // // codes considered as "failure" for the operation + // CHANGE_TRUST_MALFORMED = -1, // bad input + // CHANGE_TRUST_NO_ISSUER = -2, // could not find issuer + // CHANGE_TRUST_INVALID_LIMIT = -3, // cannot drop limit below balance + // // cannot create with a limit of 0 + // CHANGE_TRUST_LOW_RESERVE = + // -4, // not enough funds to create a new trust line, + // CHANGE_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed + // CHANGE_TRUST_TRUST_LINE_MISSING = -6, // Asset trustline is missing for pool + // CHANGE_TRUST_CANNOT_DELETE = + // -7, // Asset trustline is still referenced in a pool + // CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES = + // -8 // Asset trustline is deauthorized + // }; + // + // =========================================================================== + xdr["enum"]("ChangeTrustResultCode", { + changeTrustSuccess: 0, + changeTrustMalformed: -1, + changeTrustNoIssuer: -2, + changeTrustInvalidLimit: -3, + changeTrustLowReserve: -4, + changeTrustSelfNotAllowed: -5, + changeTrustTrustLineMissing: -6, + changeTrustCannotDelete: -7, + changeTrustNotAuthMaintainLiabilities: -8 + }); + + // === xdr source ============================================================ + // + // union ChangeTrustResult switch (ChangeTrustResultCode code) + // { + // case CHANGE_TRUST_SUCCESS: + // void; + // case CHANGE_TRUST_MALFORMED: + // case CHANGE_TRUST_NO_ISSUER: + // case CHANGE_TRUST_INVALID_LIMIT: + // case CHANGE_TRUST_LOW_RESERVE: + // case CHANGE_TRUST_SELF_NOT_ALLOWED: + // case CHANGE_TRUST_TRUST_LINE_MISSING: + // case CHANGE_TRUST_CANNOT_DELETE: + // case CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES: + // void; + // }; + // + // =========================================================================== + xdr.union("ChangeTrustResult", { + switchOn: xdr.lookup("ChangeTrustResultCode"), + switchName: "code", + switches: [["changeTrustSuccess", xdr["void"]()], ["changeTrustMalformed", xdr["void"]()], ["changeTrustNoIssuer", xdr["void"]()], ["changeTrustInvalidLimit", xdr["void"]()], ["changeTrustLowReserve", xdr["void"]()], ["changeTrustSelfNotAllowed", xdr["void"]()], ["changeTrustTrustLineMissing", xdr["void"]()], ["changeTrustCannotDelete", xdr["void"]()], ["changeTrustNotAuthMaintainLiabilities", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum AllowTrustResultCode + // { + // // codes considered as "success" for the operation + // ALLOW_TRUST_SUCCESS = 0, + // // codes considered as "failure" for the operation + // ALLOW_TRUST_MALFORMED = -1, // asset is not ASSET_TYPE_ALPHANUM + // ALLOW_TRUST_NO_TRUST_LINE = -2, // trustor does not have a trustline + // // source account does not require trust + // ALLOW_TRUST_TRUST_NOT_REQUIRED = -3, + // ALLOW_TRUST_CANT_REVOKE = -4, // source account can't revoke trust, + // ALLOW_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed + // ALLOW_TRUST_LOW_RESERVE = -6 // claimable balances can't be created + // // on revoke due to low reserves + // }; + // + // =========================================================================== + xdr["enum"]("AllowTrustResultCode", { + allowTrustSuccess: 0, + allowTrustMalformed: -1, + allowTrustNoTrustLine: -2, + allowTrustTrustNotRequired: -3, + allowTrustCantRevoke: -4, + allowTrustSelfNotAllowed: -5, + allowTrustLowReserve: -6 + }); + + // === xdr source ============================================================ + // + // union AllowTrustResult switch (AllowTrustResultCode code) + // { + // case ALLOW_TRUST_SUCCESS: + // void; + // case ALLOW_TRUST_MALFORMED: + // case ALLOW_TRUST_NO_TRUST_LINE: + // case ALLOW_TRUST_TRUST_NOT_REQUIRED: + // case ALLOW_TRUST_CANT_REVOKE: + // case ALLOW_TRUST_SELF_NOT_ALLOWED: + // case ALLOW_TRUST_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("AllowTrustResult", { + switchOn: xdr.lookup("AllowTrustResultCode"), + switchName: "code", + switches: [["allowTrustSuccess", xdr["void"]()], ["allowTrustMalformed", xdr["void"]()], ["allowTrustNoTrustLine", xdr["void"]()], ["allowTrustTrustNotRequired", xdr["void"]()], ["allowTrustCantRevoke", xdr["void"]()], ["allowTrustSelfNotAllowed", xdr["void"]()], ["allowTrustLowReserve", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum AccountMergeResultCode + // { + // // codes considered as "success" for the operation + // ACCOUNT_MERGE_SUCCESS = 0, + // // codes considered as "failure" for the operation + // ACCOUNT_MERGE_MALFORMED = -1, // can't merge onto itself + // ACCOUNT_MERGE_NO_ACCOUNT = -2, // destination does not exist + // ACCOUNT_MERGE_IMMUTABLE_SET = -3, // source account has AUTH_IMMUTABLE set + // ACCOUNT_MERGE_HAS_SUB_ENTRIES = -4, // account has trust lines/offers + // ACCOUNT_MERGE_SEQNUM_TOO_FAR = -5, // sequence number is over max allowed + // ACCOUNT_MERGE_DEST_FULL = -6, // can't add source balance to + // // destination balance + // ACCOUNT_MERGE_IS_SPONSOR = -7 // can't merge account that is a sponsor + // }; + // + // =========================================================================== + xdr["enum"]("AccountMergeResultCode", { + accountMergeSuccess: 0, + accountMergeMalformed: -1, + accountMergeNoAccount: -2, + accountMergeImmutableSet: -3, + accountMergeHasSubEntries: -4, + accountMergeSeqnumTooFar: -5, + accountMergeDestFull: -6, + accountMergeIsSponsor: -7 + }); + + // === xdr source ============================================================ + // + // union AccountMergeResult switch (AccountMergeResultCode code) + // { + // case ACCOUNT_MERGE_SUCCESS: + // int64 sourceAccountBalance; // how much got transferred from source account + // case ACCOUNT_MERGE_MALFORMED: + // case ACCOUNT_MERGE_NO_ACCOUNT: + // case ACCOUNT_MERGE_IMMUTABLE_SET: + // case ACCOUNT_MERGE_HAS_SUB_ENTRIES: + // case ACCOUNT_MERGE_SEQNUM_TOO_FAR: + // case ACCOUNT_MERGE_DEST_FULL: + // case ACCOUNT_MERGE_IS_SPONSOR: + // void; + // }; + // + // =========================================================================== + xdr.union("AccountMergeResult", { + switchOn: xdr.lookup("AccountMergeResultCode"), + switchName: "code", + switches: [["accountMergeSuccess", "sourceAccountBalance"], ["accountMergeMalformed", xdr["void"]()], ["accountMergeNoAccount", xdr["void"]()], ["accountMergeImmutableSet", xdr["void"]()], ["accountMergeHasSubEntries", xdr["void"]()], ["accountMergeSeqnumTooFar", xdr["void"]()], ["accountMergeDestFull", xdr["void"]()], ["accountMergeIsSponsor", xdr["void"]()]], + arms: { + sourceAccountBalance: xdr.lookup("Int64") + } + }); + + // === xdr source ============================================================ + // + // enum InflationResultCode + // { + // // codes considered as "success" for the operation + // INFLATION_SUCCESS = 0, + // // codes considered as "failure" for the operation + // INFLATION_NOT_TIME = -1 + // }; + // + // =========================================================================== + xdr["enum"]("InflationResultCode", { + inflationSuccess: 0, + inflationNotTime: -1 + }); + + // === xdr source ============================================================ + // + // struct InflationPayout // or use PaymentResultAtom to limit types? + // { + // AccountID destination; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("InflationPayout", [["destination", xdr.lookup("AccountId")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union InflationResult switch (InflationResultCode code) + // { + // case INFLATION_SUCCESS: + // InflationPayout payouts<>; + // case INFLATION_NOT_TIME: + // void; + // }; + // + // =========================================================================== + xdr.union("InflationResult", { + switchOn: xdr.lookup("InflationResultCode"), + switchName: "code", + switches: [["inflationSuccess", "payouts"], ["inflationNotTime", xdr["void"]()]], + arms: { + payouts: xdr.varArray(xdr.lookup("InflationPayout"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // enum ManageDataResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_DATA_SUCCESS = 0, + // // codes considered as "failure" for the operation + // MANAGE_DATA_NOT_SUPPORTED_YET = + // -1, // The network hasn't moved to this protocol change yet + // MANAGE_DATA_NAME_NOT_FOUND = + // -2, // Trying to remove a Data Entry that isn't there + // MANAGE_DATA_LOW_RESERVE = -3, // not enough funds to create a new Data Entry + // MANAGE_DATA_INVALID_NAME = -4 // Name not a valid string + // }; + // + // =========================================================================== + xdr["enum"]("ManageDataResultCode", { + manageDataSuccess: 0, + manageDataNotSupportedYet: -1, + manageDataNameNotFound: -2, + manageDataLowReserve: -3, + manageDataInvalidName: -4 + }); + + // === xdr source ============================================================ + // + // union ManageDataResult switch (ManageDataResultCode code) + // { + // case MANAGE_DATA_SUCCESS: + // void; + // case MANAGE_DATA_NOT_SUPPORTED_YET: + // case MANAGE_DATA_NAME_NOT_FOUND: + // case MANAGE_DATA_LOW_RESERVE: + // case MANAGE_DATA_INVALID_NAME: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageDataResult", { + switchOn: xdr.lookup("ManageDataResultCode"), + switchName: "code", + switches: [["manageDataSuccess", xdr["void"]()], ["manageDataNotSupportedYet", xdr["void"]()], ["manageDataNameNotFound", xdr["void"]()], ["manageDataLowReserve", xdr["void"]()], ["manageDataInvalidName", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum BumpSequenceResultCode + // { + // // codes considered as "success" for the operation + // BUMP_SEQUENCE_SUCCESS = 0, + // // codes considered as "failure" for the operation + // BUMP_SEQUENCE_BAD_SEQ = -1 // `bumpTo` is not within bounds + // }; + // + // =========================================================================== + xdr["enum"]("BumpSequenceResultCode", { + bumpSequenceSuccess: 0, + bumpSequenceBadSeq: -1 + }); + + // === xdr source ============================================================ + // + // union BumpSequenceResult switch (BumpSequenceResultCode code) + // { + // case BUMP_SEQUENCE_SUCCESS: + // void; + // case BUMP_SEQUENCE_BAD_SEQ: + // void; + // }; + // + // =========================================================================== + xdr.union("BumpSequenceResult", { + switchOn: xdr.lookup("BumpSequenceResultCode"), + switchName: "code", + switches: [["bumpSequenceSuccess", xdr["void"]()], ["bumpSequenceBadSeq", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum CreateClaimableBalanceResultCode + // { + // CREATE_CLAIMABLE_BALANCE_SUCCESS = 0, + // CREATE_CLAIMABLE_BALANCE_MALFORMED = -1, + // CREATE_CLAIMABLE_BALANCE_LOW_RESERVE = -2, + // CREATE_CLAIMABLE_BALANCE_NO_TRUST = -3, + // CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -4, + // CREATE_CLAIMABLE_BALANCE_UNDERFUNDED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("CreateClaimableBalanceResultCode", { + createClaimableBalanceSuccess: 0, + createClaimableBalanceMalformed: -1, + createClaimableBalanceLowReserve: -2, + createClaimableBalanceNoTrust: -3, + createClaimableBalanceNotAuthorized: -4, + createClaimableBalanceUnderfunded: -5 + }); + + // === xdr source ============================================================ + // + // union CreateClaimableBalanceResult switch ( + // CreateClaimableBalanceResultCode code) + // { + // case CREATE_CLAIMABLE_BALANCE_SUCCESS: + // ClaimableBalanceID balanceID; + // case CREATE_CLAIMABLE_BALANCE_MALFORMED: + // case CREATE_CLAIMABLE_BALANCE_LOW_RESERVE: + // case CREATE_CLAIMABLE_BALANCE_NO_TRUST: + // case CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED: + // case CREATE_CLAIMABLE_BALANCE_UNDERFUNDED: + // void; + // }; + // + // =========================================================================== + xdr.union("CreateClaimableBalanceResult", { + switchOn: xdr.lookup("CreateClaimableBalanceResultCode"), + switchName: "code", + switches: [["createClaimableBalanceSuccess", "balanceId"], ["createClaimableBalanceMalformed", xdr["void"]()], ["createClaimableBalanceLowReserve", xdr["void"]()], ["createClaimableBalanceNoTrust", xdr["void"]()], ["createClaimableBalanceNotAuthorized", xdr["void"]()], ["createClaimableBalanceUnderfunded", xdr["void"]()]], + arms: { + balanceId: xdr.lookup("ClaimableBalanceId") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimClaimableBalanceResultCode + // { + // CLAIM_CLAIMABLE_BALANCE_SUCCESS = 0, + // CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1, + // CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM = -2, + // CLAIM_CLAIMABLE_BALANCE_LINE_FULL = -3, + // CLAIM_CLAIMABLE_BALANCE_NO_TRUST = -4, + // CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimClaimableBalanceResultCode", { + claimClaimableBalanceSuccess: 0, + claimClaimableBalanceDoesNotExist: -1, + claimClaimableBalanceCannotClaim: -2, + claimClaimableBalanceLineFull: -3, + claimClaimableBalanceNoTrust: -4, + claimClaimableBalanceNotAuthorized: -5 + }); + + // === xdr source ============================================================ + // + // union ClaimClaimableBalanceResult switch (ClaimClaimableBalanceResultCode code) + // { + // case CLAIM_CLAIMABLE_BALANCE_SUCCESS: + // void; + // case CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST: + // case CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM: + // case CLAIM_CLAIMABLE_BALANCE_LINE_FULL: + // case CLAIM_CLAIMABLE_BALANCE_NO_TRUST: + // case CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClaimClaimableBalanceResult", { + switchOn: xdr.lookup("ClaimClaimableBalanceResultCode"), + switchName: "code", + switches: [["claimClaimableBalanceSuccess", xdr["void"]()], ["claimClaimableBalanceDoesNotExist", xdr["void"]()], ["claimClaimableBalanceCannotClaim", xdr["void"]()], ["claimClaimableBalanceLineFull", xdr["void"]()], ["claimClaimableBalanceNoTrust", xdr["void"]()], ["claimClaimableBalanceNotAuthorized", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum BeginSponsoringFutureReservesResultCode + // { + // // codes considered as "success" for the operation + // BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED = -1, + // BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED = -2, + // BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("BeginSponsoringFutureReservesResultCode", { + beginSponsoringFutureReservesSuccess: 0, + beginSponsoringFutureReservesMalformed: -1, + beginSponsoringFutureReservesAlreadySponsored: -2, + beginSponsoringFutureReservesRecursive: -3 + }); + + // === xdr source ============================================================ + // + // union BeginSponsoringFutureReservesResult switch ( + // BeginSponsoringFutureReservesResultCode code) + // { + // case BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS: + // void; + // case BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED: + // case BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED: + // case BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE: + // void; + // }; + // + // =========================================================================== + xdr.union("BeginSponsoringFutureReservesResult", { + switchOn: xdr.lookup("BeginSponsoringFutureReservesResultCode"), + switchName: "code", + switches: [["beginSponsoringFutureReservesSuccess", xdr["void"]()], ["beginSponsoringFutureReservesMalformed", xdr["void"]()], ["beginSponsoringFutureReservesAlreadySponsored", xdr["void"]()], ["beginSponsoringFutureReservesRecursive", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum EndSponsoringFutureReservesResultCode + // { + // // codes considered as "success" for the operation + // END_SPONSORING_FUTURE_RESERVES_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED = -1 + // }; + // + // =========================================================================== + xdr["enum"]("EndSponsoringFutureReservesResultCode", { + endSponsoringFutureReservesSuccess: 0, + endSponsoringFutureReservesNotSponsored: -1 + }); + + // === xdr source ============================================================ + // + // union EndSponsoringFutureReservesResult switch ( + // EndSponsoringFutureReservesResultCode code) + // { + // case END_SPONSORING_FUTURE_RESERVES_SUCCESS: + // void; + // case END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED: + // void; + // }; + // + // =========================================================================== + xdr.union("EndSponsoringFutureReservesResult", { + switchOn: xdr.lookup("EndSponsoringFutureReservesResultCode"), + switchName: "code", + switches: [["endSponsoringFutureReservesSuccess", xdr["void"]()], ["endSponsoringFutureReservesNotSponsored", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum RevokeSponsorshipResultCode + // { + // // codes considered as "success" for the operation + // REVOKE_SPONSORSHIP_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // REVOKE_SPONSORSHIP_DOES_NOT_EXIST = -1, + // REVOKE_SPONSORSHIP_NOT_SPONSOR = -2, + // REVOKE_SPONSORSHIP_LOW_RESERVE = -3, + // REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE = -4, + // REVOKE_SPONSORSHIP_MALFORMED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("RevokeSponsorshipResultCode", { + revokeSponsorshipSuccess: 0, + revokeSponsorshipDoesNotExist: -1, + revokeSponsorshipNotSponsor: -2, + revokeSponsorshipLowReserve: -3, + revokeSponsorshipOnlyTransferable: -4, + revokeSponsorshipMalformed: -5 + }); + + // === xdr source ============================================================ + // + // union RevokeSponsorshipResult switch (RevokeSponsorshipResultCode code) + // { + // case REVOKE_SPONSORSHIP_SUCCESS: + // void; + // case REVOKE_SPONSORSHIP_DOES_NOT_EXIST: + // case REVOKE_SPONSORSHIP_NOT_SPONSOR: + // case REVOKE_SPONSORSHIP_LOW_RESERVE: + // case REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE: + // case REVOKE_SPONSORSHIP_MALFORMED: + // void; + // }; + // + // =========================================================================== + xdr.union("RevokeSponsorshipResult", { + switchOn: xdr.lookup("RevokeSponsorshipResultCode"), + switchName: "code", + switches: [["revokeSponsorshipSuccess", xdr["void"]()], ["revokeSponsorshipDoesNotExist", xdr["void"]()], ["revokeSponsorshipNotSponsor", xdr["void"]()], ["revokeSponsorshipLowReserve", xdr["void"]()], ["revokeSponsorshipOnlyTransferable", xdr["void"]()], ["revokeSponsorshipMalformed", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ClawbackResultCode + // { + // // codes considered as "success" for the operation + // CLAWBACK_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // CLAWBACK_MALFORMED = -1, + // CLAWBACK_NOT_CLAWBACK_ENABLED = -2, + // CLAWBACK_NO_TRUST = -3, + // CLAWBACK_UNDERFUNDED = -4 + // }; + // + // =========================================================================== + xdr["enum"]("ClawbackResultCode", { + clawbackSuccess: 0, + clawbackMalformed: -1, + clawbackNotClawbackEnabled: -2, + clawbackNoTrust: -3, + clawbackUnderfunded: -4 + }); + + // === xdr source ============================================================ + // + // union ClawbackResult switch (ClawbackResultCode code) + // { + // case CLAWBACK_SUCCESS: + // void; + // case CLAWBACK_MALFORMED: + // case CLAWBACK_NOT_CLAWBACK_ENABLED: + // case CLAWBACK_NO_TRUST: + // case CLAWBACK_UNDERFUNDED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClawbackResult", { + switchOn: xdr.lookup("ClawbackResultCode"), + switchName: "code", + switches: [["clawbackSuccess", xdr["void"]()], ["clawbackMalformed", xdr["void"]()], ["clawbackNotClawbackEnabled", xdr["void"]()], ["clawbackNoTrust", xdr["void"]()], ["clawbackUnderfunded", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ClawbackClaimableBalanceResultCode + // { + // // codes considered as "success" for the operation + // CLAWBACK_CLAIMABLE_BALANCE_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1, + // CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER = -2, + // CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED = -3 + // }; + // + // =========================================================================== + xdr["enum"]("ClawbackClaimableBalanceResultCode", { + clawbackClaimableBalanceSuccess: 0, + clawbackClaimableBalanceDoesNotExist: -1, + clawbackClaimableBalanceNotIssuer: -2, + clawbackClaimableBalanceNotClawbackEnabled: -3 + }); + + // === xdr source ============================================================ + // + // union ClawbackClaimableBalanceResult switch ( + // ClawbackClaimableBalanceResultCode code) + // { + // case CLAWBACK_CLAIMABLE_BALANCE_SUCCESS: + // void; + // case CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST: + // case CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER: + // case CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClawbackClaimableBalanceResult", { + switchOn: xdr.lookup("ClawbackClaimableBalanceResultCode"), + switchName: "code", + switches: [["clawbackClaimableBalanceSuccess", xdr["void"]()], ["clawbackClaimableBalanceDoesNotExist", xdr["void"]()], ["clawbackClaimableBalanceNotIssuer", xdr["void"]()], ["clawbackClaimableBalanceNotClawbackEnabled", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum SetTrustLineFlagsResultCode + // { + // // codes considered as "success" for the operation + // SET_TRUST_LINE_FLAGS_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // SET_TRUST_LINE_FLAGS_MALFORMED = -1, + // SET_TRUST_LINE_FLAGS_NO_TRUST_LINE = -2, + // SET_TRUST_LINE_FLAGS_CANT_REVOKE = -3, + // SET_TRUST_LINE_FLAGS_INVALID_STATE = -4, + // SET_TRUST_LINE_FLAGS_LOW_RESERVE = -5 // claimable balances can't be created + // // on revoke due to low reserves + // }; + // + // =========================================================================== + xdr["enum"]("SetTrustLineFlagsResultCode", { + setTrustLineFlagsSuccess: 0, + setTrustLineFlagsMalformed: -1, + setTrustLineFlagsNoTrustLine: -2, + setTrustLineFlagsCantRevoke: -3, + setTrustLineFlagsInvalidState: -4, + setTrustLineFlagsLowReserve: -5 + }); + + // === xdr source ============================================================ + // + // union SetTrustLineFlagsResult switch (SetTrustLineFlagsResultCode code) + // { + // case SET_TRUST_LINE_FLAGS_SUCCESS: + // void; + // case SET_TRUST_LINE_FLAGS_MALFORMED: + // case SET_TRUST_LINE_FLAGS_NO_TRUST_LINE: + // case SET_TRUST_LINE_FLAGS_CANT_REVOKE: + // case SET_TRUST_LINE_FLAGS_INVALID_STATE: + // case SET_TRUST_LINE_FLAGS_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("SetTrustLineFlagsResult", { + switchOn: xdr.lookup("SetTrustLineFlagsResultCode"), + switchName: "code", + switches: [["setTrustLineFlagsSuccess", xdr["void"]()], ["setTrustLineFlagsMalformed", xdr["void"]()], ["setTrustLineFlagsNoTrustLine", xdr["void"]()], ["setTrustLineFlagsCantRevoke", xdr["void"]()], ["setTrustLineFlagsInvalidState", xdr["void"]()], ["setTrustLineFlagsLowReserve", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum LiquidityPoolDepositResultCode + // { + // // codes considered as "success" for the operation + // LIQUIDITY_POOL_DEPOSIT_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // LIQUIDITY_POOL_DEPOSIT_MALFORMED = -1, // bad input + // LIQUIDITY_POOL_DEPOSIT_NO_TRUST = -2, // no trust line for one of the + // // assets + // LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED = -3, // not authorized for one of the + // // assets + // LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED = -4, // not enough balance for one of + // // the assets + // LIQUIDITY_POOL_DEPOSIT_LINE_FULL = -5, // pool share trust line doesn't + // // have sufficient limit + // LIQUIDITY_POOL_DEPOSIT_BAD_PRICE = -6, // deposit price outside bounds + // LIQUIDITY_POOL_DEPOSIT_POOL_FULL = -7 // pool reserves are full + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolDepositResultCode", { + liquidityPoolDepositSuccess: 0, + liquidityPoolDepositMalformed: -1, + liquidityPoolDepositNoTrust: -2, + liquidityPoolDepositNotAuthorized: -3, + liquidityPoolDepositUnderfunded: -4, + liquidityPoolDepositLineFull: -5, + liquidityPoolDepositBadPrice: -6, + liquidityPoolDepositPoolFull: -7 + }); + + // === xdr source ============================================================ + // + // union LiquidityPoolDepositResult switch (LiquidityPoolDepositResultCode code) + // { + // case LIQUIDITY_POOL_DEPOSIT_SUCCESS: + // void; + // case LIQUIDITY_POOL_DEPOSIT_MALFORMED: + // case LIQUIDITY_POOL_DEPOSIT_NO_TRUST: + // case LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED: + // case LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED: + // case LIQUIDITY_POOL_DEPOSIT_LINE_FULL: + // case LIQUIDITY_POOL_DEPOSIT_BAD_PRICE: + // case LIQUIDITY_POOL_DEPOSIT_POOL_FULL: + // void; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolDepositResult", { + switchOn: xdr.lookup("LiquidityPoolDepositResultCode"), + switchName: "code", + switches: [["liquidityPoolDepositSuccess", xdr["void"]()], ["liquidityPoolDepositMalformed", xdr["void"]()], ["liquidityPoolDepositNoTrust", xdr["void"]()], ["liquidityPoolDepositNotAuthorized", xdr["void"]()], ["liquidityPoolDepositUnderfunded", xdr["void"]()], ["liquidityPoolDepositLineFull", xdr["void"]()], ["liquidityPoolDepositBadPrice", xdr["void"]()], ["liquidityPoolDepositPoolFull", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum LiquidityPoolWithdrawResultCode + // { + // // codes considered as "success" for the operation + // LIQUIDITY_POOL_WITHDRAW_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // LIQUIDITY_POOL_WITHDRAW_MALFORMED = -1, // bad input + // LIQUIDITY_POOL_WITHDRAW_NO_TRUST = -2, // no trust line for one of the + // // assets + // LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED = -3, // not enough balance of the + // // pool share + // LIQUIDITY_POOL_WITHDRAW_LINE_FULL = -4, // would go above limit for one + // // of the assets + // LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM = -5 // didn't withdraw enough + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolWithdrawResultCode", { + liquidityPoolWithdrawSuccess: 0, + liquidityPoolWithdrawMalformed: -1, + liquidityPoolWithdrawNoTrust: -2, + liquidityPoolWithdrawUnderfunded: -3, + liquidityPoolWithdrawLineFull: -4, + liquidityPoolWithdrawUnderMinimum: -5 + }); + + // === xdr source ============================================================ + // + // union LiquidityPoolWithdrawResult switch (LiquidityPoolWithdrawResultCode code) + // { + // case LIQUIDITY_POOL_WITHDRAW_SUCCESS: + // void; + // case LIQUIDITY_POOL_WITHDRAW_MALFORMED: + // case LIQUIDITY_POOL_WITHDRAW_NO_TRUST: + // case LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED: + // case LIQUIDITY_POOL_WITHDRAW_LINE_FULL: + // case LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM: + // void; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolWithdrawResult", { + switchOn: xdr.lookup("LiquidityPoolWithdrawResultCode"), + switchName: "code", + switches: [["liquidityPoolWithdrawSuccess", xdr["void"]()], ["liquidityPoolWithdrawMalformed", xdr["void"]()], ["liquidityPoolWithdrawNoTrust", xdr["void"]()], ["liquidityPoolWithdrawUnderfunded", xdr["void"]()], ["liquidityPoolWithdrawLineFull", xdr["void"]()], ["liquidityPoolWithdrawUnderMinimum", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum InvokeHostFunctionResultCode + // { + // // codes considered as "success" for the operation + // INVOKE_HOST_FUNCTION_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // INVOKE_HOST_FUNCTION_MALFORMED = -1, + // INVOKE_HOST_FUNCTION_TRAPPED = -2, + // INVOKE_HOST_FUNCTION_RESOURCE_LIMIT_EXCEEDED = -3, + // INVOKE_HOST_FUNCTION_ENTRY_ARCHIVED = -4, + // INVOKE_HOST_FUNCTION_INSUFFICIENT_REFUNDABLE_FEE = -5 + // }; + // + // =========================================================================== + xdr["enum"]("InvokeHostFunctionResultCode", { + invokeHostFunctionSuccess: 0, + invokeHostFunctionMalformed: -1, + invokeHostFunctionTrapped: -2, + invokeHostFunctionResourceLimitExceeded: -3, + invokeHostFunctionEntryArchived: -4, + invokeHostFunctionInsufficientRefundableFee: -5 + }); + + // === xdr source ============================================================ + // + // union InvokeHostFunctionResult switch (InvokeHostFunctionResultCode code) + // { + // case INVOKE_HOST_FUNCTION_SUCCESS: + // Hash success; // sha256(InvokeHostFunctionSuccessPreImage) + // case INVOKE_HOST_FUNCTION_MALFORMED: + // case INVOKE_HOST_FUNCTION_TRAPPED: + // case INVOKE_HOST_FUNCTION_RESOURCE_LIMIT_EXCEEDED: + // case INVOKE_HOST_FUNCTION_ENTRY_ARCHIVED: + // case INVOKE_HOST_FUNCTION_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("InvokeHostFunctionResult", { + switchOn: xdr.lookup("InvokeHostFunctionResultCode"), + switchName: "code", + switches: [["invokeHostFunctionSuccess", "success"], ["invokeHostFunctionMalformed", xdr["void"]()], ["invokeHostFunctionTrapped", xdr["void"]()], ["invokeHostFunctionResourceLimitExceeded", xdr["void"]()], ["invokeHostFunctionEntryArchived", xdr["void"]()], ["invokeHostFunctionInsufficientRefundableFee", xdr["void"]()]], + arms: { + success: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum ExtendFootprintTTLResultCode + // { + // // codes considered as "success" for the operation + // EXTEND_FOOTPRINT_TTL_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // EXTEND_FOOTPRINT_TTL_MALFORMED = -1, + // EXTEND_FOOTPRINT_TTL_RESOURCE_LIMIT_EXCEEDED = -2, + // EXTEND_FOOTPRINT_TTL_INSUFFICIENT_REFUNDABLE_FEE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("ExtendFootprintTtlResultCode", { + extendFootprintTtlSuccess: 0, + extendFootprintTtlMalformed: -1, + extendFootprintTtlResourceLimitExceeded: -2, + extendFootprintTtlInsufficientRefundableFee: -3 + }); + + // === xdr source ============================================================ + // + // union ExtendFootprintTTLResult switch (ExtendFootprintTTLResultCode code) + // { + // case EXTEND_FOOTPRINT_TTL_SUCCESS: + // void; + // case EXTEND_FOOTPRINT_TTL_MALFORMED: + // case EXTEND_FOOTPRINT_TTL_RESOURCE_LIMIT_EXCEEDED: + // case EXTEND_FOOTPRINT_TTL_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("ExtendFootprintTtlResult", { + switchOn: xdr.lookup("ExtendFootprintTtlResultCode"), + switchName: "code", + switches: [["extendFootprintTtlSuccess", xdr["void"]()], ["extendFootprintTtlMalformed", xdr["void"]()], ["extendFootprintTtlResourceLimitExceeded", xdr["void"]()], ["extendFootprintTtlInsufficientRefundableFee", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum RestoreFootprintResultCode + // { + // // codes considered as "success" for the operation + // RESTORE_FOOTPRINT_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // RESTORE_FOOTPRINT_MALFORMED = -1, + // RESTORE_FOOTPRINT_RESOURCE_LIMIT_EXCEEDED = -2, + // RESTORE_FOOTPRINT_INSUFFICIENT_REFUNDABLE_FEE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("RestoreFootprintResultCode", { + restoreFootprintSuccess: 0, + restoreFootprintMalformed: -1, + restoreFootprintResourceLimitExceeded: -2, + restoreFootprintInsufficientRefundableFee: -3 + }); + + // === xdr source ============================================================ + // + // union RestoreFootprintResult switch (RestoreFootprintResultCode code) + // { + // case RESTORE_FOOTPRINT_SUCCESS: + // void; + // case RESTORE_FOOTPRINT_MALFORMED: + // case RESTORE_FOOTPRINT_RESOURCE_LIMIT_EXCEEDED: + // case RESTORE_FOOTPRINT_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("RestoreFootprintResult", { + switchOn: xdr.lookup("RestoreFootprintResultCode"), + switchName: "code", + switches: [["restoreFootprintSuccess", xdr["void"]()], ["restoreFootprintMalformed", xdr["void"]()], ["restoreFootprintResourceLimitExceeded", xdr["void"]()], ["restoreFootprintInsufficientRefundableFee", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum OperationResultCode + // { + // opINNER = 0, // inner object result is valid + // + // opBAD_AUTH = -1, // too few valid signatures / wrong network + // opNO_ACCOUNT = -2, // source account was not found + // opNOT_SUPPORTED = -3, // operation not supported at this time + // opTOO_MANY_SUBENTRIES = -4, // max number of subentries already reached + // opEXCEEDED_WORK_LIMIT = -5, // operation did too much work + // opTOO_MANY_SPONSORING = -6 // account is sponsoring too many entries + // }; + // + // =========================================================================== + xdr["enum"]("OperationResultCode", { + opInner: 0, + opBadAuth: -1, + opNoAccount: -2, + opNotSupported: -3, + opTooManySubentries: -4, + opExceededWorkLimit: -5, + opTooManySponsoring: -6 + }); + + // === xdr source ============================================================ + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountResult createAccountResult; + // case PAYMENT: + // PaymentResult paymentResult; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult; + // case MANAGE_SELL_OFFER: + // ManageSellOfferResult manageSellOfferResult; + // case CREATE_PASSIVE_SELL_OFFER: + // ManageSellOfferResult createPassiveSellOfferResult; + // case SET_OPTIONS: + // SetOptionsResult setOptionsResult; + // case CHANGE_TRUST: + // ChangeTrustResult changeTrustResult; + // case ALLOW_TRUST: + // AllowTrustResult allowTrustResult; + // case ACCOUNT_MERGE: + // AccountMergeResult accountMergeResult; + // case INFLATION: + // InflationResult inflationResult; + // case MANAGE_DATA: + // ManageDataResult manageDataResult; + // case BUMP_SEQUENCE: + // BumpSequenceResult bumpSeqResult; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferResult manageBuyOfferResult; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendResult pathPaymentStrictSendResult; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceResult createClaimableBalanceResult; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceResult claimClaimableBalanceResult; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult; + // case END_SPONSORING_FUTURE_RESERVES: + // EndSponsoringFutureReservesResult endSponsoringFutureReservesResult; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipResult revokeSponsorshipResult; + // case CLAWBACK: + // ClawbackResult clawbackResult; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceResult clawbackClaimableBalanceResult; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsResult setTrustLineFlagsResult; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositResult liquidityPoolDepositResult; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawResult liquidityPoolWithdrawResult; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionResult invokeHostFunctionResult; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLResult extendFootprintTTLResult; + // case RESTORE_FOOTPRINT: + // RestoreFootprintResult restoreFootprintResult; + // } + // + // =========================================================================== + xdr.union("OperationResultTr", { + switchOn: xdr.lookup("OperationType"), + switchName: "type", + switches: [["createAccount", "createAccountResult"], ["payment", "paymentResult"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveResult"], ["manageSellOffer", "manageSellOfferResult"], ["createPassiveSellOffer", "createPassiveSellOfferResult"], ["setOptions", "setOptionsResult"], ["changeTrust", "changeTrustResult"], ["allowTrust", "allowTrustResult"], ["accountMerge", "accountMergeResult"], ["inflation", "inflationResult"], ["manageData", "manageDataResult"], ["bumpSequence", "bumpSeqResult"], ["manageBuyOffer", "manageBuyOfferResult"], ["pathPaymentStrictSend", "pathPaymentStrictSendResult"], ["createClaimableBalance", "createClaimableBalanceResult"], ["claimClaimableBalance", "claimClaimableBalanceResult"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesResult"], ["endSponsoringFutureReserves", "endSponsoringFutureReservesResult"], ["revokeSponsorship", "revokeSponsorshipResult"], ["clawback", "clawbackResult"], ["clawbackClaimableBalance", "clawbackClaimableBalanceResult"], ["setTrustLineFlags", "setTrustLineFlagsResult"], ["liquidityPoolDeposit", "liquidityPoolDepositResult"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawResult"], ["invokeHostFunction", "invokeHostFunctionResult"], ["extendFootprintTtl", "extendFootprintTtlResult"], ["restoreFootprint", "restoreFootprintResult"]], + arms: { + createAccountResult: xdr.lookup("CreateAccountResult"), + paymentResult: xdr.lookup("PaymentResult"), + pathPaymentStrictReceiveResult: xdr.lookup("PathPaymentStrictReceiveResult"), + manageSellOfferResult: xdr.lookup("ManageSellOfferResult"), + createPassiveSellOfferResult: xdr.lookup("ManageSellOfferResult"), + setOptionsResult: xdr.lookup("SetOptionsResult"), + changeTrustResult: xdr.lookup("ChangeTrustResult"), + allowTrustResult: xdr.lookup("AllowTrustResult"), + accountMergeResult: xdr.lookup("AccountMergeResult"), + inflationResult: xdr.lookup("InflationResult"), + manageDataResult: xdr.lookup("ManageDataResult"), + bumpSeqResult: xdr.lookup("BumpSequenceResult"), + manageBuyOfferResult: xdr.lookup("ManageBuyOfferResult"), + pathPaymentStrictSendResult: xdr.lookup("PathPaymentStrictSendResult"), + createClaimableBalanceResult: xdr.lookup("CreateClaimableBalanceResult"), + claimClaimableBalanceResult: xdr.lookup("ClaimClaimableBalanceResult"), + beginSponsoringFutureReservesResult: xdr.lookup("BeginSponsoringFutureReservesResult"), + endSponsoringFutureReservesResult: xdr.lookup("EndSponsoringFutureReservesResult"), + revokeSponsorshipResult: xdr.lookup("RevokeSponsorshipResult"), + clawbackResult: xdr.lookup("ClawbackResult"), + clawbackClaimableBalanceResult: xdr.lookup("ClawbackClaimableBalanceResult"), + setTrustLineFlagsResult: xdr.lookup("SetTrustLineFlagsResult"), + liquidityPoolDepositResult: xdr.lookup("LiquidityPoolDepositResult"), + liquidityPoolWithdrawResult: xdr.lookup("LiquidityPoolWithdrawResult"), + invokeHostFunctionResult: xdr.lookup("InvokeHostFunctionResult"), + extendFootprintTtlResult: xdr.lookup("ExtendFootprintTtlResult"), + restoreFootprintResult: xdr.lookup("RestoreFootprintResult") + } + }); + + // === xdr source ============================================================ + // + // union OperationResult switch (OperationResultCode code) + // { + // case opINNER: + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountResult createAccountResult; + // case PAYMENT: + // PaymentResult paymentResult; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult; + // case MANAGE_SELL_OFFER: + // ManageSellOfferResult manageSellOfferResult; + // case CREATE_PASSIVE_SELL_OFFER: + // ManageSellOfferResult createPassiveSellOfferResult; + // case SET_OPTIONS: + // SetOptionsResult setOptionsResult; + // case CHANGE_TRUST: + // ChangeTrustResult changeTrustResult; + // case ALLOW_TRUST: + // AllowTrustResult allowTrustResult; + // case ACCOUNT_MERGE: + // AccountMergeResult accountMergeResult; + // case INFLATION: + // InflationResult inflationResult; + // case MANAGE_DATA: + // ManageDataResult manageDataResult; + // case BUMP_SEQUENCE: + // BumpSequenceResult bumpSeqResult; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferResult manageBuyOfferResult; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendResult pathPaymentStrictSendResult; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceResult createClaimableBalanceResult; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceResult claimClaimableBalanceResult; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult; + // case END_SPONSORING_FUTURE_RESERVES: + // EndSponsoringFutureReservesResult endSponsoringFutureReservesResult; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipResult revokeSponsorshipResult; + // case CLAWBACK: + // ClawbackResult clawbackResult; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceResult clawbackClaimableBalanceResult; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsResult setTrustLineFlagsResult; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositResult liquidityPoolDepositResult; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawResult liquidityPoolWithdrawResult; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionResult invokeHostFunctionResult; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLResult extendFootprintTTLResult; + // case RESTORE_FOOTPRINT: + // RestoreFootprintResult restoreFootprintResult; + // } + // tr; + // case opBAD_AUTH: + // case opNO_ACCOUNT: + // case opNOT_SUPPORTED: + // case opTOO_MANY_SUBENTRIES: + // case opEXCEEDED_WORK_LIMIT: + // case opTOO_MANY_SPONSORING: + // void; + // }; + // + // =========================================================================== + xdr.union("OperationResult", { + switchOn: xdr.lookup("OperationResultCode"), + switchName: "code", + switches: [["opInner", "tr"], ["opBadAuth", xdr["void"]()], ["opNoAccount", xdr["void"]()], ["opNotSupported", xdr["void"]()], ["opTooManySubentries", xdr["void"]()], ["opExceededWorkLimit", xdr["void"]()], ["opTooManySponsoring", xdr["void"]()]], + arms: { + tr: xdr.lookup("OperationResultTr") + } + }); + + // === xdr source ============================================================ + // + // enum TransactionResultCode + // { + // txFEE_BUMP_INNER_SUCCESS = 1, // fee bump inner transaction succeeded + // txSUCCESS = 0, // all operations succeeded + // + // txFAILED = -1, // one of the operations failed (none were applied) + // + // txTOO_EARLY = -2, // ledger closeTime before minTime + // txTOO_LATE = -3, // ledger closeTime after maxTime + // txMISSING_OPERATION = -4, // no operation was specified + // txBAD_SEQ = -5, // sequence number does not match source account + // + // txBAD_AUTH = -6, // too few valid signatures / wrong network + // txINSUFFICIENT_BALANCE = -7, // fee would bring account below reserve + // txNO_ACCOUNT = -8, // source account not found + // txINSUFFICIENT_FEE = -9, // fee is too small + // txBAD_AUTH_EXTRA = -10, // unused signatures attached to transaction + // txINTERNAL_ERROR = -11, // an unknown error occurred + // + // txNOT_SUPPORTED = -12, // transaction type not supported + // txFEE_BUMP_INNER_FAILED = -13, // fee bump inner transaction failed + // txBAD_SPONSORSHIP = -14, // sponsorship not confirmed + // txBAD_MIN_SEQ_AGE_OR_GAP = -15, // minSeqAge or minSeqLedgerGap conditions not met + // txMALFORMED = -16, // precondition is invalid + // txSOROBAN_INVALID = -17 // soroban-specific preconditions were not met + // }; + // + // =========================================================================== + xdr["enum"]("TransactionResultCode", { + txFeeBumpInnerSuccess: 1, + txSuccess: 0, + txFailed: -1, + txTooEarly: -2, + txTooLate: -3, + txMissingOperation: -4, + txBadSeq: -5, + txBadAuth: -6, + txInsufficientBalance: -7, + txNoAccount: -8, + txInsufficientFee: -9, + txBadAuthExtra: -10, + txInternalError: -11, + txNotSupported: -12, + txFeeBumpInnerFailed: -13, + txBadSponsorship: -14, + txBadMinSeqAgeOrGap: -15, + txMalformed: -16, + txSorobanInvalid: -17 + }); + + // === xdr source ============================================================ + // + // union switch (TransactionResultCode code) + // { + // // txFEE_BUMP_INNER_SUCCESS is not included + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // txFEE_BUMP_INNER_FAILED is not included + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // + // =========================================================================== + xdr.union("InnerTransactionResultResult", { + switchOn: xdr.lookup("TransactionResultCode"), + switchName: "code", + switches: [["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr["void"]()], ["txTooLate", xdr["void"]()], ["txMissingOperation", xdr["void"]()], ["txBadSeq", xdr["void"]()], ["txBadAuth", xdr["void"]()], ["txInsufficientBalance", xdr["void"]()], ["txNoAccount", xdr["void"]()], ["txInsufficientFee", xdr["void"]()], ["txBadAuthExtra", xdr["void"]()], ["txInternalError", xdr["void"]()], ["txNotSupported", xdr["void"]()], ["txBadSponsorship", xdr["void"]()], ["txBadMinSeqAgeOrGap", xdr["void"]()], ["txMalformed", xdr["void"]()], ["txSorobanInvalid", xdr["void"]()]], + arms: { + results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("InnerTransactionResultExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct InnerTransactionResult + // { + // // Always 0. Here for binary compatibility. + // int64 feeCharged; + // + // union switch (TransactionResultCode code) + // { + // // txFEE_BUMP_INNER_SUCCESS is not included + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // txFEE_BUMP_INNER_FAILED is not included + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // result; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("InnerTransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("InnerTransactionResultResult")], ["ext", xdr.lookup("InnerTransactionResultExt")]]); + + // === xdr source ============================================================ + // + // struct InnerTransactionResultPair + // { + // Hash transactionHash; // hash of the inner transaction + // InnerTransactionResult result; // result for the inner transaction + // }; + // + // =========================================================================== + xdr.struct("InnerTransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("InnerTransactionResult")]]); + + // === xdr source ============================================================ + // + // union switch (TransactionResultCode code) + // { + // case txFEE_BUMP_INNER_SUCCESS: + // case txFEE_BUMP_INNER_FAILED: + // InnerTransactionResultPair innerResultPair; + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // case txFEE_BUMP_INNER_FAILED: handled above + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionResultResult", { + switchOn: xdr.lookup("TransactionResultCode"), + switchName: "code", + switches: [["txFeeBumpInnerSuccess", "innerResultPair"], ["txFeeBumpInnerFailed", "innerResultPair"], ["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr["void"]()], ["txTooLate", xdr["void"]()], ["txMissingOperation", xdr["void"]()], ["txBadSeq", xdr["void"]()], ["txBadAuth", xdr["void"]()], ["txInsufficientBalance", xdr["void"]()], ["txNoAccount", xdr["void"]()], ["txInsufficientFee", xdr["void"]()], ["txBadAuthExtra", xdr["void"]()], ["txInternalError", xdr["void"]()], ["txNotSupported", xdr["void"]()], ["txBadSponsorship", xdr["void"]()], ["txBadMinSeqAgeOrGap", xdr["void"]()], ["txMalformed", xdr["void"]()], ["txSorobanInvalid", xdr["void"]()]], + arms: { + innerResultPair: xdr.lookup("InnerTransactionResultPair"), + results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionResultExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionResult + // { + // int64 feeCharged; // actual fee charged for the transaction + // + // union switch (TransactionResultCode code) + // { + // case txFEE_BUMP_INNER_SUCCESS: + // case txFEE_BUMP_INNER_FAILED: + // InnerTransactionResultPair innerResultPair; + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // case txFEE_BUMP_INNER_FAILED: handled above + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // result; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("TransactionResultResult")], ["ext", xdr.lookup("TransactionResultExt")]]); + + // === xdr source ============================================================ + // + // typedef opaque Hash[32]; + // + // =========================================================================== + xdr.typedef("Hash", xdr.opaque(32)); + + // === xdr source ============================================================ + // + // typedef opaque uint256[32]; + // + // =========================================================================== + xdr.typedef("Uint256", xdr.opaque(32)); + + // === xdr source ============================================================ + // + // typedef unsigned int uint32; + // + // =========================================================================== + xdr.typedef("Uint32", xdr.uint()); + + // === xdr source ============================================================ + // + // typedef int int32; + // + // =========================================================================== + xdr.typedef("Int32", xdr["int"]()); + + // === xdr source ============================================================ + // + // typedef unsigned hyper uint64; + // + // =========================================================================== + xdr.typedef("Uint64", xdr.uhyper()); + + // === xdr source ============================================================ + // + // typedef hyper int64; + // + // =========================================================================== + xdr.typedef("Int64", xdr.hyper()); + + // === xdr source ============================================================ + // + // typedef uint64 TimePoint; + // + // =========================================================================== + xdr.typedef("TimePoint", xdr.lookup("Uint64")); + + // === xdr source ============================================================ + // + // typedef uint64 Duration; + // + // =========================================================================== + xdr.typedef("Duration", xdr.lookup("Uint64")); + + // === xdr source ============================================================ + // + // union ExtensionPoint switch (int v) + // { + // case 0: + // void; + // }; + // + // =========================================================================== + xdr.union("ExtensionPoint", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum CryptoKeyType + // { + // KEY_TYPE_ED25519 = 0, + // KEY_TYPE_PRE_AUTH_TX = 1, + // KEY_TYPE_HASH_X = 2, + // KEY_TYPE_ED25519_SIGNED_PAYLOAD = 3, + // // MUXED enum values for supported type are derived from the enum values + // // above by ORing them with 0x100 + // KEY_TYPE_MUXED_ED25519 = 0x100 + // }; + // + // =========================================================================== + xdr["enum"]("CryptoKeyType", { + keyTypeEd25519: 0, + keyTypePreAuthTx: 1, + keyTypeHashX: 2, + keyTypeEd25519SignedPayload: 3, + keyTypeMuxedEd25519: 256 + }); + + // === xdr source ============================================================ + // + // enum PublicKeyType + // { + // PUBLIC_KEY_TYPE_ED25519 = KEY_TYPE_ED25519 + // }; + // + // =========================================================================== + xdr["enum"]("PublicKeyType", { + publicKeyTypeEd25519: 0 + }); + + // === xdr source ============================================================ + // + // enum SignerKeyType + // { + // SIGNER_KEY_TYPE_ED25519 = KEY_TYPE_ED25519, + // SIGNER_KEY_TYPE_PRE_AUTH_TX = KEY_TYPE_PRE_AUTH_TX, + // SIGNER_KEY_TYPE_HASH_X = KEY_TYPE_HASH_X, + // SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD = KEY_TYPE_ED25519_SIGNED_PAYLOAD + // }; + // + // =========================================================================== + xdr["enum"]("SignerKeyType", { + signerKeyTypeEd25519: 0, + signerKeyTypePreAuthTx: 1, + signerKeyTypeHashX: 2, + signerKeyTypeEd25519SignedPayload: 3 + }); + + // === xdr source ============================================================ + // + // union PublicKey switch (PublicKeyType type) + // { + // case PUBLIC_KEY_TYPE_ED25519: + // uint256 ed25519; + // }; + // + // =========================================================================== + xdr.union("PublicKey", { + switchOn: xdr.lookup("PublicKeyType"), + switchName: "type", + switches: [["publicKeyTypeEd25519", "ed25519"]], + arms: { + ed25519: xdr.lookup("Uint256") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // /* Public key that must sign the payload. */ + // uint256 ed25519; + // /* Payload to be raw signed by ed25519. */ + // opaque payload<64>; + // } + // + // =========================================================================== + xdr.struct("SignerKeyEd25519SignedPayload", [["ed25519", xdr.lookup("Uint256")], ["payload", xdr.varOpaque(64)]]); + + // === xdr source ============================================================ + // + // union SignerKey switch (SignerKeyType type) + // { + // case SIGNER_KEY_TYPE_ED25519: + // uint256 ed25519; + // case SIGNER_KEY_TYPE_PRE_AUTH_TX: + // /* SHA-256 Hash of TransactionSignaturePayload structure */ + // uint256 preAuthTx; + // case SIGNER_KEY_TYPE_HASH_X: + // /* Hash of random 256 bit preimage X */ + // uint256 hashX; + // case SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD: + // struct + // { + // /* Public key that must sign the payload. */ + // uint256 ed25519; + // /* Payload to be raw signed by ed25519. */ + // opaque payload<64>; + // } ed25519SignedPayload; + // }; + // + // =========================================================================== + xdr.union("SignerKey", { + switchOn: xdr.lookup("SignerKeyType"), + switchName: "type", + switches: [["signerKeyTypeEd25519", "ed25519"], ["signerKeyTypePreAuthTx", "preAuthTx"], ["signerKeyTypeHashX", "hashX"], ["signerKeyTypeEd25519SignedPayload", "ed25519SignedPayload"]], + arms: { + ed25519: xdr.lookup("Uint256"), + preAuthTx: xdr.lookup("Uint256"), + hashX: xdr.lookup("Uint256"), + ed25519SignedPayload: xdr.lookup("SignerKeyEd25519SignedPayload") + } + }); + + // === xdr source ============================================================ + // + // typedef opaque Signature<64>; + // + // =========================================================================== + xdr.typedef("Signature", xdr.varOpaque(64)); + + // === xdr source ============================================================ + // + // typedef opaque SignatureHint[4]; + // + // =========================================================================== + xdr.typedef("SignatureHint", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef PublicKey NodeID; + // + // =========================================================================== + xdr.typedef("NodeId", xdr.lookup("PublicKey")); + + // === xdr source ============================================================ + // + // typedef PublicKey AccountID; + // + // =========================================================================== + xdr.typedef("AccountId", xdr.lookup("PublicKey")); + + // === xdr source ============================================================ + // + // struct Curve25519Secret + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("Curve25519Secret", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct Curve25519Public + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("Curve25519Public", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct HmacSha256Key + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("HmacSha256Key", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct HmacSha256Mac + // { + // opaque mac[32]; + // }; + // + // =========================================================================== + xdr.struct("HmacSha256Mac", [["mac", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct ShortHashSeed + // { + // opaque seed[16]; + // }; + // + // =========================================================================== + xdr.struct("ShortHashSeed", [["seed", xdr.opaque(16)]]); + + // === xdr source ============================================================ + // + // enum BinaryFuseFilterType + // { + // BINARY_FUSE_FILTER_8_BIT = 0, + // BINARY_FUSE_FILTER_16_BIT = 1, + // BINARY_FUSE_FILTER_32_BIT = 2 + // }; + // + // =========================================================================== + xdr["enum"]("BinaryFuseFilterType", { + binaryFuseFilter8Bit: 0, + binaryFuseFilter16Bit: 1, + binaryFuseFilter32Bit: 2 + }); + + // === xdr source ============================================================ + // + // struct SerializedBinaryFuseFilter + // { + // BinaryFuseFilterType type; + // + // // Seed used to hash input to filter + // ShortHashSeed inputHashSeed; + // + // // Seed used for internal filter hash operations + // ShortHashSeed filterSeed; + // uint32 segmentLength; + // uint32 segementLengthMask; + // uint32 segmentCount; + // uint32 segmentCountLength; + // uint32 fingerprintLength; // Length in terms of element count, not bytes + // + // // Array of uint8_t, uint16_t, or uint32_t depending on filter type + // opaque fingerprints<>; + // }; + // + // =========================================================================== + xdr.struct("SerializedBinaryFuseFilter", [["type", xdr.lookup("BinaryFuseFilterType")], ["inputHashSeed", xdr.lookup("ShortHashSeed")], ["filterSeed", xdr.lookup("ShortHashSeed")], ["segmentLength", xdr.lookup("Uint32")], ["segementLengthMask", xdr.lookup("Uint32")], ["segmentCount", xdr.lookup("Uint32")], ["segmentCountLength", xdr.lookup("Uint32")], ["fingerprintLength", xdr.lookup("Uint32")], ["fingerprints", xdr.varOpaque()]]); + + // === xdr source ============================================================ + // + // enum SCValType + // { + // SCV_BOOL = 0, + // SCV_VOID = 1, + // SCV_ERROR = 2, + // + // // 32 bits is the smallest type in WASM or XDR; no need for u8/u16. + // SCV_U32 = 3, + // SCV_I32 = 4, + // + // // 64 bits is naturally supported by both WASM and XDR also. + // SCV_U64 = 5, + // SCV_I64 = 6, + // + // // Time-related u64 subtypes with their own functions and formatting. + // SCV_TIMEPOINT = 7, + // SCV_DURATION = 8, + // + // // 128 bits is naturally supported by Rust and we use it for Soroban + // // fixed-point arithmetic prices / balances / similar "quantities". These + // // are represented in XDR as a pair of 2 u64s. + // SCV_U128 = 9, + // SCV_I128 = 10, + // + // // 256 bits is the size of sha256 output, ed25519 keys, and the EVM machine + // // word, so for interop use we include this even though it requires a small + // // amount of Rust guest and/or host library code. + // SCV_U256 = 11, + // SCV_I256 = 12, + // + // // Bytes come in 3 flavors, 2 of which have meaningfully different + // // formatting and validity-checking / domain-restriction. + // SCV_BYTES = 13, + // SCV_STRING = 14, + // SCV_SYMBOL = 15, + // + // // Vecs and maps are just polymorphic containers of other ScVals. + // SCV_VEC = 16, + // SCV_MAP = 17, + // + // // Address is the universal identifier for contracts and classic + // // accounts. + // SCV_ADDRESS = 18, + // + // // The following are the internal SCVal variants that are not + // // exposed to the contracts. + // SCV_CONTRACT_INSTANCE = 19, + // + // // SCV_LEDGER_KEY_CONTRACT_INSTANCE and SCV_LEDGER_KEY_NONCE are unique + // // symbolic SCVals used as the key for ledger entries for a contract's + // // instance and an address' nonce, respectively. + // SCV_LEDGER_KEY_CONTRACT_INSTANCE = 20, + // SCV_LEDGER_KEY_NONCE = 21 + // }; + // + // =========================================================================== + xdr["enum"]("ScValType", { + scvBool: 0, + scvVoid: 1, + scvError: 2, + scvU32: 3, + scvI32: 4, + scvU64: 5, + scvI64: 6, + scvTimepoint: 7, + scvDuration: 8, + scvU128: 9, + scvI128: 10, + scvU256: 11, + scvI256: 12, + scvBytes: 13, + scvString: 14, + scvSymbol: 15, + scvVec: 16, + scvMap: 17, + scvAddress: 18, + scvContractInstance: 19, + scvLedgerKeyContractInstance: 20, + scvLedgerKeyNonce: 21 + }); + + // === xdr source ============================================================ + // + // enum SCErrorType + // { + // SCE_CONTRACT = 0, // Contract-specific, user-defined codes. + // SCE_WASM_VM = 1, // Errors while interpreting WASM bytecode. + // SCE_CONTEXT = 2, // Errors in the contract's host context. + // SCE_STORAGE = 3, // Errors accessing host storage. + // SCE_OBJECT = 4, // Errors working with host objects. + // SCE_CRYPTO = 5, // Errors in cryptographic operations. + // SCE_EVENTS = 6, // Errors while emitting events. + // SCE_BUDGET = 7, // Errors relating to budget limits. + // SCE_VALUE = 8, // Errors working with host values or SCVals. + // SCE_AUTH = 9 // Errors from the authentication subsystem. + // }; + // + // =========================================================================== + xdr["enum"]("ScErrorType", { + sceContract: 0, + sceWasmVm: 1, + sceContext: 2, + sceStorage: 3, + sceObject: 4, + sceCrypto: 5, + sceEvents: 6, + sceBudget: 7, + sceValue: 8, + sceAuth: 9 + }); + + // === xdr source ============================================================ + // + // enum SCErrorCode + // { + // SCEC_ARITH_DOMAIN = 0, // Some arithmetic was undefined (overflow, divide-by-zero). + // SCEC_INDEX_BOUNDS = 1, // Something was indexed beyond its bounds. + // SCEC_INVALID_INPUT = 2, // User provided some otherwise-bad data. + // SCEC_MISSING_VALUE = 3, // Some value was required but not provided. + // SCEC_EXISTING_VALUE = 4, // Some value was provided where not allowed. + // SCEC_EXCEEDED_LIMIT = 5, // Some arbitrary limit -- gas or otherwise -- was hit. + // SCEC_INVALID_ACTION = 6, // Data was valid but action requested was not. + // SCEC_INTERNAL_ERROR = 7, // The host detected an error in its own logic. + // SCEC_UNEXPECTED_TYPE = 8, // Some type wasn't as expected. + // SCEC_UNEXPECTED_SIZE = 9 // Something's size wasn't as expected. + // }; + // + // =========================================================================== + xdr["enum"]("ScErrorCode", { + scecArithDomain: 0, + scecIndexBounds: 1, + scecInvalidInput: 2, + scecMissingValue: 3, + scecExistingValue: 4, + scecExceededLimit: 5, + scecInvalidAction: 6, + scecInternalError: 7, + scecUnexpectedType: 8, + scecUnexpectedSize: 9 + }); + + // === xdr source ============================================================ + // + // union SCError switch (SCErrorType type) + // { + // case SCE_CONTRACT: + // uint32 contractCode; + // case SCE_WASM_VM: + // case SCE_CONTEXT: + // case SCE_STORAGE: + // case SCE_OBJECT: + // case SCE_CRYPTO: + // case SCE_EVENTS: + // case SCE_BUDGET: + // case SCE_VALUE: + // case SCE_AUTH: + // SCErrorCode code; + // }; + // + // =========================================================================== + xdr.union("ScError", { + switchOn: xdr.lookup("ScErrorType"), + switchName: "type", + switches: [["sceContract", "contractCode"], ["sceWasmVm", "code"], ["sceContext", "code"], ["sceStorage", "code"], ["sceObject", "code"], ["sceCrypto", "code"], ["sceEvents", "code"], ["sceBudget", "code"], ["sceValue", "code"], ["sceAuth", "code"]], + arms: { + contractCode: xdr.lookup("Uint32"), + code: xdr.lookup("ScErrorCode") + } + }); + + // === xdr source ============================================================ + // + // struct UInt128Parts { + // uint64 hi; + // uint64 lo; + // }; + // + // =========================================================================== + xdr.struct("UInt128Parts", [["hi", xdr.lookup("Uint64")], ["lo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct Int128Parts { + // int64 hi; + // uint64 lo; + // }; + // + // =========================================================================== + xdr.struct("Int128Parts", [["hi", xdr.lookup("Int64")], ["lo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct UInt256Parts { + // uint64 hi_hi; + // uint64 hi_lo; + // uint64 lo_hi; + // uint64 lo_lo; + // }; + // + // =========================================================================== + xdr.struct("UInt256Parts", [["hiHi", xdr.lookup("Uint64")], ["hiLo", xdr.lookup("Uint64")], ["loHi", xdr.lookup("Uint64")], ["loLo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct Int256Parts { + // int64 hi_hi; + // uint64 hi_lo; + // uint64 lo_hi; + // uint64 lo_lo; + // }; + // + // =========================================================================== + xdr.struct("Int256Parts", [["hiHi", xdr.lookup("Int64")], ["hiLo", xdr.lookup("Uint64")], ["loHi", xdr.lookup("Uint64")], ["loLo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // enum ContractExecutableType + // { + // CONTRACT_EXECUTABLE_WASM = 0, + // CONTRACT_EXECUTABLE_STELLAR_ASSET = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractExecutableType", { + contractExecutableWasm: 0, + contractExecutableStellarAsset: 1 + }); + + // === xdr source ============================================================ + // + // union ContractExecutable switch (ContractExecutableType type) + // { + // case CONTRACT_EXECUTABLE_WASM: + // Hash wasm_hash; + // case CONTRACT_EXECUTABLE_STELLAR_ASSET: + // void; + // }; + // + // =========================================================================== + xdr.union("ContractExecutable", { + switchOn: xdr.lookup("ContractExecutableType"), + switchName: "type", + switches: [["contractExecutableWasm", "wasmHash"], ["contractExecutableStellarAsset", xdr["void"]()]], + arms: { + wasmHash: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum SCAddressType + // { + // SC_ADDRESS_TYPE_ACCOUNT = 0, + // SC_ADDRESS_TYPE_CONTRACT = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ScAddressType", { + scAddressTypeAccount: 0, + scAddressTypeContract: 1 + }); + + // === xdr source ============================================================ + // + // union SCAddress switch (SCAddressType type) + // { + // case SC_ADDRESS_TYPE_ACCOUNT: + // AccountID accountId; + // case SC_ADDRESS_TYPE_CONTRACT: + // Hash contractId; + // }; + // + // =========================================================================== + xdr.union("ScAddress", { + switchOn: xdr.lookup("ScAddressType"), + switchName: "type", + switches: [["scAddressTypeAccount", "accountId"], ["scAddressTypeContract", "contractId"]], + arms: { + accountId: xdr.lookup("AccountId"), + contractId: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // const SCSYMBOL_LIMIT = 32; + // + // =========================================================================== + xdr["const"]("SCSYMBOL_LIMIT", 32); + + // === xdr source ============================================================ + // + // typedef SCVal SCVec<>; + // + // =========================================================================== + xdr.typedef("ScVec", xdr.varArray(xdr.lookup("ScVal"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef SCMapEntry SCMap<>; + // + // =========================================================================== + xdr.typedef("ScMap", xdr.varArray(xdr.lookup("ScMapEntry"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef opaque SCBytes<>; + // + // =========================================================================== + xdr.typedef("ScBytes", xdr.varOpaque()); + + // === xdr source ============================================================ + // + // typedef string SCString<>; + // + // =========================================================================== + xdr.typedef("ScString", xdr.string()); + + // === xdr source ============================================================ + // + // typedef string SCSymbol; + // + // =========================================================================== + xdr.typedef("ScSymbol", xdr.string(SCSYMBOL_LIMIT)); + + // === xdr source ============================================================ + // + // struct SCNonceKey { + // int64 nonce; + // }; + // + // =========================================================================== + xdr.struct("ScNonceKey", [["nonce", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct SCContractInstance { + // ContractExecutable executable; + // SCMap* storage; + // }; + // + // =========================================================================== + xdr.struct("ScContractInstance", [["executable", xdr.lookup("ContractExecutable")], ["storage", xdr.option(xdr.lookup("ScMap"))]]); + + // === xdr source ============================================================ + // + // union SCVal switch (SCValType type) + // { + // + // case SCV_BOOL: + // bool b; + // case SCV_VOID: + // void; + // case SCV_ERROR: + // SCError error; + // + // case SCV_U32: + // uint32 u32; + // case SCV_I32: + // int32 i32; + // + // case SCV_U64: + // uint64 u64; + // case SCV_I64: + // int64 i64; + // case SCV_TIMEPOINT: + // TimePoint timepoint; + // case SCV_DURATION: + // Duration duration; + // + // case SCV_U128: + // UInt128Parts u128; + // case SCV_I128: + // Int128Parts i128; + // + // case SCV_U256: + // UInt256Parts u256; + // case SCV_I256: + // Int256Parts i256; + // + // case SCV_BYTES: + // SCBytes bytes; + // case SCV_STRING: + // SCString str; + // case SCV_SYMBOL: + // SCSymbol sym; + // + // // Vec and Map are recursive so need to live + // // behind an option, due to xdrpp limitations. + // case SCV_VEC: + // SCVec *vec; + // case SCV_MAP: + // SCMap *map; + // + // case SCV_ADDRESS: + // SCAddress address; + // + // // Special SCVals reserved for system-constructed contract-data + // // ledger keys, not generally usable elsewhere. + // case SCV_LEDGER_KEY_CONTRACT_INSTANCE: + // void; + // case SCV_LEDGER_KEY_NONCE: + // SCNonceKey nonce_key; + // + // case SCV_CONTRACT_INSTANCE: + // SCContractInstance instance; + // }; + // + // =========================================================================== + xdr.union("ScVal", { + switchOn: xdr.lookup("ScValType"), + switchName: "type", + switches: [["scvBool", "b"], ["scvVoid", xdr["void"]()], ["scvError", "error"], ["scvU32", "u32"], ["scvI32", "i32"], ["scvU64", "u64"], ["scvI64", "i64"], ["scvTimepoint", "timepoint"], ["scvDuration", "duration"], ["scvU128", "u128"], ["scvI128", "i128"], ["scvU256", "u256"], ["scvI256", "i256"], ["scvBytes", "bytes"], ["scvString", "str"], ["scvSymbol", "sym"], ["scvVec", "vec"], ["scvMap", "map"], ["scvAddress", "address"], ["scvLedgerKeyContractInstance", xdr["void"]()], ["scvLedgerKeyNonce", "nonceKey"], ["scvContractInstance", "instance"]], + arms: { + b: xdr.bool(), + error: xdr.lookup("ScError"), + u32: xdr.lookup("Uint32"), + i32: xdr.lookup("Int32"), + u64: xdr.lookup("Uint64"), + i64: xdr.lookup("Int64"), + timepoint: xdr.lookup("TimePoint"), + duration: xdr.lookup("Duration"), + u128: xdr.lookup("UInt128Parts"), + i128: xdr.lookup("Int128Parts"), + u256: xdr.lookup("UInt256Parts"), + i256: xdr.lookup("Int256Parts"), + bytes: xdr.lookup("ScBytes"), + str: xdr.lookup("ScString"), + sym: xdr.lookup("ScSymbol"), + vec: xdr.option(xdr.lookup("ScVec")), + map: xdr.option(xdr.lookup("ScMap")), + address: xdr.lookup("ScAddress"), + nonceKey: xdr.lookup("ScNonceKey"), + instance: xdr.lookup("ScContractInstance") + } + }); + + // === xdr source ============================================================ + // + // struct SCMapEntry + // { + // SCVal key; + // SCVal val; + // }; + // + // =========================================================================== + xdr.struct("ScMapEntry", [["key", xdr.lookup("ScVal")], ["val", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // enum SCEnvMetaKind + // { + // SC_ENV_META_KIND_INTERFACE_VERSION = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ScEnvMetaKind", { + scEnvMetaKindInterfaceVersion: 0 + }); + + // === xdr source ============================================================ + // + // struct { + // uint32 protocol; + // uint32 preRelease; + // } + // + // =========================================================================== + xdr.struct("ScEnvMetaEntryInterfaceVersion", [["protocol", xdr.lookup("Uint32")], ["preRelease", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union SCEnvMetaEntry switch (SCEnvMetaKind kind) + // { + // case SC_ENV_META_KIND_INTERFACE_VERSION: + // struct { + // uint32 protocol; + // uint32 preRelease; + // } interfaceVersion; + // }; + // + // =========================================================================== + xdr.union("ScEnvMetaEntry", { + switchOn: xdr.lookup("ScEnvMetaKind"), + switchName: "kind", + switches: [["scEnvMetaKindInterfaceVersion", "interfaceVersion"]], + arms: { + interfaceVersion: xdr.lookup("ScEnvMetaEntryInterfaceVersion") + } + }); + + // === xdr source ============================================================ + // + // struct SCMetaV0 + // { + // string key<>; + // string val<>; + // }; + // + // =========================================================================== + xdr.struct("ScMetaV0", [["key", xdr.string()], ["val", xdr.string()]]); + + // === xdr source ============================================================ + // + // enum SCMetaKind + // { + // SC_META_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ScMetaKind", { + scMetaV0: 0 + }); + + // === xdr source ============================================================ + // + // union SCMetaEntry switch (SCMetaKind kind) + // { + // case SC_META_V0: + // SCMetaV0 v0; + // }; + // + // =========================================================================== + xdr.union("ScMetaEntry", { + switchOn: xdr.lookup("ScMetaKind"), + switchName: "kind", + switches: [["scMetaV0", "v0"]], + arms: { + v0: xdr.lookup("ScMetaV0") + } + }); + + // === xdr source ============================================================ + // + // const SC_SPEC_DOC_LIMIT = 1024; + // + // =========================================================================== + xdr["const"]("SC_SPEC_DOC_LIMIT", 1024); + + // === xdr source ============================================================ + // + // enum SCSpecType + // { + // SC_SPEC_TYPE_VAL = 0, + // + // // Types with no parameters. + // SC_SPEC_TYPE_BOOL = 1, + // SC_SPEC_TYPE_VOID = 2, + // SC_SPEC_TYPE_ERROR = 3, + // SC_SPEC_TYPE_U32 = 4, + // SC_SPEC_TYPE_I32 = 5, + // SC_SPEC_TYPE_U64 = 6, + // SC_SPEC_TYPE_I64 = 7, + // SC_SPEC_TYPE_TIMEPOINT = 8, + // SC_SPEC_TYPE_DURATION = 9, + // SC_SPEC_TYPE_U128 = 10, + // SC_SPEC_TYPE_I128 = 11, + // SC_SPEC_TYPE_U256 = 12, + // SC_SPEC_TYPE_I256 = 13, + // SC_SPEC_TYPE_BYTES = 14, + // SC_SPEC_TYPE_STRING = 16, + // SC_SPEC_TYPE_SYMBOL = 17, + // SC_SPEC_TYPE_ADDRESS = 19, + // + // // Types with parameters. + // SC_SPEC_TYPE_OPTION = 1000, + // SC_SPEC_TYPE_RESULT = 1001, + // SC_SPEC_TYPE_VEC = 1002, + // SC_SPEC_TYPE_MAP = 1004, + // SC_SPEC_TYPE_TUPLE = 1005, + // SC_SPEC_TYPE_BYTES_N = 1006, + // + // // User defined types. + // SC_SPEC_TYPE_UDT = 2000 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecType", { + scSpecTypeVal: 0, + scSpecTypeBool: 1, + scSpecTypeVoid: 2, + scSpecTypeError: 3, + scSpecTypeU32: 4, + scSpecTypeI32: 5, + scSpecTypeU64: 6, + scSpecTypeI64: 7, + scSpecTypeTimepoint: 8, + scSpecTypeDuration: 9, + scSpecTypeU128: 10, + scSpecTypeI128: 11, + scSpecTypeU256: 12, + scSpecTypeI256: 13, + scSpecTypeBytes: 14, + scSpecTypeString: 16, + scSpecTypeSymbol: 17, + scSpecTypeAddress: 19, + scSpecTypeOption: 1000, + scSpecTypeResult: 1001, + scSpecTypeVec: 1002, + scSpecTypeMap: 1004, + scSpecTypeTuple: 1005, + scSpecTypeBytesN: 1006, + scSpecTypeUdt: 2000 + }); + + // === xdr source ============================================================ + // + // struct SCSpecTypeOption + // { + // SCSpecTypeDef valueType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeOption", [["valueType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeResult + // { + // SCSpecTypeDef okType; + // SCSpecTypeDef errorType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeResult", [["okType", xdr.lookup("ScSpecTypeDef")], ["errorType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeVec + // { + // SCSpecTypeDef elementType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeVec", [["elementType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeMap + // { + // SCSpecTypeDef keyType; + // SCSpecTypeDef valueType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeMap", [["keyType", xdr.lookup("ScSpecTypeDef")], ["valueType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeTuple + // { + // SCSpecTypeDef valueTypes<12>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeTuple", [["valueTypes", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 12)]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeBytesN + // { + // uint32 n; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeBytesN", [["n", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeUDT + // { + // string name<60>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeUdt", [["name", xdr.string(60)]]); + + // === xdr source ============================================================ + // + // union SCSpecTypeDef switch (SCSpecType type) + // { + // case SC_SPEC_TYPE_VAL: + // case SC_SPEC_TYPE_BOOL: + // case SC_SPEC_TYPE_VOID: + // case SC_SPEC_TYPE_ERROR: + // case SC_SPEC_TYPE_U32: + // case SC_SPEC_TYPE_I32: + // case SC_SPEC_TYPE_U64: + // case SC_SPEC_TYPE_I64: + // case SC_SPEC_TYPE_TIMEPOINT: + // case SC_SPEC_TYPE_DURATION: + // case SC_SPEC_TYPE_U128: + // case SC_SPEC_TYPE_I128: + // case SC_SPEC_TYPE_U256: + // case SC_SPEC_TYPE_I256: + // case SC_SPEC_TYPE_BYTES: + // case SC_SPEC_TYPE_STRING: + // case SC_SPEC_TYPE_SYMBOL: + // case SC_SPEC_TYPE_ADDRESS: + // void; + // case SC_SPEC_TYPE_OPTION: + // SCSpecTypeOption option; + // case SC_SPEC_TYPE_RESULT: + // SCSpecTypeResult result; + // case SC_SPEC_TYPE_VEC: + // SCSpecTypeVec vec; + // case SC_SPEC_TYPE_MAP: + // SCSpecTypeMap map; + // case SC_SPEC_TYPE_TUPLE: + // SCSpecTypeTuple tuple; + // case SC_SPEC_TYPE_BYTES_N: + // SCSpecTypeBytesN bytesN; + // case SC_SPEC_TYPE_UDT: + // SCSpecTypeUDT udt; + // }; + // + // =========================================================================== + xdr.union("ScSpecTypeDef", { + switchOn: xdr.lookup("ScSpecType"), + switchName: "type", + switches: [["scSpecTypeVal", xdr["void"]()], ["scSpecTypeBool", xdr["void"]()], ["scSpecTypeVoid", xdr["void"]()], ["scSpecTypeError", xdr["void"]()], ["scSpecTypeU32", xdr["void"]()], ["scSpecTypeI32", xdr["void"]()], ["scSpecTypeU64", xdr["void"]()], ["scSpecTypeI64", xdr["void"]()], ["scSpecTypeTimepoint", xdr["void"]()], ["scSpecTypeDuration", xdr["void"]()], ["scSpecTypeU128", xdr["void"]()], ["scSpecTypeI128", xdr["void"]()], ["scSpecTypeU256", xdr["void"]()], ["scSpecTypeI256", xdr["void"]()], ["scSpecTypeBytes", xdr["void"]()], ["scSpecTypeString", xdr["void"]()], ["scSpecTypeSymbol", xdr["void"]()], ["scSpecTypeAddress", xdr["void"]()], ["scSpecTypeOption", "option"], ["scSpecTypeResult", "result"], ["scSpecTypeVec", "vec"], ["scSpecTypeMap", "map"], ["scSpecTypeTuple", "tuple"], ["scSpecTypeBytesN", "bytesN"], ["scSpecTypeUdt", "udt"]], + arms: { + option: xdr.lookup("ScSpecTypeOption"), + result: xdr.lookup("ScSpecTypeResult"), + vec: xdr.lookup("ScSpecTypeVec"), + map: xdr.lookup("ScSpecTypeMap"), + tuple: xdr.lookup("ScSpecTypeTuple"), + bytesN: xdr.lookup("ScSpecTypeBytesN"), + udt: xdr.lookup("ScSpecTypeUdt") + } + }); + + // === xdr source ============================================================ + // + // struct SCSpecUDTStructFieldV0 + // { + // string doc; + // string name<30>; + // SCSpecTypeDef type; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtStructFieldV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(30)], ["type", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTStructV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTStructFieldV0 fields<40>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtStructV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["fields", xdr.varArray(xdr.lookup("ScSpecUdtStructFieldV0"), 40)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionCaseVoidV0 + // { + // string doc; + // string name<60>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionCaseVoidV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionCaseTupleV0 + // { + // string doc; + // string name<60>; + // SCSpecTypeDef type<12>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionCaseTupleV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["type", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 12)]]); + + // === xdr source ============================================================ + // + // enum SCSpecUDTUnionCaseV0Kind + // { + // SC_SPEC_UDT_UNION_CASE_VOID_V0 = 0, + // SC_SPEC_UDT_UNION_CASE_TUPLE_V0 = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecUdtUnionCaseV0Kind", { + scSpecUdtUnionCaseVoidV0: 0, + scSpecUdtUnionCaseTupleV0: 1 + }); + + // === xdr source ============================================================ + // + // union SCSpecUDTUnionCaseV0 switch (SCSpecUDTUnionCaseV0Kind kind) + // { + // case SC_SPEC_UDT_UNION_CASE_VOID_V0: + // SCSpecUDTUnionCaseVoidV0 voidCase; + // case SC_SPEC_UDT_UNION_CASE_TUPLE_V0: + // SCSpecUDTUnionCaseTupleV0 tupleCase; + // }; + // + // =========================================================================== + xdr.union("ScSpecUdtUnionCaseV0", { + switchOn: xdr.lookup("ScSpecUdtUnionCaseV0Kind"), + switchName: "kind", + switches: [["scSpecUdtUnionCaseVoidV0", "voidCase"], ["scSpecUdtUnionCaseTupleV0", "tupleCase"]], + arms: { + voidCase: xdr.lookup("ScSpecUdtUnionCaseVoidV0"), + tupleCase: xdr.lookup("ScSpecUdtUnionCaseTupleV0") + } + }); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTUnionCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtUnionCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTEnumCaseV0 + // { + // string doc; + // string name<60>; + // uint32 value; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtEnumCaseV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["value", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTEnumV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTEnumCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtEnumV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtEnumCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTErrorEnumCaseV0 + // { + // string doc; + // string name<60>; + // uint32 value; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtErrorEnumCaseV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["value", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTErrorEnumV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTErrorEnumCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtErrorEnumV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtErrorEnumCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecFunctionInputV0 + // { + // string doc; + // string name<30>; + // SCSpecTypeDef type; + // }; + // + // =========================================================================== + xdr.struct("ScSpecFunctionInputV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(30)], ["type", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecFunctionV0 + // { + // string doc; + // SCSymbol name; + // SCSpecFunctionInputV0 inputs<10>; + // SCSpecTypeDef outputs<1>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecFunctionV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.lookup("ScSymbol")], ["inputs", xdr.varArray(xdr.lookup("ScSpecFunctionInputV0"), 10)], ["outputs", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 1)]]); + + // === xdr source ============================================================ + // + // enum SCSpecEntryKind + // { + // SC_SPEC_ENTRY_FUNCTION_V0 = 0, + // SC_SPEC_ENTRY_UDT_STRUCT_V0 = 1, + // SC_SPEC_ENTRY_UDT_UNION_V0 = 2, + // SC_SPEC_ENTRY_UDT_ENUM_V0 = 3, + // SC_SPEC_ENTRY_UDT_ERROR_ENUM_V0 = 4 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecEntryKind", { + scSpecEntryFunctionV0: 0, + scSpecEntryUdtStructV0: 1, + scSpecEntryUdtUnionV0: 2, + scSpecEntryUdtEnumV0: 3, + scSpecEntryUdtErrorEnumV0: 4 + }); + + // === xdr source ============================================================ + // + // union SCSpecEntry switch (SCSpecEntryKind kind) + // { + // case SC_SPEC_ENTRY_FUNCTION_V0: + // SCSpecFunctionV0 functionV0; + // case SC_SPEC_ENTRY_UDT_STRUCT_V0: + // SCSpecUDTStructV0 udtStructV0; + // case SC_SPEC_ENTRY_UDT_UNION_V0: + // SCSpecUDTUnionV0 udtUnionV0; + // case SC_SPEC_ENTRY_UDT_ENUM_V0: + // SCSpecUDTEnumV0 udtEnumV0; + // case SC_SPEC_ENTRY_UDT_ERROR_ENUM_V0: + // SCSpecUDTErrorEnumV0 udtErrorEnumV0; + // }; + // + // =========================================================================== + xdr.union("ScSpecEntry", { + switchOn: xdr.lookup("ScSpecEntryKind"), + switchName: "kind", + switches: [["scSpecEntryFunctionV0", "functionV0"], ["scSpecEntryUdtStructV0", "udtStructV0"], ["scSpecEntryUdtUnionV0", "udtUnionV0"], ["scSpecEntryUdtEnumV0", "udtEnumV0"], ["scSpecEntryUdtErrorEnumV0", "udtErrorEnumV0"]], + arms: { + functionV0: xdr.lookup("ScSpecFunctionV0"), + udtStructV0: xdr.lookup("ScSpecUdtStructV0"), + udtUnionV0: xdr.lookup("ScSpecUdtUnionV0"), + udtEnumV0: xdr.lookup("ScSpecUdtEnumV0"), + udtErrorEnumV0: xdr.lookup("ScSpecUdtErrorEnumV0") + } + }); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractExecutionLanesV0 + // { + // // maximum number of Soroban transactions per ledger + // uint32 ledgerMaxTxCount; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractExecutionLanesV0", [["ledgerMaxTxCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractComputeV0 + // { + // // Maximum instructions per ledger + // int64 ledgerMaxInstructions; + // // Maximum instructions per transaction + // int64 txMaxInstructions; + // // Cost of 10000 instructions + // int64 feeRatePerInstructionsIncrement; + // + // // Memory limit per transaction. Unlike instructions, there is no fee + // // for memory, just the limit. + // uint32 txMemoryLimit; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractComputeV0", [["ledgerMaxInstructions", xdr.lookup("Int64")], ["txMaxInstructions", xdr.lookup("Int64")], ["feeRatePerInstructionsIncrement", xdr.lookup("Int64")], ["txMemoryLimit", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractLedgerCostV0 + // { + // // Maximum number of ledger entry read operations per ledger + // uint32 ledgerMaxReadLedgerEntries; + // // Maximum number of bytes that can be read per ledger + // uint32 ledgerMaxReadBytes; + // // Maximum number of ledger entry write operations per ledger + // uint32 ledgerMaxWriteLedgerEntries; + // // Maximum number of bytes that can be written per ledger + // uint32 ledgerMaxWriteBytes; + // + // // Maximum number of ledger entry read operations per transaction + // uint32 txMaxReadLedgerEntries; + // // Maximum number of bytes that can be read per transaction + // uint32 txMaxReadBytes; + // // Maximum number of ledger entry write operations per transaction + // uint32 txMaxWriteLedgerEntries; + // // Maximum number of bytes that can be written per transaction + // uint32 txMaxWriteBytes; + // + // int64 feeReadLedgerEntry; // Fee per ledger entry read + // int64 feeWriteLedgerEntry; // Fee per ledger entry write + // + // int64 feeRead1KB; // Fee for reading 1KB + // + // // The following parameters determine the write fee per 1KB. + // // Write fee grows linearly until bucket list reaches this size + // int64 bucketListTargetSizeBytes; + // // Fee per 1KB write when the bucket list is empty + // int64 writeFee1KBBucketListLow; + // // Fee per 1KB write when the bucket list has reached `bucketListTargetSizeBytes` + // int64 writeFee1KBBucketListHigh; + // // Write fee multiplier for any additional data past the first `bucketListTargetSizeBytes` + // uint32 bucketListWriteFeeGrowthFactor; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractLedgerCostV0", [["ledgerMaxReadLedgerEntries", xdr.lookup("Uint32")], ["ledgerMaxReadBytes", xdr.lookup("Uint32")], ["ledgerMaxWriteLedgerEntries", xdr.lookup("Uint32")], ["ledgerMaxWriteBytes", xdr.lookup("Uint32")], ["txMaxReadLedgerEntries", xdr.lookup("Uint32")], ["txMaxReadBytes", xdr.lookup("Uint32")], ["txMaxWriteLedgerEntries", xdr.lookup("Uint32")], ["txMaxWriteBytes", xdr.lookup("Uint32")], ["feeReadLedgerEntry", xdr.lookup("Int64")], ["feeWriteLedgerEntry", xdr.lookup("Int64")], ["feeRead1Kb", xdr.lookup("Int64")], ["bucketListTargetSizeBytes", xdr.lookup("Int64")], ["writeFee1KbBucketListLow", xdr.lookup("Int64")], ["writeFee1KbBucketListHigh", xdr.lookup("Int64")], ["bucketListWriteFeeGrowthFactor", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractHistoricalDataV0 + // { + // int64 feeHistorical1KB; // Fee for storing 1KB in archives + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractHistoricalDataV0", [["feeHistorical1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractEventsV0 + // { + // // Maximum size of events that a contract call can emit. + // uint32 txMaxContractEventsSizeBytes; + // // Fee for generating 1KB of contract events. + // int64 feeContractEvents1KB; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractEventsV0", [["txMaxContractEventsSizeBytes", xdr.lookup("Uint32")], ["feeContractEvents1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractBandwidthV0 + // { + // // Maximum sum of all transaction sizes in the ledger in bytes + // uint32 ledgerMaxTxsSizeBytes; + // // Maximum size in bytes for a transaction + // uint32 txMaxSizeBytes; + // + // // Fee for 1 KB of transaction size + // int64 feeTxSize1KB; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractBandwidthV0", [["ledgerMaxTxsSizeBytes", xdr.lookup("Uint32")], ["txMaxSizeBytes", xdr.lookup("Uint32")], ["feeTxSize1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum ContractCostType { + // // Cost of running 1 wasm instruction + // WasmInsnExec = 0, + // // Cost of allocating a slice of memory (in bytes) + // MemAlloc = 1, + // // Cost of copying a slice of bytes into a pre-allocated memory + // MemCpy = 2, + // // Cost of comparing two slices of memory + // MemCmp = 3, + // // Cost of a host function dispatch, not including the actual work done by + // // the function nor the cost of VM invocation machinary + // DispatchHostFunction = 4, + // // Cost of visiting a host object from the host object storage. Exists to + // // make sure some baseline cost coverage, i.e. repeatly visiting objects + // // by the guest will always incur some charges. + // VisitObject = 5, + // // Cost of serializing an xdr object to bytes + // ValSer = 6, + // // Cost of deserializing an xdr object from bytes + // ValDeser = 7, + // // Cost of computing the sha256 hash from bytes + // ComputeSha256Hash = 8, + // // Cost of computing the ed25519 pubkey from bytes + // ComputeEd25519PubKey = 9, + // // Cost of verifying ed25519 signature of a payload. + // VerifyEd25519Sig = 10, + // // Cost of instantiation a VM from wasm bytes code. + // VmInstantiation = 11, + // // Cost of instantiation a VM from a cached state. + // VmCachedInstantiation = 12, + // // Cost of invoking a function on the VM. If the function is a host function, + // // additional cost will be covered by `DispatchHostFunction`. + // InvokeVmFunction = 13, + // // Cost of computing a keccak256 hash from bytes. + // ComputeKeccak256Hash = 14, + // // Cost of decoding an ECDSA signature computed from a 256-bit prime modulus + // // curve (e.g. secp256k1 and secp256r1) + // DecodeEcdsaCurve256Sig = 15, + // // Cost of recovering an ECDSA secp256k1 key from a signature. + // RecoverEcdsaSecp256k1Key = 16, + // // Cost of int256 addition (`+`) and subtraction (`-`) operations + // Int256AddSub = 17, + // // Cost of int256 multiplication (`*`) operation + // Int256Mul = 18, + // // Cost of int256 division (`/`) operation + // Int256Div = 19, + // // Cost of int256 power (`exp`) operation + // Int256Pow = 20, + // // Cost of int256 shift (`shl`, `shr`) operation + // Int256Shift = 21, + // // Cost of drawing random bytes using a ChaCha20 PRNG + // ChaCha20DrawBytes = 22, + // + // // Cost of parsing wasm bytes that only encode instructions. + // ParseWasmInstructions = 23, + // // Cost of parsing a known number of wasm functions. + // ParseWasmFunctions = 24, + // // Cost of parsing a known number of wasm globals. + // ParseWasmGlobals = 25, + // // Cost of parsing a known number of wasm table entries. + // ParseWasmTableEntries = 26, + // // Cost of parsing a known number of wasm types. + // ParseWasmTypes = 27, + // // Cost of parsing a known number of wasm data segments. + // ParseWasmDataSegments = 28, + // // Cost of parsing a known number of wasm element segments. + // ParseWasmElemSegments = 29, + // // Cost of parsing a known number of wasm imports. + // ParseWasmImports = 30, + // // Cost of parsing a known number of wasm exports. + // ParseWasmExports = 31, + // // Cost of parsing a known number of data segment bytes. + // ParseWasmDataSegmentBytes = 32, + // + // // Cost of instantiating wasm bytes that only encode instructions. + // InstantiateWasmInstructions = 33, + // // Cost of instantiating a known number of wasm functions. + // InstantiateWasmFunctions = 34, + // // Cost of instantiating a known number of wasm globals. + // InstantiateWasmGlobals = 35, + // // Cost of instantiating a known number of wasm table entries. + // InstantiateWasmTableEntries = 36, + // // Cost of instantiating a known number of wasm types. + // InstantiateWasmTypes = 37, + // // Cost of instantiating a known number of wasm data segments. + // InstantiateWasmDataSegments = 38, + // // Cost of instantiating a known number of wasm element segments. + // InstantiateWasmElemSegments = 39, + // // Cost of instantiating a known number of wasm imports. + // InstantiateWasmImports = 40, + // // Cost of instantiating a known number of wasm exports. + // InstantiateWasmExports = 41, + // // Cost of instantiating a known number of data segment bytes. + // InstantiateWasmDataSegmentBytes = 42, + // + // // Cost of decoding a bytes array representing an uncompressed SEC-1 encoded + // // point on a 256-bit elliptic curve + // Sec1DecodePointUncompressed = 43, + // // Cost of verifying an ECDSA Secp256r1 signature + // VerifyEcdsaSecp256r1Sig = 44, + // + // // Cost of encoding a BLS12-381 Fp (base field element) + // Bls12381EncodeFp = 45, + // // Cost of decoding a BLS12-381 Fp (base field element) + // Bls12381DecodeFp = 46, + // // Cost of checking a G1 point lies on the curve + // Bls12381G1CheckPointOnCurve = 47, + // // Cost of checking a G1 point belongs to the correct subgroup + // Bls12381G1CheckPointInSubgroup = 48, + // // Cost of checking a G2 point lies on the curve + // Bls12381G2CheckPointOnCurve = 49, + // // Cost of checking a G2 point belongs to the correct subgroup + // Bls12381G2CheckPointInSubgroup = 50, + // // Cost of converting a BLS12-381 G1 point from projective to affine coordinates + // Bls12381G1ProjectiveToAffine = 51, + // // Cost of converting a BLS12-381 G2 point from projective to affine coordinates + // Bls12381G2ProjectiveToAffine = 52, + // // Cost of performing BLS12-381 G1 point addition + // Bls12381G1Add = 53, + // // Cost of performing BLS12-381 G1 scalar multiplication + // Bls12381G1Mul = 54, + // // Cost of performing BLS12-381 G1 multi-scalar multiplication (MSM) + // Bls12381G1Msm = 55, + // // Cost of mapping a BLS12-381 Fp field element to a G1 point + // Bls12381MapFpToG1 = 56, + // // Cost of hashing to a BLS12-381 G1 point + // Bls12381HashToG1 = 57, + // // Cost of performing BLS12-381 G2 point addition + // Bls12381G2Add = 58, + // // Cost of performing BLS12-381 G2 scalar multiplication + // Bls12381G2Mul = 59, + // // Cost of performing BLS12-381 G2 multi-scalar multiplication (MSM) + // Bls12381G2Msm = 60, + // // Cost of mapping a BLS12-381 Fp2 field element to a G2 point + // Bls12381MapFp2ToG2 = 61, + // // Cost of hashing to a BLS12-381 G2 point + // Bls12381HashToG2 = 62, + // // Cost of performing BLS12-381 pairing operation + // Bls12381Pairing = 63, + // // Cost of converting a BLS12-381 scalar element from U256 + // Bls12381FrFromU256 = 64, + // // Cost of converting a BLS12-381 scalar element to U256 + // Bls12381FrToU256 = 65, + // // Cost of performing BLS12-381 scalar element addition/subtraction + // Bls12381FrAddSub = 66, + // // Cost of performing BLS12-381 scalar element multiplication + // Bls12381FrMul = 67, + // // Cost of performing BLS12-381 scalar element exponentiation + // Bls12381FrPow = 68, + // // Cost of performing BLS12-381 scalar element inversion + // Bls12381FrInv = 69 + // }; + // + // =========================================================================== + xdr["enum"]("ContractCostType", { + wasmInsnExec: 0, + memAlloc: 1, + memCpy: 2, + memCmp: 3, + dispatchHostFunction: 4, + visitObject: 5, + valSer: 6, + valDeser: 7, + computeSha256Hash: 8, + computeEd25519PubKey: 9, + verifyEd25519Sig: 10, + vmInstantiation: 11, + vmCachedInstantiation: 12, + invokeVmFunction: 13, + computeKeccak256Hash: 14, + decodeEcdsaCurve256Sig: 15, + recoverEcdsaSecp256k1Key: 16, + int256AddSub: 17, + int256Mul: 18, + int256Div: 19, + int256Pow: 20, + int256Shift: 21, + chaCha20DrawBytes: 22, + parseWasmInstructions: 23, + parseWasmFunctions: 24, + parseWasmGlobals: 25, + parseWasmTableEntries: 26, + parseWasmTypes: 27, + parseWasmDataSegments: 28, + parseWasmElemSegments: 29, + parseWasmImports: 30, + parseWasmExports: 31, + parseWasmDataSegmentBytes: 32, + instantiateWasmInstructions: 33, + instantiateWasmFunctions: 34, + instantiateWasmGlobals: 35, + instantiateWasmTableEntries: 36, + instantiateWasmTypes: 37, + instantiateWasmDataSegments: 38, + instantiateWasmElemSegments: 39, + instantiateWasmImports: 40, + instantiateWasmExports: 41, + instantiateWasmDataSegmentBytes: 42, + sec1DecodePointUncompressed: 43, + verifyEcdsaSecp256r1Sig: 44, + bls12381EncodeFp: 45, + bls12381DecodeFp: 46, + bls12381G1CheckPointOnCurve: 47, + bls12381G1CheckPointInSubgroup: 48, + bls12381G2CheckPointOnCurve: 49, + bls12381G2CheckPointInSubgroup: 50, + bls12381G1ProjectiveToAffine: 51, + bls12381G2ProjectiveToAffine: 52, + bls12381G1Add: 53, + bls12381G1Mul: 54, + bls12381G1Msm: 55, + bls12381MapFpToG1: 56, + bls12381HashToG1: 57, + bls12381G2Add: 58, + bls12381G2Mul: 59, + bls12381G2Msm: 60, + bls12381MapFp2ToG2: 61, + bls12381HashToG2: 62, + bls12381Pairing: 63, + bls12381FrFromU256: 64, + bls12381FrToU256: 65, + bls12381FrAddSub: 66, + bls12381FrMul: 67, + bls12381FrPow: 68, + bls12381FrInv: 69 + }); + + // === xdr source ============================================================ + // + // struct ContractCostParamEntry { + // // use `ext` to add more terms (e.g. higher order polynomials) in the future + // ExtensionPoint ext; + // + // int64 constTerm; + // int64 linearTerm; + // }; + // + // =========================================================================== + xdr.struct("ContractCostParamEntry", [["ext", xdr.lookup("ExtensionPoint")], ["constTerm", xdr.lookup("Int64")], ["linearTerm", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct StateArchivalSettings { + // uint32 maxEntryTTL; + // uint32 minTemporaryTTL; + // uint32 minPersistentTTL; + // + // // rent_fee = wfee_rate_average / rent_rate_denominator_for_type + // int64 persistentRentRateDenominator; + // int64 tempRentRateDenominator; + // + // // max number of entries that emit archival meta in a single ledger + // uint32 maxEntriesToArchive; + // + // // Number of snapshots to use when calculating average BucketList size + // uint32 bucketListSizeWindowSampleSize; + // + // // How often to sample the BucketList size for the average, in ledgers + // uint32 bucketListWindowSamplePeriod; + // + // // Maximum number of bytes that we scan for eviction per ledger + // uint32 evictionScanSize; + // + // // Lowest BucketList level to be scanned to evict entries + // uint32 startingEvictionScanLevel; + // }; + // + // =========================================================================== + xdr.struct("StateArchivalSettings", [["maxEntryTtl", xdr.lookup("Uint32")], ["minTemporaryTtl", xdr.lookup("Uint32")], ["minPersistentTtl", xdr.lookup("Uint32")], ["persistentRentRateDenominator", xdr.lookup("Int64")], ["tempRentRateDenominator", xdr.lookup("Int64")], ["maxEntriesToArchive", xdr.lookup("Uint32")], ["bucketListSizeWindowSampleSize", xdr.lookup("Uint32")], ["bucketListWindowSamplePeriod", xdr.lookup("Uint32")], ["evictionScanSize", xdr.lookup("Uint32")], ["startingEvictionScanLevel", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct EvictionIterator { + // uint32 bucketListLevel; + // bool isCurrBucket; + // uint64 bucketFileOffset; + // }; + // + // =========================================================================== + xdr.struct("EvictionIterator", [["bucketListLevel", xdr.lookup("Uint32")], ["isCurrBucket", xdr.bool()], ["bucketFileOffset", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // const CONTRACT_COST_COUNT_LIMIT = 1024; + // + // =========================================================================== + xdr["const"]("CONTRACT_COST_COUNT_LIMIT", 1024); + + // === xdr source ============================================================ + // + // typedef ContractCostParamEntry ContractCostParams; + // + // =========================================================================== + xdr.typedef("ContractCostParams", xdr.varArray(xdr.lookup("ContractCostParamEntry"), xdr.lookup("CONTRACT_COST_COUNT_LIMIT"))); + + // === xdr source ============================================================ + // + // enum ConfigSettingID + // { + // CONFIG_SETTING_CONTRACT_MAX_SIZE_BYTES = 0, + // CONFIG_SETTING_CONTRACT_COMPUTE_V0 = 1, + // CONFIG_SETTING_CONTRACT_LEDGER_COST_V0 = 2, + // CONFIG_SETTING_CONTRACT_HISTORICAL_DATA_V0 = 3, + // CONFIG_SETTING_CONTRACT_EVENTS_V0 = 4, + // CONFIG_SETTING_CONTRACT_BANDWIDTH_V0 = 5, + // CONFIG_SETTING_CONTRACT_COST_PARAMS_CPU_INSTRUCTIONS = 6, + // CONFIG_SETTING_CONTRACT_COST_PARAMS_MEMORY_BYTES = 7, + // CONFIG_SETTING_CONTRACT_DATA_KEY_SIZE_BYTES = 8, + // CONFIG_SETTING_CONTRACT_DATA_ENTRY_SIZE_BYTES = 9, + // CONFIG_SETTING_STATE_ARCHIVAL = 10, + // CONFIG_SETTING_CONTRACT_EXECUTION_LANES = 11, + // CONFIG_SETTING_BUCKETLIST_SIZE_WINDOW = 12, + // CONFIG_SETTING_EVICTION_ITERATOR = 13 + // }; + // + // =========================================================================== + xdr["enum"]("ConfigSettingId", { + configSettingContractMaxSizeBytes: 0, + configSettingContractComputeV0: 1, + configSettingContractLedgerCostV0: 2, + configSettingContractHistoricalDataV0: 3, + configSettingContractEventsV0: 4, + configSettingContractBandwidthV0: 5, + configSettingContractCostParamsCpuInstructions: 6, + configSettingContractCostParamsMemoryBytes: 7, + configSettingContractDataKeySizeBytes: 8, + configSettingContractDataEntrySizeBytes: 9, + configSettingStateArchival: 10, + configSettingContractExecutionLanes: 11, + configSettingBucketlistSizeWindow: 12, + configSettingEvictionIterator: 13 + }); + + // === xdr source ============================================================ + // + // union ConfigSettingEntry switch (ConfigSettingID configSettingID) + // { + // case CONFIG_SETTING_CONTRACT_MAX_SIZE_BYTES: + // uint32 contractMaxSizeBytes; + // case CONFIG_SETTING_CONTRACT_COMPUTE_V0: + // ConfigSettingContractComputeV0 contractCompute; + // case CONFIG_SETTING_CONTRACT_LEDGER_COST_V0: + // ConfigSettingContractLedgerCostV0 contractLedgerCost; + // case CONFIG_SETTING_CONTRACT_HISTORICAL_DATA_V0: + // ConfigSettingContractHistoricalDataV0 contractHistoricalData; + // case CONFIG_SETTING_CONTRACT_EVENTS_V0: + // ConfigSettingContractEventsV0 contractEvents; + // case CONFIG_SETTING_CONTRACT_BANDWIDTH_V0: + // ConfigSettingContractBandwidthV0 contractBandwidth; + // case CONFIG_SETTING_CONTRACT_COST_PARAMS_CPU_INSTRUCTIONS: + // ContractCostParams contractCostParamsCpuInsns; + // case CONFIG_SETTING_CONTRACT_COST_PARAMS_MEMORY_BYTES: + // ContractCostParams contractCostParamsMemBytes; + // case CONFIG_SETTING_CONTRACT_DATA_KEY_SIZE_BYTES: + // uint32 contractDataKeySizeBytes; + // case CONFIG_SETTING_CONTRACT_DATA_ENTRY_SIZE_BYTES: + // uint32 contractDataEntrySizeBytes; + // case CONFIG_SETTING_STATE_ARCHIVAL: + // StateArchivalSettings stateArchivalSettings; + // case CONFIG_SETTING_CONTRACT_EXECUTION_LANES: + // ConfigSettingContractExecutionLanesV0 contractExecutionLanes; + // case CONFIG_SETTING_BUCKETLIST_SIZE_WINDOW: + // uint64 bucketListSizeWindow<>; + // case CONFIG_SETTING_EVICTION_ITERATOR: + // EvictionIterator evictionIterator; + // }; + // + // =========================================================================== + xdr.union("ConfigSettingEntry", { + switchOn: xdr.lookup("ConfigSettingId"), + switchName: "configSettingId", + switches: [["configSettingContractMaxSizeBytes", "contractMaxSizeBytes"], ["configSettingContractComputeV0", "contractCompute"], ["configSettingContractLedgerCostV0", "contractLedgerCost"], ["configSettingContractHistoricalDataV0", "contractHistoricalData"], ["configSettingContractEventsV0", "contractEvents"], ["configSettingContractBandwidthV0", "contractBandwidth"], ["configSettingContractCostParamsCpuInstructions", "contractCostParamsCpuInsns"], ["configSettingContractCostParamsMemoryBytes", "contractCostParamsMemBytes"], ["configSettingContractDataKeySizeBytes", "contractDataKeySizeBytes"], ["configSettingContractDataEntrySizeBytes", "contractDataEntrySizeBytes"], ["configSettingStateArchival", "stateArchivalSettings"], ["configSettingContractExecutionLanes", "contractExecutionLanes"], ["configSettingBucketlistSizeWindow", "bucketListSizeWindow"], ["configSettingEvictionIterator", "evictionIterator"]], + arms: { + contractMaxSizeBytes: xdr.lookup("Uint32"), + contractCompute: xdr.lookup("ConfigSettingContractComputeV0"), + contractLedgerCost: xdr.lookup("ConfigSettingContractLedgerCostV0"), + contractHistoricalData: xdr.lookup("ConfigSettingContractHistoricalDataV0"), + contractEvents: xdr.lookup("ConfigSettingContractEventsV0"), + contractBandwidth: xdr.lookup("ConfigSettingContractBandwidthV0"), + contractCostParamsCpuInsns: xdr.lookup("ContractCostParams"), + contractCostParamsMemBytes: xdr.lookup("ContractCostParams"), + contractDataKeySizeBytes: xdr.lookup("Uint32"), + contractDataEntrySizeBytes: xdr.lookup("Uint32"), + stateArchivalSettings: xdr.lookup("StateArchivalSettings"), + contractExecutionLanes: xdr.lookup("ConfigSettingContractExecutionLanesV0"), + bucketListSizeWindow: xdr.varArray(xdr.lookup("Uint64"), 2147483647), + evictionIterator: xdr.lookup("EvictionIterator") + } + }); +}); +var _default = exports["default"] = types; + +/***/ }), + +/***/ 5578: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LiquidityPoolFeeV18 = void 0; +exports.getLiquidityPoolId = getLiquidityPoolId; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +var _hashing = __webpack_require__(9152); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +// LiquidityPoolFeeV18 is the default liquidity pool fee in protocol v18. It defaults to 30 base points (0.3%). +var LiquidityPoolFeeV18 = exports.LiquidityPoolFeeV18 = 30; + +/** + * getLiquidityPoolId computes the Pool ID for the given assets, fee and pool type. + * + * @see [stellar-core getPoolID](https://github.com/stellar/stellar-core/blob/9f3a48c6a8f1aa77b6043a055d0638661f718080/src/ledger/test/LedgerTxnTests.cpp#L3746-L3751) + * + * @export + * @param {string} liquidityPoolType – A string representing the liquidity pool type. + * @param {object} liquidityPoolParameters – The liquidity pool parameters. + * @param {Asset} liquidityPoolParameters.assetA – The first asset in the Pool, it must respect the rule assetA < assetB. + * @param {Asset} liquidityPoolParameters.assetB – The second asset in the Pool, it must respect the rule assetA < assetB. + * @param {number} liquidityPoolParameters.fee – The liquidity pool fee. For now the only fee supported is `30`. + * + * @return {Buffer} the raw Pool ID buffer, which can be stringfied with `toString('hex')` + */ +function getLiquidityPoolId(liquidityPoolType) { + var liquidityPoolParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (liquidityPoolType !== 'constant_product') { + throw new Error('liquidityPoolType is invalid'); + } + var assetA = liquidityPoolParameters.assetA, + assetB = liquidityPoolParameters.assetB, + fee = liquidityPoolParameters.fee; + if (!assetA || !(assetA instanceof _asset.Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof _asset.Asset)) { + throw new Error('assetB is invalid'); + } + if (!fee || fee !== LiquidityPoolFeeV18) { + throw new Error('fee is invalid'); + } + if (_asset.Asset.compare(assetA, assetB) !== -1) { + throw new Error('Assets are not in lexicographic order'); + } + var lpTypeData = _xdr["default"].LiquidityPoolType.liquidityPoolConstantProduct().toXDR(); + var lpParamsData = new _xdr["default"].LiquidityPoolConstantProductParameters({ + assetA: assetA.toXDRObject(), + assetB: assetB.toXDRObject(), + fee: fee + }).toXDR(); + var payload = Buffer.concat([lpTypeData, lpParamsData]); + return (0, _hashing.hash)(payload); +} + +/***/ }), + +/***/ 9152: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.hash = hash; +var _sha = __webpack_require__(2802); +function hash(data) { + var hasher = new _sha.sha256(); + hasher.update(data, 'utf8'); + return hasher.digest(); +} + +/***/ }), + +/***/ 356: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _exportNames = { + xdr: true, + cereal: true, + hash: true, + sign: true, + verify: true, + FastSigning: true, + getLiquidityPoolId: true, + LiquidityPoolFeeV18: true, + Keypair: true, + UnsignedHyper: true, + Hyper: true, + TransactionBase: true, + Transaction: true, + FeeBumpTransaction: true, + TransactionBuilder: true, + TimeoutInfinite: true, + BASE_FEE: true, + Asset: true, + LiquidityPoolAsset: true, + LiquidityPoolId: true, + Operation: true, + AuthRequiredFlag: true, + AuthRevocableFlag: true, + AuthImmutableFlag: true, + AuthClawbackEnabledFlag: true, + Account: true, + MuxedAccount: true, + Claimant: true, + Networks: true, + StrKey: true, + SignerKey: true, + Soroban: true, + decodeAddressToMuxedAccount: true, + encodeMuxedAccountToAddress: true, + extractBaseAddress: true, + encodeMuxedAccount: true, + Contract: true, + Address: true +}; +Object.defineProperty(exports, "Account", ({ + enumerable: true, + get: function get() { + return _account.Account; + } +})); +Object.defineProperty(exports, "Address", ({ + enumerable: true, + get: function get() { + return _address.Address; + } +})); +Object.defineProperty(exports, "Asset", ({ + enumerable: true, + get: function get() { + return _asset.Asset; + } +})); +Object.defineProperty(exports, "AuthClawbackEnabledFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthClawbackEnabledFlag; + } +})); +Object.defineProperty(exports, "AuthImmutableFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthImmutableFlag; + } +})); +Object.defineProperty(exports, "AuthRequiredFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthRequiredFlag; + } +})); +Object.defineProperty(exports, "AuthRevocableFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthRevocableFlag; + } +})); +Object.defineProperty(exports, "BASE_FEE", ({ + enumerable: true, + get: function get() { + return _transaction_builder.BASE_FEE; + } +})); +Object.defineProperty(exports, "Claimant", ({ + enumerable: true, + get: function get() { + return _claimant.Claimant; + } +})); +Object.defineProperty(exports, "Contract", ({ + enumerable: true, + get: function get() { + return _contract.Contract; + } +})); +Object.defineProperty(exports, "FastSigning", ({ + enumerable: true, + get: function get() { + return _signing.FastSigning; + } +})); +Object.defineProperty(exports, "FeeBumpTransaction", ({ + enumerable: true, + get: function get() { + return _fee_bump_transaction.FeeBumpTransaction; + } +})); +Object.defineProperty(exports, "Hyper", ({ + enumerable: true, + get: function get() { + return _jsXdr.Hyper; + } +})); +Object.defineProperty(exports, "Keypair", ({ + enumerable: true, + get: function get() { + return _keypair.Keypair; + } +})); +Object.defineProperty(exports, "LiquidityPoolAsset", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_asset.LiquidityPoolAsset; + } +})); +Object.defineProperty(exports, "LiquidityPoolFeeV18", ({ + enumerable: true, + get: function get() { + return _get_liquidity_pool_id.LiquidityPoolFeeV18; + } +})); +Object.defineProperty(exports, "LiquidityPoolId", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_id.LiquidityPoolId; + } +})); +Object.defineProperty(exports, "MuxedAccount", ({ + enumerable: true, + get: function get() { + return _muxed_account.MuxedAccount; + } +})); +Object.defineProperty(exports, "Networks", ({ + enumerable: true, + get: function get() { + return _network.Networks; + } +})); +Object.defineProperty(exports, "Operation", ({ + enumerable: true, + get: function get() { + return _operation.Operation; + } +})); +Object.defineProperty(exports, "SignerKey", ({ + enumerable: true, + get: function get() { + return _signerkey.SignerKey; + } +})); +Object.defineProperty(exports, "Soroban", ({ + enumerable: true, + get: function get() { + return _soroban.Soroban; + } +})); +Object.defineProperty(exports, "StrKey", ({ + enumerable: true, + get: function get() { + return _strkey.StrKey; + } +})); +Object.defineProperty(exports, "TimeoutInfinite", ({ + enumerable: true, + get: function get() { + return _transaction_builder.TimeoutInfinite; + } +})); +Object.defineProperty(exports, "Transaction", ({ + enumerable: true, + get: function get() { + return _transaction.Transaction; + } +})); +Object.defineProperty(exports, "TransactionBase", ({ + enumerable: true, + get: function get() { + return _transaction_base.TransactionBase; + } +})); +Object.defineProperty(exports, "TransactionBuilder", ({ + enumerable: true, + get: function get() { + return _transaction_builder.TransactionBuilder; + } +})); +Object.defineProperty(exports, "UnsignedHyper", ({ + enumerable: true, + get: function get() { + return _jsXdr.UnsignedHyper; + } +})); +Object.defineProperty(exports, "cereal", ({ + enumerable: true, + get: function get() { + return _jsxdr["default"]; + } +})); +Object.defineProperty(exports, "decodeAddressToMuxedAccount", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.decodeAddressToMuxedAccount; + } +})); +exports["default"] = void 0; +Object.defineProperty(exports, "encodeMuxedAccount", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.encodeMuxedAccount; + } +})); +Object.defineProperty(exports, "encodeMuxedAccountToAddress", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.encodeMuxedAccountToAddress; + } +})); +Object.defineProperty(exports, "extractBaseAddress", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.extractBaseAddress; + } +})); +Object.defineProperty(exports, "getLiquidityPoolId", ({ + enumerable: true, + get: function get() { + return _get_liquidity_pool_id.getLiquidityPoolId; + } +})); +Object.defineProperty(exports, "hash", ({ + enumerable: true, + get: function get() { + return _hashing.hash; + } +})); +Object.defineProperty(exports, "sign", ({ + enumerable: true, + get: function get() { + return _signing.sign; + } +})); +Object.defineProperty(exports, "verify", ({ + enumerable: true, + get: function get() { + return _signing.verify; + } +})); +Object.defineProperty(exports, "xdr", ({ + enumerable: true, + get: function get() { + return _xdr["default"]; + } +})); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _jsxdr = _interopRequireDefault(__webpack_require__(3335)); +var _hashing = __webpack_require__(9152); +var _signing = __webpack_require__(15); +var _get_liquidity_pool_id = __webpack_require__(5578); +var _keypair = __webpack_require__(6691); +var _jsXdr = __webpack_require__(3740); +var _transaction_base = __webpack_require__(3758); +var _transaction = __webpack_require__(380); +var _fee_bump_transaction = __webpack_require__(9260); +var _transaction_builder = __webpack_require__(6396); +var _asset = __webpack_require__(1764); +var _liquidity_pool_asset = __webpack_require__(2262); +var _liquidity_pool_id = __webpack_require__(9353); +var _operation = __webpack_require__(7237); +var _memo = __webpack_require__(4172); +Object.keys(_memo).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _memo[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _memo[key]; + } + }); +}); +var _account = __webpack_require__(2135); +var _muxed_account = __webpack_require__(2243); +var _claimant = __webpack_require__(1387); +var _network = __webpack_require__(6202); +var _strkey = __webpack_require__(7120); +var _signerkey = __webpack_require__(225); +var _soroban = __webpack_require__(4062); +var _decode_encode_muxed_account = __webpack_require__(6160); +var _contract = __webpack_require__(7452); +var _address = __webpack_require__(1180); +var _numbers = __webpack_require__(8549); +Object.keys(_numbers).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _numbers[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _numbers[key]; + } + }); +}); +var _scval = __webpack_require__(7177); +Object.keys(_scval).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _scval[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _scval[key]; + } + }); +}); +var _events = __webpack_require__(3919); +Object.keys(_events).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _events[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _events[key]; + } + }); +}); +var _sorobandata_builder = __webpack_require__(4842); +Object.keys(_sorobandata_builder).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _sorobandata_builder[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _sorobandata_builder[key]; + } + }); +}); +var _auth = __webpack_require__(5328); +Object.keys(_auth).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _auth[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _auth[key]; + } + }); +}); +var _invocation = __webpack_require__(3564); +Object.keys(_invocation).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _invocation[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _invocation[key]; + } + }); +}); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/* eslint-disable import/no-import-module-exports */ +// +// Soroban +// +var _default = exports["default"] = module.exports; + +/***/ }), + +/***/ 3564: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.buildInvocationTree = buildInvocationTree; +exports.walkInvocationTree = walkInvocationTree; +var _asset = __webpack_require__(1764); +var _address = __webpack_require__(1180); +var _scval = __webpack_require__(7177); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * @typedef CreateInvocation + * + * @prop {'wasm'|'sac'} type a type indicating if this creation was a custom + * contract or a wrapping of an existing Stellar asset + * @prop {string} [token] when `type=='sac'`, the canonical {@link Asset} that + * is being wrapped by this Stellar Asset Contract + * @prop {object} [wasm] when `type=='wasm'`, add'l creation parameters + * + * @prop {string} wasm.hash hex hash of WASM bytecode backing this contract + * @prop {string} wasm.address contract address of this deployment + * @prop {string} wasm.salt hex salt that the user consumed when creating + * this contract (encoded in the resulting address) + * @prop {any[]} [wasm.constructorArgs] a list of natively-represented values + * (see {@link scValToNative}) that are passed to the constructor when + * creating this contract + */ + +/** + * @typedef ExecuteInvocation + * + * @prop {string} source the strkey of the contract (C...) being invoked + * @prop {string} function the name of the function being invoked + * @prop {any[]} args the natively-represented parameters to the function + * invocation (see {@link scValToNative} for rules on how they're + * represented a JS types) + */ + +/** + * @typedef InvocationTree + * @prop {'execute' | 'create'} type the type of invocation occurring, either + * contract creation or host function execution + * @prop {CreateInvocation | ExecuteInvocation} args the parameters to the + * invocation, depending on the type + * @prop {InvocationTree[]} invocations any sub-invocations that (may) occur + * as a result of this invocation (i.e. a tree of call stacks) + */ + +/** + * Turns a raw invocation tree into a human-readable format. + * + * This is designed to make the invocation tree easier to understand in order to + * inform users about the side-effects of their contract calls. This will help + * make informed decisions about whether or not a particular invocation will + * result in what you expect it to. + * + * @param {xdr.SorobanAuthorizedInvocation} root the raw XDR of the invocation, + * likely acquired from transaction simulation. this is either from the + * {@link Operation.invokeHostFunction} itself (the `func` field), or from + * the authorization entries ({@link xdr.SorobanAuthorizationEntry}, the + * `rootInvocation` field) + * + * @returns {InvocationTree} a human-readable version of the invocation tree + * + * @example + * Here, we show a browser modal after simulating an arbitrary transaction, + * `tx`, which we assume has an `Operation.invokeHostFunction` inside of it: + * + * ```typescript + * import { Server, buildInvocationTree } from '@stellar/stellar-sdk'; + * + * const s = new Server("fill in accordingly"); + * + * s.simulateTransaction(tx).then( + * (resp: SorobanRpc.SimulateTransactionResponse) => { + * if (SorobanRpc.isSuccessfulSim(resp) && ) { + * // bold assumption: there's a valid result with an auth entry + * alert( + * "You are authorizing the following invocation:\n" + + * JSON.stringify( + * buildInvocationTree(resp.result!.auth[0].rootInvocation()), + * null, + * 2 + * ) + * ); + * } + * } + * ); + * ``` + */ +function buildInvocationTree(root) { + var fn = root["function"](); + + /** @type {InvocationTree} */ + var output = {}; + + /** @type {xdr.CreateContractArgs|xdr.CreateContractArgsV2|xdr.InvokeContractArgs} */ + var inner = fn.value(); + switch (fn["switch"]().value) { + // sorobanAuthorizedFunctionTypeContractFn + case 0: + output.type = 'execute'; + output.args = { + source: _address.Address.fromScAddress(inner.contractAddress()).toString(), + "function": inner.functionName(), + args: inner.args().map(function (arg) { + return (0, _scval.scValToNative)(arg); + }) + }; + break; + + // sorobanAuthorizedFunctionTypeCreateContractHostFn + // sorobanAuthorizedFunctionTypeCreateContractV2HostFn + case 1: // fallthrough: just no ctor args in V1 + case 2: + { + var createV2 = fn["switch"]().value === 2; + output.type = 'create'; + output.args = {}; + + // If the executable is a WASM, the preimage MUST be an address. If it's a + // token, the preimage MUST be an asset. This is a cheeky way to check + // that, because wasm=0, token=1 and address=0, asset=1 in the XDR switch + // values. + // + // The first part may not be true in V2, but we'd need to update this code + // anyway so it can still be an error. + var _ref = [inner.executable(), inner.contractIdPreimage()], + exec = _ref[0], + preimage = _ref[1]; + if (!!exec["switch"]().value !== !!preimage["switch"]().value) { + throw new Error("creation function appears invalid: ".concat(JSON.stringify(inner), " (should be wasm+address or token+asset)")); + } + switch (exec["switch"]().value) { + // contractExecutableWasm + case 0: + { + /** @type {xdr.ContractIdPreimageFromAddress} */ + var details = preimage.fromAddress(); + output.args.type = 'wasm'; + output.args.wasm = _objectSpread({ + salt: details.salt().toString('hex'), + hash: exec.wasmHash().toString('hex'), + address: _address.Address.fromScAddress(details.address()).toString() + }, createV2 && { + constructorArgs: inner.constructorArgs().map(function (arg) { + return (0, _scval.scValToNative)(arg); + }) + }); + break; + } + + // contractExecutableStellarAsset + case 1: + output.args.type = 'sac'; + output.args.asset = _asset.Asset.fromOperation(preimage.fromAsset()).toString(); + break; + default: + throw new Error("unknown creation type: ".concat(JSON.stringify(exec))); + } + break; + } + default: + throw new Error("unknown invocation type (".concat(fn["switch"](), "): ").concat(JSON.stringify(fn))); + } + output.invocations = root.subInvocations().map(function (i) { + return buildInvocationTree(i); + }); + return output; +} + +/** + * @callback InvocationWalker + * + * @param {xdr.SorobanAuthorizedInvocation} node the currently explored node + * @param {number} depth the depth of the tree this node is occurring at (the + * root starts at a depth of 1) + * @param {xdr.SorobanAuthorizedInvocation} [parent] this `node`s parent node, + * if any (i.e. this doesn't exist at the root) + * + * @returns {boolean|null|void} returning exactly `false` is a hint to stop + * exploring, other values are ignored + */ + +/** + * Executes a callback function on each node in the tree until stopped. + * + * Nodes are walked in a depth-first order. Returning `false` from the callback + * stops further depth exploration at that node, but it does not stop the walk + * in a "global" view. + * + * @param {xdr.SorobanAuthorizedInvocation} root the tree to explore + * @param {InvocationWalker} callback the callback to execute for each node + * @returns {void} + */ +function walkInvocationTree(root, callback) { + walkHelper(root, 1, callback); +} +function walkHelper(node, depth, callback, parent) { + if (callback(node, depth, parent) === false /* allow void rv */) { + return; + } + node.subInvocations().forEach(function (i) { + return walkHelper(i, depth + 1, callback, node); + }); +} + +/***/ }), + +/***/ 3335: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _jsXdr = __webpack_require__(3740); +var cereal = { + XdrWriter: _jsXdr.XdrWriter, + XdrReader: _jsXdr.XdrReader +}; +var _default = exports["default"] = cereal; + +/***/ }), + +/***/ 6691: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Keypair = void 0; +var _tweetnacl = _interopRequireDefault(__webpack_require__(4940)); +var _signing = __webpack_require__(15); +var _strkey = __webpack_require__(7120); +var _hashing = __webpack_require__(9152); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": ["^"]}] */ +/** + * `Keypair` represents public (and secret) keys of the account. + * + * Currently `Keypair` only supports ed25519 but in a future this class can be abstraction layer for other + * public-key signature systems. + * + * Use more convenient methods to create `Keypair` object: + * * `{@link Keypair.fromPublicKey}` + * * `{@link Keypair.fromSecret}` + * * `{@link Keypair.random}` + * + * @constructor + * @param {object} keys At least one of keys must be provided. + * @param {string} keys.type Public-key signature system name. (currently only `ed25519` keys are supported) + * @param {Buffer} [keys.publicKey] Raw public key + * @param {Buffer} [keys.secretKey] Raw secret key (32-byte secret seed in ed25519`) + */ +var Keypair = exports.Keypair = /*#__PURE__*/function () { + function Keypair(keys) { + _classCallCheck(this, Keypair); + if (keys.type !== 'ed25519') { + throw new Error('Invalid keys type'); + } + this.type = keys.type; + if (keys.secretKey) { + keys.secretKey = Buffer.from(keys.secretKey); + if (keys.secretKey.length !== 32) { + throw new Error('secretKey length is invalid'); + } + this._secretSeed = keys.secretKey; + this._publicKey = (0, _signing.generate)(keys.secretKey); + this._secretKey = Buffer.concat([keys.secretKey, this._publicKey]); + if (keys.publicKey && !this._publicKey.equals(Buffer.from(keys.publicKey))) { + throw new Error('secretKey does not match publicKey'); + } + } else { + this._publicKey = Buffer.from(keys.publicKey); + if (this._publicKey.length !== 32) { + throw new Error('publicKey length is invalid'); + } + } + } + + /** + * Creates a new `Keypair` instance from secret. This can either be secret key or secret seed depending + * on underlying public-key signature system. Currently `Keypair` only supports ed25519. + * @param {string} secret secret key (ex. `SDAKFNYEIAORZKKCYRILFQKLLOCNPL5SWJ3YY5NM3ZH6GJSZGXHZEPQS`) + * @returns {Keypair} + */ + return _createClass(Keypair, [{ + key: "xdrAccountId", + value: function xdrAccountId() { + return new _xdr["default"].AccountId.publicKeyTypeEd25519(this._publicKey); + } + }, { + key: "xdrPublicKey", + value: function xdrPublicKey() { + return new _xdr["default"].PublicKey.publicKeyTypeEd25519(this._publicKey); + } + + /** + * Creates a {@link xdr.MuxedAccount} object from the public key. + * + * You will get a different type of muxed account depending on whether or not + * you pass an ID. + * + * @param {string} [id] - stringified integer indicating the underlying muxed + * ID of the new account object + * + * @return {xdr.MuxedAccount} + */ + }, { + key: "xdrMuxedAccount", + value: function xdrMuxedAccount(id) { + if (typeof id !== 'undefined') { + if (typeof id !== 'string') { + throw new TypeError("expected string for ID, got ".concat(_typeof(id))); + } + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromString(id), + ed25519: this._publicKey + })); + } + return new _xdr["default"].MuxedAccount.keyTypeEd25519(this._publicKey); + } + + /** + * Returns raw public key + * @returns {Buffer} + */ + }, { + key: "rawPublicKey", + value: function rawPublicKey() { + return this._publicKey; + } + }, { + key: "signatureHint", + value: function signatureHint() { + var a = this.xdrAccountId().toXDR(); + return a.slice(a.length - 4); + } + + /** + * Returns public key associated with this `Keypair` object. + * @returns {string} + */ + }, { + key: "publicKey", + value: function publicKey() { + return _strkey.StrKey.encodeEd25519PublicKey(this._publicKey); + } + + /** + * Returns secret key associated with this `Keypair` object + * @returns {string} + */ + }, { + key: "secret", + value: function secret() { + if (!this._secretSeed) { + throw new Error('no secret key available'); + } + if (this.type === 'ed25519') { + return _strkey.StrKey.encodeEd25519SecretSeed(this._secretSeed); + } + throw new Error('Invalid Keypair type'); + } + + /** + * Returns raw secret key. + * @returns {Buffer} + */ + }, { + key: "rawSecretKey", + value: function rawSecretKey() { + return this._secretSeed; + } + + /** + * Returns `true` if this `Keypair` object contains secret key and can sign. + * @returns {boolean} + */ + }, { + key: "canSign", + value: function canSign() { + return !!this._secretKey; + } + + /** + * Signs data. + * @param {Buffer} data Data to sign + * @returns {Buffer} + */ + }, { + key: "sign", + value: function sign(data) { + if (!this.canSign()) { + throw new Error('cannot sign: no secret key available'); + } + return (0, _signing.sign)(data, this._secretKey); + } + + /** + * Verifies if `signature` for `data` is valid. + * @param {Buffer} data Signed data + * @param {Buffer} signature Signature + * @returns {boolean} + */ + }, { + key: "verify", + value: function verify(data, signature) { + return (0, _signing.verify)(data, signature, this._publicKey); + } + + /** + * Returns the decorated signature (hint+sig) for arbitrary data. + * + * @param {Buffer} data arbitrary data to sign + * @return {xdr.DecoratedSignature} the raw signature structure which can be + * added directly to a transaction envelope + * + * @see TransactionBase.addDecoratedSignature + */ + }, { + key: "signDecorated", + value: function signDecorated(data) { + var signature = this.sign(data); + var hint = this.signatureHint(); + return new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signature + }); + } + + /** + * Returns the raw decorated signature (hint+sig) for a signed payload signer. + * + * The hint is defined as the last 4 bytes of the signer key XORed with last + * 4 bytes of the payload (zero-left-padded if necessary). + * + * @param {Buffer} data data to both sign and treat as the payload + * @return {xdr.DecoratedSignature} + * + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0040.md#signature-hint + * @see TransactionBase.addDecoratedSignature + */ + }, { + key: "signPayloadDecorated", + value: function signPayloadDecorated(data) { + var signature = this.sign(data); + var keyHint = this.signatureHint(); + var hint = Buffer.from(data.slice(-4)); + if (hint.length < 4) { + // append zeroes as needed + hint = Buffer.concat([hint, Buffer.alloc(4 - data.length, 0)]); + } + return new _xdr["default"].DecoratedSignature({ + hint: hint.map(function (_byte, i) { + return _byte ^ keyHint[i]; + }), + signature: signature + }); + } + }], [{ + key: "fromSecret", + value: function fromSecret(secret) { + var rawSecret = _strkey.StrKey.decodeEd25519SecretSeed(secret); + return this.fromRawEd25519Seed(rawSecret); + } + + /** + * Creates a new `Keypair` object from ed25519 secret key seed raw bytes. + * + * @param {Buffer} rawSeed Raw 32-byte ed25519 secret key seed + * @returns {Keypair} + */ + }, { + key: "fromRawEd25519Seed", + value: function fromRawEd25519Seed(rawSeed) { + return new this({ + type: 'ed25519', + secretKey: rawSeed + }); + } + + /** + * Returns `Keypair` object representing network master key. + * @param {string} networkPassphrase passphrase of the target stellar network (e.g. "Public Global Stellar Network ; September 2015"). + * @returns {Keypair} + */ + }, { + key: "master", + value: function master(networkPassphrase) { + if (!networkPassphrase) { + throw new Error('No network selected. Please pass a network argument, e.g. `Keypair.master(Networks.PUBLIC)`.'); + } + return this.fromRawEd25519Seed((0, _hashing.hash)(networkPassphrase)); + } + + /** + * Creates a new `Keypair` object from public key. + * @param {string} publicKey public key (ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`) + * @returns {Keypair} + */ + }, { + key: "fromPublicKey", + value: function fromPublicKey(publicKey) { + publicKey = _strkey.StrKey.decodeEd25519PublicKey(publicKey); + if (publicKey.length !== 32) { + throw new Error('Invalid Stellar public key'); + } + return new this({ + type: 'ed25519', + publicKey: publicKey + }); + } + + /** + * Create a random `Keypair` object. + * @returns {Keypair} + */ + }, { + key: "random", + value: function random() { + var secret = _tweetnacl["default"].randomBytes(32); + return this.fromRawEd25519Seed(secret); + } + }]); +}(); + +/***/ }), + +/***/ 2262: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LiquidityPoolAsset = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +var _get_liquidity_pool_id = __webpack_require__(5578); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * LiquidityPoolAsset class represents a liquidity pool trustline change. + * + * @constructor + * @param {Asset} assetA – The first asset in the Pool, it must respect the rule assetA < assetB. See {@link Asset.compare} for more details on how assets are sorted. + * @param {Asset} assetB – The second asset in the Pool, it must respect the rule assetA < assetB. See {@link Asset.compare} for more details on how assets are sorted. + * @param {number} fee – The liquidity pool fee. For now the only fee supported is `30`. + */ +var LiquidityPoolAsset = exports.LiquidityPoolAsset = /*#__PURE__*/function () { + function LiquidityPoolAsset(assetA, assetB, fee) { + _classCallCheck(this, LiquidityPoolAsset); + if (!assetA || !(assetA instanceof _asset.Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof _asset.Asset)) { + throw new Error('assetB is invalid'); + } + if (_asset.Asset.compare(assetA, assetB) !== -1) { + throw new Error('Assets are not in lexicographic order'); + } + if (!fee || fee !== _get_liquidity_pool_id.LiquidityPoolFeeV18) { + throw new Error('fee is invalid'); + } + this.assetA = assetA; + this.assetB = assetB; + this.fee = fee; + } + + /** + * Returns a liquidity pool asset object from its XDR ChangeTrustAsset object + * representation. + * @param {xdr.ChangeTrustAsset} ctAssetXdr - The asset XDR object. + * @returns {LiquidityPoolAsset} + */ + return _createClass(LiquidityPoolAsset, [{ + key: "toXDRObject", + value: + /** + * Returns the `xdr.ChangeTrustAsset` object for this liquidity pool asset. + * + * Note: To convert from an {@link Asset `Asset`} to `xdr.ChangeTrustAsset` + * please refer to the + * {@link Asset.toChangeTrustXDRObject `Asset.toChangeTrustXDRObject`} method. + * + * @returns {xdr.ChangeTrustAsset} XDR ChangeTrustAsset object. + */ + function toXDRObject() { + var lpConstantProductParamsXdr = new _xdr["default"].LiquidityPoolConstantProductParameters({ + assetA: this.assetA.toXDRObject(), + assetB: this.assetB.toXDRObject(), + fee: this.fee + }); + var lpParamsXdr = new _xdr["default"].LiquidityPoolParameters('liquidityPoolConstantProduct', lpConstantProductParamsXdr); + return new _xdr["default"].ChangeTrustAsset('assetTypePoolShare', lpParamsXdr); + } + + /** + * @returns {LiquidityPoolParameters} Liquidity pool parameters. + */ + }, { + key: "getLiquidityPoolParameters", + value: function getLiquidityPoolParameters() { + return _objectSpread(_objectSpread({}, this), {}, { + assetA: this.assetA, + assetB: this.assetB, + fee: this.fee + }); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {AssetType.liquidityPoolShares} asset type. Can only be `liquidity_pool_shares`. + */ + }, { + key: "getAssetType", + value: function getAssetType() { + return 'liquidity_pool_shares'; + } + + /** + * @param {LiquidityPoolAsset} other the LiquidityPoolAsset to compare + * @returns {boolean} `true` if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(other) { + return this.assetA.equals(other.assetA) && this.assetB.equals(other.assetB) && this.fee === other.fee; + } + }, { + key: "toString", + value: function toString() { + var poolId = (0, _get_liquidity_pool_id.getLiquidityPoolId)('constant_product', this.getLiquidityPoolParameters()).toString('hex'); + return "liquidity_pool:".concat(poolId); + } + }], [{ + key: "fromOperation", + value: function fromOperation(ctAssetXdr) { + var assetType = ctAssetXdr["switch"](); + if (assetType === _xdr["default"].AssetType.assetTypePoolShare()) { + var liquidityPoolParameters = ctAssetXdr.liquidityPool().constantProduct(); + return new this(_asset.Asset.fromOperation(liquidityPoolParameters.assetA()), _asset.Asset.fromOperation(liquidityPoolParameters.assetB()), liquidityPoolParameters.fee()); + } + throw new Error("Invalid asset type: ".concat(assetType.name)); + } + }]); +}(); + +/***/ }), + +/***/ 9353: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LiquidityPoolId = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * LiquidityPoolId class represents the asset referenced by a trustline to a + * liquidity pool. + * + * @constructor + * @param {string} liquidityPoolId - The ID of the liquidity pool in string 'hex'. + */ +var LiquidityPoolId = exports.LiquidityPoolId = /*#__PURE__*/function () { + function LiquidityPoolId(liquidityPoolId) { + _classCallCheck(this, LiquidityPoolId); + if (!liquidityPoolId) { + throw new Error('liquidityPoolId cannot be empty'); + } + if (!/^[a-f0-9]{64}$/.test(liquidityPoolId)) { + throw new Error('Liquidity pool ID is not a valid hash'); + } + this.liquidityPoolId = liquidityPoolId; + } + + /** + * Returns a liquidity pool ID object from its xdr.TrustLineAsset representation. + * @param {xdr.TrustLineAsset} tlAssetXdr - The asset XDR object. + * @returns {LiquidityPoolId} + */ + return _createClass(LiquidityPoolId, [{ + key: "toXDRObject", + value: + /** + * Returns the `xdr.TrustLineAsset` object for this liquidity pool ID. + * + * Note: To convert from {@link Asset `Asset`} to `xdr.TrustLineAsset` please + * refer to the + * {@link Asset.toTrustLineXDRObject `Asset.toTrustLineXDRObject`} method. + * + * @returns {xdr.TrustLineAsset} XDR LiquidityPoolId object + */ + function toXDRObject() { + var xdrPoolId = _xdr["default"].PoolId.fromXDR(this.liquidityPoolId, 'hex'); + return new _xdr["default"].TrustLineAsset('assetTypePoolShare', xdrPoolId); + } + + /** + * @returns {string} Liquidity pool ID. + */ + }, { + key: "getLiquidityPoolId", + value: function getLiquidityPoolId() { + return String(this.liquidityPoolId); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {AssetType.liquidityPoolShares} asset type. Can only be `liquidity_pool_shares`. + */ + }, { + key: "getAssetType", + value: function getAssetType() { + return 'liquidity_pool_shares'; + } + + /** + * @param {LiquidityPoolId} asset LiquidityPoolId to compare. + * @returns {boolean} `true` if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(asset) { + return this.liquidityPoolId === asset.getLiquidityPoolId(); + } + }, { + key: "toString", + value: function toString() { + return "liquidity_pool:".concat(this.liquidityPoolId); + } + }], [{ + key: "fromOperation", + value: function fromOperation(tlAssetXdr) { + var assetType = tlAssetXdr["switch"](); + if (assetType === _xdr["default"].AssetType.assetTypePoolShare()) { + var liquidityPoolId = tlAssetXdr.liquidityPoolId().toString('hex'); + return new this(liquidityPoolId); + } + throw new Error("Invalid asset type: ".concat(assetType.name)); + } + }]); +}(); + +/***/ }), + +/***/ 4172: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.MemoText = exports.MemoReturn = exports.MemoNone = exports.MemoID = exports.MemoHash = exports.Memo = void 0; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Type of {@link Memo}. + */ +var MemoNone = exports.MemoNone = 'none'; +/** + * Type of {@link Memo}. + */ +var MemoID = exports.MemoID = 'id'; +/** + * Type of {@link Memo}. + */ +var MemoText = exports.MemoText = 'text'; +/** + * Type of {@link Memo}. + */ +var MemoHash = exports.MemoHash = 'hash'; +/** + * Type of {@link Memo}. + */ +var MemoReturn = exports.MemoReturn = 'return'; + +/** + * `Memo` represents memos attached to transactions. + * + * @param {string} type - `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn` + * @param {*} value - `string` for `MemoID`, `MemoText`, buffer of hex string for `MemoHash` or `MemoReturn` + * @see [Transactions concept](https://developers.stellar.org/docs/glossary/transactions/) + * @class Memo + */ +var Memo = exports.Memo = /*#__PURE__*/function () { + function Memo(type) { + var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + _classCallCheck(this, Memo); + this._type = type; + this._value = value; + switch (this._type) { + case MemoNone: + break; + case MemoID: + Memo._validateIdValue(value); + break; + case MemoText: + Memo._validateTextValue(value); + break; + case MemoHash: + case MemoReturn: + Memo._validateHashValue(value); + // We want MemoHash and MemoReturn to have Buffer as a value + if (typeof value === 'string') { + this._value = Buffer.from(value, 'hex'); + } + break; + default: + throw new Error('Invalid memo type'); + } + } + + /** + * Contains memo type: `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn` + */ + return _createClass(Memo, [{ + key: "type", + get: function get() { + return this._type; + }, + set: function set(type) { + throw new Error('Memo is immutable'); + } + + /** + * Contains memo value: + * * `null` for `MemoNone`, + * * `string` for `MemoID`, + * * `Buffer` for `MemoText` after decoding using `fromXDRObject`, original value otherwise, + * * `Buffer` for `MemoHash`, `MemoReturn`. + */ + }, { + key: "value", + get: function get() { + switch (this._type) { + case MemoNone: + return null; + case MemoID: + case MemoText: + return this._value; + case MemoHash: + case MemoReturn: + return Buffer.from(this._value); + default: + throw new Error('Invalid memo type'); + } + }, + set: function set(value) { + throw new Error('Memo is immutable'); + } + }, { + key: "toXDRObject", + value: + /** + * Returns XDR memo object. + * @returns {xdr.Memo} + */ + function toXDRObject() { + switch (this._type) { + case MemoNone: + return _xdr["default"].Memo.memoNone(); + case MemoID: + return _xdr["default"].Memo.memoId(_jsXdr.UnsignedHyper.fromString(this._value)); + case MemoText: + return _xdr["default"].Memo.memoText(this._value); + case MemoHash: + return _xdr["default"].Memo.memoHash(this._value); + case MemoReturn: + return _xdr["default"].Memo.memoReturn(this._value); + default: + return null; + } + } + + /** + * Returns {@link Memo} from XDR memo object. + * @param {xdr.Memo} object XDR memo object + * @returns {Memo} + */ + }], [{ + key: "_validateIdValue", + value: function _validateIdValue(value) { + var error = new Error("Expects a int64 as a string. Got ".concat(value)); + if (typeof value !== 'string') { + throw error; + } + var number; + try { + number = new _bignumber["default"](value); + } catch (e) { + throw error; + } + + // Infinity + if (!number.isFinite()) { + throw error; + } + + // NaN + if (number.isNaN()) { + throw error; + } + } + }, { + key: "_validateTextValue", + value: function _validateTextValue(value) { + if (!_xdr["default"].Memo.armTypeForArm('text').isValid(value)) { + throw new Error('Expects string, array or buffer, max 28 bytes'); + } + } + }, { + key: "_validateHashValue", + value: function _validateHashValue(value) { + var error = new Error("Expects a 32 byte hash value or hex encoded string. Got ".concat(value)); + if (value === null || typeof value === 'undefined') { + throw error; + } + var valueBuffer; + if (typeof value === 'string') { + if (!/^[0-9A-Fa-f]{64}$/g.test(value)) { + throw error; + } + valueBuffer = Buffer.from(value, 'hex'); + } else if (Buffer.isBuffer(value)) { + valueBuffer = Buffer.from(value); + } else { + throw error; + } + if (!valueBuffer.length || valueBuffer.length !== 32) { + throw error; + } + } + + /** + * Returns an empty memo (`MemoNone`). + * @returns {Memo} + */ + }, { + key: "none", + value: function none() { + return new Memo(MemoNone); + } + + /** + * Creates and returns a `MemoText` memo. + * @param {string} text - memo text + * @returns {Memo} + */ + }, { + key: "text", + value: function text(_text) { + return new Memo(MemoText, _text); + } + + /** + * Creates and returns a `MemoID` memo. + * @param {string} id - 64-bit number represented as a string + * @returns {Memo} + */ + }, { + key: "id", + value: function id(_id) { + return new Memo(MemoID, _id); + } + + /** + * Creates and returns a `MemoHash` memo. + * @param {array|string} hash - 32 byte hash or hex encoded string + * @returns {Memo} + */ + }, { + key: "hash", + value: function hash(_hash) { + return new Memo(MemoHash, _hash); + } + + /** + * Creates and returns a `MemoReturn` memo. + * @param {array|string} hash - 32 byte hash or hex encoded string + * @returns {Memo} + */ + }, { + key: "return", + value: function _return(hash) { + return new Memo(MemoReturn, hash); + } + }, { + key: "fromXDRObject", + value: function fromXDRObject(object) { + switch (object.arm()) { + case 'id': + return Memo.id(object.value().toString()); + case 'text': + return Memo.text(object.value()); + case 'hash': + return Memo.hash(object.value()); + case 'retHash': + return Memo["return"](object.value()); + default: + break; + } + if (typeof object.value() === 'undefined') { + return Memo.none(); + } + throw new Error('Unknown type'); + } + }]); +}(); + +/***/ }), + +/***/ 2243: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.MuxedAccount = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _account = __webpack_require__(2135); +var _strkey = __webpack_require__(7120); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Represents a muxed account for transactions and operations. + * + * A muxed (or *multiplexed*) account (defined rigorously in + * [CAP-27](https://stellar.org/protocol/cap-27) and briefly in + * [SEP-23](https://stellar.org/protocol/sep-23)) is one that resolves a single + * Stellar `G...`` account to many different underlying IDs. + * + * For example, you may have a single Stellar address for accounting purposes: + * GA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJVSGZ + * + * Yet would like to use it for 4 different family members: + * 1: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAGZFQ + * 2: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAALIWQ + * 3: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAPYHQ + * 4: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAQLQQ + * + * This object makes it easy to create muxed accounts from regular accounts, + * duplicate them, get/set the underlying IDs, etc. without mucking around with + * the raw XDR. + * + * Because muxed accounts are purely an off-chain convention, they all share the + * sequence number tied to their underlying G... account. Thus, this object + * *requires* an {@link Account} instance to be passed in, so that muxed + * instances of an account can collectively modify the sequence number whenever + * a muxed account is used as the source of a @{link Transaction} with {@link + * TransactionBuilder}. + * + * @constructor + * + * @param {Account} account - the @{link Account} instance representing the + * underlying G... address + * @param {string} id - a stringified uint64 value that represents the + * ID of the muxed account + * + * @link https://developers.stellar.org/docs/glossary/muxed-accounts/ + */ +var MuxedAccount = exports.MuxedAccount = /*#__PURE__*/function () { + function MuxedAccount(baseAccount, id) { + _classCallCheck(this, MuxedAccount); + var accountId = baseAccount.accountId(); + if (!_strkey.StrKey.isValidEd25519PublicKey(accountId)) { + throw new Error('accountId is invalid'); + } + this.account = baseAccount; + this._muxedXdr = (0, _decode_encode_muxed_account.encodeMuxedAccount)(accountId, id); + this._mAddress = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(this._muxedXdr); + this._id = id; + } + + /** + * Parses an M-address into a MuxedAccount object. + * + * @param {string} mAddress - an M-address to transform + * @param {string} sequenceNum - the sequence number of the underlying {@link + * Account}, to use for the underlying base account (@link + * MuxedAccount.baseAccount). If you're using the SDK, you can use + * `server.loadAccount` to fetch this if you don't know it. + * + * @return {MuxedAccount} + */ + return _createClass(MuxedAccount, [{ + key: "baseAccount", + value: + /** + * @return {Account} the underlying account object shared among all muxed + * accounts with this Stellar address + */ + function baseAccount() { + return this.account; + } + + /** + * @return {string} the M-address representing this account's (G-address, ID) + */ + }, { + key: "accountId", + value: function accountId() { + return this._mAddress; + } + }, { + key: "id", + value: function id() { + return this._id; + } + }, { + key: "setId", + value: function setId(id) { + if (typeof id !== 'string') { + throw new Error('id should be a string representing a number (uint64)'); + } + this._muxedXdr.med25519().id(_xdr["default"].Uint64.fromString(id)); + this._mAddress = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(this._muxedXdr); + this._id = id; + return this; + } + + /** + * Accesses the underlying account's sequence number. + * @return {string} strigified sequence number for the underlying account + */ + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this.account.sequenceNumber(); + } + + /** + * Increments the underlying account's sequence number by one. + * @return {void} + */ + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + return this.account.incrementSequenceNumber(); + } + + /** + * @return {xdr.MuxedAccount} the XDR object representing this muxed account's + * G-address and uint64 ID + */ + }, { + key: "toXDRObject", + value: function toXDRObject() { + return this._muxedXdr; + } + }, { + key: "equals", + value: function equals(otherMuxedAccount) { + return this.accountId() === otherMuxedAccount.accountId(); + } + }], [{ + key: "fromAddress", + value: function fromAddress(mAddress, sequenceNum) { + var muxedAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(mAddress); + var gAddress = (0, _decode_encode_muxed_account.extractBaseAddress)(mAddress); + var id = muxedAccount.med25519().id().toString(); + return new MuxedAccount(new _account.Account(gAddress, sequenceNum), id); + } + }]); +}(); + +/***/ }), + +/***/ 6202: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Networks = void 0; +/** + * Contains passphrases for common networks: + * * `Networks.PUBLIC`: `Public Global Stellar Network ; September 2015` + * * `Networks.TESTNET`: `Test SDF Network ; September 2015` + * * `Networks.FUTURENET`: `Test SDF Future Network ; October 2022` + * * `Networks.STANDALONE`: `Standalone Network ; February 2017` + * + * @type {{PUBLIC: string, TESTNET: string, FUTURENET: string, STANDALONE: string }} + */ +var Networks = exports.Networks = { + PUBLIC: 'Public Global Stellar Network ; September 2015', + TESTNET: 'Test SDF Network ; September 2015', + FUTURENET: 'Test SDF Future Network ; October 2022', + SANDBOX: 'Local Sandbox Stellar Network ; September 2022', + STANDALONE: 'Standalone Network ; February 2017' +}; + +/***/ }), + +/***/ 8549: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "Int128", ({ + enumerable: true, + get: function get() { + return _int.Int128; + } +})); +Object.defineProperty(exports, "Int256", ({ + enumerable: true, + get: function get() { + return _int2.Int256; + } +})); +Object.defineProperty(exports, "ScInt", ({ + enumerable: true, + get: function get() { + return _sc_int.ScInt; + } +})); +Object.defineProperty(exports, "Uint128", ({ + enumerable: true, + get: function get() { + return _uint.Uint128; + } +})); +Object.defineProperty(exports, "Uint256", ({ + enumerable: true, + get: function get() { + return _uint2.Uint256; + } +})); +Object.defineProperty(exports, "XdrLargeInt", ({ + enumerable: true, + get: function get() { + return _xdr_large_int.XdrLargeInt; + } +})); +exports.scValToBigInt = scValToBigInt; +var _xdr_large_int = __webpack_require__(7429); +var _uint = __webpack_require__(6272); +var _uint2 = __webpack_require__(8672); +var _int = __webpack_require__(5487); +var _int2 = __webpack_require__(4063); +var _sc_int = __webpack_require__(3317); +/** + * Transforms an opaque {@link xdr.ScVal} into a native bigint, if possible. + * + * If you then want to use this in the abstractions provided by this module, + * you can pass it to the constructor of {@link XdrLargeInt}. + * + * @example + * let scv = contract.call("add", x, y); // assume it returns an xdr.ScVal + * let bigi = scValToBigInt(scv); + * + * new ScInt(bigi); // if you don't care about types, and + * new XdrLargeInt('i128', bigi); // if you do + * + * @param {xdr.ScVal} scv - the raw XDR value to parse into an integer + * @returns {bigint} the native value of this input value + * + * @throws {TypeError} if the `scv` input value doesn't represent an integer + */ +function scValToBigInt(scv) { + var scIntType = _xdr_large_int.XdrLargeInt.getType(scv["switch"]().name); + switch (scv["switch"]().name) { + case 'scvU32': + case 'scvI32': + return BigInt(scv.value()); + case 'scvU64': + case 'scvI64': + return new _xdr_large_int.XdrLargeInt(scIntType, scv.value()).toBigInt(); + case 'scvU128': + case 'scvI128': + return new _xdr_large_int.XdrLargeInt(scIntType, [scv.value().lo(), scv.value().hi()]).toBigInt(); + case 'scvU256': + case 'scvI256': + return new _xdr_large_int.XdrLargeInt(scIntType, [scv.value().loLo(), scv.value().loHi(), scv.value().hiLo(), scv.value().hiHi()]).toBigInt(); + default: + throw TypeError("expected integer type, got ".concat(scv["switch"]())); + } +} + +/***/ }), + +/***/ 5487: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Int128 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Int128 = exports.Int128 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct a signed 128-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Int128() { + _classCallCheck(this, Int128); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Int128, [args]); + } + _inherits(Int128, _LargeInt); + return _createClass(Int128, [{ + key: "unsigned", + get: function get() { + return false; + } + }, { + key: "size", + get: function get() { + return 128; + } + }]); +}(_jsXdr.LargeInt); +Int128.defineIntBoundaries(); + +/***/ }), + +/***/ 4063: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Int256 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Int256 = exports.Int256 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct a signed 256-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Int256() { + _classCallCheck(this, Int256); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Int256, [args]); + } + _inherits(Int256, _LargeInt); + return _createClass(Int256, [{ + key: "unsigned", + get: function get() { + return false; + } + }, { + key: "size", + get: function get() { + return 256; + } + }]); +}(_jsXdr.LargeInt); +Int256.defineIntBoundaries(); + +/***/ }), + +/***/ 3317: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.ScInt = void 0; +var _xdr_large_int = __webpack_require__(7429); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Provides an easier way to manipulate large numbers for Stellar operations. + * + * You can instantiate this "**s**mart **c**ontract integer" value either from + * bigints, strings, or numbers (whole numbers, or this will throw). + * + * If you need to create a native BigInt from a list of integer "parts" (for + * example, you have a series of encoded 32-bit integers that represent a larger + * value), you can use the lower level abstraction {@link XdrLargeInt}. For + * example, you could do `new XdrLargeInt('u128', bytes...).toBigInt()`. + * + * @example + * import { xdr, ScInt, scValToBigInt } from "@stellar/stellar-base"; + * + * // You have an ScVal from a contract and want to parse it into JS native. + * const value = xdr.ScVal.fromXDR(someXdr, "base64"); + * const bigi = scValToBigInt(value); // grab it as a BigInt + * let sci = new ScInt(bigi); + * + * sci.toNumber(); // gives native JS type (w/ size check) + * sci.toBigInt(); // gives the native BigInt value + * sci.toU64(); // gives ScValType-specific XDR constructs (with size checks) + * + * // You have a number and want to shove it into a contract. + * sci = ScInt(0xdeadcafebabe); + * sci.toBigInt() // returns 244838016400062n + * sci.toNumber() // throws: too large + * + * // Pass any to e.g. a Contract.call(), conversion happens automatically + * // regardless of the initial type. + * const scValU128 = sci.toU128(); + * const scValI256 = sci.toI256(); + * const scValU64 = sci.toU64(); + * + * // Lots of ways to initialize: + * ScInt("123456789123456789") + * ScInt(123456789123456789n); + * ScInt(1n << 140n); + * ScInt(-42); + * ScInt(scValToBigInt(scValU128)); // from above + * + * // If you know the type ahead of time (accessing `.raw` is faster than + * // conversions), you can specify the type directly (otherwise, it's + * // interpreted from the numbers you pass in): + * const i = ScInt(123456789n, { type: "u256" }); + * + * // For example, you can use the underlying `sdk.U256` and convert it to an + * // `xdr.ScVal` directly like so: + * const scv = new xdr.ScVal.scvU256(i.raw); + * + * // Or reinterpret it as a different type (size permitting): + * const scv = i.toI64(); + * + * @param {number|bigint|string} value - a single, integer-like value which will + * be interpreted in the smallest appropriate XDR type supported by Stellar + * (64, 128, or 256 bit integer values). signed values are supported, though + * they are sanity-checked against `opts.type`. if you need 32-bit values, + * you can construct them directly without needing this wrapper, e.g. + * `xdr.ScVal.scvU32(1234)`. + * + * @param {object} [opts] - an optional object controlling optional parameters + * @param {string} [opts.type] - force a specific data type. the type choices + * are: 'i64', 'u64', 'i128', 'u128', 'i256', and 'u256' (default: the + * smallest one that fits the `value`) + * + * @throws {RangeError} if the `value` is invalid (e.g. floating point), too + * large (i.e. exceeds a 256-bit value), or doesn't fit in the `opts.type` + * @throws {TypeError} on missing parameters, or if the "signedness" of `opts` + * doesn't match input `value`, e.g. passing `{type: 'u64'}` yet passing -1n + * @throws {SyntaxError} if a string `value` can't be parsed as a big integer + */ +var ScInt = exports.ScInt = /*#__PURE__*/function (_XdrLargeInt) { + function ScInt(value, opts) { + var _opts$type; + _classCallCheck(this, ScInt); + var signed = value < 0; + var type = (_opts$type = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type !== void 0 ? _opts$type : ''; + if (type.startsWith('u') && signed) { + throw TypeError("specified type ".concat(opts.type, " yet negative (").concat(value, ")")); + } + + // If unspecified, we make a best guess at the type based on the bit length + // of the value, treating 64 as a minimum and 256 as a maximum. + if (type === '') { + type = signed ? 'i' : 'u'; + var bitlen = nearestBigIntSize(value); + switch (bitlen) { + case 64: + case 128: + case 256: + type += bitlen.toString(); + break; + default: + throw RangeError("expected 64/128/256 bits for input (".concat(value, "), got ").concat(bitlen)); + } + } + return _callSuper(this, ScInt, [type, value]); + } + _inherits(ScInt, _XdrLargeInt); + return _createClass(ScInt); +}(_xdr_large_int.XdrLargeInt); +function nearestBigIntSize(bigI) { + var _find; + // Note: Even though BigInt.toString(2) includes the negative sign for + // negative values (???), the following is still accurate, because the + // negative sign would be represented by a sign bit. + var bitlen = bigI.toString(2).length; + return (_find = [64, 128, 256].find(function (len) { + return bitlen <= len; + })) !== null && _find !== void 0 ? _find : bitlen; +} + +/***/ }), + +/***/ 6272: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Uint128 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Uint128 = exports.Uint128 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct an unsigned 128-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Uint128() { + _classCallCheck(this, Uint128); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Uint128, [args]); + } + _inherits(Uint128, _LargeInt); + return _createClass(Uint128, [{ + key: "unsigned", + get: function get() { + return true; + } + }, { + key: "size", + get: function get() { + return 128; + } + }]); +}(_jsXdr.LargeInt); +Uint128.defineIntBoundaries(); + +/***/ }), + +/***/ 8672: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Uint256 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Uint256 = exports.Uint256 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct an unsigned 256-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Uint256() { + _classCallCheck(this, Uint256); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Uint256, [args]); + } + _inherits(Uint256, _LargeInt); + return _createClass(Uint256, [{ + key: "unsigned", + get: function get() { + return true; + } + }, { + key: "size", + get: function get() { + return 256; + } + }]); +}(_jsXdr.LargeInt); +Uint256.defineIntBoundaries(); + +/***/ }), + +/***/ 7429: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.XdrLargeInt = void 0; +var _jsXdr = __webpack_require__(3740); +var _uint = __webpack_require__(6272); +var _uint2 = __webpack_require__(8672); +var _int = __webpack_require__(5487); +var _int2 = __webpack_require__(4063); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": [">>"]}] */ +/** + * A wrapper class to represent large XDR-encodable integers. + * + * This operates at a lower level than {@link ScInt} by forcing you to specify + * the type / width / size in bits of the integer you're targeting, regardless + * of the input value(s) you provide. + * + * @param {string} type - force a specific data type. the type choices are: + * 'i64', 'u64', 'i128', 'u128', 'i256', and 'u256' (default: the smallest + * one that fits the `value`) (see {@link XdrLargeInt.isType}) + * @param {number|bigint|string|Array} values a list of + * integer-like values interpreted in big-endian order + */ +var XdrLargeInt = exports.XdrLargeInt = /*#__PURE__*/function () { + function XdrLargeInt(type, values) { + _classCallCheck(this, XdrLargeInt); + /** @type {xdr.LargeInt} */ + _defineProperty(this, "int", void 0); + // child class of a jsXdr.LargeInt + /** @type {string} */ + _defineProperty(this, "type", void 0); + if (!(values instanceof Array)) { + values = [values]; + } + + // normalize values to one type + values = values.map(function (i) { + // micro-optimization to no-op on the likeliest input value: + if (typeof i === 'bigint') { + return i; + } + if (i instanceof XdrLargeInt) { + return i.toBigInt(); + } + return BigInt(i); + }); + switch (type) { + case 'i64': + this["int"] = new _jsXdr.Hyper(values); + break; + case 'i128': + this["int"] = new _int.Int128(values); + break; + case 'i256': + this["int"] = new _int2.Int256(values); + break; + case 'u64': + this["int"] = new _jsXdr.UnsignedHyper(values); + break; + case 'u128': + this["int"] = new _uint.Uint128(values); + break; + case 'u256': + this["int"] = new _uint2.Uint256(values); + break; + default: + throw TypeError("invalid type: ".concat(type)); + } + this.type = type; + } + + /** + * @returns {number} + * @throws {RangeError} if the value can't fit into a Number + */ + return _createClass(XdrLargeInt, [{ + key: "toNumber", + value: function toNumber() { + var bi = this["int"].toBigInt(); + if (bi > Number.MAX_SAFE_INTEGER || bi < Number.MIN_SAFE_INTEGER) { + throw RangeError("value ".concat(bi, " not in range for Number ") + "[".concat(Number.MAX_SAFE_INTEGER, ", ").concat(Number.MIN_SAFE_INTEGER, "]")); + } + return Number(bi); + } + + /** @returns {bigint} */ + }, { + key: "toBigInt", + value: function toBigInt() { + return this["int"].toBigInt(); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = I64` */ + }, { + key: "toI64", + value: function toI64() { + this._sizeCheck(64); + var v = this.toBigInt(); + if (BigInt.asIntN(64, v) !== v) { + throw RangeError("value too large for i64: ".concat(v)); + } + return _xdr["default"].ScVal.scvI64(new _xdr["default"].Int64(v)); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = U64` */ + }, { + key: "toU64", + value: function toU64() { + this._sizeCheck(64); + return _xdr["default"].ScVal.scvU64(new _xdr["default"].Uint64(BigInt.asUintN(64, this.toBigInt())) // reiterpret as unsigned + ); + } + + /** + * @returns {xdr.ScVal} the integer encoded with `ScValType = I128` + * @throws {RangeError} if the value cannot fit in 128 bits + */ + }, { + key: "toI128", + value: function toI128() { + this._sizeCheck(128); + var v = this["int"].toBigInt(); + var hi64 = BigInt.asIntN(64, v >> 64n); // encode top 64 w/ sign bit + var lo64 = BigInt.asUintN(64, v); // grab btm 64, encode sign + + return _xdr["default"].ScVal.scvI128(new _xdr["default"].Int128Parts({ + hi: new _xdr["default"].Int64(hi64), + lo: new _xdr["default"].Uint64(lo64) + })); + } + + /** + * @returns {xdr.ScVal} the integer encoded with `ScValType = U128` + * @throws {RangeError} if the value cannot fit in 128 bits + */ + }, { + key: "toU128", + value: function toU128() { + this._sizeCheck(128); + var v = this["int"].toBigInt(); + return _xdr["default"].ScVal.scvU128(new _xdr["default"].UInt128Parts({ + hi: new _xdr["default"].Uint64(BigInt.asUintN(64, v >> 64n)), + lo: new _xdr["default"].Uint64(BigInt.asUintN(64, v)) + })); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = I256` */ + }, { + key: "toI256", + value: function toI256() { + var v = this["int"].toBigInt(); + var hiHi64 = BigInt.asIntN(64, v >> 192n); // keep sign bit + var hiLo64 = BigInt.asUintN(64, v >> 128n); + var loHi64 = BigInt.asUintN(64, v >> 64n); + var loLo64 = BigInt.asUintN(64, v); + return _xdr["default"].ScVal.scvI256(new _xdr["default"].Int256Parts({ + hiHi: new _xdr["default"].Int64(hiHi64), + hiLo: new _xdr["default"].Uint64(hiLo64), + loHi: new _xdr["default"].Uint64(loHi64), + loLo: new _xdr["default"].Uint64(loLo64) + })); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = U256` */ + }, { + key: "toU256", + value: function toU256() { + var v = this["int"].toBigInt(); + var hiHi64 = BigInt.asUintN(64, v >> 192n); // encode sign bit + var hiLo64 = BigInt.asUintN(64, v >> 128n); + var loHi64 = BigInt.asUintN(64, v >> 64n); + var loLo64 = BigInt.asUintN(64, v); + return _xdr["default"].ScVal.scvU256(new _xdr["default"].UInt256Parts({ + hiHi: new _xdr["default"].Uint64(hiHi64), + hiLo: new _xdr["default"].Uint64(hiLo64), + loHi: new _xdr["default"].Uint64(loHi64), + loLo: new _xdr["default"].Uint64(loLo64) + })); + } + + /** @returns {xdr.ScVal} the smallest interpretation of the stored value */ + }, { + key: "toScVal", + value: function toScVal() { + switch (this.type) { + case 'i64': + return this.toI64(); + case 'i128': + return this.toI128(); + case 'i256': + return this.toI256(); + case 'u64': + return this.toU64(); + case 'u128': + return this.toU128(); + case 'u256': + return this.toU256(); + default: + throw TypeError("invalid type: ".concat(this.type)); + } + } + }, { + key: "valueOf", + value: function valueOf() { + return this["int"].valueOf(); + } + }, { + key: "toString", + value: function toString() { + return this["int"].toString(); + } + }, { + key: "toJSON", + value: function toJSON() { + return { + value: this.toBigInt().toString(), + type: this.type + }; + } + }, { + key: "_sizeCheck", + value: function _sizeCheck(bits) { + if (this["int"].size > bits) { + throw RangeError("value too large for ".concat(bits, " bits (").concat(this.type, ")")); + } + } + }], [{ + key: "isType", + value: function isType(type) { + switch (type) { + case 'i64': + case 'i128': + case 'i256': + case 'u64': + case 'u128': + case 'u256': + return true; + default: + return false; + } + } + + /** + * Convert the raw `ScValType` string (e.g. 'scvI128', generated by the XDR) + * to a type description for {@link XdrLargeInt} construction (e.g. 'i128') + * + * @param {string} scvType the `xdr.ScValType` as a string + * @returns {string} a suitable equivalent type to construct this object + */ + }, { + key: "getType", + value: function getType(scvType) { + return scvType.slice(3).toLowerCase(); + } + }]); +}(); + +/***/ }), + +/***/ 7237: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Operation = exports.AuthRevocableFlag = exports.AuthRequiredFlag = exports.AuthImmutableFlag = exports.AuthClawbackEnabledFlag = void 0; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _util = __webpack_require__(645); +var _continued_fraction = __webpack_require__(4151); +var _asset = __webpack_require__(1764); +var _liquidity_pool_asset = __webpack_require__(2262); +var _claimant = __webpack_require__(1387); +var _strkey = __webpack_require__(7120); +var _liquidity_pool_id = __webpack_require__(9353); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var ops = _interopRequireWildcard(__webpack_require__(7511)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint-disable no-bitwise */ +var ONE = 10000000; +var MAX_INT64 = '9223372036854775807'; + +/** + * When set using `{@link Operation.setOptions}` option, requires the issuing + * account to give other accounts permission before they can hold the issuing + * account’s credit. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthRequiredFlag = exports.AuthRequiredFlag = 1 << 0; +/** + * When set using `{@link Operation.setOptions}` option, allows the issuing + * account to revoke its credit held by other accounts. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthRevocableFlag = exports.AuthRevocableFlag = 1 << 1; +/** + * When set using `{@link Operation.setOptions}` option, then none of the + * authorization flags can be set and the account can never be deleted. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthImmutableFlag = exports.AuthImmutableFlag = 1 << 2; + +/** + * When set using `{@link Operation.setOptions}` option, then any trustlines + * created by this account can have a ClawbackOp operation submitted for the + * corresponding asset. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthClawbackEnabledFlag = exports.AuthClawbackEnabledFlag = 1 << 3; + +/** + * `Operation` class represents + * [operations](https://developers.stellar.org/docs/glossary/operations/) in + * Stellar network. + * + * Use one of static methods to create operations: + * * `{@link Operation.createAccount}` + * * `{@link Operation.payment}` + * * `{@link Operation.pathPaymentStrictReceive}` + * * `{@link Operation.pathPaymentStrictSend}` + * * `{@link Operation.manageSellOffer}` + * * `{@link Operation.manageBuyOffer}` + * * `{@link Operation.createPassiveSellOffer}` + * * `{@link Operation.setOptions}` + * * `{@link Operation.changeTrust}` + * * `{@link Operation.allowTrust}` + * * `{@link Operation.accountMerge}` + * * `{@link Operation.inflation}` + * * `{@link Operation.manageData}` + * * `{@link Operation.bumpSequence}` + * * `{@link Operation.createClaimableBalance}` + * * `{@link Operation.claimClaimableBalance}` + * * `{@link Operation.beginSponsoringFutureReserves}` + * * `{@link Operation.endSponsoringFutureReserves}` + * * `{@link Operation.revokeAccountSponsorship}` + * * `{@link Operation.revokeTrustlineSponsorship}` + * * `{@link Operation.revokeOfferSponsorship}` + * * `{@link Operation.revokeDataSponsorship}` + * * `{@link Operation.revokeClaimableBalanceSponsorship}` + * * `{@link Operation.revokeLiquidityPoolSponsorship}` + * * `{@link Operation.revokeSignerSponsorship}` + * * `{@link Operation.clawback}` + * * `{@link Operation.clawbackClaimableBalance}` + * * `{@link Operation.setTrustLineFlags}` + * * `{@link Operation.liquidityPoolDeposit}` + * * `{@link Operation.liquidityPoolWithdraw}` + * * `{@link Operation.invokeHostFunction}`, which has the following additional + * "pseudo-operations" that make building host functions easier: + * - `{@link Operation.createStellarAssetContract}` + * - `{@link Operation.invokeContractFunction}` + * - `{@link Operation.createCustomContract}` + * - `{@link Operation.uploadContractWasm}` + * * `{@link Operation.extendFootprintTtlOp}` + * * `{@link Operation.restoreFootprint}` + * + * @class Operation + */ +var Operation = exports.Operation = /*#__PURE__*/function () { + function Operation() { + _classCallCheck(this, Operation); + } + return _createClass(Operation, null, [{ + key: "setSourceAccount", + value: function setSourceAccount(opAttributes, opts) { + if (opts.source) { + try { + opAttributes.sourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.source); + } catch (e) { + throw new Error('Source address is invalid'); + } + } + } + + /** + * Deconstructs the raw XDR operation object into the structured object that + * was used to create the operation (i.e. the `opts` parameter to most ops). + * + * @param {xdr.Operation} operation - An XDR Operation. + * @return {Operation} + */ + }, { + key: "fromXDRObject", + value: function fromXDRObject(operation) { + var result = {}; + if (operation.sourceAccount()) { + result.source = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(operation.sourceAccount()); + } + var attrs = operation.body().value(); + var operationName = operation.body()["switch"]().name; + switch (operationName) { + case 'createAccount': + { + result.type = 'createAccount'; + result.destination = accountIdtoAddress(attrs.destination()); + result.startingBalance = this._fromXDRAmount(attrs.startingBalance()); + break; + } + case 'payment': + { + result.type = 'payment'; + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.amount = this._fromXDRAmount(attrs.amount()); + break; + } + case 'pathPaymentStrictReceive': + { + result.type = 'pathPaymentStrictReceive'; + result.sendAsset = _asset.Asset.fromOperation(attrs.sendAsset()); + result.sendMax = this._fromXDRAmount(attrs.sendMax()); + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.destAsset = _asset.Asset.fromOperation(attrs.destAsset()); + result.destAmount = this._fromXDRAmount(attrs.destAmount()); + result.path = []; + var path = attrs.path(); + + // note that Object.values isn't supported by node 6! + Object.keys(path).forEach(function (pathKey) { + result.path.push(_asset.Asset.fromOperation(path[pathKey])); + }); + break; + } + case 'pathPaymentStrictSend': + { + result.type = 'pathPaymentStrictSend'; + result.sendAsset = _asset.Asset.fromOperation(attrs.sendAsset()); + result.sendAmount = this._fromXDRAmount(attrs.sendAmount()); + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.destAsset = _asset.Asset.fromOperation(attrs.destAsset()); + result.destMin = this._fromXDRAmount(attrs.destMin()); + result.path = []; + var _path = attrs.path(); + + // note that Object.values isn't supported by node 6! + Object.keys(_path).forEach(function (pathKey) { + result.path.push(_asset.Asset.fromOperation(_path[pathKey])); + }); + break; + } + case 'changeTrust': + { + result.type = 'changeTrust'; + switch (attrs.line()["switch"]()) { + case _xdr["default"].AssetType.assetTypePoolShare(): + result.line = _liquidity_pool_asset.LiquidityPoolAsset.fromOperation(attrs.line()); + break; + default: + result.line = _asset.Asset.fromOperation(attrs.line()); + break; + } + result.limit = this._fromXDRAmount(attrs.limit()); + break; + } + case 'allowTrust': + { + result.type = 'allowTrust'; + result.trustor = accountIdtoAddress(attrs.trustor()); + result.assetCode = attrs.asset().value().toString(); + result.assetCode = (0, _util.trimEnd)(result.assetCode, '\0'); + result.authorize = attrs.authorize(); + break; + } + case 'setOptions': + { + result.type = 'setOptions'; + if (attrs.inflationDest()) { + result.inflationDest = accountIdtoAddress(attrs.inflationDest()); + } + result.clearFlags = attrs.clearFlags(); + result.setFlags = attrs.setFlags(); + result.masterWeight = attrs.masterWeight(); + result.lowThreshold = attrs.lowThreshold(); + result.medThreshold = attrs.medThreshold(); + result.highThreshold = attrs.highThreshold(); + // home_domain is checked by iscntrl in stellar-core + result.homeDomain = attrs.homeDomain() !== undefined ? attrs.homeDomain().toString('ascii') : undefined; + if (attrs.signer()) { + var signer = {}; + var arm = attrs.signer().key().arm(); + if (arm === 'ed25519') { + signer.ed25519PublicKey = accountIdtoAddress(attrs.signer().key()); + } else if (arm === 'preAuthTx') { + signer.preAuthTx = attrs.signer().key().preAuthTx(); + } else if (arm === 'hashX') { + signer.sha256Hash = attrs.signer().key().hashX(); + } else if (arm === 'ed25519SignedPayload') { + var signedPayload = attrs.signer().key().ed25519SignedPayload(); + signer.ed25519SignedPayload = _strkey.StrKey.encodeSignedPayload(signedPayload.toXDR()); + } + signer.weight = attrs.signer().weight(); + result.signer = signer; + } + break; + } + // the next case intentionally falls through! + case 'manageOffer': + case 'manageSellOffer': + { + result.type = 'manageSellOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.price = this._fromXDRPrice(attrs.price()); + result.offerId = attrs.offerId().toString(); + break; + } + case 'manageBuyOffer': + { + result.type = 'manageBuyOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.buyAmount = this._fromXDRAmount(attrs.buyAmount()); + result.price = this._fromXDRPrice(attrs.price()); + result.offerId = attrs.offerId().toString(); + break; + } + // the next case intentionally falls through! + case 'createPassiveOffer': + case 'createPassiveSellOffer': + { + result.type = 'createPassiveSellOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.price = this._fromXDRPrice(attrs.price()); + break; + } + case 'accountMerge': + { + result.type = 'accountMerge'; + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs); + break; + } + case 'manageData': + { + result.type = 'manageData'; + // manage_data.name is checked by iscntrl in stellar-core + result.name = attrs.dataName().toString('ascii'); + result.value = attrs.dataValue(); + break; + } + case 'inflation': + { + result.type = 'inflation'; + break; + } + case 'bumpSequence': + { + result.type = 'bumpSequence'; + result.bumpTo = attrs.bumpTo().toString(); + break; + } + case 'createClaimableBalance': + { + result.type = 'createClaimableBalance'; + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.claimants = []; + attrs.claimants().forEach(function (claimant) { + result.claimants.push(_claimant.Claimant.fromXDR(claimant)); + }); + break; + } + case 'claimClaimableBalance': + { + result.type = 'claimClaimableBalance'; + result.balanceId = attrs.toXDR('hex'); + break; + } + case 'beginSponsoringFutureReserves': + { + result.type = 'beginSponsoringFutureReserves'; + result.sponsoredId = accountIdtoAddress(attrs.sponsoredId()); + break; + } + case 'endSponsoringFutureReserves': + { + result.type = 'endSponsoringFutureReserves'; + break; + } + case 'revokeSponsorship': + { + extractRevokeSponshipDetails(attrs, result); + break; + } + case 'clawback': + { + result.type = 'clawback'; + result.amount = this._fromXDRAmount(attrs.amount()); + result.from = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.from()); + result.asset = _asset.Asset.fromOperation(attrs.asset()); + break; + } + case 'clawbackClaimableBalance': + { + result.type = 'clawbackClaimableBalance'; + result.balanceId = attrs.toXDR('hex'); + break; + } + case 'setTrustLineFlags': + { + result.type = 'setTrustLineFlags'; + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.trustor = accountIdtoAddress(attrs.trustor()); + + // Convert from the integer-bitwised flag into a sensible object that + // indicates true/false for each flag that's on/off. + var clears = attrs.clearFlags(); + var sets = attrs.setFlags(); + var mapping = { + authorized: _xdr["default"].TrustLineFlags.authorizedFlag(), + authorizedToMaintainLiabilities: _xdr["default"].TrustLineFlags.authorizedToMaintainLiabilitiesFlag(), + clawbackEnabled: _xdr["default"].TrustLineFlags.trustlineClawbackEnabledFlag() + }; + var getFlagValue = function getFlagValue(key) { + var bit = mapping[key].value; + if (sets & bit) { + return true; + } + if (clears & bit) { + return false; + } + return undefined; + }; + result.flags = {}; + Object.keys(mapping).forEach(function (flagName) { + result.flags[flagName] = getFlagValue(flagName); + }); + break; + } + case 'liquidityPoolDeposit': + { + result.type = 'liquidityPoolDeposit'; + result.liquidityPoolId = attrs.liquidityPoolId().toString('hex'); + result.maxAmountA = this._fromXDRAmount(attrs.maxAmountA()); + result.maxAmountB = this._fromXDRAmount(attrs.maxAmountB()); + result.minPrice = this._fromXDRPrice(attrs.minPrice()); + result.maxPrice = this._fromXDRPrice(attrs.maxPrice()); + break; + } + case 'liquidityPoolWithdraw': + { + result.type = 'liquidityPoolWithdraw'; + result.liquidityPoolId = attrs.liquidityPoolId().toString('hex'); + result.amount = this._fromXDRAmount(attrs.amount()); + result.minAmountA = this._fromXDRAmount(attrs.minAmountA()); + result.minAmountB = this._fromXDRAmount(attrs.minAmountB()); + break; + } + case 'invokeHostFunction': + { + var _attrs$auth; + result.type = 'invokeHostFunction'; + result.func = attrs.hostFunction(); + result.auth = (_attrs$auth = attrs.auth()) !== null && _attrs$auth !== void 0 ? _attrs$auth : []; + break; + } + case 'extendFootprintTtl': + { + result.type = 'extendFootprintTtl'; + result.extendTo = attrs.extendTo(); + break; + } + case 'restoreFootprint': + { + result.type = 'restoreFootprint'; + break; + } + default: + { + throw new Error("Unknown operation: ".concat(operationName)); + } + } + return result; + } + + /** + * Validates that a given amount is possible for a Stellar asset. + * + * Specifically, this means that the amount is well, a valid number, but also + * that it is within the int64 range and has no more than 7 decimal levels of + * precision. + * + * Note that while smart contracts allow larger amounts, this is oriented + * towards validating the standard Stellar operations. + * + * @param {string} value the amount to validate + * @param {boolean} allowZero optionally, whether or not zero is valid (default: no) + * + * @returns {boolean} + */ + }, { + key: "isValidAmount", + value: function isValidAmount(value) { + var allowZero = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (typeof value !== 'string') { + return false; + } + var amount; + try { + amount = new _bignumber["default"](value); + } catch (e) { + return false; + } + if ( + // == 0 + !allowZero && amount.isZero() || + // < 0 + amount.isNegative() || + // > Max value + amount.times(ONE).gt(new _bignumber["default"](MAX_INT64).toString()) || + // Decimal places (max 7) + amount.decimalPlaces() > 7 || + // NaN or Infinity + amount.isNaN() || !amount.isFinite()) { + return false; + } + return true; + } + }, { + key: "constructAmountRequirementsError", + value: function constructAmountRequirementsError(arg) { + return "".concat(arg, " argument must be of type String, represent a positive number and have at most 7 digits after the decimal"); + } + + /** + * Returns value converted to uint32 value or undefined. + * If `value` is not `Number`, `String` or `Undefined` then throws an error. + * Used in {@link Operation.setOptions}. + * @private + * @param {string} name Name of the property (used in error message only) + * @param {*} value Value to check + * @param {function(value, name)} isValidFunction Function to check other constraints (the argument will be a `Number`) + * @returns {undefined|Number} + */ + }, { + key: "_checkUnsignedIntValue", + value: function _checkUnsignedIntValue(name, value) { + var isValidFunction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + if (typeof value === 'undefined') { + return undefined; + } + if (typeof value === 'string') { + value = parseFloat(value); + } + switch (true) { + case typeof value !== 'number' || !Number.isFinite(value) || value % 1 !== 0: + throw new Error("".concat(name, " value is invalid")); + case value < 0: + throw new Error("".concat(name, " value must be unsigned")); + case !isValidFunction || isValidFunction && isValidFunction(value, name): + return value; + default: + throw new Error("".concat(name, " value is invalid")); + } + } + /** + * @private + * @param {string|BigNumber} value Value + * @returns {Hyper} XDR amount + */ + }, { + key: "_toXDRAmount", + value: function _toXDRAmount(value) { + var amount = new _bignumber["default"](value).times(ONE); + return _jsXdr.Hyper.fromString(amount.toString()); + } + + /** + * @private + * @param {string|BigNumber} value XDR amount + * @returns {BigNumber} Number + */ + }, { + key: "_fromXDRAmount", + value: function _fromXDRAmount(value) { + return new _bignumber["default"](value).div(ONE).toFixed(7); + } + + /** + * @private + * @param {object} price Price object + * @param {function} price.n numerator function that returns a value + * @param {function} price.d denominator function that returns a value + * @returns {BigNumber} Big string + */ + }, { + key: "_fromXDRPrice", + value: function _fromXDRPrice(price) { + var n = new _bignumber["default"](price.n()); + return n.div(new _bignumber["default"](price.d())).toString(); + } + + /** + * @private + * @param {object} price Price object + * @param {function} price.n numerator function that returns a value + * @param {function} price.d denominator function that returns a value + * @returns {object} XDR price object + */ + }, { + key: "_toXDRPrice", + value: function _toXDRPrice(price) { + var xdrObject; + if (price.n && price.d) { + xdrObject = new _xdr["default"].Price(price); + } else { + var approx = (0, _continued_fraction.best_r)(price); + xdrObject = new _xdr["default"].Price({ + n: parseInt(approx[0], 10), + d: parseInt(approx[1], 10) + }); + } + if (xdrObject.n() < 0 || xdrObject.d() < 0) { + throw new Error('price must be positive'); + } + return xdrObject; + } + }]); +}(); +function extractRevokeSponshipDetails(attrs, result) { + switch (attrs["switch"]().name) { + case 'revokeSponsorshipLedgerEntry': + { + var ledgerKey = attrs.ledgerKey(); + switch (ledgerKey["switch"]().name) { + case _xdr["default"].LedgerEntryType.account().name: + { + result.type = 'revokeAccountSponsorship'; + result.account = accountIdtoAddress(ledgerKey.account().accountId()); + break; + } + case _xdr["default"].LedgerEntryType.trustline().name: + { + result.type = 'revokeTrustlineSponsorship'; + result.account = accountIdtoAddress(ledgerKey.trustLine().accountId()); + var xdrAsset = ledgerKey.trustLine().asset(); + switch (xdrAsset["switch"]()) { + case _xdr["default"].AssetType.assetTypePoolShare(): + result.asset = _liquidity_pool_id.LiquidityPoolId.fromOperation(xdrAsset); + break; + default: + result.asset = _asset.Asset.fromOperation(xdrAsset); + break; + } + break; + } + case _xdr["default"].LedgerEntryType.offer().name: + { + result.type = 'revokeOfferSponsorship'; + result.seller = accountIdtoAddress(ledgerKey.offer().sellerId()); + result.offerId = ledgerKey.offer().offerId().toString(); + break; + } + case _xdr["default"].LedgerEntryType.data().name: + { + result.type = 'revokeDataSponsorship'; + result.account = accountIdtoAddress(ledgerKey.data().accountId()); + result.name = ledgerKey.data().dataName().toString('ascii'); + break; + } + case _xdr["default"].LedgerEntryType.claimableBalance().name: + { + result.type = 'revokeClaimableBalanceSponsorship'; + result.balanceId = ledgerKey.claimableBalance().balanceId().toXDR('hex'); + break; + } + case _xdr["default"].LedgerEntryType.liquidityPool().name: + { + result.type = 'revokeLiquidityPoolSponsorship'; + result.liquidityPoolId = ledgerKey.liquidityPool().liquidityPoolId().toString('hex'); + break; + } + default: + { + throw new Error("Unknown ledgerKey: ".concat(attrs["switch"]().name)); + } + } + break; + } + case 'revokeSponsorshipSigner': + { + result.type = 'revokeSignerSponsorship'; + result.account = accountIdtoAddress(attrs.signer().accountId()); + result.signer = convertXDRSignerKeyToObject(attrs.signer().signerKey()); + break; + } + default: + { + throw new Error("Unknown revokeSponsorship: ".concat(attrs["switch"]().name)); + } + } +} +function convertXDRSignerKeyToObject(signerKey) { + var attrs = {}; + switch (signerKey["switch"]().name) { + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519().name: + { + attrs.ed25519PublicKey = _strkey.StrKey.encodeEd25519PublicKey(signerKey.ed25519()); + break; + } + case _xdr["default"].SignerKeyType.signerKeyTypePreAuthTx().name: + { + attrs.preAuthTx = signerKey.preAuthTx().toString('hex'); + break; + } + case _xdr["default"].SignerKeyType.signerKeyTypeHashX().name: + { + attrs.sha256Hash = signerKey.hashX().toString('hex'); + break; + } + default: + { + throw new Error("Unknown signerKey: ".concat(signerKey["switch"]().name)); + } + } + return attrs; +} +function accountIdtoAddress(accountId) { + return _strkey.StrKey.encodeEd25519PublicKey(accountId.ed25519()); +} + +// Attach all imported operations as static methods on the Operation class +Operation.accountMerge = ops.accountMerge; +Operation.allowTrust = ops.allowTrust; +Operation.bumpSequence = ops.bumpSequence; +Operation.changeTrust = ops.changeTrust; +Operation.createAccount = ops.createAccount; +Operation.createClaimableBalance = ops.createClaimableBalance; +Operation.claimClaimableBalance = ops.claimClaimableBalance; +Operation.clawbackClaimableBalance = ops.clawbackClaimableBalance; +Operation.createPassiveSellOffer = ops.createPassiveSellOffer; +Operation.inflation = ops.inflation; +Operation.manageData = ops.manageData; +Operation.manageSellOffer = ops.manageSellOffer; +Operation.manageBuyOffer = ops.manageBuyOffer; +Operation.pathPaymentStrictReceive = ops.pathPaymentStrictReceive; +Operation.pathPaymentStrictSend = ops.pathPaymentStrictSend; +Operation.payment = ops.payment; +Operation.setOptions = ops.setOptions; +Operation.beginSponsoringFutureReserves = ops.beginSponsoringFutureReserves; +Operation.endSponsoringFutureReserves = ops.endSponsoringFutureReserves; +Operation.revokeAccountSponsorship = ops.revokeAccountSponsorship; +Operation.revokeTrustlineSponsorship = ops.revokeTrustlineSponsorship; +Operation.revokeOfferSponsorship = ops.revokeOfferSponsorship; +Operation.revokeDataSponsorship = ops.revokeDataSponsorship; +Operation.revokeClaimableBalanceSponsorship = ops.revokeClaimableBalanceSponsorship; +Operation.revokeLiquidityPoolSponsorship = ops.revokeLiquidityPoolSponsorship; +Operation.revokeSignerSponsorship = ops.revokeSignerSponsorship; +Operation.clawback = ops.clawback; +Operation.setTrustLineFlags = ops.setTrustLineFlags; +Operation.liquidityPoolDeposit = ops.liquidityPoolDeposit; +Operation.liquidityPoolWithdraw = ops.liquidityPoolWithdraw; +Operation.invokeHostFunction = ops.invokeHostFunction; +Operation.extendFootprintTtl = ops.extendFootprintTtl; +Operation.restoreFootprint = ops.restoreFootprint; + +// these are not `xdr.Operation`s directly, but are proxies for complex but +// common versions of `Operation.invokeHostFunction` +Operation.createStellarAssetContract = ops.createStellarAssetContract; +Operation.invokeContractFunction = ops.invokeContractFunction; +Operation.createCustomContract = ops.createCustomContract; +Operation.uploadContractWasm = ops.uploadContractWasm; + +/***/ }), + +/***/ 4295: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.accountMerge = accountMerge; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Transfers native balance to destination account. + * + * @function + * @alias Operation.accountMerge + * + * @param {object} opts - options object + * @param {string} opts.destination - destination to merge the source account into + * @param {string} [opts.source] - operation source account (defaults to + * transaction source) + * + * @returns {xdr.Operation} an Account Merge operation (xdr.AccountMergeOp) + */ +function accountMerge(opts) { + var opAttributes = {}; + try { + opAttributes.body = _xdr["default"].OperationBody.accountMerge((0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination)); + } catch (e) { + throw new Error('destination is invalid'); + } + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 3683: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.allowTrust = allowTrust; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * @deprecated since v5.0 + * + * Returns an XDR AllowTrustOp. An "allow trust" operation authorizes another + * account to hold your account's credit for a given asset. + * + * @function + * @alias Operation.allowTrust + * + * @param {object} opts Options object + * @param {string} opts.trustor - The trusting account (the one being authorized) + * @param {string} opts.assetCode - The asset code being authorized. + * @param {(0|1|2)} opts.authorize - `1` to authorize, `2` to authorize to maintain liabilities, and `0` to deauthorize. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * + * @returns {xdr.AllowTrustOp} Allow Trust operation + */ +function allowTrust(opts) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.trustor)) { + throw new Error('trustor is invalid'); + } + var attributes = {}; + attributes.trustor = _keypair.Keypair.fromPublicKey(opts.trustor).xdrAccountId(); + if (opts.assetCode.length <= 4) { + var code = opts.assetCode.padEnd(4, '\0'); + attributes.asset = _xdr["default"].AssetCode.assetTypeCreditAlphanum4(code); + } else if (opts.assetCode.length <= 12) { + var _code = opts.assetCode.padEnd(12, '\0'); + attributes.asset = _xdr["default"].AssetCode.assetTypeCreditAlphanum12(_code); + } else { + throw new Error('Asset code must be 12 characters at max.'); + } + if (typeof opts.authorize === 'boolean') { + if (opts.authorize) { + attributes.authorize = _xdr["default"].TrustLineFlags.authorizedFlag().value; + } else { + attributes.authorize = 0; + } + } else { + attributes.authorize = opts.authorize; + } + var allowTrustOp = new _xdr["default"].AllowTrustOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.allowTrust(allowTrustOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7505: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.beginSponsoringFutureReserves = beginSponsoringFutureReserves; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +var _keypair = __webpack_require__(6691); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a "begin sponsoring future reserves" operation. + * @function + * @alias Operation.beginSponsoringFutureReserves + * @param {object} opts Options object + * @param {string} opts.sponsoredId - The sponsored account id. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.beginSponsoringFutureReserves({ + * sponsoredId: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * }); + * + */ +function beginSponsoringFutureReserves() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.sponsoredId)) { + throw new Error('sponsoredId is invalid'); + } + var op = new _xdr["default"].BeginSponsoringFutureReservesOp({ + sponsoredId: _keypair.Keypair.fromPublicKey(opts.sponsoredId).xdrAccountId() + }); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.beginSponsoringFutureReserves(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 6183: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.bumpSequence = bumpSequence; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation bumps sequence number. + * @function + * @alias Operation.bumpSequence + * @param {object} opts Options object + * @param {string} opts.bumpTo - Sequence number to bump to. + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.BumpSequenceOp} Operation + */ +function bumpSequence(opts) { + var attributes = {}; + if (typeof opts.bumpTo !== 'string') { + throw new Error('bumpTo must be a string'); + } + try { + // eslint-disable-next-line no-new + new _bignumber["default"](opts.bumpTo); + } catch (e) { + throw new Error('bumpTo must be a stringified number'); + } + attributes.bumpTo = _jsXdr.Hyper.fromString(opts.bumpTo); + var bumpSequenceOp = new _xdr["default"].BumpSequenceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.bumpSequence(bumpSequenceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2810: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.changeTrust = changeTrust; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +var _liquidity_pool_asset = __webpack_require__(2262); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var MAX_INT64 = '9223372036854775807'; + +/** + * Returns an XDR ChangeTrustOp. A "change trust" operation adds, removes, or updates a + * trust line for a given asset from the source account to another. + * @function + * @alias Operation.changeTrust + * @param {object} opts Options object + * @param {Asset | LiquidityPoolAsset} opts.asset - The asset for the trust line. + * @param {string} [opts.limit] - The limit for the asset, defaults to max int64. + * If the limit is set to "0" it deletes the trustline. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @returns {xdr.ChangeTrustOp} Change Trust operation + */ +function changeTrust(opts) { + var attributes = {}; + if (opts.asset instanceof _asset.Asset) { + attributes.line = opts.asset.toChangeTrustXDRObject(); + } else if (opts.asset instanceof _liquidity_pool_asset.LiquidityPoolAsset) { + attributes.line = opts.asset.toXDRObject(); + } else { + throw new TypeError('asset must be Asset or LiquidityPoolAsset'); + } + if (opts.limit !== undefined && !this.isValidAmount(opts.limit, true)) { + throw new TypeError(this.constructAmountRequirementsError('limit')); + } + if (opts.limit) { + attributes.limit = this._toXDRAmount(opts.limit); + } else { + attributes.limit = _jsXdr.Hyper.fromString(new _bignumber["default"](MAX_INT64).toString()); + } + if (opts.source) { + attributes.source = opts.source.masterKeypair; + } + var changeTrustOP = new _xdr["default"].ChangeTrustOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.changeTrust(changeTrustOP); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7239: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.claimClaimableBalance = claimClaimableBalance; +exports.validateClaimableBalanceId = validateClaimableBalanceId; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a new claim claimable balance operation. + * @function + * @alias Operation.claimClaimableBalance + * @param {object} opts Options object + * @param {string} opts.balanceId - The claimable balance id to be claimed. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} Claim claimable balance operation + * + * @example + * const op = Operation.claimClaimableBalance({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + */ +function claimClaimableBalance() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + validateClaimableBalanceId(opts.balanceId); + var attributes = {}; + attributes.balanceId = _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex'); + var claimClaimableBalanceOp = new _xdr["default"].ClaimClaimableBalanceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.claimClaimableBalance(claimClaimableBalanceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} +function validateClaimableBalanceId(balanceId) { + if (typeof balanceId !== 'string' || balanceId.length !== 8 + 64 /* 8b discriminant + 64b string */) { + throw new Error('must provide a valid claimable balance id'); + } +} + +/***/ }), + +/***/ 7651: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.clawback = clawback; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a clawback operation. + * + * @function + * @alias Operation.clawback + * + * @param {object} opts - Options object + * @param {Asset} opts.asset - The asset being clawed back. + * @param {string} opts.amount - The amount of the asset to claw back. + * @param {string} opts.from - The public key of the (optionally-muxed) + * account to claw back from. + * + * @param {string} [opts.source] - The source account for the operation. + * Defaults to the transaction's source account. + * + * @return {xdr.ClawbackOp} + * + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#clawback-operation + */ +function clawback(opts) { + var attributes = {}; + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + attributes.asset = opts.asset.toXDRObject(); + try { + attributes.from = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.from); + } catch (e) { + throw new Error('from address is invalid'); + } + var opAttributes = { + body: _xdr["default"].OperationBody.clawback(new _xdr["default"].ClawbackOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2203: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.clawbackClaimableBalance = clawbackClaimableBalance; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _claim_claimable_balance = __webpack_require__(7239); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a clawback operation for a claimable balance. + * + * @function + * @alias Operation.clawbackClaimableBalance + * @param {object} opts - Options object + * @param {string} opts.balanceId - The claimable balance ID to be clawed back. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @return {xdr.ClawbackClaimableBalanceOp} + * + * @example + * const op = Operation.clawbackClaimableBalance({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + * @link https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#clawback-claimable-balance-operation + */ +function clawbackClaimableBalance() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + (0, _claim_claimable_balance.validateClaimableBalanceId)(opts.balanceId); + var attributes = { + balanceId: _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex') + }; + var opAttributes = { + body: _xdr["default"].OperationBody.clawbackClaimableBalance(new _xdr["default"].ClawbackClaimableBalanceOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2115: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createAccount = createAccount; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create and fund a non existent account. + * @function + * @alias Operation.createAccount + * @param {object} opts Options object + * @param {string} opts.destination - Destination account ID to create an account for. + * @param {string} opts.startingBalance - Amount in XLM the account should be funded for. Must be greater + * than the [reserve balance amount](https://developers.stellar.org/docs/glossary/fees/). + * @param {string} [opts.source] - The source account for the payment. Defaults to the transaction's source account. + * @returns {xdr.CreateAccountOp} Create account operation + */ +function createAccount(opts) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.destination)) { + throw new Error('destination is invalid'); + } + if (!this.isValidAmount(opts.startingBalance, true)) { + throw new TypeError(this.constructAmountRequirementsError('startingBalance')); + } + var attributes = {}; + attributes.destination = _keypair.Keypair.fromPublicKey(opts.destination).xdrAccountId(); + attributes.startingBalance = this._toXDRAmount(opts.startingBalance); + var createAccountOp = new _xdr["default"].CreateAccountOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createAccount(createAccountOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 4831: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createClaimableBalance = createClaimableBalance; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a new claimable balance operation. + * + * @function + * @alias Operation.createClaimableBalance + * + * @param {object} opts Options object + * @param {Asset} opts.asset - The asset for the claimable balance. + * @param {string} opts.amount - Amount. + * @param {Claimant[]} opts.claimants - An array of Claimants + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} Create claimable balance operation + * + * @example + * const asset = new Asset( + * 'USD', + * 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * ); + * const amount = '100.0000000'; + * const claimants = [ + * new Claimant( + * 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ', + * Claimant.predicateBeforeAbsoluteTime("4102444800000") + * ) + * ]; + * + * const op = Operation.createClaimableBalance({ + * asset, + * amount, + * claimants + * }); + * + */ +function createClaimableBalance(opts) { + if (!(opts.asset instanceof _asset.Asset)) { + throw new Error('must provide an asset for create claimable balance operation'); + } + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + if (!Array.isArray(opts.claimants) || opts.claimants.length === 0) { + throw new Error('must provide at least one claimant'); + } + var attributes = {}; + attributes.asset = opts.asset.toXDRObject(); + attributes.amount = this._toXDRAmount(opts.amount); + attributes.claimants = Object.values(opts.claimants).map(function (c) { + return c.toXDRObject(); + }); + var createClaimableBalanceOp = new _xdr["default"].CreateClaimableBalanceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createClaimableBalance(createClaimableBalanceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 9073: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createPassiveSellOffer = createPassiveSellOffer; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR CreatePasiveSellOfferOp. A "create passive offer" operation creates an + * offer that won't consume a counter offer that exactly matches this offer. This is + * useful for offers just used as 1:1 exchanges for path payments. Use manage offer + * to manage this offer after using this operation to create it. + * @function + * @alias Operation.createPassiveSellOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.CreatePassiveSellOfferOp} Create Passive Sell Offer operation + */ +function createPassiveSellOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + var createPassiveSellOfferOp = new _xdr["default"].CreatePassiveSellOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createPassiveSellOffer(createPassiveSellOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 721: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.endSponsoringFutureReserves = endSponsoringFutureReserves; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create an "end sponsoring future reserves" operation. + * @function + * @alias Operation.endSponsoringFutureReserves + * @param {object} opts Options object + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.endSponsoringFutureReserves(); + * + */ +function endSponsoringFutureReserves() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.endSponsoringFutureReserves(); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 8752: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.extendFootprintTtl = extendFootprintTtl; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Builds an operation to bump the time-to-live (TTL) of the ledger keys. The + * keys for extension have to be provided in the read-only footprint of + * the transaction. + * + * The only parameter of the operation itself is the new minimum TTL for + * all the provided entries. If an entry already has a higher TTL, then it + * will just be skipped. + * + * TTL is the number of ledgers from the current ledger (exclusive) until + * the last ledger the entry is still considered alive (inclusive). Thus + * the exact ledger until the entries will live will only be determined + * when transaction has been applied. + * + * The footprint has to be specified in the transaction. See + * {@link TransactionBuilder}'s `opts.sorobanData` parameter, which is a + * {@link xdr.SorobanTransactionData} instance that contains fee data & resource + * usage as part of {@link xdr.SorobanResources}. + * + * @function + * @alias Operation.extendFootprintTtl + * + * @param {object} opts - object holding operation parameters + * @param {number} opts.extendTo - the minimum TTL that all the entries in + * the read-only footprint will have + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Extend Footprint TTL operation + * (xdr.ExtendFootprintTTLOp) + */ +function extendFootprintTtl(opts) { + var _opts$extendTo; + if (((_opts$extendTo = opts.extendTo) !== null && _opts$extendTo !== void 0 ? _opts$extendTo : -1) <= 0) { + throw new RangeError('extendTo has to be positive'); + } + var extendFootprintOp = new _xdr["default"].ExtendFootprintTtlOp({ + ext: new _xdr["default"].ExtensionPoint(0), + extendTo: opts.extendTo + }); + var opAttributes = { + body: _xdr["default"].OperationBody.extendFootprintTtl(extendFootprintOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7511: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "accountMerge", ({ + enumerable: true, + get: function get() { + return _account_merge.accountMerge; + } +})); +Object.defineProperty(exports, "allowTrust", ({ + enumerable: true, + get: function get() { + return _allow_trust.allowTrust; + } +})); +Object.defineProperty(exports, "beginSponsoringFutureReserves", ({ + enumerable: true, + get: function get() { + return _begin_sponsoring_future_reserves.beginSponsoringFutureReserves; + } +})); +Object.defineProperty(exports, "bumpSequence", ({ + enumerable: true, + get: function get() { + return _bump_sequence.bumpSequence; + } +})); +Object.defineProperty(exports, "changeTrust", ({ + enumerable: true, + get: function get() { + return _change_trust.changeTrust; + } +})); +Object.defineProperty(exports, "claimClaimableBalance", ({ + enumerable: true, + get: function get() { + return _claim_claimable_balance.claimClaimableBalance; + } +})); +Object.defineProperty(exports, "clawback", ({ + enumerable: true, + get: function get() { + return _clawback.clawback; + } +})); +Object.defineProperty(exports, "clawbackClaimableBalance", ({ + enumerable: true, + get: function get() { + return _clawback_claimable_balance.clawbackClaimableBalance; + } +})); +Object.defineProperty(exports, "createAccount", ({ + enumerable: true, + get: function get() { + return _create_account.createAccount; + } +})); +Object.defineProperty(exports, "createClaimableBalance", ({ + enumerable: true, + get: function get() { + return _create_claimable_balance.createClaimableBalance; + } +})); +Object.defineProperty(exports, "createCustomContract", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.createCustomContract; + } +})); +Object.defineProperty(exports, "createPassiveSellOffer", ({ + enumerable: true, + get: function get() { + return _create_passive_sell_offer.createPassiveSellOffer; + } +})); +Object.defineProperty(exports, "createStellarAssetContract", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.createStellarAssetContract; + } +})); +Object.defineProperty(exports, "endSponsoringFutureReserves", ({ + enumerable: true, + get: function get() { + return _end_sponsoring_future_reserves.endSponsoringFutureReserves; + } +})); +Object.defineProperty(exports, "extendFootprintTtl", ({ + enumerable: true, + get: function get() { + return _extend_footprint_ttl.extendFootprintTtl; + } +})); +Object.defineProperty(exports, "inflation", ({ + enumerable: true, + get: function get() { + return _inflation.inflation; + } +})); +Object.defineProperty(exports, "invokeContractFunction", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.invokeContractFunction; + } +})); +Object.defineProperty(exports, "invokeHostFunction", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.invokeHostFunction; + } +})); +Object.defineProperty(exports, "liquidityPoolDeposit", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_deposit.liquidityPoolDeposit; + } +})); +Object.defineProperty(exports, "liquidityPoolWithdraw", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_withdraw.liquidityPoolWithdraw; + } +})); +Object.defineProperty(exports, "manageBuyOffer", ({ + enumerable: true, + get: function get() { + return _manage_buy_offer.manageBuyOffer; + } +})); +Object.defineProperty(exports, "manageData", ({ + enumerable: true, + get: function get() { + return _manage_data.manageData; + } +})); +Object.defineProperty(exports, "manageSellOffer", ({ + enumerable: true, + get: function get() { + return _manage_sell_offer.manageSellOffer; + } +})); +Object.defineProperty(exports, "pathPaymentStrictReceive", ({ + enumerable: true, + get: function get() { + return _path_payment_strict_receive.pathPaymentStrictReceive; + } +})); +Object.defineProperty(exports, "pathPaymentStrictSend", ({ + enumerable: true, + get: function get() { + return _path_payment_strict_send.pathPaymentStrictSend; + } +})); +Object.defineProperty(exports, "payment", ({ + enumerable: true, + get: function get() { + return _payment.payment; + } +})); +Object.defineProperty(exports, "restoreFootprint", ({ + enumerable: true, + get: function get() { + return _restore_footprint.restoreFootprint; + } +})); +Object.defineProperty(exports, "revokeAccountSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeAccountSponsorship; + } +})); +Object.defineProperty(exports, "revokeClaimableBalanceSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeClaimableBalanceSponsorship; + } +})); +Object.defineProperty(exports, "revokeDataSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeDataSponsorship; + } +})); +Object.defineProperty(exports, "revokeLiquidityPoolSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeLiquidityPoolSponsorship; + } +})); +Object.defineProperty(exports, "revokeOfferSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeOfferSponsorship; + } +})); +Object.defineProperty(exports, "revokeSignerSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeSignerSponsorship; + } +})); +Object.defineProperty(exports, "revokeTrustlineSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeTrustlineSponsorship; + } +})); +Object.defineProperty(exports, "setOptions", ({ + enumerable: true, + get: function get() { + return _set_options.setOptions; + } +})); +Object.defineProperty(exports, "setTrustLineFlags", ({ + enumerable: true, + get: function get() { + return _set_trustline_flags.setTrustLineFlags; + } +})); +Object.defineProperty(exports, "uploadContractWasm", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.uploadContractWasm; + } +})); +var _manage_sell_offer = __webpack_require__(862); +var _create_passive_sell_offer = __webpack_require__(9073); +var _account_merge = __webpack_require__(4295); +var _allow_trust = __webpack_require__(3683); +var _bump_sequence = __webpack_require__(6183); +var _change_trust = __webpack_require__(2810); +var _create_account = __webpack_require__(2115); +var _create_claimable_balance = __webpack_require__(4831); +var _claim_claimable_balance = __webpack_require__(7239); +var _clawback_claimable_balance = __webpack_require__(2203); +var _inflation = __webpack_require__(7421); +var _manage_data = __webpack_require__(1411); +var _manage_buy_offer = __webpack_require__(1922); +var _path_payment_strict_receive = __webpack_require__(2075); +var _path_payment_strict_send = __webpack_require__(3874); +var _payment = __webpack_require__(3533); +var _set_options = __webpack_require__(2018); +var _begin_sponsoring_future_reserves = __webpack_require__(7505); +var _end_sponsoring_future_reserves = __webpack_require__(721); +var _revoke_sponsorship = __webpack_require__(7790); +var _clawback = __webpack_require__(7651); +var _set_trustline_flags = __webpack_require__(1804); +var _liquidity_pool_deposit = __webpack_require__(9845); +var _liquidity_pool_withdraw = __webpack_require__(4737); +var _invoke_host_function = __webpack_require__(4403); +var _extend_footprint_ttl = __webpack_require__(8752); +var _restore_footprint = __webpack_require__(149); + +/***/ }), + +/***/ 7421: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.inflation = inflation; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation generates the inflation. + * @function + * @alias Operation.inflation + * @param {object} [opts] Options object + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.InflationOp} Inflation operation + */ +function inflation() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.inflation(); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 4403: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createCustomContract = createCustomContract; +exports.createStellarAssetContract = createStellarAssetContract; +exports.invokeContractFunction = invokeContractFunction; +exports.invokeHostFunction = invokeHostFunction; +exports.uploadContractWasm = uploadContractWasm; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _address = __webpack_require__(1180); +var _asset = __webpack_require__(1764); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +/** + * Invokes a single smart contract host function. + * + * @function + * @alias Operation.invokeHostFunction + * + * @param {object} opts - options object + * @param {xdr.HostFunction} opts.func - host function to execute (with its + * wrapped parameters) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - list outlining the + * tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + * @see Operation.invokeContractFunction + * @see Operation.createCustomContract + * @see Operation.createStellarAssetContract + * @see Operation.uploadContractWasm + * @see Contract.call + */ +function invokeHostFunction(opts) { + if (!opts.func) { + throw new TypeError("host function invocation ('func') required (got ".concat(JSON.stringify(opts), ")")); + } + var invokeHostFunctionOp = new _xdr["default"].InvokeHostFunctionOp({ + hostFunction: opts.func, + auth: opts.auth || [] + }); + var opAttributes = { + body: _xdr["default"].OperationBody.invokeHostFunction(invokeHostFunctionOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Returns an operation that invokes a contract function. + * + * @function + * @alias Operation.invokeContractFunction + * + * @param {any} opts - the set of parameters + * @param {string} opts.contract - a strkey-fied contract address (`C...`) + * @param {string} opts.function - the name of the contract fn to invoke + * @param {xdr.ScVal[]} opts.args - parameters to pass to the function + * invocation (try {@link nativeToScVal} or {@link ScInt} to make building + * these easier) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see Operation.invokeHostFunction + * @see Contract.call + * @see Address + */ +function invokeContractFunction(opts) { + var c = new _address.Address(opts.contract); + if (c._type !== 'contract') { + throw new TypeError("expected contract strkey instance, got ".concat(c)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeInvokeContract(new _xdr["default"].InvokeContractArgs({ + contractAddress: c.toScAddress(), + functionName: opts["function"], + args: opts.args + })) + }); +} + +/** + * Returns an operation that creates a custom WASM contract and atomically + * invokes its constructor. + * + * @function + * @alias Operation.createCustomContract + * + * @param {any} opts - the set of parameters + * @param {Address} opts.address - the contract uploader address + * @param {Uint8Array|Buffer} opts.wasmHash - the SHA-256 hash of the contract + * WASM you're uploading (see {@link hash} and + * {@link Operation.uploadContractWasm}) + * @param {xdr.ScVal[]} [opts.constructorArgs] - the optional parameters to pass + * to the constructor of this contract (see {@link nativeToScVal} for ways to + * easily create these parameters from native JS values) + * @param {Uint8Array|Buffer} [opts.salt] - an optional, 32-byte salt to + * distinguish deployment instances of the same wasm from the same user (if + * omitted, one will be generated for you) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + */ +function createCustomContract(opts) { + var _opts$constructorArgs; + var salt = Buffer.from(opts.salt || getSalty()); + if (!opts.wasmHash || opts.wasmHash.length !== 32) { + throw new TypeError("expected hash(contract WASM) in 'opts.wasmHash', got ".concat(opts.wasmHash)); + } + if (salt.length !== 32) { + throw new TypeError("expected 32-byte salt in 'opts.salt', got ".concat(opts.wasmHash)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeCreateContractV2(new _xdr["default"].CreateContractArgsV2({ + executable: _xdr["default"].ContractExecutable.contractExecutableWasm(Buffer.from(opts.wasmHash)), + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAddress(new _xdr["default"].ContractIdPreimageFromAddress({ + address: opts.address.toScAddress(), + salt: salt + })), + constructorArgs: (_opts$constructorArgs = opts.constructorArgs) !== null && _opts$constructorArgs !== void 0 ? _opts$constructorArgs : [] + })) + }); +} + +/** + * Returns an operation that wraps a Stellar asset into a token contract. + * + * @function + * @alias Operation.createStellarAssetContract + * + * @param {any} opts - the set of parameters + * @param {Asset|string} opts.asset - the Stellar asset to wrap, either as an + * {@link Asset} object or in canonical form (SEP-11, `code:issuer`) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see https://stellar.org/protocol/sep-11#alphanum4-alphanum12 + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions + * @see + * https://soroban.stellar.org/docs/advanced-tutorials/stellar-asset-contract + * @see Operation.invokeHostFunction + */ +function createStellarAssetContract(opts) { + var asset = opts.asset; + if (typeof asset === 'string') { + var _asset$split = asset.split(':'), + _asset$split2 = _slicedToArray(_asset$split, 2), + code = _asset$split2[0], + issuer = _asset$split2[1]; + asset = new _asset.Asset(code, issuer); // handles 'xlm' by default + } + if (!(asset instanceof _asset.Asset)) { + throw new TypeError("expected Asset in 'opts.asset', got ".concat(asset)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeCreateContract(new _xdr["default"].CreateContractArgs({ + executable: _xdr["default"].ContractExecutable.contractExecutableStellarAsset(), + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAsset(asset.toXDRObject()) + })) + }); +} + +/** + * Returns an operation that uploads WASM for a contract. + * + * @function + * @alias Operation.uploadContractWasm + * + * @param {any} opts - the set of parameters + * @param {Uint8Array|Buffer} opts.wasm - a WASM blob to upload to the ledger + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + */ +function uploadContractWasm(opts) { + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeUploadContractWasm(Buffer.from(opts.wasm) // coalesce so we can drop `Buffer` someday + ) + }); +} + +/** @returns {Buffer} a random 256-bit "salt" value. */ +function getSalty() { + return _keypair.Keypair.random().xdrPublicKey().value(); // ed25519 is 256 bits, too +} + +/***/ }), + +/***/ 9845: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.liquidityPoolDeposit = liquidityPoolDeposit; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a liquidity pool deposit operation. + * + * @function + * @alias Operation.liquidityPoolDeposit + * @see https://developers.stellar.org/docs/start/list-of-operations/#liquidity-pool-deposit + * + * @param {object} opts - Options object + * @param {string} opts.liquidityPoolId - The liquidity pool ID. + * @param {string} opts.maxAmountA - Maximum amount of first asset to deposit. + * @param {string} opts.maxAmountB - Maximum amount of second asset to deposit. + * @param {number|string|BigNumber|Object} opts.minPrice - Minimum depositA/depositB price. + * @param {number} opts.minPrice.n - If `opts.minPrice` is an object: the price numerator + * @param {number} opts.minPrice.d - If `opts.minPrice` is an object: the price denominator + * @param {number|string|BigNumber|Object} opts.maxPrice - Maximum depositA/depositB price. + * @param {number} opts.maxPrice.n - If `opts.maxPrice` is an object: the price numerator + * @param {number} opts.maxPrice.d - If `opts.maxPrice` is an object: the price denominator + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting operation (xdr.LiquidityPoolDepositOp). + */ +function liquidityPoolDeposit() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var liquidityPoolId = opts.liquidityPoolId, + maxAmountA = opts.maxAmountA, + maxAmountB = opts.maxAmountB, + minPrice = opts.minPrice, + maxPrice = opts.maxPrice; + var attributes = {}; + if (!liquidityPoolId) { + throw new TypeError('liquidityPoolId argument is required'); + } + attributes.liquidityPoolId = _xdr["default"].PoolId.fromXDR(liquidityPoolId, 'hex'); + if (!this.isValidAmount(maxAmountA, true)) { + throw new TypeError(this.constructAmountRequirementsError('maxAmountA')); + } + attributes.maxAmountA = this._toXDRAmount(maxAmountA); + if (!this.isValidAmount(maxAmountB, true)) { + throw new TypeError(this.constructAmountRequirementsError('maxAmountB')); + } + attributes.maxAmountB = this._toXDRAmount(maxAmountB); + if (minPrice === undefined) { + throw new TypeError('minPrice argument is required'); + } + attributes.minPrice = this._toXDRPrice(minPrice); + if (maxPrice === undefined) { + throw new TypeError('maxPrice argument is required'); + } + attributes.maxPrice = this._toXDRPrice(maxPrice); + var liquidityPoolDepositOp = new _xdr["default"].LiquidityPoolDepositOp(attributes); + var opAttributes = { + body: _xdr["default"].OperationBody.liquidityPoolDeposit(liquidityPoolDepositOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 4737: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.liquidityPoolWithdraw = liquidityPoolWithdraw; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a liquidity pool withdraw operation. + * + * @function + * @alias Operation.liquidityPoolWithdraw + * @see https://developers.stellar.org/docs/start/list-of-operations/#liquidity-pool-withdraw + * + * @param {object} opts - Options object + * @param {string} opts.liquidityPoolId - The liquidity pool ID. + * @param {string} opts.amount - Amount of pool shares to withdraw. + * @param {string} opts.minAmountA - Minimum amount of first asset to withdraw. + * @param {string} opts.minAmountB - Minimum amount of second asset to withdraw. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting operation (xdr.LiquidityPoolWithdrawOp). + */ +function liquidityPoolWithdraw() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var attributes = {}; + if (!opts.liquidityPoolId) { + throw new TypeError('liquidityPoolId argument is required'); + } + attributes.liquidityPoolId = _xdr["default"].PoolId.fromXDR(opts.liquidityPoolId, 'hex'); + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (!this.isValidAmount(opts.minAmountA, true)) { + throw new TypeError(this.constructAmountRequirementsError('minAmountA')); + } + attributes.minAmountA = this._toXDRAmount(opts.minAmountA); + if (!this.isValidAmount(opts.minAmountB, true)) { + throw new TypeError(this.constructAmountRequirementsError('minAmountB')); + } + attributes.minAmountB = this._toXDRAmount(opts.minAmountB); + var liquidityPoolWithdrawOp = new _xdr["default"].LiquidityPoolWithdrawOp(attributes); + var opAttributes = { + body: _xdr["default"].OperationBody.liquidityPoolWithdraw(liquidityPoolWithdrawOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 1922: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.manageBuyOffer = manageBuyOffer; +var _jsXdr = __webpack_require__(3740); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR ManageBuyOfferOp. A "manage buy offer" operation creates, updates, or + * deletes a buy offer. + * @function + * @alias Operation.manageBuyOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.buyAmount - The total amount you're buying. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `buying` in terms of `selling`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.ManageBuyOfferOp} Manage Buy Offer operation + */ +function manageBuyOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.buyAmount, true)) { + throw new TypeError(this.constructAmountRequirementsError('buyAmount')); + } + attributes.buyAmount = this._toXDRAmount(opts.buyAmount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + if (opts.offerId !== undefined) { + opts.offerId = opts.offerId.toString(); + } else { + opts.offerId = '0'; + } + attributes.offerId = _jsXdr.Hyper.fromString(opts.offerId); + var manageBuyOfferOp = new _xdr["default"].ManageBuyOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageBuyOffer(manageBuyOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 1411: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.manageData = manageData; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation adds data entry to the ledger. + * @function + * @alias Operation.manageData + * @param {object} opts Options object + * @param {string} opts.name - The name of the data entry. + * @param {string|Buffer} opts.value - The value of the data entry. + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.ManageDataOp} Manage Data operation + */ +function manageData(opts) { + var attributes = {}; + if (!(typeof opts.name === 'string' && opts.name.length <= 64)) { + throw new Error('name must be a string, up to 64 characters'); + } + attributes.dataName = opts.name; + if (typeof opts.value !== 'string' && !Buffer.isBuffer(opts.value) && opts.value !== null) { + throw new Error('value must be a string, Buffer or null'); + } + if (typeof opts.value === 'string') { + attributes.dataValue = Buffer.from(opts.value); + } else { + attributes.dataValue = opts.value; + } + if (attributes.dataValue !== null && attributes.dataValue.length > 64) { + throw new Error('value cannot be longer that 64 bytes'); + } + var manageDataOp = new _xdr["default"].ManageDataOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageData(manageDataOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 862: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.manageSellOffer = manageSellOffer; +var _jsXdr = __webpack_require__(3740); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR ManageSellOfferOp. A "manage sell offer" operation creates, updates, or + * deletes an offer. + * @function + * @alias Operation.manageSellOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.ManageSellOfferOp} Manage Sell Offer operation + */ +function manageSellOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.amount, true)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + if (opts.offerId !== undefined) { + opts.offerId = opts.offerId.toString(); + } else { + opts.offerId = '0'; + } + attributes.offerId = _jsXdr.Hyper.fromString(opts.offerId); + var manageSellOfferOp = new _xdr["default"].ManageSellOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageSellOffer(manageSellOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2075: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.pathPaymentStrictReceive = pathPaymentStrictReceive; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a PathPaymentStrictReceive operation. + * + * A `PathPaymentStrictReceive` operation sends the specified amount to the + * destination account. It credits the destination with `destAmount` of + * `destAsset`, while debiting at most `sendMax` of `sendAsset` from the source. + * The transfer optionally occurs through a path. XLM payments create the + * destination account if it does not exist. + * + * @function + * @alias Operation.pathPaymentStrictReceive + * @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-receive + * + * @param {object} opts - Options object + * @param {Asset} opts.sendAsset - asset to pay with + * @param {string} opts.sendMax - maximum amount of sendAsset to send + * @param {string} opts.destination - destination account to send to + * @param {Asset} opts.destAsset - asset the destination will receive + * @param {string} opts.destAmount - amount the destination receives + * @param {Asset[]} opts.path - array of Asset objects to use as the path + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.PathPaymentStrictReceiveOp} the resulting path payment op + */ +function pathPaymentStrictReceive(opts) { + switch (true) { + case !opts.sendAsset: + throw new Error('Must specify a send asset'); + case !this.isValidAmount(opts.sendMax): + throw new TypeError(this.constructAmountRequirementsError('sendMax')); + case !opts.destAsset: + throw new Error('Must provide a destAsset for a payment operation'); + case !this.isValidAmount(opts.destAmount): + throw new TypeError(this.constructAmountRequirementsError('destAmount')); + default: + break; + } + var attributes = {}; + attributes.sendAsset = opts.sendAsset.toXDRObject(); + attributes.sendMax = this._toXDRAmount(opts.sendMax); + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.destAsset = opts.destAsset.toXDRObject(); + attributes.destAmount = this._toXDRAmount(opts.destAmount); + var path = opts.path ? opts.path : []; + attributes.path = path.map(function (x) { + return x.toXDRObject(); + }); + var payment = new _xdr["default"].PathPaymentStrictReceiveOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.pathPaymentStrictReceive(payment); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 3874: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.pathPaymentStrictSend = pathPaymentStrictSend; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a PathPaymentStrictSend operation. + * + * A `PathPaymentStrictSend` operation sends the specified amount to the + * destination account crediting at least `destMin` of `destAsset`, optionally + * through a path. XLM payments create the destination account if it does not + * exist. + * + * @function + * @alias Operation.pathPaymentStrictSend + * @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-send + * + * @param {object} opts - Options object + * @param {Asset} opts.sendAsset - asset to pay with + * @param {string} opts.sendAmount - amount of sendAsset to send (excluding fees) + * @param {string} opts.destination - destination account to send to + * @param {Asset} opts.destAsset - asset the destination will receive + * @param {string} opts.destMin - minimum amount of destAsset to be receive + * @param {Asset[]} opts.path - array of Asset objects to use as the path + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.Operation} the resulting path payment operation + * (xdr.PathPaymentStrictSendOp) + */ +function pathPaymentStrictSend(opts) { + switch (true) { + case !opts.sendAsset: + throw new Error('Must specify a send asset'); + case !this.isValidAmount(opts.sendAmount): + throw new TypeError(this.constructAmountRequirementsError('sendAmount')); + case !opts.destAsset: + throw new Error('Must provide a destAsset for a payment operation'); + case !this.isValidAmount(opts.destMin): + throw new TypeError(this.constructAmountRequirementsError('destMin')); + default: + break; + } + var attributes = {}; + attributes.sendAsset = opts.sendAsset.toXDRObject(); + attributes.sendAmount = this._toXDRAmount(opts.sendAmount); + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.destAsset = opts.destAsset.toXDRObject(); + attributes.destMin = this._toXDRAmount(opts.destMin); + var path = opts.path ? opts.path : []; + attributes.path = path.map(function (x) { + return x.toXDRObject(); + }); + var payment = new _xdr["default"].PathPaymentStrictSendOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.pathPaymentStrictSend(payment); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 3533: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.payment = payment; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a payment operation. + * + * @function + * @alias Operation.payment + * @see https://developers.stellar.org/docs/start/list-of-operations/#payment + * + * @param {object} opts - Options object + * @param {string} opts.destination - destination account ID + * @param {Asset} opts.asset - asset to send + * @param {string} opts.amount - amount to send + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting payment operation (xdr.PaymentOp) + */ +function payment(opts) { + if (!opts.asset) { + throw new Error('Must provide an asset for a payment operation'); + } + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + var attributes = {}; + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.asset = opts.asset.toXDRObject(); + attributes.amount = this._toXDRAmount(opts.amount); + var paymentOp = new _xdr["default"].PaymentOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.payment(paymentOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 149: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.restoreFootprint = restoreFootprint; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Builds an operation to restore the archived ledger entries specified + * by the ledger keys. + * + * The ledger keys to restore are specified separately from the operation + * in read-write footprint of the transaction. + * + * It takes no parameters because the relevant footprint is derived from the + * transaction itself. See {@link TransactionBuilder}'s `opts.sorobanData` + * parameter (or {@link TransactionBuilder.setSorobanData} / + * {@link TransactionBuilder.setLedgerKeys}), which is a + * {@link xdr.SorobanTransactionData} instance that contains fee data & resource + * usage as part of {@link xdr.SorobanTransactionData}. + * + * @function + * @alias Operation.restoreFootprint + * + * @param {object} [opts] - an optional set of parameters + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} a Bump Footprint Expiration operation + * (xdr.RestoreFootprintOp) + */ +function restoreFootprint() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var op = new _xdr["default"].RestoreFootprintOp({ + ext: new _xdr["default"].ExtensionPoint(0) + }); + var opAttributes = { + body: _xdr["default"].OperationBody.restoreFootprint(op) + }; + this.setSourceAccount(opAttributes, opts !== null && opts !== void 0 ? opts : {}); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7790: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.revokeAccountSponsorship = revokeAccountSponsorship; +exports.revokeClaimableBalanceSponsorship = revokeClaimableBalanceSponsorship; +exports.revokeDataSponsorship = revokeDataSponsorship; +exports.revokeLiquidityPoolSponsorship = revokeLiquidityPoolSponsorship; +exports.revokeOfferSponsorship = revokeOfferSponsorship; +exports.revokeSignerSponsorship = revokeSignerSponsorship; +exports.revokeTrustlineSponsorship = revokeTrustlineSponsorship; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +var _keypair = __webpack_require__(6691); +var _asset = __webpack_require__(1764); +var _liquidity_pool_id = __webpack_require__(9353); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a "revoke sponsorship" operation for an account. + * + * @function + * @alias Operation.revokeAccountSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The sponsored account ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeAccountSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * }); + * + */ +function revokeAccountSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.account(new _xdr["default"].LedgerKeyAccount({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId() + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a trustline. + * + * @function + * @alias Operation.revokeTrustlineSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID which owns the trustline. + * @param {Asset | LiquidityPoolId} opts.asset - The trustline asset. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeTrustlineSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * asset: new StellarBase.LiquidityPoolId( + * 'USDUSD', + * 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * ) + * }); + * + */ +function revokeTrustlineSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var asset; + if (opts.asset instanceof _asset.Asset) { + asset = opts.asset.toTrustLineXDRObject(); + } else if (opts.asset instanceof _liquidity_pool_id.LiquidityPoolId) { + asset = opts.asset.toXDRObject(); + } else { + throw new TypeError('asset must be an Asset or LiquidityPoolId'); + } + var ledgerKey = _xdr["default"].LedgerKey.trustline(new _xdr["default"].LedgerKeyTrustLine({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + asset: asset + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for an offer. + * + * @function + * @alias Operation.revokeOfferSponsorship + * @param {object} opts Options object + * @param {string} opts.seller - The account ID which created the offer. + * @param {string} opts.offerId - The offer ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeOfferSponsorship({ + * seller: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * offerId: '1234' + * }); + * + */ +function revokeOfferSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.seller)) { + throw new Error('seller is invalid'); + } + if (typeof opts.offerId !== 'string') { + throw new Error('offerId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.offer(new _xdr["default"].LedgerKeyOffer({ + sellerId: _keypair.Keypair.fromPublicKey(opts.seller).xdrAccountId(), + offerId: _xdr["default"].Int64.fromString(opts.offerId) + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a data entry. + * + * @function + * @alias Operation.revokeDataSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID which owns the data entry. + * @param {string} opts.name - The name of the data entry + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeDataSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * name: 'foo' + * }); + * + */ +function revokeDataSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + if (typeof opts.name !== 'string' || opts.name.length > 64) { + throw new Error('name must be a string, up to 64 characters'); + } + var ledgerKey = _xdr["default"].LedgerKey.data(new _xdr["default"].LedgerKeyData({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + dataName: opts.name + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a claimable balance. + * + * @function + * @alias Operation.revokeClaimableBalanceSponsorship + * @param {object} opts Options object + * @param {string} opts.balanceId - The sponsored claimable balance ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeClaimableBalanceSponsorship({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + */ +function revokeClaimableBalanceSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (typeof opts.balanceId !== 'string') { + throw new Error('balanceId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.claimableBalance(new _xdr["default"].LedgerKeyClaimableBalance({ + balanceId: _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex') + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Creates a "revoke sponsorship" operation for a liquidity pool. + * + * @function + * @alias Operation.revokeLiquidityPoolSponsorship + * @param {object} opts – Options object. + * @param {string} opts.liquidityPoolId - The sponsored liquidity pool ID in 'hex' string. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr Operation. + * + * @example + * const op = Operation.revokeLiquidityPoolSponsorship({ + * liquidityPoolId: 'dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7', + * }); + * + */ +function revokeLiquidityPoolSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (typeof opts.liquidityPoolId !== 'string') { + throw new Error('liquidityPoolId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.liquidityPool(new _xdr["default"].LedgerKeyLiquidityPool({ + liquidityPoolId: _xdr["default"].PoolId.fromXDR(opts.liquidityPoolId, 'hex') + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = { + body: _xdr["default"].OperationBody.revokeSponsorship(op) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a signer. + * + * @function + * @alias Operation.revokeSignerSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID where the signer sponsorship is being removed from. + * @param {object} opts.signer - The signer whose sponsorship is being removed. + * @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer. + * @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string). + * @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeSignerSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * signer: { + * ed25519PublicKey: 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ' + * } + * }) + * + */ +function revokeSignerSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var key; + if (opts.signer.ed25519PublicKey) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) { + throw new Error('signer.ed25519PublicKey is invalid.'); + } + var rawKey = _strkey.StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey); + key = new _xdr["default"].SignerKey.signerKeyTypeEd25519(rawKey); + } else if (opts.signer.preAuthTx) { + var buffer; + if (typeof opts.signer.preAuthTx === 'string') { + buffer = Buffer.from(opts.signer.preAuthTx, 'hex'); + } else { + buffer = opts.signer.preAuthTx; + } + if (!(Buffer.isBuffer(buffer) && buffer.length === 32)) { + throw new Error('signer.preAuthTx must be 32 bytes Buffer.'); + } + key = new _xdr["default"].SignerKey.signerKeyTypePreAuthTx(buffer); + } else if (opts.signer.sha256Hash) { + var _buffer; + if (typeof opts.signer.sha256Hash === 'string') { + _buffer = Buffer.from(opts.signer.sha256Hash, 'hex'); + } else { + _buffer = opts.signer.sha256Hash; + } + if (!(Buffer.isBuffer(_buffer) && _buffer.length === 32)) { + throw new Error('signer.sha256Hash must be 32 bytes Buffer.'); + } + key = new _xdr["default"].SignerKey.signerKeyTypeHashX(_buffer); + } else { + throw new Error('signer is invalid'); + } + var signer = new _xdr["default"].RevokeSponsorshipOpSigner({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + signerKey: key + }); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipSigner(signer); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2018: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.setOptions = setOptions; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/* eslint-disable no-param-reassign */ + +function weightCheckFunction(value, name) { + if (value >= 0 && value <= 255) { + return true; + } + throw new Error("".concat(name, " value must be between 0 and 255")); +} + +/** + * Returns an XDR SetOptionsOp. A "set options" operations set or clear account flags, + * set the account's inflation destination, and/or add new signers to the account. + * The flags used in `opts.clearFlags` and `opts.setFlags` can be the following: + * - `{@link AuthRequiredFlag}` + * - `{@link AuthRevocableFlag}` + * - `{@link AuthImmutableFlag}` + * - `{@link AuthClawbackEnabledFlag}` + * + * It's possible to set/clear multiple flags at once using logical or. + * + * @function + * @alias Operation.setOptions + * + * @param {object} opts Options object + * @param {string} [opts.inflationDest] - Set this account ID as the account's inflation destination. + * @param {(number|string)} [opts.clearFlags] - Bitmap integer for which account flags to clear. + * @param {(number|string)} [opts.setFlags] - Bitmap integer for which account flags to set. + * @param {number|string} [opts.masterWeight] - The master key weight. + * @param {number|string} [opts.lowThreshold] - The sum weight for the low threshold. + * @param {number|string} [opts.medThreshold] - The sum weight for the medium threshold. + * @param {number|string} [opts.highThreshold] - The sum weight for the high threshold. + * @param {object} [opts.signer] - Add or remove a signer from the account. The signer is + * deleted if the weight is 0. Only one of `ed25519PublicKey`, `sha256Hash`, `preAuthTx` should be defined. + * @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer. + * @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string) of preimage that will unlock funds. Preimage should be used as signature of future transaction. + * @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction that will unlock funds. + * @param {string} [opts.signer.ed25519SignedPayload] - Signed payload signer (ed25519 public key + raw payload) for atomic transaction signature disclosure. + * @param {number|string} [opts.signer.weight] - The weight of the new signer (0 to delete or 1-255) + * @param {string} [opts.homeDomain] - sets the home domain used for reverse federation lookup. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * + * @returns {xdr.SetOptionsOp} XDR operation + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +function setOptions(opts) { + var attributes = {}; + if (opts.inflationDest) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.inflationDest)) { + throw new Error('inflationDest is invalid'); + } + attributes.inflationDest = _keypair.Keypair.fromPublicKey(opts.inflationDest).xdrAccountId(); + } + attributes.clearFlags = this._checkUnsignedIntValue('clearFlags', opts.clearFlags); + attributes.setFlags = this._checkUnsignedIntValue('setFlags', opts.setFlags); + attributes.masterWeight = this._checkUnsignedIntValue('masterWeight', opts.masterWeight, weightCheckFunction); + attributes.lowThreshold = this._checkUnsignedIntValue('lowThreshold', opts.lowThreshold, weightCheckFunction); + attributes.medThreshold = this._checkUnsignedIntValue('medThreshold', opts.medThreshold, weightCheckFunction); + attributes.highThreshold = this._checkUnsignedIntValue('highThreshold', opts.highThreshold, weightCheckFunction); + if (opts.homeDomain !== undefined && typeof opts.homeDomain !== 'string') { + throw new TypeError('homeDomain argument must be of type String'); + } + attributes.homeDomain = opts.homeDomain; + if (opts.signer) { + var weight = this._checkUnsignedIntValue('signer.weight', opts.signer.weight, weightCheckFunction); + var key; + var setValues = 0; + if (opts.signer.ed25519PublicKey) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) { + throw new Error('signer.ed25519PublicKey is invalid.'); + } + var rawKey = _strkey.StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey); + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypeEd25519(rawKey); + setValues += 1; + } + if (opts.signer.preAuthTx) { + if (typeof opts.signer.preAuthTx === 'string') { + opts.signer.preAuthTx = Buffer.from(opts.signer.preAuthTx, 'hex'); + } + if (!(Buffer.isBuffer(opts.signer.preAuthTx) && opts.signer.preAuthTx.length === 32)) { + throw new Error('signer.preAuthTx must be 32 bytes Buffer.'); + } + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypePreAuthTx(opts.signer.preAuthTx); + setValues += 1; + } + if (opts.signer.sha256Hash) { + if (typeof opts.signer.sha256Hash === 'string') { + opts.signer.sha256Hash = Buffer.from(opts.signer.sha256Hash, 'hex'); + } + if (!(Buffer.isBuffer(opts.signer.sha256Hash) && opts.signer.sha256Hash.length === 32)) { + throw new Error('signer.sha256Hash must be 32 bytes Buffer.'); + } + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypeHashX(opts.signer.sha256Hash); + setValues += 1; + } + if (opts.signer.ed25519SignedPayload) { + if (!_strkey.StrKey.isValidSignedPayload(opts.signer.ed25519SignedPayload)) { + throw new Error('signer.ed25519SignedPayload is invalid.'); + } + var _rawKey = _strkey.StrKey.decodeSignedPayload(opts.signer.ed25519SignedPayload); + var signedPayloadXdr = _xdr["default"].SignerKeyEd25519SignedPayload.fromXDR(_rawKey); + + // eslint-disable-next-line new-cap + key = _xdr["default"].SignerKey.signerKeyTypeEd25519SignedPayload(signedPayloadXdr); + setValues += 1; + } + if (setValues !== 1) { + throw new Error('Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx.'); + } + attributes.signer = new _xdr["default"].Signer({ + key: key, + weight: weight + }); + } + var setOptionsOp = new _xdr["default"].SetOptionsOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.setOptions(setOptionsOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 1804: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.setTrustLineFlags = setTrustLineFlags; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/** + * Creates a trustline flag configuring operation. + * + * For the flags, set them to true to enable them and false to disable them. Any + * unmodified operations will be marked `undefined` in the result. + * + * Note that you can only **clear** the clawbackEnabled flag set; it must be set + * account-wide via operations.SetOptions (setting + * xdr.AccountFlags.clawbackEnabled). + * + * @function + * @alias Operation.setTrustLineFlags + * + * @param {object} opts - Options object + * @param {string} opts.trustor - the account whose trustline this is + * @param {Asset} opts.asset - the asset on the trustline + * @param {object} opts.flags - the set of flags to modify + * + * @param {bool} [opts.flags.authorized] - authorize account to perform + * transactions with its credit + * @param {bool} [opts.flags.authorizedToMaintainLiabilities] - authorize + * account to maintain and reduce liabilities for its credit + * @param {bool} [opts.flags.clawbackEnabled] - stop claimable balances on + * this trustlines from having clawbacks enabled (this flag can only be set + * to false!) + * @param {string} [opts.source] - The source account for the operation. + * Defaults to the transaction's source account. + * + * @note You must include at least one flag. + * + * @return {xdr.SetTrustLineFlagsOp} + * + * @link xdr.AccountFlags + * @link xdr.TrustLineFlags + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#set-trustline-flags-operation + * @see https://developers.stellar.org/docs/start/list-of-operations/#set-options + */ +function setTrustLineFlags() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var attributes = {}; + if (_typeof(opts.flags) !== 'object' || Object.keys(opts.flags).length === 0) { + throw new Error('opts.flags must be a map of boolean flags to modify'); + } + var mapping = { + authorized: _xdr["default"].TrustLineFlags.authorizedFlag(), + authorizedToMaintainLiabilities: _xdr["default"].TrustLineFlags.authorizedToMaintainLiabilitiesFlag(), + clawbackEnabled: _xdr["default"].TrustLineFlags.trustlineClawbackEnabledFlag() + }; + + /* eslint no-bitwise: "off" */ + var clearFlag = 0; + var setFlag = 0; + Object.keys(opts.flags).forEach(function (flagName) { + if (!Object.prototype.hasOwnProperty.call(mapping, flagName)) { + throw new Error("unsupported flag name specified: ".concat(flagName)); + } + var flagValue = opts.flags[flagName]; + var bit = mapping[flagName].value; + if (flagValue === true) { + setFlag |= bit; + } else if (flagValue === false) { + clearFlag |= bit; + } + }); + attributes.trustor = _keypair.Keypair.fromPublicKey(opts.trustor).xdrAccountId(); + attributes.asset = opts.asset.toXDRObject(); + attributes.clearFlags = clearFlag; + attributes.setFlags = setFlag; + var opAttributes = { + body: _xdr["default"].OperationBody.setTrustLineFlags(new _xdr["default"].SetTrustLineFlagsOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7177: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.nativeToScVal = nativeToScVal; +exports.scValToNative = scValToNative; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _address = __webpack_require__(1180); +var _contract = __webpack_require__(7452); +var _index = __webpack_require__(8549); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/** + * Attempts to convert native types into smart contract values + * ({@link xdr.ScVal}). + * + * Provides conversions from smart contract XDR values ({@link xdr.ScVal}) to + * native JavaScript types. + * + * The conversions are as follows: + * + * - xdr.ScVal -> passthrough + * - null/undefined -> scvVoid + * - string -> scvString (a copy is made) + * - UintArray8 -> scvBytes (a copy is made) + * - boolean -> scvBool + * + * - number/bigint -> the smallest possible XDR integer type that will fit the + * input value (if you want a specific type, use {@link ScInt}) + * + * - {@link Address} or {@link Contract} -> scvAddress (for contracts and + * public keys) + * + * - Array -> scvVec after attempting to convert each item of type `T` to an + * xdr.ScVal (recursively). note that all values must be the same type! + * + * - object -> scvMap after attempting to convert each key and value to an + * xdr.ScVal (recursively). note that there is no restriction on types + * matching anywhere (unlike arrays) + * + * When passing an integer-like native value, you can also optionally specify a + * type which will force a particular interpretation of that value. + * + * Note that not all type specifications are compatible with all `ScVal`s, e.g. + * `toScVal("a string", {type: "i256"})` will throw. + * + * @param {any} val - a native (or convertible) input value to wrap + * @param {object} [opts] - an optional set of hints around the type of + * conversion you'd like to see + * @param {string} [opts.type] - there is different behavior for different input + * types for `val`: + * + * - when `val` is an integer-like type (i.e. number|bigint), this will be + * forwarded to {@link ScInt} or forced to be u32/i32. + * + * - when `val` is an array type, this is forwarded to the recursion + * + * - when `val` is an object type (key-value entries), this should be an + * object in which each key has a pair of types (to represent forced types + * for the key and the value), where `null` (or a missing entry) indicates + * the default interpretation(s) (refer to the examples, below) + * + * - when `val` is a string type, this can be 'string' or 'symbol' to force + * a particular interpretation of `val`. + * + * - when `val` is a bytes-like type, this can be 'string', 'symbol', or + * 'bytes' to force a particular interpretation + * + * As a simple example, `nativeToScVal("hello", {type: 'symbol'})` will + * return an `scvSymbol`, whereas without the type it would have been an + * `scvString`. + * + * @returns {xdr.ScVal} a wrapped, smart, XDR version of the input value + * @throws {TypeError} if... + * - there are arrays with more than one type in them + * - there are values that do not have a sensible conversion (e.g. random XDR + * types, custom classes) + * - the type of the input object (or some inner value of said object) cannot + * be determined (via `typeof`) + * - the type you specified (via `opts.type`) is incompatible with the value + * you passed in (`val`), e.g. `nativeToScVal("a string", { type: 'i128' })`, + * though this does not apply for types that ignore `opts` (e.g. addresses). + * @see scValToNative + * + * @example + * nativeToScVal(1000); // gives ScValType === scvU64 + * nativeToScVal(1000n); // gives ScValType === scvU64 + * nativeToScVal(1n << 100n); // gives ScValType === scvU128 + * nativeToScVal(1000, { type: 'u32' }); // gives ScValType === scvU32 + * nativeToScVal(1000, { type: 'i125' }); // gives ScValType === scvI256 + * nativeToScVal("a string"); // gives ScValType === scvString + * nativeToScVal("a string", { type: 'symbol' }); // gives scvSymbol + * nativeToScVal(new Uint8Array(5)); // scvBytes + * nativeToScVal(new Uint8Array(5), { type: 'symbol' }); // scvSymbol + * nativeToScVal(null); // scvVoid + * nativeToScVal(true); // scvBool + * nativeToScVal([1, 2, 3]); // gives scvVec with each element as scvU64 + * nativeToScVal([1, 2, 3], { type: 'i128' }); // scvVec + * nativeToScVal({ 'hello': 1, 'world': [ true, false ] }, { + * type: { + * 'hello': [ 'symbol', 'i128' ], + * } + * }) + * // gives scvMap with entries: [ + * // [ scvSymbol, scvI128 ], + * // [ scvString, scvArray ] + * // ] + * + * @example + * import { + * nativeToScVal, + * scValToNative, + * ScInt, + * xdr + * } from '@stellar/stellar-base'; + * + * let gigaMap = { + * bool: true, + * void: null, + * u32: xdr.ScVal.scvU32(1), + * i32: xdr.ScVal.scvI32(1), + * u64: 1n, + * i64: -1n, + * u128: new ScInt(1).toU128(), + * i128: new ScInt(1).toI128(), + * u256: new ScInt(1).toU256(), + * i256: new ScInt(1).toI256(), + * map: { + * arbitrary: 1n, + * nested: 'values', + * etc: false + * }, + * vec: ['same', 'type', 'list'], + * }; + * + * // then, simply: + * let scv = nativeToScVal(gigaMap); // scv.switch() == xdr.ScValType.scvMap() + * + * // then... + * someContract.call("method", scv); + * + * // Similarly, the inverse should work: + * scValToNative(scv) == gigaMap; // true + */ +function nativeToScVal(val) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + switch (_typeof(val)) { + case 'object': + { + var _val$constructor$name, _val$constructor; + if (val === null) { + return _xdr["default"].ScVal.scvVoid(); + } + if (val instanceof _xdr["default"].ScVal) { + return val; // should we copy? + } + if (val instanceof _address.Address) { + return val.toScVal(); + } + if (val instanceof _contract.Contract) { + return val.address().toScVal(); + } + if (val instanceof Uint8Array || Buffer.isBuffer(val)) { + var _opts$type; + var copy = Uint8Array.from(val); + switch ((_opts$type = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type !== void 0 ? _opts$type : 'bytes') { + case 'bytes': + return _xdr["default"].ScVal.scvBytes(copy); + case 'symbol': + return _xdr["default"].ScVal.scvSymbol(copy); + case 'string': + return _xdr["default"].ScVal.scvString(copy); + default: + throw new TypeError("invalid type (".concat(opts.type, ") specified for bytes-like value")); + } + } + if (Array.isArray(val)) { + if (val.length > 0 && val.some(function (v) { + return _typeof(v) !== _typeof(val[0]); + })) { + throw new TypeError("array values (".concat(val, ") must have the same type (types: ").concat(val.map(function (v) { + return _typeof(v); + }).join(','), ")")); + } + return _xdr["default"].ScVal.scvVec(val.map(function (v) { + return nativeToScVal(v, opts); + })); + } + if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : '') !== 'Object') { + var _val$constructor2; + throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")")); + } + return _xdr["default"].ScVal.scvMap(Object.entries(val) + // The Soroban runtime expects maps to have their keys in sorted + // order, so let's do that here as part of the conversion to prevent + // confusing error messages on execution. + .sort(function (_ref, _ref2) { + var _ref3 = _slicedToArray(_ref, 1), + key1 = _ref3[0]; + var _ref4 = _slicedToArray(_ref2, 1), + key2 = _ref4[0]; + return key1.localeCompare(key2); + }).map(function (_ref5) { + var _k, _opts$type2; + var _ref6 = _slicedToArray(_ref5, 2), + k = _ref6[0], + v = _ref6[1]; + // the type can be specified with an entry for the key and the value, + // e.g. val = { 'hello': 1 } and opts.type = { hello: [ 'symbol', + // 'u128' ]} or you can use `null` for the default interpretation + var _ref7 = (_k = ((_opts$type2 = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type2 !== void 0 ? _opts$type2 : {})[k]) !== null && _k !== void 0 ? _k : [null, null], + _ref8 = _slicedToArray(_ref7, 2), + keyType = _ref8[0], + valType = _ref8[1]; + var keyOpts = keyType ? { + type: keyType + } : {}; + var valOpts = valType ? { + type: valType + } : {}; + return new _xdr["default"].ScMapEntry({ + key: nativeToScVal(k, keyOpts), + val: nativeToScVal(v, valOpts) + }); + })); + } + case 'number': + case 'bigint': + switch (opts === null || opts === void 0 ? void 0 : opts.type) { + case 'u32': + return _xdr["default"].ScVal.scvU32(val); + case 'i32': + return _xdr["default"].ScVal.scvI32(val); + default: + break; + } + return new _index.ScInt(val, { + type: opts === null || opts === void 0 ? void 0 : opts.type + }).toScVal(); + case 'string': + { + var _opts$type3; + var optType = (_opts$type3 = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type3 !== void 0 ? _opts$type3 : 'string'; + switch (optType) { + case 'string': + return _xdr["default"].ScVal.scvString(val); + case 'symbol': + return _xdr["default"].ScVal.scvSymbol(val); + case 'address': + return new _address.Address(val).toScVal(); + case 'u32': + return _xdr["default"].ScVal.scvU32(parseInt(val, 10)); + case 'i32': + return _xdr["default"].ScVal.scvI32(parseInt(val, 10)); + default: + if (_index.XdrLargeInt.isType(optType)) { + return new _index.XdrLargeInt(optType, val).toScVal(); + } + throw new TypeError("invalid type (".concat(opts.type, ") specified for string value")); + } + } + case 'boolean': + return _xdr["default"].ScVal.scvBool(val); + case 'undefined': + return _xdr["default"].ScVal.scvVoid(); + case 'function': + // FIXME: Is this too helpful? + return nativeToScVal(val()); + default: + throw new TypeError("failed to convert typeof ".concat(_typeof(val), " (").concat(val, ")")); + } +} + +/** + * Given a smart contract value, attempt to convert it to a native type. + * Possible conversions include: + * + * - void -> `null` + * - u32, i32 -> `number` + * - u64, i64, u128, i128, u256, i256 -> `bigint` + * - vec -> `Array` of any of the above (via recursion) + * - map -> key-value object of any of the above (via recursion) + * - bool -> `boolean` + * - bytes -> `Uint8Array` + * - symbol -> `string` + * - string -> `string` IF the underlying buffer can be decoded as ascii/utf8, + * `Uint8Array` of the raw contents in any error case + * + * If no viable conversion can be determined, this just "unwraps" the smart + * value to return its underlying XDR value. + * + * @param {xdr.ScVal} scv - the input smart contract value + * + * @returns {any} + * @see nativeToScVal + */ +function scValToNative(scv) { + var _scv$vec, _scv$map; + // we use the verbose xdr.ScValType..value form here because it's faster + // than string comparisons and the underlying constants never need to be + // updated + switch (scv["switch"]().value) { + case _xdr["default"].ScValType.scvVoid().value: + return null; + + // these can be converted to bigints directly + case _xdr["default"].ScValType.scvU64().value: + case _xdr["default"].ScValType.scvI64().value: + return scv.value().toBigInt(); + + // these can be parsed by internal abstractions note that this can also + // handle the above two cases, but it's not as efficient (another + // type-check, parsing, etc.) + case _xdr["default"].ScValType.scvU128().value: + case _xdr["default"].ScValType.scvI128().value: + case _xdr["default"].ScValType.scvU256().value: + case _xdr["default"].ScValType.scvI256().value: + return (0, _index.scValToBigInt)(scv); + case _xdr["default"].ScValType.scvVec().value: + return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(scValToNative); + case _xdr["default"].ScValType.scvAddress().value: + return _address.Address.fromScVal(scv).toString(); + case _xdr["default"].ScValType.scvMap().value: + return Object.fromEntries(((_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []).map(function (entry) { + return [scValToNative(entry.key()), scValToNative(entry.val())]; + })); + + // these return the primitive type directly + case _xdr["default"].ScValType.scvBool().value: + case _xdr["default"].ScValType.scvU32().value: + case _xdr["default"].ScValType.scvI32().value: + case _xdr["default"].ScValType.scvBytes().value: + return scv.value(); + + // Symbols are limited to [a-zA-Z0-9_]+, so we can safely make ascii strings + // + // Strings, however, are "presented" as strings and we treat them as such + // (in other words, string = bytes with a hint that it's text). If the user + // encoded non-printable bytes in their string value, that's on them. + // + // Note that we assume a utf8 encoding (ascii-compatible). For other + // encodings, you should probably use bytes anyway. If it cannot be decoded, + // the raw bytes are returned. + case _xdr["default"].ScValType.scvSymbol().value: + case _xdr["default"].ScValType.scvString().value: + { + var v = scv.value(); // string|Buffer + if (Buffer.isBuffer(v) || ArrayBuffer.isView(v)) { + try { + return new TextDecoder().decode(v); + } catch (e) { + return new Uint8Array(v.buffer); // copy of bytes + } + } + return v; // string already + } + + // these can be converted to bigint + case _xdr["default"].ScValType.scvTimepoint().value: + case _xdr["default"].ScValType.scvDuration().value: + return new _xdr["default"].Uint64(scv.value()).toBigInt(); + case _xdr["default"].ScValType.scvError().value: + switch (scv.error()["switch"]().value) { + // Distinguish errors from the user contract. + case _xdr["default"].ScErrorType.sceContract().value: + return { + type: 'contract', + code: scv.error().contractCode() + }; + default: + { + var err = scv.error(); + return { + type: 'system', + code: err.code().value, + value: err.code().name + }; + } + } + + // in the fallthrough case, just return the underlying value directly + default: + return scv.value(); + } +} + +/***/ }), + +/***/ 225: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.SignerKey = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * A container class with helpers to convert between signer keys + * (`xdr.SignerKey`) and {@link StrKey}s. + * + * It's primarly used for manipulating the `extraSigners` precondition on a + * {@link Transaction}. + * + * @see {@link TransactionBuilder.setExtraSigners} + */ +var SignerKey = exports.SignerKey = /*#__PURE__*/function () { + function SignerKey() { + _classCallCheck(this, SignerKey); + } + return _createClass(SignerKey, null, [{ + key: "decodeAddress", + value: + /** + * Decodes a StrKey address into an xdr.SignerKey instance. + * + * Only ED25519 public keys (G...), pre-auth transactions (T...), hashes + * (H...), and signed payloads (P...) can be signer keys. + * + * @param {string} address a StrKey-encoded signer address + * @returns {xdr.SignerKey} + */ + function decodeAddress(address) { + var signerKeyMap = { + ed25519PublicKey: _xdr["default"].SignerKey.signerKeyTypeEd25519, + preAuthTx: _xdr["default"].SignerKey.signerKeyTypePreAuthTx, + sha256Hash: _xdr["default"].SignerKey.signerKeyTypeHashX, + signedPayload: _xdr["default"].SignerKey.signerKeyTypeEd25519SignedPayload + }; + var vb = _strkey.StrKey.getVersionByteForPrefix(address); + var encoder = signerKeyMap[vb]; + if (!encoder) { + throw new Error("invalid signer key type (".concat(vb, ")")); + } + var raw = (0, _strkey.decodeCheck)(vb, address); + switch (vb) { + case 'signedPayload': + return encoder(new _xdr["default"].SignerKeyEd25519SignedPayload({ + ed25519: raw.slice(0, 32), + payload: raw.slice(32 + 4) + })); + case 'ed25519PublicKey': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + default: + return encoder(raw); + } + } + + /** + * Encodes a signer key into its StrKey equivalent. + * + * @param {xdr.SignerKey} signerKey the signer + * @returns {string} the StrKey representation of the signer + */ + }, { + key: "encodeSignerKey", + value: function encodeSignerKey(signerKey) { + var strkeyType; + var raw; + switch (signerKey["switch"]()) { + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519(): + strkeyType = 'ed25519PublicKey'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypePreAuthTx(): + strkeyType = 'preAuthTx'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypeHashX(): + strkeyType = 'sha256Hash'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519SignedPayload(): + strkeyType = 'signedPayload'; + raw = signerKey.ed25519SignedPayload().toXDR('raw'); + break; + default: + throw new Error("invalid SignerKey (type: ".concat(signerKey["switch"](), ")")); + } + return (0, _strkey.encodeCheck)(strkeyType, raw); + } + }]); +}(); + +/***/ }), + +/***/ 15: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.FastSigning = void 0; +exports.generate = generate; +exports.sign = sign; +exports.verify = verify; +// This module provides the signing functionality used by the stellar network +// The code below may look a little strange... this is because we try to provide +// the most efficient signing method possible. First, we try to load the +// native `sodium-native` package for node.js environments, and if that fails we +// fallback to `tweetnacl` + +var actualMethods = {}; + +/** + * Use this flag to check if fast signing (provided by `sodium-native` package) is available. + * If your app is signing a large number of transaction or verifying a large number + * of signatures make sure `sodium-native` package is installed. + */ +var FastSigning = exports.FastSigning = checkFastSigning(); +function sign(data, secretKey) { + return actualMethods.sign(data, secretKey); +} +function verify(data, signature, publicKey) { + return actualMethods.verify(data, signature, publicKey); +} +function generate(secretKey) { + return actualMethods.generate(secretKey); +} +function checkFastSigning() { + return typeof window === 'undefined' ? checkFastSigningNode() : checkFastSigningBrowser(); +} +function checkFastSigningNode() { + // NOTE: we use commonjs style require here because es6 imports + // can only occur at the top level. thanks, obama. + var sodium; + try { + // eslint-disable-next-line + sodium = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module 'sodium-native'"); e.code = 'MODULE_NOT_FOUND'; throw e; }())); + } catch (err) { + return checkFastSigningBrowser(); + } + if (!Object.keys(sodium).length) { + return checkFastSigningBrowser(); + } + actualMethods.generate = function (secretKey) { + var pk = Buffer.alloc(sodium.crypto_sign_PUBLICKEYBYTES); + var sk = Buffer.alloc(sodium.crypto_sign_SECRETKEYBYTES); + sodium.crypto_sign_seed_keypair(pk, sk, secretKey); + return pk; + }; + actualMethods.sign = function (data, secretKey) { + data = Buffer.from(data); + var signature = Buffer.alloc(sodium.crypto_sign_BYTES); + sodium.crypto_sign_detached(signature, data, secretKey); + return signature; + }; + actualMethods.verify = function (data, signature, publicKey) { + data = Buffer.from(data); + try { + return sodium.crypto_sign_verify_detached(signature, data, publicKey); + } catch (e) { + return false; + } + }; + return true; +} +function checkFastSigningBrowser() { + // fallback to `tweetnacl` if we're in the browser or + // if there was a failure installing `sodium-native` + // eslint-disable-next-line + var nacl = __webpack_require__(4940); + actualMethods.generate = function (secretKey) { + var secretKeyUint8 = new Uint8Array(secretKey); + var naclKeys = nacl.sign.keyPair.fromSeed(secretKeyUint8); + return Buffer.from(naclKeys.publicKey); + }; + actualMethods.sign = function (data, secretKey) { + data = Buffer.from(data); + data = new Uint8Array(data.toJSON().data); + secretKey = new Uint8Array(secretKey.toJSON().data); + var signature = nacl.sign.detached(data, secretKey); + return Buffer.from(signature); + }; + actualMethods.verify = function (data, signature, publicKey) { + data = Buffer.from(data); + data = new Uint8Array(data.toJSON().data); + signature = new Uint8Array(signature.toJSON().data); + publicKey = new Uint8Array(publicKey.toJSON().data); + return nacl.sign.detached.verify(data, signature, publicKey); + }; + return false; +} + +/***/ }), + +/***/ 4062: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Soroban = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/* Helper class to assist with formatting and parsing token amounts. */ +var Soroban = exports.Soroban = /*#__PURE__*/function () { + function Soroban() { + _classCallCheck(this, Soroban); + } + return _createClass(Soroban, null, [{ + key: "formatTokenAmount", + value: + /** + * Given a whole number smart contract amount of a token and an amount of + * decimal places (if the token has any), it returns a "display" value. + * + * All arithmetic inside the contract is performed on integers to avoid + * potential precision and consistency issues of floating-point. + * + * @param {string} amount the token amount you want to display + * @param {number} decimals specify how many decimal places a token has + * + * @returns {string} the display value + * @throws {TypeError} if the given amount has a decimal point already + * @example + * formatTokenAmount("123000", 4) === "12.3"; + */ + function formatTokenAmount(amount, decimals) { + if (amount.includes('.')) { + throw new TypeError('No decimals are allowed'); + } + var formatted = amount; + if (decimals > 0) { + if (decimals > formatted.length) { + formatted = ['0', formatted.toString().padStart(decimals, '0')].join('.'); + } else { + formatted = [formatted.slice(0, -decimals), formatted.slice(-decimals)].join('.'); + } + } + + // remove trailing zero if any + return formatted.replace(/(\.\d*?)0+$/, '$1'); + } + + /** + * Parse a token amount to use it on smart contract + * + * This function takes the display value and its decimals (if the token has + * any) and returns a string that'll be used within the smart contract. + * + * @param {string} value the token amount you want to use it on smart + * contract which you've been displaying in a UI + * @param {number} decimals the number of decimal places expected in the + * display value (different than the "actual" number, because suffix zeroes + * might not be present) + * + * @returns {string} the whole number token amount represented by the display + * value with the decimal places shifted over + * + * @example + * const displayValueAmount = "123.4560" + * const parsedAmtForSmartContract = parseTokenAmount(displayValueAmount, 5); + * parsedAmtForSmartContract === "12345600" + */ + }, { + key: "parseTokenAmount", + value: function parseTokenAmount(value, decimals) { + var _fraction$padEnd; + var _value$split$slice = value.split('.').slice(), + _value$split$slice2 = _toArray(_value$split$slice), + whole = _value$split$slice2[0], + fraction = _value$split$slice2[1], + rest = _value$split$slice2.slice(2); + if (rest.length) { + throw new Error("Invalid decimal value: ".concat(value)); + } + var shifted = BigInt(whole + ((_fraction$padEnd = fraction === null || fraction === void 0 ? void 0 : fraction.padEnd(decimals, '0')) !== null && _fraction$padEnd !== void 0 ? _fraction$padEnd : '0'.repeat(decimals))); + return shifted.toString(); + } + }]); +}(); + +/***/ }), + +/***/ 4842: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.SorobanDataBuilder = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Supports building {@link xdr.SorobanTransactionData} structures with various + * items set to specific values. + * + * This is recommended for when you are building + * {@link Operation.extendFootprintTtl} / {@link Operation.restoreFootprint} + * operations and need to {@link TransactionBuilder.setSorobanData} to avoid + * (re)building the entire data structure from scratch. + * + * @constructor + * + * @param {string | xdr.SorobanTransactionData} [sorobanData] either a + * base64-encoded string that represents an + * {@link xdr.SorobanTransactionData} instance or an XDR instance itself + * (it will be copied); if omitted or "falsy" (e.g. an empty string), it + * starts with an empty instance + * + * @example + * // You want to use an existing data blob but override specific parts. + * const newData = new SorobanDataBuilder(existing) + * .setReadOnly(someLedgerKeys) + * .setRefundableFee("1000") + * .build(); + * + * // You want an instance from scratch + * const newData = new SorobanDataBuilder() + * .setFootprint([someLedgerKey], []) + * .setRefundableFee("1000") + * .build(); + */ +var SorobanDataBuilder = exports.SorobanDataBuilder = /*#__PURE__*/function () { + function SorobanDataBuilder(sorobanData) { + _classCallCheck(this, SorobanDataBuilder); + _defineProperty(this, "_data", void 0); + var data; + if (!sorobanData) { + data = new _xdr["default"].SorobanTransactionData({ + resources: new _xdr["default"].SorobanResources({ + footprint: new _xdr["default"].LedgerFootprint({ + readOnly: [], + readWrite: [] + }), + instructions: 0, + readBytes: 0, + writeBytes: 0 + }), + ext: new _xdr["default"].ExtensionPoint(0), + resourceFee: new _xdr["default"].Int64(0) + }); + } else if (typeof sorobanData === 'string' || ArrayBuffer.isView(sorobanData)) { + data = SorobanDataBuilder.fromXDR(sorobanData); + } else { + data = SorobanDataBuilder.fromXDR(sorobanData.toXDR()); // copy + } + this._data = data; + } + + /** + * Decodes and builds a {@link xdr.SorobanTransactionData} instance. + * @param {Uint8Array|Buffer|string} data raw input to decode + * @returns {xdr.SorobanTransactionData} + */ + return _createClass(SorobanDataBuilder, [{ + key: "setResourceFee", + value: + /** + * Sets the resource fee portion of the Soroban data. + * @param {number | bigint | string} fee the resource fee to set (int64) + * @returns {SorobanDataBuilder} + */ + function setResourceFee(fee) { + this._data.resourceFee(new _xdr["default"].Int64(fee)); + return this; + } + + /** + * Sets up the resource metrics. + * + * You should almost NEVER need this, as its often generated / provided to you + * by transaction simulation/preflight from a Soroban RPC server. + * + * @param {number} cpuInstrs number of CPU instructions + * @param {number} readBytes number of bytes being read + * @param {number} writeBytes number of bytes being written + * + * @returns {SorobanDataBuilder} + */ + }, { + key: "setResources", + value: function setResources(cpuInstrs, readBytes, writeBytes) { + this._data.resources().instructions(cpuInstrs); + this._data.resources().readBytes(readBytes); + this._data.resources().writeBytes(writeBytes); + return this; + } + + /** + * Appends the given ledger keys to the existing storage access footprint. + * @param {xdr.LedgerKey[]} readOnly read-only keys to add + * @param {xdr.LedgerKey[]} readWrite read-write keys to add + * @returns {SorobanDataBuilder} this builder instance + */ + }, { + key: "appendFootprint", + value: function appendFootprint(readOnly, readWrite) { + return this.setFootprint(this.getReadOnly().concat(readOnly), this.getReadWrite().concat(readWrite)); + } + + /** + * Sets the storage access footprint to be a certain set of ledger keys. + * + * You can also set each field explicitly via + * {@link SorobanDataBuilder.setReadOnly} and + * {@link SorobanDataBuilder.setReadWrite} or add to the existing footprint + * via {@link SorobanDataBuilder.appendFootprint}. + * + * Passing `null|undefined` to either parameter will IGNORE the existing + * values. If you want to clear them, pass `[]`, instead. + * + * @param {xdr.LedgerKey[]|null} [readOnly] the set of ledger keys to set in + * the read-only portion of the transaction's `sorobanData`, or `null | + * undefined` to keep the existing keys + * @param {xdr.LedgerKey[]|null} [readWrite] the set of ledger keys to set in + * the read-write portion of the transaction's `sorobanData`, or `null | + * undefined` to keep the existing keys + * @returns {SorobanDataBuilder} this builder instance + */ + }, { + key: "setFootprint", + value: function setFootprint(readOnly, readWrite) { + if (readOnly !== null) { + // null means "leave me alone" + this.setReadOnly(readOnly); + } + if (readWrite !== null) { + this.setReadWrite(readWrite); + } + return this; + } + + /** + * @param {xdr.LedgerKey[]} readOnly read-only keys in the access footprint + * @returns {SorobanDataBuilder} + */ + }, { + key: "setReadOnly", + value: function setReadOnly(readOnly) { + this._data.resources().footprint().readOnly(readOnly !== null && readOnly !== void 0 ? readOnly : []); + return this; + } + + /** + * @param {xdr.LedgerKey[]} readWrite read-write keys in the access footprint + * @returns {SorobanDataBuilder} + */ + }, { + key: "setReadWrite", + value: function setReadWrite(readWrite) { + this._data.resources().footprint().readWrite(readWrite !== null && readWrite !== void 0 ? readWrite : []); + return this; + } + + /** + * @returns {xdr.SorobanTransactionData} a copy of the final data structure + */ + }, { + key: "build", + value: function build() { + return _xdr["default"].SorobanTransactionData.fromXDR(this._data.toXDR()); // clone + } + + // + // getters follow + // + + /** @returns {xdr.LedgerKey[]} the read-only storage access pattern */ + }, { + key: "getReadOnly", + value: function getReadOnly() { + return this.getFootprint().readOnly(); + } + + /** @returns {xdr.LedgerKey[]} the read-write storage access pattern */ + }, { + key: "getReadWrite", + value: function getReadWrite() { + return this.getFootprint().readWrite(); + } + + /** @returns {xdr.LedgerFootprint} the storage access pattern */ + }, { + key: "getFootprint", + value: function getFootprint() { + return this._data.resources().footprint(); + } + }], [{ + key: "fromXDR", + value: function fromXDR(data) { + return _xdr["default"].SorobanTransactionData.fromXDR(data, typeof data === 'string' ? 'base64' : 'raw'); + } + }]); +}(); + +/***/ }), + +/***/ 7120: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.StrKey = void 0; +exports.decodeCheck = decodeCheck; +exports.encodeCheck = encodeCheck; +var _base = _interopRequireDefault(__webpack_require__(5360)); +var _checksum = __webpack_require__(1346); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": ["<<", ">>", "^", "&", "&="]}] */ +var versionBytes = { + ed25519PublicKey: 6 << 3, + // G (when encoded in base32) + ed25519SecretSeed: 18 << 3, + // S + med25519PublicKey: 12 << 3, + // M + preAuthTx: 19 << 3, + // T + sha256Hash: 23 << 3, + // X + signedPayload: 15 << 3, + // P + contract: 2 << 3 // C +}; +var strkeyTypes = { + G: 'ed25519PublicKey', + S: 'ed25519SecretSeed', + M: 'med25519PublicKey', + T: 'preAuthTx', + X: 'sha256Hash', + P: 'signedPayload', + C: 'contract' +}; + +/** + * StrKey is a helper class that allows encoding and decoding Stellar keys + * to/from strings, i.e. between their binary (Buffer, xdr.PublicKey, etc.) and + * string (i.e. "GABCD...", etc.) representations. + */ +var StrKey = exports.StrKey = /*#__PURE__*/function () { + function StrKey() { + _classCallCheck(this, StrKey); + } + return _createClass(StrKey, null, [{ + key: "encodeEd25519PublicKey", + value: + /** + * Encodes `data` to strkey ed25519 public key. + * + * @param {Buffer} data raw data to encode + * @returns {string} "G..." representation of the key + */ + function encodeEd25519PublicKey(data) { + return encodeCheck('ed25519PublicKey', data); + } + + /** + * Decodes strkey ed25519 public key to raw data. + * + * If the parameter is a muxed account key ("M..."), this will only encode it + * as a basic Ed25519 key (as if in "G..." format). + * + * @param {string} data "G..." (or "M...") key representation to decode + * @returns {Buffer} raw key + */ + }, { + key: "decodeEd25519PublicKey", + value: function decodeEd25519PublicKey(data) { + return decodeCheck('ed25519PublicKey', data); + } + + /** + * Returns true if the given Stellar public key is a valid ed25519 public key. + * @param {string} publicKey public key to check + * @returns {boolean} + */ + }, { + key: "isValidEd25519PublicKey", + value: function isValidEd25519PublicKey(publicKey) { + return isValid('ed25519PublicKey', publicKey); + } + + /** + * Encodes data to strkey ed25519 seed. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeEd25519SecretSeed", + value: function encodeEd25519SecretSeed(data) { + return encodeCheck('ed25519SecretSeed', data); + } + + /** + * Decodes strkey ed25519 seed to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeEd25519SecretSeed", + value: function decodeEd25519SecretSeed(address) { + return decodeCheck('ed25519SecretSeed', address); + } + + /** + * Returns true if the given Stellar secret key is a valid ed25519 secret seed. + * @param {string} seed seed to check + * @returns {boolean} + */ + }, { + key: "isValidEd25519SecretSeed", + value: function isValidEd25519SecretSeed(seed) { + return isValid('ed25519SecretSeed', seed); + } + + /** + * Encodes data to strkey med25519 public key. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeMed25519PublicKey", + value: function encodeMed25519PublicKey(data) { + return encodeCheck('med25519PublicKey', data); + } + + /** + * Decodes strkey med25519 public key to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeMed25519PublicKey", + value: function decodeMed25519PublicKey(address) { + return decodeCheck('med25519PublicKey', address); + } + + /** + * Returns true if the given Stellar public key is a valid med25519 public key. + * @param {string} publicKey public key to check + * @returns {boolean} + */ + }, { + key: "isValidMed25519PublicKey", + value: function isValidMed25519PublicKey(publicKey) { + return isValid('med25519PublicKey', publicKey); + } + + /** + * Encodes data to strkey preAuthTx. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodePreAuthTx", + value: function encodePreAuthTx(data) { + return encodeCheck('preAuthTx', data); + } + + /** + * Decodes strkey PreAuthTx to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodePreAuthTx", + value: function decodePreAuthTx(address) { + return decodeCheck('preAuthTx', address); + } + + /** + * Encodes data to strkey sha256 hash. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeSha256Hash", + value: function encodeSha256Hash(data) { + return encodeCheck('sha256Hash', data); + } + + /** + * Decodes strkey sha256 hash to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeSha256Hash", + value: function decodeSha256Hash(address) { + return decodeCheck('sha256Hash', address); + } + + /** + * Encodes raw data to strkey signed payload (P...). + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeSignedPayload", + value: function encodeSignedPayload(data) { + return encodeCheck('signedPayload', data); + } + + /** + * Decodes strkey signed payload (P...) to raw data. + * @param {string} address address to decode + * @returns {Buffer} + */ + }, { + key: "decodeSignedPayload", + value: function decodeSignedPayload(address) { + return decodeCheck('signedPayload', address); + } + + /** + * Checks validity of alleged signed payload (P...) strkey address. + * @param {string} address signer key to check + * @returns {boolean} + */ + }, { + key: "isValidSignedPayload", + value: function isValidSignedPayload(address) { + return isValid('signedPayload', address); + } + + /** + * Encodes raw data to strkey contract (C...). + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeContract", + value: function encodeContract(data) { + return encodeCheck('contract', data); + } + + /** + * Decodes strkey contract (C...) to raw data. + * @param {string} address address to decode + * @returns {Buffer} + */ + }, { + key: "decodeContract", + value: function decodeContract(address) { + return decodeCheck('contract', address); + } + + /** + * Checks validity of alleged contract (C...) strkey address. + * @param {string} address signer key to check + * @returns {boolean} + */ + }, { + key: "isValidContract", + value: function isValidContract(address) { + return isValid('contract', address); + } + }, { + key: "getVersionByteForPrefix", + value: function getVersionByteForPrefix(address) { + return strkeyTypes[address[0]]; + } + }]); +}(); +/** + * Sanity-checks whether or not a strkey *appears* valid. + * + * @param {string} versionByteName the type of strkey to expect in `encoded` + * @param {string} encoded the strkey to validate + * + * @return {Boolean} whether or not the `encoded` strkey appears valid for the + * `versionByteName` strkey type (see `versionBytes`, above). + * + * @note This isn't a *definitive* check of validity, but rather a best-effort + * check based on (a) input length, (b) whether or not it can be decoded, + * and (c) output length. + */ +function isValid(versionByteName, encoded) { + if (typeof encoded !== 'string') { + return false; + } + + // basic length checks on the strkey lengths + switch (versionByteName) { + case 'ed25519PublicKey': // falls through + case 'ed25519SecretSeed': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + case 'contract': + if (encoded.length !== 56) { + return false; + } + break; + case 'med25519PublicKey': + if (encoded.length !== 69) { + return false; + } + break; + case 'signedPayload': + if (encoded.length < 56 || encoded.length > 165) { + return false; + } + break; + default: + return false; + } + var decoded = ''; + try { + decoded = decodeCheck(versionByteName, encoded); + } catch (err) { + return false; + } + + // basic length checks on the resulting buffer sizes + switch (versionByteName) { + case 'ed25519PublicKey': // falls through + case 'ed25519SecretSeed': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + case 'contract': + return decoded.length === 32; + case 'med25519PublicKey': + return decoded.length === 40; + // +8 bytes for the ID + + case 'signedPayload': + return ( + // 32 for the signer, +4 for the payload size, then either +4 for the + // min or +64 for the max payload + decoded.length >= 32 + 4 + 4 && decoded.length <= 32 + 4 + 64 + ); + default: + return false; + } +} +function decodeCheck(versionByteName, encoded) { + if (typeof encoded !== 'string') { + throw new TypeError('encoded argument must be of type String'); + } + var decoded = _base["default"].decode(encoded); + var versionByte = decoded[0]; + var payload = decoded.slice(0, -2); + var data = payload.slice(1); + var checksum = decoded.slice(-2); + if (encoded !== _base["default"].encode(decoded)) { + throw new Error('invalid encoded string'); + } + var expectedVersion = versionBytes[versionByteName]; + if (expectedVersion === undefined) { + throw new Error("".concat(versionByteName, " is not a valid version byte name. ") + "Expected one of ".concat(Object.keys(versionBytes).join(', '))); + } + if (versionByte !== expectedVersion) { + throw new Error("invalid version byte. expected ".concat(expectedVersion, ", got ").concat(versionByte)); + } + var expectedChecksum = calculateChecksum(payload); + if (!(0, _checksum.verifyChecksum)(expectedChecksum, checksum)) { + throw new Error("invalid checksum"); + } + return Buffer.from(data); +} +function encodeCheck(versionByteName, data) { + if (data === null || data === undefined) { + throw new Error('cannot encode null data'); + } + var versionByte = versionBytes[versionByteName]; + if (versionByte === undefined) { + throw new Error("".concat(versionByteName, " is not a valid version byte name. ") + "Expected one of ".concat(Object.keys(versionBytes).join(', '))); + } + data = Buffer.from(data); + var versionBuffer = Buffer.from([versionByte]); + var payload = Buffer.concat([versionBuffer, data]); + var checksum = Buffer.from(calculateChecksum(payload)); + var unencoded = Buffer.concat([payload, checksum]); + return _base["default"].encode(unencoded); +} + +// Computes the CRC16-XModem checksum of `payload` in little-endian order +function calculateChecksum(payload) { + var crcTable = [0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0]; + var crc16 = 0x0; + for (var i = 0; i < payload.length; i += 1) { + var _byte = payload[i]; + var lookupIndex = crc16 >> 8 ^ _byte; + crc16 = crc16 << 8 ^ crcTable[lookupIndex]; + crc16 &= 0xffff; + } + var checksum = new Uint8Array(2); + checksum[0] = crc16 & 0xff; + checksum[1] = crc16 >> 8 & 0xff; + return checksum; +} + +/***/ }), + +/***/ 380: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Transaction = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _hashing = __webpack_require__(9152); +var _strkey = __webpack_require__(7120); +var _operation = __webpack_require__(7237); +var _memo = __webpack_require__(4172); +var _transaction_base = __webpack_require__(3758); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Use {@link TransactionBuilder} to build a transaction object. If you have an + * object or base64-encoded string of the transaction envelope XDR, use {@link + * TransactionBuilder.fromXDR}. + * + * Once a Transaction has been created, its attributes and operations should not + * be changed. You should only add signatures (using {@link Transaction#sign}) + * to a Transaction object before submitting to the network or forwarding on to + * additional signers. + * + * @constructor + * + * @param {string|xdr.TransactionEnvelope} envelope - transaction envelope + * object or base64 encoded string + * @param {string} [networkPassphrase] - passphrase of the target stellar + * network (e.g. "Public Global Stellar Network ; September 2015") + * + * @extends TransactionBase + */ +var Transaction = exports.Transaction = /*#__PURE__*/function (_TransactionBase) { + function Transaction(envelope, networkPassphrase) { + var _this; + _classCallCheck(this, Transaction); + if (typeof envelope === 'string') { + var buffer = Buffer.from(envelope, 'base64'); + envelope = _xdr["default"].TransactionEnvelope.fromXDR(buffer); + } + var envelopeType = envelope["switch"](); + if (!(envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTxV0() || envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTx())) { + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ".concat(envelopeType.name, ".")); + } + var txEnvelope = envelope.value(); + var tx = txEnvelope.tx(); + var fee = tx.fee().toString(); + var signatures = (txEnvelope.signatures() || []).slice(); + _this = _callSuper(this, Transaction, [tx, signatures, fee, networkPassphrase]); + _this._envelopeType = envelopeType; + _this._memo = tx.memo(); + _this._sequence = tx.seqNum().toString(); + switch (_this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + _this._source = _strkey.StrKey.encodeEd25519PublicKey(_this.tx.sourceAccountEd25519()); + break; + default: + _this._source = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(_this.tx.sourceAccount()); + break; + } + var cond = null; + var timeBounds = null; + switch (_this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + timeBounds = tx.timeBounds(); + break; + case _xdr["default"].EnvelopeType.envelopeTypeTx(): + switch (tx.cond()["switch"]()) { + case _xdr["default"].PreconditionType.precondTime(): + timeBounds = tx.cond().timeBounds(); + break; + case _xdr["default"].PreconditionType.precondV2(): + cond = tx.cond().v2(); + timeBounds = cond.timeBounds(); + break; + default: + break; + } + break; + default: + break; + } + if (timeBounds) { + _this._timeBounds = { + minTime: timeBounds.minTime().toString(), + maxTime: timeBounds.maxTime().toString() + }; + } + if (cond) { + var ledgerBounds = cond.ledgerBounds(); + if (ledgerBounds) { + _this._ledgerBounds = { + minLedger: ledgerBounds.minLedger(), + maxLedger: ledgerBounds.maxLedger() + }; + } + var minSeq = cond.minSeqNum(); + if (minSeq) { + _this._minAccountSequence = minSeq.toString(); + } + _this._minAccountSequenceAge = cond.minSeqAge(); + _this._minAccountSequenceLedgerGap = cond.minSeqLedgerGap(); + _this._extraSigners = cond.extraSigners(); + } + var operations = tx.operations() || []; + _this._operations = operations.map(function (op) { + return _operation.Operation.fromXDRObject(op); + }); + return _this; + } + + /** + * @type {object} + * @property {string} 64 bit unix timestamp + * @property {string} 64 bit unix timestamp + * @readonly + */ + _inherits(Transaction, _TransactionBase); + return _createClass(Transaction, [{ + key: "timeBounds", + get: function get() { + return this._timeBounds; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {object} + * @property {number} minLedger - smallest ledger bound (uint32) + * @property {number} maxLedger - largest ledger bound (or 0 for inf) + * @readonly + */ + }, { + key: "ledgerBounds", + get: function get() { + return this._ledgerBounds; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 64 bit account sequence + * @readonly + * @type {string} + */ + }, { + key: "minAccountSequence", + get: function get() { + return this._minAccountSequence; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 64 bit number of seconds + * @type {number} + * @readonly + */ + }, { + key: "minAccountSequenceAge", + get: function get() { + return this._minAccountSequenceAge; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 32 bit number of ledgers + * @type {number} + * @readonly + */ + }, { + key: "minAccountSequenceLedgerGap", + get: function get() { + return this._minAccountSequenceLedgerGap; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * array of extra signers ({@link StrKey}s) + * @type {string[]} + * @readonly + */ + }, { + key: "extraSigners", + get: function get() { + return this._extraSigners; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "sequence", + get: function get() { + return this._sequence; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "source", + get: function get() { + return this._source; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {Array.} + * @readonly + */ + }, { + key: "operations", + get: function get() { + return this._operations; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "memo", + get: function get() { + return _memo.Memo.fromXDRObject(this._memo); + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * Returns the "signature base" of this transaction, which is the value + * that, when hashed, should be signed to create a signature that + * validators on the Stellar Network will accept. + * + * It is composed of a 4 prefix bytes followed by the xdr-encoded form + * of this transaction. + * @returns {Buffer} + */ + }, { + key: "signatureBase", + value: function signatureBase() { + var tx = this.tx; + + // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // we need a Transaction to generate the signature base + if (this._envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTxV0()) { + tx = _xdr["default"].Transaction.fromXDR(Buffer.concat([ + // TransactionV0 is a transaction with the AccountID discriminant + // stripped off, we need to put it back to build a valid transaction + // which we can use to build a TransactionSignaturePayloadTaggedTransaction + _xdr["default"].PublicKeyType.publicKeyTypeEd25519().toXDR(), tx.toXDR()])); + } + var taggedTransaction = new _xdr["default"].TransactionSignaturePayloadTaggedTransaction.envelopeTypeTx(tx); + var txSignature = new _xdr["default"].TransactionSignaturePayload({ + networkId: _xdr["default"].Hash.fromXDR((0, _hashing.hash)(this.networkPassphrase)), + taggedTransaction: taggedTransaction + }); + return txSignature.toXDR(); + } + + /** + * To envelope returns a xdr.TransactionEnvelope which can be submitted to the network. + * @returns {xdr.TransactionEnvelope} + */ + }, { + key: "toEnvelope", + value: function toEnvelope() { + var rawTx = this.tx.toXDR(); + var signatures = this.signatures.slice(); // make a copy of the signatures + + var envelope; + switch (this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTxV0(new _xdr["default"].TransactionV0Envelope({ + tx: _xdr["default"].TransactionV0.fromXDR(rawTx), + // make a copy of tx + signatures: signatures + })); + break; + case _xdr["default"].EnvelopeType.envelopeTypeTx(): + envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: _xdr["default"].Transaction.fromXDR(rawTx), + // make a copy of tx + signatures: signatures + })); + break; + default: + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ".concat(this._envelopeType.name, ".")); + } + return envelope; + } + + /** + * Calculate the claimable balance ID for an operation within the transaction. + * + * @param {integer} opIndex the index of the CreateClaimableBalance op + * @returns {string} a hex string representing the claimable balance ID + * + * @throws {RangeError} for invalid `opIndex` value + * @throws {TypeError} if op at `opIndex` is not `CreateClaimableBalance` + * @throws for general XDR un/marshalling failures + * + * @see https://github.com/stellar/go/blob/d712346e61e288d450b0c08038c158f8848cc3e4/txnbuild/transaction.go#L392-L435 + * + */ + }, { + key: "getClaimableBalanceId", + value: function getClaimableBalanceId(opIndex) { + // Validate and then extract the operation from the transaction. + if (!Number.isInteger(opIndex) || opIndex < 0 || opIndex >= this.operations.length) { + throw new RangeError('invalid operation index'); + } + var op = this.operations[opIndex]; + try { + op = _operation.Operation.createClaimableBalance(op); + } catch (err) { + throw new TypeError("expected createClaimableBalance, got ".concat(op.type, ": ").concat(err)); + } + + // Always use the transaction's *unmuxed* source. + var account = _strkey.StrKey.decodeEd25519PublicKey((0, _decode_encode_muxed_account.extractBaseAddress)(this.source)); + var operationId = _xdr["default"].HashIdPreimage.envelopeTypeOpId(new _xdr["default"].HashIdPreimageOperationId({ + sourceAccount: _xdr["default"].AccountId.publicKeyTypeEd25519(account), + seqNum: _xdr["default"].SequenceNumber.fromString(this.sequence), + opNum: opIndex + })); + var opIdHash = (0, _hashing.hash)(operationId.toXDR('raw')); + var balanceId = _xdr["default"].ClaimableBalanceId.claimableBalanceIdTypeV0(opIdHash); + return balanceId.toXDR('hex'); + } + }]); +}(_transaction_base.TransactionBase); + +/***/ }), + +/***/ 3758: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.TransactionBase = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _hashing = __webpack_require__(9152); +var _keypair = __webpack_require__(6691); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * @ignore + */ +var TransactionBase = exports.TransactionBase = /*#__PURE__*/function () { + function TransactionBase(tx, signatures, fee, networkPassphrase) { + _classCallCheck(this, TransactionBase); + if (typeof networkPassphrase !== 'string') { + throw new Error("Invalid passphrase provided to Transaction: expected a string but got a ".concat(_typeof(networkPassphrase))); + } + this._networkPassphrase = networkPassphrase; + this._tx = tx; + this._signatures = signatures; + this._fee = fee; + } + + /** + * @type {Array.} + * @readonly + */ + return _createClass(TransactionBase, [{ + key: "signatures", + get: function get() { + return this._signatures; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + }, { + key: "tx", + get: function get() { + return this._tx; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "fee", + get: function get() { + return this._fee; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "networkPassphrase", + get: function get() { + return this._networkPassphrase; + }, + set: function set(networkPassphrase) { + this._networkPassphrase = networkPassphrase; + } + + /** + * Signs the transaction with the given {@link Keypair}. + * @param {...Keypair} keypairs Keypairs of signers + * @returns {void} + */ + }, { + key: "sign", + value: function sign() { + var _this = this; + var txHash = this.hash(); + for (var _len = arguments.length, keypairs = new Array(_len), _key = 0; _key < _len; _key++) { + keypairs[_key] = arguments[_key]; + } + keypairs.forEach(function (kp) { + var sig = kp.signDecorated(txHash); + _this.signatures.push(sig); + }); + } + + /** + * Signs a transaction with the given {@link Keypair}. Useful if someone sends + * you a transaction XDR for you to sign and return (see + * [addSignature](#addSignature) for more information). + * + * When you get a transaction XDR to sign.... + * - Instantiate a `Transaction` object with the XDR + * - Use {@link Keypair} to generate a keypair object for your Stellar seed. + * - Run `getKeypairSignature` with that keypair + * - Send back the signature along with your publicKey (not your secret seed!) + * + * Example: + * ```javascript + * // `transactionXDR` is a string from the person generating the transaction + * const transaction = new Transaction(transactionXDR, networkPassphrase); + * const keypair = Keypair.fromSecret(myStellarSeed); + * return transaction.getKeypairSignature(keypair); + * ``` + * + * @param {Keypair} keypair Keypair of signer + * @returns {string} Signature string + */ + }, { + key: "getKeypairSignature", + value: function getKeypairSignature(keypair) { + return keypair.sign(this.hash()).toString('base64'); + } + + /** + * Add a signature to the transaction. Useful when a party wants to pre-sign + * a transaction but doesn't want to give access to their secret keys. + * This will also verify whether the signature is valid. + * + * Here's how you would use this feature to solicit multiple signatures. + * - Use `TransactionBuilder` to build a new transaction. + * - Make sure to set a long enough timeout on that transaction to give your + * signers enough time to sign! + * - Once you build the transaction, use `transaction.toXDR()` to get the + * base64-encoded XDR string. + * - _Warning!_ Once you've built this transaction, don't submit any other + * transactions onto your account! Doing so will invalidate this pre-compiled + * transaction! + * - Send this XDR string to your other parties. They can use the instructions + * for [getKeypairSignature](#getKeypairSignature) to sign the transaction. + * - They should send you back their `publicKey` and the `signature` string + * from [getKeypairSignature](#getKeypairSignature), both of which you pass to + * this function. + * + * @param {string} publicKey The public key of the signer + * @param {string} signature The base64 value of the signature XDR + * @returns {void} + */ + }, { + key: "addSignature", + value: function addSignature() { + var publicKey = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var signature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + if (!signature || typeof signature !== 'string') { + throw new Error('Invalid signature'); + } + if (!publicKey || typeof publicKey !== 'string') { + throw new Error('Invalid publicKey'); + } + var keypair; + var hint; + var signatureBuffer = Buffer.from(signature, 'base64'); + try { + keypair = _keypair.Keypair.fromPublicKey(publicKey); + hint = keypair.signatureHint(); + } catch (e) { + throw new Error('Invalid publicKey'); + } + if (!keypair.verify(this.hash(), signatureBuffer)) { + throw new Error('Invalid signature'); + } + this.signatures.push(new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signatureBuffer + })); + } + + /** + * Add a decorated signature directly to the transaction envelope. + * + * @param {xdr.DecoratedSignature} signature raw signature to add + * @returns {void} + * + * @see Keypair.signDecorated + * @see Keypair.signPayloadDecorated + */ + }, { + key: "addDecoratedSignature", + value: function addDecoratedSignature(signature) { + this.signatures.push(signature); + } + + /** + * Add `hashX` signer preimage as signature. + * @param {Buffer|String} preimage Preimage of hash used as signer + * @returns {void} + */ + }, { + key: "signHashX", + value: function signHashX(preimage) { + if (typeof preimage === 'string') { + preimage = Buffer.from(preimage, 'hex'); + } + if (preimage.length > 64) { + throw new Error('preimage cannnot be longer than 64 bytes'); + } + var signature = preimage; + var hashX = (0, _hashing.hash)(preimage); + var hint = hashX.slice(hashX.length - 4); + this.signatures.push(new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signature + })); + } + + /** + * Returns a hash for this transaction, suitable for signing. + * @returns {Buffer} + */ + }, { + key: "hash", + value: function hash() { + return (0, _hashing.hash)(this.signatureBase()); + } + }, { + key: "signatureBase", + value: function signatureBase() { + throw new Error('Implement in subclass'); + } + }, { + key: "toEnvelope", + value: function toEnvelope() { + throw new Error('Implement in subclass'); + } + + /** + * Get the transaction envelope as a base64-encoded string + * @returns {string} XDR string + */ + }, { + key: "toXDR", + value: function toXDR() { + return this.toEnvelope().toXDR().toString('base64'); + } + }]); +}(); + +/***/ }), + +/***/ 6396: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.TransactionBuilder = exports.TimeoutInfinite = exports.BASE_FEE = void 0; +exports.isValidDate = isValidDate; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _account = __webpack_require__(2135); +var _muxed_account = __webpack_require__(2243); +var _decode_encode_muxed_account = __webpack_require__(6160); +var _transaction = __webpack_require__(380); +var _fee_bump_transaction = __webpack_require__(9260); +var _sorobandata_builder = __webpack_require__(4842); +var _strkey = __webpack_require__(7120); +var _signerkey = __webpack_require__(225); +var _memo = __webpack_require__(4172); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Minimum base fee for transactions. If this fee is below the network + * minimum, the transaction will fail. The more operations in the + * transaction, the greater the required fee. Use {@link + * Server#fetchBaseFee} to get an accurate value of minimum transaction + * fee on the network. + * + * @constant + * @see [Fees](https://developers.stellar.org/docs/glossary/fees/) + */ +var BASE_FEE = exports.BASE_FEE = '100'; // Stroops + +/** + * @constant + * @see {@link TransactionBuilder#setTimeout} + * @see [Timeout](https://developers.stellar.org/api/resources/transactions/post/) + */ +var TimeoutInfinite = exports.TimeoutInfinite = 0; + +/** + *

Transaction builder helps constructs a new `{@link Transaction}` using the + * given {@link Account} as the transaction's "source account". The transaction + * will use the current sequence number of the given account as its sequence + * number and increment the given account's sequence number by one. The given + * source account must include a private key for signing the transaction or an + * error will be thrown.

+ * + *

Operations can be added to the transaction via their corresponding builder + * methods, and each returns the TransactionBuilder object so they can be + * chained together. After adding the desired operations, call the `build()` + * method on the `TransactionBuilder` to return a fully constructed `{@link + * Transaction}` that can be signed. The returned transaction will contain the + * sequence number of the source account and include the signature from the + * source account.

+ * + *

Be careful about unsubmitted transactions! When you build + * a transaction, `stellar-sdk` automatically increments the source account's + * sequence number. If you end up not submitting this transaction and submitting + * another one instead, it'll fail due to the sequence number being wrong. So if + * you decide not to use a built transaction, make sure to update the source + * account's sequence number with + * [Server.loadAccount](https://stellar.github.io/js-stellar-sdk/Server.html#loadAccount) + * before creating another transaction.

+ * + *

The following code example creates a new transaction with {@link + * Operation.createAccount} and {@link Operation.payment} operations. The + * Transaction's source account first funds `destinationA`, then sends a payment + * to `destinationB`. The built transaction is then signed by + * `sourceKeypair`.

+ * + * ``` + * var transaction = new TransactionBuilder(source, { fee, networkPassphrase: Networks.TESTNET }) + * .addOperation(Operation.createAccount({ + * destination: destinationA, + * startingBalance: "20" + * })) // <- funds and creates destinationA + * .addOperation(Operation.payment({ + * destination: destinationB, + * amount: "100", + * asset: Asset.native() + * })) // <- sends 100 XLM to destinationB + * .setTimeout(30) + * .build(); + * + * transaction.sign(sourceKeypair); + * ``` + * + * @constructor + * + * @param {Account} sourceAccount - source account for this transaction + * @param {object} opts - Options object + * @param {string} opts.fee - max fee you're willing to pay per + * operation in this transaction (**in stroops**) + * + * @param {object} [opts.timebounds] - timebounds for the + * validity of this transaction + * @param {number|string|Date} [opts.timebounds.minTime] - 64-bit UNIX + * timestamp or Date object + * @param {number|string|Date} [opts.timebounds.maxTime] - 64-bit UNIX + * timestamp or Date object + * @param {object} [opts.ledgerbounds] - ledger bounds for the + * validity of this transaction + * @param {number} [opts.ledgerbounds.minLedger] - number of the minimum + * ledger sequence + * @param {number} [opts.ledgerbounds.maxLedger] - number of the maximum + * ledger sequence + * @param {string} [opts.minAccountSequence] - number for + * the minimum account sequence + * @param {number} [opts.minAccountSequenceAge] - number of + * seconds for the minimum account sequence age + * @param {number} [opts.minAccountSequenceLedgerGap] - number of + * ledgers for the minimum account sequence ledger gap + * @param {string[]} [opts.extraSigners] - list of the extra signers + * required for this transaction + * @param {Memo} [opts.memo] - memo for the transaction + * @param {string} [opts.networkPassphrase] passphrase of the + * target Stellar network (e.g. "Public Global Stellar Network ; September + * 2015" for the pubnet) + * @param {xdr.SorobanTransactionData | string} [opts.sorobanData] - an + * optional instance of {@link xdr.SorobanTransactionData} to be set as the + * internal `Transaction.Ext.SorobanData` field (either the xdr object or a + * base64 string). In the case of Soroban transactions, this can be obtained + * from a prior simulation of the transaction with a contract invocation and + * provides necessary resource estimations. You can also use + * {@link SorobanDataBuilder} to construct complicated combinations of + * parameters without mucking with XDR directly. **Note:** For + * non-contract(non-Soroban) transactions, this has no effect. + */ +var TransactionBuilder = exports.TransactionBuilder = /*#__PURE__*/function () { + function TransactionBuilder(sourceAccount) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, TransactionBuilder); + if (!sourceAccount) { + throw new Error('must specify source account for the transaction'); + } + if (opts.fee === undefined) { + throw new Error('must specify fee for the transaction (in stroops)'); + } + this.source = sourceAccount; + this.operations = []; + this.baseFee = opts.fee; + this.timebounds = opts.timebounds ? _objectSpread({}, opts.timebounds) : null; + this.ledgerbounds = opts.ledgerbounds ? _objectSpread({}, opts.ledgerbounds) : null; + this.minAccountSequence = opts.minAccountSequence || null; + this.minAccountSequenceAge = opts.minAccountSequenceAge || null; + this.minAccountSequenceLedgerGap = opts.minAccountSequenceLedgerGap || null; + this.extraSigners = opts.extraSigners ? _toConsumableArray(opts.extraSigners) : null; + this.memo = opts.memo || _memo.Memo.none(); + this.networkPassphrase = opts.networkPassphrase || null; + this.sorobanData = opts.sorobanData ? new _sorobandata_builder.SorobanDataBuilder(opts.sorobanData).build() : null; + } + + /** + * Creates a builder instance using an existing {@link Transaction} as a + * template, ignoring any existing envelope signatures. + * + * Note that the sequence number WILL be cloned, so EITHER this transaction or + * the one it was cloned from will be valid. This is useful in situations + * where you are constructing a transaction in pieces and need to make + * adjustments as you go (for example, when filling out Soroban resource + * information). + * + * @param {Transaction} tx a "template" transaction to clone exactly + * @param {object} [opts] additional options to override the clone, e.g. + * {fee: '1000'} will override the existing base fee derived from `tx` (see + * the {@link TransactionBuilder} constructor for detailed options) + * + * @returns {TransactionBuilder} a "prepared" builder instance with the same + * configuration and operations as the given transaction + * + * @warning This does not clone the transaction's + * {@link xdr.SorobanTransactionData} (if applicable), use + * {@link SorobanDataBuilder} and {@link TransactionBuilder.setSorobanData} + * as needed, instead.. + * + * @todo This cannot clone {@link FeeBumpTransaction}s, yet. + */ + return _createClass(TransactionBuilder, [{ + key: "addOperation", + value: + /** + * Adds an operation to the transaction. + * + * @param {xdr.Operation} operation The xdr operation object, use {@link + * Operation} static methods. + * + * @returns {TransactionBuilder} + */ + function addOperation(operation) { + this.operations.push(operation); + return this; + } + + /** + * Adds an operation to the transaction at a specific index. + * + * @param {xdr.Operation} operation - The xdr operation object to add, use {@link Operation} static methods. + * @param {number} index - The index at which to insert the operation. + * + * @returns {TransactionBuilder} - The TransactionBuilder instance for method chaining. + */ + }, { + key: "addOperationAt", + value: function addOperationAt(operation, index) { + this.operations.splice(index, 0, operation); + return this; + } + + /** + * Removes the operations from the builder (useful when cloning). + * @returns {TransactionBuilder} this builder instance + */ + }, { + key: "clearOperations", + value: function clearOperations() { + this.operations = []; + return this; + } + + /** + * Removes the operation at the specified index from the transaction. + * + * @param {number} index - The index of the operation to remove. + * + * @returns {TransactionBuilder} The TransactionBuilder instance for method chaining. + */ + }, { + key: "clearOperationAt", + value: function clearOperationAt(index) { + this.operations.splice(index, 1); + return this; + } + + /** + * Adds a memo to the transaction. + * @param {Memo} memo {@link Memo} object + * @returns {TransactionBuilder} + */ + }, { + key: "addMemo", + value: function addMemo(memo) { + this.memo = memo; + return this; + } + + /** + * Sets a timeout precondition on the transaction. + * + * Because of the distributed nature of the Stellar network it is possible + * that the status of your transaction will be determined after a long time + * if the network is highly congested. If you want to be sure to receive the + * status of the transaction within a given period you should set the {@link + * TimeBounds} with `maxTime` on the transaction (this is what `setTimeout` + * does internally; if there's `minTime` set but no `maxTime` it will be + * added). + * + * A call to `TransactionBuilder.setTimeout` is **required** if Transaction + * does not have `max_time` set. If you don't want to set timeout, use + * `{@link TimeoutInfinite}`. In general you should set `{@link + * TimeoutInfinite}` only in smart contracts. + * + * Please note that Horizon may still return 504 Gateway Timeout + * error, even for short timeouts. In such case you need to resubmit the same + * transaction again without making any changes to receive a status. This + * method is using the machine system time (UTC), make sure it is set + * correctly. + * + * @param {number} timeoutSeconds Number of seconds the transaction is good. + * Can't be negative. If the value is {@link TimeoutInfinite}, the + * transaction is good indefinitely. + * + * @returns {TransactionBuilder} + * + * @see {@link TimeoutInfinite} + * @see https://developers.stellar.org/docs/tutorials/handling-errors/ + */ + }, { + key: "setTimeout", + value: function setTimeout(timeoutSeconds) { + if (this.timebounds !== null && this.timebounds.maxTime > 0) { + throw new Error('TimeBounds.max_time has been already set - setting timeout would overwrite it.'); + } + if (timeoutSeconds < 0) { + throw new Error('timeout cannot be negative'); + } + if (timeoutSeconds > 0) { + var timeoutTimestamp = Math.floor(Date.now() / 1000) + timeoutSeconds; + if (this.timebounds === null) { + this.timebounds = { + minTime: 0, + maxTime: timeoutTimestamp + }; + } else { + this.timebounds = { + minTime: this.timebounds.minTime, + maxTime: timeoutTimestamp + }; + } + } else { + this.timebounds = { + minTime: 0, + maxTime: 0 + }; + } + return this; + } + + /** + * If you want to prepare a transaction which will become valid at some point + * in the future, or be invalid after some time, you can set a timebounds + * precondition. Internally this will set the `minTime`, and `maxTime` + * preconditions. Conflicts with `setTimeout`, so use one or the other. + * + * @param {Date|number} minEpochOrDate Either a JS Date object, or a number + * of UNIX epoch seconds. The transaction is valid after this timestamp. + * Can't be negative. If the value is `0`, the transaction is valid + * immediately. + * @param {Date|number} maxEpochOrDate Either a JS Date object, or a number + * of UNIX epoch seconds. The transaction is valid until this timestamp. + * Can't be negative. If the value is `0`, the transaction is valid + * indefinitely. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setTimebounds", + value: function setTimebounds(minEpochOrDate, maxEpochOrDate) { + // Force it to a date type + if (typeof minEpochOrDate === 'number') { + minEpochOrDate = new Date(minEpochOrDate * 1000); + } + if (typeof maxEpochOrDate === 'number') { + maxEpochOrDate = new Date(maxEpochOrDate * 1000); + } + if (this.timebounds !== null) { + throw new Error('TimeBounds has been already set - setting timebounds would overwrite it.'); + } + + // Convert that date to the epoch seconds + var minTime = Math.floor(minEpochOrDate.valueOf() / 1000); + var maxTime = Math.floor(maxEpochOrDate.valueOf() / 1000); + if (minTime < 0) { + throw new Error('min_time cannot be negative'); + } + if (maxTime < 0) { + throw new Error('max_time cannot be negative'); + } + if (maxTime > 0 && minTime > maxTime) { + throw new Error('min_time cannot be greater than max_time'); + } + this.timebounds = { + minTime: minTime, + maxTime: maxTime + }; + return this; + } + + /** + * If you want to prepare a transaction which will only be valid within some + * range of ledgers, you can set a ledgerbounds precondition. + * Internally this will set the `minLedger` and `maxLedger` preconditions. + * + * @param {number} minLedger The minimum ledger this transaction is valid at + * or after. Cannot be negative. If the value is `0` (the default), the + * transaction is valid immediately. + * + * @param {number} maxLedger The maximum ledger this transaction is valid + * before. Cannot be negative. If the value is `0`, the transaction is + * valid indefinitely. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setLedgerbounds", + value: function setLedgerbounds(minLedger, maxLedger) { + if (this.ledgerbounds !== null) { + throw new Error('LedgerBounds has been already set - setting ledgerbounds would overwrite it.'); + } + if (minLedger < 0) { + throw new Error('min_ledger cannot be negative'); + } + if (maxLedger < 0) { + throw new Error('max_ledger cannot be negative'); + } + if (maxLedger > 0 && minLedger > maxLedger) { + throw new Error('min_ledger cannot be greater than max_ledger'); + } + this.ledgerbounds = { + minLedger: minLedger, + maxLedger: maxLedger + }; + return this; + } + + /** + * If you want to prepare a transaction which will be valid only while the + * account sequence number is + * + * minAccountSequence <= sourceAccountSequence < tx.seqNum + * + * Note that after execution the account's sequence number is always raised to + * `tx.seqNum`. Internally this will set the `minAccountSequence` + * precondition. + * + * @param {string} minAccountSequence The minimum source account sequence + * number this transaction is valid for. If the value is `0` (the + * default), the transaction is valid when `sourceAccount's sequence + * number == tx.seqNum- 1`. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequence", + value: function setMinAccountSequence(minAccountSequence) { + if (this.minAccountSequence !== null) { + throw new Error('min_account_sequence has been already set - setting min_account_sequence would overwrite it.'); + } + this.minAccountSequence = minAccountSequence; + return this; + } + + /** + * For the transaction to be valid, the current ledger time must be at least + * `minAccountSequenceAge` greater than sourceAccount's `sequenceTime`. + * Internally this will set the `minAccountSequenceAge` precondition. + * + * @param {number} durationInSeconds The minimum amount of time between + * source account sequence time and the ledger time when this transaction + * will become valid. If the value is `0`, the transaction is unrestricted + * by the account sequence age. Cannot be negative. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequenceAge", + value: function setMinAccountSequenceAge(durationInSeconds) { + if (typeof durationInSeconds !== 'number') { + throw new Error('min_account_sequence_age must be a number'); + } + if (this.minAccountSequenceAge !== null) { + throw new Error('min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.'); + } + if (durationInSeconds < 0) { + throw new Error('min_account_sequence_age cannot be negative'); + } + this.minAccountSequenceAge = durationInSeconds; + return this; + } + + /** + * For the transaction to be valid, the current ledger number must be at least + * `minAccountSequenceLedgerGap` greater than sourceAccount's ledger sequence. + * Internally this will set the `minAccountSequenceLedgerGap` precondition. + * + * @param {number} gap The minimum number of ledgers between source account + * sequence and the ledger number when this transaction will become valid. + * If the value is `0`, the transaction is unrestricted by the account + * sequence ledger. Cannot be negative. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequenceLedgerGap", + value: function setMinAccountSequenceLedgerGap(gap) { + if (this.minAccountSequenceLedgerGap !== null) { + throw new Error('min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.'); + } + if (gap < 0) { + throw new Error('min_account_sequence_ledger_gap cannot be negative'); + } + this.minAccountSequenceLedgerGap = gap; + return this; + } + + /** + * For the transaction to be valid, there must be a signature corresponding to + * every Signer in this array, even if the signature is not otherwise required + * by the sourceAccount or operations. Internally this will set the + * `extraSigners` precondition. + * + * @param {string[]} extraSigners required extra signers (as {@link StrKey}s) + * + * @returns {TransactionBuilder} + */ + }, { + key: "setExtraSigners", + value: function setExtraSigners(extraSigners) { + if (!Array.isArray(extraSigners)) { + throw new Error('extra_signers must be an array of strings.'); + } + if (this.extraSigners !== null) { + throw new Error('extra_signers has been already set - setting extra_signers would overwrite it.'); + } + if (extraSigners.length > 2) { + throw new Error('extra_signers cannot be longer than 2 elements.'); + } + this.extraSigners = _toConsumableArray(extraSigners); + return this; + } + + /** + * Set network nassphrase for the Transaction that will be built. + * + * @param {string} networkPassphrase passphrase of the target Stellar + * network (e.g. "Public Global Stellar Network ; September 2015"). + * + * @returns {TransactionBuilder} + */ + }, { + key: "setNetworkPassphrase", + value: function setNetworkPassphrase(networkPassphrase) { + this.networkPassphrase = networkPassphrase; + return this; + } + + /** + * Sets the transaction's internal Soroban transaction data (resources, + * footprint, etc.). + * + * For non-contract(non-Soroban) transactions, this setting has no effect. In + * the case of Soroban transactions, this is either an instance of + * {@link xdr.SorobanTransactionData} or a base64-encoded string of said + * structure. This is usually obtained from the simulation response based on a + * transaction with a Soroban operation (e.g. + * {@link Operation.invokeHostFunction}, providing necessary resource + * and storage footprint estimations for contract invocation. + * + * @param {xdr.SorobanTransactionData | string} sorobanData the + * {@link xdr.SorobanTransactionData} as a raw xdr object or a base64 + * string to be decoded + * + * @returns {TransactionBuilder} + * @see {SorobanDataBuilder} + */ + }, { + key: "setSorobanData", + value: function setSorobanData(sorobanData) { + this.sorobanData = new _sorobandata_builder.SorobanDataBuilder(sorobanData).build(); + return this; + } + + /** + * This will build the transaction. + * It will also increment the source account's sequence number by 1. + * @returns {Transaction} This method will return the built {@link Transaction}. + */ + }, { + key: "build", + value: function build() { + var sequenceNumber = new _bignumber["default"](this.source.sequenceNumber()).plus(1); + var fee = new _bignumber["default"](this.baseFee).times(this.operations.length).toNumber(); + var attrs = { + fee: fee, + seqNum: _xdr["default"].SequenceNumber.fromString(sequenceNumber.toString()), + memo: this.memo ? this.memo.toXDRObject() : null + }; + if (this.timebounds === null || typeof this.timebounds.minTime === 'undefined' || typeof this.timebounds.maxTime === 'undefined') { + throw new Error('TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).'); + } + if (isValidDate(this.timebounds.minTime)) { + this.timebounds.minTime = this.timebounds.minTime.getTime() / 1000; + } + if (isValidDate(this.timebounds.maxTime)) { + this.timebounds.maxTime = this.timebounds.maxTime.getTime() / 1000; + } + this.timebounds.minTime = _jsXdr.UnsignedHyper.fromString(this.timebounds.minTime.toString()); + this.timebounds.maxTime = _jsXdr.UnsignedHyper.fromString(this.timebounds.maxTime.toString()); + var timeBounds = new _xdr["default"].TimeBounds(this.timebounds); + if (this.hasV2Preconditions()) { + var ledgerBounds = null; + if (this.ledgerbounds !== null) { + ledgerBounds = new _xdr["default"].LedgerBounds(this.ledgerbounds); + } + var minSeqNum = this.minAccountSequence || '0'; + minSeqNum = _xdr["default"].SequenceNumber.fromString(minSeqNum); + var minSeqAge = _jsXdr.UnsignedHyper.fromString(this.minAccountSequenceAge !== null ? this.minAccountSequenceAge.toString() : '0'); + var minSeqLedgerGap = this.minAccountSequenceLedgerGap || 0; + var extraSigners = this.extraSigners !== null ? this.extraSigners.map(_signerkey.SignerKey.decodeAddress) : []; + attrs.cond = _xdr["default"].Preconditions.precondV2(new _xdr["default"].PreconditionsV2({ + timeBounds: timeBounds, + ledgerBounds: ledgerBounds, + minSeqNum: minSeqNum, + minSeqAge: minSeqAge, + minSeqLedgerGap: minSeqLedgerGap, + extraSigners: extraSigners + })); + } else { + attrs.cond = _xdr["default"].Preconditions.precondTime(timeBounds); + } + attrs.sourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(this.source.accountId()); + + // TODO - remove this workaround for TransactionExt ts constructor + // and use the typescript generated static factory method once fixed + // https://github.com/stellar/dts-xdr/issues/5 + if (this.sorobanData) { + // @ts-ignore + attrs.ext = new _xdr["default"].TransactionExt(1, this.sorobanData); + } else { + // @ts-ignore + attrs.ext = new _xdr["default"].TransactionExt(0, _xdr["default"].Void); + } + var xtx = new _xdr["default"].Transaction(attrs); + xtx.operations(this.operations); + var txEnvelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: xtx + })); + var tx = new _transaction.Transaction(txEnvelope, this.networkPassphrase); + this.source.incrementSequenceNumber(); + return tx; + } + }, { + key: "hasV2Preconditions", + value: function hasV2Preconditions() { + return this.ledgerbounds !== null || this.minAccountSequence !== null || this.minAccountSequenceAge !== null || this.minAccountSequenceLedgerGap !== null || this.extraSigners !== null && this.extraSigners.length > 0; + } + + /** + * Builds a {@link FeeBumpTransaction}, enabling you to resubmit an existing + * transaction with a higher fee. + * + * @param {Keypair|string} feeSource - account paying for the transaction, + * in the form of either a Keypair (only the public key is used) or + * an account ID (in G... or M... form, but refer to `withMuxing`) + * @param {string} baseFee - max fee willing to pay per operation + * in inner transaction (**in stroops**) + * @param {Transaction} innerTx - {@link Transaction} to be bumped by + * the fee bump transaction + * @param {string} networkPassphrase - passphrase of the target + * Stellar network (e.g. "Public Global Stellar Network ; September 2015", + * see {@link Networks}) + * + * @todo Alongside the next major version bump, this type signature can be + * changed to be less awkward: accept a MuxedAccount as the `feeSource` + * rather than a keypair or string. + * + * @note Your fee-bump amount should be >= 10x the original fee. + * @see https://developers.stellar.org/docs/glossary/fee-bumps/#replace-by-fee + * + * @returns {FeeBumpTransaction} + */ + }], [{ + key: "cloneFrom", + value: function cloneFrom(tx) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (!(tx instanceof _transaction.Transaction)) { + throw new TypeError("expected a 'Transaction', got: ".concat(tx)); + } + var sequenceNum = (BigInt(tx.sequence) - 1n).toString(); + var source; + // rebuild the source account based on the strkey + if (_strkey.StrKey.isValidMed25519PublicKey(tx.source)) { + source = _muxed_account.MuxedAccount.fromAddress(tx.source, sequenceNum); + } else if (_strkey.StrKey.isValidEd25519PublicKey(tx.source)) { + source = new _account.Account(tx.source, sequenceNum); + } else { + throw new TypeError("unsupported tx source account: ".concat(tx.source)); + } + + // the initial fee passed to the builder gets scaled up based on the number + // of operations at the end, so we have to down-scale first + var unscaledFee = parseInt(tx.fee, 10) / tx.operations.length; + var builder = new TransactionBuilder(source, _objectSpread({ + fee: (unscaledFee || BASE_FEE).toString(), + memo: tx.memo, + networkPassphrase: tx.networkPassphrase, + timebounds: tx.timeBounds, + ledgerbounds: tx.ledgerBounds, + minAccountSequence: tx.minAccountSequence, + minAccountSequenceAge: tx.minAccountSequenceAge, + minAccountSequenceLedgerGap: tx.minAccountSequenceLedgerGap, + extraSigners: tx.extraSigners + }, opts)); + tx._tx.operations().forEach(function (op) { + return builder.addOperation(op); + }); + return builder; + } + }, { + key: "buildFeeBumpTransaction", + value: function buildFeeBumpTransaction(feeSource, baseFee, innerTx, networkPassphrase) { + var innerOps = innerTx.operations.length; + var innerBaseFeeRate = new _bignumber["default"](innerTx.fee).div(innerOps); + var base = new _bignumber["default"](baseFee); + + // The fee rate for fee bump is at least the fee rate of the inner transaction + if (base.lt(innerBaseFeeRate)) { + throw new Error("Invalid baseFee, it should be at least ".concat(innerBaseFeeRate, " stroops.")); + } + var minBaseFee = new _bignumber["default"](BASE_FEE); + + // The fee rate is at least the minimum fee + if (base.lt(minBaseFee)) { + throw new Error("Invalid baseFee, it should be at least ".concat(minBaseFee, " stroops.")); + } + var innerTxEnvelope = innerTx.toEnvelope(); + if (innerTxEnvelope["switch"]() === _xdr["default"].EnvelopeType.envelopeTypeTxV0()) { + var v0Tx = innerTxEnvelope.v0().tx(); + var v1Tx = new _xdr["default"].Transaction({ + sourceAccount: new _xdr["default"].MuxedAccount.keyTypeEd25519(v0Tx.sourceAccountEd25519()), + fee: v0Tx.fee(), + seqNum: v0Tx.seqNum(), + cond: _xdr["default"].Preconditions.precondTime(v0Tx.timeBounds()), + memo: v0Tx.memo(), + operations: v0Tx.operations(), + ext: new _xdr["default"].TransactionExt(0) + }); + innerTxEnvelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: v1Tx, + signatures: innerTxEnvelope.v0().signatures() + })); + } + var feeSourceAccount; + if (typeof feeSource === 'string') { + feeSourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(feeSource); + } else { + feeSourceAccount = feeSource.xdrMuxedAccount(); + } + var tx = new _xdr["default"].FeeBumpTransaction({ + feeSource: feeSourceAccount, + fee: _xdr["default"].Int64.fromString(base.times(innerOps + 1).toString()), + innerTx: _xdr["default"].FeeBumpTransactionInnerTx.envelopeTypeTx(innerTxEnvelope.v1()), + ext: new _xdr["default"].FeeBumpTransactionExt(0) + }); + var feeBumpTxEnvelope = new _xdr["default"].FeeBumpTransactionEnvelope({ + tx: tx, + signatures: [] + }); + var envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTxFeeBump(feeBumpTxEnvelope); + return new _fee_bump_transaction.FeeBumpTransaction(envelope, networkPassphrase); + } + + /** + * Build a {@link Transaction} or {@link FeeBumpTransaction} from an + * xdr.TransactionEnvelope. + * + * @param {string|xdr.TransactionEnvelope} envelope - The transaction envelope + * object or base64 encoded string. + * @param {string} networkPassphrase - The network passphrase of the target + * Stellar network (e.g. "Public Global Stellar Network ; September + * 2015"), see {@link Networks}. + * + * @returns {Transaction|FeeBumpTransaction} + */ + }, { + key: "fromXDR", + value: function fromXDR(envelope, networkPassphrase) { + if (typeof envelope === 'string') { + envelope = _xdr["default"].TransactionEnvelope.fromXDR(envelope, 'base64'); + } + if (envelope["switch"]() === _xdr["default"].EnvelopeType.envelopeTypeTxFeeBump()) { + return new _fee_bump_transaction.FeeBumpTransaction(envelope, networkPassphrase); + } + return new _transaction.Transaction(envelope, networkPassphrase); + } + }]); +}(); +/** + * Checks whether a provided object is a valid Date. + * @argument {Date} d date object + * @returns {boolean} + */ +function isValidDate(d) { + // isnan is okay here because it correctly checks for invalid date objects + // eslint-disable-next-line no-restricted-globals + return d instanceof Date && !isNaN(d); +} + +/***/ }), + +/***/ 1242: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _bignumber = _interopRequireDefault(__webpack_require__(1594)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var BigNumber = _bignumber["default"].clone(); +BigNumber.DEBUG = true; // gives us exceptions on bad constructor values +var _default = exports["default"] = BigNumber; + +/***/ }), + +/***/ 1346: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.verifyChecksum = verifyChecksum; +function verifyChecksum(expected, actual) { + if (expected.length !== actual.length) { + return false; + } + if (expected.length === 0) { + return true; + } + for (var i = 0; i < expected.length; i += 1) { + if (expected[i] !== actual[i]) { + return false; + } + } + return true; +} + +/***/ }), + +/***/ 4151: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.best_r = best_r; +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +// eslint-disable-next-line no-bitwise +var MAX_INT = (1 << 31 >>> 0) - 1; + +/** + * Calculates and returns the best rational approximation of the given real number. + * @private + * @param {string|number|BigNumber} rawNumber Real number + * @throws Error Throws `Error` when the best rational approximation cannot be found. + * @returns {array} first element is n (numerator), second element is d (denominator) + */ +function best_r(rawNumber) { + var number = new _bignumber["default"](rawNumber); + var a; + var f; + var fractions = [[new _bignumber["default"](0), new _bignumber["default"](1)], [new _bignumber["default"](1), new _bignumber["default"](0)]]; + var i = 2; + + // eslint-disable-next-line no-constant-condition + while (true) { + if (number.gt(MAX_INT)) { + break; + } + a = number.integerValue(_bignumber["default"].ROUND_FLOOR); + f = number.minus(a); + var h = a.times(fractions[i - 1][0]).plus(fractions[i - 2][0]); + var k = a.times(fractions[i - 1][1]).plus(fractions[i - 2][1]); + if (h.gt(MAX_INT) || k.gt(MAX_INT)) { + break; + } + fractions.push([h, k]); + if (f.eq(0)) { + break; + } + number = new _bignumber["default"](1).div(f); + i += 1; + } + var _fractions = _slicedToArray(fractions[fractions.length - 1], 2), + n = _fractions[0], + d = _fractions[1]; + if (n.isZero() || d.isZero()) { + throw new Error("Couldn't find approximation"); + } + return [n.toNumber(), d.toNumber()]; +} + +/***/ }), + +/***/ 6160: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decodeAddressToMuxedAccount = decodeAddressToMuxedAccount; +exports.encodeMuxedAccount = encodeMuxedAccount; +exports.encodeMuxedAccountToAddress = encodeMuxedAccountToAddress; +exports.extractBaseAddress = extractBaseAddress; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Converts a Stellar address (in G... or M... form) to an `xdr.MuxedAccount` + * structure, using the ed25519 representation when possible. + * + * This supports full muxed accounts, where an `M...` address will resolve to + * both its underlying `G...` address and an integer ID. + * + * @param {string} address G... or M... address to encode into XDR + * @returns {xdr.MuxedAccount} a muxed account object for this address string + */ +function decodeAddressToMuxedAccount(address) { + if (_strkey.StrKey.isValidMed25519PublicKey(address)) { + return _decodeAddressFullyToMuxedAccount(address); + } + return _xdr["default"].MuxedAccount.keyTypeEd25519(_strkey.StrKey.decodeEd25519PublicKey(address)); +} + +/** + * Converts an xdr.MuxedAccount to its StrKey representation. + * + * This returns its "M..." string representation if there is a muxing ID within + * the object and returns the "G..." representation otherwise. + * + * @param {xdr.MuxedAccount} muxedAccount Raw account to stringify + * @returns {string} Stringified G... (corresponding to the underlying pubkey) + * or M... address (corresponding to both the key and the muxed ID) + * + * @see https://stellar.org/protocol/sep-23 + */ +function encodeMuxedAccountToAddress(muxedAccount) { + if (muxedAccount["switch"]().value === _xdr["default"].CryptoKeyType.keyTypeMuxedEd25519().value) { + return _encodeMuxedAccountFullyToAddress(muxedAccount); + } + return _strkey.StrKey.encodeEd25519PublicKey(muxedAccount.ed25519()); +} + +/** + * Transform a Stellar address (G...) and an ID into its XDR representation. + * + * @param {string} address - a Stellar G... address + * @param {string} id - a Uint64 ID represented as a string + * + * @return {xdr.MuxedAccount} - XDR representation of the above muxed account + */ +function encodeMuxedAccount(address, id) { + if (!_strkey.StrKey.isValidEd25519PublicKey(address)) { + throw new Error('address should be a Stellar account ID (G...)'); + } + if (typeof id !== 'string') { + throw new Error('id should be a string representing a number (uint64)'); + } + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromString(id), + ed25519: _strkey.StrKey.decodeEd25519PublicKey(address) + })); +} + +/** + * Extracts the underlying base (G...) address from an M-address. + * @param {string} address an account address (either M... or G...) + * @return {string} a Stellar public key address (G...) + */ +function extractBaseAddress(address) { + if (_strkey.StrKey.isValidEd25519PublicKey(address)) { + return address; + } + if (!_strkey.StrKey.isValidMed25519PublicKey(address)) { + throw new TypeError("expected muxed account (M...), got ".concat(address)); + } + var muxedAccount = decodeAddressToMuxedAccount(address); + return _strkey.StrKey.encodeEd25519PublicKey(muxedAccount.med25519().ed25519()); +} + +// Decodes an "M..." account ID into its MuxedAccount object representation. +function _decodeAddressFullyToMuxedAccount(address) { + var rawBytes = _strkey.StrKey.decodeMed25519PublicKey(address); + + // Decoding M... addresses cannot be done through a simple + // MuxedAccountMed25519.fromXDR() call, because the definition is: + // + // constructor(attributes: { id: Uint64; ed25519: Buffer }); + // + // Note the ID is the first attribute. However, the ID comes *last* in the + // stringified (base32-encoded) address itself (it's the last 8-byte suffix). + // The `fromXDR()` method interprets bytes in order, so we need to parse out + // the raw binary into its requisite parts, i.e. use the MuxedAccountMed25519 + // constructor directly. + // + // Refer to https://github.com/stellar/go/blob/master/xdr/muxed_account.go#L26 + // for the Golang implementation of the M... parsing. + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromXDR(rawBytes.subarray(-8)), + ed25519: rawBytes.subarray(0, -8) + })); +} + +// Converts an xdr.MuxedAccount into its *true* "M..." string representation. +function _encodeMuxedAccountFullyToAddress(muxedAccount) { + if (muxedAccount["switch"]() === _xdr["default"].CryptoKeyType.keyTypeEd25519()) { + return encodeMuxedAccountToAddress(muxedAccount); + } + var muxed = muxedAccount.med25519(); + return _strkey.StrKey.encodeMed25519PublicKey(Buffer.concat([muxed.ed25519(), muxed.id().toXDR('raw')])); +} + +/***/ }), + +/***/ 645: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.trimEnd = void 0; +var trimEnd = exports.trimEnd = function trimEnd(input, _char) { + var isNumber = typeof input === 'number'; + var str = String(input); + while (str.endsWith(_char)) { + str = str.slice(0, -1); + } + return isNumber ? Number(str) : str; +}; + +/***/ }), + +/***/ 1918: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _curr_generated = _interopRequireDefault(__webpack_require__(7938)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var _default = exports["default"] = _curr_generated["default"]; + +/***/ }), + +/***/ 4940: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +(function(nacl) { +'use strict'; + +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ + +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; + +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; + +var _0 = new Uint8Array(16); +var _9 = new Uint8Array(32); _9[0] = 9; + +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + +function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; +} + +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; +} + +function crypto_verify_16(x, xi, y, yi) { + return vn(x,xi,y,yi,16); +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); +} + +function core_salsa20(o, p, k, c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; + + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + + o[ 4] = x1 >>> 0 & 0xff; + o[ 5] = x1 >>> 8 & 0xff; + o[ 6] = x1 >>> 16 & 0xff; + o[ 7] = x1 >>> 24 & 0xff; + + o[ 8] = x2 >>> 0 & 0xff; + o[ 9] = x2 >>> 8 & 0xff; + o[10] = x2 >>> 16 & 0xff; + o[11] = x2 >>> 24 & 0xff; + + o[12] = x3 >>> 0 & 0xff; + o[13] = x3 >>> 8 & 0xff; + o[14] = x3 >>> 16 & 0xff; + o[15] = x3 >>> 24 & 0xff; + + o[16] = x4 >>> 0 & 0xff; + o[17] = x4 >>> 8 & 0xff; + o[18] = x4 >>> 16 & 0xff; + o[19] = x4 >>> 24 & 0xff; + + o[20] = x5 >>> 0 & 0xff; + o[21] = x5 >>> 8 & 0xff; + o[22] = x5 >>> 16 & 0xff; + o[23] = x5 >>> 24 & 0xff; + + o[24] = x6 >>> 0 & 0xff; + o[25] = x6 >>> 8 & 0xff; + o[26] = x6 >>> 16 & 0xff; + o[27] = x6 >>> 24 & 0xff; + + o[28] = x7 >>> 0 & 0xff; + o[29] = x7 >>> 8 & 0xff; + o[30] = x7 >>> 16 & 0xff; + o[31] = x7 >>> 24 & 0xff; + + o[32] = x8 >>> 0 & 0xff; + o[33] = x8 >>> 8 & 0xff; + o[34] = x8 >>> 16 & 0xff; + o[35] = x8 >>> 24 & 0xff; + + o[36] = x9 >>> 0 & 0xff; + o[37] = x9 >>> 8 & 0xff; + o[38] = x9 >>> 16 & 0xff; + o[39] = x9 >>> 24 & 0xff; + + o[40] = x10 >>> 0 & 0xff; + o[41] = x10 >>> 8 & 0xff; + o[42] = x10 >>> 16 & 0xff; + o[43] = x10 >>> 24 & 0xff; + + o[44] = x11 >>> 0 & 0xff; + o[45] = x11 >>> 8 & 0xff; + o[46] = x11 >>> 16 & 0xff; + o[47] = x11 >>> 24 & 0xff; + + o[48] = x12 >>> 0 & 0xff; + o[49] = x12 >>> 8 & 0xff; + o[50] = x12 >>> 16 & 0xff; + o[51] = x12 >>> 24 & 0xff; + + o[52] = x13 >>> 0 & 0xff; + o[53] = x13 >>> 8 & 0xff; + o[54] = x13 >>> 16 & 0xff; + o[55] = x13 >>> 24 & 0xff; + + o[56] = x14 >>> 0 & 0xff; + o[57] = x14 >>> 8 & 0xff; + o[58] = x14 >>> 16 & 0xff; + o[59] = x14 >>> 24 & 0xff; + + o[60] = x15 >>> 0 & 0xff; + o[61] = x15 >>> 8 & 0xff; + o[62] = x15 >>> 16 & 0xff; + o[63] = x15 >>> 24 & 0xff; +} + +function core_hsalsa20(o,p,k,c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + + o[ 4] = x5 >>> 0 & 0xff; + o[ 5] = x5 >>> 8 & 0xff; + o[ 6] = x5 >>> 16 & 0xff; + o[ 7] = x5 >>> 24 & 0xff; + + o[ 8] = x10 >>> 0 & 0xff; + o[ 9] = x10 >>> 8 & 0xff; + o[10] = x10 >>> 16 & 0xff; + o[11] = x10 >>> 24 & 0xff; + + o[12] = x15 >>> 0 & 0xff; + o[13] = x15 >>> 8 & 0xff; + o[14] = x15 >>> 16 & 0xff; + o[15] = x15 >>> 24 & 0xff; + + o[16] = x6 >>> 0 & 0xff; + o[17] = x6 >>> 8 & 0xff; + o[18] = x6 >>> 16 & 0xff; + o[19] = x6 >>> 24 & 0xff; + + o[20] = x7 >>> 0 & 0xff; + o[21] = x7 >>> 8 & 0xff; + o[22] = x7 >>> 16 & 0xff; + o[23] = x7 >>> 24 & 0xff; + + o[24] = x8 >>> 0 & 0xff; + o[25] = x8 >>> 8 & 0xff; + o[26] = x8 >>> 16 & 0xff; + o[27] = x8 >>> 24 & 0xff; + + o[28] = x9 >>> 0 & 0xff; + o[29] = x9 >>> 8 & 0xff; + o[30] = x9 >>> 16 & 0xff; + o[31] = x9 >>> 24 & 0xff; +} + +function crypto_core_salsa20(out,inp,k,c) { + core_salsa20(out,inp,k,c); +} + +function crypto_core_hsalsa20(out,inp,k,c) { + core_hsalsa20(out,inp,k,c); +} + +var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); + // "expand 32-byte k" + +function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + mpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + } + return 0; +} + +function crypto_stream_salsa20(c,cpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = x[i]; + } + return 0; +} + +function crypto_stream(c,cpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20(c,cpos,d,sn,s); +} + +function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); +} + +/* +* Port of Andrew Moon's Poly1305-donna-16. Public domain. +* https://github.com/floodyberry/poly1305-donna +*/ + +var poly1305 = function(key) { + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.leftover = 0; + this.fin = 0; + + var t0, t1, t2, t3, t4, t5, t6, t7; + + t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; + t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = ((t4 >>> 1)) & 0x1ffe; + t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = ((t7 >>> 5)) & 0x007f; + + this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; + this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; + this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; + this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; + this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; + this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; + this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; + this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; +}; + +poly1305.prototype.blocks = function(m, mpos, bytes) { + var hibit = this.fin ? 0 : (1 << 11); + var t0, t1, t2, t3, t4, t5, t6, t7, c; + var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; + + var h0 = this.h[0], + h1 = this.h[1], + h2 = this.h[2], + h3 = this.h[3], + h4 = this.h[4], + h5 = this.h[5], + h6 = this.h[6], + h7 = this.h[7], + h8 = this.h[8], + h9 = this.h[9]; + + var r0 = this.r[0], + r1 = this.r[1], + r2 = this.r[2], + r3 = this.r[3], + r4 = this.r[4], + r5 = this.r[5], + r6 = this.r[6], + r7 = this.r[7], + r8 = this.r[8], + r9 = this.r[9]; + + while (bytes >= 16) { + t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; + t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; + t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; + h5 += ((t4 >>> 1)) & 0x1fff; + t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; + t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + h9 += ((t7 >>> 5)) | hibit; + + c = 0; + + d0 = c; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h2 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c = (d0 >>> 13); d0 &= 0x1fff; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c += (d0 >>> 13); d0 &= 0x1fff; + + d1 = c; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h2 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c = (d1 >>> 13); d1 &= 0x1fff; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c += (d1 >>> 13); d1 &= 0x1fff; + + d2 = c; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h2 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c = (d2 >>> 13); d2 &= 0x1fff; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c += (d2 >>> 13); d2 &= 0x1fff; + + d3 = c; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h2 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c = (d3 >>> 13); d3 &= 0x1fff; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c += (d3 >>> 13); d3 &= 0x1fff; + + d4 = c; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h2 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c = (d4 >>> 13); d4 &= 0x1fff; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c += (d4 >>> 13); d4 &= 0x1fff; + + d5 = c; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h2 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c = (d5 >>> 13); d5 &= 0x1fff; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c += (d5 >>> 13); d5 &= 0x1fff; + + d6 = c; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h2 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c = (d6 >>> 13); d6 &= 0x1fff; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c += (d6 >>> 13); d6 &= 0x1fff; + + d7 = c; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h2 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c = (d7 >>> 13); d7 &= 0x1fff; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c += (d7 >>> 13); d7 &= 0x1fff; + + d8 = c; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h2 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c = (d8 >>> 13); d8 &= 0x1fff; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c += (d8 >>> 13); d8 &= 0x1fff; + + d9 = c; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h2 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c = (d9 >>> 13); d9 &= 0x1fff; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c += (d9 >>> 13); d9 &= 0x1fff; + + c = (((c << 2) + c)) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = (c >>> 13); + d1 += c; + + h0 = d0; + h1 = d1; + h2 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; + + mpos += 16; + bytes -= 16; + } + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h2; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; +}; + +poly1305.prototype.finish = function(mac, macpos) { + var g = new Uint16Array(10); + var c, mask, f, i; + + if (this.leftover) { + i = this.leftover; + this.buffer[i++] = 1; + for (; i < 16; i++) this.buffer[i] = 0; + this.fin = 1; + this.blocks(this.buffer, 0, 16); + } + + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + for (i = 2; i < 10; i++) { + this.h[i] += c; + c = this.h[i] >>> 13; + this.h[i] &= 0x1fff; + } + this.h[0] += (c * 5); + c = this.h[0] >>> 13; + this.h[0] &= 0x1fff; + this.h[1] += c; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + this.h[2] += c; + + g[0] = this.h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (i = 1; i < 10; i++) { + g[i] = this.h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= (1 << 13); + + mask = (c ^ 1) - 1; + for (i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; + + this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; + this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; + this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; + this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; + this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; + this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; + this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; + this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; + + f = this.h[0] + this.pad[0]; + this.h[0] = f & 0xffff; + for (i = 1; i < 8; i++) { + f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; + this.h[i] = f & 0xffff; + } + + mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; + mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; + mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; + mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; + mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; + mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; + mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; + mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; + mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; + mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; + mac[macpos+10] = (this.h[5] >>> 0) & 0xff; + mac[macpos+11] = (this.h[5] >>> 8) & 0xff; + mac[macpos+12] = (this.h[6] >>> 0) & 0xff; + mac[macpos+13] = (this.h[6] >>> 8) & 0xff; + mac[macpos+14] = (this.h[7] >>> 0) & 0xff; + mac[macpos+15] = (this.h[7] >>> 8) & 0xff; +}; + +poly1305.prototype.update = function(m, mpos, bytes) { + var i, want; + + if (this.leftover) { + want = (16 - this.leftover); + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) + return; + this.blocks(this.buffer, 0, 16); + this.leftover = 0; + } + + if (bytes >= 16) { + want = bytes - (bytes % 16); + this.blocks(m, mpos, want); + mpos += want; + bytes -= want; + } + + if (bytes) { + for (i = 0; i < bytes; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + this.leftover += bytes; + } +}; + +function crypto_onetimeauth(out, outpos, m, mpos, n, k) { + var s = new poly1305(k); + s.update(m, mpos, n); + s.finish(out, outpos); + return 0; +} + +function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { + var x = new Uint8Array(16); + crypto_onetimeauth(x,0,m,mpos,n,k); + return crypto_verify_16(h,hpos,x,0); +} + +function crypto_secretbox(c,m,d,n,k) { + var i; + if (d < 32) return -1; + crypto_stream_xor(c,0,m,0,d,n,k); + crypto_onetimeauth(c, 16, c, 32, d - 32, c); + for (i = 0; i < 16; i++) c[i] = 0; + return 0; +} + +function crypto_secretbox_open(m,c,d,n,k) { + var i; + var x = new Uint8Array(32); + if (d < 32) return -1; + crypto_stream(x,0,32,n,k); + if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; + crypto_stream_xor(m,0,c,0,d,n,k); + for (i = 0; i < 32; i++) m[i] = 0; + return 0; +} + +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} + +function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c-1 + 37 * (c-1); +} + +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; + } +} + +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} + +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; +} + +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} + +function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +} + +function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +} + +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is + + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} + +function S(o, a) { + M(o, a, a); +} + +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; + } + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); + } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; + } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; +} + +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); +} + +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); +} + +function crypto_box_beforenm(k, y, x) { + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y); + return crypto_core_hsalsa20(k, _0, s, sigma); +} + +var crypto_box_afternm = crypto_secretbox; +var crypto_box_open_afternm = crypto_secretbox_open; + +function crypto_box(c, m, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_afternm(c, m, d, n, k); +} + +function crypto_box_open(m, c, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_open_afternm(m, c, d, n, k); +} + +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 +]; + +function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; + + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; + } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; + + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; + + // add + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // K + h = K[i*2]; + l = K[i*2+1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // w + h = wh[i%16]; + l = wl[i%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; + + // add + h = th; + l = tl; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); + + // add + h = bh3; + l = bl3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = th; + l = tl; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); + + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); + } + } + } + + // add + h = ah0; + l = al0; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[0]; + l = hl[0]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); + + h = ah1; + l = al1; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[1]; + l = hl[1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); + + h = ah2; + l = al2; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[2]; + l = hl[2]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); + + h = ah3; + l = al3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[3]; + l = hl[3]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); + + h = ah4; + l = al4; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[4]; + l = hl[4]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); + + h = ah5; + l = al5; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[5]; + l = hl[5]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); + + h = ah6; + l = al6; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[6]; + l = hl[6]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); + + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[7]; + l = hl[7]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); + + pos += 128; + n -= 128; + } + + return n; +} + +function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; + + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; + + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; + + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; + + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; + + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); + + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); + + return 0; +} + +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } +} + +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} + +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } +} + +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} + +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; + + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + scalarbase(p, d); + pack(pk, p); + + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} + +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); + +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = Math.floor((x[j] + 128) / 256); + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} + +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} + +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; + + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); + + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; + } + } + + modL(sm.subarray(32), x); + return smlen; +} + +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + return 0; +} + +function crypto_sign_open(m, sm, n, pk) { + var i; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; + + if (n < 64) return -1; + + if (unpackneg(q, pk)) return -1; + + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); + + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; + } + + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + return n; +} + +var crypto_secretbox_KEYBYTES = 32, + crypto_secretbox_NONCEBYTES = 24, + crypto_secretbox_ZEROBYTES = 32, + crypto_secretbox_BOXZEROBYTES = 16, + crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_box_BEFORENMBYTES = 32, + crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, + crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, + crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32, + crypto_hash_BYTES = 64; + +nacl.lowlevel = { + crypto_core_hsalsa20: crypto_core_hsalsa20, + crypto_stream_xor: crypto_stream_xor, + crypto_stream: crypto_stream, + crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, + crypto_stream_salsa20: crypto_stream_salsa20, + crypto_onetimeauth: crypto_onetimeauth, + crypto_onetimeauth_verify: crypto_onetimeauth_verify, + crypto_verify_16: crypto_verify_16, + crypto_verify_32: crypto_verify_32, + crypto_secretbox: crypto_secretbox, + crypto_secretbox_open: crypto_secretbox_open, + crypto_scalarmult: crypto_scalarmult, + crypto_scalarmult_base: crypto_scalarmult_base, + crypto_box_beforenm: crypto_box_beforenm, + crypto_box_afternm: crypto_box_afternm, + crypto_box: crypto_box, + crypto_box_open: crypto_box_open, + crypto_box_keypair: crypto_box_keypair, + crypto_hash: crypto_hash, + crypto_sign: crypto_sign, + crypto_sign_keypair: crypto_sign_keypair, + crypto_sign_open: crypto_sign_open, + + crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, + crypto_sign_BYTES: crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, + crypto_hash_BYTES: crypto_hash_BYTES, + + gf: gf, + D: D, + L: L, + pack25519: pack25519, + unpack25519: unpack25519, + M: M, + A: A, + S: S, + Z: Z, + pow2523: pow2523, + add: add, + set25519: set25519, + modL: modL, + scalarmult: scalarmult, + scalarbase: scalarbase, +}; + +/* High-level API */ + +function checkLengths(k, n) { + if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); +} + +function checkBoxLengths(pk, sk) { + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); +} + +function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError('unexpected type, use Uint8Array'); + } +} + +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} + +nacl.randomBytes = function(n) { + var b = new Uint8Array(n); + randombytes(b, n); + return b; +}; + +nacl.secretbox = function(msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c = new Uint8Array(m.length); + for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; + crypto_secretbox(c, m, m.length, nonce, key); + return c.subarray(crypto_secretbox_BOXZEROBYTES); +}; + +nacl.secretbox.open = function(box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m = new Uint8Array(c.length); + for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; + if (c.length < 32) return null; + if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null; + return m.subarray(crypto_secretbox_ZEROBYTES); +}; + +nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; +nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; +nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; + +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; + +nacl.scalarMult.base = function(n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; +}; + +nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; +nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; + +nacl.box = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k); +}; + +nacl.box.before = function(publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k, publicKey, secretKey); + return k; +}; + +nacl.box.after = nacl.secretbox; + +nacl.box.open = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k); +}; + +nacl.box.open.after = nacl.secretbox.open; + +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; +nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; +nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; +nacl.box.nonceLength = crypto_box_NONCEBYTES; +nacl.box.overheadLength = nacl.secretbox.overheadLength; + +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; + +nacl.sign.open = function(signedMsg, publicKey) { + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m = new Uint8Array(mlen); + for (var i = 0; i < m.length; i++) m[i] = tmp[i]; + return m; +}; + +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; + +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; + +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; +nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; +nacl.sign.seedLength = crypto_sign_SEEDBYTES; +nacl.sign.signatureLength = crypto_sign_BYTES; + +nacl.hash = function(msg) { + checkArrayTypes(msg); + var h = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h, msg, msg.length); + return h; +}; + +nacl.hash.hashLength = crypto_hash_BYTES; + +nacl.verify = function(x, y) { + checkArrayTypes(x, y); + // Zero length arguments are considered not equal. + if (x.length === 0 || y.length === 0) return false; + if (x.length !== y.length) return false; + return (vn(x, 0, y, 0, x.length) === 0) ? true : false; +}; + +nacl.setPRNG = function(fn) { + randombytes = fn; +}; + +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; + if (crypto && crypto.getRandomValues) { + // Browsers. + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } else if (true) { + // Node.js. + crypto = __webpack_require__(2894); + if (crypto && crypto.randomBytes) { + nacl.setPRNG(function(x, n) { + var i, v = crypto.randomBytes(n); + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } + } +})(); + +})( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); + + +/***/ }), + +/***/ 1924: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ StellarBase: () => (/* reexport module object */ _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2__), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ httpClient: () => (/* reexport safe */ _http_client__WEBPACK_IMPORTED_MODULE_0__.ok) +/* harmony export */ }); +/* harmony import */ var _http_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9983); +/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4356); +/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {}; +/* harmony reexport (unknown) */ for(const __WEBPACK_IMPORT_KEY__ in _index__WEBPACK_IMPORTED_MODULE_1__) if(["default","StellarBase","httpClient"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = () => _index__WEBPACK_IMPORTED_MODULE_1__[__WEBPACK_IMPORT_KEY__] +/* harmony reexport (unknown) */ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2__); +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (module.exports); + +/***/ }), + +/***/ 8732: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ T: () => (/* binding */ Config) +/* harmony export */ }); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var defaultConfig = { + allowHttp: false, + timeout: 0 +}; +var config = _objectSpread({}, defaultConfig); +var Config = function () { + function Config() { + _classCallCheck(this, Config); + } + return _createClass(Config, null, [{ + key: "setAllowHttp", + value: function setAllowHttp(value) { + config.allowHttp = value; + } + }, { + key: "setTimeout", + value: function setTimeout(value) { + config.timeout = value; + } + }, { + key: "isAllowHttp", + value: function isAllowHttp() { + return config.allowHttp; + } + }, { + key: "getTimeout", + value: function getTimeout() { + return config.timeout; + } + }, { + key: "setDefault", + value: function setDefault() { + config = _objectSpread({}, defaultConfig); + } + }]); +}(); + + +/***/ }), + +/***/ 6299: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + AssembledTransaction: () => (/* reexport */ AssembledTransaction), + Client: () => (/* reexport */ Client), + DEFAULT_TIMEOUT: () => (/* reexport */ DEFAULT_TIMEOUT), + Err: () => (/* reexport */ Err), + NULL_ACCOUNT: () => (/* reexport */ NULL_ACCOUNT), + Ok: () => (/* reexport */ Ok), + SentTransaction: () => (/* reexport */ SentTransaction), + Spec: () => (/* reexport */ Spec), + basicNodeSigner: () => (/* reexport */ basicNodeSigner) +}); + +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./src/rpc/index.ts + 3 modules +var rpc = __webpack_require__(3496); +// EXTERNAL MODULE: ./src/rpc/api.ts +var api = __webpack_require__(4076); +// EXTERNAL MODULE: ./src/rpc/transaction.ts +var transaction = __webpack_require__(8680); +;// ./src/contract/rust_result.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Ok = function () { + function Ok(value) { + _classCallCheck(this, Ok); + this.value = value; + } + return _createClass(Ok, [{ + key: "unwrapErr", + value: function unwrapErr() { + throw new Error("No error"); + } + }, { + key: "unwrap", + value: function unwrap() { + return this.value; + } + }, { + key: "isOk", + value: function isOk() { + return true; + } + }, { + key: "isErr", + value: function isErr() { + return false; + } + }]); +}(); +var Err = function () { + function Err(error) { + _classCallCheck(this, Err); + this.error = error; + } + return _createClass(Err, [{ + key: "unwrapErr", + value: function unwrapErr() { + return this.error; + } + }, { + key: "unwrap", + value: function unwrap() { + throw new Error(this.error.message); + } + }, { + key: "isOk", + value: function isOk() { + return false; + } + }, { + key: "isErr", + value: function isErr() { + return true; + } + }]); +}(); +;// ./src/contract/types.ts + +var DEFAULT_TIMEOUT = 5 * 60; +var NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; +;// ./src/contract/utils.ts +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == utils_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(utils_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function utils_typeof(o) { "@babel/helpers - typeof"; return utils_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, utils_typeof(o); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + + +function withExponentialBackoff(_x, _x2, _x3) { + return _withExponentialBackoff.apply(this, arguments); +} +function _withExponentialBackoff() { + _withExponentialBackoff = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(fn, keepWaitingIf, timeoutInSeconds) { + var exponentialFactor, + verbose, + attempts, + count, + waitUntil, + waitTime, + totalWaitTime, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + exponentialFactor = _args.length > 3 && _args[3] !== undefined ? _args[3] : 1.5; + verbose = _args.length > 4 && _args[4] !== undefined ? _args[4] : false; + attempts = []; + count = 0; + _context.t0 = attempts; + _context.next = 7; + return fn(); + case 7: + _context.t1 = _context.sent; + _context.t0.push.call(_context.t0, _context.t1); + if (keepWaitingIf(attempts[attempts.length - 1])) { + _context.next = 11; + break; + } + return _context.abrupt("return", attempts); + case 11: + waitUntil = new Date(Date.now() + timeoutInSeconds * 1000).valueOf(); + waitTime = 1000; + totalWaitTime = waitTime; + case 14: + if (!(Date.now() < waitUntil && keepWaitingIf(attempts[attempts.length - 1]))) { + _context.next = 30; + break; + } + count += 1; + if (verbose) { + console.info("Waiting ".concat(waitTime, "ms before trying again (bringing the total wait time to ").concat(totalWaitTime, "ms so far, of total ").concat(timeoutInSeconds * 1000, "ms)")); + } + _context.next = 19; + return new Promise(function (res) { + return setTimeout(res, waitTime); + }); + case 19: + waitTime *= exponentialFactor; + if (new Date(Date.now() + waitTime).valueOf() > waitUntil) { + waitTime = waitUntil - Date.now(); + if (verbose) { + console.info("was gonna wait too long; new waitTime: ".concat(waitTime, "ms")); + } + } + totalWaitTime = waitTime + totalWaitTime; + _context.t2 = attempts; + _context.next = 25; + return fn(attempts[attempts.length - 1]); + case 25: + _context.t3 = _context.sent; + _context.t2.push.call(_context.t2, _context.t3); + if (verbose && keepWaitingIf(attempts[attempts.length - 1])) { + console.info("".concat(count, ". Called ").concat(fn, "; ").concat(attempts.length, " prev attempts. Most recent: ").concat(JSON.stringify(attempts[attempts.length - 1], null, 2))); + } + _context.next = 14; + break; + case 30: + return _context.abrupt("return", attempts); + case 31: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _withExponentialBackoff.apply(this, arguments); +} +var contractErrorPattern = /Error\(Contract, #(\d+)\)/; +function implementsToString(obj) { + return utils_typeof(obj) === "object" && obj !== null && "toString" in obj; +} +function processSpecEntryStream(buffer) { + var reader = new lib.cereal.XdrReader(buffer); + var res = []; + while (!reader.eof) { + res.push(lib.xdr.ScSpecEntry.read(reader)); + } + return res; +} +function getAccount(_x4, _x5) { + return _getAccount.apply(this, arguments); +} +function _getAccount() { + _getAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(options, server) { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", options.publicKey ? server.getAccount(options.publicKey) : new lib.Account(NULL_ACCOUNT, "0")); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _getAccount.apply(this, arguments); +} +;// ./src/contract/sent_transaction.ts +var _SentTransaction; +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == sent_transaction_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function sent_transaction_typeof(o) { "@babel/helpers - typeof"; return sent_transaction_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, sent_transaction_typeof(o); } +function sent_transaction_regeneratorRuntime() { "use strict"; sent_transaction_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == sent_transaction_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(sent_transaction_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function sent_transaction_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function sent_transaction_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { sent_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { sent_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function sent_transaction_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function sent_transaction_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, sent_transaction_toPropertyKey(o.key), o); } } +function sent_transaction_createClass(e, r, t) { return r && sent_transaction_defineProperties(e.prototype, r), t && sent_transaction_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = sent_transaction_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function sent_transaction_toPropertyKey(t) { var i = sent_transaction_toPrimitive(t, "string"); return "symbol" == sent_transaction_typeof(i) ? i : i + ""; } +function sent_transaction_toPrimitive(t, r) { if ("object" != sent_transaction_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != sent_transaction_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + +var SentTransaction = function () { + function SentTransaction(assembled) { + var _this = this, + _this$assembled$optio2; + sent_transaction_classCallCheck(this, SentTransaction); + _defineProperty(this, "send", sent_transaction_asyncToGenerator(sent_transaction_regeneratorRuntime().mark(function _callee() { + var _this$assembled$optio; + var hash, timeoutInSeconds; + return sent_transaction_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return _this.server.sendTransaction(_this.assembled.signed); + case 2: + _this.sendTransactionResponse = _context.sent; + if (!(_this.sendTransactionResponse.status !== "PENDING")) { + _context.next = 5; + break; + } + throw new SentTransaction.Errors.SendFailed("Sending the transaction to the network failed!\n".concat(JSON.stringify(_this.sendTransactionResponse, null, 2))); + case 5: + hash = _this.sendTransactionResponse.hash; + timeoutInSeconds = (_this$assembled$optio = _this.assembled.options.timeoutInSeconds) !== null && _this$assembled$optio !== void 0 ? _this$assembled$optio : DEFAULT_TIMEOUT; + _context.next = 9; + return withExponentialBackoff(function () { + return _this.server.getTransaction(hash); + }, function (resp) { + return resp.status === api/* Api */.j.GetTransactionStatus.NOT_FOUND; + }, timeoutInSeconds); + case 9: + _this.getTransactionResponseAll = _context.sent; + _this.getTransactionResponse = _this.getTransactionResponseAll[_this.getTransactionResponseAll.length - 1]; + if (!(_this.getTransactionResponse.status === api/* Api */.j.GetTransactionStatus.NOT_FOUND)) { + _context.next = 13; + break; + } + throw new SentTransaction.Errors.TransactionStillPending("Waited ".concat(timeoutInSeconds, " seconds for transaction to complete, but it did not. ") + "Returning anyway. Check the transaction status manually. " + "Sent transaction: ".concat(JSON.stringify(_this.sendTransactionResponse, null, 2), "\n") + "All attempts to get the result: ".concat(JSON.stringify(_this.getTransactionResponseAll, null, 2))); + case 13: + return _context.abrupt("return", _this); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + }))); + this.assembled = assembled; + this.server = new rpc.Server(this.assembled.options.rpcUrl, { + allowHttp: (_this$assembled$optio2 = this.assembled.options.allowHttp) !== null && _this$assembled$optio2 !== void 0 ? _this$assembled$optio2 : false + }); + } + return sent_transaction_createClass(SentTransaction, [{ + key: "result", + get: function get() { + if ("getTransactionResponse" in this && this.getTransactionResponse) { + if ("returnValue" in this.getTransactionResponse) { + return this.assembled.options.parseResultXdr(this.getTransactionResponse.returnValue); + } + throw new Error("Transaction failed! Cannot parse result."); + } + if (this.sendTransactionResponse) { + var _this$sendTransaction; + var errorResult = (_this$sendTransaction = this.sendTransactionResponse.errorResult) === null || _this$sendTransaction === void 0 ? void 0 : _this$sendTransaction.result(); + if (errorResult) { + throw new SentTransaction.Errors.SendFailed("Transaction simulation looked correct, but attempting to send the transaction failed. Check `simulation` and `sendTransactionResponseAll` to troubleshoot. Decoded `sendTransactionResponse.errorResultXdr`: ".concat(errorResult)); + } + throw new SentTransaction.Errors.SendResultOnly("Transaction was sent to the network, but not yet awaited. No result to show. Await transaction completion with `getTransaction(sendTransactionResponse.hash)`"); + } + throw new Error("Sending transaction failed: ".concat(JSON.stringify(this.assembled.signed))); + } + }]); +}(); +_SentTransaction = SentTransaction; +_defineProperty(SentTransaction, "Errors", { + SendFailed: function (_Error) { + function SendFailedError() { + sent_transaction_classCallCheck(this, SendFailedError); + return _callSuper(this, SendFailedError, arguments); + } + _inherits(SendFailedError, _Error); + return sent_transaction_createClass(SendFailedError); + }(_wrapNativeSuper(Error)), + SendResultOnly: function (_Error2) { + function SendResultOnlyError() { + sent_transaction_classCallCheck(this, SendResultOnlyError); + return _callSuper(this, SendResultOnlyError, arguments); + } + _inherits(SendResultOnlyError, _Error2); + return sent_transaction_createClass(SendResultOnlyError); + }(_wrapNativeSuper(Error)), + TransactionStillPending: function (_Error3) { + function TransactionStillPendingError() { + sent_transaction_classCallCheck(this, TransactionStillPendingError); + return _callSuper(this, TransactionStillPendingError, arguments); + } + _inherits(TransactionStillPendingError, _Error3); + return sent_transaction_createClass(TransactionStillPendingError); + }(_wrapNativeSuper(Error)) +}); +_defineProperty(SentTransaction, "init", function () { + var _ref2 = sent_transaction_asyncToGenerator(sent_transaction_regeneratorRuntime().mark(function _callee2(assembled) { + var tx, sent; + return sent_transaction_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + tx = new _SentTransaction(assembled); + _context2.next = 3; + return tx.send(); + case 3: + sent = _context2.sent; + return _context2.abrupt("return", sent); + case 5: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; +}()); +;// ./src/contract/assembled_transaction.ts +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +function assembled_transaction_callSuper(t, o, e) { return o = assembled_transaction_getPrototypeOf(o), assembled_transaction_possibleConstructorReturn(t, assembled_transaction_isNativeReflectConstruct() ? Reflect.construct(o, e || [], assembled_transaction_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function assembled_transaction_possibleConstructorReturn(t, e) { if (e && ("object" == assembled_transaction_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return assembled_transaction_assertThisInitialized(t); } +function assembled_transaction_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function assembled_transaction_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && assembled_transaction_setPrototypeOf(t, e); } +function assembled_transaction_wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return assembled_transaction_wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !assembled_transaction_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return assembled_transaction_construct(t, arguments, assembled_transaction_getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), assembled_transaction_setPrototypeOf(Wrapper, t); }, assembled_transaction_wrapNativeSuper(t); } +function assembled_transaction_construct(t, e, r) { if (assembled_transaction_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && assembled_transaction_setPrototypeOf(p, r.prototype), p; } +function assembled_transaction_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (assembled_transaction_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function assembled_transaction_isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function assembled_transaction_setPrototypeOf(t, e) { return assembled_transaction_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, assembled_transaction_setPrototypeOf(t, e); } +function assembled_transaction_getPrototypeOf(t) { return assembled_transaction_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, assembled_transaction_getPrototypeOf(t); } +function assembled_transaction_typeof(o) { "@babel/helpers - typeof"; return assembled_transaction_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, assembled_transaction_typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { assembled_transaction_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function assembled_transaction_regeneratorRuntime() { "use strict"; assembled_transaction_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == assembled_transaction_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(assembled_transaction_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function assembled_transaction_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function assembled_transaction_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { assembled_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { assembled_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function assembled_transaction_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function assembled_transaction_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, assembled_transaction_toPropertyKey(o.key), o); } } +function assembled_transaction_createClass(e, r, t) { return r && assembled_transaction_defineProperties(e.prototype, r), t && assembled_transaction_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function assembled_transaction_defineProperty(e, r, t) { return (r = assembled_transaction_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function assembled_transaction_toPropertyKey(t) { var i = assembled_transaction_toPrimitive(t, "string"); return "symbol" == assembled_transaction_typeof(i) ? i : i + ""; } +function assembled_transaction_toPrimitive(t, r) { if ("object" != assembled_transaction_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != assembled_transaction_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + + + +var AssembledTransaction = function () { + function AssembledTransaction(options) { + var _this = this, + _this$options$simulat, + _this$options$allowHt; + assembled_transaction_classCallCheck(this, AssembledTransaction); + assembled_transaction_defineProperty(this, "simulate", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee() { + var _restore; + var _ref2, + restore, + account, + result, + _this$options$fee, + _this$options$args, + _this$options$timeout, + contract, + _args = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _ref2 = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, restore = _ref2.restore; + if (_this.built) { + _context.next = 5; + break; + } + if (_this.raw) { + _context.next = 4; + break; + } + throw new Error("Transaction has not yet been assembled; " + "call `AssembledTransaction.build` first."); + case 4: + _this.built = _this.raw.build(); + case 5: + restore = (_restore = restore) !== null && _restore !== void 0 ? _restore : _this.options.restore; + delete _this.simulationResult; + delete _this.simulationTransactionData; + _context.next = 10; + return _this.server.simulateTransaction(_this.built); + case 10: + _this.simulation = _context.sent; + if (!(restore && api/* Api */.j.isSimulationRestore(_this.simulation))) { + _context.next = 25; + break; + } + _context.next = 14; + return getAccount(_this.options, _this.server); + case 14: + account = _context.sent; + _context.next = 17; + return _this.restoreFootprint(_this.simulation.restorePreamble, account); + case 17: + result = _context.sent; + if (!(result.status === api/* Api */.j.GetTransactionStatus.SUCCESS)) { + _context.next = 24; + break; + } + contract = new lib.Contract(_this.options.contractId); + _this.raw = new lib.TransactionBuilder(account, { + fee: (_this$options$fee = _this.options.fee) !== null && _this$options$fee !== void 0 ? _this$options$fee : lib.BASE_FEE, + networkPassphrase: _this.options.networkPassphrase + }).addOperation(contract.call.apply(contract, [_this.options.method].concat(_toConsumableArray((_this$options$args = _this.options.args) !== null && _this$options$args !== void 0 ? _this$options$args : [])))).setTimeout((_this$options$timeout = _this.options.timeoutInSeconds) !== null && _this$options$timeout !== void 0 ? _this$options$timeout : DEFAULT_TIMEOUT); + _context.next = 23; + return _this.simulate(); + case 23: + return _context.abrupt("return", _this); + case 24: + throw new AssembledTransaction.Errors.RestorationFailure("Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n".concat(JSON.stringify(result))); + case 25: + if (api/* Api */.j.isSimulationSuccess(_this.simulation)) { + _this.built = (0,transaction/* assembleTransaction */.X)(_this.built, _this.simulation).build(); + } + return _context.abrupt("return", _this); + case 27: + case "end": + return _context.stop(); + } + }, _callee); + }))); + assembled_transaction_defineProperty(this, "sign", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee2() { + var _this$options$timeout2; + var _ref4, + _ref4$force, + force, + _ref4$signTransaction, + signTransaction, + sigsNeeded, + timeoutInSeconds, + signOpts, + _yield$signTransactio, + signature, + error, + _args2 = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _ref4 = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref4$force = _ref4.force, force = _ref4$force === void 0 ? false : _ref4$force, _ref4$signTransaction = _ref4.signTransaction, signTransaction = _ref4$signTransaction === void 0 ? _this.options.signTransaction : _ref4$signTransaction; + if (_this.built) { + _context2.next = 3; + break; + } + throw new Error("Transaction has not yet been simulated"); + case 3: + if (!(!force && _this.isReadCall)) { + _context2.next = 5; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("This is a read call. It requires no signature or sending. " + "Use `force: true` to sign and send anyway."); + case 5: + if (signTransaction) { + _context2.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide a signTransaction function, either when calling " + "`signAndSend` or when initializing your Client"); + case 7: + sigsNeeded = _this.needsNonInvokerSigningBy().filter(function (id) { + return !id.startsWith('C'); + }); + if (!sigsNeeded.length) { + _context2.next = 10; + break; + } + throw new AssembledTransaction.Errors.NeedsMoreSignatures("Transaction requires signatures from ".concat(sigsNeeded, ". ") + "See `needsNonInvokerSigningBy` for details."); + case 10: + timeoutInSeconds = (_this$options$timeout2 = _this.options.timeoutInSeconds) !== null && _this$options$timeout2 !== void 0 ? _this$options$timeout2 : DEFAULT_TIMEOUT; + _this.built = lib.TransactionBuilder.cloneFrom(_this.built, { + fee: _this.built.fee, + timebounds: undefined, + sorobanData: _this.simulationData.transactionData + }).setTimeout(timeoutInSeconds).build(); + signOpts = { + networkPassphrase: _this.options.networkPassphrase + }; + if (_this.options.address) signOpts.address = _this.options.address; + if (_this.options.submit !== undefined) signOpts.submit = _this.options.submit; + if (_this.options.submitUrl) signOpts.submitUrl = _this.options.submitUrl; + _context2.next = 18; + return signTransaction(_this.built.toXDR(), signOpts); + case 18: + _yield$signTransactio = _context2.sent; + signature = _yield$signTransactio.signedTxXdr; + error = _yield$signTransactio.error; + _this.handleWalletError(error); + _this.signed = lib.TransactionBuilder.fromXDR(signature, _this.options.networkPassphrase); + case 23: + case "end": + return _context2.stop(); + } + }, _callee2); + }))); + assembled_transaction_defineProperty(this, "signAndSend", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee3() { + var _ref6, + _ref6$force, + force, + _ref6$signTransaction, + signTransaction, + originalSubmit, + _args3 = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _ref6 = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : {}, _ref6$force = _ref6.force, force = _ref6$force === void 0 ? false : _ref6$force, _ref6$signTransaction = _ref6.signTransaction, signTransaction = _ref6$signTransaction === void 0 ? _this.options.signTransaction : _ref6$signTransaction; + if (_this.signed) { + _context3.next = 10; + break; + } + originalSubmit = _this.options.submit; + if (_this.options.submit) { + _this.options.submit = false; + } + _context3.prev = 4; + _context3.next = 7; + return _this.sign({ + force: force, + signTransaction: signTransaction + }); + case 7: + _context3.prev = 7; + _this.options.submit = originalSubmit; + return _context3.finish(7); + case 10: + return _context3.abrupt("return", _this.send()); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3, null, [[4,, 7, 10]]); + }))); + assembled_transaction_defineProperty(this, "needsNonInvokerSigningBy", function () { + var _rawInvokeHostFunctio; + var _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref7$includeAlreadyS = _ref7.includeAlreadySigned, + includeAlreadySigned = _ref7$includeAlreadyS === void 0 ? false : _ref7$includeAlreadyS; + if (!_this.built) { + throw new Error("Transaction has not yet been simulated"); + } + if (!("operations" in _this.built)) { + throw new Error("Unexpected Transaction type; no operations: ".concat(JSON.stringify(_this.built))); + } + var rawInvokeHostFunctionOp = _this.built.operations[0]; + return _toConsumableArray(new Set(((_rawInvokeHostFunctio = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio !== void 0 ? _rawInvokeHostFunctio : []).filter(function (entry) { + return entry.credentials().switch() === lib.xdr.SorobanCredentialsType.sorobanCredentialsAddress() && (includeAlreadySigned || entry.credentials().address().signature().switch().name === "scvVoid"); + }).map(function (entry) { + return lib.Address.fromScAddress(entry.credentials().address().address()).toString(); + }))); + }); + assembled_transaction_defineProperty(this, "signAuthEntries", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee6() { + var _rawInvokeHostFunctio2; + var _ref9, + _ref9$expiration, + expiration, + _ref9$signAuthEntry, + signAuthEntry, + _ref9$address, + address, + _ref9$authorizeEntry, + authorizeEntry, + needsNonInvokerSigningBy, + rawInvokeHostFunctionOp, + authEntries, + _iterator, + _step, + _loop, + _ret, + _args7 = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee6$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _ref9 = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {}, _ref9$expiration = _ref9.expiration, expiration = _ref9$expiration === void 0 ? assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee4() { + return assembled_transaction_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this.server.getLatestLedger(); + case 2: + _context4.t0 = _context4.sent.sequence; + return _context4.abrupt("return", _context4.t0 + 100); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + }))() : _ref9$expiration, _ref9$signAuthEntry = _ref9.signAuthEntry, signAuthEntry = _ref9$signAuthEntry === void 0 ? _this.options.signAuthEntry : _ref9$signAuthEntry, _ref9$address = _ref9.address, address = _ref9$address === void 0 ? _this.options.publicKey : _ref9$address, _ref9$authorizeEntry = _ref9.authorizeEntry, authorizeEntry = _ref9$authorizeEntry === void 0 ? lib.authorizeEntry : _ref9$authorizeEntry; + if (_this.built) { + _context7.next = 3; + break; + } + throw new Error("Transaction has not yet been assembled or simulated"); + case 3: + if (!(authorizeEntry === lib.authorizeEntry)) { + _context7.next = 11; + break; + } + needsNonInvokerSigningBy = _this.needsNonInvokerSigningBy(); + if (!(needsNonInvokerSigningBy.length === 0)) { + _context7.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?"); + case 7: + if (!(needsNonInvokerSigningBy.indexOf(address !== null && address !== void 0 ? address : "") === -1)) { + _context7.next = 9; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("No auth entries for public key \"".concat(address, "\"")); + case 9: + if (signAuthEntry) { + _context7.next = 11; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`"); + case 11: + rawInvokeHostFunctionOp = _this.built.operations[0]; + authEntries = (_rawInvokeHostFunctio2 = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio2 !== void 0 ? _rawInvokeHostFunctio2 : []; + _iterator = _createForOfIteratorHelper(authEntries.entries()); + _context7.prev = 14; + _loop = assembled_transaction_regeneratorRuntime().mark(function _loop() { + var _step$value, i, entry, credentials, authEntryAddress, sign; + return assembled_transaction_regeneratorRuntime().wrap(function _loop$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _step$value = _slicedToArray(_step.value, 2), i = _step$value[0], entry = _step$value[1]; + credentials = lib.xdr.SorobanCredentials.fromXDR(entry.credentials().toXDR()); + if (!(credentials.switch() !== lib.xdr.SorobanCredentialsType.sorobanCredentialsAddress())) { + _context6.next = 4; + break; + } + return _context6.abrupt("return", 0); + case 4: + authEntryAddress = lib.Address.fromScAddress(credentials.address().address()).toString(); + if (!(authEntryAddress !== address)) { + _context6.next = 7; + break; + } + return _context6.abrupt("return", 0); + case 7: + sign = signAuthEntry !== null && signAuthEntry !== void 0 ? signAuthEntry : Promise.resolve; + _context6.t0 = authorizeEntry; + _context6.t1 = entry; + _context6.t2 = function () { + var _ref11 = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee5(preimage) { + var _yield$sign, signedAuthEntry, error; + return assembled_transaction_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return sign(preimage.toXDR("base64"), { + address: address + }); + case 2: + _yield$sign = _context5.sent; + signedAuthEntry = _yield$sign.signedAuthEntry; + error = _yield$sign.error; + _this.handleWalletError(error); + return _context5.abrupt("return", Buffer.from(signedAuthEntry, "base64")); + case 7: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x) { + return _ref11.apply(this, arguments); + }; + }(); + _context6.next = 13; + return expiration; + case 13: + _context6.t3 = _context6.sent; + _context6.t4 = _this.options.networkPassphrase; + _context6.next = 17; + return (0, _context6.t0)(_context6.t1, _context6.t2, _context6.t3, _context6.t4); + case 17: + authEntries[i] = _context6.sent; + case 18: + case "end": + return _context6.stop(); + } + }, _loop); + }); + _iterator.s(); + case 17: + if ((_step = _iterator.n()).done) { + _context7.next = 24; + break; + } + return _context7.delegateYield(_loop(), "t0", 19); + case 19: + _ret = _context7.t0; + if (!(_ret === 0)) { + _context7.next = 22; + break; + } + return _context7.abrupt("continue", 22); + case 22: + _context7.next = 17; + break; + case 24: + _context7.next = 29; + break; + case 26: + _context7.prev = 26; + _context7.t1 = _context7["catch"](14); + _iterator.e(_context7.t1); + case 29: + _context7.prev = 29; + _iterator.f(); + return _context7.finish(29); + case 32: + case "end": + return _context7.stop(); + } + }, _callee6, null, [[14, 26, 29, 32]]); + }))); + this.options = options; + this.options.simulate = (_this$options$simulat = this.options.simulate) !== null && _this$options$simulat !== void 0 ? _this$options$simulat : true; + this.server = new rpc.Server(this.options.rpcUrl, { + allowHttp: (_this$options$allowHt = this.options.allowHttp) !== null && _this$options$allowHt !== void 0 ? _this$options$allowHt : false + }); + } + return assembled_transaction_createClass(AssembledTransaction, [{ + key: "toJSON", + value: function toJSON() { + var _this$built; + return JSON.stringify({ + method: this.options.method, + tx: (_this$built = this.built) === null || _this$built === void 0 ? void 0 : _this$built.toXDR(), + simulationResult: { + auth: this.simulationData.result.auth.map(function (a) { + return a.toXDR("base64"); + }), + retval: this.simulationData.result.retval.toXDR("base64") + }, + simulationTransactionData: this.simulationData.transactionData.toXDR("base64") + }); + } + }, { + key: "toXDR", + value: function toXDR() { + var _this$built2; + if (!this.built) throw new Error("Transaction has not yet been simulated; " + "call `AssembledTransaction.simulate` first."); + return (_this$built2 = this.built) === null || _this$built2 === void 0 ? void 0 : _this$built2.toEnvelope().toXDR('base64'); + } + }, { + key: "handleWalletError", + value: function handleWalletError(error) { + if (!error) return; + var message = error.message, + code = error.code; + var fullMessage = "".concat(message).concat(error.ext ? " (".concat(error.ext.join(', '), ")") : ''); + switch (code) { + case -1: + throw new AssembledTransaction.Errors.InternalWalletError(fullMessage); + case -2: + throw new AssembledTransaction.Errors.ExternalServiceError(fullMessage); + case -3: + throw new AssembledTransaction.Errors.InvalidClientRequest(fullMessage); + case -4: + throw new AssembledTransaction.Errors.UserRejected(fullMessage); + default: + throw new Error("Unhandled error: ".concat(fullMessage)); + } + } + }, { + key: "simulationData", + get: function get() { + var _simulation$result; + if (this.simulationResult && this.simulationTransactionData) { + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + var simulation = this.simulation; + if (!simulation) { + throw new AssembledTransaction.Errors.NotYetSimulated("Transaction has not yet been simulated"); + } + if (api/* Api */.j.isSimulationError(simulation)) { + throw new AssembledTransaction.Errors.SimulationFailed("Transaction simulation failed: \"".concat(simulation.error, "\"")); + } + if (api/* Api */.j.isSimulationRestore(simulation)) { + throw new AssembledTransaction.Errors.ExpiredState("You need to restore some contract state before you can invoke this method.\n" + 'You can set `restore` to true in the method options in order to ' + 'automatically restore the contract state when needed.'); + } + this.simulationResult = (_simulation$result = simulation.result) !== null && _simulation$result !== void 0 ? _simulation$result : { + auth: [], + retval: lib.xdr.ScVal.scvVoid() + }; + this.simulationTransactionData = simulation.transactionData.build(); + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + }, { + key: "result", + get: function get() { + try { + if (!this.simulationData.result) { + throw new Error("No simulation result!"); + } + return this.options.parseResultXdr(this.simulationData.result.retval); + } catch (e) { + if (!implementsToString(e)) throw e; + var err = this.parseError(e.toString()); + if (err) return err; + throw e; + } + } + }, { + key: "parseError", + value: function parseError(errorMessage) { + if (!this.options.errorTypes) return undefined; + var match = errorMessage.match(contractErrorPattern); + if (!match) return undefined; + var i = parseInt(match[1], 10); + var err = this.options.errorTypes[i]; + if (!err) return undefined; + return new Err(err); + } + }, { + key: "send", + value: (function () { + var _send = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee7() { + var sent; + return assembled_transaction_regeneratorRuntime().wrap(function _callee7$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (this.signed) { + _context8.next = 2; + break; + } + throw new Error("The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead."); + case 2: + _context8.next = 4; + return SentTransaction.init(this); + case 4: + sent = _context8.sent; + return _context8.abrupt("return", sent); + case 6: + case "end": + return _context8.stop(); + } + }, _callee7, this); + })); + function send() { + return _send.apply(this, arguments); + } + return send; + }()) + }, { + key: "isReadCall", + get: function get() { + var authsCount = this.simulationData.result.auth.length; + var writeLength = this.simulationData.transactionData.resources().footprint().readWrite().length; + return authsCount === 0 && writeLength === 0; + } + }, { + key: "restoreFootprint", + value: (function () { + var _restoreFootprint = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee8(restorePreamble, account) { + var _account; + var restoreTx, sentTransaction; + return assembled_transaction_regeneratorRuntime().wrap(function _callee8$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + if (this.options.signTransaction) { + _context9.next = 2; + break; + } + throw new Error("For automatic restore to work you must provide a signTransaction function when initializing your Client"); + case 2: + if (!((_account = account) !== null && _account !== void 0)) { + _context9.next = 6; + break; + } + _context9.t0 = _account; + _context9.next = 9; + break; + case 6: + _context9.next = 8; + return getAccount(this.options, this.server); + case 8: + _context9.t0 = _context9.sent; + case 9: + account = _context9.t0; + _context9.next = 12; + return AssembledTransaction.buildFootprintRestoreTransaction(_objectSpread({}, this.options), restorePreamble.transactionData, account, restorePreamble.minResourceFee); + case 12: + restoreTx = _context9.sent; + _context9.next = 15; + return restoreTx.signAndSend(); + case 15: + sentTransaction = _context9.sent; + if (sentTransaction.getTransactionResponse) { + _context9.next = 18; + break; + } + throw new AssembledTransaction.Errors.RestorationFailure("The attempt at automatic restore failed. \n".concat(JSON.stringify(sentTransaction))); + case 18: + return _context9.abrupt("return", sentTransaction.getTransactionResponse); + case 19: + case "end": + return _context9.stop(); + } + }, _callee8, this); + })); + function restoreFootprint(_x2, _x3) { + return _restoreFootprint.apply(this, arguments); + } + return restoreFootprint; + }()) + }], [{ + key: "fromJSON", + value: function fromJSON(options, _ref12) { + var tx = _ref12.tx, + simulationResult = _ref12.simulationResult, + simulationTransactionData = _ref12.simulationTransactionData; + var txn = new AssembledTransaction(options); + txn.built = lib.TransactionBuilder.fromXDR(tx, options.networkPassphrase); + txn.simulationResult = { + auth: simulationResult.auth.map(function (a) { + return lib.xdr.SorobanAuthorizationEntry.fromXDR(a, "base64"); + }), + retval: lib.xdr.ScVal.fromXDR(simulationResult.retval, "base64") + }; + txn.simulationTransactionData = lib.xdr.SorobanTransactionData.fromXDR(simulationTransactionData, "base64"); + return txn; + } + }, { + key: "fromXDR", + value: function fromXDR(options, encodedXDR, spec) { + var _operation$func; + var envelope = lib.xdr.TransactionEnvelope.fromXDR(encodedXDR, "base64"); + var built = lib.TransactionBuilder.fromXDR(envelope, options.networkPassphrase); + var operation = built.operations[0]; + if (!(operation !== null && operation !== void 0 && (_operation$func = operation.func) !== null && _operation$func !== void 0 && _operation$func.value) || typeof operation.func.value !== 'function') { + throw new Error("Could not extract the method from the transaction envelope."); + } + var invokeContractArgs = operation.func.value(); + if (!(invokeContractArgs !== null && invokeContractArgs !== void 0 && invokeContractArgs.functionName)) { + throw new Error("Could not extract the method name from the transaction envelope."); + } + var method = invokeContractArgs.functionName().toString('utf-8'); + var txn = new AssembledTransaction(_objectSpread(_objectSpread({}, options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + txn.built = built; + return txn; + } + }, { + key: "build", + value: function build(options) { + var _options$args; + var contract = new lib.Contract(options.contractId); + return AssembledTransaction.buildWithOp(contract.call.apply(contract, [options.method].concat(_toConsumableArray((_options$args = options.args) !== null && _options$args !== void 0 ? _options$args : []))), options); + } + }, { + key: "buildWithOp", + value: (function () { + var _buildWithOp = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee9(operation, options) { + var _options$fee, _options$timeoutInSec; + var tx, account; + return assembled_transaction_regeneratorRuntime().wrap(function _callee9$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + tx = new AssembledTransaction(options); + _context10.next = 3; + return getAccount(options, tx.server); + case 3: + account = _context10.sent; + tx.raw = new lib.TransactionBuilder(account, { + fee: (_options$fee = options.fee) !== null && _options$fee !== void 0 ? _options$fee : lib.BASE_FEE, + networkPassphrase: options.networkPassphrase + }).setTimeout((_options$timeoutInSec = options.timeoutInSeconds) !== null && _options$timeoutInSec !== void 0 ? _options$timeoutInSec : DEFAULT_TIMEOUT).addOperation(operation); + if (!options.simulate) { + _context10.next = 8; + break; + } + _context10.next = 8; + return tx.simulate(); + case 8: + return _context10.abrupt("return", tx); + case 9: + case "end": + return _context10.stop(); + } + }, _callee9); + })); + function buildWithOp(_x4, _x5) { + return _buildWithOp.apply(this, arguments); + } + return buildWithOp; + }()) + }, { + key: "buildFootprintRestoreTransaction", + value: function () { + var _buildFootprintRestoreTransaction = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee10(options, sorobanData, account, fee) { + var _options$timeoutInSec2; + var tx; + return assembled_transaction_regeneratorRuntime().wrap(function _callee10$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + tx = new AssembledTransaction(options); + tx.raw = new lib.TransactionBuilder(account, { + fee: fee, + networkPassphrase: options.networkPassphrase + }).setSorobanData(sorobanData instanceof lib.SorobanDataBuilder ? sorobanData.build() : sorobanData).addOperation(lib.Operation.restoreFootprint({})).setTimeout((_options$timeoutInSec2 = options.timeoutInSeconds) !== null && _options$timeoutInSec2 !== void 0 ? _options$timeoutInSec2 : DEFAULT_TIMEOUT); + _context11.next = 4; + return tx.simulate({ + restore: false + }); + case 4: + return _context11.abrupt("return", tx); + case 5: + case "end": + return _context11.stop(); + } + }, _callee10); + })); + function buildFootprintRestoreTransaction(_x6, _x7, _x8, _x9) { + return _buildFootprintRestoreTransaction.apply(this, arguments); + } + return buildFootprintRestoreTransaction; + }() + }]); +}(); +assembled_transaction_defineProperty(AssembledTransaction, "Errors", { + ExpiredState: function (_Error) { + function ExpiredStateError() { + assembled_transaction_classCallCheck(this, ExpiredStateError); + return assembled_transaction_callSuper(this, ExpiredStateError, arguments); + } + assembled_transaction_inherits(ExpiredStateError, _Error); + return assembled_transaction_createClass(ExpiredStateError); + }(assembled_transaction_wrapNativeSuper(Error)), + RestorationFailure: function (_Error2) { + function RestoreFailureError() { + assembled_transaction_classCallCheck(this, RestoreFailureError); + return assembled_transaction_callSuper(this, RestoreFailureError, arguments); + } + assembled_transaction_inherits(RestoreFailureError, _Error2); + return assembled_transaction_createClass(RestoreFailureError); + }(assembled_transaction_wrapNativeSuper(Error)), + NeedsMoreSignatures: function (_Error3) { + function NeedsMoreSignaturesError() { + assembled_transaction_classCallCheck(this, NeedsMoreSignaturesError); + return assembled_transaction_callSuper(this, NeedsMoreSignaturesError, arguments); + } + assembled_transaction_inherits(NeedsMoreSignaturesError, _Error3); + return assembled_transaction_createClass(NeedsMoreSignaturesError); + }(assembled_transaction_wrapNativeSuper(Error)), + NoSignatureNeeded: function (_Error4) { + function NoSignatureNeededError() { + assembled_transaction_classCallCheck(this, NoSignatureNeededError); + return assembled_transaction_callSuper(this, NoSignatureNeededError, arguments); + } + assembled_transaction_inherits(NoSignatureNeededError, _Error4); + return assembled_transaction_createClass(NoSignatureNeededError); + }(assembled_transaction_wrapNativeSuper(Error)), + NoUnsignedNonInvokerAuthEntries: function (_Error5) { + function NoUnsignedNonInvokerAuthEntriesError() { + assembled_transaction_classCallCheck(this, NoUnsignedNonInvokerAuthEntriesError); + return assembled_transaction_callSuper(this, NoUnsignedNonInvokerAuthEntriesError, arguments); + } + assembled_transaction_inherits(NoUnsignedNonInvokerAuthEntriesError, _Error5); + return assembled_transaction_createClass(NoUnsignedNonInvokerAuthEntriesError); + }(assembled_transaction_wrapNativeSuper(Error)), + NoSigner: function (_Error6) { + function NoSignerError() { + assembled_transaction_classCallCheck(this, NoSignerError); + return assembled_transaction_callSuper(this, NoSignerError, arguments); + } + assembled_transaction_inherits(NoSignerError, _Error6); + return assembled_transaction_createClass(NoSignerError); + }(assembled_transaction_wrapNativeSuper(Error)), + NotYetSimulated: function (_Error7) { + function NotYetSimulatedError() { + assembled_transaction_classCallCheck(this, NotYetSimulatedError); + return assembled_transaction_callSuper(this, NotYetSimulatedError, arguments); + } + assembled_transaction_inherits(NotYetSimulatedError, _Error7); + return assembled_transaction_createClass(NotYetSimulatedError); + }(assembled_transaction_wrapNativeSuper(Error)), + FakeAccount: function (_Error8) { + function FakeAccountError() { + assembled_transaction_classCallCheck(this, FakeAccountError); + return assembled_transaction_callSuper(this, FakeAccountError, arguments); + } + assembled_transaction_inherits(FakeAccountError, _Error8); + return assembled_transaction_createClass(FakeAccountError); + }(assembled_transaction_wrapNativeSuper(Error)), + SimulationFailed: function (_Error9) { + function SimulationFailedError() { + assembled_transaction_classCallCheck(this, SimulationFailedError); + return assembled_transaction_callSuper(this, SimulationFailedError, arguments); + } + assembled_transaction_inherits(SimulationFailedError, _Error9); + return assembled_transaction_createClass(SimulationFailedError); + }(assembled_transaction_wrapNativeSuper(Error)), + InternalWalletError: function (_Error10) { + function InternalWalletError() { + assembled_transaction_classCallCheck(this, InternalWalletError); + return assembled_transaction_callSuper(this, InternalWalletError, arguments); + } + assembled_transaction_inherits(InternalWalletError, _Error10); + return assembled_transaction_createClass(InternalWalletError); + }(assembled_transaction_wrapNativeSuper(Error)), + ExternalServiceError: function (_Error11) { + function ExternalServiceError() { + assembled_transaction_classCallCheck(this, ExternalServiceError); + return assembled_transaction_callSuper(this, ExternalServiceError, arguments); + } + assembled_transaction_inherits(ExternalServiceError, _Error11); + return assembled_transaction_createClass(ExternalServiceError); + }(assembled_transaction_wrapNativeSuper(Error)), + InvalidClientRequest: function (_Error12) { + function InvalidClientRequestError() { + assembled_transaction_classCallCheck(this, InvalidClientRequestError); + return assembled_transaction_callSuper(this, InvalidClientRequestError, arguments); + } + assembled_transaction_inherits(InvalidClientRequestError, _Error12); + return assembled_transaction_createClass(InvalidClientRequestError); + }(assembled_transaction_wrapNativeSuper(Error)), + UserRejected: function (_Error13) { + function UserRejectedError() { + assembled_transaction_classCallCheck(this, UserRejectedError); + return assembled_transaction_callSuper(this, UserRejectedError, arguments); + } + assembled_transaction_inherits(UserRejectedError, _Error13); + return assembled_transaction_createClass(UserRejectedError); + }(assembled_transaction_wrapNativeSuper(Error)) +}); +;// ./src/contract/basic_node_signer.ts +/* provided dependency */ var basic_node_signer_Buffer = __webpack_require__(8287)["Buffer"]; +function basic_node_signer_typeof(o) { "@babel/helpers - typeof"; return basic_node_signer_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, basic_node_signer_typeof(o); } +function basic_node_signer_regeneratorRuntime() { "use strict"; basic_node_signer_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == basic_node_signer_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(basic_node_signer_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function basic_node_signer_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function basic_node_signer_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { basic_node_signer_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { basic_node_signer_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + +var basicNodeSigner = function basicNodeSigner(keypair, networkPassphrase) { + return { + signTransaction: function () { + var _signTransaction = basic_node_signer_asyncToGenerator(basic_node_signer_regeneratorRuntime().mark(function _callee(xdr, opts) { + var t; + return basic_node_signer_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + t = lib.TransactionBuilder.fromXDR(xdr, (opts === null || opts === void 0 ? void 0 : opts.networkPassphrase) || networkPassphrase); + t.sign(keypair); + return _context.abrupt("return", { + signedTxXdr: t.toXDR(), + signerAddress: keypair.publicKey() + }); + case 3: + case "end": + return _context.stop(); + } + }, _callee); + })); + function signTransaction(_x, _x2) { + return _signTransaction.apply(this, arguments); + } + return signTransaction; + }(), + signAuthEntry: function () { + var _signAuthEntry = basic_node_signer_asyncToGenerator(basic_node_signer_regeneratorRuntime().mark(function _callee2(authEntry) { + var signedAuthEntry; + return basic_node_signer_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + signedAuthEntry = keypair.sign((0,lib.hash)(basic_node_signer_Buffer.from(authEntry, "base64"))).toString("base64"); + return _context2.abrupt("return", { + signedAuthEntry: signedAuthEntry, + signerAddress: keypair.publicKey() + }); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function signAuthEntry(_x3) { + return _signAuthEntry.apply(this, arguments); + } + return signAuthEntry; + }() + }; +}; +;// ./src/contract/spec.ts +/* provided dependency */ var spec_Buffer = __webpack_require__(8287)["Buffer"]; +function spec_ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function spec_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? spec_ownKeys(Object(t), !0).forEach(function (r) { spec_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : spec_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function spec_typeof(o) { "@babel/helpers - typeof"; return spec_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, spec_typeof(o); } +function spec_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function spec_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, spec_toPropertyKey(o.key), o); } } +function spec_createClass(e, r, t) { return r && spec_defineProperties(e.prototype, r), t && spec_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function spec_defineProperty(e, r, t) { return (r = spec_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function spec_toPropertyKey(t) { var i = spec_toPrimitive(t, "string"); return "symbol" == spec_typeof(i) ? i : i + ""; } +function spec_toPrimitive(t, r) { if ("object" != spec_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != spec_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function spec_slicedToArray(r, e) { return spec_arrayWithHoles(r) || spec_iterableToArrayLimit(r, e) || spec_unsupportedIterableToArray(r, e) || spec_nonIterableRest(); } +function spec_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function spec_unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return spec_arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? spec_arrayLikeToArray(r, a) : void 0; } } +function spec_arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function spec_iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function spec_arrayWithHoles(r) { if (Array.isArray(r)) return r; } + + +function enumToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + var title = aCase.name().toString(); + var desc = aCase.doc().toString(); + oneOf.push({ + description: desc, + title: title, + enum: [aCase.value()], + type: "number" + }); + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +function isNumeric(field) { + return /^\d+$/.test(field.name().toString()); +} +function readObj(args, input) { + var inputName = input.name().toString(); + var entry = Object.entries(args).find(function (_ref) { + var _ref2 = spec_slicedToArray(_ref, 1), + name = _ref2[0]; + return name === inputName; + }); + if (!entry) { + throw new Error("Missing field ".concat(inputName)); + } + return entry[1]; +} +function findCase(name) { + return function matches(entry) { + switch (entry.switch().value) { + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var tuple = entry.tupleCase(); + return tuple.name().toString() === name; + } + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var voidCase = entry.voidCase(); + return voidCase.name().toString() === name; + } + default: + return false; + } + }; +} +function stringToScVal(str, ty) { + switch (ty.value) { + case lib.xdr.ScSpecType.scSpecTypeString().value: + return lib.xdr.ScVal.scvString(str); + case lib.xdr.ScSpecType.scSpecTypeSymbol().value: + return lib.xdr.ScVal.scvSymbol(str); + case lib.xdr.ScSpecType.scSpecTypeAddress().value: + { + var addr = lib.Address.fromString(str); + return lib.xdr.ScVal.scvAddress(addr.toScAddress()); + } + case lib.xdr.ScSpecType.scSpecTypeU64().value: + return new lib.XdrLargeInt("u64", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeI64().value: + return new lib.XdrLargeInt("i64", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeU128().value: + return new lib.XdrLargeInt("u128", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeI128().value: + return new lib.XdrLargeInt("i128", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeU256().value: + return new lib.XdrLargeInt("u256", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeI256().value: + return new lib.XdrLargeInt("i256", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeBytes().value: + case lib.xdr.ScSpecType.scSpecTypeBytesN().value: + return lib.xdr.ScVal.scvBytes(spec_Buffer.from(str, "base64")); + default: + throw new TypeError("invalid type ".concat(ty.name, " specified for string value")); + } +} +var PRIMITIVE_DEFINITONS = { + U32: { + type: "integer", + minimum: 0, + maximum: 4294967295 + }, + I32: { + type: "integer", + minimum: -2147483648, + maximum: 2147483647 + }, + U64: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 20 + }, + I64: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 21 + }, + U128: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 39 + }, + I128: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 40 + }, + U256: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 78 + }, + I256: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 79 + }, + Address: { + type: "string", + format: "address", + description: "Address can be a public key or contract id" + }, + ScString: { + type: "string", + description: "ScString is a string" + }, + ScSymbol: { + type: "string", + description: "ScString is a string" + }, + DataUrl: { + type: "string", + pattern: "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$" + } +}; +function typeRef(typeDef) { + var t = typeDef.switch(); + var value = t.value; + var ref; + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVal().value: + { + ref = "Val"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeBool().value: + { + return { + type: "boolean" + }; + } + case lib.xdr.ScSpecType.scSpecTypeVoid().value: + { + return { + type: "null" + }; + } + case lib.xdr.ScSpecType.scSpecTypeError().value: + { + ref = "Error"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU32().value: + { + ref = "U32"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI32().value: + { + ref = "I32"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU64().value: + { + ref = "U64"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI64().value: + { + ref = "I64"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeTimepoint().value: + { + throw new Error("Timepoint type not supported"); + ref = "Timepoint"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeDuration().value: + { + throw new Error("Duration not supported"); + ref = "Duration"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU128().value: + { + ref = "U128"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI128().value: + { + ref = "I128"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU256().value: + { + ref = "U256"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI256().value: + { + ref = "I256"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeBytes().value: + { + ref = "DataUrl"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeString().value: + { + ref = "ScString"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeSymbol().value: + { + ref = "ScSymbol"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeAddress().value: + { + ref = "Address"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeOption().value: + { + var opt = typeDef.option(); + return typeRef(opt.valueType()); + } + case lib.xdr.ScSpecType.scSpecTypeResult().value: + { + break; + } + case lib.xdr.ScSpecType.scSpecTypeVec().value: + { + var arr = typeDef.vec(); + var reference = typeRef(arr.elementType()); + return { + type: "array", + items: reference + }; + } + case lib.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = typeDef.map(); + var items = [typeRef(map.keyType()), typeRef(map.valueType())]; + return { + type: "array", + items: { + type: "array", + items: items, + minItems: 2, + maxItems: 2 + } + }; + } + case lib.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tuple = typeDef.tuple(); + var minItems = tuple.valueTypes().length; + var maxItems = minItems; + var _items = tuple.valueTypes().map(typeRef); + return { + type: "array", + items: _items, + minItems: minItems, + maxItems: maxItems + }; + } + case lib.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var _arr = typeDef.bytesN(); + return { + $ref: "#/definitions/DataUrl", + maxLength: _arr.n() + }; + } + case lib.xdr.ScSpecType.scSpecTypeUdt().value: + { + var udt = typeDef.udt(); + ref = udt.name().toString(); + break; + } + } + return { + $ref: "#/definitions/".concat(ref) + }; +} +function isRequired(typeDef) { + return typeDef.switch().value !== lib.xdr.ScSpecType.scSpecTypeOption().value; +} +function argsAndRequired(input) { + var properties = {}; + var required = []; + input.forEach(function (arg) { + var aType = arg.type(); + var name = arg.name().toString(); + properties[name] = typeRef(aType); + if (isRequired(aType)) { + required.push(name); + } + }); + var res = { + properties: properties + }; + if (required.length > 0) { + res.required = required; + } + return res; +} +function structToJsonSchema(udt) { + var fields = udt.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + var items = fields.map(function (_, i) { + return typeRef(fields[i].type()); + }); + return { + type: "array", + items: items, + minItems: fields.length, + maxItems: fields.length + }; + } + var description = udt.doc().toString(); + var _argsAndRequired = argsAndRequired(fields), + properties = _argsAndRequired.properties, + required = _argsAndRequired.required; + properties.additionalProperties = false; + return { + description: description, + properties: properties, + required: required, + type: "object" + }; +} +function functionToJsonSchema(func) { + var _argsAndRequired2 = argsAndRequired(func.inputs()), + properties = _argsAndRequired2.properties, + required = _argsAndRequired2.required; + var args = { + additionalProperties: false, + properties: properties, + type: "object" + }; + if ((required === null || required === void 0 ? void 0 : required.length) > 0) { + args.required = required; + } + var input = { + properties: { + args: args + } + }; + var outputs = func.outputs(); + var output = outputs.length > 0 ? typeRef(outputs[0]) : typeRef(lib.xdr.ScSpecTypeDef.scSpecTypeVoid()); + var description = func.doc().toString(); + if (description.length > 0) { + input.description = description; + } + input.additionalProperties = false; + output.additionalProperties = false; + return { + input: input, + output: output + }; +} +function unionToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + switch (aCase.switch().value) { + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var c = aCase.voidCase(); + var title = c.name().toString(); + oneOf.push({ + type: "object", + title: title, + properties: { + tag: title + }, + additionalProperties: false, + required: ["tag"] + }); + break; + } + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var _c = aCase.tupleCase(); + var _title = _c.name().toString(); + oneOf.push({ + type: "object", + title: _title, + properties: { + tag: _title, + values: { + type: "array", + items: _c.type().map(typeRef) + } + }, + required: ["tag", "values"], + additionalProperties: false + }); + } + } + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +var Spec = function () { + function Spec(entries) { + spec_classCallCheck(this, Spec); + spec_defineProperty(this, "entries", []); + if (entries.length === 0) { + throw new Error("Contract spec must have at least one entry"); + } + var entry = entries[0]; + if (typeof entry === "string") { + this.entries = entries.map(function (s) { + return lib.xdr.ScSpecEntry.fromXDR(s, "base64"); + }); + } else { + this.entries = entries; + } + } + return spec_createClass(Spec, [{ + key: "funcs", + value: function funcs() { + return this.entries.filter(function (entry) { + return entry.switch().value === lib.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value; + }).map(function (entry) { + return entry.functionV0(); + }); + } + }, { + key: "getFunc", + value: function getFunc(name) { + var entry = this.findEntry(name); + if (entry.switch().value !== lib.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value) { + throw new Error("".concat(name, " is not a function")); + } + return entry.functionV0(); + } + }, { + key: "funcArgsToScVals", + value: function funcArgsToScVals(name, args) { + var _this = this; + var fn = this.getFunc(name); + return fn.inputs().map(function (input) { + return _this.nativeToScVal(readObj(args, input), input.type()); + }); + } + }, { + key: "funcResToNative", + value: function funcResToNative(name, val_or_base64) { + var val = typeof val_or_base64 === "string" ? lib.xdr.ScVal.fromXDR(val_or_base64, "base64") : val_or_base64; + var func = this.getFunc(name); + var outputs = func.outputs(); + if (outputs.length === 0) { + var type = val.switch(); + if (type.value !== lib.xdr.ScValType.scvVoid().value) { + throw new Error("Expected void, got ".concat(type.name)); + } + return null; + } + if (outputs.length > 1) { + throw new Error("Multiple outputs not supported"); + } + var output = outputs[0]; + if (output.switch().value === lib.xdr.ScSpecType.scSpecTypeResult().value) { + return new Ok(this.scValToNative(val, output.result().okType())); + } + return this.scValToNative(val, output); + } + }, { + key: "findEntry", + value: function findEntry(name) { + var entry = this.entries.find(function (e) { + return e.value().name().toString() === name; + }); + if (!entry) { + throw new Error("no such entry: ".concat(name)); + } + return entry; + } + }, { + key: "nativeToScVal", + value: function nativeToScVal(val, ty) { + var _this2 = this; + var t = ty.switch(); + var value = t.value; + if (t.value === lib.xdr.ScSpecType.scSpecTypeUdt().value) { + var udt = ty.udt(); + return this.nativeToUdt(val, udt.name().toString()); + } + if (value === lib.xdr.ScSpecType.scSpecTypeOption().value) { + var opt = ty.option(); + if (val === undefined) { + return lib.xdr.ScVal.scvVoid(); + } + return this.nativeToScVal(val, opt.valueType()); + } + switch (spec_typeof(val)) { + case "object": + { + var _val$constructor$name, _val$constructor; + if (val === null) { + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVoid().value: + return lib.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was null")); + } + } + if (val instanceof lib.xdr.ScVal) { + return val; + } + if (val instanceof lib.Address) { + if (ty.switch().value !== lib.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.toScVal(); + } + if (val instanceof lib.Contract) { + if (ty.switch().value !== lib.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.address().toScVal(); + } + if (val instanceof Uint8Array || spec_Buffer.isBuffer(val)) { + var copy = Uint8Array.from(val); + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var bytesN = ty.bytesN(); + if (copy.length !== bytesN.n()) { + throw new TypeError("expected ".concat(bytesN.n(), " bytes, but got ").concat(copy.length)); + } + return lib.xdr.ScVal.scvBytes(copy); + } + case lib.xdr.ScSpecType.scSpecTypeBytes().value: + return lib.xdr.ScVal.scvBytes(copy); + default: + throw new TypeError("invalid type (".concat(ty, ") specified for Bytes and BytesN")); + } + } + if (Array.isArray(val)) { + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVec().value: + { + var vec = ty.vec(); + var elementType = vec.elementType(); + return lib.xdr.ScVal.scvVec(val.map(function (v) { + return _this2.nativeToScVal(v, elementType); + })); + } + case lib.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tup = ty.tuple(); + var valTypes = tup.valueTypes(); + if (val.length !== valTypes.length) { + throw new TypeError("Tuple expects ".concat(valTypes.length, " values, but ").concat(val.length, " were provided")); + } + return lib.xdr.ScVal.scvVec(val.map(function (v, i) { + return _this2.nativeToScVal(v, valTypes[i]); + })); + } + case lib.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = ty.map(); + var keyType = map.keyType(); + var valueType = map.valueType(); + return lib.xdr.ScVal.scvMap(val.map(function (entry) { + var key = _this2.nativeToScVal(entry[0], keyType); + var mapVal = _this2.nativeToScVal(entry[1], valueType); + return new lib.xdr.ScMapEntry({ + key: key, + val: mapVal + }); + })); + } + default: + throw new TypeError("Type ".concat(ty, " was not vec, but value was Array")); + } + } + if (val.constructor === Map) { + if (value !== lib.xdr.ScSpecType.scSpecTypeMap().value) { + throw new TypeError("Type ".concat(ty, " was not map, but value was Map")); + } + var scMap = ty.map(); + var _map = val; + var entries = []; + var values = _map.entries(); + var res = values.next(); + while (!res.done) { + var _res$value = spec_slicedToArray(res.value, 2), + k = _res$value[0], + v = _res$value[1]; + var key = this.nativeToScVal(k, scMap.keyType()); + var mapval = this.nativeToScVal(v, scMap.valueType()); + entries.push(new lib.xdr.ScMapEntry({ + key: key, + val: mapval + })); + res = values.next(); + } + return lib.xdr.ScVal.scvMap(entries); + } + if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : "") !== "Object") { + var _val$constructor2; + throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")")); + } + throw new TypeError("Received object ".concat(val, " did not match the provided type ").concat(ty)); + } + case "number": + case "bigint": + { + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeU32().value: + return lib.xdr.ScVal.scvU32(val); + case lib.xdr.ScSpecType.scSpecTypeI32().value: + return lib.xdr.ScVal.scvI32(val); + case lib.xdr.ScSpecType.scSpecTypeU64().value: + case lib.xdr.ScSpecType.scSpecTypeI64().value: + case lib.xdr.ScSpecType.scSpecTypeU128().value: + case lib.xdr.ScSpecType.scSpecTypeI128().value: + case lib.xdr.ScSpecType.scSpecTypeU256().value: + case lib.xdr.ScSpecType.scSpecTypeI256().value: + { + var intType = t.name.substring(10).toLowerCase(); + return new lib.XdrLargeInt(intType, val).toScVal(); + } + default: + throw new TypeError("invalid type (".concat(ty, ") specified for integer")); + } + } + case "string": + return stringToScVal(val, t); + case "boolean": + { + if (value !== lib.xdr.ScSpecType.scSpecTypeBool().value) { + throw TypeError("Type ".concat(ty, " was not bool, but value was bool")); + } + return lib.xdr.ScVal.scvBool(val); + } + case "undefined": + { + if (!ty) { + return lib.xdr.ScVal.scvVoid(); + } + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVoid().value: + case lib.xdr.ScSpecType.scSpecTypeOption().value: + return lib.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was undefined")); + } + } + case "function": + return this.nativeToScVal(val(), ty); + default: + throw new TypeError("failed to convert typeof ".concat(spec_typeof(val), " (").concat(val, ")")); + } + } + }, { + key: "nativeToUdt", + value: function nativeToUdt(val, name) { + var entry = this.findEntry(name); + switch (entry.switch()) { + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + if (typeof val !== "number") { + throw new TypeError("expected number for enum ".concat(name, ", but got ").concat(spec_typeof(val))); + } + return this.nativeToEnum(val, entry.udtEnumV0()); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.nativeToStruct(val, entry.udtStructV0()); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.nativeToUnion(val, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(name)); + } + } + }, { + key: "nativeToUnion", + value: function nativeToUnion(val, union_) { + var _this3 = this; + var entryName = val.tag; + var caseFound = union_.cases().find(function (entry) { + var caseN = entry.value().name().toString(); + return caseN === entryName; + }); + if (!caseFound) { + throw new TypeError("no such enum entry: ".concat(entryName, " in ").concat(union_)); + } + var key = lib.xdr.ScVal.scvSymbol(entryName); + switch (caseFound.switch()) { + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0(): + { + return lib.xdr.ScVal.scvVec([key]); + } + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0(): + { + var types = caseFound.tupleCase().type(); + if (Array.isArray(val.values)) { + if (val.values.length !== types.length) { + throw new TypeError("union ".concat(union_, " expects ").concat(types.length, " values, but got ").concat(val.values.length)); + } + var scvals = val.values.map(function (v, i) { + return _this3.nativeToScVal(v, types[i]); + }); + scvals.unshift(key); + return lib.xdr.ScVal.scvVec(scvals); + } + throw new Error("failed to parse union case ".concat(caseFound, " with ").concat(val)); + } + default: + throw new Error("failed to parse union ".concat(union_, " with ").concat(val)); + } + } + }, { + key: "nativeToStruct", + value: function nativeToStruct(val, struct) { + var _this4 = this; + var fields = struct.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + return lib.xdr.ScVal.scvVec(fields.map(function (_, i) { + return _this4.nativeToScVal(val[i], fields[i].type()); + })); + } + return lib.xdr.ScVal.scvMap(fields.map(function (field) { + var name = field.name().toString(); + return new lib.xdr.ScMapEntry({ + key: _this4.nativeToScVal(name, lib.xdr.ScSpecTypeDef.scSpecTypeSymbol()), + val: _this4.nativeToScVal(val[name], field.type()) + }); + })); + } + }, { + key: "nativeToEnum", + value: function nativeToEnum(val, enum_) { + if (enum_.cases().some(function (entry) { + return entry.value() === val; + })) { + return lib.xdr.ScVal.scvU32(val); + } + throw new TypeError("no such enum entry: ".concat(val, " in ").concat(enum_)); + } + }, { + key: "scValStrToNative", + value: function scValStrToNative(scv, typeDef) { + return this.scValToNative(lib.xdr.ScVal.fromXDR(scv, "base64"), typeDef); + } + }, { + key: "scValToNative", + value: function scValToNative(scv, typeDef) { + var _this5 = this; + var t = typeDef.switch(); + var value = t.value; + if (value === lib.xdr.ScSpecType.scSpecTypeUdt().value) { + return this.scValUdtToNative(scv, typeDef.udt()); + } + switch (scv.switch().value) { + case lib.xdr.ScValType.scvVoid().value: + return undefined; + case lib.xdr.ScValType.scvU64().value: + case lib.xdr.ScValType.scvI64().value: + case lib.xdr.ScValType.scvU128().value: + case lib.xdr.ScValType.scvI128().value: + case lib.xdr.ScValType.scvU256().value: + case lib.xdr.ScValType.scvI256().value: + return (0,lib.scValToBigInt)(scv); + case lib.xdr.ScValType.scvVec().value: + { + if (value === lib.xdr.ScSpecType.scSpecTypeVec().value) { + var _scv$vec; + var vec = typeDef.vec(); + return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(function (elm) { + return _this5.scValToNative(elm, vec.elementType()); + }); + } + if (value === lib.xdr.ScSpecType.scSpecTypeTuple().value) { + var _scv$vec2; + var tuple = typeDef.tuple(); + var valTypes = tuple.valueTypes(); + return ((_scv$vec2 = scv.vec()) !== null && _scv$vec2 !== void 0 ? _scv$vec2 : []).map(function (elm, i) { + return _this5.scValToNative(elm, valTypes[i]); + }); + } + throw new TypeError("Type ".concat(typeDef, " was not vec, but ").concat(scv, " is")); + } + case lib.xdr.ScValType.scvAddress().value: + return lib.Address.fromScVal(scv).toString(); + case lib.xdr.ScValType.scvMap().value: + { + var _scv$map; + var map = (_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []; + if (value === lib.xdr.ScSpecType.scSpecTypeMap().value) { + var typed = typeDef.map(); + var keyType = typed.keyType(); + var valueType = typed.valueType(); + var res = map.map(function (entry) { + return [_this5.scValToNative(entry.key(), keyType), _this5.scValToNative(entry.val(), valueType)]; + }); + return res; + } + throw new TypeError("ScSpecType ".concat(t.name, " was not map, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + case lib.xdr.ScValType.scvBool().value: + case lib.xdr.ScValType.scvU32().value: + case lib.xdr.ScValType.scvI32().value: + case lib.xdr.ScValType.scvBytes().value: + return scv.value(); + case lib.xdr.ScValType.scvString().value: + case lib.xdr.ScValType.scvSymbol().value: + { + var _scv$value; + if (value !== lib.xdr.ScSpecType.scSpecTypeString().value && value !== lib.xdr.ScSpecType.scSpecTypeSymbol().value) { + throw new Error("ScSpecType ".concat(t.name, " was not string or symbol, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + return (_scv$value = scv.value()) === null || _scv$value === void 0 ? void 0 : _scv$value.toString(); + } + case lib.xdr.ScValType.scvTimepoint().value: + case lib.xdr.ScValType.scvDuration().value: + return (0,lib.scValToBigInt)(lib.xdr.ScVal.scvU64(scv.u64())); + default: + throw new TypeError("failed to convert ".concat(JSON.stringify(scv, null, 2), " to native type from type ").concat(t.name)); + } + } + }, { + key: "scValUdtToNative", + value: function scValUdtToNative(scv, udt) { + var entry = this.findEntry(udt.name().toString()); + switch (entry.switch()) { + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + return this.enumToNative(scv); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.structToNative(scv, entry.udtStructV0()); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.unionToNative(scv, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(udt.name().toString(), ": ").concat(entry)); + } + } + }, { + key: "unionToNative", + value: function unionToNative(val, udt) { + var _this6 = this; + var vec = val.vec(); + if (!vec) { + throw new Error("".concat(JSON.stringify(val, null, 2), " is not a vec")); + } + if (vec.length === 0 && udt.cases.length !== 0) { + throw new Error("".concat(val, " has length 0, but the there are at least one case in the union")); + } + var name = vec[0].sym().toString(); + if (vec[0].switch().value !== lib.xdr.ScValType.scvSymbol().value) { + throw new Error("{vec[0]} is not a symbol"); + } + var entry = udt.cases().find(findCase(name)); + if (!entry) { + throw new Error("failed to find entry ".concat(name, " in union {udt.name().toString()}")); + } + var res = { + tag: name + }; + if (entry.switch().value === lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value) { + var tuple = entry.tupleCase(); + var ty = tuple.type(); + var values = ty.map(function (e, i) { + return _this6.scValToNative(vec[i + 1], e); + }); + res.values = values; + } + return res; + } + }, { + key: "structToNative", + value: function structToNative(val, udt) { + var _this7 = this, + _val$map; + var res = {}; + var fields = udt.fields(); + if (fields.some(isNumeric)) { + var _val$vec; + var r = (_val$vec = val.vec()) === null || _val$vec === void 0 ? void 0 : _val$vec.map(function (entry, i) { + return _this7.scValToNative(entry, fields[i].type()); + }); + return r; + } + (_val$map = val.map()) === null || _val$map === void 0 || _val$map.forEach(function (entry, i) { + var field = fields[i]; + res[field.name().toString()] = _this7.scValToNative(entry.val(), field.type()); + }); + return res; + } + }, { + key: "enumToNative", + value: function enumToNative(scv) { + if (scv.switch().value !== lib.xdr.ScValType.scvU32().value) { + throw new Error("Enum must have a u32 value"); + } + var num = scv.u32(); + return num; + } + }, { + key: "errorCases", + value: function errorCases() { + return this.entries.filter(function (entry) { + return entry.switch().value === lib.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value; + }).flatMap(function (entry) { + return entry.value().cases(); + }); + } + }, { + key: "jsonSchema", + value: function jsonSchema(funcName) { + var definitions = {}; + this.entries.forEach(function (entry) { + switch (entry.switch().value) { + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0().value: + { + var udt = entry.udtEnumV0(); + definitions[udt.name().toString()] = enumToJsonSchema(udt); + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0().value: + { + var _udt = entry.udtStructV0(); + definitions[_udt.name().toString()] = structToJsonSchema(_udt); + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0().value: + { + var _udt2 = entry.udtUnionV0(); + definitions[_udt2.name().toString()] = unionToJsonSchema(_udt2); + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value: + { + var fn = entry.functionV0(); + var fnName = fn.name().toString(); + var _functionToJsonSchema = functionToJsonSchema(fn), + input = _functionToJsonSchema.input; + definitions[fnName] = input; + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value: + {} + } + }); + var res = { + $schema: "http://json-schema.org/draft-07/schema#", + definitions: spec_objectSpread(spec_objectSpread({}, PRIMITIVE_DEFINITONS), definitions) + }; + if (funcName) { + res.$ref = "#/definitions/".concat(funcName); + } + return res; + } + }]); +}(); +;// ./src/contract/client.ts +/* provided dependency */ var client_Buffer = __webpack_require__(8287)["Buffer"]; +function client_typeof(o) { "@babel/helpers - typeof"; return client_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, client_typeof(o); } +var _excluded = ["method"], + _excluded2 = ["wasmHash", "salt", "format", "fee", "timeoutInSeconds", "simulate"]; +function client_regeneratorRuntime() { "use strict"; client_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == client_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(client_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function client_ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function client_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? client_ownKeys(Object(t), !0).forEach(function (r) { client_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : client_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } +function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; } +function client_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function client_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, client_toPropertyKey(o.key), o); } } +function client_createClass(e, r, t) { return r && client_defineProperties(e.prototype, r), t && client_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function client_defineProperty(e, r, t) { return (r = client_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function client_toPropertyKey(t) { var i = client_toPrimitive(t, "string"); return "symbol" == client_typeof(i) ? i : i + ""; } +function client_toPrimitive(t, r) { if ("object" != client_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != client_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function client_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function client_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { client_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { client_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + + + + + +var CONSTRUCTOR_FUNC = "__constructor"; +function specFromWasm(_x) { + return _specFromWasm.apply(this, arguments); +} +function _specFromWasm() { + _specFromWasm = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee5(wasm) { + var wasmModule, xdrSections, bufferSection, specEntryArray, spec; + return client_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return WebAssembly.compile(wasm); + case 2: + wasmModule = _context5.sent; + xdrSections = WebAssembly.Module.customSections(wasmModule, "contractspecv0"); + if (!(xdrSections.length === 0)) { + _context5.next = 6; + break; + } + throw new Error("Could not obtain contract spec from wasm"); + case 6: + bufferSection = client_Buffer.from(xdrSections[0]); + specEntryArray = processSpecEntryStream(bufferSection); + spec = new Spec(specEntryArray); + return _context5.abrupt("return", spec); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _specFromWasm.apply(this, arguments); +} +function specFromWasmHash(_x2, _x3) { + return _specFromWasmHash.apply(this, arguments); +} +function _specFromWasmHash() { + _specFromWasmHash = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee6(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args6 = arguments; + return client_regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + format = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context6.next = 3; + break; + } + throw new TypeError("options must contain rpcUrl"); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new rpc.Server(rpcUrl, serverOpts); + _context6.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context6.sent; + return _context6.abrupt("return", specFromWasm(wasm)); + case 10: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _specFromWasmHash.apply(this, arguments); +} +var Client = function () { + function Client(spec, options) { + var _this = this; + client_classCallCheck(this, Client); + client_defineProperty(this, "txFromJSON", function (json) { + var _JSON$parse = JSON.parse(json), + method = _JSON$parse.method, + tx = _objectWithoutProperties(_JSON$parse, _excluded); + return AssembledTransaction.fromJSON(client_objectSpread(client_objectSpread({}, _this.options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return _this.spec.funcResToNative(method, result); + } + }), tx); + }); + client_defineProperty(this, "txFromXDR", function (xdrBase64) { + return AssembledTransaction.fromXDR(_this.options, xdrBase64, _this.spec); + }); + this.spec = spec; + this.options = options; + this.spec.funcs().forEach(function (xdrFn) { + var method = xdrFn.name().toString(); + if (method === CONSTRUCTOR_FUNC) { + return; + } + var assembleTransaction = function assembleTransaction(args, methodOptions) { + return AssembledTransaction.build(client_objectSpread(client_objectSpread(client_objectSpread({ + method: method, + args: args && spec.funcArgsToScVals(method, args) + }, options), methodOptions), {}, { + errorTypes: spec.errorCases().reduce(function (acc, curr) { + return client_objectSpread(client_objectSpread({}, acc), {}, client_defineProperty({}, curr.value(), { + message: curr.doc().toString() + })); + }, {}), + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + }; + _this[method] = spec.getFunc(method).inputs().length === 0 ? function (opts) { + return assembleTransaction(undefined, opts); + } : assembleTransaction; + }); + } + return client_createClass(Client, null, [{ + key: "deploy", + value: function () { + var _deploy = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee(args, options) { + var wasmHash, salt, format, fee, timeoutInSeconds, simulate, clientOptions, spec, operation; + return client_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + wasmHash = options.wasmHash, salt = options.salt, format = options.format, fee = options.fee, timeoutInSeconds = options.timeoutInSeconds, simulate = options.simulate, clientOptions = _objectWithoutProperties(options, _excluded2); + _context.next = 3; + return specFromWasmHash(wasmHash, clientOptions, format); + case 3: + spec = _context.sent; + operation = lib.Operation.createCustomContract({ + address: new lib.Address(options.publicKey), + wasmHash: typeof wasmHash === "string" ? client_Buffer.from(wasmHash, format !== null && format !== void 0 ? format : "hex") : wasmHash, + salt: salt, + constructorArgs: args ? spec.funcArgsToScVals(CONSTRUCTOR_FUNC, args) : [] + }); + return _context.abrupt("return", AssembledTransaction.buildWithOp(operation, client_objectSpread(client_objectSpread({ + fee: fee, + timeoutInSeconds: timeoutInSeconds, + simulate: simulate + }, clientOptions), {}, { + contractId: "ignored", + method: CONSTRUCTOR_FUNC, + parseResultXdr: function parseResultXdr(result) { + return new Client(spec, client_objectSpread(client_objectSpread({}, clientOptions), {}, { + contractId: lib.Address.fromScVal(result).toString() + })); + } + }))); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + function deploy(_x4, _x5) { + return _deploy.apply(this, arguments); + } + return deploy; + }() + }, { + key: "fromWasmHash", + value: (function () { + var _fromWasmHash = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee2(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args2 = arguments; + return client_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + format = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context2.next = 3; + break; + } + throw new TypeError('options must contain rpcUrl'); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new rpc.Server(rpcUrl, serverOpts); + _context2.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context2.sent; + return _context2.abrupt("return", Client.fromWasm(wasm, options)); + case 10: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function fromWasmHash(_x6, _x7) { + return _fromWasmHash.apply(this, arguments); + } + return fromWasmHash; + }()) + }, { + key: "fromWasm", + value: (function () { + var _fromWasm = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee3(wasm, options) { + var spec; + return client_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return specFromWasm(wasm); + case 2: + spec = _context3.sent; + return _context3.abrupt("return", new Client(spec, options)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + function fromWasm(_x8, _x9) { + return _fromWasm.apply(this, arguments); + } + return fromWasm; + }()) + }, { + key: "from", + value: (function () { + var _from = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee4(options) { + var rpcUrl, contractId, allowHttp, serverOpts, server, wasm; + return client_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(!options || !options.rpcUrl || !options.contractId)) { + _context4.next = 2; + break; + } + throw new TypeError('options must contain rpcUrl and contractId'); + case 2: + rpcUrl = options.rpcUrl, contractId = options.contractId, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new rpc.Server(rpcUrl, serverOpts); + _context4.next = 7; + return server.getContractWasmByContractId(contractId); + case 7: + wasm = _context4.sent; + return _context4.abrupt("return", Client.fromWasm(wasm, options)); + case 9: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function from(_x10) { + return _from.apply(this, arguments); + } + return from; + }()) + }]); +}(); +;// ./src/contract/index.ts + + + + + + + + +/***/ }), + +/***/ 5976: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Cu: () => (/* reexport */ AccountRequiresMemoError), + v7: () => (/* reexport */ BadRequestError), + nS: () => (/* reexport */ BadResponseError), + Dr: () => (/* reexport */ NetworkError), + m_: () => (/* reexport */ NotFoundError) +}); + +;// ./src/errors/network.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var NetworkError = function (_Error) { + function NetworkError(message, response) { + var _this; + _classCallCheck(this, NetworkError); + var trueProto = (this instanceof NetworkError ? this.constructor : void 0).prototype; + _this = _callSuper(this, NetworkError, [message]); + _this.__proto__ = trueProto; + _this.constructor = NetworkError; + _this.response = response; + return _this; + } + _inherits(NetworkError, _Error); + return _createClass(NetworkError, [{ + key: "getResponse", + value: function getResponse() { + return this.response; + } + }]); +}(_wrapNativeSuper(Error)); +;// ./src/errors/not_found.ts +function not_found_typeof(o) { "@babel/helpers - typeof"; return not_found_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, not_found_typeof(o); } +function not_found_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, not_found_toPropertyKey(o.key), o); } } +function not_found_createClass(e, r, t) { return r && not_found_defineProperties(e.prototype, r), t && not_found_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function not_found_toPropertyKey(t) { var i = not_found_toPrimitive(t, "string"); return "symbol" == not_found_typeof(i) ? i : i + ""; } +function not_found_toPrimitive(t, r) { if ("object" != not_found_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != not_found_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function not_found_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function not_found_callSuper(t, o, e) { return o = not_found_getPrototypeOf(o), not_found_possibleConstructorReturn(t, not_found_isNativeReflectConstruct() ? Reflect.construct(o, e || [], not_found_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function not_found_possibleConstructorReturn(t, e) { if (e && ("object" == not_found_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return not_found_assertThisInitialized(t); } +function not_found_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function not_found_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (not_found_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function not_found_getPrototypeOf(t) { return not_found_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, not_found_getPrototypeOf(t); } +function not_found_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && not_found_setPrototypeOf(t, e); } +function not_found_setPrototypeOf(t, e) { return not_found_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, not_found_setPrototypeOf(t, e); } + +var NotFoundError = function (_NetworkError) { + function NotFoundError(message, response) { + var _this; + not_found_classCallCheck(this, NotFoundError); + var trueProto = (this instanceof NotFoundError ? this.constructor : void 0).prototype; + _this = not_found_callSuper(this, NotFoundError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = NotFoundError; + _this.name = "NotFoundError"; + return _this; + } + not_found_inherits(NotFoundError, _NetworkError); + return not_found_createClass(NotFoundError); +}(NetworkError); +;// ./src/errors/bad_request.ts +function bad_request_typeof(o) { "@babel/helpers - typeof"; return bad_request_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, bad_request_typeof(o); } +function bad_request_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, bad_request_toPropertyKey(o.key), o); } } +function bad_request_createClass(e, r, t) { return r && bad_request_defineProperties(e.prototype, r), t && bad_request_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function bad_request_toPropertyKey(t) { var i = bad_request_toPrimitive(t, "string"); return "symbol" == bad_request_typeof(i) ? i : i + ""; } +function bad_request_toPrimitive(t, r) { if ("object" != bad_request_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != bad_request_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function bad_request_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function bad_request_callSuper(t, o, e) { return o = bad_request_getPrototypeOf(o), bad_request_possibleConstructorReturn(t, bad_request_isNativeReflectConstruct() ? Reflect.construct(o, e || [], bad_request_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function bad_request_possibleConstructorReturn(t, e) { if (e && ("object" == bad_request_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return bad_request_assertThisInitialized(t); } +function bad_request_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function bad_request_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (bad_request_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function bad_request_getPrototypeOf(t) { return bad_request_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, bad_request_getPrototypeOf(t); } +function bad_request_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && bad_request_setPrototypeOf(t, e); } +function bad_request_setPrototypeOf(t, e) { return bad_request_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, bad_request_setPrototypeOf(t, e); } + +var BadRequestError = function (_NetworkError) { + function BadRequestError(message, response) { + var _this; + bad_request_classCallCheck(this, BadRequestError); + var trueProto = (this instanceof BadRequestError ? this.constructor : void 0).prototype; + _this = bad_request_callSuper(this, BadRequestError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadRequestError; + _this.name = "BadRequestError"; + return _this; + } + bad_request_inherits(BadRequestError, _NetworkError); + return bad_request_createClass(BadRequestError); +}(NetworkError); +;// ./src/errors/bad_response.ts +function bad_response_typeof(o) { "@babel/helpers - typeof"; return bad_response_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, bad_response_typeof(o); } +function bad_response_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, bad_response_toPropertyKey(o.key), o); } } +function bad_response_createClass(e, r, t) { return r && bad_response_defineProperties(e.prototype, r), t && bad_response_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function bad_response_toPropertyKey(t) { var i = bad_response_toPrimitive(t, "string"); return "symbol" == bad_response_typeof(i) ? i : i + ""; } +function bad_response_toPrimitive(t, r) { if ("object" != bad_response_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != bad_response_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function bad_response_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function bad_response_callSuper(t, o, e) { return o = bad_response_getPrototypeOf(o), bad_response_possibleConstructorReturn(t, bad_response_isNativeReflectConstruct() ? Reflect.construct(o, e || [], bad_response_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function bad_response_possibleConstructorReturn(t, e) { if (e && ("object" == bad_response_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return bad_response_assertThisInitialized(t); } +function bad_response_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function bad_response_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (bad_response_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function bad_response_getPrototypeOf(t) { return bad_response_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, bad_response_getPrototypeOf(t); } +function bad_response_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && bad_response_setPrototypeOf(t, e); } +function bad_response_setPrototypeOf(t, e) { return bad_response_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, bad_response_setPrototypeOf(t, e); } + +var BadResponseError = function (_NetworkError) { + function BadResponseError(message, response) { + var _this; + bad_response_classCallCheck(this, BadResponseError); + var trueProto = (this instanceof BadResponseError ? this.constructor : void 0).prototype; + _this = bad_response_callSuper(this, BadResponseError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadResponseError; + _this.name = "BadResponseError"; + return _this; + } + bad_response_inherits(BadResponseError, _NetworkError); + return bad_response_createClass(BadResponseError); +}(NetworkError); +;// ./src/errors/account_requires_memo.ts +function account_requires_memo_typeof(o) { "@babel/helpers - typeof"; return account_requires_memo_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, account_requires_memo_typeof(o); } +function account_requires_memo_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, account_requires_memo_toPropertyKey(o.key), o); } } +function account_requires_memo_createClass(e, r, t) { return r && account_requires_memo_defineProperties(e.prototype, r), t && account_requires_memo_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function account_requires_memo_toPropertyKey(t) { var i = account_requires_memo_toPrimitive(t, "string"); return "symbol" == account_requires_memo_typeof(i) ? i : i + ""; } +function account_requires_memo_toPrimitive(t, r) { if ("object" != account_requires_memo_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != account_requires_memo_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function account_requires_memo_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function account_requires_memo_callSuper(t, o, e) { return o = account_requires_memo_getPrototypeOf(o), account_requires_memo_possibleConstructorReturn(t, account_requires_memo_isNativeReflectConstruct() ? Reflect.construct(o, e || [], account_requires_memo_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function account_requires_memo_possibleConstructorReturn(t, e) { if (e && ("object" == account_requires_memo_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return account_requires_memo_assertThisInitialized(t); } +function account_requires_memo_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function account_requires_memo_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && account_requires_memo_setPrototypeOf(t, e); } +function account_requires_memo_wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return account_requires_memo_wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !account_requires_memo_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return account_requires_memo_construct(t, arguments, account_requires_memo_getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), account_requires_memo_setPrototypeOf(Wrapper, t); }, account_requires_memo_wrapNativeSuper(t); } +function account_requires_memo_construct(t, e, r) { if (account_requires_memo_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && account_requires_memo_setPrototypeOf(p, r.prototype), p; } +function account_requires_memo_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (account_requires_memo_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function account_requires_memo_isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function account_requires_memo_setPrototypeOf(t, e) { return account_requires_memo_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, account_requires_memo_setPrototypeOf(t, e); } +function account_requires_memo_getPrototypeOf(t) { return account_requires_memo_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, account_requires_memo_getPrototypeOf(t); } +var AccountRequiresMemoError = function (_Error) { + function AccountRequiresMemoError(message, accountId, operationIndex) { + var _this; + account_requires_memo_classCallCheck(this, AccountRequiresMemoError); + var trueProto = (this instanceof AccountRequiresMemoError ? this.constructor : void 0).prototype; + _this = account_requires_memo_callSuper(this, AccountRequiresMemoError, [message]); + _this.__proto__ = trueProto; + _this.constructor = AccountRequiresMemoError; + _this.name = "AccountRequiresMemoError"; + _this.accountId = accountId; + _this.operationIndex = operationIndex; + return _this; + } + account_requires_memo_inherits(AccountRequiresMemoError, _Error); + return account_requires_memo_createClass(AccountRequiresMemoError); +}(account_requires_memo_wrapNativeSuper(Error)); +;// ./src/errors/index.ts + + + + + + +/***/ }), + +/***/ 7600: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Api: () => (/* reexport */ Api), + FEDERATION_RESPONSE_MAX_SIZE: () => (/* reexport */ FEDERATION_RESPONSE_MAX_SIZE), + Server: () => (/* reexport */ FederationServer) +}); + +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js +var URI = __webpack_require__(4193); +var URI_default = /*#__PURE__*/__webpack_require__.n(URI); +// EXTERNAL MODULE: ./src/config.ts +var config = __webpack_require__(8732); +// EXTERNAL MODULE: ./src/errors/index.ts + 5 modules +var errors = __webpack_require__(5976); +// EXTERNAL MODULE: ./src/stellartoml/index.ts +var stellartoml = __webpack_require__(3898); +// EXTERNAL MODULE: ./src/http-client/index.ts + 1 modules +var http_client = __webpack_require__(9983); +;// ./src/federation/server.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + +var FEDERATION_RESPONSE_MAX_SIZE = 100 * 1024; +var FederationServer = function () { + function FederationServer(serverURL, domain) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + _classCallCheck(this, FederationServer); + this.serverURL = URI_default()(serverURL); + this.domain = domain; + var allowHttp = typeof opts.allowHttp === "undefined" ? config/* Config */.T.isAllowHttp() : opts.allowHttp; + this.timeout = typeof opts.timeout === "undefined" ? config/* Config */.T.getTimeout() : opts.timeout; + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure federation server"); + } + } + return _createClass(FederationServer, [{ + key: "resolveAddress", + value: (function () { + var _resolveAddress = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(address) { + var stellarAddress, url; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + stellarAddress = address; + if (!(address.indexOf("*") < 0)) { + _context.next = 5; + break; + } + if (this.domain) { + _context.next = 4; + break; + } + return _context.abrupt("return", Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object."))); + case 4: + stellarAddress = "".concat(address, "*").concat(this.domain); + case 5: + url = this.serverURL.query({ + type: "name", + q: stellarAddress + }); + return _context.abrupt("return", this._sendRequest(url)); + case 7: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function resolveAddress(_x) { + return _resolveAddress.apply(this, arguments); + } + return resolveAddress; + }()) + }, { + key: "resolveAccountId", + value: (function () { + var _resolveAccountId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(accountId) { + var url; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + url = this.serverURL.query({ + type: "id", + q: accountId + }); + return _context2.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function resolveAccountId(_x2) { + return _resolveAccountId.apply(this, arguments); + } + return resolveAccountId; + }()) + }, { + key: "resolveTransactionId", + value: (function () { + var _resolveTransactionId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(transactionId) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = this.serverURL.query({ + type: "txid", + q: transactionId + }); + return _context3.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function resolveTransactionId(_x3) { + return _resolveTransactionId.apply(this, arguments); + } + return resolveTransactionId; + }()) + }, { + key: "_sendRequest", + value: function () { + var _sendRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(url) { + var timeout; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + timeout = this.timeout; + return _context4.abrupt("return", http_client/* httpClient */.ok.get(url.toString(), { + maxContentLength: FEDERATION_RESPONSE_MAX_SIZE, + timeout: timeout + }).then(function (response) { + if (typeof response.data.memo !== "undefined" && typeof response.data.memo !== "string") { + throw new Error("memo value should be of type string"); + } + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + if (response.message.match(/^maxContentLength size/)) { + throw new Error("federation response exceeds allowed size of ".concat(FEDERATION_RESPONSE_MAX_SIZE)); + } else { + return Promise.reject(response); + } + } else { + return Promise.reject(new errors/* BadResponseError */.nS("Server query failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + } + })); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function _sendRequest(_x4) { + return _sendRequest2.apply(this, arguments); + } + return _sendRequest; + }() + }], [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(value) { + var opts, + addressParts, + _addressParts, + domain, + federationServer, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {}; + if (!(value.indexOf("*") < 0)) { + _context5.next = 5; + break; + } + if (lib.StrKey.isValidEd25519PublicKey(value)) { + _context5.next = 4; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Account ID"))); + case 4: + return _context5.abrupt("return", Promise.resolve({ + account_id: value + })); + case 5: + addressParts = value.split("*"); + _addressParts = _slicedToArray(addressParts, 2), domain = _addressParts[1]; + if (!(addressParts.length !== 2 || !domain)) { + _context5.next = 9; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Stellar address"))); + case 9: + _context5.next = 11; + return FederationServer.createForDomain(domain, opts); + case 11: + federationServer = _context5.sent; + return _context5.abrupt("return", federationServer.resolveAddress(value)); + case 13: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function resolve(_x5) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }, { + key: "createForDomain", + value: (function () { + var _createForDomain = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(domain) { + var opts, + tomlObject, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : {}; + _context6.next = 3; + return stellartoml.Resolver.resolve(domain, opts); + case 3: + tomlObject = _context6.sent; + if (tomlObject.FEDERATION_SERVER) { + _context6.next = 6; + break; + } + return _context6.abrupt("return", Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field"))); + case 6: + return _context6.abrupt("return", new FederationServer(tomlObject.FEDERATION_SERVER, domain, opts)); + case 7: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function createForDomain(_x6) { + return _createForDomain.apply(this, arguments); + } + return createForDomain; + }()) + }]); +}(); +;// ./src/federation/api.ts +var Api; +;// ./src/federation/index.ts + + + +/***/ }), + +/***/ 8242: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Api: () => (/* binding */ Api) +/* harmony export */ }); +var Api; + +/***/ }), + +/***/ 8733: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + AccountResponse: () => (/* reexport */ AccountResponse), + AxiosClient: () => (/* reexport */ horizon_axios_client), + HorizonApi: () => (/* reexport */ HorizonApi), + SERVER_TIME_MAP: () => (/* reexport */ SERVER_TIME_MAP), + Server: () => (/* reexport */ HorizonServer), + ServerApi: () => (/* reexport */ ServerApi), + "default": () => (/* binding */ horizon), + getCurrentServerTime: () => (/* reexport */ getCurrentServerTime) +}); + +;// ./src/horizon/horizon_api.ts +var HorizonApi; +(function (_HorizonApi) { + var LiquidityPoolType = function (LiquidityPoolType) { + LiquidityPoolType["constantProduct"] = "constant_product"; + return LiquidityPoolType; + }({}); + _HorizonApi.LiquidityPoolType = LiquidityPoolType; + var OperationResponseType = function (OperationResponseType) { + OperationResponseType["createAccount"] = "create_account"; + OperationResponseType["payment"] = "payment"; + OperationResponseType["pathPayment"] = "path_payment_strict_receive"; + OperationResponseType["createPassiveOffer"] = "create_passive_sell_offer"; + OperationResponseType["manageOffer"] = "manage_sell_offer"; + OperationResponseType["setOptions"] = "set_options"; + OperationResponseType["changeTrust"] = "change_trust"; + OperationResponseType["allowTrust"] = "allow_trust"; + OperationResponseType["accountMerge"] = "account_merge"; + OperationResponseType["inflation"] = "inflation"; + OperationResponseType["manageData"] = "manage_data"; + OperationResponseType["bumpSequence"] = "bump_sequence"; + OperationResponseType["manageBuyOffer"] = "manage_buy_offer"; + OperationResponseType["pathPaymentStrictSend"] = "path_payment_strict_send"; + OperationResponseType["createClaimableBalance"] = "create_claimable_balance"; + OperationResponseType["claimClaimableBalance"] = "claim_claimable_balance"; + OperationResponseType["beginSponsoringFutureReserves"] = "begin_sponsoring_future_reserves"; + OperationResponseType["endSponsoringFutureReserves"] = "end_sponsoring_future_reserves"; + OperationResponseType["revokeSponsorship"] = "revoke_sponsorship"; + OperationResponseType["clawback"] = "clawback"; + OperationResponseType["clawbackClaimableBalance"] = "clawback_claimable_balance"; + OperationResponseType["setTrustLineFlags"] = "set_trust_line_flags"; + OperationResponseType["liquidityPoolDeposit"] = "liquidity_pool_deposit"; + OperationResponseType["liquidityPoolWithdraw"] = "liquidity_pool_withdraw"; + OperationResponseType["invokeHostFunction"] = "invoke_host_function"; + OperationResponseType["bumpFootprintExpiration"] = "bump_footprint_expiration"; + OperationResponseType["restoreFootprint"] = "restore_footprint"; + return OperationResponseType; + }({}); + _HorizonApi.OperationResponseType = OperationResponseType; + var OperationResponseTypeI = function (OperationResponseTypeI) { + OperationResponseTypeI[OperationResponseTypeI["createAccount"] = 0] = "createAccount"; + OperationResponseTypeI[OperationResponseTypeI["payment"] = 1] = "payment"; + OperationResponseTypeI[OperationResponseTypeI["pathPayment"] = 2] = "pathPayment"; + OperationResponseTypeI[OperationResponseTypeI["createPassiveOffer"] = 3] = "createPassiveOffer"; + OperationResponseTypeI[OperationResponseTypeI["manageOffer"] = 4] = "manageOffer"; + OperationResponseTypeI[OperationResponseTypeI["setOptions"] = 5] = "setOptions"; + OperationResponseTypeI[OperationResponseTypeI["changeTrust"] = 6] = "changeTrust"; + OperationResponseTypeI[OperationResponseTypeI["allowTrust"] = 7] = "allowTrust"; + OperationResponseTypeI[OperationResponseTypeI["accountMerge"] = 8] = "accountMerge"; + OperationResponseTypeI[OperationResponseTypeI["inflation"] = 9] = "inflation"; + OperationResponseTypeI[OperationResponseTypeI["manageData"] = 10] = "manageData"; + OperationResponseTypeI[OperationResponseTypeI["bumpSequence"] = 11] = "bumpSequence"; + OperationResponseTypeI[OperationResponseTypeI["manageBuyOffer"] = 12] = "manageBuyOffer"; + OperationResponseTypeI[OperationResponseTypeI["pathPaymentStrictSend"] = 13] = "pathPaymentStrictSend"; + OperationResponseTypeI[OperationResponseTypeI["createClaimableBalance"] = 14] = "createClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["claimClaimableBalance"] = 15] = "claimClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["beginSponsoringFutureReserves"] = 16] = "beginSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["endSponsoringFutureReserves"] = 17] = "endSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["revokeSponsorship"] = 18] = "revokeSponsorship"; + OperationResponseTypeI[OperationResponseTypeI["clawback"] = 19] = "clawback"; + OperationResponseTypeI[OperationResponseTypeI["clawbackClaimableBalance"] = 20] = "clawbackClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["setTrustLineFlags"] = 21] = "setTrustLineFlags"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolDeposit"] = 22] = "liquidityPoolDeposit"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolWithdraw"] = 23] = "liquidityPoolWithdraw"; + OperationResponseTypeI[OperationResponseTypeI["invokeHostFunction"] = 24] = "invokeHostFunction"; + OperationResponseTypeI[OperationResponseTypeI["bumpFootprintExpiration"] = 25] = "bumpFootprintExpiration"; + OperationResponseTypeI[OperationResponseTypeI["restoreFootprint"] = 26] = "restoreFootprint"; + return OperationResponseTypeI; + }({}); + _HorizonApi.OperationResponseTypeI = OperationResponseTypeI; + ; + var TransactionFailedResultCodes = function (TransactionFailedResultCodes) { + TransactionFailedResultCodes["TX_FAILED"] = "tx_failed"; + TransactionFailedResultCodes["TX_BAD_SEQ"] = "tx_bad_seq"; + TransactionFailedResultCodes["TX_BAD_AUTH"] = "tx_bad_auth"; + TransactionFailedResultCodes["TX_BAD_AUTH_EXTRA"] = "tx_bad_auth_extra"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_SUCCESS"] = "tx_fee_bump_inner_success"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_FAILED"] = "tx_fee_bump_inner_failed"; + TransactionFailedResultCodes["TX_NOT_SUPPORTED"] = "tx_not_supported"; + TransactionFailedResultCodes["TX_SUCCESS"] = "tx_success"; + TransactionFailedResultCodes["TX_TOO_EARLY"] = "tx_too_early"; + TransactionFailedResultCodes["TX_TOO_LATE"] = "tx_too_late"; + TransactionFailedResultCodes["TX_MISSING_OPERATION"] = "tx_missing_operation"; + TransactionFailedResultCodes["TX_INSUFFICIENT_BALANCE"] = "tx_insufficient_balance"; + TransactionFailedResultCodes["TX_NO_SOURCE_ACCOUNT"] = "tx_no_source_account"; + TransactionFailedResultCodes["TX_INSUFFICIENT_FEE"] = "tx_insufficient_fee"; + TransactionFailedResultCodes["TX_INTERNAL_ERROR"] = "tx_internal_error"; + return TransactionFailedResultCodes; + }({}); + _HorizonApi.TransactionFailedResultCodes = TransactionFailedResultCodes; +})(HorizonApi || (HorizonApi = {})); +;// ./src/horizon/types/effects.ts +var effects_EffectType = function (EffectType) { + EffectType[EffectType["account_created"] = 0] = "account_created"; + EffectType[EffectType["account_removed"] = 1] = "account_removed"; + EffectType[EffectType["account_credited"] = 2] = "account_credited"; + EffectType[EffectType["account_debited"] = 3] = "account_debited"; + EffectType[EffectType["account_thresholds_updated"] = 4] = "account_thresholds_updated"; + EffectType[EffectType["account_home_domain_updated"] = 5] = "account_home_domain_updated"; + EffectType[EffectType["account_flags_updated"] = 6] = "account_flags_updated"; + EffectType[EffectType["account_inflation_destination_updated"] = 7] = "account_inflation_destination_updated"; + EffectType[EffectType["signer_created"] = 10] = "signer_created"; + EffectType[EffectType["signer_removed"] = 11] = "signer_removed"; + EffectType[EffectType["signer_updated"] = 12] = "signer_updated"; + EffectType[EffectType["trustline_created"] = 20] = "trustline_created"; + EffectType[EffectType["trustline_removed"] = 21] = "trustline_removed"; + EffectType[EffectType["trustline_updated"] = 22] = "trustline_updated"; + EffectType[EffectType["trustline_authorized"] = 23] = "trustline_authorized"; + EffectType[EffectType["trustline_deauthorized"] = 24] = "trustline_deauthorized"; + EffectType[EffectType["trustline_authorized_to_maintain_liabilities"] = 25] = "trustline_authorized_to_maintain_liabilities"; + EffectType[EffectType["trustline_flags_updated"] = 26] = "trustline_flags_updated"; + EffectType[EffectType["offer_created"] = 30] = "offer_created"; + EffectType[EffectType["offer_removed"] = 31] = "offer_removed"; + EffectType[EffectType["offer_updated"] = 32] = "offer_updated"; + EffectType[EffectType["trade"] = 33] = "trade"; + EffectType[EffectType["data_created"] = 40] = "data_created"; + EffectType[EffectType["data_removed"] = 41] = "data_removed"; + EffectType[EffectType["data_updated"] = 42] = "data_updated"; + EffectType[EffectType["sequence_bumped"] = 43] = "sequence_bumped"; + EffectType[EffectType["claimable_balance_created"] = 50] = "claimable_balance_created"; + EffectType[EffectType["claimable_balance_claimant_created"] = 51] = "claimable_balance_claimant_created"; + EffectType[EffectType["claimable_balance_claimed"] = 52] = "claimable_balance_claimed"; + EffectType[EffectType["account_sponsorship_created"] = 60] = "account_sponsorship_created"; + EffectType[EffectType["account_sponsorship_updated"] = 61] = "account_sponsorship_updated"; + EffectType[EffectType["account_sponsorship_removed"] = 62] = "account_sponsorship_removed"; + EffectType[EffectType["trustline_sponsorship_created"] = 63] = "trustline_sponsorship_created"; + EffectType[EffectType["trustline_sponsorship_updated"] = 64] = "trustline_sponsorship_updated"; + EffectType[EffectType["trustline_sponsorship_removed"] = 65] = "trustline_sponsorship_removed"; + EffectType[EffectType["data_sponsorship_created"] = 66] = "data_sponsorship_created"; + EffectType[EffectType["data_sponsorship_updated"] = 67] = "data_sponsorship_updated"; + EffectType[EffectType["data_sponsorship_removed"] = 68] = "data_sponsorship_removed"; + EffectType[EffectType["claimable_balance_sponsorship_created"] = 69] = "claimable_balance_sponsorship_created"; + EffectType[EffectType["claimable_balance_sponsorship_updated"] = 70] = "claimable_balance_sponsorship_updated"; + EffectType[EffectType["claimable_balance_sponsorship_removed"] = 71] = "claimable_balance_sponsorship_removed"; + EffectType[EffectType["signer_sponsorship_created"] = 72] = "signer_sponsorship_created"; + EffectType[EffectType["signer_sponsorship_updated"] = 73] = "signer_sponsorship_updated"; + EffectType[EffectType["signer_sponsorship_removed"] = 74] = "signer_sponsorship_removed"; + EffectType[EffectType["claimable_balance_clawed_back"] = 80] = "claimable_balance_clawed_back"; + EffectType[EffectType["liquidity_pool_deposited"] = 90] = "liquidity_pool_deposited"; + EffectType[EffectType["liquidity_pool_withdrew"] = 91] = "liquidity_pool_withdrew"; + EffectType[EffectType["liquidity_pool_trade"] = 92] = "liquidity_pool_trade"; + EffectType[EffectType["liquidity_pool_created"] = 93] = "liquidity_pool_created"; + EffectType[EffectType["liquidity_pool_removed"] = 94] = "liquidity_pool_removed"; + EffectType[EffectType["liquidity_pool_revoked"] = 95] = "liquidity_pool_revoked"; + EffectType[EffectType["contract_credited"] = 96] = "contract_credited"; + EffectType[EffectType["contract_debited"] = 97] = "contract_debited"; + return EffectType; +}({}); +;// ./src/horizon/server_api.ts + + +var ServerApi; +(function (_ServerApi) { + var EffectType = _ServerApi.EffectType = effects_EffectType; + var TradeType = function (TradeType) { + TradeType["all"] = "all"; + TradeType["liquidityPools"] = "liquidity_pool"; + TradeType["orderbook"] = "orderbook"; + return TradeType; + }({}); + _ServerApi.TradeType = TradeType; + var OperationResponseType = HorizonApi.OperationResponseType; + var OperationResponseTypeI = HorizonApi.OperationResponseTypeI; +})(ServerApi || (ServerApi = {})); +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +;// ./src/horizon/account_response.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + +var AccountResponse = function () { + function AccountResponse(response) { + var _this = this; + _classCallCheck(this, AccountResponse); + this._baseAccount = new lib.Account(response.account_id, response.sequence); + Object.entries(response).forEach(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + _this[key] = value; + }); + } + return _createClass(AccountResponse, [{ + key: "accountId", + value: function accountId() { + return this._baseAccount.accountId(); + } + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this._baseAccount.sequenceNumber(); + } + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + this._baseAccount.incrementSequenceNumber(); + this.sequence = this._baseAccount.sequenceNumber(); + } + }]); +}(); +;// ./node_modules/bignumber.js/bignumber.mjs +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + +var + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + +/* + * Create and return a BigNumber constructor. + */ +function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + P[Symbol.toStringTag] = 'BigNumber'; + + // Node.js v10.12.0+ + P[Symbol.for('nodejs.util.inspect.custom')] = P.valueOf; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; +} + + +// PRIVATE HELPER FUNCTIONS + +// These functions don't need access to variables, +// e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + +function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; +} + + +// Return a coefficient array as a string of base 10 digits. +function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); +} + + +// Compare the value of BigNumbers x and y. +function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; +} + + +/* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ +function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } +} + + +// Assumes finite n. +function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; +} + + +function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; +} + + +function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; +} + + +// EXPORT + + +var BigNumber = clone(); + +/* harmony default export */ const bignumber = (BigNumber); + +// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js +var URI = __webpack_require__(4193); +var URI_default = /*#__PURE__*/__webpack_require__.n(URI); +// EXTERNAL MODULE: ./node_modules/urijs/src/URITemplate.js +var URITemplate = __webpack_require__(9127); +var URITemplate_default = /*#__PURE__*/__webpack_require__.n(URITemplate); +// EXTERNAL MODULE: ./src/errors/index.ts + 5 modules +var errors = __webpack_require__(5976); +// EXTERNAL MODULE: ./src/http-client/index.ts + 1 modules +var http_client = __webpack_require__(9983); +;// ./src/horizon/horizon_axios_client.ts +function horizon_axios_client_typeof(o) { "@babel/helpers - typeof"; return horizon_axios_client_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, horizon_axios_client_typeof(o); } + + +var version = "13.1.0"; +var SERVER_TIME_MAP = {}; +var AxiosClient = (0,http_client/* create */.vt)({ + headers: { + "X-Client-Name": "js-stellar-sdk", + "X-Client-Version": version + } +}); +function toSeconds(ms) { + return Math.floor(ms / 1000); +} +AxiosClient.interceptors.response.use(function (response) { + var hostname = URI_default()(response.config.url).hostname(); + var serverTime = 0; + if (response.headers instanceof Headers) { + var dateHeader = response.headers.get('date'); + if (dateHeader) { + serverTime = toSeconds(Date.parse(dateHeader)); + } + } else if (horizon_axios_client_typeof(response.headers) === 'object' && 'date' in response.headers) { + var headers = response.headers; + if (typeof headers.date === 'string') { + serverTime = toSeconds(Date.parse(headers.date)); + } + } + var localTimeRecorded = toSeconds(new Date().getTime()); + if (!Number.isNaN(serverTime)) { + SERVER_TIME_MAP[hostname] = { + serverTime: serverTime, + localTimeRecorded: localTimeRecorded + }; + } + return response; +}); +/* harmony default export */ const horizon_axios_client = (AxiosClient); +function getCurrentServerTime(hostname) { + var entry = SERVER_TIME_MAP[hostname]; + if (!entry || !entry.localTimeRecorded || !entry.serverTime) { + return null; + } + var serverTime = entry.serverTime, + localTimeRecorded = entry.localTimeRecorded; + var currentTime = toSeconds(new Date().getTime()); + if (currentTime - localTimeRecorded > 60 * 5) { + return null; + } + return currentTime - localTimeRecorded + serverTime; +} +;// ./src/horizon/call_builder.ts +function call_builder_typeof(o) { "@babel/helpers - typeof"; return call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, call_builder_typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == call_builder_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(call_builder_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, call_builder_toPropertyKey(o.key), o); } } +function call_builder_createClass(e, r, t) { return r && call_builder_defineProperties(e.prototype, r), t && call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function call_builder_toPropertyKey(t) { var i = call_builder_toPrimitive(t, "string"); return "symbol" == call_builder_typeof(i) ? i : i + ""; } +function call_builder_toPrimitive(t, r) { if ("object" != call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + +var JOINABLE = ["transaction"]; +var anyGlobal = (/* unused pure expression or super */ null && (__webpack_require__.g)); +var EventSource; +if (false) { var _ref, _anyGlobal$EventSourc, _anyGlobal$window; } +var CallBuilder = function () { + function CallBuilder(serverUrl) { + var neighborRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; + call_builder_classCallCheck(this, CallBuilder); + this.url = serverUrl.clone(); + this.filter = []; + this.originalSegments = this.url.segment() || []; + this.neighborRoot = neighborRoot; + } + return call_builder_createClass(CallBuilder, [{ + key: "call", + value: function call() { + var _this = this; + this.checkFilter(); + return this._sendNormalRequest(this.url).then(function (r) { + return _this._parseResponse(r); + }); + } + }, { + key: "stream", + value: function stream() { + var _this2 = this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (EventSource === undefined) { + throw new Error("Streaming requires eventsource to be enabled. If you need this functionality, compile with USE_EVENTSOURCE=true."); + } + this.checkFilter(); + this.url.setQuery("X-Client-Name", "js-stellar-sdk"); + this.url.setQuery("X-Client-Version", version); + var es; + var timeout; + var createTimeout = function createTimeout() { + timeout = setTimeout(function () { + var _es; + (_es = es) === null || _es === void 0 || _es.close(); + es = _createEventSource(); + }, options.reconnectTimeout || 15 * 1000); + }; + var _createEventSource = function createEventSource() { + try { + es = new EventSource(_this2.url.toString()); + } catch (err) { + if (options.onerror) { + options.onerror(err); + } + } + createTimeout(); + if (!es) { + return es; + } + var closed = false; + var onClose = function onClose() { + if (closed) { + return; + } + clearTimeout(timeout); + es.close(); + _createEventSource(); + closed = true; + }; + var onMessage = function onMessage(message) { + if (message.type === "close") { + onClose(); + return; + } + var result = message.data ? _this2._parseRecord(JSON.parse(message.data)) : message; + if (result.paging_token) { + _this2.url.setQuery("cursor", result.paging_token); + } + clearTimeout(timeout); + createTimeout(); + if (typeof options.onmessage !== "undefined") { + options.onmessage(result); + } + }; + var onError = function onError(error) { + if (options.onerror) { + options.onerror(error); + } + }; + if (es.addEventListener) { + es.addEventListener("message", onMessage.bind(_this2)); + es.addEventListener("error", onError.bind(_this2)); + es.addEventListener("close", onClose.bind(_this2)); + } else { + es.onmessage = onMessage.bind(_this2); + es.onerror = onError.bind(_this2); + } + return es; + }; + _createEventSource(); + return function () { + var _es2; + clearTimeout(timeout); + (_es2 = es) === null || _es2 === void 0 || _es2.close(); + }; + } + }, { + key: "cursor", + value: function cursor(_cursor) { + this.url.setQuery("cursor", _cursor); + return this; + } + }, { + key: "limit", + value: function limit(recordsNumber) { + this.url.setQuery("limit", recordsNumber.toString()); + return this; + } + }, { + key: "order", + value: function order(direction) { + this.url.setQuery("order", direction); + return this; + } + }, { + key: "join", + value: function join(include) { + this.url.setQuery("join", include); + return this; + } + }, { + key: "forEndpoint", + value: function forEndpoint(endpoint, param) { + if (this.neighborRoot === "") { + throw new Error("Invalid usage: neighborRoot not set in constructor"); + } + this.filter.push([endpoint, param, this.neighborRoot]); + return this; + } + }, { + key: "checkFilter", + value: function checkFilter() { + if (this.filter.length >= 2) { + throw new errors/* BadRequestError */.v7("Too many filters specified", this.filter); + } + if (this.filter.length === 1) { + var newSegment = this.originalSegments.concat(this.filter[0]); + this.url.segment(newSegment); + } + } + }, { + key: "_requestFnForLink", + value: function _requestFnForLink(link) { + var _this3 = this; + return _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var opts, + uri, + template, + r, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}; + if (link.templated) { + template = URITemplate_default()(link.href); + uri = URI_default()(template.expand(opts)); + } else { + uri = URI_default()(link.href); + } + _context.next = 4; + return _this3._sendNormalRequest(uri); + case 4: + r = _context.sent; + return _context.abrupt("return", _this3._parseResponse(r)); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + } + }, { + key: "_parseRecord", + value: function _parseRecord(json) { + var _this4 = this; + if (!json._links) { + return json; + } + Object.keys(json._links).forEach(function (key) { + var n = json._links[key]; + var included = false; + if (typeof json[key] !== "undefined") { + json["".concat(key, "_attr")] = json[key]; + included = true; + } + if (included && JOINABLE.indexOf(key) >= 0) { + var record = _this4._parseRecord(json[key]); + json[key] = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", record); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + } else { + json[key] = _this4._requestFnForLink(n); + } + }); + return json; + } + }, { + key: "_sendNormalRequest", + value: function () { + var _sendNormalRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(initialUrl) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = initialUrl; + if (url.authority() === "") { + url = url.authority(this.url.authority()); + } + if (url.protocol() === "") { + url = url.protocol(this.url.protocol()); + } + return _context3.abrupt("return", AxiosClient.get(url.toString()).then(function (response) { + return response.data; + }).catch(this._handleNetworkError)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function _sendNormalRequest(_x) { + return _sendNormalRequest2.apply(this, arguments); + } + return _sendNormalRequest; + }() + }, { + key: "_parseResponse", + value: function _parseResponse(json) { + if (json._embedded && json._embedded.records) { + return this._toCollectionPage(json); + } + return this._parseRecord(json); + } + }, { + key: "_toCollectionPage", + value: function _toCollectionPage(json) { + var _this5 = this; + for (var i = 0; i < json._embedded.records.length; i += 1) { + json._embedded.records[i] = this._parseRecord(json._embedded.records[i]); + } + return { + records: json._embedded.records, + next: function () { + var _next2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + var r; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this5._sendNormalRequest(URI_default()(json._links.next.href)); + case 2: + r = _context4.sent; + return _context4.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function next() { + return _next2.apply(this, arguments); + } + return next; + }(), + prev: function () { + var _prev = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5() { + var r; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return _this5._sendNormalRequest(URI_default()(json._links.prev.href)); + case 2: + r = _context5.sent; + return _context5.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function prev() { + return _prev.apply(this, arguments); + } + return prev; + }() + }; + } + }, { + key: "_handleNetworkError", + value: (function () { + var _handleNetworkError2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(error) { + var _error$response$statu, _error$response$statu2; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + if (!(error.response && error.response.status)) { + _context6.next = 8; + break; + } + _context6.t0 = error.response.status; + _context6.next = _context6.t0 === 404 ? 4 : 5; + break; + case 4: + return _context6.abrupt("return", Promise.reject(new errors/* NotFoundError */.m_((_error$response$statu = error.response.statusText) !== null && _error$response$statu !== void 0 ? _error$response$statu : "Not Found", error.response.data))); + case 5: + return _context6.abrupt("return", Promise.reject(new errors/* NetworkError */.Dr((_error$response$statu2 = error.response.statusText) !== null && _error$response$statu2 !== void 0 ? _error$response$statu2 : "Unknown", error.response.data))); + case 6: + _context6.next = 9; + break; + case 8: + return _context6.abrupt("return", Promise.reject(new Error(error.message))); + case 9: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function _handleNetworkError(_x2) { + return _handleNetworkError2.apply(this, arguments); + } + return _handleNetworkError; + }()) + }]); +}(); +// EXTERNAL MODULE: ./src/config.ts +var config = __webpack_require__(8732); +;// ./src/horizon/account_call_builder.ts +function account_call_builder_typeof(o) { "@babel/helpers - typeof"; return account_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, account_call_builder_typeof(o); } +function account_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function account_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, account_call_builder_toPropertyKey(o.key), o); } } +function account_call_builder_createClass(e, r, t) { return r && account_call_builder_defineProperties(e.prototype, r), t && account_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function account_call_builder_toPropertyKey(t) { var i = account_call_builder_toPrimitive(t, "string"); return "symbol" == account_call_builder_typeof(i) ? i : i + ""; } +function account_call_builder_toPrimitive(t, r) { if ("object" != account_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != account_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == account_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } + +var AccountCallBuilder = function (_CallBuilder) { + function AccountCallBuilder(serverUrl) { + var _this; + account_call_builder_classCallCheck(this, AccountCallBuilder); + _this = _callSuper(this, AccountCallBuilder, [serverUrl]); + _this.url.segment("accounts"); + return _this; + } + _inherits(AccountCallBuilder, _CallBuilder); + return account_call_builder_createClass(AccountCallBuilder, [{ + key: "accountId", + value: function accountId(id) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([id]); + return builder; + } + }, { + key: "forSigner", + value: function forSigner(id) { + this.url.setQuery("signer", id); + return this; + } + }, { + key: "forAsset", + value: function forAsset(asset) { + this.url.setQuery("asset", "".concat(asset)); + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(id) { + this.url.setQuery("liquidity_pool", id); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/assets_call_builder.ts +function assets_call_builder_typeof(o) { "@babel/helpers - typeof"; return assets_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, assets_call_builder_typeof(o); } +function assets_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function assets_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, assets_call_builder_toPropertyKey(o.key), o); } } +function assets_call_builder_createClass(e, r, t) { return r && assets_call_builder_defineProperties(e.prototype, r), t && assets_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function assets_call_builder_toPropertyKey(t) { var i = assets_call_builder_toPrimitive(t, "string"); return "symbol" == assets_call_builder_typeof(i) ? i : i + ""; } +function assets_call_builder_toPrimitive(t, r) { if ("object" != assets_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != assets_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function assets_call_builder_callSuper(t, o, e) { return o = assets_call_builder_getPrototypeOf(o), assets_call_builder_possibleConstructorReturn(t, assets_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], assets_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function assets_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == assets_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return assets_call_builder_assertThisInitialized(t); } +function assets_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function assets_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (assets_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function assets_call_builder_getPrototypeOf(t) { return assets_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, assets_call_builder_getPrototypeOf(t); } +function assets_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && assets_call_builder_setPrototypeOf(t, e); } +function assets_call_builder_setPrototypeOf(t, e) { return assets_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, assets_call_builder_setPrototypeOf(t, e); } + +var AssetsCallBuilder = function (_CallBuilder) { + function AssetsCallBuilder(serverUrl) { + var _this; + assets_call_builder_classCallCheck(this, AssetsCallBuilder); + _this = assets_call_builder_callSuper(this, AssetsCallBuilder, [serverUrl]); + _this.url.segment("assets"); + return _this; + } + assets_call_builder_inherits(AssetsCallBuilder, _CallBuilder); + return assets_call_builder_createClass(AssetsCallBuilder, [{ + key: "forCode", + value: function forCode(value) { + this.url.setQuery("asset_code", value); + return this; + } + }, { + key: "forIssuer", + value: function forIssuer(value) { + this.url.setQuery("asset_issuer", value); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/claimable_balances_call_builder.ts +function claimable_balances_call_builder_typeof(o) { "@babel/helpers - typeof"; return claimable_balances_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, claimable_balances_call_builder_typeof(o); } +function claimable_balances_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function claimable_balances_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, claimable_balances_call_builder_toPropertyKey(o.key), o); } } +function claimable_balances_call_builder_createClass(e, r, t) { return r && claimable_balances_call_builder_defineProperties(e.prototype, r), t && claimable_balances_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function claimable_balances_call_builder_toPropertyKey(t) { var i = claimable_balances_call_builder_toPrimitive(t, "string"); return "symbol" == claimable_balances_call_builder_typeof(i) ? i : i + ""; } +function claimable_balances_call_builder_toPrimitive(t, r) { if ("object" != claimable_balances_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != claimable_balances_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function claimable_balances_call_builder_callSuper(t, o, e) { return o = claimable_balances_call_builder_getPrototypeOf(o), claimable_balances_call_builder_possibleConstructorReturn(t, claimable_balances_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], claimable_balances_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function claimable_balances_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == claimable_balances_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return claimable_balances_call_builder_assertThisInitialized(t); } +function claimable_balances_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function claimable_balances_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (claimable_balances_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function claimable_balances_call_builder_getPrototypeOf(t) { return claimable_balances_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, claimable_balances_call_builder_getPrototypeOf(t); } +function claimable_balances_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && claimable_balances_call_builder_setPrototypeOf(t, e); } +function claimable_balances_call_builder_setPrototypeOf(t, e) { return claimable_balances_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, claimable_balances_call_builder_setPrototypeOf(t, e); } + +var ClaimableBalanceCallBuilder = function (_CallBuilder) { + function ClaimableBalanceCallBuilder(serverUrl) { + var _this; + claimable_balances_call_builder_classCallCheck(this, ClaimableBalanceCallBuilder); + _this = claimable_balances_call_builder_callSuper(this, ClaimableBalanceCallBuilder, [serverUrl]); + _this.url.segment("claimable_balances"); + return _this; + } + claimable_balances_call_builder_inherits(ClaimableBalanceCallBuilder, _CallBuilder); + return claimable_balances_call_builder_createClass(ClaimableBalanceCallBuilder, [{ + key: "claimableBalance", + value: function claimableBalance(claimableBalanceId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([claimableBalanceId]); + return builder; + } + }, { + key: "sponsor", + value: function sponsor(_sponsor) { + this.url.setQuery("sponsor", _sponsor); + return this; + } + }, { + key: "claimant", + value: function claimant(_claimant) { + this.url.setQuery("claimant", _claimant); + return this; + } + }, { + key: "asset", + value: function asset(_asset) { + this.url.setQuery("asset", _asset.toString()); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/effect_call_builder.ts +function effect_call_builder_typeof(o) { "@babel/helpers - typeof"; return effect_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, effect_call_builder_typeof(o); } +function effect_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function effect_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, effect_call_builder_toPropertyKey(o.key), o); } } +function effect_call_builder_createClass(e, r, t) { return r && effect_call_builder_defineProperties(e.prototype, r), t && effect_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function effect_call_builder_toPropertyKey(t) { var i = effect_call_builder_toPrimitive(t, "string"); return "symbol" == effect_call_builder_typeof(i) ? i : i + ""; } +function effect_call_builder_toPrimitive(t, r) { if ("object" != effect_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != effect_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function effect_call_builder_callSuper(t, o, e) { return o = effect_call_builder_getPrototypeOf(o), effect_call_builder_possibleConstructorReturn(t, effect_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], effect_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function effect_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == effect_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return effect_call_builder_assertThisInitialized(t); } +function effect_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function effect_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (effect_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function effect_call_builder_getPrototypeOf(t) { return effect_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, effect_call_builder_getPrototypeOf(t); } +function effect_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && effect_call_builder_setPrototypeOf(t, e); } +function effect_call_builder_setPrototypeOf(t, e) { return effect_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, effect_call_builder_setPrototypeOf(t, e); } + +var EffectCallBuilder = function (_CallBuilder) { + function EffectCallBuilder(serverUrl) { + var _this; + effect_call_builder_classCallCheck(this, EffectCallBuilder); + _this = effect_call_builder_callSuper(this, EffectCallBuilder, [serverUrl, "effects"]); + _this.url.segment("effects"); + return _this; + } + effect_call_builder_inherits(EffectCallBuilder, _CallBuilder); + return effect_call_builder_createClass(EffectCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forOperation", + value: function forOperation(operationId) { + return this.forEndpoint("operations", operationId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }]); +}(CallBuilder); +;// ./src/horizon/friendbot_builder.ts +function friendbot_builder_typeof(o) { "@babel/helpers - typeof"; return friendbot_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, friendbot_builder_typeof(o); } +function friendbot_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, friendbot_builder_toPropertyKey(o.key), o); } } +function friendbot_builder_createClass(e, r, t) { return r && friendbot_builder_defineProperties(e.prototype, r), t && friendbot_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function friendbot_builder_toPropertyKey(t) { var i = friendbot_builder_toPrimitive(t, "string"); return "symbol" == friendbot_builder_typeof(i) ? i : i + ""; } +function friendbot_builder_toPrimitive(t, r) { if ("object" != friendbot_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != friendbot_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function friendbot_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function friendbot_builder_callSuper(t, o, e) { return o = friendbot_builder_getPrototypeOf(o), friendbot_builder_possibleConstructorReturn(t, friendbot_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], friendbot_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function friendbot_builder_possibleConstructorReturn(t, e) { if (e && ("object" == friendbot_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return friendbot_builder_assertThisInitialized(t); } +function friendbot_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function friendbot_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (friendbot_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function friendbot_builder_getPrototypeOf(t) { return friendbot_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, friendbot_builder_getPrototypeOf(t); } +function friendbot_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && friendbot_builder_setPrototypeOf(t, e); } +function friendbot_builder_setPrototypeOf(t, e) { return friendbot_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, friendbot_builder_setPrototypeOf(t, e); } + +var FriendbotBuilder = function (_CallBuilder) { + function FriendbotBuilder(serverUrl, address) { + var _this; + friendbot_builder_classCallCheck(this, FriendbotBuilder); + _this = friendbot_builder_callSuper(this, FriendbotBuilder, [serverUrl]); + _this.url.segment("friendbot"); + _this.url.setQuery("addr", address); + return _this; + } + friendbot_builder_inherits(FriendbotBuilder, _CallBuilder); + return friendbot_builder_createClass(FriendbotBuilder); +}(CallBuilder); +;// ./src/horizon/ledger_call_builder.ts +function ledger_call_builder_typeof(o) { "@babel/helpers - typeof"; return ledger_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, ledger_call_builder_typeof(o); } +function ledger_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function ledger_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, ledger_call_builder_toPropertyKey(o.key), o); } } +function ledger_call_builder_createClass(e, r, t) { return r && ledger_call_builder_defineProperties(e.prototype, r), t && ledger_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function ledger_call_builder_toPropertyKey(t) { var i = ledger_call_builder_toPrimitive(t, "string"); return "symbol" == ledger_call_builder_typeof(i) ? i : i + ""; } +function ledger_call_builder_toPrimitive(t, r) { if ("object" != ledger_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != ledger_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function ledger_call_builder_callSuper(t, o, e) { return o = ledger_call_builder_getPrototypeOf(o), ledger_call_builder_possibleConstructorReturn(t, ledger_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], ledger_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function ledger_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == ledger_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return ledger_call_builder_assertThisInitialized(t); } +function ledger_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function ledger_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (ledger_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function ledger_call_builder_getPrototypeOf(t) { return ledger_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, ledger_call_builder_getPrototypeOf(t); } +function ledger_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && ledger_call_builder_setPrototypeOf(t, e); } +function ledger_call_builder_setPrototypeOf(t, e) { return ledger_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, ledger_call_builder_setPrototypeOf(t, e); } + +var LedgerCallBuilder = function (_CallBuilder) { + function LedgerCallBuilder(serverUrl) { + var _this; + ledger_call_builder_classCallCheck(this, LedgerCallBuilder); + _this = ledger_call_builder_callSuper(this, LedgerCallBuilder, [serverUrl]); + _this.url.segment("ledgers"); + return _this; + } + ledger_call_builder_inherits(LedgerCallBuilder, _CallBuilder); + return ledger_call_builder_createClass(LedgerCallBuilder, [{ + key: "ledger", + value: function ledger(sequence) { + this.filter.push(["ledgers", sequence.toString()]); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/liquidity_pool_call_builder.ts +function liquidity_pool_call_builder_typeof(o) { "@babel/helpers - typeof"; return liquidity_pool_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, liquidity_pool_call_builder_typeof(o); } +function liquidity_pool_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function liquidity_pool_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, liquidity_pool_call_builder_toPropertyKey(o.key), o); } } +function liquidity_pool_call_builder_createClass(e, r, t) { return r && liquidity_pool_call_builder_defineProperties(e.prototype, r), t && liquidity_pool_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function liquidity_pool_call_builder_toPropertyKey(t) { var i = liquidity_pool_call_builder_toPrimitive(t, "string"); return "symbol" == liquidity_pool_call_builder_typeof(i) ? i : i + ""; } +function liquidity_pool_call_builder_toPrimitive(t, r) { if ("object" != liquidity_pool_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != liquidity_pool_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function liquidity_pool_call_builder_callSuper(t, o, e) { return o = liquidity_pool_call_builder_getPrototypeOf(o), liquidity_pool_call_builder_possibleConstructorReturn(t, liquidity_pool_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], liquidity_pool_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function liquidity_pool_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == liquidity_pool_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return liquidity_pool_call_builder_assertThisInitialized(t); } +function liquidity_pool_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function liquidity_pool_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (liquidity_pool_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function liquidity_pool_call_builder_getPrototypeOf(t) { return liquidity_pool_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, liquidity_pool_call_builder_getPrototypeOf(t); } +function liquidity_pool_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && liquidity_pool_call_builder_setPrototypeOf(t, e); } +function liquidity_pool_call_builder_setPrototypeOf(t, e) { return liquidity_pool_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, liquidity_pool_call_builder_setPrototypeOf(t, e); } + +var LiquidityPoolCallBuilder = function (_CallBuilder) { + function LiquidityPoolCallBuilder(serverUrl) { + var _this; + liquidity_pool_call_builder_classCallCheck(this, LiquidityPoolCallBuilder); + _this = liquidity_pool_call_builder_callSuper(this, LiquidityPoolCallBuilder, [serverUrl]); + _this.url.segment("liquidity_pools"); + return _this; + } + liquidity_pool_call_builder_inherits(LiquidityPoolCallBuilder, _CallBuilder); + return liquidity_pool_call_builder_createClass(LiquidityPoolCallBuilder, [{ + key: "forAssets", + value: function forAssets() { + for (var _len = arguments.length, assets = new Array(_len), _key = 0; _key < _len; _key++) { + assets[_key] = arguments[_key]; + } + var assetList = assets.map(function (asset) { + return asset.toString(); + }).join(","); + this.url.setQuery("reserves", assetList); + return this; + } + }, { + key: "forAccount", + value: function forAccount(id) { + this.url.setQuery("account", id); + return this; + } + }, { + key: "liquidityPoolId", + value: function liquidityPoolId(id) { + if (!id.match(/[a-fA-F0-9]{64}/)) { + throw new TypeError("".concat(id, " does not look like a liquidity pool ID")); + } + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([id.toLowerCase()]); + return builder; + } + }]); +}(CallBuilder); +;// ./src/horizon/offer_call_builder.ts +function offer_call_builder_typeof(o) { "@babel/helpers - typeof"; return offer_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, offer_call_builder_typeof(o); } +function offer_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function offer_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, offer_call_builder_toPropertyKey(o.key), o); } } +function offer_call_builder_createClass(e, r, t) { return r && offer_call_builder_defineProperties(e.prototype, r), t && offer_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function offer_call_builder_toPropertyKey(t) { var i = offer_call_builder_toPrimitive(t, "string"); return "symbol" == offer_call_builder_typeof(i) ? i : i + ""; } +function offer_call_builder_toPrimitive(t, r) { if ("object" != offer_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != offer_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function offer_call_builder_callSuper(t, o, e) { return o = offer_call_builder_getPrototypeOf(o), offer_call_builder_possibleConstructorReturn(t, offer_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], offer_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function offer_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == offer_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return offer_call_builder_assertThisInitialized(t); } +function offer_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function offer_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (offer_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function offer_call_builder_getPrototypeOf(t) { return offer_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, offer_call_builder_getPrototypeOf(t); } +function offer_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && offer_call_builder_setPrototypeOf(t, e); } +function offer_call_builder_setPrototypeOf(t, e) { return offer_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, offer_call_builder_setPrototypeOf(t, e); } + +var OfferCallBuilder = function (_CallBuilder) { + function OfferCallBuilder(serverUrl) { + var _this; + offer_call_builder_classCallCheck(this, OfferCallBuilder); + _this = offer_call_builder_callSuper(this, OfferCallBuilder, [serverUrl, "offers"]); + _this.url.segment("offers"); + return _this; + } + offer_call_builder_inherits(OfferCallBuilder, _CallBuilder); + return offer_call_builder_createClass(OfferCallBuilder, [{ + key: "offer", + value: function offer(offerId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([offerId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(id) { + return this.forEndpoint("accounts", id); + } + }, { + key: "buying", + value: function buying(asset) { + if (!asset.isNative()) { + this.url.setQuery("buying_asset_type", asset.getAssetType()); + this.url.setQuery("buying_asset_code", asset.getCode()); + this.url.setQuery("buying_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("buying_asset_type", "native"); + } + return this; + } + }, { + key: "selling", + value: function selling(asset) { + if (!asset.isNative()) { + this.url.setQuery("selling_asset_type", asset.getAssetType()); + this.url.setQuery("selling_asset_code", asset.getCode()); + this.url.setQuery("selling_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("selling_asset_type", "native"); + } + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "seller", + value: function seller(_seller) { + this.url.setQuery("seller", _seller); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/operation_call_builder.ts +function operation_call_builder_typeof(o) { "@babel/helpers - typeof"; return operation_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, operation_call_builder_typeof(o); } +function operation_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function operation_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, operation_call_builder_toPropertyKey(o.key), o); } } +function operation_call_builder_createClass(e, r, t) { return r && operation_call_builder_defineProperties(e.prototype, r), t && operation_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function operation_call_builder_toPropertyKey(t) { var i = operation_call_builder_toPrimitive(t, "string"); return "symbol" == operation_call_builder_typeof(i) ? i : i + ""; } +function operation_call_builder_toPrimitive(t, r) { if ("object" != operation_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != operation_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function operation_call_builder_callSuper(t, o, e) { return o = operation_call_builder_getPrototypeOf(o), operation_call_builder_possibleConstructorReturn(t, operation_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], operation_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function operation_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == operation_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return operation_call_builder_assertThisInitialized(t); } +function operation_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function operation_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (operation_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function operation_call_builder_getPrototypeOf(t) { return operation_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, operation_call_builder_getPrototypeOf(t); } +function operation_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && operation_call_builder_setPrototypeOf(t, e); } +function operation_call_builder_setPrototypeOf(t, e) { return operation_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, operation_call_builder_setPrototypeOf(t, e); } + +var OperationCallBuilder = function (_CallBuilder) { + function OperationCallBuilder(serverUrl) { + var _this; + operation_call_builder_classCallCheck(this, OperationCallBuilder); + _this = operation_call_builder_callSuper(this, OperationCallBuilder, [serverUrl, "operations"]); + _this.url.segment("operations"); + return _this; + } + operation_call_builder_inherits(OperationCallBuilder, _CallBuilder); + return operation_call_builder_createClass(OperationCallBuilder, [{ + key: "operation", + value: function operation(operationId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([operationId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/orderbook_call_builder.ts +function orderbook_call_builder_typeof(o) { "@babel/helpers - typeof"; return orderbook_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, orderbook_call_builder_typeof(o); } +function orderbook_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, orderbook_call_builder_toPropertyKey(o.key), o); } } +function orderbook_call_builder_createClass(e, r, t) { return r && orderbook_call_builder_defineProperties(e.prototype, r), t && orderbook_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function orderbook_call_builder_toPropertyKey(t) { var i = orderbook_call_builder_toPrimitive(t, "string"); return "symbol" == orderbook_call_builder_typeof(i) ? i : i + ""; } +function orderbook_call_builder_toPrimitive(t, r) { if ("object" != orderbook_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != orderbook_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function orderbook_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function orderbook_call_builder_callSuper(t, o, e) { return o = orderbook_call_builder_getPrototypeOf(o), orderbook_call_builder_possibleConstructorReturn(t, orderbook_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], orderbook_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function orderbook_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == orderbook_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return orderbook_call_builder_assertThisInitialized(t); } +function orderbook_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function orderbook_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (orderbook_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function orderbook_call_builder_getPrototypeOf(t) { return orderbook_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, orderbook_call_builder_getPrototypeOf(t); } +function orderbook_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && orderbook_call_builder_setPrototypeOf(t, e); } +function orderbook_call_builder_setPrototypeOf(t, e) { return orderbook_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, orderbook_call_builder_setPrototypeOf(t, e); } + +var OrderbookCallBuilder = function (_CallBuilder) { + function OrderbookCallBuilder(serverUrl, selling, buying) { + var _this; + orderbook_call_builder_classCallCheck(this, OrderbookCallBuilder); + _this = orderbook_call_builder_callSuper(this, OrderbookCallBuilder, [serverUrl]); + _this.url.segment("order_book"); + if (!selling.isNative()) { + _this.url.setQuery("selling_asset_type", selling.getAssetType()); + _this.url.setQuery("selling_asset_code", selling.getCode()); + _this.url.setQuery("selling_asset_issuer", selling.getIssuer()); + } else { + _this.url.setQuery("selling_asset_type", "native"); + } + if (!buying.isNative()) { + _this.url.setQuery("buying_asset_type", buying.getAssetType()); + _this.url.setQuery("buying_asset_code", buying.getCode()); + _this.url.setQuery("buying_asset_issuer", buying.getIssuer()); + } else { + _this.url.setQuery("buying_asset_type", "native"); + } + return _this; + } + orderbook_call_builder_inherits(OrderbookCallBuilder, _CallBuilder); + return orderbook_call_builder_createClass(OrderbookCallBuilder); +}(CallBuilder); +;// ./src/horizon/payment_call_builder.ts +function payment_call_builder_typeof(o) { "@babel/helpers - typeof"; return payment_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, payment_call_builder_typeof(o); } +function payment_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function payment_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, payment_call_builder_toPropertyKey(o.key), o); } } +function payment_call_builder_createClass(e, r, t) { return r && payment_call_builder_defineProperties(e.prototype, r), t && payment_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function payment_call_builder_toPropertyKey(t) { var i = payment_call_builder_toPrimitive(t, "string"); return "symbol" == payment_call_builder_typeof(i) ? i : i + ""; } +function payment_call_builder_toPrimitive(t, r) { if ("object" != payment_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != payment_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function payment_call_builder_callSuper(t, o, e) { return o = payment_call_builder_getPrototypeOf(o), payment_call_builder_possibleConstructorReturn(t, payment_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], payment_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function payment_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == payment_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return payment_call_builder_assertThisInitialized(t); } +function payment_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function payment_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (payment_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function payment_call_builder_getPrototypeOf(t) { return payment_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, payment_call_builder_getPrototypeOf(t); } +function payment_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && payment_call_builder_setPrototypeOf(t, e); } +function payment_call_builder_setPrototypeOf(t, e) { return payment_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, payment_call_builder_setPrototypeOf(t, e); } + +var PaymentCallBuilder = function (_CallBuilder) { + function PaymentCallBuilder(serverUrl) { + var _this; + payment_call_builder_classCallCheck(this, PaymentCallBuilder); + _this = payment_call_builder_callSuper(this, PaymentCallBuilder, [serverUrl, "payments"]); + _this.url.segment("payments"); + return _this; + } + payment_call_builder_inherits(PaymentCallBuilder, _CallBuilder); + return payment_call_builder_createClass(PaymentCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }]); +}(CallBuilder); +;// ./src/horizon/strict_receive_path_call_builder.ts +function strict_receive_path_call_builder_typeof(o) { "@babel/helpers - typeof"; return strict_receive_path_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, strict_receive_path_call_builder_typeof(o); } +function strict_receive_path_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, strict_receive_path_call_builder_toPropertyKey(o.key), o); } } +function strict_receive_path_call_builder_createClass(e, r, t) { return r && strict_receive_path_call_builder_defineProperties(e.prototype, r), t && strict_receive_path_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function strict_receive_path_call_builder_toPropertyKey(t) { var i = strict_receive_path_call_builder_toPrimitive(t, "string"); return "symbol" == strict_receive_path_call_builder_typeof(i) ? i : i + ""; } +function strict_receive_path_call_builder_toPrimitive(t, r) { if ("object" != strict_receive_path_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != strict_receive_path_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function strict_receive_path_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function strict_receive_path_call_builder_callSuper(t, o, e) { return o = strict_receive_path_call_builder_getPrototypeOf(o), strict_receive_path_call_builder_possibleConstructorReturn(t, strict_receive_path_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], strict_receive_path_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function strict_receive_path_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == strict_receive_path_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return strict_receive_path_call_builder_assertThisInitialized(t); } +function strict_receive_path_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function strict_receive_path_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (strict_receive_path_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function strict_receive_path_call_builder_getPrototypeOf(t) { return strict_receive_path_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, strict_receive_path_call_builder_getPrototypeOf(t); } +function strict_receive_path_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && strict_receive_path_call_builder_setPrototypeOf(t, e); } +function strict_receive_path_call_builder_setPrototypeOf(t, e) { return strict_receive_path_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, strict_receive_path_call_builder_setPrototypeOf(t, e); } + +var StrictReceivePathCallBuilder = function (_CallBuilder) { + function StrictReceivePathCallBuilder(serverUrl, source, destinationAsset, destinationAmount) { + var _this; + strict_receive_path_call_builder_classCallCheck(this, StrictReceivePathCallBuilder); + _this = strict_receive_path_call_builder_callSuper(this, StrictReceivePathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-receive"); + if (typeof source === "string") { + _this.url.setQuery("source_account", source); + } else { + var assets = source.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("source_assets", assets); + } + _this.url.setQuery("destination_amount", destinationAmount); + if (!destinationAsset.isNative()) { + _this.url.setQuery("destination_asset_type", destinationAsset.getAssetType()); + _this.url.setQuery("destination_asset_code", destinationAsset.getCode()); + _this.url.setQuery("destination_asset_issuer", destinationAsset.getIssuer()); + } else { + _this.url.setQuery("destination_asset_type", "native"); + } + return _this; + } + strict_receive_path_call_builder_inherits(StrictReceivePathCallBuilder, _CallBuilder); + return strict_receive_path_call_builder_createClass(StrictReceivePathCallBuilder); +}(CallBuilder); +;// ./src/horizon/strict_send_path_call_builder.ts +function strict_send_path_call_builder_typeof(o) { "@babel/helpers - typeof"; return strict_send_path_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, strict_send_path_call_builder_typeof(o); } +function strict_send_path_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, strict_send_path_call_builder_toPropertyKey(o.key), o); } } +function strict_send_path_call_builder_createClass(e, r, t) { return r && strict_send_path_call_builder_defineProperties(e.prototype, r), t && strict_send_path_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function strict_send_path_call_builder_toPropertyKey(t) { var i = strict_send_path_call_builder_toPrimitive(t, "string"); return "symbol" == strict_send_path_call_builder_typeof(i) ? i : i + ""; } +function strict_send_path_call_builder_toPrimitive(t, r) { if ("object" != strict_send_path_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != strict_send_path_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function strict_send_path_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function strict_send_path_call_builder_callSuper(t, o, e) { return o = strict_send_path_call_builder_getPrototypeOf(o), strict_send_path_call_builder_possibleConstructorReturn(t, strict_send_path_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], strict_send_path_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function strict_send_path_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == strict_send_path_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return strict_send_path_call_builder_assertThisInitialized(t); } +function strict_send_path_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function strict_send_path_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (strict_send_path_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function strict_send_path_call_builder_getPrototypeOf(t) { return strict_send_path_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, strict_send_path_call_builder_getPrototypeOf(t); } +function strict_send_path_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && strict_send_path_call_builder_setPrototypeOf(t, e); } +function strict_send_path_call_builder_setPrototypeOf(t, e) { return strict_send_path_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, strict_send_path_call_builder_setPrototypeOf(t, e); } + +var StrictSendPathCallBuilder = function (_CallBuilder) { + function StrictSendPathCallBuilder(serverUrl, sourceAsset, sourceAmount, destination) { + var _this; + strict_send_path_call_builder_classCallCheck(this, StrictSendPathCallBuilder); + _this = strict_send_path_call_builder_callSuper(this, StrictSendPathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-send"); + if (sourceAsset.isNative()) { + _this.url.setQuery("source_asset_type", "native"); + } else { + _this.url.setQuery("source_asset_type", sourceAsset.getAssetType()); + _this.url.setQuery("source_asset_code", sourceAsset.getCode()); + _this.url.setQuery("source_asset_issuer", sourceAsset.getIssuer()); + } + _this.url.setQuery("source_amount", sourceAmount); + if (typeof destination === "string") { + _this.url.setQuery("destination_account", destination); + } else { + var assets = destination.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("destination_assets", assets); + } + return _this; + } + strict_send_path_call_builder_inherits(StrictSendPathCallBuilder, _CallBuilder); + return strict_send_path_call_builder_createClass(StrictSendPathCallBuilder); +}(CallBuilder); +;// ./src/horizon/trade_aggregation_call_builder.ts +function trade_aggregation_call_builder_typeof(o) { "@babel/helpers - typeof"; return trade_aggregation_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, trade_aggregation_call_builder_typeof(o); } +function trade_aggregation_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function trade_aggregation_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, trade_aggregation_call_builder_toPropertyKey(o.key), o); } } +function trade_aggregation_call_builder_createClass(e, r, t) { return r && trade_aggregation_call_builder_defineProperties(e.prototype, r), t && trade_aggregation_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function trade_aggregation_call_builder_toPropertyKey(t) { var i = trade_aggregation_call_builder_toPrimitive(t, "string"); return "symbol" == trade_aggregation_call_builder_typeof(i) ? i : i + ""; } +function trade_aggregation_call_builder_toPrimitive(t, r) { if ("object" != trade_aggregation_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != trade_aggregation_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function trade_aggregation_call_builder_callSuper(t, o, e) { return o = trade_aggregation_call_builder_getPrototypeOf(o), trade_aggregation_call_builder_possibleConstructorReturn(t, trade_aggregation_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], trade_aggregation_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function trade_aggregation_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == trade_aggregation_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return trade_aggregation_call_builder_assertThisInitialized(t); } +function trade_aggregation_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function trade_aggregation_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (trade_aggregation_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function trade_aggregation_call_builder_getPrototypeOf(t) { return trade_aggregation_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, trade_aggregation_call_builder_getPrototypeOf(t); } +function trade_aggregation_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && trade_aggregation_call_builder_setPrototypeOf(t, e); } +function trade_aggregation_call_builder_setPrototypeOf(t, e) { return trade_aggregation_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, trade_aggregation_call_builder_setPrototypeOf(t, e); } + + +var allowedResolutions = [60000, 300000, 900000, 3600000, 86400000, 604800000]; +var TradeAggregationCallBuilder = function (_CallBuilder) { + function TradeAggregationCallBuilder(serverUrl, base, counter, start_time, end_time, resolution, offset) { + var _this; + trade_aggregation_call_builder_classCallCheck(this, TradeAggregationCallBuilder); + _this = trade_aggregation_call_builder_callSuper(this, TradeAggregationCallBuilder, [serverUrl]); + _this.url.segment("trade_aggregations"); + if (!base.isNative()) { + _this.url.setQuery("base_asset_type", base.getAssetType()); + _this.url.setQuery("base_asset_code", base.getCode()); + _this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + _this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + _this.url.setQuery("counter_asset_type", counter.getAssetType()); + _this.url.setQuery("counter_asset_code", counter.getCode()); + _this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + _this.url.setQuery("counter_asset_type", "native"); + } + if (typeof start_time !== "number" || typeof end_time !== "number") { + throw new errors/* BadRequestError */.v7("Invalid time bounds", [start_time, end_time]); + } else { + _this.url.setQuery("start_time", start_time.toString()); + _this.url.setQuery("end_time", end_time.toString()); + } + if (!_this.isValidResolution(resolution)) { + throw new errors/* BadRequestError */.v7("Invalid resolution", resolution); + } else { + _this.url.setQuery("resolution", resolution.toString()); + } + if (!_this.isValidOffset(offset, resolution)) { + throw new errors/* BadRequestError */.v7("Invalid offset", offset); + } else { + _this.url.setQuery("offset", offset.toString()); + } + return _this; + } + trade_aggregation_call_builder_inherits(TradeAggregationCallBuilder, _CallBuilder); + return trade_aggregation_call_builder_createClass(TradeAggregationCallBuilder, [{ + key: "isValidResolution", + value: function isValidResolution(resolution) { + return allowedResolutions.some(function (allowed) { + return allowed === resolution; + }); + } + }, { + key: "isValidOffset", + value: function isValidOffset(offset, resolution) { + var hour = 3600000; + return !(offset > resolution || offset >= 24 * hour || offset % hour !== 0); + } + }]); +}(CallBuilder); +;// ./src/horizon/trades_call_builder.ts +function trades_call_builder_typeof(o) { "@babel/helpers - typeof"; return trades_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, trades_call_builder_typeof(o); } +function trades_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function trades_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, trades_call_builder_toPropertyKey(o.key), o); } } +function trades_call_builder_createClass(e, r, t) { return r && trades_call_builder_defineProperties(e.prototype, r), t && trades_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function trades_call_builder_toPropertyKey(t) { var i = trades_call_builder_toPrimitive(t, "string"); return "symbol" == trades_call_builder_typeof(i) ? i : i + ""; } +function trades_call_builder_toPrimitive(t, r) { if ("object" != trades_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != trades_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function trades_call_builder_callSuper(t, o, e) { return o = trades_call_builder_getPrototypeOf(o), trades_call_builder_possibleConstructorReturn(t, trades_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], trades_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function trades_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == trades_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return trades_call_builder_assertThisInitialized(t); } +function trades_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function trades_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (trades_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function trades_call_builder_getPrototypeOf(t) { return trades_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, trades_call_builder_getPrototypeOf(t); } +function trades_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && trades_call_builder_setPrototypeOf(t, e); } +function trades_call_builder_setPrototypeOf(t, e) { return trades_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, trades_call_builder_setPrototypeOf(t, e); } + +var TradesCallBuilder = function (_CallBuilder) { + function TradesCallBuilder(serverUrl) { + var _this; + trades_call_builder_classCallCheck(this, TradesCallBuilder); + _this = trades_call_builder_callSuper(this, TradesCallBuilder, [serverUrl, "trades"]); + _this.url.segment("trades"); + return _this; + } + trades_call_builder_inherits(TradesCallBuilder, _CallBuilder); + return trades_call_builder_createClass(TradesCallBuilder, [{ + key: "forAssetPair", + value: function forAssetPair(base, counter) { + if (!base.isNative()) { + this.url.setQuery("base_asset_type", base.getAssetType()); + this.url.setQuery("base_asset_code", base.getCode()); + this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + this.url.setQuery("counter_asset_type", counter.getAssetType()); + this.url.setQuery("counter_asset_code", counter.getCode()); + this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + this.url.setQuery("counter_asset_type", "native"); + } + return this; + } + }, { + key: "forOffer", + value: function forOffer(offerId) { + this.url.setQuery("offer_id", offerId); + return this; + } + }, { + key: "forType", + value: function forType(tradeType) { + this.url.setQuery("trade_type", tradeType); + return this; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(liquidityPoolId) { + return this.forEndpoint("liquidity_pools", liquidityPoolId); + } + }]); +}(CallBuilder); +;// ./src/horizon/transaction_call_builder.ts +function transaction_call_builder_typeof(o) { "@babel/helpers - typeof"; return transaction_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, transaction_call_builder_typeof(o); } +function transaction_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function transaction_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, transaction_call_builder_toPropertyKey(o.key), o); } } +function transaction_call_builder_createClass(e, r, t) { return r && transaction_call_builder_defineProperties(e.prototype, r), t && transaction_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function transaction_call_builder_toPropertyKey(t) { var i = transaction_call_builder_toPrimitive(t, "string"); return "symbol" == transaction_call_builder_typeof(i) ? i : i + ""; } +function transaction_call_builder_toPrimitive(t, r) { if ("object" != transaction_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != transaction_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function transaction_call_builder_callSuper(t, o, e) { return o = transaction_call_builder_getPrototypeOf(o), transaction_call_builder_possibleConstructorReturn(t, transaction_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], transaction_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function transaction_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == transaction_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return transaction_call_builder_assertThisInitialized(t); } +function transaction_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function transaction_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (transaction_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function transaction_call_builder_getPrototypeOf(t) { return transaction_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, transaction_call_builder_getPrototypeOf(t); } +function transaction_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && transaction_call_builder_setPrototypeOf(t, e); } +function transaction_call_builder_setPrototypeOf(t, e) { return transaction_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, transaction_call_builder_setPrototypeOf(t, e); } + +var TransactionCallBuilder = function (_CallBuilder) { + function TransactionCallBuilder(serverUrl) { + var _this; + transaction_call_builder_classCallCheck(this, TransactionCallBuilder); + _this = transaction_call_builder_callSuper(this, TransactionCallBuilder, [serverUrl, "transactions"]); + _this.url.segment("transactions"); + return _this; + } + transaction_call_builder_inherits(TransactionCallBuilder, _CallBuilder); + return transaction_call_builder_createClass(TransactionCallBuilder, [{ + key: "transaction", + value: function transaction(transactionId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([transactionId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/server.ts +function server_typeof(o) { "@babel/helpers - typeof"; return server_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, server_typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = server_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function server_regeneratorRuntime() { "use strict"; server_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == server_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(server_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function server_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function server_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function server_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function server_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, server_toPropertyKey(o.key), o); } } +function server_createClass(e, r, t) { return r && server_defineProperties(e.prototype, r), t && server_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function server_toPropertyKey(t) { var i = server_toPrimitive(t, "string"); return "symbol" == server_typeof(i) ? i : i + ""; } +function server_toPrimitive(t, r) { if ("object" != server_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != server_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + + + + + + + + + + + + + + + + + + + +var SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000; +var STROOPS_IN_LUMEN = 10000000; +var ACCOUNT_REQUIRES_MEMO = "MQ=="; +function getAmountInLumens(amt) { + return new bignumber(amt).div(STROOPS_IN_LUMEN).toString(); +} +var HorizonServer = function () { + function HorizonServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + server_classCallCheck(this, HorizonServer); + this.serverURL = URI_default()(serverURL); + var allowHttp = typeof opts.allowHttp === "undefined" ? config/* Config */.T.isAllowHttp() : opts.allowHttp; + var customHeaders = {}; + if (opts.appName) { + customHeaders["X-App-Name"] = opts.appName; + } + if (opts.appVersion) { + customHeaders["X-App-Version"] = opts.appVersion; + } + if (opts.authToken) { + customHeaders["X-Auth-Token"] = opts.authToken; + } + if (opts.headers) { + Object.assign(customHeaders, opts.headers); + } + if (Object.keys(customHeaders).length > 0) { + horizon_axios_client.interceptors.request.use(function (config) { + config.headers = config.headers || {}; + config.headers = Object.assign(config.headers, customHeaders); + return config; + }); + } + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure horizon server"); + } + } + return server_createClass(HorizonServer, [{ + key: "fetchTimebounds", + value: (function () { + var _fetchTimebounds = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee(seconds) { + var _isRetry, + currentTime, + _args = arguments; + return server_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _isRetry = _args.length > 1 && _args[1] !== undefined ? _args[1] : false; + currentTime = getCurrentServerTime(this.serverURL.hostname()); + if (!currentTime) { + _context.next = 4; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: currentTime + seconds + }); + case 4: + if (!_isRetry) { + _context.next = 6; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: Math.floor(new Date().getTime() / 1000) + seconds + }); + case 6: + _context.next = 8; + return horizon_axios_client.get(URI_default()(this.serverURL).toString()); + case 8: + return _context.abrupt("return", this.fetchTimebounds(seconds, true)); + case 9: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function fetchTimebounds(_x) { + return _fetchTimebounds.apply(this, arguments); + } + return fetchTimebounds; + }()) + }, { + key: "fetchBaseFee", + value: (function () { + var _fetchBaseFee = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee2() { + var response; + return server_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.feeStats(); + case 2: + response = _context2.sent; + return _context2.abrupt("return", parseInt(response.last_ledger_base_fee, 10) || 100); + case 4: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function fetchBaseFee() { + return _fetchBaseFee.apply(this, arguments); + } + return fetchBaseFee; + }()) + }, { + key: "feeStats", + value: (function () { + var _feeStats = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee3() { + var cb; + return server_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + cb = new CallBuilder(URI_default()(this.serverURL)); + cb.filter.push(["fee_stats"]); + return _context3.abrupt("return", cb.call()); + case 3: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function feeStats() { + return _feeStats.apply(this, arguments); + } + return feeStats; + }()) + }, { + key: "root", + value: (function () { + var _root = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee4() { + var cb; + return server_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + cb = new CallBuilder(URI_default()(this.serverURL)); + return _context4.abrupt("return", cb.call()); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function root() { + return _root.apply(this, arguments); + } + return root; + }()) + }, { + key: "submitTransaction", + value: (function () { + var _submitTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee5(transaction) { + var opts, + tx, + _args5 = arguments; + return server_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context5.next = 4; + break; + } + _context5.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context5.abrupt("return", horizon_axios_client.post(URI_default()(this.serverURL).segment("transactions").toString(), "tx=".concat(tx), { + timeout: SUBMIT_TRANSACTION_TIMEOUT + }).then(function (response) { + if (!response.data.result_xdr) { + return response.data; + } + var responseXDR = lib.xdr.TransactionResult.fromXDR(response.data.result_xdr, "base64"); + var results = responseXDR.result().value(); + var offerResults; + var hasManageOffer; + if (results.length) { + offerResults = results.map(function (result, i) { + if (result.value().switch().name !== "manageBuyOffer" && result.value().switch().name !== "manageSellOffer") { + return null; + } + hasManageOffer = true; + var amountBought = new bignumber(0); + var amountSold = new bignumber(0); + var offerSuccess = result.value().value().success(); + var offersClaimed = offerSuccess.offersClaimed().map(function (offerClaimedAtom) { + var offerClaimed = offerClaimedAtom.value(); + var sellerId = ""; + switch (offerClaimedAtom.switch()) { + case lib.xdr.ClaimAtomType.claimAtomTypeV0(): + sellerId = lib.StrKey.encodeEd25519PublicKey(offerClaimed.sellerEd25519()); + break; + case lib.xdr.ClaimAtomType.claimAtomTypeOrderBook(): + sellerId = lib.StrKey.encodeEd25519PublicKey(offerClaimed.sellerId().ed25519()); + break; + default: + throw new Error("Invalid offer result type: ".concat(offerClaimedAtom.switch())); + } + var claimedOfferAmountBought = new bignumber(offerClaimed.amountBought().toString()); + var claimedOfferAmountSold = new bignumber(offerClaimed.amountSold().toString()); + amountBought = amountBought.plus(claimedOfferAmountSold); + amountSold = amountSold.plus(claimedOfferAmountBought); + var sold = lib.Asset.fromOperation(offerClaimed.assetSold()); + var bought = lib.Asset.fromOperation(offerClaimed.assetBought()); + var assetSold = { + type: sold.getAssetType(), + assetCode: sold.getCode(), + issuer: sold.getIssuer() + }; + var assetBought = { + type: bought.getAssetType(), + assetCode: bought.getCode(), + issuer: bought.getIssuer() + }; + return { + sellerId: sellerId, + offerId: offerClaimed.offerId().toString(), + assetSold: assetSold, + amountSold: getAmountInLumens(claimedOfferAmountSold), + assetBought: assetBought, + amountBought: getAmountInLumens(claimedOfferAmountBought) + }; + }); + var effect = offerSuccess.offer().switch().name; + var currentOffer; + if (typeof offerSuccess.offer().value === "function" && offerSuccess.offer().value()) { + var offerXDR = offerSuccess.offer().value(); + currentOffer = { + offerId: offerXDR.offerId().toString(), + selling: {}, + buying: {}, + amount: getAmountInLumens(offerXDR.amount().toString()), + price: { + n: offerXDR.price().n(), + d: offerXDR.price().d() + } + }; + var selling = lib.Asset.fromOperation(offerXDR.selling()); + currentOffer.selling = { + type: selling.getAssetType(), + assetCode: selling.getCode(), + issuer: selling.getIssuer() + }; + var buying = lib.Asset.fromOperation(offerXDR.buying()); + currentOffer.buying = { + type: buying.getAssetType(), + assetCode: buying.getCode(), + issuer: buying.getIssuer() + }; + } + return { + offersClaimed: offersClaimed, + effect: effect, + operationIndex: i, + currentOffer: currentOffer, + amountBought: getAmountInLumens(amountBought), + amountSold: getAmountInLumens(amountSold), + isFullyOpen: !offersClaimed.length && effect !== "manageOfferDeleted", + wasPartiallyFilled: !!offersClaimed.length && effect !== "manageOfferDeleted", + wasImmediatelyFilled: !!offersClaimed.length && effect === "manageOfferDeleted", + wasImmediatelyDeleted: !offersClaimed.length && effect === "manageOfferDeleted" + }; + }).filter(function (result) { + return !!result; + }); + } + return _objectSpread(_objectSpread({}, response.data), {}, { + offerResults: hasManageOffer ? offerResults : undefined + }); + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new errors/* BadResponseError */.nS("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function submitTransaction(_x2) { + return _submitTransaction.apply(this, arguments); + } + return submitTransaction; + }()) + }, { + key: "submitAsyncTransaction", + value: (function () { + var _submitAsyncTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee6(transaction) { + var opts, + tx, + _args6 = arguments; + return server_regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context6.next = 4; + break; + } + _context6.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context6.abrupt("return", horizon_axios_client.post(URI_default()(this.serverURL).segment("transactions_async").toString(), "tx=".concat(tx)).then(function (response) { + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new errors/* BadResponseError */.nS("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function submitAsyncTransaction(_x3) { + return _submitAsyncTransaction.apply(this, arguments); + } + return submitAsyncTransaction; + }()) + }, { + key: "accounts", + value: function accounts() { + return new AccountCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "claimableBalances", + value: function claimableBalances() { + return new ClaimableBalanceCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "ledgers", + value: function ledgers() { + return new LedgerCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "transactions", + value: function transactions() { + return new TransactionCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "offers", + value: function offers() { + return new OfferCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "orderbook", + value: function orderbook(selling, buying) { + return new OrderbookCallBuilder(URI_default()(this.serverURL), selling, buying); + } + }, { + key: "trades", + value: function trades() { + return new TradesCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "operations", + value: function operations() { + return new OperationCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "liquidityPools", + value: function liquidityPools() { + return new LiquidityPoolCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "strictReceivePaths", + value: function strictReceivePaths(source, destinationAsset, destinationAmount) { + return new StrictReceivePathCallBuilder(URI_default()(this.serverURL), source, destinationAsset, destinationAmount); + } + }, { + key: "strictSendPaths", + value: function strictSendPaths(sourceAsset, sourceAmount, destination) { + return new StrictSendPathCallBuilder(URI_default()(this.serverURL), sourceAsset, sourceAmount, destination); + } + }, { + key: "payments", + value: function payments() { + return new PaymentCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "effects", + value: function effects() { + return new EffectCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "friendbot", + value: function friendbot(address) { + return new FriendbotBuilder(URI_default()(this.serverURL), address); + } + }, { + key: "assets", + value: function assets() { + return new AssetsCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "loadAccount", + value: (function () { + var _loadAccount = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee7(accountId) { + var res; + return server_regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.accounts().accountId(accountId).call(); + case 2: + res = _context7.sent; + return _context7.abrupt("return", new AccountResponse(res)); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function loadAccount(_x4) { + return _loadAccount.apply(this, arguments); + } + return loadAccount; + }()) + }, { + key: "tradeAggregation", + value: function tradeAggregation(base, counter, start_time, end_time, resolution, offset) { + return new TradeAggregationCallBuilder(URI_default()(this.serverURL), base, counter, start_time, end_time, resolution, offset); + } + }, { + key: "checkMemoRequired", + value: (function () { + var _checkMemoRequired = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee8(transaction) { + var destinations, i, operation, destination, account; + return server_regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (transaction instanceof lib.FeeBumpTransaction) { + transaction = transaction.innerTransaction; + } + if (!(transaction.memo.type !== "none")) { + _context8.next = 3; + break; + } + return _context8.abrupt("return"); + case 3: + destinations = new Set(); + i = 0; + case 5: + if (!(i < transaction.operations.length)) { + _context8.next = 36; + break; + } + operation = transaction.operations[i]; + _context8.t0 = operation.type; + _context8.next = _context8.t0 === "payment" ? 10 : _context8.t0 === "pathPaymentStrictReceive" ? 10 : _context8.t0 === "pathPaymentStrictSend" ? 10 : _context8.t0 === "accountMerge" ? 10 : 11; + break; + case 10: + return _context8.abrupt("break", 12); + case 11: + return _context8.abrupt("continue", 33); + case 12: + destination = operation.destination; + if (!destinations.has(destination)) { + _context8.next = 15; + break; + } + return _context8.abrupt("continue", 33); + case 15: + destinations.add(destination); + if (!destination.startsWith("M")) { + _context8.next = 18; + break; + } + return _context8.abrupt("continue", 33); + case 18: + _context8.prev = 18; + _context8.next = 21; + return this.loadAccount(destination); + case 21: + account = _context8.sent; + if (!(account.data_attr["config.memo_required"] === ACCOUNT_REQUIRES_MEMO)) { + _context8.next = 24; + break; + } + throw new errors/* AccountRequiresMemoError */.Cu("account requires memo", destination, i); + case 24: + _context8.next = 33; + break; + case 26: + _context8.prev = 26; + _context8.t1 = _context8["catch"](18); + if (!(_context8.t1 instanceof errors/* AccountRequiresMemoError */.Cu)) { + _context8.next = 30; + break; + } + throw _context8.t1; + case 30: + if (_context8.t1 instanceof errors/* NotFoundError */.m_) { + _context8.next = 32; + break; + } + throw _context8.t1; + case 32: + return _context8.abrupt("continue", 33); + case 33: + i += 1; + _context8.next = 5; + break; + case 36: + case "end": + return _context8.stop(); + } + }, _callee8, this, [[18, 26]]); + })); + function checkMemoRequired(_x5) { + return _checkMemoRequired.apply(this, arguments); + } + return checkMemoRequired; + }()) + }]); +}(); +;// ./src/horizon/index.ts +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + +/* harmony default export */ const horizon = (module.exports); + +/***/ }), + +/***/ 6121: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + axiosClient: () => (/* binding */ axiosClient), + create: () => (/* binding */ create) +}); + +// NAMESPACE OBJECT: ./node_modules/axios/lib/platform/common/utils.js +var common_utils_namespaceObject = {}; +__webpack_require__.r(common_utils_namespaceObject); +__webpack_require__.d(common_utils_namespaceObject, { + hasBrowserEnv: () => (hasBrowserEnv), + hasStandardBrowserEnv: () => (hasStandardBrowserEnv), + hasStandardBrowserWebWorkerEnv: () => (hasStandardBrowserWebWorkerEnv), + navigator: () => (_navigator), + origin: () => (origin) +}); + +;// ./node_modules/axios/lib/helpers/bind.js + + +function bind(fn, thisArg) { + return function wrap() { + return fn.apply(thisArg, arguments); + }; +} + +;// ./node_modules/axios/lib/utils.js + + + + +// utils is a library of generic helper functions non-specific to axios + +const {toString: utils_toString} = Object.prototype; +const {getPrototypeOf} = Object; + +const kindOf = (cache => thing => { + const str = utils_toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); +})(Object.create(null)); + +const kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type +} + +const typeOfTest = type => thing => typeof thing === type; + +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * + * @returns {boolean} True if value is an Array, otherwise false + */ +const {isArray} = Array; + +/** + * Determine if a value is undefined + * + * @param {*} val The value to test + * + * @returns {boolean} True if the value is undefined, otherwise false + */ +const isUndefined = typeOfTest('undefined'); + +/** + * Determine if a value is a Buffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); +} + +/** + * Determine if a value is an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +const isArrayBuffer = kindOfTest('ArrayBuffer'); + + +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + let result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); + } + return result; +} + +/** + * Determine if a value is a String + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a String, otherwise false + */ +const isString = typeOfTest('string'); + +/** + * Determine if a value is a Function + * + * @param {*} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +const isFunction = typeOfTest('function'); + +/** + * Determine if a value is a Number + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Number, otherwise false + */ +const isNumber = typeOfTest('number'); + +/** + * Determine if a value is an Object + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an Object, otherwise false + */ +const isObject = (thing) => thing !== null && typeof thing === 'object'; + +/** + * Determine if a value is a Boolean + * + * @param {*} thing The value to test + * @returns {boolean} True if value is a Boolean, otherwise false + */ +const isBoolean = thing => thing === true || thing === false; + +/** + * Determine if a value is a plain Object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a plain Object, otherwise false + */ +const isPlainObject = (val) => { + if (kindOf(val) !== 'object') { + return false; + } + + const prototype = getPrototypeOf(val); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); +} + +/** + * Determine if a value is a Date + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Date, otherwise false + */ +const isDate = kindOfTest('Date'); + +/** + * Determine if a value is a File + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFile = kindOfTest('File'); + +/** + * Determine if a value is a Blob + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Blob, otherwise false + */ +const isBlob = kindOfTest('Blob'); + +/** + * Determine if a value is a FileList + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFileList = kindOfTest('FileList'); + +/** + * Determine if a value is a Stream + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Stream, otherwise false + */ +const isStream = (val) => isObject(val) && isFunction(val.pipe); + +/** + * Determine if a value is a FormData + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an FormData, otherwise false + */ +const isFormData = (thing) => { + let kind; + return thing && ( + (typeof FormData === 'function' && thing instanceof FormData) || ( + isFunction(thing.append) && ( + (kind = kindOf(thing)) === 'formdata' || + // detect form-data instance + (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]') + ) + ) + ) +} + +/** + * Determine if a value is a URLSearchParams object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +const isURLSearchParams = kindOfTest('URLSearchParams'); + +const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest); + +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * + * @returns {String} The String freed of excess whitespace + */ +const trim = (str) => str.trim ? + str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + * + * @param {Boolean} [allOwnKeys = false] + * @returns {any} + */ +function forEach(obj, fn, {allOwnKeys = false} = {}) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + let i; + let l; + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; + + for (i = 0; i < len; i++) { + key = keys[i]; + fn.call(null, obj[key], key, obj); + } + } +} + +function findKey(obj, key) { + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; +} + +const _global = (() => { + /*eslint no-undef:0*/ + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global) +})(); + +const isContextDefined = (context) => !isUndefined(context) && context !== _global; + +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + const {caseless} = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + } + + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); + } + return result; +} + +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * + * @param {Boolean} [allOwnKeys] + * @returns {Object} The resulting value of object a + */ +const extend = (a, b, thisArg, {allOwnKeys}= {}) => { + forEach(b, (val, key) => { + if (thisArg && isFunction(val)) { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }, {allOwnKeys}); + return a; +} + +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * + * @returns {string} content value without BOM + */ +const stripBOM = (content) => { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +} + +/** + * Inherit the prototype methods from one constructor into another + * @param {function} constructor + * @param {function} superConstructor + * @param {object} [props] + * @param {object} [descriptors] + * + * @returns {void} + */ +const inherits = (constructor, superConstructor, props, descriptors) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, 'super', { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); +} + +/** + * Resolve object with deep prototype chain to a flat object + * @param {Object} sourceObj source object + * @param {Object} [destObj] + * @param {Function|Boolean} [filter] + * @param {Function} [propFilter] + * + * @returns {Object} + */ +const toFlatObject = (sourceObj, destObj, filter, propFilter) => { + let props; + let i; + let prop; + const merged = {}; + + destObj = destObj || {}; + // eslint-disable-next-line no-eq-null,eqeqeq + if (sourceObj == null) return destObj; + + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + + return destObj; +} + +/** + * Determines whether a string ends with the characters of a specified string + * + * @param {String} str + * @param {String} searchString + * @param {Number} [position= 0] + * + * @returns {boolean} + */ +const endsWith = (str, searchString, position) => { + str = String(str); + if (position === undefined || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; +} + + +/** + * Returns new array from array like object or null if failed + * + * @param {*} [thing] + * + * @returns {?Array} + */ +const toArray = (thing) => { + if (!thing) return null; + if (isArray(thing)) return thing; + let i = thing.length; + if (!isNumber(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; +} + +/** + * Checking if the Uint8Array exists and if it does, it returns a function that checks if the + * thing passed in is an instance of Uint8Array + * + * @param {TypedArray} + * + * @returns {Array} + */ +// eslint-disable-next-line func-names +const isTypedArray = (TypedArray => { + // eslint-disable-next-line func-names + return thing => { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); + +/** + * For each entry in the object, call the function with the key and value. + * + * @param {Object} obj - The object to iterate over. + * @param {Function} fn - The function to call for each entry. + * + * @returns {void} + */ +const forEachEntry = (obj, fn) => { + const generator = obj && obj[Symbol.iterator]; + + const iterator = generator.call(obj); + + let result; + + while ((result = iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); + } +} + +/** + * It takes a regular expression and a string, and returns an array of all the matches + * + * @param {string} regExp - The regular expression to match against. + * @param {string} str - The string to search. + * + * @returns {Array} + */ +const matchAll = (regExp, str) => { + let matches; + const arr = []; + + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + + return arr; +} + +/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ +const isHTMLForm = kindOfTest('HTMLFormElement'); + +const toCamelCase = str => { + return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, + function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; + } + ); +}; + +/* Creating a function that will check if an object has a property. */ +const utils_hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); + +/** + * Determine if a value is a RegExp object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a RegExp object, otherwise false + */ +const isRegExp = kindOfTest('RegExp'); + +const reduceDescriptors = (obj, reducer) => { + const descriptors = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + + forEach(descriptors, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); + + Object.defineProperties(obj, reducedDescriptors); +} + +/** + * Makes all methods read-only + * @param {Object} obj + */ + +const freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name) => { + // skip restricted props in strict mode + if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { + return false; + } + + const value = obj[name]; + + if (!isFunction(value)) return; + + descriptor.enumerable = false; + + if ('writable' in descriptor) { + descriptor.writable = false; + return; + } + + if (!descriptor.set) { + descriptor.set = () => { + throw Error('Can not rewrite read-only method \'' + name + '\''); + }; + } + }); +} + +const toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; + + const define = (arr) => { + arr.forEach(value => { + obj[value] = true; + }); + } + + isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + + return obj; +} + +const noop = () => {} + +const toFiniteNumber = (value, defaultValue) => { + return value != null && Number.isFinite(value = +value) ? value : defaultValue; +} + +const ALPHA = 'abcdefghijklmnopqrstuvwxyz' + +const DIGIT = '0123456789'; + +const ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT +} + +const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { + let str = ''; + const {length} = alphabet; + while (size--) { + str += alphabet[Math.random() * length|0] + } + + return str; +} + +/** + * If the thing is a FormData object, return true, otherwise return false. + * + * @param {unknown} thing - The thing to check. + * + * @returns {boolean} + */ +function isSpecCompliantForm(thing) { + return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]); +} + +const toJSONObject = (obj) => { + const stack = new Array(10); + + const visit = (source, i) => { + + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + + if(!('toJSON' in source)) { + stack[i] = source; + const target = isArray(source) ? [] : {}; + + forEach(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + + stack[i] = undefined; + + return target; + } + } + + return source; + } + + return visit(obj, 0); +} + +const isAsyncFn = kindOfTest('AsyncFunction'); + +const isThenable = (thing) => + thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); + +// original code +// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 + +const _setImmediate = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; + } + + return postMessageSupported ? ((token, callbacks) => { + _global.addEventListener("message", ({source, data}) => { + if (source === _global && data === token) { + callbacks.length && callbacks.shift()(); + } + }, false); + + return (cb) => { + callbacks.push(cb); + _global.postMessage(token, "*"); + } + })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); +})( + typeof setImmediate === 'function', + isFunction(_global.postMessage) +); + +const asap = typeof queueMicrotask !== 'undefined' ? + queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate); + +// ********************* + +/* harmony default export */ const utils = ({ + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString, + isNumber, + isBoolean, + isObject, + isPlainObject, + isReadableStream, + isRequest, + isResponse, + isHeaders, + isUndefined, + isDate, + isFile, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty: utils_hasOwnProperty, + hasOwnProp: utils_hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + ALPHABET, + generateString, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable, + setImmediate: _setImmediate, + asap +}); + +;// ./node_modules/axios/lib/core/AxiosError.js + + + + +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [config] The config. + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * + * @returns {Error} The created error. + */ +function AxiosError(message, code, config, request, response) { + Error.call(this); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = (new Error()).stack; + } + + this.message = message; + this.name = 'AxiosError'; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status ? response.status : null; + } +} + +utils.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils.toJSONObject(this.config), + code: this.code, + status: this.status + }; + } +}); + +const AxiosError_prototype = AxiosError.prototype; +const descriptors = {}; + +[ + 'ERR_BAD_OPTION_VALUE', + 'ERR_BAD_OPTION', + 'ECONNABORTED', + 'ETIMEDOUT', + 'ERR_NETWORK', + 'ERR_FR_TOO_MANY_REDIRECTS', + 'ERR_DEPRECATED', + 'ERR_BAD_RESPONSE', + 'ERR_BAD_REQUEST', + 'ERR_CANCELED', + 'ERR_NOT_SUPPORT', + 'ERR_INVALID_URL' +// eslint-disable-next-line func-names +].forEach(code => { + descriptors[code] = {value: code}; +}); + +Object.defineProperties(AxiosError, descriptors); +Object.defineProperty(AxiosError_prototype, 'isAxiosError', {value: true}); + +// eslint-disable-next-line func-names +AxiosError.from = (error, code, config, request, response, customProps) => { + const axiosError = Object.create(AxiosError_prototype); + + utils.toFlatObject(error, axiosError, function filter(obj) { + return obj !== Error.prototype; + }, prop => { + return prop !== 'isAxiosError'; + }); + + AxiosError.call(axiosError, error.message, code, config, request, response); + + axiosError.cause = error; + + axiosError.name = error.name; + + customProps && Object.assign(axiosError, customProps); + + return axiosError; +}; + +/* harmony default export */ const core_AxiosError = (AxiosError); + +;// ./node_modules/axios/lib/helpers/null.js +// eslint-disable-next-line strict +/* harmony default export */ const helpers_null = (null); + +;// ./node_modules/axios/lib/helpers/toFormData.js +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + + + +// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored + + +/** + * Determines if the given thing is a array or js object. + * + * @param {string} thing - The object or array to be visited. + * + * @returns {boolean} + */ +function isVisitable(thing) { + return utils.isPlainObject(thing) || utils.isArray(thing); +} + +/** + * It removes the brackets from the end of a string + * + * @param {string} key - The key of the parameter. + * + * @returns {string} the key without the brackets. + */ +function removeBrackets(key) { + return utils.endsWith(key, '[]') ? key.slice(0, -2) : key; +} + +/** + * It takes a path, a key, and a boolean, and returns a string + * + * @param {string} path - The path to the current key. + * @param {string} key - The key of the current object being iterated over. + * @param {string} dots - If true, the key will be rendered with dots instead of brackets. + * + * @returns {string} The path to the current key. + */ +function renderKey(path, key, dots) { + if (!path) return key; + return path.concat(key).map(function each(token, i) { + // eslint-disable-next-line no-param-reassign + token = removeBrackets(token); + return !dots && i ? '[' + token + ']' : token; + }).join(dots ? '.' : ''); +} + +/** + * If the array is an array and none of its elements are visitable, then it's a flat array. + * + * @param {Array} arr - The array to check + * + * @returns {boolean} + */ +function isFlatArray(arr) { + return utils.isArray(arr) && !arr.some(isVisitable); +} + +const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); +}); + +/** + * Convert a data object to FormData + * + * @param {Object} obj + * @param {?Object} [formData] + * @param {?Object} [options] + * @param {Function} [options.visitor] + * @param {Boolean} [options.metaTokens = true] + * @param {Boolean} [options.dots = false] + * @param {?Boolean} [options.indexes = false] + * + * @returns {Object} + **/ + +/** + * It converts an object into a FormData object + * + * @param {Object} obj - The object to convert to form data. + * @param {string} formData - The FormData object to append to. + * @param {Object} options + * + * @returns + */ +function toFormData(obj, formData, options) { + if (!utils.isObject(obj)) { + throw new TypeError('target must be an object'); + } + + // eslint-disable-next-line no-param-reassign + formData = formData || new (helpers_null || FormData)(); + + // eslint-disable-next-line no-param-reassign + options = utils.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + // eslint-disable-next-line no-eq-null,eqeqeq + return !utils.isUndefined(source[option]); + }); + + const metaTokens = options.metaTokens; + // eslint-disable-next-line no-use-before-define + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; + const useBlob = _Blob && utils.isSpecCompliantForm(formData); + + if (!utils.isFunction(visitor)) { + throw new TypeError('visitor must be a function'); + } + + function convertValue(value) { + if (value === null) return ''; + + if (utils.isDate(value)) { + return value.toISOString(); + } + + if (!useBlob && utils.isBlob(value)) { + throw new core_AxiosError('Blob is not supported. Use a Buffer instead.'); + } + + if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) { + return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + } + + return value; + } + + /** + * Default visitor. + * + * @param {*} value + * @param {String|Number} key + * @param {Array} path + * @this {FormData} + * + * @returns {boolean} return true to visit the each prop of the value recursively + */ + function defaultVisitor(value, key, path) { + let arr = value; + + if (value && !path && typeof value === 'object') { + if (utils.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign + key = metaTokens ? key : key.slice(0, -2); + // eslint-disable-next-line no-param-reassign + value = JSON.stringify(value); + } else if ( + (utils.isArray(value) && isFlatArray(value)) || + ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value)) + )) { + // eslint-disable-next-line no-param-reassign + key = removeBrackets(key); + + arr.forEach(function each(el, index) { + !(utils.isUndefined(el) || el === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), + convertValue(el) + ); + }); + return false; + } + } + + if (isVisitable(value)) { + return true; + } + + formData.append(renderKey(path, key, dots), convertValue(value)); + + return false; + } + + const stack = []; + + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable + }); + + function build(value, path) { + if (utils.isUndefined(value)) return; + + if (stack.indexOf(value) !== -1) { + throw Error('Circular reference detected in ' + path.join('.')); + } + + stack.push(value); + + utils.forEach(value, function each(el, key) { + const result = !(utils.isUndefined(el) || el === null) && visitor.call( + formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers + ); + + if (result === true) { + build(el, path ? path.concat(key) : [key]); + } + }); + + stack.pop(); + } + + if (!utils.isObject(obj)) { + throw new TypeError('data must be an object'); + } + + build(obj); + + return formData; +} + +/* harmony default export */ const helpers_toFormData = (toFormData); + +;// ./node_modules/axios/lib/helpers/AxiosURLSearchParams.js + + + + +/** + * It encodes a string by replacing all characters that are not in the unreserved set with + * their percent-encoded equivalents + * + * @param {string} str - The string to encode. + * + * @returns {string} The encoded string. + */ +function encode(str) { + const charMap = { + '!': '%21', + "'": '%27', + '(': '%28', + ')': '%29', + '~': '%7E', + '%20': '+', + '%00': '\x00' + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); +} + +/** + * It takes a params object and converts it to a FormData object + * + * @param {Object} params - The parameters to be converted to a FormData object. + * @param {Object} options - The options object passed to the Axios constructor. + * + * @returns {void} + */ +function AxiosURLSearchParams(params, options) { + this._pairs = []; + + params && helpers_toFormData(params, this, options); +} + +const AxiosURLSearchParams_prototype = AxiosURLSearchParams.prototype; + +AxiosURLSearchParams_prototype.append = function append(name, value) { + this._pairs.push([name, value]); +}; + +AxiosURLSearchParams_prototype.toString = function toString(encoder) { + const _encode = encoder ? function(value) { + return encoder.call(this, value, encode); + } : encode; + + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + '=' + _encode(pair[1]); + }, '').join('&'); +}; + +/* harmony default export */ const helpers_AxiosURLSearchParams = (AxiosURLSearchParams); + +;// ./node_modules/axios/lib/helpers/buildURL.js + + + + + +/** + * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their + * URI encoded counterparts + * + * @param {string} val The value to be encoded. + * + * @returns {string} The encoded value. + */ +function buildURL_encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} + +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @param {?(object|Function)} options + * + * @returns {string} The formatted url + */ +function buildURL(url, params, options) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + + const _encode = options && options.encode || buildURL_encode; + + if (utils.isFunction(options)) { + options = { + serialize: options + }; + } + + const serializeFn = options && options.serialize; + + let serializedParams; + + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils.isURLSearchParams(params) ? + params.toString() : + new helpers_AxiosURLSearchParams(params, options).toString(_encode); + } + + if (serializedParams) { + const hashmarkIndex = url.indexOf("#"); + + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + + return url; +} + +;// ./node_modules/axios/lib/core/InterceptorManager.js + + + + +class InterceptorManager { + constructor() { + this.handlers = []; + } + + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + */ + eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; + } + } + + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + } +} + +/* harmony default export */ const core_InterceptorManager = (InterceptorManager); + +;// ./node_modules/axios/lib/defaults/transitional.js + + +/* harmony default export */ const defaults_transitional = ({ + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false +}); + +;// ./node_modules/axios/lib/platform/browser/classes/URLSearchParams.js + + + +/* harmony default export */ const classes_URLSearchParams = (typeof URLSearchParams !== 'undefined' ? URLSearchParams : helpers_AxiosURLSearchParams); + +;// ./node_modules/axios/lib/platform/browser/classes/FormData.js + + +/* harmony default export */ const classes_FormData = (typeof FormData !== 'undefined' ? FormData : null); + +;// ./node_modules/axios/lib/platform/browser/classes/Blob.js + + +/* harmony default export */ const classes_Blob = (typeof Blob !== 'undefined' ? Blob : null); + +;// ./node_modules/axios/lib/platform/browser/index.js + + + + +/* harmony default export */ const browser = ({ + isBrowser: true, + classes: { + URLSearchParams: classes_URLSearchParams, + FormData: classes_FormData, + Blob: classes_Blob + }, + protocols: ['http', 'https', 'file', 'blob', 'url', 'data'] +}); + +;// ./node_modules/axios/lib/platform/common/utils.js +const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; + +const _navigator = typeof navigator === 'object' && navigator || undefined; + +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + * + * @returns {boolean} + */ +const hasStandardBrowserEnv = hasBrowserEnv && + (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0); + +/** + * Determine if we're running in a standard browser webWorker environment + * + * Although the `isStandardBrowserEnv` method indicates that + * `allows axios to run in a web worker`, the WebWorker will still be + * filtered out due to its judgment standard + * `typeof window !== 'undefined' && typeof document !== 'undefined'`. + * This leads to a problem when axios post `FormData` in webWorker + */ +const hasStandardBrowserWebWorkerEnv = (() => { + return ( + typeof WorkerGlobalScope !== 'undefined' && + // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && + typeof self.importScripts === 'function' + ); +})(); + +const origin = hasBrowserEnv && window.location.href || 'http://localhost'; + + + +;// ./node_modules/axios/lib/platform/index.js + + + +/* harmony default export */ const platform = ({ + ...common_utils_namespaceObject, + ...browser +}); + +;// ./node_modules/axios/lib/helpers/toURLEncodedForm.js + + + + + + +function toURLEncodedForm(data, options) { + return helpers_toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (platform.isNode && utils.isBuffer(value)) { + this.append(key, value.toString('base64')); + return false; + } + + return helpers.defaultVisitor.apply(this, arguments); + } + }, options)); +} + +;// ./node_modules/axios/lib/helpers/formDataToJSON.js + + + + +/** + * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z'] + * + * @param {string} name - The name of the property to get. + * + * @returns An array of strings. + */ +function parsePropPath(name) { + // foo[x][y][z] + // foo.x.y.z + // foo-x-y-z + // foo x y z + return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => { + return match[0] === '[]' ? '' : match[1] || match[0]; + }); +} + +/** + * Convert an array to an object. + * + * @param {Array} arr - The array to convert to an object. + * + * @returns An object with the same keys and values as the array. + */ +function arrayToObject(arr) { + const obj = {}; + const keys = Object.keys(arr); + let i; + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; +} + +/** + * It takes a FormData object and returns a JavaScript object + * + * @param {string} formData The FormData object to convert to JSON. + * + * @returns {Object | null} The converted object. + */ +function formDataToJSON(formData) { + function buildPath(path, value, target, index) { + let name = path[index++]; + + if (name === '__proto__') return true; + + const isNumericKey = Number.isFinite(+name); + const isLast = index >= path.length; + name = !name && utils.isArray(target) ? target.length : name; + + if (isLast) { + if (utils.hasOwnProp(target, name)) { + target[name] = [target[name], value]; + } else { + target[name] = value; + } + + return !isNumericKey; + } + + if (!target[name] || !utils.isObject(target[name])) { + target[name] = []; + } + + const result = buildPath(path, value, target[name], index); + + if (result && utils.isArray(target[name])) { + target[name] = arrayToObject(target[name]); + } + + return !isNumericKey; + } + + if (utils.isFormData(formData) && utils.isFunction(formData.entries)) { + const obj = {}; + + utils.forEachEntry(formData, (name, value) => { + buildPath(parsePropPath(name), value, obj, 0); + }); + + return obj; + } + + return null; +} + +/* harmony default export */ const helpers_formDataToJSON = (formDataToJSON); + +;// ./node_modules/axios/lib/defaults/index.js + + + + + + + + + + +/** + * It takes a string, tries to parse it, and if it fails, it returns the stringified version + * of the input + * + * @param {any} rawValue - The value to be stringified. + * @param {Function} parser - A function that parses a string into a JavaScript object. + * @param {Function} encoder - A function that takes a value and returns a string. + * + * @returns {string} A stringified version of the rawValue. + */ +function stringifySafely(rawValue, parser, encoder) { + if (utils.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } + } + } + + return (encoder || JSON.stringify)(rawValue); +} + +const defaults = { + + transitional: defaults_transitional, + + adapter: ['xhr', 'http', 'fetch'], + + transformRequest: [function transformRequest(data, headers) { + const contentType = headers.getContentType() || ''; + const hasJSONContentType = contentType.indexOf('application/json') > -1; + const isObjectPayload = utils.isObject(data); + + if (isObjectPayload && utils.isHTMLForm(data)) { + data = new FormData(data); + } + + const isFormData = utils.isFormData(data); + + if (isFormData) { + return hasJSONContentType ? JSON.stringify(helpers_formDataToJSON(data)) : data; + } + + if (utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) || + utils.isReadableStream(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); + return data.toString(); + } + + let isFileList; + + if (isObjectPayload) { + if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + + if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { + const _FormData = this.env && this.env.FormData; + + return helpers_toFormData( + isFileList ? {'files[]': data} : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + + if (isObjectPayload || hasJSONContentType ) { + headers.setContentType('application/json', false); + return stringifySafely(data); + } + + return data; + }], + + transformResponse: [function transformResponse(data) { + const transitional = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional && transitional.forcedJSONParsing; + const JSONRequested = this.responseType === 'json'; + + if (utils.isResponse(data) || utils.isReadableStream(data)) { + return data; + } + + if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { + const silentJSONParsing = transitional && transitional.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw core_AxiosError.from(e, core_AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } + + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + + headers: { + common: { + 'Accept': 'application/json, text/plain, */*', + 'Content-Type': undefined + } + } +}; + +utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { + defaults.headers[method] = {}; +}); + +/* harmony default export */ const lib_defaults = (defaults); + +;// ./node_modules/axios/lib/helpers/parseHeaders.js + + + + +// RawAxiosHeaders whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +const ignoreDuplicateOf = utils.toObjectSet([ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]); + +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} rawHeaders Headers needing to be parsed + * + * @returns {Object} Headers parsed into an object + */ +/* harmony default export */ const parseHeaders = (rawHeaders => { + const parsed = {}; + let key; + let val; + let i; + + rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { + i = line.indexOf(':'); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + + if (!key || (parsed[key] && ignoreDuplicateOf[key])) { + return; + } + + if (key === 'set-cookie') { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + }); + + return parsed; +}); + +;// ./node_modules/axios/lib/core/AxiosHeaders.js + + + + + +const $internals = Symbol('internals'); + +function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); +} + +function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + + return utils.isArray(value) ? value.map(normalizeValue) : String(value); +} + +function parseTokens(str) { + const tokens = Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + + while ((match = tokensRE.exec(str))) { + tokens[match[1]] = match[2]; + } + + return tokens; +} + +const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); + +function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { + if (utils.isFunction(filter)) { + return filter.call(this, value, header); + } + + if (isHeaderNameFilter) { + value = header; + } + + if (!utils.isString(value)) return; + + if (utils.isString(filter)) { + return value.indexOf(filter) !== -1; + } + + if (utils.isRegExp(filter)) { + return filter.test(value); + } +} + +function formatHeader(header) { + return header.trim() + .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { + return char.toUpperCase() + str; + }); +} + +function buildAccessors(obj, header) { + const accessorName = utils.toCamelCase(' ' + header); + + ['get', 'set', 'has'].forEach(methodName => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); +} + +class AxiosHeaders { + constructor(headers) { + headers && this.set(headers); + } + + set(header, valueOrRewrite, rewrite) { + const self = this; + + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); + + if (!lHeader) { + throw new Error('header name must be a non-empty string'); + } + + const key = utils.findKey(self, lHeader); + + if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { + self[key || _header] = normalizeValue(_value); + } + } + + const setHeaders = (headers, _rewrite) => + utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + + if (utils.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite) + } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else if (utils.isHeaders(header)) { + for (const [key, value] of header.entries()) { + setHeader(value, key, rewrite); + } + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + + return this; + } + + get(header, parser) { + header = normalizeHeader(header); + + if (header) { + const key = utils.findKey(this, header); + + if (key) { + const value = this[key]; + + if (!parser) { + return value; + } + + if (parser === true) { + return parseTokens(value); + } + + if (utils.isFunction(parser)) { + return parser.call(this, value, key); + } + + if (utils.isRegExp(parser)) { + return parser.exec(value); + } + + throw new TypeError('parser must be boolean|regexp|function'); + } + } + } + + has(header, matcher) { + header = normalizeHeader(header); + + if (header) { + const key = utils.findKey(this, header); + + return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + } + + return false; + } + + delete(header, matcher) { + const self = this; + let deleted = false; + + function deleteHeader(_header) { + _header = normalizeHeader(_header); + + if (_header) { + const key = utils.findKey(self, _header); + + if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { + delete self[key]; + + deleted = true; + } + } + } + + if (utils.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + + return deleted; + } + + clear(matcher) { + const keys = Object.keys(this); + let i = keys.length; + let deleted = false; + + while (i--) { + const key = keys[i]; + if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + + return deleted; + } + + normalize(format) { + const self = this; + const headers = {}; + + utils.forEach(this, (value, header) => { + const key = utils.findKey(headers, header); + + if (key) { + self[key] = normalizeValue(value); + delete self[header]; + return; + } + + const normalized = format ? formatHeader(header) : String(header).trim(); + + if (normalized !== header) { + delete self[header]; + } + + self[normalized] = normalizeValue(value); + + headers[normalized] = true; + }); + + return this; + } + + concat(...targets) { + return this.constructor.concat(this, ...targets); + } + + toJSON(asStrings) { + const obj = Object.create(null); + + utils.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value); + }); + + return obj; + } + + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n'); + } + + get [Symbol.toStringTag]() { + return 'AxiosHeaders'; + } + + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + + static concat(first, ...targets) { + const computed = new this(first); + + targets.forEach((target) => computed.set(target)); + + return computed; + } + + static accessor(header) { + const internals = this[$internals] = (this[$internals] = { + accessors: {} + }); + + const accessors = internals.accessors; + const prototype = this.prototype; + + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); + + if (!accessors[lHeader]) { + buildAccessors(prototype, _header); + accessors[lHeader] = true; + } + } + + utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + + return this; + } +} + +AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); + +// reserved names hotfix +utils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } + } +}); + +utils.freezeMethods(AxiosHeaders); + +/* harmony default export */ const core_AxiosHeaders = (AxiosHeaders); + +;// ./node_modules/axios/lib/core/transformData.js + + + + + + +/** + * Transform the data for a request or a response + * + * @param {Array|Function} fns A single function or Array of functions + * @param {?Object} response The response object + * + * @returns {*} The resulting transformed data + */ +function transformData(fns, response) { + const config = this || lib_defaults; + const context = response || config; + const headers = core_AxiosHeaders.from(context.headers); + let data = context.data; + + utils.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); + }); + + headers.normalize(); + + return data; +} + +;// ./node_modules/axios/lib/cancel/isCancel.js + + +function isCancel(value) { + return !!(value && value.__CANCEL__); +} + +;// ./node_modules/axios/lib/cancel/CanceledError.js + + + + + +/** + * A `CanceledError` is an object that is thrown when an operation is canceled. + * + * @param {string=} message The message. + * @param {Object=} config The config. + * @param {Object=} request The request. + * + * @returns {CanceledError} The created error. + */ +function CanceledError(message, config, request) { + // eslint-disable-next-line no-eq-null,eqeqeq + core_AxiosError.call(this, message == null ? 'canceled' : message, core_AxiosError.ERR_CANCELED, config, request); + this.name = 'CanceledError'; +} + +utils.inherits(CanceledError, core_AxiosError, { + __CANCEL__: true +}); + +/* harmony default export */ const cancel_CanceledError = (CanceledError); + +;// ./node_modules/axios/lib/core/settle.js + + + + +/** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + * + * @returns {object} The response. + */ +function settle(resolve, reject, response) { + const validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new core_AxiosError( + 'Request failed with status code ' + response.status, + [core_AxiosError.ERR_BAD_REQUEST, core_AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } +} + +;// ./node_modules/axios/lib/helpers/parseProtocol.js + + +function parseProtocol(url) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ''; +} + +;// ./node_modules/axios/lib/helpers/speedometer.js + + +/** + * Calculate data maxRate + * @param {Number} [samplesCount= 10] + * @param {Number} [min= 1000] + * @returns {Function} + */ +function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + + min = min !== undefined ? min : 1000; + + return function push(chunkLength) { + const now = Date.now(); + + const startedAt = timestamps[tail]; + + if (!firstSampleTS) { + firstSampleTS = now; + } + + bytes[head] = chunkLength; + timestamps[head] = now; + + let i = tail; + let bytesCount = 0; + + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + + head = (head + 1) % samplesCount; + + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + + if (now - firstSampleTS < min) { + return; + } + + const passed = startedAt && now - startedAt; + + return passed ? Math.round(bytesCount * 1000 / passed) : undefined; + }; +} + +/* harmony default export */ const helpers_speedometer = (speedometer); + +;// ./node_modules/axios/lib/helpers/throttle.js +/** + * Throttle decorator + * @param {Function} fn + * @param {Number} freq + * @return {Function} + */ +function throttle(fn, freq) { + let timestamp = 0; + let threshold = 1000 / freq; + let lastArgs; + let timer; + + const invoke = (args, now = Date.now()) => { + timestamp = now; + lastArgs = null; + if (timer) { + clearTimeout(timer); + timer = null; + } + fn.apply(null, args); + } + + const throttled = (...args) => { + const now = Date.now(); + const passed = now - timestamp; + if ( passed >= threshold) { + invoke(args, now); + } else { + lastArgs = args; + if (!timer) { + timer = setTimeout(() => { + timer = null; + invoke(lastArgs) + }, threshold - passed); + } + } + } + + const flush = () => lastArgs && invoke(lastArgs); + + return [throttled, flush]; +} + +/* harmony default export */ const helpers_throttle = (throttle); + +;// ./node_modules/axios/lib/helpers/progressEventReducer.js + + + + +const progressEventReducer = (listener, isDownloadStream, freq = 3) => { + let bytesNotified = 0; + const _speedometer = helpers_speedometer(50, 250); + + return helpers_throttle(e => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : undefined; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange = loaded <= total; + + bytesNotified = loaded; + + const data = { + loaded, + total, + progress: total ? (loaded / total) : undefined, + bytes: progressBytes, + rate: rate ? rate : undefined, + estimated: rate && total && inRange ? (total - loaded) / rate : undefined, + event: e, + lengthComputable: total != null, + [isDownloadStream ? 'download' : 'upload']: true + }; + + listener(data); + }, freq); +} + +const progressEventDecorator = (total, throttled) => { + const lengthComputable = total != null; + + return [(loaded) => throttled[0]({ + lengthComputable, + total, + loaded + }), throttled[1]]; +} + +const asyncDecorator = (fn) => (...args) => utils.asap(() => fn(...args)); + +;// ./node_modules/axios/lib/helpers/isURLSameOrigin.js + + +/* harmony default export */ const isURLSameOrigin = (platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => { + url = new URL(url, platform.origin); + + return ( + origin.protocol === url.protocol && + origin.host === url.host && + (isMSIE || origin.port === url.port) + ); +})( + new URL(platform.origin), + platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) +) : () => true); + +;// ./node_modules/axios/lib/helpers/cookies.js + + + +/* harmony default export */ const cookies = (platform.hasStandardBrowserEnv ? + + // Standard browser envs support document.cookie + { + write(name, value, expires, path, domain, secure) { + const cookie = [name + '=' + encodeURIComponent(value)]; + + utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString()); + + utils.isString(path) && cookie.push('path=' + path); + + utils.isString(domain) && cookie.push('domain=' + domain); + + secure === true && cookie.push('secure'); + + document.cookie = cookie.join('; '); + }, + + read(name) { + const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, + + remove(name) { + this.write(name, '', Date.now() - 86400000); + } + } + + : + + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() {}, + read() { + return null; + }, + remove() {} + }); + + +;// ./node_modules/axios/lib/helpers/isAbsoluteURL.js + + +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); +} + +;// ./node_modules/axios/lib/helpers/combineURLs.js + + +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * + * @returns {string} The combined URL + */ +function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +} + +;// ./node_modules/axios/lib/core/buildFullPath.js + + + + + +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * + * @returns {string} The combined full path + */ +function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +} + +;// ./node_modules/axios/lib/core/mergeConfig.js + + + + + +const headersToObject = (thing) => thing instanceof core_AxiosHeaders ? { ...thing } : thing; + +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * + * @returns {Object} New object resulting from merging config2 to config1 + */ +function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + const config = {}; + + function getMergedValue(target, source, prop, caseless) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge.call({caseless}, target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } + + // eslint-disable-next-line consistent-return + function mergeDeepProperties(a, b, prop , caseless) { + if (!utils.isUndefined(b)) { + return getMergedValue(a, b, prop , caseless); + } else if (!utils.isUndefined(a)) { + return getMergedValue(undefined, a, prop , caseless); + } + } + + // eslint-disable-next-line consistent-return + function valueFromConfig2(a, b) { + if (!utils.isUndefined(b)) { + return getMergedValue(undefined, b); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(a, b) { + if (!utils.isUndefined(b)) { + return getMergedValue(undefined, b); + } else if (!utils.isUndefined(a)) { + return getMergedValue(undefined, a); + } + } + + // eslint-disable-next-line consistent-return + function mergeDirectKeys(a, b, prop) { + if (prop in config2) { + return getMergedValue(a, b); + } else if (prop in config1) { + return getMergedValue(undefined, a); + } + } + + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true) + }; + + utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + const merge = mergeMap[prop] || mergeDeepProperties; + const configValue = merge(config1[prop], config2[prop], prop); + (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); + + return config; +} + +;// ./node_modules/axios/lib/helpers/resolveConfig.js + + + + + + + + + +/* harmony default export */ const resolveConfig = ((config) => { + const newConfig = mergeConfig({}, config); + + let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig; + + newConfig.headers = headers = core_AxiosHeaders.from(headers); + + newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer); + + // HTTP basic authentication + if (auth) { + headers.set('Authorization', 'Basic ' + + btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : '')) + ); + } + + let contentType; + + if (utils.isFormData(data)) { + if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { + headers.setContentType(undefined); // Let the browser set it + } else if ((contentType = headers.getContentType()) !== false) { + // fix semicolon duplication issue for ReactNative FormData implementation + const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : []; + headers.setContentType([type || 'multipart/form-data', ...tokens].join('; ')); + } + } + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + + if (platform.hasStandardBrowserEnv) { + withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); + + if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) { + // Add xsrf header + const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); + + if (xsrfValue) { + headers.set(xsrfHeaderName, xsrfValue); + } + } + } + + return newConfig; +}); + + +;// ./node_modules/axios/lib/adapters/xhr.js + + + + + + + + + + + +const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; + +/* harmony default export */ const xhr = (isXHRAdapterSupported && function (config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + const _config = resolveConfig(config); + let requestData = _config.data; + const requestHeaders = core_AxiosHeaders.from(_config.headers).normalize(); + let {responseType, onUploadProgress, onDownloadProgress} = _config; + let onCanceled; + let uploadThrottled, downloadThrottled; + let flushUpload, flushDownload; + + function done() { + flushUpload && flushUpload(); // flush events + flushDownload && flushDownload(); // flush events + + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + + _config.signal && _config.signal.removeEventListener('abort', onCanceled); + } + + let request = new XMLHttpRequest(); + + request.open(_config.method.toUpperCase(), _config.url, true); + + // Set the request timeout in MS + request.timeout = _config.timeout; + + function onloadend() { + if (!request) { + return; + } + // Prepare the response + const responseHeaders = core_AxiosHeaders.from( + 'getAllResponseHeaders' in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === 'text' || responseType === 'json' ? + request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config, + request + }; + + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + + // Clean up request + request = null; + } + + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(new core_AxiosError('Request aborted', core_AxiosError.ECONNABORTED, config, request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(new core_AxiosError('Network Error', core_AxiosError.ERR_NETWORK, config, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded'; + const transitional = _config.transitional || defaults_transitional; + if (_config.timeoutErrorMessage) { + timeoutErrorMessage = _config.timeoutErrorMessage; + } + reject(new core_AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? core_AxiosError.ETIMEDOUT : core_AxiosError.ECONNABORTED, + config, + request)); + + // Clean up request + request = null; + }; + + // Remove Content-Type if data is undefined + requestData === undefined && requestHeaders.setContentType(null); + + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + + // Add withCredentials to request if needed + if (!utils.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; + } + + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = _config.responseType; + } + + // Handle progress if needed + if (onDownloadProgress) { + ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true)); + request.addEventListener('progress', downloadThrottled); + } + + // Not all browsers support upload events + if (onUploadProgress && request.upload) { + ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress)); + + request.upload.addEventListener('progress', uploadThrottled); + + request.upload.addEventListener('loadend', flushUpload); + } + + if (_config.cancelToken || _config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = cancel => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new cancel_CanceledError(null, config, request) : cancel); + request.abort(); + request = null; + }; + + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled); + } + } + + const protocol = parseProtocol(_config.url); + + if (protocol && platform.protocols.indexOf(protocol) === -1) { + reject(new core_AxiosError('Unsupported protocol ' + protocol + ':', core_AxiosError.ERR_BAD_REQUEST, config)); + return; + } + + + // Send the request + request.send(requestData || null); + }); +}); + +;// ./node_modules/axios/lib/helpers/composeSignals.js + + + + +const composeSignals = (signals, timeout) => { + const {length} = (signals = signals ? signals.filter(Boolean) : []); + + if (timeout || length) { + let controller = new AbortController(); + + let aborted; + + const onabort = function (reason) { + if (!aborted) { + aborted = true; + unsubscribe(); + const err = reason instanceof Error ? reason : this.reason; + controller.abort(err instanceof core_AxiosError ? err : new cancel_CanceledError(err instanceof Error ? err.message : err)); + } + } + + let timer = timeout && setTimeout(() => { + timer = null; + onabort(new core_AxiosError(`timeout ${timeout} of ms exceeded`, core_AxiosError.ETIMEDOUT)) + }, timeout) + + const unsubscribe = () => { + if (signals) { + timer && clearTimeout(timer); + timer = null; + signals.forEach(signal => { + signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort); + }); + signals = null; + } + } + + signals.forEach((signal) => signal.addEventListener('abort', onabort)); + + const {signal} = controller; + + signal.unsubscribe = () => utils.asap(unsubscribe); + + return signal; + } +} + +/* harmony default export */ const helpers_composeSignals = (composeSignals); + +;// ./node_modules/axios/lib/helpers/trackStream.js + +const streamChunk = function* (chunk, chunkSize) { + let len = chunk.byteLength; + + if (!chunkSize || len < chunkSize) { + yield chunk; + return; + } + + let pos = 0; + let end; + + while (pos < len) { + end = pos + chunkSize; + yield chunk.slice(pos, end); + pos = end; + } +} + +const readBytes = async function* (iterable, chunkSize) { + for await (const chunk of readStream(iterable)) { + yield* streamChunk(chunk, chunkSize); + } +} + +const readStream = async function* (stream) { + if (stream[Symbol.asyncIterator]) { + yield* stream; + return; + } + + const reader = stream.getReader(); + try { + for (;;) { + const {done, value} = await reader.read(); + if (done) { + break; + } + yield value; + } + } finally { + await reader.cancel(); + } +} + +const trackStream = (stream, chunkSize, onProgress, onFinish) => { + const iterator = readBytes(stream, chunkSize); + + let bytes = 0; + let done; + let _onFinish = (e) => { + if (!done) { + done = true; + onFinish && onFinish(e); + } + } + + return new ReadableStream({ + async pull(controller) { + try { + const {done, value} = await iterator.next(); + + if (done) { + _onFinish(); + controller.close(); + return; + } + + let len = value.byteLength; + if (onProgress) { + let loadedBytes = bytes += len; + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); + } catch (err) { + _onFinish(err); + throw err; + } + }, + cancel(reason) { + _onFinish(reason); + return iterator.return(); + } + }, { + highWaterMark: 2 + }) +} + +;// ./node_modules/axios/lib/adapters/fetch.js + + + + + + + + + + +const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function'; +const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function'; + +// used only inside the fetch adapter +const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? + ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : + async (str) => new Uint8Array(await new Response(str).arrayBuffer()) +); + +const test = (fn, ...args) => { + try { + return !!fn(...args); + } catch (e) { + return false + } +} + +const supportsRequestStream = isReadableStreamSupported && test(() => { + let duplexAccessed = false; + + const hasContentType = new Request(platform.origin, { + body: new ReadableStream(), + method: 'POST', + get duplex() { + duplexAccessed = true; + return 'half'; + }, + }).headers.has('Content-Type'); + + return duplexAccessed && !hasContentType; +}); + +const DEFAULT_CHUNK_SIZE = 64 * 1024; + +const supportsResponseStream = isReadableStreamSupported && + test(() => utils.isReadableStream(new Response('').body)); + + +const resolvers = { + stream: supportsResponseStream && ((res) => res.body) +}; + +isFetchSupported && (((res) => { + ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => { + !resolvers[type] && (resolvers[type] = utils.isFunction(res[type]) ? (res) => res[type]() : + (_, config) => { + throw new core_AxiosError(`Response type '${type}' is not supported`, core_AxiosError.ERR_NOT_SUPPORT, config); + }) + }); +})(new Response)); + +const getBodyLength = async (body) => { + if (body == null) { + return 0; + } + + if(utils.isBlob(body)) { + return body.size; + } + + if(utils.isSpecCompliantForm(body)) { + const _request = new Request(platform.origin, { + method: 'POST', + body, + }); + return (await _request.arrayBuffer()).byteLength; + } + + if(utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) { + return body.byteLength; + } + + if(utils.isURLSearchParams(body)) { + body = body + ''; + } + + if(utils.isString(body)) { + return (await encodeText(body)).byteLength; + } +} + +const resolveBodyLength = async (headers, body) => { + const length = utils.toFiniteNumber(headers.getContentLength()); + + return length == null ? getBodyLength(body) : length; +} + +/* harmony default export */ const adapters_fetch = (isFetchSupported && (async (config) => { + let { + url, + method, + data, + signal, + cancelToken, + timeout, + onDownloadProgress, + onUploadProgress, + responseType, + headers, + withCredentials = 'same-origin', + fetchOptions + } = resolveConfig(config); + + responseType = responseType ? (responseType + '').toLowerCase() : 'text'; + + let composedSignal = helpers_composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + + let request; + + const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { + composedSignal.unsubscribe(); + }); + + let requestContentLength; + + try { + if ( + onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && + (requestContentLength = await resolveBodyLength(headers, data)) !== 0 + ) { + let _request = new Request(url, { + method: 'POST', + body: data, + duplex: "half" + }); + + let contentTypeHeader; + + if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { + headers.setContentType(contentTypeHeader) + } + + if (_request.body) { + const [onProgress, flush] = progressEventDecorator( + requestContentLength, + progressEventReducer(asyncDecorator(onUploadProgress)) + ); + + data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); + } + } + + if (!utils.isString(withCredentials)) { + withCredentials = withCredentials ? 'include' : 'omit'; + } + + // Cloudflare Workers throws when credentials are defined + // see https://github.com/cloudflare/workerd/issues/902 + const isCredentialsSupported = "credentials" in Request.prototype; + request = new Request(url, { + ...fetchOptions, + signal: composedSignal, + method: method.toUpperCase(), + headers: headers.normalize().toJSON(), + body: data, + duplex: "half", + credentials: isCredentialsSupported ? withCredentials : undefined + }); + + let response = await fetch(request); + + const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); + + if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) { + const options = {}; + + ['status', 'statusText', 'headers'].forEach(prop => { + options[prop] = response[prop]; + }); + + const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length')); + + const [onProgress, flush] = onDownloadProgress && progressEventDecorator( + responseContentLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true) + ) || []; + + response = new Response( + trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { + flush && flush(); + unsubscribe && unsubscribe(); + }), + options + ); + } + + responseType = responseType || 'text'; + + let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config); + + !isStreamResponse && unsubscribe && unsubscribe(); + + return await new Promise((resolve, reject) => { + settle(resolve, reject, { + data: responseData, + headers: core_AxiosHeaders.from(response.headers), + status: response.status, + statusText: response.statusText, + config, + request + }) + }) + } catch (err) { + unsubscribe && unsubscribe(); + + if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) { + throw Object.assign( + new core_AxiosError('Network Error', core_AxiosError.ERR_NETWORK, config, request), + { + cause: err.cause || err + } + ) + } + + throw core_AxiosError.from(err, err && err.code, config, request); + } +})); + + + +;// ./node_modules/axios/lib/adapters/adapters.js + + + + + + +const knownAdapters = { + http: helpers_null, + xhr: xhr, + fetch: adapters_fetch +} + +utils.forEach(knownAdapters, (fn, value) => { + if (fn) { + try { + Object.defineProperty(fn, 'name', {value}); + } catch (e) { + // eslint-disable-next-line no-empty + } + Object.defineProperty(fn, 'adapterName', {value}); + } +}); + +const renderReason = (reason) => `- ${reason}`; + +const isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false; + +/* harmony default export */ const adapters = ({ + getAdapter: (adapters) => { + adapters = utils.isArray(adapters) ? adapters : [adapters]; + + const {length} = adapters; + let nameOrAdapter; + let adapter; + + const rejectedReasons = {}; + + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters[i]; + let id; + + adapter = nameOrAdapter; + + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + + if (adapter === undefined) { + throw new core_AxiosError(`Unknown adapter '${id}'`); + } + } + + if (adapter) { + break; + } + + rejectedReasons[id || '#' + i] = adapter; + } + + if (!adapter) { + + const reasons = Object.entries(rejectedReasons) + .map(([id, state]) => `adapter ${id} ` + + (state === false ? 'is not supported by the environment' : 'is not available in the build') + ); + + let s = length ? + (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : + 'as no adapter specified'; + + throw new core_AxiosError( + `There is no suitable adapter to dispatch the request ` + s, + 'ERR_NOT_SUPPORT' + ); + } + + return adapter; + }, + adapters: knownAdapters +}); + +;// ./node_modules/axios/lib/core/dispatchRequest.js + + + + + + + + + +/** + * Throws a `CanceledError` if cancellation has been requested. + * + * @param {Object} config The config that is to be used for the request + * + * @returns {void} + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + + if (config.signal && config.signal.aborted) { + throw new cancel_CanceledError(null, config); + } +} + +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * + * @returns {Promise} The Promise to be fulfilled + */ +function dispatchRequest(config) { + throwIfCancellationRequested(config); + + config.headers = core_AxiosHeaders.from(config.headers); + + // Transform request data + config.data = transformData.call( + config, + config.transformRequest + ); + + if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { + config.headers.setContentType('application/x-www-form-urlencoded', false); + } + + const adapter = adapters.getAdapter(config.adapter || lib_defaults.adapter); + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData.call( + config, + config.transformResponse, + response + ); + + response.headers = core_AxiosHeaders.from(response.headers); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + config.transformResponse, + reason.response + ); + reason.response.headers = core_AxiosHeaders.from(reason.response.headers); + } + } + + return Promise.reject(reason); + }); +} + +;// ./node_modules/axios/lib/env/data.js +const VERSION = "1.7.9"; +;// ./node_modules/axios/lib/helpers/validator.js + + + + + +const validators = {}; + +// eslint-disable-next-line func-names +['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => { + validators[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; +}); + +const deprecatedWarnings = {}; + +/** + * Transitional option validator + * + * @param {function|boolean?} validator - set to false if the transitional option has been removed + * @param {string?} version - deprecated version / removed since version + * @param {string?} message - some message with additional info + * + * @returns {function} + */ +validators.transitional = function transitional(validator, version, message) { + function formatMessage(opt, desc) { + return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + } + + // eslint-disable-next-line func-names + return (value, opt, opts) => { + if (validator === false) { + throw new core_AxiosError( + formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), + core_AxiosError.ERR_DEPRECATED + ); + } + + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); + } + + return validator ? validator(value, opt, opts) : true; + }; +}; + +validators.spelling = function spelling(correctSpelling) { + return (value, opt) => { + // eslint-disable-next-line no-console + console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); + return true; + } +}; + +/** + * Assert object's properties type + * + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown + * + * @returns {object} + */ + +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== 'object') { + throw new core_AxiosError('options must be an object', core_AxiosError.ERR_BAD_OPTION_VALUE); + } + const keys = Object.keys(options); + let i = keys.length; + while (i-- > 0) { + const opt = keys[i]; + const validator = schema[opt]; + if (validator) { + const value = options[opt]; + const result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new core_AxiosError('option ' + opt + ' must be ' + result, core_AxiosError.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new core_AxiosError('Unknown option ' + opt, core_AxiosError.ERR_BAD_OPTION); + } + } +} + +/* harmony default export */ const validator = ({ + assertOptions, + validators +}); + +;// ./node_modules/axios/lib/core/Axios.js + + + + + + + + + + + +const Axios_validators = validator.validators; + +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + * + * @return {Axios} A new instance of Axios + */ +class Axios { + constructor(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new core_InterceptorManager(), + response: new core_InterceptorManager() + }; + } + + /** + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled + */ + async request(configOrUrl, config) { + try { + return await this._request(configOrUrl, config); + } catch (err) { + if (err instanceof Error) { + let dummy = {}; + + Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error()); + + // slice off the Error: ... line + const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : ''; + try { + if (!err.stack) { + err.stack = stack; + // match without the 2 top stack lines + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) { + err.stack += '\n' + stack + } + } catch (e) { + // ignore the case where "stack" is an un-writable property + } + } + + throw err; + } + } + + _request(configOrUrl, config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof configOrUrl === 'string') { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } + + config = mergeConfig(this.defaults, config); + + const {transitional, paramsSerializer, headers} = config; + + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean), + forcedJSONParsing: Axios_validators.transitional(Axios_validators.boolean), + clarifyTimeoutError: Axios_validators.transitional(Axios_validators.boolean) + }, false); + } + + if (paramsSerializer != null) { + if (utils.isFunction(paramsSerializer)) { + config.paramsSerializer = { + serialize: paramsSerializer + } + } else { + validator.assertOptions(paramsSerializer, { + encode: Axios_validators.function, + serialize: Axios_validators.function + }, true); + } + } + + validator.assertOptions(config, { + baseUrl: Axios_validators.spelling('baseURL'), + withXsrfToken: Axios_validators.spelling('withXSRFToken') + }, true); + + // Set config.method + config.method = (config.method || this.defaults.method || 'get').toLowerCase(); + + // Flatten headers + let contextHeaders = headers && utils.merge( + headers.common, + headers[config.method] + ); + + headers && utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + (method) => { + delete headers[method]; + } + ); + + config.headers = core_AxiosHeaders.concat(contextHeaders, headers); + + // filter out skipped interceptors + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + + let promise; + let i = 0; + let len; + + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), undefined]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + + promise = Promise.resolve(config); + + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + + return promise; + } + + len = requestInterceptorChain.length; + + let newConfig = config; + + i = 0; + + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + + i = 0; + len = responseInterceptorChain.length; + + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + + return promise; + } + + getUri(config) { + config = mergeConfig(this.defaults, config); + const fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); + } +} + +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method, + url, + data: (config || {}).data + })); + }; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig(config || {}, { + method, + headers: isForm ? { + 'Content-Type': 'multipart/form-data' + } : {}, + url, + data + })); + }; + } + + Axios.prototype[method] = generateHTTPMethod(); + + Axios.prototype[method + 'Form'] = generateHTTPMethod(true); +}); + +/* harmony default export */ const core_Axios = (Axios); + +;// ./node_modules/axios/lib/cancel/CancelToken.js + + + + +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @param {Function} executor The executor function. + * + * @returns {CancelToken} + */ +class CancelToken { + constructor(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + let resolvePromise; + + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + const token = this; + + // eslint-disable-next-line func-names + this.promise.then(cancel => { + if (!token._listeners) return; + + let i = token._listeners.length; + + while (i-- > 0) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + + // eslint-disable-next-line func-names + this.promise.then = onfulfilled => { + let _resolve; + // eslint-disable-next-line func-names + const promise = new Promise(resolve => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + + return promise; + }; + + executor(function cancel(message, config, request) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new cancel_CanceledError(message, config, request); + resolvePromise(token.reason); + }); + } + + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } + + /** + * Subscribe to the cancel signal + */ + + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } + + /** + * Unsubscribe from the cancel signal + */ + + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } + } + + toAbortSignal() { + const controller = new AbortController(); + + const abort = (err) => { + controller.abort(err); + }; + + this.subscribe(abort); + + controller.signal.unsubscribe = () => this.unsubscribe(abort); + + return controller.signal; + } + + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + static source() { + let cancel; + const token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token, + cancel + }; + } +} + +/* harmony default export */ const cancel_CancelToken = (CancelToken); + +;// ./node_modules/axios/lib/helpers/spread.js + + +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * + * @returns {Function} + */ +function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +} + +;// ./node_modules/axios/lib/helpers/isAxiosError.js + + + + +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +function isAxiosError(payload) { + return utils.isObject(payload) && (payload.isAxiosError === true); +} + +;// ./node_modules/axios/lib/helpers/HttpStatusCode.js +const HttpStatusCode = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511, +}; + +Object.entries(HttpStatusCode).forEach(([key, value]) => { + HttpStatusCode[value] = key; +}); + +/* harmony default export */ const helpers_HttpStatusCode = (HttpStatusCode); + +;// ./node_modules/axios/lib/axios.js + + + + + + + + + + + + + + + + + + + + +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * + * @returns {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + const context = new core_Axios(defaultConfig); + const instance = bind(core_Axios.prototype.request, context); + + // Copy axios.prototype to instance + utils.extend(instance, core_Axios.prototype, context, {allOwnKeys: true}); + + // Copy context to instance + utils.extend(instance, context, null, {allOwnKeys: true}); + + // Factory for creating new instances + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; + + return instance; +} + +// Create the default instance to be exported +const axios = createInstance(lib_defaults); + +// Expose Axios class to allow class inheritance +axios.Axios = core_Axios; + +// Expose Cancel & CancelToken +axios.CanceledError = cancel_CanceledError; +axios.CancelToken = cancel_CancelToken; +axios.isCancel = isCancel; +axios.VERSION = VERSION; +axios.toFormData = helpers_toFormData; + +// Expose AxiosError class +axios.AxiosError = core_AxiosError; + +// alias for CanceledError for backward compatibility +axios.Cancel = axios.CanceledError; + +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; + +axios.spread = spread; + +// Expose isAxiosError +axios.isAxiosError = isAxiosError; + +// Expose mergeConfig +axios.mergeConfig = mergeConfig; + +axios.AxiosHeaders = core_AxiosHeaders; + +axios.formToJSON = thing => helpers_formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing); + +axios.getAdapter = adapters.getAdapter; + +axios.HttpStatusCode = helpers_HttpStatusCode; + +axios.default = axios; + +// this module should only have a default export +/* harmony default export */ const lib_axios = (axios); + +;// ./src/http-client/axios-client.ts + +var axiosClient = lib_axios; +var create = lib_axios.create; + +/***/ }), + +/***/ 9983: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + vt: () => (/* binding */ create), + ok: () => (/* binding */ httpClient) +}); + +// UNUSED EXPORTS: CancelToken + +;// ./src/http-client/types.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var CancelToken = function () { + function CancelToken(executor) { + var _this = this; + _classCallCheck(this, CancelToken); + var resolvePromise; + this.promise = new Promise(function (resolve) { + resolvePromise = resolve; + }); + executor(function (reason) { + _this.reason = reason; + resolvePromise(); + }); + } + return _createClass(CancelToken, [{ + key: "throwIfRequested", + value: function throwIfRequested() { + if (this.reason) { + throw new Error(this.reason); + } + } + }]); +}(); +;// ./src/http-client/index.ts +var httpClient; +var create; +if (true) { + var axiosModule = __webpack_require__(6121); + httpClient = axiosModule.axiosClient; + create = axiosModule.create; +} else { var fetchModule; } + + + +/***/ }), + +/***/ 4356: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ AccountRequiresMemoError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.Cu), +/* harmony export */ BadRequestError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.v7), +/* harmony export */ BadResponseError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.nS), +/* harmony export */ Config: () => (/* reexport safe */ _config__WEBPACK_IMPORTED_MODULE_1__.T), +/* harmony export */ Federation: () => (/* reexport module object */ _federation__WEBPACK_IMPORTED_MODULE_4__), +/* harmony export */ Friendbot: () => (/* reexport module object */ _friendbot__WEBPACK_IMPORTED_MODULE_6__), +/* harmony export */ Horizon: () => (/* reexport module object */ _horizon__WEBPACK_IMPORTED_MODULE_7__), +/* harmony export */ NetworkError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.Dr), +/* harmony export */ NotFoundError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.m_), +/* harmony export */ StellarToml: () => (/* reexport module object */ _stellartoml__WEBPACK_IMPORTED_MODULE_3__), +/* harmony export */ Utils: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_2__.A), +/* harmony export */ WebAuth: () => (/* reexport module object */ _webauth__WEBPACK_IMPORTED_MODULE_5__), +/* harmony export */ contract: () => (/* reexport module object */ _contract__WEBPACK_IMPORTED_MODULE_9__), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ rpc: () => (/* reexport module object */ _rpc__WEBPACK_IMPORTED_MODULE_8__) +/* harmony export */ }); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5976); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8732); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3121); +/* harmony import */ var _stellartoml__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3898); +/* harmony import */ var _federation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7600); +/* harmony import */ var _webauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(5479); +/* harmony import */ var _friendbot__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(8242); +/* harmony import */ var _horizon__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(8733); +/* harmony import */ var _rpc__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(3496); +/* harmony import */ var _contract__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(6299); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__); +/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {}; +/* harmony reexport (unknown) */ for(const __WEBPACK_IMPORT_KEY__ in _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__) if(["default","Config","Utils","StellarToml","Federation","WebAuth","Friendbot","Horizon","rpc","contract","AccountRequiresMemoError","BadRequestError","BadResponseError","NetworkError","NotFoundError"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = () => _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__[__WEBPACK_IMPORT_KEY__] +/* harmony reexport (unknown) */ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__); +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + + + + + + + + + + + + + + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (module.exports); +if (typeof __webpack_require__.g.__USE_AXIOS__ === 'undefined') { + __webpack_require__.g.__USE_AXIOS__ = true; +} +if (typeof __webpack_require__.g.__USE_EVENTSOURCE__ === 'undefined') { + __webpack_require__.g.__USE_EVENTSOURCE__ = false; +} + +/***/ }), + +/***/ 4076: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ j: () => (/* binding */ Api) +/* harmony export */ }); +var Api; +(function (_Api) { + var GetTransactionStatus = function (GetTransactionStatus) { + GetTransactionStatus["SUCCESS"] = "SUCCESS"; + GetTransactionStatus["NOT_FOUND"] = "NOT_FOUND"; + GetTransactionStatus["FAILED"] = "FAILED"; + return GetTransactionStatus; + }({}); + _Api.GetTransactionStatus = GetTransactionStatus; + function isSimulationError(sim) { + return 'error' in sim; + } + _Api.isSimulationError = isSimulationError; + function isSimulationSuccess(sim) { + return 'transactionData' in sim; + } + _Api.isSimulationSuccess = isSimulationSuccess; + function isSimulationRestore(sim) { + return isSimulationSuccess(sim) && 'restorePreamble' in sim && !!sim.restorePreamble.transactionData; + } + _Api.isSimulationRestore = isSimulationRestore; + function isSimulationRaw(sim) { + return !sim._parsed; + } + _Api.isSimulationRaw = isSimulationRaw; +})(Api || (Api = {})); + +/***/ }), + +/***/ 3496: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Api: () => (/* reexport */ api/* Api */.j), + AxiosClient: () => (/* reexport */ axios), + BasicSleepStrategy: () => (/* reexport */ BasicSleepStrategy), + Durability: () => (/* reexport */ Durability), + LinearSleepStrategy: () => (/* reexport */ LinearSleepStrategy), + Server: () => (/* reexport */ RpcServer), + assembleTransaction: () => (/* reexport */ transaction/* assembleTransaction */.X), + "default": () => (/* binding */ rpc), + parseRawEvents: () => (/* reexport */ parsers/* parseRawEvents */.fG), + parseRawSimulation: () => (/* reexport */ parsers/* parseRawSimulation */.jr) +}); + +// EXTERNAL MODULE: ./src/rpc/api.ts +var api = __webpack_require__(4076); +// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js +var URI = __webpack_require__(4193); +var URI_default = /*#__PURE__*/__webpack_require__.n(URI); +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./src/http-client/index.ts + 1 modules +var http_client = __webpack_require__(9983); +;// ./src/rpc/axios.ts + +var version = "13.1.0"; +var AxiosClient = (0,http_client/* create */.vt)({ + headers: { + 'X-Client-Name': 'js-soroban-client', + 'X-Client-Version': version + } +}); +/* harmony default export */ const axios = (AxiosClient); +;// ./src/rpc/jsonrpc.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + +function jsonrpc_hasOwnProperty(obj, prop) { + return obj.hasOwnProperty(prop); +} +function postObject(_x, _x2) { + return _postObject.apply(this, arguments); +} +function _postObject() { + _postObject = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(url, method) { + var param, + response, + _response$data, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + param = _args.length > 2 && _args[2] !== undefined ? _args[2] : null; + _context.next = 3; + return axios.post(url, { + jsonrpc: "2.0", + id: 1, + method: method, + params: param + }); + case 3: + response = _context.sent; + if (!jsonrpc_hasOwnProperty(response.data, "error")) { + _context.next = 8; + break; + } + throw response.data.error; + case 8: + return _context.abrupt("return", (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.result); + case 9: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _postObject.apply(this, arguments); +} +// EXTERNAL MODULE: ./src/rpc/transaction.ts +var transaction = __webpack_require__(8680); +// EXTERNAL MODULE: ./src/rpc/parsers.ts +var parsers = __webpack_require__(784); +// EXTERNAL MODULE: ./src/utils.ts +var utils = __webpack_require__(3121); +;// ./src/rpc/server.ts +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +function server_typeof(o) { "@babel/helpers - typeof"; return server_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, server_typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function server_regeneratorRuntime() { "use strict"; server_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == server_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(server_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function server_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function server_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == server_typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != server_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != server_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + + + +var SUBMIT_TRANSACTION_TIMEOUT = (/* unused pure expression or super */ null && (60 * 1000)); +var Durability = function (Durability) { + Durability["Temporary"] = "temporary"; + Durability["Persistent"] = "persistent"; + return Durability; +}({}); +var DEFAULT_GET_TRANSACTION_TIMEOUT = 30; +var BasicSleepStrategy = function BasicSleepStrategy(_iter) { + return 1000; +}; +var LinearSleepStrategy = function LinearSleepStrategy(iter) { + return 1000 * iter; +}; +function findCreatedAccountSequenceInTransactionMeta(meta) { + var _operations$flatMap$f; + var operations = []; + switch (meta.switch()) { + case 0: + operations = meta.operations(); + break; + case 1: + case 2: + case 3: + operations = meta.value().operations(); + break; + default: + throw new Error('Unexpected transaction meta switch value'); + } + var sequenceNumber = (_operations$flatMap$f = operations.flatMap(function (op) { + return op.changes(); + }).find(function (c) { + return c.switch() === lib.xdr.LedgerEntryChangeType.ledgerEntryCreated() && c.created().data().switch() === lib.xdr.LedgerEntryType.account(); + })) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.created()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.data()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.account()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.seqNum()) === null || _operations$flatMap$f === void 0 ? void 0 : _operations$flatMap$f.toString(); + if (sequenceNumber) { + return sequenceNumber; + } + throw new Error('No account created in transaction'); +} +var RpcServer = function () { + function RpcServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, RpcServer); + this.serverURL = URI_default()(serverURL); + if (opts.headers && Object.keys(opts.headers).length !== 0) { + axios.interceptors.request.use(function (config) { + config.headers = Object.assign(config.headers, opts.headers); + return config; + }); + } + if (this.serverURL.protocol() !== 'https' && !opts.allowHttp) { + throw new Error("Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set"); + } + } + return _createClass(RpcServer, [{ + key: "getAccount", + value: (function () { + var _getAccount = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee(address) { + var ledgerKey, resp, accountEntry; + return server_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + ledgerKey = lib.xdr.LedgerKey.account(new lib.xdr.LedgerKeyAccount({ + accountId: lib.Keypair.fromPublicKey(address).xdrPublicKey() + })); + _context.next = 3; + return this.getLedgerEntries(ledgerKey); + case 3: + resp = _context.sent; + if (!(resp.entries.length === 0)) { + _context.next = 6; + break; + } + return _context.abrupt("return", Promise.reject({ + code: 404, + message: "Account not found: ".concat(address) + })); + case 6: + accountEntry = resp.entries[0].val.account(); + return _context.abrupt("return", new lib.Account(address, accountEntry.seqNum().toString())); + case 8: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function getAccount(_x) { + return _getAccount.apply(this, arguments); + } + return getAccount; + }()) + }, { + key: "getHealth", + value: (function () { + var _getHealth = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee2() { + return server_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", postObject(this.serverURL.toString(), 'getHealth')); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function getHealth() { + return _getHealth.apply(this, arguments); + } + return getHealth; + }()) + }, { + key: "getContractData", + value: (function () { + var _getContractData = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee3(contract, key) { + var durability, + scAddress, + xdrDurability, + contractKey, + _args3 = arguments; + return server_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + durability = _args3.length > 2 && _args3[2] !== undefined ? _args3[2] : Durability.Persistent; + if (!(typeof contract === 'string')) { + _context3.next = 5; + break; + } + scAddress = new lib.Contract(contract).address().toScAddress(); + _context3.next = 14; + break; + case 5: + if (!(contract instanceof lib.Address)) { + _context3.next = 9; + break; + } + scAddress = contract.toScAddress(); + _context3.next = 14; + break; + case 9: + if (!(contract instanceof lib.Contract)) { + _context3.next = 13; + break; + } + scAddress = contract.address().toScAddress(); + _context3.next = 14; + break; + case 13: + throw new TypeError("unknown contract type: ".concat(contract)); + case 14: + _context3.t0 = durability; + _context3.next = _context3.t0 === Durability.Temporary ? 17 : _context3.t0 === Durability.Persistent ? 19 : 21; + break; + case 17: + xdrDurability = lib.xdr.ContractDataDurability.temporary(); + return _context3.abrupt("break", 22); + case 19: + xdrDurability = lib.xdr.ContractDataDurability.persistent(); + return _context3.abrupt("break", 22); + case 21: + throw new TypeError("invalid durability: ".concat(durability)); + case 22: + contractKey = lib.xdr.LedgerKey.contractData(new lib.xdr.LedgerKeyContractData({ + key: key, + contract: scAddress, + durability: xdrDurability + })); + return _context3.abrupt("return", this.getLedgerEntries(contractKey).then(function (r) { + if (r.entries.length === 0) { + return Promise.reject({ + code: 404, + message: "Contract data not found. Contract: ".concat(lib.Address.fromScAddress(scAddress).toString(), ", Key: ").concat(key.toXDR('base64'), ", Durability: ").concat(durability) + }); + } + return r.entries[0]; + })); + case 24: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function getContractData(_x2, _x3) { + return _getContractData.apply(this, arguments); + } + return getContractData; + }()) + }, { + key: "getContractWasmByContractId", + value: (function () { + var _getContractWasmByContractId = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee4(contractId) { + var _response$entries$; + var contractLedgerKey, response, wasmHash; + return server_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + contractLedgerKey = new lib.Contract(contractId).getFootprint(); + _context4.next = 3; + return this.getLedgerEntries(contractLedgerKey); + case 3: + response = _context4.sent; + if (!(!response.entries.length || !((_response$entries$ = response.entries[0]) !== null && _response$entries$ !== void 0 && _response$entries$.val))) { + _context4.next = 6; + break; + } + return _context4.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract hash from server" + })); + case 6: + wasmHash = response.entries[0].val.contractData().val().instance().executable().wasmHash(); + return _context4.abrupt("return", this.getContractWasmByHash(wasmHash)); + case 8: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function getContractWasmByContractId(_x4) { + return _getContractWasmByContractId.apply(this, arguments); + } + return getContractWasmByContractId; + }()) + }, { + key: "getContractWasmByHash", + value: (function () { + var _getContractWasmByHash = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee5(wasmHash) { + var _responseWasm$entries; + var format, + wasmHashBuffer, + ledgerKeyWasmHash, + responseWasm, + wasmBuffer, + _args5 = arguments; + return server_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + format = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : undefined; + wasmHashBuffer = typeof wasmHash === "string" ? Buffer.from(wasmHash, format) : wasmHash; + ledgerKeyWasmHash = lib.xdr.LedgerKey.contractCode(new lib.xdr.LedgerKeyContractCode({ + hash: wasmHashBuffer + })); + _context5.next = 5; + return this.getLedgerEntries(ledgerKeyWasmHash); + case 5: + responseWasm = _context5.sent; + if (!(!responseWasm.entries.length || !((_responseWasm$entries = responseWasm.entries[0]) !== null && _responseWasm$entries !== void 0 && _responseWasm$entries.val))) { + _context5.next = 8; + break; + } + return _context5.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract wasm from server" + })); + case 8: + wasmBuffer = responseWasm.entries[0].val.contractCode().code(); + return _context5.abrupt("return", wasmBuffer); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function getContractWasmByHash(_x5) { + return _getContractWasmByHash.apply(this, arguments); + } + return getContractWasmByHash; + }()) + }, { + key: "getLedgerEntries", + value: (function () { + var _getLedgerEntries2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee6() { + var _args6 = arguments; + return server_regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + return _context6.abrupt("return", this._getLedgerEntries.apply(this, _args6).then(parsers/* parseRawLedgerEntries */.$D)); + case 1: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function getLedgerEntries() { + return _getLedgerEntries2.apply(this, arguments); + } + return getLedgerEntries; + }()) + }, { + key: "_getLedgerEntries", + value: function () { + var _getLedgerEntries3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee7() { + var _len, + keys, + _key, + _args7 = arguments; + return server_regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + for (_len = _args7.length, keys = new Array(_len), _key = 0; _key < _len; _key++) { + keys[_key] = _args7[_key]; + } + return _context7.abrupt("return", postObject(this.serverURL.toString(), 'getLedgerEntries', { + keys: keys.map(function (k) { + return k.toXDR('base64'); + }) + })); + case 2: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function _getLedgerEntries() { + return _getLedgerEntries3.apply(this, arguments); + } + return _getLedgerEntries; + }() + }, { + key: "pollTransaction", + value: (function () { + var _pollTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee8(hash, opts) { + var _opts$attempts, _opts$attempts2; + var maxAttempts, foundInfo, attempt, _opts$sleepStrategy; + return server_regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + maxAttempts = ((_opts$attempts = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts !== void 0 ? _opts$attempts : 0) < 1 ? DEFAULT_GET_TRANSACTION_TIMEOUT : (_opts$attempts2 = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts2 !== void 0 ? _opts$attempts2 : DEFAULT_GET_TRANSACTION_TIMEOUT; + attempt = 1; + case 2: + if (!(attempt < maxAttempts)) { + _context8.next = 13; + break; + } + _context8.next = 5; + return this.getTransaction(hash); + case 5: + foundInfo = _context8.sent; + if (!(foundInfo.status !== api/* Api */.j.GetTransactionStatus.NOT_FOUND)) { + _context8.next = 8; + break; + } + return _context8.abrupt("return", foundInfo); + case 8: + _context8.next = 10; + return utils/* Utils */.A.sleep(((_opts$sleepStrategy = opts === null || opts === void 0 ? void 0 : opts.sleepStrategy) !== null && _opts$sleepStrategy !== void 0 ? _opts$sleepStrategy : BasicSleepStrategy)(attempt)); + case 10: + attempt++; + _context8.next = 2; + break; + case 13: + return _context8.abrupt("return", foundInfo); + case 14: + case "end": + return _context8.stop(); + } + }, _callee8, this); + })); + function pollTransaction(_x6, _x7) { + return _pollTransaction.apply(this, arguments); + } + return pollTransaction; + }()) + }, { + key: "getTransaction", + value: (function () { + var _getTransaction2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee9(hash) { + return server_regeneratorRuntime().wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + return _context9.abrupt("return", this._getTransaction(hash).then(function (raw) { + var foundInfo = {}; + if (raw.status !== api/* Api */.j.GetTransactionStatus.NOT_FOUND) { + Object.assign(foundInfo, (0,parsers/* parseTransactionInfo */.WC)(raw)); + } + var result = _objectSpread({ + status: raw.status, + txHash: hash, + latestLedger: raw.latestLedger, + latestLedgerCloseTime: raw.latestLedgerCloseTime, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTime: raw.oldestLedgerCloseTime + }, foundInfo); + return result; + })); + case 1: + case "end": + return _context9.stop(); + } + }, _callee9, this); + })); + function getTransaction(_x8) { + return _getTransaction2.apply(this, arguments); + } + return getTransaction; + }()) + }, { + key: "_getTransaction", + value: function () { + var _getTransaction3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee10(hash) { + return server_regeneratorRuntime().wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + return _context10.abrupt("return", postObject(this.serverURL.toString(), 'getTransaction', { + hash: hash + })); + case 1: + case "end": + return _context10.stop(); + } + }, _callee10, this); + })); + function _getTransaction(_x9) { + return _getTransaction3.apply(this, arguments); + } + return _getTransaction; + }() + }, { + key: "getTransactions", + value: (function () { + var _getTransactions2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee11(request) { + return server_regeneratorRuntime().wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + return _context11.abrupt("return", this._getTransactions(request).then(function (raw) { + var result = { + transactions: raw.transactions.map(parsers/* parseRawTransactions */.tR), + latestLedger: raw.latestLedger, + latestLedgerCloseTimestamp: raw.latestLedgerCloseTimestamp, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTimestamp: raw.oldestLedgerCloseTimestamp, + cursor: raw.cursor + }; + return result; + })); + case 1: + case "end": + return _context11.stop(); + } + }, _callee11, this); + })); + function getTransactions(_x10) { + return _getTransactions2.apply(this, arguments); + } + return getTransactions; + }()) + }, { + key: "_getTransactions", + value: function () { + var _getTransactions3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee12(request) { + return server_regeneratorRuntime().wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + return _context12.abrupt("return", postObject(this.serverURL.toString(), 'getTransactions', request)); + case 1: + case "end": + return _context12.stop(); + } + }, _callee12, this); + })); + function _getTransactions(_x11) { + return _getTransactions3.apply(this, arguments); + } + return _getTransactions; + }() + }, { + key: "getEvents", + value: (function () { + var _getEvents2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee13(request) { + return server_regeneratorRuntime().wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + return _context13.abrupt("return", this._getEvents(request).then(parsers/* parseRawEvents */.fG)); + case 1: + case "end": + return _context13.stop(); + } + }, _callee13, this); + })); + function getEvents(_x12) { + return _getEvents2.apply(this, arguments); + } + return getEvents; + }()) + }, { + key: "_getEvents", + value: function () { + var _getEvents3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee14(request) { + var _request$filters; + return server_regeneratorRuntime().wrap(function _callee14$(_context14) { + while (1) switch (_context14.prev = _context14.next) { + case 0: + return _context14.abrupt("return", postObject(this.serverURL.toString(), 'getEvents', _objectSpread(_objectSpread({ + filters: (_request$filters = request.filters) !== null && _request$filters !== void 0 ? _request$filters : [], + pagination: _objectSpread(_objectSpread({}, request.cursor && { + cursor: request.cursor + }), request.limit && { + limit: request.limit + }) + }, request.startLedger && { + startLedger: request.startLedger + }), request.endLedger && { + endLedger: request.endLedger + }))); + case 1: + case "end": + return _context14.stop(); + } + }, _callee14, this); + })); + function _getEvents(_x13) { + return _getEvents3.apply(this, arguments); + } + return _getEvents; + }() + }, { + key: "getNetwork", + value: (function () { + var _getNetwork = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee15() { + return server_regeneratorRuntime().wrap(function _callee15$(_context15) { + while (1) switch (_context15.prev = _context15.next) { + case 0: + return _context15.abrupt("return", postObject(this.serverURL.toString(), 'getNetwork')); + case 1: + case "end": + return _context15.stop(); + } + }, _callee15, this); + })); + function getNetwork() { + return _getNetwork.apply(this, arguments); + } + return getNetwork; + }()) + }, { + key: "getLatestLedger", + value: (function () { + var _getLatestLedger = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee16() { + return server_regeneratorRuntime().wrap(function _callee16$(_context16) { + while (1) switch (_context16.prev = _context16.next) { + case 0: + return _context16.abrupt("return", postObject(this.serverURL.toString(), 'getLatestLedger')); + case 1: + case "end": + return _context16.stop(); + } + }, _callee16, this); + })); + function getLatestLedger() { + return _getLatestLedger.apply(this, arguments); + } + return getLatestLedger; + }()) + }, { + key: "simulateTransaction", + value: (function () { + var _simulateTransaction2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee17(tx, addlResources) { + return server_regeneratorRuntime().wrap(function _callee17$(_context17) { + while (1) switch (_context17.prev = _context17.next) { + case 0: + return _context17.abrupt("return", this._simulateTransaction(tx, addlResources).then(parsers/* parseRawSimulation */.jr)); + case 1: + case "end": + return _context17.stop(); + } + }, _callee17, this); + })); + function simulateTransaction(_x14, _x15) { + return _simulateTransaction2.apply(this, arguments); + } + return simulateTransaction; + }()) + }, { + key: "_simulateTransaction", + value: function () { + var _simulateTransaction3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee18(transaction, addlResources) { + return server_regeneratorRuntime().wrap(function _callee18$(_context18) { + while (1) switch (_context18.prev = _context18.next) { + case 0: + return _context18.abrupt("return", postObject(this.serverURL.toString(), 'simulateTransaction', _objectSpread({ + transaction: transaction.toXDR() + }, addlResources !== undefined && { + resourceConfig: { + instructionLeeway: addlResources.cpuInstructions + } + }))); + case 1: + case "end": + return _context18.stop(); + } + }, _callee18, this); + })); + function _simulateTransaction(_x16, _x17) { + return _simulateTransaction3.apply(this, arguments); + } + return _simulateTransaction; + }() + }, { + key: "prepareTransaction", + value: (function () { + var _prepareTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee19(tx) { + var simResponse; + return server_regeneratorRuntime().wrap(function _callee19$(_context19) { + while (1) switch (_context19.prev = _context19.next) { + case 0: + _context19.next = 2; + return this.simulateTransaction(tx); + case 2: + simResponse = _context19.sent; + if (!api/* Api */.j.isSimulationError(simResponse)) { + _context19.next = 5; + break; + } + throw new Error(simResponse.error); + case 5: + return _context19.abrupt("return", (0,transaction/* assembleTransaction */.X)(tx, simResponse).build()); + case 6: + case "end": + return _context19.stop(); + } + }, _callee19, this); + })); + function prepareTransaction(_x18) { + return _prepareTransaction.apply(this, arguments); + } + return prepareTransaction; + }()) + }, { + key: "sendTransaction", + value: (function () { + var _sendTransaction2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee20(transaction) { + return server_regeneratorRuntime().wrap(function _callee20$(_context20) { + while (1) switch (_context20.prev = _context20.next) { + case 0: + return _context20.abrupt("return", this._sendTransaction(transaction).then(parsers/* parseRawSendTransaction */.Af)); + case 1: + case "end": + return _context20.stop(); + } + }, _callee20, this); + })); + function sendTransaction(_x19) { + return _sendTransaction2.apply(this, arguments); + } + return sendTransaction; + }()) + }, { + key: "_sendTransaction", + value: function () { + var _sendTransaction3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee21(transaction) { + return server_regeneratorRuntime().wrap(function _callee21$(_context21) { + while (1) switch (_context21.prev = _context21.next) { + case 0: + return _context21.abrupt("return", postObject(this.serverURL.toString(), 'sendTransaction', { + transaction: transaction.toXDR() + })); + case 1: + case "end": + return _context21.stop(); + } + }, _callee21, this); + })); + function _sendTransaction(_x20) { + return _sendTransaction3.apply(this, arguments); + } + return _sendTransaction; + }() + }, { + key: "requestAirdrop", + value: (function () { + var _requestAirdrop = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee22(address, friendbotUrl) { + var account, response, meta, txMeta, sequence, _error$response, _error$response$detai; + return server_regeneratorRuntime().wrap(function _callee22$(_context22) { + while (1) switch (_context22.prev = _context22.next) { + case 0: + account = typeof address === 'string' ? address : address.accountId(); + _context22.t0 = friendbotUrl; + if (_context22.t0) { + _context22.next = 6; + break; + } + _context22.next = 5; + return this.getNetwork(); + case 5: + _context22.t0 = _context22.sent.friendbotUrl; + case 6: + friendbotUrl = _context22.t0; + if (friendbotUrl) { + _context22.next = 9; + break; + } + throw new Error('No friendbot URL configured for current network'); + case 9: + _context22.prev = 9; + _context22.next = 12; + return axios.post("".concat(friendbotUrl, "?addr=").concat(encodeURIComponent(account))); + case 12: + response = _context22.sent; + if (response.data.result_meta_xdr) { + _context22.next = 22; + break; + } + _context22.next = 16; + return this.getTransaction(response.data.hash); + case 16: + txMeta = _context22.sent; + if (!(txMeta.status !== api/* Api */.j.GetTransactionStatus.SUCCESS)) { + _context22.next = 19; + break; + } + throw new Error("Funding account ".concat(address, " failed")); + case 19: + meta = txMeta.resultMetaXdr; + _context22.next = 23; + break; + case 22: + meta = lib.xdr.TransactionMeta.fromXDR(response.data.result_meta_xdr, 'base64'); + case 23: + sequence = findCreatedAccountSequenceInTransactionMeta(meta); + return _context22.abrupt("return", new lib.Account(account, sequence)); + case 27: + _context22.prev = 27; + _context22.t1 = _context22["catch"](9); + if (!(((_error$response = _context22.t1.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 400)) { + _context22.next = 32; + break; + } + if (!((_error$response$detai = _context22.t1.response.detail) !== null && _error$response$detai !== void 0 && _error$response$detai.includes('createAccountAlreadyExist'))) { + _context22.next = 32; + break; + } + return _context22.abrupt("return", this.getAccount(account)); + case 32: + throw _context22.t1; + case 33: + case "end": + return _context22.stop(); + } + }, _callee22, this, [[9, 27]]); + })); + function requestAirdrop(_x21, _x22) { + return _requestAirdrop.apply(this, arguments); + } + return requestAirdrop; + }()) + }, { + key: "getFeeStats", + value: (function () { + var _getFeeStats = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee23() { + return server_regeneratorRuntime().wrap(function _callee23$(_context23) { + while (1) switch (_context23.prev = _context23.next) { + case 0: + return _context23.abrupt("return", postObject(this.serverURL.toString(), 'getFeeStats')); + case 1: + case "end": + return _context23.stop(); + } + }, _callee23, this); + })); + function getFeeStats() { + return _getFeeStats.apply(this, arguments); + } + return getFeeStats; + }()) + }, { + key: "getVersionInfo", + value: (function () { + var _getVersionInfo = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee24() { + return server_regeneratorRuntime().wrap(function _callee24$(_context24) { + while (1) switch (_context24.prev = _context24.next) { + case 0: + return _context24.abrupt("return", postObject(this.serverURL.toString(), 'getVersionInfo')); + case 1: + case "end": + return _context24.stop(); + } + }, _callee24, this); + })); + function getVersionInfo() { + return _getVersionInfo.apply(this, arguments); + } + return getVersionInfo; + }()) + }, { + key: "getSACBalance", + value: (function () { + var _getSACBalance = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee25(contractId, sac, networkPassphrase) { + var passphrase, sacId, key, ledgerKey, response, _response$entries$2, lastModifiedLedgerSeq, liveUntilLedgerSeq, val, entry; + return server_regeneratorRuntime().wrap(function _callee25$(_context25) { + while (1) switch (_context25.prev = _context25.next) { + case 0: + if (lib.StrKey.isValidContract(contractId)) { + _context25.next = 2; + break; + } + throw new TypeError("expected contract ID, got ".concat(contractId)); + case 2: + if (!(networkPassphrase !== null && networkPassphrase !== void 0)) { + _context25.next = 6; + break; + } + _context25.t0 = networkPassphrase; + _context25.next = 9; + break; + case 6: + _context25.next = 8; + return this.getNetwork().then(function (n) { + return n.passphrase; + }); + case 8: + _context25.t0 = _context25.sent; + case 9: + passphrase = _context25.t0; + sacId = sac.contractId(passphrase); + key = lib.xdr.ScVal.scvVec([(0,lib.nativeToScVal)("Balance", { + type: "symbol" + }), (0,lib.nativeToScVal)(contractId, { + type: "address" + })]); + ledgerKey = lib.xdr.LedgerKey.contractData(new lib.xdr.LedgerKeyContractData({ + contract: new lib.Address(sacId).toScAddress(), + durability: lib.xdr.ContractDataDurability.persistent(), + key: key + })); + _context25.next = 15; + return this.getLedgerEntries(ledgerKey); + case 15: + response = _context25.sent; + if (!(response.entries.length === 0)) { + _context25.next = 18; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 18: + _response$entries$2 = response.entries[0], lastModifiedLedgerSeq = _response$entries$2.lastModifiedLedgerSeq, liveUntilLedgerSeq = _response$entries$2.liveUntilLedgerSeq, val = _response$entries$2.val; + if (!(val.switch().value !== lib.xdr.LedgerEntryType.contractData().value)) { + _context25.next = 21; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 21: + entry = (0,lib.scValToNative)(val.contractData().val()); + return _context25.abrupt("return", { + latestLedger: response.latestLedger, + balanceEntry: { + liveUntilLedgerSeq: liveUntilLedgerSeq, + lastModifiedLedgerSeq: lastModifiedLedgerSeq, + amount: entry.amount.toString(), + authorized: entry.authorized, + clawback: entry.clawback + } + }); + case 23: + case "end": + return _context25.stop(); + } + }, _callee25, this); + })); + function getSACBalance(_x23, _x24, _x25) { + return _getSACBalance.apply(this, arguments); + } + return getSACBalance; + }()) + }]); +}(); +;// ./src/rpc/index.ts +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + +/* harmony default export */ const rpc = (module.exports); + +/***/ }), + +/***/ 784: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ $D: () => (/* binding */ parseRawLedgerEntries), +/* harmony export */ Af: () => (/* binding */ parseRawSendTransaction), +/* harmony export */ WC: () => (/* binding */ parseTransactionInfo), +/* harmony export */ fG: () => (/* binding */ parseRawEvents), +/* harmony export */ jr: () => (/* binding */ parseRawSimulation), +/* harmony export */ tR: () => (/* binding */ parseRawTransactions) +/* harmony export */ }); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4076); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + +function parseRawSendTransaction(raw) { + var errorResultXdr = raw.errorResultXdr, + diagnosticEventsXdr = raw.diagnosticEventsXdr; + delete raw.errorResultXdr; + delete raw.diagnosticEventsXdr; + if (errorResultXdr) { + return _objectSpread(_objectSpread(_objectSpread({}, raw), diagnosticEventsXdr !== undefined && diagnosticEventsXdr.length > 0 && { + diagnosticEvents: diagnosticEventsXdr.map(function (evt) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + }) + }), {}, { + errorResult: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionResult.fromXDR(errorResultXdr, 'base64') + }); + } + return _objectSpread({}, raw); +} +function parseTransactionInfo(raw) { + var meta = _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionMeta.fromXDR(raw.resultMetaXdr, 'base64'); + var info = { + ledger: raw.ledger, + createdAt: raw.createdAt, + applicationOrder: raw.applicationOrder, + feeBump: raw.feeBump, + envelopeXdr: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionEnvelope.fromXDR(raw.envelopeXdr, 'base64'), + resultXdr: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionResult.fromXDR(raw.resultXdr, 'base64'), + resultMetaXdr: meta + }; + if (meta.switch() === 3 && meta.v3().sorobanMeta() !== null) { + var _meta$v3$sorobanMeta; + info.returnValue = (_meta$v3$sorobanMeta = meta.v3().sorobanMeta()) === null || _meta$v3$sorobanMeta === void 0 ? void 0 : _meta$v3$sorobanMeta.returnValue(); + } + if ('diagnosticEventsXdr' in raw && raw.diagnosticEventsXdr) { + info.diagnosticEventsXdr = raw.diagnosticEventsXdr.map(function (diagnosticEvent) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.DiagnosticEvent.fromXDR(diagnosticEvent, 'base64'); + }); + } + return info; +} +function parseRawTransactions(r) { + return _objectSpread({ + status: r.status, + txHash: r.txHash + }, parseTransactionInfo(r)); +} +function parseRawEvents(raw) { + var _raw$events; + return { + latestLedger: raw.latestLedger, + cursor: raw.cursor, + events: ((_raw$events = raw.events) !== null && _raw$events !== void 0 ? _raw$events : []).map(function (evt) { + var clone = _objectSpread({}, evt); + delete clone.contractId; + return _objectSpread(_objectSpread(_objectSpread({}, clone), evt.contractId !== '' && { + contractId: new _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.Contract(evt.contractId) + }), {}, { + topic: evt.topic.map(function (topic) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.fromXDR(topic, 'base64'); + }), + value: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.fromXDR(evt.value, 'base64') + }); + }) + }; +} +function parseRawLedgerEntries(raw) { + var _raw$entries; + return { + latestLedger: raw.latestLedger, + entries: ((_raw$entries = raw.entries) !== null && _raw$entries !== void 0 ? _raw$entries : []).map(function (rawEntry) { + if (!rawEntry.key || !rawEntry.xdr) { + throw new TypeError("invalid ledger entry: ".concat(JSON.stringify(rawEntry))); + } + return _objectSpread({ + lastModifiedLedgerSeq: rawEntry.lastModifiedLedgerSeq, + key: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerKey.fromXDR(rawEntry.key, 'base64'), + val: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerEntryData.fromXDR(rawEntry.xdr, 'base64') + }, rawEntry.liveUntilLedgerSeq !== undefined && { + liveUntilLedgerSeq: rawEntry.liveUntilLedgerSeq + }); + }) + }; +} +function parseSuccessful(sim, partial) { + var _sim$results$length, _sim$results, _sim$stateChanges$len, _sim$stateChanges, _sim$stateChanges2; + var success = _objectSpread(_objectSpread(_objectSpread({}, partial), {}, { + transactionData: new _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.SorobanDataBuilder(sim.transactionData), + minResourceFee: sim.minResourceFee + }, ((_sim$results$length = (_sim$results = sim.results) === null || _sim$results === void 0 ? void 0 : _sim$results.length) !== null && _sim$results$length !== void 0 ? _sim$results$length : 0 > 0) && { + result: sim.results.map(function (row) { + var _row$auth; + return { + auth: ((_row$auth = row.auth) !== null && _row$auth !== void 0 ? _row$auth : []).map(function (entry) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.SorobanAuthorizationEntry.fromXDR(entry, 'base64'); + }), + retval: row.xdr ? _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.fromXDR(row.xdr, 'base64') : _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.scvVoid() + }; + })[0] + }), ((_sim$stateChanges$len = (_sim$stateChanges = sim.stateChanges) === null || _sim$stateChanges === void 0 ? void 0 : _sim$stateChanges.length) !== null && _sim$stateChanges$len !== void 0 ? _sim$stateChanges$len : 0 > 0) && { + stateChanges: (_sim$stateChanges2 = sim.stateChanges) === null || _sim$stateChanges2 === void 0 ? void 0 : _sim$stateChanges2.map(function (entryChange) { + return { + type: entryChange.type, + key: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerKey.fromXDR(entryChange.key, 'base64'), + before: entryChange.before ? _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerEntry.fromXDR(entryChange.before, 'base64') : null, + after: entryChange.after ? _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerEntry.fromXDR(entryChange.after, 'base64') : null + }; + }) + }); + if (!sim.restorePreamble || sim.restorePreamble.transactionData === '') { + return success; + } + return _objectSpread(_objectSpread({}, success), {}, { + restorePreamble: { + minResourceFee: sim.restorePreamble.minResourceFee, + transactionData: new _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.SorobanDataBuilder(sim.restorePreamble.transactionData) + } + }); +} +function parseRawSimulation(sim) { + var _sim$events$map, _sim$events; + var looksRaw = _api__WEBPACK_IMPORTED_MODULE_1__/* .Api */ .j.isSimulationRaw(sim); + if (!looksRaw) { + return sim; + } + var base = { + _parsed: true, + id: sim.id, + latestLedger: sim.latestLedger, + events: (_sim$events$map = (_sim$events = sim.events) === null || _sim$events === void 0 ? void 0 : _sim$events.map(function (evt) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + })) !== null && _sim$events$map !== void 0 ? _sim$events$map : [] + }; + if (typeof sim.error === 'string') { + return _objectSpread(_objectSpread({}, base), {}, { + error: sim.error + }); + } + return parseSuccessful(sim, base); +} + +/***/ }), + +/***/ 8680: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ X: () => (/* binding */ assembleTransaction) +/* harmony export */ }); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4076); +/* harmony import */ var _parsers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(784); + + + +function isSorobanTransaction(tx) { + if (tx.operations.length !== 1) { + return false; + } + switch (tx.operations[0].type) { + case 'invokeHostFunction': + case 'extendFootprintTtl': + case 'restoreFootprint': + return true; + default: + return false; + } +} +function assembleTransaction(raw, simulation) { + if ('innerTransaction' in raw) { + return assembleTransaction(raw.innerTransaction, simulation); + } + if (!isSorobanTransaction(raw)) { + throw new TypeError('unsupported transaction: must contain exactly one ' + 'invokeHostFunction, extendFootprintTtl, or restoreFootprint ' + 'operation'); + } + var success = (0,_parsers__WEBPACK_IMPORTED_MODULE_2__/* .parseRawSimulation */ .jr)(simulation); + if (!_api__WEBPACK_IMPORTED_MODULE_1__/* .Api */ .j.isSimulationSuccess(success)) { + throw new Error("simulation incorrect: ".concat(JSON.stringify(success))); + } + var classicFeeNum = parseInt(raw.fee) || 0; + var minResourceFeeNum = parseInt(success.minResourceFee) || 0; + var txnBuilder = _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.TransactionBuilder.cloneFrom(raw, { + fee: (classicFeeNum + minResourceFeeNum).toString(), + sorobanData: success.transactionData.build(), + networkPassphrase: raw.networkPassphrase + }); + if (raw.operations[0].type === 'invokeHostFunction') { + var _invokeOp$auth; + txnBuilder.clearOperations(); + var invokeOp = raw.operations[0]; + var existingAuth = (_invokeOp$auth = invokeOp.auth) !== null && _invokeOp$auth !== void 0 ? _invokeOp$auth : []; + txnBuilder.addOperation(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.Operation.invokeHostFunction({ + source: invokeOp.source, + func: invokeOp.func, + auth: existingAuth.length > 0 ? existingAuth : success.result.auth + })); + } + return txnBuilder; +} + +/***/ }), + +/***/ 3898: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Api: () => (/* binding */ Api), +/* harmony export */ Resolver: () => (/* binding */ Resolver), +/* harmony export */ STELLAR_TOML_MAX_SIZE: () => (/* binding */ STELLAR_TOML_MAX_SIZE) +/* harmony export */ }); +/* harmony import */ var toml__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1293); +/* harmony import */ var toml__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(toml__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _http_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9983); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8732); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + +var STELLAR_TOML_MAX_SIZE = 100 * 1024; +var CancelToken = _http_client__WEBPACK_IMPORTED_MODULE_1__/* .httpClient */ .ok.CancelToken; +var Resolver = function () { + function Resolver() { + _classCallCheck(this, Resolver); + } + return _createClass(Resolver, null, [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(domain) { + var _opts$allowedRedirect; + var opts, + allowHttp, + timeout, + protocol, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 1 && _args[1] !== undefined ? _args[1] : {}; + allowHttp = typeof opts.allowHttp === "undefined" ? _config__WEBPACK_IMPORTED_MODULE_2__/* .Config */ .T.isAllowHttp() : opts.allowHttp; + timeout = typeof opts.timeout === "undefined" ? _config__WEBPACK_IMPORTED_MODULE_2__/* .Config */ .T.getTimeout() : opts.timeout; + protocol = allowHttp ? "http" : "https"; + return _context.abrupt("return", _http_client__WEBPACK_IMPORTED_MODULE_1__/* .httpClient */ .ok.get("".concat(protocol, "://").concat(domain, "/.well-known/stellar.toml"), { + maxRedirects: (_opts$allowedRedirect = opts.allowedRedirects) !== null && _opts$allowedRedirect !== void 0 ? _opts$allowedRedirect : 0, + maxContentLength: STELLAR_TOML_MAX_SIZE, + cancelToken: timeout ? new CancelToken(function (cancel) { + return setTimeout(function () { + return cancel("timeout of ".concat(timeout, "ms exceeded")); + }, timeout); + }) : undefined, + timeout: timeout + }).then(function (response) { + try { + var tomlObject = toml__WEBPACK_IMPORTED_MODULE_0___default().parse(response.data); + return Promise.resolve(tomlObject); + } catch (e) { + return Promise.reject(new Error("stellar.toml is invalid - Parsing error on line ".concat(e.line, ", column ").concat(e.column, ": ").concat(e.message))); + } + }).catch(function (err) { + if (err.message.match(/^maxContentLength size/)) { + throw new Error("stellar.toml file exceeds allowed size of ".concat(STELLAR_TOML_MAX_SIZE)); + } else { + throw err; + } + })); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + function resolve(_x) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }]); +}(); +var Api; + +/***/ }), + +/***/ 3121: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ A: () => (/* binding */ Utils) +/* harmony export */ }); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Utils = function () { + function Utils() { + _classCallCheck(this, Utils); + } + return _createClass(Utils, null, [{ + key: "validateTimebounds", + value: function validateTimebounds(transaction) { + var gracePeriod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + if (!transaction.timeBounds) { + return false; + } + var now = Math.floor(Date.now() / 1000); + var _transaction$timeBoun = transaction.timeBounds, + minTime = _transaction$timeBoun.minTime, + maxTime = _transaction$timeBoun.maxTime; + return now >= Number.parseInt(minTime, 10) - gracePeriod && now <= Number.parseInt(maxTime, 10) + gracePeriod; + } + }, { + key: "sleep", + value: function sleep(ms) { + return new Promise(function (resolve) { + return setTimeout(resolve, ms); + }); + } + }]); +}(); + +/***/ }), + +/***/ 5479: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + InvalidChallengeError: () => (/* reexport */ InvalidChallengeError), + buildChallengeTx: () => (/* reexport */ buildChallengeTx), + gatherTxSigners: () => (/* reexport */ gatherTxSigners), + readChallengeTx: () => (/* reexport */ readChallengeTx), + verifyChallengeTxSigners: () => (/* reexport */ verifyChallengeTxSigners), + verifyChallengeTxThreshold: () => (/* reexport */ verifyChallengeTxThreshold), + verifyTxSignedBy: () => (/* reexport */ verifyTxSignedBy) +}); + +// EXTERNAL MODULE: ./node_modules/randombytes/browser.js +var browser = __webpack_require__(3209); +var browser_default = /*#__PURE__*/__webpack_require__.n(browser); +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./src/utils.ts +var utils = __webpack_require__(3121); +;// ./src/webauth/errors.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var InvalidChallengeError = function (_Error) { + function InvalidChallengeError(message) { + var _this; + _classCallCheck(this, InvalidChallengeError); + var trueProto = (this instanceof InvalidChallengeError ? this.constructor : void 0).prototype; + _this = _callSuper(this, InvalidChallengeError, [message]); + _this.__proto__ = trueProto; + _this.constructor = InvalidChallengeError; + _this.name = "InvalidChallengeError"; + return _this; + } + _inherits(InvalidChallengeError, _Error); + return _createClass(InvalidChallengeError); +}(_wrapNativeSuper(Error)); +;// ./src/webauth/utils.ts +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function utils_typeof(o) { "@babel/helpers - typeof"; return utils_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, utils_typeof(o); } +function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } + + + + +function buildChallengeTx(serverKeypair, clientAccountID, homeDomain) { + var timeout = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 300; + var networkPassphrase = arguments.length > 4 ? arguments[4] : undefined; + var webAuthDomain = arguments.length > 5 ? arguments[5] : undefined; + var memo = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var clientDomain = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var clientSigningKey = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; + if (clientAccountID.startsWith("M") && memo) { + throw Error("memo cannot be used if clientAccountID is a muxed account"); + } + var account = new lib.Account(serverKeypair.publicKey(), "-1"); + var now = Math.floor(Date.now() / 1000); + var value = browser_default()(48).toString("base64"); + var builder = new lib.TransactionBuilder(account, { + fee: lib.BASE_FEE, + networkPassphrase: networkPassphrase, + timebounds: { + minTime: now, + maxTime: now + timeout + } + }).addOperation(lib.Operation.manageData({ + name: "".concat(homeDomain, " auth"), + value: value, + source: clientAccountID + })).addOperation(lib.Operation.manageData({ + name: "web_auth_domain", + value: webAuthDomain, + source: account.accountId() + })); + if (clientDomain) { + if (!clientSigningKey) { + throw Error("clientSigningKey is required if clientDomain is provided"); + } + builder.addOperation(lib.Operation.manageData({ + name: "client_domain", + value: clientDomain, + source: clientSigningKey + })); + } + if (memo) { + builder.addMemo(lib.Memo.id(memo)); + } + var transaction = builder.build(); + transaction.sign(serverKeypair); + return transaction.toEnvelope().toXDR("base64").toString(); +} +function readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain) { + var _transaction$timeBoun; + if (serverAccountID.startsWith("M")) { + throw Error("Invalid serverAccountID: multiplexed accounts are not supported."); + } + var transaction; + try { + transaction = new lib.Transaction(challengeTx, networkPassphrase); + } catch (_unused) { + try { + transaction = new lib.FeeBumpTransaction(challengeTx, networkPassphrase); + } catch (_unused2) { + throw new InvalidChallengeError("Invalid challenge: unable to deserialize challengeTx transaction string"); + } + throw new InvalidChallengeError("Invalid challenge: expected a Transaction but received a FeeBumpTransaction"); + } + var sequence = Number.parseInt(transaction.sequence, 10); + if (sequence !== 0) { + throw new InvalidChallengeError("The transaction sequence number should be zero"); + } + if (transaction.source !== serverAccountID) { + throw new InvalidChallengeError("The transaction source account is not equal to the server's account"); + } + if (transaction.operations.length < 1) { + throw new InvalidChallengeError("The transaction should contain at least one operation"); + } + var _transaction$operatio = _toArray(transaction.operations), + operation = _transaction$operatio[0], + subsequentOperations = _transaction$operatio.slice(1); + if (!operation.source) { + throw new InvalidChallengeError("The transaction's operation should contain a source account"); + } + var clientAccountID = operation.source; + var memo = null; + if (transaction.memo.type !== lib.MemoNone) { + if (clientAccountID.startsWith("M")) { + throw new InvalidChallengeError("The transaction has a memo but the client account ID is a muxed account"); + } + if (transaction.memo.type !== lib.MemoID) { + throw new InvalidChallengeError("The transaction's memo must be of type `id`"); + } + memo = transaction.memo.value; + } + if (operation.type !== "manageData") { + throw new InvalidChallengeError("The transaction's operation type should be 'manageData'"); + } + if (transaction.timeBounds && Number.parseInt((_transaction$timeBoun = transaction.timeBounds) === null || _transaction$timeBoun === void 0 ? void 0 : _transaction$timeBoun.maxTime, 10) === lib.TimeoutInfinite) { + throw new InvalidChallengeError("The transaction requires non-infinite timebounds"); + } + if (!utils/* Utils */.A.validateTimebounds(transaction, 60 * 5)) { + throw new InvalidChallengeError("The transaction has expired"); + } + if (operation.value === undefined) { + throw new InvalidChallengeError("The transaction's operation values should not be null"); + } + if (!operation.value) { + throw new InvalidChallengeError("The transaction's operation value should not be null"); + } + if (Buffer.from(operation.value.toString(), "base64").length !== 48) { + throw new InvalidChallengeError("The transaction's operation value should be a 64 bytes base64 random string"); + } + if (!homeDomains) { + throw new InvalidChallengeError("Invalid homeDomains: a home domain must be provided for verification"); + } + var matchedHomeDomain; + if (typeof homeDomains === "string") { + if ("".concat(homeDomains, " auth") === operation.name) { + matchedHomeDomain = homeDomains; + } + } else if (Array.isArray(homeDomains)) { + matchedHomeDomain = homeDomains.find(function (domain) { + return "".concat(domain, " auth") === operation.name; + }); + } else { + throw new InvalidChallengeError("Invalid homeDomains: homeDomains type is ".concat(utils_typeof(homeDomains), " but should be a string or an array")); + } + if (!matchedHomeDomain) { + throw new InvalidChallengeError("Invalid homeDomains: the transaction's operation key name does not match the expected home domain"); + } + var _iterator = _createForOfIteratorHelper(subsequentOperations), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var op = _step.value; + if (op.type !== "manageData") { + throw new InvalidChallengeError("The transaction has operations that are not of type 'manageData'"); + } + if (op.source !== serverAccountID && op.name !== "client_domain") { + throw new InvalidChallengeError("The transaction has operations that are unrecognized"); + } + if (op.name === "web_auth_domain") { + if (op.value === undefined) { + throw new InvalidChallengeError("'web_auth_domain' operation value should not be null"); + } + if (op.value.compare(Buffer.from(webAuthDomain))) { + throw new InvalidChallengeError("'web_auth_domain' operation value does not match ".concat(webAuthDomain)); + } + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + if (!verifyTxSignedBy(transaction, serverAccountID)) { + throw new InvalidChallengeError("Transaction not signed by server: '".concat(serverAccountID, "'")); + } + return { + tx: transaction, + clientAccountID: clientAccountID, + matchedHomeDomain: matchedHomeDomain, + memo: memo + }; +} +function verifyChallengeTxThreshold(challengeTx, serverAccountID, networkPassphrase, threshold, signerSummary, homeDomains, webAuthDomain) { + var signers = signerSummary.map(function (signer) { + return signer.key; + }); + var signersFound = verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain); + var weight = 0; + var _loop = function _loop() { + var _signerSummary$find; + var signer = _signersFound[_i]; + var sigWeight = ((_signerSummary$find = signerSummary.find(function (s) { + return s.key === signer; + })) === null || _signerSummary$find === void 0 ? void 0 : _signerSummary$find.weight) || 0; + weight += sigWeight; + }; + for (var _i = 0, _signersFound = signersFound; _i < _signersFound.length; _i++) { + _loop(); + } + if (weight < threshold) { + throw new InvalidChallengeError("signers with weight ".concat(weight, " do not meet threshold ").concat(threshold, "\"")); + } + return signersFound; +} +function verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain) { + var _readChallengeTx = readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain), + tx = _readChallengeTx.tx; + var serverKP; + try { + serverKP = lib.Keypair.fromPublicKey(serverAccountID); + } catch (err) { + throw new Error("Couldn't infer keypair from the provided 'serverAccountID': ".concat(err.message)); + } + var clientSigners = new Set(); + var _iterator2 = _createForOfIteratorHelper(signers), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var _signer = _step2.value; + if (_signer === serverKP.publicKey()) { + continue; + } + if (_signer.charAt(0) !== "G") { + continue; + } + clientSigners.add(_signer); + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + if (clientSigners.size === 0) { + throw new InvalidChallengeError("No verifiable client signers provided, at least one G... address must be provided"); + } + var clientSigningKey; + var _iterator3 = _createForOfIteratorHelper(tx.operations), + _step3; + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + var op = _step3.value; + if (op.type === "manageData" && op.name === "client_domain") { + if (clientSigningKey) { + throw new InvalidChallengeError("Found more than one client_domain operation"); + } + clientSigningKey = op.source; + } + } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); + } + var allSigners = [serverKP.publicKey()].concat(_toConsumableArray(Array.from(clientSigners))); + if (clientSigningKey) { + allSigners.push(clientSigningKey); + } + var signersFound = gatherTxSigners(tx, allSigners); + var serverSignatureFound = false; + var clientSigningKeySignatureFound = false; + for (var _i2 = 0, _signersFound2 = signersFound; _i2 < _signersFound2.length; _i2++) { + var signer = _signersFound2[_i2]; + if (signer === serverKP.publicKey()) { + serverSignatureFound = true; + } + if (signer === clientSigningKey) { + clientSigningKeySignatureFound = true; + } + } + if (!serverSignatureFound) { + throw new InvalidChallengeError("Transaction not signed by server: '".concat(serverKP.publicKey(), "'")); + } + if (clientSigningKey && !clientSigningKeySignatureFound) { + throw new InvalidChallengeError("Transaction not signed by the source account of the 'client_domain' " + "ManageData operation"); + } + if (signersFound.length === 1) { + throw new InvalidChallengeError("None of the given signers match the transaction signatures"); + } + if (signersFound.length !== tx.signatures.length) { + throw new InvalidChallengeError("Transaction has unrecognized signatures"); + } + signersFound.splice(signersFound.indexOf(serverKP.publicKey()), 1); + if (clientSigningKey) { + signersFound.splice(signersFound.indexOf(clientSigningKey), 1); + } + return signersFound; +} +function verifyTxSignedBy(transaction, accountID) { + return gatherTxSigners(transaction, [accountID]).length !== 0; +} +function gatherTxSigners(transaction, signers) { + var hashedSignatureBase = transaction.hash(); + var txSignatures = _toConsumableArray(transaction.signatures); + var signersFound = new Set(); + var _iterator4 = _createForOfIteratorHelper(signers), + _step4; + try { + for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { + var signer = _step4.value; + if (txSignatures.length === 0) { + break; + } + var keypair = void 0; + try { + keypair = lib.Keypair.fromPublicKey(signer); + } catch (err) { + throw new InvalidChallengeError("Signer is not a valid address: ".concat(err.message)); + } + for (var i = 0; i < txSignatures.length; i++) { + var decSig = txSignatures[i]; + if (!decSig.hint().equals(keypair.signatureHint())) { + continue; + } + if (keypair.verify(hashedSignatureBase, decSig.signature())) { + signersFound.add(signer); + txSignatures.splice(i, 1); + break; + } + } + } + } catch (err) { + _iterator4.e(err); + } finally { + _iterator4.f(); + } + return Array.from(signersFound); +} +;// ./src/webauth/index.ts + + + +/***/ }), + +/***/ 5360: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +/** + * Generate a character map. + * @param {string} alphabet e.g. "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" + * @param {object} mappings map overrides from key to value + * @method + */ + +var charmap = function (alphabet, mappings) { + mappings || (mappings = {}); + alphabet.split("").forEach(function (c, i) { + if (!(c in mappings)) mappings[c] = i; + }); + return mappings; +} + +/** + * The RFC 4648 base 32 alphabet and character map. + * @see {@link https://tools.ietf.org/html/rfc4648} + */ + +var rfc4648 = { + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", + charmap: { + 0: 14, + 1: 8 + } +}; + +rfc4648.charmap = charmap(rfc4648.alphabet, rfc4648.charmap); + +/** + * The Crockford base 32 alphabet and character map. + * @see {@link http://www.crockford.com/wrmg/base32.html} + */ + +var crockford = { + alphabet: "0123456789ABCDEFGHJKMNPQRSTVWXYZ", + charmap: { + O: 0, + I: 1, + L: 1 + } +}; + +crockford.charmap = charmap(crockford.alphabet, crockford.charmap); + +/** + * base32hex + * @see {@link https://en.wikipedia.org/wiki/Base32#base32hex} + */ + +var base32hex = { + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", + charmap: {} +}; + +base32hex.charmap = charmap(base32hex.alphabet, base32hex.charmap); + +/** + * Create a new `Decoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [charmap] Override the character map used in decoding. + * @constructor + */ + +function Decoder (options) { + this.buf = []; + this.shift = 8; + this.carry = 0; + + if (options) { + + switch (options.type) { + case "rfc4648": + this.charmap = exports.rfc4648.charmap; + break; + case "crockford": + this.charmap = exports.crockford.charmap; + break; + case "base32hex": + this.charmap = exports.base32hex.charmap; + break; + default: + throw new Error("invalid type"); + } + + if (options.charmap) this.charmap = options.charmap; + } +} + +/** + * The default character map coresponds to RFC4648. + */ + +Decoder.prototype.charmap = rfc4648.charmap; + +/** + * Decode a string, continuing from the previous state. + * + * @param {string} str + * @return {Decoder} this + */ + +Decoder.prototype.write = function (str) { + var charmap = this.charmap; + var buf = this.buf; + var shift = this.shift; + var carry = this.carry; + + // decode string + str.toUpperCase().split("").forEach(function (char) { + + // ignore padding + if (char == "=") return; + + // lookup symbol + var symbol = charmap[char] & 0xff; + + // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 + + shift -= 5; + if (shift > 0) { + carry |= symbol << shift; + } else if (shift < 0) { + buf.push(carry | (symbol >> -shift)); + shift += 8; + carry = (symbol << shift) & 0xff; + } else { + buf.push(carry | symbol); + shift = 8; + carry = 0; + } + }); + + // save state + this.shift = shift; + this.carry = carry; + + // for chaining + return this; +}; + +/** + * Finish decoding. + * + * @param {string} [str] The final string to decode. + * @return {Array} Decoded byte array. + */ + +Decoder.prototype.finalize = function (str) { + if (str) { + this.write(str); + } + if (this.shift !== 8 && this.carry !== 0) { + this.buf.push(this.carry); + this.shift = 8; + this.carry = 0; + } + return this.buf; +}; + +/** + * Create a new `Encoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [alphabet] Override the alphabet used in encoding. + * @constructor + */ + +function Encoder (options) { + this.buf = ""; + this.shift = 3; + this.carry = 0; + + if (options) { + + switch (options.type) { + case "rfc4648": + this.alphabet = exports.rfc4648.alphabet; + break; + case "crockford": + this.alphabet = exports.crockford.alphabet; + break; + case "base32hex": + this.alphabet = exports.base32hex.alphabet; + break; + default: + throw new Error("invalid type"); + } + + if (options.alphabet) this.alphabet = options.alphabet; + else if (options.lc) this.alphabet = this.alphabet.toLowerCase(); + } +} + +/** + * The default alphabet coresponds to RFC4648. + */ + +Encoder.prototype.alphabet = rfc4648.alphabet; + +/** + * Encode a byte array, continuing from the previous state. + * + * @param {byte[]} buf The byte array to encode. + * @return {Encoder} this + */ + +Encoder.prototype.write = function (buf) { + var shift = this.shift; + var carry = this.carry; + var symbol; + var byte; + var i; + + // encode each byte in buf + for (i = 0; i < buf.length; i++) { + byte = buf[i]; + + // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 + + symbol = carry | (byte >> shift); + this.buf += this.alphabet[symbol & 0x1f]; + + if (shift > 5) { + shift -= 5; + symbol = byte >> shift; + this.buf += this.alphabet[symbol & 0x1f]; + } + + shift = 5 - shift; + carry = byte << shift; + shift = 8 - shift; + } + + // save state + this.shift = shift; + this.carry = carry; + + // for chaining + return this; +}; + +/** + * Finish encoding. + * + * @param {byte[]} [buf] The final byte array to encode. + * @return {string} The encoded byte array. + */ + +Encoder.prototype.finalize = function (buf) { + if (buf) { + this.write(buf); + } + if (this.shift !== 3) { + this.buf += this.alphabet[this.carry & 0x1f]; + this.shift = 3; + this.carry = 0; + } + return this.buf; +}; + +/** + * Convenience encoder. + * + * @param {byte[]} buf The byte array to encode. + * @param {object} [options] Options to pass to the encoder. + * @return {string} The encoded string. + */ + +exports.encode = function (buf, options) { + return new Encoder(options).finalize(buf); +}; + +/** + * Convenience decoder. + * + * @param {string} str The string to decode. + * @param {object} [options] Options to pass to the decoder. + * @return {byte[]} The decoded byte array. + */ + +exports.decode = function (str, options) { + return new Decoder(options).finalize(str); +}; + +// Exports. +exports.Decoder = Decoder; +exports.Encoder = Encoder; +exports.charmap = charmap; +exports.crockford = crockford; +exports.rfc4648 = rfc4648; +exports.base32hex = base32hex; + + +/***/ }), + +/***/ 7526: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + + +/***/ }), + +/***/ 1594: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_RESULT__;;(function (globalObject) { + 'use strict'; + +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + + var BigNumber, + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + + /* + * Create and return a BigNumber constructor. + */ + function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; + } + + + // PRIVATE HELPER FUNCTIONS + + // These functions don't need access to variables, + // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + + function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; + } + + + // Return a coefficient array as a string of base 10 digits. + function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); + } + + + // Compare the value of BigNumbers x and y. + function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; + } + + + /* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ + function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } + } + + + // Assumes finite n. + function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; + } + + + function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; + } + + + function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; + } + + + // EXPORT + + + BigNumber = clone(); + BigNumber['default'] = BigNumber.BigNumber = BigNumber; + + // AMD. + if (true) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return BigNumber; }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + // Node.js and other environments that support module.exports. + } else {} +})(this); + + +/***/ }), + +/***/ 8287: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + + + +const base64 = __webpack_require__(7526) +const ieee754 = __webpack_require__(251) +const customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +const K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + const arr = new Uint8Array(1) + const proto = { foo: function () { return 42 } } + Object.setPrototypeOf(proto, Uint8Array.prototype) + Object.setPrototypeOf(arr, proto) + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + const buf = new Uint8Array(length) + Object.setPrototypeOf(buf, Buffer.prototype) + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + const valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + const b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) +Object.setPrototypeOf(Buffer, Uint8Array) + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + const length = byteLength(string, encoding) | 0 + let buf = createBuffer(length) + + const actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0 + const buf = createBuffer(length) + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView) + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + let buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype) + + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + const len = checked(obj.length) | 0 + const buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + let x = a.length + let y = b.length + + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + let i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + const buffer = Buffer.allocUnsafe(length) + let pos = 0 + for (i = 0; i < list.length; ++i) { + let buf = list[i] + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) + buf.copy(buffer, pos) + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ) + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos) + } + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + const len = string.length + const mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + let loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + let loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + const i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + const len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + const len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + const len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + const length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + let str = '' + const max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + let x = thisEnd - thisStart + let y = end - start + const len = Math.min(x, y) + + const thisCopy = this.slice(thisStart, thisEnd) + const targetCopy = target.slice(start, end) + + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + let indexSize = 1 + let arrLength = arr.length + let valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + let i + if (dir) { + let foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + let found = true + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + const remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + const strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + let i + for (i = 0; i < length; ++i) { + const parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + const remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + let loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + const res = [] + + let i = start + while (i < end) { + const firstByte = buf[i] + let codePoint = null + let bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +const MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + const len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + let res = '' + let i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + const len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + let out = '' + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]] + } + return out +} + +function utf16leSlice (buf, start, end) { + const bytes = buf.slice(start, end) + let res = '' + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + const len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + const newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype) + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + let val = this[offset + --byteLength] + let mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const lo = first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24 + + const hi = this[++offset] + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + last * 2 ** 24 + + return BigInt(lo) + (BigInt(hi) << BigInt(32)) +}) + +Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const hi = first * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + const lo = this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last + + return (BigInt(hi) << BigInt(32)) + BigInt(lo) +}) + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let i = byteLength + let mul = 1 + let val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = this[offset + 4] + + this[offset + 5] * 2 ** 8 + + this[offset + 6] * 2 ** 16 + + (last << 24) // Overflow + + return (BigInt(val) << BigInt(32)) + + BigInt(first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24) +}) + +Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + return (BigInt(val) << BigInt(32)) + + BigInt(this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last) +}) + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let mul = 1 + let i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let i = byteLength - 1 + let mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function wrtBigUInt64LE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + return offset +} + +function wrtBigUInt64BE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset + 7] = lo + lo = lo >> 8 + buf[offset + 6] = lo + lo = lo >> 8 + buf[offset + 5] = lo + lo = lo >> 8 + buf[offset + 4] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset + 3] = hi + hi = hi >> 8 + buf[offset + 2] = hi + hi = hi >> 8 + buf[offset + 1] = hi + hi = hi >> 8 + buf[offset] = hi + return offset + 8 +} + +Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = 0 + let mul = 1 + let sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = byteLength - 1 + let mul = 1 + let sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + const len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + const code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } else if (typeof val === 'boolean') { + val = Number(val) + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + let i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + const bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + const len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// CUSTOM ERRORS +// ============= + +// Simplified versions from Node, changed for Buffer-only usage +const errors = {} +function E (sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor () { + super() + + Object.defineProperty(this, 'message', { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }) + + // Add the error code to the name to include it in the stack trace. + this.name = `${this.name} [${sym}]` + // Access the stack to generate the error message including the error code + // from the name. + this.stack // eslint-disable-line no-unused-expressions + // Reset the name to the actual name. + delete this.name + } + + get code () { + return sym + } + + set code (value) { + Object.defineProperty(this, 'code', { + configurable: true, + enumerable: true, + value, + writable: true + }) + } + + toString () { + return `${this.name} [${sym}]: ${this.message}` + } + } +} + +E('ERR_BUFFER_OUT_OF_BOUNDS', + function (name) { + if (name) { + return `${name} is outside of buffer bounds` + } + + return 'Attempt to access memory outside buffer bounds' + }, RangeError) +E('ERR_INVALID_ARG_TYPE', + function (name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}` + }, TypeError) +E('ERR_OUT_OF_RANGE', + function (str, range, input) { + let msg = `The value of "${str}" is out of range.` + let received = input + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)) + } else if (typeof input === 'bigint') { + received = String(input) + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received) + } + received += 'n' + } + msg += ` It must be ${range}. Received ${received}` + return msg + }, RangeError) + +function addNumericalSeparator (val) { + let res = '' + let i = val.length + const start = val[0] === '-' ? 1 : 0 + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}` + } + return `${val.slice(0, i)}${res}` +} + +// CHECK FUNCTIONS +// =============== + +function checkBounds (buf, offset, byteLength) { + validateNumber(offset, 'offset') + if (buf[offset] === undefined || buf[offset + byteLength] === undefined) { + boundsError(offset, buf.length - (byteLength + 1)) + } +} + +function checkIntBI (value, min, max, buf, offset, byteLength) { + if (value > max || value < min) { + const n = typeof min === 'bigint' ? 'n' : '' + let range + if (byteLength > 3) { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}` + } else { + range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` + + `${(byteLength + 1) * 8 - 1}${n}` + } + } else { + range = `>= ${min}${n} and <= ${max}${n}` + } + throw new errors.ERR_OUT_OF_RANGE('value', range, value) + } + checkBounds(buf, offset, byteLength) +} + +function validateNumber (value, name) { + if (typeof value !== 'number') { + throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value) + } +} + +function boundsError (value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type) + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value) + } + + if (length < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS() + } + + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', + `>= ${type ? 1 : 0} and <= ${length}`, + value) +} + +// HELPER FUNCTIONS +// ================ + +const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function utf8ToBytes (string, units) { + units = units || Infinity + let codePoint + const length = string.length + let leadSurrogate = null + const bytes = [] + + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + let c, hi, lo + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + let i + for (i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +const hexSliceLookupTable = (function () { + const alphabet = '0123456789abcdef' + const table = new Array(256) + for (let i = 0; i < 16; ++i) { + const i16 = i * 16 + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})() + +// Return not function with Error if BigInt not supported +function defineBigIntMethod (fn) { + return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn +} + +function BufferBigIntNotDefined () { + throw new Error('BigInt not supported') +} + + +/***/ }), + +/***/ 251: +/***/ ((__unused_webpack_module, exports) => { + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + + +/***/ }), + +/***/ 6698: +/***/ ((module) => { + +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 + } + } +} + + +/***/ }), + +/***/ 3209: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"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 = (__webpack_require__(2861).Buffer) +var crypto = __webpack_require__.g.crypto || __webpack_require__.g.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 +} + + +/***/ }), + +/***/ 2861: +/***/ ((module, exports, __webpack_require__) => { + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(8287) +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) +} + + +/***/ }), + +/***/ 392: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2802: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +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 = __webpack_require__(7816) +exports.sha1 = __webpack_require__(3737) +exports.sha224 = __webpack_require__(6710) +exports.sha256 = __webpack_require__(4107) +exports.sha384 = __webpack_require__(2827) +exports.sha512 = __webpack_require__(2890) + + +/***/ }), + +/***/ 7816: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 3737: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 6710: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * 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 = __webpack_require__(6698) +var Sha256 = __webpack_require__(4107) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 4107: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2827: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698) +var SHA512 = __webpack_require__(2890) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2890: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 1293: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var parser = __webpack_require__(5546); +var compiler = __webpack_require__(2708); + +module.exports = { + parse: function(input) { + var nodes = parser.parse(input.toString()); + return compiler.compile(nodes); + } +}; + + +/***/ }), + +/***/ 2708: +/***/ ((module) => { + +"use strict"; + +function compile(nodes) { + var assignedPaths = []; + var valueAssignments = []; + var currentPath = ""; + var data = Object.create(null); + var context = data; + var arrayMode = false; + + return reduce(nodes); + + function reduce(nodes) { + var node; + for (var i = 0; i < nodes.length; i++) { + node = nodes[i]; + switch (node.type) { + case "Assign": + assign(node); + break; + case "ObjectPath": + setPath(node); + break; + case "ArrayPath": + addTableArray(node); + break; + } + } + + return data; + } + + function genError(err, line, col) { + var ex = new Error(err); + ex.line = line; + ex.column = col; + throw ex; + } + + function assign(node) { + var key = node.key; + var value = node.value; + var line = node.line; + var column = node.column; + + var fullPath; + if (currentPath) { + fullPath = currentPath + "." + key; + } else { + fullPath = key; + } + if (typeof context[key] !== "undefined") { + genError("Cannot redefine existing key '" + fullPath + "'.", line, column); + } + + context[key] = reduceValueNode(value); + + if (!pathAssigned(fullPath)) { + assignedPaths.push(fullPath); + valueAssignments.push(fullPath); + } + } + + + function pathAssigned(path) { + return assignedPaths.indexOf(path) !== -1; + } + + function reduceValueNode(node) { + if (node.type === "Array") { + return reduceArrayWithTypeChecking(node.value); + } else if (node.type === "InlineTable") { + return reduceInlineTableNode(node.value); + } else { + return node.value; + } + } + + function reduceInlineTableNode(values) { + var obj = Object.create(null); + for (var i = 0; i < values.length; i++) { + var val = values[i]; + if (val.value.type === "InlineTable") { + obj[val.key] = reduceInlineTableNode(val.value.value); + } else if (val.type === "InlineTableValue") { + obj[val.key] = reduceValueNode(val.value); + } + } + + return obj; + } + + function setPath(node) { + var path = node.value; + var quotedPath = path.map(quoteDottedString).join("."); + var line = node.line; + var column = node.column; + + if (pathAssigned(quotedPath)) { + genError("Cannot redefine existing key '" + path + "'.", line, column); + } + assignedPaths.push(quotedPath); + context = deepRef(data, path, Object.create(null), line, column); + currentPath = path; + } + + function addTableArray(node) { + var path = node.value; + var quotedPath = path.map(quoteDottedString).join("."); + var line = node.line; + var column = node.column; + + if (!pathAssigned(quotedPath)) { + assignedPaths.push(quotedPath); + } + assignedPaths = assignedPaths.filter(function(p) { + return p.indexOf(quotedPath) !== 0; + }); + assignedPaths.push(quotedPath); + context = deepRef(data, path, [], line, column); + currentPath = quotedPath; + + if (context instanceof Array) { + var newObj = Object.create(null); + context.push(newObj); + context = newObj; + } else { + genError("Cannot redefine existing key '" + path + "'.", line, column); + } + } + + // Given a path 'a.b.c', create (as necessary) `start.a`, + // `start.a.b`, and `start.a.b.c`, assigning `value` to `start.a.b.c`. + // If `a` or `b` are arrays and have items in them, the last item in the + // array is used as the context for the next sub-path. + function deepRef(start, keys, value, line, column) { + var traversed = []; + var traversedPath = ""; + var path = keys.join("."); + var ctx = start; + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + traversed.push(key); + traversedPath = traversed.join("."); + if (typeof ctx[key] === "undefined") { + if (i === keys.length - 1) { + ctx[key] = value; + } else { + ctx[key] = Object.create(null); + } + } else if (i !== keys.length - 1 && valueAssignments.indexOf(traversedPath) > -1) { + // already a non-object value at key, can't be used as part of a new path + genError("Cannot redefine existing key '" + traversedPath + "'.", line, column); + } + + ctx = ctx[key]; + if (ctx instanceof Array && ctx.length && i < keys.length - 1) { + ctx = ctx[ctx.length - 1]; + } + } + + return ctx; + } + + function reduceArrayWithTypeChecking(array) { + // Ensure that all items in the array are of the same type + var firstType = null; + for (var i = 0; i < array.length; i++) { + var node = array[i]; + if (firstType === null) { + firstType = node.type; + } else { + if (node.type !== firstType) { + genError("Cannot add value of type " + node.type + " to array of type " + + firstType + ".", node.line, node.column); + } + } + } + + // Recursively reduce array of nodes into array of the nodes' values + return array.map(reduceValueNode); + } + + function quoteDottedString(str) { + if (str.indexOf(".") > -1) { + return "\"" + str + "\""; + } else { + return str; + } + } +} + +module.exports = { + compile: compile +}; + + +/***/ }), + +/***/ 5546: +/***/ ((module) => { + +module.exports = (function() { + /* + * Generated by PEG.js 0.8.0. + * + * http://pegjs.majda.cz/ + */ + + function peg$subclass(child, parent) { + function ctor() { this.constructor = child; } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + + function SyntaxError(message, expected, found, offset, line, column) { + this.message = message; + this.expected = expected; + this.found = found; + this.offset = offset; + this.line = line; + this.column = column; + + this.name = "SyntaxError"; + } + + peg$subclass(SyntaxError, Error); + + function parse(input) { + var options = arguments.length > 1 ? arguments[1] : {}, + + peg$FAILED = {}, + + peg$startRuleFunctions = { start: peg$parsestart }, + peg$startRuleFunction = peg$parsestart, + + peg$c0 = [], + peg$c1 = function() { return nodes }, + peg$c2 = peg$FAILED, + peg$c3 = "#", + peg$c4 = { type: "literal", value: "#", description: "\"#\"" }, + peg$c5 = void 0, + peg$c6 = { type: "any", description: "any character" }, + peg$c7 = "[", + peg$c8 = { type: "literal", value: "[", description: "\"[\"" }, + peg$c9 = "]", + peg$c10 = { type: "literal", value: "]", description: "\"]\"" }, + peg$c11 = function(name) { addNode(node('ObjectPath', name, line, column)) }, + peg$c12 = function(name) { addNode(node('ArrayPath', name, line, column)) }, + peg$c13 = function(parts, name) { return parts.concat(name) }, + peg$c14 = function(name) { return [name] }, + peg$c15 = function(name) { return name }, + peg$c16 = ".", + peg$c17 = { type: "literal", value: ".", description: "\".\"" }, + peg$c18 = "=", + peg$c19 = { type: "literal", value: "=", description: "\"=\"" }, + peg$c20 = function(key, value) { addNode(node('Assign', value, line, column, key)) }, + peg$c21 = function(chars) { return chars.join('') }, + peg$c22 = function(node) { return node.value }, + peg$c23 = "\"\"\"", + peg$c24 = { type: "literal", value: "\"\"\"", description: "\"\\\"\\\"\\\"\"" }, + peg$c25 = null, + peg$c26 = function(chars) { return node('String', chars.join(''), line, column) }, + peg$c27 = "\"", + peg$c28 = { type: "literal", value: "\"", description: "\"\\\"\"" }, + peg$c29 = "'''", + peg$c30 = { type: "literal", value: "'''", description: "\"'''\"" }, + peg$c31 = "'", + peg$c32 = { type: "literal", value: "'", description: "\"'\"" }, + peg$c33 = function(char) { return char }, + peg$c34 = function(char) { return char}, + peg$c35 = "\\", + peg$c36 = { type: "literal", value: "\\", description: "\"\\\\\"" }, + peg$c37 = function() { return '' }, + peg$c38 = "e", + peg$c39 = { type: "literal", value: "e", description: "\"e\"" }, + peg$c40 = "E", + peg$c41 = { type: "literal", value: "E", description: "\"E\"" }, + peg$c42 = function(left, right) { return node('Float', parseFloat(left + 'e' + right), line, column) }, + peg$c43 = function(text) { return node('Float', parseFloat(text), line, column) }, + peg$c44 = "+", + peg$c45 = { type: "literal", value: "+", description: "\"+\"" }, + peg$c46 = function(digits) { return digits.join('') }, + peg$c47 = "-", + peg$c48 = { type: "literal", value: "-", description: "\"-\"" }, + peg$c49 = function(digits) { return '-' + digits.join('') }, + peg$c50 = function(text) { return node('Integer', parseInt(text, 10), line, column) }, + peg$c51 = "true", + peg$c52 = { type: "literal", value: "true", description: "\"true\"" }, + peg$c53 = function() { return node('Boolean', true, line, column) }, + peg$c54 = "false", + peg$c55 = { type: "literal", value: "false", description: "\"false\"" }, + peg$c56 = function() { return node('Boolean', false, line, column) }, + peg$c57 = function() { return node('Array', [], line, column) }, + peg$c58 = function(value) { return node('Array', value ? [value] : [], line, column) }, + peg$c59 = function(values) { return node('Array', values, line, column) }, + peg$c60 = function(values, value) { return node('Array', values.concat(value), line, column) }, + peg$c61 = function(value) { return value }, + peg$c62 = ",", + peg$c63 = { type: "literal", value: ",", description: "\",\"" }, + peg$c64 = "{", + peg$c65 = { type: "literal", value: "{", description: "\"{\"" }, + peg$c66 = "}", + peg$c67 = { type: "literal", value: "}", description: "\"}\"" }, + peg$c68 = function(values) { return node('InlineTable', values, line, column) }, + peg$c69 = function(key, value) { return node('InlineTableValue', value, line, column, key) }, + peg$c70 = function(digits) { return "." + digits }, + peg$c71 = function(date) { return date.join('') }, + peg$c72 = ":", + peg$c73 = { type: "literal", value: ":", description: "\":\"" }, + peg$c74 = function(time) { return time.join('') }, + peg$c75 = "T", + peg$c76 = { type: "literal", value: "T", description: "\"T\"" }, + peg$c77 = "Z", + peg$c78 = { type: "literal", value: "Z", description: "\"Z\"" }, + peg$c79 = function(date, time) { return node('Date', new Date(date + "T" + time + "Z"), line, column) }, + peg$c80 = function(date, time) { return node('Date', new Date(date + "T" + time), line, column) }, + peg$c81 = /^[ \t]/, + peg$c82 = { type: "class", value: "[ \\t]", description: "[ \\t]" }, + peg$c83 = "\n", + peg$c84 = { type: "literal", value: "\n", description: "\"\\n\"" }, + peg$c85 = "\r", + peg$c86 = { type: "literal", value: "\r", description: "\"\\r\"" }, + peg$c87 = /^[0-9a-f]/i, + peg$c88 = { type: "class", value: "[0-9a-f]i", description: "[0-9a-f]i" }, + peg$c89 = /^[0-9]/, + peg$c90 = { type: "class", value: "[0-9]", description: "[0-9]" }, + peg$c91 = "_", + peg$c92 = { type: "literal", value: "_", description: "\"_\"" }, + peg$c93 = function() { return "" }, + peg$c94 = /^[A-Za-z0-9_\-]/, + peg$c95 = { type: "class", value: "[A-Za-z0-9_\\-]", description: "[A-Za-z0-9_\\-]" }, + peg$c96 = function(d) { return d.join('') }, + peg$c97 = "\\\"", + peg$c98 = { type: "literal", value: "\\\"", description: "\"\\\\\\\"\"" }, + peg$c99 = function() { return '"' }, + peg$c100 = "\\\\", + peg$c101 = { type: "literal", value: "\\\\", description: "\"\\\\\\\\\"" }, + peg$c102 = function() { return '\\' }, + peg$c103 = "\\b", + peg$c104 = { type: "literal", value: "\\b", description: "\"\\\\b\"" }, + peg$c105 = function() { return '\b' }, + peg$c106 = "\\t", + peg$c107 = { type: "literal", value: "\\t", description: "\"\\\\t\"" }, + peg$c108 = function() { return '\t' }, + peg$c109 = "\\n", + peg$c110 = { type: "literal", value: "\\n", description: "\"\\\\n\"" }, + peg$c111 = function() { return '\n' }, + peg$c112 = "\\f", + peg$c113 = { type: "literal", value: "\\f", description: "\"\\\\f\"" }, + peg$c114 = function() { return '\f' }, + peg$c115 = "\\r", + peg$c116 = { type: "literal", value: "\\r", description: "\"\\\\r\"" }, + peg$c117 = function() { return '\r' }, + peg$c118 = "\\U", + peg$c119 = { type: "literal", value: "\\U", description: "\"\\\\U\"" }, + peg$c120 = function(digits) { return convertCodePoint(digits.join('')) }, + peg$c121 = "\\u", + peg$c122 = { type: "literal", value: "\\u", description: "\"\\\\u\"" }, + + peg$currPos = 0, + peg$reportedPos = 0, + peg$cachedPos = 0, + peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }, + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$silentFails = 0, + + peg$cache = {}, + peg$result; + + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + + function text() { + return input.substring(peg$reportedPos, peg$currPos); + } + + function offset() { + return peg$reportedPos; + } + + function line() { + return peg$computePosDetails(peg$reportedPos).line; + } + + function column() { + return peg$computePosDetails(peg$reportedPos).column; + } + + function expected(description) { + throw peg$buildException( + null, + [{ type: "other", description: description }], + peg$reportedPos + ); + } + + function error(message) { + throw peg$buildException(message, null, peg$reportedPos); + } + + function peg$computePosDetails(pos) { + function advance(details, startPos, endPos) { + var p, ch; + + for (p = startPos; p < endPos; p++) { + ch = input.charAt(p); + if (ch === "\n") { + if (!details.seenCR) { details.line++; } + details.column = 1; + details.seenCR = false; + } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { + details.line++; + details.column = 1; + details.seenCR = true; + } else { + details.column++; + details.seenCR = false; + } + } + } + + if (peg$cachedPos !== pos) { + if (peg$cachedPos > pos) { + peg$cachedPos = 0; + peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }; + } + advance(peg$cachedPosDetails, peg$cachedPos, pos); + peg$cachedPos = pos; + } + + return peg$cachedPosDetails; + } + + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { return; } + + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + + peg$maxFailExpected.push(expected); + } + + function peg$buildException(message, expected, pos) { + function cleanupExpected(expected) { + var i = 1; + + expected.sort(function(a, b) { + if (a.description < b.description) { + return -1; + } else if (a.description > b.description) { + return 1; + } else { + return 0; + } + }); + + while (i < expected.length) { + if (expected[i - 1] === expected[i]) { + expected.splice(i, 1); + } else { + i++; + } + } + } + + function buildMessage(expected, found) { + function stringEscape(s) { + function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } + + return s + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\x08/g, '\\b') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\f/g, '\\f') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); }) + .replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); }) + .replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); }); + } + + var expectedDescs = new Array(expected.length), + expectedDesc, foundDesc, i; + + for (i = 0; i < expected.length; i++) { + expectedDescs[i] = expected[i].description; + } + + expectedDesc = expected.length > 1 + ? expectedDescs.slice(0, -1).join(", ") + + " or " + + expectedDescs[expected.length - 1] + : expectedDescs[0]; + + foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input"; + + return "Expected " + expectedDesc + " but " + foundDesc + " found."; + } + + var posDetails = peg$computePosDetails(pos), + found = pos < input.length ? input.charAt(pos) : null; + + if (expected !== null) { + cleanupExpected(expected); + } + + return new SyntaxError( + message !== null ? message : buildMessage(expected, found), + expected, + found, + pos, + posDetails.line, + posDetails.column + ); + } + + function peg$parsestart() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 0, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseline(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseline(); + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c1(); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseline() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 1, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parseexpression(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parsecomment(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parsecomment(); + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseNL(); + if (s6 !== peg$FAILED) { + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseNL(); + } + } else { + s5 = peg$c2; + } + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseNL(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseNL(); + } + } else { + s2 = peg$c2; + } + if (s2 === peg$FAILED) { + s2 = peg$parseEOF(); + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$parseNL(); + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseexpression() { + var s0; + + var key = peg$currPos * 49 + 2, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsecomment(); + if (s0 === peg$FAILED) { + s0 = peg$parsepath(); + if (s0 === peg$FAILED) { + s0 = peg$parsetablearray(); + if (s0 === peg$FAILED) { + s0 = peg$parseassignment(); + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsecomment() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 3, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c3; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c4); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNL(); + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = peg$c5; + } else { + peg$currPos = s4; + s4 = peg$c2; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } else { + peg$currPos = s3; + s3 = peg$c2; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNL(); + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = peg$c5; + } else { + peg$currPos = s4; + s4 = peg$c2; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsepath() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 4, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetable_key(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s5 = peg$c9; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c11(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetablearray() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + var key = peg$currPos * 49 + 5, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s2 = peg$c7; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parsetable_key(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s6 = peg$c9; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s7 = peg$c9; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s7 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c12(s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetable_key() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 6, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsedot_ended_table_key_part(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsedot_ended_table_key_part(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + s2 = peg$parsetable_key_part(); + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c13(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsetable_key_part(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c14(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetable_key_part() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 7, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsequoted_key(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedot_ended_table_key_part() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 8, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsequoted_key(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseassignment() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 9, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsekey(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c18; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parsevalue(); + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c20(s1, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsequoted_key(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c18; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parsevalue(); + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c20(s1, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsekey() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 10, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseASCII_BASIC(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseASCII_BASIC(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c21(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsequoted_key() { + var s0, s1; + + var key = peg$currPos * 49 + 11, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsedouble_quoted_single_line_string(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c22(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsesingle_quoted_single_line_string(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c22(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsevalue() { + var s0; + + var key = peg$currPos * 49 + 12, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsestring(); + if (s0 === peg$FAILED) { + s0 = peg$parsedatetime(); + if (s0 === peg$FAILED) { + s0 = peg$parsefloat(); + if (s0 === peg$FAILED) { + s0 = peg$parseinteger(); + if (s0 === peg$FAILED) { + s0 = peg$parseboolean(); + if (s0 === peg$FAILED) { + s0 = peg$parsearray(); + if (s0 === peg$FAILED) { + s0 = peg$parseinline_table(); + } + } + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsestring() { + var s0; + + var key = peg$currPos * 49 + 13, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsedouble_quoted_multiline_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsedouble_quoted_single_line_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsesingle_quoted_multiline_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsesingle_quoted_single_line_string(); + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedouble_quoted_multiline_string() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 14, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c23) { + s1 = peg$c23; + peg$currPos += 3; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsemultiline_string_char(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsemultiline_string_char(); + } + if (s3 !== peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c23) { + s4 = peg$c23; + peg$currPos += 3; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedouble_quoted_single_line_string() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 15, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c27; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsestring_char(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsestring_char(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c27; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesingle_quoted_multiline_string() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 16, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c29) { + s1 = peg$c29; + peg$currPos += 3; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsemultiline_literal_char(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsemultiline_literal_char(); + } + if (s3 !== peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c29) { + s4 = peg$c29; + peg$currPos += 3; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesingle_quoted_single_line_string() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 17, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseliteral_char(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseliteral_char(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c31; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsestring_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 18, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseESCAPED(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 34) { + s2 = peg$c27; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseliteral_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 19, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c31; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_string_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 20, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseESCAPED(); + if (s0 === peg$FAILED) { + s0 = peg$parsemultiline_string_delim(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c23) { + s2 = peg$c23; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c34(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_string_delim() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 21, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c35; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c36); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseNLS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseNLS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c37(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_literal_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 22, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c29) { + s2 = peg$c29; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefloat() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 23, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsefloat_text(); + if (s1 === peg$FAILED) { + s1 = peg$parseinteger_text(); + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 101) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 69) { + s2 = peg$c40; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c41); } + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseinteger_text(); + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c42(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsefloat_text(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c43(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefloat_text() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 24, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c44; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + if (s1 === peg$FAILED) { + s1 = peg$c25; + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseDIGITS(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGITS(); + if (s5 !== peg$FAILED) { + s3 = [s3, s4, s5]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c46(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 45) { + s1 = peg$c47; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseDIGITS(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGITS(); + if (s5 !== peg$FAILED) { + s3 = [s3, s4, s5]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c49(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinteger() { + var s0, s1; + + var key = peg$currPos * 49 + 25, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseinteger_text(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c50(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinteger_text() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 26, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c44; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + if (s1 === peg$FAILED) { + s1 = peg$c25; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + peg$silentFails--; + if (s4 === peg$FAILED) { + s3 = peg$c5; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c46(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 45) { + s1 = peg$c47; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + peg$silentFails--; + if (s4 === peg$FAILED) { + s3 = peg$c5; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c49(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseboolean() { + var s0, s1; + + var key = peg$currPos * 49 + 27, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c51) { + s1 = peg$c51; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c52); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c53(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c54) { + s1 = peg$c54; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c55); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c56(); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 28, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_sep(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_sep(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c57(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsearray_value(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c58(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_value_list(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_value_list(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c59(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_value_list(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_value_list(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$parsearray_value(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s4 = peg$c9; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c60(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_value() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 29, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsearray_sep(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsearray_sep(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsevalue(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsearray_sep(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsearray_sep(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c61(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_value_list() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 30, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsearray_sep(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsearray_sep(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsevalue(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsearray_sep(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsearray_sep(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s4 = peg$c62; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c63); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parsearray_sep(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parsearray_sep(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c61(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_sep() { + var s0; + + var key = peg$currPos * 49 + 31, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseS(); + if (s0 === peg$FAILED) { + s0 = peg$parseNL(); + if (s0 === peg$FAILED) { + s0 = peg$parsecomment(); + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinline_table() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 32, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 123) { + s1 = peg$c64; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c65); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseinline_table_assignment(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseinline_table_assignment(); + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s5 = peg$c66; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c67); } + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c68(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinline_table_assignment() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 33, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s4 = peg$c18; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parsevalue(); + if (s6 !== peg$FAILED) { + s7 = []; + s8 = peg$parseS(); + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseS(); + } + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c62; + peg$currPos++; + } else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c63); } + } + if (s8 !== peg$FAILED) { + s9 = []; + s10 = peg$parseS(); + while (s10 !== peg$FAILED) { + s9.push(s10); + s10 = peg$parseS(); + } + if (s9 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c69(s2, s6); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s4 = peg$c18; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parsevalue(); + if (s6 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c69(s2, s6); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesecfragment() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 34, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c16; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDIGITS(); + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c70(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedate() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11; + + var key = peg$currPos * 49 + 35, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT_OR_UNDER(); + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s6 = peg$c47; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseDIGIT_OR_UNDER(); + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s9 = peg$c47; + peg$currPos++; + } else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s9 !== peg$FAILED) { + s10 = peg$parseDIGIT_OR_UNDER(); + if (s10 !== peg$FAILED) { + s11 = peg$parseDIGIT_OR_UNDER(); + if (s11 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c71(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetime() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 36, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c72; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT_OR_UNDER(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c72; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + s9 = peg$parseDIGIT_OR_UNDER(); + if (s9 !== peg$FAILED) { + s10 = peg$parsesecfragment(); + if (s10 === peg$FAILED) { + s10 = peg$c25; + } + if (s10 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c74(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetime_with_offset() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16; + + var key = peg$currPos * 49 + 37, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c72; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT_OR_UNDER(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c72; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + s9 = peg$parseDIGIT_OR_UNDER(); + if (s9 !== peg$FAILED) { + s10 = peg$parsesecfragment(); + if (s10 === peg$FAILED) { + s10 = peg$c25; + } + if (s10 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s11 = peg$c47; + peg$currPos++; + } else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s11 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s11 = peg$c44; + peg$currPos++; + } else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + } + if (s11 !== peg$FAILED) { + s12 = peg$parseDIGIT_OR_UNDER(); + if (s12 !== peg$FAILED) { + s13 = peg$parseDIGIT_OR_UNDER(); + if (s13 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s14 = peg$c72; + peg$currPos++; + } else { + s14 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s14 !== peg$FAILED) { + s15 = peg$parseDIGIT_OR_UNDER(); + if (s15 !== peg$FAILED) { + s16 = peg$parseDIGIT_OR_UNDER(); + if (s16 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c74(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedatetime() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 38, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsedate(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 84) { + s2 = peg$c75; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c76); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetime(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 90) { + s4 = peg$c77; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c78); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c79(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsedate(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 84) { + s2 = peg$c75; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c76); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetime_with_offset(); + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c80(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseS() { + var s0; + + var key = peg$currPos * 49 + 39, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c81.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c82); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseNL() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 40, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (input.charCodeAt(peg$currPos) === 10) { + s0 = peg$c83; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c84); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 13) { + s1 = peg$c85; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c86); } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 10) { + s2 = peg$c83; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c84); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseNLS() { + var s0; + + var key = peg$currPos * 49 + 41, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseNL(); + if (s0 === peg$FAILED) { + s0 = peg$parseS(); + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseEOF() { + var s0, s1; + + var key = peg$currPos * 49 + 42, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + peg$silentFails++; + if (input.length > peg$currPos) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + peg$silentFails--; + if (s1 === peg$FAILED) { + s0 = peg$c5; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseHEX() { + var s0; + + var key = peg$currPos * 49 + 43, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c87.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c88); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseDIGIT_OR_UNDER() { + var s0, s1; + + var key = peg$currPos * 49 + 44, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c89.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c90); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s1 = peg$c91; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c92); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c93(); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseASCII_BASIC() { + var s0; + + var key = peg$currPos * 49 + 45, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c94.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c95); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseDIGITS() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 46, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c96(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseESCAPED() { + var s0, s1; + + var key = peg$currPos * 49 + 47, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c97) { + s1 = peg$c97; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c98); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c99(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c100) { + s1 = peg$c100; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c102(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c103) { + s1 = peg$c103; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c104); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c105(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c106) { + s1 = peg$c106; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c107); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c108(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c109) { + s1 = peg$c109; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c110); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c111(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c112) { + s1 = peg$c112; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c113); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c114(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c115) { + s1 = peg$c115; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c116); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c117(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$parseESCAPED_UNICODE(); + } + } + } + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseESCAPED_UNICODE() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 48, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c118) { + s1 = peg$c118; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c119); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseHEX(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEX(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHEX(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHEX(); + if (s6 !== peg$FAILED) { + s7 = peg$parseHEX(); + if (s7 !== peg$FAILED) { + s8 = peg$parseHEX(); + if (s8 !== peg$FAILED) { + s9 = peg$parseHEX(); + if (s9 !== peg$FAILED) { + s10 = peg$parseHEX(); + if (s10 !== peg$FAILED) { + s3 = [s3, s4, s5, s6, s7, s8, s9, s10]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c120(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c121) { + s1 = peg$c121; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c122); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseHEX(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEX(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHEX(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHEX(); + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c120(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + + var nodes = []; + + function genError(err, line, col) { + var ex = new Error(err); + ex.line = line; + ex.column = col; + throw ex; + } + + function addNode(node) { + nodes.push(node); + } + + function node(type, value, line, column, key) { + var obj = { type: type, value: value, line: line(), column: column() }; + if (key) obj.key = key; + return obj; + } + + function convertCodePoint(str, line, col) { + var num = parseInt("0x" + str); + + if ( + !isFinite(num) || + Math.floor(num) != num || + num < 0 || + num > 0x10FFFF || + (num > 0xD7FF && num < 0xE000) + ) { + genError("Invalid Unicode escape code: " + str, line, col); + } else { + return fromCodePoint(num); + } + } + + function fromCodePoint() { + var MAX_SIZE = 0x4000; + var codeUnits = []; + var highSurrogate; + var lowSurrogate; + var index = -1; + var length = arguments.length; + if (!length) { + return ''; + } + var result = ''; + while (++index < length) { + var codePoint = Number(arguments[index]); + if (codePoint <= 0xFFFF) { // BMP code point + codeUnits.push(codePoint); + } else { // Astral code point; split in surrogate halves + // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + codePoint -= 0x10000; + highSurrogate = (codePoint >> 10) + 0xD800; + lowSurrogate = (codePoint % 0x400) + 0xDC00; + codeUnits.push(highSurrogate, lowSurrogate); + } + if (index + 1 == length || codeUnits.length > MAX_SIZE) { + result += String.fromCharCode.apply(null, codeUnits); + codeUnits.length = 0; + } + } + return result; + } + + + peg$result = peg$startRuleFunction(); + + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail({ type: "end", description: "end of input" }); + } + + throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos); + } + } + + return { + SyntaxError: SyntaxError, + parse: parse + }; +})(); + + +/***/ }), + +/***/ 1430: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * IPv6 Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (root) { + 'use strict'; + + /* + var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156"; + var _out = IPv6.best(_in); + var _expected = "fe80::204:61ff:fe9d:f156"; + + console.log(_in, _out, _expected, _out === _expected); + */ + + // save current IPv6 variable, if any + var _IPv6 = root && root.IPv6; + + function bestPresentation(address) { + // based on: + // Javascript to test an IPv6 address for proper format, and to + // present the "best text representation" according to IETF Draft RFC at + // http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04 + // 8 Feb 2010 Rich Brown, Dartware, LLC + // Please feel free to use this code as long as you provide a link to + // http://www.intermapper.com + // http://intermapper.com/support/tools/IPV6-Validator.aspx + // http://download.dartware.com/thirdparty/ipv6validator.js + + var _address = address.toLowerCase(); + var segments = _address.split(':'); + var length = segments.length; + var total = 8; + + // trim colons (:: or ::a:b:c… or …a:b:c::) + if (segments[0] === '' && segments[1] === '' && segments[2] === '') { + // must have been :: + // remove first two items + segments.shift(); + segments.shift(); + } else if (segments[0] === '' && segments[1] === '') { + // must have been ::xxxx + // remove the first item + segments.shift(); + } else if (segments[length - 1] === '' && segments[length - 2] === '') { + // must have been xxxx:: + segments.pop(); + } + + length = segments.length; + + // adjust total segments for IPv4 trailer + if (segments[length - 1].indexOf('.') !== -1) { + // found a "." which means IPv4 + total = 7; + } + + // fill empty segments them with "0000" + var pos; + for (pos = 0; pos < length; pos++) { + if (segments[pos] === '') { + break; + } + } + + if (pos < total) { + segments.splice(pos, 1, '0000'); + while (segments.length < total) { + segments.splice(pos, 0, '0000'); + } + } + + // strip leading zeros + var _segments; + for (var i = 0; i < total; i++) { + _segments = segments[i].split(''); + for (var j = 0; j < 3 ; j++) { + if (_segments[0] === '0' && _segments.length > 1) { + _segments.splice(0,1); + } else { + break; + } + } + + segments[i] = _segments.join(''); + } + + // find longest sequence of zeroes and coalesce them into one segment + var best = -1; + var _best = 0; + var _current = 0; + var current = -1; + var inzeroes = false; + // i; already declared + + for (i = 0; i < total; i++) { + if (inzeroes) { + if (segments[i] === '0') { + _current += 1; + } else { + inzeroes = false; + if (_current > _best) { + best = current; + _best = _current; + } + } + } else { + if (segments[i] === '0') { + inzeroes = true; + current = i; + _current = 1; + } + } + } + + if (_current > _best) { + best = current; + _best = _current; + } + + if (_best > 1) { + segments.splice(best, _best, ''); + } + + length = segments.length; + + // assemble remaining segments + var result = ''; + if (segments[0] === '') { + result = ':'; + } + + for (i = 0; i < length; i++) { + result += segments[i]; + if (i === length - 1) { + break; + } + + result += ':'; + } + + if (segments[length - 1] === '') { + result += ':'; + } + + return result; + } + + function noConflict() { + /*jshint validthis: true */ + if (root.IPv6 === this) { + root.IPv6 = _IPv6; + } + + return this; + } + + return { + best: bestPresentation, + noConflict: noConflict + }; +})); + + +/***/ }), + +/***/ 4704: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * Second Level Domain (SLD) Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (root) { + 'use strict'; + + // save current SecondLevelDomains variable, if any + var _SecondLevelDomains = root && root.SecondLevelDomains; + + var SLD = { + // list of known Second Level Domains + // converted list of SLDs from https://github.com/gavingmiller/second-level-domains + // ---- + // publicsuffix.org is more current and actually used by a couple of browsers internally. + // downside is it also contains domains like "dyndns.org" - which is fine for the security + // issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js + // ---- + list: { + 'ac':' com gov mil net org ', + 'ae':' ac co gov mil name net org pro sch ', + 'af':' com edu gov net org ', + 'al':' com edu gov mil net org ', + 'ao':' co ed gv it og pb ', + 'ar':' com edu gob gov int mil net org tur ', + 'at':' ac co gv or ', + 'au':' asn com csiro edu gov id net org ', + 'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ', + 'bb':' biz co com edu gov info net org store tv ', + 'bh':' biz cc com edu gov info net org ', + 'bn':' com edu gov net org ', + 'bo':' com edu gob gov int mil net org tv ', + 'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ', + 'bs':' com edu gov net org ', + 'bz':' du et om ov rg ', + 'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ', + 'ck':' biz co edu gen gov info net org ', + 'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ', + 'co':' com edu gov mil net nom org ', + 'cr':' ac c co ed fi go or sa ', + 'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ', + 'do':' art com edu gob gov mil net org sld web ', + 'dz':' art asso com edu gov net org pol ', + 'ec':' com edu fin gov info med mil net org pro ', + 'eg':' com edu eun gov mil name net org sci ', + 'er':' com edu gov ind mil net org rochest w ', + 'es':' com edu gob nom org ', + 'et':' biz com edu gov info name net org ', + 'fj':' ac biz com info mil name net org pro ', + 'fk':' ac co gov net nom org ', + 'fr':' asso com f gouv nom prd presse tm ', + 'gg':' co net org ', + 'gh':' com edu gov mil org ', + 'gn':' ac com gov net org ', + 'gr':' com edu gov mil net org ', + 'gt':' com edu gob ind mil net org ', + 'gu':' com edu gov net org ', + 'hk':' com edu gov idv net org ', + 'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ', + 'id':' ac co go mil net or sch web ', + 'il':' ac co gov idf k12 muni net org ', + 'in':' ac co edu ernet firm gen gov i ind mil net nic org res ', + 'iq':' com edu gov i mil net org ', + 'ir':' ac co dnssec gov i id net org sch ', + 'it':' edu gov ', + 'je':' co net org ', + 'jo':' com edu gov mil name net org sch ', + 'jp':' ac ad co ed go gr lg ne or ', + 'ke':' ac co go info me mobi ne or sc ', + 'kh':' com edu gov mil net org per ', + 'ki':' biz com de edu gov info mob net org tel ', + 'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ', + 'kn':' edu gov net org ', + 'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ', + 'kw':' com edu gov net org ', + 'ky':' com edu gov net org ', + 'kz':' com edu gov mil net org ', + 'lb':' com edu gov net org ', + 'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ', + 'lr':' com edu gov net org ', + 'lv':' asn com conf edu gov id mil net org ', + 'ly':' com edu gov id med net org plc sch ', + 'ma':' ac co gov m net org press ', + 'mc':' asso tm ', + 'me':' ac co edu gov its net org priv ', + 'mg':' com edu gov mil nom org prd tm ', + 'mk':' com edu gov inf name net org pro ', + 'ml':' com edu gov net org presse ', + 'mn':' edu gov org ', + 'mo':' com edu gov net org ', + 'mt':' com edu gov net org ', + 'mv':' aero biz com coop edu gov info int mil museum name net org pro ', + 'mw':' ac co com coop edu gov int museum net org ', + 'mx':' com edu gob net org ', + 'my':' com edu gov mil name net org sch ', + 'nf':' arts com firm info net other per rec store web ', + 'ng':' biz com edu gov mil mobi name net org sch ', + 'ni':' ac co com edu gob mil net nom org ', + 'np':' com edu gov mil net org ', + 'nr':' biz com edu gov info net org ', + 'om':' ac biz co com edu gov med mil museum net org pro sch ', + 'pe':' com edu gob mil net nom org sld ', + 'ph':' com edu gov i mil net ngo org ', + 'pk':' biz com edu fam gob gok gon gop gos gov net org web ', + 'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ', + 'pr':' ac biz com edu est gov info isla name net org pro prof ', + 'ps':' com edu gov net org plo sec ', + 'pw':' belau co ed go ne or ', + 'ro':' arts com firm info nom nt org rec store tm www ', + 'rs':' ac co edu gov in org ', + 'sb':' com edu gov net org ', + 'sc':' com edu gov net org ', + 'sh':' co com edu gov net nom org ', + 'sl':' com edu gov net org ', + 'st':' co com consulado edu embaixada gov mil net org principe saotome store ', + 'sv':' com edu gob org red ', + 'sz':' ac co org ', + 'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ', + 'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ', + 'tw':' club com ebiz edu game gov idv mil net org ', + 'mu':' ac co com gov net or org ', + 'mz':' ac co edu gov org ', + 'na':' co com ', + 'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ', + 'pa':' abo ac com edu gob ing med net nom org sld ', + 'pt':' com edu gov int net nome org publ ', + 'py':' com edu gov mil net org ', + 'qa':' com edu gov mil net org ', + 're':' asso com nom ', + 'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ', + 'rw':' ac co com edu gouv gov int mil net ', + 'sa':' com edu gov med net org pub sch ', + 'sd':' com edu gov info med net org tv ', + 'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ', + 'sg':' com edu gov idn net org per ', + 'sn':' art com edu gouv org perso univ ', + 'sy':' com edu gov mil net news org ', + 'th':' ac co go in mi net or ', + 'tj':' ac biz co com edu go gov info int mil name net nic org test web ', + 'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ', + 'tz':' ac co go ne or ', + 'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ', + 'ug':' ac co go ne or org sc ', + 'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ', + 'us':' dni fed isa kids nsn ', + 'uy':' com edu gub mil net org ', + 've':' co com edu gob info mil net org web ', + 'vi':' co com k12 net org ', + 'vn':' ac biz com edu gov health info int name net org pro ', + 'ye':' co com gov ltd me net org plc ', + 'yu':' ac co edu gov org ', + 'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ', + 'zm':' ac co com edu gov net org sch ', + // https://en.wikipedia.org/wiki/CentralNic#Second-level_domains + 'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ', + 'net': 'gb jp se uk ', + 'org': 'ae', + 'de': 'com ' + }, + // gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost + // in both performance and memory footprint. No initialization required. + // http://jsperf.com/uri-js-sld-regex-vs-binary-search/4 + // Following methods use lastIndexOf() rather than array.split() in order + // to avoid any memory allocations. + has: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return false; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) { + return false; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return false; + } + return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0; + }, + is: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return false; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset >= 0) { + return false; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return false; + } + return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0; + }, + get: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return null; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) { + return null; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return null; + } + if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) { + return null; + } + return domain.slice(sldOffset+1); + }, + noConflict: function(){ + if (root.SecondLevelDomains === this) { + root.SecondLevelDomains = _SecondLevelDomains; + } + return this; + } + }; + + return SLD; +})); + + +/***/ }), + +/***/ 4193: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(__webpack_require__(9340), __webpack_require__(1430), __webpack_require__(4704)); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(9340), __webpack_require__(1430), __webpack_require__(4704)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (punycode, IPv6, SLD, root) { + 'use strict'; + /*global location, escape, unescape */ + // FIXME: v2.0.0 renamce non-camelCase properties to uppercase + /*jshint camelcase: false */ + + // save current URI variable, if any + var _URI = root && root.URI; + + function URI(url, base) { + var _urlSupplied = arguments.length >= 1; + var _baseSupplied = arguments.length >= 2; + + // Allow instantiation without the 'new' keyword + if (!(this instanceof URI)) { + if (_urlSupplied) { + if (_baseSupplied) { + return new URI(url, base); + } + + return new URI(url); + } + + return new URI(); + } + + if (url === undefined) { + if (_urlSupplied) { + throw new TypeError('undefined is not a valid argument for URI'); + } + + if (typeof location !== 'undefined') { + url = location.href + ''; + } else { + url = ''; + } + } + + if (url === null) { + if (_urlSupplied) { + throw new TypeError('null is not a valid argument for URI'); + } + } + + this.href(url); + + // resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor + if (base !== undefined) { + return this.absoluteTo(base); + } + + return this; + } + + function isInteger(value) { + return /^[0-9]+$/.test(value); + } + + URI.version = '1.19.11'; + + var p = URI.prototype; + var hasOwn = Object.prototype.hasOwnProperty; + + function escapeRegEx(string) { + // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963 + return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); + } + + function getType(value) { + // IE8 doesn't return [Object Undefined] but [Object Object] for undefined value + if (value === undefined) { + return 'Undefined'; + } + + return String(Object.prototype.toString.call(value)).slice(8, -1); + } + + function isArray(obj) { + return getType(obj) === 'Array'; + } + + function filterArrayValues(data, value) { + var lookup = {}; + var i, length; + + if (getType(value) === 'RegExp') { + lookup = null; + } else if (isArray(value)) { + for (i = 0, length = value.length; i < length; i++) { + lookup[value[i]] = true; + } + } else { + lookup[value] = true; + } + + for (i = 0, length = data.length; i < length; i++) { + /*jshint laxbreak: true */ + var _match = lookup && lookup[data[i]] !== undefined + || !lookup && value.test(data[i]); + /*jshint laxbreak: false */ + if (_match) { + data.splice(i, 1); + length--; + i--; + } + } + + return data; + } + + function arrayContains(list, value) { + var i, length; + + // value may be string, number, array, regexp + if (isArray(value)) { + // Note: this can be optimized to O(n) (instead of current O(m * n)) + for (i = 0, length = value.length; i < length; i++) { + if (!arrayContains(list, value[i])) { + return false; + } + } + + return true; + } + + var _type = getType(value); + for (i = 0, length = list.length; i < length; i++) { + if (_type === 'RegExp') { + if (typeof list[i] === 'string' && list[i].match(value)) { + return true; + } + } else if (list[i] === value) { + return true; + } + } + + return false; + } + + function arraysEqual(one, two) { + if (!isArray(one) || !isArray(two)) { + return false; + } + + // arrays can't be equal if they have different amount of content + if (one.length !== two.length) { + return false; + } + + one.sort(); + two.sort(); + + for (var i = 0, l = one.length; i < l; i++) { + if (one[i] !== two[i]) { + return false; + } + } + + return true; + } + + function trimSlashes(text) { + var trim_expression = /^\/+|\/+$/g; + return text.replace(trim_expression, ''); + } + + URI._parts = function() { + return { + protocol: null, + username: null, + password: null, + hostname: null, + urn: null, + port: null, + path: null, + query: null, + fragment: null, + // state + preventInvalidHostname: URI.preventInvalidHostname, + duplicateQueryParameters: URI.duplicateQueryParameters, + escapeQuerySpace: URI.escapeQuerySpace + }; + }; + // state: throw on invalid hostname + // see https://github.com/medialize/URI.js/pull/345 + // and https://github.com/medialize/URI.js/issues/354 + URI.preventInvalidHostname = false; + // state: allow duplicate query parameters (a=1&a=1) + URI.duplicateQueryParameters = false; + // state: replaces + with %20 (space in query strings) + URI.escapeQuerySpace = true; + // static properties + URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i; + URI.idn_expression = /[^a-z0-9\._-]/i; + URI.punycode_expression = /(xn--)/i; + // well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care? + URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; + // credits to Rich Brown + // source: http://forums.intermapper.com/viewtopic.php?p=1096#1096 + // specification: http://www.ietf.org/rfc/rfc4291.txt + URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/; + // expression used is "gruber revised" (@gruber v2) determined to be the + // best solution in a regex-golf we did a couple of ages ago at + // * http://mathiasbynens.be/demo/url-regex + // * http://rodneyrehm.de/t/url-regex.html + URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig; + URI.findUri = { + // valid "scheme://" or "www." + start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi, + // everything up to the next whitespace + end: /[\s\r\n]|$/, + // trim trailing punctuation captured by end RegExp + trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/, + // balanced parens inclusion (), [], {}, <> + parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g, + }; + URI.leading_whitespace_expression = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/ + // https://infra.spec.whatwg.org/#ascii-tab-or-newline + URI.ascii_tab_whitespace = /[\u0009\u000A\u000D]+/g + // http://www.iana.org/assignments/uri-schemes.html + // http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports + URI.defaultPorts = { + http: '80', + https: '443', + ftp: '21', + gopher: '70', + ws: '80', + wss: '443' + }; + // list of protocols which always require a hostname + URI.hostProtocols = [ + 'http', + 'https' + ]; + + // allowed hostname characters according to RFC 3986 + // ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded + // I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _ + URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/; + // map DOM Elements to their URI attribute + URI.domAttributes = { + 'a': 'href', + 'blockquote': 'cite', + 'link': 'href', + 'base': 'href', + 'script': 'src', + 'form': 'action', + 'img': 'src', + 'area': 'href', + 'iframe': 'src', + 'embed': 'src', + 'source': 'src', + 'track': 'src', + 'input': 'src', // but only if type="image" + 'audio': 'src', + 'video': 'src' + }; + URI.getDomAttribute = function(node) { + if (!node || !node.nodeName) { + return undefined; + } + + var nodeName = node.nodeName.toLowerCase(); + // should only expose src for type="image" + if (nodeName === 'input' && node.type !== 'image') { + return undefined; + } + + return URI.domAttributes[nodeName]; + }; + + function escapeForDumbFirefox36(value) { + // https://github.com/medialize/URI.js/issues/91 + return escape(value); + } + + // encoding / decoding according to RFC3986 + function strictEncodeURIComponent(string) { + // see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent + return encodeURIComponent(string) + .replace(/[!'()*]/g, escapeForDumbFirefox36) + .replace(/\*/g, '%2A'); + } + URI.encode = strictEncodeURIComponent; + URI.decode = decodeURIComponent; + URI.iso8859 = function() { + URI.encode = escape; + URI.decode = unescape; + }; + URI.unicode = function() { + URI.encode = strictEncodeURIComponent; + URI.decode = decodeURIComponent; + }; + URI.characters = { + pathname: { + encode: { + // RFC3986 2.1: For consistency, URI producers and normalizers should + // use uppercase hexadecimal digits for all percent-encodings. + expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig, + map: { + // -._~!'()* + '%24': '$', + '%26': '&', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=', + '%3A': ':', + '%40': '@' + } + }, + decode: { + expression: /[\/\?#]/g, + map: { + '/': '%2F', + '?': '%3F', + '#': '%23' + } + } + }, + reserved: { + encode: { + // RFC3986 2.1: For consistency, URI producers and normalizers should + // use uppercase hexadecimal digits for all percent-encodings. + expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig, + map: { + // gen-delims + '%3A': ':', + '%2F': '/', + '%3F': '?', + '%23': '#', + '%5B': '[', + '%5D': ']', + '%40': '@', + // sub-delims + '%21': '!', + '%24': '$', + '%26': '&', + '%27': '\'', + '%28': '(', + '%29': ')', + '%2A': '*', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=' + } + } + }, + urnpath: { + // The characters under `encode` are the characters called out by RFC 2141 as being acceptable + // for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but + // these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also + // note that the colon character is not featured in the encoding map; this is because URI.js + // gives the colons in URNs semantic meaning as the delimiters of path segements, and so it + // should not appear unencoded in a segment itself. + // See also the note above about RFC3986 and capitalalized hex digits. + encode: { + expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig, + map: { + '%21': '!', + '%24': '$', + '%27': '\'', + '%28': '(', + '%29': ')', + '%2A': '*', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=', + '%40': '@' + } + }, + // These characters are the characters called out by RFC2141 as "reserved" characters that + // should never appear in a URN, plus the colon character (see note above). + decode: { + expression: /[\/\?#:]/g, + map: { + '/': '%2F', + '?': '%3F', + '#': '%23', + ':': '%3A' + } + } + } + }; + URI.encodeQuery = function(string, escapeQuerySpace) { + var escaped = URI.encode(string + ''); + if (escapeQuerySpace === undefined) { + escapeQuerySpace = URI.escapeQuerySpace; + } + + return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped; + }; + URI.decodeQuery = function(string, escapeQuerySpace) { + string += ''; + if (escapeQuerySpace === undefined) { + escapeQuerySpace = URI.escapeQuerySpace; + } + + try { + return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string); + } catch(e) { + // we're not going to mess with weird encodings, + // give up and return the undecoded original string + // see https://github.com/medialize/URI.js/issues/87 + // see https://github.com/medialize/URI.js/issues/92 + return string; + } + }; + // generate encode/decode path functions + var _parts = {'encode':'encode', 'decode':'decode'}; + var _part; + var generateAccessor = function(_group, _part) { + return function(string) { + try { + return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) { + return URI.characters[_group][_part].map[c]; + }); + } catch (e) { + // we're not going to mess with weird encodings, + // give up and return the undecoded original string + // see https://github.com/medialize/URI.js/issues/87 + // see https://github.com/medialize/URI.js/issues/92 + return string; + } + }; + }; + + for (_part in _parts) { + URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]); + URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]); + } + + var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) { + return function(string) { + // Why pass in names of functions, rather than the function objects themselves? The + // definitions of some functions (but in particular, URI.decode) will occasionally change due + // to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure + // that the functions we use here are "fresh". + var actualCodingFunc; + if (!_innerCodingFuncName) { + actualCodingFunc = URI[_codingFuncName]; + } else { + actualCodingFunc = function(string) { + return URI[_codingFuncName](URI[_innerCodingFuncName](string)); + }; + } + + var segments = (string + '').split(_sep); + + for (var i = 0, length = segments.length; i < length; i++) { + segments[i] = actualCodingFunc(segments[i]); + } + + return segments.join(_sep); + }; + }; + + // This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions. + URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment'); + URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment'); + URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode'); + URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode'); + + URI.encodeReserved = generateAccessor('reserved', 'encode'); + + URI.parse = function(string, parts) { + var pos; + if (!parts) { + parts = { + preventInvalidHostname: URI.preventInvalidHostname + }; + } + + string = string.replace(URI.leading_whitespace_expression, '') + // https://infra.spec.whatwg.org/#ascii-tab-or-newline + string = string.replace(URI.ascii_tab_whitespace, '') + + // [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment] + + // extract fragment + pos = string.indexOf('#'); + if (pos > -1) { + // escaping? + parts.fragment = string.substring(pos + 1) || null; + string = string.substring(0, pos); + } + + // extract query + pos = string.indexOf('?'); + if (pos > -1) { + // escaping? + parts.query = string.substring(pos + 1) || null; + string = string.substring(0, pos); + } + + // slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws) + string = string.replace(/^(https?|ftp|wss?)?:+[/\\]*/i, '$1://'); + // slashes and backslashes have lost all meaning for scheme relative URLs + string = string.replace(/^[/\\]{2,}/i, '//'); + + // extract protocol + if (string.substring(0, 2) === '//') { + // relative-scheme + parts.protocol = null; + string = string.substring(2); + // extract "user:pass@host:port" + string = URI.parseAuthority(string, parts); + } else { + pos = string.indexOf(':'); + if (pos > -1) { + parts.protocol = string.substring(0, pos) || null; + if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) { + // : may be within the path + parts.protocol = undefined; + } else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') { + string = string.substring(pos + 3); + + // extract "user:pass@host:port" + string = URI.parseAuthority(string, parts); + } else { + string = string.substring(pos + 1); + parts.urn = true; + } + } + } + + // what's left must be the path + parts.path = string; + + // and we're done + return parts; + }; + URI.parseHost = function(string, parts) { + if (!string) { + string = ''; + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124 + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + // https://github.com/medialize/URI.js/pull/233 + string = string.replace(/\\/g, '/'); + + // extract host:port + var pos = string.indexOf('/'); + var bracketPos; + var t; + + if (pos === -1) { + pos = string.length; + } + + if (string.charAt(0) === '[') { + // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6 + // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts + // IPv6+port in the format [2001:db8::1]:80 (for the time being) + bracketPos = string.indexOf(']'); + parts.hostname = string.substring(1, bracketPos) || null; + parts.port = string.substring(bracketPos + 2, pos) || null; + if (parts.port === '/') { + parts.port = null; + } + } else { + var firstColon = string.indexOf(':'); + var firstSlash = string.indexOf('/'); + var nextColon = string.indexOf(':', firstColon + 1); + if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) { + // IPv6 host contains multiple colons - but no port + // this notation is actually not allowed by RFC 3986, but we're a liberal parser + parts.hostname = string.substring(0, pos) || null; + parts.port = null; + } else { + t = string.substring(0, pos).split(':'); + parts.hostname = t[0] || null; + parts.port = t[1] || null; + } + } + + if (parts.hostname && string.substring(pos).charAt(0) !== '/') { + pos++; + string = '/' + string; + } + + if (parts.preventInvalidHostname) { + URI.ensureValidHostname(parts.hostname, parts.protocol); + } + + if (parts.port) { + URI.ensureValidPort(parts.port); + } + + return string.substring(pos) || '/'; + }; + URI.parseAuthority = function(string, parts) { + string = URI.parseUserinfo(string, parts); + return URI.parseHost(string, parts); + }; + URI.parseUserinfo = function(string, parts) { + // extract username:password + var _string = string + var firstBackSlash = string.indexOf('\\'); + if (firstBackSlash !== -1) { + string = string.replace(/\\/g, '/') + } + var firstSlash = string.indexOf('/'); + var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1); + var t; + + // authority@ must come before /path or \path + if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) { + t = string.substring(0, pos).split(':'); + parts.username = t[0] ? URI.decode(t[0]) : null; + t.shift(); + parts.password = t[0] ? URI.decode(t.join(':')) : null; + string = _string.substring(pos + 1); + } else { + parts.username = null; + parts.password = null; + } + + return string; + }; + URI.parseQuery = function(string, escapeQuerySpace) { + if (!string) { + return {}; + } + + // throw out the funky business - "?"[name"="value"&"]+ + string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, ''); + + if (!string) { + return {}; + } + + var items = {}; + var splits = string.split('&'); + var length = splits.length; + var v, name, value; + + for (var i = 0; i < length; i++) { + v = splits[i].split('='); + name = URI.decodeQuery(v.shift(), escapeQuerySpace); + // no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters + value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null; + + if (name === '__proto__') { + // ignore attempt at exploiting JavaScript internals + continue; + } else if (hasOwn.call(items, name)) { + if (typeof items[name] === 'string' || items[name] === null) { + items[name] = [items[name]]; + } + + items[name].push(value); + } else { + items[name] = value; + } + } + + return items; + }; + + URI.build = function(parts) { + var t = ''; + var requireAbsolutePath = false + + if (parts.protocol) { + t += parts.protocol + ':'; + } + + if (!parts.urn && (t || parts.hostname)) { + t += '//'; + requireAbsolutePath = true + } + + t += (URI.buildAuthority(parts) || ''); + + if (typeof parts.path === 'string') { + if (parts.path.charAt(0) !== '/' && requireAbsolutePath) { + t += '/'; + } + + t += parts.path; + } + + if (typeof parts.query === 'string' && parts.query) { + t += '?' + parts.query; + } + + if (typeof parts.fragment === 'string' && parts.fragment) { + t += '#' + parts.fragment; + } + return t; + }; + URI.buildHost = function(parts) { + var t = ''; + + if (!parts.hostname) { + return ''; + } else if (URI.ip6_expression.test(parts.hostname)) { + t += '[' + parts.hostname + ']'; + } else { + t += parts.hostname; + } + + if (parts.port) { + t += ':' + parts.port; + } + + return t; + }; + URI.buildAuthority = function(parts) { + return URI.buildUserinfo(parts) + URI.buildHost(parts); + }; + URI.buildUserinfo = function(parts) { + var t = ''; + + if (parts.username) { + t += URI.encode(parts.username); + } + + if (parts.password) { + t += ':' + URI.encode(parts.password); + } + + if (t) { + t += '@'; + } + + return t; + }; + URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) { + // according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html + // being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed + // the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax! + // URI.js treats the query string as being application/x-www-form-urlencoded + // see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type + + var t = ''; + var unique, key, i, length; + for (key in data) { + if (key === '__proto__') { + // ignore attempt at exploiting JavaScript internals + continue; + } else if (hasOwn.call(data, key)) { + if (isArray(data[key])) { + unique = {}; + for (i = 0, length = data[key].length; i < length; i++) { + if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) { + t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace); + if (duplicateQueryParameters !== true) { + unique[data[key][i] + ''] = true; + } + } + } + } else if (data[key] !== undefined) { + t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace); + } + } + } + + return t.substring(1); + }; + URI.buildQueryParameter = function(name, value, escapeQuerySpace) { + // http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded + // don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization + return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : ''); + }; + + URI.addQuery = function(data, name, value) { + if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + URI.addQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + if (data[name] === undefined) { + data[name] = value; + return; + } else if (typeof data[name] === 'string') { + data[name] = [data[name]]; + } + + if (!isArray(value)) { + value = [value]; + } + + data[name] = (data[name] || []).concat(value); + } else { + throw new TypeError('URI.addQuery() accepts an object, string as the name parameter'); + } + }; + + URI.setQuery = function(data, name, value) { + if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + URI.setQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + data[name] = value === undefined ? null : value; + } else { + throw new TypeError('URI.setQuery() accepts an object, string as the name parameter'); + } + }; + + URI.removeQuery = function(data, name, value) { + var i, length, key; + + if (isArray(name)) { + for (i = 0, length = name.length; i < length; i++) { + data[name[i]] = undefined; + } + } else if (getType(name) === 'RegExp') { + for (key in data) { + if (name.test(key)) { + data[key] = undefined; + } + } + } else if (typeof name === 'object') { + for (key in name) { + if (hasOwn.call(name, key)) { + URI.removeQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + if (value !== undefined) { + if (getType(value) === 'RegExp') { + if (!isArray(data[name]) && value.test(data[name])) { + data[name] = undefined; + } else { + data[name] = filterArrayValues(data[name], value); + } + } else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) { + data[name] = undefined; + } else if (isArray(data[name])) { + data[name] = filterArrayValues(data[name], value); + } + } else { + data[name] = undefined; + } + } else { + throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter'); + } + }; + URI.hasQuery = function(data, name, value, withinArray) { + switch (getType(name)) { + case 'String': + // Nothing to do here + break; + + case 'RegExp': + for (var key in data) { + if (hasOwn.call(data, key)) { + if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) { + return true; + } + } + } + + return false; + + case 'Object': + for (var _key in name) { + if (hasOwn.call(name, _key)) { + if (!URI.hasQuery(data, _key, name[_key])) { + return false; + } + } + } + + return true; + + default: + throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter'); + } + + switch (getType(value)) { + case 'Undefined': + // true if exists (but may be empty) + return name in data; // data[name] !== undefined; + + case 'Boolean': + // true if exists and non-empty + var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]); + return value === _booly; + + case 'Function': + // allow complex comparison + return !!value(data[name], name, data); + + case 'Array': + if (!isArray(data[name])) { + return false; + } + + var op = withinArray ? arrayContains : arraysEqual; + return op(data[name], value); + + case 'RegExp': + if (!isArray(data[name])) { + return Boolean(data[name] && data[name].match(value)); + } + + if (!withinArray) { + return false; + } + + return arrayContains(data[name], value); + + case 'Number': + value = String(value); + /* falls through */ + case 'String': + if (!isArray(data[name])) { + return data[name] === value; + } + + if (!withinArray) { + return false; + } + + return arrayContains(data[name], value); + + default: + throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter'); + } + }; + + + URI.joinPaths = function() { + var input = []; + var segments = []; + var nonEmptySegments = 0; + + for (var i = 0; i < arguments.length; i++) { + var url = new URI(arguments[i]); + input.push(url); + var _segments = url.segment(); + for (var s = 0; s < _segments.length; s++) { + if (typeof _segments[s] === 'string') { + segments.push(_segments[s]); + } + + if (_segments[s]) { + nonEmptySegments++; + } + } + } + + if (!segments.length || !nonEmptySegments) { + return new URI(''); + } + + var uri = new URI('').segment(segments); + + if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') { + uri.path('/' + uri.path()); + } + + return uri.normalize(); + }; + + URI.commonPath = function(one, two) { + var length = Math.min(one.length, two.length); + var pos; + + // find first non-matching character + for (pos = 0; pos < length; pos++) { + if (one.charAt(pos) !== two.charAt(pos)) { + pos--; + break; + } + } + + if (pos < 1) { + return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : ''; + } + + // revert to last / + if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') { + pos = one.substring(0, pos).lastIndexOf('/'); + } + + return one.substring(0, pos + 1); + }; + + URI.withinString = function(string, callback, options) { + options || (options = {}); + var _start = options.start || URI.findUri.start; + var _end = options.end || URI.findUri.end; + var _trim = options.trim || URI.findUri.trim; + var _parens = options.parens || URI.findUri.parens; + var _attributeOpen = /[a-z0-9-]=["']?$/i; + + _start.lastIndex = 0; + while (true) { + var match = _start.exec(string); + if (!match) { + break; + } + + var start = match.index; + if (options.ignoreHtml) { + // attribut(e=["']?$) + var attributeOpen = string.slice(Math.max(start - 3, 0), start); + if (attributeOpen && _attributeOpen.test(attributeOpen)) { + continue; + } + } + + var end = start + string.slice(start).search(_end); + var slice = string.slice(start, end); + // make sure we include well balanced parens + var parensEnd = -1; + while (true) { + var parensMatch = _parens.exec(slice); + if (!parensMatch) { + break; + } + + var parensMatchEnd = parensMatch.index + parensMatch[0].length; + parensEnd = Math.max(parensEnd, parensMatchEnd); + } + + if (parensEnd > -1) { + slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, ''); + } else { + slice = slice.replace(_trim, ''); + } + + if (slice.length <= match[0].length) { + // the extract only contains the starting marker of a URI, + // e.g. "www" or "http://" + continue; + } + + if (options.ignore && options.ignore.test(slice)) { + continue; + } + + end = start + slice.length; + var result = callback(slice, start, end, string); + if (result === undefined) { + _start.lastIndex = end; + continue; + } + + result = String(result); + string = string.slice(0, start) + result + string.slice(end); + _start.lastIndex = start + result.length; + } + + _start.lastIndex = 0; + return string; + }; + + URI.ensureValidHostname = function(v, protocol) { + // Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986) + // they are not part of DNS and therefore ignored by URI.js + + var hasHostname = !!v; // not null and not an empty string + var hasProtocol = !!protocol; + var rejectEmptyHostname = false; + + if (hasProtocol) { + rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol); + } + + if (rejectEmptyHostname && !hasHostname) { + throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol); + } else if (v && v.match(URI.invalid_hostname_characters)) { + // test punycode + if (!punycode) { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available'); + } + if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]'); + } + } + }; + + URI.ensureValidPort = function (v) { + if (!v) { + return; + } + + var port = Number(v); + if (isInteger(port) && (port > 0) && (port < 65536)) { + return; + } + + throw new TypeError('Port "' + v + '" is not a valid port'); + }; + + // noConflict + URI.noConflict = function(removeAll) { + if (removeAll) { + var unconflicted = { + URI: this.noConflict() + }; + + if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') { + unconflicted.URITemplate = root.URITemplate.noConflict(); + } + + if (root.IPv6 && typeof root.IPv6.noConflict === 'function') { + unconflicted.IPv6 = root.IPv6.noConflict(); + } + + if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') { + unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict(); + } + + return unconflicted; + } else if (root.URI === this) { + root.URI = _URI; + } + + return this; + }; + + p.build = function(deferBuild) { + if (deferBuild === true) { + this._deferred_build = true; + } else if (deferBuild === undefined || this._deferred_build) { + this._string = URI.build(this._parts); + this._deferred_build = false; + } + + return this; + }; + + p.clone = function() { + return new URI(this); + }; + + p.valueOf = p.toString = function() { + return this.build(false)._string; + }; + + + function generateSimpleAccessor(_part){ + return function(v, build) { + if (v === undefined) { + return this._parts[_part] || ''; + } else { + this._parts[_part] = v || null; + this.build(!build); + return this; + } + }; + } + + function generatePrefixAccessor(_part, _key){ + return function(v, build) { + if (v === undefined) { + return this._parts[_part] || ''; + } else { + if (v !== null) { + v = v + ''; + if (v.charAt(0) === _key) { + v = v.substring(1); + } + } + + this._parts[_part] = v; + this.build(!build); + return this; + } + }; + } + + p.protocol = generateSimpleAccessor('protocol'); + p.username = generateSimpleAccessor('username'); + p.password = generateSimpleAccessor('password'); + p.hostname = generateSimpleAccessor('hostname'); + p.port = generateSimpleAccessor('port'); + p.query = generatePrefixAccessor('query', '?'); + p.fragment = generatePrefixAccessor('fragment', '#'); + + p.search = function(v, build) { + var t = this.query(v, build); + return typeof t === 'string' && t.length ? ('?' + t) : t; + }; + p.hash = function(v, build) { + var t = this.fragment(v, build); + return typeof t === 'string' && t.length ? ('#' + t) : t; + }; + + p.pathname = function(v, build) { + if (v === undefined || v === true) { + var res = this._parts.path || (this._parts.hostname ? '/' : ''); + return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res; + } else { + if (this._parts.urn) { + this._parts.path = v ? URI.recodeUrnPath(v) : ''; + } else { + this._parts.path = v ? URI.recodePath(v) : '/'; + } + this.build(!build); + return this; + } + }; + p.path = p.pathname; + p.href = function(href, build) { + var key; + + if (href === undefined) { + return this.toString(); + } + + this._string = ''; + this._parts = URI._parts(); + + var _URI = href instanceof URI; + var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname); + if (href.nodeName) { + var attribute = URI.getDomAttribute(href); + href = href[attribute] || ''; + _object = false; + } + + // window.location is reported to be an object, but it's not the sort + // of object we're looking for: + // * location.protocol ends with a colon + // * location.query != object.search + // * location.hash != object.fragment + // simply serializing the unknown object should do the trick + // (for location, not for everything...) + if (!_URI && _object && href.pathname !== undefined) { + href = href.toString(); + } + + if (typeof href === 'string' || href instanceof String) { + this._parts = URI.parse(String(href), this._parts); + } else if (_URI || _object) { + var src = _URI ? href._parts : href; + for (key in src) { + if (key === 'query') { continue; } + if (hasOwn.call(this._parts, key)) { + this._parts[key] = src[key]; + } + } + if (src.query) { + this.query(src.query, false); + } + } else { + throw new TypeError('invalid input'); + } + + this.build(!build); + return this; + }; + + // identification accessors + p.is = function(what) { + var ip = false; + var ip4 = false; + var ip6 = false; + var name = false; + var sld = false; + var idn = false; + var punycode = false; + var relative = !this._parts.urn; + + if (this._parts.hostname) { + relative = false; + ip4 = URI.ip4_expression.test(this._parts.hostname); + ip6 = URI.ip6_expression.test(this._parts.hostname); + ip = ip4 || ip6; + name = !ip; + sld = name && SLD && SLD.has(this._parts.hostname); + idn = name && URI.idn_expression.test(this._parts.hostname); + punycode = name && URI.punycode_expression.test(this._parts.hostname); + } + + switch (what.toLowerCase()) { + case 'relative': + return relative; + + case 'absolute': + return !relative; + + // hostname identification + case 'domain': + case 'name': + return name; + + case 'sld': + return sld; + + case 'ip': + return ip; + + case 'ip4': + case 'ipv4': + case 'inet4': + return ip4; + + case 'ip6': + case 'ipv6': + case 'inet6': + return ip6; + + case 'idn': + return idn; + + case 'url': + return !this._parts.urn; + + case 'urn': + return !!this._parts.urn; + + case 'punycode': + return punycode; + } + + return null; + }; + + // component specific input validation + var _protocol = p.protocol; + var _port = p.port; + var _hostname = p.hostname; + + p.protocol = function(v, build) { + if (v) { + // accept trailing :// + v = v.replace(/:(\/\/)?$/, ''); + + if (!v.match(URI.protocol_expression)) { + throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]'); + } + } + + return _protocol.call(this, v, build); + }; + p.scheme = p.protocol; + p.port = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v !== undefined) { + if (v === 0) { + v = null; + } + + if (v) { + v += ''; + if (v.charAt(0) === ':') { + v = v.substring(1); + } + + URI.ensureValidPort(v); + } + } + return _port.call(this, v, build); + }; + p.hostname = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v !== undefined) { + var x = { preventInvalidHostname: this._parts.preventInvalidHostname }; + var res = URI.parseHost(v, x); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + v = x.hostname; + if (this._parts.preventInvalidHostname) { + URI.ensureValidHostname(v, this._parts.protocol); + } + } + + return _hostname.call(this, v, build); + }; + + // compound accessors + p.origin = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + var protocol = this.protocol(); + var authority = this.authority(); + if (!authority) { + return ''; + } + + return (protocol ? protocol + '://' : '') + this.authority(); + } else { + var origin = URI(v); + this + .protocol(origin.protocol()) + .authority(origin.authority()) + .build(!build); + return this; + } + }; + p.host = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + return this._parts.hostname ? URI.buildHost(this._parts) : ''; + } else { + var res = URI.parseHost(v, this._parts); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + this.build(!build); + return this; + } + }; + p.authority = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + return this._parts.hostname ? URI.buildAuthority(this._parts) : ''; + } else { + var res = URI.parseAuthority(v, this._parts); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + this.build(!build); + return this; + } + }; + p.userinfo = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + var t = URI.buildUserinfo(this._parts); + return t ? t.substring(0, t.length -1) : t; + } else { + if (v[v.length-1] !== '@') { + v += '@'; + } + + URI.parseUserinfo(v, this._parts); + this.build(!build); + return this; + } + }; + p.resource = function(v, build) { + var parts; + + if (v === undefined) { + return this.path() + this.search() + this.hash(); + } + + parts = URI.parse(v); + this._parts.path = parts.path; + this._parts.query = parts.query; + this._parts.fragment = parts.fragment; + this.build(!build); + return this; + }; + + // fraction accessors + p.subdomain = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + // convenience, return "www" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + // grab domain and add another segment + var end = this._parts.hostname.length - this.domain().length - 1; + return this._parts.hostname.substring(0, end) || ''; + } else { + var e = this._parts.hostname.length - this.domain().length; + var sub = this._parts.hostname.substring(0, e); + var replace = new RegExp('^' + escapeRegEx(sub)); + + if (v && v.charAt(v.length - 1) !== '.') { + v += '.'; + } + + if (v.indexOf(':') !== -1) { + throw new TypeError('Domains cannot contain colons'); + } + + if (v) { + URI.ensureValidHostname(v, this._parts.protocol); + } + + this._parts.hostname = this._parts.hostname.replace(replace, v); + this.build(!build); + return this; + } + }; + p.domain = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v === 'boolean') { + build = v; + v = undefined; + } + + // convenience, return "example.org" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + // if hostname consists of 1 or 2 segments, it must be the domain + var t = this._parts.hostname.match(/\./g); + if (t && t.length < 2) { + return this._parts.hostname; + } + + // grab tld and add another segment + var end = this._parts.hostname.length - this.tld(build).length - 1; + end = this._parts.hostname.lastIndexOf('.', end -1) + 1; + return this._parts.hostname.substring(end) || ''; + } else { + if (!v) { + throw new TypeError('cannot set domain empty'); + } + + if (v.indexOf(':') !== -1) { + throw new TypeError('Domains cannot contain colons'); + } + + URI.ensureValidHostname(v, this._parts.protocol); + + if (!this._parts.hostname || this.is('IP')) { + this._parts.hostname = v; + } else { + var replace = new RegExp(escapeRegEx(this.domain()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.tld = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v === 'boolean') { + build = v; + v = undefined; + } + + // return "org" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + var pos = this._parts.hostname.lastIndexOf('.'); + var tld = this._parts.hostname.substring(pos + 1); + + if (build !== true && SLD && SLD.list[tld.toLowerCase()]) { + return SLD.get(this._parts.hostname) || tld; + } + + return tld; + } else { + var replace; + + if (!v) { + throw new TypeError('cannot set TLD empty'); + } else if (v.match(/[^a-zA-Z0-9-]/)) { + if (SLD && SLD.is(v)) { + replace = new RegExp(escapeRegEx(this.tld()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } else { + throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]'); + } + } else if (!this._parts.hostname || this.is('IP')) { + throw new ReferenceError('cannot set TLD on non-domain host'); + } else { + replace = new RegExp(escapeRegEx(this.tld()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.directory = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined || v === true) { + if (!this._parts.path && !this._parts.hostname) { + return ''; + } + + if (this._parts.path === '/') { + return '/'; + } + + var end = this._parts.path.length - this.filename().length - 1; + var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : ''); + + return v ? URI.decodePath(res) : res; + + } else { + var e = this._parts.path.length - this.filename().length; + var directory = this._parts.path.substring(0, e); + var replace = new RegExp('^' + escapeRegEx(directory)); + + // fully qualifier directories begin with a slash + if (!this.is('relative')) { + if (!v) { + v = '/'; + } + + if (v.charAt(0) !== '/') { + v = '/' + v; + } + } + + // directories always end with a slash + if (v && v.charAt(v.length - 1) !== '/') { + v += '/'; + } + + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + this.build(!build); + return this; + } + }; + p.filename = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v !== 'string') { + if (!this._parts.path || this._parts.path === '/') { + return ''; + } + + var pos = this._parts.path.lastIndexOf('/'); + var res = this._parts.path.substring(pos+1); + + return v ? URI.decodePathSegment(res) : res; + } else { + var mutatedDirectory = false; + + if (v.charAt(0) === '/') { + v = v.substring(1); + } + + if (v.match(/\.?\//)) { + mutatedDirectory = true; + } + + var replace = new RegExp(escapeRegEx(this.filename()) + '$'); + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + + if (mutatedDirectory) { + this.normalizePath(build); + } else { + this.build(!build); + } + + return this; + } + }; + p.suffix = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined || v === true) { + if (!this._parts.path || this._parts.path === '/') { + return ''; + } + + var filename = this.filename(); + var pos = filename.lastIndexOf('.'); + var s, res; + + if (pos === -1) { + return ''; + } + + // suffix may only contain alnum characters (yup, I made this up.) + s = filename.substring(pos+1); + res = (/^[a-z0-9%]+$/i).test(s) ? s : ''; + return v ? URI.decodePathSegment(res) : res; + } else { + if (v.charAt(0) === '.') { + v = v.substring(1); + } + + var suffix = this.suffix(); + var replace; + + if (!suffix) { + if (!v) { + return this; + } + + this._parts.path += '.' + URI.recodePath(v); + } else if (!v) { + replace = new RegExp(escapeRegEx('.' + suffix) + '$'); + } else { + replace = new RegExp(escapeRegEx(suffix) + '$'); + } + + if (replace) { + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.segment = function(segment, v, build) { + var separator = this._parts.urn ? ':' : '/'; + var path = this.path(); + var absolute = path.substring(0, 1) === '/'; + var segments = path.split(separator); + + if (segment !== undefined && typeof segment !== 'number') { + build = v; + v = segment; + segment = undefined; + } + + if (segment !== undefined && typeof segment !== 'number') { + throw new Error('Bad segment "' + segment + '", must be 0-based integer'); + } + + if (absolute) { + segments.shift(); + } + + if (segment < 0) { + // allow negative indexes to address from the end + segment = Math.max(segments.length + segment, 0); + } + + if (v === undefined) { + /*jshint laxbreak: true */ + return segment === undefined + ? segments + : segments[segment]; + /*jshint laxbreak: false */ + } else if (segment === null || segments[segment] === undefined) { + if (isArray(v)) { + segments = []; + // collapse empty elements within array + for (var i=0, l=v.length; i < l; i++) { + if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) { + continue; + } + + if (segments.length && !segments[segments.length -1].length) { + segments.pop(); + } + + segments.push(trimSlashes(v[i])); + } + } else if (v || typeof v === 'string') { + v = trimSlashes(v); + if (segments[segments.length -1] === '') { + // empty trailing elements have to be overwritten + // to prevent results such as /foo//bar + segments[segments.length -1] = v; + } else { + segments.push(v); + } + } + } else { + if (v) { + segments[segment] = trimSlashes(v); + } else { + segments.splice(segment, 1); + } + } + + if (absolute) { + segments.unshift(''); + } + + return this.path(segments.join(separator), build); + }; + p.segmentCoded = function(segment, v, build) { + var segments, i, l; + + if (typeof segment !== 'number') { + build = v; + v = segment; + segment = undefined; + } + + if (v === undefined) { + segments = this.segment(segment, v, build); + if (!isArray(segments)) { + segments = segments !== undefined ? URI.decode(segments) : undefined; + } else { + for (i = 0, l = segments.length; i < l; i++) { + segments[i] = URI.decode(segments[i]); + } + } + + return segments; + } + + if (!isArray(v)) { + v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v; + } else { + for (i = 0, l = v.length; i < l; i++) { + v[i] = URI.encode(v[i]); + } + } + + return this.segment(segment, v, build); + }; + + // mutating query string + var q = p.query; + p.query = function(v, build) { + if (v === true) { + return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + } else if (typeof v === 'function') { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + var result = v.call(this, data); + this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + this.build(!build); + return this; + } else if (v !== undefined && typeof v !== 'string') { + this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + this.build(!build); + return this; + } else { + return q.call(this, v, build); + } + }; + p.setQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + + if (typeof name === 'string' || name instanceof String) { + data[name] = value !== undefined ? value : null; + } else if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + data[key] = name[key]; + } + } + } else { + throw new TypeError('URI.addQuery() accepts an object, string as the name parameter'); + } + + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.addQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + URI.addQuery(data, name, value === undefined ? null : value); + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.removeQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + URI.removeQuery(data, name, value); + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.hasQuery = function(name, value, withinArray) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + return URI.hasQuery(data, name, value, withinArray); + }; + p.setSearch = p.setQuery; + p.addSearch = p.addQuery; + p.removeSearch = p.removeQuery; + p.hasSearch = p.hasQuery; + + // sanitizing URLs + p.normalize = function() { + if (this._parts.urn) { + return this + .normalizeProtocol(false) + .normalizePath(false) + .normalizeQuery(false) + .normalizeFragment(false) + .build(); + } + + return this + .normalizeProtocol(false) + .normalizeHostname(false) + .normalizePort(false) + .normalizePath(false) + .normalizeQuery(false) + .normalizeFragment(false) + .build(); + }; + p.normalizeProtocol = function(build) { + if (typeof this._parts.protocol === 'string') { + this._parts.protocol = this._parts.protocol.toLowerCase(); + this.build(!build); + } + + return this; + }; + p.normalizeHostname = function(build) { + if (this._parts.hostname) { + if (this.is('IDN') && punycode) { + this._parts.hostname = punycode.toASCII(this._parts.hostname); + } else if (this.is('IPv6') && IPv6) { + this._parts.hostname = IPv6.best(this._parts.hostname); + } + + this._parts.hostname = this._parts.hostname.toLowerCase(); + this.build(!build); + } + + return this; + }; + p.normalizePort = function(build) { + // remove port of it's the protocol's default + if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) { + this._parts.port = null; + this.build(!build); + } + + return this; + }; + p.normalizePath = function(build) { + var _path = this._parts.path; + if (!_path) { + return this; + } + + if (this._parts.urn) { + this._parts.path = URI.recodeUrnPath(this._parts.path); + this.build(!build); + return this; + } + + if (this._parts.path === '/') { + return this; + } + + _path = URI.recodePath(_path); + + var _was_relative; + var _leadingParents = ''; + var _parent, _pos; + + // handle relative paths + if (_path.charAt(0) !== '/') { + _was_relative = true; + _path = '/' + _path; + } + + // handle relative files (as opposed to directories) + if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') { + _path += '/'; + } + + // resolve simples + _path = _path + .replace(/(\/(\.\/)+)|(\/\.$)/g, '/') + .replace(/\/{2,}/g, '/'); + + // remember leading parents + if (_was_relative) { + _leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || ''; + if (_leadingParents) { + _leadingParents = _leadingParents[0]; + } + } + + // resolve parents + while (true) { + _parent = _path.search(/\/\.\.(\/|$)/); + if (_parent === -1) { + // no more ../ to resolve + break; + } else if (_parent === 0) { + // top level cannot be relative, skip it + _path = _path.substring(3); + continue; + } + + _pos = _path.substring(0, _parent).lastIndexOf('/'); + if (_pos === -1) { + _pos = _parent; + } + _path = _path.substring(0, _pos) + _path.substring(_parent + 3); + } + + // revert to relative + if (_was_relative && this.is('relative')) { + _path = _leadingParents + _path.substring(1); + } + + this._parts.path = _path; + this.build(!build); + return this; + }; + p.normalizePathname = p.normalizePath; + p.normalizeQuery = function(build) { + if (typeof this._parts.query === 'string') { + if (!this._parts.query.length) { + this._parts.query = null; + } else { + this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace)); + } + + this.build(!build); + } + + return this; + }; + p.normalizeFragment = function(build) { + if (!this._parts.fragment) { + this._parts.fragment = null; + this.build(!build); + } + + return this; + }; + p.normalizeSearch = p.normalizeQuery; + p.normalizeHash = p.normalizeFragment; + + p.iso8859 = function() { + // expect unicode input, iso8859 output + var e = URI.encode; + var d = URI.decode; + + URI.encode = escape; + URI.decode = decodeURIComponent; + try { + this.normalize(); + } finally { + URI.encode = e; + URI.decode = d; + } + return this; + }; + + p.unicode = function() { + // expect iso8859 input, unicode output + var e = URI.encode; + var d = URI.decode; + + URI.encode = strictEncodeURIComponent; + URI.decode = unescape; + try { + this.normalize(); + } finally { + URI.encode = e; + URI.decode = d; + } + return this; + }; + + p.readable = function() { + var uri = this.clone(); + // removing username, password, because they shouldn't be displayed according to RFC 3986 + uri.username('').password('').normalize(); + var t = ''; + if (uri._parts.protocol) { + t += uri._parts.protocol + '://'; + } + + if (uri._parts.hostname) { + if (uri.is('punycode') && punycode) { + t += punycode.toUnicode(uri._parts.hostname); + if (uri._parts.port) { + t += ':' + uri._parts.port; + } + } else { + t += uri.host(); + } + } + + if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') { + t += '/'; + } + + t += uri.path(true); + if (uri._parts.query) { + var q = ''; + for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) { + var kv = (qp[i] || '').split('='); + q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace) + .replace(/&/g, '%26'); + + if (kv[1] !== undefined) { + q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace) + .replace(/&/g, '%26'); + } + } + t += '?' + q.substring(1); + } + + t += URI.decodeQuery(uri.hash(), true); + return t; + }; + + // resolving relative and absolute URLs + p.absoluteTo = function(base) { + var resolved = this.clone(); + var properties = ['protocol', 'username', 'password', 'hostname', 'port']; + var basedir, i, p; + + if (this._parts.urn) { + throw new Error('URNs do not have any generally defined hierarchical components'); + } + + if (!(base instanceof URI)) { + base = new URI(base); + } + + if (resolved._parts.protocol) { + // Directly returns even if this._parts.hostname is empty. + return resolved; + } else { + resolved._parts.protocol = base._parts.protocol; + } + + if (this._parts.hostname) { + return resolved; + } + + for (i = 0; (p = properties[i]); i++) { + resolved._parts[p] = base._parts[p]; + } + + if (!resolved._parts.path) { + resolved._parts.path = base._parts.path; + if (!resolved._parts.query) { + resolved._parts.query = base._parts.query; + } + } else { + if (resolved._parts.path.substring(-2) === '..') { + resolved._parts.path += '/'; + } + + if (resolved.path().charAt(0) !== '/') { + basedir = base.directory(); + basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : ''; + resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path; + resolved.normalizePath(); + } + } + + resolved.build(); + return resolved; + }; + p.relativeTo = function(base) { + var relative = this.clone().normalize(); + var relativeParts, baseParts, common, relativePath, basePath; + + if (relative._parts.urn) { + throw new Error('URNs do not have any generally defined hierarchical components'); + } + + base = new URI(base).normalize(); + relativeParts = relative._parts; + baseParts = base._parts; + relativePath = relative.path(); + basePath = base.path(); + + if (relativePath.charAt(0) !== '/') { + throw new Error('URI is already relative'); + } + + if (basePath.charAt(0) !== '/') { + throw new Error('Cannot calculate a URI relative to another relative URI'); + } + + if (relativeParts.protocol === baseParts.protocol) { + relativeParts.protocol = null; + } + + if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) { + return relative.build(); + } + + if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) { + return relative.build(); + } + + if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) { + relativeParts.hostname = null; + relativeParts.port = null; + } else { + return relative.build(); + } + + if (relativePath === basePath) { + relativeParts.path = ''; + return relative.build(); + } + + // determine common sub path + common = URI.commonPath(relativePath, basePath); + + // If the paths have nothing in common, return a relative URL with the absolute path. + if (!common) { + return relative.build(); + } + + var parents = baseParts.path + .substring(common.length) + .replace(/[^\/]*$/, '') + .replace(/.*?\//g, '../'); + + relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './'; + + return relative.build(); + }; + + // comparing URIs + p.equals = function(uri) { + var one = this.clone(); + var two = new URI(uri); + var one_map = {}; + var two_map = {}; + var checked = {}; + var one_query, two_query, key; + + one.normalize(); + two.normalize(); + + // exact match + if (one.toString() === two.toString()) { + return true; + } + + // extract query string + one_query = one.query(); + two_query = two.query(); + one.query(''); + two.query(''); + + // definitely not equal if not even non-query parts match + if (one.toString() !== two.toString()) { + return false; + } + + // query parameters have the same length, even if they're permuted + if (one_query.length !== two_query.length) { + return false; + } + + one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace); + two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace); + + for (key in one_map) { + if (hasOwn.call(one_map, key)) { + if (!isArray(one_map[key])) { + if (one_map[key] !== two_map[key]) { + return false; + } + } else if (!arraysEqual(one_map[key], two_map[key])) { + return false; + } + + checked[key] = true; + } + } + + for (key in two_map) { + if (hasOwn.call(two_map, key)) { + if (!checked[key]) { + // two contains a parameter not present in one + return false; + } + } + } + + return true; + }; + + // state + p.preventInvalidHostname = function(v) { + this._parts.preventInvalidHostname = !!v; + return this; + }; + + p.duplicateQueryParameters = function(v) { + this._parts.duplicateQueryParameters = !!v; + return this; + }; + + p.escapeQuerySpace = function(v) { + this._parts.escapeQuerySpace = !!v; + return this; + }; + + return URI; +})); + + +/***/ }), + +/***/ 9127: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * URI Template Support - http://tools.ietf.org/html/rfc6570 + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(__webpack_require__(4193)); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4193)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (URI, root) { + 'use strict'; + // FIXME: v2.0.0 renamce non-camelCase properties to uppercase + /*jshint camelcase: false */ + + // save current URITemplate variable, if any + var _URITemplate = root && root.URITemplate; + + var hasOwn = Object.prototype.hasOwnProperty; + function URITemplate(expression) { + // serve from cache where possible + if (URITemplate._cache[expression]) { + return URITemplate._cache[expression]; + } + + // Allow instantiation without the 'new' keyword + if (!(this instanceof URITemplate)) { + return new URITemplate(expression); + } + + this.expression = expression; + URITemplate._cache[expression] = this; + return this; + } + + function Data(data) { + this.data = data; + this.cache = {}; + } + + var p = URITemplate.prototype; + // list of operators and their defined options + var operators = { + // Simple string expansion + '' : { + prefix: '', + separator: ',', + named: false, + empty_name_separator: false, + encode : 'encode' + }, + // Reserved character strings + '+' : { + prefix: '', + separator: ',', + named: false, + empty_name_separator: false, + encode : 'encodeReserved' + }, + // Fragment identifiers prefixed by '#' + '#' : { + prefix: '#', + separator: ',', + named: false, + empty_name_separator: false, + encode : 'encodeReserved' + }, + // Name labels or extensions prefixed by '.' + '.' : { + prefix: '.', + separator: '.', + named: false, + empty_name_separator: false, + encode : 'encode' + }, + // Path segments prefixed by '/' + '/' : { + prefix: '/', + separator: '/', + named: false, + empty_name_separator: false, + encode : 'encode' + }, + // Path parameter name or name=value pairs prefixed by ';' + ';' : { + prefix: ';', + separator: ';', + named: true, + empty_name_separator: false, + encode : 'encode' + }, + // Query component beginning with '?' and consisting + // of name=value pairs separated by '&'; an + '?' : { + prefix: '?', + separator: '&', + named: true, + empty_name_separator: true, + encode : 'encode' + }, + // Continuation of query-style &name=value pairs + // within a literal query component. + '&' : { + prefix: '&', + separator: '&', + named: true, + empty_name_separator: true, + encode : 'encode' + } + + // The operator characters equals ("="), comma (","), exclamation ("!"), + // at sign ("@"), and pipe ("|") are reserved for future extensions. + }; + + // storage for already parsed templates + URITemplate._cache = {}; + // pattern to identify expressions [operator, variable-list] in template + URITemplate.EXPRESSION_PATTERN = /\{([^a-zA-Z0-9%_]?)([^\}]+)(\}|$)/g; + // pattern to identify variables [name, explode, maxlength] in variable-list + URITemplate.VARIABLE_PATTERN = /^([^*:.](?:\.?[^*:.])*)((\*)|:(\d+))?$/; + // pattern to verify variable name integrity + URITemplate.VARIABLE_NAME_PATTERN = /[^a-zA-Z0-9%_.]/; + // pattern to verify literal integrity + URITemplate.LITERAL_PATTERN = /[<>{}"`^| \\]/; + + // expand parsed expression (expression, not template!) + URITemplate.expand = function(expression, data, opts) { + // container for defined options for the given operator + var options = operators[expression.operator]; + // expansion type (include keys or not) + var type = options.named ? 'Named' : 'Unnamed'; + // list of variables within the expression + var variables = expression.variables; + // result buffer for evaluating the expression + var buffer = []; + var d, variable, i; + + for (i = 0; (variable = variables[i]); i++) { + // fetch simplified data source + d = data.get(variable.name); + if (d.type === 0 && opts && opts.strict) { + throw new Error('Missing expansion value for variable "' + variable.name + '"'); + } + if (!d.val.length) { + if (d.type) { + // empty variables (empty string) + // still lead to a separator being appended! + buffer.push(''); + } + // no data, no action + continue; + } + + if (d.type > 1 && variable.maxlength) { + // composite variable cannot specify maxlength + throw new Error('Invalid expression: Prefix modifier not applicable to variable "' + variable.name + '"'); + } + + // expand the given variable + buffer.push(URITemplate['expand' + type]( + d, + options, + variable.explode, + variable.explode && options.separator || ',', + variable.maxlength, + variable.name + )); + } + + if (buffer.length) { + return options.prefix + buffer.join(options.separator); + } else { + // prefix is not prepended for empty expressions + return ''; + } + }; + // expand a named variable + URITemplate.expandNamed = function(d, options, explode, separator, length, name) { + // variable result buffer + var result = ''; + // peformance crap + var encode = options.encode; + var empty_name_separator = options.empty_name_separator; + // flag noting if values are already encoded + var _encode = !d[encode].length; + // key for named expansion + var _name = d.type === 2 ? '': URI[encode](name); + var _value, i, l; + + // for each found value + for (i = 0, l = d.val.length; i < l; i++) { + if (length) { + // maxlength must be determined before encoding can happen + _value = URI[encode](d.val[i][1].substring(0, length)); + if (d.type === 2) { + // apply maxlength to keys of objects as well + _name = URI[encode](d.val[i][0].substring(0, length)); + } + } else if (_encode) { + // encode value + _value = URI[encode](d.val[i][1]); + if (d.type === 2) { + // encode name and cache encoded value + _name = URI[encode](d.val[i][0]); + d[encode].push([_name, _value]); + } else { + // cache encoded value + d[encode].push([undefined, _value]); + } + } else { + // values are already encoded and can be pulled from cache + _value = d[encode][i][1]; + if (d.type === 2) { + _name = d[encode][i][0]; + } + } + + if (result) { + // unless we're the first value, prepend the separator + result += separator; + } + + if (!explode) { + if (!i) { + // first element, so prepend variable name + result += URI[encode](name) + (empty_name_separator || _value ? '=' : ''); + } + + if (d.type === 2) { + // without explode-modifier, keys of objects are returned comma-separated + result += _name + ','; + } + + result += _value; + } else { + // only add the = if it is either default (?&) or there actually is a value (;) + result += _name + (empty_name_separator || _value ? '=' : '') + _value; + } + } + + return result; + }; + // expand an unnamed variable + URITemplate.expandUnnamed = function(d, options, explode, separator, length) { + // variable result buffer + var result = ''; + // performance crap + var encode = options.encode; + var empty_name_separator = options.empty_name_separator; + // flag noting if values are already encoded + var _encode = !d[encode].length; + var _name, _value, i, l; + + // for each found value + for (i = 0, l = d.val.length; i < l; i++) { + if (length) { + // maxlength must be determined before encoding can happen + _value = URI[encode](d.val[i][1].substring(0, length)); + } else if (_encode) { + // encode and cache value + _value = URI[encode](d.val[i][1]); + d[encode].push([ + d.type === 2 ? URI[encode](d.val[i][0]) : undefined, + _value + ]); + } else { + // value already encoded, pull from cache + _value = d[encode][i][1]; + } + + if (result) { + // unless we're the first value, prepend the separator + result += separator; + } + + if (d.type === 2) { + if (length) { + // maxlength also applies to keys of objects + _name = URI[encode](d.val[i][0].substring(0, length)); + } else { + // at this point the name must already be encoded + _name = d[encode][i][0]; + } + + result += _name; + if (explode) { + // explode-modifier separates name and value by "=" + result += (empty_name_separator || _value ? '=' : ''); + } else { + // no explode-modifier separates name and value by "," + result += ','; + } + } + + result += _value; + } + + return result; + }; + + URITemplate.noConflict = function() { + if (root.URITemplate === URITemplate) { + root.URITemplate = _URITemplate; + } + + return URITemplate; + }; + + // expand template through given data map + p.expand = function(data, opts) { + var result = ''; + + if (!this.parts || !this.parts.length) { + // lazilyy parse the template + this.parse(); + } + + if (!(data instanceof Data)) { + // make given data available through the + // optimized data handling thingie + data = new Data(data); + } + + for (var i = 0, l = this.parts.length; i < l; i++) { + /*jshint laxbreak: true */ + result += typeof this.parts[i] === 'string' + // literal string + ? this.parts[i] + // expression + : URITemplate.expand(this.parts[i], data, opts); + /*jshint laxbreak: false */ + } + + return result; + }; + // parse template into action tokens + p.parse = function() { + // performance crap + var expression = this.expression; + var ePattern = URITemplate.EXPRESSION_PATTERN; + var vPattern = URITemplate.VARIABLE_PATTERN; + var nPattern = URITemplate.VARIABLE_NAME_PATTERN; + var lPattern = URITemplate.LITERAL_PATTERN; + // token result buffer + var parts = []; + // position within source template + var pos = 0; + var variables, eMatch, vMatch; + + var checkLiteral = function(literal) { + if (literal.match(lPattern)) { + throw new Error('Invalid Literal "' + literal + '"'); + } + return literal; + }; + + // RegExp is shared accross all templates, + // which requires a manual reset + ePattern.lastIndex = 0; + // I don't like while(foo = bar()) loops, + // to make things simpler I go while(true) and break when required + while (true) { + eMatch = ePattern.exec(expression); + if (eMatch === null) { + // push trailing literal + parts.push(checkLiteral(expression.substring(pos))); + break; + } else { + // push leading literal + parts.push(checkLiteral(expression.substring(pos, eMatch.index))); + pos = eMatch.index + eMatch[0].length; + } + + if (!operators[eMatch[1]]) { + throw new Error('Unknown Operator "' + eMatch[1] + '" in "' + eMatch[0] + '"'); + } else if (!eMatch[3]) { + throw new Error('Unclosed Expression "' + eMatch[0] + '"'); + } + + // parse variable-list + variables = eMatch[2].split(','); + for (var i = 0, l = variables.length; i < l; i++) { + vMatch = variables[i].match(vPattern); + if (vMatch === null) { + throw new Error('Invalid Variable "' + variables[i] + '" in "' + eMatch[0] + '"'); + } else if (vMatch[1].match(nPattern)) { + throw new Error('Invalid Variable Name "' + vMatch[1] + '" in "' + eMatch[0] + '"'); + } + + variables[i] = { + name: vMatch[1], + explode: !!vMatch[3], + maxlength: vMatch[4] && parseInt(vMatch[4], 10) + }; + } + + if (!variables.length) { + throw new Error('Expression Missing Variable(s) "' + eMatch[0] + '"'); + } + + parts.push({ + expression: eMatch[0], + operator: eMatch[1], + variables: variables + }); + } + + if (!parts.length) { + // template doesn't contain any expressions + // so it is a simple literal string + // this probably should fire a warning or something? + parts.push(checkLiteral(expression)); + } + + this.parts = parts; + return this; + }; + + // simplify data structures + Data.prototype.get = function(key) { + // performance crap + var data = this.data; + // cache for processed data-point + var d = { + // type of data 0: undefined/null, 1: string, 2: object, 3: array + type: 0, + // original values (except undefined/null) + val: [], + // cache for encoded values (only for non-maxlength expansion) + encode: [], + encodeReserved: [] + }; + var i, l, value; + + if (this.cache[key] !== undefined) { + // we've already processed this key + return this.cache[key]; + } + + this.cache[key] = d; + + if (String(Object.prototype.toString.call(data)) === '[object Function]') { + // data itself is a callback (global callback) + value = data(key); + } else if (String(Object.prototype.toString.call(data[key])) === '[object Function]') { + // data is a map of callbacks (local callback) + value = data[key](key); + } else { + // data is a map of data + value = data[key]; + } + + // generalize input into [ [name1, value1], [name2, value2], … ] + // so expansion has to deal with a single data structure only + if (value === undefined || value === null) { + // undefined and null values are to be ignored completely + return d; + } else if (String(Object.prototype.toString.call(value)) === '[object Array]') { + for (i = 0, l = value.length; i < l; i++) { + if (value[i] !== undefined && value[i] !== null) { + // arrays don't have names + d.val.push([undefined, String(value[i])]); + } + } + + if (d.val.length) { + // only treat non-empty arrays as arrays + d.type = 3; // array + } + } else if (String(Object.prototype.toString.call(value)) === '[object Object]') { + for (i in value) { + if (hasOwn.call(value, i) && value[i] !== undefined && value[i] !== null) { + // objects have keys, remember them for named expansion + d.val.push([i, String(value[i])]); + } + } + + if (d.val.length) { + // only treat non-empty objects as objects + d.type = 2; // object + } + } else { + d.type = 1; // primitive string (could've been string, number, boolean and objects with a toString()) + // arrays don't have names + d.val.push([undefined, String(value)]); + } + + return d; + }; + + // hook into URI for fluid access + URI.expand = function(expression, data) { + var template = new URITemplate(expression); + var expansion = template.expand(data); + + return new URI(expansion); + }; + + return URITemplate; +})); + + +/***/ }), + +/***/ 9340: +/***/ (function(module, exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.0 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = true && exports && + !exports.nodeType && exports; + var freeModule = true && module && + !module.nodeType && module; + var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + true + ) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { + return punycode; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} + +}(this)); + + +/***/ }), + +/***/ 2894: +/***/ (() => { + +/* (ignored) */ + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat get default export */ +/******/ (() => { +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = (module) => { +/******/ var getter = module && module.__esModule ? +/******/ () => (module['default']) : +/******/ () => (module); +/******/ __webpack_require__.d(getter, { a: getter }); +/******/ return getter; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/global */ +/******/ (() => { +/******/ __webpack_require__.g = (function() { +/******/ if (typeof globalThis === 'object') return globalThis; +/******/ try { +/******/ return this || new Function('return this')(); +/******/ } catch (e) { +/******/ if (typeof window === 'object') return window; +/******/ } +/******/ })(); +/******/ })(); +/******/ +/******/ /* webpack/runtime/harmony module decorator */ +/******/ (() => { +/******/ __webpack_require__.hmd = (module) => { +/******/ module = Object.create(module); +/******/ if (!module.children) module.children = []; +/******/ Object.defineProperty(module, 'exports', { +/******/ enumerable: true, +/******/ set: () => { +/******/ throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id); +/******/ } +/******/ }); +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __webpack_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/node module decorator */ +/******/ (() => { +/******/ __webpack_require__.nmd = (module) => { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/************************************************************************/ +/******/ +/******/ // startup +/******/ // Load entry module and return exports +/******/ // This entry module is referenced by other modules so it can't be inlined +/******/ var __webpack_exports__ = __webpack_require__(1924); +/******/ +/******/ return __webpack_exports__; +/******/ })() +; +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-eventsource.min.js b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-eventsource.min.js new file mode 100644 index 000000000..ea8257e68 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-eventsource.min.js @@ -0,0 +1,2 @@ +/*! For license information please see stellar-sdk-no-eventsource.min.js.LICENSE.txt */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("StellarSdk",[],t):"object"==typeof exports?exports.StellarSdk=t():e.StellarSdk=t()}(self,(()=>(()=>{var e={3740:function(e){var t;t=()=>(()=>{var e={616:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(287);n.hp.alloc(1).subarray(0,1)instanceof n.hp||(n.hp.prototype.subarray=function(e,t){const r=Uint8Array.prototype.subarray.call(this,e,t);return Object.setPrototypeOf(r,n.hp.prototype),r});const o=n.hp},281:(e,t,r)=>{const n=r(164);e.exports=n},164:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Array:()=>D,Bool:()=>j,Double:()=>I,Enum:()=>H,Float:()=>R,Hyper:()=>O,Int:()=>k,LargeInt:()=>_,Opaque:()=>U,Option:()=>q,Quadruple:()=>C,Reference:()=>z,String:()=>L,Struct:()=>X,Union:()=>$,UnsignedHyper:()=>P,UnsignedInt:()=>A,VarArray:()=>V,VarOpaque:()=>F,Void:()=>K,XdrReader:()=>u,XdrWriter:()=>f,config:()=>ne});class n extends TypeError{constructor(e){super(`XDR Write Error: ${e}`)}}class o extends TypeError{constructor(e){super(`XDR Read Error: ${e}`)}}class i extends TypeError{constructor(e){super(`XDR Type Definition Error: ${e}`)}}class a extends i{constructor(){super("method not implemented, it should be overloaded in the descendant class.")}}var s=r(616).A;class u{constructor(e){if(!s.isBuffer(e)){if(!(e instanceof Array||Array.isArray(e)||ArrayBuffer.isView(e)))throw new o(`source invalid: ${e}`);e=s.from(e)}this._buffer=e,this._length=e.length,this._index=0}_buffer;_length;_index;get eof(){return this._index===this._length}advance(e){const t=this._index;if(this._index+=e,this._length0){for(let e=0;e0){const e=this.alloc(r);this._buffer.fill(0,e,this._index)}}writeInt32BE(e){const t=this.alloc(4);this._buffer.writeInt32BE(e,t)}writeUInt32BE(e){const t=this.alloc(4);this._buffer.writeUInt32BE(e,t)}writeBigInt64BE(e){const t=this.alloc(8);this._buffer.writeBigInt64BE(e,t)}writeBigUInt64BE(e){const t=this.alloc(8);this._buffer.writeBigUInt64BE(e,t)}writeFloatBE(e){const t=this.alloc(4);this._buffer.writeFloatBE(e,t)}writeDoubleBE(e){const t=this.alloc(8);this._buffer.writeDoubleBE(e,t)}static bufferChunkSize=l}var p=r(616).A;class d{toXDR(e="raw"){if(!this.write)return this.constructor.toXDR(this,e);const t=new f;return this.write(this,t),v(t.finalize(),e)}fromXDR(e,t="raw"){if(!this.read)return this.constructor.fromXDR(e,t);const r=new u(g(e,t)),n=this.read(r);return r.ensureInputConsumed(),n}validateXDR(e,t="raw"){try{return this.fromXDR(e,t),!0}catch(e){return!1}}static toXDR(e,t="raw"){const r=new f;return this.write(e,r),v(r.finalize(),t)}static fromXDR(e,t="raw"){const r=new u(g(e,t)),n=this.read(r);return r.ensureInputConsumed(),n}static validateXDR(e,t="raw"){try{return this.fromXDR(e,t),!0}catch(e){return!1}}}class h extends d{static read(e){throw new a}static write(e,t){throw new a}static isValid(e){return!1}}class y extends d{isValid(e){return!1}}class m extends TypeError{constructor(e){super(`Invalid format ${e}, must be one of "raw", "hex", "base64"`)}}function v(e,t){switch(t){case"raw":return e;case"hex":return e.toString("hex");case"base64":return e.toString("base64");default:throw new m(t)}}function g(e,t){switch(t){case"raw":return e;case"hex":return p.from(e,"hex");case"base64":return p.from(e,"base64");default:throw new m(t)}}function b(e,t){return null!=e&&(e instanceof t||w(e,t)&&"function"==typeof e.constructor.read&&"function"==typeof e.constructor.write&&w(e,"XdrType"))}function w(e,t){do{if(e.constructor.name===t)return!0}while(e=Object.getPrototypeOf(e));return!1}const S=2147483647;class k extends h{static read(e){return e.readInt32BE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");if((0|e)!==e)throw new n("invalid i32 value");t.writeInt32BE(e)}static isValid(e){return"number"==typeof e&&(0|e)===e&&e>=-2147483648&&e<=S}}function E(e,t,r){if("bigint"!=typeof e)throw new TypeError("Expected bigint 'value', got "+typeof e);const n=t/r;if(1===n)return[e];if(r<32||r>128||2!==n&&4!==n&&8!==n)throw new TypeError(`invalid bigint (${e}) and slice size (${t} -> ${r}) combination`);const o=BigInt(r),i=new Array(n);for(let t=0;t>=o;return i}function T(e,t){if(t)return[0n,(1n<=i&&o<=a)return o;throw new TypeError(`bigint values [${e}] for ${function(e,t){return`${t?"u":"i"}${e}`}(t,r)} out of range [${i}, ${a}]: ${o}`)}(e,this.size,this.unsigned)}get unsigned(){throw new a}get size(){throw new a}slice(e){return E(this._value,this.size,e)}toString(){return this._value.toString()}toJSON(){return{_value:this._value.toString()}}toBigInt(){return BigInt(this._value)}static read(e){const{size:t}=this.prototype;return 64===t?new this(e.readBigUInt64BE()):new this(...Array.from({length:t/64},(()=>e.readBigUInt64BE())).reverse())}static write(e,t){if(e instanceof this)e=e._value;else if("bigint"!=typeof e||e>this.MAX_VALUE||e>32n)}get size(){return 64}get unsigned(){return!1}static fromBits(e,t){return new this(e,t)}}O.defineIntBoundaries();const x=4294967295;class A extends h{static read(e){return e.readUInt32BE()}static write(e,t){if("number"!=typeof e||!(e>=0&&e<=x)||e%1!=0)throw new n("invalid u32 value");t.writeUInt32BE(e)}static isValid(e){return"number"==typeof e&&e%1==0&&e>=0&&e<=x}}A.MAX_VALUE=x,A.MIN_VALUE=0;class P extends _{constructor(...e){super(e)}get low(){return 0|Number(0xffffffffn&this._value)}get high(){return 0|Number(this._value>>32n)}get size(){return 64}get unsigned(){return!0}static fromBits(e,t){return new this(e,t)}}P.defineIntBoundaries();class R extends h{static read(e){return e.readFloatBE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");t.writeFloatBE(e)}static isValid(e){return"number"==typeof e}}class I extends h{static read(e){return e.readDoubleBE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");t.writeDoubleBE(e)}static isValid(e){return"number"==typeof e}}class C extends h{static read(){throw new i("quadruple not supported")}static write(){throw new i("quadruple not supported")}static isValid(){return!1}}class j extends h{static read(e){const t=k.read(e);switch(t){case 0:return!1;case 1:return!0;default:throw new o(`got ${t} when trying to read a bool`)}}static write(e,t){const r=e?1:0;k.write(r,t)}static isValid(e){return"boolean"==typeof e}}var B=r(616).A;class L extends y{constructor(e=A.MAX_VALUE){super(),this._maxLength=e}read(e){const t=A.read(e);if(t>this._maxLength)throw new o(`saw ${t} length String, max allowed is ${this._maxLength}`);return e.read(t)}readString(e){return this.read(e).toString("utf8")}write(e,t){const r="string"==typeof e?B.byteLength(e,"utf8"):e.length;if(r>this._maxLength)throw new n(`got ${e.length} bytes, max allowed is ${this._maxLength}`);A.write(r,t),t.write(e,r)}isValid(e){return"string"==typeof e?B.byteLength(e,"utf8")<=this._maxLength:!!(e instanceof Array||B.isBuffer(e))&&e.length<=this._maxLength}}var N=r(616).A;class U extends y{constructor(e){super(),this._length=e}read(e){return e.read(this._length)}write(e,t){const{length:r}=e;if(r!==this._length)throw new n(`got ${e.length} bytes, expected ${this._length}`);t.write(e,r)}isValid(e){return N.isBuffer(e)&&e.length===this._length}}var M=r(616).A;class F extends y{constructor(e=A.MAX_VALUE){super(),this._maxLength=e}read(e){const t=A.read(e);if(t>this._maxLength)throw new o(`saw ${t} length VarOpaque, max allowed is ${this._maxLength}`);return e.read(t)}write(e,t){const{length:r}=e;if(e.length>this._maxLength)throw new n(`got ${e.length} bytes, max allowed is ${this._maxLength}`);A.write(r,t),t.write(e,r)}isValid(e){return M.isBuffer(e)&&e.length<=this._maxLength}}class D extends y{constructor(e,t){super(),this._childType=e,this._length=t}read(e){const t=new r.g.Array(this._length);for(let r=0;rthis._maxLength)throw new o(`saw ${t} length VarArray, max allowed is ${this._maxLength}`);const r=new Array(t);for(let n=0;nthis._maxLength)throw new n(`got array of size ${e.length}, max allowed is ${this._maxLength}`);A.write(e.length,t);for(const r of e)this._childType.write(r,t)}isValid(e){if(!(e instanceof Array)||e.length>this._maxLength)return!1;for(const t of e)if(!this._childType.isValid(t))return!1;return!0}}class q extends h{constructor(e){super(),this._childType=e}read(e){if(j.read(e))return this._childType.read(e)}write(e,t){const r=null!=e;j.write(r,t),r&&this._childType.write(e,t)}isValid(e){return null==e||this._childType.isValid(e)}}class K extends h{static read(){}static write(e){if(void 0!==e)throw new n("trying to write value to a void slot")}static isValid(e){return void 0===e}}class H extends h{constructor(e,t){super(),this.name=e,this.value=t}static read(e){const t=k.read(e),r=this._byValue[t];if(void 0===r)throw new o(`unknown ${this.enumName} member for value ${t}`);return r}static write(e,t){if(!this.isValid(e))throw new n(`${e} has enum name ${e?.enumName}, not ${this.enumName}: ${JSON.stringify(e)}`);k.write(e.value,t)}static isValid(e){return e?.constructor?.enumName===this.enumName||b(e,this)}static members(){return this._members}static values(){return Object.values(this._members)}static fromName(e){const t=this._members[e];if(!t)throw new TypeError(`${e} is not a member of ${this.enumName}`);return t}static fromValue(e){const t=this._byValue[e];if(void 0===t)throw new TypeError(`${e} is not a value of any member of ${this.enumName}`);return t}static create(e,t,r){const n=class extends H{};n.enumName=t,e.results[t]=n,n._members={},n._byValue={};for(const[e,t]of Object.entries(r)){const r=new n(e,t);n._members[e]=r,n._byValue[t]=r,n[e]=()=>r}return n}}class z extends h{resolve(){throw new i('"resolve" method should be implemented in the descendant class')}}class X extends y{constructor(e){super(),this._attributes=e||{}}static read(e){const t={};for(const[r,n]of this._fields)t[r]=n.read(e);return new this(t)}static write(e,t){if(!this.isValid(e))throw new n(`${e} has struct name ${e?.constructor?.structName}, not ${this.structName}: ${JSON.stringify(e)}`);for(const[r,n]of this._fields){const o=e._attributes[r];n.write(o,t)}}static isValid(e){return e?.constructor?.structName===this.structName||b(e,this)}static create(e,t,r){const n=class extends X{};n.structName=t,e.results[t]=n;const o=new Array(r.length);for(let t=0;t{"use strict";t.byteLength=function(e){var t=s(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,i=s(e),a=i[0],u=i[1],c=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,u)),l=0,f=u>0?a-4:a;for(r=0;r>16&255,c[l++]=t>>8&255,c[l++]=255&t;return 2===u&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,c[l++]=255&t),1===u&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t),c},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],a=16383,s=0,c=n-o;sc?c:s+a));return 1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),i.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)r[a]=i[a],n[i.charCodeAt(a)]=a;function s(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,n){for(var o,i,a=[],s=t;s>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return a.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287:(e,t,r)=>{"use strict";const n=r(526),o=r(251),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=u,t.IS=50;const a=2147483647;function s(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,u.prototype),t}function u(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return f(e)}return c(e,t,r)}function c(e,t,r){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!u.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|y(e,t);let n=s(r);const o=n.write(e,t);return o!==r&&(n=n.slice(0,o)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(Q(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return p(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Q(e,ArrayBuffer)||e&&Q(e.buffer,ArrayBuffer))return d(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(Q(e,SharedArrayBuffer)||e&&Q(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return u.from(n,t,r);const o=function(e){if(u.isBuffer(e)){const t=0|h(e.length),r=s(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||W(e.length)?s(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return u.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function f(e){return l(e),s(e<0?0:0|h(e))}function p(e){const t=e.length<0?0:0|h(e.length),r=s(t);for(let n=0;n=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function y(e,t){if(u.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Q(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return X(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(o)return n?-1:X(e).length;t=(""+t).toLowerCase(),o=!0}}function m(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return R(this,t,r);case"utf8":case"utf-8":return O(this,t,r);case"ascii":return A(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return _(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function v(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function g(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),W(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,o){let i,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){let n=-1;for(i=r;is&&(r=s-u),i=r;i>=0;i--){let r=!0;for(let n=0;no&&(n=o):n=o;const i=t.length;let a;for(n>i/2&&(n=i/2),a=0;a>8,o=r%256,i.push(o),i.push(n);return i}(t,e.length-r),e,r,n)}function _(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function O(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o239?4:t>223?3:t>191?2:1;if(o+a<=r){let r,n,s,u;switch(a){case 1:t<128&&(i=t);break;case 2:r=e[o+1],128==(192&r)&&(u=(31&t)<<6|63&r,u>127&&(i=u));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(u=(15&t)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:r=e[o+1],n=e[o+2],s=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(u=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,u>65535&&u<1114112&&(i=u))}}null===i?(i=65533,a=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),o+=a}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(u.isBuffer(t)||(t=u.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!u.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},u.byteLength=y,u.prototype._isBuffer=!0,u.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(e+=" ... "),""},i&&(u.prototype[i]=u.prototype.inspect),u.prototype.compare=function(e,t,r,n,o){if(Q(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let i=(o>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0);const s=Math.min(i,a),c=this.slice(n,o),l=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let i=!1;for(;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":case"latin1":case"binary":return k(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function A(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;on)&&(r=n);let o="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function j(e,t,r,n,o,i){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function B(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function L(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r+7]=i,i>>=8,e[r+6]=i,i>>=8,e[r+5]=i,i>>=8,e[r+4]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function N(e,t,r,n,o,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function M(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,8),o.write(e,t,r,n,52,8),r+8}u.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e+--t],o=1;for(;t>0&&(o*=256);)n+=this[e+--t]*o;return n},u.prototype.readUint8=u.prototype.readUInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(o)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i=o&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=t,o=1,i=this[e+--n];for(;n>0&&(o*=256);)i+=this[e+--n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},u.prototype.readInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||C(e,4,this.length),o.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||C(e,4,this.length),o.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||C(e,8,this.length),o.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||C(e,8,this.length),o.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||j(this,e,t,r,Math.pow(2,8*r)-1,0);let o=1,i=0;for(this[t]=255&e;++i>>=0,r>>>=0,n||j(this,e,t,r,Math.pow(2,8*r)-1,0);let o=r-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigUInt64LE=J((function(e,t=0){return B(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeBigUInt64BE=J((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);j(this,e,t,r,n-1,-n)}let o=0,i=1,a=0;for(this[t]=255&e;++o>>=0,!n){const n=Math.pow(2,8*r-1);j(this,e,t,r,n-1,-n)}let o=r-1,i=1,a=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/i|0)-a&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigInt64LE=J((function(e,t=0){return B(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeBigInt64BE=J((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return M(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return M(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function q(e,t,r,n,o,i){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new F.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){K(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||H(t,e.length-(r+1))}(n,o,i)}function K(e,t){if("number"!=typeof e)throw new F.ERR_INVALID_ARG_TYPE(t,"number",e)}function H(e,t,r){if(Math.floor(e)!==e)throw K(e,r),new F.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new F.ERR_BUFFER_OUT_OF_BOUNDS;throw new F.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}D("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),D("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),D("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=V(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=V(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const z=/[^+/0-9A-Za-z-_]/g;function X(e,t){let r;t=t||1/0;const n=e.length;let o=null;const i=[];for(let a=0;a55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function G(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function $(e,t,r,n){let o;for(o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function Q(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function W(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let o=0;o<16;++o)t[n+o]=e[r]+e[o]}return t}();function J(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},251:(e,t)=>{t.read=function(e,t,r,n,o){var i,a,s=8*o-n-1,u=(1<>1,l=-7,f=r?o-1:0,p=r?-1:1,d=e[t+f];for(f+=p,i=d&(1<<-l)-1,d>>=-l,l+=s;l>0;i=256*i+e[t+f],f+=p,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=p,l-=8);if(0===i)i=1-c;else{if(i===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),i-=c}return(d?-1:1)*a*Math.pow(2,i-n)},t.write=function(e,t,r,n,o,i){var a,s,u,c=8*i-o-1,l=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,h=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?p/u:p*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=l?(s=0,a=l):a+f>=1?(s=(t*u-1)*Math.pow(2,o),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,o),a=0));o>=8;e[r+d]=255&s,d+=h,s/=256,o-=8);for(a=a<0;e[r+d]=255&a,d+=h,a/=256,c-=8);e[r+d-h]|=128*y}}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}return r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r(281)})(),e.exports=t()},2135:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Account=void 0;var n,o=(n=r(1242))&&n.__esModule?n:{default:n},i=r(7120);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function s(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Address=void 0;var n,o=r(7120),i=(n=r(1918))&&n.__esModule?n:{default:n};function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function s(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;var o,i=r(645),a=(o=r(1918))&&o.__esModule?o:{default:o},s=r(6691),u=r(7120),c=r(9152);function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:a.default.Asset;if(this.isNative())return r.assetTypeNative();this.code.length<=4?(e=a.default.AlphaNum4,t="assetTypeCreditAlphanum4"):(e=a.default.AlphaNum12,t="assetTypeCreditAlphanum12");var n=this.code.length<=4?4:12;return new r(t,new e({assetCode:this.code.padEnd(n,"\0"),issuer:s.Keypair.fromPublicKey(this.issuer).xdrAccountId()}))}},{key:"getCode",value:function(){if(void 0!==this.code)return String(this.code)}},{key:"getIssuer",value:function(){if(void 0!==this.issuer)return String(this.issuer)}},{key:"getAssetType",value:function(){switch(this.getRawAssetType().value){case a.default.AssetType.assetTypeNative().value:return"native";case a.default.AssetType.assetTypeCreditAlphanum4().value:return"credit_alphanum4";case a.default.AssetType.assetTypeCreditAlphanum12().value:return"credit_alphanum12";default:return"unknown"}}},{key:"getRawAssetType",value:function(){return this.isNative()?a.default.AssetType.assetTypeNative():this.code.length<=4?a.default.AssetType.assetTypeCreditAlphanum4():a.default.AssetType.assetTypeCreditAlphanum12()}},{key:"isNative",value:function(){return!this.issuer}},{key:"equals",value:function(e){return this.code===e.getCode()&&this.issuer===e.getIssuer()}},{key:"toString",value:function(){return this.isNative()?"native":"".concat(this.getCode(),":").concat(this.getIssuer())}}],[{key:"native",value:function(){return new e("XLM")}},{key:"fromOperation",value:function(e){var t,r;switch(e.switch()){case a.default.AssetType.assetTypeNative():return this.native();case a.default.AssetType.assetTypeCreditAlphanum4():t=e.alphaNum4();case a.default.AssetType.assetTypeCreditAlphanum12():return t=t||e.alphaNum12(),r=u.StrKey.encodeEd25519PublicKey(t.issuer().ed25519()),new this((0,i.trimEnd)(t.assetCode(),"\0"),r);default:throw new Error("Invalid asset type: ".concat(e.switch().name))}}},{key:"compare",value:function(t,r){if(!(t&&t instanceof e))throw new Error("assetA is invalid");if(!(r&&r instanceof e))throw new Error("assetB is invalid");if(t.equals(r))return 0;var n=t.getRawAssetType().value,o=r.getRawAssetType().value;if(n!==o)return n{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.authorizeEntry=y,t.authorizeInvocation=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:u.Networks.FUTURENET,s=a.Keypair.random().rawPublicKey(),c=new i.default.Int64((p=s,p.subarray(0,8).reduce((function(e,t){return e<<8|t}),0))),f=n||e.publicKey();var p;if(!f)throw new Error("authorizeInvocation requires publicKey parameter");return y(new i.default.SorobanAuthorizationEntry({rootInvocation:r,credentials:i.default.SorobanCredentials.sorobanCredentialsAddress(new i.default.SorobanAddressCredentials({address:new l.Address(f).toScAddress(),nonce:c,signatureExpirationLedger:0,signature:i.default.ScVal.scvVec([])}))}),e,t,o)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(6691),s=r(7120),u=r(6202),c=r(9152),l=r(1180),f=r(7177);function p(e){return p="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},p(e)}function d(){d=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof b?t:b,a=Object.create(i.prototype),s=new C(n||[]);return o(a,"_invoke",{value:A(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var h="suspendedStart",y="suspendedYield",m="executing",v="completed",g={};function b(){}function w(){}function S(){}var k={};c(k,a,(function(){return this}));var E=Object.getPrototypeOf,T=E&&E(E(j([])));T&&T!==r&&n.call(T,a)&&(k=T);var _=S.prototype=b.prototype=Object.create(k);function O(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function x(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==p(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function A(t,r,n){var o=h;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=P(s,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=m;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?v:y,c.arg===g)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=v,n.method="throw",n.arg=c.arg)}}}function P(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,P(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function R(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function I(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(R,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),I(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;I(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function h(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function y(e,t,r){return m.apply(this,arguments)}function m(){var e;return e=d().mark((function e(t,r,o){var p,h,y,m,v,g,b,w,S,k=arguments;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(p=k.length>3&&void 0!==k[3]?k[3]:u.Networks.FUTURENET,t.credentials().switch().value===i.default.SorobanCredentialsType.sorobanCredentialsAddress().value){e.next=3;break}return e.abrupt("return",t);case 3:if(h=i.default.SorobanAuthorizationEntry.fromXDR(t.toXDR()),(y=h.credentials().address()).signatureExpirationLedger(o),m=(0,c.hash)(n.from(p)),v=i.default.HashIdPreimage.envelopeTypeSorobanAuthorization(new i.default.HashIdPreimageSorobanAuthorization({networkId:m,nonce:y.nonce(),invocation:h.rootInvocation(),signatureExpirationLedger:y.signatureExpirationLedger()})),g=(0,c.hash)(v.toXDR()),"function"!=typeof r){e.next=18;break}return e.t0=n,e.next=13,r(v);case 13:e.t1=e.sent,b=e.t0.from.call(e.t0,e.t1),w=l.Address.fromScAddress(y.address()).toString(),e.next=20;break;case 18:b=n.from(r.sign(g)),w=r.publicKey();case 20:if(a.Keypair.fromPublicKey(w).verify(g,b)){e.next=22;break}throw new Error("signature doesn't match payload");case 22:return S=(0,f.nativeToScVal)({public_key:s.StrKey.decodeEd25519PublicKey(w),signature:b},{type:{public_key:["symbol",null],signature:["symbol",null]}}),y.signature(i.default.ScVal.scvVec([S])),e.abrupt("return",h);case 25:case"end":return e.stop()}}),e)})),m=function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){h(i,n,o,a,s,"next",e)}function s(e){h(i,n,o,a,s,"throw",e)}a(void 0)}))},m.apply(this,arguments)}},1387:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Claimant=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691),a=r(7120);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Contract=void 0;var n,o=r(1180),i=r(7237),a=(n=r(1918))&&n.__esModule?n:{default:n},s=r(7120);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){for(var r=0;r1?t-1:0),n=1;n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.humanizeEvents=function(e){return e.map((function(e){return e.inSuccessfulContractCall?c(e.event()):c(e)}))};var n=r(7120),o=r(7177);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function s(e){for(var t=1;t{"use strict";var n=r(8287).Buffer;function o(e){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.FeeBumpTransaction=void 0;var i,a=(i=r(1918))&&i.__esModule?i:{default:i},s=r(9152),u=r(380),c=r(3758),l=r(6160);function f(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(o=function(e){return e?r:t})(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=n(e)&&"function"!=typeof e)return{default:e};var r=o(t);if(r&&r.has(e))return r.get(e);var i={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&{}.hasOwnProperty.call(e,s)){var u=a?Object.getOwnPropertyDescriptor(e,s):null;u&&(u.get||u.set)?Object.defineProperty(i,s,u):i[s]=e[s]}return i.default=e,r&&r.set(e,i),i}(r(3740)).config((function(e){var t=1024;e.typedef("Value",e.varOpaque()),e.struct("ScpBallot",[["counter",e.lookup("Uint32")],["value",e.lookup("Value")]]),e.enum("ScpStatementType",{scpStPrepare:0,scpStConfirm:1,scpStExternalize:2,scpStNominate:3}),e.struct("ScpNomination",[["quorumSetHash",e.lookup("Hash")],["votes",e.varArray(e.lookup("Value"),2147483647)],["accepted",e.varArray(e.lookup("Value"),2147483647)]]),e.struct("ScpStatementPrepare",[["quorumSetHash",e.lookup("Hash")],["ballot",e.lookup("ScpBallot")],["prepared",e.option(e.lookup("ScpBallot"))],["preparedPrime",e.option(e.lookup("ScpBallot"))],["nC",e.lookup("Uint32")],["nH",e.lookup("Uint32")]]),e.struct("ScpStatementConfirm",[["ballot",e.lookup("ScpBallot")],["nPrepared",e.lookup("Uint32")],["nCommit",e.lookup("Uint32")],["nH",e.lookup("Uint32")],["quorumSetHash",e.lookup("Hash")]]),e.struct("ScpStatementExternalize",[["commit",e.lookup("ScpBallot")],["nH",e.lookup("Uint32")],["commitQuorumSetHash",e.lookup("Hash")]]),e.union("ScpStatementPledges",{switchOn:e.lookup("ScpStatementType"),switchName:"type",switches:[["scpStPrepare","prepare"],["scpStConfirm","confirm"],["scpStExternalize","externalize"],["scpStNominate","nominate"]],arms:{prepare:e.lookup("ScpStatementPrepare"),confirm:e.lookup("ScpStatementConfirm"),externalize:e.lookup("ScpStatementExternalize"),nominate:e.lookup("ScpNomination")}}),e.struct("ScpStatement",[["nodeId",e.lookup("NodeId")],["slotIndex",e.lookup("Uint64")],["pledges",e.lookup("ScpStatementPledges")]]),e.struct("ScpEnvelope",[["statement",e.lookup("ScpStatement")],["signature",e.lookup("Signature")]]),e.struct("ScpQuorumSet",[["threshold",e.lookup("Uint32")],["validators",e.varArray(e.lookup("NodeId"),2147483647)],["innerSets",e.varArray(e.lookup("ScpQuorumSet"),2147483647)]]),e.typedef("Thresholds",e.opaque(4)),e.typedef("String32",e.string(32)),e.typedef("String64",e.string(64)),e.typedef("SequenceNumber",e.lookup("Int64")),e.typedef("DataValue",e.varOpaque(64)),e.typedef("PoolId",e.lookup("Hash")),e.typedef("AssetCode4",e.opaque(4)),e.typedef("AssetCode12",e.opaque(12)),e.enum("AssetType",{assetTypeNative:0,assetTypeCreditAlphanum4:1,assetTypeCreditAlphanum12:2,assetTypePoolShare:3}),e.union("AssetCode",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeCreditAlphanum4","assetCode4"],["assetTypeCreditAlphanum12","assetCode12"]],arms:{assetCode4:e.lookup("AssetCode4"),assetCode12:e.lookup("AssetCode12")}}),e.struct("AlphaNum4",[["assetCode",e.lookup("AssetCode4")],["issuer",e.lookup("AccountId")]]),e.struct("AlphaNum12",[["assetCode",e.lookup("AssetCode12")],["issuer",e.lookup("AccountId")]]),e.union("Asset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12")}}),e.struct("Price",[["n",e.lookup("Int32")],["d",e.lookup("Int32")]]),e.struct("Liabilities",[["buying",e.lookup("Int64")],["selling",e.lookup("Int64")]]),e.enum("ThresholdIndices",{thresholdMasterWeight:0,thresholdLow:1,thresholdMed:2,thresholdHigh:3}),e.enum("LedgerEntryType",{account:0,trustline:1,offer:2,data:3,claimableBalance:4,liquidityPool:5,contractData:6,contractCode:7,configSetting:8,ttl:9}),e.struct("Signer",[["key",e.lookup("SignerKey")],["weight",e.lookup("Uint32")]]),e.enum("AccountFlags",{authRequiredFlag:1,authRevocableFlag:2,authImmutableFlag:4,authClawbackEnabledFlag:8}),e.const("MASK_ACCOUNT_FLAGS",7),e.const("MASK_ACCOUNT_FLAGS_V17",15),e.const("MAX_SIGNERS",20),e.typedef("SponsorshipDescriptor",e.option(e.lookup("AccountId"))),e.struct("AccountEntryExtensionV3",[["ext",e.lookup("ExtensionPoint")],["seqLedger",e.lookup("Uint32")],["seqTime",e.lookup("TimePoint")]]),e.union("AccountEntryExtensionV2Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[3,"v3"]],arms:{v3:e.lookup("AccountEntryExtensionV3")}}),e.struct("AccountEntryExtensionV2",[["numSponsored",e.lookup("Uint32")],["numSponsoring",e.lookup("Uint32")],["signerSponsoringIDs",e.varArray(e.lookup("SponsorshipDescriptor"),e.lookup("MAX_SIGNERS"))],["ext",e.lookup("AccountEntryExtensionV2Ext")]]),e.union("AccountEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[2,"v2"]],arms:{v2:e.lookup("AccountEntryExtensionV2")}}),e.struct("AccountEntryExtensionV1",[["liabilities",e.lookup("Liabilities")],["ext",e.lookup("AccountEntryExtensionV1Ext")]]),e.union("AccountEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("AccountEntryExtensionV1")}}),e.struct("AccountEntry",[["accountId",e.lookup("AccountId")],["balance",e.lookup("Int64")],["seqNum",e.lookup("SequenceNumber")],["numSubEntries",e.lookup("Uint32")],["inflationDest",e.option(e.lookup("AccountId"))],["flags",e.lookup("Uint32")],["homeDomain",e.lookup("String32")],["thresholds",e.lookup("Thresholds")],["signers",e.varArray(e.lookup("Signer"),e.lookup("MAX_SIGNERS"))],["ext",e.lookup("AccountEntryExt")]]),e.enum("TrustLineFlags",{authorizedFlag:1,authorizedToMaintainLiabilitiesFlag:2,trustlineClawbackEnabledFlag:4}),e.const("MASK_TRUSTLINE_FLAGS",1),e.const("MASK_TRUSTLINE_FLAGS_V13",3),e.const("MASK_TRUSTLINE_FLAGS_V17",7),e.enum("LiquidityPoolType",{liquidityPoolConstantProduct:0}),e.union("TrustLineAsset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"],["assetTypePoolShare","liquidityPoolId"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12"),liquidityPoolId:e.lookup("PoolId")}}),e.union("TrustLineEntryExtensionV2Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TrustLineEntryExtensionV2",[["liquidityPoolUseCount",e.lookup("Int32")],["ext",e.lookup("TrustLineEntryExtensionV2Ext")]]),e.union("TrustLineEntryV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[2,"v2"]],arms:{v2:e.lookup("TrustLineEntryExtensionV2")}}),e.struct("TrustLineEntryV1",[["liabilities",e.lookup("Liabilities")],["ext",e.lookup("TrustLineEntryV1Ext")]]),e.union("TrustLineEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("TrustLineEntryV1")}}),e.struct("TrustLineEntry",[["accountId",e.lookup("AccountId")],["asset",e.lookup("TrustLineAsset")],["balance",e.lookup("Int64")],["limit",e.lookup("Int64")],["flags",e.lookup("Uint32")],["ext",e.lookup("TrustLineEntryExt")]]),e.enum("OfferEntryFlags",{passiveFlag:1}),e.const("MASK_OFFERENTRY_FLAGS",1),e.union("OfferEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("OfferEntry",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")],["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")],["flags",e.lookup("Uint32")],["ext",e.lookup("OfferEntryExt")]]),e.union("DataEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("DataEntry",[["accountId",e.lookup("AccountId")],["dataName",e.lookup("String64")],["dataValue",e.lookup("DataValue")],["ext",e.lookup("DataEntryExt")]]),e.enum("ClaimPredicateType",{claimPredicateUnconditional:0,claimPredicateAnd:1,claimPredicateOr:2,claimPredicateNot:3,claimPredicateBeforeAbsoluteTime:4,claimPredicateBeforeRelativeTime:5}),e.union("ClaimPredicate",{switchOn:e.lookup("ClaimPredicateType"),switchName:"type",switches:[["claimPredicateUnconditional",e.void()],["claimPredicateAnd","andPredicates"],["claimPredicateOr","orPredicates"],["claimPredicateNot","notPredicate"],["claimPredicateBeforeAbsoluteTime","absBefore"],["claimPredicateBeforeRelativeTime","relBefore"]],arms:{andPredicates:e.varArray(e.lookup("ClaimPredicate"),2),orPredicates:e.varArray(e.lookup("ClaimPredicate"),2),notPredicate:e.option(e.lookup("ClaimPredicate")),absBefore:e.lookup("Int64"),relBefore:e.lookup("Int64")}}),e.enum("ClaimantType",{claimantTypeV0:0}),e.struct("ClaimantV0",[["destination",e.lookup("AccountId")],["predicate",e.lookup("ClaimPredicate")]]),e.union("Claimant",{switchOn:e.lookup("ClaimantType"),switchName:"type",switches:[["claimantTypeV0","v0"]],arms:{v0:e.lookup("ClaimantV0")}}),e.enum("ClaimableBalanceIdType",{claimableBalanceIdTypeV0:0}),e.union("ClaimableBalanceId",{switchOn:e.lookup("ClaimableBalanceIdType"),switchName:"type",switches:[["claimableBalanceIdTypeV0","v0"]],arms:{v0:e.lookup("Hash")}}),e.enum("ClaimableBalanceFlags",{claimableBalanceClawbackEnabledFlag:1}),e.const("MASK_CLAIMABLE_BALANCE_FLAGS",1),e.union("ClaimableBalanceEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("ClaimableBalanceEntryExtensionV1",[["ext",e.lookup("ClaimableBalanceEntryExtensionV1Ext")],["flags",e.lookup("Uint32")]]),e.union("ClaimableBalanceEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("ClaimableBalanceEntryExtensionV1")}}),e.struct("ClaimableBalanceEntry",[["balanceId",e.lookup("ClaimableBalanceId")],["claimants",e.varArray(e.lookup("Claimant"),10)],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")],["ext",e.lookup("ClaimableBalanceEntryExt")]]),e.struct("LiquidityPoolConstantProductParameters",[["assetA",e.lookup("Asset")],["assetB",e.lookup("Asset")],["fee",e.lookup("Int32")]]),e.struct("LiquidityPoolEntryConstantProduct",[["params",e.lookup("LiquidityPoolConstantProductParameters")],["reserveA",e.lookup("Int64")],["reserveB",e.lookup("Int64")],["totalPoolShares",e.lookup("Int64")],["poolSharesTrustLineCount",e.lookup("Int64")]]),e.union("LiquidityPoolEntryBody",{switchOn:e.lookup("LiquidityPoolType"),switchName:"type",switches:[["liquidityPoolConstantProduct","constantProduct"]],arms:{constantProduct:e.lookup("LiquidityPoolEntryConstantProduct")}}),e.struct("LiquidityPoolEntry",[["liquidityPoolId",e.lookup("PoolId")],["body",e.lookup("LiquidityPoolEntryBody")]]),e.enum("ContractDataDurability",{temporary:0,persistent:1}),e.struct("ContractDataEntry",[["ext",e.lookup("ExtensionPoint")],["contract",e.lookup("ScAddress")],["key",e.lookup("ScVal")],["durability",e.lookup("ContractDataDurability")],["val",e.lookup("ScVal")]]),e.struct("ContractCodeCostInputs",[["ext",e.lookup("ExtensionPoint")],["nInstructions",e.lookup("Uint32")],["nFunctions",e.lookup("Uint32")],["nGlobals",e.lookup("Uint32")],["nTableEntries",e.lookup("Uint32")],["nTypes",e.lookup("Uint32")],["nDataSegments",e.lookup("Uint32")],["nElemSegments",e.lookup("Uint32")],["nImports",e.lookup("Uint32")],["nExports",e.lookup("Uint32")],["nDataSegmentBytes",e.lookup("Uint32")]]),e.struct("ContractCodeEntryV1",[["ext",e.lookup("ExtensionPoint")],["costInputs",e.lookup("ContractCodeCostInputs")]]),e.union("ContractCodeEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("ContractCodeEntryV1")}}),e.struct("ContractCodeEntry",[["ext",e.lookup("ContractCodeEntryExt")],["hash",e.lookup("Hash")],["code",e.varOpaque()]]),e.struct("TtlEntry",[["keyHash",e.lookup("Hash")],["liveUntilLedgerSeq",e.lookup("Uint32")]]),e.union("LedgerEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerEntryExtensionV1",[["sponsoringId",e.lookup("SponsorshipDescriptor")],["ext",e.lookup("LedgerEntryExtensionV1Ext")]]),e.union("LedgerEntryData",{switchOn:e.lookup("LedgerEntryType"),switchName:"type",switches:[["account","account"],["trustline","trustLine"],["offer","offer"],["data","data"],["claimableBalance","claimableBalance"],["liquidityPool","liquidityPool"],["contractData","contractData"],["contractCode","contractCode"],["configSetting","configSetting"],["ttl","ttl"]],arms:{account:e.lookup("AccountEntry"),trustLine:e.lookup("TrustLineEntry"),offer:e.lookup("OfferEntry"),data:e.lookup("DataEntry"),claimableBalance:e.lookup("ClaimableBalanceEntry"),liquidityPool:e.lookup("LiquidityPoolEntry"),contractData:e.lookup("ContractDataEntry"),contractCode:e.lookup("ContractCodeEntry"),configSetting:e.lookup("ConfigSettingEntry"),ttl:e.lookup("TtlEntry")}}),e.union("LedgerEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerEntryExtensionV1")}}),e.struct("LedgerEntry",[["lastModifiedLedgerSeq",e.lookup("Uint32")],["data",e.lookup("LedgerEntryData")],["ext",e.lookup("LedgerEntryExt")]]),e.struct("LedgerKeyAccount",[["accountId",e.lookup("AccountId")]]),e.struct("LedgerKeyTrustLine",[["accountId",e.lookup("AccountId")],["asset",e.lookup("TrustLineAsset")]]),e.struct("LedgerKeyOffer",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")]]),e.struct("LedgerKeyData",[["accountId",e.lookup("AccountId")],["dataName",e.lookup("String64")]]),e.struct("LedgerKeyClaimableBalance",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("LedgerKeyLiquidityPool",[["liquidityPoolId",e.lookup("PoolId")]]),e.struct("LedgerKeyContractData",[["contract",e.lookup("ScAddress")],["key",e.lookup("ScVal")],["durability",e.lookup("ContractDataDurability")]]),e.struct("LedgerKeyContractCode",[["hash",e.lookup("Hash")]]),e.struct("LedgerKeyConfigSetting",[["configSettingId",e.lookup("ConfigSettingId")]]),e.struct("LedgerKeyTtl",[["keyHash",e.lookup("Hash")]]),e.union("LedgerKey",{switchOn:e.lookup("LedgerEntryType"),switchName:"type",switches:[["account","account"],["trustline","trustLine"],["offer","offer"],["data","data"],["claimableBalance","claimableBalance"],["liquidityPool","liquidityPool"],["contractData","contractData"],["contractCode","contractCode"],["configSetting","configSetting"],["ttl","ttl"]],arms:{account:e.lookup("LedgerKeyAccount"),trustLine:e.lookup("LedgerKeyTrustLine"),offer:e.lookup("LedgerKeyOffer"),data:e.lookup("LedgerKeyData"),claimableBalance:e.lookup("LedgerKeyClaimableBalance"),liquidityPool:e.lookup("LedgerKeyLiquidityPool"),contractData:e.lookup("LedgerKeyContractData"),contractCode:e.lookup("LedgerKeyContractCode"),configSetting:e.lookup("LedgerKeyConfigSetting"),ttl:e.lookup("LedgerKeyTtl")}}),e.enum("EnvelopeType",{envelopeTypeTxV0:0,envelopeTypeScp:1,envelopeTypeTx:2,envelopeTypeAuth:3,envelopeTypeScpvalue:4,envelopeTypeTxFeeBump:5,envelopeTypeOpId:6,envelopeTypePoolRevokeOpId:7,envelopeTypeContractId:8,envelopeTypeSorobanAuthorization:9}),e.enum("BucketListType",{live:0,hotArchive:1,coldArchive:2}),e.enum("BucketEntryType",{metaentry:-1,liveentry:0,deadentry:1,initentry:2}),e.enum("HotArchiveBucketEntryType",{hotArchiveMetaentry:-1,hotArchiveArchived:0,hotArchiveLive:1,hotArchiveDeleted:2}),e.enum("ColdArchiveBucketEntryType",{coldArchiveMetaentry:-1,coldArchiveArchivedLeaf:0,coldArchiveDeletedLeaf:1,coldArchiveBoundaryLeaf:2,coldArchiveHash:3}),e.union("BucketMetadataExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"bucketListType"]],arms:{bucketListType:e.lookup("BucketListType")}}),e.struct("BucketMetadata",[["ledgerVersion",e.lookup("Uint32")],["ext",e.lookup("BucketMetadataExt")]]),e.union("BucketEntry",{switchOn:e.lookup("BucketEntryType"),switchName:"type",switches:[["liveentry","liveEntry"],["initentry","liveEntry"],["deadentry","deadEntry"],["metaentry","metaEntry"]],arms:{liveEntry:e.lookup("LedgerEntry"),deadEntry:e.lookup("LedgerKey"),metaEntry:e.lookup("BucketMetadata")}}),e.union("HotArchiveBucketEntry",{switchOn:e.lookup("HotArchiveBucketEntryType"),switchName:"type",switches:[["hotArchiveArchived","archivedEntry"],["hotArchiveLive","key"],["hotArchiveDeleted","key"],["hotArchiveMetaentry","metaEntry"]],arms:{archivedEntry:e.lookup("LedgerEntry"),key:e.lookup("LedgerKey"),metaEntry:e.lookup("BucketMetadata")}}),e.struct("ColdArchiveArchivedLeaf",[["index",e.lookup("Uint32")],["archivedEntry",e.lookup("LedgerEntry")]]),e.struct("ColdArchiveDeletedLeaf",[["index",e.lookup("Uint32")],["deletedKey",e.lookup("LedgerKey")]]),e.struct("ColdArchiveBoundaryLeaf",[["index",e.lookup("Uint32")],["isLowerBound",e.bool()]]),e.struct("ColdArchiveHashEntry",[["index",e.lookup("Uint32")],["level",e.lookup("Uint32")],["hash",e.lookup("Hash")]]),e.union("ColdArchiveBucketEntry",{switchOn:e.lookup("ColdArchiveBucketEntryType"),switchName:"type",switches:[["coldArchiveMetaentry","metaEntry"],["coldArchiveArchivedLeaf","archivedLeaf"],["coldArchiveDeletedLeaf","deletedLeaf"],["coldArchiveBoundaryLeaf","boundaryLeaf"],["coldArchiveHash","hashEntry"]],arms:{metaEntry:e.lookup("BucketMetadata"),archivedLeaf:e.lookup("ColdArchiveArchivedLeaf"),deletedLeaf:e.lookup("ColdArchiveDeletedLeaf"),boundaryLeaf:e.lookup("ColdArchiveBoundaryLeaf"),hashEntry:e.lookup("ColdArchiveHashEntry")}}),e.typedef("UpgradeType",e.varOpaque(128)),e.enum("StellarValueType",{stellarValueBasic:0,stellarValueSigned:1}),e.struct("LedgerCloseValueSignature",[["nodeId",e.lookup("NodeId")],["signature",e.lookup("Signature")]]),e.union("StellarValueExt",{switchOn:e.lookup("StellarValueType"),switchName:"v",switches:[["stellarValueBasic",e.void()],["stellarValueSigned","lcValueSignature"]],arms:{lcValueSignature:e.lookup("LedgerCloseValueSignature")}}),e.struct("StellarValue",[["txSetHash",e.lookup("Hash")],["closeTime",e.lookup("TimePoint")],["upgrades",e.varArray(e.lookup("UpgradeType"),6)],["ext",e.lookup("StellarValueExt")]]),e.const("MASK_LEDGER_HEADER_FLAGS",7),e.enum("LedgerHeaderFlags",{disableLiquidityPoolTradingFlag:1,disableLiquidityPoolDepositFlag:2,disableLiquidityPoolWithdrawalFlag:4}),e.union("LedgerHeaderExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerHeaderExtensionV1",[["flags",e.lookup("Uint32")],["ext",e.lookup("LedgerHeaderExtensionV1Ext")]]),e.union("LedgerHeaderExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerHeaderExtensionV1")}}),e.struct("LedgerHeader",[["ledgerVersion",e.lookup("Uint32")],["previousLedgerHash",e.lookup("Hash")],["scpValue",e.lookup("StellarValue")],["txSetResultHash",e.lookup("Hash")],["bucketListHash",e.lookup("Hash")],["ledgerSeq",e.lookup("Uint32")],["totalCoins",e.lookup("Int64")],["feePool",e.lookup("Int64")],["inflationSeq",e.lookup("Uint32")],["idPool",e.lookup("Uint64")],["baseFee",e.lookup("Uint32")],["baseReserve",e.lookup("Uint32")],["maxTxSetSize",e.lookup("Uint32")],["skipList",e.array(e.lookup("Hash"),4)],["ext",e.lookup("LedgerHeaderExt")]]),e.enum("LedgerUpgradeType",{ledgerUpgradeVersion:1,ledgerUpgradeBaseFee:2,ledgerUpgradeMaxTxSetSize:3,ledgerUpgradeBaseReserve:4,ledgerUpgradeFlags:5,ledgerUpgradeConfig:6,ledgerUpgradeMaxSorobanTxSetSize:7}),e.struct("ConfigUpgradeSetKey",[["contractId",e.lookup("Hash")],["contentHash",e.lookup("Hash")]]),e.union("LedgerUpgrade",{switchOn:e.lookup("LedgerUpgradeType"),switchName:"type",switches:[["ledgerUpgradeVersion","newLedgerVersion"],["ledgerUpgradeBaseFee","newBaseFee"],["ledgerUpgradeMaxTxSetSize","newMaxTxSetSize"],["ledgerUpgradeBaseReserve","newBaseReserve"],["ledgerUpgradeFlags","newFlags"],["ledgerUpgradeConfig","newConfig"],["ledgerUpgradeMaxSorobanTxSetSize","newMaxSorobanTxSetSize"]],arms:{newLedgerVersion:e.lookup("Uint32"),newBaseFee:e.lookup("Uint32"),newMaxTxSetSize:e.lookup("Uint32"),newBaseReserve:e.lookup("Uint32"),newFlags:e.lookup("Uint32"),newConfig:e.lookup("ConfigUpgradeSetKey"),newMaxSorobanTxSetSize:e.lookup("Uint32")}}),e.struct("ConfigUpgradeSet",[["updatedEntry",e.varArray(e.lookup("ConfigSettingEntry"),2147483647)]]),e.enum("TxSetComponentType",{txsetCompTxsMaybeDiscountedFee:0}),e.struct("TxSetComponentTxsMaybeDiscountedFee",[["baseFee",e.option(e.lookup("Int64"))],["txes",e.varArray(e.lookup("TransactionEnvelope"),2147483647)]]),e.union("TxSetComponent",{switchOn:e.lookup("TxSetComponentType"),switchName:"type",switches:[["txsetCompTxsMaybeDiscountedFee","txsMaybeDiscountedFee"]],arms:{txsMaybeDiscountedFee:e.lookup("TxSetComponentTxsMaybeDiscountedFee")}}),e.union("TransactionPhase",{switchOn:e.int(),switchName:"v",switches:[[0,"v0Components"]],arms:{v0Components:e.varArray(e.lookup("TxSetComponent"),2147483647)}}),e.struct("TransactionSet",[["previousLedgerHash",e.lookup("Hash")],["txes",e.varArray(e.lookup("TransactionEnvelope"),2147483647)]]),e.struct("TransactionSetV1",[["previousLedgerHash",e.lookup("Hash")],["phases",e.varArray(e.lookup("TransactionPhase"),2147483647)]]),e.union("GeneralizedTransactionSet",{switchOn:e.int(),switchName:"v",switches:[[1,"v1TxSet"]],arms:{v1TxSet:e.lookup("TransactionSetV1")}}),e.struct("TransactionResultPair",[["transactionHash",e.lookup("Hash")],["result",e.lookup("TransactionResult")]]),e.struct("TransactionResultSet",[["results",e.varArray(e.lookup("TransactionResultPair"),2147483647)]]),e.union("TransactionHistoryEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"generalizedTxSet"]],arms:{generalizedTxSet:e.lookup("GeneralizedTransactionSet")}}),e.struct("TransactionHistoryEntry",[["ledgerSeq",e.lookup("Uint32")],["txSet",e.lookup("TransactionSet")],["ext",e.lookup("TransactionHistoryEntryExt")]]),e.union("TransactionHistoryResultEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionHistoryResultEntry",[["ledgerSeq",e.lookup("Uint32")],["txResultSet",e.lookup("TransactionResultSet")],["ext",e.lookup("TransactionHistoryResultEntryExt")]]),e.union("LedgerHeaderHistoryEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerHeaderHistoryEntry",[["hash",e.lookup("Hash")],["header",e.lookup("LedgerHeader")],["ext",e.lookup("LedgerHeaderHistoryEntryExt")]]),e.struct("LedgerScpMessages",[["ledgerSeq",e.lookup("Uint32")],["messages",e.varArray(e.lookup("ScpEnvelope"),2147483647)]]),e.struct("ScpHistoryEntryV0",[["quorumSets",e.varArray(e.lookup("ScpQuorumSet"),2147483647)],["ledgerMessages",e.lookup("LedgerScpMessages")]]),e.union("ScpHistoryEntry",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("ScpHistoryEntryV0")}}),e.enum("LedgerEntryChangeType",{ledgerEntryCreated:0,ledgerEntryUpdated:1,ledgerEntryRemoved:2,ledgerEntryState:3}),e.union("LedgerEntryChange",{switchOn:e.lookup("LedgerEntryChangeType"),switchName:"type",switches:[["ledgerEntryCreated","created"],["ledgerEntryUpdated","updated"],["ledgerEntryRemoved","removed"],["ledgerEntryState","state"]],arms:{created:e.lookup("LedgerEntry"),updated:e.lookup("LedgerEntry"),removed:e.lookup("LedgerKey"),state:e.lookup("LedgerEntry")}}),e.typedef("LedgerEntryChanges",e.varArray(e.lookup("LedgerEntryChange"),2147483647)),e.struct("OperationMeta",[["changes",e.lookup("LedgerEntryChanges")]]),e.struct("TransactionMetaV1",[["txChanges",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)]]),e.struct("TransactionMetaV2",[["txChangesBefore",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)],["txChangesAfter",e.lookup("LedgerEntryChanges")]]),e.enum("ContractEventType",{system:0,contract:1,diagnostic:2}),e.struct("ContractEventV0",[["topics",e.varArray(e.lookup("ScVal"),2147483647)],["data",e.lookup("ScVal")]]),e.union("ContractEventBody",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("ContractEventV0")}}),e.struct("ContractEvent",[["ext",e.lookup("ExtensionPoint")],["contractId",e.option(e.lookup("Hash"))],["type",e.lookup("ContractEventType")],["body",e.lookup("ContractEventBody")]]),e.struct("DiagnosticEvent",[["inSuccessfulContractCall",e.bool()],["event",e.lookup("ContractEvent")]]),e.typedef("DiagnosticEvents",e.varArray(e.lookup("DiagnosticEvent"),2147483647)),e.struct("SorobanTransactionMetaExtV1",[["ext",e.lookup("ExtensionPoint")],["totalNonRefundableResourceFeeCharged",e.lookup("Int64")],["totalRefundableResourceFeeCharged",e.lookup("Int64")],["rentFeeCharged",e.lookup("Int64")]]),e.union("SorobanTransactionMetaExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("SorobanTransactionMetaExtV1")}}),e.struct("SorobanTransactionMeta",[["ext",e.lookup("SorobanTransactionMetaExt")],["events",e.varArray(e.lookup("ContractEvent"),2147483647)],["returnValue",e.lookup("ScVal")],["diagnosticEvents",e.varArray(e.lookup("DiagnosticEvent"),2147483647)]]),e.struct("TransactionMetaV3",[["ext",e.lookup("ExtensionPoint")],["txChangesBefore",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)],["txChangesAfter",e.lookup("LedgerEntryChanges")],["sorobanMeta",e.option(e.lookup("SorobanTransactionMeta"))]]),e.struct("InvokeHostFunctionSuccessPreImage",[["returnValue",e.lookup("ScVal")],["events",e.varArray(e.lookup("ContractEvent"),2147483647)]]),e.union("TransactionMeta",{switchOn:e.int(),switchName:"v",switches:[[0,"operations"],[1,"v1"],[2,"v2"],[3,"v3"]],arms:{operations:e.varArray(e.lookup("OperationMeta"),2147483647),v1:e.lookup("TransactionMetaV1"),v2:e.lookup("TransactionMetaV2"),v3:e.lookup("TransactionMetaV3")}}),e.struct("TransactionResultMeta",[["result",e.lookup("TransactionResultPair")],["feeProcessing",e.lookup("LedgerEntryChanges")],["txApplyProcessing",e.lookup("TransactionMeta")]]),e.struct("UpgradeEntryMeta",[["upgrade",e.lookup("LedgerUpgrade")],["changes",e.lookup("LedgerEntryChanges")]]),e.struct("LedgerCloseMetaV0",[["ledgerHeader",e.lookup("LedgerHeaderHistoryEntry")],["txSet",e.lookup("TransactionSet")],["txProcessing",e.varArray(e.lookup("TransactionResultMeta"),2147483647)],["upgradesProcessing",e.varArray(e.lookup("UpgradeEntryMeta"),2147483647)],["scpInfo",e.varArray(e.lookup("ScpHistoryEntry"),2147483647)]]),e.struct("LedgerCloseMetaExtV1",[["ext",e.lookup("ExtensionPoint")],["sorobanFeeWrite1Kb",e.lookup("Int64")]]),e.union("LedgerCloseMetaExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerCloseMetaExtV1")}}),e.struct("LedgerCloseMetaV1",[["ext",e.lookup("LedgerCloseMetaExt")],["ledgerHeader",e.lookup("LedgerHeaderHistoryEntry")],["txSet",e.lookup("GeneralizedTransactionSet")],["txProcessing",e.varArray(e.lookup("TransactionResultMeta"),2147483647)],["upgradesProcessing",e.varArray(e.lookup("UpgradeEntryMeta"),2147483647)],["scpInfo",e.varArray(e.lookup("ScpHistoryEntry"),2147483647)],["totalByteSizeOfBucketList",e.lookup("Uint64")],["evictedTemporaryLedgerKeys",e.varArray(e.lookup("LedgerKey"),2147483647)],["evictedPersistentLedgerEntries",e.varArray(e.lookup("LedgerEntry"),2147483647)]]),e.union("LedgerCloseMeta",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"],[1,"v1"]],arms:{v0:e.lookup("LedgerCloseMetaV0"),v1:e.lookup("LedgerCloseMetaV1")}}),e.enum("ErrorCode",{errMisc:0,errData:1,errConf:2,errAuth:3,errLoad:4}),e.struct("Error",[["code",e.lookup("ErrorCode")],["msg",e.string(100)]]),e.struct("SendMore",[["numMessages",e.lookup("Uint32")]]),e.struct("SendMoreExtended",[["numMessages",e.lookup("Uint32")],["numBytes",e.lookup("Uint32")]]),e.struct("AuthCert",[["pubkey",e.lookup("Curve25519Public")],["expiration",e.lookup("Uint64")],["sig",e.lookup("Signature")]]),e.struct("Hello",[["ledgerVersion",e.lookup("Uint32")],["overlayVersion",e.lookup("Uint32")],["overlayMinVersion",e.lookup("Uint32")],["networkId",e.lookup("Hash")],["versionStr",e.string(100)],["listeningPort",e.int()],["peerId",e.lookup("NodeId")],["cert",e.lookup("AuthCert")],["nonce",e.lookup("Uint256")]]),e.const("AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED",200),e.struct("Auth",[["flags",e.int()]]),e.enum("IpAddrType",{iPv4:0,iPv6:1}),e.union("PeerAddressIp",{switchOn:e.lookup("IpAddrType"),switchName:"type",switches:[["iPv4","ipv4"],["iPv6","ipv6"]],arms:{ipv4:e.opaque(4),ipv6:e.opaque(16)}}),e.struct("PeerAddress",[["ip",e.lookup("PeerAddressIp")],["port",e.lookup("Uint32")],["numFailures",e.lookup("Uint32")]]),e.enum("MessageType",{errorMsg:0,auth:2,dontHave:3,getPeers:4,peers:5,getTxSet:6,txSet:7,generalizedTxSet:17,transaction:8,getScpQuorumset:9,scpQuorumset:10,scpMessage:11,getScpState:12,hello:13,surveyRequest:14,surveyResponse:15,sendMore:16,sendMoreExtended:20,floodAdvert:18,floodDemand:19,timeSlicedSurveyRequest:21,timeSlicedSurveyResponse:22,timeSlicedSurveyStartCollecting:23,timeSlicedSurveyStopCollecting:24}),e.struct("DontHave",[["type",e.lookup("MessageType")],["reqHash",e.lookup("Uint256")]]),e.enum("SurveyMessageCommandType",{surveyTopology:0,timeSlicedSurveyTopology:1}),e.enum("SurveyMessageResponseType",{surveyTopologyResponseV0:0,surveyTopologyResponseV1:1,surveyTopologyResponseV2:2}),e.struct("TimeSlicedSurveyStartCollectingMessage",[["surveyorId",e.lookup("NodeId")],["nonce",e.lookup("Uint32")],["ledgerNum",e.lookup("Uint32")]]),e.struct("SignedTimeSlicedSurveyStartCollectingMessage",[["signature",e.lookup("Signature")],["startCollecting",e.lookup("TimeSlicedSurveyStartCollectingMessage")]]),e.struct("TimeSlicedSurveyStopCollectingMessage",[["surveyorId",e.lookup("NodeId")],["nonce",e.lookup("Uint32")],["ledgerNum",e.lookup("Uint32")]]),e.struct("SignedTimeSlicedSurveyStopCollectingMessage",[["signature",e.lookup("Signature")],["stopCollecting",e.lookup("TimeSlicedSurveyStopCollectingMessage")]]),e.struct("SurveyRequestMessage",[["surveyorPeerId",e.lookup("NodeId")],["surveyedPeerId",e.lookup("NodeId")],["ledgerNum",e.lookup("Uint32")],["encryptionKey",e.lookup("Curve25519Public")],["commandType",e.lookup("SurveyMessageCommandType")]]),e.struct("TimeSlicedSurveyRequestMessage",[["request",e.lookup("SurveyRequestMessage")],["nonce",e.lookup("Uint32")],["inboundPeersIndex",e.lookup("Uint32")],["outboundPeersIndex",e.lookup("Uint32")]]),e.struct("SignedSurveyRequestMessage",[["requestSignature",e.lookup("Signature")],["request",e.lookup("SurveyRequestMessage")]]),e.struct("SignedTimeSlicedSurveyRequestMessage",[["requestSignature",e.lookup("Signature")],["request",e.lookup("TimeSlicedSurveyRequestMessage")]]),e.typedef("EncryptedBody",e.varOpaque(64e3)),e.struct("SurveyResponseMessage",[["surveyorPeerId",e.lookup("NodeId")],["surveyedPeerId",e.lookup("NodeId")],["ledgerNum",e.lookup("Uint32")],["commandType",e.lookup("SurveyMessageCommandType")],["encryptedBody",e.lookup("EncryptedBody")]]),e.struct("TimeSlicedSurveyResponseMessage",[["response",e.lookup("SurveyResponseMessage")],["nonce",e.lookup("Uint32")]]),e.struct("SignedSurveyResponseMessage",[["responseSignature",e.lookup("Signature")],["response",e.lookup("SurveyResponseMessage")]]),e.struct("SignedTimeSlicedSurveyResponseMessage",[["responseSignature",e.lookup("Signature")],["response",e.lookup("TimeSlicedSurveyResponseMessage")]]),e.struct("PeerStats",[["id",e.lookup("NodeId")],["versionStr",e.string(100)],["messagesRead",e.lookup("Uint64")],["messagesWritten",e.lookup("Uint64")],["bytesRead",e.lookup("Uint64")],["bytesWritten",e.lookup("Uint64")],["secondsConnected",e.lookup("Uint64")],["uniqueFloodBytesRecv",e.lookup("Uint64")],["duplicateFloodBytesRecv",e.lookup("Uint64")],["uniqueFetchBytesRecv",e.lookup("Uint64")],["duplicateFetchBytesRecv",e.lookup("Uint64")],["uniqueFloodMessageRecv",e.lookup("Uint64")],["duplicateFloodMessageRecv",e.lookup("Uint64")],["uniqueFetchMessageRecv",e.lookup("Uint64")],["duplicateFetchMessageRecv",e.lookup("Uint64")]]),e.typedef("PeerStatList",e.varArray(e.lookup("PeerStats"),25)),e.struct("TimeSlicedNodeData",[["addedAuthenticatedPeers",e.lookup("Uint32")],["droppedAuthenticatedPeers",e.lookup("Uint32")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")],["p75ScpFirstToSelfLatencyMs",e.lookup("Uint32")],["p75ScpSelfToOtherLatencyMs",e.lookup("Uint32")],["lostSyncCount",e.lookup("Uint32")],["isValidator",e.bool()],["maxInboundPeerCount",e.lookup("Uint32")],["maxOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TimeSlicedPeerData",[["peerStats",e.lookup("PeerStats")],["averageLatencyMs",e.lookup("Uint32")]]),e.typedef("TimeSlicedPeerDataList",e.varArray(e.lookup("TimeSlicedPeerData"),25)),e.struct("TopologyResponseBodyV0",[["inboundPeers",e.lookup("PeerStatList")],["outboundPeers",e.lookup("PeerStatList")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TopologyResponseBodyV1",[["inboundPeers",e.lookup("PeerStatList")],["outboundPeers",e.lookup("PeerStatList")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")],["maxInboundPeerCount",e.lookup("Uint32")],["maxOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TopologyResponseBodyV2",[["inboundPeers",e.lookup("TimeSlicedPeerDataList")],["outboundPeers",e.lookup("TimeSlicedPeerDataList")],["nodeData",e.lookup("TimeSlicedNodeData")]]),e.union("SurveyResponseBody",{switchOn:e.lookup("SurveyMessageResponseType"),switchName:"type",switches:[["surveyTopologyResponseV0","topologyResponseBodyV0"],["surveyTopologyResponseV1","topologyResponseBodyV1"],["surveyTopologyResponseV2","topologyResponseBodyV2"]],arms:{topologyResponseBodyV0:e.lookup("TopologyResponseBodyV0"),topologyResponseBodyV1:e.lookup("TopologyResponseBodyV1"),topologyResponseBodyV2:e.lookup("TopologyResponseBodyV2")}}),e.const("TX_ADVERT_VECTOR_MAX_SIZE",1e3),e.typedef("TxAdvertVector",e.varArray(e.lookup("Hash"),e.lookup("TX_ADVERT_VECTOR_MAX_SIZE"))),e.struct("FloodAdvert",[["txHashes",e.lookup("TxAdvertVector")]]),e.const("TX_DEMAND_VECTOR_MAX_SIZE",1e3),e.typedef("TxDemandVector",e.varArray(e.lookup("Hash"),e.lookup("TX_DEMAND_VECTOR_MAX_SIZE"))),e.struct("FloodDemand",[["txHashes",e.lookup("TxDemandVector")]]),e.union("StellarMessage",{switchOn:e.lookup("MessageType"),switchName:"type",switches:[["errorMsg","error"],["hello","hello"],["auth","auth"],["dontHave","dontHave"],["getPeers",e.void()],["peers","peers"],["getTxSet","txSetHash"],["txSet","txSet"],["generalizedTxSet","generalizedTxSet"],["transaction","transaction"],["surveyRequest","signedSurveyRequestMessage"],["surveyResponse","signedSurveyResponseMessage"],["timeSlicedSurveyRequest","signedTimeSlicedSurveyRequestMessage"],["timeSlicedSurveyResponse","signedTimeSlicedSurveyResponseMessage"],["timeSlicedSurveyStartCollecting","signedTimeSlicedSurveyStartCollectingMessage"],["timeSlicedSurveyStopCollecting","signedTimeSlicedSurveyStopCollectingMessage"],["getScpQuorumset","qSetHash"],["scpQuorumset","qSet"],["scpMessage","envelope"],["getScpState","getScpLedgerSeq"],["sendMore","sendMoreMessage"],["sendMoreExtended","sendMoreExtendedMessage"],["floodAdvert","floodAdvert"],["floodDemand","floodDemand"]],arms:{error:e.lookup("Error"),hello:e.lookup("Hello"),auth:e.lookup("Auth"),dontHave:e.lookup("DontHave"),peers:e.varArray(e.lookup("PeerAddress"),100),txSetHash:e.lookup("Uint256"),txSet:e.lookup("TransactionSet"),generalizedTxSet:e.lookup("GeneralizedTransactionSet"),transaction:e.lookup("TransactionEnvelope"),signedSurveyRequestMessage:e.lookup("SignedSurveyRequestMessage"),signedSurveyResponseMessage:e.lookup("SignedSurveyResponseMessage"),signedTimeSlicedSurveyRequestMessage:e.lookup("SignedTimeSlicedSurveyRequestMessage"),signedTimeSlicedSurveyResponseMessage:e.lookup("SignedTimeSlicedSurveyResponseMessage"),signedTimeSlicedSurveyStartCollectingMessage:e.lookup("SignedTimeSlicedSurveyStartCollectingMessage"),signedTimeSlicedSurveyStopCollectingMessage:e.lookup("SignedTimeSlicedSurveyStopCollectingMessage"),qSetHash:e.lookup("Uint256"),qSet:e.lookup("ScpQuorumSet"),envelope:e.lookup("ScpEnvelope"),getScpLedgerSeq:e.lookup("Uint32"),sendMoreMessage:e.lookup("SendMore"),sendMoreExtendedMessage:e.lookup("SendMoreExtended"),floodAdvert:e.lookup("FloodAdvert"),floodDemand:e.lookup("FloodDemand")}}),e.struct("AuthenticatedMessageV0",[["sequence",e.lookup("Uint64")],["message",e.lookup("StellarMessage")],["mac",e.lookup("HmacSha256Mac")]]),e.union("AuthenticatedMessage",{switchOn:e.lookup("Uint32"),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("AuthenticatedMessageV0")}}),e.const("MAX_OPS_PER_TX",100),e.union("LiquidityPoolParameters",{switchOn:e.lookup("LiquidityPoolType"),switchName:"type",switches:[["liquidityPoolConstantProduct","constantProduct"]],arms:{constantProduct:e.lookup("LiquidityPoolConstantProductParameters")}}),e.struct("MuxedAccountMed25519",[["id",e.lookup("Uint64")],["ed25519",e.lookup("Uint256")]]),e.union("MuxedAccount",{switchOn:e.lookup("CryptoKeyType"),switchName:"type",switches:[["keyTypeEd25519","ed25519"],["keyTypeMuxedEd25519","med25519"]],arms:{ed25519:e.lookup("Uint256"),med25519:e.lookup("MuxedAccountMed25519")}}),e.struct("DecoratedSignature",[["hint",e.lookup("SignatureHint")],["signature",e.lookup("Signature")]]),e.enum("OperationType",{createAccount:0,payment:1,pathPaymentStrictReceive:2,manageSellOffer:3,createPassiveSellOffer:4,setOptions:5,changeTrust:6,allowTrust:7,accountMerge:8,inflation:9,manageData:10,bumpSequence:11,manageBuyOffer:12,pathPaymentStrictSend:13,createClaimableBalance:14,claimClaimableBalance:15,beginSponsoringFutureReserves:16,endSponsoringFutureReserves:17,revokeSponsorship:18,clawback:19,clawbackClaimableBalance:20,setTrustLineFlags:21,liquidityPoolDeposit:22,liquidityPoolWithdraw:23,invokeHostFunction:24,extendFootprintTtl:25,restoreFootprint:26}),e.struct("CreateAccountOp",[["destination",e.lookup("AccountId")],["startingBalance",e.lookup("Int64")]]),e.struct("PaymentOp",[["destination",e.lookup("MuxedAccount")],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")]]),e.struct("PathPaymentStrictReceiveOp",[["sendAsset",e.lookup("Asset")],["sendMax",e.lookup("Int64")],["destination",e.lookup("MuxedAccount")],["destAsset",e.lookup("Asset")],["destAmount",e.lookup("Int64")],["path",e.varArray(e.lookup("Asset"),5)]]),e.struct("PathPaymentStrictSendOp",[["sendAsset",e.lookup("Asset")],["sendAmount",e.lookup("Int64")],["destination",e.lookup("MuxedAccount")],["destAsset",e.lookup("Asset")],["destMin",e.lookup("Int64")],["path",e.varArray(e.lookup("Asset"),5)]]),e.struct("ManageSellOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")],["offerId",e.lookup("Int64")]]),e.struct("ManageBuyOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["buyAmount",e.lookup("Int64")],["price",e.lookup("Price")],["offerId",e.lookup("Int64")]]),e.struct("CreatePassiveSellOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")]]),e.struct("SetOptionsOp",[["inflationDest",e.option(e.lookup("AccountId"))],["clearFlags",e.option(e.lookup("Uint32"))],["setFlags",e.option(e.lookup("Uint32"))],["masterWeight",e.option(e.lookup("Uint32"))],["lowThreshold",e.option(e.lookup("Uint32"))],["medThreshold",e.option(e.lookup("Uint32"))],["highThreshold",e.option(e.lookup("Uint32"))],["homeDomain",e.option(e.lookup("String32"))],["signer",e.option(e.lookup("Signer"))]]),e.union("ChangeTrustAsset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"],["assetTypePoolShare","liquidityPool"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12"),liquidityPool:e.lookup("LiquidityPoolParameters")}}),e.struct("ChangeTrustOp",[["line",e.lookup("ChangeTrustAsset")],["limit",e.lookup("Int64")]]),e.struct("AllowTrustOp",[["trustor",e.lookup("AccountId")],["asset",e.lookup("AssetCode")],["authorize",e.lookup("Uint32")]]),e.struct("ManageDataOp",[["dataName",e.lookup("String64")],["dataValue",e.option(e.lookup("DataValue"))]]),e.struct("BumpSequenceOp",[["bumpTo",e.lookup("SequenceNumber")]]),e.struct("CreateClaimableBalanceOp",[["asset",e.lookup("Asset")],["amount",e.lookup("Int64")],["claimants",e.varArray(e.lookup("Claimant"),10)]]),e.struct("ClaimClaimableBalanceOp",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("BeginSponsoringFutureReservesOp",[["sponsoredId",e.lookup("AccountId")]]),e.enum("RevokeSponsorshipType",{revokeSponsorshipLedgerEntry:0,revokeSponsorshipSigner:1}),e.struct("RevokeSponsorshipOpSigner",[["accountId",e.lookup("AccountId")],["signerKey",e.lookup("SignerKey")]]),e.union("RevokeSponsorshipOp",{switchOn:e.lookup("RevokeSponsorshipType"),switchName:"type",switches:[["revokeSponsorshipLedgerEntry","ledgerKey"],["revokeSponsorshipSigner","signer"]],arms:{ledgerKey:e.lookup("LedgerKey"),signer:e.lookup("RevokeSponsorshipOpSigner")}}),e.struct("ClawbackOp",[["asset",e.lookup("Asset")],["from",e.lookup("MuxedAccount")],["amount",e.lookup("Int64")]]),e.struct("ClawbackClaimableBalanceOp",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("SetTrustLineFlagsOp",[["trustor",e.lookup("AccountId")],["asset",e.lookup("Asset")],["clearFlags",e.lookup("Uint32")],["setFlags",e.lookup("Uint32")]]),e.const("LIQUIDITY_POOL_FEE_V18",30),e.struct("LiquidityPoolDepositOp",[["liquidityPoolId",e.lookup("PoolId")],["maxAmountA",e.lookup("Int64")],["maxAmountB",e.lookup("Int64")],["minPrice",e.lookup("Price")],["maxPrice",e.lookup("Price")]]),e.struct("LiquidityPoolWithdrawOp",[["liquidityPoolId",e.lookup("PoolId")],["amount",e.lookup("Int64")],["minAmountA",e.lookup("Int64")],["minAmountB",e.lookup("Int64")]]),e.enum("HostFunctionType",{hostFunctionTypeInvokeContract:0,hostFunctionTypeCreateContract:1,hostFunctionTypeUploadContractWasm:2,hostFunctionTypeCreateContractV2:3}),e.enum("ContractIdPreimageType",{contractIdPreimageFromAddress:0,contractIdPreimageFromAsset:1}),e.struct("ContractIdPreimageFromAddress",[["address",e.lookup("ScAddress")],["salt",e.lookup("Uint256")]]),e.union("ContractIdPreimage",{switchOn:e.lookup("ContractIdPreimageType"),switchName:"type",switches:[["contractIdPreimageFromAddress","fromAddress"],["contractIdPreimageFromAsset","fromAsset"]],arms:{fromAddress:e.lookup("ContractIdPreimageFromAddress"),fromAsset:e.lookup("Asset")}}),e.struct("CreateContractArgs",[["contractIdPreimage",e.lookup("ContractIdPreimage")],["executable",e.lookup("ContractExecutable")]]),e.struct("CreateContractArgsV2",[["contractIdPreimage",e.lookup("ContractIdPreimage")],["executable",e.lookup("ContractExecutable")],["constructorArgs",e.varArray(e.lookup("ScVal"),2147483647)]]),e.struct("InvokeContractArgs",[["contractAddress",e.lookup("ScAddress")],["functionName",e.lookup("ScSymbol")],["args",e.varArray(e.lookup("ScVal"),2147483647)]]),e.union("HostFunction",{switchOn:e.lookup("HostFunctionType"),switchName:"type",switches:[["hostFunctionTypeInvokeContract","invokeContract"],["hostFunctionTypeCreateContract","createContract"],["hostFunctionTypeUploadContractWasm","wasm"],["hostFunctionTypeCreateContractV2","createContractV2"]],arms:{invokeContract:e.lookup("InvokeContractArgs"),createContract:e.lookup("CreateContractArgs"),wasm:e.varOpaque(),createContractV2:e.lookup("CreateContractArgsV2")}}),e.enum("SorobanAuthorizedFunctionType",{sorobanAuthorizedFunctionTypeContractFn:0,sorobanAuthorizedFunctionTypeCreateContractHostFn:1,sorobanAuthorizedFunctionTypeCreateContractV2HostFn:2}),e.union("SorobanAuthorizedFunction",{switchOn:e.lookup("SorobanAuthorizedFunctionType"),switchName:"type",switches:[["sorobanAuthorizedFunctionTypeContractFn","contractFn"],["sorobanAuthorizedFunctionTypeCreateContractHostFn","createContractHostFn"],["sorobanAuthorizedFunctionTypeCreateContractV2HostFn","createContractV2HostFn"]],arms:{contractFn:e.lookup("InvokeContractArgs"),createContractHostFn:e.lookup("CreateContractArgs"),createContractV2HostFn:e.lookup("CreateContractArgsV2")}}),e.struct("SorobanAuthorizedInvocation",[["function",e.lookup("SorobanAuthorizedFunction")],["subInvocations",e.varArray(e.lookup("SorobanAuthorizedInvocation"),2147483647)]]),e.struct("SorobanAddressCredentials",[["address",e.lookup("ScAddress")],["nonce",e.lookup("Int64")],["signatureExpirationLedger",e.lookup("Uint32")],["signature",e.lookup("ScVal")]]),e.enum("SorobanCredentialsType",{sorobanCredentialsSourceAccount:0,sorobanCredentialsAddress:1}),e.union("SorobanCredentials",{switchOn:e.lookup("SorobanCredentialsType"),switchName:"type",switches:[["sorobanCredentialsSourceAccount",e.void()],["sorobanCredentialsAddress","address"]],arms:{address:e.lookup("SorobanAddressCredentials")}}),e.struct("SorobanAuthorizationEntry",[["credentials",e.lookup("SorobanCredentials")],["rootInvocation",e.lookup("SorobanAuthorizedInvocation")]]),e.struct("InvokeHostFunctionOp",[["hostFunction",e.lookup("HostFunction")],["auth",e.varArray(e.lookup("SorobanAuthorizationEntry"),2147483647)]]),e.struct("ExtendFootprintTtlOp",[["ext",e.lookup("ExtensionPoint")],["extendTo",e.lookup("Uint32")]]),e.struct("RestoreFootprintOp",[["ext",e.lookup("ExtensionPoint")]]),e.union("OperationBody",{switchOn:e.lookup("OperationType"),switchName:"type",switches:[["createAccount","createAccountOp"],["payment","paymentOp"],["pathPaymentStrictReceive","pathPaymentStrictReceiveOp"],["manageSellOffer","manageSellOfferOp"],["createPassiveSellOffer","createPassiveSellOfferOp"],["setOptions","setOptionsOp"],["changeTrust","changeTrustOp"],["allowTrust","allowTrustOp"],["accountMerge","destination"],["inflation",e.void()],["manageData","manageDataOp"],["bumpSequence","bumpSequenceOp"],["manageBuyOffer","manageBuyOfferOp"],["pathPaymentStrictSend","pathPaymentStrictSendOp"],["createClaimableBalance","createClaimableBalanceOp"],["claimClaimableBalance","claimClaimableBalanceOp"],["beginSponsoringFutureReserves","beginSponsoringFutureReservesOp"],["endSponsoringFutureReserves",e.void()],["revokeSponsorship","revokeSponsorshipOp"],["clawback","clawbackOp"],["clawbackClaimableBalance","clawbackClaimableBalanceOp"],["setTrustLineFlags","setTrustLineFlagsOp"],["liquidityPoolDeposit","liquidityPoolDepositOp"],["liquidityPoolWithdraw","liquidityPoolWithdrawOp"],["invokeHostFunction","invokeHostFunctionOp"],["extendFootprintTtl","extendFootprintTtlOp"],["restoreFootprint","restoreFootprintOp"]],arms:{createAccountOp:e.lookup("CreateAccountOp"),paymentOp:e.lookup("PaymentOp"),pathPaymentStrictReceiveOp:e.lookup("PathPaymentStrictReceiveOp"),manageSellOfferOp:e.lookup("ManageSellOfferOp"),createPassiveSellOfferOp:e.lookup("CreatePassiveSellOfferOp"),setOptionsOp:e.lookup("SetOptionsOp"),changeTrustOp:e.lookup("ChangeTrustOp"),allowTrustOp:e.lookup("AllowTrustOp"),destination:e.lookup("MuxedAccount"),manageDataOp:e.lookup("ManageDataOp"),bumpSequenceOp:e.lookup("BumpSequenceOp"),manageBuyOfferOp:e.lookup("ManageBuyOfferOp"),pathPaymentStrictSendOp:e.lookup("PathPaymentStrictSendOp"),createClaimableBalanceOp:e.lookup("CreateClaimableBalanceOp"),claimClaimableBalanceOp:e.lookup("ClaimClaimableBalanceOp"),beginSponsoringFutureReservesOp:e.lookup("BeginSponsoringFutureReservesOp"),revokeSponsorshipOp:e.lookup("RevokeSponsorshipOp"),clawbackOp:e.lookup("ClawbackOp"),clawbackClaimableBalanceOp:e.lookup("ClawbackClaimableBalanceOp"),setTrustLineFlagsOp:e.lookup("SetTrustLineFlagsOp"),liquidityPoolDepositOp:e.lookup("LiquidityPoolDepositOp"),liquidityPoolWithdrawOp:e.lookup("LiquidityPoolWithdrawOp"),invokeHostFunctionOp:e.lookup("InvokeHostFunctionOp"),extendFootprintTtlOp:e.lookup("ExtendFootprintTtlOp"),restoreFootprintOp:e.lookup("RestoreFootprintOp")}}),e.struct("Operation",[["sourceAccount",e.option(e.lookup("MuxedAccount"))],["body",e.lookup("OperationBody")]]),e.struct("HashIdPreimageOperationId",[["sourceAccount",e.lookup("AccountId")],["seqNum",e.lookup("SequenceNumber")],["opNum",e.lookup("Uint32")]]),e.struct("HashIdPreimageRevokeId",[["sourceAccount",e.lookup("AccountId")],["seqNum",e.lookup("SequenceNumber")],["opNum",e.lookup("Uint32")],["liquidityPoolId",e.lookup("PoolId")],["asset",e.lookup("Asset")]]),e.struct("HashIdPreimageContractId",[["networkId",e.lookup("Hash")],["contractIdPreimage",e.lookup("ContractIdPreimage")]]),e.struct("HashIdPreimageSorobanAuthorization",[["networkId",e.lookup("Hash")],["nonce",e.lookup("Int64")],["signatureExpirationLedger",e.lookup("Uint32")],["invocation",e.lookup("SorobanAuthorizedInvocation")]]),e.union("HashIdPreimage",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeOpId","operationId"],["envelopeTypePoolRevokeOpId","revokeId"],["envelopeTypeContractId","contractId"],["envelopeTypeSorobanAuthorization","sorobanAuthorization"]],arms:{operationId:e.lookup("HashIdPreimageOperationId"),revokeId:e.lookup("HashIdPreimageRevokeId"),contractId:e.lookup("HashIdPreimageContractId"),sorobanAuthorization:e.lookup("HashIdPreimageSorobanAuthorization")}}),e.enum("MemoType",{memoNone:0,memoText:1,memoId:2,memoHash:3,memoReturn:4}),e.union("Memo",{switchOn:e.lookup("MemoType"),switchName:"type",switches:[["memoNone",e.void()],["memoText","text"],["memoId","id"],["memoHash","hash"],["memoReturn","retHash"]],arms:{text:e.string(28),id:e.lookup("Uint64"),hash:e.lookup("Hash"),retHash:e.lookup("Hash")}}),e.struct("TimeBounds",[["minTime",e.lookup("TimePoint")],["maxTime",e.lookup("TimePoint")]]),e.struct("LedgerBounds",[["minLedger",e.lookup("Uint32")],["maxLedger",e.lookup("Uint32")]]),e.struct("PreconditionsV2",[["timeBounds",e.option(e.lookup("TimeBounds"))],["ledgerBounds",e.option(e.lookup("LedgerBounds"))],["minSeqNum",e.option(e.lookup("SequenceNumber"))],["minSeqAge",e.lookup("Duration")],["minSeqLedgerGap",e.lookup("Uint32")],["extraSigners",e.varArray(e.lookup("SignerKey"),2)]]),e.enum("PreconditionType",{precondNone:0,precondTime:1,precondV2:2}),e.union("Preconditions",{switchOn:e.lookup("PreconditionType"),switchName:"type",switches:[["precondNone",e.void()],["precondTime","timeBounds"],["precondV2","v2"]],arms:{timeBounds:e.lookup("TimeBounds"),v2:e.lookup("PreconditionsV2")}}),e.struct("LedgerFootprint",[["readOnly",e.varArray(e.lookup("LedgerKey"),2147483647)],["readWrite",e.varArray(e.lookup("LedgerKey"),2147483647)]]),e.enum("ArchivalProofType",{existence:0,nonexistence:1}),e.struct("ArchivalProofNode",[["index",e.lookup("Uint32")],["hash",e.lookup("Hash")]]),e.typedef("ProofLevel",e.varArray(e.lookup("ArchivalProofNode"),2147483647)),e.struct("NonexistenceProofBody",[["entriesToProve",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["proofLevels",e.varArray(e.lookup("ProofLevel"),2147483647)]]),e.struct("ExistenceProofBody",[["keysToProve",e.varArray(e.lookup("LedgerKey"),2147483647)],["lowBoundEntries",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["highBoundEntries",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["proofLevels",e.varArray(e.lookup("ProofLevel"),2147483647)]]),e.union("ArchivalProofBody",{switchOn:e.lookup("ArchivalProofType"),switchName:"t",switches:[["existence","nonexistenceProof"],["nonexistence","existenceProof"]],arms:{nonexistenceProof:e.lookup("NonexistenceProofBody"),existenceProof:e.lookup("ExistenceProofBody")}}),e.struct("ArchivalProof",[["epoch",e.lookup("Uint32")],["body",e.lookup("ArchivalProofBody")]]),e.struct("SorobanResources",[["footprint",e.lookup("LedgerFootprint")],["instructions",e.lookup("Uint32")],["readBytes",e.lookup("Uint32")],["writeBytes",e.lookup("Uint32")]]),e.struct("SorobanTransactionData",[["ext",e.lookup("ExtensionPoint")],["resources",e.lookup("SorobanResources")],["resourceFee",e.lookup("Int64")]]),e.union("TransactionV0Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionV0",[["sourceAccountEd25519",e.lookup("Uint256")],["fee",e.lookup("Uint32")],["seqNum",e.lookup("SequenceNumber")],["timeBounds",e.option(e.lookup("TimeBounds"))],["memo",e.lookup("Memo")],["operations",e.varArray(e.lookup("Operation"),e.lookup("MAX_OPS_PER_TX"))],["ext",e.lookup("TransactionV0Ext")]]),e.struct("TransactionV0Envelope",[["tx",e.lookup("TransactionV0")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("TransactionExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"sorobanData"]],arms:{sorobanData:e.lookup("SorobanTransactionData")}}),e.struct("Transaction",[["sourceAccount",e.lookup("MuxedAccount")],["fee",e.lookup("Uint32")],["seqNum",e.lookup("SequenceNumber")],["cond",e.lookup("Preconditions")],["memo",e.lookup("Memo")],["operations",e.varArray(e.lookup("Operation"),e.lookup("MAX_OPS_PER_TX"))],["ext",e.lookup("TransactionExt")]]),e.struct("TransactionV1Envelope",[["tx",e.lookup("Transaction")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("FeeBumpTransactionInnerTx",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTx","v1"]],arms:{v1:e.lookup("TransactionV1Envelope")}}),e.union("FeeBumpTransactionExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("FeeBumpTransaction",[["feeSource",e.lookup("MuxedAccount")],["fee",e.lookup("Int64")],["innerTx",e.lookup("FeeBumpTransactionInnerTx")],["ext",e.lookup("FeeBumpTransactionExt")]]),e.struct("FeeBumpTransactionEnvelope",[["tx",e.lookup("FeeBumpTransaction")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("TransactionEnvelope",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTxV0","v0"],["envelopeTypeTx","v1"],["envelopeTypeTxFeeBump","feeBump"]],arms:{v0:e.lookup("TransactionV0Envelope"),v1:e.lookup("TransactionV1Envelope"),feeBump:e.lookup("FeeBumpTransactionEnvelope")}}),e.union("TransactionSignaturePayloadTaggedTransaction",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTx","tx"],["envelopeTypeTxFeeBump","feeBump"]],arms:{tx:e.lookup("Transaction"),feeBump:e.lookup("FeeBumpTransaction")}}),e.struct("TransactionSignaturePayload",[["networkId",e.lookup("Hash")],["taggedTransaction",e.lookup("TransactionSignaturePayloadTaggedTransaction")]]),e.enum("ClaimAtomType",{claimAtomTypeV0:0,claimAtomTypeOrderBook:1,claimAtomTypeLiquidityPool:2}),e.struct("ClaimOfferAtomV0",[["sellerEd25519",e.lookup("Uint256")],["offerId",e.lookup("Int64")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.struct("ClaimOfferAtom",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.struct("ClaimLiquidityAtom",[["liquidityPoolId",e.lookup("PoolId")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.union("ClaimAtom",{switchOn:e.lookup("ClaimAtomType"),switchName:"type",switches:[["claimAtomTypeV0","v0"],["claimAtomTypeOrderBook","orderBook"],["claimAtomTypeLiquidityPool","liquidityPool"]],arms:{v0:e.lookup("ClaimOfferAtomV0"),orderBook:e.lookup("ClaimOfferAtom"),liquidityPool:e.lookup("ClaimLiquidityAtom")}}),e.enum("CreateAccountResultCode",{createAccountSuccess:0,createAccountMalformed:-1,createAccountUnderfunded:-2,createAccountLowReserve:-3,createAccountAlreadyExist:-4}),e.union("CreateAccountResult",{switchOn:e.lookup("CreateAccountResultCode"),switchName:"code",switches:[["createAccountSuccess",e.void()],["createAccountMalformed",e.void()],["createAccountUnderfunded",e.void()],["createAccountLowReserve",e.void()],["createAccountAlreadyExist",e.void()]],arms:{}}),e.enum("PaymentResultCode",{paymentSuccess:0,paymentMalformed:-1,paymentUnderfunded:-2,paymentSrcNoTrust:-3,paymentSrcNotAuthorized:-4,paymentNoDestination:-5,paymentNoTrust:-6,paymentNotAuthorized:-7,paymentLineFull:-8,paymentNoIssuer:-9}),e.union("PaymentResult",{switchOn:e.lookup("PaymentResultCode"),switchName:"code",switches:[["paymentSuccess",e.void()],["paymentMalformed",e.void()],["paymentUnderfunded",e.void()],["paymentSrcNoTrust",e.void()],["paymentSrcNotAuthorized",e.void()],["paymentNoDestination",e.void()],["paymentNoTrust",e.void()],["paymentNotAuthorized",e.void()],["paymentLineFull",e.void()],["paymentNoIssuer",e.void()]],arms:{}}),e.enum("PathPaymentStrictReceiveResultCode",{pathPaymentStrictReceiveSuccess:0,pathPaymentStrictReceiveMalformed:-1,pathPaymentStrictReceiveUnderfunded:-2,pathPaymentStrictReceiveSrcNoTrust:-3,pathPaymentStrictReceiveSrcNotAuthorized:-4,pathPaymentStrictReceiveNoDestination:-5,pathPaymentStrictReceiveNoTrust:-6,pathPaymentStrictReceiveNotAuthorized:-7,pathPaymentStrictReceiveLineFull:-8,pathPaymentStrictReceiveNoIssuer:-9,pathPaymentStrictReceiveTooFewOffers:-10,pathPaymentStrictReceiveOfferCrossSelf:-11,pathPaymentStrictReceiveOverSendmax:-12}),e.struct("SimplePaymentResult",[["destination",e.lookup("AccountId")],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")]]),e.struct("PathPaymentStrictReceiveResultSuccess",[["offers",e.varArray(e.lookup("ClaimAtom"),2147483647)],["last",e.lookup("SimplePaymentResult")]]),e.union("PathPaymentStrictReceiveResult",{switchOn:e.lookup("PathPaymentStrictReceiveResultCode"),switchName:"code",switches:[["pathPaymentStrictReceiveSuccess","success"],["pathPaymentStrictReceiveMalformed",e.void()],["pathPaymentStrictReceiveUnderfunded",e.void()],["pathPaymentStrictReceiveSrcNoTrust",e.void()],["pathPaymentStrictReceiveSrcNotAuthorized",e.void()],["pathPaymentStrictReceiveNoDestination",e.void()],["pathPaymentStrictReceiveNoTrust",e.void()],["pathPaymentStrictReceiveNotAuthorized",e.void()],["pathPaymentStrictReceiveLineFull",e.void()],["pathPaymentStrictReceiveNoIssuer","noIssuer"],["pathPaymentStrictReceiveTooFewOffers",e.void()],["pathPaymentStrictReceiveOfferCrossSelf",e.void()],["pathPaymentStrictReceiveOverSendmax",e.void()]],arms:{success:e.lookup("PathPaymentStrictReceiveResultSuccess"),noIssuer:e.lookup("Asset")}}),e.enum("PathPaymentStrictSendResultCode",{pathPaymentStrictSendSuccess:0,pathPaymentStrictSendMalformed:-1,pathPaymentStrictSendUnderfunded:-2,pathPaymentStrictSendSrcNoTrust:-3,pathPaymentStrictSendSrcNotAuthorized:-4,pathPaymentStrictSendNoDestination:-5,pathPaymentStrictSendNoTrust:-6,pathPaymentStrictSendNotAuthorized:-7,pathPaymentStrictSendLineFull:-8,pathPaymentStrictSendNoIssuer:-9,pathPaymentStrictSendTooFewOffers:-10,pathPaymentStrictSendOfferCrossSelf:-11,pathPaymentStrictSendUnderDestmin:-12}),e.struct("PathPaymentStrictSendResultSuccess",[["offers",e.varArray(e.lookup("ClaimAtom"),2147483647)],["last",e.lookup("SimplePaymentResult")]]),e.union("PathPaymentStrictSendResult",{switchOn:e.lookup("PathPaymentStrictSendResultCode"),switchName:"code",switches:[["pathPaymentStrictSendSuccess","success"],["pathPaymentStrictSendMalformed",e.void()],["pathPaymentStrictSendUnderfunded",e.void()],["pathPaymentStrictSendSrcNoTrust",e.void()],["pathPaymentStrictSendSrcNotAuthorized",e.void()],["pathPaymentStrictSendNoDestination",e.void()],["pathPaymentStrictSendNoTrust",e.void()],["pathPaymentStrictSendNotAuthorized",e.void()],["pathPaymentStrictSendLineFull",e.void()],["pathPaymentStrictSendNoIssuer","noIssuer"],["pathPaymentStrictSendTooFewOffers",e.void()],["pathPaymentStrictSendOfferCrossSelf",e.void()],["pathPaymentStrictSendUnderDestmin",e.void()]],arms:{success:e.lookup("PathPaymentStrictSendResultSuccess"),noIssuer:e.lookup("Asset")}}),e.enum("ManageSellOfferResultCode",{manageSellOfferSuccess:0,manageSellOfferMalformed:-1,manageSellOfferSellNoTrust:-2,manageSellOfferBuyNoTrust:-3,manageSellOfferSellNotAuthorized:-4,manageSellOfferBuyNotAuthorized:-5,manageSellOfferLineFull:-6,manageSellOfferUnderfunded:-7,manageSellOfferCrossSelf:-8,manageSellOfferSellNoIssuer:-9,manageSellOfferBuyNoIssuer:-10,manageSellOfferNotFound:-11,manageSellOfferLowReserve:-12}),e.enum("ManageOfferEffect",{manageOfferCreated:0,manageOfferUpdated:1,manageOfferDeleted:2}),e.union("ManageOfferSuccessResultOffer",{switchOn:e.lookup("ManageOfferEffect"),switchName:"effect",switches:[["manageOfferCreated","offer"],["manageOfferUpdated","offer"],["manageOfferDeleted",e.void()]],arms:{offer:e.lookup("OfferEntry")}}),e.struct("ManageOfferSuccessResult",[["offersClaimed",e.varArray(e.lookup("ClaimAtom"),2147483647)],["offer",e.lookup("ManageOfferSuccessResultOffer")]]),e.union("ManageSellOfferResult",{switchOn:e.lookup("ManageSellOfferResultCode"),switchName:"code",switches:[["manageSellOfferSuccess","success"],["manageSellOfferMalformed",e.void()],["manageSellOfferSellNoTrust",e.void()],["manageSellOfferBuyNoTrust",e.void()],["manageSellOfferSellNotAuthorized",e.void()],["manageSellOfferBuyNotAuthorized",e.void()],["manageSellOfferLineFull",e.void()],["manageSellOfferUnderfunded",e.void()],["manageSellOfferCrossSelf",e.void()],["manageSellOfferSellNoIssuer",e.void()],["manageSellOfferBuyNoIssuer",e.void()],["manageSellOfferNotFound",e.void()],["manageSellOfferLowReserve",e.void()]],arms:{success:e.lookup("ManageOfferSuccessResult")}}),e.enum("ManageBuyOfferResultCode",{manageBuyOfferSuccess:0,manageBuyOfferMalformed:-1,manageBuyOfferSellNoTrust:-2,manageBuyOfferBuyNoTrust:-3,manageBuyOfferSellNotAuthorized:-4,manageBuyOfferBuyNotAuthorized:-5,manageBuyOfferLineFull:-6,manageBuyOfferUnderfunded:-7,manageBuyOfferCrossSelf:-8,manageBuyOfferSellNoIssuer:-9,manageBuyOfferBuyNoIssuer:-10,manageBuyOfferNotFound:-11,manageBuyOfferLowReserve:-12}),e.union("ManageBuyOfferResult",{switchOn:e.lookup("ManageBuyOfferResultCode"),switchName:"code",switches:[["manageBuyOfferSuccess","success"],["manageBuyOfferMalformed",e.void()],["manageBuyOfferSellNoTrust",e.void()],["manageBuyOfferBuyNoTrust",e.void()],["manageBuyOfferSellNotAuthorized",e.void()],["manageBuyOfferBuyNotAuthorized",e.void()],["manageBuyOfferLineFull",e.void()],["manageBuyOfferUnderfunded",e.void()],["manageBuyOfferCrossSelf",e.void()],["manageBuyOfferSellNoIssuer",e.void()],["manageBuyOfferBuyNoIssuer",e.void()],["manageBuyOfferNotFound",e.void()],["manageBuyOfferLowReserve",e.void()]],arms:{success:e.lookup("ManageOfferSuccessResult")}}),e.enum("SetOptionsResultCode",{setOptionsSuccess:0,setOptionsLowReserve:-1,setOptionsTooManySigners:-2,setOptionsBadFlags:-3,setOptionsInvalidInflation:-4,setOptionsCantChange:-5,setOptionsUnknownFlag:-6,setOptionsThresholdOutOfRange:-7,setOptionsBadSigner:-8,setOptionsInvalidHomeDomain:-9,setOptionsAuthRevocableRequired:-10}),e.union("SetOptionsResult",{switchOn:e.lookup("SetOptionsResultCode"),switchName:"code",switches:[["setOptionsSuccess",e.void()],["setOptionsLowReserve",e.void()],["setOptionsTooManySigners",e.void()],["setOptionsBadFlags",e.void()],["setOptionsInvalidInflation",e.void()],["setOptionsCantChange",e.void()],["setOptionsUnknownFlag",e.void()],["setOptionsThresholdOutOfRange",e.void()],["setOptionsBadSigner",e.void()],["setOptionsInvalidHomeDomain",e.void()],["setOptionsAuthRevocableRequired",e.void()]],arms:{}}),e.enum("ChangeTrustResultCode",{changeTrustSuccess:0,changeTrustMalformed:-1,changeTrustNoIssuer:-2,changeTrustInvalidLimit:-3,changeTrustLowReserve:-4,changeTrustSelfNotAllowed:-5,changeTrustTrustLineMissing:-6,changeTrustCannotDelete:-7,changeTrustNotAuthMaintainLiabilities:-8}),e.union("ChangeTrustResult",{switchOn:e.lookup("ChangeTrustResultCode"),switchName:"code",switches:[["changeTrustSuccess",e.void()],["changeTrustMalformed",e.void()],["changeTrustNoIssuer",e.void()],["changeTrustInvalidLimit",e.void()],["changeTrustLowReserve",e.void()],["changeTrustSelfNotAllowed",e.void()],["changeTrustTrustLineMissing",e.void()],["changeTrustCannotDelete",e.void()],["changeTrustNotAuthMaintainLiabilities",e.void()]],arms:{}}),e.enum("AllowTrustResultCode",{allowTrustSuccess:0,allowTrustMalformed:-1,allowTrustNoTrustLine:-2,allowTrustTrustNotRequired:-3,allowTrustCantRevoke:-4,allowTrustSelfNotAllowed:-5,allowTrustLowReserve:-6}),e.union("AllowTrustResult",{switchOn:e.lookup("AllowTrustResultCode"),switchName:"code",switches:[["allowTrustSuccess",e.void()],["allowTrustMalformed",e.void()],["allowTrustNoTrustLine",e.void()],["allowTrustTrustNotRequired",e.void()],["allowTrustCantRevoke",e.void()],["allowTrustSelfNotAllowed",e.void()],["allowTrustLowReserve",e.void()]],arms:{}}),e.enum("AccountMergeResultCode",{accountMergeSuccess:0,accountMergeMalformed:-1,accountMergeNoAccount:-2,accountMergeImmutableSet:-3,accountMergeHasSubEntries:-4,accountMergeSeqnumTooFar:-5,accountMergeDestFull:-6,accountMergeIsSponsor:-7}),e.union("AccountMergeResult",{switchOn:e.lookup("AccountMergeResultCode"),switchName:"code",switches:[["accountMergeSuccess","sourceAccountBalance"],["accountMergeMalformed",e.void()],["accountMergeNoAccount",e.void()],["accountMergeImmutableSet",e.void()],["accountMergeHasSubEntries",e.void()],["accountMergeSeqnumTooFar",e.void()],["accountMergeDestFull",e.void()],["accountMergeIsSponsor",e.void()]],arms:{sourceAccountBalance:e.lookup("Int64")}}),e.enum("InflationResultCode",{inflationSuccess:0,inflationNotTime:-1}),e.struct("InflationPayout",[["destination",e.lookup("AccountId")],["amount",e.lookup("Int64")]]),e.union("InflationResult",{switchOn:e.lookup("InflationResultCode"),switchName:"code",switches:[["inflationSuccess","payouts"],["inflationNotTime",e.void()]],arms:{payouts:e.varArray(e.lookup("InflationPayout"),2147483647)}}),e.enum("ManageDataResultCode",{manageDataSuccess:0,manageDataNotSupportedYet:-1,manageDataNameNotFound:-2,manageDataLowReserve:-3,manageDataInvalidName:-4}),e.union("ManageDataResult",{switchOn:e.lookup("ManageDataResultCode"),switchName:"code",switches:[["manageDataSuccess",e.void()],["manageDataNotSupportedYet",e.void()],["manageDataNameNotFound",e.void()],["manageDataLowReserve",e.void()],["manageDataInvalidName",e.void()]],arms:{}}),e.enum("BumpSequenceResultCode",{bumpSequenceSuccess:0,bumpSequenceBadSeq:-1}),e.union("BumpSequenceResult",{switchOn:e.lookup("BumpSequenceResultCode"),switchName:"code",switches:[["bumpSequenceSuccess",e.void()],["bumpSequenceBadSeq",e.void()]],arms:{}}),e.enum("CreateClaimableBalanceResultCode",{createClaimableBalanceSuccess:0,createClaimableBalanceMalformed:-1,createClaimableBalanceLowReserve:-2,createClaimableBalanceNoTrust:-3,createClaimableBalanceNotAuthorized:-4,createClaimableBalanceUnderfunded:-5}),e.union("CreateClaimableBalanceResult",{switchOn:e.lookup("CreateClaimableBalanceResultCode"),switchName:"code",switches:[["createClaimableBalanceSuccess","balanceId"],["createClaimableBalanceMalformed",e.void()],["createClaimableBalanceLowReserve",e.void()],["createClaimableBalanceNoTrust",e.void()],["createClaimableBalanceNotAuthorized",e.void()],["createClaimableBalanceUnderfunded",e.void()]],arms:{balanceId:e.lookup("ClaimableBalanceId")}}),e.enum("ClaimClaimableBalanceResultCode",{claimClaimableBalanceSuccess:0,claimClaimableBalanceDoesNotExist:-1,claimClaimableBalanceCannotClaim:-2,claimClaimableBalanceLineFull:-3,claimClaimableBalanceNoTrust:-4,claimClaimableBalanceNotAuthorized:-5}),e.union("ClaimClaimableBalanceResult",{switchOn:e.lookup("ClaimClaimableBalanceResultCode"),switchName:"code",switches:[["claimClaimableBalanceSuccess",e.void()],["claimClaimableBalanceDoesNotExist",e.void()],["claimClaimableBalanceCannotClaim",e.void()],["claimClaimableBalanceLineFull",e.void()],["claimClaimableBalanceNoTrust",e.void()],["claimClaimableBalanceNotAuthorized",e.void()]],arms:{}}),e.enum("BeginSponsoringFutureReservesResultCode",{beginSponsoringFutureReservesSuccess:0,beginSponsoringFutureReservesMalformed:-1,beginSponsoringFutureReservesAlreadySponsored:-2,beginSponsoringFutureReservesRecursive:-3}),e.union("BeginSponsoringFutureReservesResult",{switchOn:e.lookup("BeginSponsoringFutureReservesResultCode"),switchName:"code",switches:[["beginSponsoringFutureReservesSuccess",e.void()],["beginSponsoringFutureReservesMalformed",e.void()],["beginSponsoringFutureReservesAlreadySponsored",e.void()],["beginSponsoringFutureReservesRecursive",e.void()]],arms:{}}),e.enum("EndSponsoringFutureReservesResultCode",{endSponsoringFutureReservesSuccess:0,endSponsoringFutureReservesNotSponsored:-1}),e.union("EndSponsoringFutureReservesResult",{switchOn:e.lookup("EndSponsoringFutureReservesResultCode"),switchName:"code",switches:[["endSponsoringFutureReservesSuccess",e.void()],["endSponsoringFutureReservesNotSponsored",e.void()]],arms:{}}),e.enum("RevokeSponsorshipResultCode",{revokeSponsorshipSuccess:0,revokeSponsorshipDoesNotExist:-1,revokeSponsorshipNotSponsor:-2,revokeSponsorshipLowReserve:-3,revokeSponsorshipOnlyTransferable:-4,revokeSponsorshipMalformed:-5}),e.union("RevokeSponsorshipResult",{switchOn:e.lookup("RevokeSponsorshipResultCode"),switchName:"code",switches:[["revokeSponsorshipSuccess",e.void()],["revokeSponsorshipDoesNotExist",e.void()],["revokeSponsorshipNotSponsor",e.void()],["revokeSponsorshipLowReserve",e.void()],["revokeSponsorshipOnlyTransferable",e.void()],["revokeSponsorshipMalformed",e.void()]],arms:{}}),e.enum("ClawbackResultCode",{clawbackSuccess:0,clawbackMalformed:-1,clawbackNotClawbackEnabled:-2,clawbackNoTrust:-3,clawbackUnderfunded:-4}),e.union("ClawbackResult",{switchOn:e.lookup("ClawbackResultCode"),switchName:"code",switches:[["clawbackSuccess",e.void()],["clawbackMalformed",e.void()],["clawbackNotClawbackEnabled",e.void()],["clawbackNoTrust",e.void()],["clawbackUnderfunded",e.void()]],arms:{}}),e.enum("ClawbackClaimableBalanceResultCode",{clawbackClaimableBalanceSuccess:0,clawbackClaimableBalanceDoesNotExist:-1,clawbackClaimableBalanceNotIssuer:-2,clawbackClaimableBalanceNotClawbackEnabled:-3}),e.union("ClawbackClaimableBalanceResult",{switchOn:e.lookup("ClawbackClaimableBalanceResultCode"),switchName:"code",switches:[["clawbackClaimableBalanceSuccess",e.void()],["clawbackClaimableBalanceDoesNotExist",e.void()],["clawbackClaimableBalanceNotIssuer",e.void()],["clawbackClaimableBalanceNotClawbackEnabled",e.void()]],arms:{}}),e.enum("SetTrustLineFlagsResultCode",{setTrustLineFlagsSuccess:0,setTrustLineFlagsMalformed:-1,setTrustLineFlagsNoTrustLine:-2,setTrustLineFlagsCantRevoke:-3,setTrustLineFlagsInvalidState:-4,setTrustLineFlagsLowReserve:-5}),e.union("SetTrustLineFlagsResult",{switchOn:e.lookup("SetTrustLineFlagsResultCode"),switchName:"code",switches:[["setTrustLineFlagsSuccess",e.void()],["setTrustLineFlagsMalformed",e.void()],["setTrustLineFlagsNoTrustLine",e.void()],["setTrustLineFlagsCantRevoke",e.void()],["setTrustLineFlagsInvalidState",e.void()],["setTrustLineFlagsLowReserve",e.void()]],arms:{}}),e.enum("LiquidityPoolDepositResultCode",{liquidityPoolDepositSuccess:0,liquidityPoolDepositMalformed:-1,liquidityPoolDepositNoTrust:-2,liquidityPoolDepositNotAuthorized:-3,liquidityPoolDepositUnderfunded:-4,liquidityPoolDepositLineFull:-5,liquidityPoolDepositBadPrice:-6,liquidityPoolDepositPoolFull:-7}),e.union("LiquidityPoolDepositResult",{switchOn:e.lookup("LiquidityPoolDepositResultCode"),switchName:"code",switches:[["liquidityPoolDepositSuccess",e.void()],["liquidityPoolDepositMalformed",e.void()],["liquidityPoolDepositNoTrust",e.void()],["liquidityPoolDepositNotAuthorized",e.void()],["liquidityPoolDepositUnderfunded",e.void()],["liquidityPoolDepositLineFull",e.void()],["liquidityPoolDepositBadPrice",e.void()],["liquidityPoolDepositPoolFull",e.void()]],arms:{}}),e.enum("LiquidityPoolWithdrawResultCode",{liquidityPoolWithdrawSuccess:0,liquidityPoolWithdrawMalformed:-1,liquidityPoolWithdrawNoTrust:-2,liquidityPoolWithdrawUnderfunded:-3,liquidityPoolWithdrawLineFull:-4,liquidityPoolWithdrawUnderMinimum:-5}),e.union("LiquidityPoolWithdrawResult",{switchOn:e.lookup("LiquidityPoolWithdrawResultCode"),switchName:"code",switches:[["liquidityPoolWithdrawSuccess",e.void()],["liquidityPoolWithdrawMalformed",e.void()],["liquidityPoolWithdrawNoTrust",e.void()],["liquidityPoolWithdrawUnderfunded",e.void()],["liquidityPoolWithdrawLineFull",e.void()],["liquidityPoolWithdrawUnderMinimum",e.void()]],arms:{}}),e.enum("InvokeHostFunctionResultCode",{invokeHostFunctionSuccess:0,invokeHostFunctionMalformed:-1,invokeHostFunctionTrapped:-2,invokeHostFunctionResourceLimitExceeded:-3,invokeHostFunctionEntryArchived:-4,invokeHostFunctionInsufficientRefundableFee:-5}),e.union("InvokeHostFunctionResult",{switchOn:e.lookup("InvokeHostFunctionResultCode"),switchName:"code",switches:[["invokeHostFunctionSuccess","success"],["invokeHostFunctionMalformed",e.void()],["invokeHostFunctionTrapped",e.void()],["invokeHostFunctionResourceLimitExceeded",e.void()],["invokeHostFunctionEntryArchived",e.void()],["invokeHostFunctionInsufficientRefundableFee",e.void()]],arms:{success:e.lookup("Hash")}}),e.enum("ExtendFootprintTtlResultCode",{extendFootprintTtlSuccess:0,extendFootprintTtlMalformed:-1,extendFootprintTtlResourceLimitExceeded:-2,extendFootprintTtlInsufficientRefundableFee:-3}),e.union("ExtendFootprintTtlResult",{switchOn:e.lookup("ExtendFootprintTtlResultCode"),switchName:"code",switches:[["extendFootprintTtlSuccess",e.void()],["extendFootprintTtlMalformed",e.void()],["extendFootprintTtlResourceLimitExceeded",e.void()],["extendFootprintTtlInsufficientRefundableFee",e.void()]],arms:{}}),e.enum("RestoreFootprintResultCode",{restoreFootprintSuccess:0,restoreFootprintMalformed:-1,restoreFootprintResourceLimitExceeded:-2,restoreFootprintInsufficientRefundableFee:-3}),e.union("RestoreFootprintResult",{switchOn:e.lookup("RestoreFootprintResultCode"),switchName:"code",switches:[["restoreFootprintSuccess",e.void()],["restoreFootprintMalformed",e.void()],["restoreFootprintResourceLimitExceeded",e.void()],["restoreFootprintInsufficientRefundableFee",e.void()]],arms:{}}),e.enum("OperationResultCode",{opInner:0,opBadAuth:-1,opNoAccount:-2,opNotSupported:-3,opTooManySubentries:-4,opExceededWorkLimit:-5,opTooManySponsoring:-6}),e.union("OperationResultTr",{switchOn:e.lookup("OperationType"),switchName:"type",switches:[["createAccount","createAccountResult"],["payment","paymentResult"],["pathPaymentStrictReceive","pathPaymentStrictReceiveResult"],["manageSellOffer","manageSellOfferResult"],["createPassiveSellOffer","createPassiveSellOfferResult"],["setOptions","setOptionsResult"],["changeTrust","changeTrustResult"],["allowTrust","allowTrustResult"],["accountMerge","accountMergeResult"],["inflation","inflationResult"],["manageData","manageDataResult"],["bumpSequence","bumpSeqResult"],["manageBuyOffer","manageBuyOfferResult"],["pathPaymentStrictSend","pathPaymentStrictSendResult"],["createClaimableBalance","createClaimableBalanceResult"],["claimClaimableBalance","claimClaimableBalanceResult"],["beginSponsoringFutureReserves","beginSponsoringFutureReservesResult"],["endSponsoringFutureReserves","endSponsoringFutureReservesResult"],["revokeSponsorship","revokeSponsorshipResult"],["clawback","clawbackResult"],["clawbackClaimableBalance","clawbackClaimableBalanceResult"],["setTrustLineFlags","setTrustLineFlagsResult"],["liquidityPoolDeposit","liquidityPoolDepositResult"],["liquidityPoolWithdraw","liquidityPoolWithdrawResult"],["invokeHostFunction","invokeHostFunctionResult"],["extendFootprintTtl","extendFootprintTtlResult"],["restoreFootprint","restoreFootprintResult"]],arms:{createAccountResult:e.lookup("CreateAccountResult"),paymentResult:e.lookup("PaymentResult"),pathPaymentStrictReceiveResult:e.lookup("PathPaymentStrictReceiveResult"),manageSellOfferResult:e.lookup("ManageSellOfferResult"),createPassiveSellOfferResult:e.lookup("ManageSellOfferResult"),setOptionsResult:e.lookup("SetOptionsResult"),changeTrustResult:e.lookup("ChangeTrustResult"),allowTrustResult:e.lookup("AllowTrustResult"),accountMergeResult:e.lookup("AccountMergeResult"),inflationResult:e.lookup("InflationResult"),manageDataResult:e.lookup("ManageDataResult"),bumpSeqResult:e.lookup("BumpSequenceResult"),manageBuyOfferResult:e.lookup("ManageBuyOfferResult"),pathPaymentStrictSendResult:e.lookup("PathPaymentStrictSendResult"),createClaimableBalanceResult:e.lookup("CreateClaimableBalanceResult"),claimClaimableBalanceResult:e.lookup("ClaimClaimableBalanceResult"),beginSponsoringFutureReservesResult:e.lookup("BeginSponsoringFutureReservesResult"),endSponsoringFutureReservesResult:e.lookup("EndSponsoringFutureReservesResult"),revokeSponsorshipResult:e.lookup("RevokeSponsorshipResult"),clawbackResult:e.lookup("ClawbackResult"),clawbackClaimableBalanceResult:e.lookup("ClawbackClaimableBalanceResult"),setTrustLineFlagsResult:e.lookup("SetTrustLineFlagsResult"),liquidityPoolDepositResult:e.lookup("LiquidityPoolDepositResult"),liquidityPoolWithdrawResult:e.lookup("LiquidityPoolWithdrawResult"),invokeHostFunctionResult:e.lookup("InvokeHostFunctionResult"),extendFootprintTtlResult:e.lookup("ExtendFootprintTtlResult"),restoreFootprintResult:e.lookup("RestoreFootprintResult")}}),e.union("OperationResult",{switchOn:e.lookup("OperationResultCode"),switchName:"code",switches:[["opInner","tr"],["opBadAuth",e.void()],["opNoAccount",e.void()],["opNotSupported",e.void()],["opTooManySubentries",e.void()],["opExceededWorkLimit",e.void()],["opTooManySponsoring",e.void()]],arms:{tr:e.lookup("OperationResultTr")}}),e.enum("TransactionResultCode",{txFeeBumpInnerSuccess:1,txSuccess:0,txFailed:-1,txTooEarly:-2,txTooLate:-3,txMissingOperation:-4,txBadSeq:-5,txBadAuth:-6,txInsufficientBalance:-7,txNoAccount:-8,txInsufficientFee:-9,txBadAuthExtra:-10,txInternalError:-11,txNotSupported:-12,txFeeBumpInnerFailed:-13,txBadSponsorship:-14,txBadMinSeqAgeOrGap:-15,txMalformed:-16,txSorobanInvalid:-17}),e.union("InnerTransactionResultResult",{switchOn:e.lookup("TransactionResultCode"),switchName:"code",switches:[["txSuccess","results"],["txFailed","results"],["txTooEarly",e.void()],["txTooLate",e.void()],["txMissingOperation",e.void()],["txBadSeq",e.void()],["txBadAuth",e.void()],["txInsufficientBalance",e.void()],["txNoAccount",e.void()],["txInsufficientFee",e.void()],["txBadAuthExtra",e.void()],["txInternalError",e.void()],["txNotSupported",e.void()],["txBadSponsorship",e.void()],["txBadMinSeqAgeOrGap",e.void()],["txMalformed",e.void()],["txSorobanInvalid",e.void()]],arms:{results:e.varArray(e.lookup("OperationResult"),2147483647)}}),e.union("InnerTransactionResultExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("InnerTransactionResult",[["feeCharged",e.lookup("Int64")],["result",e.lookup("InnerTransactionResultResult")],["ext",e.lookup("InnerTransactionResultExt")]]),e.struct("InnerTransactionResultPair",[["transactionHash",e.lookup("Hash")],["result",e.lookup("InnerTransactionResult")]]),e.union("TransactionResultResult",{switchOn:e.lookup("TransactionResultCode"),switchName:"code",switches:[["txFeeBumpInnerSuccess","innerResultPair"],["txFeeBumpInnerFailed","innerResultPair"],["txSuccess","results"],["txFailed","results"],["txTooEarly",e.void()],["txTooLate",e.void()],["txMissingOperation",e.void()],["txBadSeq",e.void()],["txBadAuth",e.void()],["txInsufficientBalance",e.void()],["txNoAccount",e.void()],["txInsufficientFee",e.void()],["txBadAuthExtra",e.void()],["txInternalError",e.void()],["txNotSupported",e.void()],["txBadSponsorship",e.void()],["txBadMinSeqAgeOrGap",e.void()],["txMalformed",e.void()],["txSorobanInvalid",e.void()]],arms:{innerResultPair:e.lookup("InnerTransactionResultPair"),results:e.varArray(e.lookup("OperationResult"),2147483647)}}),e.union("TransactionResultExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionResult",[["feeCharged",e.lookup("Int64")],["result",e.lookup("TransactionResultResult")],["ext",e.lookup("TransactionResultExt")]]),e.typedef("Hash",e.opaque(32)),e.typedef("Uint256",e.opaque(32)),e.typedef("Uint32",e.uint()),e.typedef("Int32",e.int()),e.typedef("Uint64",e.uhyper()),e.typedef("Int64",e.hyper()),e.typedef("TimePoint",e.lookup("Uint64")),e.typedef("Duration",e.lookup("Uint64")),e.union("ExtensionPoint",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.enum("CryptoKeyType",{keyTypeEd25519:0,keyTypePreAuthTx:1,keyTypeHashX:2,keyTypeEd25519SignedPayload:3,keyTypeMuxedEd25519:256}),e.enum("PublicKeyType",{publicKeyTypeEd25519:0}),e.enum("SignerKeyType",{signerKeyTypeEd25519:0,signerKeyTypePreAuthTx:1,signerKeyTypeHashX:2,signerKeyTypeEd25519SignedPayload:3}),e.union("PublicKey",{switchOn:e.lookup("PublicKeyType"),switchName:"type",switches:[["publicKeyTypeEd25519","ed25519"]],arms:{ed25519:e.lookup("Uint256")}}),e.struct("SignerKeyEd25519SignedPayload",[["ed25519",e.lookup("Uint256")],["payload",e.varOpaque(64)]]),e.union("SignerKey",{switchOn:e.lookup("SignerKeyType"),switchName:"type",switches:[["signerKeyTypeEd25519","ed25519"],["signerKeyTypePreAuthTx","preAuthTx"],["signerKeyTypeHashX","hashX"],["signerKeyTypeEd25519SignedPayload","ed25519SignedPayload"]],arms:{ed25519:e.lookup("Uint256"),preAuthTx:e.lookup("Uint256"),hashX:e.lookup("Uint256"),ed25519SignedPayload:e.lookup("SignerKeyEd25519SignedPayload")}}),e.typedef("Signature",e.varOpaque(64)),e.typedef("SignatureHint",e.opaque(4)),e.typedef("NodeId",e.lookup("PublicKey")),e.typedef("AccountId",e.lookup("PublicKey")),e.struct("Curve25519Secret",[["key",e.opaque(32)]]),e.struct("Curve25519Public",[["key",e.opaque(32)]]),e.struct("HmacSha256Key",[["key",e.opaque(32)]]),e.struct("HmacSha256Mac",[["mac",e.opaque(32)]]),e.struct("ShortHashSeed",[["seed",e.opaque(16)]]),e.enum("BinaryFuseFilterType",{binaryFuseFilter8Bit:0,binaryFuseFilter16Bit:1,binaryFuseFilter32Bit:2}),e.struct("SerializedBinaryFuseFilter",[["type",e.lookup("BinaryFuseFilterType")],["inputHashSeed",e.lookup("ShortHashSeed")],["filterSeed",e.lookup("ShortHashSeed")],["segmentLength",e.lookup("Uint32")],["segementLengthMask",e.lookup("Uint32")],["segmentCount",e.lookup("Uint32")],["segmentCountLength",e.lookup("Uint32")],["fingerprintLength",e.lookup("Uint32")],["fingerprints",e.varOpaque()]]),e.enum("ScValType",{scvBool:0,scvVoid:1,scvError:2,scvU32:3,scvI32:4,scvU64:5,scvI64:6,scvTimepoint:7,scvDuration:8,scvU128:9,scvI128:10,scvU256:11,scvI256:12,scvBytes:13,scvString:14,scvSymbol:15,scvVec:16,scvMap:17,scvAddress:18,scvContractInstance:19,scvLedgerKeyContractInstance:20,scvLedgerKeyNonce:21}),e.enum("ScErrorType",{sceContract:0,sceWasmVm:1,sceContext:2,sceStorage:3,sceObject:4,sceCrypto:5,sceEvents:6,sceBudget:7,sceValue:8,sceAuth:9}),e.enum("ScErrorCode",{scecArithDomain:0,scecIndexBounds:1,scecInvalidInput:2,scecMissingValue:3,scecExistingValue:4,scecExceededLimit:5,scecInvalidAction:6,scecInternalError:7,scecUnexpectedType:8,scecUnexpectedSize:9}),e.union("ScError",{switchOn:e.lookup("ScErrorType"),switchName:"type",switches:[["sceContract","contractCode"],["sceWasmVm","code"],["sceContext","code"],["sceStorage","code"],["sceObject","code"],["sceCrypto","code"],["sceEvents","code"],["sceBudget","code"],["sceValue","code"],["sceAuth","code"]],arms:{contractCode:e.lookup("Uint32"),code:e.lookup("ScErrorCode")}}),e.struct("UInt128Parts",[["hi",e.lookup("Uint64")],["lo",e.lookup("Uint64")]]),e.struct("Int128Parts",[["hi",e.lookup("Int64")],["lo",e.lookup("Uint64")]]),e.struct("UInt256Parts",[["hiHi",e.lookup("Uint64")],["hiLo",e.lookup("Uint64")],["loHi",e.lookup("Uint64")],["loLo",e.lookup("Uint64")]]),e.struct("Int256Parts",[["hiHi",e.lookup("Int64")],["hiLo",e.lookup("Uint64")],["loHi",e.lookup("Uint64")],["loLo",e.lookup("Uint64")]]),e.enum("ContractExecutableType",{contractExecutableWasm:0,contractExecutableStellarAsset:1}),e.union("ContractExecutable",{switchOn:e.lookup("ContractExecutableType"),switchName:"type",switches:[["contractExecutableWasm","wasmHash"],["contractExecutableStellarAsset",e.void()]],arms:{wasmHash:e.lookup("Hash")}}),e.enum("ScAddressType",{scAddressTypeAccount:0,scAddressTypeContract:1}),e.union("ScAddress",{switchOn:e.lookup("ScAddressType"),switchName:"type",switches:[["scAddressTypeAccount","accountId"],["scAddressTypeContract","contractId"]],arms:{accountId:e.lookup("AccountId"),contractId:e.lookup("Hash")}}),e.const("SCSYMBOL_LIMIT",32),e.typedef("ScVec",e.varArray(e.lookup("ScVal"),2147483647)),e.typedef("ScMap",e.varArray(e.lookup("ScMapEntry"),2147483647)),e.typedef("ScBytes",e.varOpaque()),e.typedef("ScString",e.string()),e.typedef("ScSymbol",e.string(32)),e.struct("ScNonceKey",[["nonce",e.lookup("Int64")]]),e.struct("ScContractInstance",[["executable",e.lookup("ContractExecutable")],["storage",e.option(e.lookup("ScMap"))]]),e.union("ScVal",{switchOn:e.lookup("ScValType"),switchName:"type",switches:[["scvBool","b"],["scvVoid",e.void()],["scvError","error"],["scvU32","u32"],["scvI32","i32"],["scvU64","u64"],["scvI64","i64"],["scvTimepoint","timepoint"],["scvDuration","duration"],["scvU128","u128"],["scvI128","i128"],["scvU256","u256"],["scvI256","i256"],["scvBytes","bytes"],["scvString","str"],["scvSymbol","sym"],["scvVec","vec"],["scvMap","map"],["scvAddress","address"],["scvLedgerKeyContractInstance",e.void()],["scvLedgerKeyNonce","nonceKey"],["scvContractInstance","instance"]],arms:{b:e.bool(),error:e.lookup("ScError"),u32:e.lookup("Uint32"),i32:e.lookup("Int32"),u64:e.lookup("Uint64"),i64:e.lookup("Int64"),timepoint:e.lookup("TimePoint"),duration:e.lookup("Duration"),u128:e.lookup("UInt128Parts"),i128:e.lookup("Int128Parts"),u256:e.lookup("UInt256Parts"),i256:e.lookup("Int256Parts"),bytes:e.lookup("ScBytes"),str:e.lookup("ScString"),sym:e.lookup("ScSymbol"),vec:e.option(e.lookup("ScVec")),map:e.option(e.lookup("ScMap")),address:e.lookup("ScAddress"),nonceKey:e.lookup("ScNonceKey"),instance:e.lookup("ScContractInstance")}}),e.struct("ScMapEntry",[["key",e.lookup("ScVal")],["val",e.lookup("ScVal")]]),e.enum("ScEnvMetaKind",{scEnvMetaKindInterfaceVersion:0}),e.struct("ScEnvMetaEntryInterfaceVersion",[["protocol",e.lookup("Uint32")],["preRelease",e.lookup("Uint32")]]),e.union("ScEnvMetaEntry",{switchOn:e.lookup("ScEnvMetaKind"),switchName:"kind",switches:[["scEnvMetaKindInterfaceVersion","interfaceVersion"]],arms:{interfaceVersion:e.lookup("ScEnvMetaEntryInterfaceVersion")}}),e.struct("ScMetaV0",[["key",e.string()],["val",e.string()]]),e.enum("ScMetaKind",{scMetaV0:0}),e.union("ScMetaEntry",{switchOn:e.lookup("ScMetaKind"),switchName:"kind",switches:[["scMetaV0","v0"]],arms:{v0:e.lookup("ScMetaV0")}}),e.const("SC_SPEC_DOC_LIMIT",1024),e.enum("ScSpecType",{scSpecTypeVal:0,scSpecTypeBool:1,scSpecTypeVoid:2,scSpecTypeError:3,scSpecTypeU32:4,scSpecTypeI32:5,scSpecTypeU64:6,scSpecTypeI64:7,scSpecTypeTimepoint:8,scSpecTypeDuration:9,scSpecTypeU128:10,scSpecTypeI128:11,scSpecTypeU256:12,scSpecTypeI256:13,scSpecTypeBytes:14,scSpecTypeString:16,scSpecTypeSymbol:17,scSpecTypeAddress:19,scSpecTypeOption:1e3,scSpecTypeResult:1001,scSpecTypeVec:1002,scSpecTypeMap:1004,scSpecTypeTuple:1005,scSpecTypeBytesN:1006,scSpecTypeUdt:2e3}),e.struct("ScSpecTypeOption",[["valueType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeResult",[["okType",e.lookup("ScSpecTypeDef")],["errorType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeVec",[["elementType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeMap",[["keyType",e.lookup("ScSpecTypeDef")],["valueType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeTuple",[["valueTypes",e.varArray(e.lookup("ScSpecTypeDef"),12)]]),e.struct("ScSpecTypeBytesN",[["n",e.lookup("Uint32")]]),e.struct("ScSpecTypeUdt",[["name",e.string(60)]]),e.union("ScSpecTypeDef",{switchOn:e.lookup("ScSpecType"),switchName:"type",switches:[["scSpecTypeVal",e.void()],["scSpecTypeBool",e.void()],["scSpecTypeVoid",e.void()],["scSpecTypeError",e.void()],["scSpecTypeU32",e.void()],["scSpecTypeI32",e.void()],["scSpecTypeU64",e.void()],["scSpecTypeI64",e.void()],["scSpecTypeTimepoint",e.void()],["scSpecTypeDuration",e.void()],["scSpecTypeU128",e.void()],["scSpecTypeI128",e.void()],["scSpecTypeU256",e.void()],["scSpecTypeI256",e.void()],["scSpecTypeBytes",e.void()],["scSpecTypeString",e.void()],["scSpecTypeSymbol",e.void()],["scSpecTypeAddress",e.void()],["scSpecTypeOption","option"],["scSpecTypeResult","result"],["scSpecTypeVec","vec"],["scSpecTypeMap","map"],["scSpecTypeTuple","tuple"],["scSpecTypeBytesN","bytesN"],["scSpecTypeUdt","udt"]],arms:{option:e.lookup("ScSpecTypeOption"),result:e.lookup("ScSpecTypeResult"),vec:e.lookup("ScSpecTypeVec"),map:e.lookup("ScSpecTypeMap"),tuple:e.lookup("ScSpecTypeTuple"),bytesN:e.lookup("ScSpecTypeBytesN"),udt:e.lookup("ScSpecTypeUdt")}}),e.struct("ScSpecUdtStructFieldV0",[["doc",e.string(t)],["name",e.string(30)],["type",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecUdtStructV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["fields",e.varArray(e.lookup("ScSpecUdtStructFieldV0"),40)]]),e.struct("ScSpecUdtUnionCaseVoidV0",[["doc",e.string(t)],["name",e.string(60)]]),e.struct("ScSpecUdtUnionCaseTupleV0",[["doc",e.string(t)],["name",e.string(60)],["type",e.varArray(e.lookup("ScSpecTypeDef"),12)]]),e.enum("ScSpecUdtUnionCaseV0Kind",{scSpecUdtUnionCaseVoidV0:0,scSpecUdtUnionCaseTupleV0:1}),e.union("ScSpecUdtUnionCaseV0",{switchOn:e.lookup("ScSpecUdtUnionCaseV0Kind"),switchName:"kind",switches:[["scSpecUdtUnionCaseVoidV0","voidCase"],["scSpecUdtUnionCaseTupleV0","tupleCase"]],arms:{voidCase:e.lookup("ScSpecUdtUnionCaseVoidV0"),tupleCase:e.lookup("ScSpecUdtUnionCaseTupleV0")}}),e.struct("ScSpecUdtUnionV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtUnionCaseV0"),50)]]),e.struct("ScSpecUdtEnumCaseV0",[["doc",e.string(t)],["name",e.string(60)],["value",e.lookup("Uint32")]]),e.struct("ScSpecUdtEnumV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtEnumCaseV0"),50)]]),e.struct("ScSpecUdtErrorEnumCaseV0",[["doc",e.string(t)],["name",e.string(60)],["value",e.lookup("Uint32")]]),e.struct("ScSpecUdtErrorEnumV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtErrorEnumCaseV0"),50)]]),e.struct("ScSpecFunctionInputV0",[["doc",e.string(t)],["name",e.string(30)],["type",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecFunctionV0",[["doc",e.string(t)],["name",e.lookup("ScSymbol")],["inputs",e.varArray(e.lookup("ScSpecFunctionInputV0"),10)],["outputs",e.varArray(e.lookup("ScSpecTypeDef"),1)]]),e.enum("ScSpecEntryKind",{scSpecEntryFunctionV0:0,scSpecEntryUdtStructV0:1,scSpecEntryUdtUnionV0:2,scSpecEntryUdtEnumV0:3,scSpecEntryUdtErrorEnumV0:4}),e.union("ScSpecEntry",{switchOn:e.lookup("ScSpecEntryKind"),switchName:"kind",switches:[["scSpecEntryFunctionV0","functionV0"],["scSpecEntryUdtStructV0","udtStructV0"],["scSpecEntryUdtUnionV0","udtUnionV0"],["scSpecEntryUdtEnumV0","udtEnumV0"],["scSpecEntryUdtErrorEnumV0","udtErrorEnumV0"]],arms:{functionV0:e.lookup("ScSpecFunctionV0"),udtStructV0:e.lookup("ScSpecUdtStructV0"),udtUnionV0:e.lookup("ScSpecUdtUnionV0"),udtEnumV0:e.lookup("ScSpecUdtEnumV0"),udtErrorEnumV0:e.lookup("ScSpecUdtErrorEnumV0")}}),e.struct("ConfigSettingContractExecutionLanesV0",[["ledgerMaxTxCount",e.lookup("Uint32")]]),e.struct("ConfigSettingContractComputeV0",[["ledgerMaxInstructions",e.lookup("Int64")],["txMaxInstructions",e.lookup("Int64")],["feeRatePerInstructionsIncrement",e.lookup("Int64")],["txMemoryLimit",e.lookup("Uint32")]]),e.struct("ConfigSettingContractLedgerCostV0",[["ledgerMaxReadLedgerEntries",e.lookup("Uint32")],["ledgerMaxReadBytes",e.lookup("Uint32")],["ledgerMaxWriteLedgerEntries",e.lookup("Uint32")],["ledgerMaxWriteBytes",e.lookup("Uint32")],["txMaxReadLedgerEntries",e.lookup("Uint32")],["txMaxReadBytes",e.lookup("Uint32")],["txMaxWriteLedgerEntries",e.lookup("Uint32")],["txMaxWriteBytes",e.lookup("Uint32")],["feeReadLedgerEntry",e.lookup("Int64")],["feeWriteLedgerEntry",e.lookup("Int64")],["feeRead1Kb",e.lookup("Int64")],["bucketListTargetSizeBytes",e.lookup("Int64")],["writeFee1KbBucketListLow",e.lookup("Int64")],["writeFee1KbBucketListHigh",e.lookup("Int64")],["bucketListWriteFeeGrowthFactor",e.lookup("Uint32")]]),e.struct("ConfigSettingContractHistoricalDataV0",[["feeHistorical1Kb",e.lookup("Int64")]]),e.struct("ConfigSettingContractEventsV0",[["txMaxContractEventsSizeBytes",e.lookup("Uint32")],["feeContractEvents1Kb",e.lookup("Int64")]]),e.struct("ConfigSettingContractBandwidthV0",[["ledgerMaxTxsSizeBytes",e.lookup("Uint32")],["txMaxSizeBytes",e.lookup("Uint32")],["feeTxSize1Kb",e.lookup("Int64")]]),e.enum("ContractCostType",{wasmInsnExec:0,memAlloc:1,memCpy:2,memCmp:3,dispatchHostFunction:4,visitObject:5,valSer:6,valDeser:7,computeSha256Hash:8,computeEd25519PubKey:9,verifyEd25519Sig:10,vmInstantiation:11,vmCachedInstantiation:12,invokeVmFunction:13,computeKeccak256Hash:14,decodeEcdsaCurve256Sig:15,recoverEcdsaSecp256k1Key:16,int256AddSub:17,int256Mul:18,int256Div:19,int256Pow:20,int256Shift:21,chaCha20DrawBytes:22,parseWasmInstructions:23,parseWasmFunctions:24,parseWasmGlobals:25,parseWasmTableEntries:26,parseWasmTypes:27,parseWasmDataSegments:28,parseWasmElemSegments:29,parseWasmImports:30,parseWasmExports:31,parseWasmDataSegmentBytes:32,instantiateWasmInstructions:33,instantiateWasmFunctions:34,instantiateWasmGlobals:35,instantiateWasmTableEntries:36,instantiateWasmTypes:37,instantiateWasmDataSegments:38,instantiateWasmElemSegments:39,instantiateWasmImports:40,instantiateWasmExports:41,instantiateWasmDataSegmentBytes:42,sec1DecodePointUncompressed:43,verifyEcdsaSecp256r1Sig:44,bls12381EncodeFp:45,bls12381DecodeFp:46,bls12381G1CheckPointOnCurve:47,bls12381G1CheckPointInSubgroup:48,bls12381G2CheckPointOnCurve:49,bls12381G2CheckPointInSubgroup:50,bls12381G1ProjectiveToAffine:51,bls12381G2ProjectiveToAffine:52,bls12381G1Add:53,bls12381G1Mul:54,bls12381G1Msm:55,bls12381MapFpToG1:56,bls12381HashToG1:57,bls12381G2Add:58,bls12381G2Mul:59,bls12381G2Msm:60,bls12381MapFp2ToG2:61,bls12381HashToG2:62,bls12381Pairing:63,bls12381FrFromU256:64,bls12381FrToU256:65,bls12381FrAddSub:66,bls12381FrMul:67,bls12381FrPow:68,bls12381FrInv:69}),e.struct("ContractCostParamEntry",[["ext",e.lookup("ExtensionPoint")],["constTerm",e.lookup("Int64")],["linearTerm",e.lookup("Int64")]]),e.struct("StateArchivalSettings",[["maxEntryTtl",e.lookup("Uint32")],["minTemporaryTtl",e.lookup("Uint32")],["minPersistentTtl",e.lookup("Uint32")],["persistentRentRateDenominator",e.lookup("Int64")],["tempRentRateDenominator",e.lookup("Int64")],["maxEntriesToArchive",e.lookup("Uint32")],["bucketListSizeWindowSampleSize",e.lookup("Uint32")],["bucketListWindowSamplePeriod",e.lookup("Uint32")],["evictionScanSize",e.lookup("Uint32")],["startingEvictionScanLevel",e.lookup("Uint32")]]),e.struct("EvictionIterator",[["bucketListLevel",e.lookup("Uint32")],["isCurrBucket",e.bool()],["bucketFileOffset",e.lookup("Uint64")]]),e.const("CONTRACT_COST_COUNT_LIMIT",1024),e.typedef("ContractCostParams",e.varArray(e.lookup("ContractCostParamEntry"),e.lookup("CONTRACT_COST_COUNT_LIMIT"))),e.enum("ConfigSettingId",{configSettingContractMaxSizeBytes:0,configSettingContractComputeV0:1,configSettingContractLedgerCostV0:2,configSettingContractHistoricalDataV0:3,configSettingContractEventsV0:4,configSettingContractBandwidthV0:5,configSettingContractCostParamsCpuInstructions:6,configSettingContractCostParamsMemoryBytes:7,configSettingContractDataKeySizeBytes:8,configSettingContractDataEntrySizeBytes:9,configSettingStateArchival:10,configSettingContractExecutionLanes:11,configSettingBucketlistSizeWindow:12,configSettingEvictionIterator:13}),e.union("ConfigSettingEntry",{switchOn:e.lookup("ConfigSettingId"),switchName:"configSettingId",switches:[["configSettingContractMaxSizeBytes","contractMaxSizeBytes"],["configSettingContractComputeV0","contractCompute"],["configSettingContractLedgerCostV0","contractLedgerCost"],["configSettingContractHistoricalDataV0","contractHistoricalData"],["configSettingContractEventsV0","contractEvents"],["configSettingContractBandwidthV0","contractBandwidth"],["configSettingContractCostParamsCpuInstructions","contractCostParamsCpuInsns"],["configSettingContractCostParamsMemoryBytes","contractCostParamsMemBytes"],["configSettingContractDataKeySizeBytes","contractDataKeySizeBytes"],["configSettingContractDataEntrySizeBytes","contractDataEntrySizeBytes"],["configSettingStateArchival","stateArchivalSettings"],["configSettingContractExecutionLanes","contractExecutionLanes"],["configSettingBucketlistSizeWindow","bucketListSizeWindow"],["configSettingEvictionIterator","evictionIterator"]],arms:{contractMaxSizeBytes:e.lookup("Uint32"),contractCompute:e.lookup("ConfigSettingContractComputeV0"),contractLedgerCost:e.lookup("ConfigSettingContractLedgerCostV0"),contractHistoricalData:e.lookup("ConfigSettingContractHistoricalDataV0"),contractEvents:e.lookup("ConfigSettingContractEventsV0"),contractBandwidth:e.lookup("ConfigSettingContractBandwidthV0"),contractCostParamsCpuInsns:e.lookup("ContractCostParams"),contractCostParamsMemBytes:e.lookup("ContractCostParams"),contractDataKeySizeBytes:e.lookup("Uint32"),contractDataEntrySizeBytes:e.lookup("Uint32"),stateArchivalSettings:e.lookup("StateArchivalSettings"),contractExecutionLanes:e.lookup("ConfigSettingContractExecutionLanesV0"),bucketListSizeWindow:e.varArray(e.lookup("Uint64"),2147483647),evictionIterator:e.lookup("EvictionIterator")}})}));t.default=i},5578:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.LiquidityPoolFeeV18=void 0,t.getLiquidityPoolId=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("constant_product"!==e)throw new Error("liquidityPoolType is invalid");var r=t.assetA,o=t.assetB,c=t.fee;if(!(r&&r instanceof a.Asset))throw new Error("assetA is invalid");if(!(o&&o instanceof a.Asset))throw new Error("assetB is invalid");if(!c||c!==u)throw new Error("fee is invalid");if(-1!==a.Asset.compare(r,o))throw new Error("Assets are not in lexicographic order");var l=i.default.LiquidityPoolType.liquidityPoolConstantProduct().toXDR(),f=new i.default.LiquidityPoolConstantProductParameters({assetA:r.toXDRObject(),assetB:o.toXDRObject(),fee:c}).toXDR(),p=n.concat([l,f]);return(0,s.hash)(p)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(1764),s=r(9152);var u=t.LiquidityPoolFeeV18=30},9152:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hash=function(e){var t=new n.sha256;return t.update(e,"utf8"),t.digest()};var n=r(2802)},356:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={xdr:!0,cereal:!0,hash:!0,sign:!0,verify:!0,FastSigning:!0,getLiquidityPoolId:!0,LiquidityPoolFeeV18:!0,Keypair:!0,UnsignedHyper:!0,Hyper:!0,TransactionBase:!0,Transaction:!0,FeeBumpTransaction:!0,TransactionBuilder:!0,TimeoutInfinite:!0,BASE_FEE:!0,Asset:!0,LiquidityPoolAsset:!0,LiquidityPoolId:!0,Operation:!0,AuthRequiredFlag:!0,AuthRevocableFlag:!0,AuthImmutableFlag:!0,AuthClawbackEnabledFlag:!0,Account:!0,MuxedAccount:!0,Claimant:!0,Networks:!0,StrKey:!0,SignerKey:!0,Soroban:!0,decodeAddressToMuxedAccount:!0,encodeMuxedAccountToAddress:!0,extractBaseAddress:!0,encodeMuxedAccount:!0,Contract:!0,Address:!0};Object.defineProperty(t,"Account",{enumerable:!0,get:function(){return w.Account}}),Object.defineProperty(t,"Address",{enumerable:!0,get:function(){return P.Address}}),Object.defineProperty(t,"Asset",{enumerable:!0,get:function(){return y.Asset}}),Object.defineProperty(t,"AuthClawbackEnabledFlag",{enumerable:!0,get:function(){return g.AuthClawbackEnabledFlag}}),Object.defineProperty(t,"AuthImmutableFlag",{enumerable:!0,get:function(){return g.AuthImmutableFlag}}),Object.defineProperty(t,"AuthRequiredFlag",{enumerable:!0,get:function(){return g.AuthRequiredFlag}}),Object.defineProperty(t,"AuthRevocableFlag",{enumerable:!0,get:function(){return g.AuthRevocableFlag}}),Object.defineProperty(t,"BASE_FEE",{enumerable:!0,get:function(){return h.BASE_FEE}}),Object.defineProperty(t,"Claimant",{enumerable:!0,get:function(){return k.Claimant}}),Object.defineProperty(t,"Contract",{enumerable:!0,get:function(){return A.Contract}}),Object.defineProperty(t,"FastSigning",{enumerable:!0,get:function(){return s.FastSigning}}),Object.defineProperty(t,"FeeBumpTransaction",{enumerable:!0,get:function(){return d.FeeBumpTransaction}}),Object.defineProperty(t,"Hyper",{enumerable:!0,get:function(){return l.Hyper}}),Object.defineProperty(t,"Keypair",{enumerable:!0,get:function(){return c.Keypair}}),Object.defineProperty(t,"LiquidityPoolAsset",{enumerable:!0,get:function(){return m.LiquidityPoolAsset}}),Object.defineProperty(t,"LiquidityPoolFeeV18",{enumerable:!0,get:function(){return u.LiquidityPoolFeeV18}}),Object.defineProperty(t,"LiquidityPoolId",{enumerable:!0,get:function(){return v.LiquidityPoolId}}),Object.defineProperty(t,"MuxedAccount",{enumerable:!0,get:function(){return S.MuxedAccount}}),Object.defineProperty(t,"Networks",{enumerable:!0,get:function(){return E.Networks}}),Object.defineProperty(t,"Operation",{enumerable:!0,get:function(){return g.Operation}}),Object.defineProperty(t,"SignerKey",{enumerable:!0,get:function(){return _.SignerKey}}),Object.defineProperty(t,"Soroban",{enumerable:!0,get:function(){return O.Soroban}}),Object.defineProperty(t,"StrKey",{enumerable:!0,get:function(){return T.StrKey}}),Object.defineProperty(t,"TimeoutInfinite",{enumerable:!0,get:function(){return h.TimeoutInfinite}}),Object.defineProperty(t,"Transaction",{enumerable:!0,get:function(){return p.Transaction}}),Object.defineProperty(t,"TransactionBase",{enumerable:!0,get:function(){return f.TransactionBase}}),Object.defineProperty(t,"TransactionBuilder",{enumerable:!0,get:function(){return h.TransactionBuilder}}),Object.defineProperty(t,"UnsignedHyper",{enumerable:!0,get:function(){return l.UnsignedHyper}}),Object.defineProperty(t,"cereal",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(t,"decodeAddressToMuxedAccount",{enumerable:!0,get:function(){return x.decodeAddressToMuxedAccount}}),t.default=void 0,Object.defineProperty(t,"encodeMuxedAccount",{enumerable:!0,get:function(){return x.encodeMuxedAccount}}),Object.defineProperty(t,"encodeMuxedAccountToAddress",{enumerable:!0,get:function(){return x.encodeMuxedAccountToAddress}}),Object.defineProperty(t,"extractBaseAddress",{enumerable:!0,get:function(){return x.extractBaseAddress}}),Object.defineProperty(t,"getLiquidityPoolId",{enumerable:!0,get:function(){return u.getLiquidityPoolId}}),Object.defineProperty(t,"hash",{enumerable:!0,get:function(){return a.hash}}),Object.defineProperty(t,"sign",{enumerable:!0,get:function(){return s.sign}}),Object.defineProperty(t,"verify",{enumerable:!0,get:function(){return s.verify}}),Object.defineProperty(t,"xdr",{enumerable:!0,get:function(){return o.default}});var o=N(r(1918)),i=N(r(3335)),a=r(9152),s=r(15),u=r(5578),c=r(6691),l=r(3740),f=r(3758),p=r(380),d=r(9260),h=r(6396),y=r(1764),m=r(2262),v=r(9353),g=r(7237),b=r(4172);Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===b[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return b[e]}}))}));var w=r(2135),S=r(2243),k=r(1387),E=r(6202),T=r(7120),_=r(225),O=r(4062),x=r(6160),A=r(7452),P=r(1180),R=r(8549);Object.keys(R).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===R[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return R[e]}}))}));var I=r(7177);Object.keys(I).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===I[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return I[e]}}))}));var C=r(3919);Object.keys(C).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===C[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return C[e]}}))}));var j=r(4842);Object.keys(j).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===j[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return j[e]}}))}));var B=r(5328);Object.keys(B).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===B[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return B[e]}}))}));var L=r(3564);function N(e){return e&&e.__esModule?e:{default:e}}Object.keys(L).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===L[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return L[e]}}))}));t.default=e.exports},3564:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildInvocationTree=function e(t){var r=t.function(),a={},c=r.value();switch(r.switch().value){case 0:a.type="execute",a.args={source:o.Address.fromScAddress(c.contractAddress()).toString(),function:c.functionName(),args:c.args().map((function(e){return(0,i.scValToNative)(e)}))};break;case 1:case 2:var l=2===r.switch().value;a.type="create",a.args={};var f=[c.executable(),c.contractIdPreimage()],p=f[0],d=f[1];if(!!p.switch().value!=!!d.switch().value)throw new Error("creation function appears invalid: ".concat(JSON.stringify(c)," (should be wasm+address or token+asset)"));switch(p.switch().value){case 0:var h=d.fromAddress();a.args.type="wasm",a.args.wasm=function(e){for(var t=1;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(3740),o={XdrWriter:n.XdrWriter,XdrReader:n.XdrReader};t.default=o},6691:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.Keypair=void 0;var o=c(r(4940)),i=r(15),a=r(7120),s=r(9152),u=c(r(1918));function c(e){return e&&e.__esModule?e:{default:e}}function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LiquidityPoolAsset=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(1764),a=r(5578);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function c(e){for(var t=1;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LiquidityPoolId=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n};function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.MemoText=t.MemoReturn=t.MemoNone=t.MemoID=t.MemoHash=t.Memo=void 0;var o=r(3740),i=s(r(1242)),a=s(r(1918));function s(e){return e&&e.__esModule?e:{default:e}}function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:null;switch(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._type=t,this._value=r,this._type){case f:break;case p:e._validateIdValue(r);break;case d:e._validateTextValue(r);break;case h:case y:e._validateHashValue(r),"string"==typeof r&&(this._value=n.from(r,"hex"));break;default:throw new Error("Invalid memo type")}}return t=e,s=[{key:"_validateIdValue",value:function(e){var t,r=new Error("Expects a int64 as a string. Got ".concat(e));if("string"!=typeof e)throw r;try{t=new i.default(e)}catch(e){throw r}if(!t.isFinite())throw r;if(t.isNaN())throw r}},{key:"_validateTextValue",value:function(e){if(!a.default.Memo.armTypeForArm("text").isValid(e))throw new Error("Expects string, array or buffer, max 28 bytes")}},{key:"_validateHashValue",value:function(e){var t,r=new Error("Expects a 32 byte hash value or hex encoded string. Got ".concat(e));if(null==e)throw r;if("string"==typeof e){if(!/^[0-9A-Fa-f]{64}$/g.test(e))throw r;t=n.from(e,"hex")}else{if(!n.isBuffer(e))throw r;t=n.from(e)}if(!t.length||32!==t.length)throw r}},{key:"none",value:function(){return new e(f)}},{key:"text",value:function(t){return new e(d,t)}},{key:"id",value:function(t){return new e(p,t)}},{key:"hash",value:function(t){return new e(h,t)}},{key:"return",value:function(t){return new e(y,t)}},{key:"fromXDRObject",value:function(t){switch(t.arm()){case"id":return e.id(t.value().toString());case"text":return e.text(t.value());case"hash":return e.hash(t.value());case"retHash":return e.return(t.value())}if(void 0===t.value())return e.none();throw new Error("Unknown type")}}],(r=[{key:"type",get:function(){return this._type},set:function(e){throw new Error("Memo is immutable")}},{key:"value",get:function(){switch(this._type){case f:return null;case p:case d:return this._value;case h:case y:return n.from(this._value);default:throw new Error("Invalid memo type")}},set:function(e){throw new Error("Memo is immutable")}},{key:"toXDRObject",value:function(){switch(this._type){case f:return a.default.Memo.memoNone();case p:return a.default.Memo.memoId(o.UnsignedHyper.fromString(this._value));case d:return a.default.Memo.memoText(this._value);case h:return a.default.Memo.memoHash(this._value);case y:return a.default.Memo.memoReturn(this._value);default:return null}}}])&&c(t.prototype,r),s&&c(t,s),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,s}()},2243:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MuxedAccount=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(2135),a=r(7120),s=r(6160);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Networks=void 0;t.Networks={PUBLIC:"Public Global Stellar Network ; September 2015",TESTNET:"Test SDF Network ; September 2015",FUTURENET:"Test SDF Future Network ; October 2022",SANDBOX:"Local Sandbox Stellar Network ; September 2022",STANDALONE:"Standalone Network ; February 2017"}},8549:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Int128",{enumerable:!0,get:function(){return a.Int128}}),Object.defineProperty(t,"Int256",{enumerable:!0,get:function(){return s.Int256}}),Object.defineProperty(t,"ScInt",{enumerable:!0,get:function(){return u.ScInt}}),Object.defineProperty(t,"Uint128",{enumerable:!0,get:function(){return o.Uint128}}),Object.defineProperty(t,"Uint256",{enumerable:!0,get:function(){return i.Uint256}}),Object.defineProperty(t,"XdrLargeInt",{enumerable:!0,get:function(){return n.XdrLargeInt}}),t.scValToBigInt=function(e){var t=n.XdrLargeInt.getType(e.switch().name);switch(e.switch().name){case"scvU32":case"scvI32":return BigInt(e.value());case"scvU64":case"scvI64":return new n.XdrLargeInt(t,e.value()).toBigInt();case"scvU128":case"scvI128":return new n.XdrLargeInt(t,[e.value().lo(),e.value().hi()]).toBigInt();case"scvU256":case"scvI256":return new n.XdrLargeInt(t,[e.value().loLo(),e.value().loHi(),e.value().hiLo(),e.value().hiHi()]).toBigInt();default:throw TypeError("expected integer type, got ".concat(e.switch()))}};var n=r(7429),o=r(6272),i=r(8672),a=r(5487),s=r(4063),u=r(3317)},5487:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Int128=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Int256=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.ScInt=void 0;var o=r(7429);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Uint128=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Uint256=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.XdrLargeInt=void 0;var n,o=r(3740),i=r(6272),a=r(8672),s=r(5487),u=r(4063),c=(n=r(1918))&&n.__esModule?n:{default:n};function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){for(var r=0;rNumber.MAX_SAFE_INTEGER||e>64n),r=BigInt.asUintN(64,e);return c.default.ScVal.scvI128(new c.default.Int128Parts({hi:new c.default.Int64(t),lo:new c.default.Uint64(r)}))}},{key:"toU128",value:function(){this._sizeCheck(128);var e=this.int.toBigInt();return c.default.ScVal.scvU128(new c.default.UInt128Parts({hi:new c.default.Uint64(BigInt.asUintN(64,e>>64n)),lo:new c.default.Uint64(BigInt.asUintN(64,e))}))}},{key:"toI256",value:function(){var e=this.int.toBigInt(),t=BigInt.asIntN(64,e>>192n),r=BigInt.asUintN(64,e>>128n),n=BigInt.asUintN(64,e>>64n),o=BigInt.asUintN(64,e);return c.default.ScVal.scvI256(new c.default.Int256Parts({hiHi:new c.default.Int64(t),hiLo:new c.default.Uint64(r),loHi:new c.default.Uint64(n),loLo:new c.default.Uint64(o)}))}},{key:"toU256",value:function(){var e=this.int.toBigInt(),t=BigInt.asUintN(64,e>>192n),r=BigInt.asUintN(64,e>>128n),n=BigInt.asUintN(64,e>>64n),o=BigInt.asUintN(64,e);return c.default.ScVal.scvU256(new c.default.UInt256Parts({hiHi:new c.default.Uint64(t),hiLo:new c.default.Uint64(r),loHi:new c.default.Uint64(n),loLo:new c.default.Uint64(o)}))}},{key:"toScVal",value:function(){switch(this.type){case"i64":return this.toI64();case"i128":return this.toI128();case"i256":return this.toI256();case"u64":return this.toU64();case"u128":return this.toU128();case"u256":return this.toU256();default:throw TypeError("invalid type: ".concat(this.type))}}},{key:"valueOf",value:function(){return this.int.valueOf()}},{key:"toString",value:function(){return this.int.toString()}},{key:"toJSON",value:function(){return{value:this.toBigInt().toString(),type:this.type}}},{key:"_sizeCheck",value:function(e){if(this.int.size>e)throw RangeError("value too large for ".concat(e," bits (").concat(this.type,")"))}}],[{key:"isType",value:function(e){switch(e){case"i64":case"i128":case"i256":case"u64":case"u128":case"u256":return!0;default:return!1}}},{key:"getType",value:function(e){return e.slice(3).toLowerCase()}}])}()},7237:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.AuthRevocableFlag=t.AuthRequiredFlag=t.AuthImmutableFlag=t.AuthClawbackEnabledFlag=void 0;var n=r(3740),o=m(r(1242)),i=r(645),a=r(4151),s=r(1764),u=r(2262),c=r(1387),l=r(7120),f=r(9353),p=m(r(1918)),d=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=v(e)&&"function"!=typeof e)return{default:e};var r=y(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in e)if("default"!==i&&{}.hasOwnProperty.call(e,i)){var a=o?Object.getOwnPropertyDescriptor(e,i):null;a&&(a.get||a.set)?Object.defineProperty(n,i,a):n[i]=e[i]}return n.default=e,r&&r.set(e,n),n}(r(7511)),h=r(6160);function y(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(y=function(e){return e?r:t})(e)}function m(e){return e&&e.__esModule?e:{default:e}}function v(e){return v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},v(e)}function g(e,t){for(var r=0;r1&&void 0!==arguments[1]&&arguments[1];if("string"!=typeof e)return!1;try{t=new o.default(e)}catch(e){return!1}return!(!r&&t.isZero()||t.isNegative()||t.times(w).gt(new o.default("9223372036854775807").toString())||t.decimalPlaces()>7||t.isNaN()||!t.isFinite())}},{key:"constructAmountRequirementsError",value:function(e){return"".concat(e," argument must be of type String, represent a positive number and have at most 7 digits after the decimal")}},{key:"_checkUnsignedIntValue",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;if(void 0!==t)switch("string"==typeof t&&(t=parseFloat(t)),!0){case"number"!=typeof t||!Number.isFinite(t)||t%1!=0:throw new Error("".concat(e," value is invalid"));case t<0:throw new Error("".concat(e," value must be unsigned"));case!r||r&&r(t,e):return t;default:throw new Error("".concat(e," value is invalid"))}}},{key:"_toXDRAmount",value:function(e){var t=new o.default(e).times(w);return n.Hyper.fromString(t.toString())}},{key:"_fromXDRAmount",value:function(e){return new o.default(e).div(w).toFixed(7)}},{key:"_fromXDRPrice",value:function(e){return new o.default(e.n()).div(new o.default(e.d())).toString()}},{key:"_toXDRPrice",value:function(e){var t;if(e.n&&e.d)t=new p.default.Price(e);else{var r=(0,a.best_r)(e);t=new p.default.Price({n:parseInt(r[0],10),d:parseInt(r[1],10)})}if(t.n()<0||t.d()<0)throw new Error("price must be positive");return t}}],(t=null)&&g(e.prototype,t),r&&g(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,r}());function k(e){return l.StrKey.encodeEd25519PublicKey(e.ed25519())}S.accountMerge=d.accountMerge,S.allowTrust=d.allowTrust,S.bumpSequence=d.bumpSequence,S.changeTrust=d.changeTrust,S.createAccount=d.createAccount,S.createClaimableBalance=d.createClaimableBalance,S.claimClaimableBalance=d.claimClaimableBalance,S.clawbackClaimableBalance=d.clawbackClaimableBalance,S.createPassiveSellOffer=d.createPassiveSellOffer,S.inflation=d.inflation,S.manageData=d.manageData,S.manageSellOffer=d.manageSellOffer,S.manageBuyOffer=d.manageBuyOffer,S.pathPaymentStrictReceive=d.pathPaymentStrictReceive,S.pathPaymentStrictSend=d.pathPaymentStrictSend,S.payment=d.payment,S.setOptions=d.setOptions,S.beginSponsoringFutureReserves=d.beginSponsoringFutureReserves,S.endSponsoringFutureReserves=d.endSponsoringFutureReserves,S.revokeAccountSponsorship=d.revokeAccountSponsorship,S.revokeTrustlineSponsorship=d.revokeTrustlineSponsorship,S.revokeOfferSponsorship=d.revokeOfferSponsorship,S.revokeDataSponsorship=d.revokeDataSponsorship,S.revokeClaimableBalanceSponsorship=d.revokeClaimableBalanceSponsorship,S.revokeLiquidityPoolSponsorship=d.revokeLiquidityPoolSponsorship,S.revokeSignerSponsorship=d.revokeSignerSponsorship,S.clawback=d.clawback,S.setTrustLineFlags=d.setTrustLineFlags,S.liquidityPoolDeposit=d.liquidityPoolDeposit,S.liquidityPoolWithdraw=d.liquidityPoolWithdraw,S.invokeHostFunction=d.invokeHostFunction,S.extendFootprintTtl=d.extendFootprintTtl,S.restoreFootprint=d.restoreFootprint,S.createStellarAssetContract=d.createStellarAssetContract,S.invokeContractFunction=d.invokeContractFunction,S.createCustomContract=d.createCustomContract,S.uploadContractWasm=d.uploadContractWasm},4295:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.accountMerge=function(e){var t={};try{t.body=o.default.OperationBody.accountMerge((0,i.decodeAddressToMuxedAccount)(e.destination))}catch(e){throw new Error("destination is invalid")}return this.setSourceAccount(t,e),new o.default.Operation(t)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},3683:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allowTrust=function(e){if(!a.StrKey.isValidEd25519PublicKey(e.trustor))throw new Error("trustor is invalid");var t={};if(t.trustor=i.Keypair.fromPublicKey(e.trustor).xdrAccountId(),e.assetCode.length<=4){var r=e.assetCode.padEnd(4,"\0");t.asset=o.default.AssetCode.assetTypeCreditAlphanum4(r)}else{if(!(e.assetCode.length<=12))throw new Error("Asset code must be 12 characters at max.");var n=e.assetCode.padEnd(12,"\0");t.asset=o.default.AssetCode.assetTypeCreditAlphanum12(n)}"boolean"==typeof e.authorize?e.authorize?t.authorize=o.default.TrustLineFlags.authorizedFlag().value:t.authorize=0:t.authorize=e.authorize;var s=new o.default.AllowTrustOp(t),u={};return u.body=o.default.OperationBody.allowTrust(s),this.setSourceAccount(u,e),new o.default.Operation(u)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691),a=r(7120)},7505:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.beginSponsoringFutureReserves=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!i.StrKey.isValidEd25519PublicKey(e.sponsoredId))throw new Error("sponsoredId is invalid");var t=new o.default.BeginSponsoringFutureReservesOp({sponsoredId:a.Keypair.fromPublicKey(e.sponsoredId).xdrAccountId()}),r={};return r.body=o.default.OperationBody.beginSponsoringFutureReserves(t),this.setSourceAccount(r,e),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(7120),a=r(6691)},6183:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bumpSequence=function(e){var t={};if("string"!=typeof e.bumpTo)throw new Error("bumpTo must be a string");try{new o.default(e.bumpTo)}catch(e){throw new Error("bumpTo must be a stringified number")}t.bumpTo=n.Hyper.fromString(e.bumpTo);var r=new i.default.BumpSequenceOp(t),a={};return a.body=i.default.OperationBody.bumpSequence(r),this.setSourceAccount(a,e),new i.default.Operation(a)};var n=r(3740),o=a(r(1242)),i=a(r(1918));function a(e){return e&&e.__esModule?e:{default:e}}},2810:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.changeTrust=function(e){var t={};if(e.asset instanceof a.Asset)t.line=e.asset.toChangeTrustXDRObject();else{if(!(e.asset instanceof s.LiquidityPoolAsset))throw new TypeError("asset must be Asset or LiquidityPoolAsset");t.line=e.asset.toXDRObject()}if(void 0!==e.limit&&!this.isValidAmount(e.limit,!0))throw new TypeError(this.constructAmountRequirementsError("limit"));e.limit?t.limit=this._toXDRAmount(e.limit):t.limit=n.Hyper.fromString(new o.default(c).toString());e.source&&(t.source=e.source.masterKeypair);var r=new i.default.ChangeTrustOp(t),u={};return u.body=i.default.OperationBody.changeTrust(r),this.setSourceAccount(u,e),new i.default.Operation(u)};var n=r(3740),o=u(r(1242)),i=u(r(1918)),a=r(1764),s=r(2262);function u(e){return e&&e.__esModule?e:{default:e}}var c="9223372036854775807"},7239:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.claimClaimableBalance=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};i(e.balanceId);var t={};t.balanceId=o.default.ClaimableBalanceId.fromXDR(e.balanceId,"hex");var r=new o.default.ClaimClaimableBalanceOp(t),n={};return n.body=o.default.OperationBody.claimClaimableBalance(r),this.setSourceAccount(n,e),new o.default.Operation(n)},t.validateClaimableBalanceId=i;var n,o=(n=r(1918))&&n.__esModule?n:{default:n};function i(e){if("string"!=typeof e||72!==e.length)throw new Error("must provide a valid claimable balance id")}},7651:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clawback=function(e){var t={};if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));t.amount=this._toXDRAmount(e.amount),t.asset=e.asset.toXDRObject();try{t.from=(0,i.decodeAddressToMuxedAccount)(e.from)}catch(e){throw new Error("from address is invalid")}var r={body:o.default.OperationBody.clawback(new o.default.ClawbackOp(t))};return this.setSourceAccount(r,e),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},2203:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clawbackClaimableBalance=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(0,i.validateClaimableBalanceId)(e.balanceId);var t={balanceId:o.default.ClaimableBalanceId.fromXDR(e.balanceId,"hex")},r={body:o.default.OperationBody.clawbackClaimableBalance(new o.default.ClawbackClaimableBalanceOp(t))};return this.setSourceAccount(r,e),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(7239)},2115:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createAccount=function(e){if(!a.StrKey.isValidEd25519PublicKey(e.destination))throw new Error("destination is invalid");if(!this.isValidAmount(e.startingBalance,!0))throw new TypeError(this.constructAmountRequirementsError("startingBalance"));var t={};t.destination=i.Keypair.fromPublicKey(e.destination).xdrAccountId(),t.startingBalance=this._toXDRAmount(e.startingBalance);var r=new o.default.CreateAccountOp(t),n={};return n.body=o.default.OperationBody.createAccount(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691),a=r(7120)},4831:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createClaimableBalance=function(e){if(!(e.asset instanceof i.Asset))throw new Error("must provide an asset for create claimable balance operation");if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(!Array.isArray(e.claimants)||0===e.claimants.length)throw new Error("must provide at least one claimant");var t={};t.asset=e.asset.toXDRObject(),t.amount=this._toXDRAmount(e.amount),t.claimants=Object.values(e.claimants).map((function(e){return e.toXDRObject()}));var r=new o.default.CreateClaimableBalanceOp(t),n={};return n.body=o.default.OperationBody.createClaimableBalance(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(1764)},9073:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createPassiveSellOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price);var r=new o.default.CreatePassiveSellOfferOp(t),n={};return n.body=o.default.OperationBody.createPassiveSellOffer(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},721:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endSponsoringFutureReserves=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};return t.body=o.default.OperationBody.endSponsoringFutureReserves(),this.setSourceAccount(t,e),new o.default.Operation(t)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},8752:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extendFootprintTtl=function(e){var t;if((null!==(t=e.extendTo)&&void 0!==t?t:-1)<=0)throw new RangeError("extendTo has to be positive");var r=new o.default.ExtendFootprintTtlOp({ext:new o.default.ExtensionPoint(0),extendTo:e.extendTo}),n={body:o.default.OperationBody.extendFootprintTtl(r)};return this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},7511:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"accountMerge",{enumerable:!0,get:function(){return i.accountMerge}}),Object.defineProperty(t,"allowTrust",{enumerable:!0,get:function(){return a.allowTrust}}),Object.defineProperty(t,"beginSponsoringFutureReserves",{enumerable:!0,get:function(){return w.beginSponsoringFutureReserves}}),Object.defineProperty(t,"bumpSequence",{enumerable:!0,get:function(){return s.bumpSequence}}),Object.defineProperty(t,"changeTrust",{enumerable:!0,get:function(){return u.changeTrust}}),Object.defineProperty(t,"claimClaimableBalance",{enumerable:!0,get:function(){return f.claimClaimableBalance}}),Object.defineProperty(t,"clawback",{enumerable:!0,get:function(){return E.clawback}}),Object.defineProperty(t,"clawbackClaimableBalance",{enumerable:!0,get:function(){return p.clawbackClaimableBalance}}),Object.defineProperty(t,"createAccount",{enumerable:!0,get:function(){return c.createAccount}}),Object.defineProperty(t,"createClaimableBalance",{enumerable:!0,get:function(){return l.createClaimableBalance}}),Object.defineProperty(t,"createCustomContract",{enumerable:!0,get:function(){return x.createCustomContract}}),Object.defineProperty(t,"createPassiveSellOffer",{enumerable:!0,get:function(){return o.createPassiveSellOffer}}),Object.defineProperty(t,"createStellarAssetContract",{enumerable:!0,get:function(){return x.createStellarAssetContract}}),Object.defineProperty(t,"endSponsoringFutureReserves",{enumerable:!0,get:function(){return S.endSponsoringFutureReserves}}),Object.defineProperty(t,"extendFootprintTtl",{enumerable:!0,get:function(){return A.extendFootprintTtl}}),Object.defineProperty(t,"inflation",{enumerable:!0,get:function(){return d.inflation}}),Object.defineProperty(t,"invokeContractFunction",{enumerable:!0,get:function(){return x.invokeContractFunction}}),Object.defineProperty(t,"invokeHostFunction",{enumerable:!0,get:function(){return x.invokeHostFunction}}),Object.defineProperty(t,"liquidityPoolDeposit",{enumerable:!0,get:function(){return _.liquidityPoolDeposit}}),Object.defineProperty(t,"liquidityPoolWithdraw",{enumerable:!0,get:function(){return O.liquidityPoolWithdraw}}),Object.defineProperty(t,"manageBuyOffer",{enumerable:!0,get:function(){return y.manageBuyOffer}}),Object.defineProperty(t,"manageData",{enumerable:!0,get:function(){return h.manageData}}),Object.defineProperty(t,"manageSellOffer",{enumerable:!0,get:function(){return n.manageSellOffer}}),Object.defineProperty(t,"pathPaymentStrictReceive",{enumerable:!0,get:function(){return m.pathPaymentStrictReceive}}),Object.defineProperty(t,"pathPaymentStrictSend",{enumerable:!0,get:function(){return v.pathPaymentStrictSend}}),Object.defineProperty(t,"payment",{enumerable:!0,get:function(){return g.payment}}),Object.defineProperty(t,"restoreFootprint",{enumerable:!0,get:function(){return P.restoreFootprint}}),Object.defineProperty(t,"revokeAccountSponsorship",{enumerable:!0,get:function(){return k.revokeAccountSponsorship}}),Object.defineProperty(t,"revokeClaimableBalanceSponsorship",{enumerable:!0,get:function(){return k.revokeClaimableBalanceSponsorship}}),Object.defineProperty(t,"revokeDataSponsorship",{enumerable:!0,get:function(){return k.revokeDataSponsorship}}),Object.defineProperty(t,"revokeLiquidityPoolSponsorship",{enumerable:!0,get:function(){return k.revokeLiquidityPoolSponsorship}}),Object.defineProperty(t,"revokeOfferSponsorship",{enumerable:!0,get:function(){return k.revokeOfferSponsorship}}),Object.defineProperty(t,"revokeSignerSponsorship",{enumerable:!0,get:function(){return k.revokeSignerSponsorship}}),Object.defineProperty(t,"revokeTrustlineSponsorship",{enumerable:!0,get:function(){return k.revokeTrustlineSponsorship}}),Object.defineProperty(t,"setOptions",{enumerable:!0,get:function(){return b.setOptions}}),Object.defineProperty(t,"setTrustLineFlags",{enumerable:!0,get:function(){return T.setTrustLineFlags}}),Object.defineProperty(t,"uploadContractWasm",{enumerable:!0,get:function(){return x.uploadContractWasm}});var n=r(862),o=r(9073),i=r(4295),a=r(3683),s=r(6183),u=r(2810),c=r(2115),l=r(4831),f=r(7239),p=r(2203),d=r(7421),h=r(1411),y=r(1922),m=r(2075),v=r(3874),g=r(3533),b=r(2018),w=r(7505),S=r(721),k=r(7790),E=r(7651),T=r(1804),_=r(9845),O=r(4737),x=r(4403),A=r(8752),P=r(149)},7421:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inflation=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};return t.body=o.default.OperationBody.inflation(),this.setSourceAccount(t,e),new o.default.Operation(t)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},4403:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.createCustomContract=function(e){var t,r=n.from(e.salt||a.Keypair.random().xdrPublicKey().value());if(!e.wasmHash||32!==e.wasmHash.length)throw new TypeError("expected hash(contract WASM) in 'opts.wasmHash', got ".concat(e.wasmHash));if(32!==r.length)throw new TypeError("expected 32-byte salt in 'opts.salt', got ".concat(e.wasmHash));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeCreateContractV2(new i.default.CreateContractArgsV2({executable:i.default.ContractExecutable.contractExecutableWasm(n.from(e.wasmHash)),contractIdPreimage:i.default.ContractIdPreimage.contractIdPreimageFromAddress(new i.default.ContractIdPreimageFromAddress({address:e.address.toScAddress(),salt:r})),constructorArgs:null!==(t=e.constructorArgs)&&void 0!==t?t:[]}))})},t.createStellarAssetContract=function(e){var t=e.asset;if("string"==typeof t){var r=t.split(":"),n=(l=2,function(e){if(Array.isArray(e))return e}(s=r)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(s,l)||function(e,t){if(e){if("string"==typeof e)return c(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?c(e,t):void 0}}(s,l)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),o=n[0],a=n[1];t=new u.Asset(o,a)}var s,l;if(!(t instanceof u.Asset))throw new TypeError("expected Asset in 'opts.asset', got ".concat(t));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeCreateContract(new i.default.CreateContractArgs({executable:i.default.ContractExecutable.contractExecutableStellarAsset(),contractIdPreimage:i.default.ContractIdPreimage.contractIdPreimageFromAsset(t.toXDRObject())}))})},t.invokeContractFunction=function(e){var t=new s.Address(e.contract);if("contract"!==t._type)throw new TypeError("expected contract strkey instance, got ".concat(t));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeInvokeContract(new i.default.InvokeContractArgs({contractAddress:t.toScAddress(),functionName:e.function,args:e.args}))})},t.invokeHostFunction=function(e){if(!e.func)throw new TypeError("host function invocation ('func') required (got ".concat(JSON.stringify(e),")"));var t=new i.default.InvokeHostFunctionOp({hostFunction:e.func,auth:e.auth||[]}),r={body:i.default.OperationBody.invokeHostFunction(t)};return this.setSourceAccount(r,e),new i.default.Operation(r)},t.uploadContractWasm=function(e){return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeUploadContractWasm(n.from(e.wasm))})};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(6691),s=r(1180),u=r(1764);function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.liquidityPoolDeposit=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.liquidityPoolId,r=e.maxAmountA,n=e.maxAmountB,i=e.minPrice,a=e.maxPrice,s={};if(!t)throw new TypeError("liquidityPoolId argument is required");if(s.liquidityPoolId=o.default.PoolId.fromXDR(t,"hex"),!this.isValidAmount(r,!0))throw new TypeError(this.constructAmountRequirementsError("maxAmountA"));if(s.maxAmountA=this._toXDRAmount(r),!this.isValidAmount(n,!0))throw new TypeError(this.constructAmountRequirementsError("maxAmountB"));if(s.maxAmountB=this._toXDRAmount(n),void 0===i)throw new TypeError("minPrice argument is required");if(s.minPrice=this._toXDRPrice(i),void 0===a)throw new TypeError("maxPrice argument is required");s.maxPrice=this._toXDRPrice(a);var u=new o.default.LiquidityPoolDepositOp(s),c={body:o.default.OperationBody.liquidityPoolDeposit(u)};return this.setSourceAccount(c,e),new o.default.Operation(c)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},4737:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.liquidityPoolWithdraw=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};if(!e.liquidityPoolId)throw new TypeError("liquidityPoolId argument is required");if(t.liquidityPoolId=o.default.PoolId.fromXDR(e.liquidityPoolId,"hex"),!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),!this.isValidAmount(e.minAmountA,!0))throw new TypeError(this.constructAmountRequirementsError("minAmountA"));if(t.minAmountA=this._toXDRAmount(e.minAmountA),!this.isValidAmount(e.minAmountB,!0))throw new TypeError(this.constructAmountRequirementsError("minAmountB"));t.minAmountB=this._toXDRAmount(e.minAmountB);var r=new o.default.LiquidityPoolWithdrawOp(t),n={body:o.default.OperationBody.liquidityPoolWithdraw(r)};return this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},1922:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.manageBuyOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.buyAmount,!0))throw new TypeError(this.constructAmountRequirementsError("buyAmount"));if(t.buyAmount=this._toXDRAmount(e.buyAmount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price),void 0!==e.offerId?e.offerId=e.offerId.toString():e.offerId="0";t.offerId=o.Hyper.fromString(e.offerId);var r=new i.default.ManageBuyOfferOp(t),n={};return n.body=i.default.OperationBody.manageBuyOffer(r),this.setSourceAccount(n,e),new i.default.Operation(n)};var n,o=r(3740),i=(n=r(1918))&&n.__esModule?n:{default:n}},1411:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.manageData=function(e){var t={};if(!("string"==typeof e.name&&e.name.length<=64))throw new Error("name must be a string, up to 64 characters");if(t.dataName=e.name,"string"!=typeof e.value&&!n.isBuffer(e.value)&&null!==e.value)throw new Error("value must be a string, Buffer or null");"string"==typeof e.value?t.dataValue=n.from(e.value):t.dataValue=e.value;if(null!==t.dataValue&&t.dataValue.length>64)throw new Error("value cannot be longer that 64 bytes");var r=new i.default.ManageDataOp(t),o={};return o.body=i.default.OperationBody.manageData(r),this.setSourceAccount(o,e),new i.default.Operation(o)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o}},862:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.manageSellOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.amount,!0))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price),void 0!==e.offerId?e.offerId=e.offerId.toString():e.offerId="0";t.offerId=o.Hyper.fromString(e.offerId);var r=new i.default.ManageSellOfferOp(t),n={};return n.body=i.default.OperationBody.manageSellOffer(r),this.setSourceAccount(n,e),new i.default.Operation(n)};var n,o=r(3740),i=(n=r(1918))&&n.__esModule?n:{default:n}},2075:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathPaymentStrictReceive=function(e){switch(!0){case!e.sendAsset:throw new Error("Must specify a send asset");case!this.isValidAmount(e.sendMax):throw new TypeError(this.constructAmountRequirementsError("sendMax"));case!e.destAsset:throw new Error("Must provide a destAsset for a payment operation");case!this.isValidAmount(e.destAmount):throw new TypeError(this.constructAmountRequirementsError("destAmount"))}var t={};t.sendAsset=e.sendAsset.toXDRObject(),t.sendMax=this._toXDRAmount(e.sendMax);try{t.destination=(0,i.decodeAddressToMuxedAccount)(e.destination)}catch(e){throw new Error("destination is invalid")}t.destAsset=e.destAsset.toXDRObject(),t.destAmount=this._toXDRAmount(e.destAmount);var r=e.path?e.path:[];t.path=r.map((function(e){return e.toXDRObject()}));var n=new o.default.PathPaymentStrictReceiveOp(t),a={};return a.body=o.default.OperationBody.pathPaymentStrictReceive(n),this.setSourceAccount(a,e),new o.default.Operation(a)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},3874:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathPaymentStrictSend=function(e){switch(!0){case!e.sendAsset:throw new Error("Must specify a send asset");case!this.isValidAmount(e.sendAmount):throw new TypeError(this.constructAmountRequirementsError("sendAmount"));case!e.destAsset:throw new Error("Must provide a destAsset for a payment operation");case!this.isValidAmount(e.destMin):throw new TypeError(this.constructAmountRequirementsError("destMin"))}var t={};t.sendAsset=e.sendAsset.toXDRObject(),t.sendAmount=this._toXDRAmount(e.sendAmount);try{t.destination=(0,i.decodeAddressToMuxedAccount)(e.destination)}catch(e){throw new Error("destination is invalid")}t.destAsset=e.destAsset.toXDRObject(),t.destMin=this._toXDRAmount(e.destMin);var r=e.path?e.path:[];t.path=r.map((function(e){return e.toXDRObject()}));var n=new o.default.PathPaymentStrictSendOp(t),a={};return a.body=o.default.OperationBody.pathPaymentStrictSend(n),this.setSourceAccount(a,e),new o.default.Operation(a)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},3533:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.payment=function(e){if(!e.asset)throw new Error("Must provide an asset for a payment operation");if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));var t={};try{t.destination=(0,i.decodeAddressToMuxedAccount)(e.destination)}catch(e){throw new Error("destination is invalid")}t.asset=e.asset.toXDRObject(),t.amount=this._toXDRAmount(e.amount);var r=new o.default.PaymentOp(t),n={};return n.body=o.default.OperationBody.payment(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},149:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restoreFootprint=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=new o.default.RestoreFootprintOp({ext:new o.default.ExtensionPoint(0)}),r={body:o.default.OperationBody.restoreFootprint(t)};return this.setSourceAccount(r,null!=e?e:{}),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},7790:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.revokeAccountSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");var t=i.default.LedgerKey.account(new i.default.LedgerKeyAccount({accountId:s.Keypair.fromPublicKey(e.account).xdrAccountId()})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeClaimableBalanceSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if("string"!=typeof e.balanceId)throw new Error("balanceId is invalid");var t=i.default.LedgerKey.claimableBalance(new i.default.LedgerKeyClaimableBalance({balanceId:i.default.ClaimableBalanceId.fromXDR(e.balanceId,"hex")})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeDataSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");if("string"!=typeof e.name||e.name.length>64)throw new Error("name must be a string, up to 64 characters");var t=i.default.LedgerKey.data(new i.default.LedgerKeyData({accountId:s.Keypair.fromPublicKey(e.account).xdrAccountId(),dataName:e.name})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeLiquidityPoolSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if("string"!=typeof e.liquidityPoolId)throw new Error("liquidityPoolId is invalid");var t=i.default.LedgerKey.liquidityPool(new i.default.LedgerKeyLiquidityPool({liquidityPoolId:i.default.PoolId.fromXDR(e.liquidityPoolId,"hex")})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={body:i.default.OperationBody.revokeSponsorship(r)};return this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeOfferSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(e.seller))throw new Error("seller is invalid");if("string"!=typeof e.offerId)throw new Error("offerId is invalid");var t=i.default.LedgerKey.offer(new i.default.LedgerKeyOffer({sellerId:s.Keypair.fromPublicKey(e.seller).xdrAccountId(),offerId:i.default.Int64.fromString(e.offerId)})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeSignerSponsorship=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(t.account))throw new Error("account is invalid");if(t.signer.ed25519PublicKey){if(!a.StrKey.isValidEd25519PublicKey(t.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");var r=a.StrKey.decodeEd25519PublicKey(t.signer.ed25519PublicKey);e=new i.default.SignerKey.signerKeyTypeEd25519(r)}else if(t.signer.preAuthTx){var o;if(o="string"==typeof t.signer.preAuthTx?n.from(t.signer.preAuthTx,"hex"):t.signer.preAuthTx,!n.isBuffer(o)||32!==o.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");e=new i.default.SignerKey.signerKeyTypePreAuthTx(o)}else{if(!t.signer.sha256Hash)throw new Error("signer is invalid");var u;if(u="string"==typeof t.signer.sha256Hash?n.from(t.signer.sha256Hash,"hex"):t.signer.sha256Hash,!n.isBuffer(u)||32!==u.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");e=new i.default.SignerKey.signerKeyTypeHashX(u)}var c=new i.default.RevokeSponsorshipOpSigner({accountId:s.Keypair.fromPublicKey(t.account).xdrAccountId(),signerKey:e}),l=i.default.RevokeSponsorshipOp.revokeSponsorshipSigner(c),f={};return f.body=i.default.OperationBody.revokeSponsorship(l),this.setSourceAccount(f,t),new i.default.Operation(f)},t.revokeTrustlineSponsorship=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(t.account))throw new Error("account is invalid");if(t.asset instanceof u.Asset)e=t.asset.toTrustLineXDRObject();else{if(!(t.asset instanceof c.LiquidityPoolId))throw new TypeError("asset must be an Asset or LiquidityPoolId");e=t.asset.toXDRObject()}var r=i.default.LedgerKey.trustline(new i.default.LedgerKeyTrustLine({accountId:s.Keypair.fromPublicKey(t.account).xdrAccountId(),asset:e})),n=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(r),o={};return o.body=i.default.OperationBody.revokeSponsorship(n),this.setSourceAccount(o,t),new i.default.Operation(o)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(7120),s=r(6691),u=r(1764),c=r(9353)},2018:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.setOptions=function(e){var t={};if(e.inflationDest){if(!s.StrKey.isValidEd25519PublicKey(e.inflationDest))throw new Error("inflationDest is invalid");t.inflationDest=a.Keypair.fromPublicKey(e.inflationDest).xdrAccountId()}if(t.clearFlags=this._checkUnsignedIntValue("clearFlags",e.clearFlags),t.setFlags=this._checkUnsignedIntValue("setFlags",e.setFlags),t.masterWeight=this._checkUnsignedIntValue("masterWeight",e.masterWeight,u),t.lowThreshold=this._checkUnsignedIntValue("lowThreshold",e.lowThreshold,u),t.medThreshold=this._checkUnsignedIntValue("medThreshold",e.medThreshold,u),t.highThreshold=this._checkUnsignedIntValue("highThreshold",e.highThreshold,u),void 0!==e.homeDomain&&"string"!=typeof e.homeDomain)throw new TypeError("homeDomain argument must be of type String");if(t.homeDomain=e.homeDomain,e.signer){var r,o=this._checkUnsignedIntValue("signer.weight",e.signer.weight,u),c=0;if(e.signer.ed25519PublicKey){if(!s.StrKey.isValidEd25519PublicKey(e.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");var l=s.StrKey.decodeEd25519PublicKey(e.signer.ed25519PublicKey);r=new i.default.SignerKey.signerKeyTypeEd25519(l),c+=1}if(e.signer.preAuthTx){if("string"==typeof e.signer.preAuthTx&&(e.signer.preAuthTx=n.from(e.signer.preAuthTx,"hex")),!n.isBuffer(e.signer.preAuthTx)||32!==e.signer.preAuthTx.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");r=new i.default.SignerKey.signerKeyTypePreAuthTx(e.signer.preAuthTx),c+=1}if(e.signer.sha256Hash){if("string"==typeof e.signer.sha256Hash&&(e.signer.sha256Hash=n.from(e.signer.sha256Hash,"hex")),!n.isBuffer(e.signer.sha256Hash)||32!==e.signer.sha256Hash.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");r=new i.default.SignerKey.signerKeyTypeHashX(e.signer.sha256Hash),c+=1}if(e.signer.ed25519SignedPayload){if(!s.StrKey.isValidSignedPayload(e.signer.ed25519SignedPayload))throw new Error("signer.ed25519SignedPayload is invalid.");var f=s.StrKey.decodeSignedPayload(e.signer.ed25519SignedPayload),p=i.default.SignerKeyEd25519SignedPayload.fromXDR(f);r=i.default.SignerKey.signerKeyTypeEd25519SignedPayload(p),c+=1}if(1!==c)throw new Error("Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx.");t.signer=new i.default.Signer({key:r,weight:o})}var d=new i.default.SetOptionsOp(t),h={};return h.body=i.default.OperationBody.setOptions(d),this.setSourceAccount(h,e),new i.default.Operation(h)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(6691),s=r(7120);function u(e,t){if(e>=0&&e<=255)return!0;throw new Error("".concat(t," value must be between 0 and 255"))}},1804:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setTrustLineFlags=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};if("object"!==a(e.flags)||0===Object.keys(e.flags).length)throw new Error("opts.flags must be a map of boolean flags to modify");var r={authorized:o.default.TrustLineFlags.authorizedFlag(),authorizedToMaintainLiabilities:o.default.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),clawbackEnabled:o.default.TrustLineFlags.trustlineClawbackEnabledFlag()},n=0,s=0;Object.keys(e.flags).forEach((function(t){if(!Object.prototype.hasOwnProperty.call(r,t))throw new Error("unsupported flag name specified: ".concat(t));var o=e.flags[t],i=r[t].value;!0===o?s|=i:!1===o&&(n|=i)})),t.trustor=i.Keypair.fromPublicKey(e.trustor).xdrAccountId(),t.asset=e.asset.toXDRObject(),t.clearFlags=n,t.setFlags=s;var u={body:o.default.OperationBody.setTrustLineFlags(new o.default.SetTrustLineFlagsOp(t))};return this.setSourceAccount(u,e),new o.default.Operation(u)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}},7177:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.nativeToScVal=function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(f(t)){case"object":var o,l,p;if(null===t)return i.default.ScVal.scvVoid();if(t instanceof i.default.ScVal)return t;if(t instanceof a.Address)return t.toScVal();if(t instanceof s.Contract)return t.address().toScVal();if(t instanceof Uint8Array||n.isBuffer(t)){var d,h=Uint8Array.from(t);switch(null!==(d=null==r?void 0:r.type)&&void 0!==d?d:"bytes"){case"bytes":return i.default.ScVal.scvBytes(h);case"symbol":return i.default.ScVal.scvSymbol(h);case"string":return i.default.ScVal.scvString(h);default:throw new TypeError("invalid type (".concat(r.type,") specified for bytes-like value"))}}if(Array.isArray(t)){if(t.length>0&&t.some((function(e){return f(e)!==f(t[0])})))throw new TypeError("array values (".concat(t,") must have the same type (types: ").concat(t.map((function(e){return f(e)})).join(","),")"));return i.default.ScVal.scvVec(t.map((function(t){return e(t,r)})))}if("Object"!==(null!==(o=null===(l=t.constructor)||void 0===l?void 0:l.name)&&void 0!==o?o:""))throw new TypeError("cannot interpret ".concat(null===(p=t.constructor)||void 0===p?void 0:p.name," value as ScVal (").concat(JSON.stringify(t),")"));return i.default.ScVal.scvMap(Object.entries(t).sort((function(e,t){var r=c(e,1)[0],n=c(t,1)[0];return r.localeCompare(n)})).map((function(t){var n,o,a=c(t,2),s=a[0],u=a[1],l=c(null!==(n=(null!==(o=null==r?void 0:r.type)&&void 0!==o?o:{})[s])&&void 0!==n?n:[null,null],2),f=l[0],p=l[1],d=f?{type:f}:{},h=p?{type:p}:{};return new i.default.ScMapEntry({key:e(s,d),val:e(u,h)})})));case"number":case"bigint":switch(null==r?void 0:r.type){case"u32":return i.default.ScVal.scvU32(t);case"i32":return i.default.ScVal.scvI32(t)}return new u.ScInt(t,{type:null==r?void 0:r.type}).toScVal();case"string":var y,m=null!==(y=null==r?void 0:r.type)&&void 0!==y?y:"string";switch(m){case"string":return i.default.ScVal.scvString(t);case"symbol":return i.default.ScVal.scvSymbol(t);case"address":return new a.Address(t).toScVal();case"u32":return i.default.ScVal.scvU32(parseInt(t,10));case"i32":return i.default.ScVal.scvI32(parseInt(t,10));default:if(u.XdrLargeInt.isType(m))return new u.XdrLargeInt(m,t).toScVal();throw new TypeError("invalid type (".concat(r.type,") specified for string value"))}case"boolean":return i.default.ScVal.scvBool(t);case"undefined":return i.default.ScVal.scvVoid();case"function":return e(t());default:throw new TypeError("failed to convert typeof ".concat(f(t)," (").concat(t,")"))}},t.scValToNative=function e(t){var r,o;switch(t.switch().value){case i.default.ScValType.scvVoid().value:return null;case i.default.ScValType.scvU64().value:case i.default.ScValType.scvI64().value:return t.value().toBigInt();case i.default.ScValType.scvU128().value:case i.default.ScValType.scvI128().value:case i.default.ScValType.scvU256().value:case i.default.ScValType.scvI256().value:return(0,u.scValToBigInt)(t);case i.default.ScValType.scvVec().value:return(null!==(r=t.vec())&&void 0!==r?r:[]).map(e);case i.default.ScValType.scvAddress().value:return a.Address.fromScVal(t).toString();case i.default.ScValType.scvMap().value:return Object.fromEntries((null!==(o=t.map())&&void 0!==o?o:[]).map((function(t){return[e(t.key()),e(t.val())]})));case i.default.ScValType.scvBool().value:case i.default.ScValType.scvU32().value:case i.default.ScValType.scvI32().value:case i.default.ScValType.scvBytes().value:return t.value();case i.default.ScValType.scvSymbol().value:case i.default.ScValType.scvString().value:var s=t.value();if(n.isBuffer(s)||ArrayBuffer.isView(s))try{return(new TextDecoder).decode(s)}catch(e){return new Uint8Array(s.buffer)}return s;case i.default.ScValType.scvTimepoint().value:case i.default.ScValType.scvDuration().value:return new i.default.Uint64(t.value()).toBigInt();case i.default.ScValType.scvError().value:if(t.error().switch().value===i.default.ScErrorType.sceContract().value)return{type:"contract",code:t.error().contractCode()};var c=t.error();return{type:"system",code:c.code().value,value:c.code().name};default:return t.value()}};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(1180),s=r(7452),u=r(8549);function c(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return l(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?l(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignerKey=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(7120);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function s(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.FastSigning=void 0,t.generate=function(e){return o.generate(e)},t.sign=function(e,t){return o.sign(e,t)},t.verify=function(e,t,r){return o.verify(e,t,r)};var o={};t.FastSigning="undefined"==typeof window?function(){var e;try{e=r(Object(function(){var e=new Error("Cannot find module 'sodium-native'");throw e.code="MODULE_NOT_FOUND",e}()))}catch(e){return i()}return Object.keys(e).length?(o.generate=function(t){var r=n.alloc(e.crypto_sign_PUBLICKEYBYTES),o=n.alloc(e.crypto_sign_SECRETKEYBYTES);return e.crypto_sign_seed_keypair(r,o,t),r},o.sign=function(t,r){t=n.from(t);var o=n.alloc(e.crypto_sign_BYTES);return e.crypto_sign_detached(o,t,r),o},o.verify=function(t,r,o){t=n.from(t);try{return e.crypto_sign_verify_detached(r,t,o)}catch(e){return!1}},!0):i()}():i();function i(){var e=r(4940);return o.generate=function(t){var r=new Uint8Array(t),o=e.sign.keyPair.fromSeed(r);return n.from(o.publicKey)},o.sign=function(t,r){t=n.from(t),t=new Uint8Array(t.toJSON().data),r=new Uint8Array(r.toJSON().data);var o=e.sign.detached(t,r);return n.from(o)},o.verify=function(t,r,o){return t=n.from(t),t=new Uint8Array(t.toJSON().data),r=new Uint8Array(r.toJSON().data),o=new Uint8Array(o.toJSON().data),e.sign.detached.verify(t,r,o)},!1}},4062:(e,t)=>{"use strict";function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}function n(e){return function(e){if(Array.isArray(e))return e}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return o(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?o(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r0&&(r=t>r.length?["0",r.toString().padStart(t,"0")].join("."):[r.slice(0,-t),r.slice(-t)].join(".")),r.replace(/(\.\d*?)0+$/,"$1")}},{key:"parseTokenAmount",value:function(e,t){var r,o=n(e.split(".").slice()),i=o[0],a=o[1];if(o.slice(2).length)throw new Error("Invalid decimal value: ".concat(e));return BigInt(i+(null!==(r=null==a?void 0:a.padEnd(t,"0"))&&void 0!==r?r:"0".repeat(t))).toString()}}],(t=null)&&i(e.prototype,t),r&&i(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,r}()},4842:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SorobanDataBuilder=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n};function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.StrKey=void 0,t.decodeCheck=d,t.encodeCheck=h;var o,i=(o=r(5360))&&o.__esModule?o:{default:o},a=r(1346);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){for(var r=0;r165)return!1;break;default:return!1}var r="";try{r=d(e,t)}catch(e){return!1}switch(e){case"ed25519PublicKey":case"ed25519SecretSeed":case"preAuthTx":case"sha256Hash":case"contract":return 32===r.length;case"med25519PublicKey":return 40===r.length;case"signedPayload":return r.length>=40&&r.length<=100;default:return!1}}function d(e,t){if("string"!=typeof t)throw new TypeError("encoded argument must be of type String");var r=i.default.decode(t),o=r[0],s=r.slice(0,-2),u=s.slice(1),c=r.slice(-2);if(t!==i.default.encode(r))throw new Error("invalid encoded string");var f=l[e];if(void 0===f)throw new Error("".concat(e," is not a valid version byte name. ")+"Expected one of ".concat(Object.keys(l).join(", ")));if(o!==f)throw new Error("invalid version byte. expected ".concat(f,", got ").concat(o));var p=y(s);if(!(0,a.verifyChecksum)(p,c))throw new Error("invalid checksum");return n.from(u)}function h(e,t){if(null==t)throw new Error("cannot encode null data");var r=l[e];if(void 0===r)throw new Error("".concat(e," is not a valid version byte name. ")+"Expected one of ".concat(Object.keys(l).join(", ")));t=n.from(t);var o=n.from([r]),a=n.concat([o,t]),s=n.from(y(a)),u=n.concat([a,s]);return i.default.encode(u)}function y(e){for(var t=[0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920],r=0,n=0;n>8^e[n]],r&=65535}var o=new Uint8Array(2);return o[0]=255&r,o[1]=r>>8&255,o}},380:(e,t,r)=>{"use strict";var n=r(8287).Buffer;function o(e){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Transaction=void 0;var i,a=(i=r(1918))&&i.__esModule?i:{default:i},s=r(9152),u=r(7120),c=r(7237),l=r(4172),f=r(3758),p=r(6160);function d(e,t){for(var r=0;r=this.operations.length)throw new RangeError("invalid operation index");var t=this.operations[e];try{t=c.Operation.createClaimableBalance(t)}catch(e){throw new TypeError("expected createClaimableBalance, got ".concat(t.type,": ").concat(e))}var r=u.StrKey.decodeEd25519PublicKey((0,p.extractBaseAddress)(this.source)),n=a.default.HashIdPreimage.envelopeTypeOpId(new a.default.HashIdPreimageOperationId({sourceAccount:a.default.AccountId.publicKeyTypeEd25519(r),seqNum:a.default.SequenceNumber.fromString(this.sequence),opNum:e})),o=(0,s.hash)(n.toXDR("raw"));return a.default.ClaimableBalanceId.claimableBalanceIdTypeV0(o).toXDR("hex")}}])}(f.TransactionBase)},3758:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionBase=void 0;var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(9152),s=r(6691);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:"",o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(!o||"string"!=typeof o)throw new Error("Invalid signature");if(!r||"string"!=typeof r)throw new Error("Invalid publicKey");var a=n.from(o,"base64");try{t=(e=s.Keypair.fromPublicKey(r)).signatureHint()}catch(e){throw new Error("Invalid publicKey")}if(!e.verify(this.hash(),a))throw new Error("Invalid signature");this.signatures.push(new i.default.DecoratedSignature({hint:t,signature:a}))}},{key:"addDecoratedSignature",value:function(e){this.signatures.push(e)}},{key:"signHashX",value:function(e){if("string"==typeof e&&(e=n.from(e,"hex")),e.length>64)throw new Error("preimage cannnot be longer than 64 bytes");var t=e,r=(0,a.hash)(e),o=r.slice(r.length-4);this.signatures.push(new i.default.DecoratedSignature({hint:o,signature:t}))}},{key:"hash",value:function(){return(0,a.hash)(this.signatureBase())}},{key:"signatureBase",value:function(){throw new Error("Implement in subclass")}},{key:"toEnvelope",value:function(){throw new Error("Implement in subclass")}},{key:"toXDR",value:function(){return this.toEnvelope().toXDR().toString("base64")}}])}()},6396:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionBuilder=t.TimeoutInfinite=t.BASE_FEE=void 0,t.isValidDate=_;var n=r(3740),o=y(r(1242)),i=y(r(1918)),a=r(2135),s=r(2243),u=r(6160),c=r(380),l=r(9260),f=r(4842),p=r(7120),d=r(225),h=r(4172);function y(e){return e&&e.__esModule?e:{default:e}}function m(e){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},m(e)}function v(e){return function(e){if(Array.isArray(e))return g(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return g(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?g(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function g(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r1&&void 0!==arguments[1]?arguments[1]:{};if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw new Error("must specify source account for the transaction");if(void 0===r.fee)throw new Error("must specify fee for the transaction (in stroops)");this.source=t,this.operations=[],this.baseFee=r.fee,this.timebounds=r.timebounds?w({},r.timebounds):null,this.ledgerbounds=r.ledgerbounds?w({},r.ledgerbounds):null,this.minAccountSequence=r.minAccountSequence||null,this.minAccountSequenceAge=r.minAccountSequenceAge||null,this.minAccountSequenceLedgerGap=r.minAccountSequenceLedgerGap||null,this.extraSigners=r.extraSigners?v(r.extraSigners):null,this.memo=r.memo||h.Memo.none(),this.networkPassphrase=r.networkPassphrase||null,this.sorobanData=r.sorobanData?new f.SorobanDataBuilder(r.sorobanData).build():null}return t=e,y=[{key:"cloneFrom",value:function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!(t instanceof c.Transaction))throw new TypeError("expected a 'Transaction', got: ".concat(t));var n,o=(BigInt(t.sequence)-1n).toString();if(p.StrKey.isValidMed25519PublicKey(t.source))n=s.MuxedAccount.fromAddress(t.source,o);else{if(!p.StrKey.isValidEd25519PublicKey(t.source))throw new TypeError("unsupported tx source account: ".concat(t.source));n=new a.Account(t.source,o)}var i=new e(n,w({fee:(parseInt(t.fee,10)/t.operations.length||T).toString(),memo:t.memo,networkPassphrase:t.networkPassphrase,timebounds:t.timeBounds,ledgerbounds:t.ledgerBounds,minAccountSequence:t.minAccountSequence,minAccountSequenceAge:t.minAccountSequenceAge,minAccountSequenceLedgerGap:t.minAccountSequenceLedgerGap,extraSigners:t.extraSigners},r));return t._tx.operations().forEach((function(e){return i.addOperation(e)})),i}},{key:"buildFeeBumpTransaction",value:function(e,t,r,n){var a=r.operations.length,s=new o.default(r.fee).div(a),c=new o.default(t);if(c.lt(s))throw new Error("Invalid baseFee, it should be at least ".concat(s," stroops."));var f=new o.default(T);if(c.lt(f))throw new Error("Invalid baseFee, it should be at least ".concat(f," stroops."));var p,d=r.toEnvelope();if(d.switch()===i.default.EnvelopeType.envelopeTypeTxV0()){var h=d.v0().tx(),y=new i.default.Transaction({sourceAccount:new i.default.MuxedAccount.keyTypeEd25519(h.sourceAccountEd25519()),fee:h.fee(),seqNum:h.seqNum(),cond:i.default.Preconditions.precondTime(h.timeBounds()),memo:h.memo(),operations:h.operations(),ext:new i.default.TransactionExt(0)});d=new i.default.TransactionEnvelope.envelopeTypeTx(new i.default.TransactionV1Envelope({tx:y,signatures:d.v0().signatures()}))}p="string"==typeof e?(0,u.decodeAddressToMuxedAccount)(e):e.xdrMuxedAccount();var m=new i.default.FeeBumpTransaction({feeSource:p,fee:i.default.Int64.fromString(c.times(a+1).toString()),innerTx:i.default.FeeBumpTransactionInnerTx.envelopeTypeTx(d.v1()),ext:new i.default.FeeBumpTransactionExt(0)}),v=new i.default.FeeBumpTransactionEnvelope({tx:m,signatures:[]}),g=new i.default.TransactionEnvelope.envelopeTypeTxFeeBump(v);return new l.FeeBumpTransaction(g,n)}},{key:"fromXDR",value:function(e,t){return"string"==typeof e&&(e=i.default.TransactionEnvelope.fromXDR(e,"base64")),e.switch()===i.default.EnvelopeType.envelopeTypeTxFeeBump()?new l.FeeBumpTransaction(e,t):new c.Transaction(e,t)}}],(r=[{key:"addOperation",value:function(e){return this.operations.push(e),this}},{key:"addOperationAt",value:function(e,t){return this.operations.splice(t,0,e),this}},{key:"clearOperations",value:function(){return this.operations=[],this}},{key:"clearOperationAt",value:function(e){return this.operations.splice(e,1),this}},{key:"addMemo",value:function(e){return this.memo=e,this}},{key:"setTimeout",value:function(e){if(null!==this.timebounds&&this.timebounds.maxTime>0)throw new Error("TimeBounds.max_time has been already set - setting timeout would overwrite it.");if(e<0)throw new Error("timeout cannot be negative");if(e>0){var t=Math.floor(Date.now()/1e3)+e;null===this.timebounds?this.timebounds={minTime:0,maxTime:t}:this.timebounds={minTime:this.timebounds.minTime,maxTime:t}}else this.timebounds={minTime:0,maxTime:0};return this}},{key:"setTimebounds",value:function(e,t){if("number"==typeof e&&(e=new Date(1e3*e)),"number"==typeof t&&(t=new Date(1e3*t)),null!==this.timebounds)throw new Error("TimeBounds has been already set - setting timebounds would overwrite it.");var r=Math.floor(e.valueOf()/1e3),n=Math.floor(t.valueOf()/1e3);if(r<0)throw new Error("min_time cannot be negative");if(n<0)throw new Error("max_time cannot be negative");if(n>0&&r>n)throw new Error("min_time cannot be greater than max_time");return this.timebounds={minTime:r,maxTime:n},this}},{key:"setLedgerbounds",value:function(e,t){if(null!==this.ledgerbounds)throw new Error("LedgerBounds has been already set - setting ledgerbounds would overwrite it.");if(e<0)throw new Error("min_ledger cannot be negative");if(t<0)throw new Error("max_ledger cannot be negative");if(t>0&&e>t)throw new Error("min_ledger cannot be greater than max_ledger");return this.ledgerbounds={minLedger:e,maxLedger:t},this}},{key:"setMinAccountSequence",value:function(e){if(null!==this.minAccountSequence)throw new Error("min_account_sequence has been already set - setting min_account_sequence would overwrite it.");return this.minAccountSequence=e,this}},{key:"setMinAccountSequenceAge",value:function(e){if("number"!=typeof e)throw new Error("min_account_sequence_age must be a number");if(null!==this.minAccountSequenceAge)throw new Error("min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.");if(e<0)throw new Error("min_account_sequence_age cannot be negative");return this.minAccountSequenceAge=e,this}},{key:"setMinAccountSequenceLedgerGap",value:function(e){if(null!==this.minAccountSequenceLedgerGap)throw new Error("min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.");if(e<0)throw new Error("min_account_sequence_ledger_gap cannot be negative");return this.minAccountSequenceLedgerGap=e,this}},{key:"setExtraSigners",value:function(e){if(!Array.isArray(e))throw new Error("extra_signers must be an array of strings.");if(null!==this.extraSigners)throw new Error("extra_signers has been already set - setting extra_signers would overwrite it.");if(e.length>2)throw new Error("extra_signers cannot be longer than 2 elements.");return this.extraSigners=v(e),this}},{key:"setNetworkPassphrase",value:function(e){return this.networkPassphrase=e,this}},{key:"setSorobanData",value:function(e){return this.sorobanData=new f.SorobanDataBuilder(e).build(),this}},{key:"build",value:function(){var e=new o.default(this.source.sequenceNumber()).plus(1),t={fee:new o.default(this.baseFee).times(this.operations.length).toNumber(),seqNum:i.default.SequenceNumber.fromString(e.toString()),memo:this.memo?this.memo.toXDRObject():null};if(null===this.timebounds||void 0===this.timebounds.minTime||void 0===this.timebounds.maxTime)throw new Error("TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).");_(this.timebounds.minTime)&&(this.timebounds.minTime=this.timebounds.minTime.getTime()/1e3),_(this.timebounds.maxTime)&&(this.timebounds.maxTime=this.timebounds.maxTime.getTime()/1e3),this.timebounds.minTime=n.UnsignedHyper.fromString(this.timebounds.minTime.toString()),this.timebounds.maxTime=n.UnsignedHyper.fromString(this.timebounds.maxTime.toString());var r=new i.default.TimeBounds(this.timebounds);if(this.hasV2Preconditions()){var a=null;null!==this.ledgerbounds&&(a=new i.default.LedgerBounds(this.ledgerbounds));var s=this.minAccountSequence||"0";s=i.default.SequenceNumber.fromString(s);var l=n.UnsignedHyper.fromString(null!==this.minAccountSequenceAge?this.minAccountSequenceAge.toString():"0"),f=this.minAccountSequenceLedgerGap||0,p=null!==this.extraSigners?this.extraSigners.map(d.SignerKey.decodeAddress):[];t.cond=i.default.Preconditions.precondV2(new i.default.PreconditionsV2({timeBounds:r,ledgerBounds:a,minSeqNum:s,minSeqAge:l,minSeqLedgerGap:f,extraSigners:p}))}else t.cond=i.default.Preconditions.precondTime(r);t.sourceAccount=(0,u.decodeAddressToMuxedAccount)(this.source.accountId()),this.sorobanData?t.ext=new i.default.TransactionExt(1,this.sorobanData):t.ext=new i.default.TransactionExt(0,i.default.Void);var h=new i.default.Transaction(t);h.operations(this.operations);var y=new i.default.TransactionEnvelope.envelopeTypeTx(new i.default.TransactionV1Envelope({tx:h})),m=new c.Transaction(y,this.networkPassphrase);return this.source.incrementSequenceNumber(),m}},{key:"hasV2Preconditions",value:function(){return null!==this.ledgerbounds||null!==this.minAccountSequence||null!==this.minAccountSequenceAge||null!==this.minAccountSequenceLedgerGap||null!==this.extraSigners&&this.extraSigners.length>0}}])&&k(t.prototype,r),y&&k(t,y),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,y}();function _(e){return e instanceof Date&&!isNaN(e)}},1242:(e,t,r)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=((n=r(1594))&&n.__esModule?n:{default:n}).default.clone();o.DEBUG=!0;t.default=o},1346:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyChecksum=function(e,t){if(e.length!==t.length)return!1;if(0===e.length)return!0;for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.best_r=function(e){var t,r,n=new o.default(e),s=[[new o.default(0),new o.default(1)],[new o.default(1),new o.default(0)]],u=2;for(;!n.gt(a);){t=n.integerValue(o.default.ROUND_FLOOR),r=n.minus(t);var c=t.times(s[u-1][0]).plus(s[u-2][0]),l=t.times(s[u-1][1]).plus(s[u-2][1]);if(c.gt(a)||l.gt(a))break;if(s.push([c,l]),r.eq(0))break;n=new o.default(1).div(r),u+=1}var f=(h=s[s.length-1],y=2,function(e){if(Array.isArray(e))return e}(h)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(h,y)||function(e,t){if(e){if("string"==typeof e)return i(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(e,t):void 0}}(h,y)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),p=f[0],d=f[1];var h,y;if(p.isZero()||d.isZero())throw new Error("Couldn't find approximation");return[p.toNumber(),d.toNumber()]};var n,o=(n=r(1242))&&n.__esModule?n:{default:n};function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.decodeAddressToMuxedAccount=s,t.encodeMuxedAccount=function(e,t){if(!a.StrKey.isValidEd25519PublicKey(e))throw new Error("address should be a Stellar account ID (G...)");if("string"!=typeof t)throw new Error("id should be a string representing a number (uint64)");return i.default.MuxedAccount.keyTypeMuxedEd25519(new i.default.MuxedAccountMed25519({id:i.default.Uint64.fromString(t),ed25519:a.StrKey.decodeEd25519PublicKey(e)}))},t.encodeMuxedAccountToAddress=u,t.extractBaseAddress=function(e){if(a.StrKey.isValidEd25519PublicKey(e))return e;if(!a.StrKey.isValidMed25519PublicKey(e))throw new TypeError("expected muxed account (M...), got ".concat(e));var t=s(e);return a.StrKey.encodeEd25519PublicKey(t.med25519().ed25519())};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(7120);function s(e){return a.StrKey.isValidMed25519PublicKey(e)?function(e){var t=a.StrKey.decodeMed25519PublicKey(e);return i.default.MuxedAccount.keyTypeMuxedEd25519(new i.default.MuxedAccountMed25519({id:i.default.Uint64.fromXDR(t.subarray(-8)),ed25519:t.subarray(0,-8)}))}(e):i.default.MuxedAccount.keyTypeEd25519(a.StrKey.decodeEd25519PublicKey(e))}function u(e){return e.switch().value===i.default.CryptoKeyType.keyTypeMuxedEd25519().value?function(e){if(e.switch()===i.default.CryptoKeyType.keyTypeEd25519())return u(e);var t=e.med25519();return a.StrKey.encodeMed25519PublicKey(n.concat([t.ed25519(),t.id().toXDR("raw")]))}(e):a.StrKey.encodeEd25519PublicKey(e.ed25519())}},645:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.trimEnd=void 0;t.trimEnd=function(e,t){for(var r="number"==typeof e,n=String(e);n.endsWith(t);)n=n.slice(0,-1);return r?Number(n):n}},1918:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,o=(n=r(7938))&&n.__esModule?n:{default:n};t.default=o.default},4940:(e,t,r)=>{!function(e){"use strict";var t=function(e){var t,r=new Float64Array(16);if(e)for(t=0;t>24&255,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r,e[t+4]=n>>24&255,e[t+5]=n>>16&255,e[t+6]=n>>8&255,e[t+7]=255&n}function y(e,t,r,n,o){var i,a=0;for(i=0;i>>8)-1}function m(e,t,r,n){return y(e,t,r,n,16)}function v(e,t,r,n){return y(e,t,r,n,32)}function g(e,t,r,n){!function(e,t,r,n){for(var o,i=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,s=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,c=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,l=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,p=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,h=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,y=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,m=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,v=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,g=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,b=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,w=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,S=i,k=a,E=s,T=u,_=c,O=l,x=f,A=p,P=d,R=h,I=y,C=m,j=v,B=g,L=b,N=w,U=0;U<20;U+=2)S^=(o=(j^=(o=(P^=(o=(_^=(o=S+j|0)<<7|o>>>25)+S|0)<<9|o>>>23)+_|0)<<13|o>>>19)+P|0)<<18|o>>>14,O^=(o=(k^=(o=(B^=(o=(R^=(o=O+k|0)<<7|o>>>25)+O|0)<<9|o>>>23)+R|0)<<13|o>>>19)+B|0)<<18|o>>>14,I^=(o=(x^=(o=(E^=(o=(L^=(o=I+x|0)<<7|o>>>25)+I|0)<<9|o>>>23)+L|0)<<13|o>>>19)+E|0)<<18|o>>>14,N^=(o=(C^=(o=(A^=(o=(T^=(o=N+C|0)<<7|o>>>25)+N|0)<<9|o>>>23)+T|0)<<13|o>>>19)+A|0)<<18|o>>>14,S^=(o=(T^=(o=(E^=(o=(k^=(o=S+T|0)<<7|o>>>25)+S|0)<<9|o>>>23)+k|0)<<13|o>>>19)+E|0)<<18|o>>>14,O^=(o=(_^=(o=(A^=(o=(x^=(o=O+_|0)<<7|o>>>25)+O|0)<<9|o>>>23)+x|0)<<13|o>>>19)+A|0)<<18|o>>>14,I^=(o=(R^=(o=(P^=(o=(C^=(o=I+R|0)<<7|o>>>25)+I|0)<<9|o>>>23)+C|0)<<13|o>>>19)+P|0)<<18|o>>>14,N^=(o=(L^=(o=(B^=(o=(j^=(o=N+L|0)<<7|o>>>25)+N|0)<<9|o>>>23)+j|0)<<13|o>>>19)+B|0)<<18|o>>>14;S=S+i|0,k=k+a|0,E=E+s|0,T=T+u|0,_=_+c|0,O=O+l|0,x=x+f|0,A=A+p|0,P=P+d|0,R=R+h|0,I=I+y|0,C=C+m|0,j=j+v|0,B=B+g|0,L=L+b|0,N=N+w|0,e[0]=S>>>0&255,e[1]=S>>>8&255,e[2]=S>>>16&255,e[3]=S>>>24&255,e[4]=k>>>0&255,e[5]=k>>>8&255,e[6]=k>>>16&255,e[7]=k>>>24&255,e[8]=E>>>0&255,e[9]=E>>>8&255,e[10]=E>>>16&255,e[11]=E>>>24&255,e[12]=T>>>0&255,e[13]=T>>>8&255,e[14]=T>>>16&255,e[15]=T>>>24&255,e[16]=_>>>0&255,e[17]=_>>>8&255,e[18]=_>>>16&255,e[19]=_>>>24&255,e[20]=O>>>0&255,e[21]=O>>>8&255,e[22]=O>>>16&255,e[23]=O>>>24&255,e[24]=x>>>0&255,e[25]=x>>>8&255,e[26]=x>>>16&255,e[27]=x>>>24&255,e[28]=A>>>0&255,e[29]=A>>>8&255,e[30]=A>>>16&255,e[31]=A>>>24&255,e[32]=P>>>0&255,e[33]=P>>>8&255,e[34]=P>>>16&255,e[35]=P>>>24&255,e[36]=R>>>0&255,e[37]=R>>>8&255,e[38]=R>>>16&255,e[39]=R>>>24&255,e[40]=I>>>0&255,e[41]=I>>>8&255,e[42]=I>>>16&255,e[43]=I>>>24&255,e[44]=C>>>0&255,e[45]=C>>>8&255,e[46]=C>>>16&255,e[47]=C>>>24&255,e[48]=j>>>0&255,e[49]=j>>>8&255,e[50]=j>>>16&255,e[51]=j>>>24&255,e[52]=B>>>0&255,e[53]=B>>>8&255,e[54]=B>>>16&255,e[55]=B>>>24&255,e[56]=L>>>0&255,e[57]=L>>>8&255,e[58]=L>>>16&255,e[59]=L>>>24&255,e[60]=N>>>0&255,e[61]=N>>>8&255,e[62]=N>>>16&255,e[63]=N>>>24&255}(e,t,r,n)}function b(e,t,r,n){!function(e,t,r,n){for(var o,i=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,s=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,c=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,l=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,p=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,h=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,y=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,m=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,v=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,g=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,b=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,w=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,S=0;S<20;S+=2)i^=(o=(v^=(o=(d^=(o=(c^=(o=i+v|0)<<7|o>>>25)+i|0)<<9|o>>>23)+c|0)<<13|o>>>19)+d|0)<<18|o>>>14,l^=(o=(a^=(o=(g^=(o=(h^=(o=l+a|0)<<7|o>>>25)+l|0)<<9|o>>>23)+h|0)<<13|o>>>19)+g|0)<<18|o>>>14,y^=(o=(f^=(o=(s^=(o=(b^=(o=y+f|0)<<7|o>>>25)+y|0)<<9|o>>>23)+b|0)<<13|o>>>19)+s|0)<<18|o>>>14,w^=(o=(m^=(o=(p^=(o=(u^=(o=w+m|0)<<7|o>>>25)+w|0)<<9|o>>>23)+u|0)<<13|o>>>19)+p|0)<<18|o>>>14,i^=(o=(u^=(o=(s^=(o=(a^=(o=i+u|0)<<7|o>>>25)+i|0)<<9|o>>>23)+a|0)<<13|o>>>19)+s|0)<<18|o>>>14,l^=(o=(c^=(o=(p^=(o=(f^=(o=l+c|0)<<7|o>>>25)+l|0)<<9|o>>>23)+f|0)<<13|o>>>19)+p|0)<<18|o>>>14,y^=(o=(h^=(o=(d^=(o=(m^=(o=y+h|0)<<7|o>>>25)+y|0)<<9|o>>>23)+m|0)<<13|o>>>19)+d|0)<<18|o>>>14,w^=(o=(b^=(o=(g^=(o=(v^=(o=w+b|0)<<7|o>>>25)+w|0)<<9|o>>>23)+v|0)<<13|o>>>19)+g|0)<<18|o>>>14;e[0]=i>>>0&255,e[1]=i>>>8&255,e[2]=i>>>16&255,e[3]=i>>>24&255,e[4]=l>>>0&255,e[5]=l>>>8&255,e[6]=l>>>16&255,e[7]=l>>>24&255,e[8]=y>>>0&255,e[9]=y>>>8&255,e[10]=y>>>16&255,e[11]=y>>>24&255,e[12]=w>>>0&255,e[13]=w>>>8&255,e[14]=w>>>16&255,e[15]=w>>>24&255,e[16]=f>>>0&255,e[17]=f>>>8&255,e[18]=f>>>16&255,e[19]=f>>>24&255,e[20]=p>>>0&255,e[21]=p>>>8&255,e[22]=p>>>16&255,e[23]=p>>>24&255,e[24]=d>>>0&255,e[25]=d>>>8&255,e[26]=d>>>16&255,e[27]=d>>>24&255,e[28]=h>>>0&255,e[29]=h>>>8&255,e[30]=h>>>16&255,e[31]=h>>>24&255}(e,t,r,n)}var w=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function S(e,t,r,n,o,i,a){var s,u,c=new Uint8Array(16),l=new Uint8Array(64);for(u=0;u<16;u++)c[u]=0;for(u=0;u<8;u++)c[u]=i[u];for(;o>=64;){for(g(l,c,a,w),u=0;u<64;u++)e[t+u]=r[n+u]^l[u];for(s=1,u=8;u<16;u++)s=s+(255&c[u])|0,c[u]=255&s,s>>>=8;o-=64,t+=64,n+=64}if(o>0)for(g(l,c,a,w),u=0;u=64;){for(g(u,s,o,w),a=0;a<64;a++)e[t+a]=u[a];for(i=1,a=8;a<16;a++)i=i+(255&s[a])|0,s[a]=255&i,i>>>=8;r-=64,t+=64}if(r>0)for(g(u,s,o,w),a=0;a>>13|r<<3),n=255&e[4]|(255&e[5])<<8,this.r[2]=7939&(r>>>10|n<<6),o=255&e[6]|(255&e[7])<<8,this.r[3]=8191&(n>>>7|o<<9),i=255&e[8]|(255&e[9])<<8,this.r[4]=255&(o>>>4|i<<12),this.r[5]=i>>>1&8190,a=255&e[10]|(255&e[11])<<8,this.r[6]=8191&(i>>>14|a<<2),s=255&e[12]|(255&e[13])<<8,this.r[7]=8065&(a>>>11|s<<5),u=255&e[14]|(255&e[15])<<8,this.r[8]=8191&(s>>>8|u<<8),this.r[9]=u>>>5&127,this.pad[0]=255&e[16]|(255&e[17])<<8,this.pad[1]=255&e[18]|(255&e[19])<<8,this.pad[2]=255&e[20]|(255&e[21])<<8,this.pad[3]=255&e[22]|(255&e[23])<<8,this.pad[4]=255&e[24]|(255&e[25])<<8,this.pad[5]=255&e[26]|(255&e[27])<<8,this.pad[6]=255&e[28]|(255&e[29])<<8,this.pad[7]=255&e[30]|(255&e[31])<<8};function O(e,t,r,n,o,i){var a=new _(i);return a.update(r,n,o),a.finish(e,t),0}function x(e,t,r,n,o,i){var a=new Uint8Array(16);return O(a,0,r,n,o,i),m(e,t,a,0)}function A(e,t,r,n,o){var i;if(r<32)return-1;for(T(e,0,t,0,r,n,o),O(e,16,e,32,r-32,e),i=0;i<16;i++)e[i]=0;return 0}function P(e,t,r,n,o){var i,a=new Uint8Array(32);if(r<32)return-1;if(E(a,0,32,n,o),0!==x(t,16,t,32,r-32,a))return-1;for(T(e,0,t,0,r,n,o),i=0;i<32;i++)e[i]=0;return 0}function R(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function I(e){var t,r,n=1;for(t=0;t<16;t++)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function C(e,t,r){for(var n,o=~(r-1),i=0;i<16;i++)n=o&(e[i]^t[i]),e[i]^=n,t[i]^=n}function j(e,r){var n,o,i,a=t(),s=t();for(n=0;n<16;n++)s[n]=r[n];for(I(s),I(s),I(s),o=0;o<2;o++){for(a[0]=s[0]-65517,n=1;n<15;n++)a[n]=s[n]-65535-(a[n-1]>>16&1),a[n-1]&=65535;a[15]=s[15]-32767-(a[14]>>16&1),i=a[15]>>16&1,a[14]&=65535,C(s,a,1-i)}for(n=0;n<16;n++)e[2*n]=255&s[n],e[2*n+1]=s[n]>>8}function B(e,t){var r=new Uint8Array(32),n=new Uint8Array(32);return j(r,e),j(n,t),v(r,0,n,0)}function L(e){var t=new Uint8Array(32);return j(t,e),1&t[0]}function N(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function U(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]+r[n]}function M(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]-r[n]}function F(e,t,r){var n,o,i=0,a=0,s=0,u=0,c=0,l=0,f=0,p=0,d=0,h=0,y=0,m=0,v=0,g=0,b=0,w=0,S=0,k=0,E=0,T=0,_=0,O=0,x=0,A=0,P=0,R=0,I=0,C=0,j=0,B=0,L=0,N=r[0],U=r[1],M=r[2],F=r[3],D=r[4],V=r[5],q=r[6],K=r[7],H=r[8],z=r[9],X=r[10],G=r[11],$=r[12],Q=r[13],W=r[14],Y=r[15];i+=(n=t[0])*N,a+=n*U,s+=n*M,u+=n*F,c+=n*D,l+=n*V,f+=n*q,p+=n*K,d+=n*H,h+=n*z,y+=n*X,m+=n*G,v+=n*$,g+=n*Q,b+=n*W,w+=n*Y,a+=(n=t[1])*N,s+=n*U,u+=n*M,c+=n*F,l+=n*D,f+=n*V,p+=n*q,d+=n*K,h+=n*H,y+=n*z,m+=n*X,v+=n*G,g+=n*$,b+=n*Q,w+=n*W,S+=n*Y,s+=(n=t[2])*N,u+=n*U,c+=n*M,l+=n*F,f+=n*D,p+=n*V,d+=n*q,h+=n*K,y+=n*H,m+=n*z,v+=n*X,g+=n*G,b+=n*$,w+=n*Q,S+=n*W,k+=n*Y,u+=(n=t[3])*N,c+=n*U,l+=n*M,f+=n*F,p+=n*D,d+=n*V,h+=n*q,y+=n*K,m+=n*H,v+=n*z,g+=n*X,b+=n*G,w+=n*$,S+=n*Q,k+=n*W,E+=n*Y,c+=(n=t[4])*N,l+=n*U,f+=n*M,p+=n*F,d+=n*D,h+=n*V,y+=n*q,m+=n*K,v+=n*H,g+=n*z,b+=n*X,w+=n*G,S+=n*$,k+=n*Q,E+=n*W,T+=n*Y,l+=(n=t[5])*N,f+=n*U,p+=n*M,d+=n*F,h+=n*D,y+=n*V,m+=n*q,v+=n*K,g+=n*H,b+=n*z,w+=n*X,S+=n*G,k+=n*$,E+=n*Q,T+=n*W,_+=n*Y,f+=(n=t[6])*N,p+=n*U,d+=n*M,h+=n*F,y+=n*D,m+=n*V,v+=n*q,g+=n*K,b+=n*H,w+=n*z,S+=n*X,k+=n*G,E+=n*$,T+=n*Q,_+=n*W,O+=n*Y,p+=(n=t[7])*N,d+=n*U,h+=n*M,y+=n*F,m+=n*D,v+=n*V,g+=n*q,b+=n*K,w+=n*H,S+=n*z,k+=n*X,E+=n*G,T+=n*$,_+=n*Q,O+=n*W,x+=n*Y,d+=(n=t[8])*N,h+=n*U,y+=n*M,m+=n*F,v+=n*D,g+=n*V,b+=n*q,w+=n*K,S+=n*H,k+=n*z,E+=n*X,T+=n*G,_+=n*$,O+=n*Q,x+=n*W,A+=n*Y,h+=(n=t[9])*N,y+=n*U,m+=n*M,v+=n*F,g+=n*D,b+=n*V,w+=n*q,S+=n*K,k+=n*H,E+=n*z,T+=n*X,_+=n*G,O+=n*$,x+=n*Q,A+=n*W,P+=n*Y,y+=(n=t[10])*N,m+=n*U,v+=n*M,g+=n*F,b+=n*D,w+=n*V,S+=n*q,k+=n*K,E+=n*H,T+=n*z,_+=n*X,O+=n*G,x+=n*$,A+=n*Q,P+=n*W,R+=n*Y,m+=(n=t[11])*N,v+=n*U,g+=n*M,b+=n*F,w+=n*D,S+=n*V,k+=n*q,E+=n*K,T+=n*H,_+=n*z,O+=n*X,x+=n*G,A+=n*$,P+=n*Q,R+=n*W,I+=n*Y,v+=(n=t[12])*N,g+=n*U,b+=n*M,w+=n*F,S+=n*D,k+=n*V,E+=n*q,T+=n*K,_+=n*H,O+=n*z,x+=n*X,A+=n*G,P+=n*$,R+=n*Q,I+=n*W,C+=n*Y,g+=(n=t[13])*N,b+=n*U,w+=n*M,S+=n*F,k+=n*D,E+=n*V,T+=n*q,_+=n*K,O+=n*H,x+=n*z,A+=n*X,P+=n*G,R+=n*$,I+=n*Q,C+=n*W,j+=n*Y,b+=(n=t[14])*N,w+=n*U,S+=n*M,k+=n*F,E+=n*D,T+=n*V,_+=n*q,O+=n*K,x+=n*H,A+=n*z,P+=n*X,R+=n*G,I+=n*$,C+=n*Q,j+=n*W,B+=n*Y,w+=(n=t[15])*N,a+=38*(k+=n*M),s+=38*(E+=n*F),u+=38*(T+=n*D),c+=38*(_+=n*V),l+=38*(O+=n*q),f+=38*(x+=n*K),p+=38*(A+=n*H),d+=38*(P+=n*z),h+=38*(R+=n*X),y+=38*(I+=n*G),m+=38*(C+=n*$),v+=38*(j+=n*Q),g+=38*(B+=n*W),b+=38*(L+=n*Y),i=(n=(i+=38*(S+=n*U))+(o=1)+65535)-65536*(o=Math.floor(n/65536)),a=(n=a+o+65535)-65536*(o=Math.floor(n/65536)),s=(n=s+o+65535)-65536*(o=Math.floor(n/65536)),u=(n=u+o+65535)-65536*(o=Math.floor(n/65536)),c=(n=c+o+65535)-65536*(o=Math.floor(n/65536)),l=(n=l+o+65535)-65536*(o=Math.floor(n/65536)),f=(n=f+o+65535)-65536*(o=Math.floor(n/65536)),p=(n=p+o+65535)-65536*(o=Math.floor(n/65536)),d=(n=d+o+65535)-65536*(o=Math.floor(n/65536)),h=(n=h+o+65535)-65536*(o=Math.floor(n/65536)),y=(n=y+o+65535)-65536*(o=Math.floor(n/65536)),m=(n=m+o+65535)-65536*(o=Math.floor(n/65536)),v=(n=v+o+65535)-65536*(o=Math.floor(n/65536)),g=(n=g+o+65535)-65536*(o=Math.floor(n/65536)),b=(n=b+o+65535)-65536*(o=Math.floor(n/65536)),w=(n=w+o+65535)-65536*(o=Math.floor(n/65536)),i=(n=(i+=o-1+37*(o-1))+(o=1)+65535)-65536*(o=Math.floor(n/65536)),a=(n=a+o+65535)-65536*(o=Math.floor(n/65536)),s=(n=s+o+65535)-65536*(o=Math.floor(n/65536)),u=(n=u+o+65535)-65536*(o=Math.floor(n/65536)),c=(n=c+o+65535)-65536*(o=Math.floor(n/65536)),l=(n=l+o+65535)-65536*(o=Math.floor(n/65536)),f=(n=f+o+65535)-65536*(o=Math.floor(n/65536)),p=(n=p+o+65535)-65536*(o=Math.floor(n/65536)),d=(n=d+o+65535)-65536*(o=Math.floor(n/65536)),h=(n=h+o+65535)-65536*(o=Math.floor(n/65536)),y=(n=y+o+65535)-65536*(o=Math.floor(n/65536)),m=(n=m+o+65535)-65536*(o=Math.floor(n/65536)),v=(n=v+o+65535)-65536*(o=Math.floor(n/65536)),g=(n=g+o+65535)-65536*(o=Math.floor(n/65536)),b=(n=b+o+65535)-65536*(o=Math.floor(n/65536)),w=(n=w+o+65535)-65536*(o=Math.floor(n/65536)),i+=o-1+37*(o-1),e[0]=i,e[1]=a,e[2]=s,e[3]=u,e[4]=c,e[5]=l,e[6]=f,e[7]=p,e[8]=d,e[9]=h,e[10]=y,e[11]=m,e[12]=v,e[13]=g,e[14]=b,e[15]=w}function D(e,t){F(e,t,t)}function V(e,r){var n,o=t();for(n=0;n<16;n++)o[n]=r[n];for(n=253;n>=0;n--)D(o,o),2!==n&&4!==n&&F(o,o,r);for(n=0;n<16;n++)e[n]=o[n]}function q(e,r){var n,o=t();for(n=0;n<16;n++)o[n]=r[n];for(n=250;n>=0;n--)D(o,o),1!==n&&F(o,o,r);for(n=0;n<16;n++)e[n]=o[n]}function K(e,r,n){var o,i,a=new Uint8Array(32),s=new Float64Array(80),c=t(),l=t(),f=t(),p=t(),d=t(),h=t();for(i=0;i<31;i++)a[i]=r[i];for(a[31]=127&r[31]|64,a[0]&=248,N(s,n),i=0;i<16;i++)l[i]=s[i],p[i]=c[i]=f[i]=0;for(c[0]=p[0]=1,i=254;i>=0;--i)C(c,l,o=a[i>>>3]>>>(7&i)&1),C(f,p,o),U(d,c,f),M(c,c,f),U(f,l,p),M(l,l,p),D(p,d),D(h,c),F(c,f,c),F(f,l,d),U(d,c,f),M(c,c,f),D(l,c),M(f,p,h),F(c,f,u),U(c,c,p),F(f,f,c),F(c,p,h),F(p,l,s),D(l,d),C(c,l,o),C(f,p,o);for(i=0;i<16;i++)s[i+16]=c[i],s[i+32]=f[i],s[i+48]=l[i],s[i+64]=p[i];var y=s.subarray(32),m=s.subarray(16);return V(y,y),F(m,m,y),j(e,m),0}function H(e,t){return K(e,t,i)}function z(e,t){return n(t,32),H(e,t)}function X(e,t,r){var n=new Uint8Array(32);return K(n,r,t),b(e,o,n,w)}_.prototype.blocks=function(e,t,r){for(var n,o,i,a,s,u,c,l,f,p,d,h,y,m,v,g,b,w,S,k=this.fin?0:2048,E=this.h[0],T=this.h[1],_=this.h[2],O=this.h[3],x=this.h[4],A=this.h[5],P=this.h[6],R=this.h[7],I=this.h[8],C=this.h[9],j=this.r[0],B=this.r[1],L=this.r[2],N=this.r[3],U=this.r[4],M=this.r[5],F=this.r[6],D=this.r[7],V=this.r[8],q=this.r[9];r>=16;)p=f=0,p+=(E+=8191&(n=255&e[t+0]|(255&e[t+1])<<8))*j,p+=(T+=8191&(n>>>13|(o=255&e[t+2]|(255&e[t+3])<<8)<<3))*(5*q),p+=(_+=8191&(o>>>10|(i=255&e[t+4]|(255&e[t+5])<<8)<<6))*(5*V),p+=(O+=8191&(i>>>7|(a=255&e[t+6]|(255&e[t+7])<<8)<<9))*(5*D),f=(p+=(x+=8191&(a>>>4|(s=255&e[t+8]|(255&e[t+9])<<8)<<12))*(5*F))>>>13,p&=8191,p+=(A+=s>>>1&8191)*(5*M),p+=(P+=8191&(s>>>14|(u=255&e[t+10]|(255&e[t+11])<<8)<<2))*(5*U),p+=(R+=8191&(u>>>11|(c=255&e[t+12]|(255&e[t+13])<<8)<<5))*(5*N),p+=(I+=8191&(c>>>8|(l=255&e[t+14]|(255&e[t+15])<<8)<<8))*(5*L),d=f+=(p+=(C+=l>>>5|k)*(5*B))>>>13,d+=E*B,d+=T*j,d+=_*(5*q),d+=O*(5*V),f=(d+=x*(5*D))>>>13,d&=8191,d+=A*(5*F),d+=P*(5*M),d+=R*(5*U),d+=I*(5*N),f+=(d+=C*(5*L))>>>13,d&=8191,h=f,h+=E*L,h+=T*B,h+=_*j,h+=O*(5*q),f=(h+=x*(5*V))>>>13,h&=8191,h+=A*(5*D),h+=P*(5*F),h+=R*(5*M),h+=I*(5*U),y=f+=(h+=C*(5*N))>>>13,y+=E*N,y+=T*L,y+=_*B,y+=O*j,f=(y+=x*(5*q))>>>13,y&=8191,y+=A*(5*V),y+=P*(5*D),y+=R*(5*F),y+=I*(5*M),m=f+=(y+=C*(5*U))>>>13,m+=E*U,m+=T*N,m+=_*L,m+=O*B,f=(m+=x*j)>>>13,m&=8191,m+=A*(5*q),m+=P*(5*V),m+=R*(5*D),m+=I*(5*F),v=f+=(m+=C*(5*M))>>>13,v+=E*M,v+=T*U,v+=_*N,v+=O*L,f=(v+=x*B)>>>13,v&=8191,v+=A*j,v+=P*(5*q),v+=R*(5*V),v+=I*(5*D),g=f+=(v+=C*(5*F))>>>13,g+=E*F,g+=T*M,g+=_*U,g+=O*N,f=(g+=x*L)>>>13,g&=8191,g+=A*B,g+=P*j,g+=R*(5*q),g+=I*(5*V),b=f+=(g+=C*(5*D))>>>13,b+=E*D,b+=T*F,b+=_*M,b+=O*U,f=(b+=x*N)>>>13,b&=8191,b+=A*L,b+=P*B,b+=R*j,b+=I*(5*q),w=f+=(b+=C*(5*V))>>>13,w+=E*V,w+=T*D,w+=_*F,w+=O*M,f=(w+=x*U)>>>13,w&=8191,w+=A*N,w+=P*L,w+=R*B,w+=I*j,S=f+=(w+=C*(5*q))>>>13,S+=E*q,S+=T*V,S+=_*D,S+=O*F,f=(S+=x*M)>>>13,S&=8191,S+=A*U,S+=P*N,S+=R*L,S+=I*B,E=p=8191&(f=(f=((f+=(S+=C*j)>>>13)<<2)+f|0)+(p&=8191)|0),T=d+=f>>>=13,_=h&=8191,O=y&=8191,x=m&=8191,A=v&=8191,P=g&=8191,R=b&=8191,I=w&=8191,C=S&=8191,t+=16,r-=16;this.h[0]=E,this.h[1]=T,this.h[2]=_,this.h[3]=O,this.h[4]=x,this.h[5]=A,this.h[6]=P,this.h[7]=R,this.h[8]=I,this.h[9]=C},_.prototype.finish=function(e,t){var r,n,o,i,a=new Uint16Array(10);if(this.leftover){for(i=this.leftover,this.buffer[i++]=1;i<16;i++)this.buffer[i]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(r=this.h[1]>>>13,this.h[1]&=8191,i=2;i<10;i++)this.h[i]+=r,r=this.h[i]>>>13,this.h[i]&=8191;for(this.h[0]+=5*r,r=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=r,r=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=r,a[0]=this.h[0]+5,r=a[0]>>>13,a[0]&=8191,i=1;i<10;i++)a[i]=this.h[i]+r,r=a[i]>>>13,a[i]&=8191;for(a[9]-=8192,n=(1^r)-1,i=0;i<10;i++)a[i]&=n;for(n=~n,i=0;i<10;i++)this.h[i]=this.h[i]&n|a[i];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),o=this.h[0]+this.pad[0],this.h[0]=65535&o,i=1;i<8;i++)o=(this.h[i]+this.pad[i]|0)+(o>>>16)|0,this.h[i]=65535&o;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},_.prototype.update=function(e,t,r){var n,o;if(this.leftover){for((o=16-this.leftover)>r&&(o=r),n=0;n=16&&(o=r-r%16,this.blocks(e,t,o),t+=o,r-=o),r){for(n=0;n=128;){for(k=0;k<16;k++)E=8*k+$,R[k]=r[E+0]<<24|r[E+1]<<16|r[E+2]<<8|r[E+3],I[k]=r[E+4]<<24|r[E+5]<<16|r[E+6]<<8|r[E+7];for(k=0;k<80;k++)if(o=C,i=j,a=B,s=L,u=N,c=U,l=M,F,p=D,d=V,h=q,y=K,m=H,v=z,g=X,G,O=65535&(_=G),x=_>>>16,A=65535&(T=F),P=T>>>16,O+=65535&(_=(H>>>14|N<<18)^(H>>>18|N<<14)^(N>>>9|H<<23)),x+=_>>>16,A+=65535&(T=(N>>>14|H<<18)^(N>>>18|H<<14)^(H>>>9|N<<23)),P+=T>>>16,O+=65535&(_=H&z^~H&X),x+=_>>>16,A+=65535&(T=N&U^~N&M),P+=T>>>16,O+=65535&(_=Q[2*k+1]),x+=_>>>16,A+=65535&(T=Q[2*k]),P+=T>>>16,T=R[k%16],x+=(_=I[k%16])>>>16,A+=65535&T,P+=T>>>16,A+=(x+=(O+=65535&_)>>>16)>>>16,O=65535&(_=S=65535&O|x<<16),x=_>>>16,A=65535&(T=w=65535&A|(P+=A>>>16)<<16),P=T>>>16,O+=65535&(_=(D>>>28|C<<4)^(C>>>2|D<<30)^(C>>>7|D<<25)),x+=_>>>16,A+=65535&(T=(C>>>28|D<<4)^(D>>>2|C<<30)^(D>>>7|C<<25)),P+=T>>>16,x+=(_=D&V^D&q^V&q)>>>16,A+=65535&(T=C&j^C&B^j&B),P+=T>>>16,f=65535&(A+=(x+=(O+=65535&_)>>>16)>>>16)|(P+=A>>>16)<<16,b=65535&O|x<<16,O=65535&(_=y),x=_>>>16,A=65535&(T=s),P=T>>>16,x+=(_=S)>>>16,A+=65535&(T=w),P+=T>>>16,j=o,B=i,L=a,N=s=65535&(A+=(x+=(O+=65535&_)>>>16)>>>16)|(P+=A>>>16)<<16,U=u,M=c,F=l,C=f,V=p,q=d,K=h,H=y=65535&O|x<<16,z=m,X=v,G=g,D=b,k%16==15)for(E=0;E<16;E++)T=R[E],O=65535&(_=I[E]),x=_>>>16,A=65535&T,P=T>>>16,T=R[(E+9)%16],O+=65535&(_=I[(E+9)%16]),x+=_>>>16,A+=65535&T,P+=T>>>16,w=R[(E+1)%16],O+=65535&(_=((S=I[(E+1)%16])>>>1|w<<31)^(S>>>8|w<<24)^(S>>>7|w<<25)),x+=_>>>16,A+=65535&(T=(w>>>1|S<<31)^(w>>>8|S<<24)^w>>>7),P+=T>>>16,w=R[(E+14)%16],x+=(_=((S=I[(E+14)%16])>>>19|w<<13)^(w>>>29|S<<3)^(S>>>6|w<<26))>>>16,A+=65535&(T=(w>>>19|S<<13)^(S>>>29|w<<3)^w>>>6),P+=T>>>16,P+=(A+=(x+=(O+=65535&_)>>>16)>>>16)>>>16,R[E]=65535&A|P<<16,I[E]=65535&O|x<<16;O=65535&(_=D),x=_>>>16,A=65535&(T=C),P=T>>>16,T=e[0],x+=(_=t[0])>>>16,A+=65535&T,P+=T>>>16,P+=(A+=(x+=(O+=65535&_)>>>16)>>>16)>>>16,e[0]=C=65535&A|P<<16,t[0]=D=65535&O|x<<16,O=65535&(_=V),x=_>>>16,A=65535&(T=j),P=T>>>16,T=e[1],x+=(_=t[1])>>>16,A+=65535&T,P+=T>>>16,P+=(A+=(x+=(O+=65535&_)>>>16)>>>16)>>>16,e[1]=j=65535&A|P<<16,t[1]=V=65535&O|x<<16,O=65535&(_=q),x=_>>>16,A=65535&(T=B),P=T>>>16,T=e[2],x+=(_=t[2])>>>16,A+=65535&T,P+=T>>>16,P+=(A+=(x+=(O+=65535&_)>>>16)>>>16)>>>16,e[2]=B=65535&A|P<<16,t[2]=q=65535&O|x<<16,O=65535&(_=K),x=_>>>16,A=65535&(T=L),P=T>>>16,T=e[3],x+=(_=t[3])>>>16,A+=65535&T,P+=T>>>16,P+=(A+=(x+=(O+=65535&_)>>>16)>>>16)>>>16,e[3]=L=65535&A|P<<16,t[3]=K=65535&O|x<<16,O=65535&(_=H),x=_>>>16,A=65535&(T=N),P=T>>>16,T=e[4],x+=(_=t[4])>>>16,A+=65535&T,P+=T>>>16,P+=(A+=(x+=(O+=65535&_)>>>16)>>>16)>>>16,e[4]=N=65535&A|P<<16,t[4]=H=65535&O|x<<16,O=65535&(_=z),x=_>>>16,A=65535&(T=U),P=T>>>16,T=e[5],x+=(_=t[5])>>>16,A+=65535&T,P+=T>>>16,P+=(A+=(x+=(O+=65535&_)>>>16)>>>16)>>>16,e[5]=U=65535&A|P<<16,t[5]=z=65535&O|x<<16,O=65535&(_=X),x=_>>>16,A=65535&(T=M),P=T>>>16,T=e[6],x+=(_=t[6])>>>16,A+=65535&T,P+=T>>>16,P+=(A+=(x+=(O+=65535&_)>>>16)>>>16)>>>16,e[6]=M=65535&A|P<<16,t[6]=X=65535&O|x<<16,O=65535&(_=G),x=_>>>16,A=65535&(T=F),P=T>>>16,T=e[7],x+=(_=t[7])>>>16,A+=65535&T,P+=T>>>16,P+=(A+=(x+=(O+=65535&_)>>>16)>>>16)>>>16,e[7]=F=65535&A|P<<16,t[7]=G=65535&O|x<<16,$+=128,n-=128}return n}function Y(e,t,r){var n,o=new Int32Array(8),i=new Int32Array(8),a=new Uint8Array(256),s=r;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,i[0]=4089235720,i[1]=2227873595,i[2]=4271175723,i[3]=1595750129,i[4]=2917565137,i[5]=725511199,i[6]=4215389547,i[7]=327033209,W(o,i,t,r),r%=128,n=0;n=0;--o)Z(e,t,n=r[o/8|0]>>(7&o)&1),J(t,e),J(e,e),Z(e,t,n)}function re(e,r){var n=[t(),t(),t(),t()];R(n[0],f),R(n[1],p),R(n[2],s),F(n[3],f,p),te(e,n,r)}function ne(e,r,o){var i,a=new Uint8Array(64),s=[t(),t(),t(),t()];for(o||n(r,32),Y(a,r,32),a[0]&=248,a[31]&=127,a[31]|=64,re(s,a),ee(e,s),i=0;i<32;i++)r[i+32]=e[i];return 0}var oe=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function ie(e,t){var r,n,o,i;for(n=63;n>=32;--n){for(r=0,o=n-32,i=n-12;o>4)*oe[o],r=t[o]>>8,t[o]&=255;for(o=0;o<32;o++)t[o]-=r*oe[o];for(n=0;n<32;n++)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function ae(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;ie(e,r)}function se(e,r,n,o){var i,a,s=new Uint8Array(64),u=new Uint8Array(64),c=new Uint8Array(64),l=new Float64Array(64),f=[t(),t(),t(),t()];Y(s,o,32),s[0]&=248,s[31]&=127,s[31]|=64;var p=n+64;for(i=0;i>7&&M(e[0],a,e[0]),F(e[3],e[0],e[1]),0)}(p,o))return-1;for(i=0;i=0},e.sign.keyPair=function(){var e=new Uint8Array(fe),t=new Uint8Array(pe);return ne(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(he(e),e.length!==pe)throw new Error("bad secret key size");for(var t=new Uint8Array(fe),r=0;r{"use strict";r.r(t),r.d(t,{StellarBase:()=>a,default:()=>s,httpClient:()=>n.ok});var n=r(9983),o=r(4356),i={};for(const e in o)["default","StellarBase","httpClient"].indexOf(e)<0&&(i[e]=()=>o[e]);r.d(t,i);var a=r(356);const s=(e=r.hmd(e)).exports},8732:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rh});var c,l,f,p={allowHttp:!1,timeout:0},d=a({},p),h=(c=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},f=[{key:"setAllowHttp",value:function(e){d.allowHttp=e}},{key:"setTimeout",value:function(e){d.timeout=e}},{key:"isAllowHttp",value:function(){return d.allowHttp}},{key:"getTimeout",value:function(){return d.timeout}},{key:"setDefault",value:function(){d=a({},p)}}],(l=null)&&o(c.prototype,l),f&&o(c,f),Object.defineProperty(c,"prototype",{writable:!1}),c)},6299:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AssembledTransaction:()=>de,Client:()=>tt,DEFAULT_TIMEOUT:()=>h,Err:()=>d,NULL_ACCOUNT:()=>y,Ok:()=>p,SentTransaction:()=>K,Spec:()=>Ne,basicNodeSigner:()=>be});var n=r(356),o=r(3496),i=r(4076),a=r(8680);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function c(e,t){for(var r=0;r=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),I(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;I(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function v(e){return v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},v(e)}function g(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function b(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){g(i,n,o,a,s,"next",e)}function s(e){g(i,n,o,a,s,"throw",e)}a(void 0)}))}}function w(e,t,r){return S.apply(this,arguments)}function S(){return S=b(m().mark((function e(t,r,n){var o,i,a,s,u,c,l,f=arguments;return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=f.length>3&&void 0!==f[3]?f[3]:1.5,i=f.length>4&&void 0!==f[4]&&f[4],a=[],s=0,e.t0=a,e.next=7,t();case 7:if(e.t1=e.sent,e.t0.push.call(e.t0,e.t1),r(a[a.length-1])){e.next=11;break}return e.abrupt("return",a);case 11:u=new Date(Date.now()+1e3*n).valueOf(),l=c=1e3;case 14:if(!(Date.now()u&&(c=u-Date.now(),i&&console.info("was gonna wait too long; new waitTime: ".concat(c,"ms"))),l=c+l,e.t2=a,e.next=25,t(a[a.length-1]);case 25:e.t3=e.sent,e.t2.push.call(e.t2,e.t3),i&&r(a[a.length-1])&&console.info("".concat(s,". Called ").concat(t,"; ").concat(a.length," prev attempts. Most recent: ").concat(JSON.stringify(a[a.length-1],null,2))),e.next=14;break;case 30:return e.abrupt("return",a);case 31:case"end":return e.stop()}}),e)}))),S.apply(this,arguments)}var k,E=/Error\(Contract, #(\d+)\)/;function T(e){for(var t=new n.cereal.XdrReader(e),r=[];!t.eof;)r.push(n.xdr.ScSpecEntry.read(t));return r}function _(e,t){return O.apply(this,arguments)}function O(){return(O=b(m().mark((function e(t,r){return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.publicKey?r.getAccount(t.publicKey):new n.Account(y,"0"));case 1:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function x(e,t,r){return t=C(t),function(e,t){if(t&&("object"==j(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,R()?Reflect.construct(t,r||[],C(e).constructor):t.apply(e,r))}function A(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&I(e,t)}function P(e){var t="function"==typeof Map?new Map:void 0;return P=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(R())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var o=new(e.bind.apply(e,n));return r&&I(o,r.prototype),o}(e,arguments,C(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),I(r,e)},P(e)}function R(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(R=function(){return!!e})()}function I(e,t){return I=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},I(e,t)}function C(e){return C=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},C(e)}function j(e){return j="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},j(e)}function B(){B=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,k=S&&S(S(I([])));k&&k!==r&&n.call(k,a)&&(w=k);var E=b.prototype=v.prototype=Object.create(w);function T(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function _(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==j(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function I(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:I(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function L(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function N(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){L(i,n,o,a,s,"next",e)}function s(e){L(i,n,o,a,s,"throw",e)}a(void 0)}))}}function U(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function M(e,t){for(var r=0;r=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,i=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw i}}}}function re(){re=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,k=S&&S(S(I([])));k&&k!==r&&n.call(k,a)&&(w=k);var E=b.prototype=v.prototype=Object.create(w);function T(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function _(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==Y(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function I(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:I(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function ne(e){return function(e){if(Array.isArray(e))return ie(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||oe(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function oe(e,t){if(e){if("string"==typeof e)return ie(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ie(e,t):void 0}}function ie(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r0&&void 0!==y[0]?y[0]:{}).restore,u.built){t.next=5;break}if(u.raw){t.next=4;break}throw new Error("Transaction has not yet been assembled; call `AssembledTransaction.build` first.");case 4:u.built=u.raw.build();case 5:return o=null!==(r=o)&&void 0!==r?r:u.options.restore,delete u.simulationResult,delete u.simulationTransactionData,t.next=10,u.server.simulateTransaction(u.built);case 10:if(u.simulation=t.sent,!o||!i.j.isSimulationRestore(u.simulation)){t.next=25;break}return t.next=14,_(u.options,u.server);case 14:return s=t.sent,t.next=17,u.restoreFootprint(u.simulation.restorePreamble,s);case 17:if((c=t.sent).status!==i.j.GetTransactionStatus.SUCCESS){t.next=24;break}return d=new n.Contract(u.options.contractId),u.raw=new n.TransactionBuilder(s,{fee:null!==(l=u.options.fee)&&void 0!==l?l:n.BASE_FEE,networkPassphrase:u.options.networkPassphrase}).addOperation(d.call.apply(d,[u.options.method].concat(ne(null!==(f=u.options.args)&&void 0!==f?f:[])))).setTimeout(null!==(p=u.options.timeoutInSeconds)&&void 0!==p?p:h),t.next=23,u.simulate();case 23:return t.abrupt("return",u);case 24:throw new e.Errors.RestorationFailure("Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n".concat(JSON.stringify(c)));case 25:return i.j.isSimulationSuccess(u.simulation)&&(u.built=(0,a.X)(u.built,u.simulation).build()),t.abrupt("return",u);case 27:case"end":return t.stop()}}),t)})))),fe(this,"sign",se(re().mark((function t(){var r,o,i,a,s,c,l,f,p,d,y,m,v=arguments;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i=(o=v.length>0&&void 0!==v[0]?v[0]:{}).force,a=void 0!==i&&i,s=o.signTransaction,c=void 0===s?u.options.signTransaction:s,u.built){t.next=3;break}throw new Error("Transaction has not yet been simulated");case 3:if(a||!u.isReadCall){t.next=5;break}throw new e.Errors.NoSignatureNeeded("This is a read call. It requires no signature or sending. Use `force: true` to sign and send anyway.");case 5:if(c){t.next=7;break}throw new e.Errors.NoSigner("You must provide a signTransaction function, either when calling `signAndSend` or when initializing your Client");case 7:if(!(l=u.needsNonInvokerSigningBy().filter((function(e){return!e.startsWith("C")}))).length){t.next=10;break}throw new e.Errors.NeedsMoreSignatures("Transaction requires signatures from ".concat(l,". ")+"See `needsNonInvokerSigningBy` for details.");case 10:return f=null!==(r=u.options.timeoutInSeconds)&&void 0!==r?r:h,u.built=n.TransactionBuilder.cloneFrom(u.built,{fee:u.built.fee,timebounds:void 0,sorobanData:u.simulationData.transactionData}).setTimeout(f).build(),p={networkPassphrase:u.options.networkPassphrase},u.options.address&&(p.address=u.options.address),void 0!==u.options.submit&&(p.submit=u.options.submit),u.options.submitUrl&&(p.submitUrl=u.options.submitUrl),t.next=18,c(u.built.toXDR(),p);case 18:d=t.sent,y=d.signedTxXdr,m=d.error,u.handleWalletError(m),u.signed=n.TransactionBuilder.fromXDR(y,u.options.networkPassphrase);case 23:case"end":return t.stop()}}),t)})))),fe(this,"signAndSend",se(re().mark((function e(){var t,r,n,o,i,a,s=arguments;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=(t=s.length>0&&void 0!==s[0]?s[0]:{}).force,n=void 0!==r&&r,o=t.signTransaction,i=void 0===o?u.options.signTransaction:o,u.signed){e.next=10;break}return a=u.options.submit,u.options.submit&&(u.options.submit=!1),e.prev=4,e.next=7,u.sign({force:n,signTransaction:i});case 7:return e.prev=7,u.options.submit=a,e.finish(7);case 10:return e.abrupt("return",u.send());case 11:case"end":return e.stop()}}),e,null,[[4,,7,10]])})))),fe(this,"needsNonInvokerSigningBy",(function(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).includeAlreadySigned,r=void 0!==t&&t;if(!u.built)throw new Error("Transaction has not yet been simulated");if(!("operations"in u.built))throw new Error("Unexpected Transaction type; no operations: ".concat(JSON.stringify(u.built)));var o=u.built.operations[0];return ne(new Set((null!==(e=o.auth)&&void 0!==e?e:[]).filter((function(e){return e.credentials().switch()===n.xdr.SorobanCredentialsType.sorobanCredentialsAddress()&&(r||"scvVoid"===e.credentials().address().signature().switch().name)})).map((function(e){return n.Address.fromScAddress(e.credentials().address().address()).toString()}))))})),fe(this,"signAuthEntries",se(re().mark((function t(){var r,o,i,a,s,c,l,f,p,d,h,y,m,v,g,b,w=arguments;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i=(o=w.length>0&&void 0!==w[0]?w[0]:{}).expiration,a=void 0===i?se(re().mark((function e(){return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,u.server.getLatestLedger();case 2:return e.t0=e.sent.sequence,e.abrupt("return",e.t0+100);case 4:case"end":return e.stop()}}),e)})))():i,s=o.signAuthEntry,c=void 0===s?u.options.signAuthEntry:s,l=o.address,f=void 0===l?u.options.publicKey:l,p=o.authorizeEntry,d=void 0===p?n.authorizeEntry:p,u.built){t.next=3;break}throw new Error("Transaction has not yet been assembled or simulated");case 3:if(d!==n.authorizeEntry){t.next=11;break}if(0!==(h=u.needsNonInvokerSigningBy()).length){t.next=7;break}throw new e.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?");case 7:if(-1!==h.indexOf(null!=f?f:"")){t.next=9;break}throw new e.Errors.NoSignatureNeeded('No auth entries for public key "'.concat(f,'"'));case 9:if(c){t.next=11;break}throw new e.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`");case 11:y=u.built.operations[0],m=null!==(r=y.auth)&&void 0!==r?r:[],v=te(m.entries()),t.prev=14,b=re().mark((function e(){var t,r,o,i,s;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=ee(g.value,2),r=t[0],o=t[1],(i=n.xdr.SorobanCredentials.fromXDR(o.credentials().toXDR())).switch()===n.xdr.SorobanCredentialsType.sorobanCredentialsAddress()){e.next=4;break}return e.abrupt("return",0);case 4:if(n.Address.fromScAddress(i.address().address()).toString()===f){e.next=7;break}return e.abrupt("return",0);case 7:return s=null!=c?c:Promise.resolve,e.t0=d,e.t1=o,e.t2=function(){var e=se(re().mark((function e(t){var r,n,o;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,s(t.toXDR("base64"),{address:f});case 2:return r=e.sent,n=r.signedAuthEntry,o=r.error,u.handleWalletError(o),e.abrupt("return",H.from(n,"base64"));case 7:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),e.next=13,a;case 13:return e.t3=e.sent,e.t4=u.options.networkPassphrase,e.next=17,(0,e.t0)(e.t1,e.t2,e.t3,e.t4);case 17:m[r]=e.sent;case 18:case"end":return e.stop()}}),e)})),v.s();case 17:if((g=v.n()).done){t.next=24;break}return t.delegateYield(b(),"t0",19);case 19:if(0!==t.t0){t.next=22;break}return t.abrupt("continue",22);case 22:t.next=17;break;case 24:t.next=29;break;case 26:t.prev=26,t.t1=t.catch(14),v.e(t.t1);case 29:return t.prev=29,v.f(),t.finish(29);case 32:case"end":return t.stop()}}),t,null,[[14,26,29,32]])})))),this.options=t,this.options.simulate=null===(r=this.options.simulate)||void 0===r||r,this.server=new o.Server(this.options.rpcUrl,{allowHttp:null!==(s=this.options.allowHttp)&&void 0!==s&&s})}return le(e,[{key:"toJSON",value:function(){var e;return JSON.stringify({method:this.options.method,tx:null===(e=this.built)||void 0===e?void 0:e.toXDR(),simulationResult:{auth:this.simulationData.result.auth.map((function(e){return e.toXDR("base64")})),retval:this.simulationData.result.retval.toXDR("base64")},simulationTransactionData:this.simulationData.transactionData.toXDR("base64")})}},{key:"toXDR",value:function(){var e;if(!this.built)throw new Error("Transaction has not yet been simulated; call `AssembledTransaction.simulate` first.");return null===(e=this.built)||void 0===e?void 0:e.toEnvelope().toXDR("base64")}},{key:"handleWalletError",value:function(t){if(t){var r=t.message,n=t.code,o="".concat(r).concat(t.ext?" (".concat(t.ext.join(", "),")"):"");switch(n){case-1:throw new e.Errors.InternalWalletError(o);case-2:throw new e.Errors.ExternalServiceError(o);case-3:throw new e.Errors.InvalidClientRequest(o);case-4:throw new e.Errors.UserRejected(o);default:throw new Error("Unhandled error: ".concat(o))}}}},{key:"simulationData",get:function(){var t;if(this.simulationResult&&this.simulationTransactionData)return{result:this.simulationResult,transactionData:this.simulationTransactionData};var r=this.simulation;if(!r)throw new e.Errors.NotYetSimulated("Transaction has not yet been simulated");if(i.j.isSimulationError(r))throw new e.Errors.SimulationFailed('Transaction simulation failed: "'.concat(r.error,'"'));if(i.j.isSimulationRestore(r))throw new e.Errors.ExpiredState("You need to restore some contract state before you can invoke this method.\nYou can set `restore` to true in the method options in order to automatically restore the contract state when needed.");return this.simulationResult=null!==(t=r.result)&&void 0!==t?t:{auth:[],retval:n.xdr.ScVal.scvVoid()},this.simulationTransactionData=r.transactionData.build(),{result:this.simulationResult,transactionData:this.simulationTransactionData}}},{key:"result",get:function(){try{if(!this.simulationData.result)throw new Error("No simulation result!");return this.options.parseResultXdr(this.simulationData.result.retval)}catch(r){if("object"!==v(t=r)||null===t||!("toString"in t))throw r;var e=this.parseError(r.toString());if(e)return e;throw r}var t}},{key:"parseError",value:function(e){if(this.options.errorTypes){var t=e.match(E);if(t){var r=parseInt(t[1],10),n=this.options.errorTypes[r];if(n)return new d(n)}}}},{key:"send",value:(u=se(re().mark((function e(){var t;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.signed){e.next=2;break}throw new Error("The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead.");case 2:return e.next=4,K.init(this);case 4:return t=e.sent,e.abrupt("return",t);case 6:case"end":return e.stop()}}),e,this)}))),function(){return u.apply(this,arguments)})},{key:"isReadCall",get:function(){var e=this.simulationData.result.auth.length,t=this.simulationData.transactionData.resources().footprint().readWrite().length;return 0===e&&0===t}},{key:"restoreFootprint",value:(s=se(re().mark((function t(r,n){var o,i,a;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this.options.signTransaction){t.next=2;break}throw new Error("For automatic restore to work you must provide a signTransaction function when initializing your Client");case 2:if(null===(o=n)||void 0===o){t.next=6;break}t.t0=o,t.next=9;break;case 6:return t.next=8,_(this.options,this.server);case 8:t.t0=t.sent;case 9:return n=t.t0,t.next=12,e.buildFootprintRestoreTransaction(Z({},this.options),r.transactionData,n,r.minResourceFee);case 12:return i=t.sent,t.next=15,i.signAndSend();case 15:if((a=t.sent).getTransactionResponse){t.next=18;break}throw new e.Errors.RestorationFailure("The attempt at automatic restore failed. \n".concat(JSON.stringify(a)));case 18:return t.abrupt("return",a.getTransactionResponse);case 19:case"end":return t.stop()}}),t,this)}))),function(e,t){return s.apply(this,arguments)})}],[{key:"fromJSON",value:function(t,r){var o=r.tx,i=r.simulationResult,a=r.simulationTransactionData,s=new e(t);return s.built=n.TransactionBuilder.fromXDR(o,t.networkPassphrase),s.simulationResult={auth:i.auth.map((function(e){return n.xdr.SorobanAuthorizationEntry.fromXDR(e,"base64")})),retval:n.xdr.ScVal.fromXDR(i.retval,"base64")},s.simulationTransactionData=n.xdr.SorobanTransactionData.fromXDR(a,"base64"),s}},{key:"fromXDR",value:function(t,r,o){var i,a=n.xdr.TransactionEnvelope.fromXDR(r,"base64"),s=n.TransactionBuilder.fromXDR(a,t.networkPassphrase),u=s.operations[0];if(null==u||null===(i=u.func)||void 0===i||!i.value||"function"!=typeof u.func.value)throw new Error("Could not extract the method from the transaction envelope.");var c=u.func.value();if(null==c||!c.functionName)throw new Error("Could not extract the method name from the transaction envelope.");var l=c.functionName().toString("utf-8"),f=new e(Z(Z({},t),{},{method:l,parseResultXdr:function(e){return o.funcResToNative(l,e)}}));return f.built=s,f}},{key:"build",value:function(t){var r,o=new n.Contract(t.contractId);return e.buildWithOp(o.call.apply(o,[t.method].concat(ne(null!==(r=t.args)&&void 0!==r?r:[]))),t)}},{key:"buildWithOp",value:(r=se(re().mark((function t(r,o){var i,a,s,u;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return s=new e(o),t.next=3,_(o,s.server);case 3:if(u=t.sent,s.raw=new n.TransactionBuilder(u,{fee:null!==(i=o.fee)&&void 0!==i?i:n.BASE_FEE,networkPassphrase:o.networkPassphrase}).setTimeout(null!==(a=o.timeoutInSeconds)&&void 0!==a?a:h).addOperation(r),!o.simulate){t.next=8;break}return t.next=8,s.simulate();case 8:return t.abrupt("return",s);case 9:case"end":return t.stop()}}),t)}))),function(e,t){return r.apply(this,arguments)})},{key:"buildFootprintRestoreTransaction",value:(t=se(re().mark((function t(r,o,i,a){var s,u;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return(u=new e(r)).raw=new n.TransactionBuilder(i,{fee:a,networkPassphrase:r.networkPassphrase}).setSorobanData(o instanceof n.SorobanDataBuilder?o.build():o).addOperation(n.Operation.restoreFootprint({})).setTimeout(null!==(s=r.timeoutInSeconds)&&void 0!==s?s:h),t.next=4,u.simulate({restore:!1});case 4:return t.abrupt("return",u);case 5:case"end":return t.stop()}}),t)}))),function(e,r,n,o){return t.apply(this,arguments)})}]);var t,r,s,u}();fe(de,"Errors",{ExpiredState:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),RestorationFailure:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NeedsMoreSignatures:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NoSignatureNeeded:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NoUnsignedNonInvokerAuthEntries:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NoSigner:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NotYetSimulated:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),FakeAccount:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),SimulationFailed:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),InternalWalletError:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),ExternalServiceError:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),InvalidClientRequest:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),UserRejected:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error))});var he=r(8287).Buffer;function ye(e){return ye="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ye(e)}function me(){me=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,k=S&&S(S(I([])));k&&k!==r&&n.call(k,a)&&(w=k);var E=b.prototype=v.prototype=Object.create(w);function T(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function _(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==ye(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function I(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:I(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function ve(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function ge(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){ve(i,n,o,a,s,"next",e)}function s(e){ve(i,n,o,a,s,"throw",e)}a(void 0)}))}}var be=function(e,t){return{signTransaction:(o=ge(me().mark((function r(o,i){var a;return me().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return(a=n.TransactionBuilder.fromXDR(o,(null==i?void 0:i.networkPassphrase)||t)).sign(e),r.abrupt("return",{signedTxXdr:a.toXDR(),signerAddress:e.publicKey()});case 3:case"end":return r.stop()}}),r)}))),function(e,t){return o.apply(this,arguments)}),signAuthEntry:(r=ge(me().mark((function t(r){var o;return me().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return o=e.sign((0,n.hash)(he.from(r,"base64"))).toString("base64"),t.abrupt("return",{signedAuthEntry:o,signerAddress:e.publicKey()});case 2:case"end":return t.stop()}}),t)}))),function(e){return r.apply(this,arguments)})};var r,o},we=r(8287).Buffer;function Se(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function ke(e){for(var t=1;te.length)&&(t=e.length);for(var r=0,n=Array(t);r0&&(o.required=r),o}var je,Be,Le,Ne=(je=function e(t){if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),_e(this,"entries",[]),0===t.length)throw new Error("Contract spec must have at least one entry");var r=t[0];this.entries="string"==typeof r?t.map((function(e){return n.xdr.ScSpecEntry.fromXDR(e,"base64")})):t},Be=[{key:"funcs",value:function(){return this.entries.filter((function(e){return e.switch().value===n.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value})).map((function(e){return e.functionV0()}))}},{key:"getFunc",value:function(e){var t=this.findEntry(e);if(t.switch().value!==n.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value)throw new Error("".concat(e," is not a function"));return t.functionV0()}},{key:"funcArgsToScVals",value:function(e,t){var r=this;return this.getFunc(e).inputs().map((function(e){return r.nativeToScVal(function(e,t){var r=t.name().toString(),n=Object.entries(e).find((function(e){return xe(e,1)[0]===r}));if(!n)throw new Error("Missing field ".concat(r));return n[1]}(t,e),e.type())}))}},{key:"funcResToNative",value:function(e,t){var r="string"==typeof t?n.xdr.ScVal.fromXDR(t,"base64"):t,o=this.getFunc(e).outputs();if(0===o.length){var i=r.switch();if(i.value!==n.xdr.ScValType.scvVoid().value)throw new Error("Expected void, got ".concat(i.name));return null}if(o.length>1)throw new Error("Multiple outputs not supported");var a=o[0];return a.switch().value===n.xdr.ScSpecType.scSpecTypeResult().value?new p(this.scValToNative(r,a.result().okType())):this.scValToNative(r,a)}},{key:"findEntry",value:function(e){var t=this.entries.find((function(t){return t.value().name().toString()===e}));if(!t)throw new Error("no such entry: ".concat(e));return t}},{key:"nativeToScVal",value:function(e,t){var r=this,o=t.switch(),i=o.value;if(o.value===n.xdr.ScSpecType.scSpecTypeUdt().value){var a=t.udt();return this.nativeToUdt(e,a.name().toString())}if(i===n.xdr.ScSpecType.scSpecTypeOption().value){var s=t.option();return void 0===e?n.xdr.ScVal.scvVoid():this.nativeToScVal(e,s.valueType())}switch(Ee(e)){case"object":var u,c,l;if(null===e){if(i===n.xdr.ScSpecType.scSpecTypeVoid().value)return n.xdr.ScVal.scvVoid();throw new TypeError("Type ".concat(t," was not void, but value was null"))}if(e instanceof n.xdr.ScVal)return e;if(e instanceof n.Address){if(t.switch().value!==n.xdr.ScSpecType.scSpecTypeAddress().value)throw new TypeError("Type ".concat(t," was not address, but value was Address"));return e.toScVal()}if(e instanceof n.Contract){if(t.switch().value!==n.xdr.ScSpecType.scSpecTypeAddress().value)throw new TypeError("Type ".concat(t," was not address, but value was Address"));return e.address().toScVal()}if(e instanceof Uint8Array||we.isBuffer(e)){var f=Uint8Array.from(e);switch(i){case n.xdr.ScSpecType.scSpecTypeBytesN().value:var p=t.bytesN();if(f.length!==p.n())throw new TypeError("expected ".concat(p.n()," bytes, but got ").concat(f.length));return n.xdr.ScVal.scvBytes(f);case n.xdr.ScSpecType.scSpecTypeBytes().value:return n.xdr.ScVal.scvBytes(f);default:throw new TypeError("invalid type (".concat(t,") specified for Bytes and BytesN"))}}if(Array.isArray(e))switch(i){case n.xdr.ScSpecType.scSpecTypeVec().value:var d=t.vec().elementType();return n.xdr.ScVal.scvVec(e.map((function(e){return r.nativeToScVal(e,d)})));case n.xdr.ScSpecType.scSpecTypeTuple().value:var h=t.tuple().valueTypes();if(e.length!==h.length)throw new TypeError("Tuple expects ".concat(h.length," values, but ").concat(e.length," were provided"));return n.xdr.ScVal.scvVec(e.map((function(e,t){return r.nativeToScVal(e,h[t])})));case n.xdr.ScSpecType.scSpecTypeMap().value:var y=t.map(),m=y.keyType(),v=y.valueType();return n.xdr.ScVal.scvMap(e.map((function(e){var t=r.nativeToScVal(e[0],m),o=r.nativeToScVal(e[1],v);return new n.xdr.ScMapEntry({key:t,val:o})})));default:throw new TypeError("Type ".concat(t," was not vec, but value was Array"))}if(e.constructor===Map){if(i!==n.xdr.ScSpecType.scSpecTypeMap().value)throw new TypeError("Type ".concat(t," was not map, but value was Map"));for(var g=t.map(),b=[],w=e.entries(),S=w.next();!S.done;){var k=xe(S.value,2),E=k[0],T=k[1],_=this.nativeToScVal(E,g.keyType()),O=this.nativeToScVal(T,g.valueType());b.push(new n.xdr.ScMapEntry({key:_,val:O})),S=w.next()}return n.xdr.ScVal.scvMap(b)}if("Object"!==(null!==(u=null===(c=e.constructor)||void 0===c?void 0:c.name)&&void 0!==u?u:""))throw new TypeError("cannot interpret ".concat(null===(l=e.constructor)||void 0===l?void 0:l.name," value as ScVal (").concat(JSON.stringify(e),")"));throw new TypeError("Received object ".concat(e," did not match the provided type ").concat(t));case"number":case"bigint":switch(i){case n.xdr.ScSpecType.scSpecTypeU32().value:return n.xdr.ScVal.scvU32(e);case n.xdr.ScSpecType.scSpecTypeI32().value:return n.xdr.ScVal.scvI32(e);case n.xdr.ScSpecType.scSpecTypeU64().value:case n.xdr.ScSpecType.scSpecTypeI64().value:case n.xdr.ScSpecType.scSpecTypeU128().value:case n.xdr.ScSpecType.scSpecTypeI128().value:case n.xdr.ScSpecType.scSpecTypeU256().value:case n.xdr.ScSpecType.scSpecTypeI256().value:var x=o.name.substring(10).toLowerCase();return new n.XdrLargeInt(x,e).toScVal();default:throw new TypeError("invalid type (".concat(t,") specified for integer"))}case"string":return function(e,t){switch(t.value){case n.xdr.ScSpecType.scSpecTypeString().value:return n.xdr.ScVal.scvString(e);case n.xdr.ScSpecType.scSpecTypeSymbol().value:return n.xdr.ScVal.scvSymbol(e);case n.xdr.ScSpecType.scSpecTypeAddress().value:var r=n.Address.fromString(e);return n.xdr.ScVal.scvAddress(r.toScAddress());case n.xdr.ScSpecType.scSpecTypeU64().value:return new n.XdrLargeInt("u64",e).toScVal();case n.xdr.ScSpecType.scSpecTypeI64().value:return new n.XdrLargeInt("i64",e).toScVal();case n.xdr.ScSpecType.scSpecTypeU128().value:return new n.XdrLargeInt("u128",e).toScVal();case n.xdr.ScSpecType.scSpecTypeI128().value:return new n.XdrLargeInt("i128",e).toScVal();case n.xdr.ScSpecType.scSpecTypeU256().value:return new n.XdrLargeInt("u256",e).toScVal();case n.xdr.ScSpecType.scSpecTypeI256().value:return new n.XdrLargeInt("i256",e).toScVal();case n.xdr.ScSpecType.scSpecTypeBytes().value:case n.xdr.ScSpecType.scSpecTypeBytesN().value:return n.xdr.ScVal.scvBytes(we.from(e,"base64"));default:throw new TypeError("invalid type ".concat(t.name," specified for string value"))}}(e,o);case"boolean":if(i!==n.xdr.ScSpecType.scSpecTypeBool().value)throw TypeError("Type ".concat(t," was not bool, but value was bool"));return n.xdr.ScVal.scvBool(e);case"undefined":if(!t)return n.xdr.ScVal.scvVoid();switch(i){case n.xdr.ScSpecType.scSpecTypeVoid().value:case n.xdr.ScSpecType.scSpecTypeOption().value:return n.xdr.ScVal.scvVoid();default:throw new TypeError("Type ".concat(t," was not void, but value was undefined"))}case"function":return this.nativeToScVal(e(),t);default:throw new TypeError("failed to convert typeof ".concat(Ee(e)," (").concat(e,")"))}}},{key:"nativeToUdt",value:function(e,t){var r=this.findEntry(t);switch(r.switch()){case n.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0():if("number"!=typeof e)throw new TypeError("expected number for enum ".concat(t,", but got ").concat(Ee(e)));return this.nativeToEnum(e,r.udtEnumV0());case n.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.nativeToStruct(e,r.udtStructV0());case n.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.nativeToUnion(e,r.udtUnionV0());default:throw new Error("failed to parse udt ".concat(t))}}},{key:"nativeToUnion",value:function(e,t){var r=this,o=e.tag,i=t.cases().find((function(e){return e.value().name().toString()===o}));if(!i)throw new TypeError("no such enum entry: ".concat(o," in ").concat(t));var a=n.xdr.ScVal.scvSymbol(o);switch(i.switch()){case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0():return n.xdr.ScVal.scvVec([a]);case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0():var s=i.tupleCase().type();if(Array.isArray(e.values)){if(e.values.length!==s.length)throw new TypeError("union ".concat(t," expects ").concat(s.length," values, but got ").concat(e.values.length));var u=e.values.map((function(e,t){return r.nativeToScVal(e,s[t])}));return u.unshift(a),n.xdr.ScVal.scvVec(u)}throw new Error("failed to parse union case ".concat(i," with ").concat(e));default:throw new Error("failed to parse union ".concat(t," with ").concat(e))}}},{key:"nativeToStruct",value:function(e,t){var r=this,o=t.fields();if(o.some(Pe)){if(!o.every(Pe))throw new Error("mixed numeric and non-numeric field names are not allowed");return n.xdr.ScVal.scvVec(o.map((function(t,n){return r.nativeToScVal(e[n],o[n].type())})))}return n.xdr.ScVal.scvMap(o.map((function(t){var o=t.name().toString();return new n.xdr.ScMapEntry({key:r.nativeToScVal(o,n.xdr.ScSpecTypeDef.scSpecTypeSymbol()),val:r.nativeToScVal(e[o],t.type())})})))}},{key:"nativeToEnum",value:function(e,t){if(t.cases().some((function(t){return t.value()===e})))return n.xdr.ScVal.scvU32(e);throw new TypeError("no such enum entry: ".concat(e," in ").concat(t))}},{key:"scValStrToNative",value:function(e,t){return this.scValToNative(n.xdr.ScVal.fromXDR(e,"base64"),t)}},{key:"scValToNative",value:function(e,t){var r=this,o=t.switch(),i=o.value;if(i===n.xdr.ScSpecType.scSpecTypeUdt().value)return this.scValUdtToNative(e,t.udt());switch(e.switch().value){case n.xdr.ScValType.scvVoid().value:return;case n.xdr.ScValType.scvU64().value:case n.xdr.ScValType.scvI64().value:case n.xdr.ScValType.scvU128().value:case n.xdr.ScValType.scvI128().value:case n.xdr.ScValType.scvU256().value:case n.xdr.ScValType.scvI256().value:return(0,n.scValToBigInt)(e);case n.xdr.ScValType.scvVec().value:if(i===n.xdr.ScSpecType.scSpecTypeVec().value){var a,s=t.vec();return(null!==(a=e.vec())&&void 0!==a?a:[]).map((function(e){return r.scValToNative(e,s.elementType())}))}if(i===n.xdr.ScSpecType.scSpecTypeTuple().value){var u,c=t.tuple().valueTypes();return(null!==(u=e.vec())&&void 0!==u?u:[]).map((function(e,t){return r.scValToNative(e,c[t])}))}throw new TypeError("Type ".concat(t," was not vec, but ").concat(e," is"));case n.xdr.ScValType.scvAddress().value:return n.Address.fromScVal(e).toString();case n.xdr.ScValType.scvMap().value:var l,f=null!==(l=e.map())&&void 0!==l?l:[];if(i===n.xdr.ScSpecType.scSpecTypeMap().value){var p=t.map(),d=p.keyType(),h=p.valueType();return f.map((function(e){return[r.scValToNative(e.key(),d),r.scValToNative(e.val(),h)]}))}throw new TypeError("ScSpecType ".concat(o.name," was not map, but ").concat(JSON.stringify(e,null,2)," is"));case n.xdr.ScValType.scvBool().value:case n.xdr.ScValType.scvU32().value:case n.xdr.ScValType.scvI32().value:case n.xdr.ScValType.scvBytes().value:return e.value();case n.xdr.ScValType.scvString().value:case n.xdr.ScValType.scvSymbol().value:var y;if(i!==n.xdr.ScSpecType.scSpecTypeString().value&&i!==n.xdr.ScSpecType.scSpecTypeSymbol().value)throw new Error("ScSpecType ".concat(o.name," was not string or symbol, but ").concat(JSON.stringify(e,null,2)," is"));return null===(y=e.value())||void 0===y?void 0:y.toString();case n.xdr.ScValType.scvTimepoint().value:case n.xdr.ScValType.scvDuration().value:return(0,n.scValToBigInt)(n.xdr.ScVal.scvU64(e.u64()));default:throw new TypeError("failed to convert ".concat(JSON.stringify(e,null,2)," to native type from type ").concat(o.name))}}},{key:"scValUdtToNative",value:function(e,t){var r=this.findEntry(t.name().toString());switch(r.switch()){case n.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0():return this.enumToNative(e);case n.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.structToNative(e,r.udtStructV0());case n.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.unionToNative(e,r.udtUnionV0());default:throw new Error("failed to parse udt ".concat(t.name().toString(),": ").concat(r))}}},{key:"unionToNative",value:function(e,t){var r=this,o=e.vec();if(!o)throw new Error("".concat(JSON.stringify(e,null,2)," is not a vec"));if(0===o.length&&0!==t.cases.length)throw new Error("".concat(e," has length 0, but the there are at least one case in the union"));var i=o[0].sym().toString();if(o[0].switch().value!==n.xdr.ScValType.scvSymbol().value)throw new Error("{vec[0]} is not a symbol");var a=t.cases().find(function(e){return function(t){switch(t.switch().value){case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value:return t.tupleCase().name().toString()===e;case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value:return t.voidCase().name().toString()===e;default:return!1}}}(i));if(!a)throw new Error("failed to find entry ".concat(i," in union {udt.name().toString()}"));var s={tag:i};if(a.switch().value===n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value){var u=a.tupleCase().type().map((function(e,t){return r.scValToNative(o[t+1],e)}));s.values=u}return s}},{key:"structToNative",value:function(e,t){var r,n,o=this,i={},a=t.fields();return a.some(Pe)?null===(n=e.vec())||void 0===n?void 0:n.map((function(e,t){return o.scValToNative(e,a[t].type())})):(null===(r=e.map())||void 0===r||r.forEach((function(e,t){var r=a[t];i[r.name().toString()]=o.scValToNative(e.val(),r.type())})),i)}},{key:"enumToNative",value:function(e){if(e.switch().value!==n.xdr.ScValType.scvU32().value)throw new Error("Enum must have a u32 value");return e.u32()}},{key:"errorCases",value:function(){return this.entries.filter((function(e){return e.switch().value===n.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value})).flatMap((function(e){return e.value().cases()}))}},{key:"jsonSchema",value:function(e){var t={};this.entries.forEach((function(e){switch(e.switch().value){case n.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0().value:var r=e.udtEnumV0();t[r.name().toString()]=function(e){var t=e.doc().toString(),r=e.cases(),n=[];r.forEach((function(e){var t=e.name().toString(),r=e.doc().toString();n.push({description:r,title:t,enum:[e.value()],type:"number"})}));var o={oneOf:n};return t.length>0&&(o.description=t),o}(r);break;case n.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0().value:var o=e.udtStructV0();t[o.name().toString()]=function(e){var t=e.fields();if(t.some(Pe)){if(!t.every(Pe))throw new Error("mixed numeric and non-numeric field names are not allowed");return{type:"array",items:t.map((function(e,r){return Ie(t[r].type())})),minItems:t.length,maxItems:t.length}}var r=e.doc().toString(),n=Ce(t),o=n.properties,i=n.required;return o.additionalProperties=!1,{description:r,properties:o,required:i,type:"object"}}(o);break;case n.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0().value:var i=e.udtUnionV0();t[i.name().toString()]=function(e){var t=e.doc().toString(),r=e.cases(),o=[];r.forEach((function(e){switch(e.switch().value){case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value:var t=e.voidCase().name().toString();o.push({type:"object",title:t,properties:{tag:t},additionalProperties:!1,required:["tag"]});break;case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value:var r=e.tupleCase(),i=r.name().toString();o.push({type:"object",title:i,properties:{tag:i,values:{type:"array",items:r.type().map(Ie)}},required:["tag","values"],additionalProperties:!1})}}));var i={oneOf:o};return t.length>0&&(i.description=t),i}(i);break;case n.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value:var a=e.functionV0(),s=a.name().toString(),u=function(e){var t=Ce(e.inputs()),r=t.properties,o=t.required,i={additionalProperties:!1,properties:r,type:"object"};(null==o?void 0:o.length)>0&&(i.required=o);var a={properties:{args:i}},s=e.outputs(),u=s.length>0?Ie(s[0]):Ie(n.xdr.ScSpecTypeDef.scSpecTypeVoid()),c=e.doc().toString();return c.length>0&&(a.description=c),a.additionalProperties=!1,u.additionalProperties=!1,{input:a,output:u}}(a),c=u.input;t[s]=c;case n.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value:}}));var r={$schema:"http://json-schema.org/draft-07/schema#",definitions:ke(ke({},Re),t)};return e&&(r.$ref="#/definitions/".concat(e)),r}}],Be&&Te(je.prototype,Be),Le&&Te(je,Le),Object.defineProperty(je,"prototype",{writable:!1}),je),Ue=r(8287).Buffer;function Me(e){return Me="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Me(e)}var Fe=["method"],De=["wasmHash","salt","format","fee","timeoutInSeconds","simulate"];function Ve(){Ve=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,k=S&&S(S(I([])));k&&k!==r&&n.call(k,a)&&(w=k);var E=b.prototype=v.prototype=Object.create(w);function T(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function _(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==Me(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function I(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:I(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function qe(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Ke(e){for(var t=1;t2&&void 0!==l[2]?l[2]:"hex",r&&r.rpcUrl){e.next=3;break}throw new TypeError("options must contain rpcUrl");case 3:return i=r.rpcUrl,a=r.allowHttp,s={allowHttp:a},u=new o.Server(i,s),e.next=8,u.getContractWasmByHash(t,n);case 8:return c=e.sent,e.abrupt("return",Ye(c));case 10:case"end":return e.stop()}}),e)}))),et.apply(this,arguments)}var tt=function(){function e(t,r){var n=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Xe(this,"txFromJSON",(function(e){var t=JSON.parse(e),r=t.method,o=He(t,Fe);return de.fromJSON(Ke(Ke({},n.options),{},{method:r,parseResultXdr:function(e){return n.spec.funcResToNative(r,e)}}),o)})),Xe(this,"txFromXDR",(function(e){return de.fromXDR(n.options,e,n.spec)})),this.spec=t,this.options=r,this.spec.funcs().forEach((function(e){var o=e.name().toString();if(o!==We){var i=function(e,n){return de.build(Ke(Ke(Ke({method:o,args:e&&t.funcArgsToScVals(o,e)},r),n),{},{errorTypes:t.errorCases().reduce((function(e,t){return Ke(Ke({},e),{},Xe({},t.value(),{message:t.doc().toString()}))}),{}),parseResultXdr:function(e){return t.funcResToNative(o,e)}}))};n[o]=0===t.getFunc(o).inputs().length?function(e){return i(void 0,e)}:i}}))}return function(e,t,r){return t&&ze(e.prototype,t),r&&ze(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}(e,null,[{key:"deploy",value:(a=Qe(Ve().mark((function t(r,o){var i,a,s,u,c,l,f,p,d;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=o.wasmHash,a=o.salt,s=o.format,u=o.fee,c=o.timeoutInSeconds,l=o.simulate,f=He(o,De),t.next=3,Ze(i,f,s);case 3:return p=t.sent,d=n.Operation.createCustomContract({address:new n.Address(o.publicKey),wasmHash:"string"==typeof i?Ue.from(i,null!=s?s:"hex"):i,salt:a,constructorArgs:r?p.funcArgsToScVals(We,r):[]}),t.abrupt("return",de.buildWithOp(d,Ke(Ke({fee:u,timeoutInSeconds:c,simulate:l},f),{},{contractId:"ignored",method:We,parseResultXdr:function(t){return new e(p,Ke(Ke({},f),{},{contractId:n.Address.fromScVal(t).toString()}))}})));case 6:case"end":return t.stop()}}),t)}))),function(e,t){return a.apply(this,arguments)})},{key:"fromWasmHash",value:(i=Qe(Ve().mark((function t(r,n){var i,a,s,u,c,l,f=arguments;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i=f.length>2&&void 0!==f[2]?f[2]:"hex",n&&n.rpcUrl){t.next=3;break}throw new TypeError("options must contain rpcUrl");case 3:return a=n.rpcUrl,s=n.allowHttp,u={allowHttp:s},c=new o.Server(a,u),t.next=8,c.getContractWasmByHash(r,i);case 8:return l=t.sent,t.abrupt("return",e.fromWasm(l,n));case 10:case"end":return t.stop()}}),t)}))),function(e,t){return i.apply(this,arguments)})},{key:"fromWasm",value:(r=Qe(Ve().mark((function t(r,n){var o;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,Ye(r);case 2:return o=t.sent,t.abrupt("return",new e(o,n));case 4:case"end":return t.stop()}}),t)}))),function(e,t){return r.apply(this,arguments)})},{key:"from",value:(t=Qe(Ve().mark((function t(r){var n,i,a,s,u,c;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(r&&r.rpcUrl&&r.contractId){t.next=2;break}throw new TypeError("options must contain rpcUrl and contractId");case 2:return n=r.rpcUrl,i=r.contractId,a=r.allowHttp,s={allowHttp:a},u=new o.Server(n,s),t.next=7,u.getContractWasmByContractId(i);case 7:return c=t.sent,t.abrupt("return",e.fromWasm(c,r));case 9:case"end":return t.stop()}}),t)}))),function(e){return t.apply(this,arguments)})}]);var t,r,i,a}()},5976:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rH,v7:()=>x,nS:()=>L,Dr:()=>f,m_:()=>b});var f=function(e){function t(e,r){var n;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var o=(this instanceof t?this.constructor:void 0).prototype;return(n=a(this,t,[e])).__proto__=o,n.constructor=t,n.response=r,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&c(e,t)}(t,e),r=t,(n=[{key:"getResponse",value:function(){return this.response}}])&&o(r.prototype,n),i&&o(r,i),Object.defineProperty(r,"prototype",{writable:!1}),r;var r,n,i}(s(Error));function p(e){return p="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},p(e)}function d(e,t){for(var r=0;r{"use strict";r.r(t),r.d(t,{Api:()=>{},FEDERATION_RESPONSE_MAX_SIZE:()=>g,Server:()=>b});var n=r(356),o=r(4193),i=r.n(o),a=r(8732),s=r(5976),u=r(3898),c=r(9983);function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return p(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?p(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),I(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;I(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function h(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function y(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){h(i,n,o,a,s,"next",e)}function s(e){h(i,n,o,a,s,"throw",e)}a(void 0)}))}}function m(e,t){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.serverURL=i()(t),this.domain=r;var o=void 0===n.allowHttp?a.T.isAllowHttp():n.allowHttp;if(this.timeout=void 0===n.timeout?a.T.getTimeout():n.timeout,"https"!==this.serverURL.protocol()&&!o)throw new Error("Cannot connect to insecure federation server")}return t=e,r=[{key:"resolveAddress",value:(w=y(d().mark((function e(t){var r,n;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t,!(t.indexOf("*")<0)){e.next=5;break}if(this.domain){e.next=4;break}return e.abrupt("return",Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object.")));case 4:r="".concat(t,"*").concat(this.domain);case 5:return n=this.serverURL.query({type:"name",q:r}),e.abrupt("return",this._sendRequest(n));case 7:case"end":return e.stop()}}),e,this)}))),function(e){return w.apply(this,arguments)})},{key:"resolveAccountId",value:(b=y(d().mark((function e(t){var r;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.serverURL.query({type:"id",q:t}),e.abrupt("return",this._sendRequest(r));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return b.apply(this,arguments)})},{key:"resolveTransactionId",value:(v=y(d().mark((function e(t){var r;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.serverURL.query({type:"txid",q:t}),e.abrupt("return",this._sendRequest(r));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return v.apply(this,arguments)})},{key:"_sendRequest",value:(h=y(d().mark((function e(t){var r;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.timeout,e.abrupt("return",c.ok.get(t.toString(),{maxContentLength:g,timeout:r}).then((function(e){if(void 0!==e.data.memo&&"string"!=typeof e.data.memo)throw new Error("memo value should be of type string");return e.data})).catch((function(e){if(e instanceof Error){if(e.message.match(/^maxContentLength size/))throw new Error("federation response exceeds allowed size of ".concat(g));return Promise.reject(e)}return Promise.reject(new s.nS("Server query failed. Server responded: ".concat(e.status," ").concat(e.statusText),e.data))})));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return h.apply(this,arguments)})}],o=[{key:"resolve",value:(p=y(d().mark((function t(r){var o,i,a,s,u,c=arguments;return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(o=c.length>1&&void 0!==c[1]?c[1]:{},!(r.indexOf("*")<0)){t.next=5;break}if(n.StrKey.isValidEd25519PublicKey(r)){t.next=4;break}return t.abrupt("return",Promise.reject(new Error("Invalid Account ID")));case 4:return t.abrupt("return",Promise.resolve({account_id:r}));case 5:if(i=r.split("*"),a=f(i,2),s=a[1],2===i.length&&s){t.next=9;break}return t.abrupt("return",Promise.reject(new Error("Invalid Stellar address")));case 9:return t.next=11,e.createForDomain(s,o);case 11:return u=t.sent,t.abrupt("return",u.resolveAddress(r));case 13:case"end":return t.stop()}}),t)}))),function(e){return p.apply(this,arguments)})},{key:"createForDomain",value:(l=y(d().mark((function t(r){var n,o,i=arguments;return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=i.length>1&&void 0!==i[1]?i[1]:{},t.next=3,u.Resolver.resolve(r,n);case 3:if((o=t.sent).FEDERATION_SERVER){t.next=6;break}return t.abrupt("return",Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field")));case 6:return t.abrupt("return",new e(o.FEDERATION_SERVER,r,n));case 7:case"end":return t.stop()}}),t)}))),function(e){return l.apply(this,arguments)})}],r&&m(t.prototype,r),o&&m(t,o),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,o,l,p,h,v,b,w}()},8242:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Api:()=>{}})},8733:(e,t,r)=>{"use strict";var n;r.r(t),r.d(t,{AccountResponse:()=>m,AxiosClient:()=>$,HorizonApi:()=>n,SERVER_TIME_MAP:()=>z,Server:()=>Xr,ServerApi:()=>i,default:()=>Gr,getCurrentServerTime:()=>Q}),function(e){var t=function(e){return e.constantProduct="constant_product",e}({});e.LiquidityPoolType=t;var r=function(e){return e.createAccount="create_account",e.payment="payment",e.pathPayment="path_payment_strict_receive",e.createPassiveOffer="create_passive_sell_offer",e.manageOffer="manage_sell_offer",e.setOptions="set_options",e.changeTrust="change_trust",e.allowTrust="allow_trust",e.accountMerge="account_merge",e.inflation="inflation",e.manageData="manage_data",e.bumpSequence="bump_sequence",e.manageBuyOffer="manage_buy_offer",e.pathPaymentStrictSend="path_payment_strict_send",e.createClaimableBalance="create_claimable_balance",e.claimClaimableBalance="claim_claimable_balance",e.beginSponsoringFutureReserves="begin_sponsoring_future_reserves",e.endSponsoringFutureReserves="end_sponsoring_future_reserves",e.revokeSponsorship="revoke_sponsorship",e.clawback="clawback",e.clawbackClaimableBalance="clawback_claimable_balance",e.setTrustLineFlags="set_trust_line_flags",e.liquidityPoolDeposit="liquidity_pool_deposit",e.liquidityPoolWithdraw="liquidity_pool_withdraw",e.invokeHostFunction="invoke_host_function",e.bumpFootprintExpiration="bump_footprint_expiration",e.restoreFootprint="restore_footprint",e}({});e.OperationResponseType=r;var n=function(e){return e[e.createAccount=0]="createAccount",e[e.payment=1]="payment",e[e.pathPayment=2]="pathPayment",e[e.createPassiveOffer=3]="createPassiveOffer",e[e.manageOffer=4]="manageOffer",e[e.setOptions=5]="setOptions",e[e.changeTrust=6]="changeTrust",e[e.allowTrust=7]="allowTrust",e[e.accountMerge=8]="accountMerge",e[e.inflation=9]="inflation",e[e.manageData=10]="manageData",e[e.bumpSequence=11]="bumpSequence",e[e.manageBuyOffer=12]="manageBuyOffer",e[e.pathPaymentStrictSend=13]="pathPaymentStrictSend",e[e.createClaimableBalance=14]="createClaimableBalance",e[e.claimClaimableBalance=15]="claimClaimableBalance",e[e.beginSponsoringFutureReserves=16]="beginSponsoringFutureReserves",e[e.endSponsoringFutureReserves=17]="endSponsoringFutureReserves",e[e.revokeSponsorship=18]="revokeSponsorship",e[e.clawback=19]="clawback",e[e.clawbackClaimableBalance=20]="clawbackClaimableBalance",e[e.setTrustLineFlags=21]="setTrustLineFlags",e[e.liquidityPoolDeposit=22]="liquidityPoolDeposit",e[e.liquidityPoolWithdraw=23]="liquidityPoolWithdraw",e[e.invokeHostFunction=24]="invokeHostFunction",e[e.bumpFootprintExpiration=25]="bumpFootprintExpiration",e[e.restoreFootprint=26]="restoreFootprint",e}({});e.OperationResponseTypeI=n;var o=function(e){return e.TX_FAILED="tx_failed",e.TX_BAD_SEQ="tx_bad_seq",e.TX_BAD_AUTH="tx_bad_auth",e.TX_BAD_AUTH_EXTRA="tx_bad_auth_extra",e.TX_FEE_BUMP_INNER_SUCCESS="tx_fee_bump_inner_success",e.TX_FEE_BUMP_INNER_FAILED="tx_fee_bump_inner_failed",e.TX_NOT_SUPPORTED="tx_not_supported",e.TX_SUCCESS="tx_success",e.TX_TOO_EARLY="tx_too_early",e.TX_TOO_LATE="tx_too_late",e.TX_MISSING_OPERATION="tx_missing_operation",e.TX_INSUFFICIENT_BALANCE="tx_insufficient_balance",e.TX_NO_SOURCE_ACCOUNT="tx_no_source_account",e.TX_INSUFFICIENT_FEE="tx_insufficient_fee",e.TX_INTERNAL_ERROR="tx_internal_error",e}({});e.TransactionFailedResultCodes=o}(n||(n={}));var o,i,a=((o={})[o.account_created=0]="account_created",o[o.account_removed=1]="account_removed",o[o.account_credited=2]="account_credited",o[o.account_debited=3]="account_debited",o[o.account_thresholds_updated=4]="account_thresholds_updated",o[o.account_home_domain_updated=5]="account_home_domain_updated",o[o.account_flags_updated=6]="account_flags_updated",o[o.account_inflation_destination_updated=7]="account_inflation_destination_updated",o[o.signer_created=10]="signer_created",o[o.signer_removed=11]="signer_removed",o[o.signer_updated=12]="signer_updated",o[o.trustline_created=20]="trustline_created",o[o.trustline_removed=21]="trustline_removed",o[o.trustline_updated=22]="trustline_updated",o[o.trustline_authorized=23]="trustline_authorized",o[o.trustline_deauthorized=24]="trustline_deauthorized",o[o.trustline_authorized_to_maintain_liabilities=25]="trustline_authorized_to_maintain_liabilities",o[o.trustline_flags_updated=26]="trustline_flags_updated",o[o.offer_created=30]="offer_created",o[o.offer_removed=31]="offer_removed",o[o.offer_updated=32]="offer_updated",o[o.trade=33]="trade",o[o.data_created=40]="data_created",o[o.data_removed=41]="data_removed",o[o.data_updated=42]="data_updated",o[o.sequence_bumped=43]="sequence_bumped",o[o.claimable_balance_created=50]="claimable_balance_created",o[o.claimable_balance_claimant_created=51]="claimable_balance_claimant_created",o[o.claimable_balance_claimed=52]="claimable_balance_claimed",o[o.account_sponsorship_created=60]="account_sponsorship_created",o[o.account_sponsorship_updated=61]="account_sponsorship_updated",o[o.account_sponsorship_removed=62]="account_sponsorship_removed",o[o.trustline_sponsorship_created=63]="trustline_sponsorship_created",o[o.trustline_sponsorship_updated=64]="trustline_sponsorship_updated",o[o.trustline_sponsorship_removed=65]="trustline_sponsorship_removed",o[o.data_sponsorship_created=66]="data_sponsorship_created",o[o.data_sponsorship_updated=67]="data_sponsorship_updated",o[o.data_sponsorship_removed=68]="data_sponsorship_removed",o[o.claimable_balance_sponsorship_created=69]="claimable_balance_sponsorship_created",o[o.claimable_balance_sponsorship_updated=70]="claimable_balance_sponsorship_updated",o[o.claimable_balance_sponsorship_removed=71]="claimable_balance_sponsorship_removed",o[o.signer_sponsorship_created=72]="signer_sponsorship_created",o[o.signer_sponsorship_updated=73]="signer_sponsorship_updated",o[o.signer_sponsorship_removed=74]="signer_sponsorship_removed",o[o.claimable_balance_clawed_back=80]="claimable_balance_clawed_back",o[o.liquidity_pool_deposited=90]="liquidity_pool_deposited",o[o.liquidity_pool_withdrew=91]="liquidity_pool_withdrew",o[o.liquidity_pool_trade=92]="liquidity_pool_trade",o[o.liquidity_pool_created=93]="liquidity_pool_created",o[o.liquidity_pool_removed=94]="liquidity_pool_removed",o[o.liquidity_pool_revoked=95]="liquidity_pool_revoked",o[o.contract_credited=96]="contract_credited",o[o.contract_debited=97]="contract_debited",o);!function(e){e.EffectType=a;var t=function(e){return e.all="all",e.liquidityPools="liquidity_pool",e.orderbook="orderbook",e}({});e.TradeType=t;n.OperationResponseType,n.OperationResponseTypeI}(i||(i={}));var s=r(356);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return l(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?l(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r0||e===t?t:t-1}function P(e){for(var t,r,n=1,o=e.length,i=e[0]+"";nc^r?1:-1;for(s=(u=o.length)<(c=i.length)?u:c,a=0;ai[a]^r?1:-1;return u==c?0:u>c^r?1:-1}function I(e,t,r,n){if(er||e!==b(e))throw Error(w+(n||"Argument")+("number"==typeof e?er?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function C(e){var t=e.c.length-1;return A(e.e/E)==t&&e.c[t]%2!=0}function j(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function B(e,t,r){var n,o;if(t<0){for(o=r+".";++t;o+=r);e=o+e}else if(++t>(n=e.length)){for(o=r,t-=n;--t;o+=r);e+=o}else tU?p.c=p.e=null:e.e=10;u/=10,s++);return void(s>U?p.c=p.e=null:(p.e=s,p.c=[e]))}f=String(e)}else{if(!v.test(f=String(e)))return o(p,f,c);p.s=45==f.charCodeAt(0)?(f=f.slice(1),-1):1}(s=f.indexOf("."))>-1&&(f=f.replace(".","")),(u=f.search(/e/i))>0?(s<0&&(s=u),s+=+f.slice(u+1),f=f.substring(0,u)):s<0&&(s=f.length)}else{if(I(t,2,q.length,"Base"),10==t&&K)return $(p=new H(e),h+p.e+1,y);if(f=String(e),c="number"==typeof e){if(0*e!=0)return o(p,f,c,t);if(p.s=1/e<0?(f=f.slice(1),-1):1,H.DEBUG&&f.replace(/^0\.0*|\./,"").length>15)throw Error(S+e)}else p.s=45===f.charCodeAt(0)?(f=f.slice(1),-1):1;for(r=q.slice(0,t),s=u=0,l=f.length;us){s=l;continue}}else if(!a&&(f==f.toUpperCase()&&(f=f.toLowerCase())||f==f.toLowerCase()&&(f=f.toUpperCase()))){a=!0,u=-1,s=0;continue}return o(p,String(e),c,t)}c=!1,(s=(f=n(f,t,10,p.s)).indexOf("."))>-1?f=f.replace(".",""):s=f.length}for(u=0;48===f.charCodeAt(u);u++);for(l=f.length;48===f.charCodeAt(--l););if(f=f.slice(u,++l)){if(l-=u,c&&H.DEBUG&&l>15&&(e>T||e!==b(e)))throw Error(S+p.s*e);if((s=s-u-1)>U)p.c=p.e=null;else if(s=L)?j(u,a):B(u,a,"0");else if(i=(e=$(new H(e),t,r)).e,s=(u=P(e.c)).length,1==n||2==n&&(t<=i||i<=m)){for(;ss){if(--t>0)for(u+=".";t--;u+="0");}else if((t+=i-s)>0)for(i+1==s&&(u+=".");t--;u+="0");return e.s<0&&o?"-"+u:u}function X(e,t){for(var r,n,o=1,i=new H(e[0]);o=10;o/=10,n++);return(r=n+r*E-1)>U?e.c=e.e=null:r=10;s/=10,o++);if((i=t-o)<0)i+=E,a=t,u=f[c=0],l=b(u/p[o-a-1]%10);else if((c=g((i+1)/E))>=f.length){if(!n)break e;for(;f.length<=c;f.push(0));u=l=0,o=1,a=(i%=E)-E+1}else{for(u=s=f[c],o=1;s>=10;s/=10,o++);l=(a=(i%=E)-E+o)<0?0:b(u/p[o-a-1]%10)}if(n=n||t<0||null!=f[c+1]||(a<0?u:u%p[o-a-1]),n=r<4?(l||n)&&(0==r||r==(e.s<0?3:2)):l>5||5==l&&(4==r||n||6==r&&(i>0?a>0?u/p[o-a]:0:f[c-1])%10&1||r==(e.s<0?8:7)),t<1||!f[0])return f.length=0,n?(t-=e.e+1,f[0]=p[(E-t%E)%E],e.e=-t||0):f[0]=e.e=0,e;if(0==i?(f.length=c,s=1,c--):(f.length=c+1,s=p[E-i],f[c]=a>0?b(u/p[o-a]%p[a])*s:0),n)for(;;){if(0==c){for(i=1,a=f[0];a>=10;a/=10,i++);for(a=f[0]+=s,s=1;a>=10;a/=10,s++);i!=s&&(e.e++,f[0]==k&&(f[0]=1));break}if(f[c]+=s,f[c]!=k)break;f[c--]=0,s=1}for(i=f.length;0===f[--i];f.pop());}e.e>U?e.c=e.e=null:e.e=L?j(t,r):B(t,r,"0"),e.s<0?"-"+t:t)}return H.clone=e,H.ROUND_UP=0,H.ROUND_DOWN=1,H.ROUND_CEIL=2,H.ROUND_FLOOR=3,H.ROUND_HALF_UP=4,H.ROUND_HALF_DOWN=5,H.ROUND_HALF_EVEN=6,H.ROUND_HALF_CEIL=7,H.ROUND_HALF_FLOOR=8,H.EUCLID=9,H.config=H.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(w+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(I(r=e[t],0,x,t),h=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(I(r=e[t],0,8,t),y=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(I(r[0],-x,0,t),I(r[1],0,x,t),m=r[0],L=r[1]):(I(r,-x,x,t),m=-(L=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)I(r[0],-x,-1,t),I(r[1],1,x,t),N=r[0],U=r[1];else{if(I(r,-x,x,t),!r)throw Error(w+t+" cannot be zero: "+r);N=-(U=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(w+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw M=!r,Error(w+"crypto unavailable");M=r}else M=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(I(r=e[t],0,9,t),F=r),e.hasOwnProperty(t="POW_PRECISION")&&(I(r=e[t],0,x,t),D=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(w+t+" not an object: "+r);V=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(w+t+" invalid: "+r);K="0123456789"==r.slice(0,10),q=r}}return{DECIMAL_PLACES:h,ROUNDING_MODE:y,EXPONENTIAL_AT:[m,L],RANGE:[N,U],CRYPTO:M,MODULO_MODE:F,POW_PRECISION:D,FORMAT:V,ALPHABET:q}},H.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!H.DEBUG)return!0;var t,r,n=e.c,o=e.e,i=e.s;e:if("[object Array]"=={}.toString.call(n)){if((1===i||-1===i)&&o>=-x&&o<=x&&o===b(o)){if(0===n[0]){if(0===o&&1===n.length)return!0;break e}if((t=(o+1)%E)<1&&(t+=E),String(n[0]).length==t){for(t=0;t=k||r!==b(r))break e;if(0!==r)return!0}}}else if(null===n&&null===o&&(null===i||1===i||-1===i))return!0;throw Error(w+"Invalid BigNumber: "+e)},H.maximum=H.max=function(){return X(arguments,-1)},H.minimum=H.min=function(){return X(arguments,1)},H.random=(i=9007199254740992,a=Math.random()*i&2097151?function(){return b(Math.random()*i)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,n,o,i,s=0,u=[],c=new H(d);if(null==e?e=h:I(e,0,x),o=g(e/E),M)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(o*=2));s>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[s]=r[0],t[s+1]=r[1]):(u.push(i%1e14),s+=2);s=o/2}else{if(!crypto.randomBytes)throw M=!1,Error(w+"crypto unavailable");for(t=crypto.randomBytes(o*=7);s=9e15?crypto.randomBytes(7).copy(t,s):(u.push(i%1e14),s+=7);s=o/7}if(!M)for(;s=10;i/=10,s++);sr-1&&(null==a[o+1]&&(a[o+1]=0),a[o+1]+=a[o]/r|0,a[o]%=r)}return a.reverse()}return function(n,o,i,a,s){var u,c,l,f,p,d,m,v,g=n.indexOf("."),b=h,w=y;for(g>=0&&(f=D,D=0,n=n.replace(".",""),d=(v=new H(o)).pow(n.length-g),D=f,v.c=t(B(P(d.c),d.e,"0"),10,i,e),v.e=v.c.length),l=f=(m=t(n,o,i,s?(u=q,e):(u=e,q))).length;0==m[--f];m.pop());if(!m[0])return u.charAt(0);if(g<0?--l:(d.c=m,d.e=l,d.s=a,m=(d=r(d,v,b,w,i)).c,p=d.r,l=d.e),g=m[c=l+b+1],f=i/2,p=p||c<0||null!=m[c+1],p=w<4?(null!=g||p)&&(0==w||w==(d.s<0?3:2)):g>f||g==f&&(4==w||p||6==w&&1&m[c-1]||w==(d.s<0?8:7)),c<1||!m[0])n=p?B(u.charAt(1),-b,u.charAt(0)):u.charAt(0);else{if(m.length=c,p)for(--i;++m[--c]>i;)m[c]=0,c||(++l,m=[1].concat(m));for(f=m.length;!m[--f];);for(g=0,n="";g<=f;n+=u.charAt(m[g++]));n=B(n,l,u.charAt(0))}return n}}(),r=function(){function e(e,t,r){var n,o,i,a,s=0,u=e.length,c=t%O,l=t/O|0;for(e=e.slice();u--;)s=((o=c*(i=e[u]%O)+(n=l*i+(a=e[u]/O|0)*c)%O*O+s)/r|0)+(n/O|0)+l*a,e[u]=o%r;return s&&(e=[s].concat(e)),e}function t(e,t,r,n){var o,i;if(r!=n)i=r>n?1:-1;else for(o=i=0;ot[o]?1:-1;break}return i}function r(e,t,r,n){for(var o=0;r--;)e[r]-=o,o=e[r]1;e.splice(0,1));}return function(n,o,i,a,s){var u,c,l,f,p,d,h,y,m,v,g,w,S,T,_,O,x,P=n.s==o.s?1:-1,R=n.c,I=o.c;if(!(R&&R[0]&&I&&I[0]))return new H(n.s&&o.s&&(R?!I||R[0]!=I[0]:I)?R&&0==R[0]||!I?0*P:P/0:NaN);for(m=(y=new H(P)).c=[],P=i+(c=n.e-o.e)+1,s||(s=k,c=A(n.e/E)-A(o.e/E),P=P/E|0),l=0;I[l]==(R[l]||0);l++);if(I[l]>(R[l]||0)&&c--,P<0)m.push(1),f=!0;else{for(T=R.length,O=I.length,l=0,P+=2,(p=b(s/(I[0]+1)))>1&&(I=e(I,p,s),R=e(R,p,s),O=I.length,T=R.length),S=O,g=(v=R.slice(0,O)).length;g=s/2&&_++;do{if(p=0,(u=t(I,v,O,g))<0){if(w=v[0],O!=g&&(w=w*s+(v[1]||0)),(p=b(w/_))>1)for(p>=s&&(p=s-1),h=(d=e(I,p,s)).length,g=v.length;1==t(d,v,h,g);)p--,r(d,O=10;P/=10,l++);$(y,i+(y.e=l+c*E-1)+1,a,f)}else y.e=c,y.r=+f;return y}}(),s=/^(-?)0([xbo])(?=\w[\w.]*$)/i,u=/^([^.]+)\.$/,c=/^\.([^.]+)$/,l=/^-?(Infinity|NaN)$/,f=/^\s*\+(?=[\w.])|^\s+|\s+$/g,o=function(e,t,r,n){var o,i=r?t:t.replace(f,"");if(l.test(i))e.s=isNaN(i)?null:i<0?-1:1;else{if(!r&&(i=i.replace(s,(function(e,t,r){return o="x"==(r=r.toLowerCase())?16:"b"==r?2:8,n&&n!=o?e:t})),n&&(o=n,i=i.replace(u,"$1").replace(c,"0.$1")),t!=i))return new H(i,o);if(H.DEBUG)throw Error(w+"Not a"+(n?" base "+n:"")+" number: "+t);e.s=null}e.c=e.e=null},p.absoluteValue=p.abs=function(){var e=new H(this);return e.s<0&&(e.s=1),e},p.comparedTo=function(e,t){return R(this,new H(e,t))},p.decimalPlaces=p.dp=function(e,t){var r,n,o,i=this;if(null!=e)return I(e,0,x),null==t?t=y:I(t,0,8),$(new H(i),e+i.e+1,t);if(!(r=i.c))return null;if(n=((o=r.length-1)-A(this.e/E))*E,o=r[o])for(;o%10==0;o/=10,n--);return n<0&&(n=0),n},p.dividedBy=p.div=function(e,t){return r(this,new H(e,t),h,y)},p.dividedToIntegerBy=p.idiv=function(e,t){return r(this,new H(e,t),0,1)},p.exponentiatedBy=p.pow=function(e,t){var r,n,o,i,a,s,u,c,l=this;if((e=new H(e)).c&&!e.isInteger())throw Error(w+"Exponent not an integer: "+Q(e));if(null!=t&&(t=new H(t)),a=e.e>14,!l.c||!l.c[0]||1==l.c[0]&&!l.e&&1==l.c.length||!e.c||!e.c[0])return c=new H(Math.pow(+Q(l),a?e.s*(2-C(e)):+Q(e))),t?c.mod(t):c;if(s=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new H(NaN);(n=!s&&l.isInteger()&&t.isInteger())&&(l=l.mod(t))}else{if(e.e>9&&(l.e>0||l.e<-1||(0==l.e?l.c[0]>1||a&&l.c[1]>=24e7:l.c[0]<8e13||a&&l.c[0]<=9999975e7)))return i=l.s<0&&C(e)?-0:0,l.e>-1&&(i=1/i),new H(s?1/i:i);D&&(i=g(D/E+2))}for(a?(r=new H(.5),s&&(e.s=1),u=C(e)):u=(o=Math.abs(+Q(e)))%2,c=new H(d);;){if(u){if(!(c=c.times(l)).c)break;i?c.c.length>i&&(c.c.length=i):n&&(c=c.mod(t))}if(o){if(0===(o=b(o/2)))break;u=o%2}else if($(e=e.times(r),e.e+1,1),e.e>14)u=C(e);else{if(0===(o=+Q(e)))break;u=o%2}l=l.times(l),i?l.c&&l.c.length>i&&(l.c.length=i):n&&(l=l.mod(t))}return n?c:(s&&(c=d.div(c)),t?c.mod(t):i?$(c,D,y,undefined):c)},p.integerValue=function(e){var t=new H(this);return null==e?e=y:I(e,0,8),$(t,t.e+1,e)},p.isEqualTo=p.eq=function(e,t){return 0===R(this,new H(e,t))},p.isFinite=function(){return!!this.c},p.isGreaterThan=p.gt=function(e,t){return R(this,new H(e,t))>0},p.isGreaterThanOrEqualTo=p.gte=function(e,t){return 1===(t=R(this,new H(e,t)))||0===t},p.isInteger=function(){return!!this.c&&A(this.e/E)>this.c.length-2},p.isLessThan=p.lt=function(e,t){return R(this,new H(e,t))<0},p.isLessThanOrEqualTo=p.lte=function(e,t){return-1===(t=R(this,new H(e,t)))||0===t},p.isNaN=function(){return!this.s},p.isNegative=function(){return this.s<0},p.isPositive=function(){return this.s>0},p.isZero=function(){return!!this.c&&0==this.c[0]},p.minus=function(e,t){var r,n,o,i,a=this,s=a.s;if(t=(e=new H(e,t)).s,!s||!t)return new H(NaN);if(s!=t)return e.s=-t,a.plus(e);var u=a.e/E,c=e.e/E,l=a.c,f=e.c;if(!u||!c){if(!l||!f)return l?(e.s=-t,e):new H(f?a:NaN);if(!l[0]||!f[0])return f[0]?(e.s=-t,e):new H(l[0]?a:3==y?-0:0)}if(u=A(u),c=A(c),l=l.slice(),s=u-c){for((i=s<0)?(s=-s,o=l):(c=u,o=f),o.reverse(),t=s;t--;o.push(0));o.reverse()}else for(n=(i=(s=l.length)<(t=f.length))?s:t,s=t=0;t0)for(;t--;l[r++]=0);for(t=k-1;n>s;){if(l[--n]=0;){for(r=0,p=b[o]%m,d=b[o]/m|0,i=o+(a=u);i>o;)r=((c=p*(c=g[--a]%m)+(s=d*c+(l=g[a]/m|0)*p)%m*m+h[i]+r)/y|0)+(s/m|0)+d*l,h[i--]=c%y;h[i]=r}return r?++n:h.splice(0,1),G(e,h,n)},p.negated=function(){var e=new H(this);return e.s=-e.s||null,e},p.plus=function(e,t){var r,n=this,o=n.s;if(t=(e=new H(e,t)).s,!o||!t)return new H(NaN);if(o!=t)return e.s=-t,n.minus(e);var i=n.e/E,a=e.e/E,s=n.c,u=e.c;if(!i||!a){if(!s||!u)return new H(o/0);if(!s[0]||!u[0])return u[0]?e:new H(s[0]?n:0*o)}if(i=A(i),a=A(a),s=s.slice(),o=i-a){for(o>0?(a=i,r=u):(o=-o,r=s),r.reverse();o--;r.push(0));r.reverse()}for((o=s.length)-(t=u.length)<0&&(r=u,u=s,s=r,t=o),o=0;t;)o=(s[--t]=s[t]+u[t]+o)/k|0,s[t]=k===s[t]?0:s[t]%k;return o&&(s=[o].concat(s),++a),G(e,s,a)},p.precision=p.sd=function(e,t){var r,n,o,i=this;if(null!=e&&e!==!!e)return I(e,1,x),null==t?t=y:I(t,0,8),$(new H(i),e,t);if(!(r=i.c))return null;if(n=(o=r.length-1)*E+1,o=r[o]){for(;o%10==0;o/=10,n--);for(o=r[0];o>=10;o/=10,n++);}return e&&i.e+1>n&&(n=i.e+1),n},p.shiftedBy=function(e){return I(e,-9007199254740991,T),this.times("1e"+e)},p.squareRoot=p.sqrt=function(){var e,t,n,o,i,a=this,s=a.c,u=a.s,c=a.e,l=h+4,f=new H("0.5");if(1!==u||!s||!s[0])return new H(!u||u<0&&(!s||s[0])?NaN:s?a:1/0);if(0==(u=Math.sqrt(+Q(a)))||u==1/0?(((t=P(s)).length+c)%2==0&&(t+="0"),u=Math.sqrt(+t),c=A((c+1)/2)-(c<0||c%2),n=new H(t=u==1/0?"5e"+c:(t=u.toExponential()).slice(0,t.indexOf("e")+1)+c)):n=new H(u+""),n.c[0])for((u=(c=n.e)+l)<3&&(u=0);;)if(i=n,n=f.times(i.plus(r(a,i,l,1))),P(i.c).slice(0,u)===(t=P(n.c)).slice(0,u)){if(n.e0&&h>0){for(i=h%s||s,l=d.substr(0,i);i0&&(l+=c+d.slice(i)),p&&(l="-"+l)}n=f?l+(r.decimalSeparator||"")+((u=+r.fractionGroupSize)?f.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):f):l}return(r.prefix||"")+n+(r.suffix||"")},p.toFraction=function(e){var t,n,o,i,a,s,u,c,l,f,p,h,m=this,v=m.c;if(null!=e&&(!(u=new H(e)).isInteger()&&(u.c||1!==u.s)||u.lt(d)))throw Error(w+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+Q(u));if(!v)return new H(m);for(t=new H(d),l=n=new H(d),o=c=new H(d),h=P(v),a=t.e=h.length-m.e-1,t.c[0]=_[(s=a%E)<0?E+s:s],e=!e||u.comparedTo(t)>0?a>0?t:l:u,s=U,U=1/0,u=new H(h),c.c[0]=0;f=r(u,t,0,1),1!=(i=n.plus(f.times(o))).comparedTo(e);)n=o,o=i,l=c.plus(f.times(i=l)),c=i,t=u.minus(f.times(i=t)),u=i;return i=r(e.minus(n),o,0,1),c=c.plus(i.times(l)),n=n.plus(i.times(o)),c.s=l.s=m.s,p=r(l,o,a*=2,y).minus(m).abs().comparedTo(r(c,n,a,y).minus(m).abs())<1?[l,o]:[c,n],U=s,p},p.toNumber=function(){return+Q(this)},p.toPrecision=function(e,t){return null!=e&&I(e,1,x),z(this,e,t,2)},p.toString=function(e){var t,r=this,o=r.s,i=r.e;return null===i?o?(t="Infinity",o<0&&(t="-"+t)):t="NaN":(null==e?t=i<=m||i>=L?j(P(r.c),i):B(P(r.c),i,"0"):10===e&&K?t=B(P((r=$(new H(r),h+i+1,y)).c),r.e,"0"):(I(e,2,q.length,"Base"),t=n(B(P(r.c),i,"0"),10,e,o,!0)),o<0&&r.c[0]&&(t="-"+t)),t},p.valueOf=p.toJSON=function(){return Q(this)},p._isBigNumber=!0,p[Symbol.toStringTag]="BigNumber",p[Symbol.for("nodejs.util.inspect.custom")]=p.valueOf,null!=t&&H.set(t),H}();const N=L;var U=r(4193),M=r.n(U),F=r(9127),D=r.n(F),V=r(5976),q=r(9983);function K(e){return K="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},K(e)}var H="13.1.0",z={},X=(0,q.vt)({headers:{"X-Client-Name":"js-stellar-sdk","X-Client-Version":H}});function G(e){return Math.floor(e/1e3)}X.interceptors.response.use((function(e){var t=M()(e.config.url).hostname(),r=0;if(e.headers instanceof Headers){var n=e.headers.get("date");n&&(r=G(Date.parse(n)))}else if("object"===K(e.headers)&&"date"in e.headers){var o=e.headers;"string"==typeof o.date&&(r=G(Date.parse(o.date)))}var i=G((new Date).getTime());return Number.isNaN(r)||(z[t]={serverTime:r,localTimeRecorded:i}),e}));const $=X;function Q(e){var t=z[e];if(!t||!t.localTimeRecorded||!t.serverTime)return null;var r=t.serverTime,n=t.localTimeRecorded,o=G((new Date).getTime());return o-n>300?null:o-n+r}function W(e){return W="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},W(e)}function Y(){Y=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,k=S&&S(S(I([])));k&&k!==r&&n.call(k,a)&&(w=k);var E=b.prototype=v.prototype=Object.create(w);function T(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function _(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==W(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function I(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:I(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function J(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function Z(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){J(i,n,o,a,s,"next",e)}function s(e){J(i,n,o,a,s,"throw",e)}a(void 0)}))}}function ee(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:"";!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.url=t.clone(),this.filter=[],this.originalSegments=this.url.segment()||[],this.neighborRoot=r}),[{key:"call",value:function(){var e=this;return this.checkFilter(),this._sendNormalRequest(this.url).then((function(t){return e._parseResponse(t)}))}},{key:"stream",value:function(){throw new Error("Streaming requires eventsource to be enabled. If you need this functionality, compile with USE_EVENTSOURCE=true.")}},{key:"cursor",value:function(e){return this.url.setQuery("cursor",e),this}},{key:"limit",value:function(e){return this.url.setQuery("limit",e.toString()),this}},{key:"order",value:function(e){return this.url.setQuery("order",e),this}},{key:"join",value:function(e){return this.url.setQuery("join",e),this}},{key:"forEndpoint",value:function(e,t){if(""===this.neighborRoot)throw new Error("Invalid usage: neighborRoot not set in constructor");return this.filter.push([e,t,this.neighborRoot]),this}},{key:"checkFilter",value:function(){if(this.filter.length>=2)throw new V.v7("Too many filters specified",this.filter);if(1===this.filter.length){var e=this.originalSegments.concat(this.filter[0]);this.url.segment(e)}}},{key:"_requestFnForLink",value:function(e){var t=this;return Z(Y().mark((function r(){var n,o,i,a,s=arguments;return Y().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return n=s.length>0&&void 0!==s[0]?s[0]:{},e.templated?(i=D()(e.href),o=M()(i.expand(n))):o=M()(e.href),r.next=4,t._sendNormalRequest(o);case 4:return a=r.sent,r.abrupt("return",t._parseResponse(a));case 6:case"end":return r.stop()}}),r)})))}},{key:"_parseRecord",value:function(e){var t=this;return e._links?(Object.keys(e._links).forEach((function(r){var n=e._links[r],o=!1;if(void 0!==e[r]&&(e["".concat(r,"_attr")]=e[r],o=!0),o&&oe.indexOf(r)>=0){var i=t._parseRecord(e[r]);e[r]=Z(Y().mark((function e(){return Y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",i);case 1:case"end":return e.stop()}}),e)})))}else e[r]=t._requestFnForLink(n)})),e):e}},{key:"_sendNormalRequest",value:(ne=Z(Y().mark((function e(t){var r;return Y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return""===(r=t).authority()&&(r=r.authority(this.url.authority())),""===r.protocol()&&(r=r.protocol(this.url.protocol())),e.abrupt("return",X.get(r.toString()).then((function(e){return e.data})).catch(this._handleNetworkError));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return ne.apply(this,arguments)})},{key:"_parseResponse",value:function(e){return e._embedded&&e._embedded.records?this._toCollectionPage(e):this._parseRecord(e)}},{key:"_toCollectionPage",value:function(e){for(var t,r,n=this,o=0;ot||e>=24*r||e%r!=0)}}])}(ie);function pr(e){return pr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},pr(e)}function dr(e,t){for(var r=0;r=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:I(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function jr(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function Br(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){jr(i,n,o,a,s,"next",e)}function s(e){jr(i,n,o,a,s,"throw",e)}a(void 0)}))}}function Lr(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.serverURL=M()(t);var n=void 0===r.allowHttp?ae.T.isAllowHttp():r.allowHttp,o={};if(r.appName&&(o["X-App-Name"]=r.appName),r.appVersion&&(o["X-App-Version"]=r.appVersion),r.authToken&&(o["X-Auth-Token"]=r.authToken),r.headers&&Object.assign(o,r.headers),Object.keys(o).length>0&&$.interceptors.request.use((function(e){return e.headers=e.headers||{},e.headers=Object.assign(e.headers,o),e})),"https"!==this.serverURL.protocol()&&!n)throw new Error("Cannot connect to insecure horizon server")}),[{key:"fetchTimebounds",value:(zr=Br(Cr().mark((function e(t){var r,n,o=arguments;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=o.length>1&&void 0!==o[1]&&o[1],!(n=Q(this.serverURL.hostname()))){e.next=4;break}return e.abrupt("return",{minTime:0,maxTime:n+t});case 4:if(!r){e.next=6;break}return e.abrupt("return",{minTime:0,maxTime:Math.floor((new Date).getTime()/1e3)+t});case 6:return e.next=8,$.get(M()(this.serverURL).toString());case 8:return e.abrupt("return",this.fetchTimebounds(t,!0));case 9:case"end":return e.stop()}}),e,this)}))),function(e){return zr.apply(this,arguments)})},{key:"fetchBaseFee",value:(Hr=Br(Cr().mark((function e(){var t;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.feeStats();case 2:return t=e.sent,e.abrupt("return",parseInt(t.last_ledger_base_fee,10)||100);case 4:case"end":return e.stop()}}),e,this)}))),function(){return Hr.apply(this,arguments)})},{key:"feeStats",value:(Kr=Br(Cr().mark((function e(){var t;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(t=new ie(M()(this.serverURL))).filter.push(["fee_stats"]),e.abrupt("return",t.call());case 3:case"end":return e.stop()}}),e,this)}))),function(){return Kr.apply(this,arguments)})},{key:"root",value:(qr=Br(Cr().mark((function e(){var t;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=new ie(M()(this.serverURL)),e.abrupt("return",t.call());case 2:case"end":return e.stop()}}),e,this)}))),function(){return qr.apply(this,arguments)})},{key:"submitTransaction",value:(Vr=Br(Cr().mark((function e(t){var r,n=arguments;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((n.length>1&&void 0!==n[1]?n[1]:{skipMemoRequiredCheck:!1}).skipMemoRequiredCheck){e.next=4;break}return e.next=4,this.checkMemoRequired(t);case 4:return r=encodeURIComponent(t.toEnvelope().toXDR().toString("base64")),e.abrupt("return",$.post(M()(this.serverURL).segment("transactions").toString(),"tx=".concat(r),{timeout:6e4}).then((function(e){if(!e.data.result_xdr)return e.data;var t,r,n=s.xdr.TransactionResult.fromXDR(e.data.result_xdr,"base64").result().value();return n.length&&(t=n.map((function(e,t){if("manageBuyOffer"!==e.value().switch().name&&"manageSellOffer"!==e.value().switch().name)return null;r=!0;var n,o=new N(0),i=new N(0),a=e.value().value().success(),u=a.offersClaimed().map((function(e){var t=e.value(),r="";switch(e.switch()){case s.xdr.ClaimAtomType.claimAtomTypeV0():r=s.StrKey.encodeEd25519PublicKey(t.sellerEd25519());break;case s.xdr.ClaimAtomType.claimAtomTypeOrderBook():r=s.StrKey.encodeEd25519PublicKey(t.sellerId().ed25519());break;default:throw new Error("Invalid offer result type: ".concat(e.switch()))}var n=new N(t.amountBought().toString()),a=new N(t.amountSold().toString());o=o.plus(a),i=i.plus(n);var u=s.Asset.fromOperation(t.assetSold()),c=s.Asset.fromOperation(t.assetBought()),l={type:u.getAssetType(),assetCode:u.getCode(),issuer:u.getIssuer()},f={type:c.getAssetType(),assetCode:c.getCode(),issuer:c.getIssuer()};return{sellerId:r,offerId:t.offerId().toString(),assetSold:l,amountSold:Ur(a),assetBought:f,amountBought:Ur(n)}})),c=a.offer().switch().name;if("function"==typeof a.offer().value&&a.offer().value()){var l=a.offer().value();n={offerId:l.offerId().toString(),selling:{},buying:{},amount:Ur(l.amount().toString()),price:{n:l.price().n(),d:l.price().d()}};var f=s.Asset.fromOperation(l.selling());n.selling={type:f.getAssetType(),assetCode:f.getCode(),issuer:f.getIssuer()};var p=s.Asset.fromOperation(l.buying());n.buying={type:p.getAssetType(),assetCode:p.getCode(),issuer:p.getIssuer()}}return{offersClaimed:u,effect:c,operationIndex:t,currentOffer:n,amountBought:Ur(o),amountSold:Ur(i),isFullyOpen:!u.length&&"manageOfferDeleted"!==c,wasPartiallyFilled:!!u.length&&"manageOfferDeleted"!==c,wasImmediatelyFilled:!!u.length&&"manageOfferDeleted"===c,wasImmediatelyDeleted:!u.length&&"manageOfferDeleted"===c}})).filter((function(e){return!!e}))),Rr(Rr({},e.data),{},{offerResults:r?t:void 0})})).catch((function(e){return e instanceof Error?Promise.reject(e):Promise.reject(new V.nS("Transaction submission failed. Server responded: ".concat(e.status," ").concat(e.statusText),e.data))})));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return Vr.apply(this,arguments)})},{key:"submitAsyncTransaction",value:(Dr=Br(Cr().mark((function e(t){var r,n=arguments;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((n.length>1&&void 0!==n[1]?n[1]:{skipMemoRequiredCheck:!1}).skipMemoRequiredCheck){e.next=4;break}return e.next=4,this.checkMemoRequired(t);case 4:return r=encodeURIComponent(t.toEnvelope().toXDR().toString("base64")),e.abrupt("return",$.post(M()(this.serverURL).segment("transactions_async").toString(),"tx=".concat(r)).then((function(e){return e.data})).catch((function(e){return e instanceof Error?Promise.reject(e):Promise.reject(new V.nS("Transaction submission failed. Server responded: ".concat(e.status," ").concat(e.statusText),e.data))})));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return Dr.apply(this,arguments)})},{key:"accounts",value:function(){return new he(M()(this.serverURL))}},{key:"claimableBalances",value:function(){return new Re(M()(this.serverURL))}},{key:"ledgers",value:function(){return new et(M()(this.serverURL))}},{key:"transactions",value:function(){return new xr(M()(this.serverURL))}},{key:"offers",value:function(){return new mt(M()(this.serverURL))}},{key:"orderbook",value:function(e,t){return new Ct(M()(this.serverURL),e,t)}},{key:"trades",value:function(){return new br(M()(this.serverURL))}},{key:"operations",value:function(){return new Tt(M()(this.serverURL))}},{key:"liquidityPools",value:function(){return new ut(M()(this.serverURL))}},{key:"strictReceivePaths",value:function(e,t,r){return new $t(M()(this.serverURL),e,t,r)}},{key:"strictSendPaths",value:function(e,t,r){return new rr(M()(this.serverURL),e,t,r)}},{key:"payments",value:function(){return new Dt(M()(this.serverURL))}},{key:"effects",value:function(){return new Me(M()(this.serverURL))}},{key:"friendbot",value:function(e){return new Xe(M()(this.serverURL),e)}},{key:"assets",value:function(){return new ke(M()(this.serverURL))}},{key:"loadAccount",value:(Fr=Br(Cr().mark((function e(t){var r;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.accounts().accountId(t).call();case 2:return r=e.sent,e.abrupt("return",new m(r));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return Fr.apply(this,arguments)})},{key:"tradeAggregation",value:function(e,t,r,n,o,i){return new fr(M()(this.serverURL),e,t,r,n,o,i)}},{key:"checkMemoRequired",value:(Mr=Br(Cr().mark((function e(t){var r,n,o,i;return Cr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t instanceof s.FeeBumpTransaction&&(t=t.innerTransaction),"none"===t.memo.type){e.next=3;break}return e.abrupt("return");case 3:r=new Set,n=0;case 5:if(!(n{"use strict";r.r(t),r.d(t,{axiosClient:()=>_t,create:()=>Ot});var n={};function o(e,t){return function(){return e.apply(t,arguments)}}r.r(n),r.d(n,{hasBrowserEnv:()=>he,hasStandardBrowserEnv:()=>me,hasStandardBrowserWebWorkerEnv:()=>ve,navigator:()=>ye,origin:()=>ge});const{toString:i}=Object.prototype,{getPrototypeOf:a}=Object,s=(u=Object.create(null),e=>{const t=i.call(e);return u[t]||(u[t]=t.slice(8,-1).toLowerCase())});var u;const c=e=>(e=e.toLowerCase(),t=>s(t)===e),l=e=>t=>typeof t===e,{isArray:f}=Array,p=l("undefined");const d=c("ArrayBuffer");const h=l("string"),y=l("function"),m=l("number"),v=e=>null!==e&&"object"==typeof e,g=e=>{if("object"!==s(e))return!1;const t=a(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},b=c("Date"),w=c("File"),S=c("Blob"),k=c("FileList"),E=c("URLSearchParams"),[T,_,O,x]=["ReadableStream","Request","Response","Headers"].map(c);function A(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,o;if("object"!=typeof e&&(e=[e]),f(e))for(n=0,o=e.length;n0;)if(n=r[o],t===n.toLowerCase())return n;return null}const R="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,I=e=>!p(e)&&e!==R;const C=(j="undefined"!=typeof Uint8Array&&a(Uint8Array),e=>j&&e instanceof j);var j;const B=c("HTMLFormElement"),L=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),N=c("RegExp"),U=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};A(r,((r,o)=>{let i;!1!==(i=t(r,o,e))&&(n[o]=i||r)})),Object.defineProperties(e,n)},M="abcdefghijklmnopqrstuvwxyz",F="0123456789",D={DIGIT:F,ALPHA:M,ALPHA_DIGIT:M+M.toUpperCase()+F};const V=c("AsyncFunction"),q=(K="function"==typeof setImmediate,H=y(R.postMessage),K?setImmediate:H?(z=`axios@${Math.random()}`,X=[],R.addEventListener("message",(({source:e,data:t})=>{e===R&&t===z&&X.length&&X.shift()()}),!1),e=>{X.push(e),R.postMessage(z,"*")}):e=>setTimeout(e));var K,H,z,X;const G="undefined"!=typeof queueMicrotask?queueMicrotask.bind(R):"undefined"!=typeof process&&process.nextTick||q,$={isArray:f,isArrayBuffer:d,isBuffer:function(e){return null!==e&&!p(e)&&null!==e.constructor&&!p(e.constructor)&&y(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||y(e.append)&&("formdata"===(t=s(e))||"object"===t&&y(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&d(e.buffer),t},isString:h,isNumber:m,isBoolean:e=>!0===e||!1===e,isObject:v,isPlainObject:g,isReadableStream:T,isRequest:_,isResponse:O,isHeaders:x,isUndefined:p,isDate:b,isFile:w,isBlob:S,isRegExp:N,isFunction:y,isStream:e=>v(e)&&y(e.pipe),isURLSearchParams:E,isTypedArray:C,isFileList:k,forEach:A,merge:function e(){const{caseless:t}=I(this)&&this||{},r={},n=(n,o)=>{const i=t&&P(r,o)||o;g(r[i])&&g(n)?r[i]=e(r[i],n):g(n)?r[i]=e({},n):f(n)?r[i]=n.slice():r[i]=n};for(let e=0,t=arguments.length;e(A(t,((t,n)=>{r&&y(t)?e[n]=o(t,r):e[n]=t}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let o,i,s;const u={};if(t=t||{},null==e)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],n&&!n(s,e,t)||u[s]||(t[s]=e[s],u[s]=!0);e=!1!==r&&a(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:s,kindOfTest:c,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(f(e))return e;let t=e.length;if(!m(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:B,hasOwnProperty:L,hasOwnProp:L,reduceDescriptors:U,freezeMethods:e=>{U(e,((t,r)=>{if(y(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];y(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return f(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:P,global:R,isContextDefined:I,ALPHABET:D,generateString:(e=16,t=D.ALPHA_DIGIT)=>{let r="";const{length:n}=t;for(;e--;)r+=t[Math.random()*n|0];return r},isSpecCompliantForm:function(e){return!!(e&&y(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(v(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const o=f(e)?[]:{};return A(e,((e,t)=>{const i=r(e,n+1);!p(i)&&(o[t]=i)})),t[n]=void 0,o}}return e};return r(e,0)},isAsyncFn:V,isThenable:e=>e&&(v(e)||y(e))&&y(e.then)&&y(e.catch),setImmediate:q,asap:G};function Q(e,t,r,n,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),o&&(this.response=o,this.status=o.status?o.status:null)}$.inherits(Q,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:$.toJSONObject(this.config),code:this.code,status:this.status}}});const W=Q.prototype,Y={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{Y[e]={value:e}})),Object.defineProperties(Q,Y),Object.defineProperty(W,"isAxiosError",{value:!0}),Q.from=(e,t,r,n,o,i)=>{const a=Object.create(W);return $.toFlatObject(e,a,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),Q.call(a,e.message,t,r,n,o),a.cause=e,a.name=e.name,i&&Object.assign(a,i),a};const J=Q;var Z=r(8287).Buffer;function ee(e){return $.isPlainObject(e)||$.isArray(e)}function te(e){return $.endsWith(e,"[]")?e.slice(0,-2):e}function re(e,t,r){return e?e.concat(t).map((function(e,t){return e=te(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const ne=$.toFlatObject($,{},null,(function(e){return/^is[A-Z]/.test(e)}));const oe=function(e,t,r){if(!$.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=$.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!$.isUndefined(t[e])}))).metaTokens,o=r.visitor||c,i=r.dots,a=r.indexes,s=(r.Blob||"undefined"!=typeof Blob&&Blob)&&$.isSpecCompliantForm(t);if(!$.isFunction(o))throw new TypeError("visitor must be a function");function u(e){if(null===e)return"";if($.isDate(e))return e.toISOString();if(!s&&$.isBlob(e))throw new J("Blob is not supported. Use a Buffer instead.");return $.isArrayBuffer(e)||$.isTypedArray(e)?s&&"function"==typeof Blob?new Blob([e]):Z.from(e):e}function c(e,r,o){let s=e;if(e&&!o&&"object"==typeof e)if($.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if($.isArray(e)&&function(e){return $.isArray(e)&&!e.some(ee)}(e)||($.isFileList(e)||$.endsWith(r,"[]"))&&(s=$.toArray(e)))return r=te(r),s.forEach((function(e,n){!$.isUndefined(e)&&null!==e&&t.append(!0===a?re([r],n,i):null===a?r:r+"[]",u(e))})),!1;return!!ee(e)||(t.append(re(o,r,i),u(e)),!1)}const l=[],f=Object.assign(ne,{defaultVisitor:c,convertValue:u,isVisitable:ee});if(!$.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!$.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+n.join("."));l.push(r),$.forEach(r,(function(r,i){!0===(!($.isUndefined(r)||null===r)&&o.call(t,r,$.isString(i)?i.trim():i,n,f))&&e(r,n?n.concat(i):[i])})),l.pop()}}(e),t};function ie(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function ae(e,t){this._pairs=[],e&&oe(e,this,t)}const se=ae.prototype;se.append=function(e,t){this._pairs.push([e,t])},se.toString=function(e){const t=e?function(t){return e.call(this,t,ie)}:ie;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};const ue=ae;function ce(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function le(e,t,r){if(!t)return e;const n=r&&r.encode||ce;$.isFunction(r)&&(r={serialize:r});const o=r&&r.serialize;let i;if(i=o?o(t,r):$.isURLSearchParams(t)?t.toString():new ue(t,r).toString(n),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}const fe=class{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){$.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},pe={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},de={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:ue,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},he="undefined"!=typeof window&&"undefined"!=typeof document,ye="object"==typeof navigator&&navigator||void 0,me=he&&(!ye||["ReactNative","NativeScript","NS"].indexOf(ye.product)<0),ve="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,ge=he&&window.location.href||"http://localhost",be={...n,...de};const we=function(e){function t(e,r,n,o){let i=e[o++];if("__proto__"===i)return!0;const a=Number.isFinite(+i),s=o>=e.length;if(i=!i&&$.isArray(n)?n.length:i,s)return $.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!a;n[i]&&$.isObject(n[i])||(n[i]=[]);return t(e,r,n[i],o)&&$.isArray(n[i])&&(n[i]=function(e){const t={},r=Object.keys(e);let n;const o=r.length;let i;for(n=0;n{t(function(e){return $.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null};const Se={transitional:pe,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,o=$.isObject(e);o&&$.isHTMLForm(e)&&(e=new FormData(e));if($.isFormData(e))return n?JSON.stringify(we(e)):e;if($.isArrayBuffer(e)||$.isBuffer(e)||$.isStream(e)||$.isFile(e)||$.isBlob(e)||$.isReadableStream(e))return e;if($.isArrayBufferView(e))return e.buffer;if($.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return oe(e,new be.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return be.isNode&&$.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=$.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return oe(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||n?(t.setContentType("application/json",!1),function(e,t,r){if($.isString(e))try{return(t||JSON.parse)(e),$.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Se.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if($.isResponse(e)||$.isReadableStream(e))return e;if(e&&$.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw J.from(e,J.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:be.classes.FormData,Blob:be.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};$.forEach(["delete","get","head","post","put","patch"],(e=>{Se.headers[e]={}}));const ke=Se,Ee=$.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Te=Symbol("internals");function _e(e){return e&&String(e).trim().toLowerCase()}function Oe(e){return!1===e||null==e?e:$.isArray(e)?e.map(Oe):String(e)}function xe(e,t,r,n,o){return $.isFunction(n)?n.call(this,t,r):(o&&(t=r),$.isString(t)?$.isString(n)?-1!==t.indexOf(n):$.isRegExp(n)?n.test(t):void 0:void 0)}class Ae{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function o(e,t,r){const o=_e(t);if(!o)throw new Error("header name must be a non-empty string");const i=$.findKey(n,o);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=Oe(e))}const i=(e,t)=>$.forEach(e,((e,r)=>o(e,r,t)));if($.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if($.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))i((e=>{const t={};let r,n,o;return e&&e.split("\n").forEach((function(e){o=e.indexOf(":"),r=e.substring(0,o).trim().toLowerCase(),n=e.substring(o+1).trim(),!r||t[r]&&Ee[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t);else if($.isHeaders(e))for(const[t,n]of e.entries())o(n,t,r);else null!=e&&o(t,e,r);return this}get(e,t){if(e=_e(e)){const r=$.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if($.isFunction(t))return t.call(this,e,r);if($.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=_e(e)){const r=$.findKey(this,e);return!(!r||void 0===this[r]||t&&!xe(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function o(e){if(e=_e(e)){const o=$.findKey(r,e);!o||t&&!xe(0,r[o],o,t)||(delete r[o],n=!0)}}return $.isArray(e)?e.forEach(o):o(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const o=t[r];e&&!xe(0,this[o],o,e,!0)||(delete this[o],n=!0)}return n}normalize(e){const t=this,r={};return $.forEach(this,((n,o)=>{const i=$.findKey(r,o);if(i)return t[i]=Oe(n),void delete t[o];const a=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(o):String(o).trim();a!==o&&delete t[o],t[a]=Oe(n),r[a]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return $.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&$.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[Te]=this[Te]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=_e(e);t[n]||(!function(e,t){const r=$.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,o){return this[n].call(this,t,e,r,o)},configurable:!0})}))}(r,e),t[n]=!0)}return $.isArray(e)?e.forEach(n):n(e),this}}Ae.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),$.reduceDescriptors(Ae.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),$.freezeMethods(Ae);const Pe=Ae;function Re(e,t){const r=this||ke,n=t||r,o=Pe.from(n.headers);let i=n.data;return $.forEach(e,(function(e){i=e.call(r,i,o.normalize(),t?t.status:void 0)})),o.normalize(),i}function Ie(e){return!(!e||!e.__CANCEL__)}function Ce(e,t,r){J.call(this,null==e?"canceled":e,J.ERR_CANCELED,t,r),this.name="CanceledError"}$.inherits(Ce,J,{__CANCEL__:!0});const je=Ce;function Be(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new J("Request failed with status code "+r.status,[J.ERR_BAD_REQUEST,J.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}const Le=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let o,i=0,a=0;return t=void 0!==t?t:1e3,function(s){const u=Date.now(),c=n[a];o||(o=u),r[i]=s,n[i]=u;let l=a,f=0;for(;l!==i;)f+=r[l++],l%=e;if(i=(i+1)%e,i===a&&(a=(a+1)%e),u-o{o=i,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),s=t-o;s>=i?a(e,t):(r=e,n||(n=setTimeout((()=>{n=null,a(r)}),i-s)))},()=>r&&a(r)]},Ue=(e,t,r=3)=>{let n=0;const o=Le(50,250);return Ne((r=>{const i=r.loaded,a=r.lengthComputable?r.total:void 0,s=i-n,u=o(s);n=i;e({loaded:i,total:a,progress:a?i/a:void 0,bytes:s,rate:u||void 0,estimated:u&&a&&i<=a?(a-i)/u:void 0,event:r,lengthComputable:null!=a,[t?"download":"upload"]:!0})}),r)},Me=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},Fe=e=>(...t)=>$.asap((()=>e(...t))),De=be.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,be.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(be.origin),be.navigator&&/(msie|trident)/i.test(be.navigator.userAgent)):()=>!0,Ve=be.hasStandardBrowserEnv?{write(e,t,r,n,o,i){const a=[e+"="+encodeURIComponent(t)];$.isNumber(r)&&a.push("expires="+new Date(r).toGMTString()),$.isString(n)&&a.push("path="+n),$.isString(o)&&a.push("domain="+o),!0===i&&a.push("secure"),document.cookie=a.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function qe(e,t){return e&&!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Ke=e=>e instanceof Pe?{...e}:e;function He(e,t){t=t||{};const r={};function n(e,t,r,n){return $.isPlainObject(e)&&$.isPlainObject(t)?$.merge.call({caseless:n},e,t):$.isPlainObject(t)?$.merge({},t):$.isArray(t)?t.slice():t}function o(e,t,r,o){return $.isUndefined(t)?$.isUndefined(e)?void 0:n(void 0,e,0,o):n(e,t,0,o)}function i(e,t){if(!$.isUndefined(t))return n(void 0,t)}function a(e,t){return $.isUndefined(t)?$.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function s(r,o,i){return i in t?n(r,o):i in e?n(void 0,r):void 0}const u={url:i,method:i,data:i,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:s,headers:(e,t,r)=>o(Ke(e),Ke(t),0,!0)};return $.forEach(Object.keys(Object.assign({},e,t)),(function(n){const i=u[n]||o,a=i(e[n],t[n],n);$.isUndefined(a)&&i!==s||(r[n]=a)})),r}const ze=e=>{const t=He({},e);let r,{data:n,withXSRFToken:o,xsrfHeaderName:i,xsrfCookieName:a,headers:s,auth:u}=t;if(t.headers=s=Pe.from(s),t.url=le(qe(t.baseURL,t.url),e.params,e.paramsSerializer),u&&s.set("Authorization","Basic "+btoa((u.username||"")+":"+(u.password?unescape(encodeURIComponent(u.password)):""))),$.isFormData(n))if(be.hasStandardBrowserEnv||be.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(!1!==(r=s.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];s.setContentType([e||"multipart/form-data",...t].join("; "))}if(be.hasStandardBrowserEnv&&(o&&$.isFunction(o)&&(o=o(t)),o||!1!==o&&De(t.url))){const e=i&&a&&Ve.read(a);e&&s.set(i,e)}return t},Xe="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const n=ze(e);let o=n.data;const i=Pe.from(n.headers).normalize();let a,s,u,c,l,{responseType:f,onUploadProgress:p,onDownloadProgress:d}=n;function h(){c&&c(),l&&l(),n.cancelToken&&n.cancelToken.unsubscribe(a),n.signal&&n.signal.removeEventListener("abort",a)}let y=new XMLHttpRequest;function m(){if(!y)return;const n=Pe.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders());Be((function(e){t(e),h()}),(function(e){r(e),h()}),{data:f&&"text"!==f&&"json"!==f?y.response:y.responseText,status:y.status,statusText:y.statusText,headers:n,config:e,request:y}),y=null}y.open(n.method.toUpperCase(),n.url,!0),y.timeout=n.timeout,"onloadend"in y?y.onloadend=m:y.onreadystatechange=function(){y&&4===y.readyState&&(0!==y.status||y.responseURL&&0===y.responseURL.indexOf("file:"))&&setTimeout(m)},y.onabort=function(){y&&(r(new J("Request aborted",J.ECONNABORTED,e,y)),y=null)},y.onerror=function(){r(new J("Network Error",J.ERR_NETWORK,e,y)),y=null},y.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const o=n.transitional||pe;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new J(t,o.clarifyTimeoutError?J.ETIMEDOUT:J.ECONNABORTED,e,y)),y=null},void 0===o&&i.setContentType(null),"setRequestHeader"in y&&$.forEach(i.toJSON(),(function(e,t){y.setRequestHeader(t,e)})),$.isUndefined(n.withCredentials)||(y.withCredentials=!!n.withCredentials),f&&"json"!==f&&(y.responseType=n.responseType),d&&([u,l]=Ue(d,!0),y.addEventListener("progress",u)),p&&y.upload&&([s,c]=Ue(p),y.upload.addEventListener("progress",s),y.upload.addEventListener("loadend",c)),(n.cancelToken||n.signal)&&(a=t=>{y&&(r(!t||t.type?new je(null,e,y):t),y.abort(),y=null)},n.cancelToken&&n.cancelToken.subscribe(a),n.signal&&(n.signal.aborted?a():n.signal.addEventListener("abort",a)));const v=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);v&&-1===be.protocols.indexOf(v)?r(new J("Unsupported protocol "+v+":",J.ERR_BAD_REQUEST,e)):y.send(o||null)}))},Ge=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const o=function(e){if(!r){r=!0,a();const t=e instanceof Error?e:this.reason;n.abort(t instanceof J?t:new je(t instanceof Error?t.message:t))}};let i=t&&setTimeout((()=>{i=null,o(new J(`timeout ${t} of ms exceeded`,J.ETIMEDOUT))}),t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(o):e.removeEventListener("abort",o)})),e=null)};e.forEach((e=>e.addEventListener("abort",o)));const{signal:s}=n;return s.unsubscribe=()=>$.asap(a),s}},$e=function*(e,t){let r=e.byteLength;if(!t||r{const o=async function*(e,t){for await(const r of Qe(e))yield*$e(r,t)}(e,t);let i,a=0,s=e=>{i||(i=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await o.next();if(t)return s(),void e.close();let i=n.byteLength;if(r){let e=a+=i;r(e)}e.enqueue(new Uint8Array(n))}catch(e){throw s(e),e}},cancel:e=>(s(e),o.return())},{highWaterMark:2})},Ye="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Je=Ye&&"function"==typeof ReadableStream,Ze=Ye&&("function"==typeof TextEncoder?(et=new TextEncoder,e=>et.encode(e)):async e=>new Uint8Array(await new Response(e).arrayBuffer()));var et;const tt=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},rt=Je&&tt((()=>{let e=!1;const t=new Request(be.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),nt=Je&&tt((()=>$.isReadableStream(new Response("").body))),ot={stream:nt&&(e=>e.body)};var it;Ye&&(it=new Response,["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!ot[e]&&(ot[e]=$.isFunction(it[e])?t=>t[e]():(t,r)=>{throw new J(`Response type '${e}' is not supported`,J.ERR_NOT_SUPPORT,r)})})));const at=async(e,t)=>{const r=$.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if($.isBlob(e))return e.size;if($.isSpecCompliantForm(e)){const t=new Request(be.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return $.isArrayBufferView(e)||$.isArrayBuffer(e)?e.byteLength:($.isURLSearchParams(e)&&(e+=""),$.isString(e)?(await Ze(e)).byteLength:void 0)})(t):r},st={http:null,xhr:Xe,fetch:Ye&&(async e=>{let{url:t,method:r,data:n,signal:o,cancelToken:i,timeout:a,onDownloadProgress:s,onUploadProgress:u,responseType:c,headers:l,withCredentials:f="same-origin",fetchOptions:p}=ze(e);c=c?(c+"").toLowerCase():"text";let d,h=Ge([o,i&&i.toAbortSignal()],a);const y=h&&h.unsubscribe&&(()=>{h.unsubscribe()});let m;try{if(u&&rt&&"get"!==r&&"head"!==r&&0!==(m=await at(l,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if($.isFormData(n)&&(e=r.headers.get("content-type"))&&l.setContentType(e),r.body){const[e,t]=Me(m,Ue(Fe(u)));n=We(r.body,65536,e,t)}}$.isString(f)||(f=f?"include":"omit");const o="credentials"in Request.prototype;d=new Request(t,{...p,signal:h,method:r.toUpperCase(),headers:l.normalize().toJSON(),body:n,duplex:"half",credentials:o?f:void 0});let i=await fetch(d);const a=nt&&("stream"===c||"response"===c);if(nt&&(s||a&&y)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=i[t]}));const t=$.toFiniteNumber(i.headers.get("content-length")),[r,n]=s&&Me(t,Ue(Fe(s),!0))||[];i=new Response(We(i.body,65536,r,(()=>{n&&n(),y&&y()})),e)}c=c||"text";let v=await ot[$.findKey(ot,c)||"text"](i,e);return!a&&y&&y(),await new Promise(((t,r)=>{Be(t,r,{data:v,headers:Pe.from(i.headers),status:i.status,statusText:i.statusText,config:e,request:d})}))}catch(t){if(y&&y(),t&&"TypeError"===t.name&&/fetch/i.test(t.message))throw Object.assign(new J("Network Error",J.ERR_NETWORK,e,d),{cause:t.cause||t});throw J.from(t,t&&t.code,e,d)}})};$.forEach(st,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const ut=e=>`- ${e}`,ct=e=>$.isFunction(e)||null===e||!1===e,lt=e=>{e=$.isArray(e)?e:[e];const{length:t}=e;let r,n;const o={};for(let i=0;i`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));let r=t?e.length>1?"since :\n"+e.map(ut).join("\n"):" "+ut(e[0]):"as no adapter specified";throw new J("There is no suitable adapter to dispatch the request "+r,"ERR_NOT_SUPPORT")}return n};function ft(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new je(null,e)}function pt(e){ft(e),e.headers=Pe.from(e.headers),e.data=Re.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return lt(e.adapter||ke.adapter)(e).then((function(t){return ft(e),t.data=Re.call(e,e.transformResponse,t),t.headers=Pe.from(t.headers),t}),(function(t){return Ie(t)||(ft(e),t&&t.response&&(t.response.data=Re.call(e,e.transformResponse,t.response),t.response.headers=Pe.from(t.response.headers))),Promise.reject(t)}))}const dt="1.7.9",ht={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{ht[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const yt={};ht.transitional=function(e,t,r){function n(e,t){return"[Axios v1.7.9] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,o,i)=>{if(!1===e)throw new J(n(o," has been removed"+(t?" in "+t:"")),J.ERR_DEPRECATED);return t&&!yt[o]&&(yt[o]=!0,console.warn(n(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,o,i)}},ht.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const mt={assertOptions:function(e,t,r){if("object"!=typeof e)throw new J("options must be an object",J.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let o=n.length;for(;o-- >0;){const i=n[o],a=t[i];if(a){const t=e[i],r=void 0===t||a(t,i,e);if(!0!==r)throw new J("option "+i+" must be "+r,J.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new J("Unknown option "+i,J.ERR_BAD_OPTION)}},validators:ht},vt=mt.validators;class gt{constructor(e){this.defaults=e,this.interceptors={request:new fe,response:new fe}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=He(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:o}=t;void 0!==r&&mt.assertOptions(r,{silentJSONParsing:vt.transitional(vt.boolean),forcedJSONParsing:vt.transitional(vt.boolean),clarifyTimeoutError:vt.transitional(vt.boolean)},!1),null!=n&&($.isFunction(n)?t.paramsSerializer={serialize:n}:mt.assertOptions(n,{encode:vt.function,serialize:vt.function},!0)),mt.assertOptions(t,{baseUrl:vt.spelling("baseURL"),withXsrfToken:vt.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=o&&$.merge(o.common,o[t.method]);o&&$.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete o[e]})),t.headers=Pe.concat(i,o);const a=[];let s=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(s=s&&e.synchronous,a.unshift(e.fulfilled,e.rejected))}));const u=[];let c;this.interceptors.response.forEach((function(e){u.push(e.fulfilled,e.rejected)}));let l,f=0;if(!s){const e=[pt.bind(this),void 0];for(e.unshift.apply(e,a),e.push.apply(e,u),l=e.length,c=Promise.resolve(t);f{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,o){r.reason||(r.reason=new je(e,n,o),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new wt((function(t){e=t})),cancel:e}}}const St=wt;const kt={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(kt).forEach((([e,t])=>{kt[t]=e}));const Et=kt;const Tt=function e(t){const r=new bt(t),n=o(bt.prototype.request,r);return $.extend(n,bt.prototype,r,{allOwnKeys:!0}),$.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(He(t,r))},n}(ke);Tt.Axios=bt,Tt.CanceledError=je,Tt.CancelToken=St,Tt.isCancel=Ie,Tt.VERSION=dt,Tt.toFormData=oe,Tt.AxiosError=J,Tt.Cancel=Tt.CanceledError,Tt.all=function(e){return Promise.all(e)},Tt.spread=function(e){return function(t){return e.apply(null,t)}},Tt.isAxiosError=function(e){return $.isObject(e)&&!0===e.isAxiosError},Tt.mergeConfig=He,Tt.AxiosHeaders=Pe,Tt.formToJSON=e=>we($.isHTMLForm(e)?new FormData(e):e),Tt.getAdapter=lt,Tt.HttpStatusCode=Et,Tt.default=Tt;var _t=Tt,Ot=Tt.create},9983:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rl,ok:()=>c});a=function e(t){var r,n=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.promise=new Promise((function(e){r=e})),t((function(e){n.reason=e,r()}))},(s=[{key:"throwIfRequested",value:function(){if(this.reason)throw new Error(this.reason)}}])&&o(a.prototype,s),u&&o(a,u),Object.defineProperty(a,"prototype",{writable:!1});var a,s,u,c,l,f=r(6121);c=f.axiosClient,l=f.create},4356:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AccountRequiresMemoError:()=>n.Cu,BadRequestError:()=>n.v7,BadResponseError:()=>n.nS,Config:()=>o.T,Federation:()=>s,Friendbot:()=>c,Horizon:()=>l,NetworkError:()=>n.Dr,NotFoundError:()=>n.m_,StellarToml:()=>a,Utils:()=>i.A,WebAuth:()=>u,contract:()=>p,default:()=>y,rpc:()=>f});var n=r(5976),o=r(8732),i=r(3121),a=r(3898),s=r(7600),u=r(5479),c=r(8242),l=r(8733),f=r(3496),p=r(6299),d=r(356),h={};for(const e in d)["default","Config","Utils","StellarToml","Federation","WebAuth","Friendbot","Horizon","rpc","contract","AccountRequiresMemoError","BadRequestError","BadResponseError","NetworkError","NotFoundError"].indexOf(e)<0&&(h[e]=()=>d[e]);r.d(t,h);const y=(e=r.hmd(e)).exports;void 0===r.g.__USE_AXIOS__&&(r.g.__USE_AXIOS__=!0),void 0===r.g.__USE_EVENTSOURCE__&&(r.g.__USE_EVENTSOURCE__=!1)},4076:(e,t,r)=>{"use strict";var n;r.d(t,{j:()=>n}),function(e){var t=function(e){return e.SUCCESS="SUCCESS",e.NOT_FOUND="NOT_FOUND",e.FAILED="FAILED",e}({});function r(e){return"transactionData"in e}e.GetTransactionStatus=t,e.isSimulationError=function(e){return"error"in e},e.isSimulationSuccess=r,e.isSimulationRestore=function(e){return r(e)&&"restorePreamble"in e&&!!e.restorePreamble.transactionData},e.isSimulationRaw=function(e){return!e._parsed}}(n||(n={}))},3496:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Api:()=>n.j,AxiosClient:()=>s,BasicSleepStrategy:()=>x,Durability:()=>O,LinearSleepStrategy:()=>A,Server:()=>oe,assembleTransaction:()=>d.X,default:()=>ie,parseRawEvents:()=>h.fG,parseRawSimulation:()=>h.jr});var n=r(4076),o=r(4193),i=r.n(o),a=r(356);const s=(0,r(9983).vt)({headers:{"X-Client-Name":"js-soroban-client","X-Client-Version":"13.1.0"}});function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(){c=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",l=i.toStringTag||"@@toStringTag";function f(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{f({},"")}catch(e){f=function(e,t,r){return e[t]=r}}function p(e,t,r,n){var i=t&&t.prototype instanceof b?t:b,a=Object.create(i.prototype),s=new C(n||[]);return o(a,"_invoke",{value:A(e,r,s)}),a}function d(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=p;var h="suspendedStart",y="suspendedYield",m="executing",v="completed",g={};function b(){}function w(){}function S(){}var k={};f(k,a,(function(){return this}));var E=Object.getPrototypeOf,T=E&&E(E(j([])));T&&T!==r&&n.call(T,a)&&(k=T);var _=S.prototype=b.prototype=Object.create(k);function O(e){["next","throw","return"].forEach((function(t){f(e,t,(function(e){return this._invoke(t,e)}))}))}function x(e,t){function r(o,i,a,s){var c=d(e[o],e,i);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==u(f)&&n.call(f,"__await")?t.resolve(f.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(f).then((function(e){l.value=e,a(l)}),(function(e){return r("throw",e,a,s)}))}s(c.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function A(t,r,n){var o=h;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=P(s,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=m;var c=d(t,r,n);if("normal"===c.type){if(o=n.done?v:y,c.arg===g)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=v,n.method="throw",n.arg=c.arg)}}}function P(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,P(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=d(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function R(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function I(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(R,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),I(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;I(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function l(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function f(e,t){return p.apply(this,arguments)}function p(){var e;return e=c().mark((function e(t,r){var n,o,i,a=arguments;return c().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=a.length>2&&void 0!==a[2]?a[2]:null,e.next=3,s.post(t,{jsonrpc:"2.0",id:1,method:r,params:n});case 3:if(o=e.sent,u=o.data,c="error",!u.hasOwnProperty(c)){e.next=8;break}throw o.data.error;case 8:return e.abrupt("return",null===(i=o.data)||void 0===i?void 0:i.result);case 9:case"end":return e.stop()}var u,c}),e)})),p=function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){l(i,n,o,a,s,"next",e)}function s(e){l(i,n,o,a,s,"throw",e)}a(void 0)}))},p.apply(this,arguments)}var d=r(8680),h=r(784),y=r(3121),m=r(8287).Buffer;function v(e){return v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},v(e)}function g(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function b(e){for(var t=1;t=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),I(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;I(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function k(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function E(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){k(i,n,o,a,s,"next",e)}function s(e){k(i,n,o,a,s,"throw",e)}a(void 0)}))}}function T(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:{};if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.serverURL=i()(t),r.headers&&0!==Object.keys(r.headers).length&&s.interceptors.request.use((function(e){return e.headers=Object.assign(e.headers,r.headers),e})),"https"!==this.serverURL.protocol()&&!r.allowHttp)throw new Error("Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set")},I=[{key:"getAccount",value:(ne=E(S().mark((function e(t){var r,n,o;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=a.xdr.LedgerKey.account(new a.xdr.LedgerKeyAccount({accountId:a.Keypair.fromPublicKey(t).xdrPublicKey()})),e.next=3,this.getLedgerEntries(r);case 3:if(0!==(n=e.sent).entries.length){e.next=6;break}return e.abrupt("return",Promise.reject({code:404,message:"Account not found: ".concat(t)}));case 6:return o=n.entries[0].val.account(),e.abrupt("return",new a.Account(t,o.seqNum().toString()));case 8:case"end":return e.stop()}}),e,this)}))),function(e){return ne.apply(this,arguments)})},{key:"getHealth",value:(re=E(S().mark((function e(){return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",f(this.serverURL.toString(),"getHealth"));case 1:case"end":return e.stop()}}),e,this)}))),function(){return re.apply(this,arguments)})},{key:"getContractData",value:(te=E(S().mark((function e(t,r){var n,o,i,s,u=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=u.length>2&&void 0!==u[2]?u[2]:O.Persistent,"string"!=typeof t){e.next=5;break}o=new a.Contract(t).address().toScAddress(),e.next=14;break;case 5:if(!(t instanceof a.Address)){e.next=9;break}o=t.toScAddress(),e.next=14;break;case 9:if(!(t instanceof a.Contract)){e.next=13;break}o=t.address().toScAddress(),e.next=14;break;case 13:throw new TypeError("unknown contract type: ".concat(t));case 14:e.t0=n,e.next=e.t0===O.Temporary?17:e.t0===O.Persistent?19:21;break;case 17:return i=a.xdr.ContractDataDurability.temporary(),e.abrupt("break",22);case 19:return i=a.xdr.ContractDataDurability.persistent(),e.abrupt("break",22);case 21:throw new TypeError("invalid durability: ".concat(n));case 22:return s=a.xdr.LedgerKey.contractData(new a.xdr.LedgerKeyContractData({key:r,contract:o,durability:i})),e.abrupt("return",this.getLedgerEntries(s).then((function(e){return 0===e.entries.length?Promise.reject({code:404,message:"Contract data not found. Contract: ".concat(a.Address.fromScAddress(o).toString(),", Key: ").concat(r.toXDR("base64"),", Durability: ").concat(n)}):e.entries[0]})));case 24:case"end":return e.stop()}}),e,this)}))),function(e,t){return te.apply(this,arguments)})},{key:"getContractWasmByContractId",value:(ee=E(S().mark((function e(t){var r,n,o,i;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=new a.Contract(t).getFootprint(),e.next=3,this.getLedgerEntries(n);case 3:if((o=e.sent).entries.length&&null!==(r=o.entries[0])&&void 0!==r&&r.val){e.next=6;break}return e.abrupt("return",Promise.reject({code:404,message:"Could not obtain contract hash from server"}));case 6:return i=o.entries[0].val.contractData().val().instance().executable().wasmHash(),e.abrupt("return",this.getContractWasmByHash(i));case 8:case"end":return e.stop()}}),e,this)}))),function(e){return ee.apply(this,arguments)})},{key:"getContractWasmByHash",value:(Z=E(S().mark((function e(t){var r,n,o,i,s,u,c=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=c.length>1&&void 0!==c[1]?c[1]:void 0,o="string"==typeof t?m.from(t,n):t,i=a.xdr.LedgerKey.contractCode(new a.xdr.LedgerKeyContractCode({hash:o})),e.next=5,this.getLedgerEntries(i);case 5:if((s=e.sent).entries.length&&null!==(r=s.entries[0])&&void 0!==r&&r.val){e.next=8;break}return e.abrupt("return",Promise.reject({code:404,message:"Could not obtain contract wasm from server"}));case 8:return u=s.entries[0].val.contractCode().code(),e.abrupt("return",u);case 10:case"end":return e.stop()}}),e,this)}))),function(e){return Z.apply(this,arguments)})},{key:"getLedgerEntries",value:(J=E(S().mark((function e(){var t=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this._getLedgerEntries.apply(this,t).then(h.$D));case 1:case"end":return e.stop()}}),e,this)}))),function(){return J.apply(this,arguments)})},{key:"_getLedgerEntries",value:(Y=E(S().mark((function e(){var t,r,n,o=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(t=o.length,r=new Array(t),n=0;n{"use strict";r.d(t,{$D:()=>d,Af:()=>c,WC:()=>l,fG:()=>p,jr:()=>h,tR:()=>f});var n=r(356),o=r(4076);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function s(e){for(var t=1;t0&&{diagnosticEvents:r.map((function(e){return n.xdr.DiagnosticEvent.fromXDR(e,"base64")}))}),{},{errorResult:n.xdr.TransactionResult.fromXDR(t,"base64")}):s({},e)}function l(e){var t,r=n.xdr.TransactionMeta.fromXDR(e.resultMetaXdr,"base64"),o={ledger:e.ledger,createdAt:e.createdAt,applicationOrder:e.applicationOrder,feeBump:e.feeBump,envelopeXdr:n.xdr.TransactionEnvelope.fromXDR(e.envelopeXdr,"base64"),resultXdr:n.xdr.TransactionResult.fromXDR(e.resultXdr,"base64"),resultMetaXdr:r};3===r.switch()&&null!==r.v3().sorobanMeta()&&(o.returnValue=null===(t=r.v3().sorobanMeta())||void 0===t?void 0:t.returnValue());return"diagnosticEventsXdr"in e&&e.diagnosticEventsXdr&&(o.diagnosticEventsXdr=e.diagnosticEventsXdr.map((function(e){return n.xdr.DiagnosticEvent.fromXDR(e,"base64")}))),o}function f(e){return s({status:e.status,txHash:e.txHash},l(e))}function p(e){var t;return{latestLedger:e.latestLedger,cursor:e.cursor,events:(null!==(t=e.events)&&void 0!==t?t:[]).map((function(e){var t=s({},e);return delete t.contractId,s(s(s({},t),""!==e.contractId&&{contractId:new n.Contract(e.contractId)}),{},{topic:e.topic.map((function(e){return n.xdr.ScVal.fromXDR(e,"base64")})),value:n.xdr.ScVal.fromXDR(e.value,"base64")})}))}}function d(e){var t;return{latestLedger:e.latestLedger,entries:(null!==(t=e.entries)&&void 0!==t?t:[]).map((function(e){if(!e.key||!e.xdr)throw new TypeError("invalid ledger entry: ".concat(JSON.stringify(e)));return s({lastModifiedLedgerSeq:e.lastModifiedLedgerSeq,key:n.xdr.LedgerKey.fromXDR(e.key,"base64"),val:n.xdr.LedgerEntryData.fromXDR(e.xdr,"base64")},void 0!==e.liveUntilLedgerSeq&&{liveUntilLedgerSeq:e.liveUntilLedgerSeq})}))}}function h(e){var t,r;if(!o.j.isSimulationRaw(e))return e;var i={_parsed:!0,id:e.id,latestLedger:e.latestLedger,events:null!==(t=null===(r=e.events)||void 0===r?void 0:r.map((function(e){return n.xdr.DiagnosticEvent.fromXDR(e,"base64")})))&&void 0!==t?t:[]};return"string"==typeof e.error?s(s({},i),{},{error:e.error}):function(e,t){var r,o,i,a,u,c=s(s(s({},t),{},{transactionData:new n.SorobanDataBuilder(e.transactionData),minResourceFee:e.minResourceFee},null!==(r=null===(o=e.results)||void 0===o?void 0:o.length)&&void 0!==r&&r&&{result:e.results.map((function(e){var t;return{auth:(null!==(t=e.auth)&&void 0!==t?t:[]).map((function(e){return n.xdr.SorobanAuthorizationEntry.fromXDR(e,"base64")})),retval:e.xdr?n.xdr.ScVal.fromXDR(e.xdr,"base64"):n.xdr.ScVal.scvVoid()}}))[0]}),null!==(i=null===(a=e.stateChanges)||void 0===a?void 0:a.length)&&void 0!==i&&i&&{stateChanges:null===(u=e.stateChanges)||void 0===u?void 0:u.map((function(e){return{type:e.type,key:n.xdr.LedgerKey.fromXDR(e.key,"base64"),before:e.before?n.xdr.LedgerEntry.fromXDR(e.before,"base64"):null,after:e.after?n.xdr.LedgerEntry.fromXDR(e.after,"base64"):null}}))});return e.restorePreamble&&""!==e.restorePreamble.transactionData?s(s({},c),{},{restorePreamble:{minResourceFee:e.restorePreamble.minResourceFee,transactionData:new n.SorobanDataBuilder(e.restorePreamble.transactionData)}}):c}(e,i)}},8680:(e,t,r)=>{"use strict";r.d(t,{X:()=>a});var n=r(356),o=r(4076),i=r(784);function a(e,t){if("innerTransaction"in e)return a(e.innerTransaction,t);if(!function(e){if(1!==e.operations.length)return!1;switch(e.operations[0].type){case"invokeHostFunction":case"extendFootprintTtl":case"restoreFootprint":return!0;default:return!1}}(e))throw new TypeError("unsupported transaction: must contain exactly one invokeHostFunction, extendFootprintTtl, or restoreFootprint operation");var r=(0,i.jr)(t);if(!o.j.isSimulationSuccess(r))throw new Error("simulation incorrect: ".concat(JSON.stringify(r)));var s=parseInt(e.fee)||0,u=parseInt(r.minResourceFee)||0,c=n.TransactionBuilder.cloneFrom(e,{fee:(s+u).toString(),sorobanData:r.transactionData.build(),networkPassphrase:e.networkPassphrase});if("invokeHostFunction"===e.operations[0].type){var l;c.clearOperations();var f=e.operations[0],p=null!==(l=f.auth)&&void 0!==l?l:[];c.addOperation(n.Operation.invokeHostFunction({source:f.source,func:f.func,auth:p.length>0?p:r.result.auth}))}return c}},3898:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Api:()=>{},Resolver:()=>b,STELLAR_TOML_MAX_SIZE:()=>v});var n=r(1293),o=r.n(n),i=r(9983),a=r(8732);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(){u=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",l=i.toStringTag||"@@toStringTag";function f(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{f({},"")}catch(e){f=function(e,t,r){return e[t]=r}}function p(e,t,r,n){var i=t&&t.prototype instanceof b?t:b,a=Object.create(i.prototype),s=new C(n||[]);return o(a,"_invoke",{value:A(e,r,s)}),a}function d(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=p;var h="suspendedStart",y="suspendedYield",m="executing",v="completed",g={};function b(){}function w(){}function S(){}var k={};f(k,a,(function(){return this}));var E=Object.getPrototypeOf,T=E&&E(E(j([])));T&&T!==r&&n.call(T,a)&&(k=T);var _=S.prototype=b.prototype=Object.create(k);function O(e){["next","throw","return"].forEach((function(t){f(e,t,(function(e){return this._invoke(t,e)}))}))}function x(e,t){function r(o,i,a,u){var c=d(e[o],e,i);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==s(f)&&n.call(f,"__await")?t.resolve(f.__await).then((function(e){r("next",e,a,u)}),(function(e){r("throw",e,a,u)})):t.resolve(f).then((function(e){l.value=e,a(l)}),(function(e){return r("throw",e,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function A(t,r,n){var o=h;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=P(s,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=m;var c=d(t,r,n);if("normal"===c.type){if(o=n.done?v:y,c.arg===g)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=v,n.method="throw",n.arg=c.arg)}}}function P(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,P(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=d(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function R(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function I(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(R,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),I(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;I(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function c(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function l(e,t){for(var r=0;r1&&void 0!==f[1]?f[1]:{}).allowHttp?a.T.isAllowHttp():n.allowHttp,c=void 0===n.timeout?a.T.getTimeout():n.timeout,l=s?"http":"https",e.abrupt("return",i.ok.get("".concat(l,"://").concat(t,"/.well-known/stellar.toml"),{maxRedirects:null!==(r=n.allowedRedirects)&&void 0!==r?r:0,maxContentLength:v,cancelToken:c?new g((function(e){return setTimeout((function(){return e("timeout of ".concat(c,"ms exceeded"))}),c)})):void 0,timeout:c}).then((function(e){try{var t=o().parse(e.data);return Promise.resolve(t)}catch(e){return Promise.reject(new Error("stellar.toml is invalid - Parsing error on line ".concat(e.line,", column ").concat(e.column,": ").concat(e.message)))}})).catch((function(e){throw e.message.match(/^maxContentLength size/)?new Error("stellar.toml file exceeds allowed size of ".concat(v)):e})));case 5:case"end":return e.stop()}}),e)})),m=function(){var e=this,t=arguments;return new Promise((function(r,n){var o=y.apply(e,t);function i(e){c(o,r,n,i,a,"next",e)}function a(e){c(o,r,n,i,a,"throw",e)}i(void 0)}))},function(e){return m.apply(this,arguments)})}],d&&l(p.prototype,d),h&&l(p,h),Object.defineProperty(p,"prototype",{writable:!1}),p)},3121:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rc});var a,s,u,c=(a=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},u=[{key:"validateTimebounds",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!e.timeBounds)return!1;var r=Math.floor(Date.now()/1e3),n=e.timeBounds,o=n.minTime,i=n.maxTime;return r>=Number.parseInt(o,10)-t&&r<=Number.parseInt(i,10)+t}},{key:"sleep",value:function(e){return new Promise((function(t){return setTimeout(t,e)}))}}],(s=null)&&o(a.prototype,s),u&&o(a,u),Object.defineProperty(a,"prototype",{writable:!1}),a)},5479:(e,t,r)=>{"use strict";r.r(t),r.d(t,{InvalidChallengeError:()=>y,buildChallengeTx:()=>T,gatherTxSigners:()=>P,readChallengeTx:()=>_,verifyChallengeTxSigners:()=>x,verifyChallengeTxThreshold:()=>O,verifyTxSignedBy:()=>A});var n=r(3209),o=r.n(n),i=r(356),a=r(3121);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){for(var r=0;r=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,i=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw i}}}}function b(e){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},b(e)}function w(e){return function(e){if(Array.isArray(e))return e}(e)||E(e)||S(e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function S(e,t){if(e){if("string"==typeof e)return k(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?k(e,t):void 0}}function k(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r3&&void 0!==arguments[3]?arguments[3]:300,a=arguments.length>4?arguments[4]:void 0,s=arguments.length>5?arguments[5]:void 0,u=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,c=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null,l=arguments.length>8&&void 0!==arguments[8]?arguments[8]:null;if(t.startsWith("M")&&u)throw Error("memo cannot be used if clientAccountID is a muxed account");var f=new i.Account(e.publicKey(),"-1"),p=Math.floor(Date.now()/1e3),d=o()(48).toString("base64"),h=new i.TransactionBuilder(f,{fee:i.BASE_FEE,networkPassphrase:a,timebounds:{minTime:p,maxTime:p+n}}).addOperation(i.Operation.manageData({name:"".concat(r," auth"),value:d,source:t})).addOperation(i.Operation.manageData({name:"web_auth_domain",value:s,source:f.accountId()}));if(c){if(!l)throw Error("clientSigningKey is required if clientDomain is provided");h.addOperation(i.Operation.manageData({name:"client_domain",value:c,source:l}))}u&&h.addMemo(i.Memo.id(u));var y=h.build();return y.sign(e),y.toEnvelope().toXDR("base64").toString()}function _(e,t,r,n,o){var s,u;if(t.startsWith("M"))throw Error("Invalid serverAccountID: multiplexed accounts are not supported.");try{u=new i.Transaction(e,r)}catch(t){try{u=new i.FeeBumpTransaction(e,r)}catch(e){throw new y("Invalid challenge: unable to deserialize challengeTx transaction string")}throw new y("Invalid challenge: expected a Transaction but received a FeeBumpTransaction")}if(0!==Number.parseInt(u.sequence,10))throw new y("The transaction sequence number should be zero");if(u.source!==t)throw new y("The transaction source account is not equal to the server's account");if(u.operations.length<1)throw new y("The transaction should contain at least one operation");var c=w(u.operations),l=c[0],f=c.slice(1);if(!l.source)throw new y("The transaction's operation should contain a source account");var p,d=l.source,h=null;if(u.memo.type!==i.MemoNone){if(d.startsWith("M"))throw new y("The transaction has a memo but the client account ID is a muxed account");if(u.memo.type!==i.MemoID)throw new y("The transaction's memo must be of type `id`");h=u.memo.value}if("manageData"!==l.type)throw new y("The transaction's operation type should be 'manageData'");if(u.timeBounds&&Number.parseInt(null===(s=u.timeBounds)||void 0===s?void 0:s.maxTime,10)===i.TimeoutInfinite)throw new y("The transaction requires non-infinite timebounds");if(!a.A.validateTimebounds(u,300))throw new y("The transaction has expired");if(void 0===l.value)throw new y("The transaction's operation values should not be null");if(!l.value)throw new y("The transaction's operation value should not be null");if(48!==m.from(l.value.toString(),"base64").length)throw new y("The transaction's operation value should be a 64 bytes base64 random string");if(!n)throw new y("Invalid homeDomains: a home domain must be provided for verification");if("string"==typeof n)"".concat(n," auth")===l.name&&(p=n);else{if(!Array.isArray(n))throw new y("Invalid homeDomains: homeDomains type is ".concat(b(n)," but should be a string or an array"));p=n.find((function(e){return"".concat(e," auth")===l.name}))}if(!p)throw new y("Invalid homeDomains: the transaction's operation key name does not match the expected home domain");var v,S=g(f);try{for(S.s();!(v=S.n()).done;){var k=v.value;if("manageData"!==k.type)throw new y("The transaction has operations that are not of type 'manageData'");if(k.source!==t&&"client_domain"!==k.name)throw new y("The transaction has operations that are unrecognized");if("web_auth_domain"===k.name){if(void 0===k.value)throw new y("'web_auth_domain' operation value should not be null");if(k.value.compare(m.from(o)))throw new y("'web_auth_domain' operation value does not match ".concat(o))}}}catch(e){S.e(e)}finally{S.f()}if(!A(u,t))throw new y("Transaction not signed by server: '".concat(t,"'"));return{tx:u,clientAccountID:d,matchedHomeDomain:p,memo:h}}function O(e,t,r,n,o,i,a){for(var s=x(e,t,r,o.map((function(e){return e.key})),i,a),u=0,c=function(){var e,t=f[l],r=(null===(e=o.find((function(e){return e.key===t})))||void 0===e?void 0:e.weight)||0;u+=r},l=0,f=s;l{"use strict";var r=function(e,t){return t||(t={}),e.split("").forEach((function(e,r){e in t||(t[e]=r)})),t},n={alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",charmap:{0:14,1:8}};n.charmap=r(n.alphabet,n.charmap);var o={alphabet:"0123456789ABCDEFGHJKMNPQRSTVWXYZ",charmap:{O:0,I:1,L:1}};o.charmap=r(o.alphabet,o.charmap);var i={alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",charmap:{}};function a(e){if(this.buf=[],this.shift=8,this.carry=0,e){switch(e.type){case"rfc4648":this.charmap=t.rfc4648.charmap;break;case"crockford":this.charmap=t.crockford.charmap;break;case"base32hex":this.charmap=t.base32hex.charmap;break;default:throw new Error("invalid type")}e.charmap&&(this.charmap=e.charmap)}}function s(e){if(this.buf="",this.shift=3,this.carry=0,e){switch(e.type){case"rfc4648":this.alphabet=t.rfc4648.alphabet;break;case"crockford":this.alphabet=t.crockford.alphabet;break;case"base32hex":this.alphabet=t.base32hex.alphabet;break;default:throw new Error("invalid type")}e.alphabet?this.alphabet=e.alphabet:e.lc&&(this.alphabet=this.alphabet.toLowerCase())}}i.charmap=r(i.alphabet,i.charmap),a.prototype.charmap=n.charmap,a.prototype.write=function(e){var t=this.charmap,r=this.buf,n=this.shift,o=this.carry;return e.toUpperCase().split("").forEach((function(e){if("="!=e){var i=255&t[e];(n-=5)>0?o|=i<>-n),o=i<<(n+=8)&255):(r.push(o|i),n=8,o=0)}})),this.shift=n,this.carry=o,this},a.prototype.finalize=function(e){return e&&this.write(e),8!==this.shift&&0!==this.carry&&(this.buf.push(this.carry),this.shift=8,this.carry=0),this.buf},s.prototype.alphabet=n.alphabet,s.prototype.write=function(e){var t,r,n,o=this.shift,i=this.carry;for(n=0;n>o,this.buf+=this.alphabet[31&t],o>5&&(t=r>>(o-=5),this.buf+=this.alphabet[31&t]),i=r<<(o=5-o),o=8-o;return this.shift=o,this.carry=i,this},s.prototype.finalize=function(e){return e&&this.write(e),3!==this.shift&&(this.buf+=this.alphabet[31&this.carry],this.shift=3,this.carry=0),this.buf},t.encode=function(e,t){return new s(t).finalize(e)},t.decode=function(e,t){return new a(t).finalize(e)},t.Decoder=a,t.Encoder=s,t.charmap=r,t.crockford=o,t.rfc4648=n,t.base32hex=i},7526:(e,t)=>{"use strict";t.byteLength=function(e){var t=s(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,i=s(e),a=i[0],u=i[1],c=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,u)),l=0,f=u>0?a-4:a;for(r=0;r>16&255,c[l++]=t>>8&255,c[l++]=255&t;2===u&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,c[l++]=255&t);1===u&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t);return c},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],a=16383,s=0,c=n-o;sc?c:s+a));1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return i.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)r[a]=i[a],n[i.charCodeAt(a)]=a;function s(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,n){for(var o,i,a=[],s=t;s>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return a.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},1594:function(e,t,r){var n;!function(){"use strict";var o,i=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,a=Math.ceil,s=Math.floor,u="[BigNumber Error] ",c=u+"Number primitive has more than 15 significant digits: ",l=1e14,f=14,p=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],h=1e7,y=1e9;function m(e){var t=0|e;return e>0||e===t?t:t-1}function v(e){for(var t,r,n=1,o=e.length,i=e[0]+"";nc^r?1:-1;for(s=(u=o.length)<(c=i.length)?u:c,a=0;ai[a]^r?1:-1;return u==c?0:u>c^r?1:-1}function b(e,t,r,n){if(er||e!==s(e))throw Error(u+(n||"Argument")+("number"==typeof e?er?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function w(e){var t=e.c.length-1;return m(e.e/f)==t&&e.c[t]%2!=0}function S(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function k(e,t,r){var n,o;if(t<0){for(o=r+".";++t;o+=r);e=o+e}else if(++t>(n=e.length)){for(o=r,t-=n;--t;o+=r);e+=o}else tU?v.c=v.e=null:e.e=10;d/=10,l++);return void(l>U?v.c=v.e=null:(v.e=l,v.c=[e]))}m=String(e)}else{if(!i.test(m=String(e)))return o(v,m,h);v.s=45==m.charCodeAt(0)?(m=m.slice(1),-1):1}(l=m.indexOf("."))>-1&&(m=m.replace(".","")),(d=m.search(/e/i))>0?(l<0&&(l=d),l+=+m.slice(d+1),m=m.substring(0,d)):l<0&&(l=m.length)}else{if(b(t,2,q.length,"Base"),10==t&&K)return $(v=new H(e),C+v.e+1,j);if(m=String(e),h="number"==typeof e){if(0*e!=0)return o(v,m,h,t);if(v.s=1/e<0?(m=m.slice(1),-1):1,H.DEBUG&&m.replace(/^0\.0*|\./,"").length>15)throw Error(c+e)}else v.s=45===m.charCodeAt(0)?(m=m.slice(1),-1):1;for(r=q.slice(0,t),l=d=0,y=m.length;dl){l=y;continue}}else if(!u&&(m==m.toUpperCase()&&(m=m.toLowerCase())||m==m.toLowerCase()&&(m=m.toUpperCase()))){u=!0,d=-1,l=0;continue}return o(v,String(e),h,t)}h=!1,(l=(m=n(m,t,10,v.s)).indexOf("."))>-1?m=m.replace(".",""):l=m.length}for(d=0;48===m.charCodeAt(d);d++);for(y=m.length;48===m.charCodeAt(--y););if(m=m.slice(d,++y)){if(y-=d,h&&H.DEBUG&&y>15&&(e>p||e!==s(e)))throw Error(c+v.s*e);if((l=l-d-1)>U)v.c=v.e=null;else if(l=L)?S(u,a):k(u,a,"0");else if(i=(e=$(new H(e),t,r)).e,s=(u=v(e.c)).length,1==n||2==n&&(t<=i||i<=B)){for(;ss){if(--t>0)for(u+=".";t--;u+="0");}else if((t+=i-s)>0)for(i+1==s&&(u+=".");t--;u+="0");return e.s<0&&o?"-"+u:u}function X(e,t){for(var r,n,o=1,i=new H(e[0]);o=10;o/=10,n++);return(r=n+r*f-1)>U?e.c=e.e=null:r=10;c/=10,o++);if((i=t-o)<0)i+=f,u=t,p=m[h=0],y=s(p/v[o-u-1]%10);else if((h=a((i+1)/f))>=m.length){if(!n)break e;for(;m.length<=h;m.push(0));p=y=0,o=1,u=(i%=f)-f+1}else{for(p=c=m[h],o=1;c>=10;c/=10,o++);y=(u=(i%=f)-f+o)<0?0:s(p/v[o-u-1]%10)}if(n=n||t<0||null!=m[h+1]||(u<0?p:p%v[o-u-1]),n=r<4?(y||n)&&(0==r||r==(e.s<0?3:2)):y>5||5==y&&(4==r||n||6==r&&(i>0?u>0?p/v[o-u]:0:m[h-1])%10&1||r==(e.s<0?8:7)),t<1||!m[0])return m.length=0,n?(t-=e.e+1,m[0]=v[(f-t%f)%f],e.e=-t||0):m[0]=e.e=0,e;if(0==i?(m.length=h,c=1,h--):(m.length=h+1,c=v[f-i],m[h]=u>0?s(p/v[o-u]%v[u])*c:0),n)for(;;){if(0==h){for(i=1,u=m[0];u>=10;u/=10,i++);for(u=m[0]+=c,c=1;u>=10;u/=10,c++);i!=c&&(e.e++,m[0]==l&&(m[0]=1));break}if(m[h]+=c,m[h]!=l)break;m[h--]=0,c=1}for(i=m.length;0===m[--i];m.pop());}e.e>U?e.c=e.e=null:e.e=L?S(t,r):k(t,r,"0"),e.s<0?"-"+t:t)}return H.clone=e,H.ROUND_UP=0,H.ROUND_DOWN=1,H.ROUND_CEIL=2,H.ROUND_FLOOR=3,H.ROUND_HALF_UP=4,H.ROUND_HALF_DOWN=5,H.ROUND_HALF_EVEN=6,H.ROUND_HALF_CEIL=7,H.ROUND_HALF_FLOOR=8,H.EUCLID=9,H.config=H.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(u+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(b(r=e[t],0,y,t),C=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(b(r=e[t],0,8,t),j=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(b(r[0],-y,0,t),b(r[1],0,y,t),B=r[0],L=r[1]):(b(r,-y,y,t),B=-(L=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)b(r[0],-y,-1,t),b(r[1],1,y,t),N=r[0],U=r[1];else{if(b(r,-y,y,t),!r)throw Error(u+t+" cannot be zero: "+r);N=-(U=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(u+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw M=!r,Error(u+"crypto unavailable");M=r}else M=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(b(r=e[t],0,9,t),F=r),e.hasOwnProperty(t="POW_PRECISION")&&(b(r=e[t],0,y,t),D=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(u+t+" not an object: "+r);V=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(u+t+" invalid: "+r);K="0123456789"==r.slice(0,10),q=r}}return{DECIMAL_PLACES:C,ROUNDING_MODE:j,EXPONENTIAL_AT:[B,L],RANGE:[N,U],CRYPTO:M,MODULO_MODE:F,POW_PRECISION:D,FORMAT:V,ALPHABET:q}},H.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!H.DEBUG)return!0;var t,r,n=e.c,o=e.e,i=e.s;e:if("[object Array]"=={}.toString.call(n)){if((1===i||-1===i)&&o>=-y&&o<=y&&o===s(o)){if(0===n[0]){if(0===o&&1===n.length)return!0;break e}if((t=(o+1)%f)<1&&(t+=f),String(n[0]).length==t){for(t=0;t=l||r!==s(r))break e;if(0!==r)return!0}}}else if(null===n&&null===o&&(null===i||1===i||-1===i))return!0;throw Error(u+"Invalid BigNumber: "+e)},H.maximum=H.max=function(){return X(arguments,-1)},H.minimum=H.min=function(){return X(arguments,1)},H.random=(E=9007199254740992,T=Math.random()*E&2097151?function(){return s(Math.random()*E)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,n,o,i,c=0,l=[],p=new H(I);if(null==e?e=C:b(e,0,y),o=a(e/f),M)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(o*=2));c>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[c]=r[0],t[c+1]=r[1]):(l.push(i%1e14),c+=2);c=o/2}else{if(!crypto.randomBytes)throw M=!1,Error(u+"crypto unavailable");for(t=crypto.randomBytes(o*=7);c=9e15?crypto.randomBytes(7).copy(t,c):(l.push(i%1e14),c+=7);c=o/7}if(!M)for(;c=10;i/=10,c++);cr-1&&(null==a[o+1]&&(a[o+1]=0),a[o+1]+=a[o]/r|0,a[o]%=r)}return a.reverse()}return function(n,o,i,a,s){var u,c,l,f,p,d,h,y,m=n.indexOf("."),g=C,b=j;for(m>=0&&(f=D,D=0,n=n.replace(".",""),d=(y=new H(o)).pow(n.length-m),D=f,y.c=t(k(v(d.c),d.e,"0"),10,i,e),y.e=y.c.length),l=f=(h=t(n,o,i,s?(u=q,e):(u=e,q))).length;0==h[--f];h.pop());if(!h[0])return u.charAt(0);if(m<0?--l:(d.c=h,d.e=l,d.s=a,h=(d=r(d,y,g,b,i)).c,p=d.r,l=d.e),m=h[c=l+g+1],f=i/2,p=p||c<0||null!=h[c+1],p=b<4?(null!=m||p)&&(0==b||b==(d.s<0?3:2)):m>f||m==f&&(4==b||p||6==b&&1&h[c-1]||b==(d.s<0?8:7)),c<1||!h[0])n=p?k(u.charAt(1),-g,u.charAt(0)):u.charAt(0);else{if(h.length=c,p)for(--i;++h[--c]>i;)h[c]=0,c||(++l,h=[1].concat(h));for(f=h.length;!h[--f];);for(m=0,n="";m<=f;n+=u.charAt(h[m++]));n=k(n,l,u.charAt(0))}return n}}(),r=function(){function e(e,t,r){var n,o,i,a,s=0,u=e.length,c=t%h,l=t/h|0;for(e=e.slice();u--;)s=((o=c*(i=e[u]%h)+(n=l*i+(a=e[u]/h|0)*c)%h*h+s)/r|0)+(n/h|0)+l*a,e[u]=o%r;return s&&(e=[s].concat(e)),e}function t(e,t,r,n){var o,i;if(r!=n)i=r>n?1:-1;else for(o=i=0;ot[o]?1:-1;break}return i}function r(e,t,r,n){for(var o=0;r--;)e[r]-=o,o=e[r]1;e.splice(0,1));}return function(n,o,i,a,u){var c,p,d,h,y,v,g,b,w,S,k,E,T,_,O,x,A,P=n.s==o.s?1:-1,R=n.c,I=o.c;if(!(R&&R[0]&&I&&I[0]))return new H(n.s&&o.s&&(R?!I||R[0]!=I[0]:I)?R&&0==R[0]||!I?0*P:P/0:NaN);for(w=(b=new H(P)).c=[],P=i+(p=n.e-o.e)+1,u||(u=l,p=m(n.e/f)-m(o.e/f),P=P/f|0),d=0;I[d]==(R[d]||0);d++);if(I[d]>(R[d]||0)&&p--,P<0)w.push(1),h=!0;else{for(_=R.length,x=I.length,d=0,P+=2,(y=s(u/(I[0]+1)))>1&&(I=e(I,y,u),R=e(R,y,u),x=I.length,_=R.length),T=x,k=(S=R.slice(0,x)).length;k=u/2&&O++;do{if(y=0,(c=t(I,S,x,k))<0){if(E=S[0],x!=k&&(E=E*u+(S[1]||0)),(y=s(E/O))>1)for(y>=u&&(y=u-1),g=(v=e(I,y,u)).length,k=S.length;1==t(v,S,g,k);)y--,r(v,x=10;P/=10,d++);$(b,i+(b.e=d+p*f-1)+1,a,h)}else b.e=p,b.r=+h;return b}}(),_=/^(-?)0([xbo])(?=\w[\w.]*$)/i,O=/^([^.]+)\.$/,x=/^\.([^.]+)$/,A=/^-?(Infinity|NaN)$/,P=/^\s*\+(?=[\w.])|^\s+|\s+$/g,o=function(e,t,r,n){var o,i=r?t:t.replace(P,"");if(A.test(i))e.s=isNaN(i)?null:i<0?-1:1;else{if(!r&&(i=i.replace(_,(function(e,t,r){return o="x"==(r=r.toLowerCase())?16:"b"==r?2:8,n&&n!=o?e:t})),n&&(o=n,i=i.replace(O,"$1").replace(x,"0.$1")),t!=i))return new H(i,o);if(H.DEBUG)throw Error(u+"Not a"+(n?" base "+n:"")+" number: "+t);e.s=null}e.c=e.e=null},R.absoluteValue=R.abs=function(){var e=new H(this);return e.s<0&&(e.s=1),e},R.comparedTo=function(e,t){return g(this,new H(e,t))},R.decimalPlaces=R.dp=function(e,t){var r,n,o,i=this;if(null!=e)return b(e,0,y),null==t?t=j:b(t,0,8),$(new H(i),e+i.e+1,t);if(!(r=i.c))return null;if(n=((o=r.length-1)-m(this.e/f))*f,o=r[o])for(;o%10==0;o/=10,n--);return n<0&&(n=0),n},R.dividedBy=R.div=function(e,t){return r(this,new H(e,t),C,j)},R.dividedToIntegerBy=R.idiv=function(e,t){return r(this,new H(e,t),0,1)},R.exponentiatedBy=R.pow=function(e,t){var r,n,o,i,c,l,p,d,h=this;if((e=new H(e)).c&&!e.isInteger())throw Error(u+"Exponent not an integer: "+Q(e));if(null!=t&&(t=new H(t)),c=e.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!e.c||!e.c[0])return d=new H(Math.pow(+Q(h),c?e.s*(2-w(e)):+Q(e))),t?d.mod(t):d;if(l=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new H(NaN);(n=!l&&h.isInteger()&&t.isInteger())&&(h=h.mod(t))}else{if(e.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||c&&h.c[1]>=24e7:h.c[0]<8e13||c&&h.c[0]<=9999975e7)))return i=h.s<0&&w(e)?-0:0,h.e>-1&&(i=1/i),new H(l?1/i:i);D&&(i=a(D/f+2))}for(c?(r=new H(.5),l&&(e.s=1),p=w(e)):p=(o=Math.abs(+Q(e)))%2,d=new H(I);;){if(p){if(!(d=d.times(h)).c)break;i?d.c.length>i&&(d.c.length=i):n&&(d=d.mod(t))}if(o){if(0===(o=s(o/2)))break;p=o%2}else if($(e=e.times(r),e.e+1,1),e.e>14)p=w(e);else{if(0===(o=+Q(e)))break;p=o%2}h=h.times(h),i?h.c&&h.c.length>i&&(h.c.length=i):n&&(h=h.mod(t))}return n?d:(l&&(d=I.div(d)),t?d.mod(t):i?$(d,D,j,undefined):d)},R.integerValue=function(e){var t=new H(this);return null==e?e=j:b(e,0,8),$(t,t.e+1,e)},R.isEqualTo=R.eq=function(e,t){return 0===g(this,new H(e,t))},R.isFinite=function(){return!!this.c},R.isGreaterThan=R.gt=function(e,t){return g(this,new H(e,t))>0},R.isGreaterThanOrEqualTo=R.gte=function(e,t){return 1===(t=g(this,new H(e,t)))||0===t},R.isInteger=function(){return!!this.c&&m(this.e/f)>this.c.length-2},R.isLessThan=R.lt=function(e,t){return g(this,new H(e,t))<0},R.isLessThanOrEqualTo=R.lte=function(e,t){return-1===(t=g(this,new H(e,t)))||0===t},R.isNaN=function(){return!this.s},R.isNegative=function(){return this.s<0},R.isPositive=function(){return this.s>0},R.isZero=function(){return!!this.c&&0==this.c[0]},R.minus=function(e,t){var r,n,o,i,a=this,s=a.s;if(t=(e=new H(e,t)).s,!s||!t)return new H(NaN);if(s!=t)return e.s=-t,a.plus(e);var u=a.e/f,c=e.e/f,p=a.c,d=e.c;if(!u||!c){if(!p||!d)return p?(e.s=-t,e):new H(d?a:NaN);if(!p[0]||!d[0])return d[0]?(e.s=-t,e):new H(p[0]?a:3==j?-0:0)}if(u=m(u),c=m(c),p=p.slice(),s=u-c){for((i=s<0)?(s=-s,o=p):(c=u,o=d),o.reverse(),t=s;t--;o.push(0));o.reverse()}else for(n=(i=(s=p.length)<(t=d.length))?s:t,s=t=0;t0)for(;t--;p[r++]=0);for(t=l-1;n>s;){if(p[--n]=0;){for(r=0,y=E[o]%w,v=E[o]/w|0,i=o+(a=u);i>o;)r=((c=y*(c=k[--a]%w)+(s=v*c+(p=k[a]/w|0)*y)%w*w+g[i]+r)/b|0)+(s/w|0)+v*p,g[i--]=c%b;g[i]=r}return r?++n:g.splice(0,1),G(e,g,n)},R.negated=function(){var e=new H(this);return e.s=-e.s||null,e},R.plus=function(e,t){var r,n=this,o=n.s;if(t=(e=new H(e,t)).s,!o||!t)return new H(NaN);if(o!=t)return e.s=-t,n.minus(e);var i=n.e/f,a=e.e/f,s=n.c,u=e.c;if(!i||!a){if(!s||!u)return new H(o/0);if(!s[0]||!u[0])return u[0]?e:new H(s[0]?n:0*o)}if(i=m(i),a=m(a),s=s.slice(),o=i-a){for(o>0?(a=i,r=u):(o=-o,r=s),r.reverse();o--;r.push(0));r.reverse()}for((o=s.length)-(t=u.length)<0&&(r=u,u=s,s=r,t=o),o=0;t;)o=(s[--t]=s[t]+u[t]+o)/l|0,s[t]=l===s[t]?0:s[t]%l;return o&&(s=[o].concat(s),++a),G(e,s,a)},R.precision=R.sd=function(e,t){var r,n,o,i=this;if(null!=e&&e!==!!e)return b(e,1,y),null==t?t=j:b(t,0,8),$(new H(i),e,t);if(!(r=i.c))return null;if(n=(o=r.length-1)*f+1,o=r[o]){for(;o%10==0;o/=10,n--);for(o=r[0];o>=10;o/=10,n++);}return e&&i.e+1>n&&(n=i.e+1),n},R.shiftedBy=function(e){return b(e,-9007199254740991,p),this.times("1e"+e)},R.squareRoot=R.sqrt=function(){var e,t,n,o,i,a=this,s=a.c,u=a.s,c=a.e,l=C+4,f=new H("0.5");if(1!==u||!s||!s[0])return new H(!u||u<0&&(!s||s[0])?NaN:s?a:1/0);if(0==(u=Math.sqrt(+Q(a)))||u==1/0?(((t=v(s)).length+c)%2==0&&(t+="0"),u=Math.sqrt(+t),c=m((c+1)/2)-(c<0||c%2),n=new H(t=u==1/0?"5e"+c:(t=u.toExponential()).slice(0,t.indexOf("e")+1)+c)):n=new H(u+""),n.c[0])for((u=(c=n.e)+l)<3&&(u=0);;)if(i=n,n=f.times(i.plus(r(a,i,l,1))),v(i.c).slice(0,u)===(t=v(n.c)).slice(0,u)){if(n.e0&&y>0){for(i=y%s||s,f=h.substr(0,i);i0&&(f+=l+h.slice(i)),d&&(f="-"+f)}n=p?f+(r.decimalSeparator||"")+((c=+r.fractionGroupSize)?p.replace(new RegExp("\\d{"+c+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):p):f}return(r.prefix||"")+n+(r.suffix||"")},R.toFraction=function(e){var t,n,o,i,a,s,c,l,p,h,y,m,g=this,b=g.c;if(null!=e&&(!(c=new H(e)).isInteger()&&(c.c||1!==c.s)||c.lt(I)))throw Error(u+"Argument "+(c.isInteger()?"out of range: ":"not an integer: ")+Q(c));if(!b)return new H(g);for(t=new H(I),p=n=new H(I),o=l=new H(I),m=v(b),a=t.e=m.length-g.e-1,t.c[0]=d[(s=a%f)<0?f+s:s],e=!e||c.comparedTo(t)>0?a>0?t:p:c,s=U,U=1/0,c=new H(m),l.c[0]=0;h=r(c,t,0,1),1!=(i=n.plus(h.times(o))).comparedTo(e);)n=o,o=i,p=l.plus(h.times(i=p)),l=i,t=c.minus(h.times(i=t)),c=i;return i=r(e.minus(n),o,0,1),l=l.plus(i.times(p)),n=n.plus(i.times(o)),l.s=p.s=g.s,y=r(p,o,a*=2,j).minus(g).abs().comparedTo(r(l,n,a,j).minus(g).abs())<1?[p,o]:[l,n],U=s,y},R.toNumber=function(){return+Q(this)},R.toPrecision=function(e,t){return null!=e&&b(e,1,y),z(this,e,t,2)},R.toString=function(e){var t,r=this,o=r.s,i=r.e;return null===i?o?(t="Infinity",o<0&&(t="-"+t)):t="NaN":(null==e?t=i<=B||i>=L?S(v(r.c),i):k(v(r.c),i,"0"):10===e&&K?t=k(v((r=$(new H(r),C+i+1,j)).c),r.e,"0"):(b(e,2,q.length,"Base"),t=n(k(v(r.c),i,"0"),10,e,o,!0)),o<0&&r.c[0]&&(t="-"+t)),t},R.valueOf=R.toJSON=function(){return Q(this)},R._isBigNumber=!0,null!=t&&H.set(t),H}(),o.default=o.BigNumber=o,void 0===(n=function(){return o}.call(t,r,t,e))||(e.exports=n)}()},8287:(e,t,r)=>{"use strict";const n=r(7526),o=r(251),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=u,t.SlowBuffer=function(e){+e!=e&&(e=0);return u.alloc(+e)},t.INSPECT_MAX_BYTES=50;const a=2147483647;function s(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,u.prototype),t}function u(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return f(e)}return c(e,t,r)}function c(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!u.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|y(e,t);let n=s(r);const o=n.write(e,t);o!==r&&(n=n.slice(0,o));return n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(Q(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return p(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Q(e,ArrayBuffer)||e&&Q(e.buffer,ArrayBuffer))return d(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(Q(e,SharedArrayBuffer)||e&&Q(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return u.from(n,t,r);const o=function(e){if(u.isBuffer(e)){const t=0|h(e.length),r=s(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||W(e.length)?s(0):p(e);if("Buffer"===e.type&&Array.isArray(e.data))return p(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return u.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function f(e){return l(e),s(e<0?0:0|h(e))}function p(e){const t=e.length<0?0:0|h(e.length),r=s(t);for(let n=0;n=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function y(e,t){if(u.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Q(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return X(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(o)return n?-1:X(e).length;t=(""+t).toLowerCase(),o=!0}}function m(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return R(this,t,r);case"utf8":case"utf-8":return O(this,t,r);case"ascii":return A(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return _(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function v(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function g(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),W(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,o){let i,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){let n=-1;for(i=r;is&&(r=s-u),i=r;i>=0;i--){let r=!0;for(let n=0;no&&(n=o):n=o;const i=t.length;let a;for(n>i/2&&(n=i/2),a=0;a>8,o=r%256,i.push(o),i.push(n);return i}(t,e.length-r),e,r,n)}function _(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function O(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o239?4:t>223?3:t>191?2:1;if(o+a<=r){let r,n,s,u;switch(a){case 1:t<128&&(i=t);break;case 2:r=e[o+1],128==(192&r)&&(u=(31&t)<<6|63&r,u>127&&(i=u));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(u=(15&t)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:r=e[o+1],n=e[o+2],s=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(u=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,u>65535&&u<1114112&&(i=u))}}null===i?(i=65533,a=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),o+=a}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(u.isBuffer(t)||(t=u.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!u.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},u.byteLength=y,u.prototype._isBuffer=!0,u.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(e+=" ... "),""},i&&(u.prototype[i]=u.prototype.inspect),u.prototype.compare=function(e,t,r,n,o){if(Q(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let i=(o>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0);const s=Math.min(i,a),c=this.slice(n,o),l=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let i=!1;for(;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":case"latin1":case"binary":return k(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function A(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;on)&&(r=n);let o="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function j(e,t,r,n,o,i){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function B(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function L(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r+7]=i,i>>=8,e[r+6]=i,i>>=8,e[r+5]=i,i>>=8,e[r+4]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function N(e,t,r,n,o,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function M(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,8),o.write(e,t,r,n,52,8),r+8}u.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e+--t],o=1;for(;t>0&&(o*=256);)n+=this[e+--t]*o;return n},u.prototype.readUint8=u.prototype.readUInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(o)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i=o&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=t,o=1,i=this[e+--n];for(;n>0&&(o*=256);)i+=this[e+--n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},u.prototype.readInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||C(e,4,this.length),o.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||C(e,4,this.length),o.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||C(e,8,this.length),o.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||C(e,8,this.length),o.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){j(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=1,i=0;for(this[t]=255&e;++i>>=0,r>>>=0,!n){j(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=r-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigUInt64LE=J((function(e,t=0){return B(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeBigUInt64BE=J((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);j(this,e,t,r,n-1,-n)}let o=0,i=1,a=0;for(this[t]=255&e;++o>>=0,!n){const n=Math.pow(2,8*r-1);j(this,e,t,r,n-1,-n)}let o=r-1,i=1,a=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/i|0)-a&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigInt64LE=J((function(e,t=0){return B(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeBigInt64BE=J((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return M(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return M(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function q(e,t,r,n,o,i){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new F.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){K(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||H(t,e.length-(r+1))}(n,o,i)}function K(e,t){if("number"!=typeof e)throw new F.ERR_INVALID_ARG_TYPE(t,"number",e)}function H(e,t,r){if(Math.floor(e)!==e)throw K(e,r),new F.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new F.ERR_BUFFER_OUT_OF_BOUNDS;throw new F.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}D("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),D("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),D("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=V(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=V(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const z=/[^+/0-9A-Za-z-_]/g;function X(e,t){let r;t=t||1/0;const n=e.length;let o=null;const i=[];for(let a=0;a55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function G(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function $(e,t,r,n){let o;for(o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function Q(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function W(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let o=0;o<16;++o)t[n+o]=e[r]+e[o]}return t}();function J(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},251:(e,t)=>{t.read=function(e,t,r,n,o){var i,a,s=8*o-n-1,u=(1<>1,l=-7,f=r?o-1:0,p=r?-1:1,d=e[t+f];for(f+=p,i=d&(1<<-l)-1,d>>=-l,l+=s;l>0;i=256*i+e[t+f],f+=p,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=p,l-=8);if(0===i)i=1-c;else{if(i===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),i-=c}return(d?-1:1)*a*Math.pow(2,i-n)},t.write=function(e,t,r,n,o,i){var a,s,u,c=8*i-o-1,l=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,h=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?p/u:p*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=l?(s=0,a=l):a+f>=1?(s=(t*u-1)*Math.pow(2,o),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,o),a=0));o>=8;e[r+d]=255&s,d+=h,s/=256,o-=8);for(a=a<0;e[r+d]=255&a,d+=h,a/=256,c-=8);e[r+d-h]|=128*y}},6698:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},3209:(e,t,r)=>{"use strict";var n=65536,o=4294967295;var i=r(2861).Buffer,a=r.g.crypto||r.g.msCrypto;a&&a.getRandomValues?e.exports=function(e,t){if(e>o)throw new RangeError("requested too many random bytes");var r=i.allocUnsafe(e);if(e>0)if(e>n)for(var s=0;s{var n=r(8287),o=n.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return o(e,t,r)}o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=a),a.prototype=Object.create(o.prototype),i(o,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=o(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},392:(e,t,r)=>{var n=r(2861).Buffer;function o(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}o.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=n.from(e,t));for(var r=this._block,o=this._blockSize,i=e.length,a=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,o=(r-n)/4294967296;this._block.writeUInt32BE(o,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var i=this._hash();return e?i.toString(e):i},o.prototype._update=function(){throw new Error("_update must be implemented by subclass")},e.exports=o},2802:(e,t,r)=>{var n=e.exports=function(e){e=e.toLowerCase();var t=n[e];if(!t)throw new Error(e+" is not supported (we accept pull requests)");return new t};n.sha=r(7816),n.sha1=r(3737),n.sha224=r(6710),n.sha256=r(4107),n.sha384=r(2827),n.sha512=r(2890)},7816:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,o.call(this,64,56)}function c(e){return e<<30|e>>>2}function l(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,o),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,s=0|this._d,u=0|this._e,f=0;f<16;++f)r[f]=e.readInt32BE(4*f);for(;f<80;++f)r[f]=r[f-3]^r[f-8]^r[f-14]^r[f-16];for(var p=0;p<80;++p){var d=~~(p/20),h=0|((t=n)<<5|t>>>27)+l(d,o,i,s)+u+r[p]+a[d];u=s,s=i,i=c(o),o=n,n=h}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},e.exports=u},3737:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,o.call(this,64,56)}function c(e){return e<<5|e>>>27}function l(e){return e<<30|e>>>2}function f(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,o),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,s=0|this._d,u=0|this._e,p=0;p<16;++p)r[p]=e.readInt32BE(4*p);for(;p<80;++p)r[p]=(t=r[p-3]^r[p-8]^r[p-14]^r[p-16])<<1|t>>>31;for(var d=0;d<80;++d){var h=~~(d/20),y=c(n)+f(h,o,i,s)+u+r[d]+a[h]|0;u=s,s=i,i=l(o),o=n,n=y}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},e.exports=u},6710:(e,t,r)=>{var n=r(6698),o=r(4107),i=r(392),a=r(2861).Buffer,s=new Array(64);function u(){this.init(),this._w=s,i.call(this,64,56)}n(u,o),u.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e},e.exports=u},4107:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],s=new Array(64);function u(){this.init(),this._w=s,o.call(this,64,56)}function c(e,t,r){return r^e&(t^r)}function l(e,t,r){return e&t|r&(e|t)}function f(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function p(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function d(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}n(u,o),u.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,s=0|this._d,u=0|this._e,h=0|this._f,y=0|this._g,m=0|this._h,v=0;v<16;++v)r[v]=e.readInt32BE(4*v);for(;v<64;++v)r[v]=0|(((t=r[v-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+r[v-7]+d(r[v-15])+r[v-16];for(var g=0;g<64;++g){var b=m+p(u)+c(u,h,y)+a[g]+r[g]|0,w=f(n)+l(n,o,i)|0;m=y,y=h,h=u,u=s+b|0,s=i,i=o,o=n,n=b+w|0}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0,this._f=h+this._f|0,this._g=y+this._g|0,this._h=m+this._h|0},u.prototype._hash=function(){var e=i.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},e.exports=u},2827:(e,t,r)=>{var n=r(6698),o=r(2890),i=r(392),a=r(2861).Buffer,s=new Array(160);function u(){this.init(),this._w=s,i.call(this,128,112)}n(u,o),u.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(48);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},e.exports=u},2890:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],s=new Array(160);function u(){this.init(),this._w=s,o.call(this,128,112)}function c(e,t,r){return r^e&(t^r)}function l(e,t,r){return e&t|r&(e|t)}function f(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function p(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function d(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function h(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function y(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function m(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function v(e,t){return e>>>0>>0?1:0}n(u,o),u.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},u.prototype._update=function(e){for(var t=this._w,r=0|this._ah,n=0|this._bh,o=0|this._ch,i=0|this._dh,s=0|this._eh,u=0|this._fh,g=0|this._gh,b=0|this._hh,w=0|this._al,S=0|this._bl,k=0|this._cl,E=0|this._dl,T=0|this._el,_=0|this._fl,O=0|this._gl,x=0|this._hl,A=0;A<32;A+=2)t[A]=e.readInt32BE(4*A),t[A+1]=e.readInt32BE(4*A+4);for(;A<160;A+=2){var P=t[A-30],R=t[A-30+1],I=d(P,R),C=h(R,P),j=y(P=t[A-4],R=t[A-4+1]),B=m(R,P),L=t[A-14],N=t[A-14+1],U=t[A-32],M=t[A-32+1],F=C+N|0,D=I+L+v(F,C)|0;D=(D=D+j+v(F=F+B|0,B)|0)+U+v(F=F+M|0,M)|0,t[A]=D,t[A+1]=F}for(var V=0;V<160;V+=2){D=t[V],F=t[V+1];var q=l(r,n,o),K=l(w,S,k),H=f(r,w),z=f(w,r),X=p(s,T),G=p(T,s),$=a[V],Q=a[V+1],W=c(s,u,g),Y=c(T,_,O),J=x+G|0,Z=b+X+v(J,x)|0;Z=(Z=(Z=Z+W+v(J=J+Y|0,Y)|0)+$+v(J=J+Q|0,Q)|0)+D+v(J=J+F|0,F)|0;var ee=z+K|0,te=H+q+v(ee,z)|0;b=g,x=O,g=u,O=_,u=s,_=T,s=i+Z+v(T=E+J|0,E)|0,i=o,E=k,o=n,k=S,n=r,S=w,r=Z+te+v(w=J+ee|0,J)|0}this._al=this._al+w|0,this._bl=this._bl+S|0,this._cl=this._cl+k|0,this._dl=this._dl+E|0,this._el=this._el+T|0,this._fl=this._fl+_|0,this._gl=this._gl+O|0,this._hl=this._hl+x|0,this._ah=this._ah+r+v(this._al,w)|0,this._bh=this._bh+n+v(this._bl,S)|0,this._ch=this._ch+o+v(this._cl,k)|0,this._dh=this._dh+i+v(this._dl,E)|0,this._eh=this._eh+s+v(this._el,T)|0,this._fh=this._fh+u+v(this._fl,_)|0,this._gh=this._gh+g+v(this._gl,O)|0,this._hh=this._hh+b+v(this._hl,x)|0},u.prototype._hash=function(){var e=i.allocUnsafe(64);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},e.exports=u},1293:(e,t,r)=>{var n=r(5546),o=r(2708);e.exports={parse:function(e){var t=n.parse(e.toString());return o.compile(t)}}},2708:e=>{"use strict";e.exports={compile:function(e){var t=[],r=[],n="",o=Object.create(null),i=o;return function(e){for(var t,r=0;r-1&&a("Cannot redefine existing key '"+u+"'.",o,i),(c=c[f])instanceof Array&&c.length&&l-1?'"'+e+'"':e}}}},5546:e=>{e.exports=function(){function e(e,t,r,n,o,i){this.message=e,this.expected=t,this.found=r,this.offset=n,this.line=o,this.column=i,this.name="SyntaxError"}return function(e,t){function r(){this.constructor=e}r.prototype=t.prototype,e.prototype=new r}(e,Error),{SyntaxError:e,parse:function(t){var r,n=arguments.length>1?arguments[1]:{},o={},i={start:Bt},a=Bt,s=function(){return pr},u=o,c="#",l={type:"literal",value:"#",description:'"#"'},f=void 0,p={type:"any",description:"any character"},d="[",h={type:"literal",value:"[",description:'"["'},y="]",m={type:"literal",value:"]",description:'"]"'},v=function(e){dr(hr("ObjectPath",e,Pt,Rt))},g=function(e){dr(hr("ArrayPath",e,Pt,Rt))},b=function(e,t){return e.concat(t)},w=function(e){return[e]},S=function(e){return e},k=".",E={type:"literal",value:".",description:'"."'},T="=",_={type:"literal",value:"=",description:'"="'},O=function(e,t){dr(hr("Assign",t,Pt,Rt,e))},x=function(e){return e.join("")},A=function(e){return e.value},P='"""',R={type:"literal",value:'"""',description:'"\\"\\"\\""'},I=null,C=function(e){return hr("String",e.join(""),Pt,Rt)},j='"',B={type:"literal",value:'"',description:'"\\""'},L="'''",N={type:"literal",value:"'''",description:"\"'''\""},U="'",M={type:"literal",value:"'",description:'"\'"'},F=function(e){return e},D=function(e){return e},V="\\",q={type:"literal",value:"\\",description:'"\\\\"'},K=function(){return""},H="e",z={type:"literal",value:"e",description:'"e"'},X="E",G={type:"literal",value:"E",description:'"E"'},$=function(e,t){return hr("Float",parseFloat(e+"e"+t),Pt,Rt)},Q=function(e){return hr("Float",parseFloat(e),Pt,Rt)},W="+",Y={type:"literal",value:"+",description:'"+"'},J=function(e){return e.join("")},Z="-",ee={type:"literal",value:"-",description:'"-"'},te=function(e){return"-"+e.join("")},re=function(e){return hr("Integer",parseInt(e,10),Pt,Rt)},ne="true",oe={type:"literal",value:"true",description:'"true"'},ie=function(){return hr("Boolean",!0,Pt,Rt)},ae="false",se={type:"literal",value:"false",description:'"false"'},ue=function(){return hr("Boolean",!1,Pt,Rt)},ce=function(){return hr("Array",[],Pt,Rt)},le=function(e){return hr("Array",e?[e]:[],Pt,Rt)},fe=function(e){return hr("Array",e,Pt,Rt)},pe=function(e,t){return hr("Array",e.concat(t),Pt,Rt)},de=function(e){return e},he=",",ye={type:"literal",value:",",description:'","'},me="{",ve={type:"literal",value:"{",description:'"{"'},ge="}",be={type:"literal",value:"}",description:'"}"'},we=function(e){return hr("InlineTable",e,Pt,Rt)},Se=function(e,t){return hr("InlineTableValue",t,Pt,Rt,e)},ke=function(e){return"."+e},Ee=function(e){return e.join("")},Te=":",_e={type:"literal",value:":",description:'":"'},Oe=function(e){return e.join("")},xe="T",Ae={type:"literal",value:"T",description:'"T"'},Pe="Z",Re={type:"literal",value:"Z",description:'"Z"'},Ie=function(e,t){return hr("Date",new Date(e+"T"+t+"Z"),Pt,Rt)},Ce=function(e,t){return hr("Date",new Date(e+"T"+t),Pt,Rt)},je=/^[ \t]/,Be={type:"class",value:"[ \\t]",description:"[ \\t]"},Le="\n",Ne={type:"literal",value:"\n",description:'"\\n"'},Ue="\r",Me={type:"literal",value:"\r",description:'"\\r"'},Fe=/^[0-9a-f]/i,De={type:"class",value:"[0-9a-f]i",description:"[0-9a-f]i"},Ve=/^[0-9]/,qe={type:"class",value:"[0-9]",description:"[0-9]"},Ke="_",He={type:"literal",value:"_",description:'"_"'},ze=function(){return""},Xe=/^[A-Za-z0-9_\-]/,Ge={type:"class",value:"[A-Za-z0-9_\\-]",description:"[A-Za-z0-9_\\-]"},$e=function(e){return e.join("")},Qe='\\"',We={type:"literal",value:'\\"',description:'"\\\\\\""'},Ye=function(){return'"'},Je="\\\\",Ze={type:"literal",value:"\\\\",description:'"\\\\\\\\"'},et=function(){return"\\"},tt="\\b",rt={type:"literal",value:"\\b",description:'"\\\\b"'},nt=function(){return"\b"},ot="\\t",it={type:"literal",value:"\\t",description:'"\\\\t"'},at=function(){return"\t"},st="\\n",ut={type:"literal",value:"\\n",description:'"\\\\n"'},ct=function(){return"\n"},lt="\\f",ft={type:"literal",value:"\\f",description:'"\\\\f"'},pt=function(){return"\f"},dt="\\r",ht={type:"literal",value:"\\r",description:'"\\\\r"'},yt=function(){return"\r"},mt="\\U",vt={type:"literal",value:"\\U",description:'"\\\\U"'},gt=function(e){return function(e,t,r){var n=parseInt("0x"+e);if(!(!isFinite(n)||Math.floor(n)!=n||n<0||n>1114111||n>55295&&n<57344))return function(){var e,t,r=16384,n=[],o=-1,i=arguments.length;if(!i)return"";var a="";for(;++o>10),t=s%1024+56320,n.push(e,t)),(o+1==i||n.length>r)&&(a+=String.fromCharCode.apply(null,n),n.length=0)}return a}(n);!function(e,t,r){var n=new Error(e);throw n.line=t,n.column=r,n}("Invalid Unicode escape code: "+e,t,r)}(e.join(""))},bt="\\u",wt={type:"literal",value:"\\u",description:'"\\\\u"'},St=0,kt=0,Et=0,Tt={line:1,column:1,seenCR:!1},_t=0,Ot=[],xt=0,At={};if("startRule"in n){if(!(n.startRule in i))throw new Error("Can't start parsing from rule \""+n.startRule+'".');a=i[n.startRule]}function Pt(){return It(kt).line}function Rt(){return It(kt).column}function It(e){return Et!==e&&(Et>e&&(Et=0,Tt={line:1,column:1,seenCR:!1}),function(e,r,n){var o,i;for(o=r;o_t&&(_t=St,Ot=[]),Ot.push(e))}function jt(r,n,o){var i=It(o),a=ot.description?1:0}));t1?n.slice(0,-1).join(", ")+" or "+n[e.length-1]:n[0])+" but "+(t?'"'+function(e){function t(e){return e.charCodeAt(0).toString(16).toUpperCase()}return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E\x0F]/g,(function(e){return"\\x0"+t(e)})).replace(/[\x10-\x1F\x80-\xFF]/g,(function(e){return"\\x"+t(e)})).replace(/[\u0180-\u0FFF]/g,(function(e){return"\\u0"+t(e)})).replace(/[\u1080-\uFFFF]/g,(function(e){return"\\u"+t(e)}))}(t)+'"':"end of input")+" found."}(n,a),n,a,o,i.line,i.column)}function Bt(){var e,t,r,n=49*St+0,i=At[n];if(i)return St=i.nextPos,i.result;for(e=St,t=[],r=Lt();r!==o;)t.push(r),r=Lt();return t!==o&&(kt=e,t=s()),e=t,At[n]={nextPos:St,result:e},e}function Lt(){var e,r,n,i,a,s,c,l=49*St+1,f=At[l];if(f)return St=f.nextPos,f.result;for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if(n=function(){var e,r=49*St+2,n=At[r];if(n)return St=n.nextPos,n.result;e=Nt(),e===o&&(e=function(){var e,r,n,i,a,s,c=49*St+4,l=At[c];if(l)return St=l.nextPos,l.result;e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h));if(r!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o)if((i=Ut())!==o){for(a=[],s=nr();s!==o;)a.push(s),s=nr();a!==o?(93===t.charCodeAt(St)?(s=y,St++):(s=o,0===xt&&Ct(m)),s!==o?(kt=e,e=r=v(i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;return At[c]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s,c,l,f=49*St+5,p=At[f];if(p)return St=p.nextPos,p.result;e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h));if(r!==o)if(91===t.charCodeAt(St)?(n=d,St++):(n=o,0===xt&&Ct(h)),n!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if((a=Ut())!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();s!==o?(93===t.charCodeAt(St)?(c=y,St++):(c=o,0===xt&&Ct(m)),c!==o?(93===t.charCodeAt(St)?(l=y,St++):(l=o,0===xt&&Ct(m)),l!==o?(kt=e,e=r=g(a)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u;return At[f]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s,c=49*St+9,l=At[c];if(l)return St=l.nextPos,l.result;if(e=St,r=Dt(),r!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o)if(61===t.charCodeAt(St)?(i=T,St++):(i=o,0===xt&&Ct(_)),i!==o){for(a=[],s=nr();s!==o;)a.push(s),s=nr();a!==o&&(s=qt())!==o?(kt=e,e=r=O(r,s)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;if(e===o)if(e=St,(r=Vt())!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o)if(61===t.charCodeAt(St)?(i=T,St++):(i=o,0===xt&&Ct(_)),i!==o){for(a=[],s=nr();s!==o;)a.push(s),s=nr();a!==o&&(s=qt())!==o?(kt=e,e=r=O(r,s)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;return At[c]={nextPos:St,result:e},e}())));return At[r]={nextPos:St,result:e},e}(),n!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o){for(a=[],s=Nt();s!==o;)a.push(s),s=Nt();if(a!==o){if(s=[],(c=or())!==o)for(;c!==o;)s.push(c),c=or();else s=u;s===o&&(s=ar()),s!==o?e=r=[r,n,i,a,s]:(St=e,e=u)}else St=e,e=u}else St=e,e=u}else St=e,e=u;else St=e,e=u;if(e===o){if(e=St,r=[],(n=nr())!==o)for(;n!==o;)r.push(n),n=nr();else r=u;if(r!==o){if(n=[],(i=or())!==o)for(;i!==o;)n.push(i),i=or();else n=u;n===o&&(n=ar()),n!==o?e=r=[r,n]:(St=e,e=u)}else St=e,e=u;e===o&&(e=or())}return At[l]={nextPos:St,result:e},e}function Nt(){var e,r,n,i,a,s,d=49*St+3,h=At[d];if(h)return St=h.nextPos,h.result;if(e=St,35===t.charCodeAt(St)?(r=c,St++):(r=o,0===xt&&Ct(l)),r!==o){for(n=[],i=St,a=St,xt++,(s=or())===o&&(s=ar()),xt--,s===o?a=f:(St=a,a=u),a!==o?(t.length>St?(s=t.charAt(St),St++):(s=o,0===xt&&Ct(p)),s!==o?i=a=[a,s]:(St=i,i=u)):(St=i,i=u);i!==o;)n.push(i),i=St,a=St,xt++,(s=or())===o&&(s=ar()),xt--,s===o?a=f:(St=a,a=u),a!==o?(t.length>St?(s=t.charAt(St),St++):(s=o,0===xt&&Ct(p)),s!==o?i=a=[a,s]:(St=i,i=u)):(St=i,i=u);n!==o?e=r=[r,n]:(St=e,e=u)}else St=e,e=u;return At[d]={nextPos:St,result:e},e}function Ut(){var e,t,r,n=49*St+6,i=At[n];if(i)return St=i.nextPos,i.result;if(e=St,t=[],(r=Ft())!==o)for(;r!==o;)t.push(r),r=Ft();else t=u;return t!==o&&(r=Mt())!==o?(kt=e,e=t=b(t,r)):(St=e,e=u),e===o&&(e=St,(t=Mt())!==o&&(kt=e,t=w(t)),e=t),At[n]={nextPos:St,result:e},e}function Mt(){var e,t,r,n,i,a=49*St+7,s=At[a];if(s)return St=s.nextPos,s.result;for(e=St,t=[],r=nr();r!==o;)t.push(r),r=nr();if(t!==o)if((r=Dt())!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();n!==o?(kt=e,e=t=S(r)):(St=e,e=u)}else St=e,e=u;else St=e,e=u;if(e===o){for(e=St,t=[],r=nr();r!==o;)t.push(r),r=nr();if(t!==o)if((r=Vt())!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();n!==o?(kt=e,e=t=S(r)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}return At[a]={nextPos:St,result:e},e}function Ft(){var e,r,n,i,a,s,c,l=49*St+8,f=At[l];if(f)return St=f.nextPos,f.result;for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Dt())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(46===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&Ct(E)),a!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();s!==o?(kt=e,e=r=S(n)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u;if(e===o){for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Vt())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(46===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&Ct(E)),a!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();s!==o?(kt=e,e=r=S(n)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u}return At[l]={nextPos:St,result:e},e}function Dt(){var e,t,r,n=49*St+10,i=At[n];if(i)return St=i.nextPos,i.result;if(e=St,t=[],(r=cr())!==o)for(;r!==o;)t.push(r),r=cr();else t=u;return t!==o&&(kt=e,t=x(t)),e=t,At[n]={nextPos:St,result:e},e}function Vt(){var e,t,r=49*St+11,n=At[r];return n?(St=n.nextPos,n.result):(e=St,(t=Kt())!==o&&(kt=e,t=A(t)),(e=t)===o&&(e=St,(t=Ht())!==o&&(kt=e,t=A(t)),e=t),At[r]={nextPos:St,result:e},e)}function qt(){var e,r=49*St+12,n=At[r];return n?(St=n.nextPos,n.result):(e=function(){var e,r=49*St+13,n=At[r];if(n)return St=n.nextPos,n.result;e=function(){var e,r,n,i,a,s=49*St+14,c=At[s];if(c)return St=c.nextPos,c.result;e=St,t.substr(St,3)===P?(r=P,St+=3):(r=o,0===xt&&Ct(R));if(r!==o)if((n=or())===o&&(n=I),n!==o){for(i=[],a=Gt();a!==o;)i.push(a),a=Gt();i!==o?(t.substr(St,3)===P?(a=P,St+=3):(a=o,0===xt&&Ct(R)),a!==o?(kt=e,e=r=C(i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;else St=e,e=u;return At[s]={nextPos:St,result:e},e}(),e===o&&(e=Kt())===o&&(e=function(){var e,r,n,i,a,s=49*St+16,c=At[s];if(c)return St=c.nextPos,c.result;e=St,t.substr(St,3)===L?(r=L,St+=3):(r=o,0===xt&&Ct(N));if(r!==o)if((n=or())===o&&(n=I),n!==o){for(i=[],a=$t();a!==o;)i.push(a),a=$t();i!==o?(t.substr(St,3)===L?(a=L,St+=3):(a=o,0===xt&&Ct(N)),a!==o?(kt=e,e=r=C(i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;else St=e,e=u;return At[s]={nextPos:St,result:e},e}(),e===o&&(e=Ht()));return At[r]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s=49*St+38,c=At[s];if(c)return St=c.nextPos,c.result;e=St,(r=rr())!==o?(84===t.charCodeAt(St)?(n=xe,St++):(n=o,0===xt&&Ct(Ae)),n!==o?(i=function(){var e,r,n,i,a,s,c,l,f,p,d,h=49*St+36,y=At[h];if(y)return St=y.nextPos,y.result;e=St,r=St,n=ur(),n!==o&&(i=ur())!==o?(58===t.charCodeAt(St)?(a=Te,St++):(a=o,0===xt&&Ct(_e)),a!==o&&(s=ur())!==o&&(c=ur())!==o?(58===t.charCodeAt(St)?(l=Te,St++):(l=o,0===xt&&Ct(_e)),l!==o&&(f=ur())!==o&&(p=ur())!==o?((d=tr())===o&&(d=I),d!==o?r=n=[n,i,a,s,c,l,f,p,d]:(St=r,r=u)):(St=r,r=u)):(St=r,r=u)):(St=r,r=u);r!==o&&(kt=e,r=Oe(r));return e=r,At[h]={nextPos:St,result:e},e}(),i!==o?(90===t.charCodeAt(St)?(a=Pe,St++):(a=o,0===xt&&Ct(Re)),a!==o?(kt=e,e=r=Ie(r,i)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u);e===o&&(e=St,(r=rr())!==o?(84===t.charCodeAt(St)?(n=xe,St++):(n=o,0===xt&&Ct(Ae)),n!==o?(i=function(){var e,r,n,i,a,s,c,l,f,p,d,h,y,m,v,g,b,w=49*St+37,S=At[w];if(S)return St=S.nextPos,S.result;e=St,r=St,n=ur(),n!==o&&(i=ur())!==o?(58===t.charCodeAt(St)?(a=Te,St++):(a=o,0===xt&&Ct(_e)),a!==o&&(s=ur())!==o&&(c=ur())!==o?(58===t.charCodeAt(St)?(l=Te,St++):(l=o,0===xt&&Ct(_e)),l!==o&&(f=ur())!==o&&(p=ur())!==o?((d=tr())===o&&(d=I),d!==o?(45===t.charCodeAt(St)?(h=Z,St++):(h=o,0===xt&&Ct(ee)),h===o&&(43===t.charCodeAt(St)?(h=W,St++):(h=o,0===xt&&Ct(Y))),h!==o&&(y=ur())!==o&&(m=ur())!==o?(58===t.charCodeAt(St)?(v=Te,St++):(v=o,0===xt&&Ct(_e)),v!==o&&(g=ur())!==o&&(b=ur())!==o?r=n=[n,i,a,s,c,l,f,p,d,h,y,m,v,g,b]:(St=r,r=u)):(St=r,r=u)):(St=r,r=u)):(St=r,r=u)):(St=r,r=u)):(St=r,r=u);r!==o&&(kt=e,r=Oe(r));return e=r,At[w]={nextPos:St,result:e},e}(),i!==o?(kt=e,e=r=Ce(r,i)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u));return At[s]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a=49*St+23,s=At[a];if(s)return St=s.nextPos,s.result;e=St,(r=Qt())===o&&(r=Wt());r!==o?(101===t.charCodeAt(St)?(n=H,St++):(n=o,0===xt&&Ct(z)),n===o&&(69===t.charCodeAt(St)?(n=X,St++):(n=o,0===xt&&Ct(G))),n!==o&&(i=Wt())!==o?(kt=e,e=r=$(r,i)):(St=e,e=u)):(St=e,e=u);e===o&&(e=St,(r=Qt())!==o&&(kt=e,r=Q(r)),e=r);return At[a]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,t,r=49*St+25,n=At[r];if(n)return St=n.nextPos,n.result;e=St,(t=Wt())!==o&&(kt=e,t=re(t));return e=t,At[r]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n=49*St+27,i=At[n];if(i)return St=i.nextPos,i.result;e=St,t.substr(St,4)===ne?(r=ne,St+=4):(r=o,0===xt&&Ct(oe));r!==o&&(kt=e,r=ie());e=r,e===o&&(e=St,t.substr(St,5)===ae?(r=ae,St+=5):(r=o,0===xt&&Ct(se)),r!==o&&(kt=e,r=ue()),e=r);return At[n]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s=49*St+28,c=At[s];if(c)return St=c.nextPos,c.result;e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h));if(r!==o){for(n=[],i=Zt();i!==o;)n.push(i),i=Zt();n!==o?(93===t.charCodeAt(St)?(i=y,St++):(i=o,0===xt&&Ct(m)),i!==o?(kt=e,e=r=ce()):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;if(e===o&&(e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h)),r!==o?((n=Yt())===o&&(n=I),n!==o?(93===t.charCodeAt(St)?(i=y,St++):(i=o,0===xt&&Ct(m)),i!==o?(kt=e,e=r=le(n)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u),e===o)){if(e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h)),r!==o){if(n=[],(i=Jt())!==o)for(;i!==o;)n.push(i),i=Jt();else n=u;n!==o?(93===t.charCodeAt(St)?(i=y,St++):(i=o,0===xt&&Ct(m)),i!==o?(kt=e,e=r=fe(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;if(e===o)if(e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h)),r!==o){if(n=[],(i=Jt())!==o)for(;i!==o;)n.push(i),i=Jt();else n=u;n!==o&&(i=Yt())!==o?(93===t.charCodeAt(St)?(a=y,St++):(a=o,0===xt&&Ct(m)),a!==o?(kt=e,e=r=pe(n,i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u}return At[s]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s,c=49*St+32,l=At[c];if(l)return St=l.nextPos,l.result;e=St,123===t.charCodeAt(St)?(r=me,St++):(r=o,0===xt&&Ct(ve));if(r!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o){for(i=[],a=er();a!==o;)i.push(a),a=er();if(i!==o){for(a=[],s=nr();s!==o;)a.push(s),s=nr();a!==o?(125===t.charCodeAt(St)?(s=ge,St++):(s=o,0===xt&&Ct(be)),s!==o?(kt=e,e=r=we(i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u}else St=e,e=u}else St=e,e=u;return At[c]={nextPos:St,result:e},e}())))))),At[r]={nextPos:St,result:e},e)}function Kt(){var e,r,n,i,a=49*St+15,s=At[a];if(s)return St=s.nextPos,s.result;if(e=St,34===t.charCodeAt(St)?(r=j,St++):(r=o,0===xt&&Ct(B)),r!==o){for(n=[],i=zt();i!==o;)n.push(i),i=zt();n!==o?(34===t.charCodeAt(St)?(i=j,St++):(i=o,0===xt&&Ct(B)),i!==o?(kt=e,e=r=C(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;return At[a]={nextPos:St,result:e},e}function Ht(){var e,r,n,i,a=49*St+17,s=At[a];if(s)return St=s.nextPos,s.result;if(e=St,39===t.charCodeAt(St)?(r=U,St++):(r=o,0===xt&&Ct(M)),r!==o){for(n=[],i=Xt();i!==o;)n.push(i),i=Xt();n!==o?(39===t.charCodeAt(St)?(i=U,St++):(i=o,0===xt&&Ct(M)),i!==o?(kt=e,e=r=C(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;return At[a]={nextPos:St,result:e},e}function zt(){var e,r,n,i=49*St+18,a=At[i];return a?(St=a.nextPos,a.result):((e=fr())===o&&(e=St,r=St,xt++,34===t.charCodeAt(St)?(n=j,St++):(n=o,0===xt&&Ct(B)),xt--,n===o?r=f:(St=r,r=u),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&Ct(p)),n!==o?(kt=e,e=r=F(n)):(St=e,e=u)):(St=e,e=u)),At[i]={nextPos:St,result:e},e)}function Xt(){var e,r,n,i=49*St+19,a=At[i];return a?(St=a.nextPos,a.result):(e=St,r=St,xt++,39===t.charCodeAt(St)?(n=U,St++):(n=o,0===xt&&Ct(M)),xt--,n===o?r=f:(St=r,r=u),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&Ct(p)),n!==o?(kt=e,e=r=F(n)):(St=e,e=u)):(St=e,e=u),At[i]={nextPos:St,result:e},e)}function Gt(){var e,r,n,i=49*St+20,a=At[i];return a?(St=a.nextPos,a.result):((e=fr())===o&&(e=function(){var e,r,n,i,a=49*St+21,s=At[a];if(s)return St=s.nextPos,s.result;e=St,92===t.charCodeAt(St)?(r=V,St++):(r=o,0===xt&&Ct(q));if(r!==o)if(or()!==o){for(n=[],i=ir();i!==o;)n.push(i),i=ir();n!==o?(kt=e,e=r=K()):(St=e,e=u)}else St=e,e=u;else St=e,e=u;return At[a]={nextPos:St,result:e},e}(),e===o&&(e=St,r=St,xt++,t.substr(St,3)===P?(n=P,St+=3):(n=o,0===xt&&Ct(R)),xt--,n===o?r=f:(St=r,r=u),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&Ct(p)),n!==o?(kt=e,e=r=D(n)):(St=e,e=u)):(St=e,e=u))),At[i]={nextPos:St,result:e},e)}function $t(){var e,r,n,i=49*St+22,a=At[i];return a?(St=a.nextPos,a.result):(e=St,r=St,xt++,t.substr(St,3)===L?(n=L,St+=3):(n=o,0===xt&&Ct(N)),xt--,n===o?r=f:(St=r,r=u),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&Ct(p)),n!==o?(kt=e,e=r=F(n)):(St=e,e=u)):(St=e,e=u),At[i]={nextPos:St,result:e},e)}function Qt(){var e,r,n,i,a,s,c=49*St+24,l=At[c];return l?(St=l.nextPos,l.result):(e=St,43===t.charCodeAt(St)?(r=W,St++):(r=o,0===xt&&Ct(Y)),r===o&&(r=I),r!==o?(n=St,(i=lr())!==o?(46===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&Ct(E)),a!==o&&(s=lr())!==o?n=i=[i,a,s]:(St=n,n=u)):(St=n,n=u),n!==o?(kt=e,e=r=J(n)):(St=e,e=u)):(St=e,e=u),e===o&&(e=St,45===t.charCodeAt(St)?(r=Z,St++):(r=o,0===xt&&Ct(ee)),r!==o?(n=St,(i=lr())!==o?(46===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&Ct(E)),a!==o&&(s=lr())!==o?n=i=[i,a,s]:(St=n,n=u)):(St=n,n=u),n!==o?(kt=e,e=r=te(n)):(St=e,e=u)):(St=e,e=u)),At[c]={nextPos:St,result:e},e)}function Wt(){var e,r,n,i,a,s=49*St+26,c=At[s];if(c)return St=c.nextPos,c.result;if(e=St,43===t.charCodeAt(St)?(r=W,St++):(r=o,0===xt&&Ct(Y)),r===o&&(r=I),r!==o){if(n=[],(i=ur())!==o)for(;i!==o;)n.push(i),i=ur();else n=u;n!==o?(i=St,xt++,46===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&Ct(E)),xt--,a===o?i=f:(St=i,i=u),i!==o?(kt=e,e=r=J(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;if(e===o)if(e=St,45===t.charCodeAt(St)?(r=Z,St++):(r=o,0===xt&&Ct(ee)),r!==o){if(n=[],(i=ur())!==o)for(;i!==o;)n.push(i),i=ur();else n=u;n!==o?(i=St,xt++,46===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&Ct(E)),xt--,a===o?i=f:(St=i,i=u),i!==o?(kt=e,e=r=te(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;return At[s]={nextPos:St,result:e},e}function Yt(){var e,t,r,n,i,a=49*St+29,s=At[a];if(s)return St=s.nextPos,s.result;for(e=St,t=[],r=Zt();r!==o;)t.push(r),r=Zt();if(t!==o)if((r=qt())!==o){for(n=[],i=Zt();i!==o;)n.push(i),i=Zt();n!==o?(kt=e,e=t=de(r)):(St=e,e=u)}else St=e,e=u;else St=e,e=u;return At[a]={nextPos:St,result:e},e}function Jt(){var e,r,n,i,a,s,c,l=49*St+30,f=At[l];if(f)return St=f.nextPos,f.result;for(e=St,r=[],n=Zt();n!==o;)r.push(n),n=Zt();if(r!==o)if((n=qt())!==o){for(i=[],a=Zt();a!==o;)i.push(a),a=Zt();if(i!==o)if(44===t.charCodeAt(St)?(a=he,St++):(a=o,0===xt&&Ct(ye)),a!==o){for(s=[],c=Zt();c!==o;)s.push(c),c=Zt();s!==o?(kt=e,e=r=de(n)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u;return At[l]={nextPos:St,result:e},e}function Zt(){var e,t=49*St+31,r=At[t];return r?(St=r.nextPos,r.result):((e=nr())===o&&(e=or())===o&&(e=Nt()),At[t]={nextPos:St,result:e},e)}function er(){var e,r,n,i,a,s,c,l,f,p,d,h=49*St+33,y=At[h];if(y)return St=y.nextPos,y.result;for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Dt())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(61===t.charCodeAt(St)?(a=T,St++):(a=o,0===xt&&Ct(_)),a!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();if(s!==o)if((c=qt())!==o){for(l=[],f=nr();f!==o;)l.push(f),f=nr();if(l!==o)if(44===t.charCodeAt(St)?(f=he,St++):(f=o,0===xt&&Ct(ye)),f!==o){for(p=[],d=nr();d!==o;)p.push(d),d=nr();p!==o?(kt=e,e=r=Se(n,c)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u;if(e===o){for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Dt())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(61===t.charCodeAt(St)?(a=T,St++):(a=o,0===xt&&Ct(_)),a!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();s!==o&&(c=qt())!==o?(kt=e,e=r=Se(n,c)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u}return At[h]={nextPos:St,result:e},e}function tr(){var e,r,n,i=49*St+34,a=At[i];return a?(St=a.nextPos,a.result):(e=St,46===t.charCodeAt(St)?(r=k,St++):(r=o,0===xt&&Ct(E)),r!==o&&(n=lr())!==o?(kt=e,e=r=ke(n)):(St=e,e=u),At[i]={nextPos:St,result:e},e)}function rr(){var e,r,n,i,a,s,c,l,f,p,d,h,y=49*St+35,m=At[y];return m?(St=m.nextPos,m.result):(e=St,r=St,(n=ur())!==o&&(i=ur())!==o&&(a=ur())!==o&&(s=ur())!==o?(45===t.charCodeAt(St)?(c=Z,St++):(c=o,0===xt&&Ct(ee)),c!==o&&(l=ur())!==o&&(f=ur())!==o?(45===t.charCodeAt(St)?(p=Z,St++):(p=o,0===xt&&Ct(ee)),p!==o&&(d=ur())!==o&&(h=ur())!==o?r=n=[n,i,a,s,c,l,f,p,d,h]:(St=r,r=u)):(St=r,r=u)):(St=r,r=u),r!==o&&(kt=e,r=Ee(r)),e=r,At[y]={nextPos:St,result:e},e)}function nr(){var e,r=49*St+39,n=At[r];return n?(St=n.nextPos,n.result):(je.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&Ct(Be)),At[r]={nextPos:St,result:e},e)}function or(){var e,r,n,i=49*St+40,a=At[i];return a?(St=a.nextPos,a.result):(10===t.charCodeAt(St)?(e=Le,St++):(e=o,0===xt&&Ct(Ne)),e===o&&(e=St,13===t.charCodeAt(St)?(r=Ue,St++):(r=o,0===xt&&Ct(Me)),r!==o?(10===t.charCodeAt(St)?(n=Le,St++):(n=o,0===xt&&Ct(Ne)),n!==o?e=r=[r,n]:(St=e,e=u)):(St=e,e=u)),At[i]={nextPos:St,result:e},e)}function ir(){var e,t=49*St+41,r=At[t];return r?(St=r.nextPos,r.result):((e=or())===o&&(e=nr()),At[t]={nextPos:St,result:e},e)}function ar(){var e,r,n=49*St+42,i=At[n];return i?(St=i.nextPos,i.result):(e=St,xt++,t.length>St?(r=t.charAt(St),St++):(r=o,0===xt&&Ct(p)),xt--,r===o?e=f:(St=e,e=u),At[n]={nextPos:St,result:e},e)}function sr(){var e,r=49*St+43,n=At[r];return n?(St=n.nextPos,n.result):(Fe.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&Ct(De)),At[r]={nextPos:St,result:e},e)}function ur(){var e,r,n=49*St+44,i=At[n];return i?(St=i.nextPos,i.result):(Ve.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&Ct(qe)),e===o&&(e=St,95===t.charCodeAt(St)?(r=Ke,St++):(r=o,0===xt&&Ct(He)),r!==o&&(kt=e,r=ze()),e=r),At[n]={nextPos:St,result:e},e)}function cr(){var e,r=49*St+45,n=At[r];return n?(St=n.nextPos,n.result):(Xe.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&Ct(Ge)),At[r]={nextPos:St,result:e},e)}function lr(){var e,t,r,n=49*St+46,i=At[n];if(i)return St=i.nextPos,i.result;if(e=St,t=[],(r=ur())!==o)for(;r!==o;)t.push(r),r=ur();else t=u;return t!==o&&(kt=e,t=$e(t)),e=t,At[n]={nextPos:St,result:e},e}function fr(){var e,r,n=49*St+47,i=At[n];return i?(St=i.nextPos,i.result):(e=St,t.substr(St,2)===Qe?(r=Qe,St+=2):(r=o,0===xt&&Ct(We)),r!==o&&(kt=e,r=Ye()),(e=r)===o&&(e=St,t.substr(St,2)===Je?(r=Je,St+=2):(r=o,0===xt&&Ct(Ze)),r!==o&&(kt=e,r=et()),(e=r)===o&&(e=St,t.substr(St,2)===tt?(r=tt,St+=2):(r=o,0===xt&&Ct(rt)),r!==o&&(kt=e,r=nt()),(e=r)===o&&(e=St,t.substr(St,2)===ot?(r=ot,St+=2):(r=o,0===xt&&Ct(it)),r!==o&&(kt=e,r=at()),(e=r)===o&&(e=St,t.substr(St,2)===st?(r=st,St+=2):(r=o,0===xt&&Ct(ut)),r!==o&&(kt=e,r=ct()),(e=r)===o&&(e=St,t.substr(St,2)===lt?(r=lt,St+=2):(r=o,0===xt&&Ct(ft)),r!==o&&(kt=e,r=pt()),(e=r)===o&&(e=St,t.substr(St,2)===dt?(r=dt,St+=2):(r=o,0===xt&&Ct(ht)),r!==o&&(kt=e,r=yt()),(e=r)===o&&(e=function(){var e,r,n,i,a,s,c,l,f,p,d,h=49*St+48,y=At[h];if(y)return St=y.nextPos,y.result;e=St,t.substr(St,2)===mt?(r=mt,St+=2):(r=o,0===xt&&Ct(vt));r!==o?(n=St,(i=sr())!==o&&(a=sr())!==o&&(s=sr())!==o&&(c=sr())!==o&&(l=sr())!==o&&(f=sr())!==o&&(p=sr())!==o&&(d=sr())!==o?n=i=[i,a,s,c,l,f,p,d]:(St=n,n=u),n!==o?(kt=e,e=r=gt(n)):(St=e,e=u)):(St=e,e=u);e===o&&(e=St,t.substr(St,2)===bt?(r=bt,St+=2):(r=o,0===xt&&Ct(wt)),r!==o?(n=St,(i=sr())!==o&&(a=sr())!==o&&(s=sr())!==o&&(c=sr())!==o?n=i=[i,a,s,c]:(St=n,n=u),n!==o?(kt=e,e=r=gt(n)):(St=e,e=u)):(St=e,e=u));return At[h]={nextPos:St,result:e},e}()))))))),At[n]={nextPos:St,result:e},e)}var pr=[];function dr(e){pr.push(e)}function hr(e,t,r,n,o){var i={type:e,value:t,line:r(),column:n()};return o&&(i.key=o),i}if((r=a())!==o&&St===t.length)return r;throw r!==o&&St1);s++)r.splice(0,1);n[a]=r.join("")}var u=-1,c=0,l=0,f=-1,p=!1;for(a=0;ac&&(u=f,c=l)):"0"===n[a]&&(p=!0,f=a,l=1);l>c&&(u=f,c=l),c>1&&n.splice(u,c,""),o=n.length;var d="";for(""===n[0]&&(d=":"),a=0;a=e.length-1)return!1;var n=e.lastIndexOf(".",t-1);if(n<=0||n>=t-1)return!1;var o=r.list[e.slice(t+1)];return!!o&&o.indexOf(" "+e.slice(n+1,t)+" ")>=0},is:function(e){var t=e.lastIndexOf(".");if(t<=0||t>=e.length-1)return!1;if(e.lastIndexOf(".",t-1)>=0)return!1;var n=r.list[e.slice(t+1)];return!!n&&n.indexOf(" "+e.slice(0,t)+" ")>=0},get:function(e){var t=e.lastIndexOf(".");if(t<=0||t>=e.length-1)return null;var n=e.lastIndexOf(".",t-1);if(n<=0||n>=t-1)return null;var o=r.list[e.slice(t+1)];return o?o.indexOf(" "+e.slice(n+1,t)+" ")<0?null:e.slice(n+1):null},noConflict:function(){return e.SecondLevelDomains===this&&(e.SecondLevelDomains=t),this}};return r}))},4193:function(e,t,r){var n,o,i;!function(a,s){"use strict";e.exports?e.exports=s(r(9340),r(1430),r(4704)):(o=[r(9340),r(1430),r(4704)],void 0===(i="function"==typeof(n=s)?n.apply(t,o):n)||(e.exports=i))}(0,(function(e,t,r,n){"use strict";var o=n&&n.URI;function i(e,t){var r=arguments.length>=1;if(!(this instanceof i))return r?arguments.length>=2?new i(e,t):new i(e):new i;if(void 0===e){if(r)throw new TypeError("undefined is not a valid argument for URI");e="undefined"!=typeof location?location.href+"":""}if(null===e&&r)throw new TypeError("null is not a valid argument for URI");return this.href(e),void 0!==t?this.absoluteTo(t):this}i.version="1.19.11";var a=i.prototype,s=Object.prototype.hasOwnProperty;function u(e){return e.replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")}function c(e){return void 0===e?"Undefined":String(Object.prototype.toString.call(e)).slice(8,-1)}function l(e){return"Array"===c(e)}function f(e,t){var r,n,o={};if("RegExp"===c(t))o=null;else if(l(t))for(r=0,n=t.length;r]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?\xab\xbb\u201c\u201d\u2018\u2019]))/gi,i.findUri={start:/\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,end:/[\s\r\n]|$/,trim:/[`!()\[\]{};:'".,<>?\xab\xbb\u201c\u201d\u201e\u2018\u2019]+$/,parens:/(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g},i.leading_whitespace_expression=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,i.ascii_tab_whitespace=/[\u0009\u000A\u000D]+/g,i.defaultPorts={http:"80",https:"443",ftp:"21",gopher:"70",ws:"80",wss:"443"},i.hostProtocols=["http","https"],i.invalid_hostname_characters=/[^a-zA-Z0-9\.\-:_]/,i.domAttributes={a:"href",blockquote:"cite",link:"href",base:"href",script:"src",form:"action",img:"src",area:"href",iframe:"src",embed:"src",source:"src",track:"src",input:"src",audio:"src",video:"src"},i.getDomAttribute=function(e){if(e&&e.nodeName){var t=e.nodeName.toLowerCase();if("input"!==t||"image"===e.type)return i.domAttributes[t]}},i.encode=m,i.decode=decodeURIComponent,i.iso8859=function(){i.encode=escape,i.decode=unescape},i.unicode=function(){i.encode=m,i.decode=decodeURIComponent},i.characters={pathname:{encode:{expression:/%(24|26|2B|2C|3B|3D|3A|40)/gi,map:{"%24":"$","%26":"&","%2B":"+","%2C":",","%3B":";","%3D":"=","%3A":":","%40":"@"}},decode:{expression:/[\/\?#]/g,map:{"/":"%2F","?":"%3F","#":"%23"}}},reserved:{encode:{expression:/%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/gi,map:{"%3A":":","%2F":"/","%3F":"?","%23":"#","%5B":"[","%5D":"]","%40":"@","%21":"!","%24":"$","%26":"&","%27":"'","%28":"(","%29":")","%2A":"*","%2B":"+","%2C":",","%3B":";","%3D":"="}}},urnpath:{encode:{expression:/%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/gi,map:{"%21":"!","%24":"$","%27":"'","%28":"(","%29":")","%2A":"*","%2B":"+","%2C":",","%3B":";","%3D":"=","%40":"@"}},decode:{expression:/[\/\?#:]/g,map:{"/":"%2F","?":"%3F","#":"%23",":":"%3A"}}}},i.encodeQuery=function(e,t){var r=i.encode(e+"");return void 0===t&&(t=i.escapeQuerySpace),t?r.replace(/%20/g,"+"):r},i.decodeQuery=function(e,t){e+="",void 0===t&&(t=i.escapeQuerySpace);try{return i.decode(t?e.replace(/\+/g,"%20"):e)}catch(t){return e}};var v,g={encode:"encode",decode:"decode"},b=function(e,t){return function(r){try{return i[t](r+"").replace(i.characters[e][t].expression,(function(r){return i.characters[e][t].map[r]}))}catch(e){return r}}};for(v in g)i[v+"PathSegment"]=b("pathname",g[v]),i[v+"UrnPathSegment"]=b("urnpath",g[v]);var w=function(e,t,r){return function(n){var o;o=r?function(e){return i[t](i[r](e))}:i[t];for(var a=(n+"").split(e),s=0,u=a.length;s-1&&(t.fragment=e.substring(r+1)||null,e=e.substring(0,r)),(r=e.indexOf("?"))>-1&&(t.query=e.substring(r+1)||null,e=e.substring(0,r)),"//"===(e=(e=e.replace(/^(https?|ftp|wss?)?:+[/\\]*/i,"$1://")).replace(/^[/\\]{2,}/i,"//")).substring(0,2)?(t.protocol=null,e=e.substring(2),e=i.parseAuthority(e,t)):(r=e.indexOf(":"))>-1&&(t.protocol=e.substring(0,r)||null,t.protocol&&!t.protocol.match(i.protocol_expression)?t.protocol=void 0:"//"===e.substring(r+1,r+3).replace(/\\/g,"/")?(e=e.substring(r+3),e=i.parseAuthority(e,t)):(e=e.substring(r+1),t.urn=!0)),t.path=e,t},i.parseHost=function(e,t){e||(e="");var r,n,o=(e=e.replace(/\\/g,"/")).indexOf("/");if(-1===o&&(o=e.length),"["===e.charAt(0))r=e.indexOf("]"),t.hostname=e.substring(1,r)||null,t.port=e.substring(r+2,o)||null,"/"===t.port&&(t.port=null);else{var a=e.indexOf(":"),s=e.indexOf("/"),u=e.indexOf(":",a+1);-1!==u&&(-1===s||u-1?o:e.length-1);return a>-1&&(-1===o||a-1?d.slice(0,h)+d.slice(h).replace(a,""):d.replace(a,"")).length<=c[0].length||r.ignore&&r.ignore.test(d))){var v=t(d,l,p=l+d.length,e);void 0!==v?(v=String(v),e=e.slice(0,l)+v+e.slice(p),n.lastIndex=l+v.length):n.lastIndex=p}}return n.lastIndex=0,e},i.ensureValidHostname=function(t,r){var n=!!t,o=!1;if(!!r&&(o=p(i.hostProtocols,r)),o&&!n)throw new TypeError("Hostname cannot be empty, if protocol is "+r);if(t&&t.match(i.invalid_hostname_characters)){if(!e)throw new TypeError('Hostname "'+t+'" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');if(e.toASCII(t).match(i.invalid_hostname_characters))throw new TypeError('Hostname "'+t+'" contains characters other than [A-Z0-9.-:_]')}},i.ensureValidPort=function(e){if(e){var t=Number(e);if(!(/^[0-9]+$/.test(t)&&t>0&&t<65536))throw new TypeError('Port "'+e+'" is not a valid port')}},i.noConflict=function(e){if(e){var t={URI:this.noConflict()};return n.URITemplate&&"function"==typeof n.URITemplate.noConflict&&(t.URITemplate=n.URITemplate.noConflict()),n.IPv6&&"function"==typeof n.IPv6.noConflict&&(t.IPv6=n.IPv6.noConflict()),n.SecondLevelDomains&&"function"==typeof n.SecondLevelDomains.noConflict&&(t.SecondLevelDomains=n.SecondLevelDomains.noConflict()),t}return n.URI===this&&(n.URI=o),this},a.build=function(e){return!0===e?this._deferred_build=!0:(void 0===e||this._deferred_build)&&(this._string=i.build(this._parts),this._deferred_build=!1),this},a.clone=function(){return new i(this)},a.valueOf=a.toString=function(){return this.build(!1)._string},a.protocol=S("protocol"),a.username=S("username"),a.password=S("password"),a.hostname=S("hostname"),a.port=S("port"),a.query=k("query","?"),a.fragment=k("fragment","#"),a.search=function(e,t){var r=this.query(e,t);return"string"==typeof r&&r.length?"?"+r:r},a.hash=function(e,t){var r=this.fragment(e,t);return"string"==typeof r&&r.length?"#"+r:r},a.pathname=function(e,t){if(void 0===e||!0===e){var r=this._parts.path||(this._parts.hostname?"/":"");return e?(this._parts.urn?i.decodeUrnPath:i.decodePath)(r):r}return this._parts.urn?this._parts.path=e?i.recodeUrnPath(e):"":this._parts.path=e?i.recodePath(e):"/",this.build(!t),this},a.path=a.pathname,a.href=function(e,t){var r;if(void 0===e)return this.toString();this._string="",this._parts=i._parts();var n=e instanceof i,o="object"==typeof e&&(e.hostname||e.path||e.pathname);e.nodeName&&(e=e[i.getDomAttribute(e)]||"",o=!1);if(!n&&o&&void 0!==e.pathname&&(e=e.toString()),"string"==typeof e||e instanceof String)this._parts=i.parse(String(e),this._parts);else{if(!n&&!o)throw new TypeError("invalid input");var a=n?e._parts:e;for(r in a)"query"!==r&&s.call(this._parts,r)&&(this._parts[r]=a[r]);a.query&&this.query(a.query,!1)}return this.build(!t),this},a.is=function(e){var t=!1,n=!1,o=!1,a=!1,s=!1,u=!1,c=!1,l=!this._parts.urn;switch(this._parts.hostname&&(l=!1,n=i.ip4_expression.test(this._parts.hostname),o=i.ip6_expression.test(this._parts.hostname),s=(a=!(t=n||o))&&r&&r.has(this._parts.hostname),u=a&&i.idn_expression.test(this._parts.hostname),c=a&&i.punycode_expression.test(this._parts.hostname)),e.toLowerCase()){case"relative":return l;case"absolute":return!l;case"domain":case"name":return a;case"sld":return s;case"ip":return t;case"ip4":case"ipv4":case"inet4":return n;case"ip6":case"ipv6":case"inet6":return o;case"idn":return u;case"url":return!this._parts.urn;case"urn":return!!this._parts.urn;case"punycode":return c}return null};var E=a.protocol,T=a.port,_=a.hostname;a.protocol=function(e,t){if(e&&!(e=e.replace(/:(\/\/)?$/,"")).match(i.protocol_expression))throw new TypeError('Protocol "'+e+"\" contains characters other than [A-Z0-9.+-] or doesn't start with [A-Z]");return E.call(this,e,t)},a.scheme=a.protocol,a.port=function(e,t){return this._parts.urn?void 0===e?"":this:(void 0!==e&&(0===e&&(e=null),e&&(":"===(e+="").charAt(0)&&(e=e.substring(1)),i.ensureValidPort(e))),T.call(this,e,t))},a.hostname=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0!==e){var r={preventInvalidHostname:this._parts.preventInvalidHostname};if("/"!==i.parseHost(e,r))throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');e=r.hostname,this._parts.preventInvalidHostname&&i.ensureValidHostname(e,this._parts.protocol)}return _.call(this,e,t)},a.origin=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e){var r=this.protocol();return this.authority()?(r?r+"://":"")+this.authority():""}var n=i(e);return this.protocol(n.protocol()).authority(n.authority()).build(!t),this},a.host=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e)return this._parts.hostname?i.buildHost(this._parts):"";if("/"!==i.parseHost(e,this._parts))throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');return this.build(!t),this},a.authority=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e)return this._parts.hostname?i.buildAuthority(this._parts):"";if("/"!==i.parseAuthority(e,this._parts))throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');return this.build(!t),this},a.userinfo=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e){var r=i.buildUserinfo(this._parts);return r?r.substring(0,r.length-1):r}return"@"!==e[e.length-1]&&(e+="@"),i.parseUserinfo(e,this._parts),this.build(!t),this},a.resource=function(e,t){var r;return void 0===e?this.path()+this.search()+this.hash():(r=i.parse(e),this._parts.path=r.path,this._parts.query=r.query,this._parts.fragment=r.fragment,this.build(!t),this)},a.subdomain=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e){if(!this._parts.hostname||this.is("IP"))return"";var r=this._parts.hostname.length-this.domain().length-1;return this._parts.hostname.substring(0,r)||""}var n=this._parts.hostname.length-this.domain().length,o=this._parts.hostname.substring(0,n),a=new RegExp("^"+u(o));if(e&&"."!==e.charAt(e.length-1)&&(e+="."),-1!==e.indexOf(":"))throw new TypeError("Domains cannot contain colons");return e&&i.ensureValidHostname(e,this._parts.protocol),this._parts.hostname=this._parts.hostname.replace(a,e),this.build(!t),this},a.domain=function(e,t){if(this._parts.urn)return void 0===e?"":this;if("boolean"==typeof e&&(t=e,e=void 0),void 0===e){if(!this._parts.hostname||this.is("IP"))return"";var r=this._parts.hostname.match(/\./g);if(r&&r.length<2)return this._parts.hostname;var n=this._parts.hostname.length-this.tld(t).length-1;return n=this._parts.hostname.lastIndexOf(".",n-1)+1,this._parts.hostname.substring(n)||""}if(!e)throw new TypeError("cannot set domain empty");if(-1!==e.indexOf(":"))throw new TypeError("Domains cannot contain colons");if(i.ensureValidHostname(e,this._parts.protocol),!this._parts.hostname||this.is("IP"))this._parts.hostname=e;else{var o=new RegExp(u(this.domain())+"$");this._parts.hostname=this._parts.hostname.replace(o,e)}return this.build(!t),this},a.tld=function(e,t){if(this._parts.urn)return void 0===e?"":this;if("boolean"==typeof e&&(t=e,e=void 0),void 0===e){if(!this._parts.hostname||this.is("IP"))return"";var n=this._parts.hostname.lastIndexOf("."),o=this._parts.hostname.substring(n+1);return!0!==t&&r&&r.list[o.toLowerCase()]&&r.get(this._parts.hostname)||o}var i;if(!e)throw new TypeError("cannot set TLD empty");if(e.match(/[^a-zA-Z0-9-]/)){if(!r||!r.is(e))throw new TypeError('TLD "'+e+'" contains characters other than [A-Z0-9]');i=new RegExp(u(this.tld())+"$"),this._parts.hostname=this._parts.hostname.replace(i,e)}else{if(!this._parts.hostname||this.is("IP"))throw new ReferenceError("cannot set TLD on non-domain host");i=new RegExp(u(this.tld())+"$"),this._parts.hostname=this._parts.hostname.replace(i,e)}return this.build(!t),this},a.directory=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e||!0===e){if(!this._parts.path&&!this._parts.hostname)return"";if("/"===this._parts.path)return"/";var r=this._parts.path.length-this.filename().length-1,n=this._parts.path.substring(0,r)||(this._parts.hostname?"/":"");return e?i.decodePath(n):n}var o=this._parts.path.length-this.filename().length,a=this._parts.path.substring(0,o),s=new RegExp("^"+u(a));return this.is("relative")||(e||(e="/"),"/"!==e.charAt(0)&&(e="/"+e)),e&&"/"!==e.charAt(e.length-1)&&(e+="/"),e=i.recodePath(e),this._parts.path=this._parts.path.replace(s,e),this.build(!t),this},a.filename=function(e,t){if(this._parts.urn)return void 0===e?"":this;if("string"!=typeof e){if(!this._parts.path||"/"===this._parts.path)return"";var r=this._parts.path.lastIndexOf("/"),n=this._parts.path.substring(r+1);return e?i.decodePathSegment(n):n}var o=!1;"/"===e.charAt(0)&&(e=e.substring(1)),e.match(/\.?\//)&&(o=!0);var a=new RegExp(u(this.filename())+"$");return e=i.recodePath(e),this._parts.path=this._parts.path.replace(a,e),o?this.normalizePath(t):this.build(!t),this},a.suffix=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e||!0===e){if(!this._parts.path||"/"===this._parts.path)return"";var r,n,o=this.filename(),a=o.lastIndexOf(".");return-1===a?"":(r=o.substring(a+1),n=/^[a-z0-9%]+$/i.test(r)?r:"",e?i.decodePathSegment(n):n)}"."===e.charAt(0)&&(e=e.substring(1));var s,c=this.suffix();if(c)s=e?new RegExp(u(c)+"$"):new RegExp(u("."+c)+"$");else{if(!e)return this;this._parts.path+="."+i.recodePath(e)}return s&&(e=i.recodePath(e),this._parts.path=this._parts.path.replace(s,e)),this.build(!t),this},a.segment=function(e,t,r){var n=this._parts.urn?":":"/",o=this.path(),i="/"===o.substring(0,1),a=o.split(n);if(void 0!==e&&"number"!=typeof e&&(r=t,t=e,e=void 0),void 0!==e&&"number"!=typeof e)throw new Error('Bad segment "'+e+'", must be 0-based integer');if(i&&a.shift(),e<0&&(e=Math.max(a.length+e,0)),void 0===t)return void 0===e?a:a[e];if(null===e||void 0===a[e])if(l(t)){a=[];for(var s=0,u=t.length;s{}"`^| \\]/,o.expand=function(e,t,r){var n,i,a,u=s[e.operator],c=u.named?"Named":"Unnamed",l=e.variables,f=[];for(a=0;i=l[a];a++){if(0===(n=t.get(i.name)).type&&r&&r.strict)throw new Error('Missing expansion value for variable "'+i.name+'"');if(n.val.length){if(n.type>1&&i.maxlength)throw new Error('Invalid expression: Prefix modifier not applicable to variable "'+i.name+'"');f.push(o["expand"+c](n,u,i.explode,i.explode&&u.separator||",",i.maxlength,i.name))}else n.type&&f.push("")}return f.length?u.prefix+f.join(u.separator):""},o.expandNamed=function(t,r,n,o,i,a){var s,u,c,l="",f=r.encode,p=r.empty_name_separator,d=!t[f].length,h=2===t.type?"":e[f](a);for(u=0,c=t.val.length;u= 0x80 (not a basic code point)","invalid-input":"Invalid input"},p=Math.floor,d=String.fromCharCode;function h(e){throw new RangeError(f[e])}function y(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function m(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+y((e=e.replace(l,".")).split("."),t).join(".")}function v(e){for(var t,r,n=[],o=0,i=e.length;o=55296&&t<=56319&&o65535&&(t+=d((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=d(e)})).join("")}function b(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function w(e,t,r){var n=0;for(e=r?p(e/700):e>>1,e+=p(e/t);e>455;n+=s)e=p(e/35);return p(n+36*e/(e+38))}function S(e){var t,r,n,o,i,u,c,l,f,d,y,m=[],v=e.length,b=0,S=128,k=72;for((r=e.lastIndexOf("-"))<0&&(r=0),n=0;n=128&&h("not-basic"),m.push(e.charCodeAt(n));for(o=r>0?r+1:0;o=v&&h("invalid-input"),((l=(y=e.charCodeAt(o++))-48<10?y-22:y-65<26?y-65:y-97<26?y-97:s)>=s||l>p((a-b)/u))&&h("overflow"),b+=l*u,!(l<(f=c<=k?1:c>=k+26?26:c-k));c+=s)u>p(a/(d=s-f))&&h("overflow"),u*=d;k=w(b-i,t=m.length+1,0==i),p(b/t)>a-S&&h("overflow"),S+=p(b/t),b%=t,m.splice(b++,0,S)}return g(m)}function k(e){var t,r,n,o,i,u,c,l,f,y,m,g,S,k,E,T=[];for(g=(e=v(e)).length,t=128,r=0,i=72,u=0;u=t&&mp((a-r)/(S=n+1))&&h("overflow"),r+=(c-t)*S,t=c,u=0;ua&&h("overflow"),m==t){for(l=r,f=s;!(l<(y=f<=i?1:f>=i+26?26:f-i));f+=s)E=l-y,k=s-y,T.push(d(b(y+E%k,0))),l=p(E/k);T.push(d(b(l,0))),i=w(r,S,n==o),r=0,++n}++r,++t}return T.join("")}i={version:"1.3.2",ucs2:{decode:v,encode:g},decode:S,encode:k,toASCII:function(e){return m(e,(function(e){return c.test(e)?"xn--"+k(e):e}))},toUnicode:function(e){return m(e,(function(e){return u.test(e)?S(e.slice(4).toLowerCase()):e}))}},void 0===(n=function(){return i}.call(t,r,t,e))||(e.exports=n)}()},2894:()=>{}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={id:n,loaded:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.loaded=!0,i.exports}return r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),r(1924)})())); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-eventsource.min.js.LICENSE.txt b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-eventsource.min.js.LICENSE.txt new file mode 100644 index 000000000..291e51292 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk-no-eventsource.min.js.LICENSE.txt @@ -0,0 +1,69 @@ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +/*! + * URI.js - Mutating URLs + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! + * URI.js - Mutating URLs + * IPv6 Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! + * URI.js - Mutating URLs + * Second Level Domain (SLD) Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! + * URI.js - Mutating URLs + * URI Template Support - http://tools.ietf.org/html/rfc6570 + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! https://mths.be/punycode v1.4.0 by @mathias */ + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + +/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ diff --git a/node_modules/@stellar/stellar-sdk/dist/stellar-sdk.js b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk.js new file mode 100644 index 000000000..7c4b4d09e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk.js @@ -0,0 +1,61207 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define("StellarSdk", [], factory); + else if(typeof exports === 'object') + exports["StellarSdk"] = factory(); + else + root["StellarSdk"] = factory(); +})(self, () => { +return /******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 3740: +/***/ (function(module) { + +/*! For license information please see xdr.js.LICENSE.txt */ +!function(t,e){ true?module.exports=e():0}(this,(()=>(()=>{var t={616:(t,e,r)=>{"use strict";r.d(e,{A:()=>i});var n=r(287);n.hp.alloc(1).subarray(0,1)instanceof n.hp||(n.hp.prototype.subarray=function(t,e){const r=Uint8Array.prototype.subarray.call(this,t,e);return Object.setPrototypeOf(r,n.hp.prototype),r});const i=n.hp},281:(t,e,r)=>{const n=r(164);t.exports=n},164:(t,e,r)=>{"use strict";r.r(e),r.d(e,{Array:()=>F,Bool:()=>S,Double:()=>L,Enum:()=>q,Float:()=>O,Hyper:()=>U,Int:()=>v,LargeInt:()=>x,Opaque:()=>D,Option:()=>X,Quadruple:()=>N,Reference:()=>G,String:()=>M,Struct:()=>Y,Union:()=>W,UnsignedHyper:()=>T,UnsignedInt:()=>R,VarArray:()=>P,VarOpaque:()=>z,Void:()=>k,XdrReader:()=>f,XdrWriter:()=>c,config:()=>it});class n extends TypeError{constructor(t){super(`XDR Write Error: ${t}`)}}class i extends TypeError{constructor(t){super(`XDR Read Error: ${t}`)}}class o extends TypeError{constructor(t){super(`XDR Type Definition Error: ${t}`)}}class s extends o{constructor(){super("method not implemented, it should be overloaded in the descendant class.")}}var u=r(616).A;class f{constructor(t){if(!u.isBuffer(t)){if(!(t instanceof Array||Array.isArray(t)||ArrayBuffer.isView(t)))throw new i(`source invalid: ${t}`);t=u.from(t)}this._buffer=t,this._length=t.length,this._index=0}_buffer;_length;_index;get eof(){return this._index===this._length}advance(t){const e=this._index;if(this._index+=t,this._length0){for(let t=0;t0){const t=this.alloc(r);this._buffer.fill(0,t,this._index)}}writeInt32BE(t){const e=this.alloc(4);this._buffer.writeInt32BE(t,e)}writeUInt32BE(t){const e=this.alloc(4);this._buffer.writeUInt32BE(t,e)}writeBigInt64BE(t){const e=this.alloc(8);this._buffer.writeBigInt64BE(t,e)}writeBigUInt64BE(t){const e=this.alloc(8);this._buffer.writeBigUInt64BE(t,e)}writeFloatBE(t){const e=this.alloc(4);this._buffer.writeFloatBE(t,e)}writeDoubleBE(t){const e=this.alloc(8);this._buffer.writeDoubleBE(t,e)}static bufferChunkSize=h}var l=r(616).A;class p{toXDR(t="raw"){if(!this.write)return this.constructor.toXDR(this,t);const e=new c;return this.write(this,e),w(e.finalize(),t)}fromXDR(t,e="raw"){if(!this.read)return this.constructor.fromXDR(t,e);const r=new f(m(t,e)),n=this.read(r);return r.ensureInputConsumed(),n}validateXDR(t,e="raw"){try{return this.fromXDR(t,e),!0}catch(t){return!1}}static toXDR(t,e="raw"){const r=new c;return this.write(t,r),w(r.finalize(),e)}static fromXDR(t,e="raw"){const r=new f(m(t,e)),n=this.read(r);return r.ensureInputConsumed(),n}static validateXDR(t,e="raw"){try{return this.fromXDR(t,e),!0}catch(t){return!1}}}class d extends p{static read(t){throw new s}static write(t,e){throw new s}static isValid(t){return!1}}class g extends p{isValid(t){return!1}}class y extends TypeError{constructor(t){super(`Invalid format ${t}, must be one of "raw", "hex", "base64"`)}}function w(t,e){switch(e){case"raw":return t;case"hex":return t.toString("hex");case"base64":return t.toString("base64");default:throw new y(e)}}function m(t,e){switch(e){case"raw":return t;case"hex":return l.from(t,"hex");case"base64":return l.from(t,"base64");default:throw new y(e)}}function b(t,e){return null!=t&&(t instanceof e||_(t,e)&&"function"==typeof t.constructor.read&&"function"==typeof t.constructor.write&&_(t,"XdrType"))}function _(t,e){do{if(t.constructor.name===e)return!0}while(t=Object.getPrototypeOf(t));return!1}const B=2147483647,E=-2147483648;class v extends d{static read(t){return t.readInt32BE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");if((0|t)!==t)throw new n("invalid i32 value");e.writeInt32BE(t)}static isValid(t){return"number"==typeof t&&(0|t)===t&&(t>=E&&t<=B)}}function A(t,e,r){if("bigint"!=typeof t)throw new TypeError("Expected bigint 'value', got "+typeof t);const n=e/r;if(1===n)return[t];if(r<32||r>128||2!==n&&4!==n&&8!==n)throw new TypeError(`invalid bigint (${t}) and slice size (${e} -> ${r}) combination`);const i=BigInt(r),o=new Array(n);for(let e=0;e>=i;return o}function I(t,e){if(e)return[0n,(1n<=o&&i<=s)return i;throw new TypeError(`bigint values [${t}] for ${function(t,e){return`${e?"u":"i"}${t}`}(e,r)} out of range [${o}, ${s}]: ${i}`)}(t,this.size,this.unsigned)}get unsigned(){throw new s}get size(){throw new s}slice(t){return A(this._value,this.size,t)}toString(){return this._value.toString()}toJSON(){return{_value:this._value.toString()}}toBigInt(){return BigInt(this._value)}static read(t){const{size:e}=this.prototype;return 64===e?new this(t.readBigUInt64BE()):new this(...Array.from({length:e/64},(()=>t.readBigUInt64BE())).reverse())}static write(t,e){if(t instanceof this)t=t._value;else if("bigint"!=typeof t||t>this.MAX_VALUE||t>32n)|0}get size(){return 64}get unsigned(){return!1}static fromBits(t,e){return new this(t,e)}}U.defineIntBoundaries();const $=4294967295;class R extends d{static read(t){return t.readUInt32BE()}static write(t,e){if("number"!=typeof t||!(t>=0&&t<=$)||t%1!=0)throw new n("invalid u32 value");e.writeUInt32BE(t)}static isValid(t){return"number"==typeof t&&t%1==0&&(t>=0&&t<=$)}}R.MAX_VALUE=$,R.MIN_VALUE=0;class T extends x{constructor(...t){super(t)}get low(){return Number(0xffffffffn&this._value)|0}get high(){return Number(this._value>>32n)|0}get size(){return 64}get unsigned(){return!0}static fromBits(t,e){return new this(t,e)}}T.defineIntBoundaries();class O extends d{static read(t){return t.readFloatBE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");e.writeFloatBE(t)}static isValid(t){return"number"==typeof t}}class L extends d{static read(t){return t.readDoubleBE()}static write(t,e){if("number"!=typeof t)throw new n("not a number");e.writeDoubleBE(t)}static isValid(t){return"number"==typeof t}}class N extends d{static read(){throw new o("quadruple not supported")}static write(){throw new o("quadruple not supported")}static isValid(){return!1}}class S extends d{static read(t){const e=v.read(t);switch(e){case 0:return!1;case 1:return!0;default:throw new i(`got ${e} when trying to read a bool`)}}static write(t,e){const r=t?1:0;v.write(r,e)}static isValid(t){return"boolean"==typeof t}}var V=r(616).A;class M extends g{constructor(t=R.MAX_VALUE){super(),this._maxLength=t}read(t){const e=R.read(t);if(e>this._maxLength)throw new i(`saw ${e} length String, max allowed is ${this._maxLength}`);return t.read(e)}readString(t){return this.read(t).toString("utf8")}write(t,e){const r="string"==typeof t?V.byteLength(t,"utf8"):t.length;if(r>this._maxLength)throw new n(`got ${t.length} bytes, max allowed is ${this._maxLength}`);R.write(r,e),e.write(t,r)}isValid(t){return"string"==typeof t?V.byteLength(t,"utf8")<=this._maxLength:!!(t instanceof Array||V.isBuffer(t))&&t.length<=this._maxLength}}var C=r(616).A;class D extends g{constructor(t){super(),this._length=t}read(t){return t.read(this._length)}write(t,e){const{length:r}=t;if(r!==this._length)throw new n(`got ${t.length} bytes, expected ${this._length}`);e.write(t,r)}isValid(t){return C.isBuffer(t)&&t.length===this._length}}var j=r(616).A;class z extends g{constructor(t=R.MAX_VALUE){super(),this._maxLength=t}read(t){const e=R.read(t);if(e>this._maxLength)throw new i(`saw ${e} length VarOpaque, max allowed is ${this._maxLength}`);return t.read(e)}write(t,e){const{length:r}=t;if(t.length>this._maxLength)throw new n(`got ${t.length} bytes, max allowed is ${this._maxLength}`);R.write(r,e),e.write(t,r)}isValid(t){return j.isBuffer(t)&&t.length<=this._maxLength}}class F extends g{constructor(t,e){super(),this._childType=t,this._length=e}read(t){const e=new r.g.Array(this._length);for(let r=0;rthis._maxLength)throw new i(`saw ${e} length VarArray, max allowed is ${this._maxLength}`);const r=new Array(e);for(let n=0;nthis._maxLength)throw new n(`got array of size ${t.length}, max allowed is ${this._maxLength}`);R.write(t.length,e);for(const r of t)this._childType.write(r,e)}isValid(t){if(!(t instanceof Array)||t.length>this._maxLength)return!1;for(const e of t)if(!this._childType.isValid(e))return!1;return!0}}class X extends d{constructor(t){super(),this._childType=t}read(t){if(S.read(t))return this._childType.read(t)}write(t,e){const r=null!=t;S.write(r,e),r&&this._childType.write(t,e)}isValid(t){return null==t||this._childType.isValid(t)}}class k extends d{static read(){}static write(t){if(void 0!==t)throw new n("trying to write value to a void slot")}static isValid(t){return void 0===t}}class q extends d{constructor(t,e){super(),this.name=t,this.value=e}static read(t){const e=v.read(t),r=this._byValue[e];if(void 0===r)throw new i(`unknown ${this.enumName} member for value ${e}`);return r}static write(t,e){if(!this.isValid(t))throw new n(`${t} has enum name ${t?.enumName}, not ${this.enumName}: ${JSON.stringify(t)}`);v.write(t.value,e)}static isValid(t){return t?.constructor?.enumName===this.enumName||b(t,this)}static members(){return this._members}static values(){return Object.values(this._members)}static fromName(t){const e=this._members[t];if(!e)throw new TypeError(`${t} is not a member of ${this.enumName}`);return e}static fromValue(t){const e=this._byValue[t];if(void 0===e)throw new TypeError(`${t} is not a value of any member of ${this.enumName}`);return e}static create(t,e,r){const n=class extends q{};n.enumName=e,t.results[e]=n,n._members={},n._byValue={};for(const[t,e]of Object.entries(r)){const r=new n(t,e);n._members[t]=r,n._byValue[e]=r,n[t]=()=>r}return n}}class G extends d{resolve(){throw new o('"resolve" method should be implemented in the descendant class')}}class Y extends g{constructor(t){super(),this._attributes=t||{}}static read(t){const e={};for(const[r,n]of this._fields)e[r]=n.read(t);return new this(e)}static write(t,e){if(!this.isValid(t))throw new n(`${t} has struct name ${t?.constructor?.structName}, not ${this.structName}: ${JSON.stringify(t)}`);for(const[r,n]of this._fields){const i=t._attributes[r];n.write(i,e)}}static isValid(t){return t?.constructor?.structName===this.structName||b(t,this)}static create(t,e,r){const n=class extends Y{};n.structName=e,t.results[e]=n;const i=new Array(r.length);for(let e=0;e{"use strict";e.byteLength=function(t){var e=u(t),r=e[0],n=e[1];return 3*(r+n)/4-n},e.toByteArray=function(t){var e,r,o=u(t),s=o[0],f=o[1],a=new i(function(t,e,r){return 3*(e+r)/4-r}(0,s,f)),h=0,c=f>0?s-4:s;for(r=0;r>16&255,a[h++]=e>>8&255,a[h++]=255&e;2===f&&(e=n[t.charCodeAt(r)]<<2|n[t.charCodeAt(r+1)]>>4,a[h++]=255&e);1===f&&(e=n[t.charCodeAt(r)]<<10|n[t.charCodeAt(r+1)]<<4|n[t.charCodeAt(r+2)]>>2,a[h++]=e>>8&255,a[h++]=255&e);return a},e.fromByteArray=function(t){for(var e,n=t.length,i=n%3,o=[],s=16383,u=0,a=n-i;ua?a:u+s));1===i?(e=t[n-1],o.push(r[e>>2]+r[e<<4&63]+"==")):2===i&&(e=(t[n-2]<<8)+t[n-1],o.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"="));return o.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)r[s]=o[s],n[o.charCodeAt(s)]=s;function u(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function f(t,e,n){for(var i,o,s=[],u=e;u>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return s.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287:(t,e,r)=>{"use strict";const n=r(526),i=r(251),o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.hp=f,e.IS=50;const s=2147483647;function u(t){if(t>s)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,f.prototype),e}function f(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return c(t)}return a(t,e,r)}function a(t,e,r){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!f.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|g(t,e);let n=u(r);const i=n.write(t,e);i!==r&&(n=n.slice(0,i));return n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(W(t,Uint8Array)){const e=new Uint8Array(t);return p(e.buffer,e.byteOffset,e.byteLength)}return l(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(W(t,ArrayBuffer)||t&&W(t.buffer,ArrayBuffer))return p(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(W(t,SharedArrayBuffer)||t&&W(t.buffer,SharedArrayBuffer)))return p(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return f.from(n,e,r);const i=function(t){if(f.isBuffer(t)){const e=0|d(t.length),r=u(e);return 0===r.length||t.copy(r,0,0,e),r}if(void 0!==t.length)return"number"!=typeof t.length||H(t.length)?u(0):l(t);if("Buffer"===t.type&&Array.isArray(t.data))return l(t.data)}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return f.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function h(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function c(t){return h(t),u(t<0?0:0|d(t))}function l(t){const e=t.length<0?0:0|d(t.length),r=u(e);for(let n=0;n=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|t}function g(t,e){if(f.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||W(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return G(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Y(t).length;default:if(i)return n?-1:G(t).length;e=(""+e).toLowerCase(),i=!0}}function y(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return x(this,e,r);case"ascii":return $(this,e,r);case"latin1":case"binary":return R(this,e,r);case"base64":return I(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function w(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function m(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),H(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=f.from(e,n)),f.isBuffer(e))return 0===e.length?-1:b(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):b(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(t,e,r,n,i){let o,s=1,u=t.length,f=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,f/=2,r/=2}function a(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){let n=-1;for(o=r;ou&&(r=u-f),o=r;o>=0;o--){let r=!0;for(let n=0;ni&&(n=i):n=i;const o=e.length;let s;for(n>o/2&&(n=o/2),s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function I(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function x(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i239?4:e>223?3:e>191?2:1;if(i+s<=r){let r,n,u,f;switch(s){case 1:e<128&&(o=e);break;case 2:r=t[i+1],128==(192&r)&&(f=(31&e)<<6|63&r,f>127&&(o=f));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(f=(15&e)<<12|(63&r)<<6|63&n,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:r=t[i+1],n=t[i+2],u=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&u)&&(f=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&u,f>65535&&f<1114112&&(o=f))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return function(t){const e=t.length;if(e<=U)return String.fromCharCode.apply(String,t);let r="",n=0;for(;nn.length?(f.isBuffer(e)||(e=f.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!f.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},f.byteLength=g,f.prototype._isBuffer=!0,f.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;er&&(t+=" ... "),""},o&&(f.prototype[o]=f.prototype.inspect),f.prototype.compare=function(t,e,r,n,i){if(W(t,Uint8Array)&&(t=f.from(t,t.offset,t.byteLength)),!f.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0);const u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r);for(let t=0;t>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return _(this,t,e,r);case"utf8":case"utf-8":return B(this,t,e,r);case"ascii":case"latin1":case"binary":return E(this,t,e,r);case"base64":return v(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},f.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const U=4096;function $(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;in)&&(r=n);let i="";for(let n=e;nr)throw new RangeError("Trying to access beyond buffer length")}function N(t,e,r,n,i,o){if(!f.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function S(t,e,r,n,i){P(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,r}function V(t,e,r,n,i){P(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r+7]=o,o>>=8,t[r+6]=o,o>>=8,t[r+5]=o,o>>=8,t[r+4]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=s,s>>=8,t[r+2]=s,s>>=8,t[r+1]=s,s>>=8,t[r]=s,r+8}function M(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function C(t,e,r,n,o){return e=+e,r>>>=0,o||M(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function D(t,e,r,n,o){return e=+e,r>>>=0,o||M(t,0,r,8),i.write(t,e,r,n,52,8),r+8}f.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t],i=1,o=0;for(;++o>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},f.prototype.readUint8=f.prototype.readUInt8=function(t,e){return t>>>=0,e||L(t,1,this.length),this[t]},f.prototype.readUint16LE=f.prototype.readUInt16LE=function(t,e){return t>>>=0,e||L(t,2,this.length),this[t]|this[t+1]<<8},f.prototype.readUint16BE=f.prototype.readUInt16BE=function(t,e){return t>>>=0,e||L(t,2,this.length),this[t]<<8|this[t+1]},f.prototype.readUint32LE=f.prototype.readUInt32LE=function(t,e){return t>>>=0,e||L(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},f.prototype.readUint32BE=f.prototype.readUInt32BE=function(t,e){return t>>>=0,e||L(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},f.prototype.readBigUInt64LE=Z((function(t){X(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<>>=0,e>>>=0,r||L(t,e,this.length);let n=this[t],i=1,o=0;for(;++o=i&&(n-=Math.pow(2,8*e)),n},f.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||L(t,e,this.length);let n=e,i=1,o=this[t+--n];for(;n>0&&(i*=256);)o+=this[t+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*e)),o},f.prototype.readInt8=function(t,e){return t>>>=0,e||L(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},f.prototype.readInt16LE=function(t,e){t>>>=0,e||L(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},f.prototype.readInt16BE=function(t,e){t>>>=0,e||L(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},f.prototype.readInt32LE=function(t,e){return t>>>=0,e||L(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},f.prototype.readInt32BE=function(t,e){return t>>>=0,e||L(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},f.prototype.readBigInt64LE=Z((function(t){X(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||k(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<>>=0,e||L(t,4,this.length),i.read(this,t,!0,23,4)},f.prototype.readFloatBE=function(t,e){return t>>>=0,e||L(t,4,this.length),i.read(this,t,!1,23,4)},f.prototype.readDoubleLE=function(t,e){return t>>>=0,e||L(t,8,this.length),i.read(this,t,!0,52,8)},f.prototype.readDoubleBE=function(t,e){return t>>>=0,e||L(t,8,this.length),i.read(this,t,!1,52,8)},f.prototype.writeUintLE=f.prototype.writeUIntLE=function(t,e,r,n){if(t=+t,e>>>=0,r>>>=0,!n){N(this,t,e,r,Math.pow(2,8*r)-1,0)}let i=1,o=0;for(this[e]=255&t;++o>>=0,r>>>=0,!n){N(this,t,e,r,Math.pow(2,8*r)-1,0)}let i=r-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+r},f.prototype.writeUint8=f.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,1,255,0),this[e]=255&t,e+1},f.prototype.writeUint16LE=f.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},f.prototype.writeUint16BE=f.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},f.prototype.writeUint32LE=f.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},f.prototype.writeUint32BE=f.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},f.prototype.writeBigUInt64LE=Z((function(t,e=0){return S(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),f.prototype.writeBigUInt64BE=Z((function(t,e=0){return V(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))})),f.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);N(this,t,e,r,n-1,-n)}let i=0,o=1,s=0;for(this[e]=255&t;++i>>=0,!n){const n=Math.pow(2,8*r-1);N(this,t,e,r,n-1,-n)}let i=r-1,o=1,s=0;for(this[e+i]=255&t;--i>=0&&(o*=256);)t<0&&0===s&&0!==this[e+i+1]&&(s=1),this[e+i]=(t/o|0)-s&255;return e+r},f.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},f.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},f.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},f.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},f.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||N(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},f.prototype.writeBigInt64LE=Z((function(t,e=0){return S(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),f.prototype.writeBigInt64BE=Z((function(t,e=0){return V(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),f.prototype.writeFloatLE=function(t,e,r){return C(this,t,e,!0,r)},f.prototype.writeFloatBE=function(t,e,r){return C(this,t,e,!1,r)},f.prototype.writeDoubleLE=function(t,e,r){return D(this,t,e,!0,r)},f.prototype.writeDoubleBE=function(t,e,r){return D(this,t,e,!1,r)},f.prototype.copy=function(t,e,r,n){if(!f.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function P(t,e,r,n,i,o){if(t>r||t3?0===e||e===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`:`>= ${e}${n} and <= ${r}${n}`,new j.ERR_OUT_OF_RANGE("value",i,t)}!function(t,e,r){X(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||k(e,t.length-(r+1))}(n,i,o)}function X(t,e){if("number"!=typeof t)throw new j.ERR_INVALID_ARG_TYPE(e,"number",t)}function k(t,e,r){if(Math.floor(t)!==t)throw X(t,r),new j.ERR_OUT_OF_RANGE(r||"offset","an integer",t);if(e<0)throw new j.ERR_BUFFER_OUT_OF_BOUNDS;throw new j.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}z("ERR_BUFFER_OUT_OF_BOUNDS",(function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),z("ERR_INVALID_ARG_TYPE",(function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`}),TypeError),z("ERR_OUT_OF_RANGE",(function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=F(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=F(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n}),RangeError);const q=/[^+/0-9A-Za-z-_]/g;function G(t,e){let r;e=e||1/0;const n=t.length;let i=null;const o=[];for(let s=0;s55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function Y(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(q,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function J(t,e,r,n){let i;for(i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function W(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function H(t){return t!=t}const Q=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function Z(t){return"undefined"==typeof BigInt?K:t}function K(){throw new Error("BigInt not supported")}},251:(t,e)=>{e.read=function(t,e,r,n,i){var o,s,u=8*i-n-1,f=(1<>1,h=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-h)-1,p>>=-h,h+=u;h>0;o=256*o+t[e+c],c+=l,h-=8);for(s=o&(1<<-h)-1,o>>=-h,h+=n;h>0;s=256*s+t[e+c],c+=l,h-=8);if(0===o)o=1-a;else{if(o===f)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=a}return(p?-1:1)*s*Math.pow(2,o-n)},e.write=function(t,e,r,n,i,o){var s,u,f,a=8*o-i-1,h=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=h):(s=Math.floor(Math.log(e)/Math.LN2),e*(f=Math.pow(2,-s))<1&&(s--,f*=2),(e+=s+c>=1?l/f:l*Math.pow(2,1-c))*f>=2&&(s++,f/=2),s+c>=h?(u=0,s=h):s+c>=1?(u=(e*f-1)*Math.pow(2,i),s+=c):(u=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,a-=8);t[r+p-d]|=128*g}}},e={};function r(n){var i=e[n];if(void 0!==i)return i.exports;var o=e[n]={exports:{}};return t[n](o,o.exports,r),o.exports}return r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r(281)})())); +//# sourceMappingURL=xdr.js.map + +/***/ }), + +/***/ 2135: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Account = void 0; +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Account object. + * + * `Account` represents a single account in the Stellar network and its sequence + * number. Account tracks the sequence number as it is used by {@link + * TransactionBuilder}. See + * [Accounts](https://developers.stellar.org/docs/glossary/accounts/) for + * more information about how accounts work in Stellar. + * + * @constructor + * + * @param {string} accountId - ID of the account (ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`). If you + * provide a muxed account address, this will throw; use {@link + * MuxedAccount} instead. + * @param {string} sequence - current sequence number of the account + */ +var Account = exports.Account = /*#__PURE__*/function () { + function Account(accountId, sequence) { + _classCallCheck(this, Account); + if (_strkey.StrKey.isValidMed25519PublicKey(accountId)) { + throw new Error('accountId is an M-address; use MuxedAccount instead'); + } + if (!_strkey.StrKey.isValidEd25519PublicKey(accountId)) { + throw new Error('accountId is invalid'); + } + if (!(typeof sequence === 'string')) { + throw new Error('sequence must be of type string'); + } + this._accountId = accountId; + this.sequence = new _bignumber["default"](sequence); + } + + /** + * Returns Stellar account ID, ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`. + * @returns {string} + */ + return _createClass(Account, [{ + key: "accountId", + value: function accountId() { + return this._accountId; + } + + /** + * @returns {string} sequence number for the account as a string + */ + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this.sequence.toString(); + } + + /** + * Increments sequence number in this object by one. + * @returns {void} + */ + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + this.sequence = this.sequence.plus(1); + } + }]); +}(); + +/***/ }), + +/***/ 1180: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Address = void 0; +var _strkey = __webpack_require__(7120); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Address object. + * + * `Address` represents a single address in the Stellar network. An address can + * represent an account or a contract. + * + * @constructor + * + * @param {string} address - ID of the account (ex. + * `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`). If you + * provide a muxed account address, this will throw; use {@link + * MuxedAccount} instead. + */ +var Address = exports.Address = /*#__PURE__*/function () { + function Address(address) { + _classCallCheck(this, Address); + if (_strkey.StrKey.isValidEd25519PublicKey(address)) { + this._type = 'account'; + this._key = _strkey.StrKey.decodeEd25519PublicKey(address); + } else if (_strkey.StrKey.isValidContract(address)) { + this._type = 'contract'; + this._key = _strkey.StrKey.decodeContract(address); + } else { + throw new Error("Unsupported address type: ".concat(address)); + } + } + + /** + * Parses a string and returns an Address object. + * + * @param {string} address - The address to parse. ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA` + * @returns {Address} + */ + return _createClass(Address, [{ + key: "toString", + value: + /** + * Serialize an address to string. + * + * @returns {string} + */ + function toString() { + switch (this._type) { + case 'account': + return _strkey.StrKey.encodeEd25519PublicKey(this._key); + case 'contract': + return _strkey.StrKey.encodeContract(this._key); + default: + throw new Error('Unsupported address type'); + } + } + + /** + * Convert this Address to an xdr.ScVal type. + * + * @returns {xdr.ScVal} + */ + }, { + key: "toScVal", + value: function toScVal() { + return _xdr["default"].ScVal.scvAddress(this.toScAddress()); + } + + /** + * Convert this Address to an xdr.ScAddress type. + * + * @returns {xdr.ScAddress} + */ + }, { + key: "toScAddress", + value: function toScAddress() { + switch (this._type) { + case 'account': + return _xdr["default"].ScAddress.scAddressTypeAccount(_xdr["default"].PublicKey.publicKeyTypeEd25519(this._key)); + case 'contract': + return _xdr["default"].ScAddress.scAddressTypeContract(this._key); + default: + throw new Error('Unsupported address type'); + } + } + + /** + * Return the raw public key bytes for this address. + * + * @returns {Buffer} + */ + }, { + key: "toBuffer", + value: function toBuffer() { + return this._key; + } + }], [{ + key: "fromString", + value: function fromString(address) { + return new Address(address); + } + + /** + * Creates a new account Address object from a buffer of raw bytes. + * + * @param {Buffer} buffer - The bytes of an address to parse. + * @returns {Address} + */ + }, { + key: "account", + value: function account(buffer) { + return new Address(_strkey.StrKey.encodeEd25519PublicKey(buffer)); + } + + /** + * Creates a new contract Address object from a buffer of raw bytes. + * + * @param {Buffer} buffer - The bytes of an address to parse. + * @returns {Address} + */ + }, { + key: "contract", + value: function contract(buffer) { + return new Address(_strkey.StrKey.encodeContract(buffer)); + } + + /** + * Convert this from an xdr.ScVal type + * + * @param {xdr.ScVal} scVal - The xdr.ScVal type to parse + * @returns {Address} + */ + }, { + key: "fromScVal", + value: function fromScVal(scVal) { + return Address.fromScAddress(scVal.address()); + } + + /** + * Convert this from an xdr.ScAddress type + * + * @param {xdr.ScAddress} scAddress - The xdr.ScAddress type to parse + * @returns {Address} + */ + }, { + key: "fromScAddress", + value: function fromScAddress(scAddress) { + switch (scAddress["switch"]()) { + case _xdr["default"].ScAddressType.scAddressTypeAccount(): + return Address.account(scAddress.accountId().ed25519()); + case _xdr["default"].ScAddressType.scAddressTypeContract(): + return Address.contract(scAddress.contractId()); + default: + throw new Error('Unsupported address type'); + } + } + }]); +}(); + +/***/ }), + +/***/ 1764: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Asset = void 0; +var _util = __webpack_require__(645); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +var _hashing = __webpack_require__(9152); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Asset class represents an asset, either the native asset (`XLM`) + * or an asset code / issuer account ID pair. + * + * An asset code describes an asset code and issuer pair. In the case of the native + * asset XLM, the issuer will be null. + * + * @constructor + * @param {string} code - The asset code. + * @param {string} issuer - The account ID of the issuer. + */ +var Asset = exports.Asset = /*#__PURE__*/function () { + function Asset(code, issuer) { + _classCallCheck(this, Asset); + if (!/^[a-zA-Z0-9]{1,12}$/.test(code)) { + throw new Error('Asset code is invalid (maximum alphanumeric, 12 characters at max)'); + } + if (String(code).toLowerCase() !== 'xlm' && !issuer) { + throw new Error('Issuer cannot be null'); + } + if (issuer && !_strkey.StrKey.isValidEd25519PublicKey(issuer)) { + throw new Error('Issuer is invalid'); + } + if (String(code).toLowerCase() === 'xlm') { + // transform all xLM, Xlm, etc. variants -> XLM + this.code = 'XLM'; + } else { + this.code = code; + } + this.issuer = issuer; + } + + /** + * Returns an asset object for the native asset. + * @Return {Asset} + */ + return _createClass(Asset, [{ + key: "toXDRObject", + value: + /** + * Returns the xdr.Asset object for this asset. + * @returns {xdr.Asset} XDR asset object + */ + function toXDRObject() { + return this._toXDRObject(_xdr["default"].Asset); + } + + /** + * Returns the xdr.ChangeTrustAsset object for this asset. + * @returns {xdr.ChangeTrustAsset} XDR asset object + */ + }, { + key: "toChangeTrustXDRObject", + value: function toChangeTrustXDRObject() { + return this._toXDRObject(_xdr["default"].ChangeTrustAsset); + } + + /** + * Returns the xdr.TrustLineAsset object for this asset. + * @returns {xdr.TrustLineAsset} XDR asset object + */ + }, { + key: "toTrustLineXDRObject", + value: function toTrustLineXDRObject() { + return this._toXDRObject(_xdr["default"].TrustLineAsset); + } + + /** + * Returns the would-be contract ID (`C...` format) for this asset on a given + * network. + * + * @param {string} networkPassphrase indicates which network the contract + * ID should refer to, since every network will have a unique ID for the + * same contract (see {@link Networks} for options) + * + * @returns {string} the strkey-encoded (`C...`) contract ID for this asset + * + * @warning This makes no guarantee that this contract actually *exists*. + */ + }, { + key: "contractId", + value: function contractId(networkPassphrase) { + var networkId = (0, _hashing.hash)(Buffer.from(networkPassphrase)); + var preimage = _xdr["default"].HashIdPreimage.envelopeTypeContractId(new _xdr["default"].HashIdPreimageContractId({ + networkId: networkId, + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAsset(this.toXDRObject()) + })); + return _strkey.StrKey.encodeContract((0, _hashing.hash)(preimage.toXDR())); + } + + /** + * Returns the xdr object for this asset. + * @param {xdr.Asset | xdr.ChangeTrustAsset} xdrAsset - The asset xdr object. + * @returns {xdr.Asset | xdr.ChangeTrustAsset | xdr.TrustLineAsset} XDR Asset object + */ + }, { + key: "_toXDRObject", + value: function _toXDRObject() { + var xdrAsset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _xdr["default"].Asset; + if (this.isNative()) { + return xdrAsset.assetTypeNative(); + } + var xdrType; + var xdrTypeString; + if (this.code.length <= 4) { + xdrType = _xdr["default"].AlphaNum4; + xdrTypeString = 'assetTypeCreditAlphanum4'; + } else { + xdrType = _xdr["default"].AlphaNum12; + xdrTypeString = 'assetTypeCreditAlphanum12'; + } + + // pad code with null bytes if necessary + var padLength = this.code.length <= 4 ? 4 : 12; + var paddedCode = this.code.padEnd(padLength, '\0'); + + // eslint-disable-next-line new-cap + var assetType = new xdrType({ + assetCode: paddedCode, + issuer: _keypair.Keypair.fromPublicKey(this.issuer).xdrAccountId() + }); + return new xdrAsset(xdrTypeString, assetType); + } + + /** + * @returns {string} Asset code + */ + }, { + key: "getCode", + value: function getCode() { + if (this.code === undefined) { + return undefined; + } + return String(this.code); + } + + /** + * @returns {string} Asset issuer + */ + }, { + key: "getIssuer", + value: function getIssuer() { + if (this.issuer === undefined) { + return undefined; + } + return String(this.issuer); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {string} Asset type. Can be one of following types: + * + * - `native`, + * - `credit_alphanum4`, + * - `credit_alphanum12`, or + * - `unknown` as the error case (which should never occur) + */ + }, { + key: "getAssetType", + value: function getAssetType() { + switch (this.getRawAssetType().value) { + case _xdr["default"].AssetType.assetTypeNative().value: + return 'native'; + case _xdr["default"].AssetType.assetTypeCreditAlphanum4().value: + return 'credit_alphanum4'; + case _xdr["default"].AssetType.assetTypeCreditAlphanum12().value: + return 'credit_alphanum12'; + default: + return 'unknown'; + } + } + + /** + * @returns {xdr.AssetType} the raw XDR representation of the asset type + */ + }, { + key: "getRawAssetType", + value: function getRawAssetType() { + if (this.isNative()) { + return _xdr["default"].AssetType.assetTypeNative(); + } + if (this.code.length <= 4) { + return _xdr["default"].AssetType.assetTypeCreditAlphanum4(); + } + return _xdr["default"].AssetType.assetTypeCreditAlphanum12(); + } + + /** + * @returns {boolean} true if this asset object is the native asset. + */ + }, { + key: "isNative", + value: function isNative() { + return !this.issuer; + } + + /** + * @param {Asset} asset Asset to compare + * @returns {boolean} true if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(asset) { + return this.code === asset.getCode() && this.issuer === asset.getIssuer(); + } + }, { + key: "toString", + value: function toString() { + if (this.isNative()) { + return 'native'; + } + return "".concat(this.getCode(), ":").concat(this.getIssuer()); + } + + /** + * Compares two assets according to the criteria: + * + * 1. First compare the type (native < alphanum4 < alphanum12). + * 2. If the types are equal, compare the assets codes. + * 3. If the asset codes are equal, compare the issuers. + * + * @param {Asset} assetA - the first asset + * @param {Asset} assetB - the second asset + * @returns {number} `-1` if assetA < assetB, `0` if assetA == assetB, `1` if assetA > assetB. + * + * @static + * @memberof Asset + */ + }], [{ + key: "native", + value: function _native() { + return new Asset('XLM'); + } + + /** + * Returns an asset object from its XDR object representation. + * @param {xdr.Asset} assetXdr - The asset xdr object. + * @returns {Asset} + */ + }, { + key: "fromOperation", + value: function fromOperation(assetXdr) { + var anum; + var code; + var issuer; + switch (assetXdr["switch"]()) { + case _xdr["default"].AssetType.assetTypeNative(): + return this["native"](); + case _xdr["default"].AssetType.assetTypeCreditAlphanum4(): + anum = assetXdr.alphaNum4(); + /* falls through */ + case _xdr["default"].AssetType.assetTypeCreditAlphanum12(): + anum = anum || assetXdr.alphaNum12(); + issuer = _strkey.StrKey.encodeEd25519PublicKey(anum.issuer().ed25519()); + code = (0, _util.trimEnd)(anum.assetCode(), '\0'); + return new this(code, issuer); + default: + throw new Error("Invalid asset type: ".concat(assetXdr["switch"]().name)); + } + } + }, { + key: "compare", + value: function compare(assetA, assetB) { + if (!assetA || !(assetA instanceof Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof Asset)) { + throw new Error('assetB is invalid'); + } + if (assetA.equals(assetB)) { + return 0; + } + + // Compare asset types. + var xdrAtype = assetA.getRawAssetType().value; + var xdrBtype = assetB.getRawAssetType().value; + if (xdrAtype !== xdrBtype) { + return xdrAtype < xdrBtype ? -1 : 1; + } + + // Compare asset codes. + var result = asciiCompare(assetA.getCode(), assetB.getCode()); + if (result !== 0) { + return result; + } + + // Compare asset issuers. + return asciiCompare(assetA.getIssuer(), assetB.getIssuer()); + } + }]); +}(); +/** + * Compares two ASCII strings in lexographic order with uppercase precedence. + * + * @param {string} a - the first string to compare + * @param {string} b - the second + * @returns {number} like all `compare()`s: + * -1 if `a < b`, 0 if `a == b`, and 1 if `a > b` + * + * @warning No type-checks are done on the parameters + */ +function asciiCompare(a, b) { + return Buffer.compare(Buffer.from(a, 'ascii'), Buffer.from(b, 'ascii')); +} + +/***/ }), + +/***/ 5328: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.authorizeEntry = authorizeEntry; +exports.authorizeInvocation = authorizeInvocation; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +var _network = __webpack_require__(6202); +var _hashing = __webpack_require__(9152); +var _address = __webpack_require__(1180); +var _scval = __webpack_require__(7177); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +/** + * @async + * @callback SigningCallback A callback for signing an XDR structure + * representing all of the details necessary to authorize an invocation tree. + * + * @param {xdr.HashIdPreimage} preimage the entire authorization envelope + * whose hash you should sign, so that you can inspect the entire structure + * if necessary (rather than blindly signing a hash) + * + * @returns {Promise} the signature of the raw payload (which is + * the sha256 hash of the preimage bytes, so `hash(preimage.toXDR())`) signed + * by the key corresponding to the public key in the entry you pass to + * {@link authorizeEntry} (decipherable from its + * `credentials().address().address()`) + */ +/** + * Actually authorizes an existing authorization entry using the given the + * credentials and expiration details, returning a signed copy. + * + * This "fills out" the authorization entry with a signature, indicating to the + * {@link Operation.invokeHostFunction} its attached to that: + * - a particular identity (i.e. signing {@link Keypair} or other signer) + * - approving the execution of an invocation tree (i.e. a simulation-acquired + * {@link xdr.SorobanAuthorizedInvocation} or otherwise built) + * - on a particular network (uniquely identified by its passphrase, see + * {@link Networks}) + * - until a particular ledger sequence is reached. + * + * This one lets you pass a either a {@link Keypair} (or, more accurately, + * anything with a `sign(Buffer): Buffer` method) or a callback function (see + * {@link SigningCallback}) to handle signing the envelope hash. + * + * @param {xdr.SorobanAuthorizationEntry} entry an unsigned authorization entr + * @param {Keypair | SigningCallback} signer either a {@link Keypair} instance + * or a function which takes a payload (a + * {@link xdr.HashIdPreimageSorobanAuthorization} instance) input and returns + * the signature of the hash of the raw payload bytes (where the signing key + * should correspond to the address in the `entry`) + * @param {number} validUntilLedgerSeq the (exclusive) future ledger sequence + * number until which this authorization entry should be valid (if + * `currentLedgerSeq==validUntil`, this is expired)) + * @param {string} [networkPassphrase] the network passphrase is incorprated + * into the signature (see {@link Networks} for options) + * + * @returns {Promise} a promise for an + * authorization entry that you can pass along to + * {@link Operation.invokeHostFunction} + * + * @note If using the `SigningCallback` variation, the signer is assumed to be + * the entry's credential address. If you need a different key to sign the + * entry, you will need to use different method (e.g., fork this code). + * + * @see authorizeInvocation + * @example + * import { + * SorobanRpc, + * Transaction, + * Networks, + * authorizeEntry + * } from '@stellar/stellar-sdk'; + * + * // Assume signPayloadCallback is a well-formed signing callback. + * // + * // It might, for example, pop up a modal from a browser extension, send the + * // transaction to a third-party service for signing, or just do simple + * // signing via Keypair like it does here: + * function signPayloadCallback(payload) { + * return signer.sign(hash(payload.toXDR()); + * } + * + * function multiPartyAuth( + * server: SorobanRpc.Server, + * // assume this involves multi-party auth + * tx: Transaction, + * ) { + * return server + * .simulateTransaction(tx) + * .then((simResult) => { + * tx.operations[0].auth.map(entry => + * authorizeEntry( + * entry, + * signPayloadCallback, + * currentLedger + 1000, + * Networks.TESTNET); + * )); + * + * return server.prepareTransaction(tx, simResult); + * }) + * .then((preppedTx) => { + * preppedTx.sign(source); + * return server.sendTransaction(preppedTx); + * }); + * } + */ +function authorizeEntry(_x, _x2, _x3) { + return _authorizeEntry.apply(this, arguments); +} +/** + * This builds an entry from scratch, allowing you to express authorization as a + * function of: + * - a particular identity (i.e. signing {@link Keypair} or other signer) + * - approving the execution of an invocation tree (i.e. a simulation-acquired + * {@link xdr.SorobanAuthorizedInvocation} or otherwise built) + * - on a particular network (uniquely identified by its passphrase, see + * {@link Networks}) + * - until a particular ledger sequence is reached. + * + * This is in contrast to {@link authorizeEntry}, which signs an existing entry. + * + * @param {Keypair | SigningCallback} signer either a {@link Keypair} instance + * (or anything with a `.sign(buf): Buffer-like` method) or a function which + * takes a payload (a {@link xdr.HashIdPreimageSorobanAuthorization} + * instance) input and returns the signature of the hash of the raw payload + * bytes (where the signing key should correspond to the address in the + * `entry`) + * @param {number} validUntilLedgerSeq the (exclusive) future ledger sequence + * number until which this authorization entry should be valid (if + * `currentLedgerSeq==validUntilLedgerSeq`, this is expired)) + * @param {xdr.SorobanAuthorizedInvocation} invocation the invocation tree that + * we're authorizing (likely, this comes from transaction simulation) + * @param {string} [publicKey] the public identity of the signer (when + * providing a {@link Keypair} to `signer`, this can be omitted, as it just + * uses {@link Keypair.publicKey}) + * @param {string} [networkPassphrase] the network passphrase is incorprated + * into the signature (see {@link Networks} for options, default: + * {@link Networks.FUTURENET}) + * + * @returns {Promise} a promise for an + * authorization entry that you can pass along to + * {@link Operation.invokeHostFunction} + * + * @see authorizeEntry + */ +function _authorizeEntry() { + _authorizeEntry = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(entry, signer, validUntilLedgerSeq) { + var networkPassphrase, + clone, + addrAuth, + networkId, + preimage, + payload, + signature, + publicKey, + sigScVal, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + networkPassphrase = _args.length > 3 && _args[3] !== undefined ? _args[3] : _network.Networks.FUTURENET; + if (!(entry.credentials()["switch"]().value !== _xdr["default"].SorobanCredentialsType.sorobanCredentialsAddress().value)) { + _context.next = 3; + break; + } + return _context.abrupt("return", entry); + case 3: + clone = _xdr["default"].SorobanAuthorizationEntry.fromXDR(entry.toXDR()); + /** @type {xdr.SorobanAddressCredentials} */ + addrAuth = clone.credentials().address(); + addrAuth.signatureExpirationLedger(validUntilLedgerSeq); + networkId = (0, _hashing.hash)(Buffer.from(networkPassphrase)); + preimage = _xdr["default"].HashIdPreimage.envelopeTypeSorobanAuthorization(new _xdr["default"].HashIdPreimageSorobanAuthorization({ + networkId: networkId, + nonce: addrAuth.nonce(), + invocation: clone.rootInvocation(), + signatureExpirationLedger: addrAuth.signatureExpirationLedger() + })); + payload = (0, _hashing.hash)(preimage.toXDR()); + if (!(typeof signer === 'function')) { + _context.next = 18; + break; + } + _context.t0 = Buffer; + _context.next = 13; + return signer(preimage); + case 13: + _context.t1 = _context.sent; + signature = _context.t0.from.call(_context.t0, _context.t1); + publicKey = _address.Address.fromScAddress(addrAuth.address()).toString(); + _context.next = 20; + break; + case 18: + signature = Buffer.from(signer.sign(payload)); + publicKey = signer.publicKey(); + case 20: + if (_keypair.Keypair.fromPublicKey(publicKey).verify(payload, signature)) { + _context.next = 22; + break; + } + throw new Error("signature doesn't match payload"); + case 22: + // This structure is defined here: + // https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#stellar-account-signatures + // + // Encoding a contract structure as an ScVal means the map keys are supposed + // to be symbols, hence the forced typing here. + sigScVal = (0, _scval.nativeToScVal)({ + public_key: _strkey.StrKey.decodeEd25519PublicKey(publicKey), + signature: signature + }, { + type: { + public_key: ['symbol', null], + signature: ['symbol', null] + } + }); + addrAuth.signature(_xdr["default"].ScVal.scvVec([sigScVal])); + return _context.abrupt("return", clone); + case 25: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _authorizeEntry.apply(this, arguments); +} +function authorizeInvocation(signer, validUntilLedgerSeq, invocation) { + var publicKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; + var networkPassphrase = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : _network.Networks.FUTURENET; + // We use keypairs as a source of randomness for the nonce to avoid mucking + // with any crypto dependencies. Note that this just has to be random and + // unique, not cryptographically secure, so it's fine. + var kp = _keypair.Keypair.random().rawPublicKey(); + var nonce = new _xdr["default"].Int64(bytesToInt64(kp)); + var pk = publicKey || signer.publicKey(); + if (!pk) { + throw new Error("authorizeInvocation requires publicKey parameter"); + } + var entry = new _xdr["default"].SorobanAuthorizationEntry({ + rootInvocation: invocation, + credentials: _xdr["default"].SorobanCredentials.sorobanCredentialsAddress(new _xdr["default"].SorobanAddressCredentials({ + address: new _address.Address(pk).toScAddress(), + nonce: nonce, + signatureExpirationLedger: 0, + // replaced + signature: _xdr["default"].ScVal.scvVec([]) // replaced + })) + }); + return authorizeEntry(entry, signer, validUntilLedgerSeq, networkPassphrase); +} +function bytesToInt64(bytes) { + // eslint-disable-next-line no-bitwise + return bytes.subarray(0, 8).reduce(function (accum, b) { + return accum << 8 | b; + }, 0); +} + +/***/ }), + +/***/ 1387: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Claimant = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Claimant class represents an xdr.Claimant + * + * The claim predicate is optional, it defaults to unconditional if none is specified. + * + * @constructor + * @param {string} destination - The destination account ID. + * @param {xdr.ClaimPredicate} [predicate] - The claim predicate. + */ +var Claimant = exports.Claimant = /*#__PURE__*/function () { + function Claimant(destination, predicate) { + _classCallCheck(this, Claimant); + if (destination && !_strkey.StrKey.isValidEd25519PublicKey(destination)) { + throw new Error('Destination is invalid'); + } + this._destination = destination; + if (!predicate) { + this._predicate = _xdr["default"].ClaimPredicate.claimPredicateUnconditional(); + } else if (predicate instanceof _xdr["default"].ClaimPredicate) { + this._predicate = predicate; + } else { + throw new Error('Predicate should be an xdr.ClaimPredicate'); + } + } + + /** + * Returns an unconditional claim predicate + * @Return {xdr.ClaimPredicate} + */ + return _createClass(Claimant, [{ + key: "toXDRObject", + value: + /** + * Returns the xdr object for this claimant. + * @returns {xdr.Claimant} XDR Claimant object + */ + function toXDRObject() { + var claimant = new _xdr["default"].ClaimantV0({ + destination: _keypair.Keypair.fromPublicKey(this._destination).xdrAccountId(), + predicate: this._predicate + }); + return _xdr["default"].Claimant.claimantTypeV0(claimant); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "destination", + get: function get() { + return this._destination; + }, + set: function set(value) { + throw new Error('Claimant is immutable'); + } + + /** + * @type {xdr.ClaimPredicate} + * @readonly + */ + }, { + key: "predicate", + get: function get() { + return this._predicate; + }, + set: function set(value) { + throw new Error('Claimant is immutable'); + } + }], [{ + key: "predicateUnconditional", + value: function predicateUnconditional() { + return _xdr["default"].ClaimPredicate.claimPredicateUnconditional(); + } + + /** + * Returns an `and` claim predicate + * @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate + * @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateAnd", + value: function predicateAnd(left, right) { + if (!(left instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('left Predicate should be an xdr.ClaimPredicate'); + } + if (!(right instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateAnd([left, right]); + } + + /** + * Returns an `or` claim predicate + * @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate + * @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateOr", + value: function predicateOr(left, right) { + if (!(left instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('left Predicate should be an xdr.ClaimPredicate'); + } + if (!(right instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateOr([left, right]); + } + + /** + * Returns a `not` claim predicate + * @param {xdr.ClaimPredicate} predicate an xdr.ClaimPredicate + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateNot", + value: function predicateNot(predicate) { + if (!(predicate instanceof _xdr["default"].ClaimPredicate)) { + throw new Error('right Predicate should be an xdr.ClaimPredicate'); + } + return _xdr["default"].ClaimPredicate.claimPredicateNot(predicate); + } + + /** + * Returns a `BeforeAbsoluteTime` claim predicate + * + * This predicate will be fulfilled if the closing time of the ledger that + * includes the CreateClaimableBalance operation is less than this (absolute) + * Unix timestamp (expressed in seconds). + * + * @param {string} absBefore Unix epoch (in seconds) as a string + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateBeforeAbsoluteTime", + value: function predicateBeforeAbsoluteTime(absBefore) { + return _xdr["default"].ClaimPredicate.claimPredicateBeforeAbsoluteTime(_xdr["default"].Int64.fromString(absBefore)); + } + + /** + * Returns a `BeforeRelativeTime` claim predicate + * + * This predicate will be fulfilled if the closing time of the ledger that + * includes the CreateClaimableBalance operation plus this relative time delta + * (in seconds) is less than the current time. + * + * @param {strings} seconds seconds since closeTime of the ledger in which the ClaimableBalanceEntry was created (as string) + * @Return {xdr.ClaimPredicate} + */ + }, { + key: "predicateBeforeRelativeTime", + value: function predicateBeforeRelativeTime(seconds) { + return _xdr["default"].ClaimPredicate.claimPredicateBeforeRelativeTime(_xdr["default"].Int64.fromString(seconds)); + } + + /** + * Returns a claimant object from its XDR object representation. + * @param {xdr.Claimant} claimantXdr - The claimant xdr object. + * @returns {Claimant} + */ + }, { + key: "fromXDR", + value: function fromXDR(claimantXdr) { + var value; + switch (claimantXdr["switch"]()) { + case _xdr["default"].ClaimantType.claimantTypeV0(): + value = claimantXdr.v0(); + return new this(_strkey.StrKey.encodeEd25519PublicKey(value.destination().ed25519()), value.predicate()); + default: + throw new Error("Invalid claimant type: ".concat(claimantXdr["switch"]().name)); + } + } + }]); +}(); + +/***/ }), + +/***/ 7452: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Contract = void 0; +var _address = __webpack_require__(1180); +var _operation = __webpack_require__(7237); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Create a new Contract object. + * + * `Contract` represents a single contract in the Stellar network, embodying the + * interface of the contract. See + * [Contracts](https://soroban.stellar.org/docs/learn/interacting-with-contracts) + * for more information about how contracts work in Stellar. + * + * @constructor + * + * @param {string} contractId - ID of the contract (ex. + * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`). + */ +var Contract = exports.Contract = /*#__PURE__*/function () { + function Contract(contractId) { + _classCallCheck(this, Contract); + try { + // First, try it as a strkey + this._id = _strkey.StrKey.decodeContract(contractId); + } catch (_) { + throw new Error("Invalid contract ID: ".concat(contractId)); + } + } + + /** + * Returns Stellar contract ID as a strkey, ex. + * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`. + * @returns {string} + */ + return _createClass(Contract, [{ + key: "contractId", + value: function contractId() { + return _strkey.StrKey.encodeContract(this._id); + } + + /** @returns {string} the ID as a strkey (C...) */ + }, { + key: "toString", + value: function toString() { + return this.contractId(); + } + + /** @returns {Address} the wrapped address of this contract */ + }, { + key: "address", + value: function address() { + return _address.Address.contract(this._id); + } + + /** + * Returns an operation that will invoke this contract call. + * + * @param {string} method name of the method to call + * @param {...xdr.ScVal} params arguments to pass to the function call + * + * @returns {xdr.Operation} an InvokeHostFunctionOp operation to call the + * contract with the given method and parameters + * + * @see Operation.invokeHostFunction + * @see Operation.invokeContractFunction + * @see Operation.createCustomContract + * @see Operation.createStellarAssetContract + * @see Operation.uploadContractWasm + */ + }, { + key: "call", + value: function call(method) { + for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + params[_key - 1] = arguments[_key]; + } + return _operation.Operation.invokeContractFunction({ + contract: this.address().toString(), + "function": method, + args: params + }); + } + + /** + * Returns the read-only footprint entries necessary for any invocations to + * this contract, for convenience when manually adding it to your + * transaction's overall footprint or doing bump/restore operations. + * + * @returns {xdr.LedgerKey} the ledger key for the deployed contract instance + */ + }, { + key: "getFootprint", + value: function getFootprint() { + return _xdr["default"].LedgerKey.contractData(new _xdr["default"].LedgerKeyContractData({ + contract: this.address().toScAddress(), + key: _xdr["default"].ScVal.scvLedgerKeyContractInstance(), + durability: _xdr["default"].ContractDataDurability.persistent() + })); + } + }]); +}(); + +/***/ }), + +/***/ 3919: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.humanizeEvents = humanizeEvents; +var _strkey = __webpack_require__(7120); +var _scval = __webpack_require__(7177); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Converts raw diagnostic or contract events into something with a flatter, + * human-readable, and understandable structure. + * + * @param {xdr.DiagnosticEvent[] | xdr.ContractEvent[]} events either contract + * events or diagnostic events to parse into a friendly format + * + * @returns {SorobanEvent[]} a list of human-readable event structures, where + * each element has the following properties: + * - type: a string of one of 'system', 'contract', 'diagnostic + * - contractId?: optionally, a `C...` encoded strkey + * - topics: a list of {@link scValToNative} invocations on the topics + * - data: similarly, a {@link scValToNative} invocation on the raw event data + */ +function humanizeEvents(events) { + return events.map(function (e) { + // A pseudo-instanceof check for xdr.DiagnosticEvent more reliable + // in mixed SDK environments: + if (e.inSuccessfulContractCall) { + return extractEvent(e.event()); + } + return extractEvent(e); + }); +} +function extractEvent(event) { + return _objectSpread(_objectSpread({}, typeof event.contractId === 'function' && event.contractId() != null && { + contractId: _strkey.StrKey.encodeContract(event.contractId()) + }), {}, { + type: event.type().name, + topics: event.body().value().topics().map(function (t) { + return (0, _scval.scValToNative)(t); + }), + data: (0, _scval.scValToNative)(event.body().value().data()) + }); +} + +/***/ }), + +/***/ 9260: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.FeeBumpTransaction = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _hashing = __webpack_require__(9152); +var _transaction = __webpack_require__(380); +var _transaction_base = __webpack_require__(3758); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Use {@link TransactionBuilder.buildFeeBumpTransaction} to build a + * FeeBumpTransaction object. If you have an object or base64-encoded string of + * the transaction envelope XDR use {@link TransactionBuilder.fromXDR}. + * + * Once a {@link FeeBumpTransaction} has been created, its attributes and operations + * should not be changed. You should only add signatures (using {@link FeeBumpTransaction#sign}) before + * submitting to the network or forwarding on to additional signers. + * + * @param {string|xdr.TransactionEnvelope} envelope - transaction envelope + * object or base64 encoded string. + * @param {string} networkPassphrase - passphrase of the target Stellar network + * (e.g. "Public Global Stellar Network ; September 2015"). + * + * @extends TransactionBase + */ +var FeeBumpTransaction = exports.FeeBumpTransaction = /*#__PURE__*/function (_TransactionBase) { + function FeeBumpTransaction(envelope, networkPassphrase) { + var _this; + _classCallCheck(this, FeeBumpTransaction); + if (typeof envelope === 'string') { + var buffer = Buffer.from(envelope, 'base64'); + envelope = _xdr["default"].TransactionEnvelope.fromXDR(buffer); + } + var envelopeType = envelope["switch"](); + if (envelopeType !== _xdr["default"].EnvelopeType.envelopeTypeTxFeeBump()) { + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxFeeBump but received an ".concat(envelopeType.name, ".")); + } + var txEnvelope = envelope.value(); + var tx = txEnvelope.tx(); + var fee = tx.fee().toString(); + // clone signatures + var signatures = (txEnvelope.signatures() || []).slice(); + _this = _callSuper(this, FeeBumpTransaction, [tx, signatures, fee, networkPassphrase]); + var innerTxEnvelope = _xdr["default"].TransactionEnvelope.envelopeTypeTx(tx.innerTx().v1()); + _this._feeSource = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(_this.tx.feeSource()); + _this._innerTransaction = new _transaction.Transaction(innerTxEnvelope, networkPassphrase); + return _this; + } + + /** + * @type {Transaction} + * @readonly + */ + _inherits(FeeBumpTransaction, _TransactionBase); + return _createClass(FeeBumpTransaction, [{ + key: "innerTransaction", + get: function get() { + return this._innerTransaction; + } + + /** + * @type {Operation[]} + * @readonly + */ + }, { + key: "operations", + get: function get() { + return this._innerTransaction.operations; + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "feeSource", + get: function get() { + return this._feeSource; + } + + /** + * Returns the "signature base" of this transaction, which is the value + * that, when hashed, should be signed to create a signature that + * validators on the Stellar Network will accept. + * + * It is composed of a 4 prefix bytes followed by the xdr-encoded form + * of this transaction. + * @returns {Buffer} + */ + }, { + key: "signatureBase", + value: function signatureBase() { + var taggedTransaction = new _xdr["default"].TransactionSignaturePayloadTaggedTransaction.envelopeTypeTxFeeBump(this.tx); + var txSignature = new _xdr["default"].TransactionSignaturePayload({ + networkId: _xdr["default"].Hash.fromXDR((0, _hashing.hash)(this.networkPassphrase)), + taggedTransaction: taggedTransaction + }); + return txSignature.toXDR(); + } + + /** + * To envelope returns a xdr.TransactionEnvelope which can be submitted to the network. + * @returns {xdr.TransactionEnvelope} + */ + }, { + key: "toEnvelope", + value: function toEnvelope() { + var envelope = new _xdr["default"].FeeBumpTransactionEnvelope({ + tx: _xdr["default"].FeeBumpTransaction.fromXDR(this.tx.toXDR()), + // make a copy of the tx + signatures: this.signatures.slice() // make a copy of the signatures + }); + return new _xdr["default"].TransactionEnvelope.envelopeTypeTxFeeBump(envelope); + } + }]); +}(_transaction_base.TransactionBase); + +/***/ }), + +/***/ 7938: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var XDR = _interopRequireWildcard(__webpack_require__(3740)); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +// Automatically generated by xdrgen on 2024-09-12T11:09:00-08:00 +// DO NOT EDIT or your changes may be overwritten + +/* jshint maxstatements:2147483647 */ +/* jshint esnext:true */ + +var types = XDR.config(function (xdr) { + // Workaround for https://github.com/stellar/xdrgen/issues/152 + // + // The "correct" way would be to replace bare instances of each constant with + // xdr.lookup("..."), but that's more error-prone. + var SCSYMBOL_LIMIT = 32; + var SC_SPEC_DOC_LIMIT = 1024; + + // === xdr source ============================================================ + // + // typedef opaque Value<>; + // + // =========================================================================== + xdr.typedef("Value", xdr.varOpaque()); + + // === xdr source ============================================================ + // + // struct SCPBallot + // { + // uint32 counter; // n + // Value value; // x + // }; + // + // =========================================================================== + xdr.struct("ScpBallot", [["counter", xdr.lookup("Uint32")], ["value", xdr.lookup("Value")]]); + + // === xdr source ============================================================ + // + // enum SCPStatementType + // { + // SCP_ST_PREPARE = 0, + // SCP_ST_CONFIRM = 1, + // SCP_ST_EXTERNALIZE = 2, + // SCP_ST_NOMINATE = 3 + // }; + // + // =========================================================================== + xdr["enum"]("ScpStatementType", { + scpStPrepare: 0, + scpStConfirm: 1, + scpStExternalize: 2, + scpStNominate: 3 + }); + + // === xdr source ============================================================ + // + // struct SCPNomination + // { + // Hash quorumSetHash; // D + // Value votes<>; // X + // Value accepted<>; // Y + // }; + // + // =========================================================================== + xdr.struct("ScpNomination", [["quorumSetHash", xdr.lookup("Hash")], ["votes", xdr.varArray(xdr.lookup("Value"), 2147483647)], ["accepted", xdr.varArray(xdr.lookup("Value"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } + // + // =========================================================================== + xdr.struct("ScpStatementPrepare", [["quorumSetHash", xdr.lookup("Hash")], ["ballot", xdr.lookup("ScpBallot")], ["prepared", xdr.option(xdr.lookup("ScpBallot"))], ["preparedPrime", xdr.option(xdr.lookup("ScpBallot"))], ["nC", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } + // + // =========================================================================== + xdr.struct("ScpStatementConfirm", [["ballot", xdr.lookup("ScpBallot")], ["nPrepared", xdr.lookup("Uint32")], ["nCommit", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")], ["quorumSetHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } + // + // =========================================================================== + xdr.struct("ScpStatementExternalize", [["commit", xdr.lookup("ScpBallot")], ["nH", xdr.lookup("Uint32")], ["commitQuorumSetHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union switch (SCPStatementType type) + // { + // case SCP_ST_PREPARE: + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } prepare; + // case SCP_ST_CONFIRM: + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } confirm; + // case SCP_ST_EXTERNALIZE: + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } externalize; + // case SCP_ST_NOMINATE: + // SCPNomination nominate; + // } + // + // =========================================================================== + xdr.union("ScpStatementPledges", { + switchOn: xdr.lookup("ScpStatementType"), + switchName: "type", + switches: [["scpStPrepare", "prepare"], ["scpStConfirm", "confirm"], ["scpStExternalize", "externalize"], ["scpStNominate", "nominate"]], + arms: { + prepare: xdr.lookup("ScpStatementPrepare"), + confirm: xdr.lookup("ScpStatementConfirm"), + externalize: xdr.lookup("ScpStatementExternalize"), + nominate: xdr.lookup("ScpNomination") + } + }); + + // === xdr source ============================================================ + // + // struct SCPStatement + // { + // NodeID nodeID; // v + // uint64 slotIndex; // i + // + // union switch (SCPStatementType type) + // { + // case SCP_ST_PREPARE: + // struct + // { + // Hash quorumSetHash; // D + // SCPBallot ballot; // b + // SCPBallot* prepared; // p + // SCPBallot* preparedPrime; // p' + // uint32 nC; // c.n + // uint32 nH; // h.n + // } prepare; + // case SCP_ST_CONFIRM: + // struct + // { + // SCPBallot ballot; // b + // uint32 nPrepared; // p.n + // uint32 nCommit; // c.n + // uint32 nH; // h.n + // Hash quorumSetHash; // D + // } confirm; + // case SCP_ST_EXTERNALIZE: + // struct + // { + // SCPBallot commit; // c + // uint32 nH; // h.n + // Hash commitQuorumSetHash; // D used before EXTERNALIZE + // } externalize; + // case SCP_ST_NOMINATE: + // SCPNomination nominate; + // } + // pledges; + // }; + // + // =========================================================================== + xdr.struct("ScpStatement", [["nodeId", xdr.lookup("NodeId")], ["slotIndex", xdr.lookup("Uint64")], ["pledges", xdr.lookup("ScpStatementPledges")]]); + + // === xdr source ============================================================ + // + // struct SCPEnvelope + // { + // SCPStatement statement; + // Signature signature; + // }; + // + // =========================================================================== + xdr.struct("ScpEnvelope", [["statement", xdr.lookup("ScpStatement")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // struct SCPQuorumSet + // { + // uint32 threshold; + // NodeID validators<>; + // SCPQuorumSet innerSets<>; + // }; + // + // =========================================================================== + xdr.struct("ScpQuorumSet", [["threshold", xdr.lookup("Uint32")], ["validators", xdr.varArray(xdr.lookup("NodeId"), 2147483647)], ["innerSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)]]); + + // === xdr source ============================================================ + // + // typedef opaque Thresholds[4]; + // + // =========================================================================== + xdr.typedef("Thresholds", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef string string32<32>; + // + // =========================================================================== + xdr.typedef("String32", xdr.string(32)); + + // === xdr source ============================================================ + // + // typedef string string64<64>; + // + // =========================================================================== + xdr.typedef("String64", xdr.string(64)); + + // === xdr source ============================================================ + // + // typedef int64 SequenceNumber; + // + // =========================================================================== + xdr.typedef("SequenceNumber", xdr.lookup("Int64")); + + // === xdr source ============================================================ + // + // typedef opaque DataValue<64>; + // + // =========================================================================== + xdr.typedef("DataValue", xdr.varOpaque(64)); + + // === xdr source ============================================================ + // + // typedef Hash PoolID; + // + // =========================================================================== + xdr.typedef("PoolId", xdr.lookup("Hash")); + + // === xdr source ============================================================ + // + // typedef opaque AssetCode4[4]; + // + // =========================================================================== + xdr.typedef("AssetCode4", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef opaque AssetCode12[12]; + // + // =========================================================================== + xdr.typedef("AssetCode12", xdr.opaque(12)); + + // === xdr source ============================================================ + // + // enum AssetType + // { + // ASSET_TYPE_NATIVE = 0, + // ASSET_TYPE_CREDIT_ALPHANUM4 = 1, + // ASSET_TYPE_CREDIT_ALPHANUM12 = 2, + // ASSET_TYPE_POOL_SHARE = 3 + // }; + // + // =========================================================================== + xdr["enum"]("AssetType", { + assetTypeNative: 0, + assetTypeCreditAlphanum4: 1, + assetTypeCreditAlphanum12: 2, + assetTypePoolShare: 3 + }); + + // === xdr source ============================================================ + // + // union AssetCode switch (AssetType type) + // { + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AssetCode4 assetCode4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AssetCode12 assetCode12; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("AssetCode", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeCreditAlphanum4", "assetCode4"], ["assetTypeCreditAlphanum12", "assetCode12"]], + arms: { + assetCode4: xdr.lookup("AssetCode4"), + assetCode12: xdr.lookup("AssetCode12") + } + }); + + // === xdr source ============================================================ + // + // struct AlphaNum4 + // { + // AssetCode4 assetCode; + // AccountID issuer; + // }; + // + // =========================================================================== + xdr.struct("AlphaNum4", [["assetCode", xdr.lookup("AssetCode4")], ["issuer", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // struct AlphaNum12 + // { + // AssetCode12 assetCode; + // AccountID issuer; + // }; + // + // =========================================================================== + xdr.struct("AlphaNum12", [["assetCode", xdr.lookup("AssetCode12")], ["issuer", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // union Asset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("Asset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12") + } + }); + + // === xdr source ============================================================ + // + // struct Price + // { + // int32 n; // numerator + // int32 d; // denominator + // }; + // + // =========================================================================== + xdr.struct("Price", [["n", xdr.lookup("Int32")], ["d", xdr.lookup("Int32")]]); + + // === xdr source ============================================================ + // + // struct Liabilities + // { + // int64 buying; + // int64 selling; + // }; + // + // =========================================================================== + xdr.struct("Liabilities", [["buying", xdr.lookup("Int64")], ["selling", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum ThresholdIndexes + // { + // THRESHOLD_MASTER_WEIGHT = 0, + // THRESHOLD_LOW = 1, + // THRESHOLD_MED = 2, + // THRESHOLD_HIGH = 3 + // }; + // + // =========================================================================== + xdr["enum"]("ThresholdIndices", { + thresholdMasterWeight: 0, + thresholdLow: 1, + thresholdMed: 2, + thresholdHigh: 3 + }); + + // === xdr source ============================================================ + // + // enum LedgerEntryType + // { + // ACCOUNT = 0, + // TRUSTLINE = 1, + // OFFER = 2, + // DATA = 3, + // CLAIMABLE_BALANCE = 4, + // LIQUIDITY_POOL = 5, + // CONTRACT_DATA = 6, + // CONTRACT_CODE = 7, + // CONFIG_SETTING = 8, + // TTL = 9 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerEntryType", { + account: 0, + trustline: 1, + offer: 2, + data: 3, + claimableBalance: 4, + liquidityPool: 5, + contractData: 6, + contractCode: 7, + configSetting: 8, + ttl: 9 + }); + + // === xdr source ============================================================ + // + // struct Signer + // { + // SignerKey key; + // uint32 weight; // really only need 1 byte + // }; + // + // =========================================================================== + xdr.struct("Signer", [["key", xdr.lookup("SignerKey")], ["weight", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // enum AccountFlags + // { // masks for each flag + // + // // Flags set on issuer accounts + // // TrustLines are created with authorized set to "false" requiring + // // the issuer to set it for each TrustLine + // AUTH_REQUIRED_FLAG = 0x1, + // // If set, the authorized flag in TrustLines can be cleared + // // otherwise, authorization cannot be revoked + // AUTH_REVOCABLE_FLAG = 0x2, + // // Once set, causes all AUTH_* flags to be read-only + // AUTH_IMMUTABLE_FLAG = 0x4, + // // Trustlines are created with clawback enabled set to "true", + // // and claimable balances created from those trustlines are created + // // with clawback enabled set to "true" + // AUTH_CLAWBACK_ENABLED_FLAG = 0x8 + // }; + // + // =========================================================================== + xdr["enum"]("AccountFlags", { + authRequiredFlag: 1, + authRevocableFlag: 2, + authImmutableFlag: 4, + authClawbackEnabledFlag: 8 + }); + + // === xdr source ============================================================ + // + // const MASK_ACCOUNT_FLAGS = 0x7; + // + // =========================================================================== + xdr["const"]("MASK_ACCOUNT_FLAGS", 0x7); + + // === xdr source ============================================================ + // + // const MASK_ACCOUNT_FLAGS_V17 = 0xF; + // + // =========================================================================== + xdr["const"]("MASK_ACCOUNT_FLAGS_V17", 0xF); + + // === xdr source ============================================================ + // + // const MAX_SIGNERS = 20; + // + // =========================================================================== + xdr["const"]("MAX_SIGNERS", 20); + + // === xdr source ============================================================ + // + // typedef AccountID* SponsorshipDescriptor; + // + // =========================================================================== + xdr.typedef("SponsorshipDescriptor", xdr.option(xdr.lookup("AccountId"))); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV3 + // { + // // We can use this to add more fields, or because it is first, to + // // change AccountEntryExtensionV3 into a union. + // ExtensionPoint ext; + // + // // Ledger number at which `seqNum` took on its present value. + // uint32 seqLedger; + // + // // Time at which `seqNum` took on its present value. + // TimePoint seqTime; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV3", [["ext", xdr.lookup("ExtensionPoint")], ["seqLedger", xdr.lookup("Uint32")], ["seqTime", xdr.lookup("TimePoint")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 3: + // AccountEntryExtensionV3 v3; + // } + // + // =========================================================================== + xdr.union("AccountEntryExtensionV2Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [3, "v3"]], + arms: { + v3: xdr.lookup("AccountEntryExtensionV3") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV2 + // { + // uint32 numSponsored; + // uint32 numSponsoring; + // SponsorshipDescriptor signerSponsoringIDs; + // + // union switch (int v) + // { + // case 0: + // void; + // case 3: + // AccountEntryExtensionV3 v3; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV2", [["numSponsored", xdr.lookup("Uint32")], ["numSponsoring", xdr.lookup("Uint32")], ["signerSponsoringIDs", xdr.varArray(xdr.lookup("SponsorshipDescriptor"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExtensionV2Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // AccountEntryExtensionV2 v2; + // } + // + // =========================================================================== + xdr.union("AccountEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [2, "v2"]], + arms: { + v2: xdr.lookup("AccountEntryExtensionV2") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntryExtensionV1 + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // AccountEntryExtensionV2 v2; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntryExtensionV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("AccountEntryExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // AccountEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("AccountEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("AccountEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct AccountEntry + // { + // AccountID accountID; // master public key for this account + // int64 balance; // in stroops + // SequenceNumber seqNum; // last sequence number used for this account + // uint32 numSubEntries; // number of sub-entries this account has + // // drives the reserve + // AccountID* inflationDest; // Account to vote for during inflation + // uint32 flags; // see AccountFlags + // + // string32 homeDomain; // can be used for reverse federation and memo lookup + // + // // fields used for signatures + // // thresholds stores unsigned bytes: [weight of master|low|medium|high] + // Thresholds thresholds; + // + // Signer signers; // possible signers for this account + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // AccountEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("AccountEntry", [["accountId", xdr.lookup("AccountId")], ["balance", xdr.lookup("Int64")], ["seqNum", xdr.lookup("SequenceNumber")], ["numSubEntries", xdr.lookup("Uint32")], ["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["flags", xdr.lookup("Uint32")], ["homeDomain", xdr.lookup("String32")], ["thresholds", xdr.lookup("Thresholds")], ["signers", xdr.varArray(xdr.lookup("Signer"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExt")]]); + + // === xdr source ============================================================ + // + // enum TrustLineFlags + // { + // // issuer has authorized account to perform transactions with its credit + // AUTHORIZED_FLAG = 1, + // // issuer has authorized account to maintain and reduce liabilities for its + // // credit + // AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG = 2, + // // issuer has specified that it may clawback its credit, and that claimable + // // balances created with its credit may also be clawed back + // TRUSTLINE_CLAWBACK_ENABLED_FLAG = 4 + // }; + // + // =========================================================================== + xdr["enum"]("TrustLineFlags", { + authorizedFlag: 1, + authorizedToMaintainLiabilitiesFlag: 2, + trustlineClawbackEnabledFlag: 4 + }); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS = 1; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS", 1); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS_V13 = 3; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS_V13", 3); + + // === xdr source ============================================================ + // + // const MASK_TRUSTLINE_FLAGS_V17 = 7; + // + // =========================================================================== + xdr["const"]("MASK_TRUSTLINE_FLAGS_V17", 7); + + // === xdr source ============================================================ + // + // enum LiquidityPoolType + // { + // LIQUIDITY_POOL_CONSTANT_PRODUCT = 0 + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolType", { + liquidityPoolConstantProduct: 0 + }); + + // === xdr source ============================================================ + // + // union TrustLineAsset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // case ASSET_TYPE_POOL_SHARE: + // PoolID liquidityPoolID; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("TrustLineAsset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPoolId"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12"), + liquidityPoolId: xdr.lookup("PoolId") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryExtensionV2Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TrustLineEntryExtensionV2 + // { + // int32 liquidityPoolUseCount; + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TrustLineEntryExtensionV2", [["liquidityPoolUseCount", xdr.lookup("Int32")], ["ext", xdr.lookup("TrustLineEntryExtensionV2Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [2, "v2"]], + arms: { + v2: xdr.lookup("TrustLineEntryExtensionV2") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } + // + // =========================================================================== + xdr.struct("TrustLineEntryV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("TrustLineEntryV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } v1; + // } + // + // =========================================================================== + xdr.union("TrustLineEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("TrustLineEntryV1") + } + }); + + // === xdr source ============================================================ + // + // struct TrustLineEntry + // { + // AccountID accountID; // account this trustline belongs to + // TrustLineAsset asset; // type of asset (with issuer) + // int64 balance; // how much of this asset the user has. + // // Asset defines the unit for this; + // + // int64 limit; // balance cannot be above this + // uint32 flags; // see TrustLineFlags + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // Liabilities liabilities; + // + // union switch (int v) + // { + // case 0: + // void; + // case 2: + // TrustLineEntryExtensionV2 v2; + // } + // ext; + // } v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TrustLineEntry", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")], ["balance", xdr.lookup("Int64")], ["limit", xdr.lookup("Int64")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("TrustLineEntryExt")]]); + + // === xdr source ============================================================ + // + // enum OfferEntryFlags + // { + // // an offer with this flag will not act on and take a reverse offer of equal + // // price + // PASSIVE_FLAG = 1 + // }; + // + // =========================================================================== + xdr["enum"]("OfferEntryFlags", { + passiveFlag: 1 + }); + + // === xdr source ============================================================ + // + // const MASK_OFFERENTRY_FLAGS = 1; + // + // =========================================================================== + xdr["const"]("MASK_OFFERENTRY_FLAGS", 1); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("OfferEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct OfferEntry + // { + // AccountID sellerID; + // int64 offerID; + // Asset selling; // A + // Asset buying; // B + // int64 amount; // amount of A + // + // /* price for this offer: + // price of A in terms of B + // price=AmountB/AmountA=priceNumerator/priceDenominator + // price is after fees + // */ + // Price price; + // uint32 flags; // see OfferEntryFlags + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("OfferEntry", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("OfferEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("DataEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct DataEntry + // { + // AccountID accountID; // account this data belongs to + // string64 dataName; + // DataValue dataValue; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("DataEntry", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")], ["dataValue", xdr.lookup("DataValue")], ["ext", xdr.lookup("DataEntryExt")]]); + + // === xdr source ============================================================ + // + // enum ClaimPredicateType + // { + // CLAIM_PREDICATE_UNCONDITIONAL = 0, + // CLAIM_PREDICATE_AND = 1, + // CLAIM_PREDICATE_OR = 2, + // CLAIM_PREDICATE_NOT = 3, + // CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME = 4, + // CLAIM_PREDICATE_BEFORE_RELATIVE_TIME = 5 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimPredicateType", { + claimPredicateUnconditional: 0, + claimPredicateAnd: 1, + claimPredicateOr: 2, + claimPredicateNot: 3, + claimPredicateBeforeAbsoluteTime: 4, + claimPredicateBeforeRelativeTime: 5 + }); + + // === xdr source ============================================================ + // + // union ClaimPredicate switch (ClaimPredicateType type) + // { + // case CLAIM_PREDICATE_UNCONDITIONAL: + // void; + // case CLAIM_PREDICATE_AND: + // ClaimPredicate andPredicates<2>; + // case CLAIM_PREDICATE_OR: + // ClaimPredicate orPredicates<2>; + // case CLAIM_PREDICATE_NOT: + // ClaimPredicate* notPredicate; + // case CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME: + // int64 absBefore; // Predicate will be true if closeTime < absBefore + // case CLAIM_PREDICATE_BEFORE_RELATIVE_TIME: + // int64 relBefore; // Seconds since closeTime of the ledger in which the + // // ClaimableBalanceEntry was created + // }; + // + // =========================================================================== + xdr.union("ClaimPredicate", { + switchOn: xdr.lookup("ClaimPredicateType"), + switchName: "type", + switches: [["claimPredicateUnconditional", xdr["void"]()], ["claimPredicateAnd", "andPredicates"], ["claimPredicateOr", "orPredicates"], ["claimPredicateNot", "notPredicate"], ["claimPredicateBeforeAbsoluteTime", "absBefore"], ["claimPredicateBeforeRelativeTime", "relBefore"]], + arms: { + andPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2), + orPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2), + notPredicate: xdr.option(xdr.lookup("ClaimPredicate")), + absBefore: xdr.lookup("Int64"), + relBefore: xdr.lookup("Int64") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimantType + // { + // CLAIMANT_TYPE_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimantType", { + claimantTypeV0: 0 + }); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID destination; // The account that can use this condition + // ClaimPredicate predicate; // Claimable if predicate is true + // } + // + // =========================================================================== + xdr.struct("ClaimantV0", [["destination", xdr.lookup("AccountId")], ["predicate", xdr.lookup("ClaimPredicate")]]); + + // === xdr source ============================================================ + // + // union Claimant switch (ClaimantType type) + // { + // case CLAIMANT_TYPE_V0: + // struct + // { + // AccountID destination; // The account that can use this condition + // ClaimPredicate predicate; // Claimable if predicate is true + // } v0; + // }; + // + // =========================================================================== + xdr.union("Claimant", { + switchOn: xdr.lookup("ClaimantType"), + switchName: "type", + switches: [["claimantTypeV0", "v0"]], + arms: { + v0: xdr.lookup("ClaimantV0") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimableBalanceIDType + // { + // CLAIMABLE_BALANCE_ID_TYPE_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimableBalanceIdType", { + claimableBalanceIdTypeV0: 0 + }); + + // === xdr source ============================================================ + // + // union ClaimableBalanceID switch (ClaimableBalanceIDType type) + // { + // case CLAIMABLE_BALANCE_ID_TYPE_V0: + // Hash v0; + // }; + // + // =========================================================================== + xdr.union("ClaimableBalanceId", { + switchOn: xdr.lookup("ClaimableBalanceIdType"), + switchName: "type", + switches: [["claimableBalanceIdTypeV0", "v0"]], + arms: { + v0: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimableBalanceFlags + // { + // // If set, the issuer account of the asset held by the claimable balance may + // // clawback the claimable balance + // CLAIMABLE_BALANCE_CLAWBACK_ENABLED_FLAG = 0x1 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimableBalanceFlags", { + claimableBalanceClawbackEnabledFlag: 1 + }); + + // === xdr source ============================================================ + // + // const MASK_CLAIMABLE_BALANCE_FLAGS = 0x1; + // + // =========================================================================== + xdr["const"]("MASK_CLAIMABLE_BALANCE_FLAGS", 0x1); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("ClaimableBalanceEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct ClaimableBalanceEntryExtensionV1 + // { + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // + // uint32 flags; // see ClaimableBalanceFlags + // }; + // + // =========================================================================== + xdr.struct("ClaimableBalanceEntryExtensionV1", [["ext", xdr.lookup("ClaimableBalanceEntryExtensionV1Ext")], ["flags", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ClaimableBalanceEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("ClaimableBalanceEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("ClaimableBalanceEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct ClaimableBalanceEntry + // { + // // Unique identifier for this ClaimableBalanceEntry + // ClaimableBalanceID balanceID; + // + // // List of claimants with associated predicate + // Claimant claimants<10>; + // + // // Any asset including native + // Asset asset; + // + // // Amount of asset + // int64 amount; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // ClaimableBalanceEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("ClaimableBalanceEntry", [["balanceId", xdr.lookup("ClaimableBalanceId")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["ext", xdr.lookup("ClaimableBalanceEntryExt")]]); + + // === xdr source ============================================================ + // + // struct LiquidityPoolConstantProductParameters + // { + // Asset assetA; // assetA < assetB + // Asset assetB; + // int32 fee; // Fee is in basis points, so the actual rate is (fee/100)% + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolConstantProductParameters", [["assetA", xdr.lookup("Asset")], ["assetB", xdr.lookup("Asset")], ["fee", xdr.lookup("Int32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } + // + // =========================================================================== + xdr.struct("LiquidityPoolEntryConstantProduct", [["params", xdr.lookup("LiquidityPoolConstantProductParameters")], ["reserveA", xdr.lookup("Int64")], ["reserveB", xdr.lookup("Int64")], ["totalPoolShares", xdr.lookup("Int64")], ["poolSharesTrustLineCount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } constantProduct; + // } + // + // =========================================================================== + xdr.union("LiquidityPoolEntryBody", { + switchOn: xdr.lookup("LiquidityPoolType"), + switchName: "type", + switches: [["liquidityPoolConstantProduct", "constantProduct"]], + arms: { + constantProduct: xdr.lookup("LiquidityPoolEntryConstantProduct") + } + }); + + // === xdr source ============================================================ + // + // struct LiquidityPoolEntry + // { + // PoolID liquidityPoolID; + // + // union switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // struct + // { + // LiquidityPoolConstantProductParameters params; + // + // int64 reserveA; // amount of A in the pool + // int64 reserveB; // amount of B in the pool + // int64 totalPoolShares; // total number of pool shares issued + // int64 poolSharesTrustLineCount; // number of trust lines for the + // // associated pool shares + // } constantProduct; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolEntry", [["liquidityPoolId", xdr.lookup("PoolId")], ["body", xdr.lookup("LiquidityPoolEntryBody")]]); + + // === xdr source ============================================================ + // + // enum ContractDataDurability { + // TEMPORARY = 0, + // PERSISTENT = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractDataDurability", { + temporary: 0, + persistent: 1 + }); + + // === xdr source ============================================================ + // + // struct ContractDataEntry { + // ExtensionPoint ext; + // + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // SCVal val; + // }; + // + // =========================================================================== + xdr.struct("ContractDataEntry", [["ext", xdr.lookup("ExtensionPoint")], ["contract", xdr.lookup("ScAddress")], ["key", xdr.lookup("ScVal")], ["durability", xdr.lookup("ContractDataDurability")], ["val", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // struct ContractCodeCostInputs { + // ExtensionPoint ext; + // uint32 nInstructions; + // uint32 nFunctions; + // uint32 nGlobals; + // uint32 nTableEntries; + // uint32 nTypes; + // uint32 nDataSegments; + // uint32 nElemSegments; + // uint32 nImports; + // uint32 nExports; + // uint32 nDataSegmentBytes; + // }; + // + // =========================================================================== + xdr.struct("ContractCodeCostInputs", [["ext", xdr.lookup("ExtensionPoint")], ["nInstructions", xdr.lookup("Uint32")], ["nFunctions", xdr.lookup("Uint32")], ["nGlobals", xdr.lookup("Uint32")], ["nTableEntries", xdr.lookup("Uint32")], ["nTypes", xdr.lookup("Uint32")], ["nDataSegments", xdr.lookup("Uint32")], ["nElemSegments", xdr.lookup("Uint32")], ["nImports", xdr.lookup("Uint32")], ["nExports", xdr.lookup("Uint32")], ["nDataSegmentBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } + // + // =========================================================================== + xdr.struct("ContractCodeEntryV1", [["ext", xdr.lookup("ExtensionPoint")], ["costInputs", xdr.lookup("ContractCodeCostInputs")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } v1; + // } + // + // =========================================================================== + xdr.union("ContractCodeEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("ContractCodeEntryV1") + } + }); + + // === xdr source ============================================================ + // + // struct ContractCodeEntry { + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // struct + // { + // ExtensionPoint ext; + // ContractCodeCostInputs costInputs; + // } v1; + // } ext; + // + // Hash hash; + // opaque code<>; + // }; + // + // =========================================================================== + xdr.struct("ContractCodeEntry", [["ext", xdr.lookup("ContractCodeEntryExt")], ["hash", xdr.lookup("Hash")], ["code", xdr.varOpaque()]]); + + // === xdr source ============================================================ + // + // struct TTLEntry { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // uint32 liveUntilLedgerSeq; + // }; + // + // =========================================================================== + xdr.struct("TtlEntry", [["keyHash", xdr.lookup("Hash")], ["liveUntilLedgerSeq", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerEntryExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerEntryExtensionV1 + // { + // SponsorshipDescriptor sponsoringID; + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerEntryExtensionV1", [["sponsoringId", xdr.lookup("SponsorshipDescriptor")], ["ext", xdr.lookup("LedgerEntryExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (LedgerEntryType type) + // { + // case ACCOUNT: + // AccountEntry account; + // case TRUSTLINE: + // TrustLineEntry trustLine; + // case OFFER: + // OfferEntry offer; + // case DATA: + // DataEntry data; + // case CLAIMABLE_BALANCE: + // ClaimableBalanceEntry claimableBalance; + // case LIQUIDITY_POOL: + // LiquidityPoolEntry liquidityPool; + // case CONTRACT_DATA: + // ContractDataEntry contractData; + // case CONTRACT_CODE: + // ContractCodeEntry contractCode; + // case CONFIG_SETTING: + // ConfigSettingEntry configSetting; + // case TTL: + // TTLEntry ttl; + // } + // + // =========================================================================== + xdr.union("LedgerEntryData", { + switchOn: xdr.lookup("LedgerEntryType"), + switchName: "type", + switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"], ["contractData", "contractData"], ["contractCode", "contractCode"], ["configSetting", "configSetting"], ["ttl", "ttl"]], + arms: { + account: xdr.lookup("AccountEntry"), + trustLine: xdr.lookup("TrustLineEntry"), + offer: xdr.lookup("OfferEntry"), + data: xdr.lookup("DataEntry"), + claimableBalance: xdr.lookup("ClaimableBalanceEntry"), + liquidityPool: xdr.lookup("LiquidityPoolEntry"), + contractData: xdr.lookup("ContractDataEntry"), + contractCode: xdr.lookup("ContractCodeEntry"), + configSetting: xdr.lookup("ConfigSettingEntry"), + ttl: xdr.lookup("TtlEntry") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerEntryExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("LedgerEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerEntryExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerEntry + // { + // uint32 lastModifiedLedgerSeq; // ledger the LedgerEntry was last changed + // + // union switch (LedgerEntryType type) + // { + // case ACCOUNT: + // AccountEntry account; + // case TRUSTLINE: + // TrustLineEntry trustLine; + // case OFFER: + // OfferEntry offer; + // case DATA: + // DataEntry data; + // case CLAIMABLE_BALANCE: + // ClaimableBalanceEntry claimableBalance; + // case LIQUIDITY_POOL: + // LiquidityPoolEntry liquidityPool; + // case CONTRACT_DATA: + // ContractDataEntry contractData; + // case CONTRACT_CODE: + // ContractCodeEntry contractCode; + // case CONFIG_SETTING: + // ConfigSettingEntry configSetting; + // case TTL: + // TTLEntry ttl; + // } + // data; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerEntryExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerEntry", [["lastModifiedLedgerSeq", xdr.lookup("Uint32")], ["data", xdr.lookup("LedgerEntryData")], ["ext", xdr.lookup("LedgerEntryExt")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyAccount", [["accountId", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // TrustLineAsset asset; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyTrustLine", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sellerID; + // int64 offerID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyOffer", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // string64 dataName; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyData", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimableBalanceID balanceID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyClaimableBalance", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // PoolID liquidityPoolID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyLiquidityPool", [["liquidityPoolId", xdr.lookup("PoolId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyContractData", [["contract", xdr.lookup("ScAddress")], ["key", xdr.lookup("ScVal")], ["durability", xdr.lookup("ContractDataDurability")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash hash; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyContractCode", [["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ConfigSettingID configSettingID; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyConfigSetting", [["configSettingId", xdr.lookup("ConfigSettingId")]]); + + // === xdr source ============================================================ + // + // struct + // { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // } + // + // =========================================================================== + xdr.struct("LedgerKeyTtl", [["keyHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union LedgerKey switch (LedgerEntryType type) + // { + // case ACCOUNT: + // struct + // { + // AccountID accountID; + // } account; + // + // case TRUSTLINE: + // struct + // { + // AccountID accountID; + // TrustLineAsset asset; + // } trustLine; + // + // case OFFER: + // struct + // { + // AccountID sellerID; + // int64 offerID; + // } offer; + // + // case DATA: + // struct + // { + // AccountID accountID; + // string64 dataName; + // } data; + // + // case CLAIMABLE_BALANCE: + // struct + // { + // ClaimableBalanceID balanceID; + // } claimableBalance; + // + // case LIQUIDITY_POOL: + // struct + // { + // PoolID liquidityPoolID; + // } liquidityPool; + // case CONTRACT_DATA: + // struct + // { + // SCAddress contract; + // SCVal key; + // ContractDataDurability durability; + // } contractData; + // case CONTRACT_CODE: + // struct + // { + // Hash hash; + // } contractCode; + // case CONFIG_SETTING: + // struct + // { + // ConfigSettingID configSettingID; + // } configSetting; + // case TTL: + // struct + // { + // // Hash of the LedgerKey that is associated with this TTLEntry + // Hash keyHash; + // } ttl; + // }; + // + // =========================================================================== + xdr.union("LedgerKey", { + switchOn: xdr.lookup("LedgerEntryType"), + switchName: "type", + switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"], ["contractData", "contractData"], ["contractCode", "contractCode"], ["configSetting", "configSetting"], ["ttl", "ttl"]], + arms: { + account: xdr.lookup("LedgerKeyAccount"), + trustLine: xdr.lookup("LedgerKeyTrustLine"), + offer: xdr.lookup("LedgerKeyOffer"), + data: xdr.lookup("LedgerKeyData"), + claimableBalance: xdr.lookup("LedgerKeyClaimableBalance"), + liquidityPool: xdr.lookup("LedgerKeyLiquidityPool"), + contractData: xdr.lookup("LedgerKeyContractData"), + contractCode: xdr.lookup("LedgerKeyContractCode"), + configSetting: xdr.lookup("LedgerKeyConfigSetting"), + ttl: xdr.lookup("LedgerKeyTtl") + } + }); + + // === xdr source ============================================================ + // + // enum EnvelopeType + // { + // ENVELOPE_TYPE_TX_V0 = 0, + // ENVELOPE_TYPE_SCP = 1, + // ENVELOPE_TYPE_TX = 2, + // ENVELOPE_TYPE_AUTH = 3, + // ENVELOPE_TYPE_SCPVALUE = 4, + // ENVELOPE_TYPE_TX_FEE_BUMP = 5, + // ENVELOPE_TYPE_OP_ID = 6, + // ENVELOPE_TYPE_POOL_REVOKE_OP_ID = 7, + // ENVELOPE_TYPE_CONTRACT_ID = 8, + // ENVELOPE_TYPE_SOROBAN_AUTHORIZATION = 9 + // }; + // + // =========================================================================== + xdr["enum"]("EnvelopeType", { + envelopeTypeTxV0: 0, + envelopeTypeScp: 1, + envelopeTypeTx: 2, + envelopeTypeAuth: 3, + envelopeTypeScpvalue: 4, + envelopeTypeTxFeeBump: 5, + envelopeTypeOpId: 6, + envelopeTypePoolRevokeOpId: 7, + envelopeTypeContractId: 8, + envelopeTypeSorobanAuthorization: 9 + }); + + // === xdr source ============================================================ + // + // enum BucketListType + // { + // LIVE = 0, + // HOT_ARCHIVE = 1, + // COLD_ARCHIVE = 2 + // }; + // + // =========================================================================== + xdr["enum"]("BucketListType", { + live: 0, + hotArchive: 1, + coldArchive: 2 + }); + + // === xdr source ============================================================ + // + // enum BucketEntryType + // { + // METAENTRY = + // -1, // At-and-after protocol 11: bucket metadata, should come first. + // LIVEENTRY = 0, // Before protocol 11: created-or-updated; + // // At-and-after protocol 11: only updated. + // DEADENTRY = 1, + // INITENTRY = 2 // At-and-after protocol 11: only created. + // }; + // + // =========================================================================== + xdr["enum"]("BucketEntryType", { + metaentry: -1, + liveentry: 0, + deadentry: 1, + initentry: 2 + }); + + // === xdr source ============================================================ + // + // enum HotArchiveBucketEntryType + // { + // HOT_ARCHIVE_METAENTRY = -1, // Bucket metadata, should come first. + // HOT_ARCHIVE_ARCHIVED = 0, // Entry is Archived + // HOT_ARCHIVE_LIVE = 1, // Entry was previously HOT_ARCHIVE_ARCHIVED, or HOT_ARCHIVE_DELETED, but + // // has been added back to the live BucketList. + // // Does not need to be persisted. + // HOT_ARCHIVE_DELETED = 2 // Entry deleted (Note: must be persisted in archive) + // }; + // + // =========================================================================== + xdr["enum"]("HotArchiveBucketEntryType", { + hotArchiveMetaentry: -1, + hotArchiveArchived: 0, + hotArchiveLive: 1, + hotArchiveDeleted: 2 + }); + + // === xdr source ============================================================ + // + // enum ColdArchiveBucketEntryType + // { + // COLD_ARCHIVE_METAENTRY = -1, // Bucket metadata, should come first. + // COLD_ARCHIVE_ARCHIVED_LEAF = 0, // Full LedgerEntry that was archived during the epoch + // COLD_ARCHIVE_DELETED_LEAF = 1, // LedgerKey that was deleted during the epoch + // COLD_ARCHIVE_BOUNDARY_LEAF = 2, // Dummy leaf representing low/high bound + // COLD_ARCHIVE_HASH = 3 // Intermediary Merkle hash entry + // }; + // + // =========================================================================== + xdr["enum"]("ColdArchiveBucketEntryType", { + coldArchiveMetaentry: -1, + coldArchiveArchivedLeaf: 0, + coldArchiveDeletedLeaf: 1, + coldArchiveBoundaryLeaf: 2, + coldArchiveHash: 3 + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // BucketListType bucketListType; + // } + // + // =========================================================================== + xdr.union("BucketMetadataExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "bucketListType"]], + arms: { + bucketListType: xdr.lookup("BucketListType") + } + }); + + // === xdr source ============================================================ + // + // struct BucketMetadata + // { + // // Indicates the protocol version used to create / merge this bucket. + // uint32 ledgerVersion; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // BucketListType bucketListType; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("BucketMetadata", [["ledgerVersion", xdr.lookup("Uint32")], ["ext", xdr.lookup("BucketMetadataExt")]]); + + // === xdr source ============================================================ + // + // union BucketEntry switch (BucketEntryType type) + // { + // case LIVEENTRY: + // case INITENTRY: + // LedgerEntry liveEntry; + // + // case DEADENTRY: + // LedgerKey deadEntry; + // case METAENTRY: + // BucketMetadata metaEntry; + // }; + // + // =========================================================================== + xdr.union("BucketEntry", { + switchOn: xdr.lookup("BucketEntryType"), + switchName: "type", + switches: [["liveentry", "liveEntry"], ["initentry", "liveEntry"], ["deadentry", "deadEntry"], ["metaentry", "metaEntry"]], + arms: { + liveEntry: xdr.lookup("LedgerEntry"), + deadEntry: xdr.lookup("LedgerKey"), + metaEntry: xdr.lookup("BucketMetadata") + } + }); + + // === xdr source ============================================================ + // + // union HotArchiveBucketEntry switch (HotArchiveBucketEntryType type) + // { + // case HOT_ARCHIVE_ARCHIVED: + // LedgerEntry archivedEntry; + // + // case HOT_ARCHIVE_LIVE: + // case HOT_ARCHIVE_DELETED: + // LedgerKey key; + // case HOT_ARCHIVE_METAENTRY: + // BucketMetadata metaEntry; + // }; + // + // =========================================================================== + xdr.union("HotArchiveBucketEntry", { + switchOn: xdr.lookup("HotArchiveBucketEntryType"), + switchName: "type", + switches: [["hotArchiveArchived", "archivedEntry"], ["hotArchiveLive", "key"], ["hotArchiveDeleted", "key"], ["hotArchiveMetaentry", "metaEntry"]], + arms: { + archivedEntry: xdr.lookup("LedgerEntry"), + key: xdr.lookup("LedgerKey"), + metaEntry: xdr.lookup("BucketMetadata") + } + }); + + // === xdr source ============================================================ + // + // struct ColdArchiveArchivedLeaf + // { + // uint32 index; + // LedgerEntry archivedEntry; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveArchivedLeaf", [["index", xdr.lookup("Uint32")], ["archivedEntry", xdr.lookup("LedgerEntry")]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveDeletedLeaf + // { + // uint32 index; + // LedgerKey deletedKey; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveDeletedLeaf", [["index", xdr.lookup("Uint32")], ["deletedKey", xdr.lookup("LedgerKey")]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveBoundaryLeaf + // { + // uint32 index; + // bool isLowerBound; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveBoundaryLeaf", [["index", xdr.lookup("Uint32")], ["isLowerBound", xdr.bool()]]); + + // === xdr source ============================================================ + // + // struct ColdArchiveHashEntry + // { + // uint32 index; + // uint32 level; + // Hash hash; + // }; + // + // =========================================================================== + xdr.struct("ColdArchiveHashEntry", [["index", xdr.lookup("Uint32")], ["level", xdr.lookup("Uint32")], ["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union ColdArchiveBucketEntry switch (ColdArchiveBucketEntryType type) + // { + // case COLD_ARCHIVE_METAENTRY: + // BucketMetadata metaEntry; + // case COLD_ARCHIVE_ARCHIVED_LEAF: + // ColdArchiveArchivedLeaf archivedLeaf; + // case COLD_ARCHIVE_DELETED_LEAF: + // ColdArchiveDeletedLeaf deletedLeaf; + // case COLD_ARCHIVE_BOUNDARY_LEAF: + // ColdArchiveBoundaryLeaf boundaryLeaf; + // case COLD_ARCHIVE_HASH: + // ColdArchiveHashEntry hashEntry; + // }; + // + // =========================================================================== + xdr.union("ColdArchiveBucketEntry", { + switchOn: xdr.lookup("ColdArchiveBucketEntryType"), + switchName: "type", + switches: [["coldArchiveMetaentry", "metaEntry"], ["coldArchiveArchivedLeaf", "archivedLeaf"], ["coldArchiveDeletedLeaf", "deletedLeaf"], ["coldArchiveBoundaryLeaf", "boundaryLeaf"], ["coldArchiveHash", "hashEntry"]], + arms: { + metaEntry: xdr.lookup("BucketMetadata"), + archivedLeaf: xdr.lookup("ColdArchiveArchivedLeaf"), + deletedLeaf: xdr.lookup("ColdArchiveDeletedLeaf"), + boundaryLeaf: xdr.lookup("ColdArchiveBoundaryLeaf"), + hashEntry: xdr.lookup("ColdArchiveHashEntry") + } + }); + + // === xdr source ============================================================ + // + // typedef opaque UpgradeType<128>; + // + // =========================================================================== + xdr.typedef("UpgradeType", xdr.varOpaque(128)); + + // === xdr source ============================================================ + // + // enum StellarValueType + // { + // STELLAR_VALUE_BASIC = 0, + // STELLAR_VALUE_SIGNED = 1 + // }; + // + // =========================================================================== + xdr["enum"]("StellarValueType", { + stellarValueBasic: 0, + stellarValueSigned: 1 + }); + + // === xdr source ============================================================ + // + // struct LedgerCloseValueSignature + // { + // NodeID nodeID; // which node introduced the value + // Signature signature; // nodeID's signature + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseValueSignature", [["nodeId", xdr.lookup("NodeId")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // union switch (StellarValueType v) + // { + // case STELLAR_VALUE_BASIC: + // void; + // case STELLAR_VALUE_SIGNED: + // LedgerCloseValueSignature lcValueSignature; + // } + // + // =========================================================================== + xdr.union("StellarValueExt", { + switchOn: xdr.lookup("StellarValueType"), + switchName: "v", + switches: [["stellarValueBasic", xdr["void"]()], ["stellarValueSigned", "lcValueSignature"]], + arms: { + lcValueSignature: xdr.lookup("LedgerCloseValueSignature") + } + }); + + // === xdr source ============================================================ + // + // struct StellarValue + // { + // Hash txSetHash; // transaction set to apply to previous ledger + // TimePoint closeTime; // network close time + // + // // upgrades to apply to the previous ledger (usually empty) + // // this is a vector of encoded 'LedgerUpgrade' so that nodes can drop + // // unknown steps during consensus if needed. + // // see notes below on 'LedgerUpgrade' for more detail + // // max size is dictated by number of upgrade types (+ room for future) + // UpgradeType upgrades<6>; + // + // // reserved for future use + // union switch (StellarValueType v) + // { + // case STELLAR_VALUE_BASIC: + // void; + // case STELLAR_VALUE_SIGNED: + // LedgerCloseValueSignature lcValueSignature; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("StellarValue", [["txSetHash", xdr.lookup("Hash")], ["closeTime", xdr.lookup("TimePoint")], ["upgrades", xdr.varArray(xdr.lookup("UpgradeType"), 6)], ["ext", xdr.lookup("StellarValueExt")]]); + + // === xdr source ============================================================ + // + // const MASK_LEDGER_HEADER_FLAGS = 0x7; + // + // =========================================================================== + xdr["const"]("MASK_LEDGER_HEADER_FLAGS", 0x7); + + // === xdr source ============================================================ + // + // enum LedgerHeaderFlags + // { + // DISABLE_LIQUIDITY_POOL_TRADING_FLAG = 0x1, + // DISABLE_LIQUIDITY_POOL_DEPOSIT_FLAG = 0x2, + // DISABLE_LIQUIDITY_POOL_WITHDRAWAL_FLAG = 0x4 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerHeaderFlags", { + disableLiquidityPoolTradingFlag: 1, + disableLiquidityPoolDepositFlag: 2, + disableLiquidityPoolWithdrawalFlag: 4 + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderExtensionV1Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerHeaderExtensionV1 + // { + // uint32 flags; // LedgerHeaderFlags + // + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeaderExtensionV1", [["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("LedgerHeaderExtensionV1Ext")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerHeaderExtensionV1 v1; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerHeaderExtensionV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerHeader + // { + // uint32 ledgerVersion; // the protocol version of the ledger + // Hash previousLedgerHash; // hash of the previous ledger header + // StellarValue scpValue; // what consensus agreed to + // Hash txSetResultHash; // the TransactionResultSet that led to this ledger + // Hash bucketListHash; // hash of the ledger state + // + // uint32 ledgerSeq; // sequence number of this ledger + // + // int64 totalCoins; // total number of stroops in existence. + // // 10,000,000 stroops in 1 XLM + // + // int64 feePool; // fees burned since last inflation run + // uint32 inflationSeq; // inflation sequence number + // + // uint64 idPool; // last used global ID, used for generating objects + // + // uint32 baseFee; // base fee per operation in stroops + // uint32 baseReserve; // account base reserve in stroops + // + // uint32 maxTxSetSize; // maximum size a transaction set can be + // + // Hash skipList[4]; // hashes of ledgers in the past. allows you to jump back + // // in time without walking the chain back ledger by ledger + // // each slot contains the oldest ledger that is mod of + // // either 50 5000 50000 or 500000 depending on index + // // skipList[0] mod(50), skipList[1] mod(5000), etc + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerHeaderExtensionV1 v1; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeader", [["ledgerVersion", xdr.lookup("Uint32")], ["previousLedgerHash", xdr.lookup("Hash")], ["scpValue", xdr.lookup("StellarValue")], ["txSetResultHash", xdr.lookup("Hash")], ["bucketListHash", xdr.lookup("Hash")], ["ledgerSeq", xdr.lookup("Uint32")], ["totalCoins", xdr.lookup("Int64")], ["feePool", xdr.lookup("Int64")], ["inflationSeq", xdr.lookup("Uint32")], ["idPool", xdr.lookup("Uint64")], ["baseFee", xdr.lookup("Uint32")], ["baseReserve", xdr.lookup("Uint32")], ["maxTxSetSize", xdr.lookup("Uint32")], ["skipList", xdr.array(xdr.lookup("Hash"), 4)], ["ext", xdr.lookup("LedgerHeaderExt")]]); + + // === xdr source ============================================================ + // + // enum LedgerUpgradeType + // { + // LEDGER_UPGRADE_VERSION = 1, + // LEDGER_UPGRADE_BASE_FEE = 2, + // LEDGER_UPGRADE_MAX_TX_SET_SIZE = 3, + // LEDGER_UPGRADE_BASE_RESERVE = 4, + // LEDGER_UPGRADE_FLAGS = 5, + // LEDGER_UPGRADE_CONFIG = 6, + // LEDGER_UPGRADE_MAX_SOROBAN_TX_SET_SIZE = 7 + // }; + // + // =========================================================================== + xdr["enum"]("LedgerUpgradeType", { + ledgerUpgradeVersion: 1, + ledgerUpgradeBaseFee: 2, + ledgerUpgradeMaxTxSetSize: 3, + ledgerUpgradeBaseReserve: 4, + ledgerUpgradeFlags: 5, + ledgerUpgradeConfig: 6, + ledgerUpgradeMaxSorobanTxSetSize: 7 + }); + + // === xdr source ============================================================ + // + // struct ConfigUpgradeSetKey { + // Hash contractID; + // Hash contentHash; + // }; + // + // =========================================================================== + xdr.struct("ConfigUpgradeSetKey", [["contractId", xdr.lookup("Hash")], ["contentHash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // union LedgerUpgrade switch (LedgerUpgradeType type) + // { + // case LEDGER_UPGRADE_VERSION: + // uint32 newLedgerVersion; // update ledgerVersion + // case LEDGER_UPGRADE_BASE_FEE: + // uint32 newBaseFee; // update baseFee + // case LEDGER_UPGRADE_MAX_TX_SET_SIZE: + // uint32 newMaxTxSetSize; // update maxTxSetSize + // case LEDGER_UPGRADE_BASE_RESERVE: + // uint32 newBaseReserve; // update baseReserve + // case LEDGER_UPGRADE_FLAGS: + // uint32 newFlags; // update flags + // case LEDGER_UPGRADE_CONFIG: + // // Update arbitrary `ConfigSetting` entries identified by the key. + // ConfigUpgradeSetKey newConfig; + // case LEDGER_UPGRADE_MAX_SOROBAN_TX_SET_SIZE: + // // Update ConfigSettingContractExecutionLanesV0.ledgerMaxTxCount without + // // using `LEDGER_UPGRADE_CONFIG`. + // uint32 newMaxSorobanTxSetSize; + // }; + // + // =========================================================================== + xdr.union("LedgerUpgrade", { + switchOn: xdr.lookup("LedgerUpgradeType"), + switchName: "type", + switches: [["ledgerUpgradeVersion", "newLedgerVersion"], ["ledgerUpgradeBaseFee", "newBaseFee"], ["ledgerUpgradeMaxTxSetSize", "newMaxTxSetSize"], ["ledgerUpgradeBaseReserve", "newBaseReserve"], ["ledgerUpgradeFlags", "newFlags"], ["ledgerUpgradeConfig", "newConfig"], ["ledgerUpgradeMaxSorobanTxSetSize", "newMaxSorobanTxSetSize"]], + arms: { + newLedgerVersion: xdr.lookup("Uint32"), + newBaseFee: xdr.lookup("Uint32"), + newMaxTxSetSize: xdr.lookup("Uint32"), + newBaseReserve: xdr.lookup("Uint32"), + newFlags: xdr.lookup("Uint32"), + newConfig: xdr.lookup("ConfigUpgradeSetKey"), + newMaxSorobanTxSetSize: xdr.lookup("Uint32") + } + }); + + // === xdr source ============================================================ + // + // struct ConfigUpgradeSet { + // ConfigSettingEntry updatedEntry<>; + // }; + // + // =========================================================================== + xdr.struct("ConfigUpgradeSet", [["updatedEntry", xdr.varArray(xdr.lookup("ConfigSettingEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // enum TxSetComponentType + // { + // // txs with effective fee <= bid derived from a base fee (if any). + // // If base fee is not specified, no discount is applied. + // TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE = 0 + // }; + // + // =========================================================================== + xdr["enum"]("TxSetComponentType", { + txsetCompTxsMaybeDiscountedFee: 0 + }); + + // === xdr source ============================================================ + // + // struct + // { + // int64* baseFee; + // TransactionEnvelope txs<>; + // } + // + // =========================================================================== + xdr.struct("TxSetComponentTxsMaybeDiscountedFee", [["baseFee", xdr.option(xdr.lookup("Int64"))], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union TxSetComponent switch (TxSetComponentType type) + // { + // case TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE: + // struct + // { + // int64* baseFee; + // TransactionEnvelope txs<>; + // } txsMaybeDiscountedFee; + // }; + // + // =========================================================================== + xdr.union("TxSetComponent", { + switchOn: xdr.lookup("TxSetComponentType"), + switchName: "type", + switches: [["txsetCompTxsMaybeDiscountedFee", "txsMaybeDiscountedFee"]], + arms: { + txsMaybeDiscountedFee: xdr.lookup("TxSetComponentTxsMaybeDiscountedFee") + } + }); + + // === xdr source ============================================================ + // + // union TransactionPhase switch (int v) + // { + // case 0: + // TxSetComponent v0Components<>; + // }; + // + // =========================================================================== + xdr.union("TransactionPhase", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0Components"]], + arms: { + v0Components: xdr.varArray(xdr.lookup("TxSetComponent"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // struct TransactionSet + // { + // Hash previousLedgerHash; + // TransactionEnvelope txs<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionSet", [["previousLedgerHash", xdr.lookup("Hash")], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionSetV1 + // { + // Hash previousLedgerHash; + // TransactionPhase phases<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionSetV1", [["previousLedgerHash", xdr.lookup("Hash")], ["phases", xdr.varArray(xdr.lookup("TransactionPhase"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union GeneralizedTransactionSet switch (int v) + // { + // // We consider the legacy TransactionSet to be v0. + // case 1: + // TransactionSetV1 v1TxSet; + // }; + // + // =========================================================================== + xdr.union("GeneralizedTransactionSet", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[1, "v1TxSet"]], + arms: { + v1TxSet: xdr.lookup("TransactionSetV1") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionResultPair + // { + // Hash transactionHash; + // TransactionResult result; // result for the transaction + // }; + // + // =========================================================================== + xdr.struct("TransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("TransactionResult")]]); + + // === xdr source ============================================================ + // + // struct TransactionResultSet + // { + // TransactionResultPair results<>; + // }; + // + // =========================================================================== + xdr.struct("TransactionResultSet", [["results", xdr.varArray(xdr.lookup("TransactionResultPair"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // GeneralizedTransactionSet generalizedTxSet; + // } + // + // =========================================================================== + xdr.union("TransactionHistoryEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "generalizedTxSet"]], + arms: { + generalizedTxSet: xdr.lookup("GeneralizedTransactionSet") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionHistoryEntry + // { + // uint32 ledgerSeq; + // TransactionSet txSet; + // + // // when v != 0, txSet must be empty + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // GeneralizedTransactionSet generalizedTxSet; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionHistoryEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txSet", xdr.lookup("TransactionSet")], ["ext", xdr.lookup("TransactionHistoryEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionHistoryResultEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionHistoryResultEntry + // { + // uint32 ledgerSeq; + // TransactionResultSet txResultSet; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionHistoryResultEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txResultSet", xdr.lookup("TransactionResultSet")], ["ext", xdr.lookup("TransactionHistoryResultEntryExt")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("LedgerHeaderHistoryEntryExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct LedgerHeaderHistoryEntry + // { + // Hash hash; + // LedgerHeader header; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("LedgerHeaderHistoryEntry", [["hash", xdr.lookup("Hash")], ["header", xdr.lookup("LedgerHeader")], ["ext", xdr.lookup("LedgerHeaderHistoryEntryExt")]]); + + // === xdr source ============================================================ + // + // struct LedgerSCPMessages + // { + // uint32 ledgerSeq; + // SCPEnvelope messages<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerScpMessages", [["ledgerSeq", xdr.lookup("Uint32")], ["messages", xdr.varArray(xdr.lookup("ScpEnvelope"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct SCPHistoryEntryV0 + // { + // SCPQuorumSet quorumSets<>; // additional quorum sets used by ledgerMessages + // LedgerSCPMessages ledgerMessages; + // }; + // + // =========================================================================== + xdr.struct("ScpHistoryEntryV0", [["quorumSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)], ["ledgerMessages", xdr.lookup("LedgerScpMessages")]]); + + // === xdr source ============================================================ + // + // union SCPHistoryEntry switch (int v) + // { + // case 0: + // SCPHistoryEntryV0 v0; + // }; + // + // =========================================================================== + xdr.union("ScpHistoryEntry", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("ScpHistoryEntryV0") + } + }); + + // === xdr source ============================================================ + // + // enum LedgerEntryChangeType + // { + // LEDGER_ENTRY_CREATED = 0, // entry was added to the ledger + // LEDGER_ENTRY_UPDATED = 1, // entry was modified in the ledger + // LEDGER_ENTRY_REMOVED = 2, // entry was removed from the ledger + // LEDGER_ENTRY_STATE = 3 // value of the entry + // }; + // + // =========================================================================== + xdr["enum"]("LedgerEntryChangeType", { + ledgerEntryCreated: 0, + ledgerEntryUpdated: 1, + ledgerEntryRemoved: 2, + ledgerEntryState: 3 + }); + + // === xdr source ============================================================ + // + // union LedgerEntryChange switch (LedgerEntryChangeType type) + // { + // case LEDGER_ENTRY_CREATED: + // LedgerEntry created; + // case LEDGER_ENTRY_UPDATED: + // LedgerEntry updated; + // case LEDGER_ENTRY_REMOVED: + // LedgerKey removed; + // case LEDGER_ENTRY_STATE: + // LedgerEntry state; + // }; + // + // =========================================================================== + xdr.union("LedgerEntryChange", { + switchOn: xdr.lookup("LedgerEntryChangeType"), + switchName: "type", + switches: [["ledgerEntryCreated", "created"], ["ledgerEntryUpdated", "updated"], ["ledgerEntryRemoved", "removed"], ["ledgerEntryState", "state"]], + arms: { + created: xdr.lookup("LedgerEntry"), + updated: xdr.lookup("LedgerEntry"), + removed: xdr.lookup("LedgerKey"), + state: xdr.lookup("LedgerEntry") + } + }); + + // === xdr source ============================================================ + // + // typedef LedgerEntryChange LedgerEntryChanges<>; + // + // =========================================================================== + xdr.typedef("LedgerEntryChanges", xdr.varArray(xdr.lookup("LedgerEntryChange"), 2147483647)); + + // === xdr source ============================================================ + // + // struct OperationMeta + // { + // LedgerEntryChanges changes; + // }; + // + // =========================================================================== + xdr.struct("OperationMeta", [["changes", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV1 + // { + // LedgerEntryChanges txChanges; // tx level changes if any + // OperationMeta operations<>; // meta for each operation + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV1", [["txChanges", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV2 + // { + // LedgerEntryChanges txChangesBefore; // tx level changes before operations + // // are applied if any + // OperationMeta operations<>; // meta for each operation + // LedgerEntryChanges txChangesAfter; // tx level changes after operations are + // // applied if any + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV2", [["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // enum ContractEventType + // { + // SYSTEM = 0, + // CONTRACT = 1, + // DIAGNOSTIC = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ContractEventType", { + system: 0, + contract: 1, + diagnostic: 2 + }); + + // === xdr source ============================================================ + // + // struct + // { + // SCVal topics<>; + // SCVal data; + // } + // + // =========================================================================== + xdr.struct("ContractEventV0", [["topics", xdr.varArray(xdr.lookup("ScVal"), 2147483647)], ["data", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // struct + // { + // SCVal topics<>; + // SCVal data; + // } v0; + // } + // + // =========================================================================== + xdr.union("ContractEventBody", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("ContractEventV0") + } + }); + + // === xdr source ============================================================ + // + // struct ContractEvent + // { + // // We can use this to add more fields, or because it + // // is first, to change ContractEvent into a union. + // ExtensionPoint ext; + // + // Hash* contractID; + // ContractEventType type; + // + // union switch (int v) + // { + // case 0: + // struct + // { + // SCVal topics<>; + // SCVal data; + // } v0; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("ContractEvent", [["ext", xdr.lookup("ExtensionPoint")], ["contractId", xdr.option(xdr.lookup("Hash"))], ["type", xdr.lookup("ContractEventType")], ["body", xdr.lookup("ContractEventBody")]]); + + // === xdr source ============================================================ + // + // struct DiagnosticEvent + // { + // bool inSuccessfulContractCall; + // ContractEvent event; + // }; + // + // =========================================================================== + xdr.struct("DiagnosticEvent", [["inSuccessfulContractCall", xdr.bool()], ["event", xdr.lookup("ContractEvent")]]); + + // === xdr source ============================================================ + // + // typedef DiagnosticEvent DiagnosticEvents<>; + // + // =========================================================================== + xdr.typedef("DiagnosticEvents", xdr.varArray(xdr.lookup("DiagnosticEvent"), 2147483647)); + + // === xdr source ============================================================ + // + // struct SorobanTransactionMetaExtV1 + // { + // ExtensionPoint ext; + // + // // The following are the components of the overall Soroban resource fee + // // charged for the transaction. + // // The following relation holds: + // // `resourceFeeCharged = totalNonRefundableResourceFeeCharged + totalRefundableResourceFeeCharged` + // // where `resourceFeeCharged` is the overall fee charged for the + // // transaction. Also, `resourceFeeCharged` <= `sorobanData.resourceFee` + // // i.e.we never charge more than the declared resource fee. + // // The inclusion fee for charged the Soroban transaction can be found using + // // the following equation: + // // `result.feeCharged = resourceFeeCharged + inclusionFeeCharged`. + // + // // Total amount (in stroops) that has been charged for non-refundable + // // Soroban resources. + // // Non-refundable resources are charged based on the usage declared in + // // the transaction envelope (such as `instructions`, `readBytes` etc.) and + // // is charged regardless of the success of the transaction. + // int64 totalNonRefundableResourceFeeCharged; + // // Total amount (in stroops) that has been charged for refundable + // // Soroban resource fees. + // // Currently this comprises the rent fee (`rentFeeCharged`) and the + // // fee for the events and return value. + // // Refundable resources are charged based on the actual resources usage. + // // Since currently refundable resources are only used for the successful + // // transactions, this will be `0` for failed transactions. + // int64 totalRefundableResourceFeeCharged; + // // Amount (in stroops) that has been charged for rent. + // // This is a part of `totalNonRefundableResourceFeeCharged`. + // int64 rentFeeCharged; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionMetaExtV1", [["ext", xdr.lookup("ExtensionPoint")], ["totalNonRefundableResourceFeeCharged", xdr.lookup("Int64")], ["totalRefundableResourceFeeCharged", xdr.lookup("Int64")], ["rentFeeCharged", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union SorobanTransactionMetaExt switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionMetaExtV1 v1; + // }; + // + // =========================================================================== + xdr.union("SorobanTransactionMetaExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("SorobanTransactionMetaExtV1") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanTransactionMeta + // { + // SorobanTransactionMetaExt ext; + // + // ContractEvent events<>; // custom events populated by the + // // contracts themselves. + // SCVal returnValue; // return value of the host fn invocation + // + // // Diagnostics events that are not hashed. + // // This will contain all contract and diagnostic events. Even ones + // // that were emitted in a failed contract call. + // DiagnosticEvent diagnosticEvents<>; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionMeta", [["ext", xdr.lookup("SorobanTransactionMetaExt")], ["events", xdr.varArray(xdr.lookup("ContractEvent"), 2147483647)], ["returnValue", xdr.lookup("ScVal")], ["diagnosticEvents", xdr.varArray(xdr.lookup("DiagnosticEvent"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct TransactionMetaV3 + // { + // ExtensionPoint ext; + // + // LedgerEntryChanges txChangesBefore; // tx level changes before operations + // // are applied if any + // OperationMeta operations<>; // meta for each operation + // LedgerEntryChanges txChangesAfter; // tx level changes after operations are + // // applied if any + // SorobanTransactionMeta* sorobanMeta; // Soroban-specific meta (only for + // // Soroban transactions). + // }; + // + // =========================================================================== + xdr.struct("TransactionMetaV3", [["ext", xdr.lookup("ExtensionPoint")], ["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")], ["sorobanMeta", xdr.option(xdr.lookup("SorobanTransactionMeta"))]]); + + // === xdr source ============================================================ + // + // struct InvokeHostFunctionSuccessPreImage + // { + // SCVal returnValue; + // ContractEvent events<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeHostFunctionSuccessPreImage", [["returnValue", xdr.lookup("ScVal")], ["events", xdr.varArray(xdr.lookup("ContractEvent"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union TransactionMeta switch (int v) + // { + // case 0: + // OperationMeta operations<>; + // case 1: + // TransactionMetaV1 v1; + // case 2: + // TransactionMetaV2 v2; + // case 3: + // TransactionMetaV3 v3; + // }; + // + // =========================================================================== + xdr.union("TransactionMeta", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "operations"], [1, "v1"], [2, "v2"], [3, "v3"]], + arms: { + operations: xdr.varArray(xdr.lookup("OperationMeta"), 2147483647), + v1: xdr.lookup("TransactionMetaV1"), + v2: xdr.lookup("TransactionMetaV2"), + v3: xdr.lookup("TransactionMetaV3") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionResultMeta + // { + // TransactionResultPair result; + // LedgerEntryChanges feeProcessing; + // TransactionMeta txApplyProcessing; + // }; + // + // =========================================================================== + xdr.struct("TransactionResultMeta", [["result", xdr.lookup("TransactionResultPair")], ["feeProcessing", xdr.lookup("LedgerEntryChanges")], ["txApplyProcessing", xdr.lookup("TransactionMeta")]]); + + // === xdr source ============================================================ + // + // struct UpgradeEntryMeta + // { + // LedgerUpgrade upgrade; + // LedgerEntryChanges changes; + // }; + // + // =========================================================================== + xdr.struct("UpgradeEntryMeta", [["upgrade", xdr.lookup("LedgerUpgrade")], ["changes", xdr.lookup("LedgerEntryChanges")]]); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaV0 + // { + // LedgerHeaderHistoryEntry ledgerHeader; + // // NB: txSet is sorted in "Hash order" + // TransactionSet txSet; + // + // // NB: transactions are sorted in apply order here + // // fees for all transactions are processed first + // // followed by applying transactions + // TransactionResultMeta txProcessing<>; + // + // // upgrades are applied last + // UpgradeEntryMeta upgradesProcessing<>; + // + // // other misc information attached to the ledger close + // SCPHistoryEntry scpInfo<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaV0", [["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("TransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaExtV1 + // { + // ExtensionPoint ext; + // int64 sorobanFeeWrite1KB; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaExtV1", [["ext", xdr.lookup("ExtensionPoint")], ["sorobanFeeWrite1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union LedgerCloseMetaExt switch (int v) + // { + // case 0: + // void; + // case 1: + // LedgerCloseMetaExtV1 v1; + // }; + // + // =========================================================================== + xdr.union("LedgerCloseMetaExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "v1"]], + arms: { + v1: xdr.lookup("LedgerCloseMetaExtV1") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerCloseMetaV1 + // { + // LedgerCloseMetaExt ext; + // + // LedgerHeaderHistoryEntry ledgerHeader; + // + // GeneralizedTransactionSet txSet; + // + // // NB: transactions are sorted in apply order here + // // fees for all transactions are processed first + // // followed by applying transactions + // TransactionResultMeta txProcessing<>; + // + // // upgrades are applied last + // UpgradeEntryMeta upgradesProcessing<>; + // + // // other misc information attached to the ledger close + // SCPHistoryEntry scpInfo<>; + // + // // Size in bytes of BucketList, to support downstream + // // systems calculating storage fees correctly. + // uint64 totalByteSizeOfBucketList; + // + // // Temp keys that are being evicted at this ledger. + // LedgerKey evictedTemporaryLedgerKeys<>; + // + // // Archived restorable ledger entries that are being + // // evicted at this ledger. + // LedgerEntry evictedPersistentLedgerEntries<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerCloseMetaV1", [["ext", xdr.lookup("LedgerCloseMetaExt")], ["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("GeneralizedTransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)], ["totalByteSizeOfBucketList", xdr.lookup("Uint64")], ["evictedTemporaryLedgerKeys", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["evictedPersistentLedgerEntries", xdr.varArray(xdr.lookup("LedgerEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union LedgerCloseMeta switch (int v) + // { + // case 0: + // LedgerCloseMetaV0 v0; + // case 1: + // LedgerCloseMetaV1 v1; + // }; + // + // =========================================================================== + xdr.union("LedgerCloseMeta", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, "v0"], [1, "v1"]], + arms: { + v0: xdr.lookup("LedgerCloseMetaV0"), + v1: xdr.lookup("LedgerCloseMetaV1") + } + }); + + // === xdr source ============================================================ + // + // enum ErrorCode + // { + // ERR_MISC = 0, // Unspecific error + // ERR_DATA = 1, // Malformed data + // ERR_CONF = 2, // Misconfiguration error + // ERR_AUTH = 3, // Authentication failure + // ERR_LOAD = 4 // System overloaded + // }; + // + // =========================================================================== + xdr["enum"]("ErrorCode", { + errMisc: 0, + errData: 1, + errConf: 2, + errAuth: 3, + errLoad: 4 + }); + + // === xdr source ============================================================ + // + // struct Error + // { + // ErrorCode code; + // string msg<100>; + // }; + // + // =========================================================================== + xdr.struct("Error", [["code", xdr.lookup("ErrorCode")], ["msg", xdr.string(100)]]); + + // === xdr source ============================================================ + // + // struct SendMore + // { + // uint32 numMessages; + // }; + // + // =========================================================================== + xdr.struct("SendMore", [["numMessages", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SendMoreExtended + // { + // uint32 numMessages; + // uint32 numBytes; + // }; + // + // =========================================================================== + xdr.struct("SendMoreExtended", [["numMessages", xdr.lookup("Uint32")], ["numBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct AuthCert + // { + // Curve25519Public pubkey; + // uint64 expiration; + // Signature sig; + // }; + // + // =========================================================================== + xdr.struct("AuthCert", [["pubkey", xdr.lookup("Curve25519Public")], ["expiration", xdr.lookup("Uint64")], ["sig", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // struct Hello + // { + // uint32 ledgerVersion; + // uint32 overlayVersion; + // uint32 overlayMinVersion; + // Hash networkID; + // string versionStr<100>; + // int listeningPort; + // NodeID peerID; + // AuthCert cert; + // uint256 nonce; + // }; + // + // =========================================================================== + xdr.struct("Hello", [["ledgerVersion", xdr.lookup("Uint32")], ["overlayVersion", xdr.lookup("Uint32")], ["overlayMinVersion", xdr.lookup("Uint32")], ["networkId", xdr.lookup("Hash")], ["versionStr", xdr.string(100)], ["listeningPort", xdr["int"]()], ["peerId", xdr.lookup("NodeId")], ["cert", xdr.lookup("AuthCert")], ["nonce", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // const AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED = 200; + // + // =========================================================================== + xdr["const"]("AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED", 200); + + // === xdr source ============================================================ + // + // struct Auth + // { + // int flags; + // }; + // + // =========================================================================== + xdr.struct("Auth", [["flags", xdr["int"]()]]); + + // === xdr source ============================================================ + // + // enum IPAddrType + // { + // IPv4 = 0, + // IPv6 = 1 + // }; + // + // =========================================================================== + xdr["enum"]("IpAddrType", { + iPv4: 0, + iPv6: 1 + }); + + // === xdr source ============================================================ + // + // union switch (IPAddrType type) + // { + // case IPv4: + // opaque ipv4[4]; + // case IPv6: + // opaque ipv6[16]; + // } + // + // =========================================================================== + xdr.union("PeerAddressIp", { + switchOn: xdr.lookup("IpAddrType"), + switchName: "type", + switches: [["iPv4", "ipv4"], ["iPv6", "ipv6"]], + arms: { + ipv4: xdr.opaque(4), + ipv6: xdr.opaque(16) + } + }); + + // === xdr source ============================================================ + // + // struct PeerAddress + // { + // union switch (IPAddrType type) + // { + // case IPv4: + // opaque ipv4[4]; + // case IPv6: + // opaque ipv6[16]; + // } + // ip; + // uint32 port; + // uint32 numFailures; + // }; + // + // =========================================================================== + xdr.struct("PeerAddress", [["ip", xdr.lookup("PeerAddressIp")], ["port", xdr.lookup("Uint32")], ["numFailures", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // enum MessageType + // { + // ERROR_MSG = 0, + // AUTH = 2, + // DONT_HAVE = 3, + // + // GET_PEERS = 4, // gets a list of peers this guy knows about + // PEERS = 5, + // + // GET_TX_SET = 6, // gets a particular txset by hash + // TX_SET = 7, + // GENERALIZED_TX_SET = 17, + // + // TRANSACTION = 8, // pass on a tx you have heard about + // + // // SCP + // GET_SCP_QUORUMSET = 9, + // SCP_QUORUMSET = 10, + // SCP_MESSAGE = 11, + // GET_SCP_STATE = 12, + // + // // new messages + // HELLO = 13, + // + // SURVEY_REQUEST = 14, + // SURVEY_RESPONSE = 15, + // + // SEND_MORE = 16, + // SEND_MORE_EXTENDED = 20, + // + // FLOOD_ADVERT = 18, + // FLOOD_DEMAND = 19, + // + // TIME_SLICED_SURVEY_REQUEST = 21, + // TIME_SLICED_SURVEY_RESPONSE = 22, + // TIME_SLICED_SURVEY_START_COLLECTING = 23, + // TIME_SLICED_SURVEY_STOP_COLLECTING = 24 + // }; + // + // =========================================================================== + xdr["enum"]("MessageType", { + errorMsg: 0, + auth: 2, + dontHave: 3, + getPeers: 4, + peers: 5, + getTxSet: 6, + txSet: 7, + generalizedTxSet: 17, + transaction: 8, + getScpQuorumset: 9, + scpQuorumset: 10, + scpMessage: 11, + getScpState: 12, + hello: 13, + surveyRequest: 14, + surveyResponse: 15, + sendMore: 16, + sendMoreExtended: 20, + floodAdvert: 18, + floodDemand: 19, + timeSlicedSurveyRequest: 21, + timeSlicedSurveyResponse: 22, + timeSlicedSurveyStartCollecting: 23, + timeSlicedSurveyStopCollecting: 24 + }); + + // === xdr source ============================================================ + // + // struct DontHave + // { + // MessageType type; + // uint256 reqHash; + // }; + // + // =========================================================================== + xdr.struct("DontHave", [["type", xdr.lookup("MessageType")], ["reqHash", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // enum SurveyMessageCommandType + // { + // SURVEY_TOPOLOGY = 0, + // TIME_SLICED_SURVEY_TOPOLOGY = 1 + // }; + // + // =========================================================================== + xdr["enum"]("SurveyMessageCommandType", { + surveyTopology: 0, + timeSlicedSurveyTopology: 1 + }); + + // === xdr source ============================================================ + // + // enum SurveyMessageResponseType + // { + // SURVEY_TOPOLOGY_RESPONSE_V0 = 0, + // SURVEY_TOPOLOGY_RESPONSE_V1 = 1, + // SURVEY_TOPOLOGY_RESPONSE_V2 = 2 + // }; + // + // =========================================================================== + xdr["enum"]("SurveyMessageResponseType", { + surveyTopologyResponseV0: 0, + surveyTopologyResponseV1: 1, + surveyTopologyResponseV2: 2 + }); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyStartCollectingMessage + // { + // NodeID surveyorID; + // uint32 nonce; + // uint32 ledgerNum; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyStartCollectingMessage", [["surveyorId", xdr.lookup("NodeId")], ["nonce", xdr.lookup("Uint32")], ["ledgerNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyStartCollectingMessage + // { + // Signature signature; + // TimeSlicedSurveyStartCollectingMessage startCollecting; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyStartCollectingMessage", [["signature", xdr.lookup("Signature")], ["startCollecting", xdr.lookup("TimeSlicedSurveyStartCollectingMessage")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyStopCollectingMessage + // { + // NodeID surveyorID; + // uint32 nonce; + // uint32 ledgerNum; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyStopCollectingMessage", [["surveyorId", xdr.lookup("NodeId")], ["nonce", xdr.lookup("Uint32")], ["ledgerNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyStopCollectingMessage + // { + // Signature signature; + // TimeSlicedSurveyStopCollectingMessage stopCollecting; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyStopCollectingMessage", [["signature", xdr.lookup("Signature")], ["stopCollecting", xdr.lookup("TimeSlicedSurveyStopCollectingMessage")]]); + + // === xdr source ============================================================ + // + // struct SurveyRequestMessage + // { + // NodeID surveyorPeerID; + // NodeID surveyedPeerID; + // uint32 ledgerNum; + // Curve25519Public encryptionKey; + // SurveyMessageCommandType commandType; + // }; + // + // =========================================================================== + xdr.struct("SurveyRequestMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["encryptionKey", xdr.lookup("Curve25519Public")], ["commandType", xdr.lookup("SurveyMessageCommandType")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyRequestMessage + // { + // SurveyRequestMessage request; + // uint32 nonce; + // uint32 inboundPeersIndex; + // uint32 outboundPeersIndex; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyRequestMessage", [["request", xdr.lookup("SurveyRequestMessage")], ["nonce", xdr.lookup("Uint32")], ["inboundPeersIndex", xdr.lookup("Uint32")], ["outboundPeersIndex", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedSurveyRequestMessage + // { + // Signature requestSignature; + // SurveyRequestMessage request; + // }; + // + // =========================================================================== + xdr.struct("SignedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("SurveyRequestMessage")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyRequestMessage + // { + // Signature requestSignature; + // TimeSlicedSurveyRequestMessage request; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("TimeSlicedSurveyRequestMessage")]]); + + // === xdr source ============================================================ + // + // typedef opaque EncryptedBody<64000>; + // + // =========================================================================== + xdr.typedef("EncryptedBody", xdr.varOpaque(64000)); + + // === xdr source ============================================================ + // + // struct SurveyResponseMessage + // { + // NodeID surveyorPeerID; + // NodeID surveyedPeerID; + // uint32 ledgerNum; + // SurveyMessageCommandType commandType; + // EncryptedBody encryptedBody; + // }; + // + // =========================================================================== + xdr.struct("SurveyResponseMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["commandType", xdr.lookup("SurveyMessageCommandType")], ["encryptedBody", xdr.lookup("EncryptedBody")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedSurveyResponseMessage + // { + // SurveyResponseMessage response; + // uint32 nonce; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedSurveyResponseMessage", [["response", xdr.lookup("SurveyResponseMessage")], ["nonce", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SignedSurveyResponseMessage + // { + // Signature responseSignature; + // SurveyResponseMessage response; + // }; + // + // =========================================================================== + xdr.struct("SignedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("SurveyResponseMessage")]]); + + // === xdr source ============================================================ + // + // struct SignedTimeSlicedSurveyResponseMessage + // { + // Signature responseSignature; + // TimeSlicedSurveyResponseMessage response; + // }; + // + // =========================================================================== + xdr.struct("SignedTimeSlicedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("TimeSlicedSurveyResponseMessage")]]); + + // === xdr source ============================================================ + // + // struct PeerStats + // { + // NodeID id; + // string versionStr<100>; + // uint64 messagesRead; + // uint64 messagesWritten; + // uint64 bytesRead; + // uint64 bytesWritten; + // uint64 secondsConnected; + // + // uint64 uniqueFloodBytesRecv; + // uint64 duplicateFloodBytesRecv; + // uint64 uniqueFetchBytesRecv; + // uint64 duplicateFetchBytesRecv; + // + // uint64 uniqueFloodMessageRecv; + // uint64 duplicateFloodMessageRecv; + // uint64 uniqueFetchMessageRecv; + // uint64 duplicateFetchMessageRecv; + // }; + // + // =========================================================================== + xdr.struct("PeerStats", [["id", xdr.lookup("NodeId")], ["versionStr", xdr.string(100)], ["messagesRead", xdr.lookup("Uint64")], ["messagesWritten", xdr.lookup("Uint64")], ["bytesRead", xdr.lookup("Uint64")], ["bytesWritten", xdr.lookup("Uint64")], ["secondsConnected", xdr.lookup("Uint64")], ["uniqueFloodBytesRecv", xdr.lookup("Uint64")], ["duplicateFloodBytesRecv", xdr.lookup("Uint64")], ["uniqueFetchBytesRecv", xdr.lookup("Uint64")], ["duplicateFetchBytesRecv", xdr.lookup("Uint64")], ["uniqueFloodMessageRecv", xdr.lookup("Uint64")], ["duplicateFloodMessageRecv", xdr.lookup("Uint64")], ["uniqueFetchMessageRecv", xdr.lookup("Uint64")], ["duplicateFetchMessageRecv", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // typedef PeerStats PeerStatList<25>; + // + // =========================================================================== + xdr.typedef("PeerStatList", xdr.varArray(xdr.lookup("PeerStats"), 25)); + + // === xdr source ============================================================ + // + // struct TimeSlicedNodeData + // { + // uint32 addedAuthenticatedPeers; + // uint32 droppedAuthenticatedPeers; + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // + // // SCP stats + // uint32 p75SCPFirstToSelfLatencyMs; + // uint32 p75SCPSelfToOtherLatencyMs; + // + // // How many times the node lost sync in the time slice + // uint32 lostSyncCount; + // + // // Config data + // bool isValidator; + // uint32 maxInboundPeerCount; + // uint32 maxOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedNodeData", [["addedAuthenticatedPeers", xdr.lookup("Uint32")], ["droppedAuthenticatedPeers", xdr.lookup("Uint32")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")], ["p75ScpFirstToSelfLatencyMs", xdr.lookup("Uint32")], ["p75ScpSelfToOtherLatencyMs", xdr.lookup("Uint32")], ["lostSyncCount", xdr.lookup("Uint32")], ["isValidator", xdr.bool()], ["maxInboundPeerCount", xdr.lookup("Uint32")], ["maxOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TimeSlicedPeerData + // { + // PeerStats peerStats; + // uint32 averageLatencyMs; + // }; + // + // =========================================================================== + xdr.struct("TimeSlicedPeerData", [["peerStats", xdr.lookup("PeerStats")], ["averageLatencyMs", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // typedef TimeSlicedPeerData TimeSlicedPeerDataList<25>; + // + // =========================================================================== + xdr.typedef("TimeSlicedPeerDataList", xdr.varArray(xdr.lookup("TimeSlicedPeerData"), 25)); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV0 + // { + // PeerStatList inboundPeers; + // PeerStatList outboundPeers; + // + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV0", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV1 + // { + // PeerStatList inboundPeers; + // PeerStatList outboundPeers; + // + // uint32 totalInboundPeerCount; + // uint32 totalOutboundPeerCount; + // + // uint32 maxInboundPeerCount; + // uint32 maxOutboundPeerCount; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV1", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")], ["maxInboundPeerCount", xdr.lookup("Uint32")], ["maxOutboundPeerCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct TopologyResponseBodyV2 + // { + // TimeSlicedPeerDataList inboundPeers; + // TimeSlicedPeerDataList outboundPeers; + // TimeSlicedNodeData nodeData; + // }; + // + // =========================================================================== + xdr.struct("TopologyResponseBodyV2", [["inboundPeers", xdr.lookup("TimeSlicedPeerDataList")], ["outboundPeers", xdr.lookup("TimeSlicedPeerDataList")], ["nodeData", xdr.lookup("TimeSlicedNodeData")]]); + + // === xdr source ============================================================ + // + // union SurveyResponseBody switch (SurveyMessageResponseType type) + // { + // case SURVEY_TOPOLOGY_RESPONSE_V0: + // TopologyResponseBodyV0 topologyResponseBodyV0; + // case SURVEY_TOPOLOGY_RESPONSE_V1: + // TopologyResponseBodyV1 topologyResponseBodyV1; + // case SURVEY_TOPOLOGY_RESPONSE_V2: + // TopologyResponseBodyV2 topologyResponseBodyV2; + // }; + // + // =========================================================================== + xdr.union("SurveyResponseBody", { + switchOn: xdr.lookup("SurveyMessageResponseType"), + switchName: "type", + switches: [["surveyTopologyResponseV0", "topologyResponseBodyV0"], ["surveyTopologyResponseV1", "topologyResponseBodyV1"], ["surveyTopologyResponseV2", "topologyResponseBodyV2"]], + arms: { + topologyResponseBodyV0: xdr.lookup("TopologyResponseBodyV0"), + topologyResponseBodyV1: xdr.lookup("TopologyResponseBodyV1"), + topologyResponseBodyV2: xdr.lookup("TopologyResponseBodyV2") + } + }); + + // === xdr source ============================================================ + // + // const TX_ADVERT_VECTOR_MAX_SIZE = 1000; + // + // =========================================================================== + xdr["const"]("TX_ADVERT_VECTOR_MAX_SIZE", 1000); + + // === xdr source ============================================================ + // + // typedef Hash TxAdvertVector; + // + // =========================================================================== + xdr.typedef("TxAdvertVector", xdr.varArray(xdr.lookup("Hash"), xdr.lookup("TX_ADVERT_VECTOR_MAX_SIZE"))); + + // === xdr source ============================================================ + // + // struct FloodAdvert + // { + // TxAdvertVector txHashes; + // }; + // + // =========================================================================== + xdr.struct("FloodAdvert", [["txHashes", xdr.lookup("TxAdvertVector")]]); + + // === xdr source ============================================================ + // + // const TX_DEMAND_VECTOR_MAX_SIZE = 1000; + // + // =========================================================================== + xdr["const"]("TX_DEMAND_VECTOR_MAX_SIZE", 1000); + + // === xdr source ============================================================ + // + // typedef Hash TxDemandVector; + // + // =========================================================================== + xdr.typedef("TxDemandVector", xdr.varArray(xdr.lookup("Hash"), xdr.lookup("TX_DEMAND_VECTOR_MAX_SIZE"))); + + // === xdr source ============================================================ + // + // struct FloodDemand + // { + // TxDemandVector txHashes; + // }; + // + // =========================================================================== + xdr.struct("FloodDemand", [["txHashes", xdr.lookup("TxDemandVector")]]); + + // === xdr source ============================================================ + // + // union StellarMessage switch (MessageType type) + // { + // case ERROR_MSG: + // Error error; + // case HELLO: + // Hello hello; + // case AUTH: + // Auth auth; + // case DONT_HAVE: + // DontHave dontHave; + // case GET_PEERS: + // void; + // case PEERS: + // PeerAddress peers<100>; + // + // case GET_TX_SET: + // uint256 txSetHash; + // case TX_SET: + // TransactionSet txSet; + // case GENERALIZED_TX_SET: + // GeneralizedTransactionSet generalizedTxSet; + // + // case TRANSACTION: + // TransactionEnvelope transaction; + // + // case SURVEY_REQUEST: + // SignedSurveyRequestMessage signedSurveyRequestMessage; + // + // case SURVEY_RESPONSE: + // SignedSurveyResponseMessage signedSurveyResponseMessage; + // + // case TIME_SLICED_SURVEY_REQUEST: + // SignedTimeSlicedSurveyRequestMessage signedTimeSlicedSurveyRequestMessage; + // + // case TIME_SLICED_SURVEY_RESPONSE: + // SignedTimeSlicedSurveyResponseMessage signedTimeSlicedSurveyResponseMessage; + // + // case TIME_SLICED_SURVEY_START_COLLECTING: + // SignedTimeSlicedSurveyStartCollectingMessage + // signedTimeSlicedSurveyStartCollectingMessage; + // + // case TIME_SLICED_SURVEY_STOP_COLLECTING: + // SignedTimeSlicedSurveyStopCollectingMessage + // signedTimeSlicedSurveyStopCollectingMessage; + // + // // SCP + // case GET_SCP_QUORUMSET: + // uint256 qSetHash; + // case SCP_QUORUMSET: + // SCPQuorumSet qSet; + // case SCP_MESSAGE: + // SCPEnvelope envelope; + // case GET_SCP_STATE: + // uint32 getSCPLedgerSeq; // ledger seq requested ; if 0, requests the latest + // case SEND_MORE: + // SendMore sendMoreMessage; + // case SEND_MORE_EXTENDED: + // SendMoreExtended sendMoreExtendedMessage; + // // Pull mode + // case FLOOD_ADVERT: + // FloodAdvert floodAdvert; + // case FLOOD_DEMAND: + // FloodDemand floodDemand; + // }; + // + // =========================================================================== + xdr.union("StellarMessage", { + switchOn: xdr.lookup("MessageType"), + switchName: "type", + switches: [["errorMsg", "error"], ["hello", "hello"], ["auth", "auth"], ["dontHave", "dontHave"], ["getPeers", xdr["void"]()], ["peers", "peers"], ["getTxSet", "txSetHash"], ["txSet", "txSet"], ["generalizedTxSet", "generalizedTxSet"], ["transaction", "transaction"], ["surveyRequest", "signedSurveyRequestMessage"], ["surveyResponse", "signedSurveyResponseMessage"], ["timeSlicedSurveyRequest", "signedTimeSlicedSurveyRequestMessage"], ["timeSlicedSurveyResponse", "signedTimeSlicedSurveyResponseMessage"], ["timeSlicedSurveyStartCollecting", "signedTimeSlicedSurveyStartCollectingMessage"], ["timeSlicedSurveyStopCollecting", "signedTimeSlicedSurveyStopCollectingMessage"], ["getScpQuorumset", "qSetHash"], ["scpQuorumset", "qSet"], ["scpMessage", "envelope"], ["getScpState", "getScpLedgerSeq"], ["sendMore", "sendMoreMessage"], ["sendMoreExtended", "sendMoreExtendedMessage"], ["floodAdvert", "floodAdvert"], ["floodDemand", "floodDemand"]], + arms: { + error: xdr.lookup("Error"), + hello: xdr.lookup("Hello"), + auth: xdr.lookup("Auth"), + dontHave: xdr.lookup("DontHave"), + peers: xdr.varArray(xdr.lookup("PeerAddress"), 100), + txSetHash: xdr.lookup("Uint256"), + txSet: xdr.lookup("TransactionSet"), + generalizedTxSet: xdr.lookup("GeneralizedTransactionSet"), + transaction: xdr.lookup("TransactionEnvelope"), + signedSurveyRequestMessage: xdr.lookup("SignedSurveyRequestMessage"), + signedSurveyResponseMessage: xdr.lookup("SignedSurveyResponseMessage"), + signedTimeSlicedSurveyRequestMessage: xdr.lookup("SignedTimeSlicedSurveyRequestMessage"), + signedTimeSlicedSurveyResponseMessage: xdr.lookup("SignedTimeSlicedSurveyResponseMessage"), + signedTimeSlicedSurveyStartCollectingMessage: xdr.lookup("SignedTimeSlicedSurveyStartCollectingMessage"), + signedTimeSlicedSurveyStopCollectingMessage: xdr.lookup("SignedTimeSlicedSurveyStopCollectingMessage"), + qSetHash: xdr.lookup("Uint256"), + qSet: xdr.lookup("ScpQuorumSet"), + envelope: xdr.lookup("ScpEnvelope"), + getScpLedgerSeq: xdr.lookup("Uint32"), + sendMoreMessage: xdr.lookup("SendMore"), + sendMoreExtendedMessage: xdr.lookup("SendMoreExtended"), + floodAdvert: xdr.lookup("FloodAdvert"), + floodDemand: xdr.lookup("FloodDemand") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // uint64 sequence; + // StellarMessage message; + // HmacSha256Mac mac; + // } + // + // =========================================================================== + xdr.struct("AuthenticatedMessageV0", [["sequence", xdr.lookup("Uint64")], ["message", xdr.lookup("StellarMessage")], ["mac", xdr.lookup("HmacSha256Mac")]]); + + // === xdr source ============================================================ + // + // union AuthenticatedMessage switch (uint32 v) + // { + // case 0: + // struct + // { + // uint64 sequence; + // StellarMessage message; + // HmacSha256Mac mac; + // } v0; + // }; + // + // =========================================================================== + xdr.union("AuthenticatedMessage", { + switchOn: xdr.lookup("Uint32"), + switchName: "v", + switches: [[0, "v0"]], + arms: { + v0: xdr.lookup("AuthenticatedMessageV0") + } + }); + + // === xdr source ============================================================ + // + // const MAX_OPS_PER_TX = 100; + // + // =========================================================================== + xdr["const"]("MAX_OPS_PER_TX", 100); + + // === xdr source ============================================================ + // + // union LiquidityPoolParameters switch (LiquidityPoolType type) + // { + // case LIQUIDITY_POOL_CONSTANT_PRODUCT: + // LiquidityPoolConstantProductParameters constantProduct; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolParameters", { + switchOn: xdr.lookup("LiquidityPoolType"), + switchName: "type", + switches: [["liquidityPoolConstantProduct", "constantProduct"]], + arms: { + constantProduct: xdr.lookup("LiquidityPoolConstantProductParameters") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // uint64 id; + // uint256 ed25519; + // } + // + // =========================================================================== + xdr.struct("MuxedAccountMed25519", [["id", xdr.lookup("Uint64")], ["ed25519", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // union MuxedAccount switch (CryptoKeyType type) + // { + // case KEY_TYPE_ED25519: + // uint256 ed25519; + // case KEY_TYPE_MUXED_ED25519: + // struct + // { + // uint64 id; + // uint256 ed25519; + // } med25519; + // }; + // + // =========================================================================== + xdr.union("MuxedAccount", { + switchOn: xdr.lookup("CryptoKeyType"), + switchName: "type", + switches: [["keyTypeEd25519", "ed25519"], ["keyTypeMuxedEd25519", "med25519"]], + arms: { + ed25519: xdr.lookup("Uint256"), + med25519: xdr.lookup("MuxedAccountMed25519") + } + }); + + // === xdr source ============================================================ + // + // struct DecoratedSignature + // { + // SignatureHint hint; // last 4 bytes of the public key, used as a hint + // Signature signature; // actual signature + // }; + // + // =========================================================================== + xdr.struct("DecoratedSignature", [["hint", xdr.lookup("SignatureHint")], ["signature", xdr.lookup("Signature")]]); + + // === xdr source ============================================================ + // + // enum OperationType + // { + // CREATE_ACCOUNT = 0, + // PAYMENT = 1, + // PATH_PAYMENT_STRICT_RECEIVE = 2, + // MANAGE_SELL_OFFER = 3, + // CREATE_PASSIVE_SELL_OFFER = 4, + // SET_OPTIONS = 5, + // CHANGE_TRUST = 6, + // ALLOW_TRUST = 7, + // ACCOUNT_MERGE = 8, + // INFLATION = 9, + // MANAGE_DATA = 10, + // BUMP_SEQUENCE = 11, + // MANAGE_BUY_OFFER = 12, + // PATH_PAYMENT_STRICT_SEND = 13, + // CREATE_CLAIMABLE_BALANCE = 14, + // CLAIM_CLAIMABLE_BALANCE = 15, + // BEGIN_SPONSORING_FUTURE_RESERVES = 16, + // END_SPONSORING_FUTURE_RESERVES = 17, + // REVOKE_SPONSORSHIP = 18, + // CLAWBACK = 19, + // CLAWBACK_CLAIMABLE_BALANCE = 20, + // SET_TRUST_LINE_FLAGS = 21, + // LIQUIDITY_POOL_DEPOSIT = 22, + // LIQUIDITY_POOL_WITHDRAW = 23, + // INVOKE_HOST_FUNCTION = 24, + // EXTEND_FOOTPRINT_TTL = 25, + // RESTORE_FOOTPRINT = 26 + // }; + // + // =========================================================================== + xdr["enum"]("OperationType", { + createAccount: 0, + payment: 1, + pathPaymentStrictReceive: 2, + manageSellOffer: 3, + createPassiveSellOffer: 4, + setOptions: 5, + changeTrust: 6, + allowTrust: 7, + accountMerge: 8, + inflation: 9, + manageData: 10, + bumpSequence: 11, + manageBuyOffer: 12, + pathPaymentStrictSend: 13, + createClaimableBalance: 14, + claimClaimableBalance: 15, + beginSponsoringFutureReserves: 16, + endSponsoringFutureReserves: 17, + revokeSponsorship: 18, + clawback: 19, + clawbackClaimableBalance: 20, + setTrustLineFlags: 21, + liquidityPoolDeposit: 22, + liquidityPoolWithdraw: 23, + invokeHostFunction: 24, + extendFootprintTtl: 25, + restoreFootprint: 26 + }); + + // === xdr source ============================================================ + // + // struct CreateAccountOp + // { + // AccountID destination; // account to create + // int64 startingBalance; // amount they end up with + // }; + // + // =========================================================================== + xdr.struct("CreateAccountOp", [["destination", xdr.lookup("AccountId")], ["startingBalance", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct PaymentOp + // { + // MuxedAccount destination; // recipient of the payment + // Asset asset; // what they end up with + // int64 amount; // amount they end up with + // }; + // + // =========================================================================== + xdr.struct("PaymentOp", [["destination", xdr.lookup("MuxedAccount")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct PathPaymentStrictReceiveOp + // { + // Asset sendAsset; // asset we pay with + // int64 sendMax; // the maximum amount of sendAsset to + // // send (excluding fees). + // // The operation will fail if can't be met + // + // MuxedAccount destination; // recipient of the payment + // Asset destAsset; // what they end up with + // int64 destAmount; // amount they end up with + // + // Asset path<5>; // additional hops it must go through to get there + // }; + // + // =========================================================================== + xdr.struct("PathPaymentStrictReceiveOp", [["sendAsset", xdr.lookup("Asset")], ["sendMax", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destAmount", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]); + + // === xdr source ============================================================ + // + // struct PathPaymentStrictSendOp + // { + // Asset sendAsset; // asset we pay with + // int64 sendAmount; // amount of sendAsset to send (excluding fees) + // + // MuxedAccount destination; // recipient of the payment + // Asset destAsset; // what they end up with + // int64 destMin; // the minimum amount of dest asset to + // // be received + // // The operation will fail if it can't be met + // + // Asset path<5>; // additional hops it must go through to get there + // }; + // + // =========================================================================== + xdr.struct("PathPaymentStrictSendOp", [["sendAsset", xdr.lookup("Asset")], ["sendAmount", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destMin", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]); + + // === xdr source ============================================================ + // + // struct ManageSellOfferOp + // { + // Asset selling; + // Asset buying; + // int64 amount; // amount being sold. if set to 0, delete the offer + // Price price; // price of thing being sold in terms of what you are buying + // + // // 0=create a new offer, otherwise edit an existing offer + // int64 offerID; + // }; + // + // =========================================================================== + xdr.struct("ManageSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ManageBuyOfferOp + // { + // Asset selling; + // Asset buying; + // int64 buyAmount; // amount being bought. if set to 0, delete the offer + // Price price; // price of thing being bought in terms of what you are + // // selling + // + // // 0=create a new offer, otherwise edit an existing offer + // int64 offerID; + // }; + // + // =========================================================================== + xdr.struct("ManageBuyOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["buyAmount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct CreatePassiveSellOfferOp + // { + // Asset selling; // A + // Asset buying; // B + // int64 amount; // amount taker gets + // Price price; // cost of A in terms of B + // }; + // + // =========================================================================== + xdr.struct("CreatePassiveSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")]]); + + // === xdr source ============================================================ + // + // struct SetOptionsOp + // { + // AccountID* inflationDest; // sets the inflation destination + // + // uint32* clearFlags; // which flags to clear + // uint32* setFlags; // which flags to set + // + // // account threshold manipulation + // uint32* masterWeight; // weight of the master account + // uint32* lowThreshold; + // uint32* medThreshold; + // uint32* highThreshold; + // + // string32* homeDomain; // sets the home domain + // + // // Add, update or remove a signer for the account + // // signer is deleted if the weight is 0 + // Signer* signer; + // }; + // + // =========================================================================== + xdr.struct("SetOptionsOp", [["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["clearFlags", xdr.option(xdr.lookup("Uint32"))], ["setFlags", xdr.option(xdr.lookup("Uint32"))], ["masterWeight", xdr.option(xdr.lookup("Uint32"))], ["lowThreshold", xdr.option(xdr.lookup("Uint32"))], ["medThreshold", xdr.option(xdr.lookup("Uint32"))], ["highThreshold", xdr.option(xdr.lookup("Uint32"))], ["homeDomain", xdr.option(xdr.lookup("String32"))], ["signer", xdr.option(xdr.lookup("Signer"))]]); + + // === xdr source ============================================================ + // + // union ChangeTrustAsset switch (AssetType type) + // { + // case ASSET_TYPE_NATIVE: // Not credit + // void; + // + // case ASSET_TYPE_CREDIT_ALPHANUM4: + // AlphaNum4 alphaNum4; + // + // case ASSET_TYPE_CREDIT_ALPHANUM12: + // AlphaNum12 alphaNum12; + // + // case ASSET_TYPE_POOL_SHARE: + // LiquidityPoolParameters liquidityPool; + // + // // add other asset types here in the future + // }; + // + // =========================================================================== + xdr.union("ChangeTrustAsset", { + switchOn: xdr.lookup("AssetType"), + switchName: "type", + switches: [["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPool"]], + arms: { + alphaNum4: xdr.lookup("AlphaNum4"), + alphaNum12: xdr.lookup("AlphaNum12"), + liquidityPool: xdr.lookup("LiquidityPoolParameters") + } + }); + + // === xdr source ============================================================ + // + // struct ChangeTrustOp + // { + // ChangeTrustAsset line; + // + // // if limit is set to 0, deletes the trust line + // int64 limit; + // }; + // + // =========================================================================== + xdr.struct("ChangeTrustOp", [["line", xdr.lookup("ChangeTrustAsset")], ["limit", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct AllowTrustOp + // { + // AccountID trustor; + // AssetCode asset; + // + // // One of 0, AUTHORIZED_FLAG, or AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG + // uint32 authorize; + // }; + // + // =========================================================================== + xdr.struct("AllowTrustOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("AssetCode")], ["authorize", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ManageDataOp + // { + // string64 dataName; + // DataValue* dataValue; // set to null to clear + // }; + // + // =========================================================================== + xdr.struct("ManageDataOp", [["dataName", xdr.lookup("String64")], ["dataValue", xdr.option(xdr.lookup("DataValue"))]]); + + // === xdr source ============================================================ + // + // struct BumpSequenceOp + // { + // SequenceNumber bumpTo; + // }; + // + // =========================================================================== + xdr.struct("BumpSequenceOp", [["bumpTo", xdr.lookup("SequenceNumber")]]); + + // === xdr source ============================================================ + // + // struct CreateClaimableBalanceOp + // { + // Asset asset; + // int64 amount; + // Claimant claimants<10>; + // }; + // + // =========================================================================== + xdr.struct("CreateClaimableBalanceOp", [["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)]]); + + // === xdr source ============================================================ + // + // struct ClaimClaimableBalanceOp + // { + // ClaimableBalanceID balanceID; + // }; + // + // =========================================================================== + xdr.struct("ClaimClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct BeginSponsoringFutureReservesOp + // { + // AccountID sponsoredID; + // }; + // + // =========================================================================== + xdr.struct("BeginSponsoringFutureReservesOp", [["sponsoredId", xdr.lookup("AccountId")]]); + + // === xdr source ============================================================ + // + // enum RevokeSponsorshipType + // { + // REVOKE_SPONSORSHIP_LEDGER_ENTRY = 0, + // REVOKE_SPONSORSHIP_SIGNER = 1 + // }; + // + // =========================================================================== + xdr["enum"]("RevokeSponsorshipType", { + revokeSponsorshipLedgerEntry: 0, + revokeSponsorshipSigner: 1 + }); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID accountID; + // SignerKey signerKey; + // } + // + // =========================================================================== + xdr.struct("RevokeSponsorshipOpSigner", [["accountId", xdr.lookup("AccountId")], ["signerKey", xdr.lookup("SignerKey")]]); + + // === xdr source ============================================================ + // + // union RevokeSponsorshipOp switch (RevokeSponsorshipType type) + // { + // case REVOKE_SPONSORSHIP_LEDGER_ENTRY: + // LedgerKey ledgerKey; + // case REVOKE_SPONSORSHIP_SIGNER: + // struct + // { + // AccountID accountID; + // SignerKey signerKey; + // } signer; + // }; + // + // =========================================================================== + xdr.union("RevokeSponsorshipOp", { + switchOn: xdr.lookup("RevokeSponsorshipType"), + switchName: "type", + switches: [["revokeSponsorshipLedgerEntry", "ledgerKey"], ["revokeSponsorshipSigner", "signer"]], + arms: { + ledgerKey: xdr.lookup("LedgerKey"), + signer: xdr.lookup("RevokeSponsorshipOpSigner") + } + }); + + // === xdr source ============================================================ + // + // struct ClawbackOp + // { + // Asset asset; + // MuxedAccount from; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("ClawbackOp", [["asset", xdr.lookup("Asset")], ["from", xdr.lookup("MuxedAccount")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClawbackClaimableBalanceOp + // { + // ClaimableBalanceID balanceID; + // }; + // + // =========================================================================== + xdr.struct("ClawbackClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]); + + // === xdr source ============================================================ + // + // struct SetTrustLineFlagsOp + // { + // AccountID trustor; + // Asset asset; + // + // uint32 clearFlags; // which flags to clear + // uint32 setFlags; // which flags to set + // }; + // + // =========================================================================== + xdr.struct("SetTrustLineFlagsOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["clearFlags", xdr.lookup("Uint32")], ["setFlags", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // const LIQUIDITY_POOL_FEE_V18 = 30; + // + // =========================================================================== + xdr["const"]("LIQUIDITY_POOL_FEE_V18", 30); + + // === xdr source ============================================================ + // + // struct LiquidityPoolDepositOp + // { + // PoolID liquidityPoolID; + // int64 maxAmountA; // maximum amount of first asset to deposit + // int64 maxAmountB; // maximum amount of second asset to deposit + // Price minPrice; // minimum depositA/depositB + // Price maxPrice; // maximum depositA/depositB + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolDepositOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["maxAmountA", xdr.lookup("Int64")], ["maxAmountB", xdr.lookup("Int64")], ["minPrice", xdr.lookup("Price")], ["maxPrice", xdr.lookup("Price")]]); + + // === xdr source ============================================================ + // + // struct LiquidityPoolWithdrawOp + // { + // PoolID liquidityPoolID; + // int64 amount; // amount of pool shares to withdraw + // int64 minAmountA; // minimum amount of first asset to withdraw + // int64 minAmountB; // minimum amount of second asset to withdraw + // }; + // + // =========================================================================== + xdr.struct("LiquidityPoolWithdrawOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["amount", xdr.lookup("Int64")], ["minAmountA", xdr.lookup("Int64")], ["minAmountB", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum HostFunctionType + // { + // HOST_FUNCTION_TYPE_INVOKE_CONTRACT = 0, + // HOST_FUNCTION_TYPE_CREATE_CONTRACT = 1, + // HOST_FUNCTION_TYPE_UPLOAD_CONTRACT_WASM = 2, + // HOST_FUNCTION_TYPE_CREATE_CONTRACT_V2 = 3 + // }; + // + // =========================================================================== + xdr["enum"]("HostFunctionType", { + hostFunctionTypeInvokeContract: 0, + hostFunctionTypeCreateContract: 1, + hostFunctionTypeUploadContractWasm: 2, + hostFunctionTypeCreateContractV2: 3 + }); + + // === xdr source ============================================================ + // + // enum ContractIDPreimageType + // { + // CONTRACT_ID_PREIMAGE_FROM_ADDRESS = 0, + // CONTRACT_ID_PREIMAGE_FROM_ASSET = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractIdPreimageType", { + contractIdPreimageFromAddress: 0, + contractIdPreimageFromAsset: 1 + }); + + // === xdr source ============================================================ + // + // struct + // { + // SCAddress address; + // uint256 salt; + // } + // + // =========================================================================== + xdr.struct("ContractIdPreimageFromAddress", [["address", xdr.lookup("ScAddress")], ["salt", xdr.lookup("Uint256")]]); + + // === xdr source ============================================================ + // + // union ContractIDPreimage switch (ContractIDPreimageType type) + // { + // case CONTRACT_ID_PREIMAGE_FROM_ADDRESS: + // struct + // { + // SCAddress address; + // uint256 salt; + // } fromAddress; + // case CONTRACT_ID_PREIMAGE_FROM_ASSET: + // Asset fromAsset; + // }; + // + // =========================================================================== + xdr.union("ContractIdPreimage", { + switchOn: xdr.lookup("ContractIdPreimageType"), + switchName: "type", + switches: [["contractIdPreimageFromAddress", "fromAddress"], ["contractIdPreimageFromAsset", "fromAsset"]], + arms: { + fromAddress: xdr.lookup("ContractIdPreimageFromAddress"), + fromAsset: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // struct CreateContractArgs + // { + // ContractIDPreimage contractIDPreimage; + // ContractExecutable executable; + // }; + // + // =========================================================================== + xdr.struct("CreateContractArgs", [["contractIdPreimage", xdr.lookup("ContractIdPreimage")], ["executable", xdr.lookup("ContractExecutable")]]); + + // === xdr source ============================================================ + // + // struct CreateContractArgsV2 + // { + // ContractIDPreimage contractIDPreimage; + // ContractExecutable executable; + // // Arguments of the contract's constructor. + // SCVal constructorArgs<>; + // }; + // + // =========================================================================== + xdr.struct("CreateContractArgsV2", [["contractIdPreimage", xdr.lookup("ContractIdPreimage")], ["executable", xdr.lookup("ContractExecutable")], ["constructorArgs", xdr.varArray(xdr.lookup("ScVal"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct InvokeContractArgs { + // SCAddress contractAddress; + // SCSymbol functionName; + // SCVal args<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeContractArgs", [["contractAddress", xdr.lookup("ScAddress")], ["functionName", xdr.lookup("ScSymbol")], ["args", xdr.varArray(xdr.lookup("ScVal"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union HostFunction switch (HostFunctionType type) + // { + // case HOST_FUNCTION_TYPE_INVOKE_CONTRACT: + // InvokeContractArgs invokeContract; + // case HOST_FUNCTION_TYPE_CREATE_CONTRACT: + // CreateContractArgs createContract; + // case HOST_FUNCTION_TYPE_UPLOAD_CONTRACT_WASM: + // opaque wasm<>; + // case HOST_FUNCTION_TYPE_CREATE_CONTRACT_V2: + // CreateContractArgsV2 createContractV2; + // }; + // + // =========================================================================== + xdr.union("HostFunction", { + switchOn: xdr.lookup("HostFunctionType"), + switchName: "type", + switches: [["hostFunctionTypeInvokeContract", "invokeContract"], ["hostFunctionTypeCreateContract", "createContract"], ["hostFunctionTypeUploadContractWasm", "wasm"], ["hostFunctionTypeCreateContractV2", "createContractV2"]], + arms: { + invokeContract: xdr.lookup("InvokeContractArgs"), + createContract: xdr.lookup("CreateContractArgs"), + wasm: xdr.varOpaque(), + createContractV2: xdr.lookup("CreateContractArgsV2") + } + }); + + // === xdr source ============================================================ + // + // enum SorobanAuthorizedFunctionType + // { + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN = 0, + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_HOST_FN = 1, + // SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN = 2 + // }; + // + // =========================================================================== + xdr["enum"]("SorobanAuthorizedFunctionType", { + sorobanAuthorizedFunctionTypeContractFn: 0, + sorobanAuthorizedFunctionTypeCreateContractHostFn: 1, + sorobanAuthorizedFunctionTypeCreateContractV2HostFn: 2 + }); + + // === xdr source ============================================================ + // + // union SorobanAuthorizedFunction switch (SorobanAuthorizedFunctionType type) + // { + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CONTRACT_FN: + // InvokeContractArgs contractFn; + // // This variant of auth payload for creating new contract instances + // // doesn't allow specifying the constructor arguments, creating contracts + // // with constructors that take arguments is only possible by authorizing + // // `SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN` + // // (protocol 22+). + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_HOST_FN: + // CreateContractArgs createContractHostFn; + // // This variant of auth payload for creating new contract instances + // // is only accepted in and after protocol 22. It allows authorizing the + // // contract constructor arguments. + // case SOROBAN_AUTHORIZED_FUNCTION_TYPE_CREATE_CONTRACT_V2_HOST_FN: + // CreateContractArgsV2 createContractV2HostFn; + // }; + // + // =========================================================================== + xdr.union("SorobanAuthorizedFunction", { + switchOn: xdr.lookup("SorobanAuthorizedFunctionType"), + switchName: "type", + switches: [["sorobanAuthorizedFunctionTypeContractFn", "contractFn"], ["sorobanAuthorizedFunctionTypeCreateContractHostFn", "createContractHostFn"], ["sorobanAuthorizedFunctionTypeCreateContractV2HostFn", "createContractV2HostFn"]], + arms: { + contractFn: xdr.lookup("InvokeContractArgs"), + createContractHostFn: xdr.lookup("CreateContractArgs"), + createContractV2HostFn: xdr.lookup("CreateContractArgsV2") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanAuthorizedInvocation + // { + // SorobanAuthorizedFunction function; + // SorobanAuthorizedInvocation subInvocations<>; + // }; + // + // =========================================================================== + xdr.struct("SorobanAuthorizedInvocation", [["function", xdr.lookup("SorobanAuthorizedFunction")], ["subInvocations", xdr.varArray(xdr.lookup("SorobanAuthorizedInvocation"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct SorobanAddressCredentials + // { + // SCAddress address; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SCVal signature; + // }; + // + // =========================================================================== + xdr.struct("SorobanAddressCredentials", [["address", xdr.lookup("ScAddress")], ["nonce", xdr.lookup("Int64")], ["signatureExpirationLedger", xdr.lookup("Uint32")], ["signature", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // enum SorobanCredentialsType + // { + // SOROBAN_CREDENTIALS_SOURCE_ACCOUNT = 0, + // SOROBAN_CREDENTIALS_ADDRESS = 1 + // }; + // + // =========================================================================== + xdr["enum"]("SorobanCredentialsType", { + sorobanCredentialsSourceAccount: 0, + sorobanCredentialsAddress: 1 + }); + + // === xdr source ============================================================ + // + // union SorobanCredentials switch (SorobanCredentialsType type) + // { + // case SOROBAN_CREDENTIALS_SOURCE_ACCOUNT: + // void; + // case SOROBAN_CREDENTIALS_ADDRESS: + // SorobanAddressCredentials address; + // }; + // + // =========================================================================== + xdr.union("SorobanCredentials", { + switchOn: xdr.lookup("SorobanCredentialsType"), + switchName: "type", + switches: [["sorobanCredentialsSourceAccount", xdr["void"]()], ["sorobanCredentialsAddress", "address"]], + arms: { + address: xdr.lookup("SorobanAddressCredentials") + } + }); + + // === xdr source ============================================================ + // + // struct SorobanAuthorizationEntry + // { + // SorobanCredentials credentials; + // SorobanAuthorizedInvocation rootInvocation; + // }; + // + // =========================================================================== + xdr.struct("SorobanAuthorizationEntry", [["credentials", xdr.lookup("SorobanCredentials")], ["rootInvocation", xdr.lookup("SorobanAuthorizedInvocation")]]); + + // === xdr source ============================================================ + // + // struct InvokeHostFunctionOp + // { + // // Host function to invoke. + // HostFunction hostFunction; + // // Per-address authorizations for this host function. + // SorobanAuthorizationEntry auth<>; + // }; + // + // =========================================================================== + xdr.struct("InvokeHostFunctionOp", [["hostFunction", xdr.lookup("HostFunction")], ["auth", xdr.varArray(xdr.lookup("SorobanAuthorizationEntry"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct ExtendFootprintTTLOp + // { + // ExtensionPoint ext; + // uint32 extendTo; + // }; + // + // =========================================================================== + xdr.struct("ExtendFootprintTtlOp", [["ext", xdr.lookup("ExtensionPoint")], ["extendTo", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct RestoreFootprintOp + // { + // ExtensionPoint ext; + // }; + // + // =========================================================================== + xdr.struct("RestoreFootprintOp", [["ext", xdr.lookup("ExtensionPoint")]]); + + // === xdr source ============================================================ + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountOp createAccountOp; + // case PAYMENT: + // PaymentOp paymentOp; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp; + // case MANAGE_SELL_OFFER: + // ManageSellOfferOp manageSellOfferOp; + // case CREATE_PASSIVE_SELL_OFFER: + // CreatePassiveSellOfferOp createPassiveSellOfferOp; + // case SET_OPTIONS: + // SetOptionsOp setOptionsOp; + // case CHANGE_TRUST: + // ChangeTrustOp changeTrustOp; + // case ALLOW_TRUST: + // AllowTrustOp allowTrustOp; + // case ACCOUNT_MERGE: + // MuxedAccount destination; + // case INFLATION: + // void; + // case MANAGE_DATA: + // ManageDataOp manageDataOp; + // case BUMP_SEQUENCE: + // BumpSequenceOp bumpSequenceOp; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferOp manageBuyOfferOp; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendOp pathPaymentStrictSendOp; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceOp createClaimableBalanceOp; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceOp claimClaimableBalanceOp; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp; + // case END_SPONSORING_FUTURE_RESERVES: + // void; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipOp revokeSponsorshipOp; + // case CLAWBACK: + // ClawbackOp clawbackOp; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceOp clawbackClaimableBalanceOp; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsOp setTrustLineFlagsOp; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositOp liquidityPoolDepositOp; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawOp liquidityPoolWithdrawOp; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionOp invokeHostFunctionOp; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLOp extendFootprintTTLOp; + // case RESTORE_FOOTPRINT: + // RestoreFootprintOp restoreFootprintOp; + // } + // + // =========================================================================== + xdr.union("OperationBody", { + switchOn: xdr.lookup("OperationType"), + switchName: "type", + switches: [["createAccount", "createAccountOp"], ["payment", "paymentOp"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveOp"], ["manageSellOffer", "manageSellOfferOp"], ["createPassiveSellOffer", "createPassiveSellOfferOp"], ["setOptions", "setOptionsOp"], ["changeTrust", "changeTrustOp"], ["allowTrust", "allowTrustOp"], ["accountMerge", "destination"], ["inflation", xdr["void"]()], ["manageData", "manageDataOp"], ["bumpSequence", "bumpSequenceOp"], ["manageBuyOffer", "manageBuyOfferOp"], ["pathPaymentStrictSend", "pathPaymentStrictSendOp"], ["createClaimableBalance", "createClaimableBalanceOp"], ["claimClaimableBalance", "claimClaimableBalanceOp"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesOp"], ["endSponsoringFutureReserves", xdr["void"]()], ["revokeSponsorship", "revokeSponsorshipOp"], ["clawback", "clawbackOp"], ["clawbackClaimableBalance", "clawbackClaimableBalanceOp"], ["setTrustLineFlags", "setTrustLineFlagsOp"], ["liquidityPoolDeposit", "liquidityPoolDepositOp"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawOp"], ["invokeHostFunction", "invokeHostFunctionOp"], ["extendFootprintTtl", "extendFootprintTtlOp"], ["restoreFootprint", "restoreFootprintOp"]], + arms: { + createAccountOp: xdr.lookup("CreateAccountOp"), + paymentOp: xdr.lookup("PaymentOp"), + pathPaymentStrictReceiveOp: xdr.lookup("PathPaymentStrictReceiveOp"), + manageSellOfferOp: xdr.lookup("ManageSellOfferOp"), + createPassiveSellOfferOp: xdr.lookup("CreatePassiveSellOfferOp"), + setOptionsOp: xdr.lookup("SetOptionsOp"), + changeTrustOp: xdr.lookup("ChangeTrustOp"), + allowTrustOp: xdr.lookup("AllowTrustOp"), + destination: xdr.lookup("MuxedAccount"), + manageDataOp: xdr.lookup("ManageDataOp"), + bumpSequenceOp: xdr.lookup("BumpSequenceOp"), + manageBuyOfferOp: xdr.lookup("ManageBuyOfferOp"), + pathPaymentStrictSendOp: xdr.lookup("PathPaymentStrictSendOp"), + createClaimableBalanceOp: xdr.lookup("CreateClaimableBalanceOp"), + claimClaimableBalanceOp: xdr.lookup("ClaimClaimableBalanceOp"), + beginSponsoringFutureReservesOp: xdr.lookup("BeginSponsoringFutureReservesOp"), + revokeSponsorshipOp: xdr.lookup("RevokeSponsorshipOp"), + clawbackOp: xdr.lookup("ClawbackOp"), + clawbackClaimableBalanceOp: xdr.lookup("ClawbackClaimableBalanceOp"), + setTrustLineFlagsOp: xdr.lookup("SetTrustLineFlagsOp"), + liquidityPoolDepositOp: xdr.lookup("LiquidityPoolDepositOp"), + liquidityPoolWithdrawOp: xdr.lookup("LiquidityPoolWithdrawOp"), + invokeHostFunctionOp: xdr.lookup("InvokeHostFunctionOp"), + extendFootprintTtlOp: xdr.lookup("ExtendFootprintTtlOp"), + restoreFootprintOp: xdr.lookup("RestoreFootprintOp") + } + }); + + // === xdr source ============================================================ + // + // struct Operation + // { + // // sourceAccount is the account used to run the operation + // // if not set, the runtime defaults to "sourceAccount" specified at + // // the transaction level + // MuxedAccount* sourceAccount; + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountOp createAccountOp; + // case PAYMENT: + // PaymentOp paymentOp; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp; + // case MANAGE_SELL_OFFER: + // ManageSellOfferOp manageSellOfferOp; + // case CREATE_PASSIVE_SELL_OFFER: + // CreatePassiveSellOfferOp createPassiveSellOfferOp; + // case SET_OPTIONS: + // SetOptionsOp setOptionsOp; + // case CHANGE_TRUST: + // ChangeTrustOp changeTrustOp; + // case ALLOW_TRUST: + // AllowTrustOp allowTrustOp; + // case ACCOUNT_MERGE: + // MuxedAccount destination; + // case INFLATION: + // void; + // case MANAGE_DATA: + // ManageDataOp manageDataOp; + // case BUMP_SEQUENCE: + // BumpSequenceOp bumpSequenceOp; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferOp manageBuyOfferOp; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendOp pathPaymentStrictSendOp; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceOp createClaimableBalanceOp; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceOp claimClaimableBalanceOp; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp; + // case END_SPONSORING_FUTURE_RESERVES: + // void; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipOp revokeSponsorshipOp; + // case CLAWBACK: + // ClawbackOp clawbackOp; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceOp clawbackClaimableBalanceOp; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsOp setTrustLineFlagsOp; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositOp liquidityPoolDepositOp; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawOp liquidityPoolWithdrawOp; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionOp invokeHostFunctionOp; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLOp extendFootprintTTLOp; + // case RESTORE_FOOTPRINT: + // RestoreFootprintOp restoreFootprintOp; + // } + // body; + // }; + // + // =========================================================================== + xdr.struct("Operation", [["sourceAccount", xdr.option(xdr.lookup("MuxedAccount"))], ["body", xdr.lookup("OperationBody")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageOperationId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // PoolID liquidityPoolID; + // Asset asset; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageRevokeId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")], ["liquidityPoolId", xdr.lookup("PoolId")], ["asset", xdr.lookup("Asset")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash networkID; + // ContractIDPreimage contractIDPreimage; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageContractId", [["networkId", xdr.lookup("Hash")], ["contractIdPreimage", xdr.lookup("ContractIdPreimage")]]); + + // === xdr source ============================================================ + // + // struct + // { + // Hash networkID; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SorobanAuthorizedInvocation invocation; + // } + // + // =========================================================================== + xdr.struct("HashIdPreimageSorobanAuthorization", [["networkId", xdr.lookup("Hash")], ["nonce", xdr.lookup("Int64")], ["signatureExpirationLedger", xdr.lookup("Uint32")], ["invocation", xdr.lookup("SorobanAuthorizedInvocation")]]); + + // === xdr source ============================================================ + // + // union HashIDPreimage switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_OP_ID: + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // } operationID; + // case ENVELOPE_TYPE_POOL_REVOKE_OP_ID: + // struct + // { + // AccountID sourceAccount; + // SequenceNumber seqNum; + // uint32 opNum; + // PoolID liquidityPoolID; + // Asset asset; + // } revokeID; + // case ENVELOPE_TYPE_CONTRACT_ID: + // struct + // { + // Hash networkID; + // ContractIDPreimage contractIDPreimage; + // } contractID; + // case ENVELOPE_TYPE_SOROBAN_AUTHORIZATION: + // struct + // { + // Hash networkID; + // int64 nonce; + // uint32 signatureExpirationLedger; + // SorobanAuthorizedInvocation invocation; + // } sorobanAuthorization; + // }; + // + // =========================================================================== + xdr.union("HashIdPreimage", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeOpId", "operationId"], ["envelopeTypePoolRevokeOpId", "revokeId"], ["envelopeTypeContractId", "contractId"], ["envelopeTypeSorobanAuthorization", "sorobanAuthorization"]], + arms: { + operationId: xdr.lookup("HashIdPreimageOperationId"), + revokeId: xdr.lookup("HashIdPreimageRevokeId"), + contractId: xdr.lookup("HashIdPreimageContractId"), + sorobanAuthorization: xdr.lookup("HashIdPreimageSorobanAuthorization") + } + }); + + // === xdr source ============================================================ + // + // enum MemoType + // { + // MEMO_NONE = 0, + // MEMO_TEXT = 1, + // MEMO_ID = 2, + // MEMO_HASH = 3, + // MEMO_RETURN = 4 + // }; + // + // =========================================================================== + xdr["enum"]("MemoType", { + memoNone: 0, + memoText: 1, + memoId: 2, + memoHash: 3, + memoReturn: 4 + }); + + // === xdr source ============================================================ + // + // union Memo switch (MemoType type) + // { + // case MEMO_NONE: + // void; + // case MEMO_TEXT: + // string text<28>; + // case MEMO_ID: + // uint64 id; + // case MEMO_HASH: + // Hash hash; // the hash of what to pull from the content server + // case MEMO_RETURN: + // Hash retHash; // the hash of the tx you are rejecting + // }; + // + // =========================================================================== + xdr.union("Memo", { + switchOn: xdr.lookup("MemoType"), + switchName: "type", + switches: [["memoNone", xdr["void"]()], ["memoText", "text"], ["memoId", "id"], ["memoHash", "hash"], ["memoReturn", "retHash"]], + arms: { + text: xdr.string(28), + id: xdr.lookup("Uint64"), + hash: xdr.lookup("Hash"), + retHash: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // struct TimeBounds + // { + // TimePoint minTime; + // TimePoint maxTime; // 0 here means no maxTime + // }; + // + // =========================================================================== + xdr.struct("TimeBounds", [["minTime", xdr.lookup("TimePoint")], ["maxTime", xdr.lookup("TimePoint")]]); + + // === xdr source ============================================================ + // + // struct LedgerBounds + // { + // uint32 minLedger; + // uint32 maxLedger; // 0 here means no maxLedger + // }; + // + // =========================================================================== + xdr.struct("LedgerBounds", [["minLedger", xdr.lookup("Uint32")], ["maxLedger", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct PreconditionsV2 + // { + // TimeBounds* timeBounds; + // + // // Transaction only valid for ledger numbers n such that + // // minLedger <= n < maxLedger (if maxLedger == 0, then + // // only minLedger is checked) + // LedgerBounds* ledgerBounds; + // + // // If NULL, only valid when sourceAccount's sequence number + // // is seqNum - 1. Otherwise, valid when sourceAccount's + // // sequence number n satisfies minSeqNum <= n < tx.seqNum. + // // Note that after execution the account's sequence number + // // is always raised to tx.seqNum, and a transaction is not + // // valid if tx.seqNum is too high to ensure replay protection. + // SequenceNumber* minSeqNum; + // + // // For the transaction to be valid, the current ledger time must + // // be at least minSeqAge greater than sourceAccount's seqTime. + // Duration minSeqAge; + // + // // For the transaction to be valid, the current ledger number + // // must be at least minSeqLedgerGap greater than sourceAccount's + // // seqLedger. + // uint32 minSeqLedgerGap; + // + // // For the transaction to be valid, there must be a signature + // // corresponding to every Signer in this array, even if the + // // signature is not otherwise required by the sourceAccount or + // // operations. + // SignerKey extraSigners<2>; + // }; + // + // =========================================================================== + xdr.struct("PreconditionsV2", [["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["ledgerBounds", xdr.option(xdr.lookup("LedgerBounds"))], ["minSeqNum", xdr.option(xdr.lookup("SequenceNumber"))], ["minSeqAge", xdr.lookup("Duration")], ["minSeqLedgerGap", xdr.lookup("Uint32")], ["extraSigners", xdr.varArray(xdr.lookup("SignerKey"), 2)]]); + + // === xdr source ============================================================ + // + // enum PreconditionType + // { + // PRECOND_NONE = 0, + // PRECOND_TIME = 1, + // PRECOND_V2 = 2 + // }; + // + // =========================================================================== + xdr["enum"]("PreconditionType", { + precondNone: 0, + precondTime: 1, + precondV2: 2 + }); + + // === xdr source ============================================================ + // + // union Preconditions switch (PreconditionType type) + // { + // case PRECOND_NONE: + // void; + // case PRECOND_TIME: + // TimeBounds timeBounds; + // case PRECOND_V2: + // PreconditionsV2 v2; + // }; + // + // =========================================================================== + xdr.union("Preconditions", { + switchOn: xdr.lookup("PreconditionType"), + switchName: "type", + switches: [["precondNone", xdr["void"]()], ["precondTime", "timeBounds"], ["precondV2", "v2"]], + arms: { + timeBounds: xdr.lookup("TimeBounds"), + v2: xdr.lookup("PreconditionsV2") + } + }); + + // === xdr source ============================================================ + // + // struct LedgerFootprint + // { + // LedgerKey readOnly<>; + // LedgerKey readWrite<>; + // }; + // + // =========================================================================== + xdr.struct("LedgerFootprint", [["readOnly", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["readWrite", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)]]); + + // === xdr source ============================================================ + // + // enum ArchivalProofType + // { + // EXISTENCE = 0, + // NONEXISTENCE = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ArchivalProofType", { + existence: 0, + nonexistence: 1 + }); + + // === xdr source ============================================================ + // + // struct ArchivalProofNode + // { + // uint32 index; + // Hash hash; + // }; + // + // =========================================================================== + xdr.struct("ArchivalProofNode", [["index", xdr.lookup("Uint32")], ["hash", xdr.lookup("Hash")]]); + + // === xdr source ============================================================ + // + // typedef ArchivalProofNode ProofLevel<>; + // + // =========================================================================== + xdr.typedef("ProofLevel", xdr.varArray(xdr.lookup("ArchivalProofNode"), 2147483647)); + + // === xdr source ============================================================ + // + // struct NonexistenceProofBody + // { + // ColdArchiveBucketEntry entriesToProve<>; + // + // // Vector of vectors, where proofLevels[level] + // // contains all HashNodes that correspond with that level + // ProofLevel proofLevels<>; + // }; + // + // =========================================================================== + xdr.struct("NonexistenceProofBody", [["entriesToProve", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["proofLevels", xdr.varArray(xdr.lookup("ProofLevel"), 2147483647)]]); + + // === xdr source ============================================================ + // + // struct ExistenceProofBody + // { + // LedgerKey keysToProve<>; + // + // // Bounds for each key being proved, where bound[n] + // // corresponds to keysToProve[n] + // ColdArchiveBucketEntry lowBoundEntries<>; + // ColdArchiveBucketEntry highBoundEntries<>; + // + // // Vector of vectors, where proofLevels[level] + // // contains all HashNodes that correspond with that level + // ProofLevel proofLevels<>; + // }; + // + // =========================================================================== + xdr.struct("ExistenceProofBody", [["keysToProve", xdr.varArray(xdr.lookup("LedgerKey"), 2147483647)], ["lowBoundEntries", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["highBoundEntries", xdr.varArray(xdr.lookup("ColdArchiveBucketEntry"), 2147483647)], ["proofLevels", xdr.varArray(xdr.lookup("ProofLevel"), 2147483647)]]); + + // === xdr source ============================================================ + // + // union switch (ArchivalProofType t) + // { + // case EXISTENCE: + // NonexistenceProofBody nonexistenceProof; + // case NONEXISTENCE: + // ExistenceProofBody existenceProof; + // } + // + // =========================================================================== + xdr.union("ArchivalProofBody", { + switchOn: xdr.lookup("ArchivalProofType"), + switchName: "t", + switches: [["existence", "nonexistenceProof"], ["nonexistence", "existenceProof"]], + arms: { + nonexistenceProof: xdr.lookup("NonexistenceProofBody"), + existenceProof: xdr.lookup("ExistenceProofBody") + } + }); + + // === xdr source ============================================================ + // + // struct ArchivalProof + // { + // uint32 epoch; // AST Subtree for this proof + // + // union switch (ArchivalProofType t) + // { + // case EXISTENCE: + // NonexistenceProofBody nonexistenceProof; + // case NONEXISTENCE: + // ExistenceProofBody existenceProof; + // } body; + // }; + // + // =========================================================================== + xdr.struct("ArchivalProof", [["epoch", xdr.lookup("Uint32")], ["body", xdr.lookup("ArchivalProofBody")]]); + + // === xdr source ============================================================ + // + // struct SorobanResources + // { + // // The ledger footprint of the transaction. + // LedgerFootprint footprint; + // // The maximum number of instructions this transaction can use + // uint32 instructions; + // + // // The maximum number of bytes this transaction can read from ledger + // uint32 readBytes; + // // The maximum number of bytes this transaction can write to ledger + // uint32 writeBytes; + // }; + // + // =========================================================================== + xdr.struct("SorobanResources", [["footprint", xdr.lookup("LedgerFootprint")], ["instructions", xdr.lookup("Uint32")], ["readBytes", xdr.lookup("Uint32")], ["writeBytes", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SorobanTransactionData + // { + // ExtensionPoint ext; + // SorobanResources resources; + // // Amount of the transaction `fee` allocated to the Soroban resource fees. + // // The fraction of `resourceFee` corresponding to `resources` specified + // // above is *not* refundable (i.e. fees for instructions, ledger I/O), as + // // well as fees for the transaction size. + // // The remaining part of the fee is refundable and the charged value is + // // based on the actual consumption of refundable resources (events, ledger + // // rent bumps). + // // The `inclusionFee` used for prioritization of the transaction is defined + // // as `tx.fee - resourceFee`. + // int64 resourceFee; + // }; + // + // =========================================================================== + xdr.struct("SorobanTransactionData", [["ext", xdr.lookup("ExtensionPoint")], ["resources", xdr.lookup("SorobanResources")], ["resourceFee", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionV0Ext", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionV0 + // { + // uint256 sourceAccountEd25519; + // uint32 fee; + // SequenceNumber seqNum; + // TimeBounds* timeBounds; + // Memo memo; + // Operation operations; + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionV0", [["sourceAccountEd25519", xdr.lookup("Uint256")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionV0Ext")]]); + + // === xdr source ============================================================ + // + // struct TransactionV0Envelope + // { + // TransactionV0 tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("TransactionV0Envelope", [["tx", xdr.lookup("TransactionV0")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionData sorobanData; + // } + // + // =========================================================================== + xdr.union("TransactionExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()], [1, "sorobanData"]], + arms: { + sorobanData: xdr.lookup("SorobanTransactionData") + } + }); + + // === xdr source ============================================================ + // + // struct Transaction + // { + // // account used to run the transaction + // MuxedAccount sourceAccount; + // + // // the fee the sourceAccount will pay + // uint32 fee; + // + // // sequence number to consume in the account + // SequenceNumber seqNum; + // + // // validity conditions + // Preconditions cond; + // + // Memo memo; + // + // Operation operations; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // case 1: + // SorobanTransactionData sorobanData; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("Transaction", [["sourceAccount", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["cond", xdr.lookup("Preconditions")], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionExt")]]); + + // === xdr source ============================================================ + // + // struct TransactionV1Envelope + // { + // Transaction tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("TransactionV1Envelope", [["tx", xdr.lookup("Transaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // } + // + // =========================================================================== + xdr.union("FeeBumpTransactionInnerTx", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTx", "v1"]], + arms: { + v1: xdr.lookup("TransactionV1Envelope") + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("FeeBumpTransactionExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct FeeBumpTransaction + // { + // MuxedAccount feeSource; + // int64 fee; + // union switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // } + // innerTx; + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("FeeBumpTransaction", [["feeSource", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Int64")], ["innerTx", xdr.lookup("FeeBumpTransactionInnerTx")], ["ext", xdr.lookup("FeeBumpTransactionExt")]]); + + // === xdr source ============================================================ + // + // struct FeeBumpTransactionEnvelope + // { + // FeeBumpTransaction tx; + // /* Each decorated signature is a signature over the SHA256 hash of + // * a TransactionSignaturePayload */ + // DecoratedSignature signatures<20>; + // }; + // + // =========================================================================== + xdr.struct("FeeBumpTransactionEnvelope", [["tx", xdr.lookup("FeeBumpTransaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]); + + // === xdr source ============================================================ + // + // union TransactionEnvelope switch (EnvelopeType type) + // { + // case ENVELOPE_TYPE_TX_V0: + // TransactionV0Envelope v0; + // case ENVELOPE_TYPE_TX: + // TransactionV1Envelope v1; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransactionEnvelope feeBump; + // }; + // + // =========================================================================== + xdr.union("TransactionEnvelope", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTxV0", "v0"], ["envelopeTypeTx", "v1"], ["envelopeTypeTxFeeBump", "feeBump"]], + arms: { + v0: xdr.lookup("TransactionV0Envelope"), + v1: xdr.lookup("TransactionV1Envelope"), + feeBump: xdr.lookup("FeeBumpTransactionEnvelope") + } + }); + + // === xdr source ============================================================ + // + // union switch (EnvelopeType type) + // { + // // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // case ENVELOPE_TYPE_TX: + // Transaction tx; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransaction feeBump; + // } + // + // =========================================================================== + xdr.union("TransactionSignaturePayloadTaggedTransaction", { + switchOn: xdr.lookup("EnvelopeType"), + switchName: "type", + switches: [["envelopeTypeTx", "tx"], ["envelopeTypeTxFeeBump", "feeBump"]], + arms: { + tx: xdr.lookup("Transaction"), + feeBump: xdr.lookup("FeeBumpTransaction") + } + }); + + // === xdr source ============================================================ + // + // struct TransactionSignaturePayload + // { + // Hash networkId; + // union switch (EnvelopeType type) + // { + // // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // case ENVELOPE_TYPE_TX: + // Transaction tx; + // case ENVELOPE_TYPE_TX_FEE_BUMP: + // FeeBumpTransaction feeBump; + // } + // taggedTransaction; + // }; + // + // =========================================================================== + xdr.struct("TransactionSignaturePayload", [["networkId", xdr.lookup("Hash")], ["taggedTransaction", xdr.lookup("TransactionSignaturePayloadTaggedTransaction")]]); + + // === xdr source ============================================================ + // + // enum ClaimAtomType + // { + // CLAIM_ATOM_TYPE_V0 = 0, + // CLAIM_ATOM_TYPE_ORDER_BOOK = 1, + // CLAIM_ATOM_TYPE_LIQUIDITY_POOL = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimAtomType", { + claimAtomTypeV0: 0, + claimAtomTypeOrderBook: 1, + claimAtomTypeLiquidityPool: 2 + }); + + // === xdr source ============================================================ + // + // struct ClaimOfferAtomV0 + // { + // // emitted to identify the offer + // uint256 sellerEd25519; // Account that owns the offer + // int64 offerID; + // + // // amount and asset taken from the owner + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the owner + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimOfferAtomV0", [["sellerEd25519", xdr.lookup("Uint256")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClaimOfferAtom + // { + // // emitted to identify the offer + // AccountID sellerID; // Account that owns the offer + // int64 offerID; + // + // // amount and asset taken from the owner + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the owner + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimOfferAtom", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ClaimLiquidityAtom + // { + // PoolID liquidityPoolID; + // + // // amount and asset taken from the pool + // Asset assetSold; + // int64 amountSold; + // + // // amount and asset sent to the pool + // Asset assetBought; + // int64 amountBought; + // }; + // + // =========================================================================== + xdr.struct("ClaimLiquidityAtom", [["liquidityPoolId", xdr.lookup("PoolId")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union ClaimAtom switch (ClaimAtomType type) + // { + // case CLAIM_ATOM_TYPE_V0: + // ClaimOfferAtomV0 v0; + // case CLAIM_ATOM_TYPE_ORDER_BOOK: + // ClaimOfferAtom orderBook; + // case CLAIM_ATOM_TYPE_LIQUIDITY_POOL: + // ClaimLiquidityAtom liquidityPool; + // }; + // + // =========================================================================== + xdr.union("ClaimAtom", { + switchOn: xdr.lookup("ClaimAtomType"), + switchName: "type", + switches: [["claimAtomTypeV0", "v0"], ["claimAtomTypeOrderBook", "orderBook"], ["claimAtomTypeLiquidityPool", "liquidityPool"]], + arms: { + v0: xdr.lookup("ClaimOfferAtomV0"), + orderBook: xdr.lookup("ClaimOfferAtom"), + liquidityPool: xdr.lookup("ClaimLiquidityAtom") + } + }); + + // === xdr source ============================================================ + // + // enum CreateAccountResultCode + // { + // // codes considered as "success" for the operation + // CREATE_ACCOUNT_SUCCESS = 0, // account was created + // + // // codes considered as "failure" for the operation + // CREATE_ACCOUNT_MALFORMED = -1, // invalid destination + // CREATE_ACCOUNT_UNDERFUNDED = -2, // not enough funds in source account + // CREATE_ACCOUNT_LOW_RESERVE = + // -3, // would create an account below the min reserve + // CREATE_ACCOUNT_ALREADY_EXIST = -4 // account already exists + // }; + // + // =========================================================================== + xdr["enum"]("CreateAccountResultCode", { + createAccountSuccess: 0, + createAccountMalformed: -1, + createAccountUnderfunded: -2, + createAccountLowReserve: -3, + createAccountAlreadyExist: -4 + }); + + // === xdr source ============================================================ + // + // union CreateAccountResult switch (CreateAccountResultCode code) + // { + // case CREATE_ACCOUNT_SUCCESS: + // void; + // case CREATE_ACCOUNT_MALFORMED: + // case CREATE_ACCOUNT_UNDERFUNDED: + // case CREATE_ACCOUNT_LOW_RESERVE: + // case CREATE_ACCOUNT_ALREADY_EXIST: + // void; + // }; + // + // =========================================================================== + xdr.union("CreateAccountResult", { + switchOn: xdr.lookup("CreateAccountResultCode"), + switchName: "code", + switches: [["createAccountSuccess", xdr["void"]()], ["createAccountMalformed", xdr["void"]()], ["createAccountUnderfunded", xdr["void"]()], ["createAccountLowReserve", xdr["void"]()], ["createAccountAlreadyExist", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum PaymentResultCode + // { + // // codes considered as "success" for the operation + // PAYMENT_SUCCESS = 0, // payment successfully completed + // + // // codes considered as "failure" for the operation + // PAYMENT_MALFORMED = -1, // bad input + // PAYMENT_UNDERFUNDED = -2, // not enough funds in source account + // PAYMENT_SRC_NO_TRUST = -3, // no trust line on source account + // PAYMENT_SRC_NOT_AUTHORIZED = -4, // source not authorized to transfer + // PAYMENT_NO_DESTINATION = -5, // destination account does not exist + // PAYMENT_NO_TRUST = -6, // destination missing a trust line for asset + // PAYMENT_NOT_AUTHORIZED = -7, // destination not authorized to hold asset + // PAYMENT_LINE_FULL = -8, // destination would go above their limit + // PAYMENT_NO_ISSUER = -9 // missing issuer on asset + // }; + // + // =========================================================================== + xdr["enum"]("PaymentResultCode", { + paymentSuccess: 0, + paymentMalformed: -1, + paymentUnderfunded: -2, + paymentSrcNoTrust: -3, + paymentSrcNotAuthorized: -4, + paymentNoDestination: -5, + paymentNoTrust: -6, + paymentNotAuthorized: -7, + paymentLineFull: -8, + paymentNoIssuer: -9 + }); + + // === xdr source ============================================================ + // + // union PaymentResult switch (PaymentResultCode code) + // { + // case PAYMENT_SUCCESS: + // void; + // case PAYMENT_MALFORMED: + // case PAYMENT_UNDERFUNDED: + // case PAYMENT_SRC_NO_TRUST: + // case PAYMENT_SRC_NOT_AUTHORIZED: + // case PAYMENT_NO_DESTINATION: + // case PAYMENT_NO_TRUST: + // case PAYMENT_NOT_AUTHORIZED: + // case PAYMENT_LINE_FULL: + // case PAYMENT_NO_ISSUER: + // void; + // }; + // + // =========================================================================== + xdr.union("PaymentResult", { + switchOn: xdr.lookup("PaymentResultCode"), + switchName: "code", + switches: [["paymentSuccess", xdr["void"]()], ["paymentMalformed", xdr["void"]()], ["paymentUnderfunded", xdr["void"]()], ["paymentSrcNoTrust", xdr["void"]()], ["paymentSrcNotAuthorized", xdr["void"]()], ["paymentNoDestination", xdr["void"]()], ["paymentNoTrust", xdr["void"]()], ["paymentNotAuthorized", xdr["void"]()], ["paymentLineFull", xdr["void"]()], ["paymentNoIssuer", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum PathPaymentStrictReceiveResultCode + // { + // // codes considered as "success" for the operation + // PATH_PAYMENT_STRICT_RECEIVE_SUCCESS = 0, // success + // + // // codes considered as "failure" for the operation + // PATH_PAYMENT_STRICT_RECEIVE_MALFORMED = -1, // bad input + // PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED = + // -2, // not enough funds in source account + // PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST = + // -3, // no trust line on source account + // PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED = + // -4, // source not authorized to transfer + // PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION = + // -5, // destination account does not exist + // PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST = + // -6, // dest missing a trust line for asset + // PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED = + // -7, // dest not authorized to hold asset + // PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL = + // -8, // dest would go above their limit + // PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER = -9, // missing issuer on one asset + // PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS = + // -10, // not enough offers to satisfy path + // PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF = + // -11, // would cross one of its own offers + // PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX = -12 // could not satisfy sendmax + // }; + // + // =========================================================================== + xdr["enum"]("PathPaymentStrictReceiveResultCode", { + pathPaymentStrictReceiveSuccess: 0, + pathPaymentStrictReceiveMalformed: -1, + pathPaymentStrictReceiveUnderfunded: -2, + pathPaymentStrictReceiveSrcNoTrust: -3, + pathPaymentStrictReceiveSrcNotAuthorized: -4, + pathPaymentStrictReceiveNoDestination: -5, + pathPaymentStrictReceiveNoTrust: -6, + pathPaymentStrictReceiveNotAuthorized: -7, + pathPaymentStrictReceiveLineFull: -8, + pathPaymentStrictReceiveNoIssuer: -9, + pathPaymentStrictReceiveTooFewOffers: -10, + pathPaymentStrictReceiveOfferCrossSelf: -11, + pathPaymentStrictReceiveOverSendmax: -12 + }); + + // === xdr source ============================================================ + // + // struct SimplePaymentResult + // { + // AccountID destination; + // Asset asset; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("SimplePaymentResult", [["destination", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } + // + // =========================================================================== + xdr.struct("PathPaymentStrictReceiveResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]); + + // === xdr source ============================================================ + // + // union PathPaymentStrictReceiveResult switch ( + // PathPaymentStrictReceiveResultCode code) + // { + // case PATH_PAYMENT_STRICT_RECEIVE_SUCCESS: + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } success; + // case PATH_PAYMENT_STRICT_RECEIVE_MALFORMED: + // case PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED: + // case PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST: + // case PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION: + // case PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST: + // case PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL: + // void; + // case PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER: + // Asset noIssuer; // the asset that caused the error + // case PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS: + // case PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF: + // case PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX: + // void; + // }; + // + // =========================================================================== + xdr.union("PathPaymentStrictReceiveResult", { + switchOn: xdr.lookup("PathPaymentStrictReceiveResultCode"), + switchName: "code", + switches: [["pathPaymentStrictReceiveSuccess", "success"], ["pathPaymentStrictReceiveMalformed", xdr["void"]()], ["pathPaymentStrictReceiveUnderfunded", xdr["void"]()], ["pathPaymentStrictReceiveSrcNoTrust", xdr["void"]()], ["pathPaymentStrictReceiveSrcNotAuthorized", xdr["void"]()], ["pathPaymentStrictReceiveNoDestination", xdr["void"]()], ["pathPaymentStrictReceiveNoTrust", xdr["void"]()], ["pathPaymentStrictReceiveNotAuthorized", xdr["void"]()], ["pathPaymentStrictReceiveLineFull", xdr["void"]()], ["pathPaymentStrictReceiveNoIssuer", "noIssuer"], ["pathPaymentStrictReceiveTooFewOffers", xdr["void"]()], ["pathPaymentStrictReceiveOfferCrossSelf", xdr["void"]()], ["pathPaymentStrictReceiveOverSendmax", xdr["void"]()]], + arms: { + success: xdr.lookup("PathPaymentStrictReceiveResultSuccess"), + noIssuer: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // enum PathPaymentStrictSendResultCode + // { + // // codes considered as "success" for the operation + // PATH_PAYMENT_STRICT_SEND_SUCCESS = 0, // success + // + // // codes considered as "failure" for the operation + // PATH_PAYMENT_STRICT_SEND_MALFORMED = -1, // bad input + // PATH_PAYMENT_STRICT_SEND_UNDERFUNDED = + // -2, // not enough funds in source account + // PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST = + // -3, // no trust line on source account + // PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED = + // -4, // source not authorized to transfer + // PATH_PAYMENT_STRICT_SEND_NO_DESTINATION = + // -5, // destination account does not exist + // PATH_PAYMENT_STRICT_SEND_NO_TRUST = + // -6, // dest missing a trust line for asset + // PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED = + // -7, // dest not authorized to hold asset + // PATH_PAYMENT_STRICT_SEND_LINE_FULL = -8, // dest would go above their limit + // PATH_PAYMENT_STRICT_SEND_NO_ISSUER = -9, // missing issuer on one asset + // PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS = + // -10, // not enough offers to satisfy path + // PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF = + // -11, // would cross one of its own offers + // PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN = -12 // could not satisfy destMin + // }; + // + // =========================================================================== + xdr["enum"]("PathPaymentStrictSendResultCode", { + pathPaymentStrictSendSuccess: 0, + pathPaymentStrictSendMalformed: -1, + pathPaymentStrictSendUnderfunded: -2, + pathPaymentStrictSendSrcNoTrust: -3, + pathPaymentStrictSendSrcNotAuthorized: -4, + pathPaymentStrictSendNoDestination: -5, + pathPaymentStrictSendNoTrust: -6, + pathPaymentStrictSendNotAuthorized: -7, + pathPaymentStrictSendLineFull: -8, + pathPaymentStrictSendNoIssuer: -9, + pathPaymentStrictSendTooFewOffers: -10, + pathPaymentStrictSendOfferCrossSelf: -11, + pathPaymentStrictSendUnderDestmin: -12 + }); + + // === xdr source ============================================================ + // + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } + // + // =========================================================================== + xdr.struct("PathPaymentStrictSendResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]); + + // === xdr source ============================================================ + // + // union PathPaymentStrictSendResult switch (PathPaymentStrictSendResultCode code) + // { + // case PATH_PAYMENT_STRICT_SEND_SUCCESS: + // struct + // { + // ClaimAtom offers<>; + // SimplePaymentResult last; + // } success; + // case PATH_PAYMENT_STRICT_SEND_MALFORMED: + // case PATH_PAYMENT_STRICT_SEND_UNDERFUNDED: + // case PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST: + // case PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_SEND_NO_DESTINATION: + // case PATH_PAYMENT_STRICT_SEND_NO_TRUST: + // case PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED: + // case PATH_PAYMENT_STRICT_SEND_LINE_FULL: + // void; + // case PATH_PAYMENT_STRICT_SEND_NO_ISSUER: + // Asset noIssuer; // the asset that caused the error + // case PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS: + // case PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF: + // case PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN: + // void; + // }; + // + // =========================================================================== + xdr.union("PathPaymentStrictSendResult", { + switchOn: xdr.lookup("PathPaymentStrictSendResultCode"), + switchName: "code", + switches: [["pathPaymentStrictSendSuccess", "success"], ["pathPaymentStrictSendMalformed", xdr["void"]()], ["pathPaymentStrictSendUnderfunded", xdr["void"]()], ["pathPaymentStrictSendSrcNoTrust", xdr["void"]()], ["pathPaymentStrictSendSrcNotAuthorized", xdr["void"]()], ["pathPaymentStrictSendNoDestination", xdr["void"]()], ["pathPaymentStrictSendNoTrust", xdr["void"]()], ["pathPaymentStrictSendNotAuthorized", xdr["void"]()], ["pathPaymentStrictSendLineFull", xdr["void"]()], ["pathPaymentStrictSendNoIssuer", "noIssuer"], ["pathPaymentStrictSendTooFewOffers", xdr["void"]()], ["pathPaymentStrictSendOfferCrossSelf", xdr["void"]()], ["pathPaymentStrictSendUnderDestmin", xdr["void"]()]], + arms: { + success: xdr.lookup("PathPaymentStrictSendResultSuccess"), + noIssuer: xdr.lookup("Asset") + } + }); + + // === xdr source ============================================================ + // + // enum ManageSellOfferResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_SELL_OFFER_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // MANAGE_SELL_OFFER_MALFORMED = -1, // generated offer would be invalid + // MANAGE_SELL_OFFER_SELL_NO_TRUST = + // -2, // no trust line for what we're selling + // MANAGE_SELL_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying + // MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell + // MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy + // MANAGE_SELL_OFFER_LINE_FULL = -6, // can't receive more of what it's buying + // MANAGE_SELL_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell + // MANAGE_SELL_OFFER_CROSS_SELF = + // -8, // would cross an offer from the same user + // MANAGE_SELL_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling + // MANAGE_SELL_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying + // + // // update errors + // MANAGE_SELL_OFFER_NOT_FOUND = + // -11, // offerID does not match an existing offer + // + // MANAGE_SELL_OFFER_LOW_RESERVE = + // -12 // not enough funds to create a new Offer + // }; + // + // =========================================================================== + xdr["enum"]("ManageSellOfferResultCode", { + manageSellOfferSuccess: 0, + manageSellOfferMalformed: -1, + manageSellOfferSellNoTrust: -2, + manageSellOfferBuyNoTrust: -3, + manageSellOfferSellNotAuthorized: -4, + manageSellOfferBuyNotAuthorized: -5, + manageSellOfferLineFull: -6, + manageSellOfferUnderfunded: -7, + manageSellOfferCrossSelf: -8, + manageSellOfferSellNoIssuer: -9, + manageSellOfferBuyNoIssuer: -10, + manageSellOfferNotFound: -11, + manageSellOfferLowReserve: -12 + }); + + // === xdr source ============================================================ + // + // enum ManageOfferEffect + // { + // MANAGE_OFFER_CREATED = 0, + // MANAGE_OFFER_UPDATED = 1, + // MANAGE_OFFER_DELETED = 2 + // }; + // + // =========================================================================== + xdr["enum"]("ManageOfferEffect", { + manageOfferCreated: 0, + manageOfferUpdated: 1, + manageOfferDeleted: 2 + }); + + // === xdr source ============================================================ + // + // union switch (ManageOfferEffect effect) + // { + // case MANAGE_OFFER_CREATED: + // case MANAGE_OFFER_UPDATED: + // OfferEntry offer; + // case MANAGE_OFFER_DELETED: + // void; + // } + // + // =========================================================================== + xdr.union("ManageOfferSuccessResultOffer", { + switchOn: xdr.lookup("ManageOfferEffect"), + switchName: "effect", + switches: [["manageOfferCreated", "offer"], ["manageOfferUpdated", "offer"], ["manageOfferDeleted", xdr["void"]()]], + arms: { + offer: xdr.lookup("OfferEntry") + } + }); + + // === xdr source ============================================================ + // + // struct ManageOfferSuccessResult + // { + // // offers that got claimed while creating this offer + // ClaimAtom offersClaimed<>; + // + // union switch (ManageOfferEffect effect) + // { + // case MANAGE_OFFER_CREATED: + // case MANAGE_OFFER_UPDATED: + // OfferEntry offer; + // case MANAGE_OFFER_DELETED: + // void; + // } + // offer; + // }; + // + // =========================================================================== + xdr.struct("ManageOfferSuccessResult", [["offersClaimed", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["offer", xdr.lookup("ManageOfferSuccessResultOffer")]]); + + // === xdr source ============================================================ + // + // union ManageSellOfferResult switch (ManageSellOfferResultCode code) + // { + // case MANAGE_SELL_OFFER_SUCCESS: + // ManageOfferSuccessResult success; + // case MANAGE_SELL_OFFER_MALFORMED: + // case MANAGE_SELL_OFFER_SELL_NO_TRUST: + // case MANAGE_SELL_OFFER_BUY_NO_TRUST: + // case MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED: + // case MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED: + // case MANAGE_SELL_OFFER_LINE_FULL: + // case MANAGE_SELL_OFFER_UNDERFUNDED: + // case MANAGE_SELL_OFFER_CROSS_SELF: + // case MANAGE_SELL_OFFER_SELL_NO_ISSUER: + // case MANAGE_SELL_OFFER_BUY_NO_ISSUER: + // case MANAGE_SELL_OFFER_NOT_FOUND: + // case MANAGE_SELL_OFFER_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageSellOfferResult", { + switchOn: xdr.lookup("ManageSellOfferResultCode"), + switchName: "code", + switches: [["manageSellOfferSuccess", "success"], ["manageSellOfferMalformed", xdr["void"]()], ["manageSellOfferSellNoTrust", xdr["void"]()], ["manageSellOfferBuyNoTrust", xdr["void"]()], ["manageSellOfferSellNotAuthorized", xdr["void"]()], ["manageSellOfferBuyNotAuthorized", xdr["void"]()], ["manageSellOfferLineFull", xdr["void"]()], ["manageSellOfferUnderfunded", xdr["void"]()], ["manageSellOfferCrossSelf", xdr["void"]()], ["manageSellOfferSellNoIssuer", xdr["void"]()], ["manageSellOfferBuyNoIssuer", xdr["void"]()], ["manageSellOfferNotFound", xdr["void"]()], ["manageSellOfferLowReserve", xdr["void"]()]], + arms: { + success: xdr.lookup("ManageOfferSuccessResult") + } + }); + + // === xdr source ============================================================ + // + // enum ManageBuyOfferResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_BUY_OFFER_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // MANAGE_BUY_OFFER_MALFORMED = -1, // generated offer would be invalid + // MANAGE_BUY_OFFER_SELL_NO_TRUST = -2, // no trust line for what we're selling + // MANAGE_BUY_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying + // MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell + // MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy + // MANAGE_BUY_OFFER_LINE_FULL = -6, // can't receive more of what it's buying + // MANAGE_BUY_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell + // MANAGE_BUY_OFFER_CROSS_SELF = -8, // would cross an offer from the same user + // MANAGE_BUY_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling + // MANAGE_BUY_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying + // + // // update errors + // MANAGE_BUY_OFFER_NOT_FOUND = + // -11, // offerID does not match an existing offer + // + // MANAGE_BUY_OFFER_LOW_RESERVE = -12 // not enough funds to create a new Offer + // }; + // + // =========================================================================== + xdr["enum"]("ManageBuyOfferResultCode", { + manageBuyOfferSuccess: 0, + manageBuyOfferMalformed: -1, + manageBuyOfferSellNoTrust: -2, + manageBuyOfferBuyNoTrust: -3, + manageBuyOfferSellNotAuthorized: -4, + manageBuyOfferBuyNotAuthorized: -5, + manageBuyOfferLineFull: -6, + manageBuyOfferUnderfunded: -7, + manageBuyOfferCrossSelf: -8, + manageBuyOfferSellNoIssuer: -9, + manageBuyOfferBuyNoIssuer: -10, + manageBuyOfferNotFound: -11, + manageBuyOfferLowReserve: -12 + }); + + // === xdr source ============================================================ + // + // union ManageBuyOfferResult switch (ManageBuyOfferResultCode code) + // { + // case MANAGE_BUY_OFFER_SUCCESS: + // ManageOfferSuccessResult success; + // case MANAGE_BUY_OFFER_MALFORMED: + // case MANAGE_BUY_OFFER_SELL_NO_TRUST: + // case MANAGE_BUY_OFFER_BUY_NO_TRUST: + // case MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED: + // case MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED: + // case MANAGE_BUY_OFFER_LINE_FULL: + // case MANAGE_BUY_OFFER_UNDERFUNDED: + // case MANAGE_BUY_OFFER_CROSS_SELF: + // case MANAGE_BUY_OFFER_SELL_NO_ISSUER: + // case MANAGE_BUY_OFFER_BUY_NO_ISSUER: + // case MANAGE_BUY_OFFER_NOT_FOUND: + // case MANAGE_BUY_OFFER_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageBuyOfferResult", { + switchOn: xdr.lookup("ManageBuyOfferResultCode"), + switchName: "code", + switches: [["manageBuyOfferSuccess", "success"], ["manageBuyOfferMalformed", xdr["void"]()], ["manageBuyOfferSellNoTrust", xdr["void"]()], ["manageBuyOfferBuyNoTrust", xdr["void"]()], ["manageBuyOfferSellNotAuthorized", xdr["void"]()], ["manageBuyOfferBuyNotAuthorized", xdr["void"]()], ["manageBuyOfferLineFull", xdr["void"]()], ["manageBuyOfferUnderfunded", xdr["void"]()], ["manageBuyOfferCrossSelf", xdr["void"]()], ["manageBuyOfferSellNoIssuer", xdr["void"]()], ["manageBuyOfferBuyNoIssuer", xdr["void"]()], ["manageBuyOfferNotFound", xdr["void"]()], ["manageBuyOfferLowReserve", xdr["void"]()]], + arms: { + success: xdr.lookup("ManageOfferSuccessResult") + } + }); + + // === xdr source ============================================================ + // + // enum SetOptionsResultCode + // { + // // codes considered as "success" for the operation + // SET_OPTIONS_SUCCESS = 0, + // // codes considered as "failure" for the operation + // SET_OPTIONS_LOW_RESERVE = -1, // not enough funds to add a signer + // SET_OPTIONS_TOO_MANY_SIGNERS = -2, // max number of signers already reached + // SET_OPTIONS_BAD_FLAGS = -3, // invalid combination of clear/set flags + // SET_OPTIONS_INVALID_INFLATION = -4, // inflation account does not exist + // SET_OPTIONS_CANT_CHANGE = -5, // can no longer change this option + // SET_OPTIONS_UNKNOWN_FLAG = -6, // can't set an unknown flag + // SET_OPTIONS_THRESHOLD_OUT_OF_RANGE = -7, // bad value for weight/threshold + // SET_OPTIONS_BAD_SIGNER = -8, // signer cannot be masterkey + // SET_OPTIONS_INVALID_HOME_DOMAIN = -9, // malformed home domain + // SET_OPTIONS_AUTH_REVOCABLE_REQUIRED = + // -10 // auth revocable is required for clawback + // }; + // + // =========================================================================== + xdr["enum"]("SetOptionsResultCode", { + setOptionsSuccess: 0, + setOptionsLowReserve: -1, + setOptionsTooManySigners: -2, + setOptionsBadFlags: -3, + setOptionsInvalidInflation: -4, + setOptionsCantChange: -5, + setOptionsUnknownFlag: -6, + setOptionsThresholdOutOfRange: -7, + setOptionsBadSigner: -8, + setOptionsInvalidHomeDomain: -9, + setOptionsAuthRevocableRequired: -10 + }); + + // === xdr source ============================================================ + // + // union SetOptionsResult switch (SetOptionsResultCode code) + // { + // case SET_OPTIONS_SUCCESS: + // void; + // case SET_OPTIONS_LOW_RESERVE: + // case SET_OPTIONS_TOO_MANY_SIGNERS: + // case SET_OPTIONS_BAD_FLAGS: + // case SET_OPTIONS_INVALID_INFLATION: + // case SET_OPTIONS_CANT_CHANGE: + // case SET_OPTIONS_UNKNOWN_FLAG: + // case SET_OPTIONS_THRESHOLD_OUT_OF_RANGE: + // case SET_OPTIONS_BAD_SIGNER: + // case SET_OPTIONS_INVALID_HOME_DOMAIN: + // case SET_OPTIONS_AUTH_REVOCABLE_REQUIRED: + // void; + // }; + // + // =========================================================================== + xdr.union("SetOptionsResult", { + switchOn: xdr.lookup("SetOptionsResultCode"), + switchName: "code", + switches: [["setOptionsSuccess", xdr["void"]()], ["setOptionsLowReserve", xdr["void"]()], ["setOptionsTooManySigners", xdr["void"]()], ["setOptionsBadFlags", xdr["void"]()], ["setOptionsInvalidInflation", xdr["void"]()], ["setOptionsCantChange", xdr["void"]()], ["setOptionsUnknownFlag", xdr["void"]()], ["setOptionsThresholdOutOfRange", xdr["void"]()], ["setOptionsBadSigner", xdr["void"]()], ["setOptionsInvalidHomeDomain", xdr["void"]()], ["setOptionsAuthRevocableRequired", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ChangeTrustResultCode + // { + // // codes considered as "success" for the operation + // CHANGE_TRUST_SUCCESS = 0, + // // codes considered as "failure" for the operation + // CHANGE_TRUST_MALFORMED = -1, // bad input + // CHANGE_TRUST_NO_ISSUER = -2, // could not find issuer + // CHANGE_TRUST_INVALID_LIMIT = -3, // cannot drop limit below balance + // // cannot create with a limit of 0 + // CHANGE_TRUST_LOW_RESERVE = + // -4, // not enough funds to create a new trust line, + // CHANGE_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed + // CHANGE_TRUST_TRUST_LINE_MISSING = -6, // Asset trustline is missing for pool + // CHANGE_TRUST_CANNOT_DELETE = + // -7, // Asset trustline is still referenced in a pool + // CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES = + // -8 // Asset trustline is deauthorized + // }; + // + // =========================================================================== + xdr["enum"]("ChangeTrustResultCode", { + changeTrustSuccess: 0, + changeTrustMalformed: -1, + changeTrustNoIssuer: -2, + changeTrustInvalidLimit: -3, + changeTrustLowReserve: -4, + changeTrustSelfNotAllowed: -5, + changeTrustTrustLineMissing: -6, + changeTrustCannotDelete: -7, + changeTrustNotAuthMaintainLiabilities: -8 + }); + + // === xdr source ============================================================ + // + // union ChangeTrustResult switch (ChangeTrustResultCode code) + // { + // case CHANGE_TRUST_SUCCESS: + // void; + // case CHANGE_TRUST_MALFORMED: + // case CHANGE_TRUST_NO_ISSUER: + // case CHANGE_TRUST_INVALID_LIMIT: + // case CHANGE_TRUST_LOW_RESERVE: + // case CHANGE_TRUST_SELF_NOT_ALLOWED: + // case CHANGE_TRUST_TRUST_LINE_MISSING: + // case CHANGE_TRUST_CANNOT_DELETE: + // case CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES: + // void; + // }; + // + // =========================================================================== + xdr.union("ChangeTrustResult", { + switchOn: xdr.lookup("ChangeTrustResultCode"), + switchName: "code", + switches: [["changeTrustSuccess", xdr["void"]()], ["changeTrustMalformed", xdr["void"]()], ["changeTrustNoIssuer", xdr["void"]()], ["changeTrustInvalidLimit", xdr["void"]()], ["changeTrustLowReserve", xdr["void"]()], ["changeTrustSelfNotAllowed", xdr["void"]()], ["changeTrustTrustLineMissing", xdr["void"]()], ["changeTrustCannotDelete", xdr["void"]()], ["changeTrustNotAuthMaintainLiabilities", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum AllowTrustResultCode + // { + // // codes considered as "success" for the operation + // ALLOW_TRUST_SUCCESS = 0, + // // codes considered as "failure" for the operation + // ALLOW_TRUST_MALFORMED = -1, // asset is not ASSET_TYPE_ALPHANUM + // ALLOW_TRUST_NO_TRUST_LINE = -2, // trustor does not have a trustline + // // source account does not require trust + // ALLOW_TRUST_TRUST_NOT_REQUIRED = -3, + // ALLOW_TRUST_CANT_REVOKE = -4, // source account can't revoke trust, + // ALLOW_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed + // ALLOW_TRUST_LOW_RESERVE = -6 // claimable balances can't be created + // // on revoke due to low reserves + // }; + // + // =========================================================================== + xdr["enum"]("AllowTrustResultCode", { + allowTrustSuccess: 0, + allowTrustMalformed: -1, + allowTrustNoTrustLine: -2, + allowTrustTrustNotRequired: -3, + allowTrustCantRevoke: -4, + allowTrustSelfNotAllowed: -5, + allowTrustLowReserve: -6 + }); + + // === xdr source ============================================================ + // + // union AllowTrustResult switch (AllowTrustResultCode code) + // { + // case ALLOW_TRUST_SUCCESS: + // void; + // case ALLOW_TRUST_MALFORMED: + // case ALLOW_TRUST_NO_TRUST_LINE: + // case ALLOW_TRUST_TRUST_NOT_REQUIRED: + // case ALLOW_TRUST_CANT_REVOKE: + // case ALLOW_TRUST_SELF_NOT_ALLOWED: + // case ALLOW_TRUST_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("AllowTrustResult", { + switchOn: xdr.lookup("AllowTrustResultCode"), + switchName: "code", + switches: [["allowTrustSuccess", xdr["void"]()], ["allowTrustMalformed", xdr["void"]()], ["allowTrustNoTrustLine", xdr["void"]()], ["allowTrustTrustNotRequired", xdr["void"]()], ["allowTrustCantRevoke", xdr["void"]()], ["allowTrustSelfNotAllowed", xdr["void"]()], ["allowTrustLowReserve", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum AccountMergeResultCode + // { + // // codes considered as "success" for the operation + // ACCOUNT_MERGE_SUCCESS = 0, + // // codes considered as "failure" for the operation + // ACCOUNT_MERGE_MALFORMED = -1, // can't merge onto itself + // ACCOUNT_MERGE_NO_ACCOUNT = -2, // destination does not exist + // ACCOUNT_MERGE_IMMUTABLE_SET = -3, // source account has AUTH_IMMUTABLE set + // ACCOUNT_MERGE_HAS_SUB_ENTRIES = -4, // account has trust lines/offers + // ACCOUNT_MERGE_SEQNUM_TOO_FAR = -5, // sequence number is over max allowed + // ACCOUNT_MERGE_DEST_FULL = -6, // can't add source balance to + // // destination balance + // ACCOUNT_MERGE_IS_SPONSOR = -7 // can't merge account that is a sponsor + // }; + // + // =========================================================================== + xdr["enum"]("AccountMergeResultCode", { + accountMergeSuccess: 0, + accountMergeMalformed: -1, + accountMergeNoAccount: -2, + accountMergeImmutableSet: -3, + accountMergeHasSubEntries: -4, + accountMergeSeqnumTooFar: -5, + accountMergeDestFull: -6, + accountMergeIsSponsor: -7 + }); + + // === xdr source ============================================================ + // + // union AccountMergeResult switch (AccountMergeResultCode code) + // { + // case ACCOUNT_MERGE_SUCCESS: + // int64 sourceAccountBalance; // how much got transferred from source account + // case ACCOUNT_MERGE_MALFORMED: + // case ACCOUNT_MERGE_NO_ACCOUNT: + // case ACCOUNT_MERGE_IMMUTABLE_SET: + // case ACCOUNT_MERGE_HAS_SUB_ENTRIES: + // case ACCOUNT_MERGE_SEQNUM_TOO_FAR: + // case ACCOUNT_MERGE_DEST_FULL: + // case ACCOUNT_MERGE_IS_SPONSOR: + // void; + // }; + // + // =========================================================================== + xdr.union("AccountMergeResult", { + switchOn: xdr.lookup("AccountMergeResultCode"), + switchName: "code", + switches: [["accountMergeSuccess", "sourceAccountBalance"], ["accountMergeMalformed", xdr["void"]()], ["accountMergeNoAccount", xdr["void"]()], ["accountMergeImmutableSet", xdr["void"]()], ["accountMergeHasSubEntries", xdr["void"]()], ["accountMergeSeqnumTooFar", xdr["void"]()], ["accountMergeDestFull", xdr["void"]()], ["accountMergeIsSponsor", xdr["void"]()]], + arms: { + sourceAccountBalance: xdr.lookup("Int64") + } + }); + + // === xdr source ============================================================ + // + // enum InflationResultCode + // { + // // codes considered as "success" for the operation + // INFLATION_SUCCESS = 0, + // // codes considered as "failure" for the operation + // INFLATION_NOT_TIME = -1 + // }; + // + // =========================================================================== + xdr["enum"]("InflationResultCode", { + inflationSuccess: 0, + inflationNotTime: -1 + }); + + // === xdr source ============================================================ + // + // struct InflationPayout // or use PaymentResultAtom to limit types? + // { + // AccountID destination; + // int64 amount; + // }; + // + // =========================================================================== + xdr.struct("InflationPayout", [["destination", xdr.lookup("AccountId")], ["amount", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // union InflationResult switch (InflationResultCode code) + // { + // case INFLATION_SUCCESS: + // InflationPayout payouts<>; + // case INFLATION_NOT_TIME: + // void; + // }; + // + // =========================================================================== + xdr.union("InflationResult", { + switchOn: xdr.lookup("InflationResultCode"), + switchName: "code", + switches: [["inflationSuccess", "payouts"], ["inflationNotTime", xdr["void"]()]], + arms: { + payouts: xdr.varArray(xdr.lookup("InflationPayout"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // enum ManageDataResultCode + // { + // // codes considered as "success" for the operation + // MANAGE_DATA_SUCCESS = 0, + // // codes considered as "failure" for the operation + // MANAGE_DATA_NOT_SUPPORTED_YET = + // -1, // The network hasn't moved to this protocol change yet + // MANAGE_DATA_NAME_NOT_FOUND = + // -2, // Trying to remove a Data Entry that isn't there + // MANAGE_DATA_LOW_RESERVE = -3, // not enough funds to create a new Data Entry + // MANAGE_DATA_INVALID_NAME = -4 // Name not a valid string + // }; + // + // =========================================================================== + xdr["enum"]("ManageDataResultCode", { + manageDataSuccess: 0, + manageDataNotSupportedYet: -1, + manageDataNameNotFound: -2, + manageDataLowReserve: -3, + manageDataInvalidName: -4 + }); + + // === xdr source ============================================================ + // + // union ManageDataResult switch (ManageDataResultCode code) + // { + // case MANAGE_DATA_SUCCESS: + // void; + // case MANAGE_DATA_NOT_SUPPORTED_YET: + // case MANAGE_DATA_NAME_NOT_FOUND: + // case MANAGE_DATA_LOW_RESERVE: + // case MANAGE_DATA_INVALID_NAME: + // void; + // }; + // + // =========================================================================== + xdr.union("ManageDataResult", { + switchOn: xdr.lookup("ManageDataResultCode"), + switchName: "code", + switches: [["manageDataSuccess", xdr["void"]()], ["manageDataNotSupportedYet", xdr["void"]()], ["manageDataNameNotFound", xdr["void"]()], ["manageDataLowReserve", xdr["void"]()], ["manageDataInvalidName", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum BumpSequenceResultCode + // { + // // codes considered as "success" for the operation + // BUMP_SEQUENCE_SUCCESS = 0, + // // codes considered as "failure" for the operation + // BUMP_SEQUENCE_BAD_SEQ = -1 // `bumpTo` is not within bounds + // }; + // + // =========================================================================== + xdr["enum"]("BumpSequenceResultCode", { + bumpSequenceSuccess: 0, + bumpSequenceBadSeq: -1 + }); + + // === xdr source ============================================================ + // + // union BumpSequenceResult switch (BumpSequenceResultCode code) + // { + // case BUMP_SEQUENCE_SUCCESS: + // void; + // case BUMP_SEQUENCE_BAD_SEQ: + // void; + // }; + // + // =========================================================================== + xdr.union("BumpSequenceResult", { + switchOn: xdr.lookup("BumpSequenceResultCode"), + switchName: "code", + switches: [["bumpSequenceSuccess", xdr["void"]()], ["bumpSequenceBadSeq", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum CreateClaimableBalanceResultCode + // { + // CREATE_CLAIMABLE_BALANCE_SUCCESS = 0, + // CREATE_CLAIMABLE_BALANCE_MALFORMED = -1, + // CREATE_CLAIMABLE_BALANCE_LOW_RESERVE = -2, + // CREATE_CLAIMABLE_BALANCE_NO_TRUST = -3, + // CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -4, + // CREATE_CLAIMABLE_BALANCE_UNDERFUNDED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("CreateClaimableBalanceResultCode", { + createClaimableBalanceSuccess: 0, + createClaimableBalanceMalformed: -1, + createClaimableBalanceLowReserve: -2, + createClaimableBalanceNoTrust: -3, + createClaimableBalanceNotAuthorized: -4, + createClaimableBalanceUnderfunded: -5 + }); + + // === xdr source ============================================================ + // + // union CreateClaimableBalanceResult switch ( + // CreateClaimableBalanceResultCode code) + // { + // case CREATE_CLAIMABLE_BALANCE_SUCCESS: + // ClaimableBalanceID balanceID; + // case CREATE_CLAIMABLE_BALANCE_MALFORMED: + // case CREATE_CLAIMABLE_BALANCE_LOW_RESERVE: + // case CREATE_CLAIMABLE_BALANCE_NO_TRUST: + // case CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED: + // case CREATE_CLAIMABLE_BALANCE_UNDERFUNDED: + // void; + // }; + // + // =========================================================================== + xdr.union("CreateClaimableBalanceResult", { + switchOn: xdr.lookup("CreateClaimableBalanceResultCode"), + switchName: "code", + switches: [["createClaimableBalanceSuccess", "balanceId"], ["createClaimableBalanceMalformed", xdr["void"]()], ["createClaimableBalanceLowReserve", xdr["void"]()], ["createClaimableBalanceNoTrust", xdr["void"]()], ["createClaimableBalanceNotAuthorized", xdr["void"]()], ["createClaimableBalanceUnderfunded", xdr["void"]()]], + arms: { + balanceId: xdr.lookup("ClaimableBalanceId") + } + }); + + // === xdr source ============================================================ + // + // enum ClaimClaimableBalanceResultCode + // { + // CLAIM_CLAIMABLE_BALANCE_SUCCESS = 0, + // CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1, + // CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM = -2, + // CLAIM_CLAIMABLE_BALANCE_LINE_FULL = -3, + // CLAIM_CLAIMABLE_BALANCE_NO_TRUST = -4, + // CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("ClaimClaimableBalanceResultCode", { + claimClaimableBalanceSuccess: 0, + claimClaimableBalanceDoesNotExist: -1, + claimClaimableBalanceCannotClaim: -2, + claimClaimableBalanceLineFull: -3, + claimClaimableBalanceNoTrust: -4, + claimClaimableBalanceNotAuthorized: -5 + }); + + // === xdr source ============================================================ + // + // union ClaimClaimableBalanceResult switch (ClaimClaimableBalanceResultCode code) + // { + // case CLAIM_CLAIMABLE_BALANCE_SUCCESS: + // void; + // case CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST: + // case CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM: + // case CLAIM_CLAIMABLE_BALANCE_LINE_FULL: + // case CLAIM_CLAIMABLE_BALANCE_NO_TRUST: + // case CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClaimClaimableBalanceResult", { + switchOn: xdr.lookup("ClaimClaimableBalanceResultCode"), + switchName: "code", + switches: [["claimClaimableBalanceSuccess", xdr["void"]()], ["claimClaimableBalanceDoesNotExist", xdr["void"]()], ["claimClaimableBalanceCannotClaim", xdr["void"]()], ["claimClaimableBalanceLineFull", xdr["void"]()], ["claimClaimableBalanceNoTrust", xdr["void"]()], ["claimClaimableBalanceNotAuthorized", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum BeginSponsoringFutureReservesResultCode + // { + // // codes considered as "success" for the operation + // BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED = -1, + // BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED = -2, + // BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("BeginSponsoringFutureReservesResultCode", { + beginSponsoringFutureReservesSuccess: 0, + beginSponsoringFutureReservesMalformed: -1, + beginSponsoringFutureReservesAlreadySponsored: -2, + beginSponsoringFutureReservesRecursive: -3 + }); + + // === xdr source ============================================================ + // + // union BeginSponsoringFutureReservesResult switch ( + // BeginSponsoringFutureReservesResultCode code) + // { + // case BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS: + // void; + // case BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED: + // case BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED: + // case BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE: + // void; + // }; + // + // =========================================================================== + xdr.union("BeginSponsoringFutureReservesResult", { + switchOn: xdr.lookup("BeginSponsoringFutureReservesResultCode"), + switchName: "code", + switches: [["beginSponsoringFutureReservesSuccess", xdr["void"]()], ["beginSponsoringFutureReservesMalformed", xdr["void"]()], ["beginSponsoringFutureReservesAlreadySponsored", xdr["void"]()], ["beginSponsoringFutureReservesRecursive", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum EndSponsoringFutureReservesResultCode + // { + // // codes considered as "success" for the operation + // END_SPONSORING_FUTURE_RESERVES_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED = -1 + // }; + // + // =========================================================================== + xdr["enum"]("EndSponsoringFutureReservesResultCode", { + endSponsoringFutureReservesSuccess: 0, + endSponsoringFutureReservesNotSponsored: -1 + }); + + // === xdr source ============================================================ + // + // union EndSponsoringFutureReservesResult switch ( + // EndSponsoringFutureReservesResultCode code) + // { + // case END_SPONSORING_FUTURE_RESERVES_SUCCESS: + // void; + // case END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED: + // void; + // }; + // + // =========================================================================== + xdr.union("EndSponsoringFutureReservesResult", { + switchOn: xdr.lookup("EndSponsoringFutureReservesResultCode"), + switchName: "code", + switches: [["endSponsoringFutureReservesSuccess", xdr["void"]()], ["endSponsoringFutureReservesNotSponsored", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum RevokeSponsorshipResultCode + // { + // // codes considered as "success" for the operation + // REVOKE_SPONSORSHIP_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // REVOKE_SPONSORSHIP_DOES_NOT_EXIST = -1, + // REVOKE_SPONSORSHIP_NOT_SPONSOR = -2, + // REVOKE_SPONSORSHIP_LOW_RESERVE = -3, + // REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE = -4, + // REVOKE_SPONSORSHIP_MALFORMED = -5 + // }; + // + // =========================================================================== + xdr["enum"]("RevokeSponsorshipResultCode", { + revokeSponsorshipSuccess: 0, + revokeSponsorshipDoesNotExist: -1, + revokeSponsorshipNotSponsor: -2, + revokeSponsorshipLowReserve: -3, + revokeSponsorshipOnlyTransferable: -4, + revokeSponsorshipMalformed: -5 + }); + + // === xdr source ============================================================ + // + // union RevokeSponsorshipResult switch (RevokeSponsorshipResultCode code) + // { + // case REVOKE_SPONSORSHIP_SUCCESS: + // void; + // case REVOKE_SPONSORSHIP_DOES_NOT_EXIST: + // case REVOKE_SPONSORSHIP_NOT_SPONSOR: + // case REVOKE_SPONSORSHIP_LOW_RESERVE: + // case REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE: + // case REVOKE_SPONSORSHIP_MALFORMED: + // void; + // }; + // + // =========================================================================== + xdr.union("RevokeSponsorshipResult", { + switchOn: xdr.lookup("RevokeSponsorshipResultCode"), + switchName: "code", + switches: [["revokeSponsorshipSuccess", xdr["void"]()], ["revokeSponsorshipDoesNotExist", xdr["void"]()], ["revokeSponsorshipNotSponsor", xdr["void"]()], ["revokeSponsorshipLowReserve", xdr["void"]()], ["revokeSponsorshipOnlyTransferable", xdr["void"]()], ["revokeSponsorshipMalformed", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ClawbackResultCode + // { + // // codes considered as "success" for the operation + // CLAWBACK_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // CLAWBACK_MALFORMED = -1, + // CLAWBACK_NOT_CLAWBACK_ENABLED = -2, + // CLAWBACK_NO_TRUST = -3, + // CLAWBACK_UNDERFUNDED = -4 + // }; + // + // =========================================================================== + xdr["enum"]("ClawbackResultCode", { + clawbackSuccess: 0, + clawbackMalformed: -1, + clawbackNotClawbackEnabled: -2, + clawbackNoTrust: -3, + clawbackUnderfunded: -4 + }); + + // === xdr source ============================================================ + // + // union ClawbackResult switch (ClawbackResultCode code) + // { + // case CLAWBACK_SUCCESS: + // void; + // case CLAWBACK_MALFORMED: + // case CLAWBACK_NOT_CLAWBACK_ENABLED: + // case CLAWBACK_NO_TRUST: + // case CLAWBACK_UNDERFUNDED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClawbackResult", { + switchOn: xdr.lookup("ClawbackResultCode"), + switchName: "code", + switches: [["clawbackSuccess", xdr["void"]()], ["clawbackMalformed", xdr["void"]()], ["clawbackNotClawbackEnabled", xdr["void"]()], ["clawbackNoTrust", xdr["void"]()], ["clawbackUnderfunded", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum ClawbackClaimableBalanceResultCode + // { + // // codes considered as "success" for the operation + // CLAWBACK_CLAIMABLE_BALANCE_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1, + // CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER = -2, + // CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED = -3 + // }; + // + // =========================================================================== + xdr["enum"]("ClawbackClaimableBalanceResultCode", { + clawbackClaimableBalanceSuccess: 0, + clawbackClaimableBalanceDoesNotExist: -1, + clawbackClaimableBalanceNotIssuer: -2, + clawbackClaimableBalanceNotClawbackEnabled: -3 + }); + + // === xdr source ============================================================ + // + // union ClawbackClaimableBalanceResult switch ( + // ClawbackClaimableBalanceResultCode code) + // { + // case CLAWBACK_CLAIMABLE_BALANCE_SUCCESS: + // void; + // case CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST: + // case CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER: + // case CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED: + // void; + // }; + // + // =========================================================================== + xdr.union("ClawbackClaimableBalanceResult", { + switchOn: xdr.lookup("ClawbackClaimableBalanceResultCode"), + switchName: "code", + switches: [["clawbackClaimableBalanceSuccess", xdr["void"]()], ["clawbackClaimableBalanceDoesNotExist", xdr["void"]()], ["clawbackClaimableBalanceNotIssuer", xdr["void"]()], ["clawbackClaimableBalanceNotClawbackEnabled", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum SetTrustLineFlagsResultCode + // { + // // codes considered as "success" for the operation + // SET_TRUST_LINE_FLAGS_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // SET_TRUST_LINE_FLAGS_MALFORMED = -1, + // SET_TRUST_LINE_FLAGS_NO_TRUST_LINE = -2, + // SET_TRUST_LINE_FLAGS_CANT_REVOKE = -3, + // SET_TRUST_LINE_FLAGS_INVALID_STATE = -4, + // SET_TRUST_LINE_FLAGS_LOW_RESERVE = -5 // claimable balances can't be created + // // on revoke due to low reserves + // }; + // + // =========================================================================== + xdr["enum"]("SetTrustLineFlagsResultCode", { + setTrustLineFlagsSuccess: 0, + setTrustLineFlagsMalformed: -1, + setTrustLineFlagsNoTrustLine: -2, + setTrustLineFlagsCantRevoke: -3, + setTrustLineFlagsInvalidState: -4, + setTrustLineFlagsLowReserve: -5 + }); + + // === xdr source ============================================================ + // + // union SetTrustLineFlagsResult switch (SetTrustLineFlagsResultCode code) + // { + // case SET_TRUST_LINE_FLAGS_SUCCESS: + // void; + // case SET_TRUST_LINE_FLAGS_MALFORMED: + // case SET_TRUST_LINE_FLAGS_NO_TRUST_LINE: + // case SET_TRUST_LINE_FLAGS_CANT_REVOKE: + // case SET_TRUST_LINE_FLAGS_INVALID_STATE: + // case SET_TRUST_LINE_FLAGS_LOW_RESERVE: + // void; + // }; + // + // =========================================================================== + xdr.union("SetTrustLineFlagsResult", { + switchOn: xdr.lookup("SetTrustLineFlagsResultCode"), + switchName: "code", + switches: [["setTrustLineFlagsSuccess", xdr["void"]()], ["setTrustLineFlagsMalformed", xdr["void"]()], ["setTrustLineFlagsNoTrustLine", xdr["void"]()], ["setTrustLineFlagsCantRevoke", xdr["void"]()], ["setTrustLineFlagsInvalidState", xdr["void"]()], ["setTrustLineFlagsLowReserve", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum LiquidityPoolDepositResultCode + // { + // // codes considered as "success" for the operation + // LIQUIDITY_POOL_DEPOSIT_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // LIQUIDITY_POOL_DEPOSIT_MALFORMED = -1, // bad input + // LIQUIDITY_POOL_DEPOSIT_NO_TRUST = -2, // no trust line for one of the + // // assets + // LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED = -3, // not authorized for one of the + // // assets + // LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED = -4, // not enough balance for one of + // // the assets + // LIQUIDITY_POOL_DEPOSIT_LINE_FULL = -5, // pool share trust line doesn't + // // have sufficient limit + // LIQUIDITY_POOL_DEPOSIT_BAD_PRICE = -6, // deposit price outside bounds + // LIQUIDITY_POOL_DEPOSIT_POOL_FULL = -7 // pool reserves are full + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolDepositResultCode", { + liquidityPoolDepositSuccess: 0, + liquidityPoolDepositMalformed: -1, + liquidityPoolDepositNoTrust: -2, + liquidityPoolDepositNotAuthorized: -3, + liquidityPoolDepositUnderfunded: -4, + liquidityPoolDepositLineFull: -5, + liquidityPoolDepositBadPrice: -6, + liquidityPoolDepositPoolFull: -7 + }); + + // === xdr source ============================================================ + // + // union LiquidityPoolDepositResult switch (LiquidityPoolDepositResultCode code) + // { + // case LIQUIDITY_POOL_DEPOSIT_SUCCESS: + // void; + // case LIQUIDITY_POOL_DEPOSIT_MALFORMED: + // case LIQUIDITY_POOL_DEPOSIT_NO_TRUST: + // case LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED: + // case LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED: + // case LIQUIDITY_POOL_DEPOSIT_LINE_FULL: + // case LIQUIDITY_POOL_DEPOSIT_BAD_PRICE: + // case LIQUIDITY_POOL_DEPOSIT_POOL_FULL: + // void; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolDepositResult", { + switchOn: xdr.lookup("LiquidityPoolDepositResultCode"), + switchName: "code", + switches: [["liquidityPoolDepositSuccess", xdr["void"]()], ["liquidityPoolDepositMalformed", xdr["void"]()], ["liquidityPoolDepositNoTrust", xdr["void"]()], ["liquidityPoolDepositNotAuthorized", xdr["void"]()], ["liquidityPoolDepositUnderfunded", xdr["void"]()], ["liquidityPoolDepositLineFull", xdr["void"]()], ["liquidityPoolDepositBadPrice", xdr["void"]()], ["liquidityPoolDepositPoolFull", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum LiquidityPoolWithdrawResultCode + // { + // // codes considered as "success" for the operation + // LIQUIDITY_POOL_WITHDRAW_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // LIQUIDITY_POOL_WITHDRAW_MALFORMED = -1, // bad input + // LIQUIDITY_POOL_WITHDRAW_NO_TRUST = -2, // no trust line for one of the + // // assets + // LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED = -3, // not enough balance of the + // // pool share + // LIQUIDITY_POOL_WITHDRAW_LINE_FULL = -4, // would go above limit for one + // // of the assets + // LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM = -5 // didn't withdraw enough + // }; + // + // =========================================================================== + xdr["enum"]("LiquidityPoolWithdrawResultCode", { + liquidityPoolWithdrawSuccess: 0, + liquidityPoolWithdrawMalformed: -1, + liquidityPoolWithdrawNoTrust: -2, + liquidityPoolWithdrawUnderfunded: -3, + liquidityPoolWithdrawLineFull: -4, + liquidityPoolWithdrawUnderMinimum: -5 + }); + + // === xdr source ============================================================ + // + // union LiquidityPoolWithdrawResult switch (LiquidityPoolWithdrawResultCode code) + // { + // case LIQUIDITY_POOL_WITHDRAW_SUCCESS: + // void; + // case LIQUIDITY_POOL_WITHDRAW_MALFORMED: + // case LIQUIDITY_POOL_WITHDRAW_NO_TRUST: + // case LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED: + // case LIQUIDITY_POOL_WITHDRAW_LINE_FULL: + // case LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM: + // void; + // }; + // + // =========================================================================== + xdr.union("LiquidityPoolWithdrawResult", { + switchOn: xdr.lookup("LiquidityPoolWithdrawResultCode"), + switchName: "code", + switches: [["liquidityPoolWithdrawSuccess", xdr["void"]()], ["liquidityPoolWithdrawMalformed", xdr["void"]()], ["liquidityPoolWithdrawNoTrust", xdr["void"]()], ["liquidityPoolWithdrawUnderfunded", xdr["void"]()], ["liquidityPoolWithdrawLineFull", xdr["void"]()], ["liquidityPoolWithdrawUnderMinimum", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum InvokeHostFunctionResultCode + // { + // // codes considered as "success" for the operation + // INVOKE_HOST_FUNCTION_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // INVOKE_HOST_FUNCTION_MALFORMED = -1, + // INVOKE_HOST_FUNCTION_TRAPPED = -2, + // INVOKE_HOST_FUNCTION_RESOURCE_LIMIT_EXCEEDED = -3, + // INVOKE_HOST_FUNCTION_ENTRY_ARCHIVED = -4, + // INVOKE_HOST_FUNCTION_INSUFFICIENT_REFUNDABLE_FEE = -5 + // }; + // + // =========================================================================== + xdr["enum"]("InvokeHostFunctionResultCode", { + invokeHostFunctionSuccess: 0, + invokeHostFunctionMalformed: -1, + invokeHostFunctionTrapped: -2, + invokeHostFunctionResourceLimitExceeded: -3, + invokeHostFunctionEntryArchived: -4, + invokeHostFunctionInsufficientRefundableFee: -5 + }); + + // === xdr source ============================================================ + // + // union InvokeHostFunctionResult switch (InvokeHostFunctionResultCode code) + // { + // case INVOKE_HOST_FUNCTION_SUCCESS: + // Hash success; // sha256(InvokeHostFunctionSuccessPreImage) + // case INVOKE_HOST_FUNCTION_MALFORMED: + // case INVOKE_HOST_FUNCTION_TRAPPED: + // case INVOKE_HOST_FUNCTION_RESOURCE_LIMIT_EXCEEDED: + // case INVOKE_HOST_FUNCTION_ENTRY_ARCHIVED: + // case INVOKE_HOST_FUNCTION_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("InvokeHostFunctionResult", { + switchOn: xdr.lookup("InvokeHostFunctionResultCode"), + switchName: "code", + switches: [["invokeHostFunctionSuccess", "success"], ["invokeHostFunctionMalformed", xdr["void"]()], ["invokeHostFunctionTrapped", xdr["void"]()], ["invokeHostFunctionResourceLimitExceeded", xdr["void"]()], ["invokeHostFunctionEntryArchived", xdr["void"]()], ["invokeHostFunctionInsufficientRefundableFee", xdr["void"]()]], + arms: { + success: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum ExtendFootprintTTLResultCode + // { + // // codes considered as "success" for the operation + // EXTEND_FOOTPRINT_TTL_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // EXTEND_FOOTPRINT_TTL_MALFORMED = -1, + // EXTEND_FOOTPRINT_TTL_RESOURCE_LIMIT_EXCEEDED = -2, + // EXTEND_FOOTPRINT_TTL_INSUFFICIENT_REFUNDABLE_FEE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("ExtendFootprintTtlResultCode", { + extendFootprintTtlSuccess: 0, + extendFootprintTtlMalformed: -1, + extendFootprintTtlResourceLimitExceeded: -2, + extendFootprintTtlInsufficientRefundableFee: -3 + }); + + // === xdr source ============================================================ + // + // union ExtendFootprintTTLResult switch (ExtendFootprintTTLResultCode code) + // { + // case EXTEND_FOOTPRINT_TTL_SUCCESS: + // void; + // case EXTEND_FOOTPRINT_TTL_MALFORMED: + // case EXTEND_FOOTPRINT_TTL_RESOURCE_LIMIT_EXCEEDED: + // case EXTEND_FOOTPRINT_TTL_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("ExtendFootprintTtlResult", { + switchOn: xdr.lookup("ExtendFootprintTtlResultCode"), + switchName: "code", + switches: [["extendFootprintTtlSuccess", xdr["void"]()], ["extendFootprintTtlMalformed", xdr["void"]()], ["extendFootprintTtlResourceLimitExceeded", xdr["void"]()], ["extendFootprintTtlInsufficientRefundableFee", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum RestoreFootprintResultCode + // { + // // codes considered as "success" for the operation + // RESTORE_FOOTPRINT_SUCCESS = 0, + // + // // codes considered as "failure" for the operation + // RESTORE_FOOTPRINT_MALFORMED = -1, + // RESTORE_FOOTPRINT_RESOURCE_LIMIT_EXCEEDED = -2, + // RESTORE_FOOTPRINT_INSUFFICIENT_REFUNDABLE_FEE = -3 + // }; + // + // =========================================================================== + xdr["enum"]("RestoreFootprintResultCode", { + restoreFootprintSuccess: 0, + restoreFootprintMalformed: -1, + restoreFootprintResourceLimitExceeded: -2, + restoreFootprintInsufficientRefundableFee: -3 + }); + + // === xdr source ============================================================ + // + // union RestoreFootprintResult switch (RestoreFootprintResultCode code) + // { + // case RESTORE_FOOTPRINT_SUCCESS: + // void; + // case RESTORE_FOOTPRINT_MALFORMED: + // case RESTORE_FOOTPRINT_RESOURCE_LIMIT_EXCEEDED: + // case RESTORE_FOOTPRINT_INSUFFICIENT_REFUNDABLE_FEE: + // void; + // }; + // + // =========================================================================== + xdr.union("RestoreFootprintResult", { + switchOn: xdr.lookup("RestoreFootprintResultCode"), + switchName: "code", + switches: [["restoreFootprintSuccess", xdr["void"]()], ["restoreFootprintMalformed", xdr["void"]()], ["restoreFootprintResourceLimitExceeded", xdr["void"]()], ["restoreFootprintInsufficientRefundableFee", xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum OperationResultCode + // { + // opINNER = 0, // inner object result is valid + // + // opBAD_AUTH = -1, // too few valid signatures / wrong network + // opNO_ACCOUNT = -2, // source account was not found + // opNOT_SUPPORTED = -3, // operation not supported at this time + // opTOO_MANY_SUBENTRIES = -4, // max number of subentries already reached + // opEXCEEDED_WORK_LIMIT = -5, // operation did too much work + // opTOO_MANY_SPONSORING = -6 // account is sponsoring too many entries + // }; + // + // =========================================================================== + xdr["enum"]("OperationResultCode", { + opInner: 0, + opBadAuth: -1, + opNoAccount: -2, + opNotSupported: -3, + opTooManySubentries: -4, + opExceededWorkLimit: -5, + opTooManySponsoring: -6 + }); + + // === xdr source ============================================================ + // + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountResult createAccountResult; + // case PAYMENT: + // PaymentResult paymentResult; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult; + // case MANAGE_SELL_OFFER: + // ManageSellOfferResult manageSellOfferResult; + // case CREATE_PASSIVE_SELL_OFFER: + // ManageSellOfferResult createPassiveSellOfferResult; + // case SET_OPTIONS: + // SetOptionsResult setOptionsResult; + // case CHANGE_TRUST: + // ChangeTrustResult changeTrustResult; + // case ALLOW_TRUST: + // AllowTrustResult allowTrustResult; + // case ACCOUNT_MERGE: + // AccountMergeResult accountMergeResult; + // case INFLATION: + // InflationResult inflationResult; + // case MANAGE_DATA: + // ManageDataResult manageDataResult; + // case BUMP_SEQUENCE: + // BumpSequenceResult bumpSeqResult; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferResult manageBuyOfferResult; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendResult pathPaymentStrictSendResult; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceResult createClaimableBalanceResult; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceResult claimClaimableBalanceResult; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult; + // case END_SPONSORING_FUTURE_RESERVES: + // EndSponsoringFutureReservesResult endSponsoringFutureReservesResult; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipResult revokeSponsorshipResult; + // case CLAWBACK: + // ClawbackResult clawbackResult; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceResult clawbackClaimableBalanceResult; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsResult setTrustLineFlagsResult; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositResult liquidityPoolDepositResult; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawResult liquidityPoolWithdrawResult; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionResult invokeHostFunctionResult; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLResult extendFootprintTTLResult; + // case RESTORE_FOOTPRINT: + // RestoreFootprintResult restoreFootprintResult; + // } + // + // =========================================================================== + xdr.union("OperationResultTr", { + switchOn: xdr.lookup("OperationType"), + switchName: "type", + switches: [["createAccount", "createAccountResult"], ["payment", "paymentResult"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveResult"], ["manageSellOffer", "manageSellOfferResult"], ["createPassiveSellOffer", "createPassiveSellOfferResult"], ["setOptions", "setOptionsResult"], ["changeTrust", "changeTrustResult"], ["allowTrust", "allowTrustResult"], ["accountMerge", "accountMergeResult"], ["inflation", "inflationResult"], ["manageData", "manageDataResult"], ["bumpSequence", "bumpSeqResult"], ["manageBuyOffer", "manageBuyOfferResult"], ["pathPaymentStrictSend", "pathPaymentStrictSendResult"], ["createClaimableBalance", "createClaimableBalanceResult"], ["claimClaimableBalance", "claimClaimableBalanceResult"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesResult"], ["endSponsoringFutureReserves", "endSponsoringFutureReservesResult"], ["revokeSponsorship", "revokeSponsorshipResult"], ["clawback", "clawbackResult"], ["clawbackClaimableBalance", "clawbackClaimableBalanceResult"], ["setTrustLineFlags", "setTrustLineFlagsResult"], ["liquidityPoolDeposit", "liquidityPoolDepositResult"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawResult"], ["invokeHostFunction", "invokeHostFunctionResult"], ["extendFootprintTtl", "extendFootprintTtlResult"], ["restoreFootprint", "restoreFootprintResult"]], + arms: { + createAccountResult: xdr.lookup("CreateAccountResult"), + paymentResult: xdr.lookup("PaymentResult"), + pathPaymentStrictReceiveResult: xdr.lookup("PathPaymentStrictReceiveResult"), + manageSellOfferResult: xdr.lookup("ManageSellOfferResult"), + createPassiveSellOfferResult: xdr.lookup("ManageSellOfferResult"), + setOptionsResult: xdr.lookup("SetOptionsResult"), + changeTrustResult: xdr.lookup("ChangeTrustResult"), + allowTrustResult: xdr.lookup("AllowTrustResult"), + accountMergeResult: xdr.lookup("AccountMergeResult"), + inflationResult: xdr.lookup("InflationResult"), + manageDataResult: xdr.lookup("ManageDataResult"), + bumpSeqResult: xdr.lookup("BumpSequenceResult"), + manageBuyOfferResult: xdr.lookup("ManageBuyOfferResult"), + pathPaymentStrictSendResult: xdr.lookup("PathPaymentStrictSendResult"), + createClaimableBalanceResult: xdr.lookup("CreateClaimableBalanceResult"), + claimClaimableBalanceResult: xdr.lookup("ClaimClaimableBalanceResult"), + beginSponsoringFutureReservesResult: xdr.lookup("BeginSponsoringFutureReservesResult"), + endSponsoringFutureReservesResult: xdr.lookup("EndSponsoringFutureReservesResult"), + revokeSponsorshipResult: xdr.lookup("RevokeSponsorshipResult"), + clawbackResult: xdr.lookup("ClawbackResult"), + clawbackClaimableBalanceResult: xdr.lookup("ClawbackClaimableBalanceResult"), + setTrustLineFlagsResult: xdr.lookup("SetTrustLineFlagsResult"), + liquidityPoolDepositResult: xdr.lookup("LiquidityPoolDepositResult"), + liquidityPoolWithdrawResult: xdr.lookup("LiquidityPoolWithdrawResult"), + invokeHostFunctionResult: xdr.lookup("InvokeHostFunctionResult"), + extendFootprintTtlResult: xdr.lookup("ExtendFootprintTtlResult"), + restoreFootprintResult: xdr.lookup("RestoreFootprintResult") + } + }); + + // === xdr source ============================================================ + // + // union OperationResult switch (OperationResultCode code) + // { + // case opINNER: + // union switch (OperationType type) + // { + // case CREATE_ACCOUNT: + // CreateAccountResult createAccountResult; + // case PAYMENT: + // PaymentResult paymentResult; + // case PATH_PAYMENT_STRICT_RECEIVE: + // PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult; + // case MANAGE_SELL_OFFER: + // ManageSellOfferResult manageSellOfferResult; + // case CREATE_PASSIVE_SELL_OFFER: + // ManageSellOfferResult createPassiveSellOfferResult; + // case SET_OPTIONS: + // SetOptionsResult setOptionsResult; + // case CHANGE_TRUST: + // ChangeTrustResult changeTrustResult; + // case ALLOW_TRUST: + // AllowTrustResult allowTrustResult; + // case ACCOUNT_MERGE: + // AccountMergeResult accountMergeResult; + // case INFLATION: + // InflationResult inflationResult; + // case MANAGE_DATA: + // ManageDataResult manageDataResult; + // case BUMP_SEQUENCE: + // BumpSequenceResult bumpSeqResult; + // case MANAGE_BUY_OFFER: + // ManageBuyOfferResult manageBuyOfferResult; + // case PATH_PAYMENT_STRICT_SEND: + // PathPaymentStrictSendResult pathPaymentStrictSendResult; + // case CREATE_CLAIMABLE_BALANCE: + // CreateClaimableBalanceResult createClaimableBalanceResult; + // case CLAIM_CLAIMABLE_BALANCE: + // ClaimClaimableBalanceResult claimClaimableBalanceResult; + // case BEGIN_SPONSORING_FUTURE_RESERVES: + // BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult; + // case END_SPONSORING_FUTURE_RESERVES: + // EndSponsoringFutureReservesResult endSponsoringFutureReservesResult; + // case REVOKE_SPONSORSHIP: + // RevokeSponsorshipResult revokeSponsorshipResult; + // case CLAWBACK: + // ClawbackResult clawbackResult; + // case CLAWBACK_CLAIMABLE_BALANCE: + // ClawbackClaimableBalanceResult clawbackClaimableBalanceResult; + // case SET_TRUST_LINE_FLAGS: + // SetTrustLineFlagsResult setTrustLineFlagsResult; + // case LIQUIDITY_POOL_DEPOSIT: + // LiquidityPoolDepositResult liquidityPoolDepositResult; + // case LIQUIDITY_POOL_WITHDRAW: + // LiquidityPoolWithdrawResult liquidityPoolWithdrawResult; + // case INVOKE_HOST_FUNCTION: + // InvokeHostFunctionResult invokeHostFunctionResult; + // case EXTEND_FOOTPRINT_TTL: + // ExtendFootprintTTLResult extendFootprintTTLResult; + // case RESTORE_FOOTPRINT: + // RestoreFootprintResult restoreFootprintResult; + // } + // tr; + // case opBAD_AUTH: + // case opNO_ACCOUNT: + // case opNOT_SUPPORTED: + // case opTOO_MANY_SUBENTRIES: + // case opEXCEEDED_WORK_LIMIT: + // case opTOO_MANY_SPONSORING: + // void; + // }; + // + // =========================================================================== + xdr.union("OperationResult", { + switchOn: xdr.lookup("OperationResultCode"), + switchName: "code", + switches: [["opInner", "tr"], ["opBadAuth", xdr["void"]()], ["opNoAccount", xdr["void"]()], ["opNotSupported", xdr["void"]()], ["opTooManySubentries", xdr["void"]()], ["opExceededWorkLimit", xdr["void"]()], ["opTooManySponsoring", xdr["void"]()]], + arms: { + tr: xdr.lookup("OperationResultTr") + } + }); + + // === xdr source ============================================================ + // + // enum TransactionResultCode + // { + // txFEE_BUMP_INNER_SUCCESS = 1, // fee bump inner transaction succeeded + // txSUCCESS = 0, // all operations succeeded + // + // txFAILED = -1, // one of the operations failed (none were applied) + // + // txTOO_EARLY = -2, // ledger closeTime before minTime + // txTOO_LATE = -3, // ledger closeTime after maxTime + // txMISSING_OPERATION = -4, // no operation was specified + // txBAD_SEQ = -5, // sequence number does not match source account + // + // txBAD_AUTH = -6, // too few valid signatures / wrong network + // txINSUFFICIENT_BALANCE = -7, // fee would bring account below reserve + // txNO_ACCOUNT = -8, // source account not found + // txINSUFFICIENT_FEE = -9, // fee is too small + // txBAD_AUTH_EXTRA = -10, // unused signatures attached to transaction + // txINTERNAL_ERROR = -11, // an unknown error occurred + // + // txNOT_SUPPORTED = -12, // transaction type not supported + // txFEE_BUMP_INNER_FAILED = -13, // fee bump inner transaction failed + // txBAD_SPONSORSHIP = -14, // sponsorship not confirmed + // txBAD_MIN_SEQ_AGE_OR_GAP = -15, // minSeqAge or minSeqLedgerGap conditions not met + // txMALFORMED = -16, // precondition is invalid + // txSOROBAN_INVALID = -17 // soroban-specific preconditions were not met + // }; + // + // =========================================================================== + xdr["enum"]("TransactionResultCode", { + txFeeBumpInnerSuccess: 1, + txSuccess: 0, + txFailed: -1, + txTooEarly: -2, + txTooLate: -3, + txMissingOperation: -4, + txBadSeq: -5, + txBadAuth: -6, + txInsufficientBalance: -7, + txNoAccount: -8, + txInsufficientFee: -9, + txBadAuthExtra: -10, + txInternalError: -11, + txNotSupported: -12, + txFeeBumpInnerFailed: -13, + txBadSponsorship: -14, + txBadMinSeqAgeOrGap: -15, + txMalformed: -16, + txSorobanInvalid: -17 + }); + + // === xdr source ============================================================ + // + // union switch (TransactionResultCode code) + // { + // // txFEE_BUMP_INNER_SUCCESS is not included + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // txFEE_BUMP_INNER_FAILED is not included + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // + // =========================================================================== + xdr.union("InnerTransactionResultResult", { + switchOn: xdr.lookup("TransactionResultCode"), + switchName: "code", + switches: [["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr["void"]()], ["txTooLate", xdr["void"]()], ["txMissingOperation", xdr["void"]()], ["txBadSeq", xdr["void"]()], ["txBadAuth", xdr["void"]()], ["txInsufficientBalance", xdr["void"]()], ["txNoAccount", xdr["void"]()], ["txInsufficientFee", xdr["void"]()], ["txBadAuthExtra", xdr["void"]()], ["txInternalError", xdr["void"]()], ["txNotSupported", xdr["void"]()], ["txBadSponsorship", xdr["void"]()], ["txBadMinSeqAgeOrGap", xdr["void"]()], ["txMalformed", xdr["void"]()], ["txSorobanInvalid", xdr["void"]()]], + arms: { + results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("InnerTransactionResultExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct InnerTransactionResult + // { + // // Always 0. Here for binary compatibility. + // int64 feeCharged; + // + // union switch (TransactionResultCode code) + // { + // // txFEE_BUMP_INNER_SUCCESS is not included + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // txFEE_BUMP_INNER_FAILED is not included + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // result; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("InnerTransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("InnerTransactionResultResult")], ["ext", xdr.lookup("InnerTransactionResultExt")]]); + + // === xdr source ============================================================ + // + // struct InnerTransactionResultPair + // { + // Hash transactionHash; // hash of the inner transaction + // InnerTransactionResult result; // result for the inner transaction + // }; + // + // =========================================================================== + xdr.struct("InnerTransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("InnerTransactionResult")]]); + + // === xdr source ============================================================ + // + // union switch (TransactionResultCode code) + // { + // case txFEE_BUMP_INNER_SUCCESS: + // case txFEE_BUMP_INNER_FAILED: + // InnerTransactionResultPair innerResultPair; + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // case txFEE_BUMP_INNER_FAILED: handled above + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionResultResult", { + switchOn: xdr.lookup("TransactionResultCode"), + switchName: "code", + switches: [["txFeeBumpInnerSuccess", "innerResultPair"], ["txFeeBumpInnerFailed", "innerResultPair"], ["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr["void"]()], ["txTooLate", xdr["void"]()], ["txMissingOperation", xdr["void"]()], ["txBadSeq", xdr["void"]()], ["txBadAuth", xdr["void"]()], ["txInsufficientBalance", xdr["void"]()], ["txNoAccount", xdr["void"]()], ["txInsufficientFee", xdr["void"]()], ["txBadAuthExtra", xdr["void"]()], ["txInternalError", xdr["void"]()], ["txNotSupported", xdr["void"]()], ["txBadSponsorship", xdr["void"]()], ["txBadMinSeqAgeOrGap", xdr["void"]()], ["txMalformed", xdr["void"]()], ["txSorobanInvalid", xdr["void"]()]], + arms: { + innerResultPair: xdr.lookup("InnerTransactionResultPair"), + results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647) + } + }); + + // === xdr source ============================================================ + // + // union switch (int v) + // { + // case 0: + // void; + // } + // + // =========================================================================== + xdr.union("TransactionResultExt", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // struct TransactionResult + // { + // int64 feeCharged; // actual fee charged for the transaction + // + // union switch (TransactionResultCode code) + // { + // case txFEE_BUMP_INNER_SUCCESS: + // case txFEE_BUMP_INNER_FAILED: + // InnerTransactionResultPair innerResultPair; + // case txSUCCESS: + // case txFAILED: + // OperationResult results<>; + // case txTOO_EARLY: + // case txTOO_LATE: + // case txMISSING_OPERATION: + // case txBAD_SEQ: + // case txBAD_AUTH: + // case txINSUFFICIENT_BALANCE: + // case txNO_ACCOUNT: + // case txINSUFFICIENT_FEE: + // case txBAD_AUTH_EXTRA: + // case txINTERNAL_ERROR: + // case txNOT_SUPPORTED: + // // case txFEE_BUMP_INNER_FAILED: handled above + // case txBAD_SPONSORSHIP: + // case txBAD_MIN_SEQ_AGE_OR_GAP: + // case txMALFORMED: + // case txSOROBAN_INVALID: + // void; + // } + // result; + // + // // reserved for future use + // union switch (int v) + // { + // case 0: + // void; + // } + // ext; + // }; + // + // =========================================================================== + xdr.struct("TransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("TransactionResultResult")], ["ext", xdr.lookup("TransactionResultExt")]]); + + // === xdr source ============================================================ + // + // typedef opaque Hash[32]; + // + // =========================================================================== + xdr.typedef("Hash", xdr.opaque(32)); + + // === xdr source ============================================================ + // + // typedef opaque uint256[32]; + // + // =========================================================================== + xdr.typedef("Uint256", xdr.opaque(32)); + + // === xdr source ============================================================ + // + // typedef unsigned int uint32; + // + // =========================================================================== + xdr.typedef("Uint32", xdr.uint()); + + // === xdr source ============================================================ + // + // typedef int int32; + // + // =========================================================================== + xdr.typedef("Int32", xdr["int"]()); + + // === xdr source ============================================================ + // + // typedef unsigned hyper uint64; + // + // =========================================================================== + xdr.typedef("Uint64", xdr.uhyper()); + + // === xdr source ============================================================ + // + // typedef hyper int64; + // + // =========================================================================== + xdr.typedef("Int64", xdr.hyper()); + + // === xdr source ============================================================ + // + // typedef uint64 TimePoint; + // + // =========================================================================== + xdr.typedef("TimePoint", xdr.lookup("Uint64")); + + // === xdr source ============================================================ + // + // typedef uint64 Duration; + // + // =========================================================================== + xdr.typedef("Duration", xdr.lookup("Uint64")); + + // === xdr source ============================================================ + // + // union ExtensionPoint switch (int v) + // { + // case 0: + // void; + // }; + // + // =========================================================================== + xdr.union("ExtensionPoint", { + switchOn: xdr["int"](), + switchName: "v", + switches: [[0, xdr["void"]()]], + arms: {} + }); + + // === xdr source ============================================================ + // + // enum CryptoKeyType + // { + // KEY_TYPE_ED25519 = 0, + // KEY_TYPE_PRE_AUTH_TX = 1, + // KEY_TYPE_HASH_X = 2, + // KEY_TYPE_ED25519_SIGNED_PAYLOAD = 3, + // // MUXED enum values for supported type are derived from the enum values + // // above by ORing them with 0x100 + // KEY_TYPE_MUXED_ED25519 = 0x100 + // }; + // + // =========================================================================== + xdr["enum"]("CryptoKeyType", { + keyTypeEd25519: 0, + keyTypePreAuthTx: 1, + keyTypeHashX: 2, + keyTypeEd25519SignedPayload: 3, + keyTypeMuxedEd25519: 256 + }); + + // === xdr source ============================================================ + // + // enum PublicKeyType + // { + // PUBLIC_KEY_TYPE_ED25519 = KEY_TYPE_ED25519 + // }; + // + // =========================================================================== + xdr["enum"]("PublicKeyType", { + publicKeyTypeEd25519: 0 + }); + + // === xdr source ============================================================ + // + // enum SignerKeyType + // { + // SIGNER_KEY_TYPE_ED25519 = KEY_TYPE_ED25519, + // SIGNER_KEY_TYPE_PRE_AUTH_TX = KEY_TYPE_PRE_AUTH_TX, + // SIGNER_KEY_TYPE_HASH_X = KEY_TYPE_HASH_X, + // SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD = KEY_TYPE_ED25519_SIGNED_PAYLOAD + // }; + // + // =========================================================================== + xdr["enum"]("SignerKeyType", { + signerKeyTypeEd25519: 0, + signerKeyTypePreAuthTx: 1, + signerKeyTypeHashX: 2, + signerKeyTypeEd25519SignedPayload: 3 + }); + + // === xdr source ============================================================ + // + // union PublicKey switch (PublicKeyType type) + // { + // case PUBLIC_KEY_TYPE_ED25519: + // uint256 ed25519; + // }; + // + // =========================================================================== + xdr.union("PublicKey", { + switchOn: xdr.lookup("PublicKeyType"), + switchName: "type", + switches: [["publicKeyTypeEd25519", "ed25519"]], + arms: { + ed25519: xdr.lookup("Uint256") + } + }); + + // === xdr source ============================================================ + // + // struct + // { + // /* Public key that must sign the payload. */ + // uint256 ed25519; + // /* Payload to be raw signed by ed25519. */ + // opaque payload<64>; + // } + // + // =========================================================================== + xdr.struct("SignerKeyEd25519SignedPayload", [["ed25519", xdr.lookup("Uint256")], ["payload", xdr.varOpaque(64)]]); + + // === xdr source ============================================================ + // + // union SignerKey switch (SignerKeyType type) + // { + // case SIGNER_KEY_TYPE_ED25519: + // uint256 ed25519; + // case SIGNER_KEY_TYPE_PRE_AUTH_TX: + // /* SHA-256 Hash of TransactionSignaturePayload structure */ + // uint256 preAuthTx; + // case SIGNER_KEY_TYPE_HASH_X: + // /* Hash of random 256 bit preimage X */ + // uint256 hashX; + // case SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD: + // struct + // { + // /* Public key that must sign the payload. */ + // uint256 ed25519; + // /* Payload to be raw signed by ed25519. */ + // opaque payload<64>; + // } ed25519SignedPayload; + // }; + // + // =========================================================================== + xdr.union("SignerKey", { + switchOn: xdr.lookup("SignerKeyType"), + switchName: "type", + switches: [["signerKeyTypeEd25519", "ed25519"], ["signerKeyTypePreAuthTx", "preAuthTx"], ["signerKeyTypeHashX", "hashX"], ["signerKeyTypeEd25519SignedPayload", "ed25519SignedPayload"]], + arms: { + ed25519: xdr.lookup("Uint256"), + preAuthTx: xdr.lookup("Uint256"), + hashX: xdr.lookup("Uint256"), + ed25519SignedPayload: xdr.lookup("SignerKeyEd25519SignedPayload") + } + }); + + // === xdr source ============================================================ + // + // typedef opaque Signature<64>; + // + // =========================================================================== + xdr.typedef("Signature", xdr.varOpaque(64)); + + // === xdr source ============================================================ + // + // typedef opaque SignatureHint[4]; + // + // =========================================================================== + xdr.typedef("SignatureHint", xdr.opaque(4)); + + // === xdr source ============================================================ + // + // typedef PublicKey NodeID; + // + // =========================================================================== + xdr.typedef("NodeId", xdr.lookup("PublicKey")); + + // === xdr source ============================================================ + // + // typedef PublicKey AccountID; + // + // =========================================================================== + xdr.typedef("AccountId", xdr.lookup("PublicKey")); + + // === xdr source ============================================================ + // + // struct Curve25519Secret + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("Curve25519Secret", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct Curve25519Public + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("Curve25519Public", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct HmacSha256Key + // { + // opaque key[32]; + // }; + // + // =========================================================================== + xdr.struct("HmacSha256Key", [["key", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct HmacSha256Mac + // { + // opaque mac[32]; + // }; + // + // =========================================================================== + xdr.struct("HmacSha256Mac", [["mac", xdr.opaque(32)]]); + + // === xdr source ============================================================ + // + // struct ShortHashSeed + // { + // opaque seed[16]; + // }; + // + // =========================================================================== + xdr.struct("ShortHashSeed", [["seed", xdr.opaque(16)]]); + + // === xdr source ============================================================ + // + // enum BinaryFuseFilterType + // { + // BINARY_FUSE_FILTER_8_BIT = 0, + // BINARY_FUSE_FILTER_16_BIT = 1, + // BINARY_FUSE_FILTER_32_BIT = 2 + // }; + // + // =========================================================================== + xdr["enum"]("BinaryFuseFilterType", { + binaryFuseFilter8Bit: 0, + binaryFuseFilter16Bit: 1, + binaryFuseFilter32Bit: 2 + }); + + // === xdr source ============================================================ + // + // struct SerializedBinaryFuseFilter + // { + // BinaryFuseFilterType type; + // + // // Seed used to hash input to filter + // ShortHashSeed inputHashSeed; + // + // // Seed used for internal filter hash operations + // ShortHashSeed filterSeed; + // uint32 segmentLength; + // uint32 segementLengthMask; + // uint32 segmentCount; + // uint32 segmentCountLength; + // uint32 fingerprintLength; // Length in terms of element count, not bytes + // + // // Array of uint8_t, uint16_t, or uint32_t depending on filter type + // opaque fingerprints<>; + // }; + // + // =========================================================================== + xdr.struct("SerializedBinaryFuseFilter", [["type", xdr.lookup("BinaryFuseFilterType")], ["inputHashSeed", xdr.lookup("ShortHashSeed")], ["filterSeed", xdr.lookup("ShortHashSeed")], ["segmentLength", xdr.lookup("Uint32")], ["segementLengthMask", xdr.lookup("Uint32")], ["segmentCount", xdr.lookup("Uint32")], ["segmentCountLength", xdr.lookup("Uint32")], ["fingerprintLength", xdr.lookup("Uint32")], ["fingerprints", xdr.varOpaque()]]); + + // === xdr source ============================================================ + // + // enum SCValType + // { + // SCV_BOOL = 0, + // SCV_VOID = 1, + // SCV_ERROR = 2, + // + // // 32 bits is the smallest type in WASM or XDR; no need for u8/u16. + // SCV_U32 = 3, + // SCV_I32 = 4, + // + // // 64 bits is naturally supported by both WASM and XDR also. + // SCV_U64 = 5, + // SCV_I64 = 6, + // + // // Time-related u64 subtypes with their own functions and formatting. + // SCV_TIMEPOINT = 7, + // SCV_DURATION = 8, + // + // // 128 bits is naturally supported by Rust and we use it for Soroban + // // fixed-point arithmetic prices / balances / similar "quantities". These + // // are represented in XDR as a pair of 2 u64s. + // SCV_U128 = 9, + // SCV_I128 = 10, + // + // // 256 bits is the size of sha256 output, ed25519 keys, and the EVM machine + // // word, so for interop use we include this even though it requires a small + // // amount of Rust guest and/or host library code. + // SCV_U256 = 11, + // SCV_I256 = 12, + // + // // Bytes come in 3 flavors, 2 of which have meaningfully different + // // formatting and validity-checking / domain-restriction. + // SCV_BYTES = 13, + // SCV_STRING = 14, + // SCV_SYMBOL = 15, + // + // // Vecs and maps are just polymorphic containers of other ScVals. + // SCV_VEC = 16, + // SCV_MAP = 17, + // + // // Address is the universal identifier for contracts and classic + // // accounts. + // SCV_ADDRESS = 18, + // + // // The following are the internal SCVal variants that are not + // // exposed to the contracts. + // SCV_CONTRACT_INSTANCE = 19, + // + // // SCV_LEDGER_KEY_CONTRACT_INSTANCE and SCV_LEDGER_KEY_NONCE are unique + // // symbolic SCVals used as the key for ledger entries for a contract's + // // instance and an address' nonce, respectively. + // SCV_LEDGER_KEY_CONTRACT_INSTANCE = 20, + // SCV_LEDGER_KEY_NONCE = 21 + // }; + // + // =========================================================================== + xdr["enum"]("ScValType", { + scvBool: 0, + scvVoid: 1, + scvError: 2, + scvU32: 3, + scvI32: 4, + scvU64: 5, + scvI64: 6, + scvTimepoint: 7, + scvDuration: 8, + scvU128: 9, + scvI128: 10, + scvU256: 11, + scvI256: 12, + scvBytes: 13, + scvString: 14, + scvSymbol: 15, + scvVec: 16, + scvMap: 17, + scvAddress: 18, + scvContractInstance: 19, + scvLedgerKeyContractInstance: 20, + scvLedgerKeyNonce: 21 + }); + + // === xdr source ============================================================ + // + // enum SCErrorType + // { + // SCE_CONTRACT = 0, // Contract-specific, user-defined codes. + // SCE_WASM_VM = 1, // Errors while interpreting WASM bytecode. + // SCE_CONTEXT = 2, // Errors in the contract's host context. + // SCE_STORAGE = 3, // Errors accessing host storage. + // SCE_OBJECT = 4, // Errors working with host objects. + // SCE_CRYPTO = 5, // Errors in cryptographic operations. + // SCE_EVENTS = 6, // Errors while emitting events. + // SCE_BUDGET = 7, // Errors relating to budget limits. + // SCE_VALUE = 8, // Errors working with host values or SCVals. + // SCE_AUTH = 9 // Errors from the authentication subsystem. + // }; + // + // =========================================================================== + xdr["enum"]("ScErrorType", { + sceContract: 0, + sceWasmVm: 1, + sceContext: 2, + sceStorage: 3, + sceObject: 4, + sceCrypto: 5, + sceEvents: 6, + sceBudget: 7, + sceValue: 8, + sceAuth: 9 + }); + + // === xdr source ============================================================ + // + // enum SCErrorCode + // { + // SCEC_ARITH_DOMAIN = 0, // Some arithmetic was undefined (overflow, divide-by-zero). + // SCEC_INDEX_BOUNDS = 1, // Something was indexed beyond its bounds. + // SCEC_INVALID_INPUT = 2, // User provided some otherwise-bad data. + // SCEC_MISSING_VALUE = 3, // Some value was required but not provided. + // SCEC_EXISTING_VALUE = 4, // Some value was provided where not allowed. + // SCEC_EXCEEDED_LIMIT = 5, // Some arbitrary limit -- gas or otherwise -- was hit. + // SCEC_INVALID_ACTION = 6, // Data was valid but action requested was not. + // SCEC_INTERNAL_ERROR = 7, // The host detected an error in its own logic. + // SCEC_UNEXPECTED_TYPE = 8, // Some type wasn't as expected. + // SCEC_UNEXPECTED_SIZE = 9 // Something's size wasn't as expected. + // }; + // + // =========================================================================== + xdr["enum"]("ScErrorCode", { + scecArithDomain: 0, + scecIndexBounds: 1, + scecInvalidInput: 2, + scecMissingValue: 3, + scecExistingValue: 4, + scecExceededLimit: 5, + scecInvalidAction: 6, + scecInternalError: 7, + scecUnexpectedType: 8, + scecUnexpectedSize: 9 + }); + + // === xdr source ============================================================ + // + // union SCError switch (SCErrorType type) + // { + // case SCE_CONTRACT: + // uint32 contractCode; + // case SCE_WASM_VM: + // case SCE_CONTEXT: + // case SCE_STORAGE: + // case SCE_OBJECT: + // case SCE_CRYPTO: + // case SCE_EVENTS: + // case SCE_BUDGET: + // case SCE_VALUE: + // case SCE_AUTH: + // SCErrorCode code; + // }; + // + // =========================================================================== + xdr.union("ScError", { + switchOn: xdr.lookup("ScErrorType"), + switchName: "type", + switches: [["sceContract", "contractCode"], ["sceWasmVm", "code"], ["sceContext", "code"], ["sceStorage", "code"], ["sceObject", "code"], ["sceCrypto", "code"], ["sceEvents", "code"], ["sceBudget", "code"], ["sceValue", "code"], ["sceAuth", "code"]], + arms: { + contractCode: xdr.lookup("Uint32"), + code: xdr.lookup("ScErrorCode") + } + }); + + // === xdr source ============================================================ + // + // struct UInt128Parts { + // uint64 hi; + // uint64 lo; + // }; + // + // =========================================================================== + xdr.struct("UInt128Parts", [["hi", xdr.lookup("Uint64")], ["lo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct Int128Parts { + // int64 hi; + // uint64 lo; + // }; + // + // =========================================================================== + xdr.struct("Int128Parts", [["hi", xdr.lookup("Int64")], ["lo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct UInt256Parts { + // uint64 hi_hi; + // uint64 hi_lo; + // uint64 lo_hi; + // uint64 lo_lo; + // }; + // + // =========================================================================== + xdr.struct("UInt256Parts", [["hiHi", xdr.lookup("Uint64")], ["hiLo", xdr.lookup("Uint64")], ["loHi", xdr.lookup("Uint64")], ["loLo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // struct Int256Parts { + // int64 hi_hi; + // uint64 hi_lo; + // uint64 lo_hi; + // uint64 lo_lo; + // }; + // + // =========================================================================== + xdr.struct("Int256Parts", [["hiHi", xdr.lookup("Int64")], ["hiLo", xdr.lookup("Uint64")], ["loHi", xdr.lookup("Uint64")], ["loLo", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // enum ContractExecutableType + // { + // CONTRACT_EXECUTABLE_WASM = 0, + // CONTRACT_EXECUTABLE_STELLAR_ASSET = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ContractExecutableType", { + contractExecutableWasm: 0, + contractExecutableStellarAsset: 1 + }); + + // === xdr source ============================================================ + // + // union ContractExecutable switch (ContractExecutableType type) + // { + // case CONTRACT_EXECUTABLE_WASM: + // Hash wasm_hash; + // case CONTRACT_EXECUTABLE_STELLAR_ASSET: + // void; + // }; + // + // =========================================================================== + xdr.union("ContractExecutable", { + switchOn: xdr.lookup("ContractExecutableType"), + switchName: "type", + switches: [["contractExecutableWasm", "wasmHash"], ["contractExecutableStellarAsset", xdr["void"]()]], + arms: { + wasmHash: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // enum SCAddressType + // { + // SC_ADDRESS_TYPE_ACCOUNT = 0, + // SC_ADDRESS_TYPE_CONTRACT = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ScAddressType", { + scAddressTypeAccount: 0, + scAddressTypeContract: 1 + }); + + // === xdr source ============================================================ + // + // union SCAddress switch (SCAddressType type) + // { + // case SC_ADDRESS_TYPE_ACCOUNT: + // AccountID accountId; + // case SC_ADDRESS_TYPE_CONTRACT: + // Hash contractId; + // }; + // + // =========================================================================== + xdr.union("ScAddress", { + switchOn: xdr.lookup("ScAddressType"), + switchName: "type", + switches: [["scAddressTypeAccount", "accountId"], ["scAddressTypeContract", "contractId"]], + arms: { + accountId: xdr.lookup("AccountId"), + contractId: xdr.lookup("Hash") + } + }); + + // === xdr source ============================================================ + // + // const SCSYMBOL_LIMIT = 32; + // + // =========================================================================== + xdr["const"]("SCSYMBOL_LIMIT", 32); + + // === xdr source ============================================================ + // + // typedef SCVal SCVec<>; + // + // =========================================================================== + xdr.typedef("ScVec", xdr.varArray(xdr.lookup("ScVal"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef SCMapEntry SCMap<>; + // + // =========================================================================== + xdr.typedef("ScMap", xdr.varArray(xdr.lookup("ScMapEntry"), 2147483647)); + + // === xdr source ============================================================ + // + // typedef opaque SCBytes<>; + // + // =========================================================================== + xdr.typedef("ScBytes", xdr.varOpaque()); + + // === xdr source ============================================================ + // + // typedef string SCString<>; + // + // =========================================================================== + xdr.typedef("ScString", xdr.string()); + + // === xdr source ============================================================ + // + // typedef string SCSymbol; + // + // =========================================================================== + xdr.typedef("ScSymbol", xdr.string(SCSYMBOL_LIMIT)); + + // === xdr source ============================================================ + // + // struct SCNonceKey { + // int64 nonce; + // }; + // + // =========================================================================== + xdr.struct("ScNonceKey", [["nonce", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct SCContractInstance { + // ContractExecutable executable; + // SCMap* storage; + // }; + // + // =========================================================================== + xdr.struct("ScContractInstance", [["executable", xdr.lookup("ContractExecutable")], ["storage", xdr.option(xdr.lookup("ScMap"))]]); + + // === xdr source ============================================================ + // + // union SCVal switch (SCValType type) + // { + // + // case SCV_BOOL: + // bool b; + // case SCV_VOID: + // void; + // case SCV_ERROR: + // SCError error; + // + // case SCV_U32: + // uint32 u32; + // case SCV_I32: + // int32 i32; + // + // case SCV_U64: + // uint64 u64; + // case SCV_I64: + // int64 i64; + // case SCV_TIMEPOINT: + // TimePoint timepoint; + // case SCV_DURATION: + // Duration duration; + // + // case SCV_U128: + // UInt128Parts u128; + // case SCV_I128: + // Int128Parts i128; + // + // case SCV_U256: + // UInt256Parts u256; + // case SCV_I256: + // Int256Parts i256; + // + // case SCV_BYTES: + // SCBytes bytes; + // case SCV_STRING: + // SCString str; + // case SCV_SYMBOL: + // SCSymbol sym; + // + // // Vec and Map are recursive so need to live + // // behind an option, due to xdrpp limitations. + // case SCV_VEC: + // SCVec *vec; + // case SCV_MAP: + // SCMap *map; + // + // case SCV_ADDRESS: + // SCAddress address; + // + // // Special SCVals reserved for system-constructed contract-data + // // ledger keys, not generally usable elsewhere. + // case SCV_LEDGER_KEY_CONTRACT_INSTANCE: + // void; + // case SCV_LEDGER_KEY_NONCE: + // SCNonceKey nonce_key; + // + // case SCV_CONTRACT_INSTANCE: + // SCContractInstance instance; + // }; + // + // =========================================================================== + xdr.union("ScVal", { + switchOn: xdr.lookup("ScValType"), + switchName: "type", + switches: [["scvBool", "b"], ["scvVoid", xdr["void"]()], ["scvError", "error"], ["scvU32", "u32"], ["scvI32", "i32"], ["scvU64", "u64"], ["scvI64", "i64"], ["scvTimepoint", "timepoint"], ["scvDuration", "duration"], ["scvU128", "u128"], ["scvI128", "i128"], ["scvU256", "u256"], ["scvI256", "i256"], ["scvBytes", "bytes"], ["scvString", "str"], ["scvSymbol", "sym"], ["scvVec", "vec"], ["scvMap", "map"], ["scvAddress", "address"], ["scvLedgerKeyContractInstance", xdr["void"]()], ["scvLedgerKeyNonce", "nonceKey"], ["scvContractInstance", "instance"]], + arms: { + b: xdr.bool(), + error: xdr.lookup("ScError"), + u32: xdr.lookup("Uint32"), + i32: xdr.lookup("Int32"), + u64: xdr.lookup("Uint64"), + i64: xdr.lookup("Int64"), + timepoint: xdr.lookup("TimePoint"), + duration: xdr.lookup("Duration"), + u128: xdr.lookup("UInt128Parts"), + i128: xdr.lookup("Int128Parts"), + u256: xdr.lookup("UInt256Parts"), + i256: xdr.lookup("Int256Parts"), + bytes: xdr.lookup("ScBytes"), + str: xdr.lookup("ScString"), + sym: xdr.lookup("ScSymbol"), + vec: xdr.option(xdr.lookup("ScVec")), + map: xdr.option(xdr.lookup("ScMap")), + address: xdr.lookup("ScAddress"), + nonceKey: xdr.lookup("ScNonceKey"), + instance: xdr.lookup("ScContractInstance") + } + }); + + // === xdr source ============================================================ + // + // struct SCMapEntry + // { + // SCVal key; + // SCVal val; + // }; + // + // =========================================================================== + xdr.struct("ScMapEntry", [["key", xdr.lookup("ScVal")], ["val", xdr.lookup("ScVal")]]); + + // === xdr source ============================================================ + // + // enum SCEnvMetaKind + // { + // SC_ENV_META_KIND_INTERFACE_VERSION = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ScEnvMetaKind", { + scEnvMetaKindInterfaceVersion: 0 + }); + + // === xdr source ============================================================ + // + // struct { + // uint32 protocol; + // uint32 preRelease; + // } + // + // =========================================================================== + xdr.struct("ScEnvMetaEntryInterfaceVersion", [["protocol", xdr.lookup("Uint32")], ["preRelease", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // union SCEnvMetaEntry switch (SCEnvMetaKind kind) + // { + // case SC_ENV_META_KIND_INTERFACE_VERSION: + // struct { + // uint32 protocol; + // uint32 preRelease; + // } interfaceVersion; + // }; + // + // =========================================================================== + xdr.union("ScEnvMetaEntry", { + switchOn: xdr.lookup("ScEnvMetaKind"), + switchName: "kind", + switches: [["scEnvMetaKindInterfaceVersion", "interfaceVersion"]], + arms: { + interfaceVersion: xdr.lookup("ScEnvMetaEntryInterfaceVersion") + } + }); + + // === xdr source ============================================================ + // + // struct SCMetaV0 + // { + // string key<>; + // string val<>; + // }; + // + // =========================================================================== + xdr.struct("ScMetaV0", [["key", xdr.string()], ["val", xdr.string()]]); + + // === xdr source ============================================================ + // + // enum SCMetaKind + // { + // SC_META_V0 = 0 + // }; + // + // =========================================================================== + xdr["enum"]("ScMetaKind", { + scMetaV0: 0 + }); + + // === xdr source ============================================================ + // + // union SCMetaEntry switch (SCMetaKind kind) + // { + // case SC_META_V0: + // SCMetaV0 v0; + // }; + // + // =========================================================================== + xdr.union("ScMetaEntry", { + switchOn: xdr.lookup("ScMetaKind"), + switchName: "kind", + switches: [["scMetaV0", "v0"]], + arms: { + v0: xdr.lookup("ScMetaV0") + } + }); + + // === xdr source ============================================================ + // + // const SC_SPEC_DOC_LIMIT = 1024; + // + // =========================================================================== + xdr["const"]("SC_SPEC_DOC_LIMIT", 1024); + + // === xdr source ============================================================ + // + // enum SCSpecType + // { + // SC_SPEC_TYPE_VAL = 0, + // + // // Types with no parameters. + // SC_SPEC_TYPE_BOOL = 1, + // SC_SPEC_TYPE_VOID = 2, + // SC_SPEC_TYPE_ERROR = 3, + // SC_SPEC_TYPE_U32 = 4, + // SC_SPEC_TYPE_I32 = 5, + // SC_SPEC_TYPE_U64 = 6, + // SC_SPEC_TYPE_I64 = 7, + // SC_SPEC_TYPE_TIMEPOINT = 8, + // SC_SPEC_TYPE_DURATION = 9, + // SC_SPEC_TYPE_U128 = 10, + // SC_SPEC_TYPE_I128 = 11, + // SC_SPEC_TYPE_U256 = 12, + // SC_SPEC_TYPE_I256 = 13, + // SC_SPEC_TYPE_BYTES = 14, + // SC_SPEC_TYPE_STRING = 16, + // SC_SPEC_TYPE_SYMBOL = 17, + // SC_SPEC_TYPE_ADDRESS = 19, + // + // // Types with parameters. + // SC_SPEC_TYPE_OPTION = 1000, + // SC_SPEC_TYPE_RESULT = 1001, + // SC_SPEC_TYPE_VEC = 1002, + // SC_SPEC_TYPE_MAP = 1004, + // SC_SPEC_TYPE_TUPLE = 1005, + // SC_SPEC_TYPE_BYTES_N = 1006, + // + // // User defined types. + // SC_SPEC_TYPE_UDT = 2000 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecType", { + scSpecTypeVal: 0, + scSpecTypeBool: 1, + scSpecTypeVoid: 2, + scSpecTypeError: 3, + scSpecTypeU32: 4, + scSpecTypeI32: 5, + scSpecTypeU64: 6, + scSpecTypeI64: 7, + scSpecTypeTimepoint: 8, + scSpecTypeDuration: 9, + scSpecTypeU128: 10, + scSpecTypeI128: 11, + scSpecTypeU256: 12, + scSpecTypeI256: 13, + scSpecTypeBytes: 14, + scSpecTypeString: 16, + scSpecTypeSymbol: 17, + scSpecTypeAddress: 19, + scSpecTypeOption: 1000, + scSpecTypeResult: 1001, + scSpecTypeVec: 1002, + scSpecTypeMap: 1004, + scSpecTypeTuple: 1005, + scSpecTypeBytesN: 1006, + scSpecTypeUdt: 2000 + }); + + // === xdr source ============================================================ + // + // struct SCSpecTypeOption + // { + // SCSpecTypeDef valueType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeOption", [["valueType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeResult + // { + // SCSpecTypeDef okType; + // SCSpecTypeDef errorType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeResult", [["okType", xdr.lookup("ScSpecTypeDef")], ["errorType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeVec + // { + // SCSpecTypeDef elementType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeVec", [["elementType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeMap + // { + // SCSpecTypeDef keyType; + // SCSpecTypeDef valueType; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeMap", [["keyType", xdr.lookup("ScSpecTypeDef")], ["valueType", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeTuple + // { + // SCSpecTypeDef valueTypes<12>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeTuple", [["valueTypes", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 12)]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeBytesN + // { + // uint32 n; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeBytesN", [["n", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecTypeUDT + // { + // string name<60>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecTypeUdt", [["name", xdr.string(60)]]); + + // === xdr source ============================================================ + // + // union SCSpecTypeDef switch (SCSpecType type) + // { + // case SC_SPEC_TYPE_VAL: + // case SC_SPEC_TYPE_BOOL: + // case SC_SPEC_TYPE_VOID: + // case SC_SPEC_TYPE_ERROR: + // case SC_SPEC_TYPE_U32: + // case SC_SPEC_TYPE_I32: + // case SC_SPEC_TYPE_U64: + // case SC_SPEC_TYPE_I64: + // case SC_SPEC_TYPE_TIMEPOINT: + // case SC_SPEC_TYPE_DURATION: + // case SC_SPEC_TYPE_U128: + // case SC_SPEC_TYPE_I128: + // case SC_SPEC_TYPE_U256: + // case SC_SPEC_TYPE_I256: + // case SC_SPEC_TYPE_BYTES: + // case SC_SPEC_TYPE_STRING: + // case SC_SPEC_TYPE_SYMBOL: + // case SC_SPEC_TYPE_ADDRESS: + // void; + // case SC_SPEC_TYPE_OPTION: + // SCSpecTypeOption option; + // case SC_SPEC_TYPE_RESULT: + // SCSpecTypeResult result; + // case SC_SPEC_TYPE_VEC: + // SCSpecTypeVec vec; + // case SC_SPEC_TYPE_MAP: + // SCSpecTypeMap map; + // case SC_SPEC_TYPE_TUPLE: + // SCSpecTypeTuple tuple; + // case SC_SPEC_TYPE_BYTES_N: + // SCSpecTypeBytesN bytesN; + // case SC_SPEC_TYPE_UDT: + // SCSpecTypeUDT udt; + // }; + // + // =========================================================================== + xdr.union("ScSpecTypeDef", { + switchOn: xdr.lookup("ScSpecType"), + switchName: "type", + switches: [["scSpecTypeVal", xdr["void"]()], ["scSpecTypeBool", xdr["void"]()], ["scSpecTypeVoid", xdr["void"]()], ["scSpecTypeError", xdr["void"]()], ["scSpecTypeU32", xdr["void"]()], ["scSpecTypeI32", xdr["void"]()], ["scSpecTypeU64", xdr["void"]()], ["scSpecTypeI64", xdr["void"]()], ["scSpecTypeTimepoint", xdr["void"]()], ["scSpecTypeDuration", xdr["void"]()], ["scSpecTypeU128", xdr["void"]()], ["scSpecTypeI128", xdr["void"]()], ["scSpecTypeU256", xdr["void"]()], ["scSpecTypeI256", xdr["void"]()], ["scSpecTypeBytes", xdr["void"]()], ["scSpecTypeString", xdr["void"]()], ["scSpecTypeSymbol", xdr["void"]()], ["scSpecTypeAddress", xdr["void"]()], ["scSpecTypeOption", "option"], ["scSpecTypeResult", "result"], ["scSpecTypeVec", "vec"], ["scSpecTypeMap", "map"], ["scSpecTypeTuple", "tuple"], ["scSpecTypeBytesN", "bytesN"], ["scSpecTypeUdt", "udt"]], + arms: { + option: xdr.lookup("ScSpecTypeOption"), + result: xdr.lookup("ScSpecTypeResult"), + vec: xdr.lookup("ScSpecTypeVec"), + map: xdr.lookup("ScSpecTypeMap"), + tuple: xdr.lookup("ScSpecTypeTuple"), + bytesN: xdr.lookup("ScSpecTypeBytesN"), + udt: xdr.lookup("ScSpecTypeUdt") + } + }); + + // === xdr source ============================================================ + // + // struct SCSpecUDTStructFieldV0 + // { + // string doc; + // string name<30>; + // SCSpecTypeDef type; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtStructFieldV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(30)], ["type", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTStructV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTStructFieldV0 fields<40>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtStructV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["fields", xdr.varArray(xdr.lookup("ScSpecUdtStructFieldV0"), 40)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionCaseVoidV0 + // { + // string doc; + // string name<60>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionCaseVoidV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionCaseTupleV0 + // { + // string doc; + // string name<60>; + // SCSpecTypeDef type<12>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionCaseTupleV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["type", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 12)]]); + + // === xdr source ============================================================ + // + // enum SCSpecUDTUnionCaseV0Kind + // { + // SC_SPEC_UDT_UNION_CASE_VOID_V0 = 0, + // SC_SPEC_UDT_UNION_CASE_TUPLE_V0 = 1 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecUdtUnionCaseV0Kind", { + scSpecUdtUnionCaseVoidV0: 0, + scSpecUdtUnionCaseTupleV0: 1 + }); + + // === xdr source ============================================================ + // + // union SCSpecUDTUnionCaseV0 switch (SCSpecUDTUnionCaseV0Kind kind) + // { + // case SC_SPEC_UDT_UNION_CASE_VOID_V0: + // SCSpecUDTUnionCaseVoidV0 voidCase; + // case SC_SPEC_UDT_UNION_CASE_TUPLE_V0: + // SCSpecUDTUnionCaseTupleV0 tupleCase; + // }; + // + // =========================================================================== + xdr.union("ScSpecUdtUnionCaseV0", { + switchOn: xdr.lookup("ScSpecUdtUnionCaseV0Kind"), + switchName: "kind", + switches: [["scSpecUdtUnionCaseVoidV0", "voidCase"], ["scSpecUdtUnionCaseTupleV0", "tupleCase"]], + arms: { + voidCase: xdr.lookup("ScSpecUdtUnionCaseVoidV0"), + tupleCase: xdr.lookup("ScSpecUdtUnionCaseTupleV0") + } + }); + + // === xdr source ============================================================ + // + // struct SCSpecUDTUnionV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTUnionCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtUnionV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtUnionCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTEnumCaseV0 + // { + // string doc; + // string name<60>; + // uint32 value; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtEnumCaseV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["value", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTEnumV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTEnumCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtEnumV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtEnumCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTErrorEnumCaseV0 + // { + // string doc; + // string name<60>; + // uint32 value; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtErrorEnumCaseV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(60)], ["value", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct SCSpecUDTErrorEnumV0 + // { + // string doc; + // string lib<80>; + // string name<60>; + // SCSpecUDTErrorEnumCaseV0 cases<50>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecUdtErrorEnumV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["lib", xdr.string(80)], ["name", xdr.string(60)], ["cases", xdr.varArray(xdr.lookup("ScSpecUdtErrorEnumCaseV0"), 50)]]); + + // === xdr source ============================================================ + // + // struct SCSpecFunctionInputV0 + // { + // string doc; + // string name<30>; + // SCSpecTypeDef type; + // }; + // + // =========================================================================== + xdr.struct("ScSpecFunctionInputV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.string(30)], ["type", xdr.lookup("ScSpecTypeDef")]]); + + // === xdr source ============================================================ + // + // struct SCSpecFunctionV0 + // { + // string doc; + // SCSymbol name; + // SCSpecFunctionInputV0 inputs<10>; + // SCSpecTypeDef outputs<1>; + // }; + // + // =========================================================================== + xdr.struct("ScSpecFunctionV0", [["doc", xdr.string(SC_SPEC_DOC_LIMIT)], ["name", xdr.lookup("ScSymbol")], ["inputs", xdr.varArray(xdr.lookup("ScSpecFunctionInputV0"), 10)], ["outputs", xdr.varArray(xdr.lookup("ScSpecTypeDef"), 1)]]); + + // === xdr source ============================================================ + // + // enum SCSpecEntryKind + // { + // SC_SPEC_ENTRY_FUNCTION_V0 = 0, + // SC_SPEC_ENTRY_UDT_STRUCT_V0 = 1, + // SC_SPEC_ENTRY_UDT_UNION_V0 = 2, + // SC_SPEC_ENTRY_UDT_ENUM_V0 = 3, + // SC_SPEC_ENTRY_UDT_ERROR_ENUM_V0 = 4 + // }; + // + // =========================================================================== + xdr["enum"]("ScSpecEntryKind", { + scSpecEntryFunctionV0: 0, + scSpecEntryUdtStructV0: 1, + scSpecEntryUdtUnionV0: 2, + scSpecEntryUdtEnumV0: 3, + scSpecEntryUdtErrorEnumV0: 4 + }); + + // === xdr source ============================================================ + // + // union SCSpecEntry switch (SCSpecEntryKind kind) + // { + // case SC_SPEC_ENTRY_FUNCTION_V0: + // SCSpecFunctionV0 functionV0; + // case SC_SPEC_ENTRY_UDT_STRUCT_V0: + // SCSpecUDTStructV0 udtStructV0; + // case SC_SPEC_ENTRY_UDT_UNION_V0: + // SCSpecUDTUnionV0 udtUnionV0; + // case SC_SPEC_ENTRY_UDT_ENUM_V0: + // SCSpecUDTEnumV0 udtEnumV0; + // case SC_SPEC_ENTRY_UDT_ERROR_ENUM_V0: + // SCSpecUDTErrorEnumV0 udtErrorEnumV0; + // }; + // + // =========================================================================== + xdr.union("ScSpecEntry", { + switchOn: xdr.lookup("ScSpecEntryKind"), + switchName: "kind", + switches: [["scSpecEntryFunctionV0", "functionV0"], ["scSpecEntryUdtStructV0", "udtStructV0"], ["scSpecEntryUdtUnionV0", "udtUnionV0"], ["scSpecEntryUdtEnumV0", "udtEnumV0"], ["scSpecEntryUdtErrorEnumV0", "udtErrorEnumV0"]], + arms: { + functionV0: xdr.lookup("ScSpecFunctionV0"), + udtStructV0: xdr.lookup("ScSpecUdtStructV0"), + udtUnionV0: xdr.lookup("ScSpecUdtUnionV0"), + udtEnumV0: xdr.lookup("ScSpecUdtEnumV0"), + udtErrorEnumV0: xdr.lookup("ScSpecUdtErrorEnumV0") + } + }); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractExecutionLanesV0 + // { + // // maximum number of Soroban transactions per ledger + // uint32 ledgerMaxTxCount; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractExecutionLanesV0", [["ledgerMaxTxCount", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractComputeV0 + // { + // // Maximum instructions per ledger + // int64 ledgerMaxInstructions; + // // Maximum instructions per transaction + // int64 txMaxInstructions; + // // Cost of 10000 instructions + // int64 feeRatePerInstructionsIncrement; + // + // // Memory limit per transaction. Unlike instructions, there is no fee + // // for memory, just the limit. + // uint32 txMemoryLimit; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractComputeV0", [["ledgerMaxInstructions", xdr.lookup("Int64")], ["txMaxInstructions", xdr.lookup("Int64")], ["feeRatePerInstructionsIncrement", xdr.lookup("Int64")], ["txMemoryLimit", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractLedgerCostV0 + // { + // // Maximum number of ledger entry read operations per ledger + // uint32 ledgerMaxReadLedgerEntries; + // // Maximum number of bytes that can be read per ledger + // uint32 ledgerMaxReadBytes; + // // Maximum number of ledger entry write operations per ledger + // uint32 ledgerMaxWriteLedgerEntries; + // // Maximum number of bytes that can be written per ledger + // uint32 ledgerMaxWriteBytes; + // + // // Maximum number of ledger entry read operations per transaction + // uint32 txMaxReadLedgerEntries; + // // Maximum number of bytes that can be read per transaction + // uint32 txMaxReadBytes; + // // Maximum number of ledger entry write operations per transaction + // uint32 txMaxWriteLedgerEntries; + // // Maximum number of bytes that can be written per transaction + // uint32 txMaxWriteBytes; + // + // int64 feeReadLedgerEntry; // Fee per ledger entry read + // int64 feeWriteLedgerEntry; // Fee per ledger entry write + // + // int64 feeRead1KB; // Fee for reading 1KB + // + // // The following parameters determine the write fee per 1KB. + // // Write fee grows linearly until bucket list reaches this size + // int64 bucketListTargetSizeBytes; + // // Fee per 1KB write when the bucket list is empty + // int64 writeFee1KBBucketListLow; + // // Fee per 1KB write when the bucket list has reached `bucketListTargetSizeBytes` + // int64 writeFee1KBBucketListHigh; + // // Write fee multiplier for any additional data past the first `bucketListTargetSizeBytes` + // uint32 bucketListWriteFeeGrowthFactor; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractLedgerCostV0", [["ledgerMaxReadLedgerEntries", xdr.lookup("Uint32")], ["ledgerMaxReadBytes", xdr.lookup("Uint32")], ["ledgerMaxWriteLedgerEntries", xdr.lookup("Uint32")], ["ledgerMaxWriteBytes", xdr.lookup("Uint32")], ["txMaxReadLedgerEntries", xdr.lookup("Uint32")], ["txMaxReadBytes", xdr.lookup("Uint32")], ["txMaxWriteLedgerEntries", xdr.lookup("Uint32")], ["txMaxWriteBytes", xdr.lookup("Uint32")], ["feeReadLedgerEntry", xdr.lookup("Int64")], ["feeWriteLedgerEntry", xdr.lookup("Int64")], ["feeRead1Kb", xdr.lookup("Int64")], ["bucketListTargetSizeBytes", xdr.lookup("Int64")], ["writeFee1KbBucketListLow", xdr.lookup("Int64")], ["writeFee1KbBucketListHigh", xdr.lookup("Int64")], ["bucketListWriteFeeGrowthFactor", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractHistoricalDataV0 + // { + // int64 feeHistorical1KB; // Fee for storing 1KB in archives + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractHistoricalDataV0", [["feeHistorical1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractEventsV0 + // { + // // Maximum size of events that a contract call can emit. + // uint32 txMaxContractEventsSizeBytes; + // // Fee for generating 1KB of contract events. + // int64 feeContractEvents1KB; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractEventsV0", [["txMaxContractEventsSizeBytes", xdr.lookup("Uint32")], ["feeContractEvents1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct ConfigSettingContractBandwidthV0 + // { + // // Maximum sum of all transaction sizes in the ledger in bytes + // uint32 ledgerMaxTxsSizeBytes; + // // Maximum size in bytes for a transaction + // uint32 txMaxSizeBytes; + // + // // Fee for 1 KB of transaction size + // int64 feeTxSize1KB; + // }; + // + // =========================================================================== + xdr.struct("ConfigSettingContractBandwidthV0", [["ledgerMaxTxsSizeBytes", xdr.lookup("Uint32")], ["txMaxSizeBytes", xdr.lookup("Uint32")], ["feeTxSize1Kb", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // enum ContractCostType { + // // Cost of running 1 wasm instruction + // WasmInsnExec = 0, + // // Cost of allocating a slice of memory (in bytes) + // MemAlloc = 1, + // // Cost of copying a slice of bytes into a pre-allocated memory + // MemCpy = 2, + // // Cost of comparing two slices of memory + // MemCmp = 3, + // // Cost of a host function dispatch, not including the actual work done by + // // the function nor the cost of VM invocation machinary + // DispatchHostFunction = 4, + // // Cost of visiting a host object from the host object storage. Exists to + // // make sure some baseline cost coverage, i.e. repeatly visiting objects + // // by the guest will always incur some charges. + // VisitObject = 5, + // // Cost of serializing an xdr object to bytes + // ValSer = 6, + // // Cost of deserializing an xdr object from bytes + // ValDeser = 7, + // // Cost of computing the sha256 hash from bytes + // ComputeSha256Hash = 8, + // // Cost of computing the ed25519 pubkey from bytes + // ComputeEd25519PubKey = 9, + // // Cost of verifying ed25519 signature of a payload. + // VerifyEd25519Sig = 10, + // // Cost of instantiation a VM from wasm bytes code. + // VmInstantiation = 11, + // // Cost of instantiation a VM from a cached state. + // VmCachedInstantiation = 12, + // // Cost of invoking a function on the VM. If the function is a host function, + // // additional cost will be covered by `DispatchHostFunction`. + // InvokeVmFunction = 13, + // // Cost of computing a keccak256 hash from bytes. + // ComputeKeccak256Hash = 14, + // // Cost of decoding an ECDSA signature computed from a 256-bit prime modulus + // // curve (e.g. secp256k1 and secp256r1) + // DecodeEcdsaCurve256Sig = 15, + // // Cost of recovering an ECDSA secp256k1 key from a signature. + // RecoverEcdsaSecp256k1Key = 16, + // // Cost of int256 addition (`+`) and subtraction (`-`) operations + // Int256AddSub = 17, + // // Cost of int256 multiplication (`*`) operation + // Int256Mul = 18, + // // Cost of int256 division (`/`) operation + // Int256Div = 19, + // // Cost of int256 power (`exp`) operation + // Int256Pow = 20, + // // Cost of int256 shift (`shl`, `shr`) operation + // Int256Shift = 21, + // // Cost of drawing random bytes using a ChaCha20 PRNG + // ChaCha20DrawBytes = 22, + // + // // Cost of parsing wasm bytes that only encode instructions. + // ParseWasmInstructions = 23, + // // Cost of parsing a known number of wasm functions. + // ParseWasmFunctions = 24, + // // Cost of parsing a known number of wasm globals. + // ParseWasmGlobals = 25, + // // Cost of parsing a known number of wasm table entries. + // ParseWasmTableEntries = 26, + // // Cost of parsing a known number of wasm types. + // ParseWasmTypes = 27, + // // Cost of parsing a known number of wasm data segments. + // ParseWasmDataSegments = 28, + // // Cost of parsing a known number of wasm element segments. + // ParseWasmElemSegments = 29, + // // Cost of parsing a known number of wasm imports. + // ParseWasmImports = 30, + // // Cost of parsing a known number of wasm exports. + // ParseWasmExports = 31, + // // Cost of parsing a known number of data segment bytes. + // ParseWasmDataSegmentBytes = 32, + // + // // Cost of instantiating wasm bytes that only encode instructions. + // InstantiateWasmInstructions = 33, + // // Cost of instantiating a known number of wasm functions. + // InstantiateWasmFunctions = 34, + // // Cost of instantiating a known number of wasm globals. + // InstantiateWasmGlobals = 35, + // // Cost of instantiating a known number of wasm table entries. + // InstantiateWasmTableEntries = 36, + // // Cost of instantiating a known number of wasm types. + // InstantiateWasmTypes = 37, + // // Cost of instantiating a known number of wasm data segments. + // InstantiateWasmDataSegments = 38, + // // Cost of instantiating a known number of wasm element segments. + // InstantiateWasmElemSegments = 39, + // // Cost of instantiating a known number of wasm imports. + // InstantiateWasmImports = 40, + // // Cost of instantiating a known number of wasm exports. + // InstantiateWasmExports = 41, + // // Cost of instantiating a known number of data segment bytes. + // InstantiateWasmDataSegmentBytes = 42, + // + // // Cost of decoding a bytes array representing an uncompressed SEC-1 encoded + // // point on a 256-bit elliptic curve + // Sec1DecodePointUncompressed = 43, + // // Cost of verifying an ECDSA Secp256r1 signature + // VerifyEcdsaSecp256r1Sig = 44, + // + // // Cost of encoding a BLS12-381 Fp (base field element) + // Bls12381EncodeFp = 45, + // // Cost of decoding a BLS12-381 Fp (base field element) + // Bls12381DecodeFp = 46, + // // Cost of checking a G1 point lies on the curve + // Bls12381G1CheckPointOnCurve = 47, + // // Cost of checking a G1 point belongs to the correct subgroup + // Bls12381G1CheckPointInSubgroup = 48, + // // Cost of checking a G2 point lies on the curve + // Bls12381G2CheckPointOnCurve = 49, + // // Cost of checking a G2 point belongs to the correct subgroup + // Bls12381G2CheckPointInSubgroup = 50, + // // Cost of converting a BLS12-381 G1 point from projective to affine coordinates + // Bls12381G1ProjectiveToAffine = 51, + // // Cost of converting a BLS12-381 G2 point from projective to affine coordinates + // Bls12381G2ProjectiveToAffine = 52, + // // Cost of performing BLS12-381 G1 point addition + // Bls12381G1Add = 53, + // // Cost of performing BLS12-381 G1 scalar multiplication + // Bls12381G1Mul = 54, + // // Cost of performing BLS12-381 G1 multi-scalar multiplication (MSM) + // Bls12381G1Msm = 55, + // // Cost of mapping a BLS12-381 Fp field element to a G1 point + // Bls12381MapFpToG1 = 56, + // // Cost of hashing to a BLS12-381 G1 point + // Bls12381HashToG1 = 57, + // // Cost of performing BLS12-381 G2 point addition + // Bls12381G2Add = 58, + // // Cost of performing BLS12-381 G2 scalar multiplication + // Bls12381G2Mul = 59, + // // Cost of performing BLS12-381 G2 multi-scalar multiplication (MSM) + // Bls12381G2Msm = 60, + // // Cost of mapping a BLS12-381 Fp2 field element to a G2 point + // Bls12381MapFp2ToG2 = 61, + // // Cost of hashing to a BLS12-381 G2 point + // Bls12381HashToG2 = 62, + // // Cost of performing BLS12-381 pairing operation + // Bls12381Pairing = 63, + // // Cost of converting a BLS12-381 scalar element from U256 + // Bls12381FrFromU256 = 64, + // // Cost of converting a BLS12-381 scalar element to U256 + // Bls12381FrToU256 = 65, + // // Cost of performing BLS12-381 scalar element addition/subtraction + // Bls12381FrAddSub = 66, + // // Cost of performing BLS12-381 scalar element multiplication + // Bls12381FrMul = 67, + // // Cost of performing BLS12-381 scalar element exponentiation + // Bls12381FrPow = 68, + // // Cost of performing BLS12-381 scalar element inversion + // Bls12381FrInv = 69 + // }; + // + // =========================================================================== + xdr["enum"]("ContractCostType", { + wasmInsnExec: 0, + memAlloc: 1, + memCpy: 2, + memCmp: 3, + dispatchHostFunction: 4, + visitObject: 5, + valSer: 6, + valDeser: 7, + computeSha256Hash: 8, + computeEd25519PubKey: 9, + verifyEd25519Sig: 10, + vmInstantiation: 11, + vmCachedInstantiation: 12, + invokeVmFunction: 13, + computeKeccak256Hash: 14, + decodeEcdsaCurve256Sig: 15, + recoverEcdsaSecp256k1Key: 16, + int256AddSub: 17, + int256Mul: 18, + int256Div: 19, + int256Pow: 20, + int256Shift: 21, + chaCha20DrawBytes: 22, + parseWasmInstructions: 23, + parseWasmFunctions: 24, + parseWasmGlobals: 25, + parseWasmTableEntries: 26, + parseWasmTypes: 27, + parseWasmDataSegments: 28, + parseWasmElemSegments: 29, + parseWasmImports: 30, + parseWasmExports: 31, + parseWasmDataSegmentBytes: 32, + instantiateWasmInstructions: 33, + instantiateWasmFunctions: 34, + instantiateWasmGlobals: 35, + instantiateWasmTableEntries: 36, + instantiateWasmTypes: 37, + instantiateWasmDataSegments: 38, + instantiateWasmElemSegments: 39, + instantiateWasmImports: 40, + instantiateWasmExports: 41, + instantiateWasmDataSegmentBytes: 42, + sec1DecodePointUncompressed: 43, + verifyEcdsaSecp256r1Sig: 44, + bls12381EncodeFp: 45, + bls12381DecodeFp: 46, + bls12381G1CheckPointOnCurve: 47, + bls12381G1CheckPointInSubgroup: 48, + bls12381G2CheckPointOnCurve: 49, + bls12381G2CheckPointInSubgroup: 50, + bls12381G1ProjectiveToAffine: 51, + bls12381G2ProjectiveToAffine: 52, + bls12381G1Add: 53, + bls12381G1Mul: 54, + bls12381G1Msm: 55, + bls12381MapFpToG1: 56, + bls12381HashToG1: 57, + bls12381G2Add: 58, + bls12381G2Mul: 59, + bls12381G2Msm: 60, + bls12381MapFp2ToG2: 61, + bls12381HashToG2: 62, + bls12381Pairing: 63, + bls12381FrFromU256: 64, + bls12381FrToU256: 65, + bls12381FrAddSub: 66, + bls12381FrMul: 67, + bls12381FrPow: 68, + bls12381FrInv: 69 + }); + + // === xdr source ============================================================ + // + // struct ContractCostParamEntry { + // // use `ext` to add more terms (e.g. higher order polynomials) in the future + // ExtensionPoint ext; + // + // int64 constTerm; + // int64 linearTerm; + // }; + // + // =========================================================================== + xdr.struct("ContractCostParamEntry", [["ext", xdr.lookup("ExtensionPoint")], ["constTerm", xdr.lookup("Int64")], ["linearTerm", xdr.lookup("Int64")]]); + + // === xdr source ============================================================ + // + // struct StateArchivalSettings { + // uint32 maxEntryTTL; + // uint32 minTemporaryTTL; + // uint32 minPersistentTTL; + // + // // rent_fee = wfee_rate_average / rent_rate_denominator_for_type + // int64 persistentRentRateDenominator; + // int64 tempRentRateDenominator; + // + // // max number of entries that emit archival meta in a single ledger + // uint32 maxEntriesToArchive; + // + // // Number of snapshots to use when calculating average BucketList size + // uint32 bucketListSizeWindowSampleSize; + // + // // How often to sample the BucketList size for the average, in ledgers + // uint32 bucketListWindowSamplePeriod; + // + // // Maximum number of bytes that we scan for eviction per ledger + // uint32 evictionScanSize; + // + // // Lowest BucketList level to be scanned to evict entries + // uint32 startingEvictionScanLevel; + // }; + // + // =========================================================================== + xdr.struct("StateArchivalSettings", [["maxEntryTtl", xdr.lookup("Uint32")], ["minTemporaryTtl", xdr.lookup("Uint32")], ["minPersistentTtl", xdr.lookup("Uint32")], ["persistentRentRateDenominator", xdr.lookup("Int64")], ["tempRentRateDenominator", xdr.lookup("Int64")], ["maxEntriesToArchive", xdr.lookup("Uint32")], ["bucketListSizeWindowSampleSize", xdr.lookup("Uint32")], ["bucketListWindowSamplePeriod", xdr.lookup("Uint32")], ["evictionScanSize", xdr.lookup("Uint32")], ["startingEvictionScanLevel", xdr.lookup("Uint32")]]); + + // === xdr source ============================================================ + // + // struct EvictionIterator { + // uint32 bucketListLevel; + // bool isCurrBucket; + // uint64 bucketFileOffset; + // }; + // + // =========================================================================== + xdr.struct("EvictionIterator", [["bucketListLevel", xdr.lookup("Uint32")], ["isCurrBucket", xdr.bool()], ["bucketFileOffset", xdr.lookup("Uint64")]]); + + // === xdr source ============================================================ + // + // const CONTRACT_COST_COUNT_LIMIT = 1024; + // + // =========================================================================== + xdr["const"]("CONTRACT_COST_COUNT_LIMIT", 1024); + + // === xdr source ============================================================ + // + // typedef ContractCostParamEntry ContractCostParams; + // + // =========================================================================== + xdr.typedef("ContractCostParams", xdr.varArray(xdr.lookup("ContractCostParamEntry"), xdr.lookup("CONTRACT_COST_COUNT_LIMIT"))); + + // === xdr source ============================================================ + // + // enum ConfigSettingID + // { + // CONFIG_SETTING_CONTRACT_MAX_SIZE_BYTES = 0, + // CONFIG_SETTING_CONTRACT_COMPUTE_V0 = 1, + // CONFIG_SETTING_CONTRACT_LEDGER_COST_V0 = 2, + // CONFIG_SETTING_CONTRACT_HISTORICAL_DATA_V0 = 3, + // CONFIG_SETTING_CONTRACT_EVENTS_V0 = 4, + // CONFIG_SETTING_CONTRACT_BANDWIDTH_V0 = 5, + // CONFIG_SETTING_CONTRACT_COST_PARAMS_CPU_INSTRUCTIONS = 6, + // CONFIG_SETTING_CONTRACT_COST_PARAMS_MEMORY_BYTES = 7, + // CONFIG_SETTING_CONTRACT_DATA_KEY_SIZE_BYTES = 8, + // CONFIG_SETTING_CONTRACT_DATA_ENTRY_SIZE_BYTES = 9, + // CONFIG_SETTING_STATE_ARCHIVAL = 10, + // CONFIG_SETTING_CONTRACT_EXECUTION_LANES = 11, + // CONFIG_SETTING_BUCKETLIST_SIZE_WINDOW = 12, + // CONFIG_SETTING_EVICTION_ITERATOR = 13 + // }; + // + // =========================================================================== + xdr["enum"]("ConfigSettingId", { + configSettingContractMaxSizeBytes: 0, + configSettingContractComputeV0: 1, + configSettingContractLedgerCostV0: 2, + configSettingContractHistoricalDataV0: 3, + configSettingContractEventsV0: 4, + configSettingContractBandwidthV0: 5, + configSettingContractCostParamsCpuInstructions: 6, + configSettingContractCostParamsMemoryBytes: 7, + configSettingContractDataKeySizeBytes: 8, + configSettingContractDataEntrySizeBytes: 9, + configSettingStateArchival: 10, + configSettingContractExecutionLanes: 11, + configSettingBucketlistSizeWindow: 12, + configSettingEvictionIterator: 13 + }); + + // === xdr source ============================================================ + // + // union ConfigSettingEntry switch (ConfigSettingID configSettingID) + // { + // case CONFIG_SETTING_CONTRACT_MAX_SIZE_BYTES: + // uint32 contractMaxSizeBytes; + // case CONFIG_SETTING_CONTRACT_COMPUTE_V0: + // ConfigSettingContractComputeV0 contractCompute; + // case CONFIG_SETTING_CONTRACT_LEDGER_COST_V0: + // ConfigSettingContractLedgerCostV0 contractLedgerCost; + // case CONFIG_SETTING_CONTRACT_HISTORICAL_DATA_V0: + // ConfigSettingContractHistoricalDataV0 contractHistoricalData; + // case CONFIG_SETTING_CONTRACT_EVENTS_V0: + // ConfigSettingContractEventsV0 contractEvents; + // case CONFIG_SETTING_CONTRACT_BANDWIDTH_V0: + // ConfigSettingContractBandwidthV0 contractBandwidth; + // case CONFIG_SETTING_CONTRACT_COST_PARAMS_CPU_INSTRUCTIONS: + // ContractCostParams contractCostParamsCpuInsns; + // case CONFIG_SETTING_CONTRACT_COST_PARAMS_MEMORY_BYTES: + // ContractCostParams contractCostParamsMemBytes; + // case CONFIG_SETTING_CONTRACT_DATA_KEY_SIZE_BYTES: + // uint32 contractDataKeySizeBytes; + // case CONFIG_SETTING_CONTRACT_DATA_ENTRY_SIZE_BYTES: + // uint32 contractDataEntrySizeBytes; + // case CONFIG_SETTING_STATE_ARCHIVAL: + // StateArchivalSettings stateArchivalSettings; + // case CONFIG_SETTING_CONTRACT_EXECUTION_LANES: + // ConfigSettingContractExecutionLanesV0 contractExecutionLanes; + // case CONFIG_SETTING_BUCKETLIST_SIZE_WINDOW: + // uint64 bucketListSizeWindow<>; + // case CONFIG_SETTING_EVICTION_ITERATOR: + // EvictionIterator evictionIterator; + // }; + // + // =========================================================================== + xdr.union("ConfigSettingEntry", { + switchOn: xdr.lookup("ConfigSettingId"), + switchName: "configSettingId", + switches: [["configSettingContractMaxSizeBytes", "contractMaxSizeBytes"], ["configSettingContractComputeV0", "contractCompute"], ["configSettingContractLedgerCostV0", "contractLedgerCost"], ["configSettingContractHistoricalDataV0", "contractHistoricalData"], ["configSettingContractEventsV0", "contractEvents"], ["configSettingContractBandwidthV0", "contractBandwidth"], ["configSettingContractCostParamsCpuInstructions", "contractCostParamsCpuInsns"], ["configSettingContractCostParamsMemoryBytes", "contractCostParamsMemBytes"], ["configSettingContractDataKeySizeBytes", "contractDataKeySizeBytes"], ["configSettingContractDataEntrySizeBytes", "contractDataEntrySizeBytes"], ["configSettingStateArchival", "stateArchivalSettings"], ["configSettingContractExecutionLanes", "contractExecutionLanes"], ["configSettingBucketlistSizeWindow", "bucketListSizeWindow"], ["configSettingEvictionIterator", "evictionIterator"]], + arms: { + contractMaxSizeBytes: xdr.lookup("Uint32"), + contractCompute: xdr.lookup("ConfigSettingContractComputeV0"), + contractLedgerCost: xdr.lookup("ConfigSettingContractLedgerCostV0"), + contractHistoricalData: xdr.lookup("ConfigSettingContractHistoricalDataV0"), + contractEvents: xdr.lookup("ConfigSettingContractEventsV0"), + contractBandwidth: xdr.lookup("ConfigSettingContractBandwidthV0"), + contractCostParamsCpuInsns: xdr.lookup("ContractCostParams"), + contractCostParamsMemBytes: xdr.lookup("ContractCostParams"), + contractDataKeySizeBytes: xdr.lookup("Uint32"), + contractDataEntrySizeBytes: xdr.lookup("Uint32"), + stateArchivalSettings: xdr.lookup("StateArchivalSettings"), + contractExecutionLanes: xdr.lookup("ConfigSettingContractExecutionLanesV0"), + bucketListSizeWindow: xdr.varArray(xdr.lookup("Uint64"), 2147483647), + evictionIterator: xdr.lookup("EvictionIterator") + } + }); +}); +var _default = exports["default"] = types; + +/***/ }), + +/***/ 5578: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LiquidityPoolFeeV18 = void 0; +exports.getLiquidityPoolId = getLiquidityPoolId; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +var _hashing = __webpack_require__(9152); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +// LiquidityPoolFeeV18 is the default liquidity pool fee in protocol v18. It defaults to 30 base points (0.3%). +var LiquidityPoolFeeV18 = exports.LiquidityPoolFeeV18 = 30; + +/** + * getLiquidityPoolId computes the Pool ID for the given assets, fee and pool type. + * + * @see [stellar-core getPoolID](https://github.com/stellar/stellar-core/blob/9f3a48c6a8f1aa77b6043a055d0638661f718080/src/ledger/test/LedgerTxnTests.cpp#L3746-L3751) + * + * @export + * @param {string} liquidityPoolType – A string representing the liquidity pool type. + * @param {object} liquidityPoolParameters – The liquidity pool parameters. + * @param {Asset} liquidityPoolParameters.assetA – The first asset in the Pool, it must respect the rule assetA < assetB. + * @param {Asset} liquidityPoolParameters.assetB – The second asset in the Pool, it must respect the rule assetA < assetB. + * @param {number} liquidityPoolParameters.fee – The liquidity pool fee. For now the only fee supported is `30`. + * + * @return {Buffer} the raw Pool ID buffer, which can be stringfied with `toString('hex')` + */ +function getLiquidityPoolId(liquidityPoolType) { + var liquidityPoolParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (liquidityPoolType !== 'constant_product') { + throw new Error('liquidityPoolType is invalid'); + } + var assetA = liquidityPoolParameters.assetA, + assetB = liquidityPoolParameters.assetB, + fee = liquidityPoolParameters.fee; + if (!assetA || !(assetA instanceof _asset.Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof _asset.Asset)) { + throw new Error('assetB is invalid'); + } + if (!fee || fee !== LiquidityPoolFeeV18) { + throw new Error('fee is invalid'); + } + if (_asset.Asset.compare(assetA, assetB) !== -1) { + throw new Error('Assets are not in lexicographic order'); + } + var lpTypeData = _xdr["default"].LiquidityPoolType.liquidityPoolConstantProduct().toXDR(); + var lpParamsData = new _xdr["default"].LiquidityPoolConstantProductParameters({ + assetA: assetA.toXDRObject(), + assetB: assetB.toXDRObject(), + fee: fee + }).toXDR(); + var payload = Buffer.concat([lpTypeData, lpParamsData]); + return (0, _hashing.hash)(payload); +} + +/***/ }), + +/***/ 9152: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.hash = hash; +var _sha = __webpack_require__(2802); +function hash(data) { + var hasher = new _sha.sha256(); + hasher.update(data, 'utf8'); + return hasher.digest(); +} + +/***/ }), + +/***/ 356: +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _exportNames = { + xdr: true, + cereal: true, + hash: true, + sign: true, + verify: true, + FastSigning: true, + getLiquidityPoolId: true, + LiquidityPoolFeeV18: true, + Keypair: true, + UnsignedHyper: true, + Hyper: true, + TransactionBase: true, + Transaction: true, + FeeBumpTransaction: true, + TransactionBuilder: true, + TimeoutInfinite: true, + BASE_FEE: true, + Asset: true, + LiquidityPoolAsset: true, + LiquidityPoolId: true, + Operation: true, + AuthRequiredFlag: true, + AuthRevocableFlag: true, + AuthImmutableFlag: true, + AuthClawbackEnabledFlag: true, + Account: true, + MuxedAccount: true, + Claimant: true, + Networks: true, + StrKey: true, + SignerKey: true, + Soroban: true, + decodeAddressToMuxedAccount: true, + encodeMuxedAccountToAddress: true, + extractBaseAddress: true, + encodeMuxedAccount: true, + Contract: true, + Address: true +}; +Object.defineProperty(exports, "Account", ({ + enumerable: true, + get: function get() { + return _account.Account; + } +})); +Object.defineProperty(exports, "Address", ({ + enumerable: true, + get: function get() { + return _address.Address; + } +})); +Object.defineProperty(exports, "Asset", ({ + enumerable: true, + get: function get() { + return _asset.Asset; + } +})); +Object.defineProperty(exports, "AuthClawbackEnabledFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthClawbackEnabledFlag; + } +})); +Object.defineProperty(exports, "AuthImmutableFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthImmutableFlag; + } +})); +Object.defineProperty(exports, "AuthRequiredFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthRequiredFlag; + } +})); +Object.defineProperty(exports, "AuthRevocableFlag", ({ + enumerable: true, + get: function get() { + return _operation.AuthRevocableFlag; + } +})); +Object.defineProperty(exports, "BASE_FEE", ({ + enumerable: true, + get: function get() { + return _transaction_builder.BASE_FEE; + } +})); +Object.defineProperty(exports, "Claimant", ({ + enumerable: true, + get: function get() { + return _claimant.Claimant; + } +})); +Object.defineProperty(exports, "Contract", ({ + enumerable: true, + get: function get() { + return _contract.Contract; + } +})); +Object.defineProperty(exports, "FastSigning", ({ + enumerable: true, + get: function get() { + return _signing.FastSigning; + } +})); +Object.defineProperty(exports, "FeeBumpTransaction", ({ + enumerable: true, + get: function get() { + return _fee_bump_transaction.FeeBumpTransaction; + } +})); +Object.defineProperty(exports, "Hyper", ({ + enumerable: true, + get: function get() { + return _jsXdr.Hyper; + } +})); +Object.defineProperty(exports, "Keypair", ({ + enumerable: true, + get: function get() { + return _keypair.Keypair; + } +})); +Object.defineProperty(exports, "LiquidityPoolAsset", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_asset.LiquidityPoolAsset; + } +})); +Object.defineProperty(exports, "LiquidityPoolFeeV18", ({ + enumerable: true, + get: function get() { + return _get_liquidity_pool_id.LiquidityPoolFeeV18; + } +})); +Object.defineProperty(exports, "LiquidityPoolId", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_id.LiquidityPoolId; + } +})); +Object.defineProperty(exports, "MuxedAccount", ({ + enumerable: true, + get: function get() { + return _muxed_account.MuxedAccount; + } +})); +Object.defineProperty(exports, "Networks", ({ + enumerable: true, + get: function get() { + return _network.Networks; + } +})); +Object.defineProperty(exports, "Operation", ({ + enumerable: true, + get: function get() { + return _operation.Operation; + } +})); +Object.defineProperty(exports, "SignerKey", ({ + enumerable: true, + get: function get() { + return _signerkey.SignerKey; + } +})); +Object.defineProperty(exports, "Soroban", ({ + enumerable: true, + get: function get() { + return _soroban.Soroban; + } +})); +Object.defineProperty(exports, "StrKey", ({ + enumerable: true, + get: function get() { + return _strkey.StrKey; + } +})); +Object.defineProperty(exports, "TimeoutInfinite", ({ + enumerable: true, + get: function get() { + return _transaction_builder.TimeoutInfinite; + } +})); +Object.defineProperty(exports, "Transaction", ({ + enumerable: true, + get: function get() { + return _transaction.Transaction; + } +})); +Object.defineProperty(exports, "TransactionBase", ({ + enumerable: true, + get: function get() { + return _transaction_base.TransactionBase; + } +})); +Object.defineProperty(exports, "TransactionBuilder", ({ + enumerable: true, + get: function get() { + return _transaction_builder.TransactionBuilder; + } +})); +Object.defineProperty(exports, "UnsignedHyper", ({ + enumerable: true, + get: function get() { + return _jsXdr.UnsignedHyper; + } +})); +Object.defineProperty(exports, "cereal", ({ + enumerable: true, + get: function get() { + return _jsxdr["default"]; + } +})); +Object.defineProperty(exports, "decodeAddressToMuxedAccount", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.decodeAddressToMuxedAccount; + } +})); +exports["default"] = void 0; +Object.defineProperty(exports, "encodeMuxedAccount", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.encodeMuxedAccount; + } +})); +Object.defineProperty(exports, "encodeMuxedAccountToAddress", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.encodeMuxedAccountToAddress; + } +})); +Object.defineProperty(exports, "extractBaseAddress", ({ + enumerable: true, + get: function get() { + return _decode_encode_muxed_account.extractBaseAddress; + } +})); +Object.defineProperty(exports, "getLiquidityPoolId", ({ + enumerable: true, + get: function get() { + return _get_liquidity_pool_id.getLiquidityPoolId; + } +})); +Object.defineProperty(exports, "hash", ({ + enumerable: true, + get: function get() { + return _hashing.hash; + } +})); +Object.defineProperty(exports, "sign", ({ + enumerable: true, + get: function get() { + return _signing.sign; + } +})); +Object.defineProperty(exports, "verify", ({ + enumerable: true, + get: function get() { + return _signing.verify; + } +})); +Object.defineProperty(exports, "xdr", ({ + enumerable: true, + get: function get() { + return _xdr["default"]; + } +})); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _jsxdr = _interopRequireDefault(__webpack_require__(3335)); +var _hashing = __webpack_require__(9152); +var _signing = __webpack_require__(15); +var _get_liquidity_pool_id = __webpack_require__(5578); +var _keypair = __webpack_require__(6691); +var _jsXdr = __webpack_require__(3740); +var _transaction_base = __webpack_require__(3758); +var _transaction = __webpack_require__(380); +var _fee_bump_transaction = __webpack_require__(9260); +var _transaction_builder = __webpack_require__(6396); +var _asset = __webpack_require__(1764); +var _liquidity_pool_asset = __webpack_require__(2262); +var _liquidity_pool_id = __webpack_require__(9353); +var _operation = __webpack_require__(7237); +var _memo = __webpack_require__(4172); +Object.keys(_memo).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _memo[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _memo[key]; + } + }); +}); +var _account = __webpack_require__(2135); +var _muxed_account = __webpack_require__(2243); +var _claimant = __webpack_require__(1387); +var _network = __webpack_require__(6202); +var _strkey = __webpack_require__(7120); +var _signerkey = __webpack_require__(225); +var _soroban = __webpack_require__(4062); +var _decode_encode_muxed_account = __webpack_require__(6160); +var _contract = __webpack_require__(7452); +var _address = __webpack_require__(1180); +var _numbers = __webpack_require__(8549); +Object.keys(_numbers).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _numbers[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _numbers[key]; + } + }); +}); +var _scval = __webpack_require__(7177); +Object.keys(_scval).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _scval[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _scval[key]; + } + }); +}); +var _events = __webpack_require__(3919); +Object.keys(_events).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _events[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _events[key]; + } + }); +}); +var _sorobandata_builder = __webpack_require__(4842); +Object.keys(_sorobandata_builder).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _sorobandata_builder[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _sorobandata_builder[key]; + } + }); +}); +var _auth = __webpack_require__(5328); +Object.keys(_auth).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _auth[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _auth[key]; + } + }); +}); +var _invocation = __webpack_require__(3564); +Object.keys(_invocation).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _invocation[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _invocation[key]; + } + }); +}); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/* eslint-disable import/no-import-module-exports */ +// +// Soroban +// +var _default = exports["default"] = module.exports; + +/***/ }), + +/***/ 3564: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.buildInvocationTree = buildInvocationTree; +exports.walkInvocationTree = walkInvocationTree; +var _asset = __webpack_require__(1764); +var _address = __webpack_require__(1180); +var _scval = __webpack_require__(7177); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * @typedef CreateInvocation + * + * @prop {'wasm'|'sac'} type a type indicating if this creation was a custom + * contract or a wrapping of an existing Stellar asset + * @prop {string} [token] when `type=='sac'`, the canonical {@link Asset} that + * is being wrapped by this Stellar Asset Contract + * @prop {object} [wasm] when `type=='wasm'`, add'l creation parameters + * + * @prop {string} wasm.hash hex hash of WASM bytecode backing this contract + * @prop {string} wasm.address contract address of this deployment + * @prop {string} wasm.salt hex salt that the user consumed when creating + * this contract (encoded in the resulting address) + * @prop {any[]} [wasm.constructorArgs] a list of natively-represented values + * (see {@link scValToNative}) that are passed to the constructor when + * creating this contract + */ + +/** + * @typedef ExecuteInvocation + * + * @prop {string} source the strkey of the contract (C...) being invoked + * @prop {string} function the name of the function being invoked + * @prop {any[]} args the natively-represented parameters to the function + * invocation (see {@link scValToNative} for rules on how they're + * represented a JS types) + */ + +/** + * @typedef InvocationTree + * @prop {'execute' | 'create'} type the type of invocation occurring, either + * contract creation or host function execution + * @prop {CreateInvocation | ExecuteInvocation} args the parameters to the + * invocation, depending on the type + * @prop {InvocationTree[]} invocations any sub-invocations that (may) occur + * as a result of this invocation (i.e. a tree of call stacks) + */ + +/** + * Turns a raw invocation tree into a human-readable format. + * + * This is designed to make the invocation tree easier to understand in order to + * inform users about the side-effects of their contract calls. This will help + * make informed decisions about whether or not a particular invocation will + * result in what you expect it to. + * + * @param {xdr.SorobanAuthorizedInvocation} root the raw XDR of the invocation, + * likely acquired from transaction simulation. this is either from the + * {@link Operation.invokeHostFunction} itself (the `func` field), or from + * the authorization entries ({@link xdr.SorobanAuthorizationEntry}, the + * `rootInvocation` field) + * + * @returns {InvocationTree} a human-readable version of the invocation tree + * + * @example + * Here, we show a browser modal after simulating an arbitrary transaction, + * `tx`, which we assume has an `Operation.invokeHostFunction` inside of it: + * + * ```typescript + * import { Server, buildInvocationTree } from '@stellar/stellar-sdk'; + * + * const s = new Server("fill in accordingly"); + * + * s.simulateTransaction(tx).then( + * (resp: SorobanRpc.SimulateTransactionResponse) => { + * if (SorobanRpc.isSuccessfulSim(resp) && ) { + * // bold assumption: there's a valid result with an auth entry + * alert( + * "You are authorizing the following invocation:\n" + + * JSON.stringify( + * buildInvocationTree(resp.result!.auth[0].rootInvocation()), + * null, + * 2 + * ) + * ); + * } + * } + * ); + * ``` + */ +function buildInvocationTree(root) { + var fn = root["function"](); + + /** @type {InvocationTree} */ + var output = {}; + + /** @type {xdr.CreateContractArgs|xdr.CreateContractArgsV2|xdr.InvokeContractArgs} */ + var inner = fn.value(); + switch (fn["switch"]().value) { + // sorobanAuthorizedFunctionTypeContractFn + case 0: + output.type = 'execute'; + output.args = { + source: _address.Address.fromScAddress(inner.contractAddress()).toString(), + "function": inner.functionName(), + args: inner.args().map(function (arg) { + return (0, _scval.scValToNative)(arg); + }) + }; + break; + + // sorobanAuthorizedFunctionTypeCreateContractHostFn + // sorobanAuthorizedFunctionTypeCreateContractV2HostFn + case 1: // fallthrough: just no ctor args in V1 + case 2: + { + var createV2 = fn["switch"]().value === 2; + output.type = 'create'; + output.args = {}; + + // If the executable is a WASM, the preimage MUST be an address. If it's a + // token, the preimage MUST be an asset. This is a cheeky way to check + // that, because wasm=0, token=1 and address=0, asset=1 in the XDR switch + // values. + // + // The first part may not be true in V2, but we'd need to update this code + // anyway so it can still be an error. + var _ref = [inner.executable(), inner.contractIdPreimage()], + exec = _ref[0], + preimage = _ref[1]; + if (!!exec["switch"]().value !== !!preimage["switch"]().value) { + throw new Error("creation function appears invalid: ".concat(JSON.stringify(inner), " (should be wasm+address or token+asset)")); + } + switch (exec["switch"]().value) { + // contractExecutableWasm + case 0: + { + /** @type {xdr.ContractIdPreimageFromAddress} */ + var details = preimage.fromAddress(); + output.args.type = 'wasm'; + output.args.wasm = _objectSpread({ + salt: details.salt().toString('hex'), + hash: exec.wasmHash().toString('hex'), + address: _address.Address.fromScAddress(details.address()).toString() + }, createV2 && { + constructorArgs: inner.constructorArgs().map(function (arg) { + return (0, _scval.scValToNative)(arg); + }) + }); + break; + } + + // contractExecutableStellarAsset + case 1: + output.args.type = 'sac'; + output.args.asset = _asset.Asset.fromOperation(preimage.fromAsset()).toString(); + break; + default: + throw new Error("unknown creation type: ".concat(JSON.stringify(exec))); + } + break; + } + default: + throw new Error("unknown invocation type (".concat(fn["switch"](), "): ").concat(JSON.stringify(fn))); + } + output.invocations = root.subInvocations().map(function (i) { + return buildInvocationTree(i); + }); + return output; +} + +/** + * @callback InvocationWalker + * + * @param {xdr.SorobanAuthorizedInvocation} node the currently explored node + * @param {number} depth the depth of the tree this node is occurring at (the + * root starts at a depth of 1) + * @param {xdr.SorobanAuthorizedInvocation} [parent] this `node`s parent node, + * if any (i.e. this doesn't exist at the root) + * + * @returns {boolean|null|void} returning exactly `false` is a hint to stop + * exploring, other values are ignored + */ + +/** + * Executes a callback function on each node in the tree until stopped. + * + * Nodes are walked in a depth-first order. Returning `false` from the callback + * stops further depth exploration at that node, but it does not stop the walk + * in a "global" view. + * + * @param {xdr.SorobanAuthorizedInvocation} root the tree to explore + * @param {InvocationWalker} callback the callback to execute for each node + * @returns {void} + */ +function walkInvocationTree(root, callback) { + walkHelper(root, 1, callback); +} +function walkHelper(node, depth, callback, parent) { + if (callback(node, depth, parent) === false /* allow void rv */) { + return; + } + node.subInvocations().forEach(function (i) { + return walkHelper(i, depth + 1, callback, node); + }); +} + +/***/ }), + +/***/ 3335: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _jsXdr = __webpack_require__(3740); +var cereal = { + XdrWriter: _jsXdr.XdrWriter, + XdrReader: _jsXdr.XdrReader +}; +var _default = exports["default"] = cereal; + +/***/ }), + +/***/ 6691: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Keypair = void 0; +var _tweetnacl = _interopRequireDefault(__webpack_require__(4940)); +var _signing = __webpack_require__(15); +var _strkey = __webpack_require__(7120); +var _hashing = __webpack_require__(9152); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": ["^"]}] */ +/** + * `Keypair` represents public (and secret) keys of the account. + * + * Currently `Keypair` only supports ed25519 but in a future this class can be abstraction layer for other + * public-key signature systems. + * + * Use more convenient methods to create `Keypair` object: + * * `{@link Keypair.fromPublicKey}` + * * `{@link Keypair.fromSecret}` + * * `{@link Keypair.random}` + * + * @constructor + * @param {object} keys At least one of keys must be provided. + * @param {string} keys.type Public-key signature system name. (currently only `ed25519` keys are supported) + * @param {Buffer} [keys.publicKey] Raw public key + * @param {Buffer} [keys.secretKey] Raw secret key (32-byte secret seed in ed25519`) + */ +var Keypair = exports.Keypair = /*#__PURE__*/function () { + function Keypair(keys) { + _classCallCheck(this, Keypair); + if (keys.type !== 'ed25519') { + throw new Error('Invalid keys type'); + } + this.type = keys.type; + if (keys.secretKey) { + keys.secretKey = Buffer.from(keys.secretKey); + if (keys.secretKey.length !== 32) { + throw new Error('secretKey length is invalid'); + } + this._secretSeed = keys.secretKey; + this._publicKey = (0, _signing.generate)(keys.secretKey); + this._secretKey = Buffer.concat([keys.secretKey, this._publicKey]); + if (keys.publicKey && !this._publicKey.equals(Buffer.from(keys.publicKey))) { + throw new Error('secretKey does not match publicKey'); + } + } else { + this._publicKey = Buffer.from(keys.publicKey); + if (this._publicKey.length !== 32) { + throw new Error('publicKey length is invalid'); + } + } + } + + /** + * Creates a new `Keypair` instance from secret. This can either be secret key or secret seed depending + * on underlying public-key signature system. Currently `Keypair` only supports ed25519. + * @param {string} secret secret key (ex. `SDAKFNYEIAORZKKCYRILFQKLLOCNPL5SWJ3YY5NM3ZH6GJSZGXHZEPQS`) + * @returns {Keypair} + */ + return _createClass(Keypair, [{ + key: "xdrAccountId", + value: function xdrAccountId() { + return new _xdr["default"].AccountId.publicKeyTypeEd25519(this._publicKey); + } + }, { + key: "xdrPublicKey", + value: function xdrPublicKey() { + return new _xdr["default"].PublicKey.publicKeyTypeEd25519(this._publicKey); + } + + /** + * Creates a {@link xdr.MuxedAccount} object from the public key. + * + * You will get a different type of muxed account depending on whether or not + * you pass an ID. + * + * @param {string} [id] - stringified integer indicating the underlying muxed + * ID of the new account object + * + * @return {xdr.MuxedAccount} + */ + }, { + key: "xdrMuxedAccount", + value: function xdrMuxedAccount(id) { + if (typeof id !== 'undefined') { + if (typeof id !== 'string') { + throw new TypeError("expected string for ID, got ".concat(_typeof(id))); + } + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromString(id), + ed25519: this._publicKey + })); + } + return new _xdr["default"].MuxedAccount.keyTypeEd25519(this._publicKey); + } + + /** + * Returns raw public key + * @returns {Buffer} + */ + }, { + key: "rawPublicKey", + value: function rawPublicKey() { + return this._publicKey; + } + }, { + key: "signatureHint", + value: function signatureHint() { + var a = this.xdrAccountId().toXDR(); + return a.slice(a.length - 4); + } + + /** + * Returns public key associated with this `Keypair` object. + * @returns {string} + */ + }, { + key: "publicKey", + value: function publicKey() { + return _strkey.StrKey.encodeEd25519PublicKey(this._publicKey); + } + + /** + * Returns secret key associated with this `Keypair` object + * @returns {string} + */ + }, { + key: "secret", + value: function secret() { + if (!this._secretSeed) { + throw new Error('no secret key available'); + } + if (this.type === 'ed25519') { + return _strkey.StrKey.encodeEd25519SecretSeed(this._secretSeed); + } + throw new Error('Invalid Keypair type'); + } + + /** + * Returns raw secret key. + * @returns {Buffer} + */ + }, { + key: "rawSecretKey", + value: function rawSecretKey() { + return this._secretSeed; + } + + /** + * Returns `true` if this `Keypair` object contains secret key and can sign. + * @returns {boolean} + */ + }, { + key: "canSign", + value: function canSign() { + return !!this._secretKey; + } + + /** + * Signs data. + * @param {Buffer} data Data to sign + * @returns {Buffer} + */ + }, { + key: "sign", + value: function sign(data) { + if (!this.canSign()) { + throw new Error('cannot sign: no secret key available'); + } + return (0, _signing.sign)(data, this._secretKey); + } + + /** + * Verifies if `signature` for `data` is valid. + * @param {Buffer} data Signed data + * @param {Buffer} signature Signature + * @returns {boolean} + */ + }, { + key: "verify", + value: function verify(data, signature) { + return (0, _signing.verify)(data, signature, this._publicKey); + } + + /** + * Returns the decorated signature (hint+sig) for arbitrary data. + * + * @param {Buffer} data arbitrary data to sign + * @return {xdr.DecoratedSignature} the raw signature structure which can be + * added directly to a transaction envelope + * + * @see TransactionBase.addDecoratedSignature + */ + }, { + key: "signDecorated", + value: function signDecorated(data) { + var signature = this.sign(data); + var hint = this.signatureHint(); + return new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signature + }); + } + + /** + * Returns the raw decorated signature (hint+sig) for a signed payload signer. + * + * The hint is defined as the last 4 bytes of the signer key XORed with last + * 4 bytes of the payload (zero-left-padded if necessary). + * + * @param {Buffer} data data to both sign and treat as the payload + * @return {xdr.DecoratedSignature} + * + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0040.md#signature-hint + * @see TransactionBase.addDecoratedSignature + */ + }, { + key: "signPayloadDecorated", + value: function signPayloadDecorated(data) { + var signature = this.sign(data); + var keyHint = this.signatureHint(); + var hint = Buffer.from(data.slice(-4)); + if (hint.length < 4) { + // append zeroes as needed + hint = Buffer.concat([hint, Buffer.alloc(4 - data.length, 0)]); + } + return new _xdr["default"].DecoratedSignature({ + hint: hint.map(function (_byte, i) { + return _byte ^ keyHint[i]; + }), + signature: signature + }); + } + }], [{ + key: "fromSecret", + value: function fromSecret(secret) { + var rawSecret = _strkey.StrKey.decodeEd25519SecretSeed(secret); + return this.fromRawEd25519Seed(rawSecret); + } + + /** + * Creates a new `Keypair` object from ed25519 secret key seed raw bytes. + * + * @param {Buffer} rawSeed Raw 32-byte ed25519 secret key seed + * @returns {Keypair} + */ + }, { + key: "fromRawEd25519Seed", + value: function fromRawEd25519Seed(rawSeed) { + return new this({ + type: 'ed25519', + secretKey: rawSeed + }); + } + + /** + * Returns `Keypair` object representing network master key. + * @param {string} networkPassphrase passphrase of the target stellar network (e.g. "Public Global Stellar Network ; September 2015"). + * @returns {Keypair} + */ + }, { + key: "master", + value: function master(networkPassphrase) { + if (!networkPassphrase) { + throw new Error('No network selected. Please pass a network argument, e.g. `Keypair.master(Networks.PUBLIC)`.'); + } + return this.fromRawEd25519Seed((0, _hashing.hash)(networkPassphrase)); + } + + /** + * Creates a new `Keypair` object from public key. + * @param {string} publicKey public key (ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`) + * @returns {Keypair} + */ + }, { + key: "fromPublicKey", + value: function fromPublicKey(publicKey) { + publicKey = _strkey.StrKey.decodeEd25519PublicKey(publicKey); + if (publicKey.length !== 32) { + throw new Error('Invalid Stellar public key'); + } + return new this({ + type: 'ed25519', + publicKey: publicKey + }); + } + + /** + * Create a random `Keypair` object. + * @returns {Keypair} + */ + }, { + key: "random", + value: function random() { + var secret = _tweetnacl["default"].randomBytes(32); + return this.fromRawEd25519Seed(secret); + } + }]); +}(); + +/***/ }), + +/***/ 2262: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LiquidityPoolAsset = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +var _get_liquidity_pool_id = __webpack_require__(5578); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * LiquidityPoolAsset class represents a liquidity pool trustline change. + * + * @constructor + * @param {Asset} assetA – The first asset in the Pool, it must respect the rule assetA < assetB. See {@link Asset.compare} for more details on how assets are sorted. + * @param {Asset} assetB – The second asset in the Pool, it must respect the rule assetA < assetB. See {@link Asset.compare} for more details on how assets are sorted. + * @param {number} fee – The liquidity pool fee. For now the only fee supported is `30`. + */ +var LiquidityPoolAsset = exports.LiquidityPoolAsset = /*#__PURE__*/function () { + function LiquidityPoolAsset(assetA, assetB, fee) { + _classCallCheck(this, LiquidityPoolAsset); + if (!assetA || !(assetA instanceof _asset.Asset)) { + throw new Error('assetA is invalid'); + } + if (!assetB || !(assetB instanceof _asset.Asset)) { + throw new Error('assetB is invalid'); + } + if (_asset.Asset.compare(assetA, assetB) !== -1) { + throw new Error('Assets are not in lexicographic order'); + } + if (!fee || fee !== _get_liquidity_pool_id.LiquidityPoolFeeV18) { + throw new Error('fee is invalid'); + } + this.assetA = assetA; + this.assetB = assetB; + this.fee = fee; + } + + /** + * Returns a liquidity pool asset object from its XDR ChangeTrustAsset object + * representation. + * @param {xdr.ChangeTrustAsset} ctAssetXdr - The asset XDR object. + * @returns {LiquidityPoolAsset} + */ + return _createClass(LiquidityPoolAsset, [{ + key: "toXDRObject", + value: + /** + * Returns the `xdr.ChangeTrustAsset` object for this liquidity pool asset. + * + * Note: To convert from an {@link Asset `Asset`} to `xdr.ChangeTrustAsset` + * please refer to the + * {@link Asset.toChangeTrustXDRObject `Asset.toChangeTrustXDRObject`} method. + * + * @returns {xdr.ChangeTrustAsset} XDR ChangeTrustAsset object. + */ + function toXDRObject() { + var lpConstantProductParamsXdr = new _xdr["default"].LiquidityPoolConstantProductParameters({ + assetA: this.assetA.toXDRObject(), + assetB: this.assetB.toXDRObject(), + fee: this.fee + }); + var lpParamsXdr = new _xdr["default"].LiquidityPoolParameters('liquidityPoolConstantProduct', lpConstantProductParamsXdr); + return new _xdr["default"].ChangeTrustAsset('assetTypePoolShare', lpParamsXdr); + } + + /** + * @returns {LiquidityPoolParameters} Liquidity pool parameters. + */ + }, { + key: "getLiquidityPoolParameters", + value: function getLiquidityPoolParameters() { + return _objectSpread(_objectSpread({}, this), {}, { + assetA: this.assetA, + assetB: this.assetB, + fee: this.fee + }); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {AssetType.liquidityPoolShares} asset type. Can only be `liquidity_pool_shares`. + */ + }, { + key: "getAssetType", + value: function getAssetType() { + return 'liquidity_pool_shares'; + } + + /** + * @param {LiquidityPoolAsset} other the LiquidityPoolAsset to compare + * @returns {boolean} `true` if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(other) { + return this.assetA.equals(other.assetA) && this.assetB.equals(other.assetB) && this.fee === other.fee; + } + }, { + key: "toString", + value: function toString() { + var poolId = (0, _get_liquidity_pool_id.getLiquidityPoolId)('constant_product', this.getLiquidityPoolParameters()).toString('hex'); + return "liquidity_pool:".concat(poolId); + } + }], [{ + key: "fromOperation", + value: function fromOperation(ctAssetXdr) { + var assetType = ctAssetXdr["switch"](); + if (assetType === _xdr["default"].AssetType.assetTypePoolShare()) { + var liquidityPoolParameters = ctAssetXdr.liquidityPool().constantProduct(); + return new this(_asset.Asset.fromOperation(liquidityPoolParameters.assetA()), _asset.Asset.fromOperation(liquidityPoolParameters.assetB()), liquidityPoolParameters.fee()); + } + throw new Error("Invalid asset type: ".concat(assetType.name)); + } + }]); +}(); + +/***/ }), + +/***/ 9353: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LiquidityPoolId = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * LiquidityPoolId class represents the asset referenced by a trustline to a + * liquidity pool. + * + * @constructor + * @param {string} liquidityPoolId - The ID of the liquidity pool in string 'hex'. + */ +var LiquidityPoolId = exports.LiquidityPoolId = /*#__PURE__*/function () { + function LiquidityPoolId(liquidityPoolId) { + _classCallCheck(this, LiquidityPoolId); + if (!liquidityPoolId) { + throw new Error('liquidityPoolId cannot be empty'); + } + if (!/^[a-f0-9]{64}$/.test(liquidityPoolId)) { + throw new Error('Liquidity pool ID is not a valid hash'); + } + this.liquidityPoolId = liquidityPoolId; + } + + /** + * Returns a liquidity pool ID object from its xdr.TrustLineAsset representation. + * @param {xdr.TrustLineAsset} tlAssetXdr - The asset XDR object. + * @returns {LiquidityPoolId} + */ + return _createClass(LiquidityPoolId, [{ + key: "toXDRObject", + value: + /** + * Returns the `xdr.TrustLineAsset` object for this liquidity pool ID. + * + * Note: To convert from {@link Asset `Asset`} to `xdr.TrustLineAsset` please + * refer to the + * {@link Asset.toTrustLineXDRObject `Asset.toTrustLineXDRObject`} method. + * + * @returns {xdr.TrustLineAsset} XDR LiquidityPoolId object + */ + function toXDRObject() { + var xdrPoolId = _xdr["default"].PoolId.fromXDR(this.liquidityPoolId, 'hex'); + return new _xdr["default"].TrustLineAsset('assetTypePoolShare', xdrPoolId); + } + + /** + * @returns {string} Liquidity pool ID. + */ + }, { + key: "getLiquidityPoolId", + value: function getLiquidityPoolId() { + return String(this.liquidityPoolId); + } + + /** + * @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/) + * @returns {AssetType.liquidityPoolShares} asset type. Can only be `liquidity_pool_shares`. + */ + }, { + key: "getAssetType", + value: function getAssetType() { + return 'liquidity_pool_shares'; + } + + /** + * @param {LiquidityPoolId} asset LiquidityPoolId to compare. + * @returns {boolean} `true` if this asset equals the given asset. + */ + }, { + key: "equals", + value: function equals(asset) { + return this.liquidityPoolId === asset.getLiquidityPoolId(); + } + }, { + key: "toString", + value: function toString() { + return "liquidity_pool:".concat(this.liquidityPoolId); + } + }], [{ + key: "fromOperation", + value: function fromOperation(tlAssetXdr) { + var assetType = tlAssetXdr["switch"](); + if (assetType === _xdr["default"].AssetType.assetTypePoolShare()) { + var liquidityPoolId = tlAssetXdr.liquidityPoolId().toString('hex'); + return new this(liquidityPoolId); + } + throw new Error("Invalid asset type: ".concat(assetType.name)); + } + }]); +}(); + +/***/ }), + +/***/ 4172: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.MemoText = exports.MemoReturn = exports.MemoNone = exports.MemoID = exports.MemoHash = exports.Memo = void 0; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Type of {@link Memo}. + */ +var MemoNone = exports.MemoNone = 'none'; +/** + * Type of {@link Memo}. + */ +var MemoID = exports.MemoID = 'id'; +/** + * Type of {@link Memo}. + */ +var MemoText = exports.MemoText = 'text'; +/** + * Type of {@link Memo}. + */ +var MemoHash = exports.MemoHash = 'hash'; +/** + * Type of {@link Memo}. + */ +var MemoReturn = exports.MemoReturn = 'return'; + +/** + * `Memo` represents memos attached to transactions. + * + * @param {string} type - `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn` + * @param {*} value - `string` for `MemoID`, `MemoText`, buffer of hex string for `MemoHash` or `MemoReturn` + * @see [Transactions concept](https://developers.stellar.org/docs/glossary/transactions/) + * @class Memo + */ +var Memo = exports.Memo = /*#__PURE__*/function () { + function Memo(type) { + var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + _classCallCheck(this, Memo); + this._type = type; + this._value = value; + switch (this._type) { + case MemoNone: + break; + case MemoID: + Memo._validateIdValue(value); + break; + case MemoText: + Memo._validateTextValue(value); + break; + case MemoHash: + case MemoReturn: + Memo._validateHashValue(value); + // We want MemoHash and MemoReturn to have Buffer as a value + if (typeof value === 'string') { + this._value = Buffer.from(value, 'hex'); + } + break; + default: + throw new Error('Invalid memo type'); + } + } + + /** + * Contains memo type: `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn` + */ + return _createClass(Memo, [{ + key: "type", + get: function get() { + return this._type; + }, + set: function set(type) { + throw new Error('Memo is immutable'); + } + + /** + * Contains memo value: + * * `null` for `MemoNone`, + * * `string` for `MemoID`, + * * `Buffer` for `MemoText` after decoding using `fromXDRObject`, original value otherwise, + * * `Buffer` for `MemoHash`, `MemoReturn`. + */ + }, { + key: "value", + get: function get() { + switch (this._type) { + case MemoNone: + return null; + case MemoID: + case MemoText: + return this._value; + case MemoHash: + case MemoReturn: + return Buffer.from(this._value); + default: + throw new Error('Invalid memo type'); + } + }, + set: function set(value) { + throw new Error('Memo is immutable'); + } + }, { + key: "toXDRObject", + value: + /** + * Returns XDR memo object. + * @returns {xdr.Memo} + */ + function toXDRObject() { + switch (this._type) { + case MemoNone: + return _xdr["default"].Memo.memoNone(); + case MemoID: + return _xdr["default"].Memo.memoId(_jsXdr.UnsignedHyper.fromString(this._value)); + case MemoText: + return _xdr["default"].Memo.memoText(this._value); + case MemoHash: + return _xdr["default"].Memo.memoHash(this._value); + case MemoReturn: + return _xdr["default"].Memo.memoReturn(this._value); + default: + return null; + } + } + + /** + * Returns {@link Memo} from XDR memo object. + * @param {xdr.Memo} object XDR memo object + * @returns {Memo} + */ + }], [{ + key: "_validateIdValue", + value: function _validateIdValue(value) { + var error = new Error("Expects a int64 as a string. Got ".concat(value)); + if (typeof value !== 'string') { + throw error; + } + var number; + try { + number = new _bignumber["default"](value); + } catch (e) { + throw error; + } + + // Infinity + if (!number.isFinite()) { + throw error; + } + + // NaN + if (number.isNaN()) { + throw error; + } + } + }, { + key: "_validateTextValue", + value: function _validateTextValue(value) { + if (!_xdr["default"].Memo.armTypeForArm('text').isValid(value)) { + throw new Error('Expects string, array or buffer, max 28 bytes'); + } + } + }, { + key: "_validateHashValue", + value: function _validateHashValue(value) { + var error = new Error("Expects a 32 byte hash value or hex encoded string. Got ".concat(value)); + if (value === null || typeof value === 'undefined') { + throw error; + } + var valueBuffer; + if (typeof value === 'string') { + if (!/^[0-9A-Fa-f]{64}$/g.test(value)) { + throw error; + } + valueBuffer = Buffer.from(value, 'hex'); + } else if (Buffer.isBuffer(value)) { + valueBuffer = Buffer.from(value); + } else { + throw error; + } + if (!valueBuffer.length || valueBuffer.length !== 32) { + throw error; + } + } + + /** + * Returns an empty memo (`MemoNone`). + * @returns {Memo} + */ + }, { + key: "none", + value: function none() { + return new Memo(MemoNone); + } + + /** + * Creates and returns a `MemoText` memo. + * @param {string} text - memo text + * @returns {Memo} + */ + }, { + key: "text", + value: function text(_text) { + return new Memo(MemoText, _text); + } + + /** + * Creates and returns a `MemoID` memo. + * @param {string} id - 64-bit number represented as a string + * @returns {Memo} + */ + }, { + key: "id", + value: function id(_id) { + return new Memo(MemoID, _id); + } + + /** + * Creates and returns a `MemoHash` memo. + * @param {array|string} hash - 32 byte hash or hex encoded string + * @returns {Memo} + */ + }, { + key: "hash", + value: function hash(_hash) { + return new Memo(MemoHash, _hash); + } + + /** + * Creates and returns a `MemoReturn` memo. + * @param {array|string} hash - 32 byte hash or hex encoded string + * @returns {Memo} + */ + }, { + key: "return", + value: function _return(hash) { + return new Memo(MemoReturn, hash); + } + }, { + key: "fromXDRObject", + value: function fromXDRObject(object) { + switch (object.arm()) { + case 'id': + return Memo.id(object.value().toString()); + case 'text': + return Memo.text(object.value()); + case 'hash': + return Memo.hash(object.value()); + case 'retHash': + return Memo["return"](object.value()); + default: + break; + } + if (typeof object.value() === 'undefined') { + return Memo.none(); + } + throw new Error('Unknown type'); + } + }]); +}(); + +/***/ }), + +/***/ 2243: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.MuxedAccount = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _account = __webpack_require__(2135); +var _strkey = __webpack_require__(7120); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Represents a muxed account for transactions and operations. + * + * A muxed (or *multiplexed*) account (defined rigorously in + * [CAP-27](https://stellar.org/protocol/cap-27) and briefly in + * [SEP-23](https://stellar.org/protocol/sep-23)) is one that resolves a single + * Stellar `G...`` account to many different underlying IDs. + * + * For example, you may have a single Stellar address for accounting purposes: + * GA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJVSGZ + * + * Yet would like to use it for 4 different family members: + * 1: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAGZFQ + * 2: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAALIWQ + * 3: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAPYHQ + * 4: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAQLQQ + * + * This object makes it easy to create muxed accounts from regular accounts, + * duplicate them, get/set the underlying IDs, etc. without mucking around with + * the raw XDR. + * + * Because muxed accounts are purely an off-chain convention, they all share the + * sequence number tied to their underlying G... account. Thus, this object + * *requires* an {@link Account} instance to be passed in, so that muxed + * instances of an account can collectively modify the sequence number whenever + * a muxed account is used as the source of a @{link Transaction} with {@link + * TransactionBuilder}. + * + * @constructor + * + * @param {Account} account - the @{link Account} instance representing the + * underlying G... address + * @param {string} id - a stringified uint64 value that represents the + * ID of the muxed account + * + * @link https://developers.stellar.org/docs/glossary/muxed-accounts/ + */ +var MuxedAccount = exports.MuxedAccount = /*#__PURE__*/function () { + function MuxedAccount(baseAccount, id) { + _classCallCheck(this, MuxedAccount); + var accountId = baseAccount.accountId(); + if (!_strkey.StrKey.isValidEd25519PublicKey(accountId)) { + throw new Error('accountId is invalid'); + } + this.account = baseAccount; + this._muxedXdr = (0, _decode_encode_muxed_account.encodeMuxedAccount)(accountId, id); + this._mAddress = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(this._muxedXdr); + this._id = id; + } + + /** + * Parses an M-address into a MuxedAccount object. + * + * @param {string} mAddress - an M-address to transform + * @param {string} sequenceNum - the sequence number of the underlying {@link + * Account}, to use for the underlying base account (@link + * MuxedAccount.baseAccount). If you're using the SDK, you can use + * `server.loadAccount` to fetch this if you don't know it. + * + * @return {MuxedAccount} + */ + return _createClass(MuxedAccount, [{ + key: "baseAccount", + value: + /** + * @return {Account} the underlying account object shared among all muxed + * accounts with this Stellar address + */ + function baseAccount() { + return this.account; + } + + /** + * @return {string} the M-address representing this account's (G-address, ID) + */ + }, { + key: "accountId", + value: function accountId() { + return this._mAddress; + } + }, { + key: "id", + value: function id() { + return this._id; + } + }, { + key: "setId", + value: function setId(id) { + if (typeof id !== 'string') { + throw new Error('id should be a string representing a number (uint64)'); + } + this._muxedXdr.med25519().id(_xdr["default"].Uint64.fromString(id)); + this._mAddress = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(this._muxedXdr); + this._id = id; + return this; + } + + /** + * Accesses the underlying account's sequence number. + * @return {string} strigified sequence number for the underlying account + */ + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this.account.sequenceNumber(); + } + + /** + * Increments the underlying account's sequence number by one. + * @return {void} + */ + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + return this.account.incrementSequenceNumber(); + } + + /** + * @return {xdr.MuxedAccount} the XDR object representing this muxed account's + * G-address and uint64 ID + */ + }, { + key: "toXDRObject", + value: function toXDRObject() { + return this._muxedXdr; + } + }, { + key: "equals", + value: function equals(otherMuxedAccount) { + return this.accountId() === otherMuxedAccount.accountId(); + } + }], [{ + key: "fromAddress", + value: function fromAddress(mAddress, sequenceNum) { + var muxedAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(mAddress); + var gAddress = (0, _decode_encode_muxed_account.extractBaseAddress)(mAddress); + var id = muxedAccount.med25519().id().toString(); + return new MuxedAccount(new _account.Account(gAddress, sequenceNum), id); + } + }]); +}(); + +/***/ }), + +/***/ 6202: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Networks = void 0; +/** + * Contains passphrases for common networks: + * * `Networks.PUBLIC`: `Public Global Stellar Network ; September 2015` + * * `Networks.TESTNET`: `Test SDF Network ; September 2015` + * * `Networks.FUTURENET`: `Test SDF Future Network ; October 2022` + * * `Networks.STANDALONE`: `Standalone Network ; February 2017` + * + * @type {{PUBLIC: string, TESTNET: string, FUTURENET: string, STANDALONE: string }} + */ +var Networks = exports.Networks = { + PUBLIC: 'Public Global Stellar Network ; September 2015', + TESTNET: 'Test SDF Network ; September 2015', + FUTURENET: 'Test SDF Future Network ; October 2022', + SANDBOX: 'Local Sandbox Stellar Network ; September 2022', + STANDALONE: 'Standalone Network ; February 2017' +}; + +/***/ }), + +/***/ 8549: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "Int128", ({ + enumerable: true, + get: function get() { + return _int.Int128; + } +})); +Object.defineProperty(exports, "Int256", ({ + enumerable: true, + get: function get() { + return _int2.Int256; + } +})); +Object.defineProperty(exports, "ScInt", ({ + enumerable: true, + get: function get() { + return _sc_int.ScInt; + } +})); +Object.defineProperty(exports, "Uint128", ({ + enumerable: true, + get: function get() { + return _uint.Uint128; + } +})); +Object.defineProperty(exports, "Uint256", ({ + enumerable: true, + get: function get() { + return _uint2.Uint256; + } +})); +Object.defineProperty(exports, "XdrLargeInt", ({ + enumerable: true, + get: function get() { + return _xdr_large_int.XdrLargeInt; + } +})); +exports.scValToBigInt = scValToBigInt; +var _xdr_large_int = __webpack_require__(7429); +var _uint = __webpack_require__(6272); +var _uint2 = __webpack_require__(8672); +var _int = __webpack_require__(5487); +var _int2 = __webpack_require__(4063); +var _sc_int = __webpack_require__(3317); +/** + * Transforms an opaque {@link xdr.ScVal} into a native bigint, if possible. + * + * If you then want to use this in the abstractions provided by this module, + * you can pass it to the constructor of {@link XdrLargeInt}. + * + * @example + * let scv = contract.call("add", x, y); // assume it returns an xdr.ScVal + * let bigi = scValToBigInt(scv); + * + * new ScInt(bigi); // if you don't care about types, and + * new XdrLargeInt('i128', bigi); // if you do + * + * @param {xdr.ScVal} scv - the raw XDR value to parse into an integer + * @returns {bigint} the native value of this input value + * + * @throws {TypeError} if the `scv` input value doesn't represent an integer + */ +function scValToBigInt(scv) { + var scIntType = _xdr_large_int.XdrLargeInt.getType(scv["switch"]().name); + switch (scv["switch"]().name) { + case 'scvU32': + case 'scvI32': + return BigInt(scv.value()); + case 'scvU64': + case 'scvI64': + return new _xdr_large_int.XdrLargeInt(scIntType, scv.value()).toBigInt(); + case 'scvU128': + case 'scvI128': + return new _xdr_large_int.XdrLargeInt(scIntType, [scv.value().lo(), scv.value().hi()]).toBigInt(); + case 'scvU256': + case 'scvI256': + return new _xdr_large_int.XdrLargeInt(scIntType, [scv.value().loLo(), scv.value().loHi(), scv.value().hiLo(), scv.value().hiHi()]).toBigInt(); + default: + throw TypeError("expected integer type, got ".concat(scv["switch"]())); + } +} + +/***/ }), + +/***/ 5487: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Int128 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Int128 = exports.Int128 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct a signed 128-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Int128() { + _classCallCheck(this, Int128); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Int128, [args]); + } + _inherits(Int128, _LargeInt); + return _createClass(Int128, [{ + key: "unsigned", + get: function get() { + return false; + } + }, { + key: "size", + get: function get() { + return 128; + } + }]); +}(_jsXdr.LargeInt); +Int128.defineIntBoundaries(); + +/***/ }), + +/***/ 4063: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Int256 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Int256 = exports.Int256 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct a signed 256-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Int256() { + _classCallCheck(this, Int256); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Int256, [args]); + } + _inherits(Int256, _LargeInt); + return _createClass(Int256, [{ + key: "unsigned", + get: function get() { + return false; + } + }, { + key: "size", + get: function get() { + return 256; + } + }]); +}(_jsXdr.LargeInt); +Int256.defineIntBoundaries(); + +/***/ }), + +/***/ 3317: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.ScInt = void 0; +var _xdr_large_int = __webpack_require__(7429); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Provides an easier way to manipulate large numbers for Stellar operations. + * + * You can instantiate this "**s**mart **c**ontract integer" value either from + * bigints, strings, or numbers (whole numbers, or this will throw). + * + * If you need to create a native BigInt from a list of integer "parts" (for + * example, you have a series of encoded 32-bit integers that represent a larger + * value), you can use the lower level abstraction {@link XdrLargeInt}. For + * example, you could do `new XdrLargeInt('u128', bytes...).toBigInt()`. + * + * @example + * import { xdr, ScInt, scValToBigInt } from "@stellar/stellar-base"; + * + * // You have an ScVal from a contract and want to parse it into JS native. + * const value = xdr.ScVal.fromXDR(someXdr, "base64"); + * const bigi = scValToBigInt(value); // grab it as a BigInt + * let sci = new ScInt(bigi); + * + * sci.toNumber(); // gives native JS type (w/ size check) + * sci.toBigInt(); // gives the native BigInt value + * sci.toU64(); // gives ScValType-specific XDR constructs (with size checks) + * + * // You have a number and want to shove it into a contract. + * sci = ScInt(0xdeadcafebabe); + * sci.toBigInt() // returns 244838016400062n + * sci.toNumber() // throws: too large + * + * // Pass any to e.g. a Contract.call(), conversion happens automatically + * // regardless of the initial type. + * const scValU128 = sci.toU128(); + * const scValI256 = sci.toI256(); + * const scValU64 = sci.toU64(); + * + * // Lots of ways to initialize: + * ScInt("123456789123456789") + * ScInt(123456789123456789n); + * ScInt(1n << 140n); + * ScInt(-42); + * ScInt(scValToBigInt(scValU128)); // from above + * + * // If you know the type ahead of time (accessing `.raw` is faster than + * // conversions), you can specify the type directly (otherwise, it's + * // interpreted from the numbers you pass in): + * const i = ScInt(123456789n, { type: "u256" }); + * + * // For example, you can use the underlying `sdk.U256` and convert it to an + * // `xdr.ScVal` directly like so: + * const scv = new xdr.ScVal.scvU256(i.raw); + * + * // Or reinterpret it as a different type (size permitting): + * const scv = i.toI64(); + * + * @param {number|bigint|string} value - a single, integer-like value which will + * be interpreted in the smallest appropriate XDR type supported by Stellar + * (64, 128, or 256 bit integer values). signed values are supported, though + * they are sanity-checked against `opts.type`. if you need 32-bit values, + * you can construct them directly without needing this wrapper, e.g. + * `xdr.ScVal.scvU32(1234)`. + * + * @param {object} [opts] - an optional object controlling optional parameters + * @param {string} [opts.type] - force a specific data type. the type choices + * are: 'i64', 'u64', 'i128', 'u128', 'i256', and 'u256' (default: the + * smallest one that fits the `value`) + * + * @throws {RangeError} if the `value` is invalid (e.g. floating point), too + * large (i.e. exceeds a 256-bit value), or doesn't fit in the `opts.type` + * @throws {TypeError} on missing parameters, or if the "signedness" of `opts` + * doesn't match input `value`, e.g. passing `{type: 'u64'}` yet passing -1n + * @throws {SyntaxError} if a string `value` can't be parsed as a big integer + */ +var ScInt = exports.ScInt = /*#__PURE__*/function (_XdrLargeInt) { + function ScInt(value, opts) { + var _opts$type; + _classCallCheck(this, ScInt); + var signed = value < 0; + var type = (_opts$type = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type !== void 0 ? _opts$type : ''; + if (type.startsWith('u') && signed) { + throw TypeError("specified type ".concat(opts.type, " yet negative (").concat(value, ")")); + } + + // If unspecified, we make a best guess at the type based on the bit length + // of the value, treating 64 as a minimum and 256 as a maximum. + if (type === '') { + type = signed ? 'i' : 'u'; + var bitlen = nearestBigIntSize(value); + switch (bitlen) { + case 64: + case 128: + case 256: + type += bitlen.toString(); + break; + default: + throw RangeError("expected 64/128/256 bits for input (".concat(value, "), got ").concat(bitlen)); + } + } + return _callSuper(this, ScInt, [type, value]); + } + _inherits(ScInt, _XdrLargeInt); + return _createClass(ScInt); +}(_xdr_large_int.XdrLargeInt); +function nearestBigIntSize(bigI) { + var _find; + // Note: Even though BigInt.toString(2) includes the negative sign for + // negative values (???), the following is still accurate, because the + // negative sign would be represented by a sign bit. + var bitlen = bigI.toString(2).length; + return (_find = [64, 128, 256].find(function (len) { + return bitlen <= len; + })) !== null && _find !== void 0 ? _find : bitlen; +} + +/***/ }), + +/***/ 6272: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Uint128 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Uint128 = exports.Uint128 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct an unsigned 128-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Uint128() { + _classCallCheck(this, Uint128); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Uint128, [args]); + } + _inherits(Uint128, _LargeInt); + return _createClass(Uint128, [{ + key: "unsigned", + get: function get() { + return true; + } + }, { + key: "size", + get: function get() { + return 128; + } + }]); +}(_jsXdr.LargeInt); +Uint128.defineIntBoundaries(); + +/***/ }), + +/***/ 8672: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Uint256 = void 0; +var _jsXdr = __webpack_require__(3740); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var Uint256 = exports.Uint256 = /*#__PURE__*/function (_LargeInt) { + /** + * Construct an unsigned 256-bit integer that can be XDR-encoded. + * + * @param {Array} args - one or more slices to encode + * in big-endian format (i.e. earlier elements are higher bits) + */ + function Uint256() { + _classCallCheck(this, Uint256); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return _callSuper(this, Uint256, [args]); + } + _inherits(Uint256, _LargeInt); + return _createClass(Uint256, [{ + key: "unsigned", + get: function get() { + return true; + } + }, { + key: "size", + get: function get() { + return 256; + } + }]); +}(_jsXdr.LargeInt); +Uint256.defineIntBoundaries(); + +/***/ }), + +/***/ 7429: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.XdrLargeInt = void 0; +var _jsXdr = __webpack_require__(3740); +var _uint = __webpack_require__(6272); +var _uint2 = __webpack_require__(8672); +var _int = __webpack_require__(5487); +var _int2 = __webpack_require__(4063); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": [">>"]}] */ +/** + * A wrapper class to represent large XDR-encodable integers. + * + * This operates at a lower level than {@link ScInt} by forcing you to specify + * the type / width / size in bits of the integer you're targeting, regardless + * of the input value(s) you provide. + * + * @param {string} type - force a specific data type. the type choices are: + * 'i64', 'u64', 'i128', 'u128', 'i256', and 'u256' (default: the smallest + * one that fits the `value`) (see {@link XdrLargeInt.isType}) + * @param {number|bigint|string|Array} values a list of + * integer-like values interpreted in big-endian order + */ +var XdrLargeInt = exports.XdrLargeInt = /*#__PURE__*/function () { + function XdrLargeInt(type, values) { + _classCallCheck(this, XdrLargeInt); + /** @type {xdr.LargeInt} */ + _defineProperty(this, "int", void 0); + // child class of a jsXdr.LargeInt + /** @type {string} */ + _defineProperty(this, "type", void 0); + if (!(values instanceof Array)) { + values = [values]; + } + + // normalize values to one type + values = values.map(function (i) { + // micro-optimization to no-op on the likeliest input value: + if (typeof i === 'bigint') { + return i; + } + if (i instanceof XdrLargeInt) { + return i.toBigInt(); + } + return BigInt(i); + }); + switch (type) { + case 'i64': + this["int"] = new _jsXdr.Hyper(values); + break; + case 'i128': + this["int"] = new _int.Int128(values); + break; + case 'i256': + this["int"] = new _int2.Int256(values); + break; + case 'u64': + this["int"] = new _jsXdr.UnsignedHyper(values); + break; + case 'u128': + this["int"] = new _uint.Uint128(values); + break; + case 'u256': + this["int"] = new _uint2.Uint256(values); + break; + default: + throw TypeError("invalid type: ".concat(type)); + } + this.type = type; + } + + /** + * @returns {number} + * @throws {RangeError} if the value can't fit into a Number + */ + return _createClass(XdrLargeInt, [{ + key: "toNumber", + value: function toNumber() { + var bi = this["int"].toBigInt(); + if (bi > Number.MAX_SAFE_INTEGER || bi < Number.MIN_SAFE_INTEGER) { + throw RangeError("value ".concat(bi, " not in range for Number ") + "[".concat(Number.MAX_SAFE_INTEGER, ", ").concat(Number.MIN_SAFE_INTEGER, "]")); + } + return Number(bi); + } + + /** @returns {bigint} */ + }, { + key: "toBigInt", + value: function toBigInt() { + return this["int"].toBigInt(); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = I64` */ + }, { + key: "toI64", + value: function toI64() { + this._sizeCheck(64); + var v = this.toBigInt(); + if (BigInt.asIntN(64, v) !== v) { + throw RangeError("value too large for i64: ".concat(v)); + } + return _xdr["default"].ScVal.scvI64(new _xdr["default"].Int64(v)); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = U64` */ + }, { + key: "toU64", + value: function toU64() { + this._sizeCheck(64); + return _xdr["default"].ScVal.scvU64(new _xdr["default"].Uint64(BigInt.asUintN(64, this.toBigInt())) // reiterpret as unsigned + ); + } + + /** + * @returns {xdr.ScVal} the integer encoded with `ScValType = I128` + * @throws {RangeError} if the value cannot fit in 128 bits + */ + }, { + key: "toI128", + value: function toI128() { + this._sizeCheck(128); + var v = this["int"].toBigInt(); + var hi64 = BigInt.asIntN(64, v >> 64n); // encode top 64 w/ sign bit + var lo64 = BigInt.asUintN(64, v); // grab btm 64, encode sign + + return _xdr["default"].ScVal.scvI128(new _xdr["default"].Int128Parts({ + hi: new _xdr["default"].Int64(hi64), + lo: new _xdr["default"].Uint64(lo64) + })); + } + + /** + * @returns {xdr.ScVal} the integer encoded with `ScValType = U128` + * @throws {RangeError} if the value cannot fit in 128 bits + */ + }, { + key: "toU128", + value: function toU128() { + this._sizeCheck(128); + var v = this["int"].toBigInt(); + return _xdr["default"].ScVal.scvU128(new _xdr["default"].UInt128Parts({ + hi: new _xdr["default"].Uint64(BigInt.asUintN(64, v >> 64n)), + lo: new _xdr["default"].Uint64(BigInt.asUintN(64, v)) + })); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = I256` */ + }, { + key: "toI256", + value: function toI256() { + var v = this["int"].toBigInt(); + var hiHi64 = BigInt.asIntN(64, v >> 192n); // keep sign bit + var hiLo64 = BigInt.asUintN(64, v >> 128n); + var loHi64 = BigInt.asUintN(64, v >> 64n); + var loLo64 = BigInt.asUintN(64, v); + return _xdr["default"].ScVal.scvI256(new _xdr["default"].Int256Parts({ + hiHi: new _xdr["default"].Int64(hiHi64), + hiLo: new _xdr["default"].Uint64(hiLo64), + loHi: new _xdr["default"].Uint64(loHi64), + loLo: new _xdr["default"].Uint64(loLo64) + })); + } + + /** @returns {xdr.ScVal} the integer encoded with `ScValType = U256` */ + }, { + key: "toU256", + value: function toU256() { + var v = this["int"].toBigInt(); + var hiHi64 = BigInt.asUintN(64, v >> 192n); // encode sign bit + var hiLo64 = BigInt.asUintN(64, v >> 128n); + var loHi64 = BigInt.asUintN(64, v >> 64n); + var loLo64 = BigInt.asUintN(64, v); + return _xdr["default"].ScVal.scvU256(new _xdr["default"].UInt256Parts({ + hiHi: new _xdr["default"].Uint64(hiHi64), + hiLo: new _xdr["default"].Uint64(hiLo64), + loHi: new _xdr["default"].Uint64(loHi64), + loLo: new _xdr["default"].Uint64(loLo64) + })); + } + + /** @returns {xdr.ScVal} the smallest interpretation of the stored value */ + }, { + key: "toScVal", + value: function toScVal() { + switch (this.type) { + case 'i64': + return this.toI64(); + case 'i128': + return this.toI128(); + case 'i256': + return this.toI256(); + case 'u64': + return this.toU64(); + case 'u128': + return this.toU128(); + case 'u256': + return this.toU256(); + default: + throw TypeError("invalid type: ".concat(this.type)); + } + } + }, { + key: "valueOf", + value: function valueOf() { + return this["int"].valueOf(); + } + }, { + key: "toString", + value: function toString() { + return this["int"].toString(); + } + }, { + key: "toJSON", + value: function toJSON() { + return { + value: this.toBigInt().toString(), + type: this.type + }; + } + }, { + key: "_sizeCheck", + value: function _sizeCheck(bits) { + if (this["int"].size > bits) { + throw RangeError("value too large for ".concat(bits, " bits (").concat(this.type, ")")); + } + } + }], [{ + key: "isType", + value: function isType(type) { + switch (type) { + case 'i64': + case 'i128': + case 'i256': + case 'u64': + case 'u128': + case 'u256': + return true; + default: + return false; + } + } + + /** + * Convert the raw `ScValType` string (e.g. 'scvI128', generated by the XDR) + * to a type description for {@link XdrLargeInt} construction (e.g. 'i128') + * + * @param {string} scvType the `xdr.ScValType` as a string + * @returns {string} a suitable equivalent type to construct this object + */ + }, { + key: "getType", + value: function getType(scvType) { + return scvType.slice(3).toLowerCase(); + } + }]); +}(); + +/***/ }), + +/***/ 7237: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Operation = exports.AuthRevocableFlag = exports.AuthRequiredFlag = exports.AuthImmutableFlag = exports.AuthClawbackEnabledFlag = void 0; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _util = __webpack_require__(645); +var _continued_fraction = __webpack_require__(4151); +var _asset = __webpack_require__(1764); +var _liquidity_pool_asset = __webpack_require__(2262); +var _claimant = __webpack_require__(1387); +var _strkey = __webpack_require__(7120); +var _liquidity_pool_id = __webpack_require__(9353); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var ops = _interopRequireWildcard(__webpack_require__(7511)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint-disable no-bitwise */ +var ONE = 10000000; +var MAX_INT64 = '9223372036854775807'; + +/** + * When set using `{@link Operation.setOptions}` option, requires the issuing + * account to give other accounts permission before they can hold the issuing + * account’s credit. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthRequiredFlag = exports.AuthRequiredFlag = 1 << 0; +/** + * When set using `{@link Operation.setOptions}` option, allows the issuing + * account to revoke its credit held by other accounts. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthRevocableFlag = exports.AuthRevocableFlag = 1 << 1; +/** + * When set using `{@link Operation.setOptions}` option, then none of the + * authorization flags can be set and the account can never be deleted. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthImmutableFlag = exports.AuthImmutableFlag = 1 << 2; + +/** + * When set using `{@link Operation.setOptions}` option, then any trustlines + * created by this account can have a ClawbackOp operation submitted for the + * corresponding asset. + * + * @constant + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +var AuthClawbackEnabledFlag = exports.AuthClawbackEnabledFlag = 1 << 3; + +/** + * `Operation` class represents + * [operations](https://developers.stellar.org/docs/glossary/operations/) in + * Stellar network. + * + * Use one of static methods to create operations: + * * `{@link Operation.createAccount}` + * * `{@link Operation.payment}` + * * `{@link Operation.pathPaymentStrictReceive}` + * * `{@link Operation.pathPaymentStrictSend}` + * * `{@link Operation.manageSellOffer}` + * * `{@link Operation.manageBuyOffer}` + * * `{@link Operation.createPassiveSellOffer}` + * * `{@link Operation.setOptions}` + * * `{@link Operation.changeTrust}` + * * `{@link Operation.allowTrust}` + * * `{@link Operation.accountMerge}` + * * `{@link Operation.inflation}` + * * `{@link Operation.manageData}` + * * `{@link Operation.bumpSequence}` + * * `{@link Operation.createClaimableBalance}` + * * `{@link Operation.claimClaimableBalance}` + * * `{@link Operation.beginSponsoringFutureReserves}` + * * `{@link Operation.endSponsoringFutureReserves}` + * * `{@link Operation.revokeAccountSponsorship}` + * * `{@link Operation.revokeTrustlineSponsorship}` + * * `{@link Operation.revokeOfferSponsorship}` + * * `{@link Operation.revokeDataSponsorship}` + * * `{@link Operation.revokeClaimableBalanceSponsorship}` + * * `{@link Operation.revokeLiquidityPoolSponsorship}` + * * `{@link Operation.revokeSignerSponsorship}` + * * `{@link Operation.clawback}` + * * `{@link Operation.clawbackClaimableBalance}` + * * `{@link Operation.setTrustLineFlags}` + * * `{@link Operation.liquidityPoolDeposit}` + * * `{@link Operation.liquidityPoolWithdraw}` + * * `{@link Operation.invokeHostFunction}`, which has the following additional + * "pseudo-operations" that make building host functions easier: + * - `{@link Operation.createStellarAssetContract}` + * - `{@link Operation.invokeContractFunction}` + * - `{@link Operation.createCustomContract}` + * - `{@link Operation.uploadContractWasm}` + * * `{@link Operation.extendFootprintTtlOp}` + * * `{@link Operation.restoreFootprint}` + * + * @class Operation + */ +var Operation = exports.Operation = /*#__PURE__*/function () { + function Operation() { + _classCallCheck(this, Operation); + } + return _createClass(Operation, null, [{ + key: "setSourceAccount", + value: function setSourceAccount(opAttributes, opts) { + if (opts.source) { + try { + opAttributes.sourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.source); + } catch (e) { + throw new Error('Source address is invalid'); + } + } + } + + /** + * Deconstructs the raw XDR operation object into the structured object that + * was used to create the operation (i.e. the `opts` parameter to most ops). + * + * @param {xdr.Operation} operation - An XDR Operation. + * @return {Operation} + */ + }, { + key: "fromXDRObject", + value: function fromXDRObject(operation) { + var result = {}; + if (operation.sourceAccount()) { + result.source = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(operation.sourceAccount()); + } + var attrs = operation.body().value(); + var operationName = operation.body()["switch"]().name; + switch (operationName) { + case 'createAccount': + { + result.type = 'createAccount'; + result.destination = accountIdtoAddress(attrs.destination()); + result.startingBalance = this._fromXDRAmount(attrs.startingBalance()); + break; + } + case 'payment': + { + result.type = 'payment'; + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.amount = this._fromXDRAmount(attrs.amount()); + break; + } + case 'pathPaymentStrictReceive': + { + result.type = 'pathPaymentStrictReceive'; + result.sendAsset = _asset.Asset.fromOperation(attrs.sendAsset()); + result.sendMax = this._fromXDRAmount(attrs.sendMax()); + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.destAsset = _asset.Asset.fromOperation(attrs.destAsset()); + result.destAmount = this._fromXDRAmount(attrs.destAmount()); + result.path = []; + var path = attrs.path(); + + // note that Object.values isn't supported by node 6! + Object.keys(path).forEach(function (pathKey) { + result.path.push(_asset.Asset.fromOperation(path[pathKey])); + }); + break; + } + case 'pathPaymentStrictSend': + { + result.type = 'pathPaymentStrictSend'; + result.sendAsset = _asset.Asset.fromOperation(attrs.sendAsset()); + result.sendAmount = this._fromXDRAmount(attrs.sendAmount()); + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination()); + result.destAsset = _asset.Asset.fromOperation(attrs.destAsset()); + result.destMin = this._fromXDRAmount(attrs.destMin()); + result.path = []; + var _path = attrs.path(); + + // note that Object.values isn't supported by node 6! + Object.keys(_path).forEach(function (pathKey) { + result.path.push(_asset.Asset.fromOperation(_path[pathKey])); + }); + break; + } + case 'changeTrust': + { + result.type = 'changeTrust'; + switch (attrs.line()["switch"]()) { + case _xdr["default"].AssetType.assetTypePoolShare(): + result.line = _liquidity_pool_asset.LiquidityPoolAsset.fromOperation(attrs.line()); + break; + default: + result.line = _asset.Asset.fromOperation(attrs.line()); + break; + } + result.limit = this._fromXDRAmount(attrs.limit()); + break; + } + case 'allowTrust': + { + result.type = 'allowTrust'; + result.trustor = accountIdtoAddress(attrs.trustor()); + result.assetCode = attrs.asset().value().toString(); + result.assetCode = (0, _util.trimEnd)(result.assetCode, '\0'); + result.authorize = attrs.authorize(); + break; + } + case 'setOptions': + { + result.type = 'setOptions'; + if (attrs.inflationDest()) { + result.inflationDest = accountIdtoAddress(attrs.inflationDest()); + } + result.clearFlags = attrs.clearFlags(); + result.setFlags = attrs.setFlags(); + result.masterWeight = attrs.masterWeight(); + result.lowThreshold = attrs.lowThreshold(); + result.medThreshold = attrs.medThreshold(); + result.highThreshold = attrs.highThreshold(); + // home_domain is checked by iscntrl in stellar-core + result.homeDomain = attrs.homeDomain() !== undefined ? attrs.homeDomain().toString('ascii') : undefined; + if (attrs.signer()) { + var signer = {}; + var arm = attrs.signer().key().arm(); + if (arm === 'ed25519') { + signer.ed25519PublicKey = accountIdtoAddress(attrs.signer().key()); + } else if (arm === 'preAuthTx') { + signer.preAuthTx = attrs.signer().key().preAuthTx(); + } else if (arm === 'hashX') { + signer.sha256Hash = attrs.signer().key().hashX(); + } else if (arm === 'ed25519SignedPayload') { + var signedPayload = attrs.signer().key().ed25519SignedPayload(); + signer.ed25519SignedPayload = _strkey.StrKey.encodeSignedPayload(signedPayload.toXDR()); + } + signer.weight = attrs.signer().weight(); + result.signer = signer; + } + break; + } + // the next case intentionally falls through! + case 'manageOffer': + case 'manageSellOffer': + { + result.type = 'manageSellOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.price = this._fromXDRPrice(attrs.price()); + result.offerId = attrs.offerId().toString(); + break; + } + case 'manageBuyOffer': + { + result.type = 'manageBuyOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.buyAmount = this._fromXDRAmount(attrs.buyAmount()); + result.price = this._fromXDRPrice(attrs.price()); + result.offerId = attrs.offerId().toString(); + break; + } + // the next case intentionally falls through! + case 'createPassiveOffer': + case 'createPassiveSellOffer': + { + result.type = 'createPassiveSellOffer'; + result.selling = _asset.Asset.fromOperation(attrs.selling()); + result.buying = _asset.Asset.fromOperation(attrs.buying()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.price = this._fromXDRPrice(attrs.price()); + break; + } + case 'accountMerge': + { + result.type = 'accountMerge'; + result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs); + break; + } + case 'manageData': + { + result.type = 'manageData'; + // manage_data.name is checked by iscntrl in stellar-core + result.name = attrs.dataName().toString('ascii'); + result.value = attrs.dataValue(); + break; + } + case 'inflation': + { + result.type = 'inflation'; + break; + } + case 'bumpSequence': + { + result.type = 'bumpSequence'; + result.bumpTo = attrs.bumpTo().toString(); + break; + } + case 'createClaimableBalance': + { + result.type = 'createClaimableBalance'; + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.amount = this._fromXDRAmount(attrs.amount()); + result.claimants = []; + attrs.claimants().forEach(function (claimant) { + result.claimants.push(_claimant.Claimant.fromXDR(claimant)); + }); + break; + } + case 'claimClaimableBalance': + { + result.type = 'claimClaimableBalance'; + result.balanceId = attrs.toXDR('hex'); + break; + } + case 'beginSponsoringFutureReserves': + { + result.type = 'beginSponsoringFutureReserves'; + result.sponsoredId = accountIdtoAddress(attrs.sponsoredId()); + break; + } + case 'endSponsoringFutureReserves': + { + result.type = 'endSponsoringFutureReserves'; + break; + } + case 'revokeSponsorship': + { + extractRevokeSponshipDetails(attrs, result); + break; + } + case 'clawback': + { + result.type = 'clawback'; + result.amount = this._fromXDRAmount(attrs.amount()); + result.from = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.from()); + result.asset = _asset.Asset.fromOperation(attrs.asset()); + break; + } + case 'clawbackClaimableBalance': + { + result.type = 'clawbackClaimableBalance'; + result.balanceId = attrs.toXDR('hex'); + break; + } + case 'setTrustLineFlags': + { + result.type = 'setTrustLineFlags'; + result.asset = _asset.Asset.fromOperation(attrs.asset()); + result.trustor = accountIdtoAddress(attrs.trustor()); + + // Convert from the integer-bitwised flag into a sensible object that + // indicates true/false for each flag that's on/off. + var clears = attrs.clearFlags(); + var sets = attrs.setFlags(); + var mapping = { + authorized: _xdr["default"].TrustLineFlags.authorizedFlag(), + authorizedToMaintainLiabilities: _xdr["default"].TrustLineFlags.authorizedToMaintainLiabilitiesFlag(), + clawbackEnabled: _xdr["default"].TrustLineFlags.trustlineClawbackEnabledFlag() + }; + var getFlagValue = function getFlagValue(key) { + var bit = mapping[key].value; + if (sets & bit) { + return true; + } + if (clears & bit) { + return false; + } + return undefined; + }; + result.flags = {}; + Object.keys(mapping).forEach(function (flagName) { + result.flags[flagName] = getFlagValue(flagName); + }); + break; + } + case 'liquidityPoolDeposit': + { + result.type = 'liquidityPoolDeposit'; + result.liquidityPoolId = attrs.liquidityPoolId().toString('hex'); + result.maxAmountA = this._fromXDRAmount(attrs.maxAmountA()); + result.maxAmountB = this._fromXDRAmount(attrs.maxAmountB()); + result.minPrice = this._fromXDRPrice(attrs.minPrice()); + result.maxPrice = this._fromXDRPrice(attrs.maxPrice()); + break; + } + case 'liquidityPoolWithdraw': + { + result.type = 'liquidityPoolWithdraw'; + result.liquidityPoolId = attrs.liquidityPoolId().toString('hex'); + result.amount = this._fromXDRAmount(attrs.amount()); + result.minAmountA = this._fromXDRAmount(attrs.minAmountA()); + result.minAmountB = this._fromXDRAmount(attrs.minAmountB()); + break; + } + case 'invokeHostFunction': + { + var _attrs$auth; + result.type = 'invokeHostFunction'; + result.func = attrs.hostFunction(); + result.auth = (_attrs$auth = attrs.auth()) !== null && _attrs$auth !== void 0 ? _attrs$auth : []; + break; + } + case 'extendFootprintTtl': + { + result.type = 'extendFootprintTtl'; + result.extendTo = attrs.extendTo(); + break; + } + case 'restoreFootprint': + { + result.type = 'restoreFootprint'; + break; + } + default: + { + throw new Error("Unknown operation: ".concat(operationName)); + } + } + return result; + } + + /** + * Validates that a given amount is possible for a Stellar asset. + * + * Specifically, this means that the amount is well, a valid number, but also + * that it is within the int64 range and has no more than 7 decimal levels of + * precision. + * + * Note that while smart contracts allow larger amounts, this is oriented + * towards validating the standard Stellar operations. + * + * @param {string} value the amount to validate + * @param {boolean} allowZero optionally, whether or not zero is valid (default: no) + * + * @returns {boolean} + */ + }, { + key: "isValidAmount", + value: function isValidAmount(value) { + var allowZero = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (typeof value !== 'string') { + return false; + } + var amount; + try { + amount = new _bignumber["default"](value); + } catch (e) { + return false; + } + if ( + // == 0 + !allowZero && amount.isZero() || + // < 0 + amount.isNegative() || + // > Max value + amount.times(ONE).gt(new _bignumber["default"](MAX_INT64).toString()) || + // Decimal places (max 7) + amount.decimalPlaces() > 7 || + // NaN or Infinity + amount.isNaN() || !amount.isFinite()) { + return false; + } + return true; + } + }, { + key: "constructAmountRequirementsError", + value: function constructAmountRequirementsError(arg) { + return "".concat(arg, " argument must be of type String, represent a positive number and have at most 7 digits after the decimal"); + } + + /** + * Returns value converted to uint32 value or undefined. + * If `value` is not `Number`, `String` or `Undefined` then throws an error. + * Used in {@link Operation.setOptions}. + * @private + * @param {string} name Name of the property (used in error message only) + * @param {*} value Value to check + * @param {function(value, name)} isValidFunction Function to check other constraints (the argument will be a `Number`) + * @returns {undefined|Number} + */ + }, { + key: "_checkUnsignedIntValue", + value: function _checkUnsignedIntValue(name, value) { + var isValidFunction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + if (typeof value === 'undefined') { + return undefined; + } + if (typeof value === 'string') { + value = parseFloat(value); + } + switch (true) { + case typeof value !== 'number' || !Number.isFinite(value) || value % 1 !== 0: + throw new Error("".concat(name, " value is invalid")); + case value < 0: + throw new Error("".concat(name, " value must be unsigned")); + case !isValidFunction || isValidFunction && isValidFunction(value, name): + return value; + default: + throw new Error("".concat(name, " value is invalid")); + } + } + /** + * @private + * @param {string|BigNumber} value Value + * @returns {Hyper} XDR amount + */ + }, { + key: "_toXDRAmount", + value: function _toXDRAmount(value) { + var amount = new _bignumber["default"](value).times(ONE); + return _jsXdr.Hyper.fromString(amount.toString()); + } + + /** + * @private + * @param {string|BigNumber} value XDR amount + * @returns {BigNumber} Number + */ + }, { + key: "_fromXDRAmount", + value: function _fromXDRAmount(value) { + return new _bignumber["default"](value).div(ONE).toFixed(7); + } + + /** + * @private + * @param {object} price Price object + * @param {function} price.n numerator function that returns a value + * @param {function} price.d denominator function that returns a value + * @returns {BigNumber} Big string + */ + }, { + key: "_fromXDRPrice", + value: function _fromXDRPrice(price) { + var n = new _bignumber["default"](price.n()); + return n.div(new _bignumber["default"](price.d())).toString(); + } + + /** + * @private + * @param {object} price Price object + * @param {function} price.n numerator function that returns a value + * @param {function} price.d denominator function that returns a value + * @returns {object} XDR price object + */ + }, { + key: "_toXDRPrice", + value: function _toXDRPrice(price) { + var xdrObject; + if (price.n && price.d) { + xdrObject = new _xdr["default"].Price(price); + } else { + var approx = (0, _continued_fraction.best_r)(price); + xdrObject = new _xdr["default"].Price({ + n: parseInt(approx[0], 10), + d: parseInt(approx[1], 10) + }); + } + if (xdrObject.n() < 0 || xdrObject.d() < 0) { + throw new Error('price must be positive'); + } + return xdrObject; + } + }]); +}(); +function extractRevokeSponshipDetails(attrs, result) { + switch (attrs["switch"]().name) { + case 'revokeSponsorshipLedgerEntry': + { + var ledgerKey = attrs.ledgerKey(); + switch (ledgerKey["switch"]().name) { + case _xdr["default"].LedgerEntryType.account().name: + { + result.type = 'revokeAccountSponsorship'; + result.account = accountIdtoAddress(ledgerKey.account().accountId()); + break; + } + case _xdr["default"].LedgerEntryType.trustline().name: + { + result.type = 'revokeTrustlineSponsorship'; + result.account = accountIdtoAddress(ledgerKey.trustLine().accountId()); + var xdrAsset = ledgerKey.trustLine().asset(); + switch (xdrAsset["switch"]()) { + case _xdr["default"].AssetType.assetTypePoolShare(): + result.asset = _liquidity_pool_id.LiquidityPoolId.fromOperation(xdrAsset); + break; + default: + result.asset = _asset.Asset.fromOperation(xdrAsset); + break; + } + break; + } + case _xdr["default"].LedgerEntryType.offer().name: + { + result.type = 'revokeOfferSponsorship'; + result.seller = accountIdtoAddress(ledgerKey.offer().sellerId()); + result.offerId = ledgerKey.offer().offerId().toString(); + break; + } + case _xdr["default"].LedgerEntryType.data().name: + { + result.type = 'revokeDataSponsorship'; + result.account = accountIdtoAddress(ledgerKey.data().accountId()); + result.name = ledgerKey.data().dataName().toString('ascii'); + break; + } + case _xdr["default"].LedgerEntryType.claimableBalance().name: + { + result.type = 'revokeClaimableBalanceSponsorship'; + result.balanceId = ledgerKey.claimableBalance().balanceId().toXDR('hex'); + break; + } + case _xdr["default"].LedgerEntryType.liquidityPool().name: + { + result.type = 'revokeLiquidityPoolSponsorship'; + result.liquidityPoolId = ledgerKey.liquidityPool().liquidityPoolId().toString('hex'); + break; + } + default: + { + throw new Error("Unknown ledgerKey: ".concat(attrs["switch"]().name)); + } + } + break; + } + case 'revokeSponsorshipSigner': + { + result.type = 'revokeSignerSponsorship'; + result.account = accountIdtoAddress(attrs.signer().accountId()); + result.signer = convertXDRSignerKeyToObject(attrs.signer().signerKey()); + break; + } + default: + { + throw new Error("Unknown revokeSponsorship: ".concat(attrs["switch"]().name)); + } + } +} +function convertXDRSignerKeyToObject(signerKey) { + var attrs = {}; + switch (signerKey["switch"]().name) { + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519().name: + { + attrs.ed25519PublicKey = _strkey.StrKey.encodeEd25519PublicKey(signerKey.ed25519()); + break; + } + case _xdr["default"].SignerKeyType.signerKeyTypePreAuthTx().name: + { + attrs.preAuthTx = signerKey.preAuthTx().toString('hex'); + break; + } + case _xdr["default"].SignerKeyType.signerKeyTypeHashX().name: + { + attrs.sha256Hash = signerKey.hashX().toString('hex'); + break; + } + default: + { + throw new Error("Unknown signerKey: ".concat(signerKey["switch"]().name)); + } + } + return attrs; +} +function accountIdtoAddress(accountId) { + return _strkey.StrKey.encodeEd25519PublicKey(accountId.ed25519()); +} + +// Attach all imported operations as static methods on the Operation class +Operation.accountMerge = ops.accountMerge; +Operation.allowTrust = ops.allowTrust; +Operation.bumpSequence = ops.bumpSequence; +Operation.changeTrust = ops.changeTrust; +Operation.createAccount = ops.createAccount; +Operation.createClaimableBalance = ops.createClaimableBalance; +Operation.claimClaimableBalance = ops.claimClaimableBalance; +Operation.clawbackClaimableBalance = ops.clawbackClaimableBalance; +Operation.createPassiveSellOffer = ops.createPassiveSellOffer; +Operation.inflation = ops.inflation; +Operation.manageData = ops.manageData; +Operation.manageSellOffer = ops.manageSellOffer; +Operation.manageBuyOffer = ops.manageBuyOffer; +Operation.pathPaymentStrictReceive = ops.pathPaymentStrictReceive; +Operation.pathPaymentStrictSend = ops.pathPaymentStrictSend; +Operation.payment = ops.payment; +Operation.setOptions = ops.setOptions; +Operation.beginSponsoringFutureReserves = ops.beginSponsoringFutureReserves; +Operation.endSponsoringFutureReserves = ops.endSponsoringFutureReserves; +Operation.revokeAccountSponsorship = ops.revokeAccountSponsorship; +Operation.revokeTrustlineSponsorship = ops.revokeTrustlineSponsorship; +Operation.revokeOfferSponsorship = ops.revokeOfferSponsorship; +Operation.revokeDataSponsorship = ops.revokeDataSponsorship; +Operation.revokeClaimableBalanceSponsorship = ops.revokeClaimableBalanceSponsorship; +Operation.revokeLiquidityPoolSponsorship = ops.revokeLiquidityPoolSponsorship; +Operation.revokeSignerSponsorship = ops.revokeSignerSponsorship; +Operation.clawback = ops.clawback; +Operation.setTrustLineFlags = ops.setTrustLineFlags; +Operation.liquidityPoolDeposit = ops.liquidityPoolDeposit; +Operation.liquidityPoolWithdraw = ops.liquidityPoolWithdraw; +Operation.invokeHostFunction = ops.invokeHostFunction; +Operation.extendFootprintTtl = ops.extendFootprintTtl; +Operation.restoreFootprint = ops.restoreFootprint; + +// these are not `xdr.Operation`s directly, but are proxies for complex but +// common versions of `Operation.invokeHostFunction` +Operation.createStellarAssetContract = ops.createStellarAssetContract; +Operation.invokeContractFunction = ops.invokeContractFunction; +Operation.createCustomContract = ops.createCustomContract; +Operation.uploadContractWasm = ops.uploadContractWasm; + +/***/ }), + +/***/ 4295: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.accountMerge = accountMerge; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Transfers native balance to destination account. + * + * @function + * @alias Operation.accountMerge + * + * @param {object} opts - options object + * @param {string} opts.destination - destination to merge the source account into + * @param {string} [opts.source] - operation source account (defaults to + * transaction source) + * + * @returns {xdr.Operation} an Account Merge operation (xdr.AccountMergeOp) + */ +function accountMerge(opts) { + var opAttributes = {}; + try { + opAttributes.body = _xdr["default"].OperationBody.accountMerge((0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination)); + } catch (e) { + throw new Error('destination is invalid'); + } + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 3683: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.allowTrust = allowTrust; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * @deprecated since v5.0 + * + * Returns an XDR AllowTrustOp. An "allow trust" operation authorizes another + * account to hold your account's credit for a given asset. + * + * @function + * @alias Operation.allowTrust + * + * @param {object} opts Options object + * @param {string} opts.trustor - The trusting account (the one being authorized) + * @param {string} opts.assetCode - The asset code being authorized. + * @param {(0|1|2)} opts.authorize - `1` to authorize, `2` to authorize to maintain liabilities, and `0` to deauthorize. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * + * @returns {xdr.AllowTrustOp} Allow Trust operation + */ +function allowTrust(opts) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.trustor)) { + throw new Error('trustor is invalid'); + } + var attributes = {}; + attributes.trustor = _keypair.Keypair.fromPublicKey(opts.trustor).xdrAccountId(); + if (opts.assetCode.length <= 4) { + var code = opts.assetCode.padEnd(4, '\0'); + attributes.asset = _xdr["default"].AssetCode.assetTypeCreditAlphanum4(code); + } else if (opts.assetCode.length <= 12) { + var _code = opts.assetCode.padEnd(12, '\0'); + attributes.asset = _xdr["default"].AssetCode.assetTypeCreditAlphanum12(_code); + } else { + throw new Error('Asset code must be 12 characters at max.'); + } + if (typeof opts.authorize === 'boolean') { + if (opts.authorize) { + attributes.authorize = _xdr["default"].TrustLineFlags.authorizedFlag().value; + } else { + attributes.authorize = 0; + } + } else { + attributes.authorize = opts.authorize; + } + var allowTrustOp = new _xdr["default"].AllowTrustOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.allowTrust(allowTrustOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7505: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.beginSponsoringFutureReserves = beginSponsoringFutureReserves; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +var _keypair = __webpack_require__(6691); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a "begin sponsoring future reserves" operation. + * @function + * @alias Operation.beginSponsoringFutureReserves + * @param {object} opts Options object + * @param {string} opts.sponsoredId - The sponsored account id. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.beginSponsoringFutureReserves({ + * sponsoredId: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * }); + * + */ +function beginSponsoringFutureReserves() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.sponsoredId)) { + throw new Error('sponsoredId is invalid'); + } + var op = new _xdr["default"].BeginSponsoringFutureReservesOp({ + sponsoredId: _keypair.Keypair.fromPublicKey(opts.sponsoredId).xdrAccountId() + }); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.beginSponsoringFutureReserves(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 6183: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.bumpSequence = bumpSequence; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation bumps sequence number. + * @function + * @alias Operation.bumpSequence + * @param {object} opts Options object + * @param {string} opts.bumpTo - Sequence number to bump to. + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.BumpSequenceOp} Operation + */ +function bumpSequence(opts) { + var attributes = {}; + if (typeof opts.bumpTo !== 'string') { + throw new Error('bumpTo must be a string'); + } + try { + // eslint-disable-next-line no-new + new _bignumber["default"](opts.bumpTo); + } catch (e) { + throw new Error('bumpTo must be a stringified number'); + } + attributes.bumpTo = _jsXdr.Hyper.fromString(opts.bumpTo); + var bumpSequenceOp = new _xdr["default"].BumpSequenceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.bumpSequence(bumpSequenceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2810: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.changeTrust = changeTrust; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +var _liquidity_pool_asset = __webpack_require__(2262); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var MAX_INT64 = '9223372036854775807'; + +/** + * Returns an XDR ChangeTrustOp. A "change trust" operation adds, removes, or updates a + * trust line for a given asset from the source account to another. + * @function + * @alias Operation.changeTrust + * @param {object} opts Options object + * @param {Asset | LiquidityPoolAsset} opts.asset - The asset for the trust line. + * @param {string} [opts.limit] - The limit for the asset, defaults to max int64. + * If the limit is set to "0" it deletes the trustline. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @returns {xdr.ChangeTrustOp} Change Trust operation + */ +function changeTrust(opts) { + var attributes = {}; + if (opts.asset instanceof _asset.Asset) { + attributes.line = opts.asset.toChangeTrustXDRObject(); + } else if (opts.asset instanceof _liquidity_pool_asset.LiquidityPoolAsset) { + attributes.line = opts.asset.toXDRObject(); + } else { + throw new TypeError('asset must be Asset or LiquidityPoolAsset'); + } + if (opts.limit !== undefined && !this.isValidAmount(opts.limit, true)) { + throw new TypeError(this.constructAmountRequirementsError('limit')); + } + if (opts.limit) { + attributes.limit = this._toXDRAmount(opts.limit); + } else { + attributes.limit = _jsXdr.Hyper.fromString(new _bignumber["default"](MAX_INT64).toString()); + } + if (opts.source) { + attributes.source = opts.source.masterKeypair; + } + var changeTrustOP = new _xdr["default"].ChangeTrustOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.changeTrust(changeTrustOP); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7239: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.claimClaimableBalance = claimClaimableBalance; +exports.validateClaimableBalanceId = validateClaimableBalanceId; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a new claim claimable balance operation. + * @function + * @alias Operation.claimClaimableBalance + * @param {object} opts Options object + * @param {string} opts.balanceId - The claimable balance id to be claimed. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} Claim claimable balance operation + * + * @example + * const op = Operation.claimClaimableBalance({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + */ +function claimClaimableBalance() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + validateClaimableBalanceId(opts.balanceId); + var attributes = {}; + attributes.balanceId = _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex'); + var claimClaimableBalanceOp = new _xdr["default"].ClaimClaimableBalanceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.claimClaimableBalance(claimClaimableBalanceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} +function validateClaimableBalanceId(balanceId) { + if (typeof balanceId !== 'string' || balanceId.length !== 8 + 64 /* 8b discriminant + 64b string */) { + throw new Error('must provide a valid claimable balance id'); + } +} + +/***/ }), + +/***/ 7651: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.clawback = clawback; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a clawback operation. + * + * @function + * @alias Operation.clawback + * + * @param {object} opts - Options object + * @param {Asset} opts.asset - The asset being clawed back. + * @param {string} opts.amount - The amount of the asset to claw back. + * @param {string} opts.from - The public key of the (optionally-muxed) + * account to claw back from. + * + * @param {string} [opts.source] - The source account for the operation. + * Defaults to the transaction's source account. + * + * @return {xdr.ClawbackOp} + * + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#clawback-operation + */ +function clawback(opts) { + var attributes = {}; + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + attributes.asset = opts.asset.toXDRObject(); + try { + attributes.from = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.from); + } catch (e) { + throw new Error('from address is invalid'); + } + var opAttributes = { + body: _xdr["default"].OperationBody.clawback(new _xdr["default"].ClawbackOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2203: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.clawbackClaimableBalance = clawbackClaimableBalance; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _claim_claimable_balance = __webpack_require__(7239); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a clawback operation for a claimable balance. + * + * @function + * @alias Operation.clawbackClaimableBalance + * @param {object} opts - Options object + * @param {string} opts.balanceId - The claimable balance ID to be clawed back. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @return {xdr.ClawbackClaimableBalanceOp} + * + * @example + * const op = Operation.clawbackClaimableBalance({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + * @link https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#clawback-claimable-balance-operation + */ +function clawbackClaimableBalance() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + (0, _claim_claimable_balance.validateClaimableBalanceId)(opts.balanceId); + var attributes = { + balanceId: _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex') + }; + var opAttributes = { + body: _xdr["default"].OperationBody.clawbackClaimableBalance(new _xdr["default"].ClawbackClaimableBalanceOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2115: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createAccount = createAccount; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create and fund a non existent account. + * @function + * @alias Operation.createAccount + * @param {object} opts Options object + * @param {string} opts.destination - Destination account ID to create an account for. + * @param {string} opts.startingBalance - Amount in XLM the account should be funded for. Must be greater + * than the [reserve balance amount](https://developers.stellar.org/docs/glossary/fees/). + * @param {string} [opts.source] - The source account for the payment. Defaults to the transaction's source account. + * @returns {xdr.CreateAccountOp} Create account operation + */ +function createAccount(opts) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.destination)) { + throw new Error('destination is invalid'); + } + if (!this.isValidAmount(opts.startingBalance, true)) { + throw new TypeError(this.constructAmountRequirementsError('startingBalance')); + } + var attributes = {}; + attributes.destination = _keypair.Keypair.fromPublicKey(opts.destination).xdrAccountId(); + attributes.startingBalance = this._toXDRAmount(opts.startingBalance); + var createAccountOp = new _xdr["default"].CreateAccountOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createAccount(createAccountOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 4831: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createClaimableBalance = createClaimableBalance; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _asset = __webpack_require__(1764); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a new claimable balance operation. + * + * @function + * @alias Operation.createClaimableBalance + * + * @param {object} opts Options object + * @param {Asset} opts.asset - The asset for the claimable balance. + * @param {string} opts.amount - Amount. + * @param {Claimant[]} opts.claimants - An array of Claimants + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} Create claimable balance operation + * + * @example + * const asset = new Asset( + * 'USD', + * 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * ); + * const amount = '100.0000000'; + * const claimants = [ + * new Claimant( + * 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ', + * Claimant.predicateBeforeAbsoluteTime("4102444800000") + * ) + * ]; + * + * const op = Operation.createClaimableBalance({ + * asset, + * amount, + * claimants + * }); + * + */ +function createClaimableBalance(opts) { + if (!(opts.asset instanceof _asset.Asset)) { + throw new Error('must provide an asset for create claimable balance operation'); + } + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + if (!Array.isArray(opts.claimants) || opts.claimants.length === 0) { + throw new Error('must provide at least one claimant'); + } + var attributes = {}; + attributes.asset = opts.asset.toXDRObject(); + attributes.amount = this._toXDRAmount(opts.amount); + attributes.claimants = Object.values(opts.claimants).map(function (c) { + return c.toXDRObject(); + }); + var createClaimableBalanceOp = new _xdr["default"].CreateClaimableBalanceOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createClaimableBalance(createClaimableBalanceOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 9073: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createPassiveSellOffer = createPassiveSellOffer; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR CreatePasiveSellOfferOp. A "create passive offer" operation creates an + * offer that won't consume a counter offer that exactly matches this offer. This is + * useful for offers just used as 1:1 exchanges for path payments. Use manage offer + * to manage this offer after using this operation to create it. + * @function + * @alias Operation.createPassiveSellOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.CreatePassiveSellOfferOp} Create Passive Sell Offer operation + */ +function createPassiveSellOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + var createPassiveSellOfferOp = new _xdr["default"].CreatePassiveSellOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.createPassiveSellOffer(createPassiveSellOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 721: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.endSponsoringFutureReserves = endSponsoringFutureReserves; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create an "end sponsoring future reserves" operation. + * @function + * @alias Operation.endSponsoringFutureReserves + * @param {object} opts Options object + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.endSponsoringFutureReserves(); + * + */ +function endSponsoringFutureReserves() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.endSponsoringFutureReserves(); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 8752: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.extendFootprintTtl = extendFootprintTtl; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Builds an operation to bump the time-to-live (TTL) of the ledger keys. The + * keys for extension have to be provided in the read-only footprint of + * the transaction. + * + * The only parameter of the operation itself is the new minimum TTL for + * all the provided entries. If an entry already has a higher TTL, then it + * will just be skipped. + * + * TTL is the number of ledgers from the current ledger (exclusive) until + * the last ledger the entry is still considered alive (inclusive). Thus + * the exact ledger until the entries will live will only be determined + * when transaction has been applied. + * + * The footprint has to be specified in the transaction. See + * {@link TransactionBuilder}'s `opts.sorobanData` parameter, which is a + * {@link xdr.SorobanTransactionData} instance that contains fee data & resource + * usage as part of {@link xdr.SorobanResources}. + * + * @function + * @alias Operation.extendFootprintTtl + * + * @param {object} opts - object holding operation parameters + * @param {number} opts.extendTo - the minimum TTL that all the entries in + * the read-only footprint will have + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Extend Footprint TTL operation + * (xdr.ExtendFootprintTTLOp) + */ +function extendFootprintTtl(opts) { + var _opts$extendTo; + if (((_opts$extendTo = opts.extendTo) !== null && _opts$extendTo !== void 0 ? _opts$extendTo : -1) <= 0) { + throw new RangeError('extendTo has to be positive'); + } + var extendFootprintOp = new _xdr["default"].ExtendFootprintTtlOp({ + ext: new _xdr["default"].ExtensionPoint(0), + extendTo: opts.extendTo + }); + var opAttributes = { + body: _xdr["default"].OperationBody.extendFootprintTtl(extendFootprintOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7511: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "accountMerge", ({ + enumerable: true, + get: function get() { + return _account_merge.accountMerge; + } +})); +Object.defineProperty(exports, "allowTrust", ({ + enumerable: true, + get: function get() { + return _allow_trust.allowTrust; + } +})); +Object.defineProperty(exports, "beginSponsoringFutureReserves", ({ + enumerable: true, + get: function get() { + return _begin_sponsoring_future_reserves.beginSponsoringFutureReserves; + } +})); +Object.defineProperty(exports, "bumpSequence", ({ + enumerable: true, + get: function get() { + return _bump_sequence.bumpSequence; + } +})); +Object.defineProperty(exports, "changeTrust", ({ + enumerable: true, + get: function get() { + return _change_trust.changeTrust; + } +})); +Object.defineProperty(exports, "claimClaimableBalance", ({ + enumerable: true, + get: function get() { + return _claim_claimable_balance.claimClaimableBalance; + } +})); +Object.defineProperty(exports, "clawback", ({ + enumerable: true, + get: function get() { + return _clawback.clawback; + } +})); +Object.defineProperty(exports, "clawbackClaimableBalance", ({ + enumerable: true, + get: function get() { + return _clawback_claimable_balance.clawbackClaimableBalance; + } +})); +Object.defineProperty(exports, "createAccount", ({ + enumerable: true, + get: function get() { + return _create_account.createAccount; + } +})); +Object.defineProperty(exports, "createClaimableBalance", ({ + enumerable: true, + get: function get() { + return _create_claimable_balance.createClaimableBalance; + } +})); +Object.defineProperty(exports, "createCustomContract", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.createCustomContract; + } +})); +Object.defineProperty(exports, "createPassiveSellOffer", ({ + enumerable: true, + get: function get() { + return _create_passive_sell_offer.createPassiveSellOffer; + } +})); +Object.defineProperty(exports, "createStellarAssetContract", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.createStellarAssetContract; + } +})); +Object.defineProperty(exports, "endSponsoringFutureReserves", ({ + enumerable: true, + get: function get() { + return _end_sponsoring_future_reserves.endSponsoringFutureReserves; + } +})); +Object.defineProperty(exports, "extendFootprintTtl", ({ + enumerable: true, + get: function get() { + return _extend_footprint_ttl.extendFootprintTtl; + } +})); +Object.defineProperty(exports, "inflation", ({ + enumerable: true, + get: function get() { + return _inflation.inflation; + } +})); +Object.defineProperty(exports, "invokeContractFunction", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.invokeContractFunction; + } +})); +Object.defineProperty(exports, "invokeHostFunction", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.invokeHostFunction; + } +})); +Object.defineProperty(exports, "liquidityPoolDeposit", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_deposit.liquidityPoolDeposit; + } +})); +Object.defineProperty(exports, "liquidityPoolWithdraw", ({ + enumerable: true, + get: function get() { + return _liquidity_pool_withdraw.liquidityPoolWithdraw; + } +})); +Object.defineProperty(exports, "manageBuyOffer", ({ + enumerable: true, + get: function get() { + return _manage_buy_offer.manageBuyOffer; + } +})); +Object.defineProperty(exports, "manageData", ({ + enumerable: true, + get: function get() { + return _manage_data.manageData; + } +})); +Object.defineProperty(exports, "manageSellOffer", ({ + enumerable: true, + get: function get() { + return _manage_sell_offer.manageSellOffer; + } +})); +Object.defineProperty(exports, "pathPaymentStrictReceive", ({ + enumerable: true, + get: function get() { + return _path_payment_strict_receive.pathPaymentStrictReceive; + } +})); +Object.defineProperty(exports, "pathPaymentStrictSend", ({ + enumerable: true, + get: function get() { + return _path_payment_strict_send.pathPaymentStrictSend; + } +})); +Object.defineProperty(exports, "payment", ({ + enumerable: true, + get: function get() { + return _payment.payment; + } +})); +Object.defineProperty(exports, "restoreFootprint", ({ + enumerable: true, + get: function get() { + return _restore_footprint.restoreFootprint; + } +})); +Object.defineProperty(exports, "revokeAccountSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeAccountSponsorship; + } +})); +Object.defineProperty(exports, "revokeClaimableBalanceSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeClaimableBalanceSponsorship; + } +})); +Object.defineProperty(exports, "revokeDataSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeDataSponsorship; + } +})); +Object.defineProperty(exports, "revokeLiquidityPoolSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeLiquidityPoolSponsorship; + } +})); +Object.defineProperty(exports, "revokeOfferSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeOfferSponsorship; + } +})); +Object.defineProperty(exports, "revokeSignerSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeSignerSponsorship; + } +})); +Object.defineProperty(exports, "revokeTrustlineSponsorship", ({ + enumerable: true, + get: function get() { + return _revoke_sponsorship.revokeTrustlineSponsorship; + } +})); +Object.defineProperty(exports, "setOptions", ({ + enumerable: true, + get: function get() { + return _set_options.setOptions; + } +})); +Object.defineProperty(exports, "setTrustLineFlags", ({ + enumerable: true, + get: function get() { + return _set_trustline_flags.setTrustLineFlags; + } +})); +Object.defineProperty(exports, "uploadContractWasm", ({ + enumerable: true, + get: function get() { + return _invoke_host_function.uploadContractWasm; + } +})); +var _manage_sell_offer = __webpack_require__(862); +var _create_passive_sell_offer = __webpack_require__(9073); +var _account_merge = __webpack_require__(4295); +var _allow_trust = __webpack_require__(3683); +var _bump_sequence = __webpack_require__(6183); +var _change_trust = __webpack_require__(2810); +var _create_account = __webpack_require__(2115); +var _create_claimable_balance = __webpack_require__(4831); +var _claim_claimable_balance = __webpack_require__(7239); +var _clawback_claimable_balance = __webpack_require__(2203); +var _inflation = __webpack_require__(7421); +var _manage_data = __webpack_require__(1411); +var _manage_buy_offer = __webpack_require__(1922); +var _path_payment_strict_receive = __webpack_require__(2075); +var _path_payment_strict_send = __webpack_require__(3874); +var _payment = __webpack_require__(3533); +var _set_options = __webpack_require__(2018); +var _begin_sponsoring_future_reserves = __webpack_require__(7505); +var _end_sponsoring_future_reserves = __webpack_require__(721); +var _revoke_sponsorship = __webpack_require__(7790); +var _clawback = __webpack_require__(7651); +var _set_trustline_flags = __webpack_require__(1804); +var _liquidity_pool_deposit = __webpack_require__(9845); +var _liquidity_pool_withdraw = __webpack_require__(4737); +var _invoke_host_function = __webpack_require__(4403); +var _extend_footprint_ttl = __webpack_require__(8752); +var _restore_footprint = __webpack_require__(149); + +/***/ }), + +/***/ 7421: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.inflation = inflation; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation generates the inflation. + * @function + * @alias Operation.inflation + * @param {object} [opts] Options object + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.InflationOp} Inflation operation + */ +function inflation() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.inflation(); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 4403: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createCustomContract = createCustomContract; +exports.createStellarAssetContract = createStellarAssetContract; +exports.invokeContractFunction = invokeContractFunction; +exports.invokeHostFunction = invokeHostFunction; +exports.uploadContractWasm = uploadContractWasm; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _address = __webpack_require__(1180); +var _asset = __webpack_require__(1764); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +/** + * Invokes a single smart contract host function. + * + * @function + * @alias Operation.invokeHostFunction + * + * @param {object} opts - options object + * @param {xdr.HostFunction} opts.func - host function to execute (with its + * wrapped parameters) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - list outlining the + * tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + * @see Operation.invokeContractFunction + * @see Operation.createCustomContract + * @see Operation.createStellarAssetContract + * @see Operation.uploadContractWasm + * @see Contract.call + */ +function invokeHostFunction(opts) { + if (!opts.func) { + throw new TypeError("host function invocation ('func') required (got ".concat(JSON.stringify(opts), ")")); + } + var invokeHostFunctionOp = new _xdr["default"].InvokeHostFunctionOp({ + hostFunction: opts.func, + auth: opts.auth || [] + }); + var opAttributes = { + body: _xdr["default"].OperationBody.invokeHostFunction(invokeHostFunctionOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Returns an operation that invokes a contract function. + * + * @function + * @alias Operation.invokeContractFunction + * + * @param {any} opts - the set of parameters + * @param {string} opts.contract - a strkey-fied contract address (`C...`) + * @param {string} opts.function - the name of the contract fn to invoke + * @param {xdr.ScVal[]} opts.args - parameters to pass to the function + * invocation (try {@link nativeToScVal} or {@link ScInt} to make building + * these easier) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see Operation.invokeHostFunction + * @see Contract.call + * @see Address + */ +function invokeContractFunction(opts) { + var c = new _address.Address(opts.contract); + if (c._type !== 'contract') { + throw new TypeError("expected contract strkey instance, got ".concat(c)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeInvokeContract(new _xdr["default"].InvokeContractArgs({ + contractAddress: c.toScAddress(), + functionName: opts["function"], + args: opts.args + })) + }); +} + +/** + * Returns an operation that creates a custom WASM contract and atomically + * invokes its constructor. + * + * @function + * @alias Operation.createCustomContract + * + * @param {any} opts - the set of parameters + * @param {Address} opts.address - the contract uploader address + * @param {Uint8Array|Buffer} opts.wasmHash - the SHA-256 hash of the contract + * WASM you're uploading (see {@link hash} and + * {@link Operation.uploadContractWasm}) + * @param {xdr.ScVal[]} [opts.constructorArgs] - the optional parameters to pass + * to the constructor of this contract (see {@link nativeToScVal} for ways to + * easily create these parameters from native JS values) + * @param {Uint8Array|Buffer} [opts.salt] - an optional, 32-byte salt to + * distinguish deployment instances of the same wasm from the same user (if + * omitted, one will be generated for you) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + */ +function createCustomContract(opts) { + var _opts$constructorArgs; + var salt = Buffer.from(opts.salt || getSalty()); + if (!opts.wasmHash || opts.wasmHash.length !== 32) { + throw new TypeError("expected hash(contract WASM) in 'opts.wasmHash', got ".concat(opts.wasmHash)); + } + if (salt.length !== 32) { + throw new TypeError("expected 32-byte salt in 'opts.salt', got ".concat(opts.wasmHash)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeCreateContractV2(new _xdr["default"].CreateContractArgsV2({ + executable: _xdr["default"].ContractExecutable.contractExecutableWasm(Buffer.from(opts.wasmHash)), + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAddress(new _xdr["default"].ContractIdPreimageFromAddress({ + address: opts.address.toScAddress(), + salt: salt + })), + constructorArgs: (_opts$constructorArgs = opts.constructorArgs) !== null && _opts$constructorArgs !== void 0 ? _opts$constructorArgs : [] + })) + }); +} + +/** + * Returns an operation that wraps a Stellar asset into a token contract. + * + * @function + * @alias Operation.createStellarAssetContract + * + * @param {any} opts - the set of parameters + * @param {Asset|string} opts.asset - the Stellar asset to wrap, either as an + * {@link Asset} object or in canonical form (SEP-11, `code:issuer`) + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see https://stellar.org/protocol/sep-11#alphanum4-alphanum12 + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions + * @see + * https://soroban.stellar.org/docs/advanced-tutorials/stellar-asset-contract + * @see Operation.invokeHostFunction + */ +function createStellarAssetContract(opts) { + var asset = opts.asset; + if (typeof asset === 'string') { + var _asset$split = asset.split(':'), + _asset$split2 = _slicedToArray(_asset$split, 2), + code = _asset$split2[0], + issuer = _asset$split2[1]; + asset = new _asset.Asset(code, issuer); // handles 'xlm' by default + } + if (!(asset instanceof _asset.Asset)) { + throw new TypeError("expected Asset in 'opts.asset', got ".concat(asset)); + } + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeCreateContract(new _xdr["default"].CreateContractArgs({ + executable: _xdr["default"].ContractExecutable.contractExecutableStellarAsset(), + contractIdPreimage: _xdr["default"].ContractIdPreimage.contractIdPreimageFromAsset(asset.toXDRObject()) + })) + }); +} + +/** + * Returns an operation that uploads WASM for a contract. + * + * @function + * @alias Operation.uploadContractWasm + * + * @param {any} opts - the set of parameters + * @param {Uint8Array|Buffer} opts.wasm - a WASM blob to upload to the ledger + * @param {xdr.SorobanAuthorizationEntry[]} [opts.auth] - an optional list + * outlining the tree of authorizations required for the call + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} an Invoke Host Function operation + * (xdr.InvokeHostFunctionOp) + * + * @see + * https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#function + */ +function uploadContractWasm(opts) { + return this.invokeHostFunction({ + source: opts.source, + auth: opts.auth, + func: _xdr["default"].HostFunction.hostFunctionTypeUploadContractWasm(Buffer.from(opts.wasm) // coalesce so we can drop `Buffer` someday + ) + }); +} + +/** @returns {Buffer} a random 256-bit "salt" value. */ +function getSalty() { + return _keypair.Keypair.random().xdrPublicKey().value(); // ed25519 is 256 bits, too +} + +/***/ }), + +/***/ 9845: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.liquidityPoolDeposit = liquidityPoolDeposit; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a liquidity pool deposit operation. + * + * @function + * @alias Operation.liquidityPoolDeposit + * @see https://developers.stellar.org/docs/start/list-of-operations/#liquidity-pool-deposit + * + * @param {object} opts - Options object + * @param {string} opts.liquidityPoolId - The liquidity pool ID. + * @param {string} opts.maxAmountA - Maximum amount of first asset to deposit. + * @param {string} opts.maxAmountB - Maximum amount of second asset to deposit. + * @param {number|string|BigNumber|Object} opts.minPrice - Minimum depositA/depositB price. + * @param {number} opts.minPrice.n - If `opts.minPrice` is an object: the price numerator + * @param {number} opts.minPrice.d - If `opts.minPrice` is an object: the price denominator + * @param {number|string|BigNumber|Object} opts.maxPrice - Maximum depositA/depositB price. + * @param {number} opts.maxPrice.n - If `opts.maxPrice` is an object: the price numerator + * @param {number} opts.maxPrice.d - If `opts.maxPrice` is an object: the price denominator + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting operation (xdr.LiquidityPoolDepositOp). + */ +function liquidityPoolDeposit() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var liquidityPoolId = opts.liquidityPoolId, + maxAmountA = opts.maxAmountA, + maxAmountB = opts.maxAmountB, + minPrice = opts.minPrice, + maxPrice = opts.maxPrice; + var attributes = {}; + if (!liquidityPoolId) { + throw new TypeError('liquidityPoolId argument is required'); + } + attributes.liquidityPoolId = _xdr["default"].PoolId.fromXDR(liquidityPoolId, 'hex'); + if (!this.isValidAmount(maxAmountA, true)) { + throw new TypeError(this.constructAmountRequirementsError('maxAmountA')); + } + attributes.maxAmountA = this._toXDRAmount(maxAmountA); + if (!this.isValidAmount(maxAmountB, true)) { + throw new TypeError(this.constructAmountRequirementsError('maxAmountB')); + } + attributes.maxAmountB = this._toXDRAmount(maxAmountB); + if (minPrice === undefined) { + throw new TypeError('minPrice argument is required'); + } + attributes.minPrice = this._toXDRPrice(minPrice); + if (maxPrice === undefined) { + throw new TypeError('maxPrice argument is required'); + } + attributes.maxPrice = this._toXDRPrice(maxPrice); + var liquidityPoolDepositOp = new _xdr["default"].LiquidityPoolDepositOp(attributes); + var opAttributes = { + body: _xdr["default"].OperationBody.liquidityPoolDeposit(liquidityPoolDepositOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 4737: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.liquidityPoolWithdraw = liquidityPoolWithdraw; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a liquidity pool withdraw operation. + * + * @function + * @alias Operation.liquidityPoolWithdraw + * @see https://developers.stellar.org/docs/start/list-of-operations/#liquidity-pool-withdraw + * + * @param {object} opts - Options object + * @param {string} opts.liquidityPoolId - The liquidity pool ID. + * @param {string} opts.amount - Amount of pool shares to withdraw. + * @param {string} opts.minAmountA - Minimum amount of first asset to withdraw. + * @param {string} opts.minAmountB - Minimum amount of second asset to withdraw. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting operation (xdr.LiquidityPoolWithdrawOp). + */ +function liquidityPoolWithdraw() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var attributes = {}; + if (!opts.liquidityPoolId) { + throw new TypeError('liquidityPoolId argument is required'); + } + attributes.liquidityPoolId = _xdr["default"].PoolId.fromXDR(opts.liquidityPoolId, 'hex'); + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (!this.isValidAmount(opts.minAmountA, true)) { + throw new TypeError(this.constructAmountRequirementsError('minAmountA')); + } + attributes.minAmountA = this._toXDRAmount(opts.minAmountA); + if (!this.isValidAmount(opts.minAmountB, true)) { + throw new TypeError(this.constructAmountRequirementsError('minAmountB')); + } + attributes.minAmountB = this._toXDRAmount(opts.minAmountB); + var liquidityPoolWithdrawOp = new _xdr["default"].LiquidityPoolWithdrawOp(attributes); + var opAttributes = { + body: _xdr["default"].OperationBody.liquidityPoolWithdraw(liquidityPoolWithdrawOp) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 1922: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.manageBuyOffer = manageBuyOffer; +var _jsXdr = __webpack_require__(3740); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR ManageBuyOfferOp. A "manage buy offer" operation creates, updates, or + * deletes a buy offer. + * @function + * @alias Operation.manageBuyOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.buyAmount - The total amount you're buying. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `buying` in terms of `selling`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.ManageBuyOfferOp} Manage Buy Offer operation + */ +function manageBuyOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.buyAmount, true)) { + throw new TypeError(this.constructAmountRequirementsError('buyAmount')); + } + attributes.buyAmount = this._toXDRAmount(opts.buyAmount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + if (opts.offerId !== undefined) { + opts.offerId = opts.offerId.toString(); + } else { + opts.offerId = '0'; + } + attributes.offerId = _jsXdr.Hyper.fromString(opts.offerId); + var manageBuyOfferOp = new _xdr["default"].ManageBuyOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageBuyOffer(manageBuyOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 1411: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.manageData = manageData; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * This operation adds data entry to the ledger. + * @function + * @alias Operation.manageData + * @param {object} opts Options object + * @param {string} opts.name - The name of the data entry. + * @param {string|Buffer} opts.value - The value of the data entry. + * @param {string} [opts.source] - The optional source account. + * @returns {xdr.ManageDataOp} Manage Data operation + */ +function manageData(opts) { + var attributes = {}; + if (!(typeof opts.name === 'string' && opts.name.length <= 64)) { + throw new Error('name must be a string, up to 64 characters'); + } + attributes.dataName = opts.name; + if (typeof opts.value !== 'string' && !Buffer.isBuffer(opts.value) && opts.value !== null) { + throw new Error('value must be a string, Buffer or null'); + } + if (typeof opts.value === 'string') { + attributes.dataValue = Buffer.from(opts.value); + } else { + attributes.dataValue = opts.value; + } + if (attributes.dataValue !== null && attributes.dataValue.length > 64) { + throw new Error('value cannot be longer that 64 bytes'); + } + var manageDataOp = new _xdr["default"].ManageDataOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageData(manageDataOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 862: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.manageSellOffer = manageSellOffer; +var _jsXdr = __webpack_require__(3740); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Returns a XDR ManageSellOfferOp. A "manage sell offer" operation creates, updates, or + * deletes an offer. + * @function + * @alias Operation.manageSellOffer + * @param {object} opts Options object + * @param {Asset} opts.selling - What you're selling. + * @param {Asset} opts.buying - What you're buying. + * @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer. + * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`. + * @param {number} opts.price.n - If `opts.price` is an object: the price numerator + * @param {number} opts.price.d - If `opts.price` is an object: the price denominator + * @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found. + * @returns {xdr.ManageSellOfferOp} Manage Sell Offer operation + */ +function manageSellOffer(opts) { + var attributes = {}; + attributes.selling = opts.selling.toXDRObject(); + attributes.buying = opts.buying.toXDRObject(); + if (!this.isValidAmount(opts.amount, true)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + attributes.amount = this._toXDRAmount(opts.amount); + if (opts.price === undefined) { + throw new TypeError('price argument is required'); + } + attributes.price = this._toXDRPrice(opts.price); + if (opts.offerId !== undefined) { + opts.offerId = opts.offerId.toString(); + } else { + opts.offerId = '0'; + } + attributes.offerId = _jsXdr.Hyper.fromString(opts.offerId); + var manageSellOfferOp = new _xdr["default"].ManageSellOfferOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.manageSellOffer(manageSellOfferOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2075: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.pathPaymentStrictReceive = pathPaymentStrictReceive; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a PathPaymentStrictReceive operation. + * + * A `PathPaymentStrictReceive` operation sends the specified amount to the + * destination account. It credits the destination with `destAmount` of + * `destAsset`, while debiting at most `sendMax` of `sendAsset` from the source. + * The transfer optionally occurs through a path. XLM payments create the + * destination account if it does not exist. + * + * @function + * @alias Operation.pathPaymentStrictReceive + * @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-receive + * + * @param {object} opts - Options object + * @param {Asset} opts.sendAsset - asset to pay with + * @param {string} opts.sendMax - maximum amount of sendAsset to send + * @param {string} opts.destination - destination account to send to + * @param {Asset} opts.destAsset - asset the destination will receive + * @param {string} opts.destAmount - amount the destination receives + * @param {Asset[]} opts.path - array of Asset objects to use as the path + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.PathPaymentStrictReceiveOp} the resulting path payment op + */ +function pathPaymentStrictReceive(opts) { + switch (true) { + case !opts.sendAsset: + throw new Error('Must specify a send asset'); + case !this.isValidAmount(opts.sendMax): + throw new TypeError(this.constructAmountRequirementsError('sendMax')); + case !opts.destAsset: + throw new Error('Must provide a destAsset for a payment operation'); + case !this.isValidAmount(opts.destAmount): + throw new TypeError(this.constructAmountRequirementsError('destAmount')); + default: + break; + } + var attributes = {}; + attributes.sendAsset = opts.sendAsset.toXDRObject(); + attributes.sendMax = this._toXDRAmount(opts.sendMax); + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.destAsset = opts.destAsset.toXDRObject(); + attributes.destAmount = this._toXDRAmount(opts.destAmount); + var path = opts.path ? opts.path : []; + attributes.path = path.map(function (x) { + return x.toXDRObject(); + }); + var payment = new _xdr["default"].PathPaymentStrictReceiveOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.pathPaymentStrictReceive(payment); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 3874: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.pathPaymentStrictSend = pathPaymentStrictSend; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Creates a PathPaymentStrictSend operation. + * + * A `PathPaymentStrictSend` operation sends the specified amount to the + * destination account crediting at least `destMin` of `destAsset`, optionally + * through a path. XLM payments create the destination account if it does not + * exist. + * + * @function + * @alias Operation.pathPaymentStrictSend + * @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-send + * + * @param {object} opts - Options object + * @param {Asset} opts.sendAsset - asset to pay with + * @param {string} opts.sendAmount - amount of sendAsset to send (excluding fees) + * @param {string} opts.destination - destination account to send to + * @param {Asset} opts.destAsset - asset the destination will receive + * @param {string} opts.destMin - minimum amount of destAsset to be receive + * @param {Asset[]} opts.path - array of Asset objects to use as the path + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.Operation} the resulting path payment operation + * (xdr.PathPaymentStrictSendOp) + */ +function pathPaymentStrictSend(opts) { + switch (true) { + case !opts.sendAsset: + throw new Error('Must specify a send asset'); + case !this.isValidAmount(opts.sendAmount): + throw new TypeError(this.constructAmountRequirementsError('sendAmount')); + case !opts.destAsset: + throw new Error('Must provide a destAsset for a payment operation'); + case !this.isValidAmount(opts.destMin): + throw new TypeError(this.constructAmountRequirementsError('destMin')); + default: + break; + } + var attributes = {}; + attributes.sendAsset = opts.sendAsset.toXDRObject(); + attributes.sendAmount = this._toXDRAmount(opts.sendAmount); + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.destAsset = opts.destAsset.toXDRObject(); + attributes.destMin = this._toXDRAmount(opts.destMin); + var path = opts.path ? opts.path : []; + attributes.path = path.map(function (x) { + return x.toXDRObject(); + }); + var payment = new _xdr["default"].PathPaymentStrictSendOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.pathPaymentStrictSend(payment); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 3533: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.payment = payment; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a payment operation. + * + * @function + * @alias Operation.payment + * @see https://developers.stellar.org/docs/start/list-of-operations/#payment + * + * @param {object} opts - Options object + * @param {string} opts.destination - destination account ID + * @param {Asset} opts.asset - asset to send + * @param {string} opts.amount - amount to send + * + * @param {string} [opts.source] - The source account for the payment. + * Defaults to the transaction's source account. + * + * @returns {xdr.Operation} The resulting payment operation (xdr.PaymentOp) + */ +function payment(opts) { + if (!opts.asset) { + throw new Error('Must provide an asset for a payment operation'); + } + if (!this.isValidAmount(opts.amount)) { + throw new TypeError(this.constructAmountRequirementsError('amount')); + } + var attributes = {}; + try { + attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination); + } catch (e) { + throw new Error('destination is invalid'); + } + attributes.asset = opts.asset.toXDRObject(); + attributes.amount = this._toXDRAmount(opts.amount); + var paymentOp = new _xdr["default"].PaymentOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.payment(paymentOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 149: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.restoreFootprint = restoreFootprint; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Builds an operation to restore the archived ledger entries specified + * by the ledger keys. + * + * The ledger keys to restore are specified separately from the operation + * in read-write footprint of the transaction. + * + * It takes no parameters because the relevant footprint is derived from the + * transaction itself. See {@link TransactionBuilder}'s `opts.sorobanData` + * parameter (or {@link TransactionBuilder.setSorobanData} / + * {@link TransactionBuilder.setLedgerKeys}), which is a + * {@link xdr.SorobanTransactionData} instance that contains fee data & resource + * usage as part of {@link xdr.SorobanTransactionData}. + * + * @function + * @alias Operation.restoreFootprint + * + * @param {object} [opts] - an optional set of parameters + * @param {string} [opts.source] - an optional source account + * + * @returns {xdr.Operation} a Bump Footprint Expiration operation + * (xdr.RestoreFootprintOp) + */ +function restoreFootprint() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var op = new _xdr["default"].RestoreFootprintOp({ + ext: new _xdr["default"].ExtensionPoint(0) + }); + var opAttributes = { + body: _xdr["default"].OperationBody.restoreFootprint(op) + }; + this.setSourceAccount(opAttributes, opts !== null && opts !== void 0 ? opts : {}); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7790: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.revokeAccountSponsorship = revokeAccountSponsorship; +exports.revokeClaimableBalanceSponsorship = revokeClaimableBalanceSponsorship; +exports.revokeDataSponsorship = revokeDataSponsorship; +exports.revokeLiquidityPoolSponsorship = revokeLiquidityPoolSponsorship; +exports.revokeOfferSponsorship = revokeOfferSponsorship; +exports.revokeSignerSponsorship = revokeSignerSponsorship; +exports.revokeTrustlineSponsorship = revokeTrustlineSponsorship; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +var _keypair = __webpack_require__(6691); +var _asset = __webpack_require__(1764); +var _liquidity_pool_id = __webpack_require__(9353); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Create a "revoke sponsorship" operation for an account. + * + * @function + * @alias Operation.revokeAccountSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The sponsored account ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeAccountSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * }); + * + */ +function revokeAccountSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.account(new _xdr["default"].LedgerKeyAccount({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId() + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a trustline. + * + * @function + * @alias Operation.revokeTrustlineSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID which owns the trustline. + * @param {Asset | LiquidityPoolId} opts.asset - The trustline asset. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeTrustlineSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * asset: new StellarBase.LiquidityPoolId( + * 'USDUSD', + * 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7' + * ) + * }); + * + */ +function revokeTrustlineSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var asset; + if (opts.asset instanceof _asset.Asset) { + asset = opts.asset.toTrustLineXDRObject(); + } else if (opts.asset instanceof _liquidity_pool_id.LiquidityPoolId) { + asset = opts.asset.toXDRObject(); + } else { + throw new TypeError('asset must be an Asset or LiquidityPoolId'); + } + var ledgerKey = _xdr["default"].LedgerKey.trustline(new _xdr["default"].LedgerKeyTrustLine({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + asset: asset + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for an offer. + * + * @function + * @alias Operation.revokeOfferSponsorship + * @param {object} opts Options object + * @param {string} opts.seller - The account ID which created the offer. + * @param {string} opts.offerId - The offer ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeOfferSponsorship({ + * seller: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * offerId: '1234' + * }); + * + */ +function revokeOfferSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.seller)) { + throw new Error('seller is invalid'); + } + if (typeof opts.offerId !== 'string') { + throw new Error('offerId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.offer(new _xdr["default"].LedgerKeyOffer({ + sellerId: _keypair.Keypair.fromPublicKey(opts.seller).xdrAccountId(), + offerId: _xdr["default"].Int64.fromString(opts.offerId) + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a data entry. + * + * @function + * @alias Operation.revokeDataSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID which owns the data entry. + * @param {string} opts.name - The name of the data entry + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeDataSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * name: 'foo' + * }); + * + */ +function revokeDataSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + if (typeof opts.name !== 'string' || opts.name.length > 64) { + throw new Error('name must be a string, up to 64 characters'); + } + var ledgerKey = _xdr["default"].LedgerKey.data(new _xdr["default"].LedgerKeyData({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + dataName: opts.name + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a claimable balance. + * + * @function + * @alias Operation.revokeClaimableBalanceSponsorship + * @param {object} opts Options object + * @param {string} opts.balanceId - The sponsored claimable balance ID. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeClaimableBalanceSponsorship({ + * balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be', + * }); + * + */ +function revokeClaimableBalanceSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (typeof opts.balanceId !== 'string') { + throw new Error('balanceId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.claimableBalance(new _xdr["default"].LedgerKeyClaimableBalance({ + balanceId: _xdr["default"].ClaimableBalanceId.fromXDR(opts.balanceId, 'hex') + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Creates a "revoke sponsorship" operation for a liquidity pool. + * + * @function + * @alias Operation.revokeLiquidityPoolSponsorship + * @param {object} opts – Options object. + * @param {string} opts.liquidityPoolId - The sponsored liquidity pool ID in 'hex' string. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr Operation. + * + * @example + * const op = Operation.revokeLiquidityPoolSponsorship({ + * liquidityPoolId: 'dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7', + * }); + * + */ +function revokeLiquidityPoolSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (typeof opts.liquidityPoolId !== 'string') { + throw new Error('liquidityPoolId is invalid'); + } + var ledgerKey = _xdr["default"].LedgerKey.liquidityPool(new _xdr["default"].LedgerKeyLiquidityPool({ + liquidityPoolId: _xdr["default"].PoolId.fromXDR(opts.liquidityPoolId, 'hex') + })); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey); + var opAttributes = { + body: _xdr["default"].OperationBody.revokeSponsorship(op) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/** + * Create a "revoke sponsorship" operation for a signer. + * + * @function + * @alias Operation.revokeSignerSponsorship + * @param {object} opts Options object + * @param {string} opts.account - The account ID where the signer sponsorship is being removed from. + * @param {object} opts.signer - The signer whose sponsorship is being removed. + * @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer. + * @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string). + * @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction. + * @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account. + * @returns {xdr.Operation} xdr operation + * + * @example + * const op = Operation.revokeSignerSponsorship({ + * account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7 + * signer: { + * ed25519PublicKey: 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ' + * } + * }) + * + */ +function revokeSignerSponsorship() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) { + throw new Error('account is invalid'); + } + var key; + if (opts.signer.ed25519PublicKey) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) { + throw new Error('signer.ed25519PublicKey is invalid.'); + } + var rawKey = _strkey.StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey); + key = new _xdr["default"].SignerKey.signerKeyTypeEd25519(rawKey); + } else if (opts.signer.preAuthTx) { + var buffer; + if (typeof opts.signer.preAuthTx === 'string') { + buffer = Buffer.from(opts.signer.preAuthTx, 'hex'); + } else { + buffer = opts.signer.preAuthTx; + } + if (!(Buffer.isBuffer(buffer) && buffer.length === 32)) { + throw new Error('signer.preAuthTx must be 32 bytes Buffer.'); + } + key = new _xdr["default"].SignerKey.signerKeyTypePreAuthTx(buffer); + } else if (opts.signer.sha256Hash) { + var _buffer; + if (typeof opts.signer.sha256Hash === 'string') { + _buffer = Buffer.from(opts.signer.sha256Hash, 'hex'); + } else { + _buffer = opts.signer.sha256Hash; + } + if (!(Buffer.isBuffer(_buffer) && _buffer.length === 32)) { + throw new Error('signer.sha256Hash must be 32 bytes Buffer.'); + } + key = new _xdr["default"].SignerKey.signerKeyTypeHashX(_buffer); + } else { + throw new Error('signer is invalid'); + } + var signer = new _xdr["default"].RevokeSponsorshipOpSigner({ + accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(), + signerKey: key + }); + var op = _xdr["default"].RevokeSponsorshipOp.revokeSponsorshipSigner(signer); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.revokeSponsorship(op); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 2018: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.setOptions = setOptions; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/* eslint-disable no-param-reassign */ + +function weightCheckFunction(value, name) { + if (value >= 0 && value <= 255) { + return true; + } + throw new Error("".concat(name, " value must be between 0 and 255")); +} + +/** + * Returns an XDR SetOptionsOp. A "set options" operations set or clear account flags, + * set the account's inflation destination, and/or add new signers to the account. + * The flags used in `opts.clearFlags` and `opts.setFlags` can be the following: + * - `{@link AuthRequiredFlag}` + * - `{@link AuthRevocableFlag}` + * - `{@link AuthImmutableFlag}` + * - `{@link AuthClawbackEnabledFlag}` + * + * It's possible to set/clear multiple flags at once using logical or. + * + * @function + * @alias Operation.setOptions + * + * @param {object} opts Options object + * @param {string} [opts.inflationDest] - Set this account ID as the account's inflation destination. + * @param {(number|string)} [opts.clearFlags] - Bitmap integer for which account flags to clear. + * @param {(number|string)} [opts.setFlags] - Bitmap integer for which account flags to set. + * @param {number|string} [opts.masterWeight] - The master key weight. + * @param {number|string} [opts.lowThreshold] - The sum weight for the low threshold. + * @param {number|string} [opts.medThreshold] - The sum weight for the medium threshold. + * @param {number|string} [opts.highThreshold] - The sum weight for the high threshold. + * @param {object} [opts.signer] - Add or remove a signer from the account. The signer is + * deleted if the weight is 0. Only one of `ed25519PublicKey`, `sha256Hash`, `preAuthTx` should be defined. + * @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer. + * @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string) of preimage that will unlock funds. Preimage should be used as signature of future transaction. + * @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction that will unlock funds. + * @param {string} [opts.signer.ed25519SignedPayload] - Signed payload signer (ed25519 public key + raw payload) for atomic transaction signature disclosure. + * @param {number|string} [opts.signer.weight] - The weight of the new signer (0 to delete or 1-255) + * @param {string} [opts.homeDomain] - sets the home domain used for reverse federation lookup. + * @param {string} [opts.source] - The source account (defaults to transaction source). + * + * @returns {xdr.SetOptionsOp} XDR operation + * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags) + */ +function setOptions(opts) { + var attributes = {}; + if (opts.inflationDest) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.inflationDest)) { + throw new Error('inflationDest is invalid'); + } + attributes.inflationDest = _keypair.Keypair.fromPublicKey(opts.inflationDest).xdrAccountId(); + } + attributes.clearFlags = this._checkUnsignedIntValue('clearFlags', opts.clearFlags); + attributes.setFlags = this._checkUnsignedIntValue('setFlags', opts.setFlags); + attributes.masterWeight = this._checkUnsignedIntValue('masterWeight', opts.masterWeight, weightCheckFunction); + attributes.lowThreshold = this._checkUnsignedIntValue('lowThreshold', opts.lowThreshold, weightCheckFunction); + attributes.medThreshold = this._checkUnsignedIntValue('medThreshold', opts.medThreshold, weightCheckFunction); + attributes.highThreshold = this._checkUnsignedIntValue('highThreshold', opts.highThreshold, weightCheckFunction); + if (opts.homeDomain !== undefined && typeof opts.homeDomain !== 'string') { + throw new TypeError('homeDomain argument must be of type String'); + } + attributes.homeDomain = opts.homeDomain; + if (opts.signer) { + var weight = this._checkUnsignedIntValue('signer.weight', opts.signer.weight, weightCheckFunction); + var key; + var setValues = 0; + if (opts.signer.ed25519PublicKey) { + if (!_strkey.StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) { + throw new Error('signer.ed25519PublicKey is invalid.'); + } + var rawKey = _strkey.StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey); + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypeEd25519(rawKey); + setValues += 1; + } + if (opts.signer.preAuthTx) { + if (typeof opts.signer.preAuthTx === 'string') { + opts.signer.preAuthTx = Buffer.from(opts.signer.preAuthTx, 'hex'); + } + if (!(Buffer.isBuffer(opts.signer.preAuthTx) && opts.signer.preAuthTx.length === 32)) { + throw new Error('signer.preAuthTx must be 32 bytes Buffer.'); + } + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypePreAuthTx(opts.signer.preAuthTx); + setValues += 1; + } + if (opts.signer.sha256Hash) { + if (typeof opts.signer.sha256Hash === 'string') { + opts.signer.sha256Hash = Buffer.from(opts.signer.sha256Hash, 'hex'); + } + if (!(Buffer.isBuffer(opts.signer.sha256Hash) && opts.signer.sha256Hash.length === 32)) { + throw new Error('signer.sha256Hash must be 32 bytes Buffer.'); + } + + // eslint-disable-next-line new-cap + key = new _xdr["default"].SignerKey.signerKeyTypeHashX(opts.signer.sha256Hash); + setValues += 1; + } + if (opts.signer.ed25519SignedPayload) { + if (!_strkey.StrKey.isValidSignedPayload(opts.signer.ed25519SignedPayload)) { + throw new Error('signer.ed25519SignedPayload is invalid.'); + } + var _rawKey = _strkey.StrKey.decodeSignedPayload(opts.signer.ed25519SignedPayload); + var signedPayloadXdr = _xdr["default"].SignerKeyEd25519SignedPayload.fromXDR(_rawKey); + + // eslint-disable-next-line new-cap + key = _xdr["default"].SignerKey.signerKeyTypeEd25519SignedPayload(signedPayloadXdr); + setValues += 1; + } + if (setValues !== 1) { + throw new Error('Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx.'); + } + attributes.signer = new _xdr["default"].Signer({ + key: key, + weight: weight + }); + } + var setOptionsOp = new _xdr["default"].SetOptionsOp(attributes); + var opAttributes = {}; + opAttributes.body = _xdr["default"].OperationBody.setOptions(setOptionsOp); + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 1804: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.setTrustLineFlags = setTrustLineFlags; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _keypair = __webpack_require__(6691); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/** + * Creates a trustline flag configuring operation. + * + * For the flags, set them to true to enable them and false to disable them. Any + * unmodified operations will be marked `undefined` in the result. + * + * Note that you can only **clear** the clawbackEnabled flag set; it must be set + * account-wide via operations.SetOptions (setting + * xdr.AccountFlags.clawbackEnabled). + * + * @function + * @alias Operation.setTrustLineFlags + * + * @param {object} opts - Options object + * @param {string} opts.trustor - the account whose trustline this is + * @param {Asset} opts.asset - the asset on the trustline + * @param {object} opts.flags - the set of flags to modify + * + * @param {bool} [opts.flags.authorized] - authorize account to perform + * transactions with its credit + * @param {bool} [opts.flags.authorizedToMaintainLiabilities] - authorize + * account to maintain and reduce liabilities for its credit + * @param {bool} [opts.flags.clawbackEnabled] - stop claimable balances on + * this trustlines from having clawbacks enabled (this flag can only be set + * to false!) + * @param {string} [opts.source] - The source account for the operation. + * Defaults to the transaction's source account. + * + * @note You must include at least one flag. + * + * @return {xdr.SetTrustLineFlagsOp} + * + * @link xdr.AccountFlags + * @link xdr.TrustLineFlags + * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#set-trustline-flags-operation + * @see https://developers.stellar.org/docs/start/list-of-operations/#set-options + */ +function setTrustLineFlags() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var attributes = {}; + if (_typeof(opts.flags) !== 'object' || Object.keys(opts.flags).length === 0) { + throw new Error('opts.flags must be a map of boolean flags to modify'); + } + var mapping = { + authorized: _xdr["default"].TrustLineFlags.authorizedFlag(), + authorizedToMaintainLiabilities: _xdr["default"].TrustLineFlags.authorizedToMaintainLiabilitiesFlag(), + clawbackEnabled: _xdr["default"].TrustLineFlags.trustlineClawbackEnabledFlag() + }; + + /* eslint no-bitwise: "off" */ + var clearFlag = 0; + var setFlag = 0; + Object.keys(opts.flags).forEach(function (flagName) { + if (!Object.prototype.hasOwnProperty.call(mapping, flagName)) { + throw new Error("unsupported flag name specified: ".concat(flagName)); + } + var flagValue = opts.flags[flagName]; + var bit = mapping[flagName].value; + if (flagValue === true) { + setFlag |= bit; + } else if (flagValue === false) { + clearFlag |= bit; + } + }); + attributes.trustor = _keypair.Keypair.fromPublicKey(opts.trustor).xdrAccountId(); + attributes.asset = opts.asset.toXDRObject(); + attributes.clearFlags = clearFlag; + attributes.setFlags = setFlag; + var opAttributes = { + body: _xdr["default"].OperationBody.setTrustLineFlags(new _xdr["default"].SetTrustLineFlagsOp(attributes)) + }; + this.setSourceAccount(opAttributes, opts); + return new _xdr["default"].Operation(opAttributes); +} + +/***/ }), + +/***/ 7177: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.nativeToScVal = nativeToScVal; +exports.scValToNative = scValToNative; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _address = __webpack_require__(1180); +var _contract = __webpack_require__(7452); +var _index = __webpack_require__(8549); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/** + * Attempts to convert native types into smart contract values + * ({@link xdr.ScVal}). + * + * Provides conversions from smart contract XDR values ({@link xdr.ScVal}) to + * native JavaScript types. + * + * The conversions are as follows: + * + * - xdr.ScVal -> passthrough + * - null/undefined -> scvVoid + * - string -> scvString (a copy is made) + * - UintArray8 -> scvBytes (a copy is made) + * - boolean -> scvBool + * + * - number/bigint -> the smallest possible XDR integer type that will fit the + * input value (if you want a specific type, use {@link ScInt}) + * + * - {@link Address} or {@link Contract} -> scvAddress (for contracts and + * public keys) + * + * - Array -> scvVec after attempting to convert each item of type `T` to an + * xdr.ScVal (recursively). note that all values must be the same type! + * + * - object -> scvMap after attempting to convert each key and value to an + * xdr.ScVal (recursively). note that there is no restriction on types + * matching anywhere (unlike arrays) + * + * When passing an integer-like native value, you can also optionally specify a + * type which will force a particular interpretation of that value. + * + * Note that not all type specifications are compatible with all `ScVal`s, e.g. + * `toScVal("a string", {type: "i256"})` will throw. + * + * @param {any} val - a native (or convertible) input value to wrap + * @param {object} [opts] - an optional set of hints around the type of + * conversion you'd like to see + * @param {string} [opts.type] - there is different behavior for different input + * types for `val`: + * + * - when `val` is an integer-like type (i.e. number|bigint), this will be + * forwarded to {@link ScInt} or forced to be u32/i32. + * + * - when `val` is an array type, this is forwarded to the recursion + * + * - when `val` is an object type (key-value entries), this should be an + * object in which each key has a pair of types (to represent forced types + * for the key and the value), where `null` (or a missing entry) indicates + * the default interpretation(s) (refer to the examples, below) + * + * - when `val` is a string type, this can be 'string' or 'symbol' to force + * a particular interpretation of `val`. + * + * - when `val` is a bytes-like type, this can be 'string', 'symbol', or + * 'bytes' to force a particular interpretation + * + * As a simple example, `nativeToScVal("hello", {type: 'symbol'})` will + * return an `scvSymbol`, whereas without the type it would have been an + * `scvString`. + * + * @returns {xdr.ScVal} a wrapped, smart, XDR version of the input value + * @throws {TypeError} if... + * - there are arrays with more than one type in them + * - there are values that do not have a sensible conversion (e.g. random XDR + * types, custom classes) + * - the type of the input object (or some inner value of said object) cannot + * be determined (via `typeof`) + * - the type you specified (via `opts.type`) is incompatible with the value + * you passed in (`val`), e.g. `nativeToScVal("a string", { type: 'i128' })`, + * though this does not apply for types that ignore `opts` (e.g. addresses). + * @see scValToNative + * + * @example + * nativeToScVal(1000); // gives ScValType === scvU64 + * nativeToScVal(1000n); // gives ScValType === scvU64 + * nativeToScVal(1n << 100n); // gives ScValType === scvU128 + * nativeToScVal(1000, { type: 'u32' }); // gives ScValType === scvU32 + * nativeToScVal(1000, { type: 'i125' }); // gives ScValType === scvI256 + * nativeToScVal("a string"); // gives ScValType === scvString + * nativeToScVal("a string", { type: 'symbol' }); // gives scvSymbol + * nativeToScVal(new Uint8Array(5)); // scvBytes + * nativeToScVal(new Uint8Array(5), { type: 'symbol' }); // scvSymbol + * nativeToScVal(null); // scvVoid + * nativeToScVal(true); // scvBool + * nativeToScVal([1, 2, 3]); // gives scvVec with each element as scvU64 + * nativeToScVal([1, 2, 3], { type: 'i128' }); // scvVec + * nativeToScVal({ 'hello': 1, 'world': [ true, false ] }, { + * type: { + * 'hello': [ 'symbol', 'i128' ], + * } + * }) + * // gives scvMap with entries: [ + * // [ scvSymbol, scvI128 ], + * // [ scvString, scvArray ] + * // ] + * + * @example + * import { + * nativeToScVal, + * scValToNative, + * ScInt, + * xdr + * } from '@stellar/stellar-base'; + * + * let gigaMap = { + * bool: true, + * void: null, + * u32: xdr.ScVal.scvU32(1), + * i32: xdr.ScVal.scvI32(1), + * u64: 1n, + * i64: -1n, + * u128: new ScInt(1).toU128(), + * i128: new ScInt(1).toI128(), + * u256: new ScInt(1).toU256(), + * i256: new ScInt(1).toI256(), + * map: { + * arbitrary: 1n, + * nested: 'values', + * etc: false + * }, + * vec: ['same', 'type', 'list'], + * }; + * + * // then, simply: + * let scv = nativeToScVal(gigaMap); // scv.switch() == xdr.ScValType.scvMap() + * + * // then... + * someContract.call("method", scv); + * + * // Similarly, the inverse should work: + * scValToNative(scv) == gigaMap; // true + */ +function nativeToScVal(val) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + switch (_typeof(val)) { + case 'object': + { + var _val$constructor$name, _val$constructor; + if (val === null) { + return _xdr["default"].ScVal.scvVoid(); + } + if (val instanceof _xdr["default"].ScVal) { + return val; // should we copy? + } + if (val instanceof _address.Address) { + return val.toScVal(); + } + if (val instanceof _contract.Contract) { + return val.address().toScVal(); + } + if (val instanceof Uint8Array || Buffer.isBuffer(val)) { + var _opts$type; + var copy = Uint8Array.from(val); + switch ((_opts$type = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type !== void 0 ? _opts$type : 'bytes') { + case 'bytes': + return _xdr["default"].ScVal.scvBytes(copy); + case 'symbol': + return _xdr["default"].ScVal.scvSymbol(copy); + case 'string': + return _xdr["default"].ScVal.scvString(copy); + default: + throw new TypeError("invalid type (".concat(opts.type, ") specified for bytes-like value")); + } + } + if (Array.isArray(val)) { + if (val.length > 0 && val.some(function (v) { + return _typeof(v) !== _typeof(val[0]); + })) { + throw new TypeError("array values (".concat(val, ") must have the same type (types: ").concat(val.map(function (v) { + return _typeof(v); + }).join(','), ")")); + } + return _xdr["default"].ScVal.scvVec(val.map(function (v) { + return nativeToScVal(v, opts); + })); + } + if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : '') !== 'Object') { + var _val$constructor2; + throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")")); + } + return _xdr["default"].ScVal.scvMap(Object.entries(val) + // The Soroban runtime expects maps to have their keys in sorted + // order, so let's do that here as part of the conversion to prevent + // confusing error messages on execution. + .sort(function (_ref, _ref2) { + var _ref3 = _slicedToArray(_ref, 1), + key1 = _ref3[0]; + var _ref4 = _slicedToArray(_ref2, 1), + key2 = _ref4[0]; + return key1.localeCompare(key2); + }).map(function (_ref5) { + var _k, _opts$type2; + var _ref6 = _slicedToArray(_ref5, 2), + k = _ref6[0], + v = _ref6[1]; + // the type can be specified with an entry for the key and the value, + // e.g. val = { 'hello': 1 } and opts.type = { hello: [ 'symbol', + // 'u128' ]} or you can use `null` for the default interpretation + var _ref7 = (_k = ((_opts$type2 = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type2 !== void 0 ? _opts$type2 : {})[k]) !== null && _k !== void 0 ? _k : [null, null], + _ref8 = _slicedToArray(_ref7, 2), + keyType = _ref8[0], + valType = _ref8[1]; + var keyOpts = keyType ? { + type: keyType + } : {}; + var valOpts = valType ? { + type: valType + } : {}; + return new _xdr["default"].ScMapEntry({ + key: nativeToScVal(k, keyOpts), + val: nativeToScVal(v, valOpts) + }); + })); + } + case 'number': + case 'bigint': + switch (opts === null || opts === void 0 ? void 0 : opts.type) { + case 'u32': + return _xdr["default"].ScVal.scvU32(val); + case 'i32': + return _xdr["default"].ScVal.scvI32(val); + default: + break; + } + return new _index.ScInt(val, { + type: opts === null || opts === void 0 ? void 0 : opts.type + }).toScVal(); + case 'string': + { + var _opts$type3; + var optType = (_opts$type3 = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type3 !== void 0 ? _opts$type3 : 'string'; + switch (optType) { + case 'string': + return _xdr["default"].ScVal.scvString(val); + case 'symbol': + return _xdr["default"].ScVal.scvSymbol(val); + case 'address': + return new _address.Address(val).toScVal(); + case 'u32': + return _xdr["default"].ScVal.scvU32(parseInt(val, 10)); + case 'i32': + return _xdr["default"].ScVal.scvI32(parseInt(val, 10)); + default: + if (_index.XdrLargeInt.isType(optType)) { + return new _index.XdrLargeInt(optType, val).toScVal(); + } + throw new TypeError("invalid type (".concat(opts.type, ") specified for string value")); + } + } + case 'boolean': + return _xdr["default"].ScVal.scvBool(val); + case 'undefined': + return _xdr["default"].ScVal.scvVoid(); + case 'function': + // FIXME: Is this too helpful? + return nativeToScVal(val()); + default: + throw new TypeError("failed to convert typeof ".concat(_typeof(val), " (").concat(val, ")")); + } +} + +/** + * Given a smart contract value, attempt to convert it to a native type. + * Possible conversions include: + * + * - void -> `null` + * - u32, i32 -> `number` + * - u64, i64, u128, i128, u256, i256 -> `bigint` + * - vec -> `Array` of any of the above (via recursion) + * - map -> key-value object of any of the above (via recursion) + * - bool -> `boolean` + * - bytes -> `Uint8Array` + * - symbol -> `string` + * - string -> `string` IF the underlying buffer can be decoded as ascii/utf8, + * `Uint8Array` of the raw contents in any error case + * + * If no viable conversion can be determined, this just "unwraps" the smart + * value to return its underlying XDR value. + * + * @param {xdr.ScVal} scv - the input smart contract value + * + * @returns {any} + * @see nativeToScVal + */ +function scValToNative(scv) { + var _scv$vec, _scv$map; + // we use the verbose xdr.ScValType..value form here because it's faster + // than string comparisons and the underlying constants never need to be + // updated + switch (scv["switch"]().value) { + case _xdr["default"].ScValType.scvVoid().value: + return null; + + // these can be converted to bigints directly + case _xdr["default"].ScValType.scvU64().value: + case _xdr["default"].ScValType.scvI64().value: + return scv.value().toBigInt(); + + // these can be parsed by internal abstractions note that this can also + // handle the above two cases, but it's not as efficient (another + // type-check, parsing, etc.) + case _xdr["default"].ScValType.scvU128().value: + case _xdr["default"].ScValType.scvI128().value: + case _xdr["default"].ScValType.scvU256().value: + case _xdr["default"].ScValType.scvI256().value: + return (0, _index.scValToBigInt)(scv); + case _xdr["default"].ScValType.scvVec().value: + return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(scValToNative); + case _xdr["default"].ScValType.scvAddress().value: + return _address.Address.fromScVal(scv).toString(); + case _xdr["default"].ScValType.scvMap().value: + return Object.fromEntries(((_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []).map(function (entry) { + return [scValToNative(entry.key()), scValToNative(entry.val())]; + })); + + // these return the primitive type directly + case _xdr["default"].ScValType.scvBool().value: + case _xdr["default"].ScValType.scvU32().value: + case _xdr["default"].ScValType.scvI32().value: + case _xdr["default"].ScValType.scvBytes().value: + return scv.value(); + + // Symbols are limited to [a-zA-Z0-9_]+, so we can safely make ascii strings + // + // Strings, however, are "presented" as strings and we treat them as such + // (in other words, string = bytes with a hint that it's text). If the user + // encoded non-printable bytes in their string value, that's on them. + // + // Note that we assume a utf8 encoding (ascii-compatible). For other + // encodings, you should probably use bytes anyway. If it cannot be decoded, + // the raw bytes are returned. + case _xdr["default"].ScValType.scvSymbol().value: + case _xdr["default"].ScValType.scvString().value: + { + var v = scv.value(); // string|Buffer + if (Buffer.isBuffer(v) || ArrayBuffer.isView(v)) { + try { + return new TextDecoder().decode(v); + } catch (e) { + return new Uint8Array(v.buffer); // copy of bytes + } + } + return v; // string already + } + + // these can be converted to bigint + case _xdr["default"].ScValType.scvTimepoint().value: + case _xdr["default"].ScValType.scvDuration().value: + return new _xdr["default"].Uint64(scv.value()).toBigInt(); + case _xdr["default"].ScValType.scvError().value: + switch (scv.error()["switch"]().value) { + // Distinguish errors from the user contract. + case _xdr["default"].ScErrorType.sceContract().value: + return { + type: 'contract', + code: scv.error().contractCode() + }; + default: + { + var err = scv.error(); + return { + type: 'system', + code: err.code().value, + value: err.code().name + }; + } + } + + // in the fallthrough case, just return the underlying value directly + default: + return scv.value(); + } +} + +/***/ }), + +/***/ 225: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.SignerKey = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * A container class with helpers to convert between signer keys + * (`xdr.SignerKey`) and {@link StrKey}s. + * + * It's primarly used for manipulating the `extraSigners` precondition on a + * {@link Transaction}. + * + * @see {@link TransactionBuilder.setExtraSigners} + */ +var SignerKey = exports.SignerKey = /*#__PURE__*/function () { + function SignerKey() { + _classCallCheck(this, SignerKey); + } + return _createClass(SignerKey, null, [{ + key: "decodeAddress", + value: + /** + * Decodes a StrKey address into an xdr.SignerKey instance. + * + * Only ED25519 public keys (G...), pre-auth transactions (T...), hashes + * (H...), and signed payloads (P...) can be signer keys. + * + * @param {string} address a StrKey-encoded signer address + * @returns {xdr.SignerKey} + */ + function decodeAddress(address) { + var signerKeyMap = { + ed25519PublicKey: _xdr["default"].SignerKey.signerKeyTypeEd25519, + preAuthTx: _xdr["default"].SignerKey.signerKeyTypePreAuthTx, + sha256Hash: _xdr["default"].SignerKey.signerKeyTypeHashX, + signedPayload: _xdr["default"].SignerKey.signerKeyTypeEd25519SignedPayload + }; + var vb = _strkey.StrKey.getVersionByteForPrefix(address); + var encoder = signerKeyMap[vb]; + if (!encoder) { + throw new Error("invalid signer key type (".concat(vb, ")")); + } + var raw = (0, _strkey.decodeCheck)(vb, address); + switch (vb) { + case 'signedPayload': + return encoder(new _xdr["default"].SignerKeyEd25519SignedPayload({ + ed25519: raw.slice(0, 32), + payload: raw.slice(32 + 4) + })); + case 'ed25519PublicKey': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + default: + return encoder(raw); + } + } + + /** + * Encodes a signer key into its StrKey equivalent. + * + * @param {xdr.SignerKey} signerKey the signer + * @returns {string} the StrKey representation of the signer + */ + }, { + key: "encodeSignerKey", + value: function encodeSignerKey(signerKey) { + var strkeyType; + var raw; + switch (signerKey["switch"]()) { + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519(): + strkeyType = 'ed25519PublicKey'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypePreAuthTx(): + strkeyType = 'preAuthTx'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypeHashX(): + strkeyType = 'sha256Hash'; + raw = signerKey.value(); + break; + case _xdr["default"].SignerKeyType.signerKeyTypeEd25519SignedPayload(): + strkeyType = 'signedPayload'; + raw = signerKey.ed25519SignedPayload().toXDR('raw'); + break; + default: + throw new Error("invalid SignerKey (type: ".concat(signerKey["switch"](), ")")); + } + return (0, _strkey.encodeCheck)(strkeyType, raw); + } + }]); +}(); + +/***/ }), + +/***/ 15: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.FastSigning = void 0; +exports.generate = generate; +exports.sign = sign; +exports.verify = verify; +// This module provides the signing functionality used by the stellar network +// The code below may look a little strange... this is because we try to provide +// the most efficient signing method possible. First, we try to load the +// native `sodium-native` package for node.js environments, and if that fails we +// fallback to `tweetnacl` + +var actualMethods = {}; + +/** + * Use this flag to check if fast signing (provided by `sodium-native` package) is available. + * If your app is signing a large number of transaction or verifying a large number + * of signatures make sure `sodium-native` package is installed. + */ +var FastSigning = exports.FastSigning = checkFastSigning(); +function sign(data, secretKey) { + return actualMethods.sign(data, secretKey); +} +function verify(data, signature, publicKey) { + return actualMethods.verify(data, signature, publicKey); +} +function generate(secretKey) { + return actualMethods.generate(secretKey); +} +function checkFastSigning() { + return typeof window === 'undefined' ? checkFastSigningNode() : checkFastSigningBrowser(); +} +function checkFastSigningNode() { + // NOTE: we use commonjs style require here because es6 imports + // can only occur at the top level. thanks, obama. + var sodium; + try { + // eslint-disable-next-line + sodium = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module 'sodium-native'"); e.code = 'MODULE_NOT_FOUND'; throw e; }())); + } catch (err) { + return checkFastSigningBrowser(); + } + if (!Object.keys(sodium).length) { + return checkFastSigningBrowser(); + } + actualMethods.generate = function (secretKey) { + var pk = Buffer.alloc(sodium.crypto_sign_PUBLICKEYBYTES); + var sk = Buffer.alloc(sodium.crypto_sign_SECRETKEYBYTES); + sodium.crypto_sign_seed_keypair(pk, sk, secretKey); + return pk; + }; + actualMethods.sign = function (data, secretKey) { + data = Buffer.from(data); + var signature = Buffer.alloc(sodium.crypto_sign_BYTES); + sodium.crypto_sign_detached(signature, data, secretKey); + return signature; + }; + actualMethods.verify = function (data, signature, publicKey) { + data = Buffer.from(data); + try { + return sodium.crypto_sign_verify_detached(signature, data, publicKey); + } catch (e) { + return false; + } + }; + return true; +} +function checkFastSigningBrowser() { + // fallback to `tweetnacl` if we're in the browser or + // if there was a failure installing `sodium-native` + // eslint-disable-next-line + var nacl = __webpack_require__(4940); + actualMethods.generate = function (secretKey) { + var secretKeyUint8 = new Uint8Array(secretKey); + var naclKeys = nacl.sign.keyPair.fromSeed(secretKeyUint8); + return Buffer.from(naclKeys.publicKey); + }; + actualMethods.sign = function (data, secretKey) { + data = Buffer.from(data); + data = new Uint8Array(data.toJSON().data); + secretKey = new Uint8Array(secretKey.toJSON().data); + var signature = nacl.sign.detached(data, secretKey); + return Buffer.from(signature); + }; + actualMethods.verify = function (data, signature, publicKey) { + data = Buffer.from(data); + data = new Uint8Array(data.toJSON().data); + signature = new Uint8Array(signature.toJSON().data); + publicKey = new Uint8Array(publicKey.toJSON().data); + return nacl.sign.detached.verify(data, signature, publicKey); + }; + return false; +} + +/***/ }), + +/***/ 4062: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Soroban = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/* Helper class to assist with formatting and parsing token amounts. */ +var Soroban = exports.Soroban = /*#__PURE__*/function () { + function Soroban() { + _classCallCheck(this, Soroban); + } + return _createClass(Soroban, null, [{ + key: "formatTokenAmount", + value: + /** + * Given a whole number smart contract amount of a token and an amount of + * decimal places (if the token has any), it returns a "display" value. + * + * All arithmetic inside the contract is performed on integers to avoid + * potential precision and consistency issues of floating-point. + * + * @param {string} amount the token amount you want to display + * @param {number} decimals specify how many decimal places a token has + * + * @returns {string} the display value + * @throws {TypeError} if the given amount has a decimal point already + * @example + * formatTokenAmount("123000", 4) === "12.3"; + */ + function formatTokenAmount(amount, decimals) { + if (amount.includes('.')) { + throw new TypeError('No decimals are allowed'); + } + var formatted = amount; + if (decimals > 0) { + if (decimals > formatted.length) { + formatted = ['0', formatted.toString().padStart(decimals, '0')].join('.'); + } else { + formatted = [formatted.slice(0, -decimals), formatted.slice(-decimals)].join('.'); + } + } + + // remove trailing zero if any + return formatted.replace(/(\.\d*?)0+$/, '$1'); + } + + /** + * Parse a token amount to use it on smart contract + * + * This function takes the display value and its decimals (if the token has + * any) and returns a string that'll be used within the smart contract. + * + * @param {string} value the token amount you want to use it on smart + * contract which you've been displaying in a UI + * @param {number} decimals the number of decimal places expected in the + * display value (different than the "actual" number, because suffix zeroes + * might not be present) + * + * @returns {string} the whole number token amount represented by the display + * value with the decimal places shifted over + * + * @example + * const displayValueAmount = "123.4560" + * const parsedAmtForSmartContract = parseTokenAmount(displayValueAmount, 5); + * parsedAmtForSmartContract === "12345600" + */ + }, { + key: "parseTokenAmount", + value: function parseTokenAmount(value, decimals) { + var _fraction$padEnd; + var _value$split$slice = value.split('.').slice(), + _value$split$slice2 = _toArray(_value$split$slice), + whole = _value$split$slice2[0], + fraction = _value$split$slice2[1], + rest = _value$split$slice2.slice(2); + if (rest.length) { + throw new Error("Invalid decimal value: ".concat(value)); + } + var shifted = BigInt(whole + ((_fraction$padEnd = fraction === null || fraction === void 0 ? void 0 : fraction.padEnd(decimals, '0')) !== null && _fraction$padEnd !== void 0 ? _fraction$padEnd : '0'.repeat(decimals))); + return shifted.toString(); + } + }]); +}(); + +/***/ }), + +/***/ 4842: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.SorobanDataBuilder = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Supports building {@link xdr.SorobanTransactionData} structures with various + * items set to specific values. + * + * This is recommended for when you are building + * {@link Operation.extendFootprintTtl} / {@link Operation.restoreFootprint} + * operations and need to {@link TransactionBuilder.setSorobanData} to avoid + * (re)building the entire data structure from scratch. + * + * @constructor + * + * @param {string | xdr.SorobanTransactionData} [sorobanData] either a + * base64-encoded string that represents an + * {@link xdr.SorobanTransactionData} instance or an XDR instance itself + * (it will be copied); if omitted or "falsy" (e.g. an empty string), it + * starts with an empty instance + * + * @example + * // You want to use an existing data blob but override specific parts. + * const newData = new SorobanDataBuilder(existing) + * .setReadOnly(someLedgerKeys) + * .setRefundableFee("1000") + * .build(); + * + * // You want an instance from scratch + * const newData = new SorobanDataBuilder() + * .setFootprint([someLedgerKey], []) + * .setRefundableFee("1000") + * .build(); + */ +var SorobanDataBuilder = exports.SorobanDataBuilder = /*#__PURE__*/function () { + function SorobanDataBuilder(sorobanData) { + _classCallCheck(this, SorobanDataBuilder); + _defineProperty(this, "_data", void 0); + var data; + if (!sorobanData) { + data = new _xdr["default"].SorobanTransactionData({ + resources: new _xdr["default"].SorobanResources({ + footprint: new _xdr["default"].LedgerFootprint({ + readOnly: [], + readWrite: [] + }), + instructions: 0, + readBytes: 0, + writeBytes: 0 + }), + ext: new _xdr["default"].ExtensionPoint(0), + resourceFee: new _xdr["default"].Int64(0) + }); + } else if (typeof sorobanData === 'string' || ArrayBuffer.isView(sorobanData)) { + data = SorobanDataBuilder.fromXDR(sorobanData); + } else { + data = SorobanDataBuilder.fromXDR(sorobanData.toXDR()); // copy + } + this._data = data; + } + + /** + * Decodes and builds a {@link xdr.SorobanTransactionData} instance. + * @param {Uint8Array|Buffer|string} data raw input to decode + * @returns {xdr.SorobanTransactionData} + */ + return _createClass(SorobanDataBuilder, [{ + key: "setResourceFee", + value: + /** + * Sets the resource fee portion of the Soroban data. + * @param {number | bigint | string} fee the resource fee to set (int64) + * @returns {SorobanDataBuilder} + */ + function setResourceFee(fee) { + this._data.resourceFee(new _xdr["default"].Int64(fee)); + return this; + } + + /** + * Sets up the resource metrics. + * + * You should almost NEVER need this, as its often generated / provided to you + * by transaction simulation/preflight from a Soroban RPC server. + * + * @param {number} cpuInstrs number of CPU instructions + * @param {number} readBytes number of bytes being read + * @param {number} writeBytes number of bytes being written + * + * @returns {SorobanDataBuilder} + */ + }, { + key: "setResources", + value: function setResources(cpuInstrs, readBytes, writeBytes) { + this._data.resources().instructions(cpuInstrs); + this._data.resources().readBytes(readBytes); + this._data.resources().writeBytes(writeBytes); + return this; + } + + /** + * Appends the given ledger keys to the existing storage access footprint. + * @param {xdr.LedgerKey[]} readOnly read-only keys to add + * @param {xdr.LedgerKey[]} readWrite read-write keys to add + * @returns {SorobanDataBuilder} this builder instance + */ + }, { + key: "appendFootprint", + value: function appendFootprint(readOnly, readWrite) { + return this.setFootprint(this.getReadOnly().concat(readOnly), this.getReadWrite().concat(readWrite)); + } + + /** + * Sets the storage access footprint to be a certain set of ledger keys. + * + * You can also set each field explicitly via + * {@link SorobanDataBuilder.setReadOnly} and + * {@link SorobanDataBuilder.setReadWrite} or add to the existing footprint + * via {@link SorobanDataBuilder.appendFootprint}. + * + * Passing `null|undefined` to either parameter will IGNORE the existing + * values. If you want to clear them, pass `[]`, instead. + * + * @param {xdr.LedgerKey[]|null} [readOnly] the set of ledger keys to set in + * the read-only portion of the transaction's `sorobanData`, or `null | + * undefined` to keep the existing keys + * @param {xdr.LedgerKey[]|null} [readWrite] the set of ledger keys to set in + * the read-write portion of the transaction's `sorobanData`, or `null | + * undefined` to keep the existing keys + * @returns {SorobanDataBuilder} this builder instance + */ + }, { + key: "setFootprint", + value: function setFootprint(readOnly, readWrite) { + if (readOnly !== null) { + // null means "leave me alone" + this.setReadOnly(readOnly); + } + if (readWrite !== null) { + this.setReadWrite(readWrite); + } + return this; + } + + /** + * @param {xdr.LedgerKey[]} readOnly read-only keys in the access footprint + * @returns {SorobanDataBuilder} + */ + }, { + key: "setReadOnly", + value: function setReadOnly(readOnly) { + this._data.resources().footprint().readOnly(readOnly !== null && readOnly !== void 0 ? readOnly : []); + return this; + } + + /** + * @param {xdr.LedgerKey[]} readWrite read-write keys in the access footprint + * @returns {SorobanDataBuilder} + */ + }, { + key: "setReadWrite", + value: function setReadWrite(readWrite) { + this._data.resources().footprint().readWrite(readWrite !== null && readWrite !== void 0 ? readWrite : []); + return this; + } + + /** + * @returns {xdr.SorobanTransactionData} a copy of the final data structure + */ + }, { + key: "build", + value: function build() { + return _xdr["default"].SorobanTransactionData.fromXDR(this._data.toXDR()); // clone + } + + // + // getters follow + // + + /** @returns {xdr.LedgerKey[]} the read-only storage access pattern */ + }, { + key: "getReadOnly", + value: function getReadOnly() { + return this.getFootprint().readOnly(); + } + + /** @returns {xdr.LedgerKey[]} the read-write storage access pattern */ + }, { + key: "getReadWrite", + value: function getReadWrite() { + return this.getFootprint().readWrite(); + } + + /** @returns {xdr.LedgerFootprint} the storage access pattern */ + }, { + key: "getFootprint", + value: function getFootprint() { + return this._data.resources().footprint(); + } + }], [{ + key: "fromXDR", + value: function fromXDR(data) { + return _xdr["default"].SorobanTransactionData.fromXDR(data, typeof data === 'string' ? 'base64' : 'raw'); + } + }]); +}(); + +/***/ }), + +/***/ 7120: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.StrKey = void 0; +exports.decodeCheck = decodeCheck; +exports.encodeCheck = encodeCheck; +var _base = _interopRequireDefault(__webpack_require__(5360)); +var _checksum = __webpack_require__(1346); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint no-bitwise: ["error", {"allow": ["<<", ">>", "^", "&", "&="]}] */ +var versionBytes = { + ed25519PublicKey: 6 << 3, + // G (when encoded in base32) + ed25519SecretSeed: 18 << 3, + // S + med25519PublicKey: 12 << 3, + // M + preAuthTx: 19 << 3, + // T + sha256Hash: 23 << 3, + // X + signedPayload: 15 << 3, + // P + contract: 2 << 3 // C +}; +var strkeyTypes = { + G: 'ed25519PublicKey', + S: 'ed25519SecretSeed', + M: 'med25519PublicKey', + T: 'preAuthTx', + X: 'sha256Hash', + P: 'signedPayload', + C: 'contract' +}; + +/** + * StrKey is a helper class that allows encoding and decoding Stellar keys + * to/from strings, i.e. between their binary (Buffer, xdr.PublicKey, etc.) and + * string (i.e. "GABCD...", etc.) representations. + */ +var StrKey = exports.StrKey = /*#__PURE__*/function () { + function StrKey() { + _classCallCheck(this, StrKey); + } + return _createClass(StrKey, null, [{ + key: "encodeEd25519PublicKey", + value: + /** + * Encodes `data` to strkey ed25519 public key. + * + * @param {Buffer} data raw data to encode + * @returns {string} "G..." representation of the key + */ + function encodeEd25519PublicKey(data) { + return encodeCheck('ed25519PublicKey', data); + } + + /** + * Decodes strkey ed25519 public key to raw data. + * + * If the parameter is a muxed account key ("M..."), this will only encode it + * as a basic Ed25519 key (as if in "G..." format). + * + * @param {string} data "G..." (or "M...") key representation to decode + * @returns {Buffer} raw key + */ + }, { + key: "decodeEd25519PublicKey", + value: function decodeEd25519PublicKey(data) { + return decodeCheck('ed25519PublicKey', data); + } + + /** + * Returns true if the given Stellar public key is a valid ed25519 public key. + * @param {string} publicKey public key to check + * @returns {boolean} + */ + }, { + key: "isValidEd25519PublicKey", + value: function isValidEd25519PublicKey(publicKey) { + return isValid('ed25519PublicKey', publicKey); + } + + /** + * Encodes data to strkey ed25519 seed. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeEd25519SecretSeed", + value: function encodeEd25519SecretSeed(data) { + return encodeCheck('ed25519SecretSeed', data); + } + + /** + * Decodes strkey ed25519 seed to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeEd25519SecretSeed", + value: function decodeEd25519SecretSeed(address) { + return decodeCheck('ed25519SecretSeed', address); + } + + /** + * Returns true if the given Stellar secret key is a valid ed25519 secret seed. + * @param {string} seed seed to check + * @returns {boolean} + */ + }, { + key: "isValidEd25519SecretSeed", + value: function isValidEd25519SecretSeed(seed) { + return isValid('ed25519SecretSeed', seed); + } + + /** + * Encodes data to strkey med25519 public key. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeMed25519PublicKey", + value: function encodeMed25519PublicKey(data) { + return encodeCheck('med25519PublicKey', data); + } + + /** + * Decodes strkey med25519 public key to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeMed25519PublicKey", + value: function decodeMed25519PublicKey(address) { + return decodeCheck('med25519PublicKey', address); + } + + /** + * Returns true if the given Stellar public key is a valid med25519 public key. + * @param {string} publicKey public key to check + * @returns {boolean} + */ + }, { + key: "isValidMed25519PublicKey", + value: function isValidMed25519PublicKey(publicKey) { + return isValid('med25519PublicKey', publicKey); + } + + /** + * Encodes data to strkey preAuthTx. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodePreAuthTx", + value: function encodePreAuthTx(data) { + return encodeCheck('preAuthTx', data); + } + + /** + * Decodes strkey PreAuthTx to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodePreAuthTx", + value: function decodePreAuthTx(address) { + return decodeCheck('preAuthTx', address); + } + + /** + * Encodes data to strkey sha256 hash. + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeSha256Hash", + value: function encodeSha256Hash(data) { + return encodeCheck('sha256Hash', data); + } + + /** + * Decodes strkey sha256 hash to raw data. + * @param {string} address data to decode + * @returns {Buffer} + */ + }, { + key: "decodeSha256Hash", + value: function decodeSha256Hash(address) { + return decodeCheck('sha256Hash', address); + } + + /** + * Encodes raw data to strkey signed payload (P...). + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeSignedPayload", + value: function encodeSignedPayload(data) { + return encodeCheck('signedPayload', data); + } + + /** + * Decodes strkey signed payload (P...) to raw data. + * @param {string} address address to decode + * @returns {Buffer} + */ + }, { + key: "decodeSignedPayload", + value: function decodeSignedPayload(address) { + return decodeCheck('signedPayload', address); + } + + /** + * Checks validity of alleged signed payload (P...) strkey address. + * @param {string} address signer key to check + * @returns {boolean} + */ + }, { + key: "isValidSignedPayload", + value: function isValidSignedPayload(address) { + return isValid('signedPayload', address); + } + + /** + * Encodes raw data to strkey contract (C...). + * @param {Buffer} data data to encode + * @returns {string} + */ + }, { + key: "encodeContract", + value: function encodeContract(data) { + return encodeCheck('contract', data); + } + + /** + * Decodes strkey contract (C...) to raw data. + * @param {string} address address to decode + * @returns {Buffer} + */ + }, { + key: "decodeContract", + value: function decodeContract(address) { + return decodeCheck('contract', address); + } + + /** + * Checks validity of alleged contract (C...) strkey address. + * @param {string} address signer key to check + * @returns {boolean} + */ + }, { + key: "isValidContract", + value: function isValidContract(address) { + return isValid('contract', address); + } + }, { + key: "getVersionByteForPrefix", + value: function getVersionByteForPrefix(address) { + return strkeyTypes[address[0]]; + } + }]); +}(); +/** + * Sanity-checks whether or not a strkey *appears* valid. + * + * @param {string} versionByteName the type of strkey to expect in `encoded` + * @param {string} encoded the strkey to validate + * + * @return {Boolean} whether or not the `encoded` strkey appears valid for the + * `versionByteName` strkey type (see `versionBytes`, above). + * + * @note This isn't a *definitive* check of validity, but rather a best-effort + * check based on (a) input length, (b) whether or not it can be decoded, + * and (c) output length. + */ +function isValid(versionByteName, encoded) { + if (typeof encoded !== 'string') { + return false; + } + + // basic length checks on the strkey lengths + switch (versionByteName) { + case 'ed25519PublicKey': // falls through + case 'ed25519SecretSeed': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + case 'contract': + if (encoded.length !== 56) { + return false; + } + break; + case 'med25519PublicKey': + if (encoded.length !== 69) { + return false; + } + break; + case 'signedPayload': + if (encoded.length < 56 || encoded.length > 165) { + return false; + } + break; + default: + return false; + } + var decoded = ''; + try { + decoded = decodeCheck(versionByteName, encoded); + } catch (err) { + return false; + } + + // basic length checks on the resulting buffer sizes + switch (versionByteName) { + case 'ed25519PublicKey': // falls through + case 'ed25519SecretSeed': // falls through + case 'preAuthTx': // falls through + case 'sha256Hash': // falls through + case 'contract': + return decoded.length === 32; + case 'med25519PublicKey': + return decoded.length === 40; + // +8 bytes for the ID + + case 'signedPayload': + return ( + // 32 for the signer, +4 for the payload size, then either +4 for the + // min or +64 for the max payload + decoded.length >= 32 + 4 + 4 && decoded.length <= 32 + 4 + 64 + ); + default: + return false; + } +} +function decodeCheck(versionByteName, encoded) { + if (typeof encoded !== 'string') { + throw new TypeError('encoded argument must be of type String'); + } + var decoded = _base["default"].decode(encoded); + var versionByte = decoded[0]; + var payload = decoded.slice(0, -2); + var data = payload.slice(1); + var checksum = decoded.slice(-2); + if (encoded !== _base["default"].encode(decoded)) { + throw new Error('invalid encoded string'); + } + var expectedVersion = versionBytes[versionByteName]; + if (expectedVersion === undefined) { + throw new Error("".concat(versionByteName, " is not a valid version byte name. ") + "Expected one of ".concat(Object.keys(versionBytes).join(', '))); + } + if (versionByte !== expectedVersion) { + throw new Error("invalid version byte. expected ".concat(expectedVersion, ", got ").concat(versionByte)); + } + var expectedChecksum = calculateChecksum(payload); + if (!(0, _checksum.verifyChecksum)(expectedChecksum, checksum)) { + throw new Error("invalid checksum"); + } + return Buffer.from(data); +} +function encodeCheck(versionByteName, data) { + if (data === null || data === undefined) { + throw new Error('cannot encode null data'); + } + var versionByte = versionBytes[versionByteName]; + if (versionByte === undefined) { + throw new Error("".concat(versionByteName, " is not a valid version byte name. ") + "Expected one of ".concat(Object.keys(versionBytes).join(', '))); + } + data = Buffer.from(data); + var versionBuffer = Buffer.from([versionByte]); + var payload = Buffer.concat([versionBuffer, data]); + var checksum = Buffer.from(calculateChecksum(payload)); + var unencoded = Buffer.concat([payload, checksum]); + return _base["default"].encode(unencoded); +} + +// Computes the CRC16-XModem checksum of `payload` in little-endian order +function calculateChecksum(payload) { + var crcTable = [0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0]; + var crc16 = 0x0; + for (var i = 0; i < payload.length; i += 1) { + var _byte = payload[i]; + var lookupIndex = crc16 >> 8 ^ _byte; + crc16 = crc16 << 8 ^ crcTable[lookupIndex]; + crc16 &= 0xffff; + } + var checksum = new Uint8Array(2); + checksum[0] = crc16 & 0xff; + checksum[1] = crc16 >> 8 & 0xff; + return checksum; +} + +/***/ }), + +/***/ 380: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Transaction = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _hashing = __webpack_require__(9152); +var _strkey = __webpack_require__(7120); +var _operation = __webpack_require__(7237); +var _memo = __webpack_require__(4172); +var _transaction_base = __webpack_require__(3758); +var _decode_encode_muxed_account = __webpack_require__(6160); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +/** + * Use {@link TransactionBuilder} to build a transaction object. If you have an + * object or base64-encoded string of the transaction envelope XDR, use {@link + * TransactionBuilder.fromXDR}. + * + * Once a Transaction has been created, its attributes and operations should not + * be changed. You should only add signatures (using {@link Transaction#sign}) + * to a Transaction object before submitting to the network or forwarding on to + * additional signers. + * + * @constructor + * + * @param {string|xdr.TransactionEnvelope} envelope - transaction envelope + * object or base64 encoded string + * @param {string} [networkPassphrase] - passphrase of the target stellar + * network (e.g. "Public Global Stellar Network ; September 2015") + * + * @extends TransactionBase + */ +var Transaction = exports.Transaction = /*#__PURE__*/function (_TransactionBase) { + function Transaction(envelope, networkPassphrase) { + var _this; + _classCallCheck(this, Transaction); + if (typeof envelope === 'string') { + var buffer = Buffer.from(envelope, 'base64'); + envelope = _xdr["default"].TransactionEnvelope.fromXDR(buffer); + } + var envelopeType = envelope["switch"](); + if (!(envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTxV0() || envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTx())) { + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ".concat(envelopeType.name, ".")); + } + var txEnvelope = envelope.value(); + var tx = txEnvelope.tx(); + var fee = tx.fee().toString(); + var signatures = (txEnvelope.signatures() || []).slice(); + _this = _callSuper(this, Transaction, [tx, signatures, fee, networkPassphrase]); + _this._envelopeType = envelopeType; + _this._memo = tx.memo(); + _this._sequence = tx.seqNum().toString(); + switch (_this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + _this._source = _strkey.StrKey.encodeEd25519PublicKey(_this.tx.sourceAccountEd25519()); + break; + default: + _this._source = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(_this.tx.sourceAccount()); + break; + } + var cond = null; + var timeBounds = null; + switch (_this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + timeBounds = tx.timeBounds(); + break; + case _xdr["default"].EnvelopeType.envelopeTypeTx(): + switch (tx.cond()["switch"]()) { + case _xdr["default"].PreconditionType.precondTime(): + timeBounds = tx.cond().timeBounds(); + break; + case _xdr["default"].PreconditionType.precondV2(): + cond = tx.cond().v2(); + timeBounds = cond.timeBounds(); + break; + default: + break; + } + break; + default: + break; + } + if (timeBounds) { + _this._timeBounds = { + minTime: timeBounds.minTime().toString(), + maxTime: timeBounds.maxTime().toString() + }; + } + if (cond) { + var ledgerBounds = cond.ledgerBounds(); + if (ledgerBounds) { + _this._ledgerBounds = { + minLedger: ledgerBounds.minLedger(), + maxLedger: ledgerBounds.maxLedger() + }; + } + var minSeq = cond.minSeqNum(); + if (minSeq) { + _this._minAccountSequence = minSeq.toString(); + } + _this._minAccountSequenceAge = cond.minSeqAge(); + _this._minAccountSequenceLedgerGap = cond.minSeqLedgerGap(); + _this._extraSigners = cond.extraSigners(); + } + var operations = tx.operations() || []; + _this._operations = operations.map(function (op) { + return _operation.Operation.fromXDRObject(op); + }); + return _this; + } + + /** + * @type {object} + * @property {string} 64 bit unix timestamp + * @property {string} 64 bit unix timestamp + * @readonly + */ + _inherits(Transaction, _TransactionBase); + return _createClass(Transaction, [{ + key: "timeBounds", + get: function get() { + return this._timeBounds; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {object} + * @property {number} minLedger - smallest ledger bound (uint32) + * @property {number} maxLedger - largest ledger bound (or 0 for inf) + * @readonly + */ + }, { + key: "ledgerBounds", + get: function get() { + return this._ledgerBounds; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 64 bit account sequence + * @readonly + * @type {string} + */ + }, { + key: "minAccountSequence", + get: function get() { + return this._minAccountSequence; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 64 bit number of seconds + * @type {number} + * @readonly + */ + }, { + key: "minAccountSequenceAge", + get: function get() { + return this._minAccountSequenceAge; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * 32 bit number of ledgers + * @type {number} + * @readonly + */ + }, { + key: "minAccountSequenceLedgerGap", + get: function get() { + return this._minAccountSequenceLedgerGap; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * array of extra signers ({@link StrKey}s) + * @type {string[]} + * @readonly + */ + }, { + key: "extraSigners", + get: function get() { + return this._extraSigners; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "sequence", + get: function get() { + return this._sequence; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "source", + get: function get() { + return this._source; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {Array.} + * @readonly + */ + }, { + key: "operations", + get: function get() { + return this._operations; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "memo", + get: function get() { + return _memo.Memo.fromXDRObject(this._memo); + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * Returns the "signature base" of this transaction, which is the value + * that, when hashed, should be signed to create a signature that + * validators on the Stellar Network will accept. + * + * It is composed of a 4 prefix bytes followed by the xdr-encoded form + * of this transaction. + * @returns {Buffer} + */ + }, { + key: "signatureBase", + value: function signatureBase() { + var tx = this.tx; + + // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0 + // we need a Transaction to generate the signature base + if (this._envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTxV0()) { + tx = _xdr["default"].Transaction.fromXDR(Buffer.concat([ + // TransactionV0 is a transaction with the AccountID discriminant + // stripped off, we need to put it back to build a valid transaction + // which we can use to build a TransactionSignaturePayloadTaggedTransaction + _xdr["default"].PublicKeyType.publicKeyTypeEd25519().toXDR(), tx.toXDR()])); + } + var taggedTransaction = new _xdr["default"].TransactionSignaturePayloadTaggedTransaction.envelopeTypeTx(tx); + var txSignature = new _xdr["default"].TransactionSignaturePayload({ + networkId: _xdr["default"].Hash.fromXDR((0, _hashing.hash)(this.networkPassphrase)), + taggedTransaction: taggedTransaction + }); + return txSignature.toXDR(); + } + + /** + * To envelope returns a xdr.TransactionEnvelope which can be submitted to the network. + * @returns {xdr.TransactionEnvelope} + */ + }, { + key: "toEnvelope", + value: function toEnvelope() { + var rawTx = this.tx.toXDR(); + var signatures = this.signatures.slice(); // make a copy of the signatures + + var envelope; + switch (this._envelopeType) { + case _xdr["default"].EnvelopeType.envelopeTypeTxV0(): + envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTxV0(new _xdr["default"].TransactionV0Envelope({ + tx: _xdr["default"].TransactionV0.fromXDR(rawTx), + // make a copy of tx + signatures: signatures + })); + break; + case _xdr["default"].EnvelopeType.envelopeTypeTx(): + envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: _xdr["default"].Transaction.fromXDR(rawTx), + // make a copy of tx + signatures: signatures + })); + break; + default: + throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ".concat(this._envelopeType.name, ".")); + } + return envelope; + } + + /** + * Calculate the claimable balance ID for an operation within the transaction. + * + * @param {integer} opIndex the index of the CreateClaimableBalance op + * @returns {string} a hex string representing the claimable balance ID + * + * @throws {RangeError} for invalid `opIndex` value + * @throws {TypeError} if op at `opIndex` is not `CreateClaimableBalance` + * @throws for general XDR un/marshalling failures + * + * @see https://github.com/stellar/go/blob/d712346e61e288d450b0c08038c158f8848cc3e4/txnbuild/transaction.go#L392-L435 + * + */ + }, { + key: "getClaimableBalanceId", + value: function getClaimableBalanceId(opIndex) { + // Validate and then extract the operation from the transaction. + if (!Number.isInteger(opIndex) || opIndex < 0 || opIndex >= this.operations.length) { + throw new RangeError('invalid operation index'); + } + var op = this.operations[opIndex]; + try { + op = _operation.Operation.createClaimableBalance(op); + } catch (err) { + throw new TypeError("expected createClaimableBalance, got ".concat(op.type, ": ").concat(err)); + } + + // Always use the transaction's *unmuxed* source. + var account = _strkey.StrKey.decodeEd25519PublicKey((0, _decode_encode_muxed_account.extractBaseAddress)(this.source)); + var operationId = _xdr["default"].HashIdPreimage.envelopeTypeOpId(new _xdr["default"].HashIdPreimageOperationId({ + sourceAccount: _xdr["default"].AccountId.publicKeyTypeEd25519(account), + seqNum: _xdr["default"].SequenceNumber.fromString(this.sequence), + opNum: opIndex + })); + var opIdHash = (0, _hashing.hash)(operationId.toXDR('raw')); + var balanceId = _xdr["default"].ClaimableBalanceId.claimableBalanceIdTypeV0(opIdHash); + return balanceId.toXDR('hex'); + } + }]); +}(_transaction_base.TransactionBase); + +/***/ }), + +/***/ 3758: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.TransactionBase = void 0; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _hashing = __webpack_require__(9152); +var _keypair = __webpack_require__(6691); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * @ignore + */ +var TransactionBase = exports.TransactionBase = /*#__PURE__*/function () { + function TransactionBase(tx, signatures, fee, networkPassphrase) { + _classCallCheck(this, TransactionBase); + if (typeof networkPassphrase !== 'string') { + throw new Error("Invalid passphrase provided to Transaction: expected a string but got a ".concat(_typeof(networkPassphrase))); + } + this._networkPassphrase = networkPassphrase; + this._tx = tx; + this._signatures = signatures; + this._fee = fee; + } + + /** + * @type {Array.} + * @readonly + */ + return _createClass(TransactionBase, [{ + key: "signatures", + get: function get() { + return this._signatures; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + }, { + key: "tx", + get: function get() { + return this._tx; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "fee", + get: function get() { + return this._fee; + }, + set: function set(value) { + throw new Error('Transaction is immutable'); + } + + /** + * @type {string} + * @readonly + */ + }, { + key: "networkPassphrase", + get: function get() { + return this._networkPassphrase; + }, + set: function set(networkPassphrase) { + this._networkPassphrase = networkPassphrase; + } + + /** + * Signs the transaction with the given {@link Keypair}. + * @param {...Keypair} keypairs Keypairs of signers + * @returns {void} + */ + }, { + key: "sign", + value: function sign() { + var _this = this; + var txHash = this.hash(); + for (var _len = arguments.length, keypairs = new Array(_len), _key = 0; _key < _len; _key++) { + keypairs[_key] = arguments[_key]; + } + keypairs.forEach(function (kp) { + var sig = kp.signDecorated(txHash); + _this.signatures.push(sig); + }); + } + + /** + * Signs a transaction with the given {@link Keypair}. Useful if someone sends + * you a transaction XDR for you to sign and return (see + * [addSignature](#addSignature) for more information). + * + * When you get a transaction XDR to sign.... + * - Instantiate a `Transaction` object with the XDR + * - Use {@link Keypair} to generate a keypair object for your Stellar seed. + * - Run `getKeypairSignature` with that keypair + * - Send back the signature along with your publicKey (not your secret seed!) + * + * Example: + * ```javascript + * // `transactionXDR` is a string from the person generating the transaction + * const transaction = new Transaction(transactionXDR, networkPassphrase); + * const keypair = Keypair.fromSecret(myStellarSeed); + * return transaction.getKeypairSignature(keypair); + * ``` + * + * @param {Keypair} keypair Keypair of signer + * @returns {string} Signature string + */ + }, { + key: "getKeypairSignature", + value: function getKeypairSignature(keypair) { + return keypair.sign(this.hash()).toString('base64'); + } + + /** + * Add a signature to the transaction. Useful when a party wants to pre-sign + * a transaction but doesn't want to give access to their secret keys. + * This will also verify whether the signature is valid. + * + * Here's how you would use this feature to solicit multiple signatures. + * - Use `TransactionBuilder` to build a new transaction. + * - Make sure to set a long enough timeout on that transaction to give your + * signers enough time to sign! + * - Once you build the transaction, use `transaction.toXDR()` to get the + * base64-encoded XDR string. + * - _Warning!_ Once you've built this transaction, don't submit any other + * transactions onto your account! Doing so will invalidate this pre-compiled + * transaction! + * - Send this XDR string to your other parties. They can use the instructions + * for [getKeypairSignature](#getKeypairSignature) to sign the transaction. + * - They should send you back their `publicKey` and the `signature` string + * from [getKeypairSignature](#getKeypairSignature), both of which you pass to + * this function. + * + * @param {string} publicKey The public key of the signer + * @param {string} signature The base64 value of the signature XDR + * @returns {void} + */ + }, { + key: "addSignature", + value: function addSignature() { + var publicKey = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var signature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + if (!signature || typeof signature !== 'string') { + throw new Error('Invalid signature'); + } + if (!publicKey || typeof publicKey !== 'string') { + throw new Error('Invalid publicKey'); + } + var keypair; + var hint; + var signatureBuffer = Buffer.from(signature, 'base64'); + try { + keypair = _keypair.Keypair.fromPublicKey(publicKey); + hint = keypair.signatureHint(); + } catch (e) { + throw new Error('Invalid publicKey'); + } + if (!keypair.verify(this.hash(), signatureBuffer)) { + throw new Error('Invalid signature'); + } + this.signatures.push(new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signatureBuffer + })); + } + + /** + * Add a decorated signature directly to the transaction envelope. + * + * @param {xdr.DecoratedSignature} signature raw signature to add + * @returns {void} + * + * @see Keypair.signDecorated + * @see Keypair.signPayloadDecorated + */ + }, { + key: "addDecoratedSignature", + value: function addDecoratedSignature(signature) { + this.signatures.push(signature); + } + + /** + * Add `hashX` signer preimage as signature. + * @param {Buffer|String} preimage Preimage of hash used as signer + * @returns {void} + */ + }, { + key: "signHashX", + value: function signHashX(preimage) { + if (typeof preimage === 'string') { + preimage = Buffer.from(preimage, 'hex'); + } + if (preimage.length > 64) { + throw new Error('preimage cannnot be longer than 64 bytes'); + } + var signature = preimage; + var hashX = (0, _hashing.hash)(preimage); + var hint = hashX.slice(hashX.length - 4); + this.signatures.push(new _xdr["default"].DecoratedSignature({ + hint: hint, + signature: signature + })); + } + + /** + * Returns a hash for this transaction, suitable for signing. + * @returns {Buffer} + */ + }, { + key: "hash", + value: function hash() { + return (0, _hashing.hash)(this.signatureBase()); + } + }, { + key: "signatureBase", + value: function signatureBase() { + throw new Error('Implement in subclass'); + } + }, { + key: "toEnvelope", + value: function toEnvelope() { + throw new Error('Implement in subclass'); + } + + /** + * Get the transaction envelope as a base64-encoded string + * @returns {string} XDR string + */ + }, { + key: "toXDR", + value: function toXDR() { + return this.toEnvelope().toXDR().toString('base64'); + } + }]); +}(); + +/***/ }), + +/***/ 6396: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.TransactionBuilder = exports.TimeoutInfinite = exports.BASE_FEE = void 0; +exports.isValidDate = isValidDate; +var _jsXdr = __webpack_require__(3740); +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _account = __webpack_require__(2135); +var _muxed_account = __webpack_require__(2243); +var _decode_encode_muxed_account = __webpack_require__(6160); +var _transaction = __webpack_require__(380); +var _fee_bump_transaction = __webpack_require__(9260); +var _sorobandata_builder = __webpack_require__(4842); +var _strkey = __webpack_require__(7120); +var _signerkey = __webpack_require__(225); +var _memo = __webpack_require__(4172); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +/** + * Minimum base fee for transactions. If this fee is below the network + * minimum, the transaction will fail. The more operations in the + * transaction, the greater the required fee. Use {@link + * Server#fetchBaseFee} to get an accurate value of minimum transaction + * fee on the network. + * + * @constant + * @see [Fees](https://developers.stellar.org/docs/glossary/fees/) + */ +var BASE_FEE = exports.BASE_FEE = '100'; // Stroops + +/** + * @constant + * @see {@link TransactionBuilder#setTimeout} + * @see [Timeout](https://developers.stellar.org/api/resources/transactions/post/) + */ +var TimeoutInfinite = exports.TimeoutInfinite = 0; + +/** + *

Transaction builder helps constructs a new `{@link Transaction}` using the + * given {@link Account} as the transaction's "source account". The transaction + * will use the current sequence number of the given account as its sequence + * number and increment the given account's sequence number by one. The given + * source account must include a private key for signing the transaction or an + * error will be thrown.

+ * + *

Operations can be added to the transaction via their corresponding builder + * methods, and each returns the TransactionBuilder object so they can be + * chained together. After adding the desired operations, call the `build()` + * method on the `TransactionBuilder` to return a fully constructed `{@link + * Transaction}` that can be signed. The returned transaction will contain the + * sequence number of the source account and include the signature from the + * source account.

+ * + *

Be careful about unsubmitted transactions! When you build + * a transaction, `stellar-sdk` automatically increments the source account's + * sequence number. If you end up not submitting this transaction and submitting + * another one instead, it'll fail due to the sequence number being wrong. So if + * you decide not to use a built transaction, make sure to update the source + * account's sequence number with + * [Server.loadAccount](https://stellar.github.io/js-stellar-sdk/Server.html#loadAccount) + * before creating another transaction.

+ * + *

The following code example creates a new transaction with {@link + * Operation.createAccount} and {@link Operation.payment} operations. The + * Transaction's source account first funds `destinationA`, then sends a payment + * to `destinationB`. The built transaction is then signed by + * `sourceKeypair`.

+ * + * ``` + * var transaction = new TransactionBuilder(source, { fee, networkPassphrase: Networks.TESTNET }) + * .addOperation(Operation.createAccount({ + * destination: destinationA, + * startingBalance: "20" + * })) // <- funds and creates destinationA + * .addOperation(Operation.payment({ + * destination: destinationB, + * amount: "100", + * asset: Asset.native() + * })) // <- sends 100 XLM to destinationB + * .setTimeout(30) + * .build(); + * + * transaction.sign(sourceKeypair); + * ``` + * + * @constructor + * + * @param {Account} sourceAccount - source account for this transaction + * @param {object} opts - Options object + * @param {string} opts.fee - max fee you're willing to pay per + * operation in this transaction (**in stroops**) + * + * @param {object} [opts.timebounds] - timebounds for the + * validity of this transaction + * @param {number|string|Date} [opts.timebounds.minTime] - 64-bit UNIX + * timestamp or Date object + * @param {number|string|Date} [opts.timebounds.maxTime] - 64-bit UNIX + * timestamp or Date object + * @param {object} [opts.ledgerbounds] - ledger bounds for the + * validity of this transaction + * @param {number} [opts.ledgerbounds.minLedger] - number of the minimum + * ledger sequence + * @param {number} [opts.ledgerbounds.maxLedger] - number of the maximum + * ledger sequence + * @param {string} [opts.minAccountSequence] - number for + * the minimum account sequence + * @param {number} [opts.minAccountSequenceAge] - number of + * seconds for the minimum account sequence age + * @param {number} [opts.minAccountSequenceLedgerGap] - number of + * ledgers for the minimum account sequence ledger gap + * @param {string[]} [opts.extraSigners] - list of the extra signers + * required for this transaction + * @param {Memo} [opts.memo] - memo for the transaction + * @param {string} [opts.networkPassphrase] passphrase of the + * target Stellar network (e.g. "Public Global Stellar Network ; September + * 2015" for the pubnet) + * @param {xdr.SorobanTransactionData | string} [opts.sorobanData] - an + * optional instance of {@link xdr.SorobanTransactionData} to be set as the + * internal `Transaction.Ext.SorobanData` field (either the xdr object or a + * base64 string). In the case of Soroban transactions, this can be obtained + * from a prior simulation of the transaction with a contract invocation and + * provides necessary resource estimations. You can also use + * {@link SorobanDataBuilder} to construct complicated combinations of + * parameters without mucking with XDR directly. **Note:** For + * non-contract(non-Soroban) transactions, this has no effect. + */ +var TransactionBuilder = exports.TransactionBuilder = /*#__PURE__*/function () { + function TransactionBuilder(sourceAccount) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, TransactionBuilder); + if (!sourceAccount) { + throw new Error('must specify source account for the transaction'); + } + if (opts.fee === undefined) { + throw new Error('must specify fee for the transaction (in stroops)'); + } + this.source = sourceAccount; + this.operations = []; + this.baseFee = opts.fee; + this.timebounds = opts.timebounds ? _objectSpread({}, opts.timebounds) : null; + this.ledgerbounds = opts.ledgerbounds ? _objectSpread({}, opts.ledgerbounds) : null; + this.minAccountSequence = opts.minAccountSequence || null; + this.minAccountSequenceAge = opts.minAccountSequenceAge || null; + this.minAccountSequenceLedgerGap = opts.minAccountSequenceLedgerGap || null; + this.extraSigners = opts.extraSigners ? _toConsumableArray(opts.extraSigners) : null; + this.memo = opts.memo || _memo.Memo.none(); + this.networkPassphrase = opts.networkPassphrase || null; + this.sorobanData = opts.sorobanData ? new _sorobandata_builder.SorobanDataBuilder(opts.sorobanData).build() : null; + } + + /** + * Creates a builder instance using an existing {@link Transaction} as a + * template, ignoring any existing envelope signatures. + * + * Note that the sequence number WILL be cloned, so EITHER this transaction or + * the one it was cloned from will be valid. This is useful in situations + * where you are constructing a transaction in pieces and need to make + * adjustments as you go (for example, when filling out Soroban resource + * information). + * + * @param {Transaction} tx a "template" transaction to clone exactly + * @param {object} [opts] additional options to override the clone, e.g. + * {fee: '1000'} will override the existing base fee derived from `tx` (see + * the {@link TransactionBuilder} constructor for detailed options) + * + * @returns {TransactionBuilder} a "prepared" builder instance with the same + * configuration and operations as the given transaction + * + * @warning This does not clone the transaction's + * {@link xdr.SorobanTransactionData} (if applicable), use + * {@link SorobanDataBuilder} and {@link TransactionBuilder.setSorobanData} + * as needed, instead.. + * + * @todo This cannot clone {@link FeeBumpTransaction}s, yet. + */ + return _createClass(TransactionBuilder, [{ + key: "addOperation", + value: + /** + * Adds an operation to the transaction. + * + * @param {xdr.Operation} operation The xdr operation object, use {@link + * Operation} static methods. + * + * @returns {TransactionBuilder} + */ + function addOperation(operation) { + this.operations.push(operation); + return this; + } + + /** + * Adds an operation to the transaction at a specific index. + * + * @param {xdr.Operation} operation - The xdr operation object to add, use {@link Operation} static methods. + * @param {number} index - The index at which to insert the operation. + * + * @returns {TransactionBuilder} - The TransactionBuilder instance for method chaining. + */ + }, { + key: "addOperationAt", + value: function addOperationAt(operation, index) { + this.operations.splice(index, 0, operation); + return this; + } + + /** + * Removes the operations from the builder (useful when cloning). + * @returns {TransactionBuilder} this builder instance + */ + }, { + key: "clearOperations", + value: function clearOperations() { + this.operations = []; + return this; + } + + /** + * Removes the operation at the specified index from the transaction. + * + * @param {number} index - The index of the operation to remove. + * + * @returns {TransactionBuilder} The TransactionBuilder instance for method chaining. + */ + }, { + key: "clearOperationAt", + value: function clearOperationAt(index) { + this.operations.splice(index, 1); + return this; + } + + /** + * Adds a memo to the transaction. + * @param {Memo} memo {@link Memo} object + * @returns {TransactionBuilder} + */ + }, { + key: "addMemo", + value: function addMemo(memo) { + this.memo = memo; + return this; + } + + /** + * Sets a timeout precondition on the transaction. + * + * Because of the distributed nature of the Stellar network it is possible + * that the status of your transaction will be determined after a long time + * if the network is highly congested. If you want to be sure to receive the + * status of the transaction within a given period you should set the {@link + * TimeBounds} with `maxTime` on the transaction (this is what `setTimeout` + * does internally; if there's `minTime` set but no `maxTime` it will be + * added). + * + * A call to `TransactionBuilder.setTimeout` is **required** if Transaction + * does not have `max_time` set. If you don't want to set timeout, use + * `{@link TimeoutInfinite}`. In general you should set `{@link + * TimeoutInfinite}` only in smart contracts. + * + * Please note that Horizon may still return 504 Gateway Timeout + * error, even for short timeouts. In such case you need to resubmit the same + * transaction again without making any changes to receive a status. This + * method is using the machine system time (UTC), make sure it is set + * correctly. + * + * @param {number} timeoutSeconds Number of seconds the transaction is good. + * Can't be negative. If the value is {@link TimeoutInfinite}, the + * transaction is good indefinitely. + * + * @returns {TransactionBuilder} + * + * @see {@link TimeoutInfinite} + * @see https://developers.stellar.org/docs/tutorials/handling-errors/ + */ + }, { + key: "setTimeout", + value: function setTimeout(timeoutSeconds) { + if (this.timebounds !== null && this.timebounds.maxTime > 0) { + throw new Error('TimeBounds.max_time has been already set - setting timeout would overwrite it.'); + } + if (timeoutSeconds < 0) { + throw new Error('timeout cannot be negative'); + } + if (timeoutSeconds > 0) { + var timeoutTimestamp = Math.floor(Date.now() / 1000) + timeoutSeconds; + if (this.timebounds === null) { + this.timebounds = { + minTime: 0, + maxTime: timeoutTimestamp + }; + } else { + this.timebounds = { + minTime: this.timebounds.minTime, + maxTime: timeoutTimestamp + }; + } + } else { + this.timebounds = { + minTime: 0, + maxTime: 0 + }; + } + return this; + } + + /** + * If you want to prepare a transaction which will become valid at some point + * in the future, or be invalid after some time, you can set a timebounds + * precondition. Internally this will set the `minTime`, and `maxTime` + * preconditions. Conflicts with `setTimeout`, so use one or the other. + * + * @param {Date|number} minEpochOrDate Either a JS Date object, or a number + * of UNIX epoch seconds. The transaction is valid after this timestamp. + * Can't be negative. If the value is `0`, the transaction is valid + * immediately. + * @param {Date|number} maxEpochOrDate Either a JS Date object, or a number + * of UNIX epoch seconds. The transaction is valid until this timestamp. + * Can't be negative. If the value is `0`, the transaction is valid + * indefinitely. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setTimebounds", + value: function setTimebounds(minEpochOrDate, maxEpochOrDate) { + // Force it to a date type + if (typeof minEpochOrDate === 'number') { + minEpochOrDate = new Date(minEpochOrDate * 1000); + } + if (typeof maxEpochOrDate === 'number') { + maxEpochOrDate = new Date(maxEpochOrDate * 1000); + } + if (this.timebounds !== null) { + throw new Error('TimeBounds has been already set - setting timebounds would overwrite it.'); + } + + // Convert that date to the epoch seconds + var minTime = Math.floor(minEpochOrDate.valueOf() / 1000); + var maxTime = Math.floor(maxEpochOrDate.valueOf() / 1000); + if (minTime < 0) { + throw new Error('min_time cannot be negative'); + } + if (maxTime < 0) { + throw new Error('max_time cannot be negative'); + } + if (maxTime > 0 && minTime > maxTime) { + throw new Error('min_time cannot be greater than max_time'); + } + this.timebounds = { + minTime: minTime, + maxTime: maxTime + }; + return this; + } + + /** + * If you want to prepare a transaction which will only be valid within some + * range of ledgers, you can set a ledgerbounds precondition. + * Internally this will set the `minLedger` and `maxLedger` preconditions. + * + * @param {number} minLedger The minimum ledger this transaction is valid at + * or after. Cannot be negative. If the value is `0` (the default), the + * transaction is valid immediately. + * + * @param {number} maxLedger The maximum ledger this transaction is valid + * before. Cannot be negative. If the value is `0`, the transaction is + * valid indefinitely. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setLedgerbounds", + value: function setLedgerbounds(minLedger, maxLedger) { + if (this.ledgerbounds !== null) { + throw new Error('LedgerBounds has been already set - setting ledgerbounds would overwrite it.'); + } + if (minLedger < 0) { + throw new Error('min_ledger cannot be negative'); + } + if (maxLedger < 0) { + throw new Error('max_ledger cannot be negative'); + } + if (maxLedger > 0 && minLedger > maxLedger) { + throw new Error('min_ledger cannot be greater than max_ledger'); + } + this.ledgerbounds = { + minLedger: minLedger, + maxLedger: maxLedger + }; + return this; + } + + /** + * If you want to prepare a transaction which will be valid only while the + * account sequence number is + * + * minAccountSequence <= sourceAccountSequence < tx.seqNum + * + * Note that after execution the account's sequence number is always raised to + * `tx.seqNum`. Internally this will set the `minAccountSequence` + * precondition. + * + * @param {string} minAccountSequence The minimum source account sequence + * number this transaction is valid for. If the value is `0` (the + * default), the transaction is valid when `sourceAccount's sequence + * number == tx.seqNum- 1`. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequence", + value: function setMinAccountSequence(minAccountSequence) { + if (this.minAccountSequence !== null) { + throw new Error('min_account_sequence has been already set - setting min_account_sequence would overwrite it.'); + } + this.minAccountSequence = minAccountSequence; + return this; + } + + /** + * For the transaction to be valid, the current ledger time must be at least + * `minAccountSequenceAge` greater than sourceAccount's `sequenceTime`. + * Internally this will set the `minAccountSequenceAge` precondition. + * + * @param {number} durationInSeconds The minimum amount of time between + * source account sequence time and the ledger time when this transaction + * will become valid. If the value is `0`, the transaction is unrestricted + * by the account sequence age. Cannot be negative. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequenceAge", + value: function setMinAccountSequenceAge(durationInSeconds) { + if (typeof durationInSeconds !== 'number') { + throw new Error('min_account_sequence_age must be a number'); + } + if (this.minAccountSequenceAge !== null) { + throw new Error('min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.'); + } + if (durationInSeconds < 0) { + throw new Error('min_account_sequence_age cannot be negative'); + } + this.minAccountSequenceAge = durationInSeconds; + return this; + } + + /** + * For the transaction to be valid, the current ledger number must be at least + * `minAccountSequenceLedgerGap` greater than sourceAccount's ledger sequence. + * Internally this will set the `minAccountSequenceLedgerGap` precondition. + * + * @param {number} gap The minimum number of ledgers between source account + * sequence and the ledger number when this transaction will become valid. + * If the value is `0`, the transaction is unrestricted by the account + * sequence ledger. Cannot be negative. + * + * @returns {TransactionBuilder} + */ + }, { + key: "setMinAccountSequenceLedgerGap", + value: function setMinAccountSequenceLedgerGap(gap) { + if (this.minAccountSequenceLedgerGap !== null) { + throw new Error('min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.'); + } + if (gap < 0) { + throw new Error('min_account_sequence_ledger_gap cannot be negative'); + } + this.minAccountSequenceLedgerGap = gap; + return this; + } + + /** + * For the transaction to be valid, there must be a signature corresponding to + * every Signer in this array, even if the signature is not otherwise required + * by the sourceAccount or operations. Internally this will set the + * `extraSigners` precondition. + * + * @param {string[]} extraSigners required extra signers (as {@link StrKey}s) + * + * @returns {TransactionBuilder} + */ + }, { + key: "setExtraSigners", + value: function setExtraSigners(extraSigners) { + if (!Array.isArray(extraSigners)) { + throw new Error('extra_signers must be an array of strings.'); + } + if (this.extraSigners !== null) { + throw new Error('extra_signers has been already set - setting extra_signers would overwrite it.'); + } + if (extraSigners.length > 2) { + throw new Error('extra_signers cannot be longer than 2 elements.'); + } + this.extraSigners = _toConsumableArray(extraSigners); + return this; + } + + /** + * Set network nassphrase for the Transaction that will be built. + * + * @param {string} networkPassphrase passphrase of the target Stellar + * network (e.g. "Public Global Stellar Network ; September 2015"). + * + * @returns {TransactionBuilder} + */ + }, { + key: "setNetworkPassphrase", + value: function setNetworkPassphrase(networkPassphrase) { + this.networkPassphrase = networkPassphrase; + return this; + } + + /** + * Sets the transaction's internal Soroban transaction data (resources, + * footprint, etc.). + * + * For non-contract(non-Soroban) transactions, this setting has no effect. In + * the case of Soroban transactions, this is either an instance of + * {@link xdr.SorobanTransactionData} or a base64-encoded string of said + * structure. This is usually obtained from the simulation response based on a + * transaction with a Soroban operation (e.g. + * {@link Operation.invokeHostFunction}, providing necessary resource + * and storage footprint estimations for contract invocation. + * + * @param {xdr.SorobanTransactionData | string} sorobanData the + * {@link xdr.SorobanTransactionData} as a raw xdr object or a base64 + * string to be decoded + * + * @returns {TransactionBuilder} + * @see {SorobanDataBuilder} + */ + }, { + key: "setSorobanData", + value: function setSorobanData(sorobanData) { + this.sorobanData = new _sorobandata_builder.SorobanDataBuilder(sorobanData).build(); + return this; + } + + /** + * This will build the transaction. + * It will also increment the source account's sequence number by 1. + * @returns {Transaction} This method will return the built {@link Transaction}. + */ + }, { + key: "build", + value: function build() { + var sequenceNumber = new _bignumber["default"](this.source.sequenceNumber()).plus(1); + var fee = new _bignumber["default"](this.baseFee).times(this.operations.length).toNumber(); + var attrs = { + fee: fee, + seqNum: _xdr["default"].SequenceNumber.fromString(sequenceNumber.toString()), + memo: this.memo ? this.memo.toXDRObject() : null + }; + if (this.timebounds === null || typeof this.timebounds.minTime === 'undefined' || typeof this.timebounds.maxTime === 'undefined') { + throw new Error('TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).'); + } + if (isValidDate(this.timebounds.minTime)) { + this.timebounds.minTime = this.timebounds.minTime.getTime() / 1000; + } + if (isValidDate(this.timebounds.maxTime)) { + this.timebounds.maxTime = this.timebounds.maxTime.getTime() / 1000; + } + this.timebounds.minTime = _jsXdr.UnsignedHyper.fromString(this.timebounds.minTime.toString()); + this.timebounds.maxTime = _jsXdr.UnsignedHyper.fromString(this.timebounds.maxTime.toString()); + var timeBounds = new _xdr["default"].TimeBounds(this.timebounds); + if (this.hasV2Preconditions()) { + var ledgerBounds = null; + if (this.ledgerbounds !== null) { + ledgerBounds = new _xdr["default"].LedgerBounds(this.ledgerbounds); + } + var minSeqNum = this.minAccountSequence || '0'; + minSeqNum = _xdr["default"].SequenceNumber.fromString(minSeqNum); + var minSeqAge = _jsXdr.UnsignedHyper.fromString(this.minAccountSequenceAge !== null ? this.minAccountSequenceAge.toString() : '0'); + var minSeqLedgerGap = this.minAccountSequenceLedgerGap || 0; + var extraSigners = this.extraSigners !== null ? this.extraSigners.map(_signerkey.SignerKey.decodeAddress) : []; + attrs.cond = _xdr["default"].Preconditions.precondV2(new _xdr["default"].PreconditionsV2({ + timeBounds: timeBounds, + ledgerBounds: ledgerBounds, + minSeqNum: minSeqNum, + minSeqAge: minSeqAge, + minSeqLedgerGap: minSeqLedgerGap, + extraSigners: extraSigners + })); + } else { + attrs.cond = _xdr["default"].Preconditions.precondTime(timeBounds); + } + attrs.sourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(this.source.accountId()); + + // TODO - remove this workaround for TransactionExt ts constructor + // and use the typescript generated static factory method once fixed + // https://github.com/stellar/dts-xdr/issues/5 + if (this.sorobanData) { + // @ts-ignore + attrs.ext = new _xdr["default"].TransactionExt(1, this.sorobanData); + } else { + // @ts-ignore + attrs.ext = new _xdr["default"].TransactionExt(0, _xdr["default"].Void); + } + var xtx = new _xdr["default"].Transaction(attrs); + xtx.operations(this.operations); + var txEnvelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: xtx + })); + var tx = new _transaction.Transaction(txEnvelope, this.networkPassphrase); + this.source.incrementSequenceNumber(); + return tx; + } + }, { + key: "hasV2Preconditions", + value: function hasV2Preconditions() { + return this.ledgerbounds !== null || this.minAccountSequence !== null || this.minAccountSequenceAge !== null || this.minAccountSequenceLedgerGap !== null || this.extraSigners !== null && this.extraSigners.length > 0; + } + + /** + * Builds a {@link FeeBumpTransaction}, enabling you to resubmit an existing + * transaction with a higher fee. + * + * @param {Keypair|string} feeSource - account paying for the transaction, + * in the form of either a Keypair (only the public key is used) or + * an account ID (in G... or M... form, but refer to `withMuxing`) + * @param {string} baseFee - max fee willing to pay per operation + * in inner transaction (**in stroops**) + * @param {Transaction} innerTx - {@link Transaction} to be bumped by + * the fee bump transaction + * @param {string} networkPassphrase - passphrase of the target + * Stellar network (e.g. "Public Global Stellar Network ; September 2015", + * see {@link Networks}) + * + * @todo Alongside the next major version bump, this type signature can be + * changed to be less awkward: accept a MuxedAccount as the `feeSource` + * rather than a keypair or string. + * + * @note Your fee-bump amount should be >= 10x the original fee. + * @see https://developers.stellar.org/docs/glossary/fee-bumps/#replace-by-fee + * + * @returns {FeeBumpTransaction} + */ + }], [{ + key: "cloneFrom", + value: function cloneFrom(tx) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (!(tx instanceof _transaction.Transaction)) { + throw new TypeError("expected a 'Transaction', got: ".concat(tx)); + } + var sequenceNum = (BigInt(tx.sequence) - 1n).toString(); + var source; + // rebuild the source account based on the strkey + if (_strkey.StrKey.isValidMed25519PublicKey(tx.source)) { + source = _muxed_account.MuxedAccount.fromAddress(tx.source, sequenceNum); + } else if (_strkey.StrKey.isValidEd25519PublicKey(tx.source)) { + source = new _account.Account(tx.source, sequenceNum); + } else { + throw new TypeError("unsupported tx source account: ".concat(tx.source)); + } + + // the initial fee passed to the builder gets scaled up based on the number + // of operations at the end, so we have to down-scale first + var unscaledFee = parseInt(tx.fee, 10) / tx.operations.length; + var builder = new TransactionBuilder(source, _objectSpread({ + fee: (unscaledFee || BASE_FEE).toString(), + memo: tx.memo, + networkPassphrase: tx.networkPassphrase, + timebounds: tx.timeBounds, + ledgerbounds: tx.ledgerBounds, + minAccountSequence: tx.minAccountSequence, + minAccountSequenceAge: tx.minAccountSequenceAge, + minAccountSequenceLedgerGap: tx.minAccountSequenceLedgerGap, + extraSigners: tx.extraSigners + }, opts)); + tx._tx.operations().forEach(function (op) { + return builder.addOperation(op); + }); + return builder; + } + }, { + key: "buildFeeBumpTransaction", + value: function buildFeeBumpTransaction(feeSource, baseFee, innerTx, networkPassphrase) { + var innerOps = innerTx.operations.length; + var innerBaseFeeRate = new _bignumber["default"](innerTx.fee).div(innerOps); + var base = new _bignumber["default"](baseFee); + + // The fee rate for fee bump is at least the fee rate of the inner transaction + if (base.lt(innerBaseFeeRate)) { + throw new Error("Invalid baseFee, it should be at least ".concat(innerBaseFeeRate, " stroops.")); + } + var minBaseFee = new _bignumber["default"](BASE_FEE); + + // The fee rate is at least the minimum fee + if (base.lt(minBaseFee)) { + throw new Error("Invalid baseFee, it should be at least ".concat(minBaseFee, " stroops.")); + } + var innerTxEnvelope = innerTx.toEnvelope(); + if (innerTxEnvelope["switch"]() === _xdr["default"].EnvelopeType.envelopeTypeTxV0()) { + var v0Tx = innerTxEnvelope.v0().tx(); + var v1Tx = new _xdr["default"].Transaction({ + sourceAccount: new _xdr["default"].MuxedAccount.keyTypeEd25519(v0Tx.sourceAccountEd25519()), + fee: v0Tx.fee(), + seqNum: v0Tx.seqNum(), + cond: _xdr["default"].Preconditions.precondTime(v0Tx.timeBounds()), + memo: v0Tx.memo(), + operations: v0Tx.operations(), + ext: new _xdr["default"].TransactionExt(0) + }); + innerTxEnvelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({ + tx: v1Tx, + signatures: innerTxEnvelope.v0().signatures() + })); + } + var feeSourceAccount; + if (typeof feeSource === 'string') { + feeSourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(feeSource); + } else { + feeSourceAccount = feeSource.xdrMuxedAccount(); + } + var tx = new _xdr["default"].FeeBumpTransaction({ + feeSource: feeSourceAccount, + fee: _xdr["default"].Int64.fromString(base.times(innerOps + 1).toString()), + innerTx: _xdr["default"].FeeBumpTransactionInnerTx.envelopeTypeTx(innerTxEnvelope.v1()), + ext: new _xdr["default"].FeeBumpTransactionExt(0) + }); + var feeBumpTxEnvelope = new _xdr["default"].FeeBumpTransactionEnvelope({ + tx: tx, + signatures: [] + }); + var envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTxFeeBump(feeBumpTxEnvelope); + return new _fee_bump_transaction.FeeBumpTransaction(envelope, networkPassphrase); + } + + /** + * Build a {@link Transaction} or {@link FeeBumpTransaction} from an + * xdr.TransactionEnvelope. + * + * @param {string|xdr.TransactionEnvelope} envelope - The transaction envelope + * object or base64 encoded string. + * @param {string} networkPassphrase - The network passphrase of the target + * Stellar network (e.g. "Public Global Stellar Network ; September + * 2015"), see {@link Networks}. + * + * @returns {Transaction|FeeBumpTransaction} + */ + }, { + key: "fromXDR", + value: function fromXDR(envelope, networkPassphrase) { + if (typeof envelope === 'string') { + envelope = _xdr["default"].TransactionEnvelope.fromXDR(envelope, 'base64'); + } + if (envelope["switch"]() === _xdr["default"].EnvelopeType.envelopeTypeTxFeeBump()) { + return new _fee_bump_transaction.FeeBumpTransaction(envelope, networkPassphrase); + } + return new _transaction.Transaction(envelope, networkPassphrase); + } + }]); +}(); +/** + * Checks whether a provided object is a valid Date. + * @argument {Date} d date object + * @returns {boolean} + */ +function isValidDate(d) { + // isnan is okay here because it correctly checks for invalid date objects + // eslint-disable-next-line no-restricted-globals + return d instanceof Date && !isNaN(d); +} + +/***/ }), + +/***/ 1242: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _bignumber = _interopRequireDefault(__webpack_require__(1594)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var BigNumber = _bignumber["default"].clone(); +BigNumber.DEBUG = true; // gives us exceptions on bad constructor values +var _default = exports["default"] = BigNumber; + +/***/ }), + +/***/ 1346: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.verifyChecksum = verifyChecksum; +function verifyChecksum(expected, actual) { + if (expected.length !== actual.length) { + return false; + } + if (expected.length === 0) { + return true; + } + for (var i = 0; i < expected.length; i += 1) { + if (expected[i] !== actual[i]) { + return false; + } + } + return true; +} + +/***/ }), + +/***/ 4151: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.best_r = best_r; +var _bignumber = _interopRequireDefault(__webpack_require__(1242)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +// eslint-disable-next-line no-bitwise +var MAX_INT = (1 << 31 >>> 0) - 1; + +/** + * Calculates and returns the best rational approximation of the given real number. + * @private + * @param {string|number|BigNumber} rawNumber Real number + * @throws Error Throws `Error` when the best rational approximation cannot be found. + * @returns {array} first element is n (numerator), second element is d (denominator) + */ +function best_r(rawNumber) { + var number = new _bignumber["default"](rawNumber); + var a; + var f; + var fractions = [[new _bignumber["default"](0), new _bignumber["default"](1)], [new _bignumber["default"](1), new _bignumber["default"](0)]]; + var i = 2; + + // eslint-disable-next-line no-constant-condition + while (true) { + if (number.gt(MAX_INT)) { + break; + } + a = number.integerValue(_bignumber["default"].ROUND_FLOOR); + f = number.minus(a); + var h = a.times(fractions[i - 1][0]).plus(fractions[i - 2][0]); + var k = a.times(fractions[i - 1][1]).plus(fractions[i - 2][1]); + if (h.gt(MAX_INT) || k.gt(MAX_INT)) { + break; + } + fractions.push([h, k]); + if (f.eq(0)) { + break; + } + number = new _bignumber["default"](1).div(f); + i += 1; + } + var _fractions = _slicedToArray(fractions[fractions.length - 1], 2), + n = _fractions[0], + d = _fractions[1]; + if (n.isZero() || d.isZero()) { + throw new Error("Couldn't find approximation"); + } + return [n.toNumber(), d.toNumber()]; +} + +/***/ }), + +/***/ 6160: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decodeAddressToMuxedAccount = decodeAddressToMuxedAccount; +exports.encodeMuxedAccount = encodeMuxedAccount; +exports.encodeMuxedAccountToAddress = encodeMuxedAccountToAddress; +exports.extractBaseAddress = extractBaseAddress; +var _xdr = _interopRequireDefault(__webpack_require__(1918)); +var _strkey = __webpack_require__(7120); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/** + * Converts a Stellar address (in G... or M... form) to an `xdr.MuxedAccount` + * structure, using the ed25519 representation when possible. + * + * This supports full muxed accounts, where an `M...` address will resolve to + * both its underlying `G...` address and an integer ID. + * + * @param {string} address G... or M... address to encode into XDR + * @returns {xdr.MuxedAccount} a muxed account object for this address string + */ +function decodeAddressToMuxedAccount(address) { + if (_strkey.StrKey.isValidMed25519PublicKey(address)) { + return _decodeAddressFullyToMuxedAccount(address); + } + return _xdr["default"].MuxedAccount.keyTypeEd25519(_strkey.StrKey.decodeEd25519PublicKey(address)); +} + +/** + * Converts an xdr.MuxedAccount to its StrKey representation. + * + * This returns its "M..." string representation if there is a muxing ID within + * the object and returns the "G..." representation otherwise. + * + * @param {xdr.MuxedAccount} muxedAccount Raw account to stringify + * @returns {string} Stringified G... (corresponding to the underlying pubkey) + * or M... address (corresponding to both the key and the muxed ID) + * + * @see https://stellar.org/protocol/sep-23 + */ +function encodeMuxedAccountToAddress(muxedAccount) { + if (muxedAccount["switch"]().value === _xdr["default"].CryptoKeyType.keyTypeMuxedEd25519().value) { + return _encodeMuxedAccountFullyToAddress(muxedAccount); + } + return _strkey.StrKey.encodeEd25519PublicKey(muxedAccount.ed25519()); +} + +/** + * Transform a Stellar address (G...) and an ID into its XDR representation. + * + * @param {string} address - a Stellar G... address + * @param {string} id - a Uint64 ID represented as a string + * + * @return {xdr.MuxedAccount} - XDR representation of the above muxed account + */ +function encodeMuxedAccount(address, id) { + if (!_strkey.StrKey.isValidEd25519PublicKey(address)) { + throw new Error('address should be a Stellar account ID (G...)'); + } + if (typeof id !== 'string') { + throw new Error('id should be a string representing a number (uint64)'); + } + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromString(id), + ed25519: _strkey.StrKey.decodeEd25519PublicKey(address) + })); +} + +/** + * Extracts the underlying base (G...) address from an M-address. + * @param {string} address an account address (either M... or G...) + * @return {string} a Stellar public key address (G...) + */ +function extractBaseAddress(address) { + if (_strkey.StrKey.isValidEd25519PublicKey(address)) { + return address; + } + if (!_strkey.StrKey.isValidMed25519PublicKey(address)) { + throw new TypeError("expected muxed account (M...), got ".concat(address)); + } + var muxedAccount = decodeAddressToMuxedAccount(address); + return _strkey.StrKey.encodeEd25519PublicKey(muxedAccount.med25519().ed25519()); +} + +// Decodes an "M..." account ID into its MuxedAccount object representation. +function _decodeAddressFullyToMuxedAccount(address) { + var rawBytes = _strkey.StrKey.decodeMed25519PublicKey(address); + + // Decoding M... addresses cannot be done through a simple + // MuxedAccountMed25519.fromXDR() call, because the definition is: + // + // constructor(attributes: { id: Uint64; ed25519: Buffer }); + // + // Note the ID is the first attribute. However, the ID comes *last* in the + // stringified (base32-encoded) address itself (it's the last 8-byte suffix). + // The `fromXDR()` method interprets bytes in order, so we need to parse out + // the raw binary into its requisite parts, i.e. use the MuxedAccountMed25519 + // constructor directly. + // + // Refer to https://github.com/stellar/go/blob/master/xdr/muxed_account.go#L26 + // for the Golang implementation of the M... parsing. + return _xdr["default"].MuxedAccount.keyTypeMuxedEd25519(new _xdr["default"].MuxedAccountMed25519({ + id: _xdr["default"].Uint64.fromXDR(rawBytes.subarray(-8)), + ed25519: rawBytes.subarray(0, -8) + })); +} + +// Converts an xdr.MuxedAccount into its *true* "M..." string representation. +function _encodeMuxedAccountFullyToAddress(muxedAccount) { + if (muxedAccount["switch"]() === _xdr["default"].CryptoKeyType.keyTypeEd25519()) { + return encodeMuxedAccountToAddress(muxedAccount); + } + var muxed = muxedAccount.med25519(); + return _strkey.StrKey.encodeMed25519PublicKey(Buffer.concat([muxed.ed25519(), muxed.id().toXDR('raw')])); +} + +/***/ }), + +/***/ 645: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.trimEnd = void 0; +var trimEnd = exports.trimEnd = function trimEnd(input, _char) { + var isNumber = typeof input === 'number'; + var str = String(input); + while (str.endsWith(_char)) { + str = str.slice(0, -1); + } + return isNumber ? Number(str) : str; +}; + +/***/ }), + +/***/ 1918: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _curr_generated = _interopRequireDefault(__webpack_require__(7938)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +var _default = exports["default"] = _curr_generated["default"]; + +/***/ }), + +/***/ 4940: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +(function(nacl) { +'use strict'; + +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ + +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; + +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; + +var _0 = new Uint8Array(16); +var _9 = new Uint8Array(32); _9[0] = 9; + +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + +function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; +} + +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; +} + +function crypto_verify_16(x, xi, y, yi) { + return vn(x,xi,y,yi,16); +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); +} + +function core_salsa20(o, p, k, c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; + + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + + o[ 4] = x1 >>> 0 & 0xff; + o[ 5] = x1 >>> 8 & 0xff; + o[ 6] = x1 >>> 16 & 0xff; + o[ 7] = x1 >>> 24 & 0xff; + + o[ 8] = x2 >>> 0 & 0xff; + o[ 9] = x2 >>> 8 & 0xff; + o[10] = x2 >>> 16 & 0xff; + o[11] = x2 >>> 24 & 0xff; + + o[12] = x3 >>> 0 & 0xff; + o[13] = x3 >>> 8 & 0xff; + o[14] = x3 >>> 16 & 0xff; + o[15] = x3 >>> 24 & 0xff; + + o[16] = x4 >>> 0 & 0xff; + o[17] = x4 >>> 8 & 0xff; + o[18] = x4 >>> 16 & 0xff; + o[19] = x4 >>> 24 & 0xff; + + o[20] = x5 >>> 0 & 0xff; + o[21] = x5 >>> 8 & 0xff; + o[22] = x5 >>> 16 & 0xff; + o[23] = x5 >>> 24 & 0xff; + + o[24] = x6 >>> 0 & 0xff; + o[25] = x6 >>> 8 & 0xff; + o[26] = x6 >>> 16 & 0xff; + o[27] = x6 >>> 24 & 0xff; + + o[28] = x7 >>> 0 & 0xff; + o[29] = x7 >>> 8 & 0xff; + o[30] = x7 >>> 16 & 0xff; + o[31] = x7 >>> 24 & 0xff; + + o[32] = x8 >>> 0 & 0xff; + o[33] = x8 >>> 8 & 0xff; + o[34] = x8 >>> 16 & 0xff; + o[35] = x8 >>> 24 & 0xff; + + o[36] = x9 >>> 0 & 0xff; + o[37] = x9 >>> 8 & 0xff; + o[38] = x9 >>> 16 & 0xff; + o[39] = x9 >>> 24 & 0xff; + + o[40] = x10 >>> 0 & 0xff; + o[41] = x10 >>> 8 & 0xff; + o[42] = x10 >>> 16 & 0xff; + o[43] = x10 >>> 24 & 0xff; + + o[44] = x11 >>> 0 & 0xff; + o[45] = x11 >>> 8 & 0xff; + o[46] = x11 >>> 16 & 0xff; + o[47] = x11 >>> 24 & 0xff; + + o[48] = x12 >>> 0 & 0xff; + o[49] = x12 >>> 8 & 0xff; + o[50] = x12 >>> 16 & 0xff; + o[51] = x12 >>> 24 & 0xff; + + o[52] = x13 >>> 0 & 0xff; + o[53] = x13 >>> 8 & 0xff; + o[54] = x13 >>> 16 & 0xff; + o[55] = x13 >>> 24 & 0xff; + + o[56] = x14 >>> 0 & 0xff; + o[57] = x14 >>> 8 & 0xff; + o[58] = x14 >>> 16 & 0xff; + o[59] = x14 >>> 24 & 0xff; + + o[60] = x15 >>> 0 & 0xff; + o[61] = x15 >>> 8 & 0xff; + o[62] = x15 >>> 16 & 0xff; + o[63] = x15 >>> 24 & 0xff; +} + +function core_hsalsa20(o,p,k,c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + + o[ 4] = x5 >>> 0 & 0xff; + o[ 5] = x5 >>> 8 & 0xff; + o[ 6] = x5 >>> 16 & 0xff; + o[ 7] = x5 >>> 24 & 0xff; + + o[ 8] = x10 >>> 0 & 0xff; + o[ 9] = x10 >>> 8 & 0xff; + o[10] = x10 >>> 16 & 0xff; + o[11] = x10 >>> 24 & 0xff; + + o[12] = x15 >>> 0 & 0xff; + o[13] = x15 >>> 8 & 0xff; + o[14] = x15 >>> 16 & 0xff; + o[15] = x15 >>> 24 & 0xff; + + o[16] = x6 >>> 0 & 0xff; + o[17] = x6 >>> 8 & 0xff; + o[18] = x6 >>> 16 & 0xff; + o[19] = x6 >>> 24 & 0xff; + + o[20] = x7 >>> 0 & 0xff; + o[21] = x7 >>> 8 & 0xff; + o[22] = x7 >>> 16 & 0xff; + o[23] = x7 >>> 24 & 0xff; + + o[24] = x8 >>> 0 & 0xff; + o[25] = x8 >>> 8 & 0xff; + o[26] = x8 >>> 16 & 0xff; + o[27] = x8 >>> 24 & 0xff; + + o[28] = x9 >>> 0 & 0xff; + o[29] = x9 >>> 8 & 0xff; + o[30] = x9 >>> 16 & 0xff; + o[31] = x9 >>> 24 & 0xff; +} + +function crypto_core_salsa20(out,inp,k,c) { + core_salsa20(out,inp,k,c); +} + +function crypto_core_hsalsa20(out,inp,k,c) { + core_hsalsa20(out,inp,k,c); +} + +var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); + // "expand 32-byte k" + +function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + mpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + } + return 0; +} + +function crypto_stream_salsa20(c,cpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = x[i]; + } + return 0; +} + +function crypto_stream(c,cpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20(c,cpos,d,sn,s); +} + +function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); +} + +/* +* Port of Andrew Moon's Poly1305-donna-16. Public domain. +* https://github.com/floodyberry/poly1305-donna +*/ + +var poly1305 = function(key) { + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.leftover = 0; + this.fin = 0; + + var t0, t1, t2, t3, t4, t5, t6, t7; + + t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; + t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = ((t4 >>> 1)) & 0x1ffe; + t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = ((t7 >>> 5)) & 0x007f; + + this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; + this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; + this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; + this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; + this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; + this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; + this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; + this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; +}; + +poly1305.prototype.blocks = function(m, mpos, bytes) { + var hibit = this.fin ? 0 : (1 << 11); + var t0, t1, t2, t3, t4, t5, t6, t7, c; + var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; + + var h0 = this.h[0], + h1 = this.h[1], + h2 = this.h[2], + h3 = this.h[3], + h4 = this.h[4], + h5 = this.h[5], + h6 = this.h[6], + h7 = this.h[7], + h8 = this.h[8], + h9 = this.h[9]; + + var r0 = this.r[0], + r1 = this.r[1], + r2 = this.r[2], + r3 = this.r[3], + r4 = this.r[4], + r5 = this.r[5], + r6 = this.r[6], + r7 = this.r[7], + r8 = this.r[8], + r9 = this.r[9]; + + while (bytes >= 16) { + t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; + t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; + t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; + h5 += ((t4 >>> 1)) & 0x1fff; + t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; + t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + h9 += ((t7 >>> 5)) | hibit; + + c = 0; + + d0 = c; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h2 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c = (d0 >>> 13); d0 &= 0x1fff; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c += (d0 >>> 13); d0 &= 0x1fff; + + d1 = c; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h2 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c = (d1 >>> 13); d1 &= 0x1fff; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c += (d1 >>> 13); d1 &= 0x1fff; + + d2 = c; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h2 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c = (d2 >>> 13); d2 &= 0x1fff; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c += (d2 >>> 13); d2 &= 0x1fff; + + d3 = c; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h2 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c = (d3 >>> 13); d3 &= 0x1fff; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c += (d3 >>> 13); d3 &= 0x1fff; + + d4 = c; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h2 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c = (d4 >>> 13); d4 &= 0x1fff; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c += (d4 >>> 13); d4 &= 0x1fff; + + d5 = c; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h2 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c = (d5 >>> 13); d5 &= 0x1fff; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c += (d5 >>> 13); d5 &= 0x1fff; + + d6 = c; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h2 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c = (d6 >>> 13); d6 &= 0x1fff; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c += (d6 >>> 13); d6 &= 0x1fff; + + d7 = c; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h2 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c = (d7 >>> 13); d7 &= 0x1fff; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c += (d7 >>> 13); d7 &= 0x1fff; + + d8 = c; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h2 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c = (d8 >>> 13); d8 &= 0x1fff; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c += (d8 >>> 13); d8 &= 0x1fff; + + d9 = c; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h2 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c = (d9 >>> 13); d9 &= 0x1fff; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c += (d9 >>> 13); d9 &= 0x1fff; + + c = (((c << 2) + c)) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = (c >>> 13); + d1 += c; + + h0 = d0; + h1 = d1; + h2 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; + + mpos += 16; + bytes -= 16; + } + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h2; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; +}; + +poly1305.prototype.finish = function(mac, macpos) { + var g = new Uint16Array(10); + var c, mask, f, i; + + if (this.leftover) { + i = this.leftover; + this.buffer[i++] = 1; + for (; i < 16; i++) this.buffer[i] = 0; + this.fin = 1; + this.blocks(this.buffer, 0, 16); + } + + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + for (i = 2; i < 10; i++) { + this.h[i] += c; + c = this.h[i] >>> 13; + this.h[i] &= 0x1fff; + } + this.h[0] += (c * 5); + c = this.h[0] >>> 13; + this.h[0] &= 0x1fff; + this.h[1] += c; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + this.h[2] += c; + + g[0] = this.h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (i = 1; i < 10; i++) { + g[i] = this.h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= (1 << 13); + + mask = (c ^ 1) - 1; + for (i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; + + this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; + this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; + this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; + this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; + this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; + this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; + this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; + this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; + + f = this.h[0] + this.pad[0]; + this.h[0] = f & 0xffff; + for (i = 1; i < 8; i++) { + f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; + this.h[i] = f & 0xffff; + } + + mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; + mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; + mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; + mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; + mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; + mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; + mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; + mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; + mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; + mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; + mac[macpos+10] = (this.h[5] >>> 0) & 0xff; + mac[macpos+11] = (this.h[5] >>> 8) & 0xff; + mac[macpos+12] = (this.h[6] >>> 0) & 0xff; + mac[macpos+13] = (this.h[6] >>> 8) & 0xff; + mac[macpos+14] = (this.h[7] >>> 0) & 0xff; + mac[macpos+15] = (this.h[7] >>> 8) & 0xff; +}; + +poly1305.prototype.update = function(m, mpos, bytes) { + var i, want; + + if (this.leftover) { + want = (16 - this.leftover); + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) + return; + this.blocks(this.buffer, 0, 16); + this.leftover = 0; + } + + if (bytes >= 16) { + want = bytes - (bytes % 16); + this.blocks(m, mpos, want); + mpos += want; + bytes -= want; + } + + if (bytes) { + for (i = 0; i < bytes; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + this.leftover += bytes; + } +}; + +function crypto_onetimeauth(out, outpos, m, mpos, n, k) { + var s = new poly1305(k); + s.update(m, mpos, n); + s.finish(out, outpos); + return 0; +} + +function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { + var x = new Uint8Array(16); + crypto_onetimeauth(x,0,m,mpos,n,k); + return crypto_verify_16(h,hpos,x,0); +} + +function crypto_secretbox(c,m,d,n,k) { + var i; + if (d < 32) return -1; + crypto_stream_xor(c,0,m,0,d,n,k); + crypto_onetimeauth(c, 16, c, 32, d - 32, c); + for (i = 0; i < 16; i++) c[i] = 0; + return 0; +} + +function crypto_secretbox_open(m,c,d,n,k) { + var i; + var x = new Uint8Array(32); + if (d < 32) return -1; + crypto_stream(x,0,32,n,k); + if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; + crypto_stream_xor(m,0,c,0,d,n,k); + for (i = 0; i < 32; i++) m[i] = 0; + return 0; +} + +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} + +function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c-1 + 37 * (c-1); +} + +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; + } +} + +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} + +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; +} + +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} + +function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +} + +function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +} + +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is + + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} + +function S(o, a) { + M(o, a, a); +} + +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; + } + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); + } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; + } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; +} + +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); +} + +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); +} + +function crypto_box_beforenm(k, y, x) { + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y); + return crypto_core_hsalsa20(k, _0, s, sigma); +} + +var crypto_box_afternm = crypto_secretbox; +var crypto_box_open_afternm = crypto_secretbox_open; + +function crypto_box(c, m, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_afternm(c, m, d, n, k); +} + +function crypto_box_open(m, c, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_open_afternm(m, c, d, n, k); +} + +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 +]; + +function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; + + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; + } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; + + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; + + // add + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // K + h = K[i*2]; + l = K[i*2+1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // w + h = wh[i%16]; + l = wl[i%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; + + // add + h = th; + l = tl; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); + + // add + h = bh3; + l = bl3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = th; + l = tl; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); + + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); + } + } + } + + // add + h = ah0; + l = al0; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[0]; + l = hl[0]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); + + h = ah1; + l = al1; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[1]; + l = hl[1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); + + h = ah2; + l = al2; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[2]; + l = hl[2]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); + + h = ah3; + l = al3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[3]; + l = hl[3]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); + + h = ah4; + l = al4; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[4]; + l = hl[4]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); + + h = ah5; + l = al5; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[5]; + l = hl[5]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); + + h = ah6; + l = al6; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[6]; + l = hl[6]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); + + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[7]; + l = hl[7]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); + + pos += 128; + n -= 128; + } + + return n; +} + +function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; + + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; + + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; + + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; + + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; + + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); + + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); + + return 0; +} + +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } +} + +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} + +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } +} + +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} + +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; + + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + scalarbase(p, d); + pack(pk, p); + + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} + +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); + +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = Math.floor((x[j] + 128) / 256); + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} + +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} + +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; + + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); + + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; + } + } + + modL(sm.subarray(32), x); + return smlen; +} + +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + return 0; +} + +function crypto_sign_open(m, sm, n, pk) { + var i; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; + + if (n < 64) return -1; + + if (unpackneg(q, pk)) return -1; + + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); + + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; + } + + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + return n; +} + +var crypto_secretbox_KEYBYTES = 32, + crypto_secretbox_NONCEBYTES = 24, + crypto_secretbox_ZEROBYTES = 32, + crypto_secretbox_BOXZEROBYTES = 16, + crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_box_BEFORENMBYTES = 32, + crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, + crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, + crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32, + crypto_hash_BYTES = 64; + +nacl.lowlevel = { + crypto_core_hsalsa20: crypto_core_hsalsa20, + crypto_stream_xor: crypto_stream_xor, + crypto_stream: crypto_stream, + crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, + crypto_stream_salsa20: crypto_stream_salsa20, + crypto_onetimeauth: crypto_onetimeauth, + crypto_onetimeauth_verify: crypto_onetimeauth_verify, + crypto_verify_16: crypto_verify_16, + crypto_verify_32: crypto_verify_32, + crypto_secretbox: crypto_secretbox, + crypto_secretbox_open: crypto_secretbox_open, + crypto_scalarmult: crypto_scalarmult, + crypto_scalarmult_base: crypto_scalarmult_base, + crypto_box_beforenm: crypto_box_beforenm, + crypto_box_afternm: crypto_box_afternm, + crypto_box: crypto_box, + crypto_box_open: crypto_box_open, + crypto_box_keypair: crypto_box_keypair, + crypto_hash: crypto_hash, + crypto_sign: crypto_sign, + crypto_sign_keypair: crypto_sign_keypair, + crypto_sign_open: crypto_sign_open, + + crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, + crypto_sign_BYTES: crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, + crypto_hash_BYTES: crypto_hash_BYTES, + + gf: gf, + D: D, + L: L, + pack25519: pack25519, + unpack25519: unpack25519, + M: M, + A: A, + S: S, + Z: Z, + pow2523: pow2523, + add: add, + set25519: set25519, + modL: modL, + scalarmult: scalarmult, + scalarbase: scalarbase, +}; + +/* High-level API */ + +function checkLengths(k, n) { + if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); +} + +function checkBoxLengths(pk, sk) { + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); +} + +function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError('unexpected type, use Uint8Array'); + } +} + +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} + +nacl.randomBytes = function(n) { + var b = new Uint8Array(n); + randombytes(b, n); + return b; +}; + +nacl.secretbox = function(msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c = new Uint8Array(m.length); + for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; + crypto_secretbox(c, m, m.length, nonce, key); + return c.subarray(crypto_secretbox_BOXZEROBYTES); +}; + +nacl.secretbox.open = function(box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m = new Uint8Array(c.length); + for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; + if (c.length < 32) return null; + if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null; + return m.subarray(crypto_secretbox_ZEROBYTES); +}; + +nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; +nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; +nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; + +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; + +nacl.scalarMult.base = function(n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; +}; + +nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; +nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; + +nacl.box = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k); +}; + +nacl.box.before = function(publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k, publicKey, secretKey); + return k; +}; + +nacl.box.after = nacl.secretbox; + +nacl.box.open = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k); +}; + +nacl.box.open.after = nacl.secretbox.open; + +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; +nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; +nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; +nacl.box.nonceLength = crypto_box_NONCEBYTES; +nacl.box.overheadLength = nacl.secretbox.overheadLength; + +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; + +nacl.sign.open = function(signedMsg, publicKey) { + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m = new Uint8Array(mlen); + for (var i = 0; i < m.length; i++) m[i] = tmp[i]; + return m; +}; + +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; + +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; + +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; +nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; +nacl.sign.seedLength = crypto_sign_SEEDBYTES; +nacl.sign.signatureLength = crypto_sign_BYTES; + +nacl.hash = function(msg) { + checkArrayTypes(msg); + var h = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h, msg, msg.length); + return h; +}; + +nacl.hash.hashLength = crypto_hash_BYTES; + +nacl.verify = function(x, y) { + checkArrayTypes(x, y); + // Zero length arguments are considered not equal. + if (x.length === 0 || y.length === 0) return false; + if (x.length !== y.length) return false; + return (vn(x, 0, y, 0, x.length) === 0) ? true : false; +}; + +nacl.setPRNG = function(fn) { + randombytes = fn; +}; + +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; + if (crypto && crypto.getRandomValues) { + // Browsers. + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } else if (true) { + // Node.js. + crypto = __webpack_require__(2894); + if (crypto && crypto.randomBytes) { + nacl.setPRNG(function(x, n) { + var i, v = crypto.randomBytes(n); + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } + } +})(); + +})( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); + + +/***/ }), + +/***/ 1924: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ StellarBase: () => (/* reexport module object */ _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2__), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ httpClient: () => (/* reexport safe */ _http_client__WEBPACK_IMPORTED_MODULE_0__.ok) +/* harmony export */ }); +/* harmony import */ var _http_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9983); +/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4356); +/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {}; +/* harmony reexport (unknown) */ for(const __WEBPACK_IMPORT_KEY__ in _index__WEBPACK_IMPORTED_MODULE_1__) if(["default","StellarBase","httpClient"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = () => _index__WEBPACK_IMPORTED_MODULE_1__[__WEBPACK_IMPORT_KEY__] +/* harmony reexport (unknown) */ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_2__); +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (module.exports); + +/***/ }), + +/***/ 8732: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ T: () => (/* binding */ Config) +/* harmony export */ }); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var defaultConfig = { + allowHttp: false, + timeout: 0 +}; +var config = _objectSpread({}, defaultConfig); +var Config = function () { + function Config() { + _classCallCheck(this, Config); + } + return _createClass(Config, null, [{ + key: "setAllowHttp", + value: function setAllowHttp(value) { + config.allowHttp = value; + } + }, { + key: "setTimeout", + value: function setTimeout(value) { + config.timeout = value; + } + }, { + key: "isAllowHttp", + value: function isAllowHttp() { + return config.allowHttp; + } + }, { + key: "getTimeout", + value: function getTimeout() { + return config.timeout; + } + }, { + key: "setDefault", + value: function setDefault() { + config = _objectSpread({}, defaultConfig); + } + }]); +}(); + + +/***/ }), + +/***/ 6299: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + AssembledTransaction: () => (/* reexport */ AssembledTransaction), + Client: () => (/* reexport */ Client), + DEFAULT_TIMEOUT: () => (/* reexport */ DEFAULT_TIMEOUT), + Err: () => (/* reexport */ Err), + NULL_ACCOUNT: () => (/* reexport */ NULL_ACCOUNT), + Ok: () => (/* reexport */ Ok), + SentTransaction: () => (/* reexport */ SentTransaction), + Spec: () => (/* reexport */ Spec), + basicNodeSigner: () => (/* reexport */ basicNodeSigner) +}); + +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./src/rpc/index.ts + 3 modules +var rpc = __webpack_require__(3496); +// EXTERNAL MODULE: ./src/rpc/api.ts +var api = __webpack_require__(4076); +// EXTERNAL MODULE: ./src/rpc/transaction.ts +var transaction = __webpack_require__(8680); +;// ./src/contract/rust_result.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Ok = function () { + function Ok(value) { + _classCallCheck(this, Ok); + this.value = value; + } + return _createClass(Ok, [{ + key: "unwrapErr", + value: function unwrapErr() { + throw new Error("No error"); + } + }, { + key: "unwrap", + value: function unwrap() { + return this.value; + } + }, { + key: "isOk", + value: function isOk() { + return true; + } + }, { + key: "isErr", + value: function isErr() { + return false; + } + }]); +}(); +var Err = function () { + function Err(error) { + _classCallCheck(this, Err); + this.error = error; + } + return _createClass(Err, [{ + key: "unwrapErr", + value: function unwrapErr() { + return this.error; + } + }, { + key: "unwrap", + value: function unwrap() { + throw new Error(this.error.message); + } + }, { + key: "isOk", + value: function isOk() { + return false; + } + }, { + key: "isErr", + value: function isErr() { + return true; + } + }]); +}(); +;// ./src/contract/types.ts + +var DEFAULT_TIMEOUT = 5 * 60; +var NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; +;// ./src/contract/utils.ts +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == utils_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(utils_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function utils_typeof(o) { "@babel/helpers - typeof"; return utils_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, utils_typeof(o); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + + +function withExponentialBackoff(_x, _x2, _x3) { + return _withExponentialBackoff.apply(this, arguments); +} +function _withExponentialBackoff() { + _withExponentialBackoff = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(fn, keepWaitingIf, timeoutInSeconds) { + var exponentialFactor, + verbose, + attempts, + count, + waitUntil, + waitTime, + totalWaitTime, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + exponentialFactor = _args.length > 3 && _args[3] !== undefined ? _args[3] : 1.5; + verbose = _args.length > 4 && _args[4] !== undefined ? _args[4] : false; + attempts = []; + count = 0; + _context.t0 = attempts; + _context.next = 7; + return fn(); + case 7: + _context.t1 = _context.sent; + _context.t0.push.call(_context.t0, _context.t1); + if (keepWaitingIf(attempts[attempts.length - 1])) { + _context.next = 11; + break; + } + return _context.abrupt("return", attempts); + case 11: + waitUntil = new Date(Date.now() + timeoutInSeconds * 1000).valueOf(); + waitTime = 1000; + totalWaitTime = waitTime; + case 14: + if (!(Date.now() < waitUntil && keepWaitingIf(attempts[attempts.length - 1]))) { + _context.next = 30; + break; + } + count += 1; + if (verbose) { + console.info("Waiting ".concat(waitTime, "ms before trying again (bringing the total wait time to ").concat(totalWaitTime, "ms so far, of total ").concat(timeoutInSeconds * 1000, "ms)")); + } + _context.next = 19; + return new Promise(function (res) { + return setTimeout(res, waitTime); + }); + case 19: + waitTime *= exponentialFactor; + if (new Date(Date.now() + waitTime).valueOf() > waitUntil) { + waitTime = waitUntil - Date.now(); + if (verbose) { + console.info("was gonna wait too long; new waitTime: ".concat(waitTime, "ms")); + } + } + totalWaitTime = waitTime + totalWaitTime; + _context.t2 = attempts; + _context.next = 25; + return fn(attempts[attempts.length - 1]); + case 25: + _context.t3 = _context.sent; + _context.t2.push.call(_context.t2, _context.t3); + if (verbose && keepWaitingIf(attempts[attempts.length - 1])) { + console.info("".concat(count, ". Called ").concat(fn, "; ").concat(attempts.length, " prev attempts. Most recent: ").concat(JSON.stringify(attempts[attempts.length - 1], null, 2))); + } + _context.next = 14; + break; + case 30: + return _context.abrupt("return", attempts); + case 31: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _withExponentialBackoff.apply(this, arguments); +} +var contractErrorPattern = /Error\(Contract, #(\d+)\)/; +function implementsToString(obj) { + return utils_typeof(obj) === "object" && obj !== null && "toString" in obj; +} +function processSpecEntryStream(buffer) { + var reader = new lib.cereal.XdrReader(buffer); + var res = []; + while (!reader.eof) { + res.push(lib.xdr.ScSpecEntry.read(reader)); + } + return res; +} +function getAccount(_x4, _x5) { + return _getAccount.apply(this, arguments); +} +function _getAccount() { + _getAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(options, server) { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", options.publicKey ? server.getAccount(options.publicKey) : new lib.Account(NULL_ACCOUNT, "0")); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _getAccount.apply(this, arguments); +} +;// ./src/contract/sent_transaction.ts +var _SentTransaction; +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == sent_transaction_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function sent_transaction_typeof(o) { "@babel/helpers - typeof"; return sent_transaction_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, sent_transaction_typeof(o); } +function sent_transaction_regeneratorRuntime() { "use strict"; sent_transaction_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == sent_transaction_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(sent_transaction_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function sent_transaction_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function sent_transaction_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { sent_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { sent_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function sent_transaction_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function sent_transaction_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, sent_transaction_toPropertyKey(o.key), o); } } +function sent_transaction_createClass(e, r, t) { return r && sent_transaction_defineProperties(e.prototype, r), t && sent_transaction_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = sent_transaction_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function sent_transaction_toPropertyKey(t) { var i = sent_transaction_toPrimitive(t, "string"); return "symbol" == sent_transaction_typeof(i) ? i : i + ""; } +function sent_transaction_toPrimitive(t, r) { if ("object" != sent_transaction_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != sent_transaction_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + +var SentTransaction = function () { + function SentTransaction(assembled) { + var _this = this, + _this$assembled$optio2; + sent_transaction_classCallCheck(this, SentTransaction); + _defineProperty(this, "send", sent_transaction_asyncToGenerator(sent_transaction_regeneratorRuntime().mark(function _callee() { + var _this$assembled$optio; + var hash, timeoutInSeconds; + return sent_transaction_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return _this.server.sendTransaction(_this.assembled.signed); + case 2: + _this.sendTransactionResponse = _context.sent; + if (!(_this.sendTransactionResponse.status !== "PENDING")) { + _context.next = 5; + break; + } + throw new SentTransaction.Errors.SendFailed("Sending the transaction to the network failed!\n".concat(JSON.stringify(_this.sendTransactionResponse, null, 2))); + case 5: + hash = _this.sendTransactionResponse.hash; + timeoutInSeconds = (_this$assembled$optio = _this.assembled.options.timeoutInSeconds) !== null && _this$assembled$optio !== void 0 ? _this$assembled$optio : DEFAULT_TIMEOUT; + _context.next = 9; + return withExponentialBackoff(function () { + return _this.server.getTransaction(hash); + }, function (resp) { + return resp.status === api/* Api */.j.GetTransactionStatus.NOT_FOUND; + }, timeoutInSeconds); + case 9: + _this.getTransactionResponseAll = _context.sent; + _this.getTransactionResponse = _this.getTransactionResponseAll[_this.getTransactionResponseAll.length - 1]; + if (!(_this.getTransactionResponse.status === api/* Api */.j.GetTransactionStatus.NOT_FOUND)) { + _context.next = 13; + break; + } + throw new SentTransaction.Errors.TransactionStillPending("Waited ".concat(timeoutInSeconds, " seconds for transaction to complete, but it did not. ") + "Returning anyway. Check the transaction status manually. " + "Sent transaction: ".concat(JSON.stringify(_this.sendTransactionResponse, null, 2), "\n") + "All attempts to get the result: ".concat(JSON.stringify(_this.getTransactionResponseAll, null, 2))); + case 13: + return _context.abrupt("return", _this); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + }))); + this.assembled = assembled; + this.server = new rpc.Server(this.assembled.options.rpcUrl, { + allowHttp: (_this$assembled$optio2 = this.assembled.options.allowHttp) !== null && _this$assembled$optio2 !== void 0 ? _this$assembled$optio2 : false + }); + } + return sent_transaction_createClass(SentTransaction, [{ + key: "result", + get: function get() { + if ("getTransactionResponse" in this && this.getTransactionResponse) { + if ("returnValue" in this.getTransactionResponse) { + return this.assembled.options.parseResultXdr(this.getTransactionResponse.returnValue); + } + throw new Error("Transaction failed! Cannot parse result."); + } + if (this.sendTransactionResponse) { + var _this$sendTransaction; + var errorResult = (_this$sendTransaction = this.sendTransactionResponse.errorResult) === null || _this$sendTransaction === void 0 ? void 0 : _this$sendTransaction.result(); + if (errorResult) { + throw new SentTransaction.Errors.SendFailed("Transaction simulation looked correct, but attempting to send the transaction failed. Check `simulation` and `sendTransactionResponseAll` to troubleshoot. Decoded `sendTransactionResponse.errorResultXdr`: ".concat(errorResult)); + } + throw new SentTransaction.Errors.SendResultOnly("Transaction was sent to the network, but not yet awaited. No result to show. Await transaction completion with `getTransaction(sendTransactionResponse.hash)`"); + } + throw new Error("Sending transaction failed: ".concat(JSON.stringify(this.assembled.signed))); + } + }]); +}(); +_SentTransaction = SentTransaction; +_defineProperty(SentTransaction, "Errors", { + SendFailed: function (_Error) { + function SendFailedError() { + sent_transaction_classCallCheck(this, SendFailedError); + return _callSuper(this, SendFailedError, arguments); + } + _inherits(SendFailedError, _Error); + return sent_transaction_createClass(SendFailedError); + }(_wrapNativeSuper(Error)), + SendResultOnly: function (_Error2) { + function SendResultOnlyError() { + sent_transaction_classCallCheck(this, SendResultOnlyError); + return _callSuper(this, SendResultOnlyError, arguments); + } + _inherits(SendResultOnlyError, _Error2); + return sent_transaction_createClass(SendResultOnlyError); + }(_wrapNativeSuper(Error)), + TransactionStillPending: function (_Error3) { + function TransactionStillPendingError() { + sent_transaction_classCallCheck(this, TransactionStillPendingError); + return _callSuper(this, TransactionStillPendingError, arguments); + } + _inherits(TransactionStillPendingError, _Error3); + return sent_transaction_createClass(TransactionStillPendingError); + }(_wrapNativeSuper(Error)) +}); +_defineProperty(SentTransaction, "init", function () { + var _ref2 = sent_transaction_asyncToGenerator(sent_transaction_regeneratorRuntime().mark(function _callee2(assembled) { + var tx, sent; + return sent_transaction_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + tx = new _SentTransaction(assembled); + _context2.next = 3; + return tx.send(); + case 3: + sent = _context2.sent; + return _context2.abrupt("return", sent); + case 5: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; +}()); +;// ./src/contract/assembled_transaction.ts +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +function assembled_transaction_callSuper(t, o, e) { return o = assembled_transaction_getPrototypeOf(o), assembled_transaction_possibleConstructorReturn(t, assembled_transaction_isNativeReflectConstruct() ? Reflect.construct(o, e || [], assembled_transaction_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function assembled_transaction_possibleConstructorReturn(t, e) { if (e && ("object" == assembled_transaction_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return assembled_transaction_assertThisInitialized(t); } +function assembled_transaction_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function assembled_transaction_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && assembled_transaction_setPrototypeOf(t, e); } +function assembled_transaction_wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return assembled_transaction_wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !assembled_transaction_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return assembled_transaction_construct(t, arguments, assembled_transaction_getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), assembled_transaction_setPrototypeOf(Wrapper, t); }, assembled_transaction_wrapNativeSuper(t); } +function assembled_transaction_construct(t, e, r) { if (assembled_transaction_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && assembled_transaction_setPrototypeOf(p, r.prototype), p; } +function assembled_transaction_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (assembled_transaction_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function assembled_transaction_isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function assembled_transaction_setPrototypeOf(t, e) { return assembled_transaction_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, assembled_transaction_setPrototypeOf(t, e); } +function assembled_transaction_getPrototypeOf(t) { return assembled_transaction_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, assembled_transaction_getPrototypeOf(t); } +function assembled_transaction_typeof(o) { "@babel/helpers - typeof"; return assembled_transaction_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, assembled_transaction_typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { assembled_transaction_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function assembled_transaction_regeneratorRuntime() { "use strict"; assembled_transaction_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == assembled_transaction_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(assembled_transaction_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function assembled_transaction_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function assembled_transaction_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { assembled_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { assembled_transaction_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function assembled_transaction_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function assembled_transaction_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, assembled_transaction_toPropertyKey(o.key), o); } } +function assembled_transaction_createClass(e, r, t) { return r && assembled_transaction_defineProperties(e.prototype, r), t && assembled_transaction_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function assembled_transaction_defineProperty(e, r, t) { return (r = assembled_transaction_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function assembled_transaction_toPropertyKey(t) { var i = assembled_transaction_toPrimitive(t, "string"); return "symbol" == assembled_transaction_typeof(i) ? i : i + ""; } +function assembled_transaction_toPrimitive(t, r) { if ("object" != assembled_transaction_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != assembled_transaction_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + + + +var AssembledTransaction = function () { + function AssembledTransaction(options) { + var _this = this, + _this$options$simulat, + _this$options$allowHt; + assembled_transaction_classCallCheck(this, AssembledTransaction); + assembled_transaction_defineProperty(this, "simulate", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee() { + var _restore; + var _ref2, + restore, + account, + result, + _this$options$fee, + _this$options$args, + _this$options$timeout, + contract, + _args = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _ref2 = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, restore = _ref2.restore; + if (_this.built) { + _context.next = 5; + break; + } + if (_this.raw) { + _context.next = 4; + break; + } + throw new Error("Transaction has not yet been assembled; " + "call `AssembledTransaction.build` first."); + case 4: + _this.built = _this.raw.build(); + case 5: + restore = (_restore = restore) !== null && _restore !== void 0 ? _restore : _this.options.restore; + delete _this.simulationResult; + delete _this.simulationTransactionData; + _context.next = 10; + return _this.server.simulateTransaction(_this.built); + case 10: + _this.simulation = _context.sent; + if (!(restore && api/* Api */.j.isSimulationRestore(_this.simulation))) { + _context.next = 25; + break; + } + _context.next = 14; + return getAccount(_this.options, _this.server); + case 14: + account = _context.sent; + _context.next = 17; + return _this.restoreFootprint(_this.simulation.restorePreamble, account); + case 17: + result = _context.sent; + if (!(result.status === api/* Api */.j.GetTransactionStatus.SUCCESS)) { + _context.next = 24; + break; + } + contract = new lib.Contract(_this.options.contractId); + _this.raw = new lib.TransactionBuilder(account, { + fee: (_this$options$fee = _this.options.fee) !== null && _this$options$fee !== void 0 ? _this$options$fee : lib.BASE_FEE, + networkPassphrase: _this.options.networkPassphrase + }).addOperation(contract.call.apply(contract, [_this.options.method].concat(_toConsumableArray((_this$options$args = _this.options.args) !== null && _this$options$args !== void 0 ? _this$options$args : [])))).setTimeout((_this$options$timeout = _this.options.timeoutInSeconds) !== null && _this$options$timeout !== void 0 ? _this$options$timeout : DEFAULT_TIMEOUT); + _context.next = 23; + return _this.simulate(); + case 23: + return _context.abrupt("return", _this); + case 24: + throw new AssembledTransaction.Errors.RestorationFailure("Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n".concat(JSON.stringify(result))); + case 25: + if (api/* Api */.j.isSimulationSuccess(_this.simulation)) { + _this.built = (0,transaction/* assembleTransaction */.X)(_this.built, _this.simulation).build(); + } + return _context.abrupt("return", _this); + case 27: + case "end": + return _context.stop(); + } + }, _callee); + }))); + assembled_transaction_defineProperty(this, "sign", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee2() { + var _this$options$timeout2; + var _ref4, + _ref4$force, + force, + _ref4$signTransaction, + signTransaction, + sigsNeeded, + timeoutInSeconds, + signOpts, + _yield$signTransactio, + signature, + error, + _args2 = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _ref4 = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref4$force = _ref4.force, force = _ref4$force === void 0 ? false : _ref4$force, _ref4$signTransaction = _ref4.signTransaction, signTransaction = _ref4$signTransaction === void 0 ? _this.options.signTransaction : _ref4$signTransaction; + if (_this.built) { + _context2.next = 3; + break; + } + throw new Error("Transaction has not yet been simulated"); + case 3: + if (!(!force && _this.isReadCall)) { + _context2.next = 5; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("This is a read call. It requires no signature or sending. " + "Use `force: true` to sign and send anyway."); + case 5: + if (signTransaction) { + _context2.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide a signTransaction function, either when calling " + "`signAndSend` or when initializing your Client"); + case 7: + sigsNeeded = _this.needsNonInvokerSigningBy().filter(function (id) { + return !id.startsWith('C'); + }); + if (!sigsNeeded.length) { + _context2.next = 10; + break; + } + throw new AssembledTransaction.Errors.NeedsMoreSignatures("Transaction requires signatures from ".concat(sigsNeeded, ". ") + "See `needsNonInvokerSigningBy` for details."); + case 10: + timeoutInSeconds = (_this$options$timeout2 = _this.options.timeoutInSeconds) !== null && _this$options$timeout2 !== void 0 ? _this$options$timeout2 : DEFAULT_TIMEOUT; + _this.built = lib.TransactionBuilder.cloneFrom(_this.built, { + fee: _this.built.fee, + timebounds: undefined, + sorobanData: _this.simulationData.transactionData + }).setTimeout(timeoutInSeconds).build(); + signOpts = { + networkPassphrase: _this.options.networkPassphrase + }; + if (_this.options.address) signOpts.address = _this.options.address; + if (_this.options.submit !== undefined) signOpts.submit = _this.options.submit; + if (_this.options.submitUrl) signOpts.submitUrl = _this.options.submitUrl; + _context2.next = 18; + return signTransaction(_this.built.toXDR(), signOpts); + case 18: + _yield$signTransactio = _context2.sent; + signature = _yield$signTransactio.signedTxXdr; + error = _yield$signTransactio.error; + _this.handleWalletError(error); + _this.signed = lib.TransactionBuilder.fromXDR(signature, _this.options.networkPassphrase); + case 23: + case "end": + return _context2.stop(); + } + }, _callee2); + }))); + assembled_transaction_defineProperty(this, "signAndSend", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee3() { + var _ref6, + _ref6$force, + force, + _ref6$signTransaction, + signTransaction, + originalSubmit, + _args3 = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _ref6 = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : {}, _ref6$force = _ref6.force, force = _ref6$force === void 0 ? false : _ref6$force, _ref6$signTransaction = _ref6.signTransaction, signTransaction = _ref6$signTransaction === void 0 ? _this.options.signTransaction : _ref6$signTransaction; + if (_this.signed) { + _context3.next = 10; + break; + } + originalSubmit = _this.options.submit; + if (_this.options.submit) { + _this.options.submit = false; + } + _context3.prev = 4; + _context3.next = 7; + return _this.sign({ + force: force, + signTransaction: signTransaction + }); + case 7: + _context3.prev = 7; + _this.options.submit = originalSubmit; + return _context3.finish(7); + case 10: + return _context3.abrupt("return", _this.send()); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3, null, [[4,, 7, 10]]); + }))); + assembled_transaction_defineProperty(this, "needsNonInvokerSigningBy", function () { + var _rawInvokeHostFunctio; + var _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref7$includeAlreadyS = _ref7.includeAlreadySigned, + includeAlreadySigned = _ref7$includeAlreadyS === void 0 ? false : _ref7$includeAlreadyS; + if (!_this.built) { + throw new Error("Transaction has not yet been simulated"); + } + if (!("operations" in _this.built)) { + throw new Error("Unexpected Transaction type; no operations: ".concat(JSON.stringify(_this.built))); + } + var rawInvokeHostFunctionOp = _this.built.operations[0]; + return _toConsumableArray(new Set(((_rawInvokeHostFunctio = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio !== void 0 ? _rawInvokeHostFunctio : []).filter(function (entry) { + return entry.credentials().switch() === lib.xdr.SorobanCredentialsType.sorobanCredentialsAddress() && (includeAlreadySigned || entry.credentials().address().signature().switch().name === "scvVoid"); + }).map(function (entry) { + return lib.Address.fromScAddress(entry.credentials().address().address()).toString(); + }))); + }); + assembled_transaction_defineProperty(this, "signAuthEntries", assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee6() { + var _rawInvokeHostFunctio2; + var _ref9, + _ref9$expiration, + expiration, + _ref9$signAuthEntry, + signAuthEntry, + _ref9$address, + address, + _ref9$authorizeEntry, + authorizeEntry, + needsNonInvokerSigningBy, + rawInvokeHostFunctionOp, + authEntries, + _iterator, + _step, + _loop, + _ret, + _args7 = arguments; + return assembled_transaction_regeneratorRuntime().wrap(function _callee6$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _ref9 = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {}, _ref9$expiration = _ref9.expiration, expiration = _ref9$expiration === void 0 ? assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee4() { + return assembled_transaction_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this.server.getLatestLedger(); + case 2: + _context4.t0 = _context4.sent.sequence; + return _context4.abrupt("return", _context4.t0 + 100); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + }))() : _ref9$expiration, _ref9$signAuthEntry = _ref9.signAuthEntry, signAuthEntry = _ref9$signAuthEntry === void 0 ? _this.options.signAuthEntry : _ref9$signAuthEntry, _ref9$address = _ref9.address, address = _ref9$address === void 0 ? _this.options.publicKey : _ref9$address, _ref9$authorizeEntry = _ref9.authorizeEntry, authorizeEntry = _ref9$authorizeEntry === void 0 ? lib.authorizeEntry : _ref9$authorizeEntry; + if (_this.built) { + _context7.next = 3; + break; + } + throw new Error("Transaction has not yet been assembled or simulated"); + case 3: + if (!(authorizeEntry === lib.authorizeEntry)) { + _context7.next = 11; + break; + } + needsNonInvokerSigningBy = _this.needsNonInvokerSigningBy(); + if (!(needsNonInvokerSigningBy.length === 0)) { + _context7.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?"); + case 7: + if (!(needsNonInvokerSigningBy.indexOf(address !== null && address !== void 0 ? address : "") === -1)) { + _context7.next = 9; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("No auth entries for public key \"".concat(address, "\"")); + case 9: + if (signAuthEntry) { + _context7.next = 11; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`"); + case 11: + rawInvokeHostFunctionOp = _this.built.operations[0]; + authEntries = (_rawInvokeHostFunctio2 = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio2 !== void 0 ? _rawInvokeHostFunctio2 : []; + _iterator = _createForOfIteratorHelper(authEntries.entries()); + _context7.prev = 14; + _loop = assembled_transaction_regeneratorRuntime().mark(function _loop() { + var _step$value, i, entry, credentials, authEntryAddress, sign; + return assembled_transaction_regeneratorRuntime().wrap(function _loop$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _step$value = _slicedToArray(_step.value, 2), i = _step$value[0], entry = _step$value[1]; + credentials = lib.xdr.SorobanCredentials.fromXDR(entry.credentials().toXDR()); + if (!(credentials.switch() !== lib.xdr.SorobanCredentialsType.sorobanCredentialsAddress())) { + _context6.next = 4; + break; + } + return _context6.abrupt("return", 0); + case 4: + authEntryAddress = lib.Address.fromScAddress(credentials.address().address()).toString(); + if (!(authEntryAddress !== address)) { + _context6.next = 7; + break; + } + return _context6.abrupt("return", 0); + case 7: + sign = signAuthEntry !== null && signAuthEntry !== void 0 ? signAuthEntry : Promise.resolve; + _context6.t0 = authorizeEntry; + _context6.t1 = entry; + _context6.t2 = function () { + var _ref11 = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee5(preimage) { + var _yield$sign, signedAuthEntry, error; + return assembled_transaction_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return sign(preimage.toXDR("base64"), { + address: address + }); + case 2: + _yield$sign = _context5.sent; + signedAuthEntry = _yield$sign.signedAuthEntry; + error = _yield$sign.error; + _this.handleWalletError(error); + return _context5.abrupt("return", Buffer.from(signedAuthEntry, "base64")); + case 7: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x) { + return _ref11.apply(this, arguments); + }; + }(); + _context6.next = 13; + return expiration; + case 13: + _context6.t3 = _context6.sent; + _context6.t4 = _this.options.networkPassphrase; + _context6.next = 17; + return (0, _context6.t0)(_context6.t1, _context6.t2, _context6.t3, _context6.t4); + case 17: + authEntries[i] = _context6.sent; + case 18: + case "end": + return _context6.stop(); + } + }, _loop); + }); + _iterator.s(); + case 17: + if ((_step = _iterator.n()).done) { + _context7.next = 24; + break; + } + return _context7.delegateYield(_loop(), "t0", 19); + case 19: + _ret = _context7.t0; + if (!(_ret === 0)) { + _context7.next = 22; + break; + } + return _context7.abrupt("continue", 22); + case 22: + _context7.next = 17; + break; + case 24: + _context7.next = 29; + break; + case 26: + _context7.prev = 26; + _context7.t1 = _context7["catch"](14); + _iterator.e(_context7.t1); + case 29: + _context7.prev = 29; + _iterator.f(); + return _context7.finish(29); + case 32: + case "end": + return _context7.stop(); + } + }, _callee6, null, [[14, 26, 29, 32]]); + }))); + this.options = options; + this.options.simulate = (_this$options$simulat = this.options.simulate) !== null && _this$options$simulat !== void 0 ? _this$options$simulat : true; + this.server = new rpc.Server(this.options.rpcUrl, { + allowHttp: (_this$options$allowHt = this.options.allowHttp) !== null && _this$options$allowHt !== void 0 ? _this$options$allowHt : false + }); + } + return assembled_transaction_createClass(AssembledTransaction, [{ + key: "toJSON", + value: function toJSON() { + var _this$built; + return JSON.stringify({ + method: this.options.method, + tx: (_this$built = this.built) === null || _this$built === void 0 ? void 0 : _this$built.toXDR(), + simulationResult: { + auth: this.simulationData.result.auth.map(function (a) { + return a.toXDR("base64"); + }), + retval: this.simulationData.result.retval.toXDR("base64") + }, + simulationTransactionData: this.simulationData.transactionData.toXDR("base64") + }); + } + }, { + key: "toXDR", + value: function toXDR() { + var _this$built2; + if (!this.built) throw new Error("Transaction has not yet been simulated; " + "call `AssembledTransaction.simulate` first."); + return (_this$built2 = this.built) === null || _this$built2 === void 0 ? void 0 : _this$built2.toEnvelope().toXDR('base64'); + } + }, { + key: "handleWalletError", + value: function handleWalletError(error) { + if (!error) return; + var message = error.message, + code = error.code; + var fullMessage = "".concat(message).concat(error.ext ? " (".concat(error.ext.join(', '), ")") : ''); + switch (code) { + case -1: + throw new AssembledTransaction.Errors.InternalWalletError(fullMessage); + case -2: + throw new AssembledTransaction.Errors.ExternalServiceError(fullMessage); + case -3: + throw new AssembledTransaction.Errors.InvalidClientRequest(fullMessage); + case -4: + throw new AssembledTransaction.Errors.UserRejected(fullMessage); + default: + throw new Error("Unhandled error: ".concat(fullMessage)); + } + } + }, { + key: "simulationData", + get: function get() { + var _simulation$result; + if (this.simulationResult && this.simulationTransactionData) { + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + var simulation = this.simulation; + if (!simulation) { + throw new AssembledTransaction.Errors.NotYetSimulated("Transaction has not yet been simulated"); + } + if (api/* Api */.j.isSimulationError(simulation)) { + throw new AssembledTransaction.Errors.SimulationFailed("Transaction simulation failed: \"".concat(simulation.error, "\"")); + } + if (api/* Api */.j.isSimulationRestore(simulation)) { + throw new AssembledTransaction.Errors.ExpiredState("You need to restore some contract state before you can invoke this method.\n" + 'You can set `restore` to true in the method options in order to ' + 'automatically restore the contract state when needed.'); + } + this.simulationResult = (_simulation$result = simulation.result) !== null && _simulation$result !== void 0 ? _simulation$result : { + auth: [], + retval: lib.xdr.ScVal.scvVoid() + }; + this.simulationTransactionData = simulation.transactionData.build(); + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + }, { + key: "result", + get: function get() { + try { + if (!this.simulationData.result) { + throw new Error("No simulation result!"); + } + return this.options.parseResultXdr(this.simulationData.result.retval); + } catch (e) { + if (!implementsToString(e)) throw e; + var err = this.parseError(e.toString()); + if (err) return err; + throw e; + } + } + }, { + key: "parseError", + value: function parseError(errorMessage) { + if (!this.options.errorTypes) return undefined; + var match = errorMessage.match(contractErrorPattern); + if (!match) return undefined; + var i = parseInt(match[1], 10); + var err = this.options.errorTypes[i]; + if (!err) return undefined; + return new Err(err); + } + }, { + key: "send", + value: (function () { + var _send = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee7() { + var sent; + return assembled_transaction_regeneratorRuntime().wrap(function _callee7$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (this.signed) { + _context8.next = 2; + break; + } + throw new Error("The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead."); + case 2: + _context8.next = 4; + return SentTransaction.init(this); + case 4: + sent = _context8.sent; + return _context8.abrupt("return", sent); + case 6: + case "end": + return _context8.stop(); + } + }, _callee7, this); + })); + function send() { + return _send.apply(this, arguments); + } + return send; + }()) + }, { + key: "isReadCall", + get: function get() { + var authsCount = this.simulationData.result.auth.length; + var writeLength = this.simulationData.transactionData.resources().footprint().readWrite().length; + return authsCount === 0 && writeLength === 0; + } + }, { + key: "restoreFootprint", + value: (function () { + var _restoreFootprint = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee8(restorePreamble, account) { + var _account; + var restoreTx, sentTransaction; + return assembled_transaction_regeneratorRuntime().wrap(function _callee8$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + if (this.options.signTransaction) { + _context9.next = 2; + break; + } + throw new Error("For automatic restore to work you must provide a signTransaction function when initializing your Client"); + case 2: + if (!((_account = account) !== null && _account !== void 0)) { + _context9.next = 6; + break; + } + _context9.t0 = _account; + _context9.next = 9; + break; + case 6: + _context9.next = 8; + return getAccount(this.options, this.server); + case 8: + _context9.t0 = _context9.sent; + case 9: + account = _context9.t0; + _context9.next = 12; + return AssembledTransaction.buildFootprintRestoreTransaction(_objectSpread({}, this.options), restorePreamble.transactionData, account, restorePreamble.minResourceFee); + case 12: + restoreTx = _context9.sent; + _context9.next = 15; + return restoreTx.signAndSend(); + case 15: + sentTransaction = _context9.sent; + if (sentTransaction.getTransactionResponse) { + _context9.next = 18; + break; + } + throw new AssembledTransaction.Errors.RestorationFailure("The attempt at automatic restore failed. \n".concat(JSON.stringify(sentTransaction))); + case 18: + return _context9.abrupt("return", sentTransaction.getTransactionResponse); + case 19: + case "end": + return _context9.stop(); + } + }, _callee8, this); + })); + function restoreFootprint(_x2, _x3) { + return _restoreFootprint.apply(this, arguments); + } + return restoreFootprint; + }()) + }], [{ + key: "fromJSON", + value: function fromJSON(options, _ref12) { + var tx = _ref12.tx, + simulationResult = _ref12.simulationResult, + simulationTransactionData = _ref12.simulationTransactionData; + var txn = new AssembledTransaction(options); + txn.built = lib.TransactionBuilder.fromXDR(tx, options.networkPassphrase); + txn.simulationResult = { + auth: simulationResult.auth.map(function (a) { + return lib.xdr.SorobanAuthorizationEntry.fromXDR(a, "base64"); + }), + retval: lib.xdr.ScVal.fromXDR(simulationResult.retval, "base64") + }; + txn.simulationTransactionData = lib.xdr.SorobanTransactionData.fromXDR(simulationTransactionData, "base64"); + return txn; + } + }, { + key: "fromXDR", + value: function fromXDR(options, encodedXDR, spec) { + var _operation$func; + var envelope = lib.xdr.TransactionEnvelope.fromXDR(encodedXDR, "base64"); + var built = lib.TransactionBuilder.fromXDR(envelope, options.networkPassphrase); + var operation = built.operations[0]; + if (!(operation !== null && operation !== void 0 && (_operation$func = operation.func) !== null && _operation$func !== void 0 && _operation$func.value) || typeof operation.func.value !== 'function') { + throw new Error("Could not extract the method from the transaction envelope."); + } + var invokeContractArgs = operation.func.value(); + if (!(invokeContractArgs !== null && invokeContractArgs !== void 0 && invokeContractArgs.functionName)) { + throw new Error("Could not extract the method name from the transaction envelope."); + } + var method = invokeContractArgs.functionName().toString('utf-8'); + var txn = new AssembledTransaction(_objectSpread(_objectSpread({}, options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + txn.built = built; + return txn; + } + }, { + key: "build", + value: function build(options) { + var _options$args; + var contract = new lib.Contract(options.contractId); + return AssembledTransaction.buildWithOp(contract.call.apply(contract, [options.method].concat(_toConsumableArray((_options$args = options.args) !== null && _options$args !== void 0 ? _options$args : []))), options); + } + }, { + key: "buildWithOp", + value: (function () { + var _buildWithOp = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee9(operation, options) { + var _options$fee, _options$timeoutInSec; + var tx, account; + return assembled_transaction_regeneratorRuntime().wrap(function _callee9$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + tx = new AssembledTransaction(options); + _context10.next = 3; + return getAccount(options, tx.server); + case 3: + account = _context10.sent; + tx.raw = new lib.TransactionBuilder(account, { + fee: (_options$fee = options.fee) !== null && _options$fee !== void 0 ? _options$fee : lib.BASE_FEE, + networkPassphrase: options.networkPassphrase + }).setTimeout((_options$timeoutInSec = options.timeoutInSeconds) !== null && _options$timeoutInSec !== void 0 ? _options$timeoutInSec : DEFAULT_TIMEOUT).addOperation(operation); + if (!options.simulate) { + _context10.next = 8; + break; + } + _context10.next = 8; + return tx.simulate(); + case 8: + return _context10.abrupt("return", tx); + case 9: + case "end": + return _context10.stop(); + } + }, _callee9); + })); + function buildWithOp(_x4, _x5) { + return _buildWithOp.apply(this, arguments); + } + return buildWithOp; + }()) + }, { + key: "buildFootprintRestoreTransaction", + value: function () { + var _buildFootprintRestoreTransaction = assembled_transaction_asyncToGenerator(assembled_transaction_regeneratorRuntime().mark(function _callee10(options, sorobanData, account, fee) { + var _options$timeoutInSec2; + var tx; + return assembled_transaction_regeneratorRuntime().wrap(function _callee10$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + tx = new AssembledTransaction(options); + tx.raw = new lib.TransactionBuilder(account, { + fee: fee, + networkPassphrase: options.networkPassphrase + }).setSorobanData(sorobanData instanceof lib.SorobanDataBuilder ? sorobanData.build() : sorobanData).addOperation(lib.Operation.restoreFootprint({})).setTimeout((_options$timeoutInSec2 = options.timeoutInSeconds) !== null && _options$timeoutInSec2 !== void 0 ? _options$timeoutInSec2 : DEFAULT_TIMEOUT); + _context11.next = 4; + return tx.simulate({ + restore: false + }); + case 4: + return _context11.abrupt("return", tx); + case 5: + case "end": + return _context11.stop(); + } + }, _callee10); + })); + function buildFootprintRestoreTransaction(_x6, _x7, _x8, _x9) { + return _buildFootprintRestoreTransaction.apply(this, arguments); + } + return buildFootprintRestoreTransaction; + }() + }]); +}(); +assembled_transaction_defineProperty(AssembledTransaction, "Errors", { + ExpiredState: function (_Error) { + function ExpiredStateError() { + assembled_transaction_classCallCheck(this, ExpiredStateError); + return assembled_transaction_callSuper(this, ExpiredStateError, arguments); + } + assembled_transaction_inherits(ExpiredStateError, _Error); + return assembled_transaction_createClass(ExpiredStateError); + }(assembled_transaction_wrapNativeSuper(Error)), + RestorationFailure: function (_Error2) { + function RestoreFailureError() { + assembled_transaction_classCallCheck(this, RestoreFailureError); + return assembled_transaction_callSuper(this, RestoreFailureError, arguments); + } + assembled_transaction_inherits(RestoreFailureError, _Error2); + return assembled_transaction_createClass(RestoreFailureError); + }(assembled_transaction_wrapNativeSuper(Error)), + NeedsMoreSignatures: function (_Error3) { + function NeedsMoreSignaturesError() { + assembled_transaction_classCallCheck(this, NeedsMoreSignaturesError); + return assembled_transaction_callSuper(this, NeedsMoreSignaturesError, arguments); + } + assembled_transaction_inherits(NeedsMoreSignaturesError, _Error3); + return assembled_transaction_createClass(NeedsMoreSignaturesError); + }(assembled_transaction_wrapNativeSuper(Error)), + NoSignatureNeeded: function (_Error4) { + function NoSignatureNeededError() { + assembled_transaction_classCallCheck(this, NoSignatureNeededError); + return assembled_transaction_callSuper(this, NoSignatureNeededError, arguments); + } + assembled_transaction_inherits(NoSignatureNeededError, _Error4); + return assembled_transaction_createClass(NoSignatureNeededError); + }(assembled_transaction_wrapNativeSuper(Error)), + NoUnsignedNonInvokerAuthEntries: function (_Error5) { + function NoUnsignedNonInvokerAuthEntriesError() { + assembled_transaction_classCallCheck(this, NoUnsignedNonInvokerAuthEntriesError); + return assembled_transaction_callSuper(this, NoUnsignedNonInvokerAuthEntriesError, arguments); + } + assembled_transaction_inherits(NoUnsignedNonInvokerAuthEntriesError, _Error5); + return assembled_transaction_createClass(NoUnsignedNonInvokerAuthEntriesError); + }(assembled_transaction_wrapNativeSuper(Error)), + NoSigner: function (_Error6) { + function NoSignerError() { + assembled_transaction_classCallCheck(this, NoSignerError); + return assembled_transaction_callSuper(this, NoSignerError, arguments); + } + assembled_transaction_inherits(NoSignerError, _Error6); + return assembled_transaction_createClass(NoSignerError); + }(assembled_transaction_wrapNativeSuper(Error)), + NotYetSimulated: function (_Error7) { + function NotYetSimulatedError() { + assembled_transaction_classCallCheck(this, NotYetSimulatedError); + return assembled_transaction_callSuper(this, NotYetSimulatedError, arguments); + } + assembled_transaction_inherits(NotYetSimulatedError, _Error7); + return assembled_transaction_createClass(NotYetSimulatedError); + }(assembled_transaction_wrapNativeSuper(Error)), + FakeAccount: function (_Error8) { + function FakeAccountError() { + assembled_transaction_classCallCheck(this, FakeAccountError); + return assembled_transaction_callSuper(this, FakeAccountError, arguments); + } + assembled_transaction_inherits(FakeAccountError, _Error8); + return assembled_transaction_createClass(FakeAccountError); + }(assembled_transaction_wrapNativeSuper(Error)), + SimulationFailed: function (_Error9) { + function SimulationFailedError() { + assembled_transaction_classCallCheck(this, SimulationFailedError); + return assembled_transaction_callSuper(this, SimulationFailedError, arguments); + } + assembled_transaction_inherits(SimulationFailedError, _Error9); + return assembled_transaction_createClass(SimulationFailedError); + }(assembled_transaction_wrapNativeSuper(Error)), + InternalWalletError: function (_Error10) { + function InternalWalletError() { + assembled_transaction_classCallCheck(this, InternalWalletError); + return assembled_transaction_callSuper(this, InternalWalletError, arguments); + } + assembled_transaction_inherits(InternalWalletError, _Error10); + return assembled_transaction_createClass(InternalWalletError); + }(assembled_transaction_wrapNativeSuper(Error)), + ExternalServiceError: function (_Error11) { + function ExternalServiceError() { + assembled_transaction_classCallCheck(this, ExternalServiceError); + return assembled_transaction_callSuper(this, ExternalServiceError, arguments); + } + assembled_transaction_inherits(ExternalServiceError, _Error11); + return assembled_transaction_createClass(ExternalServiceError); + }(assembled_transaction_wrapNativeSuper(Error)), + InvalidClientRequest: function (_Error12) { + function InvalidClientRequestError() { + assembled_transaction_classCallCheck(this, InvalidClientRequestError); + return assembled_transaction_callSuper(this, InvalidClientRequestError, arguments); + } + assembled_transaction_inherits(InvalidClientRequestError, _Error12); + return assembled_transaction_createClass(InvalidClientRequestError); + }(assembled_transaction_wrapNativeSuper(Error)), + UserRejected: function (_Error13) { + function UserRejectedError() { + assembled_transaction_classCallCheck(this, UserRejectedError); + return assembled_transaction_callSuper(this, UserRejectedError, arguments); + } + assembled_transaction_inherits(UserRejectedError, _Error13); + return assembled_transaction_createClass(UserRejectedError); + }(assembled_transaction_wrapNativeSuper(Error)) +}); +;// ./src/contract/basic_node_signer.ts +/* provided dependency */ var basic_node_signer_Buffer = __webpack_require__(8287)["Buffer"]; +function basic_node_signer_typeof(o) { "@babel/helpers - typeof"; return basic_node_signer_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, basic_node_signer_typeof(o); } +function basic_node_signer_regeneratorRuntime() { "use strict"; basic_node_signer_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == basic_node_signer_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(basic_node_signer_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function basic_node_signer_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function basic_node_signer_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { basic_node_signer_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { basic_node_signer_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + +var basicNodeSigner = function basicNodeSigner(keypair, networkPassphrase) { + return { + signTransaction: function () { + var _signTransaction = basic_node_signer_asyncToGenerator(basic_node_signer_regeneratorRuntime().mark(function _callee(xdr, opts) { + var t; + return basic_node_signer_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + t = lib.TransactionBuilder.fromXDR(xdr, (opts === null || opts === void 0 ? void 0 : opts.networkPassphrase) || networkPassphrase); + t.sign(keypair); + return _context.abrupt("return", { + signedTxXdr: t.toXDR(), + signerAddress: keypair.publicKey() + }); + case 3: + case "end": + return _context.stop(); + } + }, _callee); + })); + function signTransaction(_x, _x2) { + return _signTransaction.apply(this, arguments); + } + return signTransaction; + }(), + signAuthEntry: function () { + var _signAuthEntry = basic_node_signer_asyncToGenerator(basic_node_signer_regeneratorRuntime().mark(function _callee2(authEntry) { + var signedAuthEntry; + return basic_node_signer_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + signedAuthEntry = keypair.sign((0,lib.hash)(basic_node_signer_Buffer.from(authEntry, "base64"))).toString("base64"); + return _context2.abrupt("return", { + signedAuthEntry: signedAuthEntry, + signerAddress: keypair.publicKey() + }); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function signAuthEntry(_x3) { + return _signAuthEntry.apply(this, arguments); + } + return signAuthEntry; + }() + }; +}; +;// ./src/contract/spec.ts +/* provided dependency */ var spec_Buffer = __webpack_require__(8287)["Buffer"]; +function spec_ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function spec_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? spec_ownKeys(Object(t), !0).forEach(function (r) { spec_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : spec_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function spec_typeof(o) { "@babel/helpers - typeof"; return spec_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, spec_typeof(o); } +function spec_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function spec_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, spec_toPropertyKey(o.key), o); } } +function spec_createClass(e, r, t) { return r && spec_defineProperties(e.prototype, r), t && spec_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function spec_defineProperty(e, r, t) { return (r = spec_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function spec_toPropertyKey(t) { var i = spec_toPrimitive(t, "string"); return "symbol" == spec_typeof(i) ? i : i + ""; } +function spec_toPrimitive(t, r) { if ("object" != spec_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != spec_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function spec_slicedToArray(r, e) { return spec_arrayWithHoles(r) || spec_iterableToArrayLimit(r, e) || spec_unsupportedIterableToArray(r, e) || spec_nonIterableRest(); } +function spec_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function spec_unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return spec_arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? spec_arrayLikeToArray(r, a) : void 0; } } +function spec_arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function spec_iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function spec_arrayWithHoles(r) { if (Array.isArray(r)) return r; } + + +function enumToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + var title = aCase.name().toString(); + var desc = aCase.doc().toString(); + oneOf.push({ + description: desc, + title: title, + enum: [aCase.value()], + type: "number" + }); + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +function isNumeric(field) { + return /^\d+$/.test(field.name().toString()); +} +function readObj(args, input) { + var inputName = input.name().toString(); + var entry = Object.entries(args).find(function (_ref) { + var _ref2 = spec_slicedToArray(_ref, 1), + name = _ref2[0]; + return name === inputName; + }); + if (!entry) { + throw new Error("Missing field ".concat(inputName)); + } + return entry[1]; +} +function findCase(name) { + return function matches(entry) { + switch (entry.switch().value) { + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var tuple = entry.tupleCase(); + return tuple.name().toString() === name; + } + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var voidCase = entry.voidCase(); + return voidCase.name().toString() === name; + } + default: + return false; + } + }; +} +function stringToScVal(str, ty) { + switch (ty.value) { + case lib.xdr.ScSpecType.scSpecTypeString().value: + return lib.xdr.ScVal.scvString(str); + case lib.xdr.ScSpecType.scSpecTypeSymbol().value: + return lib.xdr.ScVal.scvSymbol(str); + case lib.xdr.ScSpecType.scSpecTypeAddress().value: + { + var addr = lib.Address.fromString(str); + return lib.xdr.ScVal.scvAddress(addr.toScAddress()); + } + case lib.xdr.ScSpecType.scSpecTypeU64().value: + return new lib.XdrLargeInt("u64", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeI64().value: + return new lib.XdrLargeInt("i64", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeU128().value: + return new lib.XdrLargeInt("u128", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeI128().value: + return new lib.XdrLargeInt("i128", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeU256().value: + return new lib.XdrLargeInt("u256", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeI256().value: + return new lib.XdrLargeInt("i256", str).toScVal(); + case lib.xdr.ScSpecType.scSpecTypeBytes().value: + case lib.xdr.ScSpecType.scSpecTypeBytesN().value: + return lib.xdr.ScVal.scvBytes(spec_Buffer.from(str, "base64")); + default: + throw new TypeError("invalid type ".concat(ty.name, " specified for string value")); + } +} +var PRIMITIVE_DEFINITONS = { + U32: { + type: "integer", + minimum: 0, + maximum: 4294967295 + }, + I32: { + type: "integer", + minimum: -2147483648, + maximum: 2147483647 + }, + U64: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 20 + }, + I64: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 21 + }, + U128: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 39 + }, + I128: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 40 + }, + U256: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 78 + }, + I256: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 79 + }, + Address: { + type: "string", + format: "address", + description: "Address can be a public key or contract id" + }, + ScString: { + type: "string", + description: "ScString is a string" + }, + ScSymbol: { + type: "string", + description: "ScString is a string" + }, + DataUrl: { + type: "string", + pattern: "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$" + } +}; +function typeRef(typeDef) { + var t = typeDef.switch(); + var value = t.value; + var ref; + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVal().value: + { + ref = "Val"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeBool().value: + { + return { + type: "boolean" + }; + } + case lib.xdr.ScSpecType.scSpecTypeVoid().value: + { + return { + type: "null" + }; + } + case lib.xdr.ScSpecType.scSpecTypeError().value: + { + ref = "Error"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU32().value: + { + ref = "U32"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI32().value: + { + ref = "I32"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU64().value: + { + ref = "U64"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI64().value: + { + ref = "I64"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeTimepoint().value: + { + throw new Error("Timepoint type not supported"); + ref = "Timepoint"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeDuration().value: + { + throw new Error("Duration not supported"); + ref = "Duration"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU128().value: + { + ref = "U128"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI128().value: + { + ref = "I128"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeU256().value: + { + ref = "U256"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeI256().value: + { + ref = "I256"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeBytes().value: + { + ref = "DataUrl"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeString().value: + { + ref = "ScString"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeSymbol().value: + { + ref = "ScSymbol"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeAddress().value: + { + ref = "Address"; + break; + } + case lib.xdr.ScSpecType.scSpecTypeOption().value: + { + var opt = typeDef.option(); + return typeRef(opt.valueType()); + } + case lib.xdr.ScSpecType.scSpecTypeResult().value: + { + break; + } + case lib.xdr.ScSpecType.scSpecTypeVec().value: + { + var arr = typeDef.vec(); + var reference = typeRef(arr.elementType()); + return { + type: "array", + items: reference + }; + } + case lib.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = typeDef.map(); + var items = [typeRef(map.keyType()), typeRef(map.valueType())]; + return { + type: "array", + items: { + type: "array", + items: items, + minItems: 2, + maxItems: 2 + } + }; + } + case lib.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tuple = typeDef.tuple(); + var minItems = tuple.valueTypes().length; + var maxItems = minItems; + var _items = tuple.valueTypes().map(typeRef); + return { + type: "array", + items: _items, + minItems: minItems, + maxItems: maxItems + }; + } + case lib.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var _arr = typeDef.bytesN(); + return { + $ref: "#/definitions/DataUrl", + maxLength: _arr.n() + }; + } + case lib.xdr.ScSpecType.scSpecTypeUdt().value: + { + var udt = typeDef.udt(); + ref = udt.name().toString(); + break; + } + } + return { + $ref: "#/definitions/".concat(ref) + }; +} +function isRequired(typeDef) { + return typeDef.switch().value !== lib.xdr.ScSpecType.scSpecTypeOption().value; +} +function argsAndRequired(input) { + var properties = {}; + var required = []; + input.forEach(function (arg) { + var aType = arg.type(); + var name = arg.name().toString(); + properties[name] = typeRef(aType); + if (isRequired(aType)) { + required.push(name); + } + }); + var res = { + properties: properties + }; + if (required.length > 0) { + res.required = required; + } + return res; +} +function structToJsonSchema(udt) { + var fields = udt.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + var items = fields.map(function (_, i) { + return typeRef(fields[i].type()); + }); + return { + type: "array", + items: items, + minItems: fields.length, + maxItems: fields.length + }; + } + var description = udt.doc().toString(); + var _argsAndRequired = argsAndRequired(fields), + properties = _argsAndRequired.properties, + required = _argsAndRequired.required; + properties.additionalProperties = false; + return { + description: description, + properties: properties, + required: required, + type: "object" + }; +} +function functionToJsonSchema(func) { + var _argsAndRequired2 = argsAndRequired(func.inputs()), + properties = _argsAndRequired2.properties, + required = _argsAndRequired2.required; + var args = { + additionalProperties: false, + properties: properties, + type: "object" + }; + if ((required === null || required === void 0 ? void 0 : required.length) > 0) { + args.required = required; + } + var input = { + properties: { + args: args + } + }; + var outputs = func.outputs(); + var output = outputs.length > 0 ? typeRef(outputs[0]) : typeRef(lib.xdr.ScSpecTypeDef.scSpecTypeVoid()); + var description = func.doc().toString(); + if (description.length > 0) { + input.description = description; + } + input.additionalProperties = false; + output.additionalProperties = false; + return { + input: input, + output: output + }; +} +function unionToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + switch (aCase.switch().value) { + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var c = aCase.voidCase(); + var title = c.name().toString(); + oneOf.push({ + type: "object", + title: title, + properties: { + tag: title + }, + additionalProperties: false, + required: ["tag"] + }); + break; + } + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var _c = aCase.tupleCase(); + var _title = _c.name().toString(); + oneOf.push({ + type: "object", + title: _title, + properties: { + tag: _title, + values: { + type: "array", + items: _c.type().map(typeRef) + } + }, + required: ["tag", "values"], + additionalProperties: false + }); + } + } + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +var Spec = function () { + function Spec(entries) { + spec_classCallCheck(this, Spec); + spec_defineProperty(this, "entries", []); + if (entries.length === 0) { + throw new Error("Contract spec must have at least one entry"); + } + var entry = entries[0]; + if (typeof entry === "string") { + this.entries = entries.map(function (s) { + return lib.xdr.ScSpecEntry.fromXDR(s, "base64"); + }); + } else { + this.entries = entries; + } + } + return spec_createClass(Spec, [{ + key: "funcs", + value: function funcs() { + return this.entries.filter(function (entry) { + return entry.switch().value === lib.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value; + }).map(function (entry) { + return entry.functionV0(); + }); + } + }, { + key: "getFunc", + value: function getFunc(name) { + var entry = this.findEntry(name); + if (entry.switch().value !== lib.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value) { + throw new Error("".concat(name, " is not a function")); + } + return entry.functionV0(); + } + }, { + key: "funcArgsToScVals", + value: function funcArgsToScVals(name, args) { + var _this = this; + var fn = this.getFunc(name); + return fn.inputs().map(function (input) { + return _this.nativeToScVal(readObj(args, input), input.type()); + }); + } + }, { + key: "funcResToNative", + value: function funcResToNative(name, val_or_base64) { + var val = typeof val_or_base64 === "string" ? lib.xdr.ScVal.fromXDR(val_or_base64, "base64") : val_or_base64; + var func = this.getFunc(name); + var outputs = func.outputs(); + if (outputs.length === 0) { + var type = val.switch(); + if (type.value !== lib.xdr.ScValType.scvVoid().value) { + throw new Error("Expected void, got ".concat(type.name)); + } + return null; + } + if (outputs.length > 1) { + throw new Error("Multiple outputs not supported"); + } + var output = outputs[0]; + if (output.switch().value === lib.xdr.ScSpecType.scSpecTypeResult().value) { + return new Ok(this.scValToNative(val, output.result().okType())); + } + return this.scValToNative(val, output); + } + }, { + key: "findEntry", + value: function findEntry(name) { + var entry = this.entries.find(function (e) { + return e.value().name().toString() === name; + }); + if (!entry) { + throw new Error("no such entry: ".concat(name)); + } + return entry; + } + }, { + key: "nativeToScVal", + value: function nativeToScVal(val, ty) { + var _this2 = this; + var t = ty.switch(); + var value = t.value; + if (t.value === lib.xdr.ScSpecType.scSpecTypeUdt().value) { + var udt = ty.udt(); + return this.nativeToUdt(val, udt.name().toString()); + } + if (value === lib.xdr.ScSpecType.scSpecTypeOption().value) { + var opt = ty.option(); + if (val === undefined) { + return lib.xdr.ScVal.scvVoid(); + } + return this.nativeToScVal(val, opt.valueType()); + } + switch (spec_typeof(val)) { + case "object": + { + var _val$constructor$name, _val$constructor; + if (val === null) { + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVoid().value: + return lib.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was null")); + } + } + if (val instanceof lib.xdr.ScVal) { + return val; + } + if (val instanceof lib.Address) { + if (ty.switch().value !== lib.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.toScVal(); + } + if (val instanceof lib.Contract) { + if (ty.switch().value !== lib.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.address().toScVal(); + } + if (val instanceof Uint8Array || spec_Buffer.isBuffer(val)) { + var copy = Uint8Array.from(val); + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var bytesN = ty.bytesN(); + if (copy.length !== bytesN.n()) { + throw new TypeError("expected ".concat(bytesN.n(), " bytes, but got ").concat(copy.length)); + } + return lib.xdr.ScVal.scvBytes(copy); + } + case lib.xdr.ScSpecType.scSpecTypeBytes().value: + return lib.xdr.ScVal.scvBytes(copy); + default: + throw new TypeError("invalid type (".concat(ty, ") specified for Bytes and BytesN")); + } + } + if (Array.isArray(val)) { + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVec().value: + { + var vec = ty.vec(); + var elementType = vec.elementType(); + return lib.xdr.ScVal.scvVec(val.map(function (v) { + return _this2.nativeToScVal(v, elementType); + })); + } + case lib.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tup = ty.tuple(); + var valTypes = tup.valueTypes(); + if (val.length !== valTypes.length) { + throw new TypeError("Tuple expects ".concat(valTypes.length, " values, but ").concat(val.length, " were provided")); + } + return lib.xdr.ScVal.scvVec(val.map(function (v, i) { + return _this2.nativeToScVal(v, valTypes[i]); + })); + } + case lib.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = ty.map(); + var keyType = map.keyType(); + var valueType = map.valueType(); + return lib.xdr.ScVal.scvMap(val.map(function (entry) { + var key = _this2.nativeToScVal(entry[0], keyType); + var mapVal = _this2.nativeToScVal(entry[1], valueType); + return new lib.xdr.ScMapEntry({ + key: key, + val: mapVal + }); + })); + } + default: + throw new TypeError("Type ".concat(ty, " was not vec, but value was Array")); + } + } + if (val.constructor === Map) { + if (value !== lib.xdr.ScSpecType.scSpecTypeMap().value) { + throw new TypeError("Type ".concat(ty, " was not map, but value was Map")); + } + var scMap = ty.map(); + var _map = val; + var entries = []; + var values = _map.entries(); + var res = values.next(); + while (!res.done) { + var _res$value = spec_slicedToArray(res.value, 2), + k = _res$value[0], + v = _res$value[1]; + var key = this.nativeToScVal(k, scMap.keyType()); + var mapval = this.nativeToScVal(v, scMap.valueType()); + entries.push(new lib.xdr.ScMapEntry({ + key: key, + val: mapval + })); + res = values.next(); + } + return lib.xdr.ScVal.scvMap(entries); + } + if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : "") !== "Object") { + var _val$constructor2; + throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")")); + } + throw new TypeError("Received object ".concat(val, " did not match the provided type ").concat(ty)); + } + case "number": + case "bigint": + { + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeU32().value: + return lib.xdr.ScVal.scvU32(val); + case lib.xdr.ScSpecType.scSpecTypeI32().value: + return lib.xdr.ScVal.scvI32(val); + case lib.xdr.ScSpecType.scSpecTypeU64().value: + case lib.xdr.ScSpecType.scSpecTypeI64().value: + case lib.xdr.ScSpecType.scSpecTypeU128().value: + case lib.xdr.ScSpecType.scSpecTypeI128().value: + case lib.xdr.ScSpecType.scSpecTypeU256().value: + case lib.xdr.ScSpecType.scSpecTypeI256().value: + { + var intType = t.name.substring(10).toLowerCase(); + return new lib.XdrLargeInt(intType, val).toScVal(); + } + default: + throw new TypeError("invalid type (".concat(ty, ") specified for integer")); + } + } + case "string": + return stringToScVal(val, t); + case "boolean": + { + if (value !== lib.xdr.ScSpecType.scSpecTypeBool().value) { + throw TypeError("Type ".concat(ty, " was not bool, but value was bool")); + } + return lib.xdr.ScVal.scvBool(val); + } + case "undefined": + { + if (!ty) { + return lib.xdr.ScVal.scvVoid(); + } + switch (value) { + case lib.xdr.ScSpecType.scSpecTypeVoid().value: + case lib.xdr.ScSpecType.scSpecTypeOption().value: + return lib.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was undefined")); + } + } + case "function": + return this.nativeToScVal(val(), ty); + default: + throw new TypeError("failed to convert typeof ".concat(spec_typeof(val), " (").concat(val, ")")); + } + } + }, { + key: "nativeToUdt", + value: function nativeToUdt(val, name) { + var entry = this.findEntry(name); + switch (entry.switch()) { + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + if (typeof val !== "number") { + throw new TypeError("expected number for enum ".concat(name, ", but got ").concat(spec_typeof(val))); + } + return this.nativeToEnum(val, entry.udtEnumV0()); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.nativeToStruct(val, entry.udtStructV0()); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.nativeToUnion(val, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(name)); + } + } + }, { + key: "nativeToUnion", + value: function nativeToUnion(val, union_) { + var _this3 = this; + var entryName = val.tag; + var caseFound = union_.cases().find(function (entry) { + var caseN = entry.value().name().toString(); + return caseN === entryName; + }); + if (!caseFound) { + throw new TypeError("no such enum entry: ".concat(entryName, " in ").concat(union_)); + } + var key = lib.xdr.ScVal.scvSymbol(entryName); + switch (caseFound.switch()) { + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0(): + { + return lib.xdr.ScVal.scvVec([key]); + } + case lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0(): + { + var types = caseFound.tupleCase().type(); + if (Array.isArray(val.values)) { + if (val.values.length !== types.length) { + throw new TypeError("union ".concat(union_, " expects ").concat(types.length, " values, but got ").concat(val.values.length)); + } + var scvals = val.values.map(function (v, i) { + return _this3.nativeToScVal(v, types[i]); + }); + scvals.unshift(key); + return lib.xdr.ScVal.scvVec(scvals); + } + throw new Error("failed to parse union case ".concat(caseFound, " with ").concat(val)); + } + default: + throw new Error("failed to parse union ".concat(union_, " with ").concat(val)); + } + } + }, { + key: "nativeToStruct", + value: function nativeToStruct(val, struct) { + var _this4 = this; + var fields = struct.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + return lib.xdr.ScVal.scvVec(fields.map(function (_, i) { + return _this4.nativeToScVal(val[i], fields[i].type()); + })); + } + return lib.xdr.ScVal.scvMap(fields.map(function (field) { + var name = field.name().toString(); + return new lib.xdr.ScMapEntry({ + key: _this4.nativeToScVal(name, lib.xdr.ScSpecTypeDef.scSpecTypeSymbol()), + val: _this4.nativeToScVal(val[name], field.type()) + }); + })); + } + }, { + key: "nativeToEnum", + value: function nativeToEnum(val, enum_) { + if (enum_.cases().some(function (entry) { + return entry.value() === val; + })) { + return lib.xdr.ScVal.scvU32(val); + } + throw new TypeError("no such enum entry: ".concat(val, " in ").concat(enum_)); + } + }, { + key: "scValStrToNative", + value: function scValStrToNative(scv, typeDef) { + return this.scValToNative(lib.xdr.ScVal.fromXDR(scv, "base64"), typeDef); + } + }, { + key: "scValToNative", + value: function scValToNative(scv, typeDef) { + var _this5 = this; + var t = typeDef.switch(); + var value = t.value; + if (value === lib.xdr.ScSpecType.scSpecTypeUdt().value) { + return this.scValUdtToNative(scv, typeDef.udt()); + } + switch (scv.switch().value) { + case lib.xdr.ScValType.scvVoid().value: + return undefined; + case lib.xdr.ScValType.scvU64().value: + case lib.xdr.ScValType.scvI64().value: + case lib.xdr.ScValType.scvU128().value: + case lib.xdr.ScValType.scvI128().value: + case lib.xdr.ScValType.scvU256().value: + case lib.xdr.ScValType.scvI256().value: + return (0,lib.scValToBigInt)(scv); + case lib.xdr.ScValType.scvVec().value: + { + if (value === lib.xdr.ScSpecType.scSpecTypeVec().value) { + var _scv$vec; + var vec = typeDef.vec(); + return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(function (elm) { + return _this5.scValToNative(elm, vec.elementType()); + }); + } + if (value === lib.xdr.ScSpecType.scSpecTypeTuple().value) { + var _scv$vec2; + var tuple = typeDef.tuple(); + var valTypes = tuple.valueTypes(); + return ((_scv$vec2 = scv.vec()) !== null && _scv$vec2 !== void 0 ? _scv$vec2 : []).map(function (elm, i) { + return _this5.scValToNative(elm, valTypes[i]); + }); + } + throw new TypeError("Type ".concat(typeDef, " was not vec, but ").concat(scv, " is")); + } + case lib.xdr.ScValType.scvAddress().value: + return lib.Address.fromScVal(scv).toString(); + case lib.xdr.ScValType.scvMap().value: + { + var _scv$map; + var map = (_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []; + if (value === lib.xdr.ScSpecType.scSpecTypeMap().value) { + var typed = typeDef.map(); + var keyType = typed.keyType(); + var valueType = typed.valueType(); + var res = map.map(function (entry) { + return [_this5.scValToNative(entry.key(), keyType), _this5.scValToNative(entry.val(), valueType)]; + }); + return res; + } + throw new TypeError("ScSpecType ".concat(t.name, " was not map, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + case lib.xdr.ScValType.scvBool().value: + case lib.xdr.ScValType.scvU32().value: + case lib.xdr.ScValType.scvI32().value: + case lib.xdr.ScValType.scvBytes().value: + return scv.value(); + case lib.xdr.ScValType.scvString().value: + case lib.xdr.ScValType.scvSymbol().value: + { + var _scv$value; + if (value !== lib.xdr.ScSpecType.scSpecTypeString().value && value !== lib.xdr.ScSpecType.scSpecTypeSymbol().value) { + throw new Error("ScSpecType ".concat(t.name, " was not string or symbol, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + return (_scv$value = scv.value()) === null || _scv$value === void 0 ? void 0 : _scv$value.toString(); + } + case lib.xdr.ScValType.scvTimepoint().value: + case lib.xdr.ScValType.scvDuration().value: + return (0,lib.scValToBigInt)(lib.xdr.ScVal.scvU64(scv.u64())); + default: + throw new TypeError("failed to convert ".concat(JSON.stringify(scv, null, 2), " to native type from type ").concat(t.name)); + } + } + }, { + key: "scValUdtToNative", + value: function scValUdtToNative(scv, udt) { + var entry = this.findEntry(udt.name().toString()); + switch (entry.switch()) { + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + return this.enumToNative(scv); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.structToNative(scv, entry.udtStructV0()); + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.unionToNative(scv, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(udt.name().toString(), ": ").concat(entry)); + } + } + }, { + key: "unionToNative", + value: function unionToNative(val, udt) { + var _this6 = this; + var vec = val.vec(); + if (!vec) { + throw new Error("".concat(JSON.stringify(val, null, 2), " is not a vec")); + } + if (vec.length === 0 && udt.cases.length !== 0) { + throw new Error("".concat(val, " has length 0, but the there are at least one case in the union")); + } + var name = vec[0].sym().toString(); + if (vec[0].switch().value !== lib.xdr.ScValType.scvSymbol().value) { + throw new Error("{vec[0]} is not a symbol"); + } + var entry = udt.cases().find(findCase(name)); + if (!entry) { + throw new Error("failed to find entry ".concat(name, " in union {udt.name().toString()}")); + } + var res = { + tag: name + }; + if (entry.switch().value === lib.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value) { + var tuple = entry.tupleCase(); + var ty = tuple.type(); + var values = ty.map(function (e, i) { + return _this6.scValToNative(vec[i + 1], e); + }); + res.values = values; + } + return res; + } + }, { + key: "structToNative", + value: function structToNative(val, udt) { + var _this7 = this, + _val$map; + var res = {}; + var fields = udt.fields(); + if (fields.some(isNumeric)) { + var _val$vec; + var r = (_val$vec = val.vec()) === null || _val$vec === void 0 ? void 0 : _val$vec.map(function (entry, i) { + return _this7.scValToNative(entry, fields[i].type()); + }); + return r; + } + (_val$map = val.map()) === null || _val$map === void 0 || _val$map.forEach(function (entry, i) { + var field = fields[i]; + res[field.name().toString()] = _this7.scValToNative(entry.val(), field.type()); + }); + return res; + } + }, { + key: "enumToNative", + value: function enumToNative(scv) { + if (scv.switch().value !== lib.xdr.ScValType.scvU32().value) { + throw new Error("Enum must have a u32 value"); + } + var num = scv.u32(); + return num; + } + }, { + key: "errorCases", + value: function errorCases() { + return this.entries.filter(function (entry) { + return entry.switch().value === lib.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value; + }).flatMap(function (entry) { + return entry.value().cases(); + }); + } + }, { + key: "jsonSchema", + value: function jsonSchema(funcName) { + var definitions = {}; + this.entries.forEach(function (entry) { + switch (entry.switch().value) { + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0().value: + { + var udt = entry.udtEnumV0(); + definitions[udt.name().toString()] = enumToJsonSchema(udt); + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0().value: + { + var _udt = entry.udtStructV0(); + definitions[_udt.name().toString()] = structToJsonSchema(_udt); + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0().value: + { + var _udt2 = entry.udtUnionV0(); + definitions[_udt2.name().toString()] = unionToJsonSchema(_udt2); + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value: + { + var fn = entry.functionV0(); + var fnName = fn.name().toString(); + var _functionToJsonSchema = functionToJsonSchema(fn), + input = _functionToJsonSchema.input; + definitions[fnName] = input; + break; + } + case lib.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value: + {} + } + }); + var res = { + $schema: "http://json-schema.org/draft-07/schema#", + definitions: spec_objectSpread(spec_objectSpread({}, PRIMITIVE_DEFINITONS), definitions) + }; + if (funcName) { + res.$ref = "#/definitions/".concat(funcName); + } + return res; + } + }]); +}(); +;// ./src/contract/client.ts +/* provided dependency */ var client_Buffer = __webpack_require__(8287)["Buffer"]; +function client_typeof(o) { "@babel/helpers - typeof"; return client_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, client_typeof(o); } +var _excluded = ["method"], + _excluded2 = ["wasmHash", "salt", "format", "fee", "timeoutInSeconds", "simulate"]; +function client_regeneratorRuntime() { "use strict"; client_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == client_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(client_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function client_ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function client_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? client_ownKeys(Object(t), !0).forEach(function (r) { client_defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : client_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } +function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; } +function client_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function client_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, client_toPropertyKey(o.key), o); } } +function client_createClass(e, r, t) { return r && client_defineProperties(e.prototype, r), t && client_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function client_defineProperty(e, r, t) { return (r = client_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function client_toPropertyKey(t) { var i = client_toPrimitive(t, "string"); return "symbol" == client_typeof(i) ? i : i + ""; } +function client_toPrimitive(t, r) { if ("object" != client_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != client_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function client_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function client_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { client_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { client_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + + + + + +var CONSTRUCTOR_FUNC = "__constructor"; +function specFromWasm(_x) { + return _specFromWasm.apply(this, arguments); +} +function _specFromWasm() { + _specFromWasm = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee5(wasm) { + var wasmModule, xdrSections, bufferSection, specEntryArray, spec; + return client_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return WebAssembly.compile(wasm); + case 2: + wasmModule = _context5.sent; + xdrSections = WebAssembly.Module.customSections(wasmModule, "contractspecv0"); + if (!(xdrSections.length === 0)) { + _context5.next = 6; + break; + } + throw new Error("Could not obtain contract spec from wasm"); + case 6: + bufferSection = client_Buffer.from(xdrSections[0]); + specEntryArray = processSpecEntryStream(bufferSection); + spec = new Spec(specEntryArray); + return _context5.abrupt("return", spec); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _specFromWasm.apply(this, arguments); +} +function specFromWasmHash(_x2, _x3) { + return _specFromWasmHash.apply(this, arguments); +} +function _specFromWasmHash() { + _specFromWasmHash = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee6(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args6 = arguments; + return client_regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + format = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context6.next = 3; + break; + } + throw new TypeError("options must contain rpcUrl"); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new rpc.Server(rpcUrl, serverOpts); + _context6.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context6.sent; + return _context6.abrupt("return", specFromWasm(wasm)); + case 10: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _specFromWasmHash.apply(this, arguments); +} +var Client = function () { + function Client(spec, options) { + var _this = this; + client_classCallCheck(this, Client); + client_defineProperty(this, "txFromJSON", function (json) { + var _JSON$parse = JSON.parse(json), + method = _JSON$parse.method, + tx = _objectWithoutProperties(_JSON$parse, _excluded); + return AssembledTransaction.fromJSON(client_objectSpread(client_objectSpread({}, _this.options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return _this.spec.funcResToNative(method, result); + } + }), tx); + }); + client_defineProperty(this, "txFromXDR", function (xdrBase64) { + return AssembledTransaction.fromXDR(_this.options, xdrBase64, _this.spec); + }); + this.spec = spec; + this.options = options; + this.spec.funcs().forEach(function (xdrFn) { + var method = xdrFn.name().toString(); + if (method === CONSTRUCTOR_FUNC) { + return; + } + var assembleTransaction = function assembleTransaction(args, methodOptions) { + return AssembledTransaction.build(client_objectSpread(client_objectSpread(client_objectSpread({ + method: method, + args: args && spec.funcArgsToScVals(method, args) + }, options), methodOptions), {}, { + errorTypes: spec.errorCases().reduce(function (acc, curr) { + return client_objectSpread(client_objectSpread({}, acc), {}, client_defineProperty({}, curr.value(), { + message: curr.doc().toString() + })); + }, {}), + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + }; + _this[method] = spec.getFunc(method).inputs().length === 0 ? function (opts) { + return assembleTransaction(undefined, opts); + } : assembleTransaction; + }); + } + return client_createClass(Client, null, [{ + key: "deploy", + value: function () { + var _deploy = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee(args, options) { + var wasmHash, salt, format, fee, timeoutInSeconds, simulate, clientOptions, spec, operation; + return client_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + wasmHash = options.wasmHash, salt = options.salt, format = options.format, fee = options.fee, timeoutInSeconds = options.timeoutInSeconds, simulate = options.simulate, clientOptions = _objectWithoutProperties(options, _excluded2); + _context.next = 3; + return specFromWasmHash(wasmHash, clientOptions, format); + case 3: + spec = _context.sent; + operation = lib.Operation.createCustomContract({ + address: new lib.Address(options.publicKey), + wasmHash: typeof wasmHash === "string" ? client_Buffer.from(wasmHash, format !== null && format !== void 0 ? format : "hex") : wasmHash, + salt: salt, + constructorArgs: args ? spec.funcArgsToScVals(CONSTRUCTOR_FUNC, args) : [] + }); + return _context.abrupt("return", AssembledTransaction.buildWithOp(operation, client_objectSpread(client_objectSpread({ + fee: fee, + timeoutInSeconds: timeoutInSeconds, + simulate: simulate + }, clientOptions), {}, { + contractId: "ignored", + method: CONSTRUCTOR_FUNC, + parseResultXdr: function parseResultXdr(result) { + return new Client(spec, client_objectSpread(client_objectSpread({}, clientOptions), {}, { + contractId: lib.Address.fromScVal(result).toString() + })); + } + }))); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + function deploy(_x4, _x5) { + return _deploy.apply(this, arguments); + } + return deploy; + }() + }, { + key: "fromWasmHash", + value: (function () { + var _fromWasmHash = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee2(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args2 = arguments; + return client_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + format = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context2.next = 3; + break; + } + throw new TypeError('options must contain rpcUrl'); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new rpc.Server(rpcUrl, serverOpts); + _context2.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context2.sent; + return _context2.abrupt("return", Client.fromWasm(wasm, options)); + case 10: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function fromWasmHash(_x6, _x7) { + return _fromWasmHash.apply(this, arguments); + } + return fromWasmHash; + }()) + }, { + key: "fromWasm", + value: (function () { + var _fromWasm = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee3(wasm, options) { + var spec; + return client_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return specFromWasm(wasm); + case 2: + spec = _context3.sent; + return _context3.abrupt("return", new Client(spec, options)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + function fromWasm(_x8, _x9) { + return _fromWasm.apply(this, arguments); + } + return fromWasm; + }()) + }, { + key: "from", + value: (function () { + var _from = client_asyncToGenerator(client_regeneratorRuntime().mark(function _callee4(options) { + var rpcUrl, contractId, allowHttp, serverOpts, server, wasm; + return client_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(!options || !options.rpcUrl || !options.contractId)) { + _context4.next = 2; + break; + } + throw new TypeError('options must contain rpcUrl and contractId'); + case 2: + rpcUrl = options.rpcUrl, contractId = options.contractId, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new rpc.Server(rpcUrl, serverOpts); + _context4.next = 7; + return server.getContractWasmByContractId(contractId); + case 7: + wasm = _context4.sent; + return _context4.abrupt("return", Client.fromWasm(wasm, options)); + case 9: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function from(_x10) { + return _from.apply(this, arguments); + } + return from; + }()) + }]); +}(); +;// ./src/contract/index.ts + + + + + + + + +/***/ }), + +/***/ 5976: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Cu: () => (/* reexport */ AccountRequiresMemoError), + v7: () => (/* reexport */ BadRequestError), + nS: () => (/* reexport */ BadResponseError), + Dr: () => (/* reexport */ NetworkError), + m_: () => (/* reexport */ NotFoundError) +}); + +;// ./src/errors/network.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var NetworkError = function (_Error) { + function NetworkError(message, response) { + var _this; + _classCallCheck(this, NetworkError); + var trueProto = (this instanceof NetworkError ? this.constructor : void 0).prototype; + _this = _callSuper(this, NetworkError, [message]); + _this.__proto__ = trueProto; + _this.constructor = NetworkError; + _this.response = response; + return _this; + } + _inherits(NetworkError, _Error); + return _createClass(NetworkError, [{ + key: "getResponse", + value: function getResponse() { + return this.response; + } + }]); +}(_wrapNativeSuper(Error)); +;// ./src/errors/not_found.ts +function not_found_typeof(o) { "@babel/helpers - typeof"; return not_found_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, not_found_typeof(o); } +function not_found_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, not_found_toPropertyKey(o.key), o); } } +function not_found_createClass(e, r, t) { return r && not_found_defineProperties(e.prototype, r), t && not_found_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function not_found_toPropertyKey(t) { var i = not_found_toPrimitive(t, "string"); return "symbol" == not_found_typeof(i) ? i : i + ""; } +function not_found_toPrimitive(t, r) { if ("object" != not_found_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != not_found_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function not_found_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function not_found_callSuper(t, o, e) { return o = not_found_getPrototypeOf(o), not_found_possibleConstructorReturn(t, not_found_isNativeReflectConstruct() ? Reflect.construct(o, e || [], not_found_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function not_found_possibleConstructorReturn(t, e) { if (e && ("object" == not_found_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return not_found_assertThisInitialized(t); } +function not_found_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function not_found_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (not_found_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function not_found_getPrototypeOf(t) { return not_found_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, not_found_getPrototypeOf(t); } +function not_found_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && not_found_setPrototypeOf(t, e); } +function not_found_setPrototypeOf(t, e) { return not_found_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, not_found_setPrototypeOf(t, e); } + +var NotFoundError = function (_NetworkError) { + function NotFoundError(message, response) { + var _this; + not_found_classCallCheck(this, NotFoundError); + var trueProto = (this instanceof NotFoundError ? this.constructor : void 0).prototype; + _this = not_found_callSuper(this, NotFoundError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = NotFoundError; + _this.name = "NotFoundError"; + return _this; + } + not_found_inherits(NotFoundError, _NetworkError); + return not_found_createClass(NotFoundError); +}(NetworkError); +;// ./src/errors/bad_request.ts +function bad_request_typeof(o) { "@babel/helpers - typeof"; return bad_request_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, bad_request_typeof(o); } +function bad_request_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, bad_request_toPropertyKey(o.key), o); } } +function bad_request_createClass(e, r, t) { return r && bad_request_defineProperties(e.prototype, r), t && bad_request_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function bad_request_toPropertyKey(t) { var i = bad_request_toPrimitive(t, "string"); return "symbol" == bad_request_typeof(i) ? i : i + ""; } +function bad_request_toPrimitive(t, r) { if ("object" != bad_request_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != bad_request_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function bad_request_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function bad_request_callSuper(t, o, e) { return o = bad_request_getPrototypeOf(o), bad_request_possibleConstructorReturn(t, bad_request_isNativeReflectConstruct() ? Reflect.construct(o, e || [], bad_request_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function bad_request_possibleConstructorReturn(t, e) { if (e && ("object" == bad_request_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return bad_request_assertThisInitialized(t); } +function bad_request_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function bad_request_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (bad_request_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function bad_request_getPrototypeOf(t) { return bad_request_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, bad_request_getPrototypeOf(t); } +function bad_request_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && bad_request_setPrototypeOf(t, e); } +function bad_request_setPrototypeOf(t, e) { return bad_request_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, bad_request_setPrototypeOf(t, e); } + +var BadRequestError = function (_NetworkError) { + function BadRequestError(message, response) { + var _this; + bad_request_classCallCheck(this, BadRequestError); + var trueProto = (this instanceof BadRequestError ? this.constructor : void 0).prototype; + _this = bad_request_callSuper(this, BadRequestError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadRequestError; + _this.name = "BadRequestError"; + return _this; + } + bad_request_inherits(BadRequestError, _NetworkError); + return bad_request_createClass(BadRequestError); +}(NetworkError); +;// ./src/errors/bad_response.ts +function bad_response_typeof(o) { "@babel/helpers - typeof"; return bad_response_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, bad_response_typeof(o); } +function bad_response_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, bad_response_toPropertyKey(o.key), o); } } +function bad_response_createClass(e, r, t) { return r && bad_response_defineProperties(e.prototype, r), t && bad_response_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function bad_response_toPropertyKey(t) { var i = bad_response_toPrimitive(t, "string"); return "symbol" == bad_response_typeof(i) ? i : i + ""; } +function bad_response_toPrimitive(t, r) { if ("object" != bad_response_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != bad_response_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function bad_response_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function bad_response_callSuper(t, o, e) { return o = bad_response_getPrototypeOf(o), bad_response_possibleConstructorReturn(t, bad_response_isNativeReflectConstruct() ? Reflect.construct(o, e || [], bad_response_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function bad_response_possibleConstructorReturn(t, e) { if (e && ("object" == bad_response_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return bad_response_assertThisInitialized(t); } +function bad_response_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function bad_response_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (bad_response_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function bad_response_getPrototypeOf(t) { return bad_response_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, bad_response_getPrototypeOf(t); } +function bad_response_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && bad_response_setPrototypeOf(t, e); } +function bad_response_setPrototypeOf(t, e) { return bad_response_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, bad_response_setPrototypeOf(t, e); } + +var BadResponseError = function (_NetworkError) { + function BadResponseError(message, response) { + var _this; + bad_response_classCallCheck(this, BadResponseError); + var trueProto = (this instanceof BadResponseError ? this.constructor : void 0).prototype; + _this = bad_response_callSuper(this, BadResponseError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadResponseError; + _this.name = "BadResponseError"; + return _this; + } + bad_response_inherits(BadResponseError, _NetworkError); + return bad_response_createClass(BadResponseError); +}(NetworkError); +;// ./src/errors/account_requires_memo.ts +function account_requires_memo_typeof(o) { "@babel/helpers - typeof"; return account_requires_memo_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, account_requires_memo_typeof(o); } +function account_requires_memo_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, account_requires_memo_toPropertyKey(o.key), o); } } +function account_requires_memo_createClass(e, r, t) { return r && account_requires_memo_defineProperties(e.prototype, r), t && account_requires_memo_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function account_requires_memo_toPropertyKey(t) { var i = account_requires_memo_toPrimitive(t, "string"); return "symbol" == account_requires_memo_typeof(i) ? i : i + ""; } +function account_requires_memo_toPrimitive(t, r) { if ("object" != account_requires_memo_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != account_requires_memo_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function account_requires_memo_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function account_requires_memo_callSuper(t, o, e) { return o = account_requires_memo_getPrototypeOf(o), account_requires_memo_possibleConstructorReturn(t, account_requires_memo_isNativeReflectConstruct() ? Reflect.construct(o, e || [], account_requires_memo_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function account_requires_memo_possibleConstructorReturn(t, e) { if (e && ("object" == account_requires_memo_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return account_requires_memo_assertThisInitialized(t); } +function account_requires_memo_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function account_requires_memo_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && account_requires_memo_setPrototypeOf(t, e); } +function account_requires_memo_wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return account_requires_memo_wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !account_requires_memo_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return account_requires_memo_construct(t, arguments, account_requires_memo_getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), account_requires_memo_setPrototypeOf(Wrapper, t); }, account_requires_memo_wrapNativeSuper(t); } +function account_requires_memo_construct(t, e, r) { if (account_requires_memo_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && account_requires_memo_setPrototypeOf(p, r.prototype), p; } +function account_requires_memo_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (account_requires_memo_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function account_requires_memo_isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function account_requires_memo_setPrototypeOf(t, e) { return account_requires_memo_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, account_requires_memo_setPrototypeOf(t, e); } +function account_requires_memo_getPrototypeOf(t) { return account_requires_memo_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, account_requires_memo_getPrototypeOf(t); } +var AccountRequiresMemoError = function (_Error) { + function AccountRequiresMemoError(message, accountId, operationIndex) { + var _this; + account_requires_memo_classCallCheck(this, AccountRequiresMemoError); + var trueProto = (this instanceof AccountRequiresMemoError ? this.constructor : void 0).prototype; + _this = account_requires_memo_callSuper(this, AccountRequiresMemoError, [message]); + _this.__proto__ = trueProto; + _this.constructor = AccountRequiresMemoError; + _this.name = "AccountRequiresMemoError"; + _this.accountId = accountId; + _this.operationIndex = operationIndex; + return _this; + } + account_requires_memo_inherits(AccountRequiresMemoError, _Error); + return account_requires_memo_createClass(AccountRequiresMemoError); +}(account_requires_memo_wrapNativeSuper(Error)); +;// ./src/errors/index.ts + + + + + + +/***/ }), + +/***/ 7600: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Api: () => (/* reexport */ Api), + FEDERATION_RESPONSE_MAX_SIZE: () => (/* reexport */ FEDERATION_RESPONSE_MAX_SIZE), + Server: () => (/* reexport */ FederationServer) +}); + +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js +var URI = __webpack_require__(4193); +var URI_default = /*#__PURE__*/__webpack_require__.n(URI); +// EXTERNAL MODULE: ./src/config.ts +var config = __webpack_require__(8732); +// EXTERNAL MODULE: ./src/errors/index.ts + 5 modules +var errors = __webpack_require__(5976); +// EXTERNAL MODULE: ./src/stellartoml/index.ts +var stellartoml = __webpack_require__(3898); +// EXTERNAL MODULE: ./src/http-client/index.ts + 1 modules +var http_client = __webpack_require__(9983); +;// ./src/federation/server.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + +var FEDERATION_RESPONSE_MAX_SIZE = 100 * 1024; +var FederationServer = function () { + function FederationServer(serverURL, domain) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + _classCallCheck(this, FederationServer); + this.serverURL = URI_default()(serverURL); + this.domain = domain; + var allowHttp = typeof opts.allowHttp === "undefined" ? config/* Config */.T.isAllowHttp() : opts.allowHttp; + this.timeout = typeof opts.timeout === "undefined" ? config/* Config */.T.getTimeout() : opts.timeout; + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure federation server"); + } + } + return _createClass(FederationServer, [{ + key: "resolveAddress", + value: (function () { + var _resolveAddress = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(address) { + var stellarAddress, url; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + stellarAddress = address; + if (!(address.indexOf("*") < 0)) { + _context.next = 5; + break; + } + if (this.domain) { + _context.next = 4; + break; + } + return _context.abrupt("return", Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object."))); + case 4: + stellarAddress = "".concat(address, "*").concat(this.domain); + case 5: + url = this.serverURL.query({ + type: "name", + q: stellarAddress + }); + return _context.abrupt("return", this._sendRequest(url)); + case 7: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function resolveAddress(_x) { + return _resolveAddress.apply(this, arguments); + } + return resolveAddress; + }()) + }, { + key: "resolveAccountId", + value: (function () { + var _resolveAccountId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(accountId) { + var url; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + url = this.serverURL.query({ + type: "id", + q: accountId + }); + return _context2.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function resolveAccountId(_x2) { + return _resolveAccountId.apply(this, arguments); + } + return resolveAccountId; + }()) + }, { + key: "resolveTransactionId", + value: (function () { + var _resolveTransactionId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(transactionId) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = this.serverURL.query({ + type: "txid", + q: transactionId + }); + return _context3.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function resolveTransactionId(_x3) { + return _resolveTransactionId.apply(this, arguments); + } + return resolveTransactionId; + }()) + }, { + key: "_sendRequest", + value: function () { + var _sendRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(url) { + var timeout; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + timeout = this.timeout; + return _context4.abrupt("return", http_client/* httpClient */.ok.get(url.toString(), { + maxContentLength: FEDERATION_RESPONSE_MAX_SIZE, + timeout: timeout + }).then(function (response) { + if (typeof response.data.memo !== "undefined" && typeof response.data.memo !== "string") { + throw new Error("memo value should be of type string"); + } + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + if (response.message.match(/^maxContentLength size/)) { + throw new Error("federation response exceeds allowed size of ".concat(FEDERATION_RESPONSE_MAX_SIZE)); + } else { + return Promise.reject(response); + } + } else { + return Promise.reject(new errors/* BadResponseError */.nS("Server query failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + } + })); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function _sendRequest(_x4) { + return _sendRequest2.apply(this, arguments); + } + return _sendRequest; + }() + }], [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(value) { + var opts, + addressParts, + _addressParts, + domain, + federationServer, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {}; + if (!(value.indexOf("*") < 0)) { + _context5.next = 5; + break; + } + if (lib.StrKey.isValidEd25519PublicKey(value)) { + _context5.next = 4; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Account ID"))); + case 4: + return _context5.abrupt("return", Promise.resolve({ + account_id: value + })); + case 5: + addressParts = value.split("*"); + _addressParts = _slicedToArray(addressParts, 2), domain = _addressParts[1]; + if (!(addressParts.length !== 2 || !domain)) { + _context5.next = 9; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Stellar address"))); + case 9: + _context5.next = 11; + return FederationServer.createForDomain(domain, opts); + case 11: + federationServer = _context5.sent; + return _context5.abrupt("return", federationServer.resolveAddress(value)); + case 13: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function resolve(_x5) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }, { + key: "createForDomain", + value: (function () { + var _createForDomain = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(domain) { + var opts, + tomlObject, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : {}; + _context6.next = 3; + return stellartoml.Resolver.resolve(domain, opts); + case 3: + tomlObject = _context6.sent; + if (tomlObject.FEDERATION_SERVER) { + _context6.next = 6; + break; + } + return _context6.abrupt("return", Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field"))); + case 6: + return _context6.abrupt("return", new FederationServer(tomlObject.FEDERATION_SERVER, domain, opts)); + case 7: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function createForDomain(_x6) { + return _createForDomain.apply(this, arguments); + } + return createForDomain; + }()) + }]); +}(); +;// ./src/federation/api.ts +var Api; +;// ./src/federation/index.ts + + + +/***/ }), + +/***/ 8242: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Api: () => (/* binding */ Api) +/* harmony export */ }); +var Api; + +/***/ }), + +/***/ 8733: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + AccountResponse: () => (/* reexport */ AccountResponse), + AxiosClient: () => (/* reexport */ horizon_axios_client), + HorizonApi: () => (/* reexport */ HorizonApi), + SERVER_TIME_MAP: () => (/* reexport */ SERVER_TIME_MAP), + Server: () => (/* reexport */ HorizonServer), + ServerApi: () => (/* reexport */ ServerApi), + "default": () => (/* binding */ horizon), + getCurrentServerTime: () => (/* reexport */ getCurrentServerTime) +}); + +;// ./src/horizon/horizon_api.ts +var HorizonApi; +(function (_HorizonApi) { + var LiquidityPoolType = function (LiquidityPoolType) { + LiquidityPoolType["constantProduct"] = "constant_product"; + return LiquidityPoolType; + }({}); + _HorizonApi.LiquidityPoolType = LiquidityPoolType; + var OperationResponseType = function (OperationResponseType) { + OperationResponseType["createAccount"] = "create_account"; + OperationResponseType["payment"] = "payment"; + OperationResponseType["pathPayment"] = "path_payment_strict_receive"; + OperationResponseType["createPassiveOffer"] = "create_passive_sell_offer"; + OperationResponseType["manageOffer"] = "manage_sell_offer"; + OperationResponseType["setOptions"] = "set_options"; + OperationResponseType["changeTrust"] = "change_trust"; + OperationResponseType["allowTrust"] = "allow_trust"; + OperationResponseType["accountMerge"] = "account_merge"; + OperationResponseType["inflation"] = "inflation"; + OperationResponseType["manageData"] = "manage_data"; + OperationResponseType["bumpSequence"] = "bump_sequence"; + OperationResponseType["manageBuyOffer"] = "manage_buy_offer"; + OperationResponseType["pathPaymentStrictSend"] = "path_payment_strict_send"; + OperationResponseType["createClaimableBalance"] = "create_claimable_balance"; + OperationResponseType["claimClaimableBalance"] = "claim_claimable_balance"; + OperationResponseType["beginSponsoringFutureReserves"] = "begin_sponsoring_future_reserves"; + OperationResponseType["endSponsoringFutureReserves"] = "end_sponsoring_future_reserves"; + OperationResponseType["revokeSponsorship"] = "revoke_sponsorship"; + OperationResponseType["clawback"] = "clawback"; + OperationResponseType["clawbackClaimableBalance"] = "clawback_claimable_balance"; + OperationResponseType["setTrustLineFlags"] = "set_trust_line_flags"; + OperationResponseType["liquidityPoolDeposit"] = "liquidity_pool_deposit"; + OperationResponseType["liquidityPoolWithdraw"] = "liquidity_pool_withdraw"; + OperationResponseType["invokeHostFunction"] = "invoke_host_function"; + OperationResponseType["bumpFootprintExpiration"] = "bump_footprint_expiration"; + OperationResponseType["restoreFootprint"] = "restore_footprint"; + return OperationResponseType; + }({}); + _HorizonApi.OperationResponseType = OperationResponseType; + var OperationResponseTypeI = function (OperationResponseTypeI) { + OperationResponseTypeI[OperationResponseTypeI["createAccount"] = 0] = "createAccount"; + OperationResponseTypeI[OperationResponseTypeI["payment"] = 1] = "payment"; + OperationResponseTypeI[OperationResponseTypeI["pathPayment"] = 2] = "pathPayment"; + OperationResponseTypeI[OperationResponseTypeI["createPassiveOffer"] = 3] = "createPassiveOffer"; + OperationResponseTypeI[OperationResponseTypeI["manageOffer"] = 4] = "manageOffer"; + OperationResponseTypeI[OperationResponseTypeI["setOptions"] = 5] = "setOptions"; + OperationResponseTypeI[OperationResponseTypeI["changeTrust"] = 6] = "changeTrust"; + OperationResponseTypeI[OperationResponseTypeI["allowTrust"] = 7] = "allowTrust"; + OperationResponseTypeI[OperationResponseTypeI["accountMerge"] = 8] = "accountMerge"; + OperationResponseTypeI[OperationResponseTypeI["inflation"] = 9] = "inflation"; + OperationResponseTypeI[OperationResponseTypeI["manageData"] = 10] = "manageData"; + OperationResponseTypeI[OperationResponseTypeI["bumpSequence"] = 11] = "bumpSequence"; + OperationResponseTypeI[OperationResponseTypeI["manageBuyOffer"] = 12] = "manageBuyOffer"; + OperationResponseTypeI[OperationResponseTypeI["pathPaymentStrictSend"] = 13] = "pathPaymentStrictSend"; + OperationResponseTypeI[OperationResponseTypeI["createClaimableBalance"] = 14] = "createClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["claimClaimableBalance"] = 15] = "claimClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["beginSponsoringFutureReserves"] = 16] = "beginSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["endSponsoringFutureReserves"] = 17] = "endSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["revokeSponsorship"] = 18] = "revokeSponsorship"; + OperationResponseTypeI[OperationResponseTypeI["clawback"] = 19] = "clawback"; + OperationResponseTypeI[OperationResponseTypeI["clawbackClaimableBalance"] = 20] = "clawbackClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["setTrustLineFlags"] = 21] = "setTrustLineFlags"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolDeposit"] = 22] = "liquidityPoolDeposit"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolWithdraw"] = 23] = "liquidityPoolWithdraw"; + OperationResponseTypeI[OperationResponseTypeI["invokeHostFunction"] = 24] = "invokeHostFunction"; + OperationResponseTypeI[OperationResponseTypeI["bumpFootprintExpiration"] = 25] = "bumpFootprintExpiration"; + OperationResponseTypeI[OperationResponseTypeI["restoreFootprint"] = 26] = "restoreFootprint"; + return OperationResponseTypeI; + }({}); + _HorizonApi.OperationResponseTypeI = OperationResponseTypeI; + ; + var TransactionFailedResultCodes = function (TransactionFailedResultCodes) { + TransactionFailedResultCodes["TX_FAILED"] = "tx_failed"; + TransactionFailedResultCodes["TX_BAD_SEQ"] = "tx_bad_seq"; + TransactionFailedResultCodes["TX_BAD_AUTH"] = "tx_bad_auth"; + TransactionFailedResultCodes["TX_BAD_AUTH_EXTRA"] = "tx_bad_auth_extra"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_SUCCESS"] = "tx_fee_bump_inner_success"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_FAILED"] = "tx_fee_bump_inner_failed"; + TransactionFailedResultCodes["TX_NOT_SUPPORTED"] = "tx_not_supported"; + TransactionFailedResultCodes["TX_SUCCESS"] = "tx_success"; + TransactionFailedResultCodes["TX_TOO_EARLY"] = "tx_too_early"; + TransactionFailedResultCodes["TX_TOO_LATE"] = "tx_too_late"; + TransactionFailedResultCodes["TX_MISSING_OPERATION"] = "tx_missing_operation"; + TransactionFailedResultCodes["TX_INSUFFICIENT_BALANCE"] = "tx_insufficient_balance"; + TransactionFailedResultCodes["TX_NO_SOURCE_ACCOUNT"] = "tx_no_source_account"; + TransactionFailedResultCodes["TX_INSUFFICIENT_FEE"] = "tx_insufficient_fee"; + TransactionFailedResultCodes["TX_INTERNAL_ERROR"] = "tx_internal_error"; + return TransactionFailedResultCodes; + }({}); + _HorizonApi.TransactionFailedResultCodes = TransactionFailedResultCodes; +})(HorizonApi || (HorizonApi = {})); +;// ./src/horizon/types/effects.ts +var effects_EffectType = function (EffectType) { + EffectType[EffectType["account_created"] = 0] = "account_created"; + EffectType[EffectType["account_removed"] = 1] = "account_removed"; + EffectType[EffectType["account_credited"] = 2] = "account_credited"; + EffectType[EffectType["account_debited"] = 3] = "account_debited"; + EffectType[EffectType["account_thresholds_updated"] = 4] = "account_thresholds_updated"; + EffectType[EffectType["account_home_domain_updated"] = 5] = "account_home_domain_updated"; + EffectType[EffectType["account_flags_updated"] = 6] = "account_flags_updated"; + EffectType[EffectType["account_inflation_destination_updated"] = 7] = "account_inflation_destination_updated"; + EffectType[EffectType["signer_created"] = 10] = "signer_created"; + EffectType[EffectType["signer_removed"] = 11] = "signer_removed"; + EffectType[EffectType["signer_updated"] = 12] = "signer_updated"; + EffectType[EffectType["trustline_created"] = 20] = "trustline_created"; + EffectType[EffectType["trustline_removed"] = 21] = "trustline_removed"; + EffectType[EffectType["trustline_updated"] = 22] = "trustline_updated"; + EffectType[EffectType["trustline_authorized"] = 23] = "trustline_authorized"; + EffectType[EffectType["trustline_deauthorized"] = 24] = "trustline_deauthorized"; + EffectType[EffectType["trustline_authorized_to_maintain_liabilities"] = 25] = "trustline_authorized_to_maintain_liabilities"; + EffectType[EffectType["trustline_flags_updated"] = 26] = "trustline_flags_updated"; + EffectType[EffectType["offer_created"] = 30] = "offer_created"; + EffectType[EffectType["offer_removed"] = 31] = "offer_removed"; + EffectType[EffectType["offer_updated"] = 32] = "offer_updated"; + EffectType[EffectType["trade"] = 33] = "trade"; + EffectType[EffectType["data_created"] = 40] = "data_created"; + EffectType[EffectType["data_removed"] = 41] = "data_removed"; + EffectType[EffectType["data_updated"] = 42] = "data_updated"; + EffectType[EffectType["sequence_bumped"] = 43] = "sequence_bumped"; + EffectType[EffectType["claimable_balance_created"] = 50] = "claimable_balance_created"; + EffectType[EffectType["claimable_balance_claimant_created"] = 51] = "claimable_balance_claimant_created"; + EffectType[EffectType["claimable_balance_claimed"] = 52] = "claimable_balance_claimed"; + EffectType[EffectType["account_sponsorship_created"] = 60] = "account_sponsorship_created"; + EffectType[EffectType["account_sponsorship_updated"] = 61] = "account_sponsorship_updated"; + EffectType[EffectType["account_sponsorship_removed"] = 62] = "account_sponsorship_removed"; + EffectType[EffectType["trustline_sponsorship_created"] = 63] = "trustline_sponsorship_created"; + EffectType[EffectType["trustline_sponsorship_updated"] = 64] = "trustline_sponsorship_updated"; + EffectType[EffectType["trustline_sponsorship_removed"] = 65] = "trustline_sponsorship_removed"; + EffectType[EffectType["data_sponsorship_created"] = 66] = "data_sponsorship_created"; + EffectType[EffectType["data_sponsorship_updated"] = 67] = "data_sponsorship_updated"; + EffectType[EffectType["data_sponsorship_removed"] = 68] = "data_sponsorship_removed"; + EffectType[EffectType["claimable_balance_sponsorship_created"] = 69] = "claimable_balance_sponsorship_created"; + EffectType[EffectType["claimable_balance_sponsorship_updated"] = 70] = "claimable_balance_sponsorship_updated"; + EffectType[EffectType["claimable_balance_sponsorship_removed"] = 71] = "claimable_balance_sponsorship_removed"; + EffectType[EffectType["signer_sponsorship_created"] = 72] = "signer_sponsorship_created"; + EffectType[EffectType["signer_sponsorship_updated"] = 73] = "signer_sponsorship_updated"; + EffectType[EffectType["signer_sponsorship_removed"] = 74] = "signer_sponsorship_removed"; + EffectType[EffectType["claimable_balance_clawed_back"] = 80] = "claimable_balance_clawed_back"; + EffectType[EffectType["liquidity_pool_deposited"] = 90] = "liquidity_pool_deposited"; + EffectType[EffectType["liquidity_pool_withdrew"] = 91] = "liquidity_pool_withdrew"; + EffectType[EffectType["liquidity_pool_trade"] = 92] = "liquidity_pool_trade"; + EffectType[EffectType["liquidity_pool_created"] = 93] = "liquidity_pool_created"; + EffectType[EffectType["liquidity_pool_removed"] = 94] = "liquidity_pool_removed"; + EffectType[EffectType["liquidity_pool_revoked"] = 95] = "liquidity_pool_revoked"; + EffectType[EffectType["contract_credited"] = 96] = "contract_credited"; + EffectType[EffectType["contract_debited"] = 97] = "contract_debited"; + return EffectType; +}({}); +;// ./src/horizon/server_api.ts + + +var ServerApi; +(function (_ServerApi) { + var EffectType = _ServerApi.EffectType = effects_EffectType; + var TradeType = function (TradeType) { + TradeType["all"] = "all"; + TradeType["liquidityPools"] = "liquidity_pool"; + TradeType["orderbook"] = "orderbook"; + return TradeType; + }({}); + _ServerApi.TradeType = TradeType; + var OperationResponseType = HorizonApi.OperationResponseType; + var OperationResponseTypeI = HorizonApi.OperationResponseTypeI; +})(ServerApi || (ServerApi = {})); +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +;// ./src/horizon/account_response.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + +var AccountResponse = function () { + function AccountResponse(response) { + var _this = this; + _classCallCheck(this, AccountResponse); + this._baseAccount = new lib.Account(response.account_id, response.sequence); + Object.entries(response).forEach(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + _this[key] = value; + }); + } + return _createClass(AccountResponse, [{ + key: "accountId", + value: function accountId() { + return this._baseAccount.accountId(); + } + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this._baseAccount.sequenceNumber(); + } + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + this._baseAccount.incrementSequenceNumber(); + this.sequence = this._baseAccount.sequenceNumber(); + } + }]); +}(); +;// ./node_modules/bignumber.js/bignumber.mjs +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + +var + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + +/* + * Create and return a BigNumber constructor. + */ +function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + P[Symbol.toStringTag] = 'BigNumber'; + + // Node.js v10.12.0+ + P[Symbol.for('nodejs.util.inspect.custom')] = P.valueOf; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; +} + + +// PRIVATE HELPER FUNCTIONS + +// These functions don't need access to variables, +// e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + +function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; +} + + +// Return a coefficient array as a string of base 10 digits. +function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); +} + + +// Compare the value of BigNumbers x and y. +function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; +} + + +/* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ +function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } +} + + +// Assumes finite n. +function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; +} + + +function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; +} + + +function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; +} + + +// EXPORT + + +var BigNumber = clone(); + +/* harmony default export */ const bignumber = (BigNumber); + +// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js +var URI = __webpack_require__(4193); +var URI_default = /*#__PURE__*/__webpack_require__.n(URI); +// EXTERNAL MODULE: ./node_modules/urijs/src/URITemplate.js +var URITemplate = __webpack_require__(9127); +var URITemplate_default = /*#__PURE__*/__webpack_require__.n(URITemplate); +// EXTERNAL MODULE: ./src/errors/index.ts + 5 modules +var errors = __webpack_require__(5976); +// EXTERNAL MODULE: ./src/http-client/index.ts + 1 modules +var http_client = __webpack_require__(9983); +;// ./src/horizon/horizon_axios_client.ts +function horizon_axios_client_typeof(o) { "@babel/helpers - typeof"; return horizon_axios_client_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, horizon_axios_client_typeof(o); } + + +var version = "13.1.0"; +var SERVER_TIME_MAP = {}; +var AxiosClient = (0,http_client/* create */.vt)({ + headers: { + "X-Client-Name": "js-stellar-sdk", + "X-Client-Version": version + } +}); +function toSeconds(ms) { + return Math.floor(ms / 1000); +} +AxiosClient.interceptors.response.use(function (response) { + var hostname = URI_default()(response.config.url).hostname(); + var serverTime = 0; + if (response.headers instanceof Headers) { + var dateHeader = response.headers.get('date'); + if (dateHeader) { + serverTime = toSeconds(Date.parse(dateHeader)); + } + } else if (horizon_axios_client_typeof(response.headers) === 'object' && 'date' in response.headers) { + var headers = response.headers; + if (typeof headers.date === 'string') { + serverTime = toSeconds(Date.parse(headers.date)); + } + } + var localTimeRecorded = toSeconds(new Date().getTime()); + if (!Number.isNaN(serverTime)) { + SERVER_TIME_MAP[hostname] = { + serverTime: serverTime, + localTimeRecorded: localTimeRecorded + }; + } + return response; +}); +/* harmony default export */ const horizon_axios_client = (AxiosClient); +function getCurrentServerTime(hostname) { + var entry = SERVER_TIME_MAP[hostname]; + if (!entry || !entry.localTimeRecorded || !entry.serverTime) { + return null; + } + var serverTime = entry.serverTime, + localTimeRecorded = entry.localTimeRecorded; + var currentTime = toSeconds(new Date().getTime()); + if (currentTime - localTimeRecorded > 60 * 5) { + return null; + } + return currentTime - localTimeRecorded + serverTime; +} +;// ./src/horizon/call_builder.ts +function call_builder_typeof(o) { "@babel/helpers - typeof"; return call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, call_builder_typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == call_builder_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(call_builder_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, call_builder_toPropertyKey(o.key), o); } } +function call_builder_createClass(e, r, t) { return r && call_builder_defineProperties(e.prototype, r), t && call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function call_builder_toPropertyKey(t) { var i = call_builder_toPrimitive(t, "string"); return "symbol" == call_builder_typeof(i) ? i : i + ""; } +function call_builder_toPrimitive(t, r) { if ("object" != call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + +var JOINABLE = ["transaction"]; +var anyGlobal = __webpack_require__.g; +var EventSource; +if (true) { + var _ref, _anyGlobal$EventSourc, _anyGlobal$window; + EventSource = (_ref = (_anyGlobal$EventSourc = anyGlobal.EventSource) !== null && _anyGlobal$EventSourc !== void 0 ? _anyGlobal$EventSourc : (_anyGlobal$window = anyGlobal.window) === null || _anyGlobal$window === void 0 ? void 0 : _anyGlobal$window.EventSource) !== null && _ref !== void 0 ? _ref : __webpack_require__(1731); +} +var CallBuilder = function () { + function CallBuilder(serverUrl) { + var neighborRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; + call_builder_classCallCheck(this, CallBuilder); + this.url = serverUrl.clone(); + this.filter = []; + this.originalSegments = this.url.segment() || []; + this.neighborRoot = neighborRoot; + } + return call_builder_createClass(CallBuilder, [{ + key: "call", + value: function call() { + var _this = this; + this.checkFilter(); + return this._sendNormalRequest(this.url).then(function (r) { + return _this._parseResponse(r); + }); + } + }, { + key: "stream", + value: function stream() { + var _this2 = this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (EventSource === undefined) { + throw new Error("Streaming requires eventsource to be enabled. If you need this functionality, compile with USE_EVENTSOURCE=true."); + } + this.checkFilter(); + this.url.setQuery("X-Client-Name", "js-stellar-sdk"); + this.url.setQuery("X-Client-Version", version); + var es; + var timeout; + var createTimeout = function createTimeout() { + timeout = setTimeout(function () { + var _es; + (_es = es) === null || _es === void 0 || _es.close(); + es = _createEventSource(); + }, options.reconnectTimeout || 15 * 1000); + }; + var _createEventSource = function createEventSource() { + try { + es = new EventSource(_this2.url.toString()); + } catch (err) { + if (options.onerror) { + options.onerror(err); + } + } + createTimeout(); + if (!es) { + return es; + } + var closed = false; + var onClose = function onClose() { + if (closed) { + return; + } + clearTimeout(timeout); + es.close(); + _createEventSource(); + closed = true; + }; + var onMessage = function onMessage(message) { + if (message.type === "close") { + onClose(); + return; + } + var result = message.data ? _this2._parseRecord(JSON.parse(message.data)) : message; + if (result.paging_token) { + _this2.url.setQuery("cursor", result.paging_token); + } + clearTimeout(timeout); + createTimeout(); + if (typeof options.onmessage !== "undefined") { + options.onmessage(result); + } + }; + var onError = function onError(error) { + if (options.onerror) { + options.onerror(error); + } + }; + if (es.addEventListener) { + es.addEventListener("message", onMessage.bind(_this2)); + es.addEventListener("error", onError.bind(_this2)); + es.addEventListener("close", onClose.bind(_this2)); + } else { + es.onmessage = onMessage.bind(_this2); + es.onerror = onError.bind(_this2); + } + return es; + }; + _createEventSource(); + return function () { + var _es2; + clearTimeout(timeout); + (_es2 = es) === null || _es2 === void 0 || _es2.close(); + }; + } + }, { + key: "cursor", + value: function cursor(_cursor) { + this.url.setQuery("cursor", _cursor); + return this; + } + }, { + key: "limit", + value: function limit(recordsNumber) { + this.url.setQuery("limit", recordsNumber.toString()); + return this; + } + }, { + key: "order", + value: function order(direction) { + this.url.setQuery("order", direction); + return this; + } + }, { + key: "join", + value: function join(include) { + this.url.setQuery("join", include); + return this; + } + }, { + key: "forEndpoint", + value: function forEndpoint(endpoint, param) { + if (this.neighborRoot === "") { + throw new Error("Invalid usage: neighborRoot not set in constructor"); + } + this.filter.push([endpoint, param, this.neighborRoot]); + return this; + } + }, { + key: "checkFilter", + value: function checkFilter() { + if (this.filter.length >= 2) { + throw new errors/* BadRequestError */.v7("Too many filters specified", this.filter); + } + if (this.filter.length === 1) { + var newSegment = this.originalSegments.concat(this.filter[0]); + this.url.segment(newSegment); + } + } + }, { + key: "_requestFnForLink", + value: function _requestFnForLink(link) { + var _this3 = this; + return _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var opts, + uri, + template, + r, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}; + if (link.templated) { + template = URITemplate_default()(link.href); + uri = URI_default()(template.expand(opts)); + } else { + uri = URI_default()(link.href); + } + _context.next = 4; + return _this3._sendNormalRequest(uri); + case 4: + r = _context.sent; + return _context.abrupt("return", _this3._parseResponse(r)); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + } + }, { + key: "_parseRecord", + value: function _parseRecord(json) { + var _this4 = this; + if (!json._links) { + return json; + } + Object.keys(json._links).forEach(function (key) { + var n = json._links[key]; + var included = false; + if (typeof json[key] !== "undefined") { + json["".concat(key, "_attr")] = json[key]; + included = true; + } + if (included && JOINABLE.indexOf(key) >= 0) { + var record = _this4._parseRecord(json[key]); + json[key] = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", record); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + } else { + json[key] = _this4._requestFnForLink(n); + } + }); + return json; + } + }, { + key: "_sendNormalRequest", + value: function () { + var _sendNormalRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(initialUrl) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = initialUrl; + if (url.authority() === "") { + url = url.authority(this.url.authority()); + } + if (url.protocol() === "") { + url = url.protocol(this.url.protocol()); + } + return _context3.abrupt("return", AxiosClient.get(url.toString()).then(function (response) { + return response.data; + }).catch(this._handleNetworkError)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function _sendNormalRequest(_x) { + return _sendNormalRequest2.apply(this, arguments); + } + return _sendNormalRequest; + }() + }, { + key: "_parseResponse", + value: function _parseResponse(json) { + if (json._embedded && json._embedded.records) { + return this._toCollectionPage(json); + } + return this._parseRecord(json); + } + }, { + key: "_toCollectionPage", + value: function _toCollectionPage(json) { + var _this5 = this; + for (var i = 0; i < json._embedded.records.length; i += 1) { + json._embedded.records[i] = this._parseRecord(json._embedded.records[i]); + } + return { + records: json._embedded.records, + next: function () { + var _next2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + var r; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this5._sendNormalRequest(URI_default()(json._links.next.href)); + case 2: + r = _context4.sent; + return _context4.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function next() { + return _next2.apply(this, arguments); + } + return next; + }(), + prev: function () { + var _prev = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5() { + var r; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return _this5._sendNormalRequest(URI_default()(json._links.prev.href)); + case 2: + r = _context5.sent; + return _context5.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function prev() { + return _prev.apply(this, arguments); + } + return prev; + }() + }; + } + }, { + key: "_handleNetworkError", + value: (function () { + var _handleNetworkError2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(error) { + var _error$response$statu, _error$response$statu2; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + if (!(error.response && error.response.status)) { + _context6.next = 8; + break; + } + _context6.t0 = error.response.status; + _context6.next = _context6.t0 === 404 ? 4 : 5; + break; + case 4: + return _context6.abrupt("return", Promise.reject(new errors/* NotFoundError */.m_((_error$response$statu = error.response.statusText) !== null && _error$response$statu !== void 0 ? _error$response$statu : "Not Found", error.response.data))); + case 5: + return _context6.abrupt("return", Promise.reject(new errors/* NetworkError */.Dr((_error$response$statu2 = error.response.statusText) !== null && _error$response$statu2 !== void 0 ? _error$response$statu2 : "Unknown", error.response.data))); + case 6: + _context6.next = 9; + break; + case 8: + return _context6.abrupt("return", Promise.reject(new Error(error.message))); + case 9: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function _handleNetworkError(_x2) { + return _handleNetworkError2.apply(this, arguments); + } + return _handleNetworkError; + }()) + }]); +}(); +// EXTERNAL MODULE: ./src/config.ts +var config = __webpack_require__(8732); +;// ./src/horizon/account_call_builder.ts +function account_call_builder_typeof(o) { "@babel/helpers - typeof"; return account_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, account_call_builder_typeof(o); } +function account_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function account_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, account_call_builder_toPropertyKey(o.key), o); } } +function account_call_builder_createClass(e, r, t) { return r && account_call_builder_defineProperties(e.prototype, r), t && account_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function account_call_builder_toPropertyKey(t) { var i = account_call_builder_toPrimitive(t, "string"); return "symbol" == account_call_builder_typeof(i) ? i : i + ""; } +function account_call_builder_toPrimitive(t, r) { if ("object" != account_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != account_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == account_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } + +var AccountCallBuilder = function (_CallBuilder) { + function AccountCallBuilder(serverUrl) { + var _this; + account_call_builder_classCallCheck(this, AccountCallBuilder); + _this = _callSuper(this, AccountCallBuilder, [serverUrl]); + _this.url.segment("accounts"); + return _this; + } + _inherits(AccountCallBuilder, _CallBuilder); + return account_call_builder_createClass(AccountCallBuilder, [{ + key: "accountId", + value: function accountId(id) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([id]); + return builder; + } + }, { + key: "forSigner", + value: function forSigner(id) { + this.url.setQuery("signer", id); + return this; + } + }, { + key: "forAsset", + value: function forAsset(asset) { + this.url.setQuery("asset", "".concat(asset)); + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(id) { + this.url.setQuery("liquidity_pool", id); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/assets_call_builder.ts +function assets_call_builder_typeof(o) { "@babel/helpers - typeof"; return assets_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, assets_call_builder_typeof(o); } +function assets_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function assets_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, assets_call_builder_toPropertyKey(o.key), o); } } +function assets_call_builder_createClass(e, r, t) { return r && assets_call_builder_defineProperties(e.prototype, r), t && assets_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function assets_call_builder_toPropertyKey(t) { var i = assets_call_builder_toPrimitive(t, "string"); return "symbol" == assets_call_builder_typeof(i) ? i : i + ""; } +function assets_call_builder_toPrimitive(t, r) { if ("object" != assets_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != assets_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function assets_call_builder_callSuper(t, o, e) { return o = assets_call_builder_getPrototypeOf(o), assets_call_builder_possibleConstructorReturn(t, assets_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], assets_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function assets_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == assets_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return assets_call_builder_assertThisInitialized(t); } +function assets_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function assets_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (assets_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function assets_call_builder_getPrototypeOf(t) { return assets_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, assets_call_builder_getPrototypeOf(t); } +function assets_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && assets_call_builder_setPrototypeOf(t, e); } +function assets_call_builder_setPrototypeOf(t, e) { return assets_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, assets_call_builder_setPrototypeOf(t, e); } + +var AssetsCallBuilder = function (_CallBuilder) { + function AssetsCallBuilder(serverUrl) { + var _this; + assets_call_builder_classCallCheck(this, AssetsCallBuilder); + _this = assets_call_builder_callSuper(this, AssetsCallBuilder, [serverUrl]); + _this.url.segment("assets"); + return _this; + } + assets_call_builder_inherits(AssetsCallBuilder, _CallBuilder); + return assets_call_builder_createClass(AssetsCallBuilder, [{ + key: "forCode", + value: function forCode(value) { + this.url.setQuery("asset_code", value); + return this; + } + }, { + key: "forIssuer", + value: function forIssuer(value) { + this.url.setQuery("asset_issuer", value); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/claimable_balances_call_builder.ts +function claimable_balances_call_builder_typeof(o) { "@babel/helpers - typeof"; return claimable_balances_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, claimable_balances_call_builder_typeof(o); } +function claimable_balances_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function claimable_balances_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, claimable_balances_call_builder_toPropertyKey(o.key), o); } } +function claimable_balances_call_builder_createClass(e, r, t) { return r && claimable_balances_call_builder_defineProperties(e.prototype, r), t && claimable_balances_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function claimable_balances_call_builder_toPropertyKey(t) { var i = claimable_balances_call_builder_toPrimitive(t, "string"); return "symbol" == claimable_balances_call_builder_typeof(i) ? i : i + ""; } +function claimable_balances_call_builder_toPrimitive(t, r) { if ("object" != claimable_balances_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != claimable_balances_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function claimable_balances_call_builder_callSuper(t, o, e) { return o = claimable_balances_call_builder_getPrototypeOf(o), claimable_balances_call_builder_possibleConstructorReturn(t, claimable_balances_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], claimable_balances_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function claimable_balances_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == claimable_balances_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return claimable_balances_call_builder_assertThisInitialized(t); } +function claimable_balances_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function claimable_balances_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (claimable_balances_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function claimable_balances_call_builder_getPrototypeOf(t) { return claimable_balances_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, claimable_balances_call_builder_getPrototypeOf(t); } +function claimable_balances_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && claimable_balances_call_builder_setPrototypeOf(t, e); } +function claimable_balances_call_builder_setPrototypeOf(t, e) { return claimable_balances_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, claimable_balances_call_builder_setPrototypeOf(t, e); } + +var ClaimableBalanceCallBuilder = function (_CallBuilder) { + function ClaimableBalanceCallBuilder(serverUrl) { + var _this; + claimable_balances_call_builder_classCallCheck(this, ClaimableBalanceCallBuilder); + _this = claimable_balances_call_builder_callSuper(this, ClaimableBalanceCallBuilder, [serverUrl]); + _this.url.segment("claimable_balances"); + return _this; + } + claimable_balances_call_builder_inherits(ClaimableBalanceCallBuilder, _CallBuilder); + return claimable_balances_call_builder_createClass(ClaimableBalanceCallBuilder, [{ + key: "claimableBalance", + value: function claimableBalance(claimableBalanceId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([claimableBalanceId]); + return builder; + } + }, { + key: "sponsor", + value: function sponsor(_sponsor) { + this.url.setQuery("sponsor", _sponsor); + return this; + } + }, { + key: "claimant", + value: function claimant(_claimant) { + this.url.setQuery("claimant", _claimant); + return this; + } + }, { + key: "asset", + value: function asset(_asset) { + this.url.setQuery("asset", _asset.toString()); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/effect_call_builder.ts +function effect_call_builder_typeof(o) { "@babel/helpers - typeof"; return effect_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, effect_call_builder_typeof(o); } +function effect_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function effect_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, effect_call_builder_toPropertyKey(o.key), o); } } +function effect_call_builder_createClass(e, r, t) { return r && effect_call_builder_defineProperties(e.prototype, r), t && effect_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function effect_call_builder_toPropertyKey(t) { var i = effect_call_builder_toPrimitive(t, "string"); return "symbol" == effect_call_builder_typeof(i) ? i : i + ""; } +function effect_call_builder_toPrimitive(t, r) { if ("object" != effect_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != effect_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function effect_call_builder_callSuper(t, o, e) { return o = effect_call_builder_getPrototypeOf(o), effect_call_builder_possibleConstructorReturn(t, effect_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], effect_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function effect_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == effect_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return effect_call_builder_assertThisInitialized(t); } +function effect_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function effect_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (effect_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function effect_call_builder_getPrototypeOf(t) { return effect_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, effect_call_builder_getPrototypeOf(t); } +function effect_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && effect_call_builder_setPrototypeOf(t, e); } +function effect_call_builder_setPrototypeOf(t, e) { return effect_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, effect_call_builder_setPrototypeOf(t, e); } + +var EffectCallBuilder = function (_CallBuilder) { + function EffectCallBuilder(serverUrl) { + var _this; + effect_call_builder_classCallCheck(this, EffectCallBuilder); + _this = effect_call_builder_callSuper(this, EffectCallBuilder, [serverUrl, "effects"]); + _this.url.segment("effects"); + return _this; + } + effect_call_builder_inherits(EffectCallBuilder, _CallBuilder); + return effect_call_builder_createClass(EffectCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forOperation", + value: function forOperation(operationId) { + return this.forEndpoint("operations", operationId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }]); +}(CallBuilder); +;// ./src/horizon/friendbot_builder.ts +function friendbot_builder_typeof(o) { "@babel/helpers - typeof"; return friendbot_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, friendbot_builder_typeof(o); } +function friendbot_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, friendbot_builder_toPropertyKey(o.key), o); } } +function friendbot_builder_createClass(e, r, t) { return r && friendbot_builder_defineProperties(e.prototype, r), t && friendbot_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function friendbot_builder_toPropertyKey(t) { var i = friendbot_builder_toPrimitive(t, "string"); return "symbol" == friendbot_builder_typeof(i) ? i : i + ""; } +function friendbot_builder_toPrimitive(t, r) { if ("object" != friendbot_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != friendbot_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function friendbot_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function friendbot_builder_callSuper(t, o, e) { return o = friendbot_builder_getPrototypeOf(o), friendbot_builder_possibleConstructorReturn(t, friendbot_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], friendbot_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function friendbot_builder_possibleConstructorReturn(t, e) { if (e && ("object" == friendbot_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return friendbot_builder_assertThisInitialized(t); } +function friendbot_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function friendbot_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (friendbot_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function friendbot_builder_getPrototypeOf(t) { return friendbot_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, friendbot_builder_getPrototypeOf(t); } +function friendbot_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && friendbot_builder_setPrototypeOf(t, e); } +function friendbot_builder_setPrototypeOf(t, e) { return friendbot_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, friendbot_builder_setPrototypeOf(t, e); } + +var FriendbotBuilder = function (_CallBuilder) { + function FriendbotBuilder(serverUrl, address) { + var _this; + friendbot_builder_classCallCheck(this, FriendbotBuilder); + _this = friendbot_builder_callSuper(this, FriendbotBuilder, [serverUrl]); + _this.url.segment("friendbot"); + _this.url.setQuery("addr", address); + return _this; + } + friendbot_builder_inherits(FriendbotBuilder, _CallBuilder); + return friendbot_builder_createClass(FriendbotBuilder); +}(CallBuilder); +;// ./src/horizon/ledger_call_builder.ts +function ledger_call_builder_typeof(o) { "@babel/helpers - typeof"; return ledger_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, ledger_call_builder_typeof(o); } +function ledger_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function ledger_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, ledger_call_builder_toPropertyKey(o.key), o); } } +function ledger_call_builder_createClass(e, r, t) { return r && ledger_call_builder_defineProperties(e.prototype, r), t && ledger_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function ledger_call_builder_toPropertyKey(t) { var i = ledger_call_builder_toPrimitive(t, "string"); return "symbol" == ledger_call_builder_typeof(i) ? i : i + ""; } +function ledger_call_builder_toPrimitive(t, r) { if ("object" != ledger_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != ledger_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function ledger_call_builder_callSuper(t, o, e) { return o = ledger_call_builder_getPrototypeOf(o), ledger_call_builder_possibleConstructorReturn(t, ledger_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], ledger_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function ledger_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == ledger_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return ledger_call_builder_assertThisInitialized(t); } +function ledger_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function ledger_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (ledger_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function ledger_call_builder_getPrototypeOf(t) { return ledger_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, ledger_call_builder_getPrototypeOf(t); } +function ledger_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && ledger_call_builder_setPrototypeOf(t, e); } +function ledger_call_builder_setPrototypeOf(t, e) { return ledger_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, ledger_call_builder_setPrototypeOf(t, e); } + +var LedgerCallBuilder = function (_CallBuilder) { + function LedgerCallBuilder(serverUrl) { + var _this; + ledger_call_builder_classCallCheck(this, LedgerCallBuilder); + _this = ledger_call_builder_callSuper(this, LedgerCallBuilder, [serverUrl]); + _this.url.segment("ledgers"); + return _this; + } + ledger_call_builder_inherits(LedgerCallBuilder, _CallBuilder); + return ledger_call_builder_createClass(LedgerCallBuilder, [{ + key: "ledger", + value: function ledger(sequence) { + this.filter.push(["ledgers", sequence.toString()]); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/liquidity_pool_call_builder.ts +function liquidity_pool_call_builder_typeof(o) { "@babel/helpers - typeof"; return liquidity_pool_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, liquidity_pool_call_builder_typeof(o); } +function liquidity_pool_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function liquidity_pool_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, liquidity_pool_call_builder_toPropertyKey(o.key), o); } } +function liquidity_pool_call_builder_createClass(e, r, t) { return r && liquidity_pool_call_builder_defineProperties(e.prototype, r), t && liquidity_pool_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function liquidity_pool_call_builder_toPropertyKey(t) { var i = liquidity_pool_call_builder_toPrimitive(t, "string"); return "symbol" == liquidity_pool_call_builder_typeof(i) ? i : i + ""; } +function liquidity_pool_call_builder_toPrimitive(t, r) { if ("object" != liquidity_pool_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != liquidity_pool_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function liquidity_pool_call_builder_callSuper(t, o, e) { return o = liquidity_pool_call_builder_getPrototypeOf(o), liquidity_pool_call_builder_possibleConstructorReturn(t, liquidity_pool_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], liquidity_pool_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function liquidity_pool_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == liquidity_pool_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return liquidity_pool_call_builder_assertThisInitialized(t); } +function liquidity_pool_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function liquidity_pool_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (liquidity_pool_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function liquidity_pool_call_builder_getPrototypeOf(t) { return liquidity_pool_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, liquidity_pool_call_builder_getPrototypeOf(t); } +function liquidity_pool_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && liquidity_pool_call_builder_setPrototypeOf(t, e); } +function liquidity_pool_call_builder_setPrototypeOf(t, e) { return liquidity_pool_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, liquidity_pool_call_builder_setPrototypeOf(t, e); } + +var LiquidityPoolCallBuilder = function (_CallBuilder) { + function LiquidityPoolCallBuilder(serverUrl) { + var _this; + liquidity_pool_call_builder_classCallCheck(this, LiquidityPoolCallBuilder); + _this = liquidity_pool_call_builder_callSuper(this, LiquidityPoolCallBuilder, [serverUrl]); + _this.url.segment("liquidity_pools"); + return _this; + } + liquidity_pool_call_builder_inherits(LiquidityPoolCallBuilder, _CallBuilder); + return liquidity_pool_call_builder_createClass(LiquidityPoolCallBuilder, [{ + key: "forAssets", + value: function forAssets() { + for (var _len = arguments.length, assets = new Array(_len), _key = 0; _key < _len; _key++) { + assets[_key] = arguments[_key]; + } + var assetList = assets.map(function (asset) { + return asset.toString(); + }).join(","); + this.url.setQuery("reserves", assetList); + return this; + } + }, { + key: "forAccount", + value: function forAccount(id) { + this.url.setQuery("account", id); + return this; + } + }, { + key: "liquidityPoolId", + value: function liquidityPoolId(id) { + if (!id.match(/[a-fA-F0-9]{64}/)) { + throw new TypeError("".concat(id, " does not look like a liquidity pool ID")); + } + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([id.toLowerCase()]); + return builder; + } + }]); +}(CallBuilder); +;// ./src/horizon/offer_call_builder.ts +function offer_call_builder_typeof(o) { "@babel/helpers - typeof"; return offer_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, offer_call_builder_typeof(o); } +function offer_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function offer_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, offer_call_builder_toPropertyKey(o.key), o); } } +function offer_call_builder_createClass(e, r, t) { return r && offer_call_builder_defineProperties(e.prototype, r), t && offer_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function offer_call_builder_toPropertyKey(t) { var i = offer_call_builder_toPrimitive(t, "string"); return "symbol" == offer_call_builder_typeof(i) ? i : i + ""; } +function offer_call_builder_toPrimitive(t, r) { if ("object" != offer_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != offer_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function offer_call_builder_callSuper(t, o, e) { return o = offer_call_builder_getPrototypeOf(o), offer_call_builder_possibleConstructorReturn(t, offer_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], offer_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function offer_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == offer_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return offer_call_builder_assertThisInitialized(t); } +function offer_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function offer_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (offer_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function offer_call_builder_getPrototypeOf(t) { return offer_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, offer_call_builder_getPrototypeOf(t); } +function offer_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && offer_call_builder_setPrototypeOf(t, e); } +function offer_call_builder_setPrototypeOf(t, e) { return offer_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, offer_call_builder_setPrototypeOf(t, e); } + +var OfferCallBuilder = function (_CallBuilder) { + function OfferCallBuilder(serverUrl) { + var _this; + offer_call_builder_classCallCheck(this, OfferCallBuilder); + _this = offer_call_builder_callSuper(this, OfferCallBuilder, [serverUrl, "offers"]); + _this.url.segment("offers"); + return _this; + } + offer_call_builder_inherits(OfferCallBuilder, _CallBuilder); + return offer_call_builder_createClass(OfferCallBuilder, [{ + key: "offer", + value: function offer(offerId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([offerId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(id) { + return this.forEndpoint("accounts", id); + } + }, { + key: "buying", + value: function buying(asset) { + if (!asset.isNative()) { + this.url.setQuery("buying_asset_type", asset.getAssetType()); + this.url.setQuery("buying_asset_code", asset.getCode()); + this.url.setQuery("buying_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("buying_asset_type", "native"); + } + return this; + } + }, { + key: "selling", + value: function selling(asset) { + if (!asset.isNative()) { + this.url.setQuery("selling_asset_type", asset.getAssetType()); + this.url.setQuery("selling_asset_code", asset.getCode()); + this.url.setQuery("selling_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("selling_asset_type", "native"); + } + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "seller", + value: function seller(_seller) { + this.url.setQuery("seller", _seller); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/operation_call_builder.ts +function operation_call_builder_typeof(o) { "@babel/helpers - typeof"; return operation_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, operation_call_builder_typeof(o); } +function operation_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function operation_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, operation_call_builder_toPropertyKey(o.key), o); } } +function operation_call_builder_createClass(e, r, t) { return r && operation_call_builder_defineProperties(e.prototype, r), t && operation_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function operation_call_builder_toPropertyKey(t) { var i = operation_call_builder_toPrimitive(t, "string"); return "symbol" == operation_call_builder_typeof(i) ? i : i + ""; } +function operation_call_builder_toPrimitive(t, r) { if ("object" != operation_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != operation_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function operation_call_builder_callSuper(t, o, e) { return o = operation_call_builder_getPrototypeOf(o), operation_call_builder_possibleConstructorReturn(t, operation_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], operation_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function operation_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == operation_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return operation_call_builder_assertThisInitialized(t); } +function operation_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function operation_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (operation_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function operation_call_builder_getPrototypeOf(t) { return operation_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, operation_call_builder_getPrototypeOf(t); } +function operation_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && operation_call_builder_setPrototypeOf(t, e); } +function operation_call_builder_setPrototypeOf(t, e) { return operation_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, operation_call_builder_setPrototypeOf(t, e); } + +var OperationCallBuilder = function (_CallBuilder) { + function OperationCallBuilder(serverUrl) { + var _this; + operation_call_builder_classCallCheck(this, OperationCallBuilder); + _this = operation_call_builder_callSuper(this, OperationCallBuilder, [serverUrl, "operations"]); + _this.url.segment("operations"); + return _this; + } + operation_call_builder_inherits(OperationCallBuilder, _CallBuilder); + return operation_call_builder_createClass(OperationCallBuilder, [{ + key: "operation", + value: function operation(operationId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([operationId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/orderbook_call_builder.ts +function orderbook_call_builder_typeof(o) { "@babel/helpers - typeof"; return orderbook_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, orderbook_call_builder_typeof(o); } +function orderbook_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, orderbook_call_builder_toPropertyKey(o.key), o); } } +function orderbook_call_builder_createClass(e, r, t) { return r && orderbook_call_builder_defineProperties(e.prototype, r), t && orderbook_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function orderbook_call_builder_toPropertyKey(t) { var i = orderbook_call_builder_toPrimitive(t, "string"); return "symbol" == orderbook_call_builder_typeof(i) ? i : i + ""; } +function orderbook_call_builder_toPrimitive(t, r) { if ("object" != orderbook_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != orderbook_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function orderbook_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function orderbook_call_builder_callSuper(t, o, e) { return o = orderbook_call_builder_getPrototypeOf(o), orderbook_call_builder_possibleConstructorReturn(t, orderbook_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], orderbook_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function orderbook_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == orderbook_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return orderbook_call_builder_assertThisInitialized(t); } +function orderbook_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function orderbook_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (orderbook_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function orderbook_call_builder_getPrototypeOf(t) { return orderbook_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, orderbook_call_builder_getPrototypeOf(t); } +function orderbook_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && orderbook_call_builder_setPrototypeOf(t, e); } +function orderbook_call_builder_setPrototypeOf(t, e) { return orderbook_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, orderbook_call_builder_setPrototypeOf(t, e); } + +var OrderbookCallBuilder = function (_CallBuilder) { + function OrderbookCallBuilder(serverUrl, selling, buying) { + var _this; + orderbook_call_builder_classCallCheck(this, OrderbookCallBuilder); + _this = orderbook_call_builder_callSuper(this, OrderbookCallBuilder, [serverUrl]); + _this.url.segment("order_book"); + if (!selling.isNative()) { + _this.url.setQuery("selling_asset_type", selling.getAssetType()); + _this.url.setQuery("selling_asset_code", selling.getCode()); + _this.url.setQuery("selling_asset_issuer", selling.getIssuer()); + } else { + _this.url.setQuery("selling_asset_type", "native"); + } + if (!buying.isNative()) { + _this.url.setQuery("buying_asset_type", buying.getAssetType()); + _this.url.setQuery("buying_asset_code", buying.getCode()); + _this.url.setQuery("buying_asset_issuer", buying.getIssuer()); + } else { + _this.url.setQuery("buying_asset_type", "native"); + } + return _this; + } + orderbook_call_builder_inherits(OrderbookCallBuilder, _CallBuilder); + return orderbook_call_builder_createClass(OrderbookCallBuilder); +}(CallBuilder); +;// ./src/horizon/payment_call_builder.ts +function payment_call_builder_typeof(o) { "@babel/helpers - typeof"; return payment_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, payment_call_builder_typeof(o); } +function payment_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function payment_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, payment_call_builder_toPropertyKey(o.key), o); } } +function payment_call_builder_createClass(e, r, t) { return r && payment_call_builder_defineProperties(e.prototype, r), t && payment_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function payment_call_builder_toPropertyKey(t) { var i = payment_call_builder_toPrimitive(t, "string"); return "symbol" == payment_call_builder_typeof(i) ? i : i + ""; } +function payment_call_builder_toPrimitive(t, r) { if ("object" != payment_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != payment_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function payment_call_builder_callSuper(t, o, e) { return o = payment_call_builder_getPrototypeOf(o), payment_call_builder_possibleConstructorReturn(t, payment_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], payment_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function payment_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == payment_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return payment_call_builder_assertThisInitialized(t); } +function payment_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function payment_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (payment_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function payment_call_builder_getPrototypeOf(t) { return payment_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, payment_call_builder_getPrototypeOf(t); } +function payment_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && payment_call_builder_setPrototypeOf(t, e); } +function payment_call_builder_setPrototypeOf(t, e) { return payment_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, payment_call_builder_setPrototypeOf(t, e); } + +var PaymentCallBuilder = function (_CallBuilder) { + function PaymentCallBuilder(serverUrl) { + var _this; + payment_call_builder_classCallCheck(this, PaymentCallBuilder); + _this = payment_call_builder_callSuper(this, PaymentCallBuilder, [serverUrl, "payments"]); + _this.url.segment("payments"); + return _this; + } + payment_call_builder_inherits(PaymentCallBuilder, _CallBuilder); + return payment_call_builder_createClass(PaymentCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }]); +}(CallBuilder); +;// ./src/horizon/strict_receive_path_call_builder.ts +function strict_receive_path_call_builder_typeof(o) { "@babel/helpers - typeof"; return strict_receive_path_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, strict_receive_path_call_builder_typeof(o); } +function strict_receive_path_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, strict_receive_path_call_builder_toPropertyKey(o.key), o); } } +function strict_receive_path_call_builder_createClass(e, r, t) { return r && strict_receive_path_call_builder_defineProperties(e.prototype, r), t && strict_receive_path_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function strict_receive_path_call_builder_toPropertyKey(t) { var i = strict_receive_path_call_builder_toPrimitive(t, "string"); return "symbol" == strict_receive_path_call_builder_typeof(i) ? i : i + ""; } +function strict_receive_path_call_builder_toPrimitive(t, r) { if ("object" != strict_receive_path_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != strict_receive_path_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function strict_receive_path_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function strict_receive_path_call_builder_callSuper(t, o, e) { return o = strict_receive_path_call_builder_getPrototypeOf(o), strict_receive_path_call_builder_possibleConstructorReturn(t, strict_receive_path_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], strict_receive_path_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function strict_receive_path_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == strict_receive_path_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return strict_receive_path_call_builder_assertThisInitialized(t); } +function strict_receive_path_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function strict_receive_path_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (strict_receive_path_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function strict_receive_path_call_builder_getPrototypeOf(t) { return strict_receive_path_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, strict_receive_path_call_builder_getPrototypeOf(t); } +function strict_receive_path_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && strict_receive_path_call_builder_setPrototypeOf(t, e); } +function strict_receive_path_call_builder_setPrototypeOf(t, e) { return strict_receive_path_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, strict_receive_path_call_builder_setPrototypeOf(t, e); } + +var StrictReceivePathCallBuilder = function (_CallBuilder) { + function StrictReceivePathCallBuilder(serverUrl, source, destinationAsset, destinationAmount) { + var _this; + strict_receive_path_call_builder_classCallCheck(this, StrictReceivePathCallBuilder); + _this = strict_receive_path_call_builder_callSuper(this, StrictReceivePathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-receive"); + if (typeof source === "string") { + _this.url.setQuery("source_account", source); + } else { + var assets = source.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("source_assets", assets); + } + _this.url.setQuery("destination_amount", destinationAmount); + if (!destinationAsset.isNative()) { + _this.url.setQuery("destination_asset_type", destinationAsset.getAssetType()); + _this.url.setQuery("destination_asset_code", destinationAsset.getCode()); + _this.url.setQuery("destination_asset_issuer", destinationAsset.getIssuer()); + } else { + _this.url.setQuery("destination_asset_type", "native"); + } + return _this; + } + strict_receive_path_call_builder_inherits(StrictReceivePathCallBuilder, _CallBuilder); + return strict_receive_path_call_builder_createClass(StrictReceivePathCallBuilder); +}(CallBuilder); +;// ./src/horizon/strict_send_path_call_builder.ts +function strict_send_path_call_builder_typeof(o) { "@babel/helpers - typeof"; return strict_send_path_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, strict_send_path_call_builder_typeof(o); } +function strict_send_path_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, strict_send_path_call_builder_toPropertyKey(o.key), o); } } +function strict_send_path_call_builder_createClass(e, r, t) { return r && strict_send_path_call_builder_defineProperties(e.prototype, r), t && strict_send_path_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function strict_send_path_call_builder_toPropertyKey(t) { var i = strict_send_path_call_builder_toPrimitive(t, "string"); return "symbol" == strict_send_path_call_builder_typeof(i) ? i : i + ""; } +function strict_send_path_call_builder_toPrimitive(t, r) { if ("object" != strict_send_path_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != strict_send_path_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function strict_send_path_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function strict_send_path_call_builder_callSuper(t, o, e) { return o = strict_send_path_call_builder_getPrototypeOf(o), strict_send_path_call_builder_possibleConstructorReturn(t, strict_send_path_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], strict_send_path_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function strict_send_path_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == strict_send_path_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return strict_send_path_call_builder_assertThisInitialized(t); } +function strict_send_path_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function strict_send_path_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (strict_send_path_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function strict_send_path_call_builder_getPrototypeOf(t) { return strict_send_path_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, strict_send_path_call_builder_getPrototypeOf(t); } +function strict_send_path_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && strict_send_path_call_builder_setPrototypeOf(t, e); } +function strict_send_path_call_builder_setPrototypeOf(t, e) { return strict_send_path_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, strict_send_path_call_builder_setPrototypeOf(t, e); } + +var StrictSendPathCallBuilder = function (_CallBuilder) { + function StrictSendPathCallBuilder(serverUrl, sourceAsset, sourceAmount, destination) { + var _this; + strict_send_path_call_builder_classCallCheck(this, StrictSendPathCallBuilder); + _this = strict_send_path_call_builder_callSuper(this, StrictSendPathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-send"); + if (sourceAsset.isNative()) { + _this.url.setQuery("source_asset_type", "native"); + } else { + _this.url.setQuery("source_asset_type", sourceAsset.getAssetType()); + _this.url.setQuery("source_asset_code", sourceAsset.getCode()); + _this.url.setQuery("source_asset_issuer", sourceAsset.getIssuer()); + } + _this.url.setQuery("source_amount", sourceAmount); + if (typeof destination === "string") { + _this.url.setQuery("destination_account", destination); + } else { + var assets = destination.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("destination_assets", assets); + } + return _this; + } + strict_send_path_call_builder_inherits(StrictSendPathCallBuilder, _CallBuilder); + return strict_send_path_call_builder_createClass(StrictSendPathCallBuilder); +}(CallBuilder); +;// ./src/horizon/trade_aggregation_call_builder.ts +function trade_aggregation_call_builder_typeof(o) { "@babel/helpers - typeof"; return trade_aggregation_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, trade_aggregation_call_builder_typeof(o); } +function trade_aggregation_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function trade_aggregation_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, trade_aggregation_call_builder_toPropertyKey(o.key), o); } } +function trade_aggregation_call_builder_createClass(e, r, t) { return r && trade_aggregation_call_builder_defineProperties(e.prototype, r), t && trade_aggregation_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function trade_aggregation_call_builder_toPropertyKey(t) { var i = trade_aggregation_call_builder_toPrimitive(t, "string"); return "symbol" == trade_aggregation_call_builder_typeof(i) ? i : i + ""; } +function trade_aggregation_call_builder_toPrimitive(t, r) { if ("object" != trade_aggregation_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != trade_aggregation_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function trade_aggregation_call_builder_callSuper(t, o, e) { return o = trade_aggregation_call_builder_getPrototypeOf(o), trade_aggregation_call_builder_possibleConstructorReturn(t, trade_aggregation_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], trade_aggregation_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function trade_aggregation_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == trade_aggregation_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return trade_aggregation_call_builder_assertThisInitialized(t); } +function trade_aggregation_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function trade_aggregation_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (trade_aggregation_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function trade_aggregation_call_builder_getPrototypeOf(t) { return trade_aggregation_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, trade_aggregation_call_builder_getPrototypeOf(t); } +function trade_aggregation_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && trade_aggregation_call_builder_setPrototypeOf(t, e); } +function trade_aggregation_call_builder_setPrototypeOf(t, e) { return trade_aggregation_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, trade_aggregation_call_builder_setPrototypeOf(t, e); } + + +var allowedResolutions = [60000, 300000, 900000, 3600000, 86400000, 604800000]; +var TradeAggregationCallBuilder = function (_CallBuilder) { + function TradeAggregationCallBuilder(serverUrl, base, counter, start_time, end_time, resolution, offset) { + var _this; + trade_aggregation_call_builder_classCallCheck(this, TradeAggregationCallBuilder); + _this = trade_aggregation_call_builder_callSuper(this, TradeAggregationCallBuilder, [serverUrl]); + _this.url.segment("trade_aggregations"); + if (!base.isNative()) { + _this.url.setQuery("base_asset_type", base.getAssetType()); + _this.url.setQuery("base_asset_code", base.getCode()); + _this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + _this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + _this.url.setQuery("counter_asset_type", counter.getAssetType()); + _this.url.setQuery("counter_asset_code", counter.getCode()); + _this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + _this.url.setQuery("counter_asset_type", "native"); + } + if (typeof start_time !== "number" || typeof end_time !== "number") { + throw new errors/* BadRequestError */.v7("Invalid time bounds", [start_time, end_time]); + } else { + _this.url.setQuery("start_time", start_time.toString()); + _this.url.setQuery("end_time", end_time.toString()); + } + if (!_this.isValidResolution(resolution)) { + throw new errors/* BadRequestError */.v7("Invalid resolution", resolution); + } else { + _this.url.setQuery("resolution", resolution.toString()); + } + if (!_this.isValidOffset(offset, resolution)) { + throw new errors/* BadRequestError */.v7("Invalid offset", offset); + } else { + _this.url.setQuery("offset", offset.toString()); + } + return _this; + } + trade_aggregation_call_builder_inherits(TradeAggregationCallBuilder, _CallBuilder); + return trade_aggregation_call_builder_createClass(TradeAggregationCallBuilder, [{ + key: "isValidResolution", + value: function isValidResolution(resolution) { + return allowedResolutions.some(function (allowed) { + return allowed === resolution; + }); + } + }, { + key: "isValidOffset", + value: function isValidOffset(offset, resolution) { + var hour = 3600000; + return !(offset > resolution || offset >= 24 * hour || offset % hour !== 0); + } + }]); +}(CallBuilder); +;// ./src/horizon/trades_call_builder.ts +function trades_call_builder_typeof(o) { "@babel/helpers - typeof"; return trades_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, trades_call_builder_typeof(o); } +function trades_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function trades_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, trades_call_builder_toPropertyKey(o.key), o); } } +function trades_call_builder_createClass(e, r, t) { return r && trades_call_builder_defineProperties(e.prototype, r), t && trades_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function trades_call_builder_toPropertyKey(t) { var i = trades_call_builder_toPrimitive(t, "string"); return "symbol" == trades_call_builder_typeof(i) ? i : i + ""; } +function trades_call_builder_toPrimitive(t, r) { if ("object" != trades_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != trades_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function trades_call_builder_callSuper(t, o, e) { return o = trades_call_builder_getPrototypeOf(o), trades_call_builder_possibleConstructorReturn(t, trades_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], trades_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function trades_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == trades_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return trades_call_builder_assertThisInitialized(t); } +function trades_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function trades_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (trades_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function trades_call_builder_getPrototypeOf(t) { return trades_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, trades_call_builder_getPrototypeOf(t); } +function trades_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && trades_call_builder_setPrototypeOf(t, e); } +function trades_call_builder_setPrototypeOf(t, e) { return trades_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, trades_call_builder_setPrototypeOf(t, e); } + +var TradesCallBuilder = function (_CallBuilder) { + function TradesCallBuilder(serverUrl) { + var _this; + trades_call_builder_classCallCheck(this, TradesCallBuilder); + _this = trades_call_builder_callSuper(this, TradesCallBuilder, [serverUrl, "trades"]); + _this.url.segment("trades"); + return _this; + } + trades_call_builder_inherits(TradesCallBuilder, _CallBuilder); + return trades_call_builder_createClass(TradesCallBuilder, [{ + key: "forAssetPair", + value: function forAssetPair(base, counter) { + if (!base.isNative()) { + this.url.setQuery("base_asset_type", base.getAssetType()); + this.url.setQuery("base_asset_code", base.getCode()); + this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + this.url.setQuery("counter_asset_type", counter.getAssetType()); + this.url.setQuery("counter_asset_code", counter.getCode()); + this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + this.url.setQuery("counter_asset_type", "native"); + } + return this; + } + }, { + key: "forOffer", + value: function forOffer(offerId) { + this.url.setQuery("offer_id", offerId); + return this; + } + }, { + key: "forType", + value: function forType(tradeType) { + this.url.setQuery("trade_type", tradeType); + return this; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(liquidityPoolId) { + return this.forEndpoint("liquidity_pools", liquidityPoolId); + } + }]); +}(CallBuilder); +;// ./src/horizon/transaction_call_builder.ts +function transaction_call_builder_typeof(o) { "@babel/helpers - typeof"; return transaction_call_builder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, transaction_call_builder_typeof(o); } +function transaction_call_builder_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function transaction_call_builder_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, transaction_call_builder_toPropertyKey(o.key), o); } } +function transaction_call_builder_createClass(e, r, t) { return r && transaction_call_builder_defineProperties(e.prototype, r), t && transaction_call_builder_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function transaction_call_builder_toPropertyKey(t) { var i = transaction_call_builder_toPrimitive(t, "string"); return "symbol" == transaction_call_builder_typeof(i) ? i : i + ""; } +function transaction_call_builder_toPrimitive(t, r) { if ("object" != transaction_call_builder_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != transaction_call_builder_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function transaction_call_builder_callSuper(t, o, e) { return o = transaction_call_builder_getPrototypeOf(o), transaction_call_builder_possibleConstructorReturn(t, transaction_call_builder_isNativeReflectConstruct() ? Reflect.construct(o, e || [], transaction_call_builder_getPrototypeOf(t).constructor) : o.apply(t, e)); } +function transaction_call_builder_possibleConstructorReturn(t, e) { if (e && ("object" == transaction_call_builder_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return transaction_call_builder_assertThisInitialized(t); } +function transaction_call_builder_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function transaction_call_builder_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (transaction_call_builder_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function transaction_call_builder_getPrototypeOf(t) { return transaction_call_builder_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, transaction_call_builder_getPrototypeOf(t); } +function transaction_call_builder_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && transaction_call_builder_setPrototypeOf(t, e); } +function transaction_call_builder_setPrototypeOf(t, e) { return transaction_call_builder_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, transaction_call_builder_setPrototypeOf(t, e); } + +var TransactionCallBuilder = function (_CallBuilder) { + function TransactionCallBuilder(serverUrl) { + var _this; + transaction_call_builder_classCallCheck(this, TransactionCallBuilder); + _this = transaction_call_builder_callSuper(this, TransactionCallBuilder, [serverUrl, "transactions"]); + _this.url.segment("transactions"); + return _this; + } + transaction_call_builder_inherits(TransactionCallBuilder, _CallBuilder); + return transaction_call_builder_createClass(TransactionCallBuilder, [{ + key: "transaction", + value: function transaction(transactionId) { + var builder = new CallBuilder(this.url.clone()); + builder.filter.push([transactionId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(CallBuilder); +;// ./src/horizon/server.ts +function server_typeof(o) { "@babel/helpers - typeof"; return server_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, server_typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = server_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function server_regeneratorRuntime() { "use strict"; server_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == server_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(server_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function server_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function server_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function server_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function server_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, server_toPropertyKey(o.key), o); } } +function server_createClass(e, r, t) { return r && server_defineProperties(e.prototype, r), t && server_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function server_toPropertyKey(t) { var i = server_toPrimitive(t, "string"); return "symbol" == server_typeof(i) ? i : i + ""; } +function server_toPrimitive(t, r) { if ("object" != server_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != server_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + + + + + + + + + + + + + + + + + + + +var SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000; +var STROOPS_IN_LUMEN = 10000000; +var ACCOUNT_REQUIRES_MEMO = "MQ=="; +function getAmountInLumens(amt) { + return new bignumber(amt).div(STROOPS_IN_LUMEN).toString(); +} +var HorizonServer = function () { + function HorizonServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + server_classCallCheck(this, HorizonServer); + this.serverURL = URI_default()(serverURL); + var allowHttp = typeof opts.allowHttp === "undefined" ? config/* Config */.T.isAllowHttp() : opts.allowHttp; + var customHeaders = {}; + if (opts.appName) { + customHeaders["X-App-Name"] = opts.appName; + } + if (opts.appVersion) { + customHeaders["X-App-Version"] = opts.appVersion; + } + if (opts.authToken) { + customHeaders["X-Auth-Token"] = opts.authToken; + } + if (opts.headers) { + Object.assign(customHeaders, opts.headers); + } + if (Object.keys(customHeaders).length > 0) { + horizon_axios_client.interceptors.request.use(function (config) { + config.headers = config.headers || {}; + config.headers = Object.assign(config.headers, customHeaders); + return config; + }); + } + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure horizon server"); + } + } + return server_createClass(HorizonServer, [{ + key: "fetchTimebounds", + value: (function () { + var _fetchTimebounds = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee(seconds) { + var _isRetry, + currentTime, + _args = arguments; + return server_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _isRetry = _args.length > 1 && _args[1] !== undefined ? _args[1] : false; + currentTime = getCurrentServerTime(this.serverURL.hostname()); + if (!currentTime) { + _context.next = 4; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: currentTime + seconds + }); + case 4: + if (!_isRetry) { + _context.next = 6; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: Math.floor(new Date().getTime() / 1000) + seconds + }); + case 6: + _context.next = 8; + return horizon_axios_client.get(URI_default()(this.serverURL).toString()); + case 8: + return _context.abrupt("return", this.fetchTimebounds(seconds, true)); + case 9: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function fetchTimebounds(_x) { + return _fetchTimebounds.apply(this, arguments); + } + return fetchTimebounds; + }()) + }, { + key: "fetchBaseFee", + value: (function () { + var _fetchBaseFee = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee2() { + var response; + return server_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.feeStats(); + case 2: + response = _context2.sent; + return _context2.abrupt("return", parseInt(response.last_ledger_base_fee, 10) || 100); + case 4: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function fetchBaseFee() { + return _fetchBaseFee.apply(this, arguments); + } + return fetchBaseFee; + }()) + }, { + key: "feeStats", + value: (function () { + var _feeStats = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee3() { + var cb; + return server_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + cb = new CallBuilder(URI_default()(this.serverURL)); + cb.filter.push(["fee_stats"]); + return _context3.abrupt("return", cb.call()); + case 3: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function feeStats() { + return _feeStats.apply(this, arguments); + } + return feeStats; + }()) + }, { + key: "root", + value: (function () { + var _root = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee4() { + var cb; + return server_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + cb = new CallBuilder(URI_default()(this.serverURL)); + return _context4.abrupt("return", cb.call()); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function root() { + return _root.apply(this, arguments); + } + return root; + }()) + }, { + key: "submitTransaction", + value: (function () { + var _submitTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee5(transaction) { + var opts, + tx, + _args5 = arguments; + return server_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context5.next = 4; + break; + } + _context5.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context5.abrupt("return", horizon_axios_client.post(URI_default()(this.serverURL).segment("transactions").toString(), "tx=".concat(tx), { + timeout: SUBMIT_TRANSACTION_TIMEOUT + }).then(function (response) { + if (!response.data.result_xdr) { + return response.data; + } + var responseXDR = lib.xdr.TransactionResult.fromXDR(response.data.result_xdr, "base64"); + var results = responseXDR.result().value(); + var offerResults; + var hasManageOffer; + if (results.length) { + offerResults = results.map(function (result, i) { + if (result.value().switch().name !== "manageBuyOffer" && result.value().switch().name !== "manageSellOffer") { + return null; + } + hasManageOffer = true; + var amountBought = new bignumber(0); + var amountSold = new bignumber(0); + var offerSuccess = result.value().value().success(); + var offersClaimed = offerSuccess.offersClaimed().map(function (offerClaimedAtom) { + var offerClaimed = offerClaimedAtom.value(); + var sellerId = ""; + switch (offerClaimedAtom.switch()) { + case lib.xdr.ClaimAtomType.claimAtomTypeV0(): + sellerId = lib.StrKey.encodeEd25519PublicKey(offerClaimed.sellerEd25519()); + break; + case lib.xdr.ClaimAtomType.claimAtomTypeOrderBook(): + sellerId = lib.StrKey.encodeEd25519PublicKey(offerClaimed.sellerId().ed25519()); + break; + default: + throw new Error("Invalid offer result type: ".concat(offerClaimedAtom.switch())); + } + var claimedOfferAmountBought = new bignumber(offerClaimed.amountBought().toString()); + var claimedOfferAmountSold = new bignumber(offerClaimed.amountSold().toString()); + amountBought = amountBought.plus(claimedOfferAmountSold); + amountSold = amountSold.plus(claimedOfferAmountBought); + var sold = lib.Asset.fromOperation(offerClaimed.assetSold()); + var bought = lib.Asset.fromOperation(offerClaimed.assetBought()); + var assetSold = { + type: sold.getAssetType(), + assetCode: sold.getCode(), + issuer: sold.getIssuer() + }; + var assetBought = { + type: bought.getAssetType(), + assetCode: bought.getCode(), + issuer: bought.getIssuer() + }; + return { + sellerId: sellerId, + offerId: offerClaimed.offerId().toString(), + assetSold: assetSold, + amountSold: getAmountInLumens(claimedOfferAmountSold), + assetBought: assetBought, + amountBought: getAmountInLumens(claimedOfferAmountBought) + }; + }); + var effect = offerSuccess.offer().switch().name; + var currentOffer; + if (typeof offerSuccess.offer().value === "function" && offerSuccess.offer().value()) { + var offerXDR = offerSuccess.offer().value(); + currentOffer = { + offerId: offerXDR.offerId().toString(), + selling: {}, + buying: {}, + amount: getAmountInLumens(offerXDR.amount().toString()), + price: { + n: offerXDR.price().n(), + d: offerXDR.price().d() + } + }; + var selling = lib.Asset.fromOperation(offerXDR.selling()); + currentOffer.selling = { + type: selling.getAssetType(), + assetCode: selling.getCode(), + issuer: selling.getIssuer() + }; + var buying = lib.Asset.fromOperation(offerXDR.buying()); + currentOffer.buying = { + type: buying.getAssetType(), + assetCode: buying.getCode(), + issuer: buying.getIssuer() + }; + } + return { + offersClaimed: offersClaimed, + effect: effect, + operationIndex: i, + currentOffer: currentOffer, + amountBought: getAmountInLumens(amountBought), + amountSold: getAmountInLumens(amountSold), + isFullyOpen: !offersClaimed.length && effect !== "manageOfferDeleted", + wasPartiallyFilled: !!offersClaimed.length && effect !== "manageOfferDeleted", + wasImmediatelyFilled: !!offersClaimed.length && effect === "manageOfferDeleted", + wasImmediatelyDeleted: !offersClaimed.length && effect === "manageOfferDeleted" + }; + }).filter(function (result) { + return !!result; + }); + } + return _objectSpread(_objectSpread({}, response.data), {}, { + offerResults: hasManageOffer ? offerResults : undefined + }); + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new errors/* BadResponseError */.nS("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function submitTransaction(_x2) { + return _submitTransaction.apply(this, arguments); + } + return submitTransaction; + }()) + }, { + key: "submitAsyncTransaction", + value: (function () { + var _submitAsyncTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee6(transaction) { + var opts, + tx, + _args6 = arguments; + return server_regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context6.next = 4; + break; + } + _context6.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context6.abrupt("return", horizon_axios_client.post(URI_default()(this.serverURL).segment("transactions_async").toString(), "tx=".concat(tx)).then(function (response) { + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new errors/* BadResponseError */.nS("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function submitAsyncTransaction(_x3) { + return _submitAsyncTransaction.apply(this, arguments); + } + return submitAsyncTransaction; + }()) + }, { + key: "accounts", + value: function accounts() { + return new AccountCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "claimableBalances", + value: function claimableBalances() { + return new ClaimableBalanceCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "ledgers", + value: function ledgers() { + return new LedgerCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "transactions", + value: function transactions() { + return new TransactionCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "offers", + value: function offers() { + return new OfferCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "orderbook", + value: function orderbook(selling, buying) { + return new OrderbookCallBuilder(URI_default()(this.serverURL), selling, buying); + } + }, { + key: "trades", + value: function trades() { + return new TradesCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "operations", + value: function operations() { + return new OperationCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "liquidityPools", + value: function liquidityPools() { + return new LiquidityPoolCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "strictReceivePaths", + value: function strictReceivePaths(source, destinationAsset, destinationAmount) { + return new StrictReceivePathCallBuilder(URI_default()(this.serverURL), source, destinationAsset, destinationAmount); + } + }, { + key: "strictSendPaths", + value: function strictSendPaths(sourceAsset, sourceAmount, destination) { + return new StrictSendPathCallBuilder(URI_default()(this.serverURL), sourceAsset, sourceAmount, destination); + } + }, { + key: "payments", + value: function payments() { + return new PaymentCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "effects", + value: function effects() { + return new EffectCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "friendbot", + value: function friendbot(address) { + return new FriendbotBuilder(URI_default()(this.serverURL), address); + } + }, { + key: "assets", + value: function assets() { + return new AssetsCallBuilder(URI_default()(this.serverURL)); + } + }, { + key: "loadAccount", + value: (function () { + var _loadAccount = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee7(accountId) { + var res; + return server_regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.accounts().accountId(accountId).call(); + case 2: + res = _context7.sent; + return _context7.abrupt("return", new AccountResponse(res)); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function loadAccount(_x4) { + return _loadAccount.apply(this, arguments); + } + return loadAccount; + }()) + }, { + key: "tradeAggregation", + value: function tradeAggregation(base, counter, start_time, end_time, resolution, offset) { + return new TradeAggregationCallBuilder(URI_default()(this.serverURL), base, counter, start_time, end_time, resolution, offset); + } + }, { + key: "checkMemoRequired", + value: (function () { + var _checkMemoRequired = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee8(transaction) { + var destinations, i, operation, destination, account; + return server_regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (transaction instanceof lib.FeeBumpTransaction) { + transaction = transaction.innerTransaction; + } + if (!(transaction.memo.type !== "none")) { + _context8.next = 3; + break; + } + return _context8.abrupt("return"); + case 3: + destinations = new Set(); + i = 0; + case 5: + if (!(i < transaction.operations.length)) { + _context8.next = 36; + break; + } + operation = transaction.operations[i]; + _context8.t0 = operation.type; + _context8.next = _context8.t0 === "payment" ? 10 : _context8.t0 === "pathPaymentStrictReceive" ? 10 : _context8.t0 === "pathPaymentStrictSend" ? 10 : _context8.t0 === "accountMerge" ? 10 : 11; + break; + case 10: + return _context8.abrupt("break", 12); + case 11: + return _context8.abrupt("continue", 33); + case 12: + destination = operation.destination; + if (!destinations.has(destination)) { + _context8.next = 15; + break; + } + return _context8.abrupt("continue", 33); + case 15: + destinations.add(destination); + if (!destination.startsWith("M")) { + _context8.next = 18; + break; + } + return _context8.abrupt("continue", 33); + case 18: + _context8.prev = 18; + _context8.next = 21; + return this.loadAccount(destination); + case 21: + account = _context8.sent; + if (!(account.data_attr["config.memo_required"] === ACCOUNT_REQUIRES_MEMO)) { + _context8.next = 24; + break; + } + throw new errors/* AccountRequiresMemoError */.Cu("account requires memo", destination, i); + case 24: + _context8.next = 33; + break; + case 26: + _context8.prev = 26; + _context8.t1 = _context8["catch"](18); + if (!(_context8.t1 instanceof errors/* AccountRequiresMemoError */.Cu)) { + _context8.next = 30; + break; + } + throw _context8.t1; + case 30: + if (_context8.t1 instanceof errors/* NotFoundError */.m_) { + _context8.next = 32; + break; + } + throw _context8.t1; + case 32: + return _context8.abrupt("continue", 33); + case 33: + i += 1; + _context8.next = 5; + break; + case 36: + case "end": + return _context8.stop(); + } + }, _callee8, this, [[18, 26]]); + })); + function checkMemoRequired(_x5) { + return _checkMemoRequired.apply(this, arguments); + } + return checkMemoRequired; + }()) + }]); +}(); +;// ./src/horizon/index.ts +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + +/* harmony default export */ const horizon = (module.exports); + +/***/ }), + +/***/ 6121: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + axiosClient: () => (/* binding */ axiosClient), + create: () => (/* binding */ create) +}); + +// NAMESPACE OBJECT: ./node_modules/axios/lib/platform/common/utils.js +var common_utils_namespaceObject = {}; +__webpack_require__.r(common_utils_namespaceObject); +__webpack_require__.d(common_utils_namespaceObject, { + hasBrowserEnv: () => (hasBrowserEnv), + hasStandardBrowserEnv: () => (hasStandardBrowserEnv), + hasStandardBrowserWebWorkerEnv: () => (hasStandardBrowserWebWorkerEnv), + navigator: () => (_navigator), + origin: () => (origin) +}); + +;// ./node_modules/axios/lib/helpers/bind.js + + +function bind(fn, thisArg) { + return function wrap() { + return fn.apply(thisArg, arguments); + }; +} + +;// ./node_modules/axios/lib/utils.js + + + + +// utils is a library of generic helper functions non-specific to axios + +const {toString: utils_toString} = Object.prototype; +const {getPrototypeOf} = Object; + +const kindOf = (cache => thing => { + const str = utils_toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); +})(Object.create(null)); + +const kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type +} + +const typeOfTest = type => thing => typeof thing === type; + +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * + * @returns {boolean} True if value is an Array, otherwise false + */ +const {isArray} = Array; + +/** + * Determine if a value is undefined + * + * @param {*} val The value to test + * + * @returns {boolean} True if the value is undefined, otherwise false + */ +const isUndefined = typeOfTest('undefined'); + +/** + * Determine if a value is a Buffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); +} + +/** + * Determine if a value is an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +const isArrayBuffer = kindOfTest('ArrayBuffer'); + + +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + let result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); + } + return result; +} + +/** + * Determine if a value is a String + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a String, otherwise false + */ +const isString = typeOfTest('string'); + +/** + * Determine if a value is a Function + * + * @param {*} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +const isFunction = typeOfTest('function'); + +/** + * Determine if a value is a Number + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Number, otherwise false + */ +const isNumber = typeOfTest('number'); + +/** + * Determine if a value is an Object + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an Object, otherwise false + */ +const isObject = (thing) => thing !== null && typeof thing === 'object'; + +/** + * Determine if a value is a Boolean + * + * @param {*} thing The value to test + * @returns {boolean} True if value is a Boolean, otherwise false + */ +const isBoolean = thing => thing === true || thing === false; + +/** + * Determine if a value is a plain Object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a plain Object, otherwise false + */ +const isPlainObject = (val) => { + if (kindOf(val) !== 'object') { + return false; + } + + const prototype = getPrototypeOf(val); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); +} + +/** + * Determine if a value is a Date + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Date, otherwise false + */ +const isDate = kindOfTest('Date'); + +/** + * Determine if a value is a File + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFile = kindOfTest('File'); + +/** + * Determine if a value is a Blob + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Blob, otherwise false + */ +const isBlob = kindOfTest('Blob'); + +/** + * Determine if a value is a FileList + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFileList = kindOfTest('FileList'); + +/** + * Determine if a value is a Stream + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Stream, otherwise false + */ +const isStream = (val) => isObject(val) && isFunction(val.pipe); + +/** + * Determine if a value is a FormData + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an FormData, otherwise false + */ +const isFormData = (thing) => { + let kind; + return thing && ( + (typeof FormData === 'function' && thing instanceof FormData) || ( + isFunction(thing.append) && ( + (kind = kindOf(thing)) === 'formdata' || + // detect form-data instance + (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]') + ) + ) + ) +} + +/** + * Determine if a value is a URLSearchParams object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +const isURLSearchParams = kindOfTest('URLSearchParams'); + +const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest); + +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * + * @returns {String} The String freed of excess whitespace + */ +const trim = (str) => str.trim ? + str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + * + * @param {Boolean} [allOwnKeys = false] + * @returns {any} + */ +function forEach(obj, fn, {allOwnKeys = false} = {}) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + let i; + let l; + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; + + for (i = 0; i < len; i++) { + key = keys[i]; + fn.call(null, obj[key], key, obj); + } + } +} + +function findKey(obj, key) { + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; +} + +const _global = (() => { + /*eslint no-undef:0*/ + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global) +})(); + +const isContextDefined = (context) => !isUndefined(context) && context !== _global; + +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + const {caseless} = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + } + + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); + } + return result; +} + +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * + * @param {Boolean} [allOwnKeys] + * @returns {Object} The resulting value of object a + */ +const extend = (a, b, thisArg, {allOwnKeys}= {}) => { + forEach(b, (val, key) => { + if (thisArg && isFunction(val)) { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }, {allOwnKeys}); + return a; +} + +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * + * @returns {string} content value without BOM + */ +const stripBOM = (content) => { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +} + +/** + * Inherit the prototype methods from one constructor into another + * @param {function} constructor + * @param {function} superConstructor + * @param {object} [props] + * @param {object} [descriptors] + * + * @returns {void} + */ +const inherits = (constructor, superConstructor, props, descriptors) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, 'super', { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); +} + +/** + * Resolve object with deep prototype chain to a flat object + * @param {Object} sourceObj source object + * @param {Object} [destObj] + * @param {Function|Boolean} [filter] + * @param {Function} [propFilter] + * + * @returns {Object} + */ +const toFlatObject = (sourceObj, destObj, filter, propFilter) => { + let props; + let i; + let prop; + const merged = {}; + + destObj = destObj || {}; + // eslint-disable-next-line no-eq-null,eqeqeq + if (sourceObj == null) return destObj; + + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + + return destObj; +} + +/** + * Determines whether a string ends with the characters of a specified string + * + * @param {String} str + * @param {String} searchString + * @param {Number} [position= 0] + * + * @returns {boolean} + */ +const endsWith = (str, searchString, position) => { + str = String(str); + if (position === undefined || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; +} + + +/** + * Returns new array from array like object or null if failed + * + * @param {*} [thing] + * + * @returns {?Array} + */ +const toArray = (thing) => { + if (!thing) return null; + if (isArray(thing)) return thing; + let i = thing.length; + if (!isNumber(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; +} + +/** + * Checking if the Uint8Array exists and if it does, it returns a function that checks if the + * thing passed in is an instance of Uint8Array + * + * @param {TypedArray} + * + * @returns {Array} + */ +// eslint-disable-next-line func-names +const isTypedArray = (TypedArray => { + // eslint-disable-next-line func-names + return thing => { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); + +/** + * For each entry in the object, call the function with the key and value. + * + * @param {Object} obj - The object to iterate over. + * @param {Function} fn - The function to call for each entry. + * + * @returns {void} + */ +const forEachEntry = (obj, fn) => { + const generator = obj && obj[Symbol.iterator]; + + const iterator = generator.call(obj); + + let result; + + while ((result = iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); + } +} + +/** + * It takes a regular expression and a string, and returns an array of all the matches + * + * @param {string} regExp - The regular expression to match against. + * @param {string} str - The string to search. + * + * @returns {Array} + */ +const matchAll = (regExp, str) => { + let matches; + const arr = []; + + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + + return arr; +} + +/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ +const isHTMLForm = kindOfTest('HTMLFormElement'); + +const toCamelCase = str => { + return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, + function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; + } + ); +}; + +/* Creating a function that will check if an object has a property. */ +const utils_hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); + +/** + * Determine if a value is a RegExp object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a RegExp object, otherwise false + */ +const isRegExp = kindOfTest('RegExp'); + +const reduceDescriptors = (obj, reducer) => { + const descriptors = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + + forEach(descriptors, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); + + Object.defineProperties(obj, reducedDescriptors); +} + +/** + * Makes all methods read-only + * @param {Object} obj + */ + +const freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name) => { + // skip restricted props in strict mode + if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { + return false; + } + + const value = obj[name]; + + if (!isFunction(value)) return; + + descriptor.enumerable = false; + + if ('writable' in descriptor) { + descriptor.writable = false; + return; + } + + if (!descriptor.set) { + descriptor.set = () => { + throw Error('Can not rewrite read-only method \'' + name + '\''); + }; + } + }); +} + +const toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; + + const define = (arr) => { + arr.forEach(value => { + obj[value] = true; + }); + } + + isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + + return obj; +} + +const noop = () => {} + +const toFiniteNumber = (value, defaultValue) => { + return value != null && Number.isFinite(value = +value) ? value : defaultValue; +} + +const ALPHA = 'abcdefghijklmnopqrstuvwxyz' + +const DIGIT = '0123456789'; + +const ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT +} + +const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { + let str = ''; + const {length} = alphabet; + while (size--) { + str += alphabet[Math.random() * length|0] + } + + return str; +} + +/** + * If the thing is a FormData object, return true, otherwise return false. + * + * @param {unknown} thing - The thing to check. + * + * @returns {boolean} + */ +function isSpecCompliantForm(thing) { + return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]); +} + +const toJSONObject = (obj) => { + const stack = new Array(10); + + const visit = (source, i) => { + + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + + if(!('toJSON' in source)) { + stack[i] = source; + const target = isArray(source) ? [] : {}; + + forEach(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + + stack[i] = undefined; + + return target; + } + } + + return source; + } + + return visit(obj, 0); +} + +const isAsyncFn = kindOfTest('AsyncFunction'); + +const isThenable = (thing) => + thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); + +// original code +// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 + +const _setImmediate = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; + } + + return postMessageSupported ? ((token, callbacks) => { + _global.addEventListener("message", ({source, data}) => { + if (source === _global && data === token) { + callbacks.length && callbacks.shift()(); + } + }, false); + + return (cb) => { + callbacks.push(cb); + _global.postMessage(token, "*"); + } + })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); +})( + typeof setImmediate === 'function', + isFunction(_global.postMessage) +); + +const asap = typeof queueMicrotask !== 'undefined' ? + queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate); + +// ********************* + +/* harmony default export */ const utils = ({ + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString, + isNumber, + isBoolean, + isObject, + isPlainObject, + isReadableStream, + isRequest, + isResponse, + isHeaders, + isUndefined, + isDate, + isFile, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty: utils_hasOwnProperty, + hasOwnProp: utils_hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + ALPHABET, + generateString, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable, + setImmediate: _setImmediate, + asap +}); + +;// ./node_modules/axios/lib/core/AxiosError.js + + + + +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [config] The config. + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * + * @returns {Error} The created error. + */ +function AxiosError(message, code, config, request, response) { + Error.call(this); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = (new Error()).stack; + } + + this.message = message; + this.name = 'AxiosError'; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status ? response.status : null; + } +} + +utils.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils.toJSONObject(this.config), + code: this.code, + status: this.status + }; + } +}); + +const AxiosError_prototype = AxiosError.prototype; +const descriptors = {}; + +[ + 'ERR_BAD_OPTION_VALUE', + 'ERR_BAD_OPTION', + 'ECONNABORTED', + 'ETIMEDOUT', + 'ERR_NETWORK', + 'ERR_FR_TOO_MANY_REDIRECTS', + 'ERR_DEPRECATED', + 'ERR_BAD_RESPONSE', + 'ERR_BAD_REQUEST', + 'ERR_CANCELED', + 'ERR_NOT_SUPPORT', + 'ERR_INVALID_URL' +// eslint-disable-next-line func-names +].forEach(code => { + descriptors[code] = {value: code}; +}); + +Object.defineProperties(AxiosError, descriptors); +Object.defineProperty(AxiosError_prototype, 'isAxiosError', {value: true}); + +// eslint-disable-next-line func-names +AxiosError.from = (error, code, config, request, response, customProps) => { + const axiosError = Object.create(AxiosError_prototype); + + utils.toFlatObject(error, axiosError, function filter(obj) { + return obj !== Error.prototype; + }, prop => { + return prop !== 'isAxiosError'; + }); + + AxiosError.call(axiosError, error.message, code, config, request, response); + + axiosError.cause = error; + + axiosError.name = error.name; + + customProps && Object.assign(axiosError, customProps); + + return axiosError; +}; + +/* harmony default export */ const core_AxiosError = (AxiosError); + +;// ./node_modules/axios/lib/helpers/null.js +// eslint-disable-next-line strict +/* harmony default export */ const helpers_null = (null); + +;// ./node_modules/axios/lib/helpers/toFormData.js +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; + + + + +// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored + + +/** + * Determines if the given thing is a array or js object. + * + * @param {string} thing - The object or array to be visited. + * + * @returns {boolean} + */ +function isVisitable(thing) { + return utils.isPlainObject(thing) || utils.isArray(thing); +} + +/** + * It removes the brackets from the end of a string + * + * @param {string} key - The key of the parameter. + * + * @returns {string} the key without the brackets. + */ +function removeBrackets(key) { + return utils.endsWith(key, '[]') ? key.slice(0, -2) : key; +} + +/** + * It takes a path, a key, and a boolean, and returns a string + * + * @param {string} path - The path to the current key. + * @param {string} key - The key of the current object being iterated over. + * @param {string} dots - If true, the key will be rendered with dots instead of brackets. + * + * @returns {string} The path to the current key. + */ +function renderKey(path, key, dots) { + if (!path) return key; + return path.concat(key).map(function each(token, i) { + // eslint-disable-next-line no-param-reassign + token = removeBrackets(token); + return !dots && i ? '[' + token + ']' : token; + }).join(dots ? '.' : ''); +} + +/** + * If the array is an array and none of its elements are visitable, then it's a flat array. + * + * @param {Array} arr - The array to check + * + * @returns {boolean} + */ +function isFlatArray(arr) { + return utils.isArray(arr) && !arr.some(isVisitable); +} + +const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); +}); + +/** + * Convert a data object to FormData + * + * @param {Object} obj + * @param {?Object} [formData] + * @param {?Object} [options] + * @param {Function} [options.visitor] + * @param {Boolean} [options.metaTokens = true] + * @param {Boolean} [options.dots = false] + * @param {?Boolean} [options.indexes = false] + * + * @returns {Object} + **/ + +/** + * It converts an object into a FormData object + * + * @param {Object} obj - The object to convert to form data. + * @param {string} formData - The FormData object to append to. + * @param {Object} options + * + * @returns + */ +function toFormData(obj, formData, options) { + if (!utils.isObject(obj)) { + throw new TypeError('target must be an object'); + } + + // eslint-disable-next-line no-param-reassign + formData = formData || new (helpers_null || FormData)(); + + // eslint-disable-next-line no-param-reassign + options = utils.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + // eslint-disable-next-line no-eq-null,eqeqeq + return !utils.isUndefined(source[option]); + }); + + const metaTokens = options.metaTokens; + // eslint-disable-next-line no-use-before-define + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; + const useBlob = _Blob && utils.isSpecCompliantForm(formData); + + if (!utils.isFunction(visitor)) { + throw new TypeError('visitor must be a function'); + } + + function convertValue(value) { + if (value === null) return ''; + + if (utils.isDate(value)) { + return value.toISOString(); + } + + if (!useBlob && utils.isBlob(value)) { + throw new core_AxiosError('Blob is not supported. Use a Buffer instead.'); + } + + if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) { + return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + } + + return value; + } + + /** + * Default visitor. + * + * @param {*} value + * @param {String|Number} key + * @param {Array} path + * @this {FormData} + * + * @returns {boolean} return true to visit the each prop of the value recursively + */ + function defaultVisitor(value, key, path) { + let arr = value; + + if (value && !path && typeof value === 'object') { + if (utils.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign + key = metaTokens ? key : key.slice(0, -2); + // eslint-disable-next-line no-param-reassign + value = JSON.stringify(value); + } else if ( + (utils.isArray(value) && isFlatArray(value)) || + ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value)) + )) { + // eslint-disable-next-line no-param-reassign + key = removeBrackets(key); + + arr.forEach(function each(el, index) { + !(utils.isUndefined(el) || el === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), + convertValue(el) + ); + }); + return false; + } + } + + if (isVisitable(value)) { + return true; + } + + formData.append(renderKey(path, key, dots), convertValue(value)); + + return false; + } + + const stack = []; + + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable + }); + + function build(value, path) { + if (utils.isUndefined(value)) return; + + if (stack.indexOf(value) !== -1) { + throw Error('Circular reference detected in ' + path.join('.')); + } + + stack.push(value); + + utils.forEach(value, function each(el, key) { + const result = !(utils.isUndefined(el) || el === null) && visitor.call( + formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers + ); + + if (result === true) { + build(el, path ? path.concat(key) : [key]); + } + }); + + stack.pop(); + } + + if (!utils.isObject(obj)) { + throw new TypeError('data must be an object'); + } + + build(obj); + + return formData; +} + +/* harmony default export */ const helpers_toFormData = (toFormData); + +;// ./node_modules/axios/lib/helpers/AxiosURLSearchParams.js + + + + +/** + * It encodes a string by replacing all characters that are not in the unreserved set with + * their percent-encoded equivalents + * + * @param {string} str - The string to encode. + * + * @returns {string} The encoded string. + */ +function encode(str) { + const charMap = { + '!': '%21', + "'": '%27', + '(': '%28', + ')': '%29', + '~': '%7E', + '%20': '+', + '%00': '\x00' + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); +} + +/** + * It takes a params object and converts it to a FormData object + * + * @param {Object} params - The parameters to be converted to a FormData object. + * @param {Object} options - The options object passed to the Axios constructor. + * + * @returns {void} + */ +function AxiosURLSearchParams(params, options) { + this._pairs = []; + + params && helpers_toFormData(params, this, options); +} + +const AxiosURLSearchParams_prototype = AxiosURLSearchParams.prototype; + +AxiosURLSearchParams_prototype.append = function append(name, value) { + this._pairs.push([name, value]); +}; + +AxiosURLSearchParams_prototype.toString = function toString(encoder) { + const _encode = encoder ? function(value) { + return encoder.call(this, value, encode); + } : encode; + + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + '=' + _encode(pair[1]); + }, '').join('&'); +}; + +/* harmony default export */ const helpers_AxiosURLSearchParams = (AxiosURLSearchParams); + +;// ./node_modules/axios/lib/helpers/buildURL.js + + + + + +/** + * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their + * URI encoded counterparts + * + * @param {string} val The value to be encoded. + * + * @returns {string} The encoded value. + */ +function buildURL_encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} + +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @param {?(object|Function)} options + * + * @returns {string} The formatted url + */ +function buildURL(url, params, options) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + + const _encode = options && options.encode || buildURL_encode; + + if (utils.isFunction(options)) { + options = { + serialize: options + }; + } + + const serializeFn = options && options.serialize; + + let serializedParams; + + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils.isURLSearchParams(params) ? + params.toString() : + new helpers_AxiosURLSearchParams(params, options).toString(_encode); + } + + if (serializedParams) { + const hashmarkIndex = url.indexOf("#"); + + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + + return url; +} + +;// ./node_modules/axios/lib/core/InterceptorManager.js + + + + +class InterceptorManager { + constructor() { + this.handlers = []; + } + + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + */ + eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; + } + } + + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + } +} + +/* harmony default export */ const core_InterceptorManager = (InterceptorManager); + +;// ./node_modules/axios/lib/defaults/transitional.js + + +/* harmony default export */ const defaults_transitional = ({ + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false +}); + +;// ./node_modules/axios/lib/platform/browser/classes/URLSearchParams.js + + + +/* harmony default export */ const classes_URLSearchParams = (typeof URLSearchParams !== 'undefined' ? URLSearchParams : helpers_AxiosURLSearchParams); + +;// ./node_modules/axios/lib/platform/browser/classes/FormData.js + + +/* harmony default export */ const classes_FormData = (typeof FormData !== 'undefined' ? FormData : null); + +;// ./node_modules/axios/lib/platform/browser/classes/Blob.js + + +/* harmony default export */ const classes_Blob = (typeof Blob !== 'undefined' ? Blob : null); + +;// ./node_modules/axios/lib/platform/browser/index.js + + + + +/* harmony default export */ const browser = ({ + isBrowser: true, + classes: { + URLSearchParams: classes_URLSearchParams, + FormData: classes_FormData, + Blob: classes_Blob + }, + protocols: ['http', 'https', 'file', 'blob', 'url', 'data'] +}); + +;// ./node_modules/axios/lib/platform/common/utils.js +const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; + +const _navigator = typeof navigator === 'object' && navigator || undefined; + +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + * + * @returns {boolean} + */ +const hasStandardBrowserEnv = hasBrowserEnv && + (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0); + +/** + * Determine if we're running in a standard browser webWorker environment + * + * Although the `isStandardBrowserEnv` method indicates that + * `allows axios to run in a web worker`, the WebWorker will still be + * filtered out due to its judgment standard + * `typeof window !== 'undefined' && typeof document !== 'undefined'`. + * This leads to a problem when axios post `FormData` in webWorker + */ +const hasStandardBrowserWebWorkerEnv = (() => { + return ( + typeof WorkerGlobalScope !== 'undefined' && + // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && + typeof self.importScripts === 'function' + ); +})(); + +const origin = hasBrowserEnv && window.location.href || 'http://localhost'; + + + +;// ./node_modules/axios/lib/platform/index.js + + + +/* harmony default export */ const platform = ({ + ...common_utils_namespaceObject, + ...browser +}); + +;// ./node_modules/axios/lib/helpers/toURLEncodedForm.js + + + + + + +function toURLEncodedForm(data, options) { + return helpers_toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (platform.isNode && utils.isBuffer(value)) { + this.append(key, value.toString('base64')); + return false; + } + + return helpers.defaultVisitor.apply(this, arguments); + } + }, options)); +} + +;// ./node_modules/axios/lib/helpers/formDataToJSON.js + + + + +/** + * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z'] + * + * @param {string} name - The name of the property to get. + * + * @returns An array of strings. + */ +function parsePropPath(name) { + // foo[x][y][z] + // foo.x.y.z + // foo-x-y-z + // foo x y z + return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => { + return match[0] === '[]' ? '' : match[1] || match[0]; + }); +} + +/** + * Convert an array to an object. + * + * @param {Array} arr - The array to convert to an object. + * + * @returns An object with the same keys and values as the array. + */ +function arrayToObject(arr) { + const obj = {}; + const keys = Object.keys(arr); + let i; + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; +} + +/** + * It takes a FormData object and returns a JavaScript object + * + * @param {string} formData The FormData object to convert to JSON. + * + * @returns {Object | null} The converted object. + */ +function formDataToJSON(formData) { + function buildPath(path, value, target, index) { + let name = path[index++]; + + if (name === '__proto__') return true; + + const isNumericKey = Number.isFinite(+name); + const isLast = index >= path.length; + name = !name && utils.isArray(target) ? target.length : name; + + if (isLast) { + if (utils.hasOwnProp(target, name)) { + target[name] = [target[name], value]; + } else { + target[name] = value; + } + + return !isNumericKey; + } + + if (!target[name] || !utils.isObject(target[name])) { + target[name] = []; + } + + const result = buildPath(path, value, target[name], index); + + if (result && utils.isArray(target[name])) { + target[name] = arrayToObject(target[name]); + } + + return !isNumericKey; + } + + if (utils.isFormData(formData) && utils.isFunction(formData.entries)) { + const obj = {}; + + utils.forEachEntry(formData, (name, value) => { + buildPath(parsePropPath(name), value, obj, 0); + }); + + return obj; + } + + return null; +} + +/* harmony default export */ const helpers_formDataToJSON = (formDataToJSON); + +;// ./node_modules/axios/lib/defaults/index.js + + + + + + + + + + +/** + * It takes a string, tries to parse it, and if it fails, it returns the stringified version + * of the input + * + * @param {any} rawValue - The value to be stringified. + * @param {Function} parser - A function that parses a string into a JavaScript object. + * @param {Function} encoder - A function that takes a value and returns a string. + * + * @returns {string} A stringified version of the rawValue. + */ +function stringifySafely(rawValue, parser, encoder) { + if (utils.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } + } + } + + return (encoder || JSON.stringify)(rawValue); +} + +const defaults = { + + transitional: defaults_transitional, + + adapter: ['xhr', 'http', 'fetch'], + + transformRequest: [function transformRequest(data, headers) { + const contentType = headers.getContentType() || ''; + const hasJSONContentType = contentType.indexOf('application/json') > -1; + const isObjectPayload = utils.isObject(data); + + if (isObjectPayload && utils.isHTMLForm(data)) { + data = new FormData(data); + } + + const isFormData = utils.isFormData(data); + + if (isFormData) { + return hasJSONContentType ? JSON.stringify(helpers_formDataToJSON(data)) : data; + } + + if (utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) || + utils.isReadableStream(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); + return data.toString(); + } + + let isFileList; + + if (isObjectPayload) { + if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + + if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { + const _FormData = this.env && this.env.FormData; + + return helpers_toFormData( + isFileList ? {'files[]': data} : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + + if (isObjectPayload || hasJSONContentType ) { + headers.setContentType('application/json', false); + return stringifySafely(data); + } + + return data; + }], + + transformResponse: [function transformResponse(data) { + const transitional = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional && transitional.forcedJSONParsing; + const JSONRequested = this.responseType === 'json'; + + if (utils.isResponse(data) || utils.isReadableStream(data)) { + return data; + } + + if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { + const silentJSONParsing = transitional && transitional.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw core_AxiosError.from(e, core_AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } + + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + + headers: { + common: { + 'Accept': 'application/json, text/plain, */*', + 'Content-Type': undefined + } + } +}; + +utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { + defaults.headers[method] = {}; +}); + +/* harmony default export */ const lib_defaults = (defaults); + +;// ./node_modules/axios/lib/helpers/parseHeaders.js + + + + +// RawAxiosHeaders whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +const ignoreDuplicateOf = utils.toObjectSet([ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]); + +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} rawHeaders Headers needing to be parsed + * + * @returns {Object} Headers parsed into an object + */ +/* harmony default export */ const parseHeaders = (rawHeaders => { + const parsed = {}; + let key; + let val; + let i; + + rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { + i = line.indexOf(':'); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + + if (!key || (parsed[key] && ignoreDuplicateOf[key])) { + return; + } + + if (key === 'set-cookie') { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + }); + + return parsed; +}); + +;// ./node_modules/axios/lib/core/AxiosHeaders.js + + + + + +const $internals = Symbol('internals'); + +function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); +} + +function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + + return utils.isArray(value) ? value.map(normalizeValue) : String(value); +} + +function parseTokens(str) { + const tokens = Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + + while ((match = tokensRE.exec(str))) { + tokens[match[1]] = match[2]; + } + + return tokens; +} + +const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); + +function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { + if (utils.isFunction(filter)) { + return filter.call(this, value, header); + } + + if (isHeaderNameFilter) { + value = header; + } + + if (!utils.isString(value)) return; + + if (utils.isString(filter)) { + return value.indexOf(filter) !== -1; + } + + if (utils.isRegExp(filter)) { + return filter.test(value); + } +} + +function formatHeader(header) { + return header.trim() + .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { + return char.toUpperCase() + str; + }); +} + +function buildAccessors(obj, header) { + const accessorName = utils.toCamelCase(' ' + header); + + ['get', 'set', 'has'].forEach(methodName => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); +} + +class AxiosHeaders { + constructor(headers) { + headers && this.set(headers); + } + + set(header, valueOrRewrite, rewrite) { + const self = this; + + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); + + if (!lHeader) { + throw new Error('header name must be a non-empty string'); + } + + const key = utils.findKey(self, lHeader); + + if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { + self[key || _header] = normalizeValue(_value); + } + } + + const setHeaders = (headers, _rewrite) => + utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + + if (utils.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite) + } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else if (utils.isHeaders(header)) { + for (const [key, value] of header.entries()) { + setHeader(value, key, rewrite); + } + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + + return this; + } + + get(header, parser) { + header = normalizeHeader(header); + + if (header) { + const key = utils.findKey(this, header); + + if (key) { + const value = this[key]; + + if (!parser) { + return value; + } + + if (parser === true) { + return parseTokens(value); + } + + if (utils.isFunction(parser)) { + return parser.call(this, value, key); + } + + if (utils.isRegExp(parser)) { + return parser.exec(value); + } + + throw new TypeError('parser must be boolean|regexp|function'); + } + } + } + + has(header, matcher) { + header = normalizeHeader(header); + + if (header) { + const key = utils.findKey(this, header); + + return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + } + + return false; + } + + delete(header, matcher) { + const self = this; + let deleted = false; + + function deleteHeader(_header) { + _header = normalizeHeader(_header); + + if (_header) { + const key = utils.findKey(self, _header); + + if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { + delete self[key]; + + deleted = true; + } + } + } + + if (utils.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + + return deleted; + } + + clear(matcher) { + const keys = Object.keys(this); + let i = keys.length; + let deleted = false; + + while (i--) { + const key = keys[i]; + if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + + return deleted; + } + + normalize(format) { + const self = this; + const headers = {}; + + utils.forEach(this, (value, header) => { + const key = utils.findKey(headers, header); + + if (key) { + self[key] = normalizeValue(value); + delete self[header]; + return; + } + + const normalized = format ? formatHeader(header) : String(header).trim(); + + if (normalized !== header) { + delete self[header]; + } + + self[normalized] = normalizeValue(value); + + headers[normalized] = true; + }); + + return this; + } + + concat(...targets) { + return this.constructor.concat(this, ...targets); + } + + toJSON(asStrings) { + const obj = Object.create(null); + + utils.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value); + }); + + return obj; + } + + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n'); + } + + get [Symbol.toStringTag]() { + return 'AxiosHeaders'; + } + + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + + static concat(first, ...targets) { + const computed = new this(first); + + targets.forEach((target) => computed.set(target)); + + return computed; + } + + static accessor(header) { + const internals = this[$internals] = (this[$internals] = { + accessors: {} + }); + + const accessors = internals.accessors; + const prototype = this.prototype; + + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); + + if (!accessors[lHeader]) { + buildAccessors(prototype, _header); + accessors[lHeader] = true; + } + } + + utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + + return this; + } +} + +AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); + +// reserved names hotfix +utils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } + } +}); + +utils.freezeMethods(AxiosHeaders); + +/* harmony default export */ const core_AxiosHeaders = (AxiosHeaders); + +;// ./node_modules/axios/lib/core/transformData.js + + + + + + +/** + * Transform the data for a request or a response + * + * @param {Array|Function} fns A single function or Array of functions + * @param {?Object} response The response object + * + * @returns {*} The resulting transformed data + */ +function transformData(fns, response) { + const config = this || lib_defaults; + const context = response || config; + const headers = core_AxiosHeaders.from(context.headers); + let data = context.data; + + utils.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); + }); + + headers.normalize(); + + return data; +} + +;// ./node_modules/axios/lib/cancel/isCancel.js + + +function isCancel(value) { + return !!(value && value.__CANCEL__); +} + +;// ./node_modules/axios/lib/cancel/CanceledError.js + + + + + +/** + * A `CanceledError` is an object that is thrown when an operation is canceled. + * + * @param {string=} message The message. + * @param {Object=} config The config. + * @param {Object=} request The request. + * + * @returns {CanceledError} The created error. + */ +function CanceledError(message, config, request) { + // eslint-disable-next-line no-eq-null,eqeqeq + core_AxiosError.call(this, message == null ? 'canceled' : message, core_AxiosError.ERR_CANCELED, config, request); + this.name = 'CanceledError'; +} + +utils.inherits(CanceledError, core_AxiosError, { + __CANCEL__: true +}); + +/* harmony default export */ const cancel_CanceledError = (CanceledError); + +;// ./node_modules/axios/lib/core/settle.js + + + + +/** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + * + * @returns {object} The response. + */ +function settle(resolve, reject, response) { + const validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new core_AxiosError( + 'Request failed with status code ' + response.status, + [core_AxiosError.ERR_BAD_REQUEST, core_AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } +} + +;// ./node_modules/axios/lib/helpers/parseProtocol.js + + +function parseProtocol(url) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ''; +} + +;// ./node_modules/axios/lib/helpers/speedometer.js + + +/** + * Calculate data maxRate + * @param {Number} [samplesCount= 10] + * @param {Number} [min= 1000] + * @returns {Function} + */ +function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + + min = min !== undefined ? min : 1000; + + return function push(chunkLength) { + const now = Date.now(); + + const startedAt = timestamps[tail]; + + if (!firstSampleTS) { + firstSampleTS = now; + } + + bytes[head] = chunkLength; + timestamps[head] = now; + + let i = tail; + let bytesCount = 0; + + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + + head = (head + 1) % samplesCount; + + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + + if (now - firstSampleTS < min) { + return; + } + + const passed = startedAt && now - startedAt; + + return passed ? Math.round(bytesCount * 1000 / passed) : undefined; + }; +} + +/* harmony default export */ const helpers_speedometer = (speedometer); + +;// ./node_modules/axios/lib/helpers/throttle.js +/** + * Throttle decorator + * @param {Function} fn + * @param {Number} freq + * @return {Function} + */ +function throttle(fn, freq) { + let timestamp = 0; + let threshold = 1000 / freq; + let lastArgs; + let timer; + + const invoke = (args, now = Date.now()) => { + timestamp = now; + lastArgs = null; + if (timer) { + clearTimeout(timer); + timer = null; + } + fn.apply(null, args); + } + + const throttled = (...args) => { + const now = Date.now(); + const passed = now - timestamp; + if ( passed >= threshold) { + invoke(args, now); + } else { + lastArgs = args; + if (!timer) { + timer = setTimeout(() => { + timer = null; + invoke(lastArgs) + }, threshold - passed); + } + } + } + + const flush = () => lastArgs && invoke(lastArgs); + + return [throttled, flush]; +} + +/* harmony default export */ const helpers_throttle = (throttle); + +;// ./node_modules/axios/lib/helpers/progressEventReducer.js + + + + +const progressEventReducer = (listener, isDownloadStream, freq = 3) => { + let bytesNotified = 0; + const _speedometer = helpers_speedometer(50, 250); + + return helpers_throttle(e => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : undefined; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange = loaded <= total; + + bytesNotified = loaded; + + const data = { + loaded, + total, + progress: total ? (loaded / total) : undefined, + bytes: progressBytes, + rate: rate ? rate : undefined, + estimated: rate && total && inRange ? (total - loaded) / rate : undefined, + event: e, + lengthComputable: total != null, + [isDownloadStream ? 'download' : 'upload']: true + }; + + listener(data); + }, freq); +} + +const progressEventDecorator = (total, throttled) => { + const lengthComputable = total != null; + + return [(loaded) => throttled[0]({ + lengthComputable, + total, + loaded + }), throttled[1]]; +} + +const asyncDecorator = (fn) => (...args) => utils.asap(() => fn(...args)); + +;// ./node_modules/axios/lib/helpers/isURLSameOrigin.js + + +/* harmony default export */ const isURLSameOrigin = (platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => { + url = new URL(url, platform.origin); + + return ( + origin.protocol === url.protocol && + origin.host === url.host && + (isMSIE || origin.port === url.port) + ); +})( + new URL(platform.origin), + platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) +) : () => true); + +;// ./node_modules/axios/lib/helpers/cookies.js + + + +/* harmony default export */ const cookies = (platform.hasStandardBrowserEnv ? + + // Standard browser envs support document.cookie + { + write(name, value, expires, path, domain, secure) { + const cookie = [name + '=' + encodeURIComponent(value)]; + + utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString()); + + utils.isString(path) && cookie.push('path=' + path); + + utils.isString(domain) && cookie.push('domain=' + domain); + + secure === true && cookie.push('secure'); + + document.cookie = cookie.join('; '); + }, + + read(name) { + const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, + + remove(name) { + this.write(name, '', Date.now() - 86400000); + } + } + + : + + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() {}, + read() { + return null; + }, + remove() {} + }); + + +;// ./node_modules/axios/lib/helpers/isAbsoluteURL.js + + +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); +} + +;// ./node_modules/axios/lib/helpers/combineURLs.js + + +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * + * @returns {string} The combined URL + */ +function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +} + +;// ./node_modules/axios/lib/core/buildFullPath.js + + + + + +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * + * @returns {string} The combined full path + */ +function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +} + +;// ./node_modules/axios/lib/core/mergeConfig.js + + + + + +const headersToObject = (thing) => thing instanceof core_AxiosHeaders ? { ...thing } : thing; + +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * + * @returns {Object} New object resulting from merging config2 to config1 + */ +function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + const config = {}; + + function getMergedValue(target, source, prop, caseless) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge.call({caseless}, target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } + + // eslint-disable-next-line consistent-return + function mergeDeepProperties(a, b, prop , caseless) { + if (!utils.isUndefined(b)) { + return getMergedValue(a, b, prop , caseless); + } else if (!utils.isUndefined(a)) { + return getMergedValue(undefined, a, prop , caseless); + } + } + + // eslint-disable-next-line consistent-return + function valueFromConfig2(a, b) { + if (!utils.isUndefined(b)) { + return getMergedValue(undefined, b); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(a, b) { + if (!utils.isUndefined(b)) { + return getMergedValue(undefined, b); + } else if (!utils.isUndefined(a)) { + return getMergedValue(undefined, a); + } + } + + // eslint-disable-next-line consistent-return + function mergeDirectKeys(a, b, prop) { + if (prop in config2) { + return getMergedValue(a, b); + } else if (prop in config1) { + return getMergedValue(undefined, a); + } + } + + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true) + }; + + utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + const merge = mergeMap[prop] || mergeDeepProperties; + const configValue = merge(config1[prop], config2[prop], prop); + (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); + + return config; +} + +;// ./node_modules/axios/lib/helpers/resolveConfig.js + + + + + + + + + +/* harmony default export */ const resolveConfig = ((config) => { + const newConfig = mergeConfig({}, config); + + let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig; + + newConfig.headers = headers = core_AxiosHeaders.from(headers); + + newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer); + + // HTTP basic authentication + if (auth) { + headers.set('Authorization', 'Basic ' + + btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : '')) + ); + } + + let contentType; + + if (utils.isFormData(data)) { + if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { + headers.setContentType(undefined); // Let the browser set it + } else if ((contentType = headers.getContentType()) !== false) { + // fix semicolon duplication issue for ReactNative FormData implementation + const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : []; + headers.setContentType([type || 'multipart/form-data', ...tokens].join('; ')); + } + } + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + + if (platform.hasStandardBrowserEnv) { + withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); + + if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) { + // Add xsrf header + const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); + + if (xsrfValue) { + headers.set(xsrfHeaderName, xsrfValue); + } + } + } + + return newConfig; +}); + + +;// ./node_modules/axios/lib/adapters/xhr.js + + + + + + + + + + + +const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; + +/* harmony default export */ const xhr = (isXHRAdapterSupported && function (config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + const _config = resolveConfig(config); + let requestData = _config.data; + const requestHeaders = core_AxiosHeaders.from(_config.headers).normalize(); + let {responseType, onUploadProgress, onDownloadProgress} = _config; + let onCanceled; + let uploadThrottled, downloadThrottled; + let flushUpload, flushDownload; + + function done() { + flushUpload && flushUpload(); // flush events + flushDownload && flushDownload(); // flush events + + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + + _config.signal && _config.signal.removeEventListener('abort', onCanceled); + } + + let request = new XMLHttpRequest(); + + request.open(_config.method.toUpperCase(), _config.url, true); + + // Set the request timeout in MS + request.timeout = _config.timeout; + + function onloadend() { + if (!request) { + return; + } + // Prepare the response + const responseHeaders = core_AxiosHeaders.from( + 'getAllResponseHeaders' in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === 'text' || responseType === 'json' ? + request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config, + request + }; + + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + + // Clean up request + request = null; + } + + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(new core_AxiosError('Request aborted', core_AxiosError.ECONNABORTED, config, request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(new core_AxiosError('Network Error', core_AxiosError.ERR_NETWORK, config, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded'; + const transitional = _config.transitional || defaults_transitional; + if (_config.timeoutErrorMessage) { + timeoutErrorMessage = _config.timeoutErrorMessage; + } + reject(new core_AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? core_AxiosError.ETIMEDOUT : core_AxiosError.ECONNABORTED, + config, + request)); + + // Clean up request + request = null; + }; + + // Remove Content-Type if data is undefined + requestData === undefined && requestHeaders.setContentType(null); + + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + + // Add withCredentials to request if needed + if (!utils.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; + } + + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = _config.responseType; + } + + // Handle progress if needed + if (onDownloadProgress) { + ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true)); + request.addEventListener('progress', downloadThrottled); + } + + // Not all browsers support upload events + if (onUploadProgress && request.upload) { + ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress)); + + request.upload.addEventListener('progress', uploadThrottled); + + request.upload.addEventListener('loadend', flushUpload); + } + + if (_config.cancelToken || _config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = cancel => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new cancel_CanceledError(null, config, request) : cancel); + request.abort(); + request = null; + }; + + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled); + } + } + + const protocol = parseProtocol(_config.url); + + if (protocol && platform.protocols.indexOf(protocol) === -1) { + reject(new core_AxiosError('Unsupported protocol ' + protocol + ':', core_AxiosError.ERR_BAD_REQUEST, config)); + return; + } + + + // Send the request + request.send(requestData || null); + }); +}); + +;// ./node_modules/axios/lib/helpers/composeSignals.js + + + + +const composeSignals = (signals, timeout) => { + const {length} = (signals = signals ? signals.filter(Boolean) : []); + + if (timeout || length) { + let controller = new AbortController(); + + let aborted; + + const onabort = function (reason) { + if (!aborted) { + aborted = true; + unsubscribe(); + const err = reason instanceof Error ? reason : this.reason; + controller.abort(err instanceof core_AxiosError ? err : new cancel_CanceledError(err instanceof Error ? err.message : err)); + } + } + + let timer = timeout && setTimeout(() => { + timer = null; + onabort(new core_AxiosError(`timeout ${timeout} of ms exceeded`, core_AxiosError.ETIMEDOUT)) + }, timeout) + + const unsubscribe = () => { + if (signals) { + timer && clearTimeout(timer); + timer = null; + signals.forEach(signal => { + signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort); + }); + signals = null; + } + } + + signals.forEach((signal) => signal.addEventListener('abort', onabort)); + + const {signal} = controller; + + signal.unsubscribe = () => utils.asap(unsubscribe); + + return signal; + } +} + +/* harmony default export */ const helpers_composeSignals = (composeSignals); + +;// ./node_modules/axios/lib/helpers/trackStream.js + +const streamChunk = function* (chunk, chunkSize) { + let len = chunk.byteLength; + + if (!chunkSize || len < chunkSize) { + yield chunk; + return; + } + + let pos = 0; + let end; + + while (pos < len) { + end = pos + chunkSize; + yield chunk.slice(pos, end); + pos = end; + } +} + +const readBytes = async function* (iterable, chunkSize) { + for await (const chunk of readStream(iterable)) { + yield* streamChunk(chunk, chunkSize); + } +} + +const readStream = async function* (stream) { + if (stream[Symbol.asyncIterator]) { + yield* stream; + return; + } + + const reader = stream.getReader(); + try { + for (;;) { + const {done, value} = await reader.read(); + if (done) { + break; + } + yield value; + } + } finally { + await reader.cancel(); + } +} + +const trackStream = (stream, chunkSize, onProgress, onFinish) => { + const iterator = readBytes(stream, chunkSize); + + let bytes = 0; + let done; + let _onFinish = (e) => { + if (!done) { + done = true; + onFinish && onFinish(e); + } + } + + return new ReadableStream({ + async pull(controller) { + try { + const {done, value} = await iterator.next(); + + if (done) { + _onFinish(); + controller.close(); + return; + } + + let len = value.byteLength; + if (onProgress) { + let loadedBytes = bytes += len; + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); + } catch (err) { + _onFinish(err); + throw err; + } + }, + cancel(reason) { + _onFinish(reason); + return iterator.return(); + } + }, { + highWaterMark: 2 + }) +} + +;// ./node_modules/axios/lib/adapters/fetch.js + + + + + + + + + + +const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function'; +const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function'; + +// used only inside the fetch adapter +const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? + ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : + async (str) => new Uint8Array(await new Response(str).arrayBuffer()) +); + +const test = (fn, ...args) => { + try { + return !!fn(...args); + } catch (e) { + return false + } +} + +const supportsRequestStream = isReadableStreamSupported && test(() => { + let duplexAccessed = false; + + const hasContentType = new Request(platform.origin, { + body: new ReadableStream(), + method: 'POST', + get duplex() { + duplexAccessed = true; + return 'half'; + }, + }).headers.has('Content-Type'); + + return duplexAccessed && !hasContentType; +}); + +const DEFAULT_CHUNK_SIZE = 64 * 1024; + +const supportsResponseStream = isReadableStreamSupported && + test(() => utils.isReadableStream(new Response('').body)); + + +const resolvers = { + stream: supportsResponseStream && ((res) => res.body) +}; + +isFetchSupported && (((res) => { + ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => { + !resolvers[type] && (resolvers[type] = utils.isFunction(res[type]) ? (res) => res[type]() : + (_, config) => { + throw new core_AxiosError(`Response type '${type}' is not supported`, core_AxiosError.ERR_NOT_SUPPORT, config); + }) + }); +})(new Response)); + +const getBodyLength = async (body) => { + if (body == null) { + return 0; + } + + if(utils.isBlob(body)) { + return body.size; + } + + if(utils.isSpecCompliantForm(body)) { + const _request = new Request(platform.origin, { + method: 'POST', + body, + }); + return (await _request.arrayBuffer()).byteLength; + } + + if(utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) { + return body.byteLength; + } + + if(utils.isURLSearchParams(body)) { + body = body + ''; + } + + if(utils.isString(body)) { + return (await encodeText(body)).byteLength; + } +} + +const resolveBodyLength = async (headers, body) => { + const length = utils.toFiniteNumber(headers.getContentLength()); + + return length == null ? getBodyLength(body) : length; +} + +/* harmony default export */ const adapters_fetch = (isFetchSupported && (async (config) => { + let { + url, + method, + data, + signal, + cancelToken, + timeout, + onDownloadProgress, + onUploadProgress, + responseType, + headers, + withCredentials = 'same-origin', + fetchOptions + } = resolveConfig(config); + + responseType = responseType ? (responseType + '').toLowerCase() : 'text'; + + let composedSignal = helpers_composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + + let request; + + const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { + composedSignal.unsubscribe(); + }); + + let requestContentLength; + + try { + if ( + onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && + (requestContentLength = await resolveBodyLength(headers, data)) !== 0 + ) { + let _request = new Request(url, { + method: 'POST', + body: data, + duplex: "half" + }); + + let contentTypeHeader; + + if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { + headers.setContentType(contentTypeHeader) + } + + if (_request.body) { + const [onProgress, flush] = progressEventDecorator( + requestContentLength, + progressEventReducer(asyncDecorator(onUploadProgress)) + ); + + data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); + } + } + + if (!utils.isString(withCredentials)) { + withCredentials = withCredentials ? 'include' : 'omit'; + } + + // Cloudflare Workers throws when credentials are defined + // see https://github.com/cloudflare/workerd/issues/902 + const isCredentialsSupported = "credentials" in Request.prototype; + request = new Request(url, { + ...fetchOptions, + signal: composedSignal, + method: method.toUpperCase(), + headers: headers.normalize().toJSON(), + body: data, + duplex: "half", + credentials: isCredentialsSupported ? withCredentials : undefined + }); + + let response = await fetch(request); + + const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); + + if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) { + const options = {}; + + ['status', 'statusText', 'headers'].forEach(prop => { + options[prop] = response[prop]; + }); + + const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length')); + + const [onProgress, flush] = onDownloadProgress && progressEventDecorator( + responseContentLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true) + ) || []; + + response = new Response( + trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { + flush && flush(); + unsubscribe && unsubscribe(); + }), + options + ); + } + + responseType = responseType || 'text'; + + let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config); + + !isStreamResponse && unsubscribe && unsubscribe(); + + return await new Promise((resolve, reject) => { + settle(resolve, reject, { + data: responseData, + headers: core_AxiosHeaders.from(response.headers), + status: response.status, + statusText: response.statusText, + config, + request + }) + }) + } catch (err) { + unsubscribe && unsubscribe(); + + if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) { + throw Object.assign( + new core_AxiosError('Network Error', core_AxiosError.ERR_NETWORK, config, request), + { + cause: err.cause || err + } + ) + } + + throw core_AxiosError.from(err, err && err.code, config, request); + } +})); + + + +;// ./node_modules/axios/lib/adapters/adapters.js + + + + + + +const knownAdapters = { + http: helpers_null, + xhr: xhr, + fetch: adapters_fetch +} + +utils.forEach(knownAdapters, (fn, value) => { + if (fn) { + try { + Object.defineProperty(fn, 'name', {value}); + } catch (e) { + // eslint-disable-next-line no-empty + } + Object.defineProperty(fn, 'adapterName', {value}); + } +}); + +const renderReason = (reason) => `- ${reason}`; + +const isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false; + +/* harmony default export */ const adapters = ({ + getAdapter: (adapters) => { + adapters = utils.isArray(adapters) ? adapters : [adapters]; + + const {length} = adapters; + let nameOrAdapter; + let adapter; + + const rejectedReasons = {}; + + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters[i]; + let id; + + adapter = nameOrAdapter; + + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + + if (adapter === undefined) { + throw new core_AxiosError(`Unknown adapter '${id}'`); + } + } + + if (adapter) { + break; + } + + rejectedReasons[id || '#' + i] = adapter; + } + + if (!adapter) { + + const reasons = Object.entries(rejectedReasons) + .map(([id, state]) => `adapter ${id} ` + + (state === false ? 'is not supported by the environment' : 'is not available in the build') + ); + + let s = length ? + (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : + 'as no adapter specified'; + + throw new core_AxiosError( + `There is no suitable adapter to dispatch the request ` + s, + 'ERR_NOT_SUPPORT' + ); + } + + return adapter; + }, + adapters: knownAdapters +}); + +;// ./node_modules/axios/lib/core/dispatchRequest.js + + + + + + + + + +/** + * Throws a `CanceledError` if cancellation has been requested. + * + * @param {Object} config The config that is to be used for the request + * + * @returns {void} + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + + if (config.signal && config.signal.aborted) { + throw new cancel_CanceledError(null, config); + } +} + +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * + * @returns {Promise} The Promise to be fulfilled + */ +function dispatchRequest(config) { + throwIfCancellationRequested(config); + + config.headers = core_AxiosHeaders.from(config.headers); + + // Transform request data + config.data = transformData.call( + config, + config.transformRequest + ); + + if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { + config.headers.setContentType('application/x-www-form-urlencoded', false); + } + + const adapter = adapters.getAdapter(config.adapter || lib_defaults.adapter); + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData.call( + config, + config.transformResponse, + response + ); + + response.headers = core_AxiosHeaders.from(response.headers); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + config.transformResponse, + reason.response + ); + reason.response.headers = core_AxiosHeaders.from(reason.response.headers); + } + } + + return Promise.reject(reason); + }); +} + +;// ./node_modules/axios/lib/env/data.js +const VERSION = "1.7.9"; +;// ./node_modules/axios/lib/helpers/validator.js + + + + + +const validators = {}; + +// eslint-disable-next-line func-names +['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => { + validators[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; +}); + +const deprecatedWarnings = {}; + +/** + * Transitional option validator + * + * @param {function|boolean?} validator - set to false if the transitional option has been removed + * @param {string?} version - deprecated version / removed since version + * @param {string?} message - some message with additional info + * + * @returns {function} + */ +validators.transitional = function transitional(validator, version, message) { + function formatMessage(opt, desc) { + return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + } + + // eslint-disable-next-line func-names + return (value, opt, opts) => { + if (validator === false) { + throw new core_AxiosError( + formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), + core_AxiosError.ERR_DEPRECATED + ); + } + + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); + } + + return validator ? validator(value, opt, opts) : true; + }; +}; + +validators.spelling = function spelling(correctSpelling) { + return (value, opt) => { + // eslint-disable-next-line no-console + console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); + return true; + } +}; + +/** + * Assert object's properties type + * + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown + * + * @returns {object} + */ + +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== 'object') { + throw new core_AxiosError('options must be an object', core_AxiosError.ERR_BAD_OPTION_VALUE); + } + const keys = Object.keys(options); + let i = keys.length; + while (i-- > 0) { + const opt = keys[i]; + const validator = schema[opt]; + if (validator) { + const value = options[opt]; + const result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new core_AxiosError('option ' + opt + ' must be ' + result, core_AxiosError.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new core_AxiosError('Unknown option ' + opt, core_AxiosError.ERR_BAD_OPTION); + } + } +} + +/* harmony default export */ const validator = ({ + assertOptions, + validators +}); + +;// ./node_modules/axios/lib/core/Axios.js + + + + + + + + + + + +const Axios_validators = validator.validators; + +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + * + * @return {Axios} A new instance of Axios + */ +class Axios { + constructor(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new core_InterceptorManager(), + response: new core_InterceptorManager() + }; + } + + /** + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled + */ + async request(configOrUrl, config) { + try { + return await this._request(configOrUrl, config); + } catch (err) { + if (err instanceof Error) { + let dummy = {}; + + Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error()); + + // slice off the Error: ... line + const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : ''; + try { + if (!err.stack) { + err.stack = stack; + // match without the 2 top stack lines + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) { + err.stack += '\n' + stack + } + } catch (e) { + // ignore the case where "stack" is an un-writable property + } + } + + throw err; + } + } + + _request(configOrUrl, config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof configOrUrl === 'string') { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } + + config = mergeConfig(this.defaults, config); + + const {transitional, paramsSerializer, headers} = config; + + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean), + forcedJSONParsing: Axios_validators.transitional(Axios_validators.boolean), + clarifyTimeoutError: Axios_validators.transitional(Axios_validators.boolean) + }, false); + } + + if (paramsSerializer != null) { + if (utils.isFunction(paramsSerializer)) { + config.paramsSerializer = { + serialize: paramsSerializer + } + } else { + validator.assertOptions(paramsSerializer, { + encode: Axios_validators.function, + serialize: Axios_validators.function + }, true); + } + } + + validator.assertOptions(config, { + baseUrl: Axios_validators.spelling('baseURL'), + withXsrfToken: Axios_validators.spelling('withXSRFToken') + }, true); + + // Set config.method + config.method = (config.method || this.defaults.method || 'get').toLowerCase(); + + // Flatten headers + let contextHeaders = headers && utils.merge( + headers.common, + headers[config.method] + ); + + headers && utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + (method) => { + delete headers[method]; + } + ); + + config.headers = core_AxiosHeaders.concat(contextHeaders, headers); + + // filter out skipped interceptors + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + + let promise; + let i = 0; + let len; + + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), undefined]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + + promise = Promise.resolve(config); + + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + + return promise; + } + + len = requestInterceptorChain.length; + + let newConfig = config; + + i = 0; + + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + + i = 0; + len = responseInterceptorChain.length; + + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + + return promise; + } + + getUri(config) { + config = mergeConfig(this.defaults, config); + const fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); + } +} + +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method, + url, + data: (config || {}).data + })); + }; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig(config || {}, { + method, + headers: isForm ? { + 'Content-Type': 'multipart/form-data' + } : {}, + url, + data + })); + }; + } + + Axios.prototype[method] = generateHTTPMethod(); + + Axios.prototype[method + 'Form'] = generateHTTPMethod(true); +}); + +/* harmony default export */ const core_Axios = (Axios); + +;// ./node_modules/axios/lib/cancel/CancelToken.js + + + + +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @param {Function} executor The executor function. + * + * @returns {CancelToken} + */ +class CancelToken { + constructor(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + let resolvePromise; + + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + const token = this; + + // eslint-disable-next-line func-names + this.promise.then(cancel => { + if (!token._listeners) return; + + let i = token._listeners.length; + + while (i-- > 0) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + + // eslint-disable-next-line func-names + this.promise.then = onfulfilled => { + let _resolve; + // eslint-disable-next-line func-names + const promise = new Promise(resolve => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + + return promise; + }; + + executor(function cancel(message, config, request) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new cancel_CanceledError(message, config, request); + resolvePromise(token.reason); + }); + } + + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } + + /** + * Subscribe to the cancel signal + */ + + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } + + /** + * Unsubscribe from the cancel signal + */ + + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } + } + + toAbortSignal() { + const controller = new AbortController(); + + const abort = (err) => { + controller.abort(err); + }; + + this.subscribe(abort); + + controller.signal.unsubscribe = () => this.unsubscribe(abort); + + return controller.signal; + } + + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + static source() { + let cancel; + const token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token, + cancel + }; + } +} + +/* harmony default export */ const cancel_CancelToken = (CancelToken); + +;// ./node_modules/axios/lib/helpers/spread.js + + +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * + * @returns {Function} + */ +function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +} + +;// ./node_modules/axios/lib/helpers/isAxiosError.js + + + + +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +function isAxiosError(payload) { + return utils.isObject(payload) && (payload.isAxiosError === true); +} + +;// ./node_modules/axios/lib/helpers/HttpStatusCode.js +const HttpStatusCode = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511, +}; + +Object.entries(HttpStatusCode).forEach(([key, value]) => { + HttpStatusCode[value] = key; +}); + +/* harmony default export */ const helpers_HttpStatusCode = (HttpStatusCode); + +;// ./node_modules/axios/lib/axios.js + + + + + + + + + + + + + + + + + + + + +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * + * @returns {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + const context = new core_Axios(defaultConfig); + const instance = bind(core_Axios.prototype.request, context); + + // Copy axios.prototype to instance + utils.extend(instance, core_Axios.prototype, context, {allOwnKeys: true}); + + // Copy context to instance + utils.extend(instance, context, null, {allOwnKeys: true}); + + // Factory for creating new instances + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; + + return instance; +} + +// Create the default instance to be exported +const axios = createInstance(lib_defaults); + +// Expose Axios class to allow class inheritance +axios.Axios = core_Axios; + +// Expose Cancel & CancelToken +axios.CanceledError = cancel_CanceledError; +axios.CancelToken = cancel_CancelToken; +axios.isCancel = isCancel; +axios.VERSION = VERSION; +axios.toFormData = helpers_toFormData; + +// Expose AxiosError class +axios.AxiosError = core_AxiosError; + +// alias for CanceledError for backward compatibility +axios.Cancel = axios.CanceledError; + +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; + +axios.spread = spread; + +// Expose isAxiosError +axios.isAxiosError = isAxiosError; + +// Expose mergeConfig +axios.mergeConfig = mergeConfig; + +axios.AxiosHeaders = core_AxiosHeaders; + +axios.formToJSON = thing => helpers_formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing); + +axios.getAdapter = adapters.getAdapter; + +axios.HttpStatusCode = helpers_HttpStatusCode; + +axios.default = axios; + +// this module should only have a default export +/* harmony default export */ const lib_axios = (axios); + +;// ./src/http-client/axios-client.ts + +var axiosClient = lib_axios; +var create = lib_axios.create; + +/***/ }), + +/***/ 9983: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + vt: () => (/* binding */ create), + ok: () => (/* binding */ httpClient) +}); + +// UNUSED EXPORTS: CancelToken + +;// ./src/http-client/types.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var CancelToken = function () { + function CancelToken(executor) { + var _this = this; + _classCallCheck(this, CancelToken); + var resolvePromise; + this.promise = new Promise(function (resolve) { + resolvePromise = resolve; + }); + executor(function (reason) { + _this.reason = reason; + resolvePromise(); + }); + } + return _createClass(CancelToken, [{ + key: "throwIfRequested", + value: function throwIfRequested() { + if (this.reason) { + throw new Error(this.reason); + } + } + }]); +}(); +;// ./src/http-client/index.ts +var httpClient; +var create; +if (true) { + var axiosModule = __webpack_require__(6121); + httpClient = axiosModule.axiosClient; + create = axiosModule.create; +} else { var fetchModule; } + + + +/***/ }), + +/***/ 4356: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ AccountRequiresMemoError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.Cu), +/* harmony export */ BadRequestError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.v7), +/* harmony export */ BadResponseError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.nS), +/* harmony export */ Config: () => (/* reexport safe */ _config__WEBPACK_IMPORTED_MODULE_1__.T), +/* harmony export */ Federation: () => (/* reexport module object */ _federation__WEBPACK_IMPORTED_MODULE_4__), +/* harmony export */ Friendbot: () => (/* reexport module object */ _friendbot__WEBPACK_IMPORTED_MODULE_6__), +/* harmony export */ Horizon: () => (/* reexport module object */ _horizon__WEBPACK_IMPORTED_MODULE_7__), +/* harmony export */ NetworkError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.Dr), +/* harmony export */ NotFoundError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_0__.m_), +/* harmony export */ StellarToml: () => (/* reexport module object */ _stellartoml__WEBPACK_IMPORTED_MODULE_3__), +/* harmony export */ Utils: () => (/* reexport safe */ _utils__WEBPACK_IMPORTED_MODULE_2__.A), +/* harmony export */ WebAuth: () => (/* reexport module object */ _webauth__WEBPACK_IMPORTED_MODULE_5__), +/* harmony export */ contract: () => (/* reexport module object */ _contract__WEBPACK_IMPORTED_MODULE_9__), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ rpc: () => (/* reexport module object */ _rpc__WEBPACK_IMPORTED_MODULE_8__) +/* harmony export */ }); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5976); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8732); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3121); +/* harmony import */ var _stellartoml__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3898); +/* harmony import */ var _federation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7600); +/* harmony import */ var _webauth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(5479); +/* harmony import */ var _friendbot__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(8242); +/* harmony import */ var _horizon__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(8733); +/* harmony import */ var _rpc__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(3496); +/* harmony import */ var _contract__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(6299); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__); +/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {}; +/* harmony reexport (unknown) */ for(const __WEBPACK_IMPORT_KEY__ in _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__) if(["default","Config","Utils","StellarToml","Federation","WebAuth","Friendbot","Horizon","rpc","contract","AccountRequiresMemoError","BadRequestError","BadResponseError","NetworkError","NotFoundError"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = () => _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_10__[__WEBPACK_IMPORT_KEY__] +/* harmony reexport (unknown) */ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__); +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + + + + + + + + + + + + + + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (module.exports); +if (typeof __webpack_require__.g.__USE_AXIOS__ === 'undefined') { + __webpack_require__.g.__USE_AXIOS__ = true; +} +if (typeof __webpack_require__.g.__USE_EVENTSOURCE__ === 'undefined') { + __webpack_require__.g.__USE_EVENTSOURCE__ = false; +} + +/***/ }), + +/***/ 4076: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ j: () => (/* binding */ Api) +/* harmony export */ }); +var Api; +(function (_Api) { + var GetTransactionStatus = function (GetTransactionStatus) { + GetTransactionStatus["SUCCESS"] = "SUCCESS"; + GetTransactionStatus["NOT_FOUND"] = "NOT_FOUND"; + GetTransactionStatus["FAILED"] = "FAILED"; + return GetTransactionStatus; + }({}); + _Api.GetTransactionStatus = GetTransactionStatus; + function isSimulationError(sim) { + return 'error' in sim; + } + _Api.isSimulationError = isSimulationError; + function isSimulationSuccess(sim) { + return 'transactionData' in sim; + } + _Api.isSimulationSuccess = isSimulationSuccess; + function isSimulationRestore(sim) { + return isSimulationSuccess(sim) && 'restorePreamble' in sim && !!sim.restorePreamble.transactionData; + } + _Api.isSimulationRestore = isSimulationRestore; + function isSimulationRaw(sim) { + return !sim._parsed; + } + _Api.isSimulationRaw = isSimulationRaw; +})(Api || (Api = {})); + +/***/ }), + +/***/ 3496: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + Api: () => (/* reexport */ api/* Api */.j), + AxiosClient: () => (/* reexport */ axios), + BasicSleepStrategy: () => (/* reexport */ BasicSleepStrategy), + Durability: () => (/* reexport */ Durability), + LinearSleepStrategy: () => (/* reexport */ LinearSleepStrategy), + Server: () => (/* reexport */ RpcServer), + assembleTransaction: () => (/* reexport */ transaction/* assembleTransaction */.X), + "default": () => (/* binding */ rpc), + parseRawEvents: () => (/* reexport */ parsers/* parseRawEvents */.fG), + parseRawSimulation: () => (/* reexport */ parsers/* parseRawSimulation */.jr) +}); + +// EXTERNAL MODULE: ./src/rpc/api.ts +var api = __webpack_require__(4076); +// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js +var URI = __webpack_require__(4193); +var URI_default = /*#__PURE__*/__webpack_require__.n(URI); +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./src/http-client/index.ts + 1 modules +var http_client = __webpack_require__(9983); +;// ./src/rpc/axios.ts + +var version = "13.1.0"; +var AxiosClient = (0,http_client/* create */.vt)({ + headers: { + 'X-Client-Name': 'js-soroban-client', + 'X-Client-Version': version + } +}); +/* harmony default export */ const axios = (AxiosClient); +;// ./src/rpc/jsonrpc.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } + +function jsonrpc_hasOwnProperty(obj, prop) { + return obj.hasOwnProperty(prop); +} +function postObject(_x, _x2) { + return _postObject.apply(this, arguments); +} +function _postObject() { + _postObject = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(url, method) { + var param, + response, + _response$data, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + param = _args.length > 2 && _args[2] !== undefined ? _args[2] : null; + _context.next = 3; + return axios.post(url, { + jsonrpc: "2.0", + id: 1, + method: method, + params: param + }); + case 3: + response = _context.sent; + if (!jsonrpc_hasOwnProperty(response.data, "error")) { + _context.next = 8; + break; + } + throw response.data.error; + case 8: + return _context.abrupt("return", (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.result); + case 9: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _postObject.apply(this, arguments); +} +// EXTERNAL MODULE: ./src/rpc/transaction.ts +var transaction = __webpack_require__(8680); +// EXTERNAL MODULE: ./src/rpc/parsers.ts +var parsers = __webpack_require__(784); +// EXTERNAL MODULE: ./src/utils.ts +var utils = __webpack_require__(3121); +;// ./src/rpc/server.ts +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +function server_typeof(o) { "@babel/helpers - typeof"; return server_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, server_typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function server_regeneratorRuntime() { "use strict"; server_regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == server_typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(server_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function server_asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function server_asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { server_asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == server_typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != server_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != server_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + + + + + + +var SUBMIT_TRANSACTION_TIMEOUT = (/* unused pure expression or super */ null && (60 * 1000)); +var Durability = function (Durability) { + Durability["Temporary"] = "temporary"; + Durability["Persistent"] = "persistent"; + return Durability; +}({}); +var DEFAULT_GET_TRANSACTION_TIMEOUT = 30; +var BasicSleepStrategy = function BasicSleepStrategy(_iter) { + return 1000; +}; +var LinearSleepStrategy = function LinearSleepStrategy(iter) { + return 1000 * iter; +}; +function findCreatedAccountSequenceInTransactionMeta(meta) { + var _operations$flatMap$f; + var operations = []; + switch (meta.switch()) { + case 0: + operations = meta.operations(); + break; + case 1: + case 2: + case 3: + operations = meta.value().operations(); + break; + default: + throw new Error('Unexpected transaction meta switch value'); + } + var sequenceNumber = (_operations$flatMap$f = operations.flatMap(function (op) { + return op.changes(); + }).find(function (c) { + return c.switch() === lib.xdr.LedgerEntryChangeType.ledgerEntryCreated() && c.created().data().switch() === lib.xdr.LedgerEntryType.account(); + })) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.created()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.data()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.account()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.seqNum()) === null || _operations$flatMap$f === void 0 ? void 0 : _operations$flatMap$f.toString(); + if (sequenceNumber) { + return sequenceNumber; + } + throw new Error('No account created in transaction'); +} +var RpcServer = function () { + function RpcServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, RpcServer); + this.serverURL = URI_default()(serverURL); + if (opts.headers && Object.keys(opts.headers).length !== 0) { + axios.interceptors.request.use(function (config) { + config.headers = Object.assign(config.headers, opts.headers); + return config; + }); + } + if (this.serverURL.protocol() !== 'https' && !opts.allowHttp) { + throw new Error("Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set"); + } + } + return _createClass(RpcServer, [{ + key: "getAccount", + value: (function () { + var _getAccount = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee(address) { + var ledgerKey, resp, accountEntry; + return server_regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + ledgerKey = lib.xdr.LedgerKey.account(new lib.xdr.LedgerKeyAccount({ + accountId: lib.Keypair.fromPublicKey(address).xdrPublicKey() + })); + _context.next = 3; + return this.getLedgerEntries(ledgerKey); + case 3: + resp = _context.sent; + if (!(resp.entries.length === 0)) { + _context.next = 6; + break; + } + return _context.abrupt("return", Promise.reject({ + code: 404, + message: "Account not found: ".concat(address) + })); + case 6: + accountEntry = resp.entries[0].val.account(); + return _context.abrupt("return", new lib.Account(address, accountEntry.seqNum().toString())); + case 8: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function getAccount(_x) { + return _getAccount.apply(this, arguments); + } + return getAccount; + }()) + }, { + key: "getHealth", + value: (function () { + var _getHealth = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee2() { + return server_regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", postObject(this.serverURL.toString(), 'getHealth')); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function getHealth() { + return _getHealth.apply(this, arguments); + } + return getHealth; + }()) + }, { + key: "getContractData", + value: (function () { + var _getContractData = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee3(contract, key) { + var durability, + scAddress, + xdrDurability, + contractKey, + _args3 = arguments; + return server_regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + durability = _args3.length > 2 && _args3[2] !== undefined ? _args3[2] : Durability.Persistent; + if (!(typeof contract === 'string')) { + _context3.next = 5; + break; + } + scAddress = new lib.Contract(contract).address().toScAddress(); + _context3.next = 14; + break; + case 5: + if (!(contract instanceof lib.Address)) { + _context3.next = 9; + break; + } + scAddress = contract.toScAddress(); + _context3.next = 14; + break; + case 9: + if (!(contract instanceof lib.Contract)) { + _context3.next = 13; + break; + } + scAddress = contract.address().toScAddress(); + _context3.next = 14; + break; + case 13: + throw new TypeError("unknown contract type: ".concat(contract)); + case 14: + _context3.t0 = durability; + _context3.next = _context3.t0 === Durability.Temporary ? 17 : _context3.t0 === Durability.Persistent ? 19 : 21; + break; + case 17: + xdrDurability = lib.xdr.ContractDataDurability.temporary(); + return _context3.abrupt("break", 22); + case 19: + xdrDurability = lib.xdr.ContractDataDurability.persistent(); + return _context3.abrupt("break", 22); + case 21: + throw new TypeError("invalid durability: ".concat(durability)); + case 22: + contractKey = lib.xdr.LedgerKey.contractData(new lib.xdr.LedgerKeyContractData({ + key: key, + contract: scAddress, + durability: xdrDurability + })); + return _context3.abrupt("return", this.getLedgerEntries(contractKey).then(function (r) { + if (r.entries.length === 0) { + return Promise.reject({ + code: 404, + message: "Contract data not found. Contract: ".concat(lib.Address.fromScAddress(scAddress).toString(), ", Key: ").concat(key.toXDR('base64'), ", Durability: ").concat(durability) + }); + } + return r.entries[0]; + })); + case 24: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function getContractData(_x2, _x3) { + return _getContractData.apply(this, arguments); + } + return getContractData; + }()) + }, { + key: "getContractWasmByContractId", + value: (function () { + var _getContractWasmByContractId = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee4(contractId) { + var _response$entries$; + var contractLedgerKey, response, wasmHash; + return server_regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + contractLedgerKey = new lib.Contract(contractId).getFootprint(); + _context4.next = 3; + return this.getLedgerEntries(contractLedgerKey); + case 3: + response = _context4.sent; + if (!(!response.entries.length || !((_response$entries$ = response.entries[0]) !== null && _response$entries$ !== void 0 && _response$entries$.val))) { + _context4.next = 6; + break; + } + return _context4.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract hash from server" + })); + case 6: + wasmHash = response.entries[0].val.contractData().val().instance().executable().wasmHash(); + return _context4.abrupt("return", this.getContractWasmByHash(wasmHash)); + case 8: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function getContractWasmByContractId(_x4) { + return _getContractWasmByContractId.apply(this, arguments); + } + return getContractWasmByContractId; + }()) + }, { + key: "getContractWasmByHash", + value: (function () { + var _getContractWasmByHash = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee5(wasmHash) { + var _responseWasm$entries; + var format, + wasmHashBuffer, + ledgerKeyWasmHash, + responseWasm, + wasmBuffer, + _args5 = arguments; + return server_regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + format = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : undefined; + wasmHashBuffer = typeof wasmHash === "string" ? Buffer.from(wasmHash, format) : wasmHash; + ledgerKeyWasmHash = lib.xdr.LedgerKey.contractCode(new lib.xdr.LedgerKeyContractCode({ + hash: wasmHashBuffer + })); + _context5.next = 5; + return this.getLedgerEntries(ledgerKeyWasmHash); + case 5: + responseWasm = _context5.sent; + if (!(!responseWasm.entries.length || !((_responseWasm$entries = responseWasm.entries[0]) !== null && _responseWasm$entries !== void 0 && _responseWasm$entries.val))) { + _context5.next = 8; + break; + } + return _context5.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract wasm from server" + })); + case 8: + wasmBuffer = responseWasm.entries[0].val.contractCode().code(); + return _context5.abrupt("return", wasmBuffer); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function getContractWasmByHash(_x5) { + return _getContractWasmByHash.apply(this, arguments); + } + return getContractWasmByHash; + }()) + }, { + key: "getLedgerEntries", + value: (function () { + var _getLedgerEntries2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee6() { + var _args6 = arguments; + return server_regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + return _context6.abrupt("return", this._getLedgerEntries.apply(this, _args6).then(parsers/* parseRawLedgerEntries */.$D)); + case 1: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function getLedgerEntries() { + return _getLedgerEntries2.apply(this, arguments); + } + return getLedgerEntries; + }()) + }, { + key: "_getLedgerEntries", + value: function () { + var _getLedgerEntries3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee7() { + var _len, + keys, + _key, + _args7 = arguments; + return server_regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + for (_len = _args7.length, keys = new Array(_len), _key = 0; _key < _len; _key++) { + keys[_key] = _args7[_key]; + } + return _context7.abrupt("return", postObject(this.serverURL.toString(), 'getLedgerEntries', { + keys: keys.map(function (k) { + return k.toXDR('base64'); + }) + })); + case 2: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function _getLedgerEntries() { + return _getLedgerEntries3.apply(this, arguments); + } + return _getLedgerEntries; + }() + }, { + key: "pollTransaction", + value: (function () { + var _pollTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee8(hash, opts) { + var _opts$attempts, _opts$attempts2; + var maxAttempts, foundInfo, attempt, _opts$sleepStrategy; + return server_regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + maxAttempts = ((_opts$attempts = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts !== void 0 ? _opts$attempts : 0) < 1 ? DEFAULT_GET_TRANSACTION_TIMEOUT : (_opts$attempts2 = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts2 !== void 0 ? _opts$attempts2 : DEFAULT_GET_TRANSACTION_TIMEOUT; + attempt = 1; + case 2: + if (!(attempt < maxAttempts)) { + _context8.next = 13; + break; + } + _context8.next = 5; + return this.getTransaction(hash); + case 5: + foundInfo = _context8.sent; + if (!(foundInfo.status !== api/* Api */.j.GetTransactionStatus.NOT_FOUND)) { + _context8.next = 8; + break; + } + return _context8.abrupt("return", foundInfo); + case 8: + _context8.next = 10; + return utils/* Utils */.A.sleep(((_opts$sleepStrategy = opts === null || opts === void 0 ? void 0 : opts.sleepStrategy) !== null && _opts$sleepStrategy !== void 0 ? _opts$sleepStrategy : BasicSleepStrategy)(attempt)); + case 10: + attempt++; + _context8.next = 2; + break; + case 13: + return _context8.abrupt("return", foundInfo); + case 14: + case "end": + return _context8.stop(); + } + }, _callee8, this); + })); + function pollTransaction(_x6, _x7) { + return _pollTransaction.apply(this, arguments); + } + return pollTransaction; + }()) + }, { + key: "getTransaction", + value: (function () { + var _getTransaction2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee9(hash) { + return server_regeneratorRuntime().wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + return _context9.abrupt("return", this._getTransaction(hash).then(function (raw) { + var foundInfo = {}; + if (raw.status !== api/* Api */.j.GetTransactionStatus.NOT_FOUND) { + Object.assign(foundInfo, (0,parsers/* parseTransactionInfo */.WC)(raw)); + } + var result = _objectSpread({ + status: raw.status, + txHash: hash, + latestLedger: raw.latestLedger, + latestLedgerCloseTime: raw.latestLedgerCloseTime, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTime: raw.oldestLedgerCloseTime + }, foundInfo); + return result; + })); + case 1: + case "end": + return _context9.stop(); + } + }, _callee9, this); + })); + function getTransaction(_x8) { + return _getTransaction2.apply(this, arguments); + } + return getTransaction; + }()) + }, { + key: "_getTransaction", + value: function () { + var _getTransaction3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee10(hash) { + return server_regeneratorRuntime().wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + return _context10.abrupt("return", postObject(this.serverURL.toString(), 'getTransaction', { + hash: hash + })); + case 1: + case "end": + return _context10.stop(); + } + }, _callee10, this); + })); + function _getTransaction(_x9) { + return _getTransaction3.apply(this, arguments); + } + return _getTransaction; + }() + }, { + key: "getTransactions", + value: (function () { + var _getTransactions2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee11(request) { + return server_regeneratorRuntime().wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + return _context11.abrupt("return", this._getTransactions(request).then(function (raw) { + var result = { + transactions: raw.transactions.map(parsers/* parseRawTransactions */.tR), + latestLedger: raw.latestLedger, + latestLedgerCloseTimestamp: raw.latestLedgerCloseTimestamp, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTimestamp: raw.oldestLedgerCloseTimestamp, + cursor: raw.cursor + }; + return result; + })); + case 1: + case "end": + return _context11.stop(); + } + }, _callee11, this); + })); + function getTransactions(_x10) { + return _getTransactions2.apply(this, arguments); + } + return getTransactions; + }()) + }, { + key: "_getTransactions", + value: function () { + var _getTransactions3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee12(request) { + return server_regeneratorRuntime().wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + return _context12.abrupt("return", postObject(this.serverURL.toString(), 'getTransactions', request)); + case 1: + case "end": + return _context12.stop(); + } + }, _callee12, this); + })); + function _getTransactions(_x11) { + return _getTransactions3.apply(this, arguments); + } + return _getTransactions; + }() + }, { + key: "getEvents", + value: (function () { + var _getEvents2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee13(request) { + return server_regeneratorRuntime().wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + return _context13.abrupt("return", this._getEvents(request).then(parsers/* parseRawEvents */.fG)); + case 1: + case "end": + return _context13.stop(); + } + }, _callee13, this); + })); + function getEvents(_x12) { + return _getEvents2.apply(this, arguments); + } + return getEvents; + }()) + }, { + key: "_getEvents", + value: function () { + var _getEvents3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee14(request) { + var _request$filters; + return server_regeneratorRuntime().wrap(function _callee14$(_context14) { + while (1) switch (_context14.prev = _context14.next) { + case 0: + return _context14.abrupt("return", postObject(this.serverURL.toString(), 'getEvents', _objectSpread(_objectSpread({ + filters: (_request$filters = request.filters) !== null && _request$filters !== void 0 ? _request$filters : [], + pagination: _objectSpread(_objectSpread({}, request.cursor && { + cursor: request.cursor + }), request.limit && { + limit: request.limit + }) + }, request.startLedger && { + startLedger: request.startLedger + }), request.endLedger && { + endLedger: request.endLedger + }))); + case 1: + case "end": + return _context14.stop(); + } + }, _callee14, this); + })); + function _getEvents(_x13) { + return _getEvents3.apply(this, arguments); + } + return _getEvents; + }() + }, { + key: "getNetwork", + value: (function () { + var _getNetwork = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee15() { + return server_regeneratorRuntime().wrap(function _callee15$(_context15) { + while (1) switch (_context15.prev = _context15.next) { + case 0: + return _context15.abrupt("return", postObject(this.serverURL.toString(), 'getNetwork')); + case 1: + case "end": + return _context15.stop(); + } + }, _callee15, this); + })); + function getNetwork() { + return _getNetwork.apply(this, arguments); + } + return getNetwork; + }()) + }, { + key: "getLatestLedger", + value: (function () { + var _getLatestLedger = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee16() { + return server_regeneratorRuntime().wrap(function _callee16$(_context16) { + while (1) switch (_context16.prev = _context16.next) { + case 0: + return _context16.abrupt("return", postObject(this.serverURL.toString(), 'getLatestLedger')); + case 1: + case "end": + return _context16.stop(); + } + }, _callee16, this); + })); + function getLatestLedger() { + return _getLatestLedger.apply(this, arguments); + } + return getLatestLedger; + }()) + }, { + key: "simulateTransaction", + value: (function () { + var _simulateTransaction2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee17(tx, addlResources) { + return server_regeneratorRuntime().wrap(function _callee17$(_context17) { + while (1) switch (_context17.prev = _context17.next) { + case 0: + return _context17.abrupt("return", this._simulateTransaction(tx, addlResources).then(parsers/* parseRawSimulation */.jr)); + case 1: + case "end": + return _context17.stop(); + } + }, _callee17, this); + })); + function simulateTransaction(_x14, _x15) { + return _simulateTransaction2.apply(this, arguments); + } + return simulateTransaction; + }()) + }, { + key: "_simulateTransaction", + value: function () { + var _simulateTransaction3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee18(transaction, addlResources) { + return server_regeneratorRuntime().wrap(function _callee18$(_context18) { + while (1) switch (_context18.prev = _context18.next) { + case 0: + return _context18.abrupt("return", postObject(this.serverURL.toString(), 'simulateTransaction', _objectSpread({ + transaction: transaction.toXDR() + }, addlResources !== undefined && { + resourceConfig: { + instructionLeeway: addlResources.cpuInstructions + } + }))); + case 1: + case "end": + return _context18.stop(); + } + }, _callee18, this); + })); + function _simulateTransaction(_x16, _x17) { + return _simulateTransaction3.apply(this, arguments); + } + return _simulateTransaction; + }() + }, { + key: "prepareTransaction", + value: (function () { + var _prepareTransaction = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee19(tx) { + var simResponse; + return server_regeneratorRuntime().wrap(function _callee19$(_context19) { + while (1) switch (_context19.prev = _context19.next) { + case 0: + _context19.next = 2; + return this.simulateTransaction(tx); + case 2: + simResponse = _context19.sent; + if (!api/* Api */.j.isSimulationError(simResponse)) { + _context19.next = 5; + break; + } + throw new Error(simResponse.error); + case 5: + return _context19.abrupt("return", (0,transaction/* assembleTransaction */.X)(tx, simResponse).build()); + case 6: + case "end": + return _context19.stop(); + } + }, _callee19, this); + })); + function prepareTransaction(_x18) { + return _prepareTransaction.apply(this, arguments); + } + return prepareTransaction; + }()) + }, { + key: "sendTransaction", + value: (function () { + var _sendTransaction2 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee20(transaction) { + return server_regeneratorRuntime().wrap(function _callee20$(_context20) { + while (1) switch (_context20.prev = _context20.next) { + case 0: + return _context20.abrupt("return", this._sendTransaction(transaction).then(parsers/* parseRawSendTransaction */.Af)); + case 1: + case "end": + return _context20.stop(); + } + }, _callee20, this); + })); + function sendTransaction(_x19) { + return _sendTransaction2.apply(this, arguments); + } + return sendTransaction; + }()) + }, { + key: "_sendTransaction", + value: function () { + var _sendTransaction3 = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee21(transaction) { + return server_regeneratorRuntime().wrap(function _callee21$(_context21) { + while (1) switch (_context21.prev = _context21.next) { + case 0: + return _context21.abrupt("return", postObject(this.serverURL.toString(), 'sendTransaction', { + transaction: transaction.toXDR() + })); + case 1: + case "end": + return _context21.stop(); + } + }, _callee21, this); + })); + function _sendTransaction(_x20) { + return _sendTransaction3.apply(this, arguments); + } + return _sendTransaction; + }() + }, { + key: "requestAirdrop", + value: (function () { + var _requestAirdrop = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee22(address, friendbotUrl) { + var account, response, meta, txMeta, sequence, _error$response, _error$response$detai; + return server_regeneratorRuntime().wrap(function _callee22$(_context22) { + while (1) switch (_context22.prev = _context22.next) { + case 0: + account = typeof address === 'string' ? address : address.accountId(); + _context22.t0 = friendbotUrl; + if (_context22.t0) { + _context22.next = 6; + break; + } + _context22.next = 5; + return this.getNetwork(); + case 5: + _context22.t0 = _context22.sent.friendbotUrl; + case 6: + friendbotUrl = _context22.t0; + if (friendbotUrl) { + _context22.next = 9; + break; + } + throw new Error('No friendbot URL configured for current network'); + case 9: + _context22.prev = 9; + _context22.next = 12; + return axios.post("".concat(friendbotUrl, "?addr=").concat(encodeURIComponent(account))); + case 12: + response = _context22.sent; + if (response.data.result_meta_xdr) { + _context22.next = 22; + break; + } + _context22.next = 16; + return this.getTransaction(response.data.hash); + case 16: + txMeta = _context22.sent; + if (!(txMeta.status !== api/* Api */.j.GetTransactionStatus.SUCCESS)) { + _context22.next = 19; + break; + } + throw new Error("Funding account ".concat(address, " failed")); + case 19: + meta = txMeta.resultMetaXdr; + _context22.next = 23; + break; + case 22: + meta = lib.xdr.TransactionMeta.fromXDR(response.data.result_meta_xdr, 'base64'); + case 23: + sequence = findCreatedAccountSequenceInTransactionMeta(meta); + return _context22.abrupt("return", new lib.Account(account, sequence)); + case 27: + _context22.prev = 27; + _context22.t1 = _context22["catch"](9); + if (!(((_error$response = _context22.t1.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 400)) { + _context22.next = 32; + break; + } + if (!((_error$response$detai = _context22.t1.response.detail) !== null && _error$response$detai !== void 0 && _error$response$detai.includes('createAccountAlreadyExist'))) { + _context22.next = 32; + break; + } + return _context22.abrupt("return", this.getAccount(account)); + case 32: + throw _context22.t1; + case 33: + case "end": + return _context22.stop(); + } + }, _callee22, this, [[9, 27]]); + })); + function requestAirdrop(_x21, _x22) { + return _requestAirdrop.apply(this, arguments); + } + return requestAirdrop; + }()) + }, { + key: "getFeeStats", + value: (function () { + var _getFeeStats = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee23() { + return server_regeneratorRuntime().wrap(function _callee23$(_context23) { + while (1) switch (_context23.prev = _context23.next) { + case 0: + return _context23.abrupt("return", postObject(this.serverURL.toString(), 'getFeeStats')); + case 1: + case "end": + return _context23.stop(); + } + }, _callee23, this); + })); + function getFeeStats() { + return _getFeeStats.apply(this, arguments); + } + return getFeeStats; + }()) + }, { + key: "getVersionInfo", + value: (function () { + var _getVersionInfo = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee24() { + return server_regeneratorRuntime().wrap(function _callee24$(_context24) { + while (1) switch (_context24.prev = _context24.next) { + case 0: + return _context24.abrupt("return", postObject(this.serverURL.toString(), 'getVersionInfo')); + case 1: + case "end": + return _context24.stop(); + } + }, _callee24, this); + })); + function getVersionInfo() { + return _getVersionInfo.apply(this, arguments); + } + return getVersionInfo; + }()) + }, { + key: "getSACBalance", + value: (function () { + var _getSACBalance = server_asyncToGenerator(server_regeneratorRuntime().mark(function _callee25(contractId, sac, networkPassphrase) { + var passphrase, sacId, key, ledgerKey, response, _response$entries$2, lastModifiedLedgerSeq, liveUntilLedgerSeq, val, entry; + return server_regeneratorRuntime().wrap(function _callee25$(_context25) { + while (1) switch (_context25.prev = _context25.next) { + case 0: + if (lib.StrKey.isValidContract(contractId)) { + _context25.next = 2; + break; + } + throw new TypeError("expected contract ID, got ".concat(contractId)); + case 2: + if (!(networkPassphrase !== null && networkPassphrase !== void 0)) { + _context25.next = 6; + break; + } + _context25.t0 = networkPassphrase; + _context25.next = 9; + break; + case 6: + _context25.next = 8; + return this.getNetwork().then(function (n) { + return n.passphrase; + }); + case 8: + _context25.t0 = _context25.sent; + case 9: + passphrase = _context25.t0; + sacId = sac.contractId(passphrase); + key = lib.xdr.ScVal.scvVec([(0,lib.nativeToScVal)("Balance", { + type: "symbol" + }), (0,lib.nativeToScVal)(contractId, { + type: "address" + })]); + ledgerKey = lib.xdr.LedgerKey.contractData(new lib.xdr.LedgerKeyContractData({ + contract: new lib.Address(sacId).toScAddress(), + durability: lib.xdr.ContractDataDurability.persistent(), + key: key + })); + _context25.next = 15; + return this.getLedgerEntries(ledgerKey); + case 15: + response = _context25.sent; + if (!(response.entries.length === 0)) { + _context25.next = 18; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 18: + _response$entries$2 = response.entries[0], lastModifiedLedgerSeq = _response$entries$2.lastModifiedLedgerSeq, liveUntilLedgerSeq = _response$entries$2.liveUntilLedgerSeq, val = _response$entries$2.val; + if (!(val.switch().value !== lib.xdr.LedgerEntryType.contractData().value)) { + _context25.next = 21; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 21: + entry = (0,lib.scValToNative)(val.contractData().val()); + return _context25.abrupt("return", { + latestLedger: response.latestLedger, + balanceEntry: { + liveUntilLedgerSeq: liveUntilLedgerSeq, + lastModifiedLedgerSeq: lastModifiedLedgerSeq, + amount: entry.amount.toString(), + authorized: entry.authorized, + clawback: entry.clawback + } + }); + case 23: + case "end": + return _context25.stop(); + } + }, _callee25, this); + })); + function getSACBalance(_x23, _x24, _x25) { + return _getSACBalance.apply(this, arguments); + } + return getSACBalance; + }()) + }]); +}(); +;// ./src/rpc/index.ts +/* module decorator */ module = __webpack_require__.hmd(module); + + + + + +/* harmony default export */ const rpc = (module.exports); + +/***/ }), + +/***/ 784: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ $D: () => (/* binding */ parseRawLedgerEntries), +/* harmony export */ Af: () => (/* binding */ parseRawSendTransaction), +/* harmony export */ WC: () => (/* binding */ parseTransactionInfo), +/* harmony export */ fG: () => (/* binding */ parseRawEvents), +/* harmony export */ jr: () => (/* binding */ parseRawSimulation), +/* harmony export */ tR: () => (/* binding */ parseRawTransactions) +/* harmony export */ }); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4076); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + +function parseRawSendTransaction(raw) { + var errorResultXdr = raw.errorResultXdr, + diagnosticEventsXdr = raw.diagnosticEventsXdr; + delete raw.errorResultXdr; + delete raw.diagnosticEventsXdr; + if (errorResultXdr) { + return _objectSpread(_objectSpread(_objectSpread({}, raw), diagnosticEventsXdr !== undefined && diagnosticEventsXdr.length > 0 && { + diagnosticEvents: diagnosticEventsXdr.map(function (evt) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + }) + }), {}, { + errorResult: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionResult.fromXDR(errorResultXdr, 'base64') + }); + } + return _objectSpread({}, raw); +} +function parseTransactionInfo(raw) { + var meta = _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionMeta.fromXDR(raw.resultMetaXdr, 'base64'); + var info = { + ledger: raw.ledger, + createdAt: raw.createdAt, + applicationOrder: raw.applicationOrder, + feeBump: raw.feeBump, + envelopeXdr: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionEnvelope.fromXDR(raw.envelopeXdr, 'base64'), + resultXdr: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.TransactionResult.fromXDR(raw.resultXdr, 'base64'), + resultMetaXdr: meta + }; + if (meta.switch() === 3 && meta.v3().sorobanMeta() !== null) { + var _meta$v3$sorobanMeta; + info.returnValue = (_meta$v3$sorobanMeta = meta.v3().sorobanMeta()) === null || _meta$v3$sorobanMeta === void 0 ? void 0 : _meta$v3$sorobanMeta.returnValue(); + } + if ('diagnosticEventsXdr' in raw && raw.diagnosticEventsXdr) { + info.diagnosticEventsXdr = raw.diagnosticEventsXdr.map(function (diagnosticEvent) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.DiagnosticEvent.fromXDR(diagnosticEvent, 'base64'); + }); + } + return info; +} +function parseRawTransactions(r) { + return _objectSpread({ + status: r.status, + txHash: r.txHash + }, parseTransactionInfo(r)); +} +function parseRawEvents(raw) { + var _raw$events; + return { + latestLedger: raw.latestLedger, + cursor: raw.cursor, + events: ((_raw$events = raw.events) !== null && _raw$events !== void 0 ? _raw$events : []).map(function (evt) { + var clone = _objectSpread({}, evt); + delete clone.contractId; + return _objectSpread(_objectSpread(_objectSpread({}, clone), evt.contractId !== '' && { + contractId: new _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.Contract(evt.contractId) + }), {}, { + topic: evt.topic.map(function (topic) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.fromXDR(topic, 'base64'); + }), + value: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.fromXDR(evt.value, 'base64') + }); + }) + }; +} +function parseRawLedgerEntries(raw) { + var _raw$entries; + return { + latestLedger: raw.latestLedger, + entries: ((_raw$entries = raw.entries) !== null && _raw$entries !== void 0 ? _raw$entries : []).map(function (rawEntry) { + if (!rawEntry.key || !rawEntry.xdr) { + throw new TypeError("invalid ledger entry: ".concat(JSON.stringify(rawEntry))); + } + return _objectSpread({ + lastModifiedLedgerSeq: rawEntry.lastModifiedLedgerSeq, + key: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerKey.fromXDR(rawEntry.key, 'base64'), + val: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerEntryData.fromXDR(rawEntry.xdr, 'base64') + }, rawEntry.liveUntilLedgerSeq !== undefined && { + liveUntilLedgerSeq: rawEntry.liveUntilLedgerSeq + }); + }) + }; +} +function parseSuccessful(sim, partial) { + var _sim$results$length, _sim$results, _sim$stateChanges$len, _sim$stateChanges, _sim$stateChanges2; + var success = _objectSpread(_objectSpread(_objectSpread({}, partial), {}, { + transactionData: new _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.SorobanDataBuilder(sim.transactionData), + minResourceFee: sim.minResourceFee + }, ((_sim$results$length = (_sim$results = sim.results) === null || _sim$results === void 0 ? void 0 : _sim$results.length) !== null && _sim$results$length !== void 0 ? _sim$results$length : 0 > 0) && { + result: sim.results.map(function (row) { + var _row$auth; + return { + auth: ((_row$auth = row.auth) !== null && _row$auth !== void 0 ? _row$auth : []).map(function (entry) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.SorobanAuthorizationEntry.fromXDR(entry, 'base64'); + }), + retval: row.xdr ? _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.fromXDR(row.xdr, 'base64') : _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.ScVal.scvVoid() + }; + })[0] + }), ((_sim$stateChanges$len = (_sim$stateChanges = sim.stateChanges) === null || _sim$stateChanges === void 0 ? void 0 : _sim$stateChanges.length) !== null && _sim$stateChanges$len !== void 0 ? _sim$stateChanges$len : 0 > 0) && { + stateChanges: (_sim$stateChanges2 = sim.stateChanges) === null || _sim$stateChanges2 === void 0 ? void 0 : _sim$stateChanges2.map(function (entryChange) { + return { + type: entryChange.type, + key: _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerKey.fromXDR(entryChange.key, 'base64'), + before: entryChange.before ? _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerEntry.fromXDR(entryChange.before, 'base64') : null, + after: entryChange.after ? _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.LedgerEntry.fromXDR(entryChange.after, 'base64') : null + }; + }) + }); + if (!sim.restorePreamble || sim.restorePreamble.transactionData === '') { + return success; + } + return _objectSpread(_objectSpread({}, success), {}, { + restorePreamble: { + minResourceFee: sim.restorePreamble.minResourceFee, + transactionData: new _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.SorobanDataBuilder(sim.restorePreamble.transactionData) + } + }); +} +function parseRawSimulation(sim) { + var _sim$events$map, _sim$events; + var looksRaw = _api__WEBPACK_IMPORTED_MODULE_1__/* .Api */ .j.isSimulationRaw(sim); + if (!looksRaw) { + return sim; + } + var base = { + _parsed: true, + id: sim.id, + latestLedger: sim.latestLedger, + events: (_sim$events$map = (_sim$events = sim.events) === null || _sim$events === void 0 ? void 0 : _sim$events.map(function (evt) { + return _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + })) !== null && _sim$events$map !== void 0 ? _sim$events$map : [] + }; + if (typeof sim.error === 'string') { + return _objectSpread(_objectSpread({}, base), {}, { + error: sim.error + }); + } + return parseSuccessful(sim, base); +} + +/***/ }), + +/***/ 8680: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ X: () => (/* binding */ assembleTransaction) +/* harmony export */ }); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(356); +/* harmony import */ var _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4076); +/* harmony import */ var _parsers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(784); + + + +function isSorobanTransaction(tx) { + if (tx.operations.length !== 1) { + return false; + } + switch (tx.operations[0].type) { + case 'invokeHostFunction': + case 'extendFootprintTtl': + case 'restoreFootprint': + return true; + default: + return false; + } +} +function assembleTransaction(raw, simulation) { + if ('innerTransaction' in raw) { + return assembleTransaction(raw.innerTransaction, simulation); + } + if (!isSorobanTransaction(raw)) { + throw new TypeError('unsupported transaction: must contain exactly one ' + 'invokeHostFunction, extendFootprintTtl, or restoreFootprint ' + 'operation'); + } + var success = (0,_parsers__WEBPACK_IMPORTED_MODULE_2__/* .parseRawSimulation */ .jr)(simulation); + if (!_api__WEBPACK_IMPORTED_MODULE_1__/* .Api */ .j.isSimulationSuccess(success)) { + throw new Error("simulation incorrect: ".concat(JSON.stringify(success))); + } + var classicFeeNum = parseInt(raw.fee) || 0; + var minResourceFeeNum = parseInt(success.minResourceFee) || 0; + var txnBuilder = _stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.TransactionBuilder.cloneFrom(raw, { + fee: (classicFeeNum + minResourceFeeNum).toString(), + sorobanData: success.transactionData.build(), + networkPassphrase: raw.networkPassphrase + }); + if (raw.operations[0].type === 'invokeHostFunction') { + var _invokeOp$auth; + txnBuilder.clearOperations(); + var invokeOp = raw.operations[0]; + var existingAuth = (_invokeOp$auth = invokeOp.auth) !== null && _invokeOp$auth !== void 0 ? _invokeOp$auth : []; + txnBuilder.addOperation(_stellar_stellar_base__WEBPACK_IMPORTED_MODULE_0__.Operation.invokeHostFunction({ + source: invokeOp.source, + func: invokeOp.func, + auth: existingAuth.length > 0 ? existingAuth : success.result.auth + })); + } + return txnBuilder; +} + +/***/ }), + +/***/ 3898: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Api: () => (/* binding */ Api), +/* harmony export */ Resolver: () => (/* binding */ Resolver), +/* harmony export */ STELLAR_TOML_MAX_SIZE: () => (/* binding */ STELLAR_TOML_MAX_SIZE) +/* harmony export */ }); +/* harmony import */ var toml__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1293); +/* harmony import */ var toml__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(toml__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _http_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9983); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8732); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + + + +var STELLAR_TOML_MAX_SIZE = 100 * 1024; +var CancelToken = _http_client__WEBPACK_IMPORTED_MODULE_1__/* .httpClient */ .ok.CancelToken; +var Resolver = function () { + function Resolver() { + _classCallCheck(this, Resolver); + } + return _createClass(Resolver, null, [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(domain) { + var _opts$allowedRedirect; + var opts, + allowHttp, + timeout, + protocol, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 1 && _args[1] !== undefined ? _args[1] : {}; + allowHttp = typeof opts.allowHttp === "undefined" ? _config__WEBPACK_IMPORTED_MODULE_2__/* .Config */ .T.isAllowHttp() : opts.allowHttp; + timeout = typeof opts.timeout === "undefined" ? _config__WEBPACK_IMPORTED_MODULE_2__/* .Config */ .T.getTimeout() : opts.timeout; + protocol = allowHttp ? "http" : "https"; + return _context.abrupt("return", _http_client__WEBPACK_IMPORTED_MODULE_1__/* .httpClient */ .ok.get("".concat(protocol, "://").concat(domain, "/.well-known/stellar.toml"), { + maxRedirects: (_opts$allowedRedirect = opts.allowedRedirects) !== null && _opts$allowedRedirect !== void 0 ? _opts$allowedRedirect : 0, + maxContentLength: STELLAR_TOML_MAX_SIZE, + cancelToken: timeout ? new CancelToken(function (cancel) { + return setTimeout(function () { + return cancel("timeout of ".concat(timeout, "ms exceeded")); + }, timeout); + }) : undefined, + timeout: timeout + }).then(function (response) { + try { + var tomlObject = toml__WEBPACK_IMPORTED_MODULE_0___default().parse(response.data); + return Promise.resolve(tomlObject); + } catch (e) { + return Promise.reject(new Error("stellar.toml is invalid - Parsing error on line ".concat(e.line, ", column ").concat(e.column, ": ").concat(e.message))); + } + }).catch(function (err) { + if (err.message.match(/^maxContentLength size/)) { + throw new Error("stellar.toml file exceeds allowed size of ".concat(STELLAR_TOML_MAX_SIZE)); + } else { + throw err; + } + })); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + function resolve(_x) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }]); +}(); +var Api; + +/***/ }), + +/***/ 3121: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ A: () => (/* binding */ Utils) +/* harmony export */ }); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Utils = function () { + function Utils() { + _classCallCheck(this, Utils); + } + return _createClass(Utils, null, [{ + key: "validateTimebounds", + value: function validateTimebounds(transaction) { + var gracePeriod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + if (!transaction.timeBounds) { + return false; + } + var now = Math.floor(Date.now() / 1000); + var _transaction$timeBoun = transaction.timeBounds, + minTime = _transaction$timeBoun.minTime, + maxTime = _transaction$timeBoun.maxTime; + return now >= Number.parseInt(minTime, 10) - gracePeriod && now <= Number.parseInt(maxTime, 10) + gracePeriod; + } + }, { + key: "sleep", + value: function sleep(ms) { + return new Promise(function (resolve) { + return setTimeout(resolve, ms); + }); + } + }]); +}(); + +/***/ }), + +/***/ 5479: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + InvalidChallengeError: () => (/* reexport */ InvalidChallengeError), + buildChallengeTx: () => (/* reexport */ buildChallengeTx), + gatherTxSigners: () => (/* reexport */ gatherTxSigners), + readChallengeTx: () => (/* reexport */ readChallengeTx), + verifyChallengeTxSigners: () => (/* reexport */ verifyChallengeTxSigners), + verifyChallengeTxThreshold: () => (/* reexport */ verifyChallengeTxThreshold), + verifyTxSignedBy: () => (/* reexport */ verifyTxSignedBy) +}); + +// EXTERNAL MODULE: ./node_modules/randombytes/browser.js +var browser = __webpack_require__(3209); +var browser_default = /*#__PURE__*/__webpack_require__.n(browser); +// EXTERNAL MODULE: ./node_modules/@stellar/stellar-base/lib/index.js +var lib = __webpack_require__(356); +// EXTERNAL MODULE: ./src/utils.ts +var utils = __webpack_require__(3121); +;// ./src/webauth/errors.ts +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var InvalidChallengeError = function (_Error) { + function InvalidChallengeError(message) { + var _this; + _classCallCheck(this, InvalidChallengeError); + var trueProto = (this instanceof InvalidChallengeError ? this.constructor : void 0).prototype; + _this = _callSuper(this, InvalidChallengeError, [message]); + _this.__proto__ = trueProto; + _this.constructor = InvalidChallengeError; + _this.name = "InvalidChallengeError"; + return _this; + } + _inherits(InvalidChallengeError, _Error); + return _createClass(InvalidChallengeError); +}(_wrapNativeSuper(Error)); +;// ./src/webauth/utils.ts +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function utils_typeof(o) { "@babel/helpers - typeof"; return utils_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, utils_typeof(o); } +function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } + + + + +function buildChallengeTx(serverKeypair, clientAccountID, homeDomain) { + var timeout = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 300; + var networkPassphrase = arguments.length > 4 ? arguments[4] : undefined; + var webAuthDomain = arguments.length > 5 ? arguments[5] : undefined; + var memo = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var clientDomain = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var clientSigningKey = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; + if (clientAccountID.startsWith("M") && memo) { + throw Error("memo cannot be used if clientAccountID is a muxed account"); + } + var account = new lib.Account(serverKeypair.publicKey(), "-1"); + var now = Math.floor(Date.now() / 1000); + var value = browser_default()(48).toString("base64"); + var builder = new lib.TransactionBuilder(account, { + fee: lib.BASE_FEE, + networkPassphrase: networkPassphrase, + timebounds: { + minTime: now, + maxTime: now + timeout + } + }).addOperation(lib.Operation.manageData({ + name: "".concat(homeDomain, " auth"), + value: value, + source: clientAccountID + })).addOperation(lib.Operation.manageData({ + name: "web_auth_domain", + value: webAuthDomain, + source: account.accountId() + })); + if (clientDomain) { + if (!clientSigningKey) { + throw Error("clientSigningKey is required if clientDomain is provided"); + } + builder.addOperation(lib.Operation.manageData({ + name: "client_domain", + value: clientDomain, + source: clientSigningKey + })); + } + if (memo) { + builder.addMemo(lib.Memo.id(memo)); + } + var transaction = builder.build(); + transaction.sign(serverKeypair); + return transaction.toEnvelope().toXDR("base64").toString(); +} +function readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain) { + var _transaction$timeBoun; + if (serverAccountID.startsWith("M")) { + throw Error("Invalid serverAccountID: multiplexed accounts are not supported."); + } + var transaction; + try { + transaction = new lib.Transaction(challengeTx, networkPassphrase); + } catch (_unused) { + try { + transaction = new lib.FeeBumpTransaction(challengeTx, networkPassphrase); + } catch (_unused2) { + throw new InvalidChallengeError("Invalid challenge: unable to deserialize challengeTx transaction string"); + } + throw new InvalidChallengeError("Invalid challenge: expected a Transaction but received a FeeBumpTransaction"); + } + var sequence = Number.parseInt(transaction.sequence, 10); + if (sequence !== 0) { + throw new InvalidChallengeError("The transaction sequence number should be zero"); + } + if (transaction.source !== serverAccountID) { + throw new InvalidChallengeError("The transaction source account is not equal to the server's account"); + } + if (transaction.operations.length < 1) { + throw new InvalidChallengeError("The transaction should contain at least one operation"); + } + var _transaction$operatio = _toArray(transaction.operations), + operation = _transaction$operatio[0], + subsequentOperations = _transaction$operatio.slice(1); + if (!operation.source) { + throw new InvalidChallengeError("The transaction's operation should contain a source account"); + } + var clientAccountID = operation.source; + var memo = null; + if (transaction.memo.type !== lib.MemoNone) { + if (clientAccountID.startsWith("M")) { + throw new InvalidChallengeError("The transaction has a memo but the client account ID is a muxed account"); + } + if (transaction.memo.type !== lib.MemoID) { + throw new InvalidChallengeError("The transaction's memo must be of type `id`"); + } + memo = transaction.memo.value; + } + if (operation.type !== "manageData") { + throw new InvalidChallengeError("The transaction's operation type should be 'manageData'"); + } + if (transaction.timeBounds && Number.parseInt((_transaction$timeBoun = transaction.timeBounds) === null || _transaction$timeBoun === void 0 ? void 0 : _transaction$timeBoun.maxTime, 10) === lib.TimeoutInfinite) { + throw new InvalidChallengeError("The transaction requires non-infinite timebounds"); + } + if (!utils/* Utils */.A.validateTimebounds(transaction, 60 * 5)) { + throw new InvalidChallengeError("The transaction has expired"); + } + if (operation.value === undefined) { + throw new InvalidChallengeError("The transaction's operation values should not be null"); + } + if (!operation.value) { + throw new InvalidChallengeError("The transaction's operation value should not be null"); + } + if (Buffer.from(operation.value.toString(), "base64").length !== 48) { + throw new InvalidChallengeError("The transaction's operation value should be a 64 bytes base64 random string"); + } + if (!homeDomains) { + throw new InvalidChallengeError("Invalid homeDomains: a home domain must be provided for verification"); + } + var matchedHomeDomain; + if (typeof homeDomains === "string") { + if ("".concat(homeDomains, " auth") === operation.name) { + matchedHomeDomain = homeDomains; + } + } else if (Array.isArray(homeDomains)) { + matchedHomeDomain = homeDomains.find(function (domain) { + return "".concat(domain, " auth") === operation.name; + }); + } else { + throw new InvalidChallengeError("Invalid homeDomains: homeDomains type is ".concat(utils_typeof(homeDomains), " but should be a string or an array")); + } + if (!matchedHomeDomain) { + throw new InvalidChallengeError("Invalid homeDomains: the transaction's operation key name does not match the expected home domain"); + } + var _iterator = _createForOfIteratorHelper(subsequentOperations), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var op = _step.value; + if (op.type !== "manageData") { + throw new InvalidChallengeError("The transaction has operations that are not of type 'manageData'"); + } + if (op.source !== serverAccountID && op.name !== "client_domain") { + throw new InvalidChallengeError("The transaction has operations that are unrecognized"); + } + if (op.name === "web_auth_domain") { + if (op.value === undefined) { + throw new InvalidChallengeError("'web_auth_domain' operation value should not be null"); + } + if (op.value.compare(Buffer.from(webAuthDomain))) { + throw new InvalidChallengeError("'web_auth_domain' operation value does not match ".concat(webAuthDomain)); + } + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + if (!verifyTxSignedBy(transaction, serverAccountID)) { + throw new InvalidChallengeError("Transaction not signed by server: '".concat(serverAccountID, "'")); + } + return { + tx: transaction, + clientAccountID: clientAccountID, + matchedHomeDomain: matchedHomeDomain, + memo: memo + }; +} +function verifyChallengeTxThreshold(challengeTx, serverAccountID, networkPassphrase, threshold, signerSummary, homeDomains, webAuthDomain) { + var signers = signerSummary.map(function (signer) { + return signer.key; + }); + var signersFound = verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain); + var weight = 0; + var _loop = function _loop() { + var _signerSummary$find; + var signer = _signersFound[_i]; + var sigWeight = ((_signerSummary$find = signerSummary.find(function (s) { + return s.key === signer; + })) === null || _signerSummary$find === void 0 ? void 0 : _signerSummary$find.weight) || 0; + weight += sigWeight; + }; + for (var _i = 0, _signersFound = signersFound; _i < _signersFound.length; _i++) { + _loop(); + } + if (weight < threshold) { + throw new InvalidChallengeError("signers with weight ".concat(weight, " do not meet threshold ").concat(threshold, "\"")); + } + return signersFound; +} +function verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain) { + var _readChallengeTx = readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain), + tx = _readChallengeTx.tx; + var serverKP; + try { + serverKP = lib.Keypair.fromPublicKey(serverAccountID); + } catch (err) { + throw new Error("Couldn't infer keypair from the provided 'serverAccountID': ".concat(err.message)); + } + var clientSigners = new Set(); + var _iterator2 = _createForOfIteratorHelper(signers), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var _signer = _step2.value; + if (_signer === serverKP.publicKey()) { + continue; + } + if (_signer.charAt(0) !== "G") { + continue; + } + clientSigners.add(_signer); + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + if (clientSigners.size === 0) { + throw new InvalidChallengeError("No verifiable client signers provided, at least one G... address must be provided"); + } + var clientSigningKey; + var _iterator3 = _createForOfIteratorHelper(tx.operations), + _step3; + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + var op = _step3.value; + if (op.type === "manageData" && op.name === "client_domain") { + if (clientSigningKey) { + throw new InvalidChallengeError("Found more than one client_domain operation"); + } + clientSigningKey = op.source; + } + } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); + } + var allSigners = [serverKP.publicKey()].concat(_toConsumableArray(Array.from(clientSigners))); + if (clientSigningKey) { + allSigners.push(clientSigningKey); + } + var signersFound = gatherTxSigners(tx, allSigners); + var serverSignatureFound = false; + var clientSigningKeySignatureFound = false; + for (var _i2 = 0, _signersFound2 = signersFound; _i2 < _signersFound2.length; _i2++) { + var signer = _signersFound2[_i2]; + if (signer === serverKP.publicKey()) { + serverSignatureFound = true; + } + if (signer === clientSigningKey) { + clientSigningKeySignatureFound = true; + } + } + if (!serverSignatureFound) { + throw new InvalidChallengeError("Transaction not signed by server: '".concat(serverKP.publicKey(), "'")); + } + if (clientSigningKey && !clientSigningKeySignatureFound) { + throw new InvalidChallengeError("Transaction not signed by the source account of the 'client_domain' " + "ManageData operation"); + } + if (signersFound.length === 1) { + throw new InvalidChallengeError("None of the given signers match the transaction signatures"); + } + if (signersFound.length !== tx.signatures.length) { + throw new InvalidChallengeError("Transaction has unrecognized signatures"); + } + signersFound.splice(signersFound.indexOf(serverKP.publicKey()), 1); + if (clientSigningKey) { + signersFound.splice(signersFound.indexOf(clientSigningKey), 1); + } + return signersFound; +} +function verifyTxSignedBy(transaction, accountID) { + return gatherTxSigners(transaction, [accountID]).length !== 0; +} +function gatherTxSigners(transaction, signers) { + var hashedSignatureBase = transaction.hash(); + var txSignatures = _toConsumableArray(transaction.signatures); + var signersFound = new Set(); + var _iterator4 = _createForOfIteratorHelper(signers), + _step4; + try { + for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { + var signer = _step4.value; + if (txSignatures.length === 0) { + break; + } + var keypair = void 0; + try { + keypair = lib.Keypair.fromPublicKey(signer); + } catch (err) { + throw new InvalidChallengeError("Signer is not a valid address: ".concat(err.message)); + } + for (var i = 0; i < txSignatures.length; i++) { + var decSig = txSignatures[i]; + if (!decSig.hint().equals(keypair.signatureHint())) { + continue; + } + if (keypair.verify(hashedSignatureBase, decSig.signature())) { + signersFound.add(signer); + txSignatures.splice(i, 1); + break; + } + } + } + } catch (err) { + _iterator4.e(err); + } finally { + _iterator4.f(); + } + return Array.from(signersFound); +} +;// ./src/webauth/index.ts + + + +/***/ }), + +/***/ 5360: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +/** + * Generate a character map. + * @param {string} alphabet e.g. "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" + * @param {object} mappings map overrides from key to value + * @method + */ + +var charmap = function (alphabet, mappings) { + mappings || (mappings = {}); + alphabet.split("").forEach(function (c, i) { + if (!(c in mappings)) mappings[c] = i; + }); + return mappings; +} + +/** + * The RFC 4648 base 32 alphabet and character map. + * @see {@link https://tools.ietf.org/html/rfc4648} + */ + +var rfc4648 = { + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", + charmap: { + 0: 14, + 1: 8 + } +}; + +rfc4648.charmap = charmap(rfc4648.alphabet, rfc4648.charmap); + +/** + * The Crockford base 32 alphabet and character map. + * @see {@link http://www.crockford.com/wrmg/base32.html} + */ + +var crockford = { + alphabet: "0123456789ABCDEFGHJKMNPQRSTVWXYZ", + charmap: { + O: 0, + I: 1, + L: 1 + } +}; + +crockford.charmap = charmap(crockford.alphabet, crockford.charmap); + +/** + * base32hex + * @see {@link https://en.wikipedia.org/wiki/Base32#base32hex} + */ + +var base32hex = { + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", + charmap: {} +}; + +base32hex.charmap = charmap(base32hex.alphabet, base32hex.charmap); + +/** + * Create a new `Decoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [charmap] Override the character map used in decoding. + * @constructor + */ + +function Decoder (options) { + this.buf = []; + this.shift = 8; + this.carry = 0; + + if (options) { + + switch (options.type) { + case "rfc4648": + this.charmap = exports.rfc4648.charmap; + break; + case "crockford": + this.charmap = exports.crockford.charmap; + break; + case "base32hex": + this.charmap = exports.base32hex.charmap; + break; + default: + throw new Error("invalid type"); + } + + if (options.charmap) this.charmap = options.charmap; + } +} + +/** + * The default character map coresponds to RFC4648. + */ + +Decoder.prototype.charmap = rfc4648.charmap; + +/** + * Decode a string, continuing from the previous state. + * + * @param {string} str + * @return {Decoder} this + */ + +Decoder.prototype.write = function (str) { + var charmap = this.charmap; + var buf = this.buf; + var shift = this.shift; + var carry = this.carry; + + // decode string + str.toUpperCase().split("").forEach(function (char) { + + // ignore padding + if (char == "=") return; + + // lookup symbol + var symbol = charmap[char] & 0xff; + + // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 + + shift -= 5; + if (shift > 0) { + carry |= symbol << shift; + } else if (shift < 0) { + buf.push(carry | (symbol >> -shift)); + shift += 8; + carry = (symbol << shift) & 0xff; + } else { + buf.push(carry | symbol); + shift = 8; + carry = 0; + } + }); + + // save state + this.shift = shift; + this.carry = carry; + + // for chaining + return this; +}; + +/** + * Finish decoding. + * + * @param {string} [str] The final string to decode. + * @return {Array} Decoded byte array. + */ + +Decoder.prototype.finalize = function (str) { + if (str) { + this.write(str); + } + if (this.shift !== 8 && this.carry !== 0) { + this.buf.push(this.carry); + this.shift = 8; + this.carry = 0; + } + return this.buf; +}; + +/** + * Create a new `Encoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [alphabet] Override the alphabet used in encoding. + * @constructor + */ + +function Encoder (options) { + this.buf = ""; + this.shift = 3; + this.carry = 0; + + if (options) { + + switch (options.type) { + case "rfc4648": + this.alphabet = exports.rfc4648.alphabet; + break; + case "crockford": + this.alphabet = exports.crockford.alphabet; + break; + case "base32hex": + this.alphabet = exports.base32hex.alphabet; + break; + default: + throw new Error("invalid type"); + } + + if (options.alphabet) this.alphabet = options.alphabet; + else if (options.lc) this.alphabet = this.alphabet.toLowerCase(); + } +} + +/** + * The default alphabet coresponds to RFC4648. + */ + +Encoder.prototype.alphabet = rfc4648.alphabet; + +/** + * Encode a byte array, continuing from the previous state. + * + * @param {byte[]} buf The byte array to encode. + * @return {Encoder} this + */ + +Encoder.prototype.write = function (buf) { + var shift = this.shift; + var carry = this.carry; + var symbol; + var byte; + var i; + + // encode each byte in buf + for (i = 0; i < buf.length; i++) { + byte = buf[i]; + + // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 + + symbol = carry | (byte >> shift); + this.buf += this.alphabet[symbol & 0x1f]; + + if (shift > 5) { + shift -= 5; + symbol = byte >> shift; + this.buf += this.alphabet[symbol & 0x1f]; + } + + shift = 5 - shift; + carry = byte << shift; + shift = 8 - shift; + } + + // save state + this.shift = shift; + this.carry = carry; + + // for chaining + return this; +}; + +/** + * Finish encoding. + * + * @param {byte[]} [buf] The final byte array to encode. + * @return {string} The encoded byte array. + */ + +Encoder.prototype.finalize = function (buf) { + if (buf) { + this.write(buf); + } + if (this.shift !== 3) { + this.buf += this.alphabet[this.carry & 0x1f]; + this.shift = 3; + this.carry = 0; + } + return this.buf; +}; + +/** + * Convenience encoder. + * + * @param {byte[]} buf The byte array to encode. + * @param {object} [options] Options to pass to the encoder. + * @return {string} The encoded string. + */ + +exports.encode = function (buf, options) { + return new Encoder(options).finalize(buf); +}; + +/** + * Convenience decoder. + * + * @param {string} str The string to decode. + * @param {object} [options] Options to pass to the decoder. + * @return {byte[]} The decoded byte array. + */ + +exports.decode = function (str, options) { + return new Decoder(options).finalize(str); +}; + +// Exports. +exports.Decoder = Decoder; +exports.Encoder = Encoder; +exports.charmap = charmap; +exports.crockford = crockford; +exports.rfc4648 = rfc4648; +exports.base32hex = base32hex; + + +/***/ }), + +/***/ 7526: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + + +/***/ }), + +/***/ 1594: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_RESULT__;;(function (globalObject) { + 'use strict'; + +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + + var BigNumber, + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + + /* + * Create and return a BigNumber constructor. + */ + function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; + } + + + // PRIVATE HELPER FUNCTIONS + + // These functions don't need access to variables, + // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + + function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; + } + + + // Return a coefficient array as a string of base 10 digits. + function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); + } + + + // Compare the value of BigNumbers x and y. + function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; + } + + + /* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ + function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } + } + + + // Assumes finite n. + function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; + } + + + function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; + } + + + function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; + } + + + // EXPORT + + + BigNumber = clone(); + BigNumber['default'] = BigNumber.BigNumber = BigNumber; + + // AMD. + if (true) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return BigNumber; }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + + // Node.js and other environments that support module.exports. + } else {} +})(this); + + +/***/ }), + +/***/ 8287: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + + + +const base64 = __webpack_require__(7526) +const ieee754 = __webpack_require__(251) +const customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +const K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + const arr = new Uint8Array(1) + const proto = { foo: function () { return 42 } } + Object.setPrototypeOf(proto, Uint8Array.prototype) + Object.setPrototypeOf(arr, proto) + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + const buf = new Uint8Array(length) + Object.setPrototypeOf(buf, Buffer.prototype) + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + const valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + const b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) +Object.setPrototypeOf(Buffer, Uint8Array) + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + const length = byteLength(string, encoding) | 0 + let buf = createBuffer(length) + + const actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0 + const buf = createBuffer(length) + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView) + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + let buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype) + + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + const len = checked(obj.length) | 0 + const buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + let x = a.length + let y = b.length + + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + let i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + const buffer = Buffer.allocUnsafe(length) + let pos = 0 + for (i = 0; i < list.length; ++i) { + let buf = list[i] + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) + buf.copy(buffer, pos) + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ) + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos) + } + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + const len = string.length + const mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + let loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + let loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + const i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + const len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + const len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + const len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + const length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + let str = '' + const max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + let x = thisEnd - thisStart + let y = end - start + const len = Math.min(x, y) + + const thisCopy = this.slice(thisStart, thisEnd) + const targetCopy = target.slice(start, end) + + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + let indexSize = 1 + let arrLength = arr.length + let valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + let i + if (dir) { + let foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + let found = true + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + const remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + const strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + let i + for (i = 0; i < length; ++i) { + const parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + const remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + let loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + const res = [] + + let i = start + while (i < end) { + const firstByte = buf[i] + let codePoint = null + let bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +const MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + const len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + let res = '' + let i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + const len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + let out = '' + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]] + } + return out +} + +function utf16leSlice (buf, start, end) { + const bytes = buf.slice(start, end) + let res = '' + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + const len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + const newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype) + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + let val = this[offset + --byteLength] + let mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const lo = first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24 + + const hi = this[++offset] + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + last * 2 ** 24 + + return BigInt(lo) + (BigInt(hi) << BigInt(32)) +}) + +Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const hi = first * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + const lo = this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last + + return (BigInt(hi) << BigInt(32)) + BigInt(lo) +}) + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let i = byteLength + let mul = 1 + let val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = this[offset + 4] + + this[offset + 5] * 2 ** 8 + + this[offset + 6] * 2 ** 16 + + (last << 24) // Overflow + + return (BigInt(val) << BigInt(32)) + + BigInt(first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24) +}) + +Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + return (BigInt(val) << BigInt(32)) + + BigInt(this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last) +}) + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let mul = 1 + let i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let i = byteLength - 1 + let mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function wrtBigUInt64LE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + return offset +} + +function wrtBigUInt64BE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset + 7] = lo + lo = lo >> 8 + buf[offset + 6] = lo + lo = lo >> 8 + buf[offset + 5] = lo + lo = lo >> 8 + buf[offset + 4] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset + 3] = hi + hi = hi >> 8 + buf[offset + 2] = hi + hi = hi >> 8 + buf[offset + 1] = hi + hi = hi >> 8 + buf[offset] = hi + return offset + 8 +} + +Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = 0 + let mul = 1 + let sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = byteLength - 1 + let mul = 1 + let sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + const len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + const code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } else if (typeof val === 'boolean') { + val = Number(val) + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + let i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + const bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + const len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// CUSTOM ERRORS +// ============= + +// Simplified versions from Node, changed for Buffer-only usage +const errors = {} +function E (sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor () { + super() + + Object.defineProperty(this, 'message', { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }) + + // Add the error code to the name to include it in the stack trace. + this.name = `${this.name} [${sym}]` + // Access the stack to generate the error message including the error code + // from the name. + this.stack // eslint-disable-line no-unused-expressions + // Reset the name to the actual name. + delete this.name + } + + get code () { + return sym + } + + set code (value) { + Object.defineProperty(this, 'code', { + configurable: true, + enumerable: true, + value, + writable: true + }) + } + + toString () { + return `${this.name} [${sym}]: ${this.message}` + } + } +} + +E('ERR_BUFFER_OUT_OF_BOUNDS', + function (name) { + if (name) { + return `${name} is outside of buffer bounds` + } + + return 'Attempt to access memory outside buffer bounds' + }, RangeError) +E('ERR_INVALID_ARG_TYPE', + function (name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}` + }, TypeError) +E('ERR_OUT_OF_RANGE', + function (str, range, input) { + let msg = `The value of "${str}" is out of range.` + let received = input + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)) + } else if (typeof input === 'bigint') { + received = String(input) + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received) + } + received += 'n' + } + msg += ` It must be ${range}. Received ${received}` + return msg + }, RangeError) + +function addNumericalSeparator (val) { + let res = '' + let i = val.length + const start = val[0] === '-' ? 1 : 0 + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}` + } + return `${val.slice(0, i)}${res}` +} + +// CHECK FUNCTIONS +// =============== + +function checkBounds (buf, offset, byteLength) { + validateNumber(offset, 'offset') + if (buf[offset] === undefined || buf[offset + byteLength] === undefined) { + boundsError(offset, buf.length - (byteLength + 1)) + } +} + +function checkIntBI (value, min, max, buf, offset, byteLength) { + if (value > max || value < min) { + const n = typeof min === 'bigint' ? 'n' : '' + let range + if (byteLength > 3) { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}` + } else { + range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` + + `${(byteLength + 1) * 8 - 1}${n}` + } + } else { + range = `>= ${min}${n} and <= ${max}${n}` + } + throw new errors.ERR_OUT_OF_RANGE('value', range, value) + } + checkBounds(buf, offset, byteLength) +} + +function validateNumber (value, name) { + if (typeof value !== 'number') { + throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value) + } +} + +function boundsError (value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type) + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value) + } + + if (length < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS() + } + + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', + `>= ${type ? 1 : 0} and <= ${length}`, + value) +} + +// HELPER FUNCTIONS +// ================ + +const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function utf8ToBytes (string, units) { + units = units || Infinity + let codePoint + const length = string.length + let leadSurrogate = null + const bytes = [] + + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + let c, hi, lo + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + let i + for (i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +const hexSliceLookupTable = (function () { + const alphabet = '0123456789abcdef' + const table = new Array(256) + for (let i = 0; i < 16; ++i) { + const i16 = i * 16 + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})() + +// Return not function with Error if BigInt not supported +function defineBigIntMethod (fn) { + return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn +} + +function BufferBigIntNotDefined () { + throw new Error('BigInt not supported') +} + + +/***/ }), + +/***/ 6866: +/***/ ((module) => { + +module.exports = { + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} + + +/***/ }), + +/***/ 3144: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var bind = __webpack_require__(6743); + +var $apply = __webpack_require__(1002); +var $call = __webpack_require__(76); +var $reflectApply = __webpack_require__(7119); + +/** @type {import('./actualApply')} */ +module.exports = $reflectApply || bind.call($call, $apply); + + +/***/ }), + +/***/ 2205: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var bind = __webpack_require__(6743); +var $apply = __webpack_require__(1002); +var actualApply = __webpack_require__(3144); + +/** @type {import('./applyBind')} */ +module.exports = function applyBind() { + return actualApply(bind, $apply, arguments); +}; + + +/***/ }), + +/***/ 1002: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./functionApply')} */ +module.exports = Function.prototype.apply; + + +/***/ }), + +/***/ 76: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./functionCall')} */ +module.exports = Function.prototype.call; + + +/***/ }), + +/***/ 3126: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var bind = __webpack_require__(6743); +var $TypeError = __webpack_require__(9675); + +var $call = __webpack_require__(76); +var $actualApply = __webpack_require__(3144); + +/** @type {import('.')} */ +module.exports = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== 'function') { + throw new $TypeError('a function is required'); + } + return $actualApply(bind, $call, args); +}; + + +/***/ }), + +/***/ 7119: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./reflectApply')} */ +module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; + + +/***/ }), + +/***/ 8075: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); + +var callBind = __webpack_require__(487); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; + + +/***/ }), + +/***/ 487: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var setFunctionLength = __webpack_require__(6897); + +var $defineProperty = __webpack_require__(655); + +var callBindBasic = __webpack_require__(3126); +var applyBind = __webpack_require__(2205); + +module.exports = function callBind(originalFunction) { + var func = callBindBasic(arguments); + var adjustedLength = originalFunction.length - (arguments.length - 1); + return setFunctionLength( + func, + 1 + (adjustedLength > 0 ? adjustedLength : 0), + true + ); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} + + +/***/ }), + +/***/ 6556: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); + +var callBindBasic = __webpack_require__(3126); + +/** @type {(thisArg: string, searchString: string, position?: number) => number} */ +var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]); + +/** @type {import('.')} */ +module.exports = function callBoundIntrinsic(name, allowMissing) { + // eslint-disable-next-line no-extra-parens + var intrinsic = /** @type {Parameters[0][0]} */ (GetIntrinsic(name, !!allowMissing)); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBindBasic([intrinsic]); + } + return intrinsic; +}; + + +/***/ }), + +/***/ 41: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var $defineProperty = __webpack_require__(655); + +var $SyntaxError = __webpack_require__(8068); +var $TypeError = __webpack_require__(9675); + +var gopd = __webpack_require__(5795); + +/** @type {import('.')} */ +module.exports = function defineDataProperty( + obj, + property, + value +) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new $TypeError('`obj` must be an object or a function`'); + } + if (typeof property !== 'string' && typeof property !== 'symbol') { + throw new $TypeError('`property` must be a string or a symbol`'); + } + if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { + throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null'); + } + if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { + throw new $TypeError('`nonWritable`, if provided, must be a boolean or null'); + } + if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { + throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null'); + } + if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { + throw new $TypeError('`loose`, if provided, must be a boolean'); + } + + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + + /* @type {false | TypedPropertyDescriptor} */ + var desc = !!gopd && gopd(obj, property); + + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value: value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { + // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable + obj[property] = value; // eslint-disable-line no-param-reassign + } else { + throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); + } +}; + + +/***/ }), + +/***/ 7176: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var callBind = __webpack_require__(3126); +var gOPD = __webpack_require__(5795); + +// eslint-disable-next-line no-extra-parens, no-proto +var hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; + +// eslint-disable-next-line no-extra-parens +var desc = hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); + +var $Object = Object; +var $getPrototypeOf = $Object.getPrototypeOf; + +/** @type {import('./get')} */ +module.exports = desc && typeof desc.get === 'function' + ? callBind([desc.get]) + : typeof $getPrototypeOf === 'function' + ? /** @type {import('./get')} */ function getDunder(value) { + // eslint-disable-next-line eqeqeq + return $getPrototypeOf(value == null ? value : $Object(value)); + } + : false; + + +/***/ }), + +/***/ 655: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +var $defineProperty = Object.defineProperty || false; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} + +module.exports = $defineProperty; + + +/***/ }), + +/***/ 1237: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./eval')} */ +module.exports = EvalError; + + +/***/ }), + +/***/ 9383: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +module.exports = Error; + + +/***/ }), + +/***/ 9290: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./range')} */ +module.exports = RangeError; + + +/***/ }), + +/***/ 9538: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./ref')} */ +module.exports = ReferenceError; + + +/***/ }), + +/***/ 8068: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./syntax')} */ +module.exports = SyntaxError; + + +/***/ }), + +/***/ 9675: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./type')} */ +module.exports = TypeError; + + +/***/ }), + +/***/ 5345: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./uri')} */ +module.exports = URIError; + + +/***/ }), + +/***/ 9612: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +module.exports = Object; + + +/***/ }), + +/***/ 7007: +/***/ ((module) => { + +"use strict"; +// 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. + + + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; +module.exports.once = once; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + checkListener(listener); + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + checkListener(listener); + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function once(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } + + function resolver() { + if (typeof emitter.removeListener === 'function') { + emitter.removeListener('error', errorListener); + } + resolve([].slice.call(arguments)); + }; + + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== 'error') { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); +} + +function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + } +} + +function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === 'function') { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === 'function') { + // EventTarget does not have `error` event semantics like Node + // EventEmitters, we do not listen for `error` events here. + emitter.addEventListener(name, function wrapListener(arg) { + // IE does not have builtin `{ once: true }` support so we + // have to do it manually. + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } +} + + +/***/ }), + +/***/ 1731: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +var parse = (__webpack_require__(8835).parse) +var events = __webpack_require__(7007) +var https = __webpack_require__(1083) +var http = __webpack_require__(1568) +var util = __webpack_require__(537) + +var httpsOptions = [ + 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers', + 'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity' +] + +var bom = [239, 187, 191] +var colon = 58 +var space = 32 +var lineFeed = 10 +var carriageReturn = 13 +// Beyond 256KB we could not observe any gain in performance +var maxBufferAheadAllocation = 1024 * 256 +// Headers matching the pattern should be removed when redirecting to different origin +var reUnsafeHeader = /^(cookie|authorization)$/i + +function hasBom (buf) { + return bom.every(function (charCode, index) { + return buf[index] === charCode + }) +} + +/** + * Creates a new EventSource object + * + * @param {String} url the URL to which to connect + * @param {Object} [eventSourceInitDict] extra init params. See README for details. + * @api public + **/ +function EventSource (url, eventSourceInitDict) { + var readyState = EventSource.CONNECTING + var headers = eventSourceInitDict && eventSourceInitDict.headers + var hasNewOrigin = false + Object.defineProperty(this, 'readyState', { + get: function () { + return readyState + } + }) + + Object.defineProperty(this, 'url', { + get: function () { + return url + } + }) + + var self = this + self.reconnectInterval = 1000 + self.connectionInProgress = false + + function onConnectionClosed (message) { + if (readyState === EventSource.CLOSED) return + readyState = EventSource.CONNECTING + _emit('error', new Event('error', {message: message})) + + // The url may have been changed by a temporary redirect. If that's the case, + // revert it now, and flag that we are no longer pointing to a new origin + if (reconnectUrl) { + url = reconnectUrl + reconnectUrl = null + hasNewOrigin = false + } + setTimeout(function () { + if (readyState !== EventSource.CONNECTING || self.connectionInProgress) { + return + } + self.connectionInProgress = true + connect() + }, self.reconnectInterval) + } + + var req + var lastEventId = '' + if (headers && headers['Last-Event-ID']) { + lastEventId = headers['Last-Event-ID'] + delete headers['Last-Event-ID'] + } + + var discardTrailingNewline = false + var data = '' + var eventName = '' + + var reconnectUrl = null + + function connect () { + var options = parse(url) + var isSecure = options.protocol === 'https:' + options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' } + if (lastEventId) options.headers['Last-Event-ID'] = lastEventId + if (headers) { + var reqHeaders = hasNewOrigin ? removeUnsafeHeaders(headers) : headers + for (var i in reqHeaders) { + var header = reqHeaders[i] + if (header) { + options.headers[i] = header + } + } + } + + // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`, + // but for now exists as a backwards-compatibility layer + options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized) + + if (eventSourceInitDict && eventSourceInitDict.createConnection !== undefined) { + options.createConnection = eventSourceInitDict.createConnection + } + + // If specify http proxy, make the request to sent to the proxy server, + // and include the original url in path and Host headers + var useProxy = eventSourceInitDict && eventSourceInitDict.proxy + if (useProxy) { + var proxy = parse(eventSourceInitDict.proxy) + isSecure = proxy.protocol === 'https:' + + options.protocol = isSecure ? 'https:' : 'http:' + options.path = url + options.headers.Host = options.host + options.hostname = proxy.hostname + options.host = proxy.host + options.port = proxy.port + } + + // If https options are specified, merge them into the request options + if (eventSourceInitDict && eventSourceInitDict.https) { + for (var optName in eventSourceInitDict.https) { + if (httpsOptions.indexOf(optName) === -1) { + continue + } + + var option = eventSourceInitDict.https[optName] + if (option !== undefined) { + options[optName] = option + } + } + } + + // Pass this on to the XHR + if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) { + options.withCredentials = eventSourceInitDict.withCredentials + } + + req = (isSecure ? https : http).request(options, function (res) { + self.connectionInProgress = false + // Handle HTTP errors + if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) { + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + onConnectionClosed() + return + } + + // Handle HTTP redirects + if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) { + var location = res.headers.location + if (!location) { + // Server sent redirect response without Location header. + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + return + } + var prevOrigin = new URL(url).origin + var nextOrigin = new URL(location).origin + hasNewOrigin = prevOrigin !== nextOrigin + if (res.statusCode === 307) reconnectUrl = url + url = location + process.nextTick(connect) + return + } + + if (res.statusCode !== 200) { + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + return self.close() + } + + readyState = EventSource.OPEN + res.on('close', function () { + res.removeAllListeners('close') + res.removeAllListeners('end') + onConnectionClosed() + }) + + res.on('end', function () { + res.removeAllListeners('close') + res.removeAllListeners('end') + onConnectionClosed() + }) + _emit('open', new Event('open')) + + // text/event-stream parser adapted from webkit's + // Source/WebCore/page/EventSource.cpp + var buf + var newBuffer + var startingPos = 0 + var startingFieldLength = -1 + var newBufferSize = 0 + var bytesUsed = 0 + + res.on('data', function (chunk) { + if (!buf) { + buf = chunk + if (hasBom(buf)) { + buf = buf.slice(bom.length) + } + bytesUsed = buf.length + } else { + if (chunk.length > buf.length - bytesUsed) { + newBufferSize = (buf.length * 2) + chunk.length + if (newBufferSize > maxBufferAheadAllocation) { + newBufferSize = buf.length + chunk.length + maxBufferAheadAllocation + } + newBuffer = Buffer.alloc(newBufferSize) + buf.copy(newBuffer, 0, 0, bytesUsed) + buf = newBuffer + } + chunk.copy(buf, bytesUsed) + bytesUsed += chunk.length + } + + var pos = 0 + var length = bytesUsed + + while (pos < length) { + if (discardTrailingNewline) { + if (buf[pos] === lineFeed) { + ++pos + } + discardTrailingNewline = false + } + + var lineLength = -1 + var fieldLength = startingFieldLength + var c + + for (var i = startingPos; lineLength < 0 && i < length; ++i) { + c = buf[i] + if (c === colon) { + if (fieldLength < 0) { + fieldLength = i - pos + } + } else if (c === carriageReturn) { + discardTrailingNewline = true + lineLength = i - pos + } else if (c === lineFeed) { + lineLength = i - pos + } + } + + if (lineLength < 0) { + startingPos = length - pos + startingFieldLength = fieldLength + break + } else { + startingPos = 0 + startingFieldLength = -1 + } + + parseEventStreamLine(buf, pos, fieldLength, lineLength) + + pos += lineLength + 1 + } + + if (pos === length) { + buf = void 0 + bytesUsed = 0 + } else if (pos > 0) { + buf = buf.slice(pos, bytesUsed) + bytesUsed = buf.length + } + }) + }) + + req.on('error', function (err) { + self.connectionInProgress = false + onConnectionClosed(err.message) + }) + + if (req.setNoDelay) req.setNoDelay(true) + req.end() + } + + connect() + + function _emit () { + if (self.listeners(arguments[0]).length > 0) { + self.emit.apply(self, arguments) + } + } + + this._close = function () { + if (readyState === EventSource.CLOSED) return + readyState = EventSource.CLOSED + if (req.abort) req.abort() + if (req.xhr && req.xhr.abort) req.xhr.abort() + } + + function parseEventStreamLine (buf, pos, fieldLength, lineLength) { + if (lineLength === 0) { + if (data.length > 0) { + var type = eventName || 'message' + _emit(type, new MessageEvent(type, { + data: data.slice(0, -1), // remove trailing newline + lastEventId: lastEventId, + origin: new URL(url).origin + })) + data = '' + } + eventName = void 0 + } else if (fieldLength > 0) { + var noValue = fieldLength < 0 + var step = 0 + var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString() + + if (noValue) { + step = lineLength + } else if (buf[pos + fieldLength + 1] !== space) { + step = fieldLength + 1 + } else { + step = fieldLength + 2 + } + pos += step + + var valueLength = lineLength - step + var value = buf.slice(pos, pos + valueLength).toString() + + if (field === 'data') { + data += value + '\n' + } else if (field === 'event') { + eventName = value + } else if (field === 'id') { + lastEventId = value + } else if (field === 'retry') { + var retry = parseInt(value, 10) + if (!Number.isNaN(retry)) { + self.reconnectInterval = retry + } + } + } + } +} + +module.exports = EventSource + +util.inherits(EventSource, events.EventEmitter) +EventSource.prototype.constructor = EventSource; // make stacktraces readable + +['open', 'error', 'message'].forEach(function (method) { + Object.defineProperty(EventSource.prototype, 'on' + method, { + /** + * Returns the current listener + * + * @return {Mixed} the set function or undefined + * @api private + */ + get: function get () { + var listener = this.listeners(method)[0] + return listener ? (listener._listener ? listener._listener : listener) : undefined + }, + + /** + * Start listening for events + * + * @param {Function} listener the listener + * @return {Mixed} the set function or undefined + * @api private + */ + set: function set (listener) { + this.removeAllListeners(method) + this.addEventListener(method, listener) + } + }) +}) + +/** + * Ready states + */ +Object.defineProperty(EventSource, 'CONNECTING', {enumerable: true, value: 0}) +Object.defineProperty(EventSource, 'OPEN', {enumerable: true, value: 1}) +Object.defineProperty(EventSource, 'CLOSED', {enumerable: true, value: 2}) + +EventSource.prototype.CONNECTING = 0 +EventSource.prototype.OPEN = 1 +EventSource.prototype.CLOSED = 2 + +/** + * Closes the connection, if one is made, and sets the readyState attribute to 2 (closed) + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close + * @api public + */ +EventSource.prototype.close = function () { + this._close() +} + +/** + * Emulates the W3C Browser based WebSocket interface using addEventListener. + * + * @param {String} type A string representing the event type to listen out for + * @param {Function} listener callback + * @see https://developer.mozilla.org/en/DOM/element.addEventListener + * @see http://dev.w3.org/html5/websockets/#the-websocket-interface + * @api public + */ +EventSource.prototype.addEventListener = function addEventListener (type, listener) { + if (typeof listener === 'function') { + // store a reference so we can return the original function again + listener._listener = listener + this.on(type, listener) + } +} + +/** + * Emulates the W3C Browser based WebSocket interface using dispatchEvent. + * + * @param {Event} event An event to be dispatched + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent + * @api public + */ +EventSource.prototype.dispatchEvent = function dispatchEvent (event) { + if (!event.type) { + throw new Error('UNSPECIFIED_EVENT_TYPE_ERR') + } + // if event is instance of an CustomEvent (or has 'details' property), + // send the detail object as the payload for the event + this.emit(event.type, event.detail) +} + +/** + * Emulates the W3C Browser based WebSocket interface using removeEventListener. + * + * @param {String} type A string representing the event type to remove + * @param {Function} listener callback + * @see https://developer.mozilla.org/en/DOM/element.removeEventListener + * @see http://dev.w3.org/html5/websockets/#the-websocket-interface + * @api public + */ +EventSource.prototype.removeEventListener = function removeEventListener (type, listener) { + if (typeof listener === 'function') { + listener._listener = undefined + this.removeListener(type, listener) + } +} + +/** + * W3C Event + * + * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event + * @api private + */ +function Event (type, optionalProperties) { + Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) + if (optionalProperties) { + for (var f in optionalProperties) { + if (optionalProperties.hasOwnProperty(f)) { + Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true }) + } + } + } +} + +/** + * W3C MessageEvent + * + * @see http://www.w3.org/TR/webmessaging/#event-definitions + * @api private + */ +function MessageEvent (type, eventInitDict) { + Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) + for (var f in eventInitDict) { + if (eventInitDict.hasOwnProperty(f)) { + Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true }) + } + } +} + +/** + * Returns a new object of headers that does not include any authorization and cookie headers + * + * @param {Object} headers An object of headers ({[headerName]: headerValue}) + * @return {Object} a new object of headers + * @api private + */ +function removeUnsafeHeaders (headers) { + var safe = {} + for (var key in headers) { + if (reUnsafeHeader.test(key)) { + continue + } + + safe[key] = headers[key] + } + + return safe +} + + +/***/ }), + +/***/ 2682: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isCallable = __webpack_require__(9600); + +var toStr = Object.prototype.toString; +var hasOwnProperty = Object.prototype.hasOwnProperty; + +var forEachArray = function forEachArray(array, iterator, receiver) { + for (var i = 0, len = array.length; i < len; i++) { + if (hasOwnProperty.call(array, i)) { + if (receiver == null) { + iterator(array[i], i, array); + } else { + iterator.call(receiver, array[i], i, array); + } + } + } +}; + +var forEachString = function forEachString(string, iterator, receiver) { + for (var i = 0, len = string.length; i < len; i++) { + // no such thing as a sparse string. + if (receiver == null) { + iterator(string.charAt(i), i, string); + } else { + iterator.call(receiver, string.charAt(i), i, string); + } + } +}; + +var forEachObject = function forEachObject(object, iterator, receiver) { + for (var k in object) { + if (hasOwnProperty.call(object, k)) { + if (receiver == null) { + iterator(object[k], k, object); + } else { + iterator.call(receiver, object[k], k, object); + } + } + } +}; + +var forEach = function forEach(list, iterator, thisArg) { + if (!isCallable(iterator)) { + throw new TypeError('iterator must be a function'); + } + + var receiver; + if (arguments.length >= 3) { + receiver = thisArg; + } + + if (toStr.call(list) === '[object Array]') { + forEachArray(list, iterator, receiver); + } else if (typeof list === 'string') { + forEachString(list, iterator, receiver); + } else { + forEachObject(list, iterator, receiver); + } +}; + +module.exports = forEach; + + +/***/ }), + +/***/ 1734: +/***/ ((module) => { + +"use strict"; + + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + + +/***/ }), + +/***/ 6743: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var implementation = __webpack_require__(1734); + +module.exports = Function.prototype.bind || implementation; + + +/***/ }), + +/***/ 453: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var undefined; + +var $Object = __webpack_require__(9612); + +var $Error = __webpack_require__(9383); +var $EvalError = __webpack_require__(1237); +var $RangeError = __webpack_require__(9290); +var $ReferenceError = __webpack_require__(9538); +var $SyntaxError = __webpack_require__(8068); +var $TypeError = __webpack_require__(9675); +var $URIError = __webpack_require__(5345); + +var abs = __webpack_require__(1514); +var floor = __webpack_require__(8968); +var max = __webpack_require__(6188); +var min = __webpack_require__(8002); +var pow = __webpack_require__(5880); + +var $Function = Function; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = __webpack_require__(5795); +var $defineProperty = __webpack_require__(655); + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = __webpack_require__(4039)(); +var getDunderProto = __webpack_require__(7176); + +var getProto = (typeof Reflect === 'function' && Reflect.getPrototypeOf) + || $Object.getPrototypeOf + || getDunderProto; + +var $apply = __webpack_require__(1002); +var $call = __webpack_require__(76); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': $Object, + '%Object.getOwnPropertyDescriptor%': $gOPD, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, + + '%Function.prototype.call%': $call, + '%Function.prototype.apply%': $apply, + '%Object.defineProperty%': $defineProperty, + '%Math.abs%': abs, + '%Math.floor%': floor, + '%Math.max%': max, + '%Math.min%': min, + '%Math.pow%': pow +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = __webpack_require__(6743); +var hasOwn = __webpack_require__(9957); +var $concat = bind.call($call, Array.prototype.concat); +var $spliceApply = bind.call($apply, Array.prototype.splice); +var $replace = bind.call($call, String.prototype.replace); +var $strSlice = bind.call($call, String.prototype.slice); +var $exec = bind.call($call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; + + +/***/ }), + +/***/ 6549: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./gOPD')} */ +module.exports = Object.getOwnPropertyDescriptor; + + +/***/ }), + +/***/ 5795: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +/** @type {import('.')} */ +var $gOPD = __webpack_require__(6549); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; + + +/***/ }), + +/***/ 592: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var $defineProperty = __webpack_require__(655); + +var hasPropertyDescriptors = function hasPropertyDescriptors() { + return !!$defineProperty; +}; + +hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + // node v0.6 has a bug where array lengths can be Set but not Defined + if (!$defineProperty) { + return null; + } + try { + return $defineProperty([], 'length', { value: 1 }).length !== 1; + } catch (e) { + // In Firefox 4-22, defining length on an array throws an exception. + return true; + } +}; + +module.exports = hasPropertyDescriptors; + + +/***/ }), + +/***/ 4039: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = __webpack_require__(1333); + +/** @type {import('.')} */ +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; + + +/***/ }), + +/***/ 1333: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./shams')} */ +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + /** @type {{ [k in symbol]?: unknown }} */ + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + // eslint-disable-next-line no-extra-parens + var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; + + +/***/ }), + +/***/ 9092: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hasSymbols = __webpack_require__(1333); + +/** @type {import('.')} */ +module.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; +}; + + +/***/ }), + +/***/ 9957: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = __webpack_require__(6743); + +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); + + +/***/ }), + +/***/ 1083: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var http = __webpack_require__(1568) +var url = __webpack_require__(8835) + +var https = module.exports + +for (var key in http) { + if (http.hasOwnProperty(key)) https[key] = http[key] +} + +https.request = function (params, cb) { + params = validateParams(params) + return http.request.call(this, params, cb) +} + +https.get = function (params, cb) { + params = validateParams(params) + return http.get.call(this, params, cb) +} + +function validateParams (params) { + if (typeof params === 'string') { + params = url.parse(params) + } + if (!params.protocol) { + params.protocol = 'https:' + } + if (params.protocol !== 'https:') { + throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"') + } + return params +} + + +/***/ }), + +/***/ 251: +/***/ ((__unused_webpack_module, exports) => { + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + + +/***/ }), + +/***/ 6698: +/***/ ((module) => { + +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 + } + } +} + + +/***/ }), + +/***/ 7244: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var hasToStringTag = __webpack_require__(9092)(); +var callBound = __webpack_require__(6556); + +var $toString = callBound('Object.prototype.toString'); + +/** @type {import('.')} */ +var isStandardArguments = function isArguments(value) { + if ( + hasToStringTag + && value + && typeof value === 'object' + && Symbol.toStringTag in value + ) { + return false; + } + return $toString(value) === '[object Arguments]'; +}; + +/** @type {import('.')} */ +var isLegacyArguments = function isArguments(value) { + if (isStandardArguments(value)) { + return true; + } + return value !== null + && typeof value === 'object' + && 'length' in value + && typeof value.length === 'number' + && value.length >= 0 + && $toString(value) !== '[object Array]' + && 'callee' in value + && $toString(value.callee) === '[object Function]'; +}; + +var supportsStandardArguments = (function () { + return isStandardArguments(arguments); +}()); + +// @ts-expect-error TODO make this not error +isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests + +/** @type {import('.')} */ +module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; + + +/***/ }), + +/***/ 9600: +/***/ ((module) => { + +"use strict"; + + +var fnToStr = Function.prototype.toString; +var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply; +var badArrayLike; +var isCallableMarker; +if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') { + try { + badArrayLike = Object.defineProperty({}, 'length', { + get: function () { + throw isCallableMarker; + } + }); + isCallableMarker = {}; + // eslint-disable-next-line no-throw-literal + reflectApply(function () { throw 42; }, null, badArrayLike); + } catch (_) { + if (_ !== isCallableMarker) { + reflectApply = null; + } + } +} else { + reflectApply = null; +} + +var constructorRegex = /^\s*class\b/; +var isES6ClassFn = function isES6ClassFunction(value) { + try { + var fnStr = fnToStr.call(value); + return constructorRegex.test(fnStr); + } catch (e) { + return false; // not a function + } +}; + +var tryFunctionObject = function tryFunctionToStr(value) { + try { + if (isES6ClassFn(value)) { return false; } + fnToStr.call(value); + return true; + } catch (e) { + return false; + } +}; +var toStr = Object.prototype.toString; +var objectClass = '[object Object]'; +var fnClass = '[object Function]'; +var genClass = '[object GeneratorFunction]'; +var ddaClass = '[object HTMLAllCollection]'; // IE 11 +var ddaClass2 = '[object HTML document.all class]'; +var ddaClass3 = '[object HTMLCollection]'; // IE 9-10 +var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag` + +var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing + +var isDDA = function isDocumentDotAll() { return false; }; +if (typeof document === 'object') { + // Firefox 3 canonicalizes DDA to undefined when it's not accessed directly + var all = document.all; + if (toStr.call(all) === toStr.call(document.all)) { + isDDA = function isDocumentDotAll(value) { + /* globals document: false */ + // in IE 6-8, typeof document.all is "object" and it's truthy + if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) { + try { + var str = toStr.call(value); + return ( + str === ddaClass + || str === ddaClass2 + || str === ddaClass3 // opera 12.16 + || str === objectClass // IE 6-8 + ) && value('') == null; // eslint-disable-line eqeqeq + } catch (e) { /**/ } + } + return false; + }; + } +} + +module.exports = reflectApply + ? function isCallable(value) { + if (isDDA(value)) { return true; } + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + try { + reflectApply(value, null, badArrayLike); + } catch (e) { + if (e !== isCallableMarker) { return false; } + } + return !isES6ClassFn(value) && tryFunctionObject(value); + } + : function isCallable(value) { + if (isDDA(value)) { return true; } + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + if (hasToStringTag) { return tryFunctionObject(value); } + if (isES6ClassFn(value)) { return false; } + var strClass = toStr.call(value); + if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; } + return tryFunctionObject(value); + }; + + +/***/ }), + +/***/ 8184: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var toStr = Object.prototype.toString; +var fnToStr = Function.prototype.toString; +var isFnRegex = /^\s*(?:function)?\*/; +var hasToStringTag = __webpack_require__(9092)(); +var getProto = Object.getPrototypeOf; +var getGeneratorFunc = function () { // eslint-disable-line consistent-return + if (!hasToStringTag) { + return false; + } + try { + return Function('return function*() {}')(); + } catch (e) { + } +}; +var GeneratorFunction; + +module.exports = function isGeneratorFunction(fn) { + if (typeof fn !== 'function') { + return false; + } + if (isFnRegex.test(fnToStr.call(fn))) { + return true; + } + if (!hasToStringTag) { + var str = toStr.call(fn); + return str === '[object GeneratorFunction]'; + } + if (!getProto) { + return false; + } + if (typeof GeneratorFunction === 'undefined') { + var generatorFunc = getGeneratorFunc(); + GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; + } + return getProto(fn) === GeneratorFunction; +}; + + +/***/ }), + +/***/ 5680: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var whichTypedArray = __webpack_require__(5767); + +/** @type {import('.')} */ +module.exports = function isTypedArray(value) { + return !!whichTypedArray(value); +}; + + +/***/ }), + +/***/ 1514: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./abs')} */ +module.exports = Math.abs; + + +/***/ }), + +/***/ 8968: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./abs')} */ +module.exports = Math.floor; + + +/***/ }), + +/***/ 6188: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./max')} */ +module.exports = Math.max; + + +/***/ }), + +/***/ 8002: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./min')} */ +module.exports = Math.min; + + +/***/ }), + +/***/ 5880: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./pow')} */ +module.exports = Math.pow; + + +/***/ }), + +/***/ 8859: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var hasMap = typeof Map === 'function' && Map.prototype; +var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; +var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; +var mapForEach = hasMap && Map.prototype.forEach; +var hasSet = typeof Set === 'function' && Set.prototype; +var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; +var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; +var setForEach = hasSet && Set.prototype.forEach; +var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; +var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; +var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; +var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; +var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; +var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; +var booleanValueOf = Boolean.prototype.valueOf; +var objectToString = Object.prototype.toString; +var functionToString = Function.prototype.toString; +var $match = String.prototype.match; +var $slice = String.prototype.slice; +var $replace = String.prototype.replace; +var $toUpperCase = String.prototype.toUpperCase; +var $toLowerCase = String.prototype.toLowerCase; +var $test = RegExp.prototype.test; +var $concat = Array.prototype.concat; +var $join = Array.prototype.join; +var $arrSlice = Array.prototype.slice; +var $floor = Math.floor; +var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; +var gOPS = Object.getOwnPropertySymbols; +var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; +var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; +// ie, `has-tostringtag/shams +var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') + ? Symbol.toStringTag + : null; +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( + [].__proto__ === Array.prototype // eslint-disable-line no-proto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null +); + +function addNumericSeparator(num, str) { + if ( + num === Infinity + || num === -Infinity + || num !== num + || (num && num > -1000 && num < 1000) + || $test.call(/e/, str) + ) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); +} + +var utilInspect = __webpack_require__(2634); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + +var quotes = { + __proto__: null, + 'double': '"', + single: "'" +}; +var quoteREs = { + __proto__: null, + 'double': /(["\\])/g, + single: /(['\\])/g +}; + +module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + + if (has(opts, 'quoteStyle') && !has(quotes, opts.quoteStyle)) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if ( + has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' + ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity + : opts.maxStringLength !== null + ) + ) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } + + if ( + has(opts, 'indent') + && opts.indent !== null + && opts.indent !== '\t' + && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) + ) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { depth = 0; } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray(obj) ? '[Array]' : '[Object]'; + } + + var indent = getIndent(opts, depth); + + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { s += '...'; } + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { return '[]'; } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { return '[' + String(obj) + ']'; } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + } + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + // note: in IE 8, sometimes `global !== window` but both are the prototypes of each other + /* eslint-env browser */ + if (typeof window !== 'undefined' && obj === window) { + return '{ [object Window] }'; + } + if ( + (typeof globalThis !== 'undefined' && obj === globalThis) + || (typeof __webpack_require__.g !== 'undefined' && obj === __webpack_require__.g) + ) { + return '{ [object globalThis] }'; + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { return tag + '{}'; } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); +}; + +function wrapQuotes(s, defaultStyle, opts) { + var style = opts.quoteStyle || defaultStyle; + var quoteChar = quotes[style]; + return quoteChar + s + quoteChar; +} + +function quote(s) { + return $replace.call(String(s), /"/g, '"'); +} + +function isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } + +// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives +function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; +} + +function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; +} + +var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; +function has(obj, key) { + return hasOwn.call(obj, key); +} + +function toStr(obj) { + return objectToString.call(obj); +} + +function nameOf(f) { + if (f.name) { return f.name; } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { return m[1]; } + return null; +} + +function indexOf(xs, x) { + if (xs.indexOf) { return xs.indexOf(x); } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { return i; } + } + return -1; +} + +function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; +} + +function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isElement(x) { + if (!x || typeof x !== 'object') { return false; } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; +} + +function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + var quoteRE = quoteREs[opts.quoteStyle || 'single']; + quoteRE.lastIndex = 0; + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, quoteRE, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} + +function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { return '\\' + x; } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); +} + +function markBoxed(str) { + return 'Object(' + str + ')'; +} + +function weakCollectionOf(type) { + return type + ' { ? }'; +} + +function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; +} + +function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; +} + +function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; +} + +function indentedJoin(xs, indent) { + if (xs.length === 0) { return ''; } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; +} + +function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; +} + + +/***/ }), + +/***/ 6578: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +module.exports = [ + 'Float32Array', + 'Float64Array', + 'Int8Array', + 'Int16Array', + 'Int32Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Uint16Array', + 'Uint32Array', + 'BigInt64Array', + 'BigUint64Array' +]; + + +/***/ }), + +/***/ 4765: +/***/ ((module) => { + +"use strict"; + + +var replace = String.prototype.replace; +var percentTwenties = /%20/g; + +var Format = { + RFC1738: 'RFC1738', + RFC3986: 'RFC3986' +}; + +module.exports = { + 'default': Format.RFC3986, + formatters: { + RFC1738: function (value) { + return replace.call(value, percentTwenties, '+'); + }, + RFC3986: function (value) { + return String(value); + } + }, + RFC1738: Format.RFC1738, + RFC3986: Format.RFC3986 +}; + + +/***/ }), + +/***/ 5373: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var stringify = __webpack_require__(8636); +var parse = __webpack_require__(2642); +var formats = __webpack_require__(4765); + +module.exports = { + formats: formats, + parse: parse, + stringify: stringify +}; + + +/***/ }), + +/***/ 2642: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(7720); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var defaults = { + allowDots: false, + allowEmptyArrays: false, + allowPrototypes: false, + allowSparse: false, + arrayLimit: 20, + charset: 'utf-8', + charsetSentinel: false, + comma: false, + decodeDotInKeys: false, + decoder: utils.decode, + delimiter: '&', + depth: 5, + duplicates: 'combine', + ignoreQueryPrefix: false, + interpretNumericEntities: false, + parameterLimit: 1000, + parseArrays: true, + plainObjects: false, + strictDepth: false, + strictNullHandling: false +}; + +var interpretNumericEntities = function (str) { + return str.replace(/&#(\d+);/g, function ($0, numberStr) { + return String.fromCharCode(parseInt(numberStr, 10)); + }); +}; + +var parseArrayValue = function (val, options) { + if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { + return val.split(','); + } + + return val; +}; + +// This is what browsers will submit when the ✓ character occurs in an +// application/x-www-form-urlencoded body and the encoding of the page containing +// the form is iso-8859-1, or when the submitted form has an accept-charset +// attribute of iso-8859-1. Presumably also with other charsets that do not contain +// the ✓ character, such as us-ascii. +var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') + +// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. +var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') + +var parseValues = function parseQueryStringValues(str, options) { + var obj = { __proto__: null }; + + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + cleanStr = cleanStr.replace(/%5B/gi, '[').replace(/%5D/gi, ']'); + var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; + var parts = cleanStr.split(options.delimiter, limit); + var skipIndex = -1; // Keep track of where the utf8 sentinel was found + var i; + + var charset = options.charset; + if (options.charsetSentinel) { + for (i = 0; i < parts.length; ++i) { + if (parts[i].indexOf('utf8=') === 0) { + if (parts[i] === charsetSentinel) { + charset = 'utf-8'; + } else if (parts[i] === isoSentinel) { + charset = 'iso-8859-1'; + } + skipIndex = i; + i = parts.length; // The eslint settings do not allow break; + } + } + } + + for (i = 0; i < parts.length; ++i) { + if (i === skipIndex) { + continue; + } + var part = parts[i]; + + var bracketEqualsPos = part.indexOf(']='); + var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; + + var key; + var val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset, 'key'); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); + val = utils.maybeMap( + parseArrayValue(part.slice(pos + 1), options), + function (encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, 'value'); + } + ); + } + + if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { + val = interpretNumericEntities(String(val)); + } + + if (part.indexOf('[]=') > -1) { + val = isArray(val) ? [val] : val; + } + + var existing = has.call(obj, key); + if (existing && options.duplicates === 'combine') { + obj[key] = utils.combine(obj[key], val); + } else if (!existing || options.duplicates === 'last') { + obj[key] = val; + } + } + + return obj; +}; + +var parseObject = function (chain, val, options, valuesParsed) { + var leaf = valuesParsed ? val : parseArrayValue(val, options); + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]' && options.parseArrays) { + obj = options.allowEmptyArrays && (leaf === '' || (options.strictNullHandling && leaf === null)) + ? [] + : [].concat(leaf); + } else { + obj = options.plainObjects ? { __proto__: null } : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, '.') : cleanRoot; + var index = parseInt(decodedRoot, 10); + if (!options.parseArrays && decodedRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== decodedRoot + && String(index) === decodedRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else if (decodedRoot !== '__proto__') { + obj[decodedRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = options.depth > 0 && brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, check strictDepth option for throw, else just add whatever is left + + if (segment) { + if (options.strictDepth === true) { + throw new RangeError('Input depth exceeded depth option of ' + options.depth + ' and strictDepth is true'); + } + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options, valuesParsed); +}; + +var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } + + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); + } + + if (typeof opts.decodeDotInKeys !== 'undefined' && typeof opts.decodeDotInKeys !== 'boolean') { + throw new TypeError('`decodeDotInKeys` option can only be `true` or `false`, when provided'); + } + + if (opts.decoder !== null && typeof opts.decoder !== 'undefined' && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; + + var duplicates = typeof opts.duplicates === 'undefined' ? defaults.duplicates : opts.duplicates; + + if (duplicates !== 'combine' && duplicates !== 'first' && duplicates !== 'last') { + throw new TypeError('The duplicates option must be either combine, first, or last'); + } + + var allowDots = typeof opts.allowDots === 'undefined' ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + + return { + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, + decodeDotInKeys: typeof opts.decodeDotInKeys === 'boolean' ? opts.decodeDotInKeys : defaults.decodeDotInKeys, + decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, + duplicates: duplicates, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, + strictDepth: typeof opts.strictDepth === 'boolean' ? !!opts.strictDepth : defaults.strictDepth, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (str, opts) { + var options = normalizeParseOptions(opts); + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? { __proto__: null } : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? { __proto__: null } : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); + obj = utils.merge(obj, newObj, options); + } + + if (options.allowSparse === true) { + return obj; + } + + return utils.compact(obj); +}; + + +/***/ }), + +/***/ 8636: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var getSideChannel = __webpack_require__(920); +var utils = __webpack_require__(7720); +var formats = __webpack_require__(4765); +var has = Object.prototype.hasOwnProperty; + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { + return prefix; + } +}; + +var isArray = Array.isArray; +var push = Array.prototype.push; +var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); +}; + +var toISO = Date.prototype.toISOString; + +var defaultFormat = formats['default']; +var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: 'indices', + charset: 'utf-8', + charsetSentinel: false, + commaRoundTrip: false, + delimiter: '&', + encode: true, + encodeDotInKeys: false, + encoder: utils.encode, + encodeValuesOnly: false, + filter: void undefined, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var isNonNullishPrimitive = function isNonNullishPrimitive(v) { + return typeof v === 'string' + || typeof v === 'number' + || typeof v === 'boolean' + || typeof v === 'symbol' + || typeof v === 'bigint'; +}; + +var sentinel = {}; + +var stringify = function stringify( + object, + prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + sideChannel +) { + var obj = object; + + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { + // Where object last appeared in the ref tree + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } else { + findFlag = true; // Break while + } + } + if (typeof tmpSc.get(sentinel) === 'undefined') { + step = 0; + } + } + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = utils.maybeMap(obj, function (value) { + if (value instanceof Date) { + return serializeDate(value); + } + return value; + }); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix; + } + + obj = ''; + } + + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (generateArrayPrefix === 'comma' && isArray(obj)) { + // we need to join elements in + if (encodeValuesOnly && encoder) { + obj = utils.maybeMap(obj, encoder); + } + objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; + } else if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + var encodedPrefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); + + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + '[]' : encodedPrefix; + + if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + return adjustedPrefix + '[]'; + } + + for (var j = 0; j < objKeys.length; ++j) { + var key = objKeys[j]; + var value = typeof key === 'object' && key && typeof key.value !== 'undefined' + ? key.value + : obj[key]; + + if (skipNulls && value === null) { + continue; + } + + var encodedKey = allowDots && encodeDotInKeys ? String(key).replace(/\./g, '%2E') : String(key); + var keyPrefix = isArray(obj) + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + encodedKey : '[' + encodedKey + ']'); + + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values, stringify( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + + return values; +}; + +var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; + } + + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); + } + + if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { + throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); + } + + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + var format = formats['default']; + if (typeof opts.format !== 'undefined') { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + var arrayFormat; + if (opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if ('indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = defaults.arrayFormat; + } + + if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + + var allowDots = typeof opts.allowDots === 'undefined' ? opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat: arrayFormat, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat]; + var commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (options.sort) { + objKeys.sort(options.sort); + } + + var sideChannel = getSideChannel(); + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + var value = obj[key]; + + if (options.skipNulls && value === null) { + continue; + } + pushToArray(keys, stringify( + value, + key, + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + + return joined.length > 0 ? prefix + joined : ''; +}; + + +/***/ }), + +/***/ 7720: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var formats = __webpack_require__(4765); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } +}; + +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? { __proto__: null } : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +var merge = function merge(target, source, options) { + /* eslint no-param-reassign: 0 */ + if (!source) { + return target; + } + + if (typeof source !== 'object' && typeof source !== 'function') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ( + (options && (options.plainObjects || options.allowPrototypes)) + || !has.call(Object.prototype, source) + ) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +var decode = function (str, defaultDecoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } +}; + +var limit = 1024; + +/* eslint operator-linebreak: [2, "before"] */ + +var encode = function encode(str, defaultEncoder, charset, kind, format) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== 'string') { + string = String(str); + } + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var j = 0; j < string.length; j += limit) { + var segment = string.length >= limit ? string.slice(j, j + limit) : string; + var arr = []; + + for (var i = 0; i < segment.length; ++i) { + var c = segment.charCodeAt(i); + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + arr[arr.length] = segment.charAt(i); + continue; + } + + if (c < 0x80) { + arr[arr.length] = hexTable[c]; + continue; + } + + if (c < 0x800) { + arr[arr.length] = hexTable[0xC0 | (c >> 6)] + + hexTable[0x80 | (c & 0x3F)]; + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + arr[arr.length] = hexTable[0xE0 | (c >> 12)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (segment.charCodeAt(i) & 0x3FF)); + + arr[arr.length] = hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + out += arr.join(''); + } + + return out; +}; + +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + compactQueue(queue); + + return value; +}; + +var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +var isBuffer = function isBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +var combine = function combine(a, b) { + return [].concat(a, b); +}; + +var maybeMap = function maybeMap(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +}; + +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isRegExp: isRegExp, + maybeMap: maybeMap, + merge: merge +}; + + +/***/ }), + +/***/ 3209: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"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 = (__webpack_require__(2861).Buffer) +var crypto = __webpack_require__.g.crypto || __webpack_require__.g.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 +} + + +/***/ }), + +/***/ 6048: +/***/ ((module) => { + +"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.F = codes; + + +/***/ }), + +/***/ 5382: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// 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. + + + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; +/**/ + +module.exports = Duplex; +var Readable = __webpack_require__(5412); +var Writable = __webpack_require__(6708); +__webpack_require__(6698)(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; + } +}); + +/***/ }), + +/***/ 3600: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// 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. + + + +module.exports = PassThrough; +var Transform = __webpack_require__(4610); +__webpack_require__(6698)(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); +}; + +/***/ }), + +/***/ 5412: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// 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. + + + +module.exports = Readable; + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = (__webpack_require__(7007).EventEmitter); +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = __webpack_require__(345); +/**/ + +var Buffer = (__webpack_require__(8287).Buffer); +var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : 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 = __webpack_require__(9838); +var debug; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + +var BufferList = __webpack_require__(2726); +var destroyImpl = __webpack_require__(5896); +var _require = __webpack_require__(5291), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = (__webpack_require__(6048)/* .codes */ .F), + 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; +__webpack_require__(6698)(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 || __webpack_require__(5382); + 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 = (__webpack_require__(3141)/* .StringDecoder */ .I); + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || __webpack_require__(5382); + 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 = (__webpack_require__(3141)/* .StringDecoder */ .I); + 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 = __webpack_require__(2955); + } + 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 = __webpack_require__(5157); + } + 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; +} + +/***/ }), + +/***/ 4610: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// 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. + + + +module.exports = Transform; +var _require$codes = (__webpack_require__(6048)/* .codes */ .F), + 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 = __webpack_require__(5382); +__webpack_require__(6698)(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); +} + +/***/ }), + +/***/ 6708: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// 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. + + + +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: __webpack_require__(4643) +}; +/**/ + +/**/ +var Stream = __webpack_require__(345); +/**/ + +var Buffer = (__webpack_require__(8287).Buffer); +var OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : 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 = __webpack_require__(5896); +var _require = __webpack_require__(5291), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = (__webpack_require__(6048)/* .codes */ .F), + 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; +__webpack_require__(6698)(Writable, Stream); +function nop() {} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || __webpack_require__(5382); + 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 || __webpack_require__(5382); + + // 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); +}; + +/***/ }), + +/***/ 2955: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"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 = __webpack_require__(6238); +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; + +/***/ }), + +/***/ 2726: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"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 = __webpack_require__(8287), + Buffer = _require.Buffer; +var _require2 = __webpack_require__(5340), + 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; +}(); + +/***/ }), + +/***/ 5896: +/***/ ((module) => { + +"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 +}; + +/***/ }), + +/***/ 6238: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + + + +var ERR_STREAM_PREMATURE_CLOSE = (__webpack_require__(6048)/* .codes */ .F).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; + +/***/ }), + +/***/ 5157: +/***/ ((module) => { + +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; + + +/***/ }), + +/***/ 7758: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + + + +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} +var _require$codes = (__webpack_require__(6048)/* .codes */ .F), + 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 = __webpack_require__(6238); + 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; + +/***/ }), + +/***/ 5291: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var ERR_INVALID_OPT_VALUE = (__webpack_require__(6048)/* .codes */ .F).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 +}; + +/***/ }), + +/***/ 345: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +module.exports = __webpack_require__(7007).EventEmitter; + + +/***/ }), + +/***/ 8399: +/***/ ((module, exports, __webpack_require__) => { + +exports = module.exports = __webpack_require__(5412); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = __webpack_require__(6708); +exports.Duplex = __webpack_require__(5382); +exports.Transform = __webpack_require__(4610); +exports.PassThrough = __webpack_require__(3600); +exports.finished = __webpack_require__(6238); +exports.pipeline = __webpack_require__(7758); + + +/***/ }), + +/***/ 2861: +/***/ ((module, exports, __webpack_require__) => { + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(8287) +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) +} + + +/***/ }), + +/***/ 6897: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); +var define = __webpack_require__(41); +var hasDescriptors = __webpack_require__(592)(); +var gOPD = __webpack_require__(5795); + +var $TypeError = __webpack_require__(9675); +var $floor = GetIntrinsic('%Math.floor%'); + +/** @type {import('.')} */ +module.exports = function setFunctionLength(fn, length) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { + throw new $TypeError('`length` must be a positive 32-bit integer'); + } + + var loose = arguments.length > 2 && !!arguments[2]; + + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ('length' in fn && gOPD) { + var desc = gOPD(fn, 'length'); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define(/** @type {Parameters[0]} */ (fn), 'length', length, true, true); + } else { + define(/** @type {Parameters[0]} */ (fn), 'length', length); + } + } + return fn; +}; + + +/***/ }), + +/***/ 392: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2802: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +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 = __webpack_require__(7816) +exports.sha1 = __webpack_require__(3737) +exports.sha224 = __webpack_require__(6710) +exports.sha256 = __webpack_require__(4107) +exports.sha384 = __webpack_require__(2827) +exports.sha512 = __webpack_require__(2890) + + +/***/ }), + +/***/ 7816: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 3737: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 6710: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * 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 = __webpack_require__(6698) +var Sha256 = __webpack_require__(4107) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 4107: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * 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 = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2827: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698) +var SHA512 = __webpack_require__(2890) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 2890: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var inherits = __webpack_require__(6698) +var Hash = __webpack_require__(392) +var Buffer = (__webpack_require__(2861).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 + + +/***/ }), + +/***/ 4803: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var inspect = __webpack_require__(8859); + +var $TypeError = __webpack_require__(9675); + +/* +* This function traverses the list returning the node corresponding to the given key. +* +* That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. +* By doing so, all the recently used nodes can be accessed relatively quickly. +*/ +/** @type {import('./list.d.ts').listGetNode} */ +// eslint-disable-next-line consistent-return +var listGetNode = function (list, key, isDelete) { + /** @type {typeof list | NonNullable<(typeof list)['next']>} */ + var prev = list; + /** @type {(typeof list)['next']} */ + var curr; + // eslint-disable-next-line eqeqeq + for (; (curr = prev.next) != null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + if (!isDelete) { + // eslint-disable-next-line no-extra-parens + curr.next = /** @type {NonNullable} */ (list.next); + list.next = curr; // eslint-disable-line no-param-reassign + } + return curr; + } + } +}; + +/** @type {import('./list.d.ts').listGet} */ +var listGet = function (objects, key) { + if (!objects) { + return void undefined; + } + var node = listGetNode(objects, key); + return node && node.value; +}; +/** @type {import('./list.d.ts').listSet} */ +var listSet = function (objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + // Prepend the new node to the beginning of the list + objects.next = /** @type {import('./list.d.ts').ListNode} */ ({ // eslint-disable-line no-param-reassign, no-extra-parens + key: key, + next: objects.next, + value: value + }); + } +}; +/** @type {import('./list.d.ts').listHas} */ +var listHas = function (objects, key) { + if (!objects) { + return false; + } + return !!listGetNode(objects, key); +}; +/** @type {import('./list.d.ts').listDelete} */ +// eslint-disable-next-line consistent-return +var listDelete = function (objects, key) { + if (objects) { + return listGetNode(objects, key, true); + } +}; + +/** @type {import('.')} */ +module.exports = function getSideChannelList() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {import('./list.d.ts').RootNode | undefined} */ var $o; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + var root = $o && $o.next; + var deletedNode = listDelete($o, key); + if (deletedNode && root && root === deletedNode) { + $o = void undefined; + } + return !!deletedNode; + }, + get: function (key) { + return listGet($o, key); + }, + has: function (key) { + return listHas($o, key); + }, + set: function (key, value) { + if (!$o) { + // Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head + $o = { + next: void undefined + }; + } + // eslint-disable-next-line no-extra-parens + listSet(/** @type {NonNullable} */ ($o), key, value); + } + }; + // @ts-expect-error TODO: figure out why this is erroring + return channel; +}; + + +/***/ }), + +/***/ 507: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); +var callBound = __webpack_require__(6556); +var inspect = __webpack_require__(8859); + +var $TypeError = __webpack_require__(9675); +var $Map = GetIntrinsic('%Map%', true); + +/** @type {(thisArg: Map, key: K) => V} */ +var $mapGet = callBound('Map.prototype.get', true); +/** @type {(thisArg: Map, key: K, value: V) => void} */ +var $mapSet = callBound('Map.prototype.set', true); +/** @type {(thisArg: Map, key: K) => boolean} */ +var $mapHas = callBound('Map.prototype.has', true); +/** @type {(thisArg: Map, key: K) => boolean} */ +var $mapDelete = callBound('Map.prototype.delete', true); +/** @type {(thisArg: Map) => number} */ +var $mapSize = callBound('Map.prototype.size', true); + +/** @type {import('.')} */ +module.exports = !!$Map && /** @type {Exclude} */ function getSideChannelMap() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {Map | undefined} */ var $m; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + if ($m) { + var result = $mapDelete($m, key); + if ($mapSize($m) === 0) { + $m = void undefined; + } + return result; + } + return false; + }, + get: function (key) { // eslint-disable-line consistent-return + if ($m) { + return $mapGet($m, key); + } + }, + has: function (key) { + if ($m) { + return $mapHas($m, key); + } + return false; + }, + set: function (key, value) { + if (!$m) { + // @ts-expect-error TS can't handle narrowing a variable inside a closure + $m = new $Map(); + } + $mapSet($m, key, value); + } + }; + + // @ts-expect-error TODO: figure out why TS is erroring here + return channel; +}; + + +/***/ }), + +/***/ 2271: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(453); +var callBound = __webpack_require__(6556); +var inspect = __webpack_require__(8859); +var getSideChannelMap = __webpack_require__(507); + +var $TypeError = __webpack_require__(9675); +var $WeakMap = GetIntrinsic('%WeakMap%', true); + +/** @type {(thisArg: WeakMap, key: K) => V} */ +var $weakMapGet = callBound('WeakMap.prototype.get', true); +/** @type {(thisArg: WeakMap, key: K, value: V) => void} */ +var $weakMapSet = callBound('WeakMap.prototype.set', true); +/** @type {(thisArg: WeakMap, key: K) => boolean} */ +var $weakMapHas = callBound('WeakMap.prototype.has', true); +/** @type {(thisArg: WeakMap, key: K) => boolean} */ +var $weakMapDelete = callBound('WeakMap.prototype.delete', true); + +/** @type {import('.')} */ +module.exports = $WeakMap + ? /** @type {Exclude} */ function getSideChannelWeakMap() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {WeakMap | undefined} */ var $wm; + /** @type {Channel | undefined} */ var $m; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapDelete($wm, key); + } + } else if (getSideChannelMap) { + if ($m) { + return $m['delete'](key); + } + } + return false; + }, + get: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } + return $m && $m.get(key); + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } + return !!$m && $m.has(key); + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if (getSideChannelMap) { + if (!$m) { + $m = getSideChannelMap(); + } + // eslint-disable-next-line no-extra-parens + /** @type {NonNullable} */ ($m).set(key, value); + } + } + }; + + // @ts-expect-error TODO: figure out why this is erroring + return channel; + } + : getSideChannelMap; + + +/***/ }), + +/***/ 920: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var $TypeError = __webpack_require__(9675); +var inspect = __webpack_require__(8859); +var getSideChannelList = __webpack_require__(4803); +var getSideChannelMap = __webpack_require__(507); +var getSideChannelWeakMap = __webpack_require__(2271); + +var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList; + +/** @type {import('.')} */ +module.exports = function getSideChannel() { + /** @typedef {ReturnType} Channel */ + + /** @type {Channel | undefined} */ var $channelData; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + return !!$channelData && $channelData['delete'](key); + }, + get: function (key) { + return $channelData && $channelData.get(key); + }, + has: function (key) { + return !!$channelData && $channelData.has(key); + }, + set: function (key, value) { + if (!$channelData) { + $channelData = makeChannel(); + } + + $channelData.set(key, value); + } + }; + // @ts-expect-error TODO: figure out why this is erroring + return channel; +}; + + +/***/ }), + +/***/ 1568: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +var ClientRequest = __webpack_require__(5537) +var response = __webpack_require__(6917) +var extend = __webpack_require__(7510) +var statusCodes = __webpack_require__(6866) +var url = __webpack_require__(8835) + +var http = exports + +http.request = function (opts, cb) { + if (typeof opts === 'string') + opts = url.parse(opts) + else + opts = extend(opts) + + // Normally, the page is loaded from http or https, so not specifying a protocol + // will result in a (valid) protocol-relative url. However, this won't work if + // the protocol is something else, like 'file:' + var defaultProtocol = __webpack_require__.g.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' + + var protocol = opts.protocol || defaultProtocol + var host = opts.hostname || opts.host + var port = opts.port + var path = opts.path || '/' + + // Necessary for IPv6 addresses + if (host && host.indexOf(':') !== -1) + host = '[' + host + ']' + + // This may be a relative url. The browser should always be able to interpret it correctly. + opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path + opts.method = (opts.method || 'GET').toUpperCase() + opts.headers = opts.headers || {} + + // Also valid opts.auth, opts.mode + + var req = new ClientRequest(opts) + if (cb) + req.on('response', cb) + return req +} + +http.get = function get (opts, cb) { + var req = http.request(opts, cb) + req.end() + return req +} + +http.ClientRequest = ClientRequest +http.IncomingMessage = response.IncomingMessage + +http.Agent = function () {} +http.Agent.defaultMaxSockets = 4 + +http.globalAgent = new http.Agent() + +http.STATUS_CODES = statusCodes + +http.METHODS = [ + 'CHECKOUT', + 'CONNECT', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LOCK', + 'M-SEARCH', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MOVE', + 'NOTIFY', + 'OPTIONS', + 'PATCH', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PURGE', + 'PUT', + 'REPORT', + 'SEARCH', + 'SUBSCRIBE', + 'TRACE', + 'UNLOCK', + 'UNSUBSCRIBE' +] + +/***/ }), + +/***/ 6688: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +exports.fetch = isFunction(__webpack_require__.g.fetch) && isFunction(__webpack_require__.g.ReadableStream) + +exports.writableStream = isFunction(__webpack_require__.g.WritableStream) + +exports.abortController = isFunction(__webpack_require__.g.AbortController) + +// The xhr request to example.com may violate some restrictive CSP configurations, +// so if we're running in a browser that supports `fetch`, avoid calling getXHR() +// and assume support for certain features below. +var xhr +function getXHR () { + // Cache the xhr value + if (xhr !== undefined) return xhr + + if (__webpack_require__.g.XMLHttpRequest) { + xhr = new __webpack_require__.g.XMLHttpRequest() + // If XDomainRequest is available (ie only, where xhr might not work + // cross domain), use the page location. Otherwise use example.com + // Note: this doesn't actually make an http request. + try { + xhr.open('GET', __webpack_require__.g.XDomainRequest ? '/' : 'https://example.com') + } catch(e) { + xhr = null + } + } else { + // Service workers don't have XHR + xhr = null + } + return xhr +} + +function checkTypeSupport (type) { + var xhr = getXHR() + if (!xhr) return false + try { + xhr.responseType = type + return xhr.responseType === type + } catch (e) {} + return false +} + +// If fetch is supported, then arraybuffer will be supported too. Skip calling +// checkTypeSupport(), since that calls getXHR(). +exports.arraybuffer = exports.fetch || checkTypeSupport('arraybuffer') + +// These next two tests unavoidably show warnings in Chrome. Since fetch will always +// be used if it's available, just return false for these to avoid the warnings. +exports.msstream = !exports.fetch && checkTypeSupport('ms-stream') +exports.mozchunkedarraybuffer = !exports.fetch && checkTypeSupport('moz-chunked-arraybuffer') + +// If fetch is supported, then overrideMimeType will be supported too. Skip calling +// getXHR(). +exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false) + +function isFunction (value) { + return typeof value === 'function' +} + +xhr = null // Help gc + + +/***/ }), + +/***/ 5537: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +var capability = __webpack_require__(6688) +var inherits = __webpack_require__(6698) +var response = __webpack_require__(6917) +var stream = __webpack_require__(8399) + +var IncomingMessage = response.IncomingMessage +var rStates = response.readyStates + +function decideMode (preferBinary, useFetch) { + if (capability.fetch && useFetch) { + return 'fetch' + } else if (capability.mozchunkedarraybuffer) { + return 'moz-chunked-arraybuffer' + } else if (capability.msstream) { + return 'ms-stream' + } else if (capability.arraybuffer && preferBinary) { + return 'arraybuffer' + } else { + return 'text' + } +} + +var ClientRequest = module.exports = function (opts) { + var self = this + stream.Writable.call(self) + + self._opts = opts + self._body = [] + self._headers = {} + if (opts.auth) + self.setHeader('Authorization', 'Basic ' + Buffer.from(opts.auth).toString('base64')) + Object.keys(opts.headers).forEach(function (name) { + self.setHeader(name, opts.headers[name]) + }) + + var preferBinary + var useFetch = true + if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) { + // If the use of XHR should be preferred. Not typically needed. + useFetch = false + preferBinary = true + } else if (opts.mode === 'prefer-streaming') { + // If streaming is a high priority but binary compatibility and + // the accuracy of the 'content-type' header aren't + preferBinary = false + } else if (opts.mode === 'allow-wrong-content-type') { + // If streaming is more important than preserving the 'content-type' header + preferBinary = !capability.overrideMimeType + } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { + // Use binary if text streaming may corrupt data or the content-type header, or for speed + preferBinary = true + } else { + throw new Error('Invalid value for opts.mode') + } + self._mode = decideMode(preferBinary, useFetch) + self._fetchTimer = null + self._socketTimeout = null + self._socketTimer = null + + self.on('finish', function () { + self._onFinish() + }) +} + +inherits(ClientRequest, stream.Writable) + +ClientRequest.prototype.setHeader = function (name, value) { + var self = this + var lowerName = name.toLowerCase() + // This check is not necessary, but it prevents warnings from browsers about setting unsafe + // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but + // http-browserify did it, so I will too. + if (unsafeHeaders.indexOf(lowerName) !== -1) + return + + self._headers[lowerName] = { + name: name, + value: value + } +} + +ClientRequest.prototype.getHeader = function (name) { + var header = this._headers[name.toLowerCase()] + if (header) + return header.value + return null +} + +ClientRequest.prototype.removeHeader = function (name) { + var self = this + delete self._headers[name.toLowerCase()] +} + +ClientRequest.prototype._onFinish = function () { + var self = this + + if (self._destroyed) + return + var opts = self._opts + + if ('timeout' in opts && opts.timeout !== 0) { + self.setTimeout(opts.timeout) + } + + var headersObj = self._headers + var body = null + if (opts.method !== 'GET' && opts.method !== 'HEAD') { + body = new Blob(self._body, { + type: (headersObj['content-type'] || {}).value || '' + }); + } + + // create flattened list of headers + var headersList = [] + Object.keys(headersObj).forEach(function (keyName) { + var name = headersObj[keyName].name + var value = headersObj[keyName].value + if (Array.isArray(value)) { + value.forEach(function (v) { + headersList.push([name, v]) + }) + } else { + headersList.push([name, value]) + } + }) + + if (self._mode === 'fetch') { + var signal = null + if (capability.abortController) { + var controller = new AbortController() + signal = controller.signal + self._fetchAbortController = controller + + if ('requestTimeout' in opts && opts.requestTimeout !== 0) { + self._fetchTimer = __webpack_require__.g.setTimeout(function () { + self.emit('requestTimeout') + if (self._fetchAbortController) + self._fetchAbortController.abort() + }, opts.requestTimeout) + } + } + + __webpack_require__.g.fetch(self._opts.url, { + method: self._opts.method, + headers: headersList, + body: body || undefined, + mode: 'cors', + credentials: opts.withCredentials ? 'include' : 'same-origin', + signal: signal + }).then(function (response) { + self._fetchResponse = response + self._resetTimers(false) + self._connect() + }, function (reason) { + self._resetTimers(true) + if (!self._destroyed) + self.emit('error', reason) + }) + } else { + var xhr = self._xhr = new __webpack_require__.g.XMLHttpRequest() + try { + xhr.open(self._opts.method, self._opts.url, true) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + + // Can't set responseType on really old browsers + if ('responseType' in xhr) + xhr.responseType = self._mode + + if ('withCredentials' in xhr) + xhr.withCredentials = !!opts.withCredentials + + if (self._mode === 'text' && 'overrideMimeType' in xhr) + xhr.overrideMimeType('text/plain; charset=x-user-defined') + + if ('requestTimeout' in opts) { + xhr.timeout = opts.requestTimeout + xhr.ontimeout = function () { + self.emit('requestTimeout') + } + } + + headersList.forEach(function (header) { + xhr.setRequestHeader(header[0], header[1]) + }) + + self._response = null + xhr.onreadystatechange = function () { + switch (xhr.readyState) { + case rStates.LOADING: + case rStates.DONE: + self._onXHRProgress() + break + } + } + // Necessary for streaming in Firefox, since xhr.response is ONLY defined + // in onprogress, not in onreadystatechange with xhr.readyState = 3 + if (self._mode === 'moz-chunked-arraybuffer') { + xhr.onprogress = function () { + self._onXHRProgress() + } + } + + xhr.onerror = function () { + if (self._destroyed) + return + self._resetTimers(true) + self.emit('error', new Error('XHR error')) + } + + try { + xhr.send(body) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + } +} + +/** + * Checks if xhr.status is readable and non-zero, indicating no error. + * Even though the spec says it should be available in readyState 3, + * accessing it throws an exception in IE8 + */ +function statusValid (xhr) { + try { + var status = xhr.status + return (status !== null && status !== 0) + } catch (e) { + return false + } +} + +ClientRequest.prototype._onXHRProgress = function () { + var self = this + + self._resetTimers(false) + + if (!statusValid(self._xhr) || self._destroyed) + return + + if (!self._response) + self._connect() + + self._response._onXHRProgress(self._resetTimers.bind(self)) +} + +ClientRequest.prototype._connect = function () { + var self = this + + if (self._destroyed) + return + + self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._resetTimers.bind(self)) + self._response.on('error', function(err) { + self.emit('error', err) + }) + + self.emit('response', self._response) +} + +ClientRequest.prototype._write = function (chunk, encoding, cb) { + var self = this + + self._body.push(chunk) + cb() +} + +ClientRequest.prototype._resetTimers = function (done) { + var self = this + + __webpack_require__.g.clearTimeout(self._socketTimer) + self._socketTimer = null + + if (done) { + __webpack_require__.g.clearTimeout(self._fetchTimer) + self._fetchTimer = null + } else if (self._socketTimeout) { + self._socketTimer = __webpack_require__.g.setTimeout(function () { + self.emit('timeout') + }, self._socketTimeout) + } +} + +ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function (err) { + var self = this + self._destroyed = true + self._resetTimers(true) + if (self._response) + self._response._destroyed = true + if (self._xhr) + self._xhr.abort() + else if (self._fetchAbortController) + self._fetchAbortController.abort() + + if (err) + self.emit('error', err) +} + +ClientRequest.prototype.end = function (data, encoding, cb) { + var self = this + if (typeof data === 'function') { + cb = data + data = undefined + } + + stream.Writable.prototype.end.call(self, data, encoding, cb) +} + +ClientRequest.prototype.setTimeout = function (timeout, cb) { + var self = this + + if (cb) + self.once('timeout', cb) + + self._socketTimeout = timeout + self._resetTimers(false) +} + +ClientRequest.prototype.flushHeaders = function () {} +ClientRequest.prototype.setNoDelay = function () {} +ClientRequest.prototype.setSocketKeepAlive = function () {} + +// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method +var unsafeHeaders = [ + 'accept-charset', + 'accept-encoding', + 'access-control-request-headers', + 'access-control-request-method', + 'connection', + 'content-length', + 'cookie', + 'cookie2', + 'date', + 'dnt', + 'expect', + 'host', + 'keep-alive', + 'origin', + 'referer', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'via' +] + + +/***/ }), + +/***/ 6917: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* provided dependency */ var Buffer = __webpack_require__(8287)["Buffer"]; +var capability = __webpack_require__(6688) +var inherits = __webpack_require__(6698) +var stream = __webpack_require__(8399) + +var rStates = exports.readyStates = { + UNSENT: 0, + OPENED: 1, + HEADERS_RECEIVED: 2, + LOADING: 3, + DONE: 4 +} + +var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, resetTimers) { + var self = this + stream.Readable.call(self) + + self._mode = mode + self.headers = {} + self.rawHeaders = [] + self.trailers = {} + self.rawTrailers = [] + + // Fake the 'close' event, but only once 'end' fires + self.on('end', function () { + // The nextTick is necessary to prevent the 'request' module from causing an infinite loop + process.nextTick(function () { + self.emit('close') + }) + }) + + if (mode === 'fetch') { + self._fetchResponse = response + + self.url = response.url + self.statusCode = response.status + self.statusMessage = response.statusText + + response.headers.forEach(function (header, key){ + self.headers[key.toLowerCase()] = header + self.rawHeaders.push(key, header) + }) + + if (capability.writableStream) { + var writable = new WritableStream({ + write: function (chunk) { + resetTimers(false) + return new Promise(function (resolve, reject) { + if (self._destroyed) { + reject() + } else if(self.push(Buffer.from(chunk))) { + resolve() + } else { + self._resumeFetch = resolve + } + }) + }, + close: function () { + resetTimers(true) + if (!self._destroyed) + self.push(null) + }, + abort: function (err) { + resetTimers(true) + if (!self._destroyed) + self.emit('error', err) + } + }) + + try { + response.body.pipeTo(writable).catch(function (err) { + resetTimers(true) + if (!self._destroyed) + self.emit('error', err) + }) + return + } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this + } + // fallback for when writableStream or pipeTo aren't available + var reader = response.body.getReader() + function read () { + reader.read().then(function (result) { + if (self._destroyed) + return + resetTimers(result.done) + if (result.done) { + self.push(null) + return + } + self.push(Buffer.from(result.value)) + read() + }).catch(function (err) { + resetTimers(true) + if (!self._destroyed) + self.emit('error', err) + }) + } + read() + } else { + self._xhr = xhr + self._pos = 0 + + self.url = xhr.responseURL + self.statusCode = xhr.status + self.statusMessage = xhr.statusText + var headers = xhr.getAllResponseHeaders().split(/\r?\n/) + headers.forEach(function (header) { + var matches = header.match(/^([^:]+):\s*(.*)/) + if (matches) { + var key = matches[1].toLowerCase() + if (key === 'set-cookie') { + if (self.headers[key] === undefined) { + self.headers[key] = [] + } + self.headers[key].push(matches[2]) + } else if (self.headers[key] !== undefined) { + self.headers[key] += ', ' + matches[2] + } else { + self.headers[key] = matches[2] + } + self.rawHeaders.push(matches[1], matches[2]) + } + }) + + self._charset = 'x-user-defined' + if (!capability.overrideMimeType) { + var mimeType = self.rawHeaders['mime-type'] + if (mimeType) { + var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) + if (charsetMatch) { + self._charset = charsetMatch[1].toLowerCase() + } + } + if (!self._charset) + self._charset = 'utf-8' // best guess + } + } +} + +inherits(IncomingMessage, stream.Readable) + +IncomingMessage.prototype._read = function () { + var self = this + + var resolve = self._resumeFetch + if (resolve) { + self._resumeFetch = null + resolve() + } +} + +IncomingMessage.prototype._onXHRProgress = function (resetTimers) { + var self = this + + var xhr = self._xhr + + var response = null + switch (self._mode) { + case 'text': + response = xhr.responseText + if (response.length > self._pos) { + var newData = response.substr(self._pos) + if (self._charset === 'x-user-defined') { + var buffer = Buffer.alloc(newData.length) + for (var i = 0; i < newData.length; i++) + buffer[i] = newData.charCodeAt(i) & 0xff + + self.push(buffer) + } else { + self.push(newData, self._charset) + } + self._pos = response.length + } + break + case 'arraybuffer': + if (xhr.readyState !== rStates.DONE || !xhr.response) + break + response = xhr.response + self.push(Buffer.from(new Uint8Array(response))) + break + case 'moz-chunked-arraybuffer': // take whole + response = xhr.response + if (xhr.readyState !== rStates.LOADING || !response) + break + self.push(Buffer.from(new Uint8Array(response))) + break + case 'ms-stream': + response = xhr.response + if (xhr.readyState !== rStates.LOADING) + break + var reader = new __webpack_require__.g.MSStreamReader() + reader.onprogress = function () { + if (reader.result.byteLength > self._pos) { + self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos)))) + self._pos = reader.result.byteLength + } + } + reader.onload = function () { + resetTimers(true) + self.push(null) + } + // reader.onerror = ??? // TODO: this + reader.readAsArrayBuffer(response) + break + } + + // The ms-stream case handles end separately in reader.onload() + if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { + resetTimers(true) + self.push(null) + } +} + + +/***/ }), + +/***/ 3141: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// 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. + + + +/**/ + +var Buffer = (__webpack_require__(2861).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.I = 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) : ''; +} + +/***/ }), + +/***/ 1293: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var parser = __webpack_require__(5546); +var compiler = __webpack_require__(2708); + +module.exports = { + parse: function(input) { + var nodes = parser.parse(input.toString()); + return compiler.compile(nodes); + } +}; + + +/***/ }), + +/***/ 2708: +/***/ ((module) => { + +"use strict"; + +function compile(nodes) { + var assignedPaths = []; + var valueAssignments = []; + var currentPath = ""; + var data = Object.create(null); + var context = data; + var arrayMode = false; + + return reduce(nodes); + + function reduce(nodes) { + var node; + for (var i = 0; i < nodes.length; i++) { + node = nodes[i]; + switch (node.type) { + case "Assign": + assign(node); + break; + case "ObjectPath": + setPath(node); + break; + case "ArrayPath": + addTableArray(node); + break; + } + } + + return data; + } + + function genError(err, line, col) { + var ex = new Error(err); + ex.line = line; + ex.column = col; + throw ex; + } + + function assign(node) { + var key = node.key; + var value = node.value; + var line = node.line; + var column = node.column; + + var fullPath; + if (currentPath) { + fullPath = currentPath + "." + key; + } else { + fullPath = key; + } + if (typeof context[key] !== "undefined") { + genError("Cannot redefine existing key '" + fullPath + "'.", line, column); + } + + context[key] = reduceValueNode(value); + + if (!pathAssigned(fullPath)) { + assignedPaths.push(fullPath); + valueAssignments.push(fullPath); + } + } + + + function pathAssigned(path) { + return assignedPaths.indexOf(path) !== -1; + } + + function reduceValueNode(node) { + if (node.type === "Array") { + return reduceArrayWithTypeChecking(node.value); + } else if (node.type === "InlineTable") { + return reduceInlineTableNode(node.value); + } else { + return node.value; + } + } + + function reduceInlineTableNode(values) { + var obj = Object.create(null); + for (var i = 0; i < values.length; i++) { + var val = values[i]; + if (val.value.type === "InlineTable") { + obj[val.key] = reduceInlineTableNode(val.value.value); + } else if (val.type === "InlineTableValue") { + obj[val.key] = reduceValueNode(val.value); + } + } + + return obj; + } + + function setPath(node) { + var path = node.value; + var quotedPath = path.map(quoteDottedString).join("."); + var line = node.line; + var column = node.column; + + if (pathAssigned(quotedPath)) { + genError("Cannot redefine existing key '" + path + "'.", line, column); + } + assignedPaths.push(quotedPath); + context = deepRef(data, path, Object.create(null), line, column); + currentPath = path; + } + + function addTableArray(node) { + var path = node.value; + var quotedPath = path.map(quoteDottedString).join("."); + var line = node.line; + var column = node.column; + + if (!pathAssigned(quotedPath)) { + assignedPaths.push(quotedPath); + } + assignedPaths = assignedPaths.filter(function(p) { + return p.indexOf(quotedPath) !== 0; + }); + assignedPaths.push(quotedPath); + context = deepRef(data, path, [], line, column); + currentPath = quotedPath; + + if (context instanceof Array) { + var newObj = Object.create(null); + context.push(newObj); + context = newObj; + } else { + genError("Cannot redefine existing key '" + path + "'.", line, column); + } + } + + // Given a path 'a.b.c', create (as necessary) `start.a`, + // `start.a.b`, and `start.a.b.c`, assigning `value` to `start.a.b.c`. + // If `a` or `b` are arrays and have items in them, the last item in the + // array is used as the context for the next sub-path. + function deepRef(start, keys, value, line, column) { + var traversed = []; + var traversedPath = ""; + var path = keys.join("."); + var ctx = start; + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + traversed.push(key); + traversedPath = traversed.join("."); + if (typeof ctx[key] === "undefined") { + if (i === keys.length - 1) { + ctx[key] = value; + } else { + ctx[key] = Object.create(null); + } + } else if (i !== keys.length - 1 && valueAssignments.indexOf(traversedPath) > -1) { + // already a non-object value at key, can't be used as part of a new path + genError("Cannot redefine existing key '" + traversedPath + "'.", line, column); + } + + ctx = ctx[key]; + if (ctx instanceof Array && ctx.length && i < keys.length - 1) { + ctx = ctx[ctx.length - 1]; + } + } + + return ctx; + } + + function reduceArrayWithTypeChecking(array) { + // Ensure that all items in the array are of the same type + var firstType = null; + for (var i = 0; i < array.length; i++) { + var node = array[i]; + if (firstType === null) { + firstType = node.type; + } else { + if (node.type !== firstType) { + genError("Cannot add value of type " + node.type + " to array of type " + + firstType + ".", node.line, node.column); + } + } + } + + // Recursively reduce array of nodes into array of the nodes' values + return array.map(reduceValueNode); + } + + function quoteDottedString(str) { + if (str.indexOf(".") > -1) { + return "\"" + str + "\""; + } else { + return str; + } + } +} + +module.exports = { + compile: compile +}; + + +/***/ }), + +/***/ 5546: +/***/ ((module) => { + +module.exports = (function() { + /* + * Generated by PEG.js 0.8.0. + * + * http://pegjs.majda.cz/ + */ + + function peg$subclass(child, parent) { + function ctor() { this.constructor = child; } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + + function SyntaxError(message, expected, found, offset, line, column) { + this.message = message; + this.expected = expected; + this.found = found; + this.offset = offset; + this.line = line; + this.column = column; + + this.name = "SyntaxError"; + } + + peg$subclass(SyntaxError, Error); + + function parse(input) { + var options = arguments.length > 1 ? arguments[1] : {}, + + peg$FAILED = {}, + + peg$startRuleFunctions = { start: peg$parsestart }, + peg$startRuleFunction = peg$parsestart, + + peg$c0 = [], + peg$c1 = function() { return nodes }, + peg$c2 = peg$FAILED, + peg$c3 = "#", + peg$c4 = { type: "literal", value: "#", description: "\"#\"" }, + peg$c5 = void 0, + peg$c6 = { type: "any", description: "any character" }, + peg$c7 = "[", + peg$c8 = { type: "literal", value: "[", description: "\"[\"" }, + peg$c9 = "]", + peg$c10 = { type: "literal", value: "]", description: "\"]\"" }, + peg$c11 = function(name) { addNode(node('ObjectPath', name, line, column)) }, + peg$c12 = function(name) { addNode(node('ArrayPath', name, line, column)) }, + peg$c13 = function(parts, name) { return parts.concat(name) }, + peg$c14 = function(name) { return [name] }, + peg$c15 = function(name) { return name }, + peg$c16 = ".", + peg$c17 = { type: "literal", value: ".", description: "\".\"" }, + peg$c18 = "=", + peg$c19 = { type: "literal", value: "=", description: "\"=\"" }, + peg$c20 = function(key, value) { addNode(node('Assign', value, line, column, key)) }, + peg$c21 = function(chars) { return chars.join('') }, + peg$c22 = function(node) { return node.value }, + peg$c23 = "\"\"\"", + peg$c24 = { type: "literal", value: "\"\"\"", description: "\"\\\"\\\"\\\"\"" }, + peg$c25 = null, + peg$c26 = function(chars) { return node('String', chars.join(''), line, column) }, + peg$c27 = "\"", + peg$c28 = { type: "literal", value: "\"", description: "\"\\\"\"" }, + peg$c29 = "'''", + peg$c30 = { type: "literal", value: "'''", description: "\"'''\"" }, + peg$c31 = "'", + peg$c32 = { type: "literal", value: "'", description: "\"'\"" }, + peg$c33 = function(char) { return char }, + peg$c34 = function(char) { return char}, + peg$c35 = "\\", + peg$c36 = { type: "literal", value: "\\", description: "\"\\\\\"" }, + peg$c37 = function() { return '' }, + peg$c38 = "e", + peg$c39 = { type: "literal", value: "e", description: "\"e\"" }, + peg$c40 = "E", + peg$c41 = { type: "literal", value: "E", description: "\"E\"" }, + peg$c42 = function(left, right) { return node('Float', parseFloat(left + 'e' + right), line, column) }, + peg$c43 = function(text) { return node('Float', parseFloat(text), line, column) }, + peg$c44 = "+", + peg$c45 = { type: "literal", value: "+", description: "\"+\"" }, + peg$c46 = function(digits) { return digits.join('') }, + peg$c47 = "-", + peg$c48 = { type: "literal", value: "-", description: "\"-\"" }, + peg$c49 = function(digits) { return '-' + digits.join('') }, + peg$c50 = function(text) { return node('Integer', parseInt(text, 10), line, column) }, + peg$c51 = "true", + peg$c52 = { type: "literal", value: "true", description: "\"true\"" }, + peg$c53 = function() { return node('Boolean', true, line, column) }, + peg$c54 = "false", + peg$c55 = { type: "literal", value: "false", description: "\"false\"" }, + peg$c56 = function() { return node('Boolean', false, line, column) }, + peg$c57 = function() { return node('Array', [], line, column) }, + peg$c58 = function(value) { return node('Array', value ? [value] : [], line, column) }, + peg$c59 = function(values) { return node('Array', values, line, column) }, + peg$c60 = function(values, value) { return node('Array', values.concat(value), line, column) }, + peg$c61 = function(value) { return value }, + peg$c62 = ",", + peg$c63 = { type: "literal", value: ",", description: "\",\"" }, + peg$c64 = "{", + peg$c65 = { type: "literal", value: "{", description: "\"{\"" }, + peg$c66 = "}", + peg$c67 = { type: "literal", value: "}", description: "\"}\"" }, + peg$c68 = function(values) { return node('InlineTable', values, line, column) }, + peg$c69 = function(key, value) { return node('InlineTableValue', value, line, column, key) }, + peg$c70 = function(digits) { return "." + digits }, + peg$c71 = function(date) { return date.join('') }, + peg$c72 = ":", + peg$c73 = { type: "literal", value: ":", description: "\":\"" }, + peg$c74 = function(time) { return time.join('') }, + peg$c75 = "T", + peg$c76 = { type: "literal", value: "T", description: "\"T\"" }, + peg$c77 = "Z", + peg$c78 = { type: "literal", value: "Z", description: "\"Z\"" }, + peg$c79 = function(date, time) { return node('Date', new Date(date + "T" + time + "Z"), line, column) }, + peg$c80 = function(date, time) { return node('Date', new Date(date + "T" + time), line, column) }, + peg$c81 = /^[ \t]/, + peg$c82 = { type: "class", value: "[ \\t]", description: "[ \\t]" }, + peg$c83 = "\n", + peg$c84 = { type: "literal", value: "\n", description: "\"\\n\"" }, + peg$c85 = "\r", + peg$c86 = { type: "literal", value: "\r", description: "\"\\r\"" }, + peg$c87 = /^[0-9a-f]/i, + peg$c88 = { type: "class", value: "[0-9a-f]i", description: "[0-9a-f]i" }, + peg$c89 = /^[0-9]/, + peg$c90 = { type: "class", value: "[0-9]", description: "[0-9]" }, + peg$c91 = "_", + peg$c92 = { type: "literal", value: "_", description: "\"_\"" }, + peg$c93 = function() { return "" }, + peg$c94 = /^[A-Za-z0-9_\-]/, + peg$c95 = { type: "class", value: "[A-Za-z0-9_\\-]", description: "[A-Za-z0-9_\\-]" }, + peg$c96 = function(d) { return d.join('') }, + peg$c97 = "\\\"", + peg$c98 = { type: "literal", value: "\\\"", description: "\"\\\\\\\"\"" }, + peg$c99 = function() { return '"' }, + peg$c100 = "\\\\", + peg$c101 = { type: "literal", value: "\\\\", description: "\"\\\\\\\\\"" }, + peg$c102 = function() { return '\\' }, + peg$c103 = "\\b", + peg$c104 = { type: "literal", value: "\\b", description: "\"\\\\b\"" }, + peg$c105 = function() { return '\b' }, + peg$c106 = "\\t", + peg$c107 = { type: "literal", value: "\\t", description: "\"\\\\t\"" }, + peg$c108 = function() { return '\t' }, + peg$c109 = "\\n", + peg$c110 = { type: "literal", value: "\\n", description: "\"\\\\n\"" }, + peg$c111 = function() { return '\n' }, + peg$c112 = "\\f", + peg$c113 = { type: "literal", value: "\\f", description: "\"\\\\f\"" }, + peg$c114 = function() { return '\f' }, + peg$c115 = "\\r", + peg$c116 = { type: "literal", value: "\\r", description: "\"\\\\r\"" }, + peg$c117 = function() { return '\r' }, + peg$c118 = "\\U", + peg$c119 = { type: "literal", value: "\\U", description: "\"\\\\U\"" }, + peg$c120 = function(digits) { return convertCodePoint(digits.join('')) }, + peg$c121 = "\\u", + peg$c122 = { type: "literal", value: "\\u", description: "\"\\\\u\"" }, + + peg$currPos = 0, + peg$reportedPos = 0, + peg$cachedPos = 0, + peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }, + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$silentFails = 0, + + peg$cache = {}, + peg$result; + + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + + function text() { + return input.substring(peg$reportedPos, peg$currPos); + } + + function offset() { + return peg$reportedPos; + } + + function line() { + return peg$computePosDetails(peg$reportedPos).line; + } + + function column() { + return peg$computePosDetails(peg$reportedPos).column; + } + + function expected(description) { + throw peg$buildException( + null, + [{ type: "other", description: description }], + peg$reportedPos + ); + } + + function error(message) { + throw peg$buildException(message, null, peg$reportedPos); + } + + function peg$computePosDetails(pos) { + function advance(details, startPos, endPos) { + var p, ch; + + for (p = startPos; p < endPos; p++) { + ch = input.charAt(p); + if (ch === "\n") { + if (!details.seenCR) { details.line++; } + details.column = 1; + details.seenCR = false; + } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { + details.line++; + details.column = 1; + details.seenCR = true; + } else { + details.column++; + details.seenCR = false; + } + } + } + + if (peg$cachedPos !== pos) { + if (peg$cachedPos > pos) { + peg$cachedPos = 0; + peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }; + } + advance(peg$cachedPosDetails, peg$cachedPos, pos); + peg$cachedPos = pos; + } + + return peg$cachedPosDetails; + } + + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { return; } + + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + + peg$maxFailExpected.push(expected); + } + + function peg$buildException(message, expected, pos) { + function cleanupExpected(expected) { + var i = 1; + + expected.sort(function(a, b) { + if (a.description < b.description) { + return -1; + } else if (a.description > b.description) { + return 1; + } else { + return 0; + } + }); + + while (i < expected.length) { + if (expected[i - 1] === expected[i]) { + expected.splice(i, 1); + } else { + i++; + } + } + } + + function buildMessage(expected, found) { + function stringEscape(s) { + function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } + + return s + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\x08/g, '\\b') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\f/g, '\\f') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); }) + .replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); }) + .replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); }); + } + + var expectedDescs = new Array(expected.length), + expectedDesc, foundDesc, i; + + for (i = 0; i < expected.length; i++) { + expectedDescs[i] = expected[i].description; + } + + expectedDesc = expected.length > 1 + ? expectedDescs.slice(0, -1).join(", ") + + " or " + + expectedDescs[expected.length - 1] + : expectedDescs[0]; + + foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input"; + + return "Expected " + expectedDesc + " but " + foundDesc + " found."; + } + + var posDetails = peg$computePosDetails(pos), + found = pos < input.length ? input.charAt(pos) : null; + + if (expected !== null) { + cleanupExpected(expected); + } + + return new SyntaxError( + message !== null ? message : buildMessage(expected, found), + expected, + found, + pos, + posDetails.line, + posDetails.column + ); + } + + function peg$parsestart() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 0, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseline(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseline(); + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c1(); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseline() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 1, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parseexpression(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parsecomment(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parsecomment(); + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseNL(); + if (s6 !== peg$FAILED) { + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseNL(); + } + } else { + s5 = peg$c2; + } + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseNL(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseNL(); + } + } else { + s2 = peg$c2; + } + if (s2 === peg$FAILED) { + s2 = peg$parseEOF(); + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$parseNL(); + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseexpression() { + var s0; + + var key = peg$currPos * 49 + 2, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsecomment(); + if (s0 === peg$FAILED) { + s0 = peg$parsepath(); + if (s0 === peg$FAILED) { + s0 = peg$parsetablearray(); + if (s0 === peg$FAILED) { + s0 = peg$parseassignment(); + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsecomment() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 3, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c3; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c4); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNL(); + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = peg$c5; + } else { + peg$currPos = s4; + s4 = peg$c2; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } else { + peg$currPos = s3; + s3 = peg$c2; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNL(); + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = peg$c5; + } else { + peg$currPos = s4; + s4 = peg$c2; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsepath() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 4, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetable_key(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s5 = peg$c9; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c11(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetablearray() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + var key = peg$currPos * 49 + 5, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s2 = peg$c7; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parsetable_key(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s6 = peg$c9; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s7 = peg$c9; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s7 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c12(s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetable_key() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 6, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsedot_ended_table_key_part(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsedot_ended_table_key_part(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + s2 = peg$parsetable_key_part(); + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c13(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsetable_key_part(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c14(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetable_key_part() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 7, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsequoted_key(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedot_ended_table_key_part() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 8, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsequoted_key(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseassignment() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 9, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsekey(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c18; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parsevalue(); + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c20(s1, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsequoted_key(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c18; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parsevalue(); + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c20(s1, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsekey() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 10, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseASCII_BASIC(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseASCII_BASIC(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c21(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsequoted_key() { + var s0, s1; + + var key = peg$currPos * 49 + 11, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsedouble_quoted_single_line_string(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c22(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsesingle_quoted_single_line_string(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c22(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsevalue() { + var s0; + + var key = peg$currPos * 49 + 12, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsestring(); + if (s0 === peg$FAILED) { + s0 = peg$parsedatetime(); + if (s0 === peg$FAILED) { + s0 = peg$parsefloat(); + if (s0 === peg$FAILED) { + s0 = peg$parseinteger(); + if (s0 === peg$FAILED) { + s0 = peg$parseboolean(); + if (s0 === peg$FAILED) { + s0 = peg$parsearray(); + if (s0 === peg$FAILED) { + s0 = peg$parseinline_table(); + } + } + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsestring() { + var s0; + + var key = peg$currPos * 49 + 13, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsedouble_quoted_multiline_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsedouble_quoted_single_line_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsesingle_quoted_multiline_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsesingle_quoted_single_line_string(); + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedouble_quoted_multiline_string() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 14, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c23) { + s1 = peg$c23; + peg$currPos += 3; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsemultiline_string_char(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsemultiline_string_char(); + } + if (s3 !== peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c23) { + s4 = peg$c23; + peg$currPos += 3; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedouble_quoted_single_line_string() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 15, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c27; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsestring_char(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsestring_char(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c27; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesingle_quoted_multiline_string() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 16, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c29) { + s1 = peg$c29; + peg$currPos += 3; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsemultiline_literal_char(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsemultiline_literal_char(); + } + if (s3 !== peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c29) { + s4 = peg$c29; + peg$currPos += 3; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesingle_quoted_single_line_string() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 17, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseliteral_char(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseliteral_char(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c31; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsestring_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 18, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseESCAPED(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 34) { + s2 = peg$c27; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseliteral_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 19, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c31; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_string_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 20, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseESCAPED(); + if (s0 === peg$FAILED) { + s0 = peg$parsemultiline_string_delim(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c23) { + s2 = peg$c23; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c34(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_string_delim() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 21, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c35; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c36); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseNLS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseNLS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c37(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_literal_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 22, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c29) { + s2 = peg$c29; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefloat() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 23, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsefloat_text(); + if (s1 === peg$FAILED) { + s1 = peg$parseinteger_text(); + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 101) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 69) { + s2 = peg$c40; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c41); } + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseinteger_text(); + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c42(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsefloat_text(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c43(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefloat_text() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 24, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c44; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + if (s1 === peg$FAILED) { + s1 = peg$c25; + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseDIGITS(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGITS(); + if (s5 !== peg$FAILED) { + s3 = [s3, s4, s5]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c46(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 45) { + s1 = peg$c47; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseDIGITS(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGITS(); + if (s5 !== peg$FAILED) { + s3 = [s3, s4, s5]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c49(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinteger() { + var s0, s1; + + var key = peg$currPos * 49 + 25, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseinteger_text(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c50(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinteger_text() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 26, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c44; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + if (s1 === peg$FAILED) { + s1 = peg$c25; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + peg$silentFails--; + if (s4 === peg$FAILED) { + s3 = peg$c5; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c46(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 45) { + s1 = peg$c47; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + peg$silentFails--; + if (s4 === peg$FAILED) { + s3 = peg$c5; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c49(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseboolean() { + var s0, s1; + + var key = peg$currPos * 49 + 27, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c51) { + s1 = peg$c51; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c52); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c53(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c54) { + s1 = peg$c54; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c55); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c56(); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 28, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_sep(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_sep(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c57(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsearray_value(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c58(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_value_list(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_value_list(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c59(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_value_list(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_value_list(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$parsearray_value(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s4 = peg$c9; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c60(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_value() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 29, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsearray_sep(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsearray_sep(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsevalue(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsearray_sep(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsearray_sep(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c61(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_value_list() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 30, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsearray_sep(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsearray_sep(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsevalue(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsearray_sep(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsearray_sep(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s4 = peg$c62; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c63); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parsearray_sep(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parsearray_sep(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c61(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_sep() { + var s0; + + var key = peg$currPos * 49 + 31, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseS(); + if (s0 === peg$FAILED) { + s0 = peg$parseNL(); + if (s0 === peg$FAILED) { + s0 = peg$parsecomment(); + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinline_table() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 32, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 123) { + s1 = peg$c64; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c65); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseinline_table_assignment(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseinline_table_assignment(); + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s5 = peg$c66; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c67); } + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c68(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinline_table_assignment() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 33, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s4 = peg$c18; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parsevalue(); + if (s6 !== peg$FAILED) { + s7 = []; + s8 = peg$parseS(); + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseS(); + } + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c62; + peg$currPos++; + } else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c63); } + } + if (s8 !== peg$FAILED) { + s9 = []; + s10 = peg$parseS(); + while (s10 !== peg$FAILED) { + s9.push(s10); + s10 = peg$parseS(); + } + if (s9 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c69(s2, s6); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s4 = peg$c18; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parsevalue(); + if (s6 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c69(s2, s6); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesecfragment() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 34, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c16; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDIGITS(); + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c70(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedate() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11; + + var key = peg$currPos * 49 + 35, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT_OR_UNDER(); + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s6 = peg$c47; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseDIGIT_OR_UNDER(); + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s9 = peg$c47; + peg$currPos++; + } else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s9 !== peg$FAILED) { + s10 = peg$parseDIGIT_OR_UNDER(); + if (s10 !== peg$FAILED) { + s11 = peg$parseDIGIT_OR_UNDER(); + if (s11 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c71(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetime() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 36, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c72; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT_OR_UNDER(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c72; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + s9 = peg$parseDIGIT_OR_UNDER(); + if (s9 !== peg$FAILED) { + s10 = peg$parsesecfragment(); + if (s10 === peg$FAILED) { + s10 = peg$c25; + } + if (s10 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c74(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetime_with_offset() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16; + + var key = peg$currPos * 49 + 37, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c72; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT_OR_UNDER(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c72; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + s9 = peg$parseDIGIT_OR_UNDER(); + if (s9 !== peg$FAILED) { + s10 = peg$parsesecfragment(); + if (s10 === peg$FAILED) { + s10 = peg$c25; + } + if (s10 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s11 = peg$c47; + peg$currPos++; + } else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s11 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s11 = peg$c44; + peg$currPos++; + } else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + } + if (s11 !== peg$FAILED) { + s12 = peg$parseDIGIT_OR_UNDER(); + if (s12 !== peg$FAILED) { + s13 = peg$parseDIGIT_OR_UNDER(); + if (s13 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s14 = peg$c72; + peg$currPos++; + } else { + s14 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s14 !== peg$FAILED) { + s15 = peg$parseDIGIT_OR_UNDER(); + if (s15 !== peg$FAILED) { + s16 = peg$parseDIGIT_OR_UNDER(); + if (s16 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c74(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedatetime() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 38, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsedate(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 84) { + s2 = peg$c75; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c76); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetime(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 90) { + s4 = peg$c77; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c78); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c79(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsedate(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 84) { + s2 = peg$c75; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c76); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetime_with_offset(); + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c80(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseS() { + var s0; + + var key = peg$currPos * 49 + 39, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c81.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c82); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseNL() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 40, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (input.charCodeAt(peg$currPos) === 10) { + s0 = peg$c83; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c84); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 13) { + s1 = peg$c85; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c86); } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 10) { + s2 = peg$c83; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c84); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseNLS() { + var s0; + + var key = peg$currPos * 49 + 41, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseNL(); + if (s0 === peg$FAILED) { + s0 = peg$parseS(); + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseEOF() { + var s0, s1; + + var key = peg$currPos * 49 + 42, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + peg$silentFails++; + if (input.length > peg$currPos) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + peg$silentFails--; + if (s1 === peg$FAILED) { + s0 = peg$c5; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseHEX() { + var s0; + + var key = peg$currPos * 49 + 43, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c87.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c88); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseDIGIT_OR_UNDER() { + var s0, s1; + + var key = peg$currPos * 49 + 44, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c89.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c90); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s1 = peg$c91; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c92); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c93(); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseASCII_BASIC() { + var s0; + + var key = peg$currPos * 49 + 45, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c94.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c95); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseDIGITS() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 46, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c96(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseESCAPED() { + var s0, s1; + + var key = peg$currPos * 49 + 47, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c97) { + s1 = peg$c97; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c98); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c99(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c100) { + s1 = peg$c100; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c102(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c103) { + s1 = peg$c103; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c104); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c105(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c106) { + s1 = peg$c106; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c107); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c108(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c109) { + s1 = peg$c109; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c110); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c111(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c112) { + s1 = peg$c112; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c113); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c114(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c115) { + s1 = peg$c115; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c116); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c117(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$parseESCAPED_UNICODE(); + } + } + } + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseESCAPED_UNICODE() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 48, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c118) { + s1 = peg$c118; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c119); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseHEX(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEX(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHEX(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHEX(); + if (s6 !== peg$FAILED) { + s7 = peg$parseHEX(); + if (s7 !== peg$FAILED) { + s8 = peg$parseHEX(); + if (s8 !== peg$FAILED) { + s9 = peg$parseHEX(); + if (s9 !== peg$FAILED) { + s10 = peg$parseHEX(); + if (s10 !== peg$FAILED) { + s3 = [s3, s4, s5, s6, s7, s8, s9, s10]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c120(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c121) { + s1 = peg$c121; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c122); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseHEX(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEX(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHEX(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHEX(); + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c120(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + + var nodes = []; + + function genError(err, line, col) { + var ex = new Error(err); + ex.line = line; + ex.column = col; + throw ex; + } + + function addNode(node) { + nodes.push(node); + } + + function node(type, value, line, column, key) { + var obj = { type: type, value: value, line: line(), column: column() }; + if (key) obj.key = key; + return obj; + } + + function convertCodePoint(str, line, col) { + var num = parseInt("0x" + str); + + if ( + !isFinite(num) || + Math.floor(num) != num || + num < 0 || + num > 0x10FFFF || + (num > 0xD7FF && num < 0xE000) + ) { + genError("Invalid Unicode escape code: " + str, line, col); + } else { + return fromCodePoint(num); + } + } + + function fromCodePoint() { + var MAX_SIZE = 0x4000; + var codeUnits = []; + var highSurrogate; + var lowSurrogate; + var index = -1; + var length = arguments.length; + if (!length) { + return ''; + } + var result = ''; + while (++index < length) { + var codePoint = Number(arguments[index]); + if (codePoint <= 0xFFFF) { // BMP code point + codeUnits.push(codePoint); + } else { // Astral code point; split in surrogate halves + // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + codePoint -= 0x10000; + highSurrogate = (codePoint >> 10) + 0xD800; + lowSurrogate = (codePoint % 0x400) + 0xDC00; + codeUnits.push(highSurrogate, lowSurrogate); + } + if (index + 1 == length || codeUnits.length > MAX_SIZE) { + result += String.fromCharCode.apply(null, codeUnits); + codeUnits.length = 0; + } + } + return result; + } + + + peg$result = peg$startRuleFunction(); + + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail({ type: "end", description: "end of input" }); + } + + throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos); + } + } + + return { + SyntaxError: SyntaxError, + parse: parse + }; +})(); + + +/***/ }), + +/***/ 1430: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * IPv6 Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (root) { + 'use strict'; + + /* + var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156"; + var _out = IPv6.best(_in); + var _expected = "fe80::204:61ff:fe9d:f156"; + + console.log(_in, _out, _expected, _out === _expected); + */ + + // save current IPv6 variable, if any + var _IPv6 = root && root.IPv6; + + function bestPresentation(address) { + // based on: + // Javascript to test an IPv6 address for proper format, and to + // present the "best text representation" according to IETF Draft RFC at + // http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04 + // 8 Feb 2010 Rich Brown, Dartware, LLC + // Please feel free to use this code as long as you provide a link to + // http://www.intermapper.com + // http://intermapper.com/support/tools/IPV6-Validator.aspx + // http://download.dartware.com/thirdparty/ipv6validator.js + + var _address = address.toLowerCase(); + var segments = _address.split(':'); + var length = segments.length; + var total = 8; + + // trim colons (:: or ::a:b:c… or …a:b:c::) + if (segments[0] === '' && segments[1] === '' && segments[2] === '') { + // must have been :: + // remove first two items + segments.shift(); + segments.shift(); + } else if (segments[0] === '' && segments[1] === '') { + // must have been ::xxxx + // remove the first item + segments.shift(); + } else if (segments[length - 1] === '' && segments[length - 2] === '') { + // must have been xxxx:: + segments.pop(); + } + + length = segments.length; + + // adjust total segments for IPv4 trailer + if (segments[length - 1].indexOf('.') !== -1) { + // found a "." which means IPv4 + total = 7; + } + + // fill empty segments them with "0000" + var pos; + for (pos = 0; pos < length; pos++) { + if (segments[pos] === '') { + break; + } + } + + if (pos < total) { + segments.splice(pos, 1, '0000'); + while (segments.length < total) { + segments.splice(pos, 0, '0000'); + } + } + + // strip leading zeros + var _segments; + for (var i = 0; i < total; i++) { + _segments = segments[i].split(''); + for (var j = 0; j < 3 ; j++) { + if (_segments[0] === '0' && _segments.length > 1) { + _segments.splice(0,1); + } else { + break; + } + } + + segments[i] = _segments.join(''); + } + + // find longest sequence of zeroes and coalesce them into one segment + var best = -1; + var _best = 0; + var _current = 0; + var current = -1; + var inzeroes = false; + // i; already declared + + for (i = 0; i < total; i++) { + if (inzeroes) { + if (segments[i] === '0') { + _current += 1; + } else { + inzeroes = false; + if (_current > _best) { + best = current; + _best = _current; + } + } + } else { + if (segments[i] === '0') { + inzeroes = true; + current = i; + _current = 1; + } + } + } + + if (_current > _best) { + best = current; + _best = _current; + } + + if (_best > 1) { + segments.splice(best, _best, ''); + } + + length = segments.length; + + // assemble remaining segments + var result = ''; + if (segments[0] === '') { + result = ':'; + } + + for (i = 0; i < length; i++) { + result += segments[i]; + if (i === length - 1) { + break; + } + + result += ':'; + } + + if (segments[length - 1] === '') { + result += ':'; + } + + return result; + } + + function noConflict() { + /*jshint validthis: true */ + if (root.IPv6 === this) { + root.IPv6 = _IPv6; + } + + return this; + } + + return { + best: bestPresentation, + noConflict: noConflict + }; +})); + + +/***/ }), + +/***/ 4704: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * Second Level Domain (SLD) Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (root) { + 'use strict'; + + // save current SecondLevelDomains variable, if any + var _SecondLevelDomains = root && root.SecondLevelDomains; + + var SLD = { + // list of known Second Level Domains + // converted list of SLDs from https://github.com/gavingmiller/second-level-domains + // ---- + // publicsuffix.org is more current and actually used by a couple of browsers internally. + // downside is it also contains domains like "dyndns.org" - which is fine for the security + // issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js + // ---- + list: { + 'ac':' com gov mil net org ', + 'ae':' ac co gov mil name net org pro sch ', + 'af':' com edu gov net org ', + 'al':' com edu gov mil net org ', + 'ao':' co ed gv it og pb ', + 'ar':' com edu gob gov int mil net org tur ', + 'at':' ac co gv or ', + 'au':' asn com csiro edu gov id net org ', + 'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ', + 'bb':' biz co com edu gov info net org store tv ', + 'bh':' biz cc com edu gov info net org ', + 'bn':' com edu gov net org ', + 'bo':' com edu gob gov int mil net org tv ', + 'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ', + 'bs':' com edu gov net org ', + 'bz':' du et om ov rg ', + 'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ', + 'ck':' biz co edu gen gov info net org ', + 'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ', + 'co':' com edu gov mil net nom org ', + 'cr':' ac c co ed fi go or sa ', + 'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ', + 'do':' art com edu gob gov mil net org sld web ', + 'dz':' art asso com edu gov net org pol ', + 'ec':' com edu fin gov info med mil net org pro ', + 'eg':' com edu eun gov mil name net org sci ', + 'er':' com edu gov ind mil net org rochest w ', + 'es':' com edu gob nom org ', + 'et':' biz com edu gov info name net org ', + 'fj':' ac biz com info mil name net org pro ', + 'fk':' ac co gov net nom org ', + 'fr':' asso com f gouv nom prd presse tm ', + 'gg':' co net org ', + 'gh':' com edu gov mil org ', + 'gn':' ac com gov net org ', + 'gr':' com edu gov mil net org ', + 'gt':' com edu gob ind mil net org ', + 'gu':' com edu gov net org ', + 'hk':' com edu gov idv net org ', + 'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ', + 'id':' ac co go mil net or sch web ', + 'il':' ac co gov idf k12 muni net org ', + 'in':' ac co edu ernet firm gen gov i ind mil net nic org res ', + 'iq':' com edu gov i mil net org ', + 'ir':' ac co dnssec gov i id net org sch ', + 'it':' edu gov ', + 'je':' co net org ', + 'jo':' com edu gov mil name net org sch ', + 'jp':' ac ad co ed go gr lg ne or ', + 'ke':' ac co go info me mobi ne or sc ', + 'kh':' com edu gov mil net org per ', + 'ki':' biz com de edu gov info mob net org tel ', + 'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ', + 'kn':' edu gov net org ', + 'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ', + 'kw':' com edu gov net org ', + 'ky':' com edu gov net org ', + 'kz':' com edu gov mil net org ', + 'lb':' com edu gov net org ', + 'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ', + 'lr':' com edu gov net org ', + 'lv':' asn com conf edu gov id mil net org ', + 'ly':' com edu gov id med net org plc sch ', + 'ma':' ac co gov m net org press ', + 'mc':' asso tm ', + 'me':' ac co edu gov its net org priv ', + 'mg':' com edu gov mil nom org prd tm ', + 'mk':' com edu gov inf name net org pro ', + 'ml':' com edu gov net org presse ', + 'mn':' edu gov org ', + 'mo':' com edu gov net org ', + 'mt':' com edu gov net org ', + 'mv':' aero biz com coop edu gov info int mil museum name net org pro ', + 'mw':' ac co com coop edu gov int museum net org ', + 'mx':' com edu gob net org ', + 'my':' com edu gov mil name net org sch ', + 'nf':' arts com firm info net other per rec store web ', + 'ng':' biz com edu gov mil mobi name net org sch ', + 'ni':' ac co com edu gob mil net nom org ', + 'np':' com edu gov mil net org ', + 'nr':' biz com edu gov info net org ', + 'om':' ac biz co com edu gov med mil museum net org pro sch ', + 'pe':' com edu gob mil net nom org sld ', + 'ph':' com edu gov i mil net ngo org ', + 'pk':' biz com edu fam gob gok gon gop gos gov net org web ', + 'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ', + 'pr':' ac biz com edu est gov info isla name net org pro prof ', + 'ps':' com edu gov net org plo sec ', + 'pw':' belau co ed go ne or ', + 'ro':' arts com firm info nom nt org rec store tm www ', + 'rs':' ac co edu gov in org ', + 'sb':' com edu gov net org ', + 'sc':' com edu gov net org ', + 'sh':' co com edu gov net nom org ', + 'sl':' com edu gov net org ', + 'st':' co com consulado edu embaixada gov mil net org principe saotome store ', + 'sv':' com edu gob org red ', + 'sz':' ac co org ', + 'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ', + 'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ', + 'tw':' club com ebiz edu game gov idv mil net org ', + 'mu':' ac co com gov net or org ', + 'mz':' ac co edu gov org ', + 'na':' co com ', + 'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ', + 'pa':' abo ac com edu gob ing med net nom org sld ', + 'pt':' com edu gov int net nome org publ ', + 'py':' com edu gov mil net org ', + 'qa':' com edu gov mil net org ', + 're':' asso com nom ', + 'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ', + 'rw':' ac co com edu gouv gov int mil net ', + 'sa':' com edu gov med net org pub sch ', + 'sd':' com edu gov info med net org tv ', + 'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ', + 'sg':' com edu gov idn net org per ', + 'sn':' art com edu gouv org perso univ ', + 'sy':' com edu gov mil net news org ', + 'th':' ac co go in mi net or ', + 'tj':' ac biz co com edu go gov info int mil name net nic org test web ', + 'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ', + 'tz':' ac co go ne or ', + 'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ', + 'ug':' ac co go ne or org sc ', + 'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ', + 'us':' dni fed isa kids nsn ', + 'uy':' com edu gub mil net org ', + 've':' co com edu gob info mil net org web ', + 'vi':' co com k12 net org ', + 'vn':' ac biz com edu gov health info int name net org pro ', + 'ye':' co com gov ltd me net org plc ', + 'yu':' ac co edu gov org ', + 'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ', + 'zm':' ac co com edu gov net org sch ', + // https://en.wikipedia.org/wiki/CentralNic#Second-level_domains + 'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ', + 'net': 'gb jp se uk ', + 'org': 'ae', + 'de': 'com ' + }, + // gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost + // in both performance and memory footprint. No initialization required. + // http://jsperf.com/uri-js-sld-regex-vs-binary-search/4 + // Following methods use lastIndexOf() rather than array.split() in order + // to avoid any memory allocations. + has: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return false; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) { + return false; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return false; + } + return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0; + }, + is: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return false; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset >= 0) { + return false; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return false; + } + return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0; + }, + get: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return null; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) { + return null; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return null; + } + if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) { + return null; + } + return domain.slice(sldOffset+1); + }, + noConflict: function(){ + if (root.SecondLevelDomains === this) { + root.SecondLevelDomains = _SecondLevelDomains; + } + return this; + } + }; + + return SLD; +})); + + +/***/ }), + +/***/ 4193: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(__webpack_require__(9340), __webpack_require__(1430), __webpack_require__(4704)); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(9340), __webpack_require__(1430), __webpack_require__(4704)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (punycode, IPv6, SLD, root) { + 'use strict'; + /*global location, escape, unescape */ + // FIXME: v2.0.0 renamce non-camelCase properties to uppercase + /*jshint camelcase: false */ + + // save current URI variable, if any + var _URI = root && root.URI; + + function URI(url, base) { + var _urlSupplied = arguments.length >= 1; + var _baseSupplied = arguments.length >= 2; + + // Allow instantiation without the 'new' keyword + if (!(this instanceof URI)) { + if (_urlSupplied) { + if (_baseSupplied) { + return new URI(url, base); + } + + return new URI(url); + } + + return new URI(); + } + + if (url === undefined) { + if (_urlSupplied) { + throw new TypeError('undefined is not a valid argument for URI'); + } + + if (typeof location !== 'undefined') { + url = location.href + ''; + } else { + url = ''; + } + } + + if (url === null) { + if (_urlSupplied) { + throw new TypeError('null is not a valid argument for URI'); + } + } + + this.href(url); + + // resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor + if (base !== undefined) { + return this.absoluteTo(base); + } + + return this; + } + + function isInteger(value) { + return /^[0-9]+$/.test(value); + } + + URI.version = '1.19.11'; + + var p = URI.prototype; + var hasOwn = Object.prototype.hasOwnProperty; + + function escapeRegEx(string) { + // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963 + return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); + } + + function getType(value) { + // IE8 doesn't return [Object Undefined] but [Object Object] for undefined value + if (value === undefined) { + return 'Undefined'; + } + + return String(Object.prototype.toString.call(value)).slice(8, -1); + } + + function isArray(obj) { + return getType(obj) === 'Array'; + } + + function filterArrayValues(data, value) { + var lookup = {}; + var i, length; + + if (getType(value) === 'RegExp') { + lookup = null; + } else if (isArray(value)) { + for (i = 0, length = value.length; i < length; i++) { + lookup[value[i]] = true; + } + } else { + lookup[value] = true; + } + + for (i = 0, length = data.length; i < length; i++) { + /*jshint laxbreak: true */ + var _match = lookup && lookup[data[i]] !== undefined + || !lookup && value.test(data[i]); + /*jshint laxbreak: false */ + if (_match) { + data.splice(i, 1); + length--; + i--; + } + } + + return data; + } + + function arrayContains(list, value) { + var i, length; + + // value may be string, number, array, regexp + if (isArray(value)) { + // Note: this can be optimized to O(n) (instead of current O(m * n)) + for (i = 0, length = value.length; i < length; i++) { + if (!arrayContains(list, value[i])) { + return false; + } + } + + return true; + } + + var _type = getType(value); + for (i = 0, length = list.length; i < length; i++) { + if (_type === 'RegExp') { + if (typeof list[i] === 'string' && list[i].match(value)) { + return true; + } + } else if (list[i] === value) { + return true; + } + } + + return false; + } + + function arraysEqual(one, two) { + if (!isArray(one) || !isArray(two)) { + return false; + } + + // arrays can't be equal if they have different amount of content + if (one.length !== two.length) { + return false; + } + + one.sort(); + two.sort(); + + for (var i = 0, l = one.length; i < l; i++) { + if (one[i] !== two[i]) { + return false; + } + } + + return true; + } + + function trimSlashes(text) { + var trim_expression = /^\/+|\/+$/g; + return text.replace(trim_expression, ''); + } + + URI._parts = function() { + return { + protocol: null, + username: null, + password: null, + hostname: null, + urn: null, + port: null, + path: null, + query: null, + fragment: null, + // state + preventInvalidHostname: URI.preventInvalidHostname, + duplicateQueryParameters: URI.duplicateQueryParameters, + escapeQuerySpace: URI.escapeQuerySpace + }; + }; + // state: throw on invalid hostname + // see https://github.com/medialize/URI.js/pull/345 + // and https://github.com/medialize/URI.js/issues/354 + URI.preventInvalidHostname = false; + // state: allow duplicate query parameters (a=1&a=1) + URI.duplicateQueryParameters = false; + // state: replaces + with %20 (space in query strings) + URI.escapeQuerySpace = true; + // static properties + URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i; + URI.idn_expression = /[^a-z0-9\._-]/i; + URI.punycode_expression = /(xn--)/i; + // well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care? + URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; + // credits to Rich Brown + // source: http://forums.intermapper.com/viewtopic.php?p=1096#1096 + // specification: http://www.ietf.org/rfc/rfc4291.txt + URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/; + // expression used is "gruber revised" (@gruber v2) determined to be the + // best solution in a regex-golf we did a couple of ages ago at + // * http://mathiasbynens.be/demo/url-regex + // * http://rodneyrehm.de/t/url-regex.html + URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig; + URI.findUri = { + // valid "scheme://" or "www." + start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi, + // everything up to the next whitespace + end: /[\s\r\n]|$/, + // trim trailing punctuation captured by end RegExp + trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/, + // balanced parens inclusion (), [], {}, <> + parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g, + }; + URI.leading_whitespace_expression = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/ + // https://infra.spec.whatwg.org/#ascii-tab-or-newline + URI.ascii_tab_whitespace = /[\u0009\u000A\u000D]+/g + // http://www.iana.org/assignments/uri-schemes.html + // http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports + URI.defaultPorts = { + http: '80', + https: '443', + ftp: '21', + gopher: '70', + ws: '80', + wss: '443' + }; + // list of protocols which always require a hostname + URI.hostProtocols = [ + 'http', + 'https' + ]; + + // allowed hostname characters according to RFC 3986 + // ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded + // I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _ + URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/; + // map DOM Elements to their URI attribute + URI.domAttributes = { + 'a': 'href', + 'blockquote': 'cite', + 'link': 'href', + 'base': 'href', + 'script': 'src', + 'form': 'action', + 'img': 'src', + 'area': 'href', + 'iframe': 'src', + 'embed': 'src', + 'source': 'src', + 'track': 'src', + 'input': 'src', // but only if type="image" + 'audio': 'src', + 'video': 'src' + }; + URI.getDomAttribute = function(node) { + if (!node || !node.nodeName) { + return undefined; + } + + var nodeName = node.nodeName.toLowerCase(); + // should only expose src for type="image" + if (nodeName === 'input' && node.type !== 'image') { + return undefined; + } + + return URI.domAttributes[nodeName]; + }; + + function escapeForDumbFirefox36(value) { + // https://github.com/medialize/URI.js/issues/91 + return escape(value); + } + + // encoding / decoding according to RFC3986 + function strictEncodeURIComponent(string) { + // see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent + return encodeURIComponent(string) + .replace(/[!'()*]/g, escapeForDumbFirefox36) + .replace(/\*/g, '%2A'); + } + URI.encode = strictEncodeURIComponent; + URI.decode = decodeURIComponent; + URI.iso8859 = function() { + URI.encode = escape; + URI.decode = unescape; + }; + URI.unicode = function() { + URI.encode = strictEncodeURIComponent; + URI.decode = decodeURIComponent; + }; + URI.characters = { + pathname: { + encode: { + // RFC3986 2.1: For consistency, URI producers and normalizers should + // use uppercase hexadecimal digits for all percent-encodings. + expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig, + map: { + // -._~!'()* + '%24': '$', + '%26': '&', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=', + '%3A': ':', + '%40': '@' + } + }, + decode: { + expression: /[\/\?#]/g, + map: { + '/': '%2F', + '?': '%3F', + '#': '%23' + } + } + }, + reserved: { + encode: { + // RFC3986 2.1: For consistency, URI producers and normalizers should + // use uppercase hexadecimal digits for all percent-encodings. + expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig, + map: { + // gen-delims + '%3A': ':', + '%2F': '/', + '%3F': '?', + '%23': '#', + '%5B': '[', + '%5D': ']', + '%40': '@', + // sub-delims + '%21': '!', + '%24': '$', + '%26': '&', + '%27': '\'', + '%28': '(', + '%29': ')', + '%2A': '*', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=' + } + } + }, + urnpath: { + // The characters under `encode` are the characters called out by RFC 2141 as being acceptable + // for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but + // these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also + // note that the colon character is not featured in the encoding map; this is because URI.js + // gives the colons in URNs semantic meaning as the delimiters of path segements, and so it + // should not appear unencoded in a segment itself. + // See also the note above about RFC3986 and capitalalized hex digits. + encode: { + expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig, + map: { + '%21': '!', + '%24': '$', + '%27': '\'', + '%28': '(', + '%29': ')', + '%2A': '*', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=', + '%40': '@' + } + }, + // These characters are the characters called out by RFC2141 as "reserved" characters that + // should never appear in a URN, plus the colon character (see note above). + decode: { + expression: /[\/\?#:]/g, + map: { + '/': '%2F', + '?': '%3F', + '#': '%23', + ':': '%3A' + } + } + } + }; + URI.encodeQuery = function(string, escapeQuerySpace) { + var escaped = URI.encode(string + ''); + if (escapeQuerySpace === undefined) { + escapeQuerySpace = URI.escapeQuerySpace; + } + + return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped; + }; + URI.decodeQuery = function(string, escapeQuerySpace) { + string += ''; + if (escapeQuerySpace === undefined) { + escapeQuerySpace = URI.escapeQuerySpace; + } + + try { + return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string); + } catch(e) { + // we're not going to mess with weird encodings, + // give up and return the undecoded original string + // see https://github.com/medialize/URI.js/issues/87 + // see https://github.com/medialize/URI.js/issues/92 + return string; + } + }; + // generate encode/decode path functions + var _parts = {'encode':'encode', 'decode':'decode'}; + var _part; + var generateAccessor = function(_group, _part) { + return function(string) { + try { + return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) { + return URI.characters[_group][_part].map[c]; + }); + } catch (e) { + // we're not going to mess with weird encodings, + // give up and return the undecoded original string + // see https://github.com/medialize/URI.js/issues/87 + // see https://github.com/medialize/URI.js/issues/92 + return string; + } + }; + }; + + for (_part in _parts) { + URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]); + URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]); + } + + var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) { + return function(string) { + // Why pass in names of functions, rather than the function objects themselves? The + // definitions of some functions (but in particular, URI.decode) will occasionally change due + // to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure + // that the functions we use here are "fresh". + var actualCodingFunc; + if (!_innerCodingFuncName) { + actualCodingFunc = URI[_codingFuncName]; + } else { + actualCodingFunc = function(string) { + return URI[_codingFuncName](URI[_innerCodingFuncName](string)); + }; + } + + var segments = (string + '').split(_sep); + + for (var i = 0, length = segments.length; i < length; i++) { + segments[i] = actualCodingFunc(segments[i]); + } + + return segments.join(_sep); + }; + }; + + // This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions. + URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment'); + URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment'); + URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode'); + URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode'); + + URI.encodeReserved = generateAccessor('reserved', 'encode'); + + URI.parse = function(string, parts) { + var pos; + if (!parts) { + parts = { + preventInvalidHostname: URI.preventInvalidHostname + }; + } + + string = string.replace(URI.leading_whitespace_expression, '') + // https://infra.spec.whatwg.org/#ascii-tab-or-newline + string = string.replace(URI.ascii_tab_whitespace, '') + + // [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment] + + // extract fragment + pos = string.indexOf('#'); + if (pos > -1) { + // escaping? + parts.fragment = string.substring(pos + 1) || null; + string = string.substring(0, pos); + } + + // extract query + pos = string.indexOf('?'); + if (pos > -1) { + // escaping? + parts.query = string.substring(pos + 1) || null; + string = string.substring(0, pos); + } + + // slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws) + string = string.replace(/^(https?|ftp|wss?)?:+[/\\]*/i, '$1://'); + // slashes and backslashes have lost all meaning for scheme relative URLs + string = string.replace(/^[/\\]{2,}/i, '//'); + + // extract protocol + if (string.substring(0, 2) === '//') { + // relative-scheme + parts.protocol = null; + string = string.substring(2); + // extract "user:pass@host:port" + string = URI.parseAuthority(string, parts); + } else { + pos = string.indexOf(':'); + if (pos > -1) { + parts.protocol = string.substring(0, pos) || null; + if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) { + // : may be within the path + parts.protocol = undefined; + } else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') { + string = string.substring(pos + 3); + + // extract "user:pass@host:port" + string = URI.parseAuthority(string, parts); + } else { + string = string.substring(pos + 1); + parts.urn = true; + } + } + } + + // what's left must be the path + parts.path = string; + + // and we're done + return parts; + }; + URI.parseHost = function(string, parts) { + if (!string) { + string = ''; + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124 + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + // https://github.com/medialize/URI.js/pull/233 + string = string.replace(/\\/g, '/'); + + // extract host:port + var pos = string.indexOf('/'); + var bracketPos; + var t; + + if (pos === -1) { + pos = string.length; + } + + if (string.charAt(0) === '[') { + // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6 + // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts + // IPv6+port in the format [2001:db8::1]:80 (for the time being) + bracketPos = string.indexOf(']'); + parts.hostname = string.substring(1, bracketPos) || null; + parts.port = string.substring(bracketPos + 2, pos) || null; + if (parts.port === '/') { + parts.port = null; + } + } else { + var firstColon = string.indexOf(':'); + var firstSlash = string.indexOf('/'); + var nextColon = string.indexOf(':', firstColon + 1); + if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) { + // IPv6 host contains multiple colons - but no port + // this notation is actually not allowed by RFC 3986, but we're a liberal parser + parts.hostname = string.substring(0, pos) || null; + parts.port = null; + } else { + t = string.substring(0, pos).split(':'); + parts.hostname = t[0] || null; + parts.port = t[1] || null; + } + } + + if (parts.hostname && string.substring(pos).charAt(0) !== '/') { + pos++; + string = '/' + string; + } + + if (parts.preventInvalidHostname) { + URI.ensureValidHostname(parts.hostname, parts.protocol); + } + + if (parts.port) { + URI.ensureValidPort(parts.port); + } + + return string.substring(pos) || '/'; + }; + URI.parseAuthority = function(string, parts) { + string = URI.parseUserinfo(string, parts); + return URI.parseHost(string, parts); + }; + URI.parseUserinfo = function(string, parts) { + // extract username:password + var _string = string + var firstBackSlash = string.indexOf('\\'); + if (firstBackSlash !== -1) { + string = string.replace(/\\/g, '/') + } + var firstSlash = string.indexOf('/'); + var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1); + var t; + + // authority@ must come before /path or \path + if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) { + t = string.substring(0, pos).split(':'); + parts.username = t[0] ? URI.decode(t[0]) : null; + t.shift(); + parts.password = t[0] ? URI.decode(t.join(':')) : null; + string = _string.substring(pos + 1); + } else { + parts.username = null; + parts.password = null; + } + + return string; + }; + URI.parseQuery = function(string, escapeQuerySpace) { + if (!string) { + return {}; + } + + // throw out the funky business - "?"[name"="value"&"]+ + string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, ''); + + if (!string) { + return {}; + } + + var items = {}; + var splits = string.split('&'); + var length = splits.length; + var v, name, value; + + for (var i = 0; i < length; i++) { + v = splits[i].split('='); + name = URI.decodeQuery(v.shift(), escapeQuerySpace); + // no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters + value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null; + + if (name === '__proto__') { + // ignore attempt at exploiting JavaScript internals + continue; + } else if (hasOwn.call(items, name)) { + if (typeof items[name] === 'string' || items[name] === null) { + items[name] = [items[name]]; + } + + items[name].push(value); + } else { + items[name] = value; + } + } + + return items; + }; + + URI.build = function(parts) { + var t = ''; + var requireAbsolutePath = false + + if (parts.protocol) { + t += parts.protocol + ':'; + } + + if (!parts.urn && (t || parts.hostname)) { + t += '//'; + requireAbsolutePath = true + } + + t += (URI.buildAuthority(parts) || ''); + + if (typeof parts.path === 'string') { + if (parts.path.charAt(0) !== '/' && requireAbsolutePath) { + t += '/'; + } + + t += parts.path; + } + + if (typeof parts.query === 'string' && parts.query) { + t += '?' + parts.query; + } + + if (typeof parts.fragment === 'string' && parts.fragment) { + t += '#' + parts.fragment; + } + return t; + }; + URI.buildHost = function(parts) { + var t = ''; + + if (!parts.hostname) { + return ''; + } else if (URI.ip6_expression.test(parts.hostname)) { + t += '[' + parts.hostname + ']'; + } else { + t += parts.hostname; + } + + if (parts.port) { + t += ':' + parts.port; + } + + return t; + }; + URI.buildAuthority = function(parts) { + return URI.buildUserinfo(parts) + URI.buildHost(parts); + }; + URI.buildUserinfo = function(parts) { + var t = ''; + + if (parts.username) { + t += URI.encode(parts.username); + } + + if (parts.password) { + t += ':' + URI.encode(parts.password); + } + + if (t) { + t += '@'; + } + + return t; + }; + URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) { + // according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html + // being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed + // the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax! + // URI.js treats the query string as being application/x-www-form-urlencoded + // see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type + + var t = ''; + var unique, key, i, length; + for (key in data) { + if (key === '__proto__') { + // ignore attempt at exploiting JavaScript internals + continue; + } else if (hasOwn.call(data, key)) { + if (isArray(data[key])) { + unique = {}; + for (i = 0, length = data[key].length; i < length; i++) { + if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) { + t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace); + if (duplicateQueryParameters !== true) { + unique[data[key][i] + ''] = true; + } + } + } + } else if (data[key] !== undefined) { + t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace); + } + } + } + + return t.substring(1); + }; + URI.buildQueryParameter = function(name, value, escapeQuerySpace) { + // http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded + // don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization + return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : ''); + }; + + URI.addQuery = function(data, name, value) { + if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + URI.addQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + if (data[name] === undefined) { + data[name] = value; + return; + } else if (typeof data[name] === 'string') { + data[name] = [data[name]]; + } + + if (!isArray(value)) { + value = [value]; + } + + data[name] = (data[name] || []).concat(value); + } else { + throw new TypeError('URI.addQuery() accepts an object, string as the name parameter'); + } + }; + + URI.setQuery = function(data, name, value) { + if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + URI.setQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + data[name] = value === undefined ? null : value; + } else { + throw new TypeError('URI.setQuery() accepts an object, string as the name parameter'); + } + }; + + URI.removeQuery = function(data, name, value) { + var i, length, key; + + if (isArray(name)) { + for (i = 0, length = name.length; i < length; i++) { + data[name[i]] = undefined; + } + } else if (getType(name) === 'RegExp') { + for (key in data) { + if (name.test(key)) { + data[key] = undefined; + } + } + } else if (typeof name === 'object') { + for (key in name) { + if (hasOwn.call(name, key)) { + URI.removeQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + if (value !== undefined) { + if (getType(value) === 'RegExp') { + if (!isArray(data[name]) && value.test(data[name])) { + data[name] = undefined; + } else { + data[name] = filterArrayValues(data[name], value); + } + } else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) { + data[name] = undefined; + } else if (isArray(data[name])) { + data[name] = filterArrayValues(data[name], value); + } + } else { + data[name] = undefined; + } + } else { + throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter'); + } + }; + URI.hasQuery = function(data, name, value, withinArray) { + switch (getType(name)) { + case 'String': + // Nothing to do here + break; + + case 'RegExp': + for (var key in data) { + if (hasOwn.call(data, key)) { + if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) { + return true; + } + } + } + + return false; + + case 'Object': + for (var _key in name) { + if (hasOwn.call(name, _key)) { + if (!URI.hasQuery(data, _key, name[_key])) { + return false; + } + } + } + + return true; + + default: + throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter'); + } + + switch (getType(value)) { + case 'Undefined': + // true if exists (but may be empty) + return name in data; // data[name] !== undefined; + + case 'Boolean': + // true if exists and non-empty + var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]); + return value === _booly; + + case 'Function': + // allow complex comparison + return !!value(data[name], name, data); + + case 'Array': + if (!isArray(data[name])) { + return false; + } + + var op = withinArray ? arrayContains : arraysEqual; + return op(data[name], value); + + case 'RegExp': + if (!isArray(data[name])) { + return Boolean(data[name] && data[name].match(value)); + } + + if (!withinArray) { + return false; + } + + return arrayContains(data[name], value); + + case 'Number': + value = String(value); + /* falls through */ + case 'String': + if (!isArray(data[name])) { + return data[name] === value; + } + + if (!withinArray) { + return false; + } + + return arrayContains(data[name], value); + + default: + throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter'); + } + }; + + + URI.joinPaths = function() { + var input = []; + var segments = []; + var nonEmptySegments = 0; + + for (var i = 0; i < arguments.length; i++) { + var url = new URI(arguments[i]); + input.push(url); + var _segments = url.segment(); + for (var s = 0; s < _segments.length; s++) { + if (typeof _segments[s] === 'string') { + segments.push(_segments[s]); + } + + if (_segments[s]) { + nonEmptySegments++; + } + } + } + + if (!segments.length || !nonEmptySegments) { + return new URI(''); + } + + var uri = new URI('').segment(segments); + + if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') { + uri.path('/' + uri.path()); + } + + return uri.normalize(); + }; + + URI.commonPath = function(one, two) { + var length = Math.min(one.length, two.length); + var pos; + + // find first non-matching character + for (pos = 0; pos < length; pos++) { + if (one.charAt(pos) !== two.charAt(pos)) { + pos--; + break; + } + } + + if (pos < 1) { + return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : ''; + } + + // revert to last / + if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') { + pos = one.substring(0, pos).lastIndexOf('/'); + } + + return one.substring(0, pos + 1); + }; + + URI.withinString = function(string, callback, options) { + options || (options = {}); + var _start = options.start || URI.findUri.start; + var _end = options.end || URI.findUri.end; + var _trim = options.trim || URI.findUri.trim; + var _parens = options.parens || URI.findUri.parens; + var _attributeOpen = /[a-z0-9-]=["']?$/i; + + _start.lastIndex = 0; + while (true) { + var match = _start.exec(string); + if (!match) { + break; + } + + var start = match.index; + if (options.ignoreHtml) { + // attribut(e=["']?$) + var attributeOpen = string.slice(Math.max(start - 3, 0), start); + if (attributeOpen && _attributeOpen.test(attributeOpen)) { + continue; + } + } + + var end = start + string.slice(start).search(_end); + var slice = string.slice(start, end); + // make sure we include well balanced parens + var parensEnd = -1; + while (true) { + var parensMatch = _parens.exec(slice); + if (!parensMatch) { + break; + } + + var parensMatchEnd = parensMatch.index + parensMatch[0].length; + parensEnd = Math.max(parensEnd, parensMatchEnd); + } + + if (parensEnd > -1) { + slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, ''); + } else { + slice = slice.replace(_trim, ''); + } + + if (slice.length <= match[0].length) { + // the extract only contains the starting marker of a URI, + // e.g. "www" or "http://" + continue; + } + + if (options.ignore && options.ignore.test(slice)) { + continue; + } + + end = start + slice.length; + var result = callback(slice, start, end, string); + if (result === undefined) { + _start.lastIndex = end; + continue; + } + + result = String(result); + string = string.slice(0, start) + result + string.slice(end); + _start.lastIndex = start + result.length; + } + + _start.lastIndex = 0; + return string; + }; + + URI.ensureValidHostname = function(v, protocol) { + // Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986) + // they are not part of DNS and therefore ignored by URI.js + + var hasHostname = !!v; // not null and not an empty string + var hasProtocol = !!protocol; + var rejectEmptyHostname = false; + + if (hasProtocol) { + rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol); + } + + if (rejectEmptyHostname && !hasHostname) { + throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol); + } else if (v && v.match(URI.invalid_hostname_characters)) { + // test punycode + if (!punycode) { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available'); + } + if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]'); + } + } + }; + + URI.ensureValidPort = function (v) { + if (!v) { + return; + } + + var port = Number(v); + if (isInteger(port) && (port > 0) && (port < 65536)) { + return; + } + + throw new TypeError('Port "' + v + '" is not a valid port'); + }; + + // noConflict + URI.noConflict = function(removeAll) { + if (removeAll) { + var unconflicted = { + URI: this.noConflict() + }; + + if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') { + unconflicted.URITemplate = root.URITemplate.noConflict(); + } + + if (root.IPv6 && typeof root.IPv6.noConflict === 'function') { + unconflicted.IPv6 = root.IPv6.noConflict(); + } + + if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') { + unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict(); + } + + return unconflicted; + } else if (root.URI === this) { + root.URI = _URI; + } + + return this; + }; + + p.build = function(deferBuild) { + if (deferBuild === true) { + this._deferred_build = true; + } else if (deferBuild === undefined || this._deferred_build) { + this._string = URI.build(this._parts); + this._deferred_build = false; + } + + return this; + }; + + p.clone = function() { + return new URI(this); + }; + + p.valueOf = p.toString = function() { + return this.build(false)._string; + }; + + + function generateSimpleAccessor(_part){ + return function(v, build) { + if (v === undefined) { + return this._parts[_part] || ''; + } else { + this._parts[_part] = v || null; + this.build(!build); + return this; + } + }; + } + + function generatePrefixAccessor(_part, _key){ + return function(v, build) { + if (v === undefined) { + return this._parts[_part] || ''; + } else { + if (v !== null) { + v = v + ''; + if (v.charAt(0) === _key) { + v = v.substring(1); + } + } + + this._parts[_part] = v; + this.build(!build); + return this; + } + }; + } + + p.protocol = generateSimpleAccessor('protocol'); + p.username = generateSimpleAccessor('username'); + p.password = generateSimpleAccessor('password'); + p.hostname = generateSimpleAccessor('hostname'); + p.port = generateSimpleAccessor('port'); + p.query = generatePrefixAccessor('query', '?'); + p.fragment = generatePrefixAccessor('fragment', '#'); + + p.search = function(v, build) { + var t = this.query(v, build); + return typeof t === 'string' && t.length ? ('?' + t) : t; + }; + p.hash = function(v, build) { + var t = this.fragment(v, build); + return typeof t === 'string' && t.length ? ('#' + t) : t; + }; + + p.pathname = function(v, build) { + if (v === undefined || v === true) { + var res = this._parts.path || (this._parts.hostname ? '/' : ''); + return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res; + } else { + if (this._parts.urn) { + this._parts.path = v ? URI.recodeUrnPath(v) : ''; + } else { + this._parts.path = v ? URI.recodePath(v) : '/'; + } + this.build(!build); + return this; + } + }; + p.path = p.pathname; + p.href = function(href, build) { + var key; + + if (href === undefined) { + return this.toString(); + } + + this._string = ''; + this._parts = URI._parts(); + + var _URI = href instanceof URI; + var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname); + if (href.nodeName) { + var attribute = URI.getDomAttribute(href); + href = href[attribute] || ''; + _object = false; + } + + // window.location is reported to be an object, but it's not the sort + // of object we're looking for: + // * location.protocol ends with a colon + // * location.query != object.search + // * location.hash != object.fragment + // simply serializing the unknown object should do the trick + // (for location, not for everything...) + if (!_URI && _object && href.pathname !== undefined) { + href = href.toString(); + } + + if (typeof href === 'string' || href instanceof String) { + this._parts = URI.parse(String(href), this._parts); + } else if (_URI || _object) { + var src = _URI ? href._parts : href; + for (key in src) { + if (key === 'query') { continue; } + if (hasOwn.call(this._parts, key)) { + this._parts[key] = src[key]; + } + } + if (src.query) { + this.query(src.query, false); + } + } else { + throw new TypeError('invalid input'); + } + + this.build(!build); + return this; + }; + + // identification accessors + p.is = function(what) { + var ip = false; + var ip4 = false; + var ip6 = false; + var name = false; + var sld = false; + var idn = false; + var punycode = false; + var relative = !this._parts.urn; + + if (this._parts.hostname) { + relative = false; + ip4 = URI.ip4_expression.test(this._parts.hostname); + ip6 = URI.ip6_expression.test(this._parts.hostname); + ip = ip4 || ip6; + name = !ip; + sld = name && SLD && SLD.has(this._parts.hostname); + idn = name && URI.idn_expression.test(this._parts.hostname); + punycode = name && URI.punycode_expression.test(this._parts.hostname); + } + + switch (what.toLowerCase()) { + case 'relative': + return relative; + + case 'absolute': + return !relative; + + // hostname identification + case 'domain': + case 'name': + return name; + + case 'sld': + return sld; + + case 'ip': + return ip; + + case 'ip4': + case 'ipv4': + case 'inet4': + return ip4; + + case 'ip6': + case 'ipv6': + case 'inet6': + return ip6; + + case 'idn': + return idn; + + case 'url': + return !this._parts.urn; + + case 'urn': + return !!this._parts.urn; + + case 'punycode': + return punycode; + } + + return null; + }; + + // component specific input validation + var _protocol = p.protocol; + var _port = p.port; + var _hostname = p.hostname; + + p.protocol = function(v, build) { + if (v) { + // accept trailing :// + v = v.replace(/:(\/\/)?$/, ''); + + if (!v.match(URI.protocol_expression)) { + throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]'); + } + } + + return _protocol.call(this, v, build); + }; + p.scheme = p.protocol; + p.port = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v !== undefined) { + if (v === 0) { + v = null; + } + + if (v) { + v += ''; + if (v.charAt(0) === ':') { + v = v.substring(1); + } + + URI.ensureValidPort(v); + } + } + return _port.call(this, v, build); + }; + p.hostname = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v !== undefined) { + var x = { preventInvalidHostname: this._parts.preventInvalidHostname }; + var res = URI.parseHost(v, x); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + v = x.hostname; + if (this._parts.preventInvalidHostname) { + URI.ensureValidHostname(v, this._parts.protocol); + } + } + + return _hostname.call(this, v, build); + }; + + // compound accessors + p.origin = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + var protocol = this.protocol(); + var authority = this.authority(); + if (!authority) { + return ''; + } + + return (protocol ? protocol + '://' : '') + this.authority(); + } else { + var origin = URI(v); + this + .protocol(origin.protocol()) + .authority(origin.authority()) + .build(!build); + return this; + } + }; + p.host = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + return this._parts.hostname ? URI.buildHost(this._parts) : ''; + } else { + var res = URI.parseHost(v, this._parts); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + this.build(!build); + return this; + } + }; + p.authority = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + return this._parts.hostname ? URI.buildAuthority(this._parts) : ''; + } else { + var res = URI.parseAuthority(v, this._parts); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + this.build(!build); + return this; + } + }; + p.userinfo = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + var t = URI.buildUserinfo(this._parts); + return t ? t.substring(0, t.length -1) : t; + } else { + if (v[v.length-1] !== '@') { + v += '@'; + } + + URI.parseUserinfo(v, this._parts); + this.build(!build); + return this; + } + }; + p.resource = function(v, build) { + var parts; + + if (v === undefined) { + return this.path() + this.search() + this.hash(); + } + + parts = URI.parse(v); + this._parts.path = parts.path; + this._parts.query = parts.query; + this._parts.fragment = parts.fragment; + this.build(!build); + return this; + }; + + // fraction accessors + p.subdomain = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + // convenience, return "www" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + // grab domain and add another segment + var end = this._parts.hostname.length - this.domain().length - 1; + return this._parts.hostname.substring(0, end) || ''; + } else { + var e = this._parts.hostname.length - this.domain().length; + var sub = this._parts.hostname.substring(0, e); + var replace = new RegExp('^' + escapeRegEx(sub)); + + if (v && v.charAt(v.length - 1) !== '.') { + v += '.'; + } + + if (v.indexOf(':') !== -1) { + throw new TypeError('Domains cannot contain colons'); + } + + if (v) { + URI.ensureValidHostname(v, this._parts.protocol); + } + + this._parts.hostname = this._parts.hostname.replace(replace, v); + this.build(!build); + return this; + } + }; + p.domain = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v === 'boolean') { + build = v; + v = undefined; + } + + // convenience, return "example.org" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + // if hostname consists of 1 or 2 segments, it must be the domain + var t = this._parts.hostname.match(/\./g); + if (t && t.length < 2) { + return this._parts.hostname; + } + + // grab tld and add another segment + var end = this._parts.hostname.length - this.tld(build).length - 1; + end = this._parts.hostname.lastIndexOf('.', end -1) + 1; + return this._parts.hostname.substring(end) || ''; + } else { + if (!v) { + throw new TypeError('cannot set domain empty'); + } + + if (v.indexOf(':') !== -1) { + throw new TypeError('Domains cannot contain colons'); + } + + URI.ensureValidHostname(v, this._parts.protocol); + + if (!this._parts.hostname || this.is('IP')) { + this._parts.hostname = v; + } else { + var replace = new RegExp(escapeRegEx(this.domain()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.tld = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v === 'boolean') { + build = v; + v = undefined; + } + + // return "org" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + var pos = this._parts.hostname.lastIndexOf('.'); + var tld = this._parts.hostname.substring(pos + 1); + + if (build !== true && SLD && SLD.list[tld.toLowerCase()]) { + return SLD.get(this._parts.hostname) || tld; + } + + return tld; + } else { + var replace; + + if (!v) { + throw new TypeError('cannot set TLD empty'); + } else if (v.match(/[^a-zA-Z0-9-]/)) { + if (SLD && SLD.is(v)) { + replace = new RegExp(escapeRegEx(this.tld()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } else { + throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]'); + } + } else if (!this._parts.hostname || this.is('IP')) { + throw new ReferenceError('cannot set TLD on non-domain host'); + } else { + replace = new RegExp(escapeRegEx(this.tld()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.directory = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined || v === true) { + if (!this._parts.path && !this._parts.hostname) { + return ''; + } + + if (this._parts.path === '/') { + return '/'; + } + + var end = this._parts.path.length - this.filename().length - 1; + var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : ''); + + return v ? URI.decodePath(res) : res; + + } else { + var e = this._parts.path.length - this.filename().length; + var directory = this._parts.path.substring(0, e); + var replace = new RegExp('^' + escapeRegEx(directory)); + + // fully qualifier directories begin with a slash + if (!this.is('relative')) { + if (!v) { + v = '/'; + } + + if (v.charAt(0) !== '/') { + v = '/' + v; + } + } + + // directories always end with a slash + if (v && v.charAt(v.length - 1) !== '/') { + v += '/'; + } + + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + this.build(!build); + return this; + } + }; + p.filename = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v !== 'string') { + if (!this._parts.path || this._parts.path === '/') { + return ''; + } + + var pos = this._parts.path.lastIndexOf('/'); + var res = this._parts.path.substring(pos+1); + + return v ? URI.decodePathSegment(res) : res; + } else { + var mutatedDirectory = false; + + if (v.charAt(0) === '/') { + v = v.substring(1); + } + + if (v.match(/\.?\//)) { + mutatedDirectory = true; + } + + var replace = new RegExp(escapeRegEx(this.filename()) + '$'); + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + + if (mutatedDirectory) { + this.normalizePath(build); + } else { + this.build(!build); + } + + return this; + } + }; + p.suffix = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined || v === true) { + if (!this._parts.path || this._parts.path === '/') { + return ''; + } + + var filename = this.filename(); + var pos = filename.lastIndexOf('.'); + var s, res; + + if (pos === -1) { + return ''; + } + + // suffix may only contain alnum characters (yup, I made this up.) + s = filename.substring(pos+1); + res = (/^[a-z0-9%]+$/i).test(s) ? s : ''; + return v ? URI.decodePathSegment(res) : res; + } else { + if (v.charAt(0) === '.') { + v = v.substring(1); + } + + var suffix = this.suffix(); + var replace; + + if (!suffix) { + if (!v) { + return this; + } + + this._parts.path += '.' + URI.recodePath(v); + } else if (!v) { + replace = new RegExp(escapeRegEx('.' + suffix) + '$'); + } else { + replace = new RegExp(escapeRegEx(suffix) + '$'); + } + + if (replace) { + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.segment = function(segment, v, build) { + var separator = this._parts.urn ? ':' : '/'; + var path = this.path(); + var absolute = path.substring(0, 1) === '/'; + var segments = path.split(separator); + + if (segment !== undefined && typeof segment !== 'number') { + build = v; + v = segment; + segment = undefined; + } + + if (segment !== undefined && typeof segment !== 'number') { + throw new Error('Bad segment "' + segment + '", must be 0-based integer'); + } + + if (absolute) { + segments.shift(); + } + + if (segment < 0) { + // allow negative indexes to address from the end + segment = Math.max(segments.length + segment, 0); + } + + if (v === undefined) { + /*jshint laxbreak: true */ + return segment === undefined + ? segments + : segments[segment]; + /*jshint laxbreak: false */ + } else if (segment === null || segments[segment] === undefined) { + if (isArray(v)) { + segments = []; + // collapse empty elements within array + for (var i=0, l=v.length; i < l; i++) { + if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) { + continue; + } + + if (segments.length && !segments[segments.length -1].length) { + segments.pop(); + } + + segments.push(trimSlashes(v[i])); + } + } else if (v || typeof v === 'string') { + v = trimSlashes(v); + if (segments[segments.length -1] === '') { + // empty trailing elements have to be overwritten + // to prevent results such as /foo//bar + segments[segments.length -1] = v; + } else { + segments.push(v); + } + } + } else { + if (v) { + segments[segment] = trimSlashes(v); + } else { + segments.splice(segment, 1); + } + } + + if (absolute) { + segments.unshift(''); + } + + return this.path(segments.join(separator), build); + }; + p.segmentCoded = function(segment, v, build) { + var segments, i, l; + + if (typeof segment !== 'number') { + build = v; + v = segment; + segment = undefined; + } + + if (v === undefined) { + segments = this.segment(segment, v, build); + if (!isArray(segments)) { + segments = segments !== undefined ? URI.decode(segments) : undefined; + } else { + for (i = 0, l = segments.length; i < l; i++) { + segments[i] = URI.decode(segments[i]); + } + } + + return segments; + } + + if (!isArray(v)) { + v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v; + } else { + for (i = 0, l = v.length; i < l; i++) { + v[i] = URI.encode(v[i]); + } + } + + return this.segment(segment, v, build); + }; + + // mutating query string + var q = p.query; + p.query = function(v, build) { + if (v === true) { + return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + } else if (typeof v === 'function') { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + var result = v.call(this, data); + this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + this.build(!build); + return this; + } else if (v !== undefined && typeof v !== 'string') { + this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + this.build(!build); + return this; + } else { + return q.call(this, v, build); + } + }; + p.setQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + + if (typeof name === 'string' || name instanceof String) { + data[name] = value !== undefined ? value : null; + } else if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + data[key] = name[key]; + } + } + } else { + throw new TypeError('URI.addQuery() accepts an object, string as the name parameter'); + } + + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.addQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + URI.addQuery(data, name, value === undefined ? null : value); + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.removeQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + URI.removeQuery(data, name, value); + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.hasQuery = function(name, value, withinArray) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + return URI.hasQuery(data, name, value, withinArray); + }; + p.setSearch = p.setQuery; + p.addSearch = p.addQuery; + p.removeSearch = p.removeQuery; + p.hasSearch = p.hasQuery; + + // sanitizing URLs + p.normalize = function() { + if (this._parts.urn) { + return this + .normalizeProtocol(false) + .normalizePath(false) + .normalizeQuery(false) + .normalizeFragment(false) + .build(); + } + + return this + .normalizeProtocol(false) + .normalizeHostname(false) + .normalizePort(false) + .normalizePath(false) + .normalizeQuery(false) + .normalizeFragment(false) + .build(); + }; + p.normalizeProtocol = function(build) { + if (typeof this._parts.protocol === 'string') { + this._parts.protocol = this._parts.protocol.toLowerCase(); + this.build(!build); + } + + return this; + }; + p.normalizeHostname = function(build) { + if (this._parts.hostname) { + if (this.is('IDN') && punycode) { + this._parts.hostname = punycode.toASCII(this._parts.hostname); + } else if (this.is('IPv6') && IPv6) { + this._parts.hostname = IPv6.best(this._parts.hostname); + } + + this._parts.hostname = this._parts.hostname.toLowerCase(); + this.build(!build); + } + + return this; + }; + p.normalizePort = function(build) { + // remove port of it's the protocol's default + if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) { + this._parts.port = null; + this.build(!build); + } + + return this; + }; + p.normalizePath = function(build) { + var _path = this._parts.path; + if (!_path) { + return this; + } + + if (this._parts.urn) { + this._parts.path = URI.recodeUrnPath(this._parts.path); + this.build(!build); + return this; + } + + if (this._parts.path === '/') { + return this; + } + + _path = URI.recodePath(_path); + + var _was_relative; + var _leadingParents = ''; + var _parent, _pos; + + // handle relative paths + if (_path.charAt(0) !== '/') { + _was_relative = true; + _path = '/' + _path; + } + + // handle relative files (as opposed to directories) + if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') { + _path += '/'; + } + + // resolve simples + _path = _path + .replace(/(\/(\.\/)+)|(\/\.$)/g, '/') + .replace(/\/{2,}/g, '/'); + + // remember leading parents + if (_was_relative) { + _leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || ''; + if (_leadingParents) { + _leadingParents = _leadingParents[0]; + } + } + + // resolve parents + while (true) { + _parent = _path.search(/\/\.\.(\/|$)/); + if (_parent === -1) { + // no more ../ to resolve + break; + } else if (_parent === 0) { + // top level cannot be relative, skip it + _path = _path.substring(3); + continue; + } + + _pos = _path.substring(0, _parent).lastIndexOf('/'); + if (_pos === -1) { + _pos = _parent; + } + _path = _path.substring(0, _pos) + _path.substring(_parent + 3); + } + + // revert to relative + if (_was_relative && this.is('relative')) { + _path = _leadingParents + _path.substring(1); + } + + this._parts.path = _path; + this.build(!build); + return this; + }; + p.normalizePathname = p.normalizePath; + p.normalizeQuery = function(build) { + if (typeof this._parts.query === 'string') { + if (!this._parts.query.length) { + this._parts.query = null; + } else { + this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace)); + } + + this.build(!build); + } + + return this; + }; + p.normalizeFragment = function(build) { + if (!this._parts.fragment) { + this._parts.fragment = null; + this.build(!build); + } + + return this; + }; + p.normalizeSearch = p.normalizeQuery; + p.normalizeHash = p.normalizeFragment; + + p.iso8859 = function() { + // expect unicode input, iso8859 output + var e = URI.encode; + var d = URI.decode; + + URI.encode = escape; + URI.decode = decodeURIComponent; + try { + this.normalize(); + } finally { + URI.encode = e; + URI.decode = d; + } + return this; + }; + + p.unicode = function() { + // expect iso8859 input, unicode output + var e = URI.encode; + var d = URI.decode; + + URI.encode = strictEncodeURIComponent; + URI.decode = unescape; + try { + this.normalize(); + } finally { + URI.encode = e; + URI.decode = d; + } + return this; + }; + + p.readable = function() { + var uri = this.clone(); + // removing username, password, because they shouldn't be displayed according to RFC 3986 + uri.username('').password('').normalize(); + var t = ''; + if (uri._parts.protocol) { + t += uri._parts.protocol + '://'; + } + + if (uri._parts.hostname) { + if (uri.is('punycode') && punycode) { + t += punycode.toUnicode(uri._parts.hostname); + if (uri._parts.port) { + t += ':' + uri._parts.port; + } + } else { + t += uri.host(); + } + } + + if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') { + t += '/'; + } + + t += uri.path(true); + if (uri._parts.query) { + var q = ''; + for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) { + var kv = (qp[i] || '').split('='); + q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace) + .replace(/&/g, '%26'); + + if (kv[1] !== undefined) { + q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace) + .replace(/&/g, '%26'); + } + } + t += '?' + q.substring(1); + } + + t += URI.decodeQuery(uri.hash(), true); + return t; + }; + + // resolving relative and absolute URLs + p.absoluteTo = function(base) { + var resolved = this.clone(); + var properties = ['protocol', 'username', 'password', 'hostname', 'port']; + var basedir, i, p; + + if (this._parts.urn) { + throw new Error('URNs do not have any generally defined hierarchical components'); + } + + if (!(base instanceof URI)) { + base = new URI(base); + } + + if (resolved._parts.protocol) { + // Directly returns even if this._parts.hostname is empty. + return resolved; + } else { + resolved._parts.protocol = base._parts.protocol; + } + + if (this._parts.hostname) { + return resolved; + } + + for (i = 0; (p = properties[i]); i++) { + resolved._parts[p] = base._parts[p]; + } + + if (!resolved._parts.path) { + resolved._parts.path = base._parts.path; + if (!resolved._parts.query) { + resolved._parts.query = base._parts.query; + } + } else { + if (resolved._parts.path.substring(-2) === '..') { + resolved._parts.path += '/'; + } + + if (resolved.path().charAt(0) !== '/') { + basedir = base.directory(); + basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : ''; + resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path; + resolved.normalizePath(); + } + } + + resolved.build(); + return resolved; + }; + p.relativeTo = function(base) { + var relative = this.clone().normalize(); + var relativeParts, baseParts, common, relativePath, basePath; + + if (relative._parts.urn) { + throw new Error('URNs do not have any generally defined hierarchical components'); + } + + base = new URI(base).normalize(); + relativeParts = relative._parts; + baseParts = base._parts; + relativePath = relative.path(); + basePath = base.path(); + + if (relativePath.charAt(0) !== '/') { + throw new Error('URI is already relative'); + } + + if (basePath.charAt(0) !== '/') { + throw new Error('Cannot calculate a URI relative to another relative URI'); + } + + if (relativeParts.protocol === baseParts.protocol) { + relativeParts.protocol = null; + } + + if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) { + return relative.build(); + } + + if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) { + return relative.build(); + } + + if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) { + relativeParts.hostname = null; + relativeParts.port = null; + } else { + return relative.build(); + } + + if (relativePath === basePath) { + relativeParts.path = ''; + return relative.build(); + } + + // determine common sub path + common = URI.commonPath(relativePath, basePath); + + // If the paths have nothing in common, return a relative URL with the absolute path. + if (!common) { + return relative.build(); + } + + var parents = baseParts.path + .substring(common.length) + .replace(/[^\/]*$/, '') + .replace(/.*?\//g, '../'); + + relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './'; + + return relative.build(); + }; + + // comparing URIs + p.equals = function(uri) { + var one = this.clone(); + var two = new URI(uri); + var one_map = {}; + var two_map = {}; + var checked = {}; + var one_query, two_query, key; + + one.normalize(); + two.normalize(); + + // exact match + if (one.toString() === two.toString()) { + return true; + } + + // extract query string + one_query = one.query(); + two_query = two.query(); + one.query(''); + two.query(''); + + // definitely not equal if not even non-query parts match + if (one.toString() !== two.toString()) { + return false; + } + + // query parameters have the same length, even if they're permuted + if (one_query.length !== two_query.length) { + return false; + } + + one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace); + two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace); + + for (key in one_map) { + if (hasOwn.call(one_map, key)) { + if (!isArray(one_map[key])) { + if (one_map[key] !== two_map[key]) { + return false; + } + } else if (!arraysEqual(one_map[key], two_map[key])) { + return false; + } + + checked[key] = true; + } + } + + for (key in two_map) { + if (hasOwn.call(two_map, key)) { + if (!checked[key]) { + // two contains a parameter not present in one + return false; + } + } + } + + return true; + }; + + // state + p.preventInvalidHostname = function(v) { + this._parts.preventInvalidHostname = !!v; + return this; + }; + + p.duplicateQueryParameters = function(v) { + this._parts.duplicateQueryParameters = !!v; + return this; + }; + + p.escapeQuerySpace = function(v) { + this._parts.escapeQuerySpace = !!v; + return this; + }; + + return URI; +})); + + +/***/ }), + +/***/ 9127: +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * URI.js - Mutating URLs + * URI Template Support - http://tools.ietf.org/html/rfc6570 + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if ( true && module.exports) { + // Node + module.exports = factory(__webpack_require__(4193)); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4193)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +}(this, function (URI, root) { + 'use strict'; + // FIXME: v2.0.0 renamce non-camelCase properties to uppercase + /*jshint camelcase: false */ + + // save current URITemplate variable, if any + var _URITemplate = root && root.URITemplate; + + var hasOwn = Object.prototype.hasOwnProperty; + function URITemplate(expression) { + // serve from cache where possible + if (URITemplate._cache[expression]) { + return URITemplate._cache[expression]; + } + + // Allow instantiation without the 'new' keyword + if (!(this instanceof URITemplate)) { + return new URITemplate(expression); + } + + this.expression = expression; + URITemplate._cache[expression] = this; + return this; + } + + function Data(data) { + this.data = data; + this.cache = {}; + } + + var p = URITemplate.prototype; + // list of operators and their defined options + var operators = { + // Simple string expansion + '' : { + prefix: '', + separator: ',', + named: false, + empty_name_separator: false, + encode : 'encode' + }, + // Reserved character strings + '+' : { + prefix: '', + separator: ',', + named: false, + empty_name_separator: false, + encode : 'encodeReserved' + }, + // Fragment identifiers prefixed by '#' + '#' : { + prefix: '#', + separator: ',', + named: false, + empty_name_separator: false, + encode : 'encodeReserved' + }, + // Name labels or extensions prefixed by '.' + '.' : { + prefix: '.', + separator: '.', + named: false, + empty_name_separator: false, + encode : 'encode' + }, + // Path segments prefixed by '/' + '/' : { + prefix: '/', + separator: '/', + named: false, + empty_name_separator: false, + encode : 'encode' + }, + // Path parameter name or name=value pairs prefixed by ';' + ';' : { + prefix: ';', + separator: ';', + named: true, + empty_name_separator: false, + encode : 'encode' + }, + // Query component beginning with '?' and consisting + // of name=value pairs separated by '&'; an + '?' : { + prefix: '?', + separator: '&', + named: true, + empty_name_separator: true, + encode : 'encode' + }, + // Continuation of query-style &name=value pairs + // within a literal query component. + '&' : { + prefix: '&', + separator: '&', + named: true, + empty_name_separator: true, + encode : 'encode' + } + + // The operator characters equals ("="), comma (","), exclamation ("!"), + // at sign ("@"), and pipe ("|") are reserved for future extensions. + }; + + // storage for already parsed templates + URITemplate._cache = {}; + // pattern to identify expressions [operator, variable-list] in template + URITemplate.EXPRESSION_PATTERN = /\{([^a-zA-Z0-9%_]?)([^\}]+)(\}|$)/g; + // pattern to identify variables [name, explode, maxlength] in variable-list + URITemplate.VARIABLE_PATTERN = /^([^*:.](?:\.?[^*:.])*)((\*)|:(\d+))?$/; + // pattern to verify variable name integrity + URITemplate.VARIABLE_NAME_PATTERN = /[^a-zA-Z0-9%_.]/; + // pattern to verify literal integrity + URITemplate.LITERAL_PATTERN = /[<>{}"`^| \\]/; + + // expand parsed expression (expression, not template!) + URITemplate.expand = function(expression, data, opts) { + // container for defined options for the given operator + var options = operators[expression.operator]; + // expansion type (include keys or not) + var type = options.named ? 'Named' : 'Unnamed'; + // list of variables within the expression + var variables = expression.variables; + // result buffer for evaluating the expression + var buffer = []; + var d, variable, i; + + for (i = 0; (variable = variables[i]); i++) { + // fetch simplified data source + d = data.get(variable.name); + if (d.type === 0 && opts && opts.strict) { + throw new Error('Missing expansion value for variable "' + variable.name + '"'); + } + if (!d.val.length) { + if (d.type) { + // empty variables (empty string) + // still lead to a separator being appended! + buffer.push(''); + } + // no data, no action + continue; + } + + if (d.type > 1 && variable.maxlength) { + // composite variable cannot specify maxlength + throw new Error('Invalid expression: Prefix modifier not applicable to variable "' + variable.name + '"'); + } + + // expand the given variable + buffer.push(URITemplate['expand' + type]( + d, + options, + variable.explode, + variable.explode && options.separator || ',', + variable.maxlength, + variable.name + )); + } + + if (buffer.length) { + return options.prefix + buffer.join(options.separator); + } else { + // prefix is not prepended for empty expressions + return ''; + } + }; + // expand a named variable + URITemplate.expandNamed = function(d, options, explode, separator, length, name) { + // variable result buffer + var result = ''; + // peformance crap + var encode = options.encode; + var empty_name_separator = options.empty_name_separator; + // flag noting if values are already encoded + var _encode = !d[encode].length; + // key for named expansion + var _name = d.type === 2 ? '': URI[encode](name); + var _value, i, l; + + // for each found value + for (i = 0, l = d.val.length; i < l; i++) { + if (length) { + // maxlength must be determined before encoding can happen + _value = URI[encode](d.val[i][1].substring(0, length)); + if (d.type === 2) { + // apply maxlength to keys of objects as well + _name = URI[encode](d.val[i][0].substring(0, length)); + } + } else if (_encode) { + // encode value + _value = URI[encode](d.val[i][1]); + if (d.type === 2) { + // encode name and cache encoded value + _name = URI[encode](d.val[i][0]); + d[encode].push([_name, _value]); + } else { + // cache encoded value + d[encode].push([undefined, _value]); + } + } else { + // values are already encoded and can be pulled from cache + _value = d[encode][i][1]; + if (d.type === 2) { + _name = d[encode][i][0]; + } + } + + if (result) { + // unless we're the first value, prepend the separator + result += separator; + } + + if (!explode) { + if (!i) { + // first element, so prepend variable name + result += URI[encode](name) + (empty_name_separator || _value ? '=' : ''); + } + + if (d.type === 2) { + // without explode-modifier, keys of objects are returned comma-separated + result += _name + ','; + } + + result += _value; + } else { + // only add the = if it is either default (?&) or there actually is a value (;) + result += _name + (empty_name_separator || _value ? '=' : '') + _value; + } + } + + return result; + }; + // expand an unnamed variable + URITemplate.expandUnnamed = function(d, options, explode, separator, length) { + // variable result buffer + var result = ''; + // performance crap + var encode = options.encode; + var empty_name_separator = options.empty_name_separator; + // flag noting if values are already encoded + var _encode = !d[encode].length; + var _name, _value, i, l; + + // for each found value + for (i = 0, l = d.val.length; i < l; i++) { + if (length) { + // maxlength must be determined before encoding can happen + _value = URI[encode](d.val[i][1].substring(0, length)); + } else if (_encode) { + // encode and cache value + _value = URI[encode](d.val[i][1]); + d[encode].push([ + d.type === 2 ? URI[encode](d.val[i][0]) : undefined, + _value + ]); + } else { + // value already encoded, pull from cache + _value = d[encode][i][1]; + } + + if (result) { + // unless we're the first value, prepend the separator + result += separator; + } + + if (d.type === 2) { + if (length) { + // maxlength also applies to keys of objects + _name = URI[encode](d.val[i][0].substring(0, length)); + } else { + // at this point the name must already be encoded + _name = d[encode][i][0]; + } + + result += _name; + if (explode) { + // explode-modifier separates name and value by "=" + result += (empty_name_separator || _value ? '=' : ''); + } else { + // no explode-modifier separates name and value by "," + result += ','; + } + } + + result += _value; + } + + return result; + }; + + URITemplate.noConflict = function() { + if (root.URITemplate === URITemplate) { + root.URITemplate = _URITemplate; + } + + return URITemplate; + }; + + // expand template through given data map + p.expand = function(data, opts) { + var result = ''; + + if (!this.parts || !this.parts.length) { + // lazilyy parse the template + this.parse(); + } + + if (!(data instanceof Data)) { + // make given data available through the + // optimized data handling thingie + data = new Data(data); + } + + for (var i = 0, l = this.parts.length; i < l; i++) { + /*jshint laxbreak: true */ + result += typeof this.parts[i] === 'string' + // literal string + ? this.parts[i] + // expression + : URITemplate.expand(this.parts[i], data, opts); + /*jshint laxbreak: false */ + } + + return result; + }; + // parse template into action tokens + p.parse = function() { + // performance crap + var expression = this.expression; + var ePattern = URITemplate.EXPRESSION_PATTERN; + var vPattern = URITemplate.VARIABLE_PATTERN; + var nPattern = URITemplate.VARIABLE_NAME_PATTERN; + var lPattern = URITemplate.LITERAL_PATTERN; + // token result buffer + var parts = []; + // position within source template + var pos = 0; + var variables, eMatch, vMatch; + + var checkLiteral = function(literal) { + if (literal.match(lPattern)) { + throw new Error('Invalid Literal "' + literal + '"'); + } + return literal; + }; + + // RegExp is shared accross all templates, + // which requires a manual reset + ePattern.lastIndex = 0; + // I don't like while(foo = bar()) loops, + // to make things simpler I go while(true) and break when required + while (true) { + eMatch = ePattern.exec(expression); + if (eMatch === null) { + // push trailing literal + parts.push(checkLiteral(expression.substring(pos))); + break; + } else { + // push leading literal + parts.push(checkLiteral(expression.substring(pos, eMatch.index))); + pos = eMatch.index + eMatch[0].length; + } + + if (!operators[eMatch[1]]) { + throw new Error('Unknown Operator "' + eMatch[1] + '" in "' + eMatch[0] + '"'); + } else if (!eMatch[3]) { + throw new Error('Unclosed Expression "' + eMatch[0] + '"'); + } + + // parse variable-list + variables = eMatch[2].split(','); + for (var i = 0, l = variables.length; i < l; i++) { + vMatch = variables[i].match(vPattern); + if (vMatch === null) { + throw new Error('Invalid Variable "' + variables[i] + '" in "' + eMatch[0] + '"'); + } else if (vMatch[1].match(nPattern)) { + throw new Error('Invalid Variable Name "' + vMatch[1] + '" in "' + eMatch[0] + '"'); + } + + variables[i] = { + name: vMatch[1], + explode: !!vMatch[3], + maxlength: vMatch[4] && parseInt(vMatch[4], 10) + }; + } + + if (!variables.length) { + throw new Error('Expression Missing Variable(s) "' + eMatch[0] + '"'); + } + + parts.push({ + expression: eMatch[0], + operator: eMatch[1], + variables: variables + }); + } + + if (!parts.length) { + // template doesn't contain any expressions + // so it is a simple literal string + // this probably should fire a warning or something? + parts.push(checkLiteral(expression)); + } + + this.parts = parts; + return this; + }; + + // simplify data structures + Data.prototype.get = function(key) { + // performance crap + var data = this.data; + // cache for processed data-point + var d = { + // type of data 0: undefined/null, 1: string, 2: object, 3: array + type: 0, + // original values (except undefined/null) + val: [], + // cache for encoded values (only for non-maxlength expansion) + encode: [], + encodeReserved: [] + }; + var i, l, value; + + if (this.cache[key] !== undefined) { + // we've already processed this key + return this.cache[key]; + } + + this.cache[key] = d; + + if (String(Object.prototype.toString.call(data)) === '[object Function]') { + // data itself is a callback (global callback) + value = data(key); + } else if (String(Object.prototype.toString.call(data[key])) === '[object Function]') { + // data is a map of callbacks (local callback) + value = data[key](key); + } else { + // data is a map of data + value = data[key]; + } + + // generalize input into [ [name1, value1], [name2, value2], … ] + // so expansion has to deal with a single data structure only + if (value === undefined || value === null) { + // undefined and null values are to be ignored completely + return d; + } else if (String(Object.prototype.toString.call(value)) === '[object Array]') { + for (i = 0, l = value.length; i < l; i++) { + if (value[i] !== undefined && value[i] !== null) { + // arrays don't have names + d.val.push([undefined, String(value[i])]); + } + } + + if (d.val.length) { + // only treat non-empty arrays as arrays + d.type = 3; // array + } + } else if (String(Object.prototype.toString.call(value)) === '[object Object]') { + for (i in value) { + if (hasOwn.call(value, i) && value[i] !== undefined && value[i] !== null) { + // objects have keys, remember them for named expansion + d.val.push([i, String(value[i])]); + } + } + + if (d.val.length) { + // only treat non-empty objects as objects + d.type = 2; // object + } + } else { + d.type = 1; // primitive string (could've been string, number, boolean and objects with a toString()) + // arrays don't have names + d.val.push([undefined, String(value)]); + } + + return d; + }; + + // hook into URI for fluid access + URI.expand = function(expression, data) { + var template = new URITemplate(expression); + var expansion = template.expand(data); + + return new URI(expansion); + }; + + return URITemplate; +})); + + +/***/ }), + +/***/ 9340: +/***/ (function(module, exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.0 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = true && exports && + !exports.nodeType && exports; + var freeModule = true && module && + !module.nodeType && module; + var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + true + ) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { + return punycode; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} + +}(this)); + + +/***/ }), + +/***/ 1270: +/***/ (function(module, exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = true && exports && + !exports.nodeType && exports; + var freeModule = true && module && + !module.nodeType && module; + var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + true + ) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { + return punycode; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} + +}(this)); + + +/***/ }), + +/***/ 8835: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +/* + * 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. + */ + + + +var punycode = __webpack_require__(1270); + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +/* + * define these here so at least they only have to be + * compiled once on the first module load. + */ +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/, + + /* + * RFC 2396: characters reserved for delimiting URLs. + * We actually just auto-escape these. + */ + delims = [ + '<', '>', '"', '`', ' ', '\r', '\n', '\t' + ], + + // RFC 2396: characters not allowed for various reasons. + unwise = [ + '{', '}', '|', '\\', '^', '`' + ].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + /* + * Characters that are never ever allowed in a hostname. + * Note that any invalid chars are also handled, but these + * are the ones that are *expected* to be seen, so we fast-path + * them. + */ + nonHostChars = [ + '%', '/', '?', ';', '#' + ].concat(autoEscape), + hostEndingChars = [ + '/', '?', '#' + ], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + javascript: true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + javascript: true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + http: true, + https: true, + ftp: true, + gopher: true, + file: true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = __webpack_require__(5373); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && typeof url === 'object' && url instanceof Url) { return url; } + + var u = new Url(); + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) { + if (typeof url !== 'string') { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + /* + * Copy chrome, IE, opera backslash-handling behavior. + * Back slashes before the query string get converted to forward slashes + * See: https://code.google.com/p/chromium/issues/detail?id=25916 + */ + var queryIndex = url.indexOf('?'), + splitter = queryIndex !== -1 && queryIndex < url.indexOf('#') ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + /* + * trim before proceeding. + * This is to support parse stuff like " http://foo.com \n" + */ + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + /* + * figure out if it's got a host + * user@server is *always* interpreted as a hostname, and url + * resolution will treat //foo/bar as host=foo,path=bar because that's + * how the browser resolves relative URLs. + */ + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@/]+@[^@/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { + + /* + * there's a hostname. + * the first instance of /, ?, ;, or # ends the host. + * + * If there is an @ in the hostname, then non-host chars *are* allowed + * to the left of the last @ sign, unless some host-ending character + * comes *before* the @-sign. + * URLs are obnoxious. + * + * ex: + * http://a@b@c/ => user:a@b host:c + * http://a@b?@c => user:a host:c path:/?@c + */ + + /* + * v0.12 TODO(isaacs): This is not quite how Chrome does things. + * Review our test case against browsers more comprehensively. + */ + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; } + } + + /* + * at this point, either we have an explicit point where the + * auth portion cannot go past, or the last @ char is the decider. + */ + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + /* + * atSign must be in auth portion. + * http://a@b/c@d => host:b auth:a path:/c@d + */ + atSign = rest.lastIndexOf('@', hostEnd); + } + + /* + * Now we have a portion which is definitely the auth. + * Pull that off. + */ + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; } + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) { hostEnd = rest.length; } + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + /* + * we've indicated that there is a hostname, + * so even if it's empty, it has to be present. + */ + this.hostname = this.hostname || ''; + + /* + * if hostname begins with [ and ends with ] + * assume that it's an IPv6 address. + */ + var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) { continue; } + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + /* + * we replace non-ASCII char with a temporary placeholder + * we need this to make sure size of hostname is not + * broken by replacing non-ASCII by nothing + */ + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + /* + * IDNA Support: Returns a punycoded representation of "domain". + * It only converts parts of the domain name that + * have non-ASCII characters, i.e. it doesn't matter if + * you call it with a domain that already is ASCII-only. + */ + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + /* + * strip [ and ] from the hostname + * the host field still retains them, though + */ + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + /* + * now rest is set to the post-host stuff. + * chop off any delim chars. + */ + if (!unsafeProtocol[lowerProto]) { + + /* + * First, make 100% sure that any "autoEscape" chars get + * escaped, even if encodeURIComponent doesn't think they + * need to be. + */ + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) { continue; } + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) { this.pathname = rest; } + if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { + this.pathname = '/'; + } + + // to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + /* + * ensure it's an object, and not a string url. + * If it's an obj, this is a no-op. + * this way, you can call url_format() on strings + * to clean up potentially wonky urls. + */ + if (typeof obj === 'string') { obj = urlParse(obj); } + if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); } + return obj.format(); +} + +Url.prototype.format = function () { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && typeof this.query === 'object' && Object.keys(this.query).length) { + query = querystring.stringify(this.query, { + arrayFormat: 'repeat', + addQueryPrefix: false + }); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; } + + /* + * only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + * unless they had them to begin with. + */ + if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; } + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; } + if (search && search.charAt(0) !== '?') { search = '?' + search; } + + pathname = pathname.replace(/[?#]/g, function (match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function (relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) { return relative; } + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function (relative) { + if (typeof relative === 'string') { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + /* + * hash is always overridden, no matter what. + * even href="" will remove it. + */ + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') { result[rkey] = relative[rkey]; } + } + + // urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { + result.pathname = '/'; + result.path = result.pathname; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + /* + * if it's a known url protocol, then changing + * the protocol does weird things + * first, if it's not file:, then we MUST have a host, + * and if there was a path + * to begin with, then we MUST have a path. + * if it is file:, then the host is dropped, + * because that's known to be hostless. + * anything else is assumed to be absolute. + */ + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())) { } + if (!relative.host) { relative.host = ''; } + if (!relative.hostname) { relative.hostname = ''; } + if (relPath[0] !== '') { relPath.unshift(''); } + if (relPath.length < 2) { relPath.unshift(''); } + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = result.pathname && result.pathname.charAt(0) === '/', + isRelAbs = relative.host || relative.pathname && relative.pathname.charAt(0) === '/', + mustEndAbs = isRelAbs || isSourceAbs || (result.host && relative.pathname), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + /* + * if the url is a non-slashed url, then relative + * links like ../.. should be able + * to crawl up to the hostname, as well. This is strange. + * result.protocol has already been set by now. + * Later on, put the first path part into the host field. + */ + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') { srcPath[0] = result.host; } else { srcPath.unshift(result.host); } + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') { relPath[0] = relative.host; } else { relPath.unshift(relative.host); } + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = relative.host || relative.host === '' ? relative.host : result.host; + result.hostname = relative.hostname || relative.hostname === '' ? relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + /* + * it's relative + * throw away the existing file, and take the new path instead. + */ + if (!srcPath) { srcPath = []; } + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (relative.search != null) { + /* + * just pull out the search. + * like href='?foo'. + * Put this after the other two cases because it simplifies the booleans + */ + if (psychotic) { + result.host = srcPath.shift(); + result.hostname = result.host; + /* + * occationaly the auth can get stuck only in host + * this especially happens in cases like + * url.resolveObject('mailto:local1@domain1', 'local2@domain2') + */ + var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.hostname = authInHost.shift(); + result.host = result.hostname; + } + } + result.search = relative.search; + result.query = relative.query; + // to support http.request + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + /* + * no path at all. easy. + * we've already handled the other stuff above. + */ + result.pathname = null; + // to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + /* + * if a url ENDs in . or .., then it must get a trailing slash. + * however, if it ends in anything else non-slashy, + * then it must NOT get a trailing slash. + */ + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''; + + /* + * strip single dots, resolve double dots to parent dir + * if the path tries to go above the root, `up` ends up > 0 + */ + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; + result.host = result.hostname; + /* + * occationaly the auth can get stuck only in host + * this especially happens in cases like + * url.resolveObject('mailto:local1@domain1', 'local2@domain2') + */ + var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.hostname = authInHost.shift(); + result.host = result.hostname; + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (srcPath.length > 0) { + result.pathname = srcPath.join('/'); + } else { + result.pathname = null; + result.path = null; + } + + // to support request.http + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function () { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) { this.hostname = host; } +}; + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + + +/***/ }), + +/***/ 4643: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + +/** + * 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 (!__webpack_require__.g.localStorage) return false; + } catch (_) { + return false; + } + var val = __webpack_require__.g.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} + + +/***/ }), + +/***/ 1135: +/***/ ((module) => { + +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} + +/***/ }), + +/***/ 9032: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +// Currently in sync with Node.js lib/internal/util/types.js +// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 + + + +var isArgumentsObject = __webpack_require__(7244); +var isGeneratorFunction = __webpack_require__(8184); +var whichTypedArray = __webpack_require__(5767); +var isTypedArray = __webpack_require__(5680); + +function uncurryThis(f) { + return f.call.bind(f); +} + +var BigIntSupported = typeof BigInt !== 'undefined'; +var SymbolSupported = typeof Symbol !== 'undefined'; + +var ObjectToString = uncurryThis(Object.prototype.toString); + +var numberValue = uncurryThis(Number.prototype.valueOf); +var stringValue = uncurryThis(String.prototype.valueOf); +var booleanValue = uncurryThis(Boolean.prototype.valueOf); + +if (BigIntSupported) { + var bigIntValue = uncurryThis(BigInt.prototype.valueOf); +} + +if (SymbolSupported) { + var symbolValue = uncurryThis(Symbol.prototype.valueOf); +} + +function checkBoxedPrimitive(value, prototypeValueOf) { + if (typeof value !== 'object') { + return false; + } + try { + prototypeValueOf(value); + return true; + } catch(e) { + return false; + } +} + +exports.isArgumentsObject = isArgumentsObject; +exports.isGeneratorFunction = isGeneratorFunction; +exports.isTypedArray = isTypedArray; + +// Taken from here and modified for better browser support +// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js +function isPromise(input) { + return ( + ( + typeof Promise !== 'undefined' && + input instanceof Promise + ) || + ( + input !== null && + typeof input === 'object' && + typeof input.then === 'function' && + typeof input.catch === 'function' + ) + ); +} +exports.isPromise = isPromise; + +function isArrayBufferView(value) { + if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { + return ArrayBuffer.isView(value); + } + + return ( + isTypedArray(value) || + isDataView(value) + ); +} +exports.isArrayBufferView = isArrayBufferView; + + +function isUint8Array(value) { + return whichTypedArray(value) === 'Uint8Array'; +} +exports.isUint8Array = isUint8Array; + +function isUint8ClampedArray(value) { + return whichTypedArray(value) === 'Uint8ClampedArray'; +} +exports.isUint8ClampedArray = isUint8ClampedArray; + +function isUint16Array(value) { + return whichTypedArray(value) === 'Uint16Array'; +} +exports.isUint16Array = isUint16Array; + +function isUint32Array(value) { + return whichTypedArray(value) === 'Uint32Array'; +} +exports.isUint32Array = isUint32Array; + +function isInt8Array(value) { + return whichTypedArray(value) === 'Int8Array'; +} +exports.isInt8Array = isInt8Array; + +function isInt16Array(value) { + return whichTypedArray(value) === 'Int16Array'; +} +exports.isInt16Array = isInt16Array; + +function isInt32Array(value) { + return whichTypedArray(value) === 'Int32Array'; +} +exports.isInt32Array = isInt32Array; + +function isFloat32Array(value) { + return whichTypedArray(value) === 'Float32Array'; +} +exports.isFloat32Array = isFloat32Array; + +function isFloat64Array(value) { + return whichTypedArray(value) === 'Float64Array'; +} +exports.isFloat64Array = isFloat64Array; + +function isBigInt64Array(value) { + return whichTypedArray(value) === 'BigInt64Array'; +} +exports.isBigInt64Array = isBigInt64Array; + +function isBigUint64Array(value) { + return whichTypedArray(value) === 'BigUint64Array'; +} +exports.isBigUint64Array = isBigUint64Array; + +function isMapToString(value) { + return ObjectToString(value) === '[object Map]'; +} +isMapToString.working = ( + typeof Map !== 'undefined' && + isMapToString(new Map()) +); + +function isMap(value) { + if (typeof Map === 'undefined') { + return false; + } + + return isMapToString.working + ? isMapToString(value) + : value instanceof Map; +} +exports.isMap = isMap; + +function isSetToString(value) { + return ObjectToString(value) === '[object Set]'; +} +isSetToString.working = ( + typeof Set !== 'undefined' && + isSetToString(new Set()) +); +function isSet(value) { + if (typeof Set === 'undefined') { + return false; + } + + return isSetToString.working + ? isSetToString(value) + : value instanceof Set; +} +exports.isSet = isSet; + +function isWeakMapToString(value) { + return ObjectToString(value) === '[object WeakMap]'; +} +isWeakMapToString.working = ( + typeof WeakMap !== 'undefined' && + isWeakMapToString(new WeakMap()) +); +function isWeakMap(value) { + if (typeof WeakMap === 'undefined') { + return false; + } + + return isWeakMapToString.working + ? isWeakMapToString(value) + : value instanceof WeakMap; +} +exports.isWeakMap = isWeakMap; + +function isWeakSetToString(value) { + return ObjectToString(value) === '[object WeakSet]'; +} +isWeakSetToString.working = ( + typeof WeakSet !== 'undefined' && + isWeakSetToString(new WeakSet()) +); +function isWeakSet(value) { + return isWeakSetToString(value); +} +exports.isWeakSet = isWeakSet; + +function isArrayBufferToString(value) { + return ObjectToString(value) === '[object ArrayBuffer]'; +} +isArrayBufferToString.working = ( + typeof ArrayBuffer !== 'undefined' && + isArrayBufferToString(new ArrayBuffer()) +); +function isArrayBuffer(value) { + if (typeof ArrayBuffer === 'undefined') { + return false; + } + + return isArrayBufferToString.working + ? isArrayBufferToString(value) + : value instanceof ArrayBuffer; +} +exports.isArrayBuffer = isArrayBuffer; + +function isDataViewToString(value) { + return ObjectToString(value) === '[object DataView]'; +} +isDataViewToString.working = ( + typeof ArrayBuffer !== 'undefined' && + typeof DataView !== 'undefined' && + isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) +); +function isDataView(value) { + if (typeof DataView === 'undefined') { + return false; + } + + return isDataViewToString.working + ? isDataViewToString(value) + : value instanceof DataView; +} +exports.isDataView = isDataView; + +// Store a copy of SharedArrayBuffer in case it's deleted elsewhere +var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; +function isSharedArrayBufferToString(value) { + return ObjectToString(value) === '[object SharedArrayBuffer]'; +} +function isSharedArrayBuffer(value) { + if (typeof SharedArrayBufferCopy === 'undefined') { + return false; + } + + if (typeof isSharedArrayBufferToString.working === 'undefined') { + isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); + } + + return isSharedArrayBufferToString.working + ? isSharedArrayBufferToString(value) + : value instanceof SharedArrayBufferCopy; +} +exports.isSharedArrayBuffer = isSharedArrayBuffer; + +function isAsyncFunction(value) { + return ObjectToString(value) === '[object AsyncFunction]'; +} +exports.isAsyncFunction = isAsyncFunction; + +function isMapIterator(value) { + return ObjectToString(value) === '[object Map Iterator]'; +} +exports.isMapIterator = isMapIterator; + +function isSetIterator(value) { + return ObjectToString(value) === '[object Set Iterator]'; +} +exports.isSetIterator = isSetIterator; + +function isGeneratorObject(value) { + return ObjectToString(value) === '[object Generator]'; +} +exports.isGeneratorObject = isGeneratorObject; + +function isWebAssemblyCompiledModule(value) { + return ObjectToString(value) === '[object WebAssembly.Module]'; +} +exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; + +function isNumberObject(value) { + return checkBoxedPrimitive(value, numberValue); +} +exports.isNumberObject = isNumberObject; + +function isStringObject(value) { + return checkBoxedPrimitive(value, stringValue); +} +exports.isStringObject = isStringObject; + +function isBooleanObject(value) { + return checkBoxedPrimitive(value, booleanValue); +} +exports.isBooleanObject = isBooleanObject; + +function isBigIntObject(value) { + return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); +} +exports.isBigIntObject = isBigIntObject; + +function isSymbolObject(value) { + return SymbolSupported && checkBoxedPrimitive(value, symbolValue); +} +exports.isSymbolObject = isSymbolObject; + +function isBoxedPrimitive(value) { + return ( + isNumberObject(value) || + isStringObject(value) || + isBooleanObject(value) || + isBigIntObject(value) || + isSymbolObject(value) + ); +} +exports.isBoxedPrimitive = isBoxedPrimitive; + +function isAnyArrayBuffer(value) { + return typeof Uint8Array !== 'undefined' && ( + isArrayBuffer(value) || + isSharedArrayBuffer(value) + ); +} +exports.isAnyArrayBuffer = isAnyArrayBuffer; + +['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { + Object.defineProperty(exports, method, { + enumerable: false, + value: function() { + throw new Error(method + ' is not supported in userland'); + } + }); +}); + + +/***/ }), + +/***/ 537: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +// 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. + +var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || + function getOwnPropertyDescriptors(obj) { + var keys = Object.keys(obj); + var descriptors = {}; + for (var i = 0; i < keys.length; i++) { + descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); + } + return descriptors; + }; + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + if (typeof process !== 'undefined' && process.noDeprecation === true) { + return fn; + } + + // Allow for deprecating things in the process of starting up. + if (typeof process === 'undefined') { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnvRegex = /^$/; + +if (process.env.NODE_DEBUG) { + var debugEnv = process.env.NODE_DEBUG; + debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/,/g, '$|^') + .toUpperCase(); + debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); +} +exports.debuglog = function(set) { + set = set.toUpperCase(); + if (!debugs[set]) { + if (debugEnvRegex.test(set)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').slice(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.slice(1, -1); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +exports.types = __webpack_require__(9032); + +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; +exports.types.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; +exports.types.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; +exports.types.isNativeError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = __webpack_require__(1135); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = __webpack_require__(6698); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; + +exports.promisify = function promisify(original) { + if (typeof original !== 'function') + throw new TypeError('The "original" argument must be of type Function'); + + if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { + var fn = original[kCustomPromisifiedSymbol]; + if (typeof fn !== 'function') { + throw new TypeError('The "util.promisify.custom" argument must be of type Function'); + } + Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return fn; + } + + function fn() { + var promiseResolve, promiseReject; + var promise = new Promise(function (resolve, reject) { + promiseResolve = resolve; + promiseReject = reject; + }); + + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + args.push(function (err, value) { + if (err) { + promiseReject(err); + } else { + promiseResolve(value); + } + }); + + try { + original.apply(this, args); + } catch (err) { + promiseReject(err); + } + + return promise; + } + + Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); + + if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return Object.defineProperties( + fn, + getOwnPropertyDescriptors(original) + ); +} + +exports.promisify.custom = kCustomPromisifiedSymbol + +function callbackifyOnRejected(reason, cb) { + // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). + // Because `null` is a special error value in callbacks which means "no error + // occurred", we error-wrap so the callback consumer can distinguish between + // "the promise rejected with null" or "the promise fulfilled with undefined". + if (!reason) { + var newReason = new Error('Promise was rejected with a falsy value'); + newReason.reason = reason; + reason = newReason; + } + return cb(reason); +} + +function callbackify(original) { + if (typeof original !== 'function') { + throw new TypeError('The "original" argument must be of type Function'); + } + + // We DO NOT return the promise as it gives the user a false sense that + // the promise is actually somehow related to the callback's execution + // and that the callback throwing will reject the promise. + function callbackified() { + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + + var maybeCb = args.pop(); + if (typeof maybeCb !== 'function') { + throw new TypeError('The last argument must be of type Function'); + } + var self = this; + var cb = function() { + return maybeCb.apply(self, arguments); + }; + // In true node style we process the callback on `nextTick` with all the + // implications (stack, `uncaughtException`, `async_hooks`) + original.apply(this, args) + .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, + function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); + } + + Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); + Object.defineProperties(callbackified, + getOwnPropertyDescriptors(original)); + return callbackified; +} +exports.callbackify = callbackify; + + +/***/ }), + +/***/ 5767: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var forEach = __webpack_require__(2682); +var availableTypedArrays = __webpack_require__(9209); +var callBind = __webpack_require__(487); +var callBound = __webpack_require__(8075); +var gOPD = __webpack_require__(5795); + +/** @type {(O: object) => string} */ +var $toString = callBound('Object.prototype.toString'); +var hasToStringTag = __webpack_require__(9092)(); + +var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; +var typedArrays = availableTypedArrays(); + +var $slice = callBound('String.prototype.slice'); +var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); + +/** @type {(array: readonly T[], value: unknown) => number} */ +var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { + for (var i = 0; i < array.length; i += 1) { + if (array[i] === value) { + return i; + } + } + return -1; +}; + +/** @typedef {(receiver: import('.').TypedArray) => string | typeof Uint8Array.prototype.slice.call | typeof Uint8Array.prototype.set.call} Getter */ +/** @type {{ [k in `\$${import('.').TypedArrayName}`]?: Getter } & { __proto__: null }} */ +var cache = { __proto__: null }; +if (hasToStringTag && gOPD && getPrototypeOf) { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + if (Symbol.toStringTag in arr) { + var proto = getPrototypeOf(arr); + // @ts-expect-error TS won't narrow inside a closure + var descriptor = gOPD(proto, Symbol.toStringTag); + if (!descriptor) { + var superProto = getPrototypeOf(proto); + // @ts-expect-error TS won't narrow inside a closure + descriptor = gOPD(superProto, Symbol.toStringTag); + } + // @ts-expect-error TODO: fix + cache['$' + typedArray] = callBind(descriptor.get); + } + }); +} else { + forEach(typedArrays, function (typedArray) { + var arr = new g[typedArray](); + var fn = arr.slice || arr.set; + if (fn) { + // @ts-expect-error TODO: fix + cache['$' + typedArray] = callBind(fn); + } + }); +} + +/** @type {(value: object) => false | import('.').TypedArrayName} */ +var tryTypedArrays = function tryAllTypedArrays(value) { + /** @type {ReturnType} */ var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), + /** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */ + function (getter, typedArray) { + if (!found) { + try { + // @ts-expect-error TODO: fix + if ('$' + getter(value) === typedArray) { + found = $slice(typedArray, 1); + } + } catch (e) { /**/ } + } + } + ); + return found; +}; + +/** @type {(value: object) => false | import('.').TypedArrayName} */ +var trySlices = function tryAllSlices(value) { + /** @type {ReturnType} */ var found = false; + forEach( + // eslint-disable-next-line no-extra-parens + /** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache), + /** @type {(getter: typeof cache, name: `\$${import('.').TypedArrayName}`) => void} */ function (getter, name) { + if (!found) { + try { + // @ts-expect-error TODO: fix + getter(value); + found = $slice(name, 1); + } catch (e) { /**/ } + } + } + ); + return found; +}; + +/** @type {import('.')} */ +module.exports = function whichTypedArray(value) { + if (!value || typeof value !== 'object') { return false; } + if (!hasToStringTag) { + /** @type {string} */ + var tag = $slice($toString(value), 8, -1); + if ($indexOf(typedArrays, tag) > -1) { + return tag; + } + if (tag !== 'Object') { + return false; + } + // node < 0.6 hits here on real Typed Arrays + return trySlices(value); + } + if (!gOPD) { return null; } // unknown engine + return tryTypedArrays(value); +}; + + +/***/ }), + +/***/ 7510: +/***/ ((module) => { + +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} + + +/***/ }), + +/***/ 2894: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 2634: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 5340: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 9838: +/***/ (() => { + +/* (ignored) */ + +/***/ }), + +/***/ 9209: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var possibleNames = __webpack_require__(6578); + +var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; + +/** @type {import('.')} */ +module.exports = function availableTypedArrays() { + var /** @type {ReturnType} */ out = []; + for (var i = 0; i < possibleNames.length; i++) { + if (typeof g[possibleNames[i]] === 'function') { + // @ts-expect-error + out[out.length] = possibleNames[i]; + } + } + return out; +}; + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat get default export */ +/******/ (() => { +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = (module) => { +/******/ var getter = module && module.__esModule ? +/******/ () => (module['default']) : +/******/ () => (module); +/******/ __webpack_require__.d(getter, { a: getter }); +/******/ return getter; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __webpack_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/global */ +/******/ (() => { +/******/ __webpack_require__.g = (function() { +/******/ if (typeof globalThis === 'object') return globalThis; +/******/ try { +/******/ return this || new Function('return this')(); +/******/ } catch (e) { +/******/ if (typeof window === 'object') return window; +/******/ } +/******/ })(); +/******/ })(); +/******/ +/******/ /* webpack/runtime/harmony module decorator */ +/******/ (() => { +/******/ __webpack_require__.hmd = (module) => { +/******/ module = Object.create(module); +/******/ if (!module.children) module.children = []; +/******/ Object.defineProperty(module, 'exports', { +/******/ enumerable: true, +/******/ set: () => { +/******/ throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id); +/******/ } +/******/ }); +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __webpack_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/node module decorator */ +/******/ (() => { +/******/ __webpack_require__.nmd = (module) => { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/************************************************************************/ +/******/ +/******/ // startup +/******/ // Load entry module and return exports +/******/ // This entry module is referenced by other modules so it can't be inlined +/******/ var __webpack_exports__ = __webpack_require__(1924); +/******/ +/******/ return __webpack_exports__; +/******/ })() +; +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/dist/stellar-sdk.min.js b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk.min.js new file mode 100644 index 000000000..e7d1b26c7 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk.min.js @@ -0,0 +1,2 @@ +/*! For license information please see stellar-sdk.min.js.LICENSE.txt */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("StellarSdk",[],t):"object"==typeof exports?exports.StellarSdk=t():e.StellarSdk=t()}(self,(()=>(()=>{var e={3740:function(e){var t;t=()=>(()=>{var e={616:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(287);n.hp.alloc(1).subarray(0,1)instanceof n.hp||(n.hp.prototype.subarray=function(e,t){const r=Uint8Array.prototype.subarray.call(this,e,t);return Object.setPrototypeOf(r,n.hp.prototype),r});const o=n.hp},281:(e,t,r)=>{const n=r(164);e.exports=n},164:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Array:()=>F,Bool:()=>I,Double:()=>j,Enum:()=>H,Float:()=>R,Hyper:()=>O,Int:()=>E,LargeInt:()=>T,Opaque:()=>U,Option:()=>q,Quadruple:()=>C,Reference:()=>z,String:()=>B,Struct:()=>X,Union:()=>W,UnsignedHyper:()=>P,UnsignedInt:()=>A,VarArray:()=>V,VarOpaque:()=>D,Void:()=>K,XdrReader:()=>u,XdrWriter:()=>f,config:()=>ne});class n extends TypeError{constructor(e){super(`XDR Write Error: ${e}`)}}class o extends TypeError{constructor(e){super(`XDR Read Error: ${e}`)}}class i extends TypeError{constructor(e){super(`XDR Type Definition Error: ${e}`)}}class a extends i{constructor(){super("method not implemented, it should be overloaded in the descendant class.")}}var s=r(616).A;class u{constructor(e){if(!s.isBuffer(e)){if(!(e instanceof Array||Array.isArray(e)||ArrayBuffer.isView(e)))throw new o(`source invalid: ${e}`);e=s.from(e)}this._buffer=e,this._length=e.length,this._index=0}_buffer;_length;_index;get eof(){return this._index===this._length}advance(e){const t=this._index;if(this._index+=e,this._length0){for(let e=0;e0){const e=this.alloc(r);this._buffer.fill(0,e,this._index)}}writeInt32BE(e){const t=this.alloc(4);this._buffer.writeInt32BE(e,t)}writeUInt32BE(e){const t=this.alloc(4);this._buffer.writeUInt32BE(e,t)}writeBigInt64BE(e){const t=this.alloc(8);this._buffer.writeBigInt64BE(e,t)}writeBigUInt64BE(e){const t=this.alloc(8);this._buffer.writeBigUInt64BE(e,t)}writeFloatBE(e){const t=this.alloc(4);this._buffer.writeFloatBE(e,t)}writeDoubleBE(e){const t=this.alloc(8);this._buffer.writeDoubleBE(e,t)}static bufferChunkSize=l}var p=r(616).A;class d{toXDR(e="raw"){if(!this.write)return this.constructor.toXDR(this,e);const t=new f;return this.write(this,t),v(t.finalize(),e)}fromXDR(e,t="raw"){if(!this.read)return this.constructor.fromXDR(e,t);const r=new u(g(e,t)),n=this.read(r);return r.ensureInputConsumed(),n}validateXDR(e,t="raw"){try{return this.fromXDR(e,t),!0}catch(e){return!1}}static toXDR(e,t="raw"){const r=new f;return this.write(e,r),v(r.finalize(),t)}static fromXDR(e,t="raw"){const r=new u(g(e,t)),n=this.read(r);return r.ensureInputConsumed(),n}static validateXDR(e,t="raw"){try{return this.fromXDR(e,t),!0}catch(e){return!1}}}class h extends d{static read(e){throw new a}static write(e,t){throw new a}static isValid(e){return!1}}class y extends d{isValid(e){return!1}}class m extends TypeError{constructor(e){super(`Invalid format ${e}, must be one of "raw", "hex", "base64"`)}}function v(e,t){switch(t){case"raw":return e;case"hex":return e.toString("hex");case"base64":return e.toString("base64");default:throw new m(t)}}function g(e,t){switch(t){case"raw":return e;case"hex":return p.from(e,"hex");case"base64":return p.from(e,"base64");default:throw new m(t)}}function b(e,t){return null!=e&&(e instanceof t||w(e,t)&&"function"==typeof e.constructor.read&&"function"==typeof e.constructor.write&&w(e,"XdrType"))}function w(e,t){do{if(e.constructor.name===t)return!0}while(e=Object.getPrototypeOf(e));return!1}const S=2147483647;class E extends h{static read(e){return e.readInt32BE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");if((0|e)!==e)throw new n("invalid i32 value");t.writeInt32BE(e)}static isValid(e){return"number"==typeof e&&(0|e)===e&&e>=-2147483648&&e<=S}}function _(e,t,r){if("bigint"!=typeof e)throw new TypeError("Expected bigint 'value', got "+typeof e);const n=t/r;if(1===n)return[e];if(r<32||r>128||2!==n&&4!==n&&8!==n)throw new TypeError(`invalid bigint (${e}) and slice size (${t} -> ${r}) combination`);const o=BigInt(r),i=new Array(n);for(let t=0;t>=o;return i}function k(e,t){if(t)return[0n,(1n<=i&&o<=a)return o;throw new TypeError(`bigint values [${e}] for ${function(e,t){return`${t?"u":"i"}${e}`}(t,r)} out of range [${i}, ${a}]: ${o}`)}(e,this.size,this.unsigned)}get unsigned(){throw new a}get size(){throw new a}slice(e){return _(this._value,this.size,e)}toString(){return this._value.toString()}toJSON(){return{_value:this._value.toString()}}toBigInt(){return BigInt(this._value)}static read(e){const{size:t}=this.prototype;return 64===t?new this(e.readBigUInt64BE()):new this(...Array.from({length:t/64},(()=>e.readBigUInt64BE())).reverse())}static write(e,t){if(e instanceof this)e=e._value;else if("bigint"!=typeof e||e>this.MAX_VALUE||e>32n)}get size(){return 64}get unsigned(){return!1}static fromBits(e,t){return new this(e,t)}}O.defineIntBoundaries();const x=4294967295;class A extends h{static read(e){return e.readUInt32BE()}static write(e,t){if("number"!=typeof e||!(e>=0&&e<=x)||e%1!=0)throw new n("invalid u32 value");t.writeUInt32BE(e)}static isValid(e){return"number"==typeof e&&e%1==0&&e>=0&&e<=x}}A.MAX_VALUE=x,A.MIN_VALUE=0;class P extends T{constructor(...e){super(e)}get low(){return 0|Number(0xffffffffn&this._value)}get high(){return 0|Number(this._value>>32n)}get size(){return 64}get unsigned(){return!0}static fromBits(e,t){return new this(e,t)}}P.defineIntBoundaries();class R extends h{static read(e){return e.readFloatBE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");t.writeFloatBE(e)}static isValid(e){return"number"==typeof e}}class j extends h{static read(e){return e.readDoubleBE()}static write(e,t){if("number"!=typeof e)throw new n("not a number");t.writeDoubleBE(e)}static isValid(e){return"number"==typeof e}}class C extends h{static read(){throw new i("quadruple not supported")}static write(){throw new i("quadruple not supported")}static isValid(){return!1}}class I extends h{static read(e){const t=E.read(e);switch(t){case 0:return!1;case 1:return!0;default:throw new o(`got ${t} when trying to read a bool`)}}static write(e,t){const r=e?1:0;E.write(r,t)}static isValid(e){return"boolean"==typeof e}}var L=r(616).A;class B extends y{constructor(e=A.MAX_VALUE){super(),this._maxLength=e}read(e){const t=A.read(e);if(t>this._maxLength)throw new o(`saw ${t} length String, max allowed is ${this._maxLength}`);return e.read(t)}readString(e){return this.read(e).toString("utf8")}write(e,t){const r="string"==typeof e?L.byteLength(e,"utf8"):e.length;if(r>this._maxLength)throw new n(`got ${e.length} bytes, max allowed is ${this._maxLength}`);A.write(r,t),t.write(e,r)}isValid(e){return"string"==typeof e?L.byteLength(e,"utf8")<=this._maxLength:!!(e instanceof Array||L.isBuffer(e))&&e.length<=this._maxLength}}var N=r(616).A;class U extends y{constructor(e){super(),this._length=e}read(e){return e.read(this._length)}write(e,t){const{length:r}=e;if(r!==this._length)throw new n(`got ${e.length} bytes, expected ${this._length}`);t.write(e,r)}isValid(e){return N.isBuffer(e)&&e.length===this._length}}var M=r(616).A;class D extends y{constructor(e=A.MAX_VALUE){super(),this._maxLength=e}read(e){const t=A.read(e);if(t>this._maxLength)throw new o(`saw ${t} length VarOpaque, max allowed is ${this._maxLength}`);return e.read(t)}write(e,t){const{length:r}=e;if(e.length>this._maxLength)throw new n(`got ${e.length} bytes, max allowed is ${this._maxLength}`);A.write(r,t),t.write(e,r)}isValid(e){return M.isBuffer(e)&&e.length<=this._maxLength}}class F extends y{constructor(e,t){super(),this._childType=e,this._length=t}read(e){const t=new r.g.Array(this._length);for(let r=0;rthis._maxLength)throw new o(`saw ${t} length VarArray, max allowed is ${this._maxLength}`);const r=new Array(t);for(let n=0;nthis._maxLength)throw new n(`got array of size ${e.length}, max allowed is ${this._maxLength}`);A.write(e.length,t);for(const r of e)this._childType.write(r,t)}isValid(e){if(!(e instanceof Array)||e.length>this._maxLength)return!1;for(const t of e)if(!this._childType.isValid(t))return!1;return!0}}class q extends h{constructor(e){super(),this._childType=e}read(e){if(I.read(e))return this._childType.read(e)}write(e,t){const r=null!=e;I.write(r,t),r&&this._childType.write(e,t)}isValid(e){return null==e||this._childType.isValid(e)}}class K extends h{static read(){}static write(e){if(void 0!==e)throw new n("trying to write value to a void slot")}static isValid(e){return void 0===e}}class H extends h{constructor(e,t){super(),this.name=e,this.value=t}static read(e){const t=E.read(e),r=this._byValue[t];if(void 0===r)throw new o(`unknown ${this.enumName} member for value ${t}`);return r}static write(e,t){if(!this.isValid(e))throw new n(`${e} has enum name ${e?.enumName}, not ${this.enumName}: ${JSON.stringify(e)}`);E.write(e.value,t)}static isValid(e){return e?.constructor?.enumName===this.enumName||b(e,this)}static members(){return this._members}static values(){return Object.values(this._members)}static fromName(e){const t=this._members[e];if(!t)throw new TypeError(`${e} is not a member of ${this.enumName}`);return t}static fromValue(e){const t=this._byValue[e];if(void 0===t)throw new TypeError(`${e} is not a value of any member of ${this.enumName}`);return t}static create(e,t,r){const n=class extends H{};n.enumName=t,e.results[t]=n,n._members={},n._byValue={};for(const[e,t]of Object.entries(r)){const r=new n(e,t);n._members[e]=r,n._byValue[t]=r,n[e]=()=>r}return n}}class z extends h{resolve(){throw new i('"resolve" method should be implemented in the descendant class')}}class X extends y{constructor(e){super(),this._attributes=e||{}}static read(e){const t={};for(const[r,n]of this._fields)t[r]=n.read(e);return new this(t)}static write(e,t){if(!this.isValid(e))throw new n(`${e} has struct name ${e?.constructor?.structName}, not ${this.structName}: ${JSON.stringify(e)}`);for(const[r,n]of this._fields){const o=e._attributes[r];n.write(o,t)}}static isValid(e){return e?.constructor?.structName===this.structName||b(e,this)}static create(e,t,r){const n=class extends X{};n.structName=t,e.results[t]=n;const o=new Array(r.length);for(let t=0;t{"use strict";t.byteLength=function(e){var t=s(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,i=s(e),a=i[0],u=i[1],c=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,u)),l=0,f=u>0?a-4:a;for(r=0;r>16&255,c[l++]=t>>8&255,c[l++]=255&t;return 2===u&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,c[l++]=255&t),1===u&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t),c},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],a=16383,s=0,c=n-o;sc?c:s+a));return 1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),i.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)r[a]=i[a],n[i.charCodeAt(a)]=a;function s(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,n){for(var o,i,a=[],s=t;s>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return a.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},287:(e,t,r)=>{"use strict";const n=r(526),o=r(251),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=u,t.IS=50;const a=2147483647;function s(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,u.prototype),t}function u(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return f(e)}return c(e,t,r)}function c(e,t,r){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!u.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|y(e,t);let n=s(r);const o=n.write(e,t);return o!==r&&(n=n.slice(0,o)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if($(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return p(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if($(e,ArrayBuffer)||e&&$(e.buffer,ArrayBuffer))return d(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&($(e,SharedArrayBuffer)||e&&$(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return u.from(n,t,r);const o=function(e){if(u.isBuffer(e)){const t=0|h(e.length),r=s(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||Q(e.length)?s(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return u.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function f(e){return l(e),s(e<0?0:0|h(e))}function p(e){const t=e.length<0?0:0|h(e.length),r=s(t);for(let n=0;n=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function y(e,t){if(u.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||$(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return X(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(o)return n?-1:X(e).length;t=(""+t).toLowerCase(),o=!0}}function m(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return R(this,t,r);case"utf8":case"utf-8":return O(this,t,r);case"ascii":return A(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return T(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function v(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function g(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Q(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,o){let i,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){let n=-1;for(i=r;is&&(r=s-u),i=r;i>=0;i--){let r=!0;for(let n=0;no&&(n=o):n=o;const i=t.length;let a;for(n>i/2&&(n=i/2),a=0;a>8,o=r%256,i.push(o),i.push(n);return i}(t,e.length-r),e,r,n)}function T(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function O(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o239?4:t>223?3:t>191?2:1;if(o+a<=r){let r,n,s,u;switch(a){case 1:t<128&&(i=t);break;case 2:r=e[o+1],128==(192&r)&&(u=(31&t)<<6|63&r,u>127&&(i=u));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(u=(15&t)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:r=e[o+1],n=e[o+2],s=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(u=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,u>65535&&u<1114112&&(i=u))}}null===i?(i=65533,a=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),o+=a}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(u.isBuffer(t)||(t=u.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!u.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},u.byteLength=y,u.prototype._isBuffer=!0,u.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(e+=" ... "),""},i&&(u.prototype[i]=u.prototype.inspect),u.prototype.compare=function(e,t,r,n,o){if($(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let i=(o>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0);const s=Math.min(i,a),c=this.slice(n,o),l=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let i=!1;for(;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":case"latin1":case"binary":return E(this,e,t,r);case"base64":return _(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function A(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;on)&&(r=n);let o="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function I(e,t,r,n,o,i){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function L(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function B(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r+7]=i,i>>=8,e[r+6]=i,i>>=8,e[r+5]=i,i>>=8,e[r+4]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function N(e,t,r,n,o,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function M(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,8),o.write(e,t,r,n,52,8),r+8}u.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e+--t],o=1;for(;t>0&&(o*=256);)n+=this[e+--t]*o;return n},u.prototype.readUint8=u.prototype.readUInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(o)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i=o&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=t,o=1,i=this[e+--n];for(;n>0&&(o*=256);)i+=this[e+--n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},u.prototype.readInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||C(e,4,this.length),o.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||C(e,4,this.length),o.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||C(e,8,this.length),o.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||C(e,8,this.length),o.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||I(this,e,t,r,Math.pow(2,8*r)-1,0);let o=1,i=0;for(this[t]=255&e;++i>>=0,r>>>=0,n||I(this,e,t,r,Math.pow(2,8*r)-1,0);let o=r-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigUInt64LE=J((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeBigUInt64BE=J((function(e,t=0){return B(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);I(this,e,t,r,n-1,-n)}let o=0,i=1,a=0;for(this[t]=255&e;++o>>=0,!n){const n=Math.pow(2,8*r-1);I(this,e,t,r,n-1,-n)}let o=r-1,i=1,a=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/i|0)-a&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigInt64LE=J((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeBigInt64BE=J((function(e,t=0){return B(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return M(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return M(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function q(e,t,r,n,o,i){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new D.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){K(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||H(t,e.length-(r+1))}(n,o,i)}function K(e,t){if("number"!=typeof e)throw new D.ERR_INVALID_ARG_TYPE(t,"number",e)}function H(e,t,r){if(Math.floor(e)!==e)throw K(e,r),new D.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new D.ERR_BUFFER_OUT_OF_BOUNDS;throw new D.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}F("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),F("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),F("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=V(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=V(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const z=/[^+/0-9A-Za-z-_]/g;function X(e,t){let r;t=t||1/0;const n=e.length;let o=null;const i=[];for(let a=0;a55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function G(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function W(e,t,r,n){let o;for(o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function $(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Q(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let o=0;o<16;++o)t[n+o]=e[r]+e[o]}return t}();function J(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},251:(e,t)=>{t.read=function(e,t,r,n,o){var i,a,s=8*o-n-1,u=(1<>1,l=-7,f=r?o-1:0,p=r?-1:1,d=e[t+f];for(f+=p,i=d&(1<<-l)-1,d>>=-l,l+=s;l>0;i=256*i+e[t+f],f+=p,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=p,l-=8);if(0===i)i=1-c;else{if(i===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),i-=c}return(d?-1:1)*a*Math.pow(2,i-n)},t.write=function(e,t,r,n,o,i){var a,s,u,c=8*i-o-1,l=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,h=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?p/u:p*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=l?(s=0,a=l):a+f>=1?(s=(t*u-1)*Math.pow(2,o),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,o),a=0));o>=8;e[r+d]=255&s,d+=h,s/=256,o-=8);for(a=a<0;e[r+d]=255&a,d+=h,a/=256,c-=8);e[r+d-h]|=128*y}}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}return r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r(281)})(),e.exports=t()},2135:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Account=void 0;var n,o=(n=r(1242))&&n.__esModule?n:{default:n},i=r(7120);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function s(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Address=void 0;var n,o=r(7120),i=(n=r(1918))&&n.__esModule?n:{default:n};function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function s(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.Asset=void 0;var o,i=r(645),a=(o=r(1918))&&o.__esModule?o:{default:o},s=r(6691),u=r(7120),c=r(9152);function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:a.default.Asset;if(this.isNative())return r.assetTypeNative();this.code.length<=4?(e=a.default.AlphaNum4,t="assetTypeCreditAlphanum4"):(e=a.default.AlphaNum12,t="assetTypeCreditAlphanum12");var n=this.code.length<=4?4:12;return new r(t,new e({assetCode:this.code.padEnd(n,"\0"),issuer:s.Keypair.fromPublicKey(this.issuer).xdrAccountId()}))}},{key:"getCode",value:function(){if(void 0!==this.code)return String(this.code)}},{key:"getIssuer",value:function(){if(void 0!==this.issuer)return String(this.issuer)}},{key:"getAssetType",value:function(){switch(this.getRawAssetType().value){case a.default.AssetType.assetTypeNative().value:return"native";case a.default.AssetType.assetTypeCreditAlphanum4().value:return"credit_alphanum4";case a.default.AssetType.assetTypeCreditAlphanum12().value:return"credit_alphanum12";default:return"unknown"}}},{key:"getRawAssetType",value:function(){return this.isNative()?a.default.AssetType.assetTypeNative():this.code.length<=4?a.default.AssetType.assetTypeCreditAlphanum4():a.default.AssetType.assetTypeCreditAlphanum12()}},{key:"isNative",value:function(){return!this.issuer}},{key:"equals",value:function(e){return this.code===e.getCode()&&this.issuer===e.getIssuer()}},{key:"toString",value:function(){return this.isNative()?"native":"".concat(this.getCode(),":").concat(this.getIssuer())}}],[{key:"native",value:function(){return new e("XLM")}},{key:"fromOperation",value:function(e){var t,r;switch(e.switch()){case a.default.AssetType.assetTypeNative():return this.native();case a.default.AssetType.assetTypeCreditAlphanum4():t=e.alphaNum4();case a.default.AssetType.assetTypeCreditAlphanum12():return t=t||e.alphaNum12(),r=u.StrKey.encodeEd25519PublicKey(t.issuer().ed25519()),new this((0,i.trimEnd)(t.assetCode(),"\0"),r);default:throw new Error("Invalid asset type: ".concat(e.switch().name))}}},{key:"compare",value:function(t,r){if(!(t&&t instanceof e))throw new Error("assetA is invalid");if(!(r&&r instanceof e))throw new Error("assetB is invalid");if(t.equals(r))return 0;var n=t.getRawAssetType().value,o=r.getRawAssetType().value;if(n!==o)return n{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.authorizeEntry=y,t.authorizeInvocation=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:u.Networks.FUTURENET,s=a.Keypair.random().rawPublicKey(),c=new i.default.Int64((p=s,p.subarray(0,8).reduce((function(e,t){return e<<8|t}),0))),f=n||e.publicKey();var p;if(!f)throw new Error("authorizeInvocation requires publicKey parameter");return y(new i.default.SorobanAuthorizationEntry({rootInvocation:r,credentials:i.default.SorobanCredentials.sorobanCredentialsAddress(new i.default.SorobanAddressCredentials({address:new l.Address(f).toScAddress(),nonce:c,signatureExpirationLedger:0,signature:i.default.ScVal.scvVec([])}))}),e,t,o)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(6691),s=r(7120),u=r(6202),c=r(9152),l=r(1180),f=r(7177);function p(e){return p="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},p(e)}function d(){d=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof b?t:b,a=Object.create(i.prototype),s=new C(n||[]);return o(a,"_invoke",{value:A(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var h="suspendedStart",y="suspendedYield",m="executing",v="completed",g={};function b(){}function w(){}function S(){}var E={};c(E,a,(function(){return this}));var _=Object.getPrototypeOf,k=_&&_(_(I([])));k&&k!==r&&n.call(k,a)&&(E=k);var T=S.prototype=b.prototype=Object.create(E);function O(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function x(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==p(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function A(t,r,n){var o=h;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=P(s,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=m;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?v:y,c.arg===g)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=v,n.method="throw",n.arg=c.arg)}}}function P(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,P(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function R(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function j(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(R,this),this.reset(!0)}function I(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),j(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:I(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function h(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function y(e,t,r){return m.apply(this,arguments)}function m(){var e;return e=d().mark((function e(t,r,o){var p,h,y,m,v,g,b,w,S,E=arguments;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(p=E.length>3&&void 0!==E[3]?E[3]:u.Networks.FUTURENET,t.credentials().switch().value===i.default.SorobanCredentialsType.sorobanCredentialsAddress().value){e.next=3;break}return e.abrupt("return",t);case 3:if(h=i.default.SorobanAuthorizationEntry.fromXDR(t.toXDR()),(y=h.credentials().address()).signatureExpirationLedger(o),m=(0,c.hash)(n.from(p)),v=i.default.HashIdPreimage.envelopeTypeSorobanAuthorization(new i.default.HashIdPreimageSorobanAuthorization({networkId:m,nonce:y.nonce(),invocation:h.rootInvocation(),signatureExpirationLedger:y.signatureExpirationLedger()})),g=(0,c.hash)(v.toXDR()),"function"!=typeof r){e.next=18;break}return e.t0=n,e.next=13,r(v);case 13:e.t1=e.sent,b=e.t0.from.call(e.t0,e.t1),w=l.Address.fromScAddress(y.address()).toString(),e.next=20;break;case 18:b=n.from(r.sign(g)),w=r.publicKey();case 20:if(a.Keypair.fromPublicKey(w).verify(g,b)){e.next=22;break}throw new Error("signature doesn't match payload");case 22:return S=(0,f.nativeToScVal)({public_key:s.StrKey.decodeEd25519PublicKey(w),signature:b},{type:{public_key:["symbol",null],signature:["symbol",null]}}),y.signature(i.default.ScVal.scvVec([S])),e.abrupt("return",h);case 25:case"end":return e.stop()}}),e)})),m=function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){h(i,n,o,a,s,"next",e)}function s(e){h(i,n,o,a,s,"throw",e)}a(void 0)}))},m.apply(this,arguments)}},1387:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Claimant=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691),a=r(7120);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Contract=void 0;var n,o=r(1180),i=r(7237),a=(n=r(1918))&&n.__esModule?n:{default:n},s=r(7120);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){for(var r=0;r1?t-1:0),n=1;n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.humanizeEvents=function(e){return e.map((function(e){return e.inSuccessfulContractCall?c(e.event()):c(e)}))};var n=r(7120),o=r(7177);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function s(e){for(var t=1;t{"use strict";var n=r(8287).Buffer;function o(e){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.FeeBumpTransaction=void 0;var i,a=(i=r(1918))&&i.__esModule?i:{default:i},s=r(9152),u=r(380),c=r(3758),l=r(6160);function f(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(o=function(e){return e?r:t})(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=n(e)&&"function"!=typeof e)return{default:e};var r=o(t);if(r&&r.has(e))return r.get(e);var i={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&{}.hasOwnProperty.call(e,s)){var u=a?Object.getOwnPropertyDescriptor(e,s):null;u&&(u.get||u.set)?Object.defineProperty(i,s,u):i[s]=e[s]}return i.default=e,r&&r.set(e,i),i}(r(3740)).config((function(e){var t=1024;e.typedef("Value",e.varOpaque()),e.struct("ScpBallot",[["counter",e.lookup("Uint32")],["value",e.lookup("Value")]]),e.enum("ScpStatementType",{scpStPrepare:0,scpStConfirm:1,scpStExternalize:2,scpStNominate:3}),e.struct("ScpNomination",[["quorumSetHash",e.lookup("Hash")],["votes",e.varArray(e.lookup("Value"),2147483647)],["accepted",e.varArray(e.lookup("Value"),2147483647)]]),e.struct("ScpStatementPrepare",[["quorumSetHash",e.lookup("Hash")],["ballot",e.lookup("ScpBallot")],["prepared",e.option(e.lookup("ScpBallot"))],["preparedPrime",e.option(e.lookup("ScpBallot"))],["nC",e.lookup("Uint32")],["nH",e.lookup("Uint32")]]),e.struct("ScpStatementConfirm",[["ballot",e.lookup("ScpBallot")],["nPrepared",e.lookup("Uint32")],["nCommit",e.lookup("Uint32")],["nH",e.lookup("Uint32")],["quorumSetHash",e.lookup("Hash")]]),e.struct("ScpStatementExternalize",[["commit",e.lookup("ScpBallot")],["nH",e.lookup("Uint32")],["commitQuorumSetHash",e.lookup("Hash")]]),e.union("ScpStatementPledges",{switchOn:e.lookup("ScpStatementType"),switchName:"type",switches:[["scpStPrepare","prepare"],["scpStConfirm","confirm"],["scpStExternalize","externalize"],["scpStNominate","nominate"]],arms:{prepare:e.lookup("ScpStatementPrepare"),confirm:e.lookup("ScpStatementConfirm"),externalize:e.lookup("ScpStatementExternalize"),nominate:e.lookup("ScpNomination")}}),e.struct("ScpStatement",[["nodeId",e.lookup("NodeId")],["slotIndex",e.lookup("Uint64")],["pledges",e.lookup("ScpStatementPledges")]]),e.struct("ScpEnvelope",[["statement",e.lookup("ScpStatement")],["signature",e.lookup("Signature")]]),e.struct("ScpQuorumSet",[["threshold",e.lookup("Uint32")],["validators",e.varArray(e.lookup("NodeId"),2147483647)],["innerSets",e.varArray(e.lookup("ScpQuorumSet"),2147483647)]]),e.typedef("Thresholds",e.opaque(4)),e.typedef("String32",e.string(32)),e.typedef("String64",e.string(64)),e.typedef("SequenceNumber",e.lookup("Int64")),e.typedef("DataValue",e.varOpaque(64)),e.typedef("PoolId",e.lookup("Hash")),e.typedef("AssetCode4",e.opaque(4)),e.typedef("AssetCode12",e.opaque(12)),e.enum("AssetType",{assetTypeNative:0,assetTypeCreditAlphanum4:1,assetTypeCreditAlphanum12:2,assetTypePoolShare:3}),e.union("AssetCode",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeCreditAlphanum4","assetCode4"],["assetTypeCreditAlphanum12","assetCode12"]],arms:{assetCode4:e.lookup("AssetCode4"),assetCode12:e.lookup("AssetCode12")}}),e.struct("AlphaNum4",[["assetCode",e.lookup("AssetCode4")],["issuer",e.lookup("AccountId")]]),e.struct("AlphaNum12",[["assetCode",e.lookup("AssetCode12")],["issuer",e.lookup("AccountId")]]),e.union("Asset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12")}}),e.struct("Price",[["n",e.lookup("Int32")],["d",e.lookup("Int32")]]),e.struct("Liabilities",[["buying",e.lookup("Int64")],["selling",e.lookup("Int64")]]),e.enum("ThresholdIndices",{thresholdMasterWeight:0,thresholdLow:1,thresholdMed:2,thresholdHigh:3}),e.enum("LedgerEntryType",{account:0,trustline:1,offer:2,data:3,claimableBalance:4,liquidityPool:5,contractData:6,contractCode:7,configSetting:8,ttl:9}),e.struct("Signer",[["key",e.lookup("SignerKey")],["weight",e.lookup("Uint32")]]),e.enum("AccountFlags",{authRequiredFlag:1,authRevocableFlag:2,authImmutableFlag:4,authClawbackEnabledFlag:8}),e.const("MASK_ACCOUNT_FLAGS",7),e.const("MASK_ACCOUNT_FLAGS_V17",15),e.const("MAX_SIGNERS",20),e.typedef("SponsorshipDescriptor",e.option(e.lookup("AccountId"))),e.struct("AccountEntryExtensionV3",[["ext",e.lookup("ExtensionPoint")],["seqLedger",e.lookup("Uint32")],["seqTime",e.lookup("TimePoint")]]),e.union("AccountEntryExtensionV2Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[3,"v3"]],arms:{v3:e.lookup("AccountEntryExtensionV3")}}),e.struct("AccountEntryExtensionV2",[["numSponsored",e.lookup("Uint32")],["numSponsoring",e.lookup("Uint32")],["signerSponsoringIDs",e.varArray(e.lookup("SponsorshipDescriptor"),e.lookup("MAX_SIGNERS"))],["ext",e.lookup("AccountEntryExtensionV2Ext")]]),e.union("AccountEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[2,"v2"]],arms:{v2:e.lookup("AccountEntryExtensionV2")}}),e.struct("AccountEntryExtensionV1",[["liabilities",e.lookup("Liabilities")],["ext",e.lookup("AccountEntryExtensionV1Ext")]]),e.union("AccountEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("AccountEntryExtensionV1")}}),e.struct("AccountEntry",[["accountId",e.lookup("AccountId")],["balance",e.lookup("Int64")],["seqNum",e.lookup("SequenceNumber")],["numSubEntries",e.lookup("Uint32")],["inflationDest",e.option(e.lookup("AccountId"))],["flags",e.lookup("Uint32")],["homeDomain",e.lookup("String32")],["thresholds",e.lookup("Thresholds")],["signers",e.varArray(e.lookup("Signer"),e.lookup("MAX_SIGNERS"))],["ext",e.lookup("AccountEntryExt")]]),e.enum("TrustLineFlags",{authorizedFlag:1,authorizedToMaintainLiabilitiesFlag:2,trustlineClawbackEnabledFlag:4}),e.const("MASK_TRUSTLINE_FLAGS",1),e.const("MASK_TRUSTLINE_FLAGS_V13",3),e.const("MASK_TRUSTLINE_FLAGS_V17",7),e.enum("LiquidityPoolType",{liquidityPoolConstantProduct:0}),e.union("TrustLineAsset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"],["assetTypePoolShare","liquidityPoolId"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12"),liquidityPoolId:e.lookup("PoolId")}}),e.union("TrustLineEntryExtensionV2Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TrustLineEntryExtensionV2",[["liquidityPoolUseCount",e.lookup("Int32")],["ext",e.lookup("TrustLineEntryExtensionV2Ext")]]),e.union("TrustLineEntryV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[2,"v2"]],arms:{v2:e.lookup("TrustLineEntryExtensionV2")}}),e.struct("TrustLineEntryV1",[["liabilities",e.lookup("Liabilities")],["ext",e.lookup("TrustLineEntryV1Ext")]]),e.union("TrustLineEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("TrustLineEntryV1")}}),e.struct("TrustLineEntry",[["accountId",e.lookup("AccountId")],["asset",e.lookup("TrustLineAsset")],["balance",e.lookup("Int64")],["limit",e.lookup("Int64")],["flags",e.lookup("Uint32")],["ext",e.lookup("TrustLineEntryExt")]]),e.enum("OfferEntryFlags",{passiveFlag:1}),e.const("MASK_OFFERENTRY_FLAGS",1),e.union("OfferEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("OfferEntry",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")],["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")],["flags",e.lookup("Uint32")],["ext",e.lookup("OfferEntryExt")]]),e.union("DataEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("DataEntry",[["accountId",e.lookup("AccountId")],["dataName",e.lookup("String64")],["dataValue",e.lookup("DataValue")],["ext",e.lookup("DataEntryExt")]]),e.enum("ClaimPredicateType",{claimPredicateUnconditional:0,claimPredicateAnd:1,claimPredicateOr:2,claimPredicateNot:3,claimPredicateBeforeAbsoluteTime:4,claimPredicateBeforeRelativeTime:5}),e.union("ClaimPredicate",{switchOn:e.lookup("ClaimPredicateType"),switchName:"type",switches:[["claimPredicateUnconditional",e.void()],["claimPredicateAnd","andPredicates"],["claimPredicateOr","orPredicates"],["claimPredicateNot","notPredicate"],["claimPredicateBeforeAbsoluteTime","absBefore"],["claimPredicateBeforeRelativeTime","relBefore"]],arms:{andPredicates:e.varArray(e.lookup("ClaimPredicate"),2),orPredicates:e.varArray(e.lookup("ClaimPredicate"),2),notPredicate:e.option(e.lookup("ClaimPredicate")),absBefore:e.lookup("Int64"),relBefore:e.lookup("Int64")}}),e.enum("ClaimantType",{claimantTypeV0:0}),e.struct("ClaimantV0",[["destination",e.lookup("AccountId")],["predicate",e.lookup("ClaimPredicate")]]),e.union("Claimant",{switchOn:e.lookup("ClaimantType"),switchName:"type",switches:[["claimantTypeV0","v0"]],arms:{v0:e.lookup("ClaimantV0")}}),e.enum("ClaimableBalanceIdType",{claimableBalanceIdTypeV0:0}),e.union("ClaimableBalanceId",{switchOn:e.lookup("ClaimableBalanceIdType"),switchName:"type",switches:[["claimableBalanceIdTypeV0","v0"]],arms:{v0:e.lookup("Hash")}}),e.enum("ClaimableBalanceFlags",{claimableBalanceClawbackEnabledFlag:1}),e.const("MASK_CLAIMABLE_BALANCE_FLAGS",1),e.union("ClaimableBalanceEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("ClaimableBalanceEntryExtensionV1",[["ext",e.lookup("ClaimableBalanceEntryExtensionV1Ext")],["flags",e.lookup("Uint32")]]),e.union("ClaimableBalanceEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("ClaimableBalanceEntryExtensionV1")}}),e.struct("ClaimableBalanceEntry",[["balanceId",e.lookup("ClaimableBalanceId")],["claimants",e.varArray(e.lookup("Claimant"),10)],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")],["ext",e.lookup("ClaimableBalanceEntryExt")]]),e.struct("LiquidityPoolConstantProductParameters",[["assetA",e.lookup("Asset")],["assetB",e.lookup("Asset")],["fee",e.lookup("Int32")]]),e.struct("LiquidityPoolEntryConstantProduct",[["params",e.lookup("LiquidityPoolConstantProductParameters")],["reserveA",e.lookup("Int64")],["reserveB",e.lookup("Int64")],["totalPoolShares",e.lookup("Int64")],["poolSharesTrustLineCount",e.lookup("Int64")]]),e.union("LiquidityPoolEntryBody",{switchOn:e.lookup("LiquidityPoolType"),switchName:"type",switches:[["liquidityPoolConstantProduct","constantProduct"]],arms:{constantProduct:e.lookup("LiquidityPoolEntryConstantProduct")}}),e.struct("LiquidityPoolEntry",[["liquidityPoolId",e.lookup("PoolId")],["body",e.lookup("LiquidityPoolEntryBody")]]),e.enum("ContractDataDurability",{temporary:0,persistent:1}),e.struct("ContractDataEntry",[["ext",e.lookup("ExtensionPoint")],["contract",e.lookup("ScAddress")],["key",e.lookup("ScVal")],["durability",e.lookup("ContractDataDurability")],["val",e.lookup("ScVal")]]),e.struct("ContractCodeCostInputs",[["ext",e.lookup("ExtensionPoint")],["nInstructions",e.lookup("Uint32")],["nFunctions",e.lookup("Uint32")],["nGlobals",e.lookup("Uint32")],["nTableEntries",e.lookup("Uint32")],["nTypes",e.lookup("Uint32")],["nDataSegments",e.lookup("Uint32")],["nElemSegments",e.lookup("Uint32")],["nImports",e.lookup("Uint32")],["nExports",e.lookup("Uint32")],["nDataSegmentBytes",e.lookup("Uint32")]]),e.struct("ContractCodeEntryV1",[["ext",e.lookup("ExtensionPoint")],["costInputs",e.lookup("ContractCodeCostInputs")]]),e.union("ContractCodeEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("ContractCodeEntryV1")}}),e.struct("ContractCodeEntry",[["ext",e.lookup("ContractCodeEntryExt")],["hash",e.lookup("Hash")],["code",e.varOpaque()]]),e.struct("TtlEntry",[["keyHash",e.lookup("Hash")],["liveUntilLedgerSeq",e.lookup("Uint32")]]),e.union("LedgerEntryExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerEntryExtensionV1",[["sponsoringId",e.lookup("SponsorshipDescriptor")],["ext",e.lookup("LedgerEntryExtensionV1Ext")]]),e.union("LedgerEntryData",{switchOn:e.lookup("LedgerEntryType"),switchName:"type",switches:[["account","account"],["trustline","trustLine"],["offer","offer"],["data","data"],["claimableBalance","claimableBalance"],["liquidityPool","liquidityPool"],["contractData","contractData"],["contractCode","contractCode"],["configSetting","configSetting"],["ttl","ttl"]],arms:{account:e.lookup("AccountEntry"),trustLine:e.lookup("TrustLineEntry"),offer:e.lookup("OfferEntry"),data:e.lookup("DataEntry"),claimableBalance:e.lookup("ClaimableBalanceEntry"),liquidityPool:e.lookup("LiquidityPoolEntry"),contractData:e.lookup("ContractDataEntry"),contractCode:e.lookup("ContractCodeEntry"),configSetting:e.lookup("ConfigSettingEntry"),ttl:e.lookup("TtlEntry")}}),e.union("LedgerEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerEntryExtensionV1")}}),e.struct("LedgerEntry",[["lastModifiedLedgerSeq",e.lookup("Uint32")],["data",e.lookup("LedgerEntryData")],["ext",e.lookup("LedgerEntryExt")]]),e.struct("LedgerKeyAccount",[["accountId",e.lookup("AccountId")]]),e.struct("LedgerKeyTrustLine",[["accountId",e.lookup("AccountId")],["asset",e.lookup("TrustLineAsset")]]),e.struct("LedgerKeyOffer",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")]]),e.struct("LedgerKeyData",[["accountId",e.lookup("AccountId")],["dataName",e.lookup("String64")]]),e.struct("LedgerKeyClaimableBalance",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("LedgerKeyLiquidityPool",[["liquidityPoolId",e.lookup("PoolId")]]),e.struct("LedgerKeyContractData",[["contract",e.lookup("ScAddress")],["key",e.lookup("ScVal")],["durability",e.lookup("ContractDataDurability")]]),e.struct("LedgerKeyContractCode",[["hash",e.lookup("Hash")]]),e.struct("LedgerKeyConfigSetting",[["configSettingId",e.lookup("ConfigSettingId")]]),e.struct("LedgerKeyTtl",[["keyHash",e.lookup("Hash")]]),e.union("LedgerKey",{switchOn:e.lookup("LedgerEntryType"),switchName:"type",switches:[["account","account"],["trustline","trustLine"],["offer","offer"],["data","data"],["claimableBalance","claimableBalance"],["liquidityPool","liquidityPool"],["contractData","contractData"],["contractCode","contractCode"],["configSetting","configSetting"],["ttl","ttl"]],arms:{account:e.lookup("LedgerKeyAccount"),trustLine:e.lookup("LedgerKeyTrustLine"),offer:e.lookup("LedgerKeyOffer"),data:e.lookup("LedgerKeyData"),claimableBalance:e.lookup("LedgerKeyClaimableBalance"),liquidityPool:e.lookup("LedgerKeyLiquidityPool"),contractData:e.lookup("LedgerKeyContractData"),contractCode:e.lookup("LedgerKeyContractCode"),configSetting:e.lookup("LedgerKeyConfigSetting"),ttl:e.lookup("LedgerKeyTtl")}}),e.enum("EnvelopeType",{envelopeTypeTxV0:0,envelopeTypeScp:1,envelopeTypeTx:2,envelopeTypeAuth:3,envelopeTypeScpvalue:4,envelopeTypeTxFeeBump:5,envelopeTypeOpId:6,envelopeTypePoolRevokeOpId:7,envelopeTypeContractId:8,envelopeTypeSorobanAuthorization:9}),e.enum("BucketListType",{live:0,hotArchive:1,coldArchive:2}),e.enum("BucketEntryType",{metaentry:-1,liveentry:0,deadentry:1,initentry:2}),e.enum("HotArchiveBucketEntryType",{hotArchiveMetaentry:-1,hotArchiveArchived:0,hotArchiveLive:1,hotArchiveDeleted:2}),e.enum("ColdArchiveBucketEntryType",{coldArchiveMetaentry:-1,coldArchiveArchivedLeaf:0,coldArchiveDeletedLeaf:1,coldArchiveBoundaryLeaf:2,coldArchiveHash:3}),e.union("BucketMetadataExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"bucketListType"]],arms:{bucketListType:e.lookup("BucketListType")}}),e.struct("BucketMetadata",[["ledgerVersion",e.lookup("Uint32")],["ext",e.lookup("BucketMetadataExt")]]),e.union("BucketEntry",{switchOn:e.lookup("BucketEntryType"),switchName:"type",switches:[["liveentry","liveEntry"],["initentry","liveEntry"],["deadentry","deadEntry"],["metaentry","metaEntry"]],arms:{liveEntry:e.lookup("LedgerEntry"),deadEntry:e.lookup("LedgerKey"),metaEntry:e.lookup("BucketMetadata")}}),e.union("HotArchiveBucketEntry",{switchOn:e.lookup("HotArchiveBucketEntryType"),switchName:"type",switches:[["hotArchiveArchived","archivedEntry"],["hotArchiveLive","key"],["hotArchiveDeleted","key"],["hotArchiveMetaentry","metaEntry"]],arms:{archivedEntry:e.lookup("LedgerEntry"),key:e.lookup("LedgerKey"),metaEntry:e.lookup("BucketMetadata")}}),e.struct("ColdArchiveArchivedLeaf",[["index",e.lookup("Uint32")],["archivedEntry",e.lookup("LedgerEntry")]]),e.struct("ColdArchiveDeletedLeaf",[["index",e.lookup("Uint32")],["deletedKey",e.lookup("LedgerKey")]]),e.struct("ColdArchiveBoundaryLeaf",[["index",e.lookup("Uint32")],["isLowerBound",e.bool()]]),e.struct("ColdArchiveHashEntry",[["index",e.lookup("Uint32")],["level",e.lookup("Uint32")],["hash",e.lookup("Hash")]]),e.union("ColdArchiveBucketEntry",{switchOn:e.lookup("ColdArchiveBucketEntryType"),switchName:"type",switches:[["coldArchiveMetaentry","metaEntry"],["coldArchiveArchivedLeaf","archivedLeaf"],["coldArchiveDeletedLeaf","deletedLeaf"],["coldArchiveBoundaryLeaf","boundaryLeaf"],["coldArchiveHash","hashEntry"]],arms:{metaEntry:e.lookup("BucketMetadata"),archivedLeaf:e.lookup("ColdArchiveArchivedLeaf"),deletedLeaf:e.lookup("ColdArchiveDeletedLeaf"),boundaryLeaf:e.lookup("ColdArchiveBoundaryLeaf"),hashEntry:e.lookup("ColdArchiveHashEntry")}}),e.typedef("UpgradeType",e.varOpaque(128)),e.enum("StellarValueType",{stellarValueBasic:0,stellarValueSigned:1}),e.struct("LedgerCloseValueSignature",[["nodeId",e.lookup("NodeId")],["signature",e.lookup("Signature")]]),e.union("StellarValueExt",{switchOn:e.lookup("StellarValueType"),switchName:"v",switches:[["stellarValueBasic",e.void()],["stellarValueSigned","lcValueSignature"]],arms:{lcValueSignature:e.lookup("LedgerCloseValueSignature")}}),e.struct("StellarValue",[["txSetHash",e.lookup("Hash")],["closeTime",e.lookup("TimePoint")],["upgrades",e.varArray(e.lookup("UpgradeType"),6)],["ext",e.lookup("StellarValueExt")]]),e.const("MASK_LEDGER_HEADER_FLAGS",7),e.enum("LedgerHeaderFlags",{disableLiquidityPoolTradingFlag:1,disableLiquidityPoolDepositFlag:2,disableLiquidityPoolWithdrawalFlag:4}),e.union("LedgerHeaderExtensionV1Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerHeaderExtensionV1",[["flags",e.lookup("Uint32")],["ext",e.lookup("LedgerHeaderExtensionV1Ext")]]),e.union("LedgerHeaderExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerHeaderExtensionV1")}}),e.struct("LedgerHeader",[["ledgerVersion",e.lookup("Uint32")],["previousLedgerHash",e.lookup("Hash")],["scpValue",e.lookup("StellarValue")],["txSetResultHash",e.lookup("Hash")],["bucketListHash",e.lookup("Hash")],["ledgerSeq",e.lookup("Uint32")],["totalCoins",e.lookup("Int64")],["feePool",e.lookup("Int64")],["inflationSeq",e.lookup("Uint32")],["idPool",e.lookup("Uint64")],["baseFee",e.lookup("Uint32")],["baseReserve",e.lookup("Uint32")],["maxTxSetSize",e.lookup("Uint32")],["skipList",e.array(e.lookup("Hash"),4)],["ext",e.lookup("LedgerHeaderExt")]]),e.enum("LedgerUpgradeType",{ledgerUpgradeVersion:1,ledgerUpgradeBaseFee:2,ledgerUpgradeMaxTxSetSize:3,ledgerUpgradeBaseReserve:4,ledgerUpgradeFlags:5,ledgerUpgradeConfig:6,ledgerUpgradeMaxSorobanTxSetSize:7}),e.struct("ConfigUpgradeSetKey",[["contractId",e.lookup("Hash")],["contentHash",e.lookup("Hash")]]),e.union("LedgerUpgrade",{switchOn:e.lookup("LedgerUpgradeType"),switchName:"type",switches:[["ledgerUpgradeVersion","newLedgerVersion"],["ledgerUpgradeBaseFee","newBaseFee"],["ledgerUpgradeMaxTxSetSize","newMaxTxSetSize"],["ledgerUpgradeBaseReserve","newBaseReserve"],["ledgerUpgradeFlags","newFlags"],["ledgerUpgradeConfig","newConfig"],["ledgerUpgradeMaxSorobanTxSetSize","newMaxSorobanTxSetSize"]],arms:{newLedgerVersion:e.lookup("Uint32"),newBaseFee:e.lookup("Uint32"),newMaxTxSetSize:e.lookup("Uint32"),newBaseReserve:e.lookup("Uint32"),newFlags:e.lookup("Uint32"),newConfig:e.lookup("ConfigUpgradeSetKey"),newMaxSorobanTxSetSize:e.lookup("Uint32")}}),e.struct("ConfigUpgradeSet",[["updatedEntry",e.varArray(e.lookup("ConfigSettingEntry"),2147483647)]]),e.enum("TxSetComponentType",{txsetCompTxsMaybeDiscountedFee:0}),e.struct("TxSetComponentTxsMaybeDiscountedFee",[["baseFee",e.option(e.lookup("Int64"))],["txes",e.varArray(e.lookup("TransactionEnvelope"),2147483647)]]),e.union("TxSetComponent",{switchOn:e.lookup("TxSetComponentType"),switchName:"type",switches:[["txsetCompTxsMaybeDiscountedFee","txsMaybeDiscountedFee"]],arms:{txsMaybeDiscountedFee:e.lookup("TxSetComponentTxsMaybeDiscountedFee")}}),e.union("TransactionPhase",{switchOn:e.int(),switchName:"v",switches:[[0,"v0Components"]],arms:{v0Components:e.varArray(e.lookup("TxSetComponent"),2147483647)}}),e.struct("TransactionSet",[["previousLedgerHash",e.lookup("Hash")],["txes",e.varArray(e.lookup("TransactionEnvelope"),2147483647)]]),e.struct("TransactionSetV1",[["previousLedgerHash",e.lookup("Hash")],["phases",e.varArray(e.lookup("TransactionPhase"),2147483647)]]),e.union("GeneralizedTransactionSet",{switchOn:e.int(),switchName:"v",switches:[[1,"v1TxSet"]],arms:{v1TxSet:e.lookup("TransactionSetV1")}}),e.struct("TransactionResultPair",[["transactionHash",e.lookup("Hash")],["result",e.lookup("TransactionResult")]]),e.struct("TransactionResultSet",[["results",e.varArray(e.lookup("TransactionResultPair"),2147483647)]]),e.union("TransactionHistoryEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"generalizedTxSet"]],arms:{generalizedTxSet:e.lookup("GeneralizedTransactionSet")}}),e.struct("TransactionHistoryEntry",[["ledgerSeq",e.lookup("Uint32")],["txSet",e.lookup("TransactionSet")],["ext",e.lookup("TransactionHistoryEntryExt")]]),e.union("TransactionHistoryResultEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionHistoryResultEntry",[["ledgerSeq",e.lookup("Uint32")],["txResultSet",e.lookup("TransactionResultSet")],["ext",e.lookup("TransactionHistoryResultEntryExt")]]),e.union("LedgerHeaderHistoryEntryExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("LedgerHeaderHistoryEntry",[["hash",e.lookup("Hash")],["header",e.lookup("LedgerHeader")],["ext",e.lookup("LedgerHeaderHistoryEntryExt")]]),e.struct("LedgerScpMessages",[["ledgerSeq",e.lookup("Uint32")],["messages",e.varArray(e.lookup("ScpEnvelope"),2147483647)]]),e.struct("ScpHistoryEntryV0",[["quorumSets",e.varArray(e.lookup("ScpQuorumSet"),2147483647)],["ledgerMessages",e.lookup("LedgerScpMessages")]]),e.union("ScpHistoryEntry",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("ScpHistoryEntryV0")}}),e.enum("LedgerEntryChangeType",{ledgerEntryCreated:0,ledgerEntryUpdated:1,ledgerEntryRemoved:2,ledgerEntryState:3}),e.union("LedgerEntryChange",{switchOn:e.lookup("LedgerEntryChangeType"),switchName:"type",switches:[["ledgerEntryCreated","created"],["ledgerEntryUpdated","updated"],["ledgerEntryRemoved","removed"],["ledgerEntryState","state"]],arms:{created:e.lookup("LedgerEntry"),updated:e.lookup("LedgerEntry"),removed:e.lookup("LedgerKey"),state:e.lookup("LedgerEntry")}}),e.typedef("LedgerEntryChanges",e.varArray(e.lookup("LedgerEntryChange"),2147483647)),e.struct("OperationMeta",[["changes",e.lookup("LedgerEntryChanges")]]),e.struct("TransactionMetaV1",[["txChanges",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)]]),e.struct("TransactionMetaV2",[["txChangesBefore",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)],["txChangesAfter",e.lookup("LedgerEntryChanges")]]),e.enum("ContractEventType",{system:0,contract:1,diagnostic:2}),e.struct("ContractEventV0",[["topics",e.varArray(e.lookup("ScVal"),2147483647)],["data",e.lookup("ScVal")]]),e.union("ContractEventBody",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("ContractEventV0")}}),e.struct("ContractEvent",[["ext",e.lookup("ExtensionPoint")],["contractId",e.option(e.lookup("Hash"))],["type",e.lookup("ContractEventType")],["body",e.lookup("ContractEventBody")]]),e.struct("DiagnosticEvent",[["inSuccessfulContractCall",e.bool()],["event",e.lookup("ContractEvent")]]),e.typedef("DiagnosticEvents",e.varArray(e.lookup("DiagnosticEvent"),2147483647)),e.struct("SorobanTransactionMetaExtV1",[["ext",e.lookup("ExtensionPoint")],["totalNonRefundableResourceFeeCharged",e.lookup("Int64")],["totalRefundableResourceFeeCharged",e.lookup("Int64")],["rentFeeCharged",e.lookup("Int64")]]),e.union("SorobanTransactionMetaExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("SorobanTransactionMetaExtV1")}}),e.struct("SorobanTransactionMeta",[["ext",e.lookup("SorobanTransactionMetaExt")],["events",e.varArray(e.lookup("ContractEvent"),2147483647)],["returnValue",e.lookup("ScVal")],["diagnosticEvents",e.varArray(e.lookup("DiagnosticEvent"),2147483647)]]),e.struct("TransactionMetaV3",[["ext",e.lookup("ExtensionPoint")],["txChangesBefore",e.lookup("LedgerEntryChanges")],["operations",e.varArray(e.lookup("OperationMeta"),2147483647)],["txChangesAfter",e.lookup("LedgerEntryChanges")],["sorobanMeta",e.option(e.lookup("SorobanTransactionMeta"))]]),e.struct("InvokeHostFunctionSuccessPreImage",[["returnValue",e.lookup("ScVal")],["events",e.varArray(e.lookup("ContractEvent"),2147483647)]]),e.union("TransactionMeta",{switchOn:e.int(),switchName:"v",switches:[[0,"operations"],[1,"v1"],[2,"v2"],[3,"v3"]],arms:{operations:e.varArray(e.lookup("OperationMeta"),2147483647),v1:e.lookup("TransactionMetaV1"),v2:e.lookup("TransactionMetaV2"),v3:e.lookup("TransactionMetaV3")}}),e.struct("TransactionResultMeta",[["result",e.lookup("TransactionResultPair")],["feeProcessing",e.lookup("LedgerEntryChanges")],["txApplyProcessing",e.lookup("TransactionMeta")]]),e.struct("UpgradeEntryMeta",[["upgrade",e.lookup("LedgerUpgrade")],["changes",e.lookup("LedgerEntryChanges")]]),e.struct("LedgerCloseMetaV0",[["ledgerHeader",e.lookup("LedgerHeaderHistoryEntry")],["txSet",e.lookup("TransactionSet")],["txProcessing",e.varArray(e.lookup("TransactionResultMeta"),2147483647)],["upgradesProcessing",e.varArray(e.lookup("UpgradeEntryMeta"),2147483647)],["scpInfo",e.varArray(e.lookup("ScpHistoryEntry"),2147483647)]]),e.struct("LedgerCloseMetaExtV1",[["ext",e.lookup("ExtensionPoint")],["sorobanFeeWrite1Kb",e.lookup("Int64")]]),e.union("LedgerCloseMetaExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"v1"]],arms:{v1:e.lookup("LedgerCloseMetaExtV1")}}),e.struct("LedgerCloseMetaV1",[["ext",e.lookup("LedgerCloseMetaExt")],["ledgerHeader",e.lookup("LedgerHeaderHistoryEntry")],["txSet",e.lookup("GeneralizedTransactionSet")],["txProcessing",e.varArray(e.lookup("TransactionResultMeta"),2147483647)],["upgradesProcessing",e.varArray(e.lookup("UpgradeEntryMeta"),2147483647)],["scpInfo",e.varArray(e.lookup("ScpHistoryEntry"),2147483647)],["totalByteSizeOfBucketList",e.lookup("Uint64")],["evictedTemporaryLedgerKeys",e.varArray(e.lookup("LedgerKey"),2147483647)],["evictedPersistentLedgerEntries",e.varArray(e.lookup("LedgerEntry"),2147483647)]]),e.union("LedgerCloseMeta",{switchOn:e.int(),switchName:"v",switches:[[0,"v0"],[1,"v1"]],arms:{v0:e.lookup("LedgerCloseMetaV0"),v1:e.lookup("LedgerCloseMetaV1")}}),e.enum("ErrorCode",{errMisc:0,errData:1,errConf:2,errAuth:3,errLoad:4}),e.struct("Error",[["code",e.lookup("ErrorCode")],["msg",e.string(100)]]),e.struct("SendMore",[["numMessages",e.lookup("Uint32")]]),e.struct("SendMoreExtended",[["numMessages",e.lookup("Uint32")],["numBytes",e.lookup("Uint32")]]),e.struct("AuthCert",[["pubkey",e.lookup("Curve25519Public")],["expiration",e.lookup("Uint64")],["sig",e.lookup("Signature")]]),e.struct("Hello",[["ledgerVersion",e.lookup("Uint32")],["overlayVersion",e.lookup("Uint32")],["overlayMinVersion",e.lookup("Uint32")],["networkId",e.lookup("Hash")],["versionStr",e.string(100)],["listeningPort",e.int()],["peerId",e.lookup("NodeId")],["cert",e.lookup("AuthCert")],["nonce",e.lookup("Uint256")]]),e.const("AUTH_MSG_FLAG_FLOW_CONTROL_BYTES_REQUESTED",200),e.struct("Auth",[["flags",e.int()]]),e.enum("IpAddrType",{iPv4:0,iPv6:1}),e.union("PeerAddressIp",{switchOn:e.lookup("IpAddrType"),switchName:"type",switches:[["iPv4","ipv4"],["iPv6","ipv6"]],arms:{ipv4:e.opaque(4),ipv6:e.opaque(16)}}),e.struct("PeerAddress",[["ip",e.lookup("PeerAddressIp")],["port",e.lookup("Uint32")],["numFailures",e.lookup("Uint32")]]),e.enum("MessageType",{errorMsg:0,auth:2,dontHave:3,getPeers:4,peers:5,getTxSet:6,txSet:7,generalizedTxSet:17,transaction:8,getScpQuorumset:9,scpQuorumset:10,scpMessage:11,getScpState:12,hello:13,surveyRequest:14,surveyResponse:15,sendMore:16,sendMoreExtended:20,floodAdvert:18,floodDemand:19,timeSlicedSurveyRequest:21,timeSlicedSurveyResponse:22,timeSlicedSurveyStartCollecting:23,timeSlicedSurveyStopCollecting:24}),e.struct("DontHave",[["type",e.lookup("MessageType")],["reqHash",e.lookup("Uint256")]]),e.enum("SurveyMessageCommandType",{surveyTopology:0,timeSlicedSurveyTopology:1}),e.enum("SurveyMessageResponseType",{surveyTopologyResponseV0:0,surveyTopologyResponseV1:1,surveyTopologyResponseV2:2}),e.struct("TimeSlicedSurveyStartCollectingMessage",[["surveyorId",e.lookup("NodeId")],["nonce",e.lookup("Uint32")],["ledgerNum",e.lookup("Uint32")]]),e.struct("SignedTimeSlicedSurveyStartCollectingMessage",[["signature",e.lookup("Signature")],["startCollecting",e.lookup("TimeSlicedSurveyStartCollectingMessage")]]),e.struct("TimeSlicedSurveyStopCollectingMessage",[["surveyorId",e.lookup("NodeId")],["nonce",e.lookup("Uint32")],["ledgerNum",e.lookup("Uint32")]]),e.struct("SignedTimeSlicedSurveyStopCollectingMessage",[["signature",e.lookup("Signature")],["stopCollecting",e.lookup("TimeSlicedSurveyStopCollectingMessage")]]),e.struct("SurveyRequestMessage",[["surveyorPeerId",e.lookup("NodeId")],["surveyedPeerId",e.lookup("NodeId")],["ledgerNum",e.lookup("Uint32")],["encryptionKey",e.lookup("Curve25519Public")],["commandType",e.lookup("SurveyMessageCommandType")]]),e.struct("TimeSlicedSurveyRequestMessage",[["request",e.lookup("SurveyRequestMessage")],["nonce",e.lookup("Uint32")],["inboundPeersIndex",e.lookup("Uint32")],["outboundPeersIndex",e.lookup("Uint32")]]),e.struct("SignedSurveyRequestMessage",[["requestSignature",e.lookup("Signature")],["request",e.lookup("SurveyRequestMessage")]]),e.struct("SignedTimeSlicedSurveyRequestMessage",[["requestSignature",e.lookup("Signature")],["request",e.lookup("TimeSlicedSurveyRequestMessage")]]),e.typedef("EncryptedBody",e.varOpaque(64e3)),e.struct("SurveyResponseMessage",[["surveyorPeerId",e.lookup("NodeId")],["surveyedPeerId",e.lookup("NodeId")],["ledgerNum",e.lookup("Uint32")],["commandType",e.lookup("SurveyMessageCommandType")],["encryptedBody",e.lookup("EncryptedBody")]]),e.struct("TimeSlicedSurveyResponseMessage",[["response",e.lookup("SurveyResponseMessage")],["nonce",e.lookup("Uint32")]]),e.struct("SignedSurveyResponseMessage",[["responseSignature",e.lookup("Signature")],["response",e.lookup("SurveyResponseMessage")]]),e.struct("SignedTimeSlicedSurveyResponseMessage",[["responseSignature",e.lookup("Signature")],["response",e.lookup("TimeSlicedSurveyResponseMessage")]]),e.struct("PeerStats",[["id",e.lookup("NodeId")],["versionStr",e.string(100)],["messagesRead",e.lookup("Uint64")],["messagesWritten",e.lookup("Uint64")],["bytesRead",e.lookup("Uint64")],["bytesWritten",e.lookup("Uint64")],["secondsConnected",e.lookup("Uint64")],["uniqueFloodBytesRecv",e.lookup("Uint64")],["duplicateFloodBytesRecv",e.lookup("Uint64")],["uniqueFetchBytesRecv",e.lookup("Uint64")],["duplicateFetchBytesRecv",e.lookup("Uint64")],["uniqueFloodMessageRecv",e.lookup("Uint64")],["duplicateFloodMessageRecv",e.lookup("Uint64")],["uniqueFetchMessageRecv",e.lookup("Uint64")],["duplicateFetchMessageRecv",e.lookup("Uint64")]]),e.typedef("PeerStatList",e.varArray(e.lookup("PeerStats"),25)),e.struct("TimeSlicedNodeData",[["addedAuthenticatedPeers",e.lookup("Uint32")],["droppedAuthenticatedPeers",e.lookup("Uint32")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")],["p75ScpFirstToSelfLatencyMs",e.lookup("Uint32")],["p75ScpSelfToOtherLatencyMs",e.lookup("Uint32")],["lostSyncCount",e.lookup("Uint32")],["isValidator",e.bool()],["maxInboundPeerCount",e.lookup("Uint32")],["maxOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TimeSlicedPeerData",[["peerStats",e.lookup("PeerStats")],["averageLatencyMs",e.lookup("Uint32")]]),e.typedef("TimeSlicedPeerDataList",e.varArray(e.lookup("TimeSlicedPeerData"),25)),e.struct("TopologyResponseBodyV0",[["inboundPeers",e.lookup("PeerStatList")],["outboundPeers",e.lookup("PeerStatList")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TopologyResponseBodyV1",[["inboundPeers",e.lookup("PeerStatList")],["outboundPeers",e.lookup("PeerStatList")],["totalInboundPeerCount",e.lookup("Uint32")],["totalOutboundPeerCount",e.lookup("Uint32")],["maxInboundPeerCount",e.lookup("Uint32")],["maxOutboundPeerCount",e.lookup("Uint32")]]),e.struct("TopologyResponseBodyV2",[["inboundPeers",e.lookup("TimeSlicedPeerDataList")],["outboundPeers",e.lookup("TimeSlicedPeerDataList")],["nodeData",e.lookup("TimeSlicedNodeData")]]),e.union("SurveyResponseBody",{switchOn:e.lookup("SurveyMessageResponseType"),switchName:"type",switches:[["surveyTopologyResponseV0","topologyResponseBodyV0"],["surveyTopologyResponseV1","topologyResponseBodyV1"],["surveyTopologyResponseV2","topologyResponseBodyV2"]],arms:{topologyResponseBodyV0:e.lookup("TopologyResponseBodyV0"),topologyResponseBodyV1:e.lookup("TopologyResponseBodyV1"),topologyResponseBodyV2:e.lookup("TopologyResponseBodyV2")}}),e.const("TX_ADVERT_VECTOR_MAX_SIZE",1e3),e.typedef("TxAdvertVector",e.varArray(e.lookup("Hash"),e.lookup("TX_ADVERT_VECTOR_MAX_SIZE"))),e.struct("FloodAdvert",[["txHashes",e.lookup("TxAdvertVector")]]),e.const("TX_DEMAND_VECTOR_MAX_SIZE",1e3),e.typedef("TxDemandVector",e.varArray(e.lookup("Hash"),e.lookup("TX_DEMAND_VECTOR_MAX_SIZE"))),e.struct("FloodDemand",[["txHashes",e.lookup("TxDemandVector")]]),e.union("StellarMessage",{switchOn:e.lookup("MessageType"),switchName:"type",switches:[["errorMsg","error"],["hello","hello"],["auth","auth"],["dontHave","dontHave"],["getPeers",e.void()],["peers","peers"],["getTxSet","txSetHash"],["txSet","txSet"],["generalizedTxSet","generalizedTxSet"],["transaction","transaction"],["surveyRequest","signedSurveyRequestMessage"],["surveyResponse","signedSurveyResponseMessage"],["timeSlicedSurveyRequest","signedTimeSlicedSurveyRequestMessage"],["timeSlicedSurveyResponse","signedTimeSlicedSurveyResponseMessage"],["timeSlicedSurveyStartCollecting","signedTimeSlicedSurveyStartCollectingMessage"],["timeSlicedSurveyStopCollecting","signedTimeSlicedSurveyStopCollectingMessage"],["getScpQuorumset","qSetHash"],["scpQuorumset","qSet"],["scpMessage","envelope"],["getScpState","getScpLedgerSeq"],["sendMore","sendMoreMessage"],["sendMoreExtended","sendMoreExtendedMessage"],["floodAdvert","floodAdvert"],["floodDemand","floodDemand"]],arms:{error:e.lookup("Error"),hello:e.lookup("Hello"),auth:e.lookup("Auth"),dontHave:e.lookup("DontHave"),peers:e.varArray(e.lookup("PeerAddress"),100),txSetHash:e.lookup("Uint256"),txSet:e.lookup("TransactionSet"),generalizedTxSet:e.lookup("GeneralizedTransactionSet"),transaction:e.lookup("TransactionEnvelope"),signedSurveyRequestMessage:e.lookup("SignedSurveyRequestMessage"),signedSurveyResponseMessage:e.lookup("SignedSurveyResponseMessage"),signedTimeSlicedSurveyRequestMessage:e.lookup("SignedTimeSlicedSurveyRequestMessage"),signedTimeSlicedSurveyResponseMessage:e.lookup("SignedTimeSlicedSurveyResponseMessage"),signedTimeSlicedSurveyStartCollectingMessage:e.lookup("SignedTimeSlicedSurveyStartCollectingMessage"),signedTimeSlicedSurveyStopCollectingMessage:e.lookup("SignedTimeSlicedSurveyStopCollectingMessage"),qSetHash:e.lookup("Uint256"),qSet:e.lookup("ScpQuorumSet"),envelope:e.lookup("ScpEnvelope"),getScpLedgerSeq:e.lookup("Uint32"),sendMoreMessage:e.lookup("SendMore"),sendMoreExtendedMessage:e.lookup("SendMoreExtended"),floodAdvert:e.lookup("FloodAdvert"),floodDemand:e.lookup("FloodDemand")}}),e.struct("AuthenticatedMessageV0",[["sequence",e.lookup("Uint64")],["message",e.lookup("StellarMessage")],["mac",e.lookup("HmacSha256Mac")]]),e.union("AuthenticatedMessage",{switchOn:e.lookup("Uint32"),switchName:"v",switches:[[0,"v0"]],arms:{v0:e.lookup("AuthenticatedMessageV0")}}),e.const("MAX_OPS_PER_TX",100),e.union("LiquidityPoolParameters",{switchOn:e.lookup("LiquidityPoolType"),switchName:"type",switches:[["liquidityPoolConstantProduct","constantProduct"]],arms:{constantProduct:e.lookup("LiquidityPoolConstantProductParameters")}}),e.struct("MuxedAccountMed25519",[["id",e.lookup("Uint64")],["ed25519",e.lookup("Uint256")]]),e.union("MuxedAccount",{switchOn:e.lookup("CryptoKeyType"),switchName:"type",switches:[["keyTypeEd25519","ed25519"],["keyTypeMuxedEd25519","med25519"]],arms:{ed25519:e.lookup("Uint256"),med25519:e.lookup("MuxedAccountMed25519")}}),e.struct("DecoratedSignature",[["hint",e.lookup("SignatureHint")],["signature",e.lookup("Signature")]]),e.enum("OperationType",{createAccount:0,payment:1,pathPaymentStrictReceive:2,manageSellOffer:3,createPassiveSellOffer:4,setOptions:5,changeTrust:6,allowTrust:7,accountMerge:8,inflation:9,manageData:10,bumpSequence:11,manageBuyOffer:12,pathPaymentStrictSend:13,createClaimableBalance:14,claimClaimableBalance:15,beginSponsoringFutureReserves:16,endSponsoringFutureReserves:17,revokeSponsorship:18,clawback:19,clawbackClaimableBalance:20,setTrustLineFlags:21,liquidityPoolDeposit:22,liquidityPoolWithdraw:23,invokeHostFunction:24,extendFootprintTtl:25,restoreFootprint:26}),e.struct("CreateAccountOp",[["destination",e.lookup("AccountId")],["startingBalance",e.lookup("Int64")]]),e.struct("PaymentOp",[["destination",e.lookup("MuxedAccount")],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")]]),e.struct("PathPaymentStrictReceiveOp",[["sendAsset",e.lookup("Asset")],["sendMax",e.lookup("Int64")],["destination",e.lookup("MuxedAccount")],["destAsset",e.lookup("Asset")],["destAmount",e.lookup("Int64")],["path",e.varArray(e.lookup("Asset"),5)]]),e.struct("PathPaymentStrictSendOp",[["sendAsset",e.lookup("Asset")],["sendAmount",e.lookup("Int64")],["destination",e.lookup("MuxedAccount")],["destAsset",e.lookup("Asset")],["destMin",e.lookup("Int64")],["path",e.varArray(e.lookup("Asset"),5)]]),e.struct("ManageSellOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")],["offerId",e.lookup("Int64")]]),e.struct("ManageBuyOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["buyAmount",e.lookup("Int64")],["price",e.lookup("Price")],["offerId",e.lookup("Int64")]]),e.struct("CreatePassiveSellOfferOp",[["selling",e.lookup("Asset")],["buying",e.lookup("Asset")],["amount",e.lookup("Int64")],["price",e.lookup("Price")]]),e.struct("SetOptionsOp",[["inflationDest",e.option(e.lookup("AccountId"))],["clearFlags",e.option(e.lookup("Uint32"))],["setFlags",e.option(e.lookup("Uint32"))],["masterWeight",e.option(e.lookup("Uint32"))],["lowThreshold",e.option(e.lookup("Uint32"))],["medThreshold",e.option(e.lookup("Uint32"))],["highThreshold",e.option(e.lookup("Uint32"))],["homeDomain",e.option(e.lookup("String32"))],["signer",e.option(e.lookup("Signer"))]]),e.union("ChangeTrustAsset",{switchOn:e.lookup("AssetType"),switchName:"type",switches:[["assetTypeNative",e.void()],["assetTypeCreditAlphanum4","alphaNum4"],["assetTypeCreditAlphanum12","alphaNum12"],["assetTypePoolShare","liquidityPool"]],arms:{alphaNum4:e.lookup("AlphaNum4"),alphaNum12:e.lookup("AlphaNum12"),liquidityPool:e.lookup("LiquidityPoolParameters")}}),e.struct("ChangeTrustOp",[["line",e.lookup("ChangeTrustAsset")],["limit",e.lookup("Int64")]]),e.struct("AllowTrustOp",[["trustor",e.lookup("AccountId")],["asset",e.lookup("AssetCode")],["authorize",e.lookup("Uint32")]]),e.struct("ManageDataOp",[["dataName",e.lookup("String64")],["dataValue",e.option(e.lookup("DataValue"))]]),e.struct("BumpSequenceOp",[["bumpTo",e.lookup("SequenceNumber")]]),e.struct("CreateClaimableBalanceOp",[["asset",e.lookup("Asset")],["amount",e.lookup("Int64")],["claimants",e.varArray(e.lookup("Claimant"),10)]]),e.struct("ClaimClaimableBalanceOp",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("BeginSponsoringFutureReservesOp",[["sponsoredId",e.lookup("AccountId")]]),e.enum("RevokeSponsorshipType",{revokeSponsorshipLedgerEntry:0,revokeSponsorshipSigner:1}),e.struct("RevokeSponsorshipOpSigner",[["accountId",e.lookup("AccountId")],["signerKey",e.lookup("SignerKey")]]),e.union("RevokeSponsorshipOp",{switchOn:e.lookup("RevokeSponsorshipType"),switchName:"type",switches:[["revokeSponsorshipLedgerEntry","ledgerKey"],["revokeSponsorshipSigner","signer"]],arms:{ledgerKey:e.lookup("LedgerKey"),signer:e.lookup("RevokeSponsorshipOpSigner")}}),e.struct("ClawbackOp",[["asset",e.lookup("Asset")],["from",e.lookup("MuxedAccount")],["amount",e.lookup("Int64")]]),e.struct("ClawbackClaimableBalanceOp",[["balanceId",e.lookup("ClaimableBalanceId")]]),e.struct("SetTrustLineFlagsOp",[["trustor",e.lookup("AccountId")],["asset",e.lookup("Asset")],["clearFlags",e.lookup("Uint32")],["setFlags",e.lookup("Uint32")]]),e.const("LIQUIDITY_POOL_FEE_V18",30),e.struct("LiquidityPoolDepositOp",[["liquidityPoolId",e.lookup("PoolId")],["maxAmountA",e.lookup("Int64")],["maxAmountB",e.lookup("Int64")],["minPrice",e.lookup("Price")],["maxPrice",e.lookup("Price")]]),e.struct("LiquidityPoolWithdrawOp",[["liquidityPoolId",e.lookup("PoolId")],["amount",e.lookup("Int64")],["minAmountA",e.lookup("Int64")],["minAmountB",e.lookup("Int64")]]),e.enum("HostFunctionType",{hostFunctionTypeInvokeContract:0,hostFunctionTypeCreateContract:1,hostFunctionTypeUploadContractWasm:2,hostFunctionTypeCreateContractV2:3}),e.enum("ContractIdPreimageType",{contractIdPreimageFromAddress:0,contractIdPreimageFromAsset:1}),e.struct("ContractIdPreimageFromAddress",[["address",e.lookup("ScAddress")],["salt",e.lookup("Uint256")]]),e.union("ContractIdPreimage",{switchOn:e.lookup("ContractIdPreimageType"),switchName:"type",switches:[["contractIdPreimageFromAddress","fromAddress"],["contractIdPreimageFromAsset","fromAsset"]],arms:{fromAddress:e.lookup("ContractIdPreimageFromAddress"),fromAsset:e.lookup("Asset")}}),e.struct("CreateContractArgs",[["contractIdPreimage",e.lookup("ContractIdPreimage")],["executable",e.lookup("ContractExecutable")]]),e.struct("CreateContractArgsV2",[["contractIdPreimage",e.lookup("ContractIdPreimage")],["executable",e.lookup("ContractExecutable")],["constructorArgs",e.varArray(e.lookup("ScVal"),2147483647)]]),e.struct("InvokeContractArgs",[["contractAddress",e.lookup("ScAddress")],["functionName",e.lookup("ScSymbol")],["args",e.varArray(e.lookup("ScVal"),2147483647)]]),e.union("HostFunction",{switchOn:e.lookup("HostFunctionType"),switchName:"type",switches:[["hostFunctionTypeInvokeContract","invokeContract"],["hostFunctionTypeCreateContract","createContract"],["hostFunctionTypeUploadContractWasm","wasm"],["hostFunctionTypeCreateContractV2","createContractV2"]],arms:{invokeContract:e.lookup("InvokeContractArgs"),createContract:e.lookup("CreateContractArgs"),wasm:e.varOpaque(),createContractV2:e.lookup("CreateContractArgsV2")}}),e.enum("SorobanAuthorizedFunctionType",{sorobanAuthorizedFunctionTypeContractFn:0,sorobanAuthorizedFunctionTypeCreateContractHostFn:1,sorobanAuthorizedFunctionTypeCreateContractV2HostFn:2}),e.union("SorobanAuthorizedFunction",{switchOn:e.lookup("SorobanAuthorizedFunctionType"),switchName:"type",switches:[["sorobanAuthorizedFunctionTypeContractFn","contractFn"],["sorobanAuthorizedFunctionTypeCreateContractHostFn","createContractHostFn"],["sorobanAuthorizedFunctionTypeCreateContractV2HostFn","createContractV2HostFn"]],arms:{contractFn:e.lookup("InvokeContractArgs"),createContractHostFn:e.lookup("CreateContractArgs"),createContractV2HostFn:e.lookup("CreateContractArgsV2")}}),e.struct("SorobanAuthorizedInvocation",[["function",e.lookup("SorobanAuthorizedFunction")],["subInvocations",e.varArray(e.lookup("SorobanAuthorizedInvocation"),2147483647)]]),e.struct("SorobanAddressCredentials",[["address",e.lookup("ScAddress")],["nonce",e.lookup("Int64")],["signatureExpirationLedger",e.lookup("Uint32")],["signature",e.lookup("ScVal")]]),e.enum("SorobanCredentialsType",{sorobanCredentialsSourceAccount:0,sorobanCredentialsAddress:1}),e.union("SorobanCredentials",{switchOn:e.lookup("SorobanCredentialsType"),switchName:"type",switches:[["sorobanCredentialsSourceAccount",e.void()],["sorobanCredentialsAddress","address"]],arms:{address:e.lookup("SorobanAddressCredentials")}}),e.struct("SorobanAuthorizationEntry",[["credentials",e.lookup("SorobanCredentials")],["rootInvocation",e.lookup("SorobanAuthorizedInvocation")]]),e.struct("InvokeHostFunctionOp",[["hostFunction",e.lookup("HostFunction")],["auth",e.varArray(e.lookup("SorobanAuthorizationEntry"),2147483647)]]),e.struct("ExtendFootprintTtlOp",[["ext",e.lookup("ExtensionPoint")],["extendTo",e.lookup("Uint32")]]),e.struct("RestoreFootprintOp",[["ext",e.lookup("ExtensionPoint")]]),e.union("OperationBody",{switchOn:e.lookup("OperationType"),switchName:"type",switches:[["createAccount","createAccountOp"],["payment","paymentOp"],["pathPaymentStrictReceive","pathPaymentStrictReceiveOp"],["manageSellOffer","manageSellOfferOp"],["createPassiveSellOffer","createPassiveSellOfferOp"],["setOptions","setOptionsOp"],["changeTrust","changeTrustOp"],["allowTrust","allowTrustOp"],["accountMerge","destination"],["inflation",e.void()],["manageData","manageDataOp"],["bumpSequence","bumpSequenceOp"],["manageBuyOffer","manageBuyOfferOp"],["pathPaymentStrictSend","pathPaymentStrictSendOp"],["createClaimableBalance","createClaimableBalanceOp"],["claimClaimableBalance","claimClaimableBalanceOp"],["beginSponsoringFutureReserves","beginSponsoringFutureReservesOp"],["endSponsoringFutureReserves",e.void()],["revokeSponsorship","revokeSponsorshipOp"],["clawback","clawbackOp"],["clawbackClaimableBalance","clawbackClaimableBalanceOp"],["setTrustLineFlags","setTrustLineFlagsOp"],["liquidityPoolDeposit","liquidityPoolDepositOp"],["liquidityPoolWithdraw","liquidityPoolWithdrawOp"],["invokeHostFunction","invokeHostFunctionOp"],["extendFootprintTtl","extendFootprintTtlOp"],["restoreFootprint","restoreFootprintOp"]],arms:{createAccountOp:e.lookup("CreateAccountOp"),paymentOp:e.lookup("PaymentOp"),pathPaymentStrictReceiveOp:e.lookup("PathPaymentStrictReceiveOp"),manageSellOfferOp:e.lookup("ManageSellOfferOp"),createPassiveSellOfferOp:e.lookup("CreatePassiveSellOfferOp"),setOptionsOp:e.lookup("SetOptionsOp"),changeTrustOp:e.lookup("ChangeTrustOp"),allowTrustOp:e.lookup("AllowTrustOp"),destination:e.lookup("MuxedAccount"),manageDataOp:e.lookup("ManageDataOp"),bumpSequenceOp:e.lookup("BumpSequenceOp"),manageBuyOfferOp:e.lookup("ManageBuyOfferOp"),pathPaymentStrictSendOp:e.lookup("PathPaymentStrictSendOp"),createClaimableBalanceOp:e.lookup("CreateClaimableBalanceOp"),claimClaimableBalanceOp:e.lookup("ClaimClaimableBalanceOp"),beginSponsoringFutureReservesOp:e.lookup("BeginSponsoringFutureReservesOp"),revokeSponsorshipOp:e.lookup("RevokeSponsorshipOp"),clawbackOp:e.lookup("ClawbackOp"),clawbackClaimableBalanceOp:e.lookup("ClawbackClaimableBalanceOp"),setTrustLineFlagsOp:e.lookup("SetTrustLineFlagsOp"),liquidityPoolDepositOp:e.lookup("LiquidityPoolDepositOp"),liquidityPoolWithdrawOp:e.lookup("LiquidityPoolWithdrawOp"),invokeHostFunctionOp:e.lookup("InvokeHostFunctionOp"),extendFootprintTtlOp:e.lookup("ExtendFootprintTtlOp"),restoreFootprintOp:e.lookup("RestoreFootprintOp")}}),e.struct("Operation",[["sourceAccount",e.option(e.lookup("MuxedAccount"))],["body",e.lookup("OperationBody")]]),e.struct("HashIdPreimageOperationId",[["sourceAccount",e.lookup("AccountId")],["seqNum",e.lookup("SequenceNumber")],["opNum",e.lookup("Uint32")]]),e.struct("HashIdPreimageRevokeId",[["sourceAccount",e.lookup("AccountId")],["seqNum",e.lookup("SequenceNumber")],["opNum",e.lookup("Uint32")],["liquidityPoolId",e.lookup("PoolId")],["asset",e.lookup("Asset")]]),e.struct("HashIdPreimageContractId",[["networkId",e.lookup("Hash")],["contractIdPreimage",e.lookup("ContractIdPreimage")]]),e.struct("HashIdPreimageSorobanAuthorization",[["networkId",e.lookup("Hash")],["nonce",e.lookup("Int64")],["signatureExpirationLedger",e.lookup("Uint32")],["invocation",e.lookup("SorobanAuthorizedInvocation")]]),e.union("HashIdPreimage",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeOpId","operationId"],["envelopeTypePoolRevokeOpId","revokeId"],["envelopeTypeContractId","contractId"],["envelopeTypeSorobanAuthorization","sorobanAuthorization"]],arms:{operationId:e.lookup("HashIdPreimageOperationId"),revokeId:e.lookup("HashIdPreimageRevokeId"),contractId:e.lookup("HashIdPreimageContractId"),sorobanAuthorization:e.lookup("HashIdPreimageSorobanAuthorization")}}),e.enum("MemoType",{memoNone:0,memoText:1,memoId:2,memoHash:3,memoReturn:4}),e.union("Memo",{switchOn:e.lookup("MemoType"),switchName:"type",switches:[["memoNone",e.void()],["memoText","text"],["memoId","id"],["memoHash","hash"],["memoReturn","retHash"]],arms:{text:e.string(28),id:e.lookup("Uint64"),hash:e.lookup("Hash"),retHash:e.lookup("Hash")}}),e.struct("TimeBounds",[["minTime",e.lookup("TimePoint")],["maxTime",e.lookup("TimePoint")]]),e.struct("LedgerBounds",[["minLedger",e.lookup("Uint32")],["maxLedger",e.lookup("Uint32")]]),e.struct("PreconditionsV2",[["timeBounds",e.option(e.lookup("TimeBounds"))],["ledgerBounds",e.option(e.lookup("LedgerBounds"))],["minSeqNum",e.option(e.lookup("SequenceNumber"))],["minSeqAge",e.lookup("Duration")],["minSeqLedgerGap",e.lookup("Uint32")],["extraSigners",e.varArray(e.lookup("SignerKey"),2)]]),e.enum("PreconditionType",{precondNone:0,precondTime:1,precondV2:2}),e.union("Preconditions",{switchOn:e.lookup("PreconditionType"),switchName:"type",switches:[["precondNone",e.void()],["precondTime","timeBounds"],["precondV2","v2"]],arms:{timeBounds:e.lookup("TimeBounds"),v2:e.lookup("PreconditionsV2")}}),e.struct("LedgerFootprint",[["readOnly",e.varArray(e.lookup("LedgerKey"),2147483647)],["readWrite",e.varArray(e.lookup("LedgerKey"),2147483647)]]),e.enum("ArchivalProofType",{existence:0,nonexistence:1}),e.struct("ArchivalProofNode",[["index",e.lookup("Uint32")],["hash",e.lookup("Hash")]]),e.typedef("ProofLevel",e.varArray(e.lookup("ArchivalProofNode"),2147483647)),e.struct("NonexistenceProofBody",[["entriesToProve",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["proofLevels",e.varArray(e.lookup("ProofLevel"),2147483647)]]),e.struct("ExistenceProofBody",[["keysToProve",e.varArray(e.lookup("LedgerKey"),2147483647)],["lowBoundEntries",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["highBoundEntries",e.varArray(e.lookup("ColdArchiveBucketEntry"),2147483647)],["proofLevels",e.varArray(e.lookup("ProofLevel"),2147483647)]]),e.union("ArchivalProofBody",{switchOn:e.lookup("ArchivalProofType"),switchName:"t",switches:[["existence","nonexistenceProof"],["nonexistence","existenceProof"]],arms:{nonexistenceProof:e.lookup("NonexistenceProofBody"),existenceProof:e.lookup("ExistenceProofBody")}}),e.struct("ArchivalProof",[["epoch",e.lookup("Uint32")],["body",e.lookup("ArchivalProofBody")]]),e.struct("SorobanResources",[["footprint",e.lookup("LedgerFootprint")],["instructions",e.lookup("Uint32")],["readBytes",e.lookup("Uint32")],["writeBytes",e.lookup("Uint32")]]),e.struct("SorobanTransactionData",[["ext",e.lookup("ExtensionPoint")],["resources",e.lookup("SorobanResources")],["resourceFee",e.lookup("Int64")]]),e.union("TransactionV0Ext",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionV0",[["sourceAccountEd25519",e.lookup("Uint256")],["fee",e.lookup("Uint32")],["seqNum",e.lookup("SequenceNumber")],["timeBounds",e.option(e.lookup("TimeBounds"))],["memo",e.lookup("Memo")],["operations",e.varArray(e.lookup("Operation"),e.lookup("MAX_OPS_PER_TX"))],["ext",e.lookup("TransactionV0Ext")]]),e.struct("TransactionV0Envelope",[["tx",e.lookup("TransactionV0")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("TransactionExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()],[1,"sorobanData"]],arms:{sorobanData:e.lookup("SorobanTransactionData")}}),e.struct("Transaction",[["sourceAccount",e.lookup("MuxedAccount")],["fee",e.lookup("Uint32")],["seqNum",e.lookup("SequenceNumber")],["cond",e.lookup("Preconditions")],["memo",e.lookup("Memo")],["operations",e.varArray(e.lookup("Operation"),e.lookup("MAX_OPS_PER_TX"))],["ext",e.lookup("TransactionExt")]]),e.struct("TransactionV1Envelope",[["tx",e.lookup("Transaction")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("FeeBumpTransactionInnerTx",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTx","v1"]],arms:{v1:e.lookup("TransactionV1Envelope")}}),e.union("FeeBumpTransactionExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("FeeBumpTransaction",[["feeSource",e.lookup("MuxedAccount")],["fee",e.lookup("Int64")],["innerTx",e.lookup("FeeBumpTransactionInnerTx")],["ext",e.lookup("FeeBumpTransactionExt")]]),e.struct("FeeBumpTransactionEnvelope",[["tx",e.lookup("FeeBumpTransaction")],["signatures",e.varArray(e.lookup("DecoratedSignature"),20)]]),e.union("TransactionEnvelope",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTxV0","v0"],["envelopeTypeTx","v1"],["envelopeTypeTxFeeBump","feeBump"]],arms:{v0:e.lookup("TransactionV0Envelope"),v1:e.lookup("TransactionV1Envelope"),feeBump:e.lookup("FeeBumpTransactionEnvelope")}}),e.union("TransactionSignaturePayloadTaggedTransaction",{switchOn:e.lookup("EnvelopeType"),switchName:"type",switches:[["envelopeTypeTx","tx"],["envelopeTypeTxFeeBump","feeBump"]],arms:{tx:e.lookup("Transaction"),feeBump:e.lookup("FeeBumpTransaction")}}),e.struct("TransactionSignaturePayload",[["networkId",e.lookup("Hash")],["taggedTransaction",e.lookup("TransactionSignaturePayloadTaggedTransaction")]]),e.enum("ClaimAtomType",{claimAtomTypeV0:0,claimAtomTypeOrderBook:1,claimAtomTypeLiquidityPool:2}),e.struct("ClaimOfferAtomV0",[["sellerEd25519",e.lookup("Uint256")],["offerId",e.lookup("Int64")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.struct("ClaimOfferAtom",[["sellerId",e.lookup("AccountId")],["offerId",e.lookup("Int64")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.struct("ClaimLiquidityAtom",[["liquidityPoolId",e.lookup("PoolId")],["assetSold",e.lookup("Asset")],["amountSold",e.lookup("Int64")],["assetBought",e.lookup("Asset")],["amountBought",e.lookup("Int64")]]),e.union("ClaimAtom",{switchOn:e.lookup("ClaimAtomType"),switchName:"type",switches:[["claimAtomTypeV0","v0"],["claimAtomTypeOrderBook","orderBook"],["claimAtomTypeLiquidityPool","liquidityPool"]],arms:{v0:e.lookup("ClaimOfferAtomV0"),orderBook:e.lookup("ClaimOfferAtom"),liquidityPool:e.lookup("ClaimLiquidityAtom")}}),e.enum("CreateAccountResultCode",{createAccountSuccess:0,createAccountMalformed:-1,createAccountUnderfunded:-2,createAccountLowReserve:-3,createAccountAlreadyExist:-4}),e.union("CreateAccountResult",{switchOn:e.lookup("CreateAccountResultCode"),switchName:"code",switches:[["createAccountSuccess",e.void()],["createAccountMalformed",e.void()],["createAccountUnderfunded",e.void()],["createAccountLowReserve",e.void()],["createAccountAlreadyExist",e.void()]],arms:{}}),e.enum("PaymentResultCode",{paymentSuccess:0,paymentMalformed:-1,paymentUnderfunded:-2,paymentSrcNoTrust:-3,paymentSrcNotAuthorized:-4,paymentNoDestination:-5,paymentNoTrust:-6,paymentNotAuthorized:-7,paymentLineFull:-8,paymentNoIssuer:-9}),e.union("PaymentResult",{switchOn:e.lookup("PaymentResultCode"),switchName:"code",switches:[["paymentSuccess",e.void()],["paymentMalformed",e.void()],["paymentUnderfunded",e.void()],["paymentSrcNoTrust",e.void()],["paymentSrcNotAuthorized",e.void()],["paymentNoDestination",e.void()],["paymentNoTrust",e.void()],["paymentNotAuthorized",e.void()],["paymentLineFull",e.void()],["paymentNoIssuer",e.void()]],arms:{}}),e.enum("PathPaymentStrictReceiveResultCode",{pathPaymentStrictReceiveSuccess:0,pathPaymentStrictReceiveMalformed:-1,pathPaymentStrictReceiveUnderfunded:-2,pathPaymentStrictReceiveSrcNoTrust:-3,pathPaymentStrictReceiveSrcNotAuthorized:-4,pathPaymentStrictReceiveNoDestination:-5,pathPaymentStrictReceiveNoTrust:-6,pathPaymentStrictReceiveNotAuthorized:-7,pathPaymentStrictReceiveLineFull:-8,pathPaymentStrictReceiveNoIssuer:-9,pathPaymentStrictReceiveTooFewOffers:-10,pathPaymentStrictReceiveOfferCrossSelf:-11,pathPaymentStrictReceiveOverSendmax:-12}),e.struct("SimplePaymentResult",[["destination",e.lookup("AccountId")],["asset",e.lookup("Asset")],["amount",e.lookup("Int64")]]),e.struct("PathPaymentStrictReceiveResultSuccess",[["offers",e.varArray(e.lookup("ClaimAtom"),2147483647)],["last",e.lookup("SimplePaymentResult")]]),e.union("PathPaymentStrictReceiveResult",{switchOn:e.lookup("PathPaymentStrictReceiveResultCode"),switchName:"code",switches:[["pathPaymentStrictReceiveSuccess","success"],["pathPaymentStrictReceiveMalformed",e.void()],["pathPaymentStrictReceiveUnderfunded",e.void()],["pathPaymentStrictReceiveSrcNoTrust",e.void()],["pathPaymentStrictReceiveSrcNotAuthorized",e.void()],["pathPaymentStrictReceiveNoDestination",e.void()],["pathPaymentStrictReceiveNoTrust",e.void()],["pathPaymentStrictReceiveNotAuthorized",e.void()],["pathPaymentStrictReceiveLineFull",e.void()],["pathPaymentStrictReceiveNoIssuer","noIssuer"],["pathPaymentStrictReceiveTooFewOffers",e.void()],["pathPaymentStrictReceiveOfferCrossSelf",e.void()],["pathPaymentStrictReceiveOverSendmax",e.void()]],arms:{success:e.lookup("PathPaymentStrictReceiveResultSuccess"),noIssuer:e.lookup("Asset")}}),e.enum("PathPaymentStrictSendResultCode",{pathPaymentStrictSendSuccess:0,pathPaymentStrictSendMalformed:-1,pathPaymentStrictSendUnderfunded:-2,pathPaymentStrictSendSrcNoTrust:-3,pathPaymentStrictSendSrcNotAuthorized:-4,pathPaymentStrictSendNoDestination:-5,pathPaymentStrictSendNoTrust:-6,pathPaymentStrictSendNotAuthorized:-7,pathPaymentStrictSendLineFull:-8,pathPaymentStrictSendNoIssuer:-9,pathPaymentStrictSendTooFewOffers:-10,pathPaymentStrictSendOfferCrossSelf:-11,pathPaymentStrictSendUnderDestmin:-12}),e.struct("PathPaymentStrictSendResultSuccess",[["offers",e.varArray(e.lookup("ClaimAtom"),2147483647)],["last",e.lookup("SimplePaymentResult")]]),e.union("PathPaymentStrictSendResult",{switchOn:e.lookup("PathPaymentStrictSendResultCode"),switchName:"code",switches:[["pathPaymentStrictSendSuccess","success"],["pathPaymentStrictSendMalformed",e.void()],["pathPaymentStrictSendUnderfunded",e.void()],["pathPaymentStrictSendSrcNoTrust",e.void()],["pathPaymentStrictSendSrcNotAuthorized",e.void()],["pathPaymentStrictSendNoDestination",e.void()],["pathPaymentStrictSendNoTrust",e.void()],["pathPaymentStrictSendNotAuthorized",e.void()],["pathPaymentStrictSendLineFull",e.void()],["pathPaymentStrictSendNoIssuer","noIssuer"],["pathPaymentStrictSendTooFewOffers",e.void()],["pathPaymentStrictSendOfferCrossSelf",e.void()],["pathPaymentStrictSendUnderDestmin",e.void()]],arms:{success:e.lookup("PathPaymentStrictSendResultSuccess"),noIssuer:e.lookup("Asset")}}),e.enum("ManageSellOfferResultCode",{manageSellOfferSuccess:0,manageSellOfferMalformed:-1,manageSellOfferSellNoTrust:-2,manageSellOfferBuyNoTrust:-3,manageSellOfferSellNotAuthorized:-4,manageSellOfferBuyNotAuthorized:-5,manageSellOfferLineFull:-6,manageSellOfferUnderfunded:-7,manageSellOfferCrossSelf:-8,manageSellOfferSellNoIssuer:-9,manageSellOfferBuyNoIssuer:-10,manageSellOfferNotFound:-11,manageSellOfferLowReserve:-12}),e.enum("ManageOfferEffect",{manageOfferCreated:0,manageOfferUpdated:1,manageOfferDeleted:2}),e.union("ManageOfferSuccessResultOffer",{switchOn:e.lookup("ManageOfferEffect"),switchName:"effect",switches:[["manageOfferCreated","offer"],["manageOfferUpdated","offer"],["manageOfferDeleted",e.void()]],arms:{offer:e.lookup("OfferEntry")}}),e.struct("ManageOfferSuccessResult",[["offersClaimed",e.varArray(e.lookup("ClaimAtom"),2147483647)],["offer",e.lookup("ManageOfferSuccessResultOffer")]]),e.union("ManageSellOfferResult",{switchOn:e.lookup("ManageSellOfferResultCode"),switchName:"code",switches:[["manageSellOfferSuccess","success"],["manageSellOfferMalformed",e.void()],["manageSellOfferSellNoTrust",e.void()],["manageSellOfferBuyNoTrust",e.void()],["manageSellOfferSellNotAuthorized",e.void()],["manageSellOfferBuyNotAuthorized",e.void()],["manageSellOfferLineFull",e.void()],["manageSellOfferUnderfunded",e.void()],["manageSellOfferCrossSelf",e.void()],["manageSellOfferSellNoIssuer",e.void()],["manageSellOfferBuyNoIssuer",e.void()],["manageSellOfferNotFound",e.void()],["manageSellOfferLowReserve",e.void()]],arms:{success:e.lookup("ManageOfferSuccessResult")}}),e.enum("ManageBuyOfferResultCode",{manageBuyOfferSuccess:0,manageBuyOfferMalformed:-1,manageBuyOfferSellNoTrust:-2,manageBuyOfferBuyNoTrust:-3,manageBuyOfferSellNotAuthorized:-4,manageBuyOfferBuyNotAuthorized:-5,manageBuyOfferLineFull:-6,manageBuyOfferUnderfunded:-7,manageBuyOfferCrossSelf:-8,manageBuyOfferSellNoIssuer:-9,manageBuyOfferBuyNoIssuer:-10,manageBuyOfferNotFound:-11,manageBuyOfferLowReserve:-12}),e.union("ManageBuyOfferResult",{switchOn:e.lookup("ManageBuyOfferResultCode"),switchName:"code",switches:[["manageBuyOfferSuccess","success"],["manageBuyOfferMalformed",e.void()],["manageBuyOfferSellNoTrust",e.void()],["manageBuyOfferBuyNoTrust",e.void()],["manageBuyOfferSellNotAuthorized",e.void()],["manageBuyOfferBuyNotAuthorized",e.void()],["manageBuyOfferLineFull",e.void()],["manageBuyOfferUnderfunded",e.void()],["manageBuyOfferCrossSelf",e.void()],["manageBuyOfferSellNoIssuer",e.void()],["manageBuyOfferBuyNoIssuer",e.void()],["manageBuyOfferNotFound",e.void()],["manageBuyOfferLowReserve",e.void()]],arms:{success:e.lookup("ManageOfferSuccessResult")}}),e.enum("SetOptionsResultCode",{setOptionsSuccess:0,setOptionsLowReserve:-1,setOptionsTooManySigners:-2,setOptionsBadFlags:-3,setOptionsInvalidInflation:-4,setOptionsCantChange:-5,setOptionsUnknownFlag:-6,setOptionsThresholdOutOfRange:-7,setOptionsBadSigner:-8,setOptionsInvalidHomeDomain:-9,setOptionsAuthRevocableRequired:-10}),e.union("SetOptionsResult",{switchOn:e.lookup("SetOptionsResultCode"),switchName:"code",switches:[["setOptionsSuccess",e.void()],["setOptionsLowReserve",e.void()],["setOptionsTooManySigners",e.void()],["setOptionsBadFlags",e.void()],["setOptionsInvalidInflation",e.void()],["setOptionsCantChange",e.void()],["setOptionsUnknownFlag",e.void()],["setOptionsThresholdOutOfRange",e.void()],["setOptionsBadSigner",e.void()],["setOptionsInvalidHomeDomain",e.void()],["setOptionsAuthRevocableRequired",e.void()]],arms:{}}),e.enum("ChangeTrustResultCode",{changeTrustSuccess:0,changeTrustMalformed:-1,changeTrustNoIssuer:-2,changeTrustInvalidLimit:-3,changeTrustLowReserve:-4,changeTrustSelfNotAllowed:-5,changeTrustTrustLineMissing:-6,changeTrustCannotDelete:-7,changeTrustNotAuthMaintainLiabilities:-8}),e.union("ChangeTrustResult",{switchOn:e.lookup("ChangeTrustResultCode"),switchName:"code",switches:[["changeTrustSuccess",e.void()],["changeTrustMalformed",e.void()],["changeTrustNoIssuer",e.void()],["changeTrustInvalidLimit",e.void()],["changeTrustLowReserve",e.void()],["changeTrustSelfNotAllowed",e.void()],["changeTrustTrustLineMissing",e.void()],["changeTrustCannotDelete",e.void()],["changeTrustNotAuthMaintainLiabilities",e.void()]],arms:{}}),e.enum("AllowTrustResultCode",{allowTrustSuccess:0,allowTrustMalformed:-1,allowTrustNoTrustLine:-2,allowTrustTrustNotRequired:-3,allowTrustCantRevoke:-4,allowTrustSelfNotAllowed:-5,allowTrustLowReserve:-6}),e.union("AllowTrustResult",{switchOn:e.lookup("AllowTrustResultCode"),switchName:"code",switches:[["allowTrustSuccess",e.void()],["allowTrustMalformed",e.void()],["allowTrustNoTrustLine",e.void()],["allowTrustTrustNotRequired",e.void()],["allowTrustCantRevoke",e.void()],["allowTrustSelfNotAllowed",e.void()],["allowTrustLowReserve",e.void()]],arms:{}}),e.enum("AccountMergeResultCode",{accountMergeSuccess:0,accountMergeMalformed:-1,accountMergeNoAccount:-2,accountMergeImmutableSet:-3,accountMergeHasSubEntries:-4,accountMergeSeqnumTooFar:-5,accountMergeDestFull:-6,accountMergeIsSponsor:-7}),e.union("AccountMergeResult",{switchOn:e.lookup("AccountMergeResultCode"),switchName:"code",switches:[["accountMergeSuccess","sourceAccountBalance"],["accountMergeMalformed",e.void()],["accountMergeNoAccount",e.void()],["accountMergeImmutableSet",e.void()],["accountMergeHasSubEntries",e.void()],["accountMergeSeqnumTooFar",e.void()],["accountMergeDestFull",e.void()],["accountMergeIsSponsor",e.void()]],arms:{sourceAccountBalance:e.lookup("Int64")}}),e.enum("InflationResultCode",{inflationSuccess:0,inflationNotTime:-1}),e.struct("InflationPayout",[["destination",e.lookup("AccountId")],["amount",e.lookup("Int64")]]),e.union("InflationResult",{switchOn:e.lookup("InflationResultCode"),switchName:"code",switches:[["inflationSuccess","payouts"],["inflationNotTime",e.void()]],arms:{payouts:e.varArray(e.lookup("InflationPayout"),2147483647)}}),e.enum("ManageDataResultCode",{manageDataSuccess:0,manageDataNotSupportedYet:-1,manageDataNameNotFound:-2,manageDataLowReserve:-3,manageDataInvalidName:-4}),e.union("ManageDataResult",{switchOn:e.lookup("ManageDataResultCode"),switchName:"code",switches:[["manageDataSuccess",e.void()],["manageDataNotSupportedYet",e.void()],["manageDataNameNotFound",e.void()],["manageDataLowReserve",e.void()],["manageDataInvalidName",e.void()]],arms:{}}),e.enum("BumpSequenceResultCode",{bumpSequenceSuccess:0,bumpSequenceBadSeq:-1}),e.union("BumpSequenceResult",{switchOn:e.lookup("BumpSequenceResultCode"),switchName:"code",switches:[["bumpSequenceSuccess",e.void()],["bumpSequenceBadSeq",e.void()]],arms:{}}),e.enum("CreateClaimableBalanceResultCode",{createClaimableBalanceSuccess:0,createClaimableBalanceMalformed:-1,createClaimableBalanceLowReserve:-2,createClaimableBalanceNoTrust:-3,createClaimableBalanceNotAuthorized:-4,createClaimableBalanceUnderfunded:-5}),e.union("CreateClaimableBalanceResult",{switchOn:e.lookup("CreateClaimableBalanceResultCode"),switchName:"code",switches:[["createClaimableBalanceSuccess","balanceId"],["createClaimableBalanceMalformed",e.void()],["createClaimableBalanceLowReserve",e.void()],["createClaimableBalanceNoTrust",e.void()],["createClaimableBalanceNotAuthorized",e.void()],["createClaimableBalanceUnderfunded",e.void()]],arms:{balanceId:e.lookup("ClaimableBalanceId")}}),e.enum("ClaimClaimableBalanceResultCode",{claimClaimableBalanceSuccess:0,claimClaimableBalanceDoesNotExist:-1,claimClaimableBalanceCannotClaim:-2,claimClaimableBalanceLineFull:-3,claimClaimableBalanceNoTrust:-4,claimClaimableBalanceNotAuthorized:-5}),e.union("ClaimClaimableBalanceResult",{switchOn:e.lookup("ClaimClaimableBalanceResultCode"),switchName:"code",switches:[["claimClaimableBalanceSuccess",e.void()],["claimClaimableBalanceDoesNotExist",e.void()],["claimClaimableBalanceCannotClaim",e.void()],["claimClaimableBalanceLineFull",e.void()],["claimClaimableBalanceNoTrust",e.void()],["claimClaimableBalanceNotAuthorized",e.void()]],arms:{}}),e.enum("BeginSponsoringFutureReservesResultCode",{beginSponsoringFutureReservesSuccess:0,beginSponsoringFutureReservesMalformed:-1,beginSponsoringFutureReservesAlreadySponsored:-2,beginSponsoringFutureReservesRecursive:-3}),e.union("BeginSponsoringFutureReservesResult",{switchOn:e.lookup("BeginSponsoringFutureReservesResultCode"),switchName:"code",switches:[["beginSponsoringFutureReservesSuccess",e.void()],["beginSponsoringFutureReservesMalformed",e.void()],["beginSponsoringFutureReservesAlreadySponsored",e.void()],["beginSponsoringFutureReservesRecursive",e.void()]],arms:{}}),e.enum("EndSponsoringFutureReservesResultCode",{endSponsoringFutureReservesSuccess:0,endSponsoringFutureReservesNotSponsored:-1}),e.union("EndSponsoringFutureReservesResult",{switchOn:e.lookup("EndSponsoringFutureReservesResultCode"),switchName:"code",switches:[["endSponsoringFutureReservesSuccess",e.void()],["endSponsoringFutureReservesNotSponsored",e.void()]],arms:{}}),e.enum("RevokeSponsorshipResultCode",{revokeSponsorshipSuccess:0,revokeSponsorshipDoesNotExist:-1,revokeSponsorshipNotSponsor:-2,revokeSponsorshipLowReserve:-3,revokeSponsorshipOnlyTransferable:-4,revokeSponsorshipMalformed:-5}),e.union("RevokeSponsorshipResult",{switchOn:e.lookup("RevokeSponsorshipResultCode"),switchName:"code",switches:[["revokeSponsorshipSuccess",e.void()],["revokeSponsorshipDoesNotExist",e.void()],["revokeSponsorshipNotSponsor",e.void()],["revokeSponsorshipLowReserve",e.void()],["revokeSponsorshipOnlyTransferable",e.void()],["revokeSponsorshipMalformed",e.void()]],arms:{}}),e.enum("ClawbackResultCode",{clawbackSuccess:0,clawbackMalformed:-1,clawbackNotClawbackEnabled:-2,clawbackNoTrust:-3,clawbackUnderfunded:-4}),e.union("ClawbackResult",{switchOn:e.lookup("ClawbackResultCode"),switchName:"code",switches:[["clawbackSuccess",e.void()],["clawbackMalformed",e.void()],["clawbackNotClawbackEnabled",e.void()],["clawbackNoTrust",e.void()],["clawbackUnderfunded",e.void()]],arms:{}}),e.enum("ClawbackClaimableBalanceResultCode",{clawbackClaimableBalanceSuccess:0,clawbackClaimableBalanceDoesNotExist:-1,clawbackClaimableBalanceNotIssuer:-2,clawbackClaimableBalanceNotClawbackEnabled:-3}),e.union("ClawbackClaimableBalanceResult",{switchOn:e.lookup("ClawbackClaimableBalanceResultCode"),switchName:"code",switches:[["clawbackClaimableBalanceSuccess",e.void()],["clawbackClaimableBalanceDoesNotExist",e.void()],["clawbackClaimableBalanceNotIssuer",e.void()],["clawbackClaimableBalanceNotClawbackEnabled",e.void()]],arms:{}}),e.enum("SetTrustLineFlagsResultCode",{setTrustLineFlagsSuccess:0,setTrustLineFlagsMalformed:-1,setTrustLineFlagsNoTrustLine:-2,setTrustLineFlagsCantRevoke:-3,setTrustLineFlagsInvalidState:-4,setTrustLineFlagsLowReserve:-5}),e.union("SetTrustLineFlagsResult",{switchOn:e.lookup("SetTrustLineFlagsResultCode"),switchName:"code",switches:[["setTrustLineFlagsSuccess",e.void()],["setTrustLineFlagsMalformed",e.void()],["setTrustLineFlagsNoTrustLine",e.void()],["setTrustLineFlagsCantRevoke",e.void()],["setTrustLineFlagsInvalidState",e.void()],["setTrustLineFlagsLowReserve",e.void()]],arms:{}}),e.enum("LiquidityPoolDepositResultCode",{liquidityPoolDepositSuccess:0,liquidityPoolDepositMalformed:-1,liquidityPoolDepositNoTrust:-2,liquidityPoolDepositNotAuthorized:-3,liquidityPoolDepositUnderfunded:-4,liquidityPoolDepositLineFull:-5,liquidityPoolDepositBadPrice:-6,liquidityPoolDepositPoolFull:-7}),e.union("LiquidityPoolDepositResult",{switchOn:e.lookup("LiquidityPoolDepositResultCode"),switchName:"code",switches:[["liquidityPoolDepositSuccess",e.void()],["liquidityPoolDepositMalformed",e.void()],["liquidityPoolDepositNoTrust",e.void()],["liquidityPoolDepositNotAuthorized",e.void()],["liquidityPoolDepositUnderfunded",e.void()],["liquidityPoolDepositLineFull",e.void()],["liquidityPoolDepositBadPrice",e.void()],["liquidityPoolDepositPoolFull",e.void()]],arms:{}}),e.enum("LiquidityPoolWithdrawResultCode",{liquidityPoolWithdrawSuccess:0,liquidityPoolWithdrawMalformed:-1,liquidityPoolWithdrawNoTrust:-2,liquidityPoolWithdrawUnderfunded:-3,liquidityPoolWithdrawLineFull:-4,liquidityPoolWithdrawUnderMinimum:-5}),e.union("LiquidityPoolWithdrawResult",{switchOn:e.lookup("LiquidityPoolWithdrawResultCode"),switchName:"code",switches:[["liquidityPoolWithdrawSuccess",e.void()],["liquidityPoolWithdrawMalformed",e.void()],["liquidityPoolWithdrawNoTrust",e.void()],["liquidityPoolWithdrawUnderfunded",e.void()],["liquidityPoolWithdrawLineFull",e.void()],["liquidityPoolWithdrawUnderMinimum",e.void()]],arms:{}}),e.enum("InvokeHostFunctionResultCode",{invokeHostFunctionSuccess:0,invokeHostFunctionMalformed:-1,invokeHostFunctionTrapped:-2,invokeHostFunctionResourceLimitExceeded:-3,invokeHostFunctionEntryArchived:-4,invokeHostFunctionInsufficientRefundableFee:-5}),e.union("InvokeHostFunctionResult",{switchOn:e.lookup("InvokeHostFunctionResultCode"),switchName:"code",switches:[["invokeHostFunctionSuccess","success"],["invokeHostFunctionMalformed",e.void()],["invokeHostFunctionTrapped",e.void()],["invokeHostFunctionResourceLimitExceeded",e.void()],["invokeHostFunctionEntryArchived",e.void()],["invokeHostFunctionInsufficientRefundableFee",e.void()]],arms:{success:e.lookup("Hash")}}),e.enum("ExtendFootprintTtlResultCode",{extendFootprintTtlSuccess:0,extendFootprintTtlMalformed:-1,extendFootprintTtlResourceLimitExceeded:-2,extendFootprintTtlInsufficientRefundableFee:-3}),e.union("ExtendFootprintTtlResult",{switchOn:e.lookup("ExtendFootprintTtlResultCode"),switchName:"code",switches:[["extendFootprintTtlSuccess",e.void()],["extendFootprintTtlMalformed",e.void()],["extendFootprintTtlResourceLimitExceeded",e.void()],["extendFootprintTtlInsufficientRefundableFee",e.void()]],arms:{}}),e.enum("RestoreFootprintResultCode",{restoreFootprintSuccess:0,restoreFootprintMalformed:-1,restoreFootprintResourceLimitExceeded:-2,restoreFootprintInsufficientRefundableFee:-3}),e.union("RestoreFootprintResult",{switchOn:e.lookup("RestoreFootprintResultCode"),switchName:"code",switches:[["restoreFootprintSuccess",e.void()],["restoreFootprintMalformed",e.void()],["restoreFootprintResourceLimitExceeded",e.void()],["restoreFootprintInsufficientRefundableFee",e.void()]],arms:{}}),e.enum("OperationResultCode",{opInner:0,opBadAuth:-1,opNoAccount:-2,opNotSupported:-3,opTooManySubentries:-4,opExceededWorkLimit:-5,opTooManySponsoring:-6}),e.union("OperationResultTr",{switchOn:e.lookup("OperationType"),switchName:"type",switches:[["createAccount","createAccountResult"],["payment","paymentResult"],["pathPaymentStrictReceive","pathPaymentStrictReceiveResult"],["manageSellOffer","manageSellOfferResult"],["createPassiveSellOffer","createPassiveSellOfferResult"],["setOptions","setOptionsResult"],["changeTrust","changeTrustResult"],["allowTrust","allowTrustResult"],["accountMerge","accountMergeResult"],["inflation","inflationResult"],["manageData","manageDataResult"],["bumpSequence","bumpSeqResult"],["manageBuyOffer","manageBuyOfferResult"],["pathPaymentStrictSend","pathPaymentStrictSendResult"],["createClaimableBalance","createClaimableBalanceResult"],["claimClaimableBalance","claimClaimableBalanceResult"],["beginSponsoringFutureReserves","beginSponsoringFutureReservesResult"],["endSponsoringFutureReserves","endSponsoringFutureReservesResult"],["revokeSponsorship","revokeSponsorshipResult"],["clawback","clawbackResult"],["clawbackClaimableBalance","clawbackClaimableBalanceResult"],["setTrustLineFlags","setTrustLineFlagsResult"],["liquidityPoolDeposit","liquidityPoolDepositResult"],["liquidityPoolWithdraw","liquidityPoolWithdrawResult"],["invokeHostFunction","invokeHostFunctionResult"],["extendFootprintTtl","extendFootprintTtlResult"],["restoreFootprint","restoreFootprintResult"]],arms:{createAccountResult:e.lookup("CreateAccountResult"),paymentResult:e.lookup("PaymentResult"),pathPaymentStrictReceiveResult:e.lookup("PathPaymentStrictReceiveResult"),manageSellOfferResult:e.lookup("ManageSellOfferResult"),createPassiveSellOfferResult:e.lookup("ManageSellOfferResult"),setOptionsResult:e.lookup("SetOptionsResult"),changeTrustResult:e.lookup("ChangeTrustResult"),allowTrustResult:e.lookup("AllowTrustResult"),accountMergeResult:e.lookup("AccountMergeResult"),inflationResult:e.lookup("InflationResult"),manageDataResult:e.lookup("ManageDataResult"),bumpSeqResult:e.lookup("BumpSequenceResult"),manageBuyOfferResult:e.lookup("ManageBuyOfferResult"),pathPaymentStrictSendResult:e.lookup("PathPaymentStrictSendResult"),createClaimableBalanceResult:e.lookup("CreateClaimableBalanceResult"),claimClaimableBalanceResult:e.lookup("ClaimClaimableBalanceResult"),beginSponsoringFutureReservesResult:e.lookup("BeginSponsoringFutureReservesResult"),endSponsoringFutureReservesResult:e.lookup("EndSponsoringFutureReservesResult"),revokeSponsorshipResult:e.lookup("RevokeSponsorshipResult"),clawbackResult:e.lookup("ClawbackResult"),clawbackClaimableBalanceResult:e.lookup("ClawbackClaimableBalanceResult"),setTrustLineFlagsResult:e.lookup("SetTrustLineFlagsResult"),liquidityPoolDepositResult:e.lookup("LiquidityPoolDepositResult"),liquidityPoolWithdrawResult:e.lookup("LiquidityPoolWithdrawResult"),invokeHostFunctionResult:e.lookup("InvokeHostFunctionResult"),extendFootprintTtlResult:e.lookup("ExtendFootprintTtlResult"),restoreFootprintResult:e.lookup("RestoreFootprintResult")}}),e.union("OperationResult",{switchOn:e.lookup("OperationResultCode"),switchName:"code",switches:[["opInner","tr"],["opBadAuth",e.void()],["opNoAccount",e.void()],["opNotSupported",e.void()],["opTooManySubentries",e.void()],["opExceededWorkLimit",e.void()],["opTooManySponsoring",e.void()]],arms:{tr:e.lookup("OperationResultTr")}}),e.enum("TransactionResultCode",{txFeeBumpInnerSuccess:1,txSuccess:0,txFailed:-1,txTooEarly:-2,txTooLate:-3,txMissingOperation:-4,txBadSeq:-5,txBadAuth:-6,txInsufficientBalance:-7,txNoAccount:-8,txInsufficientFee:-9,txBadAuthExtra:-10,txInternalError:-11,txNotSupported:-12,txFeeBumpInnerFailed:-13,txBadSponsorship:-14,txBadMinSeqAgeOrGap:-15,txMalformed:-16,txSorobanInvalid:-17}),e.union("InnerTransactionResultResult",{switchOn:e.lookup("TransactionResultCode"),switchName:"code",switches:[["txSuccess","results"],["txFailed","results"],["txTooEarly",e.void()],["txTooLate",e.void()],["txMissingOperation",e.void()],["txBadSeq",e.void()],["txBadAuth",e.void()],["txInsufficientBalance",e.void()],["txNoAccount",e.void()],["txInsufficientFee",e.void()],["txBadAuthExtra",e.void()],["txInternalError",e.void()],["txNotSupported",e.void()],["txBadSponsorship",e.void()],["txBadMinSeqAgeOrGap",e.void()],["txMalformed",e.void()],["txSorobanInvalid",e.void()]],arms:{results:e.varArray(e.lookup("OperationResult"),2147483647)}}),e.union("InnerTransactionResultExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("InnerTransactionResult",[["feeCharged",e.lookup("Int64")],["result",e.lookup("InnerTransactionResultResult")],["ext",e.lookup("InnerTransactionResultExt")]]),e.struct("InnerTransactionResultPair",[["transactionHash",e.lookup("Hash")],["result",e.lookup("InnerTransactionResult")]]),e.union("TransactionResultResult",{switchOn:e.lookup("TransactionResultCode"),switchName:"code",switches:[["txFeeBumpInnerSuccess","innerResultPair"],["txFeeBumpInnerFailed","innerResultPair"],["txSuccess","results"],["txFailed","results"],["txTooEarly",e.void()],["txTooLate",e.void()],["txMissingOperation",e.void()],["txBadSeq",e.void()],["txBadAuth",e.void()],["txInsufficientBalance",e.void()],["txNoAccount",e.void()],["txInsufficientFee",e.void()],["txBadAuthExtra",e.void()],["txInternalError",e.void()],["txNotSupported",e.void()],["txBadSponsorship",e.void()],["txBadMinSeqAgeOrGap",e.void()],["txMalformed",e.void()],["txSorobanInvalid",e.void()]],arms:{innerResultPair:e.lookup("InnerTransactionResultPair"),results:e.varArray(e.lookup("OperationResult"),2147483647)}}),e.union("TransactionResultExt",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.struct("TransactionResult",[["feeCharged",e.lookup("Int64")],["result",e.lookup("TransactionResultResult")],["ext",e.lookup("TransactionResultExt")]]),e.typedef("Hash",e.opaque(32)),e.typedef("Uint256",e.opaque(32)),e.typedef("Uint32",e.uint()),e.typedef("Int32",e.int()),e.typedef("Uint64",e.uhyper()),e.typedef("Int64",e.hyper()),e.typedef("TimePoint",e.lookup("Uint64")),e.typedef("Duration",e.lookup("Uint64")),e.union("ExtensionPoint",{switchOn:e.int(),switchName:"v",switches:[[0,e.void()]],arms:{}}),e.enum("CryptoKeyType",{keyTypeEd25519:0,keyTypePreAuthTx:1,keyTypeHashX:2,keyTypeEd25519SignedPayload:3,keyTypeMuxedEd25519:256}),e.enum("PublicKeyType",{publicKeyTypeEd25519:0}),e.enum("SignerKeyType",{signerKeyTypeEd25519:0,signerKeyTypePreAuthTx:1,signerKeyTypeHashX:2,signerKeyTypeEd25519SignedPayload:3}),e.union("PublicKey",{switchOn:e.lookup("PublicKeyType"),switchName:"type",switches:[["publicKeyTypeEd25519","ed25519"]],arms:{ed25519:e.lookup("Uint256")}}),e.struct("SignerKeyEd25519SignedPayload",[["ed25519",e.lookup("Uint256")],["payload",e.varOpaque(64)]]),e.union("SignerKey",{switchOn:e.lookup("SignerKeyType"),switchName:"type",switches:[["signerKeyTypeEd25519","ed25519"],["signerKeyTypePreAuthTx","preAuthTx"],["signerKeyTypeHashX","hashX"],["signerKeyTypeEd25519SignedPayload","ed25519SignedPayload"]],arms:{ed25519:e.lookup("Uint256"),preAuthTx:e.lookup("Uint256"),hashX:e.lookup("Uint256"),ed25519SignedPayload:e.lookup("SignerKeyEd25519SignedPayload")}}),e.typedef("Signature",e.varOpaque(64)),e.typedef("SignatureHint",e.opaque(4)),e.typedef("NodeId",e.lookup("PublicKey")),e.typedef("AccountId",e.lookup("PublicKey")),e.struct("Curve25519Secret",[["key",e.opaque(32)]]),e.struct("Curve25519Public",[["key",e.opaque(32)]]),e.struct("HmacSha256Key",[["key",e.opaque(32)]]),e.struct("HmacSha256Mac",[["mac",e.opaque(32)]]),e.struct("ShortHashSeed",[["seed",e.opaque(16)]]),e.enum("BinaryFuseFilterType",{binaryFuseFilter8Bit:0,binaryFuseFilter16Bit:1,binaryFuseFilter32Bit:2}),e.struct("SerializedBinaryFuseFilter",[["type",e.lookup("BinaryFuseFilterType")],["inputHashSeed",e.lookup("ShortHashSeed")],["filterSeed",e.lookup("ShortHashSeed")],["segmentLength",e.lookup("Uint32")],["segementLengthMask",e.lookup("Uint32")],["segmentCount",e.lookup("Uint32")],["segmentCountLength",e.lookup("Uint32")],["fingerprintLength",e.lookup("Uint32")],["fingerprints",e.varOpaque()]]),e.enum("ScValType",{scvBool:0,scvVoid:1,scvError:2,scvU32:3,scvI32:4,scvU64:5,scvI64:6,scvTimepoint:7,scvDuration:8,scvU128:9,scvI128:10,scvU256:11,scvI256:12,scvBytes:13,scvString:14,scvSymbol:15,scvVec:16,scvMap:17,scvAddress:18,scvContractInstance:19,scvLedgerKeyContractInstance:20,scvLedgerKeyNonce:21}),e.enum("ScErrorType",{sceContract:0,sceWasmVm:1,sceContext:2,sceStorage:3,sceObject:4,sceCrypto:5,sceEvents:6,sceBudget:7,sceValue:8,sceAuth:9}),e.enum("ScErrorCode",{scecArithDomain:0,scecIndexBounds:1,scecInvalidInput:2,scecMissingValue:3,scecExistingValue:4,scecExceededLimit:5,scecInvalidAction:6,scecInternalError:7,scecUnexpectedType:8,scecUnexpectedSize:9}),e.union("ScError",{switchOn:e.lookup("ScErrorType"),switchName:"type",switches:[["sceContract","contractCode"],["sceWasmVm","code"],["sceContext","code"],["sceStorage","code"],["sceObject","code"],["sceCrypto","code"],["sceEvents","code"],["sceBudget","code"],["sceValue","code"],["sceAuth","code"]],arms:{contractCode:e.lookup("Uint32"),code:e.lookup("ScErrorCode")}}),e.struct("UInt128Parts",[["hi",e.lookup("Uint64")],["lo",e.lookup("Uint64")]]),e.struct("Int128Parts",[["hi",e.lookup("Int64")],["lo",e.lookup("Uint64")]]),e.struct("UInt256Parts",[["hiHi",e.lookup("Uint64")],["hiLo",e.lookup("Uint64")],["loHi",e.lookup("Uint64")],["loLo",e.lookup("Uint64")]]),e.struct("Int256Parts",[["hiHi",e.lookup("Int64")],["hiLo",e.lookup("Uint64")],["loHi",e.lookup("Uint64")],["loLo",e.lookup("Uint64")]]),e.enum("ContractExecutableType",{contractExecutableWasm:0,contractExecutableStellarAsset:1}),e.union("ContractExecutable",{switchOn:e.lookup("ContractExecutableType"),switchName:"type",switches:[["contractExecutableWasm","wasmHash"],["contractExecutableStellarAsset",e.void()]],arms:{wasmHash:e.lookup("Hash")}}),e.enum("ScAddressType",{scAddressTypeAccount:0,scAddressTypeContract:1}),e.union("ScAddress",{switchOn:e.lookup("ScAddressType"),switchName:"type",switches:[["scAddressTypeAccount","accountId"],["scAddressTypeContract","contractId"]],arms:{accountId:e.lookup("AccountId"),contractId:e.lookup("Hash")}}),e.const("SCSYMBOL_LIMIT",32),e.typedef("ScVec",e.varArray(e.lookup("ScVal"),2147483647)),e.typedef("ScMap",e.varArray(e.lookup("ScMapEntry"),2147483647)),e.typedef("ScBytes",e.varOpaque()),e.typedef("ScString",e.string()),e.typedef("ScSymbol",e.string(32)),e.struct("ScNonceKey",[["nonce",e.lookup("Int64")]]),e.struct("ScContractInstance",[["executable",e.lookup("ContractExecutable")],["storage",e.option(e.lookup("ScMap"))]]),e.union("ScVal",{switchOn:e.lookup("ScValType"),switchName:"type",switches:[["scvBool","b"],["scvVoid",e.void()],["scvError","error"],["scvU32","u32"],["scvI32","i32"],["scvU64","u64"],["scvI64","i64"],["scvTimepoint","timepoint"],["scvDuration","duration"],["scvU128","u128"],["scvI128","i128"],["scvU256","u256"],["scvI256","i256"],["scvBytes","bytes"],["scvString","str"],["scvSymbol","sym"],["scvVec","vec"],["scvMap","map"],["scvAddress","address"],["scvLedgerKeyContractInstance",e.void()],["scvLedgerKeyNonce","nonceKey"],["scvContractInstance","instance"]],arms:{b:e.bool(),error:e.lookup("ScError"),u32:e.lookup("Uint32"),i32:e.lookup("Int32"),u64:e.lookup("Uint64"),i64:e.lookup("Int64"),timepoint:e.lookup("TimePoint"),duration:e.lookup("Duration"),u128:e.lookup("UInt128Parts"),i128:e.lookup("Int128Parts"),u256:e.lookup("UInt256Parts"),i256:e.lookup("Int256Parts"),bytes:e.lookup("ScBytes"),str:e.lookup("ScString"),sym:e.lookup("ScSymbol"),vec:e.option(e.lookup("ScVec")),map:e.option(e.lookup("ScMap")),address:e.lookup("ScAddress"),nonceKey:e.lookup("ScNonceKey"),instance:e.lookup("ScContractInstance")}}),e.struct("ScMapEntry",[["key",e.lookup("ScVal")],["val",e.lookup("ScVal")]]),e.enum("ScEnvMetaKind",{scEnvMetaKindInterfaceVersion:0}),e.struct("ScEnvMetaEntryInterfaceVersion",[["protocol",e.lookup("Uint32")],["preRelease",e.lookup("Uint32")]]),e.union("ScEnvMetaEntry",{switchOn:e.lookup("ScEnvMetaKind"),switchName:"kind",switches:[["scEnvMetaKindInterfaceVersion","interfaceVersion"]],arms:{interfaceVersion:e.lookup("ScEnvMetaEntryInterfaceVersion")}}),e.struct("ScMetaV0",[["key",e.string()],["val",e.string()]]),e.enum("ScMetaKind",{scMetaV0:0}),e.union("ScMetaEntry",{switchOn:e.lookup("ScMetaKind"),switchName:"kind",switches:[["scMetaV0","v0"]],arms:{v0:e.lookup("ScMetaV0")}}),e.const("SC_SPEC_DOC_LIMIT",1024),e.enum("ScSpecType",{scSpecTypeVal:0,scSpecTypeBool:1,scSpecTypeVoid:2,scSpecTypeError:3,scSpecTypeU32:4,scSpecTypeI32:5,scSpecTypeU64:6,scSpecTypeI64:7,scSpecTypeTimepoint:8,scSpecTypeDuration:9,scSpecTypeU128:10,scSpecTypeI128:11,scSpecTypeU256:12,scSpecTypeI256:13,scSpecTypeBytes:14,scSpecTypeString:16,scSpecTypeSymbol:17,scSpecTypeAddress:19,scSpecTypeOption:1e3,scSpecTypeResult:1001,scSpecTypeVec:1002,scSpecTypeMap:1004,scSpecTypeTuple:1005,scSpecTypeBytesN:1006,scSpecTypeUdt:2e3}),e.struct("ScSpecTypeOption",[["valueType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeResult",[["okType",e.lookup("ScSpecTypeDef")],["errorType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeVec",[["elementType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeMap",[["keyType",e.lookup("ScSpecTypeDef")],["valueType",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecTypeTuple",[["valueTypes",e.varArray(e.lookup("ScSpecTypeDef"),12)]]),e.struct("ScSpecTypeBytesN",[["n",e.lookup("Uint32")]]),e.struct("ScSpecTypeUdt",[["name",e.string(60)]]),e.union("ScSpecTypeDef",{switchOn:e.lookup("ScSpecType"),switchName:"type",switches:[["scSpecTypeVal",e.void()],["scSpecTypeBool",e.void()],["scSpecTypeVoid",e.void()],["scSpecTypeError",e.void()],["scSpecTypeU32",e.void()],["scSpecTypeI32",e.void()],["scSpecTypeU64",e.void()],["scSpecTypeI64",e.void()],["scSpecTypeTimepoint",e.void()],["scSpecTypeDuration",e.void()],["scSpecTypeU128",e.void()],["scSpecTypeI128",e.void()],["scSpecTypeU256",e.void()],["scSpecTypeI256",e.void()],["scSpecTypeBytes",e.void()],["scSpecTypeString",e.void()],["scSpecTypeSymbol",e.void()],["scSpecTypeAddress",e.void()],["scSpecTypeOption","option"],["scSpecTypeResult","result"],["scSpecTypeVec","vec"],["scSpecTypeMap","map"],["scSpecTypeTuple","tuple"],["scSpecTypeBytesN","bytesN"],["scSpecTypeUdt","udt"]],arms:{option:e.lookup("ScSpecTypeOption"),result:e.lookup("ScSpecTypeResult"),vec:e.lookup("ScSpecTypeVec"),map:e.lookup("ScSpecTypeMap"),tuple:e.lookup("ScSpecTypeTuple"),bytesN:e.lookup("ScSpecTypeBytesN"),udt:e.lookup("ScSpecTypeUdt")}}),e.struct("ScSpecUdtStructFieldV0",[["doc",e.string(t)],["name",e.string(30)],["type",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecUdtStructV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["fields",e.varArray(e.lookup("ScSpecUdtStructFieldV0"),40)]]),e.struct("ScSpecUdtUnionCaseVoidV0",[["doc",e.string(t)],["name",e.string(60)]]),e.struct("ScSpecUdtUnionCaseTupleV0",[["doc",e.string(t)],["name",e.string(60)],["type",e.varArray(e.lookup("ScSpecTypeDef"),12)]]),e.enum("ScSpecUdtUnionCaseV0Kind",{scSpecUdtUnionCaseVoidV0:0,scSpecUdtUnionCaseTupleV0:1}),e.union("ScSpecUdtUnionCaseV0",{switchOn:e.lookup("ScSpecUdtUnionCaseV0Kind"),switchName:"kind",switches:[["scSpecUdtUnionCaseVoidV0","voidCase"],["scSpecUdtUnionCaseTupleV0","tupleCase"]],arms:{voidCase:e.lookup("ScSpecUdtUnionCaseVoidV0"),tupleCase:e.lookup("ScSpecUdtUnionCaseTupleV0")}}),e.struct("ScSpecUdtUnionV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtUnionCaseV0"),50)]]),e.struct("ScSpecUdtEnumCaseV0",[["doc",e.string(t)],["name",e.string(60)],["value",e.lookup("Uint32")]]),e.struct("ScSpecUdtEnumV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtEnumCaseV0"),50)]]),e.struct("ScSpecUdtErrorEnumCaseV0",[["doc",e.string(t)],["name",e.string(60)],["value",e.lookup("Uint32")]]),e.struct("ScSpecUdtErrorEnumV0",[["doc",e.string(t)],["lib",e.string(80)],["name",e.string(60)],["cases",e.varArray(e.lookup("ScSpecUdtErrorEnumCaseV0"),50)]]),e.struct("ScSpecFunctionInputV0",[["doc",e.string(t)],["name",e.string(30)],["type",e.lookup("ScSpecTypeDef")]]),e.struct("ScSpecFunctionV0",[["doc",e.string(t)],["name",e.lookup("ScSymbol")],["inputs",e.varArray(e.lookup("ScSpecFunctionInputV0"),10)],["outputs",e.varArray(e.lookup("ScSpecTypeDef"),1)]]),e.enum("ScSpecEntryKind",{scSpecEntryFunctionV0:0,scSpecEntryUdtStructV0:1,scSpecEntryUdtUnionV0:2,scSpecEntryUdtEnumV0:3,scSpecEntryUdtErrorEnumV0:4}),e.union("ScSpecEntry",{switchOn:e.lookup("ScSpecEntryKind"),switchName:"kind",switches:[["scSpecEntryFunctionV0","functionV0"],["scSpecEntryUdtStructV0","udtStructV0"],["scSpecEntryUdtUnionV0","udtUnionV0"],["scSpecEntryUdtEnumV0","udtEnumV0"],["scSpecEntryUdtErrorEnumV0","udtErrorEnumV0"]],arms:{functionV0:e.lookup("ScSpecFunctionV0"),udtStructV0:e.lookup("ScSpecUdtStructV0"),udtUnionV0:e.lookup("ScSpecUdtUnionV0"),udtEnumV0:e.lookup("ScSpecUdtEnumV0"),udtErrorEnumV0:e.lookup("ScSpecUdtErrorEnumV0")}}),e.struct("ConfigSettingContractExecutionLanesV0",[["ledgerMaxTxCount",e.lookup("Uint32")]]),e.struct("ConfigSettingContractComputeV0",[["ledgerMaxInstructions",e.lookup("Int64")],["txMaxInstructions",e.lookup("Int64")],["feeRatePerInstructionsIncrement",e.lookup("Int64")],["txMemoryLimit",e.lookup("Uint32")]]),e.struct("ConfigSettingContractLedgerCostV0",[["ledgerMaxReadLedgerEntries",e.lookup("Uint32")],["ledgerMaxReadBytes",e.lookup("Uint32")],["ledgerMaxWriteLedgerEntries",e.lookup("Uint32")],["ledgerMaxWriteBytes",e.lookup("Uint32")],["txMaxReadLedgerEntries",e.lookup("Uint32")],["txMaxReadBytes",e.lookup("Uint32")],["txMaxWriteLedgerEntries",e.lookup("Uint32")],["txMaxWriteBytes",e.lookup("Uint32")],["feeReadLedgerEntry",e.lookup("Int64")],["feeWriteLedgerEntry",e.lookup("Int64")],["feeRead1Kb",e.lookup("Int64")],["bucketListTargetSizeBytes",e.lookup("Int64")],["writeFee1KbBucketListLow",e.lookup("Int64")],["writeFee1KbBucketListHigh",e.lookup("Int64")],["bucketListWriteFeeGrowthFactor",e.lookup("Uint32")]]),e.struct("ConfigSettingContractHistoricalDataV0",[["feeHistorical1Kb",e.lookup("Int64")]]),e.struct("ConfigSettingContractEventsV0",[["txMaxContractEventsSizeBytes",e.lookup("Uint32")],["feeContractEvents1Kb",e.lookup("Int64")]]),e.struct("ConfigSettingContractBandwidthV0",[["ledgerMaxTxsSizeBytes",e.lookup("Uint32")],["txMaxSizeBytes",e.lookup("Uint32")],["feeTxSize1Kb",e.lookup("Int64")]]),e.enum("ContractCostType",{wasmInsnExec:0,memAlloc:1,memCpy:2,memCmp:3,dispatchHostFunction:4,visitObject:5,valSer:6,valDeser:7,computeSha256Hash:8,computeEd25519PubKey:9,verifyEd25519Sig:10,vmInstantiation:11,vmCachedInstantiation:12,invokeVmFunction:13,computeKeccak256Hash:14,decodeEcdsaCurve256Sig:15,recoverEcdsaSecp256k1Key:16,int256AddSub:17,int256Mul:18,int256Div:19,int256Pow:20,int256Shift:21,chaCha20DrawBytes:22,parseWasmInstructions:23,parseWasmFunctions:24,parseWasmGlobals:25,parseWasmTableEntries:26,parseWasmTypes:27,parseWasmDataSegments:28,parseWasmElemSegments:29,parseWasmImports:30,parseWasmExports:31,parseWasmDataSegmentBytes:32,instantiateWasmInstructions:33,instantiateWasmFunctions:34,instantiateWasmGlobals:35,instantiateWasmTableEntries:36,instantiateWasmTypes:37,instantiateWasmDataSegments:38,instantiateWasmElemSegments:39,instantiateWasmImports:40,instantiateWasmExports:41,instantiateWasmDataSegmentBytes:42,sec1DecodePointUncompressed:43,verifyEcdsaSecp256r1Sig:44,bls12381EncodeFp:45,bls12381DecodeFp:46,bls12381G1CheckPointOnCurve:47,bls12381G1CheckPointInSubgroup:48,bls12381G2CheckPointOnCurve:49,bls12381G2CheckPointInSubgroup:50,bls12381G1ProjectiveToAffine:51,bls12381G2ProjectiveToAffine:52,bls12381G1Add:53,bls12381G1Mul:54,bls12381G1Msm:55,bls12381MapFpToG1:56,bls12381HashToG1:57,bls12381G2Add:58,bls12381G2Mul:59,bls12381G2Msm:60,bls12381MapFp2ToG2:61,bls12381HashToG2:62,bls12381Pairing:63,bls12381FrFromU256:64,bls12381FrToU256:65,bls12381FrAddSub:66,bls12381FrMul:67,bls12381FrPow:68,bls12381FrInv:69}),e.struct("ContractCostParamEntry",[["ext",e.lookup("ExtensionPoint")],["constTerm",e.lookup("Int64")],["linearTerm",e.lookup("Int64")]]),e.struct("StateArchivalSettings",[["maxEntryTtl",e.lookup("Uint32")],["minTemporaryTtl",e.lookup("Uint32")],["minPersistentTtl",e.lookup("Uint32")],["persistentRentRateDenominator",e.lookup("Int64")],["tempRentRateDenominator",e.lookup("Int64")],["maxEntriesToArchive",e.lookup("Uint32")],["bucketListSizeWindowSampleSize",e.lookup("Uint32")],["bucketListWindowSamplePeriod",e.lookup("Uint32")],["evictionScanSize",e.lookup("Uint32")],["startingEvictionScanLevel",e.lookup("Uint32")]]),e.struct("EvictionIterator",[["bucketListLevel",e.lookup("Uint32")],["isCurrBucket",e.bool()],["bucketFileOffset",e.lookup("Uint64")]]),e.const("CONTRACT_COST_COUNT_LIMIT",1024),e.typedef("ContractCostParams",e.varArray(e.lookup("ContractCostParamEntry"),e.lookup("CONTRACT_COST_COUNT_LIMIT"))),e.enum("ConfigSettingId",{configSettingContractMaxSizeBytes:0,configSettingContractComputeV0:1,configSettingContractLedgerCostV0:2,configSettingContractHistoricalDataV0:3,configSettingContractEventsV0:4,configSettingContractBandwidthV0:5,configSettingContractCostParamsCpuInstructions:6,configSettingContractCostParamsMemoryBytes:7,configSettingContractDataKeySizeBytes:8,configSettingContractDataEntrySizeBytes:9,configSettingStateArchival:10,configSettingContractExecutionLanes:11,configSettingBucketlistSizeWindow:12,configSettingEvictionIterator:13}),e.union("ConfigSettingEntry",{switchOn:e.lookup("ConfigSettingId"),switchName:"configSettingId",switches:[["configSettingContractMaxSizeBytes","contractMaxSizeBytes"],["configSettingContractComputeV0","contractCompute"],["configSettingContractLedgerCostV0","contractLedgerCost"],["configSettingContractHistoricalDataV0","contractHistoricalData"],["configSettingContractEventsV0","contractEvents"],["configSettingContractBandwidthV0","contractBandwidth"],["configSettingContractCostParamsCpuInstructions","contractCostParamsCpuInsns"],["configSettingContractCostParamsMemoryBytes","contractCostParamsMemBytes"],["configSettingContractDataKeySizeBytes","contractDataKeySizeBytes"],["configSettingContractDataEntrySizeBytes","contractDataEntrySizeBytes"],["configSettingStateArchival","stateArchivalSettings"],["configSettingContractExecutionLanes","contractExecutionLanes"],["configSettingBucketlistSizeWindow","bucketListSizeWindow"],["configSettingEvictionIterator","evictionIterator"]],arms:{contractMaxSizeBytes:e.lookup("Uint32"),contractCompute:e.lookup("ConfigSettingContractComputeV0"),contractLedgerCost:e.lookup("ConfigSettingContractLedgerCostV0"),contractHistoricalData:e.lookup("ConfigSettingContractHistoricalDataV0"),contractEvents:e.lookup("ConfigSettingContractEventsV0"),contractBandwidth:e.lookup("ConfigSettingContractBandwidthV0"),contractCostParamsCpuInsns:e.lookup("ContractCostParams"),contractCostParamsMemBytes:e.lookup("ContractCostParams"),contractDataKeySizeBytes:e.lookup("Uint32"),contractDataEntrySizeBytes:e.lookup("Uint32"),stateArchivalSettings:e.lookup("StateArchivalSettings"),contractExecutionLanes:e.lookup("ConfigSettingContractExecutionLanesV0"),bucketListSizeWindow:e.varArray(e.lookup("Uint64"),2147483647),evictionIterator:e.lookup("EvictionIterator")}})}));t.default=i},5578:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.LiquidityPoolFeeV18=void 0,t.getLiquidityPoolId=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("constant_product"!==e)throw new Error("liquidityPoolType is invalid");var r=t.assetA,o=t.assetB,c=t.fee;if(!(r&&r instanceof a.Asset))throw new Error("assetA is invalid");if(!(o&&o instanceof a.Asset))throw new Error("assetB is invalid");if(!c||c!==u)throw new Error("fee is invalid");if(-1!==a.Asset.compare(r,o))throw new Error("Assets are not in lexicographic order");var l=i.default.LiquidityPoolType.liquidityPoolConstantProduct().toXDR(),f=new i.default.LiquidityPoolConstantProductParameters({assetA:r.toXDRObject(),assetB:o.toXDRObject(),fee:c}).toXDR(),p=n.concat([l,f]);return(0,s.hash)(p)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(1764),s=r(9152);var u=t.LiquidityPoolFeeV18=30},9152:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hash=function(e){var t=new n.sha256;return t.update(e,"utf8"),t.digest()};var n=r(2802)},356:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={xdr:!0,cereal:!0,hash:!0,sign:!0,verify:!0,FastSigning:!0,getLiquidityPoolId:!0,LiquidityPoolFeeV18:!0,Keypair:!0,UnsignedHyper:!0,Hyper:!0,TransactionBase:!0,Transaction:!0,FeeBumpTransaction:!0,TransactionBuilder:!0,TimeoutInfinite:!0,BASE_FEE:!0,Asset:!0,LiquidityPoolAsset:!0,LiquidityPoolId:!0,Operation:!0,AuthRequiredFlag:!0,AuthRevocableFlag:!0,AuthImmutableFlag:!0,AuthClawbackEnabledFlag:!0,Account:!0,MuxedAccount:!0,Claimant:!0,Networks:!0,StrKey:!0,SignerKey:!0,Soroban:!0,decodeAddressToMuxedAccount:!0,encodeMuxedAccountToAddress:!0,extractBaseAddress:!0,encodeMuxedAccount:!0,Contract:!0,Address:!0};Object.defineProperty(t,"Account",{enumerable:!0,get:function(){return w.Account}}),Object.defineProperty(t,"Address",{enumerable:!0,get:function(){return P.Address}}),Object.defineProperty(t,"Asset",{enumerable:!0,get:function(){return y.Asset}}),Object.defineProperty(t,"AuthClawbackEnabledFlag",{enumerable:!0,get:function(){return g.AuthClawbackEnabledFlag}}),Object.defineProperty(t,"AuthImmutableFlag",{enumerable:!0,get:function(){return g.AuthImmutableFlag}}),Object.defineProperty(t,"AuthRequiredFlag",{enumerable:!0,get:function(){return g.AuthRequiredFlag}}),Object.defineProperty(t,"AuthRevocableFlag",{enumerable:!0,get:function(){return g.AuthRevocableFlag}}),Object.defineProperty(t,"BASE_FEE",{enumerable:!0,get:function(){return h.BASE_FEE}}),Object.defineProperty(t,"Claimant",{enumerable:!0,get:function(){return E.Claimant}}),Object.defineProperty(t,"Contract",{enumerable:!0,get:function(){return A.Contract}}),Object.defineProperty(t,"FastSigning",{enumerable:!0,get:function(){return s.FastSigning}}),Object.defineProperty(t,"FeeBumpTransaction",{enumerable:!0,get:function(){return d.FeeBumpTransaction}}),Object.defineProperty(t,"Hyper",{enumerable:!0,get:function(){return l.Hyper}}),Object.defineProperty(t,"Keypair",{enumerable:!0,get:function(){return c.Keypair}}),Object.defineProperty(t,"LiquidityPoolAsset",{enumerable:!0,get:function(){return m.LiquidityPoolAsset}}),Object.defineProperty(t,"LiquidityPoolFeeV18",{enumerable:!0,get:function(){return u.LiquidityPoolFeeV18}}),Object.defineProperty(t,"LiquidityPoolId",{enumerable:!0,get:function(){return v.LiquidityPoolId}}),Object.defineProperty(t,"MuxedAccount",{enumerable:!0,get:function(){return S.MuxedAccount}}),Object.defineProperty(t,"Networks",{enumerable:!0,get:function(){return _.Networks}}),Object.defineProperty(t,"Operation",{enumerable:!0,get:function(){return g.Operation}}),Object.defineProperty(t,"SignerKey",{enumerable:!0,get:function(){return T.SignerKey}}),Object.defineProperty(t,"Soroban",{enumerable:!0,get:function(){return O.Soroban}}),Object.defineProperty(t,"StrKey",{enumerable:!0,get:function(){return k.StrKey}}),Object.defineProperty(t,"TimeoutInfinite",{enumerable:!0,get:function(){return h.TimeoutInfinite}}),Object.defineProperty(t,"Transaction",{enumerable:!0,get:function(){return p.Transaction}}),Object.defineProperty(t,"TransactionBase",{enumerable:!0,get:function(){return f.TransactionBase}}),Object.defineProperty(t,"TransactionBuilder",{enumerable:!0,get:function(){return h.TransactionBuilder}}),Object.defineProperty(t,"UnsignedHyper",{enumerable:!0,get:function(){return l.UnsignedHyper}}),Object.defineProperty(t,"cereal",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(t,"decodeAddressToMuxedAccount",{enumerable:!0,get:function(){return x.decodeAddressToMuxedAccount}}),t.default=void 0,Object.defineProperty(t,"encodeMuxedAccount",{enumerable:!0,get:function(){return x.encodeMuxedAccount}}),Object.defineProperty(t,"encodeMuxedAccountToAddress",{enumerable:!0,get:function(){return x.encodeMuxedAccountToAddress}}),Object.defineProperty(t,"extractBaseAddress",{enumerable:!0,get:function(){return x.extractBaseAddress}}),Object.defineProperty(t,"getLiquidityPoolId",{enumerable:!0,get:function(){return u.getLiquidityPoolId}}),Object.defineProperty(t,"hash",{enumerable:!0,get:function(){return a.hash}}),Object.defineProperty(t,"sign",{enumerable:!0,get:function(){return s.sign}}),Object.defineProperty(t,"verify",{enumerable:!0,get:function(){return s.verify}}),Object.defineProperty(t,"xdr",{enumerable:!0,get:function(){return o.default}});var o=N(r(1918)),i=N(r(3335)),a=r(9152),s=r(15),u=r(5578),c=r(6691),l=r(3740),f=r(3758),p=r(380),d=r(9260),h=r(6396),y=r(1764),m=r(2262),v=r(9353),g=r(7237),b=r(4172);Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===b[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return b[e]}}))}));var w=r(2135),S=r(2243),E=r(1387),_=r(6202),k=r(7120),T=r(225),O=r(4062),x=r(6160),A=r(7452),P=r(1180),R=r(8549);Object.keys(R).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===R[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return R[e]}}))}));var j=r(7177);Object.keys(j).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===j[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return j[e]}}))}));var C=r(3919);Object.keys(C).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===C[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return C[e]}}))}));var I=r(4842);Object.keys(I).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===I[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return I[e]}}))}));var L=r(5328);Object.keys(L).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===L[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return L[e]}}))}));var B=r(3564);function N(e){return e&&e.__esModule?e:{default:e}}Object.keys(B).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(n,e)||e in t&&t[e]===B[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return B[e]}}))}));t.default=e.exports},3564:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.buildInvocationTree=function e(t){var r=t.function(),a={},c=r.value();switch(r.switch().value){case 0:a.type="execute",a.args={source:o.Address.fromScAddress(c.contractAddress()).toString(),function:c.functionName(),args:c.args().map((function(e){return(0,i.scValToNative)(e)}))};break;case 1:case 2:var l=2===r.switch().value;a.type="create",a.args={};var f=[c.executable(),c.contractIdPreimage()],p=f[0],d=f[1];if(!!p.switch().value!=!!d.switch().value)throw new Error("creation function appears invalid: ".concat(JSON.stringify(c)," (should be wasm+address or token+asset)"));switch(p.switch().value){case 0:var h=d.fromAddress();a.args.type="wasm",a.args.wasm=function(e){for(var t=1;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=r(3740),o={XdrWriter:n.XdrWriter,XdrReader:n.XdrReader};t.default=o},6691:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.Keypair=void 0;var o=c(r(4940)),i=r(15),a=r(7120),s=r(9152),u=c(r(1918));function c(e){return e&&e.__esModule?e:{default:e}}function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LiquidityPoolAsset=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(1764),a=r(5578);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function c(e){for(var t=1;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LiquidityPoolId=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n};function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.MemoText=t.MemoReturn=t.MemoNone=t.MemoID=t.MemoHash=t.Memo=void 0;var o=r(3740),i=s(r(1242)),a=s(r(1918));function s(e){return e&&e.__esModule?e:{default:e}}function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:null;switch(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._type=t,this._value=r,this._type){case f:break;case p:e._validateIdValue(r);break;case d:e._validateTextValue(r);break;case h:case y:e._validateHashValue(r),"string"==typeof r&&(this._value=n.from(r,"hex"));break;default:throw new Error("Invalid memo type")}}return t=e,s=[{key:"_validateIdValue",value:function(e){var t,r=new Error("Expects a int64 as a string. Got ".concat(e));if("string"!=typeof e)throw r;try{t=new i.default(e)}catch(e){throw r}if(!t.isFinite())throw r;if(t.isNaN())throw r}},{key:"_validateTextValue",value:function(e){if(!a.default.Memo.armTypeForArm("text").isValid(e))throw new Error("Expects string, array or buffer, max 28 bytes")}},{key:"_validateHashValue",value:function(e){var t,r=new Error("Expects a 32 byte hash value or hex encoded string. Got ".concat(e));if(null==e)throw r;if("string"==typeof e){if(!/^[0-9A-Fa-f]{64}$/g.test(e))throw r;t=n.from(e,"hex")}else{if(!n.isBuffer(e))throw r;t=n.from(e)}if(!t.length||32!==t.length)throw r}},{key:"none",value:function(){return new e(f)}},{key:"text",value:function(t){return new e(d,t)}},{key:"id",value:function(t){return new e(p,t)}},{key:"hash",value:function(t){return new e(h,t)}},{key:"return",value:function(t){return new e(y,t)}},{key:"fromXDRObject",value:function(t){switch(t.arm()){case"id":return e.id(t.value().toString());case"text":return e.text(t.value());case"hash":return e.hash(t.value());case"retHash":return e.return(t.value())}if(void 0===t.value())return e.none();throw new Error("Unknown type")}}],(r=[{key:"type",get:function(){return this._type},set:function(e){throw new Error("Memo is immutable")}},{key:"value",get:function(){switch(this._type){case f:return null;case p:case d:return this._value;case h:case y:return n.from(this._value);default:throw new Error("Invalid memo type")}},set:function(e){throw new Error("Memo is immutable")}},{key:"toXDRObject",value:function(){switch(this._type){case f:return a.default.Memo.memoNone();case p:return a.default.Memo.memoId(o.UnsignedHyper.fromString(this._value));case d:return a.default.Memo.memoText(this._value);case h:return a.default.Memo.memoHash(this._value);case y:return a.default.Memo.memoReturn(this._value);default:return null}}}])&&c(t.prototype,r),s&&c(t,s),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,s}()},2243:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MuxedAccount=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(2135),a=r(7120),s=r(6160);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Networks=void 0;t.Networks={PUBLIC:"Public Global Stellar Network ; September 2015",TESTNET:"Test SDF Network ; September 2015",FUTURENET:"Test SDF Future Network ; October 2022",SANDBOX:"Local Sandbox Stellar Network ; September 2022",STANDALONE:"Standalone Network ; February 2017"}},8549:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Int128",{enumerable:!0,get:function(){return a.Int128}}),Object.defineProperty(t,"Int256",{enumerable:!0,get:function(){return s.Int256}}),Object.defineProperty(t,"ScInt",{enumerable:!0,get:function(){return u.ScInt}}),Object.defineProperty(t,"Uint128",{enumerable:!0,get:function(){return o.Uint128}}),Object.defineProperty(t,"Uint256",{enumerable:!0,get:function(){return i.Uint256}}),Object.defineProperty(t,"XdrLargeInt",{enumerable:!0,get:function(){return n.XdrLargeInt}}),t.scValToBigInt=function(e){var t=n.XdrLargeInt.getType(e.switch().name);switch(e.switch().name){case"scvU32":case"scvI32":return BigInt(e.value());case"scvU64":case"scvI64":return new n.XdrLargeInt(t,e.value()).toBigInt();case"scvU128":case"scvI128":return new n.XdrLargeInt(t,[e.value().lo(),e.value().hi()]).toBigInt();case"scvU256":case"scvI256":return new n.XdrLargeInt(t,[e.value().loLo(),e.value().loHi(),e.value().hiLo(),e.value().hiHi()]).toBigInt();default:throw TypeError("expected integer type, got ".concat(e.switch()))}};var n=r(7429),o=r(6272),i=r(8672),a=r(5487),s=r(4063),u=r(3317)},5487:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Int128=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Int256=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.ScInt=void 0;var o=r(7429);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Uint128=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Uint256=void 0;var o=r(3740);function i(e,t){for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.XdrLargeInt=void 0;var n,o=r(3740),i=r(6272),a=r(8672),s=r(5487),u=r(4063),c=(n=r(1918))&&n.__esModule?n:{default:n};function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){for(var r=0;rNumber.MAX_SAFE_INTEGER||e>64n),r=BigInt.asUintN(64,e);return c.default.ScVal.scvI128(new c.default.Int128Parts({hi:new c.default.Int64(t),lo:new c.default.Uint64(r)}))}},{key:"toU128",value:function(){this._sizeCheck(128);var e=this.int.toBigInt();return c.default.ScVal.scvU128(new c.default.UInt128Parts({hi:new c.default.Uint64(BigInt.asUintN(64,e>>64n)),lo:new c.default.Uint64(BigInt.asUintN(64,e))}))}},{key:"toI256",value:function(){var e=this.int.toBigInt(),t=BigInt.asIntN(64,e>>192n),r=BigInt.asUintN(64,e>>128n),n=BigInt.asUintN(64,e>>64n),o=BigInt.asUintN(64,e);return c.default.ScVal.scvI256(new c.default.Int256Parts({hiHi:new c.default.Int64(t),hiLo:new c.default.Uint64(r),loHi:new c.default.Uint64(n),loLo:new c.default.Uint64(o)}))}},{key:"toU256",value:function(){var e=this.int.toBigInt(),t=BigInt.asUintN(64,e>>192n),r=BigInt.asUintN(64,e>>128n),n=BigInt.asUintN(64,e>>64n),o=BigInt.asUintN(64,e);return c.default.ScVal.scvU256(new c.default.UInt256Parts({hiHi:new c.default.Uint64(t),hiLo:new c.default.Uint64(r),loHi:new c.default.Uint64(n),loLo:new c.default.Uint64(o)}))}},{key:"toScVal",value:function(){switch(this.type){case"i64":return this.toI64();case"i128":return this.toI128();case"i256":return this.toI256();case"u64":return this.toU64();case"u128":return this.toU128();case"u256":return this.toU256();default:throw TypeError("invalid type: ".concat(this.type))}}},{key:"valueOf",value:function(){return this.int.valueOf()}},{key:"toString",value:function(){return this.int.toString()}},{key:"toJSON",value:function(){return{value:this.toBigInt().toString(),type:this.type}}},{key:"_sizeCheck",value:function(e){if(this.int.size>e)throw RangeError("value too large for ".concat(e," bits (").concat(this.type,")"))}}],[{key:"isType",value:function(e){switch(e){case"i64":case"i128":case"i256":case"u64":case"u128":case"u256":return!0;default:return!1}}},{key:"getType",value:function(e){return e.slice(3).toLowerCase()}}])}()},7237:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Operation=t.AuthRevocableFlag=t.AuthRequiredFlag=t.AuthImmutableFlag=t.AuthClawbackEnabledFlag=void 0;var n=r(3740),o=m(r(1242)),i=r(645),a=r(4151),s=r(1764),u=r(2262),c=r(1387),l=r(7120),f=r(9353),p=m(r(1918)),d=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=v(e)&&"function"!=typeof e)return{default:e};var r=y(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in e)if("default"!==i&&{}.hasOwnProperty.call(e,i)){var a=o?Object.getOwnPropertyDescriptor(e,i):null;a&&(a.get||a.set)?Object.defineProperty(n,i,a):n[i]=e[i]}return n.default=e,r&&r.set(e,n),n}(r(7511)),h=r(6160);function y(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(y=function(e){return e?r:t})(e)}function m(e){return e&&e.__esModule?e:{default:e}}function v(e){return v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},v(e)}function g(e,t){for(var r=0;r1&&void 0!==arguments[1]&&arguments[1];if("string"!=typeof e)return!1;try{t=new o.default(e)}catch(e){return!1}return!(!r&&t.isZero()||t.isNegative()||t.times(w).gt(new o.default("9223372036854775807").toString())||t.decimalPlaces()>7||t.isNaN()||!t.isFinite())}},{key:"constructAmountRequirementsError",value:function(e){return"".concat(e," argument must be of type String, represent a positive number and have at most 7 digits after the decimal")}},{key:"_checkUnsignedIntValue",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;if(void 0!==t)switch("string"==typeof t&&(t=parseFloat(t)),!0){case"number"!=typeof t||!Number.isFinite(t)||t%1!=0:throw new Error("".concat(e," value is invalid"));case t<0:throw new Error("".concat(e," value must be unsigned"));case!r||r&&r(t,e):return t;default:throw new Error("".concat(e," value is invalid"))}}},{key:"_toXDRAmount",value:function(e){var t=new o.default(e).times(w);return n.Hyper.fromString(t.toString())}},{key:"_fromXDRAmount",value:function(e){return new o.default(e).div(w).toFixed(7)}},{key:"_fromXDRPrice",value:function(e){return new o.default(e.n()).div(new o.default(e.d())).toString()}},{key:"_toXDRPrice",value:function(e){var t;if(e.n&&e.d)t=new p.default.Price(e);else{var r=(0,a.best_r)(e);t=new p.default.Price({n:parseInt(r[0],10),d:parseInt(r[1],10)})}if(t.n()<0||t.d()<0)throw new Error("price must be positive");return t}}],(t=null)&&g(e.prototype,t),r&&g(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,r}());function E(e){return l.StrKey.encodeEd25519PublicKey(e.ed25519())}S.accountMerge=d.accountMerge,S.allowTrust=d.allowTrust,S.bumpSequence=d.bumpSequence,S.changeTrust=d.changeTrust,S.createAccount=d.createAccount,S.createClaimableBalance=d.createClaimableBalance,S.claimClaimableBalance=d.claimClaimableBalance,S.clawbackClaimableBalance=d.clawbackClaimableBalance,S.createPassiveSellOffer=d.createPassiveSellOffer,S.inflation=d.inflation,S.manageData=d.manageData,S.manageSellOffer=d.manageSellOffer,S.manageBuyOffer=d.manageBuyOffer,S.pathPaymentStrictReceive=d.pathPaymentStrictReceive,S.pathPaymentStrictSend=d.pathPaymentStrictSend,S.payment=d.payment,S.setOptions=d.setOptions,S.beginSponsoringFutureReserves=d.beginSponsoringFutureReserves,S.endSponsoringFutureReserves=d.endSponsoringFutureReserves,S.revokeAccountSponsorship=d.revokeAccountSponsorship,S.revokeTrustlineSponsorship=d.revokeTrustlineSponsorship,S.revokeOfferSponsorship=d.revokeOfferSponsorship,S.revokeDataSponsorship=d.revokeDataSponsorship,S.revokeClaimableBalanceSponsorship=d.revokeClaimableBalanceSponsorship,S.revokeLiquidityPoolSponsorship=d.revokeLiquidityPoolSponsorship,S.revokeSignerSponsorship=d.revokeSignerSponsorship,S.clawback=d.clawback,S.setTrustLineFlags=d.setTrustLineFlags,S.liquidityPoolDeposit=d.liquidityPoolDeposit,S.liquidityPoolWithdraw=d.liquidityPoolWithdraw,S.invokeHostFunction=d.invokeHostFunction,S.extendFootprintTtl=d.extendFootprintTtl,S.restoreFootprint=d.restoreFootprint,S.createStellarAssetContract=d.createStellarAssetContract,S.invokeContractFunction=d.invokeContractFunction,S.createCustomContract=d.createCustomContract,S.uploadContractWasm=d.uploadContractWasm},4295:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.accountMerge=function(e){var t={};try{t.body=o.default.OperationBody.accountMerge((0,i.decodeAddressToMuxedAccount)(e.destination))}catch(e){throw new Error("destination is invalid")}return this.setSourceAccount(t,e),new o.default.Operation(t)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},3683:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.allowTrust=function(e){if(!a.StrKey.isValidEd25519PublicKey(e.trustor))throw new Error("trustor is invalid");var t={};if(t.trustor=i.Keypair.fromPublicKey(e.trustor).xdrAccountId(),e.assetCode.length<=4){var r=e.assetCode.padEnd(4,"\0");t.asset=o.default.AssetCode.assetTypeCreditAlphanum4(r)}else{if(!(e.assetCode.length<=12))throw new Error("Asset code must be 12 characters at max.");var n=e.assetCode.padEnd(12,"\0");t.asset=o.default.AssetCode.assetTypeCreditAlphanum12(n)}"boolean"==typeof e.authorize?e.authorize?t.authorize=o.default.TrustLineFlags.authorizedFlag().value:t.authorize=0:t.authorize=e.authorize;var s=new o.default.AllowTrustOp(t),u={};return u.body=o.default.OperationBody.allowTrust(s),this.setSourceAccount(u,e),new o.default.Operation(u)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691),a=r(7120)},7505:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.beginSponsoringFutureReserves=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!i.StrKey.isValidEd25519PublicKey(e.sponsoredId))throw new Error("sponsoredId is invalid");var t=new o.default.BeginSponsoringFutureReservesOp({sponsoredId:a.Keypair.fromPublicKey(e.sponsoredId).xdrAccountId()}),r={};return r.body=o.default.OperationBody.beginSponsoringFutureReserves(t),this.setSourceAccount(r,e),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(7120),a=r(6691)},6183:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bumpSequence=function(e){var t={};if("string"!=typeof e.bumpTo)throw new Error("bumpTo must be a string");try{new o.default(e.bumpTo)}catch(e){throw new Error("bumpTo must be a stringified number")}t.bumpTo=n.Hyper.fromString(e.bumpTo);var r=new i.default.BumpSequenceOp(t),a={};return a.body=i.default.OperationBody.bumpSequence(r),this.setSourceAccount(a,e),new i.default.Operation(a)};var n=r(3740),o=a(r(1242)),i=a(r(1918));function a(e){return e&&e.__esModule?e:{default:e}}},2810:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.changeTrust=function(e){var t={};if(e.asset instanceof a.Asset)t.line=e.asset.toChangeTrustXDRObject();else{if(!(e.asset instanceof s.LiquidityPoolAsset))throw new TypeError("asset must be Asset or LiquidityPoolAsset");t.line=e.asset.toXDRObject()}if(void 0!==e.limit&&!this.isValidAmount(e.limit,!0))throw new TypeError(this.constructAmountRequirementsError("limit"));e.limit?t.limit=this._toXDRAmount(e.limit):t.limit=n.Hyper.fromString(new o.default(c).toString());e.source&&(t.source=e.source.masterKeypair);var r=new i.default.ChangeTrustOp(t),u={};return u.body=i.default.OperationBody.changeTrust(r),this.setSourceAccount(u,e),new i.default.Operation(u)};var n=r(3740),o=u(r(1242)),i=u(r(1918)),a=r(1764),s=r(2262);function u(e){return e&&e.__esModule?e:{default:e}}var c="9223372036854775807"},7239:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.claimClaimableBalance=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};i(e.balanceId);var t={};t.balanceId=o.default.ClaimableBalanceId.fromXDR(e.balanceId,"hex");var r=new o.default.ClaimClaimableBalanceOp(t),n={};return n.body=o.default.OperationBody.claimClaimableBalance(r),this.setSourceAccount(n,e),new o.default.Operation(n)},t.validateClaimableBalanceId=i;var n,o=(n=r(1918))&&n.__esModule?n:{default:n};function i(e){if("string"!=typeof e||72!==e.length)throw new Error("must provide a valid claimable balance id")}},7651:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clawback=function(e){var t={};if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));t.amount=this._toXDRAmount(e.amount),t.asset=e.asset.toXDRObject();try{t.from=(0,i.decodeAddressToMuxedAccount)(e.from)}catch(e){throw new Error("from address is invalid")}var r={body:o.default.OperationBody.clawback(new o.default.ClawbackOp(t))};return this.setSourceAccount(r,e),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},2203:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clawbackClaimableBalance=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(0,i.validateClaimableBalanceId)(e.balanceId);var t={balanceId:o.default.ClaimableBalanceId.fromXDR(e.balanceId,"hex")},r={body:o.default.OperationBody.clawbackClaimableBalance(new o.default.ClawbackClaimableBalanceOp(t))};return this.setSourceAccount(r,e),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(7239)},2115:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createAccount=function(e){if(!a.StrKey.isValidEd25519PublicKey(e.destination))throw new Error("destination is invalid");if(!this.isValidAmount(e.startingBalance,!0))throw new TypeError(this.constructAmountRequirementsError("startingBalance"));var t={};t.destination=i.Keypair.fromPublicKey(e.destination).xdrAccountId(),t.startingBalance=this._toXDRAmount(e.startingBalance);var r=new o.default.CreateAccountOp(t),n={};return n.body=o.default.OperationBody.createAccount(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691),a=r(7120)},4831:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createClaimableBalance=function(e){if(!(e.asset instanceof i.Asset))throw new Error("must provide an asset for create claimable balance operation");if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(!Array.isArray(e.claimants)||0===e.claimants.length)throw new Error("must provide at least one claimant");var t={};t.asset=e.asset.toXDRObject(),t.amount=this._toXDRAmount(e.amount),t.claimants=Object.values(e.claimants).map((function(e){return e.toXDRObject()}));var r=new o.default.CreateClaimableBalanceOp(t),n={};return n.body=o.default.OperationBody.createClaimableBalance(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(1764)},9073:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createPassiveSellOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price);var r=new o.default.CreatePassiveSellOfferOp(t),n={};return n.body=o.default.OperationBody.createPassiveSellOffer(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},721:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endSponsoringFutureReserves=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};return t.body=o.default.OperationBody.endSponsoringFutureReserves(),this.setSourceAccount(t,e),new o.default.Operation(t)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},8752:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extendFootprintTtl=function(e){var t;if((null!==(t=e.extendTo)&&void 0!==t?t:-1)<=0)throw new RangeError("extendTo has to be positive");var r=new o.default.ExtendFootprintTtlOp({ext:new o.default.ExtensionPoint(0),extendTo:e.extendTo}),n={body:o.default.OperationBody.extendFootprintTtl(r)};return this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},7511:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"accountMerge",{enumerable:!0,get:function(){return i.accountMerge}}),Object.defineProperty(t,"allowTrust",{enumerable:!0,get:function(){return a.allowTrust}}),Object.defineProperty(t,"beginSponsoringFutureReserves",{enumerable:!0,get:function(){return w.beginSponsoringFutureReserves}}),Object.defineProperty(t,"bumpSequence",{enumerable:!0,get:function(){return s.bumpSequence}}),Object.defineProperty(t,"changeTrust",{enumerable:!0,get:function(){return u.changeTrust}}),Object.defineProperty(t,"claimClaimableBalance",{enumerable:!0,get:function(){return f.claimClaimableBalance}}),Object.defineProperty(t,"clawback",{enumerable:!0,get:function(){return _.clawback}}),Object.defineProperty(t,"clawbackClaimableBalance",{enumerable:!0,get:function(){return p.clawbackClaimableBalance}}),Object.defineProperty(t,"createAccount",{enumerable:!0,get:function(){return c.createAccount}}),Object.defineProperty(t,"createClaimableBalance",{enumerable:!0,get:function(){return l.createClaimableBalance}}),Object.defineProperty(t,"createCustomContract",{enumerable:!0,get:function(){return x.createCustomContract}}),Object.defineProperty(t,"createPassiveSellOffer",{enumerable:!0,get:function(){return o.createPassiveSellOffer}}),Object.defineProperty(t,"createStellarAssetContract",{enumerable:!0,get:function(){return x.createStellarAssetContract}}),Object.defineProperty(t,"endSponsoringFutureReserves",{enumerable:!0,get:function(){return S.endSponsoringFutureReserves}}),Object.defineProperty(t,"extendFootprintTtl",{enumerable:!0,get:function(){return A.extendFootprintTtl}}),Object.defineProperty(t,"inflation",{enumerable:!0,get:function(){return d.inflation}}),Object.defineProperty(t,"invokeContractFunction",{enumerable:!0,get:function(){return x.invokeContractFunction}}),Object.defineProperty(t,"invokeHostFunction",{enumerable:!0,get:function(){return x.invokeHostFunction}}),Object.defineProperty(t,"liquidityPoolDeposit",{enumerable:!0,get:function(){return T.liquidityPoolDeposit}}),Object.defineProperty(t,"liquidityPoolWithdraw",{enumerable:!0,get:function(){return O.liquidityPoolWithdraw}}),Object.defineProperty(t,"manageBuyOffer",{enumerable:!0,get:function(){return y.manageBuyOffer}}),Object.defineProperty(t,"manageData",{enumerable:!0,get:function(){return h.manageData}}),Object.defineProperty(t,"manageSellOffer",{enumerable:!0,get:function(){return n.manageSellOffer}}),Object.defineProperty(t,"pathPaymentStrictReceive",{enumerable:!0,get:function(){return m.pathPaymentStrictReceive}}),Object.defineProperty(t,"pathPaymentStrictSend",{enumerable:!0,get:function(){return v.pathPaymentStrictSend}}),Object.defineProperty(t,"payment",{enumerable:!0,get:function(){return g.payment}}),Object.defineProperty(t,"restoreFootprint",{enumerable:!0,get:function(){return P.restoreFootprint}}),Object.defineProperty(t,"revokeAccountSponsorship",{enumerable:!0,get:function(){return E.revokeAccountSponsorship}}),Object.defineProperty(t,"revokeClaimableBalanceSponsorship",{enumerable:!0,get:function(){return E.revokeClaimableBalanceSponsorship}}),Object.defineProperty(t,"revokeDataSponsorship",{enumerable:!0,get:function(){return E.revokeDataSponsorship}}),Object.defineProperty(t,"revokeLiquidityPoolSponsorship",{enumerable:!0,get:function(){return E.revokeLiquidityPoolSponsorship}}),Object.defineProperty(t,"revokeOfferSponsorship",{enumerable:!0,get:function(){return E.revokeOfferSponsorship}}),Object.defineProperty(t,"revokeSignerSponsorship",{enumerable:!0,get:function(){return E.revokeSignerSponsorship}}),Object.defineProperty(t,"revokeTrustlineSponsorship",{enumerable:!0,get:function(){return E.revokeTrustlineSponsorship}}),Object.defineProperty(t,"setOptions",{enumerable:!0,get:function(){return b.setOptions}}),Object.defineProperty(t,"setTrustLineFlags",{enumerable:!0,get:function(){return k.setTrustLineFlags}}),Object.defineProperty(t,"uploadContractWasm",{enumerable:!0,get:function(){return x.uploadContractWasm}});var n=r(862),o=r(9073),i=r(4295),a=r(3683),s=r(6183),u=r(2810),c=r(2115),l=r(4831),f=r(7239),p=r(2203),d=r(7421),h=r(1411),y=r(1922),m=r(2075),v=r(3874),g=r(3533),b=r(2018),w=r(7505),S=r(721),E=r(7790),_=r(7651),k=r(1804),T=r(9845),O=r(4737),x=r(4403),A=r(8752),P=r(149)},7421:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.inflation=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};return t.body=o.default.OperationBody.inflation(),this.setSourceAccount(t,e),new o.default.Operation(t)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},4403:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.createCustomContract=function(e){var t,r=n.from(e.salt||a.Keypair.random().xdrPublicKey().value());if(!e.wasmHash||32!==e.wasmHash.length)throw new TypeError("expected hash(contract WASM) in 'opts.wasmHash', got ".concat(e.wasmHash));if(32!==r.length)throw new TypeError("expected 32-byte salt in 'opts.salt', got ".concat(e.wasmHash));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeCreateContractV2(new i.default.CreateContractArgsV2({executable:i.default.ContractExecutable.contractExecutableWasm(n.from(e.wasmHash)),contractIdPreimage:i.default.ContractIdPreimage.contractIdPreimageFromAddress(new i.default.ContractIdPreimageFromAddress({address:e.address.toScAddress(),salt:r})),constructorArgs:null!==(t=e.constructorArgs)&&void 0!==t?t:[]}))})},t.createStellarAssetContract=function(e){var t=e.asset;if("string"==typeof t){var r=t.split(":"),n=(l=2,function(e){if(Array.isArray(e))return e}(s=r)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(s,l)||function(e,t){if(e){if("string"==typeof e)return c(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?c(e,t):void 0}}(s,l)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),o=n[0],a=n[1];t=new u.Asset(o,a)}var s,l;if(!(t instanceof u.Asset))throw new TypeError("expected Asset in 'opts.asset', got ".concat(t));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeCreateContract(new i.default.CreateContractArgs({executable:i.default.ContractExecutable.contractExecutableStellarAsset(),contractIdPreimage:i.default.ContractIdPreimage.contractIdPreimageFromAsset(t.toXDRObject())}))})},t.invokeContractFunction=function(e){var t=new s.Address(e.contract);if("contract"!==t._type)throw new TypeError("expected contract strkey instance, got ".concat(t));return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeInvokeContract(new i.default.InvokeContractArgs({contractAddress:t.toScAddress(),functionName:e.function,args:e.args}))})},t.invokeHostFunction=function(e){if(!e.func)throw new TypeError("host function invocation ('func') required (got ".concat(JSON.stringify(e),")"));var t=new i.default.InvokeHostFunctionOp({hostFunction:e.func,auth:e.auth||[]}),r={body:i.default.OperationBody.invokeHostFunction(t)};return this.setSourceAccount(r,e),new i.default.Operation(r)},t.uploadContractWasm=function(e){return this.invokeHostFunction({source:e.source,auth:e.auth,func:i.default.HostFunction.hostFunctionTypeUploadContractWasm(n.from(e.wasm))})};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(6691),s=r(1180),u=r(1764);function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.liquidityPoolDeposit=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.liquidityPoolId,r=e.maxAmountA,n=e.maxAmountB,i=e.minPrice,a=e.maxPrice,s={};if(!t)throw new TypeError("liquidityPoolId argument is required");if(s.liquidityPoolId=o.default.PoolId.fromXDR(t,"hex"),!this.isValidAmount(r,!0))throw new TypeError(this.constructAmountRequirementsError("maxAmountA"));if(s.maxAmountA=this._toXDRAmount(r),!this.isValidAmount(n,!0))throw new TypeError(this.constructAmountRequirementsError("maxAmountB"));if(s.maxAmountB=this._toXDRAmount(n),void 0===i)throw new TypeError("minPrice argument is required");if(s.minPrice=this._toXDRPrice(i),void 0===a)throw new TypeError("maxPrice argument is required");s.maxPrice=this._toXDRPrice(a);var u=new o.default.LiquidityPoolDepositOp(s),c={body:o.default.OperationBody.liquidityPoolDeposit(u)};return this.setSourceAccount(c,e),new o.default.Operation(c)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},4737:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.liquidityPoolWithdraw=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};if(!e.liquidityPoolId)throw new TypeError("liquidityPoolId argument is required");if(t.liquidityPoolId=o.default.PoolId.fromXDR(e.liquidityPoolId,"hex"),!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),!this.isValidAmount(e.minAmountA,!0))throw new TypeError(this.constructAmountRequirementsError("minAmountA"));if(t.minAmountA=this._toXDRAmount(e.minAmountA),!this.isValidAmount(e.minAmountB,!0))throw new TypeError(this.constructAmountRequirementsError("minAmountB"));t.minAmountB=this._toXDRAmount(e.minAmountB);var r=new o.default.LiquidityPoolWithdrawOp(t),n={body:o.default.OperationBody.liquidityPoolWithdraw(r)};return this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},1922:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.manageBuyOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.buyAmount,!0))throw new TypeError(this.constructAmountRequirementsError("buyAmount"));if(t.buyAmount=this._toXDRAmount(e.buyAmount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price),void 0!==e.offerId?e.offerId=e.offerId.toString():e.offerId="0";t.offerId=o.Hyper.fromString(e.offerId);var r=new i.default.ManageBuyOfferOp(t),n={};return n.body=i.default.OperationBody.manageBuyOffer(r),this.setSourceAccount(n,e),new i.default.Operation(n)};var n,o=r(3740),i=(n=r(1918))&&n.__esModule?n:{default:n}},1411:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.manageData=function(e){var t={};if(!("string"==typeof e.name&&e.name.length<=64))throw new Error("name must be a string, up to 64 characters");if(t.dataName=e.name,"string"!=typeof e.value&&!n.isBuffer(e.value)&&null!==e.value)throw new Error("value must be a string, Buffer or null");"string"==typeof e.value?t.dataValue=n.from(e.value):t.dataValue=e.value;if(null!==t.dataValue&&t.dataValue.length>64)throw new Error("value cannot be longer that 64 bytes");var r=new i.default.ManageDataOp(t),o={};return o.body=i.default.OperationBody.manageData(r),this.setSourceAccount(o,e),new i.default.Operation(o)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o}},862:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.manageSellOffer=function(e){var t={};if(t.selling=e.selling.toXDRObject(),t.buying=e.buying.toXDRObject(),!this.isValidAmount(e.amount,!0))throw new TypeError(this.constructAmountRequirementsError("amount"));if(t.amount=this._toXDRAmount(e.amount),void 0===e.price)throw new TypeError("price argument is required");t.price=this._toXDRPrice(e.price),void 0!==e.offerId?e.offerId=e.offerId.toString():e.offerId="0";t.offerId=o.Hyper.fromString(e.offerId);var r=new i.default.ManageSellOfferOp(t),n={};return n.body=i.default.OperationBody.manageSellOffer(r),this.setSourceAccount(n,e),new i.default.Operation(n)};var n,o=r(3740),i=(n=r(1918))&&n.__esModule?n:{default:n}},2075:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathPaymentStrictReceive=function(e){switch(!0){case!e.sendAsset:throw new Error("Must specify a send asset");case!this.isValidAmount(e.sendMax):throw new TypeError(this.constructAmountRequirementsError("sendMax"));case!e.destAsset:throw new Error("Must provide a destAsset for a payment operation");case!this.isValidAmount(e.destAmount):throw new TypeError(this.constructAmountRequirementsError("destAmount"))}var t={};t.sendAsset=e.sendAsset.toXDRObject(),t.sendMax=this._toXDRAmount(e.sendMax);try{t.destination=(0,i.decodeAddressToMuxedAccount)(e.destination)}catch(e){throw new Error("destination is invalid")}t.destAsset=e.destAsset.toXDRObject(),t.destAmount=this._toXDRAmount(e.destAmount);var r=e.path?e.path:[];t.path=r.map((function(e){return e.toXDRObject()}));var n=new o.default.PathPaymentStrictReceiveOp(t),a={};return a.body=o.default.OperationBody.pathPaymentStrictReceive(n),this.setSourceAccount(a,e),new o.default.Operation(a)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},3874:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.pathPaymentStrictSend=function(e){switch(!0){case!e.sendAsset:throw new Error("Must specify a send asset");case!this.isValidAmount(e.sendAmount):throw new TypeError(this.constructAmountRequirementsError("sendAmount"));case!e.destAsset:throw new Error("Must provide a destAsset for a payment operation");case!this.isValidAmount(e.destMin):throw new TypeError(this.constructAmountRequirementsError("destMin"))}var t={};t.sendAsset=e.sendAsset.toXDRObject(),t.sendAmount=this._toXDRAmount(e.sendAmount);try{t.destination=(0,i.decodeAddressToMuxedAccount)(e.destination)}catch(e){throw new Error("destination is invalid")}t.destAsset=e.destAsset.toXDRObject(),t.destMin=this._toXDRAmount(e.destMin);var r=e.path?e.path:[];t.path=r.map((function(e){return e.toXDRObject()}));var n=new o.default.PathPaymentStrictSendOp(t),a={};return a.body=o.default.OperationBody.pathPaymentStrictSend(n),this.setSourceAccount(a,e),new o.default.Operation(a)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},3533:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.payment=function(e){if(!e.asset)throw new Error("Must provide an asset for a payment operation");if(!this.isValidAmount(e.amount))throw new TypeError(this.constructAmountRequirementsError("amount"));var t={};try{t.destination=(0,i.decodeAddressToMuxedAccount)(e.destination)}catch(e){throw new Error("destination is invalid")}t.asset=e.asset.toXDRObject(),t.amount=this._toXDRAmount(e.amount);var r=new o.default.PaymentOp(t),n={};return n.body=o.default.OperationBody.payment(r),this.setSourceAccount(n,e),new o.default.Operation(n)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6160)},149:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.restoreFootprint=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=new o.default.RestoreFootprintOp({ext:new o.default.ExtensionPoint(0)}),r={body:o.default.OperationBody.restoreFootprint(t)};return this.setSourceAccount(r,null!=e?e:{}),new o.default.Operation(r)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n}},7790:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.revokeAccountSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");var t=i.default.LedgerKey.account(new i.default.LedgerKeyAccount({accountId:s.Keypair.fromPublicKey(e.account).xdrAccountId()})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeClaimableBalanceSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if("string"!=typeof e.balanceId)throw new Error("balanceId is invalid");var t=i.default.LedgerKey.claimableBalance(new i.default.LedgerKeyClaimableBalance({balanceId:i.default.ClaimableBalanceId.fromXDR(e.balanceId,"hex")})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeDataSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(e.account))throw new Error("account is invalid");if("string"!=typeof e.name||e.name.length>64)throw new Error("name must be a string, up to 64 characters");var t=i.default.LedgerKey.data(new i.default.LedgerKeyData({accountId:s.Keypair.fromPublicKey(e.account).xdrAccountId(),dataName:e.name})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeLiquidityPoolSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if("string"!=typeof e.liquidityPoolId)throw new Error("liquidityPoolId is invalid");var t=i.default.LedgerKey.liquidityPool(new i.default.LedgerKeyLiquidityPool({liquidityPoolId:i.default.PoolId.fromXDR(e.liquidityPoolId,"hex")})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={body:i.default.OperationBody.revokeSponsorship(r)};return this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeOfferSponsorship=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(e.seller))throw new Error("seller is invalid");if("string"!=typeof e.offerId)throw new Error("offerId is invalid");var t=i.default.LedgerKey.offer(new i.default.LedgerKeyOffer({sellerId:s.Keypair.fromPublicKey(e.seller).xdrAccountId(),offerId:i.default.Int64.fromString(e.offerId)})),r=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(t),n={};return n.body=i.default.OperationBody.revokeSponsorship(r),this.setSourceAccount(n,e),new i.default.Operation(n)},t.revokeSignerSponsorship=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(t.account))throw new Error("account is invalid");if(t.signer.ed25519PublicKey){if(!a.StrKey.isValidEd25519PublicKey(t.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");var r=a.StrKey.decodeEd25519PublicKey(t.signer.ed25519PublicKey);e=new i.default.SignerKey.signerKeyTypeEd25519(r)}else if(t.signer.preAuthTx){var o;if(o="string"==typeof t.signer.preAuthTx?n.from(t.signer.preAuthTx,"hex"):t.signer.preAuthTx,!n.isBuffer(o)||32!==o.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");e=new i.default.SignerKey.signerKeyTypePreAuthTx(o)}else{if(!t.signer.sha256Hash)throw new Error("signer is invalid");var u;if(u="string"==typeof t.signer.sha256Hash?n.from(t.signer.sha256Hash,"hex"):t.signer.sha256Hash,!n.isBuffer(u)||32!==u.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");e=new i.default.SignerKey.signerKeyTypeHashX(u)}var c=new i.default.RevokeSponsorshipOpSigner({accountId:s.Keypair.fromPublicKey(t.account).xdrAccountId(),signerKey:e}),l=i.default.RevokeSponsorshipOp.revokeSponsorshipSigner(c),f={};return f.body=i.default.OperationBody.revokeSponsorship(l),this.setSourceAccount(f,t),new i.default.Operation(f)},t.revokeTrustlineSponsorship=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!a.StrKey.isValidEd25519PublicKey(t.account))throw new Error("account is invalid");if(t.asset instanceof u.Asset)e=t.asset.toTrustLineXDRObject();else{if(!(t.asset instanceof c.LiquidityPoolId))throw new TypeError("asset must be an Asset or LiquidityPoolId");e=t.asset.toXDRObject()}var r=i.default.LedgerKey.trustline(new i.default.LedgerKeyTrustLine({accountId:s.Keypair.fromPublicKey(t.account).xdrAccountId(),asset:e})),n=i.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(r),o={};return o.body=i.default.OperationBody.revokeSponsorship(n),this.setSourceAccount(o,t),new i.default.Operation(o)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(7120),s=r(6691),u=r(1764),c=r(9353)},2018:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.setOptions=function(e){var t={};if(e.inflationDest){if(!s.StrKey.isValidEd25519PublicKey(e.inflationDest))throw new Error("inflationDest is invalid");t.inflationDest=a.Keypair.fromPublicKey(e.inflationDest).xdrAccountId()}if(t.clearFlags=this._checkUnsignedIntValue("clearFlags",e.clearFlags),t.setFlags=this._checkUnsignedIntValue("setFlags",e.setFlags),t.masterWeight=this._checkUnsignedIntValue("masterWeight",e.masterWeight,u),t.lowThreshold=this._checkUnsignedIntValue("lowThreshold",e.lowThreshold,u),t.medThreshold=this._checkUnsignedIntValue("medThreshold",e.medThreshold,u),t.highThreshold=this._checkUnsignedIntValue("highThreshold",e.highThreshold,u),void 0!==e.homeDomain&&"string"!=typeof e.homeDomain)throw new TypeError("homeDomain argument must be of type String");if(t.homeDomain=e.homeDomain,e.signer){var r,o=this._checkUnsignedIntValue("signer.weight",e.signer.weight,u),c=0;if(e.signer.ed25519PublicKey){if(!s.StrKey.isValidEd25519PublicKey(e.signer.ed25519PublicKey))throw new Error("signer.ed25519PublicKey is invalid.");var l=s.StrKey.decodeEd25519PublicKey(e.signer.ed25519PublicKey);r=new i.default.SignerKey.signerKeyTypeEd25519(l),c+=1}if(e.signer.preAuthTx){if("string"==typeof e.signer.preAuthTx&&(e.signer.preAuthTx=n.from(e.signer.preAuthTx,"hex")),!n.isBuffer(e.signer.preAuthTx)||32!==e.signer.preAuthTx.length)throw new Error("signer.preAuthTx must be 32 bytes Buffer.");r=new i.default.SignerKey.signerKeyTypePreAuthTx(e.signer.preAuthTx),c+=1}if(e.signer.sha256Hash){if("string"==typeof e.signer.sha256Hash&&(e.signer.sha256Hash=n.from(e.signer.sha256Hash,"hex")),!n.isBuffer(e.signer.sha256Hash)||32!==e.signer.sha256Hash.length)throw new Error("signer.sha256Hash must be 32 bytes Buffer.");r=new i.default.SignerKey.signerKeyTypeHashX(e.signer.sha256Hash),c+=1}if(e.signer.ed25519SignedPayload){if(!s.StrKey.isValidSignedPayload(e.signer.ed25519SignedPayload))throw new Error("signer.ed25519SignedPayload is invalid.");var f=s.StrKey.decodeSignedPayload(e.signer.ed25519SignedPayload),p=i.default.SignerKeyEd25519SignedPayload.fromXDR(f);r=i.default.SignerKey.signerKeyTypeEd25519SignedPayload(p),c+=1}if(1!==c)throw new Error("Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx.");t.signer=new i.default.Signer({key:r,weight:o})}var d=new i.default.SetOptionsOp(t),h={};return h.body=i.default.OperationBody.setOptions(d),this.setSourceAccount(h,e),new i.default.Operation(h)};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(6691),s=r(7120);function u(e,t){if(e>=0&&e<=255)return!0;throw new Error("".concat(t," value must be between 0 and 255"))}},1804:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setTrustLineFlags=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};if("object"!==a(e.flags)||0===Object.keys(e.flags).length)throw new Error("opts.flags must be a map of boolean flags to modify");var r={authorized:o.default.TrustLineFlags.authorizedFlag(),authorizedToMaintainLiabilities:o.default.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),clawbackEnabled:o.default.TrustLineFlags.trustlineClawbackEnabledFlag()},n=0,s=0;Object.keys(e.flags).forEach((function(t){if(!Object.prototype.hasOwnProperty.call(r,t))throw new Error("unsupported flag name specified: ".concat(t));var o=e.flags[t],i=r[t].value;!0===o?s|=i:!1===o&&(n|=i)})),t.trustor=i.Keypair.fromPublicKey(e.trustor).xdrAccountId(),t.asset=e.asset.toXDRObject(),t.clearFlags=n,t.setFlags=s;var u={body:o.default.OperationBody.setTrustLineFlags(new o.default.SetTrustLineFlagsOp(t))};return this.setSourceAccount(u,e),new o.default.Operation(u)};var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(6691);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}},7177:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.nativeToScVal=function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};switch(f(t)){case"object":var o,l,p;if(null===t)return i.default.ScVal.scvVoid();if(t instanceof i.default.ScVal)return t;if(t instanceof a.Address)return t.toScVal();if(t instanceof s.Contract)return t.address().toScVal();if(t instanceof Uint8Array||n.isBuffer(t)){var d,h=Uint8Array.from(t);switch(null!==(d=null==r?void 0:r.type)&&void 0!==d?d:"bytes"){case"bytes":return i.default.ScVal.scvBytes(h);case"symbol":return i.default.ScVal.scvSymbol(h);case"string":return i.default.ScVal.scvString(h);default:throw new TypeError("invalid type (".concat(r.type,") specified for bytes-like value"))}}if(Array.isArray(t)){if(t.length>0&&t.some((function(e){return f(e)!==f(t[0])})))throw new TypeError("array values (".concat(t,") must have the same type (types: ").concat(t.map((function(e){return f(e)})).join(","),")"));return i.default.ScVal.scvVec(t.map((function(t){return e(t,r)})))}if("Object"!==(null!==(o=null===(l=t.constructor)||void 0===l?void 0:l.name)&&void 0!==o?o:""))throw new TypeError("cannot interpret ".concat(null===(p=t.constructor)||void 0===p?void 0:p.name," value as ScVal (").concat(JSON.stringify(t),")"));return i.default.ScVal.scvMap(Object.entries(t).sort((function(e,t){var r=c(e,1)[0],n=c(t,1)[0];return r.localeCompare(n)})).map((function(t){var n,o,a=c(t,2),s=a[0],u=a[1],l=c(null!==(n=(null!==(o=null==r?void 0:r.type)&&void 0!==o?o:{})[s])&&void 0!==n?n:[null,null],2),f=l[0],p=l[1],d=f?{type:f}:{},h=p?{type:p}:{};return new i.default.ScMapEntry({key:e(s,d),val:e(u,h)})})));case"number":case"bigint":switch(null==r?void 0:r.type){case"u32":return i.default.ScVal.scvU32(t);case"i32":return i.default.ScVal.scvI32(t)}return new u.ScInt(t,{type:null==r?void 0:r.type}).toScVal();case"string":var y,m=null!==(y=null==r?void 0:r.type)&&void 0!==y?y:"string";switch(m){case"string":return i.default.ScVal.scvString(t);case"symbol":return i.default.ScVal.scvSymbol(t);case"address":return new a.Address(t).toScVal();case"u32":return i.default.ScVal.scvU32(parseInt(t,10));case"i32":return i.default.ScVal.scvI32(parseInt(t,10));default:if(u.XdrLargeInt.isType(m))return new u.XdrLargeInt(m,t).toScVal();throw new TypeError("invalid type (".concat(r.type,") specified for string value"))}case"boolean":return i.default.ScVal.scvBool(t);case"undefined":return i.default.ScVal.scvVoid();case"function":return e(t());default:throw new TypeError("failed to convert typeof ".concat(f(t)," (").concat(t,")"))}},t.scValToNative=function e(t){var r,o;switch(t.switch().value){case i.default.ScValType.scvVoid().value:return null;case i.default.ScValType.scvU64().value:case i.default.ScValType.scvI64().value:return t.value().toBigInt();case i.default.ScValType.scvU128().value:case i.default.ScValType.scvI128().value:case i.default.ScValType.scvU256().value:case i.default.ScValType.scvI256().value:return(0,u.scValToBigInt)(t);case i.default.ScValType.scvVec().value:return(null!==(r=t.vec())&&void 0!==r?r:[]).map(e);case i.default.ScValType.scvAddress().value:return a.Address.fromScVal(t).toString();case i.default.ScValType.scvMap().value:return Object.fromEntries((null!==(o=t.map())&&void 0!==o?o:[]).map((function(t){return[e(t.key()),e(t.val())]})));case i.default.ScValType.scvBool().value:case i.default.ScValType.scvU32().value:case i.default.ScValType.scvI32().value:case i.default.ScValType.scvBytes().value:return t.value();case i.default.ScValType.scvSymbol().value:case i.default.ScValType.scvString().value:var s=t.value();if(n.isBuffer(s)||ArrayBuffer.isView(s))try{return(new TextDecoder).decode(s)}catch(e){return new Uint8Array(s.buffer)}return s;case i.default.ScValType.scvTimepoint().value:case i.default.ScValType.scvDuration().value:return new i.default.Uint64(t.value()).toBigInt();case i.default.ScValType.scvError().value:if(t.error().switch().value===i.default.ScErrorType.sceContract().value)return{type:"contract",code:t.error().contractCode()};var c=t.error();return{type:"system",code:c.code().value,value:c.code().name};default:return t.value()}};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(1180),s=r(7452),u=r(8549);function c(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return l(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?l(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SignerKey=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n},i=r(7120);function a(e){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a(e)}function s(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.FastSigning=void 0,t.generate=function(e){return o.generate(e)},t.sign=function(e,t){return o.sign(e,t)},t.verify=function(e,t,r){return o.verify(e,t,r)};var o={};t.FastSigning="undefined"==typeof window?function(){var e;try{e=r(Object(function(){var e=new Error("Cannot find module 'sodium-native'");throw e.code="MODULE_NOT_FOUND",e}()))}catch(e){return i()}return Object.keys(e).length?(o.generate=function(t){var r=n.alloc(e.crypto_sign_PUBLICKEYBYTES),o=n.alloc(e.crypto_sign_SECRETKEYBYTES);return e.crypto_sign_seed_keypair(r,o,t),r},o.sign=function(t,r){t=n.from(t);var o=n.alloc(e.crypto_sign_BYTES);return e.crypto_sign_detached(o,t,r),o},o.verify=function(t,r,o){t=n.from(t);try{return e.crypto_sign_verify_detached(r,t,o)}catch(e){return!1}},!0):i()}():i();function i(){var e=r(4940);return o.generate=function(t){var r=new Uint8Array(t),o=e.sign.keyPair.fromSeed(r);return n.from(o.publicKey)},o.sign=function(t,r){t=n.from(t),t=new Uint8Array(t.toJSON().data),r=new Uint8Array(r.toJSON().data);var o=e.sign.detached(t,r);return n.from(o)},o.verify=function(t,r,o){return t=n.from(t),t=new Uint8Array(t.toJSON().data),r=new Uint8Array(r.toJSON().data),o=new Uint8Array(o.toJSON().data),e.sign.detached.verify(t,r,o)},!1}},4062:(e,t)=>{"use strict";function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}function n(e){return function(e){if(Array.isArray(e))return e}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return o(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?o(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r0&&(r=t>r.length?["0",r.toString().padStart(t,"0")].join("."):[r.slice(0,-t),r.slice(-t)].join(".")),r.replace(/(\.\d*?)0+$/,"$1")}},{key:"parseTokenAmount",value:function(e,t){var r,o=n(e.split(".").slice()),i=o[0],a=o[1];if(o.slice(2).length)throw new Error("Invalid decimal value: ".concat(e));return BigInt(i+(null!==(r=null==a?void 0:a.padEnd(t,"0"))&&void 0!==r?r:"0".repeat(t))).toString()}}],(t=null)&&i(e.prototype,t),r&&i(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,r}()},4842:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SorobanDataBuilder=void 0;var n,o=(n=r(1918))&&n.__esModule?n:{default:n};function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){for(var r=0;r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.StrKey=void 0,t.decodeCheck=d,t.encodeCheck=h;var o,i=(o=r(5360))&&o.__esModule?o:{default:o},a=r(1346);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){for(var r=0;r165)return!1;break;default:return!1}var r="";try{r=d(e,t)}catch(e){return!1}switch(e){case"ed25519PublicKey":case"ed25519SecretSeed":case"preAuthTx":case"sha256Hash":case"contract":return 32===r.length;case"med25519PublicKey":return 40===r.length;case"signedPayload":return r.length>=40&&r.length<=100;default:return!1}}function d(e,t){if("string"!=typeof t)throw new TypeError("encoded argument must be of type String");var r=i.default.decode(t),o=r[0],s=r.slice(0,-2),u=s.slice(1),c=r.slice(-2);if(t!==i.default.encode(r))throw new Error("invalid encoded string");var f=l[e];if(void 0===f)throw new Error("".concat(e," is not a valid version byte name. ")+"Expected one of ".concat(Object.keys(l).join(", ")));if(o!==f)throw new Error("invalid version byte. expected ".concat(f,", got ").concat(o));var p=y(s);if(!(0,a.verifyChecksum)(p,c))throw new Error("invalid checksum");return n.from(u)}function h(e,t){if(null==t)throw new Error("cannot encode null data");var r=l[e];if(void 0===r)throw new Error("".concat(e," is not a valid version byte name. ")+"Expected one of ".concat(Object.keys(l).join(", ")));t=n.from(t);var o=n.from([r]),a=n.concat([o,t]),s=n.from(y(a)),u=n.concat([a,s]);return i.default.encode(u)}function y(e){for(var t=[0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920],r=0,n=0;n>8^e[n]],r&=65535}var o=new Uint8Array(2);return o[0]=255&r,o[1]=r>>8&255,o}},380:(e,t,r)=>{"use strict";var n=r(8287).Buffer;function o(e){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.Transaction=void 0;var i,a=(i=r(1918))&&i.__esModule?i:{default:i},s=r(9152),u=r(7120),c=r(7237),l=r(4172),f=r(3758),p=r(6160);function d(e,t){for(var r=0;r=this.operations.length)throw new RangeError("invalid operation index");var t=this.operations[e];try{t=c.Operation.createClaimableBalance(t)}catch(e){throw new TypeError("expected createClaimableBalance, got ".concat(t.type,": ").concat(e))}var r=u.StrKey.decodeEd25519PublicKey((0,p.extractBaseAddress)(this.source)),n=a.default.HashIdPreimage.envelopeTypeOpId(new a.default.HashIdPreimageOperationId({sourceAccount:a.default.AccountId.publicKeyTypeEd25519(r),seqNum:a.default.SequenceNumber.fromString(this.sequence),opNum:e})),o=(0,s.hash)(n.toXDR("raw"));return a.default.ClaimableBalanceId.claimableBalanceIdTypeV0(o).toXDR("hex")}}])}(f.TransactionBase)},3758:(e,t,r)=>{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionBase=void 0;var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(9152),s=r(6691);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:"",o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(!o||"string"!=typeof o)throw new Error("Invalid signature");if(!r||"string"!=typeof r)throw new Error("Invalid publicKey");var a=n.from(o,"base64");try{t=(e=s.Keypair.fromPublicKey(r)).signatureHint()}catch(e){throw new Error("Invalid publicKey")}if(!e.verify(this.hash(),a))throw new Error("Invalid signature");this.signatures.push(new i.default.DecoratedSignature({hint:t,signature:a}))}},{key:"addDecoratedSignature",value:function(e){this.signatures.push(e)}},{key:"signHashX",value:function(e){if("string"==typeof e&&(e=n.from(e,"hex")),e.length>64)throw new Error("preimage cannnot be longer than 64 bytes");var t=e,r=(0,a.hash)(e),o=r.slice(r.length-4);this.signatures.push(new i.default.DecoratedSignature({hint:o,signature:t}))}},{key:"hash",value:function(){return(0,a.hash)(this.signatureBase())}},{key:"signatureBase",value:function(){throw new Error("Implement in subclass")}},{key:"toEnvelope",value:function(){throw new Error("Implement in subclass")}},{key:"toXDR",value:function(){return this.toEnvelope().toXDR().toString("base64")}}])}()},6396:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TransactionBuilder=t.TimeoutInfinite=t.BASE_FEE=void 0,t.isValidDate=T;var n=r(3740),o=y(r(1242)),i=y(r(1918)),a=r(2135),s=r(2243),u=r(6160),c=r(380),l=r(9260),f=r(4842),p=r(7120),d=r(225),h=r(4172);function y(e){return e&&e.__esModule?e:{default:e}}function m(e){return m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},m(e)}function v(e){return function(e){if(Array.isArray(e))return g(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return g(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?g(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function g(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r1&&void 0!==arguments[1]?arguments[1]:{};if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),!t)throw new Error("must specify source account for the transaction");if(void 0===r.fee)throw new Error("must specify fee for the transaction (in stroops)");this.source=t,this.operations=[],this.baseFee=r.fee,this.timebounds=r.timebounds?w({},r.timebounds):null,this.ledgerbounds=r.ledgerbounds?w({},r.ledgerbounds):null,this.minAccountSequence=r.minAccountSequence||null,this.minAccountSequenceAge=r.minAccountSequenceAge||null,this.minAccountSequenceLedgerGap=r.minAccountSequenceLedgerGap||null,this.extraSigners=r.extraSigners?v(r.extraSigners):null,this.memo=r.memo||h.Memo.none(),this.networkPassphrase=r.networkPassphrase||null,this.sorobanData=r.sorobanData?new f.SorobanDataBuilder(r.sorobanData).build():null}return t=e,y=[{key:"cloneFrom",value:function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!(t instanceof c.Transaction))throw new TypeError("expected a 'Transaction', got: ".concat(t));var n,o=(BigInt(t.sequence)-1n).toString();if(p.StrKey.isValidMed25519PublicKey(t.source))n=s.MuxedAccount.fromAddress(t.source,o);else{if(!p.StrKey.isValidEd25519PublicKey(t.source))throw new TypeError("unsupported tx source account: ".concat(t.source));n=new a.Account(t.source,o)}var i=new e(n,w({fee:(parseInt(t.fee,10)/t.operations.length||k).toString(),memo:t.memo,networkPassphrase:t.networkPassphrase,timebounds:t.timeBounds,ledgerbounds:t.ledgerBounds,minAccountSequence:t.minAccountSequence,minAccountSequenceAge:t.minAccountSequenceAge,minAccountSequenceLedgerGap:t.minAccountSequenceLedgerGap,extraSigners:t.extraSigners},r));return t._tx.operations().forEach((function(e){return i.addOperation(e)})),i}},{key:"buildFeeBumpTransaction",value:function(e,t,r,n){var a=r.operations.length,s=new o.default(r.fee).div(a),c=new o.default(t);if(c.lt(s))throw new Error("Invalid baseFee, it should be at least ".concat(s," stroops."));var f=new o.default(k);if(c.lt(f))throw new Error("Invalid baseFee, it should be at least ".concat(f," stroops."));var p,d=r.toEnvelope();if(d.switch()===i.default.EnvelopeType.envelopeTypeTxV0()){var h=d.v0().tx(),y=new i.default.Transaction({sourceAccount:new i.default.MuxedAccount.keyTypeEd25519(h.sourceAccountEd25519()),fee:h.fee(),seqNum:h.seqNum(),cond:i.default.Preconditions.precondTime(h.timeBounds()),memo:h.memo(),operations:h.operations(),ext:new i.default.TransactionExt(0)});d=new i.default.TransactionEnvelope.envelopeTypeTx(new i.default.TransactionV1Envelope({tx:y,signatures:d.v0().signatures()}))}p="string"==typeof e?(0,u.decodeAddressToMuxedAccount)(e):e.xdrMuxedAccount();var m=new i.default.FeeBumpTransaction({feeSource:p,fee:i.default.Int64.fromString(c.times(a+1).toString()),innerTx:i.default.FeeBumpTransactionInnerTx.envelopeTypeTx(d.v1()),ext:new i.default.FeeBumpTransactionExt(0)}),v=new i.default.FeeBumpTransactionEnvelope({tx:m,signatures:[]}),g=new i.default.TransactionEnvelope.envelopeTypeTxFeeBump(v);return new l.FeeBumpTransaction(g,n)}},{key:"fromXDR",value:function(e,t){return"string"==typeof e&&(e=i.default.TransactionEnvelope.fromXDR(e,"base64")),e.switch()===i.default.EnvelopeType.envelopeTypeTxFeeBump()?new l.FeeBumpTransaction(e,t):new c.Transaction(e,t)}}],(r=[{key:"addOperation",value:function(e){return this.operations.push(e),this}},{key:"addOperationAt",value:function(e,t){return this.operations.splice(t,0,e),this}},{key:"clearOperations",value:function(){return this.operations=[],this}},{key:"clearOperationAt",value:function(e){return this.operations.splice(e,1),this}},{key:"addMemo",value:function(e){return this.memo=e,this}},{key:"setTimeout",value:function(e){if(null!==this.timebounds&&this.timebounds.maxTime>0)throw new Error("TimeBounds.max_time has been already set - setting timeout would overwrite it.");if(e<0)throw new Error("timeout cannot be negative");if(e>0){var t=Math.floor(Date.now()/1e3)+e;null===this.timebounds?this.timebounds={minTime:0,maxTime:t}:this.timebounds={minTime:this.timebounds.minTime,maxTime:t}}else this.timebounds={minTime:0,maxTime:0};return this}},{key:"setTimebounds",value:function(e,t){if("number"==typeof e&&(e=new Date(1e3*e)),"number"==typeof t&&(t=new Date(1e3*t)),null!==this.timebounds)throw new Error("TimeBounds has been already set - setting timebounds would overwrite it.");var r=Math.floor(e.valueOf()/1e3),n=Math.floor(t.valueOf()/1e3);if(r<0)throw new Error("min_time cannot be negative");if(n<0)throw new Error("max_time cannot be negative");if(n>0&&r>n)throw new Error("min_time cannot be greater than max_time");return this.timebounds={minTime:r,maxTime:n},this}},{key:"setLedgerbounds",value:function(e,t){if(null!==this.ledgerbounds)throw new Error("LedgerBounds has been already set - setting ledgerbounds would overwrite it.");if(e<0)throw new Error("min_ledger cannot be negative");if(t<0)throw new Error("max_ledger cannot be negative");if(t>0&&e>t)throw new Error("min_ledger cannot be greater than max_ledger");return this.ledgerbounds={minLedger:e,maxLedger:t},this}},{key:"setMinAccountSequence",value:function(e){if(null!==this.minAccountSequence)throw new Error("min_account_sequence has been already set - setting min_account_sequence would overwrite it.");return this.minAccountSequence=e,this}},{key:"setMinAccountSequenceAge",value:function(e){if("number"!=typeof e)throw new Error("min_account_sequence_age must be a number");if(null!==this.minAccountSequenceAge)throw new Error("min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.");if(e<0)throw new Error("min_account_sequence_age cannot be negative");return this.minAccountSequenceAge=e,this}},{key:"setMinAccountSequenceLedgerGap",value:function(e){if(null!==this.minAccountSequenceLedgerGap)throw new Error("min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.");if(e<0)throw new Error("min_account_sequence_ledger_gap cannot be negative");return this.minAccountSequenceLedgerGap=e,this}},{key:"setExtraSigners",value:function(e){if(!Array.isArray(e))throw new Error("extra_signers must be an array of strings.");if(null!==this.extraSigners)throw new Error("extra_signers has been already set - setting extra_signers would overwrite it.");if(e.length>2)throw new Error("extra_signers cannot be longer than 2 elements.");return this.extraSigners=v(e),this}},{key:"setNetworkPassphrase",value:function(e){return this.networkPassphrase=e,this}},{key:"setSorobanData",value:function(e){return this.sorobanData=new f.SorobanDataBuilder(e).build(),this}},{key:"build",value:function(){var e=new o.default(this.source.sequenceNumber()).plus(1),t={fee:new o.default(this.baseFee).times(this.operations.length).toNumber(),seqNum:i.default.SequenceNumber.fromString(e.toString()),memo:this.memo?this.memo.toXDRObject():null};if(null===this.timebounds||void 0===this.timebounds.minTime||void 0===this.timebounds.maxTime)throw new Error("TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).");T(this.timebounds.minTime)&&(this.timebounds.minTime=this.timebounds.minTime.getTime()/1e3),T(this.timebounds.maxTime)&&(this.timebounds.maxTime=this.timebounds.maxTime.getTime()/1e3),this.timebounds.minTime=n.UnsignedHyper.fromString(this.timebounds.minTime.toString()),this.timebounds.maxTime=n.UnsignedHyper.fromString(this.timebounds.maxTime.toString());var r=new i.default.TimeBounds(this.timebounds);if(this.hasV2Preconditions()){var a=null;null!==this.ledgerbounds&&(a=new i.default.LedgerBounds(this.ledgerbounds));var s=this.minAccountSequence||"0";s=i.default.SequenceNumber.fromString(s);var l=n.UnsignedHyper.fromString(null!==this.minAccountSequenceAge?this.minAccountSequenceAge.toString():"0"),f=this.minAccountSequenceLedgerGap||0,p=null!==this.extraSigners?this.extraSigners.map(d.SignerKey.decodeAddress):[];t.cond=i.default.Preconditions.precondV2(new i.default.PreconditionsV2({timeBounds:r,ledgerBounds:a,minSeqNum:s,minSeqAge:l,minSeqLedgerGap:f,extraSigners:p}))}else t.cond=i.default.Preconditions.precondTime(r);t.sourceAccount=(0,u.decodeAddressToMuxedAccount)(this.source.accountId()),this.sorobanData?t.ext=new i.default.TransactionExt(1,this.sorobanData):t.ext=new i.default.TransactionExt(0,i.default.Void);var h=new i.default.Transaction(t);h.operations(this.operations);var y=new i.default.TransactionEnvelope.envelopeTypeTx(new i.default.TransactionV1Envelope({tx:h})),m=new c.Transaction(y,this.networkPassphrase);return this.source.incrementSequenceNumber(),m}},{key:"hasV2Preconditions",value:function(){return null!==this.ledgerbounds||null!==this.minAccountSequence||null!==this.minAccountSequenceAge||null!==this.minAccountSequenceLedgerGap||null!==this.extraSigners&&this.extraSigners.length>0}}])&&E(t.prototype,r),y&&E(t,y),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,y}();function T(e){return e instanceof Date&&!isNaN(e)}},1242:(e,t,r)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=((n=r(1594))&&n.__esModule?n:{default:n}).default.clone();o.DEBUG=!0;t.default=o},1346:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.verifyChecksum=function(e,t){if(e.length!==t.length)return!1;if(0===e.length)return!0;for(var r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.best_r=function(e){var t,r,n=new o.default(e),s=[[new o.default(0),new o.default(1)],[new o.default(1),new o.default(0)]],u=2;for(;!n.gt(a);){t=n.integerValue(o.default.ROUND_FLOOR),r=n.minus(t);var c=t.times(s[u-1][0]).plus(s[u-2][0]),l=t.times(s[u-1][1]).plus(s[u-2][1]);if(c.gt(a)||l.gt(a))break;if(s.push([c,l]),r.eq(0))break;n=new o.default(1).div(r),u+=1}var f=(h=s[s.length-1],y=2,function(e){if(Array.isArray(e))return e}(h)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(h,y)||function(e,t){if(e){if("string"==typeof e)return i(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(e,t):void 0}}(h,y)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),p=f[0],d=f[1];var h,y;if(p.isZero()||d.isZero())throw new Error("Couldn't find approximation");return[p.toNumber(),d.toNumber()]};var n,o=(n=r(1242))&&n.__esModule?n:{default:n};function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r{"use strict";var n=r(8287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.decodeAddressToMuxedAccount=s,t.encodeMuxedAccount=function(e,t){if(!a.StrKey.isValidEd25519PublicKey(e))throw new Error("address should be a Stellar account ID (G...)");if("string"!=typeof t)throw new Error("id should be a string representing a number (uint64)");return i.default.MuxedAccount.keyTypeMuxedEd25519(new i.default.MuxedAccountMed25519({id:i.default.Uint64.fromString(t),ed25519:a.StrKey.decodeEd25519PublicKey(e)}))},t.encodeMuxedAccountToAddress=u,t.extractBaseAddress=function(e){if(a.StrKey.isValidEd25519PublicKey(e))return e;if(!a.StrKey.isValidMed25519PublicKey(e))throw new TypeError("expected muxed account (M...), got ".concat(e));var t=s(e);return a.StrKey.encodeEd25519PublicKey(t.med25519().ed25519())};var o,i=(o=r(1918))&&o.__esModule?o:{default:o},a=r(7120);function s(e){return a.StrKey.isValidMed25519PublicKey(e)?function(e){var t=a.StrKey.decodeMed25519PublicKey(e);return i.default.MuxedAccount.keyTypeMuxedEd25519(new i.default.MuxedAccountMed25519({id:i.default.Uint64.fromXDR(t.subarray(-8)),ed25519:t.subarray(0,-8)}))}(e):i.default.MuxedAccount.keyTypeEd25519(a.StrKey.decodeEd25519PublicKey(e))}function u(e){return e.switch().value===i.default.CryptoKeyType.keyTypeMuxedEd25519().value?function(e){if(e.switch()===i.default.CryptoKeyType.keyTypeEd25519())return u(e);var t=e.med25519();return a.StrKey.encodeMed25519PublicKey(n.concat([t.ed25519(),t.id().toXDR("raw")]))}(e):a.StrKey.encodeEd25519PublicKey(e.ed25519())}},645:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.trimEnd=void 0;t.trimEnd=function(e,t){for(var r="number"==typeof e,n=String(e);n.endsWith(t);)n=n.slice(0,-1);return r?Number(n):n}},1918:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n,o=(n=r(7938))&&n.__esModule?n:{default:n};t.default=o.default},4940:(e,t,r)=>{!function(e){"use strict";var t=function(e){var t,r=new Float64Array(16);if(e)for(t=0;t>24&255,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r,e[t+4]=n>>24&255,e[t+5]=n>>16&255,e[t+6]=n>>8&255,e[t+7]=255&n}function y(e,t,r,n,o){var i,a=0;for(i=0;i>>8)-1}function m(e,t,r,n){return y(e,t,r,n,16)}function v(e,t,r,n){return y(e,t,r,n,32)}function g(e,t,r,n){!function(e,t,r,n){for(var o,i=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,s=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,c=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,l=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,p=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,h=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,y=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,m=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,v=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,g=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,b=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,w=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,S=i,E=a,_=s,k=u,T=c,O=l,x=f,A=p,P=d,R=h,j=y,C=m,I=v,L=g,B=b,N=w,U=0;U<20;U+=2)S^=(o=(I^=(o=(P^=(o=(T^=(o=S+I|0)<<7|o>>>25)+S|0)<<9|o>>>23)+T|0)<<13|o>>>19)+P|0)<<18|o>>>14,O^=(o=(E^=(o=(L^=(o=(R^=(o=O+E|0)<<7|o>>>25)+O|0)<<9|o>>>23)+R|0)<<13|o>>>19)+L|0)<<18|o>>>14,j^=(o=(x^=(o=(_^=(o=(B^=(o=j+x|0)<<7|o>>>25)+j|0)<<9|o>>>23)+B|0)<<13|o>>>19)+_|0)<<18|o>>>14,N^=(o=(C^=(o=(A^=(o=(k^=(o=N+C|0)<<7|o>>>25)+N|0)<<9|o>>>23)+k|0)<<13|o>>>19)+A|0)<<18|o>>>14,S^=(o=(k^=(o=(_^=(o=(E^=(o=S+k|0)<<7|o>>>25)+S|0)<<9|o>>>23)+E|0)<<13|o>>>19)+_|0)<<18|o>>>14,O^=(o=(T^=(o=(A^=(o=(x^=(o=O+T|0)<<7|o>>>25)+O|0)<<9|o>>>23)+x|0)<<13|o>>>19)+A|0)<<18|o>>>14,j^=(o=(R^=(o=(P^=(o=(C^=(o=j+R|0)<<7|o>>>25)+j|0)<<9|o>>>23)+C|0)<<13|o>>>19)+P|0)<<18|o>>>14,N^=(o=(B^=(o=(L^=(o=(I^=(o=N+B|0)<<7|o>>>25)+N|0)<<9|o>>>23)+I|0)<<13|o>>>19)+L|0)<<18|o>>>14;S=S+i|0,E=E+a|0,_=_+s|0,k=k+u|0,T=T+c|0,O=O+l|0,x=x+f|0,A=A+p|0,P=P+d|0,R=R+h|0,j=j+y|0,C=C+m|0,I=I+v|0,L=L+g|0,B=B+b|0,N=N+w|0,e[0]=S>>>0&255,e[1]=S>>>8&255,e[2]=S>>>16&255,e[3]=S>>>24&255,e[4]=E>>>0&255,e[5]=E>>>8&255,e[6]=E>>>16&255,e[7]=E>>>24&255,e[8]=_>>>0&255,e[9]=_>>>8&255,e[10]=_>>>16&255,e[11]=_>>>24&255,e[12]=k>>>0&255,e[13]=k>>>8&255,e[14]=k>>>16&255,e[15]=k>>>24&255,e[16]=T>>>0&255,e[17]=T>>>8&255,e[18]=T>>>16&255,e[19]=T>>>24&255,e[20]=O>>>0&255,e[21]=O>>>8&255,e[22]=O>>>16&255,e[23]=O>>>24&255,e[24]=x>>>0&255,e[25]=x>>>8&255,e[26]=x>>>16&255,e[27]=x>>>24&255,e[28]=A>>>0&255,e[29]=A>>>8&255,e[30]=A>>>16&255,e[31]=A>>>24&255,e[32]=P>>>0&255,e[33]=P>>>8&255,e[34]=P>>>16&255,e[35]=P>>>24&255,e[36]=R>>>0&255,e[37]=R>>>8&255,e[38]=R>>>16&255,e[39]=R>>>24&255,e[40]=j>>>0&255,e[41]=j>>>8&255,e[42]=j>>>16&255,e[43]=j>>>24&255,e[44]=C>>>0&255,e[45]=C>>>8&255,e[46]=C>>>16&255,e[47]=C>>>24&255,e[48]=I>>>0&255,e[49]=I>>>8&255,e[50]=I>>>16&255,e[51]=I>>>24&255,e[52]=L>>>0&255,e[53]=L>>>8&255,e[54]=L>>>16&255,e[55]=L>>>24&255,e[56]=B>>>0&255,e[57]=B>>>8&255,e[58]=B>>>16&255,e[59]=B>>>24&255,e[60]=N>>>0&255,e[61]=N>>>8&255,e[62]=N>>>16&255,e[63]=N>>>24&255}(e,t,r,n)}function b(e,t,r,n){!function(e,t,r,n){for(var o,i=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,s=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,c=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,l=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,p=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,h=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,y=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,m=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,v=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,g=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,b=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,w=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,S=0;S<20;S+=2)i^=(o=(v^=(o=(d^=(o=(c^=(o=i+v|0)<<7|o>>>25)+i|0)<<9|o>>>23)+c|0)<<13|o>>>19)+d|0)<<18|o>>>14,l^=(o=(a^=(o=(g^=(o=(h^=(o=l+a|0)<<7|o>>>25)+l|0)<<9|o>>>23)+h|0)<<13|o>>>19)+g|0)<<18|o>>>14,y^=(o=(f^=(o=(s^=(o=(b^=(o=y+f|0)<<7|o>>>25)+y|0)<<9|o>>>23)+b|0)<<13|o>>>19)+s|0)<<18|o>>>14,w^=(o=(m^=(o=(p^=(o=(u^=(o=w+m|0)<<7|o>>>25)+w|0)<<9|o>>>23)+u|0)<<13|o>>>19)+p|0)<<18|o>>>14,i^=(o=(u^=(o=(s^=(o=(a^=(o=i+u|0)<<7|o>>>25)+i|0)<<9|o>>>23)+a|0)<<13|o>>>19)+s|0)<<18|o>>>14,l^=(o=(c^=(o=(p^=(o=(f^=(o=l+c|0)<<7|o>>>25)+l|0)<<9|o>>>23)+f|0)<<13|o>>>19)+p|0)<<18|o>>>14,y^=(o=(h^=(o=(d^=(o=(m^=(o=y+h|0)<<7|o>>>25)+y|0)<<9|o>>>23)+m|0)<<13|o>>>19)+d|0)<<18|o>>>14,w^=(o=(b^=(o=(g^=(o=(v^=(o=w+b|0)<<7|o>>>25)+w|0)<<9|o>>>23)+v|0)<<13|o>>>19)+g|0)<<18|o>>>14;e[0]=i>>>0&255,e[1]=i>>>8&255,e[2]=i>>>16&255,e[3]=i>>>24&255,e[4]=l>>>0&255,e[5]=l>>>8&255,e[6]=l>>>16&255,e[7]=l>>>24&255,e[8]=y>>>0&255,e[9]=y>>>8&255,e[10]=y>>>16&255,e[11]=y>>>24&255,e[12]=w>>>0&255,e[13]=w>>>8&255,e[14]=w>>>16&255,e[15]=w>>>24&255,e[16]=f>>>0&255,e[17]=f>>>8&255,e[18]=f>>>16&255,e[19]=f>>>24&255,e[20]=p>>>0&255,e[21]=p>>>8&255,e[22]=p>>>16&255,e[23]=p>>>24&255,e[24]=d>>>0&255,e[25]=d>>>8&255,e[26]=d>>>16&255,e[27]=d>>>24&255,e[28]=h>>>0&255,e[29]=h>>>8&255,e[30]=h>>>16&255,e[31]=h>>>24&255}(e,t,r,n)}var w=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function S(e,t,r,n,o,i,a){var s,u,c=new Uint8Array(16),l=new Uint8Array(64);for(u=0;u<16;u++)c[u]=0;for(u=0;u<8;u++)c[u]=i[u];for(;o>=64;){for(g(l,c,a,w),u=0;u<64;u++)e[t+u]=r[n+u]^l[u];for(s=1,u=8;u<16;u++)s=s+(255&c[u])|0,c[u]=255&s,s>>>=8;o-=64,t+=64,n+=64}if(o>0)for(g(l,c,a,w),u=0;u=64;){for(g(u,s,o,w),a=0;a<64;a++)e[t+a]=u[a];for(i=1,a=8;a<16;a++)i=i+(255&s[a])|0,s[a]=255&i,i>>>=8;r-=64,t+=64}if(r>0)for(g(u,s,o,w),a=0;a>>13|r<<3),n=255&e[4]|(255&e[5])<<8,this.r[2]=7939&(r>>>10|n<<6),o=255&e[6]|(255&e[7])<<8,this.r[3]=8191&(n>>>7|o<<9),i=255&e[8]|(255&e[9])<<8,this.r[4]=255&(o>>>4|i<<12),this.r[5]=i>>>1&8190,a=255&e[10]|(255&e[11])<<8,this.r[6]=8191&(i>>>14|a<<2),s=255&e[12]|(255&e[13])<<8,this.r[7]=8065&(a>>>11|s<<5),u=255&e[14]|(255&e[15])<<8,this.r[8]=8191&(s>>>8|u<<8),this.r[9]=u>>>5&127,this.pad[0]=255&e[16]|(255&e[17])<<8,this.pad[1]=255&e[18]|(255&e[19])<<8,this.pad[2]=255&e[20]|(255&e[21])<<8,this.pad[3]=255&e[22]|(255&e[23])<<8,this.pad[4]=255&e[24]|(255&e[25])<<8,this.pad[5]=255&e[26]|(255&e[27])<<8,this.pad[6]=255&e[28]|(255&e[29])<<8,this.pad[7]=255&e[30]|(255&e[31])<<8};function O(e,t,r,n,o,i){var a=new T(i);return a.update(r,n,o),a.finish(e,t),0}function x(e,t,r,n,o,i){var a=new Uint8Array(16);return O(a,0,r,n,o,i),m(e,t,a,0)}function A(e,t,r,n,o){var i;if(r<32)return-1;for(k(e,0,t,0,r,n,o),O(e,16,e,32,r-32,e),i=0;i<16;i++)e[i]=0;return 0}function P(e,t,r,n,o){var i,a=new Uint8Array(32);if(r<32)return-1;if(_(a,0,32,n,o),0!==x(t,16,t,32,r-32,a))return-1;for(k(e,0,t,0,r,n,o),i=0;i<32;i++)e[i]=0;return 0}function R(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function j(e){var t,r,n=1;for(t=0;t<16;t++)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function C(e,t,r){for(var n,o=~(r-1),i=0;i<16;i++)n=o&(e[i]^t[i]),e[i]^=n,t[i]^=n}function I(e,r){var n,o,i,a=t(),s=t();for(n=0;n<16;n++)s[n]=r[n];for(j(s),j(s),j(s),o=0;o<2;o++){for(a[0]=s[0]-65517,n=1;n<15;n++)a[n]=s[n]-65535-(a[n-1]>>16&1),a[n-1]&=65535;a[15]=s[15]-32767-(a[14]>>16&1),i=a[15]>>16&1,a[14]&=65535,C(s,a,1-i)}for(n=0;n<16;n++)e[2*n]=255&s[n],e[2*n+1]=s[n]>>8}function L(e,t){var r=new Uint8Array(32),n=new Uint8Array(32);return I(r,e),I(n,t),v(r,0,n,0)}function B(e){var t=new Uint8Array(32);return I(t,e),1&t[0]}function N(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function U(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]+r[n]}function M(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]-r[n]}function D(e,t,r){var n,o,i=0,a=0,s=0,u=0,c=0,l=0,f=0,p=0,d=0,h=0,y=0,m=0,v=0,g=0,b=0,w=0,S=0,E=0,_=0,k=0,T=0,O=0,x=0,A=0,P=0,R=0,j=0,C=0,I=0,L=0,B=0,N=r[0],U=r[1],M=r[2],D=r[3],F=r[4],V=r[5],q=r[6],K=r[7],H=r[8],z=r[9],X=r[10],G=r[11],W=r[12],$=r[13],Q=r[14],Y=r[15];i+=(n=t[0])*N,a+=n*U,s+=n*M,u+=n*D,c+=n*F,l+=n*V,f+=n*q,p+=n*K,d+=n*H,h+=n*z,y+=n*X,m+=n*G,v+=n*W,g+=n*$,b+=n*Q,w+=n*Y,a+=(n=t[1])*N,s+=n*U,u+=n*M,c+=n*D,l+=n*F,f+=n*V,p+=n*q,d+=n*K,h+=n*H,y+=n*z,m+=n*X,v+=n*G,g+=n*W,b+=n*$,w+=n*Q,S+=n*Y,s+=(n=t[2])*N,u+=n*U,c+=n*M,l+=n*D,f+=n*F,p+=n*V,d+=n*q,h+=n*K,y+=n*H,m+=n*z,v+=n*X,g+=n*G,b+=n*W,w+=n*$,S+=n*Q,E+=n*Y,u+=(n=t[3])*N,c+=n*U,l+=n*M,f+=n*D,p+=n*F,d+=n*V,h+=n*q,y+=n*K,m+=n*H,v+=n*z,g+=n*X,b+=n*G,w+=n*W,S+=n*$,E+=n*Q,_+=n*Y,c+=(n=t[4])*N,l+=n*U,f+=n*M,p+=n*D,d+=n*F,h+=n*V,y+=n*q,m+=n*K,v+=n*H,g+=n*z,b+=n*X,w+=n*G,S+=n*W,E+=n*$,_+=n*Q,k+=n*Y,l+=(n=t[5])*N,f+=n*U,p+=n*M,d+=n*D,h+=n*F,y+=n*V,m+=n*q,v+=n*K,g+=n*H,b+=n*z,w+=n*X,S+=n*G,E+=n*W,_+=n*$,k+=n*Q,T+=n*Y,f+=(n=t[6])*N,p+=n*U,d+=n*M,h+=n*D,y+=n*F,m+=n*V,v+=n*q,g+=n*K,b+=n*H,w+=n*z,S+=n*X,E+=n*G,_+=n*W,k+=n*$,T+=n*Q,O+=n*Y,p+=(n=t[7])*N,d+=n*U,h+=n*M,y+=n*D,m+=n*F,v+=n*V,g+=n*q,b+=n*K,w+=n*H,S+=n*z,E+=n*X,_+=n*G,k+=n*W,T+=n*$,O+=n*Q,x+=n*Y,d+=(n=t[8])*N,h+=n*U,y+=n*M,m+=n*D,v+=n*F,g+=n*V,b+=n*q,w+=n*K,S+=n*H,E+=n*z,_+=n*X,k+=n*G,T+=n*W,O+=n*$,x+=n*Q,A+=n*Y,h+=(n=t[9])*N,y+=n*U,m+=n*M,v+=n*D,g+=n*F,b+=n*V,w+=n*q,S+=n*K,E+=n*H,_+=n*z,k+=n*X,T+=n*G,O+=n*W,x+=n*$,A+=n*Q,P+=n*Y,y+=(n=t[10])*N,m+=n*U,v+=n*M,g+=n*D,b+=n*F,w+=n*V,S+=n*q,E+=n*K,_+=n*H,k+=n*z,T+=n*X,O+=n*G,x+=n*W,A+=n*$,P+=n*Q,R+=n*Y,m+=(n=t[11])*N,v+=n*U,g+=n*M,b+=n*D,w+=n*F,S+=n*V,E+=n*q,_+=n*K,k+=n*H,T+=n*z,O+=n*X,x+=n*G,A+=n*W,P+=n*$,R+=n*Q,j+=n*Y,v+=(n=t[12])*N,g+=n*U,b+=n*M,w+=n*D,S+=n*F,E+=n*V,_+=n*q,k+=n*K,T+=n*H,O+=n*z,x+=n*X,A+=n*G,P+=n*W,R+=n*$,j+=n*Q,C+=n*Y,g+=(n=t[13])*N,b+=n*U,w+=n*M,S+=n*D,E+=n*F,_+=n*V,k+=n*q,T+=n*K,O+=n*H,x+=n*z,A+=n*X,P+=n*G,R+=n*W,j+=n*$,C+=n*Q,I+=n*Y,b+=(n=t[14])*N,w+=n*U,S+=n*M,E+=n*D,_+=n*F,k+=n*V,T+=n*q,O+=n*K,x+=n*H,A+=n*z,P+=n*X,R+=n*G,j+=n*W,C+=n*$,I+=n*Q,L+=n*Y,w+=(n=t[15])*N,a+=38*(E+=n*M),s+=38*(_+=n*D),u+=38*(k+=n*F),c+=38*(T+=n*V),l+=38*(O+=n*q),f+=38*(x+=n*K),p+=38*(A+=n*H),d+=38*(P+=n*z),h+=38*(R+=n*X),y+=38*(j+=n*G),m+=38*(C+=n*W),v+=38*(I+=n*$),g+=38*(L+=n*Q),b+=38*(B+=n*Y),i=(n=(i+=38*(S+=n*U))+(o=1)+65535)-65536*(o=Math.floor(n/65536)),a=(n=a+o+65535)-65536*(o=Math.floor(n/65536)),s=(n=s+o+65535)-65536*(o=Math.floor(n/65536)),u=(n=u+o+65535)-65536*(o=Math.floor(n/65536)),c=(n=c+o+65535)-65536*(o=Math.floor(n/65536)),l=(n=l+o+65535)-65536*(o=Math.floor(n/65536)),f=(n=f+o+65535)-65536*(o=Math.floor(n/65536)),p=(n=p+o+65535)-65536*(o=Math.floor(n/65536)),d=(n=d+o+65535)-65536*(o=Math.floor(n/65536)),h=(n=h+o+65535)-65536*(o=Math.floor(n/65536)),y=(n=y+o+65535)-65536*(o=Math.floor(n/65536)),m=(n=m+o+65535)-65536*(o=Math.floor(n/65536)),v=(n=v+o+65535)-65536*(o=Math.floor(n/65536)),g=(n=g+o+65535)-65536*(o=Math.floor(n/65536)),b=(n=b+o+65535)-65536*(o=Math.floor(n/65536)),w=(n=w+o+65535)-65536*(o=Math.floor(n/65536)),i=(n=(i+=o-1+37*(o-1))+(o=1)+65535)-65536*(o=Math.floor(n/65536)),a=(n=a+o+65535)-65536*(o=Math.floor(n/65536)),s=(n=s+o+65535)-65536*(o=Math.floor(n/65536)),u=(n=u+o+65535)-65536*(o=Math.floor(n/65536)),c=(n=c+o+65535)-65536*(o=Math.floor(n/65536)),l=(n=l+o+65535)-65536*(o=Math.floor(n/65536)),f=(n=f+o+65535)-65536*(o=Math.floor(n/65536)),p=(n=p+o+65535)-65536*(o=Math.floor(n/65536)),d=(n=d+o+65535)-65536*(o=Math.floor(n/65536)),h=(n=h+o+65535)-65536*(o=Math.floor(n/65536)),y=(n=y+o+65535)-65536*(o=Math.floor(n/65536)),m=(n=m+o+65535)-65536*(o=Math.floor(n/65536)),v=(n=v+o+65535)-65536*(o=Math.floor(n/65536)),g=(n=g+o+65535)-65536*(o=Math.floor(n/65536)),b=(n=b+o+65535)-65536*(o=Math.floor(n/65536)),w=(n=w+o+65535)-65536*(o=Math.floor(n/65536)),i+=o-1+37*(o-1),e[0]=i,e[1]=a,e[2]=s,e[3]=u,e[4]=c,e[5]=l,e[6]=f,e[7]=p,e[8]=d,e[9]=h,e[10]=y,e[11]=m,e[12]=v,e[13]=g,e[14]=b,e[15]=w}function F(e,t){D(e,t,t)}function V(e,r){var n,o=t();for(n=0;n<16;n++)o[n]=r[n];for(n=253;n>=0;n--)F(o,o),2!==n&&4!==n&&D(o,o,r);for(n=0;n<16;n++)e[n]=o[n]}function q(e,r){var n,o=t();for(n=0;n<16;n++)o[n]=r[n];for(n=250;n>=0;n--)F(o,o),1!==n&&D(o,o,r);for(n=0;n<16;n++)e[n]=o[n]}function K(e,r,n){var o,i,a=new Uint8Array(32),s=new Float64Array(80),c=t(),l=t(),f=t(),p=t(),d=t(),h=t();for(i=0;i<31;i++)a[i]=r[i];for(a[31]=127&r[31]|64,a[0]&=248,N(s,n),i=0;i<16;i++)l[i]=s[i],p[i]=c[i]=f[i]=0;for(c[0]=p[0]=1,i=254;i>=0;--i)C(c,l,o=a[i>>>3]>>>(7&i)&1),C(f,p,o),U(d,c,f),M(c,c,f),U(f,l,p),M(l,l,p),F(p,d),F(h,c),D(c,f,c),D(f,l,d),U(d,c,f),M(c,c,f),F(l,c),M(f,p,h),D(c,f,u),U(c,c,p),D(f,f,c),D(c,p,h),D(p,l,s),F(l,d),C(c,l,o),C(f,p,o);for(i=0;i<16;i++)s[i+16]=c[i],s[i+32]=f[i],s[i+48]=l[i],s[i+64]=p[i];var y=s.subarray(32),m=s.subarray(16);return V(y,y),D(m,m,y),I(e,m),0}function H(e,t){return K(e,t,i)}function z(e,t){return n(t,32),H(e,t)}function X(e,t,r){var n=new Uint8Array(32);return K(n,r,t),b(e,o,n,w)}T.prototype.blocks=function(e,t,r){for(var n,o,i,a,s,u,c,l,f,p,d,h,y,m,v,g,b,w,S,E=this.fin?0:2048,_=this.h[0],k=this.h[1],T=this.h[2],O=this.h[3],x=this.h[4],A=this.h[5],P=this.h[6],R=this.h[7],j=this.h[8],C=this.h[9],I=this.r[0],L=this.r[1],B=this.r[2],N=this.r[3],U=this.r[4],M=this.r[5],D=this.r[6],F=this.r[7],V=this.r[8],q=this.r[9];r>=16;)p=f=0,p+=(_+=8191&(n=255&e[t+0]|(255&e[t+1])<<8))*I,p+=(k+=8191&(n>>>13|(o=255&e[t+2]|(255&e[t+3])<<8)<<3))*(5*q),p+=(T+=8191&(o>>>10|(i=255&e[t+4]|(255&e[t+5])<<8)<<6))*(5*V),p+=(O+=8191&(i>>>7|(a=255&e[t+6]|(255&e[t+7])<<8)<<9))*(5*F),f=(p+=(x+=8191&(a>>>4|(s=255&e[t+8]|(255&e[t+9])<<8)<<12))*(5*D))>>>13,p&=8191,p+=(A+=s>>>1&8191)*(5*M),p+=(P+=8191&(s>>>14|(u=255&e[t+10]|(255&e[t+11])<<8)<<2))*(5*U),p+=(R+=8191&(u>>>11|(c=255&e[t+12]|(255&e[t+13])<<8)<<5))*(5*N),p+=(j+=8191&(c>>>8|(l=255&e[t+14]|(255&e[t+15])<<8)<<8))*(5*B),d=f+=(p+=(C+=l>>>5|E)*(5*L))>>>13,d+=_*L,d+=k*I,d+=T*(5*q),d+=O*(5*V),f=(d+=x*(5*F))>>>13,d&=8191,d+=A*(5*D),d+=P*(5*M),d+=R*(5*U),d+=j*(5*N),f+=(d+=C*(5*B))>>>13,d&=8191,h=f,h+=_*B,h+=k*L,h+=T*I,h+=O*(5*q),f=(h+=x*(5*V))>>>13,h&=8191,h+=A*(5*F),h+=P*(5*D),h+=R*(5*M),h+=j*(5*U),y=f+=(h+=C*(5*N))>>>13,y+=_*N,y+=k*B,y+=T*L,y+=O*I,f=(y+=x*(5*q))>>>13,y&=8191,y+=A*(5*V),y+=P*(5*F),y+=R*(5*D),y+=j*(5*M),m=f+=(y+=C*(5*U))>>>13,m+=_*U,m+=k*N,m+=T*B,m+=O*L,f=(m+=x*I)>>>13,m&=8191,m+=A*(5*q),m+=P*(5*V),m+=R*(5*F),m+=j*(5*D),v=f+=(m+=C*(5*M))>>>13,v+=_*M,v+=k*U,v+=T*N,v+=O*B,f=(v+=x*L)>>>13,v&=8191,v+=A*I,v+=P*(5*q),v+=R*(5*V),v+=j*(5*F),g=f+=(v+=C*(5*D))>>>13,g+=_*D,g+=k*M,g+=T*U,g+=O*N,f=(g+=x*B)>>>13,g&=8191,g+=A*L,g+=P*I,g+=R*(5*q),g+=j*(5*V),b=f+=(g+=C*(5*F))>>>13,b+=_*F,b+=k*D,b+=T*M,b+=O*U,f=(b+=x*N)>>>13,b&=8191,b+=A*B,b+=P*L,b+=R*I,b+=j*(5*q),w=f+=(b+=C*(5*V))>>>13,w+=_*V,w+=k*F,w+=T*D,w+=O*M,f=(w+=x*U)>>>13,w&=8191,w+=A*N,w+=P*B,w+=R*L,w+=j*I,S=f+=(w+=C*(5*q))>>>13,S+=_*q,S+=k*V,S+=T*F,S+=O*D,f=(S+=x*M)>>>13,S&=8191,S+=A*U,S+=P*N,S+=R*B,S+=j*L,_=p=8191&(f=(f=((f+=(S+=C*I)>>>13)<<2)+f|0)+(p&=8191)|0),k=d+=f>>>=13,T=h&=8191,O=y&=8191,x=m&=8191,A=v&=8191,P=g&=8191,R=b&=8191,j=w&=8191,C=S&=8191,t+=16,r-=16;this.h[0]=_,this.h[1]=k,this.h[2]=T,this.h[3]=O,this.h[4]=x,this.h[5]=A,this.h[6]=P,this.h[7]=R,this.h[8]=j,this.h[9]=C},T.prototype.finish=function(e,t){var r,n,o,i,a=new Uint16Array(10);if(this.leftover){for(i=this.leftover,this.buffer[i++]=1;i<16;i++)this.buffer[i]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(r=this.h[1]>>>13,this.h[1]&=8191,i=2;i<10;i++)this.h[i]+=r,r=this.h[i]>>>13,this.h[i]&=8191;for(this.h[0]+=5*r,r=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=r,r=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=r,a[0]=this.h[0]+5,r=a[0]>>>13,a[0]&=8191,i=1;i<10;i++)a[i]=this.h[i]+r,r=a[i]>>>13,a[i]&=8191;for(a[9]-=8192,n=(1^r)-1,i=0;i<10;i++)a[i]&=n;for(n=~n,i=0;i<10;i++)this.h[i]=this.h[i]&n|a[i];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),o=this.h[0]+this.pad[0],this.h[0]=65535&o,i=1;i<8;i++)o=(this.h[i]+this.pad[i]|0)+(o>>>16)|0,this.h[i]=65535&o;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},T.prototype.update=function(e,t,r){var n,o;if(this.leftover){for((o=16-this.leftover)>r&&(o=r),n=0;n=16&&(o=r-r%16,this.blocks(e,t,o),t+=o,r-=o),r){for(n=0;n=128;){for(E=0;E<16;E++)_=8*E+W,R[E]=r[_+0]<<24|r[_+1]<<16|r[_+2]<<8|r[_+3],j[E]=r[_+4]<<24|r[_+5]<<16|r[_+6]<<8|r[_+7];for(E=0;E<80;E++)if(o=C,i=I,a=L,s=B,u=N,c=U,l=M,D,p=F,d=V,h=q,y=K,m=H,v=z,g=X,G,O=65535&(T=G),x=T>>>16,A=65535&(k=D),P=k>>>16,O+=65535&(T=(H>>>14|N<<18)^(H>>>18|N<<14)^(N>>>9|H<<23)),x+=T>>>16,A+=65535&(k=(N>>>14|H<<18)^(N>>>18|H<<14)^(H>>>9|N<<23)),P+=k>>>16,O+=65535&(T=H&z^~H&X),x+=T>>>16,A+=65535&(k=N&U^~N&M),P+=k>>>16,O+=65535&(T=$[2*E+1]),x+=T>>>16,A+=65535&(k=$[2*E]),P+=k>>>16,k=R[E%16],x+=(T=j[E%16])>>>16,A+=65535&k,P+=k>>>16,A+=(x+=(O+=65535&T)>>>16)>>>16,O=65535&(T=S=65535&O|x<<16),x=T>>>16,A=65535&(k=w=65535&A|(P+=A>>>16)<<16),P=k>>>16,O+=65535&(T=(F>>>28|C<<4)^(C>>>2|F<<30)^(C>>>7|F<<25)),x+=T>>>16,A+=65535&(k=(C>>>28|F<<4)^(F>>>2|C<<30)^(F>>>7|C<<25)),P+=k>>>16,x+=(T=F&V^F&q^V&q)>>>16,A+=65535&(k=C&I^C&L^I&L),P+=k>>>16,f=65535&(A+=(x+=(O+=65535&T)>>>16)>>>16)|(P+=A>>>16)<<16,b=65535&O|x<<16,O=65535&(T=y),x=T>>>16,A=65535&(k=s),P=k>>>16,x+=(T=S)>>>16,A+=65535&(k=w),P+=k>>>16,I=o,L=i,B=a,N=s=65535&(A+=(x+=(O+=65535&T)>>>16)>>>16)|(P+=A>>>16)<<16,U=u,M=c,D=l,C=f,V=p,q=d,K=h,H=y=65535&O|x<<16,z=m,X=v,G=g,F=b,E%16==15)for(_=0;_<16;_++)k=R[_],O=65535&(T=j[_]),x=T>>>16,A=65535&k,P=k>>>16,k=R[(_+9)%16],O+=65535&(T=j[(_+9)%16]),x+=T>>>16,A+=65535&k,P+=k>>>16,w=R[(_+1)%16],O+=65535&(T=((S=j[(_+1)%16])>>>1|w<<31)^(S>>>8|w<<24)^(S>>>7|w<<25)),x+=T>>>16,A+=65535&(k=(w>>>1|S<<31)^(w>>>8|S<<24)^w>>>7),P+=k>>>16,w=R[(_+14)%16],x+=(T=((S=j[(_+14)%16])>>>19|w<<13)^(w>>>29|S<<3)^(S>>>6|w<<26))>>>16,A+=65535&(k=(w>>>19|S<<13)^(S>>>29|w<<3)^w>>>6),P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,R[_]=65535&A|P<<16,j[_]=65535&O|x<<16;O=65535&(T=F),x=T>>>16,A=65535&(k=C),P=k>>>16,k=e[0],x+=(T=t[0])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[0]=C=65535&A|P<<16,t[0]=F=65535&O|x<<16,O=65535&(T=V),x=T>>>16,A=65535&(k=I),P=k>>>16,k=e[1],x+=(T=t[1])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[1]=I=65535&A|P<<16,t[1]=V=65535&O|x<<16,O=65535&(T=q),x=T>>>16,A=65535&(k=L),P=k>>>16,k=e[2],x+=(T=t[2])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[2]=L=65535&A|P<<16,t[2]=q=65535&O|x<<16,O=65535&(T=K),x=T>>>16,A=65535&(k=B),P=k>>>16,k=e[3],x+=(T=t[3])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[3]=B=65535&A|P<<16,t[3]=K=65535&O|x<<16,O=65535&(T=H),x=T>>>16,A=65535&(k=N),P=k>>>16,k=e[4],x+=(T=t[4])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[4]=N=65535&A|P<<16,t[4]=H=65535&O|x<<16,O=65535&(T=z),x=T>>>16,A=65535&(k=U),P=k>>>16,k=e[5],x+=(T=t[5])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[5]=U=65535&A|P<<16,t[5]=z=65535&O|x<<16,O=65535&(T=X),x=T>>>16,A=65535&(k=M),P=k>>>16,k=e[6],x+=(T=t[6])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[6]=M=65535&A|P<<16,t[6]=X=65535&O|x<<16,O=65535&(T=G),x=T>>>16,A=65535&(k=D),P=k>>>16,k=e[7],x+=(T=t[7])>>>16,A+=65535&k,P+=k>>>16,P+=(A+=(x+=(O+=65535&T)>>>16)>>>16)>>>16,e[7]=D=65535&A|P<<16,t[7]=G=65535&O|x<<16,W+=128,n-=128}return n}function Y(e,t,r){var n,o=new Int32Array(8),i=new Int32Array(8),a=new Uint8Array(256),s=r;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,i[0]=4089235720,i[1]=2227873595,i[2]=4271175723,i[3]=1595750129,i[4]=2917565137,i[5]=725511199,i[6]=4215389547,i[7]=327033209,Q(o,i,t,r),r%=128,n=0;n=0;--o)Z(e,t,n=r[o/8|0]>>(7&o)&1),J(t,e),J(e,e),Z(e,t,n)}function re(e,r){var n=[t(),t(),t(),t()];R(n[0],f),R(n[1],p),R(n[2],s),D(n[3],f,p),te(e,n,r)}function ne(e,r,o){var i,a=new Uint8Array(64),s=[t(),t(),t(),t()];for(o||n(r,32),Y(a,r,32),a[0]&=248,a[31]&=127,a[31]|=64,re(s,a),ee(e,s),i=0;i<32;i++)r[i+32]=e[i];return 0}var oe=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function ie(e,t){var r,n,o,i;for(n=63;n>=32;--n){for(r=0,o=n-32,i=n-12;o>4)*oe[o],r=t[o]>>8,t[o]&=255;for(o=0;o<32;o++)t[o]-=r*oe[o];for(n=0;n<32;n++)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function ae(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;ie(e,r)}function se(e,r,n,o){var i,a,s=new Uint8Array(64),u=new Uint8Array(64),c=new Uint8Array(64),l=new Float64Array(64),f=[t(),t(),t(),t()];Y(s,o,32),s[0]&=248,s[31]&=127,s[31]|=64;var p=n+64;for(i=0;i>7&&M(e[0],a,e[0]),D(e[3],e[0],e[1]),0)}(p,o))return-1;for(i=0;i=0},e.sign.keyPair=function(){var e=new Uint8Array(fe),t=new Uint8Array(pe);return ne(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(he(e),e.length!==pe)throw new Error("bad secret key size");for(var t=new Uint8Array(fe),r=0;r{"use strict";r.r(t),r.d(t,{StellarBase:()=>a,default:()=>s,httpClient:()=>n.ok});var n=r(9983),o=r(4356),i={};for(const e in o)["default","StellarBase","httpClient"].indexOf(e)<0&&(i[e]=()=>o[e]);r.d(t,i);var a=r(356);const s=(e=r.hmd(e)).exports},8732:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rh});var c,l,f,p={allowHttp:!1,timeout:0},d=a({},p),h=(c=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},f=[{key:"setAllowHttp",value:function(e){d.allowHttp=e}},{key:"setTimeout",value:function(e){d.timeout=e}},{key:"isAllowHttp",value:function(){return d.allowHttp}},{key:"getTimeout",value:function(){return d.timeout}},{key:"setDefault",value:function(){d=a({},p)}}],(l=null)&&o(c.prototype,l),f&&o(c,f),Object.defineProperty(c,"prototype",{writable:!1}),c)},6299:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AssembledTransaction:()=>de,Client:()=>tt,DEFAULT_TIMEOUT:()=>h,Err:()=>d,NULL_ACCOUNT:()=>y,Ok:()=>p,SentTransaction:()=>K,Spec:()=>Ne,basicNodeSigner:()=>be});var n=r(356),o=r(3496),i=r(4076),a=r(8680);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function c(e,t){for(var r=0;r=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),j(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:I(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function v(e){return v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},v(e)}function g(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function b(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){g(i,n,o,a,s,"next",e)}function s(e){g(i,n,o,a,s,"throw",e)}a(void 0)}))}}function w(e,t,r){return S.apply(this,arguments)}function S(){return S=b(m().mark((function e(t,r,n){var o,i,a,s,u,c,l,f=arguments;return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=f.length>3&&void 0!==f[3]?f[3]:1.5,i=f.length>4&&void 0!==f[4]&&f[4],a=[],s=0,e.t0=a,e.next=7,t();case 7:if(e.t1=e.sent,e.t0.push.call(e.t0,e.t1),r(a[a.length-1])){e.next=11;break}return e.abrupt("return",a);case 11:u=new Date(Date.now()+1e3*n).valueOf(),l=c=1e3;case 14:if(!(Date.now()u&&(c=u-Date.now(),i&&console.info("was gonna wait too long; new waitTime: ".concat(c,"ms"))),l=c+l,e.t2=a,e.next=25,t(a[a.length-1]);case 25:e.t3=e.sent,e.t2.push.call(e.t2,e.t3),i&&r(a[a.length-1])&&console.info("".concat(s,". Called ").concat(t,"; ").concat(a.length," prev attempts. Most recent: ").concat(JSON.stringify(a[a.length-1],null,2))),e.next=14;break;case 30:return e.abrupt("return",a);case 31:case"end":return e.stop()}}),e)}))),S.apply(this,arguments)}var E,_=/Error\(Contract, #(\d+)\)/;function k(e){for(var t=new n.cereal.XdrReader(e),r=[];!t.eof;)r.push(n.xdr.ScSpecEntry.read(t));return r}function T(e,t){return O.apply(this,arguments)}function O(){return(O=b(m().mark((function e(t,r){return m().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t.publicKey?r.getAccount(t.publicKey):new n.Account(y,"0"));case 1:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function x(e,t,r){return t=C(t),function(e,t){if(t&&("object"==I(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,R()?Reflect.construct(t,r||[],C(e).constructor):t.apply(e,r))}function A(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&j(e,t)}function P(e){var t="function"==typeof Map?new Map:void 0;return P=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(R())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var o=new(e.bind.apply(e,n));return r&&j(o,r.prototype),o}(e,arguments,C(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),j(r,e)},P(e)}function R(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(R=function(){return!!e})()}function j(e,t){return j=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},j(e,t)}function C(e){return C=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},C(e)}function I(e){return I="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},I(e)}function L(){L=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,E=S&&S(S(j([])));E&&E!==r&&n.call(E,a)&&(w=E);var _=b.prototype=v.prototype=Object.create(w);function k(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==I(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function B(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function N(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){B(i,n,o,a,s,"next",e)}function s(e){B(i,n,o,a,s,"throw",e)}a(void 0)}))}}function U(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function M(e,t){for(var r=0;r=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,i=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw i}}}}function re(){re=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,E=S&&S(S(j([])));E&&E!==r&&n.call(E,a)&&(w=E);var _=b.prototype=v.prototype=Object.create(w);function k(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==Y(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function ne(e){return function(e){if(Array.isArray(e))return ie(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||oe(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function oe(e,t){if(e){if("string"==typeof e)return ie(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ie(e,t):void 0}}function ie(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r0&&void 0!==y[0]?y[0]:{}).restore,u.built){t.next=5;break}if(u.raw){t.next=4;break}throw new Error("Transaction has not yet been assembled; call `AssembledTransaction.build` first.");case 4:u.built=u.raw.build();case 5:return o=null!==(r=o)&&void 0!==r?r:u.options.restore,delete u.simulationResult,delete u.simulationTransactionData,t.next=10,u.server.simulateTransaction(u.built);case 10:if(u.simulation=t.sent,!o||!i.j.isSimulationRestore(u.simulation)){t.next=25;break}return t.next=14,T(u.options,u.server);case 14:return s=t.sent,t.next=17,u.restoreFootprint(u.simulation.restorePreamble,s);case 17:if((c=t.sent).status!==i.j.GetTransactionStatus.SUCCESS){t.next=24;break}return d=new n.Contract(u.options.contractId),u.raw=new n.TransactionBuilder(s,{fee:null!==(l=u.options.fee)&&void 0!==l?l:n.BASE_FEE,networkPassphrase:u.options.networkPassphrase}).addOperation(d.call.apply(d,[u.options.method].concat(ne(null!==(f=u.options.args)&&void 0!==f?f:[])))).setTimeout(null!==(p=u.options.timeoutInSeconds)&&void 0!==p?p:h),t.next=23,u.simulate();case 23:return t.abrupt("return",u);case 24:throw new e.Errors.RestorationFailure("Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n".concat(JSON.stringify(c)));case 25:return i.j.isSimulationSuccess(u.simulation)&&(u.built=(0,a.X)(u.built,u.simulation).build()),t.abrupt("return",u);case 27:case"end":return t.stop()}}),t)})))),fe(this,"sign",se(re().mark((function t(){var r,o,i,a,s,c,l,f,p,d,y,m,v=arguments;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i=(o=v.length>0&&void 0!==v[0]?v[0]:{}).force,a=void 0!==i&&i,s=o.signTransaction,c=void 0===s?u.options.signTransaction:s,u.built){t.next=3;break}throw new Error("Transaction has not yet been simulated");case 3:if(a||!u.isReadCall){t.next=5;break}throw new e.Errors.NoSignatureNeeded("This is a read call. It requires no signature or sending. Use `force: true` to sign and send anyway.");case 5:if(c){t.next=7;break}throw new e.Errors.NoSigner("You must provide a signTransaction function, either when calling `signAndSend` or when initializing your Client");case 7:if(!(l=u.needsNonInvokerSigningBy().filter((function(e){return!e.startsWith("C")}))).length){t.next=10;break}throw new e.Errors.NeedsMoreSignatures("Transaction requires signatures from ".concat(l,". ")+"See `needsNonInvokerSigningBy` for details.");case 10:return f=null!==(r=u.options.timeoutInSeconds)&&void 0!==r?r:h,u.built=n.TransactionBuilder.cloneFrom(u.built,{fee:u.built.fee,timebounds:void 0,sorobanData:u.simulationData.transactionData}).setTimeout(f).build(),p={networkPassphrase:u.options.networkPassphrase},u.options.address&&(p.address=u.options.address),void 0!==u.options.submit&&(p.submit=u.options.submit),u.options.submitUrl&&(p.submitUrl=u.options.submitUrl),t.next=18,c(u.built.toXDR(),p);case 18:d=t.sent,y=d.signedTxXdr,m=d.error,u.handleWalletError(m),u.signed=n.TransactionBuilder.fromXDR(y,u.options.networkPassphrase);case 23:case"end":return t.stop()}}),t)})))),fe(this,"signAndSend",se(re().mark((function e(){var t,r,n,o,i,a,s=arguments;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=(t=s.length>0&&void 0!==s[0]?s[0]:{}).force,n=void 0!==r&&r,o=t.signTransaction,i=void 0===o?u.options.signTransaction:o,u.signed){e.next=10;break}return a=u.options.submit,u.options.submit&&(u.options.submit=!1),e.prev=4,e.next=7,u.sign({force:n,signTransaction:i});case 7:return e.prev=7,u.options.submit=a,e.finish(7);case 10:return e.abrupt("return",u.send());case 11:case"end":return e.stop()}}),e,null,[[4,,7,10]])})))),fe(this,"needsNonInvokerSigningBy",(function(){var e,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).includeAlreadySigned,r=void 0!==t&&t;if(!u.built)throw new Error("Transaction has not yet been simulated");if(!("operations"in u.built))throw new Error("Unexpected Transaction type; no operations: ".concat(JSON.stringify(u.built)));var o=u.built.operations[0];return ne(new Set((null!==(e=o.auth)&&void 0!==e?e:[]).filter((function(e){return e.credentials().switch()===n.xdr.SorobanCredentialsType.sorobanCredentialsAddress()&&(r||"scvVoid"===e.credentials().address().signature().switch().name)})).map((function(e){return n.Address.fromScAddress(e.credentials().address().address()).toString()}))))})),fe(this,"signAuthEntries",se(re().mark((function t(){var r,o,i,a,s,c,l,f,p,d,h,y,m,v,g,b,w=arguments;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i=(o=w.length>0&&void 0!==w[0]?w[0]:{}).expiration,a=void 0===i?se(re().mark((function e(){return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,u.server.getLatestLedger();case 2:return e.t0=e.sent.sequence,e.abrupt("return",e.t0+100);case 4:case"end":return e.stop()}}),e)})))():i,s=o.signAuthEntry,c=void 0===s?u.options.signAuthEntry:s,l=o.address,f=void 0===l?u.options.publicKey:l,p=o.authorizeEntry,d=void 0===p?n.authorizeEntry:p,u.built){t.next=3;break}throw new Error("Transaction has not yet been assembled or simulated");case 3:if(d!==n.authorizeEntry){t.next=11;break}if(0!==(h=u.needsNonInvokerSigningBy()).length){t.next=7;break}throw new e.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?");case 7:if(-1!==h.indexOf(null!=f?f:"")){t.next=9;break}throw new e.Errors.NoSignatureNeeded('No auth entries for public key "'.concat(f,'"'));case 9:if(c){t.next=11;break}throw new e.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`");case 11:y=u.built.operations[0],m=null!==(r=y.auth)&&void 0!==r?r:[],v=te(m.entries()),t.prev=14,b=re().mark((function e(){var t,r,o,i,s;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=ee(g.value,2),r=t[0],o=t[1],(i=n.xdr.SorobanCredentials.fromXDR(o.credentials().toXDR())).switch()===n.xdr.SorobanCredentialsType.sorobanCredentialsAddress()){e.next=4;break}return e.abrupt("return",0);case 4:if(n.Address.fromScAddress(i.address().address()).toString()===f){e.next=7;break}return e.abrupt("return",0);case 7:return s=null!=c?c:Promise.resolve,e.t0=d,e.t1=o,e.t2=function(){var e=se(re().mark((function e(t){var r,n,o;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,s(t.toXDR("base64"),{address:f});case 2:return r=e.sent,n=r.signedAuthEntry,o=r.error,u.handleWalletError(o),e.abrupt("return",H.from(n,"base64"));case 7:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),e.next=13,a;case 13:return e.t3=e.sent,e.t4=u.options.networkPassphrase,e.next=17,(0,e.t0)(e.t1,e.t2,e.t3,e.t4);case 17:m[r]=e.sent;case 18:case"end":return e.stop()}}),e)})),v.s();case 17:if((g=v.n()).done){t.next=24;break}return t.delegateYield(b(),"t0",19);case 19:if(0!==t.t0){t.next=22;break}return t.abrupt("continue",22);case 22:t.next=17;break;case 24:t.next=29;break;case 26:t.prev=26,t.t1=t.catch(14),v.e(t.t1);case 29:return t.prev=29,v.f(),t.finish(29);case 32:case"end":return t.stop()}}),t,null,[[14,26,29,32]])})))),this.options=t,this.options.simulate=null===(r=this.options.simulate)||void 0===r||r,this.server=new o.Server(this.options.rpcUrl,{allowHttp:null!==(s=this.options.allowHttp)&&void 0!==s&&s})}return le(e,[{key:"toJSON",value:function(){var e;return JSON.stringify({method:this.options.method,tx:null===(e=this.built)||void 0===e?void 0:e.toXDR(),simulationResult:{auth:this.simulationData.result.auth.map((function(e){return e.toXDR("base64")})),retval:this.simulationData.result.retval.toXDR("base64")},simulationTransactionData:this.simulationData.transactionData.toXDR("base64")})}},{key:"toXDR",value:function(){var e;if(!this.built)throw new Error("Transaction has not yet been simulated; call `AssembledTransaction.simulate` first.");return null===(e=this.built)||void 0===e?void 0:e.toEnvelope().toXDR("base64")}},{key:"handleWalletError",value:function(t){if(t){var r=t.message,n=t.code,o="".concat(r).concat(t.ext?" (".concat(t.ext.join(", "),")"):"");switch(n){case-1:throw new e.Errors.InternalWalletError(o);case-2:throw new e.Errors.ExternalServiceError(o);case-3:throw new e.Errors.InvalidClientRequest(o);case-4:throw new e.Errors.UserRejected(o);default:throw new Error("Unhandled error: ".concat(o))}}}},{key:"simulationData",get:function(){var t;if(this.simulationResult&&this.simulationTransactionData)return{result:this.simulationResult,transactionData:this.simulationTransactionData};var r=this.simulation;if(!r)throw new e.Errors.NotYetSimulated("Transaction has not yet been simulated");if(i.j.isSimulationError(r))throw new e.Errors.SimulationFailed('Transaction simulation failed: "'.concat(r.error,'"'));if(i.j.isSimulationRestore(r))throw new e.Errors.ExpiredState("You need to restore some contract state before you can invoke this method.\nYou can set `restore` to true in the method options in order to automatically restore the contract state when needed.");return this.simulationResult=null!==(t=r.result)&&void 0!==t?t:{auth:[],retval:n.xdr.ScVal.scvVoid()},this.simulationTransactionData=r.transactionData.build(),{result:this.simulationResult,transactionData:this.simulationTransactionData}}},{key:"result",get:function(){try{if(!this.simulationData.result)throw new Error("No simulation result!");return this.options.parseResultXdr(this.simulationData.result.retval)}catch(r){if("object"!==v(t=r)||null===t||!("toString"in t))throw r;var e=this.parseError(r.toString());if(e)return e;throw r}var t}},{key:"parseError",value:function(e){if(this.options.errorTypes){var t=e.match(_);if(t){var r=parseInt(t[1],10),n=this.options.errorTypes[r];if(n)return new d(n)}}}},{key:"send",value:(u=se(re().mark((function e(){var t;return re().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.signed){e.next=2;break}throw new Error("The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead.");case 2:return e.next=4,K.init(this);case 4:return t=e.sent,e.abrupt("return",t);case 6:case"end":return e.stop()}}),e,this)}))),function(){return u.apply(this,arguments)})},{key:"isReadCall",get:function(){var e=this.simulationData.result.auth.length,t=this.simulationData.transactionData.resources().footprint().readWrite().length;return 0===e&&0===t}},{key:"restoreFootprint",value:(s=se(re().mark((function t(r,n){var o,i,a;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this.options.signTransaction){t.next=2;break}throw new Error("For automatic restore to work you must provide a signTransaction function when initializing your Client");case 2:if(null===(o=n)||void 0===o){t.next=6;break}t.t0=o,t.next=9;break;case 6:return t.next=8,T(this.options,this.server);case 8:t.t0=t.sent;case 9:return n=t.t0,t.next=12,e.buildFootprintRestoreTransaction(Z({},this.options),r.transactionData,n,r.minResourceFee);case 12:return i=t.sent,t.next=15,i.signAndSend();case 15:if((a=t.sent).getTransactionResponse){t.next=18;break}throw new e.Errors.RestorationFailure("The attempt at automatic restore failed. \n".concat(JSON.stringify(a)));case 18:return t.abrupt("return",a.getTransactionResponse);case 19:case"end":return t.stop()}}),t,this)}))),function(e,t){return s.apply(this,arguments)})}],[{key:"fromJSON",value:function(t,r){var o=r.tx,i=r.simulationResult,a=r.simulationTransactionData,s=new e(t);return s.built=n.TransactionBuilder.fromXDR(o,t.networkPassphrase),s.simulationResult={auth:i.auth.map((function(e){return n.xdr.SorobanAuthorizationEntry.fromXDR(e,"base64")})),retval:n.xdr.ScVal.fromXDR(i.retval,"base64")},s.simulationTransactionData=n.xdr.SorobanTransactionData.fromXDR(a,"base64"),s}},{key:"fromXDR",value:function(t,r,o){var i,a=n.xdr.TransactionEnvelope.fromXDR(r,"base64"),s=n.TransactionBuilder.fromXDR(a,t.networkPassphrase),u=s.operations[0];if(null==u||null===(i=u.func)||void 0===i||!i.value||"function"!=typeof u.func.value)throw new Error("Could not extract the method from the transaction envelope.");var c=u.func.value();if(null==c||!c.functionName)throw new Error("Could not extract the method name from the transaction envelope.");var l=c.functionName().toString("utf-8"),f=new e(Z(Z({},t),{},{method:l,parseResultXdr:function(e){return o.funcResToNative(l,e)}}));return f.built=s,f}},{key:"build",value:function(t){var r,o=new n.Contract(t.contractId);return e.buildWithOp(o.call.apply(o,[t.method].concat(ne(null!==(r=t.args)&&void 0!==r?r:[]))),t)}},{key:"buildWithOp",value:(r=se(re().mark((function t(r,o){var i,a,s,u;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return s=new e(o),t.next=3,T(o,s.server);case 3:if(u=t.sent,s.raw=new n.TransactionBuilder(u,{fee:null!==(i=o.fee)&&void 0!==i?i:n.BASE_FEE,networkPassphrase:o.networkPassphrase}).setTimeout(null!==(a=o.timeoutInSeconds)&&void 0!==a?a:h).addOperation(r),!o.simulate){t.next=8;break}return t.next=8,s.simulate();case 8:return t.abrupt("return",s);case 9:case"end":return t.stop()}}),t)}))),function(e,t){return r.apply(this,arguments)})},{key:"buildFootprintRestoreTransaction",value:(t=se(re().mark((function t(r,o,i,a){var s,u;return re().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return(u=new e(r)).raw=new n.TransactionBuilder(i,{fee:a,networkPassphrase:r.networkPassphrase}).setSorobanData(o instanceof n.SorobanDataBuilder?o.build():o).addOperation(n.Operation.restoreFootprint({})).setTimeout(null!==(s=r.timeoutInSeconds)&&void 0!==s?s:h),t.next=4,u.simulate({restore:!1});case 4:return t.abrupt("return",u);case 5:case"end":return t.stop()}}),t)}))),function(e,r,n,o){return t.apply(this,arguments)})}]);var t,r,s,u}();fe(de,"Errors",{ExpiredState:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),RestorationFailure:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NeedsMoreSignatures:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NoSignatureNeeded:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NoUnsignedNonInvokerAuthEntries:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NoSigner:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),NotYetSimulated:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),FakeAccount:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),SimulationFailed:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),InternalWalletError:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),ExternalServiceError:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),InvalidClientRequest:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error)),UserRejected:function(e){function t(){return ue(this,t),z(this,t,arguments)}return X(t,e),le(t)}(G(Error))});var he=r(8287).Buffer;function ye(e){return ye="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ye(e)}function me(){me=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,E=S&&S(S(j([])));E&&E!==r&&n.call(E,a)&&(w=E);var _=b.prototype=v.prototype=Object.create(w);function k(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==ye(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function ve(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function ge(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){ve(i,n,o,a,s,"next",e)}function s(e){ve(i,n,o,a,s,"throw",e)}a(void 0)}))}}var be=function(e,t){return{signTransaction:(o=ge(me().mark((function r(o,i){var a;return me().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return(a=n.TransactionBuilder.fromXDR(o,(null==i?void 0:i.networkPassphrase)||t)).sign(e),r.abrupt("return",{signedTxXdr:a.toXDR(),signerAddress:e.publicKey()});case 3:case"end":return r.stop()}}),r)}))),function(e,t){return o.apply(this,arguments)}),signAuthEntry:(r=ge(me().mark((function t(r){var o;return me().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return o=e.sign((0,n.hash)(he.from(r,"base64"))).toString("base64"),t.abrupt("return",{signedAuthEntry:o,signerAddress:e.publicKey()});case 2:case"end":return t.stop()}}),t)}))),function(e){return r.apply(this,arguments)})};var r,o},we=r(8287).Buffer;function Se(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Ee(e){for(var t=1;te.length)&&(t=e.length);for(var r=0,n=Array(t);r0&&(o.required=r),o}var Ie,Le,Be,Ne=(Ie=function e(t){if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Te(this,"entries",[]),0===t.length)throw new Error("Contract spec must have at least one entry");var r=t[0];this.entries="string"==typeof r?t.map((function(e){return n.xdr.ScSpecEntry.fromXDR(e,"base64")})):t},Le=[{key:"funcs",value:function(){return this.entries.filter((function(e){return e.switch().value===n.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value})).map((function(e){return e.functionV0()}))}},{key:"getFunc",value:function(e){var t=this.findEntry(e);if(t.switch().value!==n.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value)throw new Error("".concat(e," is not a function"));return t.functionV0()}},{key:"funcArgsToScVals",value:function(e,t){var r=this;return this.getFunc(e).inputs().map((function(e){return r.nativeToScVal(function(e,t){var r=t.name().toString(),n=Object.entries(e).find((function(e){return xe(e,1)[0]===r}));if(!n)throw new Error("Missing field ".concat(r));return n[1]}(t,e),e.type())}))}},{key:"funcResToNative",value:function(e,t){var r="string"==typeof t?n.xdr.ScVal.fromXDR(t,"base64"):t,o=this.getFunc(e).outputs();if(0===o.length){var i=r.switch();if(i.value!==n.xdr.ScValType.scvVoid().value)throw new Error("Expected void, got ".concat(i.name));return null}if(o.length>1)throw new Error("Multiple outputs not supported");var a=o[0];return a.switch().value===n.xdr.ScSpecType.scSpecTypeResult().value?new p(this.scValToNative(r,a.result().okType())):this.scValToNative(r,a)}},{key:"findEntry",value:function(e){var t=this.entries.find((function(t){return t.value().name().toString()===e}));if(!t)throw new Error("no such entry: ".concat(e));return t}},{key:"nativeToScVal",value:function(e,t){var r=this,o=t.switch(),i=o.value;if(o.value===n.xdr.ScSpecType.scSpecTypeUdt().value){var a=t.udt();return this.nativeToUdt(e,a.name().toString())}if(i===n.xdr.ScSpecType.scSpecTypeOption().value){var s=t.option();return void 0===e?n.xdr.ScVal.scvVoid():this.nativeToScVal(e,s.valueType())}switch(_e(e)){case"object":var u,c,l;if(null===e){if(i===n.xdr.ScSpecType.scSpecTypeVoid().value)return n.xdr.ScVal.scvVoid();throw new TypeError("Type ".concat(t," was not void, but value was null"))}if(e instanceof n.xdr.ScVal)return e;if(e instanceof n.Address){if(t.switch().value!==n.xdr.ScSpecType.scSpecTypeAddress().value)throw new TypeError("Type ".concat(t," was not address, but value was Address"));return e.toScVal()}if(e instanceof n.Contract){if(t.switch().value!==n.xdr.ScSpecType.scSpecTypeAddress().value)throw new TypeError("Type ".concat(t," was not address, but value was Address"));return e.address().toScVal()}if(e instanceof Uint8Array||we.isBuffer(e)){var f=Uint8Array.from(e);switch(i){case n.xdr.ScSpecType.scSpecTypeBytesN().value:var p=t.bytesN();if(f.length!==p.n())throw new TypeError("expected ".concat(p.n()," bytes, but got ").concat(f.length));return n.xdr.ScVal.scvBytes(f);case n.xdr.ScSpecType.scSpecTypeBytes().value:return n.xdr.ScVal.scvBytes(f);default:throw new TypeError("invalid type (".concat(t,") specified for Bytes and BytesN"))}}if(Array.isArray(e))switch(i){case n.xdr.ScSpecType.scSpecTypeVec().value:var d=t.vec().elementType();return n.xdr.ScVal.scvVec(e.map((function(e){return r.nativeToScVal(e,d)})));case n.xdr.ScSpecType.scSpecTypeTuple().value:var h=t.tuple().valueTypes();if(e.length!==h.length)throw new TypeError("Tuple expects ".concat(h.length," values, but ").concat(e.length," were provided"));return n.xdr.ScVal.scvVec(e.map((function(e,t){return r.nativeToScVal(e,h[t])})));case n.xdr.ScSpecType.scSpecTypeMap().value:var y=t.map(),m=y.keyType(),v=y.valueType();return n.xdr.ScVal.scvMap(e.map((function(e){var t=r.nativeToScVal(e[0],m),o=r.nativeToScVal(e[1],v);return new n.xdr.ScMapEntry({key:t,val:o})})));default:throw new TypeError("Type ".concat(t," was not vec, but value was Array"))}if(e.constructor===Map){if(i!==n.xdr.ScSpecType.scSpecTypeMap().value)throw new TypeError("Type ".concat(t," was not map, but value was Map"));for(var g=t.map(),b=[],w=e.entries(),S=w.next();!S.done;){var E=xe(S.value,2),_=E[0],k=E[1],T=this.nativeToScVal(_,g.keyType()),O=this.nativeToScVal(k,g.valueType());b.push(new n.xdr.ScMapEntry({key:T,val:O})),S=w.next()}return n.xdr.ScVal.scvMap(b)}if("Object"!==(null!==(u=null===(c=e.constructor)||void 0===c?void 0:c.name)&&void 0!==u?u:""))throw new TypeError("cannot interpret ".concat(null===(l=e.constructor)||void 0===l?void 0:l.name," value as ScVal (").concat(JSON.stringify(e),")"));throw new TypeError("Received object ".concat(e," did not match the provided type ").concat(t));case"number":case"bigint":switch(i){case n.xdr.ScSpecType.scSpecTypeU32().value:return n.xdr.ScVal.scvU32(e);case n.xdr.ScSpecType.scSpecTypeI32().value:return n.xdr.ScVal.scvI32(e);case n.xdr.ScSpecType.scSpecTypeU64().value:case n.xdr.ScSpecType.scSpecTypeI64().value:case n.xdr.ScSpecType.scSpecTypeU128().value:case n.xdr.ScSpecType.scSpecTypeI128().value:case n.xdr.ScSpecType.scSpecTypeU256().value:case n.xdr.ScSpecType.scSpecTypeI256().value:var x=o.name.substring(10).toLowerCase();return new n.XdrLargeInt(x,e).toScVal();default:throw new TypeError("invalid type (".concat(t,") specified for integer"))}case"string":return function(e,t){switch(t.value){case n.xdr.ScSpecType.scSpecTypeString().value:return n.xdr.ScVal.scvString(e);case n.xdr.ScSpecType.scSpecTypeSymbol().value:return n.xdr.ScVal.scvSymbol(e);case n.xdr.ScSpecType.scSpecTypeAddress().value:var r=n.Address.fromString(e);return n.xdr.ScVal.scvAddress(r.toScAddress());case n.xdr.ScSpecType.scSpecTypeU64().value:return new n.XdrLargeInt("u64",e).toScVal();case n.xdr.ScSpecType.scSpecTypeI64().value:return new n.XdrLargeInt("i64",e).toScVal();case n.xdr.ScSpecType.scSpecTypeU128().value:return new n.XdrLargeInt("u128",e).toScVal();case n.xdr.ScSpecType.scSpecTypeI128().value:return new n.XdrLargeInt("i128",e).toScVal();case n.xdr.ScSpecType.scSpecTypeU256().value:return new n.XdrLargeInt("u256",e).toScVal();case n.xdr.ScSpecType.scSpecTypeI256().value:return new n.XdrLargeInt("i256",e).toScVal();case n.xdr.ScSpecType.scSpecTypeBytes().value:case n.xdr.ScSpecType.scSpecTypeBytesN().value:return n.xdr.ScVal.scvBytes(we.from(e,"base64"));default:throw new TypeError("invalid type ".concat(t.name," specified for string value"))}}(e,o);case"boolean":if(i!==n.xdr.ScSpecType.scSpecTypeBool().value)throw TypeError("Type ".concat(t," was not bool, but value was bool"));return n.xdr.ScVal.scvBool(e);case"undefined":if(!t)return n.xdr.ScVal.scvVoid();switch(i){case n.xdr.ScSpecType.scSpecTypeVoid().value:case n.xdr.ScSpecType.scSpecTypeOption().value:return n.xdr.ScVal.scvVoid();default:throw new TypeError("Type ".concat(t," was not void, but value was undefined"))}case"function":return this.nativeToScVal(e(),t);default:throw new TypeError("failed to convert typeof ".concat(_e(e)," (").concat(e,")"))}}},{key:"nativeToUdt",value:function(e,t){var r=this.findEntry(t);switch(r.switch()){case n.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0():if("number"!=typeof e)throw new TypeError("expected number for enum ".concat(t,", but got ").concat(_e(e)));return this.nativeToEnum(e,r.udtEnumV0());case n.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.nativeToStruct(e,r.udtStructV0());case n.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.nativeToUnion(e,r.udtUnionV0());default:throw new Error("failed to parse udt ".concat(t))}}},{key:"nativeToUnion",value:function(e,t){var r=this,o=e.tag,i=t.cases().find((function(e){return e.value().name().toString()===o}));if(!i)throw new TypeError("no such enum entry: ".concat(o," in ").concat(t));var a=n.xdr.ScVal.scvSymbol(o);switch(i.switch()){case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0():return n.xdr.ScVal.scvVec([a]);case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0():var s=i.tupleCase().type();if(Array.isArray(e.values)){if(e.values.length!==s.length)throw new TypeError("union ".concat(t," expects ").concat(s.length," values, but got ").concat(e.values.length));var u=e.values.map((function(e,t){return r.nativeToScVal(e,s[t])}));return u.unshift(a),n.xdr.ScVal.scvVec(u)}throw new Error("failed to parse union case ".concat(i," with ").concat(e));default:throw new Error("failed to parse union ".concat(t," with ").concat(e))}}},{key:"nativeToStruct",value:function(e,t){var r=this,o=t.fields();if(o.some(Pe)){if(!o.every(Pe))throw new Error("mixed numeric and non-numeric field names are not allowed");return n.xdr.ScVal.scvVec(o.map((function(t,n){return r.nativeToScVal(e[n],o[n].type())})))}return n.xdr.ScVal.scvMap(o.map((function(t){var o=t.name().toString();return new n.xdr.ScMapEntry({key:r.nativeToScVal(o,n.xdr.ScSpecTypeDef.scSpecTypeSymbol()),val:r.nativeToScVal(e[o],t.type())})})))}},{key:"nativeToEnum",value:function(e,t){if(t.cases().some((function(t){return t.value()===e})))return n.xdr.ScVal.scvU32(e);throw new TypeError("no such enum entry: ".concat(e," in ").concat(t))}},{key:"scValStrToNative",value:function(e,t){return this.scValToNative(n.xdr.ScVal.fromXDR(e,"base64"),t)}},{key:"scValToNative",value:function(e,t){var r=this,o=t.switch(),i=o.value;if(i===n.xdr.ScSpecType.scSpecTypeUdt().value)return this.scValUdtToNative(e,t.udt());switch(e.switch().value){case n.xdr.ScValType.scvVoid().value:return;case n.xdr.ScValType.scvU64().value:case n.xdr.ScValType.scvI64().value:case n.xdr.ScValType.scvU128().value:case n.xdr.ScValType.scvI128().value:case n.xdr.ScValType.scvU256().value:case n.xdr.ScValType.scvI256().value:return(0,n.scValToBigInt)(e);case n.xdr.ScValType.scvVec().value:if(i===n.xdr.ScSpecType.scSpecTypeVec().value){var a,s=t.vec();return(null!==(a=e.vec())&&void 0!==a?a:[]).map((function(e){return r.scValToNative(e,s.elementType())}))}if(i===n.xdr.ScSpecType.scSpecTypeTuple().value){var u,c=t.tuple().valueTypes();return(null!==(u=e.vec())&&void 0!==u?u:[]).map((function(e,t){return r.scValToNative(e,c[t])}))}throw new TypeError("Type ".concat(t," was not vec, but ").concat(e," is"));case n.xdr.ScValType.scvAddress().value:return n.Address.fromScVal(e).toString();case n.xdr.ScValType.scvMap().value:var l,f=null!==(l=e.map())&&void 0!==l?l:[];if(i===n.xdr.ScSpecType.scSpecTypeMap().value){var p=t.map(),d=p.keyType(),h=p.valueType();return f.map((function(e){return[r.scValToNative(e.key(),d),r.scValToNative(e.val(),h)]}))}throw new TypeError("ScSpecType ".concat(o.name," was not map, but ").concat(JSON.stringify(e,null,2)," is"));case n.xdr.ScValType.scvBool().value:case n.xdr.ScValType.scvU32().value:case n.xdr.ScValType.scvI32().value:case n.xdr.ScValType.scvBytes().value:return e.value();case n.xdr.ScValType.scvString().value:case n.xdr.ScValType.scvSymbol().value:var y;if(i!==n.xdr.ScSpecType.scSpecTypeString().value&&i!==n.xdr.ScSpecType.scSpecTypeSymbol().value)throw new Error("ScSpecType ".concat(o.name," was not string or symbol, but ").concat(JSON.stringify(e,null,2)," is"));return null===(y=e.value())||void 0===y?void 0:y.toString();case n.xdr.ScValType.scvTimepoint().value:case n.xdr.ScValType.scvDuration().value:return(0,n.scValToBigInt)(n.xdr.ScVal.scvU64(e.u64()));default:throw new TypeError("failed to convert ".concat(JSON.stringify(e,null,2)," to native type from type ").concat(o.name))}}},{key:"scValUdtToNative",value:function(e,t){var r=this.findEntry(t.name().toString());switch(r.switch()){case n.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0():return this.enumToNative(e);case n.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0():return this.structToNative(e,r.udtStructV0());case n.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0():return this.unionToNative(e,r.udtUnionV0());default:throw new Error("failed to parse udt ".concat(t.name().toString(),": ").concat(r))}}},{key:"unionToNative",value:function(e,t){var r=this,o=e.vec();if(!o)throw new Error("".concat(JSON.stringify(e,null,2)," is not a vec"));if(0===o.length&&0!==t.cases.length)throw new Error("".concat(e," has length 0, but the there are at least one case in the union"));var i=o[0].sym().toString();if(o[0].switch().value!==n.xdr.ScValType.scvSymbol().value)throw new Error("{vec[0]} is not a symbol");var a=t.cases().find(function(e){return function(t){switch(t.switch().value){case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value:return t.tupleCase().name().toString()===e;case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value:return t.voidCase().name().toString()===e;default:return!1}}}(i));if(!a)throw new Error("failed to find entry ".concat(i," in union {udt.name().toString()}"));var s={tag:i};if(a.switch().value===n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value){var u=a.tupleCase().type().map((function(e,t){return r.scValToNative(o[t+1],e)}));s.values=u}return s}},{key:"structToNative",value:function(e,t){var r,n,o=this,i={},a=t.fields();return a.some(Pe)?null===(n=e.vec())||void 0===n?void 0:n.map((function(e,t){return o.scValToNative(e,a[t].type())})):(null===(r=e.map())||void 0===r||r.forEach((function(e,t){var r=a[t];i[r.name().toString()]=o.scValToNative(e.val(),r.type())})),i)}},{key:"enumToNative",value:function(e){if(e.switch().value!==n.xdr.ScValType.scvU32().value)throw new Error("Enum must have a u32 value");return e.u32()}},{key:"errorCases",value:function(){return this.entries.filter((function(e){return e.switch().value===n.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value})).flatMap((function(e){return e.value().cases()}))}},{key:"jsonSchema",value:function(e){var t={};this.entries.forEach((function(e){switch(e.switch().value){case n.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0().value:var r=e.udtEnumV0();t[r.name().toString()]=function(e){var t=e.doc().toString(),r=e.cases(),n=[];r.forEach((function(e){var t=e.name().toString(),r=e.doc().toString();n.push({description:r,title:t,enum:[e.value()],type:"number"})}));var o={oneOf:n};return t.length>0&&(o.description=t),o}(r);break;case n.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0().value:var o=e.udtStructV0();t[o.name().toString()]=function(e){var t=e.fields();if(t.some(Pe)){if(!t.every(Pe))throw new Error("mixed numeric and non-numeric field names are not allowed");return{type:"array",items:t.map((function(e,r){return je(t[r].type())})),minItems:t.length,maxItems:t.length}}var r=e.doc().toString(),n=Ce(t),o=n.properties,i=n.required;return o.additionalProperties=!1,{description:r,properties:o,required:i,type:"object"}}(o);break;case n.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0().value:var i=e.udtUnionV0();t[i.name().toString()]=function(e){var t=e.doc().toString(),r=e.cases(),o=[];r.forEach((function(e){switch(e.switch().value){case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value:var t=e.voidCase().name().toString();o.push({type:"object",title:t,properties:{tag:t},additionalProperties:!1,required:["tag"]});break;case n.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value:var r=e.tupleCase(),i=r.name().toString();o.push({type:"object",title:i,properties:{tag:i,values:{type:"array",items:r.type().map(je)}},required:["tag","values"],additionalProperties:!1})}}));var i={oneOf:o};return t.length>0&&(i.description=t),i}(i);break;case n.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value:var a=e.functionV0(),s=a.name().toString(),u=function(e){var t=Ce(e.inputs()),r=t.properties,o=t.required,i={additionalProperties:!1,properties:r,type:"object"};(null==o?void 0:o.length)>0&&(i.required=o);var a={properties:{args:i}},s=e.outputs(),u=s.length>0?je(s[0]):je(n.xdr.ScSpecTypeDef.scSpecTypeVoid()),c=e.doc().toString();return c.length>0&&(a.description=c),a.additionalProperties=!1,u.additionalProperties=!1,{input:a,output:u}}(a),c=u.input;t[s]=c;case n.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value:}}));var r={$schema:"http://json-schema.org/draft-07/schema#",definitions:Ee(Ee({},Re),t)};return e&&(r.$ref="#/definitions/".concat(e)),r}}],Le&&ke(Ie.prototype,Le),Be&&ke(Ie,Be),Object.defineProperty(Ie,"prototype",{writable:!1}),Ie),Ue=r(8287).Buffer;function Me(e){return Me="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Me(e)}var De=["method"],Fe=["wasmHash","salt","format","fee","timeoutInSeconds","simulate"];function Ve(){Ve=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,E=S&&S(S(j([])));E&&E!==r&&n.call(E,a)&&(w=E);var _=b.prototype=v.prototype=Object.create(w);function k(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==Me(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function qe(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Ke(e){for(var t=1;t2&&void 0!==l[2]?l[2]:"hex",r&&r.rpcUrl){e.next=3;break}throw new TypeError("options must contain rpcUrl");case 3:return i=r.rpcUrl,a=r.allowHttp,s={allowHttp:a},u=new o.Server(i,s),e.next=8,u.getContractWasmByHash(t,n);case 8:return c=e.sent,e.abrupt("return",Ye(c));case 10:case"end":return e.stop()}}),e)}))),et.apply(this,arguments)}var tt=function(){function e(t,r){var n=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Xe(this,"txFromJSON",(function(e){var t=JSON.parse(e),r=t.method,o=He(t,De);return de.fromJSON(Ke(Ke({},n.options),{},{method:r,parseResultXdr:function(e){return n.spec.funcResToNative(r,e)}}),o)})),Xe(this,"txFromXDR",(function(e){return de.fromXDR(n.options,e,n.spec)})),this.spec=t,this.options=r,this.spec.funcs().forEach((function(e){var o=e.name().toString();if(o!==Qe){var i=function(e,n){return de.build(Ke(Ke(Ke({method:o,args:e&&t.funcArgsToScVals(o,e)},r),n),{},{errorTypes:t.errorCases().reduce((function(e,t){return Ke(Ke({},e),{},Xe({},t.value(),{message:t.doc().toString()}))}),{}),parseResultXdr:function(e){return t.funcResToNative(o,e)}}))};n[o]=0===t.getFunc(o).inputs().length?function(e){return i(void 0,e)}:i}}))}return function(e,t,r){return t&&ze(e.prototype,t),r&&ze(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}(e,null,[{key:"deploy",value:(a=$e(Ve().mark((function t(r,o){var i,a,s,u,c,l,f,p,d;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=o.wasmHash,a=o.salt,s=o.format,u=o.fee,c=o.timeoutInSeconds,l=o.simulate,f=He(o,Fe),t.next=3,Ze(i,f,s);case 3:return p=t.sent,d=n.Operation.createCustomContract({address:new n.Address(o.publicKey),wasmHash:"string"==typeof i?Ue.from(i,null!=s?s:"hex"):i,salt:a,constructorArgs:r?p.funcArgsToScVals(Qe,r):[]}),t.abrupt("return",de.buildWithOp(d,Ke(Ke({fee:u,timeoutInSeconds:c,simulate:l},f),{},{contractId:"ignored",method:Qe,parseResultXdr:function(t){return new e(p,Ke(Ke({},f),{},{contractId:n.Address.fromScVal(t).toString()}))}})));case 6:case"end":return t.stop()}}),t)}))),function(e,t){return a.apply(this,arguments)})},{key:"fromWasmHash",value:(i=$e(Ve().mark((function t(r,n){var i,a,s,u,c,l,f=arguments;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i=f.length>2&&void 0!==f[2]?f[2]:"hex",n&&n.rpcUrl){t.next=3;break}throw new TypeError("options must contain rpcUrl");case 3:return a=n.rpcUrl,s=n.allowHttp,u={allowHttp:s},c=new o.Server(a,u),t.next=8,c.getContractWasmByHash(r,i);case 8:return l=t.sent,t.abrupt("return",e.fromWasm(l,n));case 10:case"end":return t.stop()}}),t)}))),function(e,t){return i.apply(this,arguments)})},{key:"fromWasm",value:(r=$e(Ve().mark((function t(r,n){var o;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,Ye(r);case 2:return o=t.sent,t.abrupt("return",new e(o,n));case 4:case"end":return t.stop()}}),t)}))),function(e,t){return r.apply(this,arguments)})},{key:"from",value:(t=$e(Ve().mark((function t(r){var n,i,a,s,u,c;return Ve().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(r&&r.rpcUrl&&r.contractId){t.next=2;break}throw new TypeError("options must contain rpcUrl and contractId");case 2:return n=r.rpcUrl,i=r.contractId,a=r.allowHttp,s={allowHttp:a},u=new o.Server(n,s),t.next=7,u.getContractWasmByContractId(i);case 7:return c=t.sent,t.abrupt("return",e.fromWasm(c,r));case 9:case"end":return t.stop()}}),t)}))),function(e){return t.apply(this,arguments)})}]);var t,r,i,a}()},5976:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rH,v7:()=>x,nS:()=>B,Dr:()=>f,m_:()=>b});var f=function(e){function t(e,r){var n;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var o=(this instanceof t?this.constructor:void 0).prototype;return(n=a(this,t,[e])).__proto__=o,n.constructor=t,n.response=r,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&c(e,t)}(t,e),r=t,(n=[{key:"getResponse",value:function(){return this.response}}])&&o(r.prototype,n),i&&o(r,i),Object.defineProperty(r,"prototype",{writable:!1}),r;var r,n,i}(s(Error));function p(e){return p="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},p(e)}function d(e,t){for(var r=0;r{"use strict";r.r(t),r.d(t,{Api:()=>{},FEDERATION_RESPONSE_MAX_SIZE:()=>g,Server:()=>b});var n=r(356),o=r(4193),i=r.n(o),a=r(8732),s=r(5976),u=r(3898),c=r(9983);function l(e){return l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l(e)}function f(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return p(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?p(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),j(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:I(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function h(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function y(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){h(i,n,o,a,s,"next",e)}function s(e){h(i,n,o,a,s,"throw",e)}a(void 0)}))}}function m(e,t){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.serverURL=i()(t),this.domain=r;var o=void 0===n.allowHttp?a.T.isAllowHttp():n.allowHttp;if(this.timeout=void 0===n.timeout?a.T.getTimeout():n.timeout,"https"!==this.serverURL.protocol()&&!o)throw new Error("Cannot connect to insecure federation server")}return t=e,r=[{key:"resolveAddress",value:(w=y(d().mark((function e(t){var r,n;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t,!(t.indexOf("*")<0)){e.next=5;break}if(this.domain){e.next=4;break}return e.abrupt("return",Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object.")));case 4:r="".concat(t,"*").concat(this.domain);case 5:return n=this.serverURL.query({type:"name",q:r}),e.abrupt("return",this._sendRequest(n));case 7:case"end":return e.stop()}}),e,this)}))),function(e){return w.apply(this,arguments)})},{key:"resolveAccountId",value:(b=y(d().mark((function e(t){var r;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.serverURL.query({type:"id",q:t}),e.abrupt("return",this._sendRequest(r));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return b.apply(this,arguments)})},{key:"resolveTransactionId",value:(v=y(d().mark((function e(t){var r;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.serverURL.query({type:"txid",q:t}),e.abrupt("return",this._sendRequest(r));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return v.apply(this,arguments)})},{key:"_sendRequest",value:(h=y(d().mark((function e(t){var r;return d().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.timeout,e.abrupt("return",c.ok.get(t.toString(),{maxContentLength:g,timeout:r}).then((function(e){if(void 0!==e.data.memo&&"string"!=typeof e.data.memo)throw new Error("memo value should be of type string");return e.data})).catch((function(e){if(e instanceof Error){if(e.message.match(/^maxContentLength size/))throw new Error("federation response exceeds allowed size of ".concat(g));return Promise.reject(e)}return Promise.reject(new s.nS("Server query failed. Server responded: ".concat(e.status," ").concat(e.statusText),e.data))})));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return h.apply(this,arguments)})}],o=[{key:"resolve",value:(p=y(d().mark((function t(r){var o,i,a,s,u,c=arguments;return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(o=c.length>1&&void 0!==c[1]?c[1]:{},!(r.indexOf("*")<0)){t.next=5;break}if(n.StrKey.isValidEd25519PublicKey(r)){t.next=4;break}return t.abrupt("return",Promise.reject(new Error("Invalid Account ID")));case 4:return t.abrupt("return",Promise.resolve({account_id:r}));case 5:if(i=r.split("*"),a=f(i,2),s=a[1],2===i.length&&s){t.next=9;break}return t.abrupt("return",Promise.reject(new Error("Invalid Stellar address")));case 9:return t.next=11,e.createForDomain(s,o);case 11:return u=t.sent,t.abrupt("return",u.resolveAddress(r));case 13:case"end":return t.stop()}}),t)}))),function(e){return p.apply(this,arguments)})},{key:"createForDomain",value:(l=y(d().mark((function t(r){var n,o,i=arguments;return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=i.length>1&&void 0!==i[1]?i[1]:{},t.next=3,u.Resolver.resolve(r,n);case 3:if((o=t.sent).FEDERATION_SERVER){t.next=6;break}return t.abrupt("return",Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field")));case 6:return t.abrupt("return",new e(o.FEDERATION_SERVER,r,n));case 7:case"end":return t.stop()}}),t)}))),function(e){return l.apply(this,arguments)})}],r&&m(t.prototype,r),o&&m(t,o),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,r,o,l,p,h,v,b,w}()},8242:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Api:()=>{}})},8733:(e,t,r)=>{"use strict";var n;r.r(t),r.d(t,{AccountResponse:()=>m,AxiosClient:()=>W,HorizonApi:()=>n,SERVER_TIME_MAP:()=>z,Server:()=>Yr,ServerApi:()=>i,default:()=>Jr,getCurrentServerTime:()=>$}),function(e){var t=function(e){return e.constantProduct="constant_product",e}({});e.LiquidityPoolType=t;var r=function(e){return e.createAccount="create_account",e.payment="payment",e.pathPayment="path_payment_strict_receive",e.createPassiveOffer="create_passive_sell_offer",e.manageOffer="manage_sell_offer",e.setOptions="set_options",e.changeTrust="change_trust",e.allowTrust="allow_trust",e.accountMerge="account_merge",e.inflation="inflation",e.manageData="manage_data",e.bumpSequence="bump_sequence",e.manageBuyOffer="manage_buy_offer",e.pathPaymentStrictSend="path_payment_strict_send",e.createClaimableBalance="create_claimable_balance",e.claimClaimableBalance="claim_claimable_balance",e.beginSponsoringFutureReserves="begin_sponsoring_future_reserves",e.endSponsoringFutureReserves="end_sponsoring_future_reserves",e.revokeSponsorship="revoke_sponsorship",e.clawback="clawback",e.clawbackClaimableBalance="clawback_claimable_balance",e.setTrustLineFlags="set_trust_line_flags",e.liquidityPoolDeposit="liquidity_pool_deposit",e.liquidityPoolWithdraw="liquidity_pool_withdraw",e.invokeHostFunction="invoke_host_function",e.bumpFootprintExpiration="bump_footprint_expiration",e.restoreFootprint="restore_footprint",e}({});e.OperationResponseType=r;var n=function(e){return e[e.createAccount=0]="createAccount",e[e.payment=1]="payment",e[e.pathPayment=2]="pathPayment",e[e.createPassiveOffer=3]="createPassiveOffer",e[e.manageOffer=4]="manageOffer",e[e.setOptions=5]="setOptions",e[e.changeTrust=6]="changeTrust",e[e.allowTrust=7]="allowTrust",e[e.accountMerge=8]="accountMerge",e[e.inflation=9]="inflation",e[e.manageData=10]="manageData",e[e.bumpSequence=11]="bumpSequence",e[e.manageBuyOffer=12]="manageBuyOffer",e[e.pathPaymentStrictSend=13]="pathPaymentStrictSend",e[e.createClaimableBalance=14]="createClaimableBalance",e[e.claimClaimableBalance=15]="claimClaimableBalance",e[e.beginSponsoringFutureReserves=16]="beginSponsoringFutureReserves",e[e.endSponsoringFutureReserves=17]="endSponsoringFutureReserves",e[e.revokeSponsorship=18]="revokeSponsorship",e[e.clawback=19]="clawback",e[e.clawbackClaimableBalance=20]="clawbackClaimableBalance",e[e.setTrustLineFlags=21]="setTrustLineFlags",e[e.liquidityPoolDeposit=22]="liquidityPoolDeposit",e[e.liquidityPoolWithdraw=23]="liquidityPoolWithdraw",e[e.invokeHostFunction=24]="invokeHostFunction",e[e.bumpFootprintExpiration=25]="bumpFootprintExpiration",e[e.restoreFootprint=26]="restoreFootprint",e}({});e.OperationResponseTypeI=n;var o=function(e){return e.TX_FAILED="tx_failed",e.TX_BAD_SEQ="tx_bad_seq",e.TX_BAD_AUTH="tx_bad_auth",e.TX_BAD_AUTH_EXTRA="tx_bad_auth_extra",e.TX_FEE_BUMP_INNER_SUCCESS="tx_fee_bump_inner_success",e.TX_FEE_BUMP_INNER_FAILED="tx_fee_bump_inner_failed",e.TX_NOT_SUPPORTED="tx_not_supported",e.TX_SUCCESS="tx_success",e.TX_TOO_EARLY="tx_too_early",e.TX_TOO_LATE="tx_too_late",e.TX_MISSING_OPERATION="tx_missing_operation",e.TX_INSUFFICIENT_BALANCE="tx_insufficient_balance",e.TX_NO_SOURCE_ACCOUNT="tx_no_source_account",e.TX_INSUFFICIENT_FEE="tx_insufficient_fee",e.TX_INTERNAL_ERROR="tx_internal_error",e}({});e.TransactionFailedResultCodes=o}(n||(n={}));var o,i,a=((o={})[o.account_created=0]="account_created",o[o.account_removed=1]="account_removed",o[o.account_credited=2]="account_credited",o[o.account_debited=3]="account_debited",o[o.account_thresholds_updated=4]="account_thresholds_updated",o[o.account_home_domain_updated=5]="account_home_domain_updated",o[o.account_flags_updated=6]="account_flags_updated",o[o.account_inflation_destination_updated=7]="account_inflation_destination_updated",o[o.signer_created=10]="signer_created",o[o.signer_removed=11]="signer_removed",o[o.signer_updated=12]="signer_updated",o[o.trustline_created=20]="trustline_created",o[o.trustline_removed=21]="trustline_removed",o[o.trustline_updated=22]="trustline_updated",o[o.trustline_authorized=23]="trustline_authorized",o[o.trustline_deauthorized=24]="trustline_deauthorized",o[o.trustline_authorized_to_maintain_liabilities=25]="trustline_authorized_to_maintain_liabilities",o[o.trustline_flags_updated=26]="trustline_flags_updated",o[o.offer_created=30]="offer_created",o[o.offer_removed=31]="offer_removed",o[o.offer_updated=32]="offer_updated",o[o.trade=33]="trade",o[o.data_created=40]="data_created",o[o.data_removed=41]="data_removed",o[o.data_updated=42]="data_updated",o[o.sequence_bumped=43]="sequence_bumped",o[o.claimable_balance_created=50]="claimable_balance_created",o[o.claimable_balance_claimant_created=51]="claimable_balance_claimant_created",o[o.claimable_balance_claimed=52]="claimable_balance_claimed",o[o.account_sponsorship_created=60]="account_sponsorship_created",o[o.account_sponsorship_updated=61]="account_sponsorship_updated",o[o.account_sponsorship_removed=62]="account_sponsorship_removed",o[o.trustline_sponsorship_created=63]="trustline_sponsorship_created",o[o.trustline_sponsorship_updated=64]="trustline_sponsorship_updated",o[o.trustline_sponsorship_removed=65]="trustline_sponsorship_removed",o[o.data_sponsorship_created=66]="data_sponsorship_created",o[o.data_sponsorship_updated=67]="data_sponsorship_updated",o[o.data_sponsorship_removed=68]="data_sponsorship_removed",o[o.claimable_balance_sponsorship_created=69]="claimable_balance_sponsorship_created",o[o.claimable_balance_sponsorship_updated=70]="claimable_balance_sponsorship_updated",o[o.claimable_balance_sponsorship_removed=71]="claimable_balance_sponsorship_removed",o[o.signer_sponsorship_created=72]="signer_sponsorship_created",o[o.signer_sponsorship_updated=73]="signer_sponsorship_updated",o[o.signer_sponsorship_removed=74]="signer_sponsorship_removed",o[o.claimable_balance_clawed_back=80]="claimable_balance_clawed_back",o[o.liquidity_pool_deposited=90]="liquidity_pool_deposited",o[o.liquidity_pool_withdrew=91]="liquidity_pool_withdrew",o[o.liquidity_pool_trade=92]="liquidity_pool_trade",o[o.liquidity_pool_created=93]="liquidity_pool_created",o[o.liquidity_pool_removed=94]="liquidity_pool_removed",o[o.liquidity_pool_revoked=95]="liquidity_pool_revoked",o[o.contract_credited=96]="contract_credited",o[o.contract_debited=97]="contract_debited",o);!function(e){e.EffectType=a;var t=function(e){return e.all="all",e.liquidityPools="liquidity_pool",e.orderbook="orderbook",e}({});e.TradeType=t;n.OperationResponseType,n.OperationResponseTypeI}(i||(i={}));var s=r(356);function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],u=!0,c=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);u=!0);}catch(e){c=!0,o=e}finally{try{if(!u&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return l(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?l(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r0||e===t?t:t-1}function P(e){for(var t,r,n=1,o=e.length,i=e[0]+"";nc^r?1:-1;for(s=(u=o.length)<(c=i.length)?u:c,a=0;ai[a]^r?1:-1;return u==c?0:u>c^r?1:-1}function j(e,t,r,n){if(er||e!==b(e))throw Error(w+(n||"Argument")+("number"==typeof e?er?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function C(e){var t=e.c.length-1;return A(e.e/_)==t&&e.c[t]%2!=0}function I(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function L(e,t,r){var n,o;if(t<0){for(o=r+".";++t;o+=r);e=o+e}else if(++t>(n=e.length)){for(o=r,t-=n;--t;o+=r);e+=o}else tU?p.c=p.e=null:e.e=10;u/=10,s++);return void(s>U?p.c=p.e=null:(p.e=s,p.c=[e]))}f=String(e)}else{if(!v.test(f=String(e)))return o(p,f,c);p.s=45==f.charCodeAt(0)?(f=f.slice(1),-1):1}(s=f.indexOf("."))>-1&&(f=f.replace(".","")),(u=f.search(/e/i))>0?(s<0&&(s=u),s+=+f.slice(u+1),f=f.substring(0,u)):s<0&&(s=f.length)}else{if(j(t,2,q.length,"Base"),10==t&&K)return W(p=new H(e),h+p.e+1,y);if(f=String(e),c="number"==typeof e){if(0*e!=0)return o(p,f,c,t);if(p.s=1/e<0?(f=f.slice(1),-1):1,H.DEBUG&&f.replace(/^0\.0*|\./,"").length>15)throw Error(S+e)}else p.s=45===f.charCodeAt(0)?(f=f.slice(1),-1):1;for(r=q.slice(0,t),s=u=0,l=f.length;us){s=l;continue}}else if(!a&&(f==f.toUpperCase()&&(f=f.toLowerCase())||f==f.toLowerCase()&&(f=f.toUpperCase()))){a=!0,u=-1,s=0;continue}return o(p,String(e),c,t)}c=!1,(s=(f=n(f,t,10,p.s)).indexOf("."))>-1?f=f.replace(".",""):s=f.length}for(u=0;48===f.charCodeAt(u);u++);for(l=f.length;48===f.charCodeAt(--l););if(f=f.slice(u,++l)){if(l-=u,c&&H.DEBUG&&l>15&&(e>k||e!==b(e)))throw Error(S+p.s*e);if((s=s-u-1)>U)p.c=p.e=null;else if(s=B)?I(u,a):L(u,a,"0");else if(i=(e=W(new H(e),t,r)).e,s=(u=P(e.c)).length,1==n||2==n&&(t<=i||i<=m)){for(;ss){if(--t>0)for(u+=".";t--;u+="0");}else if((t+=i-s)>0)for(i+1==s&&(u+=".");t--;u+="0");return e.s<0&&o?"-"+u:u}function X(e,t){for(var r,n,o=1,i=new H(e[0]);o=10;o/=10,n++);return(r=n+r*_-1)>U?e.c=e.e=null:r=10;s/=10,o++);if((i=t-o)<0)i+=_,a=t,u=f[c=0],l=b(u/p[o-a-1]%10);else if((c=g((i+1)/_))>=f.length){if(!n)break e;for(;f.length<=c;f.push(0));u=l=0,o=1,a=(i%=_)-_+1}else{for(u=s=f[c],o=1;s>=10;s/=10,o++);l=(a=(i%=_)-_+o)<0?0:b(u/p[o-a-1]%10)}if(n=n||t<0||null!=f[c+1]||(a<0?u:u%p[o-a-1]),n=r<4?(l||n)&&(0==r||r==(e.s<0?3:2)):l>5||5==l&&(4==r||n||6==r&&(i>0?a>0?u/p[o-a]:0:f[c-1])%10&1||r==(e.s<0?8:7)),t<1||!f[0])return f.length=0,n?(t-=e.e+1,f[0]=p[(_-t%_)%_],e.e=-t||0):f[0]=e.e=0,e;if(0==i?(f.length=c,s=1,c--):(f.length=c+1,s=p[_-i],f[c]=a>0?b(u/p[o-a]%p[a])*s:0),n)for(;;){if(0==c){for(i=1,a=f[0];a>=10;a/=10,i++);for(a=f[0]+=s,s=1;a>=10;a/=10,s++);i!=s&&(e.e++,f[0]==E&&(f[0]=1));break}if(f[c]+=s,f[c]!=E)break;f[c--]=0,s=1}for(i=f.length;0===f[--i];f.pop());}e.e>U?e.c=e.e=null:e.e=B?I(t,r):L(t,r,"0"),e.s<0?"-"+t:t)}return H.clone=e,H.ROUND_UP=0,H.ROUND_DOWN=1,H.ROUND_CEIL=2,H.ROUND_FLOOR=3,H.ROUND_HALF_UP=4,H.ROUND_HALF_DOWN=5,H.ROUND_HALF_EVEN=6,H.ROUND_HALF_CEIL=7,H.ROUND_HALF_FLOOR=8,H.EUCLID=9,H.config=H.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(w+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(j(r=e[t],0,x,t),h=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(j(r=e[t],0,8,t),y=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(j(r[0],-x,0,t),j(r[1],0,x,t),m=r[0],B=r[1]):(j(r,-x,x,t),m=-(B=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)j(r[0],-x,-1,t),j(r[1],1,x,t),N=r[0],U=r[1];else{if(j(r,-x,x,t),!r)throw Error(w+t+" cannot be zero: "+r);N=-(U=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(w+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw M=!r,Error(w+"crypto unavailable");M=r}else M=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(j(r=e[t],0,9,t),D=r),e.hasOwnProperty(t="POW_PRECISION")&&(j(r=e[t],0,x,t),F=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(w+t+" not an object: "+r);V=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(w+t+" invalid: "+r);K="0123456789"==r.slice(0,10),q=r}}return{DECIMAL_PLACES:h,ROUNDING_MODE:y,EXPONENTIAL_AT:[m,B],RANGE:[N,U],CRYPTO:M,MODULO_MODE:D,POW_PRECISION:F,FORMAT:V,ALPHABET:q}},H.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!H.DEBUG)return!0;var t,r,n=e.c,o=e.e,i=e.s;e:if("[object Array]"=={}.toString.call(n)){if((1===i||-1===i)&&o>=-x&&o<=x&&o===b(o)){if(0===n[0]){if(0===o&&1===n.length)return!0;break e}if((t=(o+1)%_)<1&&(t+=_),String(n[0]).length==t){for(t=0;t=E||r!==b(r))break e;if(0!==r)return!0}}}else if(null===n&&null===o&&(null===i||1===i||-1===i))return!0;throw Error(w+"Invalid BigNumber: "+e)},H.maximum=H.max=function(){return X(arguments,-1)},H.minimum=H.min=function(){return X(arguments,1)},H.random=(i=9007199254740992,a=Math.random()*i&2097151?function(){return b(Math.random()*i)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,n,o,i,s=0,u=[],c=new H(d);if(null==e?e=h:j(e,0,x),o=g(e/_),M)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(o*=2));s>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[s]=r[0],t[s+1]=r[1]):(u.push(i%1e14),s+=2);s=o/2}else{if(!crypto.randomBytes)throw M=!1,Error(w+"crypto unavailable");for(t=crypto.randomBytes(o*=7);s=9e15?crypto.randomBytes(7).copy(t,s):(u.push(i%1e14),s+=7);s=o/7}if(!M)for(;s=10;i/=10,s++);s<_&&(n-=_-s)}return c.e=n,c.c=u,c}),H.sum=function(){for(var e=1,t=arguments,r=new H(t[0]);er-1&&(null==a[o+1]&&(a[o+1]=0),a[o+1]+=a[o]/r|0,a[o]%=r)}return a.reverse()}return function(n,o,i,a,s){var u,c,l,f,p,d,m,v,g=n.indexOf("."),b=h,w=y;for(g>=0&&(f=F,F=0,n=n.replace(".",""),d=(v=new H(o)).pow(n.length-g),F=f,v.c=t(L(P(d.c),d.e,"0"),10,i,e),v.e=v.c.length),l=f=(m=t(n,o,i,s?(u=q,e):(u=e,q))).length;0==m[--f];m.pop());if(!m[0])return u.charAt(0);if(g<0?--l:(d.c=m,d.e=l,d.s=a,m=(d=r(d,v,b,w,i)).c,p=d.r,l=d.e),g=m[c=l+b+1],f=i/2,p=p||c<0||null!=m[c+1],p=w<4?(null!=g||p)&&(0==w||w==(d.s<0?3:2)):g>f||g==f&&(4==w||p||6==w&&1&m[c-1]||w==(d.s<0?8:7)),c<1||!m[0])n=p?L(u.charAt(1),-b,u.charAt(0)):u.charAt(0);else{if(m.length=c,p)for(--i;++m[--c]>i;)m[c]=0,c||(++l,m=[1].concat(m));for(f=m.length;!m[--f];);for(g=0,n="";g<=f;n+=u.charAt(m[g++]));n=L(n,l,u.charAt(0))}return n}}(),r=function(){function e(e,t,r){var n,o,i,a,s=0,u=e.length,c=t%O,l=t/O|0;for(e=e.slice();u--;)s=((o=c*(i=e[u]%O)+(n=l*i+(a=e[u]/O|0)*c)%O*O+s)/r|0)+(n/O|0)+l*a,e[u]=o%r;return s&&(e=[s].concat(e)),e}function t(e,t,r,n){var o,i;if(r!=n)i=r>n?1:-1;else for(o=i=0;ot[o]?1:-1;break}return i}function r(e,t,r,n){for(var o=0;r--;)e[r]-=o,o=e[r]1;e.splice(0,1));}return function(n,o,i,a,s){var u,c,l,f,p,d,h,y,m,v,g,w,S,k,T,O,x,P=n.s==o.s?1:-1,R=n.c,j=o.c;if(!(R&&R[0]&&j&&j[0]))return new H(n.s&&o.s&&(R?!j||R[0]!=j[0]:j)?R&&0==R[0]||!j?0*P:P/0:NaN);for(m=(y=new H(P)).c=[],P=i+(c=n.e-o.e)+1,s||(s=E,c=A(n.e/_)-A(o.e/_),P=P/_|0),l=0;j[l]==(R[l]||0);l++);if(j[l]>(R[l]||0)&&c--,P<0)m.push(1),f=!0;else{for(k=R.length,O=j.length,l=0,P+=2,(p=b(s/(j[0]+1)))>1&&(j=e(j,p,s),R=e(R,p,s),O=j.length,k=R.length),S=O,g=(v=R.slice(0,O)).length;g=s/2&&T++;do{if(p=0,(u=t(j,v,O,g))<0){if(w=v[0],O!=g&&(w=w*s+(v[1]||0)),(p=b(w/T))>1)for(p>=s&&(p=s-1),h=(d=e(j,p,s)).length,g=v.length;1==t(d,v,h,g);)p--,r(d,O=10;P/=10,l++);W(y,i+(y.e=l+c*_-1)+1,a,f)}else y.e=c,y.r=+f;return y}}(),s=/^(-?)0([xbo])(?=\w[\w.]*$)/i,u=/^([^.]+)\.$/,c=/^\.([^.]+)$/,l=/^-?(Infinity|NaN)$/,f=/^\s*\+(?=[\w.])|^\s+|\s+$/g,o=function(e,t,r,n){var o,i=r?t:t.replace(f,"");if(l.test(i))e.s=isNaN(i)?null:i<0?-1:1;else{if(!r&&(i=i.replace(s,(function(e,t,r){return o="x"==(r=r.toLowerCase())?16:"b"==r?2:8,n&&n!=o?e:t})),n&&(o=n,i=i.replace(u,"$1").replace(c,"0.$1")),t!=i))return new H(i,o);if(H.DEBUG)throw Error(w+"Not a"+(n?" base "+n:"")+" number: "+t);e.s=null}e.c=e.e=null},p.absoluteValue=p.abs=function(){var e=new H(this);return e.s<0&&(e.s=1),e},p.comparedTo=function(e,t){return R(this,new H(e,t))},p.decimalPlaces=p.dp=function(e,t){var r,n,o,i=this;if(null!=e)return j(e,0,x),null==t?t=y:j(t,0,8),W(new H(i),e+i.e+1,t);if(!(r=i.c))return null;if(n=((o=r.length-1)-A(this.e/_))*_,o=r[o])for(;o%10==0;o/=10,n--);return n<0&&(n=0),n},p.dividedBy=p.div=function(e,t){return r(this,new H(e,t),h,y)},p.dividedToIntegerBy=p.idiv=function(e,t){return r(this,new H(e,t),0,1)},p.exponentiatedBy=p.pow=function(e,t){var r,n,o,i,a,s,u,c,l=this;if((e=new H(e)).c&&!e.isInteger())throw Error(w+"Exponent not an integer: "+$(e));if(null!=t&&(t=new H(t)),a=e.e>14,!l.c||!l.c[0]||1==l.c[0]&&!l.e&&1==l.c.length||!e.c||!e.c[0])return c=new H(Math.pow(+$(l),a?e.s*(2-C(e)):+$(e))),t?c.mod(t):c;if(s=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new H(NaN);(n=!s&&l.isInteger()&&t.isInteger())&&(l=l.mod(t))}else{if(e.e>9&&(l.e>0||l.e<-1||(0==l.e?l.c[0]>1||a&&l.c[1]>=24e7:l.c[0]<8e13||a&&l.c[0]<=9999975e7)))return i=l.s<0&&C(e)?-0:0,l.e>-1&&(i=1/i),new H(s?1/i:i);F&&(i=g(F/_+2))}for(a?(r=new H(.5),s&&(e.s=1),u=C(e)):u=(o=Math.abs(+$(e)))%2,c=new H(d);;){if(u){if(!(c=c.times(l)).c)break;i?c.c.length>i&&(c.c.length=i):n&&(c=c.mod(t))}if(o){if(0===(o=b(o/2)))break;u=o%2}else if(W(e=e.times(r),e.e+1,1),e.e>14)u=C(e);else{if(0===(o=+$(e)))break;u=o%2}l=l.times(l),i?l.c&&l.c.length>i&&(l.c.length=i):n&&(l=l.mod(t))}return n?c:(s&&(c=d.div(c)),t?c.mod(t):i?W(c,F,y,undefined):c)},p.integerValue=function(e){var t=new H(this);return null==e?e=y:j(e,0,8),W(t,t.e+1,e)},p.isEqualTo=p.eq=function(e,t){return 0===R(this,new H(e,t))},p.isFinite=function(){return!!this.c},p.isGreaterThan=p.gt=function(e,t){return R(this,new H(e,t))>0},p.isGreaterThanOrEqualTo=p.gte=function(e,t){return 1===(t=R(this,new H(e,t)))||0===t},p.isInteger=function(){return!!this.c&&A(this.e/_)>this.c.length-2},p.isLessThan=p.lt=function(e,t){return R(this,new H(e,t))<0},p.isLessThanOrEqualTo=p.lte=function(e,t){return-1===(t=R(this,new H(e,t)))||0===t},p.isNaN=function(){return!this.s},p.isNegative=function(){return this.s<0},p.isPositive=function(){return this.s>0},p.isZero=function(){return!!this.c&&0==this.c[0]},p.minus=function(e,t){var r,n,o,i,a=this,s=a.s;if(t=(e=new H(e,t)).s,!s||!t)return new H(NaN);if(s!=t)return e.s=-t,a.plus(e);var u=a.e/_,c=e.e/_,l=a.c,f=e.c;if(!u||!c){if(!l||!f)return l?(e.s=-t,e):new H(f?a:NaN);if(!l[0]||!f[0])return f[0]?(e.s=-t,e):new H(l[0]?a:3==y?-0:0)}if(u=A(u),c=A(c),l=l.slice(),s=u-c){for((i=s<0)?(s=-s,o=l):(c=u,o=f),o.reverse(),t=s;t--;o.push(0));o.reverse()}else for(n=(i=(s=l.length)<(t=f.length))?s:t,s=t=0;t0)for(;t--;l[r++]=0);for(t=E-1;n>s;){if(l[--n]=0;){for(r=0,p=b[o]%m,d=b[o]/m|0,i=o+(a=u);i>o;)r=((c=p*(c=g[--a]%m)+(s=d*c+(l=g[a]/m|0)*p)%m*m+h[i]+r)/y|0)+(s/m|0)+d*l,h[i--]=c%y;h[i]=r}return r?++n:h.splice(0,1),G(e,h,n)},p.negated=function(){var e=new H(this);return e.s=-e.s||null,e},p.plus=function(e,t){var r,n=this,o=n.s;if(t=(e=new H(e,t)).s,!o||!t)return new H(NaN);if(o!=t)return e.s=-t,n.minus(e);var i=n.e/_,a=e.e/_,s=n.c,u=e.c;if(!i||!a){if(!s||!u)return new H(o/0);if(!s[0]||!u[0])return u[0]?e:new H(s[0]?n:0*o)}if(i=A(i),a=A(a),s=s.slice(),o=i-a){for(o>0?(a=i,r=u):(o=-o,r=s),r.reverse();o--;r.push(0));r.reverse()}for((o=s.length)-(t=u.length)<0&&(r=u,u=s,s=r,t=o),o=0;t;)o=(s[--t]=s[t]+u[t]+o)/E|0,s[t]=E===s[t]?0:s[t]%E;return o&&(s=[o].concat(s),++a),G(e,s,a)},p.precision=p.sd=function(e,t){var r,n,o,i=this;if(null!=e&&e!==!!e)return j(e,1,x),null==t?t=y:j(t,0,8),W(new H(i),e,t);if(!(r=i.c))return null;if(n=(o=r.length-1)*_+1,o=r[o]){for(;o%10==0;o/=10,n--);for(o=r[0];o>=10;o/=10,n++);}return e&&i.e+1>n&&(n=i.e+1),n},p.shiftedBy=function(e){return j(e,-9007199254740991,k),this.times("1e"+e)},p.squareRoot=p.sqrt=function(){var e,t,n,o,i,a=this,s=a.c,u=a.s,c=a.e,l=h+4,f=new H("0.5");if(1!==u||!s||!s[0])return new H(!u||u<0&&(!s||s[0])?NaN:s?a:1/0);if(0==(u=Math.sqrt(+$(a)))||u==1/0?(((t=P(s)).length+c)%2==0&&(t+="0"),u=Math.sqrt(+t),c=A((c+1)/2)-(c<0||c%2),n=new H(t=u==1/0?"5e"+c:(t=u.toExponential()).slice(0,t.indexOf("e")+1)+c)):n=new H(u+""),n.c[0])for((u=(c=n.e)+l)<3&&(u=0);;)if(i=n,n=f.times(i.plus(r(a,i,l,1))),P(i.c).slice(0,u)===(t=P(n.c)).slice(0,u)){if(n.e0&&h>0){for(i=h%s||s,l=d.substr(0,i);i0&&(l+=c+d.slice(i)),p&&(l="-"+l)}n=f?l+(r.decimalSeparator||"")+((u=+r.fractionGroupSize)?f.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):f):l}return(r.prefix||"")+n+(r.suffix||"")},p.toFraction=function(e){var t,n,o,i,a,s,u,c,l,f,p,h,m=this,v=m.c;if(null!=e&&(!(u=new H(e)).isInteger()&&(u.c||1!==u.s)||u.lt(d)))throw Error(w+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+$(u));if(!v)return new H(m);for(t=new H(d),l=n=new H(d),o=c=new H(d),h=P(v),a=t.e=h.length-m.e-1,t.c[0]=T[(s=a%_)<0?_+s:s],e=!e||u.comparedTo(t)>0?a>0?t:l:u,s=U,U=1/0,u=new H(h),c.c[0]=0;f=r(u,t,0,1),1!=(i=n.plus(f.times(o))).comparedTo(e);)n=o,o=i,l=c.plus(f.times(i=l)),c=i,t=u.minus(f.times(i=t)),u=i;return i=r(e.minus(n),o,0,1),c=c.plus(i.times(l)),n=n.plus(i.times(o)),c.s=l.s=m.s,p=r(l,o,a*=2,y).minus(m).abs().comparedTo(r(c,n,a,y).minus(m).abs())<1?[l,o]:[c,n],U=s,p},p.toNumber=function(){return+$(this)},p.toPrecision=function(e,t){return null!=e&&j(e,1,x),z(this,e,t,2)},p.toString=function(e){var t,r=this,o=r.s,i=r.e;return null===i?o?(t="Infinity",o<0&&(t="-"+t)):t="NaN":(null==e?t=i<=m||i>=B?I(P(r.c),i):L(P(r.c),i,"0"):10===e&&K?t=L(P((r=W(new H(r),h+i+1,y)).c),r.e,"0"):(j(e,2,q.length,"Base"),t=n(L(P(r.c),i,"0"),10,e,o,!0)),o<0&&r.c[0]&&(t="-"+t)),t},p.valueOf=p.toJSON=function(){return $(this)},p._isBigNumber=!0,p[Symbol.toStringTag]="BigNumber",p[Symbol.for("nodejs.util.inspect.custom")]=p.valueOf,null!=t&&H.set(t),H}();const N=B;var U=r(4193),M=r.n(U),D=r(9127),F=r.n(D),V=r(5976),q=r(9983);function K(e){return K="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},K(e)}var H="13.1.0",z={},X=(0,q.vt)({headers:{"X-Client-Name":"js-stellar-sdk","X-Client-Version":H}});function G(e){return Math.floor(e/1e3)}X.interceptors.response.use((function(e){var t=M()(e.config.url).hostname(),r=0;if(e.headers instanceof Headers){var n=e.headers.get("date");n&&(r=G(Date.parse(n)))}else if("object"===K(e.headers)&&"date"in e.headers){var o=e.headers;"string"==typeof o.date&&(r=G(Date.parse(o.date)))}var i=G((new Date).getTime());return Number.isNaN(r)||(z[t]={serverTime:r,localTimeRecorded:i}),e}));const W=X;function $(e){var t=z[e];if(!t||!t.localTimeRecorded||!t.serverTime)return null;var r=t.serverTime,n=t.localTimeRecorded,o=G((new Date).getTime());return o-n>300?null:o-n+r}function Q(e){return Q="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Q(e)}function Y(){Y=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function l(e,t,r,n){var i=t&&t.prototype instanceof v?t:v,a=Object.create(i.prototype),s=new R(n||[]);return o(a,"_invoke",{value:O(e,r,s)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var p="suspendedStart",d="suspendedYield",h="executing",y="completed",m={};function v(){}function g(){}function b(){}var w={};c(w,a,(function(){return this}));var S=Object.getPrototypeOf,E=S&&S(S(j([])));E&&E!==r&&n.call(E,a)&&(w=E);var _=b.prototype=v.prototype=Object.create(w);function k(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function T(e,t){function r(o,i,a,s){var u=f(e[o],e,i);if("throw"!==u.type){var c=u.arg,l=c.value;return l&&"object"==Q(l)&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(l).then((function(e){c.value=e,a(c)}),(function(e){return r("throw",e,a,s)}))}s(u.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function O(t,r,n){var o=p;return function(i,a){if(o===h)throw Error("Generator is already running");if(o===y){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=x(s,n);if(u){if(u===m)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=y,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=h;var c=f(t,r,n);if("normal"===c.type){if(o=n.done?y:d,c.arg===m)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=y,n.method="throw",n.arg=c.arg)}}}function x(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,x(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),m;var i=f(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,m;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,m):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,m)}function A(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(A,this),this.reset(!0)}function j(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function J(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function Z(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){J(i,n,o,a,s,"next",e)}function s(e){J(i,n,o,a,s,"throw",e)}a(void 0)}))}}function ee(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:"";!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.url=t.clone(),this.filter=[],this.originalSegments=this.url.segment()||[],this.neighborRoot=r}),[{key:"call",value:function(){var e=this;return this.checkFilter(),this._sendNormalRequest(this.url).then((function(t){return e._parseResponse(t)}))}},{key:"stream",value:function(){var e,t,r=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(void 0===re)throw new Error("Streaming requires eventsource to be enabled. If you need this functionality, compile with USE_EVENTSOURCE=true.");this.checkFilter(),this.url.setQuery("X-Client-Name","js-stellar-sdk"),this.url.setQuery("X-Client-Version",H);var o=function(){t=setTimeout((function(){var t;null===(t=e)||void 0===t||t.close(),e=i()}),n.reconnectTimeout||15e3)},i=function(){try{e=new re(r.url.toString())}catch(e){n.onerror&&n.onerror(e)}if(o(),!e)return e;var a=!1,s=function(){a||(clearTimeout(t),e.close(),i(),a=!0)},u=function(e){if("close"!==e.type){var i=e.data?r._parseRecord(JSON.parse(e.data)):e;i.paging_token&&r.url.setQuery("cursor",i.paging_token),clearTimeout(t),o(),void 0!==n.onmessage&&n.onmessage(i)}else s()},c=function(e){n.onerror&&n.onerror(e)};return e.addEventListener?(e.addEventListener("message",u.bind(r)),e.addEventListener("error",c.bind(r)),e.addEventListener("close",s.bind(r))):(e.onmessage=u.bind(r),e.onerror=c.bind(r)),e};return i(),function(){var r;clearTimeout(t),null===(r=e)||void 0===r||r.close()}}},{key:"cursor",value:function(e){return this.url.setQuery("cursor",e),this}},{key:"limit",value:function(e){return this.url.setQuery("limit",e.toString()),this}},{key:"order",value:function(e){return this.url.setQuery("order",e),this}},{key:"join",value:function(e){return this.url.setQuery("join",e),this}},{key:"forEndpoint",value:function(e,t){if(""===this.neighborRoot)throw new Error("Invalid usage: neighborRoot not set in constructor");return this.filter.push([e,t,this.neighborRoot]),this}},{key:"checkFilter",value:function(){if(this.filter.length>=2)throw new V.v7("Too many filters specified",this.filter);if(1===this.filter.length){var e=this.originalSegments.concat(this.filter[0]);this.url.segment(e)}}},{key:"_requestFnForLink",value:function(e){var t=this;return Z(Y().mark((function r(){var n,o,i,a,s=arguments;return Y().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return n=s.length>0&&void 0!==s[0]?s[0]:{},e.templated?(i=F()(e.href),o=M()(i.expand(n))):o=M()(e.href),r.next=4,t._sendNormalRequest(o);case 4:return a=r.sent,r.abrupt("return",t._parseResponse(a));case 6:case"end":return r.stop()}}),r)})))}},{key:"_parseRecord",value:function(e){var t=this;return e._links?(Object.keys(e._links).forEach((function(r){var n=e._links[r],o=!1;if(void 0!==e[r]&&(e["".concat(r,"_attr")]=e[r],o=!0),o&&ae.indexOf(r)>=0){var i=t._parseRecord(e[r]);e[r]=Z(Y().mark((function e(){return Y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",i);case 1:case"end":return e.stop()}}),e)})))}else e[r]=t._requestFnForLink(n)})),e):e}},{key:"_sendNormalRequest",value:(ce=Z(Y().mark((function e(t){var r;return Y().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return""===(r=t).authority()&&(r=r.authority(this.url.authority())),""===r.protocol()&&(r=r.protocol(this.url.protocol())),e.abrupt("return",X.get(r.toString()).then((function(e){return e.data})).catch(this._handleNetworkError));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return ce.apply(this,arguments)})},{key:"_parseResponse",value:function(e){return e._embedded&&e._embedded.records?this._toCollectionPage(e):this._parseRecord(e)}},{key:"_toCollectionPage",value:function(e){for(var t,r,n=this,o=0;ot||e>=24*r||e%r!=0)}}])}(le);function vr(e){return vr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},vr(e)}function gr(e,t){for(var r=0;r=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function Mr(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function Dr(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){Mr(i,n,o,a,s,"next",e)}function s(e){Mr(i,n,o,a,s,"throw",e)}a(void 0)}))}}function Fr(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.serverURL=M()(t);var n=void 0===r.allowHttp?fe.T.isAllowHttp():r.allowHttp,o={};if(r.appName&&(o["X-App-Name"]=r.appName),r.appVersion&&(o["X-App-Version"]=r.appVersion),r.authToken&&(o["X-Auth-Token"]=r.authToken),r.headers&&Object.assign(o,r.headers),Object.keys(o).length>0&&W.interceptors.request.use((function(e){return e.headers=e.headers||{},e.headers=Object.assign(e.headers,o),e})),"https"!==this.serverURL.protocol()&&!n)throw new Error("Cannot connect to insecure horizon server")}),[{key:"fetchTimebounds",value:(Qr=Dr(Ur().mark((function e(t){var r,n,o=arguments;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=o.length>1&&void 0!==o[1]&&o[1],!(n=$(this.serverURL.hostname()))){e.next=4;break}return e.abrupt("return",{minTime:0,maxTime:n+t});case 4:if(!r){e.next=6;break}return e.abrupt("return",{minTime:0,maxTime:Math.floor((new Date).getTime()/1e3)+t});case 6:return e.next=8,W.get(M()(this.serverURL).toString());case 8:return e.abrupt("return",this.fetchTimebounds(t,!0));case 9:case"end":return e.stop()}}),e,this)}))),function(e){return Qr.apply(this,arguments)})},{key:"fetchBaseFee",value:($r=Dr(Ur().mark((function e(){var t;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.feeStats();case 2:return t=e.sent,e.abrupt("return",parseInt(t.last_ledger_base_fee,10)||100);case 4:case"end":return e.stop()}}),e,this)}))),function(){return $r.apply(this,arguments)})},{key:"feeStats",value:(Wr=Dr(Ur().mark((function e(){var t;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(t=new le(M()(this.serverURL))).filter.push(["fee_stats"]),e.abrupt("return",t.call());case 3:case"end":return e.stop()}}),e,this)}))),function(){return Wr.apply(this,arguments)})},{key:"root",value:(Gr=Dr(Ur().mark((function e(){var t;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=new le(M()(this.serverURL)),e.abrupt("return",t.call());case 2:case"end":return e.stop()}}),e,this)}))),function(){return Gr.apply(this,arguments)})},{key:"submitTransaction",value:(Xr=Dr(Ur().mark((function e(t){var r,n=arguments;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((n.length>1&&void 0!==n[1]?n[1]:{skipMemoRequiredCheck:!1}).skipMemoRequiredCheck){e.next=4;break}return e.next=4,this.checkMemoRequired(t);case 4:return r=encodeURIComponent(t.toEnvelope().toXDR().toString("base64")),e.abrupt("return",W.post(M()(this.serverURL).segment("transactions").toString(),"tx=".concat(r),{timeout:6e4}).then((function(e){if(!e.data.result_xdr)return e.data;var t,r,n=s.xdr.TransactionResult.fromXDR(e.data.result_xdr,"base64").result().value();return n.length&&(t=n.map((function(e,t){if("manageBuyOffer"!==e.value().switch().name&&"manageSellOffer"!==e.value().switch().name)return null;r=!0;var n,o=new N(0),i=new N(0),a=e.value().value().success(),u=a.offersClaimed().map((function(e){var t=e.value(),r="";switch(e.switch()){case s.xdr.ClaimAtomType.claimAtomTypeV0():r=s.StrKey.encodeEd25519PublicKey(t.sellerEd25519());break;case s.xdr.ClaimAtomType.claimAtomTypeOrderBook():r=s.StrKey.encodeEd25519PublicKey(t.sellerId().ed25519());break;default:throw new Error("Invalid offer result type: ".concat(e.switch()))}var n=new N(t.amountBought().toString()),a=new N(t.amountSold().toString());o=o.plus(a),i=i.plus(n);var u=s.Asset.fromOperation(t.assetSold()),c=s.Asset.fromOperation(t.assetBought()),l={type:u.getAssetType(),assetCode:u.getCode(),issuer:u.getIssuer()},f={type:c.getAssetType(),assetCode:c.getCode(),issuer:c.getIssuer()};return{sellerId:r,offerId:t.offerId().toString(),assetSold:l,amountSold:qr(a),assetBought:f,amountBought:qr(n)}})),c=a.offer().switch().name;if("function"==typeof a.offer().value&&a.offer().value()){var l=a.offer().value();n={offerId:l.offerId().toString(),selling:{},buying:{},amount:qr(l.amount().toString()),price:{n:l.price().n(),d:l.price().d()}};var f=s.Asset.fromOperation(l.selling());n.selling={type:f.getAssetType(),assetCode:f.getCode(),issuer:f.getIssuer()};var p=s.Asset.fromOperation(l.buying());n.buying={type:p.getAssetType(),assetCode:p.getCode(),issuer:p.getIssuer()}}return{offersClaimed:u,effect:c,operationIndex:t,currentOffer:n,amountBought:qr(o),amountSold:qr(i),isFullyOpen:!u.length&&"manageOfferDeleted"!==c,wasPartiallyFilled:!!u.length&&"manageOfferDeleted"!==c,wasImmediatelyFilled:!!u.length&&"manageOfferDeleted"===c,wasImmediatelyDeleted:!u.length&&"manageOfferDeleted"===c}})).filter((function(e){return!!e}))),Br(Br({},e.data),{},{offerResults:r?t:void 0})})).catch((function(e){return e instanceof Error?Promise.reject(e):Promise.reject(new V.nS("Transaction submission failed. Server responded: ".concat(e.status," ").concat(e.statusText),e.data))})));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return Xr.apply(this,arguments)})},{key:"submitAsyncTransaction",value:(zr=Dr(Ur().mark((function e(t){var r,n=arguments;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((n.length>1&&void 0!==n[1]?n[1]:{skipMemoRequiredCheck:!1}).skipMemoRequiredCheck){e.next=4;break}return e.next=4,this.checkMemoRequired(t);case 4:return r=encodeURIComponent(t.toEnvelope().toXDR().toString("base64")),e.abrupt("return",W.post(M()(this.serverURL).segment("transactions_async").toString(),"tx=".concat(r)).then((function(e){return e.data})).catch((function(e){return e instanceof Error?Promise.reject(e):Promise.reject(new V.nS("Transaction submission failed. Server responded: ".concat(e.status," ").concat(e.statusText),e.data))})));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return zr.apply(this,arguments)})},{key:"accounts",value:function(){return new be(M()(this.serverURL))}},{key:"claimableBalances",value:function(){return new Be(M()(this.serverURL))}},{key:"ledgers",value:function(){return new it(M()(this.serverURL))}},{key:"transactions",value:function(){return new Cr(M()(this.serverURL))}},{key:"offers",value:function(){return new St(M()(this.serverURL))}},{key:"orderbook",value:function(e,t){return new Ut(M()(this.serverURL),e,t)}},{key:"trades",value:function(){return new kr(M()(this.serverURL))}},{key:"operations",value:function(){return new Pt(M()(this.serverURL))}},{key:"liquidityPools",value:function(){return new dt(M()(this.serverURL))}},{key:"strictReceivePaths",value:function(e,t,r){return new Zt(M()(this.serverURL),e,t,r)}},{key:"strictSendPaths",value:function(e,t,r){return new sr(M()(this.serverURL),e,t,r)}},{key:"payments",value:function(){return new zt(M()(this.serverURL))}},{key:"effects",value:function(){return new Ke(M()(this.serverURL))}},{key:"friendbot",value:function(e){return new Ye(M()(this.serverURL),e)}},{key:"assets",value:function(){return new xe(M()(this.serverURL))}},{key:"loadAccount",value:(Hr=Dr(Ur().mark((function e(t){var r;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.accounts().accountId(t).call();case 2:return r=e.sent,e.abrupt("return",new m(r));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return Hr.apply(this,arguments)})},{key:"tradeAggregation",value:function(e,t,r,n,o,i){return new mr(M()(this.serverURL),e,t,r,n,o,i)}},{key:"checkMemoRequired",value:(Kr=Dr(Ur().mark((function e(t){var r,n,o,i;return Ur().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t instanceof s.FeeBumpTransaction&&(t=t.innerTransaction),"none"===t.memo.type){e.next=3;break}return e.abrupt("return");case 3:r=new Set,n=0;case 5:if(!(n{"use strict";r.r(t),r.d(t,{axiosClient:()=>Tt,create:()=>Ot});var n={};function o(e,t){return function(){return e.apply(t,arguments)}}r.r(n),r.d(n,{hasBrowserEnv:()=>he,hasStandardBrowserEnv:()=>me,hasStandardBrowserWebWorkerEnv:()=>ve,navigator:()=>ye,origin:()=>ge});const{toString:i}=Object.prototype,{getPrototypeOf:a}=Object,s=(u=Object.create(null),e=>{const t=i.call(e);return u[t]||(u[t]=t.slice(8,-1).toLowerCase())});var u;const c=e=>(e=e.toLowerCase(),t=>s(t)===e),l=e=>t=>typeof t===e,{isArray:f}=Array,p=l("undefined");const d=c("ArrayBuffer");const h=l("string"),y=l("function"),m=l("number"),v=e=>null!==e&&"object"==typeof e,g=e=>{if("object"!==s(e))return!1;const t=a(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},b=c("Date"),w=c("File"),S=c("Blob"),E=c("FileList"),_=c("URLSearchParams"),[k,T,O,x]=["ReadableStream","Request","Response","Headers"].map(c);function A(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,o;if("object"!=typeof e&&(e=[e]),f(e))for(n=0,o=e.length;n0;)if(n=r[o],t===n.toLowerCase())return n;return null}const R="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,j=e=>!p(e)&&e!==R;const C=(I="undefined"!=typeof Uint8Array&&a(Uint8Array),e=>I&&e instanceof I);var I;const L=c("HTMLFormElement"),B=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),N=c("RegExp"),U=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};A(r,((r,o)=>{let i;!1!==(i=t(r,o,e))&&(n[o]=i||r)})),Object.defineProperties(e,n)},M="abcdefghijklmnopqrstuvwxyz",D="0123456789",F={DIGIT:D,ALPHA:M,ALPHA_DIGIT:M+M.toUpperCase()+D};const V=c("AsyncFunction"),q=(K="function"==typeof setImmediate,H=y(R.postMessage),K?setImmediate:H?(z=`axios@${Math.random()}`,X=[],R.addEventListener("message",(({source:e,data:t})=>{e===R&&t===z&&X.length&&X.shift()()}),!1),e=>{X.push(e),R.postMessage(z,"*")}):e=>setTimeout(e));var K,H,z,X;const G="undefined"!=typeof queueMicrotask?queueMicrotask.bind(R):"undefined"!=typeof process&&process.nextTick||q,W={isArray:f,isArrayBuffer:d,isBuffer:function(e){return null!==e&&!p(e)&&null!==e.constructor&&!p(e.constructor)&&y(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||y(e.append)&&("formdata"===(t=s(e))||"object"===t&&y(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&d(e.buffer),t},isString:h,isNumber:m,isBoolean:e=>!0===e||!1===e,isObject:v,isPlainObject:g,isReadableStream:k,isRequest:T,isResponse:O,isHeaders:x,isUndefined:p,isDate:b,isFile:w,isBlob:S,isRegExp:N,isFunction:y,isStream:e=>v(e)&&y(e.pipe),isURLSearchParams:_,isTypedArray:C,isFileList:E,forEach:A,merge:function e(){const{caseless:t}=j(this)&&this||{},r={},n=(n,o)=>{const i=t&&P(r,o)||o;g(r[i])&&g(n)?r[i]=e(r[i],n):g(n)?r[i]=e({},n):f(n)?r[i]=n.slice():r[i]=n};for(let e=0,t=arguments.length;e(A(t,((t,n)=>{r&&y(t)?e[n]=o(t,r):e[n]=t}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let o,i,s;const u={};if(t=t||{},null==e)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],n&&!n(s,e,t)||u[s]||(t[s]=e[s],u[s]=!0);e=!1!==r&&a(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:s,kindOfTest:c,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(f(e))return e;let t=e.length;if(!m(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:L,hasOwnProperty:B,hasOwnProp:B,reduceDescriptors:U,freezeMethods:e=>{U(e,((t,r)=>{if(y(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];y(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return f(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:P,global:R,isContextDefined:j,ALPHABET:F,generateString:(e=16,t=F.ALPHA_DIGIT)=>{let r="";const{length:n}=t;for(;e--;)r+=t[Math.random()*n|0];return r},isSpecCompliantForm:function(e){return!!(e&&y(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(v(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const o=f(e)?[]:{};return A(e,((e,t)=>{const i=r(e,n+1);!p(i)&&(o[t]=i)})),t[n]=void 0,o}}return e};return r(e,0)},isAsyncFn:V,isThenable:e=>e&&(v(e)||y(e))&&y(e.then)&&y(e.catch),setImmediate:q,asap:G};function $(e,t,r,n,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),o&&(this.response=o,this.status=o.status?o.status:null)}W.inherits($,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:W.toJSONObject(this.config),code:this.code,status:this.status}}});const Q=$.prototype,Y={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{Y[e]={value:e}})),Object.defineProperties($,Y),Object.defineProperty(Q,"isAxiosError",{value:!0}),$.from=(e,t,r,n,o,i)=>{const a=Object.create(Q);return W.toFlatObject(e,a,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),$.call(a,e.message,t,r,n,o),a.cause=e,a.name=e.name,i&&Object.assign(a,i),a};const J=$;var Z=r(8287).Buffer;function ee(e){return W.isPlainObject(e)||W.isArray(e)}function te(e){return W.endsWith(e,"[]")?e.slice(0,-2):e}function re(e,t,r){return e?e.concat(t).map((function(e,t){return e=te(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const ne=W.toFlatObject(W,{},null,(function(e){return/^is[A-Z]/.test(e)}));const oe=function(e,t,r){if(!W.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=W.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!W.isUndefined(t[e])}))).metaTokens,o=r.visitor||c,i=r.dots,a=r.indexes,s=(r.Blob||"undefined"!=typeof Blob&&Blob)&&W.isSpecCompliantForm(t);if(!W.isFunction(o))throw new TypeError("visitor must be a function");function u(e){if(null===e)return"";if(W.isDate(e))return e.toISOString();if(!s&&W.isBlob(e))throw new J("Blob is not supported. Use a Buffer instead.");return W.isArrayBuffer(e)||W.isTypedArray(e)?s&&"function"==typeof Blob?new Blob([e]):Z.from(e):e}function c(e,r,o){let s=e;if(e&&!o&&"object"==typeof e)if(W.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(W.isArray(e)&&function(e){return W.isArray(e)&&!e.some(ee)}(e)||(W.isFileList(e)||W.endsWith(r,"[]"))&&(s=W.toArray(e)))return r=te(r),s.forEach((function(e,n){!W.isUndefined(e)&&null!==e&&t.append(!0===a?re([r],n,i):null===a?r:r+"[]",u(e))})),!1;return!!ee(e)||(t.append(re(o,r,i),u(e)),!1)}const l=[],f=Object.assign(ne,{defaultVisitor:c,convertValue:u,isVisitable:ee});if(!W.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!W.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+n.join("."));l.push(r),W.forEach(r,(function(r,i){!0===(!(W.isUndefined(r)||null===r)&&o.call(t,r,W.isString(i)?i.trim():i,n,f))&&e(r,n?n.concat(i):[i])})),l.pop()}}(e),t};function ie(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function ae(e,t){this._pairs=[],e&&oe(e,this,t)}const se=ae.prototype;se.append=function(e,t){this._pairs.push([e,t])},se.toString=function(e){const t=e?function(t){return e.call(this,t,ie)}:ie;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};const ue=ae;function ce(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function le(e,t,r){if(!t)return e;const n=r&&r.encode||ce;W.isFunction(r)&&(r={serialize:r});const o=r&&r.serialize;let i;if(i=o?o(t,r):W.isURLSearchParams(t)?t.toString():new ue(t,r).toString(n),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}const fe=class{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){W.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},pe={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},de={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:ue,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},he="undefined"!=typeof window&&"undefined"!=typeof document,ye="object"==typeof navigator&&navigator||void 0,me=he&&(!ye||["ReactNative","NativeScript","NS"].indexOf(ye.product)<0),ve="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,ge=he&&window.location.href||"http://localhost",be={...n,...de};const we=function(e){function t(e,r,n,o){let i=e[o++];if("__proto__"===i)return!0;const a=Number.isFinite(+i),s=o>=e.length;if(i=!i&&W.isArray(n)?n.length:i,s)return W.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!a;n[i]&&W.isObject(n[i])||(n[i]=[]);return t(e,r,n[i],o)&&W.isArray(n[i])&&(n[i]=function(e){const t={},r=Object.keys(e);let n;const o=r.length;let i;for(n=0;n{t(function(e){return W.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null};const Se={transitional:pe,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,o=W.isObject(e);o&&W.isHTMLForm(e)&&(e=new FormData(e));if(W.isFormData(e))return n?JSON.stringify(we(e)):e;if(W.isArrayBuffer(e)||W.isBuffer(e)||W.isStream(e)||W.isFile(e)||W.isBlob(e)||W.isReadableStream(e))return e;if(W.isArrayBufferView(e))return e.buffer;if(W.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return oe(e,new be.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return be.isNode&&W.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=W.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return oe(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||n?(t.setContentType("application/json",!1),function(e,t,r){if(W.isString(e))try{return(t||JSON.parse)(e),W.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Se.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(W.isResponse(e)||W.isReadableStream(e))return e;if(e&&W.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw J.from(e,J.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:be.classes.FormData,Blob:be.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};W.forEach(["delete","get","head","post","put","patch"],(e=>{Se.headers[e]={}}));const Ee=Se,_e=W.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),ke=Symbol("internals");function Te(e){return e&&String(e).trim().toLowerCase()}function Oe(e){return!1===e||null==e?e:W.isArray(e)?e.map(Oe):String(e)}function xe(e,t,r,n,o){return W.isFunction(n)?n.call(this,t,r):(o&&(t=r),W.isString(t)?W.isString(n)?-1!==t.indexOf(n):W.isRegExp(n)?n.test(t):void 0:void 0)}class Ae{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function o(e,t,r){const o=Te(t);if(!o)throw new Error("header name must be a non-empty string");const i=W.findKey(n,o);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=Oe(e))}const i=(e,t)=>W.forEach(e,((e,r)=>o(e,r,t)));if(W.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(W.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))i((e=>{const t={};let r,n,o;return e&&e.split("\n").forEach((function(e){o=e.indexOf(":"),r=e.substring(0,o).trim().toLowerCase(),n=e.substring(o+1).trim(),!r||t[r]&&_e[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t);else if(W.isHeaders(e))for(const[t,n]of e.entries())o(n,t,r);else null!=e&&o(t,e,r);return this}get(e,t){if(e=Te(e)){const r=W.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(W.isFunction(t))return t.call(this,e,r);if(W.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Te(e)){const r=W.findKey(this,e);return!(!r||void 0===this[r]||t&&!xe(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function o(e){if(e=Te(e)){const o=W.findKey(r,e);!o||t&&!xe(0,r[o],o,t)||(delete r[o],n=!0)}}return W.isArray(e)?e.forEach(o):o(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const o=t[r];e&&!xe(0,this[o],o,e,!0)||(delete this[o],n=!0)}return n}normalize(e){const t=this,r={};return W.forEach(this,((n,o)=>{const i=W.findKey(r,o);if(i)return t[i]=Oe(n),void delete t[o];const a=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(o):String(o).trim();a!==o&&delete t[o],t[a]=Oe(n),r[a]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return W.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&W.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[ke]=this[ke]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=Te(e);t[n]||(!function(e,t){const r=W.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,o){return this[n].call(this,t,e,r,o)},configurable:!0})}))}(r,e),t[n]=!0)}return W.isArray(e)?e.forEach(n):n(e),this}}Ae.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),W.reduceDescriptors(Ae.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),W.freezeMethods(Ae);const Pe=Ae;function Re(e,t){const r=this||Ee,n=t||r,o=Pe.from(n.headers);let i=n.data;return W.forEach(e,(function(e){i=e.call(r,i,o.normalize(),t?t.status:void 0)})),o.normalize(),i}function je(e){return!(!e||!e.__CANCEL__)}function Ce(e,t,r){J.call(this,null==e?"canceled":e,J.ERR_CANCELED,t,r),this.name="CanceledError"}W.inherits(Ce,J,{__CANCEL__:!0});const Ie=Ce;function Le(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new J("Request failed with status code "+r.status,[J.ERR_BAD_REQUEST,J.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}const Be=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let o,i=0,a=0;return t=void 0!==t?t:1e3,function(s){const u=Date.now(),c=n[a];o||(o=u),r[i]=s,n[i]=u;let l=a,f=0;for(;l!==i;)f+=r[l++],l%=e;if(i=(i+1)%e,i===a&&(a=(a+1)%e),u-o{o=i,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),s=t-o;s>=i?a(e,t):(r=e,n||(n=setTimeout((()=>{n=null,a(r)}),i-s)))},()=>r&&a(r)]},Ue=(e,t,r=3)=>{let n=0;const o=Be(50,250);return Ne((r=>{const i=r.loaded,a=r.lengthComputable?r.total:void 0,s=i-n,u=o(s);n=i;e({loaded:i,total:a,progress:a?i/a:void 0,bytes:s,rate:u||void 0,estimated:u&&a&&i<=a?(a-i)/u:void 0,event:r,lengthComputable:null!=a,[t?"download":"upload"]:!0})}),r)},Me=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},De=e=>(...t)=>W.asap((()=>e(...t))),Fe=be.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,be.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(be.origin),be.navigator&&/(msie|trident)/i.test(be.navigator.userAgent)):()=>!0,Ve=be.hasStandardBrowserEnv?{write(e,t,r,n,o,i){const a=[e+"="+encodeURIComponent(t)];W.isNumber(r)&&a.push("expires="+new Date(r).toGMTString()),W.isString(n)&&a.push("path="+n),W.isString(o)&&a.push("domain="+o),!0===i&&a.push("secure"),document.cookie=a.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function qe(e,t){return e&&!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Ke=e=>e instanceof Pe?{...e}:e;function He(e,t){t=t||{};const r={};function n(e,t,r,n){return W.isPlainObject(e)&&W.isPlainObject(t)?W.merge.call({caseless:n},e,t):W.isPlainObject(t)?W.merge({},t):W.isArray(t)?t.slice():t}function o(e,t,r,o){return W.isUndefined(t)?W.isUndefined(e)?void 0:n(void 0,e,0,o):n(e,t,0,o)}function i(e,t){if(!W.isUndefined(t))return n(void 0,t)}function a(e,t){return W.isUndefined(t)?W.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function s(r,o,i){return i in t?n(r,o):i in e?n(void 0,r):void 0}const u={url:i,method:i,data:i,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:s,headers:(e,t,r)=>o(Ke(e),Ke(t),0,!0)};return W.forEach(Object.keys(Object.assign({},e,t)),(function(n){const i=u[n]||o,a=i(e[n],t[n],n);W.isUndefined(a)&&i!==s||(r[n]=a)})),r}const ze=e=>{const t=He({},e);let r,{data:n,withXSRFToken:o,xsrfHeaderName:i,xsrfCookieName:a,headers:s,auth:u}=t;if(t.headers=s=Pe.from(s),t.url=le(qe(t.baseURL,t.url),e.params,e.paramsSerializer),u&&s.set("Authorization","Basic "+btoa((u.username||"")+":"+(u.password?unescape(encodeURIComponent(u.password)):""))),W.isFormData(n))if(be.hasStandardBrowserEnv||be.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(!1!==(r=s.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];s.setContentType([e||"multipart/form-data",...t].join("; "))}if(be.hasStandardBrowserEnv&&(o&&W.isFunction(o)&&(o=o(t)),o||!1!==o&&Fe(t.url))){const e=i&&a&&Ve.read(a);e&&s.set(i,e)}return t},Xe="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const n=ze(e);let o=n.data;const i=Pe.from(n.headers).normalize();let a,s,u,c,l,{responseType:f,onUploadProgress:p,onDownloadProgress:d}=n;function h(){c&&c(),l&&l(),n.cancelToken&&n.cancelToken.unsubscribe(a),n.signal&&n.signal.removeEventListener("abort",a)}let y=new XMLHttpRequest;function m(){if(!y)return;const n=Pe.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders());Le((function(e){t(e),h()}),(function(e){r(e),h()}),{data:f&&"text"!==f&&"json"!==f?y.response:y.responseText,status:y.status,statusText:y.statusText,headers:n,config:e,request:y}),y=null}y.open(n.method.toUpperCase(),n.url,!0),y.timeout=n.timeout,"onloadend"in y?y.onloadend=m:y.onreadystatechange=function(){y&&4===y.readyState&&(0!==y.status||y.responseURL&&0===y.responseURL.indexOf("file:"))&&setTimeout(m)},y.onabort=function(){y&&(r(new J("Request aborted",J.ECONNABORTED,e,y)),y=null)},y.onerror=function(){r(new J("Network Error",J.ERR_NETWORK,e,y)),y=null},y.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const o=n.transitional||pe;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new J(t,o.clarifyTimeoutError?J.ETIMEDOUT:J.ECONNABORTED,e,y)),y=null},void 0===o&&i.setContentType(null),"setRequestHeader"in y&&W.forEach(i.toJSON(),(function(e,t){y.setRequestHeader(t,e)})),W.isUndefined(n.withCredentials)||(y.withCredentials=!!n.withCredentials),f&&"json"!==f&&(y.responseType=n.responseType),d&&([u,l]=Ue(d,!0),y.addEventListener("progress",u)),p&&y.upload&&([s,c]=Ue(p),y.upload.addEventListener("progress",s),y.upload.addEventListener("loadend",c)),(n.cancelToken||n.signal)&&(a=t=>{y&&(r(!t||t.type?new Ie(null,e,y):t),y.abort(),y=null)},n.cancelToken&&n.cancelToken.subscribe(a),n.signal&&(n.signal.aborted?a():n.signal.addEventListener("abort",a)));const v=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);v&&-1===be.protocols.indexOf(v)?r(new J("Unsupported protocol "+v+":",J.ERR_BAD_REQUEST,e)):y.send(o||null)}))},Ge=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const o=function(e){if(!r){r=!0,a();const t=e instanceof Error?e:this.reason;n.abort(t instanceof J?t:new Ie(t instanceof Error?t.message:t))}};let i=t&&setTimeout((()=>{i=null,o(new J(`timeout ${t} of ms exceeded`,J.ETIMEDOUT))}),t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(o):e.removeEventListener("abort",o)})),e=null)};e.forEach((e=>e.addEventListener("abort",o)));const{signal:s}=n;return s.unsubscribe=()=>W.asap(a),s}},We=function*(e,t){let r=e.byteLength;if(!t||r{const o=async function*(e,t){for await(const r of $e(e))yield*We(r,t)}(e,t);let i,a=0,s=e=>{i||(i=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await o.next();if(t)return s(),void e.close();let i=n.byteLength;if(r){let e=a+=i;r(e)}e.enqueue(new Uint8Array(n))}catch(e){throw s(e),e}},cancel:e=>(s(e),o.return())},{highWaterMark:2})},Ye="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Je=Ye&&"function"==typeof ReadableStream,Ze=Ye&&("function"==typeof TextEncoder?(et=new TextEncoder,e=>et.encode(e)):async e=>new Uint8Array(await new Response(e).arrayBuffer()));var et;const tt=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},rt=Je&&tt((()=>{let e=!1;const t=new Request(be.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),nt=Je&&tt((()=>W.isReadableStream(new Response("").body))),ot={stream:nt&&(e=>e.body)};var it;Ye&&(it=new Response,["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!ot[e]&&(ot[e]=W.isFunction(it[e])?t=>t[e]():(t,r)=>{throw new J(`Response type '${e}' is not supported`,J.ERR_NOT_SUPPORT,r)})})));const at=async(e,t)=>{const r=W.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(W.isBlob(e))return e.size;if(W.isSpecCompliantForm(e)){const t=new Request(be.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return W.isArrayBufferView(e)||W.isArrayBuffer(e)?e.byteLength:(W.isURLSearchParams(e)&&(e+=""),W.isString(e)?(await Ze(e)).byteLength:void 0)})(t):r},st={http:null,xhr:Xe,fetch:Ye&&(async e=>{let{url:t,method:r,data:n,signal:o,cancelToken:i,timeout:a,onDownloadProgress:s,onUploadProgress:u,responseType:c,headers:l,withCredentials:f="same-origin",fetchOptions:p}=ze(e);c=c?(c+"").toLowerCase():"text";let d,h=Ge([o,i&&i.toAbortSignal()],a);const y=h&&h.unsubscribe&&(()=>{h.unsubscribe()});let m;try{if(u&&rt&&"get"!==r&&"head"!==r&&0!==(m=await at(l,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(W.isFormData(n)&&(e=r.headers.get("content-type"))&&l.setContentType(e),r.body){const[e,t]=Me(m,Ue(De(u)));n=Qe(r.body,65536,e,t)}}W.isString(f)||(f=f?"include":"omit");const o="credentials"in Request.prototype;d=new Request(t,{...p,signal:h,method:r.toUpperCase(),headers:l.normalize().toJSON(),body:n,duplex:"half",credentials:o?f:void 0});let i=await fetch(d);const a=nt&&("stream"===c||"response"===c);if(nt&&(s||a&&y)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=i[t]}));const t=W.toFiniteNumber(i.headers.get("content-length")),[r,n]=s&&Me(t,Ue(De(s),!0))||[];i=new Response(Qe(i.body,65536,r,(()=>{n&&n(),y&&y()})),e)}c=c||"text";let v=await ot[W.findKey(ot,c)||"text"](i,e);return!a&&y&&y(),await new Promise(((t,r)=>{Le(t,r,{data:v,headers:Pe.from(i.headers),status:i.status,statusText:i.statusText,config:e,request:d})}))}catch(t){if(y&&y(),t&&"TypeError"===t.name&&/fetch/i.test(t.message))throw Object.assign(new J("Network Error",J.ERR_NETWORK,e,d),{cause:t.cause||t});throw J.from(t,t&&t.code,e,d)}})};W.forEach(st,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const ut=e=>`- ${e}`,ct=e=>W.isFunction(e)||null===e||!1===e,lt=e=>{e=W.isArray(e)?e:[e];const{length:t}=e;let r,n;const o={};for(let i=0;i`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));let r=t?e.length>1?"since :\n"+e.map(ut).join("\n"):" "+ut(e[0]):"as no adapter specified";throw new J("There is no suitable adapter to dispatch the request "+r,"ERR_NOT_SUPPORT")}return n};function ft(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Ie(null,e)}function pt(e){ft(e),e.headers=Pe.from(e.headers),e.data=Re.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return lt(e.adapter||Ee.adapter)(e).then((function(t){return ft(e),t.data=Re.call(e,e.transformResponse,t),t.headers=Pe.from(t.headers),t}),(function(t){return je(t)||(ft(e),t&&t.response&&(t.response.data=Re.call(e,e.transformResponse,t.response),t.response.headers=Pe.from(t.response.headers))),Promise.reject(t)}))}const dt="1.7.9",ht={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{ht[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const yt={};ht.transitional=function(e,t,r){function n(e,t){return"[Axios v1.7.9] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,o,i)=>{if(!1===e)throw new J(n(o," has been removed"+(t?" in "+t:"")),J.ERR_DEPRECATED);return t&&!yt[o]&&(yt[o]=!0,console.warn(n(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,o,i)}},ht.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const mt={assertOptions:function(e,t,r){if("object"!=typeof e)throw new J("options must be an object",J.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let o=n.length;for(;o-- >0;){const i=n[o],a=t[i];if(a){const t=e[i],r=void 0===t||a(t,i,e);if(!0!==r)throw new J("option "+i+" must be "+r,J.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new J("Unknown option "+i,J.ERR_BAD_OPTION)}},validators:ht},vt=mt.validators;class gt{constructor(e){this.defaults=e,this.interceptors={request:new fe,response:new fe}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=He(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:o}=t;void 0!==r&&mt.assertOptions(r,{silentJSONParsing:vt.transitional(vt.boolean),forcedJSONParsing:vt.transitional(vt.boolean),clarifyTimeoutError:vt.transitional(vt.boolean)},!1),null!=n&&(W.isFunction(n)?t.paramsSerializer={serialize:n}:mt.assertOptions(n,{encode:vt.function,serialize:vt.function},!0)),mt.assertOptions(t,{baseUrl:vt.spelling("baseURL"),withXsrfToken:vt.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=o&&W.merge(o.common,o[t.method]);o&&W.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete o[e]})),t.headers=Pe.concat(i,o);const a=[];let s=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(s=s&&e.synchronous,a.unshift(e.fulfilled,e.rejected))}));const u=[];let c;this.interceptors.response.forEach((function(e){u.push(e.fulfilled,e.rejected)}));let l,f=0;if(!s){const e=[pt.bind(this),void 0];for(e.unshift.apply(e,a),e.push.apply(e,u),l=e.length,c=Promise.resolve(t);f{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,o){r.reason||(r.reason=new Ie(e,n,o),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new wt((function(t){e=t})),cancel:e}}}const St=wt;const Et={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Et).forEach((([e,t])=>{Et[t]=e}));const _t=Et;const kt=function e(t){const r=new bt(t),n=o(bt.prototype.request,r);return W.extend(n,bt.prototype,r,{allOwnKeys:!0}),W.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(He(t,r))},n}(Ee);kt.Axios=bt,kt.CanceledError=Ie,kt.CancelToken=St,kt.isCancel=je,kt.VERSION=dt,kt.toFormData=oe,kt.AxiosError=J,kt.Cancel=kt.CanceledError,kt.all=function(e){return Promise.all(e)},kt.spread=function(e){return function(t){return e.apply(null,t)}},kt.isAxiosError=function(e){return W.isObject(e)&&!0===e.isAxiosError},kt.mergeConfig=He,kt.AxiosHeaders=Pe,kt.formToJSON=e=>we(W.isHTMLForm(e)?new FormData(e):e),kt.getAdapter=lt,kt.HttpStatusCode=_t,kt.default=kt;var Tt=kt,Ot=kt.create},9983:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rl,ok:()=>c});a=function e(t){var r,n=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.promise=new Promise((function(e){r=e})),t((function(e){n.reason=e,r()}))},(s=[{key:"throwIfRequested",value:function(){if(this.reason)throw new Error(this.reason)}}])&&o(a.prototype,s),u&&o(a,u),Object.defineProperty(a,"prototype",{writable:!1});var a,s,u,c,l,f=r(6121);c=f.axiosClient,l=f.create},4356:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AccountRequiresMemoError:()=>n.Cu,BadRequestError:()=>n.v7,BadResponseError:()=>n.nS,Config:()=>o.T,Federation:()=>s,Friendbot:()=>c,Horizon:()=>l,NetworkError:()=>n.Dr,NotFoundError:()=>n.m_,StellarToml:()=>a,Utils:()=>i.A,WebAuth:()=>u,contract:()=>p,default:()=>y,rpc:()=>f});var n=r(5976),o=r(8732),i=r(3121),a=r(3898),s=r(7600),u=r(5479),c=r(8242),l=r(8733),f=r(3496),p=r(6299),d=r(356),h={};for(const e in d)["default","Config","Utils","StellarToml","Federation","WebAuth","Friendbot","Horizon","rpc","contract","AccountRequiresMemoError","BadRequestError","BadResponseError","NetworkError","NotFoundError"].indexOf(e)<0&&(h[e]=()=>d[e]);r.d(t,h);const y=(e=r.hmd(e)).exports;void 0===r.g.__USE_AXIOS__&&(r.g.__USE_AXIOS__=!0),void 0===r.g.__USE_EVENTSOURCE__&&(r.g.__USE_EVENTSOURCE__=!1)},4076:(e,t,r)=>{"use strict";var n;r.d(t,{j:()=>n}),function(e){var t=function(e){return e.SUCCESS="SUCCESS",e.NOT_FOUND="NOT_FOUND",e.FAILED="FAILED",e}({});function r(e){return"transactionData"in e}e.GetTransactionStatus=t,e.isSimulationError=function(e){return"error"in e},e.isSimulationSuccess=r,e.isSimulationRestore=function(e){return r(e)&&"restorePreamble"in e&&!!e.restorePreamble.transactionData},e.isSimulationRaw=function(e){return!e._parsed}}(n||(n={}))},3496:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Api:()=>n.j,AxiosClient:()=>s,BasicSleepStrategy:()=>x,Durability:()=>O,LinearSleepStrategy:()=>A,Server:()=>oe,assembleTransaction:()=>d.X,default:()=>ie,parseRawEvents:()=>h.fG,parseRawSimulation:()=>h.jr});var n=r(4076),o=r(4193),i=r.n(o),a=r(356);const s=(0,r(9983).vt)({headers:{"X-Client-Name":"js-soroban-client","X-Client-Version":"13.1.0"}});function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function c(){c=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",l=i.toStringTag||"@@toStringTag";function f(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{f({},"")}catch(e){f=function(e,t,r){return e[t]=r}}function p(e,t,r,n){var i=t&&t.prototype instanceof b?t:b,a=Object.create(i.prototype),s=new C(n||[]);return o(a,"_invoke",{value:A(e,r,s)}),a}function d(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=p;var h="suspendedStart",y="suspendedYield",m="executing",v="completed",g={};function b(){}function w(){}function S(){}var E={};f(E,a,(function(){return this}));var _=Object.getPrototypeOf,k=_&&_(_(I([])));k&&k!==r&&n.call(k,a)&&(E=k);var T=S.prototype=b.prototype=Object.create(E);function O(e){["next","throw","return"].forEach((function(t){f(e,t,(function(e){return this._invoke(t,e)}))}))}function x(e,t){function r(o,i,a,s){var c=d(e[o],e,i);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==u(f)&&n.call(f,"__await")?t.resolve(f.__await).then((function(e){r("next",e,a,s)}),(function(e){r("throw",e,a,s)})):t.resolve(f).then((function(e){l.value=e,a(l)}),(function(e){return r("throw",e,a,s)}))}s(c.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function A(t,r,n){var o=h;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=P(s,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=m;var c=d(t,r,n);if("normal"===c.type){if(o=n.done?v:y,c.arg===g)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=v,n.method="throw",n.arg=c.arg)}}}function P(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,P(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=d(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function R(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function j(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(R,this),this.reset(!0)}function I(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),j(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:I(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function l(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function f(e,t){return p.apply(this,arguments)}function p(){var e;return e=c().mark((function e(t,r){var n,o,i,a=arguments;return c().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=a.length>2&&void 0!==a[2]?a[2]:null,e.next=3,s.post(t,{jsonrpc:"2.0",id:1,method:r,params:n});case 3:if(o=e.sent,u=o.data,c="error",!u.hasOwnProperty(c)){e.next=8;break}throw o.data.error;case 8:return e.abrupt("return",null===(i=o.data)||void 0===i?void 0:i.result);case 9:case"end":return e.stop()}var u,c}),e)})),p=function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){l(i,n,o,a,s,"next",e)}function s(e){l(i,n,o,a,s,"throw",e)}a(void 0)}))},p.apply(this,arguments)}var d=r(8680),h=r(784),y=r(3121),m=r(8287).Buffer;function v(e){return v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},v(e)}function g(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function b(e){for(var t=1;t=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),j(r),m}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:I(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),m}},t}function E(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function _(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){E(i,n,o,a,s,"next",e)}function s(e){E(i,n,o,a,s,"throw",e)}a(void 0)}))}}function k(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:{};if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.serverURL=i()(t),r.headers&&0!==Object.keys(r.headers).length&&s.interceptors.request.use((function(e){return e.headers=Object.assign(e.headers,r.headers),e})),"https"!==this.serverURL.protocol()&&!r.allowHttp)throw new Error("Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set")},j=[{key:"getAccount",value:(ne=_(S().mark((function e(t){var r,n,o;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=a.xdr.LedgerKey.account(new a.xdr.LedgerKeyAccount({accountId:a.Keypair.fromPublicKey(t).xdrPublicKey()})),e.next=3,this.getLedgerEntries(r);case 3:if(0!==(n=e.sent).entries.length){e.next=6;break}return e.abrupt("return",Promise.reject({code:404,message:"Account not found: ".concat(t)}));case 6:return o=n.entries[0].val.account(),e.abrupt("return",new a.Account(t,o.seqNum().toString()));case 8:case"end":return e.stop()}}),e,this)}))),function(e){return ne.apply(this,arguments)})},{key:"getHealth",value:(re=_(S().mark((function e(){return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",f(this.serverURL.toString(),"getHealth"));case 1:case"end":return e.stop()}}),e,this)}))),function(){return re.apply(this,arguments)})},{key:"getContractData",value:(te=_(S().mark((function e(t,r){var n,o,i,s,u=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=u.length>2&&void 0!==u[2]?u[2]:O.Persistent,"string"!=typeof t){e.next=5;break}o=new a.Contract(t).address().toScAddress(),e.next=14;break;case 5:if(!(t instanceof a.Address)){e.next=9;break}o=t.toScAddress(),e.next=14;break;case 9:if(!(t instanceof a.Contract)){e.next=13;break}o=t.address().toScAddress(),e.next=14;break;case 13:throw new TypeError("unknown contract type: ".concat(t));case 14:e.t0=n,e.next=e.t0===O.Temporary?17:e.t0===O.Persistent?19:21;break;case 17:return i=a.xdr.ContractDataDurability.temporary(),e.abrupt("break",22);case 19:return i=a.xdr.ContractDataDurability.persistent(),e.abrupt("break",22);case 21:throw new TypeError("invalid durability: ".concat(n));case 22:return s=a.xdr.LedgerKey.contractData(new a.xdr.LedgerKeyContractData({key:r,contract:o,durability:i})),e.abrupt("return",this.getLedgerEntries(s).then((function(e){return 0===e.entries.length?Promise.reject({code:404,message:"Contract data not found. Contract: ".concat(a.Address.fromScAddress(o).toString(),", Key: ").concat(r.toXDR("base64"),", Durability: ").concat(n)}):e.entries[0]})));case 24:case"end":return e.stop()}}),e,this)}))),function(e,t){return te.apply(this,arguments)})},{key:"getContractWasmByContractId",value:(ee=_(S().mark((function e(t){var r,n,o,i;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=new a.Contract(t).getFootprint(),e.next=3,this.getLedgerEntries(n);case 3:if((o=e.sent).entries.length&&null!==(r=o.entries[0])&&void 0!==r&&r.val){e.next=6;break}return e.abrupt("return",Promise.reject({code:404,message:"Could not obtain contract hash from server"}));case 6:return i=o.entries[0].val.contractData().val().instance().executable().wasmHash(),e.abrupt("return",this.getContractWasmByHash(i));case 8:case"end":return e.stop()}}),e,this)}))),function(e){return ee.apply(this,arguments)})},{key:"getContractWasmByHash",value:(Z=_(S().mark((function e(t){var r,n,o,i,s,u,c=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=c.length>1&&void 0!==c[1]?c[1]:void 0,o="string"==typeof t?m.from(t,n):t,i=a.xdr.LedgerKey.contractCode(new a.xdr.LedgerKeyContractCode({hash:o})),e.next=5,this.getLedgerEntries(i);case 5:if((s=e.sent).entries.length&&null!==(r=s.entries[0])&&void 0!==r&&r.val){e.next=8;break}return e.abrupt("return",Promise.reject({code:404,message:"Could not obtain contract wasm from server"}));case 8:return u=s.entries[0].val.contractCode().code(),e.abrupt("return",u);case 10:case"end":return e.stop()}}),e,this)}))),function(e){return Z.apply(this,arguments)})},{key:"getLedgerEntries",value:(J=_(S().mark((function e(){var t=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this._getLedgerEntries.apply(this,t).then(h.$D));case 1:case"end":return e.stop()}}),e,this)}))),function(){return J.apply(this,arguments)})},{key:"_getLedgerEntries",value:(Y=_(S().mark((function e(){var t,r,n,o=arguments;return S().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(t=o.length,r=new Array(t),n=0;n{"use strict";r.d(t,{$D:()=>d,Af:()=>c,WC:()=>l,fG:()=>p,jr:()=>h,tR:()=>f});var n=r(356),o=r(4076);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function s(e){for(var t=1;t0&&{diagnosticEvents:r.map((function(e){return n.xdr.DiagnosticEvent.fromXDR(e,"base64")}))}),{},{errorResult:n.xdr.TransactionResult.fromXDR(t,"base64")}):s({},e)}function l(e){var t,r=n.xdr.TransactionMeta.fromXDR(e.resultMetaXdr,"base64"),o={ledger:e.ledger,createdAt:e.createdAt,applicationOrder:e.applicationOrder,feeBump:e.feeBump,envelopeXdr:n.xdr.TransactionEnvelope.fromXDR(e.envelopeXdr,"base64"),resultXdr:n.xdr.TransactionResult.fromXDR(e.resultXdr,"base64"),resultMetaXdr:r};3===r.switch()&&null!==r.v3().sorobanMeta()&&(o.returnValue=null===(t=r.v3().sorobanMeta())||void 0===t?void 0:t.returnValue());return"diagnosticEventsXdr"in e&&e.diagnosticEventsXdr&&(o.diagnosticEventsXdr=e.diagnosticEventsXdr.map((function(e){return n.xdr.DiagnosticEvent.fromXDR(e,"base64")}))),o}function f(e){return s({status:e.status,txHash:e.txHash},l(e))}function p(e){var t;return{latestLedger:e.latestLedger,cursor:e.cursor,events:(null!==(t=e.events)&&void 0!==t?t:[]).map((function(e){var t=s({},e);return delete t.contractId,s(s(s({},t),""!==e.contractId&&{contractId:new n.Contract(e.contractId)}),{},{topic:e.topic.map((function(e){return n.xdr.ScVal.fromXDR(e,"base64")})),value:n.xdr.ScVal.fromXDR(e.value,"base64")})}))}}function d(e){var t;return{latestLedger:e.latestLedger,entries:(null!==(t=e.entries)&&void 0!==t?t:[]).map((function(e){if(!e.key||!e.xdr)throw new TypeError("invalid ledger entry: ".concat(JSON.stringify(e)));return s({lastModifiedLedgerSeq:e.lastModifiedLedgerSeq,key:n.xdr.LedgerKey.fromXDR(e.key,"base64"),val:n.xdr.LedgerEntryData.fromXDR(e.xdr,"base64")},void 0!==e.liveUntilLedgerSeq&&{liveUntilLedgerSeq:e.liveUntilLedgerSeq})}))}}function h(e){var t,r;if(!o.j.isSimulationRaw(e))return e;var i={_parsed:!0,id:e.id,latestLedger:e.latestLedger,events:null!==(t=null===(r=e.events)||void 0===r?void 0:r.map((function(e){return n.xdr.DiagnosticEvent.fromXDR(e,"base64")})))&&void 0!==t?t:[]};return"string"==typeof e.error?s(s({},i),{},{error:e.error}):function(e,t){var r,o,i,a,u,c=s(s(s({},t),{},{transactionData:new n.SorobanDataBuilder(e.transactionData),minResourceFee:e.minResourceFee},null!==(r=null===(o=e.results)||void 0===o?void 0:o.length)&&void 0!==r&&r&&{result:e.results.map((function(e){var t;return{auth:(null!==(t=e.auth)&&void 0!==t?t:[]).map((function(e){return n.xdr.SorobanAuthorizationEntry.fromXDR(e,"base64")})),retval:e.xdr?n.xdr.ScVal.fromXDR(e.xdr,"base64"):n.xdr.ScVal.scvVoid()}}))[0]}),null!==(i=null===(a=e.stateChanges)||void 0===a?void 0:a.length)&&void 0!==i&&i&&{stateChanges:null===(u=e.stateChanges)||void 0===u?void 0:u.map((function(e){return{type:e.type,key:n.xdr.LedgerKey.fromXDR(e.key,"base64"),before:e.before?n.xdr.LedgerEntry.fromXDR(e.before,"base64"):null,after:e.after?n.xdr.LedgerEntry.fromXDR(e.after,"base64"):null}}))});return e.restorePreamble&&""!==e.restorePreamble.transactionData?s(s({},c),{},{restorePreamble:{minResourceFee:e.restorePreamble.minResourceFee,transactionData:new n.SorobanDataBuilder(e.restorePreamble.transactionData)}}):c}(e,i)}},8680:(e,t,r)=>{"use strict";r.d(t,{X:()=>a});var n=r(356),o=r(4076),i=r(784);function a(e,t){if("innerTransaction"in e)return a(e.innerTransaction,t);if(!function(e){if(1!==e.operations.length)return!1;switch(e.operations[0].type){case"invokeHostFunction":case"extendFootprintTtl":case"restoreFootprint":return!0;default:return!1}}(e))throw new TypeError("unsupported transaction: must contain exactly one invokeHostFunction, extendFootprintTtl, or restoreFootprint operation");var r=(0,i.jr)(t);if(!o.j.isSimulationSuccess(r))throw new Error("simulation incorrect: ".concat(JSON.stringify(r)));var s=parseInt(e.fee)||0,u=parseInt(r.minResourceFee)||0,c=n.TransactionBuilder.cloneFrom(e,{fee:(s+u).toString(),sorobanData:r.transactionData.build(),networkPassphrase:e.networkPassphrase});if("invokeHostFunction"===e.operations[0].type){var l;c.clearOperations();var f=e.operations[0],p=null!==(l=f.auth)&&void 0!==l?l:[];c.addOperation(n.Operation.invokeHostFunction({source:f.source,func:f.func,auth:p.length>0?p:r.result.auth}))}return c}},3898:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Api:()=>{},Resolver:()=>b,STELLAR_TOML_MAX_SIZE:()=>v});var n=r(1293),o=r.n(n),i=r(9983),a=r(8732);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(){u=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(e,t,r){e[t]=r.value},i="function"==typeof Symbol?Symbol:{},a=i.iterator||"@@iterator",c=i.asyncIterator||"@@asyncIterator",l=i.toStringTag||"@@toStringTag";function f(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{f({},"")}catch(e){f=function(e,t,r){return e[t]=r}}function p(e,t,r,n){var i=t&&t.prototype instanceof b?t:b,a=Object.create(i.prototype),s=new C(n||[]);return o(a,"_invoke",{value:A(e,r,s)}),a}function d(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=p;var h="suspendedStart",y="suspendedYield",m="executing",v="completed",g={};function b(){}function w(){}function S(){}var E={};f(E,a,(function(){return this}));var _=Object.getPrototypeOf,k=_&&_(_(I([])));k&&k!==r&&n.call(k,a)&&(E=k);var T=S.prototype=b.prototype=Object.create(E);function O(e){["next","throw","return"].forEach((function(t){f(e,t,(function(e){return this._invoke(t,e)}))}))}function x(e,t){function r(o,i,a,u){var c=d(e[o],e,i);if("throw"!==c.type){var l=c.arg,f=l.value;return f&&"object"==s(f)&&n.call(f,"__await")?t.resolve(f.__await).then((function(e){r("next",e,a,u)}),(function(e){r("throw",e,a,u)})):t.resolve(f).then((function(e){l.value=e,a(l)}),(function(e){return r("throw",e,a,u)}))}u(c.arg)}var i;o(this,"_invoke",{value:function(e,n){function o(){return new t((function(t,o){r(e,n,t,o)}))}return i=i?i.then(o,o):o()}})}function A(t,r,n){var o=h;return function(i,a){if(o===m)throw Error("Generator is already running");if(o===v){if("throw"===i)throw a;return{value:e,done:!0}}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var u=P(s,n);if(u){if(u===g)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===h)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=m;var c=d(t,r,n);if("normal"===c.type){if(o=n.done?v:y,c.arg===g)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=v,n.method="throw",n.arg=c.arg)}}}function P(t,r){var n=r.method,o=t.iterator[n];if(o===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,P(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),g;var i=d(o,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var a=i.arg;return a?a.done?(r[t.resultName]=a.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function R(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function j(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(R,this),this.reset(!0)}function I(t){if(t||""===t){var r=t[a];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,i=function r(){for(;++o=0;--i){var a=this.tryEntries[i],s=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(u&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),j(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:I(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}function c(e,t,r,n,o,i,a){try{var s=e[i](a),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function l(e,t){for(var r=0;r1&&void 0!==f[1]?f[1]:{}).allowHttp?a.T.isAllowHttp():n.allowHttp,c=void 0===n.timeout?a.T.getTimeout():n.timeout,l=s?"http":"https",e.abrupt("return",i.ok.get("".concat(l,"://").concat(t,"/.well-known/stellar.toml"),{maxRedirects:null!==(r=n.allowedRedirects)&&void 0!==r?r:0,maxContentLength:v,cancelToken:c?new g((function(e){return setTimeout((function(){return e("timeout of ".concat(c,"ms exceeded"))}),c)})):void 0,timeout:c}).then((function(e){try{var t=o().parse(e.data);return Promise.resolve(t)}catch(e){return Promise.reject(new Error("stellar.toml is invalid - Parsing error on line ".concat(e.line,", column ").concat(e.column,": ").concat(e.message)))}})).catch((function(e){throw e.message.match(/^maxContentLength size/)?new Error("stellar.toml file exceeds allowed size of ".concat(v)):e})));case 5:case"end":return e.stop()}}),e)})),m=function(){var e=this,t=arguments;return new Promise((function(r,n){var o=y.apply(e,t);function i(e){c(o,r,n,i,a,"next",e)}function a(e){c(o,r,n,i,a,"throw",e)}i(void 0)}))},function(e){return m.apply(this,arguments)})}],d&&l(p.prototype,d),h&&l(p,h),Object.defineProperty(p,"prototype",{writable:!1}),p)},3121:(e,t,r)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e,t){for(var r=0;rc});var a,s,u,c=(a=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},u=[{key:"validateTimebounds",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!e.timeBounds)return!1;var r=Math.floor(Date.now()/1e3),n=e.timeBounds,o=n.minTime,i=n.maxTime;return r>=Number.parseInt(o,10)-t&&r<=Number.parseInt(i,10)+t}},{key:"sleep",value:function(e){return new Promise((function(t){return setTimeout(t,e)}))}}],(s=null)&&o(a.prototype,s),u&&o(a,u),Object.defineProperty(a,"prototype",{writable:!1}),a)},5479:(e,t,r)=>{"use strict";r.r(t),r.d(t,{InvalidChallengeError:()=>y,buildChallengeTx:()=>k,gatherTxSigners:()=>P,readChallengeTx:()=>T,verifyChallengeTxSigners:()=>x,verifyChallengeTxThreshold:()=>O,verifyTxSignedBy:()=>A});var n=r(3209),o=r.n(n),i=r(356),a=r(3121);function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){for(var r=0;r=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,i=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw i}}}}function b(e){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},b(e)}function w(e){return function(e){if(Array.isArray(e))return e}(e)||_(e)||S(e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function S(e,t){if(e){if("string"==typeof e)return E(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?E(e,t):void 0}}function E(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r3&&void 0!==arguments[3]?arguments[3]:300,a=arguments.length>4?arguments[4]:void 0,s=arguments.length>5?arguments[5]:void 0,u=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,c=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null,l=arguments.length>8&&void 0!==arguments[8]?arguments[8]:null;if(t.startsWith("M")&&u)throw Error("memo cannot be used if clientAccountID is a muxed account");var f=new i.Account(e.publicKey(),"-1"),p=Math.floor(Date.now()/1e3),d=o()(48).toString("base64"),h=new i.TransactionBuilder(f,{fee:i.BASE_FEE,networkPassphrase:a,timebounds:{minTime:p,maxTime:p+n}}).addOperation(i.Operation.manageData({name:"".concat(r," auth"),value:d,source:t})).addOperation(i.Operation.manageData({name:"web_auth_domain",value:s,source:f.accountId()}));if(c){if(!l)throw Error("clientSigningKey is required if clientDomain is provided");h.addOperation(i.Operation.manageData({name:"client_domain",value:c,source:l}))}u&&h.addMemo(i.Memo.id(u));var y=h.build();return y.sign(e),y.toEnvelope().toXDR("base64").toString()}function T(e,t,r,n,o){var s,u;if(t.startsWith("M"))throw Error("Invalid serverAccountID: multiplexed accounts are not supported.");try{u=new i.Transaction(e,r)}catch(t){try{u=new i.FeeBumpTransaction(e,r)}catch(e){throw new y("Invalid challenge: unable to deserialize challengeTx transaction string")}throw new y("Invalid challenge: expected a Transaction but received a FeeBumpTransaction")}if(0!==Number.parseInt(u.sequence,10))throw new y("The transaction sequence number should be zero");if(u.source!==t)throw new y("The transaction source account is not equal to the server's account");if(u.operations.length<1)throw new y("The transaction should contain at least one operation");var c=w(u.operations),l=c[0],f=c.slice(1);if(!l.source)throw new y("The transaction's operation should contain a source account");var p,d=l.source,h=null;if(u.memo.type!==i.MemoNone){if(d.startsWith("M"))throw new y("The transaction has a memo but the client account ID is a muxed account");if(u.memo.type!==i.MemoID)throw new y("The transaction's memo must be of type `id`");h=u.memo.value}if("manageData"!==l.type)throw new y("The transaction's operation type should be 'manageData'");if(u.timeBounds&&Number.parseInt(null===(s=u.timeBounds)||void 0===s?void 0:s.maxTime,10)===i.TimeoutInfinite)throw new y("The transaction requires non-infinite timebounds");if(!a.A.validateTimebounds(u,300))throw new y("The transaction has expired");if(void 0===l.value)throw new y("The transaction's operation values should not be null");if(!l.value)throw new y("The transaction's operation value should not be null");if(48!==m.from(l.value.toString(),"base64").length)throw new y("The transaction's operation value should be a 64 bytes base64 random string");if(!n)throw new y("Invalid homeDomains: a home domain must be provided for verification");if("string"==typeof n)"".concat(n," auth")===l.name&&(p=n);else{if(!Array.isArray(n))throw new y("Invalid homeDomains: homeDomains type is ".concat(b(n)," but should be a string or an array"));p=n.find((function(e){return"".concat(e," auth")===l.name}))}if(!p)throw new y("Invalid homeDomains: the transaction's operation key name does not match the expected home domain");var v,S=g(f);try{for(S.s();!(v=S.n()).done;){var E=v.value;if("manageData"!==E.type)throw new y("The transaction has operations that are not of type 'manageData'");if(E.source!==t&&"client_domain"!==E.name)throw new y("The transaction has operations that are unrecognized");if("web_auth_domain"===E.name){if(void 0===E.value)throw new y("'web_auth_domain' operation value should not be null");if(E.value.compare(m.from(o)))throw new y("'web_auth_domain' operation value does not match ".concat(o))}}}catch(e){S.e(e)}finally{S.f()}if(!A(u,t))throw new y("Transaction not signed by server: '".concat(t,"'"));return{tx:u,clientAccountID:d,matchedHomeDomain:p,memo:h}}function O(e,t,r,n,o,i,a){for(var s=x(e,t,r,o.map((function(e){return e.key})),i,a),u=0,c=function(){var e,t=f[l],r=(null===(e=o.find((function(e){return e.key===t})))||void 0===e?void 0:e.weight)||0;u+=r},l=0,f=s;l{"use strict";var r=function(e,t){return t||(t={}),e.split("").forEach((function(e,r){e in t||(t[e]=r)})),t},n={alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",charmap:{0:14,1:8}};n.charmap=r(n.alphabet,n.charmap);var o={alphabet:"0123456789ABCDEFGHJKMNPQRSTVWXYZ",charmap:{O:0,I:1,L:1}};o.charmap=r(o.alphabet,o.charmap);var i={alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",charmap:{}};function a(e){if(this.buf=[],this.shift=8,this.carry=0,e){switch(e.type){case"rfc4648":this.charmap=t.rfc4648.charmap;break;case"crockford":this.charmap=t.crockford.charmap;break;case"base32hex":this.charmap=t.base32hex.charmap;break;default:throw new Error("invalid type")}e.charmap&&(this.charmap=e.charmap)}}function s(e){if(this.buf="",this.shift=3,this.carry=0,e){switch(e.type){case"rfc4648":this.alphabet=t.rfc4648.alphabet;break;case"crockford":this.alphabet=t.crockford.alphabet;break;case"base32hex":this.alphabet=t.base32hex.alphabet;break;default:throw new Error("invalid type")}e.alphabet?this.alphabet=e.alphabet:e.lc&&(this.alphabet=this.alphabet.toLowerCase())}}i.charmap=r(i.alphabet,i.charmap),a.prototype.charmap=n.charmap,a.prototype.write=function(e){var t=this.charmap,r=this.buf,n=this.shift,o=this.carry;return e.toUpperCase().split("").forEach((function(e){if("="!=e){var i=255&t[e];(n-=5)>0?o|=i<>-n),o=i<<(n+=8)&255):(r.push(o|i),n=8,o=0)}})),this.shift=n,this.carry=o,this},a.prototype.finalize=function(e){return e&&this.write(e),8!==this.shift&&0!==this.carry&&(this.buf.push(this.carry),this.shift=8,this.carry=0),this.buf},s.prototype.alphabet=n.alphabet,s.prototype.write=function(e){var t,r,n,o=this.shift,i=this.carry;for(n=0;n>o,this.buf+=this.alphabet[31&t],o>5&&(t=r>>(o-=5),this.buf+=this.alphabet[31&t]),i=r<<(o=5-o),o=8-o;return this.shift=o,this.carry=i,this},s.prototype.finalize=function(e){return e&&this.write(e),3!==this.shift&&(this.buf+=this.alphabet[31&this.carry],this.shift=3,this.carry=0),this.buf},t.encode=function(e,t){return new s(t).finalize(e)},t.decode=function(e,t){return new a(t).finalize(e)},t.Decoder=a,t.Encoder=s,t.charmap=r,t.crockford=o,t.rfc4648=n,t.base32hex=i},7526:(e,t)=>{"use strict";t.byteLength=function(e){var t=s(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,i=s(e),a=i[0],u=i[1],c=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,u)),l=0,f=u>0?a-4:a;for(r=0;r>16&255,c[l++]=t>>8&255,c[l++]=255&t;2===u&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,c[l++]=255&t);1===u&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t);return c},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],a=16383,s=0,c=n-o;sc?c:s+a));1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return i.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)r[a]=i[a],n[i.charCodeAt(a)]=a;function s(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,n){for(var o,i,a=[],s=t;s>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return a.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},1594:function(e,t,r){var n;!function(){"use strict";var o,i=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,a=Math.ceil,s=Math.floor,u="[BigNumber Error] ",c=u+"Number primitive has more than 15 significant digits: ",l=1e14,f=14,p=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],h=1e7,y=1e9;function m(e){var t=0|e;return e>0||e===t?t:t-1}function v(e){for(var t,r,n=1,o=e.length,i=e[0]+"";nc^r?1:-1;for(s=(u=o.length)<(c=i.length)?u:c,a=0;ai[a]^r?1:-1;return u==c?0:u>c^r?1:-1}function b(e,t,r,n){if(er||e!==s(e))throw Error(u+(n||"Argument")+("number"==typeof e?er?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function w(e){var t=e.c.length-1;return m(e.e/f)==t&&e.c[t]%2!=0}function S(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function E(e,t,r){var n,o;if(t<0){for(o=r+".";++t;o+=r);e=o+e}else if(++t>(n=e.length)){for(o=r,t-=n;--t;o+=r);e+=o}else tU?v.c=v.e=null:e.e=10;d/=10,l++);return void(l>U?v.c=v.e=null:(v.e=l,v.c=[e]))}m=String(e)}else{if(!i.test(m=String(e)))return o(v,m,h);v.s=45==m.charCodeAt(0)?(m=m.slice(1),-1):1}(l=m.indexOf("."))>-1&&(m=m.replace(".","")),(d=m.search(/e/i))>0?(l<0&&(l=d),l+=+m.slice(d+1),m=m.substring(0,d)):l<0&&(l=m.length)}else{if(b(t,2,q.length,"Base"),10==t&&K)return W(v=new H(e),C+v.e+1,I);if(m=String(e),h="number"==typeof e){if(0*e!=0)return o(v,m,h,t);if(v.s=1/e<0?(m=m.slice(1),-1):1,H.DEBUG&&m.replace(/^0\.0*|\./,"").length>15)throw Error(c+e)}else v.s=45===m.charCodeAt(0)?(m=m.slice(1),-1):1;for(r=q.slice(0,t),l=d=0,y=m.length;dl){l=y;continue}}else if(!u&&(m==m.toUpperCase()&&(m=m.toLowerCase())||m==m.toLowerCase()&&(m=m.toUpperCase()))){u=!0,d=-1,l=0;continue}return o(v,String(e),h,t)}h=!1,(l=(m=n(m,t,10,v.s)).indexOf("."))>-1?m=m.replace(".",""):l=m.length}for(d=0;48===m.charCodeAt(d);d++);for(y=m.length;48===m.charCodeAt(--y););if(m=m.slice(d,++y)){if(y-=d,h&&H.DEBUG&&y>15&&(e>p||e!==s(e)))throw Error(c+v.s*e);if((l=l-d-1)>U)v.c=v.e=null;else if(l=B)?S(u,a):E(u,a,"0");else if(i=(e=W(new H(e),t,r)).e,s=(u=v(e.c)).length,1==n||2==n&&(t<=i||i<=L)){for(;ss){if(--t>0)for(u+=".";t--;u+="0");}else if((t+=i-s)>0)for(i+1==s&&(u+=".");t--;u+="0");return e.s<0&&o?"-"+u:u}function X(e,t){for(var r,n,o=1,i=new H(e[0]);o=10;o/=10,n++);return(r=n+r*f-1)>U?e.c=e.e=null:r=10;c/=10,o++);if((i=t-o)<0)i+=f,u=t,p=m[h=0],y=s(p/v[o-u-1]%10);else if((h=a((i+1)/f))>=m.length){if(!n)break e;for(;m.length<=h;m.push(0));p=y=0,o=1,u=(i%=f)-f+1}else{for(p=c=m[h],o=1;c>=10;c/=10,o++);y=(u=(i%=f)-f+o)<0?0:s(p/v[o-u-1]%10)}if(n=n||t<0||null!=m[h+1]||(u<0?p:p%v[o-u-1]),n=r<4?(y||n)&&(0==r||r==(e.s<0?3:2)):y>5||5==y&&(4==r||n||6==r&&(i>0?u>0?p/v[o-u]:0:m[h-1])%10&1||r==(e.s<0?8:7)),t<1||!m[0])return m.length=0,n?(t-=e.e+1,m[0]=v[(f-t%f)%f],e.e=-t||0):m[0]=e.e=0,e;if(0==i?(m.length=h,c=1,h--):(m.length=h+1,c=v[f-i],m[h]=u>0?s(p/v[o-u]%v[u])*c:0),n)for(;;){if(0==h){for(i=1,u=m[0];u>=10;u/=10,i++);for(u=m[0]+=c,c=1;u>=10;u/=10,c++);i!=c&&(e.e++,m[0]==l&&(m[0]=1));break}if(m[h]+=c,m[h]!=l)break;m[h--]=0,c=1}for(i=m.length;0===m[--i];m.pop());}e.e>U?e.c=e.e=null:e.e=B?S(t,r):E(t,r,"0"),e.s<0?"-"+t:t)}return H.clone=e,H.ROUND_UP=0,H.ROUND_DOWN=1,H.ROUND_CEIL=2,H.ROUND_FLOOR=3,H.ROUND_HALF_UP=4,H.ROUND_HALF_DOWN=5,H.ROUND_HALF_EVEN=6,H.ROUND_HALF_CEIL=7,H.ROUND_HALF_FLOOR=8,H.EUCLID=9,H.config=H.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(u+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(b(r=e[t],0,y,t),C=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(b(r=e[t],0,8,t),I=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(b(r[0],-y,0,t),b(r[1],0,y,t),L=r[0],B=r[1]):(b(r,-y,y,t),L=-(B=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)b(r[0],-y,-1,t),b(r[1],1,y,t),N=r[0],U=r[1];else{if(b(r,-y,y,t),!r)throw Error(u+t+" cannot be zero: "+r);N=-(U=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(u+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw M=!r,Error(u+"crypto unavailable");M=r}else M=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(b(r=e[t],0,9,t),D=r),e.hasOwnProperty(t="POW_PRECISION")&&(b(r=e[t],0,y,t),F=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(u+t+" not an object: "+r);V=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(u+t+" invalid: "+r);K="0123456789"==r.slice(0,10),q=r}}return{DECIMAL_PLACES:C,ROUNDING_MODE:I,EXPONENTIAL_AT:[L,B],RANGE:[N,U],CRYPTO:M,MODULO_MODE:D,POW_PRECISION:F,FORMAT:V,ALPHABET:q}},H.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!H.DEBUG)return!0;var t,r,n=e.c,o=e.e,i=e.s;e:if("[object Array]"=={}.toString.call(n)){if((1===i||-1===i)&&o>=-y&&o<=y&&o===s(o)){if(0===n[0]){if(0===o&&1===n.length)return!0;break e}if((t=(o+1)%f)<1&&(t+=f),String(n[0]).length==t){for(t=0;t=l||r!==s(r))break e;if(0!==r)return!0}}}else if(null===n&&null===o&&(null===i||1===i||-1===i))return!0;throw Error(u+"Invalid BigNumber: "+e)},H.maximum=H.max=function(){return X(arguments,-1)},H.minimum=H.min=function(){return X(arguments,1)},H.random=(_=9007199254740992,k=Math.random()*_&2097151?function(){return s(Math.random()*_)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,n,o,i,c=0,l=[],p=new H(j);if(null==e?e=C:b(e,0,y),o=a(e/f),M)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(o*=2));c>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[c]=r[0],t[c+1]=r[1]):(l.push(i%1e14),c+=2);c=o/2}else{if(!crypto.randomBytes)throw M=!1,Error(u+"crypto unavailable");for(t=crypto.randomBytes(o*=7);c=9e15?crypto.randomBytes(7).copy(t,c):(l.push(i%1e14),c+=7);c=o/7}if(!M)for(;c=10;i/=10,c++);cr-1&&(null==a[o+1]&&(a[o+1]=0),a[o+1]+=a[o]/r|0,a[o]%=r)}return a.reverse()}return function(n,o,i,a,s){var u,c,l,f,p,d,h,y,m=n.indexOf("."),g=C,b=I;for(m>=0&&(f=F,F=0,n=n.replace(".",""),d=(y=new H(o)).pow(n.length-m),F=f,y.c=t(E(v(d.c),d.e,"0"),10,i,e),y.e=y.c.length),l=f=(h=t(n,o,i,s?(u=q,e):(u=e,q))).length;0==h[--f];h.pop());if(!h[0])return u.charAt(0);if(m<0?--l:(d.c=h,d.e=l,d.s=a,h=(d=r(d,y,g,b,i)).c,p=d.r,l=d.e),m=h[c=l+g+1],f=i/2,p=p||c<0||null!=h[c+1],p=b<4?(null!=m||p)&&(0==b||b==(d.s<0?3:2)):m>f||m==f&&(4==b||p||6==b&&1&h[c-1]||b==(d.s<0?8:7)),c<1||!h[0])n=p?E(u.charAt(1),-g,u.charAt(0)):u.charAt(0);else{if(h.length=c,p)for(--i;++h[--c]>i;)h[c]=0,c||(++l,h=[1].concat(h));for(f=h.length;!h[--f];);for(m=0,n="";m<=f;n+=u.charAt(h[m++]));n=E(n,l,u.charAt(0))}return n}}(),r=function(){function e(e,t,r){var n,o,i,a,s=0,u=e.length,c=t%h,l=t/h|0;for(e=e.slice();u--;)s=((o=c*(i=e[u]%h)+(n=l*i+(a=e[u]/h|0)*c)%h*h+s)/r|0)+(n/h|0)+l*a,e[u]=o%r;return s&&(e=[s].concat(e)),e}function t(e,t,r,n){var o,i;if(r!=n)i=r>n?1:-1;else for(o=i=0;ot[o]?1:-1;break}return i}function r(e,t,r,n){for(var o=0;r--;)e[r]-=o,o=e[r]1;e.splice(0,1));}return function(n,o,i,a,u){var c,p,d,h,y,v,g,b,w,S,E,_,k,T,O,x,A,P=n.s==o.s?1:-1,R=n.c,j=o.c;if(!(R&&R[0]&&j&&j[0]))return new H(n.s&&o.s&&(R?!j||R[0]!=j[0]:j)?R&&0==R[0]||!j?0*P:P/0:NaN);for(w=(b=new H(P)).c=[],P=i+(p=n.e-o.e)+1,u||(u=l,p=m(n.e/f)-m(o.e/f),P=P/f|0),d=0;j[d]==(R[d]||0);d++);if(j[d]>(R[d]||0)&&p--,P<0)w.push(1),h=!0;else{for(T=R.length,x=j.length,d=0,P+=2,(y=s(u/(j[0]+1)))>1&&(j=e(j,y,u),R=e(R,y,u),x=j.length,T=R.length),k=x,E=(S=R.slice(0,x)).length;E=u/2&&O++;do{if(y=0,(c=t(j,S,x,E))<0){if(_=S[0],x!=E&&(_=_*u+(S[1]||0)),(y=s(_/O))>1)for(y>=u&&(y=u-1),g=(v=e(j,y,u)).length,E=S.length;1==t(v,S,g,E);)y--,r(v,x=10;P/=10,d++);W(b,i+(b.e=d+p*f-1)+1,a,h)}else b.e=p,b.r=+h;return b}}(),T=/^(-?)0([xbo])(?=\w[\w.]*$)/i,O=/^([^.]+)\.$/,x=/^\.([^.]+)$/,A=/^-?(Infinity|NaN)$/,P=/^\s*\+(?=[\w.])|^\s+|\s+$/g,o=function(e,t,r,n){var o,i=r?t:t.replace(P,"");if(A.test(i))e.s=isNaN(i)?null:i<0?-1:1;else{if(!r&&(i=i.replace(T,(function(e,t,r){return o="x"==(r=r.toLowerCase())?16:"b"==r?2:8,n&&n!=o?e:t})),n&&(o=n,i=i.replace(O,"$1").replace(x,"0.$1")),t!=i))return new H(i,o);if(H.DEBUG)throw Error(u+"Not a"+(n?" base "+n:"")+" number: "+t);e.s=null}e.c=e.e=null},R.absoluteValue=R.abs=function(){var e=new H(this);return e.s<0&&(e.s=1),e},R.comparedTo=function(e,t){return g(this,new H(e,t))},R.decimalPlaces=R.dp=function(e,t){var r,n,o,i=this;if(null!=e)return b(e,0,y),null==t?t=I:b(t,0,8),W(new H(i),e+i.e+1,t);if(!(r=i.c))return null;if(n=((o=r.length-1)-m(this.e/f))*f,o=r[o])for(;o%10==0;o/=10,n--);return n<0&&(n=0),n},R.dividedBy=R.div=function(e,t){return r(this,new H(e,t),C,I)},R.dividedToIntegerBy=R.idiv=function(e,t){return r(this,new H(e,t),0,1)},R.exponentiatedBy=R.pow=function(e,t){var r,n,o,i,c,l,p,d,h=this;if((e=new H(e)).c&&!e.isInteger())throw Error(u+"Exponent not an integer: "+$(e));if(null!=t&&(t=new H(t)),c=e.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!e.c||!e.c[0])return d=new H(Math.pow(+$(h),c?e.s*(2-w(e)):+$(e))),t?d.mod(t):d;if(l=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new H(NaN);(n=!l&&h.isInteger()&&t.isInteger())&&(h=h.mod(t))}else{if(e.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||c&&h.c[1]>=24e7:h.c[0]<8e13||c&&h.c[0]<=9999975e7)))return i=h.s<0&&w(e)?-0:0,h.e>-1&&(i=1/i),new H(l?1/i:i);F&&(i=a(F/f+2))}for(c?(r=new H(.5),l&&(e.s=1),p=w(e)):p=(o=Math.abs(+$(e)))%2,d=new H(j);;){if(p){if(!(d=d.times(h)).c)break;i?d.c.length>i&&(d.c.length=i):n&&(d=d.mod(t))}if(o){if(0===(o=s(o/2)))break;p=o%2}else if(W(e=e.times(r),e.e+1,1),e.e>14)p=w(e);else{if(0===(o=+$(e)))break;p=o%2}h=h.times(h),i?h.c&&h.c.length>i&&(h.c.length=i):n&&(h=h.mod(t))}return n?d:(l&&(d=j.div(d)),t?d.mod(t):i?W(d,F,I,undefined):d)},R.integerValue=function(e){var t=new H(this);return null==e?e=I:b(e,0,8),W(t,t.e+1,e)},R.isEqualTo=R.eq=function(e,t){return 0===g(this,new H(e,t))},R.isFinite=function(){return!!this.c},R.isGreaterThan=R.gt=function(e,t){return g(this,new H(e,t))>0},R.isGreaterThanOrEqualTo=R.gte=function(e,t){return 1===(t=g(this,new H(e,t)))||0===t},R.isInteger=function(){return!!this.c&&m(this.e/f)>this.c.length-2},R.isLessThan=R.lt=function(e,t){return g(this,new H(e,t))<0},R.isLessThanOrEqualTo=R.lte=function(e,t){return-1===(t=g(this,new H(e,t)))||0===t},R.isNaN=function(){return!this.s},R.isNegative=function(){return this.s<0},R.isPositive=function(){return this.s>0},R.isZero=function(){return!!this.c&&0==this.c[0]},R.minus=function(e,t){var r,n,o,i,a=this,s=a.s;if(t=(e=new H(e,t)).s,!s||!t)return new H(NaN);if(s!=t)return e.s=-t,a.plus(e);var u=a.e/f,c=e.e/f,p=a.c,d=e.c;if(!u||!c){if(!p||!d)return p?(e.s=-t,e):new H(d?a:NaN);if(!p[0]||!d[0])return d[0]?(e.s=-t,e):new H(p[0]?a:3==I?-0:0)}if(u=m(u),c=m(c),p=p.slice(),s=u-c){for((i=s<0)?(s=-s,o=p):(c=u,o=d),o.reverse(),t=s;t--;o.push(0));o.reverse()}else for(n=(i=(s=p.length)<(t=d.length))?s:t,s=t=0;t0)for(;t--;p[r++]=0);for(t=l-1;n>s;){if(p[--n]=0;){for(r=0,y=_[o]%w,v=_[o]/w|0,i=o+(a=u);i>o;)r=((c=y*(c=E[--a]%w)+(s=v*c+(p=E[a]/w|0)*y)%w*w+g[i]+r)/b|0)+(s/w|0)+v*p,g[i--]=c%b;g[i]=r}return r?++n:g.splice(0,1),G(e,g,n)},R.negated=function(){var e=new H(this);return e.s=-e.s||null,e},R.plus=function(e,t){var r,n=this,o=n.s;if(t=(e=new H(e,t)).s,!o||!t)return new H(NaN);if(o!=t)return e.s=-t,n.minus(e);var i=n.e/f,a=e.e/f,s=n.c,u=e.c;if(!i||!a){if(!s||!u)return new H(o/0);if(!s[0]||!u[0])return u[0]?e:new H(s[0]?n:0*o)}if(i=m(i),a=m(a),s=s.slice(),o=i-a){for(o>0?(a=i,r=u):(o=-o,r=s),r.reverse();o--;r.push(0));r.reverse()}for((o=s.length)-(t=u.length)<0&&(r=u,u=s,s=r,t=o),o=0;t;)o=(s[--t]=s[t]+u[t]+o)/l|0,s[t]=l===s[t]?0:s[t]%l;return o&&(s=[o].concat(s),++a),G(e,s,a)},R.precision=R.sd=function(e,t){var r,n,o,i=this;if(null!=e&&e!==!!e)return b(e,1,y),null==t?t=I:b(t,0,8),W(new H(i),e,t);if(!(r=i.c))return null;if(n=(o=r.length-1)*f+1,o=r[o]){for(;o%10==0;o/=10,n--);for(o=r[0];o>=10;o/=10,n++);}return e&&i.e+1>n&&(n=i.e+1),n},R.shiftedBy=function(e){return b(e,-9007199254740991,p),this.times("1e"+e)},R.squareRoot=R.sqrt=function(){var e,t,n,o,i,a=this,s=a.c,u=a.s,c=a.e,l=C+4,f=new H("0.5");if(1!==u||!s||!s[0])return new H(!u||u<0&&(!s||s[0])?NaN:s?a:1/0);if(0==(u=Math.sqrt(+$(a)))||u==1/0?(((t=v(s)).length+c)%2==0&&(t+="0"),u=Math.sqrt(+t),c=m((c+1)/2)-(c<0||c%2),n=new H(t=u==1/0?"5e"+c:(t=u.toExponential()).slice(0,t.indexOf("e")+1)+c)):n=new H(u+""),n.c[0])for((u=(c=n.e)+l)<3&&(u=0);;)if(i=n,n=f.times(i.plus(r(a,i,l,1))),v(i.c).slice(0,u)===(t=v(n.c)).slice(0,u)){if(n.e0&&y>0){for(i=y%s||s,f=h.substr(0,i);i0&&(f+=l+h.slice(i)),d&&(f="-"+f)}n=p?f+(r.decimalSeparator||"")+((c=+r.fractionGroupSize)?p.replace(new RegExp("\\d{"+c+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):p):f}return(r.prefix||"")+n+(r.suffix||"")},R.toFraction=function(e){var t,n,o,i,a,s,c,l,p,h,y,m,g=this,b=g.c;if(null!=e&&(!(c=new H(e)).isInteger()&&(c.c||1!==c.s)||c.lt(j)))throw Error(u+"Argument "+(c.isInteger()?"out of range: ":"not an integer: ")+$(c));if(!b)return new H(g);for(t=new H(j),p=n=new H(j),o=l=new H(j),m=v(b),a=t.e=m.length-g.e-1,t.c[0]=d[(s=a%f)<0?f+s:s],e=!e||c.comparedTo(t)>0?a>0?t:p:c,s=U,U=1/0,c=new H(m),l.c[0]=0;h=r(c,t,0,1),1!=(i=n.plus(h.times(o))).comparedTo(e);)n=o,o=i,p=l.plus(h.times(i=p)),l=i,t=c.minus(h.times(i=t)),c=i;return i=r(e.minus(n),o,0,1),l=l.plus(i.times(p)),n=n.plus(i.times(o)),l.s=p.s=g.s,y=r(p,o,a*=2,I).minus(g).abs().comparedTo(r(l,n,a,I).minus(g).abs())<1?[p,o]:[l,n],U=s,y},R.toNumber=function(){return+$(this)},R.toPrecision=function(e,t){return null!=e&&b(e,1,y),z(this,e,t,2)},R.toString=function(e){var t,r=this,o=r.s,i=r.e;return null===i?o?(t="Infinity",o<0&&(t="-"+t)):t="NaN":(null==e?t=i<=L||i>=B?S(v(r.c),i):E(v(r.c),i,"0"):10===e&&K?t=E(v((r=W(new H(r),C+i+1,I)).c),r.e,"0"):(b(e,2,q.length,"Base"),t=n(E(v(r.c),i,"0"),10,e,o,!0)),o<0&&r.c[0]&&(t="-"+t)),t},R.valueOf=R.toJSON=function(){return $(this)},R._isBigNumber=!0,null!=t&&H.set(t),H}(),o.default=o.BigNumber=o,void 0===(n=function(){return o}.call(t,r,t,e))||(e.exports=n)}()},8287:(e,t,r)=>{"use strict";const n=r(7526),o=r(251),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=u,t.SlowBuffer=function(e){+e!=e&&(e=0);return u.alloc(+e)},t.INSPECT_MAX_BYTES=50;const a=2147483647;function s(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,u.prototype),t}function u(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return f(e)}return c(e,t,r)}function c(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!u.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|y(e,t);let n=s(r);const o=n.write(e,t);o!==r&&(n=n.slice(0,o));return n}(e,t);if(ArrayBuffer.isView(e))return function(e){if($(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return p(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if($(e,ArrayBuffer)||e&&$(e.buffer,ArrayBuffer))return d(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&($(e,SharedArrayBuffer)||e&&$(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return u.from(n,t,r);const o=function(e){if(u.isBuffer(e)){const t=0|h(e.length),r=s(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||Q(e.length)?s(0):p(e);if("Buffer"===e.type&&Array.isArray(e.data))return p(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return u.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function f(e){return l(e),s(e<0?0:0|h(e))}function p(e){const t=e.length<0?0:0|h(e.length),r=s(t);for(let n=0;n=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function y(e,t){if(u.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||$(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return X(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(o)return n?-1:X(e).length;t=(""+t).toLowerCase(),o=!0}}function m(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return R(this,t,r);case"utf8":case"utf-8":return O(this,t,r);case"ascii":return A(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return T(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function v(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function g(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Q(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,o){let i,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){let n=-1;for(i=r;is&&(r=s-u),i=r;i>=0;i--){let r=!0;for(let n=0;no&&(n=o):n=o;const i=t.length;let a;for(n>i/2&&(n=i/2),a=0;a>8,o=r%256,i.push(o),i.push(n);return i}(t,e.length-r),e,r,n)}function T(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function O(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o239?4:t>223?3:t>191?2:1;if(o+a<=r){let r,n,s,u;switch(a){case 1:t<128&&(i=t);break;case 2:r=e[o+1],128==(192&r)&&(u=(31&t)<<6|63&r,u>127&&(i=u));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(u=(15&t)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:r=e[o+1],n=e[o+2],s=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(u=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,u>65535&&u<1114112&&(i=u))}}null===i?(i=65533,a=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),o+=a}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(u.isBuffer(t)||(t=u.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!u.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},u.byteLength=y,u.prototype._isBuffer=!0,u.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(e+=" ... "),""},i&&(u.prototype[i]=u.prototype.inspect),u.prototype.compare=function(e,t,r,n,o){if($(e,Uint8Array)&&(e=u.from(e,e.offset,e.byteLength)),!u.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let i=(o>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0);const s=Math.min(i,a),c=this.slice(n,o),l=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let i=!1;for(;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":case"latin1":case"binary":return E(this,e,t,r);case"base64":return _(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function A(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;on)&&(r=n);let o="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function I(e,t,r,n,o,i){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function L(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function B(e,t,r,n,o){q(t,n,o,e,r,7);let i=Number(t&BigInt(4294967295));e[r+7]=i,i>>=8,e[r+6]=i,i>>=8,e[r+5]=i,i>>=8,e[r+4]=i;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function N(e,t,r,n,o,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function M(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,0,r,8),o.write(e,t,r,n,52,8),r+8}u.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e+--t],o=1;for(;t>0&&(o*=256);)n+=this[e+--t]*o;return n},u.prototype.readUint8=u.prototype.readUInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||C(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(o)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||C(e,t,this.length);let n=this[e],o=1,i=0;for(;++i=o&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||C(e,t,this.length);let n=t,o=1,i=this[e+--n];for(;n>0&&(o*=256);)i+=this[e+--n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},u.prototype.readInt8=function(e,t){return e>>>=0,t||C(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){e>>>=0,t||C(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||C(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=J((function(e){K(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||H(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||C(e,4,this.length),o.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||C(e,4,this.length),o.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||C(e,8,this.length),o.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||C(e,8,this.length),o.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){I(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=1,i=0;for(this[t]=255&e;++i>>=0,r>>>=0,!n){I(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=r-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigUInt64LE=J((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeBigUInt64BE=J((function(e,t=0){return B(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);I(this,e,t,r,n-1,-n)}let o=0,i=1,a=0;for(this[t]=255&e;++o>>=0,!n){const n=Math.pow(2,8*r-1);I(this,e,t,r,n-1,-n)}let o=r-1,i=1,a=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/i|0)-a&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},u.prototype.writeBigInt64LE=J((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeBigInt64BE=J((function(e,t=0){return B(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return M(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return M(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function q(e,t,r,n,o,i){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(i+1)}${n}`:`>= -(2${n} ** ${8*(i+1)-1}${n}) and < 2 ** ${8*(i+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new D.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){K(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||H(t,e.length-(r+1))}(n,o,i)}function K(e,t){if("number"!=typeof e)throw new D.ERR_INVALID_ARG_TYPE(t,"number",e)}function H(e,t,r){if(Math.floor(e)!==e)throw K(e,r),new D.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new D.ERR_BUFFER_OUT_OF_BOUNDS;throw new D.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}F("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),F("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),F("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=V(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=V(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const z=/[^+/0-9A-Za-z-_]/g;function X(e,t){let r;t=t||1/0;const n=e.length;let o=null;const i=[];for(let a=0;a55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function G(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function W(e,t,r,n){let o;for(o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function $(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Q(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let o=0;o<16;++o)t[n+o]=e[r]+e[o]}return t}();function J(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},6866:e=>{e.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},3144:(e,t,r)=>{"use strict";var n=r(6743),o=r(1002),i=r(76),a=r(7119);e.exports=a||n.call(i,o)},2205:(e,t,r)=>{"use strict";var n=r(6743),o=r(1002),i=r(3144);e.exports=function(){return i(n,o,arguments)}},1002:e=>{"use strict";e.exports=Function.prototype.apply},76:e=>{"use strict";e.exports=Function.prototype.call},3126:(e,t,r)=>{"use strict";var n=r(6743),o=r(9675),i=r(76),a=r(3144);e.exports=function(e){if(e.length<1||"function"!=typeof e[0])throw new o("a function is required");return a(n,i,e)}},7119:e=>{"use strict";e.exports="undefined"!=typeof Reflect&&Reflect&&Reflect.apply},8075:(e,t,r)=>{"use strict";var n=r(453),o=r(487),i=o(n("String.prototype.indexOf"));e.exports=function(e,t){var r=n(e,!!t);return"function"==typeof r&&i(e,".prototype.")>-1?o(r):r}},487:(e,t,r)=>{"use strict";var n=r(6897),o=r(655),i=r(3126),a=r(2205);e.exports=function(e){var t=i(arguments),r=e.length-(arguments.length-1);return n(t,1+(r>0?r:0),!0)},o?o(e.exports,"apply",{value:a}):e.exports.apply=a},6556:(e,t,r)=>{"use strict";var n=r(453),o=r(3126),i=o([n("%String.prototype.indexOf%")]);e.exports=function(e,t){var r=n(e,!!t);return"function"==typeof r&&i(e,".prototype.")>-1?o([r]):r}},41:(e,t,r)=>{"use strict";var n=r(655),o=r(8068),i=r(9675),a=r(5795);e.exports=function(e,t,r){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new i("`obj` must be an object or a function`");if("string"!=typeof t&&"symbol"!=typeof t)throw new i("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new i("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new i("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new i("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new i("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,u=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,l=arguments.length>6&&arguments[6],f=!!a&&a(e,t);if(n)n(e,t,{configurable:null===c&&f?f.configurable:!c,enumerable:null===s&&f?f.enumerable:!s,value:r,writable:null===u&&f?f.writable:!u});else{if(!l&&(s||u||c))throw new o("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");e[t]=r}}},7176:(e,t,r)=>{"use strict";var n=r(3126),o=r(5795),i=[].__proto__===Array.prototype&&o&&o(Object.prototype,"__proto__"),a=Object,s=a.getPrototypeOf;e.exports=i&&"function"==typeof i.get?n([i.get]):"function"==typeof s&&function(e){return s(null==e?e:a(e))}},655:e=>{"use strict";var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch(e){t=!1}e.exports=t},1237:e=>{"use strict";e.exports=EvalError},9383:e=>{"use strict";e.exports=Error},9290:e=>{"use strict";e.exports=RangeError},9538:e=>{"use strict";e.exports=ReferenceError},8068:e=>{"use strict";e.exports=SyntaxError},9675:e=>{"use strict";e.exports=TypeError},5345:e=>{"use strict";e.exports=URIError},9612:e=>{"use strict";e.exports=Object},7007:e=>{"use strict";var t,r="object"==typeof Reflect?Reflect:null,n=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var o=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}e.exports=i,e.exports.once=function(e,t){return new Promise((function(r,n){function o(r){e.removeListener(t,i),n(r)}function i(){"function"==typeof e.removeListener&&e.removeListener("error",o),r([].slice.call(arguments))}y(e,t,i,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&y(e,"error",t,r)}(e,o,{once:!0})}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var a=10;function s(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function u(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,r,n){var o,i,a,c;if(s(r),void 0===(i=e._events)?(i=e._events=Object.create(null),e._eventsCount=0):(void 0!==i.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),i=e._events),a=i[t]),void 0===a)a=i[t]=r,++e._eventsCount;else if("function"==typeof a?a=i[t]=n?[r,a]:[a,r]:n?a.unshift(r):a.push(r),(o=u(e))>0&&a.length>o&&!a.warned){a.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=a.length,c=l,console&&console.warn&&console.warn(c)}return e}function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function f(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},o=l.bind(n);return o.listener=r,n.wrapFn=o,o}function p(e,t,r){var n=e._events;if(void 0===n)return[];var o=n[t];return void 0===o?[]:"function"==typeof o?r?[o.listener||o]:[o]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var u=i[e];if(void 0===u)return!1;if("function"==typeof u)n(u,this,t);else{var c=u.length,l=h(u,c);for(r=0;r=0;i--)if(r[i]===t||r[i].listener===t){a=r[i].listener,o=i;break}if(o<0)return this;0===o?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},i.prototype.listeners=function(e){return p(this,e,!0)},i.prototype.rawListeners=function(e){return p(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):d.call(e,t)},i.prototype.listenerCount=d,i.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},1731:(e,t,r)=>{var n=r(8287).Buffer,o=r(8835).parse,i=r(7007),a=r(1083),s=r(1568),u=r(537),c=["pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","secureProtocol","servername","checkServerIdentity"],l=[239,187,191],f=262144,p=/^(cookie|authorization)$/i;function d(e,t){var r=d.CONNECTING,i=t&&t.headers,u=!1;Object.defineProperty(this,"readyState",{get:function(){return r}}),Object.defineProperty(this,"url",{get:function(){return e}});var m,v=this;function g(t){r!==d.CLOSED&&(r=d.CONNECTING,T("error",new h("error",{message:t})),_&&(e=_,_=null,u=!1),setTimeout((function(){r!==d.CONNECTING||v.connectionInProgress||(v.connectionInProgress=!0,k())}),v.reconnectInterval))}v.reconnectInterval=1e3,v.connectionInProgress=!1;var b="";i&&i["Last-Event-ID"]&&(b=i["Last-Event-ID"],delete i["Last-Event-ID"]);var w=!1,S="",E="",_=null;function k(){var y=o(e),S="https:"===y.protocol;if(y.headers={"Cache-Control":"no-cache",Accept:"text/event-stream"},b&&(y.headers["Last-Event-ID"]=b),i){var E=u?function(e){var t={};for(var r in e)p.test(r)||(t[r]=e[r]);return t}(i):i;for(var x in E){var A=E[x];A&&(y.headers[x]=A)}}if(y.rejectUnauthorized=!(t&&!t.rejectUnauthorized),t&&void 0!==t.createConnection&&(y.createConnection=t.createConnection),t&&t.proxy){var P=o(t.proxy);S="https:"===P.protocol,y.protocol=S?"https:":"http:",y.path=e,y.headers.Host=y.host,y.hostname=P.hostname,y.host=P.host,y.port=P.port}if(t&&t.https)for(var R in t.https)if(-1!==c.indexOf(R)){var j=t.https[R];void 0!==j&&(y[R]=j)}t&&void 0!==t.withCredentials&&(y.withCredentials=t.withCredentials),m=(S?a:s).request(y,(function(t){if(v.connectionInProgress=!1,500===t.statusCode||502===t.statusCode||503===t.statusCode||504===t.statusCode)return T("error",new h("error",{status:t.statusCode,message:t.statusMessage})),void g();if(301===t.statusCode||302===t.statusCode||307===t.statusCode){var o=t.headers.location;if(!o)return void T("error",new h("error",{status:t.statusCode,message:t.statusMessage}));var i=new URL(e).origin,a=new URL(o).origin;return u=i!==a,307===t.statusCode&&(_=e),e=o,void process.nextTick(k)}if(200!==t.statusCode)return T("error",new h("error",{status:t.statusCode,message:t.statusMessage})),v.close();var s,c;r=d.OPEN,t.on("close",(function(){t.removeAllListeners("close"),t.removeAllListeners("end"),g()})),t.on("end",(function(){t.removeAllListeners("close"),t.removeAllListeners("end"),g()})),T("open",new h("open"));var p=0,y=-1,m=0,b=0;t.on("data",(function(e){s?(e.length>s.length-b&&((m=2*s.length+e.length)>f&&(m=s.length+e.length+f),c=n.alloc(m),s.copy(c,0,0,b),s=c),e.copy(s,b),b+=e.length):(function(e){return l.every((function(t,r){return e[r]===t}))}(s=e)&&(s=s.slice(l.length)),b=s.length);for(var t=0,r=b;t0&&(s=s.slice(t,b),b=s.length)}))})),m.on("error",(function(e){v.connectionInProgress=!1,g(e.message)})),m.setNoDelay&&m.setNoDelay(!0),m.end()}function T(){v.listeners(arguments[0]).length>0&&v.emit.apply(v,arguments)}function O(t,r,n,o){if(0===o){if(S.length>0){var i=E||"message";T(i,new y(i,{data:S.slice(0,-1),lastEventId:b,origin:new URL(e).origin})),S=""}E=void 0}else if(n>0){var a=n<0,s=0,u=t.slice(r,r+(a?o:n)).toString();r+=s=a?o:32!==t[r+n+1]?n+1:n+2;var c=o-s,l=t.slice(r,r+c).toString();if("data"===u)S+=l+"\n";else if("event"===u)E=l;else if("id"===u)b=l;else if("retry"===u){var f=parseInt(l,10);Number.isNaN(f)||(v.reconnectInterval=f)}}}k(),this._close=function(){r!==d.CLOSED&&(r=d.CLOSED,m.abort&&m.abort(),m.xhr&&m.xhr.abort&&m.xhr.abort())}}function h(e,t){if(Object.defineProperty(this,"type",{writable:!1,value:e,enumerable:!0}),t)for(var r in t)t.hasOwnProperty(r)&&Object.defineProperty(this,r,{writable:!1,value:t[r],enumerable:!0})}function y(e,t){for(var r in Object.defineProperty(this,"type",{writable:!1,value:e,enumerable:!0}),t)t.hasOwnProperty(r)&&Object.defineProperty(this,r,{writable:!1,value:t[r],enumerable:!0})}e.exports=d,u.inherits(d,i.EventEmitter),d.prototype.constructor=d,["open","error","message"].forEach((function(e){Object.defineProperty(d.prototype,"on"+e,{get:function(){var t=this.listeners(e)[0];return t?t._listener?t._listener:t:void 0},set:function(t){this.removeAllListeners(e),this.addEventListener(e,t)}})})),Object.defineProperty(d,"CONNECTING",{enumerable:!0,value:0}),Object.defineProperty(d,"OPEN",{enumerable:!0,value:1}),Object.defineProperty(d,"CLOSED",{enumerable:!0,value:2}),d.prototype.CONNECTING=0,d.prototype.OPEN=1,d.prototype.CLOSED=2,d.prototype.close=function(){this._close()},d.prototype.addEventListener=function(e,t){"function"==typeof t&&(t._listener=t,this.on(e,t))},d.prototype.dispatchEvent=function(e){if(!e.type)throw new Error("UNSPECIFIED_EVENT_TYPE_ERR");this.emit(e.type,e.detail)},d.prototype.removeEventListener=function(e,t){"function"==typeof t&&(t._listener=void 0,this.removeListener(e,t))}},2682:(e,t,r)=>{"use strict";var n=r(9600),o=Object.prototype.toString,i=Object.prototype.hasOwnProperty;e.exports=function(e,t,r){if(!n(t))throw new TypeError("iterator must be a function");var a;arguments.length>=3&&(a=r),"[object Array]"===o.call(e)?function(e,t,r){for(var n=0,o=e.length;n{"use strict";var t=Object.prototype.toString,r=Math.max,n=function(e,t){for(var r=[],n=0;n{"use strict";var n=r(1734);e.exports=Function.prototype.bind||n},453:(e,t,r)=>{"use strict";var n,o=r(9612),i=r(9383),a=r(1237),s=r(9290),u=r(9538),c=r(8068),l=r(9675),f=r(5345),p=r(1514),d=r(8968),h=r(6188),y=r(8002),m=r(5880),v=Function,g=function(e){try{return v('"use strict"; return ('+e+").constructor;")()}catch(e){}},b=r(5795),w=r(655),S=function(){throw new l},E=b?function(){try{return S}catch(e){try{return b(arguments,"callee").get}catch(e){return S}}}():S,_=r(4039)(),k=r(7176),T="function"==typeof Reflect&&Reflect.getPrototypeOf||o.getPrototypeOf||k,O=r(1002),x=r(76),A={},P="undefined"!=typeof Uint8Array&&T?T(Uint8Array):n,R={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?n:ArrayBuffer,"%ArrayIteratorPrototype%":_&&T?T([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":A,"%AsyncGenerator%":A,"%AsyncGeneratorFunction%":A,"%AsyncIteratorPrototype%":A,"%Atomics%":"undefined"==typeof Atomics?n:Atomics,"%BigInt%":"undefined"==typeof BigInt?n:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?n:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":a,"%Float32Array%":"undefined"==typeof Float32Array?n:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?n:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?n:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":A,"%Int8Array%":"undefined"==typeof Int8Array?n:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?n:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":_&&T?T(T([][Symbol.iterator]())):n,"%JSON%":"object"==typeof JSON?JSON:n,"%Map%":"undefined"==typeof Map?n:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&_&&T?T((new Map)[Symbol.iterator]()):n,"%Math%":Math,"%Number%":Number,"%Object%":o,"%Object.getOwnPropertyDescriptor%":b,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?n:Promise,"%Proxy%":"undefined"==typeof Proxy?n:Proxy,"%RangeError%":s,"%ReferenceError%":u,"%Reflect%":"undefined"==typeof Reflect?n:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?n:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&_&&T?T((new Set)[Symbol.iterator]()):n,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":_&&T?T(""[Symbol.iterator]()):n,"%Symbol%":_?Symbol:n,"%SyntaxError%":c,"%ThrowTypeError%":E,"%TypedArray%":P,"%TypeError%":l,"%Uint8Array%":"undefined"==typeof Uint8Array?n:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?n:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?n:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?n:Uint32Array,"%URIError%":f,"%WeakMap%":"undefined"==typeof WeakMap?n:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?n:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?n:WeakSet,"%Function.prototype.call%":x,"%Function.prototype.apply%":O,"%Object.defineProperty%":w,"%Math.abs%":p,"%Math.floor%":d,"%Math.max%":h,"%Math.min%":y,"%Math.pow%":m};if(T)try{null.error}catch(e){var j=T(T(e));R["%Error.prototype%"]=j}var C=function e(t){var r;if("%AsyncFunction%"===t)r=g("async function () {}");else if("%GeneratorFunction%"===t)r=g("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=g("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var o=e("%AsyncGenerator%");o&&T&&(r=T(o.prototype))}return R[t]=r,r},I={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},L=r(6743),B=r(9957),N=L.call(x,Array.prototype.concat),U=L.call(O,Array.prototype.splice),M=L.call(x,String.prototype.replace),D=L.call(x,String.prototype.slice),F=L.call(x,RegExp.prototype.exec),V=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,q=/\\(\\)?/g,K=function(e,t){var r,n=e;if(B(I,n)&&(n="%"+(r=I[n])[0]+"%"),B(R,n)){var o=R[n];if(o===A&&(o=C(n)),void 0===o&&!t)throw new l("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:o}}throw new c("intrinsic "+e+" does not exist!")};e.exports=function(e,t){if("string"!=typeof e||0===e.length)throw new l("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new l('"allowMissing" argument must be a boolean');if(null===F(/^%?[^%]*%?$/,e))throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=function(e){var t=D(e,0,1),r=D(e,-1);if("%"===t&&"%"!==r)throw new c("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new c("invalid intrinsic syntax, expected opening `%`");var n=[];return M(e,V,(function(e,t,r,o){n[n.length]=r?M(o,q,"$1"):t||e})),n}(e),n=r.length>0?r[0]:"",o=K("%"+n+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(n=u[0],U(r,N([0,1],u)));for(var f=1,p=!0;f=r.length){var m=b(a,d);a=(p=!!m)&&"get"in m&&!("originalValue"in m.get)?m.get:a[d]}else p=B(a,d),a=a[d];p&&!s&&(R[i]=a)}}return a}},6549:e=>{"use strict";e.exports=Object.getOwnPropertyDescriptor},5795:(e,t,r)=>{"use strict";var n=r(6549);if(n)try{n([],"length")}catch(e){n=null}e.exports=n},592:(e,t,r)=>{"use strict";var n=r(655),o=function(){return!!n};o.hasArrayLengthDefineBug=function(){if(!n)return null;try{return 1!==n([],"length",{value:1}).length}catch(e){return!0}},e.exports=o},4039:(e,t,r)=>{"use strict";var n="undefined"!=typeof Symbol&&Symbol,o=r(1333);e.exports=function(){return"function"==typeof n&&("function"==typeof Symbol&&("symbol"==typeof n("foo")&&("symbol"==typeof Symbol("bar")&&o())))}},1333:e=>{"use strict";e.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(var n in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var o=Object.getOwnPropertySymbols(e);if(1!==o.length||o[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(e,t);if(42!==i.value||!0!==i.enumerable)return!1}return!0}},9092:(e,t,r)=>{"use strict";var n=r(1333);e.exports=function(){return n()&&!!Symbol.toStringTag}},9957:(e,t,r)=>{"use strict";var n=Function.prototype.call,o=Object.prototype.hasOwnProperty,i=r(6743);e.exports=i.call(n,o)},1083:(e,t,r)=>{var n=r(1568),o=r(8835),i=e.exports;for(var a in n)n.hasOwnProperty(a)&&(i[a]=n[a]);function s(e){if("string"==typeof e&&(e=o.parse(e)),e.protocol||(e.protocol="https:"),"https:"!==e.protocol)throw new Error('Protocol "'+e.protocol+'" not supported. Expected "https:"');return e}i.request=function(e,t){return e=s(e),n.request.call(this,e,t)},i.get=function(e,t){return e=s(e),n.get.call(this,e,t)}},251:(e,t)=>{t.read=function(e,t,r,n,o){var i,a,s=8*o-n-1,u=(1<>1,l=-7,f=r?o-1:0,p=r?-1:1,d=e[t+f];for(f+=p,i=d&(1<<-l)-1,d>>=-l,l+=s;l>0;i=256*i+e[t+f],f+=p,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=p,l-=8);if(0===i)i=1-c;else{if(i===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),i-=c}return(d?-1:1)*a*Math.pow(2,i-n)},t.write=function(e,t,r,n,o,i){var a,s,u,c=8*i-o-1,l=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,h=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?p/u:p*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=l?(s=0,a=l):a+f>=1?(s=(t*u-1)*Math.pow(2,o),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,o),a=0));o>=8;e[r+d]=255&s,d+=h,s/=256,o-=8);for(a=a<0;e[r+d]=255&a,d+=h,a/=256,c-=8);e[r+d-h]|=128*y}},6698:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},7244:(e,t,r)=>{"use strict";var n=r(9092)(),o=r(6556)("Object.prototype.toString"),i=function(e){return!(n&&e&&"object"==typeof e&&Symbol.toStringTag in e)&&"[object Arguments]"===o(e)},a=function(e){return!!i(e)||null!==e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==o(e)&&"callee"in e&&"[object Function]"===o(e.callee)},s=function(){return i(arguments)}();i.isLegacyArguments=a,e.exports=s?i:a},9600:e=>{"use strict";var t,r,n=Function.prototype.toString,o="object"==typeof Reflect&&null!==Reflect&&Reflect.apply;if("function"==typeof o&&"function"==typeof Object.defineProperty)try{t=Object.defineProperty({},"length",{get:function(){throw r}}),r={},o((function(){throw 42}),null,t)}catch(e){e!==r&&(o=null)}else o=null;var i=/^\s*class\b/,a=function(e){try{var t=n.call(e);return i.test(t)}catch(e){return!1}},s=function(e){try{return!a(e)&&(n.call(e),!0)}catch(e){return!1}},u=Object.prototype.toString,c="function"==typeof Symbol&&!!Symbol.toStringTag,l=!(0 in[,]),f=function(){return!1};if("object"==typeof document){var p=document.all;u.call(p)===u.call(document.all)&&(f=function(e){if((l||!e)&&(void 0===e||"object"==typeof e))try{var t=u.call(e);return("[object HTMLAllCollection]"===t||"[object HTML document.all class]"===t||"[object HTMLCollection]"===t||"[object Object]"===t)&&null==e("")}catch(e){}return!1})}e.exports=o?function(e){if(f(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;try{o(e,null,t)}catch(e){if(e!==r)return!1}return!a(e)&&s(e)}:function(e){if(f(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;if(c)return s(e);if(a(e))return!1;var t=u.call(e);return!("[object Function]"!==t&&"[object GeneratorFunction]"!==t&&!/^\[object HTML/.test(t))&&s(e)}},8184:(e,t,r)=>{"use strict";var n,o=Object.prototype.toString,i=Function.prototype.toString,a=/^\s*(?:function)?\*/,s=r(9092)(),u=Object.getPrototypeOf;e.exports=function(e){if("function"!=typeof e)return!1;if(a.test(i.call(e)))return!0;if(!s)return"[object GeneratorFunction]"===o.call(e);if(!u)return!1;if(void 0===n){var t=function(){if(!s)return!1;try{return Function("return function*() {}")()}catch(e){}}();n=!!t&&u(t)}return u(e)===n}},5680:(e,t,r)=>{"use strict";var n=r(5767);e.exports=function(e){return!!n(e)}},1514:e=>{"use strict";e.exports=Math.abs},8968:e=>{"use strict";e.exports=Math.floor},6188:e=>{"use strict";e.exports=Math.max},8002:e=>{"use strict";e.exports=Math.min},5880:e=>{"use strict";e.exports=Math.pow},8859:(e,t,r)=>{var n="function"==typeof Map&&Map.prototype,o=Object.getOwnPropertyDescriptor&&n?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,i=n&&o&&"function"==typeof o.get?o.get:null,a=n&&Map.prototype.forEach,s="function"==typeof Set&&Set.prototype,u=Object.getOwnPropertyDescriptor&&s?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,c=s&&u&&"function"==typeof u.get?u.get:null,l=s&&Set.prototype.forEach,f="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,p="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,d="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,h=Boolean.prototype.valueOf,y=Object.prototype.toString,m=Function.prototype.toString,v=String.prototype.match,g=String.prototype.slice,b=String.prototype.replace,w=String.prototype.toUpperCase,S=String.prototype.toLowerCase,E=RegExp.prototype.test,_=Array.prototype.concat,k=Array.prototype.join,T=Array.prototype.slice,O=Math.floor,x="function"==typeof BigInt?BigInt.prototype.valueOf:null,A=Object.getOwnPropertySymbols,P="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,R="function"==typeof Symbol&&"object"==typeof Symbol.iterator,j="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===R||"symbol")?Symbol.toStringTag:null,C=Object.prototype.propertyIsEnumerable,I=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function L(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||E.call(/e/,t))return t;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var n=e<0?-O(-e):O(e);if(n!==e){var o=String(n),i=g.call(t,o.length+1);return b.call(o,r,"$&_")+"."+b.call(b.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return b.call(t,r,"$&_")}var B=r(2634),N=B.custom,U=H(N)?N:null,M={__proto__:null,double:'"',single:"'"},D={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};function F(e,t,r){var n=r.quoteStyle||t,o=M[n];return o+e+o}function V(e){return b.call(String(e),/"/g,""")}function q(e){return!("[object Array]"!==G(e)||j&&"object"==typeof e&&j in e)}function K(e){return!("[object RegExp]"!==G(e)||j&&"object"==typeof e&&j in e)}function H(e){if(R)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!P)return!1;try{return P.call(e),!0}catch(e){}return!1}e.exports=function e(t,n,o,s){var u=n||{};if(X(u,"quoteStyle")&&!X(M,u.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(X(u,"maxStringLength")&&("number"==typeof u.maxStringLength?u.maxStringLength<0&&u.maxStringLength!==1/0:null!==u.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var y=!X(u,"customInspect")||u.customInspect;if("boolean"!=typeof y&&"symbol"!==y)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(X(u,"indent")&&null!==u.indent&&"\t"!==u.indent&&!(parseInt(u.indent,10)===u.indent&&u.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(X(u,"numericSeparator")&&"boolean"!=typeof u.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var w=u.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return $(t,u);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var E=String(t);return w?L(t,E):E}if("bigint"==typeof t){var O=String(t)+"n";return w?L(t,O):O}var A=void 0===u.depth?5:u.depth;if(void 0===o&&(o=0),o>=A&&A>0&&"object"==typeof t)return q(t)?"[Array]":"[Object]";var N=function(e,t){var r;if("\t"===e.indent)r="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;r=k.call(Array(e.indent+1)," ")}return{base:r,prev:k.call(Array(t+1),r)}}(u,o);if(void 0===s)s=[];else if(W(s,t)>=0)return"[Circular]";function D(t,r,n){if(r&&(s=T.call(s)).push(r),n){var i={depth:u.depth};return X(u,"quoteStyle")&&(i.quoteStyle=u.quoteStyle),e(t,i,o+1,s)}return e(t,u,o+1,s)}if("function"==typeof t&&!K(t)){var z=function(e){if(e.name)return e.name;var t=v.call(m.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),Q=te(t,D);return"[Function"+(z?": "+z:" (anonymous)")+"]"+(Q.length>0?" { "+k.call(Q,", ")+" }":"")}if(H(t)){var re=R?b.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):P.call(t);return"object"!=typeof t||R?re:Y(re)}if(function(e){if(!e||"object"!=typeof e)return!1;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;return"string"==typeof e.nodeName&&"function"==typeof e.getAttribute}(t)){for(var ne="<"+S.call(String(t.nodeName)),oe=t.attributes||[],ie=0;ie"}if(q(t)){if(0===t.length)return"[]";var ae=te(t,D);return N&&!function(e){for(var t=0;t=0)return!1;return!0}(ae)?"["+ee(ae,N)+"]":"[ "+k.call(ae,", ")+" ]"}if(function(e){return!("[object Error]"!==G(e)||j&&"object"==typeof e&&j in e)}(t)){var se=te(t,D);return"cause"in Error.prototype||!("cause"in t)||C.call(t,"cause")?0===se.length?"["+String(t)+"]":"{ ["+String(t)+"] "+k.call(se,", ")+" }":"{ ["+String(t)+"] "+k.call(_.call("[cause]: "+D(t.cause),se),", ")+" }"}if("object"==typeof t&&y){if(U&&"function"==typeof t[U]&&B)return B(t,{depth:A-o});if("symbol"!==y&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!i||!e||"object"!=typeof e)return!1;try{i.call(e);try{c.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var ue=[];return a&&a.call(t,(function(e,r){ue.push(D(r,t,!0)+" => "+D(e,t))})),Z("Map",i.call(t),ue,N)}if(function(e){if(!c||!e||"object"!=typeof e)return!1;try{c.call(e);try{i.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var ce=[];return l&&l.call(t,(function(e){ce.push(D(e,t))})),Z("Set",c.call(t),ce,N)}if(function(e){if(!f||!e||"object"!=typeof e)return!1;try{f.call(e,f);try{p.call(e,p)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return J("WeakMap");if(function(e){if(!p||!e||"object"!=typeof e)return!1;try{p.call(e,p);try{f.call(e,f)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return J("WeakSet");if(function(e){if(!d||!e||"object"!=typeof e)return!1;try{return d.call(e),!0}catch(e){}return!1}(t))return J("WeakRef");if(function(e){return!("[object Number]"!==G(e)||j&&"object"==typeof e&&j in e)}(t))return Y(D(Number(t)));if(function(e){if(!e||"object"!=typeof e||!x)return!1;try{return x.call(e),!0}catch(e){}return!1}(t))return Y(D(x.call(t)));if(function(e){return!("[object Boolean]"!==G(e)||j&&"object"==typeof e&&j in e)}(t))return Y(h.call(t));if(function(e){return!("[object String]"!==G(e)||j&&"object"==typeof e&&j in e)}(t))return Y(D(String(t)));if("undefined"!=typeof window&&t===window)return"{ [object Window] }";if("undefined"!=typeof globalThis&&t===globalThis||void 0!==r.g&&t===r.g)return"{ [object globalThis] }";if(!function(e){return!("[object Date]"!==G(e)||j&&"object"==typeof e&&j in e)}(t)&&!K(t)){var le=te(t,D),fe=I?I(t)===Object.prototype:t instanceof Object||t.constructor===Object,pe=t instanceof Object?"":"null prototype",de=!fe&&j&&Object(t)===t&&j in t?g.call(G(t),8,-1):pe?"Object":"",he=(fe||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(de||pe?"["+k.call(_.call([],de||[],pe||[]),": ")+"] ":"");return 0===le.length?he+"{}":N?he+"{"+ee(le,N)+"}":he+"{ "+k.call(le,", ")+" }"}return String(t)};var z=Object.prototype.hasOwnProperty||function(e){return e in this};function X(e,t){return z.call(e,t)}function G(e){return y.call(e)}function W(e,t){if(e.indexOf)return e.indexOf(t);for(var r=0,n=e.length;rt.maxStringLength){var r=e.length-t.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return $(g.call(e,0,t.maxStringLength),t)+n}var o=D[t.quoteStyle||"single"];return o.lastIndex=0,F(b.call(b.call(e,o,"\\$1"),/[\x00-\x1f]/g,Q),"single",t)}function Q(e){var t=e.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return r?"\\"+r:"\\x"+(t<16?"0":"")+w.call(t.toString(16))}function Y(e){return"Object("+e+")"}function J(e){return e+" { ? }"}function Z(e,t,r,n){return e+" ("+t+") {"+(n?ee(r,n):k.call(r,", "))+"}"}function ee(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+k.call(e,","+r)+"\n"+t.prev}function te(e,t){var r=q(e),n=[];if(r){n.length=e.length;for(var o=0;o{"use strict";e.exports=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]},4765:e=>{"use strict";var t=String.prototype.replace,r=/%20/g,n="RFC1738",o="RFC3986";e.exports={default:o,formatters:{RFC1738:function(e){return t.call(e,r,"+")},RFC3986:function(e){return String(e)}},RFC1738:n,RFC3986:o}},5373:(e,t,r)=>{"use strict";var n=r(8636),o=r(2642),i=r(4765);e.exports={formats:i,parse:o,stringify:n}},2642:(e,t,r)=>{"use strict";var n=r(7720),o=Object.prototype.hasOwnProperty,i=Array.isArray,a={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:n.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},s=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},u=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},c=function(e,t,r,n){if(e){var i=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,a=/(\[[^[\]]*])/g,s=r.depth>0&&/(\[[^[\]]*])/.exec(i),c=s?i.slice(0,s.index):i,l=[];if(c){if(!r.plainObjects&&o.call(Object.prototype,c)&&!r.allowPrototypes)return;l.push(c)}for(var f=0;r.depth>0&&null!==(s=a.exec(i))&&f=0;--i){var a,s=e[i];if("[]"===s&&r.parseArrays)a=r.allowEmptyArrays&&(""===o||r.strictNullHandling&&null===o)?[]:[].concat(o);else{a=r.plainObjects?{__proto__:null}:{};var c="["===s.charAt(0)&&"]"===s.charAt(s.length-1)?s.slice(1,-1):s,l=r.decodeDotInKeys?c.replace(/%2E/g,"."):c,f=parseInt(l,10);r.parseArrays||""!==l?!isNaN(f)&&s!==l&&String(f)===l&&f>=0&&r.parseArrays&&f<=r.arrayLimit?(a=[])[f]=o:"__proto__"!==l&&(a[l]=o):a={0:o}}o=a}return o}(l,t,r,n)}};e.exports=function(e,t){var r=function(e){if(!e)return a;if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.decodeDotInKeys&&"boolean"!=typeof e.decodeDotInKeys)throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?a.charset:e.charset,r=void 0===e.duplicates?a.duplicates:e.duplicates;if("combine"!==r&&"first"!==r&&"last"!==r)throw new TypeError("The duplicates option must be either combine, first, or last");return{allowDots:void 0===e.allowDots?!0===e.decodeDotInKeys||a.allowDots:!!e.allowDots,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:a.allowEmptyArrays,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:a.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:a.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:a.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:a.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:a.comma,decodeDotInKeys:"boolean"==typeof e.decodeDotInKeys?e.decodeDotInKeys:a.decodeDotInKeys,decoder:"function"==typeof e.decoder?e.decoder:a.decoder,delimiter:"string"==typeof e.delimiter||n.isRegExp(e.delimiter)?e.delimiter:a.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:a.depth,duplicates:r,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:a.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:a.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:a.plainObjects,strictDepth:"boolean"==typeof e.strictDepth?!!e.strictDepth:a.strictDepth,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:a.strictNullHandling}}(t);if(""===e||null==e)return r.plainObjects?{__proto__:null}:{};for(var l="string"==typeof e?function(e,t){var r={__proto__:null},c=t.ignoreQueryPrefix?e.replace(/^\?/,""):e;c=c.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var l,f=t.parameterLimit===1/0?void 0:t.parameterLimit,p=c.split(t.delimiter,f),d=-1,h=t.charset;if(t.charsetSentinel)for(l=0;l-1&&(m=i(m)?[m]:m);var w=o.call(r,y);w&&"combine"===t.duplicates?r[y]=n.combine(r[y],m):w&&"last"!==t.duplicates||(r[y]=m)}return r}(e,r):e,f=r.plainObjects?{__proto__:null}:{},p=Object.keys(l),d=0;d{"use strict";var n=r(920),o=r(7720),i=r(4765),a=Object.prototype.hasOwnProperty,s={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},u=Array.isArray,c=Array.prototype.push,l=function(e,t){c.apply(e,u(t)?t:[t])},f=Date.prototype.toISOString,p=i.default,d={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,commaRoundTrip:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:o.encode,encodeValuesOnly:!1,filter:void 0,format:p,formatter:i.formatters[p],indices:!1,serializeDate:function(e){return f.call(e)},skipNulls:!1,strictNullHandling:!1},h={},y=function e(t,r,i,a,s,c,f,p,y,m,v,g,b,w,S,E,_,k){for(var T,O=t,x=k,A=0,P=!1;void 0!==(x=x.get(h))&&!P;){var R=x.get(t);if(A+=1,void 0!==R){if(R===A)throw new RangeError("Cyclic object value");P=!0}void 0===x.get(h)&&(A=0)}if("function"==typeof m?O=m(r,O):O instanceof Date?O=b(O):"comma"===i&&u(O)&&(O=o.maybeMap(O,(function(e){return e instanceof Date?b(e):e}))),null===O){if(c)return y&&!E?y(r,d.encoder,_,"key",w):r;O=""}if("string"==typeof(T=O)||"number"==typeof T||"boolean"==typeof T||"symbol"==typeof T||"bigint"==typeof T||o.isBuffer(O))return y?[S(E?r:y(r,d.encoder,_,"key",w))+"="+S(y(O,d.encoder,_,"value",w))]:[S(r)+"="+S(String(O))];var j,C=[];if(void 0===O)return C;if("comma"===i&&u(O))E&&y&&(O=o.maybeMap(O,y)),j=[{value:O.length>0?O.join(",")||null:void 0}];else if(u(m))j=m;else{var I=Object.keys(O);j=v?I.sort(v):I}var L=p?String(r).replace(/\./g,"%2E"):String(r),B=a&&u(O)&&1===O.length?L+"[]":L;if(s&&u(O)&&0===O.length)return B+"[]";for(var N=0;N0?S+w:""}},7720:(e,t,r)=>{"use strict";var n=r(4765),o=Object.prototype.hasOwnProperty,i=Array.isArray,a=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),s=function(e,t){for(var r=t&&t.plainObjects?{__proto__:null}:{},n=0;n1;){var t=e.pop(),r=t.obj[t.prop];if(i(r)){for(var n=[],o=0;o=u?s.slice(l,l+u):s,p=[],d=0;d=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||i===n.RFC1738&&(40===h||41===h)?p[p.length]=f.charAt(d):h<128?p[p.length]=a[h]:h<2048?p[p.length]=a[192|h>>6]+a[128|63&h]:h<55296||h>=57344?p[p.length]=a[224|h>>12]+a[128|h>>6&63]+a[128|63&h]:(d+=1,h=65536+((1023&h)<<10|1023&f.charCodeAt(d)),p[p.length]=a[240|h>>18]+a[128|h>>12&63]+a[128|h>>6&63]+a[128|63&h])}c+=p.join("")}return c},isBuffer:function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(i(e)){for(var r=[],n=0;n{"use strict";var n=65536,o=4294967295;var i=r(2861).Buffer,a=r.g.crypto||r.g.msCrypto;a&&a.getRandomValues?e.exports=function(e,t){if(e>o)throw new RangeError("requested too many random bytes");var r=i.allocUnsafe(e);if(e>0)if(e>n)for(var s=0;s{"use strict";var t={};function r(e,r,n){n||(n=Error);var o=function(e){var t,n;function o(t,n,o){return e.call(this,function(e,t,n){return"string"==typeof r?r:r(e,t,n)}(t,n,o))||this}return n=e,(t=o).prototype=Object.create(n.prototype),t.prototype.constructor=t,t.__proto__=n,o}(n);o.prototype.name=n.name,o.prototype.code=e,t[e]=o}function n(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map((function(e){return String(e)})),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:2===r?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}r("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),r("ERR_INVALID_ARG_TYPE",(function(e,t,r){var o,i,a,s;if("string"==typeof t&&(i="not ",t.substr(!a||a<0?0:+a,i.length)===i)?(o="must not be",t=t.replace(/^not /,"")):o="must be",function(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}(e," argument"))s="The ".concat(e," ").concat(o," ").concat(n(t,"type"));else{var u=function(e,t,r){return"number"!=typeof r&&(r=0),!(r+t.length>e.length)&&-1!==e.indexOf(t,r)}(e,".")?"property":"argument";s='The "'.concat(e,'" ').concat(u," ").concat(o," ").concat(n(t,"type"))}return s+=". Received type ".concat(typeof r)}),TypeError),r("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),r("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),r("ERR_STREAM_PREMATURE_CLOSE","Premature close"),r("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),r("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),r("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),r("ERR_STREAM_WRITE_AFTER_END","write after end"),r("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),r("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),r("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),e.exports.F=t},5382:(e,t,r)=>{"use strict";var n=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};e.exports=c;var o=r(5412),i=r(6708);r(6698)(c,o);for(var a=n(i.prototype),s=0;s{"use strict";e.exports=o;var n=r(4610);function o(e){if(!(this instanceof o))return new o(e);n.call(this,e)}r(6698)(o,n),o.prototype._transform=function(e,t,r){r(null,e)}},5412:(e,t,r)=>{"use strict";var n;e.exports=k,k.ReadableState=_;r(7007).EventEmitter;var o=function(e,t){return e.listeners(t).length},i=r(345),a=r(8287).Buffer,s=(void 0!==r.g?r.g:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var u,c=r(9838);u=c&&c.debuglog?c.debuglog("stream"):function(){};var l,f,p,d=r(2726),h=r(5896),y=r(5291).getHighWaterMark,m=r(6048).F,v=m.ERR_INVALID_ARG_TYPE,g=m.ERR_STREAM_PUSH_AFTER_EOF,b=m.ERR_METHOD_NOT_IMPLEMENTED,w=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;r(6698)(k,i);var S=h.errorOrDestroy,E=["error","close","destroy","pause","resume"];function _(e,t,o){n=n||r(5382),e=e||{},"boolean"!=typeof o&&(o=t instanceof n),this.objectMode=!!e.objectMode,o&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=y(this,e,"readableHighWaterMark",o),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==e.emitClose,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(l||(l=r(3141).I),this.decoder=new l(e.encoding),this.encoding=e.encoding)}function k(e){if(n=n||r(5382),!(this instanceof k))return new k(e);var t=this instanceof n;this._readableState=new _(e,this,t),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),i.call(this)}function T(e,t,r,n,o){u("readableAddChunk",t);var i,c=e._readableState;if(null===t)c.reading=!1,function(e,t){if(u("onEofChunk"),t.ended)return;if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,t.sync?P(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,R(e)))}(e,c);else if(o||(i=function(e,t){var r;n=t,a.isBuffer(n)||n instanceof s||"string"==typeof t||void 0===t||e.objectMode||(r=new v("chunk",["string","Buffer","Uint8Array"],t));var n;return r}(c,t)),i)S(e,i);else if(c.objectMode||t&&t.length>0)if("string"==typeof t||c.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=function(e){return a.from(e)}(t)),n)c.endEmitted?S(e,new w):O(e,c,t,!0);else if(c.ended)S(e,new g);else{if(c.destroyed)return!1;c.reading=!1,c.decoder&&!r?(t=c.decoder.write(t),c.objectMode||0!==t.length?O(e,c,t,!1):j(e,c)):O(e,c,t,!1)}else n||(c.reading=!1,j(e,c));return!c.ended&&(c.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=x?e=x:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function P(e){var t=e._readableState;u("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u("emitReadable",t.flowing),t.emittedReadable=!0,process.nextTick(R,e))}function R(e){var t=e._readableState;u("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,N(e)}function j(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(C,e,t))}function C(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function L(e){u("readable nexttick read 0"),e.read(0)}function B(e,t){u("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),N(e),t.flowing&&!t.reading&&e.read(0)}function N(e){var t=e._readableState;for(u("flow",t.flowing);t.flowing&&null!==e.read(););}function U(e,t){return 0===t.length?null:(t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r);var r}function M(e){var t=e._readableState;u("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(D,t,e))}function D(e,t){if(u("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy()}}function F(e,t){for(var r=0,n=e.length;r=t.highWaterMark:t.length>0)||t.ended))return u("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?M(this):P(this),null;if(0===(e=A(e,t))&&t.ended)return 0===t.length&&M(this),null;var n,o=t.needReadable;return u("need readable",o),(0===t.length||t.length-e0?U(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&M(this)),null!==n&&this.emit("data",n),n},k.prototype._read=function(e){S(this,new b("_read()"))},k.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e)}n.pipesCount+=1,u("pipe count=%d opts=%j",n.pipesCount,t);var i=(!t||!1!==t.end)&&e!==process.stdout&&e!==process.stderr?s:y;function a(t,o){u("onunpipe"),t===r&&o&&!1===o.hasUnpiped&&(o.hasUnpiped=!0,u("cleanup"),e.removeListener("close",d),e.removeListener("finish",h),e.removeListener("drain",c),e.removeListener("error",p),e.removeListener("unpipe",a),r.removeListener("end",s),r.removeListener("end",y),r.removeListener("data",f),l=!0,!n.awaitDrain||e._writableState&&!e._writableState.needDrain||c())}function s(){u("onend"),e.end()}n.endEmitted?process.nextTick(i):r.once("end",i),e.on("unpipe",a);var c=function(e){return function(){var t=e._readableState;u("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,N(e))}}(r);e.on("drain",c);var l=!1;function f(t){u("ondata");var o=e.write(t);u("dest.write",o),!1===o&&((1===n.pipesCount&&n.pipes===e||n.pipesCount>1&&-1!==F(n.pipes,e))&&!l&&(u("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function p(t){u("onerror",t),y(),e.removeListener("error",p),0===o(e,"error")&&S(e,t)}function d(){e.removeListener("finish",h),y()}function h(){u("onfinish"),e.removeListener("close",d),y()}function y(){u("unpipe"),r.unpipe(e)}return r.on("data",f),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",p),e.once("close",d),e.once("finish",h),e.emit("pipe",r),n.flowing||(u("pipe resume"),r.resume()),e},k.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r)),this;if(!e){var n=t.pipes,o=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i0,!1!==n.flowing&&this.resume()):"readable"===e&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,u("on readable",n.length,n.reading),n.length?P(this):n.reading||process.nextTick(L,this))),r},k.prototype.addListener=k.prototype.on,k.prototype.removeListener=function(e,t){var r=i.prototype.removeListener.call(this,e,t);return"readable"===e&&process.nextTick(I,this),r},k.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||process.nextTick(I,this),t},k.prototype.resume=function(){var e=this._readableState;return e.flowing||(u("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(B,e,t))}(this,e)),e.paused=!1,this},k.prototype.pause=function(){return u("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(u("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},k.prototype.wrap=function(e){var t=this,r=this._readableState,n=!1;for(var o in e.on("end",(function(){if(u("wrapped end"),r.decoder&&!r.ended){var e=r.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(o){(u("wrapped data"),r.decoder&&(o=r.decoder.write(o)),r.objectMode&&null==o)||(r.objectMode||o&&o.length)&&(t.push(o)||(n=!0,e.pause()))})),e)void 0===this[o]&&"function"==typeof e[o]&&(this[o]=function(t){return function(){return e[t].apply(e,arguments)}}(o));for(var i=0;i{"use strict";e.exports=l;var n=r(6048).F,o=n.ERR_METHOD_NOT_IMPLEMENTED,i=n.ERR_MULTIPLE_CALLBACK,a=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,s=n.ERR_TRANSFORM_WITH_LENGTH_0,u=r(5382);function c(e,t){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(null===n)return this.emit("error",new i);r.writechunk=null,r.writecb=null,null!=t&&this.push(t),n(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length{"use strict";function n(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,r){var n=e.entry;e.entry=null;for(;n;){var o=n.callback;t.pendingcb--,o(r),n=n.next}t.corkedRequestsFree.next=e}(t,e)}}var o;e.exports=k,k.WritableState=_;var i={deprecate:r(4643)},a=r(345),s=r(8287).Buffer,u=(void 0!==r.g?r.g:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var c,l=r(5896),f=r(5291).getHighWaterMark,p=r(6048).F,d=p.ERR_INVALID_ARG_TYPE,h=p.ERR_METHOD_NOT_IMPLEMENTED,y=p.ERR_MULTIPLE_CALLBACK,m=p.ERR_STREAM_CANNOT_PIPE,v=p.ERR_STREAM_DESTROYED,g=p.ERR_STREAM_NULL_VALUES,b=p.ERR_STREAM_WRITE_AFTER_END,w=p.ERR_UNKNOWN_ENCODING,S=l.errorOrDestroy;function E(){}function _(e,t,i){o=o||r(5382),e=e||{},"boolean"!=typeof i&&(i=t instanceof o),this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=f(this,e,"writableHighWaterMark",i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=!1===e.decodeStrings;this.decodeStrings=!a,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,n=r.sync,o=r.writecb;if("function"!=typeof o)throw new y;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,n,o){--t.pendingcb,r?(process.nextTick(o,n),process.nextTick(R,e,t),e._writableState.errorEmitted=!0,S(e,n)):(o(n),e._writableState.errorEmitted=!0,S(e,n),R(e,t))}(e,r,n,t,o);else{var i=A(r)||e.destroyed;i||r.corked||r.bufferProcessing||!r.bufferedRequest||x(e,r),n?process.nextTick(O,e,r,i,o):O(e,r,i,o)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==e.emitClose,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new n(this)}function k(e){var t=this instanceof(o=o||r(5382));if(!t&&!c.call(k,this))return new k(e);this._writableState=new _(e,this,t),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),a.call(this)}function T(e,t,r,n,o,i,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new v("write")):r?e._writev(o,t.onwrite):e._write(o,i,t.onwrite),t.sync=!1}function O(e,t,r,n){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),R(e,t)}function x(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var o=t.bufferedRequestCount,i=new Array(o),a=t.corkedRequestsFree;a.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,T(e,t,!0,t.length,i,"",a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new n(t),t.bufferedRequestCount=0}else{for(;r;){var c=r.chunk,l=r.encoding,f=r.callback;if(T(e,t,!1,t.objectMode?1:c.length,c,l,f),r=r.next,t.bufferedRequestCount--,t.writing)break}null===r&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}function A(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function P(e,t){e._final((function(r){t.pendingcb--,r&&S(e,r),t.prefinished=!0,e.emit("prefinish"),R(e,t)}))}function R(e,t){var r=A(t);if(r&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,process.nextTick(P,e,t)))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var n=e._readableState;(!n||n.autoDestroy&&n.endEmitted)&&e.destroy()}return r}r(6698)(k,a),_.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(_.prototype,"buffer",{get:i.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(c=Function.prototype[Symbol.hasInstance],Object.defineProperty(k,Symbol.hasInstance,{value:function(e){return!!c.call(this,e)||this===k&&(e&&e._writableState instanceof _)}})):c=function(e){return e instanceof this},k.prototype.pipe=function(){S(this,new m)},k.prototype.write=function(e,t,r){var n,o=this._writableState,i=!1,a=!o.objectMode&&(n=e,s.isBuffer(n)||n instanceof u);return a&&!s.isBuffer(e)&&(e=function(e){return s.from(e)}(e)),"function"==typeof t&&(r=t,t=null),a?t="buffer":t||(t=o.defaultEncoding),"function"!=typeof r&&(r=E),o.ending?function(e,t){var r=new b;S(e,r),process.nextTick(t,r)}(this,r):(a||function(e,t,r,n){var o;return null===r?o=new g:"string"==typeof r||t.objectMode||(o=new d("chunk",["string","Buffer"],r)),!o||(S(e,o),process.nextTick(n,o),!1)}(this,o,e,r))&&(o.pendingcb++,i=function(e,t,r,n,o,i){if(!r){var a=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=s.from(t,r));return t}(t,n,o);n!==a&&(r=!0,o="buffer",n=a)}var u=t.objectMode?1:n.length;t.length+=u;var c=t.length-1))throw new w(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(k.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(k.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),k.prototype._write=function(e,t,r){r(new h("_write()"))},k.prototype._writev=null,k.prototype.end=function(e,t,r){var n=this._writableState;return"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||function(e,t,r){t.ending=!0,R(e,t),r&&(t.finished?process.nextTick(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r),this},Object.defineProperty(k.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(k.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),k.prototype.destroy=l.destroy,k.prototype._undestroy=l.undestroy,k.prototype._destroy=function(e,t){t(e)}},2955:(e,t,r)=>{"use strict";var n;function o(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var i=r(6238),a=Symbol("lastResolve"),s=Symbol("lastReject"),u=Symbol("error"),c=Symbol("ended"),l=Symbol("lastPromise"),f=Symbol("handlePromise"),p=Symbol("stream");function d(e,t){return{value:e,done:t}}function h(e){var t=e[a];if(null!==t){var r=e[p].read();null!==r&&(e[l]=null,e[a]=null,e[s]=null,t(d(r,!1)))}}function y(e){process.nextTick(h,e)}var m=Object.getPrototypeOf((function(){})),v=Object.setPrototypeOf((o(n={get stream(){return this[p]},next:function(){var e=this,t=this[u];if(null!==t)return Promise.reject(t);if(this[c])return Promise.resolve(d(void 0,!0));if(this[p].destroyed)return new Promise((function(t,r){process.nextTick((function(){e[u]?r(e[u]):t(d(void 0,!0))}))}));var r,n=this[l];if(n)r=new Promise(function(e,t){return function(r,n){e.then((function(){t[c]?r(d(void 0,!0)):t[f](r,n)}),n)}}(n,this));else{var o=this[p].read();if(null!==o)return Promise.resolve(d(o,!1));r=new Promise(this[f])}return this[l]=r,r}},Symbol.asyncIterator,(function(){return this})),o(n,"return",(function(){var e=this;return new Promise((function(t,r){e[p].destroy(null,(function(e){e?r(e):t(d(void 0,!0))}))}))})),n),m);e.exports=function(e){var t,r=Object.create(v,(o(t={},p,{value:e,writable:!0}),o(t,a,{value:null,writable:!0}),o(t,s,{value:null,writable:!0}),o(t,u,{value:null,writable:!0}),o(t,c,{value:e._readableState.endEmitted,writable:!0}),o(t,f,{value:function(e,t){var n=r[p].read();n?(r[l]=null,r[a]=null,r[s]=null,e(d(n,!1))):(r[a]=e,r[s]=t)},writable:!0}),t));return r[l]=null,i(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=r[s];return null!==t&&(r[l]=null,r[a]=null,r[s]=null,t(e)),void(r[u]=e)}var n=r[a];null!==n&&(r[l]=null,r[a]=null,r[s]=null,n(d(void 0,!0))),r[c]=!0})),e.on("readable",y.bind(null,r)),r}},2726:(e,t,r)=>{"use strict";function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function o(e){for(var t=1;t0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r}},{key:"concat",value:function(e){if(0===this.length)return u.alloc(0);for(var t,r,n,o=u.allocUnsafe(e>>>0),i=this.head,a=0;i;)t=i.data,r=o,n=a,u.prototype.copy.call(t,r,n),a+=i.data.length,i=i.next;return o}},{key:"consume",value:function(e,t){var r;return eo.length?o.length:e;if(i===o.length?n+=o:n+=o.slice(0,e),0==(e-=i)){i===o.length?(++r,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=o.slice(i));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(e){var t=u.allocUnsafe(e),r=this.head,n=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var o=r.data,i=e>o.length?o.length:e;if(o.copy(t,t.length-e,0,i),0==(e-=i)){i===o.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=o.slice(i));break}++n}return this.length-=n,t}},{key:l,value:function(e,t){return c(this,o(o({},t),{},{depth:0,customInspect:!1}))}}])&&a(t.prototype,r),n&&a(t,n),Object.defineProperty(t,"prototype",{writable:!1}),e}()},5896:e=>{"use strict";function t(e,t){n(e,t),r(e)}function r(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function n(e,t){e.emit("error",t)}e.exports={destroy:function(e,o){var i=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(o?o(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(n,this,e)):process.nextTick(n,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,(function(e){!o&&e?i._writableState?i._writableState.errorEmitted?process.nextTick(r,i):(i._writableState.errorEmitted=!0,process.nextTick(t,i,e)):process.nextTick(t,i,e):o?(process.nextTick(r,i),o(e)):process.nextTick(r,i)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var r=e._readableState,n=e._writableState;r&&r.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}}},6238:(e,t,r)=>{"use strict";var n=r(6048).F.ERR_STREAM_PREMATURE_CLOSE;function o(){}e.exports=function e(t,r,i){if("function"==typeof r)return e(t,null,r);r||(r={}),i=function(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,n=new Array(r),o=0;o{e.exports=function(){throw new Error("Readable.from is not available in the browser")}},7758:(e,t,r)=>{"use strict";var n;var o=r(6048).F,i=o.ERR_MISSING_ARGS,a=o.ERR_STREAM_DESTROYED;function s(e){if(e)throw e}function u(e){e()}function c(e,t){return e.pipe(t)}e.exports=function(){for(var e=arguments.length,t=new Array(e),o=0;o0,(function(e){l||(l=e),e&&p.forEach(u),i||(p.forEach(u),f(l))}))}));return t.reduce(c)}},5291:(e,t,r)=>{"use strict";var n=r(6048).F.ERR_INVALID_OPT_VALUE;e.exports={getHighWaterMark:function(e,t,r,o){var i=function(e,t,r){return null!=e.highWaterMark?e.highWaterMark:t?e[r]:null}(t,o,r);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new n(o?r:"highWaterMark",i);return Math.floor(i)}return e.objectMode?16:16384}}},345:(e,t,r)=>{e.exports=r(7007).EventEmitter},8399:(e,t,r)=>{(t=e.exports=r(5412)).Stream=t,t.Readable=t,t.Writable=r(6708),t.Duplex=r(5382),t.Transform=r(4610),t.PassThrough=r(3600),t.finished=r(6238),t.pipeline=r(7758)},2861:(e,t,r)=>{var n=r(8287),o=n.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return o(e,t,r)}o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=a),a.prototype=Object.create(o.prototype),i(o,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=o(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},6897:(e,t,r)=>{"use strict";var n=r(453),o=r(41),i=r(592)(),a=r(5795),s=r(9675),u=n("%Math.floor%");e.exports=function(e,t){if("function"!=typeof e)throw new s("`fn` is not a function");if("number"!=typeof t||t<0||t>4294967295||u(t)!==t)throw new s("`length` must be a positive 32-bit integer");var r=arguments.length>2&&!!arguments[2],n=!0,c=!0;if("length"in e&&a){var l=a(e,"length");l&&!l.configurable&&(n=!1),l&&!l.writable&&(c=!1)}return(n||c||!r)&&(i?o(e,"length",t,!0,!0):o(e,"length",t)),e}},392:(e,t,r)=>{var n=r(2861).Buffer;function o(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}o.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=n.from(e,t));for(var r=this._block,o=this._blockSize,i=e.length,a=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,o=(r-n)/4294967296;this._block.writeUInt32BE(o,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var i=this._hash();return e?i.toString(e):i},o.prototype._update=function(){throw new Error("_update must be implemented by subclass")},e.exports=o},2802:(e,t,r)=>{var n=e.exports=function(e){e=e.toLowerCase();var t=n[e];if(!t)throw new Error(e+" is not supported (we accept pull requests)");return new t};n.sha=r(7816),n.sha1=r(3737),n.sha224=r(6710),n.sha256=r(4107),n.sha384=r(2827),n.sha512=r(2890)},7816:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,o.call(this,64,56)}function c(e){return e<<30|e>>>2}function l(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,o),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,s=0|this._d,u=0|this._e,f=0;f<16;++f)r[f]=e.readInt32BE(4*f);for(;f<80;++f)r[f]=r[f-3]^r[f-8]^r[f-14]^r[f-16];for(var p=0;p<80;++p){var d=~~(p/20),h=0|((t=n)<<5|t>>>27)+l(d,o,i,s)+u+r[p]+a[d];u=s,s=i,i=c(o),o=n,n=h}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},e.exports=u},3737:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,o.call(this,64,56)}function c(e){return e<<5|e>>>27}function l(e){return e<<30|e>>>2}function f(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,o),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,s=0|this._d,u=0|this._e,p=0;p<16;++p)r[p]=e.readInt32BE(4*p);for(;p<80;++p)r[p]=(t=r[p-3]^r[p-8]^r[p-14]^r[p-16])<<1|t>>>31;for(var d=0;d<80;++d){var h=~~(d/20),y=c(n)+f(h,o,i,s)+u+r[d]+a[h]|0;u=s,s=i,i=l(o),o=n,n=y}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},e.exports=u},6710:(e,t,r)=>{var n=r(6698),o=r(4107),i=r(392),a=r(2861).Buffer,s=new Array(64);function u(){this.init(),this._w=s,i.call(this,64,56)}n(u,o),u.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e},e.exports=u},4107:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],s=new Array(64);function u(){this.init(),this._w=s,o.call(this,64,56)}function c(e,t,r){return r^e&(t^r)}function l(e,t,r){return e&t|r&(e|t)}function f(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function p(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function d(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}n(u,o),u.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,o=0|this._b,i=0|this._c,s=0|this._d,u=0|this._e,h=0|this._f,y=0|this._g,m=0|this._h,v=0;v<16;++v)r[v]=e.readInt32BE(4*v);for(;v<64;++v)r[v]=0|(((t=r[v-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+r[v-7]+d(r[v-15])+r[v-16];for(var g=0;g<64;++g){var b=m+p(u)+c(u,h,y)+a[g]+r[g]|0,w=f(n)+l(n,o,i)|0;m=y,y=h,h=u,u=s+b|0,s=i,i=o,o=n,n=b+w|0}this._a=n+this._a|0,this._b=o+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0,this._f=h+this._f|0,this._g=y+this._g|0,this._h=m+this._h|0},u.prototype._hash=function(){var e=i.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},e.exports=u},2827:(e,t,r)=>{var n=r(6698),o=r(2890),i=r(392),a=r(2861).Buffer,s=new Array(160);function u(){this.init(),this._w=s,i.call(this,128,112)}n(u,o),u.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(48);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},e.exports=u},2890:(e,t,r)=>{var n=r(6698),o=r(392),i=r(2861).Buffer,a=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],s=new Array(160);function u(){this.init(),this._w=s,o.call(this,128,112)}function c(e,t,r){return r^e&(t^r)}function l(e,t,r){return e&t|r&(e|t)}function f(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function p(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function d(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function h(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function y(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function m(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function v(e,t){return e>>>0>>0?1:0}n(u,o),u.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},u.prototype._update=function(e){for(var t=this._w,r=0|this._ah,n=0|this._bh,o=0|this._ch,i=0|this._dh,s=0|this._eh,u=0|this._fh,g=0|this._gh,b=0|this._hh,w=0|this._al,S=0|this._bl,E=0|this._cl,_=0|this._dl,k=0|this._el,T=0|this._fl,O=0|this._gl,x=0|this._hl,A=0;A<32;A+=2)t[A]=e.readInt32BE(4*A),t[A+1]=e.readInt32BE(4*A+4);for(;A<160;A+=2){var P=t[A-30],R=t[A-30+1],j=d(P,R),C=h(R,P),I=y(P=t[A-4],R=t[A-4+1]),L=m(R,P),B=t[A-14],N=t[A-14+1],U=t[A-32],M=t[A-32+1],D=C+N|0,F=j+B+v(D,C)|0;F=(F=F+I+v(D=D+L|0,L)|0)+U+v(D=D+M|0,M)|0,t[A]=F,t[A+1]=D}for(var V=0;V<160;V+=2){F=t[V],D=t[V+1];var q=l(r,n,o),K=l(w,S,E),H=f(r,w),z=f(w,r),X=p(s,k),G=p(k,s),W=a[V],$=a[V+1],Q=c(s,u,g),Y=c(k,T,O),J=x+G|0,Z=b+X+v(J,x)|0;Z=(Z=(Z=Z+Q+v(J=J+Y|0,Y)|0)+W+v(J=J+$|0,$)|0)+F+v(J=J+D|0,D)|0;var ee=z+K|0,te=H+q+v(ee,z)|0;b=g,x=O,g=u,O=T,u=s,T=k,s=i+Z+v(k=_+J|0,_)|0,i=o,_=E,o=n,E=S,n=r,S=w,r=Z+te+v(w=J+ee|0,J)|0}this._al=this._al+w|0,this._bl=this._bl+S|0,this._cl=this._cl+E|0,this._dl=this._dl+_|0,this._el=this._el+k|0,this._fl=this._fl+T|0,this._gl=this._gl+O|0,this._hl=this._hl+x|0,this._ah=this._ah+r+v(this._al,w)|0,this._bh=this._bh+n+v(this._bl,S)|0,this._ch=this._ch+o+v(this._cl,E)|0,this._dh=this._dh+i+v(this._dl,_)|0,this._eh=this._eh+s+v(this._el,k)|0,this._fh=this._fh+u+v(this._fl,T)|0,this._gh=this._gh+g+v(this._gl,O)|0,this._hh=this._hh+b+v(this._hl,x)|0},u.prototype._hash=function(){var e=i.allocUnsafe(64);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},e.exports=u},4803:(e,t,r)=>{"use strict";var n=r(8859),o=r(9675),i=function(e,t,r){for(var n,o=e;null!=(n=o.next);o=n)if(n.key===t)return o.next=n.next,r||(n.next=e.next,e.next=n),n};e.exports=function(){var e,t={assert:function(e){if(!t.has(e))throw new o("Side channel does not contain "+n(e))},delete:function(t){var r=e&&e.next,n=function(e,t){if(e)return i(e,t,!0)}(e,t);return n&&r&&r===n&&(e=void 0),!!n},get:function(t){return function(e,t){if(e){var r=i(e,t);return r&&r.value}}(e,t)},has:function(t){return function(e,t){return!!e&&!!i(e,t)}(e,t)},set:function(t,r){e||(e={next:void 0}),function(e,t,r){var n=i(e,t);n?n.value=r:e.next={key:t,next:e.next,value:r}}(e,t,r)}};return t}},507:(e,t,r)=>{"use strict";var n=r(453),o=r(6556),i=r(8859),a=r(9675),s=n("%Map%",!0),u=o("Map.prototype.get",!0),c=o("Map.prototype.set",!0),l=o("Map.prototype.has",!0),f=o("Map.prototype.delete",!0),p=o("Map.prototype.size",!0);e.exports=!!s&&function(){var e,t={assert:function(e){if(!t.has(e))throw new a("Side channel does not contain "+i(e))},delete:function(t){if(e){var r=f(e,t);return 0===p(e)&&(e=void 0),r}return!1},get:function(t){if(e)return u(e,t)},has:function(t){return!!e&&l(e,t)},set:function(t,r){e||(e=new s),c(e,t,r)}};return t}},2271:(e,t,r)=>{"use strict";var n=r(453),o=r(6556),i=r(8859),a=r(507),s=r(9675),u=n("%WeakMap%",!0),c=o("WeakMap.prototype.get",!0),l=o("WeakMap.prototype.set",!0),f=o("WeakMap.prototype.has",!0),p=o("WeakMap.prototype.delete",!0);e.exports=u?function(){var e,t,r={assert:function(e){if(!r.has(e))throw new s("Side channel does not contain "+i(e))},delete:function(r){if(u&&r&&("object"==typeof r||"function"==typeof r)){if(e)return p(e,r)}else if(a&&t)return t.delete(r);return!1},get:function(r){return u&&r&&("object"==typeof r||"function"==typeof r)&&e?c(e,r):t&&t.get(r)},has:function(r){return u&&r&&("object"==typeof r||"function"==typeof r)&&e?f(e,r):!!t&&t.has(r)},set:function(r,n){u&&r&&("object"==typeof r||"function"==typeof r)?(e||(e=new u),l(e,r,n)):a&&(t||(t=a()),t.set(r,n))}};return r}:a},920:(e,t,r)=>{"use strict";var n=r(9675),o=r(8859),i=r(4803),a=r(507),s=r(2271)||a||i;e.exports=function(){var e,t={assert:function(e){if(!t.has(e))throw new n("Side channel does not contain "+o(e))},delete:function(t){return!!e&&e.delete(t)},get:function(t){return e&&e.get(t)},has:function(t){return!!e&&e.has(t)},set:function(t,r){e||(e=s()),e.set(t,r)}};return t}},1568:(e,t,r)=>{var n=r(5537),o=r(6917),i=r(7510),a=r(6866),s=r(8835),u=t;u.request=function(e,t){e="string"==typeof e?s.parse(e):i(e);var o=-1===r.g.location.protocol.search(/^https?:$/)?"http:":"",a=e.protocol||o,u=e.hostname||e.host,c=e.port,l=e.path||"/";u&&-1!==u.indexOf(":")&&(u="["+u+"]"),e.url=(u?a+"//"+u:"")+(c?":"+c:"")+l,e.method=(e.method||"GET").toUpperCase(),e.headers=e.headers||{};var f=new n(e);return t&&f.on("response",t),f},u.get=function(e,t){var r=u.request(e,t);return r.end(),r},u.ClientRequest=n,u.IncomingMessage=o.IncomingMessage,u.Agent=function(){},u.Agent.defaultMaxSockets=4,u.globalAgent=new u.Agent,u.STATUS_CODES=a,u.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]},6688:(e,t,r)=>{var n;function o(){if(void 0!==n)return n;if(r.g.XMLHttpRequest){n=new r.g.XMLHttpRequest;try{n.open("GET",r.g.XDomainRequest?"/":"https://example.com")}catch(e){n=null}}else n=null;return n}function i(e){var t=o();if(!t)return!1;try{return t.responseType=e,t.responseType===e}catch(e){}return!1}function a(e){return"function"==typeof e}t.fetch=a(r.g.fetch)&&a(r.g.ReadableStream),t.writableStream=a(r.g.WritableStream),t.abortController=a(r.g.AbortController),t.arraybuffer=t.fetch||i("arraybuffer"),t.msstream=!t.fetch&&i("ms-stream"),t.mozchunkedarraybuffer=!t.fetch&&i("moz-chunked-arraybuffer"),t.overrideMimeType=t.fetch||!!o()&&a(o().overrideMimeType),n=null},5537:(e,t,r)=>{var n=r(8287).Buffer,o=r(6688),i=r(6698),a=r(6917),s=r(8399),u=a.IncomingMessage,c=a.readyStates;var l=e.exports=function(e){var t,r=this;s.Writable.call(r),r._opts=e,r._body=[],r._headers={},e.auth&&r.setHeader("Authorization","Basic "+n.from(e.auth).toString("base64")),Object.keys(e.headers).forEach((function(t){r.setHeader(t,e.headers[t])}));var i=!0;if("disable-fetch"===e.mode||"requestTimeout"in e&&!o.abortController)i=!1,t=!0;else if("prefer-streaming"===e.mode)t=!1;else if("allow-wrong-content-type"===e.mode)t=!o.overrideMimeType;else{if(e.mode&&"default"!==e.mode&&"prefer-fast"!==e.mode)throw new Error("Invalid value for opts.mode");t=!0}r._mode=function(e,t){return o.fetch&&t?"fetch":o.mozchunkedarraybuffer?"moz-chunked-arraybuffer":o.msstream?"ms-stream":o.arraybuffer&&e?"arraybuffer":"text"}(t,i),r._fetchTimer=null,r._socketTimeout=null,r._socketTimer=null,r.on("finish",(function(){r._onFinish()}))};i(l,s.Writable),l.prototype.setHeader=function(e,t){var r=e.toLowerCase();-1===f.indexOf(r)&&(this._headers[r]={name:e,value:t})},l.prototype.getHeader=function(e){var t=this._headers[e.toLowerCase()];return t?t.value:null},l.prototype.removeHeader=function(e){delete this._headers[e.toLowerCase()]},l.prototype._onFinish=function(){var e=this;if(!e._destroyed){var t=e._opts;"timeout"in t&&0!==t.timeout&&e.setTimeout(t.timeout);var n=e._headers,i=null;"GET"!==t.method&&"HEAD"!==t.method&&(i=new Blob(e._body,{type:(n["content-type"]||{}).value||""}));var a=[];if(Object.keys(n).forEach((function(e){var t=n[e].name,r=n[e].value;Array.isArray(r)?r.forEach((function(e){a.push([t,e])})):a.push([t,r])})),"fetch"===e._mode){var s=null;if(o.abortController){var u=new AbortController;s=u.signal,e._fetchAbortController=u,"requestTimeout"in t&&0!==t.requestTimeout&&(e._fetchTimer=r.g.setTimeout((function(){e.emit("requestTimeout"),e._fetchAbortController&&e._fetchAbortController.abort()}),t.requestTimeout))}r.g.fetch(e._opts.url,{method:e._opts.method,headers:a,body:i||void 0,mode:"cors",credentials:t.withCredentials?"include":"same-origin",signal:s}).then((function(t){e._fetchResponse=t,e._resetTimers(!1),e._connect()}),(function(t){e._resetTimers(!0),e._destroyed||e.emit("error",t)}))}else{var l=e._xhr=new r.g.XMLHttpRequest;try{l.open(e._opts.method,e._opts.url,!0)}catch(t){return void process.nextTick((function(){e.emit("error",t)}))}"responseType"in l&&(l.responseType=e._mode),"withCredentials"in l&&(l.withCredentials=!!t.withCredentials),"text"===e._mode&&"overrideMimeType"in l&&l.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in t&&(l.timeout=t.requestTimeout,l.ontimeout=function(){e.emit("requestTimeout")}),a.forEach((function(e){l.setRequestHeader(e[0],e[1])})),e._response=null,l.onreadystatechange=function(){switch(l.readyState){case c.LOADING:case c.DONE:e._onXHRProgress()}},"moz-chunked-arraybuffer"===e._mode&&(l.onprogress=function(){e._onXHRProgress()}),l.onerror=function(){e._destroyed||(e._resetTimers(!0),e.emit("error",new Error("XHR error")))};try{l.send(i)}catch(t){return void process.nextTick((function(){e.emit("error",t)}))}}}},l.prototype._onXHRProgress=function(){var e=this;e._resetTimers(!1),function(e){try{var t=e.status;return null!==t&&0!==t}catch(e){return!1}}(e._xhr)&&!e._destroyed&&(e._response||e._connect(),e._response._onXHRProgress(e._resetTimers.bind(e)))},l.prototype._connect=function(){var e=this;e._destroyed||(e._response=new u(e._xhr,e._fetchResponse,e._mode,e._resetTimers.bind(e)),e._response.on("error",(function(t){e.emit("error",t)})),e.emit("response",e._response))},l.prototype._write=function(e,t,r){this._body.push(e),r()},l.prototype._resetTimers=function(e){var t=this;r.g.clearTimeout(t._socketTimer),t._socketTimer=null,e?(r.g.clearTimeout(t._fetchTimer),t._fetchTimer=null):t._socketTimeout&&(t._socketTimer=r.g.setTimeout((function(){t.emit("timeout")}),t._socketTimeout))},l.prototype.abort=l.prototype.destroy=function(e){var t=this;t._destroyed=!0,t._resetTimers(!0),t._response&&(t._response._destroyed=!0),t._xhr?t._xhr.abort():t._fetchAbortController&&t._fetchAbortController.abort(),e&&t.emit("error",e)},l.prototype.end=function(e,t,r){"function"==typeof e&&(r=e,e=void 0),s.Writable.prototype.end.call(this,e,t,r)},l.prototype.setTimeout=function(e,t){var r=this;t&&r.once("timeout",t),r._socketTimeout=e,r._resetTimers(!1)},l.prototype.flushHeaders=function(){},l.prototype.setNoDelay=function(){},l.prototype.setSocketKeepAlive=function(){};var f=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]},6917:(e,t,r)=>{var n=r(8287).Buffer,o=r(6688),i=r(6698),a=r(8399),s=t.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},u=t.IncomingMessage=function(e,t,r,i){var s=this;if(a.Readable.call(s),s._mode=r,s.headers={},s.rawHeaders=[],s.trailers={},s.rawTrailers=[],s.on("end",(function(){process.nextTick((function(){s.emit("close")}))})),"fetch"===r){if(s._fetchResponse=t,s.url=t.url,s.statusCode=t.status,s.statusMessage=t.statusText,t.headers.forEach((function(e,t){s.headers[t.toLowerCase()]=e,s.rawHeaders.push(t,e)})),o.writableStream){var u=new WritableStream({write:function(e){return i(!1),new Promise((function(t,r){s._destroyed?r():s.push(n.from(e))?t():s._resumeFetch=t}))},close:function(){i(!0),s._destroyed||s.push(null)},abort:function(e){i(!0),s._destroyed||s.emit("error",e)}});try{return void t.body.pipeTo(u).catch((function(e){i(!0),s._destroyed||s.emit("error",e)}))}catch(e){}}var c=t.body.getReader();!function e(){c.read().then((function(t){s._destroyed||(i(t.done),t.done?s.push(null):(s.push(n.from(t.value)),e()))})).catch((function(e){i(!0),s._destroyed||s.emit("error",e)}))}()}else{if(s._xhr=e,s._pos=0,s.url=e.responseURL,s.statusCode=e.status,s.statusMessage=e.statusText,e.getAllResponseHeaders().split(/\r?\n/).forEach((function(e){var t=e.match(/^([^:]+):\s*(.*)/);if(t){var r=t[1].toLowerCase();"set-cookie"===r?(void 0===s.headers[r]&&(s.headers[r]=[]),s.headers[r].push(t[2])):void 0!==s.headers[r]?s.headers[r]+=", "+t[2]:s.headers[r]=t[2],s.rawHeaders.push(t[1],t[2])}})),s._charset="x-user-defined",!o.overrideMimeType){var l=s.rawHeaders["mime-type"];if(l){var f=l.match(/;\s*charset=([^;])(;|$)/);f&&(s._charset=f[1].toLowerCase())}s._charset||(s._charset="utf-8")}}};i(u,a.Readable),u.prototype._read=function(){var e=this._resumeFetch;e&&(this._resumeFetch=null,e())},u.prototype._onXHRProgress=function(e){var t=this,o=t._xhr,i=null;switch(t._mode){case"text":if((i=o.responseText).length>t._pos){var a=i.substr(t._pos);if("x-user-defined"===t._charset){for(var u=n.alloc(a.length),c=0;ct._pos&&(t.push(n.from(new Uint8Array(l.result.slice(t._pos)))),t._pos=l.result.byteLength)},l.onload=function(){e(!0),t.push(null)},l.readAsArrayBuffer(i)}t._xhr.readyState===s.DONE&&"ms-stream"!==t._mode&&(e(!0),t.push(null))}},3141:(e,t,r)=>{"use strict";var n=r(2861).Buffer,o=n.isEncoding||function(e){switch((e=""+e)&&e.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!0;default:return!1}};function i(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){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 e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=u,this.end=c,t=4;break;case"utf8":this.fillLast=s,t=4;break;case"base64":this.text=l,this.end=f,t=3;break;default:return this.write=p,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function a(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e){var t=this.lastTotal-this.lastNeed,r=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"\ufffd";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"\ufffd";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"\ufffd"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function u(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function c(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function l(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function f(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function p(e){return e.toString(this.encoding)}function d(e){return e&&e.length?this.write(e):""}t.I=i,i.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return o>0&&(e.lastNeed=o-1),o;if(--n=0)return o>0&&(e.lastNeed=o-2),o;if(--n=0)return o>0&&(2===o?o=0:e.lastNeed=o-3),o;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},i.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},1293:(e,t,r)=>{var n=r(5546),o=r(2708);e.exports={parse:function(e){var t=n.parse(e.toString());return o.compile(t)}}},2708:e=>{"use strict";e.exports={compile:function(e){var t=[],r=[],n="",o=Object.create(null),i=o;return function(e){for(var t,r=0;r-1&&a("Cannot redefine existing key '"+u+"'.",o,i),(c=c[f])instanceof Array&&c.length&&l-1?'"'+e+'"':e}}}},5546:e=>{e.exports=function(){function e(e,t,r,n,o,i){this.message=e,this.expected=t,this.found=r,this.offset=n,this.line=o,this.column=i,this.name="SyntaxError"}return function(e,t){function r(){this.constructor=e}r.prototype=t.prototype,e.prototype=new r}(e,Error),{SyntaxError:e,parse:function(t){var r,n=arguments.length>1?arguments[1]:{},o={},i={start:Lt},a=Lt,s=function(){return pr},u=o,c="#",l={type:"literal",value:"#",description:'"#"'},f=void 0,p={type:"any",description:"any character"},d="[",h={type:"literal",value:"[",description:'"["'},y="]",m={type:"literal",value:"]",description:'"]"'},v=function(e){dr(hr("ObjectPath",e,Pt,Rt))},g=function(e){dr(hr("ArrayPath",e,Pt,Rt))},b=function(e,t){return e.concat(t)},w=function(e){return[e]},S=function(e){return e},E=".",_={type:"literal",value:".",description:'"."'},k="=",T={type:"literal",value:"=",description:'"="'},O=function(e,t){dr(hr("Assign",t,Pt,Rt,e))},x=function(e){return e.join("")},A=function(e){return e.value},P='"""',R={type:"literal",value:'"""',description:'"\\"\\"\\""'},j=null,C=function(e){return hr("String",e.join(""),Pt,Rt)},I='"',L={type:"literal",value:'"',description:'"\\""'},B="'''",N={type:"literal",value:"'''",description:"\"'''\""},U="'",M={type:"literal",value:"'",description:'"\'"'},D=function(e){return e},F=function(e){return e},V="\\",q={type:"literal",value:"\\",description:'"\\\\"'},K=function(){return""},H="e",z={type:"literal",value:"e",description:'"e"'},X="E",G={type:"literal",value:"E",description:'"E"'},W=function(e,t){return hr("Float",parseFloat(e+"e"+t),Pt,Rt)},$=function(e){return hr("Float",parseFloat(e),Pt,Rt)},Q="+",Y={type:"literal",value:"+",description:'"+"'},J=function(e){return e.join("")},Z="-",ee={type:"literal",value:"-",description:'"-"'},te=function(e){return"-"+e.join("")},re=function(e){return hr("Integer",parseInt(e,10),Pt,Rt)},ne="true",oe={type:"literal",value:"true",description:'"true"'},ie=function(){return hr("Boolean",!0,Pt,Rt)},ae="false",se={type:"literal",value:"false",description:'"false"'},ue=function(){return hr("Boolean",!1,Pt,Rt)},ce=function(){return hr("Array",[],Pt,Rt)},le=function(e){return hr("Array",e?[e]:[],Pt,Rt)},fe=function(e){return hr("Array",e,Pt,Rt)},pe=function(e,t){return hr("Array",e.concat(t),Pt,Rt)},de=function(e){return e},he=",",ye={type:"literal",value:",",description:'","'},me="{",ve={type:"literal",value:"{",description:'"{"'},ge="}",be={type:"literal",value:"}",description:'"}"'},we=function(e){return hr("InlineTable",e,Pt,Rt)},Se=function(e,t){return hr("InlineTableValue",t,Pt,Rt,e)},Ee=function(e){return"."+e},_e=function(e){return e.join("")},ke=":",Te={type:"literal",value:":",description:'":"'},Oe=function(e){return e.join("")},xe="T",Ae={type:"literal",value:"T",description:'"T"'},Pe="Z",Re={type:"literal",value:"Z",description:'"Z"'},je=function(e,t){return hr("Date",new Date(e+"T"+t+"Z"),Pt,Rt)},Ce=function(e,t){return hr("Date",new Date(e+"T"+t),Pt,Rt)},Ie=/^[ \t]/,Le={type:"class",value:"[ \\t]",description:"[ \\t]"},Be="\n",Ne={type:"literal",value:"\n",description:'"\\n"'},Ue="\r",Me={type:"literal",value:"\r",description:'"\\r"'},De=/^[0-9a-f]/i,Fe={type:"class",value:"[0-9a-f]i",description:"[0-9a-f]i"},Ve=/^[0-9]/,qe={type:"class",value:"[0-9]",description:"[0-9]"},Ke="_",He={type:"literal",value:"_",description:'"_"'},ze=function(){return""},Xe=/^[A-Za-z0-9_\-]/,Ge={type:"class",value:"[A-Za-z0-9_\\-]",description:"[A-Za-z0-9_\\-]"},We=function(e){return e.join("")},$e='\\"',Qe={type:"literal",value:'\\"',description:'"\\\\\\""'},Ye=function(){return'"'},Je="\\\\",Ze={type:"literal",value:"\\\\",description:'"\\\\\\\\"'},et=function(){return"\\"},tt="\\b",rt={type:"literal",value:"\\b",description:'"\\\\b"'},nt=function(){return"\b"},ot="\\t",it={type:"literal",value:"\\t",description:'"\\\\t"'},at=function(){return"\t"},st="\\n",ut={type:"literal",value:"\\n",description:'"\\\\n"'},ct=function(){return"\n"},lt="\\f",ft={type:"literal",value:"\\f",description:'"\\\\f"'},pt=function(){return"\f"},dt="\\r",ht={type:"literal",value:"\\r",description:'"\\\\r"'},yt=function(){return"\r"},mt="\\U",vt={type:"literal",value:"\\U",description:'"\\\\U"'},gt=function(e){return function(e,t,r){var n=parseInt("0x"+e);if(!(!isFinite(n)||Math.floor(n)!=n||n<0||n>1114111||n>55295&&n<57344))return function(){var e,t,r=16384,n=[],o=-1,i=arguments.length;if(!i)return"";var a="";for(;++o>10),t=s%1024+56320,n.push(e,t)),(o+1==i||n.length>r)&&(a+=String.fromCharCode.apply(null,n),n.length=0)}return a}(n);!function(e,t,r){var n=new Error(e);throw n.line=t,n.column=r,n}("Invalid Unicode escape code: "+e,t,r)}(e.join(""))},bt="\\u",wt={type:"literal",value:"\\u",description:'"\\\\u"'},St=0,Et=0,_t=0,kt={line:1,column:1,seenCR:!1},Tt=0,Ot=[],xt=0,At={};if("startRule"in n){if(!(n.startRule in i))throw new Error("Can't start parsing from rule \""+n.startRule+'".');a=i[n.startRule]}function Pt(){return jt(Et).line}function Rt(){return jt(Et).column}function jt(e){return _t!==e&&(_t>e&&(_t=0,kt={line:1,column:1,seenCR:!1}),function(e,r,n){var o,i;for(o=r;oTt&&(Tt=St,Ot=[]),Ot.push(e))}function It(r,n,o){var i=jt(o),a=ot.description?1:0}));t1?n.slice(0,-1).join(", ")+" or "+n[e.length-1]:n[0])+" but "+(t?'"'+function(e){function t(e){return e.charCodeAt(0).toString(16).toUpperCase()}return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E\x0F]/g,(function(e){return"\\x0"+t(e)})).replace(/[\x10-\x1F\x80-\xFF]/g,(function(e){return"\\x"+t(e)})).replace(/[\u0180-\u0FFF]/g,(function(e){return"\\u0"+t(e)})).replace(/[\u1080-\uFFFF]/g,(function(e){return"\\u"+t(e)}))}(t)+'"':"end of input")+" found."}(n,a),n,a,o,i.line,i.column)}function Lt(){var e,t,r,n=49*St+0,i=At[n];if(i)return St=i.nextPos,i.result;for(e=St,t=[],r=Bt();r!==o;)t.push(r),r=Bt();return t!==o&&(Et=e,t=s()),e=t,At[n]={nextPos:St,result:e},e}function Bt(){var e,r,n,i,a,s,c,l=49*St+1,f=At[l];if(f)return St=f.nextPos,f.result;for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if(n=function(){var e,r=49*St+2,n=At[r];if(n)return St=n.nextPos,n.result;e=Nt(),e===o&&(e=function(){var e,r,n,i,a,s,c=49*St+4,l=At[c];if(l)return St=l.nextPos,l.result;e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h));if(r!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o)if((i=Ut())!==o){for(a=[],s=nr();s!==o;)a.push(s),s=nr();a!==o?(93===t.charCodeAt(St)?(s=y,St++):(s=o,0===xt&&Ct(m)),s!==o?(Et=e,e=r=v(i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;return At[c]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s,c,l,f=49*St+5,p=At[f];if(p)return St=p.nextPos,p.result;e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h));if(r!==o)if(91===t.charCodeAt(St)?(n=d,St++):(n=o,0===xt&&Ct(h)),n!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if((a=Ut())!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();s!==o?(93===t.charCodeAt(St)?(c=y,St++):(c=o,0===xt&&Ct(m)),c!==o?(93===t.charCodeAt(St)?(l=y,St++):(l=o,0===xt&&Ct(m)),l!==o?(Et=e,e=r=g(a)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u;return At[f]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s,c=49*St+9,l=At[c];if(l)return St=l.nextPos,l.result;if(e=St,r=Ft(),r!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o)if(61===t.charCodeAt(St)?(i=k,St++):(i=o,0===xt&&Ct(T)),i!==o){for(a=[],s=nr();s!==o;)a.push(s),s=nr();a!==o&&(s=qt())!==o?(Et=e,e=r=O(r,s)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;if(e===o)if(e=St,(r=Vt())!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o)if(61===t.charCodeAt(St)?(i=k,St++):(i=o,0===xt&&Ct(T)),i!==o){for(a=[],s=nr();s!==o;)a.push(s),s=nr();a!==o&&(s=qt())!==o?(Et=e,e=r=O(r,s)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;return At[c]={nextPos:St,result:e},e}())));return At[r]={nextPos:St,result:e},e}(),n!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o){for(a=[],s=Nt();s!==o;)a.push(s),s=Nt();if(a!==o){if(s=[],(c=or())!==o)for(;c!==o;)s.push(c),c=or();else s=u;s===o&&(s=ar()),s!==o?e=r=[r,n,i,a,s]:(St=e,e=u)}else St=e,e=u}else St=e,e=u}else St=e,e=u;else St=e,e=u;if(e===o){if(e=St,r=[],(n=nr())!==o)for(;n!==o;)r.push(n),n=nr();else r=u;if(r!==o){if(n=[],(i=or())!==o)for(;i!==o;)n.push(i),i=or();else n=u;n===o&&(n=ar()),n!==o?e=r=[r,n]:(St=e,e=u)}else St=e,e=u;e===o&&(e=or())}return At[l]={nextPos:St,result:e},e}function Nt(){var e,r,n,i,a,s,d=49*St+3,h=At[d];if(h)return St=h.nextPos,h.result;if(e=St,35===t.charCodeAt(St)?(r=c,St++):(r=o,0===xt&&Ct(l)),r!==o){for(n=[],i=St,a=St,xt++,(s=or())===o&&(s=ar()),xt--,s===o?a=f:(St=a,a=u),a!==o?(t.length>St?(s=t.charAt(St),St++):(s=o,0===xt&&Ct(p)),s!==o?i=a=[a,s]:(St=i,i=u)):(St=i,i=u);i!==o;)n.push(i),i=St,a=St,xt++,(s=or())===o&&(s=ar()),xt--,s===o?a=f:(St=a,a=u),a!==o?(t.length>St?(s=t.charAt(St),St++):(s=o,0===xt&&Ct(p)),s!==o?i=a=[a,s]:(St=i,i=u)):(St=i,i=u);n!==o?e=r=[r,n]:(St=e,e=u)}else St=e,e=u;return At[d]={nextPos:St,result:e},e}function Ut(){var e,t,r,n=49*St+6,i=At[n];if(i)return St=i.nextPos,i.result;if(e=St,t=[],(r=Dt())!==o)for(;r!==o;)t.push(r),r=Dt();else t=u;return t!==o&&(r=Mt())!==o?(Et=e,e=t=b(t,r)):(St=e,e=u),e===o&&(e=St,(t=Mt())!==o&&(Et=e,t=w(t)),e=t),At[n]={nextPos:St,result:e},e}function Mt(){var e,t,r,n,i,a=49*St+7,s=At[a];if(s)return St=s.nextPos,s.result;for(e=St,t=[],r=nr();r!==o;)t.push(r),r=nr();if(t!==o)if((r=Ft())!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();n!==o?(Et=e,e=t=S(r)):(St=e,e=u)}else St=e,e=u;else St=e,e=u;if(e===o){for(e=St,t=[],r=nr();r!==o;)t.push(r),r=nr();if(t!==o)if((r=Vt())!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();n!==o?(Et=e,e=t=S(r)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}return At[a]={nextPos:St,result:e},e}function Dt(){var e,r,n,i,a,s,c,l=49*St+8,f=At[l];if(f)return St=f.nextPos,f.result;for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Ft())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(46===t.charCodeAt(St)?(a=E,St++):(a=o,0===xt&&Ct(_)),a!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();s!==o?(Et=e,e=r=S(n)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u;if(e===o){for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Vt())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(46===t.charCodeAt(St)?(a=E,St++):(a=o,0===xt&&Ct(_)),a!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();s!==o?(Et=e,e=r=S(n)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u}return At[l]={nextPos:St,result:e},e}function Ft(){var e,t,r,n=49*St+10,i=At[n];if(i)return St=i.nextPos,i.result;if(e=St,t=[],(r=cr())!==o)for(;r!==o;)t.push(r),r=cr();else t=u;return t!==o&&(Et=e,t=x(t)),e=t,At[n]={nextPos:St,result:e},e}function Vt(){var e,t,r=49*St+11,n=At[r];return n?(St=n.nextPos,n.result):(e=St,(t=Kt())!==o&&(Et=e,t=A(t)),(e=t)===o&&(e=St,(t=Ht())!==o&&(Et=e,t=A(t)),e=t),At[r]={nextPos:St,result:e},e)}function qt(){var e,r=49*St+12,n=At[r];return n?(St=n.nextPos,n.result):(e=function(){var e,r=49*St+13,n=At[r];if(n)return St=n.nextPos,n.result;e=function(){var e,r,n,i,a,s=49*St+14,c=At[s];if(c)return St=c.nextPos,c.result;e=St,t.substr(St,3)===P?(r=P,St+=3):(r=o,0===xt&&Ct(R));if(r!==o)if((n=or())===o&&(n=j),n!==o){for(i=[],a=Gt();a!==o;)i.push(a),a=Gt();i!==o?(t.substr(St,3)===P?(a=P,St+=3):(a=o,0===xt&&Ct(R)),a!==o?(Et=e,e=r=C(i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;else St=e,e=u;return At[s]={nextPos:St,result:e},e}(),e===o&&(e=Kt())===o&&(e=function(){var e,r,n,i,a,s=49*St+16,c=At[s];if(c)return St=c.nextPos,c.result;e=St,t.substr(St,3)===B?(r=B,St+=3):(r=o,0===xt&&Ct(N));if(r!==o)if((n=or())===o&&(n=j),n!==o){for(i=[],a=Wt();a!==o;)i.push(a),a=Wt();i!==o?(t.substr(St,3)===B?(a=B,St+=3):(a=o,0===xt&&Ct(N)),a!==o?(Et=e,e=r=C(i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;else St=e,e=u;return At[s]={nextPos:St,result:e},e}(),e===o&&(e=Ht()));return At[r]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s=49*St+38,c=At[s];if(c)return St=c.nextPos,c.result;e=St,(r=rr())!==o?(84===t.charCodeAt(St)?(n=xe,St++):(n=o,0===xt&&Ct(Ae)),n!==o?(i=function(){var e,r,n,i,a,s,c,l,f,p,d,h=49*St+36,y=At[h];if(y)return St=y.nextPos,y.result;e=St,r=St,n=ur(),n!==o&&(i=ur())!==o?(58===t.charCodeAt(St)?(a=ke,St++):(a=o,0===xt&&Ct(Te)),a!==o&&(s=ur())!==o&&(c=ur())!==o?(58===t.charCodeAt(St)?(l=ke,St++):(l=o,0===xt&&Ct(Te)),l!==o&&(f=ur())!==o&&(p=ur())!==o?((d=tr())===o&&(d=j),d!==o?r=n=[n,i,a,s,c,l,f,p,d]:(St=r,r=u)):(St=r,r=u)):(St=r,r=u)):(St=r,r=u);r!==o&&(Et=e,r=Oe(r));return e=r,At[h]={nextPos:St,result:e},e}(),i!==o?(90===t.charCodeAt(St)?(a=Pe,St++):(a=o,0===xt&&Ct(Re)),a!==o?(Et=e,e=r=je(r,i)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u);e===o&&(e=St,(r=rr())!==o?(84===t.charCodeAt(St)?(n=xe,St++):(n=o,0===xt&&Ct(Ae)),n!==o?(i=function(){var e,r,n,i,a,s,c,l,f,p,d,h,y,m,v,g,b,w=49*St+37,S=At[w];if(S)return St=S.nextPos,S.result;e=St,r=St,n=ur(),n!==o&&(i=ur())!==o?(58===t.charCodeAt(St)?(a=ke,St++):(a=o,0===xt&&Ct(Te)),a!==o&&(s=ur())!==o&&(c=ur())!==o?(58===t.charCodeAt(St)?(l=ke,St++):(l=o,0===xt&&Ct(Te)),l!==o&&(f=ur())!==o&&(p=ur())!==o?((d=tr())===o&&(d=j),d!==o?(45===t.charCodeAt(St)?(h=Z,St++):(h=o,0===xt&&Ct(ee)),h===o&&(43===t.charCodeAt(St)?(h=Q,St++):(h=o,0===xt&&Ct(Y))),h!==o&&(y=ur())!==o&&(m=ur())!==o?(58===t.charCodeAt(St)?(v=ke,St++):(v=o,0===xt&&Ct(Te)),v!==o&&(g=ur())!==o&&(b=ur())!==o?r=n=[n,i,a,s,c,l,f,p,d,h,y,m,v,g,b]:(St=r,r=u)):(St=r,r=u)):(St=r,r=u)):(St=r,r=u)):(St=r,r=u)):(St=r,r=u);r!==o&&(Et=e,r=Oe(r));return e=r,At[w]={nextPos:St,result:e},e}(),i!==o?(Et=e,e=r=Ce(r,i)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u));return At[s]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a=49*St+23,s=At[a];if(s)return St=s.nextPos,s.result;e=St,(r=$t())===o&&(r=Qt());r!==o?(101===t.charCodeAt(St)?(n=H,St++):(n=o,0===xt&&Ct(z)),n===o&&(69===t.charCodeAt(St)?(n=X,St++):(n=o,0===xt&&Ct(G))),n!==o&&(i=Qt())!==o?(Et=e,e=r=W(r,i)):(St=e,e=u)):(St=e,e=u);e===o&&(e=St,(r=$t())!==o&&(Et=e,r=$(r)),e=r);return At[a]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,t,r=49*St+25,n=At[r];if(n)return St=n.nextPos,n.result;e=St,(t=Qt())!==o&&(Et=e,t=re(t));return e=t,At[r]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n=49*St+27,i=At[n];if(i)return St=i.nextPos,i.result;e=St,t.substr(St,4)===ne?(r=ne,St+=4):(r=o,0===xt&&Ct(oe));r!==o&&(Et=e,r=ie());e=r,e===o&&(e=St,t.substr(St,5)===ae?(r=ae,St+=5):(r=o,0===xt&&Ct(se)),r!==o&&(Et=e,r=ue()),e=r);return At[n]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s=49*St+28,c=At[s];if(c)return St=c.nextPos,c.result;e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h));if(r!==o){for(n=[],i=Zt();i!==o;)n.push(i),i=Zt();n!==o?(93===t.charCodeAt(St)?(i=y,St++):(i=o,0===xt&&Ct(m)),i!==o?(Et=e,e=r=ce()):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;if(e===o&&(e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h)),r!==o?((n=Yt())===o&&(n=j),n!==o?(93===t.charCodeAt(St)?(i=y,St++):(i=o,0===xt&&Ct(m)),i!==o?(Et=e,e=r=le(n)):(St=e,e=u)):(St=e,e=u)):(St=e,e=u),e===o)){if(e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h)),r!==o){if(n=[],(i=Jt())!==o)for(;i!==o;)n.push(i),i=Jt();else n=u;n!==o?(93===t.charCodeAt(St)?(i=y,St++):(i=o,0===xt&&Ct(m)),i!==o?(Et=e,e=r=fe(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;if(e===o)if(e=St,91===t.charCodeAt(St)?(r=d,St++):(r=o,0===xt&&Ct(h)),r!==o){if(n=[],(i=Jt())!==o)for(;i!==o;)n.push(i),i=Jt();else n=u;n!==o&&(i=Yt())!==o?(93===t.charCodeAt(St)?(a=y,St++):(a=o,0===xt&&Ct(m)),a!==o?(Et=e,e=r=pe(n,i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u}return At[s]={nextPos:St,result:e},e}(),e===o&&(e=function(){var e,r,n,i,a,s,c=49*St+32,l=At[c];if(l)return St=l.nextPos,l.result;e=St,123===t.charCodeAt(St)?(r=me,St++):(r=o,0===xt&&Ct(ve));if(r!==o){for(n=[],i=nr();i!==o;)n.push(i),i=nr();if(n!==o){for(i=[],a=er();a!==o;)i.push(a),a=er();if(i!==o){for(a=[],s=nr();s!==o;)a.push(s),s=nr();a!==o?(125===t.charCodeAt(St)?(s=ge,St++):(s=o,0===xt&&Ct(be)),s!==o?(Et=e,e=r=we(i)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u}else St=e,e=u}else St=e,e=u;return At[c]={nextPos:St,result:e},e}())))))),At[r]={nextPos:St,result:e},e)}function Kt(){var e,r,n,i,a=49*St+15,s=At[a];if(s)return St=s.nextPos,s.result;if(e=St,34===t.charCodeAt(St)?(r=I,St++):(r=o,0===xt&&Ct(L)),r!==o){for(n=[],i=zt();i!==o;)n.push(i),i=zt();n!==o?(34===t.charCodeAt(St)?(i=I,St++):(i=o,0===xt&&Ct(L)),i!==o?(Et=e,e=r=C(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;return At[a]={nextPos:St,result:e},e}function Ht(){var e,r,n,i,a=49*St+17,s=At[a];if(s)return St=s.nextPos,s.result;if(e=St,39===t.charCodeAt(St)?(r=U,St++):(r=o,0===xt&&Ct(M)),r!==o){for(n=[],i=Xt();i!==o;)n.push(i),i=Xt();n!==o?(39===t.charCodeAt(St)?(i=U,St++):(i=o,0===xt&&Ct(M)),i!==o?(Et=e,e=r=C(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;return At[a]={nextPos:St,result:e},e}function zt(){var e,r,n,i=49*St+18,a=At[i];return a?(St=a.nextPos,a.result):((e=fr())===o&&(e=St,r=St,xt++,34===t.charCodeAt(St)?(n=I,St++):(n=o,0===xt&&Ct(L)),xt--,n===o?r=f:(St=r,r=u),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&Ct(p)),n!==o?(Et=e,e=r=D(n)):(St=e,e=u)):(St=e,e=u)),At[i]={nextPos:St,result:e},e)}function Xt(){var e,r,n,i=49*St+19,a=At[i];return a?(St=a.nextPos,a.result):(e=St,r=St,xt++,39===t.charCodeAt(St)?(n=U,St++):(n=o,0===xt&&Ct(M)),xt--,n===o?r=f:(St=r,r=u),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&Ct(p)),n!==o?(Et=e,e=r=D(n)):(St=e,e=u)):(St=e,e=u),At[i]={nextPos:St,result:e},e)}function Gt(){var e,r,n,i=49*St+20,a=At[i];return a?(St=a.nextPos,a.result):((e=fr())===o&&(e=function(){var e,r,n,i,a=49*St+21,s=At[a];if(s)return St=s.nextPos,s.result;e=St,92===t.charCodeAt(St)?(r=V,St++):(r=o,0===xt&&Ct(q));if(r!==o)if(or()!==o){for(n=[],i=ir();i!==o;)n.push(i),i=ir();n!==o?(Et=e,e=r=K()):(St=e,e=u)}else St=e,e=u;else St=e,e=u;return At[a]={nextPos:St,result:e},e}(),e===o&&(e=St,r=St,xt++,t.substr(St,3)===P?(n=P,St+=3):(n=o,0===xt&&Ct(R)),xt--,n===o?r=f:(St=r,r=u),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&Ct(p)),n!==o?(Et=e,e=r=F(n)):(St=e,e=u)):(St=e,e=u))),At[i]={nextPos:St,result:e},e)}function Wt(){var e,r,n,i=49*St+22,a=At[i];return a?(St=a.nextPos,a.result):(e=St,r=St,xt++,t.substr(St,3)===B?(n=B,St+=3):(n=o,0===xt&&Ct(N)),xt--,n===o?r=f:(St=r,r=u),r!==o?(t.length>St?(n=t.charAt(St),St++):(n=o,0===xt&&Ct(p)),n!==o?(Et=e,e=r=D(n)):(St=e,e=u)):(St=e,e=u),At[i]={nextPos:St,result:e},e)}function $t(){var e,r,n,i,a,s,c=49*St+24,l=At[c];return l?(St=l.nextPos,l.result):(e=St,43===t.charCodeAt(St)?(r=Q,St++):(r=o,0===xt&&Ct(Y)),r===o&&(r=j),r!==o?(n=St,(i=lr())!==o?(46===t.charCodeAt(St)?(a=E,St++):(a=o,0===xt&&Ct(_)),a!==o&&(s=lr())!==o?n=i=[i,a,s]:(St=n,n=u)):(St=n,n=u),n!==o?(Et=e,e=r=J(n)):(St=e,e=u)):(St=e,e=u),e===o&&(e=St,45===t.charCodeAt(St)?(r=Z,St++):(r=o,0===xt&&Ct(ee)),r!==o?(n=St,(i=lr())!==o?(46===t.charCodeAt(St)?(a=E,St++):(a=o,0===xt&&Ct(_)),a!==o&&(s=lr())!==o?n=i=[i,a,s]:(St=n,n=u)):(St=n,n=u),n!==o?(Et=e,e=r=te(n)):(St=e,e=u)):(St=e,e=u)),At[c]={nextPos:St,result:e},e)}function Qt(){var e,r,n,i,a,s=49*St+26,c=At[s];if(c)return St=c.nextPos,c.result;if(e=St,43===t.charCodeAt(St)?(r=Q,St++):(r=o,0===xt&&Ct(Y)),r===o&&(r=j),r!==o){if(n=[],(i=ur())!==o)for(;i!==o;)n.push(i),i=ur();else n=u;n!==o?(i=St,xt++,46===t.charCodeAt(St)?(a=E,St++):(a=o,0===xt&&Ct(_)),xt--,a===o?i=f:(St=i,i=u),i!==o?(Et=e,e=r=J(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;if(e===o)if(e=St,45===t.charCodeAt(St)?(r=Z,St++):(r=o,0===xt&&Ct(ee)),r!==o){if(n=[],(i=ur())!==o)for(;i!==o;)n.push(i),i=ur();else n=u;n!==o?(i=St,xt++,46===t.charCodeAt(St)?(a=E,St++):(a=o,0===xt&&Ct(_)),xt--,a===o?i=f:(St=i,i=u),i!==o?(Et=e,e=r=te(n)):(St=e,e=u)):(St=e,e=u)}else St=e,e=u;return At[s]={nextPos:St,result:e},e}function Yt(){var e,t,r,n,i,a=49*St+29,s=At[a];if(s)return St=s.nextPos,s.result;for(e=St,t=[],r=Zt();r!==o;)t.push(r),r=Zt();if(t!==o)if((r=qt())!==o){for(n=[],i=Zt();i!==o;)n.push(i),i=Zt();n!==o?(Et=e,e=t=de(r)):(St=e,e=u)}else St=e,e=u;else St=e,e=u;return At[a]={nextPos:St,result:e},e}function Jt(){var e,r,n,i,a,s,c,l=49*St+30,f=At[l];if(f)return St=f.nextPos,f.result;for(e=St,r=[],n=Zt();n!==o;)r.push(n),n=Zt();if(r!==o)if((n=qt())!==o){for(i=[],a=Zt();a!==o;)i.push(a),a=Zt();if(i!==o)if(44===t.charCodeAt(St)?(a=he,St++):(a=o,0===xt&&Ct(ye)),a!==o){for(s=[],c=Zt();c!==o;)s.push(c),c=Zt();s!==o?(Et=e,e=r=de(n)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u;return At[l]={nextPos:St,result:e},e}function Zt(){var e,t=49*St+31,r=At[t];return r?(St=r.nextPos,r.result):((e=nr())===o&&(e=or())===o&&(e=Nt()),At[t]={nextPos:St,result:e},e)}function er(){var e,r,n,i,a,s,c,l,f,p,d,h=49*St+33,y=At[h];if(y)return St=y.nextPos,y.result;for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Ft())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(61===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&Ct(T)),a!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();if(s!==o)if((c=qt())!==o){for(l=[],f=nr();f!==o;)l.push(f),f=nr();if(l!==o)if(44===t.charCodeAt(St)?(f=he,St++):(f=o,0===xt&&Ct(ye)),f!==o){for(p=[],d=nr();d!==o;)p.push(d),d=nr();p!==o?(Et=e,e=r=Se(n,c)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u;if(e===o){for(e=St,r=[],n=nr();n!==o;)r.push(n),n=nr();if(r!==o)if((n=Ft())!==o){for(i=[],a=nr();a!==o;)i.push(a),a=nr();if(i!==o)if(61===t.charCodeAt(St)?(a=k,St++):(a=o,0===xt&&Ct(T)),a!==o){for(s=[],c=nr();c!==o;)s.push(c),c=nr();s!==o&&(c=qt())!==o?(Et=e,e=r=Se(n,c)):(St=e,e=u)}else St=e,e=u;else St=e,e=u}else St=e,e=u;else St=e,e=u}return At[h]={nextPos:St,result:e},e}function tr(){var e,r,n,i=49*St+34,a=At[i];return a?(St=a.nextPos,a.result):(e=St,46===t.charCodeAt(St)?(r=E,St++):(r=o,0===xt&&Ct(_)),r!==o&&(n=lr())!==o?(Et=e,e=r=Ee(n)):(St=e,e=u),At[i]={nextPos:St,result:e},e)}function rr(){var e,r,n,i,a,s,c,l,f,p,d,h,y=49*St+35,m=At[y];return m?(St=m.nextPos,m.result):(e=St,r=St,(n=ur())!==o&&(i=ur())!==o&&(a=ur())!==o&&(s=ur())!==o?(45===t.charCodeAt(St)?(c=Z,St++):(c=o,0===xt&&Ct(ee)),c!==o&&(l=ur())!==o&&(f=ur())!==o?(45===t.charCodeAt(St)?(p=Z,St++):(p=o,0===xt&&Ct(ee)),p!==o&&(d=ur())!==o&&(h=ur())!==o?r=n=[n,i,a,s,c,l,f,p,d,h]:(St=r,r=u)):(St=r,r=u)):(St=r,r=u),r!==o&&(Et=e,r=_e(r)),e=r,At[y]={nextPos:St,result:e},e)}function nr(){var e,r=49*St+39,n=At[r];return n?(St=n.nextPos,n.result):(Ie.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&Ct(Le)),At[r]={nextPos:St,result:e},e)}function or(){var e,r,n,i=49*St+40,a=At[i];return a?(St=a.nextPos,a.result):(10===t.charCodeAt(St)?(e=Be,St++):(e=o,0===xt&&Ct(Ne)),e===o&&(e=St,13===t.charCodeAt(St)?(r=Ue,St++):(r=o,0===xt&&Ct(Me)),r!==o?(10===t.charCodeAt(St)?(n=Be,St++):(n=o,0===xt&&Ct(Ne)),n!==o?e=r=[r,n]:(St=e,e=u)):(St=e,e=u)),At[i]={nextPos:St,result:e},e)}function ir(){var e,t=49*St+41,r=At[t];return r?(St=r.nextPos,r.result):((e=or())===o&&(e=nr()),At[t]={nextPos:St,result:e},e)}function ar(){var e,r,n=49*St+42,i=At[n];return i?(St=i.nextPos,i.result):(e=St,xt++,t.length>St?(r=t.charAt(St),St++):(r=o,0===xt&&Ct(p)),xt--,r===o?e=f:(St=e,e=u),At[n]={nextPos:St,result:e},e)}function sr(){var e,r=49*St+43,n=At[r];return n?(St=n.nextPos,n.result):(De.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&Ct(Fe)),At[r]={nextPos:St,result:e},e)}function ur(){var e,r,n=49*St+44,i=At[n];return i?(St=i.nextPos,i.result):(Ve.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&Ct(qe)),e===o&&(e=St,95===t.charCodeAt(St)?(r=Ke,St++):(r=o,0===xt&&Ct(He)),r!==o&&(Et=e,r=ze()),e=r),At[n]={nextPos:St,result:e},e)}function cr(){var e,r=49*St+45,n=At[r];return n?(St=n.nextPos,n.result):(Xe.test(t.charAt(St))?(e=t.charAt(St),St++):(e=o,0===xt&&Ct(Ge)),At[r]={nextPos:St,result:e},e)}function lr(){var e,t,r,n=49*St+46,i=At[n];if(i)return St=i.nextPos,i.result;if(e=St,t=[],(r=ur())!==o)for(;r!==o;)t.push(r),r=ur();else t=u;return t!==o&&(Et=e,t=We(t)),e=t,At[n]={nextPos:St,result:e},e}function fr(){var e,r,n=49*St+47,i=At[n];return i?(St=i.nextPos,i.result):(e=St,t.substr(St,2)===$e?(r=$e,St+=2):(r=o,0===xt&&Ct(Qe)),r!==o&&(Et=e,r=Ye()),(e=r)===o&&(e=St,t.substr(St,2)===Je?(r=Je,St+=2):(r=o,0===xt&&Ct(Ze)),r!==o&&(Et=e,r=et()),(e=r)===o&&(e=St,t.substr(St,2)===tt?(r=tt,St+=2):(r=o,0===xt&&Ct(rt)),r!==o&&(Et=e,r=nt()),(e=r)===o&&(e=St,t.substr(St,2)===ot?(r=ot,St+=2):(r=o,0===xt&&Ct(it)),r!==o&&(Et=e,r=at()),(e=r)===o&&(e=St,t.substr(St,2)===st?(r=st,St+=2):(r=o,0===xt&&Ct(ut)),r!==o&&(Et=e,r=ct()),(e=r)===o&&(e=St,t.substr(St,2)===lt?(r=lt,St+=2):(r=o,0===xt&&Ct(ft)),r!==o&&(Et=e,r=pt()),(e=r)===o&&(e=St,t.substr(St,2)===dt?(r=dt,St+=2):(r=o,0===xt&&Ct(ht)),r!==o&&(Et=e,r=yt()),(e=r)===o&&(e=function(){var e,r,n,i,a,s,c,l,f,p,d,h=49*St+48,y=At[h];if(y)return St=y.nextPos,y.result;e=St,t.substr(St,2)===mt?(r=mt,St+=2):(r=o,0===xt&&Ct(vt));r!==o?(n=St,(i=sr())!==o&&(a=sr())!==o&&(s=sr())!==o&&(c=sr())!==o&&(l=sr())!==o&&(f=sr())!==o&&(p=sr())!==o&&(d=sr())!==o?n=i=[i,a,s,c,l,f,p,d]:(St=n,n=u),n!==o?(Et=e,e=r=gt(n)):(St=e,e=u)):(St=e,e=u);e===o&&(e=St,t.substr(St,2)===bt?(r=bt,St+=2):(r=o,0===xt&&Ct(wt)),r!==o?(n=St,(i=sr())!==o&&(a=sr())!==o&&(s=sr())!==o&&(c=sr())!==o?n=i=[i,a,s,c]:(St=n,n=u),n!==o?(Et=e,e=r=gt(n)):(St=e,e=u)):(St=e,e=u));return At[h]={nextPos:St,result:e},e}()))))))),At[n]={nextPos:St,result:e},e)}var pr=[];function dr(e){pr.push(e)}function hr(e,t,r,n,o){var i={type:e,value:t,line:r(),column:n()};return o&&(i.key=o),i}if((r=a())!==o&&St===t.length)return r;throw r!==o&&St1);s++)r.splice(0,1);n[a]=r.join("")}var u=-1,c=0,l=0,f=-1,p=!1;for(a=0;ac&&(u=f,c=l)):"0"===n[a]&&(p=!0,f=a,l=1);l>c&&(u=f,c=l),c>1&&n.splice(u,c,""),o=n.length;var d="";for(""===n[0]&&(d=":"),a=0;a=e.length-1)return!1;var n=e.lastIndexOf(".",t-1);if(n<=0||n>=t-1)return!1;var o=r.list[e.slice(t+1)];return!!o&&o.indexOf(" "+e.slice(n+1,t)+" ")>=0},is:function(e){var t=e.lastIndexOf(".");if(t<=0||t>=e.length-1)return!1;if(e.lastIndexOf(".",t-1)>=0)return!1;var n=r.list[e.slice(t+1)];return!!n&&n.indexOf(" "+e.slice(0,t)+" ")>=0},get:function(e){var t=e.lastIndexOf(".");if(t<=0||t>=e.length-1)return null;var n=e.lastIndexOf(".",t-1);if(n<=0||n>=t-1)return null;var o=r.list[e.slice(t+1)];return o?o.indexOf(" "+e.slice(n+1,t)+" ")<0?null:e.slice(n+1):null},noConflict:function(){return e.SecondLevelDomains===this&&(e.SecondLevelDomains=t),this}};return r}))},4193:function(e,t,r){var n,o,i;!function(a,s){"use strict";e.exports?e.exports=s(r(9340),r(1430),r(4704)):(o=[r(9340),r(1430),r(4704)],void 0===(i="function"==typeof(n=s)?n.apply(t,o):n)||(e.exports=i))}(0,(function(e,t,r,n){"use strict";var o=n&&n.URI;function i(e,t){var r=arguments.length>=1;if(!(this instanceof i))return r?arguments.length>=2?new i(e,t):new i(e):new i;if(void 0===e){if(r)throw new TypeError("undefined is not a valid argument for URI");e="undefined"!=typeof location?location.href+"":""}if(null===e&&r)throw new TypeError("null is not a valid argument for URI");return this.href(e),void 0!==t?this.absoluteTo(t):this}i.version="1.19.11";var a=i.prototype,s=Object.prototype.hasOwnProperty;function u(e){return e.replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")}function c(e){return void 0===e?"Undefined":String(Object.prototype.toString.call(e)).slice(8,-1)}function l(e){return"Array"===c(e)}function f(e,t){var r,n,o={};if("RegExp"===c(t))o=null;else if(l(t))for(r=0,n=t.length;r]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?\xab\xbb\u201c\u201d\u2018\u2019]))/gi,i.findUri={start:/\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,end:/[\s\r\n]|$/,trim:/[`!()\[\]{};:'".,<>?\xab\xbb\u201c\u201d\u201e\u2018\u2019]+$/,parens:/(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g},i.leading_whitespace_expression=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,i.ascii_tab_whitespace=/[\u0009\u000A\u000D]+/g,i.defaultPorts={http:"80",https:"443",ftp:"21",gopher:"70",ws:"80",wss:"443"},i.hostProtocols=["http","https"],i.invalid_hostname_characters=/[^a-zA-Z0-9\.\-:_]/,i.domAttributes={a:"href",blockquote:"cite",link:"href",base:"href",script:"src",form:"action",img:"src",area:"href",iframe:"src",embed:"src",source:"src",track:"src",input:"src",audio:"src",video:"src"},i.getDomAttribute=function(e){if(e&&e.nodeName){var t=e.nodeName.toLowerCase();if("input"!==t||"image"===e.type)return i.domAttributes[t]}},i.encode=m,i.decode=decodeURIComponent,i.iso8859=function(){i.encode=escape,i.decode=unescape},i.unicode=function(){i.encode=m,i.decode=decodeURIComponent},i.characters={pathname:{encode:{expression:/%(24|26|2B|2C|3B|3D|3A|40)/gi,map:{"%24":"$","%26":"&","%2B":"+","%2C":",","%3B":";","%3D":"=","%3A":":","%40":"@"}},decode:{expression:/[\/\?#]/g,map:{"/":"%2F","?":"%3F","#":"%23"}}},reserved:{encode:{expression:/%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/gi,map:{"%3A":":","%2F":"/","%3F":"?","%23":"#","%5B":"[","%5D":"]","%40":"@","%21":"!","%24":"$","%26":"&","%27":"'","%28":"(","%29":")","%2A":"*","%2B":"+","%2C":",","%3B":";","%3D":"="}}},urnpath:{encode:{expression:/%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/gi,map:{"%21":"!","%24":"$","%27":"'","%28":"(","%29":")","%2A":"*","%2B":"+","%2C":",","%3B":";","%3D":"=","%40":"@"}},decode:{expression:/[\/\?#:]/g,map:{"/":"%2F","?":"%3F","#":"%23",":":"%3A"}}}},i.encodeQuery=function(e,t){var r=i.encode(e+"");return void 0===t&&(t=i.escapeQuerySpace),t?r.replace(/%20/g,"+"):r},i.decodeQuery=function(e,t){e+="",void 0===t&&(t=i.escapeQuerySpace);try{return i.decode(t?e.replace(/\+/g,"%20"):e)}catch(t){return e}};var v,g={encode:"encode",decode:"decode"},b=function(e,t){return function(r){try{return i[t](r+"").replace(i.characters[e][t].expression,(function(r){return i.characters[e][t].map[r]}))}catch(e){return r}}};for(v in g)i[v+"PathSegment"]=b("pathname",g[v]),i[v+"UrnPathSegment"]=b("urnpath",g[v]);var w=function(e,t,r){return function(n){var o;o=r?function(e){return i[t](i[r](e))}:i[t];for(var a=(n+"").split(e),s=0,u=a.length;s-1&&(t.fragment=e.substring(r+1)||null,e=e.substring(0,r)),(r=e.indexOf("?"))>-1&&(t.query=e.substring(r+1)||null,e=e.substring(0,r)),"//"===(e=(e=e.replace(/^(https?|ftp|wss?)?:+[/\\]*/i,"$1://")).replace(/^[/\\]{2,}/i,"//")).substring(0,2)?(t.protocol=null,e=e.substring(2),e=i.parseAuthority(e,t)):(r=e.indexOf(":"))>-1&&(t.protocol=e.substring(0,r)||null,t.protocol&&!t.protocol.match(i.protocol_expression)?t.protocol=void 0:"//"===e.substring(r+1,r+3).replace(/\\/g,"/")?(e=e.substring(r+3),e=i.parseAuthority(e,t)):(e=e.substring(r+1),t.urn=!0)),t.path=e,t},i.parseHost=function(e,t){e||(e="");var r,n,o=(e=e.replace(/\\/g,"/")).indexOf("/");if(-1===o&&(o=e.length),"["===e.charAt(0))r=e.indexOf("]"),t.hostname=e.substring(1,r)||null,t.port=e.substring(r+2,o)||null,"/"===t.port&&(t.port=null);else{var a=e.indexOf(":"),s=e.indexOf("/"),u=e.indexOf(":",a+1);-1!==u&&(-1===s||u-1?o:e.length-1);return a>-1&&(-1===o||a-1?d.slice(0,h)+d.slice(h).replace(a,""):d.replace(a,"")).length<=c[0].length||r.ignore&&r.ignore.test(d))){var v=t(d,l,p=l+d.length,e);void 0!==v?(v=String(v),e=e.slice(0,l)+v+e.slice(p),n.lastIndex=l+v.length):n.lastIndex=p}}return n.lastIndex=0,e},i.ensureValidHostname=function(t,r){var n=!!t,o=!1;if(!!r&&(o=p(i.hostProtocols,r)),o&&!n)throw new TypeError("Hostname cannot be empty, if protocol is "+r);if(t&&t.match(i.invalid_hostname_characters)){if(!e)throw new TypeError('Hostname "'+t+'" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');if(e.toASCII(t).match(i.invalid_hostname_characters))throw new TypeError('Hostname "'+t+'" contains characters other than [A-Z0-9.-:_]')}},i.ensureValidPort=function(e){if(e){var t=Number(e);if(!(/^[0-9]+$/.test(t)&&t>0&&t<65536))throw new TypeError('Port "'+e+'" is not a valid port')}},i.noConflict=function(e){if(e){var t={URI:this.noConflict()};return n.URITemplate&&"function"==typeof n.URITemplate.noConflict&&(t.URITemplate=n.URITemplate.noConflict()),n.IPv6&&"function"==typeof n.IPv6.noConflict&&(t.IPv6=n.IPv6.noConflict()),n.SecondLevelDomains&&"function"==typeof n.SecondLevelDomains.noConflict&&(t.SecondLevelDomains=n.SecondLevelDomains.noConflict()),t}return n.URI===this&&(n.URI=o),this},a.build=function(e){return!0===e?this._deferred_build=!0:(void 0===e||this._deferred_build)&&(this._string=i.build(this._parts),this._deferred_build=!1),this},a.clone=function(){return new i(this)},a.valueOf=a.toString=function(){return this.build(!1)._string},a.protocol=S("protocol"),a.username=S("username"),a.password=S("password"),a.hostname=S("hostname"),a.port=S("port"),a.query=E("query","?"),a.fragment=E("fragment","#"),a.search=function(e,t){var r=this.query(e,t);return"string"==typeof r&&r.length?"?"+r:r},a.hash=function(e,t){var r=this.fragment(e,t);return"string"==typeof r&&r.length?"#"+r:r},a.pathname=function(e,t){if(void 0===e||!0===e){var r=this._parts.path||(this._parts.hostname?"/":"");return e?(this._parts.urn?i.decodeUrnPath:i.decodePath)(r):r}return this._parts.urn?this._parts.path=e?i.recodeUrnPath(e):"":this._parts.path=e?i.recodePath(e):"/",this.build(!t),this},a.path=a.pathname,a.href=function(e,t){var r;if(void 0===e)return this.toString();this._string="",this._parts=i._parts();var n=e instanceof i,o="object"==typeof e&&(e.hostname||e.path||e.pathname);e.nodeName&&(e=e[i.getDomAttribute(e)]||"",o=!1);if(!n&&o&&void 0!==e.pathname&&(e=e.toString()),"string"==typeof e||e instanceof String)this._parts=i.parse(String(e),this._parts);else{if(!n&&!o)throw new TypeError("invalid input");var a=n?e._parts:e;for(r in a)"query"!==r&&s.call(this._parts,r)&&(this._parts[r]=a[r]);a.query&&this.query(a.query,!1)}return this.build(!t),this},a.is=function(e){var t=!1,n=!1,o=!1,a=!1,s=!1,u=!1,c=!1,l=!this._parts.urn;switch(this._parts.hostname&&(l=!1,n=i.ip4_expression.test(this._parts.hostname),o=i.ip6_expression.test(this._parts.hostname),s=(a=!(t=n||o))&&r&&r.has(this._parts.hostname),u=a&&i.idn_expression.test(this._parts.hostname),c=a&&i.punycode_expression.test(this._parts.hostname)),e.toLowerCase()){case"relative":return l;case"absolute":return!l;case"domain":case"name":return a;case"sld":return s;case"ip":return t;case"ip4":case"ipv4":case"inet4":return n;case"ip6":case"ipv6":case"inet6":return o;case"idn":return u;case"url":return!this._parts.urn;case"urn":return!!this._parts.urn;case"punycode":return c}return null};var _=a.protocol,k=a.port,T=a.hostname;a.protocol=function(e,t){if(e&&!(e=e.replace(/:(\/\/)?$/,"")).match(i.protocol_expression))throw new TypeError('Protocol "'+e+"\" contains characters other than [A-Z0-9.+-] or doesn't start with [A-Z]");return _.call(this,e,t)},a.scheme=a.protocol,a.port=function(e,t){return this._parts.urn?void 0===e?"":this:(void 0!==e&&(0===e&&(e=null),e&&(":"===(e+="").charAt(0)&&(e=e.substring(1)),i.ensureValidPort(e))),k.call(this,e,t))},a.hostname=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0!==e){var r={preventInvalidHostname:this._parts.preventInvalidHostname};if("/"!==i.parseHost(e,r))throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');e=r.hostname,this._parts.preventInvalidHostname&&i.ensureValidHostname(e,this._parts.protocol)}return T.call(this,e,t)},a.origin=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e){var r=this.protocol();return this.authority()?(r?r+"://":"")+this.authority():""}var n=i(e);return this.protocol(n.protocol()).authority(n.authority()).build(!t),this},a.host=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e)return this._parts.hostname?i.buildHost(this._parts):"";if("/"!==i.parseHost(e,this._parts))throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');return this.build(!t),this},a.authority=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e)return this._parts.hostname?i.buildAuthority(this._parts):"";if("/"!==i.parseAuthority(e,this._parts))throw new TypeError('Hostname "'+e+'" contains characters other than [A-Z0-9.-]');return this.build(!t),this},a.userinfo=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e){var r=i.buildUserinfo(this._parts);return r?r.substring(0,r.length-1):r}return"@"!==e[e.length-1]&&(e+="@"),i.parseUserinfo(e,this._parts),this.build(!t),this},a.resource=function(e,t){var r;return void 0===e?this.path()+this.search()+this.hash():(r=i.parse(e),this._parts.path=r.path,this._parts.query=r.query,this._parts.fragment=r.fragment,this.build(!t),this)},a.subdomain=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e){if(!this._parts.hostname||this.is("IP"))return"";var r=this._parts.hostname.length-this.domain().length-1;return this._parts.hostname.substring(0,r)||""}var n=this._parts.hostname.length-this.domain().length,o=this._parts.hostname.substring(0,n),a=new RegExp("^"+u(o));if(e&&"."!==e.charAt(e.length-1)&&(e+="."),-1!==e.indexOf(":"))throw new TypeError("Domains cannot contain colons");return e&&i.ensureValidHostname(e,this._parts.protocol),this._parts.hostname=this._parts.hostname.replace(a,e),this.build(!t),this},a.domain=function(e,t){if(this._parts.urn)return void 0===e?"":this;if("boolean"==typeof e&&(t=e,e=void 0),void 0===e){if(!this._parts.hostname||this.is("IP"))return"";var r=this._parts.hostname.match(/\./g);if(r&&r.length<2)return this._parts.hostname;var n=this._parts.hostname.length-this.tld(t).length-1;return n=this._parts.hostname.lastIndexOf(".",n-1)+1,this._parts.hostname.substring(n)||""}if(!e)throw new TypeError("cannot set domain empty");if(-1!==e.indexOf(":"))throw new TypeError("Domains cannot contain colons");if(i.ensureValidHostname(e,this._parts.protocol),!this._parts.hostname||this.is("IP"))this._parts.hostname=e;else{var o=new RegExp(u(this.domain())+"$");this._parts.hostname=this._parts.hostname.replace(o,e)}return this.build(!t),this},a.tld=function(e,t){if(this._parts.urn)return void 0===e?"":this;if("boolean"==typeof e&&(t=e,e=void 0),void 0===e){if(!this._parts.hostname||this.is("IP"))return"";var n=this._parts.hostname.lastIndexOf("."),o=this._parts.hostname.substring(n+1);return!0!==t&&r&&r.list[o.toLowerCase()]&&r.get(this._parts.hostname)||o}var i;if(!e)throw new TypeError("cannot set TLD empty");if(e.match(/[^a-zA-Z0-9-]/)){if(!r||!r.is(e))throw new TypeError('TLD "'+e+'" contains characters other than [A-Z0-9]');i=new RegExp(u(this.tld())+"$"),this._parts.hostname=this._parts.hostname.replace(i,e)}else{if(!this._parts.hostname||this.is("IP"))throw new ReferenceError("cannot set TLD on non-domain host");i=new RegExp(u(this.tld())+"$"),this._parts.hostname=this._parts.hostname.replace(i,e)}return this.build(!t),this},a.directory=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e||!0===e){if(!this._parts.path&&!this._parts.hostname)return"";if("/"===this._parts.path)return"/";var r=this._parts.path.length-this.filename().length-1,n=this._parts.path.substring(0,r)||(this._parts.hostname?"/":"");return e?i.decodePath(n):n}var o=this._parts.path.length-this.filename().length,a=this._parts.path.substring(0,o),s=new RegExp("^"+u(a));return this.is("relative")||(e||(e="/"),"/"!==e.charAt(0)&&(e="/"+e)),e&&"/"!==e.charAt(e.length-1)&&(e+="/"),e=i.recodePath(e),this._parts.path=this._parts.path.replace(s,e),this.build(!t),this},a.filename=function(e,t){if(this._parts.urn)return void 0===e?"":this;if("string"!=typeof e){if(!this._parts.path||"/"===this._parts.path)return"";var r=this._parts.path.lastIndexOf("/"),n=this._parts.path.substring(r+1);return e?i.decodePathSegment(n):n}var o=!1;"/"===e.charAt(0)&&(e=e.substring(1)),e.match(/\.?\//)&&(o=!0);var a=new RegExp(u(this.filename())+"$");return e=i.recodePath(e),this._parts.path=this._parts.path.replace(a,e),o?this.normalizePath(t):this.build(!t),this},a.suffix=function(e,t){if(this._parts.urn)return void 0===e?"":this;if(void 0===e||!0===e){if(!this._parts.path||"/"===this._parts.path)return"";var r,n,o=this.filename(),a=o.lastIndexOf(".");return-1===a?"":(r=o.substring(a+1),n=/^[a-z0-9%]+$/i.test(r)?r:"",e?i.decodePathSegment(n):n)}"."===e.charAt(0)&&(e=e.substring(1));var s,c=this.suffix();if(c)s=e?new RegExp(u(c)+"$"):new RegExp(u("."+c)+"$");else{if(!e)return this;this._parts.path+="."+i.recodePath(e)}return s&&(e=i.recodePath(e),this._parts.path=this._parts.path.replace(s,e)),this.build(!t),this},a.segment=function(e,t,r){var n=this._parts.urn?":":"/",o=this.path(),i="/"===o.substring(0,1),a=o.split(n);if(void 0!==e&&"number"!=typeof e&&(r=t,t=e,e=void 0),void 0!==e&&"number"!=typeof e)throw new Error('Bad segment "'+e+'", must be 0-based integer');if(i&&a.shift(),e<0&&(e=Math.max(a.length+e,0)),void 0===t)return void 0===e?a:a[e];if(null===e||void 0===a[e])if(l(t)){a=[];for(var s=0,u=t.length;s{}"`^| \\]/,o.expand=function(e,t,r){var n,i,a,u=s[e.operator],c=u.named?"Named":"Unnamed",l=e.variables,f=[];for(a=0;i=l[a];a++){if(0===(n=t.get(i.name)).type&&r&&r.strict)throw new Error('Missing expansion value for variable "'+i.name+'"');if(n.val.length){if(n.type>1&&i.maxlength)throw new Error('Invalid expression: Prefix modifier not applicable to variable "'+i.name+'"');f.push(o["expand"+c](n,u,i.explode,i.explode&&u.separator||",",i.maxlength,i.name))}else n.type&&f.push("")}return f.length?u.prefix+f.join(u.separator):""},o.expandNamed=function(t,r,n,o,i,a){var s,u,c,l="",f=r.encode,p=r.empty_name_separator,d=!t[f].length,h=2===t.type?"":e[f](a);for(u=0,c=t.val.length;u= 0x80 (not a basic code point)","invalid-input":"Invalid input"},p=Math.floor,d=String.fromCharCode;function h(e){throw new RangeError(f[e])}function y(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function m(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+y((e=e.replace(l,".")).split("."),t).join(".")}function v(e){for(var t,r,n=[],o=0,i=e.length;o=55296&&t<=56319&&o65535&&(t+=d((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=d(e)})).join("")}function b(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function w(e,t,r){var n=0;for(e=r?p(e/700):e>>1,e+=p(e/t);e>455;n+=s)e=p(e/35);return p(n+36*e/(e+38))}function S(e){var t,r,n,o,i,u,c,l,f,d,y,m=[],v=e.length,b=0,S=128,E=72;for((r=e.lastIndexOf("-"))<0&&(r=0),n=0;n=128&&h("not-basic"),m.push(e.charCodeAt(n));for(o=r>0?r+1:0;o=v&&h("invalid-input"),((l=(y=e.charCodeAt(o++))-48<10?y-22:y-65<26?y-65:y-97<26?y-97:s)>=s||l>p((a-b)/u))&&h("overflow"),b+=l*u,!(l<(f=c<=E?1:c>=E+26?26:c-E));c+=s)u>p(a/(d=s-f))&&h("overflow"),u*=d;E=w(b-i,t=m.length+1,0==i),p(b/t)>a-S&&h("overflow"),S+=p(b/t),b%=t,m.splice(b++,0,S)}return g(m)}function E(e){var t,r,n,o,i,u,c,l,f,y,m,g,S,E,_,k=[];for(g=(e=v(e)).length,t=128,r=0,i=72,u=0;u=t&&mp((a-r)/(S=n+1))&&h("overflow"),r+=(c-t)*S,t=c,u=0;ua&&h("overflow"),m==t){for(l=r,f=s;!(l<(y=f<=i?1:f>=i+26?26:f-i));f+=s)_=l-y,E=s-y,k.push(d(b(y+_%E,0))),l=p(_/E);k.push(d(b(l,0))),i=w(r,S,n==o),r=0,++n}++r,++t}return k.join("")}i={version:"1.3.2",ucs2:{decode:v,encode:g},decode:S,encode:E,toASCII:function(e){return m(e,(function(e){return c.test(e)?"xn--"+E(e):e}))},toUnicode:function(e){return m(e,(function(e){return u.test(e)?S(e.slice(4).toLowerCase()):e}))}},void 0===(n=function(){return i}.call(t,r,t,e))||(e.exports=n)}()},1270:function(e,t,r){var n;e=r.nmd(e),function(){t&&t.nodeType,e&&e.nodeType;var o="object"==typeof r.g&&r.g;o.global!==o&&o.window!==o&&o.self;var i,a=2147483647,s=36,u=/^xn--/,c=/[^\x20-\x7E]/,l=/[\x2E\u3002\uFF0E\uFF61]/g,f={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},p=Math.floor,d=String.fromCharCode;function h(e){throw new RangeError(f[e])}function y(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function m(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+y((e=e.replace(l,".")).split("."),t).join(".")}function v(e){for(var t,r,n=[],o=0,i=e.length;o=55296&&t<=56319&&o65535&&(t+=d((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=d(e)})).join("")}function b(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function w(e,t,r){var n=0;for(e=r?p(e/700):e>>1,e+=p(e/t);e>455;n+=s)e=p(e/35);return p(n+36*e/(e+38))}function S(e){var t,r,n,o,i,u,c,l,f,d,y,m=[],v=e.length,b=0,S=128,E=72;for((r=e.lastIndexOf("-"))<0&&(r=0),n=0;n=128&&h("not-basic"),m.push(e.charCodeAt(n));for(o=r>0?r+1:0;o=v&&h("invalid-input"),((l=(y=e.charCodeAt(o++))-48<10?y-22:y-65<26?y-65:y-97<26?y-97:s)>=s||l>p((a-b)/u))&&h("overflow"),b+=l*u,!(l<(f=c<=E?1:c>=E+26?26:c-E));c+=s)u>p(a/(d=s-f))&&h("overflow"),u*=d;E=w(b-i,t=m.length+1,0==i),p(b/t)>a-S&&h("overflow"),S+=p(b/t),b%=t,m.splice(b++,0,S)}return g(m)}function E(e){var t,r,n,o,i,u,c,l,f,y,m,g,S,E,_,k=[];for(g=(e=v(e)).length,t=128,r=0,i=72,u=0;u=t&&mp((a-r)/(S=n+1))&&h("overflow"),r+=(c-t)*S,t=c,u=0;ua&&h("overflow"),m==t){for(l=r,f=s;!(l<(y=f<=i?1:f>=i+26?26:f-i));f+=s)_=l-y,E=s-y,k.push(d(b(y+_%E,0))),l=p(_/E);k.push(d(b(l,0))),i=w(r,S,n==o),r=0,++n}++r,++t}return k.join("")}i={version:"1.4.1",ucs2:{decode:v,encode:g},decode:S,encode:E,toASCII:function(e){return m(e,(function(e){return c.test(e)?"xn--"+E(e):e}))},toUnicode:function(e){return m(e,(function(e){return u.test(e)?S(e.slice(4).toLowerCase()):e}))}},void 0===(n=function(){return i}.call(t,r,t,e))||(e.exports=n)}()},8835:(e,t,r)=>{"use strict";var n=r(1270);function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var i=/^([a-z0-9.+-]+:)/i,a=/:[0-9]*$/,s=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,u=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),c=["'"].concat(u),l=["%","/","?",";","#"].concat(c),f=["/","?","#"],p=/^[+a-z0-9A-Z_-]{0,63}$/,d=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,h={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},m={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},v=r(5373);function g(e,t,r){if(e&&"object"==typeof e&&e instanceof o)return e;var n=new o;return n.parse(e,t,r),n}o.prototype.parse=function(e,t,r){if("string"!=typeof e)throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o=e.indexOf("?"),a=-1!==o&&o127?C+="x":C+=j[I];if(!C.match(p)){var B=P.slice(0,O),N=P.slice(O+1),U=j.match(d);U&&(B.push(U[1]),N.unshift(U[2])),N.length&&(g="/"+N.join(".")+g),this.hostname=B.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),A||(this.hostname=n.toASCII(this.hostname));var M=this.port?":"+this.port:"",D=this.hostname||"";this.host=D+M,this.href+=this.host,A&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==g[0]&&(g="/"+g))}if(!h[S])for(O=0,R=c.length;O0)&&r.host.split("@"))&&(r.auth=A.shift(),r.hostname=A.shift(),r.host=r.hostname);return r.search=e.search,r.query=e.query,null===r.pathname&&null===r.search||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!E.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var k=E.slice(-1)[0],T=(r.host||e.host||E.length>1)&&("."===k||".."===k)||""===k,O=0,x=E.length;x>=0;x--)"."===(k=E[x])?E.splice(x,1):".."===k?(E.splice(x,1),O++):O&&(E.splice(x,1),O--);if(!w&&!S)for(;O--;O)E.unshift("..");!w||""===E[0]||E[0]&&"/"===E[0].charAt(0)||E.unshift(""),T&&"/"!==E.join("/").substr(-1)&&E.push("");var A,P=""===E[0]||E[0]&&"/"===E[0].charAt(0);_&&(r.hostname=P?"":E.length?E.shift():"",r.host=r.hostname,(A=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=A.shift(),r.hostname=A.shift(),r.host=r.hostname));return(w=w||r.host&&E.length)&&!P&&E.unshift(""),E.length>0?r.pathname=E.join("/"):(r.pathname=null,r.path=null),null===r.pathname&&null===r.search||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=e.auth||r.auth,r.slashes=r.slashes||e.slashes,r.href=r.format(),r},o.prototype.parseHost=function(){var e=this.host,t=a.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)},t.parse=g,t.resolve=function(e,t){return g(e,!1,!0).resolve(t)},t.resolveObject=function(e,t){return e?g(e,!1,!0).resolveObject(t):t},t.format=function(e){return"string"==typeof e&&(e=g(e)),e instanceof o?e.format():o.prototype.format.call(e)},t.Url=o},4643:(e,t,r)=>{function n(e){try{if(!r.g.localStorage)return!1}catch(e){return!1}var t=r.g.localStorage[e];return null!=t&&"true"===String(t).toLowerCase()}e.exports=function(e,t){if(n("noDeprecation"))return e;var r=!1;return function(){if(!r){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}}},1135:e=>{e.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},9032:(e,t,r)=>{"use strict";var n=r(7244),o=r(8184),i=r(5767),a=r(5680);function s(e){return e.call.bind(e)}var u="undefined"!=typeof BigInt,c="undefined"!=typeof Symbol,l=s(Object.prototype.toString),f=s(Number.prototype.valueOf),p=s(String.prototype.valueOf),d=s(Boolean.prototype.valueOf);if(u)var h=s(BigInt.prototype.valueOf);if(c)var y=s(Symbol.prototype.valueOf);function m(e,t){if("object"!=typeof e)return!1;try{return t(e),!0}catch(e){return!1}}function v(e){return"[object Map]"===l(e)}function g(e){return"[object Set]"===l(e)}function b(e){return"[object WeakMap]"===l(e)}function w(e){return"[object WeakSet]"===l(e)}function S(e){return"[object ArrayBuffer]"===l(e)}function E(e){return"undefined"!=typeof ArrayBuffer&&(S.working?S(e):e instanceof ArrayBuffer)}function _(e){return"[object DataView]"===l(e)}function k(e){return"undefined"!=typeof DataView&&(_.working?_(e):e instanceof DataView)}t.isArgumentsObject=n,t.isGeneratorFunction=o,t.isTypedArray=a,t.isPromise=function(e){return"undefined"!=typeof Promise&&e instanceof Promise||null!==e&&"object"==typeof e&&"function"==typeof e.then&&"function"==typeof e.catch},t.isArrayBufferView=function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):a(e)||k(e)},t.isUint8Array=function(e){return"Uint8Array"===i(e)},t.isUint8ClampedArray=function(e){return"Uint8ClampedArray"===i(e)},t.isUint16Array=function(e){return"Uint16Array"===i(e)},t.isUint32Array=function(e){return"Uint32Array"===i(e)},t.isInt8Array=function(e){return"Int8Array"===i(e)},t.isInt16Array=function(e){return"Int16Array"===i(e)},t.isInt32Array=function(e){return"Int32Array"===i(e)},t.isFloat32Array=function(e){return"Float32Array"===i(e)},t.isFloat64Array=function(e){return"Float64Array"===i(e)},t.isBigInt64Array=function(e){return"BigInt64Array"===i(e)},t.isBigUint64Array=function(e){return"BigUint64Array"===i(e)},v.working="undefined"!=typeof Map&&v(new Map),t.isMap=function(e){return"undefined"!=typeof Map&&(v.working?v(e):e instanceof Map)},g.working="undefined"!=typeof Set&&g(new Set),t.isSet=function(e){return"undefined"!=typeof Set&&(g.working?g(e):e instanceof Set)},b.working="undefined"!=typeof WeakMap&&b(new WeakMap),t.isWeakMap=function(e){return"undefined"!=typeof WeakMap&&(b.working?b(e):e instanceof WeakMap)},w.working="undefined"!=typeof WeakSet&&w(new WeakSet),t.isWeakSet=function(e){return w(e)},S.working="undefined"!=typeof ArrayBuffer&&S(new ArrayBuffer),t.isArrayBuffer=E,_.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&_(new DataView(new ArrayBuffer(1),0,1)),t.isDataView=k;var T="undefined"!=typeof SharedArrayBuffer?SharedArrayBuffer:void 0;function O(e){return"[object SharedArrayBuffer]"===l(e)}function x(e){return void 0!==T&&(void 0===O.working&&(O.working=O(new T)),O.working?O(e):e instanceof T)}function A(e){return m(e,f)}function P(e){return m(e,p)}function R(e){return m(e,d)}function j(e){return u&&m(e,h)}function C(e){return c&&m(e,y)}t.isSharedArrayBuffer=x,t.isAsyncFunction=function(e){return"[object AsyncFunction]"===l(e)},t.isMapIterator=function(e){return"[object Map Iterator]"===l(e)},t.isSetIterator=function(e){return"[object Set Iterator]"===l(e)},t.isGeneratorObject=function(e){return"[object Generator]"===l(e)},t.isWebAssemblyCompiledModule=function(e){return"[object WebAssembly.Module]"===l(e)},t.isNumberObject=A,t.isStringObject=P,t.isBooleanObject=R,t.isBigIntObject=j,t.isSymbolObject=C,t.isBoxedPrimitive=function(e){return A(e)||P(e)||R(e)||j(e)||C(e)},t.isAnyArrayBuffer=function(e){return"undefined"!=typeof Uint8Array&&(E(e)||x(e))},["isProxy","isExternal","isModuleNamespaceObject"].forEach((function(e){Object.defineProperty(t,e,{enumerable:!1,value:function(){throw new Error(e+" is not supported in userland")}})}))},537:(e,t,r)=>{var n=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),r={},n=0;n=i)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}})),s=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),y(r)?n.showHidden=r:r&&t._extend(n,r),b(n.showHidden)&&(n.showHidden=!1),b(n.depth)&&(n.depth=2),b(n.colors)&&(n.colors=!1),b(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=c),f(n,e,n.depth)}function c(e,t){var r=u.styles[t];return r?"\x1b["+u.colors[r][0]+"m"+e+"\x1b["+u.colors[r][1]+"m":e}function l(e,t){return e}function f(e,r,n){if(e.customInspect&&r&&k(r.inspect)&&r.inspect!==t.inspect&&(!r.constructor||r.constructor.prototype!==r)){var o=r.inspect(n,e);return g(o)||(o=f(e,o,n)),o}var i=function(e,t){if(b(t))return e.stylize("undefined","undefined");if(g(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(v(t))return e.stylize(""+t,"number");if(y(t))return e.stylize(""+t,"boolean");if(m(t))return e.stylize("null","null")}(e,r);if(i)return i;var a=Object.keys(r),s=function(e){var t={};return e.forEach((function(e,r){t[e]=!0})),t}(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(r)),_(r)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return p(r);if(0===a.length){if(k(r)){var u=r.name?": "+r.name:"";return e.stylize("[Function"+u+"]","special")}if(w(r))return e.stylize(RegExp.prototype.toString.call(r),"regexp");if(E(r))return e.stylize(Date.prototype.toString.call(r),"date");if(_(r))return p(r)}var c,l="",S=!1,T=["{","}"];(h(r)&&(S=!0,T=["[","]"]),k(r))&&(l=" [Function"+(r.name?": "+r.name:"")+"]");return w(r)&&(l=" "+RegExp.prototype.toString.call(r)),E(r)&&(l=" "+Date.prototype.toUTCString.call(r)),_(r)&&(l=" "+p(r)),0!==a.length||S&&0!=r.length?n<0?w(r)?e.stylize(RegExp.prototype.toString.call(r),"regexp"):e.stylize("[Object]","special"):(e.seen.push(r),c=S?function(e,t,r,n,o){for(var i=[],a=0,s=t.length;a=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1}),0);if(n>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(c,l,T)):T[0]+l+T[1]}function p(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,r,n,o,i){var a,s,u;if((u=Object.getOwnPropertyDescriptor(t,o)||{value:t[o]}).get?s=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(s=e.stylize("[Setter]","special")),A(n,o)||(a="["+o+"]"),s||(e.seen.indexOf(u.value)<0?(s=m(r)?f(e,u.value,null):f(e,u.value,r-1)).indexOf("\n")>-1&&(s=i?s.split("\n").map((function(e){return" "+e})).join("\n").slice(2):"\n"+s.split("\n").map((function(e){return" "+e})).join("\n")):s=e.stylize("[Circular]","special")),b(a)){if(i&&o.match(/^\d+$/))return s;(a=JSON.stringify(""+o)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.slice(1,-1),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function h(e){return Array.isArray(e)}function y(e){return"boolean"==typeof e}function m(e){return null===e}function v(e){return"number"==typeof e}function g(e){return"string"==typeof e}function b(e){return void 0===e}function w(e){return S(e)&&"[object RegExp]"===T(e)}function S(e){return"object"==typeof e&&null!==e}function E(e){return S(e)&&"[object Date]"===T(e)}function _(e){return S(e)&&("[object Error]"===T(e)||e instanceof Error)}function k(e){return"function"==typeof e}function T(e){return Object.prototype.toString.call(e)}function O(e){return e<10?"0"+e.toString(10):e.toString(10)}t.debuglog=function(e){if(e=e.toUpperCase(),!i[e])if(a.test(e)){var r=process.pid;i[e]=function(){var n=t.format.apply(t,arguments);console.error("%s %d: %s",e,r,n)}}else i[e]=function(){};return i[e]},t.inspect=u,u.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},u.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},t.types=r(9032),t.isArray=h,t.isBoolean=y,t.isNull=m,t.isNullOrUndefined=function(e){return null==e},t.isNumber=v,t.isString=g,t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=b,t.isRegExp=w,t.types.isRegExp=w,t.isObject=S,t.isDate=E,t.types.isDate=E,t.isError=_,t.types.isNativeError=_,t.isFunction=k,t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=r(1135);var x=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function A(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.log=function(){var e,r;console.log("%s - %s",(e=new Date,r=[O(e.getHours()),O(e.getMinutes()),O(e.getSeconds())].join(":"),[e.getDate(),x[e.getMonth()],r].join(" ")),t.format.apply(t,arguments))},t.inherits=r(6698),t._extend=function(e,t){if(!t||!S(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e};var P="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function R(e,t){if(!e){var r=new Error("Promise was rejected with a falsy value");r.reason=e,e=r}return t(e)}t.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(P&&e[P]){var t;if("function"!=typeof(t=e[P]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(t,P,{value:t,enumerable:!1,writable:!1,configurable:!0}),t}function t(){for(var t,r,n=new Promise((function(e,n){t=e,r=n})),o=[],i=0;i{"use strict";var n=r(2682),o=r(9209),i=r(487),a=r(8075),s=r(5795),u=a("Object.prototype.toString"),c=r(9092)(),l="undefined"==typeof globalThis?r.g:globalThis,f=o(),p=a("String.prototype.slice"),d=Object.getPrototypeOf,h=a("Array.prototype.indexOf",!0)||function(e,t){for(var r=0;r-1?t:"Object"===t&&function(e){var t=!1;return n(y,(function(r,n){if(!t)try{r(e),t=p(n,1)}catch(e){}})),t}(e)}return s?function(e){var t=!1;return n(y,(function(r,n){if(!t)try{"$"+r(e)===n&&(t=p(n,1))}catch(e){}})),t}(e):null}},7510:e=>{e.exports=function(){for(var e={},r=0;r{},2634:()=>{},5340:()=>{},9838:()=>{},9209:(e,t,r)=>{"use strict";var n=r(6578),o="undefined"==typeof globalThis?r.g:globalThis;e.exports=function(){for(var e=[],t=0;t{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),r(1924)})())); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/dist/stellar-sdk.min.js.LICENSE.txt b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk.min.js.LICENSE.txt new file mode 100644 index 000000000..35726554b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/dist/stellar-sdk.min.js.LICENSE.txt @@ -0,0 +1,71 @@ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +/*! + * URI.js - Mutating URLs + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! + * URI.js - Mutating URLs + * IPv6 Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! + * URI.js - Mutating URLs + * Second Level Domain (SLD) Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! + * URI.js - Mutating URLs + * URI Template Support - http://tools.ietf.org/html/rfc6570 + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +/*! https://mths.be/punycode v1.4.0 by @mathias */ + +/*! https://mths.be/punycode v1.4.1 by @mathias */ + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + +/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ diff --git a/node_modules/@stellar/stellar-sdk/lib/browser.d.ts b/node_modules/@stellar/stellar-sdk/lib/browser.d.ts new file mode 100644 index 000000000..bfdbd32a2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/browser.d.ts @@ -0,0 +1,6 @@ +import { httpClient } from "./http-client"; +export * from "./index"; +export * as StellarBase from "@stellar/stellar-base"; +export { httpClient }; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/browser.js b/node_modules/@stellar/stellar-sdk/lib/browser.js new file mode 100644 index 000000000..f21e953f0 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/browser.js @@ -0,0 +1,35 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + httpClient: true, + StellarBase: true +}; +exports.default = exports.StellarBase = void 0; +Object.defineProperty(exports, "httpClient", { + enumerable: true, + get: function get() { + return _httpClient.httpClient; + } +}); +var _httpClient = require("./http-client"); +var _index = require("./index"); +Object.keys(_index).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _index[key]; + } + }); +}); +var _StellarBase = _interopRequireWildcard(require("@stellar/stellar-base")); +exports.StellarBase = _StellarBase; +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/config.d.ts b/node_modules/@stellar/stellar-sdk/lib/config.d.ts new file mode 100644 index 000000000..3daa1aa99 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/config.d.ts @@ -0,0 +1,64 @@ +/** + * Global config parameters. + */ +export interface Configuration { + /** + * Allow connecting to http servers. This must be set to false in production deployments! + * @default false + */ + allowHttp: boolean; + /** + * Allow a timeout. Allows user to avoid nasty lag due network issues. + * @default 0 + */ + timeout: number; +} +/** + * Global config class. + * + * @hideconstructor + * + * @example Usage in node + * import { Config } from '@stellar/stellar-sdk'; + * Config.setAllowHttp(true); + * Config.setTimeout(5000); + * + * @example Usage in the browser + * StellarSdk.Config.setAllowHttp(true); + * StellarSdk.Config.setTimeout(5000); + */ +declare class Config { + /** + * Sets `allowHttp` flag globally. When set to `true`, connections to insecure + * http protocol servers will be allowed. Must be set to `false` in + * production. + * @default false + * @static + */ + static setAllowHttp(value: boolean): void; + /** + * Sets `timeout` flag globally. When set to anything besides 0, the request + * will timeout after specified time (ms). + * @default 0 + * @static + */ + static setTimeout(value: number): void; + /** + * Returns the configured `allowHttp` flag. + * @static + * @returns {boolean} + */ + static isAllowHttp(): boolean; + /** + * Returns the configured `timeout` flag. + * @static + * @returns {number} + */ + static getTimeout(): number; + /** + * Sets all global config flags to default values. + * @static + */ + static setDefault(): void; +} +export { Config }; diff --git a/node_modules/@stellar/stellar-sdk/lib/config.js b/node_modules/@stellar/stellar-sdk/lib/config.js new file mode 100644 index 000000000..e19e63d74 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/config.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Config = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var defaultConfig = { + allowHttp: false, + timeout: 0 +}; +var config = _objectSpread({}, defaultConfig); +var Config = exports.Config = function () { + function Config() { + _classCallCheck(this, Config); + } + return _createClass(Config, null, [{ + key: "setAllowHttp", + value: function setAllowHttp(value) { + config.allowHttp = value; + } + }, { + key: "setTimeout", + value: function setTimeout(value) { + config.timeout = value; + } + }, { + key: "isAllowHttp", + value: function isAllowHttp() { + return config.allowHttp; + } + }, { + key: "getTimeout", + value: function getTimeout() { + return config.timeout; + } + }, { + key: "setDefault", + value: function setDefault() { + config = _objectSpread({}, defaultConfig); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/assembled_transaction.d.ts b/node_modules/@stellar/stellar-sdk/lib/contract/assembled_transaction.d.ts new file mode 100644 index 000000000..c420d90f2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/assembled_transaction.d.ts @@ -0,0 +1,627 @@ +import { Account, SorobanDataBuilder, TransactionBuilder, authorizeEntry as stellarBaseAuthorizeEntry, xdr } from "@stellar/stellar-base"; +import type { AssembledTransactionOptions, ClientOptions, Tx, XDR_BASE64 } from "./types"; +import { Api } from "../rpc/api"; +import { SentTransaction } from "./sent_transaction"; +import { Spec } from "./spec"; +/** @module contract */ +/** + * The main workhorse of {@link Client}. This class is used to wrap a + * transaction-under-construction and provide high-level interfaces to the most + * common workflows, while still providing access to low-level stellar-sdk + * transaction manipulation. + * + * Most of the time, you will not construct an `AssembledTransaction` directly, + * but instead receive one as the return value of a `Client` method. If + * you're familiar with the libraries generated by soroban-cli's `contract + * bindings typescript` command, these also wraps `Client` and return + * `AssembledTransaction` instances. + * + * Let's look at examples of how to use `AssembledTransaction` for a variety of + * use-cases: + * + * #### 1. Simple read call + * + * Since these only require simulation, you can get the `result` of the call + * right after constructing your `AssembledTransaction`: + * + * ```ts + * const { result } = await AssembledTransaction.build({ + * method: 'myReadMethod', + * args: spec.funcArgsToScVals('myReadMethod', { + * args: 'for', + * my: 'method', + * ... + * }), + * contractId: 'C123…', + * networkPassphrase: '…', + * rpcUrl: 'https://…', + * publicKey: undefined, // irrelevant, for simulation-only read calls + * parseResultXdr: (result: xdr.ScVal) => + * spec.funcResToNative('myReadMethod', result), + * }) + * ``` + * + * While that looks pretty complicated, most of the time you will use this in + * conjunction with {@link Client}, which simplifies it to: + * + * ```ts + * const { result } = await client.myReadMethod({ + * args: 'for', + * my: 'method', + * ... + * }) + * ``` + * + * #### 2. Simple write call + * + * For write calls that will be simulated and then sent to the network without + * further manipulation, only one more step is needed: + * + * ```ts + * const assembledTx = await client.myWriteMethod({ + * args: 'for', + * my: 'method', + * ... + * }) + * const sentTx = await assembledTx.signAndSend() + * ``` + * + * Here we're assuming that you're using a {@link Client}, rather than + * constructing `AssembledTransaction`'s directly. + * + * Note that `sentTx`, the return value of `signAndSend`, is a + * {@link SentTransaction}. `SentTransaction` is similar to + * `AssembledTransaction`, but is missing many of the methods and fields that + * are only relevant while assembling a transaction. It also has a few extra + * methods and fields that are only relevant after the transaction has been + * sent to the network. + * + * Like `AssembledTransaction`, `SentTransaction` also has a `result` getter, + * which contains the parsed final return value of the contract call. Most of + * the time, you may only be interested in this, so rather than getting the + * whole `sentTx` you may just want to: + * + * ```ts + * const tx = await client.myWriteMethod({ args: 'for', my: 'method', ... }) + * const { result } = await tx.signAndSend() + * ``` + * + * #### 3. More fine-grained control over transaction construction + * + * If you need more control over the transaction before simulating it, you can + * set various {@link MethodOptions} when constructing your + * `AssembledTransaction`. With a {@link Client}, this is passed as a + * second object after the arguments (or the only object, if the method takes + * no arguments): + * + * ```ts + * const tx = await client.myWriteMethod( + * { + * args: 'for', + * my: 'method', + * ... + * }, { + * fee: '10000', // default: {@link BASE_FEE} + * simulate: false, + * timeoutInSeconds: 20, // default: {@link DEFAULT_TIMEOUT} + * } + * ) + * ``` + * + * Since we've skipped simulation, we can now edit the `raw` transaction and + * then manually call `simulate`: + * + * ```ts + * tx.raw.addMemo(Memo.text('Nice memo, friend!')) + * await tx.simulate() + * ``` + * + * If you need to inspect the simulation later, you can access it with + * `tx.simulation`. + * + * #### 4. Multi-auth workflows + * + * Soroban, and Stellar in general, allows multiple parties to sign a + * transaction. + * + * Let's consider an Atomic Swap contract. Alice wants to give 10 of her Token + * A tokens to Bob for 5 of his Token B tokens. + * + * ```ts + * const ALICE = 'G123...' + * const BOB = 'G456...' + * const TOKEN_A = 'C123…' + * const TOKEN_B = 'C456…' + * const AMOUNT_A = 10n + * const AMOUNT_B = 5n + * ``` + * + * Let's say Alice is also going to be the one signing the final transaction + * envelope, meaning she is the invoker. So your app, from Alice's browser, + * simulates the `swap` call: + * + * ```ts + * const tx = await swapClient.swap({ + * a: ALICE, + * b: BOB, + * token_a: TOKEN_A, + * token_b: TOKEN_B, + * amount_a: AMOUNT_A, + * amount_b: AMOUNT_B, + * }) + * ``` + * + * But your app can't `signAndSend` this right away, because Bob needs to sign + * it first. You can check this: + * + * ```ts + * const whoElseNeedsToSign = tx.needsNonInvokerSigningBy() + * ``` + * + * You can verify that `whoElseNeedsToSign` is an array of length `1`, + * containing only Bob's public key. + * + * Then, still on Alice's machine, you can serialize the + * transaction-under-assembly: + * + * ```ts + * const json = tx.toJSON() + * ``` + * + * And now you need to send it to Bob's browser. How you do this depends on + * your app. Maybe you send it to a server first, maybe you use WebSockets, or + * maybe you have Alice text the JSON blob to Bob and have him paste it into + * your app in his browser (note: this option might be error-prone 😄). + * + * Once you get the JSON blob into your app on Bob's machine, you can + * deserialize it: + * + * ```ts + * const tx = swapClient.txFromJSON(json) + * ``` + * + * Or, if you're using a client generated with `soroban contract bindings + * typescript`, this deserialization will look like: + * + * ```ts + * const tx = swapClient.fromJSON.swap(json) + * ``` + * + * Then you can have Bob sign it. What Bob will actually need to sign is some + * _auth entries_ within the transaction, not the transaction itself or the + * transaction envelope. Your app can verify that Bob has the correct wallet + * selected, then: + * + * ```ts + * await tx.signAuthEntries() + * ``` + * + * Under the hood, this uses `signAuthEntry`, which you either need to inject + * during initial construction of the `Client`/`AssembledTransaction`, + * or which you can pass directly to `signAuthEntries`. + * + * Now Bob can again serialize the transaction and send back to Alice, where + * she can finally call `signAndSend()`. + * + * To see an even more complicated example, where Alice swaps with Bob but the + * transaction is invoked by yet another party, check out + * [test-swap.js](../../test/e2e/src/test-swap.js). + * + * @memberof module:contract + */ +export declare class AssembledTransaction { + options: AssembledTransactionOptions; + /** + * The TransactionBuilder as constructed in `{@link + * AssembledTransaction}.build`. Feel free set `simulate: false` to modify + * this object before calling `tx.simulate()` manually. Example: + * + * ```ts + * const tx = await myContract.myMethod( + * { args: 'for', my: 'method', ... }, + * { simulate: false } + * ); + * tx.raw.addMemo(Memo.text('Nice memo, friend!')) + * await tx.simulate(); + * ``` + */ + raw?: TransactionBuilder; + /** + * The Transaction as it was built with `raw.build()` right before + * simulation. Once this is set, modifying `raw` will have no effect unless + * you call `tx.simulate()` again. + */ + built?: Tx; + /** + * The result of the transaction simulation. This is set after the first call + * to `simulate`. It is difficult to serialize and deserialize, so it is not + * included in the `toJSON` and `fromJSON` methods. See `simulationData` + * cached, serializable access to the data needed by AssembledTransaction + * logic. + */ + simulation?: Api.SimulateTransactionResponse; + /** + * Cached simulation result. This is set after the first call to + * {@link AssembledTransaction#simulationData}, and is used to facilitate + * serialization and deserialization of the AssembledTransaction. + * + * Most of the time, if you need this data, you can call + * `tx.simulation.result`. + * + * If you need access to this data after a transaction has been serialized + * and then deserialized, you can call `simulationData.result`. + */ + private simulationResult?; + /** + * Cached simulation transaction data. This is set after the first call to + * {@link AssembledTransaction#simulationData}, and is used to facilitate + * serialization and deserialization of the AssembledTransaction. + * + * Most of the time, if you need this data, you can call + * `simulation.transactionData`. + * + * If you need access to this data after a transaction has been serialized + * and then deserialized, you can call `simulationData.transactionData`. + */ + private simulationTransactionData?; + /** + * The Soroban server to use for all RPC calls. This is constructed from the + * `rpcUrl` in the options. + */ + private server; + /** + * The signed transaction. + */ + signed?: Tx; + /** + * A list of the most important errors that various AssembledTransaction + * methods can throw. Feel free to catch specific errors in your application + * logic. + */ + static Errors: { + ExpiredState: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + RestorationFailure: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NeedsMoreSignatures: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NoSignatureNeeded: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NoUnsignedNonInvokerAuthEntries: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NoSigner: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NotYetSimulated: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + FakeAccount: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + SimulationFailed: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + InternalWalletError: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + ExternalServiceError: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + InvalidClientRequest: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + UserRejected: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + }; + /** + * Serialize the AssembledTransaction to a JSON string. This is useful for + * saving the transaction to a database or sending it over the wire for + * multi-auth workflows. `fromJSON` can be used to deserialize the + * transaction. This only works with transactions that have been simulated. + */ + toJSON(): string; + static fromJSON(options: Omit, "args">, { tx, simulationResult, simulationTransactionData, }: { + tx: XDR_BASE64; + simulationResult: { + auth: XDR_BASE64[]; + retval: XDR_BASE64; + }; + simulationTransactionData: XDR_BASE64; + }): AssembledTransaction; + /** + * Serialize the AssembledTransaction to a base64-encoded XDR string. + */ + toXDR(): string; + /** + * Deserialize the AssembledTransaction from a base64-encoded XDR string. + */ + static fromXDR(options: Omit, "args" | "method" | "parseResultXdr">, encodedXDR: string, spec: Spec): AssembledTransaction; + private handleWalletError; + private constructor(); + /** + * Construct a new AssembledTransaction. This is the main way to create a new + * AssembledTransaction; the constructor is private. + * + * This is an asynchronous constructor for two reasons: + * + * 1. It needs to fetch the account from the network to get the current + * sequence number. + * 2. It needs to simulate the transaction to get the expected fee. + * + * If you don't want to simulate the transaction, you can set `simulate` to + * `false` in the options. + * + * If you need to create an operation other than `invokeHostFunction`, you + * can use {@link AssembledTransaction.buildWithOp} instead. + * + * @example + * const tx = await AssembledTransaction.build({ + * ..., + * simulate: false, + * }) + */ + static build(options: AssembledTransactionOptions): Promise>; + /** + * Construct a new AssembledTransaction, specifying an Operation other than + * `invokeHostFunction` (the default used by {@link AssembledTransaction.build}). + * + * Note: `AssembledTransaction` currently assumes these operations can be + * simulated. This is not true for classic operations; only for those used by + * Soroban Smart Contracts like `invokeHostFunction` and `createCustomContract`. + * + * @example + * const tx = await AssembledTransaction.buildWithOp( + * Operation.createCustomContract({ ... }); + * { + * ..., + * simulate: false, + * } + * ) + */ + static buildWithOp(operation: xdr.Operation, options: AssembledTransactionOptions): Promise>; + private static buildFootprintRestoreTransaction; + simulate: ({ restore }?: { + restore?: boolean; + }) => Promise; + get simulationData(): { + result: Api.SimulateHostFunctionResult; + transactionData: xdr.SorobanTransactionData; + }; + get result(): T; + private parseError; + /** + * Sign the transaction with the signTransaction function included previously. + * If you did not previously include one, you need to include one now. + */ + sign: ({ force, signTransaction, }?: { + /** + * If `true`, sign and send the transaction even if it is a read call + */ + force?: boolean; + /** + * You must provide this here if you did not provide one before + */ + signTransaction?: ClientOptions["signTransaction"]; + }) => Promise; + /** + * Sends the transaction to the network to return a `SentTransaction` that + * keeps track of all the attempts to fetch the transaction. + */ + send(): Promise>; + /** + * Sign the transaction with the `signTransaction` function included previously. + * If you did not previously include one, you need to include one now. + * After signing, this method will send the transaction to the network and + * return a `SentTransaction` that keeps track * of all the attempts to fetch the transaction. + */ + signAndSend: ({ force, signTransaction, }?: { + /** + * If `true`, sign and send the transaction even if it is a read call + */ + force?: boolean; + /** + * You must provide this here if you did not provide one before + */ + signTransaction?: ClientOptions["signTransaction"]; + }) => Promise>; + /** + * Get a list of accounts, other than the invoker of the simulation, that + * need to sign auth entries in this transaction. + * + * Soroban allows multiple people to sign a transaction. Someone needs to + * sign the final transaction envelope; this person/account is called the + * _invoker_, or _source_. Other accounts might need to sign individual auth + * entries in the transaction, if they're not also the invoker. + * + * This function returns a list of accounts that need to sign auth entries, + * assuming that the same invoker/source account will sign the final + * transaction envelope as signed the initial simulation. + * + * One at a time, for each public key in this array, you will need to + * serialize this transaction with `toJSON`, send to the owner of that key, + * deserialize the transaction with `txFromJson`, and call + * {@link AssembledTransaction#signAuthEntries}. Then re-serialize and send to + * the next account in this list. + */ + needsNonInvokerSigningBy: ({ includeAlreadySigned, }?: { + /** + * Whether or not to include auth entries that have already been signed. + * Default: false + */ + includeAlreadySigned?: boolean; + }) => string[]; + /** + * If {@link AssembledTransaction#needsNonInvokerSigningBy} returns a + * non-empty list, you can serialize the transaction with `toJSON`, send it to + * the owner of one of the public keys in the map, deserialize with + * `txFromJSON`, and call this method on their machine. Internally, this will + * use `signAuthEntry` function from connected `wallet` for each. + * + * Then, re-serialize the transaction and either send to the next + * `needsNonInvokerSigningBy` owner, or send it back to the original account + * who simulated the transaction so they can {@link AssembledTransaction#sign} + * the transaction envelope and {@link AssembledTransaction#send} it to the + * network. + * + * Sending to all `needsNonInvokerSigningBy` owners in parallel is not + * currently supported! + */ + signAuthEntries: ({ expiration, signAuthEntry, address, authorizeEntry, }?: { + /** + * When to set each auth entry to expire. Could be any number of blocks in + * the future. Can be supplied as a promise or a raw number. Default: + * about 8.3 minutes from now. + */ + expiration?: number | Promise; + /** + * Sign all auth entries for this account. Default: the account that + * constructed the transaction + */ + address?: string; + /** + * You must provide this here if you did not provide one before and you are not passing `authorizeEntry`. Default: the `signAuthEntry` function from the `Client` options. Must sign things as the given `publicKey`. + */ + signAuthEntry?: ClientOptions["signAuthEntry"]; + /** + * If you have a pro use-case and need to override the default `authorizeEntry` function, rather than using the one in @stellar/stellar-base, you can do that! Your function needs to take at least the first argument, `entry: xdr.SorobanAuthorizationEntry`, and return a `Promise`. + * + * Note that you if you pass this, then `signAuthEntry` will be ignored. + */ + authorizeEntry?: typeof stellarBaseAuthorizeEntry; + }) => Promise; + /** + * Whether this transaction is a read call. This is determined by the + * simulation result and the transaction data. If the transaction is a read + * call, it will not need to be signed and sent to the network. If this + * returns `false`, then you need to call `signAndSend` on this transaction. + */ + get isReadCall(): boolean; + /** + * Restores the footprint (resource ledger entries that can be read or written) + * of an expired transaction. + * + * The method will: + * 1. Build a new transaction aimed at restoring the necessary resources. + * 2. Sign this new transaction if a `signTransaction` handler is provided. + * 3. Send the signed transaction to the network. + * 4. Await and return the response from the network. + * + * Preconditions: + * - A `signTransaction` function must be provided during the Client initialization. + * - The provided `restorePreamble` should include a minimum resource fee and valid + * transaction data. + * + * @throws {Error} - Throws an error if no `signTransaction` function is provided during + * Client initialization. + * @throws {AssembledTransaction.Errors.RestoreFailure} - Throws a custom error if the + * restore transaction fails, providing the details of the failure. + */ + restoreFootprint( + /** + * The preamble object containing data required to + * build the restore transaction. + */ + restorePreamble: { + minResourceFee: string; + transactionData: SorobanDataBuilder; + }, + /** The account that is executing the footprint restore operation. If omitted, will use the account from the AssembledTransaction. */ + account?: Account): Promise; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/assembled_transaction.js b/node_modules/@stellar/stellar-sdk/lib/contract/assembled_transaction.js new file mode 100644 index 000000000..aaeaac04e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/assembled_transaction.js @@ -0,0 +1,841 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AssembledTransaction = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _rpc = require("../rpc"); +var _api = require("../rpc/api"); +var _transaction = require("../rpc/transaction"); +var _rust_result = require("./rust_result"); +var _utils = require("./utils"); +var _types = require("./types"); +var _sent_transaction = require("./sent_transaction"); +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var AssembledTransaction = exports.AssembledTransaction = function () { + function AssembledTransaction(options) { + var _this = this, + _this$options$simulat, + _this$options$allowHt; + _classCallCheck(this, AssembledTransaction); + _defineProperty(this, "simulate", _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var _restore; + var _ref2, + restore, + account, + result, + _this$options$fee, + _this$options$args, + _this$options$timeout, + contract, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _ref2 = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, restore = _ref2.restore; + if (_this.built) { + _context.next = 5; + break; + } + if (_this.raw) { + _context.next = 4; + break; + } + throw new Error("Transaction has not yet been assembled; " + "call `AssembledTransaction.build` first."); + case 4: + _this.built = _this.raw.build(); + case 5: + restore = (_restore = restore) !== null && _restore !== void 0 ? _restore : _this.options.restore; + delete _this.simulationResult; + delete _this.simulationTransactionData; + _context.next = 10; + return _this.server.simulateTransaction(_this.built); + case 10: + _this.simulation = _context.sent; + if (!(restore && _api.Api.isSimulationRestore(_this.simulation))) { + _context.next = 25; + break; + } + _context.next = 14; + return (0, _utils.getAccount)(_this.options, _this.server); + case 14: + account = _context.sent; + _context.next = 17; + return _this.restoreFootprint(_this.simulation.restorePreamble, account); + case 17: + result = _context.sent; + if (!(result.status === _api.Api.GetTransactionStatus.SUCCESS)) { + _context.next = 24; + break; + } + contract = new _stellarBase.Contract(_this.options.contractId); + _this.raw = new _stellarBase.TransactionBuilder(account, { + fee: (_this$options$fee = _this.options.fee) !== null && _this$options$fee !== void 0 ? _this$options$fee : _stellarBase.BASE_FEE, + networkPassphrase: _this.options.networkPassphrase + }).addOperation(contract.call.apply(contract, [_this.options.method].concat(_toConsumableArray((_this$options$args = _this.options.args) !== null && _this$options$args !== void 0 ? _this$options$args : [])))).setTimeout((_this$options$timeout = _this.options.timeoutInSeconds) !== null && _this$options$timeout !== void 0 ? _this$options$timeout : _types.DEFAULT_TIMEOUT); + _context.next = 23; + return _this.simulate(); + case 23: + return _context.abrupt("return", _this); + case 24: + throw new AssembledTransaction.Errors.RestorationFailure("Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n".concat(JSON.stringify(result))); + case 25: + if (_api.Api.isSimulationSuccess(_this.simulation)) { + _this.built = (0, _transaction.assembleTransaction)(_this.built, _this.simulation).build(); + } + return _context.abrupt("return", _this); + case 27: + case "end": + return _context.stop(); + } + }, _callee); + }))); + _defineProperty(this, "sign", _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + var _this$options$timeout2; + var _ref4, + _ref4$force, + force, + _ref4$signTransaction, + signTransaction, + sigsNeeded, + timeoutInSeconds, + signOpts, + _yield$signTransactio, + signature, + error, + _args2 = arguments; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _ref4 = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref4$force = _ref4.force, force = _ref4$force === void 0 ? false : _ref4$force, _ref4$signTransaction = _ref4.signTransaction, signTransaction = _ref4$signTransaction === void 0 ? _this.options.signTransaction : _ref4$signTransaction; + if (_this.built) { + _context2.next = 3; + break; + } + throw new Error("Transaction has not yet been simulated"); + case 3: + if (!(!force && _this.isReadCall)) { + _context2.next = 5; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("This is a read call. It requires no signature or sending. " + "Use `force: true` to sign and send anyway."); + case 5: + if (signTransaction) { + _context2.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide a signTransaction function, either when calling " + "`signAndSend` or when initializing your Client"); + case 7: + sigsNeeded = _this.needsNonInvokerSigningBy().filter(function (id) { + return !id.startsWith('C'); + }); + if (!sigsNeeded.length) { + _context2.next = 10; + break; + } + throw new AssembledTransaction.Errors.NeedsMoreSignatures("Transaction requires signatures from ".concat(sigsNeeded, ". ") + "See `needsNonInvokerSigningBy` for details."); + case 10: + timeoutInSeconds = (_this$options$timeout2 = _this.options.timeoutInSeconds) !== null && _this$options$timeout2 !== void 0 ? _this$options$timeout2 : _types.DEFAULT_TIMEOUT; + _this.built = _stellarBase.TransactionBuilder.cloneFrom(_this.built, { + fee: _this.built.fee, + timebounds: undefined, + sorobanData: _this.simulationData.transactionData + }).setTimeout(timeoutInSeconds).build(); + signOpts = { + networkPassphrase: _this.options.networkPassphrase + }; + if (_this.options.address) signOpts.address = _this.options.address; + if (_this.options.submit !== undefined) signOpts.submit = _this.options.submit; + if (_this.options.submitUrl) signOpts.submitUrl = _this.options.submitUrl; + _context2.next = 18; + return signTransaction(_this.built.toXDR(), signOpts); + case 18: + _yield$signTransactio = _context2.sent; + signature = _yield$signTransactio.signedTxXdr; + error = _yield$signTransactio.error; + _this.handleWalletError(error); + _this.signed = _stellarBase.TransactionBuilder.fromXDR(signature, _this.options.networkPassphrase); + case 23: + case "end": + return _context2.stop(); + } + }, _callee2); + }))); + _defineProperty(this, "signAndSend", _asyncToGenerator(_regeneratorRuntime().mark(function _callee3() { + var _ref6, + _ref6$force, + force, + _ref6$signTransaction, + signTransaction, + originalSubmit, + _args3 = arguments; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _ref6 = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : {}, _ref6$force = _ref6.force, force = _ref6$force === void 0 ? false : _ref6$force, _ref6$signTransaction = _ref6.signTransaction, signTransaction = _ref6$signTransaction === void 0 ? _this.options.signTransaction : _ref6$signTransaction; + if (_this.signed) { + _context3.next = 10; + break; + } + originalSubmit = _this.options.submit; + if (_this.options.submit) { + _this.options.submit = false; + } + _context3.prev = 4; + _context3.next = 7; + return _this.sign({ + force: force, + signTransaction: signTransaction + }); + case 7: + _context3.prev = 7; + _this.options.submit = originalSubmit; + return _context3.finish(7); + case 10: + return _context3.abrupt("return", _this.send()); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3, null, [[4,, 7, 10]]); + }))); + _defineProperty(this, "needsNonInvokerSigningBy", function () { + var _rawInvokeHostFunctio; + var _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref7$includeAlreadyS = _ref7.includeAlreadySigned, + includeAlreadySigned = _ref7$includeAlreadyS === void 0 ? false : _ref7$includeAlreadyS; + if (!_this.built) { + throw new Error("Transaction has not yet been simulated"); + } + if (!("operations" in _this.built)) { + throw new Error("Unexpected Transaction type; no operations: ".concat(JSON.stringify(_this.built))); + } + var rawInvokeHostFunctionOp = _this.built.operations[0]; + return _toConsumableArray(new Set(((_rawInvokeHostFunctio = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio !== void 0 ? _rawInvokeHostFunctio : []).filter(function (entry) { + return entry.credentials().switch() === _stellarBase.xdr.SorobanCredentialsType.sorobanCredentialsAddress() && (includeAlreadySigned || entry.credentials().address().signature().switch().name === "scvVoid"); + }).map(function (entry) { + return _stellarBase.Address.fromScAddress(entry.credentials().address().address()).toString(); + }))); + }); + _defineProperty(this, "signAuthEntries", _asyncToGenerator(_regeneratorRuntime().mark(function _callee6() { + var _rawInvokeHostFunctio2; + var _ref9, + _ref9$expiration, + expiration, + _ref9$signAuthEntry, + signAuthEntry, + _ref9$address, + address, + _ref9$authorizeEntry, + authorizeEntry, + needsNonInvokerSigningBy, + rawInvokeHostFunctionOp, + authEntries, + _iterator, + _step, + _loop, + _ret, + _args7 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _ref9 = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {}, _ref9$expiration = _ref9.expiration, expiration = _ref9$expiration === void 0 ? _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this.server.getLatestLedger(); + case 2: + _context4.t0 = _context4.sent.sequence; + return _context4.abrupt("return", _context4.t0 + 100); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + }))() : _ref9$expiration, _ref9$signAuthEntry = _ref9.signAuthEntry, signAuthEntry = _ref9$signAuthEntry === void 0 ? _this.options.signAuthEntry : _ref9$signAuthEntry, _ref9$address = _ref9.address, address = _ref9$address === void 0 ? _this.options.publicKey : _ref9$address, _ref9$authorizeEntry = _ref9.authorizeEntry, authorizeEntry = _ref9$authorizeEntry === void 0 ? _stellarBase.authorizeEntry : _ref9$authorizeEntry; + if (_this.built) { + _context7.next = 3; + break; + } + throw new Error("Transaction has not yet been assembled or simulated"); + case 3: + if (!(authorizeEntry === _stellarBase.authorizeEntry)) { + _context7.next = 11; + break; + } + needsNonInvokerSigningBy = _this.needsNonInvokerSigningBy(); + if (!(needsNonInvokerSigningBy.length === 0)) { + _context7.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?"); + case 7: + if (!(needsNonInvokerSigningBy.indexOf(address !== null && address !== void 0 ? address : "") === -1)) { + _context7.next = 9; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("No auth entries for public key \"".concat(address, "\"")); + case 9: + if (signAuthEntry) { + _context7.next = 11; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`"); + case 11: + rawInvokeHostFunctionOp = _this.built.operations[0]; + authEntries = (_rawInvokeHostFunctio2 = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio2 !== void 0 ? _rawInvokeHostFunctio2 : []; + _iterator = _createForOfIteratorHelper(authEntries.entries()); + _context7.prev = 14; + _loop = _regeneratorRuntime().mark(function _loop() { + var _step$value, i, entry, credentials, authEntryAddress, sign; + return _regeneratorRuntime().wrap(function _loop$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _step$value = _slicedToArray(_step.value, 2), i = _step$value[0], entry = _step$value[1]; + credentials = _stellarBase.xdr.SorobanCredentials.fromXDR(entry.credentials().toXDR()); + if (!(credentials.switch() !== _stellarBase.xdr.SorobanCredentialsType.sorobanCredentialsAddress())) { + _context6.next = 4; + break; + } + return _context6.abrupt("return", 0); + case 4: + authEntryAddress = _stellarBase.Address.fromScAddress(credentials.address().address()).toString(); + if (!(authEntryAddress !== address)) { + _context6.next = 7; + break; + } + return _context6.abrupt("return", 0); + case 7: + sign = signAuthEntry !== null && signAuthEntry !== void 0 ? signAuthEntry : Promise.resolve; + _context6.t0 = authorizeEntry; + _context6.t1 = entry; + _context6.t2 = function () { + var _ref11 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(preimage) { + var _yield$sign, signedAuthEntry, error; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return sign(preimage.toXDR("base64"), { + address: address + }); + case 2: + _yield$sign = _context5.sent; + signedAuthEntry = _yield$sign.signedAuthEntry; + error = _yield$sign.error; + _this.handleWalletError(error); + return _context5.abrupt("return", Buffer.from(signedAuthEntry, "base64")); + case 7: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x) { + return _ref11.apply(this, arguments); + }; + }(); + _context6.next = 13; + return expiration; + case 13: + _context6.t3 = _context6.sent; + _context6.t4 = _this.options.networkPassphrase; + _context6.next = 17; + return (0, _context6.t0)(_context6.t1, _context6.t2, _context6.t3, _context6.t4); + case 17: + authEntries[i] = _context6.sent; + case 18: + case "end": + return _context6.stop(); + } + }, _loop); + }); + _iterator.s(); + case 17: + if ((_step = _iterator.n()).done) { + _context7.next = 24; + break; + } + return _context7.delegateYield(_loop(), "t0", 19); + case 19: + _ret = _context7.t0; + if (!(_ret === 0)) { + _context7.next = 22; + break; + } + return _context7.abrupt("continue", 22); + case 22: + _context7.next = 17; + break; + case 24: + _context7.next = 29; + break; + case 26: + _context7.prev = 26; + _context7.t1 = _context7["catch"](14); + _iterator.e(_context7.t1); + case 29: + _context7.prev = 29; + _iterator.f(); + return _context7.finish(29); + case 32: + case "end": + return _context7.stop(); + } + }, _callee6, null, [[14, 26, 29, 32]]); + }))); + this.options = options; + this.options.simulate = (_this$options$simulat = this.options.simulate) !== null && _this$options$simulat !== void 0 ? _this$options$simulat : true; + this.server = new _rpc.Server(this.options.rpcUrl, { + allowHttp: (_this$options$allowHt = this.options.allowHttp) !== null && _this$options$allowHt !== void 0 ? _this$options$allowHt : false + }); + } + return _createClass(AssembledTransaction, [{ + key: "toJSON", + value: function toJSON() { + var _this$built; + return JSON.stringify({ + method: this.options.method, + tx: (_this$built = this.built) === null || _this$built === void 0 ? void 0 : _this$built.toXDR(), + simulationResult: { + auth: this.simulationData.result.auth.map(function (a) { + return a.toXDR("base64"); + }), + retval: this.simulationData.result.retval.toXDR("base64") + }, + simulationTransactionData: this.simulationData.transactionData.toXDR("base64") + }); + } + }, { + key: "toXDR", + value: function toXDR() { + var _this$built2; + if (!this.built) throw new Error("Transaction has not yet been simulated; " + "call `AssembledTransaction.simulate` first."); + return (_this$built2 = this.built) === null || _this$built2 === void 0 ? void 0 : _this$built2.toEnvelope().toXDR('base64'); + } + }, { + key: "handleWalletError", + value: function handleWalletError(error) { + if (!error) return; + var message = error.message, + code = error.code; + var fullMessage = "".concat(message).concat(error.ext ? " (".concat(error.ext.join(', '), ")") : ''); + switch (code) { + case -1: + throw new AssembledTransaction.Errors.InternalWalletError(fullMessage); + case -2: + throw new AssembledTransaction.Errors.ExternalServiceError(fullMessage); + case -3: + throw new AssembledTransaction.Errors.InvalidClientRequest(fullMessage); + case -4: + throw new AssembledTransaction.Errors.UserRejected(fullMessage); + default: + throw new Error("Unhandled error: ".concat(fullMessage)); + } + } + }, { + key: "simulationData", + get: function get() { + var _simulation$result; + if (this.simulationResult && this.simulationTransactionData) { + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + var simulation = this.simulation; + if (!simulation) { + throw new AssembledTransaction.Errors.NotYetSimulated("Transaction has not yet been simulated"); + } + if (_api.Api.isSimulationError(simulation)) { + throw new AssembledTransaction.Errors.SimulationFailed("Transaction simulation failed: \"".concat(simulation.error, "\"")); + } + if (_api.Api.isSimulationRestore(simulation)) { + throw new AssembledTransaction.Errors.ExpiredState("You need to restore some contract state before you can invoke this method.\n" + 'You can set `restore` to true in the method options in order to ' + 'automatically restore the contract state when needed.'); + } + this.simulationResult = (_simulation$result = simulation.result) !== null && _simulation$result !== void 0 ? _simulation$result : { + auth: [], + retval: _stellarBase.xdr.ScVal.scvVoid() + }; + this.simulationTransactionData = simulation.transactionData.build(); + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + }, { + key: "result", + get: function get() { + try { + if (!this.simulationData.result) { + throw new Error("No simulation result!"); + } + return this.options.parseResultXdr(this.simulationData.result.retval); + } catch (e) { + if (!(0, _utils.implementsToString)(e)) throw e; + var err = this.parseError(e.toString()); + if (err) return err; + throw e; + } + } + }, { + key: "parseError", + value: function parseError(errorMessage) { + if (!this.options.errorTypes) return undefined; + var match = errorMessage.match(_utils.contractErrorPattern); + if (!match) return undefined; + var i = parseInt(match[1], 10); + var err = this.options.errorTypes[i]; + if (!err) return undefined; + return new _rust_result.Err(err); + } + }, { + key: "send", + value: (function () { + var _send = _asyncToGenerator(_regeneratorRuntime().mark(function _callee7() { + var sent; + return _regeneratorRuntime().wrap(function _callee7$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (this.signed) { + _context8.next = 2; + break; + } + throw new Error("The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead."); + case 2: + _context8.next = 4; + return _sent_transaction.SentTransaction.init(this); + case 4: + sent = _context8.sent; + return _context8.abrupt("return", sent); + case 6: + case "end": + return _context8.stop(); + } + }, _callee7, this); + })); + function send() { + return _send.apply(this, arguments); + } + return send; + }()) + }, { + key: "isReadCall", + get: function get() { + var authsCount = this.simulationData.result.auth.length; + var writeLength = this.simulationData.transactionData.resources().footprint().readWrite().length; + return authsCount === 0 && writeLength === 0; + } + }, { + key: "restoreFootprint", + value: (function () { + var _restoreFootprint = _asyncToGenerator(_regeneratorRuntime().mark(function _callee8(restorePreamble, account) { + var _account; + var restoreTx, sentTransaction; + return _regeneratorRuntime().wrap(function _callee8$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + if (this.options.signTransaction) { + _context9.next = 2; + break; + } + throw new Error("For automatic restore to work you must provide a signTransaction function when initializing your Client"); + case 2: + if (!((_account = account) !== null && _account !== void 0)) { + _context9.next = 6; + break; + } + _context9.t0 = _account; + _context9.next = 9; + break; + case 6: + _context9.next = 8; + return (0, _utils.getAccount)(this.options, this.server); + case 8: + _context9.t0 = _context9.sent; + case 9: + account = _context9.t0; + _context9.next = 12; + return AssembledTransaction.buildFootprintRestoreTransaction(_objectSpread({}, this.options), restorePreamble.transactionData, account, restorePreamble.minResourceFee); + case 12: + restoreTx = _context9.sent; + _context9.next = 15; + return restoreTx.signAndSend(); + case 15: + sentTransaction = _context9.sent; + if (sentTransaction.getTransactionResponse) { + _context9.next = 18; + break; + } + throw new AssembledTransaction.Errors.RestorationFailure("The attempt at automatic restore failed. \n".concat(JSON.stringify(sentTransaction))); + case 18: + return _context9.abrupt("return", sentTransaction.getTransactionResponse); + case 19: + case "end": + return _context9.stop(); + } + }, _callee8, this); + })); + function restoreFootprint(_x2, _x3) { + return _restoreFootprint.apply(this, arguments); + } + return restoreFootprint; + }()) + }], [{ + key: "fromJSON", + value: function fromJSON(options, _ref12) { + var tx = _ref12.tx, + simulationResult = _ref12.simulationResult, + simulationTransactionData = _ref12.simulationTransactionData; + var txn = new AssembledTransaction(options); + txn.built = _stellarBase.TransactionBuilder.fromXDR(tx, options.networkPassphrase); + txn.simulationResult = { + auth: simulationResult.auth.map(function (a) { + return _stellarBase.xdr.SorobanAuthorizationEntry.fromXDR(a, "base64"); + }), + retval: _stellarBase.xdr.ScVal.fromXDR(simulationResult.retval, "base64") + }; + txn.simulationTransactionData = _stellarBase.xdr.SorobanTransactionData.fromXDR(simulationTransactionData, "base64"); + return txn; + } + }, { + key: "fromXDR", + value: function fromXDR(options, encodedXDR, spec) { + var _operation$func; + var envelope = _stellarBase.xdr.TransactionEnvelope.fromXDR(encodedXDR, "base64"); + var built = _stellarBase.TransactionBuilder.fromXDR(envelope, options.networkPassphrase); + var operation = built.operations[0]; + if (!(operation !== null && operation !== void 0 && (_operation$func = operation.func) !== null && _operation$func !== void 0 && _operation$func.value) || typeof operation.func.value !== 'function') { + throw new Error("Could not extract the method from the transaction envelope."); + } + var invokeContractArgs = operation.func.value(); + if (!(invokeContractArgs !== null && invokeContractArgs !== void 0 && invokeContractArgs.functionName)) { + throw new Error("Could not extract the method name from the transaction envelope."); + } + var method = invokeContractArgs.functionName().toString('utf-8'); + var txn = new AssembledTransaction(_objectSpread(_objectSpread({}, options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + txn.built = built; + return txn; + } + }, { + key: "build", + value: function build(options) { + var _options$args; + var contract = new _stellarBase.Contract(options.contractId); + return AssembledTransaction.buildWithOp(contract.call.apply(contract, [options.method].concat(_toConsumableArray((_options$args = options.args) !== null && _options$args !== void 0 ? _options$args : []))), options); + } + }, { + key: "buildWithOp", + value: (function () { + var _buildWithOp = _asyncToGenerator(_regeneratorRuntime().mark(function _callee9(operation, options) { + var _options$fee, _options$timeoutInSec; + var tx, account; + return _regeneratorRuntime().wrap(function _callee9$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + tx = new AssembledTransaction(options); + _context10.next = 3; + return (0, _utils.getAccount)(options, tx.server); + case 3: + account = _context10.sent; + tx.raw = new _stellarBase.TransactionBuilder(account, { + fee: (_options$fee = options.fee) !== null && _options$fee !== void 0 ? _options$fee : _stellarBase.BASE_FEE, + networkPassphrase: options.networkPassphrase + }).setTimeout((_options$timeoutInSec = options.timeoutInSeconds) !== null && _options$timeoutInSec !== void 0 ? _options$timeoutInSec : _types.DEFAULT_TIMEOUT).addOperation(operation); + if (!options.simulate) { + _context10.next = 8; + break; + } + _context10.next = 8; + return tx.simulate(); + case 8: + return _context10.abrupt("return", tx); + case 9: + case "end": + return _context10.stop(); + } + }, _callee9); + })); + function buildWithOp(_x4, _x5) { + return _buildWithOp.apply(this, arguments); + } + return buildWithOp; + }()) + }, { + key: "buildFootprintRestoreTransaction", + value: function () { + var _buildFootprintRestoreTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee10(options, sorobanData, account, fee) { + var _options$timeoutInSec2; + var tx; + return _regeneratorRuntime().wrap(function _callee10$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + tx = new AssembledTransaction(options); + tx.raw = new _stellarBase.TransactionBuilder(account, { + fee: fee, + networkPassphrase: options.networkPassphrase + }).setSorobanData(sorobanData instanceof _stellarBase.SorobanDataBuilder ? sorobanData.build() : sorobanData).addOperation(_stellarBase.Operation.restoreFootprint({})).setTimeout((_options$timeoutInSec2 = options.timeoutInSeconds) !== null && _options$timeoutInSec2 !== void 0 ? _options$timeoutInSec2 : _types.DEFAULT_TIMEOUT); + _context11.next = 4; + return tx.simulate({ + restore: false + }); + case 4: + return _context11.abrupt("return", tx); + case 5: + case "end": + return _context11.stop(); + } + }, _callee10); + })); + function buildFootprintRestoreTransaction(_x6, _x7, _x8, _x9) { + return _buildFootprintRestoreTransaction.apply(this, arguments); + } + return buildFootprintRestoreTransaction; + }() + }]); +}(); +_defineProperty(AssembledTransaction, "Errors", { + ExpiredState: function (_Error) { + function ExpiredStateError() { + _classCallCheck(this, ExpiredStateError); + return _callSuper(this, ExpiredStateError, arguments); + } + _inherits(ExpiredStateError, _Error); + return _createClass(ExpiredStateError); + }(_wrapNativeSuper(Error)), + RestorationFailure: function (_Error2) { + function RestoreFailureError() { + _classCallCheck(this, RestoreFailureError); + return _callSuper(this, RestoreFailureError, arguments); + } + _inherits(RestoreFailureError, _Error2); + return _createClass(RestoreFailureError); + }(_wrapNativeSuper(Error)), + NeedsMoreSignatures: function (_Error3) { + function NeedsMoreSignaturesError() { + _classCallCheck(this, NeedsMoreSignaturesError); + return _callSuper(this, NeedsMoreSignaturesError, arguments); + } + _inherits(NeedsMoreSignaturesError, _Error3); + return _createClass(NeedsMoreSignaturesError); + }(_wrapNativeSuper(Error)), + NoSignatureNeeded: function (_Error4) { + function NoSignatureNeededError() { + _classCallCheck(this, NoSignatureNeededError); + return _callSuper(this, NoSignatureNeededError, arguments); + } + _inherits(NoSignatureNeededError, _Error4); + return _createClass(NoSignatureNeededError); + }(_wrapNativeSuper(Error)), + NoUnsignedNonInvokerAuthEntries: function (_Error5) { + function NoUnsignedNonInvokerAuthEntriesError() { + _classCallCheck(this, NoUnsignedNonInvokerAuthEntriesError); + return _callSuper(this, NoUnsignedNonInvokerAuthEntriesError, arguments); + } + _inherits(NoUnsignedNonInvokerAuthEntriesError, _Error5); + return _createClass(NoUnsignedNonInvokerAuthEntriesError); + }(_wrapNativeSuper(Error)), + NoSigner: function (_Error6) { + function NoSignerError() { + _classCallCheck(this, NoSignerError); + return _callSuper(this, NoSignerError, arguments); + } + _inherits(NoSignerError, _Error6); + return _createClass(NoSignerError); + }(_wrapNativeSuper(Error)), + NotYetSimulated: function (_Error7) { + function NotYetSimulatedError() { + _classCallCheck(this, NotYetSimulatedError); + return _callSuper(this, NotYetSimulatedError, arguments); + } + _inherits(NotYetSimulatedError, _Error7); + return _createClass(NotYetSimulatedError); + }(_wrapNativeSuper(Error)), + FakeAccount: function (_Error8) { + function FakeAccountError() { + _classCallCheck(this, FakeAccountError); + return _callSuper(this, FakeAccountError, arguments); + } + _inherits(FakeAccountError, _Error8); + return _createClass(FakeAccountError); + }(_wrapNativeSuper(Error)), + SimulationFailed: function (_Error9) { + function SimulationFailedError() { + _classCallCheck(this, SimulationFailedError); + return _callSuper(this, SimulationFailedError, arguments); + } + _inherits(SimulationFailedError, _Error9); + return _createClass(SimulationFailedError); + }(_wrapNativeSuper(Error)), + InternalWalletError: function (_Error10) { + function InternalWalletError() { + _classCallCheck(this, InternalWalletError); + return _callSuper(this, InternalWalletError, arguments); + } + _inherits(InternalWalletError, _Error10); + return _createClass(InternalWalletError); + }(_wrapNativeSuper(Error)), + ExternalServiceError: function (_Error11) { + function ExternalServiceError() { + _classCallCheck(this, ExternalServiceError); + return _callSuper(this, ExternalServiceError, arguments); + } + _inherits(ExternalServiceError, _Error11); + return _createClass(ExternalServiceError); + }(_wrapNativeSuper(Error)), + InvalidClientRequest: function (_Error12) { + function InvalidClientRequestError() { + _classCallCheck(this, InvalidClientRequestError); + return _callSuper(this, InvalidClientRequestError, arguments); + } + _inherits(InvalidClientRequestError, _Error12); + return _createClass(InvalidClientRequestError); + }(_wrapNativeSuper(Error)), + UserRejected: function (_Error13) { + function UserRejectedError() { + _classCallCheck(this, UserRejectedError); + return _callSuper(this, UserRejectedError, arguments); + } + _inherits(UserRejectedError, _Error13); + return _createClass(UserRejectedError); + }(_wrapNativeSuper(Error)) +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/basic_node_signer.d.ts b/node_modules/@stellar/stellar-sdk/lib/contract/basic_node_signer.d.ts new file mode 100644 index 000000000..b82cc36f3 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/basic_node_signer.d.ts @@ -0,0 +1,18 @@ +import { Keypair } from "@stellar/stellar-base"; +import { SignAuthEntry, SignTransaction } from "./types"; +/** + * For use with {@link Client} and {@link module:contract.AssembledTransaction}. + * Implements `signTransaction` and `signAuthEntry` with signatures expected by + * those classes. This is useful for testing and maybe some simple Node + * applications. Feel free to use this as a starting point for your own + * Wallet/TransactionSigner implementation. + * + * @memberof module:contract + * + * @param {Keypair} keypair {@link Keypair} to use to sign the transaction or auth entry + * @param {string} networkPassphrase passphrase of network to sign for + */ +export declare const basicNodeSigner: (keypair: Keypair, networkPassphrase: string) => { + signTransaction: SignTransaction; + signAuthEntry: SignAuthEntry; +}; diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/basic_node_signer.js b/node_modules/@stellar/stellar-sdk/lib/contract/basic_node_signer.js new file mode 100644 index 000000000..b91d3149a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/basic_node_signer.js @@ -0,0 +1,60 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.basicNodeSigner = void 0; +var _stellarBase = require("@stellar/stellar-base"); +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +var basicNodeSigner = exports.basicNodeSigner = function basicNodeSigner(keypair, networkPassphrase) { + return { + signTransaction: function () { + var _signTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(xdr, opts) { + var t; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + t = _stellarBase.TransactionBuilder.fromXDR(xdr, (opts === null || opts === void 0 ? void 0 : opts.networkPassphrase) || networkPassphrase); + t.sign(keypair); + return _context.abrupt("return", { + signedTxXdr: t.toXDR(), + signerAddress: keypair.publicKey() + }); + case 3: + case "end": + return _context.stop(); + } + }, _callee); + })); + function signTransaction(_x, _x2) { + return _signTransaction.apply(this, arguments); + } + return signTransaction; + }(), + signAuthEntry: function () { + var _signAuthEntry = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(authEntry) { + var signedAuthEntry; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + signedAuthEntry = keypair.sign((0, _stellarBase.hash)(Buffer.from(authEntry, "base64"))).toString("base64"); + return _context2.abrupt("return", { + signedAuthEntry: signedAuthEntry, + signerAddress: keypair.publicKey() + }); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function signAuthEntry(_x3) { + return _signAuthEntry.apply(this, arguments); + } + return signAuthEntry; + }() + }; +}; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/client.d.ts b/node_modules/@stellar/stellar-sdk/lib/contract/client.d.ts new file mode 100644 index 000000000..c41fb7d25 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/client.d.ts @@ -0,0 +1,64 @@ +import { Spec } from "./spec"; +import { AssembledTransaction } from "./assembled_transaction"; +import type { ClientOptions, MethodOptions } from "./types"; +/** + * Generate a class from the contract spec that where each contract method + * gets included with an identical name. + * + * Each method returns an {@link module:contract.AssembledTransaction | AssembledTransaction} that can + * be used to modify, simulate, decode results, and possibly sign, & submit the + * transaction. + * + * @memberof module:contract + * + * @class + * @param {module:contract.Spec} spec {@link Spec} to construct a Client for + * @param {ClientOptions} options see {@link ClientOptions} + */ +export declare class Client { + readonly spec: Spec; + readonly options: ClientOptions; + static deploy( + /** Constructor/Initialization Args for the contract's `__constructor` method */ + args: Record | null, + /** Options for initalizing a Client as well as for calling a method, with extras specific to deploying. */ + options: MethodOptions & Omit & { + /** The hash of the Wasm blob, which must already be installed on-chain. */ + wasmHash: Buffer | string; + /** Salt used to generate the contract's ID. Passed through to {@link Operation.createCustomContract}. Default: random. */ + salt?: Buffer | Uint8Array; + /** The format used to decode `wasmHash`, if it's provided as a string. */ + format?: "hex" | "base64"; + }): Promise>; + constructor(spec: Spec, options: ClientOptions); + /** + * Generates a Client instance from the provided ClientOptions and the contract's wasm hash. + * The wasmHash can be provided in either hex or base64 format. + * + * @param {Buffer | string} wasmHash The hash of the contract's wasm binary, in either hex or base64 format. + * @param {ClientOptions} options The ClientOptions object containing the necessary configuration, including the rpcUrl. + * @param {('hex' | 'base64')} [format='hex'] The format of the provided wasmHash, either "hex" or "base64". Defaults to "hex". + * @returns {Promise} A Promise that resolves to a Client instance. + * @throws {TypeError} If the provided options object does not contain an rpcUrl. + */ + static fromWasmHash(wasmHash: Buffer | string, options: ClientOptions, format?: "hex" | "base64"): Promise; + /** + * Generates a Client instance from the provided ClientOptions and the contract's wasm binary. + * + * @param {Buffer} wasm The contract's wasm binary as a Buffer. + * @param {ClientOptions} options The ClientOptions object containing the necessary configuration. + * @returns {Promise} A Promise that resolves to a Client instance. + * @throws {Error} If the contract spec cannot be obtained from the provided wasm binary. + */ + static fromWasm(wasm: Buffer, options: ClientOptions): Promise; + /** + * Generates a Client instance from the provided ClientOptions, which must include the contractId and rpcUrl. + * + * @param {ClientOptions} options The ClientOptions object containing the necessary configuration, including the contractId and rpcUrl. + * @returns {Promise} A Promise that resolves to a Client instance. + * @throws {TypeError} If the provided options object does not contain both rpcUrl and contractId. + */ + static from(options: ClientOptions): Promise; + txFromJSON: (json: string) => AssembledTransaction; + txFromXDR: (xdrBase64: string) => AssembledTransaction; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/client.js b/node_modules/@stellar/stellar-sdk/lib/contract/client.js new file mode 100644 index 000000000..4caa08ec6 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/client.js @@ -0,0 +1,291 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Client = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _spec = require("./spec"); +var _rpc = require("../rpc"); +var _assembled_transaction = require("./assembled_transaction"); +var _utils = require("./utils"); +var _excluded = ["method"], + _excluded2 = ["wasmHash", "salt", "format", "fee", "timeoutInSeconds", "simulate"]; +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } +function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +var CONSTRUCTOR_FUNC = "__constructor"; +function specFromWasm(_x) { + return _specFromWasm.apply(this, arguments); +} +function _specFromWasm() { + _specFromWasm = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(wasm) { + var wasmModule, xdrSections, bufferSection, specEntryArray, spec; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return WebAssembly.compile(wasm); + case 2: + wasmModule = _context5.sent; + xdrSections = WebAssembly.Module.customSections(wasmModule, "contractspecv0"); + if (!(xdrSections.length === 0)) { + _context5.next = 6; + break; + } + throw new Error("Could not obtain contract spec from wasm"); + case 6: + bufferSection = Buffer.from(xdrSections[0]); + specEntryArray = (0, _utils.processSpecEntryStream)(bufferSection); + spec = new _spec.Spec(specEntryArray); + return _context5.abrupt("return", spec); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _specFromWasm.apply(this, arguments); +} +function specFromWasmHash(_x2, _x3) { + return _specFromWasmHash.apply(this, arguments); +} +function _specFromWasmHash() { + _specFromWasmHash = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + format = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context6.next = 3; + break; + } + throw new TypeError("options must contain rpcUrl"); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new _rpc.Server(rpcUrl, serverOpts); + _context6.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context6.sent; + return _context6.abrupt("return", specFromWasm(wasm)); + case 10: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _specFromWasmHash.apply(this, arguments); +} +var Client = exports.Client = function () { + function Client(spec, options) { + var _this = this; + _classCallCheck(this, Client); + _defineProperty(this, "txFromJSON", function (json) { + var _JSON$parse = JSON.parse(json), + method = _JSON$parse.method, + tx = _objectWithoutProperties(_JSON$parse, _excluded); + return _assembled_transaction.AssembledTransaction.fromJSON(_objectSpread(_objectSpread({}, _this.options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return _this.spec.funcResToNative(method, result); + } + }), tx); + }); + _defineProperty(this, "txFromXDR", function (xdrBase64) { + return _assembled_transaction.AssembledTransaction.fromXDR(_this.options, xdrBase64, _this.spec); + }); + this.spec = spec; + this.options = options; + this.spec.funcs().forEach(function (xdrFn) { + var method = xdrFn.name().toString(); + if (method === CONSTRUCTOR_FUNC) { + return; + } + var assembleTransaction = function assembleTransaction(args, methodOptions) { + return _assembled_transaction.AssembledTransaction.build(_objectSpread(_objectSpread(_objectSpread({ + method: method, + args: args && spec.funcArgsToScVals(method, args) + }, options), methodOptions), {}, { + errorTypes: spec.errorCases().reduce(function (acc, curr) { + return _objectSpread(_objectSpread({}, acc), {}, _defineProperty({}, curr.value(), { + message: curr.doc().toString() + })); + }, {}), + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + }; + _this[method] = spec.getFunc(method).inputs().length === 0 ? function (opts) { + return assembleTransaction(undefined, opts); + } : assembleTransaction; + }); + } + return _createClass(Client, null, [{ + key: "deploy", + value: function () { + var _deploy = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(args, options) { + var wasmHash, salt, format, fee, timeoutInSeconds, simulate, clientOptions, spec, operation; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + wasmHash = options.wasmHash, salt = options.salt, format = options.format, fee = options.fee, timeoutInSeconds = options.timeoutInSeconds, simulate = options.simulate, clientOptions = _objectWithoutProperties(options, _excluded2); + _context.next = 3; + return specFromWasmHash(wasmHash, clientOptions, format); + case 3: + spec = _context.sent; + operation = _stellarBase.Operation.createCustomContract({ + address: new _stellarBase.Address(options.publicKey), + wasmHash: typeof wasmHash === "string" ? Buffer.from(wasmHash, format !== null && format !== void 0 ? format : "hex") : wasmHash, + salt: salt, + constructorArgs: args ? spec.funcArgsToScVals(CONSTRUCTOR_FUNC, args) : [] + }); + return _context.abrupt("return", _assembled_transaction.AssembledTransaction.buildWithOp(operation, _objectSpread(_objectSpread({ + fee: fee, + timeoutInSeconds: timeoutInSeconds, + simulate: simulate + }, clientOptions), {}, { + contractId: "ignored", + method: CONSTRUCTOR_FUNC, + parseResultXdr: function parseResultXdr(result) { + return new Client(spec, _objectSpread(_objectSpread({}, clientOptions), {}, { + contractId: _stellarBase.Address.fromScVal(result).toString() + })); + } + }))); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + function deploy(_x4, _x5) { + return _deploy.apply(this, arguments); + } + return deploy; + }() + }, { + key: "fromWasmHash", + value: (function () { + var _fromWasmHash = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args2 = arguments; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + format = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context2.next = 3; + break; + } + throw new TypeError('options must contain rpcUrl'); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new _rpc.Server(rpcUrl, serverOpts); + _context2.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context2.sent; + return _context2.abrupt("return", Client.fromWasm(wasm, options)); + case 10: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function fromWasmHash(_x6, _x7) { + return _fromWasmHash.apply(this, arguments); + } + return fromWasmHash; + }()) + }, { + key: "fromWasm", + value: (function () { + var _fromWasm = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(wasm, options) { + var spec; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return specFromWasm(wasm); + case 2: + spec = _context3.sent; + return _context3.abrupt("return", new Client(spec, options)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + function fromWasm(_x8, _x9) { + return _fromWasm.apply(this, arguments); + } + return fromWasm; + }()) + }, { + key: "from", + value: (function () { + var _from = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(options) { + var rpcUrl, contractId, allowHttp, serverOpts, server, wasm; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(!options || !options.rpcUrl || !options.contractId)) { + _context4.next = 2; + break; + } + throw new TypeError('options must contain rpcUrl and contractId'); + case 2: + rpcUrl = options.rpcUrl, contractId = options.contractId, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new _rpc.Server(rpcUrl, serverOpts); + _context4.next = 7; + return server.getContractWasmByContractId(contractId); + case 7: + wasm = _context4.sent; + return _context4.abrupt("return", Client.fromWasm(wasm, options)); + case 9: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function from(_x10) { + return _from.apply(this, arguments); + } + return from; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/contract/index.d.ts new file mode 100644 index 000000000..8b9e1dc5e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/index.d.ts @@ -0,0 +1,7 @@ +export * from "./assembled_transaction"; +export * from "./basic_node_signer"; +export * from "./client"; +export * from "./rust_result"; +export * from "./sent_transaction"; +export * from "./spec"; +export * from "./types"; diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/index.js b/node_modules/@stellar/stellar-sdk/lib/contract/index.js new file mode 100644 index 000000000..9a10eddfc --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/index.js @@ -0,0 +1,82 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _assembled_transaction = require("./assembled_transaction"); +Object.keys(_assembled_transaction).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _assembled_transaction[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _assembled_transaction[key]; + } + }); +}); +var _basic_node_signer = require("./basic_node_signer"); +Object.keys(_basic_node_signer).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _basic_node_signer[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _basic_node_signer[key]; + } + }); +}); +var _client = require("./client"); +Object.keys(_client).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _client[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _client[key]; + } + }); +}); +var _rust_result = require("./rust_result"); +Object.keys(_rust_result).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _rust_result[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _rust_result[key]; + } + }); +}); +var _sent_transaction = require("./sent_transaction"); +Object.keys(_sent_transaction).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _sent_transaction[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _sent_transaction[key]; + } + }); +}); +var _spec = require("./spec"); +Object.keys(_spec).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _spec[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _spec[key]; + } + }); +}); +var _types = require("./types"); +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _types[key]; + } + }); +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/rust_result.d.ts b/node_modules/@stellar/stellar-sdk/lib/contract/rust_result.d.ts new file mode 100644 index 000000000..f72a123e1 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/rust_result.d.ts @@ -0,0 +1,81 @@ +/** + * A minimal implementation of Rust's `Result` type. Used for contract + * methods that return Results, to maintain their distinction from methods + * that simply either return a value or throw. + * + * #### Why is this needed? + * + * This is used by {@link module:contract.Spec | `ContractSpec`} and + * {@link module:contract.AssembledTransaction | `AssembledTransaction`} when + * parsing values return by contracts. + * + * Contract methods can be implemented to return simple values, in which case + * they can also throw errors. This matches JavaScript's most idiomatic + * workflow, using `try...catch` blocks. + * + * But Rust also gives the flexibility of returning `Result` types. And Soroban + * contracts further support this with the `#[contracterror]` macro. Should + * JavaScript calls to such methods ignore all of that, and just flatten this + * extra info down to the same `try...catch` flow as other methods? We're not + * sure. + * + * For now, we've added this minimal implementation of Rust's `Result` logic, + * which exports the `Result` interface and its associated implementations, + * `Ok` and `Err`. This allows `ContractSpec` and `AssembledTransaction` to + * work together to duplicate the contract's Rust logic, always returning + * `Result` types for contract methods that are implemented to do so. + * + * In the future, if this feels too un-idiomatic for JavaScript, we can always + * remove this and flatten all JS calls to `try...catch`. Easier to remove this + * logic later than it would be to add it. + * + * @memberof module:contract + */ +export interface Result { + unwrap(): T; + unwrapErr(): E; + isOk(): boolean; + isErr(): boolean; +} +/** + * Error interface containing the error message. Matches Rust's implementation. + * Part of implementing {@link module:contract.Result | Result}, a minimal + * implementation of Rust's `Result` type. Used for contract methods that return + * Results, to maintain their distinction from methods that simply either return + * a value or throw. + * + * @memberof module:contract + */ +export interface ErrorMessage { + message: string; +} +/** + * Part of implementing {@link module:contract.Result | Result}, a minimal + * implementation of Rust's `Result` type. Used for contract methods that return + * Results, to maintain their distinction from methods that simply either return + * a value or throw. + * @private + */ +export declare class Ok implements Result { + readonly value: T; + constructor(value: T); + unwrapErr(): never; + unwrap(): T; + isOk(): boolean; + isErr(): boolean; +} +/** + * Part of implementing {@link module:contract.Result | Result}, a minimal + * implementation of Rust's `Result` type. Used for contract methods that return + * Results, to maintain their distinction from methods that simply either return + * a value or throw. + * @private + */ +export declare class Err implements Result { + readonly error: E; + constructor(error: E); + unwrapErr(): E; + unwrap(): never; + isOk(): boolean; + isErr(): boolean; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/rust_result.js b/node_modules/@stellar/stellar-sdk/lib/contract/rust_result.js new file mode 100644 index 000000000..5cbad1179 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/rust_result.js @@ -0,0 +1,66 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Ok = exports.Err = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Ok = exports.Ok = function () { + function Ok(value) { + _classCallCheck(this, Ok); + this.value = value; + } + return _createClass(Ok, [{ + key: "unwrapErr", + value: function unwrapErr() { + throw new Error("No error"); + } + }, { + key: "unwrap", + value: function unwrap() { + return this.value; + } + }, { + key: "isOk", + value: function isOk() { + return true; + } + }, { + key: "isErr", + value: function isErr() { + return false; + } + }]); +}(); +var Err = exports.Err = function () { + function Err(error) { + _classCallCheck(this, Err); + this.error = error; + } + return _createClass(Err, [{ + key: "unwrapErr", + value: function unwrapErr() { + return this.error; + } + }, { + key: "unwrap", + value: function unwrap() { + throw new Error(this.error.message); + } + }, { + key: "isOk", + value: function isOk() { + return false; + } + }, { + key: "isErr", + value: function isErr() { + return true; + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/sent_transaction.d.ts b/node_modules/@stellar/stellar-sdk/lib/contract/sent_transaction.d.ts new file mode 100644 index 000000000..ab3234a2d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/sent_transaction.d.ts @@ -0,0 +1,84 @@ +import { Server } from "../rpc"; +import { Api } from "../rpc/api"; +import type { AssembledTransaction } from "./assembled_transaction"; +/** + * A transaction that has been sent to the Soroban network. This happens in two steps: + * + * 1. `sendTransaction`: initial submission of the transaction to the network. + * If this step runs into problems, the attempt to sign and send will be + * aborted. You can see the result of this call in the + * `sendTransactionResponse` getter. + * 2. `getTransaction`: once the transaction has been submitted to the network + * successfully, you need to wait for it to finalize to get the result of the + * transaction. This will be retried with exponential backoff for + * {@link MethodOptions.timeoutInSeconds} seconds. See all attempts in + * `getTransactionResponseAll` and the most recent attempt in + * `getTransactionResponse`. + * + * @memberof module:contract + * @class + * + * @param {Function} signTransaction More info in {@link MethodOptions} + * @param {module:contract.AssembledTransaction} assembled {@link AssembledTransaction} from which this SentTransaction was initialized + */ +export declare class SentTransaction { + assembled: AssembledTransaction; + server: Server; + /** + * The result of calling `sendTransaction` to broadcast the transaction to the + * network. + */ + sendTransactionResponse?: Api.SendTransactionResponse; + /** + * If `sendTransaction` completes successfully (which means it has `status: 'PENDING'`), + * then `getTransaction` will be called in a loop for + * {@link MethodOptions.timeoutInSeconds} seconds. This array contains all + * the results of those calls. + */ + getTransactionResponseAll?: Api.GetTransactionResponse[]; + /** + * The most recent result of calling `getTransaction`, from the + * `getTransactionResponseAll` array. + */ + getTransactionResponse?: Api.GetTransactionResponse; + static Errors: { + SendFailed: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + SendResultOnly: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + TransactionStillPending: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + }; + constructor(assembled: AssembledTransaction); + /** + * Initialize a `SentTransaction` from `options` and a `signed` + * AssembledTransaction. This will also send the transaction to the network. + */ + static init: (assembled: AssembledTransaction) => Promise>; + private send; + get result(): T; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/sent_transaction.js b/node_modules/@stellar/stellar-sdk/lib/contract/sent_transaction.js new file mode 100644 index 000000000..03d0948b5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/sent_transaction.js @@ -0,0 +1,151 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SentTransaction = void 0; +var _rpc = require("../rpc"); +var _api = require("../rpc/api"); +var _utils = require("./utils"); +var _types = require("./types"); +var _SentTransaction; +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var SentTransaction = exports.SentTransaction = function () { + function SentTransaction(assembled) { + var _this = this, + _this$assembled$optio2; + _classCallCheck(this, SentTransaction); + _defineProperty(this, "send", _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var _this$assembled$optio; + var hash, timeoutInSeconds; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return _this.server.sendTransaction(_this.assembled.signed); + case 2: + _this.sendTransactionResponse = _context.sent; + if (!(_this.sendTransactionResponse.status !== "PENDING")) { + _context.next = 5; + break; + } + throw new SentTransaction.Errors.SendFailed("Sending the transaction to the network failed!\n".concat(JSON.stringify(_this.sendTransactionResponse, null, 2))); + case 5: + hash = _this.sendTransactionResponse.hash; + timeoutInSeconds = (_this$assembled$optio = _this.assembled.options.timeoutInSeconds) !== null && _this$assembled$optio !== void 0 ? _this$assembled$optio : _types.DEFAULT_TIMEOUT; + _context.next = 9; + return (0, _utils.withExponentialBackoff)(function () { + return _this.server.getTransaction(hash); + }, function (resp) { + return resp.status === _api.Api.GetTransactionStatus.NOT_FOUND; + }, timeoutInSeconds); + case 9: + _this.getTransactionResponseAll = _context.sent; + _this.getTransactionResponse = _this.getTransactionResponseAll[_this.getTransactionResponseAll.length - 1]; + if (!(_this.getTransactionResponse.status === _api.Api.GetTransactionStatus.NOT_FOUND)) { + _context.next = 13; + break; + } + throw new SentTransaction.Errors.TransactionStillPending("Waited ".concat(timeoutInSeconds, " seconds for transaction to complete, but it did not. ") + "Returning anyway. Check the transaction status manually. " + "Sent transaction: ".concat(JSON.stringify(_this.sendTransactionResponse, null, 2), "\n") + "All attempts to get the result: ".concat(JSON.stringify(_this.getTransactionResponseAll, null, 2))); + case 13: + return _context.abrupt("return", _this); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + }))); + this.assembled = assembled; + this.server = new _rpc.Server(this.assembled.options.rpcUrl, { + allowHttp: (_this$assembled$optio2 = this.assembled.options.allowHttp) !== null && _this$assembled$optio2 !== void 0 ? _this$assembled$optio2 : false + }); + } + return _createClass(SentTransaction, [{ + key: "result", + get: function get() { + if ("getTransactionResponse" in this && this.getTransactionResponse) { + if ("returnValue" in this.getTransactionResponse) { + return this.assembled.options.parseResultXdr(this.getTransactionResponse.returnValue); + } + throw new Error("Transaction failed! Cannot parse result."); + } + if (this.sendTransactionResponse) { + var _this$sendTransaction; + var errorResult = (_this$sendTransaction = this.sendTransactionResponse.errorResult) === null || _this$sendTransaction === void 0 ? void 0 : _this$sendTransaction.result(); + if (errorResult) { + throw new SentTransaction.Errors.SendFailed("Transaction simulation looked correct, but attempting to send the transaction failed. Check `simulation` and `sendTransactionResponseAll` to troubleshoot. Decoded `sendTransactionResponse.errorResultXdr`: ".concat(errorResult)); + } + throw new SentTransaction.Errors.SendResultOnly("Transaction was sent to the network, but not yet awaited. No result to show. Await transaction completion with `getTransaction(sendTransactionResponse.hash)`"); + } + throw new Error("Sending transaction failed: ".concat(JSON.stringify(this.assembled.signed))); + } + }]); +}(); +_SentTransaction = SentTransaction; +_defineProperty(SentTransaction, "Errors", { + SendFailed: function (_Error) { + function SendFailedError() { + _classCallCheck(this, SendFailedError); + return _callSuper(this, SendFailedError, arguments); + } + _inherits(SendFailedError, _Error); + return _createClass(SendFailedError); + }(_wrapNativeSuper(Error)), + SendResultOnly: function (_Error2) { + function SendResultOnlyError() { + _classCallCheck(this, SendResultOnlyError); + return _callSuper(this, SendResultOnlyError, arguments); + } + _inherits(SendResultOnlyError, _Error2); + return _createClass(SendResultOnlyError); + }(_wrapNativeSuper(Error)), + TransactionStillPending: function (_Error3) { + function TransactionStillPendingError() { + _classCallCheck(this, TransactionStillPendingError); + return _callSuper(this, TransactionStillPendingError, arguments); + } + _inherits(TransactionStillPendingError, _Error3); + return _createClass(TransactionStillPendingError); + }(_wrapNativeSuper(Error)) +}); +_defineProperty(SentTransaction, "init", function () { + var _ref2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(assembled) { + var tx, sent; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + tx = new _SentTransaction(assembled); + _context2.next = 3; + return tx.send(); + case 3: + sent = _context2.sent; + return _context2.abrupt("return", sent); + case 5: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; +}()); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/spec.d.ts b/node_modules/@stellar/stellar-sdk/lib/contract/spec.d.ts new file mode 100644 index 000000000..737c8c464 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/spec.d.ts @@ -0,0 +1,152 @@ +import type { JSONSchema7 } from "json-schema"; +import { xdr } from "@stellar/stellar-base"; +export interface Union { + tag: string; + values?: T; +} +/** + * Provides a ContractSpec class which can contains the XDR types defined by the contract. + * This allows the class to be used to convert between native and raw `xdr.ScVal`s. + * + * Constructs a new ContractSpec from an array of XDR spec entries. + * + * @memberof module:contract + * @param {xdr.ScSpecEntry[] | string[]} entries the XDR spec entries + * @throws {Error} if entries is invalid + * + * @example + * const specEntries = [...]; // XDR spec entries of a smart contract + * const contractSpec = new ContractSpec(specEntries); + * + * // Convert native value to ScVal + * const args = { + * arg1: 'value1', + * arg2: 1234 + * }; + * const scArgs = contractSpec.funcArgsToScVals('funcName', args); + * + * // Call contract + * const resultScv = await callContract(contractId, 'funcName', scArgs); + * + * // Convert result ScVal back to native value + * const result = contractSpec.funcResToNative('funcName', resultScv); + * + * console.log(result); // {success: true} + */ +export declare class Spec { + /** + * The XDR spec entries. + */ + entries: xdr.ScSpecEntry[]; + constructor(entries: xdr.ScSpecEntry[] | string[]); + /** + * Gets the XDR functions from the spec. + * @returns {xdr.ScSpecFunctionV0[]} all contract functions + */ + funcs(): xdr.ScSpecFunctionV0[]; + /** + * Gets the XDR function spec for the given function name. + * + * @param {string} name the name of the function + * @returns {xdr.ScSpecFunctionV0} the function spec + * + * @throws {Error} if no function with the given name exists + */ + getFunc(name: string): xdr.ScSpecFunctionV0; + /** + * Converts native JS arguments to ScVals for calling a contract function. + * + * @param {string} name the name of the function + * @param {object} args the arguments object + * @returns {xdr.ScVal[]} the converted arguments + * + * @throws {Error} if argument is missing or incorrect type + * + * @example + * const args = { + * arg1: 'value1', + * arg2: 1234 + * }; + * const scArgs = contractSpec.funcArgsToScVals('funcName', args); + */ + funcArgsToScVals(name: string, args: object): xdr.ScVal[]; + /** + * Converts the result ScVal of a function call to a native JS value. + * + * @param {string} name the name of the function + * @param {xdr.ScVal | string} val_or_base64 the result ScVal or base64 encoded string + * @returns {any} the converted native value + * + * @throws {Error} if return type mismatch or invalid input + * + * @example + * const resultScv = 'AAA=='; // Base64 encoded ScVal + * const result = contractSpec.funcResToNative('funcName', resultScv); + */ + funcResToNative(name: string, val_or_base64: xdr.ScVal | string): any; + /** + * Finds the XDR spec entry for the given name. + * + * @param {string} name the name to find + * @returns {xdr.ScSpecEntry} the entry + * + * @throws {Error} if no entry with the given name exists + */ + findEntry(name: string): xdr.ScSpecEntry; + /** + * Converts a native JS value to an ScVal based on the given type. + * + * @param {any} val the native JS value + * @param {xdr.ScSpecTypeDef} [ty] the expected type + * @returns {xdr.ScVal} the converted ScVal + * + * @throws {Error} if value cannot be converted to the given type + */ + nativeToScVal(val: any, ty: xdr.ScSpecTypeDef): xdr.ScVal; + private nativeToUdt; + private nativeToUnion; + private nativeToStruct; + private nativeToEnum; + /** + * Converts an base64 encoded ScVal back to a native JS value based on the given type. + * + * @param {string} scv the base64 encoded ScVal + * @param {xdr.ScSpecTypeDef} typeDef the expected type + * @returns {any} the converted native JS value + * + * @throws {Error} if ScVal cannot be converted to the given type + */ + scValStrToNative(scv: string, typeDef: xdr.ScSpecTypeDef): T; + /** + * Converts an ScVal back to a native JS value based on the given type. + * + * @param {xdr.ScVal} scv the ScVal + * @param {xdr.ScSpecTypeDef} typeDef the expected type + * @returns {any} the converted native JS value + * + * @throws {Error} if ScVal cannot be converted to the given type + */ + scValToNative(scv: xdr.ScVal, typeDef: xdr.ScSpecTypeDef): T; + private scValUdtToNative; + private unionToNative; + private structToNative; + private enumToNative; + /** + * Gets the XDR error cases from the spec. + * + * @returns {xdr.ScSpecFunctionV0[]} all contract functions + * + */ + errorCases(): xdr.ScSpecUdtErrorEnumCaseV0[]; + /** + * Converts the contract spec to a JSON schema. + * + * If `funcName` is provided, the schema will be a reference to the function schema. + * + * @param {string} [funcName] the name of the function to convert + * @returns {JSONSchema7} the converted JSON schema + * + * @throws {Error} if the contract spec is invalid + */ + jsonSchema(funcName?: string): JSONSchema7; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/spec.js b/node_modules/@stellar/stellar-sdk/lib/contract/spec.js new file mode 100644 index 000000000..1a70b3d2f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/spec.js @@ -0,0 +1,1020 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Spec = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _rust_result = require("./rust_result"); +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function enumToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + var title = aCase.name().toString(); + var desc = aCase.doc().toString(); + oneOf.push({ + description: desc, + title: title, + enum: [aCase.value()], + type: "number" + }); + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +function isNumeric(field) { + return /^\d+$/.test(field.name().toString()); +} +function readObj(args, input) { + var inputName = input.name().toString(); + var entry = Object.entries(args).find(function (_ref) { + var _ref2 = _slicedToArray(_ref, 1), + name = _ref2[0]; + return name === inputName; + }); + if (!entry) { + throw new Error("Missing field ".concat(inputName)); + } + return entry[1]; +} +function findCase(name) { + return function matches(entry) { + switch (entry.switch().value) { + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var tuple = entry.tupleCase(); + return tuple.name().toString() === name; + } + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var voidCase = entry.voidCase(); + return voidCase.name().toString() === name; + } + default: + return false; + } + }; +} +function stringToScVal(str, ty) { + switch (ty.value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeString().value: + return _stellarBase.xdr.ScVal.scvString(str); + case _stellarBase.xdr.ScSpecType.scSpecTypeSymbol().value: + return _stellarBase.xdr.ScVal.scvSymbol(str); + case _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value: + { + var addr = _stellarBase.Address.fromString(str); + return _stellarBase.xdr.ScVal.scvAddress(addr.toScAddress()); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU64().value: + return new _stellarBase.XdrLargeInt("u64", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeI64().value: + return new _stellarBase.XdrLargeInt("i64", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeU128().value: + return new _stellarBase.XdrLargeInt("u128", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeI128().value: + return new _stellarBase.XdrLargeInt("i128", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeU256().value: + return new _stellarBase.XdrLargeInt("u256", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeI256().value: + return new _stellarBase.XdrLargeInt("i256", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeBytes().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeBytesN().value: + return _stellarBase.xdr.ScVal.scvBytes(Buffer.from(str, "base64")); + default: + throw new TypeError("invalid type ".concat(ty.name, " specified for string value")); + } +} +var PRIMITIVE_DEFINITONS = { + U32: { + type: "integer", + minimum: 0, + maximum: 4294967295 + }, + I32: { + type: "integer", + minimum: -2147483648, + maximum: 2147483647 + }, + U64: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 20 + }, + I64: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 21 + }, + U128: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 39 + }, + I128: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 40 + }, + U256: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 78 + }, + I256: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 79 + }, + Address: { + type: "string", + format: "address", + description: "Address can be a public key or contract id" + }, + ScString: { + type: "string", + description: "ScString is a string" + }, + ScSymbol: { + type: "string", + description: "ScString is a string" + }, + DataUrl: { + type: "string", + pattern: "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$" + } +}; +function typeRef(typeDef) { + var t = typeDef.switch(); + var value = t.value; + var ref; + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVal().value: + { + ref = "Val"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBool().value: + { + return { + type: "boolean" + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeVoid().value: + { + return { + type: "null" + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeError().value: + { + ref = "Error"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU32().value: + { + ref = "U32"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI32().value: + { + ref = "I32"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU64().value: + { + ref = "U64"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI64().value: + { + ref = "I64"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeTimepoint().value: + { + throw new Error("Timepoint type not supported"); + ref = "Timepoint"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeDuration().value: + { + throw new Error("Duration not supported"); + ref = "Duration"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU128().value: + { + ref = "U128"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI128().value: + { + ref = "I128"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU256().value: + { + ref = "U256"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI256().value: + { + ref = "I256"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBytes().value: + { + ref = "DataUrl"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeString().value: + { + ref = "ScString"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeSymbol().value: + { + ref = "ScSymbol"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value: + { + ref = "Address"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeOption().value: + { + var opt = typeDef.option(); + return typeRef(opt.valueType()); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeResult().value: + { + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeVec().value: + { + var arr = typeDef.vec(); + var reference = typeRef(arr.elementType()); + return { + type: "array", + items: reference + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = typeDef.map(); + var items = [typeRef(map.keyType()), typeRef(map.valueType())]; + return { + type: "array", + items: { + type: "array", + items: items, + minItems: 2, + maxItems: 2 + } + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tuple = typeDef.tuple(); + var minItems = tuple.valueTypes().length; + var maxItems = minItems; + var _items = tuple.valueTypes().map(typeRef); + return { + type: "array", + items: _items, + minItems: minItems, + maxItems: maxItems + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var _arr = typeDef.bytesN(); + return { + $ref: "#/definitions/DataUrl", + maxLength: _arr.n() + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeUdt().value: + { + var udt = typeDef.udt(); + ref = udt.name().toString(); + break; + } + } + return { + $ref: "#/definitions/".concat(ref) + }; +} +function isRequired(typeDef) { + return typeDef.switch().value !== _stellarBase.xdr.ScSpecType.scSpecTypeOption().value; +} +function argsAndRequired(input) { + var properties = {}; + var required = []; + input.forEach(function (arg) { + var aType = arg.type(); + var name = arg.name().toString(); + properties[name] = typeRef(aType); + if (isRequired(aType)) { + required.push(name); + } + }); + var res = { + properties: properties + }; + if (required.length > 0) { + res.required = required; + } + return res; +} +function structToJsonSchema(udt) { + var fields = udt.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + var items = fields.map(function (_, i) { + return typeRef(fields[i].type()); + }); + return { + type: "array", + items: items, + minItems: fields.length, + maxItems: fields.length + }; + } + var description = udt.doc().toString(); + var _argsAndRequired = argsAndRequired(fields), + properties = _argsAndRequired.properties, + required = _argsAndRequired.required; + properties.additionalProperties = false; + return { + description: description, + properties: properties, + required: required, + type: "object" + }; +} +function functionToJsonSchema(func) { + var _argsAndRequired2 = argsAndRequired(func.inputs()), + properties = _argsAndRequired2.properties, + required = _argsAndRequired2.required; + var args = { + additionalProperties: false, + properties: properties, + type: "object" + }; + if ((required === null || required === void 0 ? void 0 : required.length) > 0) { + args.required = required; + } + var input = { + properties: { + args: args + } + }; + var outputs = func.outputs(); + var output = outputs.length > 0 ? typeRef(outputs[0]) : typeRef(_stellarBase.xdr.ScSpecTypeDef.scSpecTypeVoid()); + var description = func.doc().toString(); + if (description.length > 0) { + input.description = description; + } + input.additionalProperties = false; + output.additionalProperties = false; + return { + input: input, + output: output + }; +} +function unionToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + switch (aCase.switch().value) { + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var c = aCase.voidCase(); + var title = c.name().toString(); + oneOf.push({ + type: "object", + title: title, + properties: { + tag: title + }, + additionalProperties: false, + required: ["tag"] + }); + break; + } + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var _c = aCase.tupleCase(); + var _title = _c.name().toString(); + oneOf.push({ + type: "object", + title: _title, + properties: { + tag: _title, + values: { + type: "array", + items: _c.type().map(typeRef) + } + }, + required: ["tag", "values"], + additionalProperties: false + }); + } + } + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +var Spec = exports.Spec = function () { + function Spec(entries) { + _classCallCheck(this, Spec); + _defineProperty(this, "entries", []); + if (entries.length === 0) { + throw new Error("Contract spec must have at least one entry"); + } + var entry = entries[0]; + if (typeof entry === "string") { + this.entries = entries.map(function (s) { + return _stellarBase.xdr.ScSpecEntry.fromXDR(s, "base64"); + }); + } else { + this.entries = entries; + } + } + return _createClass(Spec, [{ + key: "funcs", + value: function funcs() { + return this.entries.filter(function (entry) { + return entry.switch().value === _stellarBase.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value; + }).map(function (entry) { + return entry.functionV0(); + }); + } + }, { + key: "getFunc", + value: function getFunc(name) { + var entry = this.findEntry(name); + if (entry.switch().value !== _stellarBase.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value) { + throw new Error("".concat(name, " is not a function")); + } + return entry.functionV0(); + } + }, { + key: "funcArgsToScVals", + value: function funcArgsToScVals(name, args) { + var _this = this; + var fn = this.getFunc(name); + return fn.inputs().map(function (input) { + return _this.nativeToScVal(readObj(args, input), input.type()); + }); + } + }, { + key: "funcResToNative", + value: function funcResToNative(name, val_or_base64) { + var val = typeof val_or_base64 === "string" ? _stellarBase.xdr.ScVal.fromXDR(val_or_base64, "base64") : val_or_base64; + var func = this.getFunc(name); + var outputs = func.outputs(); + if (outputs.length === 0) { + var type = val.switch(); + if (type.value !== _stellarBase.xdr.ScValType.scvVoid().value) { + throw new Error("Expected void, got ".concat(type.name)); + } + return null; + } + if (outputs.length > 1) { + throw new Error("Multiple outputs not supported"); + } + var output = outputs[0]; + if (output.switch().value === _stellarBase.xdr.ScSpecType.scSpecTypeResult().value) { + return new _rust_result.Ok(this.scValToNative(val, output.result().okType())); + } + return this.scValToNative(val, output); + } + }, { + key: "findEntry", + value: function findEntry(name) { + var entry = this.entries.find(function (e) { + return e.value().name().toString() === name; + }); + if (!entry) { + throw new Error("no such entry: ".concat(name)); + } + return entry; + } + }, { + key: "nativeToScVal", + value: function nativeToScVal(val, ty) { + var _this2 = this; + var t = ty.switch(); + var value = t.value; + if (t.value === _stellarBase.xdr.ScSpecType.scSpecTypeUdt().value) { + var udt = ty.udt(); + return this.nativeToUdt(val, udt.name().toString()); + } + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeOption().value) { + var opt = ty.option(); + if (val === undefined) { + return _stellarBase.xdr.ScVal.scvVoid(); + } + return this.nativeToScVal(val, opt.valueType()); + } + switch (_typeof(val)) { + case "object": + { + var _val$constructor$name, _val$constructor; + if (val === null) { + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVoid().value: + return _stellarBase.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was null")); + } + } + if (val instanceof _stellarBase.xdr.ScVal) { + return val; + } + if (val instanceof _stellarBase.Address) { + if (ty.switch().value !== _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.toScVal(); + } + if (val instanceof _stellarBase.Contract) { + if (ty.switch().value !== _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.address().toScVal(); + } + if (val instanceof Uint8Array || Buffer.isBuffer(val)) { + var copy = Uint8Array.from(val); + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var bytesN = ty.bytesN(); + if (copy.length !== bytesN.n()) { + throw new TypeError("expected ".concat(bytesN.n(), " bytes, but got ").concat(copy.length)); + } + return _stellarBase.xdr.ScVal.scvBytes(copy); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBytes().value: + return _stellarBase.xdr.ScVal.scvBytes(copy); + default: + throw new TypeError("invalid type (".concat(ty, ") specified for Bytes and BytesN")); + } + } + if (Array.isArray(val)) { + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVec().value: + { + var vec = ty.vec(); + var elementType = vec.elementType(); + return _stellarBase.xdr.ScVal.scvVec(val.map(function (v) { + return _this2.nativeToScVal(v, elementType); + })); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tup = ty.tuple(); + var valTypes = tup.valueTypes(); + if (val.length !== valTypes.length) { + throw new TypeError("Tuple expects ".concat(valTypes.length, " values, but ").concat(val.length, " were provided")); + } + return _stellarBase.xdr.ScVal.scvVec(val.map(function (v, i) { + return _this2.nativeToScVal(v, valTypes[i]); + })); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = ty.map(); + var keyType = map.keyType(); + var valueType = map.valueType(); + return _stellarBase.xdr.ScVal.scvMap(val.map(function (entry) { + var key = _this2.nativeToScVal(entry[0], keyType); + var mapVal = _this2.nativeToScVal(entry[1], valueType); + return new _stellarBase.xdr.ScMapEntry({ + key: key, + val: mapVal + }); + })); + } + default: + throw new TypeError("Type ".concat(ty, " was not vec, but value was Array")); + } + } + if (val.constructor === Map) { + if (value !== _stellarBase.xdr.ScSpecType.scSpecTypeMap().value) { + throw new TypeError("Type ".concat(ty, " was not map, but value was Map")); + } + var scMap = ty.map(); + var _map = val; + var entries = []; + var values = _map.entries(); + var res = values.next(); + while (!res.done) { + var _res$value = _slicedToArray(res.value, 2), + k = _res$value[0], + v = _res$value[1]; + var key = this.nativeToScVal(k, scMap.keyType()); + var mapval = this.nativeToScVal(v, scMap.valueType()); + entries.push(new _stellarBase.xdr.ScMapEntry({ + key: key, + val: mapval + })); + res = values.next(); + } + return _stellarBase.xdr.ScVal.scvMap(entries); + } + if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : "") !== "Object") { + var _val$constructor2; + throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")")); + } + throw new TypeError("Received object ".concat(val, " did not match the provided type ").concat(ty)); + } + case "number": + case "bigint": + { + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeU32().value: + return _stellarBase.xdr.ScVal.scvU32(val); + case _stellarBase.xdr.ScSpecType.scSpecTypeI32().value: + return _stellarBase.xdr.ScVal.scvI32(val); + case _stellarBase.xdr.ScSpecType.scSpecTypeU64().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeI64().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeU128().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeI128().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeU256().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeI256().value: + { + var intType = t.name.substring(10).toLowerCase(); + return new _stellarBase.XdrLargeInt(intType, val).toScVal(); + } + default: + throw new TypeError("invalid type (".concat(ty, ") specified for integer")); + } + } + case "string": + return stringToScVal(val, t); + case "boolean": + { + if (value !== _stellarBase.xdr.ScSpecType.scSpecTypeBool().value) { + throw TypeError("Type ".concat(ty, " was not bool, but value was bool")); + } + return _stellarBase.xdr.ScVal.scvBool(val); + } + case "undefined": + { + if (!ty) { + return _stellarBase.xdr.ScVal.scvVoid(); + } + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVoid().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeOption().value: + return _stellarBase.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was undefined")); + } + } + case "function": + return this.nativeToScVal(val(), ty); + default: + throw new TypeError("failed to convert typeof ".concat(_typeof(val), " (").concat(val, ")")); + } + } + }, { + key: "nativeToUdt", + value: function nativeToUdt(val, name) { + var entry = this.findEntry(name); + switch (entry.switch()) { + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + if (typeof val !== "number") { + throw new TypeError("expected number for enum ".concat(name, ", but got ").concat(_typeof(val))); + } + return this.nativeToEnum(val, entry.udtEnumV0()); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.nativeToStruct(val, entry.udtStructV0()); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.nativeToUnion(val, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(name)); + } + } + }, { + key: "nativeToUnion", + value: function nativeToUnion(val, union_) { + var _this3 = this; + var entryName = val.tag; + var caseFound = union_.cases().find(function (entry) { + var caseN = entry.value().name().toString(); + return caseN === entryName; + }); + if (!caseFound) { + throw new TypeError("no such enum entry: ".concat(entryName, " in ").concat(union_)); + } + var key = _stellarBase.xdr.ScVal.scvSymbol(entryName); + switch (caseFound.switch()) { + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0(): + { + return _stellarBase.xdr.ScVal.scvVec([key]); + } + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0(): + { + var types = caseFound.tupleCase().type(); + if (Array.isArray(val.values)) { + if (val.values.length !== types.length) { + throw new TypeError("union ".concat(union_, " expects ").concat(types.length, " values, but got ").concat(val.values.length)); + } + var scvals = val.values.map(function (v, i) { + return _this3.nativeToScVal(v, types[i]); + }); + scvals.unshift(key); + return _stellarBase.xdr.ScVal.scvVec(scvals); + } + throw new Error("failed to parse union case ".concat(caseFound, " with ").concat(val)); + } + default: + throw new Error("failed to parse union ".concat(union_, " with ").concat(val)); + } + } + }, { + key: "nativeToStruct", + value: function nativeToStruct(val, struct) { + var _this4 = this; + var fields = struct.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + return _stellarBase.xdr.ScVal.scvVec(fields.map(function (_, i) { + return _this4.nativeToScVal(val[i], fields[i].type()); + })); + } + return _stellarBase.xdr.ScVal.scvMap(fields.map(function (field) { + var name = field.name().toString(); + return new _stellarBase.xdr.ScMapEntry({ + key: _this4.nativeToScVal(name, _stellarBase.xdr.ScSpecTypeDef.scSpecTypeSymbol()), + val: _this4.nativeToScVal(val[name], field.type()) + }); + })); + } + }, { + key: "nativeToEnum", + value: function nativeToEnum(val, enum_) { + if (enum_.cases().some(function (entry) { + return entry.value() === val; + })) { + return _stellarBase.xdr.ScVal.scvU32(val); + } + throw new TypeError("no such enum entry: ".concat(val, " in ").concat(enum_)); + } + }, { + key: "scValStrToNative", + value: function scValStrToNative(scv, typeDef) { + return this.scValToNative(_stellarBase.xdr.ScVal.fromXDR(scv, "base64"), typeDef); + } + }, { + key: "scValToNative", + value: function scValToNative(scv, typeDef) { + var _this5 = this; + var t = typeDef.switch(); + var value = t.value; + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeUdt().value) { + return this.scValUdtToNative(scv, typeDef.udt()); + } + switch (scv.switch().value) { + case _stellarBase.xdr.ScValType.scvVoid().value: + return undefined; + case _stellarBase.xdr.ScValType.scvU64().value: + case _stellarBase.xdr.ScValType.scvI64().value: + case _stellarBase.xdr.ScValType.scvU128().value: + case _stellarBase.xdr.ScValType.scvI128().value: + case _stellarBase.xdr.ScValType.scvU256().value: + case _stellarBase.xdr.ScValType.scvI256().value: + return (0, _stellarBase.scValToBigInt)(scv); + case _stellarBase.xdr.ScValType.scvVec().value: + { + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeVec().value) { + var _scv$vec; + var vec = typeDef.vec(); + return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(function (elm) { + return _this5.scValToNative(elm, vec.elementType()); + }); + } + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeTuple().value) { + var _scv$vec2; + var tuple = typeDef.tuple(); + var valTypes = tuple.valueTypes(); + return ((_scv$vec2 = scv.vec()) !== null && _scv$vec2 !== void 0 ? _scv$vec2 : []).map(function (elm, i) { + return _this5.scValToNative(elm, valTypes[i]); + }); + } + throw new TypeError("Type ".concat(typeDef, " was not vec, but ").concat(scv, " is")); + } + case _stellarBase.xdr.ScValType.scvAddress().value: + return _stellarBase.Address.fromScVal(scv).toString(); + case _stellarBase.xdr.ScValType.scvMap().value: + { + var _scv$map; + var map = (_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []; + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeMap().value) { + var typed = typeDef.map(); + var keyType = typed.keyType(); + var valueType = typed.valueType(); + var res = map.map(function (entry) { + return [_this5.scValToNative(entry.key(), keyType), _this5.scValToNative(entry.val(), valueType)]; + }); + return res; + } + throw new TypeError("ScSpecType ".concat(t.name, " was not map, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + case _stellarBase.xdr.ScValType.scvBool().value: + case _stellarBase.xdr.ScValType.scvU32().value: + case _stellarBase.xdr.ScValType.scvI32().value: + case _stellarBase.xdr.ScValType.scvBytes().value: + return scv.value(); + case _stellarBase.xdr.ScValType.scvString().value: + case _stellarBase.xdr.ScValType.scvSymbol().value: + { + var _scv$value; + if (value !== _stellarBase.xdr.ScSpecType.scSpecTypeString().value && value !== _stellarBase.xdr.ScSpecType.scSpecTypeSymbol().value) { + throw new Error("ScSpecType ".concat(t.name, " was not string or symbol, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + return (_scv$value = scv.value()) === null || _scv$value === void 0 ? void 0 : _scv$value.toString(); + } + case _stellarBase.xdr.ScValType.scvTimepoint().value: + case _stellarBase.xdr.ScValType.scvDuration().value: + return (0, _stellarBase.scValToBigInt)(_stellarBase.xdr.ScVal.scvU64(scv.u64())); + default: + throw new TypeError("failed to convert ".concat(JSON.stringify(scv, null, 2), " to native type from type ").concat(t.name)); + } + } + }, { + key: "scValUdtToNative", + value: function scValUdtToNative(scv, udt) { + var entry = this.findEntry(udt.name().toString()); + switch (entry.switch()) { + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + return this.enumToNative(scv); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.structToNative(scv, entry.udtStructV0()); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.unionToNative(scv, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(udt.name().toString(), ": ").concat(entry)); + } + } + }, { + key: "unionToNative", + value: function unionToNative(val, udt) { + var _this6 = this; + var vec = val.vec(); + if (!vec) { + throw new Error("".concat(JSON.stringify(val, null, 2), " is not a vec")); + } + if (vec.length === 0 && udt.cases.length !== 0) { + throw new Error("".concat(val, " has length 0, but the there are at least one case in the union")); + } + var name = vec[0].sym().toString(); + if (vec[0].switch().value !== _stellarBase.xdr.ScValType.scvSymbol().value) { + throw new Error("{vec[0]} is not a symbol"); + } + var entry = udt.cases().find(findCase(name)); + if (!entry) { + throw new Error("failed to find entry ".concat(name, " in union {udt.name().toString()}")); + } + var res = { + tag: name + }; + if (entry.switch().value === _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value) { + var tuple = entry.tupleCase(); + var ty = tuple.type(); + var values = ty.map(function (e, i) { + return _this6.scValToNative(vec[i + 1], e); + }); + res.values = values; + } + return res; + } + }, { + key: "structToNative", + value: function structToNative(val, udt) { + var _this7 = this, + _val$map; + var res = {}; + var fields = udt.fields(); + if (fields.some(isNumeric)) { + var _val$vec; + var r = (_val$vec = val.vec()) === null || _val$vec === void 0 ? void 0 : _val$vec.map(function (entry, i) { + return _this7.scValToNative(entry, fields[i].type()); + }); + return r; + } + (_val$map = val.map()) === null || _val$map === void 0 || _val$map.forEach(function (entry, i) { + var field = fields[i]; + res[field.name().toString()] = _this7.scValToNative(entry.val(), field.type()); + }); + return res; + } + }, { + key: "enumToNative", + value: function enumToNative(scv) { + if (scv.switch().value !== _stellarBase.xdr.ScValType.scvU32().value) { + throw new Error("Enum must have a u32 value"); + } + var num = scv.u32(); + return num; + } + }, { + key: "errorCases", + value: function errorCases() { + return this.entries.filter(function (entry) { + return entry.switch().value === _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value; + }).flatMap(function (entry) { + return entry.value().cases(); + }); + } + }, { + key: "jsonSchema", + value: function jsonSchema(funcName) { + var definitions = {}; + this.entries.forEach(function (entry) { + switch (entry.switch().value) { + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0().value: + { + var udt = entry.udtEnumV0(); + definitions[udt.name().toString()] = enumToJsonSchema(udt); + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0().value: + { + var _udt = entry.udtStructV0(); + definitions[_udt.name().toString()] = structToJsonSchema(_udt); + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0().value: + { + var _udt2 = entry.udtUnionV0(); + definitions[_udt2.name().toString()] = unionToJsonSchema(_udt2); + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value: + { + var fn = entry.functionV0(); + var fnName = fn.name().toString(); + var _functionToJsonSchema = functionToJsonSchema(fn), + input = _functionToJsonSchema.input; + definitions[fnName] = input; + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value: + {} + } + }); + var res = { + $schema: "http://json-schema.org/draft-07/schema#", + definitions: _objectSpread(_objectSpread({}, PRIMITIVE_DEFINITONS), definitions) + }; + if (funcName) { + res.$ref = "#/definitions/".concat(funcName); + } + return res; + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/types.d.ts b/node_modules/@stellar/stellar-sdk/lib/contract/types.d.ts new file mode 100644 index 000000000..bceff262c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/types.d.ts @@ -0,0 +1,244 @@ +import { Memo, MemoType, Operation, Transaction, xdr } from "@stellar/stellar-base"; +export type XDR_BASE64 = string; +/** + * An unsigned 32-bit integer. + * @memberof module:contract + */ +export type u32 = number; +/** + * A signed 32-bit integer. + * @memberof module:contract + */ +export type i32 = number; +/** + * An unsigned 64-bit integer. + * @memberof module:contract + */ +export type u64 = bigint; +/** + * A signed 64-bit integer. + * @memberof module:contract + */ +export type i64 = bigint; +/** + * An unsigned 128-bit integer. + * @memberof module:contract + */ +export type u128 = bigint; +/** + * A signed 128-bit integer. + * @memberof module:contract + */ +export type i128 = bigint; +/** + * An unsigned 256-bit integer. + * @memberof module:contract + */ +export type u256 = bigint; +/** + * A signed 256-bit integer. + * @memberof module:contract + */ +export type i256 = bigint; +export type Option = T | undefined; +export type Typepoint = bigint; +export type Duration = bigint; +/** + * A "regular" transaction, as opposed to a FeeBumpTransaction. + * @memberof module:contract + * @type {Transaction, Operation[]>} + */ +export type Tx = Transaction, Operation[]>; +export interface WalletError { + message: string; + code: number; + ext?: Array; +} +/** + * A function to request a wallet to sign a built transaction + * + * This function takes an XDR provided by the requester and applies a signature to it. + * It returns a base64-encoded string XDR-encoded Transaction Envelope with Decorated Signatures + * and the signer address back to the requester. + * + * @param xdr - The XDR string representing the transaction to be signed. + * @param opts - Options for signing the transaction. + * @param opts.networkPassphrase - The network's passphrase on which the transaction is intended to be signed. + * @param opts.address - The public key of the account that should be used to sign. + * @param opts.submit - If set to true, submits the transaction immediately after signing. + * @param opts.submitUrl - The URL of the network to which the transaction should be submitted, if applicable. + * + * @returns A promise resolving to an object with the signed transaction XDR and optional signer address and error. + */ +export type SignTransaction = (xdr: string, opts?: { + networkPassphrase?: string; + address?: string; + submit?: boolean; + submitUrl?: string; +}) => Promise<{ + signedTxXdr: string; + signerAddress?: string; +} & { + error?: WalletError; +}>; +/** + * A function to request a wallet to sign an authorization entry preimage. + * + * Similar to signing a transaction, this function takes an authorization entry preimage provided by the + * requester and applies a signature to it. + * It returns a signed hash of the same authorization entry and the signer address back to the requester. + * + * @param authEntry - The authorization entry preimage to be signed. + * @param opts - Options for signing the authorization entry. + * @param opts.networkPassphrase - The network's passphrase on which the authorization entry is intended to be signed. + * @param opts.address - The public key of the account that should be used to sign. + * + * @returns A promise resolving to an object with the signed authorization entry and optional signer address and error. + */ +export type SignAuthEntry = (authEntry: string, opts?: { + networkPassphrase?: string; + address?: string; +}) => Promise<{ + signedAuthEntry: string; + signerAddress?: string; +} & { + error?: WalletError; +}>; +/** + * Options for a smart contract client. + * @memberof module:contract + */ +export type ClientOptions = { + /** + * The public key of the account that will send this transaction. You can + * override this for specific methods later, like + * [signAndSend]{@link module:contract.AssembledTransaction#signAndSend} and + * [signAuthEntries]{@link module:contract.AssembledTransaction#signAuthEntries}. + */ + publicKey?: string; + /** + * A function to sign the transaction using the private key corresponding to + * the given `publicKey`. You do not need to provide this, for read-only + * calls, which only need to be simulated. If you do not need to sign and + * send, there is no need to provide this. If you do not provide it during + * initialization, you can provide it later when you call + * {@link module:contract.AssembledTransaction#signAndSend signAndSend}. + * + * Matches signature of `signTransaction` from Freighter. + */ + signTransaction?: SignTransaction; + /** + * A function to sign a specific auth entry for a transaction, using the + * private key corresponding to the provided `publicKey`. This is only needed + * for multi-auth transactions, in which one transaction is signed by + * multiple parties. If you do not provide it during initialization, you can + * provide it later when you call {@link module:contract.AssembledTransaction#signAuthEntries signAuthEntries}. + * + * Matches signature of `signAuthEntry` from Freighter. + */ + signAuthEntry?: SignAuthEntry; + /** The address of the contract the client will interact with. */ + contractId: string; + /** + * The network passphrase for the Stellar network this contract is deployed + * to. + */ + networkPassphrase: string; + /** + * The URL of the RPC instance that will be used to interact with this + * contract. + */ + rpcUrl: string; + /** + * If true, will allow HTTP requests to the Soroban network. If false, will + * only allow HTTPS requests. + * @default false + */ + allowHttp?: boolean; + /** + * This gets filled in automatically from the ContractSpec when you + * instantiate a {@link Client}. + * + * Background: If the contract you're calling uses the `#[contracterror]` + * macro to create an `Error` enum, then those errors get included in the + * on-chain XDR that also describes your contract's methods. Each error will + * have a specific number. + * + * A Client makes method calls with an {@link module:contract.AssembledTransaction AssembledTransaction}. + * When one of these method calls encounters an error, `AssembledTransaction` + * will first attempt to parse the error as an "official" `contracterror` + * error, by using this passed-in `errorTypes` object. See + * {@link module:contract.AssembledTransaction#parseError parseError}. If `errorTypes` is blank or no + * matching error is found, then it will throw the raw error. + * @default {} + */ + errorTypes?: Record; +}; +/** + * Options for a smart contract method invocation. + * @memberof module:contract + */ +export type MethodOptions = { + /** + * The fee to pay for the transaction. + * @default 100 + */ + fee?: string; + /** + * The timebounds which should be set for transactions generated by this + * contract client. {@link module:contract#.DEFAULT_TIMEOUT} + * @default 300 + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the + * AssembledTransaction. + * @default true + */ + simulate?: boolean; + /** + * If true, will automatically attempt to restore the transaction if there + * are archived entries that need renewal. + * @default false + */ + restore?: boolean; +}; +export type AssembledTransactionOptions = MethodOptions & ClientOptions & { + method: string; + args?: any[]; + parseResultXdr: (xdr: xdr.ScVal) => T; + /** + * The address of the account that should sign the transaction. Useful when + * a wallet holds multiple addresses to ensure signing with the intended one. + */ + address?: string; + /** + * This option will be passed through to the SEP43-compatible wallet extension. If true, and if the wallet supports it, the transaction will be signed and immediately submitted to the network by the wallet, bypassing the submit logic in {@link SentTransaction}. + * @default false + */ + submit?: boolean; + /** + * The URL of the network to which the transaction should be submitted. + * Only applicable when 'submit' is set to true. + */ + submitUrl?: string; +}; +/** + * The default timebounds, in seconds, during which a transaction will be valid. + * This is attached to the transaction _before_ transaction simulation (it is + * needed for simulation to succeed). It is also re-calculated and re-added + * _before_ transaction signing. + * @constant {number} + * @default 300 + * @memberof module:contract + */ +export declare const DEFAULT_TIMEOUT: number; +/** + * An impossible account on the Stellar network + * @constant {string} + * @default GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF + * @memberof module:contract + */ +export declare const NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/types.js b/node_modules/@stellar/stellar-sdk/lib/contract/types.js new file mode 100644 index 000000000..81a5b0f1c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/types.js @@ -0,0 +1,9 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NULL_ACCOUNT = exports.DEFAULT_TIMEOUT = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var DEFAULT_TIMEOUT = exports.DEFAULT_TIMEOUT = 5 * 60; +var NULL_ACCOUNT = exports.NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/contract/utils.d.ts new file mode 100644 index 000000000..12ee8e61e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/utils.d.ts @@ -0,0 +1,46 @@ +import { xdr, Account } from "@stellar/stellar-base"; +import { Server } from "../rpc"; +import { AssembledTransactionOptions } from "./types"; +/** + * Keep calling a `fn` for `timeoutInSeconds` seconds, if `keepWaitingIf` is + * true. Returns an array of all attempts to call the function. + * @private + */ +export declare function withExponentialBackoff( +/** Function to call repeatedly */ +fn: (previousFailure?: T) => Promise, +/** Condition to check when deciding whether or not to call `fn` again */ +keepWaitingIf: (result: T) => boolean, +/** How long to wait between the first and second call */ +timeoutInSeconds: number, +/** What to multiply `timeoutInSeconds` by, each subsequent attempt */ +exponentialFactor?: number, +/** Whether to log extra info */ +verbose?: boolean): Promise; +/** + * If contracts are implemented using the `#[contracterror]` macro, then the + * errors get included in the on-chain XDR that also describes your contract's + * methods. Each error will have a specific number. This Regular Expression + * matches these "expected error types" that a contract may throw, and helps + * {@link AssembledTransaction} parse these errors. + * + * @constant {RegExp} + * @default "/Error\(Contract, #(\d+)\)/" + * @memberof module:contract.Client + */ +export declare const contractErrorPattern: RegExp; +/** + * A TypeScript type guard that checks if an object has a `toString` method. + * @private + */ +export declare function implementsToString( +/** some object that may or may not have a `toString` method */ +obj: unknown): obj is { + toString(): string; +}; +/** + * Reads a binary stream of ScSpecEntries into an array for processing by ContractSpec + * @private + */ +export declare function processSpecEntryStream(buffer: Buffer): xdr.ScSpecEntry[]; +export declare function getAccount(options: AssembledTransactionOptions, server: Server): Promise; diff --git a/node_modules/@stellar/stellar-sdk/lib/contract/utils.js b/node_modules/@stellar/stellar-sdk/lib/contract/utils.js new file mode 100644 index 000000000..8db862695 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/contract/utils.js @@ -0,0 +1,123 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.contractErrorPattern = void 0; +exports.getAccount = getAccount; +exports.implementsToString = implementsToString; +exports.processSpecEntryStream = processSpecEntryStream; +exports.withExponentialBackoff = withExponentialBackoff; +var _stellarBase = require("@stellar/stellar-base"); +var _types = require("./types"); +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function withExponentialBackoff(_x, _x2, _x3) { + return _withExponentialBackoff.apply(this, arguments); +} +function _withExponentialBackoff() { + _withExponentialBackoff = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(fn, keepWaitingIf, timeoutInSeconds) { + var exponentialFactor, + verbose, + attempts, + count, + waitUntil, + waitTime, + totalWaitTime, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + exponentialFactor = _args.length > 3 && _args[3] !== undefined ? _args[3] : 1.5; + verbose = _args.length > 4 && _args[4] !== undefined ? _args[4] : false; + attempts = []; + count = 0; + _context.t0 = attempts; + _context.next = 7; + return fn(); + case 7: + _context.t1 = _context.sent; + _context.t0.push.call(_context.t0, _context.t1); + if (keepWaitingIf(attempts[attempts.length - 1])) { + _context.next = 11; + break; + } + return _context.abrupt("return", attempts); + case 11: + waitUntil = new Date(Date.now() + timeoutInSeconds * 1000).valueOf(); + waitTime = 1000; + totalWaitTime = waitTime; + case 14: + if (!(Date.now() < waitUntil && keepWaitingIf(attempts[attempts.length - 1]))) { + _context.next = 30; + break; + } + count += 1; + if (verbose) { + console.info("Waiting ".concat(waitTime, "ms before trying again (bringing the total wait time to ").concat(totalWaitTime, "ms so far, of total ").concat(timeoutInSeconds * 1000, "ms)")); + } + _context.next = 19; + return new Promise(function (res) { + return setTimeout(res, waitTime); + }); + case 19: + waitTime *= exponentialFactor; + if (new Date(Date.now() + waitTime).valueOf() > waitUntil) { + waitTime = waitUntil - Date.now(); + if (verbose) { + console.info("was gonna wait too long; new waitTime: ".concat(waitTime, "ms")); + } + } + totalWaitTime = waitTime + totalWaitTime; + _context.t2 = attempts; + _context.next = 25; + return fn(attempts[attempts.length - 1]); + case 25: + _context.t3 = _context.sent; + _context.t2.push.call(_context.t2, _context.t3); + if (verbose && keepWaitingIf(attempts[attempts.length - 1])) { + console.info("".concat(count, ". Called ").concat(fn, "; ").concat(attempts.length, " prev attempts. Most recent: ").concat(JSON.stringify(attempts[attempts.length - 1], null, 2))); + } + _context.next = 14; + break; + case 30: + return _context.abrupt("return", attempts); + case 31: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _withExponentialBackoff.apply(this, arguments); +} +var contractErrorPattern = exports.contractErrorPattern = /Error\(Contract, #(\d+)\)/; +function implementsToString(obj) { + return _typeof(obj) === "object" && obj !== null && "toString" in obj; +} +function processSpecEntryStream(buffer) { + var reader = new _stellarBase.cereal.XdrReader(buffer); + var res = []; + while (!reader.eof) { + res.push(_stellarBase.xdr.ScSpecEntry.read(reader)); + } + return res; +} +function getAccount(_x4, _x5) { + return _getAccount.apply(this, arguments); +} +function _getAccount() { + _getAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(options, server) { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", options.publicKey ? server.getAccount(options.publicKey) : new _stellarBase.Account(_types.NULL_ACCOUNT, "0")); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _getAccount.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/errors/account_requires_memo.d.ts b/node_modules/@stellar/stellar-sdk/lib/errors/account_requires_memo.d.ts new file mode 100644 index 000000000..2c845d12f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/errors/account_requires_memo.d.ts @@ -0,0 +1,24 @@ +/** + * AccountRequiresMemoError is raised when a transaction is trying to submit an + * operation to an account which requires a memo. See + * [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md) + * for more information. + * + * This error contains two attributes to help you identify the account requiring + * the memo and the operation where the account is the destination + * @category Errors + * + * @param {string} message Human-readable error message + * @param {string} accountId The account which requires a memo + * @param {number} operationIndex The index of the operation where `accountId` is the destination + * + * @example + * console.log('The following account requires a memo ', err.accountId) + * console.log('The account is used in operation: ', err.operationIndex) + */ +export declare class AccountRequiresMemoError extends Error { + __proto__: AccountRequiresMemoError; + accountId: string; + operationIndex: number; + constructor(message: string, accountId: string, operationIndex: number); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/errors/account_requires_memo.js b/node_modules/@stellar/stellar-sdk/lib/errors/account_requires_memo.js new file mode 100644 index 000000000..669d85bc6 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/errors/account_requires_memo.js @@ -0,0 +1,38 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AccountRequiresMemoError = void 0; +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var AccountRequiresMemoError = exports.AccountRequiresMemoError = function (_Error) { + function AccountRequiresMemoError(message, accountId, operationIndex) { + var _this; + _classCallCheck(this, AccountRequiresMemoError); + var trueProto = (this instanceof AccountRequiresMemoError ? this.constructor : void 0).prototype; + _this = _callSuper(this, AccountRequiresMemoError, [message]); + _this.__proto__ = trueProto; + _this.constructor = AccountRequiresMemoError; + _this.name = "AccountRequiresMemoError"; + _this.accountId = accountId; + _this.operationIndex = operationIndex; + return _this; + } + _inherits(AccountRequiresMemoError, _Error); + return _createClass(AccountRequiresMemoError); +}(_wrapNativeSuper(Error)); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/errors/bad_request.d.ts b/node_modules/@stellar/stellar-sdk/lib/errors/bad_request.d.ts new file mode 100644 index 000000000..4d1d320d5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/errors/bad_request.d.ts @@ -0,0 +1,14 @@ +import { NetworkError } from "./network"; +/** + * BadRequestError is raised when a request made to Horizon is invalid in some + * way (incorrect timebounds for trade call builders, for example.) + * @augments NetworkError + * @inheritdoc + * @category Errors + * + * @param {string} message Human-readable error message + * @param {any} response Response details, received from the Horizon server + */ +export declare class BadRequestError extends NetworkError { + constructor(message: string, response: any); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/errors/bad_request.js b/node_modules/@stellar/stellar-sdk/lib/errors/bad_request.js new file mode 100644 index 000000000..24aeb632c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/errors/bad_request.js @@ -0,0 +1,34 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BadRequestError = void 0; +var _network = require("./network"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var BadRequestError = exports.BadRequestError = function (_NetworkError) { + function BadRequestError(message, response) { + var _this; + _classCallCheck(this, BadRequestError); + var trueProto = (this instanceof BadRequestError ? this.constructor : void 0).prototype; + _this = _callSuper(this, BadRequestError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadRequestError; + _this.name = "BadRequestError"; + return _this; + } + _inherits(BadRequestError, _NetworkError); + return _createClass(BadRequestError); +}(_network.NetworkError); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/errors/bad_response.d.ts b/node_modules/@stellar/stellar-sdk/lib/errors/bad_response.d.ts new file mode 100644 index 000000000..22de8f235 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/errors/bad_response.d.ts @@ -0,0 +1,17 @@ +import { NetworkError } from "./network"; +/** + * BadResponseError is raised when a response from a + * {@link module:Horizon | Horizon} or {@link module:Federation | Federation} + * server is invalid in some way. For example, a federation response may exceed + * the maximum allowed size, or a transaction submission may have failed with + * Horizon. + * @augments NetworkError + * @inheritdoc + * @category Errors + * + * @param {string} message Human-readable error message. + * @param {any} response Response details, received from the server. + */ +export declare class BadResponseError extends NetworkError { + constructor(message: string, response: any); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/errors/bad_response.js b/node_modules/@stellar/stellar-sdk/lib/errors/bad_response.js new file mode 100644 index 000000000..c7fbbacec --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/errors/bad_response.js @@ -0,0 +1,34 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BadResponseError = void 0; +var _network = require("./network"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var BadResponseError = exports.BadResponseError = function (_NetworkError) { + function BadResponseError(message, response) { + var _this; + _classCallCheck(this, BadResponseError); + var trueProto = (this instanceof BadResponseError ? this.constructor : void 0).prototype; + _this = _callSuper(this, BadResponseError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadResponseError; + _this.name = "BadResponseError"; + return _this; + } + _inherits(BadResponseError, _NetworkError); + return _createClass(BadResponseError); +}(_network.NetworkError); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/errors/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/errors/index.d.ts new file mode 100644 index 000000000..cb4f19458 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/errors/index.d.ts @@ -0,0 +1,5 @@ +export * from "./network"; +export * from "./not_found"; +export * from "./bad_request"; +export * from "./bad_response"; +export * from "./account_requires_memo"; diff --git a/node_modules/@stellar/stellar-sdk/lib/errors/index.js b/node_modules/@stellar/stellar-sdk/lib/errors/index.js new file mode 100644 index 000000000..f0f9d584e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/errors/index.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _network = require("./network"); +Object.keys(_network).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _network[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _network[key]; + } + }); +}); +var _not_found = require("./not_found"); +Object.keys(_not_found).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _not_found[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _not_found[key]; + } + }); +}); +var _bad_request = require("./bad_request"); +Object.keys(_bad_request).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _bad_request[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _bad_request[key]; + } + }); +}); +var _bad_response = require("./bad_response"); +Object.keys(_bad_response).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _bad_response[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _bad_response[key]; + } + }); +}); +var _account_requires_memo = require("./account_requires_memo"); +Object.keys(_account_requires_memo).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _account_requires_memo[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _account_requires_memo[key]; + } + }); +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/errors/network.d.ts b/node_modules/@stellar/stellar-sdk/lib/errors/network.d.ts new file mode 100644 index 000000000..fad4e7745 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/errors/network.d.ts @@ -0,0 +1,33 @@ +import { HorizonApi } from "../horizon/horizon_api"; +/** + * NetworkError is raised when an interaction with a Horizon server has caused + * some kind of problem. + * @category Errors + * + * @param {string} message Human-readable error message + * @param {any} response Response details, received from the Horizon server. + * @param {HorizonApi.ErrorResponseData} [response.data] The data returned by Horizon as part of the error: {@link https://developers.stellar.org/docs/data/horizon/api-reference/errors/response | Error Response} + * @param {number} [response.status] HTTP status code describing the basic issue with a submitted transaction {@link https://developers.stellar.org/docs/data/horizon/api-reference/errors/http-status-codes/standard | Standard Status Codes} + * @param {string} [response.statusText] A human-readable description of what the status code means: {@link https://developers.stellar.org/docs/data/horizon/api-reference/errors/http-status-codes/horizon-specific | Horizon-Specific Status Codes} + * @param {string} [response.url] URL which can provide more information about the problem that occurred. + */ +export declare class NetworkError extends Error { + response: { + data?: HorizonApi.ErrorResponseData; + status?: number; + statusText?: string; + url?: string; + }; + __proto__: NetworkError; + constructor(message: string, response: any); + /** + * Returns the error response sent by the Horizon server. + * @returns {any} + */ + getResponse(): { + data?: HorizonApi.ErrorResponseData; + status?: number; + statusText?: string; + url?: string; + }; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/errors/network.js b/node_modules/@stellar/stellar-sdk/lib/errors/network.js new file mode 100644 index 000000000..a26433617 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/errors/network.js @@ -0,0 +1,41 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NetworkError = void 0; +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var NetworkError = exports.NetworkError = function (_Error) { + function NetworkError(message, response) { + var _this; + _classCallCheck(this, NetworkError); + var trueProto = (this instanceof NetworkError ? this.constructor : void 0).prototype; + _this = _callSuper(this, NetworkError, [message]); + _this.__proto__ = trueProto; + _this.constructor = NetworkError; + _this.response = response; + return _this; + } + _inherits(NetworkError, _Error); + return _createClass(NetworkError, [{ + key: "getResponse", + value: function getResponse() { + return this.response; + } + }]); +}(_wrapNativeSuper(Error)); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/errors/not_found.d.ts b/node_modules/@stellar/stellar-sdk/lib/errors/not_found.d.ts new file mode 100644 index 000000000..bca48d935 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/errors/not_found.d.ts @@ -0,0 +1,14 @@ +import { NetworkError } from "./network"; +/** + * NotFoundError is raised when the resource requested from Horizon is + * unavailable. + * @augments NetworkError + * @inheritdoc + * @category Errors + * + * @param {string} message Human-readable error message + * @param {any} response Response details, received from the Horizon server + */ +export declare class NotFoundError extends NetworkError { + constructor(message: string, response: any); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/errors/not_found.js b/node_modules/@stellar/stellar-sdk/lib/errors/not_found.js new file mode 100644 index 000000000..d828c18cf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/errors/not_found.js @@ -0,0 +1,34 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NotFoundError = void 0; +var _network = require("./network"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var NotFoundError = exports.NotFoundError = function (_NetworkError) { + function NotFoundError(message, response) { + var _this; + _classCallCheck(this, NotFoundError); + var trueProto = (this instanceof NotFoundError ? this.constructor : void 0).prototype; + _this = _callSuper(this, NotFoundError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = NotFoundError; + _this.name = "NotFoundError"; + return _this; + } + _inherits(NotFoundError, _NetworkError); + return _createClass(NotFoundError); +}(_network.NetworkError); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/federation/api.d.ts b/node_modules/@stellar/stellar-sdk/lib/federation/api.d.ts new file mode 100644 index 000000000..f7feb38bf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/federation/api.d.ts @@ -0,0 +1,32 @@ +export declare namespace Api { + /** + * Record returned from a federation server. + */ + interface Record { + /** + * The Stellar public key resolved from the federation lookup + */ + account_id: string; + /** + * The type of memo, if any, required to send payments to this user + */ + memo_type?: string; + /** + * The memo value, if any, required to send payments to this user + */ + memo?: string; + } + /** + * Options for configuring connections to federation servers. You can also use {@link Config} class to set this globally. + */ + interface Options { + /** + * Allow connecting to http servers, default: `false`. This must be set to false in production deployments! + */ + allowHttp?: boolean; + /** + * Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue. + */ + timeout?: number; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/federation/api.js b/node_modules/@stellar/stellar-sdk/lib/federation/api.js new file mode 100644 index 000000000..081ac7fbf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/federation/api.js @@ -0,0 +1,7 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Api = void 0; +var Api; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/federation/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/federation/index.d.ts new file mode 100644 index 000000000..4eaff4f80 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/federation/index.d.ts @@ -0,0 +1,2 @@ +export { FederationServer as Server, FEDERATION_RESPONSE_MAX_SIZE } from './server'; +export * from './api'; diff --git a/node_modules/@stellar/stellar-sdk/lib/federation/index.js b/node_modules/@stellar/stellar-sdk/lib/federation/index.js new file mode 100644 index 000000000..2d73772d2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/federation/index.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Server: true, + FEDERATION_RESPONSE_MAX_SIZE: true +}; +Object.defineProperty(exports, "FEDERATION_RESPONSE_MAX_SIZE", { + enumerable: true, + get: function get() { + return _server.FEDERATION_RESPONSE_MAX_SIZE; + } +}); +Object.defineProperty(exports, "Server", { + enumerable: true, + get: function get() { + return _server.FederationServer; + } +}); +var _server = require("./server"); +var _api = require("./api"); +Object.keys(_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _api[key]; + } + }); +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/federation/server.d.ts b/node_modules/@stellar/stellar-sdk/lib/federation/server.d.ts new file mode 100644 index 000000000..bde8cb479 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/federation/server.d.ts @@ -0,0 +1,116 @@ +import { Api } from "./api"; +/** @module Federation */ +/** + * The maximum size of response from a federation server + * @default 102400 + */ +export declare const FEDERATION_RESPONSE_MAX_SIZE: number; +/** + * Federation.Server handles a network connection to a + * [federation server](https://developers.stellar.org/docs/learn/encyclopedia/federation) + * instance and exposes an interface for requests to that instance. + * + * @alias module:Federation.Server + * @memberof module:Federation + * @param {string} serverURL The federation server URL (ex. `https://acme.com/federation`). + * @param {string} domain Domain this server represents + * @param {Api.Options} [opts] Options object + * @returns {void} + */ +export declare class FederationServer { + /** + * The federation server URL (ex. `https://acme.com/federation`). + */ + private readonly serverURL; + /** + * Domain this server represents. + */ + private readonly domain; + /** + * Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue. + */ + private readonly timeout; + /** + * A helper method for handling user inputs that contain `destination` value. + * It accepts two types of values: + * + * * For Stellar address (ex. `bob*stellar.org`) it splits Stellar address and then tries to find information about + * federation server in `stellar.toml` file for a given domain. It returns a `Promise` which resolves if federation + * server exists and user has been found and rejects in all other cases. + * * For Account ID (ex. `GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS`) it returns a `Promise` which + * resolves if Account ID is valid and rejects in all other cases. Please note that this method does not check + * if the account actually exists in a ledger. + * + * @example + * StellarSdk.FederationServer.resolve('bob*stellar.org') + * .then(federationRecord => { + * // { + * // account_id: 'GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS', + * // memo_type: 'id', + * // memo: 100 + * // } + * }); + * + * @see Federation doc + * @see Stellar.toml doc + * @param {string} value Stellar Address (ex. `bob*stellar.org`) + * @param {object} [opts] Options object + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the provided account ID is not a valid Ed25519 public key. + */ + static resolve(value: string, opts?: Api.Options): Promise; + /** + * Creates a `FederationServer` instance based on information from + * [stellar.toml](https://developers.stellar.org/docs/issuing-assets/publishing-asset-info) + * file for a given domain. + * + * If `stellar.toml` file does not exist for a given domain or it does not + * contain information about a federation server Promise will reject. + * + * @example + * StellarSdk.FederationServer.createForDomain('acme.com') + * .then(federationServer => { + * // federationServer.resolveAddress('bob').then(...) + * }) + * .catch(error => { + * // stellar.toml does not exist or it does not contain information about federation server. + * }); + * + * @see Stellar.toml doc + * @param {string} domain Domain to get federation server for + * @param {module:Federation.Api.Options} [opts] Options object + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the domain's stellar.toml file does not contain a federation server field. + */ + static createForDomain(domain: string, opts?: Api.Options): Promise; + constructor(serverURL: string, domain: string, opts?: Api.Options); + /** + * Get the federation record if the user was found for a given Stellar address + * @see Federation doc + * @param {string} address Stellar address (ex. `bob*stellar.org`). If `FederationServer` was instantiated with `domain` param only username (ex. `bob`) can be passed. + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the federated address does not contain a domain, or if the server object was not instantiated with a `domain` parameter + */ + resolveAddress(address: string): Promise; + /** + * Given an account ID, get their federation record if the user was found + * @see Federation doc + * @param {string} accountId Account ID (ex. `GBYNR2QJXLBCBTRN44MRORCMI4YO7FZPFBCNOKTOBCAAFC7KC3LNPRYS`) + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the federation server returns an invalid memo value. + * @throws Will throw an error if the federation server's response exceeds the allowed maximum size. + * @throws {BadResponseError} Will throw an error if the server query fails with an improper response. + */ + resolveAccountId(accountId: string): Promise; + /** + * Given a transactionId, get the federation record if the sender of the transaction was found + * @see Federation doc + * @param {string} transactionId Transaction ID (ex. `3389e9f0f1a65f19736cacf544c2e825313e8447f569233bb8db39aa607c8889`) + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the federation server returns an invalid memo value. + * @throws Will throw an error if the federation server's response exceeds the allowed maximum size. + * @throws {BadResponseError} Will throw an error if the server query fails with an improper response. + */ + resolveTransactionId(transactionId: string): Promise; + private _sendRequest; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/federation/server.js b/node_modules/@stellar/stellar-sdk/lib/federation/server.js new file mode 100644 index 000000000..36d7789cd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/federation/server.js @@ -0,0 +1,252 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FederationServer = exports.FEDERATION_RESPONSE_MAX_SIZE = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _urijs = _interopRequireDefault(require("urijs")); +var _config = require("../config"); +var _errors = require("../errors"); +var _stellartoml = require("../stellartoml"); +var _httpClient = require("../http-client"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var FEDERATION_RESPONSE_MAX_SIZE = exports.FEDERATION_RESPONSE_MAX_SIZE = 100 * 1024; +var FederationServer = exports.FederationServer = function () { + function FederationServer(serverURL, domain) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + _classCallCheck(this, FederationServer); + this.serverURL = (0, _urijs.default)(serverURL); + this.domain = domain; + var allowHttp = typeof opts.allowHttp === "undefined" ? _config.Config.isAllowHttp() : opts.allowHttp; + this.timeout = typeof opts.timeout === "undefined" ? _config.Config.getTimeout() : opts.timeout; + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure federation server"); + } + } + return _createClass(FederationServer, [{ + key: "resolveAddress", + value: (function () { + var _resolveAddress = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(address) { + var stellarAddress, url; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + stellarAddress = address; + if (!(address.indexOf("*") < 0)) { + _context.next = 5; + break; + } + if (this.domain) { + _context.next = 4; + break; + } + return _context.abrupt("return", Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object."))); + case 4: + stellarAddress = "".concat(address, "*").concat(this.domain); + case 5: + url = this.serverURL.query({ + type: "name", + q: stellarAddress + }); + return _context.abrupt("return", this._sendRequest(url)); + case 7: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function resolveAddress(_x) { + return _resolveAddress.apply(this, arguments); + } + return resolveAddress; + }()) + }, { + key: "resolveAccountId", + value: (function () { + var _resolveAccountId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(accountId) { + var url; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + url = this.serverURL.query({ + type: "id", + q: accountId + }); + return _context2.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function resolveAccountId(_x2) { + return _resolveAccountId.apply(this, arguments); + } + return resolveAccountId; + }()) + }, { + key: "resolveTransactionId", + value: (function () { + var _resolveTransactionId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(transactionId) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = this.serverURL.query({ + type: "txid", + q: transactionId + }); + return _context3.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function resolveTransactionId(_x3) { + return _resolveTransactionId.apply(this, arguments); + } + return resolveTransactionId; + }()) + }, { + key: "_sendRequest", + value: function () { + var _sendRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(url) { + var timeout; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + timeout = this.timeout; + return _context4.abrupt("return", _httpClient.httpClient.get(url.toString(), { + maxContentLength: FEDERATION_RESPONSE_MAX_SIZE, + timeout: timeout + }).then(function (response) { + if (typeof response.data.memo !== "undefined" && typeof response.data.memo !== "string") { + throw new Error("memo value should be of type string"); + } + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + if (response.message.match(/^maxContentLength size/)) { + throw new Error("federation response exceeds allowed size of ".concat(FEDERATION_RESPONSE_MAX_SIZE)); + } else { + return Promise.reject(response); + } + } else { + return Promise.reject(new _errors.BadResponseError("Server query failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + } + })); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function _sendRequest(_x4) { + return _sendRequest2.apply(this, arguments); + } + return _sendRequest; + }() + }], [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(value) { + var opts, + addressParts, + _addressParts, + domain, + federationServer, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {}; + if (!(value.indexOf("*") < 0)) { + _context5.next = 5; + break; + } + if (_stellarBase.StrKey.isValidEd25519PublicKey(value)) { + _context5.next = 4; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Account ID"))); + case 4: + return _context5.abrupt("return", Promise.resolve({ + account_id: value + })); + case 5: + addressParts = value.split("*"); + _addressParts = _slicedToArray(addressParts, 2), domain = _addressParts[1]; + if (!(addressParts.length !== 2 || !domain)) { + _context5.next = 9; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Stellar address"))); + case 9: + _context5.next = 11; + return FederationServer.createForDomain(domain, opts); + case 11: + federationServer = _context5.sent; + return _context5.abrupt("return", federationServer.resolveAddress(value)); + case 13: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function resolve(_x5) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }, { + key: "createForDomain", + value: (function () { + var _createForDomain = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(domain) { + var opts, + tomlObject, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : {}; + _context6.next = 3; + return _stellartoml.Resolver.resolve(domain, opts); + case 3: + tomlObject = _context6.sent; + if (tomlObject.FEDERATION_SERVER) { + _context6.next = 6; + break; + } + return _context6.abrupt("return", Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field"))); + case 6: + return _context6.abrupt("return", new FederationServer(tomlObject.FEDERATION_SERVER, domain, opts)); + case 7: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function createForDomain(_x6) { + return _createForDomain.apply(this, arguments); + } + return createForDomain; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/friendbot/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/friendbot/index.d.ts new file mode 100644 index 000000000..5181343e0 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/friendbot/index.d.ts @@ -0,0 +1,6 @@ +export declare namespace Api { + interface Response { + hash: string; + result_meta_xdr: string; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/friendbot/index.js b/node_modules/@stellar/stellar-sdk/lib/friendbot/index.js new file mode 100644 index 000000000..081ac7fbf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/friendbot/index.js @@ -0,0 +1,7 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Api = void 0; +var Api; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/account_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/account_call_builder.d.ts new file mode 100644 index 000000000..87c625f4f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/account_call_builder.d.ts @@ -0,0 +1,56 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link AccountCallBuilder} pointed to server defined by `serverUrl`. + * + * Do not create this object directly, use {@link Horizon.Server#accounts}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|All Accounts} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class AccountCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Returns information and links relating to a single account. + * The balances section in the returned JSON will also list all the trust lines this account has set up. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-an-account|Account Details} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {CallBuilder} a new CallBuilder instance for the /accounts/:id endpoint + */ + accountId(id: string): CallBuilder; + /** + * This endpoint filters accounts by signer account. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|Accounts} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + forSigner(id: string): this; + /** + * This endpoint filters all accounts who are trustees to an asset. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|Accounts} + * @see Asset + * @param {Asset} asset For example: `new Asset('USD','GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD')` + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + forAsset(asset: Asset): this; + /** + * This endpoint filters accounts where the given account is sponsoring the account or any of its sub-entries.. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|Accounts} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + sponsor(id: string): this; + /** + * This endpoint filters accounts holding a trustline to the given liquidity pool. + * + * @param {string} id The ID of the liquidity pool. For example: `dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7`. + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + forLiquidityPool(id: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/account_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/account_call_builder.js new file mode 100644 index 000000000..cdf9aa78a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/account_call_builder.js @@ -0,0 +1,62 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AccountCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var AccountCallBuilder = exports.AccountCallBuilder = function (_CallBuilder) { + function AccountCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, AccountCallBuilder); + _this = _callSuper(this, AccountCallBuilder, [serverUrl]); + _this.url.segment("accounts"); + return _this; + } + _inherits(AccountCallBuilder, _CallBuilder); + return _createClass(AccountCallBuilder, [{ + key: "accountId", + value: function accountId(id) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([id]); + return builder; + } + }, { + key: "forSigner", + value: function forSigner(id) { + this.url.setQuery("signer", id); + return this; + } + }, { + key: "forAsset", + value: function forAsset(asset) { + this.url.setQuery("asset", "".concat(asset)); + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(id) { + this.url.setQuery("liquidity_pool", id); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/account_response.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/account_response.d.ts new file mode 100644 index 000000000..a5a448de4 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/account_response.d.ts @@ -0,0 +1,61 @@ +import { HorizonApi } from "./horizon_api"; +import { ServerApi } from "./server_api"; +/** + * Do not create this object directly, use {@link module:Horizon.Server#loadAccount | Horizon.Server#loadAccount}. + * + * Returns information and links relating to a single account. + * The balances section in the returned JSON will also list all the trust lines this account has set up. + * It also contains {@link BaseAccount} object and exposes it's methods so can be used in {@link TransactionBuilder}. + * + * @memberof module:Horizon + * @private + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/accounts/object|Account Details} + * @param {string} response Response from horizon account endpoint. + * @returns {AccountResponse} AccountResponse instance + */ +export declare class AccountResponse { + readonly id: string; + readonly paging_token: string; + readonly account_id: string; + sequence: string; + readonly sequence_ledger?: number; + readonly sequence_time?: string; + readonly subentry_count: number; + readonly home_domain?: string; + readonly inflation_destination?: string; + readonly last_modified_ledger: number; + readonly last_modified_time: string; + readonly thresholds: HorizonApi.AccountThresholds; + readonly flags: HorizonApi.Flags; + readonly balances: HorizonApi.BalanceLine[]; + readonly signers: ServerApi.AccountRecordSigners[]; + readonly data: (options: { + value: string; + }) => Promise<{ + value: string; + }>; + readonly data_attr: Record; + readonly effects: ServerApi.CallCollectionFunction; + readonly offers: ServerApi.CallCollectionFunction; + readonly operations: ServerApi.CallCollectionFunction; + readonly payments: ServerApi.CallCollectionFunction; + readonly trades: ServerApi.CallCollectionFunction; + private readonly _baseAccount; + constructor(response: ServerApi.AccountRecord); + /** + * Get Stellar account public key ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA` + * @returns {string} accountId + */ + accountId(): string; + /** + * Get the current sequence number + * @returns {string} sequenceNumber + */ + sequenceNumber(): string; + /** + * Increments sequence number in this object by one. + * @returns {void} + */ + incrementSequenceNumber(): void; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/account_response.js b/node_modules/@stellar/stellar-sdk/lib/horizon/account_response.js new file mode 100644 index 000000000..682b46360 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/account_response.js @@ -0,0 +1,49 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AccountResponse = void 0; +var _stellarBase = require("@stellar/stellar-base"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var AccountResponse = exports.AccountResponse = function () { + function AccountResponse(response) { + var _this = this; + _classCallCheck(this, AccountResponse); + this._baseAccount = new _stellarBase.Account(response.account_id, response.sequence); + Object.entries(response).forEach(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + _this[key] = value; + }); + } + return _createClass(AccountResponse, [{ + key: "accountId", + value: function accountId() { + return this._baseAccount.accountId(); + } + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this._baseAccount.sequenceNumber(); + } + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + this._baseAccount.incrementSequenceNumber(); + this.sequence = this._baseAccount.sequenceNumber(); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/assets_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/assets_call_builder.d.ts new file mode 100644 index 000000000..38c7f9f14 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/assets_call_builder.d.ts @@ -0,0 +1,27 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link AssetsCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#assets}. + * + * @class + * @augments CallBuilder + * @private + * @param {string} serverUrl Horizon server URL. + */ +export declare class AssetsCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * This endpoint filters all assets by the asset code. + * @param {string} value For example: `USD` + * @returns {AssetsCallBuilder} current AssetCallBuilder instance + */ + forCode(value: string): AssetsCallBuilder; + /** + * This endpoint filters all assets by the asset issuer. + * @param {string} value For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {AssetsCallBuilder} current AssetCallBuilder instance + */ + forIssuer(value: string): AssetsCallBuilder; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/assets_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/assets_call_builder.js new file mode 100644 index 000000000..68d89ba1f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/assets_call_builder.js @@ -0,0 +1,43 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AssetsCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var AssetsCallBuilder = exports.AssetsCallBuilder = function (_CallBuilder) { + function AssetsCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, AssetsCallBuilder); + _this = _callSuper(this, AssetsCallBuilder, [serverUrl]); + _this.url.segment("assets"); + return _this; + } + _inherits(AssetsCallBuilder, _CallBuilder); + return _createClass(AssetsCallBuilder, [{ + key: "forCode", + value: function forCode(value) { + this.url.setQuery("asset_code", value); + return this; + } + }, { + key: "forIssuer", + value: function forIssuer(value) { + this.url.setQuery("asset_issuer", value); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/call_builder.d.ts new file mode 100644 index 000000000..f40d6db20 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/call_builder.d.ts @@ -0,0 +1,128 @@ +import URI from "urijs"; +import { HorizonApi } from "./horizon_api"; +import { ServerApi } from "./server_api"; +export interface EventSourceOptions { + onmessage?: (value: T) => void; + onerror?: (event: MessageEvent) => void; + reconnectTimeout?: number; +} +/** + * Creates a new {@link CallBuilder} pointed to server defined by serverUrl. + * + * This is an **abstract** class. Do not create this object directly, use {@link Server} class. + * @param {string} serverUrl URL of Horizon server + * @class CallBuilder + */ +export declare class CallBuilder> { + protected url: URI; + filter: string[][]; + protected originalSegments: string[]; + protected neighborRoot: string; + constructor(serverUrl: URI, neighborRoot?: string); + /** + * Triggers a HTTP request using this builder's current configuration. + * @returns {Promise} a Promise that resolves to the server's response. + */ + call(): Promise; + /** + * Creates an EventSource that listens for incoming messages from the server. To stop listening for new + * events call the function returned by this method. + * @see [Horizon Response Format](https://developers.stellar.org/api/introduction/response-format/) + * @see [MDN EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) + * @param {object} [options] EventSource options. + * @param {Function} [options.onmessage] Callback function to handle incoming messages. + * @param {Function} [options.onerror] Callback function to handle errors. + * @param {number} [options.reconnectTimeout] Custom stream connection timeout in ms, default is 15 seconds. + * @returns {Function} Close function. Run to close the connection and stop listening for new events. + */ + stream(options?: EventSourceOptions ? U : T>): () => void; + /** + * Sets `cursor` parameter for the current call. Returns the CallBuilder object on which this method has been called. + * @see [Paging](https://developers.stellar.org/api/introduction/pagination/) + * @param {string} cursor A cursor is a value that points to a specific location in a collection of resources. + * @returns {object} current CallBuilder instance + */ + cursor(cursor: string): this; + /** + * Sets `limit` parameter for the current call. Returns the CallBuilder object on which this method has been called. + * @see [Paging](https://developers.stellar.org/api/introduction/pagination/) + * @param {number} recordsNumber Number of records the server should return. + * @returns {object} current CallBuilder instance + */ + limit(recordsNumber: number): this; + /** + * Sets `order` parameter for the current call. Returns the CallBuilder object on which this method has been called. + * @param {"asc"|"desc"} direction Sort direction + * @returns {object} current CallBuilder instance + */ + order(direction: "asc" | "desc"): this; + /** + * Sets `join` parameter for the current call. The `join` parameter + * includes the requested resource in the response. Currently, the + * only valid value for the parameter is `transactions` and is only + * supported on the operations and payments endpoints. The response + * will include a `transaction` field for each operation in the + * response. + * + * @param "include" join Records to be included in the response. + * @returns {object} current CallBuilder instance. + */ + join(include: "transactions"): this; + /** + * A helper method to craft queries to "neighbor" endpoints. + * + * For example, we have an `/effects` suffix endpoint on many different + * "root" endpoints, such as `/transactions/:id` and `/accounts/:id`. So, + * it's helpful to be able to conveniently create queries to the + * `/accounts/:id/effects` endpoint: + * + * this.forEndpoint("accounts", accountId)`. + * + * @param {string} endpoint neighbor endpoint in question, like /operations + * @param {string} param filter parameter, like an operation ID + * + * @returns {CallBuilder} this CallBuilder instance + */ + protected forEndpoint(endpoint: string, param: string): this; + /** + * @private + * @returns {void} + */ + private checkFilter; + /** + * Convert a link object to a function that fetches that link. + * @private + * @param {object} link A link object + * @param {boolean} link.href the URI of the link + * @param {boolean} [link.templated] Whether the link is templated + * @returns {Function} A function that requests the link + */ + private _requestFnForLink; + /** + * Given the json response, find and convert each link into a function that + * calls that link. + * @private + * @param {object} json JSON response + * @returns {object} JSON response with string links replaced with functions + */ + private _parseRecord; + private _sendNormalRequest; + /** + * @private + * @param {object} json Response object + * @returns {object} Extended response + */ + private _parseResponse; + /** + * @private + * @param {object} json Response object + * @returns {object} Extended response object + */ + private _toCollectionPage; + /** + * @private + * @param {object} error Network error object + * @returns {Promise} Promise that rejects with a human-readable error + */ + private _handleNetworkError; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/call_builder.js new file mode 100644 index 000000000..76d56529d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/call_builder.js @@ -0,0 +1,362 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.CallBuilder = void 0; +var _urijs = _interopRequireDefault(require("urijs")); +var _URITemplate = _interopRequireDefault(require("urijs/src/URITemplate")); +var _errors = require("../errors"); +var _horizon_axios_client = require("./horizon_axios_client"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var JOINABLE = ["transaction"]; +var anyGlobal = global; +var EventSource; +if (typeof true !== 'undefined' && true) { + var _ref, _anyGlobal$EventSourc, _anyGlobal$window; + EventSource = (_ref = (_anyGlobal$EventSourc = anyGlobal.EventSource) !== null && _anyGlobal$EventSourc !== void 0 ? _anyGlobal$EventSourc : (_anyGlobal$window = anyGlobal.window) === null || _anyGlobal$window === void 0 ? void 0 : _anyGlobal$window.EventSource) !== null && _ref !== void 0 ? _ref : require("eventsource"); +} +var CallBuilder = exports.CallBuilder = function () { + function CallBuilder(serverUrl) { + var neighborRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; + _classCallCheck(this, CallBuilder); + this.url = serverUrl.clone(); + this.filter = []; + this.originalSegments = this.url.segment() || []; + this.neighborRoot = neighborRoot; + } + return _createClass(CallBuilder, [{ + key: "call", + value: function call() { + var _this = this; + this.checkFilter(); + return this._sendNormalRequest(this.url).then(function (r) { + return _this._parseResponse(r); + }); + } + }, { + key: "stream", + value: function stream() { + var _this2 = this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (EventSource === undefined) { + throw new Error("Streaming requires eventsource to be enabled. If you need this functionality, compile with USE_EVENTSOURCE=true."); + } + this.checkFilter(); + this.url.setQuery("X-Client-Name", "js-stellar-sdk"); + this.url.setQuery("X-Client-Version", _horizon_axios_client.version); + var es; + var timeout; + var createTimeout = function createTimeout() { + timeout = setTimeout(function () { + var _es; + (_es = es) === null || _es === void 0 || _es.close(); + es = _createEventSource(); + }, options.reconnectTimeout || 15 * 1000); + }; + var _createEventSource = function createEventSource() { + try { + es = new EventSource(_this2.url.toString()); + } catch (err) { + if (options.onerror) { + options.onerror(err); + } + } + createTimeout(); + if (!es) { + return es; + } + var closed = false; + var onClose = function onClose() { + if (closed) { + return; + } + clearTimeout(timeout); + es.close(); + _createEventSource(); + closed = true; + }; + var onMessage = function onMessage(message) { + if (message.type === "close") { + onClose(); + return; + } + var result = message.data ? _this2._parseRecord(JSON.parse(message.data)) : message; + if (result.paging_token) { + _this2.url.setQuery("cursor", result.paging_token); + } + clearTimeout(timeout); + createTimeout(); + if (typeof options.onmessage !== "undefined") { + options.onmessage(result); + } + }; + var onError = function onError(error) { + if (options.onerror) { + options.onerror(error); + } + }; + if (es.addEventListener) { + es.addEventListener("message", onMessage.bind(_this2)); + es.addEventListener("error", onError.bind(_this2)); + es.addEventListener("close", onClose.bind(_this2)); + } else { + es.onmessage = onMessage.bind(_this2); + es.onerror = onError.bind(_this2); + } + return es; + }; + _createEventSource(); + return function () { + var _es2; + clearTimeout(timeout); + (_es2 = es) === null || _es2 === void 0 || _es2.close(); + }; + } + }, { + key: "cursor", + value: function cursor(_cursor) { + this.url.setQuery("cursor", _cursor); + return this; + } + }, { + key: "limit", + value: function limit(recordsNumber) { + this.url.setQuery("limit", recordsNumber.toString()); + return this; + } + }, { + key: "order", + value: function order(direction) { + this.url.setQuery("order", direction); + return this; + } + }, { + key: "join", + value: function join(include) { + this.url.setQuery("join", include); + return this; + } + }, { + key: "forEndpoint", + value: function forEndpoint(endpoint, param) { + if (this.neighborRoot === "") { + throw new Error("Invalid usage: neighborRoot not set in constructor"); + } + this.filter.push([endpoint, param, this.neighborRoot]); + return this; + } + }, { + key: "checkFilter", + value: function checkFilter() { + if (this.filter.length >= 2) { + throw new _errors.BadRequestError("Too many filters specified", this.filter); + } + if (this.filter.length === 1) { + var newSegment = this.originalSegments.concat(this.filter[0]); + this.url.segment(newSegment); + } + } + }, { + key: "_requestFnForLink", + value: function _requestFnForLink(link) { + var _this3 = this; + return _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var opts, + uri, + template, + r, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}; + if (link.templated) { + template = (0, _URITemplate.default)(link.href); + uri = (0, _urijs.default)(template.expand(opts)); + } else { + uri = (0, _urijs.default)(link.href); + } + _context.next = 4; + return _this3._sendNormalRequest(uri); + case 4: + r = _context.sent; + return _context.abrupt("return", _this3._parseResponse(r)); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + } + }, { + key: "_parseRecord", + value: function _parseRecord(json) { + var _this4 = this; + if (!json._links) { + return json; + } + Object.keys(json._links).forEach(function (key) { + var n = json._links[key]; + var included = false; + if (typeof json[key] !== "undefined") { + json["".concat(key, "_attr")] = json[key]; + included = true; + } + if (included && JOINABLE.indexOf(key) >= 0) { + var record = _this4._parseRecord(json[key]); + json[key] = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", record); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + } else { + json[key] = _this4._requestFnForLink(n); + } + }); + return json; + } + }, { + key: "_sendNormalRequest", + value: function () { + var _sendNormalRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(initialUrl) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = initialUrl; + if (url.authority() === "") { + url = url.authority(this.url.authority()); + } + if (url.protocol() === "") { + url = url.protocol(this.url.protocol()); + } + return _context3.abrupt("return", _horizon_axios_client.AxiosClient.get(url.toString()).then(function (response) { + return response.data; + }).catch(this._handleNetworkError)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function _sendNormalRequest(_x) { + return _sendNormalRequest2.apply(this, arguments); + } + return _sendNormalRequest; + }() + }, { + key: "_parseResponse", + value: function _parseResponse(json) { + if (json._embedded && json._embedded.records) { + return this._toCollectionPage(json); + } + return this._parseRecord(json); + } + }, { + key: "_toCollectionPage", + value: function _toCollectionPage(json) { + var _this5 = this; + for (var i = 0; i < json._embedded.records.length; i += 1) { + json._embedded.records[i] = this._parseRecord(json._embedded.records[i]); + } + return { + records: json._embedded.records, + next: function () { + var _next2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + var r; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this5._sendNormalRequest((0, _urijs.default)(json._links.next.href)); + case 2: + r = _context4.sent; + return _context4.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function next() { + return _next2.apply(this, arguments); + } + return next; + }(), + prev: function () { + var _prev = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5() { + var r; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return _this5._sendNormalRequest((0, _urijs.default)(json._links.prev.href)); + case 2: + r = _context5.sent; + return _context5.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function prev() { + return _prev.apply(this, arguments); + } + return prev; + }() + }; + } + }, { + key: "_handleNetworkError", + value: (function () { + var _handleNetworkError2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(error) { + var _error$response$statu, _error$response$statu2; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + if (!(error.response && error.response.status)) { + _context6.next = 8; + break; + } + _context6.t0 = error.response.status; + _context6.next = _context6.t0 === 404 ? 4 : 5; + break; + case 4: + return _context6.abrupt("return", Promise.reject(new _errors.NotFoundError((_error$response$statu = error.response.statusText) !== null && _error$response$statu !== void 0 ? _error$response$statu : "Not Found", error.response.data))); + case 5: + return _context6.abrupt("return", Promise.reject(new _errors.NetworkError((_error$response$statu2 = error.response.statusText) !== null && _error$response$statu2 !== void 0 ? _error$response$statu2 : "Unknown", error.response.data))); + case 6: + _context6.next = 9; + break; + case 8: + return _context6.abrupt("return", Promise.reject(new Error(error.message))); + case 9: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function _handleNetworkError(_x2) { + return _handleNetworkError2.apply(this, arguments); + } + return _handleNetworkError; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/claimable_balances_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/claimable_balances_call_builder.d.ts new file mode 100644 index 000000000..6e5f7eea7 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/claimable_balances_call_builder.d.ts @@ -0,0 +1,50 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link ClaimableBalanceCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#claimableBalances}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/claimablebalances|Claimable Balances} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class ClaimableBalanceCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The claimable balance details endpoint provides information on a single claimable balance. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-claimable-balance|Claimable Balance Details} + * @param {string} claimableBalanceId Claimable balance ID + * @returns {CallBuilder} CallBuilder OperationCallBuilder instance + */ + claimableBalance(claimableBalanceId: string): CallBuilder; + /** + * Returns all claimable balances which are sponsored by the given account ID. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-claimable-balances|Claimable Balances} + * @param {string} sponsor For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance + */ + sponsor(sponsor: string): this; + /** + * Returns all claimable balances which can be claimed by the given account ID. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-claimable-balances|Claimable Balances} + * @param {string} claimant For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance + */ + claimant(claimant: string): this; + /** + * Returns all claimable balances which provide a balance for the given asset. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-claimable-balances|Claimable Balances} + * @param {Asset} asset The Asset held by the claimable balance + * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance + */ + asset(asset: Asset): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/claimable_balances_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/claimable_balances_call_builder.js new file mode 100644 index 000000000..188c8076a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/claimable_balances_call_builder.js @@ -0,0 +1,56 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ClaimableBalanceCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var ClaimableBalanceCallBuilder = exports.ClaimableBalanceCallBuilder = function (_CallBuilder) { + function ClaimableBalanceCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, ClaimableBalanceCallBuilder); + _this = _callSuper(this, ClaimableBalanceCallBuilder, [serverUrl]); + _this.url.segment("claimable_balances"); + return _this; + } + _inherits(ClaimableBalanceCallBuilder, _CallBuilder); + return _createClass(ClaimableBalanceCallBuilder, [{ + key: "claimableBalance", + value: function claimableBalance(claimableBalanceId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([claimableBalanceId]); + return builder; + } + }, { + key: "sponsor", + value: function sponsor(_sponsor) { + this.url.setQuery("sponsor", _sponsor); + return this; + } + }, { + key: "claimant", + value: function claimant(_claimant) { + this.url.setQuery("claimant", _claimant); + return this; + } + }, { + key: "asset", + value: function asset(_asset) { + this.url.setQuery("asset", _asset.toString()); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/effect_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/effect_call_builder.d.ts new file mode 100644 index 000000000..8f1e56266 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/effect_call_builder.d.ts @@ -0,0 +1,53 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link EffectCallBuilder} pointed to server defined by serverUrl. + * Do not create this object directly, use {@link Horizon.Server#effects}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/effects|All Effects} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class EffectCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * This endpoint represents all effects that changed a given account. It will return relevant effects from the creation of the account to the current ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-effects-by-account-id|Effects for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * Effects are the specific ways that the ledger was changed by any operation. + * + * This endpoint represents all effects that occurred in the given ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-ledgers-effects|Effects for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all effects that occurred as a result of a given transaction. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-transactions-effects|Effects for Transaction} + * @param {string} transactionId Transaction ID + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forTransaction(transactionId: string): this; + /** + * This endpoint represents all effects that occurred as a result of a given operation. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-an-operations-effects|Effects for Operation} + * @param {number} operationId Operation ID + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forOperation(operationId: string): this; + /** + * This endpoint represents all effects involving a particular liquidity pool. + * + * @param {string} poolId liquidity pool ID + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forLiquidityPool(poolId: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/effect_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/effect_call_builder.js new file mode 100644 index 000000000..147128700 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/effect_call_builder.js @@ -0,0 +1,56 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.EffectCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var EffectCallBuilder = exports.EffectCallBuilder = function (_CallBuilder) { + function EffectCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, EffectCallBuilder); + _this = _callSuper(this, EffectCallBuilder, [serverUrl, "effects"]); + _this.url.segment("effects"); + return _this; + } + _inherits(EffectCallBuilder, _CallBuilder); + return _createClass(EffectCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forOperation", + value: function forOperation(operationId) { + return this.forEndpoint("operations", operationId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/friendbot_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/friendbot_builder.d.ts new file mode 100644 index 000000000..30e5addb9 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/friendbot_builder.d.ts @@ -0,0 +1,4 @@ +import { CallBuilder } from "./call_builder"; +export declare class FriendbotBuilder extends CallBuilder { + constructor(serverUrl: URI, address: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/friendbot_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/friendbot_builder.js new file mode 100644 index 000000000..f80bd06f8 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/friendbot_builder.js @@ -0,0 +1,32 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FriendbotBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var FriendbotBuilder = exports.FriendbotBuilder = function (_CallBuilder) { + function FriendbotBuilder(serverUrl, address) { + var _this; + _classCallCheck(this, FriendbotBuilder); + _this = _callSuper(this, FriendbotBuilder, [serverUrl]); + _this.url.segment("friendbot"); + _this.url.setQuery("addr", address); + return _this; + } + _inherits(FriendbotBuilder, _CallBuilder); + return _createClass(FriendbotBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/horizon_api.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/horizon_api.d.ts new file mode 100644 index 000000000..d52968614 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/horizon_api.d.ts @@ -0,0 +1,540 @@ +import { AssetType, MemoType } from "@stellar/stellar-base"; +export declare namespace HorizonApi { + interface ResponseLink { + href: string; + templated?: boolean; + } + interface BaseResponse { + _links: { + [key in T | "self"]: ResponseLink; + }; + } + interface SubmitTransactionResponse { + hash: string; + ledger: number; + successful: boolean; + envelope_xdr: string; + result_xdr: string; + result_meta_xdr: string; + paging_token: string; + } + interface SubmitAsyncTransactionResponse { + hash: string; + tx_status: string; + error_result_xdr: string; + } + interface FeeBumpTransactionResponse { + hash: string; + signatures: string[]; + } + interface InnerTransactionResponse { + hash: string; + signatures: string[]; + max_fee: string; + } + interface TransactionPreconditions { + timebounds?: { + min_time: string; + max_time: string; + }; + ledgerbounds?: { + min_ledger: number; + max_ledger: number; + }; + min_account_sequence?: string; + min_account_sequence_age?: string; + min_account_sequence_ledger_gap?: number; + extra_signers?: string[]; + } + interface TransactionResponse extends SubmitTransactionResponse, BaseResponse<"account" | "ledger" | "operations" | "effects" | "succeeds" | "precedes"> { + created_at: string; + fee_meta_xdr: string; + fee_charged: number | string; + max_fee: number | string; + id: string; + memo_type: MemoType; + memo?: string; + memo_bytes?: string; + operation_count: number; + paging_token: string; + signatures: string[]; + source_account: string; + source_account_sequence: string; + fee_account: string; + inner_transaction?: InnerTransactionResponse; + fee_bump_transaction?: FeeBumpTransactionResponse; + preconditions?: TransactionPreconditions; + } + interface BalanceLineNative { + balance: string; + asset_type: AssetType.native; + buying_liabilities: string; + selling_liabilities: string; + } + interface BalanceLineLiquidityPool { + liquidity_pool_id: string; + asset_type: AssetType.liquidityPoolShares; + balance: string; + limit: string; + last_modified_ledger: number; + is_authorized: boolean; + is_authorized_to_maintain_liabilities: boolean; + is_clawback_enabled: boolean; + sponsor?: string; + } + interface BalanceLineAsset { + balance: string; + limit: string; + asset_type: T; + asset_code: string; + asset_issuer: string; + buying_liabilities: string; + selling_liabilities: string; + last_modified_ledger: number; + is_authorized: boolean; + is_authorized_to_maintain_liabilities: boolean; + is_clawback_enabled: boolean; + sponsor?: string; + } + type BalanceLine = T extends AssetType.native ? BalanceLineNative : T extends AssetType.credit4 | AssetType.credit12 ? BalanceLineAsset : T extends AssetType.liquidityPoolShares ? BalanceLineLiquidityPool : BalanceLineNative | BalanceLineAsset | BalanceLineLiquidityPool; + interface AssetAccounts { + authorized: number; + authorized_to_maintain_liabilities: number; + unauthorized: number; + } + interface AssetBalances { + authorized: string; + authorized_to_maintain_liabilities: string; + unauthorized: string; + } + interface PriceR { + numerator: number; + denominator: number; + } + interface PriceRShorthand { + n: number; + d: number; + } + interface AccountThresholds { + low_threshold: number; + med_threshold: number; + high_threshold: number; + } + interface Flags { + auth_immutable: boolean; + auth_required: boolean; + auth_revocable: boolean; + auth_clawback_enabled: boolean; + } + interface AccountSigner { + key: string; + weight: number; + type: string; + sponsor?: string; + } + interface AccountResponse extends BaseResponse<"transactions" | "operations" | "payments" | "effects" | "offers" | "trades" | "data"> { + id: string; + paging_token: string; + account_id: string; + sequence: string; + sequence_ledger?: number; + sequence_time?: string; + subentry_count: number; + thresholds: AccountThresholds; + last_modified_ledger: number; + last_modified_time: string; + flags: Flags; + balances: BalanceLine[]; + signers: AccountSigner[]; + data: { + [key: string]: string; + }; + sponsor?: string; + num_sponsoring: number; + num_sponsored: number; + } + enum LiquidityPoolType { + constantProduct = "constant_product" + } + enum OperationResponseType { + createAccount = "create_account", + payment = "payment", + pathPayment = "path_payment_strict_receive", + createPassiveOffer = "create_passive_sell_offer", + manageOffer = "manage_sell_offer", + setOptions = "set_options", + changeTrust = "change_trust", + allowTrust = "allow_trust", + accountMerge = "account_merge", + inflation = "inflation", + manageData = "manage_data", + bumpSequence = "bump_sequence", + manageBuyOffer = "manage_buy_offer", + pathPaymentStrictSend = "path_payment_strict_send", + createClaimableBalance = "create_claimable_balance", + claimClaimableBalance = "claim_claimable_balance", + beginSponsoringFutureReserves = "begin_sponsoring_future_reserves", + endSponsoringFutureReserves = "end_sponsoring_future_reserves", + revokeSponsorship = "revoke_sponsorship", + clawback = "clawback", + clawbackClaimableBalance = "clawback_claimable_balance", + setTrustLineFlags = "set_trust_line_flags", + liquidityPoolDeposit = "liquidity_pool_deposit", + liquidityPoolWithdraw = "liquidity_pool_withdraw", + invokeHostFunction = "invoke_host_function", + bumpFootprintExpiration = "bump_footprint_expiration", + restoreFootprint = "restore_footprint" + } + enum OperationResponseTypeI { + createAccount = 0, + payment = 1, + pathPayment = 2, + createPassiveOffer = 3, + manageOffer = 4, + setOptions = 5, + changeTrust = 6, + allowTrust = 7, + accountMerge = 8, + inflation = 9, + manageData = 10, + bumpSequence = 11, + manageBuyOffer = 12, + pathPaymentStrictSend = 13, + createClaimableBalance = 14, + claimClaimableBalance = 15, + beginSponsoringFutureReserves = 16, + endSponsoringFutureReserves = 17, + revokeSponsorship = 18, + clawback = 19, + clawbackClaimableBalance = 20, + setTrustLineFlags = 21, + liquidityPoolDeposit = 22, + liquidityPoolWithdraw = 23, + invokeHostFunction = 24, + bumpFootprintExpiration = 25, + restoreFootprint = 26 + } + interface BaseOperationResponse extends BaseResponse<"succeeds" | "precedes" | "effects" | "transaction"> { + id: string; + paging_token: string; + source_account: string; + type: T; + type_i: TI; + created_at: string; + transaction_hash: string; + transaction_successful: boolean; + } + interface CreateAccountOperationResponse extends BaseOperationResponse { + account: string; + funder: string; + starting_balance: string; + } + interface PaymentOperationResponse extends BaseOperationResponse { + from: string; + to: string; + asset_type: AssetType; + asset_code?: string; + asset_issuer?: string; + amount: string; + } + interface PathPaymentOperationResponse extends BaseOperationResponse { + amount: string; + asset_code?: string; + asset_issuer?: string; + asset_type: AssetType; + from: string; + path: Array<{ + asset_code: string; + asset_issuer: string; + asset_type: AssetType; + }>; + source_amount: string; + source_asset_code?: string; + source_asset_issuer?: string; + source_asset_type: AssetType; + source_max: string; + to: string; + } + interface PathPaymentStrictSendOperationResponse extends BaseOperationResponse { + amount: string; + asset_code?: string; + asset_issuer?: string; + asset_type: AssetType; + destination_min: string; + from: string; + path: Array<{ + asset_code: string; + asset_issuer: string; + asset_type: AssetType; + }>; + source_amount: string; + source_asset_code?: string; + source_asset_issuer?: string; + source_asset_type: AssetType; + to: string; + } + interface ManageOfferOperationResponse extends BaseOperationResponse { + offer_id: number | string; + amount: string; + buying_asset_type: AssetType; + buying_asset_code?: string; + buying_asset_issuer?: string; + price: string; + price_r: PriceR; + selling_asset_type: AssetType; + selling_asset_code?: string; + selling_asset_issuer?: string; + } + interface PassiveOfferOperationResponse extends BaseOperationResponse { + offer_id: number | string; + amount: string; + buying_asset_type: AssetType; + buying_asset_code?: string; + buying_asset_issuer?: string; + price: string; + price_r: PriceR; + selling_asset_type: AssetType; + selling_asset_code?: string; + selling_asset_issuer?: string; + } + interface SetOptionsOperationResponse extends BaseOperationResponse { + signer_key?: string; + signer_weight?: number; + master_key_weight?: number; + low_threshold?: number; + med_threshold?: number; + high_threshold?: number; + home_domain?: string; + set_flags: Array<1 | 2 | 4>; + set_flags_s: Array<"auth_required_flag" | "auth_revocable_flag" | "auth_clawback_enabled_flag">; + clear_flags: Array<1 | 2 | 4>; + clear_flags_s: Array<"auth_required_flag" | "auth_revocable_flag" | "auth_clawback_enabled_flag">; + } + interface ChangeTrustOperationResponse extends BaseOperationResponse { + asset_type: AssetType.credit4 | AssetType.credit12 | AssetType.liquidityPoolShares; + asset_code?: string; + asset_issuer?: string; + liquidity_pool_id?: string; + trustee?: string; + trustor: string; + limit: string; + } + interface AllowTrustOperationResponse extends BaseOperationResponse { + asset_type: AssetType; + asset_code: string; + asset_issuer: string; + authorize: boolean; + authorize_to_maintain_liabilities: boolean; + trustee: string; + trustor: string; + } + interface AccountMergeOperationResponse extends BaseOperationResponse { + into: string; + } + interface InflationOperationResponse extends BaseOperationResponse { + } + interface ManageDataOperationResponse extends BaseOperationResponse { + name: string; + value: Buffer; + } + interface BumpSequenceOperationResponse extends BaseOperationResponse { + bump_to: string; + } + interface Predicate { + and?: Predicate[]; + or?: Predicate[]; + not?: Predicate; + abs_before?: string; + rel_before?: string; + } + interface Claimant { + destination: string; + predicate: Predicate; + } + interface CreateClaimableBalanceOperationResponse extends BaseOperationResponse { + asset: string; + amount: string; + sponsor: string; + claimants: Claimant[]; + } + interface ClaimClaimableBalanceOperationResponse extends BaseOperationResponse { + balance_id: string; + claimant: string; + } + interface BeginSponsoringFutureReservesOperationResponse extends BaseOperationResponse { + sponsored_id: string; + } + interface EndSponsoringFutureReservesOperationResponse extends BaseOperationResponse { + begin_sponsor: string; + } + interface RevokeSponsorshipOperationResponse extends BaseOperationResponse { + account_id?: string; + claimable_balance_id?: string; + data_account_id?: string; + data_name?: string; + offer_id?: string; + trustline_account_id?: string; + trustline_asset?: string; + trustline_liquidity_pool_id?: string; + signer_account_id?: string; + signer_key?: string; + } + interface ClawbackOperationResponse extends BaseOperationResponse { + asset_type: AssetType; + asset_code: string; + asset_issuer: string; + from: string; + amount: string; + } + interface ClawbackClaimableBalanceOperationResponse extends BaseOperationResponse { + balance_id: string; + } + interface SetTrustLineFlagsOperationResponse extends BaseOperationResponse { + asset_type: AssetType; + asset_code: string; + asset_issuer: string; + trustor: string; + set_flags: Array<1 | 2 | 4>; + clear_flags: Array<1 | 2 | 4>; + } + interface Reserve { + asset: string; + amount: string; + } + interface DepositLiquidityOperationResponse extends BaseOperationResponse { + liquidity_pool_id: string; + reserves_max: Reserve[]; + min_price: string; + min_price_r: PriceRShorthand; + max_price: string; + max_price_r: PriceRShorthand; + reserves_deposited: Reserve[]; + shares_received: string; + } + interface WithdrawLiquidityOperationResponse extends BaseOperationResponse { + liquidity_pool_id: string; + reserves_min: Reserve[]; + shares: string; + reserves_received: Reserve[]; + } + interface BalanceChange { + asset_type: string; + asset_code?: string; + asset_issuer?: string; + type: string; + from: string; + to: string; + amount: string; + } + interface InvokeHostFunctionOperationResponse extends BaseOperationResponse { + function: string; + parameters: { + value: string; + type: string; + }[]; + address: string; + salt: string; + asset_balance_changes: BalanceChange[]; + } + interface BumpFootprintExpirationOperationResponse extends BaseOperationResponse { + ledgers_to_expire: number; + } + interface RestoreFootprintOperationResponse extends BaseOperationResponse { + } + interface ResponseCollection { + _links: { + self: ResponseLink; + next: ResponseLink; + prev: ResponseLink; + }; + _embedded: { + records: T[]; + }; + } + interface TransactionResponseCollection extends ResponseCollection { + } + interface FeeDistribution { + max: string; + min: string; + mode: string; + p10: string; + p20: string; + p30: string; + p40: string; + p50: string; + p60: string; + p70: string; + p80: string; + p90: string; + p95: string; + p99: string; + } + interface FeeStatsResponse { + last_ledger: string; + last_ledger_base_fee: string; + ledger_capacity_usage: string; + fee_charged: FeeDistribution; + max_fee: FeeDistribution; + } + type ErrorResponseData = ErrorResponseData.RateLimitExceeded | ErrorResponseData.InternalServerError | ErrorResponseData.TransactionFailed; + namespace ErrorResponseData { + interface Base { + status: number; + title: string; + type: string; + details: string; + instance: string; + } + interface RateLimitExceeded extends Base { + status: 429; + title: "Rate Limit Exceeded"; + } + interface InternalServerError extends Base { + status: 500; + title: "Internal Server Error"; + } + interface TransactionFailed extends Base { + status: 400; + title: "Transaction Failed"; + extras: TransactionFailedExtras; + } + } + enum TransactionFailedResultCodes { + TX_FAILED = "tx_failed", + TX_BAD_SEQ = "tx_bad_seq", + TX_BAD_AUTH = "tx_bad_auth", + TX_BAD_AUTH_EXTRA = "tx_bad_auth_extra", + TX_FEE_BUMP_INNER_SUCCESS = "tx_fee_bump_inner_success", + TX_FEE_BUMP_INNER_FAILED = "tx_fee_bump_inner_failed", + TX_NOT_SUPPORTED = "tx_not_supported", + TX_SUCCESS = "tx_success", + TX_TOO_EARLY = "tx_too_early", + TX_TOO_LATE = "tx_too_late", + TX_MISSING_OPERATION = "tx_missing_operation", + TX_INSUFFICIENT_BALANCE = "tx_insufficient_balance", + TX_NO_SOURCE_ACCOUNT = "tx_no_source_account", + TX_INSUFFICIENT_FEE = "tx_insufficient_fee", + TX_INTERNAL_ERROR = "tx_internal_error" + } + interface TransactionFailedExtras { + envelope_xdr: string; + result_codes: { + transaction: TransactionFailedResultCodes; + operations: string[]; + }; + result_xdr: string; + } + interface RootResponse { + horizon_version: string; + core_version: string; + ingest_latest_ledger: number; + history_latest_ledger: number; + history_latest_ledger_closed_at: string; + history_elder_ledger: number; + core_latest_ledger: number; + network_passphrase: string; + current_protocol_version: number; + supported_protocol_version: number; + core_supported_protocol_version: number; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/horizon_api.js b/node_modules/@stellar/stellar-sdk/lib/horizon/horizon_api.js new file mode 100644 index 000000000..b4b1c1878 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/horizon_api.js @@ -0,0 +1,96 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.HorizonApi = void 0; +var HorizonApi; +(function (_HorizonApi) { + var LiquidityPoolType = function (LiquidityPoolType) { + LiquidityPoolType["constantProduct"] = "constant_product"; + return LiquidityPoolType; + }({}); + _HorizonApi.LiquidityPoolType = LiquidityPoolType; + var OperationResponseType = function (OperationResponseType) { + OperationResponseType["createAccount"] = "create_account"; + OperationResponseType["payment"] = "payment"; + OperationResponseType["pathPayment"] = "path_payment_strict_receive"; + OperationResponseType["createPassiveOffer"] = "create_passive_sell_offer"; + OperationResponseType["manageOffer"] = "manage_sell_offer"; + OperationResponseType["setOptions"] = "set_options"; + OperationResponseType["changeTrust"] = "change_trust"; + OperationResponseType["allowTrust"] = "allow_trust"; + OperationResponseType["accountMerge"] = "account_merge"; + OperationResponseType["inflation"] = "inflation"; + OperationResponseType["manageData"] = "manage_data"; + OperationResponseType["bumpSequence"] = "bump_sequence"; + OperationResponseType["manageBuyOffer"] = "manage_buy_offer"; + OperationResponseType["pathPaymentStrictSend"] = "path_payment_strict_send"; + OperationResponseType["createClaimableBalance"] = "create_claimable_balance"; + OperationResponseType["claimClaimableBalance"] = "claim_claimable_balance"; + OperationResponseType["beginSponsoringFutureReserves"] = "begin_sponsoring_future_reserves"; + OperationResponseType["endSponsoringFutureReserves"] = "end_sponsoring_future_reserves"; + OperationResponseType["revokeSponsorship"] = "revoke_sponsorship"; + OperationResponseType["clawback"] = "clawback"; + OperationResponseType["clawbackClaimableBalance"] = "clawback_claimable_balance"; + OperationResponseType["setTrustLineFlags"] = "set_trust_line_flags"; + OperationResponseType["liquidityPoolDeposit"] = "liquidity_pool_deposit"; + OperationResponseType["liquidityPoolWithdraw"] = "liquidity_pool_withdraw"; + OperationResponseType["invokeHostFunction"] = "invoke_host_function"; + OperationResponseType["bumpFootprintExpiration"] = "bump_footprint_expiration"; + OperationResponseType["restoreFootprint"] = "restore_footprint"; + return OperationResponseType; + }({}); + _HorizonApi.OperationResponseType = OperationResponseType; + var OperationResponseTypeI = function (OperationResponseTypeI) { + OperationResponseTypeI[OperationResponseTypeI["createAccount"] = 0] = "createAccount"; + OperationResponseTypeI[OperationResponseTypeI["payment"] = 1] = "payment"; + OperationResponseTypeI[OperationResponseTypeI["pathPayment"] = 2] = "pathPayment"; + OperationResponseTypeI[OperationResponseTypeI["createPassiveOffer"] = 3] = "createPassiveOffer"; + OperationResponseTypeI[OperationResponseTypeI["manageOffer"] = 4] = "manageOffer"; + OperationResponseTypeI[OperationResponseTypeI["setOptions"] = 5] = "setOptions"; + OperationResponseTypeI[OperationResponseTypeI["changeTrust"] = 6] = "changeTrust"; + OperationResponseTypeI[OperationResponseTypeI["allowTrust"] = 7] = "allowTrust"; + OperationResponseTypeI[OperationResponseTypeI["accountMerge"] = 8] = "accountMerge"; + OperationResponseTypeI[OperationResponseTypeI["inflation"] = 9] = "inflation"; + OperationResponseTypeI[OperationResponseTypeI["manageData"] = 10] = "manageData"; + OperationResponseTypeI[OperationResponseTypeI["bumpSequence"] = 11] = "bumpSequence"; + OperationResponseTypeI[OperationResponseTypeI["manageBuyOffer"] = 12] = "manageBuyOffer"; + OperationResponseTypeI[OperationResponseTypeI["pathPaymentStrictSend"] = 13] = "pathPaymentStrictSend"; + OperationResponseTypeI[OperationResponseTypeI["createClaimableBalance"] = 14] = "createClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["claimClaimableBalance"] = 15] = "claimClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["beginSponsoringFutureReserves"] = 16] = "beginSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["endSponsoringFutureReserves"] = 17] = "endSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["revokeSponsorship"] = 18] = "revokeSponsorship"; + OperationResponseTypeI[OperationResponseTypeI["clawback"] = 19] = "clawback"; + OperationResponseTypeI[OperationResponseTypeI["clawbackClaimableBalance"] = 20] = "clawbackClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["setTrustLineFlags"] = 21] = "setTrustLineFlags"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolDeposit"] = 22] = "liquidityPoolDeposit"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolWithdraw"] = 23] = "liquidityPoolWithdraw"; + OperationResponseTypeI[OperationResponseTypeI["invokeHostFunction"] = 24] = "invokeHostFunction"; + OperationResponseTypeI[OperationResponseTypeI["bumpFootprintExpiration"] = 25] = "bumpFootprintExpiration"; + OperationResponseTypeI[OperationResponseTypeI["restoreFootprint"] = 26] = "restoreFootprint"; + return OperationResponseTypeI; + }({}); + _HorizonApi.OperationResponseTypeI = OperationResponseTypeI; + ; + var TransactionFailedResultCodes = function (TransactionFailedResultCodes) { + TransactionFailedResultCodes["TX_FAILED"] = "tx_failed"; + TransactionFailedResultCodes["TX_BAD_SEQ"] = "tx_bad_seq"; + TransactionFailedResultCodes["TX_BAD_AUTH"] = "tx_bad_auth"; + TransactionFailedResultCodes["TX_BAD_AUTH_EXTRA"] = "tx_bad_auth_extra"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_SUCCESS"] = "tx_fee_bump_inner_success"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_FAILED"] = "tx_fee_bump_inner_failed"; + TransactionFailedResultCodes["TX_NOT_SUPPORTED"] = "tx_not_supported"; + TransactionFailedResultCodes["TX_SUCCESS"] = "tx_success"; + TransactionFailedResultCodes["TX_TOO_EARLY"] = "tx_too_early"; + TransactionFailedResultCodes["TX_TOO_LATE"] = "tx_too_late"; + TransactionFailedResultCodes["TX_MISSING_OPERATION"] = "tx_missing_operation"; + TransactionFailedResultCodes["TX_INSUFFICIENT_BALANCE"] = "tx_insufficient_balance"; + TransactionFailedResultCodes["TX_NO_SOURCE_ACCOUNT"] = "tx_no_source_account"; + TransactionFailedResultCodes["TX_INSUFFICIENT_FEE"] = "tx_insufficient_fee"; + TransactionFailedResultCodes["TX_INTERNAL_ERROR"] = "tx_internal_error"; + return TransactionFailedResultCodes; + }({}); + _HorizonApi.TransactionFailedResultCodes = TransactionFailedResultCodes; +})(HorizonApi || (exports.HorizonApi = HorizonApi = {})); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/horizon_axios_client.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/horizon_axios_client.d.ts new file mode 100644 index 000000000..a5934c906 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/horizon_axios_client.d.ts @@ -0,0 +1,37 @@ +export declare const version: string; +export interface ServerTime { + serverTime: number; + localTimeRecorded: number; +} +/** + * keep a local map of server times + * (export this purely for testing purposes) + * + * each entry will map the server domain to the last-known time and the local + * time it was recorded, ex: + * + * @example + * "horizon-testnet.stellar.org": { + * serverTime: 1552513039, + * localTimeRecorded: 1552513052 + * } + * + * @constant {Record.} + * @default {} + * @memberof module:Horizon + */ +export declare const SERVER_TIME_MAP: Record; +export declare const AxiosClient: import("../http-client").HttpClient; +export default AxiosClient; +/** + * Given a hostname, get the current time of that server (i.e., use the last- + * recorded server time and offset it by the time since then.) If there IS no + * recorded server time, or it's been 5 minutes since the last, return null. + * @memberof module:Horizon + * + * @param {string} hostname Hostname of a Horizon server. + * @returns {number} The UNIX timestamp (in seconds, not milliseconds) + * representing the current time on that server, or `null` if we don't have + * a record of that time. + */ +export declare function getCurrentServerTime(hostname: string): number | null; diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/horizon_axios_client.js b/node_modules/@stellar/stellar-sdk/lib/horizon/horizon_axios_client.js new file mode 100644 index 000000000..d9c56d163 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/horizon_axios_client.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.SERVER_TIME_MAP = exports.AxiosClient = void 0; +exports.getCurrentServerTime = getCurrentServerTime; +exports.version = void 0; +var _urijs = _interopRequireDefault(require("urijs")); +var _httpClient = require("../http-client"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +var version = exports.version = "13.1.0"; +var SERVER_TIME_MAP = exports.SERVER_TIME_MAP = {}; +var AxiosClient = exports.AxiosClient = (0, _httpClient.create)({ + headers: { + "X-Client-Name": "js-stellar-sdk", + "X-Client-Version": version + } +}); +function toSeconds(ms) { + return Math.floor(ms / 1000); +} +AxiosClient.interceptors.response.use(function (response) { + var hostname = (0, _urijs.default)(response.config.url).hostname(); + var serverTime = 0; + if (response.headers instanceof Headers) { + var dateHeader = response.headers.get('date'); + if (dateHeader) { + serverTime = toSeconds(Date.parse(dateHeader)); + } + } else if (_typeof(response.headers) === 'object' && 'date' in response.headers) { + var headers = response.headers; + if (typeof headers.date === 'string') { + serverTime = toSeconds(Date.parse(headers.date)); + } + } + var localTimeRecorded = toSeconds(new Date().getTime()); + if (!Number.isNaN(serverTime)) { + SERVER_TIME_MAP[hostname] = { + serverTime: serverTime, + localTimeRecorded: localTimeRecorded + }; + } + return response; +}); +var _default = exports.default = AxiosClient; +function getCurrentServerTime(hostname) { + var entry = SERVER_TIME_MAP[hostname]; + if (!entry || !entry.localTimeRecorded || !entry.serverTime) { + return null; + } + var serverTime = entry.serverTime, + localTimeRecorded = entry.localTimeRecorded; + var currentTime = toSeconds(new Date().getTime()); + if (currentTime - localTimeRecorded > 60 * 5) { + return null; + } + return currentTime - localTimeRecorded + serverTime; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/index.d.ts new file mode 100644 index 000000000..9a351398f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/index.d.ts @@ -0,0 +1,8 @@ +/** @module Horizon */ +export * from "./horizon_api"; +export * from "./server_api"; +export * from "./account_response"; +export { HorizonServer as Server } from "./server"; +export { default as AxiosClient, SERVER_TIME_MAP, getCurrentServerTime } from "./horizon_axios_client"; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/index.js b/node_modules/@stellar/stellar-sdk/lib/horizon/index.js new file mode 100644 index 000000000..4ea741268 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/index.js @@ -0,0 +1,78 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Server: true, + AxiosClient: true, + SERVER_TIME_MAP: true, + getCurrentServerTime: true +}; +Object.defineProperty(exports, "AxiosClient", { + enumerable: true, + get: function get() { + return _horizon_axios_client.default; + } +}); +Object.defineProperty(exports, "SERVER_TIME_MAP", { + enumerable: true, + get: function get() { + return _horizon_axios_client.SERVER_TIME_MAP; + } +}); +Object.defineProperty(exports, "Server", { + enumerable: true, + get: function get() { + return _server.HorizonServer; + } +}); +exports.default = void 0; +Object.defineProperty(exports, "getCurrentServerTime", { + enumerable: true, + get: function get() { + return _horizon_axios_client.getCurrentServerTime; + } +}); +var _horizon_api = require("./horizon_api"); +Object.keys(_horizon_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _horizon_api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _horizon_api[key]; + } + }); +}); +var _server_api = require("./server_api"); +Object.keys(_server_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _server_api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _server_api[key]; + } + }); +}); +var _account_response = require("./account_response"); +Object.keys(_account_response).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _account_response[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _account_response[key]; + } + }); +}); +var _server = require("./server"); +var _horizon_axios_client = _interopRequireWildcard(require("./horizon_axios_client")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/ledger_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/ledger_call_builder.d.ts new file mode 100644 index 000000000..76c7f38ef --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/ledger_call_builder.d.ts @@ -0,0 +1,23 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link LedgerCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#ledgers}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-ledgers|All Ledgers} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class LedgerCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Provides information on a single ledger. + * @param {number|string} sequence Ledger sequence + * @returns {LedgerCallBuilder} current LedgerCallBuilder instance + */ + ledger(sequence: number | string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/ledger_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/ledger_call_builder.js new file mode 100644 index 000000000..93b2801b3 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/ledger_call_builder.js @@ -0,0 +1,37 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LedgerCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var LedgerCallBuilder = exports.LedgerCallBuilder = function (_CallBuilder) { + function LedgerCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, LedgerCallBuilder); + _this = _callSuper(this, LedgerCallBuilder, [serverUrl]); + _this.url.segment("ledgers"); + return _this; + } + _inherits(LedgerCallBuilder, _CallBuilder); + return _createClass(LedgerCallBuilder, [{ + key: "ledger", + value: function ledger(sequence) { + this.filter.push(["ledgers", sequence.toString()]); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/liquidity_pool_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/liquidity_pool_call_builder.d.ts new file mode 100644 index 000000000..806984c17 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/liquidity_pool_call_builder.d.ts @@ -0,0 +1,37 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link LiquidityPoolCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#liquidityPools}. + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class LiquidityPoolCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Filters out pools whose reserves don't exactly match these assets. + * + * @see Asset + * @returns {LiquidityPoolCallBuilder} current LiquidityPoolCallBuilder instance + */ + forAssets(...assets: Asset[]): this; + /** + * Retrieves all pools an account is participating in. + * + * @param {string} id the participant account to filter by + * @returns {LiquidityPoolCallBuilder} current LiquidityPoolCallBuilder instance + */ + forAccount(id: string): this; + /** + * Retrieves a specific liquidity pool by ID. + * + * @param {string} id the hash/ID of the liquidity pool + * @returns {CallBuilder} a new CallBuilder instance for the /liquidity_pools/:id endpoint + */ + liquidityPoolId(id: string): CallBuilder; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/liquidity_pool_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/liquidity_pool_call_builder.js new file mode 100644 index 000000000..7f0c6ff78 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/liquidity_pool_call_builder.js @@ -0,0 +1,59 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LiquidityPoolCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var LiquidityPoolCallBuilder = exports.LiquidityPoolCallBuilder = function (_CallBuilder) { + function LiquidityPoolCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, LiquidityPoolCallBuilder); + _this = _callSuper(this, LiquidityPoolCallBuilder, [serverUrl]); + _this.url.segment("liquidity_pools"); + return _this; + } + _inherits(LiquidityPoolCallBuilder, _CallBuilder); + return _createClass(LiquidityPoolCallBuilder, [{ + key: "forAssets", + value: function forAssets() { + for (var _len = arguments.length, assets = new Array(_len), _key = 0; _key < _len; _key++) { + assets[_key] = arguments[_key]; + } + var assetList = assets.map(function (asset) { + return asset.toString(); + }).join(","); + this.url.setQuery("reserves", assetList); + return this; + } + }, { + key: "forAccount", + value: function forAccount(id) { + this.url.setQuery("account", id); + return this; + } + }, { + key: "liquidityPoolId", + value: function liquidityPoolId(id) { + if (!id.match(/[a-fA-F0-9]{64}/)) { + throw new TypeError("".concat(id, " does not look like a liquidity pool ID")); + } + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([id.toLowerCase()]); + return builder; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/offer_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/offer_call_builder.d.ts new file mode 100644 index 000000000..2628c3960 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/offer_call_builder.d.ts @@ -0,0 +1,65 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link OfferCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#offers}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/|Offers} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class OfferCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The offer details endpoint provides information on a single offer. The offer ID provided in the id + * argument specifies which offer to load. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/single/|Offer Details} + * @param {string} offerId Offer ID + * @returns {CallBuilder} CallBuilder OperationCallBuilder instance + */ + offer(offerId: string): CallBuilder; + /** + * Returns all offers where the given account is involved. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/accounts/offers/|Offers} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + forAccount(id: string): this; + /** + * Returns all offers buying an asset. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/list/|Offers} + * @see Asset + * @param {Asset} asset For example: `new Asset('USD','GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD')` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + buying(asset: Asset): this; + /** + * Returns all offers selling an asset. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/list/|Offers} + * @see Asset + * @param {Asset} asset For example: `new Asset('EUR','GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD')` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + selling(asset: Asset): this; + /** + * This endpoint filters offers where the given account is sponsoring the offer entry. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-all-offers|Offers} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + sponsor(id: string): this; + /** + * This endpoint filters offers where the given account is the seller. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-all-offers|Offers} + * @param {string} seller For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + seller(seller: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/offer_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/offer_call_builder.js new file mode 100644 index 000000000..12c6a6277 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/offer_call_builder.js @@ -0,0 +1,79 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OfferCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var OfferCallBuilder = exports.OfferCallBuilder = function (_CallBuilder) { + function OfferCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, OfferCallBuilder); + _this = _callSuper(this, OfferCallBuilder, [serverUrl, "offers"]); + _this.url.segment("offers"); + return _this; + } + _inherits(OfferCallBuilder, _CallBuilder); + return _createClass(OfferCallBuilder, [{ + key: "offer", + value: function offer(offerId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([offerId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(id) { + return this.forEndpoint("accounts", id); + } + }, { + key: "buying", + value: function buying(asset) { + if (!asset.isNative()) { + this.url.setQuery("buying_asset_type", asset.getAssetType()); + this.url.setQuery("buying_asset_code", asset.getCode()); + this.url.setQuery("buying_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("buying_asset_type", "native"); + } + return this; + } + }, { + key: "selling", + value: function selling(asset) { + if (!asset.isNative()) { + this.url.setQuery("selling_asset_type", asset.getAssetType()); + this.url.setQuery("selling_asset_code", asset.getCode()); + this.url.setQuery("selling_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("selling_asset_type", "native"); + } + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "seller", + value: function seller(_seller) { + this.url.setQuery("seller", _seller); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/operation_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/operation_call_builder.d.ts new file mode 100644 index 000000000..ca7c9781c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/operation_call_builder.d.ts @@ -0,0 +1,69 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link OperationCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#operations}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/operations|All Operations} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class OperationCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The operation details endpoint provides information on a single operation. The operation ID provided in the id + * argument specifies which operation to load. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-an-operation|Operation Details} + * @param {number} operationId Operation ID + * @returns {CallBuilder} this OperationCallBuilder instance + */ + operation(operationId: string): CallBuilder; + /** + * This endpoint represents all operations that were included in valid transactions that affected a particular account. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-operations-by-account-id|Operations for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * This endpoint represents all operations that reference a given claimable_balance. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/cb-retrieve-related-operations|Operations for Claimable Balance} + * @param {string} claimableBalanceId Claimable Balance ID + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forClaimableBalance(claimableBalanceId: string): this; + /** + * This endpoint returns all operations that occurred in a given ledger. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-ledgers-operations|Operations for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all operations that are part of a given transaction. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-transactions-operations|Operations for Transaction} + * @param {string} transactionId Transaction ID + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forTransaction(transactionId: string): this; + /** + * This endpoint represents all operations involving a particular liquidity pool. + * + * @param {string} poolId liquidity pool ID + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forLiquidityPool(poolId: string): this; + /** + * Adds a parameter defining whether to include failed transactions. + * By default, only operations of successful transactions are returned. + * + * @param {boolean} value Set to `true` to include operations of failed transactions. + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + includeFailed(value: boolean): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/operation_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/operation_call_builder.js new file mode 100644 index 000000000..d24cd67d7 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/operation_call_builder.js @@ -0,0 +1,69 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OperationCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var OperationCallBuilder = exports.OperationCallBuilder = function (_CallBuilder) { + function OperationCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, OperationCallBuilder); + _this = _callSuper(this, OperationCallBuilder, [serverUrl, "operations"]); + _this.url.segment("operations"); + return _this; + } + _inherits(OperationCallBuilder, _CallBuilder); + return _createClass(OperationCallBuilder, [{ + key: "operation", + value: function operation(operationId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([operationId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/orderbook_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/orderbook_call_builder.d.ts new file mode 100644 index 000000000..484126432 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/orderbook_call_builder.d.ts @@ -0,0 +1,20 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link OrderbookCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#orderbook}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/order-books|Orderbook Details} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl serverUrl Horizon server URL. + * @param {Asset} selling Asset being sold + * @param {Asset} buying Asset being bought + */ +export declare class OrderbookCallBuilder extends CallBuilder { + constructor(serverUrl: URI, selling: Asset, buying: Asset); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/orderbook_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/orderbook_call_builder.js new file mode 100644 index 000000000..c4d3dd4c6 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/orderbook_call_builder.js @@ -0,0 +1,45 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OrderbookCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var OrderbookCallBuilder = exports.OrderbookCallBuilder = function (_CallBuilder) { + function OrderbookCallBuilder(serverUrl, selling, buying) { + var _this; + _classCallCheck(this, OrderbookCallBuilder); + _this = _callSuper(this, OrderbookCallBuilder, [serverUrl]); + _this.url.segment("order_book"); + if (!selling.isNative()) { + _this.url.setQuery("selling_asset_type", selling.getAssetType()); + _this.url.setQuery("selling_asset_code", selling.getCode()); + _this.url.setQuery("selling_asset_issuer", selling.getIssuer()); + } else { + _this.url.setQuery("selling_asset_type", "native"); + } + if (!buying.isNative()) { + _this.url.setQuery("buying_asset_type", buying.getAssetType()); + _this.url.setQuery("buying_asset_code", buying.getCode()); + _this.url.setQuery("buying_asset_issuer", buying.getIssuer()); + } else { + _this.url.setQuery("buying_asset_type", "native"); + } + return _this; + } + _inherits(OrderbookCallBuilder, _CallBuilder); + return _createClass(OrderbookCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/path_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/path_call_builder.d.ts new file mode 100644 index 000000000..56c89afa9 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/path_call_builder.d.ts @@ -0,0 +1,35 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * The Stellar Network allows payments to be made across assets through path payments. A path payment specifies a + * series of assets to route a payment through, from source asset (the asset debited from the payer) to destination + * asset (the asset credited to the payee). + * + * A path search is specified using: + * + * * The destination address + * * The source address + * * The asset and amount that the destination account should receive + * + * As part of the search, horizon will load a list of assets available to the source address and will find any + * payment paths from those source assets to the desired destination asset. The search's amount parameter will be + * used to determine if there a given path can satisfy a payment of the desired amount. + * + * Do not create this object directly, use {@link Horizon.Server#paths}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/paths|Find Payment Paths} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + * @param {string} source The sender's account ID. Any returned path must use a source that the sender can hold. + * @param {string} destination The destination account ID that any returned path should use. + * @param {Asset} destinationAsset The destination asset. + * @param {string} destinationAmount The amount, denominated in the destination asset, that any returned path should be able to satisfy. + */ +export declare class PathCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, source: string, destination: string, destinationAsset: Asset, destinationAmount: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/path_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/path_call_builder.js new file mode 100644 index 000000000..53f5cebbe --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/path_call_builder.js @@ -0,0 +1,41 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PathCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var PathCallBuilder = exports.PathCallBuilder = function (_CallBuilder) { + function PathCallBuilder(serverUrl, source, destination, destinationAsset, destinationAmount) { + var _this; + _classCallCheck(this, PathCallBuilder); + _this = _callSuper(this, PathCallBuilder, [serverUrl]); + _this.url.segment("paths"); + _this.url.setQuery("destination_account", destination); + _this.url.setQuery("source_account", source); + _this.url.setQuery("destination_amount", destinationAmount); + if (!destinationAsset.isNative()) { + _this.url.setQuery("destination_asset_type", destinationAsset.getAssetType()); + _this.url.setQuery("destination_asset_code", destinationAsset.getCode()); + _this.url.setQuery("destination_asset_issuer", destinationAsset.getIssuer()); + } else { + _this.url.setQuery("destination_asset_type", "native"); + } + return _this; + } + _inherits(PathCallBuilder, _CallBuilder); + return _createClass(PathCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/payment_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/payment_call_builder.d.ts new file mode 100644 index 000000000..bcee63c88 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/payment_call_builder.d.ts @@ -0,0 +1,39 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link PaymentCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#payments}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/horizon/resources/list-all-payments/|All Payments} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + */ +export declare class PaymentCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * This endpoint responds with a collection of Payment operations where the given account was either the sender or receiver. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/horizon/resources/get-payments-by-account-id|Payments for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {PaymentCallBuilder} this PaymentCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * This endpoint represents all payment operations that are part of a valid transactions in a given ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/horizon/resources/retrieve-a-ledgers-payments|Payments for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {PaymentCallBuilder} this PaymentCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all payment operations that are part of a given transaction. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/transactions/payments/|Payments for Transaction} + * @param {string} transactionId Transaction ID + * @returns {PaymentCallBuilder} this PaymentCallBuilder instance + */ + forTransaction(transactionId: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/payment_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/payment_call_builder.js new file mode 100644 index 000000000..e3a9c26bf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/payment_call_builder.js @@ -0,0 +1,46 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PaymentCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var PaymentCallBuilder = exports.PaymentCallBuilder = function (_CallBuilder) { + function PaymentCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, PaymentCallBuilder); + _this = _callSuper(this, PaymentCallBuilder, [serverUrl, "payments"]); + _this.url.segment("payments"); + return _this; + } + _inherits(PaymentCallBuilder, _CallBuilder); + return _createClass(PaymentCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/server.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/server.d.ts new file mode 100644 index 000000000..ef83c857a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/server.d.ts @@ -0,0 +1,394 @@ +import { Asset, FeeBumpTransaction, Transaction } from "@stellar/stellar-base"; +import URI from "urijs"; +import { AccountCallBuilder } from "./account_call_builder"; +import { AccountResponse } from "./account_response"; +import { AssetsCallBuilder } from "./assets_call_builder"; +import { ClaimableBalanceCallBuilder } from "./claimable_balances_call_builder"; +import { EffectCallBuilder } from "./effect_call_builder"; +import { FriendbotBuilder } from "./friendbot_builder"; +import { HorizonApi } from "./horizon_api"; +import { LedgerCallBuilder } from "./ledger_call_builder"; +import { LiquidityPoolCallBuilder } from "./liquidity_pool_call_builder"; +import { OfferCallBuilder } from "./offer_call_builder"; +import { OperationCallBuilder } from "./operation_call_builder"; +import { OrderbookCallBuilder } from "./orderbook_call_builder"; +import { PathCallBuilder } from "./path_call_builder"; +import { PaymentCallBuilder } from "./payment_call_builder"; +import { TradeAggregationCallBuilder } from "./trade_aggregation_call_builder"; +import { TradesCallBuilder } from "./trades_call_builder"; +import { TransactionCallBuilder } from "./transaction_call_builder"; +/** + * Default transaction submission timeout for Horizon requests, in milliseconds + * @constant {number} + * @default 60000 + * @memberof module:Horizon.Server + */ +export declare const SUBMIT_TRANSACTION_TIMEOUT: number; +/** + * Server handles the network connection to a [Horizon](https://developers.stellar.org/docs/data/horizon) + * instance and exposes an interface for requests to that instance. + * @class + * @alias module:Horizon.Server + * @memberof module:Horizon + * + * @param {string} serverURL Horizon Server URL (ex. `https://horizon-testnet.stellar.org`). + * @param {module:Horizon.Server.Options} [opts] Options object + */ +export declare class HorizonServer { + /** + * Horizon Server URL (ex. `https://horizon-testnet.stellar.org`) + * + * @todo Solve `URI(this.serverURL as any)`. + */ + readonly serverURL: URI; + constructor(serverURL: string, opts?: HorizonServer.Options); + /** + * Get timebounds for N seconds from now, when you're creating a transaction + * with {@link TransactionBuilder}. + * + * By default, {@link TransactionBuilder} uses the current local time, but + * your machine's local time could be different from Horizon's. This gives you + * more assurance that your timebounds will reflect what you want. + * + * Note that this will generate your timebounds when you **init the transaction**, + * not when you build or submit the transaction! So give yourself enough time to get + * the transaction built and signed before submitting. + * + * @example + * const transaction = new StellarSdk.TransactionBuilder(accountId, { + * fee: await StellarSdk.Server.fetchBaseFee(), + * timebounds: await StellarSdk.Server.fetchTimebounds(100) + * }) + * .addOperation(operation) + * // normally we would need to call setTimeout here, but setting timebounds + * // earlier does the trick! + * .build(); + * + * @param {number} seconds Number of seconds past the current time to wait. + * @param {boolean} [_isRetry] True if this is a retry. Only set this internally! + * This is to avoid a scenario where Horizon is horking up the wrong date. + * @returns {Promise} Promise that resolves a `timebounds` object + * (with the shape `{ minTime: 0, maxTime: N }`) that you can set the `timebounds` option to. + */ + fetchTimebounds(seconds: number, _isRetry?: boolean): Promise; + /** + * Fetch the base fee. Since this hits the server, if the server call fails, + * you might get an error. You should be prepared to use a default value if + * that happens! + * @returns {Promise} Promise that resolves to the base fee. + */ + fetchBaseFee(): Promise; + /** + * Fetch the fee stats endpoint. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/fee-stats|Fee Stats} + * @returns {Promise} Promise that resolves to the fee stats returned by Horizon. + */ + feeStats(): Promise; + /** + * Fetch the Horizon server's root endpoint. + * @returns {Promise} Promise that resolves to the root endpoint returned by Horizon. + */ + root(): Promise; + /** + * Submits a transaction to the network. + * + * By default this function calls {@link Horizon.Server#checkMemoRequired}, you can + * skip this check by setting the option `skipMemoRequiredCheck` to `true`. + * + * If you submit any number of `manageOffer` operations, this will add an + * attribute to the response that will help you analyze what happened with + * your offers. + * + * For example, you'll want to examine `offerResults` to add affordances like + * these to your app: + * - If `wasImmediatelyFilled` is true, then no offer was created. So if you + * normally watch the `Server.offers` endpoint for offer updates, you + * instead need to check `Server.trades` to find the result of this filled + * offer. + * - If `wasImmediatelyDeleted` is true, then the offer you submitted was + * deleted without reaching the orderbook or being matched (possibly because + * your amounts were rounded down to zero). So treat the just-submitted + * offer request as if it never happened. + * - If `wasPartiallyFilled` is true, you can tell the user that + * `amountBought` or `amountSold` have already been transferred. + * + * @example + * const res = { + * ...response, + * offerResults: [ + * { + * // Exact ordered list of offers that executed, with the exception + * // that the last one may not have executed entirely. + * offersClaimed: [ + * sellerId: String, + * offerId: String, + * assetSold: { + * type: 'native|credit_alphanum4|credit_alphanum12', + * + * // these are only present if the asset is not native + * assetCode: String, + * issuer: String, + * }, + * + * // same shape as assetSold + * assetBought: {} + * ], + * + * // What effect your manageOffer op had + * effect: "manageOfferCreated|manageOfferUpdated|manageOfferDeleted", + * + * // Whether your offer immediately got matched and filled + * wasImmediatelyFilled: Boolean, + * + * // Whether your offer immediately got deleted, if for example the order was too small + * wasImmediatelyDeleted: Boolean, + * + * // Whether the offer was partially, but not completely, filled + * wasPartiallyFilled: Boolean, + * + * // The full requested amount of the offer is open for matching + * isFullyOpen: Boolean, + * + * // The total amount of tokens bought / sold during transaction execution + * amountBought: Number, + * amountSold: Number, + * + * // if the offer was created, updated, or partially filled, this is + * // the outstanding offer + * currentOffer: { + * offerId: String, + * amount: String, + * price: { + * n: String, + * d: String, + * }, + * + * selling: { + * type: 'native|credit_alphanum4|credit_alphanum12', + * + * // these are only present if the asset is not native + * assetCode: String, + * issuer: String, + * }, + * + * // same as `selling` + * buying: {}, + * }, + * + * // the index of this particular operation in the op stack + * operationIndex: Number + * } + * ] + * } + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/submit-a-transaction|Submit a Transaction} + * @param {Transaction|FeeBumpTransaction} transaction - The transaction to submit. + * @param {object} [opts] Options object + * @param {boolean} [opts.skipMemoRequiredCheck] - Allow skipping memo + * required check, default: `false`. See + * [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md). + * @returns {Promise} Promise that resolves or rejects with response from + * horizon. + */ + submitTransaction(transaction: Transaction | FeeBumpTransaction, opts?: HorizonServer.SubmitTransactionOptions): Promise; + /** + * Submits an asynchronous transaction to the network. Unlike the synchronous version, which blocks + * and waits for the transaction to be ingested in Horizon, this endpoint relays the response from + * core directly back to the user. + * + * By default, this function calls {@link HorizonServer#checkMemoRequired}, you can + * skip this check by setting the option `skipMemoRequiredCheck` to `true`. + * + * @see [Submit-Async-Transaction](https://developers.stellar.org/docs/data/horizon/api-reference/resources/submit-async-transaction) + * @param {Transaction|FeeBumpTransaction} transaction - The transaction to submit. + * @param {object} [opts] Options object + * @param {boolean} [opts.skipMemoRequiredCheck] - Allow skipping memo + * required check, default: `false`. See + * [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md). + * @returns {Promise} Promise that resolves or rejects with response from + * horizon. + */ + submitAsyncTransaction(transaction: Transaction | FeeBumpTransaction, opts?: HorizonServer.SubmitTransactionOptions): Promise; + /** + * @returns {AccountCallBuilder} New {@link AccountCallBuilder} object configured by a current Horizon server configuration. + */ + accounts(): AccountCallBuilder; + /** + * @returns {ClaimableBalanceCallBuilder} New {@link ClaimableBalanceCallBuilder} object configured by a current Horizon server configuration. + */ + claimableBalances(): ClaimableBalanceCallBuilder; + /** + * @returns {LedgerCallBuilder} New {@link LedgerCallBuilder} object configured by a current Horizon server configuration. + */ + ledgers(): LedgerCallBuilder; + /** + * @returns {TransactionCallBuilder} New {@link TransactionCallBuilder} object configured by a current Horizon server configuration. + */ + transactions(): TransactionCallBuilder; + /** + * People on the Stellar network can make offers to buy or sell assets. This endpoint represents all the offers on the DEX. + * + * You can query all offers for account using the function `.accountId`. + * + * @example + * server.offers() + * .forAccount(accountId).call() + * .then(function(offers) { + * console.log(offers); + * }); + * + * @returns {OfferCallBuilder} New {@link OfferCallBuilder} object + */ + offers(): OfferCallBuilder; + /** + * @param {Asset} selling Asset being sold + * @param {Asset} buying Asset being bought + * @returns {OrderbookCallBuilder} New {@link OrderbookCallBuilder} object configured by a current Horizon server configuration. + */ + orderbook(selling: Asset, buying: Asset): OrderbookCallBuilder; + /** + * Returns + * @returns {TradesCallBuilder} New {@link TradesCallBuilder} object configured by a current Horizon server configuration. + */ + trades(): TradesCallBuilder; + /** + * @returns {OperationCallBuilder} New {@link OperationCallBuilder} object configured by a current Horizon server configuration. + */ + operations(): OperationCallBuilder; + /** + * @returns {LiquidityPoolCallBuilder} New {@link LiquidityPoolCallBuilder} + * object configured to the current Horizon server settings. + */ + liquidityPools(): LiquidityPoolCallBuilder; + /** + * The Stellar Network allows payments to be made between assets through path + * payments. A strict receive path payment specifies a series of assets to + * route a payment through, from source asset (the asset debited from the + * payer) to destination asset (the asset credited to the payee). + * + * A strict receive path search is specified using: + * + * * The destination address. + * * The source address or source assets. + * * The asset and amount that the destination account should receive. + * + * As part of the search, horizon will load a list of assets available to the + * source address and will find any payment paths from those source assets to + * the desired destination asset. The search's amount parameter will be used + * to determine if there a given path can satisfy a payment of the desired + * amount. + * + * If a list of assets is passed as the source, horizon will find any payment + * paths from those source assets to the desired destination asset. + * + * @param {string|Asset[]} source The sender's account ID or a list of assets. Any returned path will use a source that the sender can hold. + * @param {Asset} destinationAsset The destination asset. + * @param {string} destinationAmount The amount, denominated in the destination asset, that any returned path should be able to satisfy. + * @returns {StrictReceivePathCallBuilder} New {@link StrictReceivePathCallBuilder} object configured with the current Horizon server configuration. + */ + strictReceivePaths(source: string | Asset[], destinationAsset: Asset, destinationAmount: string): PathCallBuilder; + /** + * The Stellar Network allows payments to be made between assets through path payments. A strict send path payment specifies a + * series of assets to route a payment through, from source asset (the asset debited from the payer) to destination + * asset (the asset credited to the payee). + * + * A strict send path search is specified using: + * + * The asset and amount that is being sent. + * The destination account or the destination assets. + * + * @param {Asset} sourceAsset The asset to be sent. + * @param {string} sourceAmount The amount, denominated in the source asset, that any returned path should be able to satisfy. + * @param {string|Asset[]} destination The destination account or the destination assets. + * @returns {StrictSendPathCallBuilder} New {@link StrictSendPathCallBuilder} object configured with the current Horizon server configuration. + */ + strictSendPaths(sourceAsset: Asset, sourceAmount: string, destination: string | Asset[]): PathCallBuilder; + /** + * @returns {PaymentCallBuilder} New {@link PaymentCallBuilder} instance configured with the current + * Horizon server configuration. + */ + payments(): PaymentCallBuilder; + /** + * @returns {EffectCallBuilder} New {@link EffectCallBuilder} instance configured with the current + * Horizon server configuration + */ + effects(): EffectCallBuilder; + /** + * @param {string} address The Stellar ID that you want Friendbot to send lumens to + * @returns {FriendbotBuilder} New {@link FriendbotBuilder} instance configured with the current + * Horizon server configuration + * @private + */ + friendbot(address: string): FriendbotBuilder; + /** + * Get a new {@link AssetsCallBuilder} instance configured with the current + * Horizon server configuration. + * @returns {AssetsCallBuilder} New AssetsCallBuilder instance + */ + assets(): AssetsCallBuilder; + /** + * Fetches an account's most current state in the ledger, then creates and + * returns an {@link AccountResponse} object. + * + * @param {string} accountId - The account to load. + * + * @returns {Promise} Returns a promise to the {@link AccountResponse} object + * with populated sequence number. + */ + loadAccount(accountId: string): Promise; + /** + * + * @param {Asset} base base asset + * @param {Asset} counter counter asset + * @param {number} start_time lower time boundary represented as millis since epoch + * @param {number} end_time upper time boundary represented as millis since epoch + * @param {number} resolution segment duration as millis since epoch. *Supported values are 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). + * @param {number} offset segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. + * Returns new {@link TradeAggregationCallBuilder} object configured with the current Horizon server configuration. + * @returns {TradeAggregationCallBuilder} New TradeAggregationCallBuilder instance + */ + tradeAggregation(base: Asset, counter: Asset, start_time: number, end_time: number, resolution: number, offset: number): TradeAggregationCallBuilder; + /** + * Check if any of the destination accounts requires a memo. + * + * This function implements a memo required check as defined in + * [SEP-29](https://stellar.org/protocol/sep-29). It will load each account + * which is the destination and check if it has the data field + * `config.memo_required` set to `"MQ=="`. + * + * Each account is checked sequentially instead of loading multiple accounts + * at the same time from Horizon. + * + * @see {@link https://stellar.org/protocol/sep-29|SEP-29: Account Memo Requirements} + * @param {Transaction} transaction - The transaction to check. + * @returns {Promise} - If any of the destination account + * requires a memo, the promise will throw {@link AccountRequiresMemoError}. + * @throws {AccountRequiresMemoError} + */ + checkMemoRequired(transaction: Transaction | FeeBumpTransaction): Promise; +} +/** + * Options for configuring connections to Horizon servers. + * @typedef {object} Options + * @memberof module:Horizon.Server + * @property {boolean} [allowHttp] Allow connecting to http servers, default: `false`. This must be set to false in production deployments! You can also use {@link Config} class to set this globally. + * @property {string} [appName] Allow set custom header `X-App-Name`, default: `undefined`. + * @property {string} [appVersion] Allow set custom header `X-App-Version`, default: `undefined`. + * @property {string} [authToken] Allow set custom header `X-Auth-Token`, default: `undefined`. + */ +export declare namespace HorizonServer { + interface Options { + allowHttp?: boolean; + appName?: string; + appVersion?: string; + authToken?: string; + headers?: Record; + } + interface Timebounds { + minTime: number; + maxTime: number; + } + interface SubmitTransactionOptions { + skipMemoRequiredCheck?: boolean; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/server.js b/node_modules/@stellar/stellar-sdk/lib/horizon/server.js new file mode 100644 index 000000000..111c8b341 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/server.js @@ -0,0 +1,571 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SUBMIT_TRANSACTION_TIMEOUT = exports.HorizonServer = void 0; +var _bignumber = _interopRequireDefault(require("bignumber.js")); +var _stellarBase = require("@stellar/stellar-base"); +var _urijs = _interopRequireDefault(require("urijs")); +var _call_builder = require("./call_builder"); +var _config = require("../config"); +var _errors = require("../errors"); +var _account_call_builder = require("./account_call_builder"); +var _account_response = require("./account_response"); +var _assets_call_builder = require("./assets_call_builder"); +var _claimable_balances_call_builder = require("./claimable_balances_call_builder"); +var _effect_call_builder = require("./effect_call_builder"); +var _friendbot_builder = require("./friendbot_builder"); +var _ledger_call_builder = require("./ledger_call_builder"); +var _liquidity_pool_call_builder = require("./liquidity_pool_call_builder"); +var _offer_call_builder = require("./offer_call_builder"); +var _operation_call_builder = require("./operation_call_builder"); +var _orderbook_call_builder = require("./orderbook_call_builder"); +var _payment_call_builder = require("./payment_call_builder"); +var _strict_receive_path_call_builder = require("./strict_receive_path_call_builder"); +var _strict_send_path_call_builder = require("./strict_send_path_call_builder"); +var _trade_aggregation_call_builder = require("./trade_aggregation_call_builder"); +var _trades_call_builder = require("./trades_call_builder"); +var _transaction_call_builder = require("./transaction_call_builder"); +var _horizon_axios_client = _interopRequireWildcard(require("./horizon_axios_client")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var SUBMIT_TRANSACTION_TIMEOUT = exports.SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000; +var STROOPS_IN_LUMEN = 10000000; +var ACCOUNT_REQUIRES_MEMO = "MQ=="; +function getAmountInLumens(amt) { + return new _bignumber.default(amt).div(STROOPS_IN_LUMEN).toString(); +} +var HorizonServer = exports.HorizonServer = function () { + function HorizonServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, HorizonServer); + this.serverURL = (0, _urijs.default)(serverURL); + var allowHttp = typeof opts.allowHttp === "undefined" ? _config.Config.isAllowHttp() : opts.allowHttp; + var customHeaders = {}; + if (opts.appName) { + customHeaders["X-App-Name"] = opts.appName; + } + if (opts.appVersion) { + customHeaders["X-App-Version"] = opts.appVersion; + } + if (opts.authToken) { + customHeaders["X-Auth-Token"] = opts.authToken; + } + if (opts.headers) { + Object.assign(customHeaders, opts.headers); + } + if (Object.keys(customHeaders).length > 0) { + _horizon_axios_client.default.interceptors.request.use(function (config) { + config.headers = config.headers || {}; + config.headers = Object.assign(config.headers, customHeaders); + return config; + }); + } + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure horizon server"); + } + } + return _createClass(HorizonServer, [{ + key: "fetchTimebounds", + value: (function () { + var _fetchTimebounds = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(seconds) { + var _isRetry, + currentTime, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _isRetry = _args.length > 1 && _args[1] !== undefined ? _args[1] : false; + currentTime = (0, _horizon_axios_client.getCurrentServerTime)(this.serverURL.hostname()); + if (!currentTime) { + _context.next = 4; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: currentTime + seconds + }); + case 4: + if (!_isRetry) { + _context.next = 6; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: Math.floor(new Date().getTime() / 1000) + seconds + }); + case 6: + _context.next = 8; + return _horizon_axios_client.default.get((0, _urijs.default)(this.serverURL).toString()); + case 8: + return _context.abrupt("return", this.fetchTimebounds(seconds, true)); + case 9: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function fetchTimebounds(_x) { + return _fetchTimebounds.apply(this, arguments); + } + return fetchTimebounds; + }()) + }, { + key: "fetchBaseFee", + value: (function () { + var _fetchBaseFee = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + var response; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.feeStats(); + case 2: + response = _context2.sent; + return _context2.abrupt("return", parseInt(response.last_ledger_base_fee, 10) || 100); + case 4: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function fetchBaseFee() { + return _fetchBaseFee.apply(this, arguments); + } + return fetchBaseFee; + }()) + }, { + key: "feeStats", + value: (function () { + var _feeStats = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3() { + var cb; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + cb = new _call_builder.CallBuilder((0, _urijs.default)(this.serverURL)); + cb.filter.push(["fee_stats"]); + return _context3.abrupt("return", cb.call()); + case 3: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function feeStats() { + return _feeStats.apply(this, arguments); + } + return feeStats; + }()) + }, { + key: "root", + value: (function () { + var _root = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + var cb; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + cb = new _call_builder.CallBuilder((0, _urijs.default)(this.serverURL)); + return _context4.abrupt("return", cb.call()); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function root() { + return _root.apply(this, arguments); + } + return root; + }()) + }, { + key: "submitTransaction", + value: (function () { + var _submitTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(transaction) { + var opts, + tx, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context5.next = 4; + break; + } + _context5.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context5.abrupt("return", _horizon_axios_client.default.post((0, _urijs.default)(this.serverURL).segment("transactions").toString(), "tx=".concat(tx), { + timeout: SUBMIT_TRANSACTION_TIMEOUT + }).then(function (response) { + if (!response.data.result_xdr) { + return response.data; + } + var responseXDR = _stellarBase.xdr.TransactionResult.fromXDR(response.data.result_xdr, "base64"); + var results = responseXDR.result().value(); + var offerResults; + var hasManageOffer; + if (results.length) { + offerResults = results.map(function (result, i) { + if (result.value().switch().name !== "manageBuyOffer" && result.value().switch().name !== "manageSellOffer") { + return null; + } + hasManageOffer = true; + var amountBought = new _bignumber.default(0); + var amountSold = new _bignumber.default(0); + var offerSuccess = result.value().value().success(); + var offersClaimed = offerSuccess.offersClaimed().map(function (offerClaimedAtom) { + var offerClaimed = offerClaimedAtom.value(); + var sellerId = ""; + switch (offerClaimedAtom.switch()) { + case _stellarBase.xdr.ClaimAtomType.claimAtomTypeV0(): + sellerId = _stellarBase.StrKey.encodeEd25519PublicKey(offerClaimed.sellerEd25519()); + break; + case _stellarBase.xdr.ClaimAtomType.claimAtomTypeOrderBook(): + sellerId = _stellarBase.StrKey.encodeEd25519PublicKey(offerClaimed.sellerId().ed25519()); + break; + default: + throw new Error("Invalid offer result type: ".concat(offerClaimedAtom.switch())); + } + var claimedOfferAmountBought = new _bignumber.default(offerClaimed.amountBought().toString()); + var claimedOfferAmountSold = new _bignumber.default(offerClaimed.amountSold().toString()); + amountBought = amountBought.plus(claimedOfferAmountSold); + amountSold = amountSold.plus(claimedOfferAmountBought); + var sold = _stellarBase.Asset.fromOperation(offerClaimed.assetSold()); + var bought = _stellarBase.Asset.fromOperation(offerClaimed.assetBought()); + var assetSold = { + type: sold.getAssetType(), + assetCode: sold.getCode(), + issuer: sold.getIssuer() + }; + var assetBought = { + type: bought.getAssetType(), + assetCode: bought.getCode(), + issuer: bought.getIssuer() + }; + return { + sellerId: sellerId, + offerId: offerClaimed.offerId().toString(), + assetSold: assetSold, + amountSold: getAmountInLumens(claimedOfferAmountSold), + assetBought: assetBought, + amountBought: getAmountInLumens(claimedOfferAmountBought) + }; + }); + var effect = offerSuccess.offer().switch().name; + var currentOffer; + if (typeof offerSuccess.offer().value === "function" && offerSuccess.offer().value()) { + var offerXDR = offerSuccess.offer().value(); + currentOffer = { + offerId: offerXDR.offerId().toString(), + selling: {}, + buying: {}, + amount: getAmountInLumens(offerXDR.amount().toString()), + price: { + n: offerXDR.price().n(), + d: offerXDR.price().d() + } + }; + var selling = _stellarBase.Asset.fromOperation(offerXDR.selling()); + currentOffer.selling = { + type: selling.getAssetType(), + assetCode: selling.getCode(), + issuer: selling.getIssuer() + }; + var buying = _stellarBase.Asset.fromOperation(offerXDR.buying()); + currentOffer.buying = { + type: buying.getAssetType(), + assetCode: buying.getCode(), + issuer: buying.getIssuer() + }; + } + return { + offersClaimed: offersClaimed, + effect: effect, + operationIndex: i, + currentOffer: currentOffer, + amountBought: getAmountInLumens(amountBought), + amountSold: getAmountInLumens(amountSold), + isFullyOpen: !offersClaimed.length && effect !== "manageOfferDeleted", + wasPartiallyFilled: !!offersClaimed.length && effect !== "manageOfferDeleted", + wasImmediatelyFilled: !!offersClaimed.length && effect === "manageOfferDeleted", + wasImmediatelyDeleted: !offersClaimed.length && effect === "manageOfferDeleted" + }; + }).filter(function (result) { + return !!result; + }); + } + return _objectSpread(_objectSpread({}, response.data), {}, { + offerResults: hasManageOffer ? offerResults : undefined + }); + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new _errors.BadResponseError("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function submitTransaction(_x2) { + return _submitTransaction.apply(this, arguments); + } + return submitTransaction; + }()) + }, { + key: "submitAsyncTransaction", + value: (function () { + var _submitAsyncTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(transaction) { + var opts, + tx, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context6.next = 4; + break; + } + _context6.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context6.abrupt("return", _horizon_axios_client.default.post((0, _urijs.default)(this.serverURL).segment("transactions_async").toString(), "tx=".concat(tx)).then(function (response) { + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new _errors.BadResponseError("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function submitAsyncTransaction(_x3) { + return _submitAsyncTransaction.apply(this, arguments); + } + return submitAsyncTransaction; + }()) + }, { + key: "accounts", + value: function accounts() { + return new _account_call_builder.AccountCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "claimableBalances", + value: function claimableBalances() { + return new _claimable_balances_call_builder.ClaimableBalanceCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "ledgers", + value: function ledgers() { + return new _ledger_call_builder.LedgerCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "transactions", + value: function transactions() { + return new _transaction_call_builder.TransactionCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "offers", + value: function offers() { + return new _offer_call_builder.OfferCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "orderbook", + value: function orderbook(selling, buying) { + return new _orderbook_call_builder.OrderbookCallBuilder((0, _urijs.default)(this.serverURL), selling, buying); + } + }, { + key: "trades", + value: function trades() { + return new _trades_call_builder.TradesCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "operations", + value: function operations() { + return new _operation_call_builder.OperationCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "liquidityPools", + value: function liquidityPools() { + return new _liquidity_pool_call_builder.LiquidityPoolCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "strictReceivePaths", + value: function strictReceivePaths(source, destinationAsset, destinationAmount) { + return new _strict_receive_path_call_builder.StrictReceivePathCallBuilder((0, _urijs.default)(this.serverURL), source, destinationAsset, destinationAmount); + } + }, { + key: "strictSendPaths", + value: function strictSendPaths(sourceAsset, sourceAmount, destination) { + return new _strict_send_path_call_builder.StrictSendPathCallBuilder((0, _urijs.default)(this.serverURL), sourceAsset, sourceAmount, destination); + } + }, { + key: "payments", + value: function payments() { + return new _payment_call_builder.PaymentCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "effects", + value: function effects() { + return new _effect_call_builder.EffectCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "friendbot", + value: function friendbot(address) { + return new _friendbot_builder.FriendbotBuilder((0, _urijs.default)(this.serverURL), address); + } + }, { + key: "assets", + value: function assets() { + return new _assets_call_builder.AssetsCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "loadAccount", + value: (function () { + var _loadAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee7(accountId) { + var res; + return _regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.accounts().accountId(accountId).call(); + case 2: + res = _context7.sent; + return _context7.abrupt("return", new _account_response.AccountResponse(res)); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function loadAccount(_x4) { + return _loadAccount.apply(this, arguments); + } + return loadAccount; + }()) + }, { + key: "tradeAggregation", + value: function tradeAggregation(base, counter, start_time, end_time, resolution, offset) { + return new _trade_aggregation_call_builder.TradeAggregationCallBuilder((0, _urijs.default)(this.serverURL), base, counter, start_time, end_time, resolution, offset); + } + }, { + key: "checkMemoRequired", + value: (function () { + var _checkMemoRequired = _asyncToGenerator(_regeneratorRuntime().mark(function _callee8(transaction) { + var destinations, i, operation, destination, account; + return _regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (transaction instanceof _stellarBase.FeeBumpTransaction) { + transaction = transaction.innerTransaction; + } + if (!(transaction.memo.type !== "none")) { + _context8.next = 3; + break; + } + return _context8.abrupt("return"); + case 3: + destinations = new Set(); + i = 0; + case 5: + if (!(i < transaction.operations.length)) { + _context8.next = 36; + break; + } + operation = transaction.operations[i]; + _context8.t0 = operation.type; + _context8.next = _context8.t0 === "payment" ? 10 : _context8.t0 === "pathPaymentStrictReceive" ? 10 : _context8.t0 === "pathPaymentStrictSend" ? 10 : _context8.t0 === "accountMerge" ? 10 : 11; + break; + case 10: + return _context8.abrupt("break", 12); + case 11: + return _context8.abrupt("continue", 33); + case 12: + destination = operation.destination; + if (!destinations.has(destination)) { + _context8.next = 15; + break; + } + return _context8.abrupt("continue", 33); + case 15: + destinations.add(destination); + if (!destination.startsWith("M")) { + _context8.next = 18; + break; + } + return _context8.abrupt("continue", 33); + case 18: + _context8.prev = 18; + _context8.next = 21; + return this.loadAccount(destination); + case 21: + account = _context8.sent; + if (!(account.data_attr["config.memo_required"] === ACCOUNT_REQUIRES_MEMO)) { + _context8.next = 24; + break; + } + throw new _errors.AccountRequiresMemoError("account requires memo", destination, i); + case 24: + _context8.next = 33; + break; + case 26: + _context8.prev = 26; + _context8.t1 = _context8["catch"](18); + if (!(_context8.t1 instanceof _errors.AccountRequiresMemoError)) { + _context8.next = 30; + break; + } + throw _context8.t1; + case 30: + if (_context8.t1 instanceof _errors.NotFoundError) { + _context8.next = 32; + break; + } + throw _context8.t1; + case 32: + return _context8.abrupt("continue", 33); + case 33: + i += 1; + _context8.next = 5; + break; + case 36: + case "end": + return _context8.stop(); + } + }, _callee8, this, [[18, 26]]); + })); + function checkMemoRequired(_x5) { + return _checkMemoRequired.apply(this, arguments); + } + return checkMemoRequired; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/server_api.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/server_api.d.ts new file mode 100644 index 000000000..77a8367ba --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/server_api.d.ts @@ -0,0 +1,264 @@ +import { Asset } from "@stellar/stellar-base"; +import { HorizonApi } from "./horizon_api"; +import { AccountRecordSigners as AccountRecordSignersType } from "./types/account"; +import { AssetRecord as AssetRecordType } from "./types/assets"; +import * as Effects from "./types/effects"; +import { OfferRecord as OfferRecordType } from "./types/offer"; +import { Trade } from "./types/trade"; +export declare namespace ServerApi { + export type OfferRecord = OfferRecordType; + export type AccountRecordSigners = AccountRecordSignersType; + export type AssetRecord = AssetRecordType; + export interface CollectionPage { + records: T[]; + next: () => Promise>; + prev: () => Promise>; + } + export interface CallFunctionTemplateOptions { + cursor?: string | number; + limit?: number; + order?: "asc" | "desc"; + } + export type CallFunction = () => Promise; + export type CallCollectionFunction = (options?: CallFunctionTemplateOptions) => Promise>; + type BaseEffectRecordFromTypes = Effects.AccountCreated | Effects.AccountCredited | Effects.AccountDebited | Effects.AccountThresholdsUpdated | Effects.AccountHomeDomainUpdated | Effects.AccountFlagsUpdated | Effects.DataCreated | Effects.DataRemoved | Effects.DataUpdated | Effects.SequenceBumped | Effects.SignerCreated | Effects.SignerRemoved | Effects.SignerUpdated | Effects.TrustlineCreated | Effects.TrustlineRemoved | Effects.TrustlineUpdated | Effects.TrustlineAuthorized | Effects.TrustlineDeauthorized | Effects.TrustlineAuthorizedToMaintainLiabilities | Effects.ClaimableBalanceCreated | Effects.ClaimableBalanceClaimed | Effects.ClaimableBalanceClaimantCreated | Effects.AccountSponsorshipCreated | Effects.AccountSponsorshipRemoved | Effects.AccountSponsorshipUpdated | Effects.TrustlineSponsorshipCreated | Effects.TrustlineSponsorshipUpdated | Effects.TrustlineSponsorshipRemoved | Effects.DateSponsorshipCreated | Effects.DateSponsorshipUpdated | Effects.DateSponsorshipRemoved | Effects.ClaimableBalanceSponsorshipCreated | Effects.ClaimableBalanceSponsorshipRemoved | Effects.ClaimableBalanceSponsorshipUpdated | Effects.SignerSponsorshipCreated | Effects.SignerSponsorshipUpdated | Effects.SignerSponsorshipRemoved | Effects.LiquidityPoolDeposited | Effects.LiquidityPoolWithdrew | Effects.LiquidityPoolCreated | Effects.LiquidityPoolRemoved | Effects.LiquidityPoolRevoked | Effects.LiquidityPoolTrade | Effects.ContractCredited | Effects.ContractDebited | Trade; + export type EffectRecord = BaseEffectRecordFromTypes & EffectRecordMethods; + export const EffectType: typeof Effects.EffectType; + export interface ClaimableBalanceRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + asset: string; + amount: string; + sponsor?: string; + last_modified_ledger: number; + claimants: HorizonApi.Claimant[]; + } + export interface AccountRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + account_id: string; + sequence: string; + sequence_ledger?: number; + sequence_time?: string; + subentry_count: number; + home_domain?: string; + inflation_destination?: string; + last_modified_ledger: number; + last_modified_time: string; + thresholds: HorizonApi.AccountThresholds; + flags: HorizonApi.Flags; + balances: HorizonApi.BalanceLine[]; + signers: AccountRecordSigners[]; + data: (options: { + value: string; + }) => Promise<{ + value: string; + }>; + data_attr: { + [key: string]: string; + }; + sponsor?: string; + num_sponsoring: number; + num_sponsored: number; + effects: CallCollectionFunction; + offers: CallCollectionFunction; + operations: CallCollectionFunction; + payments: CallCollectionFunction; + trades: CallCollectionFunction; + } + export interface LiquidityPoolRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + fee_bp: number; + type: HorizonApi.LiquidityPoolType; + total_trustlines: string; + total_shares: string; + reserves: HorizonApi.Reserve[]; + } + export enum TradeType { + all = "all", + liquidityPools = "liquidity_pool", + orderbook = "orderbook" + } + interface EffectRecordMethods { + operation?: CallFunction; + precedes?: CallFunction; + succeeds?: CallFunction; + } + export interface LedgerRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + hash: string; + prev_hash: string; + sequence: number; + successful_transaction_count: number; + failed_transaction_count: number; + operation_count: number; + tx_set_operation_count: number | null; + closed_at: string; + total_coins: string; + fee_pool: string; + max_tx_set_size: number; + protocol_version: number; + header_xdr: string; + base_fee_in_stroops: number; + base_reserve_in_stroops: number; + effects: CallCollectionFunction; + operations: CallCollectionFunction; + self: CallFunction; + transactions: CallCollectionFunction; + } + import OperationResponseType = HorizonApi.OperationResponseType; + import OperationResponseTypeI = HorizonApi.OperationResponseTypeI; + export interface BaseOperationRecord extends HorizonApi.BaseOperationResponse { + self: CallFunction; + succeeds: CallFunction; + precedes: CallFunction; + effects: CallCollectionFunction; + transaction: CallFunction; + } + export interface CreateAccountOperationRecord extends BaseOperationRecord, HorizonApi.CreateAccountOperationResponse { + } + export interface PaymentOperationRecord extends BaseOperationRecord, HorizonApi.PaymentOperationResponse { + sender: CallFunction; + receiver: CallFunction; + } + export interface PathPaymentOperationRecord extends BaseOperationRecord, HorizonApi.PathPaymentOperationResponse { + } + export interface PathPaymentStrictSendOperationRecord extends BaseOperationRecord, HorizonApi.PathPaymentStrictSendOperationResponse { + } + export interface ManageOfferOperationRecord extends BaseOperationRecord, HorizonApi.ManageOfferOperationResponse { + } + export interface PassiveOfferOperationRecord extends BaseOperationRecord, HorizonApi.PassiveOfferOperationResponse { + } + export interface SetOptionsOperationRecord extends BaseOperationRecord, HorizonApi.SetOptionsOperationResponse { + } + export interface ChangeTrustOperationRecord extends BaseOperationRecord, HorizonApi.ChangeTrustOperationResponse { + } + export interface AllowTrustOperationRecord extends BaseOperationRecord, HorizonApi.AllowTrustOperationResponse { + } + export interface AccountMergeOperationRecord extends BaseOperationRecord, HorizonApi.AccountMergeOperationResponse { + } + export interface InflationOperationRecord extends BaseOperationRecord, HorizonApi.InflationOperationResponse { + } + export interface ManageDataOperationRecord extends BaseOperationRecord, HorizonApi.ManageDataOperationResponse { + } + export interface BumpSequenceOperationRecord extends BaseOperationRecord, HorizonApi.BumpSequenceOperationResponse { + } + export interface CreateClaimableBalanceOperationRecord extends BaseOperationRecord, HorizonApi.CreateClaimableBalanceOperationResponse { + } + export interface ClaimClaimableBalanceOperationRecord extends BaseOperationRecord, HorizonApi.ClaimClaimableBalanceOperationResponse { + } + export interface BeginSponsoringFutureReservesOperationRecord extends BaseOperationRecord, HorizonApi.BeginSponsoringFutureReservesOperationResponse { + } + export interface EndSponsoringFutureReservesOperationRecord extends BaseOperationRecord, HorizonApi.EndSponsoringFutureReservesOperationResponse { + } + export interface RevokeSponsorshipOperationRecord extends BaseOperationRecord, HorizonApi.RevokeSponsorshipOperationResponse { + } + export interface ClawbackOperationRecord extends BaseOperationRecord, HorizonApi.ClawbackOperationResponse { + } + export interface ClawbackClaimableBalanceOperationRecord extends BaseOperationRecord, HorizonApi.ClawbackClaimableBalanceOperationResponse { + } + export interface SetTrustLineFlagsOperationRecord extends BaseOperationRecord, HorizonApi.SetTrustLineFlagsOperationResponse { + } + export interface DepositLiquidityOperationRecord extends BaseOperationRecord, HorizonApi.DepositLiquidityOperationResponse { + } + export interface WithdrawLiquidityOperationRecord extends BaseOperationRecord, HorizonApi.WithdrawLiquidityOperationResponse { + } + export interface InvokeHostFunctionOperationRecord extends BaseOperationRecord, HorizonApi.InvokeHostFunctionOperationResponse { + } + export interface BumpFootprintExpirationOperationRecord extends BaseOperationRecord, HorizonApi.BumpFootprintExpirationOperationResponse { + } + export interface RestoreFootprintOperationRecord extends BaseOperationRecord, HorizonApi.RestoreFootprintOperationResponse { + } + export type OperationRecord = CreateAccountOperationRecord | PaymentOperationRecord | PathPaymentOperationRecord | ManageOfferOperationRecord | PassiveOfferOperationRecord | SetOptionsOperationRecord | ChangeTrustOperationRecord | AllowTrustOperationRecord | AccountMergeOperationRecord | InflationOperationRecord | ManageDataOperationRecord | BumpSequenceOperationRecord | PathPaymentStrictSendOperationRecord | CreateClaimableBalanceOperationRecord | ClaimClaimableBalanceOperationRecord | BeginSponsoringFutureReservesOperationRecord | EndSponsoringFutureReservesOperationRecord | RevokeSponsorshipOperationRecord | ClawbackClaimableBalanceOperationRecord | ClawbackOperationRecord | SetTrustLineFlagsOperationRecord | DepositLiquidityOperationRecord | WithdrawLiquidityOperationRecord | InvokeHostFunctionOperationRecord | BumpFootprintExpirationOperationRecord | RestoreFootprintOperationRecord; + export namespace TradeRecord { + interface Base extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + ledger_close_time: string; + trade_type: TradeType; + base_account?: string; + base_amount: string; + base_asset_type: string; + base_asset_code?: string; + base_asset_issuer?: string; + counter_account?: string; + counter_amount: string; + counter_asset_type: string; + counter_asset_code?: string; + counter_asset_issuer?: string; + base_is_seller: boolean; + price?: { + n: string; + d: string; + }; + operation: CallFunction; + } + export interface Orderbook extends Base { + trade_type: TradeType.orderbook; + base_offer_id: string; + base_account: string; + counter_offer_id: string; + counter_account: string; + base: CallFunction; + counter: CallFunction; + } + export interface LiquidityPool extends Base { + trade_type: TradeType.liquidityPools; + base_liquidity_pool_id?: string; + counter_liquidity_pool_id?: string; + liquidity_pool_fee_bp: number; + base: CallFunction; + counter: CallFunction; + } + export {}; + } + export type TradeRecord = TradeRecord.Orderbook | TradeRecord.LiquidityPool; + export interface TransactionRecord extends Omit { + ledger_attr: HorizonApi.TransactionResponse["ledger"]; + account: CallFunction; + effects: CallCollectionFunction; + ledger: CallFunction; + operations: CallCollectionFunction; + precedes: CallFunction; + self: CallFunction; + succeeds: CallFunction; + } + export interface OrderbookRecord extends HorizonApi.BaseResponse { + bids: Array<{ + price_r: { + d: number; + n: number; + }; + price: string; + amount: string; + }>; + asks: Array<{ + price_r: { + d: number; + n: number; + }; + price: string; + amount: string; + }>; + base: Asset; + counter: Asset; + } + export interface PaymentPathRecord extends HorizonApi.BaseResponse { + path: Array<{ + asset_code: string; + asset_issuer: string; + asset_type: string; + }>; + source_amount: string; + source_asset_type: string; + source_asset_code: string; + source_asset_issuer: string; + destination_amount: string; + destination_asset_type: string; + destination_asset_code: string; + destination_asset_issuer: string; + } + export {}; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/server_api.js b/node_modules/@stellar/stellar-sdk/lib/horizon/server_api.js new file mode 100644 index 000000000..df0eafd7f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/server_api.js @@ -0,0 +1,24 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ServerApi = void 0; +var _horizon_api = require("./horizon_api"); +var Effects = _interopRequireWildcard(require("./types/effects")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var ServerApi; +(function (_ServerApi) { + var EffectType = _ServerApi.EffectType = Effects.EffectType; + var TradeType = function (TradeType) { + TradeType["all"] = "all"; + TradeType["liquidityPools"] = "liquidity_pool"; + TradeType["orderbook"] = "orderbook"; + return TradeType; + }({}); + _ServerApi.TradeType = TradeType; + var OperationResponseType = _horizon_api.HorizonApi.OperationResponseType; + var OperationResponseTypeI = _horizon_api.HorizonApi.OperationResponseTypeI; +})(ServerApi || (exports.ServerApi = ServerApi = {})); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/strict_receive_path_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/strict_receive_path_call_builder.d.ts new file mode 100644 index 000000000..1e9a28025 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/strict_receive_path_call_builder.d.ts @@ -0,0 +1,38 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * The Stellar Network allows payments to be made across assets through path + * payments. A strict receive path payment specifies a series of assets to route + * a payment through, from source asset (the asset debited from the payer) to + * destination asset (the asset credited to the payee). + * + * A path search is specified using: + * + * * The source address or source assets. + * * The asset and amount that the destination account should receive + * + * As part of the search, horizon will load a list of assets available to the + * source address and will find any payment paths from those source assets to + * the desired destination asset. The search's amount parameter will be used to + * determine if there a given path can satisfy a payment of the desired amount. + * + * If a list of assets is passed as the source, horizon will find any payment + * paths from those source assets to the desired destination asset. + * + * Do not create this object directly, use {@link Horizon.Server#strictReceivePaths}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/paths|Find Payment Paths} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + * @param {string|Asset[]} source The sender's account ID or a list of Assets. Any returned path must use a source that the sender can hold. + * @param {Asset} destinationAsset The destination asset. + * @param {string} destinationAmount The amount, denominated in the destination asset, that any returned path should be able to satisfy. + */ +export declare class StrictReceivePathCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, source: string | Asset[], destinationAsset: Asset, destinationAmount: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/strict_receive_path_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/strict_receive_path_call_builder.js new file mode 100644 index 000000000..5e4a5a992 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/strict_receive_path_call_builder.js @@ -0,0 +1,50 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.StrictReceivePathCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var StrictReceivePathCallBuilder = exports.StrictReceivePathCallBuilder = function (_CallBuilder) { + function StrictReceivePathCallBuilder(serverUrl, source, destinationAsset, destinationAmount) { + var _this; + _classCallCheck(this, StrictReceivePathCallBuilder); + _this = _callSuper(this, StrictReceivePathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-receive"); + if (typeof source === "string") { + _this.url.setQuery("source_account", source); + } else { + var assets = source.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("source_assets", assets); + } + _this.url.setQuery("destination_amount", destinationAmount); + if (!destinationAsset.isNative()) { + _this.url.setQuery("destination_asset_type", destinationAsset.getAssetType()); + _this.url.setQuery("destination_asset_code", destinationAsset.getCode()); + _this.url.setQuery("destination_asset_issuer", destinationAsset.getIssuer()); + } else { + _this.url.setQuery("destination_asset_type", "native"); + } + return _this; + } + _inherits(StrictReceivePathCallBuilder, _CallBuilder); + return _createClass(StrictReceivePathCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/strict_send_path_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/strict_send_path_call_builder.d.ts new file mode 100644 index 000000000..85cd9a154 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/strict_send_path_call_builder.d.ts @@ -0,0 +1,38 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * The Stellar Network allows payments to be made across assets through path + * payments. A strict send path payment specifies a series of assets to route a + * payment through, from source asset (the asset debited from the payer) to + * destination asset (the asset credited to the payee). + * + * A strict send path search is specified using: + * + * The source asset + * The source amount + * The destination assets or destination account. + * + * As part of the search, horizon will load a list of assets available to the + * source address and will find any payment paths from those source assets to + * the desired destination asset. The search's source_amount parameter will be + * used to determine if there a given path can satisfy a payment of the desired + * amount. + * + * Do not create this object directly, use {@link Horizon.Server#strictSendPaths}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/paths|Find Payment Paths} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + * @param {Asset} sourceAsset The asset to be sent. + * @param {string} sourceAmount The amount, denominated in the source asset, that any returned path should be able to satisfy. + * @param {string|Asset[]} destination The destination account or the destination assets. + * + */ +export declare class StrictSendPathCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, sourceAsset: Asset, sourceAmount: string, destination: string | Asset[]); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/strict_send_path_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/strict_send_path_call_builder.js new file mode 100644 index 000000000..f65a1d0a5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/strict_send_path_call_builder.js @@ -0,0 +1,50 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.StrictSendPathCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var StrictSendPathCallBuilder = exports.StrictSendPathCallBuilder = function (_CallBuilder) { + function StrictSendPathCallBuilder(serverUrl, sourceAsset, sourceAmount, destination) { + var _this; + _classCallCheck(this, StrictSendPathCallBuilder); + _this = _callSuper(this, StrictSendPathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-send"); + if (sourceAsset.isNative()) { + _this.url.setQuery("source_asset_type", "native"); + } else { + _this.url.setQuery("source_asset_type", sourceAsset.getAssetType()); + _this.url.setQuery("source_asset_code", sourceAsset.getCode()); + _this.url.setQuery("source_asset_issuer", sourceAsset.getIssuer()); + } + _this.url.setQuery("source_amount", sourceAmount); + if (typeof destination === "string") { + _this.url.setQuery("destination_account", destination); + } else { + var assets = destination.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("destination_assets", assets); + } + return _this; + } + _inherits(StrictSendPathCallBuilder, _CallBuilder); + return _createClass(StrictSendPathCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/trade_aggregation_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/trade_aggregation_call_builder.d.ts new file mode 100644 index 000000000..fe8dc52d5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/trade_aggregation_call_builder.d.ts @@ -0,0 +1,49 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { HorizonApi } from "./horizon_api"; +import { ServerApi } from "./server_api"; +/** + * Trade Aggregations facilitate efficient gathering of historical trade data. + * + * Do not create this object directly, use {@link Horizon.Server#tradeAggregation}. + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl serverUrl Horizon server URL. + * @param {Asset} base base asset + * @param {Asset} counter counter asset + * @param {number} start_time lower time boundary represented as millis since epoch + * @param {number} end_time upper time boundary represented as millis since epoch + * @param {number} resolution segment duration as millis since epoch. *Supported values are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). + * @param {number} offset segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. + */ +export declare class TradeAggregationCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, base: Asset, counter: Asset, start_time: number, end_time: number, resolution: number, offset: number); + /** + * @private + * @param {number} resolution Trade data resolution in milliseconds + * @returns {boolean} true if the resolution is allowed + */ + private isValidResolution; + /** + * @private + * @param {number} offset Time offset in milliseconds + * @param {number} resolution Trade data resolution in milliseconds + * @returns {boolean} true if the offset is valid + */ + private isValidOffset; +} +interface TradeAggregationRecord extends HorizonApi.BaseResponse { + timestamp: number | string; + trade_count: number | string; + base_volume: string; + counter_volume: string; + avg: string; + high: string; + low: string; + open: string; + close: string; +} +export {}; diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/trade_aggregation_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/trade_aggregation_call_builder.js new file mode 100644 index 000000000..b6866d738 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/trade_aggregation_call_builder.js @@ -0,0 +1,76 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TradeAggregationCallBuilder = void 0; +var _call_builder = require("./call_builder"); +var _errors = require("../errors"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var allowedResolutions = [60000, 300000, 900000, 3600000, 86400000, 604800000]; +var TradeAggregationCallBuilder = exports.TradeAggregationCallBuilder = function (_CallBuilder) { + function TradeAggregationCallBuilder(serverUrl, base, counter, start_time, end_time, resolution, offset) { + var _this; + _classCallCheck(this, TradeAggregationCallBuilder); + _this = _callSuper(this, TradeAggregationCallBuilder, [serverUrl]); + _this.url.segment("trade_aggregations"); + if (!base.isNative()) { + _this.url.setQuery("base_asset_type", base.getAssetType()); + _this.url.setQuery("base_asset_code", base.getCode()); + _this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + _this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + _this.url.setQuery("counter_asset_type", counter.getAssetType()); + _this.url.setQuery("counter_asset_code", counter.getCode()); + _this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + _this.url.setQuery("counter_asset_type", "native"); + } + if (typeof start_time !== "number" || typeof end_time !== "number") { + throw new _errors.BadRequestError("Invalid time bounds", [start_time, end_time]); + } else { + _this.url.setQuery("start_time", start_time.toString()); + _this.url.setQuery("end_time", end_time.toString()); + } + if (!_this.isValidResolution(resolution)) { + throw new _errors.BadRequestError("Invalid resolution", resolution); + } else { + _this.url.setQuery("resolution", resolution.toString()); + } + if (!_this.isValidOffset(offset, resolution)) { + throw new _errors.BadRequestError("Invalid offset", offset); + } else { + _this.url.setQuery("offset", offset.toString()); + } + return _this; + } + _inherits(TradeAggregationCallBuilder, _CallBuilder); + return _createClass(TradeAggregationCallBuilder, [{ + key: "isValidResolution", + value: function isValidResolution(resolution) { + return allowedResolutions.some(function (allowed) { + return allowed === resolution; + }); + } + }, { + key: "isValidOffset", + value: function isValidOffset(offset, resolution) { + var hour = 3600000; + return !(offset > resolution || offset >= 24 * hour || offset % hour !== 0); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/trades_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/trades_call_builder.d.ts new file mode 100644 index 000000000..2a407642e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/trades_call_builder.d.ts @@ -0,0 +1,52 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link TradesCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#trades}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/trades|Trades} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl serverUrl Horizon server URL. + */ +export declare class TradesCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Filter trades for a specific asset pair (orderbook) + * @param {Asset} base asset + * @param {Asset} counter asset + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forAssetPair(base: Asset, counter: Asset): this; + /** + * Filter trades for a specific offer + * @param {string} offerId ID of the offer + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forOffer(offerId: string): this; + /** + * Filter trades by a specific type. + * @param {ServerApi.TradeType} tradeType the trade type to filter by. + * @returns {TradesCallBuilder} current TradesCallBuilder instance. + */ + forType(tradeType: ServerApi.TradeType): this; + /** + * Filter trades for a specific account + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-trades-by-account-id|Trades for Account} + * @param {string} accountId For example: `GBYTR4MC5JAX4ALGUBJD7EIKZVM7CUGWKXIUJMRSMK573XH2O7VAK3SR` + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * Filter trades for a specific liquidity pool + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-related-trades|Trades for Liquidity Pool} + * @param {string} liquidityPoolId For example: `3b476aff8a406a6ec3b61d5c038009cef85f2ddfaf616822dc4fec92845149b4` + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forLiquidityPool(liquidityPoolId: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/trades_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/trades_call_builder.js new file mode 100644 index 000000000..5c6b23bec --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/trades_call_builder.js @@ -0,0 +1,72 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TradesCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var TradesCallBuilder = exports.TradesCallBuilder = function (_CallBuilder) { + function TradesCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, TradesCallBuilder); + _this = _callSuper(this, TradesCallBuilder, [serverUrl, "trades"]); + _this.url.segment("trades"); + return _this; + } + _inherits(TradesCallBuilder, _CallBuilder); + return _createClass(TradesCallBuilder, [{ + key: "forAssetPair", + value: function forAssetPair(base, counter) { + if (!base.isNative()) { + this.url.setQuery("base_asset_type", base.getAssetType()); + this.url.setQuery("base_asset_code", base.getCode()); + this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + this.url.setQuery("counter_asset_type", counter.getAssetType()); + this.url.setQuery("counter_asset_code", counter.getCode()); + this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + this.url.setQuery("counter_asset_type", "native"); + } + return this; + } + }, { + key: "forOffer", + value: function forOffer(offerId) { + this.url.setQuery("offer_id", offerId); + return this; + } + }, { + key: "forType", + value: function forType(tradeType) { + this.url.setQuery("trade_type", tradeType); + return this; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(liquidityPoolId) { + return this.forEndpoint("liquidity_pools", liquidityPoolId); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/transaction_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/transaction_call_builder.d.ts new file mode 100644 index 000000000..4c40ce94d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/transaction_call_builder.d.ts @@ -0,0 +1,60 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link TransactionCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#transactions}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-transactions|All Transactions} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + */ +export declare class TransactionCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The transaction details endpoint provides information on a single transaction. The transaction hash provided in the hash argument specifies which transaction to load. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-transaction|Transaction Details} + * @param {string} transactionId Transaction ID + * @returns {CallBuilder} a CallBuilder instance + */ + transaction(transactionId: string): CallBuilder; + /** + * This endpoint represents all transactions that affected a given account. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-transactions-by-account-id|Transactions for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {TransactionCallBuilder} current TransactionCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * This endpoint represents all transactions that reference a given claimable_balance. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/cb-retrieve-related-transactions|Transactions for Claimable Balance} + * @param {string} claimableBalanceId Claimable Balance ID + * @returns {TransactionCallBuilder} this TransactionCallBuilder instance + */ + forClaimableBalance(claimableBalanceId: string): this; + /** + * This endpoint represents all transactions in a given ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-ledgers-transactions|Transactions for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {TransactionCallBuilder} current TransactionCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all transactions involving a particular liquidity pool. + * + * @param {string} poolId liquidity pool ID + * @returns {TransactionCallBuilder} this TransactionCallBuilder instance + */ + forLiquidityPool(poolId: string): this; + /** + * Adds a parameter defining whether to include failed transactions. By default only successful transactions are + * returned. + * @param {boolean} value Set to `true` to include failed transactions. + * @returns {TransactionCallBuilder} current TransactionCallBuilder instance + */ + includeFailed(value: boolean): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/transaction_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/horizon/transaction_call_builder.js new file mode 100644 index 000000000..746c7bfbf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/transaction_call_builder.js @@ -0,0 +1,64 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TransactionCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var TransactionCallBuilder = exports.TransactionCallBuilder = function (_CallBuilder) { + function TransactionCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, TransactionCallBuilder); + _this = _callSuper(this, TransactionCallBuilder, [serverUrl, "transactions"]); + _this.url.segment("transactions"); + return _this; + } + _inherits(TransactionCallBuilder, _CallBuilder); + return _createClass(TransactionCallBuilder, [{ + key: "transaction", + value: function transaction(transactionId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([transactionId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/types/account.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/types/account.d.ts new file mode 100644 index 000000000..3edc78aad --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/types/account.d.ts @@ -0,0 +1,5 @@ +export interface AccountRecordSigners { + key: string; + weight: number; + type: string; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/types/account.js b/node_modules/@stellar/stellar-sdk/lib/horizon/types/account.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/types/account.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/types/assets.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/types/assets.d.ts new file mode 100644 index 000000000..c85e71a32 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/types/assets.d.ts @@ -0,0 +1,17 @@ +import { AssetType } from "@stellar/stellar-base"; +import { HorizonApi } from "../horizon_api"; +export interface AssetRecord extends HorizonApi.BaseResponse { + asset_type: AssetType.credit4 | AssetType.credit12; + asset_code: string; + asset_issuer: string; + paging_token: string; + accounts: HorizonApi.AssetAccounts; + balances: HorizonApi.AssetBalances; + num_claimable_balances: number; + num_liquidity_pools: number; + num_contracts: number; + claimable_balances_amount: string; + liquidity_pools_amount: string; + contracts_amount: string; + flags: HorizonApi.Flags; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/types/assets.js b/node_modules/@stellar/stellar-sdk/lib/horizon/types/assets.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/types/assets.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/types/effects.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/types/effects.d.ts new file mode 100644 index 000000000..a3a628dce --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/types/effects.d.ts @@ -0,0 +1,285 @@ +import { HorizonApi } from "../horizon_api"; +import { OfferAsset } from "./offer"; +export declare enum EffectType { + account_created = 0, + account_removed = 1, + account_credited = 2, + account_debited = 3, + account_thresholds_updated = 4, + account_home_domain_updated = 5, + account_flags_updated = 6, + account_inflation_destination_updated = 7, + signer_created = 10, + signer_removed = 11, + signer_updated = 12, + trustline_created = 20, + trustline_removed = 21, + trustline_updated = 22, + trustline_authorized = 23, + trustline_deauthorized = 24, + trustline_authorized_to_maintain_liabilities = 25,// deprecated, use trustline_flags_updated + trustline_flags_updated = 26, + offer_created = 30, + offer_removed = 31, + offer_updated = 32, + trade = 33, + data_created = 40, + data_removed = 41, + data_updated = 42, + sequence_bumped = 43, + claimable_balance_created = 50, + claimable_balance_claimant_created = 51, + claimable_balance_claimed = 52, + account_sponsorship_created = 60, + account_sponsorship_updated = 61, + account_sponsorship_removed = 62, + trustline_sponsorship_created = 63, + trustline_sponsorship_updated = 64, + trustline_sponsorship_removed = 65, + data_sponsorship_created = 66, + data_sponsorship_updated = 67, + data_sponsorship_removed = 68, + claimable_balance_sponsorship_created = 69, + claimable_balance_sponsorship_updated = 70, + claimable_balance_sponsorship_removed = 71, + signer_sponsorship_created = 72, + signer_sponsorship_updated = 73, + signer_sponsorship_removed = 74, + claimable_balance_clawed_back = 80, + liquidity_pool_deposited = 90, + liquidity_pool_withdrew = 91, + liquidity_pool_trade = 92, + liquidity_pool_created = 93, + liquidity_pool_removed = 94, + liquidity_pool_revoked = 95, + contract_credited = 96, + contract_debited = 97 +} +export interface BaseEffectRecord extends HorizonApi.BaseResponse { + id: string; + account: string; + paging_token: string; + type_i: EffectType; + type: T; + created_at: string; +} +export interface AccountCreated extends BaseEffectRecord<'account_created'> { + type_i: EffectType.account_created; + starting_balance: string; +} +export interface AccountCredited extends BaseEffectRecord<'account_credited'>, OfferAsset { + type_i: EffectType.account_credited; + amount: string; +} +export interface AccountDebited extends BaseEffectRecord<'account_debited'>, OfferAsset { + type_i: EffectType.account_debited; + amount: string; +} +export interface AccountThresholdsUpdated extends BaseEffectRecord<'account_thresholds_updated'> { + type_i: EffectType.account_thresholds_updated; + low_threshold: number; + med_threshold: number; + high_threshold: number; +} +export interface AccountHomeDomainUpdated extends BaseEffectRecord<'account_home_domain_updated'> { + type_i: EffectType.account_home_domain_updated; + home_domain: string; +} +export interface AccountFlagsUpdated extends BaseEffectRecord<'account_flags_updated'> { + type_i: EffectType.account_flags_updated; + auth_required_flag: boolean; + auth_revokable_flag: boolean; +} +interface DataEvents extends BaseEffectRecord { + name: boolean; + value: boolean; +} +export interface DataCreated extends DataEvents<'data_created'> { + type_i: EffectType.data_created; +} +export interface DataUpdated extends DataEvents<'data_updated'> { + type_i: EffectType.data_updated; +} +export interface DataRemoved extends DataEvents<'data_removed'> { + type_i: EffectType.data_removed; +} +export interface SequenceBumped extends BaseEffectRecord<'sequence_bumped'> { + type_i: EffectType.sequence_bumped; + new_seq: number | string; +} +interface SignerEvents extends BaseEffectRecord { + weight: number; + key: string; + public_key: string; +} +export interface SignerCreated extends SignerEvents<'signer_created'> { + type_i: EffectType.signer_created; +} +export interface SignerRemoved extends SignerEvents<'signer_removed'> { + type_i: EffectType.signer_removed; +} +export interface SignerUpdated extends SignerEvents<'signer_updated'> { + type_i: EffectType.signer_updated; +} +interface TrustlineEvents extends BaseEffectRecord, OfferAsset { + limit: string; + liquidity_pool_id?: string; +} +export interface TrustlineCreated extends TrustlineEvents<'trustline_created'> { + type_i: EffectType.trustline_created; +} +export interface TrustlineRemoved extends TrustlineEvents<'trustline_removed'> { + type_i: EffectType.trustline_removed; +} +export interface TrustlineUpdated extends TrustlineEvents<'trustline_updated'> { + type_i: EffectType.trustline_updated; +} +export interface TrustlineAuthorized extends BaseEffectRecord<'trustline_authorized'> { + type_i: EffectType.trustline_authorized; + asset_type: OfferAsset["asset_type"]; + asset_code: OfferAsset["asset_code"]; + trustor: string; +} +export interface TrustlineDeauthorized extends Omit { + type_i: EffectType.trustline_deauthorized; +} +export interface TrustlineAuthorizedToMaintainLiabilities extends Omit { + type_i: EffectType.trustline_authorized_to_maintain_liabilities; +} +export interface ClaimableBalanceCreated extends BaseEffectRecord<'claimable_balance_created'> { + type_i: EffectType.claimable_balance_created; + amount: string; + balance_type_i: string; + asset: string; +} +export interface ClaimableBalanceClaimed extends Omit { + type_i: EffectType.claimable_balance_claimed; +} +export interface ClaimableBalanceClaimantCreated extends Omit { + type_i: EffectType.claimable_balance_claimant_created; +} +interface SponsershipFields { + sponsor: string; + new_sponsor: string; + former_sponsor: string; +} +interface AccountSponsorshipEvents extends BaseEffectRecord, SponsershipFields { +} +export type AccountSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.account_sponsorship_created; +}; +export type AccountSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.account_sponsorship_updated; +}; +export type AccountSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.account_sponsorship_removed; +}; +interface TrustlineSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + asset?: string; + liquidity_pool_id?: string; +} +export type TrustlineSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.trustline_sponsorship_created; +}; +export type TrustlineSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.trustline_sponsorship_updated; +}; +export type TrustlineSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.trustline_sponsorship_removed; +}; +interface DataSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + data_name: string; +} +export type DateSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.data_sponsorship_created; +}; +export type DateSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.data_sponsorship_updated; +}; +export type DateSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.data_sponsorship_removed; +}; +interface ClaimableBalanceSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + balance_type_i: string; +} +export type ClaimableBalanceSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.claimable_balance_sponsorship_created; +}; +export type ClaimableBalanceSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.claimable_balance_sponsorship_updated; +}; +export type ClaimableBalanceSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.claimable_balance_sponsorship_removed; +}; +interface SignerSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + signer: string; +} +export type SignerSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.signer_sponsorship_created; +}; +export type SignerSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.signer_sponsorship_updated; +}; +export type SignerSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.signer_sponsorship_removed; +}; +export interface ClaimableBalanceClawedBack extends HorizonApi.BaseResponse { + balance_id: string; +} +export interface LiquidityPoolEffectRecord extends HorizonApi.BaseResponse { + id: string; + fee_bp: number; + type: HorizonApi.LiquidityPoolType; + total_trustlines: string; + total_shares: string; + reserves: HorizonApi.Reserve[]; +} +export interface LiquidityPoolDeposited extends BaseEffectRecord<'liquidity_pool_deposited'> { + type_i: EffectType.liquidity_pool_deposited; + liquidity_pool: LiquidityPoolEffectRecord; + reserves_deposited: HorizonApi.Reserve[]; + shares_received: string; +} +export interface LiquidityPoolWithdrew extends BaseEffectRecord<'liquidity_pool_withdrew'> { + type_i: EffectType.liquidity_pool_withdrew; + liquidity_pool: LiquidityPoolEffectRecord; + reserves_received: HorizonApi.Reserve[]; + shares_redeemed: string; +} +export interface LiquidityPoolTrade extends BaseEffectRecord<'liquidity_pool_trade'> { + type_i: EffectType.liquidity_pool_trade; + liquidity_pool: LiquidityPoolEffectRecord; + sold: HorizonApi.Reserve; + bought: HorizonApi.Reserve; +} +export interface LiquidityPoolCreated extends BaseEffectRecord<'liquidity_pool_created'> { + type_i: EffectType.liquidity_pool_created; + liquidity_pool: LiquidityPoolEffectRecord; +} +export interface LiquidityPoolRemoved extends BaseEffectRecord<'liquidity_pool_removed'> { + type_i: EffectType.liquidity_pool_removed; + liquidity_pool_id: string; +} +export interface LiquidityPoolRevoked extends BaseEffectRecord<'liquidity_pool_revoked'> { + type_i: EffectType.liquidity_pool_revoked; + liquidity_pool: LiquidityPoolEffectRecord; + reserves_revoked: [ + { + asset: string; + amount: string; + claimable_balance_id: string; + } + ]; + shares_revoked: string; +} +export interface ContractCredited extends BaseEffectRecord<'contract_credited'>, OfferAsset { + type_i: EffectType.contract_credited; + contract: string; + amount: string; +} +export interface ContractDebited extends BaseEffectRecord<'contract_debited'>, OfferAsset { + type_i: EffectType.contract_debited; + contract: string; + amount: string; +} +export {}; diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/types/effects.js b/node_modules/@stellar/stellar-sdk/lib/horizon/types/effects.js new file mode 100644 index 000000000..3b28a678f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/types/effects.js @@ -0,0 +1,62 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.EffectType = void 0; +var EffectType = exports.EffectType = function (EffectType) { + EffectType[EffectType["account_created"] = 0] = "account_created"; + EffectType[EffectType["account_removed"] = 1] = "account_removed"; + EffectType[EffectType["account_credited"] = 2] = "account_credited"; + EffectType[EffectType["account_debited"] = 3] = "account_debited"; + EffectType[EffectType["account_thresholds_updated"] = 4] = "account_thresholds_updated"; + EffectType[EffectType["account_home_domain_updated"] = 5] = "account_home_domain_updated"; + EffectType[EffectType["account_flags_updated"] = 6] = "account_flags_updated"; + EffectType[EffectType["account_inflation_destination_updated"] = 7] = "account_inflation_destination_updated"; + EffectType[EffectType["signer_created"] = 10] = "signer_created"; + EffectType[EffectType["signer_removed"] = 11] = "signer_removed"; + EffectType[EffectType["signer_updated"] = 12] = "signer_updated"; + EffectType[EffectType["trustline_created"] = 20] = "trustline_created"; + EffectType[EffectType["trustline_removed"] = 21] = "trustline_removed"; + EffectType[EffectType["trustline_updated"] = 22] = "trustline_updated"; + EffectType[EffectType["trustline_authorized"] = 23] = "trustline_authorized"; + EffectType[EffectType["trustline_deauthorized"] = 24] = "trustline_deauthorized"; + EffectType[EffectType["trustline_authorized_to_maintain_liabilities"] = 25] = "trustline_authorized_to_maintain_liabilities"; + EffectType[EffectType["trustline_flags_updated"] = 26] = "trustline_flags_updated"; + EffectType[EffectType["offer_created"] = 30] = "offer_created"; + EffectType[EffectType["offer_removed"] = 31] = "offer_removed"; + EffectType[EffectType["offer_updated"] = 32] = "offer_updated"; + EffectType[EffectType["trade"] = 33] = "trade"; + EffectType[EffectType["data_created"] = 40] = "data_created"; + EffectType[EffectType["data_removed"] = 41] = "data_removed"; + EffectType[EffectType["data_updated"] = 42] = "data_updated"; + EffectType[EffectType["sequence_bumped"] = 43] = "sequence_bumped"; + EffectType[EffectType["claimable_balance_created"] = 50] = "claimable_balance_created"; + EffectType[EffectType["claimable_balance_claimant_created"] = 51] = "claimable_balance_claimant_created"; + EffectType[EffectType["claimable_balance_claimed"] = 52] = "claimable_balance_claimed"; + EffectType[EffectType["account_sponsorship_created"] = 60] = "account_sponsorship_created"; + EffectType[EffectType["account_sponsorship_updated"] = 61] = "account_sponsorship_updated"; + EffectType[EffectType["account_sponsorship_removed"] = 62] = "account_sponsorship_removed"; + EffectType[EffectType["trustline_sponsorship_created"] = 63] = "trustline_sponsorship_created"; + EffectType[EffectType["trustline_sponsorship_updated"] = 64] = "trustline_sponsorship_updated"; + EffectType[EffectType["trustline_sponsorship_removed"] = 65] = "trustline_sponsorship_removed"; + EffectType[EffectType["data_sponsorship_created"] = 66] = "data_sponsorship_created"; + EffectType[EffectType["data_sponsorship_updated"] = 67] = "data_sponsorship_updated"; + EffectType[EffectType["data_sponsorship_removed"] = 68] = "data_sponsorship_removed"; + EffectType[EffectType["claimable_balance_sponsorship_created"] = 69] = "claimable_balance_sponsorship_created"; + EffectType[EffectType["claimable_balance_sponsorship_updated"] = 70] = "claimable_balance_sponsorship_updated"; + EffectType[EffectType["claimable_balance_sponsorship_removed"] = 71] = "claimable_balance_sponsorship_removed"; + EffectType[EffectType["signer_sponsorship_created"] = 72] = "signer_sponsorship_created"; + EffectType[EffectType["signer_sponsorship_updated"] = 73] = "signer_sponsorship_updated"; + EffectType[EffectType["signer_sponsorship_removed"] = 74] = "signer_sponsorship_removed"; + EffectType[EffectType["claimable_balance_clawed_back"] = 80] = "claimable_balance_clawed_back"; + EffectType[EffectType["liquidity_pool_deposited"] = 90] = "liquidity_pool_deposited"; + EffectType[EffectType["liquidity_pool_withdrew"] = 91] = "liquidity_pool_withdrew"; + EffectType[EffectType["liquidity_pool_trade"] = 92] = "liquidity_pool_trade"; + EffectType[EffectType["liquidity_pool_created"] = 93] = "liquidity_pool_created"; + EffectType[EffectType["liquidity_pool_removed"] = 94] = "liquidity_pool_removed"; + EffectType[EffectType["liquidity_pool_revoked"] = 95] = "liquidity_pool_revoked"; + EffectType[EffectType["contract_credited"] = 96] = "contract_credited"; + EffectType[EffectType["contract_debited"] = 97] = "contract_debited"; + return EffectType; +}({}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/types/offer.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/types/offer.d.ts new file mode 100644 index 000000000..a58e3f16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/types/offer.d.ts @@ -0,0 +1,20 @@ +import { AssetType } from "@stellar/stellar-base"; +import { HorizonApi } from "../horizon_api"; +export interface OfferAsset { + asset_type: AssetType; + asset_code?: string; + asset_issuer?: string; +} +export interface OfferRecord extends HorizonApi.BaseResponse { + id: number | string; + paging_token: string; + seller: string; + selling: OfferAsset; + buying: OfferAsset; + amount: string; + price_r: HorizonApi.PriceRShorthand; + price: string; + last_modified_ledger: number; + last_modified_time: string; + sponsor?: string; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/types/offer.js b/node_modules/@stellar/stellar-sdk/lib/horizon/types/offer.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/types/offer.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/types/trade.d.ts b/node_modules/@stellar/stellar-sdk/lib/horizon/types/trade.d.ts new file mode 100644 index 000000000..a38f75361 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/types/trade.d.ts @@ -0,0 +1,14 @@ +import { BaseEffectRecord, EffectType } from "./effects"; +export interface Trade extends BaseEffectRecord<'trade'> { + type_i: EffectType.trade; + seller: string; + offer_id: number | string; + bought_amount: string; + bought_asset_type: string; + bought_asset_code: string; + bought_asset_issuer: string; + sold_amount: string; + sold_asset_type: string; + sold_asset_code: string; + sold_asset_issuer: string; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/horizon/types/trade.js b/node_modules/@stellar/stellar-sdk/lib/horizon/types/trade.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/horizon/types/trade.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/http-client/axios-client.d.ts b/node_modules/@stellar/stellar-sdk/lib/http-client/axios-client.d.ts new file mode 100644 index 000000000..739c21526 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/http-client/axios-client.d.ts @@ -0,0 +1,2 @@ +export declare const axiosClient: import("axios").AxiosStatic; +export declare const create: (config?: import("axios").CreateAxiosDefaults) => import("axios").AxiosInstance; diff --git a/node_modules/@stellar/stellar-sdk/lib/http-client/axios-client.js b/node_modules/@stellar/stellar-sdk/lib/http-client/axios-client.js new file mode 100644 index 000000000..12a4eb449 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/http-client/axios-client.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.create = exports.axiosClient = void 0; +var _axios = _interopRequireDefault(require("axios")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +var axiosClient = exports.axiosClient = _axios.default; +var create = exports.create = _axios.default.create; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/http-client/fetch-client.d.ts b/node_modules/@stellar/stellar-sdk/lib/http-client/fetch-client.d.ts new file mode 100644 index 000000000..8b91ef645 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/http-client/fetch-client.d.ts @@ -0,0 +1,11 @@ +import { AxiosRequestConfig, AxiosResponse } from 'feaxios'; +import { CancelToken, HttpClient, HttpClientRequestConfig, HttpClientResponse } from './types'; +export interface HttpResponse extends AxiosResponse { +} +export interface FetchClientConfig extends AxiosRequestConfig { + adapter?: (config: HttpClientRequestConfig) => Promise>; + cancelToken?: CancelToken; +} +declare function createFetchClient(fetchConfig?: HttpClientRequestConfig): HttpClient; +export declare const fetchClient: HttpClient; +export { createFetchClient as create }; diff --git a/node_modules/@stellar/stellar-sdk/lib/http-client/fetch-client.js b/node_modules/@stellar/stellar-sdk/lib/http-client/fetch-client.js new file mode 100644 index 000000000..5da967e91 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/http-client/fetch-client.js @@ -0,0 +1,229 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.create = createFetchClient; +exports.fetchClient = void 0; +var _feaxios = _interopRequireDefault(require("feaxios")); +var _types = require("./types"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var InterceptorManager = function () { + function InterceptorManager() { + _classCallCheck(this, InterceptorManager); + _defineProperty(this, "handlers", []); + } + return _createClass(InterceptorManager, [{ + key: "use", + value: function use(fulfilled, rejected) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected + }); + return this.handlers.length - 1; + } + }, { + key: "eject", + value: function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + }, { + key: "forEach", + value: function forEach(fn) { + this.handlers.forEach(function (h) { + if (h !== null) { + fn(h); + } + }); + } + }]); +}(); +function getFormConfig(config) { + var formConfig = config || {}; + formConfig.headers = new Headers(formConfig.headers || {}); + formConfig.headers.set('Content-Type', 'application/x-www-form-urlencoded'); + return formConfig; +} +function createFetchClient() { + var fetchConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var defaults = _objectSpread(_objectSpread({}, fetchConfig), {}, { + headers: fetchConfig.headers || {} + }); + var instance = _feaxios.default.create(defaults); + var requestInterceptors = new InterceptorManager(); + var responseInterceptors = new InterceptorManager(); + var httpClient = { + interceptors: { + request: requestInterceptors, + response: responseInterceptors + }, + defaults: _objectSpread(_objectSpread({}, defaults), {}, { + adapter: function adapter(config) { + return instance.request(config); + } + }), + create: function create(config) { + return createFetchClient(_objectSpread(_objectSpread({}, this.defaults), config)); + }, + makeRequest: function makeRequest(config) { + var _this = this; + return new Promise(function (resolve, reject) { + var abortController = new AbortController(); + config.signal = abortController.signal; + if (config.cancelToken) { + config.cancelToken.promise.then(function () { + abortController.abort(); + reject(new Error('Request canceled')); + }); + } + var modifiedConfig = config; + if (requestInterceptors.handlers.length > 0) { + var chain = requestInterceptors.handlers.filter(function (interceptor) { + return interceptor !== null; + }).flatMap(function (interceptor) { + return [interceptor.fulfilled, interceptor.rejected]; + }); + for (var i = 0, len = chain.length; i < len; i += 2) { + var onFulfilled = chain[i]; + var onRejected = chain[i + 1]; + try { + if (onFulfilled) modifiedConfig = onFulfilled(modifiedConfig); + } catch (error) { + if (onRejected) onRejected === null || onRejected === void 0 || onRejected(error); + reject(error); + return; + } + } + } + var adapter = modifiedConfig.adapter || _this.defaults.adapter; + if (!adapter) { + throw new Error('No adapter available'); + } + var responsePromise = adapter(modifiedConfig).then(function (axiosResponse) { + var httpClientResponse = { + data: axiosResponse.data, + headers: axiosResponse.headers, + config: axiosResponse.config, + status: axiosResponse.status, + statusText: axiosResponse.statusText + }; + return httpClientResponse; + }); + if (responseInterceptors.handlers.length > 0) { + var _chain = responseInterceptors.handlers.filter(function (interceptor) { + return interceptor !== null; + }).flatMap(function (interceptor) { + return [interceptor.fulfilled, interceptor.rejected]; + }); + var _loop = function _loop(_i) { + responsePromise = responsePromise.then(function (response) { + var fulfilledInterceptor = _chain[_i]; + if (typeof fulfilledInterceptor === 'function') { + return fulfilledInterceptor(response); + } + return response; + }, function (error) { + var rejectedInterceptor = _chain[_i + 1]; + if (typeof rejectedInterceptor === 'function') { + return rejectedInterceptor(error); + } + throw error; + }).then(function (interceptedResponse) { + return interceptedResponse; + }); + }; + for (var _i = 0, _len = _chain.length; _i < _len; _i += 2) { + _loop(_i); + } + } + responsePromise.then(resolve).catch(reject); + }); + }, + get: function get(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'get' + })); + }, + delete: function _delete(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'delete' + })); + }, + head: function head(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'head' + })); + }, + options: function options(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'options' + })); + }, + post: function post(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'post', + data: data + })); + }, + put: function put(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'put', + data: data + })); + }, + patch: function patch(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'patch', + data: data + })); + }, + postForm: function postForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'post', + data: data + })); + }, + putForm: function putForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'put', + data: data + })); + }, + patchForm: function patchForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'patch', + data: data + })); + }, + CancelToken: _types.CancelToken, + isCancel: function isCancel(value) { + return value instanceof Error && value.message === 'Request canceled'; + } + }; + return httpClient; +} +var fetchClient = exports.fetchClient = createFetchClient(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/http-client/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/http-client/index.d.ts new file mode 100644 index 000000000..b6dea58cd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/http-client/index.d.ts @@ -0,0 +1,5 @@ +import { HttpClient, HttpClientRequestConfig } from "./types"; +declare let httpClient: HttpClient; +declare let create: (config?: HttpClientRequestConfig) => HttpClient; +export { httpClient, create }; +export * from "./types"; diff --git a/node_modules/@stellar/stellar-sdk/lib/http-client/index.js b/node_modules/@stellar/stellar-sdk/lib/http-client/index.js new file mode 100644 index 000000000..96d7a6f35 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/http-client/index.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + httpClient: true, + create: true +}; +exports.httpClient = exports.create = void 0; +var _types = require("./types"); +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _types[key]; + } + }); +}); +var httpClient; +var create; +if (true) { + var axiosModule = require('./axios-client'); + exports.httpClient = httpClient = axiosModule.axiosClient; + exports.create = create = axiosModule.create; +} else { + var fetchModule = require('./fetch-client'); + exports.httpClient = httpClient = fetchModule.fetchClient; + exports.create = create = fetchModule.create; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/http-client/types.d.ts b/node_modules/@stellar/stellar-sdk/lib/http-client/types.d.ts new file mode 100644 index 000000000..6aa38dddc --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/http-client/types.d.ts @@ -0,0 +1,70 @@ +export type HttpResponseHeaders = Record & { + 'set-cookie'?: string[]; +}; +export interface HttpClientDefaults extends Omit { + headers?: [string, string][] | Record | Headers | undefined; +} +export interface HttpClientResponse { + data: T; + headers: HttpResponseHeaders; + config: any; + status: number; + statusText: string; +} +export interface CancelToken { + promise: Promise; + throwIfRequested(): void; + reason?: string; +} +type HeadersInit = [string, string][] | Record | Headers; +export interface HttpClientRequestConfig { + url?: string; + method?: string; + baseURL?: string; + data?: D; + timeout?: number; + fetchOptions?: Record; + headers?: HeadersInit; + params?: Record; + maxContentLength?: number; + maxRedirects?: number; + cancelToken?: CancelToken; + adapter?: (config: HttpClientRequestConfig) => Promise; +} +export interface HttpClient { + get: (url: string, config?: HttpClientRequestConfig) => Promise>; + delete: (url: string, config?: HttpClientRequestConfig) => Promise>; + head: (url: string, config?: HttpClientRequestConfig) => Promise>; + options: (url: string, config?: HttpClientRequestConfig) => Promise>; + post: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + put: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + patch: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + postForm: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + putForm: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + patchForm: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + interceptors: { + request: InterceptorManager; + response: InterceptorManager; + }; + defaults: HttpClientDefaults; + CancelToken: typeof CancelToken; + isCancel: (value: any) => boolean; + makeRequest: (config: HttpClientRequestConfig) => Promise>; + create: (config?: HttpClientRequestConfig) => HttpClient; +} +export interface Interceptor { + fulfilled: (value: V) => V | Promise; + rejected?: (error: any) => any; +} +export interface InterceptorManager { + use(fulfilled: (value: V) => V | Promise, rejected?: (error: any) => any): number; + eject(id: number): void; + forEach(fn: (interceptor: Interceptor) => void): void; + handlers: Array | null>; +} +export declare class CancelToken { + promise: Promise; + reason?: string; + constructor(executor: (cancel: (reason?: string) => void) => void); +} +export {}; diff --git a/node_modules/@stellar/stellar-sdk/lib/http-client/types.js b/node_modules/@stellar/stellar-sdk/lib/http-client/types.js new file mode 100644 index 000000000..80b1012fb --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/http-client/types.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.CancelToken = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var CancelToken = exports.CancelToken = function () { + function CancelToken(executor) { + var _this = this; + _classCallCheck(this, CancelToken); + var resolvePromise; + this.promise = new Promise(function (resolve) { + resolvePromise = resolve; + }); + executor(function (reason) { + _this.reason = reason; + resolvePromise(); + }); + } + return _createClass(CancelToken, [{ + key: "throwIfRequested", + value: function throwIfRequested() { + if (this.reason) { + throw new Error(this.reason); + } + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/index.d.ts new file mode 100644 index 000000000..6ae366241 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/index.d.ts @@ -0,0 +1,32 @@ +export * from './errors'; +export { Config } from './config'; +export { Utils } from './utils'; +export * as StellarToml from './stellartoml'; +export * as Federation from './federation'; +export * as WebAuth from './webauth'; +export * as Friendbot from './friendbot'; +export * as Horizon from './horizon'; +/** + * Tools for interacting with the Soroban RPC server, such as `Server`, + * `assembleTransaction`, and the `Api` types. You can import these from the + * `/rpc` entrypoint, if your version of Node and your TypeScript configuration + * allow it: + * + * @example + * import { Server } from '@stellar/stellar-sdk/rpc'; + */ +export * as rpc from './rpc'; +/** + * Tools for interacting with smart contracts, such as `Client`, `Spec`, and + * `AssembledTransaction`. You can import these from the `/contract` + * entrypoint, if your version of Node and your TypeScript configuration allow + * it: + * + * @example + * import { Client } from '@stellar/stellar-sdk/contract'; + * @private + */ +export * as contract from './contract'; +export * from '@stellar/stellar-base'; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/index.js b/node_modules/@stellar/stellar-sdk/lib/index.js new file mode 100644 index 000000000..cbdb8649c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/index.js @@ -0,0 +1,80 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Config: true, + Utils: true, + StellarToml: true, + Federation: true, + WebAuth: true, + Friendbot: true, + Horizon: true, + rpc: true, + contract: true +}; +Object.defineProperty(exports, "Config", { + enumerable: true, + get: function get() { + return _config.Config; + } +}); +exports.StellarToml = exports.Horizon = exports.Friendbot = exports.Federation = void 0; +Object.defineProperty(exports, "Utils", { + enumerable: true, + get: function get() { + return _utils.Utils; + } +}); +exports.rpc = exports.default = exports.contract = exports.WebAuth = void 0; +var _errors = require("./errors"); +Object.keys(_errors).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _errors[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _errors[key]; + } + }); +}); +var _config = require("./config"); +var _utils = require("./utils"); +var _StellarToml = _interopRequireWildcard(require("./stellartoml")); +exports.StellarToml = _StellarToml; +var _Federation = _interopRequireWildcard(require("./federation")); +exports.Federation = _Federation; +var _WebAuth = _interopRequireWildcard(require("./webauth")); +exports.WebAuth = _WebAuth; +var _Friendbot = _interopRequireWildcard(require("./friendbot")); +exports.Friendbot = _Friendbot; +var _Horizon = _interopRequireWildcard(require("./horizon")); +exports.Horizon = _Horizon; +var _rpc = _interopRequireWildcard(require("./rpc")); +exports.rpc = _rpc; +var _contract = _interopRequireWildcard(require("./contract")); +exports.contract = _contract; +var _stellarBase = require("@stellar/stellar-base"); +Object.keys(_stellarBase).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _stellarBase[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _stellarBase[key]; + } + }); +}); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; +if (typeof global.__USE_AXIOS__ === 'undefined') { + global.__USE_AXIOS__ = true; +} +if (typeof global.__USE_EVENTSOURCE__ === 'undefined') { + global.__USE_EVENTSOURCE__ = false; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/browser.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/browser.d.ts new file mode 100644 index 000000000..bfdbd32a2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/browser.d.ts @@ -0,0 +1,6 @@ +import { httpClient } from "./http-client"; +export * from "./index"; +export * as StellarBase from "@stellar/stellar-base"; +export { httpClient }; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/browser.js b/node_modules/@stellar/stellar-sdk/lib/minimal/browser.js new file mode 100644 index 000000000..f21e953f0 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/browser.js @@ -0,0 +1,35 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + httpClient: true, + StellarBase: true +}; +exports.default = exports.StellarBase = void 0; +Object.defineProperty(exports, "httpClient", { + enumerable: true, + get: function get() { + return _httpClient.httpClient; + } +}); +var _httpClient = require("./http-client"); +var _index = require("./index"); +Object.keys(_index).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _index[key]; + } + }); +}); +var _StellarBase = _interopRequireWildcard(require("@stellar/stellar-base")); +exports.StellarBase = _StellarBase; +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/config.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/config.d.ts new file mode 100644 index 000000000..3daa1aa99 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/config.d.ts @@ -0,0 +1,64 @@ +/** + * Global config parameters. + */ +export interface Configuration { + /** + * Allow connecting to http servers. This must be set to false in production deployments! + * @default false + */ + allowHttp: boolean; + /** + * Allow a timeout. Allows user to avoid nasty lag due network issues. + * @default 0 + */ + timeout: number; +} +/** + * Global config class. + * + * @hideconstructor + * + * @example Usage in node + * import { Config } from '@stellar/stellar-sdk'; + * Config.setAllowHttp(true); + * Config.setTimeout(5000); + * + * @example Usage in the browser + * StellarSdk.Config.setAllowHttp(true); + * StellarSdk.Config.setTimeout(5000); + */ +declare class Config { + /** + * Sets `allowHttp` flag globally. When set to `true`, connections to insecure + * http protocol servers will be allowed. Must be set to `false` in + * production. + * @default false + * @static + */ + static setAllowHttp(value: boolean): void; + /** + * Sets `timeout` flag globally. When set to anything besides 0, the request + * will timeout after specified time (ms). + * @default 0 + * @static + */ + static setTimeout(value: number): void; + /** + * Returns the configured `allowHttp` flag. + * @static + * @returns {boolean} + */ + static isAllowHttp(): boolean; + /** + * Returns the configured `timeout` flag. + * @static + * @returns {number} + */ + static getTimeout(): number; + /** + * Sets all global config flags to default values. + * @static + */ + static setDefault(): void; +} +export { Config }; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/config.js b/node_modules/@stellar/stellar-sdk/lib/minimal/config.js new file mode 100644 index 000000000..e19e63d74 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/config.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Config = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var defaultConfig = { + allowHttp: false, + timeout: 0 +}; +var config = _objectSpread({}, defaultConfig); +var Config = exports.Config = function () { + function Config() { + _classCallCheck(this, Config); + } + return _createClass(Config, null, [{ + key: "setAllowHttp", + value: function setAllowHttp(value) { + config.allowHttp = value; + } + }, { + key: "setTimeout", + value: function setTimeout(value) { + config.timeout = value; + } + }, { + key: "isAllowHttp", + value: function isAllowHttp() { + return config.allowHttp; + } + }, { + key: "getTimeout", + value: function getTimeout() { + return config.timeout; + } + }, { + key: "setDefault", + value: function setDefault() { + config = _objectSpread({}, defaultConfig); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/assembled_transaction.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/assembled_transaction.d.ts new file mode 100644 index 000000000..c420d90f2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/assembled_transaction.d.ts @@ -0,0 +1,627 @@ +import { Account, SorobanDataBuilder, TransactionBuilder, authorizeEntry as stellarBaseAuthorizeEntry, xdr } from "@stellar/stellar-base"; +import type { AssembledTransactionOptions, ClientOptions, Tx, XDR_BASE64 } from "./types"; +import { Api } from "../rpc/api"; +import { SentTransaction } from "./sent_transaction"; +import { Spec } from "./spec"; +/** @module contract */ +/** + * The main workhorse of {@link Client}. This class is used to wrap a + * transaction-under-construction and provide high-level interfaces to the most + * common workflows, while still providing access to low-level stellar-sdk + * transaction manipulation. + * + * Most of the time, you will not construct an `AssembledTransaction` directly, + * but instead receive one as the return value of a `Client` method. If + * you're familiar with the libraries generated by soroban-cli's `contract + * bindings typescript` command, these also wraps `Client` and return + * `AssembledTransaction` instances. + * + * Let's look at examples of how to use `AssembledTransaction` for a variety of + * use-cases: + * + * #### 1. Simple read call + * + * Since these only require simulation, you can get the `result` of the call + * right after constructing your `AssembledTransaction`: + * + * ```ts + * const { result } = await AssembledTransaction.build({ + * method: 'myReadMethod', + * args: spec.funcArgsToScVals('myReadMethod', { + * args: 'for', + * my: 'method', + * ... + * }), + * contractId: 'C123…', + * networkPassphrase: '…', + * rpcUrl: 'https://…', + * publicKey: undefined, // irrelevant, for simulation-only read calls + * parseResultXdr: (result: xdr.ScVal) => + * spec.funcResToNative('myReadMethod', result), + * }) + * ``` + * + * While that looks pretty complicated, most of the time you will use this in + * conjunction with {@link Client}, which simplifies it to: + * + * ```ts + * const { result } = await client.myReadMethod({ + * args: 'for', + * my: 'method', + * ... + * }) + * ``` + * + * #### 2. Simple write call + * + * For write calls that will be simulated and then sent to the network without + * further manipulation, only one more step is needed: + * + * ```ts + * const assembledTx = await client.myWriteMethod({ + * args: 'for', + * my: 'method', + * ... + * }) + * const sentTx = await assembledTx.signAndSend() + * ``` + * + * Here we're assuming that you're using a {@link Client}, rather than + * constructing `AssembledTransaction`'s directly. + * + * Note that `sentTx`, the return value of `signAndSend`, is a + * {@link SentTransaction}. `SentTransaction` is similar to + * `AssembledTransaction`, but is missing many of the methods and fields that + * are only relevant while assembling a transaction. It also has a few extra + * methods and fields that are only relevant after the transaction has been + * sent to the network. + * + * Like `AssembledTransaction`, `SentTransaction` also has a `result` getter, + * which contains the parsed final return value of the contract call. Most of + * the time, you may only be interested in this, so rather than getting the + * whole `sentTx` you may just want to: + * + * ```ts + * const tx = await client.myWriteMethod({ args: 'for', my: 'method', ... }) + * const { result } = await tx.signAndSend() + * ``` + * + * #### 3. More fine-grained control over transaction construction + * + * If you need more control over the transaction before simulating it, you can + * set various {@link MethodOptions} when constructing your + * `AssembledTransaction`. With a {@link Client}, this is passed as a + * second object after the arguments (or the only object, if the method takes + * no arguments): + * + * ```ts + * const tx = await client.myWriteMethod( + * { + * args: 'for', + * my: 'method', + * ... + * }, { + * fee: '10000', // default: {@link BASE_FEE} + * simulate: false, + * timeoutInSeconds: 20, // default: {@link DEFAULT_TIMEOUT} + * } + * ) + * ``` + * + * Since we've skipped simulation, we can now edit the `raw` transaction and + * then manually call `simulate`: + * + * ```ts + * tx.raw.addMemo(Memo.text('Nice memo, friend!')) + * await tx.simulate() + * ``` + * + * If you need to inspect the simulation later, you can access it with + * `tx.simulation`. + * + * #### 4. Multi-auth workflows + * + * Soroban, and Stellar in general, allows multiple parties to sign a + * transaction. + * + * Let's consider an Atomic Swap contract. Alice wants to give 10 of her Token + * A tokens to Bob for 5 of his Token B tokens. + * + * ```ts + * const ALICE = 'G123...' + * const BOB = 'G456...' + * const TOKEN_A = 'C123…' + * const TOKEN_B = 'C456…' + * const AMOUNT_A = 10n + * const AMOUNT_B = 5n + * ``` + * + * Let's say Alice is also going to be the one signing the final transaction + * envelope, meaning she is the invoker. So your app, from Alice's browser, + * simulates the `swap` call: + * + * ```ts + * const tx = await swapClient.swap({ + * a: ALICE, + * b: BOB, + * token_a: TOKEN_A, + * token_b: TOKEN_B, + * amount_a: AMOUNT_A, + * amount_b: AMOUNT_B, + * }) + * ``` + * + * But your app can't `signAndSend` this right away, because Bob needs to sign + * it first. You can check this: + * + * ```ts + * const whoElseNeedsToSign = tx.needsNonInvokerSigningBy() + * ``` + * + * You can verify that `whoElseNeedsToSign` is an array of length `1`, + * containing only Bob's public key. + * + * Then, still on Alice's machine, you can serialize the + * transaction-under-assembly: + * + * ```ts + * const json = tx.toJSON() + * ``` + * + * And now you need to send it to Bob's browser. How you do this depends on + * your app. Maybe you send it to a server first, maybe you use WebSockets, or + * maybe you have Alice text the JSON blob to Bob and have him paste it into + * your app in his browser (note: this option might be error-prone 😄). + * + * Once you get the JSON blob into your app on Bob's machine, you can + * deserialize it: + * + * ```ts + * const tx = swapClient.txFromJSON(json) + * ``` + * + * Or, if you're using a client generated with `soroban contract bindings + * typescript`, this deserialization will look like: + * + * ```ts + * const tx = swapClient.fromJSON.swap(json) + * ``` + * + * Then you can have Bob sign it. What Bob will actually need to sign is some + * _auth entries_ within the transaction, not the transaction itself or the + * transaction envelope. Your app can verify that Bob has the correct wallet + * selected, then: + * + * ```ts + * await tx.signAuthEntries() + * ``` + * + * Under the hood, this uses `signAuthEntry`, which you either need to inject + * during initial construction of the `Client`/`AssembledTransaction`, + * or which you can pass directly to `signAuthEntries`. + * + * Now Bob can again serialize the transaction and send back to Alice, where + * she can finally call `signAndSend()`. + * + * To see an even more complicated example, where Alice swaps with Bob but the + * transaction is invoked by yet another party, check out + * [test-swap.js](../../test/e2e/src/test-swap.js). + * + * @memberof module:contract + */ +export declare class AssembledTransaction { + options: AssembledTransactionOptions; + /** + * The TransactionBuilder as constructed in `{@link + * AssembledTransaction}.build`. Feel free set `simulate: false` to modify + * this object before calling `tx.simulate()` manually. Example: + * + * ```ts + * const tx = await myContract.myMethod( + * { args: 'for', my: 'method', ... }, + * { simulate: false } + * ); + * tx.raw.addMemo(Memo.text('Nice memo, friend!')) + * await tx.simulate(); + * ``` + */ + raw?: TransactionBuilder; + /** + * The Transaction as it was built with `raw.build()` right before + * simulation. Once this is set, modifying `raw` will have no effect unless + * you call `tx.simulate()` again. + */ + built?: Tx; + /** + * The result of the transaction simulation. This is set after the first call + * to `simulate`. It is difficult to serialize and deserialize, so it is not + * included in the `toJSON` and `fromJSON` methods. See `simulationData` + * cached, serializable access to the data needed by AssembledTransaction + * logic. + */ + simulation?: Api.SimulateTransactionResponse; + /** + * Cached simulation result. This is set after the first call to + * {@link AssembledTransaction#simulationData}, and is used to facilitate + * serialization and deserialization of the AssembledTransaction. + * + * Most of the time, if you need this data, you can call + * `tx.simulation.result`. + * + * If you need access to this data after a transaction has been serialized + * and then deserialized, you can call `simulationData.result`. + */ + private simulationResult?; + /** + * Cached simulation transaction data. This is set after the first call to + * {@link AssembledTransaction#simulationData}, and is used to facilitate + * serialization and deserialization of the AssembledTransaction. + * + * Most of the time, if you need this data, you can call + * `simulation.transactionData`. + * + * If you need access to this data after a transaction has been serialized + * and then deserialized, you can call `simulationData.transactionData`. + */ + private simulationTransactionData?; + /** + * The Soroban server to use for all RPC calls. This is constructed from the + * `rpcUrl` in the options. + */ + private server; + /** + * The signed transaction. + */ + signed?: Tx; + /** + * A list of the most important errors that various AssembledTransaction + * methods can throw. Feel free to catch specific errors in your application + * logic. + */ + static Errors: { + ExpiredState: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + RestorationFailure: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NeedsMoreSignatures: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NoSignatureNeeded: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NoUnsignedNonInvokerAuthEntries: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NoSigner: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NotYetSimulated: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + FakeAccount: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + SimulationFailed: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + InternalWalletError: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + ExternalServiceError: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + InvalidClientRequest: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + UserRejected: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + }; + /** + * Serialize the AssembledTransaction to a JSON string. This is useful for + * saving the transaction to a database or sending it over the wire for + * multi-auth workflows. `fromJSON` can be used to deserialize the + * transaction. This only works with transactions that have been simulated. + */ + toJSON(): string; + static fromJSON(options: Omit, "args">, { tx, simulationResult, simulationTransactionData, }: { + tx: XDR_BASE64; + simulationResult: { + auth: XDR_BASE64[]; + retval: XDR_BASE64; + }; + simulationTransactionData: XDR_BASE64; + }): AssembledTransaction; + /** + * Serialize the AssembledTransaction to a base64-encoded XDR string. + */ + toXDR(): string; + /** + * Deserialize the AssembledTransaction from a base64-encoded XDR string. + */ + static fromXDR(options: Omit, "args" | "method" | "parseResultXdr">, encodedXDR: string, spec: Spec): AssembledTransaction; + private handleWalletError; + private constructor(); + /** + * Construct a new AssembledTransaction. This is the main way to create a new + * AssembledTransaction; the constructor is private. + * + * This is an asynchronous constructor for two reasons: + * + * 1. It needs to fetch the account from the network to get the current + * sequence number. + * 2. It needs to simulate the transaction to get the expected fee. + * + * If you don't want to simulate the transaction, you can set `simulate` to + * `false` in the options. + * + * If you need to create an operation other than `invokeHostFunction`, you + * can use {@link AssembledTransaction.buildWithOp} instead. + * + * @example + * const tx = await AssembledTransaction.build({ + * ..., + * simulate: false, + * }) + */ + static build(options: AssembledTransactionOptions): Promise>; + /** + * Construct a new AssembledTransaction, specifying an Operation other than + * `invokeHostFunction` (the default used by {@link AssembledTransaction.build}). + * + * Note: `AssembledTransaction` currently assumes these operations can be + * simulated. This is not true for classic operations; only for those used by + * Soroban Smart Contracts like `invokeHostFunction` and `createCustomContract`. + * + * @example + * const tx = await AssembledTransaction.buildWithOp( + * Operation.createCustomContract({ ... }); + * { + * ..., + * simulate: false, + * } + * ) + */ + static buildWithOp(operation: xdr.Operation, options: AssembledTransactionOptions): Promise>; + private static buildFootprintRestoreTransaction; + simulate: ({ restore }?: { + restore?: boolean; + }) => Promise; + get simulationData(): { + result: Api.SimulateHostFunctionResult; + transactionData: xdr.SorobanTransactionData; + }; + get result(): T; + private parseError; + /** + * Sign the transaction with the signTransaction function included previously. + * If you did not previously include one, you need to include one now. + */ + sign: ({ force, signTransaction, }?: { + /** + * If `true`, sign and send the transaction even if it is a read call + */ + force?: boolean; + /** + * You must provide this here if you did not provide one before + */ + signTransaction?: ClientOptions["signTransaction"]; + }) => Promise; + /** + * Sends the transaction to the network to return a `SentTransaction` that + * keeps track of all the attempts to fetch the transaction. + */ + send(): Promise>; + /** + * Sign the transaction with the `signTransaction` function included previously. + * If you did not previously include one, you need to include one now. + * After signing, this method will send the transaction to the network and + * return a `SentTransaction` that keeps track * of all the attempts to fetch the transaction. + */ + signAndSend: ({ force, signTransaction, }?: { + /** + * If `true`, sign and send the transaction even if it is a read call + */ + force?: boolean; + /** + * You must provide this here if you did not provide one before + */ + signTransaction?: ClientOptions["signTransaction"]; + }) => Promise>; + /** + * Get a list of accounts, other than the invoker of the simulation, that + * need to sign auth entries in this transaction. + * + * Soroban allows multiple people to sign a transaction. Someone needs to + * sign the final transaction envelope; this person/account is called the + * _invoker_, or _source_. Other accounts might need to sign individual auth + * entries in the transaction, if they're not also the invoker. + * + * This function returns a list of accounts that need to sign auth entries, + * assuming that the same invoker/source account will sign the final + * transaction envelope as signed the initial simulation. + * + * One at a time, for each public key in this array, you will need to + * serialize this transaction with `toJSON`, send to the owner of that key, + * deserialize the transaction with `txFromJson`, and call + * {@link AssembledTransaction#signAuthEntries}. Then re-serialize and send to + * the next account in this list. + */ + needsNonInvokerSigningBy: ({ includeAlreadySigned, }?: { + /** + * Whether or not to include auth entries that have already been signed. + * Default: false + */ + includeAlreadySigned?: boolean; + }) => string[]; + /** + * If {@link AssembledTransaction#needsNonInvokerSigningBy} returns a + * non-empty list, you can serialize the transaction with `toJSON`, send it to + * the owner of one of the public keys in the map, deserialize with + * `txFromJSON`, and call this method on their machine. Internally, this will + * use `signAuthEntry` function from connected `wallet` for each. + * + * Then, re-serialize the transaction and either send to the next + * `needsNonInvokerSigningBy` owner, or send it back to the original account + * who simulated the transaction so they can {@link AssembledTransaction#sign} + * the transaction envelope and {@link AssembledTransaction#send} it to the + * network. + * + * Sending to all `needsNonInvokerSigningBy` owners in parallel is not + * currently supported! + */ + signAuthEntries: ({ expiration, signAuthEntry, address, authorizeEntry, }?: { + /** + * When to set each auth entry to expire. Could be any number of blocks in + * the future. Can be supplied as a promise or a raw number. Default: + * about 8.3 minutes from now. + */ + expiration?: number | Promise; + /** + * Sign all auth entries for this account. Default: the account that + * constructed the transaction + */ + address?: string; + /** + * You must provide this here if you did not provide one before and you are not passing `authorizeEntry`. Default: the `signAuthEntry` function from the `Client` options. Must sign things as the given `publicKey`. + */ + signAuthEntry?: ClientOptions["signAuthEntry"]; + /** + * If you have a pro use-case and need to override the default `authorizeEntry` function, rather than using the one in @stellar/stellar-base, you can do that! Your function needs to take at least the first argument, `entry: xdr.SorobanAuthorizationEntry`, and return a `Promise`. + * + * Note that you if you pass this, then `signAuthEntry` will be ignored. + */ + authorizeEntry?: typeof stellarBaseAuthorizeEntry; + }) => Promise; + /** + * Whether this transaction is a read call. This is determined by the + * simulation result and the transaction data. If the transaction is a read + * call, it will not need to be signed and sent to the network. If this + * returns `false`, then you need to call `signAndSend` on this transaction. + */ + get isReadCall(): boolean; + /** + * Restores the footprint (resource ledger entries that can be read or written) + * of an expired transaction. + * + * The method will: + * 1. Build a new transaction aimed at restoring the necessary resources. + * 2. Sign this new transaction if a `signTransaction` handler is provided. + * 3. Send the signed transaction to the network. + * 4. Await and return the response from the network. + * + * Preconditions: + * - A `signTransaction` function must be provided during the Client initialization. + * - The provided `restorePreamble` should include a minimum resource fee and valid + * transaction data. + * + * @throws {Error} - Throws an error if no `signTransaction` function is provided during + * Client initialization. + * @throws {AssembledTransaction.Errors.RestoreFailure} - Throws a custom error if the + * restore transaction fails, providing the details of the failure. + */ + restoreFootprint( + /** + * The preamble object containing data required to + * build the restore transaction. + */ + restorePreamble: { + minResourceFee: string; + transactionData: SorobanDataBuilder; + }, + /** The account that is executing the footprint restore operation. If omitted, will use the account from the AssembledTransaction. */ + account?: Account): Promise; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/assembled_transaction.js b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/assembled_transaction.js new file mode 100644 index 000000000..aaeaac04e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/assembled_transaction.js @@ -0,0 +1,841 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AssembledTransaction = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _rpc = require("../rpc"); +var _api = require("../rpc/api"); +var _transaction = require("../rpc/transaction"); +var _rust_result = require("./rust_result"); +var _utils = require("./utils"); +var _types = require("./types"); +var _sent_transaction = require("./sent_transaction"); +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var AssembledTransaction = exports.AssembledTransaction = function () { + function AssembledTransaction(options) { + var _this = this, + _this$options$simulat, + _this$options$allowHt; + _classCallCheck(this, AssembledTransaction); + _defineProperty(this, "simulate", _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var _restore; + var _ref2, + restore, + account, + result, + _this$options$fee, + _this$options$args, + _this$options$timeout, + contract, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _ref2 = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, restore = _ref2.restore; + if (_this.built) { + _context.next = 5; + break; + } + if (_this.raw) { + _context.next = 4; + break; + } + throw new Error("Transaction has not yet been assembled; " + "call `AssembledTransaction.build` first."); + case 4: + _this.built = _this.raw.build(); + case 5: + restore = (_restore = restore) !== null && _restore !== void 0 ? _restore : _this.options.restore; + delete _this.simulationResult; + delete _this.simulationTransactionData; + _context.next = 10; + return _this.server.simulateTransaction(_this.built); + case 10: + _this.simulation = _context.sent; + if (!(restore && _api.Api.isSimulationRestore(_this.simulation))) { + _context.next = 25; + break; + } + _context.next = 14; + return (0, _utils.getAccount)(_this.options, _this.server); + case 14: + account = _context.sent; + _context.next = 17; + return _this.restoreFootprint(_this.simulation.restorePreamble, account); + case 17: + result = _context.sent; + if (!(result.status === _api.Api.GetTransactionStatus.SUCCESS)) { + _context.next = 24; + break; + } + contract = new _stellarBase.Contract(_this.options.contractId); + _this.raw = new _stellarBase.TransactionBuilder(account, { + fee: (_this$options$fee = _this.options.fee) !== null && _this$options$fee !== void 0 ? _this$options$fee : _stellarBase.BASE_FEE, + networkPassphrase: _this.options.networkPassphrase + }).addOperation(contract.call.apply(contract, [_this.options.method].concat(_toConsumableArray((_this$options$args = _this.options.args) !== null && _this$options$args !== void 0 ? _this$options$args : [])))).setTimeout((_this$options$timeout = _this.options.timeoutInSeconds) !== null && _this$options$timeout !== void 0 ? _this$options$timeout : _types.DEFAULT_TIMEOUT); + _context.next = 23; + return _this.simulate(); + case 23: + return _context.abrupt("return", _this); + case 24: + throw new AssembledTransaction.Errors.RestorationFailure("Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n".concat(JSON.stringify(result))); + case 25: + if (_api.Api.isSimulationSuccess(_this.simulation)) { + _this.built = (0, _transaction.assembleTransaction)(_this.built, _this.simulation).build(); + } + return _context.abrupt("return", _this); + case 27: + case "end": + return _context.stop(); + } + }, _callee); + }))); + _defineProperty(this, "sign", _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + var _this$options$timeout2; + var _ref4, + _ref4$force, + force, + _ref4$signTransaction, + signTransaction, + sigsNeeded, + timeoutInSeconds, + signOpts, + _yield$signTransactio, + signature, + error, + _args2 = arguments; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _ref4 = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref4$force = _ref4.force, force = _ref4$force === void 0 ? false : _ref4$force, _ref4$signTransaction = _ref4.signTransaction, signTransaction = _ref4$signTransaction === void 0 ? _this.options.signTransaction : _ref4$signTransaction; + if (_this.built) { + _context2.next = 3; + break; + } + throw new Error("Transaction has not yet been simulated"); + case 3: + if (!(!force && _this.isReadCall)) { + _context2.next = 5; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("This is a read call. It requires no signature or sending. " + "Use `force: true` to sign and send anyway."); + case 5: + if (signTransaction) { + _context2.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide a signTransaction function, either when calling " + "`signAndSend` or when initializing your Client"); + case 7: + sigsNeeded = _this.needsNonInvokerSigningBy().filter(function (id) { + return !id.startsWith('C'); + }); + if (!sigsNeeded.length) { + _context2.next = 10; + break; + } + throw new AssembledTransaction.Errors.NeedsMoreSignatures("Transaction requires signatures from ".concat(sigsNeeded, ". ") + "See `needsNonInvokerSigningBy` for details."); + case 10: + timeoutInSeconds = (_this$options$timeout2 = _this.options.timeoutInSeconds) !== null && _this$options$timeout2 !== void 0 ? _this$options$timeout2 : _types.DEFAULT_TIMEOUT; + _this.built = _stellarBase.TransactionBuilder.cloneFrom(_this.built, { + fee: _this.built.fee, + timebounds: undefined, + sorobanData: _this.simulationData.transactionData + }).setTimeout(timeoutInSeconds).build(); + signOpts = { + networkPassphrase: _this.options.networkPassphrase + }; + if (_this.options.address) signOpts.address = _this.options.address; + if (_this.options.submit !== undefined) signOpts.submit = _this.options.submit; + if (_this.options.submitUrl) signOpts.submitUrl = _this.options.submitUrl; + _context2.next = 18; + return signTransaction(_this.built.toXDR(), signOpts); + case 18: + _yield$signTransactio = _context2.sent; + signature = _yield$signTransactio.signedTxXdr; + error = _yield$signTransactio.error; + _this.handleWalletError(error); + _this.signed = _stellarBase.TransactionBuilder.fromXDR(signature, _this.options.networkPassphrase); + case 23: + case "end": + return _context2.stop(); + } + }, _callee2); + }))); + _defineProperty(this, "signAndSend", _asyncToGenerator(_regeneratorRuntime().mark(function _callee3() { + var _ref6, + _ref6$force, + force, + _ref6$signTransaction, + signTransaction, + originalSubmit, + _args3 = arguments; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _ref6 = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : {}, _ref6$force = _ref6.force, force = _ref6$force === void 0 ? false : _ref6$force, _ref6$signTransaction = _ref6.signTransaction, signTransaction = _ref6$signTransaction === void 0 ? _this.options.signTransaction : _ref6$signTransaction; + if (_this.signed) { + _context3.next = 10; + break; + } + originalSubmit = _this.options.submit; + if (_this.options.submit) { + _this.options.submit = false; + } + _context3.prev = 4; + _context3.next = 7; + return _this.sign({ + force: force, + signTransaction: signTransaction + }); + case 7: + _context3.prev = 7; + _this.options.submit = originalSubmit; + return _context3.finish(7); + case 10: + return _context3.abrupt("return", _this.send()); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3, null, [[4,, 7, 10]]); + }))); + _defineProperty(this, "needsNonInvokerSigningBy", function () { + var _rawInvokeHostFunctio; + var _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref7$includeAlreadyS = _ref7.includeAlreadySigned, + includeAlreadySigned = _ref7$includeAlreadyS === void 0 ? false : _ref7$includeAlreadyS; + if (!_this.built) { + throw new Error("Transaction has not yet been simulated"); + } + if (!("operations" in _this.built)) { + throw new Error("Unexpected Transaction type; no operations: ".concat(JSON.stringify(_this.built))); + } + var rawInvokeHostFunctionOp = _this.built.operations[0]; + return _toConsumableArray(new Set(((_rawInvokeHostFunctio = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio !== void 0 ? _rawInvokeHostFunctio : []).filter(function (entry) { + return entry.credentials().switch() === _stellarBase.xdr.SorobanCredentialsType.sorobanCredentialsAddress() && (includeAlreadySigned || entry.credentials().address().signature().switch().name === "scvVoid"); + }).map(function (entry) { + return _stellarBase.Address.fromScAddress(entry.credentials().address().address()).toString(); + }))); + }); + _defineProperty(this, "signAuthEntries", _asyncToGenerator(_regeneratorRuntime().mark(function _callee6() { + var _rawInvokeHostFunctio2; + var _ref9, + _ref9$expiration, + expiration, + _ref9$signAuthEntry, + signAuthEntry, + _ref9$address, + address, + _ref9$authorizeEntry, + authorizeEntry, + needsNonInvokerSigningBy, + rawInvokeHostFunctionOp, + authEntries, + _iterator, + _step, + _loop, + _ret, + _args7 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _ref9 = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {}, _ref9$expiration = _ref9.expiration, expiration = _ref9$expiration === void 0 ? _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this.server.getLatestLedger(); + case 2: + _context4.t0 = _context4.sent.sequence; + return _context4.abrupt("return", _context4.t0 + 100); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + }))() : _ref9$expiration, _ref9$signAuthEntry = _ref9.signAuthEntry, signAuthEntry = _ref9$signAuthEntry === void 0 ? _this.options.signAuthEntry : _ref9$signAuthEntry, _ref9$address = _ref9.address, address = _ref9$address === void 0 ? _this.options.publicKey : _ref9$address, _ref9$authorizeEntry = _ref9.authorizeEntry, authorizeEntry = _ref9$authorizeEntry === void 0 ? _stellarBase.authorizeEntry : _ref9$authorizeEntry; + if (_this.built) { + _context7.next = 3; + break; + } + throw new Error("Transaction has not yet been assembled or simulated"); + case 3: + if (!(authorizeEntry === _stellarBase.authorizeEntry)) { + _context7.next = 11; + break; + } + needsNonInvokerSigningBy = _this.needsNonInvokerSigningBy(); + if (!(needsNonInvokerSigningBy.length === 0)) { + _context7.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?"); + case 7: + if (!(needsNonInvokerSigningBy.indexOf(address !== null && address !== void 0 ? address : "") === -1)) { + _context7.next = 9; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("No auth entries for public key \"".concat(address, "\"")); + case 9: + if (signAuthEntry) { + _context7.next = 11; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`"); + case 11: + rawInvokeHostFunctionOp = _this.built.operations[0]; + authEntries = (_rawInvokeHostFunctio2 = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio2 !== void 0 ? _rawInvokeHostFunctio2 : []; + _iterator = _createForOfIteratorHelper(authEntries.entries()); + _context7.prev = 14; + _loop = _regeneratorRuntime().mark(function _loop() { + var _step$value, i, entry, credentials, authEntryAddress, sign; + return _regeneratorRuntime().wrap(function _loop$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _step$value = _slicedToArray(_step.value, 2), i = _step$value[0], entry = _step$value[1]; + credentials = _stellarBase.xdr.SorobanCredentials.fromXDR(entry.credentials().toXDR()); + if (!(credentials.switch() !== _stellarBase.xdr.SorobanCredentialsType.sorobanCredentialsAddress())) { + _context6.next = 4; + break; + } + return _context6.abrupt("return", 0); + case 4: + authEntryAddress = _stellarBase.Address.fromScAddress(credentials.address().address()).toString(); + if (!(authEntryAddress !== address)) { + _context6.next = 7; + break; + } + return _context6.abrupt("return", 0); + case 7: + sign = signAuthEntry !== null && signAuthEntry !== void 0 ? signAuthEntry : Promise.resolve; + _context6.t0 = authorizeEntry; + _context6.t1 = entry; + _context6.t2 = function () { + var _ref11 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(preimage) { + var _yield$sign, signedAuthEntry, error; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return sign(preimage.toXDR("base64"), { + address: address + }); + case 2: + _yield$sign = _context5.sent; + signedAuthEntry = _yield$sign.signedAuthEntry; + error = _yield$sign.error; + _this.handleWalletError(error); + return _context5.abrupt("return", Buffer.from(signedAuthEntry, "base64")); + case 7: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x) { + return _ref11.apply(this, arguments); + }; + }(); + _context6.next = 13; + return expiration; + case 13: + _context6.t3 = _context6.sent; + _context6.t4 = _this.options.networkPassphrase; + _context6.next = 17; + return (0, _context6.t0)(_context6.t1, _context6.t2, _context6.t3, _context6.t4); + case 17: + authEntries[i] = _context6.sent; + case 18: + case "end": + return _context6.stop(); + } + }, _loop); + }); + _iterator.s(); + case 17: + if ((_step = _iterator.n()).done) { + _context7.next = 24; + break; + } + return _context7.delegateYield(_loop(), "t0", 19); + case 19: + _ret = _context7.t0; + if (!(_ret === 0)) { + _context7.next = 22; + break; + } + return _context7.abrupt("continue", 22); + case 22: + _context7.next = 17; + break; + case 24: + _context7.next = 29; + break; + case 26: + _context7.prev = 26; + _context7.t1 = _context7["catch"](14); + _iterator.e(_context7.t1); + case 29: + _context7.prev = 29; + _iterator.f(); + return _context7.finish(29); + case 32: + case "end": + return _context7.stop(); + } + }, _callee6, null, [[14, 26, 29, 32]]); + }))); + this.options = options; + this.options.simulate = (_this$options$simulat = this.options.simulate) !== null && _this$options$simulat !== void 0 ? _this$options$simulat : true; + this.server = new _rpc.Server(this.options.rpcUrl, { + allowHttp: (_this$options$allowHt = this.options.allowHttp) !== null && _this$options$allowHt !== void 0 ? _this$options$allowHt : false + }); + } + return _createClass(AssembledTransaction, [{ + key: "toJSON", + value: function toJSON() { + var _this$built; + return JSON.stringify({ + method: this.options.method, + tx: (_this$built = this.built) === null || _this$built === void 0 ? void 0 : _this$built.toXDR(), + simulationResult: { + auth: this.simulationData.result.auth.map(function (a) { + return a.toXDR("base64"); + }), + retval: this.simulationData.result.retval.toXDR("base64") + }, + simulationTransactionData: this.simulationData.transactionData.toXDR("base64") + }); + } + }, { + key: "toXDR", + value: function toXDR() { + var _this$built2; + if (!this.built) throw new Error("Transaction has not yet been simulated; " + "call `AssembledTransaction.simulate` first."); + return (_this$built2 = this.built) === null || _this$built2 === void 0 ? void 0 : _this$built2.toEnvelope().toXDR('base64'); + } + }, { + key: "handleWalletError", + value: function handleWalletError(error) { + if (!error) return; + var message = error.message, + code = error.code; + var fullMessage = "".concat(message).concat(error.ext ? " (".concat(error.ext.join(', '), ")") : ''); + switch (code) { + case -1: + throw new AssembledTransaction.Errors.InternalWalletError(fullMessage); + case -2: + throw new AssembledTransaction.Errors.ExternalServiceError(fullMessage); + case -3: + throw new AssembledTransaction.Errors.InvalidClientRequest(fullMessage); + case -4: + throw new AssembledTransaction.Errors.UserRejected(fullMessage); + default: + throw new Error("Unhandled error: ".concat(fullMessage)); + } + } + }, { + key: "simulationData", + get: function get() { + var _simulation$result; + if (this.simulationResult && this.simulationTransactionData) { + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + var simulation = this.simulation; + if (!simulation) { + throw new AssembledTransaction.Errors.NotYetSimulated("Transaction has not yet been simulated"); + } + if (_api.Api.isSimulationError(simulation)) { + throw new AssembledTransaction.Errors.SimulationFailed("Transaction simulation failed: \"".concat(simulation.error, "\"")); + } + if (_api.Api.isSimulationRestore(simulation)) { + throw new AssembledTransaction.Errors.ExpiredState("You need to restore some contract state before you can invoke this method.\n" + 'You can set `restore` to true in the method options in order to ' + 'automatically restore the contract state when needed.'); + } + this.simulationResult = (_simulation$result = simulation.result) !== null && _simulation$result !== void 0 ? _simulation$result : { + auth: [], + retval: _stellarBase.xdr.ScVal.scvVoid() + }; + this.simulationTransactionData = simulation.transactionData.build(); + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + }, { + key: "result", + get: function get() { + try { + if (!this.simulationData.result) { + throw new Error("No simulation result!"); + } + return this.options.parseResultXdr(this.simulationData.result.retval); + } catch (e) { + if (!(0, _utils.implementsToString)(e)) throw e; + var err = this.parseError(e.toString()); + if (err) return err; + throw e; + } + } + }, { + key: "parseError", + value: function parseError(errorMessage) { + if (!this.options.errorTypes) return undefined; + var match = errorMessage.match(_utils.contractErrorPattern); + if (!match) return undefined; + var i = parseInt(match[1], 10); + var err = this.options.errorTypes[i]; + if (!err) return undefined; + return new _rust_result.Err(err); + } + }, { + key: "send", + value: (function () { + var _send = _asyncToGenerator(_regeneratorRuntime().mark(function _callee7() { + var sent; + return _regeneratorRuntime().wrap(function _callee7$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (this.signed) { + _context8.next = 2; + break; + } + throw new Error("The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead."); + case 2: + _context8.next = 4; + return _sent_transaction.SentTransaction.init(this); + case 4: + sent = _context8.sent; + return _context8.abrupt("return", sent); + case 6: + case "end": + return _context8.stop(); + } + }, _callee7, this); + })); + function send() { + return _send.apply(this, arguments); + } + return send; + }()) + }, { + key: "isReadCall", + get: function get() { + var authsCount = this.simulationData.result.auth.length; + var writeLength = this.simulationData.transactionData.resources().footprint().readWrite().length; + return authsCount === 0 && writeLength === 0; + } + }, { + key: "restoreFootprint", + value: (function () { + var _restoreFootprint = _asyncToGenerator(_regeneratorRuntime().mark(function _callee8(restorePreamble, account) { + var _account; + var restoreTx, sentTransaction; + return _regeneratorRuntime().wrap(function _callee8$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + if (this.options.signTransaction) { + _context9.next = 2; + break; + } + throw new Error("For automatic restore to work you must provide a signTransaction function when initializing your Client"); + case 2: + if (!((_account = account) !== null && _account !== void 0)) { + _context9.next = 6; + break; + } + _context9.t0 = _account; + _context9.next = 9; + break; + case 6: + _context9.next = 8; + return (0, _utils.getAccount)(this.options, this.server); + case 8: + _context9.t0 = _context9.sent; + case 9: + account = _context9.t0; + _context9.next = 12; + return AssembledTransaction.buildFootprintRestoreTransaction(_objectSpread({}, this.options), restorePreamble.transactionData, account, restorePreamble.minResourceFee); + case 12: + restoreTx = _context9.sent; + _context9.next = 15; + return restoreTx.signAndSend(); + case 15: + sentTransaction = _context9.sent; + if (sentTransaction.getTransactionResponse) { + _context9.next = 18; + break; + } + throw new AssembledTransaction.Errors.RestorationFailure("The attempt at automatic restore failed. \n".concat(JSON.stringify(sentTransaction))); + case 18: + return _context9.abrupt("return", sentTransaction.getTransactionResponse); + case 19: + case "end": + return _context9.stop(); + } + }, _callee8, this); + })); + function restoreFootprint(_x2, _x3) { + return _restoreFootprint.apply(this, arguments); + } + return restoreFootprint; + }()) + }], [{ + key: "fromJSON", + value: function fromJSON(options, _ref12) { + var tx = _ref12.tx, + simulationResult = _ref12.simulationResult, + simulationTransactionData = _ref12.simulationTransactionData; + var txn = new AssembledTransaction(options); + txn.built = _stellarBase.TransactionBuilder.fromXDR(tx, options.networkPassphrase); + txn.simulationResult = { + auth: simulationResult.auth.map(function (a) { + return _stellarBase.xdr.SorobanAuthorizationEntry.fromXDR(a, "base64"); + }), + retval: _stellarBase.xdr.ScVal.fromXDR(simulationResult.retval, "base64") + }; + txn.simulationTransactionData = _stellarBase.xdr.SorobanTransactionData.fromXDR(simulationTransactionData, "base64"); + return txn; + } + }, { + key: "fromXDR", + value: function fromXDR(options, encodedXDR, spec) { + var _operation$func; + var envelope = _stellarBase.xdr.TransactionEnvelope.fromXDR(encodedXDR, "base64"); + var built = _stellarBase.TransactionBuilder.fromXDR(envelope, options.networkPassphrase); + var operation = built.operations[0]; + if (!(operation !== null && operation !== void 0 && (_operation$func = operation.func) !== null && _operation$func !== void 0 && _operation$func.value) || typeof operation.func.value !== 'function') { + throw new Error("Could not extract the method from the transaction envelope."); + } + var invokeContractArgs = operation.func.value(); + if (!(invokeContractArgs !== null && invokeContractArgs !== void 0 && invokeContractArgs.functionName)) { + throw new Error("Could not extract the method name from the transaction envelope."); + } + var method = invokeContractArgs.functionName().toString('utf-8'); + var txn = new AssembledTransaction(_objectSpread(_objectSpread({}, options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + txn.built = built; + return txn; + } + }, { + key: "build", + value: function build(options) { + var _options$args; + var contract = new _stellarBase.Contract(options.contractId); + return AssembledTransaction.buildWithOp(contract.call.apply(contract, [options.method].concat(_toConsumableArray((_options$args = options.args) !== null && _options$args !== void 0 ? _options$args : []))), options); + } + }, { + key: "buildWithOp", + value: (function () { + var _buildWithOp = _asyncToGenerator(_regeneratorRuntime().mark(function _callee9(operation, options) { + var _options$fee, _options$timeoutInSec; + var tx, account; + return _regeneratorRuntime().wrap(function _callee9$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + tx = new AssembledTransaction(options); + _context10.next = 3; + return (0, _utils.getAccount)(options, tx.server); + case 3: + account = _context10.sent; + tx.raw = new _stellarBase.TransactionBuilder(account, { + fee: (_options$fee = options.fee) !== null && _options$fee !== void 0 ? _options$fee : _stellarBase.BASE_FEE, + networkPassphrase: options.networkPassphrase + }).setTimeout((_options$timeoutInSec = options.timeoutInSeconds) !== null && _options$timeoutInSec !== void 0 ? _options$timeoutInSec : _types.DEFAULT_TIMEOUT).addOperation(operation); + if (!options.simulate) { + _context10.next = 8; + break; + } + _context10.next = 8; + return tx.simulate(); + case 8: + return _context10.abrupt("return", tx); + case 9: + case "end": + return _context10.stop(); + } + }, _callee9); + })); + function buildWithOp(_x4, _x5) { + return _buildWithOp.apply(this, arguments); + } + return buildWithOp; + }()) + }, { + key: "buildFootprintRestoreTransaction", + value: function () { + var _buildFootprintRestoreTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee10(options, sorobanData, account, fee) { + var _options$timeoutInSec2; + var tx; + return _regeneratorRuntime().wrap(function _callee10$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + tx = new AssembledTransaction(options); + tx.raw = new _stellarBase.TransactionBuilder(account, { + fee: fee, + networkPassphrase: options.networkPassphrase + }).setSorobanData(sorobanData instanceof _stellarBase.SorobanDataBuilder ? sorobanData.build() : sorobanData).addOperation(_stellarBase.Operation.restoreFootprint({})).setTimeout((_options$timeoutInSec2 = options.timeoutInSeconds) !== null && _options$timeoutInSec2 !== void 0 ? _options$timeoutInSec2 : _types.DEFAULT_TIMEOUT); + _context11.next = 4; + return tx.simulate({ + restore: false + }); + case 4: + return _context11.abrupt("return", tx); + case 5: + case "end": + return _context11.stop(); + } + }, _callee10); + })); + function buildFootprintRestoreTransaction(_x6, _x7, _x8, _x9) { + return _buildFootprintRestoreTransaction.apply(this, arguments); + } + return buildFootprintRestoreTransaction; + }() + }]); +}(); +_defineProperty(AssembledTransaction, "Errors", { + ExpiredState: function (_Error) { + function ExpiredStateError() { + _classCallCheck(this, ExpiredStateError); + return _callSuper(this, ExpiredStateError, arguments); + } + _inherits(ExpiredStateError, _Error); + return _createClass(ExpiredStateError); + }(_wrapNativeSuper(Error)), + RestorationFailure: function (_Error2) { + function RestoreFailureError() { + _classCallCheck(this, RestoreFailureError); + return _callSuper(this, RestoreFailureError, arguments); + } + _inherits(RestoreFailureError, _Error2); + return _createClass(RestoreFailureError); + }(_wrapNativeSuper(Error)), + NeedsMoreSignatures: function (_Error3) { + function NeedsMoreSignaturesError() { + _classCallCheck(this, NeedsMoreSignaturesError); + return _callSuper(this, NeedsMoreSignaturesError, arguments); + } + _inherits(NeedsMoreSignaturesError, _Error3); + return _createClass(NeedsMoreSignaturesError); + }(_wrapNativeSuper(Error)), + NoSignatureNeeded: function (_Error4) { + function NoSignatureNeededError() { + _classCallCheck(this, NoSignatureNeededError); + return _callSuper(this, NoSignatureNeededError, arguments); + } + _inherits(NoSignatureNeededError, _Error4); + return _createClass(NoSignatureNeededError); + }(_wrapNativeSuper(Error)), + NoUnsignedNonInvokerAuthEntries: function (_Error5) { + function NoUnsignedNonInvokerAuthEntriesError() { + _classCallCheck(this, NoUnsignedNonInvokerAuthEntriesError); + return _callSuper(this, NoUnsignedNonInvokerAuthEntriesError, arguments); + } + _inherits(NoUnsignedNonInvokerAuthEntriesError, _Error5); + return _createClass(NoUnsignedNonInvokerAuthEntriesError); + }(_wrapNativeSuper(Error)), + NoSigner: function (_Error6) { + function NoSignerError() { + _classCallCheck(this, NoSignerError); + return _callSuper(this, NoSignerError, arguments); + } + _inherits(NoSignerError, _Error6); + return _createClass(NoSignerError); + }(_wrapNativeSuper(Error)), + NotYetSimulated: function (_Error7) { + function NotYetSimulatedError() { + _classCallCheck(this, NotYetSimulatedError); + return _callSuper(this, NotYetSimulatedError, arguments); + } + _inherits(NotYetSimulatedError, _Error7); + return _createClass(NotYetSimulatedError); + }(_wrapNativeSuper(Error)), + FakeAccount: function (_Error8) { + function FakeAccountError() { + _classCallCheck(this, FakeAccountError); + return _callSuper(this, FakeAccountError, arguments); + } + _inherits(FakeAccountError, _Error8); + return _createClass(FakeAccountError); + }(_wrapNativeSuper(Error)), + SimulationFailed: function (_Error9) { + function SimulationFailedError() { + _classCallCheck(this, SimulationFailedError); + return _callSuper(this, SimulationFailedError, arguments); + } + _inherits(SimulationFailedError, _Error9); + return _createClass(SimulationFailedError); + }(_wrapNativeSuper(Error)), + InternalWalletError: function (_Error10) { + function InternalWalletError() { + _classCallCheck(this, InternalWalletError); + return _callSuper(this, InternalWalletError, arguments); + } + _inherits(InternalWalletError, _Error10); + return _createClass(InternalWalletError); + }(_wrapNativeSuper(Error)), + ExternalServiceError: function (_Error11) { + function ExternalServiceError() { + _classCallCheck(this, ExternalServiceError); + return _callSuper(this, ExternalServiceError, arguments); + } + _inherits(ExternalServiceError, _Error11); + return _createClass(ExternalServiceError); + }(_wrapNativeSuper(Error)), + InvalidClientRequest: function (_Error12) { + function InvalidClientRequestError() { + _classCallCheck(this, InvalidClientRequestError); + return _callSuper(this, InvalidClientRequestError, arguments); + } + _inherits(InvalidClientRequestError, _Error12); + return _createClass(InvalidClientRequestError); + }(_wrapNativeSuper(Error)), + UserRejected: function (_Error13) { + function UserRejectedError() { + _classCallCheck(this, UserRejectedError); + return _callSuper(this, UserRejectedError, arguments); + } + _inherits(UserRejectedError, _Error13); + return _createClass(UserRejectedError); + }(_wrapNativeSuper(Error)) +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/basic_node_signer.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/basic_node_signer.d.ts new file mode 100644 index 000000000..b82cc36f3 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/basic_node_signer.d.ts @@ -0,0 +1,18 @@ +import { Keypair } from "@stellar/stellar-base"; +import { SignAuthEntry, SignTransaction } from "./types"; +/** + * For use with {@link Client} and {@link module:contract.AssembledTransaction}. + * Implements `signTransaction` and `signAuthEntry` with signatures expected by + * those classes. This is useful for testing and maybe some simple Node + * applications. Feel free to use this as a starting point for your own + * Wallet/TransactionSigner implementation. + * + * @memberof module:contract + * + * @param {Keypair} keypair {@link Keypair} to use to sign the transaction or auth entry + * @param {string} networkPassphrase passphrase of network to sign for + */ +export declare const basicNodeSigner: (keypair: Keypair, networkPassphrase: string) => { + signTransaction: SignTransaction; + signAuthEntry: SignAuthEntry; +}; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/basic_node_signer.js b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/basic_node_signer.js new file mode 100644 index 000000000..b91d3149a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/basic_node_signer.js @@ -0,0 +1,60 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.basicNodeSigner = void 0; +var _stellarBase = require("@stellar/stellar-base"); +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +var basicNodeSigner = exports.basicNodeSigner = function basicNodeSigner(keypair, networkPassphrase) { + return { + signTransaction: function () { + var _signTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(xdr, opts) { + var t; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + t = _stellarBase.TransactionBuilder.fromXDR(xdr, (opts === null || opts === void 0 ? void 0 : opts.networkPassphrase) || networkPassphrase); + t.sign(keypair); + return _context.abrupt("return", { + signedTxXdr: t.toXDR(), + signerAddress: keypair.publicKey() + }); + case 3: + case "end": + return _context.stop(); + } + }, _callee); + })); + function signTransaction(_x, _x2) { + return _signTransaction.apply(this, arguments); + } + return signTransaction; + }(), + signAuthEntry: function () { + var _signAuthEntry = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(authEntry) { + var signedAuthEntry; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + signedAuthEntry = keypair.sign((0, _stellarBase.hash)(Buffer.from(authEntry, "base64"))).toString("base64"); + return _context2.abrupt("return", { + signedAuthEntry: signedAuthEntry, + signerAddress: keypair.publicKey() + }); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function signAuthEntry(_x3) { + return _signAuthEntry.apply(this, arguments); + } + return signAuthEntry; + }() + }; +}; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/client.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/client.d.ts new file mode 100644 index 000000000..c41fb7d25 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/client.d.ts @@ -0,0 +1,64 @@ +import { Spec } from "./spec"; +import { AssembledTransaction } from "./assembled_transaction"; +import type { ClientOptions, MethodOptions } from "./types"; +/** + * Generate a class from the contract spec that where each contract method + * gets included with an identical name. + * + * Each method returns an {@link module:contract.AssembledTransaction | AssembledTransaction} that can + * be used to modify, simulate, decode results, and possibly sign, & submit the + * transaction. + * + * @memberof module:contract + * + * @class + * @param {module:contract.Spec} spec {@link Spec} to construct a Client for + * @param {ClientOptions} options see {@link ClientOptions} + */ +export declare class Client { + readonly spec: Spec; + readonly options: ClientOptions; + static deploy( + /** Constructor/Initialization Args for the contract's `__constructor` method */ + args: Record | null, + /** Options for initalizing a Client as well as for calling a method, with extras specific to deploying. */ + options: MethodOptions & Omit & { + /** The hash of the Wasm blob, which must already be installed on-chain. */ + wasmHash: Buffer | string; + /** Salt used to generate the contract's ID. Passed through to {@link Operation.createCustomContract}. Default: random. */ + salt?: Buffer | Uint8Array; + /** The format used to decode `wasmHash`, if it's provided as a string. */ + format?: "hex" | "base64"; + }): Promise>; + constructor(spec: Spec, options: ClientOptions); + /** + * Generates a Client instance from the provided ClientOptions and the contract's wasm hash. + * The wasmHash can be provided in either hex or base64 format. + * + * @param {Buffer | string} wasmHash The hash of the contract's wasm binary, in either hex or base64 format. + * @param {ClientOptions} options The ClientOptions object containing the necessary configuration, including the rpcUrl. + * @param {('hex' | 'base64')} [format='hex'] The format of the provided wasmHash, either "hex" or "base64". Defaults to "hex". + * @returns {Promise} A Promise that resolves to a Client instance. + * @throws {TypeError} If the provided options object does not contain an rpcUrl. + */ + static fromWasmHash(wasmHash: Buffer | string, options: ClientOptions, format?: "hex" | "base64"): Promise; + /** + * Generates a Client instance from the provided ClientOptions and the contract's wasm binary. + * + * @param {Buffer} wasm The contract's wasm binary as a Buffer. + * @param {ClientOptions} options The ClientOptions object containing the necessary configuration. + * @returns {Promise} A Promise that resolves to a Client instance. + * @throws {Error} If the contract spec cannot be obtained from the provided wasm binary. + */ + static fromWasm(wasm: Buffer, options: ClientOptions): Promise; + /** + * Generates a Client instance from the provided ClientOptions, which must include the contractId and rpcUrl. + * + * @param {ClientOptions} options The ClientOptions object containing the necessary configuration, including the contractId and rpcUrl. + * @returns {Promise} A Promise that resolves to a Client instance. + * @throws {TypeError} If the provided options object does not contain both rpcUrl and contractId. + */ + static from(options: ClientOptions): Promise; + txFromJSON: (json: string) => AssembledTransaction; + txFromXDR: (xdrBase64: string) => AssembledTransaction; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/client.js b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/client.js new file mode 100644 index 000000000..4caa08ec6 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/client.js @@ -0,0 +1,291 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Client = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _spec = require("./spec"); +var _rpc = require("../rpc"); +var _assembled_transaction = require("./assembled_transaction"); +var _utils = require("./utils"); +var _excluded = ["method"], + _excluded2 = ["wasmHash", "salt", "format", "fee", "timeoutInSeconds", "simulate"]; +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } +function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +var CONSTRUCTOR_FUNC = "__constructor"; +function specFromWasm(_x) { + return _specFromWasm.apply(this, arguments); +} +function _specFromWasm() { + _specFromWasm = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(wasm) { + var wasmModule, xdrSections, bufferSection, specEntryArray, spec; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return WebAssembly.compile(wasm); + case 2: + wasmModule = _context5.sent; + xdrSections = WebAssembly.Module.customSections(wasmModule, "contractspecv0"); + if (!(xdrSections.length === 0)) { + _context5.next = 6; + break; + } + throw new Error("Could not obtain contract spec from wasm"); + case 6: + bufferSection = Buffer.from(xdrSections[0]); + specEntryArray = (0, _utils.processSpecEntryStream)(bufferSection); + spec = new _spec.Spec(specEntryArray); + return _context5.abrupt("return", spec); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _specFromWasm.apply(this, arguments); +} +function specFromWasmHash(_x2, _x3) { + return _specFromWasmHash.apply(this, arguments); +} +function _specFromWasmHash() { + _specFromWasmHash = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + format = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context6.next = 3; + break; + } + throw new TypeError("options must contain rpcUrl"); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new _rpc.Server(rpcUrl, serverOpts); + _context6.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context6.sent; + return _context6.abrupt("return", specFromWasm(wasm)); + case 10: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _specFromWasmHash.apply(this, arguments); +} +var Client = exports.Client = function () { + function Client(spec, options) { + var _this = this; + _classCallCheck(this, Client); + _defineProperty(this, "txFromJSON", function (json) { + var _JSON$parse = JSON.parse(json), + method = _JSON$parse.method, + tx = _objectWithoutProperties(_JSON$parse, _excluded); + return _assembled_transaction.AssembledTransaction.fromJSON(_objectSpread(_objectSpread({}, _this.options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return _this.spec.funcResToNative(method, result); + } + }), tx); + }); + _defineProperty(this, "txFromXDR", function (xdrBase64) { + return _assembled_transaction.AssembledTransaction.fromXDR(_this.options, xdrBase64, _this.spec); + }); + this.spec = spec; + this.options = options; + this.spec.funcs().forEach(function (xdrFn) { + var method = xdrFn.name().toString(); + if (method === CONSTRUCTOR_FUNC) { + return; + } + var assembleTransaction = function assembleTransaction(args, methodOptions) { + return _assembled_transaction.AssembledTransaction.build(_objectSpread(_objectSpread(_objectSpread({ + method: method, + args: args && spec.funcArgsToScVals(method, args) + }, options), methodOptions), {}, { + errorTypes: spec.errorCases().reduce(function (acc, curr) { + return _objectSpread(_objectSpread({}, acc), {}, _defineProperty({}, curr.value(), { + message: curr.doc().toString() + })); + }, {}), + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + }; + _this[method] = spec.getFunc(method).inputs().length === 0 ? function (opts) { + return assembleTransaction(undefined, opts); + } : assembleTransaction; + }); + } + return _createClass(Client, null, [{ + key: "deploy", + value: function () { + var _deploy = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(args, options) { + var wasmHash, salt, format, fee, timeoutInSeconds, simulate, clientOptions, spec, operation; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + wasmHash = options.wasmHash, salt = options.salt, format = options.format, fee = options.fee, timeoutInSeconds = options.timeoutInSeconds, simulate = options.simulate, clientOptions = _objectWithoutProperties(options, _excluded2); + _context.next = 3; + return specFromWasmHash(wasmHash, clientOptions, format); + case 3: + spec = _context.sent; + operation = _stellarBase.Operation.createCustomContract({ + address: new _stellarBase.Address(options.publicKey), + wasmHash: typeof wasmHash === "string" ? Buffer.from(wasmHash, format !== null && format !== void 0 ? format : "hex") : wasmHash, + salt: salt, + constructorArgs: args ? spec.funcArgsToScVals(CONSTRUCTOR_FUNC, args) : [] + }); + return _context.abrupt("return", _assembled_transaction.AssembledTransaction.buildWithOp(operation, _objectSpread(_objectSpread({ + fee: fee, + timeoutInSeconds: timeoutInSeconds, + simulate: simulate + }, clientOptions), {}, { + contractId: "ignored", + method: CONSTRUCTOR_FUNC, + parseResultXdr: function parseResultXdr(result) { + return new Client(spec, _objectSpread(_objectSpread({}, clientOptions), {}, { + contractId: _stellarBase.Address.fromScVal(result).toString() + })); + } + }))); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + function deploy(_x4, _x5) { + return _deploy.apply(this, arguments); + } + return deploy; + }() + }, { + key: "fromWasmHash", + value: (function () { + var _fromWasmHash = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args2 = arguments; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + format = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context2.next = 3; + break; + } + throw new TypeError('options must contain rpcUrl'); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new _rpc.Server(rpcUrl, serverOpts); + _context2.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context2.sent; + return _context2.abrupt("return", Client.fromWasm(wasm, options)); + case 10: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function fromWasmHash(_x6, _x7) { + return _fromWasmHash.apply(this, arguments); + } + return fromWasmHash; + }()) + }, { + key: "fromWasm", + value: (function () { + var _fromWasm = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(wasm, options) { + var spec; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return specFromWasm(wasm); + case 2: + spec = _context3.sent; + return _context3.abrupt("return", new Client(spec, options)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + function fromWasm(_x8, _x9) { + return _fromWasm.apply(this, arguments); + } + return fromWasm; + }()) + }, { + key: "from", + value: (function () { + var _from = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(options) { + var rpcUrl, contractId, allowHttp, serverOpts, server, wasm; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(!options || !options.rpcUrl || !options.contractId)) { + _context4.next = 2; + break; + } + throw new TypeError('options must contain rpcUrl and contractId'); + case 2: + rpcUrl = options.rpcUrl, contractId = options.contractId, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new _rpc.Server(rpcUrl, serverOpts); + _context4.next = 7; + return server.getContractWasmByContractId(contractId); + case 7: + wasm = _context4.sent; + return _context4.abrupt("return", Client.fromWasm(wasm, options)); + case 9: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function from(_x10) { + return _from.apply(this, arguments); + } + return from; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/index.d.ts new file mode 100644 index 000000000..8b9e1dc5e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/index.d.ts @@ -0,0 +1,7 @@ +export * from "./assembled_transaction"; +export * from "./basic_node_signer"; +export * from "./client"; +export * from "./rust_result"; +export * from "./sent_transaction"; +export * from "./spec"; +export * from "./types"; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/index.js b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/index.js new file mode 100644 index 000000000..9a10eddfc --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/index.js @@ -0,0 +1,82 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _assembled_transaction = require("./assembled_transaction"); +Object.keys(_assembled_transaction).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _assembled_transaction[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _assembled_transaction[key]; + } + }); +}); +var _basic_node_signer = require("./basic_node_signer"); +Object.keys(_basic_node_signer).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _basic_node_signer[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _basic_node_signer[key]; + } + }); +}); +var _client = require("./client"); +Object.keys(_client).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _client[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _client[key]; + } + }); +}); +var _rust_result = require("./rust_result"); +Object.keys(_rust_result).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _rust_result[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _rust_result[key]; + } + }); +}); +var _sent_transaction = require("./sent_transaction"); +Object.keys(_sent_transaction).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _sent_transaction[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _sent_transaction[key]; + } + }); +}); +var _spec = require("./spec"); +Object.keys(_spec).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _spec[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _spec[key]; + } + }); +}); +var _types = require("./types"); +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _types[key]; + } + }); +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/rust_result.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/rust_result.d.ts new file mode 100644 index 000000000..f72a123e1 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/rust_result.d.ts @@ -0,0 +1,81 @@ +/** + * A minimal implementation of Rust's `Result` type. Used for contract + * methods that return Results, to maintain their distinction from methods + * that simply either return a value or throw. + * + * #### Why is this needed? + * + * This is used by {@link module:contract.Spec | `ContractSpec`} and + * {@link module:contract.AssembledTransaction | `AssembledTransaction`} when + * parsing values return by contracts. + * + * Contract methods can be implemented to return simple values, in which case + * they can also throw errors. This matches JavaScript's most idiomatic + * workflow, using `try...catch` blocks. + * + * But Rust also gives the flexibility of returning `Result` types. And Soroban + * contracts further support this with the `#[contracterror]` macro. Should + * JavaScript calls to such methods ignore all of that, and just flatten this + * extra info down to the same `try...catch` flow as other methods? We're not + * sure. + * + * For now, we've added this minimal implementation of Rust's `Result` logic, + * which exports the `Result` interface and its associated implementations, + * `Ok` and `Err`. This allows `ContractSpec` and `AssembledTransaction` to + * work together to duplicate the contract's Rust logic, always returning + * `Result` types for contract methods that are implemented to do so. + * + * In the future, if this feels too un-idiomatic for JavaScript, we can always + * remove this and flatten all JS calls to `try...catch`. Easier to remove this + * logic later than it would be to add it. + * + * @memberof module:contract + */ +export interface Result { + unwrap(): T; + unwrapErr(): E; + isOk(): boolean; + isErr(): boolean; +} +/** + * Error interface containing the error message. Matches Rust's implementation. + * Part of implementing {@link module:contract.Result | Result}, a minimal + * implementation of Rust's `Result` type. Used for contract methods that return + * Results, to maintain their distinction from methods that simply either return + * a value or throw. + * + * @memberof module:contract + */ +export interface ErrorMessage { + message: string; +} +/** + * Part of implementing {@link module:contract.Result | Result}, a minimal + * implementation of Rust's `Result` type. Used for contract methods that return + * Results, to maintain their distinction from methods that simply either return + * a value or throw. + * @private + */ +export declare class Ok implements Result { + readonly value: T; + constructor(value: T); + unwrapErr(): never; + unwrap(): T; + isOk(): boolean; + isErr(): boolean; +} +/** + * Part of implementing {@link module:contract.Result | Result}, a minimal + * implementation of Rust's `Result` type. Used for contract methods that return + * Results, to maintain their distinction from methods that simply either return + * a value or throw. + * @private + */ +export declare class Err implements Result { + readonly error: E; + constructor(error: E); + unwrapErr(): E; + unwrap(): never; + isOk(): boolean; + isErr(): boolean; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/rust_result.js b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/rust_result.js new file mode 100644 index 000000000..5cbad1179 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/rust_result.js @@ -0,0 +1,66 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Ok = exports.Err = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Ok = exports.Ok = function () { + function Ok(value) { + _classCallCheck(this, Ok); + this.value = value; + } + return _createClass(Ok, [{ + key: "unwrapErr", + value: function unwrapErr() { + throw new Error("No error"); + } + }, { + key: "unwrap", + value: function unwrap() { + return this.value; + } + }, { + key: "isOk", + value: function isOk() { + return true; + } + }, { + key: "isErr", + value: function isErr() { + return false; + } + }]); +}(); +var Err = exports.Err = function () { + function Err(error) { + _classCallCheck(this, Err); + this.error = error; + } + return _createClass(Err, [{ + key: "unwrapErr", + value: function unwrapErr() { + return this.error; + } + }, { + key: "unwrap", + value: function unwrap() { + throw new Error(this.error.message); + } + }, { + key: "isOk", + value: function isOk() { + return false; + } + }, { + key: "isErr", + value: function isErr() { + return true; + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/sent_transaction.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/sent_transaction.d.ts new file mode 100644 index 000000000..ab3234a2d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/sent_transaction.d.ts @@ -0,0 +1,84 @@ +import { Server } from "../rpc"; +import { Api } from "../rpc/api"; +import type { AssembledTransaction } from "./assembled_transaction"; +/** + * A transaction that has been sent to the Soroban network. This happens in two steps: + * + * 1. `sendTransaction`: initial submission of the transaction to the network. + * If this step runs into problems, the attempt to sign and send will be + * aborted. You can see the result of this call in the + * `sendTransactionResponse` getter. + * 2. `getTransaction`: once the transaction has been submitted to the network + * successfully, you need to wait for it to finalize to get the result of the + * transaction. This will be retried with exponential backoff for + * {@link MethodOptions.timeoutInSeconds} seconds. See all attempts in + * `getTransactionResponseAll` and the most recent attempt in + * `getTransactionResponse`. + * + * @memberof module:contract + * @class + * + * @param {Function} signTransaction More info in {@link MethodOptions} + * @param {module:contract.AssembledTransaction} assembled {@link AssembledTransaction} from which this SentTransaction was initialized + */ +export declare class SentTransaction { + assembled: AssembledTransaction; + server: Server; + /** + * The result of calling `sendTransaction` to broadcast the transaction to the + * network. + */ + sendTransactionResponse?: Api.SendTransactionResponse; + /** + * If `sendTransaction` completes successfully (which means it has `status: 'PENDING'`), + * then `getTransaction` will be called in a loop for + * {@link MethodOptions.timeoutInSeconds} seconds. This array contains all + * the results of those calls. + */ + getTransactionResponseAll?: Api.GetTransactionResponse[]; + /** + * The most recent result of calling `getTransaction`, from the + * `getTransactionResponseAll` array. + */ + getTransactionResponse?: Api.GetTransactionResponse; + static Errors: { + SendFailed: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + SendResultOnly: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + TransactionStillPending: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + }; + constructor(assembled: AssembledTransaction); + /** + * Initialize a `SentTransaction` from `options` and a `signed` + * AssembledTransaction. This will also send the transaction to the network. + */ + static init: (assembled: AssembledTransaction) => Promise>; + private send; + get result(): T; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/sent_transaction.js b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/sent_transaction.js new file mode 100644 index 000000000..03d0948b5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/sent_transaction.js @@ -0,0 +1,151 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SentTransaction = void 0; +var _rpc = require("../rpc"); +var _api = require("../rpc/api"); +var _utils = require("./utils"); +var _types = require("./types"); +var _SentTransaction; +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var SentTransaction = exports.SentTransaction = function () { + function SentTransaction(assembled) { + var _this = this, + _this$assembled$optio2; + _classCallCheck(this, SentTransaction); + _defineProperty(this, "send", _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var _this$assembled$optio; + var hash, timeoutInSeconds; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return _this.server.sendTransaction(_this.assembled.signed); + case 2: + _this.sendTransactionResponse = _context.sent; + if (!(_this.sendTransactionResponse.status !== "PENDING")) { + _context.next = 5; + break; + } + throw new SentTransaction.Errors.SendFailed("Sending the transaction to the network failed!\n".concat(JSON.stringify(_this.sendTransactionResponse, null, 2))); + case 5: + hash = _this.sendTransactionResponse.hash; + timeoutInSeconds = (_this$assembled$optio = _this.assembled.options.timeoutInSeconds) !== null && _this$assembled$optio !== void 0 ? _this$assembled$optio : _types.DEFAULT_TIMEOUT; + _context.next = 9; + return (0, _utils.withExponentialBackoff)(function () { + return _this.server.getTransaction(hash); + }, function (resp) { + return resp.status === _api.Api.GetTransactionStatus.NOT_FOUND; + }, timeoutInSeconds); + case 9: + _this.getTransactionResponseAll = _context.sent; + _this.getTransactionResponse = _this.getTransactionResponseAll[_this.getTransactionResponseAll.length - 1]; + if (!(_this.getTransactionResponse.status === _api.Api.GetTransactionStatus.NOT_FOUND)) { + _context.next = 13; + break; + } + throw new SentTransaction.Errors.TransactionStillPending("Waited ".concat(timeoutInSeconds, " seconds for transaction to complete, but it did not. ") + "Returning anyway. Check the transaction status manually. " + "Sent transaction: ".concat(JSON.stringify(_this.sendTransactionResponse, null, 2), "\n") + "All attempts to get the result: ".concat(JSON.stringify(_this.getTransactionResponseAll, null, 2))); + case 13: + return _context.abrupt("return", _this); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + }))); + this.assembled = assembled; + this.server = new _rpc.Server(this.assembled.options.rpcUrl, { + allowHttp: (_this$assembled$optio2 = this.assembled.options.allowHttp) !== null && _this$assembled$optio2 !== void 0 ? _this$assembled$optio2 : false + }); + } + return _createClass(SentTransaction, [{ + key: "result", + get: function get() { + if ("getTransactionResponse" in this && this.getTransactionResponse) { + if ("returnValue" in this.getTransactionResponse) { + return this.assembled.options.parseResultXdr(this.getTransactionResponse.returnValue); + } + throw new Error("Transaction failed! Cannot parse result."); + } + if (this.sendTransactionResponse) { + var _this$sendTransaction; + var errorResult = (_this$sendTransaction = this.sendTransactionResponse.errorResult) === null || _this$sendTransaction === void 0 ? void 0 : _this$sendTransaction.result(); + if (errorResult) { + throw new SentTransaction.Errors.SendFailed("Transaction simulation looked correct, but attempting to send the transaction failed. Check `simulation` and `sendTransactionResponseAll` to troubleshoot. Decoded `sendTransactionResponse.errorResultXdr`: ".concat(errorResult)); + } + throw new SentTransaction.Errors.SendResultOnly("Transaction was sent to the network, but not yet awaited. No result to show. Await transaction completion with `getTransaction(sendTransactionResponse.hash)`"); + } + throw new Error("Sending transaction failed: ".concat(JSON.stringify(this.assembled.signed))); + } + }]); +}(); +_SentTransaction = SentTransaction; +_defineProperty(SentTransaction, "Errors", { + SendFailed: function (_Error) { + function SendFailedError() { + _classCallCheck(this, SendFailedError); + return _callSuper(this, SendFailedError, arguments); + } + _inherits(SendFailedError, _Error); + return _createClass(SendFailedError); + }(_wrapNativeSuper(Error)), + SendResultOnly: function (_Error2) { + function SendResultOnlyError() { + _classCallCheck(this, SendResultOnlyError); + return _callSuper(this, SendResultOnlyError, arguments); + } + _inherits(SendResultOnlyError, _Error2); + return _createClass(SendResultOnlyError); + }(_wrapNativeSuper(Error)), + TransactionStillPending: function (_Error3) { + function TransactionStillPendingError() { + _classCallCheck(this, TransactionStillPendingError); + return _callSuper(this, TransactionStillPendingError, arguments); + } + _inherits(TransactionStillPendingError, _Error3); + return _createClass(TransactionStillPendingError); + }(_wrapNativeSuper(Error)) +}); +_defineProperty(SentTransaction, "init", function () { + var _ref2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(assembled) { + var tx, sent; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + tx = new _SentTransaction(assembled); + _context2.next = 3; + return tx.send(); + case 3: + sent = _context2.sent; + return _context2.abrupt("return", sent); + case 5: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; +}()); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/spec.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/spec.d.ts new file mode 100644 index 000000000..737c8c464 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/spec.d.ts @@ -0,0 +1,152 @@ +import type { JSONSchema7 } from "json-schema"; +import { xdr } from "@stellar/stellar-base"; +export interface Union { + tag: string; + values?: T; +} +/** + * Provides a ContractSpec class which can contains the XDR types defined by the contract. + * This allows the class to be used to convert between native and raw `xdr.ScVal`s. + * + * Constructs a new ContractSpec from an array of XDR spec entries. + * + * @memberof module:contract + * @param {xdr.ScSpecEntry[] | string[]} entries the XDR spec entries + * @throws {Error} if entries is invalid + * + * @example + * const specEntries = [...]; // XDR spec entries of a smart contract + * const contractSpec = new ContractSpec(specEntries); + * + * // Convert native value to ScVal + * const args = { + * arg1: 'value1', + * arg2: 1234 + * }; + * const scArgs = contractSpec.funcArgsToScVals('funcName', args); + * + * // Call contract + * const resultScv = await callContract(contractId, 'funcName', scArgs); + * + * // Convert result ScVal back to native value + * const result = contractSpec.funcResToNative('funcName', resultScv); + * + * console.log(result); // {success: true} + */ +export declare class Spec { + /** + * The XDR spec entries. + */ + entries: xdr.ScSpecEntry[]; + constructor(entries: xdr.ScSpecEntry[] | string[]); + /** + * Gets the XDR functions from the spec. + * @returns {xdr.ScSpecFunctionV0[]} all contract functions + */ + funcs(): xdr.ScSpecFunctionV0[]; + /** + * Gets the XDR function spec for the given function name. + * + * @param {string} name the name of the function + * @returns {xdr.ScSpecFunctionV0} the function spec + * + * @throws {Error} if no function with the given name exists + */ + getFunc(name: string): xdr.ScSpecFunctionV0; + /** + * Converts native JS arguments to ScVals for calling a contract function. + * + * @param {string} name the name of the function + * @param {object} args the arguments object + * @returns {xdr.ScVal[]} the converted arguments + * + * @throws {Error} if argument is missing or incorrect type + * + * @example + * const args = { + * arg1: 'value1', + * arg2: 1234 + * }; + * const scArgs = contractSpec.funcArgsToScVals('funcName', args); + */ + funcArgsToScVals(name: string, args: object): xdr.ScVal[]; + /** + * Converts the result ScVal of a function call to a native JS value. + * + * @param {string} name the name of the function + * @param {xdr.ScVal | string} val_or_base64 the result ScVal or base64 encoded string + * @returns {any} the converted native value + * + * @throws {Error} if return type mismatch or invalid input + * + * @example + * const resultScv = 'AAA=='; // Base64 encoded ScVal + * const result = contractSpec.funcResToNative('funcName', resultScv); + */ + funcResToNative(name: string, val_or_base64: xdr.ScVal | string): any; + /** + * Finds the XDR spec entry for the given name. + * + * @param {string} name the name to find + * @returns {xdr.ScSpecEntry} the entry + * + * @throws {Error} if no entry with the given name exists + */ + findEntry(name: string): xdr.ScSpecEntry; + /** + * Converts a native JS value to an ScVal based on the given type. + * + * @param {any} val the native JS value + * @param {xdr.ScSpecTypeDef} [ty] the expected type + * @returns {xdr.ScVal} the converted ScVal + * + * @throws {Error} if value cannot be converted to the given type + */ + nativeToScVal(val: any, ty: xdr.ScSpecTypeDef): xdr.ScVal; + private nativeToUdt; + private nativeToUnion; + private nativeToStruct; + private nativeToEnum; + /** + * Converts an base64 encoded ScVal back to a native JS value based on the given type. + * + * @param {string} scv the base64 encoded ScVal + * @param {xdr.ScSpecTypeDef} typeDef the expected type + * @returns {any} the converted native JS value + * + * @throws {Error} if ScVal cannot be converted to the given type + */ + scValStrToNative(scv: string, typeDef: xdr.ScSpecTypeDef): T; + /** + * Converts an ScVal back to a native JS value based on the given type. + * + * @param {xdr.ScVal} scv the ScVal + * @param {xdr.ScSpecTypeDef} typeDef the expected type + * @returns {any} the converted native JS value + * + * @throws {Error} if ScVal cannot be converted to the given type + */ + scValToNative(scv: xdr.ScVal, typeDef: xdr.ScSpecTypeDef): T; + private scValUdtToNative; + private unionToNative; + private structToNative; + private enumToNative; + /** + * Gets the XDR error cases from the spec. + * + * @returns {xdr.ScSpecFunctionV0[]} all contract functions + * + */ + errorCases(): xdr.ScSpecUdtErrorEnumCaseV0[]; + /** + * Converts the contract spec to a JSON schema. + * + * If `funcName` is provided, the schema will be a reference to the function schema. + * + * @param {string} [funcName] the name of the function to convert + * @returns {JSONSchema7} the converted JSON schema + * + * @throws {Error} if the contract spec is invalid + */ + jsonSchema(funcName?: string): JSONSchema7; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/spec.js b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/spec.js new file mode 100644 index 000000000..1a70b3d2f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/spec.js @@ -0,0 +1,1020 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Spec = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _rust_result = require("./rust_result"); +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function enumToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + var title = aCase.name().toString(); + var desc = aCase.doc().toString(); + oneOf.push({ + description: desc, + title: title, + enum: [aCase.value()], + type: "number" + }); + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +function isNumeric(field) { + return /^\d+$/.test(field.name().toString()); +} +function readObj(args, input) { + var inputName = input.name().toString(); + var entry = Object.entries(args).find(function (_ref) { + var _ref2 = _slicedToArray(_ref, 1), + name = _ref2[0]; + return name === inputName; + }); + if (!entry) { + throw new Error("Missing field ".concat(inputName)); + } + return entry[1]; +} +function findCase(name) { + return function matches(entry) { + switch (entry.switch().value) { + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var tuple = entry.tupleCase(); + return tuple.name().toString() === name; + } + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var voidCase = entry.voidCase(); + return voidCase.name().toString() === name; + } + default: + return false; + } + }; +} +function stringToScVal(str, ty) { + switch (ty.value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeString().value: + return _stellarBase.xdr.ScVal.scvString(str); + case _stellarBase.xdr.ScSpecType.scSpecTypeSymbol().value: + return _stellarBase.xdr.ScVal.scvSymbol(str); + case _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value: + { + var addr = _stellarBase.Address.fromString(str); + return _stellarBase.xdr.ScVal.scvAddress(addr.toScAddress()); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU64().value: + return new _stellarBase.XdrLargeInt("u64", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeI64().value: + return new _stellarBase.XdrLargeInt("i64", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeU128().value: + return new _stellarBase.XdrLargeInt("u128", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeI128().value: + return new _stellarBase.XdrLargeInt("i128", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeU256().value: + return new _stellarBase.XdrLargeInt("u256", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeI256().value: + return new _stellarBase.XdrLargeInt("i256", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeBytes().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeBytesN().value: + return _stellarBase.xdr.ScVal.scvBytes(Buffer.from(str, "base64")); + default: + throw new TypeError("invalid type ".concat(ty.name, " specified for string value")); + } +} +var PRIMITIVE_DEFINITONS = { + U32: { + type: "integer", + minimum: 0, + maximum: 4294967295 + }, + I32: { + type: "integer", + minimum: -2147483648, + maximum: 2147483647 + }, + U64: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 20 + }, + I64: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 21 + }, + U128: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 39 + }, + I128: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 40 + }, + U256: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 78 + }, + I256: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 79 + }, + Address: { + type: "string", + format: "address", + description: "Address can be a public key or contract id" + }, + ScString: { + type: "string", + description: "ScString is a string" + }, + ScSymbol: { + type: "string", + description: "ScString is a string" + }, + DataUrl: { + type: "string", + pattern: "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$" + } +}; +function typeRef(typeDef) { + var t = typeDef.switch(); + var value = t.value; + var ref; + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVal().value: + { + ref = "Val"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBool().value: + { + return { + type: "boolean" + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeVoid().value: + { + return { + type: "null" + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeError().value: + { + ref = "Error"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU32().value: + { + ref = "U32"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI32().value: + { + ref = "I32"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU64().value: + { + ref = "U64"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI64().value: + { + ref = "I64"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeTimepoint().value: + { + throw new Error("Timepoint type not supported"); + ref = "Timepoint"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeDuration().value: + { + throw new Error("Duration not supported"); + ref = "Duration"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU128().value: + { + ref = "U128"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI128().value: + { + ref = "I128"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU256().value: + { + ref = "U256"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI256().value: + { + ref = "I256"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBytes().value: + { + ref = "DataUrl"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeString().value: + { + ref = "ScString"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeSymbol().value: + { + ref = "ScSymbol"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value: + { + ref = "Address"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeOption().value: + { + var opt = typeDef.option(); + return typeRef(opt.valueType()); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeResult().value: + { + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeVec().value: + { + var arr = typeDef.vec(); + var reference = typeRef(arr.elementType()); + return { + type: "array", + items: reference + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = typeDef.map(); + var items = [typeRef(map.keyType()), typeRef(map.valueType())]; + return { + type: "array", + items: { + type: "array", + items: items, + minItems: 2, + maxItems: 2 + } + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tuple = typeDef.tuple(); + var minItems = tuple.valueTypes().length; + var maxItems = minItems; + var _items = tuple.valueTypes().map(typeRef); + return { + type: "array", + items: _items, + minItems: minItems, + maxItems: maxItems + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var _arr = typeDef.bytesN(); + return { + $ref: "#/definitions/DataUrl", + maxLength: _arr.n() + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeUdt().value: + { + var udt = typeDef.udt(); + ref = udt.name().toString(); + break; + } + } + return { + $ref: "#/definitions/".concat(ref) + }; +} +function isRequired(typeDef) { + return typeDef.switch().value !== _stellarBase.xdr.ScSpecType.scSpecTypeOption().value; +} +function argsAndRequired(input) { + var properties = {}; + var required = []; + input.forEach(function (arg) { + var aType = arg.type(); + var name = arg.name().toString(); + properties[name] = typeRef(aType); + if (isRequired(aType)) { + required.push(name); + } + }); + var res = { + properties: properties + }; + if (required.length > 0) { + res.required = required; + } + return res; +} +function structToJsonSchema(udt) { + var fields = udt.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + var items = fields.map(function (_, i) { + return typeRef(fields[i].type()); + }); + return { + type: "array", + items: items, + minItems: fields.length, + maxItems: fields.length + }; + } + var description = udt.doc().toString(); + var _argsAndRequired = argsAndRequired(fields), + properties = _argsAndRequired.properties, + required = _argsAndRequired.required; + properties.additionalProperties = false; + return { + description: description, + properties: properties, + required: required, + type: "object" + }; +} +function functionToJsonSchema(func) { + var _argsAndRequired2 = argsAndRequired(func.inputs()), + properties = _argsAndRequired2.properties, + required = _argsAndRequired2.required; + var args = { + additionalProperties: false, + properties: properties, + type: "object" + }; + if ((required === null || required === void 0 ? void 0 : required.length) > 0) { + args.required = required; + } + var input = { + properties: { + args: args + } + }; + var outputs = func.outputs(); + var output = outputs.length > 0 ? typeRef(outputs[0]) : typeRef(_stellarBase.xdr.ScSpecTypeDef.scSpecTypeVoid()); + var description = func.doc().toString(); + if (description.length > 0) { + input.description = description; + } + input.additionalProperties = false; + output.additionalProperties = false; + return { + input: input, + output: output + }; +} +function unionToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + switch (aCase.switch().value) { + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var c = aCase.voidCase(); + var title = c.name().toString(); + oneOf.push({ + type: "object", + title: title, + properties: { + tag: title + }, + additionalProperties: false, + required: ["tag"] + }); + break; + } + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var _c = aCase.tupleCase(); + var _title = _c.name().toString(); + oneOf.push({ + type: "object", + title: _title, + properties: { + tag: _title, + values: { + type: "array", + items: _c.type().map(typeRef) + } + }, + required: ["tag", "values"], + additionalProperties: false + }); + } + } + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +var Spec = exports.Spec = function () { + function Spec(entries) { + _classCallCheck(this, Spec); + _defineProperty(this, "entries", []); + if (entries.length === 0) { + throw new Error("Contract spec must have at least one entry"); + } + var entry = entries[0]; + if (typeof entry === "string") { + this.entries = entries.map(function (s) { + return _stellarBase.xdr.ScSpecEntry.fromXDR(s, "base64"); + }); + } else { + this.entries = entries; + } + } + return _createClass(Spec, [{ + key: "funcs", + value: function funcs() { + return this.entries.filter(function (entry) { + return entry.switch().value === _stellarBase.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value; + }).map(function (entry) { + return entry.functionV0(); + }); + } + }, { + key: "getFunc", + value: function getFunc(name) { + var entry = this.findEntry(name); + if (entry.switch().value !== _stellarBase.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value) { + throw new Error("".concat(name, " is not a function")); + } + return entry.functionV0(); + } + }, { + key: "funcArgsToScVals", + value: function funcArgsToScVals(name, args) { + var _this = this; + var fn = this.getFunc(name); + return fn.inputs().map(function (input) { + return _this.nativeToScVal(readObj(args, input), input.type()); + }); + } + }, { + key: "funcResToNative", + value: function funcResToNative(name, val_or_base64) { + var val = typeof val_or_base64 === "string" ? _stellarBase.xdr.ScVal.fromXDR(val_or_base64, "base64") : val_or_base64; + var func = this.getFunc(name); + var outputs = func.outputs(); + if (outputs.length === 0) { + var type = val.switch(); + if (type.value !== _stellarBase.xdr.ScValType.scvVoid().value) { + throw new Error("Expected void, got ".concat(type.name)); + } + return null; + } + if (outputs.length > 1) { + throw new Error("Multiple outputs not supported"); + } + var output = outputs[0]; + if (output.switch().value === _stellarBase.xdr.ScSpecType.scSpecTypeResult().value) { + return new _rust_result.Ok(this.scValToNative(val, output.result().okType())); + } + return this.scValToNative(val, output); + } + }, { + key: "findEntry", + value: function findEntry(name) { + var entry = this.entries.find(function (e) { + return e.value().name().toString() === name; + }); + if (!entry) { + throw new Error("no such entry: ".concat(name)); + } + return entry; + } + }, { + key: "nativeToScVal", + value: function nativeToScVal(val, ty) { + var _this2 = this; + var t = ty.switch(); + var value = t.value; + if (t.value === _stellarBase.xdr.ScSpecType.scSpecTypeUdt().value) { + var udt = ty.udt(); + return this.nativeToUdt(val, udt.name().toString()); + } + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeOption().value) { + var opt = ty.option(); + if (val === undefined) { + return _stellarBase.xdr.ScVal.scvVoid(); + } + return this.nativeToScVal(val, opt.valueType()); + } + switch (_typeof(val)) { + case "object": + { + var _val$constructor$name, _val$constructor; + if (val === null) { + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVoid().value: + return _stellarBase.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was null")); + } + } + if (val instanceof _stellarBase.xdr.ScVal) { + return val; + } + if (val instanceof _stellarBase.Address) { + if (ty.switch().value !== _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.toScVal(); + } + if (val instanceof _stellarBase.Contract) { + if (ty.switch().value !== _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.address().toScVal(); + } + if (val instanceof Uint8Array || Buffer.isBuffer(val)) { + var copy = Uint8Array.from(val); + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var bytesN = ty.bytesN(); + if (copy.length !== bytesN.n()) { + throw new TypeError("expected ".concat(bytesN.n(), " bytes, but got ").concat(copy.length)); + } + return _stellarBase.xdr.ScVal.scvBytes(copy); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBytes().value: + return _stellarBase.xdr.ScVal.scvBytes(copy); + default: + throw new TypeError("invalid type (".concat(ty, ") specified for Bytes and BytesN")); + } + } + if (Array.isArray(val)) { + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVec().value: + { + var vec = ty.vec(); + var elementType = vec.elementType(); + return _stellarBase.xdr.ScVal.scvVec(val.map(function (v) { + return _this2.nativeToScVal(v, elementType); + })); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tup = ty.tuple(); + var valTypes = tup.valueTypes(); + if (val.length !== valTypes.length) { + throw new TypeError("Tuple expects ".concat(valTypes.length, " values, but ").concat(val.length, " were provided")); + } + return _stellarBase.xdr.ScVal.scvVec(val.map(function (v, i) { + return _this2.nativeToScVal(v, valTypes[i]); + })); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = ty.map(); + var keyType = map.keyType(); + var valueType = map.valueType(); + return _stellarBase.xdr.ScVal.scvMap(val.map(function (entry) { + var key = _this2.nativeToScVal(entry[0], keyType); + var mapVal = _this2.nativeToScVal(entry[1], valueType); + return new _stellarBase.xdr.ScMapEntry({ + key: key, + val: mapVal + }); + })); + } + default: + throw new TypeError("Type ".concat(ty, " was not vec, but value was Array")); + } + } + if (val.constructor === Map) { + if (value !== _stellarBase.xdr.ScSpecType.scSpecTypeMap().value) { + throw new TypeError("Type ".concat(ty, " was not map, but value was Map")); + } + var scMap = ty.map(); + var _map = val; + var entries = []; + var values = _map.entries(); + var res = values.next(); + while (!res.done) { + var _res$value = _slicedToArray(res.value, 2), + k = _res$value[0], + v = _res$value[1]; + var key = this.nativeToScVal(k, scMap.keyType()); + var mapval = this.nativeToScVal(v, scMap.valueType()); + entries.push(new _stellarBase.xdr.ScMapEntry({ + key: key, + val: mapval + })); + res = values.next(); + } + return _stellarBase.xdr.ScVal.scvMap(entries); + } + if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : "") !== "Object") { + var _val$constructor2; + throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")")); + } + throw new TypeError("Received object ".concat(val, " did not match the provided type ").concat(ty)); + } + case "number": + case "bigint": + { + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeU32().value: + return _stellarBase.xdr.ScVal.scvU32(val); + case _stellarBase.xdr.ScSpecType.scSpecTypeI32().value: + return _stellarBase.xdr.ScVal.scvI32(val); + case _stellarBase.xdr.ScSpecType.scSpecTypeU64().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeI64().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeU128().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeI128().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeU256().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeI256().value: + { + var intType = t.name.substring(10).toLowerCase(); + return new _stellarBase.XdrLargeInt(intType, val).toScVal(); + } + default: + throw new TypeError("invalid type (".concat(ty, ") specified for integer")); + } + } + case "string": + return stringToScVal(val, t); + case "boolean": + { + if (value !== _stellarBase.xdr.ScSpecType.scSpecTypeBool().value) { + throw TypeError("Type ".concat(ty, " was not bool, but value was bool")); + } + return _stellarBase.xdr.ScVal.scvBool(val); + } + case "undefined": + { + if (!ty) { + return _stellarBase.xdr.ScVal.scvVoid(); + } + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVoid().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeOption().value: + return _stellarBase.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was undefined")); + } + } + case "function": + return this.nativeToScVal(val(), ty); + default: + throw new TypeError("failed to convert typeof ".concat(_typeof(val), " (").concat(val, ")")); + } + } + }, { + key: "nativeToUdt", + value: function nativeToUdt(val, name) { + var entry = this.findEntry(name); + switch (entry.switch()) { + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + if (typeof val !== "number") { + throw new TypeError("expected number for enum ".concat(name, ", but got ").concat(_typeof(val))); + } + return this.nativeToEnum(val, entry.udtEnumV0()); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.nativeToStruct(val, entry.udtStructV0()); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.nativeToUnion(val, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(name)); + } + } + }, { + key: "nativeToUnion", + value: function nativeToUnion(val, union_) { + var _this3 = this; + var entryName = val.tag; + var caseFound = union_.cases().find(function (entry) { + var caseN = entry.value().name().toString(); + return caseN === entryName; + }); + if (!caseFound) { + throw new TypeError("no such enum entry: ".concat(entryName, " in ").concat(union_)); + } + var key = _stellarBase.xdr.ScVal.scvSymbol(entryName); + switch (caseFound.switch()) { + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0(): + { + return _stellarBase.xdr.ScVal.scvVec([key]); + } + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0(): + { + var types = caseFound.tupleCase().type(); + if (Array.isArray(val.values)) { + if (val.values.length !== types.length) { + throw new TypeError("union ".concat(union_, " expects ").concat(types.length, " values, but got ").concat(val.values.length)); + } + var scvals = val.values.map(function (v, i) { + return _this3.nativeToScVal(v, types[i]); + }); + scvals.unshift(key); + return _stellarBase.xdr.ScVal.scvVec(scvals); + } + throw new Error("failed to parse union case ".concat(caseFound, " with ").concat(val)); + } + default: + throw new Error("failed to parse union ".concat(union_, " with ").concat(val)); + } + } + }, { + key: "nativeToStruct", + value: function nativeToStruct(val, struct) { + var _this4 = this; + var fields = struct.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + return _stellarBase.xdr.ScVal.scvVec(fields.map(function (_, i) { + return _this4.nativeToScVal(val[i], fields[i].type()); + })); + } + return _stellarBase.xdr.ScVal.scvMap(fields.map(function (field) { + var name = field.name().toString(); + return new _stellarBase.xdr.ScMapEntry({ + key: _this4.nativeToScVal(name, _stellarBase.xdr.ScSpecTypeDef.scSpecTypeSymbol()), + val: _this4.nativeToScVal(val[name], field.type()) + }); + })); + } + }, { + key: "nativeToEnum", + value: function nativeToEnum(val, enum_) { + if (enum_.cases().some(function (entry) { + return entry.value() === val; + })) { + return _stellarBase.xdr.ScVal.scvU32(val); + } + throw new TypeError("no such enum entry: ".concat(val, " in ").concat(enum_)); + } + }, { + key: "scValStrToNative", + value: function scValStrToNative(scv, typeDef) { + return this.scValToNative(_stellarBase.xdr.ScVal.fromXDR(scv, "base64"), typeDef); + } + }, { + key: "scValToNative", + value: function scValToNative(scv, typeDef) { + var _this5 = this; + var t = typeDef.switch(); + var value = t.value; + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeUdt().value) { + return this.scValUdtToNative(scv, typeDef.udt()); + } + switch (scv.switch().value) { + case _stellarBase.xdr.ScValType.scvVoid().value: + return undefined; + case _stellarBase.xdr.ScValType.scvU64().value: + case _stellarBase.xdr.ScValType.scvI64().value: + case _stellarBase.xdr.ScValType.scvU128().value: + case _stellarBase.xdr.ScValType.scvI128().value: + case _stellarBase.xdr.ScValType.scvU256().value: + case _stellarBase.xdr.ScValType.scvI256().value: + return (0, _stellarBase.scValToBigInt)(scv); + case _stellarBase.xdr.ScValType.scvVec().value: + { + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeVec().value) { + var _scv$vec; + var vec = typeDef.vec(); + return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(function (elm) { + return _this5.scValToNative(elm, vec.elementType()); + }); + } + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeTuple().value) { + var _scv$vec2; + var tuple = typeDef.tuple(); + var valTypes = tuple.valueTypes(); + return ((_scv$vec2 = scv.vec()) !== null && _scv$vec2 !== void 0 ? _scv$vec2 : []).map(function (elm, i) { + return _this5.scValToNative(elm, valTypes[i]); + }); + } + throw new TypeError("Type ".concat(typeDef, " was not vec, but ").concat(scv, " is")); + } + case _stellarBase.xdr.ScValType.scvAddress().value: + return _stellarBase.Address.fromScVal(scv).toString(); + case _stellarBase.xdr.ScValType.scvMap().value: + { + var _scv$map; + var map = (_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []; + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeMap().value) { + var typed = typeDef.map(); + var keyType = typed.keyType(); + var valueType = typed.valueType(); + var res = map.map(function (entry) { + return [_this5.scValToNative(entry.key(), keyType), _this5.scValToNative(entry.val(), valueType)]; + }); + return res; + } + throw new TypeError("ScSpecType ".concat(t.name, " was not map, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + case _stellarBase.xdr.ScValType.scvBool().value: + case _stellarBase.xdr.ScValType.scvU32().value: + case _stellarBase.xdr.ScValType.scvI32().value: + case _stellarBase.xdr.ScValType.scvBytes().value: + return scv.value(); + case _stellarBase.xdr.ScValType.scvString().value: + case _stellarBase.xdr.ScValType.scvSymbol().value: + { + var _scv$value; + if (value !== _stellarBase.xdr.ScSpecType.scSpecTypeString().value && value !== _stellarBase.xdr.ScSpecType.scSpecTypeSymbol().value) { + throw new Error("ScSpecType ".concat(t.name, " was not string or symbol, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + return (_scv$value = scv.value()) === null || _scv$value === void 0 ? void 0 : _scv$value.toString(); + } + case _stellarBase.xdr.ScValType.scvTimepoint().value: + case _stellarBase.xdr.ScValType.scvDuration().value: + return (0, _stellarBase.scValToBigInt)(_stellarBase.xdr.ScVal.scvU64(scv.u64())); + default: + throw new TypeError("failed to convert ".concat(JSON.stringify(scv, null, 2), " to native type from type ").concat(t.name)); + } + } + }, { + key: "scValUdtToNative", + value: function scValUdtToNative(scv, udt) { + var entry = this.findEntry(udt.name().toString()); + switch (entry.switch()) { + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + return this.enumToNative(scv); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.structToNative(scv, entry.udtStructV0()); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.unionToNative(scv, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(udt.name().toString(), ": ").concat(entry)); + } + } + }, { + key: "unionToNative", + value: function unionToNative(val, udt) { + var _this6 = this; + var vec = val.vec(); + if (!vec) { + throw new Error("".concat(JSON.stringify(val, null, 2), " is not a vec")); + } + if (vec.length === 0 && udt.cases.length !== 0) { + throw new Error("".concat(val, " has length 0, but the there are at least one case in the union")); + } + var name = vec[0].sym().toString(); + if (vec[0].switch().value !== _stellarBase.xdr.ScValType.scvSymbol().value) { + throw new Error("{vec[0]} is not a symbol"); + } + var entry = udt.cases().find(findCase(name)); + if (!entry) { + throw new Error("failed to find entry ".concat(name, " in union {udt.name().toString()}")); + } + var res = { + tag: name + }; + if (entry.switch().value === _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value) { + var tuple = entry.tupleCase(); + var ty = tuple.type(); + var values = ty.map(function (e, i) { + return _this6.scValToNative(vec[i + 1], e); + }); + res.values = values; + } + return res; + } + }, { + key: "structToNative", + value: function structToNative(val, udt) { + var _this7 = this, + _val$map; + var res = {}; + var fields = udt.fields(); + if (fields.some(isNumeric)) { + var _val$vec; + var r = (_val$vec = val.vec()) === null || _val$vec === void 0 ? void 0 : _val$vec.map(function (entry, i) { + return _this7.scValToNative(entry, fields[i].type()); + }); + return r; + } + (_val$map = val.map()) === null || _val$map === void 0 || _val$map.forEach(function (entry, i) { + var field = fields[i]; + res[field.name().toString()] = _this7.scValToNative(entry.val(), field.type()); + }); + return res; + } + }, { + key: "enumToNative", + value: function enumToNative(scv) { + if (scv.switch().value !== _stellarBase.xdr.ScValType.scvU32().value) { + throw new Error("Enum must have a u32 value"); + } + var num = scv.u32(); + return num; + } + }, { + key: "errorCases", + value: function errorCases() { + return this.entries.filter(function (entry) { + return entry.switch().value === _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value; + }).flatMap(function (entry) { + return entry.value().cases(); + }); + } + }, { + key: "jsonSchema", + value: function jsonSchema(funcName) { + var definitions = {}; + this.entries.forEach(function (entry) { + switch (entry.switch().value) { + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0().value: + { + var udt = entry.udtEnumV0(); + definitions[udt.name().toString()] = enumToJsonSchema(udt); + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0().value: + { + var _udt = entry.udtStructV0(); + definitions[_udt.name().toString()] = structToJsonSchema(_udt); + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0().value: + { + var _udt2 = entry.udtUnionV0(); + definitions[_udt2.name().toString()] = unionToJsonSchema(_udt2); + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value: + { + var fn = entry.functionV0(); + var fnName = fn.name().toString(); + var _functionToJsonSchema = functionToJsonSchema(fn), + input = _functionToJsonSchema.input; + definitions[fnName] = input; + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value: + {} + } + }); + var res = { + $schema: "http://json-schema.org/draft-07/schema#", + definitions: _objectSpread(_objectSpread({}, PRIMITIVE_DEFINITONS), definitions) + }; + if (funcName) { + res.$ref = "#/definitions/".concat(funcName); + } + return res; + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/types.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/types.d.ts new file mode 100644 index 000000000..bceff262c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/types.d.ts @@ -0,0 +1,244 @@ +import { Memo, MemoType, Operation, Transaction, xdr } from "@stellar/stellar-base"; +export type XDR_BASE64 = string; +/** + * An unsigned 32-bit integer. + * @memberof module:contract + */ +export type u32 = number; +/** + * A signed 32-bit integer. + * @memberof module:contract + */ +export type i32 = number; +/** + * An unsigned 64-bit integer. + * @memberof module:contract + */ +export type u64 = bigint; +/** + * A signed 64-bit integer. + * @memberof module:contract + */ +export type i64 = bigint; +/** + * An unsigned 128-bit integer. + * @memberof module:contract + */ +export type u128 = bigint; +/** + * A signed 128-bit integer. + * @memberof module:contract + */ +export type i128 = bigint; +/** + * An unsigned 256-bit integer. + * @memberof module:contract + */ +export type u256 = bigint; +/** + * A signed 256-bit integer. + * @memberof module:contract + */ +export type i256 = bigint; +export type Option = T | undefined; +export type Typepoint = bigint; +export type Duration = bigint; +/** + * A "regular" transaction, as opposed to a FeeBumpTransaction. + * @memberof module:contract + * @type {Transaction, Operation[]>} + */ +export type Tx = Transaction, Operation[]>; +export interface WalletError { + message: string; + code: number; + ext?: Array; +} +/** + * A function to request a wallet to sign a built transaction + * + * This function takes an XDR provided by the requester and applies a signature to it. + * It returns a base64-encoded string XDR-encoded Transaction Envelope with Decorated Signatures + * and the signer address back to the requester. + * + * @param xdr - The XDR string representing the transaction to be signed. + * @param opts - Options for signing the transaction. + * @param opts.networkPassphrase - The network's passphrase on which the transaction is intended to be signed. + * @param opts.address - The public key of the account that should be used to sign. + * @param opts.submit - If set to true, submits the transaction immediately after signing. + * @param opts.submitUrl - The URL of the network to which the transaction should be submitted, if applicable. + * + * @returns A promise resolving to an object with the signed transaction XDR and optional signer address and error. + */ +export type SignTransaction = (xdr: string, opts?: { + networkPassphrase?: string; + address?: string; + submit?: boolean; + submitUrl?: string; +}) => Promise<{ + signedTxXdr: string; + signerAddress?: string; +} & { + error?: WalletError; +}>; +/** + * A function to request a wallet to sign an authorization entry preimage. + * + * Similar to signing a transaction, this function takes an authorization entry preimage provided by the + * requester and applies a signature to it. + * It returns a signed hash of the same authorization entry and the signer address back to the requester. + * + * @param authEntry - The authorization entry preimage to be signed. + * @param opts - Options for signing the authorization entry. + * @param opts.networkPassphrase - The network's passphrase on which the authorization entry is intended to be signed. + * @param opts.address - The public key of the account that should be used to sign. + * + * @returns A promise resolving to an object with the signed authorization entry and optional signer address and error. + */ +export type SignAuthEntry = (authEntry: string, opts?: { + networkPassphrase?: string; + address?: string; +}) => Promise<{ + signedAuthEntry: string; + signerAddress?: string; +} & { + error?: WalletError; +}>; +/** + * Options for a smart contract client. + * @memberof module:contract + */ +export type ClientOptions = { + /** + * The public key of the account that will send this transaction. You can + * override this for specific methods later, like + * [signAndSend]{@link module:contract.AssembledTransaction#signAndSend} and + * [signAuthEntries]{@link module:contract.AssembledTransaction#signAuthEntries}. + */ + publicKey?: string; + /** + * A function to sign the transaction using the private key corresponding to + * the given `publicKey`. You do not need to provide this, for read-only + * calls, which only need to be simulated. If you do not need to sign and + * send, there is no need to provide this. If you do not provide it during + * initialization, you can provide it later when you call + * {@link module:contract.AssembledTransaction#signAndSend signAndSend}. + * + * Matches signature of `signTransaction` from Freighter. + */ + signTransaction?: SignTransaction; + /** + * A function to sign a specific auth entry for a transaction, using the + * private key corresponding to the provided `publicKey`. This is only needed + * for multi-auth transactions, in which one transaction is signed by + * multiple parties. If you do not provide it during initialization, you can + * provide it later when you call {@link module:contract.AssembledTransaction#signAuthEntries signAuthEntries}. + * + * Matches signature of `signAuthEntry` from Freighter. + */ + signAuthEntry?: SignAuthEntry; + /** The address of the contract the client will interact with. */ + contractId: string; + /** + * The network passphrase for the Stellar network this contract is deployed + * to. + */ + networkPassphrase: string; + /** + * The URL of the RPC instance that will be used to interact with this + * contract. + */ + rpcUrl: string; + /** + * If true, will allow HTTP requests to the Soroban network. If false, will + * only allow HTTPS requests. + * @default false + */ + allowHttp?: boolean; + /** + * This gets filled in automatically from the ContractSpec when you + * instantiate a {@link Client}. + * + * Background: If the contract you're calling uses the `#[contracterror]` + * macro to create an `Error` enum, then those errors get included in the + * on-chain XDR that also describes your contract's methods. Each error will + * have a specific number. + * + * A Client makes method calls with an {@link module:contract.AssembledTransaction AssembledTransaction}. + * When one of these method calls encounters an error, `AssembledTransaction` + * will first attempt to parse the error as an "official" `contracterror` + * error, by using this passed-in `errorTypes` object. See + * {@link module:contract.AssembledTransaction#parseError parseError}. If `errorTypes` is blank or no + * matching error is found, then it will throw the raw error. + * @default {} + */ + errorTypes?: Record; +}; +/** + * Options for a smart contract method invocation. + * @memberof module:contract + */ +export type MethodOptions = { + /** + * The fee to pay for the transaction. + * @default 100 + */ + fee?: string; + /** + * The timebounds which should be set for transactions generated by this + * contract client. {@link module:contract#.DEFAULT_TIMEOUT} + * @default 300 + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the + * AssembledTransaction. + * @default true + */ + simulate?: boolean; + /** + * If true, will automatically attempt to restore the transaction if there + * are archived entries that need renewal. + * @default false + */ + restore?: boolean; +}; +export type AssembledTransactionOptions = MethodOptions & ClientOptions & { + method: string; + args?: any[]; + parseResultXdr: (xdr: xdr.ScVal) => T; + /** + * The address of the account that should sign the transaction. Useful when + * a wallet holds multiple addresses to ensure signing with the intended one. + */ + address?: string; + /** + * This option will be passed through to the SEP43-compatible wallet extension. If true, and if the wallet supports it, the transaction will be signed and immediately submitted to the network by the wallet, bypassing the submit logic in {@link SentTransaction}. + * @default false + */ + submit?: boolean; + /** + * The URL of the network to which the transaction should be submitted. + * Only applicable when 'submit' is set to true. + */ + submitUrl?: string; +}; +/** + * The default timebounds, in seconds, during which a transaction will be valid. + * This is attached to the transaction _before_ transaction simulation (it is + * needed for simulation to succeed). It is also re-calculated and re-added + * _before_ transaction signing. + * @constant {number} + * @default 300 + * @memberof module:contract + */ +export declare const DEFAULT_TIMEOUT: number; +/** + * An impossible account on the Stellar network + * @constant {string} + * @default GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF + * @memberof module:contract + */ +export declare const NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/types.js b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/types.js new file mode 100644 index 000000000..81a5b0f1c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/types.js @@ -0,0 +1,9 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NULL_ACCOUNT = exports.DEFAULT_TIMEOUT = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var DEFAULT_TIMEOUT = exports.DEFAULT_TIMEOUT = 5 * 60; +var NULL_ACCOUNT = exports.NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/utils.d.ts new file mode 100644 index 000000000..12ee8e61e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/utils.d.ts @@ -0,0 +1,46 @@ +import { xdr, Account } from "@stellar/stellar-base"; +import { Server } from "../rpc"; +import { AssembledTransactionOptions } from "./types"; +/** + * Keep calling a `fn` for `timeoutInSeconds` seconds, if `keepWaitingIf` is + * true. Returns an array of all attempts to call the function. + * @private + */ +export declare function withExponentialBackoff( +/** Function to call repeatedly */ +fn: (previousFailure?: T) => Promise, +/** Condition to check when deciding whether or not to call `fn` again */ +keepWaitingIf: (result: T) => boolean, +/** How long to wait between the first and second call */ +timeoutInSeconds: number, +/** What to multiply `timeoutInSeconds` by, each subsequent attempt */ +exponentialFactor?: number, +/** Whether to log extra info */ +verbose?: boolean): Promise; +/** + * If contracts are implemented using the `#[contracterror]` macro, then the + * errors get included in the on-chain XDR that also describes your contract's + * methods. Each error will have a specific number. This Regular Expression + * matches these "expected error types" that a contract may throw, and helps + * {@link AssembledTransaction} parse these errors. + * + * @constant {RegExp} + * @default "/Error\(Contract, #(\d+)\)/" + * @memberof module:contract.Client + */ +export declare const contractErrorPattern: RegExp; +/** + * A TypeScript type guard that checks if an object has a `toString` method. + * @private + */ +export declare function implementsToString( +/** some object that may or may not have a `toString` method */ +obj: unknown): obj is { + toString(): string; +}; +/** + * Reads a binary stream of ScSpecEntries into an array for processing by ContractSpec + * @private + */ +export declare function processSpecEntryStream(buffer: Buffer): xdr.ScSpecEntry[]; +export declare function getAccount(options: AssembledTransactionOptions, server: Server): Promise; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/contract/utils.js b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/utils.js new file mode 100644 index 000000000..8db862695 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/contract/utils.js @@ -0,0 +1,123 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.contractErrorPattern = void 0; +exports.getAccount = getAccount; +exports.implementsToString = implementsToString; +exports.processSpecEntryStream = processSpecEntryStream; +exports.withExponentialBackoff = withExponentialBackoff; +var _stellarBase = require("@stellar/stellar-base"); +var _types = require("./types"); +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function withExponentialBackoff(_x, _x2, _x3) { + return _withExponentialBackoff.apply(this, arguments); +} +function _withExponentialBackoff() { + _withExponentialBackoff = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(fn, keepWaitingIf, timeoutInSeconds) { + var exponentialFactor, + verbose, + attempts, + count, + waitUntil, + waitTime, + totalWaitTime, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + exponentialFactor = _args.length > 3 && _args[3] !== undefined ? _args[3] : 1.5; + verbose = _args.length > 4 && _args[4] !== undefined ? _args[4] : false; + attempts = []; + count = 0; + _context.t0 = attempts; + _context.next = 7; + return fn(); + case 7: + _context.t1 = _context.sent; + _context.t0.push.call(_context.t0, _context.t1); + if (keepWaitingIf(attempts[attempts.length - 1])) { + _context.next = 11; + break; + } + return _context.abrupt("return", attempts); + case 11: + waitUntil = new Date(Date.now() + timeoutInSeconds * 1000).valueOf(); + waitTime = 1000; + totalWaitTime = waitTime; + case 14: + if (!(Date.now() < waitUntil && keepWaitingIf(attempts[attempts.length - 1]))) { + _context.next = 30; + break; + } + count += 1; + if (verbose) { + console.info("Waiting ".concat(waitTime, "ms before trying again (bringing the total wait time to ").concat(totalWaitTime, "ms so far, of total ").concat(timeoutInSeconds * 1000, "ms)")); + } + _context.next = 19; + return new Promise(function (res) { + return setTimeout(res, waitTime); + }); + case 19: + waitTime *= exponentialFactor; + if (new Date(Date.now() + waitTime).valueOf() > waitUntil) { + waitTime = waitUntil - Date.now(); + if (verbose) { + console.info("was gonna wait too long; new waitTime: ".concat(waitTime, "ms")); + } + } + totalWaitTime = waitTime + totalWaitTime; + _context.t2 = attempts; + _context.next = 25; + return fn(attempts[attempts.length - 1]); + case 25: + _context.t3 = _context.sent; + _context.t2.push.call(_context.t2, _context.t3); + if (verbose && keepWaitingIf(attempts[attempts.length - 1])) { + console.info("".concat(count, ". Called ").concat(fn, "; ").concat(attempts.length, " prev attempts. Most recent: ").concat(JSON.stringify(attempts[attempts.length - 1], null, 2))); + } + _context.next = 14; + break; + case 30: + return _context.abrupt("return", attempts); + case 31: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _withExponentialBackoff.apply(this, arguments); +} +var contractErrorPattern = exports.contractErrorPattern = /Error\(Contract, #(\d+)\)/; +function implementsToString(obj) { + return _typeof(obj) === "object" && obj !== null && "toString" in obj; +} +function processSpecEntryStream(buffer) { + var reader = new _stellarBase.cereal.XdrReader(buffer); + var res = []; + while (!reader.eof) { + res.push(_stellarBase.xdr.ScSpecEntry.read(reader)); + } + return res; +} +function getAccount(_x4, _x5) { + return _getAccount.apply(this, arguments); +} +function _getAccount() { + _getAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(options, server) { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", options.publicKey ? server.getAccount(options.publicKey) : new _stellarBase.Account(_types.NULL_ACCOUNT, "0")); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _getAccount.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/errors/account_requires_memo.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/account_requires_memo.d.ts new file mode 100644 index 000000000..2c845d12f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/account_requires_memo.d.ts @@ -0,0 +1,24 @@ +/** + * AccountRequiresMemoError is raised when a transaction is trying to submit an + * operation to an account which requires a memo. See + * [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md) + * for more information. + * + * This error contains two attributes to help you identify the account requiring + * the memo and the operation where the account is the destination + * @category Errors + * + * @param {string} message Human-readable error message + * @param {string} accountId The account which requires a memo + * @param {number} operationIndex The index of the operation where `accountId` is the destination + * + * @example + * console.log('The following account requires a memo ', err.accountId) + * console.log('The account is used in operation: ', err.operationIndex) + */ +export declare class AccountRequiresMemoError extends Error { + __proto__: AccountRequiresMemoError; + accountId: string; + operationIndex: number; + constructor(message: string, accountId: string, operationIndex: number); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/errors/account_requires_memo.js b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/account_requires_memo.js new file mode 100644 index 000000000..669d85bc6 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/account_requires_memo.js @@ -0,0 +1,38 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AccountRequiresMemoError = void 0; +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var AccountRequiresMemoError = exports.AccountRequiresMemoError = function (_Error) { + function AccountRequiresMemoError(message, accountId, operationIndex) { + var _this; + _classCallCheck(this, AccountRequiresMemoError); + var trueProto = (this instanceof AccountRequiresMemoError ? this.constructor : void 0).prototype; + _this = _callSuper(this, AccountRequiresMemoError, [message]); + _this.__proto__ = trueProto; + _this.constructor = AccountRequiresMemoError; + _this.name = "AccountRequiresMemoError"; + _this.accountId = accountId; + _this.operationIndex = operationIndex; + return _this; + } + _inherits(AccountRequiresMemoError, _Error); + return _createClass(AccountRequiresMemoError); +}(_wrapNativeSuper(Error)); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/errors/bad_request.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/bad_request.d.ts new file mode 100644 index 000000000..4d1d320d5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/bad_request.d.ts @@ -0,0 +1,14 @@ +import { NetworkError } from "./network"; +/** + * BadRequestError is raised when a request made to Horizon is invalid in some + * way (incorrect timebounds for trade call builders, for example.) + * @augments NetworkError + * @inheritdoc + * @category Errors + * + * @param {string} message Human-readable error message + * @param {any} response Response details, received from the Horizon server + */ +export declare class BadRequestError extends NetworkError { + constructor(message: string, response: any); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/errors/bad_request.js b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/bad_request.js new file mode 100644 index 000000000..24aeb632c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/bad_request.js @@ -0,0 +1,34 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BadRequestError = void 0; +var _network = require("./network"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var BadRequestError = exports.BadRequestError = function (_NetworkError) { + function BadRequestError(message, response) { + var _this; + _classCallCheck(this, BadRequestError); + var trueProto = (this instanceof BadRequestError ? this.constructor : void 0).prototype; + _this = _callSuper(this, BadRequestError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadRequestError; + _this.name = "BadRequestError"; + return _this; + } + _inherits(BadRequestError, _NetworkError); + return _createClass(BadRequestError); +}(_network.NetworkError); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/errors/bad_response.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/bad_response.d.ts new file mode 100644 index 000000000..22de8f235 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/bad_response.d.ts @@ -0,0 +1,17 @@ +import { NetworkError } from "./network"; +/** + * BadResponseError is raised when a response from a + * {@link module:Horizon | Horizon} or {@link module:Federation | Federation} + * server is invalid in some way. For example, a federation response may exceed + * the maximum allowed size, or a transaction submission may have failed with + * Horizon. + * @augments NetworkError + * @inheritdoc + * @category Errors + * + * @param {string} message Human-readable error message. + * @param {any} response Response details, received from the server. + */ +export declare class BadResponseError extends NetworkError { + constructor(message: string, response: any); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/errors/bad_response.js b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/bad_response.js new file mode 100644 index 000000000..c7fbbacec --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/bad_response.js @@ -0,0 +1,34 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BadResponseError = void 0; +var _network = require("./network"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var BadResponseError = exports.BadResponseError = function (_NetworkError) { + function BadResponseError(message, response) { + var _this; + _classCallCheck(this, BadResponseError); + var trueProto = (this instanceof BadResponseError ? this.constructor : void 0).prototype; + _this = _callSuper(this, BadResponseError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadResponseError; + _this.name = "BadResponseError"; + return _this; + } + _inherits(BadResponseError, _NetworkError); + return _createClass(BadResponseError); +}(_network.NetworkError); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/errors/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/index.d.ts new file mode 100644 index 000000000..cb4f19458 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/index.d.ts @@ -0,0 +1,5 @@ +export * from "./network"; +export * from "./not_found"; +export * from "./bad_request"; +export * from "./bad_response"; +export * from "./account_requires_memo"; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/errors/index.js b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/index.js new file mode 100644 index 000000000..f0f9d584e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/index.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _network = require("./network"); +Object.keys(_network).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _network[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _network[key]; + } + }); +}); +var _not_found = require("./not_found"); +Object.keys(_not_found).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _not_found[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _not_found[key]; + } + }); +}); +var _bad_request = require("./bad_request"); +Object.keys(_bad_request).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _bad_request[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _bad_request[key]; + } + }); +}); +var _bad_response = require("./bad_response"); +Object.keys(_bad_response).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _bad_response[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _bad_response[key]; + } + }); +}); +var _account_requires_memo = require("./account_requires_memo"); +Object.keys(_account_requires_memo).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _account_requires_memo[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _account_requires_memo[key]; + } + }); +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/errors/network.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/network.d.ts new file mode 100644 index 000000000..fad4e7745 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/network.d.ts @@ -0,0 +1,33 @@ +import { HorizonApi } from "../horizon/horizon_api"; +/** + * NetworkError is raised when an interaction with a Horizon server has caused + * some kind of problem. + * @category Errors + * + * @param {string} message Human-readable error message + * @param {any} response Response details, received from the Horizon server. + * @param {HorizonApi.ErrorResponseData} [response.data] The data returned by Horizon as part of the error: {@link https://developers.stellar.org/docs/data/horizon/api-reference/errors/response | Error Response} + * @param {number} [response.status] HTTP status code describing the basic issue with a submitted transaction {@link https://developers.stellar.org/docs/data/horizon/api-reference/errors/http-status-codes/standard | Standard Status Codes} + * @param {string} [response.statusText] A human-readable description of what the status code means: {@link https://developers.stellar.org/docs/data/horizon/api-reference/errors/http-status-codes/horizon-specific | Horizon-Specific Status Codes} + * @param {string} [response.url] URL which can provide more information about the problem that occurred. + */ +export declare class NetworkError extends Error { + response: { + data?: HorizonApi.ErrorResponseData; + status?: number; + statusText?: string; + url?: string; + }; + __proto__: NetworkError; + constructor(message: string, response: any); + /** + * Returns the error response sent by the Horizon server. + * @returns {any} + */ + getResponse(): { + data?: HorizonApi.ErrorResponseData; + status?: number; + statusText?: string; + url?: string; + }; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/errors/network.js b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/network.js new file mode 100644 index 000000000..a26433617 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/network.js @@ -0,0 +1,41 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NetworkError = void 0; +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var NetworkError = exports.NetworkError = function (_Error) { + function NetworkError(message, response) { + var _this; + _classCallCheck(this, NetworkError); + var trueProto = (this instanceof NetworkError ? this.constructor : void 0).prototype; + _this = _callSuper(this, NetworkError, [message]); + _this.__proto__ = trueProto; + _this.constructor = NetworkError; + _this.response = response; + return _this; + } + _inherits(NetworkError, _Error); + return _createClass(NetworkError, [{ + key: "getResponse", + value: function getResponse() { + return this.response; + } + }]); +}(_wrapNativeSuper(Error)); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/errors/not_found.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/not_found.d.ts new file mode 100644 index 000000000..bca48d935 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/not_found.d.ts @@ -0,0 +1,14 @@ +import { NetworkError } from "./network"; +/** + * NotFoundError is raised when the resource requested from Horizon is + * unavailable. + * @augments NetworkError + * @inheritdoc + * @category Errors + * + * @param {string} message Human-readable error message + * @param {any} response Response details, received from the Horizon server + */ +export declare class NotFoundError extends NetworkError { + constructor(message: string, response: any); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/errors/not_found.js b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/not_found.js new file mode 100644 index 000000000..d828c18cf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/errors/not_found.js @@ -0,0 +1,34 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NotFoundError = void 0; +var _network = require("./network"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var NotFoundError = exports.NotFoundError = function (_NetworkError) { + function NotFoundError(message, response) { + var _this; + _classCallCheck(this, NotFoundError); + var trueProto = (this instanceof NotFoundError ? this.constructor : void 0).prototype; + _this = _callSuper(this, NotFoundError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = NotFoundError; + _this.name = "NotFoundError"; + return _this; + } + _inherits(NotFoundError, _NetworkError); + return _createClass(NotFoundError); +}(_network.NetworkError); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/federation/api.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/federation/api.d.ts new file mode 100644 index 000000000..f7feb38bf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/federation/api.d.ts @@ -0,0 +1,32 @@ +export declare namespace Api { + /** + * Record returned from a federation server. + */ + interface Record { + /** + * The Stellar public key resolved from the federation lookup + */ + account_id: string; + /** + * The type of memo, if any, required to send payments to this user + */ + memo_type?: string; + /** + * The memo value, if any, required to send payments to this user + */ + memo?: string; + } + /** + * Options for configuring connections to federation servers. You can also use {@link Config} class to set this globally. + */ + interface Options { + /** + * Allow connecting to http servers, default: `false`. This must be set to false in production deployments! + */ + allowHttp?: boolean; + /** + * Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue. + */ + timeout?: number; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/federation/api.js b/node_modules/@stellar/stellar-sdk/lib/minimal/federation/api.js new file mode 100644 index 000000000..081ac7fbf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/federation/api.js @@ -0,0 +1,7 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Api = void 0; +var Api; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/federation/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/federation/index.d.ts new file mode 100644 index 000000000..4eaff4f80 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/federation/index.d.ts @@ -0,0 +1,2 @@ +export { FederationServer as Server, FEDERATION_RESPONSE_MAX_SIZE } from './server'; +export * from './api'; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/federation/index.js b/node_modules/@stellar/stellar-sdk/lib/minimal/federation/index.js new file mode 100644 index 000000000..2d73772d2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/federation/index.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Server: true, + FEDERATION_RESPONSE_MAX_SIZE: true +}; +Object.defineProperty(exports, "FEDERATION_RESPONSE_MAX_SIZE", { + enumerable: true, + get: function get() { + return _server.FEDERATION_RESPONSE_MAX_SIZE; + } +}); +Object.defineProperty(exports, "Server", { + enumerable: true, + get: function get() { + return _server.FederationServer; + } +}); +var _server = require("./server"); +var _api = require("./api"); +Object.keys(_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _api[key]; + } + }); +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/federation/server.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/federation/server.d.ts new file mode 100644 index 000000000..bde8cb479 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/federation/server.d.ts @@ -0,0 +1,116 @@ +import { Api } from "./api"; +/** @module Federation */ +/** + * The maximum size of response from a federation server + * @default 102400 + */ +export declare const FEDERATION_RESPONSE_MAX_SIZE: number; +/** + * Federation.Server handles a network connection to a + * [federation server](https://developers.stellar.org/docs/learn/encyclopedia/federation) + * instance and exposes an interface for requests to that instance. + * + * @alias module:Federation.Server + * @memberof module:Federation + * @param {string} serverURL The federation server URL (ex. `https://acme.com/federation`). + * @param {string} domain Domain this server represents + * @param {Api.Options} [opts] Options object + * @returns {void} + */ +export declare class FederationServer { + /** + * The federation server URL (ex. `https://acme.com/federation`). + */ + private readonly serverURL; + /** + * Domain this server represents. + */ + private readonly domain; + /** + * Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue. + */ + private readonly timeout; + /** + * A helper method for handling user inputs that contain `destination` value. + * It accepts two types of values: + * + * * For Stellar address (ex. `bob*stellar.org`) it splits Stellar address and then tries to find information about + * federation server in `stellar.toml` file for a given domain. It returns a `Promise` which resolves if federation + * server exists and user has been found and rejects in all other cases. + * * For Account ID (ex. `GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS`) it returns a `Promise` which + * resolves if Account ID is valid and rejects in all other cases. Please note that this method does not check + * if the account actually exists in a ledger. + * + * @example + * StellarSdk.FederationServer.resolve('bob*stellar.org') + * .then(federationRecord => { + * // { + * // account_id: 'GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS', + * // memo_type: 'id', + * // memo: 100 + * // } + * }); + * + * @see Federation doc + * @see Stellar.toml doc + * @param {string} value Stellar Address (ex. `bob*stellar.org`) + * @param {object} [opts] Options object + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the provided account ID is not a valid Ed25519 public key. + */ + static resolve(value: string, opts?: Api.Options): Promise; + /** + * Creates a `FederationServer` instance based on information from + * [stellar.toml](https://developers.stellar.org/docs/issuing-assets/publishing-asset-info) + * file for a given domain. + * + * If `stellar.toml` file does not exist for a given domain or it does not + * contain information about a federation server Promise will reject. + * + * @example + * StellarSdk.FederationServer.createForDomain('acme.com') + * .then(federationServer => { + * // federationServer.resolveAddress('bob').then(...) + * }) + * .catch(error => { + * // stellar.toml does not exist or it does not contain information about federation server. + * }); + * + * @see Stellar.toml doc + * @param {string} domain Domain to get federation server for + * @param {module:Federation.Api.Options} [opts] Options object + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the domain's stellar.toml file does not contain a federation server field. + */ + static createForDomain(domain: string, opts?: Api.Options): Promise; + constructor(serverURL: string, domain: string, opts?: Api.Options); + /** + * Get the federation record if the user was found for a given Stellar address + * @see Federation doc + * @param {string} address Stellar address (ex. `bob*stellar.org`). If `FederationServer` was instantiated with `domain` param only username (ex. `bob`) can be passed. + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the federated address does not contain a domain, or if the server object was not instantiated with a `domain` parameter + */ + resolveAddress(address: string): Promise; + /** + * Given an account ID, get their federation record if the user was found + * @see Federation doc + * @param {string} accountId Account ID (ex. `GBYNR2QJXLBCBTRN44MRORCMI4YO7FZPFBCNOKTOBCAAFC7KC3LNPRYS`) + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the federation server returns an invalid memo value. + * @throws Will throw an error if the federation server's response exceeds the allowed maximum size. + * @throws {BadResponseError} Will throw an error if the server query fails with an improper response. + */ + resolveAccountId(accountId: string): Promise; + /** + * Given a transactionId, get the federation record if the sender of the transaction was found + * @see Federation doc + * @param {string} transactionId Transaction ID (ex. `3389e9f0f1a65f19736cacf544c2e825313e8447f569233bb8db39aa607c8889`) + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the federation server returns an invalid memo value. + * @throws Will throw an error if the federation server's response exceeds the allowed maximum size. + * @throws {BadResponseError} Will throw an error if the server query fails with an improper response. + */ + resolveTransactionId(transactionId: string): Promise; + private _sendRequest; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/federation/server.js b/node_modules/@stellar/stellar-sdk/lib/minimal/federation/server.js new file mode 100644 index 000000000..36d7789cd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/federation/server.js @@ -0,0 +1,252 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FederationServer = exports.FEDERATION_RESPONSE_MAX_SIZE = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _urijs = _interopRequireDefault(require("urijs")); +var _config = require("../config"); +var _errors = require("../errors"); +var _stellartoml = require("../stellartoml"); +var _httpClient = require("../http-client"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var FEDERATION_RESPONSE_MAX_SIZE = exports.FEDERATION_RESPONSE_MAX_SIZE = 100 * 1024; +var FederationServer = exports.FederationServer = function () { + function FederationServer(serverURL, domain) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + _classCallCheck(this, FederationServer); + this.serverURL = (0, _urijs.default)(serverURL); + this.domain = domain; + var allowHttp = typeof opts.allowHttp === "undefined" ? _config.Config.isAllowHttp() : opts.allowHttp; + this.timeout = typeof opts.timeout === "undefined" ? _config.Config.getTimeout() : opts.timeout; + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure federation server"); + } + } + return _createClass(FederationServer, [{ + key: "resolveAddress", + value: (function () { + var _resolveAddress = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(address) { + var stellarAddress, url; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + stellarAddress = address; + if (!(address.indexOf("*") < 0)) { + _context.next = 5; + break; + } + if (this.domain) { + _context.next = 4; + break; + } + return _context.abrupt("return", Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object."))); + case 4: + stellarAddress = "".concat(address, "*").concat(this.domain); + case 5: + url = this.serverURL.query({ + type: "name", + q: stellarAddress + }); + return _context.abrupt("return", this._sendRequest(url)); + case 7: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function resolveAddress(_x) { + return _resolveAddress.apply(this, arguments); + } + return resolveAddress; + }()) + }, { + key: "resolveAccountId", + value: (function () { + var _resolveAccountId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(accountId) { + var url; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + url = this.serverURL.query({ + type: "id", + q: accountId + }); + return _context2.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function resolveAccountId(_x2) { + return _resolveAccountId.apply(this, arguments); + } + return resolveAccountId; + }()) + }, { + key: "resolveTransactionId", + value: (function () { + var _resolveTransactionId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(transactionId) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = this.serverURL.query({ + type: "txid", + q: transactionId + }); + return _context3.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function resolveTransactionId(_x3) { + return _resolveTransactionId.apply(this, arguments); + } + return resolveTransactionId; + }()) + }, { + key: "_sendRequest", + value: function () { + var _sendRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(url) { + var timeout; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + timeout = this.timeout; + return _context4.abrupt("return", _httpClient.httpClient.get(url.toString(), { + maxContentLength: FEDERATION_RESPONSE_MAX_SIZE, + timeout: timeout + }).then(function (response) { + if (typeof response.data.memo !== "undefined" && typeof response.data.memo !== "string") { + throw new Error("memo value should be of type string"); + } + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + if (response.message.match(/^maxContentLength size/)) { + throw new Error("federation response exceeds allowed size of ".concat(FEDERATION_RESPONSE_MAX_SIZE)); + } else { + return Promise.reject(response); + } + } else { + return Promise.reject(new _errors.BadResponseError("Server query failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + } + })); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function _sendRequest(_x4) { + return _sendRequest2.apply(this, arguments); + } + return _sendRequest; + }() + }], [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(value) { + var opts, + addressParts, + _addressParts, + domain, + federationServer, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {}; + if (!(value.indexOf("*") < 0)) { + _context5.next = 5; + break; + } + if (_stellarBase.StrKey.isValidEd25519PublicKey(value)) { + _context5.next = 4; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Account ID"))); + case 4: + return _context5.abrupt("return", Promise.resolve({ + account_id: value + })); + case 5: + addressParts = value.split("*"); + _addressParts = _slicedToArray(addressParts, 2), domain = _addressParts[1]; + if (!(addressParts.length !== 2 || !domain)) { + _context5.next = 9; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Stellar address"))); + case 9: + _context5.next = 11; + return FederationServer.createForDomain(domain, opts); + case 11: + federationServer = _context5.sent; + return _context5.abrupt("return", federationServer.resolveAddress(value)); + case 13: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function resolve(_x5) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }, { + key: "createForDomain", + value: (function () { + var _createForDomain = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(domain) { + var opts, + tomlObject, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : {}; + _context6.next = 3; + return _stellartoml.Resolver.resolve(domain, opts); + case 3: + tomlObject = _context6.sent; + if (tomlObject.FEDERATION_SERVER) { + _context6.next = 6; + break; + } + return _context6.abrupt("return", Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field"))); + case 6: + return _context6.abrupt("return", new FederationServer(tomlObject.FEDERATION_SERVER, domain, opts)); + case 7: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function createForDomain(_x6) { + return _createForDomain.apply(this, arguments); + } + return createForDomain; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/friendbot/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/friendbot/index.d.ts new file mode 100644 index 000000000..5181343e0 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/friendbot/index.d.ts @@ -0,0 +1,6 @@ +export declare namespace Api { + interface Response { + hash: string; + result_meta_xdr: string; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/friendbot/index.js b/node_modules/@stellar/stellar-sdk/lib/minimal/friendbot/index.js new file mode 100644 index 000000000..081ac7fbf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/friendbot/index.js @@ -0,0 +1,7 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Api = void 0; +var Api; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/account_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/account_call_builder.d.ts new file mode 100644 index 000000000..87c625f4f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/account_call_builder.d.ts @@ -0,0 +1,56 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link AccountCallBuilder} pointed to server defined by `serverUrl`. + * + * Do not create this object directly, use {@link Horizon.Server#accounts}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|All Accounts} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class AccountCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Returns information and links relating to a single account. + * The balances section in the returned JSON will also list all the trust lines this account has set up. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-an-account|Account Details} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {CallBuilder} a new CallBuilder instance for the /accounts/:id endpoint + */ + accountId(id: string): CallBuilder; + /** + * This endpoint filters accounts by signer account. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|Accounts} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + forSigner(id: string): this; + /** + * This endpoint filters all accounts who are trustees to an asset. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|Accounts} + * @see Asset + * @param {Asset} asset For example: `new Asset('USD','GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD')` + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + forAsset(asset: Asset): this; + /** + * This endpoint filters accounts where the given account is sponsoring the account or any of its sub-entries.. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|Accounts} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + sponsor(id: string): this; + /** + * This endpoint filters accounts holding a trustline to the given liquidity pool. + * + * @param {string} id The ID of the liquidity pool. For example: `dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7`. + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + forLiquidityPool(id: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/account_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/account_call_builder.js new file mode 100644 index 000000000..cdf9aa78a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/account_call_builder.js @@ -0,0 +1,62 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AccountCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var AccountCallBuilder = exports.AccountCallBuilder = function (_CallBuilder) { + function AccountCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, AccountCallBuilder); + _this = _callSuper(this, AccountCallBuilder, [serverUrl]); + _this.url.segment("accounts"); + return _this; + } + _inherits(AccountCallBuilder, _CallBuilder); + return _createClass(AccountCallBuilder, [{ + key: "accountId", + value: function accountId(id) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([id]); + return builder; + } + }, { + key: "forSigner", + value: function forSigner(id) { + this.url.setQuery("signer", id); + return this; + } + }, { + key: "forAsset", + value: function forAsset(asset) { + this.url.setQuery("asset", "".concat(asset)); + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(id) { + this.url.setQuery("liquidity_pool", id); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/account_response.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/account_response.d.ts new file mode 100644 index 000000000..a5a448de4 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/account_response.d.ts @@ -0,0 +1,61 @@ +import { HorizonApi } from "./horizon_api"; +import { ServerApi } from "./server_api"; +/** + * Do not create this object directly, use {@link module:Horizon.Server#loadAccount | Horizon.Server#loadAccount}. + * + * Returns information and links relating to a single account. + * The balances section in the returned JSON will also list all the trust lines this account has set up. + * It also contains {@link BaseAccount} object and exposes it's methods so can be used in {@link TransactionBuilder}. + * + * @memberof module:Horizon + * @private + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/accounts/object|Account Details} + * @param {string} response Response from horizon account endpoint. + * @returns {AccountResponse} AccountResponse instance + */ +export declare class AccountResponse { + readonly id: string; + readonly paging_token: string; + readonly account_id: string; + sequence: string; + readonly sequence_ledger?: number; + readonly sequence_time?: string; + readonly subentry_count: number; + readonly home_domain?: string; + readonly inflation_destination?: string; + readonly last_modified_ledger: number; + readonly last_modified_time: string; + readonly thresholds: HorizonApi.AccountThresholds; + readonly flags: HorizonApi.Flags; + readonly balances: HorizonApi.BalanceLine[]; + readonly signers: ServerApi.AccountRecordSigners[]; + readonly data: (options: { + value: string; + }) => Promise<{ + value: string; + }>; + readonly data_attr: Record; + readonly effects: ServerApi.CallCollectionFunction; + readonly offers: ServerApi.CallCollectionFunction; + readonly operations: ServerApi.CallCollectionFunction; + readonly payments: ServerApi.CallCollectionFunction; + readonly trades: ServerApi.CallCollectionFunction; + private readonly _baseAccount; + constructor(response: ServerApi.AccountRecord); + /** + * Get Stellar account public key ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA` + * @returns {string} accountId + */ + accountId(): string; + /** + * Get the current sequence number + * @returns {string} sequenceNumber + */ + sequenceNumber(): string; + /** + * Increments sequence number in this object by one. + * @returns {void} + */ + incrementSequenceNumber(): void; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/account_response.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/account_response.js new file mode 100644 index 000000000..682b46360 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/account_response.js @@ -0,0 +1,49 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AccountResponse = void 0; +var _stellarBase = require("@stellar/stellar-base"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var AccountResponse = exports.AccountResponse = function () { + function AccountResponse(response) { + var _this = this; + _classCallCheck(this, AccountResponse); + this._baseAccount = new _stellarBase.Account(response.account_id, response.sequence); + Object.entries(response).forEach(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + _this[key] = value; + }); + } + return _createClass(AccountResponse, [{ + key: "accountId", + value: function accountId() { + return this._baseAccount.accountId(); + } + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this._baseAccount.sequenceNumber(); + } + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + this._baseAccount.incrementSequenceNumber(); + this.sequence = this._baseAccount.sequenceNumber(); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/assets_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/assets_call_builder.d.ts new file mode 100644 index 000000000..38c7f9f14 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/assets_call_builder.d.ts @@ -0,0 +1,27 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link AssetsCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#assets}. + * + * @class + * @augments CallBuilder + * @private + * @param {string} serverUrl Horizon server URL. + */ +export declare class AssetsCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * This endpoint filters all assets by the asset code. + * @param {string} value For example: `USD` + * @returns {AssetsCallBuilder} current AssetCallBuilder instance + */ + forCode(value: string): AssetsCallBuilder; + /** + * This endpoint filters all assets by the asset issuer. + * @param {string} value For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {AssetsCallBuilder} current AssetCallBuilder instance + */ + forIssuer(value: string): AssetsCallBuilder; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/assets_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/assets_call_builder.js new file mode 100644 index 000000000..68d89ba1f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/assets_call_builder.js @@ -0,0 +1,43 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AssetsCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var AssetsCallBuilder = exports.AssetsCallBuilder = function (_CallBuilder) { + function AssetsCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, AssetsCallBuilder); + _this = _callSuper(this, AssetsCallBuilder, [serverUrl]); + _this.url.segment("assets"); + return _this; + } + _inherits(AssetsCallBuilder, _CallBuilder); + return _createClass(AssetsCallBuilder, [{ + key: "forCode", + value: function forCode(value) { + this.url.setQuery("asset_code", value); + return this; + } + }, { + key: "forIssuer", + value: function forIssuer(value) { + this.url.setQuery("asset_issuer", value); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/call_builder.d.ts new file mode 100644 index 000000000..f40d6db20 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/call_builder.d.ts @@ -0,0 +1,128 @@ +import URI from "urijs"; +import { HorizonApi } from "./horizon_api"; +import { ServerApi } from "./server_api"; +export interface EventSourceOptions { + onmessage?: (value: T) => void; + onerror?: (event: MessageEvent) => void; + reconnectTimeout?: number; +} +/** + * Creates a new {@link CallBuilder} pointed to server defined by serverUrl. + * + * This is an **abstract** class. Do not create this object directly, use {@link Server} class. + * @param {string} serverUrl URL of Horizon server + * @class CallBuilder + */ +export declare class CallBuilder> { + protected url: URI; + filter: string[][]; + protected originalSegments: string[]; + protected neighborRoot: string; + constructor(serverUrl: URI, neighborRoot?: string); + /** + * Triggers a HTTP request using this builder's current configuration. + * @returns {Promise} a Promise that resolves to the server's response. + */ + call(): Promise; + /** + * Creates an EventSource that listens for incoming messages from the server. To stop listening for new + * events call the function returned by this method. + * @see [Horizon Response Format](https://developers.stellar.org/api/introduction/response-format/) + * @see [MDN EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) + * @param {object} [options] EventSource options. + * @param {Function} [options.onmessage] Callback function to handle incoming messages. + * @param {Function} [options.onerror] Callback function to handle errors. + * @param {number} [options.reconnectTimeout] Custom stream connection timeout in ms, default is 15 seconds. + * @returns {Function} Close function. Run to close the connection and stop listening for new events. + */ + stream(options?: EventSourceOptions ? U : T>): () => void; + /** + * Sets `cursor` parameter for the current call. Returns the CallBuilder object on which this method has been called. + * @see [Paging](https://developers.stellar.org/api/introduction/pagination/) + * @param {string} cursor A cursor is a value that points to a specific location in a collection of resources. + * @returns {object} current CallBuilder instance + */ + cursor(cursor: string): this; + /** + * Sets `limit` parameter for the current call. Returns the CallBuilder object on which this method has been called. + * @see [Paging](https://developers.stellar.org/api/introduction/pagination/) + * @param {number} recordsNumber Number of records the server should return. + * @returns {object} current CallBuilder instance + */ + limit(recordsNumber: number): this; + /** + * Sets `order` parameter for the current call. Returns the CallBuilder object on which this method has been called. + * @param {"asc"|"desc"} direction Sort direction + * @returns {object} current CallBuilder instance + */ + order(direction: "asc" | "desc"): this; + /** + * Sets `join` parameter for the current call. The `join` parameter + * includes the requested resource in the response. Currently, the + * only valid value for the parameter is `transactions` and is only + * supported on the operations and payments endpoints. The response + * will include a `transaction` field for each operation in the + * response. + * + * @param "include" join Records to be included in the response. + * @returns {object} current CallBuilder instance. + */ + join(include: "transactions"): this; + /** + * A helper method to craft queries to "neighbor" endpoints. + * + * For example, we have an `/effects` suffix endpoint on many different + * "root" endpoints, such as `/transactions/:id` and `/accounts/:id`. So, + * it's helpful to be able to conveniently create queries to the + * `/accounts/:id/effects` endpoint: + * + * this.forEndpoint("accounts", accountId)`. + * + * @param {string} endpoint neighbor endpoint in question, like /operations + * @param {string} param filter parameter, like an operation ID + * + * @returns {CallBuilder} this CallBuilder instance + */ + protected forEndpoint(endpoint: string, param: string): this; + /** + * @private + * @returns {void} + */ + private checkFilter; + /** + * Convert a link object to a function that fetches that link. + * @private + * @param {object} link A link object + * @param {boolean} link.href the URI of the link + * @param {boolean} [link.templated] Whether the link is templated + * @returns {Function} A function that requests the link + */ + private _requestFnForLink; + /** + * Given the json response, find and convert each link into a function that + * calls that link. + * @private + * @param {object} json JSON response + * @returns {object} JSON response with string links replaced with functions + */ + private _parseRecord; + private _sendNormalRequest; + /** + * @private + * @param {object} json Response object + * @returns {object} Extended response + */ + private _parseResponse; + /** + * @private + * @param {object} json Response object + * @returns {object} Extended response object + */ + private _toCollectionPage; + /** + * @private + * @param {object} error Network error object + * @returns {Promise} Promise that rejects with a human-readable error + */ + private _handleNetworkError; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/call_builder.js new file mode 100644 index 000000000..ba9cda7a4 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/call_builder.js @@ -0,0 +1,362 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.CallBuilder = void 0; +var _urijs = _interopRequireDefault(require("urijs")); +var _URITemplate = _interopRequireDefault(require("urijs/src/URITemplate")); +var _errors = require("../errors"); +var _horizon_axios_client = require("./horizon_axios_client"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var JOINABLE = ["transaction"]; +var anyGlobal = global; +var EventSource; +if (typeof false !== 'undefined' && false) { + var _ref, _anyGlobal$EventSourc, _anyGlobal$window; + EventSource = (_ref = (_anyGlobal$EventSourc = anyGlobal.EventSource) !== null && _anyGlobal$EventSourc !== void 0 ? _anyGlobal$EventSourc : (_anyGlobal$window = anyGlobal.window) === null || _anyGlobal$window === void 0 ? void 0 : _anyGlobal$window.EventSource) !== null && _ref !== void 0 ? _ref : require("eventsource"); +} +var CallBuilder = exports.CallBuilder = function () { + function CallBuilder(serverUrl) { + var neighborRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; + _classCallCheck(this, CallBuilder); + this.url = serverUrl.clone(); + this.filter = []; + this.originalSegments = this.url.segment() || []; + this.neighborRoot = neighborRoot; + } + return _createClass(CallBuilder, [{ + key: "call", + value: function call() { + var _this = this; + this.checkFilter(); + return this._sendNormalRequest(this.url).then(function (r) { + return _this._parseResponse(r); + }); + } + }, { + key: "stream", + value: function stream() { + var _this2 = this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (EventSource === undefined) { + throw new Error("Streaming requires eventsource to be enabled. If you need this functionality, compile with USE_EVENTSOURCE=true."); + } + this.checkFilter(); + this.url.setQuery("X-Client-Name", "js-stellar-sdk"); + this.url.setQuery("X-Client-Version", _horizon_axios_client.version); + var es; + var timeout; + var createTimeout = function createTimeout() { + timeout = setTimeout(function () { + var _es; + (_es = es) === null || _es === void 0 || _es.close(); + es = _createEventSource(); + }, options.reconnectTimeout || 15 * 1000); + }; + var _createEventSource = function createEventSource() { + try { + es = new EventSource(_this2.url.toString()); + } catch (err) { + if (options.onerror) { + options.onerror(err); + } + } + createTimeout(); + if (!es) { + return es; + } + var closed = false; + var onClose = function onClose() { + if (closed) { + return; + } + clearTimeout(timeout); + es.close(); + _createEventSource(); + closed = true; + }; + var onMessage = function onMessage(message) { + if (message.type === "close") { + onClose(); + return; + } + var result = message.data ? _this2._parseRecord(JSON.parse(message.data)) : message; + if (result.paging_token) { + _this2.url.setQuery("cursor", result.paging_token); + } + clearTimeout(timeout); + createTimeout(); + if (typeof options.onmessage !== "undefined") { + options.onmessage(result); + } + }; + var onError = function onError(error) { + if (options.onerror) { + options.onerror(error); + } + }; + if (es.addEventListener) { + es.addEventListener("message", onMessage.bind(_this2)); + es.addEventListener("error", onError.bind(_this2)); + es.addEventListener("close", onClose.bind(_this2)); + } else { + es.onmessage = onMessage.bind(_this2); + es.onerror = onError.bind(_this2); + } + return es; + }; + _createEventSource(); + return function () { + var _es2; + clearTimeout(timeout); + (_es2 = es) === null || _es2 === void 0 || _es2.close(); + }; + } + }, { + key: "cursor", + value: function cursor(_cursor) { + this.url.setQuery("cursor", _cursor); + return this; + } + }, { + key: "limit", + value: function limit(recordsNumber) { + this.url.setQuery("limit", recordsNumber.toString()); + return this; + } + }, { + key: "order", + value: function order(direction) { + this.url.setQuery("order", direction); + return this; + } + }, { + key: "join", + value: function join(include) { + this.url.setQuery("join", include); + return this; + } + }, { + key: "forEndpoint", + value: function forEndpoint(endpoint, param) { + if (this.neighborRoot === "") { + throw new Error("Invalid usage: neighborRoot not set in constructor"); + } + this.filter.push([endpoint, param, this.neighborRoot]); + return this; + } + }, { + key: "checkFilter", + value: function checkFilter() { + if (this.filter.length >= 2) { + throw new _errors.BadRequestError("Too many filters specified", this.filter); + } + if (this.filter.length === 1) { + var newSegment = this.originalSegments.concat(this.filter[0]); + this.url.segment(newSegment); + } + } + }, { + key: "_requestFnForLink", + value: function _requestFnForLink(link) { + var _this3 = this; + return _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var opts, + uri, + template, + r, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}; + if (link.templated) { + template = (0, _URITemplate.default)(link.href); + uri = (0, _urijs.default)(template.expand(opts)); + } else { + uri = (0, _urijs.default)(link.href); + } + _context.next = 4; + return _this3._sendNormalRequest(uri); + case 4: + r = _context.sent; + return _context.abrupt("return", _this3._parseResponse(r)); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + } + }, { + key: "_parseRecord", + value: function _parseRecord(json) { + var _this4 = this; + if (!json._links) { + return json; + } + Object.keys(json._links).forEach(function (key) { + var n = json._links[key]; + var included = false; + if (typeof json[key] !== "undefined") { + json["".concat(key, "_attr")] = json[key]; + included = true; + } + if (included && JOINABLE.indexOf(key) >= 0) { + var record = _this4._parseRecord(json[key]); + json[key] = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", record); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + } else { + json[key] = _this4._requestFnForLink(n); + } + }); + return json; + } + }, { + key: "_sendNormalRequest", + value: function () { + var _sendNormalRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(initialUrl) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = initialUrl; + if (url.authority() === "") { + url = url.authority(this.url.authority()); + } + if (url.protocol() === "") { + url = url.protocol(this.url.protocol()); + } + return _context3.abrupt("return", _horizon_axios_client.AxiosClient.get(url.toString()).then(function (response) { + return response.data; + }).catch(this._handleNetworkError)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function _sendNormalRequest(_x) { + return _sendNormalRequest2.apply(this, arguments); + } + return _sendNormalRequest; + }() + }, { + key: "_parseResponse", + value: function _parseResponse(json) { + if (json._embedded && json._embedded.records) { + return this._toCollectionPage(json); + } + return this._parseRecord(json); + } + }, { + key: "_toCollectionPage", + value: function _toCollectionPage(json) { + var _this5 = this; + for (var i = 0; i < json._embedded.records.length; i += 1) { + json._embedded.records[i] = this._parseRecord(json._embedded.records[i]); + } + return { + records: json._embedded.records, + next: function () { + var _next2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + var r; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this5._sendNormalRequest((0, _urijs.default)(json._links.next.href)); + case 2: + r = _context4.sent; + return _context4.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function next() { + return _next2.apply(this, arguments); + } + return next; + }(), + prev: function () { + var _prev = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5() { + var r; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return _this5._sendNormalRequest((0, _urijs.default)(json._links.prev.href)); + case 2: + r = _context5.sent; + return _context5.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function prev() { + return _prev.apply(this, arguments); + } + return prev; + }() + }; + } + }, { + key: "_handleNetworkError", + value: (function () { + var _handleNetworkError2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(error) { + var _error$response$statu, _error$response$statu2; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + if (!(error.response && error.response.status)) { + _context6.next = 8; + break; + } + _context6.t0 = error.response.status; + _context6.next = _context6.t0 === 404 ? 4 : 5; + break; + case 4: + return _context6.abrupt("return", Promise.reject(new _errors.NotFoundError((_error$response$statu = error.response.statusText) !== null && _error$response$statu !== void 0 ? _error$response$statu : "Not Found", error.response.data))); + case 5: + return _context6.abrupt("return", Promise.reject(new _errors.NetworkError((_error$response$statu2 = error.response.statusText) !== null && _error$response$statu2 !== void 0 ? _error$response$statu2 : "Unknown", error.response.data))); + case 6: + _context6.next = 9; + break; + case 8: + return _context6.abrupt("return", Promise.reject(new Error(error.message))); + case 9: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function _handleNetworkError(_x2) { + return _handleNetworkError2.apply(this, arguments); + } + return _handleNetworkError; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/claimable_balances_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/claimable_balances_call_builder.d.ts new file mode 100644 index 000000000..6e5f7eea7 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/claimable_balances_call_builder.d.ts @@ -0,0 +1,50 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link ClaimableBalanceCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#claimableBalances}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/claimablebalances|Claimable Balances} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class ClaimableBalanceCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The claimable balance details endpoint provides information on a single claimable balance. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-claimable-balance|Claimable Balance Details} + * @param {string} claimableBalanceId Claimable balance ID + * @returns {CallBuilder} CallBuilder OperationCallBuilder instance + */ + claimableBalance(claimableBalanceId: string): CallBuilder; + /** + * Returns all claimable balances which are sponsored by the given account ID. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-claimable-balances|Claimable Balances} + * @param {string} sponsor For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance + */ + sponsor(sponsor: string): this; + /** + * Returns all claimable balances which can be claimed by the given account ID. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-claimable-balances|Claimable Balances} + * @param {string} claimant For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance + */ + claimant(claimant: string): this; + /** + * Returns all claimable balances which provide a balance for the given asset. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-claimable-balances|Claimable Balances} + * @param {Asset} asset The Asset held by the claimable balance + * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance + */ + asset(asset: Asset): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/claimable_balances_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/claimable_balances_call_builder.js new file mode 100644 index 000000000..188c8076a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/claimable_balances_call_builder.js @@ -0,0 +1,56 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ClaimableBalanceCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var ClaimableBalanceCallBuilder = exports.ClaimableBalanceCallBuilder = function (_CallBuilder) { + function ClaimableBalanceCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, ClaimableBalanceCallBuilder); + _this = _callSuper(this, ClaimableBalanceCallBuilder, [serverUrl]); + _this.url.segment("claimable_balances"); + return _this; + } + _inherits(ClaimableBalanceCallBuilder, _CallBuilder); + return _createClass(ClaimableBalanceCallBuilder, [{ + key: "claimableBalance", + value: function claimableBalance(claimableBalanceId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([claimableBalanceId]); + return builder; + } + }, { + key: "sponsor", + value: function sponsor(_sponsor) { + this.url.setQuery("sponsor", _sponsor); + return this; + } + }, { + key: "claimant", + value: function claimant(_claimant) { + this.url.setQuery("claimant", _claimant); + return this; + } + }, { + key: "asset", + value: function asset(_asset) { + this.url.setQuery("asset", _asset.toString()); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/effect_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/effect_call_builder.d.ts new file mode 100644 index 000000000..8f1e56266 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/effect_call_builder.d.ts @@ -0,0 +1,53 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link EffectCallBuilder} pointed to server defined by serverUrl. + * Do not create this object directly, use {@link Horizon.Server#effects}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/effects|All Effects} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class EffectCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * This endpoint represents all effects that changed a given account. It will return relevant effects from the creation of the account to the current ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-effects-by-account-id|Effects for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * Effects are the specific ways that the ledger was changed by any operation. + * + * This endpoint represents all effects that occurred in the given ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-ledgers-effects|Effects for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all effects that occurred as a result of a given transaction. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-transactions-effects|Effects for Transaction} + * @param {string} transactionId Transaction ID + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forTransaction(transactionId: string): this; + /** + * This endpoint represents all effects that occurred as a result of a given operation. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-an-operations-effects|Effects for Operation} + * @param {number} operationId Operation ID + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forOperation(operationId: string): this; + /** + * This endpoint represents all effects involving a particular liquidity pool. + * + * @param {string} poolId liquidity pool ID + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forLiquidityPool(poolId: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/effect_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/effect_call_builder.js new file mode 100644 index 000000000..147128700 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/effect_call_builder.js @@ -0,0 +1,56 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.EffectCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var EffectCallBuilder = exports.EffectCallBuilder = function (_CallBuilder) { + function EffectCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, EffectCallBuilder); + _this = _callSuper(this, EffectCallBuilder, [serverUrl, "effects"]); + _this.url.segment("effects"); + return _this; + } + _inherits(EffectCallBuilder, _CallBuilder); + return _createClass(EffectCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forOperation", + value: function forOperation(operationId) { + return this.forEndpoint("operations", operationId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/friendbot_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/friendbot_builder.d.ts new file mode 100644 index 000000000..30e5addb9 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/friendbot_builder.d.ts @@ -0,0 +1,4 @@ +import { CallBuilder } from "./call_builder"; +export declare class FriendbotBuilder extends CallBuilder { + constructor(serverUrl: URI, address: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/friendbot_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/friendbot_builder.js new file mode 100644 index 000000000..f80bd06f8 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/friendbot_builder.js @@ -0,0 +1,32 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FriendbotBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var FriendbotBuilder = exports.FriendbotBuilder = function (_CallBuilder) { + function FriendbotBuilder(serverUrl, address) { + var _this; + _classCallCheck(this, FriendbotBuilder); + _this = _callSuper(this, FriendbotBuilder, [serverUrl]); + _this.url.segment("friendbot"); + _this.url.setQuery("addr", address); + return _this; + } + _inherits(FriendbotBuilder, _CallBuilder); + return _createClass(FriendbotBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/horizon_api.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/horizon_api.d.ts new file mode 100644 index 000000000..d52968614 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/horizon_api.d.ts @@ -0,0 +1,540 @@ +import { AssetType, MemoType } from "@stellar/stellar-base"; +export declare namespace HorizonApi { + interface ResponseLink { + href: string; + templated?: boolean; + } + interface BaseResponse { + _links: { + [key in T | "self"]: ResponseLink; + }; + } + interface SubmitTransactionResponse { + hash: string; + ledger: number; + successful: boolean; + envelope_xdr: string; + result_xdr: string; + result_meta_xdr: string; + paging_token: string; + } + interface SubmitAsyncTransactionResponse { + hash: string; + tx_status: string; + error_result_xdr: string; + } + interface FeeBumpTransactionResponse { + hash: string; + signatures: string[]; + } + interface InnerTransactionResponse { + hash: string; + signatures: string[]; + max_fee: string; + } + interface TransactionPreconditions { + timebounds?: { + min_time: string; + max_time: string; + }; + ledgerbounds?: { + min_ledger: number; + max_ledger: number; + }; + min_account_sequence?: string; + min_account_sequence_age?: string; + min_account_sequence_ledger_gap?: number; + extra_signers?: string[]; + } + interface TransactionResponse extends SubmitTransactionResponse, BaseResponse<"account" | "ledger" | "operations" | "effects" | "succeeds" | "precedes"> { + created_at: string; + fee_meta_xdr: string; + fee_charged: number | string; + max_fee: number | string; + id: string; + memo_type: MemoType; + memo?: string; + memo_bytes?: string; + operation_count: number; + paging_token: string; + signatures: string[]; + source_account: string; + source_account_sequence: string; + fee_account: string; + inner_transaction?: InnerTransactionResponse; + fee_bump_transaction?: FeeBumpTransactionResponse; + preconditions?: TransactionPreconditions; + } + interface BalanceLineNative { + balance: string; + asset_type: AssetType.native; + buying_liabilities: string; + selling_liabilities: string; + } + interface BalanceLineLiquidityPool { + liquidity_pool_id: string; + asset_type: AssetType.liquidityPoolShares; + balance: string; + limit: string; + last_modified_ledger: number; + is_authorized: boolean; + is_authorized_to_maintain_liabilities: boolean; + is_clawback_enabled: boolean; + sponsor?: string; + } + interface BalanceLineAsset { + balance: string; + limit: string; + asset_type: T; + asset_code: string; + asset_issuer: string; + buying_liabilities: string; + selling_liabilities: string; + last_modified_ledger: number; + is_authorized: boolean; + is_authorized_to_maintain_liabilities: boolean; + is_clawback_enabled: boolean; + sponsor?: string; + } + type BalanceLine = T extends AssetType.native ? BalanceLineNative : T extends AssetType.credit4 | AssetType.credit12 ? BalanceLineAsset : T extends AssetType.liquidityPoolShares ? BalanceLineLiquidityPool : BalanceLineNative | BalanceLineAsset | BalanceLineLiquidityPool; + interface AssetAccounts { + authorized: number; + authorized_to_maintain_liabilities: number; + unauthorized: number; + } + interface AssetBalances { + authorized: string; + authorized_to_maintain_liabilities: string; + unauthorized: string; + } + interface PriceR { + numerator: number; + denominator: number; + } + interface PriceRShorthand { + n: number; + d: number; + } + interface AccountThresholds { + low_threshold: number; + med_threshold: number; + high_threshold: number; + } + interface Flags { + auth_immutable: boolean; + auth_required: boolean; + auth_revocable: boolean; + auth_clawback_enabled: boolean; + } + interface AccountSigner { + key: string; + weight: number; + type: string; + sponsor?: string; + } + interface AccountResponse extends BaseResponse<"transactions" | "operations" | "payments" | "effects" | "offers" | "trades" | "data"> { + id: string; + paging_token: string; + account_id: string; + sequence: string; + sequence_ledger?: number; + sequence_time?: string; + subentry_count: number; + thresholds: AccountThresholds; + last_modified_ledger: number; + last_modified_time: string; + flags: Flags; + balances: BalanceLine[]; + signers: AccountSigner[]; + data: { + [key: string]: string; + }; + sponsor?: string; + num_sponsoring: number; + num_sponsored: number; + } + enum LiquidityPoolType { + constantProduct = "constant_product" + } + enum OperationResponseType { + createAccount = "create_account", + payment = "payment", + pathPayment = "path_payment_strict_receive", + createPassiveOffer = "create_passive_sell_offer", + manageOffer = "manage_sell_offer", + setOptions = "set_options", + changeTrust = "change_trust", + allowTrust = "allow_trust", + accountMerge = "account_merge", + inflation = "inflation", + manageData = "manage_data", + bumpSequence = "bump_sequence", + manageBuyOffer = "manage_buy_offer", + pathPaymentStrictSend = "path_payment_strict_send", + createClaimableBalance = "create_claimable_balance", + claimClaimableBalance = "claim_claimable_balance", + beginSponsoringFutureReserves = "begin_sponsoring_future_reserves", + endSponsoringFutureReserves = "end_sponsoring_future_reserves", + revokeSponsorship = "revoke_sponsorship", + clawback = "clawback", + clawbackClaimableBalance = "clawback_claimable_balance", + setTrustLineFlags = "set_trust_line_flags", + liquidityPoolDeposit = "liquidity_pool_deposit", + liquidityPoolWithdraw = "liquidity_pool_withdraw", + invokeHostFunction = "invoke_host_function", + bumpFootprintExpiration = "bump_footprint_expiration", + restoreFootprint = "restore_footprint" + } + enum OperationResponseTypeI { + createAccount = 0, + payment = 1, + pathPayment = 2, + createPassiveOffer = 3, + manageOffer = 4, + setOptions = 5, + changeTrust = 6, + allowTrust = 7, + accountMerge = 8, + inflation = 9, + manageData = 10, + bumpSequence = 11, + manageBuyOffer = 12, + pathPaymentStrictSend = 13, + createClaimableBalance = 14, + claimClaimableBalance = 15, + beginSponsoringFutureReserves = 16, + endSponsoringFutureReserves = 17, + revokeSponsorship = 18, + clawback = 19, + clawbackClaimableBalance = 20, + setTrustLineFlags = 21, + liquidityPoolDeposit = 22, + liquidityPoolWithdraw = 23, + invokeHostFunction = 24, + bumpFootprintExpiration = 25, + restoreFootprint = 26 + } + interface BaseOperationResponse extends BaseResponse<"succeeds" | "precedes" | "effects" | "transaction"> { + id: string; + paging_token: string; + source_account: string; + type: T; + type_i: TI; + created_at: string; + transaction_hash: string; + transaction_successful: boolean; + } + interface CreateAccountOperationResponse extends BaseOperationResponse { + account: string; + funder: string; + starting_balance: string; + } + interface PaymentOperationResponse extends BaseOperationResponse { + from: string; + to: string; + asset_type: AssetType; + asset_code?: string; + asset_issuer?: string; + amount: string; + } + interface PathPaymentOperationResponse extends BaseOperationResponse { + amount: string; + asset_code?: string; + asset_issuer?: string; + asset_type: AssetType; + from: string; + path: Array<{ + asset_code: string; + asset_issuer: string; + asset_type: AssetType; + }>; + source_amount: string; + source_asset_code?: string; + source_asset_issuer?: string; + source_asset_type: AssetType; + source_max: string; + to: string; + } + interface PathPaymentStrictSendOperationResponse extends BaseOperationResponse { + amount: string; + asset_code?: string; + asset_issuer?: string; + asset_type: AssetType; + destination_min: string; + from: string; + path: Array<{ + asset_code: string; + asset_issuer: string; + asset_type: AssetType; + }>; + source_amount: string; + source_asset_code?: string; + source_asset_issuer?: string; + source_asset_type: AssetType; + to: string; + } + interface ManageOfferOperationResponse extends BaseOperationResponse { + offer_id: number | string; + amount: string; + buying_asset_type: AssetType; + buying_asset_code?: string; + buying_asset_issuer?: string; + price: string; + price_r: PriceR; + selling_asset_type: AssetType; + selling_asset_code?: string; + selling_asset_issuer?: string; + } + interface PassiveOfferOperationResponse extends BaseOperationResponse { + offer_id: number | string; + amount: string; + buying_asset_type: AssetType; + buying_asset_code?: string; + buying_asset_issuer?: string; + price: string; + price_r: PriceR; + selling_asset_type: AssetType; + selling_asset_code?: string; + selling_asset_issuer?: string; + } + interface SetOptionsOperationResponse extends BaseOperationResponse { + signer_key?: string; + signer_weight?: number; + master_key_weight?: number; + low_threshold?: number; + med_threshold?: number; + high_threshold?: number; + home_domain?: string; + set_flags: Array<1 | 2 | 4>; + set_flags_s: Array<"auth_required_flag" | "auth_revocable_flag" | "auth_clawback_enabled_flag">; + clear_flags: Array<1 | 2 | 4>; + clear_flags_s: Array<"auth_required_flag" | "auth_revocable_flag" | "auth_clawback_enabled_flag">; + } + interface ChangeTrustOperationResponse extends BaseOperationResponse { + asset_type: AssetType.credit4 | AssetType.credit12 | AssetType.liquidityPoolShares; + asset_code?: string; + asset_issuer?: string; + liquidity_pool_id?: string; + trustee?: string; + trustor: string; + limit: string; + } + interface AllowTrustOperationResponse extends BaseOperationResponse { + asset_type: AssetType; + asset_code: string; + asset_issuer: string; + authorize: boolean; + authorize_to_maintain_liabilities: boolean; + trustee: string; + trustor: string; + } + interface AccountMergeOperationResponse extends BaseOperationResponse { + into: string; + } + interface InflationOperationResponse extends BaseOperationResponse { + } + interface ManageDataOperationResponse extends BaseOperationResponse { + name: string; + value: Buffer; + } + interface BumpSequenceOperationResponse extends BaseOperationResponse { + bump_to: string; + } + interface Predicate { + and?: Predicate[]; + or?: Predicate[]; + not?: Predicate; + abs_before?: string; + rel_before?: string; + } + interface Claimant { + destination: string; + predicate: Predicate; + } + interface CreateClaimableBalanceOperationResponse extends BaseOperationResponse { + asset: string; + amount: string; + sponsor: string; + claimants: Claimant[]; + } + interface ClaimClaimableBalanceOperationResponse extends BaseOperationResponse { + balance_id: string; + claimant: string; + } + interface BeginSponsoringFutureReservesOperationResponse extends BaseOperationResponse { + sponsored_id: string; + } + interface EndSponsoringFutureReservesOperationResponse extends BaseOperationResponse { + begin_sponsor: string; + } + interface RevokeSponsorshipOperationResponse extends BaseOperationResponse { + account_id?: string; + claimable_balance_id?: string; + data_account_id?: string; + data_name?: string; + offer_id?: string; + trustline_account_id?: string; + trustline_asset?: string; + trustline_liquidity_pool_id?: string; + signer_account_id?: string; + signer_key?: string; + } + interface ClawbackOperationResponse extends BaseOperationResponse { + asset_type: AssetType; + asset_code: string; + asset_issuer: string; + from: string; + amount: string; + } + interface ClawbackClaimableBalanceOperationResponse extends BaseOperationResponse { + balance_id: string; + } + interface SetTrustLineFlagsOperationResponse extends BaseOperationResponse { + asset_type: AssetType; + asset_code: string; + asset_issuer: string; + trustor: string; + set_flags: Array<1 | 2 | 4>; + clear_flags: Array<1 | 2 | 4>; + } + interface Reserve { + asset: string; + amount: string; + } + interface DepositLiquidityOperationResponse extends BaseOperationResponse { + liquidity_pool_id: string; + reserves_max: Reserve[]; + min_price: string; + min_price_r: PriceRShorthand; + max_price: string; + max_price_r: PriceRShorthand; + reserves_deposited: Reserve[]; + shares_received: string; + } + interface WithdrawLiquidityOperationResponse extends BaseOperationResponse { + liquidity_pool_id: string; + reserves_min: Reserve[]; + shares: string; + reserves_received: Reserve[]; + } + interface BalanceChange { + asset_type: string; + asset_code?: string; + asset_issuer?: string; + type: string; + from: string; + to: string; + amount: string; + } + interface InvokeHostFunctionOperationResponse extends BaseOperationResponse { + function: string; + parameters: { + value: string; + type: string; + }[]; + address: string; + salt: string; + asset_balance_changes: BalanceChange[]; + } + interface BumpFootprintExpirationOperationResponse extends BaseOperationResponse { + ledgers_to_expire: number; + } + interface RestoreFootprintOperationResponse extends BaseOperationResponse { + } + interface ResponseCollection { + _links: { + self: ResponseLink; + next: ResponseLink; + prev: ResponseLink; + }; + _embedded: { + records: T[]; + }; + } + interface TransactionResponseCollection extends ResponseCollection { + } + interface FeeDistribution { + max: string; + min: string; + mode: string; + p10: string; + p20: string; + p30: string; + p40: string; + p50: string; + p60: string; + p70: string; + p80: string; + p90: string; + p95: string; + p99: string; + } + interface FeeStatsResponse { + last_ledger: string; + last_ledger_base_fee: string; + ledger_capacity_usage: string; + fee_charged: FeeDistribution; + max_fee: FeeDistribution; + } + type ErrorResponseData = ErrorResponseData.RateLimitExceeded | ErrorResponseData.InternalServerError | ErrorResponseData.TransactionFailed; + namespace ErrorResponseData { + interface Base { + status: number; + title: string; + type: string; + details: string; + instance: string; + } + interface RateLimitExceeded extends Base { + status: 429; + title: "Rate Limit Exceeded"; + } + interface InternalServerError extends Base { + status: 500; + title: "Internal Server Error"; + } + interface TransactionFailed extends Base { + status: 400; + title: "Transaction Failed"; + extras: TransactionFailedExtras; + } + } + enum TransactionFailedResultCodes { + TX_FAILED = "tx_failed", + TX_BAD_SEQ = "tx_bad_seq", + TX_BAD_AUTH = "tx_bad_auth", + TX_BAD_AUTH_EXTRA = "tx_bad_auth_extra", + TX_FEE_BUMP_INNER_SUCCESS = "tx_fee_bump_inner_success", + TX_FEE_BUMP_INNER_FAILED = "tx_fee_bump_inner_failed", + TX_NOT_SUPPORTED = "tx_not_supported", + TX_SUCCESS = "tx_success", + TX_TOO_EARLY = "tx_too_early", + TX_TOO_LATE = "tx_too_late", + TX_MISSING_OPERATION = "tx_missing_operation", + TX_INSUFFICIENT_BALANCE = "tx_insufficient_balance", + TX_NO_SOURCE_ACCOUNT = "tx_no_source_account", + TX_INSUFFICIENT_FEE = "tx_insufficient_fee", + TX_INTERNAL_ERROR = "tx_internal_error" + } + interface TransactionFailedExtras { + envelope_xdr: string; + result_codes: { + transaction: TransactionFailedResultCodes; + operations: string[]; + }; + result_xdr: string; + } + interface RootResponse { + horizon_version: string; + core_version: string; + ingest_latest_ledger: number; + history_latest_ledger: number; + history_latest_ledger_closed_at: string; + history_elder_ledger: number; + core_latest_ledger: number; + network_passphrase: string; + current_protocol_version: number; + supported_protocol_version: number; + core_supported_protocol_version: number; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/horizon_api.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/horizon_api.js new file mode 100644 index 000000000..b4b1c1878 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/horizon_api.js @@ -0,0 +1,96 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.HorizonApi = void 0; +var HorizonApi; +(function (_HorizonApi) { + var LiquidityPoolType = function (LiquidityPoolType) { + LiquidityPoolType["constantProduct"] = "constant_product"; + return LiquidityPoolType; + }({}); + _HorizonApi.LiquidityPoolType = LiquidityPoolType; + var OperationResponseType = function (OperationResponseType) { + OperationResponseType["createAccount"] = "create_account"; + OperationResponseType["payment"] = "payment"; + OperationResponseType["pathPayment"] = "path_payment_strict_receive"; + OperationResponseType["createPassiveOffer"] = "create_passive_sell_offer"; + OperationResponseType["manageOffer"] = "manage_sell_offer"; + OperationResponseType["setOptions"] = "set_options"; + OperationResponseType["changeTrust"] = "change_trust"; + OperationResponseType["allowTrust"] = "allow_trust"; + OperationResponseType["accountMerge"] = "account_merge"; + OperationResponseType["inflation"] = "inflation"; + OperationResponseType["manageData"] = "manage_data"; + OperationResponseType["bumpSequence"] = "bump_sequence"; + OperationResponseType["manageBuyOffer"] = "manage_buy_offer"; + OperationResponseType["pathPaymentStrictSend"] = "path_payment_strict_send"; + OperationResponseType["createClaimableBalance"] = "create_claimable_balance"; + OperationResponseType["claimClaimableBalance"] = "claim_claimable_balance"; + OperationResponseType["beginSponsoringFutureReserves"] = "begin_sponsoring_future_reserves"; + OperationResponseType["endSponsoringFutureReserves"] = "end_sponsoring_future_reserves"; + OperationResponseType["revokeSponsorship"] = "revoke_sponsorship"; + OperationResponseType["clawback"] = "clawback"; + OperationResponseType["clawbackClaimableBalance"] = "clawback_claimable_balance"; + OperationResponseType["setTrustLineFlags"] = "set_trust_line_flags"; + OperationResponseType["liquidityPoolDeposit"] = "liquidity_pool_deposit"; + OperationResponseType["liquidityPoolWithdraw"] = "liquidity_pool_withdraw"; + OperationResponseType["invokeHostFunction"] = "invoke_host_function"; + OperationResponseType["bumpFootprintExpiration"] = "bump_footprint_expiration"; + OperationResponseType["restoreFootprint"] = "restore_footprint"; + return OperationResponseType; + }({}); + _HorizonApi.OperationResponseType = OperationResponseType; + var OperationResponseTypeI = function (OperationResponseTypeI) { + OperationResponseTypeI[OperationResponseTypeI["createAccount"] = 0] = "createAccount"; + OperationResponseTypeI[OperationResponseTypeI["payment"] = 1] = "payment"; + OperationResponseTypeI[OperationResponseTypeI["pathPayment"] = 2] = "pathPayment"; + OperationResponseTypeI[OperationResponseTypeI["createPassiveOffer"] = 3] = "createPassiveOffer"; + OperationResponseTypeI[OperationResponseTypeI["manageOffer"] = 4] = "manageOffer"; + OperationResponseTypeI[OperationResponseTypeI["setOptions"] = 5] = "setOptions"; + OperationResponseTypeI[OperationResponseTypeI["changeTrust"] = 6] = "changeTrust"; + OperationResponseTypeI[OperationResponseTypeI["allowTrust"] = 7] = "allowTrust"; + OperationResponseTypeI[OperationResponseTypeI["accountMerge"] = 8] = "accountMerge"; + OperationResponseTypeI[OperationResponseTypeI["inflation"] = 9] = "inflation"; + OperationResponseTypeI[OperationResponseTypeI["manageData"] = 10] = "manageData"; + OperationResponseTypeI[OperationResponseTypeI["bumpSequence"] = 11] = "bumpSequence"; + OperationResponseTypeI[OperationResponseTypeI["manageBuyOffer"] = 12] = "manageBuyOffer"; + OperationResponseTypeI[OperationResponseTypeI["pathPaymentStrictSend"] = 13] = "pathPaymentStrictSend"; + OperationResponseTypeI[OperationResponseTypeI["createClaimableBalance"] = 14] = "createClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["claimClaimableBalance"] = 15] = "claimClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["beginSponsoringFutureReserves"] = 16] = "beginSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["endSponsoringFutureReserves"] = 17] = "endSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["revokeSponsorship"] = 18] = "revokeSponsorship"; + OperationResponseTypeI[OperationResponseTypeI["clawback"] = 19] = "clawback"; + OperationResponseTypeI[OperationResponseTypeI["clawbackClaimableBalance"] = 20] = "clawbackClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["setTrustLineFlags"] = 21] = "setTrustLineFlags"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolDeposit"] = 22] = "liquidityPoolDeposit"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolWithdraw"] = 23] = "liquidityPoolWithdraw"; + OperationResponseTypeI[OperationResponseTypeI["invokeHostFunction"] = 24] = "invokeHostFunction"; + OperationResponseTypeI[OperationResponseTypeI["bumpFootprintExpiration"] = 25] = "bumpFootprintExpiration"; + OperationResponseTypeI[OperationResponseTypeI["restoreFootprint"] = 26] = "restoreFootprint"; + return OperationResponseTypeI; + }({}); + _HorizonApi.OperationResponseTypeI = OperationResponseTypeI; + ; + var TransactionFailedResultCodes = function (TransactionFailedResultCodes) { + TransactionFailedResultCodes["TX_FAILED"] = "tx_failed"; + TransactionFailedResultCodes["TX_BAD_SEQ"] = "tx_bad_seq"; + TransactionFailedResultCodes["TX_BAD_AUTH"] = "tx_bad_auth"; + TransactionFailedResultCodes["TX_BAD_AUTH_EXTRA"] = "tx_bad_auth_extra"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_SUCCESS"] = "tx_fee_bump_inner_success"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_FAILED"] = "tx_fee_bump_inner_failed"; + TransactionFailedResultCodes["TX_NOT_SUPPORTED"] = "tx_not_supported"; + TransactionFailedResultCodes["TX_SUCCESS"] = "tx_success"; + TransactionFailedResultCodes["TX_TOO_EARLY"] = "tx_too_early"; + TransactionFailedResultCodes["TX_TOO_LATE"] = "tx_too_late"; + TransactionFailedResultCodes["TX_MISSING_OPERATION"] = "tx_missing_operation"; + TransactionFailedResultCodes["TX_INSUFFICIENT_BALANCE"] = "tx_insufficient_balance"; + TransactionFailedResultCodes["TX_NO_SOURCE_ACCOUNT"] = "tx_no_source_account"; + TransactionFailedResultCodes["TX_INSUFFICIENT_FEE"] = "tx_insufficient_fee"; + TransactionFailedResultCodes["TX_INTERNAL_ERROR"] = "tx_internal_error"; + return TransactionFailedResultCodes; + }({}); + _HorizonApi.TransactionFailedResultCodes = TransactionFailedResultCodes; +})(HorizonApi || (exports.HorizonApi = HorizonApi = {})); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/horizon_axios_client.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/horizon_axios_client.d.ts new file mode 100644 index 000000000..a5934c906 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/horizon_axios_client.d.ts @@ -0,0 +1,37 @@ +export declare const version: string; +export interface ServerTime { + serverTime: number; + localTimeRecorded: number; +} +/** + * keep a local map of server times + * (export this purely for testing purposes) + * + * each entry will map the server domain to the last-known time and the local + * time it was recorded, ex: + * + * @example + * "horizon-testnet.stellar.org": { + * serverTime: 1552513039, + * localTimeRecorded: 1552513052 + * } + * + * @constant {Record.} + * @default {} + * @memberof module:Horizon + */ +export declare const SERVER_TIME_MAP: Record; +export declare const AxiosClient: import("../http-client").HttpClient; +export default AxiosClient; +/** + * Given a hostname, get the current time of that server (i.e., use the last- + * recorded server time and offset it by the time since then.) If there IS no + * recorded server time, or it's been 5 minutes since the last, return null. + * @memberof module:Horizon + * + * @param {string} hostname Hostname of a Horizon server. + * @returns {number} The UNIX timestamp (in seconds, not milliseconds) + * representing the current time on that server, or `null` if we don't have + * a record of that time. + */ +export declare function getCurrentServerTime(hostname: string): number | null; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/horizon_axios_client.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/horizon_axios_client.js new file mode 100644 index 000000000..d9c56d163 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/horizon_axios_client.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.SERVER_TIME_MAP = exports.AxiosClient = void 0; +exports.getCurrentServerTime = getCurrentServerTime; +exports.version = void 0; +var _urijs = _interopRequireDefault(require("urijs")); +var _httpClient = require("../http-client"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +var version = exports.version = "13.1.0"; +var SERVER_TIME_MAP = exports.SERVER_TIME_MAP = {}; +var AxiosClient = exports.AxiosClient = (0, _httpClient.create)({ + headers: { + "X-Client-Name": "js-stellar-sdk", + "X-Client-Version": version + } +}); +function toSeconds(ms) { + return Math.floor(ms / 1000); +} +AxiosClient.interceptors.response.use(function (response) { + var hostname = (0, _urijs.default)(response.config.url).hostname(); + var serverTime = 0; + if (response.headers instanceof Headers) { + var dateHeader = response.headers.get('date'); + if (dateHeader) { + serverTime = toSeconds(Date.parse(dateHeader)); + } + } else if (_typeof(response.headers) === 'object' && 'date' in response.headers) { + var headers = response.headers; + if (typeof headers.date === 'string') { + serverTime = toSeconds(Date.parse(headers.date)); + } + } + var localTimeRecorded = toSeconds(new Date().getTime()); + if (!Number.isNaN(serverTime)) { + SERVER_TIME_MAP[hostname] = { + serverTime: serverTime, + localTimeRecorded: localTimeRecorded + }; + } + return response; +}); +var _default = exports.default = AxiosClient; +function getCurrentServerTime(hostname) { + var entry = SERVER_TIME_MAP[hostname]; + if (!entry || !entry.localTimeRecorded || !entry.serverTime) { + return null; + } + var serverTime = entry.serverTime, + localTimeRecorded = entry.localTimeRecorded; + var currentTime = toSeconds(new Date().getTime()); + if (currentTime - localTimeRecorded > 60 * 5) { + return null; + } + return currentTime - localTimeRecorded + serverTime; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/index.d.ts new file mode 100644 index 000000000..9a351398f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/index.d.ts @@ -0,0 +1,8 @@ +/** @module Horizon */ +export * from "./horizon_api"; +export * from "./server_api"; +export * from "./account_response"; +export { HorizonServer as Server } from "./server"; +export { default as AxiosClient, SERVER_TIME_MAP, getCurrentServerTime } from "./horizon_axios_client"; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/index.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/index.js new file mode 100644 index 000000000..4ea741268 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/index.js @@ -0,0 +1,78 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Server: true, + AxiosClient: true, + SERVER_TIME_MAP: true, + getCurrentServerTime: true +}; +Object.defineProperty(exports, "AxiosClient", { + enumerable: true, + get: function get() { + return _horizon_axios_client.default; + } +}); +Object.defineProperty(exports, "SERVER_TIME_MAP", { + enumerable: true, + get: function get() { + return _horizon_axios_client.SERVER_TIME_MAP; + } +}); +Object.defineProperty(exports, "Server", { + enumerable: true, + get: function get() { + return _server.HorizonServer; + } +}); +exports.default = void 0; +Object.defineProperty(exports, "getCurrentServerTime", { + enumerable: true, + get: function get() { + return _horizon_axios_client.getCurrentServerTime; + } +}); +var _horizon_api = require("./horizon_api"); +Object.keys(_horizon_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _horizon_api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _horizon_api[key]; + } + }); +}); +var _server_api = require("./server_api"); +Object.keys(_server_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _server_api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _server_api[key]; + } + }); +}); +var _account_response = require("./account_response"); +Object.keys(_account_response).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _account_response[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _account_response[key]; + } + }); +}); +var _server = require("./server"); +var _horizon_axios_client = _interopRequireWildcard(require("./horizon_axios_client")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/ledger_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/ledger_call_builder.d.ts new file mode 100644 index 000000000..76c7f38ef --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/ledger_call_builder.d.ts @@ -0,0 +1,23 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link LedgerCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#ledgers}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-ledgers|All Ledgers} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class LedgerCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Provides information on a single ledger. + * @param {number|string} sequence Ledger sequence + * @returns {LedgerCallBuilder} current LedgerCallBuilder instance + */ + ledger(sequence: number | string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/ledger_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/ledger_call_builder.js new file mode 100644 index 000000000..93b2801b3 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/ledger_call_builder.js @@ -0,0 +1,37 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LedgerCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var LedgerCallBuilder = exports.LedgerCallBuilder = function (_CallBuilder) { + function LedgerCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, LedgerCallBuilder); + _this = _callSuper(this, LedgerCallBuilder, [serverUrl]); + _this.url.segment("ledgers"); + return _this; + } + _inherits(LedgerCallBuilder, _CallBuilder); + return _createClass(LedgerCallBuilder, [{ + key: "ledger", + value: function ledger(sequence) { + this.filter.push(["ledgers", sequence.toString()]); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/liquidity_pool_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/liquidity_pool_call_builder.d.ts new file mode 100644 index 000000000..806984c17 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/liquidity_pool_call_builder.d.ts @@ -0,0 +1,37 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link LiquidityPoolCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#liquidityPools}. + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class LiquidityPoolCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Filters out pools whose reserves don't exactly match these assets. + * + * @see Asset + * @returns {LiquidityPoolCallBuilder} current LiquidityPoolCallBuilder instance + */ + forAssets(...assets: Asset[]): this; + /** + * Retrieves all pools an account is participating in. + * + * @param {string} id the participant account to filter by + * @returns {LiquidityPoolCallBuilder} current LiquidityPoolCallBuilder instance + */ + forAccount(id: string): this; + /** + * Retrieves a specific liquidity pool by ID. + * + * @param {string} id the hash/ID of the liquidity pool + * @returns {CallBuilder} a new CallBuilder instance for the /liquidity_pools/:id endpoint + */ + liquidityPoolId(id: string): CallBuilder; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/liquidity_pool_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/liquidity_pool_call_builder.js new file mode 100644 index 000000000..7f0c6ff78 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/liquidity_pool_call_builder.js @@ -0,0 +1,59 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LiquidityPoolCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var LiquidityPoolCallBuilder = exports.LiquidityPoolCallBuilder = function (_CallBuilder) { + function LiquidityPoolCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, LiquidityPoolCallBuilder); + _this = _callSuper(this, LiquidityPoolCallBuilder, [serverUrl]); + _this.url.segment("liquidity_pools"); + return _this; + } + _inherits(LiquidityPoolCallBuilder, _CallBuilder); + return _createClass(LiquidityPoolCallBuilder, [{ + key: "forAssets", + value: function forAssets() { + for (var _len = arguments.length, assets = new Array(_len), _key = 0; _key < _len; _key++) { + assets[_key] = arguments[_key]; + } + var assetList = assets.map(function (asset) { + return asset.toString(); + }).join(","); + this.url.setQuery("reserves", assetList); + return this; + } + }, { + key: "forAccount", + value: function forAccount(id) { + this.url.setQuery("account", id); + return this; + } + }, { + key: "liquidityPoolId", + value: function liquidityPoolId(id) { + if (!id.match(/[a-fA-F0-9]{64}/)) { + throw new TypeError("".concat(id, " does not look like a liquidity pool ID")); + } + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([id.toLowerCase()]); + return builder; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/offer_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/offer_call_builder.d.ts new file mode 100644 index 000000000..2628c3960 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/offer_call_builder.d.ts @@ -0,0 +1,65 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link OfferCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#offers}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/|Offers} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class OfferCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The offer details endpoint provides information on a single offer. The offer ID provided in the id + * argument specifies which offer to load. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/single/|Offer Details} + * @param {string} offerId Offer ID + * @returns {CallBuilder} CallBuilder OperationCallBuilder instance + */ + offer(offerId: string): CallBuilder; + /** + * Returns all offers where the given account is involved. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/accounts/offers/|Offers} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + forAccount(id: string): this; + /** + * Returns all offers buying an asset. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/list/|Offers} + * @see Asset + * @param {Asset} asset For example: `new Asset('USD','GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD')` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + buying(asset: Asset): this; + /** + * Returns all offers selling an asset. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/list/|Offers} + * @see Asset + * @param {Asset} asset For example: `new Asset('EUR','GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD')` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + selling(asset: Asset): this; + /** + * This endpoint filters offers where the given account is sponsoring the offer entry. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-all-offers|Offers} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + sponsor(id: string): this; + /** + * This endpoint filters offers where the given account is the seller. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-all-offers|Offers} + * @param {string} seller For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + seller(seller: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/offer_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/offer_call_builder.js new file mode 100644 index 000000000..12c6a6277 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/offer_call_builder.js @@ -0,0 +1,79 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OfferCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var OfferCallBuilder = exports.OfferCallBuilder = function (_CallBuilder) { + function OfferCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, OfferCallBuilder); + _this = _callSuper(this, OfferCallBuilder, [serverUrl, "offers"]); + _this.url.segment("offers"); + return _this; + } + _inherits(OfferCallBuilder, _CallBuilder); + return _createClass(OfferCallBuilder, [{ + key: "offer", + value: function offer(offerId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([offerId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(id) { + return this.forEndpoint("accounts", id); + } + }, { + key: "buying", + value: function buying(asset) { + if (!asset.isNative()) { + this.url.setQuery("buying_asset_type", asset.getAssetType()); + this.url.setQuery("buying_asset_code", asset.getCode()); + this.url.setQuery("buying_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("buying_asset_type", "native"); + } + return this; + } + }, { + key: "selling", + value: function selling(asset) { + if (!asset.isNative()) { + this.url.setQuery("selling_asset_type", asset.getAssetType()); + this.url.setQuery("selling_asset_code", asset.getCode()); + this.url.setQuery("selling_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("selling_asset_type", "native"); + } + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "seller", + value: function seller(_seller) { + this.url.setQuery("seller", _seller); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/operation_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/operation_call_builder.d.ts new file mode 100644 index 000000000..ca7c9781c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/operation_call_builder.d.ts @@ -0,0 +1,69 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link OperationCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#operations}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/operations|All Operations} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class OperationCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The operation details endpoint provides information on a single operation. The operation ID provided in the id + * argument specifies which operation to load. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-an-operation|Operation Details} + * @param {number} operationId Operation ID + * @returns {CallBuilder} this OperationCallBuilder instance + */ + operation(operationId: string): CallBuilder; + /** + * This endpoint represents all operations that were included in valid transactions that affected a particular account. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-operations-by-account-id|Operations for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * This endpoint represents all operations that reference a given claimable_balance. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/cb-retrieve-related-operations|Operations for Claimable Balance} + * @param {string} claimableBalanceId Claimable Balance ID + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forClaimableBalance(claimableBalanceId: string): this; + /** + * This endpoint returns all operations that occurred in a given ledger. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-ledgers-operations|Operations for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all operations that are part of a given transaction. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-transactions-operations|Operations for Transaction} + * @param {string} transactionId Transaction ID + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forTransaction(transactionId: string): this; + /** + * This endpoint represents all operations involving a particular liquidity pool. + * + * @param {string} poolId liquidity pool ID + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forLiquidityPool(poolId: string): this; + /** + * Adds a parameter defining whether to include failed transactions. + * By default, only operations of successful transactions are returned. + * + * @param {boolean} value Set to `true` to include operations of failed transactions. + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + includeFailed(value: boolean): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/operation_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/operation_call_builder.js new file mode 100644 index 000000000..d24cd67d7 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/operation_call_builder.js @@ -0,0 +1,69 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OperationCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var OperationCallBuilder = exports.OperationCallBuilder = function (_CallBuilder) { + function OperationCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, OperationCallBuilder); + _this = _callSuper(this, OperationCallBuilder, [serverUrl, "operations"]); + _this.url.segment("operations"); + return _this; + } + _inherits(OperationCallBuilder, _CallBuilder); + return _createClass(OperationCallBuilder, [{ + key: "operation", + value: function operation(operationId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([operationId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/orderbook_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/orderbook_call_builder.d.ts new file mode 100644 index 000000000..484126432 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/orderbook_call_builder.d.ts @@ -0,0 +1,20 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link OrderbookCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#orderbook}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/order-books|Orderbook Details} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl serverUrl Horizon server URL. + * @param {Asset} selling Asset being sold + * @param {Asset} buying Asset being bought + */ +export declare class OrderbookCallBuilder extends CallBuilder { + constructor(serverUrl: URI, selling: Asset, buying: Asset); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/orderbook_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/orderbook_call_builder.js new file mode 100644 index 000000000..c4d3dd4c6 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/orderbook_call_builder.js @@ -0,0 +1,45 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OrderbookCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var OrderbookCallBuilder = exports.OrderbookCallBuilder = function (_CallBuilder) { + function OrderbookCallBuilder(serverUrl, selling, buying) { + var _this; + _classCallCheck(this, OrderbookCallBuilder); + _this = _callSuper(this, OrderbookCallBuilder, [serverUrl]); + _this.url.segment("order_book"); + if (!selling.isNative()) { + _this.url.setQuery("selling_asset_type", selling.getAssetType()); + _this.url.setQuery("selling_asset_code", selling.getCode()); + _this.url.setQuery("selling_asset_issuer", selling.getIssuer()); + } else { + _this.url.setQuery("selling_asset_type", "native"); + } + if (!buying.isNative()) { + _this.url.setQuery("buying_asset_type", buying.getAssetType()); + _this.url.setQuery("buying_asset_code", buying.getCode()); + _this.url.setQuery("buying_asset_issuer", buying.getIssuer()); + } else { + _this.url.setQuery("buying_asset_type", "native"); + } + return _this; + } + _inherits(OrderbookCallBuilder, _CallBuilder); + return _createClass(OrderbookCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/path_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/path_call_builder.d.ts new file mode 100644 index 000000000..56c89afa9 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/path_call_builder.d.ts @@ -0,0 +1,35 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * The Stellar Network allows payments to be made across assets through path payments. A path payment specifies a + * series of assets to route a payment through, from source asset (the asset debited from the payer) to destination + * asset (the asset credited to the payee). + * + * A path search is specified using: + * + * * The destination address + * * The source address + * * The asset and amount that the destination account should receive + * + * As part of the search, horizon will load a list of assets available to the source address and will find any + * payment paths from those source assets to the desired destination asset. The search's amount parameter will be + * used to determine if there a given path can satisfy a payment of the desired amount. + * + * Do not create this object directly, use {@link Horizon.Server#paths}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/paths|Find Payment Paths} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + * @param {string} source The sender's account ID. Any returned path must use a source that the sender can hold. + * @param {string} destination The destination account ID that any returned path should use. + * @param {Asset} destinationAsset The destination asset. + * @param {string} destinationAmount The amount, denominated in the destination asset, that any returned path should be able to satisfy. + */ +export declare class PathCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, source: string, destination: string, destinationAsset: Asset, destinationAmount: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/path_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/path_call_builder.js new file mode 100644 index 000000000..53f5cebbe --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/path_call_builder.js @@ -0,0 +1,41 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PathCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var PathCallBuilder = exports.PathCallBuilder = function (_CallBuilder) { + function PathCallBuilder(serverUrl, source, destination, destinationAsset, destinationAmount) { + var _this; + _classCallCheck(this, PathCallBuilder); + _this = _callSuper(this, PathCallBuilder, [serverUrl]); + _this.url.segment("paths"); + _this.url.setQuery("destination_account", destination); + _this.url.setQuery("source_account", source); + _this.url.setQuery("destination_amount", destinationAmount); + if (!destinationAsset.isNative()) { + _this.url.setQuery("destination_asset_type", destinationAsset.getAssetType()); + _this.url.setQuery("destination_asset_code", destinationAsset.getCode()); + _this.url.setQuery("destination_asset_issuer", destinationAsset.getIssuer()); + } else { + _this.url.setQuery("destination_asset_type", "native"); + } + return _this; + } + _inherits(PathCallBuilder, _CallBuilder); + return _createClass(PathCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/payment_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/payment_call_builder.d.ts new file mode 100644 index 000000000..bcee63c88 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/payment_call_builder.d.ts @@ -0,0 +1,39 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link PaymentCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#payments}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/horizon/resources/list-all-payments/|All Payments} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + */ +export declare class PaymentCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * This endpoint responds with a collection of Payment operations where the given account was either the sender or receiver. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/horizon/resources/get-payments-by-account-id|Payments for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {PaymentCallBuilder} this PaymentCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * This endpoint represents all payment operations that are part of a valid transactions in a given ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/horizon/resources/retrieve-a-ledgers-payments|Payments for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {PaymentCallBuilder} this PaymentCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all payment operations that are part of a given transaction. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/transactions/payments/|Payments for Transaction} + * @param {string} transactionId Transaction ID + * @returns {PaymentCallBuilder} this PaymentCallBuilder instance + */ + forTransaction(transactionId: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/payment_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/payment_call_builder.js new file mode 100644 index 000000000..e3a9c26bf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/payment_call_builder.js @@ -0,0 +1,46 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PaymentCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var PaymentCallBuilder = exports.PaymentCallBuilder = function (_CallBuilder) { + function PaymentCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, PaymentCallBuilder); + _this = _callSuper(this, PaymentCallBuilder, [serverUrl, "payments"]); + _this.url.segment("payments"); + return _this; + } + _inherits(PaymentCallBuilder, _CallBuilder); + return _createClass(PaymentCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/server.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/server.d.ts new file mode 100644 index 000000000..ef83c857a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/server.d.ts @@ -0,0 +1,394 @@ +import { Asset, FeeBumpTransaction, Transaction } from "@stellar/stellar-base"; +import URI from "urijs"; +import { AccountCallBuilder } from "./account_call_builder"; +import { AccountResponse } from "./account_response"; +import { AssetsCallBuilder } from "./assets_call_builder"; +import { ClaimableBalanceCallBuilder } from "./claimable_balances_call_builder"; +import { EffectCallBuilder } from "./effect_call_builder"; +import { FriendbotBuilder } from "./friendbot_builder"; +import { HorizonApi } from "./horizon_api"; +import { LedgerCallBuilder } from "./ledger_call_builder"; +import { LiquidityPoolCallBuilder } from "./liquidity_pool_call_builder"; +import { OfferCallBuilder } from "./offer_call_builder"; +import { OperationCallBuilder } from "./operation_call_builder"; +import { OrderbookCallBuilder } from "./orderbook_call_builder"; +import { PathCallBuilder } from "./path_call_builder"; +import { PaymentCallBuilder } from "./payment_call_builder"; +import { TradeAggregationCallBuilder } from "./trade_aggregation_call_builder"; +import { TradesCallBuilder } from "./trades_call_builder"; +import { TransactionCallBuilder } from "./transaction_call_builder"; +/** + * Default transaction submission timeout for Horizon requests, in milliseconds + * @constant {number} + * @default 60000 + * @memberof module:Horizon.Server + */ +export declare const SUBMIT_TRANSACTION_TIMEOUT: number; +/** + * Server handles the network connection to a [Horizon](https://developers.stellar.org/docs/data/horizon) + * instance and exposes an interface for requests to that instance. + * @class + * @alias module:Horizon.Server + * @memberof module:Horizon + * + * @param {string} serverURL Horizon Server URL (ex. `https://horizon-testnet.stellar.org`). + * @param {module:Horizon.Server.Options} [opts] Options object + */ +export declare class HorizonServer { + /** + * Horizon Server URL (ex. `https://horizon-testnet.stellar.org`) + * + * @todo Solve `URI(this.serverURL as any)`. + */ + readonly serverURL: URI; + constructor(serverURL: string, opts?: HorizonServer.Options); + /** + * Get timebounds for N seconds from now, when you're creating a transaction + * with {@link TransactionBuilder}. + * + * By default, {@link TransactionBuilder} uses the current local time, but + * your machine's local time could be different from Horizon's. This gives you + * more assurance that your timebounds will reflect what you want. + * + * Note that this will generate your timebounds when you **init the transaction**, + * not when you build or submit the transaction! So give yourself enough time to get + * the transaction built and signed before submitting. + * + * @example + * const transaction = new StellarSdk.TransactionBuilder(accountId, { + * fee: await StellarSdk.Server.fetchBaseFee(), + * timebounds: await StellarSdk.Server.fetchTimebounds(100) + * }) + * .addOperation(operation) + * // normally we would need to call setTimeout here, but setting timebounds + * // earlier does the trick! + * .build(); + * + * @param {number} seconds Number of seconds past the current time to wait. + * @param {boolean} [_isRetry] True if this is a retry. Only set this internally! + * This is to avoid a scenario where Horizon is horking up the wrong date. + * @returns {Promise} Promise that resolves a `timebounds` object + * (with the shape `{ minTime: 0, maxTime: N }`) that you can set the `timebounds` option to. + */ + fetchTimebounds(seconds: number, _isRetry?: boolean): Promise; + /** + * Fetch the base fee. Since this hits the server, if the server call fails, + * you might get an error. You should be prepared to use a default value if + * that happens! + * @returns {Promise} Promise that resolves to the base fee. + */ + fetchBaseFee(): Promise; + /** + * Fetch the fee stats endpoint. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/fee-stats|Fee Stats} + * @returns {Promise} Promise that resolves to the fee stats returned by Horizon. + */ + feeStats(): Promise; + /** + * Fetch the Horizon server's root endpoint. + * @returns {Promise} Promise that resolves to the root endpoint returned by Horizon. + */ + root(): Promise; + /** + * Submits a transaction to the network. + * + * By default this function calls {@link Horizon.Server#checkMemoRequired}, you can + * skip this check by setting the option `skipMemoRequiredCheck` to `true`. + * + * If you submit any number of `manageOffer` operations, this will add an + * attribute to the response that will help you analyze what happened with + * your offers. + * + * For example, you'll want to examine `offerResults` to add affordances like + * these to your app: + * - If `wasImmediatelyFilled` is true, then no offer was created. So if you + * normally watch the `Server.offers` endpoint for offer updates, you + * instead need to check `Server.trades` to find the result of this filled + * offer. + * - If `wasImmediatelyDeleted` is true, then the offer you submitted was + * deleted without reaching the orderbook or being matched (possibly because + * your amounts were rounded down to zero). So treat the just-submitted + * offer request as if it never happened. + * - If `wasPartiallyFilled` is true, you can tell the user that + * `amountBought` or `amountSold` have already been transferred. + * + * @example + * const res = { + * ...response, + * offerResults: [ + * { + * // Exact ordered list of offers that executed, with the exception + * // that the last one may not have executed entirely. + * offersClaimed: [ + * sellerId: String, + * offerId: String, + * assetSold: { + * type: 'native|credit_alphanum4|credit_alphanum12', + * + * // these are only present if the asset is not native + * assetCode: String, + * issuer: String, + * }, + * + * // same shape as assetSold + * assetBought: {} + * ], + * + * // What effect your manageOffer op had + * effect: "manageOfferCreated|manageOfferUpdated|manageOfferDeleted", + * + * // Whether your offer immediately got matched and filled + * wasImmediatelyFilled: Boolean, + * + * // Whether your offer immediately got deleted, if for example the order was too small + * wasImmediatelyDeleted: Boolean, + * + * // Whether the offer was partially, but not completely, filled + * wasPartiallyFilled: Boolean, + * + * // The full requested amount of the offer is open for matching + * isFullyOpen: Boolean, + * + * // The total amount of tokens bought / sold during transaction execution + * amountBought: Number, + * amountSold: Number, + * + * // if the offer was created, updated, or partially filled, this is + * // the outstanding offer + * currentOffer: { + * offerId: String, + * amount: String, + * price: { + * n: String, + * d: String, + * }, + * + * selling: { + * type: 'native|credit_alphanum4|credit_alphanum12', + * + * // these are only present if the asset is not native + * assetCode: String, + * issuer: String, + * }, + * + * // same as `selling` + * buying: {}, + * }, + * + * // the index of this particular operation in the op stack + * operationIndex: Number + * } + * ] + * } + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/submit-a-transaction|Submit a Transaction} + * @param {Transaction|FeeBumpTransaction} transaction - The transaction to submit. + * @param {object} [opts] Options object + * @param {boolean} [opts.skipMemoRequiredCheck] - Allow skipping memo + * required check, default: `false`. See + * [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md). + * @returns {Promise} Promise that resolves or rejects with response from + * horizon. + */ + submitTransaction(transaction: Transaction | FeeBumpTransaction, opts?: HorizonServer.SubmitTransactionOptions): Promise; + /** + * Submits an asynchronous transaction to the network. Unlike the synchronous version, which blocks + * and waits for the transaction to be ingested in Horizon, this endpoint relays the response from + * core directly back to the user. + * + * By default, this function calls {@link HorizonServer#checkMemoRequired}, you can + * skip this check by setting the option `skipMemoRequiredCheck` to `true`. + * + * @see [Submit-Async-Transaction](https://developers.stellar.org/docs/data/horizon/api-reference/resources/submit-async-transaction) + * @param {Transaction|FeeBumpTransaction} transaction - The transaction to submit. + * @param {object} [opts] Options object + * @param {boolean} [opts.skipMemoRequiredCheck] - Allow skipping memo + * required check, default: `false`. See + * [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md). + * @returns {Promise} Promise that resolves or rejects with response from + * horizon. + */ + submitAsyncTransaction(transaction: Transaction | FeeBumpTransaction, opts?: HorizonServer.SubmitTransactionOptions): Promise; + /** + * @returns {AccountCallBuilder} New {@link AccountCallBuilder} object configured by a current Horizon server configuration. + */ + accounts(): AccountCallBuilder; + /** + * @returns {ClaimableBalanceCallBuilder} New {@link ClaimableBalanceCallBuilder} object configured by a current Horizon server configuration. + */ + claimableBalances(): ClaimableBalanceCallBuilder; + /** + * @returns {LedgerCallBuilder} New {@link LedgerCallBuilder} object configured by a current Horizon server configuration. + */ + ledgers(): LedgerCallBuilder; + /** + * @returns {TransactionCallBuilder} New {@link TransactionCallBuilder} object configured by a current Horizon server configuration. + */ + transactions(): TransactionCallBuilder; + /** + * People on the Stellar network can make offers to buy or sell assets. This endpoint represents all the offers on the DEX. + * + * You can query all offers for account using the function `.accountId`. + * + * @example + * server.offers() + * .forAccount(accountId).call() + * .then(function(offers) { + * console.log(offers); + * }); + * + * @returns {OfferCallBuilder} New {@link OfferCallBuilder} object + */ + offers(): OfferCallBuilder; + /** + * @param {Asset} selling Asset being sold + * @param {Asset} buying Asset being bought + * @returns {OrderbookCallBuilder} New {@link OrderbookCallBuilder} object configured by a current Horizon server configuration. + */ + orderbook(selling: Asset, buying: Asset): OrderbookCallBuilder; + /** + * Returns + * @returns {TradesCallBuilder} New {@link TradesCallBuilder} object configured by a current Horizon server configuration. + */ + trades(): TradesCallBuilder; + /** + * @returns {OperationCallBuilder} New {@link OperationCallBuilder} object configured by a current Horizon server configuration. + */ + operations(): OperationCallBuilder; + /** + * @returns {LiquidityPoolCallBuilder} New {@link LiquidityPoolCallBuilder} + * object configured to the current Horizon server settings. + */ + liquidityPools(): LiquidityPoolCallBuilder; + /** + * The Stellar Network allows payments to be made between assets through path + * payments. A strict receive path payment specifies a series of assets to + * route a payment through, from source asset (the asset debited from the + * payer) to destination asset (the asset credited to the payee). + * + * A strict receive path search is specified using: + * + * * The destination address. + * * The source address or source assets. + * * The asset and amount that the destination account should receive. + * + * As part of the search, horizon will load a list of assets available to the + * source address and will find any payment paths from those source assets to + * the desired destination asset. The search's amount parameter will be used + * to determine if there a given path can satisfy a payment of the desired + * amount. + * + * If a list of assets is passed as the source, horizon will find any payment + * paths from those source assets to the desired destination asset. + * + * @param {string|Asset[]} source The sender's account ID or a list of assets. Any returned path will use a source that the sender can hold. + * @param {Asset} destinationAsset The destination asset. + * @param {string} destinationAmount The amount, denominated in the destination asset, that any returned path should be able to satisfy. + * @returns {StrictReceivePathCallBuilder} New {@link StrictReceivePathCallBuilder} object configured with the current Horizon server configuration. + */ + strictReceivePaths(source: string | Asset[], destinationAsset: Asset, destinationAmount: string): PathCallBuilder; + /** + * The Stellar Network allows payments to be made between assets through path payments. A strict send path payment specifies a + * series of assets to route a payment through, from source asset (the asset debited from the payer) to destination + * asset (the asset credited to the payee). + * + * A strict send path search is specified using: + * + * The asset and amount that is being sent. + * The destination account or the destination assets. + * + * @param {Asset} sourceAsset The asset to be sent. + * @param {string} sourceAmount The amount, denominated in the source asset, that any returned path should be able to satisfy. + * @param {string|Asset[]} destination The destination account or the destination assets. + * @returns {StrictSendPathCallBuilder} New {@link StrictSendPathCallBuilder} object configured with the current Horizon server configuration. + */ + strictSendPaths(sourceAsset: Asset, sourceAmount: string, destination: string | Asset[]): PathCallBuilder; + /** + * @returns {PaymentCallBuilder} New {@link PaymentCallBuilder} instance configured with the current + * Horizon server configuration. + */ + payments(): PaymentCallBuilder; + /** + * @returns {EffectCallBuilder} New {@link EffectCallBuilder} instance configured with the current + * Horizon server configuration + */ + effects(): EffectCallBuilder; + /** + * @param {string} address The Stellar ID that you want Friendbot to send lumens to + * @returns {FriendbotBuilder} New {@link FriendbotBuilder} instance configured with the current + * Horizon server configuration + * @private + */ + friendbot(address: string): FriendbotBuilder; + /** + * Get a new {@link AssetsCallBuilder} instance configured with the current + * Horizon server configuration. + * @returns {AssetsCallBuilder} New AssetsCallBuilder instance + */ + assets(): AssetsCallBuilder; + /** + * Fetches an account's most current state in the ledger, then creates and + * returns an {@link AccountResponse} object. + * + * @param {string} accountId - The account to load. + * + * @returns {Promise} Returns a promise to the {@link AccountResponse} object + * with populated sequence number. + */ + loadAccount(accountId: string): Promise; + /** + * + * @param {Asset} base base asset + * @param {Asset} counter counter asset + * @param {number} start_time lower time boundary represented as millis since epoch + * @param {number} end_time upper time boundary represented as millis since epoch + * @param {number} resolution segment duration as millis since epoch. *Supported values are 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). + * @param {number} offset segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. + * Returns new {@link TradeAggregationCallBuilder} object configured with the current Horizon server configuration. + * @returns {TradeAggregationCallBuilder} New TradeAggregationCallBuilder instance + */ + tradeAggregation(base: Asset, counter: Asset, start_time: number, end_time: number, resolution: number, offset: number): TradeAggregationCallBuilder; + /** + * Check if any of the destination accounts requires a memo. + * + * This function implements a memo required check as defined in + * [SEP-29](https://stellar.org/protocol/sep-29). It will load each account + * which is the destination and check if it has the data field + * `config.memo_required` set to `"MQ=="`. + * + * Each account is checked sequentially instead of loading multiple accounts + * at the same time from Horizon. + * + * @see {@link https://stellar.org/protocol/sep-29|SEP-29: Account Memo Requirements} + * @param {Transaction} transaction - The transaction to check. + * @returns {Promise} - If any of the destination account + * requires a memo, the promise will throw {@link AccountRequiresMemoError}. + * @throws {AccountRequiresMemoError} + */ + checkMemoRequired(transaction: Transaction | FeeBumpTransaction): Promise; +} +/** + * Options for configuring connections to Horizon servers. + * @typedef {object} Options + * @memberof module:Horizon.Server + * @property {boolean} [allowHttp] Allow connecting to http servers, default: `false`. This must be set to false in production deployments! You can also use {@link Config} class to set this globally. + * @property {string} [appName] Allow set custom header `X-App-Name`, default: `undefined`. + * @property {string} [appVersion] Allow set custom header `X-App-Version`, default: `undefined`. + * @property {string} [authToken] Allow set custom header `X-Auth-Token`, default: `undefined`. + */ +export declare namespace HorizonServer { + interface Options { + allowHttp?: boolean; + appName?: string; + appVersion?: string; + authToken?: string; + headers?: Record; + } + interface Timebounds { + minTime: number; + maxTime: number; + } + interface SubmitTransactionOptions { + skipMemoRequiredCheck?: boolean; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/server.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/server.js new file mode 100644 index 000000000..111c8b341 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/server.js @@ -0,0 +1,571 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SUBMIT_TRANSACTION_TIMEOUT = exports.HorizonServer = void 0; +var _bignumber = _interopRequireDefault(require("bignumber.js")); +var _stellarBase = require("@stellar/stellar-base"); +var _urijs = _interopRequireDefault(require("urijs")); +var _call_builder = require("./call_builder"); +var _config = require("../config"); +var _errors = require("../errors"); +var _account_call_builder = require("./account_call_builder"); +var _account_response = require("./account_response"); +var _assets_call_builder = require("./assets_call_builder"); +var _claimable_balances_call_builder = require("./claimable_balances_call_builder"); +var _effect_call_builder = require("./effect_call_builder"); +var _friendbot_builder = require("./friendbot_builder"); +var _ledger_call_builder = require("./ledger_call_builder"); +var _liquidity_pool_call_builder = require("./liquidity_pool_call_builder"); +var _offer_call_builder = require("./offer_call_builder"); +var _operation_call_builder = require("./operation_call_builder"); +var _orderbook_call_builder = require("./orderbook_call_builder"); +var _payment_call_builder = require("./payment_call_builder"); +var _strict_receive_path_call_builder = require("./strict_receive_path_call_builder"); +var _strict_send_path_call_builder = require("./strict_send_path_call_builder"); +var _trade_aggregation_call_builder = require("./trade_aggregation_call_builder"); +var _trades_call_builder = require("./trades_call_builder"); +var _transaction_call_builder = require("./transaction_call_builder"); +var _horizon_axios_client = _interopRequireWildcard(require("./horizon_axios_client")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var SUBMIT_TRANSACTION_TIMEOUT = exports.SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000; +var STROOPS_IN_LUMEN = 10000000; +var ACCOUNT_REQUIRES_MEMO = "MQ=="; +function getAmountInLumens(amt) { + return new _bignumber.default(amt).div(STROOPS_IN_LUMEN).toString(); +} +var HorizonServer = exports.HorizonServer = function () { + function HorizonServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, HorizonServer); + this.serverURL = (0, _urijs.default)(serverURL); + var allowHttp = typeof opts.allowHttp === "undefined" ? _config.Config.isAllowHttp() : opts.allowHttp; + var customHeaders = {}; + if (opts.appName) { + customHeaders["X-App-Name"] = opts.appName; + } + if (opts.appVersion) { + customHeaders["X-App-Version"] = opts.appVersion; + } + if (opts.authToken) { + customHeaders["X-Auth-Token"] = opts.authToken; + } + if (opts.headers) { + Object.assign(customHeaders, opts.headers); + } + if (Object.keys(customHeaders).length > 0) { + _horizon_axios_client.default.interceptors.request.use(function (config) { + config.headers = config.headers || {}; + config.headers = Object.assign(config.headers, customHeaders); + return config; + }); + } + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure horizon server"); + } + } + return _createClass(HorizonServer, [{ + key: "fetchTimebounds", + value: (function () { + var _fetchTimebounds = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(seconds) { + var _isRetry, + currentTime, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _isRetry = _args.length > 1 && _args[1] !== undefined ? _args[1] : false; + currentTime = (0, _horizon_axios_client.getCurrentServerTime)(this.serverURL.hostname()); + if (!currentTime) { + _context.next = 4; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: currentTime + seconds + }); + case 4: + if (!_isRetry) { + _context.next = 6; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: Math.floor(new Date().getTime() / 1000) + seconds + }); + case 6: + _context.next = 8; + return _horizon_axios_client.default.get((0, _urijs.default)(this.serverURL).toString()); + case 8: + return _context.abrupt("return", this.fetchTimebounds(seconds, true)); + case 9: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function fetchTimebounds(_x) { + return _fetchTimebounds.apply(this, arguments); + } + return fetchTimebounds; + }()) + }, { + key: "fetchBaseFee", + value: (function () { + var _fetchBaseFee = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + var response; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.feeStats(); + case 2: + response = _context2.sent; + return _context2.abrupt("return", parseInt(response.last_ledger_base_fee, 10) || 100); + case 4: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function fetchBaseFee() { + return _fetchBaseFee.apply(this, arguments); + } + return fetchBaseFee; + }()) + }, { + key: "feeStats", + value: (function () { + var _feeStats = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3() { + var cb; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + cb = new _call_builder.CallBuilder((0, _urijs.default)(this.serverURL)); + cb.filter.push(["fee_stats"]); + return _context3.abrupt("return", cb.call()); + case 3: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function feeStats() { + return _feeStats.apply(this, arguments); + } + return feeStats; + }()) + }, { + key: "root", + value: (function () { + var _root = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + var cb; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + cb = new _call_builder.CallBuilder((0, _urijs.default)(this.serverURL)); + return _context4.abrupt("return", cb.call()); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function root() { + return _root.apply(this, arguments); + } + return root; + }()) + }, { + key: "submitTransaction", + value: (function () { + var _submitTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(transaction) { + var opts, + tx, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context5.next = 4; + break; + } + _context5.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context5.abrupt("return", _horizon_axios_client.default.post((0, _urijs.default)(this.serverURL).segment("transactions").toString(), "tx=".concat(tx), { + timeout: SUBMIT_TRANSACTION_TIMEOUT + }).then(function (response) { + if (!response.data.result_xdr) { + return response.data; + } + var responseXDR = _stellarBase.xdr.TransactionResult.fromXDR(response.data.result_xdr, "base64"); + var results = responseXDR.result().value(); + var offerResults; + var hasManageOffer; + if (results.length) { + offerResults = results.map(function (result, i) { + if (result.value().switch().name !== "manageBuyOffer" && result.value().switch().name !== "manageSellOffer") { + return null; + } + hasManageOffer = true; + var amountBought = new _bignumber.default(0); + var amountSold = new _bignumber.default(0); + var offerSuccess = result.value().value().success(); + var offersClaimed = offerSuccess.offersClaimed().map(function (offerClaimedAtom) { + var offerClaimed = offerClaimedAtom.value(); + var sellerId = ""; + switch (offerClaimedAtom.switch()) { + case _stellarBase.xdr.ClaimAtomType.claimAtomTypeV0(): + sellerId = _stellarBase.StrKey.encodeEd25519PublicKey(offerClaimed.sellerEd25519()); + break; + case _stellarBase.xdr.ClaimAtomType.claimAtomTypeOrderBook(): + sellerId = _stellarBase.StrKey.encodeEd25519PublicKey(offerClaimed.sellerId().ed25519()); + break; + default: + throw new Error("Invalid offer result type: ".concat(offerClaimedAtom.switch())); + } + var claimedOfferAmountBought = new _bignumber.default(offerClaimed.amountBought().toString()); + var claimedOfferAmountSold = new _bignumber.default(offerClaimed.amountSold().toString()); + amountBought = amountBought.plus(claimedOfferAmountSold); + amountSold = amountSold.plus(claimedOfferAmountBought); + var sold = _stellarBase.Asset.fromOperation(offerClaimed.assetSold()); + var bought = _stellarBase.Asset.fromOperation(offerClaimed.assetBought()); + var assetSold = { + type: sold.getAssetType(), + assetCode: sold.getCode(), + issuer: sold.getIssuer() + }; + var assetBought = { + type: bought.getAssetType(), + assetCode: bought.getCode(), + issuer: bought.getIssuer() + }; + return { + sellerId: sellerId, + offerId: offerClaimed.offerId().toString(), + assetSold: assetSold, + amountSold: getAmountInLumens(claimedOfferAmountSold), + assetBought: assetBought, + amountBought: getAmountInLumens(claimedOfferAmountBought) + }; + }); + var effect = offerSuccess.offer().switch().name; + var currentOffer; + if (typeof offerSuccess.offer().value === "function" && offerSuccess.offer().value()) { + var offerXDR = offerSuccess.offer().value(); + currentOffer = { + offerId: offerXDR.offerId().toString(), + selling: {}, + buying: {}, + amount: getAmountInLumens(offerXDR.amount().toString()), + price: { + n: offerXDR.price().n(), + d: offerXDR.price().d() + } + }; + var selling = _stellarBase.Asset.fromOperation(offerXDR.selling()); + currentOffer.selling = { + type: selling.getAssetType(), + assetCode: selling.getCode(), + issuer: selling.getIssuer() + }; + var buying = _stellarBase.Asset.fromOperation(offerXDR.buying()); + currentOffer.buying = { + type: buying.getAssetType(), + assetCode: buying.getCode(), + issuer: buying.getIssuer() + }; + } + return { + offersClaimed: offersClaimed, + effect: effect, + operationIndex: i, + currentOffer: currentOffer, + amountBought: getAmountInLumens(amountBought), + amountSold: getAmountInLumens(amountSold), + isFullyOpen: !offersClaimed.length && effect !== "manageOfferDeleted", + wasPartiallyFilled: !!offersClaimed.length && effect !== "manageOfferDeleted", + wasImmediatelyFilled: !!offersClaimed.length && effect === "manageOfferDeleted", + wasImmediatelyDeleted: !offersClaimed.length && effect === "manageOfferDeleted" + }; + }).filter(function (result) { + return !!result; + }); + } + return _objectSpread(_objectSpread({}, response.data), {}, { + offerResults: hasManageOffer ? offerResults : undefined + }); + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new _errors.BadResponseError("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function submitTransaction(_x2) { + return _submitTransaction.apply(this, arguments); + } + return submitTransaction; + }()) + }, { + key: "submitAsyncTransaction", + value: (function () { + var _submitAsyncTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(transaction) { + var opts, + tx, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context6.next = 4; + break; + } + _context6.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context6.abrupt("return", _horizon_axios_client.default.post((0, _urijs.default)(this.serverURL).segment("transactions_async").toString(), "tx=".concat(tx)).then(function (response) { + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new _errors.BadResponseError("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function submitAsyncTransaction(_x3) { + return _submitAsyncTransaction.apply(this, arguments); + } + return submitAsyncTransaction; + }()) + }, { + key: "accounts", + value: function accounts() { + return new _account_call_builder.AccountCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "claimableBalances", + value: function claimableBalances() { + return new _claimable_balances_call_builder.ClaimableBalanceCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "ledgers", + value: function ledgers() { + return new _ledger_call_builder.LedgerCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "transactions", + value: function transactions() { + return new _transaction_call_builder.TransactionCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "offers", + value: function offers() { + return new _offer_call_builder.OfferCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "orderbook", + value: function orderbook(selling, buying) { + return new _orderbook_call_builder.OrderbookCallBuilder((0, _urijs.default)(this.serverURL), selling, buying); + } + }, { + key: "trades", + value: function trades() { + return new _trades_call_builder.TradesCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "operations", + value: function operations() { + return new _operation_call_builder.OperationCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "liquidityPools", + value: function liquidityPools() { + return new _liquidity_pool_call_builder.LiquidityPoolCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "strictReceivePaths", + value: function strictReceivePaths(source, destinationAsset, destinationAmount) { + return new _strict_receive_path_call_builder.StrictReceivePathCallBuilder((0, _urijs.default)(this.serverURL), source, destinationAsset, destinationAmount); + } + }, { + key: "strictSendPaths", + value: function strictSendPaths(sourceAsset, sourceAmount, destination) { + return new _strict_send_path_call_builder.StrictSendPathCallBuilder((0, _urijs.default)(this.serverURL), sourceAsset, sourceAmount, destination); + } + }, { + key: "payments", + value: function payments() { + return new _payment_call_builder.PaymentCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "effects", + value: function effects() { + return new _effect_call_builder.EffectCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "friendbot", + value: function friendbot(address) { + return new _friendbot_builder.FriendbotBuilder((0, _urijs.default)(this.serverURL), address); + } + }, { + key: "assets", + value: function assets() { + return new _assets_call_builder.AssetsCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "loadAccount", + value: (function () { + var _loadAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee7(accountId) { + var res; + return _regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.accounts().accountId(accountId).call(); + case 2: + res = _context7.sent; + return _context7.abrupt("return", new _account_response.AccountResponse(res)); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function loadAccount(_x4) { + return _loadAccount.apply(this, arguments); + } + return loadAccount; + }()) + }, { + key: "tradeAggregation", + value: function tradeAggregation(base, counter, start_time, end_time, resolution, offset) { + return new _trade_aggregation_call_builder.TradeAggregationCallBuilder((0, _urijs.default)(this.serverURL), base, counter, start_time, end_time, resolution, offset); + } + }, { + key: "checkMemoRequired", + value: (function () { + var _checkMemoRequired = _asyncToGenerator(_regeneratorRuntime().mark(function _callee8(transaction) { + var destinations, i, operation, destination, account; + return _regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (transaction instanceof _stellarBase.FeeBumpTransaction) { + transaction = transaction.innerTransaction; + } + if (!(transaction.memo.type !== "none")) { + _context8.next = 3; + break; + } + return _context8.abrupt("return"); + case 3: + destinations = new Set(); + i = 0; + case 5: + if (!(i < transaction.operations.length)) { + _context8.next = 36; + break; + } + operation = transaction.operations[i]; + _context8.t0 = operation.type; + _context8.next = _context8.t0 === "payment" ? 10 : _context8.t0 === "pathPaymentStrictReceive" ? 10 : _context8.t0 === "pathPaymentStrictSend" ? 10 : _context8.t0 === "accountMerge" ? 10 : 11; + break; + case 10: + return _context8.abrupt("break", 12); + case 11: + return _context8.abrupt("continue", 33); + case 12: + destination = operation.destination; + if (!destinations.has(destination)) { + _context8.next = 15; + break; + } + return _context8.abrupt("continue", 33); + case 15: + destinations.add(destination); + if (!destination.startsWith("M")) { + _context8.next = 18; + break; + } + return _context8.abrupt("continue", 33); + case 18: + _context8.prev = 18; + _context8.next = 21; + return this.loadAccount(destination); + case 21: + account = _context8.sent; + if (!(account.data_attr["config.memo_required"] === ACCOUNT_REQUIRES_MEMO)) { + _context8.next = 24; + break; + } + throw new _errors.AccountRequiresMemoError("account requires memo", destination, i); + case 24: + _context8.next = 33; + break; + case 26: + _context8.prev = 26; + _context8.t1 = _context8["catch"](18); + if (!(_context8.t1 instanceof _errors.AccountRequiresMemoError)) { + _context8.next = 30; + break; + } + throw _context8.t1; + case 30: + if (_context8.t1 instanceof _errors.NotFoundError) { + _context8.next = 32; + break; + } + throw _context8.t1; + case 32: + return _context8.abrupt("continue", 33); + case 33: + i += 1; + _context8.next = 5; + break; + case 36: + case "end": + return _context8.stop(); + } + }, _callee8, this, [[18, 26]]); + })); + function checkMemoRequired(_x5) { + return _checkMemoRequired.apply(this, arguments); + } + return checkMemoRequired; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/server_api.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/server_api.d.ts new file mode 100644 index 000000000..77a8367ba --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/server_api.d.ts @@ -0,0 +1,264 @@ +import { Asset } from "@stellar/stellar-base"; +import { HorizonApi } from "./horizon_api"; +import { AccountRecordSigners as AccountRecordSignersType } from "./types/account"; +import { AssetRecord as AssetRecordType } from "./types/assets"; +import * as Effects from "./types/effects"; +import { OfferRecord as OfferRecordType } from "./types/offer"; +import { Trade } from "./types/trade"; +export declare namespace ServerApi { + export type OfferRecord = OfferRecordType; + export type AccountRecordSigners = AccountRecordSignersType; + export type AssetRecord = AssetRecordType; + export interface CollectionPage { + records: T[]; + next: () => Promise>; + prev: () => Promise>; + } + export interface CallFunctionTemplateOptions { + cursor?: string | number; + limit?: number; + order?: "asc" | "desc"; + } + export type CallFunction = () => Promise; + export type CallCollectionFunction = (options?: CallFunctionTemplateOptions) => Promise>; + type BaseEffectRecordFromTypes = Effects.AccountCreated | Effects.AccountCredited | Effects.AccountDebited | Effects.AccountThresholdsUpdated | Effects.AccountHomeDomainUpdated | Effects.AccountFlagsUpdated | Effects.DataCreated | Effects.DataRemoved | Effects.DataUpdated | Effects.SequenceBumped | Effects.SignerCreated | Effects.SignerRemoved | Effects.SignerUpdated | Effects.TrustlineCreated | Effects.TrustlineRemoved | Effects.TrustlineUpdated | Effects.TrustlineAuthorized | Effects.TrustlineDeauthorized | Effects.TrustlineAuthorizedToMaintainLiabilities | Effects.ClaimableBalanceCreated | Effects.ClaimableBalanceClaimed | Effects.ClaimableBalanceClaimantCreated | Effects.AccountSponsorshipCreated | Effects.AccountSponsorshipRemoved | Effects.AccountSponsorshipUpdated | Effects.TrustlineSponsorshipCreated | Effects.TrustlineSponsorshipUpdated | Effects.TrustlineSponsorshipRemoved | Effects.DateSponsorshipCreated | Effects.DateSponsorshipUpdated | Effects.DateSponsorshipRemoved | Effects.ClaimableBalanceSponsorshipCreated | Effects.ClaimableBalanceSponsorshipRemoved | Effects.ClaimableBalanceSponsorshipUpdated | Effects.SignerSponsorshipCreated | Effects.SignerSponsorshipUpdated | Effects.SignerSponsorshipRemoved | Effects.LiquidityPoolDeposited | Effects.LiquidityPoolWithdrew | Effects.LiquidityPoolCreated | Effects.LiquidityPoolRemoved | Effects.LiquidityPoolRevoked | Effects.LiquidityPoolTrade | Effects.ContractCredited | Effects.ContractDebited | Trade; + export type EffectRecord = BaseEffectRecordFromTypes & EffectRecordMethods; + export const EffectType: typeof Effects.EffectType; + export interface ClaimableBalanceRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + asset: string; + amount: string; + sponsor?: string; + last_modified_ledger: number; + claimants: HorizonApi.Claimant[]; + } + export interface AccountRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + account_id: string; + sequence: string; + sequence_ledger?: number; + sequence_time?: string; + subentry_count: number; + home_domain?: string; + inflation_destination?: string; + last_modified_ledger: number; + last_modified_time: string; + thresholds: HorizonApi.AccountThresholds; + flags: HorizonApi.Flags; + balances: HorizonApi.BalanceLine[]; + signers: AccountRecordSigners[]; + data: (options: { + value: string; + }) => Promise<{ + value: string; + }>; + data_attr: { + [key: string]: string; + }; + sponsor?: string; + num_sponsoring: number; + num_sponsored: number; + effects: CallCollectionFunction; + offers: CallCollectionFunction; + operations: CallCollectionFunction; + payments: CallCollectionFunction; + trades: CallCollectionFunction; + } + export interface LiquidityPoolRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + fee_bp: number; + type: HorizonApi.LiquidityPoolType; + total_trustlines: string; + total_shares: string; + reserves: HorizonApi.Reserve[]; + } + export enum TradeType { + all = "all", + liquidityPools = "liquidity_pool", + orderbook = "orderbook" + } + interface EffectRecordMethods { + operation?: CallFunction; + precedes?: CallFunction; + succeeds?: CallFunction; + } + export interface LedgerRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + hash: string; + prev_hash: string; + sequence: number; + successful_transaction_count: number; + failed_transaction_count: number; + operation_count: number; + tx_set_operation_count: number | null; + closed_at: string; + total_coins: string; + fee_pool: string; + max_tx_set_size: number; + protocol_version: number; + header_xdr: string; + base_fee_in_stroops: number; + base_reserve_in_stroops: number; + effects: CallCollectionFunction; + operations: CallCollectionFunction; + self: CallFunction; + transactions: CallCollectionFunction; + } + import OperationResponseType = HorizonApi.OperationResponseType; + import OperationResponseTypeI = HorizonApi.OperationResponseTypeI; + export interface BaseOperationRecord extends HorizonApi.BaseOperationResponse { + self: CallFunction; + succeeds: CallFunction; + precedes: CallFunction; + effects: CallCollectionFunction; + transaction: CallFunction; + } + export interface CreateAccountOperationRecord extends BaseOperationRecord, HorizonApi.CreateAccountOperationResponse { + } + export interface PaymentOperationRecord extends BaseOperationRecord, HorizonApi.PaymentOperationResponse { + sender: CallFunction; + receiver: CallFunction; + } + export interface PathPaymentOperationRecord extends BaseOperationRecord, HorizonApi.PathPaymentOperationResponse { + } + export interface PathPaymentStrictSendOperationRecord extends BaseOperationRecord, HorizonApi.PathPaymentStrictSendOperationResponse { + } + export interface ManageOfferOperationRecord extends BaseOperationRecord, HorizonApi.ManageOfferOperationResponse { + } + export interface PassiveOfferOperationRecord extends BaseOperationRecord, HorizonApi.PassiveOfferOperationResponse { + } + export interface SetOptionsOperationRecord extends BaseOperationRecord, HorizonApi.SetOptionsOperationResponse { + } + export interface ChangeTrustOperationRecord extends BaseOperationRecord, HorizonApi.ChangeTrustOperationResponse { + } + export interface AllowTrustOperationRecord extends BaseOperationRecord, HorizonApi.AllowTrustOperationResponse { + } + export interface AccountMergeOperationRecord extends BaseOperationRecord, HorizonApi.AccountMergeOperationResponse { + } + export interface InflationOperationRecord extends BaseOperationRecord, HorizonApi.InflationOperationResponse { + } + export interface ManageDataOperationRecord extends BaseOperationRecord, HorizonApi.ManageDataOperationResponse { + } + export interface BumpSequenceOperationRecord extends BaseOperationRecord, HorizonApi.BumpSequenceOperationResponse { + } + export interface CreateClaimableBalanceOperationRecord extends BaseOperationRecord, HorizonApi.CreateClaimableBalanceOperationResponse { + } + export interface ClaimClaimableBalanceOperationRecord extends BaseOperationRecord, HorizonApi.ClaimClaimableBalanceOperationResponse { + } + export interface BeginSponsoringFutureReservesOperationRecord extends BaseOperationRecord, HorizonApi.BeginSponsoringFutureReservesOperationResponse { + } + export interface EndSponsoringFutureReservesOperationRecord extends BaseOperationRecord, HorizonApi.EndSponsoringFutureReservesOperationResponse { + } + export interface RevokeSponsorshipOperationRecord extends BaseOperationRecord, HorizonApi.RevokeSponsorshipOperationResponse { + } + export interface ClawbackOperationRecord extends BaseOperationRecord, HorizonApi.ClawbackOperationResponse { + } + export interface ClawbackClaimableBalanceOperationRecord extends BaseOperationRecord, HorizonApi.ClawbackClaimableBalanceOperationResponse { + } + export interface SetTrustLineFlagsOperationRecord extends BaseOperationRecord, HorizonApi.SetTrustLineFlagsOperationResponse { + } + export interface DepositLiquidityOperationRecord extends BaseOperationRecord, HorizonApi.DepositLiquidityOperationResponse { + } + export interface WithdrawLiquidityOperationRecord extends BaseOperationRecord, HorizonApi.WithdrawLiquidityOperationResponse { + } + export interface InvokeHostFunctionOperationRecord extends BaseOperationRecord, HorizonApi.InvokeHostFunctionOperationResponse { + } + export interface BumpFootprintExpirationOperationRecord extends BaseOperationRecord, HorizonApi.BumpFootprintExpirationOperationResponse { + } + export interface RestoreFootprintOperationRecord extends BaseOperationRecord, HorizonApi.RestoreFootprintOperationResponse { + } + export type OperationRecord = CreateAccountOperationRecord | PaymentOperationRecord | PathPaymentOperationRecord | ManageOfferOperationRecord | PassiveOfferOperationRecord | SetOptionsOperationRecord | ChangeTrustOperationRecord | AllowTrustOperationRecord | AccountMergeOperationRecord | InflationOperationRecord | ManageDataOperationRecord | BumpSequenceOperationRecord | PathPaymentStrictSendOperationRecord | CreateClaimableBalanceOperationRecord | ClaimClaimableBalanceOperationRecord | BeginSponsoringFutureReservesOperationRecord | EndSponsoringFutureReservesOperationRecord | RevokeSponsorshipOperationRecord | ClawbackClaimableBalanceOperationRecord | ClawbackOperationRecord | SetTrustLineFlagsOperationRecord | DepositLiquidityOperationRecord | WithdrawLiquidityOperationRecord | InvokeHostFunctionOperationRecord | BumpFootprintExpirationOperationRecord | RestoreFootprintOperationRecord; + export namespace TradeRecord { + interface Base extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + ledger_close_time: string; + trade_type: TradeType; + base_account?: string; + base_amount: string; + base_asset_type: string; + base_asset_code?: string; + base_asset_issuer?: string; + counter_account?: string; + counter_amount: string; + counter_asset_type: string; + counter_asset_code?: string; + counter_asset_issuer?: string; + base_is_seller: boolean; + price?: { + n: string; + d: string; + }; + operation: CallFunction; + } + export interface Orderbook extends Base { + trade_type: TradeType.orderbook; + base_offer_id: string; + base_account: string; + counter_offer_id: string; + counter_account: string; + base: CallFunction; + counter: CallFunction; + } + export interface LiquidityPool extends Base { + trade_type: TradeType.liquidityPools; + base_liquidity_pool_id?: string; + counter_liquidity_pool_id?: string; + liquidity_pool_fee_bp: number; + base: CallFunction; + counter: CallFunction; + } + export {}; + } + export type TradeRecord = TradeRecord.Orderbook | TradeRecord.LiquidityPool; + export interface TransactionRecord extends Omit { + ledger_attr: HorizonApi.TransactionResponse["ledger"]; + account: CallFunction; + effects: CallCollectionFunction; + ledger: CallFunction; + operations: CallCollectionFunction; + precedes: CallFunction; + self: CallFunction; + succeeds: CallFunction; + } + export interface OrderbookRecord extends HorizonApi.BaseResponse { + bids: Array<{ + price_r: { + d: number; + n: number; + }; + price: string; + amount: string; + }>; + asks: Array<{ + price_r: { + d: number; + n: number; + }; + price: string; + amount: string; + }>; + base: Asset; + counter: Asset; + } + export interface PaymentPathRecord extends HorizonApi.BaseResponse { + path: Array<{ + asset_code: string; + asset_issuer: string; + asset_type: string; + }>; + source_amount: string; + source_asset_type: string; + source_asset_code: string; + source_asset_issuer: string; + destination_amount: string; + destination_asset_type: string; + destination_asset_code: string; + destination_asset_issuer: string; + } + export {}; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/server_api.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/server_api.js new file mode 100644 index 000000000..df0eafd7f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/server_api.js @@ -0,0 +1,24 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ServerApi = void 0; +var _horizon_api = require("./horizon_api"); +var Effects = _interopRequireWildcard(require("./types/effects")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var ServerApi; +(function (_ServerApi) { + var EffectType = _ServerApi.EffectType = Effects.EffectType; + var TradeType = function (TradeType) { + TradeType["all"] = "all"; + TradeType["liquidityPools"] = "liquidity_pool"; + TradeType["orderbook"] = "orderbook"; + return TradeType; + }({}); + _ServerApi.TradeType = TradeType; + var OperationResponseType = _horizon_api.HorizonApi.OperationResponseType; + var OperationResponseTypeI = _horizon_api.HorizonApi.OperationResponseTypeI; +})(ServerApi || (exports.ServerApi = ServerApi = {})); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/strict_receive_path_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/strict_receive_path_call_builder.d.ts new file mode 100644 index 000000000..1e9a28025 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/strict_receive_path_call_builder.d.ts @@ -0,0 +1,38 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * The Stellar Network allows payments to be made across assets through path + * payments. A strict receive path payment specifies a series of assets to route + * a payment through, from source asset (the asset debited from the payer) to + * destination asset (the asset credited to the payee). + * + * A path search is specified using: + * + * * The source address or source assets. + * * The asset and amount that the destination account should receive + * + * As part of the search, horizon will load a list of assets available to the + * source address and will find any payment paths from those source assets to + * the desired destination asset. The search's amount parameter will be used to + * determine if there a given path can satisfy a payment of the desired amount. + * + * If a list of assets is passed as the source, horizon will find any payment + * paths from those source assets to the desired destination asset. + * + * Do not create this object directly, use {@link Horizon.Server#strictReceivePaths}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/paths|Find Payment Paths} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + * @param {string|Asset[]} source The sender's account ID or a list of Assets. Any returned path must use a source that the sender can hold. + * @param {Asset} destinationAsset The destination asset. + * @param {string} destinationAmount The amount, denominated in the destination asset, that any returned path should be able to satisfy. + */ +export declare class StrictReceivePathCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, source: string | Asset[], destinationAsset: Asset, destinationAmount: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/strict_receive_path_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/strict_receive_path_call_builder.js new file mode 100644 index 000000000..5e4a5a992 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/strict_receive_path_call_builder.js @@ -0,0 +1,50 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.StrictReceivePathCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var StrictReceivePathCallBuilder = exports.StrictReceivePathCallBuilder = function (_CallBuilder) { + function StrictReceivePathCallBuilder(serverUrl, source, destinationAsset, destinationAmount) { + var _this; + _classCallCheck(this, StrictReceivePathCallBuilder); + _this = _callSuper(this, StrictReceivePathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-receive"); + if (typeof source === "string") { + _this.url.setQuery("source_account", source); + } else { + var assets = source.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("source_assets", assets); + } + _this.url.setQuery("destination_amount", destinationAmount); + if (!destinationAsset.isNative()) { + _this.url.setQuery("destination_asset_type", destinationAsset.getAssetType()); + _this.url.setQuery("destination_asset_code", destinationAsset.getCode()); + _this.url.setQuery("destination_asset_issuer", destinationAsset.getIssuer()); + } else { + _this.url.setQuery("destination_asset_type", "native"); + } + return _this; + } + _inherits(StrictReceivePathCallBuilder, _CallBuilder); + return _createClass(StrictReceivePathCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/strict_send_path_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/strict_send_path_call_builder.d.ts new file mode 100644 index 000000000..85cd9a154 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/strict_send_path_call_builder.d.ts @@ -0,0 +1,38 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * The Stellar Network allows payments to be made across assets through path + * payments. A strict send path payment specifies a series of assets to route a + * payment through, from source asset (the asset debited from the payer) to + * destination asset (the asset credited to the payee). + * + * A strict send path search is specified using: + * + * The source asset + * The source amount + * The destination assets or destination account. + * + * As part of the search, horizon will load a list of assets available to the + * source address and will find any payment paths from those source assets to + * the desired destination asset. The search's source_amount parameter will be + * used to determine if there a given path can satisfy a payment of the desired + * amount. + * + * Do not create this object directly, use {@link Horizon.Server#strictSendPaths}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/paths|Find Payment Paths} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + * @param {Asset} sourceAsset The asset to be sent. + * @param {string} sourceAmount The amount, denominated in the source asset, that any returned path should be able to satisfy. + * @param {string|Asset[]} destination The destination account or the destination assets. + * + */ +export declare class StrictSendPathCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, sourceAsset: Asset, sourceAmount: string, destination: string | Asset[]); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/strict_send_path_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/strict_send_path_call_builder.js new file mode 100644 index 000000000..f65a1d0a5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/strict_send_path_call_builder.js @@ -0,0 +1,50 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.StrictSendPathCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var StrictSendPathCallBuilder = exports.StrictSendPathCallBuilder = function (_CallBuilder) { + function StrictSendPathCallBuilder(serverUrl, sourceAsset, sourceAmount, destination) { + var _this; + _classCallCheck(this, StrictSendPathCallBuilder); + _this = _callSuper(this, StrictSendPathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-send"); + if (sourceAsset.isNative()) { + _this.url.setQuery("source_asset_type", "native"); + } else { + _this.url.setQuery("source_asset_type", sourceAsset.getAssetType()); + _this.url.setQuery("source_asset_code", sourceAsset.getCode()); + _this.url.setQuery("source_asset_issuer", sourceAsset.getIssuer()); + } + _this.url.setQuery("source_amount", sourceAmount); + if (typeof destination === "string") { + _this.url.setQuery("destination_account", destination); + } else { + var assets = destination.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("destination_assets", assets); + } + return _this; + } + _inherits(StrictSendPathCallBuilder, _CallBuilder); + return _createClass(StrictSendPathCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/trade_aggregation_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/trade_aggregation_call_builder.d.ts new file mode 100644 index 000000000..fe8dc52d5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/trade_aggregation_call_builder.d.ts @@ -0,0 +1,49 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { HorizonApi } from "./horizon_api"; +import { ServerApi } from "./server_api"; +/** + * Trade Aggregations facilitate efficient gathering of historical trade data. + * + * Do not create this object directly, use {@link Horizon.Server#tradeAggregation}. + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl serverUrl Horizon server URL. + * @param {Asset} base base asset + * @param {Asset} counter counter asset + * @param {number} start_time lower time boundary represented as millis since epoch + * @param {number} end_time upper time boundary represented as millis since epoch + * @param {number} resolution segment duration as millis since epoch. *Supported values are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). + * @param {number} offset segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. + */ +export declare class TradeAggregationCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, base: Asset, counter: Asset, start_time: number, end_time: number, resolution: number, offset: number); + /** + * @private + * @param {number} resolution Trade data resolution in milliseconds + * @returns {boolean} true if the resolution is allowed + */ + private isValidResolution; + /** + * @private + * @param {number} offset Time offset in milliseconds + * @param {number} resolution Trade data resolution in milliseconds + * @returns {boolean} true if the offset is valid + */ + private isValidOffset; +} +interface TradeAggregationRecord extends HorizonApi.BaseResponse { + timestamp: number | string; + trade_count: number | string; + base_volume: string; + counter_volume: string; + avg: string; + high: string; + low: string; + open: string; + close: string; +} +export {}; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/trade_aggregation_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/trade_aggregation_call_builder.js new file mode 100644 index 000000000..b6866d738 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/trade_aggregation_call_builder.js @@ -0,0 +1,76 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TradeAggregationCallBuilder = void 0; +var _call_builder = require("./call_builder"); +var _errors = require("../errors"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var allowedResolutions = [60000, 300000, 900000, 3600000, 86400000, 604800000]; +var TradeAggregationCallBuilder = exports.TradeAggregationCallBuilder = function (_CallBuilder) { + function TradeAggregationCallBuilder(serverUrl, base, counter, start_time, end_time, resolution, offset) { + var _this; + _classCallCheck(this, TradeAggregationCallBuilder); + _this = _callSuper(this, TradeAggregationCallBuilder, [serverUrl]); + _this.url.segment("trade_aggregations"); + if (!base.isNative()) { + _this.url.setQuery("base_asset_type", base.getAssetType()); + _this.url.setQuery("base_asset_code", base.getCode()); + _this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + _this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + _this.url.setQuery("counter_asset_type", counter.getAssetType()); + _this.url.setQuery("counter_asset_code", counter.getCode()); + _this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + _this.url.setQuery("counter_asset_type", "native"); + } + if (typeof start_time !== "number" || typeof end_time !== "number") { + throw new _errors.BadRequestError("Invalid time bounds", [start_time, end_time]); + } else { + _this.url.setQuery("start_time", start_time.toString()); + _this.url.setQuery("end_time", end_time.toString()); + } + if (!_this.isValidResolution(resolution)) { + throw new _errors.BadRequestError("Invalid resolution", resolution); + } else { + _this.url.setQuery("resolution", resolution.toString()); + } + if (!_this.isValidOffset(offset, resolution)) { + throw new _errors.BadRequestError("Invalid offset", offset); + } else { + _this.url.setQuery("offset", offset.toString()); + } + return _this; + } + _inherits(TradeAggregationCallBuilder, _CallBuilder); + return _createClass(TradeAggregationCallBuilder, [{ + key: "isValidResolution", + value: function isValidResolution(resolution) { + return allowedResolutions.some(function (allowed) { + return allowed === resolution; + }); + } + }, { + key: "isValidOffset", + value: function isValidOffset(offset, resolution) { + var hour = 3600000; + return !(offset > resolution || offset >= 24 * hour || offset % hour !== 0); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/trades_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/trades_call_builder.d.ts new file mode 100644 index 000000000..2a407642e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/trades_call_builder.d.ts @@ -0,0 +1,52 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link TradesCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#trades}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/trades|Trades} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl serverUrl Horizon server URL. + */ +export declare class TradesCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Filter trades for a specific asset pair (orderbook) + * @param {Asset} base asset + * @param {Asset} counter asset + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forAssetPair(base: Asset, counter: Asset): this; + /** + * Filter trades for a specific offer + * @param {string} offerId ID of the offer + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forOffer(offerId: string): this; + /** + * Filter trades by a specific type. + * @param {ServerApi.TradeType} tradeType the trade type to filter by. + * @returns {TradesCallBuilder} current TradesCallBuilder instance. + */ + forType(tradeType: ServerApi.TradeType): this; + /** + * Filter trades for a specific account + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-trades-by-account-id|Trades for Account} + * @param {string} accountId For example: `GBYTR4MC5JAX4ALGUBJD7EIKZVM7CUGWKXIUJMRSMK573XH2O7VAK3SR` + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * Filter trades for a specific liquidity pool + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-related-trades|Trades for Liquidity Pool} + * @param {string} liquidityPoolId For example: `3b476aff8a406a6ec3b61d5c038009cef85f2ddfaf616822dc4fec92845149b4` + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forLiquidityPool(liquidityPoolId: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/trades_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/trades_call_builder.js new file mode 100644 index 000000000..5c6b23bec --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/trades_call_builder.js @@ -0,0 +1,72 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TradesCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var TradesCallBuilder = exports.TradesCallBuilder = function (_CallBuilder) { + function TradesCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, TradesCallBuilder); + _this = _callSuper(this, TradesCallBuilder, [serverUrl, "trades"]); + _this.url.segment("trades"); + return _this; + } + _inherits(TradesCallBuilder, _CallBuilder); + return _createClass(TradesCallBuilder, [{ + key: "forAssetPair", + value: function forAssetPair(base, counter) { + if (!base.isNative()) { + this.url.setQuery("base_asset_type", base.getAssetType()); + this.url.setQuery("base_asset_code", base.getCode()); + this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + this.url.setQuery("counter_asset_type", counter.getAssetType()); + this.url.setQuery("counter_asset_code", counter.getCode()); + this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + this.url.setQuery("counter_asset_type", "native"); + } + return this; + } + }, { + key: "forOffer", + value: function forOffer(offerId) { + this.url.setQuery("offer_id", offerId); + return this; + } + }, { + key: "forType", + value: function forType(tradeType) { + this.url.setQuery("trade_type", tradeType); + return this; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(liquidityPoolId) { + return this.forEndpoint("liquidity_pools", liquidityPoolId); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/transaction_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/transaction_call_builder.d.ts new file mode 100644 index 000000000..4c40ce94d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/transaction_call_builder.d.ts @@ -0,0 +1,60 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link TransactionCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#transactions}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-transactions|All Transactions} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + */ +export declare class TransactionCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The transaction details endpoint provides information on a single transaction. The transaction hash provided in the hash argument specifies which transaction to load. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-transaction|Transaction Details} + * @param {string} transactionId Transaction ID + * @returns {CallBuilder} a CallBuilder instance + */ + transaction(transactionId: string): CallBuilder; + /** + * This endpoint represents all transactions that affected a given account. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-transactions-by-account-id|Transactions for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {TransactionCallBuilder} current TransactionCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * This endpoint represents all transactions that reference a given claimable_balance. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/cb-retrieve-related-transactions|Transactions for Claimable Balance} + * @param {string} claimableBalanceId Claimable Balance ID + * @returns {TransactionCallBuilder} this TransactionCallBuilder instance + */ + forClaimableBalance(claimableBalanceId: string): this; + /** + * This endpoint represents all transactions in a given ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-ledgers-transactions|Transactions for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {TransactionCallBuilder} current TransactionCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all transactions involving a particular liquidity pool. + * + * @param {string} poolId liquidity pool ID + * @returns {TransactionCallBuilder} this TransactionCallBuilder instance + */ + forLiquidityPool(poolId: string): this; + /** + * Adds a parameter defining whether to include failed transactions. By default only successful transactions are + * returned. + * @param {boolean} value Set to `true` to include failed transactions. + * @returns {TransactionCallBuilder} current TransactionCallBuilder instance + */ + includeFailed(value: boolean): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/transaction_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/transaction_call_builder.js new file mode 100644 index 000000000..746c7bfbf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/transaction_call_builder.js @@ -0,0 +1,64 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TransactionCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var TransactionCallBuilder = exports.TransactionCallBuilder = function (_CallBuilder) { + function TransactionCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, TransactionCallBuilder); + _this = _callSuper(this, TransactionCallBuilder, [serverUrl, "transactions"]); + _this.url.segment("transactions"); + return _this; + } + _inherits(TransactionCallBuilder, _CallBuilder); + return _createClass(TransactionCallBuilder, [{ + key: "transaction", + value: function transaction(transactionId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([transactionId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/account.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/account.d.ts new file mode 100644 index 000000000..3edc78aad --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/account.d.ts @@ -0,0 +1,5 @@ +export interface AccountRecordSigners { + key: string; + weight: number; + type: string; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/account.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/account.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/account.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/assets.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/assets.d.ts new file mode 100644 index 000000000..c85e71a32 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/assets.d.ts @@ -0,0 +1,17 @@ +import { AssetType } from "@stellar/stellar-base"; +import { HorizonApi } from "../horizon_api"; +export interface AssetRecord extends HorizonApi.BaseResponse { + asset_type: AssetType.credit4 | AssetType.credit12; + asset_code: string; + asset_issuer: string; + paging_token: string; + accounts: HorizonApi.AssetAccounts; + balances: HorizonApi.AssetBalances; + num_claimable_balances: number; + num_liquidity_pools: number; + num_contracts: number; + claimable_balances_amount: string; + liquidity_pools_amount: string; + contracts_amount: string; + flags: HorizonApi.Flags; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/assets.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/assets.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/assets.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/effects.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/effects.d.ts new file mode 100644 index 000000000..a3a628dce --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/effects.d.ts @@ -0,0 +1,285 @@ +import { HorizonApi } from "../horizon_api"; +import { OfferAsset } from "./offer"; +export declare enum EffectType { + account_created = 0, + account_removed = 1, + account_credited = 2, + account_debited = 3, + account_thresholds_updated = 4, + account_home_domain_updated = 5, + account_flags_updated = 6, + account_inflation_destination_updated = 7, + signer_created = 10, + signer_removed = 11, + signer_updated = 12, + trustline_created = 20, + trustline_removed = 21, + trustline_updated = 22, + trustline_authorized = 23, + trustline_deauthorized = 24, + trustline_authorized_to_maintain_liabilities = 25,// deprecated, use trustline_flags_updated + trustline_flags_updated = 26, + offer_created = 30, + offer_removed = 31, + offer_updated = 32, + trade = 33, + data_created = 40, + data_removed = 41, + data_updated = 42, + sequence_bumped = 43, + claimable_balance_created = 50, + claimable_balance_claimant_created = 51, + claimable_balance_claimed = 52, + account_sponsorship_created = 60, + account_sponsorship_updated = 61, + account_sponsorship_removed = 62, + trustline_sponsorship_created = 63, + trustline_sponsorship_updated = 64, + trustline_sponsorship_removed = 65, + data_sponsorship_created = 66, + data_sponsorship_updated = 67, + data_sponsorship_removed = 68, + claimable_balance_sponsorship_created = 69, + claimable_balance_sponsorship_updated = 70, + claimable_balance_sponsorship_removed = 71, + signer_sponsorship_created = 72, + signer_sponsorship_updated = 73, + signer_sponsorship_removed = 74, + claimable_balance_clawed_back = 80, + liquidity_pool_deposited = 90, + liquidity_pool_withdrew = 91, + liquidity_pool_trade = 92, + liquidity_pool_created = 93, + liquidity_pool_removed = 94, + liquidity_pool_revoked = 95, + contract_credited = 96, + contract_debited = 97 +} +export interface BaseEffectRecord extends HorizonApi.BaseResponse { + id: string; + account: string; + paging_token: string; + type_i: EffectType; + type: T; + created_at: string; +} +export interface AccountCreated extends BaseEffectRecord<'account_created'> { + type_i: EffectType.account_created; + starting_balance: string; +} +export interface AccountCredited extends BaseEffectRecord<'account_credited'>, OfferAsset { + type_i: EffectType.account_credited; + amount: string; +} +export interface AccountDebited extends BaseEffectRecord<'account_debited'>, OfferAsset { + type_i: EffectType.account_debited; + amount: string; +} +export interface AccountThresholdsUpdated extends BaseEffectRecord<'account_thresholds_updated'> { + type_i: EffectType.account_thresholds_updated; + low_threshold: number; + med_threshold: number; + high_threshold: number; +} +export interface AccountHomeDomainUpdated extends BaseEffectRecord<'account_home_domain_updated'> { + type_i: EffectType.account_home_domain_updated; + home_domain: string; +} +export interface AccountFlagsUpdated extends BaseEffectRecord<'account_flags_updated'> { + type_i: EffectType.account_flags_updated; + auth_required_flag: boolean; + auth_revokable_flag: boolean; +} +interface DataEvents extends BaseEffectRecord { + name: boolean; + value: boolean; +} +export interface DataCreated extends DataEvents<'data_created'> { + type_i: EffectType.data_created; +} +export interface DataUpdated extends DataEvents<'data_updated'> { + type_i: EffectType.data_updated; +} +export interface DataRemoved extends DataEvents<'data_removed'> { + type_i: EffectType.data_removed; +} +export interface SequenceBumped extends BaseEffectRecord<'sequence_bumped'> { + type_i: EffectType.sequence_bumped; + new_seq: number | string; +} +interface SignerEvents extends BaseEffectRecord { + weight: number; + key: string; + public_key: string; +} +export interface SignerCreated extends SignerEvents<'signer_created'> { + type_i: EffectType.signer_created; +} +export interface SignerRemoved extends SignerEvents<'signer_removed'> { + type_i: EffectType.signer_removed; +} +export interface SignerUpdated extends SignerEvents<'signer_updated'> { + type_i: EffectType.signer_updated; +} +interface TrustlineEvents extends BaseEffectRecord, OfferAsset { + limit: string; + liquidity_pool_id?: string; +} +export interface TrustlineCreated extends TrustlineEvents<'trustline_created'> { + type_i: EffectType.trustline_created; +} +export interface TrustlineRemoved extends TrustlineEvents<'trustline_removed'> { + type_i: EffectType.trustline_removed; +} +export interface TrustlineUpdated extends TrustlineEvents<'trustline_updated'> { + type_i: EffectType.trustline_updated; +} +export interface TrustlineAuthorized extends BaseEffectRecord<'trustline_authorized'> { + type_i: EffectType.trustline_authorized; + asset_type: OfferAsset["asset_type"]; + asset_code: OfferAsset["asset_code"]; + trustor: string; +} +export interface TrustlineDeauthorized extends Omit { + type_i: EffectType.trustline_deauthorized; +} +export interface TrustlineAuthorizedToMaintainLiabilities extends Omit { + type_i: EffectType.trustline_authorized_to_maintain_liabilities; +} +export interface ClaimableBalanceCreated extends BaseEffectRecord<'claimable_balance_created'> { + type_i: EffectType.claimable_balance_created; + amount: string; + balance_type_i: string; + asset: string; +} +export interface ClaimableBalanceClaimed extends Omit { + type_i: EffectType.claimable_balance_claimed; +} +export interface ClaimableBalanceClaimantCreated extends Omit { + type_i: EffectType.claimable_balance_claimant_created; +} +interface SponsershipFields { + sponsor: string; + new_sponsor: string; + former_sponsor: string; +} +interface AccountSponsorshipEvents extends BaseEffectRecord, SponsershipFields { +} +export type AccountSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.account_sponsorship_created; +}; +export type AccountSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.account_sponsorship_updated; +}; +export type AccountSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.account_sponsorship_removed; +}; +interface TrustlineSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + asset?: string; + liquidity_pool_id?: string; +} +export type TrustlineSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.trustline_sponsorship_created; +}; +export type TrustlineSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.trustline_sponsorship_updated; +}; +export type TrustlineSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.trustline_sponsorship_removed; +}; +interface DataSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + data_name: string; +} +export type DateSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.data_sponsorship_created; +}; +export type DateSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.data_sponsorship_updated; +}; +export type DateSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.data_sponsorship_removed; +}; +interface ClaimableBalanceSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + balance_type_i: string; +} +export type ClaimableBalanceSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.claimable_balance_sponsorship_created; +}; +export type ClaimableBalanceSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.claimable_balance_sponsorship_updated; +}; +export type ClaimableBalanceSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.claimable_balance_sponsorship_removed; +}; +interface SignerSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + signer: string; +} +export type SignerSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.signer_sponsorship_created; +}; +export type SignerSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.signer_sponsorship_updated; +}; +export type SignerSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.signer_sponsorship_removed; +}; +export interface ClaimableBalanceClawedBack extends HorizonApi.BaseResponse { + balance_id: string; +} +export interface LiquidityPoolEffectRecord extends HorizonApi.BaseResponse { + id: string; + fee_bp: number; + type: HorizonApi.LiquidityPoolType; + total_trustlines: string; + total_shares: string; + reserves: HorizonApi.Reserve[]; +} +export interface LiquidityPoolDeposited extends BaseEffectRecord<'liquidity_pool_deposited'> { + type_i: EffectType.liquidity_pool_deposited; + liquidity_pool: LiquidityPoolEffectRecord; + reserves_deposited: HorizonApi.Reserve[]; + shares_received: string; +} +export interface LiquidityPoolWithdrew extends BaseEffectRecord<'liquidity_pool_withdrew'> { + type_i: EffectType.liquidity_pool_withdrew; + liquidity_pool: LiquidityPoolEffectRecord; + reserves_received: HorizonApi.Reserve[]; + shares_redeemed: string; +} +export interface LiquidityPoolTrade extends BaseEffectRecord<'liquidity_pool_trade'> { + type_i: EffectType.liquidity_pool_trade; + liquidity_pool: LiquidityPoolEffectRecord; + sold: HorizonApi.Reserve; + bought: HorizonApi.Reserve; +} +export interface LiquidityPoolCreated extends BaseEffectRecord<'liquidity_pool_created'> { + type_i: EffectType.liquidity_pool_created; + liquidity_pool: LiquidityPoolEffectRecord; +} +export interface LiquidityPoolRemoved extends BaseEffectRecord<'liquidity_pool_removed'> { + type_i: EffectType.liquidity_pool_removed; + liquidity_pool_id: string; +} +export interface LiquidityPoolRevoked extends BaseEffectRecord<'liquidity_pool_revoked'> { + type_i: EffectType.liquidity_pool_revoked; + liquidity_pool: LiquidityPoolEffectRecord; + reserves_revoked: [ + { + asset: string; + amount: string; + claimable_balance_id: string; + } + ]; + shares_revoked: string; +} +export interface ContractCredited extends BaseEffectRecord<'contract_credited'>, OfferAsset { + type_i: EffectType.contract_credited; + contract: string; + amount: string; +} +export interface ContractDebited extends BaseEffectRecord<'contract_debited'>, OfferAsset { + type_i: EffectType.contract_debited; + contract: string; + amount: string; +} +export {}; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/effects.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/effects.js new file mode 100644 index 000000000..3b28a678f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/effects.js @@ -0,0 +1,62 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.EffectType = void 0; +var EffectType = exports.EffectType = function (EffectType) { + EffectType[EffectType["account_created"] = 0] = "account_created"; + EffectType[EffectType["account_removed"] = 1] = "account_removed"; + EffectType[EffectType["account_credited"] = 2] = "account_credited"; + EffectType[EffectType["account_debited"] = 3] = "account_debited"; + EffectType[EffectType["account_thresholds_updated"] = 4] = "account_thresholds_updated"; + EffectType[EffectType["account_home_domain_updated"] = 5] = "account_home_domain_updated"; + EffectType[EffectType["account_flags_updated"] = 6] = "account_flags_updated"; + EffectType[EffectType["account_inflation_destination_updated"] = 7] = "account_inflation_destination_updated"; + EffectType[EffectType["signer_created"] = 10] = "signer_created"; + EffectType[EffectType["signer_removed"] = 11] = "signer_removed"; + EffectType[EffectType["signer_updated"] = 12] = "signer_updated"; + EffectType[EffectType["trustline_created"] = 20] = "trustline_created"; + EffectType[EffectType["trustline_removed"] = 21] = "trustline_removed"; + EffectType[EffectType["trustline_updated"] = 22] = "trustline_updated"; + EffectType[EffectType["trustline_authorized"] = 23] = "trustline_authorized"; + EffectType[EffectType["trustline_deauthorized"] = 24] = "trustline_deauthorized"; + EffectType[EffectType["trustline_authorized_to_maintain_liabilities"] = 25] = "trustline_authorized_to_maintain_liabilities"; + EffectType[EffectType["trustline_flags_updated"] = 26] = "trustline_flags_updated"; + EffectType[EffectType["offer_created"] = 30] = "offer_created"; + EffectType[EffectType["offer_removed"] = 31] = "offer_removed"; + EffectType[EffectType["offer_updated"] = 32] = "offer_updated"; + EffectType[EffectType["trade"] = 33] = "trade"; + EffectType[EffectType["data_created"] = 40] = "data_created"; + EffectType[EffectType["data_removed"] = 41] = "data_removed"; + EffectType[EffectType["data_updated"] = 42] = "data_updated"; + EffectType[EffectType["sequence_bumped"] = 43] = "sequence_bumped"; + EffectType[EffectType["claimable_balance_created"] = 50] = "claimable_balance_created"; + EffectType[EffectType["claimable_balance_claimant_created"] = 51] = "claimable_balance_claimant_created"; + EffectType[EffectType["claimable_balance_claimed"] = 52] = "claimable_balance_claimed"; + EffectType[EffectType["account_sponsorship_created"] = 60] = "account_sponsorship_created"; + EffectType[EffectType["account_sponsorship_updated"] = 61] = "account_sponsorship_updated"; + EffectType[EffectType["account_sponsorship_removed"] = 62] = "account_sponsorship_removed"; + EffectType[EffectType["trustline_sponsorship_created"] = 63] = "trustline_sponsorship_created"; + EffectType[EffectType["trustline_sponsorship_updated"] = 64] = "trustline_sponsorship_updated"; + EffectType[EffectType["trustline_sponsorship_removed"] = 65] = "trustline_sponsorship_removed"; + EffectType[EffectType["data_sponsorship_created"] = 66] = "data_sponsorship_created"; + EffectType[EffectType["data_sponsorship_updated"] = 67] = "data_sponsorship_updated"; + EffectType[EffectType["data_sponsorship_removed"] = 68] = "data_sponsorship_removed"; + EffectType[EffectType["claimable_balance_sponsorship_created"] = 69] = "claimable_balance_sponsorship_created"; + EffectType[EffectType["claimable_balance_sponsorship_updated"] = 70] = "claimable_balance_sponsorship_updated"; + EffectType[EffectType["claimable_balance_sponsorship_removed"] = 71] = "claimable_balance_sponsorship_removed"; + EffectType[EffectType["signer_sponsorship_created"] = 72] = "signer_sponsorship_created"; + EffectType[EffectType["signer_sponsorship_updated"] = 73] = "signer_sponsorship_updated"; + EffectType[EffectType["signer_sponsorship_removed"] = 74] = "signer_sponsorship_removed"; + EffectType[EffectType["claimable_balance_clawed_back"] = 80] = "claimable_balance_clawed_back"; + EffectType[EffectType["liquidity_pool_deposited"] = 90] = "liquidity_pool_deposited"; + EffectType[EffectType["liquidity_pool_withdrew"] = 91] = "liquidity_pool_withdrew"; + EffectType[EffectType["liquidity_pool_trade"] = 92] = "liquidity_pool_trade"; + EffectType[EffectType["liquidity_pool_created"] = 93] = "liquidity_pool_created"; + EffectType[EffectType["liquidity_pool_removed"] = 94] = "liquidity_pool_removed"; + EffectType[EffectType["liquidity_pool_revoked"] = 95] = "liquidity_pool_revoked"; + EffectType[EffectType["contract_credited"] = 96] = "contract_credited"; + EffectType[EffectType["contract_debited"] = 97] = "contract_debited"; + return EffectType; +}({}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/offer.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/offer.d.ts new file mode 100644 index 000000000..a58e3f16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/offer.d.ts @@ -0,0 +1,20 @@ +import { AssetType } from "@stellar/stellar-base"; +import { HorizonApi } from "../horizon_api"; +export interface OfferAsset { + asset_type: AssetType; + asset_code?: string; + asset_issuer?: string; +} +export interface OfferRecord extends HorizonApi.BaseResponse { + id: number | string; + paging_token: string; + seller: string; + selling: OfferAsset; + buying: OfferAsset; + amount: string; + price_r: HorizonApi.PriceRShorthand; + price: string; + last_modified_ledger: number; + last_modified_time: string; + sponsor?: string; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/offer.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/offer.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/offer.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/trade.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/trade.d.ts new file mode 100644 index 000000000..a38f75361 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/trade.d.ts @@ -0,0 +1,14 @@ +import { BaseEffectRecord, EffectType } from "./effects"; +export interface Trade extends BaseEffectRecord<'trade'> { + type_i: EffectType.trade; + seller: string; + offer_id: number | string; + bought_amount: string; + bought_asset_type: string; + bought_asset_code: string; + bought_asset_issuer: string; + sold_amount: string; + sold_asset_type: string; + sold_asset_code: string; + sold_asset_issuer: string; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/trade.js b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/trade.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/horizon/types/trade.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/axios-client.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/axios-client.d.ts new file mode 100644 index 000000000..739c21526 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/axios-client.d.ts @@ -0,0 +1,2 @@ +export declare const axiosClient: import("axios").AxiosStatic; +export declare const create: (config?: import("axios").CreateAxiosDefaults) => import("axios").AxiosInstance; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/axios-client.js b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/axios-client.js new file mode 100644 index 000000000..12a4eb449 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/axios-client.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.create = exports.axiosClient = void 0; +var _axios = _interopRequireDefault(require("axios")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +var axiosClient = exports.axiosClient = _axios.default; +var create = exports.create = _axios.default.create; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/fetch-client.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/fetch-client.d.ts new file mode 100644 index 000000000..8b91ef645 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/fetch-client.d.ts @@ -0,0 +1,11 @@ +import { AxiosRequestConfig, AxiosResponse } from 'feaxios'; +import { CancelToken, HttpClient, HttpClientRequestConfig, HttpClientResponse } from './types'; +export interface HttpResponse extends AxiosResponse { +} +export interface FetchClientConfig extends AxiosRequestConfig { + adapter?: (config: HttpClientRequestConfig) => Promise>; + cancelToken?: CancelToken; +} +declare function createFetchClient(fetchConfig?: HttpClientRequestConfig): HttpClient; +export declare const fetchClient: HttpClient; +export { createFetchClient as create }; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/fetch-client.js b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/fetch-client.js new file mode 100644 index 000000000..5da967e91 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/fetch-client.js @@ -0,0 +1,229 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.create = createFetchClient; +exports.fetchClient = void 0; +var _feaxios = _interopRequireDefault(require("feaxios")); +var _types = require("./types"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var InterceptorManager = function () { + function InterceptorManager() { + _classCallCheck(this, InterceptorManager); + _defineProperty(this, "handlers", []); + } + return _createClass(InterceptorManager, [{ + key: "use", + value: function use(fulfilled, rejected) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected + }); + return this.handlers.length - 1; + } + }, { + key: "eject", + value: function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + }, { + key: "forEach", + value: function forEach(fn) { + this.handlers.forEach(function (h) { + if (h !== null) { + fn(h); + } + }); + } + }]); +}(); +function getFormConfig(config) { + var formConfig = config || {}; + formConfig.headers = new Headers(formConfig.headers || {}); + formConfig.headers.set('Content-Type', 'application/x-www-form-urlencoded'); + return formConfig; +} +function createFetchClient() { + var fetchConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var defaults = _objectSpread(_objectSpread({}, fetchConfig), {}, { + headers: fetchConfig.headers || {} + }); + var instance = _feaxios.default.create(defaults); + var requestInterceptors = new InterceptorManager(); + var responseInterceptors = new InterceptorManager(); + var httpClient = { + interceptors: { + request: requestInterceptors, + response: responseInterceptors + }, + defaults: _objectSpread(_objectSpread({}, defaults), {}, { + adapter: function adapter(config) { + return instance.request(config); + } + }), + create: function create(config) { + return createFetchClient(_objectSpread(_objectSpread({}, this.defaults), config)); + }, + makeRequest: function makeRequest(config) { + var _this = this; + return new Promise(function (resolve, reject) { + var abortController = new AbortController(); + config.signal = abortController.signal; + if (config.cancelToken) { + config.cancelToken.promise.then(function () { + abortController.abort(); + reject(new Error('Request canceled')); + }); + } + var modifiedConfig = config; + if (requestInterceptors.handlers.length > 0) { + var chain = requestInterceptors.handlers.filter(function (interceptor) { + return interceptor !== null; + }).flatMap(function (interceptor) { + return [interceptor.fulfilled, interceptor.rejected]; + }); + for (var i = 0, len = chain.length; i < len; i += 2) { + var onFulfilled = chain[i]; + var onRejected = chain[i + 1]; + try { + if (onFulfilled) modifiedConfig = onFulfilled(modifiedConfig); + } catch (error) { + if (onRejected) onRejected === null || onRejected === void 0 || onRejected(error); + reject(error); + return; + } + } + } + var adapter = modifiedConfig.adapter || _this.defaults.adapter; + if (!adapter) { + throw new Error('No adapter available'); + } + var responsePromise = adapter(modifiedConfig).then(function (axiosResponse) { + var httpClientResponse = { + data: axiosResponse.data, + headers: axiosResponse.headers, + config: axiosResponse.config, + status: axiosResponse.status, + statusText: axiosResponse.statusText + }; + return httpClientResponse; + }); + if (responseInterceptors.handlers.length > 0) { + var _chain = responseInterceptors.handlers.filter(function (interceptor) { + return interceptor !== null; + }).flatMap(function (interceptor) { + return [interceptor.fulfilled, interceptor.rejected]; + }); + var _loop = function _loop(_i) { + responsePromise = responsePromise.then(function (response) { + var fulfilledInterceptor = _chain[_i]; + if (typeof fulfilledInterceptor === 'function') { + return fulfilledInterceptor(response); + } + return response; + }, function (error) { + var rejectedInterceptor = _chain[_i + 1]; + if (typeof rejectedInterceptor === 'function') { + return rejectedInterceptor(error); + } + throw error; + }).then(function (interceptedResponse) { + return interceptedResponse; + }); + }; + for (var _i = 0, _len = _chain.length; _i < _len; _i += 2) { + _loop(_i); + } + } + responsePromise.then(resolve).catch(reject); + }); + }, + get: function get(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'get' + })); + }, + delete: function _delete(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'delete' + })); + }, + head: function head(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'head' + })); + }, + options: function options(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'options' + })); + }, + post: function post(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'post', + data: data + })); + }, + put: function put(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'put', + data: data + })); + }, + patch: function patch(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'patch', + data: data + })); + }, + postForm: function postForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'post', + data: data + })); + }, + putForm: function putForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'put', + data: data + })); + }, + patchForm: function patchForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'patch', + data: data + })); + }, + CancelToken: _types.CancelToken, + isCancel: function isCancel(value) { + return value instanceof Error && value.message === 'Request canceled'; + } + }; + return httpClient; +} +var fetchClient = exports.fetchClient = createFetchClient(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/index.d.ts new file mode 100644 index 000000000..b6dea58cd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/index.d.ts @@ -0,0 +1,5 @@ +import { HttpClient, HttpClientRequestConfig } from "./types"; +declare let httpClient: HttpClient; +declare let create: (config?: HttpClientRequestConfig) => HttpClient; +export { httpClient, create }; +export * from "./types"; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/index.js b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/index.js new file mode 100644 index 000000000..8e8e6230a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/index.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + httpClient: true, + create: true +}; +exports.httpClient = exports.create = void 0; +var _types = require("./types"); +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _types[key]; + } + }); +}); +var httpClient; +var create; +if (false) { + var axiosModule = require('./axios-client'); + exports.httpClient = httpClient = axiosModule.axiosClient; + exports.create = create = axiosModule.create; +} else { + var fetchModule = require('./fetch-client'); + exports.httpClient = httpClient = fetchModule.fetchClient; + exports.create = create = fetchModule.create; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/types.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/types.d.ts new file mode 100644 index 000000000..6aa38dddc --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/types.d.ts @@ -0,0 +1,70 @@ +export type HttpResponseHeaders = Record & { + 'set-cookie'?: string[]; +}; +export interface HttpClientDefaults extends Omit { + headers?: [string, string][] | Record | Headers | undefined; +} +export interface HttpClientResponse { + data: T; + headers: HttpResponseHeaders; + config: any; + status: number; + statusText: string; +} +export interface CancelToken { + promise: Promise; + throwIfRequested(): void; + reason?: string; +} +type HeadersInit = [string, string][] | Record | Headers; +export interface HttpClientRequestConfig { + url?: string; + method?: string; + baseURL?: string; + data?: D; + timeout?: number; + fetchOptions?: Record; + headers?: HeadersInit; + params?: Record; + maxContentLength?: number; + maxRedirects?: number; + cancelToken?: CancelToken; + adapter?: (config: HttpClientRequestConfig) => Promise; +} +export interface HttpClient { + get: (url: string, config?: HttpClientRequestConfig) => Promise>; + delete: (url: string, config?: HttpClientRequestConfig) => Promise>; + head: (url: string, config?: HttpClientRequestConfig) => Promise>; + options: (url: string, config?: HttpClientRequestConfig) => Promise>; + post: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + put: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + patch: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + postForm: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + putForm: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + patchForm: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + interceptors: { + request: InterceptorManager; + response: InterceptorManager; + }; + defaults: HttpClientDefaults; + CancelToken: typeof CancelToken; + isCancel: (value: any) => boolean; + makeRequest: (config: HttpClientRequestConfig) => Promise>; + create: (config?: HttpClientRequestConfig) => HttpClient; +} +export interface Interceptor { + fulfilled: (value: V) => V | Promise; + rejected?: (error: any) => any; +} +export interface InterceptorManager { + use(fulfilled: (value: V) => V | Promise, rejected?: (error: any) => any): number; + eject(id: number): void; + forEach(fn: (interceptor: Interceptor) => void): void; + handlers: Array | null>; +} +export declare class CancelToken { + promise: Promise; + reason?: string; + constructor(executor: (cancel: (reason?: string) => void) => void); +} +export {}; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/types.js b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/types.js new file mode 100644 index 000000000..80b1012fb --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/http-client/types.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.CancelToken = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var CancelToken = exports.CancelToken = function () { + function CancelToken(executor) { + var _this = this; + _classCallCheck(this, CancelToken); + var resolvePromise; + this.promise = new Promise(function (resolve) { + resolvePromise = resolve; + }); + executor(function (reason) { + _this.reason = reason; + resolvePromise(); + }); + } + return _createClass(CancelToken, [{ + key: "throwIfRequested", + value: function throwIfRequested() { + if (this.reason) { + throw new Error(this.reason); + } + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/index.d.ts new file mode 100644 index 000000000..6ae366241 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/index.d.ts @@ -0,0 +1,32 @@ +export * from './errors'; +export { Config } from './config'; +export { Utils } from './utils'; +export * as StellarToml from './stellartoml'; +export * as Federation from './federation'; +export * as WebAuth from './webauth'; +export * as Friendbot from './friendbot'; +export * as Horizon from './horizon'; +/** + * Tools for interacting with the Soroban RPC server, such as `Server`, + * `assembleTransaction`, and the `Api` types. You can import these from the + * `/rpc` entrypoint, if your version of Node and your TypeScript configuration + * allow it: + * + * @example + * import { Server } from '@stellar/stellar-sdk/rpc'; + */ +export * as rpc from './rpc'; +/** + * Tools for interacting with smart contracts, such as `Client`, `Spec`, and + * `AssembledTransaction`. You can import these from the `/contract` + * entrypoint, if your version of Node and your TypeScript configuration allow + * it: + * + * @example + * import { Client } from '@stellar/stellar-sdk/contract'; + * @private + */ +export * as contract from './contract'; +export * from '@stellar/stellar-base'; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/index.js b/node_modules/@stellar/stellar-sdk/lib/minimal/index.js new file mode 100644 index 000000000..cbdb8649c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/index.js @@ -0,0 +1,80 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Config: true, + Utils: true, + StellarToml: true, + Federation: true, + WebAuth: true, + Friendbot: true, + Horizon: true, + rpc: true, + contract: true +}; +Object.defineProperty(exports, "Config", { + enumerable: true, + get: function get() { + return _config.Config; + } +}); +exports.StellarToml = exports.Horizon = exports.Friendbot = exports.Federation = void 0; +Object.defineProperty(exports, "Utils", { + enumerable: true, + get: function get() { + return _utils.Utils; + } +}); +exports.rpc = exports.default = exports.contract = exports.WebAuth = void 0; +var _errors = require("./errors"); +Object.keys(_errors).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _errors[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _errors[key]; + } + }); +}); +var _config = require("./config"); +var _utils = require("./utils"); +var _StellarToml = _interopRequireWildcard(require("./stellartoml")); +exports.StellarToml = _StellarToml; +var _Federation = _interopRequireWildcard(require("./federation")); +exports.Federation = _Federation; +var _WebAuth = _interopRequireWildcard(require("./webauth")); +exports.WebAuth = _WebAuth; +var _Friendbot = _interopRequireWildcard(require("./friendbot")); +exports.Friendbot = _Friendbot; +var _Horizon = _interopRequireWildcard(require("./horizon")); +exports.Horizon = _Horizon; +var _rpc = _interopRequireWildcard(require("./rpc")); +exports.rpc = _rpc; +var _contract = _interopRequireWildcard(require("./contract")); +exports.contract = _contract; +var _stellarBase = require("@stellar/stellar-base"); +Object.keys(_stellarBase).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _stellarBase[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _stellarBase[key]; + } + }); +}); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; +if (typeof global.__USE_AXIOS__ === 'undefined') { + global.__USE_AXIOS__ = true; +} +if (typeof global.__USE_EVENTSOURCE__ === 'undefined') { + global.__USE_EVENTSOURCE__ = false; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/api.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/api.d.ts new file mode 100644 index 000000000..87d269804 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/api.d.ts @@ -0,0 +1,363 @@ +import { Contract, SorobanDataBuilder, xdr } from '@stellar/stellar-base'; +export declare namespace Api { + export interface GetHealthResponse { + status: 'healthy'; + } + export interface LedgerEntryResult { + lastModifiedLedgerSeq?: number; + key: xdr.LedgerKey; + val: xdr.LedgerEntryData; + liveUntilLedgerSeq?: number; + } + export interface RawLedgerEntryResult { + lastModifiedLedgerSeq?: number; + /** a base-64 encoded {@link xdr.LedgerKey} instance */ + key: string; + /** a base-64 encoded {@link xdr.LedgerEntryData} instance */ + xdr: string; + /** + * optional, a future ledger number upon which this entry will expire + * based on https://github.com/stellar/soroban-tools/issues/1010 + */ + liveUntilLedgerSeq?: number; + } + /** An XDR-parsed version of {@link this.RawLedgerEntryResult} */ + export interface GetLedgerEntriesResponse { + entries: LedgerEntryResult[]; + latestLedger: number; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries */ + export interface RawGetLedgerEntriesResponse { + entries?: RawLedgerEntryResult[]; + latestLedger: number; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getNetwork */ + export interface GetNetworkResponse { + friendbotUrl?: string; + passphrase: string; + protocolVersion: string; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLatestLedger */ + export interface GetLatestLedgerResponse { + id: string; + sequence: number; + protocolVersion: string; + } + export enum GetTransactionStatus { + SUCCESS = "SUCCESS", + NOT_FOUND = "NOT_FOUND", + FAILED = "FAILED" + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransaction */ + export type GetTransactionResponse = GetSuccessfulTransactionResponse | GetFailedTransactionResponse | GetMissingTransactionResponse; + interface GetAnyTransactionResponse { + status: GetTransactionStatus; + txHash: string; + latestLedger: number; + latestLedgerCloseTime: number; + oldestLedger: number; + oldestLedgerCloseTime: number; + } + export interface GetMissingTransactionResponse extends GetAnyTransactionResponse { + status: GetTransactionStatus.NOT_FOUND; + } + export interface GetFailedTransactionResponse extends GetAnyTransactionResponse { + status: GetTransactionStatus.FAILED; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + envelopeXdr: xdr.TransactionEnvelope; + resultXdr: xdr.TransactionResult; + resultMetaXdr: xdr.TransactionMeta; + diagnosticEventsXdr?: xdr.DiagnosticEvent[]; + } + export interface GetSuccessfulTransactionResponse extends GetAnyTransactionResponse { + status: GetTransactionStatus.SUCCESS; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + envelopeXdr: xdr.TransactionEnvelope; + resultXdr: xdr.TransactionResult; + resultMetaXdr: xdr.TransactionMeta; + diagnosticEventsXdr?: xdr.DiagnosticEvent[]; + returnValue?: xdr.ScVal; + } + export interface RawGetTransactionResponse { + status: GetTransactionStatus; + latestLedger: number; + latestLedgerCloseTime: number; + oldestLedger: number; + oldestLedgerCloseTime: number; + txHash: string; + applicationOrder?: number; + feeBump?: boolean; + ledger?: number; + createdAt?: number; + envelopeXdr?: string; + resultXdr?: string; + resultMetaXdr?: string; + diagnosticEventsXdr?: string[]; + } + export interface GetTransactionsRequest { + startLedger: number; + cursor?: string; + limit?: number; + } + export interface RawTransactionInfo { + status: GetTransactionStatus; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + txHash: string; + envelopeXdr?: string; + resultXdr?: string; + resultMetaXdr?: string; + diagnosticEventsXdr?: string[]; + } + export interface TransactionInfo { + status: GetTransactionStatus; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + txHash: string; + envelopeXdr: xdr.TransactionEnvelope; + resultXdr: xdr.TransactionResult; + resultMetaXdr: xdr.TransactionMeta; + returnValue?: xdr.ScVal; + diagnosticEventsXdr?: xdr.DiagnosticEvent[]; + } + export interface GetTransactionsResponse { + transactions: TransactionInfo[]; + latestLedger: number; + latestLedgerCloseTimestamp: number; + oldestLedger: number; + oldestLedgerCloseTimestamp: number; + cursor: string; + } + export interface RawGetTransactionsResponse { + transactions: RawTransactionInfo[]; + latestLedger: number; + latestLedgerCloseTimestamp: number; + oldestLedger: number; + oldestLedgerCloseTimestamp: number; + cursor: string; + } + export type EventType = 'contract' | 'system' | 'diagnostic'; + export interface EventFilter { + type?: EventType; + contractIds?: string[]; + topics?: string[][]; + } + export interface GetEventsResponse { + latestLedger: number; + events: EventResponse[]; + cursor: string; + } + export interface EventResponse extends BaseEventResponse { + contractId?: Contract; + topic: xdr.ScVal[]; + value: xdr.ScVal; + } + export interface RawGetEventsResponse { + latestLedger: number; + events: RawEventResponse[]; + cursor: string; + } + interface BaseEventResponse { + id: string; + type: EventType; + ledger: number; + ledgerClosedAt: string; + pagingToken: string; + inSuccessfulContractCall: boolean; + txHash: string; + } + export interface RawEventResponse extends BaseEventResponse { + contractId: string; + topic: string[]; + value: string; + } + interface RawLedgerEntryChange { + type: number; + /** This is LedgerKey in base64 */ + key: string; + /** This is xdr.LedgerEntry in base64 */ + before: string | null; + /** This is xdr.LedgerEntry in base64 */ + after: string | null; + } + export interface LedgerEntryChange { + type: number; + key: xdr.LedgerKey; + before: xdr.LedgerEntry | null; + after: xdr.LedgerEntry | null; + } + export type SendTransactionStatus = 'PENDING' | 'DUPLICATE' | 'TRY_AGAIN_LATER' | 'ERROR'; + export interface SendTransactionResponse extends BaseSendTransactionResponse { + errorResult?: xdr.TransactionResult; + diagnosticEvents?: xdr.DiagnosticEvent[]; + } + export interface RawSendTransactionResponse extends BaseSendTransactionResponse { + /** + * This is a base64-encoded instance of {@link xdr.TransactionResult}, set + * only when `status` is `"ERROR"`. + * + * It contains details on why the network rejected the transaction. + */ + errorResultXdr?: string; + /** + * This is a base64-encoded instance of an array of + * {@link xdr.DiagnosticEvent}s, set only when `status` is `"ERROR"` and + * diagnostic events are enabled on the server. + */ + diagnosticEventsXdr?: string[]; + } + export interface BaseSendTransactionResponse { + status: SendTransactionStatus; + hash: string; + latestLedger: number; + latestLedgerCloseTime: number; + } + export interface SimulateHostFunctionResult { + auth: xdr.SorobanAuthorizationEntry[]; + retval: xdr.ScVal; + } + /** + * Simplifies {@link Api.RawSimulateTransactionResponse} into separate interfaces + * based on status: + * - on success, this includes all fields, though `result` is only present + * if an invocation was simulated (since otherwise there's nothing to + * "resultify") + * - if there was an expiration error, this includes error and restoration + * fields + * - for all other errors, this only includes error fields + * + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction + */ + export type SimulateTransactionResponse = SimulateTransactionSuccessResponse | SimulateTransactionRestoreResponse | SimulateTransactionErrorResponse; + export interface BaseSimulateTransactionResponse { + /** always present: the JSON-RPC request ID */ + id: string; + /** always present: the LCL known to the server when responding */ + latestLedger: number; + /** + * The field is always present, but may be empty in cases where: + * - you didn't simulate an invocation or + * - there were no events + */ + events: xdr.DiagnosticEvent[]; + /** a private field to mark the schema as parsed */ + _parsed: boolean; + } + /** Includes simplified fields only present on success. */ + export interface SimulateTransactionSuccessResponse extends BaseSimulateTransactionResponse { + transactionData: SorobanDataBuilder; + minResourceFee: string; + /** present only for invocation simulation */ + result?: SimulateHostFunctionResult; + /** State Difference information */ + stateChanges?: LedgerEntryChange[]; + } + /** Includes details about why the simulation failed */ + export interface SimulateTransactionErrorResponse extends BaseSimulateTransactionResponse { + error: string; + events: xdr.DiagnosticEvent[]; + } + export interface SimulateTransactionRestoreResponse extends SimulateTransactionSuccessResponse { + result: SimulateHostFunctionResult; + /** + * Indicates that a restoration is necessary prior to submission. + * + * In other words, seeing a restoration preamble means that your invocation + * was executed AS IF the required ledger entries were present, and this + * field includes information about what you need to restore for the + * simulation to succeed. + */ + restorePreamble: { + minResourceFee: string; + transactionData: SorobanDataBuilder; + }; + } + export function isSimulationError(sim: SimulateTransactionResponse): sim is SimulateTransactionErrorResponse; + export function isSimulationSuccess(sim: SimulateTransactionResponse): sim is SimulateTransactionSuccessResponse; + export function isSimulationRestore(sim: SimulateTransactionResponse): sim is SimulateTransactionRestoreResponse; + export function isSimulationRaw(sim: Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse): sim is Api.RawSimulateTransactionResponse; + interface RawSimulateHostFunctionResult { + auth?: string[]; + xdr: string; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction */ + export interface RawSimulateTransactionResponse { + id: string; + latestLedger: number; + error?: string; + /** This is an xdr.SorobanTransactionData in base64 */ + transactionData?: string; + /** These are xdr.DiagnosticEvents in base64 */ + events?: string[]; + minResourceFee?: string; + /** + * This will only contain a single element if present, because only a single + * invokeHostFunctionOperation is supported per transaction. + * */ + results?: RawSimulateHostFunctionResult[]; + /** Present if succeeded but has expired ledger entries */ + restorePreamble?: { + minResourceFee: string; + transactionData: string; + }; + /** State difference information */ + stateChanges?: RawLedgerEntryChange[]; + } + export interface GetVersionInfoResponse { + version: string; + commitHash: string; + buildTimestamp: string; + captiveCoreVersion: string; + protocolVersion: number; + commit_hash: string; + build_timestamp: string; + captive_core_version: string; + protocol_version: number; + } + export interface GetFeeStatsResponse { + sorobanInclusionFee: FeeDistribution; + inclusionFee: FeeDistribution; + latestLedger: number; + } + interface FeeDistribution { + max: string; + min: string; + mode: string; + p10: string; + p20: string; + p30: string; + p40: string; + p50: string; + p60: string; + p70: string; + p80: string; + p90: string; + p95: string; + p99: string; + transactionCount: string; + ledgerCount: number; + } + export interface BalanceResponse { + latestLedger: number; + /** present only on success, otherwise request malformed or no balance */ + balanceEntry?: { + /** a 64-bit integer */ + amount: string; + authorized: boolean; + clawback: boolean; + lastModifiedLedgerSeq?: number; + liveUntilLedgerSeq?: number; + }; + } + export {}; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/api.js b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/api.js new file mode 100644 index 000000000..119ddb359 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/api.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Api = void 0; +var Api; +(function (_Api) { + var GetTransactionStatus = function (GetTransactionStatus) { + GetTransactionStatus["SUCCESS"] = "SUCCESS"; + GetTransactionStatus["NOT_FOUND"] = "NOT_FOUND"; + GetTransactionStatus["FAILED"] = "FAILED"; + return GetTransactionStatus; + }({}); + _Api.GetTransactionStatus = GetTransactionStatus; + function isSimulationError(sim) { + return 'error' in sim; + } + _Api.isSimulationError = isSimulationError; + function isSimulationSuccess(sim) { + return 'transactionData' in sim; + } + _Api.isSimulationSuccess = isSimulationSuccess; + function isSimulationRestore(sim) { + return isSimulationSuccess(sim) && 'restorePreamble' in sim && !!sim.restorePreamble.transactionData; + } + _Api.isSimulationRestore = isSimulationRestore; + function isSimulationRaw(sim) { + return !sim._parsed; + } + _Api.isSimulationRaw = isSimulationRaw; +})(Api || (exports.Api = Api = {})); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/axios.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/axios.d.ts new file mode 100644 index 000000000..e33eb69ca --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/axios.d.ts @@ -0,0 +1,4 @@ +import { HttpClient } from "../http-client"; +export declare const version: string; +export declare const AxiosClient: HttpClient; +export default AxiosClient; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/axios.js b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/axios.js new file mode 100644 index 000000000..7ac7ee27c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/axios.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.version = exports.default = exports.AxiosClient = void 0; +var _httpClient = require("../http-client"); +var version = exports.version = "13.1.0"; +var AxiosClient = exports.AxiosClient = (0, _httpClient.create)({ + headers: { + 'X-Client-Name': 'js-soroban-client', + 'X-Client-Version': version + } +}); +var _default = exports.default = AxiosClient; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/browser.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/browser.d.ts new file mode 100644 index 000000000..ca51e31ab --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/browser.d.ts @@ -0,0 +1,4 @@ +export * from './index'; +export * as StellarBase from '@stellar/stellar-base'; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/browser.js b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/browser.js new file mode 100644 index 000000000..81ef3ddb4 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/browser.js @@ -0,0 +1,27 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + StellarBase: true +}; +exports.default = exports.StellarBase = void 0; +var _index = require("./index"); +Object.keys(_index).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _index[key]; + } + }); +}); +var _StellarBase = _interopRequireWildcard(require("@stellar/stellar-base")); +exports.StellarBase = _StellarBase; +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/index.d.ts new file mode 100644 index 000000000..59ea4be47 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/index.d.ts @@ -0,0 +1,8 @@ +/** @module rpc */ +export * from "./api"; +export { RpcServer as Server, BasicSleepStrategy, LinearSleepStrategy, Durability } from "./server"; +export { default as AxiosClient } from "./axios"; +export { parseRawSimulation, parseRawEvents } from "./parsers"; +export * from "./transaction"; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/index.js b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/index.js new file mode 100644 index 000000000..f5a9e18bd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/index.js @@ -0,0 +1,86 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Server: true, + BasicSleepStrategy: true, + LinearSleepStrategy: true, + Durability: true, + AxiosClient: true, + parseRawSimulation: true, + parseRawEvents: true +}; +Object.defineProperty(exports, "AxiosClient", { + enumerable: true, + get: function get() { + return _axios.default; + } +}); +Object.defineProperty(exports, "BasicSleepStrategy", { + enumerable: true, + get: function get() { + return _server.BasicSleepStrategy; + } +}); +Object.defineProperty(exports, "Durability", { + enumerable: true, + get: function get() { + return _server.Durability; + } +}); +Object.defineProperty(exports, "LinearSleepStrategy", { + enumerable: true, + get: function get() { + return _server.LinearSleepStrategy; + } +}); +Object.defineProperty(exports, "Server", { + enumerable: true, + get: function get() { + return _server.RpcServer; + } +}); +exports.default = void 0; +Object.defineProperty(exports, "parseRawEvents", { + enumerable: true, + get: function get() { + return _parsers.parseRawEvents; + } +}); +Object.defineProperty(exports, "parseRawSimulation", { + enumerable: true, + get: function get() { + return _parsers.parseRawSimulation; + } +}); +var _api = require("./api"); +Object.keys(_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _api[key]; + } + }); +}); +var _server = require("./server"); +var _axios = _interopRequireDefault(require("./axios")); +var _parsers = require("./parsers"); +var _transaction = require("./transaction"); +Object.keys(_transaction).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _transaction[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _transaction[key]; + } + }); +}); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/jsonrpc.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/jsonrpc.d.ts new file mode 100644 index 000000000..bba021d3c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/jsonrpc.d.ts @@ -0,0 +1,35 @@ +export type Id = string | number; +export interface Request { + jsonrpc: "2.0"; + id: Id; + method: string; + params: T; +} +export interface Notification { + jsonrpc: "2.0"; + method: string; + params?: T; +} +export type Response = { + jsonrpc: "2.0"; + id: Id; +} & ({ + error: Error; +} | { + result: T; +}); +export interface Error { + code: number; + message?: string; + data?: E; +} +/** + * Sends the jsonrpc 'params' as a single 'param' object (no array support). + * + * @param {string} url URL to the RPC instance + * @param {string} method RPC method name that should be called + * @param {(any | null)} [param=null] params that should be supplied to the method + * @returns {Promise} + * @private + */ +export declare function postObject(url: string, method: string, param?: any): Promise; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/jsonrpc.js b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/jsonrpc.js new file mode 100644 index 000000000..8ba0f1a64 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/jsonrpc.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.postObject = postObject; +var _axios = _interopRequireDefault(require("./axios")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function hasOwnProperty(obj, prop) { + return obj.hasOwnProperty(prop); +} +function postObject(_x, _x2) { + return _postObject.apply(this, arguments); +} +function _postObject() { + _postObject = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(url, method) { + var param, + response, + _response$data, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + param = _args.length > 2 && _args[2] !== undefined ? _args[2] : null; + _context.next = 3; + return _axios.default.post(url, { + jsonrpc: "2.0", + id: 1, + method: method, + params: param + }); + case 3: + response = _context.sent; + if (!hasOwnProperty(response.data, "error")) { + _context.next = 8; + break; + } + throw response.data.error; + case 8: + return _context.abrupt("return", (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.result); + case 9: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _postObject.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/parsers.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/parsers.d.ts new file mode 100644 index 000000000..28871d62b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/parsers.d.ts @@ -0,0 +1,39 @@ +import { Api } from './api'; +/** + * Parse the response from invoking the `submitTransaction` method of a Soroban RPC server. + * @memberof module:rpc + * @private + * + * @param {Api.RawSendTransactionResponse} raw the raw `submitTransaction` response from the Soroban RPC server to parse + * @returns {Api.SendTransactionResponse} transaction response parsed from the Soroban RPC server's response + */ +export declare function parseRawSendTransaction(raw: Api.RawSendTransactionResponse): Api.SendTransactionResponse; +export declare function parseTransactionInfo(raw: Api.RawTransactionInfo | Api.RawGetTransactionResponse): Omit; +export declare function parseRawTransactions(r: Api.RawTransactionInfo): Api.TransactionInfo; +/** + * Parse and return the retrieved events, if any, from a raw response from a Soroban RPC server. + * @memberof module:rpc + * + * @param {Api.RawGetEventsResponse} raw the raw `getEvents` response from the Soroban RPC server to parse + * @returns {Api.GetEventsResponse} events parsed from the Soroban RPC server's response + */ +export declare function parseRawEvents(raw: Api.RawGetEventsResponse): Api.GetEventsResponse; +/** + * Parse and return the retrieved ledger entries, if any, from a raw response from a Soroban RPC server. + * @memberof module:rpc + * @private + * + * @param {Api.RawGetLedgerEntriesResponse} raw he raw `getLedgerEntries` response from the Soroban RPC server to parse + * @returns {Api.GetLedgerEntriesResponse} ledger entries parsed from the Soroban RPC server's response + */ +export declare function parseRawLedgerEntries(raw: Api.RawGetLedgerEntriesResponse): Api.GetLedgerEntriesResponse; +/** + * Converts a raw response schema into one with parsed XDR fields and a simplified interface. + * @warning This API is only exported for testing purposes and should not be relied on or considered "stable". + * @memberof module:rpc + * + * @param {Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse} sim the raw response schema (parsed ones are allowed, best-effort + * detected, and returned untouched) + * @returns {Api.SimulateTransactionResponse} the original parameter (if already parsed), parsed otherwise + */ +export declare function parseRawSimulation(sim: Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse): Api.SimulateTransactionResponse; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/parsers.js b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/parsers.js new file mode 100644 index 000000000..196336b10 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/parsers.js @@ -0,0 +1,156 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parseRawEvents = parseRawEvents; +exports.parseRawLedgerEntries = parseRawLedgerEntries; +exports.parseRawSendTransaction = parseRawSendTransaction; +exports.parseRawSimulation = parseRawSimulation; +exports.parseRawTransactions = parseRawTransactions; +exports.parseTransactionInfo = parseTransactionInfo; +var _stellarBase = require("@stellar/stellar-base"); +var _api = require("./api"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function parseRawSendTransaction(raw) { + var errorResultXdr = raw.errorResultXdr, + diagnosticEventsXdr = raw.diagnosticEventsXdr; + delete raw.errorResultXdr; + delete raw.diagnosticEventsXdr; + if (errorResultXdr) { + return _objectSpread(_objectSpread(_objectSpread({}, raw), diagnosticEventsXdr !== undefined && diagnosticEventsXdr.length > 0 && { + diagnosticEvents: diagnosticEventsXdr.map(function (evt) { + return _stellarBase.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + }) + }), {}, { + errorResult: _stellarBase.xdr.TransactionResult.fromXDR(errorResultXdr, 'base64') + }); + } + return _objectSpread({}, raw); +} +function parseTransactionInfo(raw) { + var meta = _stellarBase.xdr.TransactionMeta.fromXDR(raw.resultMetaXdr, 'base64'); + var info = { + ledger: raw.ledger, + createdAt: raw.createdAt, + applicationOrder: raw.applicationOrder, + feeBump: raw.feeBump, + envelopeXdr: _stellarBase.xdr.TransactionEnvelope.fromXDR(raw.envelopeXdr, 'base64'), + resultXdr: _stellarBase.xdr.TransactionResult.fromXDR(raw.resultXdr, 'base64'), + resultMetaXdr: meta + }; + if (meta.switch() === 3 && meta.v3().sorobanMeta() !== null) { + var _meta$v3$sorobanMeta; + info.returnValue = (_meta$v3$sorobanMeta = meta.v3().sorobanMeta()) === null || _meta$v3$sorobanMeta === void 0 ? void 0 : _meta$v3$sorobanMeta.returnValue(); + } + if ('diagnosticEventsXdr' in raw && raw.diagnosticEventsXdr) { + info.diagnosticEventsXdr = raw.diagnosticEventsXdr.map(function (diagnosticEvent) { + return _stellarBase.xdr.DiagnosticEvent.fromXDR(diagnosticEvent, 'base64'); + }); + } + return info; +} +function parseRawTransactions(r) { + return _objectSpread({ + status: r.status, + txHash: r.txHash + }, parseTransactionInfo(r)); +} +function parseRawEvents(raw) { + var _raw$events; + return { + latestLedger: raw.latestLedger, + cursor: raw.cursor, + events: ((_raw$events = raw.events) !== null && _raw$events !== void 0 ? _raw$events : []).map(function (evt) { + var clone = _objectSpread({}, evt); + delete clone.contractId; + return _objectSpread(_objectSpread(_objectSpread({}, clone), evt.contractId !== '' && { + contractId: new _stellarBase.Contract(evt.contractId) + }), {}, { + topic: evt.topic.map(function (topic) { + return _stellarBase.xdr.ScVal.fromXDR(topic, 'base64'); + }), + value: _stellarBase.xdr.ScVal.fromXDR(evt.value, 'base64') + }); + }) + }; +} +function parseRawLedgerEntries(raw) { + var _raw$entries; + return { + latestLedger: raw.latestLedger, + entries: ((_raw$entries = raw.entries) !== null && _raw$entries !== void 0 ? _raw$entries : []).map(function (rawEntry) { + if (!rawEntry.key || !rawEntry.xdr) { + throw new TypeError("invalid ledger entry: ".concat(JSON.stringify(rawEntry))); + } + return _objectSpread({ + lastModifiedLedgerSeq: rawEntry.lastModifiedLedgerSeq, + key: _stellarBase.xdr.LedgerKey.fromXDR(rawEntry.key, 'base64'), + val: _stellarBase.xdr.LedgerEntryData.fromXDR(rawEntry.xdr, 'base64') + }, rawEntry.liveUntilLedgerSeq !== undefined && { + liveUntilLedgerSeq: rawEntry.liveUntilLedgerSeq + }); + }) + }; +} +function parseSuccessful(sim, partial) { + var _sim$results$length, _sim$results, _sim$stateChanges$len, _sim$stateChanges, _sim$stateChanges2; + var success = _objectSpread(_objectSpread(_objectSpread({}, partial), {}, { + transactionData: new _stellarBase.SorobanDataBuilder(sim.transactionData), + minResourceFee: sim.minResourceFee + }, ((_sim$results$length = (_sim$results = sim.results) === null || _sim$results === void 0 ? void 0 : _sim$results.length) !== null && _sim$results$length !== void 0 ? _sim$results$length : 0 > 0) && { + result: sim.results.map(function (row) { + var _row$auth; + return { + auth: ((_row$auth = row.auth) !== null && _row$auth !== void 0 ? _row$auth : []).map(function (entry) { + return _stellarBase.xdr.SorobanAuthorizationEntry.fromXDR(entry, 'base64'); + }), + retval: row.xdr ? _stellarBase.xdr.ScVal.fromXDR(row.xdr, 'base64') : _stellarBase.xdr.ScVal.scvVoid() + }; + })[0] + }), ((_sim$stateChanges$len = (_sim$stateChanges = sim.stateChanges) === null || _sim$stateChanges === void 0 ? void 0 : _sim$stateChanges.length) !== null && _sim$stateChanges$len !== void 0 ? _sim$stateChanges$len : 0 > 0) && { + stateChanges: (_sim$stateChanges2 = sim.stateChanges) === null || _sim$stateChanges2 === void 0 ? void 0 : _sim$stateChanges2.map(function (entryChange) { + return { + type: entryChange.type, + key: _stellarBase.xdr.LedgerKey.fromXDR(entryChange.key, 'base64'), + before: entryChange.before ? _stellarBase.xdr.LedgerEntry.fromXDR(entryChange.before, 'base64') : null, + after: entryChange.after ? _stellarBase.xdr.LedgerEntry.fromXDR(entryChange.after, 'base64') : null + }; + }) + }); + if (!sim.restorePreamble || sim.restorePreamble.transactionData === '') { + return success; + } + return _objectSpread(_objectSpread({}, success), {}, { + restorePreamble: { + minResourceFee: sim.restorePreamble.minResourceFee, + transactionData: new _stellarBase.SorobanDataBuilder(sim.restorePreamble.transactionData) + } + }); +} +function parseRawSimulation(sim) { + var _sim$events$map, _sim$events; + var looksRaw = _api.Api.isSimulationRaw(sim); + if (!looksRaw) { + return sim; + } + var base = { + _parsed: true, + id: sim.id, + latestLedger: sim.latestLedger, + events: (_sim$events$map = (_sim$events = sim.events) === null || _sim$events === void 0 ? void 0 : _sim$events.map(function (evt) { + return _stellarBase.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + })) !== null && _sim$events$map !== void 0 ? _sim$events$map : [] + }; + if (typeof sim.error === 'string') { + return _objectSpread(_objectSpread({}, base), {}, { + error: sim.error + }); + } + return parseSuccessful(sim, base); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/server.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/server.d.ts new file mode 100644 index 000000000..7b90f345d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/server.d.ts @@ -0,0 +1,622 @@ +import URI from 'urijs'; +import { Account, Address, Asset, Contract, FeeBumpTransaction, Transaction, xdr } from '@stellar/stellar-base'; +import { Api } from './api'; +/** + * Default transaction submission timeout for RPC requests, in milliseconds + * @constant {number} + * @default 60000 + * @memberof module:rpc.Server + */ +export declare const SUBMIT_TRANSACTION_TIMEOUT: number; +/** + * Specifies the durability namespace of contract-related ledger entries. + * @enum {('temporary' | 'persistent')} + * @memberof module:rpc + * + * @see {@link https://developers.stellar.org/docs/learn/smart-contract-internals/state-archival | State Archival docs} + * @see {@link https://docs.rs/soroban-sdk/latest/soroban_sdk/storage/struct.Storage.html | Rust SDK Storage docs} + */ +export declare enum Durability { + Temporary = "temporary", + Persistent = "persistent" +} +/** + * @typedef {object} GetEventsRequest Describes the complex filter combinations available for event queries. + * @property {Array.} filters Filters to use when querying events from the RPC server. + * @property {number} [startLedger] Ledger number (inclusive) to begin querying events. + * @property {string} [cursor] Page cursor (exclusive) to begin querying events. + * @property {number} [limit=100] The maximum number of events that should be returned in the RPC response. + * @memberof module:rpc.Server + */ +/** + * @typedef {object} ResourceLeeway Describes additional resource leeways for transaction simulation. + * @property {number} cpuInstructions Simulate the transaction with more CPU instructions available. + * @memberof module:rpc.Server + */ +/** + * @typedef {object} Options Options for configuring connections to RPC servers. + * @property {boolean} [allowHttp=false] Allow connecting to http servers, default: `false`. This must be set to false in production deployments! + * @property {number} [timeout=0] Allow a timeout, default: 0. Allows user to avoid nasty lag. You can also use {@link Config} class to set this globally. + * @property {Record} [headers] Additional headers that should be added to any requests to the RPC server. + * @memberof module:rpc.Server + */ +export declare namespace RpcServer { + interface GetEventsRequest { + filters: Api.EventFilter[]; + startLedger?: number; + endLedger?: number; + cursor?: string; + limit?: number; + } + interface PollingOptions { + attempts?: number; + sleepStrategy?: SleepStrategy; + } + interface ResourceLeeway { + cpuInstructions: number; + } + interface Options { + allowHttp?: boolean; + timeout?: number; + headers?: Record; + } +} +export declare const BasicSleepStrategy: SleepStrategy; +export declare const LinearSleepStrategy: SleepStrategy; +/** + * A function that returns the number of *milliseconds* to sleep + * on a given `iter`ation. + */ +export type SleepStrategy = (iter: number) => number; +/** + * Handles the network connection to a Soroban RPC instance, exposing an + * interface for requests to that instance. + * + * @alias module:rpc.Server + * @memberof module:rpc + * + * @param {string} serverURL Soroban-RPC Server URL (ex. `http://localhost:8000/soroban/rpc`). + * @param {module:rpc.Server.Options} [opts] Options object + * @param {boolean} [opts.allowHttp] Allows connecting to insecure http servers + * (default: `false`). This must be set to false in production deployments! + * You can also use {@link Config} class to set this globally. + * @param {Record} [opts.headers] Allows setting custom headers + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods | API reference docs} + */ +export declare class RpcServer { + readonly serverURL: URI; + constructor(serverURL: string, opts?: RpcServer.Options); + /** + * Fetch a minimal set of current info about a Stellar account. + * + * Needed to get the current sequence number for the account so you can build + * a successful transaction with {@link TransactionBuilder}. + * + * @param {string} address The public address of the account to load. + * @returns {Promise} A promise which resolves to the {@link Account} + * object with a populated sequence number + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs} + * + * @example + * const accountId = "GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4"; + * server.getAccount(accountId).then((account) => { + * console.log("sequence:", account.sequence); + * }); + */ + getAccount(address: string): Promise; + /** + * General node health check. + * + * @returns {Promise} A promise which resolves to the + * {@link Api.GetHealthResponse} object with the status of the + * server (e.g. "healthy"). + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getHealth | getLedgerEntries docs} + * + * @example + * server.getHealth().then((health) => { + * console.log("status:", health.status); + * }); + */ + getHealth(): Promise; + /** + * Reads the current value of contract data ledger entries directly. + * + * Allows you to directly inspect the current state of a contract. This is a + * backup way to access your contract data which may not be available via + * events or {@link module:rpc.Server#simulateTransaction}. + * + * @param {string|Address|Contract} contract The contract ID containing the + * data to load as a strkey (`C...` form), a {@link Contract}, or an + * {@link Address} instance + * @param {xdr.ScVal} key The key of the contract data to load + * @param {module:rpc.Durability} [durability=Durability.Persistent] The "durability + * keyspace" that this ledger key belongs to, which is either 'temporary' + * or 'persistent' (the default), see {@link module:rpc.Durability}. + * @returns {Promise} The current data value + * + * @warning If the data entry in question is a 'temporary' entry, it's + * entirely possible that it has expired out of existence. + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs} + * + * @example + * const contractId = "CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5"; + * const key = xdr.ScVal.scvSymbol("counter"); + * server.getContractData(contractId, key, Durability.Temporary).then(data => { + * console.log("value:", data.val); + * console.log("liveUntilLedgerSeq:", data.liveUntilLedgerSeq); + * console.log("lastModified:", data.lastModifiedLedgerSeq); + * console.log("latestLedger:", data.latestLedger); + * }); + */ + getContractData(contract: string | Address | Contract, key: xdr.ScVal, durability?: Durability): Promise; + /** + * Retrieves the WASM bytecode for a given contract. + * + * This method allows you to fetch the WASM bytecode associated with a contract + * deployed on the Soroban network. The WASM bytecode represents the executable + * code of the contract. + * + * @param {string} contractId The contract ID containing the WASM bytecode to retrieve + * @returns {Promise} A Buffer containing the WASM bytecode + * @throws {Error} If the contract or its associated WASM bytecode cannot be + * found on the network. + * + * @example + * const contractId = "CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5"; + * server.getContractWasmByContractId(contractId).then(wasmBuffer => { + * console.log("WASM bytecode length:", wasmBuffer.length); + * // ... do something with the WASM bytecode ... + * }).catch(err => { + * console.error("Error fetching WASM bytecode:", err); + * }); + */ + getContractWasmByContractId(contractId: string): Promise; + /** + * Retrieves the WASM bytecode for a given contract hash. + * + * This method allows you to fetch the WASM bytecode associated with a contract + * deployed on the Soroban network using the contract's WASM hash. The WASM bytecode + * represents the executable code of the contract. + * + * @param {Buffer} wasmHash The WASM hash of the contract + * @returns {Promise} A Buffer containing the WASM bytecode + * @throws {Error} If the contract or its associated WASM bytecode cannot be + * found on the network. + * + * @example + * const wasmHash = Buffer.from("..."); + * server.getContractWasmByHash(wasmHash).then(wasmBuffer => { + * console.log("WASM bytecode length:", wasmBuffer.length); + * // ... do something with the WASM bytecode ... + * }).catch(err => { + * console.error("Error fetching WASM bytecode:", err); + * }); + */ + getContractWasmByHash(wasmHash: Buffer | string, format?: undefined | "hex" | "base64"): Promise; + /** + * Reads the current value of arbitrary ledger entries directly. + * + * Allows you to directly inspect the current state of contracts, contract's + * code, accounts, or any other ledger entries. + * + * To fetch a contract's WASM byte-code, built the appropriate + * {@link xdr.LedgerKeyContractCode} ledger entry key (or see + * {@link Contract.getFootprint}). + * + * @param {xdr.ScVal[]} keys One or more ledger entry keys to load + * @returns {Promise} The current on-chain + * values for the given ledger keys + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs} + * @see RpcServer._getLedgerEntries + * @example + * const contractId = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM"; + * const key = xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({ + * contractId: StrKey.decodeContract(contractId), + * key: xdr.ScVal.scvSymbol("counter"), + * })); + * + * server.getLedgerEntries([key]).then(response => { + * const ledgerData = response.entries[0]; + * console.log("key:", ledgerData.key); + * console.log("value:", ledgerData.val); + * console.log("liveUntilLedgerSeq:", ledgerData.liveUntilLedgerSeq); + * console.log("lastModified:", ledgerData.lastModifiedLedgerSeq); + * console.log("latestLedger:", response.latestLedger); + * }); + */ + getLedgerEntries(...keys: xdr.LedgerKey[]): Promise; + _getLedgerEntries(...keys: xdr.LedgerKey[]): Promise; + /** + * Poll for a particular transaction with certain parameters. + * + * After submitting a transaction, clients can use this to poll for + * transaction completion and return a definitive state of success or failure. + * + * @param {string} hash the transaction you're polling for + * @param {number} [opts.attempts] (optional) the number of attempts to make + * before returning the last-seen status. By default or on invalid inputs, + * try 5 times. + * @param {SleepStrategy} [opts.sleepStrategy] (optional) the amount of time + * to wait for between each attempt. By default, sleep for 1 second between + * each attempt. + * + * @return {Promise} the response after a "found" + * response (which may be success or failure) or the last response obtained + * after polling the maximum number of specified attempts. + * + * @example + * const h = "c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a"; + * const txStatus = await server.pollTransaction(h, { + * attempts: 100, // I'm a maniac + * sleepStrategy: rpc.LinearSleepStrategy + * }); // this will take 5,050 seconds to complete + */ + pollTransaction(hash: string, opts?: RpcServer.PollingOptions): Promise; + /** + * Fetch the details of a submitted transaction. + * + * After submitting a transaction, clients should poll this to tell when the + * transaction has completed. + * + * @param {string} hash Hex-encoded hash of the transaction to check + * @returns {Promise} The status, result, and + * other details about the transaction + * + * @see + * {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransaction | getTransaction docs} + * + * @example + * const transactionHash = "c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a"; + * server.getTransaction(transactionHash).then((tx) => { + * console.log("status:", tx.status); + * console.log("envelopeXdr:", tx.envelopeXdr); + * console.log("resultMetaXdr:", tx.resultMetaXdr); + * console.log("resultXdr:", tx.resultXdr); + * }); + */ + getTransaction(hash: string): Promise; + _getTransaction(hash: string): Promise; + /** + * Fetch transactions starting from a given start ledger or a cursor. The end ledger is the latest ledger + * in that RPC instance. + * + * @param {Api.GetTransactionsRequest} request - The request parameters. + * @returns {Promise} - A promise that resolves to the transactions response. + * + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransactions + * @example + * server.getTransactions({ + * startLedger: 10000, + * limit: 10, + * }).then((response) => { + * console.log("Transactions:", response.transactions); + * console.log("Latest Ledger:", response.latestLedger); + * console.log("Cursor:", response.cursor); + * }); + */ + getTransactions(request: Api.GetTransactionsRequest): Promise; + private _getTransactions; + /** + * Fetch all events that match a given set of filters. + * + * The given filters (see {@link module:rpc.Api.EventFilter | Api.EventFilter} + * for detailed fields) are combined only in a logical OR fashion, and all of + * the fields in each filter are optional. + * + * To page through events, use the `pagingToken` field on the relevant + * {@link Api.EventResponse} object to set the `cursor` parameter. + * + * @param {module:rpc.Server.GetEventsRequest} request Event filters + * @returns {Promise} A paginatable set of the events + * matching the given event filters + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getEvents | getEvents docs} + * + * @example + * server.getEvents({ + * startLedger: 1000, + * endLedger: 2000, + * filters: [ + * { + * type: "contract", + * contractIds: [ "deadb33f..." ], + * topics: [[ "AAAABQAAAAh0cmFuc2Zlcg==", "AAAAAQB6Mcc=", "*" ]] + * }, { + * type: "system", + * contractIds: [ "...c4f3b4b3..." ], + * topics: [[ "*" ], [ "*", "AAAAAQB6Mcc=" ]] + * }, { + * contractIds: [ "...c4f3b4b3..." ], + * topics: [[ "AAAABQAAAAh0cmFuc2Zlcg==" ]] + * }, { + * type: "diagnostic", + * topics: [[ "AAAAAQB6Mcc=" ]] + * } + * ], + * limit: 10, + * }); + */ + getEvents(request: RpcServer.GetEventsRequest): Promise; + _getEvents(request: RpcServer.GetEventsRequest): Promise; + /** + * Fetch metadata about the network this Soroban RPC server is connected to. + * + * @returns {Promise} Metadata about the current + * network this RPC server is connected to + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getNetwork | getNetwork docs} + * + * @example + * server.getNetwork().then((network) => { + * console.log("friendbotUrl:", network.friendbotUrl); + * console.log("passphrase:", network.passphrase); + * console.log("protocolVersion:", network.protocolVersion); + * }); + */ + getNetwork(): Promise; + /** + * Fetch the latest ledger meta info from network which this Soroban RPC + * server is connected to. + * + * @returns {Promise} metadata about the + * latest ledger on the network that this RPC server is connected to + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLatestLedger | getLatestLedger docs} + * + * @example + * server.getLatestLedger().then((response) => { + * console.log("hash:", response.id); + * console.log("sequence:", response.sequence); + * console.log("protocolVersion:", response.protocolVersion); + * }); + */ + getLatestLedger(): Promise; + /** + * Submit a trial contract invocation to get back return values, expected + * ledger footprint, expected authorizations, and expected costs. + * + * @param {Transaction | FeeBumpTransaction} tx the transaction to + * simulate, which should include exactly one operation (one of + * {@link xdr.InvokeHostFunctionOp}, {@link xdr.ExtendFootprintTTLOp}, or + * {@link xdr.RestoreFootprintOp}). Any provided footprint or auth + * information will be ignored. + * @returns {Promise} An object with the + * cost, footprint, result/auth requirements (if applicable), and error of + * the transaction + * + * @see {@link https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/operations-and-transactions | transaction docs} + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction | simulateTransaction docs} + * @see module:rpc.Server#prepareTransaction + * @see module:rpc.assembleTransaction + * + * @example + * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE'; + * const contract = new StellarSdk.Contract(contractId); + * + * // Right now, this is just the default fee for this example. + * const fee = StellarSdk.BASE_FEE; + * const transaction = new StellarSdk.TransactionBuilder(account, { fee }) + * // Uncomment the following line to build transactions for the live network. Be + * // sure to also change the horizon hostname. + * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC) + * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET) + * .setTimeout(30) // valid for the next 30s + * // Add an operation to call increment() on the contract + * .addOperation(contract.call("increment")) + * .build(); + * + * server.simulateTransaction(transaction).then((sim) => { + * console.log("cost:", sim.cost); + * console.log("result:", sim.result); + * console.log("error:", sim.error); + * console.log("latestLedger:", sim.latestLedger); + * }); + */ + simulateTransaction(tx: Transaction | FeeBumpTransaction, addlResources?: RpcServer.ResourceLeeway): Promise; + _simulateTransaction(transaction: Transaction | FeeBumpTransaction, addlResources?: RpcServer.ResourceLeeway): Promise; + /** + * Submit a trial contract invocation, first run a simulation of the contract + * invocation as defined on the incoming transaction, and apply the results to + * a new copy of the transaction which is then returned. Setting the ledger + * footprint and authorization, so the resulting transaction is ready for + * signing & sending. + * + * The returned transaction will also have an updated fee that is the sum of + * fee set on incoming transaction with the contract resource fees estimated + * from simulation. It is advisable to check the fee on returned transaction + * and validate or take appropriate measures for interaction with user to + * confirm it is acceptable. + * + * You can call the {@link module:rpc.Server#simulateTransaction} method + * directly first if you want to inspect estimated fees for a given + * transaction in detail first, then re-assemble it manually or via + * {@link module:rpc.assembleTransaction}. + * + * @param {Transaction | FeeBumpTransaction} tx the transaction to + * prepare. It should include exactly one operation, which must be one of + * {@link xdr.InvokeHostFunctionOp}, {@link xdr.ExtendFootprintTTLOp}, + * or {@link xdr.RestoreFootprintOp}. + * + * Any provided footprint will be overwritten. However, if your operation + * has existing auth entries, they will be preferred over ALL auth entries + * from the simulation. In other words, if you include auth entries, you + * don't care about the auth returned from the simulation. Other fields + * (footprint, etc.) will be filled as normal. + * @returns {Promise} A copy of the + * transaction with the expected authorizations (in the case of + * invocation), resources, and ledger footprints added. The transaction fee + * will also automatically be padded with the contract's minimum resource + * fees discovered from the simulation. + * @throws {jsonrpc.Error|Error|Api.SimulateTransactionErrorResponse} + * If simulation fails + * + * @see module:rpc.assembleTransaction + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction | simulateTransaction docs} + * + * @example + * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE'; + * const contract = new StellarSdk.Contract(contractId); + * + * // Right now, this is just the default fee for this example. + * const fee = StellarSdk.BASE_FEE; + * const transaction = new StellarSdk.TransactionBuilder(account, { fee }) + * // Uncomment the following line to build transactions for the live network. Be + * // sure to also change the horizon hostname. + * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC) + * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET) + * .setTimeout(30) // valid for the next 30s + * // Add an operation to call increment() on the contract + * .addOperation(contract.call("increment")) + * .build(); + * + * const preparedTransaction = await server.prepareTransaction(transaction); + * + * // Sign this transaction with the secret key + * // NOTE: signing is transaction is network specific. Test network transactions + * // won't work in the public network. To switch networks, use the Network object + * // as explained above (look for StellarSdk.Network). + * const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey); + * preparedTransaction.sign(sourceKeypair); + * + * server.sendTransaction(transaction).then(result => { + * console.log("hash:", result.hash); + * console.log("status:", result.status); + * console.log("errorResultXdr:", result.errorResultXdr); + * }); + */ + prepareTransaction(tx: Transaction | FeeBumpTransaction): Promise, import("@stellar/stellar-base").Operation[]>>; + /** + * Submit a real transaction to the Stellar network. + * + * Unlike Horizon, Soroban RPC does not wait for transaction completion. It + * simply validates the transaction and enqueues it. Clients should call + * {@link module:rpc.Server#getTransaction} to learn about transaction + * success/failure. + * + * @param {Transaction | FeeBumpTransaction} transaction to submit + * @returns {Promise} the + * transaction id, status, and any error if available + * + * @see {@link https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/operations-and-transactions | transaction docs} + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/sendTransaction | sendTransaction docs} + * + * @example + * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE'; + * const contract = new StellarSdk.Contract(contractId); + * + * // Right now, this is just the default fee for this example. + * const fee = StellarSdk.BASE_FEE; + * const transaction = new StellarSdk.TransactionBuilder(account, { fee }) + * // Uncomment the following line to build transactions for the live network. Be + * // sure to also change the horizon hostname. + * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC) + * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET) + * .setTimeout(30) // valid for the next 30s + * // Add an operation to call increment() on the contract + * .addOperation(contract.call("increment")) + * .build(); + * + * // Sign this transaction with the secret key + * // NOTE: signing is transaction is network specific. Test network transactions + * // won't work in the public network. To switch networks, use the Network object + * // as explained above (look for StellarSdk.Network). + * const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey); + * transaction.sign(sourceKeypair); + * + * server.sendTransaction(transaction).then((result) => { + * console.log("hash:", result.hash); + * console.log("status:", result.status); + * console.log("errorResultXdr:", result.errorResultXdr); + * }); + */ + sendTransaction(transaction: Transaction | FeeBumpTransaction): Promise; + _sendTransaction(transaction: Transaction | FeeBumpTransaction): Promise; + /** + * Fund a new account using the network's Friendbot faucet, if any. + * + * @param {string | Account} address The address or account instance that we + * want to create and fund with Friendbot + * @param {string} [friendbotUrl] Optionally, an explicit address for + * friendbot (by default: this calls the Soroban RPC + * {@link module:rpc.Server#getNetwork | getNetwork} method to try to + * discover this network's Friendbot url). + * @returns {Promise} An {@link Account} object for the created + * account, or the existing account if it's already funded with the + * populated sequence number (note that the account will not be "topped + * off" if it already exists) + * @throws If Friendbot is not configured on this network or request failure + * + * @see {@link https://developers.stellar.org/docs/learn/networks#friendbot | Friendbot docs} + * @see {@link module:Friendbot.Api.Response} + * + * @example + * server + * .requestAirdrop("GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4") + * .then((accountCreated) => { + * console.log("accountCreated:", accountCreated); + * }).catch((error) => { + * console.error("error:", error); + * }); + */ + requestAirdrop(address: string | Pick, friendbotUrl?: string): Promise; + /** + * Provides an analysis of the recent fee stats for regular and smart + * contract operations. + * + * @returns {Promise} the fee stats + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getFeeStats + */ + getFeeStats(): Promise; + /** + * Provides information about the current version details of the Soroban RPC and captive-core + * + * @returns {Promise} the version info + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getVersionInfo + */ + getVersionInfo(): Promise; + /** + * Returns a contract's balance of a particular SAC asset, if any. + * + * This is a convenience wrapper around {@link Server.getLedgerEntries}. + * + * @param {string} contractId the contract ID (string `C...`) whose + * balance of `sac` you want to know + * @param {Asset} sac the built-in SAC token (e.g. `USDC:GABC...`) that + * you are querying from the given `contract`. + * @param {string} [networkPassphrase] optionally, the network passphrase to + * which this token applies. If omitted, a request about network + * information will be made (see {@link getNetwork}), since contract IDs + * for assets are specific to a network. You can refer to {@link Networks} + * for a list of built-in passphrases, e.g., `Networks.TESTNET`. + * + * @returns {Promise}, which will contain the balance + * entry details if and only if the request returned a valid balance ledger + * entry. If it doesn't, the `balanceEntry` field will not exist. + * + * @throws {TypeError} If `contractId` is not a valid contract strkey (C...). + * + * @see getLedgerEntries + * @see https://developers.stellar.org/docs/tokens/stellar-asset-contract + * + * @example + * // assume `contractId` is some contract with an XLM balance + * // assume server is an instantiated `Server` instance. + * const entry = (await server.getSACBalance( + * new Address(contractId), + * Asset.native(), + * Networks.PUBLIC + * )); + * + * // assumes BigInt support: + * console.log( + * entry.balanceEntry ? + * BigInt(entry.balanceEntry.amount) : + * "Contract has no XLM"); + */ + getSACBalance(contractId: string, sac: Asset, networkPassphrase?: string): Promise; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/server.js b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/server.js new file mode 100644 index 000000000..b7b367d32 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/server.js @@ -0,0 +1,896 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SUBMIT_TRANSACTION_TIMEOUT = exports.RpcServer = exports.LinearSleepStrategy = exports.Durability = exports.BasicSleepStrategy = void 0; +var _urijs = _interopRequireDefault(require("urijs")); +var _stellarBase = require("@stellar/stellar-base"); +var _axios = _interopRequireDefault(require("./axios")); +var jsonrpc = _interopRequireWildcard(require("./jsonrpc")); +var _api = require("./api"); +var _transaction = require("./transaction"); +var _parsers = require("./parsers"); +var _utils = require("../utils"); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var SUBMIT_TRANSACTION_TIMEOUT = exports.SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000; +var Durability = exports.Durability = function (Durability) { + Durability["Temporary"] = "temporary"; + Durability["Persistent"] = "persistent"; + return Durability; +}({}); +var DEFAULT_GET_TRANSACTION_TIMEOUT = 30; +var BasicSleepStrategy = exports.BasicSleepStrategy = function BasicSleepStrategy(_iter) { + return 1000; +}; +var LinearSleepStrategy = exports.LinearSleepStrategy = function LinearSleepStrategy(iter) { + return 1000 * iter; +}; +function findCreatedAccountSequenceInTransactionMeta(meta) { + var _operations$flatMap$f; + var operations = []; + switch (meta.switch()) { + case 0: + operations = meta.operations(); + break; + case 1: + case 2: + case 3: + operations = meta.value().operations(); + break; + default: + throw new Error('Unexpected transaction meta switch value'); + } + var sequenceNumber = (_operations$flatMap$f = operations.flatMap(function (op) { + return op.changes(); + }).find(function (c) { + return c.switch() === _stellarBase.xdr.LedgerEntryChangeType.ledgerEntryCreated() && c.created().data().switch() === _stellarBase.xdr.LedgerEntryType.account(); + })) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.created()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.data()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.account()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.seqNum()) === null || _operations$flatMap$f === void 0 ? void 0 : _operations$flatMap$f.toString(); + if (sequenceNumber) { + return sequenceNumber; + } + throw new Error('No account created in transaction'); +} +var RpcServer = exports.RpcServer = function () { + function RpcServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, RpcServer); + this.serverURL = (0, _urijs.default)(serverURL); + if (opts.headers && Object.keys(opts.headers).length !== 0) { + _axios.default.interceptors.request.use(function (config) { + config.headers = Object.assign(config.headers, opts.headers); + return config; + }); + } + if (this.serverURL.protocol() !== 'https' && !opts.allowHttp) { + throw new Error("Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set"); + } + } + return _createClass(RpcServer, [{ + key: "getAccount", + value: (function () { + var _getAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(address) { + var ledgerKey, resp, accountEntry; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + ledgerKey = _stellarBase.xdr.LedgerKey.account(new _stellarBase.xdr.LedgerKeyAccount({ + accountId: _stellarBase.Keypair.fromPublicKey(address).xdrPublicKey() + })); + _context.next = 3; + return this.getLedgerEntries(ledgerKey); + case 3: + resp = _context.sent; + if (!(resp.entries.length === 0)) { + _context.next = 6; + break; + } + return _context.abrupt("return", Promise.reject({ + code: 404, + message: "Account not found: ".concat(address) + })); + case 6: + accountEntry = resp.entries[0].val.account(); + return _context.abrupt("return", new _stellarBase.Account(address, accountEntry.seqNum().toString())); + case 8: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function getAccount(_x) { + return _getAccount.apply(this, arguments); + } + return getAccount; + }()) + }, { + key: "getHealth", + value: (function () { + var _getHealth = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getHealth')); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function getHealth() { + return _getHealth.apply(this, arguments); + } + return getHealth; + }()) + }, { + key: "getContractData", + value: (function () { + var _getContractData = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(contract, key) { + var durability, + scAddress, + xdrDurability, + contractKey, + _args3 = arguments; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + durability = _args3.length > 2 && _args3[2] !== undefined ? _args3[2] : Durability.Persistent; + if (!(typeof contract === 'string')) { + _context3.next = 5; + break; + } + scAddress = new _stellarBase.Contract(contract).address().toScAddress(); + _context3.next = 14; + break; + case 5: + if (!(contract instanceof _stellarBase.Address)) { + _context3.next = 9; + break; + } + scAddress = contract.toScAddress(); + _context3.next = 14; + break; + case 9: + if (!(contract instanceof _stellarBase.Contract)) { + _context3.next = 13; + break; + } + scAddress = contract.address().toScAddress(); + _context3.next = 14; + break; + case 13: + throw new TypeError("unknown contract type: ".concat(contract)); + case 14: + _context3.t0 = durability; + _context3.next = _context3.t0 === Durability.Temporary ? 17 : _context3.t0 === Durability.Persistent ? 19 : 21; + break; + case 17: + xdrDurability = _stellarBase.xdr.ContractDataDurability.temporary(); + return _context3.abrupt("break", 22); + case 19: + xdrDurability = _stellarBase.xdr.ContractDataDurability.persistent(); + return _context3.abrupt("break", 22); + case 21: + throw new TypeError("invalid durability: ".concat(durability)); + case 22: + contractKey = _stellarBase.xdr.LedgerKey.contractData(new _stellarBase.xdr.LedgerKeyContractData({ + key: key, + contract: scAddress, + durability: xdrDurability + })); + return _context3.abrupt("return", this.getLedgerEntries(contractKey).then(function (r) { + if (r.entries.length === 0) { + return Promise.reject({ + code: 404, + message: "Contract data not found. Contract: ".concat(_stellarBase.Address.fromScAddress(scAddress).toString(), ", Key: ").concat(key.toXDR('base64'), ", Durability: ").concat(durability) + }); + } + return r.entries[0]; + })); + case 24: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function getContractData(_x2, _x3) { + return _getContractData.apply(this, arguments); + } + return getContractData; + }()) + }, { + key: "getContractWasmByContractId", + value: (function () { + var _getContractWasmByContractId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(contractId) { + var _response$entries$; + var contractLedgerKey, response, wasmHash; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + contractLedgerKey = new _stellarBase.Contract(contractId).getFootprint(); + _context4.next = 3; + return this.getLedgerEntries(contractLedgerKey); + case 3: + response = _context4.sent; + if (!(!response.entries.length || !((_response$entries$ = response.entries[0]) !== null && _response$entries$ !== void 0 && _response$entries$.val))) { + _context4.next = 6; + break; + } + return _context4.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract hash from server" + })); + case 6: + wasmHash = response.entries[0].val.contractData().val().instance().executable().wasmHash(); + return _context4.abrupt("return", this.getContractWasmByHash(wasmHash)); + case 8: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function getContractWasmByContractId(_x4) { + return _getContractWasmByContractId.apply(this, arguments); + } + return getContractWasmByContractId; + }()) + }, { + key: "getContractWasmByHash", + value: (function () { + var _getContractWasmByHash = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(wasmHash) { + var _responseWasm$entries; + var format, + wasmHashBuffer, + ledgerKeyWasmHash, + responseWasm, + wasmBuffer, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + format = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : undefined; + wasmHashBuffer = typeof wasmHash === "string" ? Buffer.from(wasmHash, format) : wasmHash; + ledgerKeyWasmHash = _stellarBase.xdr.LedgerKey.contractCode(new _stellarBase.xdr.LedgerKeyContractCode({ + hash: wasmHashBuffer + })); + _context5.next = 5; + return this.getLedgerEntries(ledgerKeyWasmHash); + case 5: + responseWasm = _context5.sent; + if (!(!responseWasm.entries.length || !((_responseWasm$entries = responseWasm.entries[0]) !== null && _responseWasm$entries !== void 0 && _responseWasm$entries.val))) { + _context5.next = 8; + break; + } + return _context5.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract wasm from server" + })); + case 8: + wasmBuffer = responseWasm.entries[0].val.contractCode().code(); + return _context5.abrupt("return", wasmBuffer); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function getContractWasmByHash(_x5) { + return _getContractWasmByHash.apply(this, arguments); + } + return getContractWasmByHash; + }()) + }, { + key: "getLedgerEntries", + value: (function () { + var _getLedgerEntries2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6() { + var _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + return _context6.abrupt("return", this._getLedgerEntries.apply(this, _args6).then(_parsers.parseRawLedgerEntries)); + case 1: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function getLedgerEntries() { + return _getLedgerEntries2.apply(this, arguments); + } + return getLedgerEntries; + }()) + }, { + key: "_getLedgerEntries", + value: function () { + var _getLedgerEntries3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee7() { + var _len, + keys, + _key, + _args7 = arguments; + return _regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + for (_len = _args7.length, keys = new Array(_len), _key = 0; _key < _len; _key++) { + keys[_key] = _args7[_key]; + } + return _context7.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getLedgerEntries', { + keys: keys.map(function (k) { + return k.toXDR('base64'); + }) + })); + case 2: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function _getLedgerEntries() { + return _getLedgerEntries3.apply(this, arguments); + } + return _getLedgerEntries; + }() + }, { + key: "pollTransaction", + value: (function () { + var _pollTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee8(hash, opts) { + var _opts$attempts, _opts$attempts2; + var maxAttempts, foundInfo, attempt, _opts$sleepStrategy; + return _regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + maxAttempts = ((_opts$attempts = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts !== void 0 ? _opts$attempts : 0) < 1 ? DEFAULT_GET_TRANSACTION_TIMEOUT : (_opts$attempts2 = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts2 !== void 0 ? _opts$attempts2 : DEFAULT_GET_TRANSACTION_TIMEOUT; + attempt = 1; + case 2: + if (!(attempt < maxAttempts)) { + _context8.next = 13; + break; + } + _context8.next = 5; + return this.getTransaction(hash); + case 5: + foundInfo = _context8.sent; + if (!(foundInfo.status !== _api.Api.GetTransactionStatus.NOT_FOUND)) { + _context8.next = 8; + break; + } + return _context8.abrupt("return", foundInfo); + case 8: + _context8.next = 10; + return _utils.Utils.sleep(((_opts$sleepStrategy = opts === null || opts === void 0 ? void 0 : opts.sleepStrategy) !== null && _opts$sleepStrategy !== void 0 ? _opts$sleepStrategy : BasicSleepStrategy)(attempt)); + case 10: + attempt++; + _context8.next = 2; + break; + case 13: + return _context8.abrupt("return", foundInfo); + case 14: + case "end": + return _context8.stop(); + } + }, _callee8, this); + })); + function pollTransaction(_x6, _x7) { + return _pollTransaction.apply(this, arguments); + } + return pollTransaction; + }()) + }, { + key: "getTransaction", + value: (function () { + var _getTransaction2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee9(hash) { + return _regeneratorRuntime().wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + return _context9.abrupt("return", this._getTransaction(hash).then(function (raw) { + var foundInfo = {}; + if (raw.status !== _api.Api.GetTransactionStatus.NOT_FOUND) { + Object.assign(foundInfo, (0, _parsers.parseTransactionInfo)(raw)); + } + var result = _objectSpread({ + status: raw.status, + txHash: hash, + latestLedger: raw.latestLedger, + latestLedgerCloseTime: raw.latestLedgerCloseTime, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTime: raw.oldestLedgerCloseTime + }, foundInfo); + return result; + })); + case 1: + case "end": + return _context9.stop(); + } + }, _callee9, this); + })); + function getTransaction(_x8) { + return _getTransaction2.apply(this, arguments); + } + return getTransaction; + }()) + }, { + key: "_getTransaction", + value: function () { + var _getTransaction3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee10(hash) { + return _regeneratorRuntime().wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + return _context10.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getTransaction', { + hash: hash + })); + case 1: + case "end": + return _context10.stop(); + } + }, _callee10, this); + })); + function _getTransaction(_x9) { + return _getTransaction3.apply(this, arguments); + } + return _getTransaction; + }() + }, { + key: "getTransactions", + value: (function () { + var _getTransactions2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee11(request) { + return _regeneratorRuntime().wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + return _context11.abrupt("return", this._getTransactions(request).then(function (raw) { + var result = { + transactions: raw.transactions.map(_parsers.parseRawTransactions), + latestLedger: raw.latestLedger, + latestLedgerCloseTimestamp: raw.latestLedgerCloseTimestamp, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTimestamp: raw.oldestLedgerCloseTimestamp, + cursor: raw.cursor + }; + return result; + })); + case 1: + case "end": + return _context11.stop(); + } + }, _callee11, this); + })); + function getTransactions(_x10) { + return _getTransactions2.apply(this, arguments); + } + return getTransactions; + }()) + }, { + key: "_getTransactions", + value: function () { + var _getTransactions3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee12(request) { + return _regeneratorRuntime().wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + return _context12.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getTransactions', request)); + case 1: + case "end": + return _context12.stop(); + } + }, _callee12, this); + })); + function _getTransactions(_x11) { + return _getTransactions3.apply(this, arguments); + } + return _getTransactions; + }() + }, { + key: "getEvents", + value: (function () { + var _getEvents2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee13(request) { + return _regeneratorRuntime().wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + return _context13.abrupt("return", this._getEvents(request).then(_parsers.parseRawEvents)); + case 1: + case "end": + return _context13.stop(); + } + }, _callee13, this); + })); + function getEvents(_x12) { + return _getEvents2.apply(this, arguments); + } + return getEvents; + }()) + }, { + key: "_getEvents", + value: function () { + var _getEvents3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee14(request) { + var _request$filters; + return _regeneratorRuntime().wrap(function _callee14$(_context14) { + while (1) switch (_context14.prev = _context14.next) { + case 0: + return _context14.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getEvents', _objectSpread(_objectSpread({ + filters: (_request$filters = request.filters) !== null && _request$filters !== void 0 ? _request$filters : [], + pagination: _objectSpread(_objectSpread({}, request.cursor && { + cursor: request.cursor + }), request.limit && { + limit: request.limit + }) + }, request.startLedger && { + startLedger: request.startLedger + }), request.endLedger && { + endLedger: request.endLedger + }))); + case 1: + case "end": + return _context14.stop(); + } + }, _callee14, this); + })); + function _getEvents(_x13) { + return _getEvents3.apply(this, arguments); + } + return _getEvents; + }() + }, { + key: "getNetwork", + value: (function () { + var _getNetwork = _asyncToGenerator(_regeneratorRuntime().mark(function _callee15() { + return _regeneratorRuntime().wrap(function _callee15$(_context15) { + while (1) switch (_context15.prev = _context15.next) { + case 0: + return _context15.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getNetwork')); + case 1: + case "end": + return _context15.stop(); + } + }, _callee15, this); + })); + function getNetwork() { + return _getNetwork.apply(this, arguments); + } + return getNetwork; + }()) + }, { + key: "getLatestLedger", + value: (function () { + var _getLatestLedger = _asyncToGenerator(_regeneratorRuntime().mark(function _callee16() { + return _regeneratorRuntime().wrap(function _callee16$(_context16) { + while (1) switch (_context16.prev = _context16.next) { + case 0: + return _context16.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getLatestLedger')); + case 1: + case "end": + return _context16.stop(); + } + }, _callee16, this); + })); + function getLatestLedger() { + return _getLatestLedger.apply(this, arguments); + } + return getLatestLedger; + }()) + }, { + key: "simulateTransaction", + value: (function () { + var _simulateTransaction2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee17(tx, addlResources) { + return _regeneratorRuntime().wrap(function _callee17$(_context17) { + while (1) switch (_context17.prev = _context17.next) { + case 0: + return _context17.abrupt("return", this._simulateTransaction(tx, addlResources).then(_parsers.parseRawSimulation)); + case 1: + case "end": + return _context17.stop(); + } + }, _callee17, this); + })); + function simulateTransaction(_x14, _x15) { + return _simulateTransaction2.apply(this, arguments); + } + return simulateTransaction; + }()) + }, { + key: "_simulateTransaction", + value: function () { + var _simulateTransaction3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee18(transaction, addlResources) { + return _regeneratorRuntime().wrap(function _callee18$(_context18) { + while (1) switch (_context18.prev = _context18.next) { + case 0: + return _context18.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'simulateTransaction', _objectSpread({ + transaction: transaction.toXDR() + }, addlResources !== undefined && { + resourceConfig: { + instructionLeeway: addlResources.cpuInstructions + } + }))); + case 1: + case "end": + return _context18.stop(); + } + }, _callee18, this); + })); + function _simulateTransaction(_x16, _x17) { + return _simulateTransaction3.apply(this, arguments); + } + return _simulateTransaction; + }() + }, { + key: "prepareTransaction", + value: (function () { + var _prepareTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee19(tx) { + var simResponse; + return _regeneratorRuntime().wrap(function _callee19$(_context19) { + while (1) switch (_context19.prev = _context19.next) { + case 0: + _context19.next = 2; + return this.simulateTransaction(tx); + case 2: + simResponse = _context19.sent; + if (!_api.Api.isSimulationError(simResponse)) { + _context19.next = 5; + break; + } + throw new Error(simResponse.error); + case 5: + return _context19.abrupt("return", (0, _transaction.assembleTransaction)(tx, simResponse).build()); + case 6: + case "end": + return _context19.stop(); + } + }, _callee19, this); + })); + function prepareTransaction(_x18) { + return _prepareTransaction.apply(this, arguments); + } + return prepareTransaction; + }()) + }, { + key: "sendTransaction", + value: (function () { + var _sendTransaction2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee20(transaction) { + return _regeneratorRuntime().wrap(function _callee20$(_context20) { + while (1) switch (_context20.prev = _context20.next) { + case 0: + return _context20.abrupt("return", this._sendTransaction(transaction).then(_parsers.parseRawSendTransaction)); + case 1: + case "end": + return _context20.stop(); + } + }, _callee20, this); + })); + function sendTransaction(_x19) { + return _sendTransaction2.apply(this, arguments); + } + return sendTransaction; + }()) + }, { + key: "_sendTransaction", + value: function () { + var _sendTransaction3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee21(transaction) { + return _regeneratorRuntime().wrap(function _callee21$(_context21) { + while (1) switch (_context21.prev = _context21.next) { + case 0: + return _context21.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'sendTransaction', { + transaction: transaction.toXDR() + })); + case 1: + case "end": + return _context21.stop(); + } + }, _callee21, this); + })); + function _sendTransaction(_x20) { + return _sendTransaction3.apply(this, arguments); + } + return _sendTransaction; + }() + }, { + key: "requestAirdrop", + value: (function () { + var _requestAirdrop = _asyncToGenerator(_regeneratorRuntime().mark(function _callee22(address, friendbotUrl) { + var account, response, meta, txMeta, sequence, _error$response, _error$response$detai; + return _regeneratorRuntime().wrap(function _callee22$(_context22) { + while (1) switch (_context22.prev = _context22.next) { + case 0: + account = typeof address === 'string' ? address : address.accountId(); + _context22.t0 = friendbotUrl; + if (_context22.t0) { + _context22.next = 6; + break; + } + _context22.next = 5; + return this.getNetwork(); + case 5: + _context22.t0 = _context22.sent.friendbotUrl; + case 6: + friendbotUrl = _context22.t0; + if (friendbotUrl) { + _context22.next = 9; + break; + } + throw new Error('No friendbot URL configured for current network'); + case 9: + _context22.prev = 9; + _context22.next = 12; + return _axios.default.post("".concat(friendbotUrl, "?addr=").concat(encodeURIComponent(account))); + case 12: + response = _context22.sent; + if (response.data.result_meta_xdr) { + _context22.next = 22; + break; + } + _context22.next = 16; + return this.getTransaction(response.data.hash); + case 16: + txMeta = _context22.sent; + if (!(txMeta.status !== _api.Api.GetTransactionStatus.SUCCESS)) { + _context22.next = 19; + break; + } + throw new Error("Funding account ".concat(address, " failed")); + case 19: + meta = txMeta.resultMetaXdr; + _context22.next = 23; + break; + case 22: + meta = _stellarBase.xdr.TransactionMeta.fromXDR(response.data.result_meta_xdr, 'base64'); + case 23: + sequence = findCreatedAccountSequenceInTransactionMeta(meta); + return _context22.abrupt("return", new _stellarBase.Account(account, sequence)); + case 27: + _context22.prev = 27; + _context22.t1 = _context22["catch"](9); + if (!(((_error$response = _context22.t1.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 400)) { + _context22.next = 32; + break; + } + if (!((_error$response$detai = _context22.t1.response.detail) !== null && _error$response$detai !== void 0 && _error$response$detai.includes('createAccountAlreadyExist'))) { + _context22.next = 32; + break; + } + return _context22.abrupt("return", this.getAccount(account)); + case 32: + throw _context22.t1; + case 33: + case "end": + return _context22.stop(); + } + }, _callee22, this, [[9, 27]]); + })); + function requestAirdrop(_x21, _x22) { + return _requestAirdrop.apply(this, arguments); + } + return requestAirdrop; + }()) + }, { + key: "getFeeStats", + value: (function () { + var _getFeeStats = _asyncToGenerator(_regeneratorRuntime().mark(function _callee23() { + return _regeneratorRuntime().wrap(function _callee23$(_context23) { + while (1) switch (_context23.prev = _context23.next) { + case 0: + return _context23.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getFeeStats')); + case 1: + case "end": + return _context23.stop(); + } + }, _callee23, this); + })); + function getFeeStats() { + return _getFeeStats.apply(this, arguments); + } + return getFeeStats; + }()) + }, { + key: "getVersionInfo", + value: (function () { + var _getVersionInfo = _asyncToGenerator(_regeneratorRuntime().mark(function _callee24() { + return _regeneratorRuntime().wrap(function _callee24$(_context24) { + while (1) switch (_context24.prev = _context24.next) { + case 0: + return _context24.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getVersionInfo')); + case 1: + case "end": + return _context24.stop(); + } + }, _callee24, this); + })); + function getVersionInfo() { + return _getVersionInfo.apply(this, arguments); + } + return getVersionInfo; + }()) + }, { + key: "getSACBalance", + value: (function () { + var _getSACBalance = _asyncToGenerator(_regeneratorRuntime().mark(function _callee25(contractId, sac, networkPassphrase) { + var passphrase, sacId, key, ledgerKey, response, _response$entries$2, lastModifiedLedgerSeq, liveUntilLedgerSeq, val, entry; + return _regeneratorRuntime().wrap(function _callee25$(_context25) { + while (1) switch (_context25.prev = _context25.next) { + case 0: + if (_stellarBase.StrKey.isValidContract(contractId)) { + _context25.next = 2; + break; + } + throw new TypeError("expected contract ID, got ".concat(contractId)); + case 2: + if (!(networkPassphrase !== null && networkPassphrase !== void 0)) { + _context25.next = 6; + break; + } + _context25.t0 = networkPassphrase; + _context25.next = 9; + break; + case 6: + _context25.next = 8; + return this.getNetwork().then(function (n) { + return n.passphrase; + }); + case 8: + _context25.t0 = _context25.sent; + case 9: + passphrase = _context25.t0; + sacId = sac.contractId(passphrase); + key = _stellarBase.xdr.ScVal.scvVec([(0, _stellarBase.nativeToScVal)("Balance", { + type: "symbol" + }), (0, _stellarBase.nativeToScVal)(contractId, { + type: "address" + })]); + ledgerKey = _stellarBase.xdr.LedgerKey.contractData(new _stellarBase.xdr.LedgerKeyContractData({ + contract: new _stellarBase.Address(sacId).toScAddress(), + durability: _stellarBase.xdr.ContractDataDurability.persistent(), + key: key + })); + _context25.next = 15; + return this.getLedgerEntries(ledgerKey); + case 15: + response = _context25.sent; + if (!(response.entries.length === 0)) { + _context25.next = 18; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 18: + _response$entries$2 = response.entries[0], lastModifiedLedgerSeq = _response$entries$2.lastModifiedLedgerSeq, liveUntilLedgerSeq = _response$entries$2.liveUntilLedgerSeq, val = _response$entries$2.val; + if (!(val.switch().value !== _stellarBase.xdr.LedgerEntryType.contractData().value)) { + _context25.next = 21; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 21: + entry = (0, _stellarBase.scValToNative)(val.contractData().val()); + return _context25.abrupt("return", { + latestLedger: response.latestLedger, + balanceEntry: { + liveUntilLedgerSeq: liveUntilLedgerSeq, + lastModifiedLedgerSeq: lastModifiedLedgerSeq, + amount: entry.amount.toString(), + authorized: entry.authorized, + clawback: entry.clawback + } + }); + case 23: + case "end": + return _context25.stop(); + } + }, _callee25, this); + })); + function getSACBalance(_x23, _x24, _x25) { + return _getSACBalance.apply(this, arguments); + } + return getSACBalance; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/transaction.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/transaction.d.ts new file mode 100644 index 000000000..c20ee31ad --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/transaction.d.ts @@ -0,0 +1,21 @@ +import { FeeBumpTransaction, Transaction, TransactionBuilder } from '@stellar/stellar-base'; +import { Api } from './api'; +/** + * Combines the given raw transaction alongside the simulation results. + * If the given transaction already has authorization entries in a host + * function invocation (see {@link Operation.invokeHostFunction}), **the + * simulation entries are ignored**. + * + * If the given transaction already has authorization entries in a host function + * invocation (see {@link Operation.invokeHostFunction}), **the simulation + * entries are ignored**. + * + * @param {Transaction|FeeBumpTransaction} raw the initial transaction, w/o simulation applied + * @param {Api.SimulateTransactionResponse|Api.RawSimulateTransactionResponse} simulation the Soroban RPC simulation result (see {@link module:rpc.Server#simulateTransaction}) + * @returns {TransactionBuilder} a new, cloned transaction with the proper auth and resource (fee, footprint) simulation data applied + * + * @memberof module:rpc + * @see {@link module:rpc.Server#simulateTransaction} + * @see {@link module:rpc.Server#prepareTransaction} + */ +export declare function assembleTransaction(raw: Transaction | FeeBumpTransaction, simulation: Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse): TransactionBuilder; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/transaction.js b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/transaction.js new file mode 100644 index 000000000..51bc94e7b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/transaction.js @@ -0,0 +1,53 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.assembleTransaction = assembleTransaction; +var _stellarBase = require("@stellar/stellar-base"); +var _api = require("./api"); +var _parsers = require("./parsers"); +function isSorobanTransaction(tx) { + if (tx.operations.length !== 1) { + return false; + } + switch (tx.operations[0].type) { + case 'invokeHostFunction': + case 'extendFootprintTtl': + case 'restoreFootprint': + return true; + default: + return false; + } +} +function assembleTransaction(raw, simulation) { + if ('innerTransaction' in raw) { + return assembleTransaction(raw.innerTransaction, simulation); + } + if (!isSorobanTransaction(raw)) { + throw new TypeError('unsupported transaction: must contain exactly one ' + 'invokeHostFunction, extendFootprintTtl, or restoreFootprint ' + 'operation'); + } + var success = (0, _parsers.parseRawSimulation)(simulation); + if (!_api.Api.isSimulationSuccess(success)) { + throw new Error("simulation incorrect: ".concat(JSON.stringify(success))); + } + var classicFeeNum = parseInt(raw.fee) || 0; + var minResourceFeeNum = parseInt(success.minResourceFee) || 0; + var txnBuilder = _stellarBase.TransactionBuilder.cloneFrom(raw, { + fee: (classicFeeNum + minResourceFeeNum).toString(), + sorobanData: success.transactionData.build(), + networkPassphrase: raw.networkPassphrase + }); + if (raw.operations[0].type === 'invokeHostFunction') { + var _invokeOp$auth; + txnBuilder.clearOperations(); + var invokeOp = raw.operations[0]; + var existingAuth = (_invokeOp$auth = invokeOp.auth) !== null && _invokeOp$auth !== void 0 ? _invokeOp$auth : []; + txnBuilder.addOperation(_stellarBase.Operation.invokeHostFunction({ + source: invokeOp.source, + func: invokeOp.func, + auth: existingAuth.length > 0 ? existingAuth : success.result.auth + })); + } + return txnBuilder; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/utils.d.ts new file mode 100644 index 000000000..e1cc19c4b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/utils.d.ts @@ -0,0 +1 @@ +export declare function hasOwnProperty(obj: X, prop: Y): obj is X & Record; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/utils.js b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/utils.js new file mode 100644 index 000000000..e2148d9bd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/rpc/utils.js @@ -0,0 +1,9 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.hasOwnProperty = hasOwnProperty; +function hasOwnProperty(obj, prop) { + return obj.hasOwnProperty(prop); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/stellartoml/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/stellartoml/index.d.ts new file mode 100644 index 000000000..9309f1dfd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/stellartoml/index.d.ts @@ -0,0 +1,132 @@ +import { Networks } from "@stellar/stellar-base"; +/** @module StellarToml */ +/** + * The maximum size of stellar.toml file, in bytes + * @constant {number} + * @default 102400 + */ +export declare const STELLAR_TOML_MAX_SIZE: number; +/** + * Resolver allows resolving `stellar.toml` files. + * @memberof module:StellarToml + * @hideconstructor + */ +export declare class Resolver { + /** + * Returns a parsed `stellar.toml` file for a given domain. + * @see {@link https://developers.stellar.org/docs/tokens/publishing-asset-info | Stellar.toml doc} + * + * @param {string} domain Domain to get stellar.toml file for + * @param {object} [opts] Options object + * @param {boolean} [opts.allowHttp=false] - Allow connecting to http servers. This must be set to false in production deployments! + * @param {number} [opts.timeout=0] - Allow a timeout. Allows user to avoid nasty lag due to TOML resolve issue. + * @returns {Promise} A `Promise` that resolves to the parsed stellar.toml object + * + * @example + * StellarSdk.StellarToml.Resolver.resolve('acme.com') + * .then(stellarToml => { + * // stellarToml in an object representing domain stellar.toml file. + * }) + * .catch(error => { + * // stellar.toml does not exist or is invalid + * }); + */ + static resolve(domain: string, opts?: Api.StellarTomlResolveOptions): Promise; +} +export declare namespace Api { + interface StellarTomlResolveOptions { + allowHttp?: boolean; + timeout?: number; + allowedRedirects?: number; + } + type Url = string; + type PublicKey = string; + type ISODateTime = string; + interface Documentation { + ORG_NAME?: string; + ORG_DBA?: string; + ORG_URL?: Url; + ORG_PHONE_NUMBER?: string; + ORG_LOGO?: Url; + ORG_LICENSE_NUMBER?: string; + ORG_LICENSING_AUTHORITY?: string; + ORG_LICENSE_TYPE?: string; + ORG_DESCRIPTION?: string; + ORG_PHYSICAL_ADDRESS?: string; + ORG_PHYSICAL_ADDRESS_ATTESTATION?: string; + ORG_PHONE_NUMBER_ATTESTATION?: string; + ORG_OFFICIAL_EMAIL?: string; + ORG_SUPPORT_EMAIL?: string; + ORG_KEYBASE?: string; + ORG_TWITTER?: string; + ORG_GITHUB?: string; + [key: string]: unknown; + } + interface Principal { + name: string; + email: string; + github?: string; + keybase?: string; + telegram?: string; + twitter?: string; + id_photo_hash?: string; + verification_photo_hash?: string; + [key: string]: unknown; + } + interface Currency { + code?: string; + code_template?: string; + issuer?: PublicKey; + display_decimals?: number; + status?: "live" | "dead" | "test" | "private"; + name?: string; + desc?: string; + conditions?: string; + fixed_number?: number; + max_number?: number; + is_asset_anchored?: boolean; + anchor_asset_type?: "fiat" | "crypto" | "nft" | "stock" | "bond" | "commodity" | "realestate" | "other"; + anchor_asset?: string; + attestation_of_reserve?: Url; + attestation_of_reserve_amount?: string; + attestation_of_reserve_last_audit?: ISODateTime; + is_unlimited?: boolean; + redemption_instructions?: string; + image?: Url; + regulated?: boolean; + collateral_addresses?: string[]; + collateral_address_messages?: string[]; + collateral_address_signatures?: string[]; + approval_server?: Url; + approval_criteria?: string; + [key: string]: unknown; + } + interface Validator { + ALIAS?: string; + DISPLAY_NAME?: string; + PUBLIC_KEY?: PublicKey; + HOST?: string; + HISTORY?: Url; + [key: string]: unknown; + } + interface StellarToml { + VERSION?: string; + ACCOUNTS?: PublicKey[]; + NETWORK_PASSPHRASE?: Networks; + TRANSFER_SERVER_SEP0024?: Url; + TRANSFER_SERVER?: Url; + KYC_SERVER?: Url; + WEB_AUTH_ENDPOINT?: Url; + FEDERATION_SERVER?: Url; + SIGNING_KEY?: PublicKey; + HORIZON_URL?: Url; + URI_REQUEST_SIGNING_KEY?: PublicKey; + DIRECT_PAYMENT_SERVER?: Url; + ANCHOR_QUOTE_SERVER?: Url; + DOCUMENTATION?: Documentation; + PRINCIPALS?: Principal[]; + CURRENCIES?: Currency[]; + VALIDATORS?: Validator[]; + [key: string]: unknown; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/stellartoml/index.js b/node_modules/@stellar/stellar-sdk/lib/minimal/stellartoml/index.js new file mode 100644 index 000000000..4b5aa2452 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/stellartoml/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.STELLAR_TOML_MAX_SIZE = exports.Resolver = exports.Api = void 0; +var _toml = _interopRequireDefault(require("toml")); +var _httpClient = require("../http-client"); +var _config = require("../config"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var STELLAR_TOML_MAX_SIZE = exports.STELLAR_TOML_MAX_SIZE = 100 * 1024; +var CancelToken = _httpClient.httpClient.CancelToken; +var Resolver = exports.Resolver = function () { + function Resolver() { + _classCallCheck(this, Resolver); + } + return _createClass(Resolver, null, [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(domain) { + var _opts$allowedRedirect; + var opts, + allowHttp, + timeout, + protocol, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 1 && _args[1] !== undefined ? _args[1] : {}; + allowHttp = typeof opts.allowHttp === "undefined" ? _config.Config.isAllowHttp() : opts.allowHttp; + timeout = typeof opts.timeout === "undefined" ? _config.Config.getTimeout() : opts.timeout; + protocol = allowHttp ? "http" : "https"; + return _context.abrupt("return", _httpClient.httpClient.get("".concat(protocol, "://").concat(domain, "/.well-known/stellar.toml"), { + maxRedirects: (_opts$allowedRedirect = opts.allowedRedirects) !== null && _opts$allowedRedirect !== void 0 ? _opts$allowedRedirect : 0, + maxContentLength: STELLAR_TOML_MAX_SIZE, + cancelToken: timeout ? new CancelToken(function (cancel) { + return setTimeout(function () { + return cancel("timeout of ".concat(timeout, "ms exceeded")); + }, timeout); + }) : undefined, + timeout: timeout + }).then(function (response) { + try { + var tomlObject = _toml.default.parse(response.data); + return Promise.resolve(tomlObject); + } catch (e) { + return Promise.reject(new Error("stellar.toml is invalid - Parsing error on line ".concat(e.line, ", column ").concat(e.column, ": ").concat(e.message))); + } + }).catch(function (err) { + if (err.message.match(/^maxContentLength size/)) { + throw new Error("stellar.toml file exceeds allowed size of ".concat(STELLAR_TOML_MAX_SIZE)); + } else { + throw err; + } + })); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + function resolve(_x) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }]); +}(); +var Api; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/utils.d.ts new file mode 100644 index 000000000..68cf6c0c2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/utils.d.ts @@ -0,0 +1,20 @@ +import { Transaction } from "@stellar/stellar-base"; +/** + * Miscellaneous utilities. + * + * @hideconstructor + */ +export declare class Utils { + /** + * Verifies if the current date is within the transaction's timebounds + * + * @param {Transaction} transaction The transaction whose timebounds will be validated. + * @param {number} [gracePeriod=0] An additional window of time that should be considered valid on either end of the transaction's time range. + * + * @returns {boolean} Returns true if the current time is within the transaction's [minTime, maxTime] range. + * + * @static + */ + static validateTimebounds(transaction: Transaction, gracePeriod?: number): boolean; + static sleep(ms: number): Promise; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/utils.js b/node_modules/@stellar/stellar-sdk/lib/minimal/utils.js new file mode 100644 index 000000000..3609eac76 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/utils.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Utils = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Utils = exports.Utils = function () { + function Utils() { + _classCallCheck(this, Utils); + } + return _createClass(Utils, null, [{ + key: "validateTimebounds", + value: function validateTimebounds(transaction) { + var gracePeriod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + if (!transaction.timeBounds) { + return false; + } + var now = Math.floor(Date.now() / 1000); + var _transaction$timeBoun = transaction.timeBounds, + minTime = _transaction$timeBoun.minTime, + maxTime = _transaction$timeBoun.maxTime; + return now >= Number.parseInt(minTime, 10) - gracePeriod && now <= Number.parseInt(maxTime, 10) + gracePeriod; + } + }, { + key: "sleep", + value: function sleep(ms) { + return new Promise(function (resolve) { + return setTimeout(resolve, ms); + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/errors.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/errors.d.ts new file mode 100644 index 000000000..0e59f59ee --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/errors.d.ts @@ -0,0 +1,13 @@ +/** + * InvalidChallengeError is raised when a challenge transaction does not meet + * the requirements for a SEP-10 challenge transaction (for example, a non-zero + * sequence number). + * @memberof module:WebAuth + * @category Errors + * + * @param {string} message Human-readable error message. + */ +export declare class InvalidChallengeError extends Error { + __proto__: InvalidChallengeError; + constructor(message: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/errors.js b/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/errors.js new file mode 100644 index 000000000..2542a4449 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/errors.js @@ -0,0 +1,36 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.InvalidChallengeError = void 0; +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var InvalidChallengeError = exports.InvalidChallengeError = function (_Error) { + function InvalidChallengeError(message) { + var _this; + _classCallCheck(this, InvalidChallengeError); + var trueProto = (this instanceof InvalidChallengeError ? this.constructor : void 0).prototype; + _this = _callSuper(this, InvalidChallengeError, [message]); + _this.__proto__ = trueProto; + _this.constructor = InvalidChallengeError; + _this.name = "InvalidChallengeError"; + return _this; + } + _inherits(InvalidChallengeError, _Error); + return _createClass(InvalidChallengeError); +}(_wrapNativeSuper(Error)); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/index.d.ts new file mode 100644 index 000000000..e63282485 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/index.d.ts @@ -0,0 +1,2 @@ +export * from './utils'; +export { InvalidChallengeError } from './errors'; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/index.js b/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/index.js new file mode 100644 index 000000000..a0ee4d041 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/index.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + InvalidChallengeError: true +}; +Object.defineProperty(exports, "InvalidChallengeError", { + enumerable: true, + get: function get() { + return _errors.InvalidChallengeError; + } +}); +var _utils = require("./utils"); +Object.keys(_utils).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _utils[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utils[key]; + } + }); +}); +var _errors = require("./errors"); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/utils.d.ts new file mode 100644 index 000000000..a725201df --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/utils.d.ts @@ -0,0 +1,307 @@ +/** + * Stellar Web Authentication + * @module WebAuth + * @see {@link https://stellar.org/protocol-10 | SEP-10 Specification} + */ +import { FeeBumpTransaction, Keypair, Transaction } from "@stellar/stellar-base"; +import { ServerApi } from "../horizon/server_api"; +/** + * Returns a valid {@link https://stellar.org/protocol/sep-10 | SEP-10} + * challenge transaction which you can use for Stellar Web Authentication. + * + * @param {Keypair} serverKeypair Keypair for server's signing account. + * @param {string} clientAccountID The stellar account (G...) or muxed account + * (M...) that the wallet wishes to authenticate with the server. + * @param {string} homeDomain The fully qualified domain name of the service + * requiring authentication + * @param {number} [timeout=300] Challenge duration (default to 5 minutes). + * @param {string} networkPassphrase The network passphrase. If you pass this + * argument then timeout is required. + * @param {string} webAuthDomain The fully qualified domain name of the service + * issuing the challenge. + * @param {string} [memo] The memo to attach to the challenge transaction. The + * memo must be of type `id`. If the `clientaccountID` is a muxed account, + * memos cannot be used. + * @param {string} [clientDomain] The fully qualified domain of the client + * requesting the challenge. Only necessary when the the 'client_domain' + * parameter is passed. + * @param {string} [clientSigningKey] The public key assigned to the SIGNING_KEY + * attribute specified on the stellar.toml hosted on the client domain. Only + * necessary when the 'client_domain' parameter is passed. + * @returns {string} A base64 encoded string of the raw TransactionEnvelope xdr + * struct for the transaction. + * @throws {Error} Will throw if `clientAccountID is a muxed account, and `memo` + * is present. + * @throws {Error} Will throw if `clientDomain` is provided, but + * `clientSigningKey` is missing + * + * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth} + * + * @example + * import { Keypair, Networks, WebAuth } from 'stellar-sdk' + * + * let serverKeyPair = Keypair.fromSecret("server-secret") + * let challenge = WebAuth.buildChallengeTx( + * serverKeyPair, + * "client-stellar-account-id", + * "stellar.org", + * 300, + * Networks.TESTNET); + */ +export declare function buildChallengeTx(serverKeypair: Keypair, clientAccountID: string, homeDomain: string, timeout: number | undefined, networkPassphrase: string, webAuthDomain: string, memo?: string | null, clientDomain?: string | null, clientSigningKey?: string | null): string; +/** + * A parsed and validated challenge transaction, and some of its constituent details. + * @memberof module:WebAuth + */ +export type ChallengeTxDetails = { + /** The challenge transaction. */ + tx: Transaction; + /** The Stellar public key (master key) used to sign the Manage Data operation. */ + clientAccountId: string; + /** The matched home domain. */ + matchedHomeDomain: string; + /** The memo attached to the transaction, which will be null if not present */ + memo?: string; +}; +/** + * Reads a SEP-10 challenge transaction and returns the decoded transaction and + * client account ID contained within. + * + * It also verifies that the transaction has been signed by the server. + * + * It does not verify that the transaction has been signed by the client or that + * any signatures other than the server's on the transaction are valid. Use one + * of the following functions to completely verify the transaction: + * + * - {@link module:WebAuth~verifyChallengeTxThreshold} + * - {@link module:WebAuth~verifyChallengeTxSigners} + * + * @param {string} challengeTx SEP0010 challenge transaction in base64. + * @param {string} serverAccountID The server's stellar account (public key). + * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF + * Network ; September 2015' (see {@link Networks}) + * @param {string | Array.} homeDomains The home domain that is expected + * to be included in the first Manage Data operation's string key. If an + * array is provided, one of the domain names in the array must match. + * @param {string} webAuthDomain The home domain that is expected to be included + * as the value of the Manage Data operation with the 'web_auth_domain' key. + * If no such operation is included, this parameter is not used. + * @returns {module:WebAuth.ChallengeTxDetails} The actual transaction and the + * Stellar public key (master key) used to sign the Manage Data operation, + * the matched home domain, and the memo attached to the transaction, which + * will be null if not present. + * + * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth} + */ +export declare function readChallengeTx(challengeTx: string, serverAccountID: string, networkPassphrase: string, homeDomains: string | string[], webAuthDomain: string): { + tx: Transaction; + clientAccountID: string; + matchedHomeDomain: string; + memo: string | null; +}; +/** + * Verifies that for a SEP-10 challenge transaction all signatures on the + * transaction are accounted for and that the signatures meet a threshold on an + * account. A transaction is verified if it is signed by the server account, and + * all other signatures match a signer that has been provided as an argument, + * and those signatures meet a threshold on the account. + * + * Signers that are not prefixed as an address/account ID strkey (G...) will be + * ignored. + * + * Errors will be raised if: + * - The transaction is invalid according to + * {@link module:WebAuth~readChallengeTx}. + * - No client signatures are found on the transaction. + * - One or more signatures in the transaction are not identifiable as the + * server account or one of the signers provided in the arguments. + * - The signatures are all valid but do not meet the threshold. + * + * @param {string} challengeTx SEP0010 challenge transaction in base64. + * @param {string} serverAccountID The server's stellar account (public key). + * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF + * Network ; September 2015' (see {@link Networks}). + * @param {number} threshold The required signatures threshold for verifying + * this transaction. + * @param {Array.} signerSummary a map of all + * authorized signers to their weights. It's used to validate if the + * transaction signatures have met the given threshold. + * @param {string | Array.} homeDomains The home domain(s) that should + * be included in the first Manage Data operation's string key. Required in + * verifyChallengeTxSigners() => readChallengeTx(). + * @param {string} webAuthDomain The home domain that is expected to be included + * as the value of the Manage Data operation with the 'web_auth_domain' key, + * if present. Used in verifyChallengeTxSigners() => readChallengeTx(). + * @returns {Array.} The list of signers public keys that have signed + * the transaction, excluding the server account ID, given that the threshold + * was met. + * @throws {module:WebAuth.InvalidChallengeError} Will throw if the collective + * weight of the transaction's signers does not meet the necessary threshold + * to verify this transaction. + * + * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth} + * + * @example + * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk'; + * + * const serverKP = Keypair.random(); + * const clientKP1 = Keypair.random(); + * const clientKP2 = Keypair.random(); + * + * // Challenge, possibly built in the server side + * const challenge = WebAuth.buildChallengeTx( + * serverKP, + * clientKP1.publicKey(), + * "SDF", + * 300, + * Networks.TESTNET + * ); + * + * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client + * + * // Transaction gathered from a challenge, possibly from the client side + * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET); + * transaction.sign(clientKP1, clientKP2); + * const signedChallenge = transaction + * .toEnvelope() + * .toXDR("base64") + * .toString(); + * + * // Defining the threshold and signerSummary + * const threshold = 3; + * const signerSummary = [ + * { + * key: this.clientKP1.publicKey(), + * weight: 1, + * }, + * { + * key: this.clientKP2.publicKey(), + * weight: 2, + * }, + * ]; + * + * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()] + * WebAuth.verifyChallengeTxThreshold( + * signedChallenge, + * serverKP.publicKey(), + * Networks.TESTNET, + * threshold, + * signerSummary + * ); + */ +export declare function verifyChallengeTxThreshold(challengeTx: string, serverAccountID: string, networkPassphrase: string, threshold: number, signerSummary: ServerApi.AccountRecordSigners[], homeDomains: string | string[], webAuthDomain: string): string[]; +/** + * Verifies that for a SEP 10 challenge transaction all signatures on the + * transaction are accounted for. A transaction is verified if it is signed by + * the server account, and all other signatures match a signer that has been + * provided as an argument (as the accountIDs list). Additional signers can be + * provided that do not have a signature, but all signatures must be matched to + * a signer (accountIDs) for verification to succeed. If verification succeeds, + * a list of signers that were found is returned, not including the server + * account ID. + * + * Signers that are not prefixed as an address/account ID strkey (G...) will be + * ignored. + * + * Errors will be raised if: + * - The transaction is invalid according to + * {@link module:WebAuth~readChallengeTx}. + * - No client signatures are found on the transaction. + * - One or more signatures in the transaction are not identifiable as the + * server account or one of the signers provided in the arguments. + * + * @param {string} challengeTx SEP0010 challenge transaction in base64. + * @param {string} serverAccountID The server's stellar account (public key). + * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF + * Network ; September 2015' (see {@link Networks}). + * @param {Array.} signers The signers public keys. This list should + * contain the public keys for all signers that have signed the transaction. + * @param {string | Array.} [homeDomains] The home domain(s) that should + * be included in the first Manage Data operation's string key. Required in + * readChallengeTx(). + * @param {string} webAuthDomain The home domain that is expected to be included + * as the value of the Manage Data operation with the 'web_auth_domain' key, + * if present. Used in readChallengeTx(). + * @returns {Array.} The list of signers public keys that have signed + * the transaction, excluding the server account ID. + * + * @see {@link https://stellar.org/protocol/sep-10|SEP-10: Stellar Web Auth} + * @example + * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk'; + * + * const serverKP = Keypair.random(); + * const clientKP1 = Keypair.random(); + * const clientKP2 = Keypair.random(); + * + * // Challenge, possibly built in the server side + * const challenge = WebAuth.buildChallengeTx( + * serverKP, + * clientKP1.publicKey(), + * "SDF", + * 300, + * Networks.TESTNET + * ); + * + * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client + * + * // Transaction gathered from a challenge, possibly from the client side + * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET); + * transaction.sign(clientKP1, clientKP2); + * const signedChallenge = transaction + * .toEnvelope() + * .toXDR("base64") + * .toString(); + * + * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()] + * WebAuth.verifyChallengeTxSigners( + * signedChallenge, + * serverKP.publicKey(), + * Networks.TESTNET, + * threshold, + * [clientKP1.publicKey(), clientKP2.publicKey()] + * ); + */ +export declare function verifyChallengeTxSigners(challengeTx: string, serverAccountID: string, networkPassphrase: string, signers: string[], homeDomains: string | string[], webAuthDomain: string): string[]; +/** + * Verifies if a transaction was signed by the given account id. + * + * @param {Transaction | FeeBumpTransaction} transaction The signed transaction. + * @param {string} accountID The signer's public key. + * @returns {boolean} Whether or not `accountID` was found to have signed the + * transaction. + * + * @example + * let keypair = Keypair.random(); + * const account = new StellarSdk.Account(keypair.publicKey(), "-1"); + * + * const transaction = new TransactionBuilder(account, { fee: 100 }) + * .setTimeout(30) + * .build(); + * + * transaction.sign(keypair) + * WebAuth.verifyTxSignedBy(transaction, keypair.publicKey()) + */ +export declare function verifyTxSignedBy(transaction: FeeBumpTransaction | Transaction, accountID: string): boolean; +/** + * Checks if a transaction has been signed by one or more of the given signers, + * returning a list of non-repeated signers that were found to have signed the + * given transaction. + * + * @param {Transaction | FeeBumpTransaction} transaction The signed transaction. + * @param {Array.} signers The signer's public keys. + * @returns {Array.} A list of signers that were found to have signed + * the transaction. + * + * @example + * let keypair1 = Keypair.random(); + * let keypair2 = Keypair.random(); + * const account = new StellarSdk.Account(keypair1.publicKey(), "-1"); + * + * const transaction = new TransactionBuilder(account, { fee: 100 }) + * .setTimeout(30) + * .build(); + * + * transaction.sign(keypair1, keypair2) + * WebAuth.gatherTxSigners(transaction, [keypair1.publicKey(), keypair2.publicKey()]) + */ +export declare function gatherTxSigners(transaction: FeeBumpTransaction | Transaction, signers: string[]): string[]; diff --git a/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/utils.js b/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/utils.js new file mode 100644 index 000000000..bc35281aa --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/minimal/webauth/utils.js @@ -0,0 +1,332 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildChallengeTx = buildChallengeTx; +exports.gatherTxSigners = gatherTxSigners; +exports.readChallengeTx = readChallengeTx; +exports.verifyChallengeTxSigners = verifyChallengeTxSigners; +exports.verifyChallengeTxThreshold = verifyChallengeTxThreshold; +exports.verifyTxSignedBy = verifyTxSignedBy; +var _randombytes = _interopRequireDefault(require("randombytes")); +var _stellarBase = require("@stellar/stellar-base"); +var _utils = require("../utils"); +var _errors = require("./errors"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function buildChallengeTx(serverKeypair, clientAccountID, homeDomain) { + var timeout = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 300; + var networkPassphrase = arguments.length > 4 ? arguments[4] : undefined; + var webAuthDomain = arguments.length > 5 ? arguments[5] : undefined; + var memo = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var clientDomain = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var clientSigningKey = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; + if (clientAccountID.startsWith("M") && memo) { + throw Error("memo cannot be used if clientAccountID is a muxed account"); + } + var account = new _stellarBase.Account(serverKeypair.publicKey(), "-1"); + var now = Math.floor(Date.now() / 1000); + var value = (0, _randombytes.default)(48).toString("base64"); + var builder = new _stellarBase.TransactionBuilder(account, { + fee: _stellarBase.BASE_FEE, + networkPassphrase: networkPassphrase, + timebounds: { + minTime: now, + maxTime: now + timeout + } + }).addOperation(_stellarBase.Operation.manageData({ + name: "".concat(homeDomain, " auth"), + value: value, + source: clientAccountID + })).addOperation(_stellarBase.Operation.manageData({ + name: "web_auth_domain", + value: webAuthDomain, + source: account.accountId() + })); + if (clientDomain) { + if (!clientSigningKey) { + throw Error("clientSigningKey is required if clientDomain is provided"); + } + builder.addOperation(_stellarBase.Operation.manageData({ + name: "client_domain", + value: clientDomain, + source: clientSigningKey + })); + } + if (memo) { + builder.addMemo(_stellarBase.Memo.id(memo)); + } + var transaction = builder.build(); + transaction.sign(serverKeypair); + return transaction.toEnvelope().toXDR("base64").toString(); +} +function readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain) { + var _transaction$timeBoun; + if (serverAccountID.startsWith("M")) { + throw Error("Invalid serverAccountID: multiplexed accounts are not supported."); + } + var transaction; + try { + transaction = new _stellarBase.Transaction(challengeTx, networkPassphrase); + } catch (_unused) { + try { + transaction = new _stellarBase.FeeBumpTransaction(challengeTx, networkPassphrase); + } catch (_unused2) { + throw new _errors.InvalidChallengeError("Invalid challenge: unable to deserialize challengeTx transaction string"); + } + throw new _errors.InvalidChallengeError("Invalid challenge: expected a Transaction but received a FeeBumpTransaction"); + } + var sequence = Number.parseInt(transaction.sequence, 10); + if (sequence !== 0) { + throw new _errors.InvalidChallengeError("The transaction sequence number should be zero"); + } + if (transaction.source !== serverAccountID) { + throw new _errors.InvalidChallengeError("The transaction source account is not equal to the server's account"); + } + if (transaction.operations.length < 1) { + throw new _errors.InvalidChallengeError("The transaction should contain at least one operation"); + } + var _transaction$operatio = _toArray(transaction.operations), + operation = _transaction$operatio[0], + subsequentOperations = _transaction$operatio.slice(1); + if (!operation.source) { + throw new _errors.InvalidChallengeError("The transaction's operation should contain a source account"); + } + var clientAccountID = operation.source; + var memo = null; + if (transaction.memo.type !== _stellarBase.MemoNone) { + if (clientAccountID.startsWith("M")) { + throw new _errors.InvalidChallengeError("The transaction has a memo but the client account ID is a muxed account"); + } + if (transaction.memo.type !== _stellarBase.MemoID) { + throw new _errors.InvalidChallengeError("The transaction's memo must be of type `id`"); + } + memo = transaction.memo.value; + } + if (operation.type !== "manageData") { + throw new _errors.InvalidChallengeError("The transaction's operation type should be 'manageData'"); + } + if (transaction.timeBounds && Number.parseInt((_transaction$timeBoun = transaction.timeBounds) === null || _transaction$timeBoun === void 0 ? void 0 : _transaction$timeBoun.maxTime, 10) === _stellarBase.TimeoutInfinite) { + throw new _errors.InvalidChallengeError("The transaction requires non-infinite timebounds"); + } + if (!_utils.Utils.validateTimebounds(transaction, 60 * 5)) { + throw new _errors.InvalidChallengeError("The transaction has expired"); + } + if (operation.value === undefined) { + throw new _errors.InvalidChallengeError("The transaction's operation values should not be null"); + } + if (!operation.value) { + throw new _errors.InvalidChallengeError("The transaction's operation value should not be null"); + } + if (Buffer.from(operation.value.toString(), "base64").length !== 48) { + throw new _errors.InvalidChallengeError("The transaction's operation value should be a 64 bytes base64 random string"); + } + if (!homeDomains) { + throw new _errors.InvalidChallengeError("Invalid homeDomains: a home domain must be provided for verification"); + } + var matchedHomeDomain; + if (typeof homeDomains === "string") { + if ("".concat(homeDomains, " auth") === operation.name) { + matchedHomeDomain = homeDomains; + } + } else if (Array.isArray(homeDomains)) { + matchedHomeDomain = homeDomains.find(function (domain) { + return "".concat(domain, " auth") === operation.name; + }); + } else { + throw new _errors.InvalidChallengeError("Invalid homeDomains: homeDomains type is ".concat(_typeof(homeDomains), " but should be a string or an array")); + } + if (!matchedHomeDomain) { + throw new _errors.InvalidChallengeError("Invalid homeDomains: the transaction's operation key name does not match the expected home domain"); + } + var _iterator = _createForOfIteratorHelper(subsequentOperations), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var op = _step.value; + if (op.type !== "manageData") { + throw new _errors.InvalidChallengeError("The transaction has operations that are not of type 'manageData'"); + } + if (op.source !== serverAccountID && op.name !== "client_domain") { + throw new _errors.InvalidChallengeError("The transaction has operations that are unrecognized"); + } + if (op.name === "web_auth_domain") { + if (op.value === undefined) { + throw new _errors.InvalidChallengeError("'web_auth_domain' operation value should not be null"); + } + if (op.value.compare(Buffer.from(webAuthDomain))) { + throw new _errors.InvalidChallengeError("'web_auth_domain' operation value does not match ".concat(webAuthDomain)); + } + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + if (!verifyTxSignedBy(transaction, serverAccountID)) { + throw new _errors.InvalidChallengeError("Transaction not signed by server: '".concat(serverAccountID, "'")); + } + return { + tx: transaction, + clientAccountID: clientAccountID, + matchedHomeDomain: matchedHomeDomain, + memo: memo + }; +} +function verifyChallengeTxThreshold(challengeTx, serverAccountID, networkPassphrase, threshold, signerSummary, homeDomains, webAuthDomain) { + var signers = signerSummary.map(function (signer) { + return signer.key; + }); + var signersFound = verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain); + var weight = 0; + var _loop = function _loop() { + var _signerSummary$find; + var signer = _signersFound[_i]; + var sigWeight = ((_signerSummary$find = signerSummary.find(function (s) { + return s.key === signer; + })) === null || _signerSummary$find === void 0 ? void 0 : _signerSummary$find.weight) || 0; + weight += sigWeight; + }; + for (var _i = 0, _signersFound = signersFound; _i < _signersFound.length; _i++) { + _loop(); + } + if (weight < threshold) { + throw new _errors.InvalidChallengeError("signers with weight ".concat(weight, " do not meet threshold ").concat(threshold, "\"")); + } + return signersFound; +} +function verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain) { + var _readChallengeTx = readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain), + tx = _readChallengeTx.tx; + var serverKP; + try { + serverKP = _stellarBase.Keypair.fromPublicKey(serverAccountID); + } catch (err) { + throw new Error("Couldn't infer keypair from the provided 'serverAccountID': ".concat(err.message)); + } + var clientSigners = new Set(); + var _iterator2 = _createForOfIteratorHelper(signers), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var _signer = _step2.value; + if (_signer === serverKP.publicKey()) { + continue; + } + if (_signer.charAt(0) !== "G") { + continue; + } + clientSigners.add(_signer); + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + if (clientSigners.size === 0) { + throw new _errors.InvalidChallengeError("No verifiable client signers provided, at least one G... address must be provided"); + } + var clientSigningKey; + var _iterator3 = _createForOfIteratorHelper(tx.operations), + _step3; + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + var op = _step3.value; + if (op.type === "manageData" && op.name === "client_domain") { + if (clientSigningKey) { + throw new _errors.InvalidChallengeError("Found more than one client_domain operation"); + } + clientSigningKey = op.source; + } + } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); + } + var allSigners = [serverKP.publicKey()].concat(_toConsumableArray(Array.from(clientSigners))); + if (clientSigningKey) { + allSigners.push(clientSigningKey); + } + var signersFound = gatherTxSigners(tx, allSigners); + var serverSignatureFound = false; + var clientSigningKeySignatureFound = false; + for (var _i2 = 0, _signersFound2 = signersFound; _i2 < _signersFound2.length; _i2++) { + var signer = _signersFound2[_i2]; + if (signer === serverKP.publicKey()) { + serverSignatureFound = true; + } + if (signer === clientSigningKey) { + clientSigningKeySignatureFound = true; + } + } + if (!serverSignatureFound) { + throw new _errors.InvalidChallengeError("Transaction not signed by server: '".concat(serverKP.publicKey(), "'")); + } + if (clientSigningKey && !clientSigningKeySignatureFound) { + throw new _errors.InvalidChallengeError("Transaction not signed by the source account of the 'client_domain' " + "ManageData operation"); + } + if (signersFound.length === 1) { + throw new _errors.InvalidChallengeError("None of the given signers match the transaction signatures"); + } + if (signersFound.length !== tx.signatures.length) { + throw new _errors.InvalidChallengeError("Transaction has unrecognized signatures"); + } + signersFound.splice(signersFound.indexOf(serverKP.publicKey()), 1); + if (clientSigningKey) { + signersFound.splice(signersFound.indexOf(clientSigningKey), 1); + } + return signersFound; +} +function verifyTxSignedBy(transaction, accountID) { + return gatherTxSigners(transaction, [accountID]).length !== 0; +} +function gatherTxSigners(transaction, signers) { + var hashedSignatureBase = transaction.hash(); + var txSignatures = _toConsumableArray(transaction.signatures); + var signersFound = new Set(); + var _iterator4 = _createForOfIteratorHelper(signers), + _step4; + try { + for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { + var signer = _step4.value; + if (txSignatures.length === 0) { + break; + } + var keypair = void 0; + try { + keypair = _stellarBase.Keypair.fromPublicKey(signer); + } catch (err) { + throw new _errors.InvalidChallengeError("Signer is not a valid address: ".concat(err.message)); + } + for (var i = 0; i < txSignatures.length; i++) { + var decSig = txSignatures[i]; + if (!decSig.hint().equals(keypair.signatureHint())) { + continue; + } + if (keypair.verify(hashedSignatureBase, decSig.signature())) { + signersFound.add(signer); + txSignatures.splice(i, 1); + break; + } + } + } + } catch (err) { + _iterator4.e(err); + } finally { + _iterator4.f(); + } + return Array.from(signersFound); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/browser.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/browser.d.ts new file mode 100644 index 000000000..bfdbd32a2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/browser.d.ts @@ -0,0 +1,6 @@ +import { httpClient } from "./http-client"; +export * from "./index"; +export * as StellarBase from "@stellar/stellar-base"; +export { httpClient }; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/browser.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/browser.js new file mode 100644 index 000000000..f21e953f0 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/browser.js @@ -0,0 +1,35 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + httpClient: true, + StellarBase: true +}; +exports.default = exports.StellarBase = void 0; +Object.defineProperty(exports, "httpClient", { + enumerable: true, + get: function get() { + return _httpClient.httpClient; + } +}); +var _httpClient = require("./http-client"); +var _index = require("./index"); +Object.keys(_index).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _index[key]; + } + }); +}); +var _StellarBase = _interopRequireWildcard(require("@stellar/stellar-base")); +exports.StellarBase = _StellarBase; +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/config.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/config.d.ts new file mode 100644 index 000000000..3daa1aa99 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/config.d.ts @@ -0,0 +1,64 @@ +/** + * Global config parameters. + */ +export interface Configuration { + /** + * Allow connecting to http servers. This must be set to false in production deployments! + * @default false + */ + allowHttp: boolean; + /** + * Allow a timeout. Allows user to avoid nasty lag due network issues. + * @default 0 + */ + timeout: number; +} +/** + * Global config class. + * + * @hideconstructor + * + * @example Usage in node + * import { Config } from '@stellar/stellar-sdk'; + * Config.setAllowHttp(true); + * Config.setTimeout(5000); + * + * @example Usage in the browser + * StellarSdk.Config.setAllowHttp(true); + * StellarSdk.Config.setTimeout(5000); + */ +declare class Config { + /** + * Sets `allowHttp` flag globally. When set to `true`, connections to insecure + * http protocol servers will be allowed. Must be set to `false` in + * production. + * @default false + * @static + */ + static setAllowHttp(value: boolean): void; + /** + * Sets `timeout` flag globally. When set to anything besides 0, the request + * will timeout after specified time (ms). + * @default 0 + * @static + */ + static setTimeout(value: number): void; + /** + * Returns the configured `allowHttp` flag. + * @static + * @returns {boolean} + */ + static isAllowHttp(): boolean; + /** + * Returns the configured `timeout` flag. + * @static + * @returns {number} + */ + static getTimeout(): number; + /** + * Sets all global config flags to default values. + * @static + */ + static setDefault(): void; +} +export { Config }; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/config.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/config.js new file mode 100644 index 000000000..e19e63d74 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/config.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Config = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var defaultConfig = { + allowHttp: false, + timeout: 0 +}; +var config = _objectSpread({}, defaultConfig); +var Config = exports.Config = function () { + function Config() { + _classCallCheck(this, Config); + } + return _createClass(Config, null, [{ + key: "setAllowHttp", + value: function setAllowHttp(value) { + config.allowHttp = value; + } + }, { + key: "setTimeout", + value: function setTimeout(value) { + config.timeout = value; + } + }, { + key: "isAllowHttp", + value: function isAllowHttp() { + return config.allowHttp; + } + }, { + key: "getTimeout", + value: function getTimeout() { + return config.timeout; + } + }, { + key: "setDefault", + value: function setDefault() { + config = _objectSpread({}, defaultConfig); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/assembled_transaction.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/assembled_transaction.d.ts new file mode 100644 index 000000000..c420d90f2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/assembled_transaction.d.ts @@ -0,0 +1,627 @@ +import { Account, SorobanDataBuilder, TransactionBuilder, authorizeEntry as stellarBaseAuthorizeEntry, xdr } from "@stellar/stellar-base"; +import type { AssembledTransactionOptions, ClientOptions, Tx, XDR_BASE64 } from "./types"; +import { Api } from "../rpc/api"; +import { SentTransaction } from "./sent_transaction"; +import { Spec } from "./spec"; +/** @module contract */ +/** + * The main workhorse of {@link Client}. This class is used to wrap a + * transaction-under-construction and provide high-level interfaces to the most + * common workflows, while still providing access to low-level stellar-sdk + * transaction manipulation. + * + * Most of the time, you will not construct an `AssembledTransaction` directly, + * but instead receive one as the return value of a `Client` method. If + * you're familiar with the libraries generated by soroban-cli's `contract + * bindings typescript` command, these also wraps `Client` and return + * `AssembledTransaction` instances. + * + * Let's look at examples of how to use `AssembledTransaction` for a variety of + * use-cases: + * + * #### 1. Simple read call + * + * Since these only require simulation, you can get the `result` of the call + * right after constructing your `AssembledTransaction`: + * + * ```ts + * const { result } = await AssembledTransaction.build({ + * method: 'myReadMethod', + * args: spec.funcArgsToScVals('myReadMethod', { + * args: 'for', + * my: 'method', + * ... + * }), + * contractId: 'C123…', + * networkPassphrase: '…', + * rpcUrl: 'https://…', + * publicKey: undefined, // irrelevant, for simulation-only read calls + * parseResultXdr: (result: xdr.ScVal) => + * spec.funcResToNative('myReadMethod', result), + * }) + * ``` + * + * While that looks pretty complicated, most of the time you will use this in + * conjunction with {@link Client}, which simplifies it to: + * + * ```ts + * const { result } = await client.myReadMethod({ + * args: 'for', + * my: 'method', + * ... + * }) + * ``` + * + * #### 2. Simple write call + * + * For write calls that will be simulated and then sent to the network without + * further manipulation, only one more step is needed: + * + * ```ts + * const assembledTx = await client.myWriteMethod({ + * args: 'for', + * my: 'method', + * ... + * }) + * const sentTx = await assembledTx.signAndSend() + * ``` + * + * Here we're assuming that you're using a {@link Client}, rather than + * constructing `AssembledTransaction`'s directly. + * + * Note that `sentTx`, the return value of `signAndSend`, is a + * {@link SentTransaction}. `SentTransaction` is similar to + * `AssembledTransaction`, but is missing many of the methods and fields that + * are only relevant while assembling a transaction. It also has a few extra + * methods and fields that are only relevant after the transaction has been + * sent to the network. + * + * Like `AssembledTransaction`, `SentTransaction` also has a `result` getter, + * which contains the parsed final return value of the contract call. Most of + * the time, you may only be interested in this, so rather than getting the + * whole `sentTx` you may just want to: + * + * ```ts + * const tx = await client.myWriteMethod({ args: 'for', my: 'method', ... }) + * const { result } = await tx.signAndSend() + * ``` + * + * #### 3. More fine-grained control over transaction construction + * + * If you need more control over the transaction before simulating it, you can + * set various {@link MethodOptions} when constructing your + * `AssembledTransaction`. With a {@link Client}, this is passed as a + * second object after the arguments (or the only object, if the method takes + * no arguments): + * + * ```ts + * const tx = await client.myWriteMethod( + * { + * args: 'for', + * my: 'method', + * ... + * }, { + * fee: '10000', // default: {@link BASE_FEE} + * simulate: false, + * timeoutInSeconds: 20, // default: {@link DEFAULT_TIMEOUT} + * } + * ) + * ``` + * + * Since we've skipped simulation, we can now edit the `raw` transaction and + * then manually call `simulate`: + * + * ```ts + * tx.raw.addMemo(Memo.text('Nice memo, friend!')) + * await tx.simulate() + * ``` + * + * If you need to inspect the simulation later, you can access it with + * `tx.simulation`. + * + * #### 4. Multi-auth workflows + * + * Soroban, and Stellar in general, allows multiple parties to sign a + * transaction. + * + * Let's consider an Atomic Swap contract. Alice wants to give 10 of her Token + * A tokens to Bob for 5 of his Token B tokens. + * + * ```ts + * const ALICE = 'G123...' + * const BOB = 'G456...' + * const TOKEN_A = 'C123…' + * const TOKEN_B = 'C456…' + * const AMOUNT_A = 10n + * const AMOUNT_B = 5n + * ``` + * + * Let's say Alice is also going to be the one signing the final transaction + * envelope, meaning she is the invoker. So your app, from Alice's browser, + * simulates the `swap` call: + * + * ```ts + * const tx = await swapClient.swap({ + * a: ALICE, + * b: BOB, + * token_a: TOKEN_A, + * token_b: TOKEN_B, + * amount_a: AMOUNT_A, + * amount_b: AMOUNT_B, + * }) + * ``` + * + * But your app can't `signAndSend` this right away, because Bob needs to sign + * it first. You can check this: + * + * ```ts + * const whoElseNeedsToSign = tx.needsNonInvokerSigningBy() + * ``` + * + * You can verify that `whoElseNeedsToSign` is an array of length `1`, + * containing only Bob's public key. + * + * Then, still on Alice's machine, you can serialize the + * transaction-under-assembly: + * + * ```ts + * const json = tx.toJSON() + * ``` + * + * And now you need to send it to Bob's browser. How you do this depends on + * your app. Maybe you send it to a server first, maybe you use WebSockets, or + * maybe you have Alice text the JSON blob to Bob and have him paste it into + * your app in his browser (note: this option might be error-prone 😄). + * + * Once you get the JSON blob into your app on Bob's machine, you can + * deserialize it: + * + * ```ts + * const tx = swapClient.txFromJSON(json) + * ``` + * + * Or, if you're using a client generated with `soroban contract bindings + * typescript`, this deserialization will look like: + * + * ```ts + * const tx = swapClient.fromJSON.swap(json) + * ``` + * + * Then you can have Bob sign it. What Bob will actually need to sign is some + * _auth entries_ within the transaction, not the transaction itself or the + * transaction envelope. Your app can verify that Bob has the correct wallet + * selected, then: + * + * ```ts + * await tx.signAuthEntries() + * ``` + * + * Under the hood, this uses `signAuthEntry`, which you either need to inject + * during initial construction of the `Client`/`AssembledTransaction`, + * or which you can pass directly to `signAuthEntries`. + * + * Now Bob can again serialize the transaction and send back to Alice, where + * she can finally call `signAndSend()`. + * + * To see an even more complicated example, where Alice swaps with Bob but the + * transaction is invoked by yet another party, check out + * [test-swap.js](../../test/e2e/src/test-swap.js). + * + * @memberof module:contract + */ +export declare class AssembledTransaction { + options: AssembledTransactionOptions; + /** + * The TransactionBuilder as constructed in `{@link + * AssembledTransaction}.build`. Feel free set `simulate: false` to modify + * this object before calling `tx.simulate()` manually. Example: + * + * ```ts + * const tx = await myContract.myMethod( + * { args: 'for', my: 'method', ... }, + * { simulate: false } + * ); + * tx.raw.addMemo(Memo.text('Nice memo, friend!')) + * await tx.simulate(); + * ``` + */ + raw?: TransactionBuilder; + /** + * The Transaction as it was built with `raw.build()` right before + * simulation. Once this is set, modifying `raw` will have no effect unless + * you call `tx.simulate()` again. + */ + built?: Tx; + /** + * The result of the transaction simulation. This is set after the first call + * to `simulate`. It is difficult to serialize and deserialize, so it is not + * included in the `toJSON` and `fromJSON` methods. See `simulationData` + * cached, serializable access to the data needed by AssembledTransaction + * logic. + */ + simulation?: Api.SimulateTransactionResponse; + /** + * Cached simulation result. This is set after the first call to + * {@link AssembledTransaction#simulationData}, and is used to facilitate + * serialization and deserialization of the AssembledTransaction. + * + * Most of the time, if you need this data, you can call + * `tx.simulation.result`. + * + * If you need access to this data after a transaction has been serialized + * and then deserialized, you can call `simulationData.result`. + */ + private simulationResult?; + /** + * Cached simulation transaction data. This is set after the first call to + * {@link AssembledTransaction#simulationData}, and is used to facilitate + * serialization and deserialization of the AssembledTransaction. + * + * Most of the time, if you need this data, you can call + * `simulation.transactionData`. + * + * If you need access to this data after a transaction has been serialized + * and then deserialized, you can call `simulationData.transactionData`. + */ + private simulationTransactionData?; + /** + * The Soroban server to use for all RPC calls. This is constructed from the + * `rpcUrl` in the options. + */ + private server; + /** + * The signed transaction. + */ + signed?: Tx; + /** + * A list of the most important errors that various AssembledTransaction + * methods can throw. Feel free to catch specific errors in your application + * logic. + */ + static Errors: { + ExpiredState: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + RestorationFailure: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NeedsMoreSignatures: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NoSignatureNeeded: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NoUnsignedNonInvokerAuthEntries: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NoSigner: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NotYetSimulated: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + FakeAccount: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + SimulationFailed: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + InternalWalletError: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + ExternalServiceError: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + InvalidClientRequest: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + UserRejected: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + }; + /** + * Serialize the AssembledTransaction to a JSON string. This is useful for + * saving the transaction to a database or sending it over the wire for + * multi-auth workflows. `fromJSON` can be used to deserialize the + * transaction. This only works with transactions that have been simulated. + */ + toJSON(): string; + static fromJSON(options: Omit, "args">, { tx, simulationResult, simulationTransactionData, }: { + tx: XDR_BASE64; + simulationResult: { + auth: XDR_BASE64[]; + retval: XDR_BASE64; + }; + simulationTransactionData: XDR_BASE64; + }): AssembledTransaction; + /** + * Serialize the AssembledTransaction to a base64-encoded XDR string. + */ + toXDR(): string; + /** + * Deserialize the AssembledTransaction from a base64-encoded XDR string. + */ + static fromXDR(options: Omit, "args" | "method" | "parseResultXdr">, encodedXDR: string, spec: Spec): AssembledTransaction; + private handleWalletError; + private constructor(); + /** + * Construct a new AssembledTransaction. This is the main way to create a new + * AssembledTransaction; the constructor is private. + * + * This is an asynchronous constructor for two reasons: + * + * 1. It needs to fetch the account from the network to get the current + * sequence number. + * 2. It needs to simulate the transaction to get the expected fee. + * + * If you don't want to simulate the transaction, you can set `simulate` to + * `false` in the options. + * + * If you need to create an operation other than `invokeHostFunction`, you + * can use {@link AssembledTransaction.buildWithOp} instead. + * + * @example + * const tx = await AssembledTransaction.build({ + * ..., + * simulate: false, + * }) + */ + static build(options: AssembledTransactionOptions): Promise>; + /** + * Construct a new AssembledTransaction, specifying an Operation other than + * `invokeHostFunction` (the default used by {@link AssembledTransaction.build}). + * + * Note: `AssembledTransaction` currently assumes these operations can be + * simulated. This is not true for classic operations; only for those used by + * Soroban Smart Contracts like `invokeHostFunction` and `createCustomContract`. + * + * @example + * const tx = await AssembledTransaction.buildWithOp( + * Operation.createCustomContract({ ... }); + * { + * ..., + * simulate: false, + * } + * ) + */ + static buildWithOp(operation: xdr.Operation, options: AssembledTransactionOptions): Promise>; + private static buildFootprintRestoreTransaction; + simulate: ({ restore }?: { + restore?: boolean; + }) => Promise; + get simulationData(): { + result: Api.SimulateHostFunctionResult; + transactionData: xdr.SorobanTransactionData; + }; + get result(): T; + private parseError; + /** + * Sign the transaction with the signTransaction function included previously. + * If you did not previously include one, you need to include one now. + */ + sign: ({ force, signTransaction, }?: { + /** + * If `true`, sign and send the transaction even if it is a read call + */ + force?: boolean; + /** + * You must provide this here if you did not provide one before + */ + signTransaction?: ClientOptions["signTransaction"]; + }) => Promise; + /** + * Sends the transaction to the network to return a `SentTransaction` that + * keeps track of all the attempts to fetch the transaction. + */ + send(): Promise>; + /** + * Sign the transaction with the `signTransaction` function included previously. + * If you did not previously include one, you need to include one now. + * After signing, this method will send the transaction to the network and + * return a `SentTransaction` that keeps track * of all the attempts to fetch the transaction. + */ + signAndSend: ({ force, signTransaction, }?: { + /** + * If `true`, sign and send the transaction even if it is a read call + */ + force?: boolean; + /** + * You must provide this here if you did not provide one before + */ + signTransaction?: ClientOptions["signTransaction"]; + }) => Promise>; + /** + * Get a list of accounts, other than the invoker of the simulation, that + * need to sign auth entries in this transaction. + * + * Soroban allows multiple people to sign a transaction. Someone needs to + * sign the final transaction envelope; this person/account is called the + * _invoker_, or _source_. Other accounts might need to sign individual auth + * entries in the transaction, if they're not also the invoker. + * + * This function returns a list of accounts that need to sign auth entries, + * assuming that the same invoker/source account will sign the final + * transaction envelope as signed the initial simulation. + * + * One at a time, for each public key in this array, you will need to + * serialize this transaction with `toJSON`, send to the owner of that key, + * deserialize the transaction with `txFromJson`, and call + * {@link AssembledTransaction#signAuthEntries}. Then re-serialize and send to + * the next account in this list. + */ + needsNonInvokerSigningBy: ({ includeAlreadySigned, }?: { + /** + * Whether or not to include auth entries that have already been signed. + * Default: false + */ + includeAlreadySigned?: boolean; + }) => string[]; + /** + * If {@link AssembledTransaction#needsNonInvokerSigningBy} returns a + * non-empty list, you can serialize the transaction with `toJSON`, send it to + * the owner of one of the public keys in the map, deserialize with + * `txFromJSON`, and call this method on their machine. Internally, this will + * use `signAuthEntry` function from connected `wallet` for each. + * + * Then, re-serialize the transaction and either send to the next + * `needsNonInvokerSigningBy` owner, or send it back to the original account + * who simulated the transaction so they can {@link AssembledTransaction#sign} + * the transaction envelope and {@link AssembledTransaction#send} it to the + * network. + * + * Sending to all `needsNonInvokerSigningBy` owners in parallel is not + * currently supported! + */ + signAuthEntries: ({ expiration, signAuthEntry, address, authorizeEntry, }?: { + /** + * When to set each auth entry to expire. Could be any number of blocks in + * the future. Can be supplied as a promise or a raw number. Default: + * about 8.3 minutes from now. + */ + expiration?: number | Promise; + /** + * Sign all auth entries for this account. Default: the account that + * constructed the transaction + */ + address?: string; + /** + * You must provide this here if you did not provide one before and you are not passing `authorizeEntry`. Default: the `signAuthEntry` function from the `Client` options. Must sign things as the given `publicKey`. + */ + signAuthEntry?: ClientOptions["signAuthEntry"]; + /** + * If you have a pro use-case and need to override the default `authorizeEntry` function, rather than using the one in @stellar/stellar-base, you can do that! Your function needs to take at least the first argument, `entry: xdr.SorobanAuthorizationEntry`, and return a `Promise`. + * + * Note that you if you pass this, then `signAuthEntry` will be ignored. + */ + authorizeEntry?: typeof stellarBaseAuthorizeEntry; + }) => Promise; + /** + * Whether this transaction is a read call. This is determined by the + * simulation result and the transaction data. If the transaction is a read + * call, it will not need to be signed and sent to the network. If this + * returns `false`, then you need to call `signAndSend` on this transaction. + */ + get isReadCall(): boolean; + /** + * Restores the footprint (resource ledger entries that can be read or written) + * of an expired transaction. + * + * The method will: + * 1. Build a new transaction aimed at restoring the necessary resources. + * 2. Sign this new transaction if a `signTransaction` handler is provided. + * 3. Send the signed transaction to the network. + * 4. Await and return the response from the network. + * + * Preconditions: + * - A `signTransaction` function must be provided during the Client initialization. + * - The provided `restorePreamble` should include a minimum resource fee and valid + * transaction data. + * + * @throws {Error} - Throws an error if no `signTransaction` function is provided during + * Client initialization. + * @throws {AssembledTransaction.Errors.RestoreFailure} - Throws a custom error if the + * restore transaction fails, providing the details of the failure. + */ + restoreFootprint( + /** + * The preamble object containing data required to + * build the restore transaction. + */ + restorePreamble: { + minResourceFee: string; + transactionData: SorobanDataBuilder; + }, + /** The account that is executing the footprint restore operation. If omitted, will use the account from the AssembledTransaction. */ + account?: Account): Promise; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/assembled_transaction.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/assembled_transaction.js new file mode 100644 index 000000000..aaeaac04e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/assembled_transaction.js @@ -0,0 +1,841 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AssembledTransaction = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _rpc = require("../rpc"); +var _api = require("../rpc/api"); +var _transaction = require("../rpc/transaction"); +var _rust_result = require("./rust_result"); +var _utils = require("./utils"); +var _types = require("./types"); +var _sent_transaction = require("./sent_transaction"); +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var AssembledTransaction = exports.AssembledTransaction = function () { + function AssembledTransaction(options) { + var _this = this, + _this$options$simulat, + _this$options$allowHt; + _classCallCheck(this, AssembledTransaction); + _defineProperty(this, "simulate", _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var _restore; + var _ref2, + restore, + account, + result, + _this$options$fee, + _this$options$args, + _this$options$timeout, + contract, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _ref2 = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, restore = _ref2.restore; + if (_this.built) { + _context.next = 5; + break; + } + if (_this.raw) { + _context.next = 4; + break; + } + throw new Error("Transaction has not yet been assembled; " + "call `AssembledTransaction.build` first."); + case 4: + _this.built = _this.raw.build(); + case 5: + restore = (_restore = restore) !== null && _restore !== void 0 ? _restore : _this.options.restore; + delete _this.simulationResult; + delete _this.simulationTransactionData; + _context.next = 10; + return _this.server.simulateTransaction(_this.built); + case 10: + _this.simulation = _context.sent; + if (!(restore && _api.Api.isSimulationRestore(_this.simulation))) { + _context.next = 25; + break; + } + _context.next = 14; + return (0, _utils.getAccount)(_this.options, _this.server); + case 14: + account = _context.sent; + _context.next = 17; + return _this.restoreFootprint(_this.simulation.restorePreamble, account); + case 17: + result = _context.sent; + if (!(result.status === _api.Api.GetTransactionStatus.SUCCESS)) { + _context.next = 24; + break; + } + contract = new _stellarBase.Contract(_this.options.contractId); + _this.raw = new _stellarBase.TransactionBuilder(account, { + fee: (_this$options$fee = _this.options.fee) !== null && _this$options$fee !== void 0 ? _this$options$fee : _stellarBase.BASE_FEE, + networkPassphrase: _this.options.networkPassphrase + }).addOperation(contract.call.apply(contract, [_this.options.method].concat(_toConsumableArray((_this$options$args = _this.options.args) !== null && _this$options$args !== void 0 ? _this$options$args : [])))).setTimeout((_this$options$timeout = _this.options.timeoutInSeconds) !== null && _this$options$timeout !== void 0 ? _this$options$timeout : _types.DEFAULT_TIMEOUT); + _context.next = 23; + return _this.simulate(); + case 23: + return _context.abrupt("return", _this); + case 24: + throw new AssembledTransaction.Errors.RestorationFailure("Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n".concat(JSON.stringify(result))); + case 25: + if (_api.Api.isSimulationSuccess(_this.simulation)) { + _this.built = (0, _transaction.assembleTransaction)(_this.built, _this.simulation).build(); + } + return _context.abrupt("return", _this); + case 27: + case "end": + return _context.stop(); + } + }, _callee); + }))); + _defineProperty(this, "sign", _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + var _this$options$timeout2; + var _ref4, + _ref4$force, + force, + _ref4$signTransaction, + signTransaction, + sigsNeeded, + timeoutInSeconds, + signOpts, + _yield$signTransactio, + signature, + error, + _args2 = arguments; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _ref4 = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref4$force = _ref4.force, force = _ref4$force === void 0 ? false : _ref4$force, _ref4$signTransaction = _ref4.signTransaction, signTransaction = _ref4$signTransaction === void 0 ? _this.options.signTransaction : _ref4$signTransaction; + if (_this.built) { + _context2.next = 3; + break; + } + throw new Error("Transaction has not yet been simulated"); + case 3: + if (!(!force && _this.isReadCall)) { + _context2.next = 5; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("This is a read call. It requires no signature or sending. " + "Use `force: true` to sign and send anyway."); + case 5: + if (signTransaction) { + _context2.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide a signTransaction function, either when calling " + "`signAndSend` or when initializing your Client"); + case 7: + sigsNeeded = _this.needsNonInvokerSigningBy().filter(function (id) { + return !id.startsWith('C'); + }); + if (!sigsNeeded.length) { + _context2.next = 10; + break; + } + throw new AssembledTransaction.Errors.NeedsMoreSignatures("Transaction requires signatures from ".concat(sigsNeeded, ". ") + "See `needsNonInvokerSigningBy` for details."); + case 10: + timeoutInSeconds = (_this$options$timeout2 = _this.options.timeoutInSeconds) !== null && _this$options$timeout2 !== void 0 ? _this$options$timeout2 : _types.DEFAULT_TIMEOUT; + _this.built = _stellarBase.TransactionBuilder.cloneFrom(_this.built, { + fee: _this.built.fee, + timebounds: undefined, + sorobanData: _this.simulationData.transactionData + }).setTimeout(timeoutInSeconds).build(); + signOpts = { + networkPassphrase: _this.options.networkPassphrase + }; + if (_this.options.address) signOpts.address = _this.options.address; + if (_this.options.submit !== undefined) signOpts.submit = _this.options.submit; + if (_this.options.submitUrl) signOpts.submitUrl = _this.options.submitUrl; + _context2.next = 18; + return signTransaction(_this.built.toXDR(), signOpts); + case 18: + _yield$signTransactio = _context2.sent; + signature = _yield$signTransactio.signedTxXdr; + error = _yield$signTransactio.error; + _this.handleWalletError(error); + _this.signed = _stellarBase.TransactionBuilder.fromXDR(signature, _this.options.networkPassphrase); + case 23: + case "end": + return _context2.stop(); + } + }, _callee2); + }))); + _defineProperty(this, "signAndSend", _asyncToGenerator(_regeneratorRuntime().mark(function _callee3() { + var _ref6, + _ref6$force, + force, + _ref6$signTransaction, + signTransaction, + originalSubmit, + _args3 = arguments; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _ref6 = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : {}, _ref6$force = _ref6.force, force = _ref6$force === void 0 ? false : _ref6$force, _ref6$signTransaction = _ref6.signTransaction, signTransaction = _ref6$signTransaction === void 0 ? _this.options.signTransaction : _ref6$signTransaction; + if (_this.signed) { + _context3.next = 10; + break; + } + originalSubmit = _this.options.submit; + if (_this.options.submit) { + _this.options.submit = false; + } + _context3.prev = 4; + _context3.next = 7; + return _this.sign({ + force: force, + signTransaction: signTransaction + }); + case 7: + _context3.prev = 7; + _this.options.submit = originalSubmit; + return _context3.finish(7); + case 10: + return _context3.abrupt("return", _this.send()); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3, null, [[4,, 7, 10]]); + }))); + _defineProperty(this, "needsNonInvokerSigningBy", function () { + var _rawInvokeHostFunctio; + var _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref7$includeAlreadyS = _ref7.includeAlreadySigned, + includeAlreadySigned = _ref7$includeAlreadyS === void 0 ? false : _ref7$includeAlreadyS; + if (!_this.built) { + throw new Error("Transaction has not yet been simulated"); + } + if (!("operations" in _this.built)) { + throw new Error("Unexpected Transaction type; no operations: ".concat(JSON.stringify(_this.built))); + } + var rawInvokeHostFunctionOp = _this.built.operations[0]; + return _toConsumableArray(new Set(((_rawInvokeHostFunctio = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio !== void 0 ? _rawInvokeHostFunctio : []).filter(function (entry) { + return entry.credentials().switch() === _stellarBase.xdr.SorobanCredentialsType.sorobanCredentialsAddress() && (includeAlreadySigned || entry.credentials().address().signature().switch().name === "scvVoid"); + }).map(function (entry) { + return _stellarBase.Address.fromScAddress(entry.credentials().address().address()).toString(); + }))); + }); + _defineProperty(this, "signAuthEntries", _asyncToGenerator(_regeneratorRuntime().mark(function _callee6() { + var _rawInvokeHostFunctio2; + var _ref9, + _ref9$expiration, + expiration, + _ref9$signAuthEntry, + signAuthEntry, + _ref9$address, + address, + _ref9$authorizeEntry, + authorizeEntry, + needsNonInvokerSigningBy, + rawInvokeHostFunctionOp, + authEntries, + _iterator, + _step, + _loop, + _ret, + _args7 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _ref9 = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {}, _ref9$expiration = _ref9.expiration, expiration = _ref9$expiration === void 0 ? _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this.server.getLatestLedger(); + case 2: + _context4.t0 = _context4.sent.sequence; + return _context4.abrupt("return", _context4.t0 + 100); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + }))() : _ref9$expiration, _ref9$signAuthEntry = _ref9.signAuthEntry, signAuthEntry = _ref9$signAuthEntry === void 0 ? _this.options.signAuthEntry : _ref9$signAuthEntry, _ref9$address = _ref9.address, address = _ref9$address === void 0 ? _this.options.publicKey : _ref9$address, _ref9$authorizeEntry = _ref9.authorizeEntry, authorizeEntry = _ref9$authorizeEntry === void 0 ? _stellarBase.authorizeEntry : _ref9$authorizeEntry; + if (_this.built) { + _context7.next = 3; + break; + } + throw new Error("Transaction has not yet been assembled or simulated"); + case 3: + if (!(authorizeEntry === _stellarBase.authorizeEntry)) { + _context7.next = 11; + break; + } + needsNonInvokerSigningBy = _this.needsNonInvokerSigningBy(); + if (!(needsNonInvokerSigningBy.length === 0)) { + _context7.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?"); + case 7: + if (!(needsNonInvokerSigningBy.indexOf(address !== null && address !== void 0 ? address : "") === -1)) { + _context7.next = 9; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("No auth entries for public key \"".concat(address, "\"")); + case 9: + if (signAuthEntry) { + _context7.next = 11; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`"); + case 11: + rawInvokeHostFunctionOp = _this.built.operations[0]; + authEntries = (_rawInvokeHostFunctio2 = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio2 !== void 0 ? _rawInvokeHostFunctio2 : []; + _iterator = _createForOfIteratorHelper(authEntries.entries()); + _context7.prev = 14; + _loop = _regeneratorRuntime().mark(function _loop() { + var _step$value, i, entry, credentials, authEntryAddress, sign; + return _regeneratorRuntime().wrap(function _loop$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _step$value = _slicedToArray(_step.value, 2), i = _step$value[0], entry = _step$value[1]; + credentials = _stellarBase.xdr.SorobanCredentials.fromXDR(entry.credentials().toXDR()); + if (!(credentials.switch() !== _stellarBase.xdr.SorobanCredentialsType.sorobanCredentialsAddress())) { + _context6.next = 4; + break; + } + return _context6.abrupt("return", 0); + case 4: + authEntryAddress = _stellarBase.Address.fromScAddress(credentials.address().address()).toString(); + if (!(authEntryAddress !== address)) { + _context6.next = 7; + break; + } + return _context6.abrupt("return", 0); + case 7: + sign = signAuthEntry !== null && signAuthEntry !== void 0 ? signAuthEntry : Promise.resolve; + _context6.t0 = authorizeEntry; + _context6.t1 = entry; + _context6.t2 = function () { + var _ref11 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(preimage) { + var _yield$sign, signedAuthEntry, error; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return sign(preimage.toXDR("base64"), { + address: address + }); + case 2: + _yield$sign = _context5.sent; + signedAuthEntry = _yield$sign.signedAuthEntry; + error = _yield$sign.error; + _this.handleWalletError(error); + return _context5.abrupt("return", Buffer.from(signedAuthEntry, "base64")); + case 7: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x) { + return _ref11.apply(this, arguments); + }; + }(); + _context6.next = 13; + return expiration; + case 13: + _context6.t3 = _context6.sent; + _context6.t4 = _this.options.networkPassphrase; + _context6.next = 17; + return (0, _context6.t0)(_context6.t1, _context6.t2, _context6.t3, _context6.t4); + case 17: + authEntries[i] = _context6.sent; + case 18: + case "end": + return _context6.stop(); + } + }, _loop); + }); + _iterator.s(); + case 17: + if ((_step = _iterator.n()).done) { + _context7.next = 24; + break; + } + return _context7.delegateYield(_loop(), "t0", 19); + case 19: + _ret = _context7.t0; + if (!(_ret === 0)) { + _context7.next = 22; + break; + } + return _context7.abrupt("continue", 22); + case 22: + _context7.next = 17; + break; + case 24: + _context7.next = 29; + break; + case 26: + _context7.prev = 26; + _context7.t1 = _context7["catch"](14); + _iterator.e(_context7.t1); + case 29: + _context7.prev = 29; + _iterator.f(); + return _context7.finish(29); + case 32: + case "end": + return _context7.stop(); + } + }, _callee6, null, [[14, 26, 29, 32]]); + }))); + this.options = options; + this.options.simulate = (_this$options$simulat = this.options.simulate) !== null && _this$options$simulat !== void 0 ? _this$options$simulat : true; + this.server = new _rpc.Server(this.options.rpcUrl, { + allowHttp: (_this$options$allowHt = this.options.allowHttp) !== null && _this$options$allowHt !== void 0 ? _this$options$allowHt : false + }); + } + return _createClass(AssembledTransaction, [{ + key: "toJSON", + value: function toJSON() { + var _this$built; + return JSON.stringify({ + method: this.options.method, + tx: (_this$built = this.built) === null || _this$built === void 0 ? void 0 : _this$built.toXDR(), + simulationResult: { + auth: this.simulationData.result.auth.map(function (a) { + return a.toXDR("base64"); + }), + retval: this.simulationData.result.retval.toXDR("base64") + }, + simulationTransactionData: this.simulationData.transactionData.toXDR("base64") + }); + } + }, { + key: "toXDR", + value: function toXDR() { + var _this$built2; + if (!this.built) throw new Error("Transaction has not yet been simulated; " + "call `AssembledTransaction.simulate` first."); + return (_this$built2 = this.built) === null || _this$built2 === void 0 ? void 0 : _this$built2.toEnvelope().toXDR('base64'); + } + }, { + key: "handleWalletError", + value: function handleWalletError(error) { + if (!error) return; + var message = error.message, + code = error.code; + var fullMessage = "".concat(message).concat(error.ext ? " (".concat(error.ext.join(', '), ")") : ''); + switch (code) { + case -1: + throw new AssembledTransaction.Errors.InternalWalletError(fullMessage); + case -2: + throw new AssembledTransaction.Errors.ExternalServiceError(fullMessage); + case -3: + throw new AssembledTransaction.Errors.InvalidClientRequest(fullMessage); + case -4: + throw new AssembledTransaction.Errors.UserRejected(fullMessage); + default: + throw new Error("Unhandled error: ".concat(fullMessage)); + } + } + }, { + key: "simulationData", + get: function get() { + var _simulation$result; + if (this.simulationResult && this.simulationTransactionData) { + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + var simulation = this.simulation; + if (!simulation) { + throw new AssembledTransaction.Errors.NotYetSimulated("Transaction has not yet been simulated"); + } + if (_api.Api.isSimulationError(simulation)) { + throw new AssembledTransaction.Errors.SimulationFailed("Transaction simulation failed: \"".concat(simulation.error, "\"")); + } + if (_api.Api.isSimulationRestore(simulation)) { + throw new AssembledTransaction.Errors.ExpiredState("You need to restore some contract state before you can invoke this method.\n" + 'You can set `restore` to true in the method options in order to ' + 'automatically restore the contract state when needed.'); + } + this.simulationResult = (_simulation$result = simulation.result) !== null && _simulation$result !== void 0 ? _simulation$result : { + auth: [], + retval: _stellarBase.xdr.ScVal.scvVoid() + }; + this.simulationTransactionData = simulation.transactionData.build(); + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + }, { + key: "result", + get: function get() { + try { + if (!this.simulationData.result) { + throw new Error("No simulation result!"); + } + return this.options.parseResultXdr(this.simulationData.result.retval); + } catch (e) { + if (!(0, _utils.implementsToString)(e)) throw e; + var err = this.parseError(e.toString()); + if (err) return err; + throw e; + } + } + }, { + key: "parseError", + value: function parseError(errorMessage) { + if (!this.options.errorTypes) return undefined; + var match = errorMessage.match(_utils.contractErrorPattern); + if (!match) return undefined; + var i = parseInt(match[1], 10); + var err = this.options.errorTypes[i]; + if (!err) return undefined; + return new _rust_result.Err(err); + } + }, { + key: "send", + value: (function () { + var _send = _asyncToGenerator(_regeneratorRuntime().mark(function _callee7() { + var sent; + return _regeneratorRuntime().wrap(function _callee7$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (this.signed) { + _context8.next = 2; + break; + } + throw new Error("The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead."); + case 2: + _context8.next = 4; + return _sent_transaction.SentTransaction.init(this); + case 4: + sent = _context8.sent; + return _context8.abrupt("return", sent); + case 6: + case "end": + return _context8.stop(); + } + }, _callee7, this); + })); + function send() { + return _send.apply(this, arguments); + } + return send; + }()) + }, { + key: "isReadCall", + get: function get() { + var authsCount = this.simulationData.result.auth.length; + var writeLength = this.simulationData.transactionData.resources().footprint().readWrite().length; + return authsCount === 0 && writeLength === 0; + } + }, { + key: "restoreFootprint", + value: (function () { + var _restoreFootprint = _asyncToGenerator(_regeneratorRuntime().mark(function _callee8(restorePreamble, account) { + var _account; + var restoreTx, sentTransaction; + return _regeneratorRuntime().wrap(function _callee8$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + if (this.options.signTransaction) { + _context9.next = 2; + break; + } + throw new Error("For automatic restore to work you must provide a signTransaction function when initializing your Client"); + case 2: + if (!((_account = account) !== null && _account !== void 0)) { + _context9.next = 6; + break; + } + _context9.t0 = _account; + _context9.next = 9; + break; + case 6: + _context9.next = 8; + return (0, _utils.getAccount)(this.options, this.server); + case 8: + _context9.t0 = _context9.sent; + case 9: + account = _context9.t0; + _context9.next = 12; + return AssembledTransaction.buildFootprintRestoreTransaction(_objectSpread({}, this.options), restorePreamble.transactionData, account, restorePreamble.minResourceFee); + case 12: + restoreTx = _context9.sent; + _context9.next = 15; + return restoreTx.signAndSend(); + case 15: + sentTransaction = _context9.sent; + if (sentTransaction.getTransactionResponse) { + _context9.next = 18; + break; + } + throw new AssembledTransaction.Errors.RestorationFailure("The attempt at automatic restore failed. \n".concat(JSON.stringify(sentTransaction))); + case 18: + return _context9.abrupt("return", sentTransaction.getTransactionResponse); + case 19: + case "end": + return _context9.stop(); + } + }, _callee8, this); + })); + function restoreFootprint(_x2, _x3) { + return _restoreFootprint.apply(this, arguments); + } + return restoreFootprint; + }()) + }], [{ + key: "fromJSON", + value: function fromJSON(options, _ref12) { + var tx = _ref12.tx, + simulationResult = _ref12.simulationResult, + simulationTransactionData = _ref12.simulationTransactionData; + var txn = new AssembledTransaction(options); + txn.built = _stellarBase.TransactionBuilder.fromXDR(tx, options.networkPassphrase); + txn.simulationResult = { + auth: simulationResult.auth.map(function (a) { + return _stellarBase.xdr.SorobanAuthorizationEntry.fromXDR(a, "base64"); + }), + retval: _stellarBase.xdr.ScVal.fromXDR(simulationResult.retval, "base64") + }; + txn.simulationTransactionData = _stellarBase.xdr.SorobanTransactionData.fromXDR(simulationTransactionData, "base64"); + return txn; + } + }, { + key: "fromXDR", + value: function fromXDR(options, encodedXDR, spec) { + var _operation$func; + var envelope = _stellarBase.xdr.TransactionEnvelope.fromXDR(encodedXDR, "base64"); + var built = _stellarBase.TransactionBuilder.fromXDR(envelope, options.networkPassphrase); + var operation = built.operations[0]; + if (!(operation !== null && operation !== void 0 && (_operation$func = operation.func) !== null && _operation$func !== void 0 && _operation$func.value) || typeof operation.func.value !== 'function') { + throw new Error("Could not extract the method from the transaction envelope."); + } + var invokeContractArgs = operation.func.value(); + if (!(invokeContractArgs !== null && invokeContractArgs !== void 0 && invokeContractArgs.functionName)) { + throw new Error("Could not extract the method name from the transaction envelope."); + } + var method = invokeContractArgs.functionName().toString('utf-8'); + var txn = new AssembledTransaction(_objectSpread(_objectSpread({}, options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + txn.built = built; + return txn; + } + }, { + key: "build", + value: function build(options) { + var _options$args; + var contract = new _stellarBase.Contract(options.contractId); + return AssembledTransaction.buildWithOp(contract.call.apply(contract, [options.method].concat(_toConsumableArray((_options$args = options.args) !== null && _options$args !== void 0 ? _options$args : []))), options); + } + }, { + key: "buildWithOp", + value: (function () { + var _buildWithOp = _asyncToGenerator(_regeneratorRuntime().mark(function _callee9(operation, options) { + var _options$fee, _options$timeoutInSec; + var tx, account; + return _regeneratorRuntime().wrap(function _callee9$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + tx = new AssembledTransaction(options); + _context10.next = 3; + return (0, _utils.getAccount)(options, tx.server); + case 3: + account = _context10.sent; + tx.raw = new _stellarBase.TransactionBuilder(account, { + fee: (_options$fee = options.fee) !== null && _options$fee !== void 0 ? _options$fee : _stellarBase.BASE_FEE, + networkPassphrase: options.networkPassphrase + }).setTimeout((_options$timeoutInSec = options.timeoutInSeconds) !== null && _options$timeoutInSec !== void 0 ? _options$timeoutInSec : _types.DEFAULT_TIMEOUT).addOperation(operation); + if (!options.simulate) { + _context10.next = 8; + break; + } + _context10.next = 8; + return tx.simulate(); + case 8: + return _context10.abrupt("return", tx); + case 9: + case "end": + return _context10.stop(); + } + }, _callee9); + })); + function buildWithOp(_x4, _x5) { + return _buildWithOp.apply(this, arguments); + } + return buildWithOp; + }()) + }, { + key: "buildFootprintRestoreTransaction", + value: function () { + var _buildFootprintRestoreTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee10(options, sorobanData, account, fee) { + var _options$timeoutInSec2; + var tx; + return _regeneratorRuntime().wrap(function _callee10$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + tx = new AssembledTransaction(options); + tx.raw = new _stellarBase.TransactionBuilder(account, { + fee: fee, + networkPassphrase: options.networkPassphrase + }).setSorobanData(sorobanData instanceof _stellarBase.SorobanDataBuilder ? sorobanData.build() : sorobanData).addOperation(_stellarBase.Operation.restoreFootprint({})).setTimeout((_options$timeoutInSec2 = options.timeoutInSeconds) !== null && _options$timeoutInSec2 !== void 0 ? _options$timeoutInSec2 : _types.DEFAULT_TIMEOUT); + _context11.next = 4; + return tx.simulate({ + restore: false + }); + case 4: + return _context11.abrupt("return", tx); + case 5: + case "end": + return _context11.stop(); + } + }, _callee10); + })); + function buildFootprintRestoreTransaction(_x6, _x7, _x8, _x9) { + return _buildFootprintRestoreTransaction.apply(this, arguments); + } + return buildFootprintRestoreTransaction; + }() + }]); +}(); +_defineProperty(AssembledTransaction, "Errors", { + ExpiredState: function (_Error) { + function ExpiredStateError() { + _classCallCheck(this, ExpiredStateError); + return _callSuper(this, ExpiredStateError, arguments); + } + _inherits(ExpiredStateError, _Error); + return _createClass(ExpiredStateError); + }(_wrapNativeSuper(Error)), + RestorationFailure: function (_Error2) { + function RestoreFailureError() { + _classCallCheck(this, RestoreFailureError); + return _callSuper(this, RestoreFailureError, arguments); + } + _inherits(RestoreFailureError, _Error2); + return _createClass(RestoreFailureError); + }(_wrapNativeSuper(Error)), + NeedsMoreSignatures: function (_Error3) { + function NeedsMoreSignaturesError() { + _classCallCheck(this, NeedsMoreSignaturesError); + return _callSuper(this, NeedsMoreSignaturesError, arguments); + } + _inherits(NeedsMoreSignaturesError, _Error3); + return _createClass(NeedsMoreSignaturesError); + }(_wrapNativeSuper(Error)), + NoSignatureNeeded: function (_Error4) { + function NoSignatureNeededError() { + _classCallCheck(this, NoSignatureNeededError); + return _callSuper(this, NoSignatureNeededError, arguments); + } + _inherits(NoSignatureNeededError, _Error4); + return _createClass(NoSignatureNeededError); + }(_wrapNativeSuper(Error)), + NoUnsignedNonInvokerAuthEntries: function (_Error5) { + function NoUnsignedNonInvokerAuthEntriesError() { + _classCallCheck(this, NoUnsignedNonInvokerAuthEntriesError); + return _callSuper(this, NoUnsignedNonInvokerAuthEntriesError, arguments); + } + _inherits(NoUnsignedNonInvokerAuthEntriesError, _Error5); + return _createClass(NoUnsignedNonInvokerAuthEntriesError); + }(_wrapNativeSuper(Error)), + NoSigner: function (_Error6) { + function NoSignerError() { + _classCallCheck(this, NoSignerError); + return _callSuper(this, NoSignerError, arguments); + } + _inherits(NoSignerError, _Error6); + return _createClass(NoSignerError); + }(_wrapNativeSuper(Error)), + NotYetSimulated: function (_Error7) { + function NotYetSimulatedError() { + _classCallCheck(this, NotYetSimulatedError); + return _callSuper(this, NotYetSimulatedError, arguments); + } + _inherits(NotYetSimulatedError, _Error7); + return _createClass(NotYetSimulatedError); + }(_wrapNativeSuper(Error)), + FakeAccount: function (_Error8) { + function FakeAccountError() { + _classCallCheck(this, FakeAccountError); + return _callSuper(this, FakeAccountError, arguments); + } + _inherits(FakeAccountError, _Error8); + return _createClass(FakeAccountError); + }(_wrapNativeSuper(Error)), + SimulationFailed: function (_Error9) { + function SimulationFailedError() { + _classCallCheck(this, SimulationFailedError); + return _callSuper(this, SimulationFailedError, arguments); + } + _inherits(SimulationFailedError, _Error9); + return _createClass(SimulationFailedError); + }(_wrapNativeSuper(Error)), + InternalWalletError: function (_Error10) { + function InternalWalletError() { + _classCallCheck(this, InternalWalletError); + return _callSuper(this, InternalWalletError, arguments); + } + _inherits(InternalWalletError, _Error10); + return _createClass(InternalWalletError); + }(_wrapNativeSuper(Error)), + ExternalServiceError: function (_Error11) { + function ExternalServiceError() { + _classCallCheck(this, ExternalServiceError); + return _callSuper(this, ExternalServiceError, arguments); + } + _inherits(ExternalServiceError, _Error11); + return _createClass(ExternalServiceError); + }(_wrapNativeSuper(Error)), + InvalidClientRequest: function (_Error12) { + function InvalidClientRequestError() { + _classCallCheck(this, InvalidClientRequestError); + return _callSuper(this, InvalidClientRequestError, arguments); + } + _inherits(InvalidClientRequestError, _Error12); + return _createClass(InvalidClientRequestError); + }(_wrapNativeSuper(Error)), + UserRejected: function (_Error13) { + function UserRejectedError() { + _classCallCheck(this, UserRejectedError); + return _callSuper(this, UserRejectedError, arguments); + } + _inherits(UserRejectedError, _Error13); + return _createClass(UserRejectedError); + }(_wrapNativeSuper(Error)) +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/basic_node_signer.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/basic_node_signer.d.ts new file mode 100644 index 000000000..b82cc36f3 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/basic_node_signer.d.ts @@ -0,0 +1,18 @@ +import { Keypair } from "@stellar/stellar-base"; +import { SignAuthEntry, SignTransaction } from "./types"; +/** + * For use with {@link Client} and {@link module:contract.AssembledTransaction}. + * Implements `signTransaction` and `signAuthEntry` with signatures expected by + * those classes. This is useful for testing and maybe some simple Node + * applications. Feel free to use this as a starting point for your own + * Wallet/TransactionSigner implementation. + * + * @memberof module:contract + * + * @param {Keypair} keypair {@link Keypair} to use to sign the transaction or auth entry + * @param {string} networkPassphrase passphrase of network to sign for + */ +export declare const basicNodeSigner: (keypair: Keypair, networkPassphrase: string) => { + signTransaction: SignTransaction; + signAuthEntry: SignAuthEntry; +}; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/basic_node_signer.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/basic_node_signer.js new file mode 100644 index 000000000..b91d3149a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/basic_node_signer.js @@ -0,0 +1,60 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.basicNodeSigner = void 0; +var _stellarBase = require("@stellar/stellar-base"); +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +var basicNodeSigner = exports.basicNodeSigner = function basicNodeSigner(keypair, networkPassphrase) { + return { + signTransaction: function () { + var _signTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(xdr, opts) { + var t; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + t = _stellarBase.TransactionBuilder.fromXDR(xdr, (opts === null || opts === void 0 ? void 0 : opts.networkPassphrase) || networkPassphrase); + t.sign(keypair); + return _context.abrupt("return", { + signedTxXdr: t.toXDR(), + signerAddress: keypair.publicKey() + }); + case 3: + case "end": + return _context.stop(); + } + }, _callee); + })); + function signTransaction(_x, _x2) { + return _signTransaction.apply(this, arguments); + } + return signTransaction; + }(), + signAuthEntry: function () { + var _signAuthEntry = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(authEntry) { + var signedAuthEntry; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + signedAuthEntry = keypair.sign((0, _stellarBase.hash)(Buffer.from(authEntry, "base64"))).toString("base64"); + return _context2.abrupt("return", { + signedAuthEntry: signedAuthEntry, + signerAddress: keypair.publicKey() + }); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function signAuthEntry(_x3) { + return _signAuthEntry.apply(this, arguments); + } + return signAuthEntry; + }() + }; +}; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/client.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/client.d.ts new file mode 100644 index 000000000..c41fb7d25 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/client.d.ts @@ -0,0 +1,64 @@ +import { Spec } from "./spec"; +import { AssembledTransaction } from "./assembled_transaction"; +import type { ClientOptions, MethodOptions } from "./types"; +/** + * Generate a class from the contract spec that where each contract method + * gets included with an identical name. + * + * Each method returns an {@link module:contract.AssembledTransaction | AssembledTransaction} that can + * be used to modify, simulate, decode results, and possibly sign, & submit the + * transaction. + * + * @memberof module:contract + * + * @class + * @param {module:contract.Spec} spec {@link Spec} to construct a Client for + * @param {ClientOptions} options see {@link ClientOptions} + */ +export declare class Client { + readonly spec: Spec; + readonly options: ClientOptions; + static deploy( + /** Constructor/Initialization Args for the contract's `__constructor` method */ + args: Record | null, + /** Options for initalizing a Client as well as for calling a method, with extras specific to deploying. */ + options: MethodOptions & Omit & { + /** The hash of the Wasm blob, which must already be installed on-chain. */ + wasmHash: Buffer | string; + /** Salt used to generate the contract's ID. Passed through to {@link Operation.createCustomContract}. Default: random. */ + salt?: Buffer | Uint8Array; + /** The format used to decode `wasmHash`, if it's provided as a string. */ + format?: "hex" | "base64"; + }): Promise>; + constructor(spec: Spec, options: ClientOptions); + /** + * Generates a Client instance from the provided ClientOptions and the contract's wasm hash. + * The wasmHash can be provided in either hex or base64 format. + * + * @param {Buffer | string} wasmHash The hash of the contract's wasm binary, in either hex or base64 format. + * @param {ClientOptions} options The ClientOptions object containing the necessary configuration, including the rpcUrl. + * @param {('hex' | 'base64')} [format='hex'] The format of the provided wasmHash, either "hex" or "base64". Defaults to "hex". + * @returns {Promise} A Promise that resolves to a Client instance. + * @throws {TypeError} If the provided options object does not contain an rpcUrl. + */ + static fromWasmHash(wasmHash: Buffer | string, options: ClientOptions, format?: "hex" | "base64"): Promise; + /** + * Generates a Client instance from the provided ClientOptions and the contract's wasm binary. + * + * @param {Buffer} wasm The contract's wasm binary as a Buffer. + * @param {ClientOptions} options The ClientOptions object containing the necessary configuration. + * @returns {Promise} A Promise that resolves to a Client instance. + * @throws {Error} If the contract spec cannot be obtained from the provided wasm binary. + */ + static fromWasm(wasm: Buffer, options: ClientOptions): Promise; + /** + * Generates a Client instance from the provided ClientOptions, which must include the contractId and rpcUrl. + * + * @param {ClientOptions} options The ClientOptions object containing the necessary configuration, including the contractId and rpcUrl. + * @returns {Promise} A Promise that resolves to a Client instance. + * @throws {TypeError} If the provided options object does not contain both rpcUrl and contractId. + */ + static from(options: ClientOptions): Promise; + txFromJSON: (json: string) => AssembledTransaction; + txFromXDR: (xdrBase64: string) => AssembledTransaction; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/client.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/client.js new file mode 100644 index 000000000..4caa08ec6 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/client.js @@ -0,0 +1,291 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Client = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _spec = require("./spec"); +var _rpc = require("../rpc"); +var _assembled_transaction = require("./assembled_transaction"); +var _utils = require("./utils"); +var _excluded = ["method"], + _excluded2 = ["wasmHash", "salt", "format", "fee", "timeoutInSeconds", "simulate"]; +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } +function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +var CONSTRUCTOR_FUNC = "__constructor"; +function specFromWasm(_x) { + return _specFromWasm.apply(this, arguments); +} +function _specFromWasm() { + _specFromWasm = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(wasm) { + var wasmModule, xdrSections, bufferSection, specEntryArray, spec; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return WebAssembly.compile(wasm); + case 2: + wasmModule = _context5.sent; + xdrSections = WebAssembly.Module.customSections(wasmModule, "contractspecv0"); + if (!(xdrSections.length === 0)) { + _context5.next = 6; + break; + } + throw new Error("Could not obtain contract spec from wasm"); + case 6: + bufferSection = Buffer.from(xdrSections[0]); + specEntryArray = (0, _utils.processSpecEntryStream)(bufferSection); + spec = new _spec.Spec(specEntryArray); + return _context5.abrupt("return", spec); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _specFromWasm.apply(this, arguments); +} +function specFromWasmHash(_x2, _x3) { + return _specFromWasmHash.apply(this, arguments); +} +function _specFromWasmHash() { + _specFromWasmHash = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + format = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context6.next = 3; + break; + } + throw new TypeError("options must contain rpcUrl"); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new _rpc.Server(rpcUrl, serverOpts); + _context6.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context6.sent; + return _context6.abrupt("return", specFromWasm(wasm)); + case 10: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _specFromWasmHash.apply(this, arguments); +} +var Client = exports.Client = function () { + function Client(spec, options) { + var _this = this; + _classCallCheck(this, Client); + _defineProperty(this, "txFromJSON", function (json) { + var _JSON$parse = JSON.parse(json), + method = _JSON$parse.method, + tx = _objectWithoutProperties(_JSON$parse, _excluded); + return _assembled_transaction.AssembledTransaction.fromJSON(_objectSpread(_objectSpread({}, _this.options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return _this.spec.funcResToNative(method, result); + } + }), tx); + }); + _defineProperty(this, "txFromXDR", function (xdrBase64) { + return _assembled_transaction.AssembledTransaction.fromXDR(_this.options, xdrBase64, _this.spec); + }); + this.spec = spec; + this.options = options; + this.spec.funcs().forEach(function (xdrFn) { + var method = xdrFn.name().toString(); + if (method === CONSTRUCTOR_FUNC) { + return; + } + var assembleTransaction = function assembleTransaction(args, methodOptions) { + return _assembled_transaction.AssembledTransaction.build(_objectSpread(_objectSpread(_objectSpread({ + method: method, + args: args && spec.funcArgsToScVals(method, args) + }, options), methodOptions), {}, { + errorTypes: spec.errorCases().reduce(function (acc, curr) { + return _objectSpread(_objectSpread({}, acc), {}, _defineProperty({}, curr.value(), { + message: curr.doc().toString() + })); + }, {}), + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + }; + _this[method] = spec.getFunc(method).inputs().length === 0 ? function (opts) { + return assembleTransaction(undefined, opts); + } : assembleTransaction; + }); + } + return _createClass(Client, null, [{ + key: "deploy", + value: function () { + var _deploy = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(args, options) { + var wasmHash, salt, format, fee, timeoutInSeconds, simulate, clientOptions, spec, operation; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + wasmHash = options.wasmHash, salt = options.salt, format = options.format, fee = options.fee, timeoutInSeconds = options.timeoutInSeconds, simulate = options.simulate, clientOptions = _objectWithoutProperties(options, _excluded2); + _context.next = 3; + return specFromWasmHash(wasmHash, clientOptions, format); + case 3: + spec = _context.sent; + operation = _stellarBase.Operation.createCustomContract({ + address: new _stellarBase.Address(options.publicKey), + wasmHash: typeof wasmHash === "string" ? Buffer.from(wasmHash, format !== null && format !== void 0 ? format : "hex") : wasmHash, + salt: salt, + constructorArgs: args ? spec.funcArgsToScVals(CONSTRUCTOR_FUNC, args) : [] + }); + return _context.abrupt("return", _assembled_transaction.AssembledTransaction.buildWithOp(operation, _objectSpread(_objectSpread({ + fee: fee, + timeoutInSeconds: timeoutInSeconds, + simulate: simulate + }, clientOptions), {}, { + contractId: "ignored", + method: CONSTRUCTOR_FUNC, + parseResultXdr: function parseResultXdr(result) { + return new Client(spec, _objectSpread(_objectSpread({}, clientOptions), {}, { + contractId: _stellarBase.Address.fromScVal(result).toString() + })); + } + }))); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + function deploy(_x4, _x5) { + return _deploy.apply(this, arguments); + } + return deploy; + }() + }, { + key: "fromWasmHash", + value: (function () { + var _fromWasmHash = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args2 = arguments; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + format = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context2.next = 3; + break; + } + throw new TypeError('options must contain rpcUrl'); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new _rpc.Server(rpcUrl, serverOpts); + _context2.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context2.sent; + return _context2.abrupt("return", Client.fromWasm(wasm, options)); + case 10: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function fromWasmHash(_x6, _x7) { + return _fromWasmHash.apply(this, arguments); + } + return fromWasmHash; + }()) + }, { + key: "fromWasm", + value: (function () { + var _fromWasm = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(wasm, options) { + var spec; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return specFromWasm(wasm); + case 2: + spec = _context3.sent; + return _context3.abrupt("return", new Client(spec, options)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + function fromWasm(_x8, _x9) { + return _fromWasm.apply(this, arguments); + } + return fromWasm; + }()) + }, { + key: "from", + value: (function () { + var _from = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(options) { + var rpcUrl, contractId, allowHttp, serverOpts, server, wasm; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(!options || !options.rpcUrl || !options.contractId)) { + _context4.next = 2; + break; + } + throw new TypeError('options must contain rpcUrl and contractId'); + case 2: + rpcUrl = options.rpcUrl, contractId = options.contractId, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new _rpc.Server(rpcUrl, serverOpts); + _context4.next = 7; + return server.getContractWasmByContractId(contractId); + case 7: + wasm = _context4.sent; + return _context4.abrupt("return", Client.fromWasm(wasm, options)); + case 9: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function from(_x10) { + return _from.apply(this, arguments); + } + return from; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/index.d.ts new file mode 100644 index 000000000..8b9e1dc5e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/index.d.ts @@ -0,0 +1,7 @@ +export * from "./assembled_transaction"; +export * from "./basic_node_signer"; +export * from "./client"; +export * from "./rust_result"; +export * from "./sent_transaction"; +export * from "./spec"; +export * from "./types"; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/index.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/index.js new file mode 100644 index 000000000..9a10eddfc --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/index.js @@ -0,0 +1,82 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _assembled_transaction = require("./assembled_transaction"); +Object.keys(_assembled_transaction).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _assembled_transaction[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _assembled_transaction[key]; + } + }); +}); +var _basic_node_signer = require("./basic_node_signer"); +Object.keys(_basic_node_signer).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _basic_node_signer[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _basic_node_signer[key]; + } + }); +}); +var _client = require("./client"); +Object.keys(_client).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _client[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _client[key]; + } + }); +}); +var _rust_result = require("./rust_result"); +Object.keys(_rust_result).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _rust_result[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _rust_result[key]; + } + }); +}); +var _sent_transaction = require("./sent_transaction"); +Object.keys(_sent_transaction).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _sent_transaction[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _sent_transaction[key]; + } + }); +}); +var _spec = require("./spec"); +Object.keys(_spec).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _spec[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _spec[key]; + } + }); +}); +var _types = require("./types"); +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _types[key]; + } + }); +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/rust_result.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/rust_result.d.ts new file mode 100644 index 000000000..f72a123e1 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/rust_result.d.ts @@ -0,0 +1,81 @@ +/** + * A minimal implementation of Rust's `Result` type. Used for contract + * methods that return Results, to maintain their distinction from methods + * that simply either return a value or throw. + * + * #### Why is this needed? + * + * This is used by {@link module:contract.Spec | `ContractSpec`} and + * {@link module:contract.AssembledTransaction | `AssembledTransaction`} when + * parsing values return by contracts. + * + * Contract methods can be implemented to return simple values, in which case + * they can also throw errors. This matches JavaScript's most idiomatic + * workflow, using `try...catch` blocks. + * + * But Rust also gives the flexibility of returning `Result` types. And Soroban + * contracts further support this with the `#[contracterror]` macro. Should + * JavaScript calls to such methods ignore all of that, and just flatten this + * extra info down to the same `try...catch` flow as other methods? We're not + * sure. + * + * For now, we've added this minimal implementation of Rust's `Result` logic, + * which exports the `Result` interface and its associated implementations, + * `Ok` and `Err`. This allows `ContractSpec` and `AssembledTransaction` to + * work together to duplicate the contract's Rust logic, always returning + * `Result` types for contract methods that are implemented to do so. + * + * In the future, if this feels too un-idiomatic for JavaScript, we can always + * remove this and flatten all JS calls to `try...catch`. Easier to remove this + * logic later than it would be to add it. + * + * @memberof module:contract + */ +export interface Result { + unwrap(): T; + unwrapErr(): E; + isOk(): boolean; + isErr(): boolean; +} +/** + * Error interface containing the error message. Matches Rust's implementation. + * Part of implementing {@link module:contract.Result | Result}, a minimal + * implementation of Rust's `Result` type. Used for contract methods that return + * Results, to maintain their distinction from methods that simply either return + * a value or throw. + * + * @memberof module:contract + */ +export interface ErrorMessage { + message: string; +} +/** + * Part of implementing {@link module:contract.Result | Result}, a minimal + * implementation of Rust's `Result` type. Used for contract methods that return + * Results, to maintain their distinction from methods that simply either return + * a value or throw. + * @private + */ +export declare class Ok implements Result { + readonly value: T; + constructor(value: T); + unwrapErr(): never; + unwrap(): T; + isOk(): boolean; + isErr(): boolean; +} +/** + * Part of implementing {@link module:contract.Result | Result}, a minimal + * implementation of Rust's `Result` type. Used for contract methods that return + * Results, to maintain their distinction from methods that simply either return + * a value or throw. + * @private + */ +export declare class Err implements Result { + readonly error: E; + constructor(error: E); + unwrapErr(): E; + unwrap(): never; + isOk(): boolean; + isErr(): boolean; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/rust_result.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/rust_result.js new file mode 100644 index 000000000..5cbad1179 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/rust_result.js @@ -0,0 +1,66 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Ok = exports.Err = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Ok = exports.Ok = function () { + function Ok(value) { + _classCallCheck(this, Ok); + this.value = value; + } + return _createClass(Ok, [{ + key: "unwrapErr", + value: function unwrapErr() { + throw new Error("No error"); + } + }, { + key: "unwrap", + value: function unwrap() { + return this.value; + } + }, { + key: "isOk", + value: function isOk() { + return true; + } + }, { + key: "isErr", + value: function isErr() { + return false; + } + }]); +}(); +var Err = exports.Err = function () { + function Err(error) { + _classCallCheck(this, Err); + this.error = error; + } + return _createClass(Err, [{ + key: "unwrapErr", + value: function unwrapErr() { + return this.error; + } + }, { + key: "unwrap", + value: function unwrap() { + throw new Error(this.error.message); + } + }, { + key: "isOk", + value: function isOk() { + return false; + } + }, { + key: "isErr", + value: function isErr() { + return true; + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/sent_transaction.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/sent_transaction.d.ts new file mode 100644 index 000000000..ab3234a2d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/sent_transaction.d.ts @@ -0,0 +1,84 @@ +import { Server } from "../rpc"; +import { Api } from "../rpc/api"; +import type { AssembledTransaction } from "./assembled_transaction"; +/** + * A transaction that has been sent to the Soroban network. This happens in two steps: + * + * 1. `sendTransaction`: initial submission of the transaction to the network. + * If this step runs into problems, the attempt to sign and send will be + * aborted. You can see the result of this call in the + * `sendTransactionResponse` getter. + * 2. `getTransaction`: once the transaction has been submitted to the network + * successfully, you need to wait for it to finalize to get the result of the + * transaction. This will be retried with exponential backoff for + * {@link MethodOptions.timeoutInSeconds} seconds. See all attempts in + * `getTransactionResponseAll` and the most recent attempt in + * `getTransactionResponse`. + * + * @memberof module:contract + * @class + * + * @param {Function} signTransaction More info in {@link MethodOptions} + * @param {module:contract.AssembledTransaction} assembled {@link AssembledTransaction} from which this SentTransaction was initialized + */ +export declare class SentTransaction { + assembled: AssembledTransaction; + server: Server; + /** + * The result of calling `sendTransaction` to broadcast the transaction to the + * network. + */ + sendTransactionResponse?: Api.SendTransactionResponse; + /** + * If `sendTransaction` completes successfully (which means it has `status: 'PENDING'`), + * then `getTransaction` will be called in a loop for + * {@link MethodOptions.timeoutInSeconds} seconds. This array contains all + * the results of those calls. + */ + getTransactionResponseAll?: Api.GetTransactionResponse[]; + /** + * The most recent result of calling `getTransaction`, from the + * `getTransactionResponseAll` array. + */ + getTransactionResponse?: Api.GetTransactionResponse; + static Errors: { + SendFailed: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + SendResultOnly: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + TransactionStillPending: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + }; + constructor(assembled: AssembledTransaction); + /** + * Initialize a `SentTransaction` from `options` and a `signed` + * AssembledTransaction. This will also send the transaction to the network. + */ + static init: (assembled: AssembledTransaction) => Promise>; + private send; + get result(): T; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/sent_transaction.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/sent_transaction.js new file mode 100644 index 000000000..03d0948b5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/sent_transaction.js @@ -0,0 +1,151 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SentTransaction = void 0; +var _rpc = require("../rpc"); +var _api = require("../rpc/api"); +var _utils = require("./utils"); +var _types = require("./types"); +var _SentTransaction; +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var SentTransaction = exports.SentTransaction = function () { + function SentTransaction(assembled) { + var _this = this, + _this$assembled$optio2; + _classCallCheck(this, SentTransaction); + _defineProperty(this, "send", _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var _this$assembled$optio; + var hash, timeoutInSeconds; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return _this.server.sendTransaction(_this.assembled.signed); + case 2: + _this.sendTransactionResponse = _context.sent; + if (!(_this.sendTransactionResponse.status !== "PENDING")) { + _context.next = 5; + break; + } + throw new SentTransaction.Errors.SendFailed("Sending the transaction to the network failed!\n".concat(JSON.stringify(_this.sendTransactionResponse, null, 2))); + case 5: + hash = _this.sendTransactionResponse.hash; + timeoutInSeconds = (_this$assembled$optio = _this.assembled.options.timeoutInSeconds) !== null && _this$assembled$optio !== void 0 ? _this$assembled$optio : _types.DEFAULT_TIMEOUT; + _context.next = 9; + return (0, _utils.withExponentialBackoff)(function () { + return _this.server.getTransaction(hash); + }, function (resp) { + return resp.status === _api.Api.GetTransactionStatus.NOT_FOUND; + }, timeoutInSeconds); + case 9: + _this.getTransactionResponseAll = _context.sent; + _this.getTransactionResponse = _this.getTransactionResponseAll[_this.getTransactionResponseAll.length - 1]; + if (!(_this.getTransactionResponse.status === _api.Api.GetTransactionStatus.NOT_FOUND)) { + _context.next = 13; + break; + } + throw new SentTransaction.Errors.TransactionStillPending("Waited ".concat(timeoutInSeconds, " seconds for transaction to complete, but it did not. ") + "Returning anyway. Check the transaction status manually. " + "Sent transaction: ".concat(JSON.stringify(_this.sendTransactionResponse, null, 2), "\n") + "All attempts to get the result: ".concat(JSON.stringify(_this.getTransactionResponseAll, null, 2))); + case 13: + return _context.abrupt("return", _this); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + }))); + this.assembled = assembled; + this.server = new _rpc.Server(this.assembled.options.rpcUrl, { + allowHttp: (_this$assembled$optio2 = this.assembled.options.allowHttp) !== null && _this$assembled$optio2 !== void 0 ? _this$assembled$optio2 : false + }); + } + return _createClass(SentTransaction, [{ + key: "result", + get: function get() { + if ("getTransactionResponse" in this && this.getTransactionResponse) { + if ("returnValue" in this.getTransactionResponse) { + return this.assembled.options.parseResultXdr(this.getTransactionResponse.returnValue); + } + throw new Error("Transaction failed! Cannot parse result."); + } + if (this.sendTransactionResponse) { + var _this$sendTransaction; + var errorResult = (_this$sendTransaction = this.sendTransactionResponse.errorResult) === null || _this$sendTransaction === void 0 ? void 0 : _this$sendTransaction.result(); + if (errorResult) { + throw new SentTransaction.Errors.SendFailed("Transaction simulation looked correct, but attempting to send the transaction failed. Check `simulation` and `sendTransactionResponseAll` to troubleshoot. Decoded `sendTransactionResponse.errorResultXdr`: ".concat(errorResult)); + } + throw new SentTransaction.Errors.SendResultOnly("Transaction was sent to the network, but not yet awaited. No result to show. Await transaction completion with `getTransaction(sendTransactionResponse.hash)`"); + } + throw new Error("Sending transaction failed: ".concat(JSON.stringify(this.assembled.signed))); + } + }]); +}(); +_SentTransaction = SentTransaction; +_defineProperty(SentTransaction, "Errors", { + SendFailed: function (_Error) { + function SendFailedError() { + _classCallCheck(this, SendFailedError); + return _callSuper(this, SendFailedError, arguments); + } + _inherits(SendFailedError, _Error); + return _createClass(SendFailedError); + }(_wrapNativeSuper(Error)), + SendResultOnly: function (_Error2) { + function SendResultOnlyError() { + _classCallCheck(this, SendResultOnlyError); + return _callSuper(this, SendResultOnlyError, arguments); + } + _inherits(SendResultOnlyError, _Error2); + return _createClass(SendResultOnlyError); + }(_wrapNativeSuper(Error)), + TransactionStillPending: function (_Error3) { + function TransactionStillPendingError() { + _classCallCheck(this, TransactionStillPendingError); + return _callSuper(this, TransactionStillPendingError, arguments); + } + _inherits(TransactionStillPendingError, _Error3); + return _createClass(TransactionStillPendingError); + }(_wrapNativeSuper(Error)) +}); +_defineProperty(SentTransaction, "init", function () { + var _ref2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(assembled) { + var tx, sent; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + tx = new _SentTransaction(assembled); + _context2.next = 3; + return tx.send(); + case 3: + sent = _context2.sent; + return _context2.abrupt("return", sent); + case 5: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; +}()); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/spec.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/spec.d.ts new file mode 100644 index 000000000..737c8c464 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/spec.d.ts @@ -0,0 +1,152 @@ +import type { JSONSchema7 } from "json-schema"; +import { xdr } from "@stellar/stellar-base"; +export interface Union { + tag: string; + values?: T; +} +/** + * Provides a ContractSpec class which can contains the XDR types defined by the contract. + * This allows the class to be used to convert between native and raw `xdr.ScVal`s. + * + * Constructs a new ContractSpec from an array of XDR spec entries. + * + * @memberof module:contract + * @param {xdr.ScSpecEntry[] | string[]} entries the XDR spec entries + * @throws {Error} if entries is invalid + * + * @example + * const specEntries = [...]; // XDR spec entries of a smart contract + * const contractSpec = new ContractSpec(specEntries); + * + * // Convert native value to ScVal + * const args = { + * arg1: 'value1', + * arg2: 1234 + * }; + * const scArgs = contractSpec.funcArgsToScVals('funcName', args); + * + * // Call contract + * const resultScv = await callContract(contractId, 'funcName', scArgs); + * + * // Convert result ScVal back to native value + * const result = contractSpec.funcResToNative('funcName', resultScv); + * + * console.log(result); // {success: true} + */ +export declare class Spec { + /** + * The XDR spec entries. + */ + entries: xdr.ScSpecEntry[]; + constructor(entries: xdr.ScSpecEntry[] | string[]); + /** + * Gets the XDR functions from the spec. + * @returns {xdr.ScSpecFunctionV0[]} all contract functions + */ + funcs(): xdr.ScSpecFunctionV0[]; + /** + * Gets the XDR function spec for the given function name. + * + * @param {string} name the name of the function + * @returns {xdr.ScSpecFunctionV0} the function spec + * + * @throws {Error} if no function with the given name exists + */ + getFunc(name: string): xdr.ScSpecFunctionV0; + /** + * Converts native JS arguments to ScVals for calling a contract function. + * + * @param {string} name the name of the function + * @param {object} args the arguments object + * @returns {xdr.ScVal[]} the converted arguments + * + * @throws {Error} if argument is missing or incorrect type + * + * @example + * const args = { + * arg1: 'value1', + * arg2: 1234 + * }; + * const scArgs = contractSpec.funcArgsToScVals('funcName', args); + */ + funcArgsToScVals(name: string, args: object): xdr.ScVal[]; + /** + * Converts the result ScVal of a function call to a native JS value. + * + * @param {string} name the name of the function + * @param {xdr.ScVal | string} val_or_base64 the result ScVal or base64 encoded string + * @returns {any} the converted native value + * + * @throws {Error} if return type mismatch or invalid input + * + * @example + * const resultScv = 'AAA=='; // Base64 encoded ScVal + * const result = contractSpec.funcResToNative('funcName', resultScv); + */ + funcResToNative(name: string, val_or_base64: xdr.ScVal | string): any; + /** + * Finds the XDR spec entry for the given name. + * + * @param {string} name the name to find + * @returns {xdr.ScSpecEntry} the entry + * + * @throws {Error} if no entry with the given name exists + */ + findEntry(name: string): xdr.ScSpecEntry; + /** + * Converts a native JS value to an ScVal based on the given type. + * + * @param {any} val the native JS value + * @param {xdr.ScSpecTypeDef} [ty] the expected type + * @returns {xdr.ScVal} the converted ScVal + * + * @throws {Error} if value cannot be converted to the given type + */ + nativeToScVal(val: any, ty: xdr.ScSpecTypeDef): xdr.ScVal; + private nativeToUdt; + private nativeToUnion; + private nativeToStruct; + private nativeToEnum; + /** + * Converts an base64 encoded ScVal back to a native JS value based on the given type. + * + * @param {string} scv the base64 encoded ScVal + * @param {xdr.ScSpecTypeDef} typeDef the expected type + * @returns {any} the converted native JS value + * + * @throws {Error} if ScVal cannot be converted to the given type + */ + scValStrToNative(scv: string, typeDef: xdr.ScSpecTypeDef): T; + /** + * Converts an ScVal back to a native JS value based on the given type. + * + * @param {xdr.ScVal} scv the ScVal + * @param {xdr.ScSpecTypeDef} typeDef the expected type + * @returns {any} the converted native JS value + * + * @throws {Error} if ScVal cannot be converted to the given type + */ + scValToNative(scv: xdr.ScVal, typeDef: xdr.ScSpecTypeDef): T; + private scValUdtToNative; + private unionToNative; + private structToNative; + private enumToNative; + /** + * Gets the XDR error cases from the spec. + * + * @returns {xdr.ScSpecFunctionV0[]} all contract functions + * + */ + errorCases(): xdr.ScSpecUdtErrorEnumCaseV0[]; + /** + * Converts the contract spec to a JSON schema. + * + * If `funcName` is provided, the schema will be a reference to the function schema. + * + * @param {string} [funcName] the name of the function to convert + * @returns {JSONSchema7} the converted JSON schema + * + * @throws {Error} if the contract spec is invalid + */ + jsonSchema(funcName?: string): JSONSchema7; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/spec.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/spec.js new file mode 100644 index 000000000..1a70b3d2f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/spec.js @@ -0,0 +1,1020 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Spec = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _rust_result = require("./rust_result"); +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function enumToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + var title = aCase.name().toString(); + var desc = aCase.doc().toString(); + oneOf.push({ + description: desc, + title: title, + enum: [aCase.value()], + type: "number" + }); + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +function isNumeric(field) { + return /^\d+$/.test(field.name().toString()); +} +function readObj(args, input) { + var inputName = input.name().toString(); + var entry = Object.entries(args).find(function (_ref) { + var _ref2 = _slicedToArray(_ref, 1), + name = _ref2[0]; + return name === inputName; + }); + if (!entry) { + throw new Error("Missing field ".concat(inputName)); + } + return entry[1]; +} +function findCase(name) { + return function matches(entry) { + switch (entry.switch().value) { + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var tuple = entry.tupleCase(); + return tuple.name().toString() === name; + } + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var voidCase = entry.voidCase(); + return voidCase.name().toString() === name; + } + default: + return false; + } + }; +} +function stringToScVal(str, ty) { + switch (ty.value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeString().value: + return _stellarBase.xdr.ScVal.scvString(str); + case _stellarBase.xdr.ScSpecType.scSpecTypeSymbol().value: + return _stellarBase.xdr.ScVal.scvSymbol(str); + case _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value: + { + var addr = _stellarBase.Address.fromString(str); + return _stellarBase.xdr.ScVal.scvAddress(addr.toScAddress()); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU64().value: + return new _stellarBase.XdrLargeInt("u64", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeI64().value: + return new _stellarBase.XdrLargeInt("i64", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeU128().value: + return new _stellarBase.XdrLargeInt("u128", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeI128().value: + return new _stellarBase.XdrLargeInt("i128", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeU256().value: + return new _stellarBase.XdrLargeInt("u256", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeI256().value: + return new _stellarBase.XdrLargeInt("i256", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeBytes().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeBytesN().value: + return _stellarBase.xdr.ScVal.scvBytes(Buffer.from(str, "base64")); + default: + throw new TypeError("invalid type ".concat(ty.name, " specified for string value")); + } +} +var PRIMITIVE_DEFINITONS = { + U32: { + type: "integer", + minimum: 0, + maximum: 4294967295 + }, + I32: { + type: "integer", + minimum: -2147483648, + maximum: 2147483647 + }, + U64: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 20 + }, + I64: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 21 + }, + U128: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 39 + }, + I128: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 40 + }, + U256: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 78 + }, + I256: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 79 + }, + Address: { + type: "string", + format: "address", + description: "Address can be a public key or contract id" + }, + ScString: { + type: "string", + description: "ScString is a string" + }, + ScSymbol: { + type: "string", + description: "ScString is a string" + }, + DataUrl: { + type: "string", + pattern: "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$" + } +}; +function typeRef(typeDef) { + var t = typeDef.switch(); + var value = t.value; + var ref; + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVal().value: + { + ref = "Val"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBool().value: + { + return { + type: "boolean" + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeVoid().value: + { + return { + type: "null" + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeError().value: + { + ref = "Error"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU32().value: + { + ref = "U32"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI32().value: + { + ref = "I32"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU64().value: + { + ref = "U64"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI64().value: + { + ref = "I64"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeTimepoint().value: + { + throw new Error("Timepoint type not supported"); + ref = "Timepoint"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeDuration().value: + { + throw new Error("Duration not supported"); + ref = "Duration"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU128().value: + { + ref = "U128"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI128().value: + { + ref = "I128"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU256().value: + { + ref = "U256"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI256().value: + { + ref = "I256"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBytes().value: + { + ref = "DataUrl"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeString().value: + { + ref = "ScString"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeSymbol().value: + { + ref = "ScSymbol"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value: + { + ref = "Address"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeOption().value: + { + var opt = typeDef.option(); + return typeRef(opt.valueType()); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeResult().value: + { + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeVec().value: + { + var arr = typeDef.vec(); + var reference = typeRef(arr.elementType()); + return { + type: "array", + items: reference + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = typeDef.map(); + var items = [typeRef(map.keyType()), typeRef(map.valueType())]; + return { + type: "array", + items: { + type: "array", + items: items, + minItems: 2, + maxItems: 2 + } + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tuple = typeDef.tuple(); + var minItems = tuple.valueTypes().length; + var maxItems = minItems; + var _items = tuple.valueTypes().map(typeRef); + return { + type: "array", + items: _items, + minItems: minItems, + maxItems: maxItems + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var _arr = typeDef.bytesN(); + return { + $ref: "#/definitions/DataUrl", + maxLength: _arr.n() + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeUdt().value: + { + var udt = typeDef.udt(); + ref = udt.name().toString(); + break; + } + } + return { + $ref: "#/definitions/".concat(ref) + }; +} +function isRequired(typeDef) { + return typeDef.switch().value !== _stellarBase.xdr.ScSpecType.scSpecTypeOption().value; +} +function argsAndRequired(input) { + var properties = {}; + var required = []; + input.forEach(function (arg) { + var aType = arg.type(); + var name = arg.name().toString(); + properties[name] = typeRef(aType); + if (isRequired(aType)) { + required.push(name); + } + }); + var res = { + properties: properties + }; + if (required.length > 0) { + res.required = required; + } + return res; +} +function structToJsonSchema(udt) { + var fields = udt.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + var items = fields.map(function (_, i) { + return typeRef(fields[i].type()); + }); + return { + type: "array", + items: items, + minItems: fields.length, + maxItems: fields.length + }; + } + var description = udt.doc().toString(); + var _argsAndRequired = argsAndRequired(fields), + properties = _argsAndRequired.properties, + required = _argsAndRequired.required; + properties.additionalProperties = false; + return { + description: description, + properties: properties, + required: required, + type: "object" + }; +} +function functionToJsonSchema(func) { + var _argsAndRequired2 = argsAndRequired(func.inputs()), + properties = _argsAndRequired2.properties, + required = _argsAndRequired2.required; + var args = { + additionalProperties: false, + properties: properties, + type: "object" + }; + if ((required === null || required === void 0 ? void 0 : required.length) > 0) { + args.required = required; + } + var input = { + properties: { + args: args + } + }; + var outputs = func.outputs(); + var output = outputs.length > 0 ? typeRef(outputs[0]) : typeRef(_stellarBase.xdr.ScSpecTypeDef.scSpecTypeVoid()); + var description = func.doc().toString(); + if (description.length > 0) { + input.description = description; + } + input.additionalProperties = false; + output.additionalProperties = false; + return { + input: input, + output: output + }; +} +function unionToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + switch (aCase.switch().value) { + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var c = aCase.voidCase(); + var title = c.name().toString(); + oneOf.push({ + type: "object", + title: title, + properties: { + tag: title + }, + additionalProperties: false, + required: ["tag"] + }); + break; + } + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var _c = aCase.tupleCase(); + var _title = _c.name().toString(); + oneOf.push({ + type: "object", + title: _title, + properties: { + tag: _title, + values: { + type: "array", + items: _c.type().map(typeRef) + } + }, + required: ["tag", "values"], + additionalProperties: false + }); + } + } + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +var Spec = exports.Spec = function () { + function Spec(entries) { + _classCallCheck(this, Spec); + _defineProperty(this, "entries", []); + if (entries.length === 0) { + throw new Error("Contract spec must have at least one entry"); + } + var entry = entries[0]; + if (typeof entry === "string") { + this.entries = entries.map(function (s) { + return _stellarBase.xdr.ScSpecEntry.fromXDR(s, "base64"); + }); + } else { + this.entries = entries; + } + } + return _createClass(Spec, [{ + key: "funcs", + value: function funcs() { + return this.entries.filter(function (entry) { + return entry.switch().value === _stellarBase.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value; + }).map(function (entry) { + return entry.functionV0(); + }); + } + }, { + key: "getFunc", + value: function getFunc(name) { + var entry = this.findEntry(name); + if (entry.switch().value !== _stellarBase.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value) { + throw new Error("".concat(name, " is not a function")); + } + return entry.functionV0(); + } + }, { + key: "funcArgsToScVals", + value: function funcArgsToScVals(name, args) { + var _this = this; + var fn = this.getFunc(name); + return fn.inputs().map(function (input) { + return _this.nativeToScVal(readObj(args, input), input.type()); + }); + } + }, { + key: "funcResToNative", + value: function funcResToNative(name, val_or_base64) { + var val = typeof val_or_base64 === "string" ? _stellarBase.xdr.ScVal.fromXDR(val_or_base64, "base64") : val_or_base64; + var func = this.getFunc(name); + var outputs = func.outputs(); + if (outputs.length === 0) { + var type = val.switch(); + if (type.value !== _stellarBase.xdr.ScValType.scvVoid().value) { + throw new Error("Expected void, got ".concat(type.name)); + } + return null; + } + if (outputs.length > 1) { + throw new Error("Multiple outputs not supported"); + } + var output = outputs[0]; + if (output.switch().value === _stellarBase.xdr.ScSpecType.scSpecTypeResult().value) { + return new _rust_result.Ok(this.scValToNative(val, output.result().okType())); + } + return this.scValToNative(val, output); + } + }, { + key: "findEntry", + value: function findEntry(name) { + var entry = this.entries.find(function (e) { + return e.value().name().toString() === name; + }); + if (!entry) { + throw new Error("no such entry: ".concat(name)); + } + return entry; + } + }, { + key: "nativeToScVal", + value: function nativeToScVal(val, ty) { + var _this2 = this; + var t = ty.switch(); + var value = t.value; + if (t.value === _stellarBase.xdr.ScSpecType.scSpecTypeUdt().value) { + var udt = ty.udt(); + return this.nativeToUdt(val, udt.name().toString()); + } + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeOption().value) { + var opt = ty.option(); + if (val === undefined) { + return _stellarBase.xdr.ScVal.scvVoid(); + } + return this.nativeToScVal(val, opt.valueType()); + } + switch (_typeof(val)) { + case "object": + { + var _val$constructor$name, _val$constructor; + if (val === null) { + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVoid().value: + return _stellarBase.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was null")); + } + } + if (val instanceof _stellarBase.xdr.ScVal) { + return val; + } + if (val instanceof _stellarBase.Address) { + if (ty.switch().value !== _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.toScVal(); + } + if (val instanceof _stellarBase.Contract) { + if (ty.switch().value !== _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.address().toScVal(); + } + if (val instanceof Uint8Array || Buffer.isBuffer(val)) { + var copy = Uint8Array.from(val); + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var bytesN = ty.bytesN(); + if (copy.length !== bytesN.n()) { + throw new TypeError("expected ".concat(bytesN.n(), " bytes, but got ").concat(copy.length)); + } + return _stellarBase.xdr.ScVal.scvBytes(copy); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBytes().value: + return _stellarBase.xdr.ScVal.scvBytes(copy); + default: + throw new TypeError("invalid type (".concat(ty, ") specified for Bytes and BytesN")); + } + } + if (Array.isArray(val)) { + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVec().value: + { + var vec = ty.vec(); + var elementType = vec.elementType(); + return _stellarBase.xdr.ScVal.scvVec(val.map(function (v) { + return _this2.nativeToScVal(v, elementType); + })); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tup = ty.tuple(); + var valTypes = tup.valueTypes(); + if (val.length !== valTypes.length) { + throw new TypeError("Tuple expects ".concat(valTypes.length, " values, but ").concat(val.length, " were provided")); + } + return _stellarBase.xdr.ScVal.scvVec(val.map(function (v, i) { + return _this2.nativeToScVal(v, valTypes[i]); + })); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = ty.map(); + var keyType = map.keyType(); + var valueType = map.valueType(); + return _stellarBase.xdr.ScVal.scvMap(val.map(function (entry) { + var key = _this2.nativeToScVal(entry[0], keyType); + var mapVal = _this2.nativeToScVal(entry[1], valueType); + return new _stellarBase.xdr.ScMapEntry({ + key: key, + val: mapVal + }); + })); + } + default: + throw new TypeError("Type ".concat(ty, " was not vec, but value was Array")); + } + } + if (val.constructor === Map) { + if (value !== _stellarBase.xdr.ScSpecType.scSpecTypeMap().value) { + throw new TypeError("Type ".concat(ty, " was not map, but value was Map")); + } + var scMap = ty.map(); + var _map = val; + var entries = []; + var values = _map.entries(); + var res = values.next(); + while (!res.done) { + var _res$value = _slicedToArray(res.value, 2), + k = _res$value[0], + v = _res$value[1]; + var key = this.nativeToScVal(k, scMap.keyType()); + var mapval = this.nativeToScVal(v, scMap.valueType()); + entries.push(new _stellarBase.xdr.ScMapEntry({ + key: key, + val: mapval + })); + res = values.next(); + } + return _stellarBase.xdr.ScVal.scvMap(entries); + } + if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : "") !== "Object") { + var _val$constructor2; + throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")")); + } + throw new TypeError("Received object ".concat(val, " did not match the provided type ").concat(ty)); + } + case "number": + case "bigint": + { + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeU32().value: + return _stellarBase.xdr.ScVal.scvU32(val); + case _stellarBase.xdr.ScSpecType.scSpecTypeI32().value: + return _stellarBase.xdr.ScVal.scvI32(val); + case _stellarBase.xdr.ScSpecType.scSpecTypeU64().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeI64().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeU128().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeI128().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeU256().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeI256().value: + { + var intType = t.name.substring(10).toLowerCase(); + return new _stellarBase.XdrLargeInt(intType, val).toScVal(); + } + default: + throw new TypeError("invalid type (".concat(ty, ") specified for integer")); + } + } + case "string": + return stringToScVal(val, t); + case "boolean": + { + if (value !== _stellarBase.xdr.ScSpecType.scSpecTypeBool().value) { + throw TypeError("Type ".concat(ty, " was not bool, but value was bool")); + } + return _stellarBase.xdr.ScVal.scvBool(val); + } + case "undefined": + { + if (!ty) { + return _stellarBase.xdr.ScVal.scvVoid(); + } + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVoid().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeOption().value: + return _stellarBase.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was undefined")); + } + } + case "function": + return this.nativeToScVal(val(), ty); + default: + throw new TypeError("failed to convert typeof ".concat(_typeof(val), " (").concat(val, ")")); + } + } + }, { + key: "nativeToUdt", + value: function nativeToUdt(val, name) { + var entry = this.findEntry(name); + switch (entry.switch()) { + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + if (typeof val !== "number") { + throw new TypeError("expected number for enum ".concat(name, ", but got ").concat(_typeof(val))); + } + return this.nativeToEnum(val, entry.udtEnumV0()); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.nativeToStruct(val, entry.udtStructV0()); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.nativeToUnion(val, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(name)); + } + } + }, { + key: "nativeToUnion", + value: function nativeToUnion(val, union_) { + var _this3 = this; + var entryName = val.tag; + var caseFound = union_.cases().find(function (entry) { + var caseN = entry.value().name().toString(); + return caseN === entryName; + }); + if (!caseFound) { + throw new TypeError("no such enum entry: ".concat(entryName, " in ").concat(union_)); + } + var key = _stellarBase.xdr.ScVal.scvSymbol(entryName); + switch (caseFound.switch()) { + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0(): + { + return _stellarBase.xdr.ScVal.scvVec([key]); + } + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0(): + { + var types = caseFound.tupleCase().type(); + if (Array.isArray(val.values)) { + if (val.values.length !== types.length) { + throw new TypeError("union ".concat(union_, " expects ").concat(types.length, " values, but got ").concat(val.values.length)); + } + var scvals = val.values.map(function (v, i) { + return _this3.nativeToScVal(v, types[i]); + }); + scvals.unshift(key); + return _stellarBase.xdr.ScVal.scvVec(scvals); + } + throw new Error("failed to parse union case ".concat(caseFound, " with ").concat(val)); + } + default: + throw new Error("failed to parse union ".concat(union_, " with ").concat(val)); + } + } + }, { + key: "nativeToStruct", + value: function nativeToStruct(val, struct) { + var _this4 = this; + var fields = struct.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + return _stellarBase.xdr.ScVal.scvVec(fields.map(function (_, i) { + return _this4.nativeToScVal(val[i], fields[i].type()); + })); + } + return _stellarBase.xdr.ScVal.scvMap(fields.map(function (field) { + var name = field.name().toString(); + return new _stellarBase.xdr.ScMapEntry({ + key: _this4.nativeToScVal(name, _stellarBase.xdr.ScSpecTypeDef.scSpecTypeSymbol()), + val: _this4.nativeToScVal(val[name], field.type()) + }); + })); + } + }, { + key: "nativeToEnum", + value: function nativeToEnum(val, enum_) { + if (enum_.cases().some(function (entry) { + return entry.value() === val; + })) { + return _stellarBase.xdr.ScVal.scvU32(val); + } + throw new TypeError("no such enum entry: ".concat(val, " in ").concat(enum_)); + } + }, { + key: "scValStrToNative", + value: function scValStrToNative(scv, typeDef) { + return this.scValToNative(_stellarBase.xdr.ScVal.fromXDR(scv, "base64"), typeDef); + } + }, { + key: "scValToNative", + value: function scValToNative(scv, typeDef) { + var _this5 = this; + var t = typeDef.switch(); + var value = t.value; + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeUdt().value) { + return this.scValUdtToNative(scv, typeDef.udt()); + } + switch (scv.switch().value) { + case _stellarBase.xdr.ScValType.scvVoid().value: + return undefined; + case _stellarBase.xdr.ScValType.scvU64().value: + case _stellarBase.xdr.ScValType.scvI64().value: + case _stellarBase.xdr.ScValType.scvU128().value: + case _stellarBase.xdr.ScValType.scvI128().value: + case _stellarBase.xdr.ScValType.scvU256().value: + case _stellarBase.xdr.ScValType.scvI256().value: + return (0, _stellarBase.scValToBigInt)(scv); + case _stellarBase.xdr.ScValType.scvVec().value: + { + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeVec().value) { + var _scv$vec; + var vec = typeDef.vec(); + return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(function (elm) { + return _this5.scValToNative(elm, vec.elementType()); + }); + } + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeTuple().value) { + var _scv$vec2; + var tuple = typeDef.tuple(); + var valTypes = tuple.valueTypes(); + return ((_scv$vec2 = scv.vec()) !== null && _scv$vec2 !== void 0 ? _scv$vec2 : []).map(function (elm, i) { + return _this5.scValToNative(elm, valTypes[i]); + }); + } + throw new TypeError("Type ".concat(typeDef, " was not vec, but ").concat(scv, " is")); + } + case _stellarBase.xdr.ScValType.scvAddress().value: + return _stellarBase.Address.fromScVal(scv).toString(); + case _stellarBase.xdr.ScValType.scvMap().value: + { + var _scv$map; + var map = (_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []; + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeMap().value) { + var typed = typeDef.map(); + var keyType = typed.keyType(); + var valueType = typed.valueType(); + var res = map.map(function (entry) { + return [_this5.scValToNative(entry.key(), keyType), _this5.scValToNative(entry.val(), valueType)]; + }); + return res; + } + throw new TypeError("ScSpecType ".concat(t.name, " was not map, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + case _stellarBase.xdr.ScValType.scvBool().value: + case _stellarBase.xdr.ScValType.scvU32().value: + case _stellarBase.xdr.ScValType.scvI32().value: + case _stellarBase.xdr.ScValType.scvBytes().value: + return scv.value(); + case _stellarBase.xdr.ScValType.scvString().value: + case _stellarBase.xdr.ScValType.scvSymbol().value: + { + var _scv$value; + if (value !== _stellarBase.xdr.ScSpecType.scSpecTypeString().value && value !== _stellarBase.xdr.ScSpecType.scSpecTypeSymbol().value) { + throw new Error("ScSpecType ".concat(t.name, " was not string or symbol, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + return (_scv$value = scv.value()) === null || _scv$value === void 0 ? void 0 : _scv$value.toString(); + } + case _stellarBase.xdr.ScValType.scvTimepoint().value: + case _stellarBase.xdr.ScValType.scvDuration().value: + return (0, _stellarBase.scValToBigInt)(_stellarBase.xdr.ScVal.scvU64(scv.u64())); + default: + throw new TypeError("failed to convert ".concat(JSON.stringify(scv, null, 2), " to native type from type ").concat(t.name)); + } + } + }, { + key: "scValUdtToNative", + value: function scValUdtToNative(scv, udt) { + var entry = this.findEntry(udt.name().toString()); + switch (entry.switch()) { + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + return this.enumToNative(scv); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.structToNative(scv, entry.udtStructV0()); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.unionToNative(scv, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(udt.name().toString(), ": ").concat(entry)); + } + } + }, { + key: "unionToNative", + value: function unionToNative(val, udt) { + var _this6 = this; + var vec = val.vec(); + if (!vec) { + throw new Error("".concat(JSON.stringify(val, null, 2), " is not a vec")); + } + if (vec.length === 0 && udt.cases.length !== 0) { + throw new Error("".concat(val, " has length 0, but the there are at least one case in the union")); + } + var name = vec[0].sym().toString(); + if (vec[0].switch().value !== _stellarBase.xdr.ScValType.scvSymbol().value) { + throw new Error("{vec[0]} is not a symbol"); + } + var entry = udt.cases().find(findCase(name)); + if (!entry) { + throw new Error("failed to find entry ".concat(name, " in union {udt.name().toString()}")); + } + var res = { + tag: name + }; + if (entry.switch().value === _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value) { + var tuple = entry.tupleCase(); + var ty = tuple.type(); + var values = ty.map(function (e, i) { + return _this6.scValToNative(vec[i + 1], e); + }); + res.values = values; + } + return res; + } + }, { + key: "structToNative", + value: function structToNative(val, udt) { + var _this7 = this, + _val$map; + var res = {}; + var fields = udt.fields(); + if (fields.some(isNumeric)) { + var _val$vec; + var r = (_val$vec = val.vec()) === null || _val$vec === void 0 ? void 0 : _val$vec.map(function (entry, i) { + return _this7.scValToNative(entry, fields[i].type()); + }); + return r; + } + (_val$map = val.map()) === null || _val$map === void 0 || _val$map.forEach(function (entry, i) { + var field = fields[i]; + res[field.name().toString()] = _this7.scValToNative(entry.val(), field.type()); + }); + return res; + } + }, { + key: "enumToNative", + value: function enumToNative(scv) { + if (scv.switch().value !== _stellarBase.xdr.ScValType.scvU32().value) { + throw new Error("Enum must have a u32 value"); + } + var num = scv.u32(); + return num; + } + }, { + key: "errorCases", + value: function errorCases() { + return this.entries.filter(function (entry) { + return entry.switch().value === _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value; + }).flatMap(function (entry) { + return entry.value().cases(); + }); + } + }, { + key: "jsonSchema", + value: function jsonSchema(funcName) { + var definitions = {}; + this.entries.forEach(function (entry) { + switch (entry.switch().value) { + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0().value: + { + var udt = entry.udtEnumV0(); + definitions[udt.name().toString()] = enumToJsonSchema(udt); + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0().value: + { + var _udt = entry.udtStructV0(); + definitions[_udt.name().toString()] = structToJsonSchema(_udt); + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0().value: + { + var _udt2 = entry.udtUnionV0(); + definitions[_udt2.name().toString()] = unionToJsonSchema(_udt2); + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value: + { + var fn = entry.functionV0(); + var fnName = fn.name().toString(); + var _functionToJsonSchema = functionToJsonSchema(fn), + input = _functionToJsonSchema.input; + definitions[fnName] = input; + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value: + {} + } + }); + var res = { + $schema: "http://json-schema.org/draft-07/schema#", + definitions: _objectSpread(_objectSpread({}, PRIMITIVE_DEFINITONS), definitions) + }; + if (funcName) { + res.$ref = "#/definitions/".concat(funcName); + } + return res; + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/types.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/types.d.ts new file mode 100644 index 000000000..bceff262c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/types.d.ts @@ -0,0 +1,244 @@ +import { Memo, MemoType, Operation, Transaction, xdr } from "@stellar/stellar-base"; +export type XDR_BASE64 = string; +/** + * An unsigned 32-bit integer. + * @memberof module:contract + */ +export type u32 = number; +/** + * A signed 32-bit integer. + * @memberof module:contract + */ +export type i32 = number; +/** + * An unsigned 64-bit integer. + * @memberof module:contract + */ +export type u64 = bigint; +/** + * A signed 64-bit integer. + * @memberof module:contract + */ +export type i64 = bigint; +/** + * An unsigned 128-bit integer. + * @memberof module:contract + */ +export type u128 = bigint; +/** + * A signed 128-bit integer. + * @memberof module:contract + */ +export type i128 = bigint; +/** + * An unsigned 256-bit integer. + * @memberof module:contract + */ +export type u256 = bigint; +/** + * A signed 256-bit integer. + * @memberof module:contract + */ +export type i256 = bigint; +export type Option = T | undefined; +export type Typepoint = bigint; +export type Duration = bigint; +/** + * A "regular" transaction, as opposed to a FeeBumpTransaction. + * @memberof module:contract + * @type {Transaction, Operation[]>} + */ +export type Tx = Transaction, Operation[]>; +export interface WalletError { + message: string; + code: number; + ext?: Array; +} +/** + * A function to request a wallet to sign a built transaction + * + * This function takes an XDR provided by the requester and applies a signature to it. + * It returns a base64-encoded string XDR-encoded Transaction Envelope with Decorated Signatures + * and the signer address back to the requester. + * + * @param xdr - The XDR string representing the transaction to be signed. + * @param opts - Options for signing the transaction. + * @param opts.networkPassphrase - The network's passphrase on which the transaction is intended to be signed. + * @param opts.address - The public key of the account that should be used to sign. + * @param opts.submit - If set to true, submits the transaction immediately after signing. + * @param opts.submitUrl - The URL of the network to which the transaction should be submitted, if applicable. + * + * @returns A promise resolving to an object with the signed transaction XDR and optional signer address and error. + */ +export type SignTransaction = (xdr: string, opts?: { + networkPassphrase?: string; + address?: string; + submit?: boolean; + submitUrl?: string; +}) => Promise<{ + signedTxXdr: string; + signerAddress?: string; +} & { + error?: WalletError; +}>; +/** + * A function to request a wallet to sign an authorization entry preimage. + * + * Similar to signing a transaction, this function takes an authorization entry preimage provided by the + * requester and applies a signature to it. + * It returns a signed hash of the same authorization entry and the signer address back to the requester. + * + * @param authEntry - The authorization entry preimage to be signed. + * @param opts - Options for signing the authorization entry. + * @param opts.networkPassphrase - The network's passphrase on which the authorization entry is intended to be signed. + * @param opts.address - The public key of the account that should be used to sign. + * + * @returns A promise resolving to an object with the signed authorization entry and optional signer address and error. + */ +export type SignAuthEntry = (authEntry: string, opts?: { + networkPassphrase?: string; + address?: string; +}) => Promise<{ + signedAuthEntry: string; + signerAddress?: string; +} & { + error?: WalletError; +}>; +/** + * Options for a smart contract client. + * @memberof module:contract + */ +export type ClientOptions = { + /** + * The public key of the account that will send this transaction. You can + * override this for specific methods later, like + * [signAndSend]{@link module:contract.AssembledTransaction#signAndSend} and + * [signAuthEntries]{@link module:contract.AssembledTransaction#signAuthEntries}. + */ + publicKey?: string; + /** + * A function to sign the transaction using the private key corresponding to + * the given `publicKey`. You do not need to provide this, for read-only + * calls, which only need to be simulated. If you do not need to sign and + * send, there is no need to provide this. If you do not provide it during + * initialization, you can provide it later when you call + * {@link module:contract.AssembledTransaction#signAndSend signAndSend}. + * + * Matches signature of `signTransaction` from Freighter. + */ + signTransaction?: SignTransaction; + /** + * A function to sign a specific auth entry for a transaction, using the + * private key corresponding to the provided `publicKey`. This is only needed + * for multi-auth transactions, in which one transaction is signed by + * multiple parties. If you do not provide it during initialization, you can + * provide it later when you call {@link module:contract.AssembledTransaction#signAuthEntries signAuthEntries}. + * + * Matches signature of `signAuthEntry` from Freighter. + */ + signAuthEntry?: SignAuthEntry; + /** The address of the contract the client will interact with. */ + contractId: string; + /** + * The network passphrase for the Stellar network this contract is deployed + * to. + */ + networkPassphrase: string; + /** + * The URL of the RPC instance that will be used to interact with this + * contract. + */ + rpcUrl: string; + /** + * If true, will allow HTTP requests to the Soroban network. If false, will + * only allow HTTPS requests. + * @default false + */ + allowHttp?: boolean; + /** + * This gets filled in automatically from the ContractSpec when you + * instantiate a {@link Client}. + * + * Background: If the contract you're calling uses the `#[contracterror]` + * macro to create an `Error` enum, then those errors get included in the + * on-chain XDR that also describes your contract's methods. Each error will + * have a specific number. + * + * A Client makes method calls with an {@link module:contract.AssembledTransaction AssembledTransaction}. + * When one of these method calls encounters an error, `AssembledTransaction` + * will first attempt to parse the error as an "official" `contracterror` + * error, by using this passed-in `errorTypes` object. See + * {@link module:contract.AssembledTransaction#parseError parseError}. If `errorTypes` is blank or no + * matching error is found, then it will throw the raw error. + * @default {} + */ + errorTypes?: Record; +}; +/** + * Options for a smart contract method invocation. + * @memberof module:contract + */ +export type MethodOptions = { + /** + * The fee to pay for the transaction. + * @default 100 + */ + fee?: string; + /** + * The timebounds which should be set for transactions generated by this + * contract client. {@link module:contract#.DEFAULT_TIMEOUT} + * @default 300 + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the + * AssembledTransaction. + * @default true + */ + simulate?: boolean; + /** + * If true, will automatically attempt to restore the transaction if there + * are archived entries that need renewal. + * @default false + */ + restore?: boolean; +}; +export type AssembledTransactionOptions = MethodOptions & ClientOptions & { + method: string; + args?: any[]; + parseResultXdr: (xdr: xdr.ScVal) => T; + /** + * The address of the account that should sign the transaction. Useful when + * a wallet holds multiple addresses to ensure signing with the intended one. + */ + address?: string; + /** + * This option will be passed through to the SEP43-compatible wallet extension. If true, and if the wallet supports it, the transaction will be signed and immediately submitted to the network by the wallet, bypassing the submit logic in {@link SentTransaction}. + * @default false + */ + submit?: boolean; + /** + * The URL of the network to which the transaction should be submitted. + * Only applicable when 'submit' is set to true. + */ + submitUrl?: string; +}; +/** + * The default timebounds, in seconds, during which a transaction will be valid. + * This is attached to the transaction _before_ transaction simulation (it is + * needed for simulation to succeed). It is also re-calculated and re-added + * _before_ transaction signing. + * @constant {number} + * @default 300 + * @memberof module:contract + */ +export declare const DEFAULT_TIMEOUT: number; +/** + * An impossible account on the Stellar network + * @constant {string} + * @default GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF + * @memberof module:contract + */ +export declare const NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/types.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/types.js new file mode 100644 index 000000000..81a5b0f1c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/types.js @@ -0,0 +1,9 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NULL_ACCOUNT = exports.DEFAULT_TIMEOUT = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var DEFAULT_TIMEOUT = exports.DEFAULT_TIMEOUT = 5 * 60; +var NULL_ACCOUNT = exports.NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/utils.d.ts new file mode 100644 index 000000000..12ee8e61e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/utils.d.ts @@ -0,0 +1,46 @@ +import { xdr, Account } from "@stellar/stellar-base"; +import { Server } from "../rpc"; +import { AssembledTransactionOptions } from "./types"; +/** + * Keep calling a `fn` for `timeoutInSeconds` seconds, if `keepWaitingIf` is + * true. Returns an array of all attempts to call the function. + * @private + */ +export declare function withExponentialBackoff( +/** Function to call repeatedly */ +fn: (previousFailure?: T) => Promise, +/** Condition to check when deciding whether or not to call `fn` again */ +keepWaitingIf: (result: T) => boolean, +/** How long to wait between the first and second call */ +timeoutInSeconds: number, +/** What to multiply `timeoutInSeconds` by, each subsequent attempt */ +exponentialFactor?: number, +/** Whether to log extra info */ +verbose?: boolean): Promise; +/** + * If contracts are implemented using the `#[contracterror]` macro, then the + * errors get included in the on-chain XDR that also describes your contract's + * methods. Each error will have a specific number. This Regular Expression + * matches these "expected error types" that a contract may throw, and helps + * {@link AssembledTransaction} parse these errors. + * + * @constant {RegExp} + * @default "/Error\(Contract, #(\d+)\)/" + * @memberof module:contract.Client + */ +export declare const contractErrorPattern: RegExp; +/** + * A TypeScript type guard that checks if an object has a `toString` method. + * @private + */ +export declare function implementsToString( +/** some object that may or may not have a `toString` method */ +obj: unknown): obj is { + toString(): string; +}; +/** + * Reads a binary stream of ScSpecEntries into an array for processing by ContractSpec + * @private + */ +export declare function processSpecEntryStream(buffer: Buffer): xdr.ScSpecEntry[]; +export declare function getAccount(options: AssembledTransactionOptions, server: Server): Promise; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/utils.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/utils.js new file mode 100644 index 000000000..8db862695 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/contract/utils.js @@ -0,0 +1,123 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.contractErrorPattern = void 0; +exports.getAccount = getAccount; +exports.implementsToString = implementsToString; +exports.processSpecEntryStream = processSpecEntryStream; +exports.withExponentialBackoff = withExponentialBackoff; +var _stellarBase = require("@stellar/stellar-base"); +var _types = require("./types"); +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function withExponentialBackoff(_x, _x2, _x3) { + return _withExponentialBackoff.apply(this, arguments); +} +function _withExponentialBackoff() { + _withExponentialBackoff = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(fn, keepWaitingIf, timeoutInSeconds) { + var exponentialFactor, + verbose, + attempts, + count, + waitUntil, + waitTime, + totalWaitTime, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + exponentialFactor = _args.length > 3 && _args[3] !== undefined ? _args[3] : 1.5; + verbose = _args.length > 4 && _args[4] !== undefined ? _args[4] : false; + attempts = []; + count = 0; + _context.t0 = attempts; + _context.next = 7; + return fn(); + case 7: + _context.t1 = _context.sent; + _context.t0.push.call(_context.t0, _context.t1); + if (keepWaitingIf(attempts[attempts.length - 1])) { + _context.next = 11; + break; + } + return _context.abrupt("return", attempts); + case 11: + waitUntil = new Date(Date.now() + timeoutInSeconds * 1000).valueOf(); + waitTime = 1000; + totalWaitTime = waitTime; + case 14: + if (!(Date.now() < waitUntil && keepWaitingIf(attempts[attempts.length - 1]))) { + _context.next = 30; + break; + } + count += 1; + if (verbose) { + console.info("Waiting ".concat(waitTime, "ms before trying again (bringing the total wait time to ").concat(totalWaitTime, "ms so far, of total ").concat(timeoutInSeconds * 1000, "ms)")); + } + _context.next = 19; + return new Promise(function (res) { + return setTimeout(res, waitTime); + }); + case 19: + waitTime *= exponentialFactor; + if (new Date(Date.now() + waitTime).valueOf() > waitUntil) { + waitTime = waitUntil - Date.now(); + if (verbose) { + console.info("was gonna wait too long; new waitTime: ".concat(waitTime, "ms")); + } + } + totalWaitTime = waitTime + totalWaitTime; + _context.t2 = attempts; + _context.next = 25; + return fn(attempts[attempts.length - 1]); + case 25: + _context.t3 = _context.sent; + _context.t2.push.call(_context.t2, _context.t3); + if (verbose && keepWaitingIf(attempts[attempts.length - 1])) { + console.info("".concat(count, ". Called ").concat(fn, "; ").concat(attempts.length, " prev attempts. Most recent: ").concat(JSON.stringify(attempts[attempts.length - 1], null, 2))); + } + _context.next = 14; + break; + case 30: + return _context.abrupt("return", attempts); + case 31: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _withExponentialBackoff.apply(this, arguments); +} +var contractErrorPattern = exports.contractErrorPattern = /Error\(Contract, #(\d+)\)/; +function implementsToString(obj) { + return _typeof(obj) === "object" && obj !== null && "toString" in obj; +} +function processSpecEntryStream(buffer) { + var reader = new _stellarBase.cereal.XdrReader(buffer); + var res = []; + while (!reader.eof) { + res.push(_stellarBase.xdr.ScSpecEntry.read(reader)); + } + return res; +} +function getAccount(_x4, _x5) { + return _getAccount.apply(this, arguments); +} +function _getAccount() { + _getAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(options, server) { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", options.publicKey ? server.getAccount(options.publicKey) : new _stellarBase.Account(_types.NULL_ACCOUNT, "0")); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _getAccount.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/account_requires_memo.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/account_requires_memo.d.ts new file mode 100644 index 000000000..2c845d12f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/account_requires_memo.d.ts @@ -0,0 +1,24 @@ +/** + * AccountRequiresMemoError is raised when a transaction is trying to submit an + * operation to an account which requires a memo. See + * [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md) + * for more information. + * + * This error contains two attributes to help you identify the account requiring + * the memo and the operation where the account is the destination + * @category Errors + * + * @param {string} message Human-readable error message + * @param {string} accountId The account which requires a memo + * @param {number} operationIndex The index of the operation where `accountId` is the destination + * + * @example + * console.log('The following account requires a memo ', err.accountId) + * console.log('The account is used in operation: ', err.operationIndex) + */ +export declare class AccountRequiresMemoError extends Error { + __proto__: AccountRequiresMemoError; + accountId: string; + operationIndex: number; + constructor(message: string, accountId: string, operationIndex: number); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/account_requires_memo.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/account_requires_memo.js new file mode 100644 index 000000000..669d85bc6 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/account_requires_memo.js @@ -0,0 +1,38 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AccountRequiresMemoError = void 0; +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var AccountRequiresMemoError = exports.AccountRequiresMemoError = function (_Error) { + function AccountRequiresMemoError(message, accountId, operationIndex) { + var _this; + _classCallCheck(this, AccountRequiresMemoError); + var trueProto = (this instanceof AccountRequiresMemoError ? this.constructor : void 0).prototype; + _this = _callSuper(this, AccountRequiresMemoError, [message]); + _this.__proto__ = trueProto; + _this.constructor = AccountRequiresMemoError; + _this.name = "AccountRequiresMemoError"; + _this.accountId = accountId; + _this.operationIndex = operationIndex; + return _this; + } + _inherits(AccountRequiresMemoError, _Error); + return _createClass(AccountRequiresMemoError); +}(_wrapNativeSuper(Error)); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/bad_request.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/bad_request.d.ts new file mode 100644 index 000000000..4d1d320d5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/bad_request.d.ts @@ -0,0 +1,14 @@ +import { NetworkError } from "./network"; +/** + * BadRequestError is raised when a request made to Horizon is invalid in some + * way (incorrect timebounds for trade call builders, for example.) + * @augments NetworkError + * @inheritdoc + * @category Errors + * + * @param {string} message Human-readable error message + * @param {any} response Response details, received from the Horizon server + */ +export declare class BadRequestError extends NetworkError { + constructor(message: string, response: any); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/bad_request.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/bad_request.js new file mode 100644 index 000000000..24aeb632c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/bad_request.js @@ -0,0 +1,34 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BadRequestError = void 0; +var _network = require("./network"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var BadRequestError = exports.BadRequestError = function (_NetworkError) { + function BadRequestError(message, response) { + var _this; + _classCallCheck(this, BadRequestError); + var trueProto = (this instanceof BadRequestError ? this.constructor : void 0).prototype; + _this = _callSuper(this, BadRequestError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadRequestError; + _this.name = "BadRequestError"; + return _this; + } + _inherits(BadRequestError, _NetworkError); + return _createClass(BadRequestError); +}(_network.NetworkError); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/bad_response.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/bad_response.d.ts new file mode 100644 index 000000000..22de8f235 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/bad_response.d.ts @@ -0,0 +1,17 @@ +import { NetworkError } from "./network"; +/** + * BadResponseError is raised when a response from a + * {@link module:Horizon | Horizon} or {@link module:Federation | Federation} + * server is invalid in some way. For example, a federation response may exceed + * the maximum allowed size, or a transaction submission may have failed with + * Horizon. + * @augments NetworkError + * @inheritdoc + * @category Errors + * + * @param {string} message Human-readable error message. + * @param {any} response Response details, received from the server. + */ +export declare class BadResponseError extends NetworkError { + constructor(message: string, response: any); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/bad_response.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/bad_response.js new file mode 100644 index 000000000..c7fbbacec --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/bad_response.js @@ -0,0 +1,34 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BadResponseError = void 0; +var _network = require("./network"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var BadResponseError = exports.BadResponseError = function (_NetworkError) { + function BadResponseError(message, response) { + var _this; + _classCallCheck(this, BadResponseError); + var trueProto = (this instanceof BadResponseError ? this.constructor : void 0).prototype; + _this = _callSuper(this, BadResponseError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadResponseError; + _this.name = "BadResponseError"; + return _this; + } + _inherits(BadResponseError, _NetworkError); + return _createClass(BadResponseError); +}(_network.NetworkError); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/index.d.ts new file mode 100644 index 000000000..cb4f19458 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/index.d.ts @@ -0,0 +1,5 @@ +export * from "./network"; +export * from "./not_found"; +export * from "./bad_request"; +export * from "./bad_response"; +export * from "./account_requires_memo"; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/index.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/index.js new file mode 100644 index 000000000..f0f9d584e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/index.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _network = require("./network"); +Object.keys(_network).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _network[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _network[key]; + } + }); +}); +var _not_found = require("./not_found"); +Object.keys(_not_found).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _not_found[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _not_found[key]; + } + }); +}); +var _bad_request = require("./bad_request"); +Object.keys(_bad_request).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _bad_request[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _bad_request[key]; + } + }); +}); +var _bad_response = require("./bad_response"); +Object.keys(_bad_response).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _bad_response[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _bad_response[key]; + } + }); +}); +var _account_requires_memo = require("./account_requires_memo"); +Object.keys(_account_requires_memo).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _account_requires_memo[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _account_requires_memo[key]; + } + }); +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/network.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/network.d.ts new file mode 100644 index 000000000..fad4e7745 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/network.d.ts @@ -0,0 +1,33 @@ +import { HorizonApi } from "../horizon/horizon_api"; +/** + * NetworkError is raised when an interaction with a Horizon server has caused + * some kind of problem. + * @category Errors + * + * @param {string} message Human-readable error message + * @param {any} response Response details, received from the Horizon server. + * @param {HorizonApi.ErrorResponseData} [response.data] The data returned by Horizon as part of the error: {@link https://developers.stellar.org/docs/data/horizon/api-reference/errors/response | Error Response} + * @param {number} [response.status] HTTP status code describing the basic issue with a submitted transaction {@link https://developers.stellar.org/docs/data/horizon/api-reference/errors/http-status-codes/standard | Standard Status Codes} + * @param {string} [response.statusText] A human-readable description of what the status code means: {@link https://developers.stellar.org/docs/data/horizon/api-reference/errors/http-status-codes/horizon-specific | Horizon-Specific Status Codes} + * @param {string} [response.url] URL which can provide more information about the problem that occurred. + */ +export declare class NetworkError extends Error { + response: { + data?: HorizonApi.ErrorResponseData; + status?: number; + statusText?: string; + url?: string; + }; + __proto__: NetworkError; + constructor(message: string, response: any); + /** + * Returns the error response sent by the Horizon server. + * @returns {any} + */ + getResponse(): { + data?: HorizonApi.ErrorResponseData; + status?: number; + statusText?: string; + url?: string; + }; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/network.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/network.js new file mode 100644 index 000000000..a26433617 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/network.js @@ -0,0 +1,41 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NetworkError = void 0; +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var NetworkError = exports.NetworkError = function (_Error) { + function NetworkError(message, response) { + var _this; + _classCallCheck(this, NetworkError); + var trueProto = (this instanceof NetworkError ? this.constructor : void 0).prototype; + _this = _callSuper(this, NetworkError, [message]); + _this.__proto__ = trueProto; + _this.constructor = NetworkError; + _this.response = response; + return _this; + } + _inherits(NetworkError, _Error); + return _createClass(NetworkError, [{ + key: "getResponse", + value: function getResponse() { + return this.response; + } + }]); +}(_wrapNativeSuper(Error)); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/not_found.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/not_found.d.ts new file mode 100644 index 000000000..bca48d935 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/not_found.d.ts @@ -0,0 +1,14 @@ +import { NetworkError } from "./network"; +/** + * NotFoundError is raised when the resource requested from Horizon is + * unavailable. + * @augments NetworkError + * @inheritdoc + * @category Errors + * + * @param {string} message Human-readable error message + * @param {any} response Response details, received from the Horizon server + */ +export declare class NotFoundError extends NetworkError { + constructor(message: string, response: any); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/not_found.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/not_found.js new file mode 100644 index 000000000..d828c18cf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/errors/not_found.js @@ -0,0 +1,34 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NotFoundError = void 0; +var _network = require("./network"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var NotFoundError = exports.NotFoundError = function (_NetworkError) { + function NotFoundError(message, response) { + var _this; + _classCallCheck(this, NotFoundError); + var trueProto = (this instanceof NotFoundError ? this.constructor : void 0).prototype; + _this = _callSuper(this, NotFoundError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = NotFoundError; + _this.name = "NotFoundError"; + return _this; + } + _inherits(NotFoundError, _NetworkError); + return _createClass(NotFoundError); +}(_network.NetworkError); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/api.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/api.d.ts new file mode 100644 index 000000000..f7feb38bf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/api.d.ts @@ -0,0 +1,32 @@ +export declare namespace Api { + /** + * Record returned from a federation server. + */ + interface Record { + /** + * The Stellar public key resolved from the federation lookup + */ + account_id: string; + /** + * The type of memo, if any, required to send payments to this user + */ + memo_type?: string; + /** + * The memo value, if any, required to send payments to this user + */ + memo?: string; + } + /** + * Options for configuring connections to federation servers. You can also use {@link Config} class to set this globally. + */ + interface Options { + /** + * Allow connecting to http servers, default: `false`. This must be set to false in production deployments! + */ + allowHttp?: boolean; + /** + * Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue. + */ + timeout?: number; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/api.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/api.js new file mode 100644 index 000000000..081ac7fbf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/api.js @@ -0,0 +1,7 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Api = void 0; +var Api; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/index.d.ts new file mode 100644 index 000000000..4eaff4f80 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/index.d.ts @@ -0,0 +1,2 @@ +export { FederationServer as Server, FEDERATION_RESPONSE_MAX_SIZE } from './server'; +export * from './api'; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/index.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/index.js new file mode 100644 index 000000000..2d73772d2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/index.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Server: true, + FEDERATION_RESPONSE_MAX_SIZE: true +}; +Object.defineProperty(exports, "FEDERATION_RESPONSE_MAX_SIZE", { + enumerable: true, + get: function get() { + return _server.FEDERATION_RESPONSE_MAX_SIZE; + } +}); +Object.defineProperty(exports, "Server", { + enumerable: true, + get: function get() { + return _server.FederationServer; + } +}); +var _server = require("./server"); +var _api = require("./api"); +Object.keys(_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _api[key]; + } + }); +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/server.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/server.d.ts new file mode 100644 index 000000000..bde8cb479 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/server.d.ts @@ -0,0 +1,116 @@ +import { Api } from "./api"; +/** @module Federation */ +/** + * The maximum size of response from a federation server + * @default 102400 + */ +export declare const FEDERATION_RESPONSE_MAX_SIZE: number; +/** + * Federation.Server handles a network connection to a + * [federation server](https://developers.stellar.org/docs/learn/encyclopedia/federation) + * instance and exposes an interface for requests to that instance. + * + * @alias module:Federation.Server + * @memberof module:Federation + * @param {string} serverURL The federation server URL (ex. `https://acme.com/federation`). + * @param {string} domain Domain this server represents + * @param {Api.Options} [opts] Options object + * @returns {void} + */ +export declare class FederationServer { + /** + * The federation server URL (ex. `https://acme.com/federation`). + */ + private readonly serverURL; + /** + * Domain this server represents. + */ + private readonly domain; + /** + * Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue. + */ + private readonly timeout; + /** + * A helper method for handling user inputs that contain `destination` value. + * It accepts two types of values: + * + * * For Stellar address (ex. `bob*stellar.org`) it splits Stellar address and then tries to find information about + * federation server in `stellar.toml` file for a given domain. It returns a `Promise` which resolves if federation + * server exists and user has been found and rejects in all other cases. + * * For Account ID (ex. `GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS`) it returns a `Promise` which + * resolves if Account ID is valid and rejects in all other cases. Please note that this method does not check + * if the account actually exists in a ledger. + * + * @example + * StellarSdk.FederationServer.resolve('bob*stellar.org') + * .then(federationRecord => { + * // { + * // account_id: 'GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS', + * // memo_type: 'id', + * // memo: 100 + * // } + * }); + * + * @see Federation doc + * @see Stellar.toml doc + * @param {string} value Stellar Address (ex. `bob*stellar.org`) + * @param {object} [opts] Options object + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the provided account ID is not a valid Ed25519 public key. + */ + static resolve(value: string, opts?: Api.Options): Promise; + /** + * Creates a `FederationServer` instance based on information from + * [stellar.toml](https://developers.stellar.org/docs/issuing-assets/publishing-asset-info) + * file for a given domain. + * + * If `stellar.toml` file does not exist for a given domain or it does not + * contain information about a federation server Promise will reject. + * + * @example + * StellarSdk.FederationServer.createForDomain('acme.com') + * .then(federationServer => { + * // federationServer.resolveAddress('bob').then(...) + * }) + * .catch(error => { + * // stellar.toml does not exist or it does not contain information about federation server. + * }); + * + * @see Stellar.toml doc + * @param {string} domain Domain to get federation server for + * @param {module:Federation.Api.Options} [opts] Options object + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the domain's stellar.toml file does not contain a federation server field. + */ + static createForDomain(domain: string, opts?: Api.Options): Promise; + constructor(serverURL: string, domain: string, opts?: Api.Options); + /** + * Get the federation record if the user was found for a given Stellar address + * @see Federation doc + * @param {string} address Stellar address (ex. `bob*stellar.org`). If `FederationServer` was instantiated with `domain` param only username (ex. `bob`) can be passed. + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the federated address does not contain a domain, or if the server object was not instantiated with a `domain` parameter + */ + resolveAddress(address: string): Promise; + /** + * Given an account ID, get their federation record if the user was found + * @see Federation doc + * @param {string} accountId Account ID (ex. `GBYNR2QJXLBCBTRN44MRORCMI4YO7FZPFBCNOKTOBCAAFC7KC3LNPRYS`) + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the federation server returns an invalid memo value. + * @throws Will throw an error if the federation server's response exceeds the allowed maximum size. + * @throws {BadResponseError} Will throw an error if the server query fails with an improper response. + */ + resolveAccountId(accountId: string): Promise; + /** + * Given a transactionId, get the federation record if the sender of the transaction was found + * @see Federation doc + * @param {string} transactionId Transaction ID (ex. `3389e9f0f1a65f19736cacf544c2e825313e8447f569233bb8db39aa607c8889`) + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the federation server returns an invalid memo value. + * @throws Will throw an error if the federation server's response exceeds the allowed maximum size. + * @throws {BadResponseError} Will throw an error if the server query fails with an improper response. + */ + resolveTransactionId(transactionId: string): Promise; + private _sendRequest; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/server.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/server.js new file mode 100644 index 000000000..36d7789cd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/federation/server.js @@ -0,0 +1,252 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FederationServer = exports.FEDERATION_RESPONSE_MAX_SIZE = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _urijs = _interopRequireDefault(require("urijs")); +var _config = require("../config"); +var _errors = require("../errors"); +var _stellartoml = require("../stellartoml"); +var _httpClient = require("../http-client"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var FEDERATION_RESPONSE_MAX_SIZE = exports.FEDERATION_RESPONSE_MAX_SIZE = 100 * 1024; +var FederationServer = exports.FederationServer = function () { + function FederationServer(serverURL, domain) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + _classCallCheck(this, FederationServer); + this.serverURL = (0, _urijs.default)(serverURL); + this.domain = domain; + var allowHttp = typeof opts.allowHttp === "undefined" ? _config.Config.isAllowHttp() : opts.allowHttp; + this.timeout = typeof opts.timeout === "undefined" ? _config.Config.getTimeout() : opts.timeout; + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure federation server"); + } + } + return _createClass(FederationServer, [{ + key: "resolveAddress", + value: (function () { + var _resolveAddress = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(address) { + var stellarAddress, url; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + stellarAddress = address; + if (!(address.indexOf("*") < 0)) { + _context.next = 5; + break; + } + if (this.domain) { + _context.next = 4; + break; + } + return _context.abrupt("return", Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object."))); + case 4: + stellarAddress = "".concat(address, "*").concat(this.domain); + case 5: + url = this.serverURL.query({ + type: "name", + q: stellarAddress + }); + return _context.abrupt("return", this._sendRequest(url)); + case 7: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function resolveAddress(_x) { + return _resolveAddress.apply(this, arguments); + } + return resolveAddress; + }()) + }, { + key: "resolveAccountId", + value: (function () { + var _resolveAccountId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(accountId) { + var url; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + url = this.serverURL.query({ + type: "id", + q: accountId + }); + return _context2.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function resolveAccountId(_x2) { + return _resolveAccountId.apply(this, arguments); + } + return resolveAccountId; + }()) + }, { + key: "resolveTransactionId", + value: (function () { + var _resolveTransactionId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(transactionId) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = this.serverURL.query({ + type: "txid", + q: transactionId + }); + return _context3.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function resolveTransactionId(_x3) { + return _resolveTransactionId.apply(this, arguments); + } + return resolveTransactionId; + }()) + }, { + key: "_sendRequest", + value: function () { + var _sendRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(url) { + var timeout; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + timeout = this.timeout; + return _context4.abrupt("return", _httpClient.httpClient.get(url.toString(), { + maxContentLength: FEDERATION_RESPONSE_MAX_SIZE, + timeout: timeout + }).then(function (response) { + if (typeof response.data.memo !== "undefined" && typeof response.data.memo !== "string") { + throw new Error("memo value should be of type string"); + } + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + if (response.message.match(/^maxContentLength size/)) { + throw new Error("federation response exceeds allowed size of ".concat(FEDERATION_RESPONSE_MAX_SIZE)); + } else { + return Promise.reject(response); + } + } else { + return Promise.reject(new _errors.BadResponseError("Server query failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + } + })); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function _sendRequest(_x4) { + return _sendRequest2.apply(this, arguments); + } + return _sendRequest; + }() + }], [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(value) { + var opts, + addressParts, + _addressParts, + domain, + federationServer, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {}; + if (!(value.indexOf("*") < 0)) { + _context5.next = 5; + break; + } + if (_stellarBase.StrKey.isValidEd25519PublicKey(value)) { + _context5.next = 4; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Account ID"))); + case 4: + return _context5.abrupt("return", Promise.resolve({ + account_id: value + })); + case 5: + addressParts = value.split("*"); + _addressParts = _slicedToArray(addressParts, 2), domain = _addressParts[1]; + if (!(addressParts.length !== 2 || !domain)) { + _context5.next = 9; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Stellar address"))); + case 9: + _context5.next = 11; + return FederationServer.createForDomain(domain, opts); + case 11: + federationServer = _context5.sent; + return _context5.abrupt("return", federationServer.resolveAddress(value)); + case 13: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function resolve(_x5) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }, { + key: "createForDomain", + value: (function () { + var _createForDomain = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(domain) { + var opts, + tomlObject, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : {}; + _context6.next = 3; + return _stellartoml.Resolver.resolve(domain, opts); + case 3: + tomlObject = _context6.sent; + if (tomlObject.FEDERATION_SERVER) { + _context6.next = 6; + break; + } + return _context6.abrupt("return", Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field"))); + case 6: + return _context6.abrupt("return", new FederationServer(tomlObject.FEDERATION_SERVER, domain, opts)); + case 7: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function createForDomain(_x6) { + return _createForDomain.apply(this, arguments); + } + return createForDomain; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/friendbot/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/friendbot/index.d.ts new file mode 100644 index 000000000..5181343e0 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/friendbot/index.d.ts @@ -0,0 +1,6 @@ +export declare namespace Api { + interface Response { + hash: string; + result_meta_xdr: string; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/friendbot/index.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/friendbot/index.js new file mode 100644 index 000000000..081ac7fbf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/friendbot/index.js @@ -0,0 +1,7 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Api = void 0; +var Api; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/account_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/account_call_builder.d.ts new file mode 100644 index 000000000..87c625f4f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/account_call_builder.d.ts @@ -0,0 +1,56 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link AccountCallBuilder} pointed to server defined by `serverUrl`. + * + * Do not create this object directly, use {@link Horizon.Server#accounts}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|All Accounts} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class AccountCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Returns information and links relating to a single account. + * The balances section in the returned JSON will also list all the trust lines this account has set up. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-an-account|Account Details} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {CallBuilder} a new CallBuilder instance for the /accounts/:id endpoint + */ + accountId(id: string): CallBuilder; + /** + * This endpoint filters accounts by signer account. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|Accounts} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + forSigner(id: string): this; + /** + * This endpoint filters all accounts who are trustees to an asset. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|Accounts} + * @see Asset + * @param {Asset} asset For example: `new Asset('USD','GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD')` + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + forAsset(asset: Asset): this; + /** + * This endpoint filters accounts where the given account is sponsoring the account or any of its sub-entries.. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|Accounts} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + sponsor(id: string): this; + /** + * This endpoint filters accounts holding a trustline to the given liquidity pool. + * + * @param {string} id The ID of the liquidity pool. For example: `dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7`. + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + forLiquidityPool(id: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/account_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/account_call_builder.js new file mode 100644 index 000000000..cdf9aa78a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/account_call_builder.js @@ -0,0 +1,62 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AccountCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var AccountCallBuilder = exports.AccountCallBuilder = function (_CallBuilder) { + function AccountCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, AccountCallBuilder); + _this = _callSuper(this, AccountCallBuilder, [serverUrl]); + _this.url.segment("accounts"); + return _this; + } + _inherits(AccountCallBuilder, _CallBuilder); + return _createClass(AccountCallBuilder, [{ + key: "accountId", + value: function accountId(id) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([id]); + return builder; + } + }, { + key: "forSigner", + value: function forSigner(id) { + this.url.setQuery("signer", id); + return this; + } + }, { + key: "forAsset", + value: function forAsset(asset) { + this.url.setQuery("asset", "".concat(asset)); + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(id) { + this.url.setQuery("liquidity_pool", id); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/account_response.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/account_response.d.ts new file mode 100644 index 000000000..a5a448de4 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/account_response.d.ts @@ -0,0 +1,61 @@ +import { HorizonApi } from "./horizon_api"; +import { ServerApi } from "./server_api"; +/** + * Do not create this object directly, use {@link module:Horizon.Server#loadAccount | Horizon.Server#loadAccount}. + * + * Returns information and links relating to a single account. + * The balances section in the returned JSON will also list all the trust lines this account has set up. + * It also contains {@link BaseAccount} object and exposes it's methods so can be used in {@link TransactionBuilder}. + * + * @memberof module:Horizon + * @private + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/accounts/object|Account Details} + * @param {string} response Response from horizon account endpoint. + * @returns {AccountResponse} AccountResponse instance + */ +export declare class AccountResponse { + readonly id: string; + readonly paging_token: string; + readonly account_id: string; + sequence: string; + readonly sequence_ledger?: number; + readonly sequence_time?: string; + readonly subentry_count: number; + readonly home_domain?: string; + readonly inflation_destination?: string; + readonly last_modified_ledger: number; + readonly last_modified_time: string; + readonly thresholds: HorizonApi.AccountThresholds; + readonly flags: HorizonApi.Flags; + readonly balances: HorizonApi.BalanceLine[]; + readonly signers: ServerApi.AccountRecordSigners[]; + readonly data: (options: { + value: string; + }) => Promise<{ + value: string; + }>; + readonly data_attr: Record; + readonly effects: ServerApi.CallCollectionFunction; + readonly offers: ServerApi.CallCollectionFunction; + readonly operations: ServerApi.CallCollectionFunction; + readonly payments: ServerApi.CallCollectionFunction; + readonly trades: ServerApi.CallCollectionFunction; + private readonly _baseAccount; + constructor(response: ServerApi.AccountRecord); + /** + * Get Stellar account public key ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA` + * @returns {string} accountId + */ + accountId(): string; + /** + * Get the current sequence number + * @returns {string} sequenceNumber + */ + sequenceNumber(): string; + /** + * Increments sequence number in this object by one. + * @returns {void} + */ + incrementSequenceNumber(): void; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/account_response.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/account_response.js new file mode 100644 index 000000000..682b46360 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/account_response.js @@ -0,0 +1,49 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AccountResponse = void 0; +var _stellarBase = require("@stellar/stellar-base"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var AccountResponse = exports.AccountResponse = function () { + function AccountResponse(response) { + var _this = this; + _classCallCheck(this, AccountResponse); + this._baseAccount = new _stellarBase.Account(response.account_id, response.sequence); + Object.entries(response).forEach(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + _this[key] = value; + }); + } + return _createClass(AccountResponse, [{ + key: "accountId", + value: function accountId() { + return this._baseAccount.accountId(); + } + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this._baseAccount.sequenceNumber(); + } + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + this._baseAccount.incrementSequenceNumber(); + this.sequence = this._baseAccount.sequenceNumber(); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/assets_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/assets_call_builder.d.ts new file mode 100644 index 000000000..38c7f9f14 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/assets_call_builder.d.ts @@ -0,0 +1,27 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link AssetsCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#assets}. + * + * @class + * @augments CallBuilder + * @private + * @param {string} serverUrl Horizon server URL. + */ +export declare class AssetsCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * This endpoint filters all assets by the asset code. + * @param {string} value For example: `USD` + * @returns {AssetsCallBuilder} current AssetCallBuilder instance + */ + forCode(value: string): AssetsCallBuilder; + /** + * This endpoint filters all assets by the asset issuer. + * @param {string} value For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {AssetsCallBuilder} current AssetCallBuilder instance + */ + forIssuer(value: string): AssetsCallBuilder; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/assets_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/assets_call_builder.js new file mode 100644 index 000000000..68d89ba1f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/assets_call_builder.js @@ -0,0 +1,43 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AssetsCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var AssetsCallBuilder = exports.AssetsCallBuilder = function (_CallBuilder) { + function AssetsCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, AssetsCallBuilder); + _this = _callSuper(this, AssetsCallBuilder, [serverUrl]); + _this.url.segment("assets"); + return _this; + } + _inherits(AssetsCallBuilder, _CallBuilder); + return _createClass(AssetsCallBuilder, [{ + key: "forCode", + value: function forCode(value) { + this.url.setQuery("asset_code", value); + return this; + } + }, { + key: "forIssuer", + value: function forIssuer(value) { + this.url.setQuery("asset_issuer", value); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/call_builder.d.ts new file mode 100644 index 000000000..f40d6db20 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/call_builder.d.ts @@ -0,0 +1,128 @@ +import URI from "urijs"; +import { HorizonApi } from "./horizon_api"; +import { ServerApi } from "./server_api"; +export interface EventSourceOptions { + onmessage?: (value: T) => void; + onerror?: (event: MessageEvent) => void; + reconnectTimeout?: number; +} +/** + * Creates a new {@link CallBuilder} pointed to server defined by serverUrl. + * + * This is an **abstract** class. Do not create this object directly, use {@link Server} class. + * @param {string} serverUrl URL of Horizon server + * @class CallBuilder + */ +export declare class CallBuilder> { + protected url: URI; + filter: string[][]; + protected originalSegments: string[]; + protected neighborRoot: string; + constructor(serverUrl: URI, neighborRoot?: string); + /** + * Triggers a HTTP request using this builder's current configuration. + * @returns {Promise} a Promise that resolves to the server's response. + */ + call(): Promise; + /** + * Creates an EventSource that listens for incoming messages from the server. To stop listening for new + * events call the function returned by this method. + * @see [Horizon Response Format](https://developers.stellar.org/api/introduction/response-format/) + * @see [MDN EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) + * @param {object} [options] EventSource options. + * @param {Function} [options.onmessage] Callback function to handle incoming messages. + * @param {Function} [options.onerror] Callback function to handle errors. + * @param {number} [options.reconnectTimeout] Custom stream connection timeout in ms, default is 15 seconds. + * @returns {Function} Close function. Run to close the connection and stop listening for new events. + */ + stream(options?: EventSourceOptions ? U : T>): () => void; + /** + * Sets `cursor` parameter for the current call. Returns the CallBuilder object on which this method has been called. + * @see [Paging](https://developers.stellar.org/api/introduction/pagination/) + * @param {string} cursor A cursor is a value that points to a specific location in a collection of resources. + * @returns {object} current CallBuilder instance + */ + cursor(cursor: string): this; + /** + * Sets `limit` parameter for the current call. Returns the CallBuilder object on which this method has been called. + * @see [Paging](https://developers.stellar.org/api/introduction/pagination/) + * @param {number} recordsNumber Number of records the server should return. + * @returns {object} current CallBuilder instance + */ + limit(recordsNumber: number): this; + /** + * Sets `order` parameter for the current call. Returns the CallBuilder object on which this method has been called. + * @param {"asc"|"desc"} direction Sort direction + * @returns {object} current CallBuilder instance + */ + order(direction: "asc" | "desc"): this; + /** + * Sets `join` parameter for the current call. The `join` parameter + * includes the requested resource in the response. Currently, the + * only valid value for the parameter is `transactions` and is only + * supported on the operations and payments endpoints. The response + * will include a `transaction` field for each operation in the + * response. + * + * @param "include" join Records to be included in the response. + * @returns {object} current CallBuilder instance. + */ + join(include: "transactions"): this; + /** + * A helper method to craft queries to "neighbor" endpoints. + * + * For example, we have an `/effects` suffix endpoint on many different + * "root" endpoints, such as `/transactions/:id` and `/accounts/:id`. So, + * it's helpful to be able to conveniently create queries to the + * `/accounts/:id/effects` endpoint: + * + * this.forEndpoint("accounts", accountId)`. + * + * @param {string} endpoint neighbor endpoint in question, like /operations + * @param {string} param filter parameter, like an operation ID + * + * @returns {CallBuilder} this CallBuilder instance + */ + protected forEndpoint(endpoint: string, param: string): this; + /** + * @private + * @returns {void} + */ + private checkFilter; + /** + * Convert a link object to a function that fetches that link. + * @private + * @param {object} link A link object + * @param {boolean} link.href the URI of the link + * @param {boolean} [link.templated] Whether the link is templated + * @returns {Function} A function that requests the link + */ + private _requestFnForLink; + /** + * Given the json response, find and convert each link into a function that + * calls that link. + * @private + * @param {object} json JSON response + * @returns {object} JSON response with string links replaced with functions + */ + private _parseRecord; + private _sendNormalRequest; + /** + * @private + * @param {object} json Response object + * @returns {object} Extended response + */ + private _parseResponse; + /** + * @private + * @param {object} json Response object + * @returns {object} Extended response object + */ + private _toCollectionPage; + /** + * @private + * @param {object} error Network error object + * @returns {Promise} Promise that rejects with a human-readable error + */ + private _handleNetworkError; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/call_builder.js new file mode 100644 index 000000000..76d56529d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/call_builder.js @@ -0,0 +1,362 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.CallBuilder = void 0; +var _urijs = _interopRequireDefault(require("urijs")); +var _URITemplate = _interopRequireDefault(require("urijs/src/URITemplate")); +var _errors = require("../errors"); +var _horizon_axios_client = require("./horizon_axios_client"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var JOINABLE = ["transaction"]; +var anyGlobal = global; +var EventSource; +if (typeof true !== 'undefined' && true) { + var _ref, _anyGlobal$EventSourc, _anyGlobal$window; + EventSource = (_ref = (_anyGlobal$EventSourc = anyGlobal.EventSource) !== null && _anyGlobal$EventSourc !== void 0 ? _anyGlobal$EventSourc : (_anyGlobal$window = anyGlobal.window) === null || _anyGlobal$window === void 0 ? void 0 : _anyGlobal$window.EventSource) !== null && _ref !== void 0 ? _ref : require("eventsource"); +} +var CallBuilder = exports.CallBuilder = function () { + function CallBuilder(serverUrl) { + var neighborRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; + _classCallCheck(this, CallBuilder); + this.url = serverUrl.clone(); + this.filter = []; + this.originalSegments = this.url.segment() || []; + this.neighborRoot = neighborRoot; + } + return _createClass(CallBuilder, [{ + key: "call", + value: function call() { + var _this = this; + this.checkFilter(); + return this._sendNormalRequest(this.url).then(function (r) { + return _this._parseResponse(r); + }); + } + }, { + key: "stream", + value: function stream() { + var _this2 = this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (EventSource === undefined) { + throw new Error("Streaming requires eventsource to be enabled. If you need this functionality, compile with USE_EVENTSOURCE=true."); + } + this.checkFilter(); + this.url.setQuery("X-Client-Name", "js-stellar-sdk"); + this.url.setQuery("X-Client-Version", _horizon_axios_client.version); + var es; + var timeout; + var createTimeout = function createTimeout() { + timeout = setTimeout(function () { + var _es; + (_es = es) === null || _es === void 0 || _es.close(); + es = _createEventSource(); + }, options.reconnectTimeout || 15 * 1000); + }; + var _createEventSource = function createEventSource() { + try { + es = new EventSource(_this2.url.toString()); + } catch (err) { + if (options.onerror) { + options.onerror(err); + } + } + createTimeout(); + if (!es) { + return es; + } + var closed = false; + var onClose = function onClose() { + if (closed) { + return; + } + clearTimeout(timeout); + es.close(); + _createEventSource(); + closed = true; + }; + var onMessage = function onMessage(message) { + if (message.type === "close") { + onClose(); + return; + } + var result = message.data ? _this2._parseRecord(JSON.parse(message.data)) : message; + if (result.paging_token) { + _this2.url.setQuery("cursor", result.paging_token); + } + clearTimeout(timeout); + createTimeout(); + if (typeof options.onmessage !== "undefined") { + options.onmessage(result); + } + }; + var onError = function onError(error) { + if (options.onerror) { + options.onerror(error); + } + }; + if (es.addEventListener) { + es.addEventListener("message", onMessage.bind(_this2)); + es.addEventListener("error", onError.bind(_this2)); + es.addEventListener("close", onClose.bind(_this2)); + } else { + es.onmessage = onMessage.bind(_this2); + es.onerror = onError.bind(_this2); + } + return es; + }; + _createEventSource(); + return function () { + var _es2; + clearTimeout(timeout); + (_es2 = es) === null || _es2 === void 0 || _es2.close(); + }; + } + }, { + key: "cursor", + value: function cursor(_cursor) { + this.url.setQuery("cursor", _cursor); + return this; + } + }, { + key: "limit", + value: function limit(recordsNumber) { + this.url.setQuery("limit", recordsNumber.toString()); + return this; + } + }, { + key: "order", + value: function order(direction) { + this.url.setQuery("order", direction); + return this; + } + }, { + key: "join", + value: function join(include) { + this.url.setQuery("join", include); + return this; + } + }, { + key: "forEndpoint", + value: function forEndpoint(endpoint, param) { + if (this.neighborRoot === "") { + throw new Error("Invalid usage: neighborRoot not set in constructor"); + } + this.filter.push([endpoint, param, this.neighborRoot]); + return this; + } + }, { + key: "checkFilter", + value: function checkFilter() { + if (this.filter.length >= 2) { + throw new _errors.BadRequestError("Too many filters specified", this.filter); + } + if (this.filter.length === 1) { + var newSegment = this.originalSegments.concat(this.filter[0]); + this.url.segment(newSegment); + } + } + }, { + key: "_requestFnForLink", + value: function _requestFnForLink(link) { + var _this3 = this; + return _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var opts, + uri, + template, + r, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}; + if (link.templated) { + template = (0, _URITemplate.default)(link.href); + uri = (0, _urijs.default)(template.expand(opts)); + } else { + uri = (0, _urijs.default)(link.href); + } + _context.next = 4; + return _this3._sendNormalRequest(uri); + case 4: + r = _context.sent; + return _context.abrupt("return", _this3._parseResponse(r)); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + } + }, { + key: "_parseRecord", + value: function _parseRecord(json) { + var _this4 = this; + if (!json._links) { + return json; + } + Object.keys(json._links).forEach(function (key) { + var n = json._links[key]; + var included = false; + if (typeof json[key] !== "undefined") { + json["".concat(key, "_attr")] = json[key]; + included = true; + } + if (included && JOINABLE.indexOf(key) >= 0) { + var record = _this4._parseRecord(json[key]); + json[key] = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", record); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + } else { + json[key] = _this4._requestFnForLink(n); + } + }); + return json; + } + }, { + key: "_sendNormalRequest", + value: function () { + var _sendNormalRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(initialUrl) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = initialUrl; + if (url.authority() === "") { + url = url.authority(this.url.authority()); + } + if (url.protocol() === "") { + url = url.protocol(this.url.protocol()); + } + return _context3.abrupt("return", _horizon_axios_client.AxiosClient.get(url.toString()).then(function (response) { + return response.data; + }).catch(this._handleNetworkError)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function _sendNormalRequest(_x) { + return _sendNormalRequest2.apply(this, arguments); + } + return _sendNormalRequest; + }() + }, { + key: "_parseResponse", + value: function _parseResponse(json) { + if (json._embedded && json._embedded.records) { + return this._toCollectionPage(json); + } + return this._parseRecord(json); + } + }, { + key: "_toCollectionPage", + value: function _toCollectionPage(json) { + var _this5 = this; + for (var i = 0; i < json._embedded.records.length; i += 1) { + json._embedded.records[i] = this._parseRecord(json._embedded.records[i]); + } + return { + records: json._embedded.records, + next: function () { + var _next2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + var r; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this5._sendNormalRequest((0, _urijs.default)(json._links.next.href)); + case 2: + r = _context4.sent; + return _context4.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function next() { + return _next2.apply(this, arguments); + } + return next; + }(), + prev: function () { + var _prev = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5() { + var r; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return _this5._sendNormalRequest((0, _urijs.default)(json._links.prev.href)); + case 2: + r = _context5.sent; + return _context5.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function prev() { + return _prev.apply(this, arguments); + } + return prev; + }() + }; + } + }, { + key: "_handleNetworkError", + value: (function () { + var _handleNetworkError2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(error) { + var _error$response$statu, _error$response$statu2; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + if (!(error.response && error.response.status)) { + _context6.next = 8; + break; + } + _context6.t0 = error.response.status; + _context6.next = _context6.t0 === 404 ? 4 : 5; + break; + case 4: + return _context6.abrupt("return", Promise.reject(new _errors.NotFoundError((_error$response$statu = error.response.statusText) !== null && _error$response$statu !== void 0 ? _error$response$statu : "Not Found", error.response.data))); + case 5: + return _context6.abrupt("return", Promise.reject(new _errors.NetworkError((_error$response$statu2 = error.response.statusText) !== null && _error$response$statu2 !== void 0 ? _error$response$statu2 : "Unknown", error.response.data))); + case 6: + _context6.next = 9; + break; + case 8: + return _context6.abrupt("return", Promise.reject(new Error(error.message))); + case 9: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function _handleNetworkError(_x2) { + return _handleNetworkError2.apply(this, arguments); + } + return _handleNetworkError; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/claimable_balances_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/claimable_balances_call_builder.d.ts new file mode 100644 index 000000000..6e5f7eea7 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/claimable_balances_call_builder.d.ts @@ -0,0 +1,50 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link ClaimableBalanceCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#claimableBalances}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/claimablebalances|Claimable Balances} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class ClaimableBalanceCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The claimable balance details endpoint provides information on a single claimable balance. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-claimable-balance|Claimable Balance Details} + * @param {string} claimableBalanceId Claimable balance ID + * @returns {CallBuilder} CallBuilder OperationCallBuilder instance + */ + claimableBalance(claimableBalanceId: string): CallBuilder; + /** + * Returns all claimable balances which are sponsored by the given account ID. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-claimable-balances|Claimable Balances} + * @param {string} sponsor For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance + */ + sponsor(sponsor: string): this; + /** + * Returns all claimable balances which can be claimed by the given account ID. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-claimable-balances|Claimable Balances} + * @param {string} claimant For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance + */ + claimant(claimant: string): this; + /** + * Returns all claimable balances which provide a balance for the given asset. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-claimable-balances|Claimable Balances} + * @param {Asset} asset The Asset held by the claimable balance + * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance + */ + asset(asset: Asset): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/claimable_balances_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/claimable_balances_call_builder.js new file mode 100644 index 000000000..188c8076a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/claimable_balances_call_builder.js @@ -0,0 +1,56 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ClaimableBalanceCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var ClaimableBalanceCallBuilder = exports.ClaimableBalanceCallBuilder = function (_CallBuilder) { + function ClaimableBalanceCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, ClaimableBalanceCallBuilder); + _this = _callSuper(this, ClaimableBalanceCallBuilder, [serverUrl]); + _this.url.segment("claimable_balances"); + return _this; + } + _inherits(ClaimableBalanceCallBuilder, _CallBuilder); + return _createClass(ClaimableBalanceCallBuilder, [{ + key: "claimableBalance", + value: function claimableBalance(claimableBalanceId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([claimableBalanceId]); + return builder; + } + }, { + key: "sponsor", + value: function sponsor(_sponsor) { + this.url.setQuery("sponsor", _sponsor); + return this; + } + }, { + key: "claimant", + value: function claimant(_claimant) { + this.url.setQuery("claimant", _claimant); + return this; + } + }, { + key: "asset", + value: function asset(_asset) { + this.url.setQuery("asset", _asset.toString()); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/effect_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/effect_call_builder.d.ts new file mode 100644 index 000000000..8f1e56266 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/effect_call_builder.d.ts @@ -0,0 +1,53 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link EffectCallBuilder} pointed to server defined by serverUrl. + * Do not create this object directly, use {@link Horizon.Server#effects}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/effects|All Effects} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class EffectCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * This endpoint represents all effects that changed a given account. It will return relevant effects from the creation of the account to the current ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-effects-by-account-id|Effects for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * Effects are the specific ways that the ledger was changed by any operation. + * + * This endpoint represents all effects that occurred in the given ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-ledgers-effects|Effects for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all effects that occurred as a result of a given transaction. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-transactions-effects|Effects for Transaction} + * @param {string} transactionId Transaction ID + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forTransaction(transactionId: string): this; + /** + * This endpoint represents all effects that occurred as a result of a given operation. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-an-operations-effects|Effects for Operation} + * @param {number} operationId Operation ID + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forOperation(operationId: string): this; + /** + * This endpoint represents all effects involving a particular liquidity pool. + * + * @param {string} poolId liquidity pool ID + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forLiquidityPool(poolId: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/effect_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/effect_call_builder.js new file mode 100644 index 000000000..147128700 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/effect_call_builder.js @@ -0,0 +1,56 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.EffectCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var EffectCallBuilder = exports.EffectCallBuilder = function (_CallBuilder) { + function EffectCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, EffectCallBuilder); + _this = _callSuper(this, EffectCallBuilder, [serverUrl, "effects"]); + _this.url.segment("effects"); + return _this; + } + _inherits(EffectCallBuilder, _CallBuilder); + return _createClass(EffectCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forOperation", + value: function forOperation(operationId) { + return this.forEndpoint("operations", operationId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/friendbot_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/friendbot_builder.d.ts new file mode 100644 index 000000000..30e5addb9 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/friendbot_builder.d.ts @@ -0,0 +1,4 @@ +import { CallBuilder } from "./call_builder"; +export declare class FriendbotBuilder extends CallBuilder { + constructor(serverUrl: URI, address: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/friendbot_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/friendbot_builder.js new file mode 100644 index 000000000..f80bd06f8 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/friendbot_builder.js @@ -0,0 +1,32 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FriendbotBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var FriendbotBuilder = exports.FriendbotBuilder = function (_CallBuilder) { + function FriendbotBuilder(serverUrl, address) { + var _this; + _classCallCheck(this, FriendbotBuilder); + _this = _callSuper(this, FriendbotBuilder, [serverUrl]); + _this.url.segment("friendbot"); + _this.url.setQuery("addr", address); + return _this; + } + _inherits(FriendbotBuilder, _CallBuilder); + return _createClass(FriendbotBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/horizon_api.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/horizon_api.d.ts new file mode 100644 index 000000000..d52968614 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/horizon_api.d.ts @@ -0,0 +1,540 @@ +import { AssetType, MemoType } from "@stellar/stellar-base"; +export declare namespace HorizonApi { + interface ResponseLink { + href: string; + templated?: boolean; + } + interface BaseResponse { + _links: { + [key in T | "self"]: ResponseLink; + }; + } + interface SubmitTransactionResponse { + hash: string; + ledger: number; + successful: boolean; + envelope_xdr: string; + result_xdr: string; + result_meta_xdr: string; + paging_token: string; + } + interface SubmitAsyncTransactionResponse { + hash: string; + tx_status: string; + error_result_xdr: string; + } + interface FeeBumpTransactionResponse { + hash: string; + signatures: string[]; + } + interface InnerTransactionResponse { + hash: string; + signatures: string[]; + max_fee: string; + } + interface TransactionPreconditions { + timebounds?: { + min_time: string; + max_time: string; + }; + ledgerbounds?: { + min_ledger: number; + max_ledger: number; + }; + min_account_sequence?: string; + min_account_sequence_age?: string; + min_account_sequence_ledger_gap?: number; + extra_signers?: string[]; + } + interface TransactionResponse extends SubmitTransactionResponse, BaseResponse<"account" | "ledger" | "operations" | "effects" | "succeeds" | "precedes"> { + created_at: string; + fee_meta_xdr: string; + fee_charged: number | string; + max_fee: number | string; + id: string; + memo_type: MemoType; + memo?: string; + memo_bytes?: string; + operation_count: number; + paging_token: string; + signatures: string[]; + source_account: string; + source_account_sequence: string; + fee_account: string; + inner_transaction?: InnerTransactionResponse; + fee_bump_transaction?: FeeBumpTransactionResponse; + preconditions?: TransactionPreconditions; + } + interface BalanceLineNative { + balance: string; + asset_type: AssetType.native; + buying_liabilities: string; + selling_liabilities: string; + } + interface BalanceLineLiquidityPool { + liquidity_pool_id: string; + asset_type: AssetType.liquidityPoolShares; + balance: string; + limit: string; + last_modified_ledger: number; + is_authorized: boolean; + is_authorized_to_maintain_liabilities: boolean; + is_clawback_enabled: boolean; + sponsor?: string; + } + interface BalanceLineAsset { + balance: string; + limit: string; + asset_type: T; + asset_code: string; + asset_issuer: string; + buying_liabilities: string; + selling_liabilities: string; + last_modified_ledger: number; + is_authorized: boolean; + is_authorized_to_maintain_liabilities: boolean; + is_clawback_enabled: boolean; + sponsor?: string; + } + type BalanceLine = T extends AssetType.native ? BalanceLineNative : T extends AssetType.credit4 | AssetType.credit12 ? BalanceLineAsset : T extends AssetType.liquidityPoolShares ? BalanceLineLiquidityPool : BalanceLineNative | BalanceLineAsset | BalanceLineLiquidityPool; + interface AssetAccounts { + authorized: number; + authorized_to_maintain_liabilities: number; + unauthorized: number; + } + interface AssetBalances { + authorized: string; + authorized_to_maintain_liabilities: string; + unauthorized: string; + } + interface PriceR { + numerator: number; + denominator: number; + } + interface PriceRShorthand { + n: number; + d: number; + } + interface AccountThresholds { + low_threshold: number; + med_threshold: number; + high_threshold: number; + } + interface Flags { + auth_immutable: boolean; + auth_required: boolean; + auth_revocable: boolean; + auth_clawback_enabled: boolean; + } + interface AccountSigner { + key: string; + weight: number; + type: string; + sponsor?: string; + } + interface AccountResponse extends BaseResponse<"transactions" | "operations" | "payments" | "effects" | "offers" | "trades" | "data"> { + id: string; + paging_token: string; + account_id: string; + sequence: string; + sequence_ledger?: number; + sequence_time?: string; + subentry_count: number; + thresholds: AccountThresholds; + last_modified_ledger: number; + last_modified_time: string; + flags: Flags; + balances: BalanceLine[]; + signers: AccountSigner[]; + data: { + [key: string]: string; + }; + sponsor?: string; + num_sponsoring: number; + num_sponsored: number; + } + enum LiquidityPoolType { + constantProduct = "constant_product" + } + enum OperationResponseType { + createAccount = "create_account", + payment = "payment", + pathPayment = "path_payment_strict_receive", + createPassiveOffer = "create_passive_sell_offer", + manageOffer = "manage_sell_offer", + setOptions = "set_options", + changeTrust = "change_trust", + allowTrust = "allow_trust", + accountMerge = "account_merge", + inflation = "inflation", + manageData = "manage_data", + bumpSequence = "bump_sequence", + manageBuyOffer = "manage_buy_offer", + pathPaymentStrictSend = "path_payment_strict_send", + createClaimableBalance = "create_claimable_balance", + claimClaimableBalance = "claim_claimable_balance", + beginSponsoringFutureReserves = "begin_sponsoring_future_reserves", + endSponsoringFutureReserves = "end_sponsoring_future_reserves", + revokeSponsorship = "revoke_sponsorship", + clawback = "clawback", + clawbackClaimableBalance = "clawback_claimable_balance", + setTrustLineFlags = "set_trust_line_flags", + liquidityPoolDeposit = "liquidity_pool_deposit", + liquidityPoolWithdraw = "liquidity_pool_withdraw", + invokeHostFunction = "invoke_host_function", + bumpFootprintExpiration = "bump_footprint_expiration", + restoreFootprint = "restore_footprint" + } + enum OperationResponseTypeI { + createAccount = 0, + payment = 1, + pathPayment = 2, + createPassiveOffer = 3, + manageOffer = 4, + setOptions = 5, + changeTrust = 6, + allowTrust = 7, + accountMerge = 8, + inflation = 9, + manageData = 10, + bumpSequence = 11, + manageBuyOffer = 12, + pathPaymentStrictSend = 13, + createClaimableBalance = 14, + claimClaimableBalance = 15, + beginSponsoringFutureReserves = 16, + endSponsoringFutureReserves = 17, + revokeSponsorship = 18, + clawback = 19, + clawbackClaimableBalance = 20, + setTrustLineFlags = 21, + liquidityPoolDeposit = 22, + liquidityPoolWithdraw = 23, + invokeHostFunction = 24, + bumpFootprintExpiration = 25, + restoreFootprint = 26 + } + interface BaseOperationResponse extends BaseResponse<"succeeds" | "precedes" | "effects" | "transaction"> { + id: string; + paging_token: string; + source_account: string; + type: T; + type_i: TI; + created_at: string; + transaction_hash: string; + transaction_successful: boolean; + } + interface CreateAccountOperationResponse extends BaseOperationResponse { + account: string; + funder: string; + starting_balance: string; + } + interface PaymentOperationResponse extends BaseOperationResponse { + from: string; + to: string; + asset_type: AssetType; + asset_code?: string; + asset_issuer?: string; + amount: string; + } + interface PathPaymentOperationResponse extends BaseOperationResponse { + amount: string; + asset_code?: string; + asset_issuer?: string; + asset_type: AssetType; + from: string; + path: Array<{ + asset_code: string; + asset_issuer: string; + asset_type: AssetType; + }>; + source_amount: string; + source_asset_code?: string; + source_asset_issuer?: string; + source_asset_type: AssetType; + source_max: string; + to: string; + } + interface PathPaymentStrictSendOperationResponse extends BaseOperationResponse { + amount: string; + asset_code?: string; + asset_issuer?: string; + asset_type: AssetType; + destination_min: string; + from: string; + path: Array<{ + asset_code: string; + asset_issuer: string; + asset_type: AssetType; + }>; + source_amount: string; + source_asset_code?: string; + source_asset_issuer?: string; + source_asset_type: AssetType; + to: string; + } + interface ManageOfferOperationResponse extends BaseOperationResponse { + offer_id: number | string; + amount: string; + buying_asset_type: AssetType; + buying_asset_code?: string; + buying_asset_issuer?: string; + price: string; + price_r: PriceR; + selling_asset_type: AssetType; + selling_asset_code?: string; + selling_asset_issuer?: string; + } + interface PassiveOfferOperationResponse extends BaseOperationResponse { + offer_id: number | string; + amount: string; + buying_asset_type: AssetType; + buying_asset_code?: string; + buying_asset_issuer?: string; + price: string; + price_r: PriceR; + selling_asset_type: AssetType; + selling_asset_code?: string; + selling_asset_issuer?: string; + } + interface SetOptionsOperationResponse extends BaseOperationResponse { + signer_key?: string; + signer_weight?: number; + master_key_weight?: number; + low_threshold?: number; + med_threshold?: number; + high_threshold?: number; + home_domain?: string; + set_flags: Array<1 | 2 | 4>; + set_flags_s: Array<"auth_required_flag" | "auth_revocable_flag" | "auth_clawback_enabled_flag">; + clear_flags: Array<1 | 2 | 4>; + clear_flags_s: Array<"auth_required_flag" | "auth_revocable_flag" | "auth_clawback_enabled_flag">; + } + interface ChangeTrustOperationResponse extends BaseOperationResponse { + asset_type: AssetType.credit4 | AssetType.credit12 | AssetType.liquidityPoolShares; + asset_code?: string; + asset_issuer?: string; + liquidity_pool_id?: string; + trustee?: string; + trustor: string; + limit: string; + } + interface AllowTrustOperationResponse extends BaseOperationResponse { + asset_type: AssetType; + asset_code: string; + asset_issuer: string; + authorize: boolean; + authorize_to_maintain_liabilities: boolean; + trustee: string; + trustor: string; + } + interface AccountMergeOperationResponse extends BaseOperationResponse { + into: string; + } + interface InflationOperationResponse extends BaseOperationResponse { + } + interface ManageDataOperationResponse extends BaseOperationResponse { + name: string; + value: Buffer; + } + interface BumpSequenceOperationResponse extends BaseOperationResponse { + bump_to: string; + } + interface Predicate { + and?: Predicate[]; + or?: Predicate[]; + not?: Predicate; + abs_before?: string; + rel_before?: string; + } + interface Claimant { + destination: string; + predicate: Predicate; + } + interface CreateClaimableBalanceOperationResponse extends BaseOperationResponse { + asset: string; + amount: string; + sponsor: string; + claimants: Claimant[]; + } + interface ClaimClaimableBalanceOperationResponse extends BaseOperationResponse { + balance_id: string; + claimant: string; + } + interface BeginSponsoringFutureReservesOperationResponse extends BaseOperationResponse { + sponsored_id: string; + } + interface EndSponsoringFutureReservesOperationResponse extends BaseOperationResponse { + begin_sponsor: string; + } + interface RevokeSponsorshipOperationResponse extends BaseOperationResponse { + account_id?: string; + claimable_balance_id?: string; + data_account_id?: string; + data_name?: string; + offer_id?: string; + trustline_account_id?: string; + trustline_asset?: string; + trustline_liquidity_pool_id?: string; + signer_account_id?: string; + signer_key?: string; + } + interface ClawbackOperationResponse extends BaseOperationResponse { + asset_type: AssetType; + asset_code: string; + asset_issuer: string; + from: string; + amount: string; + } + interface ClawbackClaimableBalanceOperationResponse extends BaseOperationResponse { + balance_id: string; + } + interface SetTrustLineFlagsOperationResponse extends BaseOperationResponse { + asset_type: AssetType; + asset_code: string; + asset_issuer: string; + trustor: string; + set_flags: Array<1 | 2 | 4>; + clear_flags: Array<1 | 2 | 4>; + } + interface Reserve { + asset: string; + amount: string; + } + interface DepositLiquidityOperationResponse extends BaseOperationResponse { + liquidity_pool_id: string; + reserves_max: Reserve[]; + min_price: string; + min_price_r: PriceRShorthand; + max_price: string; + max_price_r: PriceRShorthand; + reserves_deposited: Reserve[]; + shares_received: string; + } + interface WithdrawLiquidityOperationResponse extends BaseOperationResponse { + liquidity_pool_id: string; + reserves_min: Reserve[]; + shares: string; + reserves_received: Reserve[]; + } + interface BalanceChange { + asset_type: string; + asset_code?: string; + asset_issuer?: string; + type: string; + from: string; + to: string; + amount: string; + } + interface InvokeHostFunctionOperationResponse extends BaseOperationResponse { + function: string; + parameters: { + value: string; + type: string; + }[]; + address: string; + salt: string; + asset_balance_changes: BalanceChange[]; + } + interface BumpFootprintExpirationOperationResponse extends BaseOperationResponse { + ledgers_to_expire: number; + } + interface RestoreFootprintOperationResponse extends BaseOperationResponse { + } + interface ResponseCollection { + _links: { + self: ResponseLink; + next: ResponseLink; + prev: ResponseLink; + }; + _embedded: { + records: T[]; + }; + } + interface TransactionResponseCollection extends ResponseCollection { + } + interface FeeDistribution { + max: string; + min: string; + mode: string; + p10: string; + p20: string; + p30: string; + p40: string; + p50: string; + p60: string; + p70: string; + p80: string; + p90: string; + p95: string; + p99: string; + } + interface FeeStatsResponse { + last_ledger: string; + last_ledger_base_fee: string; + ledger_capacity_usage: string; + fee_charged: FeeDistribution; + max_fee: FeeDistribution; + } + type ErrorResponseData = ErrorResponseData.RateLimitExceeded | ErrorResponseData.InternalServerError | ErrorResponseData.TransactionFailed; + namespace ErrorResponseData { + interface Base { + status: number; + title: string; + type: string; + details: string; + instance: string; + } + interface RateLimitExceeded extends Base { + status: 429; + title: "Rate Limit Exceeded"; + } + interface InternalServerError extends Base { + status: 500; + title: "Internal Server Error"; + } + interface TransactionFailed extends Base { + status: 400; + title: "Transaction Failed"; + extras: TransactionFailedExtras; + } + } + enum TransactionFailedResultCodes { + TX_FAILED = "tx_failed", + TX_BAD_SEQ = "tx_bad_seq", + TX_BAD_AUTH = "tx_bad_auth", + TX_BAD_AUTH_EXTRA = "tx_bad_auth_extra", + TX_FEE_BUMP_INNER_SUCCESS = "tx_fee_bump_inner_success", + TX_FEE_BUMP_INNER_FAILED = "tx_fee_bump_inner_failed", + TX_NOT_SUPPORTED = "tx_not_supported", + TX_SUCCESS = "tx_success", + TX_TOO_EARLY = "tx_too_early", + TX_TOO_LATE = "tx_too_late", + TX_MISSING_OPERATION = "tx_missing_operation", + TX_INSUFFICIENT_BALANCE = "tx_insufficient_balance", + TX_NO_SOURCE_ACCOUNT = "tx_no_source_account", + TX_INSUFFICIENT_FEE = "tx_insufficient_fee", + TX_INTERNAL_ERROR = "tx_internal_error" + } + interface TransactionFailedExtras { + envelope_xdr: string; + result_codes: { + transaction: TransactionFailedResultCodes; + operations: string[]; + }; + result_xdr: string; + } + interface RootResponse { + horizon_version: string; + core_version: string; + ingest_latest_ledger: number; + history_latest_ledger: number; + history_latest_ledger_closed_at: string; + history_elder_ledger: number; + core_latest_ledger: number; + network_passphrase: string; + current_protocol_version: number; + supported_protocol_version: number; + core_supported_protocol_version: number; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/horizon_api.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/horizon_api.js new file mode 100644 index 000000000..b4b1c1878 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/horizon_api.js @@ -0,0 +1,96 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.HorizonApi = void 0; +var HorizonApi; +(function (_HorizonApi) { + var LiquidityPoolType = function (LiquidityPoolType) { + LiquidityPoolType["constantProduct"] = "constant_product"; + return LiquidityPoolType; + }({}); + _HorizonApi.LiquidityPoolType = LiquidityPoolType; + var OperationResponseType = function (OperationResponseType) { + OperationResponseType["createAccount"] = "create_account"; + OperationResponseType["payment"] = "payment"; + OperationResponseType["pathPayment"] = "path_payment_strict_receive"; + OperationResponseType["createPassiveOffer"] = "create_passive_sell_offer"; + OperationResponseType["manageOffer"] = "manage_sell_offer"; + OperationResponseType["setOptions"] = "set_options"; + OperationResponseType["changeTrust"] = "change_trust"; + OperationResponseType["allowTrust"] = "allow_trust"; + OperationResponseType["accountMerge"] = "account_merge"; + OperationResponseType["inflation"] = "inflation"; + OperationResponseType["manageData"] = "manage_data"; + OperationResponseType["bumpSequence"] = "bump_sequence"; + OperationResponseType["manageBuyOffer"] = "manage_buy_offer"; + OperationResponseType["pathPaymentStrictSend"] = "path_payment_strict_send"; + OperationResponseType["createClaimableBalance"] = "create_claimable_balance"; + OperationResponseType["claimClaimableBalance"] = "claim_claimable_balance"; + OperationResponseType["beginSponsoringFutureReserves"] = "begin_sponsoring_future_reserves"; + OperationResponseType["endSponsoringFutureReserves"] = "end_sponsoring_future_reserves"; + OperationResponseType["revokeSponsorship"] = "revoke_sponsorship"; + OperationResponseType["clawback"] = "clawback"; + OperationResponseType["clawbackClaimableBalance"] = "clawback_claimable_balance"; + OperationResponseType["setTrustLineFlags"] = "set_trust_line_flags"; + OperationResponseType["liquidityPoolDeposit"] = "liquidity_pool_deposit"; + OperationResponseType["liquidityPoolWithdraw"] = "liquidity_pool_withdraw"; + OperationResponseType["invokeHostFunction"] = "invoke_host_function"; + OperationResponseType["bumpFootprintExpiration"] = "bump_footprint_expiration"; + OperationResponseType["restoreFootprint"] = "restore_footprint"; + return OperationResponseType; + }({}); + _HorizonApi.OperationResponseType = OperationResponseType; + var OperationResponseTypeI = function (OperationResponseTypeI) { + OperationResponseTypeI[OperationResponseTypeI["createAccount"] = 0] = "createAccount"; + OperationResponseTypeI[OperationResponseTypeI["payment"] = 1] = "payment"; + OperationResponseTypeI[OperationResponseTypeI["pathPayment"] = 2] = "pathPayment"; + OperationResponseTypeI[OperationResponseTypeI["createPassiveOffer"] = 3] = "createPassiveOffer"; + OperationResponseTypeI[OperationResponseTypeI["manageOffer"] = 4] = "manageOffer"; + OperationResponseTypeI[OperationResponseTypeI["setOptions"] = 5] = "setOptions"; + OperationResponseTypeI[OperationResponseTypeI["changeTrust"] = 6] = "changeTrust"; + OperationResponseTypeI[OperationResponseTypeI["allowTrust"] = 7] = "allowTrust"; + OperationResponseTypeI[OperationResponseTypeI["accountMerge"] = 8] = "accountMerge"; + OperationResponseTypeI[OperationResponseTypeI["inflation"] = 9] = "inflation"; + OperationResponseTypeI[OperationResponseTypeI["manageData"] = 10] = "manageData"; + OperationResponseTypeI[OperationResponseTypeI["bumpSequence"] = 11] = "bumpSequence"; + OperationResponseTypeI[OperationResponseTypeI["manageBuyOffer"] = 12] = "manageBuyOffer"; + OperationResponseTypeI[OperationResponseTypeI["pathPaymentStrictSend"] = 13] = "pathPaymentStrictSend"; + OperationResponseTypeI[OperationResponseTypeI["createClaimableBalance"] = 14] = "createClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["claimClaimableBalance"] = 15] = "claimClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["beginSponsoringFutureReserves"] = 16] = "beginSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["endSponsoringFutureReserves"] = 17] = "endSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["revokeSponsorship"] = 18] = "revokeSponsorship"; + OperationResponseTypeI[OperationResponseTypeI["clawback"] = 19] = "clawback"; + OperationResponseTypeI[OperationResponseTypeI["clawbackClaimableBalance"] = 20] = "clawbackClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["setTrustLineFlags"] = 21] = "setTrustLineFlags"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolDeposit"] = 22] = "liquidityPoolDeposit"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolWithdraw"] = 23] = "liquidityPoolWithdraw"; + OperationResponseTypeI[OperationResponseTypeI["invokeHostFunction"] = 24] = "invokeHostFunction"; + OperationResponseTypeI[OperationResponseTypeI["bumpFootprintExpiration"] = 25] = "bumpFootprintExpiration"; + OperationResponseTypeI[OperationResponseTypeI["restoreFootprint"] = 26] = "restoreFootprint"; + return OperationResponseTypeI; + }({}); + _HorizonApi.OperationResponseTypeI = OperationResponseTypeI; + ; + var TransactionFailedResultCodes = function (TransactionFailedResultCodes) { + TransactionFailedResultCodes["TX_FAILED"] = "tx_failed"; + TransactionFailedResultCodes["TX_BAD_SEQ"] = "tx_bad_seq"; + TransactionFailedResultCodes["TX_BAD_AUTH"] = "tx_bad_auth"; + TransactionFailedResultCodes["TX_BAD_AUTH_EXTRA"] = "tx_bad_auth_extra"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_SUCCESS"] = "tx_fee_bump_inner_success"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_FAILED"] = "tx_fee_bump_inner_failed"; + TransactionFailedResultCodes["TX_NOT_SUPPORTED"] = "tx_not_supported"; + TransactionFailedResultCodes["TX_SUCCESS"] = "tx_success"; + TransactionFailedResultCodes["TX_TOO_EARLY"] = "tx_too_early"; + TransactionFailedResultCodes["TX_TOO_LATE"] = "tx_too_late"; + TransactionFailedResultCodes["TX_MISSING_OPERATION"] = "tx_missing_operation"; + TransactionFailedResultCodes["TX_INSUFFICIENT_BALANCE"] = "tx_insufficient_balance"; + TransactionFailedResultCodes["TX_NO_SOURCE_ACCOUNT"] = "tx_no_source_account"; + TransactionFailedResultCodes["TX_INSUFFICIENT_FEE"] = "tx_insufficient_fee"; + TransactionFailedResultCodes["TX_INTERNAL_ERROR"] = "tx_internal_error"; + return TransactionFailedResultCodes; + }({}); + _HorizonApi.TransactionFailedResultCodes = TransactionFailedResultCodes; +})(HorizonApi || (exports.HorizonApi = HorizonApi = {})); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/horizon_axios_client.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/horizon_axios_client.d.ts new file mode 100644 index 000000000..a5934c906 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/horizon_axios_client.d.ts @@ -0,0 +1,37 @@ +export declare const version: string; +export interface ServerTime { + serverTime: number; + localTimeRecorded: number; +} +/** + * keep a local map of server times + * (export this purely for testing purposes) + * + * each entry will map the server domain to the last-known time and the local + * time it was recorded, ex: + * + * @example + * "horizon-testnet.stellar.org": { + * serverTime: 1552513039, + * localTimeRecorded: 1552513052 + * } + * + * @constant {Record.} + * @default {} + * @memberof module:Horizon + */ +export declare const SERVER_TIME_MAP: Record; +export declare const AxiosClient: import("../http-client").HttpClient; +export default AxiosClient; +/** + * Given a hostname, get the current time of that server (i.e., use the last- + * recorded server time and offset it by the time since then.) If there IS no + * recorded server time, or it's been 5 minutes since the last, return null. + * @memberof module:Horizon + * + * @param {string} hostname Hostname of a Horizon server. + * @returns {number} The UNIX timestamp (in seconds, not milliseconds) + * representing the current time on that server, or `null` if we don't have + * a record of that time. + */ +export declare function getCurrentServerTime(hostname: string): number | null; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/horizon_axios_client.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/horizon_axios_client.js new file mode 100644 index 000000000..d9c56d163 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/horizon_axios_client.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.SERVER_TIME_MAP = exports.AxiosClient = void 0; +exports.getCurrentServerTime = getCurrentServerTime; +exports.version = void 0; +var _urijs = _interopRequireDefault(require("urijs")); +var _httpClient = require("../http-client"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +var version = exports.version = "13.1.0"; +var SERVER_TIME_MAP = exports.SERVER_TIME_MAP = {}; +var AxiosClient = exports.AxiosClient = (0, _httpClient.create)({ + headers: { + "X-Client-Name": "js-stellar-sdk", + "X-Client-Version": version + } +}); +function toSeconds(ms) { + return Math.floor(ms / 1000); +} +AxiosClient.interceptors.response.use(function (response) { + var hostname = (0, _urijs.default)(response.config.url).hostname(); + var serverTime = 0; + if (response.headers instanceof Headers) { + var dateHeader = response.headers.get('date'); + if (dateHeader) { + serverTime = toSeconds(Date.parse(dateHeader)); + } + } else if (_typeof(response.headers) === 'object' && 'date' in response.headers) { + var headers = response.headers; + if (typeof headers.date === 'string') { + serverTime = toSeconds(Date.parse(headers.date)); + } + } + var localTimeRecorded = toSeconds(new Date().getTime()); + if (!Number.isNaN(serverTime)) { + SERVER_TIME_MAP[hostname] = { + serverTime: serverTime, + localTimeRecorded: localTimeRecorded + }; + } + return response; +}); +var _default = exports.default = AxiosClient; +function getCurrentServerTime(hostname) { + var entry = SERVER_TIME_MAP[hostname]; + if (!entry || !entry.localTimeRecorded || !entry.serverTime) { + return null; + } + var serverTime = entry.serverTime, + localTimeRecorded = entry.localTimeRecorded; + var currentTime = toSeconds(new Date().getTime()); + if (currentTime - localTimeRecorded > 60 * 5) { + return null; + } + return currentTime - localTimeRecorded + serverTime; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/index.d.ts new file mode 100644 index 000000000..9a351398f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/index.d.ts @@ -0,0 +1,8 @@ +/** @module Horizon */ +export * from "./horizon_api"; +export * from "./server_api"; +export * from "./account_response"; +export { HorizonServer as Server } from "./server"; +export { default as AxiosClient, SERVER_TIME_MAP, getCurrentServerTime } from "./horizon_axios_client"; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/index.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/index.js new file mode 100644 index 000000000..4ea741268 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/index.js @@ -0,0 +1,78 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Server: true, + AxiosClient: true, + SERVER_TIME_MAP: true, + getCurrentServerTime: true +}; +Object.defineProperty(exports, "AxiosClient", { + enumerable: true, + get: function get() { + return _horizon_axios_client.default; + } +}); +Object.defineProperty(exports, "SERVER_TIME_MAP", { + enumerable: true, + get: function get() { + return _horizon_axios_client.SERVER_TIME_MAP; + } +}); +Object.defineProperty(exports, "Server", { + enumerable: true, + get: function get() { + return _server.HorizonServer; + } +}); +exports.default = void 0; +Object.defineProperty(exports, "getCurrentServerTime", { + enumerable: true, + get: function get() { + return _horizon_axios_client.getCurrentServerTime; + } +}); +var _horizon_api = require("./horizon_api"); +Object.keys(_horizon_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _horizon_api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _horizon_api[key]; + } + }); +}); +var _server_api = require("./server_api"); +Object.keys(_server_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _server_api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _server_api[key]; + } + }); +}); +var _account_response = require("./account_response"); +Object.keys(_account_response).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _account_response[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _account_response[key]; + } + }); +}); +var _server = require("./server"); +var _horizon_axios_client = _interopRequireWildcard(require("./horizon_axios_client")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/ledger_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/ledger_call_builder.d.ts new file mode 100644 index 000000000..76c7f38ef --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/ledger_call_builder.d.ts @@ -0,0 +1,23 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link LedgerCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#ledgers}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-ledgers|All Ledgers} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class LedgerCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Provides information on a single ledger. + * @param {number|string} sequence Ledger sequence + * @returns {LedgerCallBuilder} current LedgerCallBuilder instance + */ + ledger(sequence: number | string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/ledger_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/ledger_call_builder.js new file mode 100644 index 000000000..93b2801b3 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/ledger_call_builder.js @@ -0,0 +1,37 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LedgerCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var LedgerCallBuilder = exports.LedgerCallBuilder = function (_CallBuilder) { + function LedgerCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, LedgerCallBuilder); + _this = _callSuper(this, LedgerCallBuilder, [serverUrl]); + _this.url.segment("ledgers"); + return _this; + } + _inherits(LedgerCallBuilder, _CallBuilder); + return _createClass(LedgerCallBuilder, [{ + key: "ledger", + value: function ledger(sequence) { + this.filter.push(["ledgers", sequence.toString()]); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/liquidity_pool_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/liquidity_pool_call_builder.d.ts new file mode 100644 index 000000000..806984c17 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/liquidity_pool_call_builder.d.ts @@ -0,0 +1,37 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link LiquidityPoolCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#liquidityPools}. + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class LiquidityPoolCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Filters out pools whose reserves don't exactly match these assets. + * + * @see Asset + * @returns {LiquidityPoolCallBuilder} current LiquidityPoolCallBuilder instance + */ + forAssets(...assets: Asset[]): this; + /** + * Retrieves all pools an account is participating in. + * + * @param {string} id the participant account to filter by + * @returns {LiquidityPoolCallBuilder} current LiquidityPoolCallBuilder instance + */ + forAccount(id: string): this; + /** + * Retrieves a specific liquidity pool by ID. + * + * @param {string} id the hash/ID of the liquidity pool + * @returns {CallBuilder} a new CallBuilder instance for the /liquidity_pools/:id endpoint + */ + liquidityPoolId(id: string): CallBuilder; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/liquidity_pool_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/liquidity_pool_call_builder.js new file mode 100644 index 000000000..7f0c6ff78 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/liquidity_pool_call_builder.js @@ -0,0 +1,59 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LiquidityPoolCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var LiquidityPoolCallBuilder = exports.LiquidityPoolCallBuilder = function (_CallBuilder) { + function LiquidityPoolCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, LiquidityPoolCallBuilder); + _this = _callSuper(this, LiquidityPoolCallBuilder, [serverUrl]); + _this.url.segment("liquidity_pools"); + return _this; + } + _inherits(LiquidityPoolCallBuilder, _CallBuilder); + return _createClass(LiquidityPoolCallBuilder, [{ + key: "forAssets", + value: function forAssets() { + for (var _len = arguments.length, assets = new Array(_len), _key = 0; _key < _len; _key++) { + assets[_key] = arguments[_key]; + } + var assetList = assets.map(function (asset) { + return asset.toString(); + }).join(","); + this.url.setQuery("reserves", assetList); + return this; + } + }, { + key: "forAccount", + value: function forAccount(id) { + this.url.setQuery("account", id); + return this; + } + }, { + key: "liquidityPoolId", + value: function liquidityPoolId(id) { + if (!id.match(/[a-fA-F0-9]{64}/)) { + throw new TypeError("".concat(id, " does not look like a liquidity pool ID")); + } + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([id.toLowerCase()]); + return builder; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/offer_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/offer_call_builder.d.ts new file mode 100644 index 000000000..2628c3960 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/offer_call_builder.d.ts @@ -0,0 +1,65 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link OfferCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#offers}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/|Offers} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class OfferCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The offer details endpoint provides information on a single offer. The offer ID provided in the id + * argument specifies which offer to load. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/single/|Offer Details} + * @param {string} offerId Offer ID + * @returns {CallBuilder} CallBuilder OperationCallBuilder instance + */ + offer(offerId: string): CallBuilder; + /** + * Returns all offers where the given account is involved. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/accounts/offers/|Offers} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + forAccount(id: string): this; + /** + * Returns all offers buying an asset. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/list/|Offers} + * @see Asset + * @param {Asset} asset For example: `new Asset('USD','GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD')` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + buying(asset: Asset): this; + /** + * Returns all offers selling an asset. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/list/|Offers} + * @see Asset + * @param {Asset} asset For example: `new Asset('EUR','GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD')` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + selling(asset: Asset): this; + /** + * This endpoint filters offers where the given account is sponsoring the offer entry. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-all-offers|Offers} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + sponsor(id: string): this; + /** + * This endpoint filters offers where the given account is the seller. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-all-offers|Offers} + * @param {string} seller For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + seller(seller: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/offer_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/offer_call_builder.js new file mode 100644 index 000000000..12c6a6277 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/offer_call_builder.js @@ -0,0 +1,79 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OfferCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var OfferCallBuilder = exports.OfferCallBuilder = function (_CallBuilder) { + function OfferCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, OfferCallBuilder); + _this = _callSuper(this, OfferCallBuilder, [serverUrl, "offers"]); + _this.url.segment("offers"); + return _this; + } + _inherits(OfferCallBuilder, _CallBuilder); + return _createClass(OfferCallBuilder, [{ + key: "offer", + value: function offer(offerId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([offerId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(id) { + return this.forEndpoint("accounts", id); + } + }, { + key: "buying", + value: function buying(asset) { + if (!asset.isNative()) { + this.url.setQuery("buying_asset_type", asset.getAssetType()); + this.url.setQuery("buying_asset_code", asset.getCode()); + this.url.setQuery("buying_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("buying_asset_type", "native"); + } + return this; + } + }, { + key: "selling", + value: function selling(asset) { + if (!asset.isNative()) { + this.url.setQuery("selling_asset_type", asset.getAssetType()); + this.url.setQuery("selling_asset_code", asset.getCode()); + this.url.setQuery("selling_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("selling_asset_type", "native"); + } + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "seller", + value: function seller(_seller) { + this.url.setQuery("seller", _seller); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/operation_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/operation_call_builder.d.ts new file mode 100644 index 000000000..ca7c9781c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/operation_call_builder.d.ts @@ -0,0 +1,69 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link OperationCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#operations}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/operations|All Operations} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class OperationCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The operation details endpoint provides information on a single operation. The operation ID provided in the id + * argument specifies which operation to load. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-an-operation|Operation Details} + * @param {number} operationId Operation ID + * @returns {CallBuilder} this OperationCallBuilder instance + */ + operation(operationId: string): CallBuilder; + /** + * This endpoint represents all operations that were included in valid transactions that affected a particular account. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-operations-by-account-id|Operations for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * This endpoint represents all operations that reference a given claimable_balance. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/cb-retrieve-related-operations|Operations for Claimable Balance} + * @param {string} claimableBalanceId Claimable Balance ID + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forClaimableBalance(claimableBalanceId: string): this; + /** + * This endpoint returns all operations that occurred in a given ledger. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-ledgers-operations|Operations for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all operations that are part of a given transaction. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-transactions-operations|Operations for Transaction} + * @param {string} transactionId Transaction ID + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forTransaction(transactionId: string): this; + /** + * This endpoint represents all operations involving a particular liquidity pool. + * + * @param {string} poolId liquidity pool ID + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forLiquidityPool(poolId: string): this; + /** + * Adds a parameter defining whether to include failed transactions. + * By default, only operations of successful transactions are returned. + * + * @param {boolean} value Set to `true` to include operations of failed transactions. + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + includeFailed(value: boolean): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/operation_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/operation_call_builder.js new file mode 100644 index 000000000..d24cd67d7 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/operation_call_builder.js @@ -0,0 +1,69 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OperationCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var OperationCallBuilder = exports.OperationCallBuilder = function (_CallBuilder) { + function OperationCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, OperationCallBuilder); + _this = _callSuper(this, OperationCallBuilder, [serverUrl, "operations"]); + _this.url.segment("operations"); + return _this; + } + _inherits(OperationCallBuilder, _CallBuilder); + return _createClass(OperationCallBuilder, [{ + key: "operation", + value: function operation(operationId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([operationId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/orderbook_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/orderbook_call_builder.d.ts new file mode 100644 index 000000000..484126432 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/orderbook_call_builder.d.ts @@ -0,0 +1,20 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link OrderbookCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#orderbook}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/order-books|Orderbook Details} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl serverUrl Horizon server URL. + * @param {Asset} selling Asset being sold + * @param {Asset} buying Asset being bought + */ +export declare class OrderbookCallBuilder extends CallBuilder { + constructor(serverUrl: URI, selling: Asset, buying: Asset); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/orderbook_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/orderbook_call_builder.js new file mode 100644 index 000000000..c4d3dd4c6 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/orderbook_call_builder.js @@ -0,0 +1,45 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OrderbookCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var OrderbookCallBuilder = exports.OrderbookCallBuilder = function (_CallBuilder) { + function OrderbookCallBuilder(serverUrl, selling, buying) { + var _this; + _classCallCheck(this, OrderbookCallBuilder); + _this = _callSuper(this, OrderbookCallBuilder, [serverUrl]); + _this.url.segment("order_book"); + if (!selling.isNative()) { + _this.url.setQuery("selling_asset_type", selling.getAssetType()); + _this.url.setQuery("selling_asset_code", selling.getCode()); + _this.url.setQuery("selling_asset_issuer", selling.getIssuer()); + } else { + _this.url.setQuery("selling_asset_type", "native"); + } + if (!buying.isNative()) { + _this.url.setQuery("buying_asset_type", buying.getAssetType()); + _this.url.setQuery("buying_asset_code", buying.getCode()); + _this.url.setQuery("buying_asset_issuer", buying.getIssuer()); + } else { + _this.url.setQuery("buying_asset_type", "native"); + } + return _this; + } + _inherits(OrderbookCallBuilder, _CallBuilder); + return _createClass(OrderbookCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/path_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/path_call_builder.d.ts new file mode 100644 index 000000000..56c89afa9 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/path_call_builder.d.ts @@ -0,0 +1,35 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * The Stellar Network allows payments to be made across assets through path payments. A path payment specifies a + * series of assets to route a payment through, from source asset (the asset debited from the payer) to destination + * asset (the asset credited to the payee). + * + * A path search is specified using: + * + * * The destination address + * * The source address + * * The asset and amount that the destination account should receive + * + * As part of the search, horizon will load a list of assets available to the source address and will find any + * payment paths from those source assets to the desired destination asset. The search's amount parameter will be + * used to determine if there a given path can satisfy a payment of the desired amount. + * + * Do not create this object directly, use {@link Horizon.Server#paths}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/paths|Find Payment Paths} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + * @param {string} source The sender's account ID. Any returned path must use a source that the sender can hold. + * @param {string} destination The destination account ID that any returned path should use. + * @param {Asset} destinationAsset The destination asset. + * @param {string} destinationAmount The amount, denominated in the destination asset, that any returned path should be able to satisfy. + */ +export declare class PathCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, source: string, destination: string, destinationAsset: Asset, destinationAmount: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/path_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/path_call_builder.js new file mode 100644 index 000000000..53f5cebbe --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/path_call_builder.js @@ -0,0 +1,41 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PathCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var PathCallBuilder = exports.PathCallBuilder = function (_CallBuilder) { + function PathCallBuilder(serverUrl, source, destination, destinationAsset, destinationAmount) { + var _this; + _classCallCheck(this, PathCallBuilder); + _this = _callSuper(this, PathCallBuilder, [serverUrl]); + _this.url.segment("paths"); + _this.url.setQuery("destination_account", destination); + _this.url.setQuery("source_account", source); + _this.url.setQuery("destination_amount", destinationAmount); + if (!destinationAsset.isNative()) { + _this.url.setQuery("destination_asset_type", destinationAsset.getAssetType()); + _this.url.setQuery("destination_asset_code", destinationAsset.getCode()); + _this.url.setQuery("destination_asset_issuer", destinationAsset.getIssuer()); + } else { + _this.url.setQuery("destination_asset_type", "native"); + } + return _this; + } + _inherits(PathCallBuilder, _CallBuilder); + return _createClass(PathCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/payment_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/payment_call_builder.d.ts new file mode 100644 index 000000000..bcee63c88 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/payment_call_builder.d.ts @@ -0,0 +1,39 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link PaymentCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#payments}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/horizon/resources/list-all-payments/|All Payments} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + */ +export declare class PaymentCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * This endpoint responds with a collection of Payment operations where the given account was either the sender or receiver. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/horizon/resources/get-payments-by-account-id|Payments for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {PaymentCallBuilder} this PaymentCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * This endpoint represents all payment operations that are part of a valid transactions in a given ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/horizon/resources/retrieve-a-ledgers-payments|Payments for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {PaymentCallBuilder} this PaymentCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all payment operations that are part of a given transaction. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/transactions/payments/|Payments for Transaction} + * @param {string} transactionId Transaction ID + * @returns {PaymentCallBuilder} this PaymentCallBuilder instance + */ + forTransaction(transactionId: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/payment_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/payment_call_builder.js new file mode 100644 index 000000000..e3a9c26bf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/payment_call_builder.js @@ -0,0 +1,46 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PaymentCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var PaymentCallBuilder = exports.PaymentCallBuilder = function (_CallBuilder) { + function PaymentCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, PaymentCallBuilder); + _this = _callSuper(this, PaymentCallBuilder, [serverUrl, "payments"]); + _this.url.segment("payments"); + return _this; + } + _inherits(PaymentCallBuilder, _CallBuilder); + return _createClass(PaymentCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/server.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/server.d.ts new file mode 100644 index 000000000..ef83c857a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/server.d.ts @@ -0,0 +1,394 @@ +import { Asset, FeeBumpTransaction, Transaction } from "@stellar/stellar-base"; +import URI from "urijs"; +import { AccountCallBuilder } from "./account_call_builder"; +import { AccountResponse } from "./account_response"; +import { AssetsCallBuilder } from "./assets_call_builder"; +import { ClaimableBalanceCallBuilder } from "./claimable_balances_call_builder"; +import { EffectCallBuilder } from "./effect_call_builder"; +import { FriendbotBuilder } from "./friendbot_builder"; +import { HorizonApi } from "./horizon_api"; +import { LedgerCallBuilder } from "./ledger_call_builder"; +import { LiquidityPoolCallBuilder } from "./liquidity_pool_call_builder"; +import { OfferCallBuilder } from "./offer_call_builder"; +import { OperationCallBuilder } from "./operation_call_builder"; +import { OrderbookCallBuilder } from "./orderbook_call_builder"; +import { PathCallBuilder } from "./path_call_builder"; +import { PaymentCallBuilder } from "./payment_call_builder"; +import { TradeAggregationCallBuilder } from "./trade_aggregation_call_builder"; +import { TradesCallBuilder } from "./trades_call_builder"; +import { TransactionCallBuilder } from "./transaction_call_builder"; +/** + * Default transaction submission timeout for Horizon requests, in milliseconds + * @constant {number} + * @default 60000 + * @memberof module:Horizon.Server + */ +export declare const SUBMIT_TRANSACTION_TIMEOUT: number; +/** + * Server handles the network connection to a [Horizon](https://developers.stellar.org/docs/data/horizon) + * instance and exposes an interface for requests to that instance. + * @class + * @alias module:Horizon.Server + * @memberof module:Horizon + * + * @param {string} serverURL Horizon Server URL (ex. `https://horizon-testnet.stellar.org`). + * @param {module:Horizon.Server.Options} [opts] Options object + */ +export declare class HorizonServer { + /** + * Horizon Server URL (ex. `https://horizon-testnet.stellar.org`) + * + * @todo Solve `URI(this.serverURL as any)`. + */ + readonly serverURL: URI; + constructor(serverURL: string, opts?: HorizonServer.Options); + /** + * Get timebounds for N seconds from now, when you're creating a transaction + * with {@link TransactionBuilder}. + * + * By default, {@link TransactionBuilder} uses the current local time, but + * your machine's local time could be different from Horizon's. This gives you + * more assurance that your timebounds will reflect what you want. + * + * Note that this will generate your timebounds when you **init the transaction**, + * not when you build or submit the transaction! So give yourself enough time to get + * the transaction built and signed before submitting. + * + * @example + * const transaction = new StellarSdk.TransactionBuilder(accountId, { + * fee: await StellarSdk.Server.fetchBaseFee(), + * timebounds: await StellarSdk.Server.fetchTimebounds(100) + * }) + * .addOperation(operation) + * // normally we would need to call setTimeout here, but setting timebounds + * // earlier does the trick! + * .build(); + * + * @param {number} seconds Number of seconds past the current time to wait. + * @param {boolean} [_isRetry] True if this is a retry. Only set this internally! + * This is to avoid a scenario where Horizon is horking up the wrong date. + * @returns {Promise} Promise that resolves a `timebounds` object + * (with the shape `{ minTime: 0, maxTime: N }`) that you can set the `timebounds` option to. + */ + fetchTimebounds(seconds: number, _isRetry?: boolean): Promise; + /** + * Fetch the base fee. Since this hits the server, if the server call fails, + * you might get an error. You should be prepared to use a default value if + * that happens! + * @returns {Promise} Promise that resolves to the base fee. + */ + fetchBaseFee(): Promise; + /** + * Fetch the fee stats endpoint. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/fee-stats|Fee Stats} + * @returns {Promise} Promise that resolves to the fee stats returned by Horizon. + */ + feeStats(): Promise; + /** + * Fetch the Horizon server's root endpoint. + * @returns {Promise} Promise that resolves to the root endpoint returned by Horizon. + */ + root(): Promise; + /** + * Submits a transaction to the network. + * + * By default this function calls {@link Horizon.Server#checkMemoRequired}, you can + * skip this check by setting the option `skipMemoRequiredCheck` to `true`. + * + * If you submit any number of `manageOffer` operations, this will add an + * attribute to the response that will help you analyze what happened with + * your offers. + * + * For example, you'll want to examine `offerResults` to add affordances like + * these to your app: + * - If `wasImmediatelyFilled` is true, then no offer was created. So if you + * normally watch the `Server.offers` endpoint for offer updates, you + * instead need to check `Server.trades` to find the result of this filled + * offer. + * - If `wasImmediatelyDeleted` is true, then the offer you submitted was + * deleted without reaching the orderbook or being matched (possibly because + * your amounts were rounded down to zero). So treat the just-submitted + * offer request as if it never happened. + * - If `wasPartiallyFilled` is true, you can tell the user that + * `amountBought` or `amountSold` have already been transferred. + * + * @example + * const res = { + * ...response, + * offerResults: [ + * { + * // Exact ordered list of offers that executed, with the exception + * // that the last one may not have executed entirely. + * offersClaimed: [ + * sellerId: String, + * offerId: String, + * assetSold: { + * type: 'native|credit_alphanum4|credit_alphanum12', + * + * // these are only present if the asset is not native + * assetCode: String, + * issuer: String, + * }, + * + * // same shape as assetSold + * assetBought: {} + * ], + * + * // What effect your manageOffer op had + * effect: "manageOfferCreated|manageOfferUpdated|manageOfferDeleted", + * + * // Whether your offer immediately got matched and filled + * wasImmediatelyFilled: Boolean, + * + * // Whether your offer immediately got deleted, if for example the order was too small + * wasImmediatelyDeleted: Boolean, + * + * // Whether the offer was partially, but not completely, filled + * wasPartiallyFilled: Boolean, + * + * // The full requested amount of the offer is open for matching + * isFullyOpen: Boolean, + * + * // The total amount of tokens bought / sold during transaction execution + * amountBought: Number, + * amountSold: Number, + * + * // if the offer was created, updated, or partially filled, this is + * // the outstanding offer + * currentOffer: { + * offerId: String, + * amount: String, + * price: { + * n: String, + * d: String, + * }, + * + * selling: { + * type: 'native|credit_alphanum4|credit_alphanum12', + * + * // these are only present if the asset is not native + * assetCode: String, + * issuer: String, + * }, + * + * // same as `selling` + * buying: {}, + * }, + * + * // the index of this particular operation in the op stack + * operationIndex: Number + * } + * ] + * } + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/submit-a-transaction|Submit a Transaction} + * @param {Transaction|FeeBumpTransaction} transaction - The transaction to submit. + * @param {object} [opts] Options object + * @param {boolean} [opts.skipMemoRequiredCheck] - Allow skipping memo + * required check, default: `false`. See + * [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md). + * @returns {Promise} Promise that resolves or rejects with response from + * horizon. + */ + submitTransaction(transaction: Transaction | FeeBumpTransaction, opts?: HorizonServer.SubmitTransactionOptions): Promise; + /** + * Submits an asynchronous transaction to the network. Unlike the synchronous version, which blocks + * and waits for the transaction to be ingested in Horizon, this endpoint relays the response from + * core directly back to the user. + * + * By default, this function calls {@link HorizonServer#checkMemoRequired}, you can + * skip this check by setting the option `skipMemoRequiredCheck` to `true`. + * + * @see [Submit-Async-Transaction](https://developers.stellar.org/docs/data/horizon/api-reference/resources/submit-async-transaction) + * @param {Transaction|FeeBumpTransaction} transaction - The transaction to submit. + * @param {object} [opts] Options object + * @param {boolean} [opts.skipMemoRequiredCheck] - Allow skipping memo + * required check, default: `false`. See + * [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md). + * @returns {Promise} Promise that resolves or rejects with response from + * horizon. + */ + submitAsyncTransaction(transaction: Transaction | FeeBumpTransaction, opts?: HorizonServer.SubmitTransactionOptions): Promise; + /** + * @returns {AccountCallBuilder} New {@link AccountCallBuilder} object configured by a current Horizon server configuration. + */ + accounts(): AccountCallBuilder; + /** + * @returns {ClaimableBalanceCallBuilder} New {@link ClaimableBalanceCallBuilder} object configured by a current Horizon server configuration. + */ + claimableBalances(): ClaimableBalanceCallBuilder; + /** + * @returns {LedgerCallBuilder} New {@link LedgerCallBuilder} object configured by a current Horizon server configuration. + */ + ledgers(): LedgerCallBuilder; + /** + * @returns {TransactionCallBuilder} New {@link TransactionCallBuilder} object configured by a current Horizon server configuration. + */ + transactions(): TransactionCallBuilder; + /** + * People on the Stellar network can make offers to buy or sell assets. This endpoint represents all the offers on the DEX. + * + * You can query all offers for account using the function `.accountId`. + * + * @example + * server.offers() + * .forAccount(accountId).call() + * .then(function(offers) { + * console.log(offers); + * }); + * + * @returns {OfferCallBuilder} New {@link OfferCallBuilder} object + */ + offers(): OfferCallBuilder; + /** + * @param {Asset} selling Asset being sold + * @param {Asset} buying Asset being bought + * @returns {OrderbookCallBuilder} New {@link OrderbookCallBuilder} object configured by a current Horizon server configuration. + */ + orderbook(selling: Asset, buying: Asset): OrderbookCallBuilder; + /** + * Returns + * @returns {TradesCallBuilder} New {@link TradesCallBuilder} object configured by a current Horizon server configuration. + */ + trades(): TradesCallBuilder; + /** + * @returns {OperationCallBuilder} New {@link OperationCallBuilder} object configured by a current Horizon server configuration. + */ + operations(): OperationCallBuilder; + /** + * @returns {LiquidityPoolCallBuilder} New {@link LiquidityPoolCallBuilder} + * object configured to the current Horizon server settings. + */ + liquidityPools(): LiquidityPoolCallBuilder; + /** + * The Stellar Network allows payments to be made between assets through path + * payments. A strict receive path payment specifies a series of assets to + * route a payment through, from source asset (the asset debited from the + * payer) to destination asset (the asset credited to the payee). + * + * A strict receive path search is specified using: + * + * * The destination address. + * * The source address or source assets. + * * The asset and amount that the destination account should receive. + * + * As part of the search, horizon will load a list of assets available to the + * source address and will find any payment paths from those source assets to + * the desired destination asset. The search's amount parameter will be used + * to determine if there a given path can satisfy a payment of the desired + * amount. + * + * If a list of assets is passed as the source, horizon will find any payment + * paths from those source assets to the desired destination asset. + * + * @param {string|Asset[]} source The sender's account ID or a list of assets. Any returned path will use a source that the sender can hold. + * @param {Asset} destinationAsset The destination asset. + * @param {string} destinationAmount The amount, denominated in the destination asset, that any returned path should be able to satisfy. + * @returns {StrictReceivePathCallBuilder} New {@link StrictReceivePathCallBuilder} object configured with the current Horizon server configuration. + */ + strictReceivePaths(source: string | Asset[], destinationAsset: Asset, destinationAmount: string): PathCallBuilder; + /** + * The Stellar Network allows payments to be made between assets through path payments. A strict send path payment specifies a + * series of assets to route a payment through, from source asset (the asset debited from the payer) to destination + * asset (the asset credited to the payee). + * + * A strict send path search is specified using: + * + * The asset and amount that is being sent. + * The destination account or the destination assets. + * + * @param {Asset} sourceAsset The asset to be sent. + * @param {string} sourceAmount The amount, denominated in the source asset, that any returned path should be able to satisfy. + * @param {string|Asset[]} destination The destination account or the destination assets. + * @returns {StrictSendPathCallBuilder} New {@link StrictSendPathCallBuilder} object configured with the current Horizon server configuration. + */ + strictSendPaths(sourceAsset: Asset, sourceAmount: string, destination: string | Asset[]): PathCallBuilder; + /** + * @returns {PaymentCallBuilder} New {@link PaymentCallBuilder} instance configured with the current + * Horizon server configuration. + */ + payments(): PaymentCallBuilder; + /** + * @returns {EffectCallBuilder} New {@link EffectCallBuilder} instance configured with the current + * Horizon server configuration + */ + effects(): EffectCallBuilder; + /** + * @param {string} address The Stellar ID that you want Friendbot to send lumens to + * @returns {FriendbotBuilder} New {@link FriendbotBuilder} instance configured with the current + * Horizon server configuration + * @private + */ + friendbot(address: string): FriendbotBuilder; + /** + * Get a new {@link AssetsCallBuilder} instance configured with the current + * Horizon server configuration. + * @returns {AssetsCallBuilder} New AssetsCallBuilder instance + */ + assets(): AssetsCallBuilder; + /** + * Fetches an account's most current state in the ledger, then creates and + * returns an {@link AccountResponse} object. + * + * @param {string} accountId - The account to load. + * + * @returns {Promise} Returns a promise to the {@link AccountResponse} object + * with populated sequence number. + */ + loadAccount(accountId: string): Promise; + /** + * + * @param {Asset} base base asset + * @param {Asset} counter counter asset + * @param {number} start_time lower time boundary represented as millis since epoch + * @param {number} end_time upper time boundary represented as millis since epoch + * @param {number} resolution segment duration as millis since epoch. *Supported values are 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). + * @param {number} offset segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. + * Returns new {@link TradeAggregationCallBuilder} object configured with the current Horizon server configuration. + * @returns {TradeAggregationCallBuilder} New TradeAggregationCallBuilder instance + */ + tradeAggregation(base: Asset, counter: Asset, start_time: number, end_time: number, resolution: number, offset: number): TradeAggregationCallBuilder; + /** + * Check if any of the destination accounts requires a memo. + * + * This function implements a memo required check as defined in + * [SEP-29](https://stellar.org/protocol/sep-29). It will load each account + * which is the destination and check if it has the data field + * `config.memo_required` set to `"MQ=="`. + * + * Each account is checked sequentially instead of loading multiple accounts + * at the same time from Horizon. + * + * @see {@link https://stellar.org/protocol/sep-29|SEP-29: Account Memo Requirements} + * @param {Transaction} transaction - The transaction to check. + * @returns {Promise} - If any of the destination account + * requires a memo, the promise will throw {@link AccountRequiresMemoError}. + * @throws {AccountRequiresMemoError} + */ + checkMemoRequired(transaction: Transaction | FeeBumpTransaction): Promise; +} +/** + * Options for configuring connections to Horizon servers. + * @typedef {object} Options + * @memberof module:Horizon.Server + * @property {boolean} [allowHttp] Allow connecting to http servers, default: `false`. This must be set to false in production deployments! You can also use {@link Config} class to set this globally. + * @property {string} [appName] Allow set custom header `X-App-Name`, default: `undefined`. + * @property {string} [appVersion] Allow set custom header `X-App-Version`, default: `undefined`. + * @property {string} [authToken] Allow set custom header `X-Auth-Token`, default: `undefined`. + */ +export declare namespace HorizonServer { + interface Options { + allowHttp?: boolean; + appName?: string; + appVersion?: string; + authToken?: string; + headers?: Record; + } + interface Timebounds { + minTime: number; + maxTime: number; + } + interface SubmitTransactionOptions { + skipMemoRequiredCheck?: boolean; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/server.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/server.js new file mode 100644 index 000000000..111c8b341 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/server.js @@ -0,0 +1,571 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SUBMIT_TRANSACTION_TIMEOUT = exports.HorizonServer = void 0; +var _bignumber = _interopRequireDefault(require("bignumber.js")); +var _stellarBase = require("@stellar/stellar-base"); +var _urijs = _interopRequireDefault(require("urijs")); +var _call_builder = require("./call_builder"); +var _config = require("../config"); +var _errors = require("../errors"); +var _account_call_builder = require("./account_call_builder"); +var _account_response = require("./account_response"); +var _assets_call_builder = require("./assets_call_builder"); +var _claimable_balances_call_builder = require("./claimable_balances_call_builder"); +var _effect_call_builder = require("./effect_call_builder"); +var _friendbot_builder = require("./friendbot_builder"); +var _ledger_call_builder = require("./ledger_call_builder"); +var _liquidity_pool_call_builder = require("./liquidity_pool_call_builder"); +var _offer_call_builder = require("./offer_call_builder"); +var _operation_call_builder = require("./operation_call_builder"); +var _orderbook_call_builder = require("./orderbook_call_builder"); +var _payment_call_builder = require("./payment_call_builder"); +var _strict_receive_path_call_builder = require("./strict_receive_path_call_builder"); +var _strict_send_path_call_builder = require("./strict_send_path_call_builder"); +var _trade_aggregation_call_builder = require("./trade_aggregation_call_builder"); +var _trades_call_builder = require("./trades_call_builder"); +var _transaction_call_builder = require("./transaction_call_builder"); +var _horizon_axios_client = _interopRequireWildcard(require("./horizon_axios_client")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var SUBMIT_TRANSACTION_TIMEOUT = exports.SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000; +var STROOPS_IN_LUMEN = 10000000; +var ACCOUNT_REQUIRES_MEMO = "MQ=="; +function getAmountInLumens(amt) { + return new _bignumber.default(amt).div(STROOPS_IN_LUMEN).toString(); +} +var HorizonServer = exports.HorizonServer = function () { + function HorizonServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, HorizonServer); + this.serverURL = (0, _urijs.default)(serverURL); + var allowHttp = typeof opts.allowHttp === "undefined" ? _config.Config.isAllowHttp() : opts.allowHttp; + var customHeaders = {}; + if (opts.appName) { + customHeaders["X-App-Name"] = opts.appName; + } + if (opts.appVersion) { + customHeaders["X-App-Version"] = opts.appVersion; + } + if (opts.authToken) { + customHeaders["X-Auth-Token"] = opts.authToken; + } + if (opts.headers) { + Object.assign(customHeaders, opts.headers); + } + if (Object.keys(customHeaders).length > 0) { + _horizon_axios_client.default.interceptors.request.use(function (config) { + config.headers = config.headers || {}; + config.headers = Object.assign(config.headers, customHeaders); + return config; + }); + } + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure horizon server"); + } + } + return _createClass(HorizonServer, [{ + key: "fetchTimebounds", + value: (function () { + var _fetchTimebounds = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(seconds) { + var _isRetry, + currentTime, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _isRetry = _args.length > 1 && _args[1] !== undefined ? _args[1] : false; + currentTime = (0, _horizon_axios_client.getCurrentServerTime)(this.serverURL.hostname()); + if (!currentTime) { + _context.next = 4; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: currentTime + seconds + }); + case 4: + if (!_isRetry) { + _context.next = 6; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: Math.floor(new Date().getTime() / 1000) + seconds + }); + case 6: + _context.next = 8; + return _horizon_axios_client.default.get((0, _urijs.default)(this.serverURL).toString()); + case 8: + return _context.abrupt("return", this.fetchTimebounds(seconds, true)); + case 9: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function fetchTimebounds(_x) { + return _fetchTimebounds.apply(this, arguments); + } + return fetchTimebounds; + }()) + }, { + key: "fetchBaseFee", + value: (function () { + var _fetchBaseFee = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + var response; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.feeStats(); + case 2: + response = _context2.sent; + return _context2.abrupt("return", parseInt(response.last_ledger_base_fee, 10) || 100); + case 4: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function fetchBaseFee() { + return _fetchBaseFee.apply(this, arguments); + } + return fetchBaseFee; + }()) + }, { + key: "feeStats", + value: (function () { + var _feeStats = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3() { + var cb; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + cb = new _call_builder.CallBuilder((0, _urijs.default)(this.serverURL)); + cb.filter.push(["fee_stats"]); + return _context3.abrupt("return", cb.call()); + case 3: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function feeStats() { + return _feeStats.apply(this, arguments); + } + return feeStats; + }()) + }, { + key: "root", + value: (function () { + var _root = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + var cb; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + cb = new _call_builder.CallBuilder((0, _urijs.default)(this.serverURL)); + return _context4.abrupt("return", cb.call()); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function root() { + return _root.apply(this, arguments); + } + return root; + }()) + }, { + key: "submitTransaction", + value: (function () { + var _submitTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(transaction) { + var opts, + tx, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context5.next = 4; + break; + } + _context5.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context5.abrupt("return", _horizon_axios_client.default.post((0, _urijs.default)(this.serverURL).segment("transactions").toString(), "tx=".concat(tx), { + timeout: SUBMIT_TRANSACTION_TIMEOUT + }).then(function (response) { + if (!response.data.result_xdr) { + return response.data; + } + var responseXDR = _stellarBase.xdr.TransactionResult.fromXDR(response.data.result_xdr, "base64"); + var results = responseXDR.result().value(); + var offerResults; + var hasManageOffer; + if (results.length) { + offerResults = results.map(function (result, i) { + if (result.value().switch().name !== "manageBuyOffer" && result.value().switch().name !== "manageSellOffer") { + return null; + } + hasManageOffer = true; + var amountBought = new _bignumber.default(0); + var amountSold = new _bignumber.default(0); + var offerSuccess = result.value().value().success(); + var offersClaimed = offerSuccess.offersClaimed().map(function (offerClaimedAtom) { + var offerClaimed = offerClaimedAtom.value(); + var sellerId = ""; + switch (offerClaimedAtom.switch()) { + case _stellarBase.xdr.ClaimAtomType.claimAtomTypeV0(): + sellerId = _stellarBase.StrKey.encodeEd25519PublicKey(offerClaimed.sellerEd25519()); + break; + case _stellarBase.xdr.ClaimAtomType.claimAtomTypeOrderBook(): + sellerId = _stellarBase.StrKey.encodeEd25519PublicKey(offerClaimed.sellerId().ed25519()); + break; + default: + throw new Error("Invalid offer result type: ".concat(offerClaimedAtom.switch())); + } + var claimedOfferAmountBought = new _bignumber.default(offerClaimed.amountBought().toString()); + var claimedOfferAmountSold = new _bignumber.default(offerClaimed.amountSold().toString()); + amountBought = amountBought.plus(claimedOfferAmountSold); + amountSold = amountSold.plus(claimedOfferAmountBought); + var sold = _stellarBase.Asset.fromOperation(offerClaimed.assetSold()); + var bought = _stellarBase.Asset.fromOperation(offerClaimed.assetBought()); + var assetSold = { + type: sold.getAssetType(), + assetCode: sold.getCode(), + issuer: sold.getIssuer() + }; + var assetBought = { + type: bought.getAssetType(), + assetCode: bought.getCode(), + issuer: bought.getIssuer() + }; + return { + sellerId: sellerId, + offerId: offerClaimed.offerId().toString(), + assetSold: assetSold, + amountSold: getAmountInLumens(claimedOfferAmountSold), + assetBought: assetBought, + amountBought: getAmountInLumens(claimedOfferAmountBought) + }; + }); + var effect = offerSuccess.offer().switch().name; + var currentOffer; + if (typeof offerSuccess.offer().value === "function" && offerSuccess.offer().value()) { + var offerXDR = offerSuccess.offer().value(); + currentOffer = { + offerId: offerXDR.offerId().toString(), + selling: {}, + buying: {}, + amount: getAmountInLumens(offerXDR.amount().toString()), + price: { + n: offerXDR.price().n(), + d: offerXDR.price().d() + } + }; + var selling = _stellarBase.Asset.fromOperation(offerXDR.selling()); + currentOffer.selling = { + type: selling.getAssetType(), + assetCode: selling.getCode(), + issuer: selling.getIssuer() + }; + var buying = _stellarBase.Asset.fromOperation(offerXDR.buying()); + currentOffer.buying = { + type: buying.getAssetType(), + assetCode: buying.getCode(), + issuer: buying.getIssuer() + }; + } + return { + offersClaimed: offersClaimed, + effect: effect, + operationIndex: i, + currentOffer: currentOffer, + amountBought: getAmountInLumens(amountBought), + amountSold: getAmountInLumens(amountSold), + isFullyOpen: !offersClaimed.length && effect !== "manageOfferDeleted", + wasPartiallyFilled: !!offersClaimed.length && effect !== "manageOfferDeleted", + wasImmediatelyFilled: !!offersClaimed.length && effect === "manageOfferDeleted", + wasImmediatelyDeleted: !offersClaimed.length && effect === "manageOfferDeleted" + }; + }).filter(function (result) { + return !!result; + }); + } + return _objectSpread(_objectSpread({}, response.data), {}, { + offerResults: hasManageOffer ? offerResults : undefined + }); + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new _errors.BadResponseError("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function submitTransaction(_x2) { + return _submitTransaction.apply(this, arguments); + } + return submitTransaction; + }()) + }, { + key: "submitAsyncTransaction", + value: (function () { + var _submitAsyncTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(transaction) { + var opts, + tx, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context6.next = 4; + break; + } + _context6.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context6.abrupt("return", _horizon_axios_client.default.post((0, _urijs.default)(this.serverURL).segment("transactions_async").toString(), "tx=".concat(tx)).then(function (response) { + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new _errors.BadResponseError("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function submitAsyncTransaction(_x3) { + return _submitAsyncTransaction.apply(this, arguments); + } + return submitAsyncTransaction; + }()) + }, { + key: "accounts", + value: function accounts() { + return new _account_call_builder.AccountCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "claimableBalances", + value: function claimableBalances() { + return new _claimable_balances_call_builder.ClaimableBalanceCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "ledgers", + value: function ledgers() { + return new _ledger_call_builder.LedgerCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "transactions", + value: function transactions() { + return new _transaction_call_builder.TransactionCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "offers", + value: function offers() { + return new _offer_call_builder.OfferCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "orderbook", + value: function orderbook(selling, buying) { + return new _orderbook_call_builder.OrderbookCallBuilder((0, _urijs.default)(this.serverURL), selling, buying); + } + }, { + key: "trades", + value: function trades() { + return new _trades_call_builder.TradesCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "operations", + value: function operations() { + return new _operation_call_builder.OperationCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "liquidityPools", + value: function liquidityPools() { + return new _liquidity_pool_call_builder.LiquidityPoolCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "strictReceivePaths", + value: function strictReceivePaths(source, destinationAsset, destinationAmount) { + return new _strict_receive_path_call_builder.StrictReceivePathCallBuilder((0, _urijs.default)(this.serverURL), source, destinationAsset, destinationAmount); + } + }, { + key: "strictSendPaths", + value: function strictSendPaths(sourceAsset, sourceAmount, destination) { + return new _strict_send_path_call_builder.StrictSendPathCallBuilder((0, _urijs.default)(this.serverURL), sourceAsset, sourceAmount, destination); + } + }, { + key: "payments", + value: function payments() { + return new _payment_call_builder.PaymentCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "effects", + value: function effects() { + return new _effect_call_builder.EffectCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "friendbot", + value: function friendbot(address) { + return new _friendbot_builder.FriendbotBuilder((0, _urijs.default)(this.serverURL), address); + } + }, { + key: "assets", + value: function assets() { + return new _assets_call_builder.AssetsCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "loadAccount", + value: (function () { + var _loadAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee7(accountId) { + var res; + return _regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.accounts().accountId(accountId).call(); + case 2: + res = _context7.sent; + return _context7.abrupt("return", new _account_response.AccountResponse(res)); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function loadAccount(_x4) { + return _loadAccount.apply(this, arguments); + } + return loadAccount; + }()) + }, { + key: "tradeAggregation", + value: function tradeAggregation(base, counter, start_time, end_time, resolution, offset) { + return new _trade_aggregation_call_builder.TradeAggregationCallBuilder((0, _urijs.default)(this.serverURL), base, counter, start_time, end_time, resolution, offset); + } + }, { + key: "checkMemoRequired", + value: (function () { + var _checkMemoRequired = _asyncToGenerator(_regeneratorRuntime().mark(function _callee8(transaction) { + var destinations, i, operation, destination, account; + return _regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (transaction instanceof _stellarBase.FeeBumpTransaction) { + transaction = transaction.innerTransaction; + } + if (!(transaction.memo.type !== "none")) { + _context8.next = 3; + break; + } + return _context8.abrupt("return"); + case 3: + destinations = new Set(); + i = 0; + case 5: + if (!(i < transaction.operations.length)) { + _context8.next = 36; + break; + } + operation = transaction.operations[i]; + _context8.t0 = operation.type; + _context8.next = _context8.t0 === "payment" ? 10 : _context8.t0 === "pathPaymentStrictReceive" ? 10 : _context8.t0 === "pathPaymentStrictSend" ? 10 : _context8.t0 === "accountMerge" ? 10 : 11; + break; + case 10: + return _context8.abrupt("break", 12); + case 11: + return _context8.abrupt("continue", 33); + case 12: + destination = operation.destination; + if (!destinations.has(destination)) { + _context8.next = 15; + break; + } + return _context8.abrupt("continue", 33); + case 15: + destinations.add(destination); + if (!destination.startsWith("M")) { + _context8.next = 18; + break; + } + return _context8.abrupt("continue", 33); + case 18: + _context8.prev = 18; + _context8.next = 21; + return this.loadAccount(destination); + case 21: + account = _context8.sent; + if (!(account.data_attr["config.memo_required"] === ACCOUNT_REQUIRES_MEMO)) { + _context8.next = 24; + break; + } + throw new _errors.AccountRequiresMemoError("account requires memo", destination, i); + case 24: + _context8.next = 33; + break; + case 26: + _context8.prev = 26; + _context8.t1 = _context8["catch"](18); + if (!(_context8.t1 instanceof _errors.AccountRequiresMemoError)) { + _context8.next = 30; + break; + } + throw _context8.t1; + case 30: + if (_context8.t1 instanceof _errors.NotFoundError) { + _context8.next = 32; + break; + } + throw _context8.t1; + case 32: + return _context8.abrupt("continue", 33); + case 33: + i += 1; + _context8.next = 5; + break; + case 36: + case "end": + return _context8.stop(); + } + }, _callee8, this, [[18, 26]]); + })); + function checkMemoRequired(_x5) { + return _checkMemoRequired.apply(this, arguments); + } + return checkMemoRequired; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/server_api.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/server_api.d.ts new file mode 100644 index 000000000..77a8367ba --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/server_api.d.ts @@ -0,0 +1,264 @@ +import { Asset } from "@stellar/stellar-base"; +import { HorizonApi } from "./horizon_api"; +import { AccountRecordSigners as AccountRecordSignersType } from "./types/account"; +import { AssetRecord as AssetRecordType } from "./types/assets"; +import * as Effects from "./types/effects"; +import { OfferRecord as OfferRecordType } from "./types/offer"; +import { Trade } from "./types/trade"; +export declare namespace ServerApi { + export type OfferRecord = OfferRecordType; + export type AccountRecordSigners = AccountRecordSignersType; + export type AssetRecord = AssetRecordType; + export interface CollectionPage { + records: T[]; + next: () => Promise>; + prev: () => Promise>; + } + export interface CallFunctionTemplateOptions { + cursor?: string | number; + limit?: number; + order?: "asc" | "desc"; + } + export type CallFunction = () => Promise; + export type CallCollectionFunction = (options?: CallFunctionTemplateOptions) => Promise>; + type BaseEffectRecordFromTypes = Effects.AccountCreated | Effects.AccountCredited | Effects.AccountDebited | Effects.AccountThresholdsUpdated | Effects.AccountHomeDomainUpdated | Effects.AccountFlagsUpdated | Effects.DataCreated | Effects.DataRemoved | Effects.DataUpdated | Effects.SequenceBumped | Effects.SignerCreated | Effects.SignerRemoved | Effects.SignerUpdated | Effects.TrustlineCreated | Effects.TrustlineRemoved | Effects.TrustlineUpdated | Effects.TrustlineAuthorized | Effects.TrustlineDeauthorized | Effects.TrustlineAuthorizedToMaintainLiabilities | Effects.ClaimableBalanceCreated | Effects.ClaimableBalanceClaimed | Effects.ClaimableBalanceClaimantCreated | Effects.AccountSponsorshipCreated | Effects.AccountSponsorshipRemoved | Effects.AccountSponsorshipUpdated | Effects.TrustlineSponsorshipCreated | Effects.TrustlineSponsorshipUpdated | Effects.TrustlineSponsorshipRemoved | Effects.DateSponsorshipCreated | Effects.DateSponsorshipUpdated | Effects.DateSponsorshipRemoved | Effects.ClaimableBalanceSponsorshipCreated | Effects.ClaimableBalanceSponsorshipRemoved | Effects.ClaimableBalanceSponsorshipUpdated | Effects.SignerSponsorshipCreated | Effects.SignerSponsorshipUpdated | Effects.SignerSponsorshipRemoved | Effects.LiquidityPoolDeposited | Effects.LiquidityPoolWithdrew | Effects.LiquidityPoolCreated | Effects.LiquidityPoolRemoved | Effects.LiquidityPoolRevoked | Effects.LiquidityPoolTrade | Effects.ContractCredited | Effects.ContractDebited | Trade; + export type EffectRecord = BaseEffectRecordFromTypes & EffectRecordMethods; + export const EffectType: typeof Effects.EffectType; + export interface ClaimableBalanceRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + asset: string; + amount: string; + sponsor?: string; + last_modified_ledger: number; + claimants: HorizonApi.Claimant[]; + } + export interface AccountRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + account_id: string; + sequence: string; + sequence_ledger?: number; + sequence_time?: string; + subentry_count: number; + home_domain?: string; + inflation_destination?: string; + last_modified_ledger: number; + last_modified_time: string; + thresholds: HorizonApi.AccountThresholds; + flags: HorizonApi.Flags; + balances: HorizonApi.BalanceLine[]; + signers: AccountRecordSigners[]; + data: (options: { + value: string; + }) => Promise<{ + value: string; + }>; + data_attr: { + [key: string]: string; + }; + sponsor?: string; + num_sponsoring: number; + num_sponsored: number; + effects: CallCollectionFunction; + offers: CallCollectionFunction; + operations: CallCollectionFunction; + payments: CallCollectionFunction; + trades: CallCollectionFunction; + } + export interface LiquidityPoolRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + fee_bp: number; + type: HorizonApi.LiquidityPoolType; + total_trustlines: string; + total_shares: string; + reserves: HorizonApi.Reserve[]; + } + export enum TradeType { + all = "all", + liquidityPools = "liquidity_pool", + orderbook = "orderbook" + } + interface EffectRecordMethods { + operation?: CallFunction; + precedes?: CallFunction; + succeeds?: CallFunction; + } + export interface LedgerRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + hash: string; + prev_hash: string; + sequence: number; + successful_transaction_count: number; + failed_transaction_count: number; + operation_count: number; + tx_set_operation_count: number | null; + closed_at: string; + total_coins: string; + fee_pool: string; + max_tx_set_size: number; + protocol_version: number; + header_xdr: string; + base_fee_in_stroops: number; + base_reserve_in_stroops: number; + effects: CallCollectionFunction; + operations: CallCollectionFunction; + self: CallFunction; + transactions: CallCollectionFunction; + } + import OperationResponseType = HorizonApi.OperationResponseType; + import OperationResponseTypeI = HorizonApi.OperationResponseTypeI; + export interface BaseOperationRecord extends HorizonApi.BaseOperationResponse { + self: CallFunction; + succeeds: CallFunction; + precedes: CallFunction; + effects: CallCollectionFunction; + transaction: CallFunction; + } + export interface CreateAccountOperationRecord extends BaseOperationRecord, HorizonApi.CreateAccountOperationResponse { + } + export interface PaymentOperationRecord extends BaseOperationRecord, HorizonApi.PaymentOperationResponse { + sender: CallFunction; + receiver: CallFunction; + } + export interface PathPaymentOperationRecord extends BaseOperationRecord, HorizonApi.PathPaymentOperationResponse { + } + export interface PathPaymentStrictSendOperationRecord extends BaseOperationRecord, HorizonApi.PathPaymentStrictSendOperationResponse { + } + export interface ManageOfferOperationRecord extends BaseOperationRecord, HorizonApi.ManageOfferOperationResponse { + } + export interface PassiveOfferOperationRecord extends BaseOperationRecord, HorizonApi.PassiveOfferOperationResponse { + } + export interface SetOptionsOperationRecord extends BaseOperationRecord, HorizonApi.SetOptionsOperationResponse { + } + export interface ChangeTrustOperationRecord extends BaseOperationRecord, HorizonApi.ChangeTrustOperationResponse { + } + export interface AllowTrustOperationRecord extends BaseOperationRecord, HorizonApi.AllowTrustOperationResponse { + } + export interface AccountMergeOperationRecord extends BaseOperationRecord, HorizonApi.AccountMergeOperationResponse { + } + export interface InflationOperationRecord extends BaseOperationRecord, HorizonApi.InflationOperationResponse { + } + export interface ManageDataOperationRecord extends BaseOperationRecord, HorizonApi.ManageDataOperationResponse { + } + export interface BumpSequenceOperationRecord extends BaseOperationRecord, HorizonApi.BumpSequenceOperationResponse { + } + export interface CreateClaimableBalanceOperationRecord extends BaseOperationRecord, HorizonApi.CreateClaimableBalanceOperationResponse { + } + export interface ClaimClaimableBalanceOperationRecord extends BaseOperationRecord, HorizonApi.ClaimClaimableBalanceOperationResponse { + } + export interface BeginSponsoringFutureReservesOperationRecord extends BaseOperationRecord, HorizonApi.BeginSponsoringFutureReservesOperationResponse { + } + export interface EndSponsoringFutureReservesOperationRecord extends BaseOperationRecord, HorizonApi.EndSponsoringFutureReservesOperationResponse { + } + export interface RevokeSponsorshipOperationRecord extends BaseOperationRecord, HorizonApi.RevokeSponsorshipOperationResponse { + } + export interface ClawbackOperationRecord extends BaseOperationRecord, HorizonApi.ClawbackOperationResponse { + } + export interface ClawbackClaimableBalanceOperationRecord extends BaseOperationRecord, HorizonApi.ClawbackClaimableBalanceOperationResponse { + } + export interface SetTrustLineFlagsOperationRecord extends BaseOperationRecord, HorizonApi.SetTrustLineFlagsOperationResponse { + } + export interface DepositLiquidityOperationRecord extends BaseOperationRecord, HorizonApi.DepositLiquidityOperationResponse { + } + export interface WithdrawLiquidityOperationRecord extends BaseOperationRecord, HorizonApi.WithdrawLiquidityOperationResponse { + } + export interface InvokeHostFunctionOperationRecord extends BaseOperationRecord, HorizonApi.InvokeHostFunctionOperationResponse { + } + export interface BumpFootprintExpirationOperationRecord extends BaseOperationRecord, HorizonApi.BumpFootprintExpirationOperationResponse { + } + export interface RestoreFootprintOperationRecord extends BaseOperationRecord, HorizonApi.RestoreFootprintOperationResponse { + } + export type OperationRecord = CreateAccountOperationRecord | PaymentOperationRecord | PathPaymentOperationRecord | ManageOfferOperationRecord | PassiveOfferOperationRecord | SetOptionsOperationRecord | ChangeTrustOperationRecord | AllowTrustOperationRecord | AccountMergeOperationRecord | InflationOperationRecord | ManageDataOperationRecord | BumpSequenceOperationRecord | PathPaymentStrictSendOperationRecord | CreateClaimableBalanceOperationRecord | ClaimClaimableBalanceOperationRecord | BeginSponsoringFutureReservesOperationRecord | EndSponsoringFutureReservesOperationRecord | RevokeSponsorshipOperationRecord | ClawbackClaimableBalanceOperationRecord | ClawbackOperationRecord | SetTrustLineFlagsOperationRecord | DepositLiquidityOperationRecord | WithdrawLiquidityOperationRecord | InvokeHostFunctionOperationRecord | BumpFootprintExpirationOperationRecord | RestoreFootprintOperationRecord; + export namespace TradeRecord { + interface Base extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + ledger_close_time: string; + trade_type: TradeType; + base_account?: string; + base_amount: string; + base_asset_type: string; + base_asset_code?: string; + base_asset_issuer?: string; + counter_account?: string; + counter_amount: string; + counter_asset_type: string; + counter_asset_code?: string; + counter_asset_issuer?: string; + base_is_seller: boolean; + price?: { + n: string; + d: string; + }; + operation: CallFunction; + } + export interface Orderbook extends Base { + trade_type: TradeType.orderbook; + base_offer_id: string; + base_account: string; + counter_offer_id: string; + counter_account: string; + base: CallFunction; + counter: CallFunction; + } + export interface LiquidityPool extends Base { + trade_type: TradeType.liquidityPools; + base_liquidity_pool_id?: string; + counter_liquidity_pool_id?: string; + liquidity_pool_fee_bp: number; + base: CallFunction; + counter: CallFunction; + } + export {}; + } + export type TradeRecord = TradeRecord.Orderbook | TradeRecord.LiquidityPool; + export interface TransactionRecord extends Omit { + ledger_attr: HorizonApi.TransactionResponse["ledger"]; + account: CallFunction; + effects: CallCollectionFunction; + ledger: CallFunction; + operations: CallCollectionFunction; + precedes: CallFunction; + self: CallFunction; + succeeds: CallFunction; + } + export interface OrderbookRecord extends HorizonApi.BaseResponse { + bids: Array<{ + price_r: { + d: number; + n: number; + }; + price: string; + amount: string; + }>; + asks: Array<{ + price_r: { + d: number; + n: number; + }; + price: string; + amount: string; + }>; + base: Asset; + counter: Asset; + } + export interface PaymentPathRecord extends HorizonApi.BaseResponse { + path: Array<{ + asset_code: string; + asset_issuer: string; + asset_type: string; + }>; + source_amount: string; + source_asset_type: string; + source_asset_code: string; + source_asset_issuer: string; + destination_amount: string; + destination_asset_type: string; + destination_asset_code: string; + destination_asset_issuer: string; + } + export {}; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/server_api.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/server_api.js new file mode 100644 index 000000000..df0eafd7f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/server_api.js @@ -0,0 +1,24 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ServerApi = void 0; +var _horizon_api = require("./horizon_api"); +var Effects = _interopRequireWildcard(require("./types/effects")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var ServerApi; +(function (_ServerApi) { + var EffectType = _ServerApi.EffectType = Effects.EffectType; + var TradeType = function (TradeType) { + TradeType["all"] = "all"; + TradeType["liquidityPools"] = "liquidity_pool"; + TradeType["orderbook"] = "orderbook"; + return TradeType; + }({}); + _ServerApi.TradeType = TradeType; + var OperationResponseType = _horizon_api.HorizonApi.OperationResponseType; + var OperationResponseTypeI = _horizon_api.HorizonApi.OperationResponseTypeI; +})(ServerApi || (exports.ServerApi = ServerApi = {})); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/strict_receive_path_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/strict_receive_path_call_builder.d.ts new file mode 100644 index 000000000..1e9a28025 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/strict_receive_path_call_builder.d.ts @@ -0,0 +1,38 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * The Stellar Network allows payments to be made across assets through path + * payments. A strict receive path payment specifies a series of assets to route + * a payment through, from source asset (the asset debited from the payer) to + * destination asset (the asset credited to the payee). + * + * A path search is specified using: + * + * * The source address or source assets. + * * The asset and amount that the destination account should receive + * + * As part of the search, horizon will load a list of assets available to the + * source address and will find any payment paths from those source assets to + * the desired destination asset. The search's amount parameter will be used to + * determine if there a given path can satisfy a payment of the desired amount. + * + * If a list of assets is passed as the source, horizon will find any payment + * paths from those source assets to the desired destination asset. + * + * Do not create this object directly, use {@link Horizon.Server#strictReceivePaths}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/paths|Find Payment Paths} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + * @param {string|Asset[]} source The sender's account ID or a list of Assets. Any returned path must use a source that the sender can hold. + * @param {Asset} destinationAsset The destination asset. + * @param {string} destinationAmount The amount, denominated in the destination asset, that any returned path should be able to satisfy. + */ +export declare class StrictReceivePathCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, source: string | Asset[], destinationAsset: Asset, destinationAmount: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/strict_receive_path_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/strict_receive_path_call_builder.js new file mode 100644 index 000000000..5e4a5a992 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/strict_receive_path_call_builder.js @@ -0,0 +1,50 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.StrictReceivePathCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var StrictReceivePathCallBuilder = exports.StrictReceivePathCallBuilder = function (_CallBuilder) { + function StrictReceivePathCallBuilder(serverUrl, source, destinationAsset, destinationAmount) { + var _this; + _classCallCheck(this, StrictReceivePathCallBuilder); + _this = _callSuper(this, StrictReceivePathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-receive"); + if (typeof source === "string") { + _this.url.setQuery("source_account", source); + } else { + var assets = source.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("source_assets", assets); + } + _this.url.setQuery("destination_amount", destinationAmount); + if (!destinationAsset.isNative()) { + _this.url.setQuery("destination_asset_type", destinationAsset.getAssetType()); + _this.url.setQuery("destination_asset_code", destinationAsset.getCode()); + _this.url.setQuery("destination_asset_issuer", destinationAsset.getIssuer()); + } else { + _this.url.setQuery("destination_asset_type", "native"); + } + return _this; + } + _inherits(StrictReceivePathCallBuilder, _CallBuilder); + return _createClass(StrictReceivePathCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/strict_send_path_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/strict_send_path_call_builder.d.ts new file mode 100644 index 000000000..85cd9a154 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/strict_send_path_call_builder.d.ts @@ -0,0 +1,38 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * The Stellar Network allows payments to be made across assets through path + * payments. A strict send path payment specifies a series of assets to route a + * payment through, from source asset (the asset debited from the payer) to + * destination asset (the asset credited to the payee). + * + * A strict send path search is specified using: + * + * The source asset + * The source amount + * The destination assets or destination account. + * + * As part of the search, horizon will load a list of assets available to the + * source address and will find any payment paths from those source assets to + * the desired destination asset. The search's source_amount parameter will be + * used to determine if there a given path can satisfy a payment of the desired + * amount. + * + * Do not create this object directly, use {@link Horizon.Server#strictSendPaths}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/paths|Find Payment Paths} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + * @param {Asset} sourceAsset The asset to be sent. + * @param {string} sourceAmount The amount, denominated in the source asset, that any returned path should be able to satisfy. + * @param {string|Asset[]} destination The destination account or the destination assets. + * + */ +export declare class StrictSendPathCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, sourceAsset: Asset, sourceAmount: string, destination: string | Asset[]); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/strict_send_path_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/strict_send_path_call_builder.js new file mode 100644 index 000000000..f65a1d0a5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/strict_send_path_call_builder.js @@ -0,0 +1,50 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.StrictSendPathCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var StrictSendPathCallBuilder = exports.StrictSendPathCallBuilder = function (_CallBuilder) { + function StrictSendPathCallBuilder(serverUrl, sourceAsset, sourceAmount, destination) { + var _this; + _classCallCheck(this, StrictSendPathCallBuilder); + _this = _callSuper(this, StrictSendPathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-send"); + if (sourceAsset.isNative()) { + _this.url.setQuery("source_asset_type", "native"); + } else { + _this.url.setQuery("source_asset_type", sourceAsset.getAssetType()); + _this.url.setQuery("source_asset_code", sourceAsset.getCode()); + _this.url.setQuery("source_asset_issuer", sourceAsset.getIssuer()); + } + _this.url.setQuery("source_amount", sourceAmount); + if (typeof destination === "string") { + _this.url.setQuery("destination_account", destination); + } else { + var assets = destination.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("destination_assets", assets); + } + return _this; + } + _inherits(StrictSendPathCallBuilder, _CallBuilder); + return _createClass(StrictSendPathCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/trade_aggregation_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/trade_aggregation_call_builder.d.ts new file mode 100644 index 000000000..fe8dc52d5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/trade_aggregation_call_builder.d.ts @@ -0,0 +1,49 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { HorizonApi } from "./horizon_api"; +import { ServerApi } from "./server_api"; +/** + * Trade Aggregations facilitate efficient gathering of historical trade data. + * + * Do not create this object directly, use {@link Horizon.Server#tradeAggregation}. + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl serverUrl Horizon server URL. + * @param {Asset} base base asset + * @param {Asset} counter counter asset + * @param {number} start_time lower time boundary represented as millis since epoch + * @param {number} end_time upper time boundary represented as millis since epoch + * @param {number} resolution segment duration as millis since epoch. *Supported values are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). + * @param {number} offset segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. + */ +export declare class TradeAggregationCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, base: Asset, counter: Asset, start_time: number, end_time: number, resolution: number, offset: number); + /** + * @private + * @param {number} resolution Trade data resolution in milliseconds + * @returns {boolean} true if the resolution is allowed + */ + private isValidResolution; + /** + * @private + * @param {number} offset Time offset in milliseconds + * @param {number} resolution Trade data resolution in milliseconds + * @returns {boolean} true if the offset is valid + */ + private isValidOffset; +} +interface TradeAggregationRecord extends HorizonApi.BaseResponse { + timestamp: number | string; + trade_count: number | string; + base_volume: string; + counter_volume: string; + avg: string; + high: string; + low: string; + open: string; + close: string; +} +export {}; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/trade_aggregation_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/trade_aggregation_call_builder.js new file mode 100644 index 000000000..b6866d738 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/trade_aggregation_call_builder.js @@ -0,0 +1,76 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TradeAggregationCallBuilder = void 0; +var _call_builder = require("./call_builder"); +var _errors = require("../errors"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var allowedResolutions = [60000, 300000, 900000, 3600000, 86400000, 604800000]; +var TradeAggregationCallBuilder = exports.TradeAggregationCallBuilder = function (_CallBuilder) { + function TradeAggregationCallBuilder(serverUrl, base, counter, start_time, end_time, resolution, offset) { + var _this; + _classCallCheck(this, TradeAggregationCallBuilder); + _this = _callSuper(this, TradeAggregationCallBuilder, [serverUrl]); + _this.url.segment("trade_aggregations"); + if (!base.isNative()) { + _this.url.setQuery("base_asset_type", base.getAssetType()); + _this.url.setQuery("base_asset_code", base.getCode()); + _this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + _this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + _this.url.setQuery("counter_asset_type", counter.getAssetType()); + _this.url.setQuery("counter_asset_code", counter.getCode()); + _this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + _this.url.setQuery("counter_asset_type", "native"); + } + if (typeof start_time !== "number" || typeof end_time !== "number") { + throw new _errors.BadRequestError("Invalid time bounds", [start_time, end_time]); + } else { + _this.url.setQuery("start_time", start_time.toString()); + _this.url.setQuery("end_time", end_time.toString()); + } + if (!_this.isValidResolution(resolution)) { + throw new _errors.BadRequestError("Invalid resolution", resolution); + } else { + _this.url.setQuery("resolution", resolution.toString()); + } + if (!_this.isValidOffset(offset, resolution)) { + throw new _errors.BadRequestError("Invalid offset", offset); + } else { + _this.url.setQuery("offset", offset.toString()); + } + return _this; + } + _inherits(TradeAggregationCallBuilder, _CallBuilder); + return _createClass(TradeAggregationCallBuilder, [{ + key: "isValidResolution", + value: function isValidResolution(resolution) { + return allowedResolutions.some(function (allowed) { + return allowed === resolution; + }); + } + }, { + key: "isValidOffset", + value: function isValidOffset(offset, resolution) { + var hour = 3600000; + return !(offset > resolution || offset >= 24 * hour || offset % hour !== 0); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/trades_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/trades_call_builder.d.ts new file mode 100644 index 000000000..2a407642e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/trades_call_builder.d.ts @@ -0,0 +1,52 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link TradesCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#trades}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/trades|Trades} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl serverUrl Horizon server URL. + */ +export declare class TradesCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Filter trades for a specific asset pair (orderbook) + * @param {Asset} base asset + * @param {Asset} counter asset + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forAssetPair(base: Asset, counter: Asset): this; + /** + * Filter trades for a specific offer + * @param {string} offerId ID of the offer + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forOffer(offerId: string): this; + /** + * Filter trades by a specific type. + * @param {ServerApi.TradeType} tradeType the trade type to filter by. + * @returns {TradesCallBuilder} current TradesCallBuilder instance. + */ + forType(tradeType: ServerApi.TradeType): this; + /** + * Filter trades for a specific account + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-trades-by-account-id|Trades for Account} + * @param {string} accountId For example: `GBYTR4MC5JAX4ALGUBJD7EIKZVM7CUGWKXIUJMRSMK573XH2O7VAK3SR` + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * Filter trades for a specific liquidity pool + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-related-trades|Trades for Liquidity Pool} + * @param {string} liquidityPoolId For example: `3b476aff8a406a6ec3b61d5c038009cef85f2ddfaf616822dc4fec92845149b4` + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forLiquidityPool(liquidityPoolId: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/trades_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/trades_call_builder.js new file mode 100644 index 000000000..5c6b23bec --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/trades_call_builder.js @@ -0,0 +1,72 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TradesCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var TradesCallBuilder = exports.TradesCallBuilder = function (_CallBuilder) { + function TradesCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, TradesCallBuilder); + _this = _callSuper(this, TradesCallBuilder, [serverUrl, "trades"]); + _this.url.segment("trades"); + return _this; + } + _inherits(TradesCallBuilder, _CallBuilder); + return _createClass(TradesCallBuilder, [{ + key: "forAssetPair", + value: function forAssetPair(base, counter) { + if (!base.isNative()) { + this.url.setQuery("base_asset_type", base.getAssetType()); + this.url.setQuery("base_asset_code", base.getCode()); + this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + this.url.setQuery("counter_asset_type", counter.getAssetType()); + this.url.setQuery("counter_asset_code", counter.getCode()); + this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + this.url.setQuery("counter_asset_type", "native"); + } + return this; + } + }, { + key: "forOffer", + value: function forOffer(offerId) { + this.url.setQuery("offer_id", offerId); + return this; + } + }, { + key: "forType", + value: function forType(tradeType) { + this.url.setQuery("trade_type", tradeType); + return this; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(liquidityPoolId) { + return this.forEndpoint("liquidity_pools", liquidityPoolId); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/transaction_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/transaction_call_builder.d.ts new file mode 100644 index 000000000..4c40ce94d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/transaction_call_builder.d.ts @@ -0,0 +1,60 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link TransactionCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#transactions}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-transactions|All Transactions} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + */ +export declare class TransactionCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The transaction details endpoint provides information on a single transaction. The transaction hash provided in the hash argument specifies which transaction to load. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-transaction|Transaction Details} + * @param {string} transactionId Transaction ID + * @returns {CallBuilder} a CallBuilder instance + */ + transaction(transactionId: string): CallBuilder; + /** + * This endpoint represents all transactions that affected a given account. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-transactions-by-account-id|Transactions for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {TransactionCallBuilder} current TransactionCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * This endpoint represents all transactions that reference a given claimable_balance. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/cb-retrieve-related-transactions|Transactions for Claimable Balance} + * @param {string} claimableBalanceId Claimable Balance ID + * @returns {TransactionCallBuilder} this TransactionCallBuilder instance + */ + forClaimableBalance(claimableBalanceId: string): this; + /** + * This endpoint represents all transactions in a given ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-ledgers-transactions|Transactions for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {TransactionCallBuilder} current TransactionCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all transactions involving a particular liquidity pool. + * + * @param {string} poolId liquidity pool ID + * @returns {TransactionCallBuilder} this TransactionCallBuilder instance + */ + forLiquidityPool(poolId: string): this; + /** + * Adds a parameter defining whether to include failed transactions. By default only successful transactions are + * returned. + * @param {boolean} value Set to `true` to include failed transactions. + * @returns {TransactionCallBuilder} current TransactionCallBuilder instance + */ + includeFailed(value: boolean): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/transaction_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/transaction_call_builder.js new file mode 100644 index 000000000..746c7bfbf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/transaction_call_builder.js @@ -0,0 +1,64 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TransactionCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var TransactionCallBuilder = exports.TransactionCallBuilder = function (_CallBuilder) { + function TransactionCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, TransactionCallBuilder); + _this = _callSuper(this, TransactionCallBuilder, [serverUrl, "transactions"]); + _this.url.segment("transactions"); + return _this; + } + _inherits(TransactionCallBuilder, _CallBuilder); + return _createClass(TransactionCallBuilder, [{ + key: "transaction", + value: function transaction(transactionId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([transactionId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/account.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/account.d.ts new file mode 100644 index 000000000..3edc78aad --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/account.d.ts @@ -0,0 +1,5 @@ +export interface AccountRecordSigners { + key: string; + weight: number; + type: string; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/account.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/account.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/account.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/assets.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/assets.d.ts new file mode 100644 index 000000000..c85e71a32 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/assets.d.ts @@ -0,0 +1,17 @@ +import { AssetType } from "@stellar/stellar-base"; +import { HorizonApi } from "../horizon_api"; +export interface AssetRecord extends HorizonApi.BaseResponse { + asset_type: AssetType.credit4 | AssetType.credit12; + asset_code: string; + asset_issuer: string; + paging_token: string; + accounts: HorizonApi.AssetAccounts; + balances: HorizonApi.AssetBalances; + num_claimable_balances: number; + num_liquidity_pools: number; + num_contracts: number; + claimable_balances_amount: string; + liquidity_pools_amount: string; + contracts_amount: string; + flags: HorizonApi.Flags; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/assets.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/assets.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/assets.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/effects.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/effects.d.ts new file mode 100644 index 000000000..a3a628dce --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/effects.d.ts @@ -0,0 +1,285 @@ +import { HorizonApi } from "../horizon_api"; +import { OfferAsset } from "./offer"; +export declare enum EffectType { + account_created = 0, + account_removed = 1, + account_credited = 2, + account_debited = 3, + account_thresholds_updated = 4, + account_home_domain_updated = 5, + account_flags_updated = 6, + account_inflation_destination_updated = 7, + signer_created = 10, + signer_removed = 11, + signer_updated = 12, + trustline_created = 20, + trustline_removed = 21, + trustline_updated = 22, + trustline_authorized = 23, + trustline_deauthorized = 24, + trustline_authorized_to_maintain_liabilities = 25,// deprecated, use trustline_flags_updated + trustline_flags_updated = 26, + offer_created = 30, + offer_removed = 31, + offer_updated = 32, + trade = 33, + data_created = 40, + data_removed = 41, + data_updated = 42, + sequence_bumped = 43, + claimable_balance_created = 50, + claimable_balance_claimant_created = 51, + claimable_balance_claimed = 52, + account_sponsorship_created = 60, + account_sponsorship_updated = 61, + account_sponsorship_removed = 62, + trustline_sponsorship_created = 63, + trustline_sponsorship_updated = 64, + trustline_sponsorship_removed = 65, + data_sponsorship_created = 66, + data_sponsorship_updated = 67, + data_sponsorship_removed = 68, + claimable_balance_sponsorship_created = 69, + claimable_balance_sponsorship_updated = 70, + claimable_balance_sponsorship_removed = 71, + signer_sponsorship_created = 72, + signer_sponsorship_updated = 73, + signer_sponsorship_removed = 74, + claimable_balance_clawed_back = 80, + liquidity_pool_deposited = 90, + liquidity_pool_withdrew = 91, + liquidity_pool_trade = 92, + liquidity_pool_created = 93, + liquidity_pool_removed = 94, + liquidity_pool_revoked = 95, + contract_credited = 96, + contract_debited = 97 +} +export interface BaseEffectRecord extends HorizonApi.BaseResponse { + id: string; + account: string; + paging_token: string; + type_i: EffectType; + type: T; + created_at: string; +} +export interface AccountCreated extends BaseEffectRecord<'account_created'> { + type_i: EffectType.account_created; + starting_balance: string; +} +export interface AccountCredited extends BaseEffectRecord<'account_credited'>, OfferAsset { + type_i: EffectType.account_credited; + amount: string; +} +export interface AccountDebited extends BaseEffectRecord<'account_debited'>, OfferAsset { + type_i: EffectType.account_debited; + amount: string; +} +export interface AccountThresholdsUpdated extends BaseEffectRecord<'account_thresholds_updated'> { + type_i: EffectType.account_thresholds_updated; + low_threshold: number; + med_threshold: number; + high_threshold: number; +} +export interface AccountHomeDomainUpdated extends BaseEffectRecord<'account_home_domain_updated'> { + type_i: EffectType.account_home_domain_updated; + home_domain: string; +} +export interface AccountFlagsUpdated extends BaseEffectRecord<'account_flags_updated'> { + type_i: EffectType.account_flags_updated; + auth_required_flag: boolean; + auth_revokable_flag: boolean; +} +interface DataEvents extends BaseEffectRecord { + name: boolean; + value: boolean; +} +export interface DataCreated extends DataEvents<'data_created'> { + type_i: EffectType.data_created; +} +export interface DataUpdated extends DataEvents<'data_updated'> { + type_i: EffectType.data_updated; +} +export interface DataRemoved extends DataEvents<'data_removed'> { + type_i: EffectType.data_removed; +} +export interface SequenceBumped extends BaseEffectRecord<'sequence_bumped'> { + type_i: EffectType.sequence_bumped; + new_seq: number | string; +} +interface SignerEvents extends BaseEffectRecord { + weight: number; + key: string; + public_key: string; +} +export interface SignerCreated extends SignerEvents<'signer_created'> { + type_i: EffectType.signer_created; +} +export interface SignerRemoved extends SignerEvents<'signer_removed'> { + type_i: EffectType.signer_removed; +} +export interface SignerUpdated extends SignerEvents<'signer_updated'> { + type_i: EffectType.signer_updated; +} +interface TrustlineEvents extends BaseEffectRecord, OfferAsset { + limit: string; + liquidity_pool_id?: string; +} +export interface TrustlineCreated extends TrustlineEvents<'trustline_created'> { + type_i: EffectType.trustline_created; +} +export interface TrustlineRemoved extends TrustlineEvents<'trustline_removed'> { + type_i: EffectType.trustline_removed; +} +export interface TrustlineUpdated extends TrustlineEvents<'trustline_updated'> { + type_i: EffectType.trustline_updated; +} +export interface TrustlineAuthorized extends BaseEffectRecord<'trustline_authorized'> { + type_i: EffectType.trustline_authorized; + asset_type: OfferAsset["asset_type"]; + asset_code: OfferAsset["asset_code"]; + trustor: string; +} +export interface TrustlineDeauthorized extends Omit { + type_i: EffectType.trustline_deauthorized; +} +export interface TrustlineAuthorizedToMaintainLiabilities extends Omit { + type_i: EffectType.trustline_authorized_to_maintain_liabilities; +} +export interface ClaimableBalanceCreated extends BaseEffectRecord<'claimable_balance_created'> { + type_i: EffectType.claimable_balance_created; + amount: string; + balance_type_i: string; + asset: string; +} +export interface ClaimableBalanceClaimed extends Omit { + type_i: EffectType.claimable_balance_claimed; +} +export interface ClaimableBalanceClaimantCreated extends Omit { + type_i: EffectType.claimable_balance_claimant_created; +} +interface SponsershipFields { + sponsor: string; + new_sponsor: string; + former_sponsor: string; +} +interface AccountSponsorshipEvents extends BaseEffectRecord, SponsershipFields { +} +export type AccountSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.account_sponsorship_created; +}; +export type AccountSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.account_sponsorship_updated; +}; +export type AccountSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.account_sponsorship_removed; +}; +interface TrustlineSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + asset?: string; + liquidity_pool_id?: string; +} +export type TrustlineSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.trustline_sponsorship_created; +}; +export type TrustlineSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.trustline_sponsorship_updated; +}; +export type TrustlineSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.trustline_sponsorship_removed; +}; +interface DataSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + data_name: string; +} +export type DateSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.data_sponsorship_created; +}; +export type DateSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.data_sponsorship_updated; +}; +export type DateSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.data_sponsorship_removed; +}; +interface ClaimableBalanceSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + balance_type_i: string; +} +export type ClaimableBalanceSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.claimable_balance_sponsorship_created; +}; +export type ClaimableBalanceSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.claimable_balance_sponsorship_updated; +}; +export type ClaimableBalanceSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.claimable_balance_sponsorship_removed; +}; +interface SignerSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + signer: string; +} +export type SignerSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.signer_sponsorship_created; +}; +export type SignerSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.signer_sponsorship_updated; +}; +export type SignerSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.signer_sponsorship_removed; +}; +export interface ClaimableBalanceClawedBack extends HorizonApi.BaseResponse { + balance_id: string; +} +export interface LiquidityPoolEffectRecord extends HorizonApi.BaseResponse { + id: string; + fee_bp: number; + type: HorizonApi.LiquidityPoolType; + total_trustlines: string; + total_shares: string; + reserves: HorizonApi.Reserve[]; +} +export interface LiquidityPoolDeposited extends BaseEffectRecord<'liquidity_pool_deposited'> { + type_i: EffectType.liquidity_pool_deposited; + liquidity_pool: LiquidityPoolEffectRecord; + reserves_deposited: HorizonApi.Reserve[]; + shares_received: string; +} +export interface LiquidityPoolWithdrew extends BaseEffectRecord<'liquidity_pool_withdrew'> { + type_i: EffectType.liquidity_pool_withdrew; + liquidity_pool: LiquidityPoolEffectRecord; + reserves_received: HorizonApi.Reserve[]; + shares_redeemed: string; +} +export interface LiquidityPoolTrade extends BaseEffectRecord<'liquidity_pool_trade'> { + type_i: EffectType.liquidity_pool_trade; + liquidity_pool: LiquidityPoolEffectRecord; + sold: HorizonApi.Reserve; + bought: HorizonApi.Reserve; +} +export interface LiquidityPoolCreated extends BaseEffectRecord<'liquidity_pool_created'> { + type_i: EffectType.liquidity_pool_created; + liquidity_pool: LiquidityPoolEffectRecord; +} +export interface LiquidityPoolRemoved extends BaseEffectRecord<'liquidity_pool_removed'> { + type_i: EffectType.liquidity_pool_removed; + liquidity_pool_id: string; +} +export interface LiquidityPoolRevoked extends BaseEffectRecord<'liquidity_pool_revoked'> { + type_i: EffectType.liquidity_pool_revoked; + liquidity_pool: LiquidityPoolEffectRecord; + reserves_revoked: [ + { + asset: string; + amount: string; + claimable_balance_id: string; + } + ]; + shares_revoked: string; +} +export interface ContractCredited extends BaseEffectRecord<'contract_credited'>, OfferAsset { + type_i: EffectType.contract_credited; + contract: string; + amount: string; +} +export interface ContractDebited extends BaseEffectRecord<'contract_debited'>, OfferAsset { + type_i: EffectType.contract_debited; + contract: string; + amount: string; +} +export {}; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/effects.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/effects.js new file mode 100644 index 000000000..3b28a678f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/effects.js @@ -0,0 +1,62 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.EffectType = void 0; +var EffectType = exports.EffectType = function (EffectType) { + EffectType[EffectType["account_created"] = 0] = "account_created"; + EffectType[EffectType["account_removed"] = 1] = "account_removed"; + EffectType[EffectType["account_credited"] = 2] = "account_credited"; + EffectType[EffectType["account_debited"] = 3] = "account_debited"; + EffectType[EffectType["account_thresholds_updated"] = 4] = "account_thresholds_updated"; + EffectType[EffectType["account_home_domain_updated"] = 5] = "account_home_domain_updated"; + EffectType[EffectType["account_flags_updated"] = 6] = "account_flags_updated"; + EffectType[EffectType["account_inflation_destination_updated"] = 7] = "account_inflation_destination_updated"; + EffectType[EffectType["signer_created"] = 10] = "signer_created"; + EffectType[EffectType["signer_removed"] = 11] = "signer_removed"; + EffectType[EffectType["signer_updated"] = 12] = "signer_updated"; + EffectType[EffectType["trustline_created"] = 20] = "trustline_created"; + EffectType[EffectType["trustline_removed"] = 21] = "trustline_removed"; + EffectType[EffectType["trustline_updated"] = 22] = "trustline_updated"; + EffectType[EffectType["trustline_authorized"] = 23] = "trustline_authorized"; + EffectType[EffectType["trustline_deauthorized"] = 24] = "trustline_deauthorized"; + EffectType[EffectType["trustline_authorized_to_maintain_liabilities"] = 25] = "trustline_authorized_to_maintain_liabilities"; + EffectType[EffectType["trustline_flags_updated"] = 26] = "trustline_flags_updated"; + EffectType[EffectType["offer_created"] = 30] = "offer_created"; + EffectType[EffectType["offer_removed"] = 31] = "offer_removed"; + EffectType[EffectType["offer_updated"] = 32] = "offer_updated"; + EffectType[EffectType["trade"] = 33] = "trade"; + EffectType[EffectType["data_created"] = 40] = "data_created"; + EffectType[EffectType["data_removed"] = 41] = "data_removed"; + EffectType[EffectType["data_updated"] = 42] = "data_updated"; + EffectType[EffectType["sequence_bumped"] = 43] = "sequence_bumped"; + EffectType[EffectType["claimable_balance_created"] = 50] = "claimable_balance_created"; + EffectType[EffectType["claimable_balance_claimant_created"] = 51] = "claimable_balance_claimant_created"; + EffectType[EffectType["claimable_balance_claimed"] = 52] = "claimable_balance_claimed"; + EffectType[EffectType["account_sponsorship_created"] = 60] = "account_sponsorship_created"; + EffectType[EffectType["account_sponsorship_updated"] = 61] = "account_sponsorship_updated"; + EffectType[EffectType["account_sponsorship_removed"] = 62] = "account_sponsorship_removed"; + EffectType[EffectType["trustline_sponsorship_created"] = 63] = "trustline_sponsorship_created"; + EffectType[EffectType["trustline_sponsorship_updated"] = 64] = "trustline_sponsorship_updated"; + EffectType[EffectType["trustline_sponsorship_removed"] = 65] = "trustline_sponsorship_removed"; + EffectType[EffectType["data_sponsorship_created"] = 66] = "data_sponsorship_created"; + EffectType[EffectType["data_sponsorship_updated"] = 67] = "data_sponsorship_updated"; + EffectType[EffectType["data_sponsorship_removed"] = 68] = "data_sponsorship_removed"; + EffectType[EffectType["claimable_balance_sponsorship_created"] = 69] = "claimable_balance_sponsorship_created"; + EffectType[EffectType["claimable_balance_sponsorship_updated"] = 70] = "claimable_balance_sponsorship_updated"; + EffectType[EffectType["claimable_balance_sponsorship_removed"] = 71] = "claimable_balance_sponsorship_removed"; + EffectType[EffectType["signer_sponsorship_created"] = 72] = "signer_sponsorship_created"; + EffectType[EffectType["signer_sponsorship_updated"] = 73] = "signer_sponsorship_updated"; + EffectType[EffectType["signer_sponsorship_removed"] = 74] = "signer_sponsorship_removed"; + EffectType[EffectType["claimable_balance_clawed_back"] = 80] = "claimable_balance_clawed_back"; + EffectType[EffectType["liquidity_pool_deposited"] = 90] = "liquidity_pool_deposited"; + EffectType[EffectType["liquidity_pool_withdrew"] = 91] = "liquidity_pool_withdrew"; + EffectType[EffectType["liquidity_pool_trade"] = 92] = "liquidity_pool_trade"; + EffectType[EffectType["liquidity_pool_created"] = 93] = "liquidity_pool_created"; + EffectType[EffectType["liquidity_pool_removed"] = 94] = "liquidity_pool_removed"; + EffectType[EffectType["liquidity_pool_revoked"] = 95] = "liquidity_pool_revoked"; + EffectType[EffectType["contract_credited"] = 96] = "contract_credited"; + EffectType[EffectType["contract_debited"] = 97] = "contract_debited"; + return EffectType; +}({}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/offer.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/offer.d.ts new file mode 100644 index 000000000..a58e3f16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/offer.d.ts @@ -0,0 +1,20 @@ +import { AssetType } from "@stellar/stellar-base"; +import { HorizonApi } from "../horizon_api"; +export interface OfferAsset { + asset_type: AssetType; + asset_code?: string; + asset_issuer?: string; +} +export interface OfferRecord extends HorizonApi.BaseResponse { + id: number | string; + paging_token: string; + seller: string; + selling: OfferAsset; + buying: OfferAsset; + amount: string; + price_r: HorizonApi.PriceRShorthand; + price: string; + last_modified_ledger: number; + last_modified_time: string; + sponsor?: string; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/offer.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/offer.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/offer.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/trade.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/trade.d.ts new file mode 100644 index 000000000..a38f75361 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/trade.d.ts @@ -0,0 +1,14 @@ +import { BaseEffectRecord, EffectType } from "./effects"; +export interface Trade extends BaseEffectRecord<'trade'> { + type_i: EffectType.trade; + seller: string; + offer_id: number | string; + bought_amount: string; + bought_asset_type: string; + bought_asset_code: string; + bought_asset_issuer: string; + sold_amount: string; + sold_asset_type: string; + sold_asset_code: string; + sold_asset_issuer: string; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/trade.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/trade.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/horizon/types/trade.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/axios-client.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/axios-client.d.ts new file mode 100644 index 000000000..739c21526 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/axios-client.d.ts @@ -0,0 +1,2 @@ +export declare const axiosClient: import("axios").AxiosStatic; +export declare const create: (config?: import("axios").CreateAxiosDefaults) => import("axios").AxiosInstance; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/axios-client.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/axios-client.js new file mode 100644 index 000000000..12a4eb449 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/axios-client.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.create = exports.axiosClient = void 0; +var _axios = _interopRequireDefault(require("axios")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +var axiosClient = exports.axiosClient = _axios.default; +var create = exports.create = _axios.default.create; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/fetch-client.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/fetch-client.d.ts new file mode 100644 index 000000000..8b91ef645 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/fetch-client.d.ts @@ -0,0 +1,11 @@ +import { AxiosRequestConfig, AxiosResponse } from 'feaxios'; +import { CancelToken, HttpClient, HttpClientRequestConfig, HttpClientResponse } from './types'; +export interface HttpResponse extends AxiosResponse { +} +export interface FetchClientConfig extends AxiosRequestConfig { + adapter?: (config: HttpClientRequestConfig) => Promise>; + cancelToken?: CancelToken; +} +declare function createFetchClient(fetchConfig?: HttpClientRequestConfig): HttpClient; +export declare const fetchClient: HttpClient; +export { createFetchClient as create }; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/fetch-client.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/fetch-client.js new file mode 100644 index 000000000..5da967e91 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/fetch-client.js @@ -0,0 +1,229 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.create = createFetchClient; +exports.fetchClient = void 0; +var _feaxios = _interopRequireDefault(require("feaxios")); +var _types = require("./types"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var InterceptorManager = function () { + function InterceptorManager() { + _classCallCheck(this, InterceptorManager); + _defineProperty(this, "handlers", []); + } + return _createClass(InterceptorManager, [{ + key: "use", + value: function use(fulfilled, rejected) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected + }); + return this.handlers.length - 1; + } + }, { + key: "eject", + value: function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + }, { + key: "forEach", + value: function forEach(fn) { + this.handlers.forEach(function (h) { + if (h !== null) { + fn(h); + } + }); + } + }]); +}(); +function getFormConfig(config) { + var formConfig = config || {}; + formConfig.headers = new Headers(formConfig.headers || {}); + formConfig.headers.set('Content-Type', 'application/x-www-form-urlencoded'); + return formConfig; +} +function createFetchClient() { + var fetchConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var defaults = _objectSpread(_objectSpread({}, fetchConfig), {}, { + headers: fetchConfig.headers || {} + }); + var instance = _feaxios.default.create(defaults); + var requestInterceptors = new InterceptorManager(); + var responseInterceptors = new InterceptorManager(); + var httpClient = { + interceptors: { + request: requestInterceptors, + response: responseInterceptors + }, + defaults: _objectSpread(_objectSpread({}, defaults), {}, { + adapter: function adapter(config) { + return instance.request(config); + } + }), + create: function create(config) { + return createFetchClient(_objectSpread(_objectSpread({}, this.defaults), config)); + }, + makeRequest: function makeRequest(config) { + var _this = this; + return new Promise(function (resolve, reject) { + var abortController = new AbortController(); + config.signal = abortController.signal; + if (config.cancelToken) { + config.cancelToken.promise.then(function () { + abortController.abort(); + reject(new Error('Request canceled')); + }); + } + var modifiedConfig = config; + if (requestInterceptors.handlers.length > 0) { + var chain = requestInterceptors.handlers.filter(function (interceptor) { + return interceptor !== null; + }).flatMap(function (interceptor) { + return [interceptor.fulfilled, interceptor.rejected]; + }); + for (var i = 0, len = chain.length; i < len; i += 2) { + var onFulfilled = chain[i]; + var onRejected = chain[i + 1]; + try { + if (onFulfilled) modifiedConfig = onFulfilled(modifiedConfig); + } catch (error) { + if (onRejected) onRejected === null || onRejected === void 0 || onRejected(error); + reject(error); + return; + } + } + } + var adapter = modifiedConfig.adapter || _this.defaults.adapter; + if (!adapter) { + throw new Error('No adapter available'); + } + var responsePromise = adapter(modifiedConfig).then(function (axiosResponse) { + var httpClientResponse = { + data: axiosResponse.data, + headers: axiosResponse.headers, + config: axiosResponse.config, + status: axiosResponse.status, + statusText: axiosResponse.statusText + }; + return httpClientResponse; + }); + if (responseInterceptors.handlers.length > 0) { + var _chain = responseInterceptors.handlers.filter(function (interceptor) { + return interceptor !== null; + }).flatMap(function (interceptor) { + return [interceptor.fulfilled, interceptor.rejected]; + }); + var _loop = function _loop(_i) { + responsePromise = responsePromise.then(function (response) { + var fulfilledInterceptor = _chain[_i]; + if (typeof fulfilledInterceptor === 'function') { + return fulfilledInterceptor(response); + } + return response; + }, function (error) { + var rejectedInterceptor = _chain[_i + 1]; + if (typeof rejectedInterceptor === 'function') { + return rejectedInterceptor(error); + } + throw error; + }).then(function (interceptedResponse) { + return interceptedResponse; + }); + }; + for (var _i = 0, _len = _chain.length; _i < _len; _i += 2) { + _loop(_i); + } + } + responsePromise.then(resolve).catch(reject); + }); + }, + get: function get(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'get' + })); + }, + delete: function _delete(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'delete' + })); + }, + head: function head(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'head' + })); + }, + options: function options(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'options' + })); + }, + post: function post(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'post', + data: data + })); + }, + put: function put(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'put', + data: data + })); + }, + patch: function patch(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'patch', + data: data + })); + }, + postForm: function postForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'post', + data: data + })); + }, + putForm: function putForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'put', + data: data + })); + }, + patchForm: function patchForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'patch', + data: data + })); + }, + CancelToken: _types.CancelToken, + isCancel: function isCancel(value) { + return value instanceof Error && value.message === 'Request canceled'; + } + }; + return httpClient; +} +var fetchClient = exports.fetchClient = createFetchClient(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/index.d.ts new file mode 100644 index 000000000..b6dea58cd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/index.d.ts @@ -0,0 +1,5 @@ +import { HttpClient, HttpClientRequestConfig } from "./types"; +declare let httpClient: HttpClient; +declare let create: (config?: HttpClientRequestConfig) => HttpClient; +export { httpClient, create }; +export * from "./types"; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/index.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/index.js new file mode 100644 index 000000000..8e8e6230a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/index.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + httpClient: true, + create: true +}; +exports.httpClient = exports.create = void 0; +var _types = require("./types"); +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _types[key]; + } + }); +}); +var httpClient; +var create; +if (false) { + var axiosModule = require('./axios-client'); + exports.httpClient = httpClient = axiosModule.axiosClient; + exports.create = create = axiosModule.create; +} else { + var fetchModule = require('./fetch-client'); + exports.httpClient = httpClient = fetchModule.fetchClient; + exports.create = create = fetchModule.create; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/types.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/types.d.ts new file mode 100644 index 000000000..6aa38dddc --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/types.d.ts @@ -0,0 +1,70 @@ +export type HttpResponseHeaders = Record & { + 'set-cookie'?: string[]; +}; +export interface HttpClientDefaults extends Omit { + headers?: [string, string][] | Record | Headers | undefined; +} +export interface HttpClientResponse { + data: T; + headers: HttpResponseHeaders; + config: any; + status: number; + statusText: string; +} +export interface CancelToken { + promise: Promise; + throwIfRequested(): void; + reason?: string; +} +type HeadersInit = [string, string][] | Record | Headers; +export interface HttpClientRequestConfig { + url?: string; + method?: string; + baseURL?: string; + data?: D; + timeout?: number; + fetchOptions?: Record; + headers?: HeadersInit; + params?: Record; + maxContentLength?: number; + maxRedirects?: number; + cancelToken?: CancelToken; + adapter?: (config: HttpClientRequestConfig) => Promise; +} +export interface HttpClient { + get: (url: string, config?: HttpClientRequestConfig) => Promise>; + delete: (url: string, config?: HttpClientRequestConfig) => Promise>; + head: (url: string, config?: HttpClientRequestConfig) => Promise>; + options: (url: string, config?: HttpClientRequestConfig) => Promise>; + post: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + put: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + patch: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + postForm: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + putForm: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + patchForm: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + interceptors: { + request: InterceptorManager; + response: InterceptorManager; + }; + defaults: HttpClientDefaults; + CancelToken: typeof CancelToken; + isCancel: (value: any) => boolean; + makeRequest: (config: HttpClientRequestConfig) => Promise>; + create: (config?: HttpClientRequestConfig) => HttpClient; +} +export interface Interceptor { + fulfilled: (value: V) => V | Promise; + rejected?: (error: any) => any; +} +export interface InterceptorManager { + use(fulfilled: (value: V) => V | Promise, rejected?: (error: any) => any): number; + eject(id: number): void; + forEach(fn: (interceptor: Interceptor) => void): void; + handlers: Array | null>; +} +export declare class CancelToken { + promise: Promise; + reason?: string; + constructor(executor: (cancel: (reason?: string) => void) => void); +} +export {}; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/types.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/types.js new file mode 100644 index 000000000..80b1012fb --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/http-client/types.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.CancelToken = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var CancelToken = exports.CancelToken = function () { + function CancelToken(executor) { + var _this = this; + _classCallCheck(this, CancelToken); + var resolvePromise; + this.promise = new Promise(function (resolve) { + resolvePromise = resolve; + }); + executor(function (reason) { + _this.reason = reason; + resolvePromise(); + }); + } + return _createClass(CancelToken, [{ + key: "throwIfRequested", + value: function throwIfRequested() { + if (this.reason) { + throw new Error(this.reason); + } + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/index.d.ts new file mode 100644 index 000000000..6ae366241 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/index.d.ts @@ -0,0 +1,32 @@ +export * from './errors'; +export { Config } from './config'; +export { Utils } from './utils'; +export * as StellarToml from './stellartoml'; +export * as Federation from './federation'; +export * as WebAuth from './webauth'; +export * as Friendbot from './friendbot'; +export * as Horizon from './horizon'; +/** + * Tools for interacting with the Soroban RPC server, such as `Server`, + * `assembleTransaction`, and the `Api` types. You can import these from the + * `/rpc` entrypoint, if your version of Node and your TypeScript configuration + * allow it: + * + * @example + * import { Server } from '@stellar/stellar-sdk/rpc'; + */ +export * as rpc from './rpc'; +/** + * Tools for interacting with smart contracts, such as `Client`, `Spec`, and + * `AssembledTransaction`. You can import these from the `/contract` + * entrypoint, if your version of Node and your TypeScript configuration allow + * it: + * + * @example + * import { Client } from '@stellar/stellar-sdk/contract'; + * @private + */ +export * as contract from './contract'; +export * from '@stellar/stellar-base'; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/index.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/index.js new file mode 100644 index 000000000..cbdb8649c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/index.js @@ -0,0 +1,80 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Config: true, + Utils: true, + StellarToml: true, + Federation: true, + WebAuth: true, + Friendbot: true, + Horizon: true, + rpc: true, + contract: true +}; +Object.defineProperty(exports, "Config", { + enumerable: true, + get: function get() { + return _config.Config; + } +}); +exports.StellarToml = exports.Horizon = exports.Friendbot = exports.Federation = void 0; +Object.defineProperty(exports, "Utils", { + enumerable: true, + get: function get() { + return _utils.Utils; + } +}); +exports.rpc = exports.default = exports.contract = exports.WebAuth = void 0; +var _errors = require("./errors"); +Object.keys(_errors).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _errors[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _errors[key]; + } + }); +}); +var _config = require("./config"); +var _utils = require("./utils"); +var _StellarToml = _interopRequireWildcard(require("./stellartoml")); +exports.StellarToml = _StellarToml; +var _Federation = _interopRequireWildcard(require("./federation")); +exports.Federation = _Federation; +var _WebAuth = _interopRequireWildcard(require("./webauth")); +exports.WebAuth = _WebAuth; +var _Friendbot = _interopRequireWildcard(require("./friendbot")); +exports.Friendbot = _Friendbot; +var _Horizon = _interopRequireWildcard(require("./horizon")); +exports.Horizon = _Horizon; +var _rpc = _interopRequireWildcard(require("./rpc")); +exports.rpc = _rpc; +var _contract = _interopRequireWildcard(require("./contract")); +exports.contract = _contract; +var _stellarBase = require("@stellar/stellar-base"); +Object.keys(_stellarBase).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _stellarBase[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _stellarBase[key]; + } + }); +}); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; +if (typeof global.__USE_AXIOS__ === 'undefined') { + global.__USE_AXIOS__ = true; +} +if (typeof global.__USE_EVENTSOURCE__ === 'undefined') { + global.__USE_EVENTSOURCE__ = false; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/api.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/api.d.ts new file mode 100644 index 000000000..87d269804 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/api.d.ts @@ -0,0 +1,363 @@ +import { Contract, SorobanDataBuilder, xdr } from '@stellar/stellar-base'; +export declare namespace Api { + export interface GetHealthResponse { + status: 'healthy'; + } + export interface LedgerEntryResult { + lastModifiedLedgerSeq?: number; + key: xdr.LedgerKey; + val: xdr.LedgerEntryData; + liveUntilLedgerSeq?: number; + } + export interface RawLedgerEntryResult { + lastModifiedLedgerSeq?: number; + /** a base-64 encoded {@link xdr.LedgerKey} instance */ + key: string; + /** a base-64 encoded {@link xdr.LedgerEntryData} instance */ + xdr: string; + /** + * optional, a future ledger number upon which this entry will expire + * based on https://github.com/stellar/soroban-tools/issues/1010 + */ + liveUntilLedgerSeq?: number; + } + /** An XDR-parsed version of {@link this.RawLedgerEntryResult} */ + export interface GetLedgerEntriesResponse { + entries: LedgerEntryResult[]; + latestLedger: number; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries */ + export interface RawGetLedgerEntriesResponse { + entries?: RawLedgerEntryResult[]; + latestLedger: number; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getNetwork */ + export interface GetNetworkResponse { + friendbotUrl?: string; + passphrase: string; + protocolVersion: string; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLatestLedger */ + export interface GetLatestLedgerResponse { + id: string; + sequence: number; + protocolVersion: string; + } + export enum GetTransactionStatus { + SUCCESS = "SUCCESS", + NOT_FOUND = "NOT_FOUND", + FAILED = "FAILED" + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransaction */ + export type GetTransactionResponse = GetSuccessfulTransactionResponse | GetFailedTransactionResponse | GetMissingTransactionResponse; + interface GetAnyTransactionResponse { + status: GetTransactionStatus; + txHash: string; + latestLedger: number; + latestLedgerCloseTime: number; + oldestLedger: number; + oldestLedgerCloseTime: number; + } + export interface GetMissingTransactionResponse extends GetAnyTransactionResponse { + status: GetTransactionStatus.NOT_FOUND; + } + export interface GetFailedTransactionResponse extends GetAnyTransactionResponse { + status: GetTransactionStatus.FAILED; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + envelopeXdr: xdr.TransactionEnvelope; + resultXdr: xdr.TransactionResult; + resultMetaXdr: xdr.TransactionMeta; + diagnosticEventsXdr?: xdr.DiagnosticEvent[]; + } + export interface GetSuccessfulTransactionResponse extends GetAnyTransactionResponse { + status: GetTransactionStatus.SUCCESS; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + envelopeXdr: xdr.TransactionEnvelope; + resultXdr: xdr.TransactionResult; + resultMetaXdr: xdr.TransactionMeta; + diagnosticEventsXdr?: xdr.DiagnosticEvent[]; + returnValue?: xdr.ScVal; + } + export interface RawGetTransactionResponse { + status: GetTransactionStatus; + latestLedger: number; + latestLedgerCloseTime: number; + oldestLedger: number; + oldestLedgerCloseTime: number; + txHash: string; + applicationOrder?: number; + feeBump?: boolean; + ledger?: number; + createdAt?: number; + envelopeXdr?: string; + resultXdr?: string; + resultMetaXdr?: string; + diagnosticEventsXdr?: string[]; + } + export interface GetTransactionsRequest { + startLedger: number; + cursor?: string; + limit?: number; + } + export interface RawTransactionInfo { + status: GetTransactionStatus; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + txHash: string; + envelopeXdr?: string; + resultXdr?: string; + resultMetaXdr?: string; + diagnosticEventsXdr?: string[]; + } + export interface TransactionInfo { + status: GetTransactionStatus; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + txHash: string; + envelopeXdr: xdr.TransactionEnvelope; + resultXdr: xdr.TransactionResult; + resultMetaXdr: xdr.TransactionMeta; + returnValue?: xdr.ScVal; + diagnosticEventsXdr?: xdr.DiagnosticEvent[]; + } + export interface GetTransactionsResponse { + transactions: TransactionInfo[]; + latestLedger: number; + latestLedgerCloseTimestamp: number; + oldestLedger: number; + oldestLedgerCloseTimestamp: number; + cursor: string; + } + export interface RawGetTransactionsResponse { + transactions: RawTransactionInfo[]; + latestLedger: number; + latestLedgerCloseTimestamp: number; + oldestLedger: number; + oldestLedgerCloseTimestamp: number; + cursor: string; + } + export type EventType = 'contract' | 'system' | 'diagnostic'; + export interface EventFilter { + type?: EventType; + contractIds?: string[]; + topics?: string[][]; + } + export interface GetEventsResponse { + latestLedger: number; + events: EventResponse[]; + cursor: string; + } + export interface EventResponse extends BaseEventResponse { + contractId?: Contract; + topic: xdr.ScVal[]; + value: xdr.ScVal; + } + export interface RawGetEventsResponse { + latestLedger: number; + events: RawEventResponse[]; + cursor: string; + } + interface BaseEventResponse { + id: string; + type: EventType; + ledger: number; + ledgerClosedAt: string; + pagingToken: string; + inSuccessfulContractCall: boolean; + txHash: string; + } + export interface RawEventResponse extends BaseEventResponse { + contractId: string; + topic: string[]; + value: string; + } + interface RawLedgerEntryChange { + type: number; + /** This is LedgerKey in base64 */ + key: string; + /** This is xdr.LedgerEntry in base64 */ + before: string | null; + /** This is xdr.LedgerEntry in base64 */ + after: string | null; + } + export interface LedgerEntryChange { + type: number; + key: xdr.LedgerKey; + before: xdr.LedgerEntry | null; + after: xdr.LedgerEntry | null; + } + export type SendTransactionStatus = 'PENDING' | 'DUPLICATE' | 'TRY_AGAIN_LATER' | 'ERROR'; + export interface SendTransactionResponse extends BaseSendTransactionResponse { + errorResult?: xdr.TransactionResult; + diagnosticEvents?: xdr.DiagnosticEvent[]; + } + export interface RawSendTransactionResponse extends BaseSendTransactionResponse { + /** + * This is a base64-encoded instance of {@link xdr.TransactionResult}, set + * only when `status` is `"ERROR"`. + * + * It contains details on why the network rejected the transaction. + */ + errorResultXdr?: string; + /** + * This is a base64-encoded instance of an array of + * {@link xdr.DiagnosticEvent}s, set only when `status` is `"ERROR"` and + * diagnostic events are enabled on the server. + */ + diagnosticEventsXdr?: string[]; + } + export interface BaseSendTransactionResponse { + status: SendTransactionStatus; + hash: string; + latestLedger: number; + latestLedgerCloseTime: number; + } + export interface SimulateHostFunctionResult { + auth: xdr.SorobanAuthorizationEntry[]; + retval: xdr.ScVal; + } + /** + * Simplifies {@link Api.RawSimulateTransactionResponse} into separate interfaces + * based on status: + * - on success, this includes all fields, though `result` is only present + * if an invocation was simulated (since otherwise there's nothing to + * "resultify") + * - if there was an expiration error, this includes error and restoration + * fields + * - for all other errors, this only includes error fields + * + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction + */ + export type SimulateTransactionResponse = SimulateTransactionSuccessResponse | SimulateTransactionRestoreResponse | SimulateTransactionErrorResponse; + export interface BaseSimulateTransactionResponse { + /** always present: the JSON-RPC request ID */ + id: string; + /** always present: the LCL known to the server when responding */ + latestLedger: number; + /** + * The field is always present, but may be empty in cases where: + * - you didn't simulate an invocation or + * - there were no events + */ + events: xdr.DiagnosticEvent[]; + /** a private field to mark the schema as parsed */ + _parsed: boolean; + } + /** Includes simplified fields only present on success. */ + export interface SimulateTransactionSuccessResponse extends BaseSimulateTransactionResponse { + transactionData: SorobanDataBuilder; + minResourceFee: string; + /** present only for invocation simulation */ + result?: SimulateHostFunctionResult; + /** State Difference information */ + stateChanges?: LedgerEntryChange[]; + } + /** Includes details about why the simulation failed */ + export interface SimulateTransactionErrorResponse extends BaseSimulateTransactionResponse { + error: string; + events: xdr.DiagnosticEvent[]; + } + export interface SimulateTransactionRestoreResponse extends SimulateTransactionSuccessResponse { + result: SimulateHostFunctionResult; + /** + * Indicates that a restoration is necessary prior to submission. + * + * In other words, seeing a restoration preamble means that your invocation + * was executed AS IF the required ledger entries were present, and this + * field includes information about what you need to restore for the + * simulation to succeed. + */ + restorePreamble: { + minResourceFee: string; + transactionData: SorobanDataBuilder; + }; + } + export function isSimulationError(sim: SimulateTransactionResponse): sim is SimulateTransactionErrorResponse; + export function isSimulationSuccess(sim: SimulateTransactionResponse): sim is SimulateTransactionSuccessResponse; + export function isSimulationRestore(sim: SimulateTransactionResponse): sim is SimulateTransactionRestoreResponse; + export function isSimulationRaw(sim: Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse): sim is Api.RawSimulateTransactionResponse; + interface RawSimulateHostFunctionResult { + auth?: string[]; + xdr: string; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction */ + export interface RawSimulateTransactionResponse { + id: string; + latestLedger: number; + error?: string; + /** This is an xdr.SorobanTransactionData in base64 */ + transactionData?: string; + /** These are xdr.DiagnosticEvents in base64 */ + events?: string[]; + minResourceFee?: string; + /** + * This will only contain a single element if present, because only a single + * invokeHostFunctionOperation is supported per transaction. + * */ + results?: RawSimulateHostFunctionResult[]; + /** Present if succeeded but has expired ledger entries */ + restorePreamble?: { + minResourceFee: string; + transactionData: string; + }; + /** State difference information */ + stateChanges?: RawLedgerEntryChange[]; + } + export interface GetVersionInfoResponse { + version: string; + commitHash: string; + buildTimestamp: string; + captiveCoreVersion: string; + protocolVersion: number; + commit_hash: string; + build_timestamp: string; + captive_core_version: string; + protocol_version: number; + } + export interface GetFeeStatsResponse { + sorobanInclusionFee: FeeDistribution; + inclusionFee: FeeDistribution; + latestLedger: number; + } + interface FeeDistribution { + max: string; + min: string; + mode: string; + p10: string; + p20: string; + p30: string; + p40: string; + p50: string; + p60: string; + p70: string; + p80: string; + p90: string; + p95: string; + p99: string; + transactionCount: string; + ledgerCount: number; + } + export interface BalanceResponse { + latestLedger: number; + /** present only on success, otherwise request malformed or no balance */ + balanceEntry?: { + /** a 64-bit integer */ + amount: string; + authorized: boolean; + clawback: boolean; + lastModifiedLedgerSeq?: number; + liveUntilLedgerSeq?: number; + }; + } + export {}; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/api.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/api.js new file mode 100644 index 000000000..119ddb359 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/api.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Api = void 0; +var Api; +(function (_Api) { + var GetTransactionStatus = function (GetTransactionStatus) { + GetTransactionStatus["SUCCESS"] = "SUCCESS"; + GetTransactionStatus["NOT_FOUND"] = "NOT_FOUND"; + GetTransactionStatus["FAILED"] = "FAILED"; + return GetTransactionStatus; + }({}); + _Api.GetTransactionStatus = GetTransactionStatus; + function isSimulationError(sim) { + return 'error' in sim; + } + _Api.isSimulationError = isSimulationError; + function isSimulationSuccess(sim) { + return 'transactionData' in sim; + } + _Api.isSimulationSuccess = isSimulationSuccess; + function isSimulationRestore(sim) { + return isSimulationSuccess(sim) && 'restorePreamble' in sim && !!sim.restorePreamble.transactionData; + } + _Api.isSimulationRestore = isSimulationRestore; + function isSimulationRaw(sim) { + return !sim._parsed; + } + _Api.isSimulationRaw = isSimulationRaw; +})(Api || (exports.Api = Api = {})); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/axios.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/axios.d.ts new file mode 100644 index 000000000..e33eb69ca --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/axios.d.ts @@ -0,0 +1,4 @@ +import { HttpClient } from "../http-client"; +export declare const version: string; +export declare const AxiosClient: HttpClient; +export default AxiosClient; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/axios.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/axios.js new file mode 100644 index 000000000..7ac7ee27c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/axios.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.version = exports.default = exports.AxiosClient = void 0; +var _httpClient = require("../http-client"); +var version = exports.version = "13.1.0"; +var AxiosClient = exports.AxiosClient = (0, _httpClient.create)({ + headers: { + 'X-Client-Name': 'js-soroban-client', + 'X-Client-Version': version + } +}); +var _default = exports.default = AxiosClient; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/browser.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/browser.d.ts new file mode 100644 index 000000000..ca51e31ab --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/browser.d.ts @@ -0,0 +1,4 @@ +export * from './index'; +export * as StellarBase from '@stellar/stellar-base'; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/browser.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/browser.js new file mode 100644 index 000000000..81ef3ddb4 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/browser.js @@ -0,0 +1,27 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + StellarBase: true +}; +exports.default = exports.StellarBase = void 0; +var _index = require("./index"); +Object.keys(_index).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _index[key]; + } + }); +}); +var _StellarBase = _interopRequireWildcard(require("@stellar/stellar-base")); +exports.StellarBase = _StellarBase; +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/index.d.ts new file mode 100644 index 000000000..59ea4be47 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/index.d.ts @@ -0,0 +1,8 @@ +/** @module rpc */ +export * from "./api"; +export { RpcServer as Server, BasicSleepStrategy, LinearSleepStrategy, Durability } from "./server"; +export { default as AxiosClient } from "./axios"; +export { parseRawSimulation, parseRawEvents } from "./parsers"; +export * from "./transaction"; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/index.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/index.js new file mode 100644 index 000000000..f5a9e18bd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/index.js @@ -0,0 +1,86 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Server: true, + BasicSleepStrategy: true, + LinearSleepStrategy: true, + Durability: true, + AxiosClient: true, + parseRawSimulation: true, + parseRawEvents: true +}; +Object.defineProperty(exports, "AxiosClient", { + enumerable: true, + get: function get() { + return _axios.default; + } +}); +Object.defineProperty(exports, "BasicSleepStrategy", { + enumerable: true, + get: function get() { + return _server.BasicSleepStrategy; + } +}); +Object.defineProperty(exports, "Durability", { + enumerable: true, + get: function get() { + return _server.Durability; + } +}); +Object.defineProperty(exports, "LinearSleepStrategy", { + enumerable: true, + get: function get() { + return _server.LinearSleepStrategy; + } +}); +Object.defineProperty(exports, "Server", { + enumerable: true, + get: function get() { + return _server.RpcServer; + } +}); +exports.default = void 0; +Object.defineProperty(exports, "parseRawEvents", { + enumerable: true, + get: function get() { + return _parsers.parseRawEvents; + } +}); +Object.defineProperty(exports, "parseRawSimulation", { + enumerable: true, + get: function get() { + return _parsers.parseRawSimulation; + } +}); +var _api = require("./api"); +Object.keys(_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _api[key]; + } + }); +}); +var _server = require("./server"); +var _axios = _interopRequireDefault(require("./axios")); +var _parsers = require("./parsers"); +var _transaction = require("./transaction"); +Object.keys(_transaction).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _transaction[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _transaction[key]; + } + }); +}); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/jsonrpc.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/jsonrpc.d.ts new file mode 100644 index 000000000..bba021d3c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/jsonrpc.d.ts @@ -0,0 +1,35 @@ +export type Id = string | number; +export interface Request { + jsonrpc: "2.0"; + id: Id; + method: string; + params: T; +} +export interface Notification { + jsonrpc: "2.0"; + method: string; + params?: T; +} +export type Response = { + jsonrpc: "2.0"; + id: Id; +} & ({ + error: Error; +} | { + result: T; +}); +export interface Error { + code: number; + message?: string; + data?: E; +} +/** + * Sends the jsonrpc 'params' as a single 'param' object (no array support). + * + * @param {string} url URL to the RPC instance + * @param {string} method RPC method name that should be called + * @param {(any | null)} [param=null] params that should be supplied to the method + * @returns {Promise} + * @private + */ +export declare function postObject(url: string, method: string, param?: any): Promise; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/jsonrpc.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/jsonrpc.js new file mode 100644 index 000000000..8ba0f1a64 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/jsonrpc.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.postObject = postObject; +var _axios = _interopRequireDefault(require("./axios")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function hasOwnProperty(obj, prop) { + return obj.hasOwnProperty(prop); +} +function postObject(_x, _x2) { + return _postObject.apply(this, arguments); +} +function _postObject() { + _postObject = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(url, method) { + var param, + response, + _response$data, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + param = _args.length > 2 && _args[2] !== undefined ? _args[2] : null; + _context.next = 3; + return _axios.default.post(url, { + jsonrpc: "2.0", + id: 1, + method: method, + params: param + }); + case 3: + response = _context.sent; + if (!hasOwnProperty(response.data, "error")) { + _context.next = 8; + break; + } + throw response.data.error; + case 8: + return _context.abrupt("return", (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.result); + case 9: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _postObject.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/parsers.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/parsers.d.ts new file mode 100644 index 000000000..28871d62b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/parsers.d.ts @@ -0,0 +1,39 @@ +import { Api } from './api'; +/** + * Parse the response from invoking the `submitTransaction` method of a Soroban RPC server. + * @memberof module:rpc + * @private + * + * @param {Api.RawSendTransactionResponse} raw the raw `submitTransaction` response from the Soroban RPC server to parse + * @returns {Api.SendTransactionResponse} transaction response parsed from the Soroban RPC server's response + */ +export declare function parseRawSendTransaction(raw: Api.RawSendTransactionResponse): Api.SendTransactionResponse; +export declare function parseTransactionInfo(raw: Api.RawTransactionInfo | Api.RawGetTransactionResponse): Omit; +export declare function parseRawTransactions(r: Api.RawTransactionInfo): Api.TransactionInfo; +/** + * Parse and return the retrieved events, if any, from a raw response from a Soroban RPC server. + * @memberof module:rpc + * + * @param {Api.RawGetEventsResponse} raw the raw `getEvents` response from the Soroban RPC server to parse + * @returns {Api.GetEventsResponse} events parsed from the Soroban RPC server's response + */ +export declare function parseRawEvents(raw: Api.RawGetEventsResponse): Api.GetEventsResponse; +/** + * Parse and return the retrieved ledger entries, if any, from a raw response from a Soroban RPC server. + * @memberof module:rpc + * @private + * + * @param {Api.RawGetLedgerEntriesResponse} raw he raw `getLedgerEntries` response from the Soroban RPC server to parse + * @returns {Api.GetLedgerEntriesResponse} ledger entries parsed from the Soroban RPC server's response + */ +export declare function parseRawLedgerEntries(raw: Api.RawGetLedgerEntriesResponse): Api.GetLedgerEntriesResponse; +/** + * Converts a raw response schema into one with parsed XDR fields and a simplified interface. + * @warning This API is only exported for testing purposes and should not be relied on or considered "stable". + * @memberof module:rpc + * + * @param {Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse} sim the raw response schema (parsed ones are allowed, best-effort + * detected, and returned untouched) + * @returns {Api.SimulateTransactionResponse} the original parameter (if already parsed), parsed otherwise + */ +export declare function parseRawSimulation(sim: Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse): Api.SimulateTransactionResponse; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/parsers.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/parsers.js new file mode 100644 index 000000000..196336b10 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/parsers.js @@ -0,0 +1,156 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parseRawEvents = parseRawEvents; +exports.parseRawLedgerEntries = parseRawLedgerEntries; +exports.parseRawSendTransaction = parseRawSendTransaction; +exports.parseRawSimulation = parseRawSimulation; +exports.parseRawTransactions = parseRawTransactions; +exports.parseTransactionInfo = parseTransactionInfo; +var _stellarBase = require("@stellar/stellar-base"); +var _api = require("./api"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function parseRawSendTransaction(raw) { + var errorResultXdr = raw.errorResultXdr, + diagnosticEventsXdr = raw.diagnosticEventsXdr; + delete raw.errorResultXdr; + delete raw.diagnosticEventsXdr; + if (errorResultXdr) { + return _objectSpread(_objectSpread(_objectSpread({}, raw), diagnosticEventsXdr !== undefined && diagnosticEventsXdr.length > 0 && { + diagnosticEvents: diagnosticEventsXdr.map(function (evt) { + return _stellarBase.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + }) + }), {}, { + errorResult: _stellarBase.xdr.TransactionResult.fromXDR(errorResultXdr, 'base64') + }); + } + return _objectSpread({}, raw); +} +function parseTransactionInfo(raw) { + var meta = _stellarBase.xdr.TransactionMeta.fromXDR(raw.resultMetaXdr, 'base64'); + var info = { + ledger: raw.ledger, + createdAt: raw.createdAt, + applicationOrder: raw.applicationOrder, + feeBump: raw.feeBump, + envelopeXdr: _stellarBase.xdr.TransactionEnvelope.fromXDR(raw.envelopeXdr, 'base64'), + resultXdr: _stellarBase.xdr.TransactionResult.fromXDR(raw.resultXdr, 'base64'), + resultMetaXdr: meta + }; + if (meta.switch() === 3 && meta.v3().sorobanMeta() !== null) { + var _meta$v3$sorobanMeta; + info.returnValue = (_meta$v3$sorobanMeta = meta.v3().sorobanMeta()) === null || _meta$v3$sorobanMeta === void 0 ? void 0 : _meta$v3$sorobanMeta.returnValue(); + } + if ('diagnosticEventsXdr' in raw && raw.diagnosticEventsXdr) { + info.diagnosticEventsXdr = raw.diagnosticEventsXdr.map(function (diagnosticEvent) { + return _stellarBase.xdr.DiagnosticEvent.fromXDR(diagnosticEvent, 'base64'); + }); + } + return info; +} +function parseRawTransactions(r) { + return _objectSpread({ + status: r.status, + txHash: r.txHash + }, parseTransactionInfo(r)); +} +function parseRawEvents(raw) { + var _raw$events; + return { + latestLedger: raw.latestLedger, + cursor: raw.cursor, + events: ((_raw$events = raw.events) !== null && _raw$events !== void 0 ? _raw$events : []).map(function (evt) { + var clone = _objectSpread({}, evt); + delete clone.contractId; + return _objectSpread(_objectSpread(_objectSpread({}, clone), evt.contractId !== '' && { + contractId: new _stellarBase.Contract(evt.contractId) + }), {}, { + topic: evt.topic.map(function (topic) { + return _stellarBase.xdr.ScVal.fromXDR(topic, 'base64'); + }), + value: _stellarBase.xdr.ScVal.fromXDR(evt.value, 'base64') + }); + }) + }; +} +function parseRawLedgerEntries(raw) { + var _raw$entries; + return { + latestLedger: raw.latestLedger, + entries: ((_raw$entries = raw.entries) !== null && _raw$entries !== void 0 ? _raw$entries : []).map(function (rawEntry) { + if (!rawEntry.key || !rawEntry.xdr) { + throw new TypeError("invalid ledger entry: ".concat(JSON.stringify(rawEntry))); + } + return _objectSpread({ + lastModifiedLedgerSeq: rawEntry.lastModifiedLedgerSeq, + key: _stellarBase.xdr.LedgerKey.fromXDR(rawEntry.key, 'base64'), + val: _stellarBase.xdr.LedgerEntryData.fromXDR(rawEntry.xdr, 'base64') + }, rawEntry.liveUntilLedgerSeq !== undefined && { + liveUntilLedgerSeq: rawEntry.liveUntilLedgerSeq + }); + }) + }; +} +function parseSuccessful(sim, partial) { + var _sim$results$length, _sim$results, _sim$stateChanges$len, _sim$stateChanges, _sim$stateChanges2; + var success = _objectSpread(_objectSpread(_objectSpread({}, partial), {}, { + transactionData: new _stellarBase.SorobanDataBuilder(sim.transactionData), + minResourceFee: sim.minResourceFee + }, ((_sim$results$length = (_sim$results = sim.results) === null || _sim$results === void 0 ? void 0 : _sim$results.length) !== null && _sim$results$length !== void 0 ? _sim$results$length : 0 > 0) && { + result: sim.results.map(function (row) { + var _row$auth; + return { + auth: ((_row$auth = row.auth) !== null && _row$auth !== void 0 ? _row$auth : []).map(function (entry) { + return _stellarBase.xdr.SorobanAuthorizationEntry.fromXDR(entry, 'base64'); + }), + retval: row.xdr ? _stellarBase.xdr.ScVal.fromXDR(row.xdr, 'base64') : _stellarBase.xdr.ScVal.scvVoid() + }; + })[0] + }), ((_sim$stateChanges$len = (_sim$stateChanges = sim.stateChanges) === null || _sim$stateChanges === void 0 ? void 0 : _sim$stateChanges.length) !== null && _sim$stateChanges$len !== void 0 ? _sim$stateChanges$len : 0 > 0) && { + stateChanges: (_sim$stateChanges2 = sim.stateChanges) === null || _sim$stateChanges2 === void 0 ? void 0 : _sim$stateChanges2.map(function (entryChange) { + return { + type: entryChange.type, + key: _stellarBase.xdr.LedgerKey.fromXDR(entryChange.key, 'base64'), + before: entryChange.before ? _stellarBase.xdr.LedgerEntry.fromXDR(entryChange.before, 'base64') : null, + after: entryChange.after ? _stellarBase.xdr.LedgerEntry.fromXDR(entryChange.after, 'base64') : null + }; + }) + }); + if (!sim.restorePreamble || sim.restorePreamble.transactionData === '') { + return success; + } + return _objectSpread(_objectSpread({}, success), {}, { + restorePreamble: { + minResourceFee: sim.restorePreamble.minResourceFee, + transactionData: new _stellarBase.SorobanDataBuilder(sim.restorePreamble.transactionData) + } + }); +} +function parseRawSimulation(sim) { + var _sim$events$map, _sim$events; + var looksRaw = _api.Api.isSimulationRaw(sim); + if (!looksRaw) { + return sim; + } + var base = { + _parsed: true, + id: sim.id, + latestLedger: sim.latestLedger, + events: (_sim$events$map = (_sim$events = sim.events) === null || _sim$events === void 0 ? void 0 : _sim$events.map(function (evt) { + return _stellarBase.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + })) !== null && _sim$events$map !== void 0 ? _sim$events$map : [] + }; + if (typeof sim.error === 'string') { + return _objectSpread(_objectSpread({}, base), {}, { + error: sim.error + }); + } + return parseSuccessful(sim, base); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/server.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/server.d.ts new file mode 100644 index 000000000..7b90f345d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/server.d.ts @@ -0,0 +1,622 @@ +import URI from 'urijs'; +import { Account, Address, Asset, Contract, FeeBumpTransaction, Transaction, xdr } from '@stellar/stellar-base'; +import { Api } from './api'; +/** + * Default transaction submission timeout for RPC requests, in milliseconds + * @constant {number} + * @default 60000 + * @memberof module:rpc.Server + */ +export declare const SUBMIT_TRANSACTION_TIMEOUT: number; +/** + * Specifies the durability namespace of contract-related ledger entries. + * @enum {('temporary' | 'persistent')} + * @memberof module:rpc + * + * @see {@link https://developers.stellar.org/docs/learn/smart-contract-internals/state-archival | State Archival docs} + * @see {@link https://docs.rs/soroban-sdk/latest/soroban_sdk/storage/struct.Storage.html | Rust SDK Storage docs} + */ +export declare enum Durability { + Temporary = "temporary", + Persistent = "persistent" +} +/** + * @typedef {object} GetEventsRequest Describes the complex filter combinations available for event queries. + * @property {Array.} filters Filters to use when querying events from the RPC server. + * @property {number} [startLedger] Ledger number (inclusive) to begin querying events. + * @property {string} [cursor] Page cursor (exclusive) to begin querying events. + * @property {number} [limit=100] The maximum number of events that should be returned in the RPC response. + * @memberof module:rpc.Server + */ +/** + * @typedef {object} ResourceLeeway Describes additional resource leeways for transaction simulation. + * @property {number} cpuInstructions Simulate the transaction with more CPU instructions available. + * @memberof module:rpc.Server + */ +/** + * @typedef {object} Options Options for configuring connections to RPC servers. + * @property {boolean} [allowHttp=false] Allow connecting to http servers, default: `false`. This must be set to false in production deployments! + * @property {number} [timeout=0] Allow a timeout, default: 0. Allows user to avoid nasty lag. You can also use {@link Config} class to set this globally. + * @property {Record} [headers] Additional headers that should be added to any requests to the RPC server. + * @memberof module:rpc.Server + */ +export declare namespace RpcServer { + interface GetEventsRequest { + filters: Api.EventFilter[]; + startLedger?: number; + endLedger?: number; + cursor?: string; + limit?: number; + } + interface PollingOptions { + attempts?: number; + sleepStrategy?: SleepStrategy; + } + interface ResourceLeeway { + cpuInstructions: number; + } + interface Options { + allowHttp?: boolean; + timeout?: number; + headers?: Record; + } +} +export declare const BasicSleepStrategy: SleepStrategy; +export declare const LinearSleepStrategy: SleepStrategy; +/** + * A function that returns the number of *milliseconds* to sleep + * on a given `iter`ation. + */ +export type SleepStrategy = (iter: number) => number; +/** + * Handles the network connection to a Soroban RPC instance, exposing an + * interface for requests to that instance. + * + * @alias module:rpc.Server + * @memberof module:rpc + * + * @param {string} serverURL Soroban-RPC Server URL (ex. `http://localhost:8000/soroban/rpc`). + * @param {module:rpc.Server.Options} [opts] Options object + * @param {boolean} [opts.allowHttp] Allows connecting to insecure http servers + * (default: `false`). This must be set to false in production deployments! + * You can also use {@link Config} class to set this globally. + * @param {Record} [opts.headers] Allows setting custom headers + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods | API reference docs} + */ +export declare class RpcServer { + readonly serverURL: URI; + constructor(serverURL: string, opts?: RpcServer.Options); + /** + * Fetch a minimal set of current info about a Stellar account. + * + * Needed to get the current sequence number for the account so you can build + * a successful transaction with {@link TransactionBuilder}. + * + * @param {string} address The public address of the account to load. + * @returns {Promise} A promise which resolves to the {@link Account} + * object with a populated sequence number + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs} + * + * @example + * const accountId = "GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4"; + * server.getAccount(accountId).then((account) => { + * console.log("sequence:", account.sequence); + * }); + */ + getAccount(address: string): Promise; + /** + * General node health check. + * + * @returns {Promise} A promise which resolves to the + * {@link Api.GetHealthResponse} object with the status of the + * server (e.g. "healthy"). + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getHealth | getLedgerEntries docs} + * + * @example + * server.getHealth().then((health) => { + * console.log("status:", health.status); + * }); + */ + getHealth(): Promise; + /** + * Reads the current value of contract data ledger entries directly. + * + * Allows you to directly inspect the current state of a contract. This is a + * backup way to access your contract data which may not be available via + * events or {@link module:rpc.Server#simulateTransaction}. + * + * @param {string|Address|Contract} contract The contract ID containing the + * data to load as a strkey (`C...` form), a {@link Contract}, or an + * {@link Address} instance + * @param {xdr.ScVal} key The key of the contract data to load + * @param {module:rpc.Durability} [durability=Durability.Persistent] The "durability + * keyspace" that this ledger key belongs to, which is either 'temporary' + * or 'persistent' (the default), see {@link module:rpc.Durability}. + * @returns {Promise} The current data value + * + * @warning If the data entry in question is a 'temporary' entry, it's + * entirely possible that it has expired out of existence. + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs} + * + * @example + * const contractId = "CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5"; + * const key = xdr.ScVal.scvSymbol("counter"); + * server.getContractData(contractId, key, Durability.Temporary).then(data => { + * console.log("value:", data.val); + * console.log("liveUntilLedgerSeq:", data.liveUntilLedgerSeq); + * console.log("lastModified:", data.lastModifiedLedgerSeq); + * console.log("latestLedger:", data.latestLedger); + * }); + */ + getContractData(contract: string | Address | Contract, key: xdr.ScVal, durability?: Durability): Promise; + /** + * Retrieves the WASM bytecode for a given contract. + * + * This method allows you to fetch the WASM bytecode associated with a contract + * deployed on the Soroban network. The WASM bytecode represents the executable + * code of the contract. + * + * @param {string} contractId The contract ID containing the WASM bytecode to retrieve + * @returns {Promise} A Buffer containing the WASM bytecode + * @throws {Error} If the contract or its associated WASM bytecode cannot be + * found on the network. + * + * @example + * const contractId = "CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5"; + * server.getContractWasmByContractId(contractId).then(wasmBuffer => { + * console.log("WASM bytecode length:", wasmBuffer.length); + * // ... do something with the WASM bytecode ... + * }).catch(err => { + * console.error("Error fetching WASM bytecode:", err); + * }); + */ + getContractWasmByContractId(contractId: string): Promise; + /** + * Retrieves the WASM bytecode for a given contract hash. + * + * This method allows you to fetch the WASM bytecode associated with a contract + * deployed on the Soroban network using the contract's WASM hash. The WASM bytecode + * represents the executable code of the contract. + * + * @param {Buffer} wasmHash The WASM hash of the contract + * @returns {Promise} A Buffer containing the WASM bytecode + * @throws {Error} If the contract or its associated WASM bytecode cannot be + * found on the network. + * + * @example + * const wasmHash = Buffer.from("..."); + * server.getContractWasmByHash(wasmHash).then(wasmBuffer => { + * console.log("WASM bytecode length:", wasmBuffer.length); + * // ... do something with the WASM bytecode ... + * }).catch(err => { + * console.error("Error fetching WASM bytecode:", err); + * }); + */ + getContractWasmByHash(wasmHash: Buffer | string, format?: undefined | "hex" | "base64"): Promise; + /** + * Reads the current value of arbitrary ledger entries directly. + * + * Allows you to directly inspect the current state of contracts, contract's + * code, accounts, or any other ledger entries. + * + * To fetch a contract's WASM byte-code, built the appropriate + * {@link xdr.LedgerKeyContractCode} ledger entry key (or see + * {@link Contract.getFootprint}). + * + * @param {xdr.ScVal[]} keys One or more ledger entry keys to load + * @returns {Promise} The current on-chain + * values for the given ledger keys + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs} + * @see RpcServer._getLedgerEntries + * @example + * const contractId = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM"; + * const key = xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({ + * contractId: StrKey.decodeContract(contractId), + * key: xdr.ScVal.scvSymbol("counter"), + * })); + * + * server.getLedgerEntries([key]).then(response => { + * const ledgerData = response.entries[0]; + * console.log("key:", ledgerData.key); + * console.log("value:", ledgerData.val); + * console.log("liveUntilLedgerSeq:", ledgerData.liveUntilLedgerSeq); + * console.log("lastModified:", ledgerData.lastModifiedLedgerSeq); + * console.log("latestLedger:", response.latestLedger); + * }); + */ + getLedgerEntries(...keys: xdr.LedgerKey[]): Promise; + _getLedgerEntries(...keys: xdr.LedgerKey[]): Promise; + /** + * Poll for a particular transaction with certain parameters. + * + * After submitting a transaction, clients can use this to poll for + * transaction completion and return a definitive state of success or failure. + * + * @param {string} hash the transaction you're polling for + * @param {number} [opts.attempts] (optional) the number of attempts to make + * before returning the last-seen status. By default or on invalid inputs, + * try 5 times. + * @param {SleepStrategy} [opts.sleepStrategy] (optional) the amount of time + * to wait for between each attempt. By default, sleep for 1 second between + * each attempt. + * + * @return {Promise} the response after a "found" + * response (which may be success or failure) or the last response obtained + * after polling the maximum number of specified attempts. + * + * @example + * const h = "c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a"; + * const txStatus = await server.pollTransaction(h, { + * attempts: 100, // I'm a maniac + * sleepStrategy: rpc.LinearSleepStrategy + * }); // this will take 5,050 seconds to complete + */ + pollTransaction(hash: string, opts?: RpcServer.PollingOptions): Promise; + /** + * Fetch the details of a submitted transaction. + * + * After submitting a transaction, clients should poll this to tell when the + * transaction has completed. + * + * @param {string} hash Hex-encoded hash of the transaction to check + * @returns {Promise} The status, result, and + * other details about the transaction + * + * @see + * {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransaction | getTransaction docs} + * + * @example + * const transactionHash = "c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a"; + * server.getTransaction(transactionHash).then((tx) => { + * console.log("status:", tx.status); + * console.log("envelopeXdr:", tx.envelopeXdr); + * console.log("resultMetaXdr:", tx.resultMetaXdr); + * console.log("resultXdr:", tx.resultXdr); + * }); + */ + getTransaction(hash: string): Promise; + _getTransaction(hash: string): Promise; + /** + * Fetch transactions starting from a given start ledger or a cursor. The end ledger is the latest ledger + * in that RPC instance. + * + * @param {Api.GetTransactionsRequest} request - The request parameters. + * @returns {Promise} - A promise that resolves to the transactions response. + * + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransactions + * @example + * server.getTransactions({ + * startLedger: 10000, + * limit: 10, + * }).then((response) => { + * console.log("Transactions:", response.transactions); + * console.log("Latest Ledger:", response.latestLedger); + * console.log("Cursor:", response.cursor); + * }); + */ + getTransactions(request: Api.GetTransactionsRequest): Promise; + private _getTransactions; + /** + * Fetch all events that match a given set of filters. + * + * The given filters (see {@link module:rpc.Api.EventFilter | Api.EventFilter} + * for detailed fields) are combined only in a logical OR fashion, and all of + * the fields in each filter are optional. + * + * To page through events, use the `pagingToken` field on the relevant + * {@link Api.EventResponse} object to set the `cursor` parameter. + * + * @param {module:rpc.Server.GetEventsRequest} request Event filters + * @returns {Promise} A paginatable set of the events + * matching the given event filters + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getEvents | getEvents docs} + * + * @example + * server.getEvents({ + * startLedger: 1000, + * endLedger: 2000, + * filters: [ + * { + * type: "contract", + * contractIds: [ "deadb33f..." ], + * topics: [[ "AAAABQAAAAh0cmFuc2Zlcg==", "AAAAAQB6Mcc=", "*" ]] + * }, { + * type: "system", + * contractIds: [ "...c4f3b4b3..." ], + * topics: [[ "*" ], [ "*", "AAAAAQB6Mcc=" ]] + * }, { + * contractIds: [ "...c4f3b4b3..." ], + * topics: [[ "AAAABQAAAAh0cmFuc2Zlcg==" ]] + * }, { + * type: "diagnostic", + * topics: [[ "AAAAAQB6Mcc=" ]] + * } + * ], + * limit: 10, + * }); + */ + getEvents(request: RpcServer.GetEventsRequest): Promise; + _getEvents(request: RpcServer.GetEventsRequest): Promise; + /** + * Fetch metadata about the network this Soroban RPC server is connected to. + * + * @returns {Promise} Metadata about the current + * network this RPC server is connected to + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getNetwork | getNetwork docs} + * + * @example + * server.getNetwork().then((network) => { + * console.log("friendbotUrl:", network.friendbotUrl); + * console.log("passphrase:", network.passphrase); + * console.log("protocolVersion:", network.protocolVersion); + * }); + */ + getNetwork(): Promise; + /** + * Fetch the latest ledger meta info from network which this Soroban RPC + * server is connected to. + * + * @returns {Promise} metadata about the + * latest ledger on the network that this RPC server is connected to + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLatestLedger | getLatestLedger docs} + * + * @example + * server.getLatestLedger().then((response) => { + * console.log("hash:", response.id); + * console.log("sequence:", response.sequence); + * console.log("protocolVersion:", response.protocolVersion); + * }); + */ + getLatestLedger(): Promise; + /** + * Submit a trial contract invocation to get back return values, expected + * ledger footprint, expected authorizations, and expected costs. + * + * @param {Transaction | FeeBumpTransaction} tx the transaction to + * simulate, which should include exactly one operation (one of + * {@link xdr.InvokeHostFunctionOp}, {@link xdr.ExtendFootprintTTLOp}, or + * {@link xdr.RestoreFootprintOp}). Any provided footprint or auth + * information will be ignored. + * @returns {Promise} An object with the + * cost, footprint, result/auth requirements (if applicable), and error of + * the transaction + * + * @see {@link https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/operations-and-transactions | transaction docs} + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction | simulateTransaction docs} + * @see module:rpc.Server#prepareTransaction + * @see module:rpc.assembleTransaction + * + * @example + * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE'; + * const contract = new StellarSdk.Contract(contractId); + * + * // Right now, this is just the default fee for this example. + * const fee = StellarSdk.BASE_FEE; + * const transaction = new StellarSdk.TransactionBuilder(account, { fee }) + * // Uncomment the following line to build transactions for the live network. Be + * // sure to also change the horizon hostname. + * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC) + * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET) + * .setTimeout(30) // valid for the next 30s + * // Add an operation to call increment() on the contract + * .addOperation(contract.call("increment")) + * .build(); + * + * server.simulateTransaction(transaction).then((sim) => { + * console.log("cost:", sim.cost); + * console.log("result:", sim.result); + * console.log("error:", sim.error); + * console.log("latestLedger:", sim.latestLedger); + * }); + */ + simulateTransaction(tx: Transaction | FeeBumpTransaction, addlResources?: RpcServer.ResourceLeeway): Promise; + _simulateTransaction(transaction: Transaction | FeeBumpTransaction, addlResources?: RpcServer.ResourceLeeway): Promise; + /** + * Submit a trial contract invocation, first run a simulation of the contract + * invocation as defined on the incoming transaction, and apply the results to + * a new copy of the transaction which is then returned. Setting the ledger + * footprint and authorization, so the resulting transaction is ready for + * signing & sending. + * + * The returned transaction will also have an updated fee that is the sum of + * fee set on incoming transaction with the contract resource fees estimated + * from simulation. It is advisable to check the fee on returned transaction + * and validate or take appropriate measures for interaction with user to + * confirm it is acceptable. + * + * You can call the {@link module:rpc.Server#simulateTransaction} method + * directly first if you want to inspect estimated fees for a given + * transaction in detail first, then re-assemble it manually or via + * {@link module:rpc.assembleTransaction}. + * + * @param {Transaction | FeeBumpTransaction} tx the transaction to + * prepare. It should include exactly one operation, which must be one of + * {@link xdr.InvokeHostFunctionOp}, {@link xdr.ExtendFootprintTTLOp}, + * or {@link xdr.RestoreFootprintOp}. + * + * Any provided footprint will be overwritten. However, if your operation + * has existing auth entries, they will be preferred over ALL auth entries + * from the simulation. In other words, if you include auth entries, you + * don't care about the auth returned from the simulation. Other fields + * (footprint, etc.) will be filled as normal. + * @returns {Promise} A copy of the + * transaction with the expected authorizations (in the case of + * invocation), resources, and ledger footprints added. The transaction fee + * will also automatically be padded with the contract's minimum resource + * fees discovered from the simulation. + * @throws {jsonrpc.Error|Error|Api.SimulateTransactionErrorResponse} + * If simulation fails + * + * @see module:rpc.assembleTransaction + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction | simulateTransaction docs} + * + * @example + * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE'; + * const contract = new StellarSdk.Contract(contractId); + * + * // Right now, this is just the default fee for this example. + * const fee = StellarSdk.BASE_FEE; + * const transaction = new StellarSdk.TransactionBuilder(account, { fee }) + * // Uncomment the following line to build transactions for the live network. Be + * // sure to also change the horizon hostname. + * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC) + * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET) + * .setTimeout(30) // valid for the next 30s + * // Add an operation to call increment() on the contract + * .addOperation(contract.call("increment")) + * .build(); + * + * const preparedTransaction = await server.prepareTransaction(transaction); + * + * // Sign this transaction with the secret key + * // NOTE: signing is transaction is network specific. Test network transactions + * // won't work in the public network. To switch networks, use the Network object + * // as explained above (look for StellarSdk.Network). + * const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey); + * preparedTransaction.sign(sourceKeypair); + * + * server.sendTransaction(transaction).then(result => { + * console.log("hash:", result.hash); + * console.log("status:", result.status); + * console.log("errorResultXdr:", result.errorResultXdr); + * }); + */ + prepareTransaction(tx: Transaction | FeeBumpTransaction): Promise, import("@stellar/stellar-base").Operation[]>>; + /** + * Submit a real transaction to the Stellar network. + * + * Unlike Horizon, Soroban RPC does not wait for transaction completion. It + * simply validates the transaction and enqueues it. Clients should call + * {@link module:rpc.Server#getTransaction} to learn about transaction + * success/failure. + * + * @param {Transaction | FeeBumpTransaction} transaction to submit + * @returns {Promise} the + * transaction id, status, and any error if available + * + * @see {@link https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/operations-and-transactions | transaction docs} + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/sendTransaction | sendTransaction docs} + * + * @example + * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE'; + * const contract = new StellarSdk.Contract(contractId); + * + * // Right now, this is just the default fee for this example. + * const fee = StellarSdk.BASE_FEE; + * const transaction = new StellarSdk.TransactionBuilder(account, { fee }) + * // Uncomment the following line to build transactions for the live network. Be + * // sure to also change the horizon hostname. + * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC) + * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET) + * .setTimeout(30) // valid for the next 30s + * // Add an operation to call increment() on the contract + * .addOperation(contract.call("increment")) + * .build(); + * + * // Sign this transaction with the secret key + * // NOTE: signing is transaction is network specific. Test network transactions + * // won't work in the public network. To switch networks, use the Network object + * // as explained above (look for StellarSdk.Network). + * const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey); + * transaction.sign(sourceKeypair); + * + * server.sendTransaction(transaction).then((result) => { + * console.log("hash:", result.hash); + * console.log("status:", result.status); + * console.log("errorResultXdr:", result.errorResultXdr); + * }); + */ + sendTransaction(transaction: Transaction | FeeBumpTransaction): Promise; + _sendTransaction(transaction: Transaction | FeeBumpTransaction): Promise; + /** + * Fund a new account using the network's Friendbot faucet, if any. + * + * @param {string | Account} address The address or account instance that we + * want to create and fund with Friendbot + * @param {string} [friendbotUrl] Optionally, an explicit address for + * friendbot (by default: this calls the Soroban RPC + * {@link module:rpc.Server#getNetwork | getNetwork} method to try to + * discover this network's Friendbot url). + * @returns {Promise} An {@link Account} object for the created + * account, or the existing account if it's already funded with the + * populated sequence number (note that the account will not be "topped + * off" if it already exists) + * @throws If Friendbot is not configured on this network or request failure + * + * @see {@link https://developers.stellar.org/docs/learn/networks#friendbot | Friendbot docs} + * @see {@link module:Friendbot.Api.Response} + * + * @example + * server + * .requestAirdrop("GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4") + * .then((accountCreated) => { + * console.log("accountCreated:", accountCreated); + * }).catch((error) => { + * console.error("error:", error); + * }); + */ + requestAirdrop(address: string | Pick, friendbotUrl?: string): Promise; + /** + * Provides an analysis of the recent fee stats for regular and smart + * contract operations. + * + * @returns {Promise} the fee stats + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getFeeStats + */ + getFeeStats(): Promise; + /** + * Provides information about the current version details of the Soroban RPC and captive-core + * + * @returns {Promise} the version info + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getVersionInfo + */ + getVersionInfo(): Promise; + /** + * Returns a contract's balance of a particular SAC asset, if any. + * + * This is a convenience wrapper around {@link Server.getLedgerEntries}. + * + * @param {string} contractId the contract ID (string `C...`) whose + * balance of `sac` you want to know + * @param {Asset} sac the built-in SAC token (e.g. `USDC:GABC...`) that + * you are querying from the given `contract`. + * @param {string} [networkPassphrase] optionally, the network passphrase to + * which this token applies. If omitted, a request about network + * information will be made (see {@link getNetwork}), since contract IDs + * for assets are specific to a network. You can refer to {@link Networks} + * for a list of built-in passphrases, e.g., `Networks.TESTNET`. + * + * @returns {Promise}, which will contain the balance + * entry details if and only if the request returned a valid balance ledger + * entry. If it doesn't, the `balanceEntry` field will not exist. + * + * @throws {TypeError} If `contractId` is not a valid contract strkey (C...). + * + * @see getLedgerEntries + * @see https://developers.stellar.org/docs/tokens/stellar-asset-contract + * + * @example + * // assume `contractId` is some contract with an XLM balance + * // assume server is an instantiated `Server` instance. + * const entry = (await server.getSACBalance( + * new Address(contractId), + * Asset.native(), + * Networks.PUBLIC + * )); + * + * // assumes BigInt support: + * console.log( + * entry.balanceEntry ? + * BigInt(entry.balanceEntry.amount) : + * "Contract has no XLM"); + */ + getSACBalance(contractId: string, sac: Asset, networkPassphrase?: string): Promise; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/server.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/server.js new file mode 100644 index 000000000..b7b367d32 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/server.js @@ -0,0 +1,896 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SUBMIT_TRANSACTION_TIMEOUT = exports.RpcServer = exports.LinearSleepStrategy = exports.Durability = exports.BasicSleepStrategy = void 0; +var _urijs = _interopRequireDefault(require("urijs")); +var _stellarBase = require("@stellar/stellar-base"); +var _axios = _interopRequireDefault(require("./axios")); +var jsonrpc = _interopRequireWildcard(require("./jsonrpc")); +var _api = require("./api"); +var _transaction = require("./transaction"); +var _parsers = require("./parsers"); +var _utils = require("../utils"); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var SUBMIT_TRANSACTION_TIMEOUT = exports.SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000; +var Durability = exports.Durability = function (Durability) { + Durability["Temporary"] = "temporary"; + Durability["Persistent"] = "persistent"; + return Durability; +}({}); +var DEFAULT_GET_TRANSACTION_TIMEOUT = 30; +var BasicSleepStrategy = exports.BasicSleepStrategy = function BasicSleepStrategy(_iter) { + return 1000; +}; +var LinearSleepStrategy = exports.LinearSleepStrategy = function LinearSleepStrategy(iter) { + return 1000 * iter; +}; +function findCreatedAccountSequenceInTransactionMeta(meta) { + var _operations$flatMap$f; + var operations = []; + switch (meta.switch()) { + case 0: + operations = meta.operations(); + break; + case 1: + case 2: + case 3: + operations = meta.value().operations(); + break; + default: + throw new Error('Unexpected transaction meta switch value'); + } + var sequenceNumber = (_operations$flatMap$f = operations.flatMap(function (op) { + return op.changes(); + }).find(function (c) { + return c.switch() === _stellarBase.xdr.LedgerEntryChangeType.ledgerEntryCreated() && c.created().data().switch() === _stellarBase.xdr.LedgerEntryType.account(); + })) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.created()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.data()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.account()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.seqNum()) === null || _operations$flatMap$f === void 0 ? void 0 : _operations$flatMap$f.toString(); + if (sequenceNumber) { + return sequenceNumber; + } + throw new Error('No account created in transaction'); +} +var RpcServer = exports.RpcServer = function () { + function RpcServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, RpcServer); + this.serverURL = (0, _urijs.default)(serverURL); + if (opts.headers && Object.keys(opts.headers).length !== 0) { + _axios.default.interceptors.request.use(function (config) { + config.headers = Object.assign(config.headers, opts.headers); + return config; + }); + } + if (this.serverURL.protocol() !== 'https' && !opts.allowHttp) { + throw new Error("Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set"); + } + } + return _createClass(RpcServer, [{ + key: "getAccount", + value: (function () { + var _getAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(address) { + var ledgerKey, resp, accountEntry; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + ledgerKey = _stellarBase.xdr.LedgerKey.account(new _stellarBase.xdr.LedgerKeyAccount({ + accountId: _stellarBase.Keypair.fromPublicKey(address).xdrPublicKey() + })); + _context.next = 3; + return this.getLedgerEntries(ledgerKey); + case 3: + resp = _context.sent; + if (!(resp.entries.length === 0)) { + _context.next = 6; + break; + } + return _context.abrupt("return", Promise.reject({ + code: 404, + message: "Account not found: ".concat(address) + })); + case 6: + accountEntry = resp.entries[0].val.account(); + return _context.abrupt("return", new _stellarBase.Account(address, accountEntry.seqNum().toString())); + case 8: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function getAccount(_x) { + return _getAccount.apply(this, arguments); + } + return getAccount; + }()) + }, { + key: "getHealth", + value: (function () { + var _getHealth = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getHealth')); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function getHealth() { + return _getHealth.apply(this, arguments); + } + return getHealth; + }()) + }, { + key: "getContractData", + value: (function () { + var _getContractData = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(contract, key) { + var durability, + scAddress, + xdrDurability, + contractKey, + _args3 = arguments; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + durability = _args3.length > 2 && _args3[2] !== undefined ? _args3[2] : Durability.Persistent; + if (!(typeof contract === 'string')) { + _context3.next = 5; + break; + } + scAddress = new _stellarBase.Contract(contract).address().toScAddress(); + _context3.next = 14; + break; + case 5: + if (!(contract instanceof _stellarBase.Address)) { + _context3.next = 9; + break; + } + scAddress = contract.toScAddress(); + _context3.next = 14; + break; + case 9: + if (!(contract instanceof _stellarBase.Contract)) { + _context3.next = 13; + break; + } + scAddress = contract.address().toScAddress(); + _context3.next = 14; + break; + case 13: + throw new TypeError("unknown contract type: ".concat(contract)); + case 14: + _context3.t0 = durability; + _context3.next = _context3.t0 === Durability.Temporary ? 17 : _context3.t0 === Durability.Persistent ? 19 : 21; + break; + case 17: + xdrDurability = _stellarBase.xdr.ContractDataDurability.temporary(); + return _context3.abrupt("break", 22); + case 19: + xdrDurability = _stellarBase.xdr.ContractDataDurability.persistent(); + return _context3.abrupt("break", 22); + case 21: + throw new TypeError("invalid durability: ".concat(durability)); + case 22: + contractKey = _stellarBase.xdr.LedgerKey.contractData(new _stellarBase.xdr.LedgerKeyContractData({ + key: key, + contract: scAddress, + durability: xdrDurability + })); + return _context3.abrupt("return", this.getLedgerEntries(contractKey).then(function (r) { + if (r.entries.length === 0) { + return Promise.reject({ + code: 404, + message: "Contract data not found. Contract: ".concat(_stellarBase.Address.fromScAddress(scAddress).toString(), ", Key: ").concat(key.toXDR('base64'), ", Durability: ").concat(durability) + }); + } + return r.entries[0]; + })); + case 24: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function getContractData(_x2, _x3) { + return _getContractData.apply(this, arguments); + } + return getContractData; + }()) + }, { + key: "getContractWasmByContractId", + value: (function () { + var _getContractWasmByContractId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(contractId) { + var _response$entries$; + var contractLedgerKey, response, wasmHash; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + contractLedgerKey = new _stellarBase.Contract(contractId).getFootprint(); + _context4.next = 3; + return this.getLedgerEntries(contractLedgerKey); + case 3: + response = _context4.sent; + if (!(!response.entries.length || !((_response$entries$ = response.entries[0]) !== null && _response$entries$ !== void 0 && _response$entries$.val))) { + _context4.next = 6; + break; + } + return _context4.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract hash from server" + })); + case 6: + wasmHash = response.entries[0].val.contractData().val().instance().executable().wasmHash(); + return _context4.abrupt("return", this.getContractWasmByHash(wasmHash)); + case 8: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function getContractWasmByContractId(_x4) { + return _getContractWasmByContractId.apply(this, arguments); + } + return getContractWasmByContractId; + }()) + }, { + key: "getContractWasmByHash", + value: (function () { + var _getContractWasmByHash = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(wasmHash) { + var _responseWasm$entries; + var format, + wasmHashBuffer, + ledgerKeyWasmHash, + responseWasm, + wasmBuffer, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + format = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : undefined; + wasmHashBuffer = typeof wasmHash === "string" ? Buffer.from(wasmHash, format) : wasmHash; + ledgerKeyWasmHash = _stellarBase.xdr.LedgerKey.contractCode(new _stellarBase.xdr.LedgerKeyContractCode({ + hash: wasmHashBuffer + })); + _context5.next = 5; + return this.getLedgerEntries(ledgerKeyWasmHash); + case 5: + responseWasm = _context5.sent; + if (!(!responseWasm.entries.length || !((_responseWasm$entries = responseWasm.entries[0]) !== null && _responseWasm$entries !== void 0 && _responseWasm$entries.val))) { + _context5.next = 8; + break; + } + return _context5.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract wasm from server" + })); + case 8: + wasmBuffer = responseWasm.entries[0].val.contractCode().code(); + return _context5.abrupt("return", wasmBuffer); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function getContractWasmByHash(_x5) { + return _getContractWasmByHash.apply(this, arguments); + } + return getContractWasmByHash; + }()) + }, { + key: "getLedgerEntries", + value: (function () { + var _getLedgerEntries2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6() { + var _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + return _context6.abrupt("return", this._getLedgerEntries.apply(this, _args6).then(_parsers.parseRawLedgerEntries)); + case 1: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function getLedgerEntries() { + return _getLedgerEntries2.apply(this, arguments); + } + return getLedgerEntries; + }()) + }, { + key: "_getLedgerEntries", + value: function () { + var _getLedgerEntries3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee7() { + var _len, + keys, + _key, + _args7 = arguments; + return _regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + for (_len = _args7.length, keys = new Array(_len), _key = 0; _key < _len; _key++) { + keys[_key] = _args7[_key]; + } + return _context7.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getLedgerEntries', { + keys: keys.map(function (k) { + return k.toXDR('base64'); + }) + })); + case 2: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function _getLedgerEntries() { + return _getLedgerEntries3.apply(this, arguments); + } + return _getLedgerEntries; + }() + }, { + key: "pollTransaction", + value: (function () { + var _pollTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee8(hash, opts) { + var _opts$attempts, _opts$attempts2; + var maxAttempts, foundInfo, attempt, _opts$sleepStrategy; + return _regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + maxAttempts = ((_opts$attempts = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts !== void 0 ? _opts$attempts : 0) < 1 ? DEFAULT_GET_TRANSACTION_TIMEOUT : (_opts$attempts2 = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts2 !== void 0 ? _opts$attempts2 : DEFAULT_GET_TRANSACTION_TIMEOUT; + attempt = 1; + case 2: + if (!(attempt < maxAttempts)) { + _context8.next = 13; + break; + } + _context8.next = 5; + return this.getTransaction(hash); + case 5: + foundInfo = _context8.sent; + if (!(foundInfo.status !== _api.Api.GetTransactionStatus.NOT_FOUND)) { + _context8.next = 8; + break; + } + return _context8.abrupt("return", foundInfo); + case 8: + _context8.next = 10; + return _utils.Utils.sleep(((_opts$sleepStrategy = opts === null || opts === void 0 ? void 0 : opts.sleepStrategy) !== null && _opts$sleepStrategy !== void 0 ? _opts$sleepStrategy : BasicSleepStrategy)(attempt)); + case 10: + attempt++; + _context8.next = 2; + break; + case 13: + return _context8.abrupt("return", foundInfo); + case 14: + case "end": + return _context8.stop(); + } + }, _callee8, this); + })); + function pollTransaction(_x6, _x7) { + return _pollTransaction.apply(this, arguments); + } + return pollTransaction; + }()) + }, { + key: "getTransaction", + value: (function () { + var _getTransaction2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee9(hash) { + return _regeneratorRuntime().wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + return _context9.abrupt("return", this._getTransaction(hash).then(function (raw) { + var foundInfo = {}; + if (raw.status !== _api.Api.GetTransactionStatus.NOT_FOUND) { + Object.assign(foundInfo, (0, _parsers.parseTransactionInfo)(raw)); + } + var result = _objectSpread({ + status: raw.status, + txHash: hash, + latestLedger: raw.latestLedger, + latestLedgerCloseTime: raw.latestLedgerCloseTime, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTime: raw.oldestLedgerCloseTime + }, foundInfo); + return result; + })); + case 1: + case "end": + return _context9.stop(); + } + }, _callee9, this); + })); + function getTransaction(_x8) { + return _getTransaction2.apply(this, arguments); + } + return getTransaction; + }()) + }, { + key: "_getTransaction", + value: function () { + var _getTransaction3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee10(hash) { + return _regeneratorRuntime().wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + return _context10.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getTransaction', { + hash: hash + })); + case 1: + case "end": + return _context10.stop(); + } + }, _callee10, this); + })); + function _getTransaction(_x9) { + return _getTransaction3.apply(this, arguments); + } + return _getTransaction; + }() + }, { + key: "getTransactions", + value: (function () { + var _getTransactions2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee11(request) { + return _regeneratorRuntime().wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + return _context11.abrupt("return", this._getTransactions(request).then(function (raw) { + var result = { + transactions: raw.transactions.map(_parsers.parseRawTransactions), + latestLedger: raw.latestLedger, + latestLedgerCloseTimestamp: raw.latestLedgerCloseTimestamp, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTimestamp: raw.oldestLedgerCloseTimestamp, + cursor: raw.cursor + }; + return result; + })); + case 1: + case "end": + return _context11.stop(); + } + }, _callee11, this); + })); + function getTransactions(_x10) { + return _getTransactions2.apply(this, arguments); + } + return getTransactions; + }()) + }, { + key: "_getTransactions", + value: function () { + var _getTransactions3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee12(request) { + return _regeneratorRuntime().wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + return _context12.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getTransactions', request)); + case 1: + case "end": + return _context12.stop(); + } + }, _callee12, this); + })); + function _getTransactions(_x11) { + return _getTransactions3.apply(this, arguments); + } + return _getTransactions; + }() + }, { + key: "getEvents", + value: (function () { + var _getEvents2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee13(request) { + return _regeneratorRuntime().wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + return _context13.abrupt("return", this._getEvents(request).then(_parsers.parseRawEvents)); + case 1: + case "end": + return _context13.stop(); + } + }, _callee13, this); + })); + function getEvents(_x12) { + return _getEvents2.apply(this, arguments); + } + return getEvents; + }()) + }, { + key: "_getEvents", + value: function () { + var _getEvents3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee14(request) { + var _request$filters; + return _regeneratorRuntime().wrap(function _callee14$(_context14) { + while (1) switch (_context14.prev = _context14.next) { + case 0: + return _context14.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getEvents', _objectSpread(_objectSpread({ + filters: (_request$filters = request.filters) !== null && _request$filters !== void 0 ? _request$filters : [], + pagination: _objectSpread(_objectSpread({}, request.cursor && { + cursor: request.cursor + }), request.limit && { + limit: request.limit + }) + }, request.startLedger && { + startLedger: request.startLedger + }), request.endLedger && { + endLedger: request.endLedger + }))); + case 1: + case "end": + return _context14.stop(); + } + }, _callee14, this); + })); + function _getEvents(_x13) { + return _getEvents3.apply(this, arguments); + } + return _getEvents; + }() + }, { + key: "getNetwork", + value: (function () { + var _getNetwork = _asyncToGenerator(_regeneratorRuntime().mark(function _callee15() { + return _regeneratorRuntime().wrap(function _callee15$(_context15) { + while (1) switch (_context15.prev = _context15.next) { + case 0: + return _context15.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getNetwork')); + case 1: + case "end": + return _context15.stop(); + } + }, _callee15, this); + })); + function getNetwork() { + return _getNetwork.apply(this, arguments); + } + return getNetwork; + }()) + }, { + key: "getLatestLedger", + value: (function () { + var _getLatestLedger = _asyncToGenerator(_regeneratorRuntime().mark(function _callee16() { + return _regeneratorRuntime().wrap(function _callee16$(_context16) { + while (1) switch (_context16.prev = _context16.next) { + case 0: + return _context16.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getLatestLedger')); + case 1: + case "end": + return _context16.stop(); + } + }, _callee16, this); + })); + function getLatestLedger() { + return _getLatestLedger.apply(this, arguments); + } + return getLatestLedger; + }()) + }, { + key: "simulateTransaction", + value: (function () { + var _simulateTransaction2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee17(tx, addlResources) { + return _regeneratorRuntime().wrap(function _callee17$(_context17) { + while (1) switch (_context17.prev = _context17.next) { + case 0: + return _context17.abrupt("return", this._simulateTransaction(tx, addlResources).then(_parsers.parseRawSimulation)); + case 1: + case "end": + return _context17.stop(); + } + }, _callee17, this); + })); + function simulateTransaction(_x14, _x15) { + return _simulateTransaction2.apply(this, arguments); + } + return simulateTransaction; + }()) + }, { + key: "_simulateTransaction", + value: function () { + var _simulateTransaction3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee18(transaction, addlResources) { + return _regeneratorRuntime().wrap(function _callee18$(_context18) { + while (1) switch (_context18.prev = _context18.next) { + case 0: + return _context18.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'simulateTransaction', _objectSpread({ + transaction: transaction.toXDR() + }, addlResources !== undefined && { + resourceConfig: { + instructionLeeway: addlResources.cpuInstructions + } + }))); + case 1: + case "end": + return _context18.stop(); + } + }, _callee18, this); + })); + function _simulateTransaction(_x16, _x17) { + return _simulateTransaction3.apply(this, arguments); + } + return _simulateTransaction; + }() + }, { + key: "prepareTransaction", + value: (function () { + var _prepareTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee19(tx) { + var simResponse; + return _regeneratorRuntime().wrap(function _callee19$(_context19) { + while (1) switch (_context19.prev = _context19.next) { + case 0: + _context19.next = 2; + return this.simulateTransaction(tx); + case 2: + simResponse = _context19.sent; + if (!_api.Api.isSimulationError(simResponse)) { + _context19.next = 5; + break; + } + throw new Error(simResponse.error); + case 5: + return _context19.abrupt("return", (0, _transaction.assembleTransaction)(tx, simResponse).build()); + case 6: + case "end": + return _context19.stop(); + } + }, _callee19, this); + })); + function prepareTransaction(_x18) { + return _prepareTransaction.apply(this, arguments); + } + return prepareTransaction; + }()) + }, { + key: "sendTransaction", + value: (function () { + var _sendTransaction2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee20(transaction) { + return _regeneratorRuntime().wrap(function _callee20$(_context20) { + while (1) switch (_context20.prev = _context20.next) { + case 0: + return _context20.abrupt("return", this._sendTransaction(transaction).then(_parsers.parseRawSendTransaction)); + case 1: + case "end": + return _context20.stop(); + } + }, _callee20, this); + })); + function sendTransaction(_x19) { + return _sendTransaction2.apply(this, arguments); + } + return sendTransaction; + }()) + }, { + key: "_sendTransaction", + value: function () { + var _sendTransaction3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee21(transaction) { + return _regeneratorRuntime().wrap(function _callee21$(_context21) { + while (1) switch (_context21.prev = _context21.next) { + case 0: + return _context21.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'sendTransaction', { + transaction: transaction.toXDR() + })); + case 1: + case "end": + return _context21.stop(); + } + }, _callee21, this); + })); + function _sendTransaction(_x20) { + return _sendTransaction3.apply(this, arguments); + } + return _sendTransaction; + }() + }, { + key: "requestAirdrop", + value: (function () { + var _requestAirdrop = _asyncToGenerator(_regeneratorRuntime().mark(function _callee22(address, friendbotUrl) { + var account, response, meta, txMeta, sequence, _error$response, _error$response$detai; + return _regeneratorRuntime().wrap(function _callee22$(_context22) { + while (1) switch (_context22.prev = _context22.next) { + case 0: + account = typeof address === 'string' ? address : address.accountId(); + _context22.t0 = friendbotUrl; + if (_context22.t0) { + _context22.next = 6; + break; + } + _context22.next = 5; + return this.getNetwork(); + case 5: + _context22.t0 = _context22.sent.friendbotUrl; + case 6: + friendbotUrl = _context22.t0; + if (friendbotUrl) { + _context22.next = 9; + break; + } + throw new Error('No friendbot URL configured for current network'); + case 9: + _context22.prev = 9; + _context22.next = 12; + return _axios.default.post("".concat(friendbotUrl, "?addr=").concat(encodeURIComponent(account))); + case 12: + response = _context22.sent; + if (response.data.result_meta_xdr) { + _context22.next = 22; + break; + } + _context22.next = 16; + return this.getTransaction(response.data.hash); + case 16: + txMeta = _context22.sent; + if (!(txMeta.status !== _api.Api.GetTransactionStatus.SUCCESS)) { + _context22.next = 19; + break; + } + throw new Error("Funding account ".concat(address, " failed")); + case 19: + meta = txMeta.resultMetaXdr; + _context22.next = 23; + break; + case 22: + meta = _stellarBase.xdr.TransactionMeta.fromXDR(response.data.result_meta_xdr, 'base64'); + case 23: + sequence = findCreatedAccountSequenceInTransactionMeta(meta); + return _context22.abrupt("return", new _stellarBase.Account(account, sequence)); + case 27: + _context22.prev = 27; + _context22.t1 = _context22["catch"](9); + if (!(((_error$response = _context22.t1.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 400)) { + _context22.next = 32; + break; + } + if (!((_error$response$detai = _context22.t1.response.detail) !== null && _error$response$detai !== void 0 && _error$response$detai.includes('createAccountAlreadyExist'))) { + _context22.next = 32; + break; + } + return _context22.abrupt("return", this.getAccount(account)); + case 32: + throw _context22.t1; + case 33: + case "end": + return _context22.stop(); + } + }, _callee22, this, [[9, 27]]); + })); + function requestAirdrop(_x21, _x22) { + return _requestAirdrop.apply(this, arguments); + } + return requestAirdrop; + }()) + }, { + key: "getFeeStats", + value: (function () { + var _getFeeStats = _asyncToGenerator(_regeneratorRuntime().mark(function _callee23() { + return _regeneratorRuntime().wrap(function _callee23$(_context23) { + while (1) switch (_context23.prev = _context23.next) { + case 0: + return _context23.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getFeeStats')); + case 1: + case "end": + return _context23.stop(); + } + }, _callee23, this); + })); + function getFeeStats() { + return _getFeeStats.apply(this, arguments); + } + return getFeeStats; + }()) + }, { + key: "getVersionInfo", + value: (function () { + var _getVersionInfo = _asyncToGenerator(_regeneratorRuntime().mark(function _callee24() { + return _regeneratorRuntime().wrap(function _callee24$(_context24) { + while (1) switch (_context24.prev = _context24.next) { + case 0: + return _context24.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getVersionInfo')); + case 1: + case "end": + return _context24.stop(); + } + }, _callee24, this); + })); + function getVersionInfo() { + return _getVersionInfo.apply(this, arguments); + } + return getVersionInfo; + }()) + }, { + key: "getSACBalance", + value: (function () { + var _getSACBalance = _asyncToGenerator(_regeneratorRuntime().mark(function _callee25(contractId, sac, networkPassphrase) { + var passphrase, sacId, key, ledgerKey, response, _response$entries$2, lastModifiedLedgerSeq, liveUntilLedgerSeq, val, entry; + return _regeneratorRuntime().wrap(function _callee25$(_context25) { + while (1) switch (_context25.prev = _context25.next) { + case 0: + if (_stellarBase.StrKey.isValidContract(contractId)) { + _context25.next = 2; + break; + } + throw new TypeError("expected contract ID, got ".concat(contractId)); + case 2: + if (!(networkPassphrase !== null && networkPassphrase !== void 0)) { + _context25.next = 6; + break; + } + _context25.t0 = networkPassphrase; + _context25.next = 9; + break; + case 6: + _context25.next = 8; + return this.getNetwork().then(function (n) { + return n.passphrase; + }); + case 8: + _context25.t0 = _context25.sent; + case 9: + passphrase = _context25.t0; + sacId = sac.contractId(passphrase); + key = _stellarBase.xdr.ScVal.scvVec([(0, _stellarBase.nativeToScVal)("Balance", { + type: "symbol" + }), (0, _stellarBase.nativeToScVal)(contractId, { + type: "address" + })]); + ledgerKey = _stellarBase.xdr.LedgerKey.contractData(new _stellarBase.xdr.LedgerKeyContractData({ + contract: new _stellarBase.Address(sacId).toScAddress(), + durability: _stellarBase.xdr.ContractDataDurability.persistent(), + key: key + })); + _context25.next = 15; + return this.getLedgerEntries(ledgerKey); + case 15: + response = _context25.sent; + if (!(response.entries.length === 0)) { + _context25.next = 18; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 18: + _response$entries$2 = response.entries[0], lastModifiedLedgerSeq = _response$entries$2.lastModifiedLedgerSeq, liveUntilLedgerSeq = _response$entries$2.liveUntilLedgerSeq, val = _response$entries$2.val; + if (!(val.switch().value !== _stellarBase.xdr.LedgerEntryType.contractData().value)) { + _context25.next = 21; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 21: + entry = (0, _stellarBase.scValToNative)(val.contractData().val()); + return _context25.abrupt("return", { + latestLedger: response.latestLedger, + balanceEntry: { + liveUntilLedgerSeq: liveUntilLedgerSeq, + lastModifiedLedgerSeq: lastModifiedLedgerSeq, + amount: entry.amount.toString(), + authorized: entry.authorized, + clawback: entry.clawback + } + }); + case 23: + case "end": + return _context25.stop(); + } + }, _callee25, this); + })); + function getSACBalance(_x23, _x24, _x25) { + return _getSACBalance.apply(this, arguments); + } + return getSACBalance; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/transaction.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/transaction.d.ts new file mode 100644 index 000000000..c20ee31ad --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/transaction.d.ts @@ -0,0 +1,21 @@ +import { FeeBumpTransaction, Transaction, TransactionBuilder } from '@stellar/stellar-base'; +import { Api } from './api'; +/** + * Combines the given raw transaction alongside the simulation results. + * If the given transaction already has authorization entries in a host + * function invocation (see {@link Operation.invokeHostFunction}), **the + * simulation entries are ignored**. + * + * If the given transaction already has authorization entries in a host function + * invocation (see {@link Operation.invokeHostFunction}), **the simulation + * entries are ignored**. + * + * @param {Transaction|FeeBumpTransaction} raw the initial transaction, w/o simulation applied + * @param {Api.SimulateTransactionResponse|Api.RawSimulateTransactionResponse} simulation the Soroban RPC simulation result (see {@link module:rpc.Server#simulateTransaction}) + * @returns {TransactionBuilder} a new, cloned transaction with the proper auth and resource (fee, footprint) simulation data applied + * + * @memberof module:rpc + * @see {@link module:rpc.Server#simulateTransaction} + * @see {@link module:rpc.Server#prepareTransaction} + */ +export declare function assembleTransaction(raw: Transaction | FeeBumpTransaction, simulation: Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse): TransactionBuilder; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/transaction.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/transaction.js new file mode 100644 index 000000000..51bc94e7b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/transaction.js @@ -0,0 +1,53 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.assembleTransaction = assembleTransaction; +var _stellarBase = require("@stellar/stellar-base"); +var _api = require("./api"); +var _parsers = require("./parsers"); +function isSorobanTransaction(tx) { + if (tx.operations.length !== 1) { + return false; + } + switch (tx.operations[0].type) { + case 'invokeHostFunction': + case 'extendFootprintTtl': + case 'restoreFootprint': + return true; + default: + return false; + } +} +function assembleTransaction(raw, simulation) { + if ('innerTransaction' in raw) { + return assembleTransaction(raw.innerTransaction, simulation); + } + if (!isSorobanTransaction(raw)) { + throw new TypeError('unsupported transaction: must contain exactly one ' + 'invokeHostFunction, extendFootprintTtl, or restoreFootprint ' + 'operation'); + } + var success = (0, _parsers.parseRawSimulation)(simulation); + if (!_api.Api.isSimulationSuccess(success)) { + throw new Error("simulation incorrect: ".concat(JSON.stringify(success))); + } + var classicFeeNum = parseInt(raw.fee) || 0; + var minResourceFeeNum = parseInt(success.minResourceFee) || 0; + var txnBuilder = _stellarBase.TransactionBuilder.cloneFrom(raw, { + fee: (classicFeeNum + minResourceFeeNum).toString(), + sorobanData: success.transactionData.build(), + networkPassphrase: raw.networkPassphrase + }); + if (raw.operations[0].type === 'invokeHostFunction') { + var _invokeOp$auth; + txnBuilder.clearOperations(); + var invokeOp = raw.operations[0]; + var existingAuth = (_invokeOp$auth = invokeOp.auth) !== null && _invokeOp$auth !== void 0 ? _invokeOp$auth : []; + txnBuilder.addOperation(_stellarBase.Operation.invokeHostFunction({ + source: invokeOp.source, + func: invokeOp.func, + auth: existingAuth.length > 0 ? existingAuth : success.result.auth + })); + } + return txnBuilder; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/utils.d.ts new file mode 100644 index 000000000..e1cc19c4b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/utils.d.ts @@ -0,0 +1 @@ +export declare function hasOwnProperty(obj: X, prop: Y): obj is X & Record; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/utils.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/utils.js new file mode 100644 index 000000000..e2148d9bd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/rpc/utils.js @@ -0,0 +1,9 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.hasOwnProperty = hasOwnProperty; +function hasOwnProperty(obj, prop) { + return obj.hasOwnProperty(prop); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/stellartoml/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/stellartoml/index.d.ts new file mode 100644 index 000000000..9309f1dfd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/stellartoml/index.d.ts @@ -0,0 +1,132 @@ +import { Networks } from "@stellar/stellar-base"; +/** @module StellarToml */ +/** + * The maximum size of stellar.toml file, in bytes + * @constant {number} + * @default 102400 + */ +export declare const STELLAR_TOML_MAX_SIZE: number; +/** + * Resolver allows resolving `stellar.toml` files. + * @memberof module:StellarToml + * @hideconstructor + */ +export declare class Resolver { + /** + * Returns a parsed `stellar.toml` file for a given domain. + * @see {@link https://developers.stellar.org/docs/tokens/publishing-asset-info | Stellar.toml doc} + * + * @param {string} domain Domain to get stellar.toml file for + * @param {object} [opts] Options object + * @param {boolean} [opts.allowHttp=false] - Allow connecting to http servers. This must be set to false in production deployments! + * @param {number} [opts.timeout=0] - Allow a timeout. Allows user to avoid nasty lag due to TOML resolve issue. + * @returns {Promise} A `Promise` that resolves to the parsed stellar.toml object + * + * @example + * StellarSdk.StellarToml.Resolver.resolve('acme.com') + * .then(stellarToml => { + * // stellarToml in an object representing domain stellar.toml file. + * }) + * .catch(error => { + * // stellar.toml does not exist or is invalid + * }); + */ + static resolve(domain: string, opts?: Api.StellarTomlResolveOptions): Promise; +} +export declare namespace Api { + interface StellarTomlResolveOptions { + allowHttp?: boolean; + timeout?: number; + allowedRedirects?: number; + } + type Url = string; + type PublicKey = string; + type ISODateTime = string; + interface Documentation { + ORG_NAME?: string; + ORG_DBA?: string; + ORG_URL?: Url; + ORG_PHONE_NUMBER?: string; + ORG_LOGO?: Url; + ORG_LICENSE_NUMBER?: string; + ORG_LICENSING_AUTHORITY?: string; + ORG_LICENSE_TYPE?: string; + ORG_DESCRIPTION?: string; + ORG_PHYSICAL_ADDRESS?: string; + ORG_PHYSICAL_ADDRESS_ATTESTATION?: string; + ORG_PHONE_NUMBER_ATTESTATION?: string; + ORG_OFFICIAL_EMAIL?: string; + ORG_SUPPORT_EMAIL?: string; + ORG_KEYBASE?: string; + ORG_TWITTER?: string; + ORG_GITHUB?: string; + [key: string]: unknown; + } + interface Principal { + name: string; + email: string; + github?: string; + keybase?: string; + telegram?: string; + twitter?: string; + id_photo_hash?: string; + verification_photo_hash?: string; + [key: string]: unknown; + } + interface Currency { + code?: string; + code_template?: string; + issuer?: PublicKey; + display_decimals?: number; + status?: "live" | "dead" | "test" | "private"; + name?: string; + desc?: string; + conditions?: string; + fixed_number?: number; + max_number?: number; + is_asset_anchored?: boolean; + anchor_asset_type?: "fiat" | "crypto" | "nft" | "stock" | "bond" | "commodity" | "realestate" | "other"; + anchor_asset?: string; + attestation_of_reserve?: Url; + attestation_of_reserve_amount?: string; + attestation_of_reserve_last_audit?: ISODateTime; + is_unlimited?: boolean; + redemption_instructions?: string; + image?: Url; + regulated?: boolean; + collateral_addresses?: string[]; + collateral_address_messages?: string[]; + collateral_address_signatures?: string[]; + approval_server?: Url; + approval_criteria?: string; + [key: string]: unknown; + } + interface Validator { + ALIAS?: string; + DISPLAY_NAME?: string; + PUBLIC_KEY?: PublicKey; + HOST?: string; + HISTORY?: Url; + [key: string]: unknown; + } + interface StellarToml { + VERSION?: string; + ACCOUNTS?: PublicKey[]; + NETWORK_PASSPHRASE?: Networks; + TRANSFER_SERVER_SEP0024?: Url; + TRANSFER_SERVER?: Url; + KYC_SERVER?: Url; + WEB_AUTH_ENDPOINT?: Url; + FEDERATION_SERVER?: Url; + SIGNING_KEY?: PublicKey; + HORIZON_URL?: Url; + URI_REQUEST_SIGNING_KEY?: PublicKey; + DIRECT_PAYMENT_SERVER?: Url; + ANCHOR_QUOTE_SERVER?: Url; + DOCUMENTATION?: Documentation; + PRINCIPALS?: Principal[]; + CURRENCIES?: Currency[]; + VALIDATORS?: Validator[]; + [key: string]: unknown; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/stellartoml/index.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/stellartoml/index.js new file mode 100644 index 000000000..4b5aa2452 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/stellartoml/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.STELLAR_TOML_MAX_SIZE = exports.Resolver = exports.Api = void 0; +var _toml = _interopRequireDefault(require("toml")); +var _httpClient = require("../http-client"); +var _config = require("../config"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var STELLAR_TOML_MAX_SIZE = exports.STELLAR_TOML_MAX_SIZE = 100 * 1024; +var CancelToken = _httpClient.httpClient.CancelToken; +var Resolver = exports.Resolver = function () { + function Resolver() { + _classCallCheck(this, Resolver); + } + return _createClass(Resolver, null, [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(domain) { + var _opts$allowedRedirect; + var opts, + allowHttp, + timeout, + protocol, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 1 && _args[1] !== undefined ? _args[1] : {}; + allowHttp = typeof opts.allowHttp === "undefined" ? _config.Config.isAllowHttp() : opts.allowHttp; + timeout = typeof opts.timeout === "undefined" ? _config.Config.getTimeout() : opts.timeout; + protocol = allowHttp ? "http" : "https"; + return _context.abrupt("return", _httpClient.httpClient.get("".concat(protocol, "://").concat(domain, "/.well-known/stellar.toml"), { + maxRedirects: (_opts$allowedRedirect = opts.allowedRedirects) !== null && _opts$allowedRedirect !== void 0 ? _opts$allowedRedirect : 0, + maxContentLength: STELLAR_TOML_MAX_SIZE, + cancelToken: timeout ? new CancelToken(function (cancel) { + return setTimeout(function () { + return cancel("timeout of ".concat(timeout, "ms exceeded")); + }, timeout); + }) : undefined, + timeout: timeout + }).then(function (response) { + try { + var tomlObject = _toml.default.parse(response.data); + return Promise.resolve(tomlObject); + } catch (e) { + return Promise.reject(new Error("stellar.toml is invalid - Parsing error on line ".concat(e.line, ", column ").concat(e.column, ": ").concat(e.message))); + } + }).catch(function (err) { + if (err.message.match(/^maxContentLength size/)) { + throw new Error("stellar.toml file exceeds allowed size of ".concat(STELLAR_TOML_MAX_SIZE)); + } else { + throw err; + } + })); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + function resolve(_x) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }]); +}(); +var Api; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/utils.d.ts new file mode 100644 index 000000000..68cf6c0c2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/utils.d.ts @@ -0,0 +1,20 @@ +import { Transaction } from "@stellar/stellar-base"; +/** + * Miscellaneous utilities. + * + * @hideconstructor + */ +export declare class Utils { + /** + * Verifies if the current date is within the transaction's timebounds + * + * @param {Transaction} transaction The transaction whose timebounds will be validated. + * @param {number} [gracePeriod=0] An additional window of time that should be considered valid on either end of the transaction's time range. + * + * @returns {boolean} Returns true if the current time is within the transaction's [minTime, maxTime] range. + * + * @static + */ + static validateTimebounds(transaction: Transaction, gracePeriod?: number): boolean; + static sleep(ms: number): Promise; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/utils.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/utils.js new file mode 100644 index 000000000..3609eac76 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/utils.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Utils = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Utils = exports.Utils = function () { + function Utils() { + _classCallCheck(this, Utils); + } + return _createClass(Utils, null, [{ + key: "validateTimebounds", + value: function validateTimebounds(transaction) { + var gracePeriod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + if (!transaction.timeBounds) { + return false; + } + var now = Math.floor(Date.now() / 1000); + var _transaction$timeBoun = transaction.timeBounds, + minTime = _transaction$timeBoun.minTime, + maxTime = _transaction$timeBoun.maxTime; + return now >= Number.parseInt(minTime, 10) - gracePeriod && now <= Number.parseInt(maxTime, 10) + gracePeriod; + } + }, { + key: "sleep", + value: function sleep(ms) { + return new Promise(function (resolve) { + return setTimeout(resolve, ms); + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/errors.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/errors.d.ts new file mode 100644 index 000000000..0e59f59ee --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/errors.d.ts @@ -0,0 +1,13 @@ +/** + * InvalidChallengeError is raised when a challenge transaction does not meet + * the requirements for a SEP-10 challenge transaction (for example, a non-zero + * sequence number). + * @memberof module:WebAuth + * @category Errors + * + * @param {string} message Human-readable error message. + */ +export declare class InvalidChallengeError extends Error { + __proto__: InvalidChallengeError; + constructor(message: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/errors.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/errors.js new file mode 100644 index 000000000..2542a4449 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/errors.js @@ -0,0 +1,36 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.InvalidChallengeError = void 0; +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var InvalidChallengeError = exports.InvalidChallengeError = function (_Error) { + function InvalidChallengeError(message) { + var _this; + _classCallCheck(this, InvalidChallengeError); + var trueProto = (this instanceof InvalidChallengeError ? this.constructor : void 0).prototype; + _this = _callSuper(this, InvalidChallengeError, [message]); + _this.__proto__ = trueProto; + _this.constructor = InvalidChallengeError; + _this.name = "InvalidChallengeError"; + return _this; + } + _inherits(InvalidChallengeError, _Error); + return _createClass(InvalidChallengeError); +}(_wrapNativeSuper(Error)); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/index.d.ts new file mode 100644 index 000000000..e63282485 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/index.d.ts @@ -0,0 +1,2 @@ +export * from './utils'; +export { InvalidChallengeError } from './errors'; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/index.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/index.js new file mode 100644 index 000000000..a0ee4d041 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/index.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + InvalidChallengeError: true +}; +Object.defineProperty(exports, "InvalidChallengeError", { + enumerable: true, + get: function get() { + return _errors.InvalidChallengeError; + } +}); +var _utils = require("./utils"); +Object.keys(_utils).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _utils[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utils[key]; + } + }); +}); +var _errors = require("./errors"); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/utils.d.ts new file mode 100644 index 000000000..a725201df --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/utils.d.ts @@ -0,0 +1,307 @@ +/** + * Stellar Web Authentication + * @module WebAuth + * @see {@link https://stellar.org/protocol-10 | SEP-10 Specification} + */ +import { FeeBumpTransaction, Keypair, Transaction } from "@stellar/stellar-base"; +import { ServerApi } from "../horizon/server_api"; +/** + * Returns a valid {@link https://stellar.org/protocol/sep-10 | SEP-10} + * challenge transaction which you can use for Stellar Web Authentication. + * + * @param {Keypair} serverKeypair Keypair for server's signing account. + * @param {string} clientAccountID The stellar account (G...) or muxed account + * (M...) that the wallet wishes to authenticate with the server. + * @param {string} homeDomain The fully qualified domain name of the service + * requiring authentication + * @param {number} [timeout=300] Challenge duration (default to 5 minutes). + * @param {string} networkPassphrase The network passphrase. If you pass this + * argument then timeout is required. + * @param {string} webAuthDomain The fully qualified domain name of the service + * issuing the challenge. + * @param {string} [memo] The memo to attach to the challenge transaction. The + * memo must be of type `id`. If the `clientaccountID` is a muxed account, + * memos cannot be used. + * @param {string} [clientDomain] The fully qualified domain of the client + * requesting the challenge. Only necessary when the the 'client_domain' + * parameter is passed. + * @param {string} [clientSigningKey] The public key assigned to the SIGNING_KEY + * attribute specified on the stellar.toml hosted on the client domain. Only + * necessary when the 'client_domain' parameter is passed. + * @returns {string} A base64 encoded string of the raw TransactionEnvelope xdr + * struct for the transaction. + * @throws {Error} Will throw if `clientAccountID is a muxed account, and `memo` + * is present. + * @throws {Error} Will throw if `clientDomain` is provided, but + * `clientSigningKey` is missing + * + * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth} + * + * @example + * import { Keypair, Networks, WebAuth } from 'stellar-sdk' + * + * let serverKeyPair = Keypair.fromSecret("server-secret") + * let challenge = WebAuth.buildChallengeTx( + * serverKeyPair, + * "client-stellar-account-id", + * "stellar.org", + * 300, + * Networks.TESTNET); + */ +export declare function buildChallengeTx(serverKeypair: Keypair, clientAccountID: string, homeDomain: string, timeout: number | undefined, networkPassphrase: string, webAuthDomain: string, memo?: string | null, clientDomain?: string | null, clientSigningKey?: string | null): string; +/** + * A parsed and validated challenge transaction, and some of its constituent details. + * @memberof module:WebAuth + */ +export type ChallengeTxDetails = { + /** The challenge transaction. */ + tx: Transaction; + /** The Stellar public key (master key) used to sign the Manage Data operation. */ + clientAccountId: string; + /** The matched home domain. */ + matchedHomeDomain: string; + /** The memo attached to the transaction, which will be null if not present */ + memo?: string; +}; +/** + * Reads a SEP-10 challenge transaction and returns the decoded transaction and + * client account ID contained within. + * + * It also verifies that the transaction has been signed by the server. + * + * It does not verify that the transaction has been signed by the client or that + * any signatures other than the server's on the transaction are valid. Use one + * of the following functions to completely verify the transaction: + * + * - {@link module:WebAuth~verifyChallengeTxThreshold} + * - {@link module:WebAuth~verifyChallengeTxSigners} + * + * @param {string} challengeTx SEP0010 challenge transaction in base64. + * @param {string} serverAccountID The server's stellar account (public key). + * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF + * Network ; September 2015' (see {@link Networks}) + * @param {string | Array.} homeDomains The home domain that is expected + * to be included in the first Manage Data operation's string key. If an + * array is provided, one of the domain names in the array must match. + * @param {string} webAuthDomain The home domain that is expected to be included + * as the value of the Manage Data operation with the 'web_auth_domain' key. + * If no such operation is included, this parameter is not used. + * @returns {module:WebAuth.ChallengeTxDetails} The actual transaction and the + * Stellar public key (master key) used to sign the Manage Data operation, + * the matched home domain, and the memo attached to the transaction, which + * will be null if not present. + * + * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth} + */ +export declare function readChallengeTx(challengeTx: string, serverAccountID: string, networkPassphrase: string, homeDomains: string | string[], webAuthDomain: string): { + tx: Transaction; + clientAccountID: string; + matchedHomeDomain: string; + memo: string | null; +}; +/** + * Verifies that for a SEP-10 challenge transaction all signatures on the + * transaction are accounted for and that the signatures meet a threshold on an + * account. A transaction is verified if it is signed by the server account, and + * all other signatures match a signer that has been provided as an argument, + * and those signatures meet a threshold on the account. + * + * Signers that are not prefixed as an address/account ID strkey (G...) will be + * ignored. + * + * Errors will be raised if: + * - The transaction is invalid according to + * {@link module:WebAuth~readChallengeTx}. + * - No client signatures are found on the transaction. + * - One or more signatures in the transaction are not identifiable as the + * server account or one of the signers provided in the arguments. + * - The signatures are all valid but do not meet the threshold. + * + * @param {string} challengeTx SEP0010 challenge transaction in base64. + * @param {string} serverAccountID The server's stellar account (public key). + * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF + * Network ; September 2015' (see {@link Networks}). + * @param {number} threshold The required signatures threshold for verifying + * this transaction. + * @param {Array.} signerSummary a map of all + * authorized signers to their weights. It's used to validate if the + * transaction signatures have met the given threshold. + * @param {string | Array.} homeDomains The home domain(s) that should + * be included in the first Manage Data operation's string key. Required in + * verifyChallengeTxSigners() => readChallengeTx(). + * @param {string} webAuthDomain The home domain that is expected to be included + * as the value of the Manage Data operation with the 'web_auth_domain' key, + * if present. Used in verifyChallengeTxSigners() => readChallengeTx(). + * @returns {Array.} The list of signers public keys that have signed + * the transaction, excluding the server account ID, given that the threshold + * was met. + * @throws {module:WebAuth.InvalidChallengeError} Will throw if the collective + * weight of the transaction's signers does not meet the necessary threshold + * to verify this transaction. + * + * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth} + * + * @example + * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk'; + * + * const serverKP = Keypair.random(); + * const clientKP1 = Keypair.random(); + * const clientKP2 = Keypair.random(); + * + * // Challenge, possibly built in the server side + * const challenge = WebAuth.buildChallengeTx( + * serverKP, + * clientKP1.publicKey(), + * "SDF", + * 300, + * Networks.TESTNET + * ); + * + * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client + * + * // Transaction gathered from a challenge, possibly from the client side + * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET); + * transaction.sign(clientKP1, clientKP2); + * const signedChallenge = transaction + * .toEnvelope() + * .toXDR("base64") + * .toString(); + * + * // Defining the threshold and signerSummary + * const threshold = 3; + * const signerSummary = [ + * { + * key: this.clientKP1.publicKey(), + * weight: 1, + * }, + * { + * key: this.clientKP2.publicKey(), + * weight: 2, + * }, + * ]; + * + * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()] + * WebAuth.verifyChallengeTxThreshold( + * signedChallenge, + * serverKP.publicKey(), + * Networks.TESTNET, + * threshold, + * signerSummary + * ); + */ +export declare function verifyChallengeTxThreshold(challengeTx: string, serverAccountID: string, networkPassphrase: string, threshold: number, signerSummary: ServerApi.AccountRecordSigners[], homeDomains: string | string[], webAuthDomain: string): string[]; +/** + * Verifies that for a SEP 10 challenge transaction all signatures on the + * transaction are accounted for. A transaction is verified if it is signed by + * the server account, and all other signatures match a signer that has been + * provided as an argument (as the accountIDs list). Additional signers can be + * provided that do not have a signature, but all signatures must be matched to + * a signer (accountIDs) for verification to succeed. If verification succeeds, + * a list of signers that were found is returned, not including the server + * account ID. + * + * Signers that are not prefixed as an address/account ID strkey (G...) will be + * ignored. + * + * Errors will be raised if: + * - The transaction is invalid according to + * {@link module:WebAuth~readChallengeTx}. + * - No client signatures are found on the transaction. + * - One or more signatures in the transaction are not identifiable as the + * server account or one of the signers provided in the arguments. + * + * @param {string} challengeTx SEP0010 challenge transaction in base64. + * @param {string} serverAccountID The server's stellar account (public key). + * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF + * Network ; September 2015' (see {@link Networks}). + * @param {Array.} signers The signers public keys. This list should + * contain the public keys for all signers that have signed the transaction. + * @param {string | Array.} [homeDomains] The home domain(s) that should + * be included in the first Manage Data operation's string key. Required in + * readChallengeTx(). + * @param {string} webAuthDomain The home domain that is expected to be included + * as the value of the Manage Data operation with the 'web_auth_domain' key, + * if present. Used in readChallengeTx(). + * @returns {Array.} The list of signers public keys that have signed + * the transaction, excluding the server account ID. + * + * @see {@link https://stellar.org/protocol/sep-10|SEP-10: Stellar Web Auth} + * @example + * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk'; + * + * const serverKP = Keypair.random(); + * const clientKP1 = Keypair.random(); + * const clientKP2 = Keypair.random(); + * + * // Challenge, possibly built in the server side + * const challenge = WebAuth.buildChallengeTx( + * serverKP, + * clientKP1.publicKey(), + * "SDF", + * 300, + * Networks.TESTNET + * ); + * + * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client + * + * // Transaction gathered from a challenge, possibly from the client side + * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET); + * transaction.sign(clientKP1, clientKP2); + * const signedChallenge = transaction + * .toEnvelope() + * .toXDR("base64") + * .toString(); + * + * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()] + * WebAuth.verifyChallengeTxSigners( + * signedChallenge, + * serverKP.publicKey(), + * Networks.TESTNET, + * threshold, + * [clientKP1.publicKey(), clientKP2.publicKey()] + * ); + */ +export declare function verifyChallengeTxSigners(challengeTx: string, serverAccountID: string, networkPassphrase: string, signers: string[], homeDomains: string | string[], webAuthDomain: string): string[]; +/** + * Verifies if a transaction was signed by the given account id. + * + * @param {Transaction | FeeBumpTransaction} transaction The signed transaction. + * @param {string} accountID The signer's public key. + * @returns {boolean} Whether or not `accountID` was found to have signed the + * transaction. + * + * @example + * let keypair = Keypair.random(); + * const account = new StellarSdk.Account(keypair.publicKey(), "-1"); + * + * const transaction = new TransactionBuilder(account, { fee: 100 }) + * .setTimeout(30) + * .build(); + * + * transaction.sign(keypair) + * WebAuth.verifyTxSignedBy(transaction, keypair.publicKey()) + */ +export declare function verifyTxSignedBy(transaction: FeeBumpTransaction | Transaction, accountID: string): boolean; +/** + * Checks if a transaction has been signed by one or more of the given signers, + * returning a list of non-repeated signers that were found to have signed the + * given transaction. + * + * @param {Transaction | FeeBumpTransaction} transaction The signed transaction. + * @param {Array.} signers The signer's public keys. + * @returns {Array.} A list of signers that were found to have signed + * the transaction. + * + * @example + * let keypair1 = Keypair.random(); + * let keypair2 = Keypair.random(); + * const account = new StellarSdk.Account(keypair1.publicKey(), "-1"); + * + * const transaction = new TransactionBuilder(account, { fee: 100 }) + * .setTimeout(30) + * .build(); + * + * transaction.sign(keypair1, keypair2) + * WebAuth.gatherTxSigners(transaction, [keypair1.publicKey(), keypair2.publicKey()]) + */ +export declare function gatherTxSigners(transaction: FeeBumpTransaction | Transaction, signers: string[]): string[]; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/utils.js b/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/utils.js new file mode 100644 index 000000000..bc35281aa --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-axios/webauth/utils.js @@ -0,0 +1,332 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildChallengeTx = buildChallengeTx; +exports.gatherTxSigners = gatherTxSigners; +exports.readChallengeTx = readChallengeTx; +exports.verifyChallengeTxSigners = verifyChallengeTxSigners; +exports.verifyChallengeTxThreshold = verifyChallengeTxThreshold; +exports.verifyTxSignedBy = verifyTxSignedBy; +var _randombytes = _interopRequireDefault(require("randombytes")); +var _stellarBase = require("@stellar/stellar-base"); +var _utils = require("../utils"); +var _errors = require("./errors"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function buildChallengeTx(serverKeypair, clientAccountID, homeDomain) { + var timeout = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 300; + var networkPassphrase = arguments.length > 4 ? arguments[4] : undefined; + var webAuthDomain = arguments.length > 5 ? arguments[5] : undefined; + var memo = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var clientDomain = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var clientSigningKey = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; + if (clientAccountID.startsWith("M") && memo) { + throw Error("memo cannot be used if clientAccountID is a muxed account"); + } + var account = new _stellarBase.Account(serverKeypair.publicKey(), "-1"); + var now = Math.floor(Date.now() / 1000); + var value = (0, _randombytes.default)(48).toString("base64"); + var builder = new _stellarBase.TransactionBuilder(account, { + fee: _stellarBase.BASE_FEE, + networkPassphrase: networkPassphrase, + timebounds: { + minTime: now, + maxTime: now + timeout + } + }).addOperation(_stellarBase.Operation.manageData({ + name: "".concat(homeDomain, " auth"), + value: value, + source: clientAccountID + })).addOperation(_stellarBase.Operation.manageData({ + name: "web_auth_domain", + value: webAuthDomain, + source: account.accountId() + })); + if (clientDomain) { + if (!clientSigningKey) { + throw Error("clientSigningKey is required if clientDomain is provided"); + } + builder.addOperation(_stellarBase.Operation.manageData({ + name: "client_domain", + value: clientDomain, + source: clientSigningKey + })); + } + if (memo) { + builder.addMemo(_stellarBase.Memo.id(memo)); + } + var transaction = builder.build(); + transaction.sign(serverKeypair); + return transaction.toEnvelope().toXDR("base64").toString(); +} +function readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain) { + var _transaction$timeBoun; + if (serverAccountID.startsWith("M")) { + throw Error("Invalid serverAccountID: multiplexed accounts are not supported."); + } + var transaction; + try { + transaction = new _stellarBase.Transaction(challengeTx, networkPassphrase); + } catch (_unused) { + try { + transaction = new _stellarBase.FeeBumpTransaction(challengeTx, networkPassphrase); + } catch (_unused2) { + throw new _errors.InvalidChallengeError("Invalid challenge: unable to deserialize challengeTx transaction string"); + } + throw new _errors.InvalidChallengeError("Invalid challenge: expected a Transaction but received a FeeBumpTransaction"); + } + var sequence = Number.parseInt(transaction.sequence, 10); + if (sequence !== 0) { + throw new _errors.InvalidChallengeError("The transaction sequence number should be zero"); + } + if (transaction.source !== serverAccountID) { + throw new _errors.InvalidChallengeError("The transaction source account is not equal to the server's account"); + } + if (transaction.operations.length < 1) { + throw new _errors.InvalidChallengeError("The transaction should contain at least one operation"); + } + var _transaction$operatio = _toArray(transaction.operations), + operation = _transaction$operatio[0], + subsequentOperations = _transaction$operatio.slice(1); + if (!operation.source) { + throw new _errors.InvalidChallengeError("The transaction's operation should contain a source account"); + } + var clientAccountID = operation.source; + var memo = null; + if (transaction.memo.type !== _stellarBase.MemoNone) { + if (clientAccountID.startsWith("M")) { + throw new _errors.InvalidChallengeError("The transaction has a memo but the client account ID is a muxed account"); + } + if (transaction.memo.type !== _stellarBase.MemoID) { + throw new _errors.InvalidChallengeError("The transaction's memo must be of type `id`"); + } + memo = transaction.memo.value; + } + if (operation.type !== "manageData") { + throw new _errors.InvalidChallengeError("The transaction's operation type should be 'manageData'"); + } + if (transaction.timeBounds && Number.parseInt((_transaction$timeBoun = transaction.timeBounds) === null || _transaction$timeBoun === void 0 ? void 0 : _transaction$timeBoun.maxTime, 10) === _stellarBase.TimeoutInfinite) { + throw new _errors.InvalidChallengeError("The transaction requires non-infinite timebounds"); + } + if (!_utils.Utils.validateTimebounds(transaction, 60 * 5)) { + throw new _errors.InvalidChallengeError("The transaction has expired"); + } + if (operation.value === undefined) { + throw new _errors.InvalidChallengeError("The transaction's operation values should not be null"); + } + if (!operation.value) { + throw new _errors.InvalidChallengeError("The transaction's operation value should not be null"); + } + if (Buffer.from(operation.value.toString(), "base64").length !== 48) { + throw new _errors.InvalidChallengeError("The transaction's operation value should be a 64 bytes base64 random string"); + } + if (!homeDomains) { + throw new _errors.InvalidChallengeError("Invalid homeDomains: a home domain must be provided for verification"); + } + var matchedHomeDomain; + if (typeof homeDomains === "string") { + if ("".concat(homeDomains, " auth") === operation.name) { + matchedHomeDomain = homeDomains; + } + } else if (Array.isArray(homeDomains)) { + matchedHomeDomain = homeDomains.find(function (domain) { + return "".concat(domain, " auth") === operation.name; + }); + } else { + throw new _errors.InvalidChallengeError("Invalid homeDomains: homeDomains type is ".concat(_typeof(homeDomains), " but should be a string or an array")); + } + if (!matchedHomeDomain) { + throw new _errors.InvalidChallengeError("Invalid homeDomains: the transaction's operation key name does not match the expected home domain"); + } + var _iterator = _createForOfIteratorHelper(subsequentOperations), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var op = _step.value; + if (op.type !== "manageData") { + throw new _errors.InvalidChallengeError("The transaction has operations that are not of type 'manageData'"); + } + if (op.source !== serverAccountID && op.name !== "client_domain") { + throw new _errors.InvalidChallengeError("The transaction has operations that are unrecognized"); + } + if (op.name === "web_auth_domain") { + if (op.value === undefined) { + throw new _errors.InvalidChallengeError("'web_auth_domain' operation value should not be null"); + } + if (op.value.compare(Buffer.from(webAuthDomain))) { + throw new _errors.InvalidChallengeError("'web_auth_domain' operation value does not match ".concat(webAuthDomain)); + } + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + if (!verifyTxSignedBy(transaction, serverAccountID)) { + throw new _errors.InvalidChallengeError("Transaction not signed by server: '".concat(serverAccountID, "'")); + } + return { + tx: transaction, + clientAccountID: clientAccountID, + matchedHomeDomain: matchedHomeDomain, + memo: memo + }; +} +function verifyChallengeTxThreshold(challengeTx, serverAccountID, networkPassphrase, threshold, signerSummary, homeDomains, webAuthDomain) { + var signers = signerSummary.map(function (signer) { + return signer.key; + }); + var signersFound = verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain); + var weight = 0; + var _loop = function _loop() { + var _signerSummary$find; + var signer = _signersFound[_i]; + var sigWeight = ((_signerSummary$find = signerSummary.find(function (s) { + return s.key === signer; + })) === null || _signerSummary$find === void 0 ? void 0 : _signerSummary$find.weight) || 0; + weight += sigWeight; + }; + for (var _i = 0, _signersFound = signersFound; _i < _signersFound.length; _i++) { + _loop(); + } + if (weight < threshold) { + throw new _errors.InvalidChallengeError("signers with weight ".concat(weight, " do not meet threshold ").concat(threshold, "\"")); + } + return signersFound; +} +function verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain) { + var _readChallengeTx = readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain), + tx = _readChallengeTx.tx; + var serverKP; + try { + serverKP = _stellarBase.Keypair.fromPublicKey(serverAccountID); + } catch (err) { + throw new Error("Couldn't infer keypair from the provided 'serverAccountID': ".concat(err.message)); + } + var clientSigners = new Set(); + var _iterator2 = _createForOfIteratorHelper(signers), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var _signer = _step2.value; + if (_signer === serverKP.publicKey()) { + continue; + } + if (_signer.charAt(0) !== "G") { + continue; + } + clientSigners.add(_signer); + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + if (clientSigners.size === 0) { + throw new _errors.InvalidChallengeError("No verifiable client signers provided, at least one G... address must be provided"); + } + var clientSigningKey; + var _iterator3 = _createForOfIteratorHelper(tx.operations), + _step3; + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + var op = _step3.value; + if (op.type === "manageData" && op.name === "client_domain") { + if (clientSigningKey) { + throw new _errors.InvalidChallengeError("Found more than one client_domain operation"); + } + clientSigningKey = op.source; + } + } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); + } + var allSigners = [serverKP.publicKey()].concat(_toConsumableArray(Array.from(clientSigners))); + if (clientSigningKey) { + allSigners.push(clientSigningKey); + } + var signersFound = gatherTxSigners(tx, allSigners); + var serverSignatureFound = false; + var clientSigningKeySignatureFound = false; + for (var _i2 = 0, _signersFound2 = signersFound; _i2 < _signersFound2.length; _i2++) { + var signer = _signersFound2[_i2]; + if (signer === serverKP.publicKey()) { + serverSignatureFound = true; + } + if (signer === clientSigningKey) { + clientSigningKeySignatureFound = true; + } + } + if (!serverSignatureFound) { + throw new _errors.InvalidChallengeError("Transaction not signed by server: '".concat(serverKP.publicKey(), "'")); + } + if (clientSigningKey && !clientSigningKeySignatureFound) { + throw new _errors.InvalidChallengeError("Transaction not signed by the source account of the 'client_domain' " + "ManageData operation"); + } + if (signersFound.length === 1) { + throw new _errors.InvalidChallengeError("None of the given signers match the transaction signatures"); + } + if (signersFound.length !== tx.signatures.length) { + throw new _errors.InvalidChallengeError("Transaction has unrecognized signatures"); + } + signersFound.splice(signersFound.indexOf(serverKP.publicKey()), 1); + if (clientSigningKey) { + signersFound.splice(signersFound.indexOf(clientSigningKey), 1); + } + return signersFound; +} +function verifyTxSignedBy(transaction, accountID) { + return gatherTxSigners(transaction, [accountID]).length !== 0; +} +function gatherTxSigners(transaction, signers) { + var hashedSignatureBase = transaction.hash(); + var txSignatures = _toConsumableArray(transaction.signatures); + var signersFound = new Set(); + var _iterator4 = _createForOfIteratorHelper(signers), + _step4; + try { + for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { + var signer = _step4.value; + if (txSignatures.length === 0) { + break; + } + var keypair = void 0; + try { + keypair = _stellarBase.Keypair.fromPublicKey(signer); + } catch (err) { + throw new _errors.InvalidChallengeError("Signer is not a valid address: ".concat(err.message)); + } + for (var i = 0; i < txSignatures.length; i++) { + var decSig = txSignatures[i]; + if (!decSig.hint().equals(keypair.signatureHint())) { + continue; + } + if (keypair.verify(hashedSignatureBase, decSig.signature())) { + signersFound.add(signer); + txSignatures.splice(i, 1); + break; + } + } + } + } catch (err) { + _iterator4.e(err); + } finally { + _iterator4.f(); + } + return Array.from(signersFound); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/browser.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/browser.d.ts new file mode 100644 index 000000000..bfdbd32a2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/browser.d.ts @@ -0,0 +1,6 @@ +import { httpClient } from "./http-client"; +export * from "./index"; +export * as StellarBase from "@stellar/stellar-base"; +export { httpClient }; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/browser.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/browser.js new file mode 100644 index 000000000..f21e953f0 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/browser.js @@ -0,0 +1,35 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + httpClient: true, + StellarBase: true +}; +exports.default = exports.StellarBase = void 0; +Object.defineProperty(exports, "httpClient", { + enumerable: true, + get: function get() { + return _httpClient.httpClient; + } +}); +var _httpClient = require("./http-client"); +var _index = require("./index"); +Object.keys(_index).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _index[key]; + } + }); +}); +var _StellarBase = _interopRequireWildcard(require("@stellar/stellar-base")); +exports.StellarBase = _StellarBase; +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/config.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/config.d.ts new file mode 100644 index 000000000..3daa1aa99 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/config.d.ts @@ -0,0 +1,64 @@ +/** + * Global config parameters. + */ +export interface Configuration { + /** + * Allow connecting to http servers. This must be set to false in production deployments! + * @default false + */ + allowHttp: boolean; + /** + * Allow a timeout. Allows user to avoid nasty lag due network issues. + * @default 0 + */ + timeout: number; +} +/** + * Global config class. + * + * @hideconstructor + * + * @example Usage in node + * import { Config } from '@stellar/stellar-sdk'; + * Config.setAllowHttp(true); + * Config.setTimeout(5000); + * + * @example Usage in the browser + * StellarSdk.Config.setAllowHttp(true); + * StellarSdk.Config.setTimeout(5000); + */ +declare class Config { + /** + * Sets `allowHttp` flag globally. When set to `true`, connections to insecure + * http protocol servers will be allowed. Must be set to `false` in + * production. + * @default false + * @static + */ + static setAllowHttp(value: boolean): void; + /** + * Sets `timeout` flag globally. When set to anything besides 0, the request + * will timeout after specified time (ms). + * @default 0 + * @static + */ + static setTimeout(value: number): void; + /** + * Returns the configured `allowHttp` flag. + * @static + * @returns {boolean} + */ + static isAllowHttp(): boolean; + /** + * Returns the configured `timeout` flag. + * @static + * @returns {number} + */ + static getTimeout(): number; + /** + * Sets all global config flags to default values. + * @static + */ + static setDefault(): void; +} +export { Config }; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/config.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/config.js new file mode 100644 index 000000000..e19e63d74 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/config.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Config = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var defaultConfig = { + allowHttp: false, + timeout: 0 +}; +var config = _objectSpread({}, defaultConfig); +var Config = exports.Config = function () { + function Config() { + _classCallCheck(this, Config); + } + return _createClass(Config, null, [{ + key: "setAllowHttp", + value: function setAllowHttp(value) { + config.allowHttp = value; + } + }, { + key: "setTimeout", + value: function setTimeout(value) { + config.timeout = value; + } + }, { + key: "isAllowHttp", + value: function isAllowHttp() { + return config.allowHttp; + } + }, { + key: "getTimeout", + value: function getTimeout() { + return config.timeout; + } + }, { + key: "setDefault", + value: function setDefault() { + config = _objectSpread({}, defaultConfig); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/assembled_transaction.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/assembled_transaction.d.ts new file mode 100644 index 000000000..c420d90f2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/assembled_transaction.d.ts @@ -0,0 +1,627 @@ +import { Account, SorobanDataBuilder, TransactionBuilder, authorizeEntry as stellarBaseAuthorizeEntry, xdr } from "@stellar/stellar-base"; +import type { AssembledTransactionOptions, ClientOptions, Tx, XDR_BASE64 } from "./types"; +import { Api } from "../rpc/api"; +import { SentTransaction } from "./sent_transaction"; +import { Spec } from "./spec"; +/** @module contract */ +/** + * The main workhorse of {@link Client}. This class is used to wrap a + * transaction-under-construction and provide high-level interfaces to the most + * common workflows, while still providing access to low-level stellar-sdk + * transaction manipulation. + * + * Most of the time, you will not construct an `AssembledTransaction` directly, + * but instead receive one as the return value of a `Client` method. If + * you're familiar with the libraries generated by soroban-cli's `contract + * bindings typescript` command, these also wraps `Client` and return + * `AssembledTransaction` instances. + * + * Let's look at examples of how to use `AssembledTransaction` for a variety of + * use-cases: + * + * #### 1. Simple read call + * + * Since these only require simulation, you can get the `result` of the call + * right after constructing your `AssembledTransaction`: + * + * ```ts + * const { result } = await AssembledTransaction.build({ + * method: 'myReadMethod', + * args: spec.funcArgsToScVals('myReadMethod', { + * args: 'for', + * my: 'method', + * ... + * }), + * contractId: 'C123…', + * networkPassphrase: '…', + * rpcUrl: 'https://…', + * publicKey: undefined, // irrelevant, for simulation-only read calls + * parseResultXdr: (result: xdr.ScVal) => + * spec.funcResToNative('myReadMethod', result), + * }) + * ``` + * + * While that looks pretty complicated, most of the time you will use this in + * conjunction with {@link Client}, which simplifies it to: + * + * ```ts + * const { result } = await client.myReadMethod({ + * args: 'for', + * my: 'method', + * ... + * }) + * ``` + * + * #### 2. Simple write call + * + * For write calls that will be simulated and then sent to the network without + * further manipulation, only one more step is needed: + * + * ```ts + * const assembledTx = await client.myWriteMethod({ + * args: 'for', + * my: 'method', + * ... + * }) + * const sentTx = await assembledTx.signAndSend() + * ``` + * + * Here we're assuming that you're using a {@link Client}, rather than + * constructing `AssembledTransaction`'s directly. + * + * Note that `sentTx`, the return value of `signAndSend`, is a + * {@link SentTransaction}. `SentTransaction` is similar to + * `AssembledTransaction`, but is missing many of the methods and fields that + * are only relevant while assembling a transaction. It also has a few extra + * methods and fields that are only relevant after the transaction has been + * sent to the network. + * + * Like `AssembledTransaction`, `SentTransaction` also has a `result` getter, + * which contains the parsed final return value of the contract call. Most of + * the time, you may only be interested in this, so rather than getting the + * whole `sentTx` you may just want to: + * + * ```ts + * const tx = await client.myWriteMethod({ args: 'for', my: 'method', ... }) + * const { result } = await tx.signAndSend() + * ``` + * + * #### 3. More fine-grained control over transaction construction + * + * If you need more control over the transaction before simulating it, you can + * set various {@link MethodOptions} when constructing your + * `AssembledTransaction`. With a {@link Client}, this is passed as a + * second object after the arguments (or the only object, if the method takes + * no arguments): + * + * ```ts + * const tx = await client.myWriteMethod( + * { + * args: 'for', + * my: 'method', + * ... + * }, { + * fee: '10000', // default: {@link BASE_FEE} + * simulate: false, + * timeoutInSeconds: 20, // default: {@link DEFAULT_TIMEOUT} + * } + * ) + * ``` + * + * Since we've skipped simulation, we can now edit the `raw` transaction and + * then manually call `simulate`: + * + * ```ts + * tx.raw.addMemo(Memo.text('Nice memo, friend!')) + * await tx.simulate() + * ``` + * + * If you need to inspect the simulation later, you can access it with + * `tx.simulation`. + * + * #### 4. Multi-auth workflows + * + * Soroban, and Stellar in general, allows multiple parties to sign a + * transaction. + * + * Let's consider an Atomic Swap contract. Alice wants to give 10 of her Token + * A tokens to Bob for 5 of his Token B tokens. + * + * ```ts + * const ALICE = 'G123...' + * const BOB = 'G456...' + * const TOKEN_A = 'C123…' + * const TOKEN_B = 'C456…' + * const AMOUNT_A = 10n + * const AMOUNT_B = 5n + * ``` + * + * Let's say Alice is also going to be the one signing the final transaction + * envelope, meaning she is the invoker. So your app, from Alice's browser, + * simulates the `swap` call: + * + * ```ts + * const tx = await swapClient.swap({ + * a: ALICE, + * b: BOB, + * token_a: TOKEN_A, + * token_b: TOKEN_B, + * amount_a: AMOUNT_A, + * amount_b: AMOUNT_B, + * }) + * ``` + * + * But your app can't `signAndSend` this right away, because Bob needs to sign + * it first. You can check this: + * + * ```ts + * const whoElseNeedsToSign = tx.needsNonInvokerSigningBy() + * ``` + * + * You can verify that `whoElseNeedsToSign` is an array of length `1`, + * containing only Bob's public key. + * + * Then, still on Alice's machine, you can serialize the + * transaction-under-assembly: + * + * ```ts + * const json = tx.toJSON() + * ``` + * + * And now you need to send it to Bob's browser. How you do this depends on + * your app. Maybe you send it to a server first, maybe you use WebSockets, or + * maybe you have Alice text the JSON blob to Bob and have him paste it into + * your app in his browser (note: this option might be error-prone 😄). + * + * Once you get the JSON blob into your app on Bob's machine, you can + * deserialize it: + * + * ```ts + * const tx = swapClient.txFromJSON(json) + * ``` + * + * Or, if you're using a client generated with `soroban contract bindings + * typescript`, this deserialization will look like: + * + * ```ts + * const tx = swapClient.fromJSON.swap(json) + * ``` + * + * Then you can have Bob sign it. What Bob will actually need to sign is some + * _auth entries_ within the transaction, not the transaction itself or the + * transaction envelope. Your app can verify that Bob has the correct wallet + * selected, then: + * + * ```ts + * await tx.signAuthEntries() + * ``` + * + * Under the hood, this uses `signAuthEntry`, which you either need to inject + * during initial construction of the `Client`/`AssembledTransaction`, + * or which you can pass directly to `signAuthEntries`. + * + * Now Bob can again serialize the transaction and send back to Alice, where + * she can finally call `signAndSend()`. + * + * To see an even more complicated example, where Alice swaps with Bob but the + * transaction is invoked by yet another party, check out + * [test-swap.js](../../test/e2e/src/test-swap.js). + * + * @memberof module:contract + */ +export declare class AssembledTransaction { + options: AssembledTransactionOptions; + /** + * The TransactionBuilder as constructed in `{@link + * AssembledTransaction}.build`. Feel free set `simulate: false` to modify + * this object before calling `tx.simulate()` manually. Example: + * + * ```ts + * const tx = await myContract.myMethod( + * { args: 'for', my: 'method', ... }, + * { simulate: false } + * ); + * tx.raw.addMemo(Memo.text('Nice memo, friend!')) + * await tx.simulate(); + * ``` + */ + raw?: TransactionBuilder; + /** + * The Transaction as it was built with `raw.build()` right before + * simulation. Once this is set, modifying `raw` will have no effect unless + * you call `tx.simulate()` again. + */ + built?: Tx; + /** + * The result of the transaction simulation. This is set after the first call + * to `simulate`. It is difficult to serialize and deserialize, so it is not + * included in the `toJSON` and `fromJSON` methods. See `simulationData` + * cached, serializable access to the data needed by AssembledTransaction + * logic. + */ + simulation?: Api.SimulateTransactionResponse; + /** + * Cached simulation result. This is set after the first call to + * {@link AssembledTransaction#simulationData}, and is used to facilitate + * serialization and deserialization of the AssembledTransaction. + * + * Most of the time, if you need this data, you can call + * `tx.simulation.result`. + * + * If you need access to this data after a transaction has been serialized + * and then deserialized, you can call `simulationData.result`. + */ + private simulationResult?; + /** + * Cached simulation transaction data. This is set after the first call to + * {@link AssembledTransaction#simulationData}, and is used to facilitate + * serialization and deserialization of the AssembledTransaction. + * + * Most of the time, if you need this data, you can call + * `simulation.transactionData`. + * + * If you need access to this data after a transaction has been serialized + * and then deserialized, you can call `simulationData.transactionData`. + */ + private simulationTransactionData?; + /** + * The Soroban server to use for all RPC calls. This is constructed from the + * `rpcUrl` in the options. + */ + private server; + /** + * The signed transaction. + */ + signed?: Tx; + /** + * A list of the most important errors that various AssembledTransaction + * methods can throw. Feel free to catch specific errors in your application + * logic. + */ + static Errors: { + ExpiredState: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + RestorationFailure: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NeedsMoreSignatures: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NoSignatureNeeded: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NoUnsignedNonInvokerAuthEntries: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NoSigner: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + NotYetSimulated: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + FakeAccount: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + SimulationFailed: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + InternalWalletError: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + ExternalServiceError: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + InvalidClientRequest: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + UserRejected: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + }; + /** + * Serialize the AssembledTransaction to a JSON string. This is useful for + * saving the transaction to a database or sending it over the wire for + * multi-auth workflows. `fromJSON` can be used to deserialize the + * transaction. This only works with transactions that have been simulated. + */ + toJSON(): string; + static fromJSON(options: Omit, "args">, { tx, simulationResult, simulationTransactionData, }: { + tx: XDR_BASE64; + simulationResult: { + auth: XDR_BASE64[]; + retval: XDR_BASE64; + }; + simulationTransactionData: XDR_BASE64; + }): AssembledTransaction; + /** + * Serialize the AssembledTransaction to a base64-encoded XDR string. + */ + toXDR(): string; + /** + * Deserialize the AssembledTransaction from a base64-encoded XDR string. + */ + static fromXDR(options: Omit, "args" | "method" | "parseResultXdr">, encodedXDR: string, spec: Spec): AssembledTransaction; + private handleWalletError; + private constructor(); + /** + * Construct a new AssembledTransaction. This is the main way to create a new + * AssembledTransaction; the constructor is private. + * + * This is an asynchronous constructor for two reasons: + * + * 1. It needs to fetch the account from the network to get the current + * sequence number. + * 2. It needs to simulate the transaction to get the expected fee. + * + * If you don't want to simulate the transaction, you can set `simulate` to + * `false` in the options. + * + * If you need to create an operation other than `invokeHostFunction`, you + * can use {@link AssembledTransaction.buildWithOp} instead. + * + * @example + * const tx = await AssembledTransaction.build({ + * ..., + * simulate: false, + * }) + */ + static build(options: AssembledTransactionOptions): Promise>; + /** + * Construct a new AssembledTransaction, specifying an Operation other than + * `invokeHostFunction` (the default used by {@link AssembledTransaction.build}). + * + * Note: `AssembledTransaction` currently assumes these operations can be + * simulated. This is not true for classic operations; only for those used by + * Soroban Smart Contracts like `invokeHostFunction` and `createCustomContract`. + * + * @example + * const tx = await AssembledTransaction.buildWithOp( + * Operation.createCustomContract({ ... }); + * { + * ..., + * simulate: false, + * } + * ) + */ + static buildWithOp(operation: xdr.Operation, options: AssembledTransactionOptions): Promise>; + private static buildFootprintRestoreTransaction; + simulate: ({ restore }?: { + restore?: boolean; + }) => Promise; + get simulationData(): { + result: Api.SimulateHostFunctionResult; + transactionData: xdr.SorobanTransactionData; + }; + get result(): T; + private parseError; + /** + * Sign the transaction with the signTransaction function included previously. + * If you did not previously include one, you need to include one now. + */ + sign: ({ force, signTransaction, }?: { + /** + * If `true`, sign and send the transaction even if it is a read call + */ + force?: boolean; + /** + * You must provide this here if you did not provide one before + */ + signTransaction?: ClientOptions["signTransaction"]; + }) => Promise; + /** + * Sends the transaction to the network to return a `SentTransaction` that + * keeps track of all the attempts to fetch the transaction. + */ + send(): Promise>; + /** + * Sign the transaction with the `signTransaction` function included previously. + * If you did not previously include one, you need to include one now. + * After signing, this method will send the transaction to the network and + * return a `SentTransaction` that keeps track * of all the attempts to fetch the transaction. + */ + signAndSend: ({ force, signTransaction, }?: { + /** + * If `true`, sign and send the transaction even if it is a read call + */ + force?: boolean; + /** + * You must provide this here if you did not provide one before + */ + signTransaction?: ClientOptions["signTransaction"]; + }) => Promise>; + /** + * Get a list of accounts, other than the invoker of the simulation, that + * need to sign auth entries in this transaction. + * + * Soroban allows multiple people to sign a transaction. Someone needs to + * sign the final transaction envelope; this person/account is called the + * _invoker_, or _source_. Other accounts might need to sign individual auth + * entries in the transaction, if they're not also the invoker. + * + * This function returns a list of accounts that need to sign auth entries, + * assuming that the same invoker/source account will sign the final + * transaction envelope as signed the initial simulation. + * + * One at a time, for each public key in this array, you will need to + * serialize this transaction with `toJSON`, send to the owner of that key, + * deserialize the transaction with `txFromJson`, and call + * {@link AssembledTransaction#signAuthEntries}. Then re-serialize and send to + * the next account in this list. + */ + needsNonInvokerSigningBy: ({ includeAlreadySigned, }?: { + /** + * Whether or not to include auth entries that have already been signed. + * Default: false + */ + includeAlreadySigned?: boolean; + }) => string[]; + /** + * If {@link AssembledTransaction#needsNonInvokerSigningBy} returns a + * non-empty list, you can serialize the transaction with `toJSON`, send it to + * the owner of one of the public keys in the map, deserialize with + * `txFromJSON`, and call this method on their machine. Internally, this will + * use `signAuthEntry` function from connected `wallet` for each. + * + * Then, re-serialize the transaction and either send to the next + * `needsNonInvokerSigningBy` owner, or send it back to the original account + * who simulated the transaction so they can {@link AssembledTransaction#sign} + * the transaction envelope and {@link AssembledTransaction#send} it to the + * network. + * + * Sending to all `needsNonInvokerSigningBy` owners in parallel is not + * currently supported! + */ + signAuthEntries: ({ expiration, signAuthEntry, address, authorizeEntry, }?: { + /** + * When to set each auth entry to expire. Could be any number of blocks in + * the future. Can be supplied as a promise or a raw number. Default: + * about 8.3 minutes from now. + */ + expiration?: number | Promise; + /** + * Sign all auth entries for this account. Default: the account that + * constructed the transaction + */ + address?: string; + /** + * You must provide this here if you did not provide one before and you are not passing `authorizeEntry`. Default: the `signAuthEntry` function from the `Client` options. Must sign things as the given `publicKey`. + */ + signAuthEntry?: ClientOptions["signAuthEntry"]; + /** + * If you have a pro use-case and need to override the default `authorizeEntry` function, rather than using the one in @stellar/stellar-base, you can do that! Your function needs to take at least the first argument, `entry: xdr.SorobanAuthorizationEntry`, and return a `Promise`. + * + * Note that you if you pass this, then `signAuthEntry` will be ignored. + */ + authorizeEntry?: typeof stellarBaseAuthorizeEntry; + }) => Promise; + /** + * Whether this transaction is a read call. This is determined by the + * simulation result and the transaction data. If the transaction is a read + * call, it will not need to be signed and sent to the network. If this + * returns `false`, then you need to call `signAndSend` on this transaction. + */ + get isReadCall(): boolean; + /** + * Restores the footprint (resource ledger entries that can be read or written) + * of an expired transaction. + * + * The method will: + * 1. Build a new transaction aimed at restoring the necessary resources. + * 2. Sign this new transaction if a `signTransaction` handler is provided. + * 3. Send the signed transaction to the network. + * 4. Await and return the response from the network. + * + * Preconditions: + * - A `signTransaction` function must be provided during the Client initialization. + * - The provided `restorePreamble` should include a minimum resource fee and valid + * transaction data. + * + * @throws {Error} - Throws an error if no `signTransaction` function is provided during + * Client initialization. + * @throws {AssembledTransaction.Errors.RestoreFailure} - Throws a custom error if the + * restore transaction fails, providing the details of the failure. + */ + restoreFootprint( + /** + * The preamble object containing data required to + * build the restore transaction. + */ + restorePreamble: { + minResourceFee: string; + transactionData: SorobanDataBuilder; + }, + /** The account that is executing the footprint restore operation. If omitted, will use the account from the AssembledTransaction. */ + account?: Account): Promise; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/assembled_transaction.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/assembled_transaction.js new file mode 100644 index 000000000..aaeaac04e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/assembled_transaction.js @@ -0,0 +1,841 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AssembledTransaction = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _rpc = require("../rpc"); +var _api = require("../rpc/api"); +var _transaction = require("../rpc/transaction"); +var _rust_result = require("./rust_result"); +var _utils = require("./utils"); +var _types = require("./types"); +var _sent_transaction = require("./sent_transaction"); +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var AssembledTransaction = exports.AssembledTransaction = function () { + function AssembledTransaction(options) { + var _this = this, + _this$options$simulat, + _this$options$allowHt; + _classCallCheck(this, AssembledTransaction); + _defineProperty(this, "simulate", _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var _restore; + var _ref2, + restore, + account, + result, + _this$options$fee, + _this$options$args, + _this$options$timeout, + contract, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _ref2 = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, restore = _ref2.restore; + if (_this.built) { + _context.next = 5; + break; + } + if (_this.raw) { + _context.next = 4; + break; + } + throw new Error("Transaction has not yet been assembled; " + "call `AssembledTransaction.build` first."); + case 4: + _this.built = _this.raw.build(); + case 5: + restore = (_restore = restore) !== null && _restore !== void 0 ? _restore : _this.options.restore; + delete _this.simulationResult; + delete _this.simulationTransactionData; + _context.next = 10; + return _this.server.simulateTransaction(_this.built); + case 10: + _this.simulation = _context.sent; + if (!(restore && _api.Api.isSimulationRestore(_this.simulation))) { + _context.next = 25; + break; + } + _context.next = 14; + return (0, _utils.getAccount)(_this.options, _this.server); + case 14: + account = _context.sent; + _context.next = 17; + return _this.restoreFootprint(_this.simulation.restorePreamble, account); + case 17: + result = _context.sent; + if (!(result.status === _api.Api.GetTransactionStatus.SUCCESS)) { + _context.next = 24; + break; + } + contract = new _stellarBase.Contract(_this.options.contractId); + _this.raw = new _stellarBase.TransactionBuilder(account, { + fee: (_this$options$fee = _this.options.fee) !== null && _this$options$fee !== void 0 ? _this$options$fee : _stellarBase.BASE_FEE, + networkPassphrase: _this.options.networkPassphrase + }).addOperation(contract.call.apply(contract, [_this.options.method].concat(_toConsumableArray((_this$options$args = _this.options.args) !== null && _this$options$args !== void 0 ? _this$options$args : [])))).setTimeout((_this$options$timeout = _this.options.timeoutInSeconds) !== null && _this$options$timeout !== void 0 ? _this$options$timeout : _types.DEFAULT_TIMEOUT); + _context.next = 23; + return _this.simulate(); + case 23: + return _context.abrupt("return", _this); + case 24: + throw new AssembledTransaction.Errors.RestorationFailure("Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\n".concat(JSON.stringify(result))); + case 25: + if (_api.Api.isSimulationSuccess(_this.simulation)) { + _this.built = (0, _transaction.assembleTransaction)(_this.built, _this.simulation).build(); + } + return _context.abrupt("return", _this); + case 27: + case "end": + return _context.stop(); + } + }, _callee); + }))); + _defineProperty(this, "sign", _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + var _this$options$timeout2; + var _ref4, + _ref4$force, + force, + _ref4$signTransaction, + signTransaction, + sigsNeeded, + timeoutInSeconds, + signOpts, + _yield$signTransactio, + signature, + error, + _args2 = arguments; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _ref4 = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref4$force = _ref4.force, force = _ref4$force === void 0 ? false : _ref4$force, _ref4$signTransaction = _ref4.signTransaction, signTransaction = _ref4$signTransaction === void 0 ? _this.options.signTransaction : _ref4$signTransaction; + if (_this.built) { + _context2.next = 3; + break; + } + throw new Error("Transaction has not yet been simulated"); + case 3: + if (!(!force && _this.isReadCall)) { + _context2.next = 5; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("This is a read call. It requires no signature or sending. " + "Use `force: true` to sign and send anyway."); + case 5: + if (signTransaction) { + _context2.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide a signTransaction function, either when calling " + "`signAndSend` or when initializing your Client"); + case 7: + sigsNeeded = _this.needsNonInvokerSigningBy().filter(function (id) { + return !id.startsWith('C'); + }); + if (!sigsNeeded.length) { + _context2.next = 10; + break; + } + throw new AssembledTransaction.Errors.NeedsMoreSignatures("Transaction requires signatures from ".concat(sigsNeeded, ". ") + "See `needsNonInvokerSigningBy` for details."); + case 10: + timeoutInSeconds = (_this$options$timeout2 = _this.options.timeoutInSeconds) !== null && _this$options$timeout2 !== void 0 ? _this$options$timeout2 : _types.DEFAULT_TIMEOUT; + _this.built = _stellarBase.TransactionBuilder.cloneFrom(_this.built, { + fee: _this.built.fee, + timebounds: undefined, + sorobanData: _this.simulationData.transactionData + }).setTimeout(timeoutInSeconds).build(); + signOpts = { + networkPassphrase: _this.options.networkPassphrase + }; + if (_this.options.address) signOpts.address = _this.options.address; + if (_this.options.submit !== undefined) signOpts.submit = _this.options.submit; + if (_this.options.submitUrl) signOpts.submitUrl = _this.options.submitUrl; + _context2.next = 18; + return signTransaction(_this.built.toXDR(), signOpts); + case 18: + _yield$signTransactio = _context2.sent; + signature = _yield$signTransactio.signedTxXdr; + error = _yield$signTransactio.error; + _this.handleWalletError(error); + _this.signed = _stellarBase.TransactionBuilder.fromXDR(signature, _this.options.networkPassphrase); + case 23: + case "end": + return _context2.stop(); + } + }, _callee2); + }))); + _defineProperty(this, "signAndSend", _asyncToGenerator(_regeneratorRuntime().mark(function _callee3() { + var _ref6, + _ref6$force, + force, + _ref6$signTransaction, + signTransaction, + originalSubmit, + _args3 = arguments; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _ref6 = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : {}, _ref6$force = _ref6.force, force = _ref6$force === void 0 ? false : _ref6$force, _ref6$signTransaction = _ref6.signTransaction, signTransaction = _ref6$signTransaction === void 0 ? _this.options.signTransaction : _ref6$signTransaction; + if (_this.signed) { + _context3.next = 10; + break; + } + originalSubmit = _this.options.submit; + if (_this.options.submit) { + _this.options.submit = false; + } + _context3.prev = 4; + _context3.next = 7; + return _this.sign({ + force: force, + signTransaction: signTransaction + }); + case 7: + _context3.prev = 7; + _this.options.submit = originalSubmit; + return _context3.finish(7); + case 10: + return _context3.abrupt("return", _this.send()); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3, null, [[4,, 7, 10]]); + }))); + _defineProperty(this, "needsNonInvokerSigningBy", function () { + var _rawInvokeHostFunctio; + var _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref7$includeAlreadyS = _ref7.includeAlreadySigned, + includeAlreadySigned = _ref7$includeAlreadyS === void 0 ? false : _ref7$includeAlreadyS; + if (!_this.built) { + throw new Error("Transaction has not yet been simulated"); + } + if (!("operations" in _this.built)) { + throw new Error("Unexpected Transaction type; no operations: ".concat(JSON.stringify(_this.built))); + } + var rawInvokeHostFunctionOp = _this.built.operations[0]; + return _toConsumableArray(new Set(((_rawInvokeHostFunctio = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio !== void 0 ? _rawInvokeHostFunctio : []).filter(function (entry) { + return entry.credentials().switch() === _stellarBase.xdr.SorobanCredentialsType.sorobanCredentialsAddress() && (includeAlreadySigned || entry.credentials().address().signature().switch().name === "scvVoid"); + }).map(function (entry) { + return _stellarBase.Address.fromScAddress(entry.credentials().address().address()).toString(); + }))); + }); + _defineProperty(this, "signAuthEntries", _asyncToGenerator(_regeneratorRuntime().mark(function _callee6() { + var _rawInvokeHostFunctio2; + var _ref9, + _ref9$expiration, + expiration, + _ref9$signAuthEntry, + signAuthEntry, + _ref9$address, + address, + _ref9$authorizeEntry, + authorizeEntry, + needsNonInvokerSigningBy, + rawInvokeHostFunctionOp, + authEntries, + _iterator, + _step, + _loop, + _ret, + _args7 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _ref9 = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {}, _ref9$expiration = _ref9.expiration, expiration = _ref9$expiration === void 0 ? _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this.server.getLatestLedger(); + case 2: + _context4.t0 = _context4.sent.sequence; + return _context4.abrupt("return", _context4.t0 + 100); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + }))() : _ref9$expiration, _ref9$signAuthEntry = _ref9.signAuthEntry, signAuthEntry = _ref9$signAuthEntry === void 0 ? _this.options.signAuthEntry : _ref9$signAuthEntry, _ref9$address = _ref9.address, address = _ref9$address === void 0 ? _this.options.publicKey : _ref9$address, _ref9$authorizeEntry = _ref9.authorizeEntry, authorizeEntry = _ref9$authorizeEntry === void 0 ? _stellarBase.authorizeEntry : _ref9$authorizeEntry; + if (_this.built) { + _context7.next = 3; + break; + } + throw new Error("Transaction has not yet been assembled or simulated"); + case 3: + if (!(authorizeEntry === _stellarBase.authorizeEntry)) { + _context7.next = 11; + break; + } + needsNonInvokerSigningBy = _this.needsNonInvokerSigningBy(); + if (!(needsNonInvokerSigningBy.length === 0)) { + _context7.next = 7; + break; + } + throw new AssembledTransaction.Errors.NoUnsignedNonInvokerAuthEntries("No unsigned non-invoker auth entries; maybe you already signed?"); + case 7: + if (!(needsNonInvokerSigningBy.indexOf(address !== null && address !== void 0 ? address : "") === -1)) { + _context7.next = 9; + break; + } + throw new AssembledTransaction.Errors.NoSignatureNeeded("No auth entries for public key \"".concat(address, "\"")); + case 9: + if (signAuthEntry) { + _context7.next = 11; + break; + } + throw new AssembledTransaction.Errors.NoSigner("You must provide `signAuthEntry` or a custom `authorizeEntry`"); + case 11: + rawInvokeHostFunctionOp = _this.built.operations[0]; + authEntries = (_rawInvokeHostFunctio2 = rawInvokeHostFunctionOp.auth) !== null && _rawInvokeHostFunctio2 !== void 0 ? _rawInvokeHostFunctio2 : []; + _iterator = _createForOfIteratorHelper(authEntries.entries()); + _context7.prev = 14; + _loop = _regeneratorRuntime().mark(function _loop() { + var _step$value, i, entry, credentials, authEntryAddress, sign; + return _regeneratorRuntime().wrap(function _loop$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _step$value = _slicedToArray(_step.value, 2), i = _step$value[0], entry = _step$value[1]; + credentials = _stellarBase.xdr.SorobanCredentials.fromXDR(entry.credentials().toXDR()); + if (!(credentials.switch() !== _stellarBase.xdr.SorobanCredentialsType.sorobanCredentialsAddress())) { + _context6.next = 4; + break; + } + return _context6.abrupt("return", 0); + case 4: + authEntryAddress = _stellarBase.Address.fromScAddress(credentials.address().address()).toString(); + if (!(authEntryAddress !== address)) { + _context6.next = 7; + break; + } + return _context6.abrupt("return", 0); + case 7: + sign = signAuthEntry !== null && signAuthEntry !== void 0 ? signAuthEntry : Promise.resolve; + _context6.t0 = authorizeEntry; + _context6.t1 = entry; + _context6.t2 = function () { + var _ref11 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(preimage) { + var _yield$sign, signedAuthEntry, error; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return sign(preimage.toXDR("base64"), { + address: address + }); + case 2: + _yield$sign = _context5.sent; + signedAuthEntry = _yield$sign.signedAuthEntry; + error = _yield$sign.error; + _this.handleWalletError(error); + return _context5.abrupt("return", Buffer.from(signedAuthEntry, "base64")); + case 7: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x) { + return _ref11.apply(this, arguments); + }; + }(); + _context6.next = 13; + return expiration; + case 13: + _context6.t3 = _context6.sent; + _context6.t4 = _this.options.networkPassphrase; + _context6.next = 17; + return (0, _context6.t0)(_context6.t1, _context6.t2, _context6.t3, _context6.t4); + case 17: + authEntries[i] = _context6.sent; + case 18: + case "end": + return _context6.stop(); + } + }, _loop); + }); + _iterator.s(); + case 17: + if ((_step = _iterator.n()).done) { + _context7.next = 24; + break; + } + return _context7.delegateYield(_loop(), "t0", 19); + case 19: + _ret = _context7.t0; + if (!(_ret === 0)) { + _context7.next = 22; + break; + } + return _context7.abrupt("continue", 22); + case 22: + _context7.next = 17; + break; + case 24: + _context7.next = 29; + break; + case 26: + _context7.prev = 26; + _context7.t1 = _context7["catch"](14); + _iterator.e(_context7.t1); + case 29: + _context7.prev = 29; + _iterator.f(); + return _context7.finish(29); + case 32: + case "end": + return _context7.stop(); + } + }, _callee6, null, [[14, 26, 29, 32]]); + }))); + this.options = options; + this.options.simulate = (_this$options$simulat = this.options.simulate) !== null && _this$options$simulat !== void 0 ? _this$options$simulat : true; + this.server = new _rpc.Server(this.options.rpcUrl, { + allowHttp: (_this$options$allowHt = this.options.allowHttp) !== null && _this$options$allowHt !== void 0 ? _this$options$allowHt : false + }); + } + return _createClass(AssembledTransaction, [{ + key: "toJSON", + value: function toJSON() { + var _this$built; + return JSON.stringify({ + method: this.options.method, + tx: (_this$built = this.built) === null || _this$built === void 0 ? void 0 : _this$built.toXDR(), + simulationResult: { + auth: this.simulationData.result.auth.map(function (a) { + return a.toXDR("base64"); + }), + retval: this.simulationData.result.retval.toXDR("base64") + }, + simulationTransactionData: this.simulationData.transactionData.toXDR("base64") + }); + } + }, { + key: "toXDR", + value: function toXDR() { + var _this$built2; + if (!this.built) throw new Error("Transaction has not yet been simulated; " + "call `AssembledTransaction.simulate` first."); + return (_this$built2 = this.built) === null || _this$built2 === void 0 ? void 0 : _this$built2.toEnvelope().toXDR('base64'); + } + }, { + key: "handleWalletError", + value: function handleWalletError(error) { + if (!error) return; + var message = error.message, + code = error.code; + var fullMessage = "".concat(message).concat(error.ext ? " (".concat(error.ext.join(', '), ")") : ''); + switch (code) { + case -1: + throw new AssembledTransaction.Errors.InternalWalletError(fullMessage); + case -2: + throw new AssembledTransaction.Errors.ExternalServiceError(fullMessage); + case -3: + throw new AssembledTransaction.Errors.InvalidClientRequest(fullMessage); + case -4: + throw new AssembledTransaction.Errors.UserRejected(fullMessage); + default: + throw new Error("Unhandled error: ".concat(fullMessage)); + } + } + }, { + key: "simulationData", + get: function get() { + var _simulation$result; + if (this.simulationResult && this.simulationTransactionData) { + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + var simulation = this.simulation; + if (!simulation) { + throw new AssembledTransaction.Errors.NotYetSimulated("Transaction has not yet been simulated"); + } + if (_api.Api.isSimulationError(simulation)) { + throw new AssembledTransaction.Errors.SimulationFailed("Transaction simulation failed: \"".concat(simulation.error, "\"")); + } + if (_api.Api.isSimulationRestore(simulation)) { + throw new AssembledTransaction.Errors.ExpiredState("You need to restore some contract state before you can invoke this method.\n" + 'You can set `restore` to true in the method options in order to ' + 'automatically restore the contract state when needed.'); + } + this.simulationResult = (_simulation$result = simulation.result) !== null && _simulation$result !== void 0 ? _simulation$result : { + auth: [], + retval: _stellarBase.xdr.ScVal.scvVoid() + }; + this.simulationTransactionData = simulation.transactionData.build(); + return { + result: this.simulationResult, + transactionData: this.simulationTransactionData + }; + } + }, { + key: "result", + get: function get() { + try { + if (!this.simulationData.result) { + throw new Error("No simulation result!"); + } + return this.options.parseResultXdr(this.simulationData.result.retval); + } catch (e) { + if (!(0, _utils.implementsToString)(e)) throw e; + var err = this.parseError(e.toString()); + if (err) return err; + throw e; + } + } + }, { + key: "parseError", + value: function parseError(errorMessage) { + if (!this.options.errorTypes) return undefined; + var match = errorMessage.match(_utils.contractErrorPattern); + if (!match) return undefined; + var i = parseInt(match[1], 10); + var err = this.options.errorTypes[i]; + if (!err) return undefined; + return new _rust_result.Err(err); + } + }, { + key: "send", + value: (function () { + var _send = _asyncToGenerator(_regeneratorRuntime().mark(function _callee7() { + var sent; + return _regeneratorRuntime().wrap(function _callee7$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (this.signed) { + _context8.next = 2; + break; + } + throw new Error("The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead."); + case 2: + _context8.next = 4; + return _sent_transaction.SentTransaction.init(this); + case 4: + sent = _context8.sent; + return _context8.abrupt("return", sent); + case 6: + case "end": + return _context8.stop(); + } + }, _callee7, this); + })); + function send() { + return _send.apply(this, arguments); + } + return send; + }()) + }, { + key: "isReadCall", + get: function get() { + var authsCount = this.simulationData.result.auth.length; + var writeLength = this.simulationData.transactionData.resources().footprint().readWrite().length; + return authsCount === 0 && writeLength === 0; + } + }, { + key: "restoreFootprint", + value: (function () { + var _restoreFootprint = _asyncToGenerator(_regeneratorRuntime().mark(function _callee8(restorePreamble, account) { + var _account; + var restoreTx, sentTransaction; + return _regeneratorRuntime().wrap(function _callee8$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + if (this.options.signTransaction) { + _context9.next = 2; + break; + } + throw new Error("For automatic restore to work you must provide a signTransaction function when initializing your Client"); + case 2: + if (!((_account = account) !== null && _account !== void 0)) { + _context9.next = 6; + break; + } + _context9.t0 = _account; + _context9.next = 9; + break; + case 6: + _context9.next = 8; + return (0, _utils.getAccount)(this.options, this.server); + case 8: + _context9.t0 = _context9.sent; + case 9: + account = _context9.t0; + _context9.next = 12; + return AssembledTransaction.buildFootprintRestoreTransaction(_objectSpread({}, this.options), restorePreamble.transactionData, account, restorePreamble.minResourceFee); + case 12: + restoreTx = _context9.sent; + _context9.next = 15; + return restoreTx.signAndSend(); + case 15: + sentTransaction = _context9.sent; + if (sentTransaction.getTransactionResponse) { + _context9.next = 18; + break; + } + throw new AssembledTransaction.Errors.RestorationFailure("The attempt at automatic restore failed. \n".concat(JSON.stringify(sentTransaction))); + case 18: + return _context9.abrupt("return", sentTransaction.getTransactionResponse); + case 19: + case "end": + return _context9.stop(); + } + }, _callee8, this); + })); + function restoreFootprint(_x2, _x3) { + return _restoreFootprint.apply(this, arguments); + } + return restoreFootprint; + }()) + }], [{ + key: "fromJSON", + value: function fromJSON(options, _ref12) { + var tx = _ref12.tx, + simulationResult = _ref12.simulationResult, + simulationTransactionData = _ref12.simulationTransactionData; + var txn = new AssembledTransaction(options); + txn.built = _stellarBase.TransactionBuilder.fromXDR(tx, options.networkPassphrase); + txn.simulationResult = { + auth: simulationResult.auth.map(function (a) { + return _stellarBase.xdr.SorobanAuthorizationEntry.fromXDR(a, "base64"); + }), + retval: _stellarBase.xdr.ScVal.fromXDR(simulationResult.retval, "base64") + }; + txn.simulationTransactionData = _stellarBase.xdr.SorobanTransactionData.fromXDR(simulationTransactionData, "base64"); + return txn; + } + }, { + key: "fromXDR", + value: function fromXDR(options, encodedXDR, spec) { + var _operation$func; + var envelope = _stellarBase.xdr.TransactionEnvelope.fromXDR(encodedXDR, "base64"); + var built = _stellarBase.TransactionBuilder.fromXDR(envelope, options.networkPassphrase); + var operation = built.operations[0]; + if (!(operation !== null && operation !== void 0 && (_operation$func = operation.func) !== null && _operation$func !== void 0 && _operation$func.value) || typeof operation.func.value !== 'function') { + throw new Error("Could not extract the method from the transaction envelope."); + } + var invokeContractArgs = operation.func.value(); + if (!(invokeContractArgs !== null && invokeContractArgs !== void 0 && invokeContractArgs.functionName)) { + throw new Error("Could not extract the method name from the transaction envelope."); + } + var method = invokeContractArgs.functionName().toString('utf-8'); + var txn = new AssembledTransaction(_objectSpread(_objectSpread({}, options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + txn.built = built; + return txn; + } + }, { + key: "build", + value: function build(options) { + var _options$args; + var contract = new _stellarBase.Contract(options.contractId); + return AssembledTransaction.buildWithOp(contract.call.apply(contract, [options.method].concat(_toConsumableArray((_options$args = options.args) !== null && _options$args !== void 0 ? _options$args : []))), options); + } + }, { + key: "buildWithOp", + value: (function () { + var _buildWithOp = _asyncToGenerator(_regeneratorRuntime().mark(function _callee9(operation, options) { + var _options$fee, _options$timeoutInSec; + var tx, account; + return _regeneratorRuntime().wrap(function _callee9$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + tx = new AssembledTransaction(options); + _context10.next = 3; + return (0, _utils.getAccount)(options, tx.server); + case 3: + account = _context10.sent; + tx.raw = new _stellarBase.TransactionBuilder(account, { + fee: (_options$fee = options.fee) !== null && _options$fee !== void 0 ? _options$fee : _stellarBase.BASE_FEE, + networkPassphrase: options.networkPassphrase + }).setTimeout((_options$timeoutInSec = options.timeoutInSeconds) !== null && _options$timeoutInSec !== void 0 ? _options$timeoutInSec : _types.DEFAULT_TIMEOUT).addOperation(operation); + if (!options.simulate) { + _context10.next = 8; + break; + } + _context10.next = 8; + return tx.simulate(); + case 8: + return _context10.abrupt("return", tx); + case 9: + case "end": + return _context10.stop(); + } + }, _callee9); + })); + function buildWithOp(_x4, _x5) { + return _buildWithOp.apply(this, arguments); + } + return buildWithOp; + }()) + }, { + key: "buildFootprintRestoreTransaction", + value: function () { + var _buildFootprintRestoreTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee10(options, sorobanData, account, fee) { + var _options$timeoutInSec2; + var tx; + return _regeneratorRuntime().wrap(function _callee10$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + tx = new AssembledTransaction(options); + tx.raw = new _stellarBase.TransactionBuilder(account, { + fee: fee, + networkPassphrase: options.networkPassphrase + }).setSorobanData(sorobanData instanceof _stellarBase.SorobanDataBuilder ? sorobanData.build() : sorobanData).addOperation(_stellarBase.Operation.restoreFootprint({})).setTimeout((_options$timeoutInSec2 = options.timeoutInSeconds) !== null && _options$timeoutInSec2 !== void 0 ? _options$timeoutInSec2 : _types.DEFAULT_TIMEOUT); + _context11.next = 4; + return tx.simulate({ + restore: false + }); + case 4: + return _context11.abrupt("return", tx); + case 5: + case "end": + return _context11.stop(); + } + }, _callee10); + })); + function buildFootprintRestoreTransaction(_x6, _x7, _x8, _x9) { + return _buildFootprintRestoreTransaction.apply(this, arguments); + } + return buildFootprintRestoreTransaction; + }() + }]); +}(); +_defineProperty(AssembledTransaction, "Errors", { + ExpiredState: function (_Error) { + function ExpiredStateError() { + _classCallCheck(this, ExpiredStateError); + return _callSuper(this, ExpiredStateError, arguments); + } + _inherits(ExpiredStateError, _Error); + return _createClass(ExpiredStateError); + }(_wrapNativeSuper(Error)), + RestorationFailure: function (_Error2) { + function RestoreFailureError() { + _classCallCheck(this, RestoreFailureError); + return _callSuper(this, RestoreFailureError, arguments); + } + _inherits(RestoreFailureError, _Error2); + return _createClass(RestoreFailureError); + }(_wrapNativeSuper(Error)), + NeedsMoreSignatures: function (_Error3) { + function NeedsMoreSignaturesError() { + _classCallCheck(this, NeedsMoreSignaturesError); + return _callSuper(this, NeedsMoreSignaturesError, arguments); + } + _inherits(NeedsMoreSignaturesError, _Error3); + return _createClass(NeedsMoreSignaturesError); + }(_wrapNativeSuper(Error)), + NoSignatureNeeded: function (_Error4) { + function NoSignatureNeededError() { + _classCallCheck(this, NoSignatureNeededError); + return _callSuper(this, NoSignatureNeededError, arguments); + } + _inherits(NoSignatureNeededError, _Error4); + return _createClass(NoSignatureNeededError); + }(_wrapNativeSuper(Error)), + NoUnsignedNonInvokerAuthEntries: function (_Error5) { + function NoUnsignedNonInvokerAuthEntriesError() { + _classCallCheck(this, NoUnsignedNonInvokerAuthEntriesError); + return _callSuper(this, NoUnsignedNonInvokerAuthEntriesError, arguments); + } + _inherits(NoUnsignedNonInvokerAuthEntriesError, _Error5); + return _createClass(NoUnsignedNonInvokerAuthEntriesError); + }(_wrapNativeSuper(Error)), + NoSigner: function (_Error6) { + function NoSignerError() { + _classCallCheck(this, NoSignerError); + return _callSuper(this, NoSignerError, arguments); + } + _inherits(NoSignerError, _Error6); + return _createClass(NoSignerError); + }(_wrapNativeSuper(Error)), + NotYetSimulated: function (_Error7) { + function NotYetSimulatedError() { + _classCallCheck(this, NotYetSimulatedError); + return _callSuper(this, NotYetSimulatedError, arguments); + } + _inherits(NotYetSimulatedError, _Error7); + return _createClass(NotYetSimulatedError); + }(_wrapNativeSuper(Error)), + FakeAccount: function (_Error8) { + function FakeAccountError() { + _classCallCheck(this, FakeAccountError); + return _callSuper(this, FakeAccountError, arguments); + } + _inherits(FakeAccountError, _Error8); + return _createClass(FakeAccountError); + }(_wrapNativeSuper(Error)), + SimulationFailed: function (_Error9) { + function SimulationFailedError() { + _classCallCheck(this, SimulationFailedError); + return _callSuper(this, SimulationFailedError, arguments); + } + _inherits(SimulationFailedError, _Error9); + return _createClass(SimulationFailedError); + }(_wrapNativeSuper(Error)), + InternalWalletError: function (_Error10) { + function InternalWalletError() { + _classCallCheck(this, InternalWalletError); + return _callSuper(this, InternalWalletError, arguments); + } + _inherits(InternalWalletError, _Error10); + return _createClass(InternalWalletError); + }(_wrapNativeSuper(Error)), + ExternalServiceError: function (_Error11) { + function ExternalServiceError() { + _classCallCheck(this, ExternalServiceError); + return _callSuper(this, ExternalServiceError, arguments); + } + _inherits(ExternalServiceError, _Error11); + return _createClass(ExternalServiceError); + }(_wrapNativeSuper(Error)), + InvalidClientRequest: function (_Error12) { + function InvalidClientRequestError() { + _classCallCheck(this, InvalidClientRequestError); + return _callSuper(this, InvalidClientRequestError, arguments); + } + _inherits(InvalidClientRequestError, _Error12); + return _createClass(InvalidClientRequestError); + }(_wrapNativeSuper(Error)), + UserRejected: function (_Error13) { + function UserRejectedError() { + _classCallCheck(this, UserRejectedError); + return _callSuper(this, UserRejectedError, arguments); + } + _inherits(UserRejectedError, _Error13); + return _createClass(UserRejectedError); + }(_wrapNativeSuper(Error)) +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/basic_node_signer.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/basic_node_signer.d.ts new file mode 100644 index 000000000..b82cc36f3 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/basic_node_signer.d.ts @@ -0,0 +1,18 @@ +import { Keypair } from "@stellar/stellar-base"; +import { SignAuthEntry, SignTransaction } from "./types"; +/** + * For use with {@link Client} and {@link module:contract.AssembledTransaction}. + * Implements `signTransaction` and `signAuthEntry` with signatures expected by + * those classes. This is useful for testing and maybe some simple Node + * applications. Feel free to use this as a starting point for your own + * Wallet/TransactionSigner implementation. + * + * @memberof module:contract + * + * @param {Keypair} keypair {@link Keypair} to use to sign the transaction or auth entry + * @param {string} networkPassphrase passphrase of network to sign for + */ +export declare const basicNodeSigner: (keypair: Keypair, networkPassphrase: string) => { + signTransaction: SignTransaction; + signAuthEntry: SignAuthEntry; +}; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/basic_node_signer.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/basic_node_signer.js new file mode 100644 index 000000000..b91d3149a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/basic_node_signer.js @@ -0,0 +1,60 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.basicNodeSigner = void 0; +var _stellarBase = require("@stellar/stellar-base"); +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +var basicNodeSigner = exports.basicNodeSigner = function basicNodeSigner(keypair, networkPassphrase) { + return { + signTransaction: function () { + var _signTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(xdr, opts) { + var t; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + t = _stellarBase.TransactionBuilder.fromXDR(xdr, (opts === null || opts === void 0 ? void 0 : opts.networkPassphrase) || networkPassphrase); + t.sign(keypair); + return _context.abrupt("return", { + signedTxXdr: t.toXDR(), + signerAddress: keypair.publicKey() + }); + case 3: + case "end": + return _context.stop(); + } + }, _callee); + })); + function signTransaction(_x, _x2) { + return _signTransaction.apply(this, arguments); + } + return signTransaction; + }(), + signAuthEntry: function () { + var _signAuthEntry = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(authEntry) { + var signedAuthEntry; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + signedAuthEntry = keypair.sign((0, _stellarBase.hash)(Buffer.from(authEntry, "base64"))).toString("base64"); + return _context2.abrupt("return", { + signedAuthEntry: signedAuthEntry, + signerAddress: keypair.publicKey() + }); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function signAuthEntry(_x3) { + return _signAuthEntry.apply(this, arguments); + } + return signAuthEntry; + }() + }; +}; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/client.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/client.d.ts new file mode 100644 index 000000000..c41fb7d25 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/client.d.ts @@ -0,0 +1,64 @@ +import { Spec } from "./spec"; +import { AssembledTransaction } from "./assembled_transaction"; +import type { ClientOptions, MethodOptions } from "./types"; +/** + * Generate a class from the contract spec that where each contract method + * gets included with an identical name. + * + * Each method returns an {@link module:contract.AssembledTransaction | AssembledTransaction} that can + * be used to modify, simulate, decode results, and possibly sign, & submit the + * transaction. + * + * @memberof module:contract + * + * @class + * @param {module:contract.Spec} spec {@link Spec} to construct a Client for + * @param {ClientOptions} options see {@link ClientOptions} + */ +export declare class Client { + readonly spec: Spec; + readonly options: ClientOptions; + static deploy( + /** Constructor/Initialization Args for the contract's `__constructor` method */ + args: Record | null, + /** Options for initalizing a Client as well as for calling a method, with extras specific to deploying. */ + options: MethodOptions & Omit & { + /** The hash of the Wasm blob, which must already be installed on-chain. */ + wasmHash: Buffer | string; + /** Salt used to generate the contract's ID. Passed through to {@link Operation.createCustomContract}. Default: random. */ + salt?: Buffer | Uint8Array; + /** The format used to decode `wasmHash`, if it's provided as a string. */ + format?: "hex" | "base64"; + }): Promise>; + constructor(spec: Spec, options: ClientOptions); + /** + * Generates a Client instance from the provided ClientOptions and the contract's wasm hash. + * The wasmHash can be provided in either hex or base64 format. + * + * @param {Buffer | string} wasmHash The hash of the contract's wasm binary, in either hex or base64 format. + * @param {ClientOptions} options The ClientOptions object containing the necessary configuration, including the rpcUrl. + * @param {('hex' | 'base64')} [format='hex'] The format of the provided wasmHash, either "hex" or "base64". Defaults to "hex". + * @returns {Promise} A Promise that resolves to a Client instance. + * @throws {TypeError} If the provided options object does not contain an rpcUrl. + */ + static fromWasmHash(wasmHash: Buffer | string, options: ClientOptions, format?: "hex" | "base64"): Promise; + /** + * Generates a Client instance from the provided ClientOptions and the contract's wasm binary. + * + * @param {Buffer} wasm The contract's wasm binary as a Buffer. + * @param {ClientOptions} options The ClientOptions object containing the necessary configuration. + * @returns {Promise} A Promise that resolves to a Client instance. + * @throws {Error} If the contract spec cannot be obtained from the provided wasm binary. + */ + static fromWasm(wasm: Buffer, options: ClientOptions): Promise; + /** + * Generates a Client instance from the provided ClientOptions, which must include the contractId and rpcUrl. + * + * @param {ClientOptions} options The ClientOptions object containing the necessary configuration, including the contractId and rpcUrl. + * @returns {Promise} A Promise that resolves to a Client instance. + * @throws {TypeError} If the provided options object does not contain both rpcUrl and contractId. + */ + static from(options: ClientOptions): Promise; + txFromJSON: (json: string) => AssembledTransaction; + txFromXDR: (xdrBase64: string) => AssembledTransaction; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/client.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/client.js new file mode 100644 index 000000000..4caa08ec6 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/client.js @@ -0,0 +1,291 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Client = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _spec = require("./spec"); +var _rpc = require("../rpc"); +var _assembled_transaction = require("./assembled_transaction"); +var _utils = require("./utils"); +var _excluded = ["method"], + _excluded2 = ["wasmHash", "salt", "format", "fee", "timeoutInSeconds", "simulate"]; +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } +function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +var CONSTRUCTOR_FUNC = "__constructor"; +function specFromWasm(_x) { + return _specFromWasm.apply(this, arguments); +} +function _specFromWasm() { + _specFromWasm = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(wasm) { + var wasmModule, xdrSections, bufferSection, specEntryArray, spec; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return WebAssembly.compile(wasm); + case 2: + wasmModule = _context5.sent; + xdrSections = WebAssembly.Module.customSections(wasmModule, "contractspecv0"); + if (!(xdrSections.length === 0)) { + _context5.next = 6; + break; + } + throw new Error("Could not obtain contract spec from wasm"); + case 6: + bufferSection = Buffer.from(xdrSections[0]); + specEntryArray = (0, _utils.processSpecEntryStream)(bufferSection); + spec = new _spec.Spec(specEntryArray); + return _context5.abrupt("return", spec); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _specFromWasm.apply(this, arguments); +} +function specFromWasmHash(_x2, _x3) { + return _specFromWasmHash.apply(this, arguments); +} +function _specFromWasmHash() { + _specFromWasmHash = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + format = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context6.next = 3; + break; + } + throw new TypeError("options must contain rpcUrl"); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new _rpc.Server(rpcUrl, serverOpts); + _context6.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context6.sent; + return _context6.abrupt("return", specFromWasm(wasm)); + case 10: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _specFromWasmHash.apply(this, arguments); +} +var Client = exports.Client = function () { + function Client(spec, options) { + var _this = this; + _classCallCheck(this, Client); + _defineProperty(this, "txFromJSON", function (json) { + var _JSON$parse = JSON.parse(json), + method = _JSON$parse.method, + tx = _objectWithoutProperties(_JSON$parse, _excluded); + return _assembled_transaction.AssembledTransaction.fromJSON(_objectSpread(_objectSpread({}, _this.options), {}, { + method: method, + parseResultXdr: function parseResultXdr(result) { + return _this.spec.funcResToNative(method, result); + } + }), tx); + }); + _defineProperty(this, "txFromXDR", function (xdrBase64) { + return _assembled_transaction.AssembledTransaction.fromXDR(_this.options, xdrBase64, _this.spec); + }); + this.spec = spec; + this.options = options; + this.spec.funcs().forEach(function (xdrFn) { + var method = xdrFn.name().toString(); + if (method === CONSTRUCTOR_FUNC) { + return; + } + var assembleTransaction = function assembleTransaction(args, methodOptions) { + return _assembled_transaction.AssembledTransaction.build(_objectSpread(_objectSpread(_objectSpread({ + method: method, + args: args && spec.funcArgsToScVals(method, args) + }, options), methodOptions), {}, { + errorTypes: spec.errorCases().reduce(function (acc, curr) { + return _objectSpread(_objectSpread({}, acc), {}, _defineProperty({}, curr.value(), { + message: curr.doc().toString() + })); + }, {}), + parseResultXdr: function parseResultXdr(result) { + return spec.funcResToNative(method, result); + } + })); + }; + _this[method] = spec.getFunc(method).inputs().length === 0 ? function (opts) { + return assembleTransaction(undefined, opts); + } : assembleTransaction; + }); + } + return _createClass(Client, null, [{ + key: "deploy", + value: function () { + var _deploy = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(args, options) { + var wasmHash, salt, format, fee, timeoutInSeconds, simulate, clientOptions, spec, operation; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + wasmHash = options.wasmHash, salt = options.salt, format = options.format, fee = options.fee, timeoutInSeconds = options.timeoutInSeconds, simulate = options.simulate, clientOptions = _objectWithoutProperties(options, _excluded2); + _context.next = 3; + return specFromWasmHash(wasmHash, clientOptions, format); + case 3: + spec = _context.sent; + operation = _stellarBase.Operation.createCustomContract({ + address: new _stellarBase.Address(options.publicKey), + wasmHash: typeof wasmHash === "string" ? Buffer.from(wasmHash, format !== null && format !== void 0 ? format : "hex") : wasmHash, + salt: salt, + constructorArgs: args ? spec.funcArgsToScVals(CONSTRUCTOR_FUNC, args) : [] + }); + return _context.abrupt("return", _assembled_transaction.AssembledTransaction.buildWithOp(operation, _objectSpread(_objectSpread({ + fee: fee, + timeoutInSeconds: timeoutInSeconds, + simulate: simulate + }, clientOptions), {}, { + contractId: "ignored", + method: CONSTRUCTOR_FUNC, + parseResultXdr: function parseResultXdr(result) { + return new Client(spec, _objectSpread(_objectSpread({}, clientOptions), {}, { + contractId: _stellarBase.Address.fromScVal(result).toString() + })); + } + }))); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + function deploy(_x4, _x5) { + return _deploy.apply(this, arguments); + } + return deploy; + }() + }, { + key: "fromWasmHash", + value: (function () { + var _fromWasmHash = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(wasmHash, options) { + var format, + rpcUrl, + allowHttp, + serverOpts, + server, + wasm, + _args2 = arguments; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + format = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : "hex"; + if (!(!options || !options.rpcUrl)) { + _context2.next = 3; + break; + } + throw new TypeError('options must contain rpcUrl'); + case 3: + rpcUrl = options.rpcUrl, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new _rpc.Server(rpcUrl, serverOpts); + _context2.next = 8; + return server.getContractWasmByHash(wasmHash, format); + case 8: + wasm = _context2.sent; + return _context2.abrupt("return", Client.fromWasm(wasm, options)); + case 10: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function fromWasmHash(_x6, _x7) { + return _fromWasmHash.apply(this, arguments); + } + return fromWasmHash; + }()) + }, { + key: "fromWasm", + value: (function () { + var _fromWasm = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(wasm, options) { + var spec; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return specFromWasm(wasm); + case 2: + spec = _context3.sent; + return _context3.abrupt("return", new Client(spec, options)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + function fromWasm(_x8, _x9) { + return _fromWasm.apply(this, arguments); + } + return fromWasm; + }()) + }, { + key: "from", + value: (function () { + var _from = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(options) { + var rpcUrl, contractId, allowHttp, serverOpts, server, wasm; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(!options || !options.rpcUrl || !options.contractId)) { + _context4.next = 2; + break; + } + throw new TypeError('options must contain rpcUrl and contractId'); + case 2: + rpcUrl = options.rpcUrl, contractId = options.contractId, allowHttp = options.allowHttp; + serverOpts = { + allowHttp: allowHttp + }; + server = new _rpc.Server(rpcUrl, serverOpts); + _context4.next = 7; + return server.getContractWasmByContractId(contractId); + case 7: + wasm = _context4.sent; + return _context4.abrupt("return", Client.fromWasm(wasm, options)); + case 9: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function from(_x10) { + return _from.apply(this, arguments); + } + return from; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/index.d.ts new file mode 100644 index 000000000..8b9e1dc5e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/index.d.ts @@ -0,0 +1,7 @@ +export * from "./assembled_transaction"; +export * from "./basic_node_signer"; +export * from "./client"; +export * from "./rust_result"; +export * from "./sent_transaction"; +export * from "./spec"; +export * from "./types"; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/index.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/index.js new file mode 100644 index 000000000..9a10eddfc --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/index.js @@ -0,0 +1,82 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _assembled_transaction = require("./assembled_transaction"); +Object.keys(_assembled_transaction).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _assembled_transaction[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _assembled_transaction[key]; + } + }); +}); +var _basic_node_signer = require("./basic_node_signer"); +Object.keys(_basic_node_signer).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _basic_node_signer[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _basic_node_signer[key]; + } + }); +}); +var _client = require("./client"); +Object.keys(_client).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _client[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _client[key]; + } + }); +}); +var _rust_result = require("./rust_result"); +Object.keys(_rust_result).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _rust_result[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _rust_result[key]; + } + }); +}); +var _sent_transaction = require("./sent_transaction"); +Object.keys(_sent_transaction).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _sent_transaction[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _sent_transaction[key]; + } + }); +}); +var _spec = require("./spec"); +Object.keys(_spec).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _spec[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _spec[key]; + } + }); +}); +var _types = require("./types"); +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _types[key]; + } + }); +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/rust_result.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/rust_result.d.ts new file mode 100644 index 000000000..f72a123e1 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/rust_result.d.ts @@ -0,0 +1,81 @@ +/** + * A minimal implementation of Rust's `Result` type. Used for contract + * methods that return Results, to maintain their distinction from methods + * that simply either return a value or throw. + * + * #### Why is this needed? + * + * This is used by {@link module:contract.Spec | `ContractSpec`} and + * {@link module:contract.AssembledTransaction | `AssembledTransaction`} when + * parsing values return by contracts. + * + * Contract methods can be implemented to return simple values, in which case + * they can also throw errors. This matches JavaScript's most idiomatic + * workflow, using `try...catch` blocks. + * + * But Rust also gives the flexibility of returning `Result` types. And Soroban + * contracts further support this with the `#[contracterror]` macro. Should + * JavaScript calls to such methods ignore all of that, and just flatten this + * extra info down to the same `try...catch` flow as other methods? We're not + * sure. + * + * For now, we've added this minimal implementation of Rust's `Result` logic, + * which exports the `Result` interface and its associated implementations, + * `Ok` and `Err`. This allows `ContractSpec` and `AssembledTransaction` to + * work together to duplicate the contract's Rust logic, always returning + * `Result` types for contract methods that are implemented to do so. + * + * In the future, if this feels too un-idiomatic for JavaScript, we can always + * remove this and flatten all JS calls to `try...catch`. Easier to remove this + * logic later than it would be to add it. + * + * @memberof module:contract + */ +export interface Result { + unwrap(): T; + unwrapErr(): E; + isOk(): boolean; + isErr(): boolean; +} +/** + * Error interface containing the error message. Matches Rust's implementation. + * Part of implementing {@link module:contract.Result | Result}, a minimal + * implementation of Rust's `Result` type. Used for contract methods that return + * Results, to maintain their distinction from methods that simply either return + * a value or throw. + * + * @memberof module:contract + */ +export interface ErrorMessage { + message: string; +} +/** + * Part of implementing {@link module:contract.Result | Result}, a minimal + * implementation of Rust's `Result` type. Used for contract methods that return + * Results, to maintain their distinction from methods that simply either return + * a value or throw. + * @private + */ +export declare class Ok implements Result { + readonly value: T; + constructor(value: T); + unwrapErr(): never; + unwrap(): T; + isOk(): boolean; + isErr(): boolean; +} +/** + * Part of implementing {@link module:contract.Result | Result}, a minimal + * implementation of Rust's `Result` type. Used for contract methods that return + * Results, to maintain their distinction from methods that simply either return + * a value or throw. + * @private + */ +export declare class Err implements Result { + readonly error: E; + constructor(error: E); + unwrapErr(): E; + unwrap(): never; + isOk(): boolean; + isErr(): boolean; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/rust_result.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/rust_result.js new file mode 100644 index 000000000..5cbad1179 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/rust_result.js @@ -0,0 +1,66 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Ok = exports.Err = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Ok = exports.Ok = function () { + function Ok(value) { + _classCallCheck(this, Ok); + this.value = value; + } + return _createClass(Ok, [{ + key: "unwrapErr", + value: function unwrapErr() { + throw new Error("No error"); + } + }, { + key: "unwrap", + value: function unwrap() { + return this.value; + } + }, { + key: "isOk", + value: function isOk() { + return true; + } + }, { + key: "isErr", + value: function isErr() { + return false; + } + }]); +}(); +var Err = exports.Err = function () { + function Err(error) { + _classCallCheck(this, Err); + this.error = error; + } + return _createClass(Err, [{ + key: "unwrapErr", + value: function unwrapErr() { + return this.error; + } + }, { + key: "unwrap", + value: function unwrap() { + throw new Error(this.error.message); + } + }, { + key: "isOk", + value: function isOk() { + return false; + } + }, { + key: "isErr", + value: function isErr() { + return true; + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/sent_transaction.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/sent_transaction.d.ts new file mode 100644 index 000000000..ab3234a2d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/sent_transaction.d.ts @@ -0,0 +1,84 @@ +import { Server } from "../rpc"; +import { Api } from "../rpc/api"; +import type { AssembledTransaction } from "./assembled_transaction"; +/** + * A transaction that has been sent to the Soroban network. This happens in two steps: + * + * 1. `sendTransaction`: initial submission of the transaction to the network. + * If this step runs into problems, the attempt to sign and send will be + * aborted. You can see the result of this call in the + * `sendTransactionResponse` getter. + * 2. `getTransaction`: once the transaction has been submitted to the network + * successfully, you need to wait for it to finalize to get the result of the + * transaction. This will be retried with exponential backoff for + * {@link MethodOptions.timeoutInSeconds} seconds. See all attempts in + * `getTransactionResponseAll` and the most recent attempt in + * `getTransactionResponse`. + * + * @memberof module:contract + * @class + * + * @param {Function} signTransaction More info in {@link MethodOptions} + * @param {module:contract.AssembledTransaction} assembled {@link AssembledTransaction} from which this SentTransaction was initialized + */ +export declare class SentTransaction { + assembled: AssembledTransaction; + server: Server; + /** + * The result of calling `sendTransaction` to broadcast the transaction to the + * network. + */ + sendTransactionResponse?: Api.SendTransactionResponse; + /** + * If `sendTransaction` completes successfully (which means it has `status: 'PENDING'`), + * then `getTransaction` will be called in a loop for + * {@link MethodOptions.timeoutInSeconds} seconds. This array contains all + * the results of those calls. + */ + getTransactionResponseAll?: Api.GetTransactionResponse[]; + /** + * The most recent result of calling `getTransaction`, from the + * `getTransactionResponseAll` array. + */ + getTransactionResponse?: Api.GetTransactionResponse; + static Errors: { + SendFailed: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + SendResultOnly: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + TransactionStillPending: { + new (message?: string): { + name: string; + message: string; + stack?: string; + }; + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + stackTraceLimit: number; + }; + }; + constructor(assembled: AssembledTransaction); + /** + * Initialize a `SentTransaction` from `options` and a `signed` + * AssembledTransaction. This will also send the transaction to the network. + */ + static init: (assembled: AssembledTransaction) => Promise>; + private send; + get result(): T; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/sent_transaction.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/sent_transaction.js new file mode 100644 index 000000000..03d0948b5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/sent_transaction.js @@ -0,0 +1,151 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SentTransaction = void 0; +var _rpc = require("../rpc"); +var _api = require("../rpc/api"); +var _utils = require("./utils"); +var _types = require("./types"); +var _SentTransaction; +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var SentTransaction = exports.SentTransaction = function () { + function SentTransaction(assembled) { + var _this = this, + _this$assembled$optio2; + _classCallCheck(this, SentTransaction); + _defineProperty(this, "send", _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var _this$assembled$optio; + var hash, timeoutInSeconds; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return _this.server.sendTransaction(_this.assembled.signed); + case 2: + _this.sendTransactionResponse = _context.sent; + if (!(_this.sendTransactionResponse.status !== "PENDING")) { + _context.next = 5; + break; + } + throw new SentTransaction.Errors.SendFailed("Sending the transaction to the network failed!\n".concat(JSON.stringify(_this.sendTransactionResponse, null, 2))); + case 5: + hash = _this.sendTransactionResponse.hash; + timeoutInSeconds = (_this$assembled$optio = _this.assembled.options.timeoutInSeconds) !== null && _this$assembled$optio !== void 0 ? _this$assembled$optio : _types.DEFAULT_TIMEOUT; + _context.next = 9; + return (0, _utils.withExponentialBackoff)(function () { + return _this.server.getTransaction(hash); + }, function (resp) { + return resp.status === _api.Api.GetTransactionStatus.NOT_FOUND; + }, timeoutInSeconds); + case 9: + _this.getTransactionResponseAll = _context.sent; + _this.getTransactionResponse = _this.getTransactionResponseAll[_this.getTransactionResponseAll.length - 1]; + if (!(_this.getTransactionResponse.status === _api.Api.GetTransactionStatus.NOT_FOUND)) { + _context.next = 13; + break; + } + throw new SentTransaction.Errors.TransactionStillPending("Waited ".concat(timeoutInSeconds, " seconds for transaction to complete, but it did not. ") + "Returning anyway. Check the transaction status manually. " + "Sent transaction: ".concat(JSON.stringify(_this.sendTransactionResponse, null, 2), "\n") + "All attempts to get the result: ".concat(JSON.stringify(_this.getTransactionResponseAll, null, 2))); + case 13: + return _context.abrupt("return", _this); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + }))); + this.assembled = assembled; + this.server = new _rpc.Server(this.assembled.options.rpcUrl, { + allowHttp: (_this$assembled$optio2 = this.assembled.options.allowHttp) !== null && _this$assembled$optio2 !== void 0 ? _this$assembled$optio2 : false + }); + } + return _createClass(SentTransaction, [{ + key: "result", + get: function get() { + if ("getTransactionResponse" in this && this.getTransactionResponse) { + if ("returnValue" in this.getTransactionResponse) { + return this.assembled.options.parseResultXdr(this.getTransactionResponse.returnValue); + } + throw new Error("Transaction failed! Cannot parse result."); + } + if (this.sendTransactionResponse) { + var _this$sendTransaction; + var errorResult = (_this$sendTransaction = this.sendTransactionResponse.errorResult) === null || _this$sendTransaction === void 0 ? void 0 : _this$sendTransaction.result(); + if (errorResult) { + throw new SentTransaction.Errors.SendFailed("Transaction simulation looked correct, but attempting to send the transaction failed. Check `simulation` and `sendTransactionResponseAll` to troubleshoot. Decoded `sendTransactionResponse.errorResultXdr`: ".concat(errorResult)); + } + throw new SentTransaction.Errors.SendResultOnly("Transaction was sent to the network, but not yet awaited. No result to show. Await transaction completion with `getTransaction(sendTransactionResponse.hash)`"); + } + throw new Error("Sending transaction failed: ".concat(JSON.stringify(this.assembled.signed))); + } + }]); +}(); +_SentTransaction = SentTransaction; +_defineProperty(SentTransaction, "Errors", { + SendFailed: function (_Error) { + function SendFailedError() { + _classCallCheck(this, SendFailedError); + return _callSuper(this, SendFailedError, arguments); + } + _inherits(SendFailedError, _Error); + return _createClass(SendFailedError); + }(_wrapNativeSuper(Error)), + SendResultOnly: function (_Error2) { + function SendResultOnlyError() { + _classCallCheck(this, SendResultOnlyError); + return _callSuper(this, SendResultOnlyError, arguments); + } + _inherits(SendResultOnlyError, _Error2); + return _createClass(SendResultOnlyError); + }(_wrapNativeSuper(Error)), + TransactionStillPending: function (_Error3) { + function TransactionStillPendingError() { + _classCallCheck(this, TransactionStillPendingError); + return _callSuper(this, TransactionStillPendingError, arguments); + } + _inherits(TransactionStillPendingError, _Error3); + return _createClass(TransactionStillPendingError); + }(_wrapNativeSuper(Error)) +}); +_defineProperty(SentTransaction, "init", function () { + var _ref2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(assembled) { + var tx, sent; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + tx = new _SentTransaction(assembled); + _context2.next = 3; + return tx.send(); + case 3: + sent = _context2.sent; + return _context2.abrupt("return", sent); + case 5: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; +}()); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/spec.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/spec.d.ts new file mode 100644 index 000000000..737c8c464 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/spec.d.ts @@ -0,0 +1,152 @@ +import type { JSONSchema7 } from "json-schema"; +import { xdr } from "@stellar/stellar-base"; +export interface Union { + tag: string; + values?: T; +} +/** + * Provides a ContractSpec class which can contains the XDR types defined by the contract. + * This allows the class to be used to convert between native and raw `xdr.ScVal`s. + * + * Constructs a new ContractSpec from an array of XDR spec entries. + * + * @memberof module:contract + * @param {xdr.ScSpecEntry[] | string[]} entries the XDR spec entries + * @throws {Error} if entries is invalid + * + * @example + * const specEntries = [...]; // XDR spec entries of a smart contract + * const contractSpec = new ContractSpec(specEntries); + * + * // Convert native value to ScVal + * const args = { + * arg1: 'value1', + * arg2: 1234 + * }; + * const scArgs = contractSpec.funcArgsToScVals('funcName', args); + * + * // Call contract + * const resultScv = await callContract(contractId, 'funcName', scArgs); + * + * // Convert result ScVal back to native value + * const result = contractSpec.funcResToNative('funcName', resultScv); + * + * console.log(result); // {success: true} + */ +export declare class Spec { + /** + * The XDR spec entries. + */ + entries: xdr.ScSpecEntry[]; + constructor(entries: xdr.ScSpecEntry[] | string[]); + /** + * Gets the XDR functions from the spec. + * @returns {xdr.ScSpecFunctionV0[]} all contract functions + */ + funcs(): xdr.ScSpecFunctionV0[]; + /** + * Gets the XDR function spec for the given function name. + * + * @param {string} name the name of the function + * @returns {xdr.ScSpecFunctionV0} the function spec + * + * @throws {Error} if no function with the given name exists + */ + getFunc(name: string): xdr.ScSpecFunctionV0; + /** + * Converts native JS arguments to ScVals for calling a contract function. + * + * @param {string} name the name of the function + * @param {object} args the arguments object + * @returns {xdr.ScVal[]} the converted arguments + * + * @throws {Error} if argument is missing or incorrect type + * + * @example + * const args = { + * arg1: 'value1', + * arg2: 1234 + * }; + * const scArgs = contractSpec.funcArgsToScVals('funcName', args); + */ + funcArgsToScVals(name: string, args: object): xdr.ScVal[]; + /** + * Converts the result ScVal of a function call to a native JS value. + * + * @param {string} name the name of the function + * @param {xdr.ScVal | string} val_or_base64 the result ScVal or base64 encoded string + * @returns {any} the converted native value + * + * @throws {Error} if return type mismatch or invalid input + * + * @example + * const resultScv = 'AAA=='; // Base64 encoded ScVal + * const result = contractSpec.funcResToNative('funcName', resultScv); + */ + funcResToNative(name: string, val_or_base64: xdr.ScVal | string): any; + /** + * Finds the XDR spec entry for the given name. + * + * @param {string} name the name to find + * @returns {xdr.ScSpecEntry} the entry + * + * @throws {Error} if no entry with the given name exists + */ + findEntry(name: string): xdr.ScSpecEntry; + /** + * Converts a native JS value to an ScVal based on the given type. + * + * @param {any} val the native JS value + * @param {xdr.ScSpecTypeDef} [ty] the expected type + * @returns {xdr.ScVal} the converted ScVal + * + * @throws {Error} if value cannot be converted to the given type + */ + nativeToScVal(val: any, ty: xdr.ScSpecTypeDef): xdr.ScVal; + private nativeToUdt; + private nativeToUnion; + private nativeToStruct; + private nativeToEnum; + /** + * Converts an base64 encoded ScVal back to a native JS value based on the given type. + * + * @param {string} scv the base64 encoded ScVal + * @param {xdr.ScSpecTypeDef} typeDef the expected type + * @returns {any} the converted native JS value + * + * @throws {Error} if ScVal cannot be converted to the given type + */ + scValStrToNative(scv: string, typeDef: xdr.ScSpecTypeDef): T; + /** + * Converts an ScVal back to a native JS value based on the given type. + * + * @param {xdr.ScVal} scv the ScVal + * @param {xdr.ScSpecTypeDef} typeDef the expected type + * @returns {any} the converted native JS value + * + * @throws {Error} if ScVal cannot be converted to the given type + */ + scValToNative(scv: xdr.ScVal, typeDef: xdr.ScSpecTypeDef): T; + private scValUdtToNative; + private unionToNative; + private structToNative; + private enumToNative; + /** + * Gets the XDR error cases from the spec. + * + * @returns {xdr.ScSpecFunctionV0[]} all contract functions + * + */ + errorCases(): xdr.ScSpecUdtErrorEnumCaseV0[]; + /** + * Converts the contract spec to a JSON schema. + * + * If `funcName` is provided, the schema will be a reference to the function schema. + * + * @param {string} [funcName] the name of the function to convert + * @returns {JSONSchema7} the converted JSON schema + * + * @throws {Error} if the contract spec is invalid + */ + jsonSchema(funcName?: string): JSONSchema7; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/spec.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/spec.js new file mode 100644 index 000000000..1a70b3d2f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/spec.js @@ -0,0 +1,1020 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Spec = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _rust_result = require("./rust_result"); +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function enumToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + var title = aCase.name().toString(); + var desc = aCase.doc().toString(); + oneOf.push({ + description: desc, + title: title, + enum: [aCase.value()], + type: "number" + }); + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +function isNumeric(field) { + return /^\d+$/.test(field.name().toString()); +} +function readObj(args, input) { + var inputName = input.name().toString(); + var entry = Object.entries(args).find(function (_ref) { + var _ref2 = _slicedToArray(_ref, 1), + name = _ref2[0]; + return name === inputName; + }); + if (!entry) { + throw new Error("Missing field ".concat(inputName)); + } + return entry[1]; +} +function findCase(name) { + return function matches(entry) { + switch (entry.switch().value) { + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var tuple = entry.tupleCase(); + return tuple.name().toString() === name; + } + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var voidCase = entry.voidCase(); + return voidCase.name().toString() === name; + } + default: + return false; + } + }; +} +function stringToScVal(str, ty) { + switch (ty.value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeString().value: + return _stellarBase.xdr.ScVal.scvString(str); + case _stellarBase.xdr.ScSpecType.scSpecTypeSymbol().value: + return _stellarBase.xdr.ScVal.scvSymbol(str); + case _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value: + { + var addr = _stellarBase.Address.fromString(str); + return _stellarBase.xdr.ScVal.scvAddress(addr.toScAddress()); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU64().value: + return new _stellarBase.XdrLargeInt("u64", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeI64().value: + return new _stellarBase.XdrLargeInt("i64", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeU128().value: + return new _stellarBase.XdrLargeInt("u128", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeI128().value: + return new _stellarBase.XdrLargeInt("i128", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeU256().value: + return new _stellarBase.XdrLargeInt("u256", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeI256().value: + return new _stellarBase.XdrLargeInt("i256", str).toScVal(); + case _stellarBase.xdr.ScSpecType.scSpecTypeBytes().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeBytesN().value: + return _stellarBase.xdr.ScVal.scvBytes(Buffer.from(str, "base64")); + default: + throw new TypeError("invalid type ".concat(ty.name, " specified for string value")); + } +} +var PRIMITIVE_DEFINITONS = { + U32: { + type: "integer", + minimum: 0, + maximum: 4294967295 + }, + I32: { + type: "integer", + minimum: -2147483648, + maximum: 2147483647 + }, + U64: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 20 + }, + I64: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 21 + }, + U128: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 39 + }, + I128: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 40 + }, + U256: { + type: "string", + pattern: "^([1-9][0-9]*|0)$", + minLength: 1, + maxLength: 78 + }, + I256: { + type: "string", + pattern: "^(-?[1-9][0-9]*|0)$", + minLength: 1, + maxLength: 79 + }, + Address: { + type: "string", + format: "address", + description: "Address can be a public key or contract id" + }, + ScString: { + type: "string", + description: "ScString is a string" + }, + ScSymbol: { + type: "string", + description: "ScString is a string" + }, + DataUrl: { + type: "string", + pattern: "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=)?$" + } +}; +function typeRef(typeDef) { + var t = typeDef.switch(); + var value = t.value; + var ref; + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVal().value: + { + ref = "Val"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBool().value: + { + return { + type: "boolean" + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeVoid().value: + { + return { + type: "null" + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeError().value: + { + ref = "Error"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU32().value: + { + ref = "U32"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI32().value: + { + ref = "I32"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU64().value: + { + ref = "U64"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI64().value: + { + ref = "I64"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeTimepoint().value: + { + throw new Error("Timepoint type not supported"); + ref = "Timepoint"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeDuration().value: + { + throw new Error("Duration not supported"); + ref = "Duration"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU128().value: + { + ref = "U128"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI128().value: + { + ref = "I128"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeU256().value: + { + ref = "U256"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeI256().value: + { + ref = "I256"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBytes().value: + { + ref = "DataUrl"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeString().value: + { + ref = "ScString"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeSymbol().value: + { + ref = "ScSymbol"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value: + { + ref = "Address"; + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeOption().value: + { + var opt = typeDef.option(); + return typeRef(opt.valueType()); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeResult().value: + { + break; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeVec().value: + { + var arr = typeDef.vec(); + var reference = typeRef(arr.elementType()); + return { + type: "array", + items: reference + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = typeDef.map(); + var items = [typeRef(map.keyType()), typeRef(map.valueType())]; + return { + type: "array", + items: { + type: "array", + items: items, + minItems: 2, + maxItems: 2 + } + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tuple = typeDef.tuple(); + var minItems = tuple.valueTypes().length; + var maxItems = minItems; + var _items = tuple.valueTypes().map(typeRef); + return { + type: "array", + items: _items, + minItems: minItems, + maxItems: maxItems + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var _arr = typeDef.bytesN(); + return { + $ref: "#/definitions/DataUrl", + maxLength: _arr.n() + }; + } + case _stellarBase.xdr.ScSpecType.scSpecTypeUdt().value: + { + var udt = typeDef.udt(); + ref = udt.name().toString(); + break; + } + } + return { + $ref: "#/definitions/".concat(ref) + }; +} +function isRequired(typeDef) { + return typeDef.switch().value !== _stellarBase.xdr.ScSpecType.scSpecTypeOption().value; +} +function argsAndRequired(input) { + var properties = {}; + var required = []; + input.forEach(function (arg) { + var aType = arg.type(); + var name = arg.name().toString(); + properties[name] = typeRef(aType); + if (isRequired(aType)) { + required.push(name); + } + }); + var res = { + properties: properties + }; + if (required.length > 0) { + res.required = required; + } + return res; +} +function structToJsonSchema(udt) { + var fields = udt.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + var items = fields.map(function (_, i) { + return typeRef(fields[i].type()); + }); + return { + type: "array", + items: items, + minItems: fields.length, + maxItems: fields.length + }; + } + var description = udt.doc().toString(); + var _argsAndRequired = argsAndRequired(fields), + properties = _argsAndRequired.properties, + required = _argsAndRequired.required; + properties.additionalProperties = false; + return { + description: description, + properties: properties, + required: required, + type: "object" + }; +} +function functionToJsonSchema(func) { + var _argsAndRequired2 = argsAndRequired(func.inputs()), + properties = _argsAndRequired2.properties, + required = _argsAndRequired2.required; + var args = { + additionalProperties: false, + properties: properties, + type: "object" + }; + if ((required === null || required === void 0 ? void 0 : required.length) > 0) { + args.required = required; + } + var input = { + properties: { + args: args + } + }; + var outputs = func.outputs(); + var output = outputs.length > 0 ? typeRef(outputs[0]) : typeRef(_stellarBase.xdr.ScSpecTypeDef.scSpecTypeVoid()); + var description = func.doc().toString(); + if (description.length > 0) { + input.description = description; + } + input.additionalProperties = false; + output.additionalProperties = false; + return { + input: input, + output: output + }; +} +function unionToJsonSchema(udt) { + var description = udt.doc().toString(); + var cases = udt.cases(); + var oneOf = []; + cases.forEach(function (aCase) { + switch (aCase.switch().value) { + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0().value: + { + var c = aCase.voidCase(); + var title = c.name().toString(); + oneOf.push({ + type: "object", + title: title, + properties: { + tag: title + }, + additionalProperties: false, + required: ["tag"] + }); + break; + } + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value: + { + var _c = aCase.tupleCase(); + var _title = _c.name().toString(); + oneOf.push({ + type: "object", + title: _title, + properties: { + tag: _title, + values: { + type: "array", + items: _c.type().map(typeRef) + } + }, + required: ["tag", "values"], + additionalProperties: false + }); + } + } + }); + var res = { + oneOf: oneOf + }; + if (description.length > 0) { + res.description = description; + } + return res; +} +var Spec = exports.Spec = function () { + function Spec(entries) { + _classCallCheck(this, Spec); + _defineProperty(this, "entries", []); + if (entries.length === 0) { + throw new Error("Contract spec must have at least one entry"); + } + var entry = entries[0]; + if (typeof entry === "string") { + this.entries = entries.map(function (s) { + return _stellarBase.xdr.ScSpecEntry.fromXDR(s, "base64"); + }); + } else { + this.entries = entries; + } + } + return _createClass(Spec, [{ + key: "funcs", + value: function funcs() { + return this.entries.filter(function (entry) { + return entry.switch().value === _stellarBase.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value; + }).map(function (entry) { + return entry.functionV0(); + }); + } + }, { + key: "getFunc", + value: function getFunc(name) { + var entry = this.findEntry(name); + if (entry.switch().value !== _stellarBase.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value) { + throw new Error("".concat(name, " is not a function")); + } + return entry.functionV0(); + } + }, { + key: "funcArgsToScVals", + value: function funcArgsToScVals(name, args) { + var _this = this; + var fn = this.getFunc(name); + return fn.inputs().map(function (input) { + return _this.nativeToScVal(readObj(args, input), input.type()); + }); + } + }, { + key: "funcResToNative", + value: function funcResToNative(name, val_or_base64) { + var val = typeof val_or_base64 === "string" ? _stellarBase.xdr.ScVal.fromXDR(val_or_base64, "base64") : val_or_base64; + var func = this.getFunc(name); + var outputs = func.outputs(); + if (outputs.length === 0) { + var type = val.switch(); + if (type.value !== _stellarBase.xdr.ScValType.scvVoid().value) { + throw new Error("Expected void, got ".concat(type.name)); + } + return null; + } + if (outputs.length > 1) { + throw new Error("Multiple outputs not supported"); + } + var output = outputs[0]; + if (output.switch().value === _stellarBase.xdr.ScSpecType.scSpecTypeResult().value) { + return new _rust_result.Ok(this.scValToNative(val, output.result().okType())); + } + return this.scValToNative(val, output); + } + }, { + key: "findEntry", + value: function findEntry(name) { + var entry = this.entries.find(function (e) { + return e.value().name().toString() === name; + }); + if (!entry) { + throw new Error("no such entry: ".concat(name)); + } + return entry; + } + }, { + key: "nativeToScVal", + value: function nativeToScVal(val, ty) { + var _this2 = this; + var t = ty.switch(); + var value = t.value; + if (t.value === _stellarBase.xdr.ScSpecType.scSpecTypeUdt().value) { + var udt = ty.udt(); + return this.nativeToUdt(val, udt.name().toString()); + } + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeOption().value) { + var opt = ty.option(); + if (val === undefined) { + return _stellarBase.xdr.ScVal.scvVoid(); + } + return this.nativeToScVal(val, opt.valueType()); + } + switch (_typeof(val)) { + case "object": + { + var _val$constructor$name, _val$constructor; + if (val === null) { + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVoid().value: + return _stellarBase.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was null")); + } + } + if (val instanceof _stellarBase.xdr.ScVal) { + return val; + } + if (val instanceof _stellarBase.Address) { + if (ty.switch().value !== _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.toScVal(); + } + if (val instanceof _stellarBase.Contract) { + if (ty.switch().value !== _stellarBase.xdr.ScSpecType.scSpecTypeAddress().value) { + throw new TypeError("Type ".concat(ty, " was not address, but value was Address")); + } + return val.address().toScVal(); + } + if (val instanceof Uint8Array || Buffer.isBuffer(val)) { + var copy = Uint8Array.from(val); + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeBytesN().value: + { + var bytesN = ty.bytesN(); + if (copy.length !== bytesN.n()) { + throw new TypeError("expected ".concat(bytesN.n(), " bytes, but got ").concat(copy.length)); + } + return _stellarBase.xdr.ScVal.scvBytes(copy); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeBytes().value: + return _stellarBase.xdr.ScVal.scvBytes(copy); + default: + throw new TypeError("invalid type (".concat(ty, ") specified for Bytes and BytesN")); + } + } + if (Array.isArray(val)) { + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVec().value: + { + var vec = ty.vec(); + var elementType = vec.elementType(); + return _stellarBase.xdr.ScVal.scvVec(val.map(function (v) { + return _this2.nativeToScVal(v, elementType); + })); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeTuple().value: + { + var tup = ty.tuple(); + var valTypes = tup.valueTypes(); + if (val.length !== valTypes.length) { + throw new TypeError("Tuple expects ".concat(valTypes.length, " values, but ").concat(val.length, " were provided")); + } + return _stellarBase.xdr.ScVal.scvVec(val.map(function (v, i) { + return _this2.nativeToScVal(v, valTypes[i]); + })); + } + case _stellarBase.xdr.ScSpecType.scSpecTypeMap().value: + { + var map = ty.map(); + var keyType = map.keyType(); + var valueType = map.valueType(); + return _stellarBase.xdr.ScVal.scvMap(val.map(function (entry) { + var key = _this2.nativeToScVal(entry[0], keyType); + var mapVal = _this2.nativeToScVal(entry[1], valueType); + return new _stellarBase.xdr.ScMapEntry({ + key: key, + val: mapVal + }); + })); + } + default: + throw new TypeError("Type ".concat(ty, " was not vec, but value was Array")); + } + } + if (val.constructor === Map) { + if (value !== _stellarBase.xdr.ScSpecType.scSpecTypeMap().value) { + throw new TypeError("Type ".concat(ty, " was not map, but value was Map")); + } + var scMap = ty.map(); + var _map = val; + var entries = []; + var values = _map.entries(); + var res = values.next(); + while (!res.done) { + var _res$value = _slicedToArray(res.value, 2), + k = _res$value[0], + v = _res$value[1]; + var key = this.nativeToScVal(k, scMap.keyType()); + var mapval = this.nativeToScVal(v, scMap.valueType()); + entries.push(new _stellarBase.xdr.ScMapEntry({ + key: key, + val: mapval + })); + res = values.next(); + } + return _stellarBase.xdr.ScVal.scvMap(entries); + } + if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : "") !== "Object") { + var _val$constructor2; + throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")")); + } + throw new TypeError("Received object ".concat(val, " did not match the provided type ").concat(ty)); + } + case "number": + case "bigint": + { + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeU32().value: + return _stellarBase.xdr.ScVal.scvU32(val); + case _stellarBase.xdr.ScSpecType.scSpecTypeI32().value: + return _stellarBase.xdr.ScVal.scvI32(val); + case _stellarBase.xdr.ScSpecType.scSpecTypeU64().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeI64().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeU128().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeI128().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeU256().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeI256().value: + { + var intType = t.name.substring(10).toLowerCase(); + return new _stellarBase.XdrLargeInt(intType, val).toScVal(); + } + default: + throw new TypeError("invalid type (".concat(ty, ") specified for integer")); + } + } + case "string": + return stringToScVal(val, t); + case "boolean": + { + if (value !== _stellarBase.xdr.ScSpecType.scSpecTypeBool().value) { + throw TypeError("Type ".concat(ty, " was not bool, but value was bool")); + } + return _stellarBase.xdr.ScVal.scvBool(val); + } + case "undefined": + { + if (!ty) { + return _stellarBase.xdr.ScVal.scvVoid(); + } + switch (value) { + case _stellarBase.xdr.ScSpecType.scSpecTypeVoid().value: + case _stellarBase.xdr.ScSpecType.scSpecTypeOption().value: + return _stellarBase.xdr.ScVal.scvVoid(); + default: + throw new TypeError("Type ".concat(ty, " was not void, but value was undefined")); + } + } + case "function": + return this.nativeToScVal(val(), ty); + default: + throw new TypeError("failed to convert typeof ".concat(_typeof(val), " (").concat(val, ")")); + } + } + }, { + key: "nativeToUdt", + value: function nativeToUdt(val, name) { + var entry = this.findEntry(name); + switch (entry.switch()) { + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + if (typeof val !== "number") { + throw new TypeError("expected number for enum ".concat(name, ", but got ").concat(_typeof(val))); + } + return this.nativeToEnum(val, entry.udtEnumV0()); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.nativeToStruct(val, entry.udtStructV0()); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.nativeToUnion(val, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(name)); + } + } + }, { + key: "nativeToUnion", + value: function nativeToUnion(val, union_) { + var _this3 = this; + var entryName = val.tag; + var caseFound = union_.cases().find(function (entry) { + var caseN = entry.value().name().toString(); + return caseN === entryName; + }); + if (!caseFound) { + throw new TypeError("no such enum entry: ".concat(entryName, " in ").concat(union_)); + } + var key = _stellarBase.xdr.ScVal.scvSymbol(entryName); + switch (caseFound.switch()) { + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseVoidV0(): + { + return _stellarBase.xdr.ScVal.scvVec([key]); + } + case _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0(): + { + var types = caseFound.tupleCase().type(); + if (Array.isArray(val.values)) { + if (val.values.length !== types.length) { + throw new TypeError("union ".concat(union_, " expects ").concat(types.length, " values, but got ").concat(val.values.length)); + } + var scvals = val.values.map(function (v, i) { + return _this3.nativeToScVal(v, types[i]); + }); + scvals.unshift(key); + return _stellarBase.xdr.ScVal.scvVec(scvals); + } + throw new Error("failed to parse union case ".concat(caseFound, " with ").concat(val)); + } + default: + throw new Error("failed to parse union ".concat(union_, " with ").concat(val)); + } + } + }, { + key: "nativeToStruct", + value: function nativeToStruct(val, struct) { + var _this4 = this; + var fields = struct.fields(); + if (fields.some(isNumeric)) { + if (!fields.every(isNumeric)) { + throw new Error("mixed numeric and non-numeric field names are not allowed"); + } + return _stellarBase.xdr.ScVal.scvVec(fields.map(function (_, i) { + return _this4.nativeToScVal(val[i], fields[i].type()); + })); + } + return _stellarBase.xdr.ScVal.scvMap(fields.map(function (field) { + var name = field.name().toString(); + return new _stellarBase.xdr.ScMapEntry({ + key: _this4.nativeToScVal(name, _stellarBase.xdr.ScSpecTypeDef.scSpecTypeSymbol()), + val: _this4.nativeToScVal(val[name], field.type()) + }); + })); + } + }, { + key: "nativeToEnum", + value: function nativeToEnum(val, enum_) { + if (enum_.cases().some(function (entry) { + return entry.value() === val; + })) { + return _stellarBase.xdr.ScVal.scvU32(val); + } + throw new TypeError("no such enum entry: ".concat(val, " in ").concat(enum_)); + } + }, { + key: "scValStrToNative", + value: function scValStrToNative(scv, typeDef) { + return this.scValToNative(_stellarBase.xdr.ScVal.fromXDR(scv, "base64"), typeDef); + } + }, { + key: "scValToNative", + value: function scValToNative(scv, typeDef) { + var _this5 = this; + var t = typeDef.switch(); + var value = t.value; + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeUdt().value) { + return this.scValUdtToNative(scv, typeDef.udt()); + } + switch (scv.switch().value) { + case _stellarBase.xdr.ScValType.scvVoid().value: + return undefined; + case _stellarBase.xdr.ScValType.scvU64().value: + case _stellarBase.xdr.ScValType.scvI64().value: + case _stellarBase.xdr.ScValType.scvU128().value: + case _stellarBase.xdr.ScValType.scvI128().value: + case _stellarBase.xdr.ScValType.scvU256().value: + case _stellarBase.xdr.ScValType.scvI256().value: + return (0, _stellarBase.scValToBigInt)(scv); + case _stellarBase.xdr.ScValType.scvVec().value: + { + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeVec().value) { + var _scv$vec; + var vec = typeDef.vec(); + return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(function (elm) { + return _this5.scValToNative(elm, vec.elementType()); + }); + } + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeTuple().value) { + var _scv$vec2; + var tuple = typeDef.tuple(); + var valTypes = tuple.valueTypes(); + return ((_scv$vec2 = scv.vec()) !== null && _scv$vec2 !== void 0 ? _scv$vec2 : []).map(function (elm, i) { + return _this5.scValToNative(elm, valTypes[i]); + }); + } + throw new TypeError("Type ".concat(typeDef, " was not vec, but ").concat(scv, " is")); + } + case _stellarBase.xdr.ScValType.scvAddress().value: + return _stellarBase.Address.fromScVal(scv).toString(); + case _stellarBase.xdr.ScValType.scvMap().value: + { + var _scv$map; + var map = (_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []; + if (value === _stellarBase.xdr.ScSpecType.scSpecTypeMap().value) { + var typed = typeDef.map(); + var keyType = typed.keyType(); + var valueType = typed.valueType(); + var res = map.map(function (entry) { + return [_this5.scValToNative(entry.key(), keyType), _this5.scValToNative(entry.val(), valueType)]; + }); + return res; + } + throw new TypeError("ScSpecType ".concat(t.name, " was not map, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + case _stellarBase.xdr.ScValType.scvBool().value: + case _stellarBase.xdr.ScValType.scvU32().value: + case _stellarBase.xdr.ScValType.scvI32().value: + case _stellarBase.xdr.ScValType.scvBytes().value: + return scv.value(); + case _stellarBase.xdr.ScValType.scvString().value: + case _stellarBase.xdr.ScValType.scvSymbol().value: + { + var _scv$value; + if (value !== _stellarBase.xdr.ScSpecType.scSpecTypeString().value && value !== _stellarBase.xdr.ScSpecType.scSpecTypeSymbol().value) { + throw new Error("ScSpecType ".concat(t.name, " was not string or symbol, but ").concat(JSON.stringify(scv, null, 2), " is")); + } + return (_scv$value = scv.value()) === null || _scv$value === void 0 ? void 0 : _scv$value.toString(); + } + case _stellarBase.xdr.ScValType.scvTimepoint().value: + case _stellarBase.xdr.ScValType.scvDuration().value: + return (0, _stellarBase.scValToBigInt)(_stellarBase.xdr.ScVal.scvU64(scv.u64())); + default: + throw new TypeError("failed to convert ".concat(JSON.stringify(scv, null, 2), " to native type from type ").concat(t.name)); + } + } + }, { + key: "scValUdtToNative", + value: function scValUdtToNative(scv, udt) { + var entry = this.findEntry(udt.name().toString()); + switch (entry.switch()) { + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0(): + return this.enumToNative(scv); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0(): + return this.structToNative(scv, entry.udtStructV0()); + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0(): + return this.unionToNative(scv, entry.udtUnionV0()); + default: + throw new Error("failed to parse udt ".concat(udt.name().toString(), ": ").concat(entry)); + } + } + }, { + key: "unionToNative", + value: function unionToNative(val, udt) { + var _this6 = this; + var vec = val.vec(); + if (!vec) { + throw new Error("".concat(JSON.stringify(val, null, 2), " is not a vec")); + } + if (vec.length === 0 && udt.cases.length !== 0) { + throw new Error("".concat(val, " has length 0, but the there are at least one case in the union")); + } + var name = vec[0].sym().toString(); + if (vec[0].switch().value !== _stellarBase.xdr.ScValType.scvSymbol().value) { + throw new Error("{vec[0]} is not a symbol"); + } + var entry = udt.cases().find(findCase(name)); + if (!entry) { + throw new Error("failed to find entry ".concat(name, " in union {udt.name().toString()}")); + } + var res = { + tag: name + }; + if (entry.switch().value === _stellarBase.xdr.ScSpecUdtUnionCaseV0Kind.scSpecUdtUnionCaseTupleV0().value) { + var tuple = entry.tupleCase(); + var ty = tuple.type(); + var values = ty.map(function (e, i) { + return _this6.scValToNative(vec[i + 1], e); + }); + res.values = values; + } + return res; + } + }, { + key: "structToNative", + value: function structToNative(val, udt) { + var _this7 = this, + _val$map; + var res = {}; + var fields = udt.fields(); + if (fields.some(isNumeric)) { + var _val$vec; + var r = (_val$vec = val.vec()) === null || _val$vec === void 0 ? void 0 : _val$vec.map(function (entry, i) { + return _this7.scValToNative(entry, fields[i].type()); + }); + return r; + } + (_val$map = val.map()) === null || _val$map === void 0 || _val$map.forEach(function (entry, i) { + var field = fields[i]; + res[field.name().toString()] = _this7.scValToNative(entry.val(), field.type()); + }); + return res; + } + }, { + key: "enumToNative", + value: function enumToNative(scv) { + if (scv.switch().value !== _stellarBase.xdr.ScValType.scvU32().value) { + throw new Error("Enum must have a u32 value"); + } + var num = scv.u32(); + return num; + } + }, { + key: "errorCases", + value: function errorCases() { + return this.entries.filter(function (entry) { + return entry.switch().value === _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value; + }).flatMap(function (entry) { + return entry.value().cases(); + }); + } + }, { + key: "jsonSchema", + value: function jsonSchema(funcName) { + var definitions = {}; + this.entries.forEach(function (entry) { + switch (entry.switch().value) { + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtEnumV0().value: + { + var udt = entry.udtEnumV0(); + definitions[udt.name().toString()] = enumToJsonSchema(udt); + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtStructV0().value: + { + var _udt = entry.udtStructV0(); + definitions[_udt.name().toString()] = structToJsonSchema(_udt); + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtUnionV0().value: + { + var _udt2 = entry.udtUnionV0(); + definitions[_udt2.name().toString()] = unionToJsonSchema(_udt2); + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryFunctionV0().value: + { + var fn = entry.functionV0(); + var fnName = fn.name().toString(); + var _functionToJsonSchema = functionToJsonSchema(fn), + input = _functionToJsonSchema.input; + definitions[fnName] = input; + break; + } + case _stellarBase.xdr.ScSpecEntryKind.scSpecEntryUdtErrorEnumV0().value: + {} + } + }); + var res = { + $schema: "http://json-schema.org/draft-07/schema#", + definitions: _objectSpread(_objectSpread({}, PRIMITIVE_DEFINITONS), definitions) + }; + if (funcName) { + res.$ref = "#/definitions/".concat(funcName); + } + return res; + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/types.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/types.d.ts new file mode 100644 index 000000000..bceff262c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/types.d.ts @@ -0,0 +1,244 @@ +import { Memo, MemoType, Operation, Transaction, xdr } from "@stellar/stellar-base"; +export type XDR_BASE64 = string; +/** + * An unsigned 32-bit integer. + * @memberof module:contract + */ +export type u32 = number; +/** + * A signed 32-bit integer. + * @memberof module:contract + */ +export type i32 = number; +/** + * An unsigned 64-bit integer. + * @memberof module:contract + */ +export type u64 = bigint; +/** + * A signed 64-bit integer. + * @memberof module:contract + */ +export type i64 = bigint; +/** + * An unsigned 128-bit integer. + * @memberof module:contract + */ +export type u128 = bigint; +/** + * A signed 128-bit integer. + * @memberof module:contract + */ +export type i128 = bigint; +/** + * An unsigned 256-bit integer. + * @memberof module:contract + */ +export type u256 = bigint; +/** + * A signed 256-bit integer. + * @memberof module:contract + */ +export type i256 = bigint; +export type Option = T | undefined; +export type Typepoint = bigint; +export type Duration = bigint; +/** + * A "regular" transaction, as opposed to a FeeBumpTransaction. + * @memberof module:contract + * @type {Transaction, Operation[]>} + */ +export type Tx = Transaction, Operation[]>; +export interface WalletError { + message: string; + code: number; + ext?: Array; +} +/** + * A function to request a wallet to sign a built transaction + * + * This function takes an XDR provided by the requester and applies a signature to it. + * It returns a base64-encoded string XDR-encoded Transaction Envelope with Decorated Signatures + * and the signer address back to the requester. + * + * @param xdr - The XDR string representing the transaction to be signed. + * @param opts - Options for signing the transaction. + * @param opts.networkPassphrase - The network's passphrase on which the transaction is intended to be signed. + * @param opts.address - The public key of the account that should be used to sign. + * @param opts.submit - If set to true, submits the transaction immediately after signing. + * @param opts.submitUrl - The URL of the network to which the transaction should be submitted, if applicable. + * + * @returns A promise resolving to an object with the signed transaction XDR and optional signer address and error. + */ +export type SignTransaction = (xdr: string, opts?: { + networkPassphrase?: string; + address?: string; + submit?: boolean; + submitUrl?: string; +}) => Promise<{ + signedTxXdr: string; + signerAddress?: string; +} & { + error?: WalletError; +}>; +/** + * A function to request a wallet to sign an authorization entry preimage. + * + * Similar to signing a transaction, this function takes an authorization entry preimage provided by the + * requester and applies a signature to it. + * It returns a signed hash of the same authorization entry and the signer address back to the requester. + * + * @param authEntry - The authorization entry preimage to be signed. + * @param opts - Options for signing the authorization entry. + * @param opts.networkPassphrase - The network's passphrase on which the authorization entry is intended to be signed. + * @param opts.address - The public key of the account that should be used to sign. + * + * @returns A promise resolving to an object with the signed authorization entry and optional signer address and error. + */ +export type SignAuthEntry = (authEntry: string, opts?: { + networkPassphrase?: string; + address?: string; +}) => Promise<{ + signedAuthEntry: string; + signerAddress?: string; +} & { + error?: WalletError; +}>; +/** + * Options for a smart contract client. + * @memberof module:contract + */ +export type ClientOptions = { + /** + * The public key of the account that will send this transaction. You can + * override this for specific methods later, like + * [signAndSend]{@link module:contract.AssembledTransaction#signAndSend} and + * [signAuthEntries]{@link module:contract.AssembledTransaction#signAuthEntries}. + */ + publicKey?: string; + /** + * A function to sign the transaction using the private key corresponding to + * the given `publicKey`. You do not need to provide this, for read-only + * calls, which only need to be simulated. If you do not need to sign and + * send, there is no need to provide this. If you do not provide it during + * initialization, you can provide it later when you call + * {@link module:contract.AssembledTransaction#signAndSend signAndSend}. + * + * Matches signature of `signTransaction` from Freighter. + */ + signTransaction?: SignTransaction; + /** + * A function to sign a specific auth entry for a transaction, using the + * private key corresponding to the provided `publicKey`. This is only needed + * for multi-auth transactions, in which one transaction is signed by + * multiple parties. If you do not provide it during initialization, you can + * provide it later when you call {@link module:contract.AssembledTransaction#signAuthEntries signAuthEntries}. + * + * Matches signature of `signAuthEntry` from Freighter. + */ + signAuthEntry?: SignAuthEntry; + /** The address of the contract the client will interact with. */ + contractId: string; + /** + * The network passphrase for the Stellar network this contract is deployed + * to. + */ + networkPassphrase: string; + /** + * The URL of the RPC instance that will be used to interact with this + * contract. + */ + rpcUrl: string; + /** + * If true, will allow HTTP requests to the Soroban network. If false, will + * only allow HTTPS requests. + * @default false + */ + allowHttp?: boolean; + /** + * This gets filled in automatically from the ContractSpec when you + * instantiate a {@link Client}. + * + * Background: If the contract you're calling uses the `#[contracterror]` + * macro to create an `Error` enum, then those errors get included in the + * on-chain XDR that also describes your contract's methods. Each error will + * have a specific number. + * + * A Client makes method calls with an {@link module:contract.AssembledTransaction AssembledTransaction}. + * When one of these method calls encounters an error, `AssembledTransaction` + * will first attempt to parse the error as an "official" `contracterror` + * error, by using this passed-in `errorTypes` object. See + * {@link module:contract.AssembledTransaction#parseError parseError}. If `errorTypes` is blank or no + * matching error is found, then it will throw the raw error. + * @default {} + */ + errorTypes?: Record; +}; +/** + * Options for a smart contract method invocation. + * @memberof module:contract + */ +export type MethodOptions = { + /** + * The fee to pay for the transaction. + * @default 100 + */ + fee?: string; + /** + * The timebounds which should be set for transactions generated by this + * contract client. {@link module:contract#.DEFAULT_TIMEOUT} + * @default 300 + */ + timeoutInSeconds?: number; + /** + * Whether to automatically simulate the transaction when constructing the + * AssembledTransaction. + * @default true + */ + simulate?: boolean; + /** + * If true, will automatically attempt to restore the transaction if there + * are archived entries that need renewal. + * @default false + */ + restore?: boolean; +}; +export type AssembledTransactionOptions = MethodOptions & ClientOptions & { + method: string; + args?: any[]; + parseResultXdr: (xdr: xdr.ScVal) => T; + /** + * The address of the account that should sign the transaction. Useful when + * a wallet holds multiple addresses to ensure signing with the intended one. + */ + address?: string; + /** + * This option will be passed through to the SEP43-compatible wallet extension. If true, and if the wallet supports it, the transaction will be signed and immediately submitted to the network by the wallet, bypassing the submit logic in {@link SentTransaction}. + * @default false + */ + submit?: boolean; + /** + * The URL of the network to which the transaction should be submitted. + * Only applicable when 'submit' is set to true. + */ + submitUrl?: string; +}; +/** + * The default timebounds, in seconds, during which a transaction will be valid. + * This is attached to the transaction _before_ transaction simulation (it is + * needed for simulation to succeed). It is also re-calculated and re-added + * _before_ transaction signing. + * @constant {number} + * @default 300 + * @memberof module:contract + */ +export declare const DEFAULT_TIMEOUT: number; +/** + * An impossible account on the Stellar network + * @constant {string} + * @default GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF + * @memberof module:contract + */ +export declare const NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/types.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/types.js new file mode 100644 index 000000000..81a5b0f1c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/types.js @@ -0,0 +1,9 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NULL_ACCOUNT = exports.DEFAULT_TIMEOUT = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var DEFAULT_TIMEOUT = exports.DEFAULT_TIMEOUT = 5 * 60; +var NULL_ACCOUNT = exports.NULL_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/utils.d.ts new file mode 100644 index 000000000..12ee8e61e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/utils.d.ts @@ -0,0 +1,46 @@ +import { xdr, Account } from "@stellar/stellar-base"; +import { Server } from "../rpc"; +import { AssembledTransactionOptions } from "./types"; +/** + * Keep calling a `fn` for `timeoutInSeconds` seconds, if `keepWaitingIf` is + * true. Returns an array of all attempts to call the function. + * @private + */ +export declare function withExponentialBackoff( +/** Function to call repeatedly */ +fn: (previousFailure?: T) => Promise, +/** Condition to check when deciding whether or not to call `fn` again */ +keepWaitingIf: (result: T) => boolean, +/** How long to wait between the first and second call */ +timeoutInSeconds: number, +/** What to multiply `timeoutInSeconds` by, each subsequent attempt */ +exponentialFactor?: number, +/** Whether to log extra info */ +verbose?: boolean): Promise; +/** + * If contracts are implemented using the `#[contracterror]` macro, then the + * errors get included in the on-chain XDR that also describes your contract's + * methods. Each error will have a specific number. This Regular Expression + * matches these "expected error types" that a contract may throw, and helps + * {@link AssembledTransaction} parse these errors. + * + * @constant {RegExp} + * @default "/Error\(Contract, #(\d+)\)/" + * @memberof module:contract.Client + */ +export declare const contractErrorPattern: RegExp; +/** + * A TypeScript type guard that checks if an object has a `toString` method. + * @private + */ +export declare function implementsToString( +/** some object that may or may not have a `toString` method */ +obj: unknown): obj is { + toString(): string; +}; +/** + * Reads a binary stream of ScSpecEntries into an array for processing by ContractSpec + * @private + */ +export declare function processSpecEntryStream(buffer: Buffer): xdr.ScSpecEntry[]; +export declare function getAccount(options: AssembledTransactionOptions, server: Server): Promise; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/utils.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/utils.js new file mode 100644 index 000000000..8db862695 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/contract/utils.js @@ -0,0 +1,123 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.contractErrorPattern = void 0; +exports.getAccount = getAccount; +exports.implementsToString = implementsToString; +exports.processSpecEntryStream = processSpecEntryStream; +exports.withExponentialBackoff = withExponentialBackoff; +var _stellarBase = require("@stellar/stellar-base"); +var _types = require("./types"); +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function withExponentialBackoff(_x, _x2, _x3) { + return _withExponentialBackoff.apply(this, arguments); +} +function _withExponentialBackoff() { + _withExponentialBackoff = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(fn, keepWaitingIf, timeoutInSeconds) { + var exponentialFactor, + verbose, + attempts, + count, + waitUntil, + waitTime, + totalWaitTime, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + exponentialFactor = _args.length > 3 && _args[3] !== undefined ? _args[3] : 1.5; + verbose = _args.length > 4 && _args[4] !== undefined ? _args[4] : false; + attempts = []; + count = 0; + _context.t0 = attempts; + _context.next = 7; + return fn(); + case 7: + _context.t1 = _context.sent; + _context.t0.push.call(_context.t0, _context.t1); + if (keepWaitingIf(attempts[attempts.length - 1])) { + _context.next = 11; + break; + } + return _context.abrupt("return", attempts); + case 11: + waitUntil = new Date(Date.now() + timeoutInSeconds * 1000).valueOf(); + waitTime = 1000; + totalWaitTime = waitTime; + case 14: + if (!(Date.now() < waitUntil && keepWaitingIf(attempts[attempts.length - 1]))) { + _context.next = 30; + break; + } + count += 1; + if (verbose) { + console.info("Waiting ".concat(waitTime, "ms before trying again (bringing the total wait time to ").concat(totalWaitTime, "ms so far, of total ").concat(timeoutInSeconds * 1000, "ms)")); + } + _context.next = 19; + return new Promise(function (res) { + return setTimeout(res, waitTime); + }); + case 19: + waitTime *= exponentialFactor; + if (new Date(Date.now() + waitTime).valueOf() > waitUntil) { + waitTime = waitUntil - Date.now(); + if (verbose) { + console.info("was gonna wait too long; new waitTime: ".concat(waitTime, "ms")); + } + } + totalWaitTime = waitTime + totalWaitTime; + _context.t2 = attempts; + _context.next = 25; + return fn(attempts[attempts.length - 1]); + case 25: + _context.t3 = _context.sent; + _context.t2.push.call(_context.t2, _context.t3); + if (verbose && keepWaitingIf(attempts[attempts.length - 1])) { + console.info("".concat(count, ". Called ").concat(fn, "; ").concat(attempts.length, " prev attempts. Most recent: ").concat(JSON.stringify(attempts[attempts.length - 1], null, 2))); + } + _context.next = 14; + break; + case 30: + return _context.abrupt("return", attempts); + case 31: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _withExponentialBackoff.apply(this, arguments); +} +var contractErrorPattern = exports.contractErrorPattern = /Error\(Contract, #(\d+)\)/; +function implementsToString(obj) { + return _typeof(obj) === "object" && obj !== null && "toString" in obj; +} +function processSpecEntryStream(buffer) { + var reader = new _stellarBase.cereal.XdrReader(buffer); + var res = []; + while (!reader.eof) { + res.push(_stellarBase.xdr.ScSpecEntry.read(reader)); + } + return res; +} +function getAccount(_x4, _x5) { + return _getAccount.apply(this, arguments); +} +function _getAccount() { + _getAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(options, server) { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", options.publicKey ? server.getAccount(options.publicKey) : new _stellarBase.Account(_types.NULL_ACCOUNT, "0")); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _getAccount.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/account_requires_memo.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/account_requires_memo.d.ts new file mode 100644 index 000000000..2c845d12f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/account_requires_memo.d.ts @@ -0,0 +1,24 @@ +/** + * AccountRequiresMemoError is raised when a transaction is trying to submit an + * operation to an account which requires a memo. See + * [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md) + * for more information. + * + * This error contains two attributes to help you identify the account requiring + * the memo and the operation where the account is the destination + * @category Errors + * + * @param {string} message Human-readable error message + * @param {string} accountId The account which requires a memo + * @param {number} operationIndex The index of the operation where `accountId` is the destination + * + * @example + * console.log('The following account requires a memo ', err.accountId) + * console.log('The account is used in operation: ', err.operationIndex) + */ +export declare class AccountRequiresMemoError extends Error { + __proto__: AccountRequiresMemoError; + accountId: string; + operationIndex: number; + constructor(message: string, accountId: string, operationIndex: number); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/account_requires_memo.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/account_requires_memo.js new file mode 100644 index 000000000..669d85bc6 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/account_requires_memo.js @@ -0,0 +1,38 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AccountRequiresMemoError = void 0; +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var AccountRequiresMemoError = exports.AccountRequiresMemoError = function (_Error) { + function AccountRequiresMemoError(message, accountId, operationIndex) { + var _this; + _classCallCheck(this, AccountRequiresMemoError); + var trueProto = (this instanceof AccountRequiresMemoError ? this.constructor : void 0).prototype; + _this = _callSuper(this, AccountRequiresMemoError, [message]); + _this.__proto__ = trueProto; + _this.constructor = AccountRequiresMemoError; + _this.name = "AccountRequiresMemoError"; + _this.accountId = accountId; + _this.operationIndex = operationIndex; + return _this; + } + _inherits(AccountRequiresMemoError, _Error); + return _createClass(AccountRequiresMemoError); +}(_wrapNativeSuper(Error)); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/bad_request.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/bad_request.d.ts new file mode 100644 index 000000000..4d1d320d5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/bad_request.d.ts @@ -0,0 +1,14 @@ +import { NetworkError } from "./network"; +/** + * BadRequestError is raised when a request made to Horizon is invalid in some + * way (incorrect timebounds for trade call builders, for example.) + * @augments NetworkError + * @inheritdoc + * @category Errors + * + * @param {string} message Human-readable error message + * @param {any} response Response details, received from the Horizon server + */ +export declare class BadRequestError extends NetworkError { + constructor(message: string, response: any); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/bad_request.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/bad_request.js new file mode 100644 index 000000000..24aeb632c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/bad_request.js @@ -0,0 +1,34 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BadRequestError = void 0; +var _network = require("./network"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var BadRequestError = exports.BadRequestError = function (_NetworkError) { + function BadRequestError(message, response) { + var _this; + _classCallCheck(this, BadRequestError); + var trueProto = (this instanceof BadRequestError ? this.constructor : void 0).prototype; + _this = _callSuper(this, BadRequestError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadRequestError; + _this.name = "BadRequestError"; + return _this; + } + _inherits(BadRequestError, _NetworkError); + return _createClass(BadRequestError); +}(_network.NetworkError); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/bad_response.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/bad_response.d.ts new file mode 100644 index 000000000..22de8f235 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/bad_response.d.ts @@ -0,0 +1,17 @@ +import { NetworkError } from "./network"; +/** + * BadResponseError is raised when a response from a + * {@link module:Horizon | Horizon} or {@link module:Federation | Federation} + * server is invalid in some way. For example, a federation response may exceed + * the maximum allowed size, or a transaction submission may have failed with + * Horizon. + * @augments NetworkError + * @inheritdoc + * @category Errors + * + * @param {string} message Human-readable error message. + * @param {any} response Response details, received from the server. + */ +export declare class BadResponseError extends NetworkError { + constructor(message: string, response: any); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/bad_response.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/bad_response.js new file mode 100644 index 000000000..c7fbbacec --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/bad_response.js @@ -0,0 +1,34 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BadResponseError = void 0; +var _network = require("./network"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var BadResponseError = exports.BadResponseError = function (_NetworkError) { + function BadResponseError(message, response) { + var _this; + _classCallCheck(this, BadResponseError); + var trueProto = (this instanceof BadResponseError ? this.constructor : void 0).prototype; + _this = _callSuper(this, BadResponseError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = BadResponseError; + _this.name = "BadResponseError"; + return _this; + } + _inherits(BadResponseError, _NetworkError); + return _createClass(BadResponseError); +}(_network.NetworkError); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/index.d.ts new file mode 100644 index 000000000..cb4f19458 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/index.d.ts @@ -0,0 +1,5 @@ +export * from "./network"; +export * from "./not_found"; +export * from "./bad_request"; +export * from "./bad_response"; +export * from "./account_requires_memo"; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/index.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/index.js new file mode 100644 index 000000000..f0f9d584e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/index.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _network = require("./network"); +Object.keys(_network).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _network[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _network[key]; + } + }); +}); +var _not_found = require("./not_found"); +Object.keys(_not_found).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _not_found[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _not_found[key]; + } + }); +}); +var _bad_request = require("./bad_request"); +Object.keys(_bad_request).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _bad_request[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _bad_request[key]; + } + }); +}); +var _bad_response = require("./bad_response"); +Object.keys(_bad_response).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _bad_response[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _bad_response[key]; + } + }); +}); +var _account_requires_memo = require("./account_requires_memo"); +Object.keys(_account_requires_memo).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _account_requires_memo[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _account_requires_memo[key]; + } + }); +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/network.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/network.d.ts new file mode 100644 index 000000000..fad4e7745 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/network.d.ts @@ -0,0 +1,33 @@ +import { HorizonApi } from "../horizon/horizon_api"; +/** + * NetworkError is raised when an interaction with a Horizon server has caused + * some kind of problem. + * @category Errors + * + * @param {string} message Human-readable error message + * @param {any} response Response details, received from the Horizon server. + * @param {HorizonApi.ErrorResponseData} [response.data] The data returned by Horizon as part of the error: {@link https://developers.stellar.org/docs/data/horizon/api-reference/errors/response | Error Response} + * @param {number} [response.status] HTTP status code describing the basic issue with a submitted transaction {@link https://developers.stellar.org/docs/data/horizon/api-reference/errors/http-status-codes/standard | Standard Status Codes} + * @param {string} [response.statusText] A human-readable description of what the status code means: {@link https://developers.stellar.org/docs/data/horizon/api-reference/errors/http-status-codes/horizon-specific | Horizon-Specific Status Codes} + * @param {string} [response.url] URL which can provide more information about the problem that occurred. + */ +export declare class NetworkError extends Error { + response: { + data?: HorizonApi.ErrorResponseData; + status?: number; + statusText?: string; + url?: string; + }; + __proto__: NetworkError; + constructor(message: string, response: any); + /** + * Returns the error response sent by the Horizon server. + * @returns {any} + */ + getResponse(): { + data?: HorizonApi.ErrorResponseData; + status?: number; + statusText?: string; + url?: string; + }; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/network.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/network.js new file mode 100644 index 000000000..a26433617 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/network.js @@ -0,0 +1,41 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NetworkError = void 0; +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var NetworkError = exports.NetworkError = function (_Error) { + function NetworkError(message, response) { + var _this; + _classCallCheck(this, NetworkError); + var trueProto = (this instanceof NetworkError ? this.constructor : void 0).prototype; + _this = _callSuper(this, NetworkError, [message]); + _this.__proto__ = trueProto; + _this.constructor = NetworkError; + _this.response = response; + return _this; + } + _inherits(NetworkError, _Error); + return _createClass(NetworkError, [{ + key: "getResponse", + value: function getResponse() { + return this.response; + } + }]); +}(_wrapNativeSuper(Error)); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/not_found.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/not_found.d.ts new file mode 100644 index 000000000..bca48d935 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/not_found.d.ts @@ -0,0 +1,14 @@ +import { NetworkError } from "./network"; +/** + * NotFoundError is raised when the resource requested from Horizon is + * unavailable. + * @augments NetworkError + * @inheritdoc + * @category Errors + * + * @param {string} message Human-readable error message + * @param {any} response Response details, received from the Horizon server + */ +export declare class NotFoundError extends NetworkError { + constructor(message: string, response: any); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/not_found.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/not_found.js new file mode 100644 index 000000000..d828c18cf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/errors/not_found.js @@ -0,0 +1,34 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NotFoundError = void 0; +var _network = require("./network"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var NotFoundError = exports.NotFoundError = function (_NetworkError) { + function NotFoundError(message, response) { + var _this; + _classCallCheck(this, NotFoundError); + var trueProto = (this instanceof NotFoundError ? this.constructor : void 0).prototype; + _this = _callSuper(this, NotFoundError, [message, response]); + _this.__proto__ = trueProto; + _this.constructor = NotFoundError; + _this.name = "NotFoundError"; + return _this; + } + _inherits(NotFoundError, _NetworkError); + return _createClass(NotFoundError); +}(_network.NetworkError); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/api.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/api.d.ts new file mode 100644 index 000000000..f7feb38bf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/api.d.ts @@ -0,0 +1,32 @@ +export declare namespace Api { + /** + * Record returned from a federation server. + */ + interface Record { + /** + * The Stellar public key resolved from the federation lookup + */ + account_id: string; + /** + * The type of memo, if any, required to send payments to this user + */ + memo_type?: string; + /** + * The memo value, if any, required to send payments to this user + */ + memo?: string; + } + /** + * Options for configuring connections to federation servers. You can also use {@link Config} class to set this globally. + */ + interface Options { + /** + * Allow connecting to http servers, default: `false`. This must be set to false in production deployments! + */ + allowHttp?: boolean; + /** + * Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue. + */ + timeout?: number; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/api.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/api.js new file mode 100644 index 000000000..081ac7fbf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/api.js @@ -0,0 +1,7 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Api = void 0; +var Api; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/index.d.ts new file mode 100644 index 000000000..4eaff4f80 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/index.d.ts @@ -0,0 +1,2 @@ +export { FederationServer as Server, FEDERATION_RESPONSE_MAX_SIZE } from './server'; +export * from './api'; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/index.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/index.js new file mode 100644 index 000000000..2d73772d2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/index.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Server: true, + FEDERATION_RESPONSE_MAX_SIZE: true +}; +Object.defineProperty(exports, "FEDERATION_RESPONSE_MAX_SIZE", { + enumerable: true, + get: function get() { + return _server.FEDERATION_RESPONSE_MAX_SIZE; + } +}); +Object.defineProperty(exports, "Server", { + enumerable: true, + get: function get() { + return _server.FederationServer; + } +}); +var _server = require("./server"); +var _api = require("./api"); +Object.keys(_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _api[key]; + } + }); +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/server.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/server.d.ts new file mode 100644 index 000000000..bde8cb479 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/server.d.ts @@ -0,0 +1,116 @@ +import { Api } from "./api"; +/** @module Federation */ +/** + * The maximum size of response from a federation server + * @default 102400 + */ +export declare const FEDERATION_RESPONSE_MAX_SIZE: number; +/** + * Federation.Server handles a network connection to a + * [federation server](https://developers.stellar.org/docs/learn/encyclopedia/federation) + * instance and exposes an interface for requests to that instance. + * + * @alias module:Federation.Server + * @memberof module:Federation + * @param {string} serverURL The federation server URL (ex. `https://acme.com/federation`). + * @param {string} domain Domain this server represents + * @param {Api.Options} [opts] Options object + * @returns {void} + */ +export declare class FederationServer { + /** + * The federation server URL (ex. `https://acme.com/federation`). + */ + private readonly serverURL; + /** + * Domain this server represents. + */ + private readonly domain; + /** + * Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue. + */ + private readonly timeout; + /** + * A helper method for handling user inputs that contain `destination` value. + * It accepts two types of values: + * + * * For Stellar address (ex. `bob*stellar.org`) it splits Stellar address and then tries to find information about + * federation server in `stellar.toml` file for a given domain. It returns a `Promise` which resolves if federation + * server exists and user has been found and rejects in all other cases. + * * For Account ID (ex. `GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS`) it returns a `Promise` which + * resolves if Account ID is valid and rejects in all other cases. Please note that this method does not check + * if the account actually exists in a ledger. + * + * @example + * StellarSdk.FederationServer.resolve('bob*stellar.org') + * .then(federationRecord => { + * // { + * // account_id: 'GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS', + * // memo_type: 'id', + * // memo: 100 + * // } + * }); + * + * @see Federation doc + * @see Stellar.toml doc + * @param {string} value Stellar Address (ex. `bob*stellar.org`) + * @param {object} [opts] Options object + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the provided account ID is not a valid Ed25519 public key. + */ + static resolve(value: string, opts?: Api.Options): Promise; + /** + * Creates a `FederationServer` instance based on information from + * [stellar.toml](https://developers.stellar.org/docs/issuing-assets/publishing-asset-info) + * file for a given domain. + * + * If `stellar.toml` file does not exist for a given domain or it does not + * contain information about a federation server Promise will reject. + * + * @example + * StellarSdk.FederationServer.createForDomain('acme.com') + * .then(federationServer => { + * // federationServer.resolveAddress('bob').then(...) + * }) + * .catch(error => { + * // stellar.toml does not exist or it does not contain information about federation server. + * }); + * + * @see Stellar.toml doc + * @param {string} domain Domain to get federation server for + * @param {module:Federation.Api.Options} [opts] Options object + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the domain's stellar.toml file does not contain a federation server field. + */ + static createForDomain(domain: string, opts?: Api.Options): Promise; + constructor(serverURL: string, domain: string, opts?: Api.Options); + /** + * Get the federation record if the user was found for a given Stellar address + * @see Federation doc + * @param {string} address Stellar address (ex. `bob*stellar.org`). If `FederationServer` was instantiated with `domain` param only username (ex. `bob`) can be passed. + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the federated address does not contain a domain, or if the server object was not instantiated with a `domain` parameter + */ + resolveAddress(address: string): Promise; + /** + * Given an account ID, get their federation record if the user was found + * @see Federation doc + * @param {string} accountId Account ID (ex. `GBYNR2QJXLBCBTRN44MRORCMI4YO7FZPFBCNOKTOBCAAFC7KC3LNPRYS`) + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the federation server returns an invalid memo value. + * @throws Will throw an error if the federation server's response exceeds the allowed maximum size. + * @throws {BadResponseError} Will throw an error if the server query fails with an improper response. + */ + resolveAccountId(accountId: string): Promise; + /** + * Given a transactionId, get the federation record if the sender of the transaction was found + * @see Federation doc + * @param {string} transactionId Transaction ID (ex. `3389e9f0f1a65f19736cacf544c2e825313e8447f569233bb8db39aa607c8889`) + * @returns {Promise} A promise that resolves to the federation record + * @throws Will throw an error if the federation server returns an invalid memo value. + * @throws Will throw an error if the federation server's response exceeds the allowed maximum size. + * @throws {BadResponseError} Will throw an error if the server query fails with an improper response. + */ + resolveTransactionId(transactionId: string): Promise; + private _sendRequest; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/server.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/server.js new file mode 100644 index 000000000..36d7789cd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/federation/server.js @@ -0,0 +1,252 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FederationServer = exports.FEDERATION_RESPONSE_MAX_SIZE = void 0; +var _stellarBase = require("@stellar/stellar-base"); +var _urijs = _interopRequireDefault(require("urijs")); +var _config = require("../config"); +var _errors = require("../errors"); +var _stellartoml = require("../stellartoml"); +var _httpClient = require("../http-client"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var FEDERATION_RESPONSE_MAX_SIZE = exports.FEDERATION_RESPONSE_MAX_SIZE = 100 * 1024; +var FederationServer = exports.FederationServer = function () { + function FederationServer(serverURL, domain) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + _classCallCheck(this, FederationServer); + this.serverURL = (0, _urijs.default)(serverURL); + this.domain = domain; + var allowHttp = typeof opts.allowHttp === "undefined" ? _config.Config.isAllowHttp() : opts.allowHttp; + this.timeout = typeof opts.timeout === "undefined" ? _config.Config.getTimeout() : opts.timeout; + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure federation server"); + } + } + return _createClass(FederationServer, [{ + key: "resolveAddress", + value: (function () { + var _resolveAddress = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(address) { + var stellarAddress, url; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + stellarAddress = address; + if (!(address.indexOf("*") < 0)) { + _context.next = 5; + break; + } + if (this.domain) { + _context.next = 4; + break; + } + return _context.abrupt("return", Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object."))); + case 4: + stellarAddress = "".concat(address, "*").concat(this.domain); + case 5: + url = this.serverURL.query({ + type: "name", + q: stellarAddress + }); + return _context.abrupt("return", this._sendRequest(url)); + case 7: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function resolveAddress(_x) { + return _resolveAddress.apply(this, arguments); + } + return resolveAddress; + }()) + }, { + key: "resolveAccountId", + value: (function () { + var _resolveAccountId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2(accountId) { + var url; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + url = this.serverURL.query({ + type: "id", + q: accountId + }); + return _context2.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function resolveAccountId(_x2) { + return _resolveAccountId.apply(this, arguments); + } + return resolveAccountId; + }()) + }, { + key: "resolveTransactionId", + value: (function () { + var _resolveTransactionId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(transactionId) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = this.serverURL.query({ + type: "txid", + q: transactionId + }); + return _context3.abrupt("return", this._sendRequest(url)); + case 2: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function resolveTransactionId(_x3) { + return _resolveTransactionId.apply(this, arguments); + } + return resolveTransactionId; + }()) + }, { + key: "_sendRequest", + value: function () { + var _sendRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(url) { + var timeout; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + timeout = this.timeout; + return _context4.abrupt("return", _httpClient.httpClient.get(url.toString(), { + maxContentLength: FEDERATION_RESPONSE_MAX_SIZE, + timeout: timeout + }).then(function (response) { + if (typeof response.data.memo !== "undefined" && typeof response.data.memo !== "string") { + throw new Error("memo value should be of type string"); + } + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + if (response.message.match(/^maxContentLength size/)) { + throw new Error("federation response exceeds allowed size of ".concat(FEDERATION_RESPONSE_MAX_SIZE)); + } else { + return Promise.reject(response); + } + } else { + return Promise.reject(new _errors.BadResponseError("Server query failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + } + })); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function _sendRequest(_x4) { + return _sendRequest2.apply(this, arguments); + } + return _sendRequest; + }() + }], [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(value) { + var opts, + addressParts, + _addressParts, + domain, + federationServer, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {}; + if (!(value.indexOf("*") < 0)) { + _context5.next = 5; + break; + } + if (_stellarBase.StrKey.isValidEd25519PublicKey(value)) { + _context5.next = 4; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Account ID"))); + case 4: + return _context5.abrupt("return", Promise.resolve({ + account_id: value + })); + case 5: + addressParts = value.split("*"); + _addressParts = _slicedToArray(addressParts, 2), domain = _addressParts[1]; + if (!(addressParts.length !== 2 || !domain)) { + _context5.next = 9; + break; + } + return _context5.abrupt("return", Promise.reject(new Error("Invalid Stellar address"))); + case 9: + _context5.next = 11; + return FederationServer.createForDomain(domain, opts); + case 11: + federationServer = _context5.sent; + return _context5.abrupt("return", federationServer.resolveAddress(value)); + case 13: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function resolve(_x5) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }, { + key: "createForDomain", + value: (function () { + var _createForDomain = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(domain) { + var opts, + tomlObject, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : {}; + _context6.next = 3; + return _stellartoml.Resolver.resolve(domain, opts); + case 3: + tomlObject = _context6.sent; + if (tomlObject.FEDERATION_SERVER) { + _context6.next = 6; + break; + } + return _context6.abrupt("return", Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field"))); + case 6: + return _context6.abrupt("return", new FederationServer(tomlObject.FEDERATION_SERVER, domain, opts)); + case 7: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function createForDomain(_x6) { + return _createForDomain.apply(this, arguments); + } + return createForDomain; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/friendbot/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/friendbot/index.d.ts new file mode 100644 index 000000000..5181343e0 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/friendbot/index.d.ts @@ -0,0 +1,6 @@ +export declare namespace Api { + interface Response { + hash: string; + result_meta_xdr: string; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/friendbot/index.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/friendbot/index.js new file mode 100644 index 000000000..081ac7fbf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/friendbot/index.js @@ -0,0 +1,7 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Api = void 0; +var Api; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/account_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/account_call_builder.d.ts new file mode 100644 index 000000000..87c625f4f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/account_call_builder.d.ts @@ -0,0 +1,56 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link AccountCallBuilder} pointed to server defined by `serverUrl`. + * + * Do not create this object directly, use {@link Horizon.Server#accounts}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|All Accounts} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class AccountCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Returns information and links relating to a single account. + * The balances section in the returned JSON will also list all the trust lines this account has set up. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-an-account|Account Details} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {CallBuilder} a new CallBuilder instance for the /accounts/:id endpoint + */ + accountId(id: string): CallBuilder; + /** + * This endpoint filters accounts by signer account. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|Accounts} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + forSigner(id: string): this; + /** + * This endpoint filters all accounts who are trustees to an asset. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|Accounts} + * @see Asset + * @param {Asset} asset For example: `new Asset('USD','GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD')` + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + forAsset(asset: Asset): this; + /** + * This endpoint filters accounts where the given account is sponsoring the account or any of its sub-entries.. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-accounts|Accounts} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + sponsor(id: string): this; + /** + * This endpoint filters accounts holding a trustline to the given liquidity pool. + * + * @param {string} id The ID of the liquidity pool. For example: `dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7`. + * @returns {AccountCallBuilder} current AccountCallBuilder instance + */ + forLiquidityPool(id: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/account_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/account_call_builder.js new file mode 100644 index 000000000..cdf9aa78a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/account_call_builder.js @@ -0,0 +1,62 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AccountCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var AccountCallBuilder = exports.AccountCallBuilder = function (_CallBuilder) { + function AccountCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, AccountCallBuilder); + _this = _callSuper(this, AccountCallBuilder, [serverUrl]); + _this.url.segment("accounts"); + return _this; + } + _inherits(AccountCallBuilder, _CallBuilder); + return _createClass(AccountCallBuilder, [{ + key: "accountId", + value: function accountId(id) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([id]); + return builder; + } + }, { + key: "forSigner", + value: function forSigner(id) { + this.url.setQuery("signer", id); + return this; + } + }, { + key: "forAsset", + value: function forAsset(asset) { + this.url.setQuery("asset", "".concat(asset)); + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(id) { + this.url.setQuery("liquidity_pool", id); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/account_response.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/account_response.d.ts new file mode 100644 index 000000000..a5a448de4 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/account_response.d.ts @@ -0,0 +1,61 @@ +import { HorizonApi } from "./horizon_api"; +import { ServerApi } from "./server_api"; +/** + * Do not create this object directly, use {@link module:Horizon.Server#loadAccount | Horizon.Server#loadAccount}. + * + * Returns information and links relating to a single account. + * The balances section in the returned JSON will also list all the trust lines this account has set up. + * It also contains {@link BaseAccount} object and exposes it's methods so can be used in {@link TransactionBuilder}. + * + * @memberof module:Horizon + * @private + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/accounts/object|Account Details} + * @param {string} response Response from horizon account endpoint. + * @returns {AccountResponse} AccountResponse instance + */ +export declare class AccountResponse { + readonly id: string; + readonly paging_token: string; + readonly account_id: string; + sequence: string; + readonly sequence_ledger?: number; + readonly sequence_time?: string; + readonly subentry_count: number; + readonly home_domain?: string; + readonly inflation_destination?: string; + readonly last_modified_ledger: number; + readonly last_modified_time: string; + readonly thresholds: HorizonApi.AccountThresholds; + readonly flags: HorizonApi.Flags; + readonly balances: HorizonApi.BalanceLine[]; + readonly signers: ServerApi.AccountRecordSigners[]; + readonly data: (options: { + value: string; + }) => Promise<{ + value: string; + }>; + readonly data_attr: Record; + readonly effects: ServerApi.CallCollectionFunction; + readonly offers: ServerApi.CallCollectionFunction; + readonly operations: ServerApi.CallCollectionFunction; + readonly payments: ServerApi.CallCollectionFunction; + readonly trades: ServerApi.CallCollectionFunction; + private readonly _baseAccount; + constructor(response: ServerApi.AccountRecord); + /** + * Get Stellar account public key ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA` + * @returns {string} accountId + */ + accountId(): string; + /** + * Get the current sequence number + * @returns {string} sequenceNumber + */ + sequenceNumber(): string; + /** + * Increments sequence number in this object by one. + * @returns {void} + */ + incrementSequenceNumber(): void; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/account_response.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/account_response.js new file mode 100644 index 000000000..682b46360 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/account_response.js @@ -0,0 +1,49 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AccountResponse = void 0; +var _stellarBase = require("@stellar/stellar-base"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var AccountResponse = exports.AccountResponse = function () { + function AccountResponse(response) { + var _this = this; + _classCallCheck(this, AccountResponse); + this._baseAccount = new _stellarBase.Account(response.account_id, response.sequence); + Object.entries(response).forEach(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + _this[key] = value; + }); + } + return _createClass(AccountResponse, [{ + key: "accountId", + value: function accountId() { + return this._baseAccount.accountId(); + } + }, { + key: "sequenceNumber", + value: function sequenceNumber() { + return this._baseAccount.sequenceNumber(); + } + }, { + key: "incrementSequenceNumber", + value: function incrementSequenceNumber() { + this._baseAccount.incrementSequenceNumber(); + this.sequence = this._baseAccount.sequenceNumber(); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/assets_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/assets_call_builder.d.ts new file mode 100644 index 000000000..38c7f9f14 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/assets_call_builder.d.ts @@ -0,0 +1,27 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link AssetsCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#assets}. + * + * @class + * @augments CallBuilder + * @private + * @param {string} serverUrl Horizon server URL. + */ +export declare class AssetsCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * This endpoint filters all assets by the asset code. + * @param {string} value For example: `USD` + * @returns {AssetsCallBuilder} current AssetCallBuilder instance + */ + forCode(value: string): AssetsCallBuilder; + /** + * This endpoint filters all assets by the asset issuer. + * @param {string} value For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {AssetsCallBuilder} current AssetCallBuilder instance + */ + forIssuer(value: string): AssetsCallBuilder; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/assets_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/assets_call_builder.js new file mode 100644 index 000000000..68d89ba1f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/assets_call_builder.js @@ -0,0 +1,43 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AssetsCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var AssetsCallBuilder = exports.AssetsCallBuilder = function (_CallBuilder) { + function AssetsCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, AssetsCallBuilder); + _this = _callSuper(this, AssetsCallBuilder, [serverUrl]); + _this.url.segment("assets"); + return _this; + } + _inherits(AssetsCallBuilder, _CallBuilder); + return _createClass(AssetsCallBuilder, [{ + key: "forCode", + value: function forCode(value) { + this.url.setQuery("asset_code", value); + return this; + } + }, { + key: "forIssuer", + value: function forIssuer(value) { + this.url.setQuery("asset_issuer", value); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/call_builder.d.ts new file mode 100644 index 000000000..f40d6db20 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/call_builder.d.ts @@ -0,0 +1,128 @@ +import URI from "urijs"; +import { HorizonApi } from "./horizon_api"; +import { ServerApi } from "./server_api"; +export interface EventSourceOptions { + onmessage?: (value: T) => void; + onerror?: (event: MessageEvent) => void; + reconnectTimeout?: number; +} +/** + * Creates a new {@link CallBuilder} pointed to server defined by serverUrl. + * + * This is an **abstract** class. Do not create this object directly, use {@link Server} class. + * @param {string} serverUrl URL of Horizon server + * @class CallBuilder + */ +export declare class CallBuilder> { + protected url: URI; + filter: string[][]; + protected originalSegments: string[]; + protected neighborRoot: string; + constructor(serverUrl: URI, neighborRoot?: string); + /** + * Triggers a HTTP request using this builder's current configuration. + * @returns {Promise} a Promise that resolves to the server's response. + */ + call(): Promise; + /** + * Creates an EventSource that listens for incoming messages from the server. To stop listening for new + * events call the function returned by this method. + * @see [Horizon Response Format](https://developers.stellar.org/api/introduction/response-format/) + * @see [MDN EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) + * @param {object} [options] EventSource options. + * @param {Function} [options.onmessage] Callback function to handle incoming messages. + * @param {Function} [options.onerror] Callback function to handle errors. + * @param {number} [options.reconnectTimeout] Custom stream connection timeout in ms, default is 15 seconds. + * @returns {Function} Close function. Run to close the connection and stop listening for new events. + */ + stream(options?: EventSourceOptions ? U : T>): () => void; + /** + * Sets `cursor` parameter for the current call. Returns the CallBuilder object on which this method has been called. + * @see [Paging](https://developers.stellar.org/api/introduction/pagination/) + * @param {string} cursor A cursor is a value that points to a specific location in a collection of resources. + * @returns {object} current CallBuilder instance + */ + cursor(cursor: string): this; + /** + * Sets `limit` parameter for the current call. Returns the CallBuilder object on which this method has been called. + * @see [Paging](https://developers.stellar.org/api/introduction/pagination/) + * @param {number} recordsNumber Number of records the server should return. + * @returns {object} current CallBuilder instance + */ + limit(recordsNumber: number): this; + /** + * Sets `order` parameter for the current call. Returns the CallBuilder object on which this method has been called. + * @param {"asc"|"desc"} direction Sort direction + * @returns {object} current CallBuilder instance + */ + order(direction: "asc" | "desc"): this; + /** + * Sets `join` parameter for the current call. The `join` parameter + * includes the requested resource in the response. Currently, the + * only valid value for the parameter is `transactions` and is only + * supported on the operations and payments endpoints. The response + * will include a `transaction` field for each operation in the + * response. + * + * @param "include" join Records to be included in the response. + * @returns {object} current CallBuilder instance. + */ + join(include: "transactions"): this; + /** + * A helper method to craft queries to "neighbor" endpoints. + * + * For example, we have an `/effects` suffix endpoint on many different + * "root" endpoints, such as `/transactions/:id` and `/accounts/:id`. So, + * it's helpful to be able to conveniently create queries to the + * `/accounts/:id/effects` endpoint: + * + * this.forEndpoint("accounts", accountId)`. + * + * @param {string} endpoint neighbor endpoint in question, like /operations + * @param {string} param filter parameter, like an operation ID + * + * @returns {CallBuilder} this CallBuilder instance + */ + protected forEndpoint(endpoint: string, param: string): this; + /** + * @private + * @returns {void} + */ + private checkFilter; + /** + * Convert a link object to a function that fetches that link. + * @private + * @param {object} link A link object + * @param {boolean} link.href the URI of the link + * @param {boolean} [link.templated] Whether the link is templated + * @returns {Function} A function that requests the link + */ + private _requestFnForLink; + /** + * Given the json response, find and convert each link into a function that + * calls that link. + * @private + * @param {object} json JSON response + * @returns {object} JSON response with string links replaced with functions + */ + private _parseRecord; + private _sendNormalRequest; + /** + * @private + * @param {object} json Response object + * @returns {object} Extended response + */ + private _parseResponse; + /** + * @private + * @param {object} json Response object + * @returns {object} Extended response object + */ + private _toCollectionPage; + /** + * @private + * @param {object} error Network error object + * @returns {Promise} Promise that rejects with a human-readable error + */ + private _handleNetworkError; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/call_builder.js new file mode 100644 index 000000000..ba9cda7a4 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/call_builder.js @@ -0,0 +1,362 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.CallBuilder = void 0; +var _urijs = _interopRequireDefault(require("urijs")); +var _URITemplate = _interopRequireDefault(require("urijs/src/URITemplate")); +var _errors = require("../errors"); +var _horizon_axios_client = require("./horizon_axios_client"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var JOINABLE = ["transaction"]; +var anyGlobal = global; +var EventSource; +if (typeof false !== 'undefined' && false) { + var _ref, _anyGlobal$EventSourc, _anyGlobal$window; + EventSource = (_ref = (_anyGlobal$EventSourc = anyGlobal.EventSource) !== null && _anyGlobal$EventSourc !== void 0 ? _anyGlobal$EventSourc : (_anyGlobal$window = anyGlobal.window) === null || _anyGlobal$window === void 0 ? void 0 : _anyGlobal$window.EventSource) !== null && _ref !== void 0 ? _ref : require("eventsource"); +} +var CallBuilder = exports.CallBuilder = function () { + function CallBuilder(serverUrl) { + var neighborRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; + _classCallCheck(this, CallBuilder); + this.url = serverUrl.clone(); + this.filter = []; + this.originalSegments = this.url.segment() || []; + this.neighborRoot = neighborRoot; + } + return _createClass(CallBuilder, [{ + key: "call", + value: function call() { + var _this = this; + this.checkFilter(); + return this._sendNormalRequest(this.url).then(function (r) { + return _this._parseResponse(r); + }); + } + }, { + key: "stream", + value: function stream() { + var _this2 = this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (EventSource === undefined) { + throw new Error("Streaming requires eventsource to be enabled. If you need this functionality, compile with USE_EVENTSOURCE=true."); + } + this.checkFilter(); + this.url.setQuery("X-Client-Name", "js-stellar-sdk"); + this.url.setQuery("X-Client-Version", _horizon_axios_client.version); + var es; + var timeout; + var createTimeout = function createTimeout() { + timeout = setTimeout(function () { + var _es; + (_es = es) === null || _es === void 0 || _es.close(); + es = _createEventSource(); + }, options.reconnectTimeout || 15 * 1000); + }; + var _createEventSource = function createEventSource() { + try { + es = new EventSource(_this2.url.toString()); + } catch (err) { + if (options.onerror) { + options.onerror(err); + } + } + createTimeout(); + if (!es) { + return es; + } + var closed = false; + var onClose = function onClose() { + if (closed) { + return; + } + clearTimeout(timeout); + es.close(); + _createEventSource(); + closed = true; + }; + var onMessage = function onMessage(message) { + if (message.type === "close") { + onClose(); + return; + } + var result = message.data ? _this2._parseRecord(JSON.parse(message.data)) : message; + if (result.paging_token) { + _this2.url.setQuery("cursor", result.paging_token); + } + clearTimeout(timeout); + createTimeout(); + if (typeof options.onmessage !== "undefined") { + options.onmessage(result); + } + }; + var onError = function onError(error) { + if (options.onerror) { + options.onerror(error); + } + }; + if (es.addEventListener) { + es.addEventListener("message", onMessage.bind(_this2)); + es.addEventListener("error", onError.bind(_this2)); + es.addEventListener("close", onClose.bind(_this2)); + } else { + es.onmessage = onMessage.bind(_this2); + es.onerror = onError.bind(_this2); + } + return es; + }; + _createEventSource(); + return function () { + var _es2; + clearTimeout(timeout); + (_es2 = es) === null || _es2 === void 0 || _es2.close(); + }; + } + }, { + key: "cursor", + value: function cursor(_cursor) { + this.url.setQuery("cursor", _cursor); + return this; + } + }, { + key: "limit", + value: function limit(recordsNumber) { + this.url.setQuery("limit", recordsNumber.toString()); + return this; + } + }, { + key: "order", + value: function order(direction) { + this.url.setQuery("order", direction); + return this; + } + }, { + key: "join", + value: function join(include) { + this.url.setQuery("join", include); + return this; + } + }, { + key: "forEndpoint", + value: function forEndpoint(endpoint, param) { + if (this.neighborRoot === "") { + throw new Error("Invalid usage: neighborRoot not set in constructor"); + } + this.filter.push([endpoint, param, this.neighborRoot]); + return this; + } + }, { + key: "checkFilter", + value: function checkFilter() { + if (this.filter.length >= 2) { + throw new _errors.BadRequestError("Too many filters specified", this.filter); + } + if (this.filter.length === 1) { + var newSegment = this.originalSegments.concat(this.filter[0]); + this.url.segment(newSegment); + } + } + }, { + key: "_requestFnForLink", + value: function _requestFnForLink(link) { + var _this3 = this; + return _asyncToGenerator(_regeneratorRuntime().mark(function _callee() { + var opts, + uri, + template, + r, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}; + if (link.templated) { + template = (0, _URITemplate.default)(link.href); + uri = (0, _urijs.default)(template.expand(opts)); + } else { + uri = (0, _urijs.default)(link.href); + } + _context.next = 4; + return _this3._sendNormalRequest(uri); + case 4: + r = _context.sent; + return _context.abrupt("return", _this3._parseResponse(r)); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + } + }, { + key: "_parseRecord", + value: function _parseRecord(json) { + var _this4 = this; + if (!json._links) { + return json; + } + Object.keys(json._links).forEach(function (key) { + var n = json._links[key]; + var included = false; + if (typeof json[key] !== "undefined") { + json["".concat(key, "_attr")] = json[key]; + included = true; + } + if (included && JOINABLE.indexOf(key) >= 0) { + var record = _this4._parseRecord(json[key]); + json[key] = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", record); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + } else { + json[key] = _this4._requestFnForLink(n); + } + }); + return json; + } + }, { + key: "_sendNormalRequest", + value: function () { + var _sendNormalRequest2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(initialUrl) { + var url; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + url = initialUrl; + if (url.authority() === "") { + url = url.authority(this.url.authority()); + } + if (url.protocol() === "") { + url = url.protocol(this.url.protocol()); + } + return _context3.abrupt("return", _horizon_axios_client.AxiosClient.get(url.toString()).then(function (response) { + return response.data; + }).catch(this._handleNetworkError)); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function _sendNormalRequest(_x) { + return _sendNormalRequest2.apply(this, arguments); + } + return _sendNormalRequest; + }() + }, { + key: "_parseResponse", + value: function _parseResponse(json) { + if (json._embedded && json._embedded.records) { + return this._toCollectionPage(json); + } + return this._parseRecord(json); + } + }, { + key: "_toCollectionPage", + value: function _toCollectionPage(json) { + var _this5 = this; + for (var i = 0; i < json._embedded.records.length; i += 1) { + json._embedded.records[i] = this._parseRecord(json._embedded.records[i]); + } + return { + records: json._embedded.records, + next: function () { + var _next2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + var r; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _this5._sendNormalRequest((0, _urijs.default)(json._links.next.href)); + case 2: + r = _context4.sent; + return _context4.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function next() { + return _next2.apply(this, arguments); + } + return next; + }(), + prev: function () { + var _prev = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5() { + var r; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return _this5._sendNormalRequest((0, _urijs.default)(json._links.prev.href)); + case 2: + r = _context5.sent; + return _context5.abrupt("return", _this5._toCollectionPage(r)); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function prev() { + return _prev.apply(this, arguments); + } + return prev; + }() + }; + } + }, { + key: "_handleNetworkError", + value: (function () { + var _handleNetworkError2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(error) { + var _error$response$statu, _error$response$statu2; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + if (!(error.response && error.response.status)) { + _context6.next = 8; + break; + } + _context6.t0 = error.response.status; + _context6.next = _context6.t0 === 404 ? 4 : 5; + break; + case 4: + return _context6.abrupt("return", Promise.reject(new _errors.NotFoundError((_error$response$statu = error.response.statusText) !== null && _error$response$statu !== void 0 ? _error$response$statu : "Not Found", error.response.data))); + case 5: + return _context6.abrupt("return", Promise.reject(new _errors.NetworkError((_error$response$statu2 = error.response.statusText) !== null && _error$response$statu2 !== void 0 ? _error$response$statu2 : "Unknown", error.response.data))); + case 6: + _context6.next = 9; + break; + case 8: + return _context6.abrupt("return", Promise.reject(new Error(error.message))); + case 9: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + function _handleNetworkError(_x2) { + return _handleNetworkError2.apply(this, arguments); + } + return _handleNetworkError; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/claimable_balances_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/claimable_balances_call_builder.d.ts new file mode 100644 index 000000000..6e5f7eea7 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/claimable_balances_call_builder.d.ts @@ -0,0 +1,50 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link ClaimableBalanceCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#claimableBalances}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/claimablebalances|Claimable Balances} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class ClaimableBalanceCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The claimable balance details endpoint provides information on a single claimable balance. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-claimable-balance|Claimable Balance Details} + * @param {string} claimableBalanceId Claimable balance ID + * @returns {CallBuilder} CallBuilder OperationCallBuilder instance + */ + claimableBalance(claimableBalanceId: string): CallBuilder; + /** + * Returns all claimable balances which are sponsored by the given account ID. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-claimable-balances|Claimable Balances} + * @param {string} sponsor For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance + */ + sponsor(sponsor: string): this; + /** + * Returns all claimable balances which can be claimed by the given account ID. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-claimable-balances|Claimable Balances} + * @param {string} claimant For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance + */ + claimant(claimant: string): this; + /** + * Returns all claimable balances which provide a balance for the given asset. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-claimable-balances|Claimable Balances} + * @param {Asset} asset The Asset held by the claimable balance + * @returns {ClaimableBalanceCallBuilder} current ClaimableBalanceCallBuilder instance + */ + asset(asset: Asset): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/claimable_balances_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/claimable_balances_call_builder.js new file mode 100644 index 000000000..188c8076a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/claimable_balances_call_builder.js @@ -0,0 +1,56 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ClaimableBalanceCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var ClaimableBalanceCallBuilder = exports.ClaimableBalanceCallBuilder = function (_CallBuilder) { + function ClaimableBalanceCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, ClaimableBalanceCallBuilder); + _this = _callSuper(this, ClaimableBalanceCallBuilder, [serverUrl]); + _this.url.segment("claimable_balances"); + return _this; + } + _inherits(ClaimableBalanceCallBuilder, _CallBuilder); + return _createClass(ClaimableBalanceCallBuilder, [{ + key: "claimableBalance", + value: function claimableBalance(claimableBalanceId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([claimableBalanceId]); + return builder; + } + }, { + key: "sponsor", + value: function sponsor(_sponsor) { + this.url.setQuery("sponsor", _sponsor); + return this; + } + }, { + key: "claimant", + value: function claimant(_claimant) { + this.url.setQuery("claimant", _claimant); + return this; + } + }, { + key: "asset", + value: function asset(_asset) { + this.url.setQuery("asset", _asset.toString()); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/effect_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/effect_call_builder.d.ts new file mode 100644 index 000000000..8f1e56266 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/effect_call_builder.d.ts @@ -0,0 +1,53 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link EffectCallBuilder} pointed to server defined by serverUrl. + * Do not create this object directly, use {@link Horizon.Server#effects}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/effects|All Effects} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class EffectCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * This endpoint represents all effects that changed a given account. It will return relevant effects from the creation of the account to the current ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-effects-by-account-id|Effects for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * Effects are the specific ways that the ledger was changed by any operation. + * + * This endpoint represents all effects that occurred in the given ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-ledgers-effects|Effects for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all effects that occurred as a result of a given transaction. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-transactions-effects|Effects for Transaction} + * @param {string} transactionId Transaction ID + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forTransaction(transactionId: string): this; + /** + * This endpoint represents all effects that occurred as a result of a given operation. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-an-operations-effects|Effects for Operation} + * @param {number} operationId Operation ID + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forOperation(operationId: string): this; + /** + * This endpoint represents all effects involving a particular liquidity pool. + * + * @param {string} poolId liquidity pool ID + * @returns {EffectCallBuilder} this EffectCallBuilder instance + */ + forLiquidityPool(poolId: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/effect_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/effect_call_builder.js new file mode 100644 index 000000000..147128700 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/effect_call_builder.js @@ -0,0 +1,56 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.EffectCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var EffectCallBuilder = exports.EffectCallBuilder = function (_CallBuilder) { + function EffectCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, EffectCallBuilder); + _this = _callSuper(this, EffectCallBuilder, [serverUrl, "effects"]); + _this.url.segment("effects"); + return _this; + } + _inherits(EffectCallBuilder, _CallBuilder); + return _createClass(EffectCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forOperation", + value: function forOperation(operationId) { + return this.forEndpoint("operations", operationId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/friendbot_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/friendbot_builder.d.ts new file mode 100644 index 000000000..30e5addb9 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/friendbot_builder.d.ts @@ -0,0 +1,4 @@ +import { CallBuilder } from "./call_builder"; +export declare class FriendbotBuilder extends CallBuilder { + constructor(serverUrl: URI, address: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/friendbot_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/friendbot_builder.js new file mode 100644 index 000000000..f80bd06f8 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/friendbot_builder.js @@ -0,0 +1,32 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FriendbotBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var FriendbotBuilder = exports.FriendbotBuilder = function (_CallBuilder) { + function FriendbotBuilder(serverUrl, address) { + var _this; + _classCallCheck(this, FriendbotBuilder); + _this = _callSuper(this, FriendbotBuilder, [serverUrl]); + _this.url.segment("friendbot"); + _this.url.setQuery("addr", address); + return _this; + } + _inherits(FriendbotBuilder, _CallBuilder); + return _createClass(FriendbotBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/horizon_api.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/horizon_api.d.ts new file mode 100644 index 000000000..d52968614 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/horizon_api.d.ts @@ -0,0 +1,540 @@ +import { AssetType, MemoType } from "@stellar/stellar-base"; +export declare namespace HorizonApi { + interface ResponseLink { + href: string; + templated?: boolean; + } + interface BaseResponse { + _links: { + [key in T | "self"]: ResponseLink; + }; + } + interface SubmitTransactionResponse { + hash: string; + ledger: number; + successful: boolean; + envelope_xdr: string; + result_xdr: string; + result_meta_xdr: string; + paging_token: string; + } + interface SubmitAsyncTransactionResponse { + hash: string; + tx_status: string; + error_result_xdr: string; + } + interface FeeBumpTransactionResponse { + hash: string; + signatures: string[]; + } + interface InnerTransactionResponse { + hash: string; + signatures: string[]; + max_fee: string; + } + interface TransactionPreconditions { + timebounds?: { + min_time: string; + max_time: string; + }; + ledgerbounds?: { + min_ledger: number; + max_ledger: number; + }; + min_account_sequence?: string; + min_account_sequence_age?: string; + min_account_sequence_ledger_gap?: number; + extra_signers?: string[]; + } + interface TransactionResponse extends SubmitTransactionResponse, BaseResponse<"account" | "ledger" | "operations" | "effects" | "succeeds" | "precedes"> { + created_at: string; + fee_meta_xdr: string; + fee_charged: number | string; + max_fee: number | string; + id: string; + memo_type: MemoType; + memo?: string; + memo_bytes?: string; + operation_count: number; + paging_token: string; + signatures: string[]; + source_account: string; + source_account_sequence: string; + fee_account: string; + inner_transaction?: InnerTransactionResponse; + fee_bump_transaction?: FeeBumpTransactionResponse; + preconditions?: TransactionPreconditions; + } + interface BalanceLineNative { + balance: string; + asset_type: AssetType.native; + buying_liabilities: string; + selling_liabilities: string; + } + interface BalanceLineLiquidityPool { + liquidity_pool_id: string; + asset_type: AssetType.liquidityPoolShares; + balance: string; + limit: string; + last_modified_ledger: number; + is_authorized: boolean; + is_authorized_to_maintain_liabilities: boolean; + is_clawback_enabled: boolean; + sponsor?: string; + } + interface BalanceLineAsset { + balance: string; + limit: string; + asset_type: T; + asset_code: string; + asset_issuer: string; + buying_liabilities: string; + selling_liabilities: string; + last_modified_ledger: number; + is_authorized: boolean; + is_authorized_to_maintain_liabilities: boolean; + is_clawback_enabled: boolean; + sponsor?: string; + } + type BalanceLine = T extends AssetType.native ? BalanceLineNative : T extends AssetType.credit4 | AssetType.credit12 ? BalanceLineAsset : T extends AssetType.liquidityPoolShares ? BalanceLineLiquidityPool : BalanceLineNative | BalanceLineAsset | BalanceLineLiquidityPool; + interface AssetAccounts { + authorized: number; + authorized_to_maintain_liabilities: number; + unauthorized: number; + } + interface AssetBalances { + authorized: string; + authorized_to_maintain_liabilities: string; + unauthorized: string; + } + interface PriceR { + numerator: number; + denominator: number; + } + interface PriceRShorthand { + n: number; + d: number; + } + interface AccountThresholds { + low_threshold: number; + med_threshold: number; + high_threshold: number; + } + interface Flags { + auth_immutable: boolean; + auth_required: boolean; + auth_revocable: boolean; + auth_clawback_enabled: boolean; + } + interface AccountSigner { + key: string; + weight: number; + type: string; + sponsor?: string; + } + interface AccountResponse extends BaseResponse<"transactions" | "operations" | "payments" | "effects" | "offers" | "trades" | "data"> { + id: string; + paging_token: string; + account_id: string; + sequence: string; + sequence_ledger?: number; + sequence_time?: string; + subentry_count: number; + thresholds: AccountThresholds; + last_modified_ledger: number; + last_modified_time: string; + flags: Flags; + balances: BalanceLine[]; + signers: AccountSigner[]; + data: { + [key: string]: string; + }; + sponsor?: string; + num_sponsoring: number; + num_sponsored: number; + } + enum LiquidityPoolType { + constantProduct = "constant_product" + } + enum OperationResponseType { + createAccount = "create_account", + payment = "payment", + pathPayment = "path_payment_strict_receive", + createPassiveOffer = "create_passive_sell_offer", + manageOffer = "manage_sell_offer", + setOptions = "set_options", + changeTrust = "change_trust", + allowTrust = "allow_trust", + accountMerge = "account_merge", + inflation = "inflation", + manageData = "manage_data", + bumpSequence = "bump_sequence", + manageBuyOffer = "manage_buy_offer", + pathPaymentStrictSend = "path_payment_strict_send", + createClaimableBalance = "create_claimable_balance", + claimClaimableBalance = "claim_claimable_balance", + beginSponsoringFutureReserves = "begin_sponsoring_future_reserves", + endSponsoringFutureReserves = "end_sponsoring_future_reserves", + revokeSponsorship = "revoke_sponsorship", + clawback = "clawback", + clawbackClaimableBalance = "clawback_claimable_balance", + setTrustLineFlags = "set_trust_line_flags", + liquidityPoolDeposit = "liquidity_pool_deposit", + liquidityPoolWithdraw = "liquidity_pool_withdraw", + invokeHostFunction = "invoke_host_function", + bumpFootprintExpiration = "bump_footprint_expiration", + restoreFootprint = "restore_footprint" + } + enum OperationResponseTypeI { + createAccount = 0, + payment = 1, + pathPayment = 2, + createPassiveOffer = 3, + manageOffer = 4, + setOptions = 5, + changeTrust = 6, + allowTrust = 7, + accountMerge = 8, + inflation = 9, + manageData = 10, + bumpSequence = 11, + manageBuyOffer = 12, + pathPaymentStrictSend = 13, + createClaimableBalance = 14, + claimClaimableBalance = 15, + beginSponsoringFutureReserves = 16, + endSponsoringFutureReserves = 17, + revokeSponsorship = 18, + clawback = 19, + clawbackClaimableBalance = 20, + setTrustLineFlags = 21, + liquidityPoolDeposit = 22, + liquidityPoolWithdraw = 23, + invokeHostFunction = 24, + bumpFootprintExpiration = 25, + restoreFootprint = 26 + } + interface BaseOperationResponse extends BaseResponse<"succeeds" | "precedes" | "effects" | "transaction"> { + id: string; + paging_token: string; + source_account: string; + type: T; + type_i: TI; + created_at: string; + transaction_hash: string; + transaction_successful: boolean; + } + interface CreateAccountOperationResponse extends BaseOperationResponse { + account: string; + funder: string; + starting_balance: string; + } + interface PaymentOperationResponse extends BaseOperationResponse { + from: string; + to: string; + asset_type: AssetType; + asset_code?: string; + asset_issuer?: string; + amount: string; + } + interface PathPaymentOperationResponse extends BaseOperationResponse { + amount: string; + asset_code?: string; + asset_issuer?: string; + asset_type: AssetType; + from: string; + path: Array<{ + asset_code: string; + asset_issuer: string; + asset_type: AssetType; + }>; + source_amount: string; + source_asset_code?: string; + source_asset_issuer?: string; + source_asset_type: AssetType; + source_max: string; + to: string; + } + interface PathPaymentStrictSendOperationResponse extends BaseOperationResponse { + amount: string; + asset_code?: string; + asset_issuer?: string; + asset_type: AssetType; + destination_min: string; + from: string; + path: Array<{ + asset_code: string; + asset_issuer: string; + asset_type: AssetType; + }>; + source_amount: string; + source_asset_code?: string; + source_asset_issuer?: string; + source_asset_type: AssetType; + to: string; + } + interface ManageOfferOperationResponse extends BaseOperationResponse { + offer_id: number | string; + amount: string; + buying_asset_type: AssetType; + buying_asset_code?: string; + buying_asset_issuer?: string; + price: string; + price_r: PriceR; + selling_asset_type: AssetType; + selling_asset_code?: string; + selling_asset_issuer?: string; + } + interface PassiveOfferOperationResponse extends BaseOperationResponse { + offer_id: number | string; + amount: string; + buying_asset_type: AssetType; + buying_asset_code?: string; + buying_asset_issuer?: string; + price: string; + price_r: PriceR; + selling_asset_type: AssetType; + selling_asset_code?: string; + selling_asset_issuer?: string; + } + interface SetOptionsOperationResponse extends BaseOperationResponse { + signer_key?: string; + signer_weight?: number; + master_key_weight?: number; + low_threshold?: number; + med_threshold?: number; + high_threshold?: number; + home_domain?: string; + set_flags: Array<1 | 2 | 4>; + set_flags_s: Array<"auth_required_flag" | "auth_revocable_flag" | "auth_clawback_enabled_flag">; + clear_flags: Array<1 | 2 | 4>; + clear_flags_s: Array<"auth_required_flag" | "auth_revocable_flag" | "auth_clawback_enabled_flag">; + } + interface ChangeTrustOperationResponse extends BaseOperationResponse { + asset_type: AssetType.credit4 | AssetType.credit12 | AssetType.liquidityPoolShares; + asset_code?: string; + asset_issuer?: string; + liquidity_pool_id?: string; + trustee?: string; + trustor: string; + limit: string; + } + interface AllowTrustOperationResponse extends BaseOperationResponse { + asset_type: AssetType; + asset_code: string; + asset_issuer: string; + authorize: boolean; + authorize_to_maintain_liabilities: boolean; + trustee: string; + trustor: string; + } + interface AccountMergeOperationResponse extends BaseOperationResponse { + into: string; + } + interface InflationOperationResponse extends BaseOperationResponse { + } + interface ManageDataOperationResponse extends BaseOperationResponse { + name: string; + value: Buffer; + } + interface BumpSequenceOperationResponse extends BaseOperationResponse { + bump_to: string; + } + interface Predicate { + and?: Predicate[]; + or?: Predicate[]; + not?: Predicate; + abs_before?: string; + rel_before?: string; + } + interface Claimant { + destination: string; + predicate: Predicate; + } + interface CreateClaimableBalanceOperationResponse extends BaseOperationResponse { + asset: string; + amount: string; + sponsor: string; + claimants: Claimant[]; + } + interface ClaimClaimableBalanceOperationResponse extends BaseOperationResponse { + balance_id: string; + claimant: string; + } + interface BeginSponsoringFutureReservesOperationResponse extends BaseOperationResponse { + sponsored_id: string; + } + interface EndSponsoringFutureReservesOperationResponse extends BaseOperationResponse { + begin_sponsor: string; + } + interface RevokeSponsorshipOperationResponse extends BaseOperationResponse { + account_id?: string; + claimable_balance_id?: string; + data_account_id?: string; + data_name?: string; + offer_id?: string; + trustline_account_id?: string; + trustline_asset?: string; + trustline_liquidity_pool_id?: string; + signer_account_id?: string; + signer_key?: string; + } + interface ClawbackOperationResponse extends BaseOperationResponse { + asset_type: AssetType; + asset_code: string; + asset_issuer: string; + from: string; + amount: string; + } + interface ClawbackClaimableBalanceOperationResponse extends BaseOperationResponse { + balance_id: string; + } + interface SetTrustLineFlagsOperationResponse extends BaseOperationResponse { + asset_type: AssetType; + asset_code: string; + asset_issuer: string; + trustor: string; + set_flags: Array<1 | 2 | 4>; + clear_flags: Array<1 | 2 | 4>; + } + interface Reserve { + asset: string; + amount: string; + } + interface DepositLiquidityOperationResponse extends BaseOperationResponse { + liquidity_pool_id: string; + reserves_max: Reserve[]; + min_price: string; + min_price_r: PriceRShorthand; + max_price: string; + max_price_r: PriceRShorthand; + reserves_deposited: Reserve[]; + shares_received: string; + } + interface WithdrawLiquidityOperationResponse extends BaseOperationResponse { + liquidity_pool_id: string; + reserves_min: Reserve[]; + shares: string; + reserves_received: Reserve[]; + } + interface BalanceChange { + asset_type: string; + asset_code?: string; + asset_issuer?: string; + type: string; + from: string; + to: string; + amount: string; + } + interface InvokeHostFunctionOperationResponse extends BaseOperationResponse { + function: string; + parameters: { + value: string; + type: string; + }[]; + address: string; + salt: string; + asset_balance_changes: BalanceChange[]; + } + interface BumpFootprintExpirationOperationResponse extends BaseOperationResponse { + ledgers_to_expire: number; + } + interface RestoreFootprintOperationResponse extends BaseOperationResponse { + } + interface ResponseCollection { + _links: { + self: ResponseLink; + next: ResponseLink; + prev: ResponseLink; + }; + _embedded: { + records: T[]; + }; + } + interface TransactionResponseCollection extends ResponseCollection { + } + interface FeeDistribution { + max: string; + min: string; + mode: string; + p10: string; + p20: string; + p30: string; + p40: string; + p50: string; + p60: string; + p70: string; + p80: string; + p90: string; + p95: string; + p99: string; + } + interface FeeStatsResponse { + last_ledger: string; + last_ledger_base_fee: string; + ledger_capacity_usage: string; + fee_charged: FeeDistribution; + max_fee: FeeDistribution; + } + type ErrorResponseData = ErrorResponseData.RateLimitExceeded | ErrorResponseData.InternalServerError | ErrorResponseData.TransactionFailed; + namespace ErrorResponseData { + interface Base { + status: number; + title: string; + type: string; + details: string; + instance: string; + } + interface RateLimitExceeded extends Base { + status: 429; + title: "Rate Limit Exceeded"; + } + interface InternalServerError extends Base { + status: 500; + title: "Internal Server Error"; + } + interface TransactionFailed extends Base { + status: 400; + title: "Transaction Failed"; + extras: TransactionFailedExtras; + } + } + enum TransactionFailedResultCodes { + TX_FAILED = "tx_failed", + TX_BAD_SEQ = "tx_bad_seq", + TX_BAD_AUTH = "tx_bad_auth", + TX_BAD_AUTH_EXTRA = "tx_bad_auth_extra", + TX_FEE_BUMP_INNER_SUCCESS = "tx_fee_bump_inner_success", + TX_FEE_BUMP_INNER_FAILED = "tx_fee_bump_inner_failed", + TX_NOT_SUPPORTED = "tx_not_supported", + TX_SUCCESS = "tx_success", + TX_TOO_EARLY = "tx_too_early", + TX_TOO_LATE = "tx_too_late", + TX_MISSING_OPERATION = "tx_missing_operation", + TX_INSUFFICIENT_BALANCE = "tx_insufficient_balance", + TX_NO_SOURCE_ACCOUNT = "tx_no_source_account", + TX_INSUFFICIENT_FEE = "tx_insufficient_fee", + TX_INTERNAL_ERROR = "tx_internal_error" + } + interface TransactionFailedExtras { + envelope_xdr: string; + result_codes: { + transaction: TransactionFailedResultCodes; + operations: string[]; + }; + result_xdr: string; + } + interface RootResponse { + horizon_version: string; + core_version: string; + ingest_latest_ledger: number; + history_latest_ledger: number; + history_latest_ledger_closed_at: string; + history_elder_ledger: number; + core_latest_ledger: number; + network_passphrase: string; + current_protocol_version: number; + supported_protocol_version: number; + core_supported_protocol_version: number; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/horizon_api.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/horizon_api.js new file mode 100644 index 000000000..b4b1c1878 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/horizon_api.js @@ -0,0 +1,96 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.HorizonApi = void 0; +var HorizonApi; +(function (_HorizonApi) { + var LiquidityPoolType = function (LiquidityPoolType) { + LiquidityPoolType["constantProduct"] = "constant_product"; + return LiquidityPoolType; + }({}); + _HorizonApi.LiquidityPoolType = LiquidityPoolType; + var OperationResponseType = function (OperationResponseType) { + OperationResponseType["createAccount"] = "create_account"; + OperationResponseType["payment"] = "payment"; + OperationResponseType["pathPayment"] = "path_payment_strict_receive"; + OperationResponseType["createPassiveOffer"] = "create_passive_sell_offer"; + OperationResponseType["manageOffer"] = "manage_sell_offer"; + OperationResponseType["setOptions"] = "set_options"; + OperationResponseType["changeTrust"] = "change_trust"; + OperationResponseType["allowTrust"] = "allow_trust"; + OperationResponseType["accountMerge"] = "account_merge"; + OperationResponseType["inflation"] = "inflation"; + OperationResponseType["manageData"] = "manage_data"; + OperationResponseType["bumpSequence"] = "bump_sequence"; + OperationResponseType["manageBuyOffer"] = "manage_buy_offer"; + OperationResponseType["pathPaymentStrictSend"] = "path_payment_strict_send"; + OperationResponseType["createClaimableBalance"] = "create_claimable_balance"; + OperationResponseType["claimClaimableBalance"] = "claim_claimable_balance"; + OperationResponseType["beginSponsoringFutureReserves"] = "begin_sponsoring_future_reserves"; + OperationResponseType["endSponsoringFutureReserves"] = "end_sponsoring_future_reserves"; + OperationResponseType["revokeSponsorship"] = "revoke_sponsorship"; + OperationResponseType["clawback"] = "clawback"; + OperationResponseType["clawbackClaimableBalance"] = "clawback_claimable_balance"; + OperationResponseType["setTrustLineFlags"] = "set_trust_line_flags"; + OperationResponseType["liquidityPoolDeposit"] = "liquidity_pool_deposit"; + OperationResponseType["liquidityPoolWithdraw"] = "liquidity_pool_withdraw"; + OperationResponseType["invokeHostFunction"] = "invoke_host_function"; + OperationResponseType["bumpFootprintExpiration"] = "bump_footprint_expiration"; + OperationResponseType["restoreFootprint"] = "restore_footprint"; + return OperationResponseType; + }({}); + _HorizonApi.OperationResponseType = OperationResponseType; + var OperationResponseTypeI = function (OperationResponseTypeI) { + OperationResponseTypeI[OperationResponseTypeI["createAccount"] = 0] = "createAccount"; + OperationResponseTypeI[OperationResponseTypeI["payment"] = 1] = "payment"; + OperationResponseTypeI[OperationResponseTypeI["pathPayment"] = 2] = "pathPayment"; + OperationResponseTypeI[OperationResponseTypeI["createPassiveOffer"] = 3] = "createPassiveOffer"; + OperationResponseTypeI[OperationResponseTypeI["manageOffer"] = 4] = "manageOffer"; + OperationResponseTypeI[OperationResponseTypeI["setOptions"] = 5] = "setOptions"; + OperationResponseTypeI[OperationResponseTypeI["changeTrust"] = 6] = "changeTrust"; + OperationResponseTypeI[OperationResponseTypeI["allowTrust"] = 7] = "allowTrust"; + OperationResponseTypeI[OperationResponseTypeI["accountMerge"] = 8] = "accountMerge"; + OperationResponseTypeI[OperationResponseTypeI["inflation"] = 9] = "inflation"; + OperationResponseTypeI[OperationResponseTypeI["manageData"] = 10] = "manageData"; + OperationResponseTypeI[OperationResponseTypeI["bumpSequence"] = 11] = "bumpSequence"; + OperationResponseTypeI[OperationResponseTypeI["manageBuyOffer"] = 12] = "manageBuyOffer"; + OperationResponseTypeI[OperationResponseTypeI["pathPaymentStrictSend"] = 13] = "pathPaymentStrictSend"; + OperationResponseTypeI[OperationResponseTypeI["createClaimableBalance"] = 14] = "createClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["claimClaimableBalance"] = 15] = "claimClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["beginSponsoringFutureReserves"] = 16] = "beginSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["endSponsoringFutureReserves"] = 17] = "endSponsoringFutureReserves"; + OperationResponseTypeI[OperationResponseTypeI["revokeSponsorship"] = 18] = "revokeSponsorship"; + OperationResponseTypeI[OperationResponseTypeI["clawback"] = 19] = "clawback"; + OperationResponseTypeI[OperationResponseTypeI["clawbackClaimableBalance"] = 20] = "clawbackClaimableBalance"; + OperationResponseTypeI[OperationResponseTypeI["setTrustLineFlags"] = 21] = "setTrustLineFlags"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolDeposit"] = 22] = "liquidityPoolDeposit"; + OperationResponseTypeI[OperationResponseTypeI["liquidityPoolWithdraw"] = 23] = "liquidityPoolWithdraw"; + OperationResponseTypeI[OperationResponseTypeI["invokeHostFunction"] = 24] = "invokeHostFunction"; + OperationResponseTypeI[OperationResponseTypeI["bumpFootprintExpiration"] = 25] = "bumpFootprintExpiration"; + OperationResponseTypeI[OperationResponseTypeI["restoreFootprint"] = 26] = "restoreFootprint"; + return OperationResponseTypeI; + }({}); + _HorizonApi.OperationResponseTypeI = OperationResponseTypeI; + ; + var TransactionFailedResultCodes = function (TransactionFailedResultCodes) { + TransactionFailedResultCodes["TX_FAILED"] = "tx_failed"; + TransactionFailedResultCodes["TX_BAD_SEQ"] = "tx_bad_seq"; + TransactionFailedResultCodes["TX_BAD_AUTH"] = "tx_bad_auth"; + TransactionFailedResultCodes["TX_BAD_AUTH_EXTRA"] = "tx_bad_auth_extra"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_SUCCESS"] = "tx_fee_bump_inner_success"; + TransactionFailedResultCodes["TX_FEE_BUMP_INNER_FAILED"] = "tx_fee_bump_inner_failed"; + TransactionFailedResultCodes["TX_NOT_SUPPORTED"] = "tx_not_supported"; + TransactionFailedResultCodes["TX_SUCCESS"] = "tx_success"; + TransactionFailedResultCodes["TX_TOO_EARLY"] = "tx_too_early"; + TransactionFailedResultCodes["TX_TOO_LATE"] = "tx_too_late"; + TransactionFailedResultCodes["TX_MISSING_OPERATION"] = "tx_missing_operation"; + TransactionFailedResultCodes["TX_INSUFFICIENT_BALANCE"] = "tx_insufficient_balance"; + TransactionFailedResultCodes["TX_NO_SOURCE_ACCOUNT"] = "tx_no_source_account"; + TransactionFailedResultCodes["TX_INSUFFICIENT_FEE"] = "tx_insufficient_fee"; + TransactionFailedResultCodes["TX_INTERNAL_ERROR"] = "tx_internal_error"; + return TransactionFailedResultCodes; + }({}); + _HorizonApi.TransactionFailedResultCodes = TransactionFailedResultCodes; +})(HorizonApi || (exports.HorizonApi = HorizonApi = {})); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/horizon_axios_client.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/horizon_axios_client.d.ts new file mode 100644 index 000000000..a5934c906 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/horizon_axios_client.d.ts @@ -0,0 +1,37 @@ +export declare const version: string; +export interface ServerTime { + serverTime: number; + localTimeRecorded: number; +} +/** + * keep a local map of server times + * (export this purely for testing purposes) + * + * each entry will map the server domain to the last-known time and the local + * time it was recorded, ex: + * + * @example + * "horizon-testnet.stellar.org": { + * serverTime: 1552513039, + * localTimeRecorded: 1552513052 + * } + * + * @constant {Record.} + * @default {} + * @memberof module:Horizon + */ +export declare const SERVER_TIME_MAP: Record; +export declare const AxiosClient: import("../http-client").HttpClient; +export default AxiosClient; +/** + * Given a hostname, get the current time of that server (i.e., use the last- + * recorded server time and offset it by the time since then.) If there IS no + * recorded server time, or it's been 5 minutes since the last, return null. + * @memberof module:Horizon + * + * @param {string} hostname Hostname of a Horizon server. + * @returns {number} The UNIX timestamp (in seconds, not milliseconds) + * representing the current time on that server, or `null` if we don't have + * a record of that time. + */ +export declare function getCurrentServerTime(hostname: string): number | null; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/horizon_axios_client.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/horizon_axios_client.js new file mode 100644 index 000000000..d9c56d163 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/horizon_axios_client.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.SERVER_TIME_MAP = exports.AxiosClient = void 0; +exports.getCurrentServerTime = getCurrentServerTime; +exports.version = void 0; +var _urijs = _interopRequireDefault(require("urijs")); +var _httpClient = require("../http-client"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +var version = exports.version = "13.1.0"; +var SERVER_TIME_MAP = exports.SERVER_TIME_MAP = {}; +var AxiosClient = exports.AxiosClient = (0, _httpClient.create)({ + headers: { + "X-Client-Name": "js-stellar-sdk", + "X-Client-Version": version + } +}); +function toSeconds(ms) { + return Math.floor(ms / 1000); +} +AxiosClient.interceptors.response.use(function (response) { + var hostname = (0, _urijs.default)(response.config.url).hostname(); + var serverTime = 0; + if (response.headers instanceof Headers) { + var dateHeader = response.headers.get('date'); + if (dateHeader) { + serverTime = toSeconds(Date.parse(dateHeader)); + } + } else if (_typeof(response.headers) === 'object' && 'date' in response.headers) { + var headers = response.headers; + if (typeof headers.date === 'string') { + serverTime = toSeconds(Date.parse(headers.date)); + } + } + var localTimeRecorded = toSeconds(new Date().getTime()); + if (!Number.isNaN(serverTime)) { + SERVER_TIME_MAP[hostname] = { + serverTime: serverTime, + localTimeRecorded: localTimeRecorded + }; + } + return response; +}); +var _default = exports.default = AxiosClient; +function getCurrentServerTime(hostname) { + var entry = SERVER_TIME_MAP[hostname]; + if (!entry || !entry.localTimeRecorded || !entry.serverTime) { + return null; + } + var serverTime = entry.serverTime, + localTimeRecorded = entry.localTimeRecorded; + var currentTime = toSeconds(new Date().getTime()); + if (currentTime - localTimeRecorded > 60 * 5) { + return null; + } + return currentTime - localTimeRecorded + serverTime; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/index.d.ts new file mode 100644 index 000000000..9a351398f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/index.d.ts @@ -0,0 +1,8 @@ +/** @module Horizon */ +export * from "./horizon_api"; +export * from "./server_api"; +export * from "./account_response"; +export { HorizonServer as Server } from "./server"; +export { default as AxiosClient, SERVER_TIME_MAP, getCurrentServerTime } from "./horizon_axios_client"; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/index.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/index.js new file mode 100644 index 000000000..4ea741268 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/index.js @@ -0,0 +1,78 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Server: true, + AxiosClient: true, + SERVER_TIME_MAP: true, + getCurrentServerTime: true +}; +Object.defineProperty(exports, "AxiosClient", { + enumerable: true, + get: function get() { + return _horizon_axios_client.default; + } +}); +Object.defineProperty(exports, "SERVER_TIME_MAP", { + enumerable: true, + get: function get() { + return _horizon_axios_client.SERVER_TIME_MAP; + } +}); +Object.defineProperty(exports, "Server", { + enumerable: true, + get: function get() { + return _server.HorizonServer; + } +}); +exports.default = void 0; +Object.defineProperty(exports, "getCurrentServerTime", { + enumerable: true, + get: function get() { + return _horizon_axios_client.getCurrentServerTime; + } +}); +var _horizon_api = require("./horizon_api"); +Object.keys(_horizon_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _horizon_api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _horizon_api[key]; + } + }); +}); +var _server_api = require("./server_api"); +Object.keys(_server_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _server_api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _server_api[key]; + } + }); +}); +var _account_response = require("./account_response"); +Object.keys(_account_response).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _account_response[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _account_response[key]; + } + }); +}); +var _server = require("./server"); +var _horizon_axios_client = _interopRequireWildcard(require("./horizon_axios_client")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/ledger_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/ledger_call_builder.d.ts new file mode 100644 index 000000000..76c7f38ef --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/ledger_call_builder.d.ts @@ -0,0 +1,23 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link LedgerCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#ledgers}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-ledgers|All Ledgers} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class LedgerCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Provides information on a single ledger. + * @param {number|string} sequence Ledger sequence + * @returns {LedgerCallBuilder} current LedgerCallBuilder instance + */ + ledger(sequence: number | string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/ledger_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/ledger_call_builder.js new file mode 100644 index 000000000..93b2801b3 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/ledger_call_builder.js @@ -0,0 +1,37 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LedgerCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var LedgerCallBuilder = exports.LedgerCallBuilder = function (_CallBuilder) { + function LedgerCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, LedgerCallBuilder); + _this = _callSuper(this, LedgerCallBuilder, [serverUrl]); + _this.url.segment("ledgers"); + return _this; + } + _inherits(LedgerCallBuilder, _CallBuilder); + return _createClass(LedgerCallBuilder, [{ + key: "ledger", + value: function ledger(sequence) { + this.filter.push(["ledgers", sequence.toString()]); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/liquidity_pool_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/liquidity_pool_call_builder.d.ts new file mode 100644 index 000000000..806984c17 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/liquidity_pool_call_builder.d.ts @@ -0,0 +1,37 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link LiquidityPoolCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#liquidityPools}. + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class LiquidityPoolCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Filters out pools whose reserves don't exactly match these assets. + * + * @see Asset + * @returns {LiquidityPoolCallBuilder} current LiquidityPoolCallBuilder instance + */ + forAssets(...assets: Asset[]): this; + /** + * Retrieves all pools an account is participating in. + * + * @param {string} id the participant account to filter by + * @returns {LiquidityPoolCallBuilder} current LiquidityPoolCallBuilder instance + */ + forAccount(id: string): this; + /** + * Retrieves a specific liquidity pool by ID. + * + * @param {string} id the hash/ID of the liquidity pool + * @returns {CallBuilder} a new CallBuilder instance for the /liquidity_pools/:id endpoint + */ + liquidityPoolId(id: string): CallBuilder; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/liquidity_pool_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/liquidity_pool_call_builder.js new file mode 100644 index 000000000..7f0c6ff78 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/liquidity_pool_call_builder.js @@ -0,0 +1,59 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LiquidityPoolCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var LiquidityPoolCallBuilder = exports.LiquidityPoolCallBuilder = function (_CallBuilder) { + function LiquidityPoolCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, LiquidityPoolCallBuilder); + _this = _callSuper(this, LiquidityPoolCallBuilder, [serverUrl]); + _this.url.segment("liquidity_pools"); + return _this; + } + _inherits(LiquidityPoolCallBuilder, _CallBuilder); + return _createClass(LiquidityPoolCallBuilder, [{ + key: "forAssets", + value: function forAssets() { + for (var _len = arguments.length, assets = new Array(_len), _key = 0; _key < _len; _key++) { + assets[_key] = arguments[_key]; + } + var assetList = assets.map(function (asset) { + return asset.toString(); + }).join(","); + this.url.setQuery("reserves", assetList); + return this; + } + }, { + key: "forAccount", + value: function forAccount(id) { + this.url.setQuery("account", id); + return this; + } + }, { + key: "liquidityPoolId", + value: function liquidityPoolId(id) { + if (!id.match(/[a-fA-F0-9]{64}/)) { + throw new TypeError("".concat(id, " does not look like a liquidity pool ID")); + } + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([id.toLowerCase()]); + return builder; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/offer_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/offer_call_builder.d.ts new file mode 100644 index 000000000..2628c3960 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/offer_call_builder.d.ts @@ -0,0 +1,65 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link OfferCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#offers}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/|Offers} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class OfferCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The offer details endpoint provides information on a single offer. The offer ID provided in the id + * argument specifies which offer to load. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/single/|Offer Details} + * @param {string} offerId Offer ID + * @returns {CallBuilder} CallBuilder OperationCallBuilder instance + */ + offer(offerId: string): CallBuilder; + /** + * Returns all offers where the given account is involved. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/accounts/offers/|Offers} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + forAccount(id: string): this; + /** + * Returns all offers buying an asset. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/list/|Offers} + * @see Asset + * @param {Asset} asset For example: `new Asset('USD','GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD')` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + buying(asset: Asset): this; + /** + * Returns all offers selling an asset. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/offers/list/|Offers} + * @see Asset + * @param {Asset} asset For example: `new Asset('EUR','GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD')` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + selling(asset: Asset): this; + /** + * This endpoint filters offers where the given account is sponsoring the offer entry. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-all-offers|Offers} + * @param {string} id For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + sponsor(id: string): this; + /** + * This endpoint filters offers where the given account is the seller. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-all-offers|Offers} + * @param {string} seller For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OfferCallBuilder} current OfferCallBuilder instance + */ + seller(seller: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/offer_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/offer_call_builder.js new file mode 100644 index 000000000..12c6a6277 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/offer_call_builder.js @@ -0,0 +1,79 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OfferCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var OfferCallBuilder = exports.OfferCallBuilder = function (_CallBuilder) { + function OfferCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, OfferCallBuilder); + _this = _callSuper(this, OfferCallBuilder, [serverUrl, "offers"]); + _this.url.segment("offers"); + return _this; + } + _inherits(OfferCallBuilder, _CallBuilder); + return _createClass(OfferCallBuilder, [{ + key: "offer", + value: function offer(offerId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([offerId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(id) { + return this.forEndpoint("accounts", id); + } + }, { + key: "buying", + value: function buying(asset) { + if (!asset.isNative()) { + this.url.setQuery("buying_asset_type", asset.getAssetType()); + this.url.setQuery("buying_asset_code", asset.getCode()); + this.url.setQuery("buying_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("buying_asset_type", "native"); + } + return this; + } + }, { + key: "selling", + value: function selling(asset) { + if (!asset.isNative()) { + this.url.setQuery("selling_asset_type", asset.getAssetType()); + this.url.setQuery("selling_asset_code", asset.getCode()); + this.url.setQuery("selling_asset_issuer", asset.getIssuer()); + } else { + this.url.setQuery("selling_asset_type", "native"); + } + return this; + } + }, { + key: "sponsor", + value: function sponsor(id) { + this.url.setQuery("sponsor", id); + return this; + } + }, { + key: "seller", + value: function seller(_seller) { + this.url.setQuery("seller", _seller); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/operation_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/operation_call_builder.d.ts new file mode 100644 index 000000000..ca7c9781c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/operation_call_builder.d.ts @@ -0,0 +1,69 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link OperationCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#operations}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/operations|All Operations} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl Horizon server URL. + */ +export declare class OperationCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The operation details endpoint provides information on a single operation. The operation ID provided in the id + * argument specifies which operation to load. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-an-operation|Operation Details} + * @param {number} operationId Operation ID + * @returns {CallBuilder} this OperationCallBuilder instance + */ + operation(operationId: string): CallBuilder; + /** + * This endpoint represents all operations that were included in valid transactions that affected a particular account. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-operations-by-account-id|Operations for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * This endpoint represents all operations that reference a given claimable_balance. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/cb-retrieve-related-operations|Operations for Claimable Balance} + * @param {string} claimableBalanceId Claimable Balance ID + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forClaimableBalance(claimableBalanceId: string): this; + /** + * This endpoint returns all operations that occurred in a given ledger. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-ledgers-operations|Operations for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all operations that are part of a given transaction. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-transactions-operations|Operations for Transaction} + * @param {string} transactionId Transaction ID + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forTransaction(transactionId: string): this; + /** + * This endpoint represents all operations involving a particular liquidity pool. + * + * @param {string} poolId liquidity pool ID + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + forLiquidityPool(poolId: string): this; + /** + * Adds a parameter defining whether to include failed transactions. + * By default, only operations of successful transactions are returned. + * + * @param {boolean} value Set to `true` to include operations of failed transactions. + * @returns {OperationCallBuilder} this OperationCallBuilder instance + */ + includeFailed(value: boolean): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/operation_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/operation_call_builder.js new file mode 100644 index 000000000..d24cd67d7 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/operation_call_builder.js @@ -0,0 +1,69 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OperationCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var OperationCallBuilder = exports.OperationCallBuilder = function (_CallBuilder) { + function OperationCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, OperationCallBuilder); + _this = _callSuper(this, OperationCallBuilder, [serverUrl, "operations"]); + _this.url.segment("operations"); + return _this; + } + _inherits(OperationCallBuilder, _CallBuilder); + return _createClass(OperationCallBuilder, [{ + key: "operation", + value: function operation(operationId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([operationId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/orderbook_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/orderbook_call_builder.d.ts new file mode 100644 index 000000000..484126432 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/orderbook_call_builder.d.ts @@ -0,0 +1,20 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link OrderbookCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#orderbook}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/order-books|Orderbook Details} + * + * @augments CallBuilder + * @private + * @class + * @param {string} serverUrl serverUrl Horizon server URL. + * @param {Asset} selling Asset being sold + * @param {Asset} buying Asset being bought + */ +export declare class OrderbookCallBuilder extends CallBuilder { + constructor(serverUrl: URI, selling: Asset, buying: Asset); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/orderbook_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/orderbook_call_builder.js new file mode 100644 index 000000000..c4d3dd4c6 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/orderbook_call_builder.js @@ -0,0 +1,45 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OrderbookCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var OrderbookCallBuilder = exports.OrderbookCallBuilder = function (_CallBuilder) { + function OrderbookCallBuilder(serverUrl, selling, buying) { + var _this; + _classCallCheck(this, OrderbookCallBuilder); + _this = _callSuper(this, OrderbookCallBuilder, [serverUrl]); + _this.url.segment("order_book"); + if (!selling.isNative()) { + _this.url.setQuery("selling_asset_type", selling.getAssetType()); + _this.url.setQuery("selling_asset_code", selling.getCode()); + _this.url.setQuery("selling_asset_issuer", selling.getIssuer()); + } else { + _this.url.setQuery("selling_asset_type", "native"); + } + if (!buying.isNative()) { + _this.url.setQuery("buying_asset_type", buying.getAssetType()); + _this.url.setQuery("buying_asset_code", buying.getCode()); + _this.url.setQuery("buying_asset_issuer", buying.getIssuer()); + } else { + _this.url.setQuery("buying_asset_type", "native"); + } + return _this; + } + _inherits(OrderbookCallBuilder, _CallBuilder); + return _createClass(OrderbookCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/path_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/path_call_builder.d.ts new file mode 100644 index 000000000..56c89afa9 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/path_call_builder.d.ts @@ -0,0 +1,35 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * The Stellar Network allows payments to be made across assets through path payments. A path payment specifies a + * series of assets to route a payment through, from source asset (the asset debited from the payer) to destination + * asset (the asset credited to the payee). + * + * A path search is specified using: + * + * * The destination address + * * The source address + * * The asset and amount that the destination account should receive + * + * As part of the search, horizon will load a list of assets available to the source address and will find any + * payment paths from those source assets to the desired destination asset. The search's amount parameter will be + * used to determine if there a given path can satisfy a payment of the desired amount. + * + * Do not create this object directly, use {@link Horizon.Server#paths}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/paths|Find Payment Paths} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + * @param {string} source The sender's account ID. Any returned path must use a source that the sender can hold. + * @param {string} destination The destination account ID that any returned path should use. + * @param {Asset} destinationAsset The destination asset. + * @param {string} destinationAmount The amount, denominated in the destination asset, that any returned path should be able to satisfy. + */ +export declare class PathCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, source: string, destination: string, destinationAsset: Asset, destinationAmount: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/path_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/path_call_builder.js new file mode 100644 index 000000000..53f5cebbe --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/path_call_builder.js @@ -0,0 +1,41 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PathCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var PathCallBuilder = exports.PathCallBuilder = function (_CallBuilder) { + function PathCallBuilder(serverUrl, source, destination, destinationAsset, destinationAmount) { + var _this; + _classCallCheck(this, PathCallBuilder); + _this = _callSuper(this, PathCallBuilder, [serverUrl]); + _this.url.segment("paths"); + _this.url.setQuery("destination_account", destination); + _this.url.setQuery("source_account", source); + _this.url.setQuery("destination_amount", destinationAmount); + if (!destinationAsset.isNative()) { + _this.url.setQuery("destination_asset_type", destinationAsset.getAssetType()); + _this.url.setQuery("destination_asset_code", destinationAsset.getCode()); + _this.url.setQuery("destination_asset_issuer", destinationAsset.getIssuer()); + } else { + _this.url.setQuery("destination_asset_type", "native"); + } + return _this; + } + _inherits(PathCallBuilder, _CallBuilder); + return _createClass(PathCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/payment_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/payment_call_builder.d.ts new file mode 100644 index 000000000..bcee63c88 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/payment_call_builder.d.ts @@ -0,0 +1,39 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link PaymentCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#payments}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/horizon/resources/list-all-payments/|All Payments} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + */ +export declare class PaymentCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * This endpoint responds with a collection of Payment operations where the given account was either the sender or receiver. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/horizon/resources/get-payments-by-account-id|Payments for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {PaymentCallBuilder} this PaymentCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * This endpoint represents all payment operations that are part of a valid transactions in a given ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/horizon/resources/retrieve-a-ledgers-payments|Payments for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {PaymentCallBuilder} this PaymentCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all payment operations that are part of a given transaction. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/transactions/payments/|Payments for Transaction} + * @param {string} transactionId Transaction ID + * @returns {PaymentCallBuilder} this PaymentCallBuilder instance + */ + forTransaction(transactionId: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/payment_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/payment_call_builder.js new file mode 100644 index 000000000..e3a9c26bf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/payment_call_builder.js @@ -0,0 +1,46 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PaymentCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var PaymentCallBuilder = exports.PaymentCallBuilder = function (_CallBuilder) { + function PaymentCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, PaymentCallBuilder); + _this = _callSuper(this, PaymentCallBuilder, [serverUrl, "payments"]); + _this.url.segment("payments"); + return _this; + } + _inherits(PaymentCallBuilder, _CallBuilder); + return _createClass(PaymentCallBuilder, [{ + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forTransaction", + value: function forTransaction(transactionId) { + return this.forEndpoint("transactions", transactionId); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/server.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/server.d.ts new file mode 100644 index 000000000..ef83c857a --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/server.d.ts @@ -0,0 +1,394 @@ +import { Asset, FeeBumpTransaction, Transaction } from "@stellar/stellar-base"; +import URI from "urijs"; +import { AccountCallBuilder } from "./account_call_builder"; +import { AccountResponse } from "./account_response"; +import { AssetsCallBuilder } from "./assets_call_builder"; +import { ClaimableBalanceCallBuilder } from "./claimable_balances_call_builder"; +import { EffectCallBuilder } from "./effect_call_builder"; +import { FriendbotBuilder } from "./friendbot_builder"; +import { HorizonApi } from "./horizon_api"; +import { LedgerCallBuilder } from "./ledger_call_builder"; +import { LiquidityPoolCallBuilder } from "./liquidity_pool_call_builder"; +import { OfferCallBuilder } from "./offer_call_builder"; +import { OperationCallBuilder } from "./operation_call_builder"; +import { OrderbookCallBuilder } from "./orderbook_call_builder"; +import { PathCallBuilder } from "./path_call_builder"; +import { PaymentCallBuilder } from "./payment_call_builder"; +import { TradeAggregationCallBuilder } from "./trade_aggregation_call_builder"; +import { TradesCallBuilder } from "./trades_call_builder"; +import { TransactionCallBuilder } from "./transaction_call_builder"; +/** + * Default transaction submission timeout for Horizon requests, in milliseconds + * @constant {number} + * @default 60000 + * @memberof module:Horizon.Server + */ +export declare const SUBMIT_TRANSACTION_TIMEOUT: number; +/** + * Server handles the network connection to a [Horizon](https://developers.stellar.org/docs/data/horizon) + * instance and exposes an interface for requests to that instance. + * @class + * @alias module:Horizon.Server + * @memberof module:Horizon + * + * @param {string} serverURL Horizon Server URL (ex. `https://horizon-testnet.stellar.org`). + * @param {module:Horizon.Server.Options} [opts] Options object + */ +export declare class HorizonServer { + /** + * Horizon Server URL (ex. `https://horizon-testnet.stellar.org`) + * + * @todo Solve `URI(this.serverURL as any)`. + */ + readonly serverURL: URI; + constructor(serverURL: string, opts?: HorizonServer.Options); + /** + * Get timebounds for N seconds from now, when you're creating a transaction + * with {@link TransactionBuilder}. + * + * By default, {@link TransactionBuilder} uses the current local time, but + * your machine's local time could be different from Horizon's. This gives you + * more assurance that your timebounds will reflect what you want. + * + * Note that this will generate your timebounds when you **init the transaction**, + * not when you build or submit the transaction! So give yourself enough time to get + * the transaction built and signed before submitting. + * + * @example + * const transaction = new StellarSdk.TransactionBuilder(accountId, { + * fee: await StellarSdk.Server.fetchBaseFee(), + * timebounds: await StellarSdk.Server.fetchTimebounds(100) + * }) + * .addOperation(operation) + * // normally we would need to call setTimeout here, but setting timebounds + * // earlier does the trick! + * .build(); + * + * @param {number} seconds Number of seconds past the current time to wait. + * @param {boolean} [_isRetry] True if this is a retry. Only set this internally! + * This is to avoid a scenario where Horizon is horking up the wrong date. + * @returns {Promise} Promise that resolves a `timebounds` object + * (with the shape `{ minTime: 0, maxTime: N }`) that you can set the `timebounds` option to. + */ + fetchTimebounds(seconds: number, _isRetry?: boolean): Promise; + /** + * Fetch the base fee. Since this hits the server, if the server call fails, + * you might get an error. You should be prepared to use a default value if + * that happens! + * @returns {Promise} Promise that resolves to the base fee. + */ + fetchBaseFee(): Promise; + /** + * Fetch the fee stats endpoint. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/fee-stats|Fee Stats} + * @returns {Promise} Promise that resolves to the fee stats returned by Horizon. + */ + feeStats(): Promise; + /** + * Fetch the Horizon server's root endpoint. + * @returns {Promise} Promise that resolves to the root endpoint returned by Horizon. + */ + root(): Promise; + /** + * Submits a transaction to the network. + * + * By default this function calls {@link Horizon.Server#checkMemoRequired}, you can + * skip this check by setting the option `skipMemoRequiredCheck` to `true`. + * + * If you submit any number of `manageOffer` operations, this will add an + * attribute to the response that will help you analyze what happened with + * your offers. + * + * For example, you'll want to examine `offerResults` to add affordances like + * these to your app: + * - If `wasImmediatelyFilled` is true, then no offer was created. So if you + * normally watch the `Server.offers` endpoint for offer updates, you + * instead need to check `Server.trades` to find the result of this filled + * offer. + * - If `wasImmediatelyDeleted` is true, then the offer you submitted was + * deleted without reaching the orderbook or being matched (possibly because + * your amounts were rounded down to zero). So treat the just-submitted + * offer request as if it never happened. + * - If `wasPartiallyFilled` is true, you can tell the user that + * `amountBought` or `amountSold` have already been transferred. + * + * @example + * const res = { + * ...response, + * offerResults: [ + * { + * // Exact ordered list of offers that executed, with the exception + * // that the last one may not have executed entirely. + * offersClaimed: [ + * sellerId: String, + * offerId: String, + * assetSold: { + * type: 'native|credit_alphanum4|credit_alphanum12', + * + * // these are only present if the asset is not native + * assetCode: String, + * issuer: String, + * }, + * + * // same shape as assetSold + * assetBought: {} + * ], + * + * // What effect your manageOffer op had + * effect: "manageOfferCreated|manageOfferUpdated|manageOfferDeleted", + * + * // Whether your offer immediately got matched and filled + * wasImmediatelyFilled: Boolean, + * + * // Whether your offer immediately got deleted, if for example the order was too small + * wasImmediatelyDeleted: Boolean, + * + * // Whether the offer was partially, but not completely, filled + * wasPartiallyFilled: Boolean, + * + * // The full requested amount of the offer is open for matching + * isFullyOpen: Boolean, + * + * // The total amount of tokens bought / sold during transaction execution + * amountBought: Number, + * amountSold: Number, + * + * // if the offer was created, updated, or partially filled, this is + * // the outstanding offer + * currentOffer: { + * offerId: String, + * amount: String, + * price: { + * n: String, + * d: String, + * }, + * + * selling: { + * type: 'native|credit_alphanum4|credit_alphanum12', + * + * // these are only present if the asset is not native + * assetCode: String, + * issuer: String, + * }, + * + * // same as `selling` + * buying: {}, + * }, + * + * // the index of this particular operation in the op stack + * operationIndex: Number + * } + * ] + * } + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/submit-a-transaction|Submit a Transaction} + * @param {Transaction|FeeBumpTransaction} transaction - The transaction to submit. + * @param {object} [opts] Options object + * @param {boolean} [opts.skipMemoRequiredCheck] - Allow skipping memo + * required check, default: `false`. See + * [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md). + * @returns {Promise} Promise that resolves or rejects with response from + * horizon. + */ + submitTransaction(transaction: Transaction | FeeBumpTransaction, opts?: HorizonServer.SubmitTransactionOptions): Promise; + /** + * Submits an asynchronous transaction to the network. Unlike the synchronous version, which blocks + * and waits for the transaction to be ingested in Horizon, this endpoint relays the response from + * core directly back to the user. + * + * By default, this function calls {@link HorizonServer#checkMemoRequired}, you can + * skip this check by setting the option `skipMemoRequiredCheck` to `true`. + * + * @see [Submit-Async-Transaction](https://developers.stellar.org/docs/data/horizon/api-reference/resources/submit-async-transaction) + * @param {Transaction|FeeBumpTransaction} transaction - The transaction to submit. + * @param {object} [opts] Options object + * @param {boolean} [opts.skipMemoRequiredCheck] - Allow skipping memo + * required check, default: `false`. See + * [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md). + * @returns {Promise} Promise that resolves or rejects with response from + * horizon. + */ + submitAsyncTransaction(transaction: Transaction | FeeBumpTransaction, opts?: HorizonServer.SubmitTransactionOptions): Promise; + /** + * @returns {AccountCallBuilder} New {@link AccountCallBuilder} object configured by a current Horizon server configuration. + */ + accounts(): AccountCallBuilder; + /** + * @returns {ClaimableBalanceCallBuilder} New {@link ClaimableBalanceCallBuilder} object configured by a current Horizon server configuration. + */ + claimableBalances(): ClaimableBalanceCallBuilder; + /** + * @returns {LedgerCallBuilder} New {@link LedgerCallBuilder} object configured by a current Horizon server configuration. + */ + ledgers(): LedgerCallBuilder; + /** + * @returns {TransactionCallBuilder} New {@link TransactionCallBuilder} object configured by a current Horizon server configuration. + */ + transactions(): TransactionCallBuilder; + /** + * People on the Stellar network can make offers to buy or sell assets. This endpoint represents all the offers on the DEX. + * + * You can query all offers for account using the function `.accountId`. + * + * @example + * server.offers() + * .forAccount(accountId).call() + * .then(function(offers) { + * console.log(offers); + * }); + * + * @returns {OfferCallBuilder} New {@link OfferCallBuilder} object + */ + offers(): OfferCallBuilder; + /** + * @param {Asset} selling Asset being sold + * @param {Asset} buying Asset being bought + * @returns {OrderbookCallBuilder} New {@link OrderbookCallBuilder} object configured by a current Horizon server configuration. + */ + orderbook(selling: Asset, buying: Asset): OrderbookCallBuilder; + /** + * Returns + * @returns {TradesCallBuilder} New {@link TradesCallBuilder} object configured by a current Horizon server configuration. + */ + trades(): TradesCallBuilder; + /** + * @returns {OperationCallBuilder} New {@link OperationCallBuilder} object configured by a current Horizon server configuration. + */ + operations(): OperationCallBuilder; + /** + * @returns {LiquidityPoolCallBuilder} New {@link LiquidityPoolCallBuilder} + * object configured to the current Horizon server settings. + */ + liquidityPools(): LiquidityPoolCallBuilder; + /** + * The Stellar Network allows payments to be made between assets through path + * payments. A strict receive path payment specifies a series of assets to + * route a payment through, from source asset (the asset debited from the + * payer) to destination asset (the asset credited to the payee). + * + * A strict receive path search is specified using: + * + * * The destination address. + * * The source address or source assets. + * * The asset and amount that the destination account should receive. + * + * As part of the search, horizon will load a list of assets available to the + * source address and will find any payment paths from those source assets to + * the desired destination asset. The search's amount parameter will be used + * to determine if there a given path can satisfy a payment of the desired + * amount. + * + * If a list of assets is passed as the source, horizon will find any payment + * paths from those source assets to the desired destination asset. + * + * @param {string|Asset[]} source The sender's account ID or a list of assets. Any returned path will use a source that the sender can hold. + * @param {Asset} destinationAsset The destination asset. + * @param {string} destinationAmount The amount, denominated in the destination asset, that any returned path should be able to satisfy. + * @returns {StrictReceivePathCallBuilder} New {@link StrictReceivePathCallBuilder} object configured with the current Horizon server configuration. + */ + strictReceivePaths(source: string | Asset[], destinationAsset: Asset, destinationAmount: string): PathCallBuilder; + /** + * The Stellar Network allows payments to be made between assets through path payments. A strict send path payment specifies a + * series of assets to route a payment through, from source asset (the asset debited from the payer) to destination + * asset (the asset credited to the payee). + * + * A strict send path search is specified using: + * + * The asset and amount that is being sent. + * The destination account or the destination assets. + * + * @param {Asset} sourceAsset The asset to be sent. + * @param {string} sourceAmount The amount, denominated in the source asset, that any returned path should be able to satisfy. + * @param {string|Asset[]} destination The destination account or the destination assets. + * @returns {StrictSendPathCallBuilder} New {@link StrictSendPathCallBuilder} object configured with the current Horizon server configuration. + */ + strictSendPaths(sourceAsset: Asset, sourceAmount: string, destination: string | Asset[]): PathCallBuilder; + /** + * @returns {PaymentCallBuilder} New {@link PaymentCallBuilder} instance configured with the current + * Horizon server configuration. + */ + payments(): PaymentCallBuilder; + /** + * @returns {EffectCallBuilder} New {@link EffectCallBuilder} instance configured with the current + * Horizon server configuration + */ + effects(): EffectCallBuilder; + /** + * @param {string} address The Stellar ID that you want Friendbot to send lumens to + * @returns {FriendbotBuilder} New {@link FriendbotBuilder} instance configured with the current + * Horizon server configuration + * @private + */ + friendbot(address: string): FriendbotBuilder; + /** + * Get a new {@link AssetsCallBuilder} instance configured with the current + * Horizon server configuration. + * @returns {AssetsCallBuilder} New AssetsCallBuilder instance + */ + assets(): AssetsCallBuilder; + /** + * Fetches an account's most current state in the ledger, then creates and + * returns an {@link AccountResponse} object. + * + * @param {string} accountId - The account to load. + * + * @returns {Promise} Returns a promise to the {@link AccountResponse} object + * with populated sequence number. + */ + loadAccount(accountId: string): Promise; + /** + * + * @param {Asset} base base asset + * @param {Asset} counter counter asset + * @param {number} start_time lower time boundary represented as millis since epoch + * @param {number} end_time upper time boundary represented as millis since epoch + * @param {number} resolution segment duration as millis since epoch. *Supported values are 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). + * @param {number} offset segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. + * Returns new {@link TradeAggregationCallBuilder} object configured with the current Horizon server configuration. + * @returns {TradeAggregationCallBuilder} New TradeAggregationCallBuilder instance + */ + tradeAggregation(base: Asset, counter: Asset, start_time: number, end_time: number, resolution: number, offset: number): TradeAggregationCallBuilder; + /** + * Check if any of the destination accounts requires a memo. + * + * This function implements a memo required check as defined in + * [SEP-29](https://stellar.org/protocol/sep-29). It will load each account + * which is the destination and check if it has the data field + * `config.memo_required` set to `"MQ=="`. + * + * Each account is checked sequentially instead of loading multiple accounts + * at the same time from Horizon. + * + * @see {@link https://stellar.org/protocol/sep-29|SEP-29: Account Memo Requirements} + * @param {Transaction} transaction - The transaction to check. + * @returns {Promise} - If any of the destination account + * requires a memo, the promise will throw {@link AccountRequiresMemoError}. + * @throws {AccountRequiresMemoError} + */ + checkMemoRequired(transaction: Transaction | FeeBumpTransaction): Promise; +} +/** + * Options for configuring connections to Horizon servers. + * @typedef {object} Options + * @memberof module:Horizon.Server + * @property {boolean} [allowHttp] Allow connecting to http servers, default: `false`. This must be set to false in production deployments! You can also use {@link Config} class to set this globally. + * @property {string} [appName] Allow set custom header `X-App-Name`, default: `undefined`. + * @property {string} [appVersion] Allow set custom header `X-App-Version`, default: `undefined`. + * @property {string} [authToken] Allow set custom header `X-Auth-Token`, default: `undefined`. + */ +export declare namespace HorizonServer { + interface Options { + allowHttp?: boolean; + appName?: string; + appVersion?: string; + authToken?: string; + headers?: Record; + } + interface Timebounds { + minTime: number; + maxTime: number; + } + interface SubmitTransactionOptions { + skipMemoRequiredCheck?: boolean; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/server.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/server.js new file mode 100644 index 000000000..111c8b341 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/server.js @@ -0,0 +1,571 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SUBMIT_TRANSACTION_TIMEOUT = exports.HorizonServer = void 0; +var _bignumber = _interopRequireDefault(require("bignumber.js")); +var _stellarBase = require("@stellar/stellar-base"); +var _urijs = _interopRequireDefault(require("urijs")); +var _call_builder = require("./call_builder"); +var _config = require("../config"); +var _errors = require("../errors"); +var _account_call_builder = require("./account_call_builder"); +var _account_response = require("./account_response"); +var _assets_call_builder = require("./assets_call_builder"); +var _claimable_balances_call_builder = require("./claimable_balances_call_builder"); +var _effect_call_builder = require("./effect_call_builder"); +var _friendbot_builder = require("./friendbot_builder"); +var _ledger_call_builder = require("./ledger_call_builder"); +var _liquidity_pool_call_builder = require("./liquidity_pool_call_builder"); +var _offer_call_builder = require("./offer_call_builder"); +var _operation_call_builder = require("./operation_call_builder"); +var _orderbook_call_builder = require("./orderbook_call_builder"); +var _payment_call_builder = require("./payment_call_builder"); +var _strict_receive_path_call_builder = require("./strict_receive_path_call_builder"); +var _strict_send_path_call_builder = require("./strict_send_path_call_builder"); +var _trade_aggregation_call_builder = require("./trade_aggregation_call_builder"); +var _trades_call_builder = require("./trades_call_builder"); +var _transaction_call_builder = require("./transaction_call_builder"); +var _horizon_axios_client = _interopRequireWildcard(require("./horizon_axios_client")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var SUBMIT_TRANSACTION_TIMEOUT = exports.SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000; +var STROOPS_IN_LUMEN = 10000000; +var ACCOUNT_REQUIRES_MEMO = "MQ=="; +function getAmountInLumens(amt) { + return new _bignumber.default(amt).div(STROOPS_IN_LUMEN).toString(); +} +var HorizonServer = exports.HorizonServer = function () { + function HorizonServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, HorizonServer); + this.serverURL = (0, _urijs.default)(serverURL); + var allowHttp = typeof opts.allowHttp === "undefined" ? _config.Config.isAllowHttp() : opts.allowHttp; + var customHeaders = {}; + if (opts.appName) { + customHeaders["X-App-Name"] = opts.appName; + } + if (opts.appVersion) { + customHeaders["X-App-Version"] = opts.appVersion; + } + if (opts.authToken) { + customHeaders["X-Auth-Token"] = opts.authToken; + } + if (opts.headers) { + Object.assign(customHeaders, opts.headers); + } + if (Object.keys(customHeaders).length > 0) { + _horizon_axios_client.default.interceptors.request.use(function (config) { + config.headers = config.headers || {}; + config.headers = Object.assign(config.headers, customHeaders); + return config; + }); + } + if (this.serverURL.protocol() !== "https" && !allowHttp) { + throw new Error("Cannot connect to insecure horizon server"); + } + } + return _createClass(HorizonServer, [{ + key: "fetchTimebounds", + value: (function () { + var _fetchTimebounds = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(seconds) { + var _isRetry, + currentTime, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _isRetry = _args.length > 1 && _args[1] !== undefined ? _args[1] : false; + currentTime = (0, _horizon_axios_client.getCurrentServerTime)(this.serverURL.hostname()); + if (!currentTime) { + _context.next = 4; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: currentTime + seconds + }); + case 4: + if (!_isRetry) { + _context.next = 6; + break; + } + return _context.abrupt("return", { + minTime: 0, + maxTime: Math.floor(new Date().getTime() / 1000) + seconds + }); + case 6: + _context.next = 8; + return _horizon_axios_client.default.get((0, _urijs.default)(this.serverURL).toString()); + case 8: + return _context.abrupt("return", this.fetchTimebounds(seconds, true)); + case 9: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function fetchTimebounds(_x) { + return _fetchTimebounds.apply(this, arguments); + } + return fetchTimebounds; + }()) + }, { + key: "fetchBaseFee", + value: (function () { + var _fetchBaseFee = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + var response; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.feeStats(); + case 2: + response = _context2.sent; + return _context2.abrupt("return", parseInt(response.last_ledger_base_fee, 10) || 100); + case 4: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function fetchBaseFee() { + return _fetchBaseFee.apply(this, arguments); + } + return fetchBaseFee; + }()) + }, { + key: "feeStats", + value: (function () { + var _feeStats = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3() { + var cb; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + cb = new _call_builder.CallBuilder((0, _urijs.default)(this.serverURL)); + cb.filter.push(["fee_stats"]); + return _context3.abrupt("return", cb.call()); + case 3: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function feeStats() { + return _feeStats.apply(this, arguments); + } + return feeStats; + }()) + }, { + key: "root", + value: (function () { + var _root = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4() { + var cb; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + cb = new _call_builder.CallBuilder((0, _urijs.default)(this.serverURL)); + return _context4.abrupt("return", cb.call()); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function root() { + return _root.apply(this, arguments); + } + return root; + }()) + }, { + key: "submitTransaction", + value: (function () { + var _submitTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(transaction) { + var opts, + tx, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + opts = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context5.next = 4; + break; + } + _context5.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context5.abrupt("return", _horizon_axios_client.default.post((0, _urijs.default)(this.serverURL).segment("transactions").toString(), "tx=".concat(tx), { + timeout: SUBMIT_TRANSACTION_TIMEOUT + }).then(function (response) { + if (!response.data.result_xdr) { + return response.data; + } + var responseXDR = _stellarBase.xdr.TransactionResult.fromXDR(response.data.result_xdr, "base64"); + var results = responseXDR.result().value(); + var offerResults; + var hasManageOffer; + if (results.length) { + offerResults = results.map(function (result, i) { + if (result.value().switch().name !== "manageBuyOffer" && result.value().switch().name !== "manageSellOffer") { + return null; + } + hasManageOffer = true; + var amountBought = new _bignumber.default(0); + var amountSold = new _bignumber.default(0); + var offerSuccess = result.value().value().success(); + var offersClaimed = offerSuccess.offersClaimed().map(function (offerClaimedAtom) { + var offerClaimed = offerClaimedAtom.value(); + var sellerId = ""; + switch (offerClaimedAtom.switch()) { + case _stellarBase.xdr.ClaimAtomType.claimAtomTypeV0(): + sellerId = _stellarBase.StrKey.encodeEd25519PublicKey(offerClaimed.sellerEd25519()); + break; + case _stellarBase.xdr.ClaimAtomType.claimAtomTypeOrderBook(): + sellerId = _stellarBase.StrKey.encodeEd25519PublicKey(offerClaimed.sellerId().ed25519()); + break; + default: + throw new Error("Invalid offer result type: ".concat(offerClaimedAtom.switch())); + } + var claimedOfferAmountBought = new _bignumber.default(offerClaimed.amountBought().toString()); + var claimedOfferAmountSold = new _bignumber.default(offerClaimed.amountSold().toString()); + amountBought = amountBought.plus(claimedOfferAmountSold); + amountSold = amountSold.plus(claimedOfferAmountBought); + var sold = _stellarBase.Asset.fromOperation(offerClaimed.assetSold()); + var bought = _stellarBase.Asset.fromOperation(offerClaimed.assetBought()); + var assetSold = { + type: sold.getAssetType(), + assetCode: sold.getCode(), + issuer: sold.getIssuer() + }; + var assetBought = { + type: bought.getAssetType(), + assetCode: bought.getCode(), + issuer: bought.getIssuer() + }; + return { + sellerId: sellerId, + offerId: offerClaimed.offerId().toString(), + assetSold: assetSold, + amountSold: getAmountInLumens(claimedOfferAmountSold), + assetBought: assetBought, + amountBought: getAmountInLumens(claimedOfferAmountBought) + }; + }); + var effect = offerSuccess.offer().switch().name; + var currentOffer; + if (typeof offerSuccess.offer().value === "function" && offerSuccess.offer().value()) { + var offerXDR = offerSuccess.offer().value(); + currentOffer = { + offerId: offerXDR.offerId().toString(), + selling: {}, + buying: {}, + amount: getAmountInLumens(offerXDR.amount().toString()), + price: { + n: offerXDR.price().n(), + d: offerXDR.price().d() + } + }; + var selling = _stellarBase.Asset.fromOperation(offerXDR.selling()); + currentOffer.selling = { + type: selling.getAssetType(), + assetCode: selling.getCode(), + issuer: selling.getIssuer() + }; + var buying = _stellarBase.Asset.fromOperation(offerXDR.buying()); + currentOffer.buying = { + type: buying.getAssetType(), + assetCode: buying.getCode(), + issuer: buying.getIssuer() + }; + } + return { + offersClaimed: offersClaimed, + effect: effect, + operationIndex: i, + currentOffer: currentOffer, + amountBought: getAmountInLumens(amountBought), + amountSold: getAmountInLumens(amountSold), + isFullyOpen: !offersClaimed.length && effect !== "manageOfferDeleted", + wasPartiallyFilled: !!offersClaimed.length && effect !== "manageOfferDeleted", + wasImmediatelyFilled: !!offersClaimed.length && effect === "manageOfferDeleted", + wasImmediatelyDeleted: !offersClaimed.length && effect === "manageOfferDeleted" + }; + }).filter(function (result) { + return !!result; + }); + } + return _objectSpread(_objectSpread({}, response.data), {}, { + offerResults: hasManageOffer ? offerResults : undefined + }); + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new _errors.BadResponseError("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function submitTransaction(_x2) { + return _submitTransaction.apply(this, arguments); + } + return submitTransaction; + }()) + }, { + key: "submitAsyncTransaction", + value: (function () { + var _submitAsyncTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6(transaction) { + var opts, + tx, + _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + opts = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : { + skipMemoRequiredCheck: false + }; + if (opts.skipMemoRequiredCheck) { + _context6.next = 4; + break; + } + _context6.next = 4; + return this.checkMemoRequired(transaction); + case 4: + tx = encodeURIComponent(transaction.toEnvelope().toXDR().toString("base64")); + return _context6.abrupt("return", _horizon_axios_client.default.post((0, _urijs.default)(this.serverURL).segment("transactions_async").toString(), "tx=".concat(tx)).then(function (response) { + return response.data; + }).catch(function (response) { + if (response instanceof Error) { + return Promise.reject(response); + } + return Promise.reject(new _errors.BadResponseError("Transaction submission failed. Server responded: ".concat(response.status, " ").concat(response.statusText), response.data)); + })); + case 6: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function submitAsyncTransaction(_x3) { + return _submitAsyncTransaction.apply(this, arguments); + } + return submitAsyncTransaction; + }()) + }, { + key: "accounts", + value: function accounts() { + return new _account_call_builder.AccountCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "claimableBalances", + value: function claimableBalances() { + return new _claimable_balances_call_builder.ClaimableBalanceCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "ledgers", + value: function ledgers() { + return new _ledger_call_builder.LedgerCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "transactions", + value: function transactions() { + return new _transaction_call_builder.TransactionCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "offers", + value: function offers() { + return new _offer_call_builder.OfferCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "orderbook", + value: function orderbook(selling, buying) { + return new _orderbook_call_builder.OrderbookCallBuilder((0, _urijs.default)(this.serverURL), selling, buying); + } + }, { + key: "trades", + value: function trades() { + return new _trades_call_builder.TradesCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "operations", + value: function operations() { + return new _operation_call_builder.OperationCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "liquidityPools", + value: function liquidityPools() { + return new _liquidity_pool_call_builder.LiquidityPoolCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "strictReceivePaths", + value: function strictReceivePaths(source, destinationAsset, destinationAmount) { + return new _strict_receive_path_call_builder.StrictReceivePathCallBuilder((0, _urijs.default)(this.serverURL), source, destinationAsset, destinationAmount); + } + }, { + key: "strictSendPaths", + value: function strictSendPaths(sourceAsset, sourceAmount, destination) { + return new _strict_send_path_call_builder.StrictSendPathCallBuilder((0, _urijs.default)(this.serverURL), sourceAsset, sourceAmount, destination); + } + }, { + key: "payments", + value: function payments() { + return new _payment_call_builder.PaymentCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "effects", + value: function effects() { + return new _effect_call_builder.EffectCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "friendbot", + value: function friendbot(address) { + return new _friendbot_builder.FriendbotBuilder((0, _urijs.default)(this.serverURL), address); + } + }, { + key: "assets", + value: function assets() { + return new _assets_call_builder.AssetsCallBuilder((0, _urijs.default)(this.serverURL)); + } + }, { + key: "loadAccount", + value: (function () { + var _loadAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee7(accountId) { + var res; + return _regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.accounts().accountId(accountId).call(); + case 2: + res = _context7.sent; + return _context7.abrupt("return", new _account_response.AccountResponse(res)); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function loadAccount(_x4) { + return _loadAccount.apply(this, arguments); + } + return loadAccount; + }()) + }, { + key: "tradeAggregation", + value: function tradeAggregation(base, counter, start_time, end_time, resolution, offset) { + return new _trade_aggregation_call_builder.TradeAggregationCallBuilder((0, _urijs.default)(this.serverURL), base, counter, start_time, end_time, resolution, offset); + } + }, { + key: "checkMemoRequired", + value: (function () { + var _checkMemoRequired = _asyncToGenerator(_regeneratorRuntime().mark(function _callee8(transaction) { + var destinations, i, operation, destination, account; + return _regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + if (transaction instanceof _stellarBase.FeeBumpTransaction) { + transaction = transaction.innerTransaction; + } + if (!(transaction.memo.type !== "none")) { + _context8.next = 3; + break; + } + return _context8.abrupt("return"); + case 3: + destinations = new Set(); + i = 0; + case 5: + if (!(i < transaction.operations.length)) { + _context8.next = 36; + break; + } + operation = transaction.operations[i]; + _context8.t0 = operation.type; + _context8.next = _context8.t0 === "payment" ? 10 : _context8.t0 === "pathPaymentStrictReceive" ? 10 : _context8.t0 === "pathPaymentStrictSend" ? 10 : _context8.t0 === "accountMerge" ? 10 : 11; + break; + case 10: + return _context8.abrupt("break", 12); + case 11: + return _context8.abrupt("continue", 33); + case 12: + destination = operation.destination; + if (!destinations.has(destination)) { + _context8.next = 15; + break; + } + return _context8.abrupt("continue", 33); + case 15: + destinations.add(destination); + if (!destination.startsWith("M")) { + _context8.next = 18; + break; + } + return _context8.abrupt("continue", 33); + case 18: + _context8.prev = 18; + _context8.next = 21; + return this.loadAccount(destination); + case 21: + account = _context8.sent; + if (!(account.data_attr["config.memo_required"] === ACCOUNT_REQUIRES_MEMO)) { + _context8.next = 24; + break; + } + throw new _errors.AccountRequiresMemoError("account requires memo", destination, i); + case 24: + _context8.next = 33; + break; + case 26: + _context8.prev = 26; + _context8.t1 = _context8["catch"](18); + if (!(_context8.t1 instanceof _errors.AccountRequiresMemoError)) { + _context8.next = 30; + break; + } + throw _context8.t1; + case 30: + if (_context8.t1 instanceof _errors.NotFoundError) { + _context8.next = 32; + break; + } + throw _context8.t1; + case 32: + return _context8.abrupt("continue", 33); + case 33: + i += 1; + _context8.next = 5; + break; + case 36: + case "end": + return _context8.stop(); + } + }, _callee8, this, [[18, 26]]); + })); + function checkMemoRequired(_x5) { + return _checkMemoRequired.apply(this, arguments); + } + return checkMemoRequired; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/server_api.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/server_api.d.ts new file mode 100644 index 000000000..77a8367ba --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/server_api.d.ts @@ -0,0 +1,264 @@ +import { Asset } from "@stellar/stellar-base"; +import { HorizonApi } from "./horizon_api"; +import { AccountRecordSigners as AccountRecordSignersType } from "./types/account"; +import { AssetRecord as AssetRecordType } from "./types/assets"; +import * as Effects from "./types/effects"; +import { OfferRecord as OfferRecordType } from "./types/offer"; +import { Trade } from "./types/trade"; +export declare namespace ServerApi { + export type OfferRecord = OfferRecordType; + export type AccountRecordSigners = AccountRecordSignersType; + export type AssetRecord = AssetRecordType; + export interface CollectionPage { + records: T[]; + next: () => Promise>; + prev: () => Promise>; + } + export interface CallFunctionTemplateOptions { + cursor?: string | number; + limit?: number; + order?: "asc" | "desc"; + } + export type CallFunction = () => Promise; + export type CallCollectionFunction = (options?: CallFunctionTemplateOptions) => Promise>; + type BaseEffectRecordFromTypes = Effects.AccountCreated | Effects.AccountCredited | Effects.AccountDebited | Effects.AccountThresholdsUpdated | Effects.AccountHomeDomainUpdated | Effects.AccountFlagsUpdated | Effects.DataCreated | Effects.DataRemoved | Effects.DataUpdated | Effects.SequenceBumped | Effects.SignerCreated | Effects.SignerRemoved | Effects.SignerUpdated | Effects.TrustlineCreated | Effects.TrustlineRemoved | Effects.TrustlineUpdated | Effects.TrustlineAuthorized | Effects.TrustlineDeauthorized | Effects.TrustlineAuthorizedToMaintainLiabilities | Effects.ClaimableBalanceCreated | Effects.ClaimableBalanceClaimed | Effects.ClaimableBalanceClaimantCreated | Effects.AccountSponsorshipCreated | Effects.AccountSponsorshipRemoved | Effects.AccountSponsorshipUpdated | Effects.TrustlineSponsorshipCreated | Effects.TrustlineSponsorshipUpdated | Effects.TrustlineSponsorshipRemoved | Effects.DateSponsorshipCreated | Effects.DateSponsorshipUpdated | Effects.DateSponsorshipRemoved | Effects.ClaimableBalanceSponsorshipCreated | Effects.ClaimableBalanceSponsorshipRemoved | Effects.ClaimableBalanceSponsorshipUpdated | Effects.SignerSponsorshipCreated | Effects.SignerSponsorshipUpdated | Effects.SignerSponsorshipRemoved | Effects.LiquidityPoolDeposited | Effects.LiquidityPoolWithdrew | Effects.LiquidityPoolCreated | Effects.LiquidityPoolRemoved | Effects.LiquidityPoolRevoked | Effects.LiquidityPoolTrade | Effects.ContractCredited | Effects.ContractDebited | Trade; + export type EffectRecord = BaseEffectRecordFromTypes & EffectRecordMethods; + export const EffectType: typeof Effects.EffectType; + export interface ClaimableBalanceRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + asset: string; + amount: string; + sponsor?: string; + last_modified_ledger: number; + claimants: HorizonApi.Claimant[]; + } + export interface AccountRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + account_id: string; + sequence: string; + sequence_ledger?: number; + sequence_time?: string; + subentry_count: number; + home_domain?: string; + inflation_destination?: string; + last_modified_ledger: number; + last_modified_time: string; + thresholds: HorizonApi.AccountThresholds; + flags: HorizonApi.Flags; + balances: HorizonApi.BalanceLine[]; + signers: AccountRecordSigners[]; + data: (options: { + value: string; + }) => Promise<{ + value: string; + }>; + data_attr: { + [key: string]: string; + }; + sponsor?: string; + num_sponsoring: number; + num_sponsored: number; + effects: CallCollectionFunction; + offers: CallCollectionFunction; + operations: CallCollectionFunction; + payments: CallCollectionFunction; + trades: CallCollectionFunction; + } + export interface LiquidityPoolRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + fee_bp: number; + type: HorizonApi.LiquidityPoolType; + total_trustlines: string; + total_shares: string; + reserves: HorizonApi.Reserve[]; + } + export enum TradeType { + all = "all", + liquidityPools = "liquidity_pool", + orderbook = "orderbook" + } + interface EffectRecordMethods { + operation?: CallFunction; + precedes?: CallFunction; + succeeds?: CallFunction; + } + export interface LedgerRecord extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + hash: string; + prev_hash: string; + sequence: number; + successful_transaction_count: number; + failed_transaction_count: number; + operation_count: number; + tx_set_operation_count: number | null; + closed_at: string; + total_coins: string; + fee_pool: string; + max_tx_set_size: number; + protocol_version: number; + header_xdr: string; + base_fee_in_stroops: number; + base_reserve_in_stroops: number; + effects: CallCollectionFunction; + operations: CallCollectionFunction; + self: CallFunction; + transactions: CallCollectionFunction; + } + import OperationResponseType = HorizonApi.OperationResponseType; + import OperationResponseTypeI = HorizonApi.OperationResponseTypeI; + export interface BaseOperationRecord extends HorizonApi.BaseOperationResponse { + self: CallFunction; + succeeds: CallFunction; + precedes: CallFunction; + effects: CallCollectionFunction; + transaction: CallFunction; + } + export interface CreateAccountOperationRecord extends BaseOperationRecord, HorizonApi.CreateAccountOperationResponse { + } + export interface PaymentOperationRecord extends BaseOperationRecord, HorizonApi.PaymentOperationResponse { + sender: CallFunction; + receiver: CallFunction; + } + export interface PathPaymentOperationRecord extends BaseOperationRecord, HorizonApi.PathPaymentOperationResponse { + } + export interface PathPaymentStrictSendOperationRecord extends BaseOperationRecord, HorizonApi.PathPaymentStrictSendOperationResponse { + } + export interface ManageOfferOperationRecord extends BaseOperationRecord, HorizonApi.ManageOfferOperationResponse { + } + export interface PassiveOfferOperationRecord extends BaseOperationRecord, HorizonApi.PassiveOfferOperationResponse { + } + export interface SetOptionsOperationRecord extends BaseOperationRecord, HorizonApi.SetOptionsOperationResponse { + } + export interface ChangeTrustOperationRecord extends BaseOperationRecord, HorizonApi.ChangeTrustOperationResponse { + } + export interface AllowTrustOperationRecord extends BaseOperationRecord, HorizonApi.AllowTrustOperationResponse { + } + export interface AccountMergeOperationRecord extends BaseOperationRecord, HorizonApi.AccountMergeOperationResponse { + } + export interface InflationOperationRecord extends BaseOperationRecord, HorizonApi.InflationOperationResponse { + } + export interface ManageDataOperationRecord extends BaseOperationRecord, HorizonApi.ManageDataOperationResponse { + } + export interface BumpSequenceOperationRecord extends BaseOperationRecord, HorizonApi.BumpSequenceOperationResponse { + } + export interface CreateClaimableBalanceOperationRecord extends BaseOperationRecord, HorizonApi.CreateClaimableBalanceOperationResponse { + } + export interface ClaimClaimableBalanceOperationRecord extends BaseOperationRecord, HorizonApi.ClaimClaimableBalanceOperationResponse { + } + export interface BeginSponsoringFutureReservesOperationRecord extends BaseOperationRecord, HorizonApi.BeginSponsoringFutureReservesOperationResponse { + } + export interface EndSponsoringFutureReservesOperationRecord extends BaseOperationRecord, HorizonApi.EndSponsoringFutureReservesOperationResponse { + } + export interface RevokeSponsorshipOperationRecord extends BaseOperationRecord, HorizonApi.RevokeSponsorshipOperationResponse { + } + export interface ClawbackOperationRecord extends BaseOperationRecord, HorizonApi.ClawbackOperationResponse { + } + export interface ClawbackClaimableBalanceOperationRecord extends BaseOperationRecord, HorizonApi.ClawbackClaimableBalanceOperationResponse { + } + export interface SetTrustLineFlagsOperationRecord extends BaseOperationRecord, HorizonApi.SetTrustLineFlagsOperationResponse { + } + export interface DepositLiquidityOperationRecord extends BaseOperationRecord, HorizonApi.DepositLiquidityOperationResponse { + } + export interface WithdrawLiquidityOperationRecord extends BaseOperationRecord, HorizonApi.WithdrawLiquidityOperationResponse { + } + export interface InvokeHostFunctionOperationRecord extends BaseOperationRecord, HorizonApi.InvokeHostFunctionOperationResponse { + } + export interface BumpFootprintExpirationOperationRecord extends BaseOperationRecord, HorizonApi.BumpFootprintExpirationOperationResponse { + } + export interface RestoreFootprintOperationRecord extends BaseOperationRecord, HorizonApi.RestoreFootprintOperationResponse { + } + export type OperationRecord = CreateAccountOperationRecord | PaymentOperationRecord | PathPaymentOperationRecord | ManageOfferOperationRecord | PassiveOfferOperationRecord | SetOptionsOperationRecord | ChangeTrustOperationRecord | AllowTrustOperationRecord | AccountMergeOperationRecord | InflationOperationRecord | ManageDataOperationRecord | BumpSequenceOperationRecord | PathPaymentStrictSendOperationRecord | CreateClaimableBalanceOperationRecord | ClaimClaimableBalanceOperationRecord | BeginSponsoringFutureReservesOperationRecord | EndSponsoringFutureReservesOperationRecord | RevokeSponsorshipOperationRecord | ClawbackClaimableBalanceOperationRecord | ClawbackOperationRecord | SetTrustLineFlagsOperationRecord | DepositLiquidityOperationRecord | WithdrawLiquidityOperationRecord | InvokeHostFunctionOperationRecord | BumpFootprintExpirationOperationRecord | RestoreFootprintOperationRecord; + export namespace TradeRecord { + interface Base extends HorizonApi.BaseResponse { + id: string; + paging_token: string; + ledger_close_time: string; + trade_type: TradeType; + base_account?: string; + base_amount: string; + base_asset_type: string; + base_asset_code?: string; + base_asset_issuer?: string; + counter_account?: string; + counter_amount: string; + counter_asset_type: string; + counter_asset_code?: string; + counter_asset_issuer?: string; + base_is_seller: boolean; + price?: { + n: string; + d: string; + }; + operation: CallFunction; + } + export interface Orderbook extends Base { + trade_type: TradeType.orderbook; + base_offer_id: string; + base_account: string; + counter_offer_id: string; + counter_account: string; + base: CallFunction; + counter: CallFunction; + } + export interface LiquidityPool extends Base { + trade_type: TradeType.liquidityPools; + base_liquidity_pool_id?: string; + counter_liquidity_pool_id?: string; + liquidity_pool_fee_bp: number; + base: CallFunction; + counter: CallFunction; + } + export {}; + } + export type TradeRecord = TradeRecord.Orderbook | TradeRecord.LiquidityPool; + export interface TransactionRecord extends Omit { + ledger_attr: HorizonApi.TransactionResponse["ledger"]; + account: CallFunction; + effects: CallCollectionFunction; + ledger: CallFunction; + operations: CallCollectionFunction; + precedes: CallFunction; + self: CallFunction; + succeeds: CallFunction; + } + export interface OrderbookRecord extends HorizonApi.BaseResponse { + bids: Array<{ + price_r: { + d: number; + n: number; + }; + price: string; + amount: string; + }>; + asks: Array<{ + price_r: { + d: number; + n: number; + }; + price: string; + amount: string; + }>; + base: Asset; + counter: Asset; + } + export interface PaymentPathRecord extends HorizonApi.BaseResponse { + path: Array<{ + asset_code: string; + asset_issuer: string; + asset_type: string; + }>; + source_amount: string; + source_asset_type: string; + source_asset_code: string; + source_asset_issuer: string; + destination_amount: string; + destination_asset_type: string; + destination_asset_code: string; + destination_asset_issuer: string; + } + export {}; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/server_api.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/server_api.js new file mode 100644 index 000000000..df0eafd7f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/server_api.js @@ -0,0 +1,24 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ServerApi = void 0; +var _horizon_api = require("./horizon_api"); +var Effects = _interopRequireWildcard(require("./types/effects")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var ServerApi; +(function (_ServerApi) { + var EffectType = _ServerApi.EffectType = Effects.EffectType; + var TradeType = function (TradeType) { + TradeType["all"] = "all"; + TradeType["liquidityPools"] = "liquidity_pool"; + TradeType["orderbook"] = "orderbook"; + return TradeType; + }({}); + _ServerApi.TradeType = TradeType; + var OperationResponseType = _horizon_api.HorizonApi.OperationResponseType; + var OperationResponseTypeI = _horizon_api.HorizonApi.OperationResponseTypeI; +})(ServerApi || (exports.ServerApi = ServerApi = {})); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/strict_receive_path_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/strict_receive_path_call_builder.d.ts new file mode 100644 index 000000000..1e9a28025 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/strict_receive_path_call_builder.d.ts @@ -0,0 +1,38 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * The Stellar Network allows payments to be made across assets through path + * payments. A strict receive path payment specifies a series of assets to route + * a payment through, from source asset (the asset debited from the payer) to + * destination asset (the asset credited to the payee). + * + * A path search is specified using: + * + * * The source address or source assets. + * * The asset and amount that the destination account should receive + * + * As part of the search, horizon will load a list of assets available to the + * source address and will find any payment paths from those source assets to + * the desired destination asset. The search's amount parameter will be used to + * determine if there a given path can satisfy a payment of the desired amount. + * + * If a list of assets is passed as the source, horizon will find any payment + * paths from those source assets to the desired destination asset. + * + * Do not create this object directly, use {@link Horizon.Server#strictReceivePaths}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/paths|Find Payment Paths} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + * @param {string|Asset[]} source The sender's account ID or a list of Assets. Any returned path must use a source that the sender can hold. + * @param {Asset} destinationAsset The destination asset. + * @param {string} destinationAmount The amount, denominated in the destination asset, that any returned path should be able to satisfy. + */ +export declare class StrictReceivePathCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, source: string | Asset[], destinationAsset: Asset, destinationAmount: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/strict_receive_path_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/strict_receive_path_call_builder.js new file mode 100644 index 000000000..5e4a5a992 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/strict_receive_path_call_builder.js @@ -0,0 +1,50 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.StrictReceivePathCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var StrictReceivePathCallBuilder = exports.StrictReceivePathCallBuilder = function (_CallBuilder) { + function StrictReceivePathCallBuilder(serverUrl, source, destinationAsset, destinationAmount) { + var _this; + _classCallCheck(this, StrictReceivePathCallBuilder); + _this = _callSuper(this, StrictReceivePathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-receive"); + if (typeof source === "string") { + _this.url.setQuery("source_account", source); + } else { + var assets = source.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("source_assets", assets); + } + _this.url.setQuery("destination_amount", destinationAmount); + if (!destinationAsset.isNative()) { + _this.url.setQuery("destination_asset_type", destinationAsset.getAssetType()); + _this.url.setQuery("destination_asset_code", destinationAsset.getCode()); + _this.url.setQuery("destination_asset_issuer", destinationAsset.getIssuer()); + } else { + _this.url.setQuery("destination_asset_type", "native"); + } + return _this; + } + _inherits(StrictReceivePathCallBuilder, _CallBuilder); + return _createClass(StrictReceivePathCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/strict_send_path_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/strict_send_path_call_builder.d.ts new file mode 100644 index 000000000..85cd9a154 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/strict_send_path_call_builder.d.ts @@ -0,0 +1,38 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * The Stellar Network allows payments to be made across assets through path + * payments. A strict send path payment specifies a series of assets to route a + * payment through, from source asset (the asset debited from the payer) to + * destination asset (the asset credited to the payee). + * + * A strict send path search is specified using: + * + * The source asset + * The source amount + * The destination assets or destination account. + * + * As part of the search, horizon will load a list of assets available to the + * source address and will find any payment paths from those source assets to + * the desired destination asset. The search's source_amount parameter will be + * used to determine if there a given path can satisfy a payment of the desired + * amount. + * + * Do not create this object directly, use {@link Horizon.Server#strictSendPaths}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/aggregations/paths|Find Payment Paths} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + * @param {Asset} sourceAsset The asset to be sent. + * @param {string} sourceAmount The amount, denominated in the source asset, that any returned path should be able to satisfy. + * @param {string|Asset[]} destination The destination account or the destination assets. + * + */ +export declare class StrictSendPathCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, sourceAsset: Asset, sourceAmount: string, destination: string | Asset[]); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/strict_send_path_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/strict_send_path_call_builder.js new file mode 100644 index 000000000..f65a1d0a5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/strict_send_path_call_builder.js @@ -0,0 +1,50 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.StrictSendPathCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var StrictSendPathCallBuilder = exports.StrictSendPathCallBuilder = function (_CallBuilder) { + function StrictSendPathCallBuilder(serverUrl, sourceAsset, sourceAmount, destination) { + var _this; + _classCallCheck(this, StrictSendPathCallBuilder); + _this = _callSuper(this, StrictSendPathCallBuilder, [serverUrl]); + _this.url.segment("paths/strict-send"); + if (sourceAsset.isNative()) { + _this.url.setQuery("source_asset_type", "native"); + } else { + _this.url.setQuery("source_asset_type", sourceAsset.getAssetType()); + _this.url.setQuery("source_asset_code", sourceAsset.getCode()); + _this.url.setQuery("source_asset_issuer", sourceAsset.getIssuer()); + } + _this.url.setQuery("source_amount", sourceAmount); + if (typeof destination === "string") { + _this.url.setQuery("destination_account", destination); + } else { + var assets = destination.map(function (asset) { + if (asset.isNative()) { + return "native"; + } + return "".concat(asset.getCode(), ":").concat(asset.getIssuer()); + }).join(","); + _this.url.setQuery("destination_assets", assets); + } + return _this; + } + _inherits(StrictSendPathCallBuilder, _CallBuilder); + return _createClass(StrictSendPathCallBuilder); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/trade_aggregation_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/trade_aggregation_call_builder.d.ts new file mode 100644 index 000000000..fe8dc52d5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/trade_aggregation_call_builder.d.ts @@ -0,0 +1,49 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { HorizonApi } from "./horizon_api"; +import { ServerApi } from "./server_api"; +/** + * Trade Aggregations facilitate efficient gathering of historical trade data. + * + * Do not create this object directly, use {@link Horizon.Server#tradeAggregation}. + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl serverUrl Horizon server URL. + * @param {Asset} base base asset + * @param {Asset} counter counter asset + * @param {number} start_time lower time boundary represented as millis since epoch + * @param {number} end_time upper time boundary represented as millis since epoch + * @param {number} resolution segment duration as millis since epoch. *Supported values are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). + * @param {number} offset segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. + */ +export declare class TradeAggregationCallBuilder extends CallBuilder> { + constructor(serverUrl: URI, base: Asset, counter: Asset, start_time: number, end_time: number, resolution: number, offset: number); + /** + * @private + * @param {number} resolution Trade data resolution in milliseconds + * @returns {boolean} true if the resolution is allowed + */ + private isValidResolution; + /** + * @private + * @param {number} offset Time offset in milliseconds + * @param {number} resolution Trade data resolution in milliseconds + * @returns {boolean} true if the offset is valid + */ + private isValidOffset; +} +interface TradeAggregationRecord extends HorizonApi.BaseResponse { + timestamp: number | string; + trade_count: number | string; + base_volume: string; + counter_volume: string; + avg: string; + high: string; + low: string; + open: string; + close: string; +} +export {}; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/trade_aggregation_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/trade_aggregation_call_builder.js new file mode 100644 index 000000000..b6866d738 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/trade_aggregation_call_builder.js @@ -0,0 +1,76 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TradeAggregationCallBuilder = void 0; +var _call_builder = require("./call_builder"); +var _errors = require("../errors"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var allowedResolutions = [60000, 300000, 900000, 3600000, 86400000, 604800000]; +var TradeAggregationCallBuilder = exports.TradeAggregationCallBuilder = function (_CallBuilder) { + function TradeAggregationCallBuilder(serverUrl, base, counter, start_time, end_time, resolution, offset) { + var _this; + _classCallCheck(this, TradeAggregationCallBuilder); + _this = _callSuper(this, TradeAggregationCallBuilder, [serverUrl]); + _this.url.segment("trade_aggregations"); + if (!base.isNative()) { + _this.url.setQuery("base_asset_type", base.getAssetType()); + _this.url.setQuery("base_asset_code", base.getCode()); + _this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + _this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + _this.url.setQuery("counter_asset_type", counter.getAssetType()); + _this.url.setQuery("counter_asset_code", counter.getCode()); + _this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + _this.url.setQuery("counter_asset_type", "native"); + } + if (typeof start_time !== "number" || typeof end_time !== "number") { + throw new _errors.BadRequestError("Invalid time bounds", [start_time, end_time]); + } else { + _this.url.setQuery("start_time", start_time.toString()); + _this.url.setQuery("end_time", end_time.toString()); + } + if (!_this.isValidResolution(resolution)) { + throw new _errors.BadRequestError("Invalid resolution", resolution); + } else { + _this.url.setQuery("resolution", resolution.toString()); + } + if (!_this.isValidOffset(offset, resolution)) { + throw new _errors.BadRequestError("Invalid offset", offset); + } else { + _this.url.setQuery("offset", offset.toString()); + } + return _this; + } + _inherits(TradeAggregationCallBuilder, _CallBuilder); + return _createClass(TradeAggregationCallBuilder, [{ + key: "isValidResolution", + value: function isValidResolution(resolution) { + return allowedResolutions.some(function (allowed) { + return allowed === resolution; + }); + } + }, { + key: "isValidOffset", + value: function isValidOffset(offset, resolution) { + var hour = 3600000; + return !(offset > resolution || offset >= 24 * hour || offset % hour !== 0); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/trades_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/trades_call_builder.d.ts new file mode 100644 index 000000000..2a407642e --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/trades_call_builder.d.ts @@ -0,0 +1,52 @@ +import { Asset } from "@stellar/stellar-base"; +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link TradesCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#trades}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/trades|Trades} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl serverUrl Horizon server URL. + */ +export declare class TradesCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * Filter trades for a specific asset pair (orderbook) + * @param {Asset} base asset + * @param {Asset} counter asset + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forAssetPair(base: Asset, counter: Asset): this; + /** + * Filter trades for a specific offer + * @param {string} offerId ID of the offer + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forOffer(offerId: string): this; + /** + * Filter trades by a specific type. + * @param {ServerApi.TradeType} tradeType the trade type to filter by. + * @returns {TradesCallBuilder} current TradesCallBuilder instance. + */ + forType(tradeType: ServerApi.TradeType): this; + /** + * Filter trades for a specific account + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-trades-by-account-id|Trades for Account} + * @param {string} accountId For example: `GBYTR4MC5JAX4ALGUBJD7EIKZVM7CUGWKXIUJMRSMK573XH2O7VAK3SR` + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * Filter trades for a specific liquidity pool + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-related-trades|Trades for Liquidity Pool} + * @param {string} liquidityPoolId For example: `3b476aff8a406a6ec3b61d5c038009cef85f2ddfaf616822dc4fec92845149b4` + * @returns {TradesCallBuilder} current TradesCallBuilder instance + */ + forLiquidityPool(liquidityPoolId: string): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/trades_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/trades_call_builder.js new file mode 100644 index 000000000..5c6b23bec --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/trades_call_builder.js @@ -0,0 +1,72 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TradesCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var TradesCallBuilder = exports.TradesCallBuilder = function (_CallBuilder) { + function TradesCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, TradesCallBuilder); + _this = _callSuper(this, TradesCallBuilder, [serverUrl, "trades"]); + _this.url.segment("trades"); + return _this; + } + _inherits(TradesCallBuilder, _CallBuilder); + return _createClass(TradesCallBuilder, [{ + key: "forAssetPair", + value: function forAssetPair(base, counter) { + if (!base.isNative()) { + this.url.setQuery("base_asset_type", base.getAssetType()); + this.url.setQuery("base_asset_code", base.getCode()); + this.url.setQuery("base_asset_issuer", base.getIssuer()); + } else { + this.url.setQuery("base_asset_type", "native"); + } + if (!counter.isNative()) { + this.url.setQuery("counter_asset_type", counter.getAssetType()); + this.url.setQuery("counter_asset_code", counter.getCode()); + this.url.setQuery("counter_asset_issuer", counter.getIssuer()); + } else { + this.url.setQuery("counter_asset_type", "native"); + } + return this; + } + }, { + key: "forOffer", + value: function forOffer(offerId) { + this.url.setQuery("offer_id", offerId); + return this; + } + }, { + key: "forType", + value: function forType(tradeType) { + this.url.setQuery("trade_type", tradeType); + return this; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(liquidityPoolId) { + return this.forEndpoint("liquidity_pools", liquidityPoolId); + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/transaction_call_builder.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/transaction_call_builder.d.ts new file mode 100644 index 000000000..4c40ce94d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/transaction_call_builder.d.ts @@ -0,0 +1,60 @@ +import { CallBuilder } from "./call_builder"; +import { ServerApi } from "./server_api"; +/** + * Creates a new {@link TransactionCallBuilder} pointed to server defined by serverUrl. + * + * Do not create this object directly, use {@link Horizon.Server#transactions}. + * + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/list-all-transactions|All Transactions} + * + * @augments CallBuilder + * @private + * @class + * + * @param {string} serverUrl Horizon server URL. + */ +export declare class TransactionCallBuilder extends CallBuilder> { + constructor(serverUrl: URI); + /** + * The transaction details endpoint provides information on a single transaction. The transaction hash provided in the hash argument specifies which transaction to load. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-transaction|Transaction Details} + * @param {string} transactionId Transaction ID + * @returns {CallBuilder} a CallBuilder instance + */ + transaction(transactionId: string): CallBuilder; + /** + * This endpoint represents all transactions that affected a given account. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/get-transactions-by-account-id|Transactions for Account} + * @param {string} accountId For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` + * @returns {TransactionCallBuilder} current TransactionCallBuilder instance + */ + forAccount(accountId: string): this; + /** + * This endpoint represents all transactions that reference a given claimable_balance. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/cb-retrieve-related-transactions|Transactions for Claimable Balance} + * @param {string} claimableBalanceId Claimable Balance ID + * @returns {TransactionCallBuilder} this TransactionCallBuilder instance + */ + forClaimableBalance(claimableBalanceId: string): this; + /** + * This endpoint represents all transactions in a given ledger. + * @see {@link https://developers.stellar.org/docs/data/horizon/api-reference/resources/retrieve-a-ledgers-transactions|Transactions for Ledger} + * @param {number|string} sequence Ledger sequence + * @returns {TransactionCallBuilder} current TransactionCallBuilder instance + */ + forLedger(sequence: number | string): this; + /** + * This endpoint represents all transactions involving a particular liquidity pool. + * + * @param {string} poolId liquidity pool ID + * @returns {TransactionCallBuilder} this TransactionCallBuilder instance + */ + forLiquidityPool(poolId: string): this; + /** + * Adds a parameter defining whether to include failed transactions. By default only successful transactions are + * returned. + * @param {boolean} value Set to `true` to include failed transactions. + * @returns {TransactionCallBuilder} current TransactionCallBuilder instance + */ + includeFailed(value: boolean): this; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/transaction_call_builder.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/transaction_call_builder.js new file mode 100644 index 000000000..746c7bfbf --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/transaction_call_builder.js @@ -0,0 +1,64 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TransactionCallBuilder = void 0; +var _call_builder = require("./call_builder"); +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +var TransactionCallBuilder = exports.TransactionCallBuilder = function (_CallBuilder) { + function TransactionCallBuilder(serverUrl) { + var _this; + _classCallCheck(this, TransactionCallBuilder); + _this = _callSuper(this, TransactionCallBuilder, [serverUrl, "transactions"]); + _this.url.segment("transactions"); + return _this; + } + _inherits(TransactionCallBuilder, _CallBuilder); + return _createClass(TransactionCallBuilder, [{ + key: "transaction", + value: function transaction(transactionId) { + var builder = new _call_builder.CallBuilder(this.url.clone()); + builder.filter.push([transactionId]); + return builder; + } + }, { + key: "forAccount", + value: function forAccount(accountId) { + return this.forEndpoint("accounts", accountId); + } + }, { + key: "forClaimableBalance", + value: function forClaimableBalance(claimableBalanceId) { + return this.forEndpoint("claimable_balances", claimableBalanceId); + } + }, { + key: "forLedger", + value: function forLedger(sequence) { + return this.forEndpoint("ledgers", sequence.toString()); + } + }, { + key: "forLiquidityPool", + value: function forLiquidityPool(poolId) { + return this.forEndpoint("liquidity_pools", poolId); + } + }, { + key: "includeFailed", + value: function includeFailed(value) { + this.url.setQuery("include_failed", value.toString()); + return this; + } + }]); +}(_call_builder.CallBuilder); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/account.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/account.d.ts new file mode 100644 index 000000000..3edc78aad --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/account.d.ts @@ -0,0 +1,5 @@ +export interface AccountRecordSigners { + key: string; + weight: number; + type: string; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/account.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/account.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/account.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/assets.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/assets.d.ts new file mode 100644 index 000000000..c85e71a32 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/assets.d.ts @@ -0,0 +1,17 @@ +import { AssetType } from "@stellar/stellar-base"; +import { HorizonApi } from "../horizon_api"; +export interface AssetRecord extends HorizonApi.BaseResponse { + asset_type: AssetType.credit4 | AssetType.credit12; + asset_code: string; + asset_issuer: string; + paging_token: string; + accounts: HorizonApi.AssetAccounts; + balances: HorizonApi.AssetBalances; + num_claimable_balances: number; + num_liquidity_pools: number; + num_contracts: number; + claimable_balances_amount: string; + liquidity_pools_amount: string; + contracts_amount: string; + flags: HorizonApi.Flags; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/assets.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/assets.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/assets.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/effects.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/effects.d.ts new file mode 100644 index 000000000..a3a628dce --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/effects.d.ts @@ -0,0 +1,285 @@ +import { HorizonApi } from "../horizon_api"; +import { OfferAsset } from "./offer"; +export declare enum EffectType { + account_created = 0, + account_removed = 1, + account_credited = 2, + account_debited = 3, + account_thresholds_updated = 4, + account_home_domain_updated = 5, + account_flags_updated = 6, + account_inflation_destination_updated = 7, + signer_created = 10, + signer_removed = 11, + signer_updated = 12, + trustline_created = 20, + trustline_removed = 21, + trustline_updated = 22, + trustline_authorized = 23, + trustline_deauthorized = 24, + trustline_authorized_to_maintain_liabilities = 25,// deprecated, use trustline_flags_updated + trustline_flags_updated = 26, + offer_created = 30, + offer_removed = 31, + offer_updated = 32, + trade = 33, + data_created = 40, + data_removed = 41, + data_updated = 42, + sequence_bumped = 43, + claimable_balance_created = 50, + claimable_balance_claimant_created = 51, + claimable_balance_claimed = 52, + account_sponsorship_created = 60, + account_sponsorship_updated = 61, + account_sponsorship_removed = 62, + trustline_sponsorship_created = 63, + trustline_sponsorship_updated = 64, + trustline_sponsorship_removed = 65, + data_sponsorship_created = 66, + data_sponsorship_updated = 67, + data_sponsorship_removed = 68, + claimable_balance_sponsorship_created = 69, + claimable_balance_sponsorship_updated = 70, + claimable_balance_sponsorship_removed = 71, + signer_sponsorship_created = 72, + signer_sponsorship_updated = 73, + signer_sponsorship_removed = 74, + claimable_balance_clawed_back = 80, + liquidity_pool_deposited = 90, + liquidity_pool_withdrew = 91, + liquidity_pool_trade = 92, + liquidity_pool_created = 93, + liquidity_pool_removed = 94, + liquidity_pool_revoked = 95, + contract_credited = 96, + contract_debited = 97 +} +export interface BaseEffectRecord extends HorizonApi.BaseResponse { + id: string; + account: string; + paging_token: string; + type_i: EffectType; + type: T; + created_at: string; +} +export interface AccountCreated extends BaseEffectRecord<'account_created'> { + type_i: EffectType.account_created; + starting_balance: string; +} +export interface AccountCredited extends BaseEffectRecord<'account_credited'>, OfferAsset { + type_i: EffectType.account_credited; + amount: string; +} +export interface AccountDebited extends BaseEffectRecord<'account_debited'>, OfferAsset { + type_i: EffectType.account_debited; + amount: string; +} +export interface AccountThresholdsUpdated extends BaseEffectRecord<'account_thresholds_updated'> { + type_i: EffectType.account_thresholds_updated; + low_threshold: number; + med_threshold: number; + high_threshold: number; +} +export interface AccountHomeDomainUpdated extends BaseEffectRecord<'account_home_domain_updated'> { + type_i: EffectType.account_home_domain_updated; + home_domain: string; +} +export interface AccountFlagsUpdated extends BaseEffectRecord<'account_flags_updated'> { + type_i: EffectType.account_flags_updated; + auth_required_flag: boolean; + auth_revokable_flag: boolean; +} +interface DataEvents extends BaseEffectRecord { + name: boolean; + value: boolean; +} +export interface DataCreated extends DataEvents<'data_created'> { + type_i: EffectType.data_created; +} +export interface DataUpdated extends DataEvents<'data_updated'> { + type_i: EffectType.data_updated; +} +export interface DataRemoved extends DataEvents<'data_removed'> { + type_i: EffectType.data_removed; +} +export interface SequenceBumped extends BaseEffectRecord<'sequence_bumped'> { + type_i: EffectType.sequence_bumped; + new_seq: number | string; +} +interface SignerEvents extends BaseEffectRecord { + weight: number; + key: string; + public_key: string; +} +export interface SignerCreated extends SignerEvents<'signer_created'> { + type_i: EffectType.signer_created; +} +export interface SignerRemoved extends SignerEvents<'signer_removed'> { + type_i: EffectType.signer_removed; +} +export interface SignerUpdated extends SignerEvents<'signer_updated'> { + type_i: EffectType.signer_updated; +} +interface TrustlineEvents extends BaseEffectRecord, OfferAsset { + limit: string; + liquidity_pool_id?: string; +} +export interface TrustlineCreated extends TrustlineEvents<'trustline_created'> { + type_i: EffectType.trustline_created; +} +export interface TrustlineRemoved extends TrustlineEvents<'trustline_removed'> { + type_i: EffectType.trustline_removed; +} +export interface TrustlineUpdated extends TrustlineEvents<'trustline_updated'> { + type_i: EffectType.trustline_updated; +} +export interface TrustlineAuthorized extends BaseEffectRecord<'trustline_authorized'> { + type_i: EffectType.trustline_authorized; + asset_type: OfferAsset["asset_type"]; + asset_code: OfferAsset["asset_code"]; + trustor: string; +} +export interface TrustlineDeauthorized extends Omit { + type_i: EffectType.trustline_deauthorized; +} +export interface TrustlineAuthorizedToMaintainLiabilities extends Omit { + type_i: EffectType.trustline_authorized_to_maintain_liabilities; +} +export interface ClaimableBalanceCreated extends BaseEffectRecord<'claimable_balance_created'> { + type_i: EffectType.claimable_balance_created; + amount: string; + balance_type_i: string; + asset: string; +} +export interface ClaimableBalanceClaimed extends Omit { + type_i: EffectType.claimable_balance_claimed; +} +export interface ClaimableBalanceClaimantCreated extends Omit { + type_i: EffectType.claimable_balance_claimant_created; +} +interface SponsershipFields { + sponsor: string; + new_sponsor: string; + former_sponsor: string; +} +interface AccountSponsorshipEvents extends BaseEffectRecord, SponsershipFields { +} +export type AccountSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.account_sponsorship_created; +}; +export type AccountSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.account_sponsorship_updated; +}; +export type AccountSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.account_sponsorship_removed; +}; +interface TrustlineSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + asset?: string; + liquidity_pool_id?: string; +} +export type TrustlineSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.trustline_sponsorship_created; +}; +export type TrustlineSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.trustline_sponsorship_updated; +}; +export type TrustlineSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.trustline_sponsorship_removed; +}; +interface DataSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + data_name: string; +} +export type DateSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.data_sponsorship_created; +}; +export type DateSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.data_sponsorship_updated; +}; +export type DateSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.data_sponsorship_removed; +}; +interface ClaimableBalanceSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + balance_type_i: string; +} +export type ClaimableBalanceSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.claimable_balance_sponsorship_created; +}; +export type ClaimableBalanceSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.claimable_balance_sponsorship_updated; +}; +export type ClaimableBalanceSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.claimable_balance_sponsorship_removed; +}; +interface SignerSponsorshipEvents extends BaseEffectRecord, SponsershipFields { + signer: string; +} +export type SignerSponsorshipCreated = Omit, "new_sponsor" | "former_sponsor"> & { + type_i: EffectType.signer_sponsorship_created; +}; +export type SignerSponsorshipUpdated = Omit, "sponsor"> & { + type_i: EffectType.signer_sponsorship_updated; +}; +export type SignerSponsorshipRemoved = Omit, "new_sponsor" | "sponsor"> & { + type_i: EffectType.signer_sponsorship_removed; +}; +export interface ClaimableBalanceClawedBack extends HorizonApi.BaseResponse { + balance_id: string; +} +export interface LiquidityPoolEffectRecord extends HorizonApi.BaseResponse { + id: string; + fee_bp: number; + type: HorizonApi.LiquidityPoolType; + total_trustlines: string; + total_shares: string; + reserves: HorizonApi.Reserve[]; +} +export interface LiquidityPoolDeposited extends BaseEffectRecord<'liquidity_pool_deposited'> { + type_i: EffectType.liquidity_pool_deposited; + liquidity_pool: LiquidityPoolEffectRecord; + reserves_deposited: HorizonApi.Reserve[]; + shares_received: string; +} +export interface LiquidityPoolWithdrew extends BaseEffectRecord<'liquidity_pool_withdrew'> { + type_i: EffectType.liquidity_pool_withdrew; + liquidity_pool: LiquidityPoolEffectRecord; + reserves_received: HorizonApi.Reserve[]; + shares_redeemed: string; +} +export interface LiquidityPoolTrade extends BaseEffectRecord<'liquidity_pool_trade'> { + type_i: EffectType.liquidity_pool_trade; + liquidity_pool: LiquidityPoolEffectRecord; + sold: HorizonApi.Reserve; + bought: HorizonApi.Reserve; +} +export interface LiquidityPoolCreated extends BaseEffectRecord<'liquidity_pool_created'> { + type_i: EffectType.liquidity_pool_created; + liquidity_pool: LiquidityPoolEffectRecord; +} +export interface LiquidityPoolRemoved extends BaseEffectRecord<'liquidity_pool_removed'> { + type_i: EffectType.liquidity_pool_removed; + liquidity_pool_id: string; +} +export interface LiquidityPoolRevoked extends BaseEffectRecord<'liquidity_pool_revoked'> { + type_i: EffectType.liquidity_pool_revoked; + liquidity_pool: LiquidityPoolEffectRecord; + reserves_revoked: [ + { + asset: string; + amount: string; + claimable_balance_id: string; + } + ]; + shares_revoked: string; +} +export interface ContractCredited extends BaseEffectRecord<'contract_credited'>, OfferAsset { + type_i: EffectType.contract_credited; + contract: string; + amount: string; +} +export interface ContractDebited extends BaseEffectRecord<'contract_debited'>, OfferAsset { + type_i: EffectType.contract_debited; + contract: string; + amount: string; +} +export {}; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/effects.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/effects.js new file mode 100644 index 000000000..3b28a678f --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/effects.js @@ -0,0 +1,62 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.EffectType = void 0; +var EffectType = exports.EffectType = function (EffectType) { + EffectType[EffectType["account_created"] = 0] = "account_created"; + EffectType[EffectType["account_removed"] = 1] = "account_removed"; + EffectType[EffectType["account_credited"] = 2] = "account_credited"; + EffectType[EffectType["account_debited"] = 3] = "account_debited"; + EffectType[EffectType["account_thresholds_updated"] = 4] = "account_thresholds_updated"; + EffectType[EffectType["account_home_domain_updated"] = 5] = "account_home_domain_updated"; + EffectType[EffectType["account_flags_updated"] = 6] = "account_flags_updated"; + EffectType[EffectType["account_inflation_destination_updated"] = 7] = "account_inflation_destination_updated"; + EffectType[EffectType["signer_created"] = 10] = "signer_created"; + EffectType[EffectType["signer_removed"] = 11] = "signer_removed"; + EffectType[EffectType["signer_updated"] = 12] = "signer_updated"; + EffectType[EffectType["trustline_created"] = 20] = "trustline_created"; + EffectType[EffectType["trustline_removed"] = 21] = "trustline_removed"; + EffectType[EffectType["trustline_updated"] = 22] = "trustline_updated"; + EffectType[EffectType["trustline_authorized"] = 23] = "trustline_authorized"; + EffectType[EffectType["trustline_deauthorized"] = 24] = "trustline_deauthorized"; + EffectType[EffectType["trustline_authorized_to_maintain_liabilities"] = 25] = "trustline_authorized_to_maintain_liabilities"; + EffectType[EffectType["trustline_flags_updated"] = 26] = "trustline_flags_updated"; + EffectType[EffectType["offer_created"] = 30] = "offer_created"; + EffectType[EffectType["offer_removed"] = 31] = "offer_removed"; + EffectType[EffectType["offer_updated"] = 32] = "offer_updated"; + EffectType[EffectType["trade"] = 33] = "trade"; + EffectType[EffectType["data_created"] = 40] = "data_created"; + EffectType[EffectType["data_removed"] = 41] = "data_removed"; + EffectType[EffectType["data_updated"] = 42] = "data_updated"; + EffectType[EffectType["sequence_bumped"] = 43] = "sequence_bumped"; + EffectType[EffectType["claimable_balance_created"] = 50] = "claimable_balance_created"; + EffectType[EffectType["claimable_balance_claimant_created"] = 51] = "claimable_balance_claimant_created"; + EffectType[EffectType["claimable_balance_claimed"] = 52] = "claimable_balance_claimed"; + EffectType[EffectType["account_sponsorship_created"] = 60] = "account_sponsorship_created"; + EffectType[EffectType["account_sponsorship_updated"] = 61] = "account_sponsorship_updated"; + EffectType[EffectType["account_sponsorship_removed"] = 62] = "account_sponsorship_removed"; + EffectType[EffectType["trustline_sponsorship_created"] = 63] = "trustline_sponsorship_created"; + EffectType[EffectType["trustline_sponsorship_updated"] = 64] = "trustline_sponsorship_updated"; + EffectType[EffectType["trustline_sponsorship_removed"] = 65] = "trustline_sponsorship_removed"; + EffectType[EffectType["data_sponsorship_created"] = 66] = "data_sponsorship_created"; + EffectType[EffectType["data_sponsorship_updated"] = 67] = "data_sponsorship_updated"; + EffectType[EffectType["data_sponsorship_removed"] = 68] = "data_sponsorship_removed"; + EffectType[EffectType["claimable_balance_sponsorship_created"] = 69] = "claimable_balance_sponsorship_created"; + EffectType[EffectType["claimable_balance_sponsorship_updated"] = 70] = "claimable_balance_sponsorship_updated"; + EffectType[EffectType["claimable_balance_sponsorship_removed"] = 71] = "claimable_balance_sponsorship_removed"; + EffectType[EffectType["signer_sponsorship_created"] = 72] = "signer_sponsorship_created"; + EffectType[EffectType["signer_sponsorship_updated"] = 73] = "signer_sponsorship_updated"; + EffectType[EffectType["signer_sponsorship_removed"] = 74] = "signer_sponsorship_removed"; + EffectType[EffectType["claimable_balance_clawed_back"] = 80] = "claimable_balance_clawed_back"; + EffectType[EffectType["liquidity_pool_deposited"] = 90] = "liquidity_pool_deposited"; + EffectType[EffectType["liquidity_pool_withdrew"] = 91] = "liquidity_pool_withdrew"; + EffectType[EffectType["liquidity_pool_trade"] = 92] = "liquidity_pool_trade"; + EffectType[EffectType["liquidity_pool_created"] = 93] = "liquidity_pool_created"; + EffectType[EffectType["liquidity_pool_removed"] = 94] = "liquidity_pool_removed"; + EffectType[EffectType["liquidity_pool_revoked"] = 95] = "liquidity_pool_revoked"; + EffectType[EffectType["contract_credited"] = 96] = "contract_credited"; + EffectType[EffectType["contract_debited"] = 97] = "contract_debited"; + return EffectType; +}({}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/offer.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/offer.d.ts new file mode 100644 index 000000000..a58e3f16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/offer.d.ts @@ -0,0 +1,20 @@ +import { AssetType } from "@stellar/stellar-base"; +import { HorizonApi } from "../horizon_api"; +export interface OfferAsset { + asset_type: AssetType; + asset_code?: string; + asset_issuer?: string; +} +export interface OfferRecord extends HorizonApi.BaseResponse { + id: number | string; + paging_token: string; + seller: string; + selling: OfferAsset; + buying: OfferAsset; + amount: string; + price_r: HorizonApi.PriceRShorthand; + price: string; + last_modified_ledger: number; + last_modified_time: string; + sponsor?: string; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/offer.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/offer.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/offer.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/trade.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/trade.d.ts new file mode 100644 index 000000000..a38f75361 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/trade.d.ts @@ -0,0 +1,14 @@ +import { BaseEffectRecord, EffectType } from "./effects"; +export interface Trade extends BaseEffectRecord<'trade'> { + type_i: EffectType.trade; + seller: string; + offer_id: number | string; + bought_amount: string; + bought_asset_type: string; + bought_asset_code: string; + bought_asset_issuer: string; + sold_amount: string; + sold_asset_type: string; + sold_asset_code: string; + sold_asset_issuer: string; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/trade.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/trade.js new file mode 100644 index 000000000..430afc16c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/horizon/types/trade.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/axios-client.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/axios-client.d.ts new file mode 100644 index 000000000..739c21526 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/axios-client.d.ts @@ -0,0 +1,2 @@ +export declare const axiosClient: import("axios").AxiosStatic; +export declare const create: (config?: import("axios").CreateAxiosDefaults) => import("axios").AxiosInstance; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/axios-client.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/axios-client.js new file mode 100644 index 000000000..12a4eb449 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/axios-client.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.create = exports.axiosClient = void 0; +var _axios = _interopRequireDefault(require("axios")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +var axiosClient = exports.axiosClient = _axios.default; +var create = exports.create = _axios.default.create; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/fetch-client.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/fetch-client.d.ts new file mode 100644 index 000000000..8b91ef645 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/fetch-client.d.ts @@ -0,0 +1,11 @@ +import { AxiosRequestConfig, AxiosResponse } from 'feaxios'; +import { CancelToken, HttpClient, HttpClientRequestConfig, HttpClientResponse } from './types'; +export interface HttpResponse extends AxiosResponse { +} +export interface FetchClientConfig extends AxiosRequestConfig { + adapter?: (config: HttpClientRequestConfig) => Promise>; + cancelToken?: CancelToken; +} +declare function createFetchClient(fetchConfig?: HttpClientRequestConfig): HttpClient; +export declare const fetchClient: HttpClient; +export { createFetchClient as create }; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/fetch-client.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/fetch-client.js new file mode 100644 index 000000000..5da967e91 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/fetch-client.js @@ -0,0 +1,229 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.create = createFetchClient; +exports.fetchClient = void 0; +var _feaxios = _interopRequireDefault(require("feaxios")); +var _types = require("./types"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var InterceptorManager = function () { + function InterceptorManager() { + _classCallCheck(this, InterceptorManager); + _defineProperty(this, "handlers", []); + } + return _createClass(InterceptorManager, [{ + key: "use", + value: function use(fulfilled, rejected) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected + }); + return this.handlers.length - 1; + } + }, { + key: "eject", + value: function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + }, { + key: "forEach", + value: function forEach(fn) { + this.handlers.forEach(function (h) { + if (h !== null) { + fn(h); + } + }); + } + }]); +}(); +function getFormConfig(config) { + var formConfig = config || {}; + formConfig.headers = new Headers(formConfig.headers || {}); + formConfig.headers.set('Content-Type', 'application/x-www-form-urlencoded'); + return formConfig; +} +function createFetchClient() { + var fetchConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var defaults = _objectSpread(_objectSpread({}, fetchConfig), {}, { + headers: fetchConfig.headers || {} + }); + var instance = _feaxios.default.create(defaults); + var requestInterceptors = new InterceptorManager(); + var responseInterceptors = new InterceptorManager(); + var httpClient = { + interceptors: { + request: requestInterceptors, + response: responseInterceptors + }, + defaults: _objectSpread(_objectSpread({}, defaults), {}, { + adapter: function adapter(config) { + return instance.request(config); + } + }), + create: function create(config) { + return createFetchClient(_objectSpread(_objectSpread({}, this.defaults), config)); + }, + makeRequest: function makeRequest(config) { + var _this = this; + return new Promise(function (resolve, reject) { + var abortController = new AbortController(); + config.signal = abortController.signal; + if (config.cancelToken) { + config.cancelToken.promise.then(function () { + abortController.abort(); + reject(new Error('Request canceled')); + }); + } + var modifiedConfig = config; + if (requestInterceptors.handlers.length > 0) { + var chain = requestInterceptors.handlers.filter(function (interceptor) { + return interceptor !== null; + }).flatMap(function (interceptor) { + return [interceptor.fulfilled, interceptor.rejected]; + }); + for (var i = 0, len = chain.length; i < len; i += 2) { + var onFulfilled = chain[i]; + var onRejected = chain[i + 1]; + try { + if (onFulfilled) modifiedConfig = onFulfilled(modifiedConfig); + } catch (error) { + if (onRejected) onRejected === null || onRejected === void 0 || onRejected(error); + reject(error); + return; + } + } + } + var adapter = modifiedConfig.adapter || _this.defaults.adapter; + if (!adapter) { + throw new Error('No adapter available'); + } + var responsePromise = adapter(modifiedConfig).then(function (axiosResponse) { + var httpClientResponse = { + data: axiosResponse.data, + headers: axiosResponse.headers, + config: axiosResponse.config, + status: axiosResponse.status, + statusText: axiosResponse.statusText + }; + return httpClientResponse; + }); + if (responseInterceptors.handlers.length > 0) { + var _chain = responseInterceptors.handlers.filter(function (interceptor) { + return interceptor !== null; + }).flatMap(function (interceptor) { + return [interceptor.fulfilled, interceptor.rejected]; + }); + var _loop = function _loop(_i) { + responsePromise = responsePromise.then(function (response) { + var fulfilledInterceptor = _chain[_i]; + if (typeof fulfilledInterceptor === 'function') { + return fulfilledInterceptor(response); + } + return response; + }, function (error) { + var rejectedInterceptor = _chain[_i + 1]; + if (typeof rejectedInterceptor === 'function') { + return rejectedInterceptor(error); + } + throw error; + }).then(function (interceptedResponse) { + return interceptedResponse; + }); + }; + for (var _i = 0, _len = _chain.length; _i < _len; _i += 2) { + _loop(_i); + } + } + responsePromise.then(resolve).catch(reject); + }); + }, + get: function get(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'get' + })); + }, + delete: function _delete(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'delete' + })); + }, + head: function head(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'head' + })); + }, + options: function options(url, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'options' + })); + }, + post: function post(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'post', + data: data + })); + }, + put: function put(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'put', + data: data + })); + }, + patch: function patch(url, data, config) { + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), config), {}, { + url: url, + method: 'patch', + data: data + })); + }, + postForm: function postForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'post', + data: data + })); + }, + putForm: function putForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'put', + data: data + })); + }, + patchForm: function patchForm(url, data, config) { + var formConfig = getFormConfig(config); + return this.makeRequest(_objectSpread(_objectSpread(_objectSpread({}, this.defaults), formConfig), {}, { + url: url, + method: 'patch', + data: data + })); + }, + CancelToken: _types.CancelToken, + isCancel: function isCancel(value) { + return value instanceof Error && value.message === 'Request canceled'; + } + }; + return httpClient; +} +var fetchClient = exports.fetchClient = createFetchClient(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/index.d.ts new file mode 100644 index 000000000..b6dea58cd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/index.d.ts @@ -0,0 +1,5 @@ +import { HttpClient, HttpClientRequestConfig } from "./types"; +declare let httpClient: HttpClient; +declare let create: (config?: HttpClientRequestConfig) => HttpClient; +export { httpClient, create }; +export * from "./types"; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/index.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/index.js new file mode 100644 index 000000000..96d7a6f35 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/index.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + httpClient: true, + create: true +}; +exports.httpClient = exports.create = void 0; +var _types = require("./types"); +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _types[key]; + } + }); +}); +var httpClient; +var create; +if (true) { + var axiosModule = require('./axios-client'); + exports.httpClient = httpClient = axiosModule.axiosClient; + exports.create = create = axiosModule.create; +} else { + var fetchModule = require('./fetch-client'); + exports.httpClient = httpClient = fetchModule.fetchClient; + exports.create = create = fetchModule.create; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/types.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/types.d.ts new file mode 100644 index 000000000..6aa38dddc --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/types.d.ts @@ -0,0 +1,70 @@ +export type HttpResponseHeaders = Record & { + 'set-cookie'?: string[]; +}; +export interface HttpClientDefaults extends Omit { + headers?: [string, string][] | Record | Headers | undefined; +} +export interface HttpClientResponse { + data: T; + headers: HttpResponseHeaders; + config: any; + status: number; + statusText: string; +} +export interface CancelToken { + promise: Promise; + throwIfRequested(): void; + reason?: string; +} +type HeadersInit = [string, string][] | Record | Headers; +export interface HttpClientRequestConfig { + url?: string; + method?: string; + baseURL?: string; + data?: D; + timeout?: number; + fetchOptions?: Record; + headers?: HeadersInit; + params?: Record; + maxContentLength?: number; + maxRedirects?: number; + cancelToken?: CancelToken; + adapter?: (config: HttpClientRequestConfig) => Promise; +} +export interface HttpClient { + get: (url: string, config?: HttpClientRequestConfig) => Promise>; + delete: (url: string, config?: HttpClientRequestConfig) => Promise>; + head: (url: string, config?: HttpClientRequestConfig) => Promise>; + options: (url: string, config?: HttpClientRequestConfig) => Promise>; + post: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + put: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + patch: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + postForm: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + putForm: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + patchForm: (url: string, data?: any, config?: HttpClientRequestConfig) => Promise>; + interceptors: { + request: InterceptorManager; + response: InterceptorManager; + }; + defaults: HttpClientDefaults; + CancelToken: typeof CancelToken; + isCancel: (value: any) => boolean; + makeRequest: (config: HttpClientRequestConfig) => Promise>; + create: (config?: HttpClientRequestConfig) => HttpClient; +} +export interface Interceptor { + fulfilled: (value: V) => V | Promise; + rejected?: (error: any) => any; +} +export interface InterceptorManager { + use(fulfilled: (value: V) => V | Promise, rejected?: (error: any) => any): number; + eject(id: number): void; + forEach(fn: (interceptor: Interceptor) => void): void; + handlers: Array | null>; +} +export declare class CancelToken { + promise: Promise; + reason?: string; + constructor(executor: (cancel: (reason?: string) => void) => void); +} +export {}; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/types.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/types.js new file mode 100644 index 000000000..80b1012fb --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/http-client/types.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.CancelToken = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var CancelToken = exports.CancelToken = function () { + function CancelToken(executor) { + var _this = this; + _classCallCheck(this, CancelToken); + var resolvePromise; + this.promise = new Promise(function (resolve) { + resolvePromise = resolve; + }); + executor(function (reason) { + _this.reason = reason; + resolvePromise(); + }); + } + return _createClass(CancelToken, [{ + key: "throwIfRequested", + value: function throwIfRequested() { + if (this.reason) { + throw new Error(this.reason); + } + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/index.d.ts new file mode 100644 index 000000000..6ae366241 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/index.d.ts @@ -0,0 +1,32 @@ +export * from './errors'; +export { Config } from './config'; +export { Utils } from './utils'; +export * as StellarToml from './stellartoml'; +export * as Federation from './federation'; +export * as WebAuth from './webauth'; +export * as Friendbot from './friendbot'; +export * as Horizon from './horizon'; +/** + * Tools for interacting with the Soroban RPC server, such as `Server`, + * `assembleTransaction`, and the `Api` types. You can import these from the + * `/rpc` entrypoint, if your version of Node and your TypeScript configuration + * allow it: + * + * @example + * import { Server } from '@stellar/stellar-sdk/rpc'; + */ +export * as rpc from './rpc'; +/** + * Tools for interacting with smart contracts, such as `Client`, `Spec`, and + * `AssembledTransaction`. You can import these from the `/contract` + * entrypoint, if your version of Node and your TypeScript configuration allow + * it: + * + * @example + * import { Client } from '@stellar/stellar-sdk/contract'; + * @private + */ +export * as contract from './contract'; +export * from '@stellar/stellar-base'; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/index.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/index.js new file mode 100644 index 000000000..cbdb8649c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/index.js @@ -0,0 +1,80 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Config: true, + Utils: true, + StellarToml: true, + Federation: true, + WebAuth: true, + Friendbot: true, + Horizon: true, + rpc: true, + contract: true +}; +Object.defineProperty(exports, "Config", { + enumerable: true, + get: function get() { + return _config.Config; + } +}); +exports.StellarToml = exports.Horizon = exports.Friendbot = exports.Federation = void 0; +Object.defineProperty(exports, "Utils", { + enumerable: true, + get: function get() { + return _utils.Utils; + } +}); +exports.rpc = exports.default = exports.contract = exports.WebAuth = void 0; +var _errors = require("./errors"); +Object.keys(_errors).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _errors[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _errors[key]; + } + }); +}); +var _config = require("./config"); +var _utils = require("./utils"); +var _StellarToml = _interopRequireWildcard(require("./stellartoml")); +exports.StellarToml = _StellarToml; +var _Federation = _interopRequireWildcard(require("./federation")); +exports.Federation = _Federation; +var _WebAuth = _interopRequireWildcard(require("./webauth")); +exports.WebAuth = _WebAuth; +var _Friendbot = _interopRequireWildcard(require("./friendbot")); +exports.Friendbot = _Friendbot; +var _Horizon = _interopRequireWildcard(require("./horizon")); +exports.Horizon = _Horizon; +var _rpc = _interopRequireWildcard(require("./rpc")); +exports.rpc = _rpc; +var _contract = _interopRequireWildcard(require("./contract")); +exports.contract = _contract; +var _stellarBase = require("@stellar/stellar-base"); +Object.keys(_stellarBase).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _stellarBase[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _stellarBase[key]; + } + }); +}); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; +if (typeof global.__USE_AXIOS__ === 'undefined') { + global.__USE_AXIOS__ = true; +} +if (typeof global.__USE_EVENTSOURCE__ === 'undefined') { + global.__USE_EVENTSOURCE__ = false; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/api.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/api.d.ts new file mode 100644 index 000000000..87d269804 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/api.d.ts @@ -0,0 +1,363 @@ +import { Contract, SorobanDataBuilder, xdr } from '@stellar/stellar-base'; +export declare namespace Api { + export interface GetHealthResponse { + status: 'healthy'; + } + export interface LedgerEntryResult { + lastModifiedLedgerSeq?: number; + key: xdr.LedgerKey; + val: xdr.LedgerEntryData; + liveUntilLedgerSeq?: number; + } + export interface RawLedgerEntryResult { + lastModifiedLedgerSeq?: number; + /** a base-64 encoded {@link xdr.LedgerKey} instance */ + key: string; + /** a base-64 encoded {@link xdr.LedgerEntryData} instance */ + xdr: string; + /** + * optional, a future ledger number upon which this entry will expire + * based on https://github.com/stellar/soroban-tools/issues/1010 + */ + liveUntilLedgerSeq?: number; + } + /** An XDR-parsed version of {@link this.RawLedgerEntryResult} */ + export interface GetLedgerEntriesResponse { + entries: LedgerEntryResult[]; + latestLedger: number; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries */ + export interface RawGetLedgerEntriesResponse { + entries?: RawLedgerEntryResult[]; + latestLedger: number; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getNetwork */ + export interface GetNetworkResponse { + friendbotUrl?: string; + passphrase: string; + protocolVersion: string; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLatestLedger */ + export interface GetLatestLedgerResponse { + id: string; + sequence: number; + protocolVersion: string; + } + export enum GetTransactionStatus { + SUCCESS = "SUCCESS", + NOT_FOUND = "NOT_FOUND", + FAILED = "FAILED" + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransaction */ + export type GetTransactionResponse = GetSuccessfulTransactionResponse | GetFailedTransactionResponse | GetMissingTransactionResponse; + interface GetAnyTransactionResponse { + status: GetTransactionStatus; + txHash: string; + latestLedger: number; + latestLedgerCloseTime: number; + oldestLedger: number; + oldestLedgerCloseTime: number; + } + export interface GetMissingTransactionResponse extends GetAnyTransactionResponse { + status: GetTransactionStatus.NOT_FOUND; + } + export interface GetFailedTransactionResponse extends GetAnyTransactionResponse { + status: GetTransactionStatus.FAILED; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + envelopeXdr: xdr.TransactionEnvelope; + resultXdr: xdr.TransactionResult; + resultMetaXdr: xdr.TransactionMeta; + diagnosticEventsXdr?: xdr.DiagnosticEvent[]; + } + export interface GetSuccessfulTransactionResponse extends GetAnyTransactionResponse { + status: GetTransactionStatus.SUCCESS; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + envelopeXdr: xdr.TransactionEnvelope; + resultXdr: xdr.TransactionResult; + resultMetaXdr: xdr.TransactionMeta; + diagnosticEventsXdr?: xdr.DiagnosticEvent[]; + returnValue?: xdr.ScVal; + } + export interface RawGetTransactionResponse { + status: GetTransactionStatus; + latestLedger: number; + latestLedgerCloseTime: number; + oldestLedger: number; + oldestLedgerCloseTime: number; + txHash: string; + applicationOrder?: number; + feeBump?: boolean; + ledger?: number; + createdAt?: number; + envelopeXdr?: string; + resultXdr?: string; + resultMetaXdr?: string; + diagnosticEventsXdr?: string[]; + } + export interface GetTransactionsRequest { + startLedger: number; + cursor?: string; + limit?: number; + } + export interface RawTransactionInfo { + status: GetTransactionStatus; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + txHash: string; + envelopeXdr?: string; + resultXdr?: string; + resultMetaXdr?: string; + diagnosticEventsXdr?: string[]; + } + export interface TransactionInfo { + status: GetTransactionStatus; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + txHash: string; + envelopeXdr: xdr.TransactionEnvelope; + resultXdr: xdr.TransactionResult; + resultMetaXdr: xdr.TransactionMeta; + returnValue?: xdr.ScVal; + diagnosticEventsXdr?: xdr.DiagnosticEvent[]; + } + export interface GetTransactionsResponse { + transactions: TransactionInfo[]; + latestLedger: number; + latestLedgerCloseTimestamp: number; + oldestLedger: number; + oldestLedgerCloseTimestamp: number; + cursor: string; + } + export interface RawGetTransactionsResponse { + transactions: RawTransactionInfo[]; + latestLedger: number; + latestLedgerCloseTimestamp: number; + oldestLedger: number; + oldestLedgerCloseTimestamp: number; + cursor: string; + } + export type EventType = 'contract' | 'system' | 'diagnostic'; + export interface EventFilter { + type?: EventType; + contractIds?: string[]; + topics?: string[][]; + } + export interface GetEventsResponse { + latestLedger: number; + events: EventResponse[]; + cursor: string; + } + export interface EventResponse extends BaseEventResponse { + contractId?: Contract; + topic: xdr.ScVal[]; + value: xdr.ScVal; + } + export interface RawGetEventsResponse { + latestLedger: number; + events: RawEventResponse[]; + cursor: string; + } + interface BaseEventResponse { + id: string; + type: EventType; + ledger: number; + ledgerClosedAt: string; + pagingToken: string; + inSuccessfulContractCall: boolean; + txHash: string; + } + export interface RawEventResponse extends BaseEventResponse { + contractId: string; + topic: string[]; + value: string; + } + interface RawLedgerEntryChange { + type: number; + /** This is LedgerKey in base64 */ + key: string; + /** This is xdr.LedgerEntry in base64 */ + before: string | null; + /** This is xdr.LedgerEntry in base64 */ + after: string | null; + } + export interface LedgerEntryChange { + type: number; + key: xdr.LedgerKey; + before: xdr.LedgerEntry | null; + after: xdr.LedgerEntry | null; + } + export type SendTransactionStatus = 'PENDING' | 'DUPLICATE' | 'TRY_AGAIN_LATER' | 'ERROR'; + export interface SendTransactionResponse extends BaseSendTransactionResponse { + errorResult?: xdr.TransactionResult; + diagnosticEvents?: xdr.DiagnosticEvent[]; + } + export interface RawSendTransactionResponse extends BaseSendTransactionResponse { + /** + * This is a base64-encoded instance of {@link xdr.TransactionResult}, set + * only when `status` is `"ERROR"`. + * + * It contains details on why the network rejected the transaction. + */ + errorResultXdr?: string; + /** + * This is a base64-encoded instance of an array of + * {@link xdr.DiagnosticEvent}s, set only when `status` is `"ERROR"` and + * diagnostic events are enabled on the server. + */ + diagnosticEventsXdr?: string[]; + } + export interface BaseSendTransactionResponse { + status: SendTransactionStatus; + hash: string; + latestLedger: number; + latestLedgerCloseTime: number; + } + export interface SimulateHostFunctionResult { + auth: xdr.SorobanAuthorizationEntry[]; + retval: xdr.ScVal; + } + /** + * Simplifies {@link Api.RawSimulateTransactionResponse} into separate interfaces + * based on status: + * - on success, this includes all fields, though `result` is only present + * if an invocation was simulated (since otherwise there's nothing to + * "resultify") + * - if there was an expiration error, this includes error and restoration + * fields + * - for all other errors, this only includes error fields + * + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction + */ + export type SimulateTransactionResponse = SimulateTransactionSuccessResponse | SimulateTransactionRestoreResponse | SimulateTransactionErrorResponse; + export interface BaseSimulateTransactionResponse { + /** always present: the JSON-RPC request ID */ + id: string; + /** always present: the LCL known to the server when responding */ + latestLedger: number; + /** + * The field is always present, but may be empty in cases where: + * - you didn't simulate an invocation or + * - there were no events + */ + events: xdr.DiagnosticEvent[]; + /** a private field to mark the schema as parsed */ + _parsed: boolean; + } + /** Includes simplified fields only present on success. */ + export interface SimulateTransactionSuccessResponse extends BaseSimulateTransactionResponse { + transactionData: SorobanDataBuilder; + minResourceFee: string; + /** present only for invocation simulation */ + result?: SimulateHostFunctionResult; + /** State Difference information */ + stateChanges?: LedgerEntryChange[]; + } + /** Includes details about why the simulation failed */ + export interface SimulateTransactionErrorResponse extends BaseSimulateTransactionResponse { + error: string; + events: xdr.DiagnosticEvent[]; + } + export interface SimulateTransactionRestoreResponse extends SimulateTransactionSuccessResponse { + result: SimulateHostFunctionResult; + /** + * Indicates that a restoration is necessary prior to submission. + * + * In other words, seeing a restoration preamble means that your invocation + * was executed AS IF the required ledger entries were present, and this + * field includes information about what you need to restore for the + * simulation to succeed. + */ + restorePreamble: { + minResourceFee: string; + transactionData: SorobanDataBuilder; + }; + } + export function isSimulationError(sim: SimulateTransactionResponse): sim is SimulateTransactionErrorResponse; + export function isSimulationSuccess(sim: SimulateTransactionResponse): sim is SimulateTransactionSuccessResponse; + export function isSimulationRestore(sim: SimulateTransactionResponse): sim is SimulateTransactionRestoreResponse; + export function isSimulationRaw(sim: Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse): sim is Api.RawSimulateTransactionResponse; + interface RawSimulateHostFunctionResult { + auth?: string[]; + xdr: string; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction */ + export interface RawSimulateTransactionResponse { + id: string; + latestLedger: number; + error?: string; + /** This is an xdr.SorobanTransactionData in base64 */ + transactionData?: string; + /** These are xdr.DiagnosticEvents in base64 */ + events?: string[]; + minResourceFee?: string; + /** + * This will only contain a single element if present, because only a single + * invokeHostFunctionOperation is supported per transaction. + * */ + results?: RawSimulateHostFunctionResult[]; + /** Present if succeeded but has expired ledger entries */ + restorePreamble?: { + minResourceFee: string; + transactionData: string; + }; + /** State difference information */ + stateChanges?: RawLedgerEntryChange[]; + } + export interface GetVersionInfoResponse { + version: string; + commitHash: string; + buildTimestamp: string; + captiveCoreVersion: string; + protocolVersion: number; + commit_hash: string; + build_timestamp: string; + captive_core_version: string; + protocol_version: number; + } + export interface GetFeeStatsResponse { + sorobanInclusionFee: FeeDistribution; + inclusionFee: FeeDistribution; + latestLedger: number; + } + interface FeeDistribution { + max: string; + min: string; + mode: string; + p10: string; + p20: string; + p30: string; + p40: string; + p50: string; + p60: string; + p70: string; + p80: string; + p90: string; + p95: string; + p99: string; + transactionCount: string; + ledgerCount: number; + } + export interface BalanceResponse { + latestLedger: number; + /** present only on success, otherwise request malformed or no balance */ + balanceEntry?: { + /** a 64-bit integer */ + amount: string; + authorized: boolean; + clawback: boolean; + lastModifiedLedgerSeq?: number; + liveUntilLedgerSeq?: number; + }; + } + export {}; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/api.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/api.js new file mode 100644 index 000000000..119ddb359 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/api.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Api = void 0; +var Api; +(function (_Api) { + var GetTransactionStatus = function (GetTransactionStatus) { + GetTransactionStatus["SUCCESS"] = "SUCCESS"; + GetTransactionStatus["NOT_FOUND"] = "NOT_FOUND"; + GetTransactionStatus["FAILED"] = "FAILED"; + return GetTransactionStatus; + }({}); + _Api.GetTransactionStatus = GetTransactionStatus; + function isSimulationError(sim) { + return 'error' in sim; + } + _Api.isSimulationError = isSimulationError; + function isSimulationSuccess(sim) { + return 'transactionData' in sim; + } + _Api.isSimulationSuccess = isSimulationSuccess; + function isSimulationRestore(sim) { + return isSimulationSuccess(sim) && 'restorePreamble' in sim && !!sim.restorePreamble.transactionData; + } + _Api.isSimulationRestore = isSimulationRestore; + function isSimulationRaw(sim) { + return !sim._parsed; + } + _Api.isSimulationRaw = isSimulationRaw; +})(Api || (exports.Api = Api = {})); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/axios.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/axios.d.ts new file mode 100644 index 000000000..e33eb69ca --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/axios.d.ts @@ -0,0 +1,4 @@ +import { HttpClient } from "../http-client"; +export declare const version: string; +export declare const AxiosClient: HttpClient; +export default AxiosClient; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/axios.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/axios.js new file mode 100644 index 000000000..7ac7ee27c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/axios.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.version = exports.default = exports.AxiosClient = void 0; +var _httpClient = require("../http-client"); +var version = exports.version = "13.1.0"; +var AxiosClient = exports.AxiosClient = (0, _httpClient.create)({ + headers: { + 'X-Client-Name': 'js-soroban-client', + 'X-Client-Version': version + } +}); +var _default = exports.default = AxiosClient; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/browser.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/browser.d.ts new file mode 100644 index 000000000..ca51e31ab --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/browser.d.ts @@ -0,0 +1,4 @@ +export * from './index'; +export * as StellarBase from '@stellar/stellar-base'; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/browser.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/browser.js new file mode 100644 index 000000000..81ef3ddb4 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/browser.js @@ -0,0 +1,27 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + StellarBase: true +}; +exports.default = exports.StellarBase = void 0; +var _index = require("./index"); +Object.keys(_index).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _index[key]; + } + }); +}); +var _StellarBase = _interopRequireWildcard(require("@stellar/stellar-base")); +exports.StellarBase = _StellarBase; +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/index.d.ts new file mode 100644 index 000000000..59ea4be47 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/index.d.ts @@ -0,0 +1,8 @@ +/** @module rpc */ +export * from "./api"; +export { RpcServer as Server, BasicSleepStrategy, LinearSleepStrategy, Durability } from "./server"; +export { default as AxiosClient } from "./axios"; +export { parseRawSimulation, parseRawEvents } from "./parsers"; +export * from "./transaction"; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/index.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/index.js new file mode 100644 index 000000000..f5a9e18bd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/index.js @@ -0,0 +1,86 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Server: true, + BasicSleepStrategy: true, + LinearSleepStrategy: true, + Durability: true, + AxiosClient: true, + parseRawSimulation: true, + parseRawEvents: true +}; +Object.defineProperty(exports, "AxiosClient", { + enumerable: true, + get: function get() { + return _axios.default; + } +}); +Object.defineProperty(exports, "BasicSleepStrategy", { + enumerable: true, + get: function get() { + return _server.BasicSleepStrategy; + } +}); +Object.defineProperty(exports, "Durability", { + enumerable: true, + get: function get() { + return _server.Durability; + } +}); +Object.defineProperty(exports, "LinearSleepStrategy", { + enumerable: true, + get: function get() { + return _server.LinearSleepStrategy; + } +}); +Object.defineProperty(exports, "Server", { + enumerable: true, + get: function get() { + return _server.RpcServer; + } +}); +exports.default = void 0; +Object.defineProperty(exports, "parseRawEvents", { + enumerable: true, + get: function get() { + return _parsers.parseRawEvents; + } +}); +Object.defineProperty(exports, "parseRawSimulation", { + enumerable: true, + get: function get() { + return _parsers.parseRawSimulation; + } +}); +var _api = require("./api"); +Object.keys(_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _api[key]; + } + }); +}); +var _server = require("./server"); +var _axios = _interopRequireDefault(require("./axios")); +var _parsers = require("./parsers"); +var _transaction = require("./transaction"); +Object.keys(_transaction).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _transaction[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _transaction[key]; + } + }); +}); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/jsonrpc.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/jsonrpc.d.ts new file mode 100644 index 000000000..bba021d3c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/jsonrpc.d.ts @@ -0,0 +1,35 @@ +export type Id = string | number; +export interface Request { + jsonrpc: "2.0"; + id: Id; + method: string; + params: T; +} +export interface Notification { + jsonrpc: "2.0"; + method: string; + params?: T; +} +export type Response = { + jsonrpc: "2.0"; + id: Id; +} & ({ + error: Error; +} | { + result: T; +}); +export interface Error { + code: number; + message?: string; + data?: E; +} +/** + * Sends the jsonrpc 'params' as a single 'param' object (no array support). + * + * @param {string} url URL to the RPC instance + * @param {string} method RPC method name that should be called + * @param {(any | null)} [param=null] params that should be supplied to the method + * @returns {Promise} + * @private + */ +export declare function postObject(url: string, method: string, param?: any): Promise; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/jsonrpc.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/jsonrpc.js new file mode 100644 index 000000000..8ba0f1a64 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/jsonrpc.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.postObject = postObject; +var _axios = _interopRequireDefault(require("./axios")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function hasOwnProperty(obj, prop) { + return obj.hasOwnProperty(prop); +} +function postObject(_x, _x2) { + return _postObject.apply(this, arguments); +} +function _postObject() { + _postObject = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(url, method) { + var param, + response, + _response$data, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + param = _args.length > 2 && _args[2] !== undefined ? _args[2] : null; + _context.next = 3; + return _axios.default.post(url, { + jsonrpc: "2.0", + id: 1, + method: method, + params: param + }); + case 3: + response = _context.sent; + if (!hasOwnProperty(response.data, "error")) { + _context.next = 8; + break; + } + throw response.data.error; + case 8: + return _context.abrupt("return", (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.result); + case 9: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _postObject.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/parsers.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/parsers.d.ts new file mode 100644 index 000000000..28871d62b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/parsers.d.ts @@ -0,0 +1,39 @@ +import { Api } from './api'; +/** + * Parse the response from invoking the `submitTransaction` method of a Soroban RPC server. + * @memberof module:rpc + * @private + * + * @param {Api.RawSendTransactionResponse} raw the raw `submitTransaction` response from the Soroban RPC server to parse + * @returns {Api.SendTransactionResponse} transaction response parsed from the Soroban RPC server's response + */ +export declare function parseRawSendTransaction(raw: Api.RawSendTransactionResponse): Api.SendTransactionResponse; +export declare function parseTransactionInfo(raw: Api.RawTransactionInfo | Api.RawGetTransactionResponse): Omit; +export declare function parseRawTransactions(r: Api.RawTransactionInfo): Api.TransactionInfo; +/** + * Parse and return the retrieved events, if any, from a raw response from a Soroban RPC server. + * @memberof module:rpc + * + * @param {Api.RawGetEventsResponse} raw the raw `getEvents` response from the Soroban RPC server to parse + * @returns {Api.GetEventsResponse} events parsed from the Soroban RPC server's response + */ +export declare function parseRawEvents(raw: Api.RawGetEventsResponse): Api.GetEventsResponse; +/** + * Parse and return the retrieved ledger entries, if any, from a raw response from a Soroban RPC server. + * @memberof module:rpc + * @private + * + * @param {Api.RawGetLedgerEntriesResponse} raw he raw `getLedgerEntries` response from the Soroban RPC server to parse + * @returns {Api.GetLedgerEntriesResponse} ledger entries parsed from the Soroban RPC server's response + */ +export declare function parseRawLedgerEntries(raw: Api.RawGetLedgerEntriesResponse): Api.GetLedgerEntriesResponse; +/** + * Converts a raw response schema into one with parsed XDR fields and a simplified interface. + * @warning This API is only exported for testing purposes and should not be relied on or considered "stable". + * @memberof module:rpc + * + * @param {Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse} sim the raw response schema (parsed ones are allowed, best-effort + * detected, and returned untouched) + * @returns {Api.SimulateTransactionResponse} the original parameter (if already parsed), parsed otherwise + */ +export declare function parseRawSimulation(sim: Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse): Api.SimulateTransactionResponse; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/parsers.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/parsers.js new file mode 100644 index 000000000..196336b10 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/parsers.js @@ -0,0 +1,156 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parseRawEvents = parseRawEvents; +exports.parseRawLedgerEntries = parseRawLedgerEntries; +exports.parseRawSendTransaction = parseRawSendTransaction; +exports.parseRawSimulation = parseRawSimulation; +exports.parseRawTransactions = parseRawTransactions; +exports.parseTransactionInfo = parseTransactionInfo; +var _stellarBase = require("@stellar/stellar-base"); +var _api = require("./api"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function parseRawSendTransaction(raw) { + var errorResultXdr = raw.errorResultXdr, + diagnosticEventsXdr = raw.diagnosticEventsXdr; + delete raw.errorResultXdr; + delete raw.diagnosticEventsXdr; + if (errorResultXdr) { + return _objectSpread(_objectSpread(_objectSpread({}, raw), diagnosticEventsXdr !== undefined && diagnosticEventsXdr.length > 0 && { + diagnosticEvents: diagnosticEventsXdr.map(function (evt) { + return _stellarBase.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + }) + }), {}, { + errorResult: _stellarBase.xdr.TransactionResult.fromXDR(errorResultXdr, 'base64') + }); + } + return _objectSpread({}, raw); +} +function parseTransactionInfo(raw) { + var meta = _stellarBase.xdr.TransactionMeta.fromXDR(raw.resultMetaXdr, 'base64'); + var info = { + ledger: raw.ledger, + createdAt: raw.createdAt, + applicationOrder: raw.applicationOrder, + feeBump: raw.feeBump, + envelopeXdr: _stellarBase.xdr.TransactionEnvelope.fromXDR(raw.envelopeXdr, 'base64'), + resultXdr: _stellarBase.xdr.TransactionResult.fromXDR(raw.resultXdr, 'base64'), + resultMetaXdr: meta + }; + if (meta.switch() === 3 && meta.v3().sorobanMeta() !== null) { + var _meta$v3$sorobanMeta; + info.returnValue = (_meta$v3$sorobanMeta = meta.v3().sorobanMeta()) === null || _meta$v3$sorobanMeta === void 0 ? void 0 : _meta$v3$sorobanMeta.returnValue(); + } + if ('diagnosticEventsXdr' in raw && raw.diagnosticEventsXdr) { + info.diagnosticEventsXdr = raw.diagnosticEventsXdr.map(function (diagnosticEvent) { + return _stellarBase.xdr.DiagnosticEvent.fromXDR(diagnosticEvent, 'base64'); + }); + } + return info; +} +function parseRawTransactions(r) { + return _objectSpread({ + status: r.status, + txHash: r.txHash + }, parseTransactionInfo(r)); +} +function parseRawEvents(raw) { + var _raw$events; + return { + latestLedger: raw.latestLedger, + cursor: raw.cursor, + events: ((_raw$events = raw.events) !== null && _raw$events !== void 0 ? _raw$events : []).map(function (evt) { + var clone = _objectSpread({}, evt); + delete clone.contractId; + return _objectSpread(_objectSpread(_objectSpread({}, clone), evt.contractId !== '' && { + contractId: new _stellarBase.Contract(evt.contractId) + }), {}, { + topic: evt.topic.map(function (topic) { + return _stellarBase.xdr.ScVal.fromXDR(topic, 'base64'); + }), + value: _stellarBase.xdr.ScVal.fromXDR(evt.value, 'base64') + }); + }) + }; +} +function parseRawLedgerEntries(raw) { + var _raw$entries; + return { + latestLedger: raw.latestLedger, + entries: ((_raw$entries = raw.entries) !== null && _raw$entries !== void 0 ? _raw$entries : []).map(function (rawEntry) { + if (!rawEntry.key || !rawEntry.xdr) { + throw new TypeError("invalid ledger entry: ".concat(JSON.stringify(rawEntry))); + } + return _objectSpread({ + lastModifiedLedgerSeq: rawEntry.lastModifiedLedgerSeq, + key: _stellarBase.xdr.LedgerKey.fromXDR(rawEntry.key, 'base64'), + val: _stellarBase.xdr.LedgerEntryData.fromXDR(rawEntry.xdr, 'base64') + }, rawEntry.liveUntilLedgerSeq !== undefined && { + liveUntilLedgerSeq: rawEntry.liveUntilLedgerSeq + }); + }) + }; +} +function parseSuccessful(sim, partial) { + var _sim$results$length, _sim$results, _sim$stateChanges$len, _sim$stateChanges, _sim$stateChanges2; + var success = _objectSpread(_objectSpread(_objectSpread({}, partial), {}, { + transactionData: new _stellarBase.SorobanDataBuilder(sim.transactionData), + minResourceFee: sim.minResourceFee + }, ((_sim$results$length = (_sim$results = sim.results) === null || _sim$results === void 0 ? void 0 : _sim$results.length) !== null && _sim$results$length !== void 0 ? _sim$results$length : 0 > 0) && { + result: sim.results.map(function (row) { + var _row$auth; + return { + auth: ((_row$auth = row.auth) !== null && _row$auth !== void 0 ? _row$auth : []).map(function (entry) { + return _stellarBase.xdr.SorobanAuthorizationEntry.fromXDR(entry, 'base64'); + }), + retval: row.xdr ? _stellarBase.xdr.ScVal.fromXDR(row.xdr, 'base64') : _stellarBase.xdr.ScVal.scvVoid() + }; + })[0] + }), ((_sim$stateChanges$len = (_sim$stateChanges = sim.stateChanges) === null || _sim$stateChanges === void 0 ? void 0 : _sim$stateChanges.length) !== null && _sim$stateChanges$len !== void 0 ? _sim$stateChanges$len : 0 > 0) && { + stateChanges: (_sim$stateChanges2 = sim.stateChanges) === null || _sim$stateChanges2 === void 0 ? void 0 : _sim$stateChanges2.map(function (entryChange) { + return { + type: entryChange.type, + key: _stellarBase.xdr.LedgerKey.fromXDR(entryChange.key, 'base64'), + before: entryChange.before ? _stellarBase.xdr.LedgerEntry.fromXDR(entryChange.before, 'base64') : null, + after: entryChange.after ? _stellarBase.xdr.LedgerEntry.fromXDR(entryChange.after, 'base64') : null + }; + }) + }); + if (!sim.restorePreamble || sim.restorePreamble.transactionData === '') { + return success; + } + return _objectSpread(_objectSpread({}, success), {}, { + restorePreamble: { + minResourceFee: sim.restorePreamble.minResourceFee, + transactionData: new _stellarBase.SorobanDataBuilder(sim.restorePreamble.transactionData) + } + }); +} +function parseRawSimulation(sim) { + var _sim$events$map, _sim$events; + var looksRaw = _api.Api.isSimulationRaw(sim); + if (!looksRaw) { + return sim; + } + var base = { + _parsed: true, + id: sim.id, + latestLedger: sim.latestLedger, + events: (_sim$events$map = (_sim$events = sim.events) === null || _sim$events === void 0 ? void 0 : _sim$events.map(function (evt) { + return _stellarBase.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + })) !== null && _sim$events$map !== void 0 ? _sim$events$map : [] + }; + if (typeof sim.error === 'string') { + return _objectSpread(_objectSpread({}, base), {}, { + error: sim.error + }); + } + return parseSuccessful(sim, base); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/server.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/server.d.ts new file mode 100644 index 000000000..7b90f345d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/server.d.ts @@ -0,0 +1,622 @@ +import URI from 'urijs'; +import { Account, Address, Asset, Contract, FeeBumpTransaction, Transaction, xdr } from '@stellar/stellar-base'; +import { Api } from './api'; +/** + * Default transaction submission timeout for RPC requests, in milliseconds + * @constant {number} + * @default 60000 + * @memberof module:rpc.Server + */ +export declare const SUBMIT_TRANSACTION_TIMEOUT: number; +/** + * Specifies the durability namespace of contract-related ledger entries. + * @enum {('temporary' | 'persistent')} + * @memberof module:rpc + * + * @see {@link https://developers.stellar.org/docs/learn/smart-contract-internals/state-archival | State Archival docs} + * @see {@link https://docs.rs/soroban-sdk/latest/soroban_sdk/storage/struct.Storage.html | Rust SDK Storage docs} + */ +export declare enum Durability { + Temporary = "temporary", + Persistent = "persistent" +} +/** + * @typedef {object} GetEventsRequest Describes the complex filter combinations available for event queries. + * @property {Array.} filters Filters to use when querying events from the RPC server. + * @property {number} [startLedger] Ledger number (inclusive) to begin querying events. + * @property {string} [cursor] Page cursor (exclusive) to begin querying events. + * @property {number} [limit=100] The maximum number of events that should be returned in the RPC response. + * @memberof module:rpc.Server + */ +/** + * @typedef {object} ResourceLeeway Describes additional resource leeways for transaction simulation. + * @property {number} cpuInstructions Simulate the transaction with more CPU instructions available. + * @memberof module:rpc.Server + */ +/** + * @typedef {object} Options Options for configuring connections to RPC servers. + * @property {boolean} [allowHttp=false] Allow connecting to http servers, default: `false`. This must be set to false in production deployments! + * @property {number} [timeout=0] Allow a timeout, default: 0. Allows user to avoid nasty lag. You can also use {@link Config} class to set this globally. + * @property {Record} [headers] Additional headers that should be added to any requests to the RPC server. + * @memberof module:rpc.Server + */ +export declare namespace RpcServer { + interface GetEventsRequest { + filters: Api.EventFilter[]; + startLedger?: number; + endLedger?: number; + cursor?: string; + limit?: number; + } + interface PollingOptions { + attempts?: number; + sleepStrategy?: SleepStrategy; + } + interface ResourceLeeway { + cpuInstructions: number; + } + interface Options { + allowHttp?: boolean; + timeout?: number; + headers?: Record; + } +} +export declare const BasicSleepStrategy: SleepStrategy; +export declare const LinearSleepStrategy: SleepStrategy; +/** + * A function that returns the number of *milliseconds* to sleep + * on a given `iter`ation. + */ +export type SleepStrategy = (iter: number) => number; +/** + * Handles the network connection to a Soroban RPC instance, exposing an + * interface for requests to that instance. + * + * @alias module:rpc.Server + * @memberof module:rpc + * + * @param {string} serverURL Soroban-RPC Server URL (ex. `http://localhost:8000/soroban/rpc`). + * @param {module:rpc.Server.Options} [opts] Options object + * @param {boolean} [opts.allowHttp] Allows connecting to insecure http servers + * (default: `false`). This must be set to false in production deployments! + * You can also use {@link Config} class to set this globally. + * @param {Record} [opts.headers] Allows setting custom headers + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods | API reference docs} + */ +export declare class RpcServer { + readonly serverURL: URI; + constructor(serverURL: string, opts?: RpcServer.Options); + /** + * Fetch a minimal set of current info about a Stellar account. + * + * Needed to get the current sequence number for the account so you can build + * a successful transaction with {@link TransactionBuilder}. + * + * @param {string} address The public address of the account to load. + * @returns {Promise} A promise which resolves to the {@link Account} + * object with a populated sequence number + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs} + * + * @example + * const accountId = "GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4"; + * server.getAccount(accountId).then((account) => { + * console.log("sequence:", account.sequence); + * }); + */ + getAccount(address: string): Promise; + /** + * General node health check. + * + * @returns {Promise} A promise which resolves to the + * {@link Api.GetHealthResponse} object with the status of the + * server (e.g. "healthy"). + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getHealth | getLedgerEntries docs} + * + * @example + * server.getHealth().then((health) => { + * console.log("status:", health.status); + * }); + */ + getHealth(): Promise; + /** + * Reads the current value of contract data ledger entries directly. + * + * Allows you to directly inspect the current state of a contract. This is a + * backup way to access your contract data which may not be available via + * events or {@link module:rpc.Server#simulateTransaction}. + * + * @param {string|Address|Contract} contract The contract ID containing the + * data to load as a strkey (`C...` form), a {@link Contract}, or an + * {@link Address} instance + * @param {xdr.ScVal} key The key of the contract data to load + * @param {module:rpc.Durability} [durability=Durability.Persistent] The "durability + * keyspace" that this ledger key belongs to, which is either 'temporary' + * or 'persistent' (the default), see {@link module:rpc.Durability}. + * @returns {Promise} The current data value + * + * @warning If the data entry in question is a 'temporary' entry, it's + * entirely possible that it has expired out of existence. + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs} + * + * @example + * const contractId = "CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5"; + * const key = xdr.ScVal.scvSymbol("counter"); + * server.getContractData(contractId, key, Durability.Temporary).then(data => { + * console.log("value:", data.val); + * console.log("liveUntilLedgerSeq:", data.liveUntilLedgerSeq); + * console.log("lastModified:", data.lastModifiedLedgerSeq); + * console.log("latestLedger:", data.latestLedger); + * }); + */ + getContractData(contract: string | Address | Contract, key: xdr.ScVal, durability?: Durability): Promise; + /** + * Retrieves the WASM bytecode for a given contract. + * + * This method allows you to fetch the WASM bytecode associated with a contract + * deployed on the Soroban network. The WASM bytecode represents the executable + * code of the contract. + * + * @param {string} contractId The contract ID containing the WASM bytecode to retrieve + * @returns {Promise} A Buffer containing the WASM bytecode + * @throws {Error} If the contract or its associated WASM bytecode cannot be + * found on the network. + * + * @example + * const contractId = "CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5"; + * server.getContractWasmByContractId(contractId).then(wasmBuffer => { + * console.log("WASM bytecode length:", wasmBuffer.length); + * // ... do something with the WASM bytecode ... + * }).catch(err => { + * console.error("Error fetching WASM bytecode:", err); + * }); + */ + getContractWasmByContractId(contractId: string): Promise; + /** + * Retrieves the WASM bytecode for a given contract hash. + * + * This method allows you to fetch the WASM bytecode associated with a contract + * deployed on the Soroban network using the contract's WASM hash. The WASM bytecode + * represents the executable code of the contract. + * + * @param {Buffer} wasmHash The WASM hash of the contract + * @returns {Promise} A Buffer containing the WASM bytecode + * @throws {Error} If the contract or its associated WASM bytecode cannot be + * found on the network. + * + * @example + * const wasmHash = Buffer.from("..."); + * server.getContractWasmByHash(wasmHash).then(wasmBuffer => { + * console.log("WASM bytecode length:", wasmBuffer.length); + * // ... do something with the WASM bytecode ... + * }).catch(err => { + * console.error("Error fetching WASM bytecode:", err); + * }); + */ + getContractWasmByHash(wasmHash: Buffer | string, format?: undefined | "hex" | "base64"): Promise; + /** + * Reads the current value of arbitrary ledger entries directly. + * + * Allows you to directly inspect the current state of contracts, contract's + * code, accounts, or any other ledger entries. + * + * To fetch a contract's WASM byte-code, built the appropriate + * {@link xdr.LedgerKeyContractCode} ledger entry key (or see + * {@link Contract.getFootprint}). + * + * @param {xdr.ScVal[]} keys One or more ledger entry keys to load + * @returns {Promise} The current on-chain + * values for the given ledger keys + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs} + * @see RpcServer._getLedgerEntries + * @example + * const contractId = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM"; + * const key = xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({ + * contractId: StrKey.decodeContract(contractId), + * key: xdr.ScVal.scvSymbol("counter"), + * })); + * + * server.getLedgerEntries([key]).then(response => { + * const ledgerData = response.entries[0]; + * console.log("key:", ledgerData.key); + * console.log("value:", ledgerData.val); + * console.log("liveUntilLedgerSeq:", ledgerData.liveUntilLedgerSeq); + * console.log("lastModified:", ledgerData.lastModifiedLedgerSeq); + * console.log("latestLedger:", response.latestLedger); + * }); + */ + getLedgerEntries(...keys: xdr.LedgerKey[]): Promise; + _getLedgerEntries(...keys: xdr.LedgerKey[]): Promise; + /** + * Poll for a particular transaction with certain parameters. + * + * After submitting a transaction, clients can use this to poll for + * transaction completion and return a definitive state of success or failure. + * + * @param {string} hash the transaction you're polling for + * @param {number} [opts.attempts] (optional) the number of attempts to make + * before returning the last-seen status. By default or on invalid inputs, + * try 5 times. + * @param {SleepStrategy} [opts.sleepStrategy] (optional) the amount of time + * to wait for between each attempt. By default, sleep for 1 second between + * each attempt. + * + * @return {Promise} the response after a "found" + * response (which may be success or failure) or the last response obtained + * after polling the maximum number of specified attempts. + * + * @example + * const h = "c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a"; + * const txStatus = await server.pollTransaction(h, { + * attempts: 100, // I'm a maniac + * sleepStrategy: rpc.LinearSleepStrategy + * }); // this will take 5,050 seconds to complete + */ + pollTransaction(hash: string, opts?: RpcServer.PollingOptions): Promise; + /** + * Fetch the details of a submitted transaction. + * + * After submitting a transaction, clients should poll this to tell when the + * transaction has completed. + * + * @param {string} hash Hex-encoded hash of the transaction to check + * @returns {Promise} The status, result, and + * other details about the transaction + * + * @see + * {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransaction | getTransaction docs} + * + * @example + * const transactionHash = "c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a"; + * server.getTransaction(transactionHash).then((tx) => { + * console.log("status:", tx.status); + * console.log("envelopeXdr:", tx.envelopeXdr); + * console.log("resultMetaXdr:", tx.resultMetaXdr); + * console.log("resultXdr:", tx.resultXdr); + * }); + */ + getTransaction(hash: string): Promise; + _getTransaction(hash: string): Promise; + /** + * Fetch transactions starting from a given start ledger or a cursor. The end ledger is the latest ledger + * in that RPC instance. + * + * @param {Api.GetTransactionsRequest} request - The request parameters. + * @returns {Promise} - A promise that resolves to the transactions response. + * + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransactions + * @example + * server.getTransactions({ + * startLedger: 10000, + * limit: 10, + * }).then((response) => { + * console.log("Transactions:", response.transactions); + * console.log("Latest Ledger:", response.latestLedger); + * console.log("Cursor:", response.cursor); + * }); + */ + getTransactions(request: Api.GetTransactionsRequest): Promise; + private _getTransactions; + /** + * Fetch all events that match a given set of filters. + * + * The given filters (see {@link module:rpc.Api.EventFilter | Api.EventFilter} + * for detailed fields) are combined only in a logical OR fashion, and all of + * the fields in each filter are optional. + * + * To page through events, use the `pagingToken` field on the relevant + * {@link Api.EventResponse} object to set the `cursor` parameter. + * + * @param {module:rpc.Server.GetEventsRequest} request Event filters + * @returns {Promise} A paginatable set of the events + * matching the given event filters + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getEvents | getEvents docs} + * + * @example + * server.getEvents({ + * startLedger: 1000, + * endLedger: 2000, + * filters: [ + * { + * type: "contract", + * contractIds: [ "deadb33f..." ], + * topics: [[ "AAAABQAAAAh0cmFuc2Zlcg==", "AAAAAQB6Mcc=", "*" ]] + * }, { + * type: "system", + * contractIds: [ "...c4f3b4b3..." ], + * topics: [[ "*" ], [ "*", "AAAAAQB6Mcc=" ]] + * }, { + * contractIds: [ "...c4f3b4b3..." ], + * topics: [[ "AAAABQAAAAh0cmFuc2Zlcg==" ]] + * }, { + * type: "diagnostic", + * topics: [[ "AAAAAQB6Mcc=" ]] + * } + * ], + * limit: 10, + * }); + */ + getEvents(request: RpcServer.GetEventsRequest): Promise; + _getEvents(request: RpcServer.GetEventsRequest): Promise; + /** + * Fetch metadata about the network this Soroban RPC server is connected to. + * + * @returns {Promise} Metadata about the current + * network this RPC server is connected to + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getNetwork | getNetwork docs} + * + * @example + * server.getNetwork().then((network) => { + * console.log("friendbotUrl:", network.friendbotUrl); + * console.log("passphrase:", network.passphrase); + * console.log("protocolVersion:", network.protocolVersion); + * }); + */ + getNetwork(): Promise; + /** + * Fetch the latest ledger meta info from network which this Soroban RPC + * server is connected to. + * + * @returns {Promise} metadata about the + * latest ledger on the network that this RPC server is connected to + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLatestLedger | getLatestLedger docs} + * + * @example + * server.getLatestLedger().then((response) => { + * console.log("hash:", response.id); + * console.log("sequence:", response.sequence); + * console.log("protocolVersion:", response.protocolVersion); + * }); + */ + getLatestLedger(): Promise; + /** + * Submit a trial contract invocation to get back return values, expected + * ledger footprint, expected authorizations, and expected costs. + * + * @param {Transaction | FeeBumpTransaction} tx the transaction to + * simulate, which should include exactly one operation (one of + * {@link xdr.InvokeHostFunctionOp}, {@link xdr.ExtendFootprintTTLOp}, or + * {@link xdr.RestoreFootprintOp}). Any provided footprint or auth + * information will be ignored. + * @returns {Promise} An object with the + * cost, footprint, result/auth requirements (if applicable), and error of + * the transaction + * + * @see {@link https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/operations-and-transactions | transaction docs} + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction | simulateTransaction docs} + * @see module:rpc.Server#prepareTransaction + * @see module:rpc.assembleTransaction + * + * @example + * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE'; + * const contract = new StellarSdk.Contract(contractId); + * + * // Right now, this is just the default fee for this example. + * const fee = StellarSdk.BASE_FEE; + * const transaction = new StellarSdk.TransactionBuilder(account, { fee }) + * // Uncomment the following line to build transactions for the live network. Be + * // sure to also change the horizon hostname. + * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC) + * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET) + * .setTimeout(30) // valid for the next 30s + * // Add an operation to call increment() on the contract + * .addOperation(contract.call("increment")) + * .build(); + * + * server.simulateTransaction(transaction).then((sim) => { + * console.log("cost:", sim.cost); + * console.log("result:", sim.result); + * console.log("error:", sim.error); + * console.log("latestLedger:", sim.latestLedger); + * }); + */ + simulateTransaction(tx: Transaction | FeeBumpTransaction, addlResources?: RpcServer.ResourceLeeway): Promise; + _simulateTransaction(transaction: Transaction | FeeBumpTransaction, addlResources?: RpcServer.ResourceLeeway): Promise; + /** + * Submit a trial contract invocation, first run a simulation of the contract + * invocation as defined on the incoming transaction, and apply the results to + * a new copy of the transaction which is then returned. Setting the ledger + * footprint and authorization, so the resulting transaction is ready for + * signing & sending. + * + * The returned transaction will also have an updated fee that is the sum of + * fee set on incoming transaction with the contract resource fees estimated + * from simulation. It is advisable to check the fee on returned transaction + * and validate or take appropriate measures for interaction with user to + * confirm it is acceptable. + * + * You can call the {@link module:rpc.Server#simulateTransaction} method + * directly first if you want to inspect estimated fees for a given + * transaction in detail first, then re-assemble it manually or via + * {@link module:rpc.assembleTransaction}. + * + * @param {Transaction | FeeBumpTransaction} tx the transaction to + * prepare. It should include exactly one operation, which must be one of + * {@link xdr.InvokeHostFunctionOp}, {@link xdr.ExtendFootprintTTLOp}, + * or {@link xdr.RestoreFootprintOp}. + * + * Any provided footprint will be overwritten. However, if your operation + * has existing auth entries, they will be preferred over ALL auth entries + * from the simulation. In other words, if you include auth entries, you + * don't care about the auth returned from the simulation. Other fields + * (footprint, etc.) will be filled as normal. + * @returns {Promise} A copy of the + * transaction with the expected authorizations (in the case of + * invocation), resources, and ledger footprints added. The transaction fee + * will also automatically be padded with the contract's minimum resource + * fees discovered from the simulation. + * @throws {jsonrpc.Error|Error|Api.SimulateTransactionErrorResponse} + * If simulation fails + * + * @see module:rpc.assembleTransaction + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction | simulateTransaction docs} + * + * @example + * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE'; + * const contract = new StellarSdk.Contract(contractId); + * + * // Right now, this is just the default fee for this example. + * const fee = StellarSdk.BASE_FEE; + * const transaction = new StellarSdk.TransactionBuilder(account, { fee }) + * // Uncomment the following line to build transactions for the live network. Be + * // sure to also change the horizon hostname. + * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC) + * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET) + * .setTimeout(30) // valid for the next 30s + * // Add an operation to call increment() on the contract + * .addOperation(contract.call("increment")) + * .build(); + * + * const preparedTransaction = await server.prepareTransaction(transaction); + * + * // Sign this transaction with the secret key + * // NOTE: signing is transaction is network specific. Test network transactions + * // won't work in the public network. To switch networks, use the Network object + * // as explained above (look for StellarSdk.Network). + * const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey); + * preparedTransaction.sign(sourceKeypair); + * + * server.sendTransaction(transaction).then(result => { + * console.log("hash:", result.hash); + * console.log("status:", result.status); + * console.log("errorResultXdr:", result.errorResultXdr); + * }); + */ + prepareTransaction(tx: Transaction | FeeBumpTransaction): Promise, import("@stellar/stellar-base").Operation[]>>; + /** + * Submit a real transaction to the Stellar network. + * + * Unlike Horizon, Soroban RPC does not wait for transaction completion. It + * simply validates the transaction and enqueues it. Clients should call + * {@link module:rpc.Server#getTransaction} to learn about transaction + * success/failure. + * + * @param {Transaction | FeeBumpTransaction} transaction to submit + * @returns {Promise} the + * transaction id, status, and any error if available + * + * @see {@link https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/operations-and-transactions | transaction docs} + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/sendTransaction | sendTransaction docs} + * + * @example + * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE'; + * const contract = new StellarSdk.Contract(contractId); + * + * // Right now, this is just the default fee for this example. + * const fee = StellarSdk.BASE_FEE; + * const transaction = new StellarSdk.TransactionBuilder(account, { fee }) + * // Uncomment the following line to build transactions for the live network. Be + * // sure to also change the horizon hostname. + * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC) + * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET) + * .setTimeout(30) // valid for the next 30s + * // Add an operation to call increment() on the contract + * .addOperation(contract.call("increment")) + * .build(); + * + * // Sign this transaction with the secret key + * // NOTE: signing is transaction is network specific. Test network transactions + * // won't work in the public network. To switch networks, use the Network object + * // as explained above (look for StellarSdk.Network). + * const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey); + * transaction.sign(sourceKeypair); + * + * server.sendTransaction(transaction).then((result) => { + * console.log("hash:", result.hash); + * console.log("status:", result.status); + * console.log("errorResultXdr:", result.errorResultXdr); + * }); + */ + sendTransaction(transaction: Transaction | FeeBumpTransaction): Promise; + _sendTransaction(transaction: Transaction | FeeBumpTransaction): Promise; + /** + * Fund a new account using the network's Friendbot faucet, if any. + * + * @param {string | Account} address The address or account instance that we + * want to create and fund with Friendbot + * @param {string} [friendbotUrl] Optionally, an explicit address for + * friendbot (by default: this calls the Soroban RPC + * {@link module:rpc.Server#getNetwork | getNetwork} method to try to + * discover this network's Friendbot url). + * @returns {Promise} An {@link Account} object for the created + * account, or the existing account if it's already funded with the + * populated sequence number (note that the account will not be "topped + * off" if it already exists) + * @throws If Friendbot is not configured on this network or request failure + * + * @see {@link https://developers.stellar.org/docs/learn/networks#friendbot | Friendbot docs} + * @see {@link module:Friendbot.Api.Response} + * + * @example + * server + * .requestAirdrop("GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4") + * .then((accountCreated) => { + * console.log("accountCreated:", accountCreated); + * }).catch((error) => { + * console.error("error:", error); + * }); + */ + requestAirdrop(address: string | Pick, friendbotUrl?: string): Promise; + /** + * Provides an analysis of the recent fee stats for regular and smart + * contract operations. + * + * @returns {Promise} the fee stats + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getFeeStats + */ + getFeeStats(): Promise; + /** + * Provides information about the current version details of the Soroban RPC and captive-core + * + * @returns {Promise} the version info + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getVersionInfo + */ + getVersionInfo(): Promise; + /** + * Returns a contract's balance of a particular SAC asset, if any. + * + * This is a convenience wrapper around {@link Server.getLedgerEntries}. + * + * @param {string} contractId the contract ID (string `C...`) whose + * balance of `sac` you want to know + * @param {Asset} sac the built-in SAC token (e.g. `USDC:GABC...`) that + * you are querying from the given `contract`. + * @param {string} [networkPassphrase] optionally, the network passphrase to + * which this token applies. If omitted, a request about network + * information will be made (see {@link getNetwork}), since contract IDs + * for assets are specific to a network. You can refer to {@link Networks} + * for a list of built-in passphrases, e.g., `Networks.TESTNET`. + * + * @returns {Promise}, which will contain the balance + * entry details if and only if the request returned a valid balance ledger + * entry. If it doesn't, the `balanceEntry` field will not exist. + * + * @throws {TypeError} If `contractId` is not a valid contract strkey (C...). + * + * @see getLedgerEntries + * @see https://developers.stellar.org/docs/tokens/stellar-asset-contract + * + * @example + * // assume `contractId` is some contract with an XLM balance + * // assume server is an instantiated `Server` instance. + * const entry = (await server.getSACBalance( + * new Address(contractId), + * Asset.native(), + * Networks.PUBLIC + * )); + * + * // assumes BigInt support: + * console.log( + * entry.balanceEntry ? + * BigInt(entry.balanceEntry.amount) : + * "Contract has no XLM"); + */ + getSACBalance(contractId: string, sac: Asset, networkPassphrase?: string): Promise; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/server.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/server.js new file mode 100644 index 000000000..b7b367d32 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/server.js @@ -0,0 +1,896 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SUBMIT_TRANSACTION_TIMEOUT = exports.RpcServer = exports.LinearSleepStrategy = exports.Durability = exports.BasicSleepStrategy = void 0; +var _urijs = _interopRequireDefault(require("urijs")); +var _stellarBase = require("@stellar/stellar-base"); +var _axios = _interopRequireDefault(require("./axios")); +var jsonrpc = _interopRequireWildcard(require("./jsonrpc")); +var _api = require("./api"); +var _transaction = require("./transaction"); +var _parsers = require("./parsers"); +var _utils = require("../utils"); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var SUBMIT_TRANSACTION_TIMEOUT = exports.SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000; +var Durability = exports.Durability = function (Durability) { + Durability["Temporary"] = "temporary"; + Durability["Persistent"] = "persistent"; + return Durability; +}({}); +var DEFAULT_GET_TRANSACTION_TIMEOUT = 30; +var BasicSleepStrategy = exports.BasicSleepStrategy = function BasicSleepStrategy(_iter) { + return 1000; +}; +var LinearSleepStrategy = exports.LinearSleepStrategy = function LinearSleepStrategy(iter) { + return 1000 * iter; +}; +function findCreatedAccountSequenceInTransactionMeta(meta) { + var _operations$flatMap$f; + var operations = []; + switch (meta.switch()) { + case 0: + operations = meta.operations(); + break; + case 1: + case 2: + case 3: + operations = meta.value().operations(); + break; + default: + throw new Error('Unexpected transaction meta switch value'); + } + var sequenceNumber = (_operations$flatMap$f = operations.flatMap(function (op) { + return op.changes(); + }).find(function (c) { + return c.switch() === _stellarBase.xdr.LedgerEntryChangeType.ledgerEntryCreated() && c.created().data().switch() === _stellarBase.xdr.LedgerEntryType.account(); + })) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.created()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.data()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.account()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.seqNum()) === null || _operations$flatMap$f === void 0 ? void 0 : _operations$flatMap$f.toString(); + if (sequenceNumber) { + return sequenceNumber; + } + throw new Error('No account created in transaction'); +} +var RpcServer = exports.RpcServer = function () { + function RpcServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, RpcServer); + this.serverURL = (0, _urijs.default)(serverURL); + if (opts.headers && Object.keys(opts.headers).length !== 0) { + _axios.default.interceptors.request.use(function (config) { + config.headers = Object.assign(config.headers, opts.headers); + return config; + }); + } + if (this.serverURL.protocol() !== 'https' && !opts.allowHttp) { + throw new Error("Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set"); + } + } + return _createClass(RpcServer, [{ + key: "getAccount", + value: (function () { + var _getAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(address) { + var ledgerKey, resp, accountEntry; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + ledgerKey = _stellarBase.xdr.LedgerKey.account(new _stellarBase.xdr.LedgerKeyAccount({ + accountId: _stellarBase.Keypair.fromPublicKey(address).xdrPublicKey() + })); + _context.next = 3; + return this.getLedgerEntries(ledgerKey); + case 3: + resp = _context.sent; + if (!(resp.entries.length === 0)) { + _context.next = 6; + break; + } + return _context.abrupt("return", Promise.reject({ + code: 404, + message: "Account not found: ".concat(address) + })); + case 6: + accountEntry = resp.entries[0].val.account(); + return _context.abrupt("return", new _stellarBase.Account(address, accountEntry.seqNum().toString())); + case 8: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function getAccount(_x) { + return _getAccount.apply(this, arguments); + } + return getAccount; + }()) + }, { + key: "getHealth", + value: (function () { + var _getHealth = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getHealth')); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function getHealth() { + return _getHealth.apply(this, arguments); + } + return getHealth; + }()) + }, { + key: "getContractData", + value: (function () { + var _getContractData = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(contract, key) { + var durability, + scAddress, + xdrDurability, + contractKey, + _args3 = arguments; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + durability = _args3.length > 2 && _args3[2] !== undefined ? _args3[2] : Durability.Persistent; + if (!(typeof contract === 'string')) { + _context3.next = 5; + break; + } + scAddress = new _stellarBase.Contract(contract).address().toScAddress(); + _context3.next = 14; + break; + case 5: + if (!(contract instanceof _stellarBase.Address)) { + _context3.next = 9; + break; + } + scAddress = contract.toScAddress(); + _context3.next = 14; + break; + case 9: + if (!(contract instanceof _stellarBase.Contract)) { + _context3.next = 13; + break; + } + scAddress = contract.address().toScAddress(); + _context3.next = 14; + break; + case 13: + throw new TypeError("unknown contract type: ".concat(contract)); + case 14: + _context3.t0 = durability; + _context3.next = _context3.t0 === Durability.Temporary ? 17 : _context3.t0 === Durability.Persistent ? 19 : 21; + break; + case 17: + xdrDurability = _stellarBase.xdr.ContractDataDurability.temporary(); + return _context3.abrupt("break", 22); + case 19: + xdrDurability = _stellarBase.xdr.ContractDataDurability.persistent(); + return _context3.abrupt("break", 22); + case 21: + throw new TypeError("invalid durability: ".concat(durability)); + case 22: + contractKey = _stellarBase.xdr.LedgerKey.contractData(new _stellarBase.xdr.LedgerKeyContractData({ + key: key, + contract: scAddress, + durability: xdrDurability + })); + return _context3.abrupt("return", this.getLedgerEntries(contractKey).then(function (r) { + if (r.entries.length === 0) { + return Promise.reject({ + code: 404, + message: "Contract data not found. Contract: ".concat(_stellarBase.Address.fromScAddress(scAddress).toString(), ", Key: ").concat(key.toXDR('base64'), ", Durability: ").concat(durability) + }); + } + return r.entries[0]; + })); + case 24: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function getContractData(_x2, _x3) { + return _getContractData.apply(this, arguments); + } + return getContractData; + }()) + }, { + key: "getContractWasmByContractId", + value: (function () { + var _getContractWasmByContractId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(contractId) { + var _response$entries$; + var contractLedgerKey, response, wasmHash; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + contractLedgerKey = new _stellarBase.Contract(contractId).getFootprint(); + _context4.next = 3; + return this.getLedgerEntries(contractLedgerKey); + case 3: + response = _context4.sent; + if (!(!response.entries.length || !((_response$entries$ = response.entries[0]) !== null && _response$entries$ !== void 0 && _response$entries$.val))) { + _context4.next = 6; + break; + } + return _context4.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract hash from server" + })); + case 6: + wasmHash = response.entries[0].val.contractData().val().instance().executable().wasmHash(); + return _context4.abrupt("return", this.getContractWasmByHash(wasmHash)); + case 8: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function getContractWasmByContractId(_x4) { + return _getContractWasmByContractId.apply(this, arguments); + } + return getContractWasmByContractId; + }()) + }, { + key: "getContractWasmByHash", + value: (function () { + var _getContractWasmByHash = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(wasmHash) { + var _responseWasm$entries; + var format, + wasmHashBuffer, + ledgerKeyWasmHash, + responseWasm, + wasmBuffer, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + format = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : undefined; + wasmHashBuffer = typeof wasmHash === "string" ? Buffer.from(wasmHash, format) : wasmHash; + ledgerKeyWasmHash = _stellarBase.xdr.LedgerKey.contractCode(new _stellarBase.xdr.LedgerKeyContractCode({ + hash: wasmHashBuffer + })); + _context5.next = 5; + return this.getLedgerEntries(ledgerKeyWasmHash); + case 5: + responseWasm = _context5.sent; + if (!(!responseWasm.entries.length || !((_responseWasm$entries = responseWasm.entries[0]) !== null && _responseWasm$entries !== void 0 && _responseWasm$entries.val))) { + _context5.next = 8; + break; + } + return _context5.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract wasm from server" + })); + case 8: + wasmBuffer = responseWasm.entries[0].val.contractCode().code(); + return _context5.abrupt("return", wasmBuffer); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function getContractWasmByHash(_x5) { + return _getContractWasmByHash.apply(this, arguments); + } + return getContractWasmByHash; + }()) + }, { + key: "getLedgerEntries", + value: (function () { + var _getLedgerEntries2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6() { + var _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + return _context6.abrupt("return", this._getLedgerEntries.apply(this, _args6).then(_parsers.parseRawLedgerEntries)); + case 1: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function getLedgerEntries() { + return _getLedgerEntries2.apply(this, arguments); + } + return getLedgerEntries; + }()) + }, { + key: "_getLedgerEntries", + value: function () { + var _getLedgerEntries3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee7() { + var _len, + keys, + _key, + _args7 = arguments; + return _regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + for (_len = _args7.length, keys = new Array(_len), _key = 0; _key < _len; _key++) { + keys[_key] = _args7[_key]; + } + return _context7.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getLedgerEntries', { + keys: keys.map(function (k) { + return k.toXDR('base64'); + }) + })); + case 2: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function _getLedgerEntries() { + return _getLedgerEntries3.apply(this, arguments); + } + return _getLedgerEntries; + }() + }, { + key: "pollTransaction", + value: (function () { + var _pollTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee8(hash, opts) { + var _opts$attempts, _opts$attempts2; + var maxAttempts, foundInfo, attempt, _opts$sleepStrategy; + return _regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + maxAttempts = ((_opts$attempts = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts !== void 0 ? _opts$attempts : 0) < 1 ? DEFAULT_GET_TRANSACTION_TIMEOUT : (_opts$attempts2 = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts2 !== void 0 ? _opts$attempts2 : DEFAULT_GET_TRANSACTION_TIMEOUT; + attempt = 1; + case 2: + if (!(attempt < maxAttempts)) { + _context8.next = 13; + break; + } + _context8.next = 5; + return this.getTransaction(hash); + case 5: + foundInfo = _context8.sent; + if (!(foundInfo.status !== _api.Api.GetTransactionStatus.NOT_FOUND)) { + _context8.next = 8; + break; + } + return _context8.abrupt("return", foundInfo); + case 8: + _context8.next = 10; + return _utils.Utils.sleep(((_opts$sleepStrategy = opts === null || opts === void 0 ? void 0 : opts.sleepStrategy) !== null && _opts$sleepStrategy !== void 0 ? _opts$sleepStrategy : BasicSleepStrategy)(attempt)); + case 10: + attempt++; + _context8.next = 2; + break; + case 13: + return _context8.abrupt("return", foundInfo); + case 14: + case "end": + return _context8.stop(); + } + }, _callee8, this); + })); + function pollTransaction(_x6, _x7) { + return _pollTransaction.apply(this, arguments); + } + return pollTransaction; + }()) + }, { + key: "getTransaction", + value: (function () { + var _getTransaction2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee9(hash) { + return _regeneratorRuntime().wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + return _context9.abrupt("return", this._getTransaction(hash).then(function (raw) { + var foundInfo = {}; + if (raw.status !== _api.Api.GetTransactionStatus.NOT_FOUND) { + Object.assign(foundInfo, (0, _parsers.parseTransactionInfo)(raw)); + } + var result = _objectSpread({ + status: raw.status, + txHash: hash, + latestLedger: raw.latestLedger, + latestLedgerCloseTime: raw.latestLedgerCloseTime, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTime: raw.oldestLedgerCloseTime + }, foundInfo); + return result; + })); + case 1: + case "end": + return _context9.stop(); + } + }, _callee9, this); + })); + function getTransaction(_x8) { + return _getTransaction2.apply(this, arguments); + } + return getTransaction; + }()) + }, { + key: "_getTransaction", + value: function () { + var _getTransaction3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee10(hash) { + return _regeneratorRuntime().wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + return _context10.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getTransaction', { + hash: hash + })); + case 1: + case "end": + return _context10.stop(); + } + }, _callee10, this); + })); + function _getTransaction(_x9) { + return _getTransaction3.apply(this, arguments); + } + return _getTransaction; + }() + }, { + key: "getTransactions", + value: (function () { + var _getTransactions2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee11(request) { + return _regeneratorRuntime().wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + return _context11.abrupt("return", this._getTransactions(request).then(function (raw) { + var result = { + transactions: raw.transactions.map(_parsers.parseRawTransactions), + latestLedger: raw.latestLedger, + latestLedgerCloseTimestamp: raw.latestLedgerCloseTimestamp, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTimestamp: raw.oldestLedgerCloseTimestamp, + cursor: raw.cursor + }; + return result; + })); + case 1: + case "end": + return _context11.stop(); + } + }, _callee11, this); + })); + function getTransactions(_x10) { + return _getTransactions2.apply(this, arguments); + } + return getTransactions; + }()) + }, { + key: "_getTransactions", + value: function () { + var _getTransactions3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee12(request) { + return _regeneratorRuntime().wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + return _context12.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getTransactions', request)); + case 1: + case "end": + return _context12.stop(); + } + }, _callee12, this); + })); + function _getTransactions(_x11) { + return _getTransactions3.apply(this, arguments); + } + return _getTransactions; + }() + }, { + key: "getEvents", + value: (function () { + var _getEvents2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee13(request) { + return _regeneratorRuntime().wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + return _context13.abrupt("return", this._getEvents(request).then(_parsers.parseRawEvents)); + case 1: + case "end": + return _context13.stop(); + } + }, _callee13, this); + })); + function getEvents(_x12) { + return _getEvents2.apply(this, arguments); + } + return getEvents; + }()) + }, { + key: "_getEvents", + value: function () { + var _getEvents3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee14(request) { + var _request$filters; + return _regeneratorRuntime().wrap(function _callee14$(_context14) { + while (1) switch (_context14.prev = _context14.next) { + case 0: + return _context14.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getEvents', _objectSpread(_objectSpread({ + filters: (_request$filters = request.filters) !== null && _request$filters !== void 0 ? _request$filters : [], + pagination: _objectSpread(_objectSpread({}, request.cursor && { + cursor: request.cursor + }), request.limit && { + limit: request.limit + }) + }, request.startLedger && { + startLedger: request.startLedger + }), request.endLedger && { + endLedger: request.endLedger + }))); + case 1: + case "end": + return _context14.stop(); + } + }, _callee14, this); + })); + function _getEvents(_x13) { + return _getEvents3.apply(this, arguments); + } + return _getEvents; + }() + }, { + key: "getNetwork", + value: (function () { + var _getNetwork = _asyncToGenerator(_regeneratorRuntime().mark(function _callee15() { + return _regeneratorRuntime().wrap(function _callee15$(_context15) { + while (1) switch (_context15.prev = _context15.next) { + case 0: + return _context15.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getNetwork')); + case 1: + case "end": + return _context15.stop(); + } + }, _callee15, this); + })); + function getNetwork() { + return _getNetwork.apply(this, arguments); + } + return getNetwork; + }()) + }, { + key: "getLatestLedger", + value: (function () { + var _getLatestLedger = _asyncToGenerator(_regeneratorRuntime().mark(function _callee16() { + return _regeneratorRuntime().wrap(function _callee16$(_context16) { + while (1) switch (_context16.prev = _context16.next) { + case 0: + return _context16.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getLatestLedger')); + case 1: + case "end": + return _context16.stop(); + } + }, _callee16, this); + })); + function getLatestLedger() { + return _getLatestLedger.apply(this, arguments); + } + return getLatestLedger; + }()) + }, { + key: "simulateTransaction", + value: (function () { + var _simulateTransaction2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee17(tx, addlResources) { + return _regeneratorRuntime().wrap(function _callee17$(_context17) { + while (1) switch (_context17.prev = _context17.next) { + case 0: + return _context17.abrupt("return", this._simulateTransaction(tx, addlResources).then(_parsers.parseRawSimulation)); + case 1: + case "end": + return _context17.stop(); + } + }, _callee17, this); + })); + function simulateTransaction(_x14, _x15) { + return _simulateTransaction2.apply(this, arguments); + } + return simulateTransaction; + }()) + }, { + key: "_simulateTransaction", + value: function () { + var _simulateTransaction3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee18(transaction, addlResources) { + return _regeneratorRuntime().wrap(function _callee18$(_context18) { + while (1) switch (_context18.prev = _context18.next) { + case 0: + return _context18.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'simulateTransaction', _objectSpread({ + transaction: transaction.toXDR() + }, addlResources !== undefined && { + resourceConfig: { + instructionLeeway: addlResources.cpuInstructions + } + }))); + case 1: + case "end": + return _context18.stop(); + } + }, _callee18, this); + })); + function _simulateTransaction(_x16, _x17) { + return _simulateTransaction3.apply(this, arguments); + } + return _simulateTransaction; + }() + }, { + key: "prepareTransaction", + value: (function () { + var _prepareTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee19(tx) { + var simResponse; + return _regeneratorRuntime().wrap(function _callee19$(_context19) { + while (1) switch (_context19.prev = _context19.next) { + case 0: + _context19.next = 2; + return this.simulateTransaction(tx); + case 2: + simResponse = _context19.sent; + if (!_api.Api.isSimulationError(simResponse)) { + _context19.next = 5; + break; + } + throw new Error(simResponse.error); + case 5: + return _context19.abrupt("return", (0, _transaction.assembleTransaction)(tx, simResponse).build()); + case 6: + case "end": + return _context19.stop(); + } + }, _callee19, this); + })); + function prepareTransaction(_x18) { + return _prepareTransaction.apply(this, arguments); + } + return prepareTransaction; + }()) + }, { + key: "sendTransaction", + value: (function () { + var _sendTransaction2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee20(transaction) { + return _regeneratorRuntime().wrap(function _callee20$(_context20) { + while (1) switch (_context20.prev = _context20.next) { + case 0: + return _context20.abrupt("return", this._sendTransaction(transaction).then(_parsers.parseRawSendTransaction)); + case 1: + case "end": + return _context20.stop(); + } + }, _callee20, this); + })); + function sendTransaction(_x19) { + return _sendTransaction2.apply(this, arguments); + } + return sendTransaction; + }()) + }, { + key: "_sendTransaction", + value: function () { + var _sendTransaction3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee21(transaction) { + return _regeneratorRuntime().wrap(function _callee21$(_context21) { + while (1) switch (_context21.prev = _context21.next) { + case 0: + return _context21.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'sendTransaction', { + transaction: transaction.toXDR() + })); + case 1: + case "end": + return _context21.stop(); + } + }, _callee21, this); + })); + function _sendTransaction(_x20) { + return _sendTransaction3.apply(this, arguments); + } + return _sendTransaction; + }() + }, { + key: "requestAirdrop", + value: (function () { + var _requestAirdrop = _asyncToGenerator(_regeneratorRuntime().mark(function _callee22(address, friendbotUrl) { + var account, response, meta, txMeta, sequence, _error$response, _error$response$detai; + return _regeneratorRuntime().wrap(function _callee22$(_context22) { + while (1) switch (_context22.prev = _context22.next) { + case 0: + account = typeof address === 'string' ? address : address.accountId(); + _context22.t0 = friendbotUrl; + if (_context22.t0) { + _context22.next = 6; + break; + } + _context22.next = 5; + return this.getNetwork(); + case 5: + _context22.t0 = _context22.sent.friendbotUrl; + case 6: + friendbotUrl = _context22.t0; + if (friendbotUrl) { + _context22.next = 9; + break; + } + throw new Error('No friendbot URL configured for current network'); + case 9: + _context22.prev = 9; + _context22.next = 12; + return _axios.default.post("".concat(friendbotUrl, "?addr=").concat(encodeURIComponent(account))); + case 12: + response = _context22.sent; + if (response.data.result_meta_xdr) { + _context22.next = 22; + break; + } + _context22.next = 16; + return this.getTransaction(response.data.hash); + case 16: + txMeta = _context22.sent; + if (!(txMeta.status !== _api.Api.GetTransactionStatus.SUCCESS)) { + _context22.next = 19; + break; + } + throw new Error("Funding account ".concat(address, " failed")); + case 19: + meta = txMeta.resultMetaXdr; + _context22.next = 23; + break; + case 22: + meta = _stellarBase.xdr.TransactionMeta.fromXDR(response.data.result_meta_xdr, 'base64'); + case 23: + sequence = findCreatedAccountSequenceInTransactionMeta(meta); + return _context22.abrupt("return", new _stellarBase.Account(account, sequence)); + case 27: + _context22.prev = 27; + _context22.t1 = _context22["catch"](9); + if (!(((_error$response = _context22.t1.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 400)) { + _context22.next = 32; + break; + } + if (!((_error$response$detai = _context22.t1.response.detail) !== null && _error$response$detai !== void 0 && _error$response$detai.includes('createAccountAlreadyExist'))) { + _context22.next = 32; + break; + } + return _context22.abrupt("return", this.getAccount(account)); + case 32: + throw _context22.t1; + case 33: + case "end": + return _context22.stop(); + } + }, _callee22, this, [[9, 27]]); + })); + function requestAirdrop(_x21, _x22) { + return _requestAirdrop.apply(this, arguments); + } + return requestAirdrop; + }()) + }, { + key: "getFeeStats", + value: (function () { + var _getFeeStats = _asyncToGenerator(_regeneratorRuntime().mark(function _callee23() { + return _regeneratorRuntime().wrap(function _callee23$(_context23) { + while (1) switch (_context23.prev = _context23.next) { + case 0: + return _context23.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getFeeStats')); + case 1: + case "end": + return _context23.stop(); + } + }, _callee23, this); + })); + function getFeeStats() { + return _getFeeStats.apply(this, arguments); + } + return getFeeStats; + }()) + }, { + key: "getVersionInfo", + value: (function () { + var _getVersionInfo = _asyncToGenerator(_regeneratorRuntime().mark(function _callee24() { + return _regeneratorRuntime().wrap(function _callee24$(_context24) { + while (1) switch (_context24.prev = _context24.next) { + case 0: + return _context24.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getVersionInfo')); + case 1: + case "end": + return _context24.stop(); + } + }, _callee24, this); + })); + function getVersionInfo() { + return _getVersionInfo.apply(this, arguments); + } + return getVersionInfo; + }()) + }, { + key: "getSACBalance", + value: (function () { + var _getSACBalance = _asyncToGenerator(_regeneratorRuntime().mark(function _callee25(contractId, sac, networkPassphrase) { + var passphrase, sacId, key, ledgerKey, response, _response$entries$2, lastModifiedLedgerSeq, liveUntilLedgerSeq, val, entry; + return _regeneratorRuntime().wrap(function _callee25$(_context25) { + while (1) switch (_context25.prev = _context25.next) { + case 0: + if (_stellarBase.StrKey.isValidContract(contractId)) { + _context25.next = 2; + break; + } + throw new TypeError("expected contract ID, got ".concat(contractId)); + case 2: + if (!(networkPassphrase !== null && networkPassphrase !== void 0)) { + _context25.next = 6; + break; + } + _context25.t0 = networkPassphrase; + _context25.next = 9; + break; + case 6: + _context25.next = 8; + return this.getNetwork().then(function (n) { + return n.passphrase; + }); + case 8: + _context25.t0 = _context25.sent; + case 9: + passphrase = _context25.t0; + sacId = sac.contractId(passphrase); + key = _stellarBase.xdr.ScVal.scvVec([(0, _stellarBase.nativeToScVal)("Balance", { + type: "symbol" + }), (0, _stellarBase.nativeToScVal)(contractId, { + type: "address" + })]); + ledgerKey = _stellarBase.xdr.LedgerKey.contractData(new _stellarBase.xdr.LedgerKeyContractData({ + contract: new _stellarBase.Address(sacId).toScAddress(), + durability: _stellarBase.xdr.ContractDataDurability.persistent(), + key: key + })); + _context25.next = 15; + return this.getLedgerEntries(ledgerKey); + case 15: + response = _context25.sent; + if (!(response.entries.length === 0)) { + _context25.next = 18; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 18: + _response$entries$2 = response.entries[0], lastModifiedLedgerSeq = _response$entries$2.lastModifiedLedgerSeq, liveUntilLedgerSeq = _response$entries$2.liveUntilLedgerSeq, val = _response$entries$2.val; + if (!(val.switch().value !== _stellarBase.xdr.LedgerEntryType.contractData().value)) { + _context25.next = 21; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 21: + entry = (0, _stellarBase.scValToNative)(val.contractData().val()); + return _context25.abrupt("return", { + latestLedger: response.latestLedger, + balanceEntry: { + liveUntilLedgerSeq: liveUntilLedgerSeq, + lastModifiedLedgerSeq: lastModifiedLedgerSeq, + amount: entry.amount.toString(), + authorized: entry.authorized, + clawback: entry.clawback + } + }); + case 23: + case "end": + return _context25.stop(); + } + }, _callee25, this); + })); + function getSACBalance(_x23, _x24, _x25) { + return _getSACBalance.apply(this, arguments); + } + return getSACBalance; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/transaction.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/transaction.d.ts new file mode 100644 index 000000000..c20ee31ad --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/transaction.d.ts @@ -0,0 +1,21 @@ +import { FeeBumpTransaction, Transaction, TransactionBuilder } from '@stellar/stellar-base'; +import { Api } from './api'; +/** + * Combines the given raw transaction alongside the simulation results. + * If the given transaction already has authorization entries in a host + * function invocation (see {@link Operation.invokeHostFunction}), **the + * simulation entries are ignored**. + * + * If the given transaction already has authorization entries in a host function + * invocation (see {@link Operation.invokeHostFunction}), **the simulation + * entries are ignored**. + * + * @param {Transaction|FeeBumpTransaction} raw the initial transaction, w/o simulation applied + * @param {Api.SimulateTransactionResponse|Api.RawSimulateTransactionResponse} simulation the Soroban RPC simulation result (see {@link module:rpc.Server#simulateTransaction}) + * @returns {TransactionBuilder} a new, cloned transaction with the proper auth and resource (fee, footprint) simulation data applied + * + * @memberof module:rpc + * @see {@link module:rpc.Server#simulateTransaction} + * @see {@link module:rpc.Server#prepareTransaction} + */ +export declare function assembleTransaction(raw: Transaction | FeeBumpTransaction, simulation: Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse): TransactionBuilder; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/transaction.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/transaction.js new file mode 100644 index 000000000..51bc94e7b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/transaction.js @@ -0,0 +1,53 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.assembleTransaction = assembleTransaction; +var _stellarBase = require("@stellar/stellar-base"); +var _api = require("./api"); +var _parsers = require("./parsers"); +function isSorobanTransaction(tx) { + if (tx.operations.length !== 1) { + return false; + } + switch (tx.operations[0].type) { + case 'invokeHostFunction': + case 'extendFootprintTtl': + case 'restoreFootprint': + return true; + default: + return false; + } +} +function assembleTransaction(raw, simulation) { + if ('innerTransaction' in raw) { + return assembleTransaction(raw.innerTransaction, simulation); + } + if (!isSorobanTransaction(raw)) { + throw new TypeError('unsupported transaction: must contain exactly one ' + 'invokeHostFunction, extendFootprintTtl, or restoreFootprint ' + 'operation'); + } + var success = (0, _parsers.parseRawSimulation)(simulation); + if (!_api.Api.isSimulationSuccess(success)) { + throw new Error("simulation incorrect: ".concat(JSON.stringify(success))); + } + var classicFeeNum = parseInt(raw.fee) || 0; + var minResourceFeeNum = parseInt(success.minResourceFee) || 0; + var txnBuilder = _stellarBase.TransactionBuilder.cloneFrom(raw, { + fee: (classicFeeNum + minResourceFeeNum).toString(), + sorobanData: success.transactionData.build(), + networkPassphrase: raw.networkPassphrase + }); + if (raw.operations[0].type === 'invokeHostFunction') { + var _invokeOp$auth; + txnBuilder.clearOperations(); + var invokeOp = raw.operations[0]; + var existingAuth = (_invokeOp$auth = invokeOp.auth) !== null && _invokeOp$auth !== void 0 ? _invokeOp$auth : []; + txnBuilder.addOperation(_stellarBase.Operation.invokeHostFunction({ + source: invokeOp.source, + func: invokeOp.func, + auth: existingAuth.length > 0 ? existingAuth : success.result.auth + })); + } + return txnBuilder; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/utils.d.ts new file mode 100644 index 000000000..e1cc19c4b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/utils.d.ts @@ -0,0 +1 @@ +export declare function hasOwnProperty(obj: X, prop: Y): obj is X & Record; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/utils.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/utils.js new file mode 100644 index 000000000..e2148d9bd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/rpc/utils.js @@ -0,0 +1,9 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.hasOwnProperty = hasOwnProperty; +function hasOwnProperty(obj, prop) { + return obj.hasOwnProperty(prop); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/stellartoml/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/stellartoml/index.d.ts new file mode 100644 index 000000000..9309f1dfd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/stellartoml/index.d.ts @@ -0,0 +1,132 @@ +import { Networks } from "@stellar/stellar-base"; +/** @module StellarToml */ +/** + * The maximum size of stellar.toml file, in bytes + * @constant {number} + * @default 102400 + */ +export declare const STELLAR_TOML_MAX_SIZE: number; +/** + * Resolver allows resolving `stellar.toml` files. + * @memberof module:StellarToml + * @hideconstructor + */ +export declare class Resolver { + /** + * Returns a parsed `stellar.toml` file for a given domain. + * @see {@link https://developers.stellar.org/docs/tokens/publishing-asset-info | Stellar.toml doc} + * + * @param {string} domain Domain to get stellar.toml file for + * @param {object} [opts] Options object + * @param {boolean} [opts.allowHttp=false] - Allow connecting to http servers. This must be set to false in production deployments! + * @param {number} [opts.timeout=0] - Allow a timeout. Allows user to avoid nasty lag due to TOML resolve issue. + * @returns {Promise} A `Promise` that resolves to the parsed stellar.toml object + * + * @example + * StellarSdk.StellarToml.Resolver.resolve('acme.com') + * .then(stellarToml => { + * // stellarToml in an object representing domain stellar.toml file. + * }) + * .catch(error => { + * // stellar.toml does not exist or is invalid + * }); + */ + static resolve(domain: string, opts?: Api.StellarTomlResolveOptions): Promise; +} +export declare namespace Api { + interface StellarTomlResolveOptions { + allowHttp?: boolean; + timeout?: number; + allowedRedirects?: number; + } + type Url = string; + type PublicKey = string; + type ISODateTime = string; + interface Documentation { + ORG_NAME?: string; + ORG_DBA?: string; + ORG_URL?: Url; + ORG_PHONE_NUMBER?: string; + ORG_LOGO?: Url; + ORG_LICENSE_NUMBER?: string; + ORG_LICENSING_AUTHORITY?: string; + ORG_LICENSE_TYPE?: string; + ORG_DESCRIPTION?: string; + ORG_PHYSICAL_ADDRESS?: string; + ORG_PHYSICAL_ADDRESS_ATTESTATION?: string; + ORG_PHONE_NUMBER_ATTESTATION?: string; + ORG_OFFICIAL_EMAIL?: string; + ORG_SUPPORT_EMAIL?: string; + ORG_KEYBASE?: string; + ORG_TWITTER?: string; + ORG_GITHUB?: string; + [key: string]: unknown; + } + interface Principal { + name: string; + email: string; + github?: string; + keybase?: string; + telegram?: string; + twitter?: string; + id_photo_hash?: string; + verification_photo_hash?: string; + [key: string]: unknown; + } + interface Currency { + code?: string; + code_template?: string; + issuer?: PublicKey; + display_decimals?: number; + status?: "live" | "dead" | "test" | "private"; + name?: string; + desc?: string; + conditions?: string; + fixed_number?: number; + max_number?: number; + is_asset_anchored?: boolean; + anchor_asset_type?: "fiat" | "crypto" | "nft" | "stock" | "bond" | "commodity" | "realestate" | "other"; + anchor_asset?: string; + attestation_of_reserve?: Url; + attestation_of_reserve_amount?: string; + attestation_of_reserve_last_audit?: ISODateTime; + is_unlimited?: boolean; + redemption_instructions?: string; + image?: Url; + regulated?: boolean; + collateral_addresses?: string[]; + collateral_address_messages?: string[]; + collateral_address_signatures?: string[]; + approval_server?: Url; + approval_criteria?: string; + [key: string]: unknown; + } + interface Validator { + ALIAS?: string; + DISPLAY_NAME?: string; + PUBLIC_KEY?: PublicKey; + HOST?: string; + HISTORY?: Url; + [key: string]: unknown; + } + interface StellarToml { + VERSION?: string; + ACCOUNTS?: PublicKey[]; + NETWORK_PASSPHRASE?: Networks; + TRANSFER_SERVER_SEP0024?: Url; + TRANSFER_SERVER?: Url; + KYC_SERVER?: Url; + WEB_AUTH_ENDPOINT?: Url; + FEDERATION_SERVER?: Url; + SIGNING_KEY?: PublicKey; + HORIZON_URL?: Url; + URI_REQUEST_SIGNING_KEY?: PublicKey; + DIRECT_PAYMENT_SERVER?: Url; + ANCHOR_QUOTE_SERVER?: Url; + DOCUMENTATION?: Documentation; + PRINCIPALS?: Principal[]; + CURRENCIES?: Currency[]; + VALIDATORS?: Validator[]; + [key: string]: unknown; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/stellartoml/index.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/stellartoml/index.js new file mode 100644 index 000000000..4b5aa2452 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/stellartoml/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.STELLAR_TOML_MAX_SIZE = exports.Resolver = exports.Api = void 0; +var _toml = _interopRequireDefault(require("toml")); +var _httpClient = require("../http-client"); +var _config = require("../config"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var STELLAR_TOML_MAX_SIZE = exports.STELLAR_TOML_MAX_SIZE = 100 * 1024; +var CancelToken = _httpClient.httpClient.CancelToken; +var Resolver = exports.Resolver = function () { + function Resolver() { + _classCallCheck(this, Resolver); + } + return _createClass(Resolver, null, [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(domain) { + var _opts$allowedRedirect; + var opts, + allowHttp, + timeout, + protocol, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 1 && _args[1] !== undefined ? _args[1] : {}; + allowHttp = typeof opts.allowHttp === "undefined" ? _config.Config.isAllowHttp() : opts.allowHttp; + timeout = typeof opts.timeout === "undefined" ? _config.Config.getTimeout() : opts.timeout; + protocol = allowHttp ? "http" : "https"; + return _context.abrupt("return", _httpClient.httpClient.get("".concat(protocol, "://").concat(domain, "/.well-known/stellar.toml"), { + maxRedirects: (_opts$allowedRedirect = opts.allowedRedirects) !== null && _opts$allowedRedirect !== void 0 ? _opts$allowedRedirect : 0, + maxContentLength: STELLAR_TOML_MAX_SIZE, + cancelToken: timeout ? new CancelToken(function (cancel) { + return setTimeout(function () { + return cancel("timeout of ".concat(timeout, "ms exceeded")); + }, timeout); + }) : undefined, + timeout: timeout + }).then(function (response) { + try { + var tomlObject = _toml.default.parse(response.data); + return Promise.resolve(tomlObject); + } catch (e) { + return Promise.reject(new Error("stellar.toml is invalid - Parsing error on line ".concat(e.line, ", column ").concat(e.column, ": ").concat(e.message))); + } + }).catch(function (err) { + if (err.message.match(/^maxContentLength size/)) { + throw new Error("stellar.toml file exceeds allowed size of ".concat(STELLAR_TOML_MAX_SIZE)); + } else { + throw err; + } + })); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + function resolve(_x) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }]); +}(); +var Api; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/utils.d.ts new file mode 100644 index 000000000..68cf6c0c2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/utils.d.ts @@ -0,0 +1,20 @@ +import { Transaction } from "@stellar/stellar-base"; +/** + * Miscellaneous utilities. + * + * @hideconstructor + */ +export declare class Utils { + /** + * Verifies if the current date is within the transaction's timebounds + * + * @param {Transaction} transaction The transaction whose timebounds will be validated. + * @param {number} [gracePeriod=0] An additional window of time that should be considered valid on either end of the transaction's time range. + * + * @returns {boolean} Returns true if the current time is within the transaction's [minTime, maxTime] range. + * + * @static + */ + static validateTimebounds(transaction: Transaction, gracePeriod?: number): boolean; + static sleep(ms: number): Promise; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/utils.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/utils.js new file mode 100644 index 000000000..3609eac76 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/utils.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Utils = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Utils = exports.Utils = function () { + function Utils() { + _classCallCheck(this, Utils); + } + return _createClass(Utils, null, [{ + key: "validateTimebounds", + value: function validateTimebounds(transaction) { + var gracePeriod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + if (!transaction.timeBounds) { + return false; + } + var now = Math.floor(Date.now() / 1000); + var _transaction$timeBoun = transaction.timeBounds, + minTime = _transaction$timeBoun.minTime, + maxTime = _transaction$timeBoun.maxTime; + return now >= Number.parseInt(minTime, 10) - gracePeriod && now <= Number.parseInt(maxTime, 10) + gracePeriod; + } + }, { + key: "sleep", + value: function sleep(ms) { + return new Promise(function (resolve) { + return setTimeout(resolve, ms); + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/errors.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/errors.d.ts new file mode 100644 index 000000000..0e59f59ee --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/errors.d.ts @@ -0,0 +1,13 @@ +/** + * InvalidChallengeError is raised when a challenge transaction does not meet + * the requirements for a SEP-10 challenge transaction (for example, a non-zero + * sequence number). + * @memberof module:WebAuth + * @category Errors + * + * @param {string} message Human-readable error message. + */ +export declare class InvalidChallengeError extends Error { + __proto__: InvalidChallengeError; + constructor(message: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/errors.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/errors.js new file mode 100644 index 000000000..2542a4449 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/errors.js @@ -0,0 +1,36 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.InvalidChallengeError = void 0; +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var InvalidChallengeError = exports.InvalidChallengeError = function (_Error) { + function InvalidChallengeError(message) { + var _this; + _classCallCheck(this, InvalidChallengeError); + var trueProto = (this instanceof InvalidChallengeError ? this.constructor : void 0).prototype; + _this = _callSuper(this, InvalidChallengeError, [message]); + _this.__proto__ = trueProto; + _this.constructor = InvalidChallengeError; + _this.name = "InvalidChallengeError"; + return _this; + } + _inherits(InvalidChallengeError, _Error); + return _createClass(InvalidChallengeError); +}(_wrapNativeSuper(Error)); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/index.d.ts new file mode 100644 index 000000000..e63282485 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/index.d.ts @@ -0,0 +1,2 @@ +export * from './utils'; +export { InvalidChallengeError } from './errors'; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/index.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/index.js new file mode 100644 index 000000000..a0ee4d041 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/index.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + InvalidChallengeError: true +}; +Object.defineProperty(exports, "InvalidChallengeError", { + enumerable: true, + get: function get() { + return _errors.InvalidChallengeError; + } +}); +var _utils = require("./utils"); +Object.keys(_utils).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _utils[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utils[key]; + } + }); +}); +var _errors = require("./errors"); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/utils.d.ts new file mode 100644 index 000000000..a725201df --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/utils.d.ts @@ -0,0 +1,307 @@ +/** + * Stellar Web Authentication + * @module WebAuth + * @see {@link https://stellar.org/protocol-10 | SEP-10 Specification} + */ +import { FeeBumpTransaction, Keypair, Transaction } from "@stellar/stellar-base"; +import { ServerApi } from "../horizon/server_api"; +/** + * Returns a valid {@link https://stellar.org/protocol/sep-10 | SEP-10} + * challenge transaction which you can use for Stellar Web Authentication. + * + * @param {Keypair} serverKeypair Keypair for server's signing account. + * @param {string} clientAccountID The stellar account (G...) or muxed account + * (M...) that the wallet wishes to authenticate with the server. + * @param {string} homeDomain The fully qualified domain name of the service + * requiring authentication + * @param {number} [timeout=300] Challenge duration (default to 5 minutes). + * @param {string} networkPassphrase The network passphrase. If you pass this + * argument then timeout is required. + * @param {string} webAuthDomain The fully qualified domain name of the service + * issuing the challenge. + * @param {string} [memo] The memo to attach to the challenge transaction. The + * memo must be of type `id`. If the `clientaccountID` is a muxed account, + * memos cannot be used. + * @param {string} [clientDomain] The fully qualified domain of the client + * requesting the challenge. Only necessary when the the 'client_domain' + * parameter is passed. + * @param {string} [clientSigningKey] The public key assigned to the SIGNING_KEY + * attribute specified on the stellar.toml hosted on the client domain. Only + * necessary when the 'client_domain' parameter is passed. + * @returns {string} A base64 encoded string of the raw TransactionEnvelope xdr + * struct for the transaction. + * @throws {Error} Will throw if `clientAccountID is a muxed account, and `memo` + * is present. + * @throws {Error} Will throw if `clientDomain` is provided, but + * `clientSigningKey` is missing + * + * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth} + * + * @example + * import { Keypair, Networks, WebAuth } from 'stellar-sdk' + * + * let serverKeyPair = Keypair.fromSecret("server-secret") + * let challenge = WebAuth.buildChallengeTx( + * serverKeyPair, + * "client-stellar-account-id", + * "stellar.org", + * 300, + * Networks.TESTNET); + */ +export declare function buildChallengeTx(serverKeypair: Keypair, clientAccountID: string, homeDomain: string, timeout: number | undefined, networkPassphrase: string, webAuthDomain: string, memo?: string | null, clientDomain?: string | null, clientSigningKey?: string | null): string; +/** + * A parsed and validated challenge transaction, and some of its constituent details. + * @memberof module:WebAuth + */ +export type ChallengeTxDetails = { + /** The challenge transaction. */ + tx: Transaction; + /** The Stellar public key (master key) used to sign the Manage Data operation. */ + clientAccountId: string; + /** The matched home domain. */ + matchedHomeDomain: string; + /** The memo attached to the transaction, which will be null if not present */ + memo?: string; +}; +/** + * Reads a SEP-10 challenge transaction and returns the decoded transaction and + * client account ID contained within. + * + * It also verifies that the transaction has been signed by the server. + * + * It does not verify that the transaction has been signed by the client or that + * any signatures other than the server's on the transaction are valid. Use one + * of the following functions to completely verify the transaction: + * + * - {@link module:WebAuth~verifyChallengeTxThreshold} + * - {@link module:WebAuth~verifyChallengeTxSigners} + * + * @param {string} challengeTx SEP0010 challenge transaction in base64. + * @param {string} serverAccountID The server's stellar account (public key). + * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF + * Network ; September 2015' (see {@link Networks}) + * @param {string | Array.} homeDomains The home domain that is expected + * to be included in the first Manage Data operation's string key. If an + * array is provided, one of the domain names in the array must match. + * @param {string} webAuthDomain The home domain that is expected to be included + * as the value of the Manage Data operation with the 'web_auth_domain' key. + * If no such operation is included, this parameter is not used. + * @returns {module:WebAuth.ChallengeTxDetails} The actual transaction and the + * Stellar public key (master key) used to sign the Manage Data operation, + * the matched home domain, and the memo attached to the transaction, which + * will be null if not present. + * + * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth} + */ +export declare function readChallengeTx(challengeTx: string, serverAccountID: string, networkPassphrase: string, homeDomains: string | string[], webAuthDomain: string): { + tx: Transaction; + clientAccountID: string; + matchedHomeDomain: string; + memo: string | null; +}; +/** + * Verifies that for a SEP-10 challenge transaction all signatures on the + * transaction are accounted for and that the signatures meet a threshold on an + * account. A transaction is verified if it is signed by the server account, and + * all other signatures match a signer that has been provided as an argument, + * and those signatures meet a threshold on the account. + * + * Signers that are not prefixed as an address/account ID strkey (G...) will be + * ignored. + * + * Errors will be raised if: + * - The transaction is invalid according to + * {@link module:WebAuth~readChallengeTx}. + * - No client signatures are found on the transaction. + * - One or more signatures in the transaction are not identifiable as the + * server account or one of the signers provided in the arguments. + * - The signatures are all valid but do not meet the threshold. + * + * @param {string} challengeTx SEP0010 challenge transaction in base64. + * @param {string} serverAccountID The server's stellar account (public key). + * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF + * Network ; September 2015' (see {@link Networks}). + * @param {number} threshold The required signatures threshold for verifying + * this transaction. + * @param {Array.} signerSummary a map of all + * authorized signers to their weights. It's used to validate if the + * transaction signatures have met the given threshold. + * @param {string | Array.} homeDomains The home domain(s) that should + * be included in the first Manage Data operation's string key. Required in + * verifyChallengeTxSigners() => readChallengeTx(). + * @param {string} webAuthDomain The home domain that is expected to be included + * as the value of the Manage Data operation with the 'web_auth_domain' key, + * if present. Used in verifyChallengeTxSigners() => readChallengeTx(). + * @returns {Array.} The list of signers public keys that have signed + * the transaction, excluding the server account ID, given that the threshold + * was met. + * @throws {module:WebAuth.InvalidChallengeError} Will throw if the collective + * weight of the transaction's signers does not meet the necessary threshold + * to verify this transaction. + * + * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth} + * + * @example + * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk'; + * + * const serverKP = Keypair.random(); + * const clientKP1 = Keypair.random(); + * const clientKP2 = Keypair.random(); + * + * // Challenge, possibly built in the server side + * const challenge = WebAuth.buildChallengeTx( + * serverKP, + * clientKP1.publicKey(), + * "SDF", + * 300, + * Networks.TESTNET + * ); + * + * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client + * + * // Transaction gathered from a challenge, possibly from the client side + * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET); + * transaction.sign(clientKP1, clientKP2); + * const signedChallenge = transaction + * .toEnvelope() + * .toXDR("base64") + * .toString(); + * + * // Defining the threshold and signerSummary + * const threshold = 3; + * const signerSummary = [ + * { + * key: this.clientKP1.publicKey(), + * weight: 1, + * }, + * { + * key: this.clientKP2.publicKey(), + * weight: 2, + * }, + * ]; + * + * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()] + * WebAuth.verifyChallengeTxThreshold( + * signedChallenge, + * serverKP.publicKey(), + * Networks.TESTNET, + * threshold, + * signerSummary + * ); + */ +export declare function verifyChallengeTxThreshold(challengeTx: string, serverAccountID: string, networkPassphrase: string, threshold: number, signerSummary: ServerApi.AccountRecordSigners[], homeDomains: string | string[], webAuthDomain: string): string[]; +/** + * Verifies that for a SEP 10 challenge transaction all signatures on the + * transaction are accounted for. A transaction is verified if it is signed by + * the server account, and all other signatures match a signer that has been + * provided as an argument (as the accountIDs list). Additional signers can be + * provided that do not have a signature, but all signatures must be matched to + * a signer (accountIDs) for verification to succeed. If verification succeeds, + * a list of signers that were found is returned, not including the server + * account ID. + * + * Signers that are not prefixed as an address/account ID strkey (G...) will be + * ignored. + * + * Errors will be raised if: + * - The transaction is invalid according to + * {@link module:WebAuth~readChallengeTx}. + * - No client signatures are found on the transaction. + * - One or more signatures in the transaction are not identifiable as the + * server account or one of the signers provided in the arguments. + * + * @param {string} challengeTx SEP0010 challenge transaction in base64. + * @param {string} serverAccountID The server's stellar account (public key). + * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF + * Network ; September 2015' (see {@link Networks}). + * @param {Array.} signers The signers public keys. This list should + * contain the public keys for all signers that have signed the transaction. + * @param {string | Array.} [homeDomains] The home domain(s) that should + * be included in the first Manage Data operation's string key. Required in + * readChallengeTx(). + * @param {string} webAuthDomain The home domain that is expected to be included + * as the value of the Manage Data operation with the 'web_auth_domain' key, + * if present. Used in readChallengeTx(). + * @returns {Array.} The list of signers public keys that have signed + * the transaction, excluding the server account ID. + * + * @see {@link https://stellar.org/protocol/sep-10|SEP-10: Stellar Web Auth} + * @example + * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk'; + * + * const serverKP = Keypair.random(); + * const clientKP1 = Keypair.random(); + * const clientKP2 = Keypair.random(); + * + * // Challenge, possibly built in the server side + * const challenge = WebAuth.buildChallengeTx( + * serverKP, + * clientKP1.publicKey(), + * "SDF", + * 300, + * Networks.TESTNET + * ); + * + * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client + * + * // Transaction gathered from a challenge, possibly from the client side + * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET); + * transaction.sign(clientKP1, clientKP2); + * const signedChallenge = transaction + * .toEnvelope() + * .toXDR("base64") + * .toString(); + * + * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()] + * WebAuth.verifyChallengeTxSigners( + * signedChallenge, + * serverKP.publicKey(), + * Networks.TESTNET, + * threshold, + * [clientKP1.publicKey(), clientKP2.publicKey()] + * ); + */ +export declare function verifyChallengeTxSigners(challengeTx: string, serverAccountID: string, networkPassphrase: string, signers: string[], homeDomains: string | string[], webAuthDomain: string): string[]; +/** + * Verifies if a transaction was signed by the given account id. + * + * @param {Transaction | FeeBumpTransaction} transaction The signed transaction. + * @param {string} accountID The signer's public key. + * @returns {boolean} Whether or not `accountID` was found to have signed the + * transaction. + * + * @example + * let keypair = Keypair.random(); + * const account = new StellarSdk.Account(keypair.publicKey(), "-1"); + * + * const transaction = new TransactionBuilder(account, { fee: 100 }) + * .setTimeout(30) + * .build(); + * + * transaction.sign(keypair) + * WebAuth.verifyTxSignedBy(transaction, keypair.publicKey()) + */ +export declare function verifyTxSignedBy(transaction: FeeBumpTransaction | Transaction, accountID: string): boolean; +/** + * Checks if a transaction has been signed by one or more of the given signers, + * returning a list of non-repeated signers that were found to have signed the + * given transaction. + * + * @param {Transaction | FeeBumpTransaction} transaction The signed transaction. + * @param {Array.} signers The signer's public keys. + * @returns {Array.} A list of signers that were found to have signed + * the transaction. + * + * @example + * let keypair1 = Keypair.random(); + * let keypair2 = Keypair.random(); + * const account = new StellarSdk.Account(keypair1.publicKey(), "-1"); + * + * const transaction = new TransactionBuilder(account, { fee: 100 }) + * .setTimeout(30) + * .build(); + * + * transaction.sign(keypair1, keypair2) + * WebAuth.gatherTxSigners(transaction, [keypair1.publicKey(), keypair2.publicKey()]) + */ +export declare function gatherTxSigners(transaction: FeeBumpTransaction | Transaction, signers: string[]): string[]; diff --git a/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/utils.js b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/utils.js new file mode 100644 index 000000000..bc35281aa --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/no-eventsource/webauth/utils.js @@ -0,0 +1,332 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildChallengeTx = buildChallengeTx; +exports.gatherTxSigners = gatherTxSigners; +exports.readChallengeTx = readChallengeTx; +exports.verifyChallengeTxSigners = verifyChallengeTxSigners; +exports.verifyChallengeTxThreshold = verifyChallengeTxThreshold; +exports.verifyTxSignedBy = verifyTxSignedBy; +var _randombytes = _interopRequireDefault(require("randombytes")); +var _stellarBase = require("@stellar/stellar-base"); +var _utils = require("../utils"); +var _errors = require("./errors"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function buildChallengeTx(serverKeypair, clientAccountID, homeDomain) { + var timeout = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 300; + var networkPassphrase = arguments.length > 4 ? arguments[4] : undefined; + var webAuthDomain = arguments.length > 5 ? arguments[5] : undefined; + var memo = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var clientDomain = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var clientSigningKey = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; + if (clientAccountID.startsWith("M") && memo) { + throw Error("memo cannot be used if clientAccountID is a muxed account"); + } + var account = new _stellarBase.Account(serverKeypair.publicKey(), "-1"); + var now = Math.floor(Date.now() / 1000); + var value = (0, _randombytes.default)(48).toString("base64"); + var builder = new _stellarBase.TransactionBuilder(account, { + fee: _stellarBase.BASE_FEE, + networkPassphrase: networkPassphrase, + timebounds: { + minTime: now, + maxTime: now + timeout + } + }).addOperation(_stellarBase.Operation.manageData({ + name: "".concat(homeDomain, " auth"), + value: value, + source: clientAccountID + })).addOperation(_stellarBase.Operation.manageData({ + name: "web_auth_domain", + value: webAuthDomain, + source: account.accountId() + })); + if (clientDomain) { + if (!clientSigningKey) { + throw Error("clientSigningKey is required if clientDomain is provided"); + } + builder.addOperation(_stellarBase.Operation.manageData({ + name: "client_domain", + value: clientDomain, + source: clientSigningKey + })); + } + if (memo) { + builder.addMemo(_stellarBase.Memo.id(memo)); + } + var transaction = builder.build(); + transaction.sign(serverKeypair); + return transaction.toEnvelope().toXDR("base64").toString(); +} +function readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain) { + var _transaction$timeBoun; + if (serverAccountID.startsWith("M")) { + throw Error("Invalid serverAccountID: multiplexed accounts are not supported."); + } + var transaction; + try { + transaction = new _stellarBase.Transaction(challengeTx, networkPassphrase); + } catch (_unused) { + try { + transaction = new _stellarBase.FeeBumpTransaction(challengeTx, networkPassphrase); + } catch (_unused2) { + throw new _errors.InvalidChallengeError("Invalid challenge: unable to deserialize challengeTx transaction string"); + } + throw new _errors.InvalidChallengeError("Invalid challenge: expected a Transaction but received a FeeBumpTransaction"); + } + var sequence = Number.parseInt(transaction.sequence, 10); + if (sequence !== 0) { + throw new _errors.InvalidChallengeError("The transaction sequence number should be zero"); + } + if (transaction.source !== serverAccountID) { + throw new _errors.InvalidChallengeError("The transaction source account is not equal to the server's account"); + } + if (transaction.operations.length < 1) { + throw new _errors.InvalidChallengeError("The transaction should contain at least one operation"); + } + var _transaction$operatio = _toArray(transaction.operations), + operation = _transaction$operatio[0], + subsequentOperations = _transaction$operatio.slice(1); + if (!operation.source) { + throw new _errors.InvalidChallengeError("The transaction's operation should contain a source account"); + } + var clientAccountID = operation.source; + var memo = null; + if (transaction.memo.type !== _stellarBase.MemoNone) { + if (clientAccountID.startsWith("M")) { + throw new _errors.InvalidChallengeError("The transaction has a memo but the client account ID is a muxed account"); + } + if (transaction.memo.type !== _stellarBase.MemoID) { + throw new _errors.InvalidChallengeError("The transaction's memo must be of type `id`"); + } + memo = transaction.memo.value; + } + if (operation.type !== "manageData") { + throw new _errors.InvalidChallengeError("The transaction's operation type should be 'manageData'"); + } + if (transaction.timeBounds && Number.parseInt((_transaction$timeBoun = transaction.timeBounds) === null || _transaction$timeBoun === void 0 ? void 0 : _transaction$timeBoun.maxTime, 10) === _stellarBase.TimeoutInfinite) { + throw new _errors.InvalidChallengeError("The transaction requires non-infinite timebounds"); + } + if (!_utils.Utils.validateTimebounds(transaction, 60 * 5)) { + throw new _errors.InvalidChallengeError("The transaction has expired"); + } + if (operation.value === undefined) { + throw new _errors.InvalidChallengeError("The transaction's operation values should not be null"); + } + if (!operation.value) { + throw new _errors.InvalidChallengeError("The transaction's operation value should not be null"); + } + if (Buffer.from(operation.value.toString(), "base64").length !== 48) { + throw new _errors.InvalidChallengeError("The transaction's operation value should be a 64 bytes base64 random string"); + } + if (!homeDomains) { + throw new _errors.InvalidChallengeError("Invalid homeDomains: a home domain must be provided for verification"); + } + var matchedHomeDomain; + if (typeof homeDomains === "string") { + if ("".concat(homeDomains, " auth") === operation.name) { + matchedHomeDomain = homeDomains; + } + } else if (Array.isArray(homeDomains)) { + matchedHomeDomain = homeDomains.find(function (domain) { + return "".concat(domain, " auth") === operation.name; + }); + } else { + throw new _errors.InvalidChallengeError("Invalid homeDomains: homeDomains type is ".concat(_typeof(homeDomains), " but should be a string or an array")); + } + if (!matchedHomeDomain) { + throw new _errors.InvalidChallengeError("Invalid homeDomains: the transaction's operation key name does not match the expected home domain"); + } + var _iterator = _createForOfIteratorHelper(subsequentOperations), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var op = _step.value; + if (op.type !== "manageData") { + throw new _errors.InvalidChallengeError("The transaction has operations that are not of type 'manageData'"); + } + if (op.source !== serverAccountID && op.name !== "client_domain") { + throw new _errors.InvalidChallengeError("The transaction has operations that are unrecognized"); + } + if (op.name === "web_auth_domain") { + if (op.value === undefined) { + throw new _errors.InvalidChallengeError("'web_auth_domain' operation value should not be null"); + } + if (op.value.compare(Buffer.from(webAuthDomain))) { + throw new _errors.InvalidChallengeError("'web_auth_domain' operation value does not match ".concat(webAuthDomain)); + } + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + if (!verifyTxSignedBy(transaction, serverAccountID)) { + throw new _errors.InvalidChallengeError("Transaction not signed by server: '".concat(serverAccountID, "'")); + } + return { + tx: transaction, + clientAccountID: clientAccountID, + matchedHomeDomain: matchedHomeDomain, + memo: memo + }; +} +function verifyChallengeTxThreshold(challengeTx, serverAccountID, networkPassphrase, threshold, signerSummary, homeDomains, webAuthDomain) { + var signers = signerSummary.map(function (signer) { + return signer.key; + }); + var signersFound = verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain); + var weight = 0; + var _loop = function _loop() { + var _signerSummary$find; + var signer = _signersFound[_i]; + var sigWeight = ((_signerSummary$find = signerSummary.find(function (s) { + return s.key === signer; + })) === null || _signerSummary$find === void 0 ? void 0 : _signerSummary$find.weight) || 0; + weight += sigWeight; + }; + for (var _i = 0, _signersFound = signersFound; _i < _signersFound.length; _i++) { + _loop(); + } + if (weight < threshold) { + throw new _errors.InvalidChallengeError("signers with weight ".concat(weight, " do not meet threshold ").concat(threshold, "\"")); + } + return signersFound; +} +function verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain) { + var _readChallengeTx = readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain), + tx = _readChallengeTx.tx; + var serverKP; + try { + serverKP = _stellarBase.Keypair.fromPublicKey(serverAccountID); + } catch (err) { + throw new Error("Couldn't infer keypair from the provided 'serverAccountID': ".concat(err.message)); + } + var clientSigners = new Set(); + var _iterator2 = _createForOfIteratorHelper(signers), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var _signer = _step2.value; + if (_signer === serverKP.publicKey()) { + continue; + } + if (_signer.charAt(0) !== "G") { + continue; + } + clientSigners.add(_signer); + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + if (clientSigners.size === 0) { + throw new _errors.InvalidChallengeError("No verifiable client signers provided, at least one G... address must be provided"); + } + var clientSigningKey; + var _iterator3 = _createForOfIteratorHelper(tx.operations), + _step3; + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + var op = _step3.value; + if (op.type === "manageData" && op.name === "client_domain") { + if (clientSigningKey) { + throw new _errors.InvalidChallengeError("Found more than one client_domain operation"); + } + clientSigningKey = op.source; + } + } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); + } + var allSigners = [serverKP.publicKey()].concat(_toConsumableArray(Array.from(clientSigners))); + if (clientSigningKey) { + allSigners.push(clientSigningKey); + } + var signersFound = gatherTxSigners(tx, allSigners); + var serverSignatureFound = false; + var clientSigningKeySignatureFound = false; + for (var _i2 = 0, _signersFound2 = signersFound; _i2 < _signersFound2.length; _i2++) { + var signer = _signersFound2[_i2]; + if (signer === serverKP.publicKey()) { + serverSignatureFound = true; + } + if (signer === clientSigningKey) { + clientSigningKeySignatureFound = true; + } + } + if (!serverSignatureFound) { + throw new _errors.InvalidChallengeError("Transaction not signed by server: '".concat(serverKP.publicKey(), "'")); + } + if (clientSigningKey && !clientSigningKeySignatureFound) { + throw new _errors.InvalidChallengeError("Transaction not signed by the source account of the 'client_domain' " + "ManageData operation"); + } + if (signersFound.length === 1) { + throw new _errors.InvalidChallengeError("None of the given signers match the transaction signatures"); + } + if (signersFound.length !== tx.signatures.length) { + throw new _errors.InvalidChallengeError("Transaction has unrecognized signatures"); + } + signersFound.splice(signersFound.indexOf(serverKP.publicKey()), 1); + if (clientSigningKey) { + signersFound.splice(signersFound.indexOf(clientSigningKey), 1); + } + return signersFound; +} +function verifyTxSignedBy(transaction, accountID) { + return gatherTxSigners(transaction, [accountID]).length !== 0; +} +function gatherTxSigners(transaction, signers) { + var hashedSignatureBase = transaction.hash(); + var txSignatures = _toConsumableArray(transaction.signatures); + var signersFound = new Set(); + var _iterator4 = _createForOfIteratorHelper(signers), + _step4; + try { + for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { + var signer = _step4.value; + if (txSignatures.length === 0) { + break; + } + var keypair = void 0; + try { + keypair = _stellarBase.Keypair.fromPublicKey(signer); + } catch (err) { + throw new _errors.InvalidChallengeError("Signer is not a valid address: ".concat(err.message)); + } + for (var i = 0; i < txSignatures.length; i++) { + var decSig = txSignatures[i]; + if (!decSig.hint().equals(keypair.signatureHint())) { + continue; + } + if (keypair.verify(hashedSignatureBase, decSig.signature())) { + signersFound.add(signer); + txSignatures.splice(i, 1); + break; + } + } + } + } catch (err) { + _iterator4.e(err); + } finally { + _iterator4.f(); + } + return Array.from(signersFound); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/api.d.ts b/node_modules/@stellar/stellar-sdk/lib/rpc/api.d.ts new file mode 100644 index 000000000..87d269804 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/api.d.ts @@ -0,0 +1,363 @@ +import { Contract, SorobanDataBuilder, xdr } from '@stellar/stellar-base'; +export declare namespace Api { + export interface GetHealthResponse { + status: 'healthy'; + } + export interface LedgerEntryResult { + lastModifiedLedgerSeq?: number; + key: xdr.LedgerKey; + val: xdr.LedgerEntryData; + liveUntilLedgerSeq?: number; + } + export interface RawLedgerEntryResult { + lastModifiedLedgerSeq?: number; + /** a base-64 encoded {@link xdr.LedgerKey} instance */ + key: string; + /** a base-64 encoded {@link xdr.LedgerEntryData} instance */ + xdr: string; + /** + * optional, a future ledger number upon which this entry will expire + * based on https://github.com/stellar/soroban-tools/issues/1010 + */ + liveUntilLedgerSeq?: number; + } + /** An XDR-parsed version of {@link this.RawLedgerEntryResult} */ + export interface GetLedgerEntriesResponse { + entries: LedgerEntryResult[]; + latestLedger: number; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries */ + export interface RawGetLedgerEntriesResponse { + entries?: RawLedgerEntryResult[]; + latestLedger: number; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getNetwork */ + export interface GetNetworkResponse { + friendbotUrl?: string; + passphrase: string; + protocolVersion: string; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLatestLedger */ + export interface GetLatestLedgerResponse { + id: string; + sequence: number; + protocolVersion: string; + } + export enum GetTransactionStatus { + SUCCESS = "SUCCESS", + NOT_FOUND = "NOT_FOUND", + FAILED = "FAILED" + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransaction */ + export type GetTransactionResponse = GetSuccessfulTransactionResponse | GetFailedTransactionResponse | GetMissingTransactionResponse; + interface GetAnyTransactionResponse { + status: GetTransactionStatus; + txHash: string; + latestLedger: number; + latestLedgerCloseTime: number; + oldestLedger: number; + oldestLedgerCloseTime: number; + } + export interface GetMissingTransactionResponse extends GetAnyTransactionResponse { + status: GetTransactionStatus.NOT_FOUND; + } + export interface GetFailedTransactionResponse extends GetAnyTransactionResponse { + status: GetTransactionStatus.FAILED; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + envelopeXdr: xdr.TransactionEnvelope; + resultXdr: xdr.TransactionResult; + resultMetaXdr: xdr.TransactionMeta; + diagnosticEventsXdr?: xdr.DiagnosticEvent[]; + } + export interface GetSuccessfulTransactionResponse extends GetAnyTransactionResponse { + status: GetTransactionStatus.SUCCESS; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + envelopeXdr: xdr.TransactionEnvelope; + resultXdr: xdr.TransactionResult; + resultMetaXdr: xdr.TransactionMeta; + diagnosticEventsXdr?: xdr.DiagnosticEvent[]; + returnValue?: xdr.ScVal; + } + export interface RawGetTransactionResponse { + status: GetTransactionStatus; + latestLedger: number; + latestLedgerCloseTime: number; + oldestLedger: number; + oldestLedgerCloseTime: number; + txHash: string; + applicationOrder?: number; + feeBump?: boolean; + ledger?: number; + createdAt?: number; + envelopeXdr?: string; + resultXdr?: string; + resultMetaXdr?: string; + diagnosticEventsXdr?: string[]; + } + export interface GetTransactionsRequest { + startLedger: number; + cursor?: string; + limit?: number; + } + export interface RawTransactionInfo { + status: GetTransactionStatus; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + txHash: string; + envelopeXdr?: string; + resultXdr?: string; + resultMetaXdr?: string; + diagnosticEventsXdr?: string[]; + } + export interface TransactionInfo { + status: GetTransactionStatus; + ledger: number; + createdAt: number; + applicationOrder: number; + feeBump: boolean; + txHash: string; + envelopeXdr: xdr.TransactionEnvelope; + resultXdr: xdr.TransactionResult; + resultMetaXdr: xdr.TransactionMeta; + returnValue?: xdr.ScVal; + diagnosticEventsXdr?: xdr.DiagnosticEvent[]; + } + export interface GetTransactionsResponse { + transactions: TransactionInfo[]; + latestLedger: number; + latestLedgerCloseTimestamp: number; + oldestLedger: number; + oldestLedgerCloseTimestamp: number; + cursor: string; + } + export interface RawGetTransactionsResponse { + transactions: RawTransactionInfo[]; + latestLedger: number; + latestLedgerCloseTimestamp: number; + oldestLedger: number; + oldestLedgerCloseTimestamp: number; + cursor: string; + } + export type EventType = 'contract' | 'system' | 'diagnostic'; + export interface EventFilter { + type?: EventType; + contractIds?: string[]; + topics?: string[][]; + } + export interface GetEventsResponse { + latestLedger: number; + events: EventResponse[]; + cursor: string; + } + export interface EventResponse extends BaseEventResponse { + contractId?: Contract; + topic: xdr.ScVal[]; + value: xdr.ScVal; + } + export interface RawGetEventsResponse { + latestLedger: number; + events: RawEventResponse[]; + cursor: string; + } + interface BaseEventResponse { + id: string; + type: EventType; + ledger: number; + ledgerClosedAt: string; + pagingToken: string; + inSuccessfulContractCall: boolean; + txHash: string; + } + export interface RawEventResponse extends BaseEventResponse { + contractId: string; + topic: string[]; + value: string; + } + interface RawLedgerEntryChange { + type: number; + /** This is LedgerKey in base64 */ + key: string; + /** This is xdr.LedgerEntry in base64 */ + before: string | null; + /** This is xdr.LedgerEntry in base64 */ + after: string | null; + } + export interface LedgerEntryChange { + type: number; + key: xdr.LedgerKey; + before: xdr.LedgerEntry | null; + after: xdr.LedgerEntry | null; + } + export type SendTransactionStatus = 'PENDING' | 'DUPLICATE' | 'TRY_AGAIN_LATER' | 'ERROR'; + export interface SendTransactionResponse extends BaseSendTransactionResponse { + errorResult?: xdr.TransactionResult; + diagnosticEvents?: xdr.DiagnosticEvent[]; + } + export interface RawSendTransactionResponse extends BaseSendTransactionResponse { + /** + * This is a base64-encoded instance of {@link xdr.TransactionResult}, set + * only when `status` is `"ERROR"`. + * + * It contains details on why the network rejected the transaction. + */ + errorResultXdr?: string; + /** + * This is a base64-encoded instance of an array of + * {@link xdr.DiagnosticEvent}s, set only when `status` is `"ERROR"` and + * diagnostic events are enabled on the server. + */ + diagnosticEventsXdr?: string[]; + } + export interface BaseSendTransactionResponse { + status: SendTransactionStatus; + hash: string; + latestLedger: number; + latestLedgerCloseTime: number; + } + export interface SimulateHostFunctionResult { + auth: xdr.SorobanAuthorizationEntry[]; + retval: xdr.ScVal; + } + /** + * Simplifies {@link Api.RawSimulateTransactionResponse} into separate interfaces + * based on status: + * - on success, this includes all fields, though `result` is only present + * if an invocation was simulated (since otherwise there's nothing to + * "resultify") + * - if there was an expiration error, this includes error and restoration + * fields + * - for all other errors, this only includes error fields + * + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction + */ + export type SimulateTransactionResponse = SimulateTransactionSuccessResponse | SimulateTransactionRestoreResponse | SimulateTransactionErrorResponse; + export interface BaseSimulateTransactionResponse { + /** always present: the JSON-RPC request ID */ + id: string; + /** always present: the LCL known to the server when responding */ + latestLedger: number; + /** + * The field is always present, but may be empty in cases where: + * - you didn't simulate an invocation or + * - there were no events + */ + events: xdr.DiagnosticEvent[]; + /** a private field to mark the schema as parsed */ + _parsed: boolean; + } + /** Includes simplified fields only present on success. */ + export interface SimulateTransactionSuccessResponse extends BaseSimulateTransactionResponse { + transactionData: SorobanDataBuilder; + minResourceFee: string; + /** present only for invocation simulation */ + result?: SimulateHostFunctionResult; + /** State Difference information */ + stateChanges?: LedgerEntryChange[]; + } + /** Includes details about why the simulation failed */ + export interface SimulateTransactionErrorResponse extends BaseSimulateTransactionResponse { + error: string; + events: xdr.DiagnosticEvent[]; + } + export interface SimulateTransactionRestoreResponse extends SimulateTransactionSuccessResponse { + result: SimulateHostFunctionResult; + /** + * Indicates that a restoration is necessary prior to submission. + * + * In other words, seeing a restoration preamble means that your invocation + * was executed AS IF the required ledger entries were present, and this + * field includes information about what you need to restore for the + * simulation to succeed. + */ + restorePreamble: { + minResourceFee: string; + transactionData: SorobanDataBuilder; + }; + } + export function isSimulationError(sim: SimulateTransactionResponse): sim is SimulateTransactionErrorResponse; + export function isSimulationSuccess(sim: SimulateTransactionResponse): sim is SimulateTransactionSuccessResponse; + export function isSimulationRestore(sim: SimulateTransactionResponse): sim is SimulateTransactionRestoreResponse; + export function isSimulationRaw(sim: Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse): sim is Api.RawSimulateTransactionResponse; + interface RawSimulateHostFunctionResult { + auth?: string[]; + xdr: string; + } + /** @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction */ + export interface RawSimulateTransactionResponse { + id: string; + latestLedger: number; + error?: string; + /** This is an xdr.SorobanTransactionData in base64 */ + transactionData?: string; + /** These are xdr.DiagnosticEvents in base64 */ + events?: string[]; + minResourceFee?: string; + /** + * This will only contain a single element if present, because only a single + * invokeHostFunctionOperation is supported per transaction. + * */ + results?: RawSimulateHostFunctionResult[]; + /** Present if succeeded but has expired ledger entries */ + restorePreamble?: { + minResourceFee: string; + transactionData: string; + }; + /** State difference information */ + stateChanges?: RawLedgerEntryChange[]; + } + export interface GetVersionInfoResponse { + version: string; + commitHash: string; + buildTimestamp: string; + captiveCoreVersion: string; + protocolVersion: number; + commit_hash: string; + build_timestamp: string; + captive_core_version: string; + protocol_version: number; + } + export interface GetFeeStatsResponse { + sorobanInclusionFee: FeeDistribution; + inclusionFee: FeeDistribution; + latestLedger: number; + } + interface FeeDistribution { + max: string; + min: string; + mode: string; + p10: string; + p20: string; + p30: string; + p40: string; + p50: string; + p60: string; + p70: string; + p80: string; + p90: string; + p95: string; + p99: string; + transactionCount: string; + ledgerCount: number; + } + export interface BalanceResponse { + latestLedger: number; + /** present only on success, otherwise request malformed or no balance */ + balanceEntry?: { + /** a 64-bit integer */ + amount: string; + authorized: boolean; + clawback: boolean; + lastModifiedLedgerSeq?: number; + liveUntilLedgerSeq?: number; + }; + } + export {}; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/api.js b/node_modules/@stellar/stellar-sdk/lib/rpc/api.js new file mode 100644 index 000000000..119ddb359 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/api.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Api = void 0; +var Api; +(function (_Api) { + var GetTransactionStatus = function (GetTransactionStatus) { + GetTransactionStatus["SUCCESS"] = "SUCCESS"; + GetTransactionStatus["NOT_FOUND"] = "NOT_FOUND"; + GetTransactionStatus["FAILED"] = "FAILED"; + return GetTransactionStatus; + }({}); + _Api.GetTransactionStatus = GetTransactionStatus; + function isSimulationError(sim) { + return 'error' in sim; + } + _Api.isSimulationError = isSimulationError; + function isSimulationSuccess(sim) { + return 'transactionData' in sim; + } + _Api.isSimulationSuccess = isSimulationSuccess; + function isSimulationRestore(sim) { + return isSimulationSuccess(sim) && 'restorePreamble' in sim && !!sim.restorePreamble.transactionData; + } + _Api.isSimulationRestore = isSimulationRestore; + function isSimulationRaw(sim) { + return !sim._parsed; + } + _Api.isSimulationRaw = isSimulationRaw; +})(Api || (exports.Api = Api = {})); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/axios.d.ts b/node_modules/@stellar/stellar-sdk/lib/rpc/axios.d.ts new file mode 100644 index 000000000..e33eb69ca --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/axios.d.ts @@ -0,0 +1,4 @@ +import { HttpClient } from "../http-client"; +export declare const version: string; +export declare const AxiosClient: HttpClient; +export default AxiosClient; diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/axios.js b/node_modules/@stellar/stellar-sdk/lib/rpc/axios.js new file mode 100644 index 000000000..7ac7ee27c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/axios.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.version = exports.default = exports.AxiosClient = void 0; +var _httpClient = require("../http-client"); +var version = exports.version = "13.1.0"; +var AxiosClient = exports.AxiosClient = (0, _httpClient.create)({ + headers: { + 'X-Client-Name': 'js-soroban-client', + 'X-Client-Version': version + } +}); +var _default = exports.default = AxiosClient; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/browser.d.ts b/node_modules/@stellar/stellar-sdk/lib/rpc/browser.d.ts new file mode 100644 index 000000000..ca51e31ab --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/browser.d.ts @@ -0,0 +1,4 @@ +export * from './index'; +export * as StellarBase from '@stellar/stellar-base'; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/browser.js b/node_modules/@stellar/stellar-sdk/lib/rpc/browser.js new file mode 100644 index 000000000..81ef3ddb4 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/browser.js @@ -0,0 +1,27 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + StellarBase: true +}; +exports.default = exports.StellarBase = void 0; +var _index = require("./index"); +Object.keys(_index).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _index[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _index[key]; + } + }); +}); +var _StellarBase = _interopRequireWildcard(require("@stellar/stellar-base")); +exports.StellarBase = _StellarBase; +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/rpc/index.d.ts new file mode 100644 index 000000000..59ea4be47 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/index.d.ts @@ -0,0 +1,8 @@ +/** @module rpc */ +export * from "./api"; +export { RpcServer as Server, BasicSleepStrategy, LinearSleepStrategy, Durability } from "./server"; +export { default as AxiosClient } from "./axios"; +export { parseRawSimulation, parseRawEvents } from "./parsers"; +export * from "./transaction"; +declare const _default: any; +export default _default; diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/index.js b/node_modules/@stellar/stellar-sdk/lib/rpc/index.js new file mode 100644 index 000000000..f5a9e18bd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/index.js @@ -0,0 +1,86 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + Server: true, + BasicSleepStrategy: true, + LinearSleepStrategy: true, + Durability: true, + AxiosClient: true, + parseRawSimulation: true, + parseRawEvents: true +}; +Object.defineProperty(exports, "AxiosClient", { + enumerable: true, + get: function get() { + return _axios.default; + } +}); +Object.defineProperty(exports, "BasicSleepStrategy", { + enumerable: true, + get: function get() { + return _server.BasicSleepStrategy; + } +}); +Object.defineProperty(exports, "Durability", { + enumerable: true, + get: function get() { + return _server.Durability; + } +}); +Object.defineProperty(exports, "LinearSleepStrategy", { + enumerable: true, + get: function get() { + return _server.LinearSleepStrategy; + } +}); +Object.defineProperty(exports, "Server", { + enumerable: true, + get: function get() { + return _server.RpcServer; + } +}); +exports.default = void 0; +Object.defineProperty(exports, "parseRawEvents", { + enumerable: true, + get: function get() { + return _parsers.parseRawEvents; + } +}); +Object.defineProperty(exports, "parseRawSimulation", { + enumerable: true, + get: function get() { + return _parsers.parseRawSimulation; + } +}); +var _api = require("./api"); +Object.keys(_api).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _api[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _api[key]; + } + }); +}); +var _server = require("./server"); +var _axios = _interopRequireDefault(require("./axios")); +var _parsers = require("./parsers"); +var _transaction = require("./transaction"); +Object.keys(_transaction).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _transaction[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _transaction[key]; + } + }); +}); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +var _default = exports.default = module.exports; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/jsonrpc.d.ts b/node_modules/@stellar/stellar-sdk/lib/rpc/jsonrpc.d.ts new file mode 100644 index 000000000..bba021d3c --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/jsonrpc.d.ts @@ -0,0 +1,35 @@ +export type Id = string | number; +export interface Request { + jsonrpc: "2.0"; + id: Id; + method: string; + params: T; +} +export interface Notification { + jsonrpc: "2.0"; + method: string; + params?: T; +} +export type Response = { + jsonrpc: "2.0"; + id: Id; +} & ({ + error: Error; +} | { + result: T; +}); +export interface Error { + code: number; + message?: string; + data?: E; +} +/** + * Sends the jsonrpc 'params' as a single 'param' object (no array support). + * + * @param {string} url URL to the RPC instance + * @param {string} method RPC method name that should be called + * @param {(any | null)} [param=null] params that should be supplied to the method + * @returns {Promise} + * @private + */ +export declare function postObject(url: string, method: string, param?: any): Promise; diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/jsonrpc.js b/node_modules/@stellar/stellar-sdk/lib/rpc/jsonrpc.js new file mode 100644 index 000000000..8ba0f1a64 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/jsonrpc.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.postObject = postObject; +var _axios = _interopRequireDefault(require("./axios")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function hasOwnProperty(obj, prop) { + return obj.hasOwnProperty(prop); +} +function postObject(_x, _x2) { + return _postObject.apply(this, arguments); +} +function _postObject() { + _postObject = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(url, method) { + var param, + response, + _response$data, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + param = _args.length > 2 && _args[2] !== undefined ? _args[2] : null; + _context.next = 3; + return _axios.default.post(url, { + jsonrpc: "2.0", + id: 1, + method: method, + params: param + }); + case 3: + response = _context.sent; + if (!hasOwnProperty(response.data, "error")) { + _context.next = 8; + break; + } + throw response.data.error; + case 8: + return _context.abrupt("return", (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.result); + case 9: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _postObject.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/parsers.d.ts b/node_modules/@stellar/stellar-sdk/lib/rpc/parsers.d.ts new file mode 100644 index 000000000..28871d62b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/parsers.d.ts @@ -0,0 +1,39 @@ +import { Api } from './api'; +/** + * Parse the response from invoking the `submitTransaction` method of a Soroban RPC server. + * @memberof module:rpc + * @private + * + * @param {Api.RawSendTransactionResponse} raw the raw `submitTransaction` response from the Soroban RPC server to parse + * @returns {Api.SendTransactionResponse} transaction response parsed from the Soroban RPC server's response + */ +export declare function parseRawSendTransaction(raw: Api.RawSendTransactionResponse): Api.SendTransactionResponse; +export declare function parseTransactionInfo(raw: Api.RawTransactionInfo | Api.RawGetTransactionResponse): Omit; +export declare function parseRawTransactions(r: Api.RawTransactionInfo): Api.TransactionInfo; +/** + * Parse and return the retrieved events, if any, from a raw response from a Soroban RPC server. + * @memberof module:rpc + * + * @param {Api.RawGetEventsResponse} raw the raw `getEvents` response from the Soroban RPC server to parse + * @returns {Api.GetEventsResponse} events parsed from the Soroban RPC server's response + */ +export declare function parseRawEvents(raw: Api.RawGetEventsResponse): Api.GetEventsResponse; +/** + * Parse and return the retrieved ledger entries, if any, from a raw response from a Soroban RPC server. + * @memberof module:rpc + * @private + * + * @param {Api.RawGetLedgerEntriesResponse} raw he raw `getLedgerEntries` response from the Soroban RPC server to parse + * @returns {Api.GetLedgerEntriesResponse} ledger entries parsed from the Soroban RPC server's response + */ +export declare function parseRawLedgerEntries(raw: Api.RawGetLedgerEntriesResponse): Api.GetLedgerEntriesResponse; +/** + * Converts a raw response schema into one with parsed XDR fields and a simplified interface. + * @warning This API is only exported for testing purposes and should not be relied on or considered "stable". + * @memberof module:rpc + * + * @param {Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse} sim the raw response schema (parsed ones are allowed, best-effort + * detected, and returned untouched) + * @returns {Api.SimulateTransactionResponse} the original parameter (if already parsed), parsed otherwise + */ +export declare function parseRawSimulation(sim: Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse): Api.SimulateTransactionResponse; diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/parsers.js b/node_modules/@stellar/stellar-sdk/lib/rpc/parsers.js new file mode 100644 index 000000000..196336b10 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/parsers.js @@ -0,0 +1,156 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parseRawEvents = parseRawEvents; +exports.parseRawLedgerEntries = parseRawLedgerEntries; +exports.parseRawSendTransaction = parseRawSendTransaction; +exports.parseRawSimulation = parseRawSimulation; +exports.parseRawTransactions = parseRawTransactions; +exports.parseTransactionInfo = parseTransactionInfo; +var _stellarBase = require("@stellar/stellar-base"); +var _api = require("./api"); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function parseRawSendTransaction(raw) { + var errorResultXdr = raw.errorResultXdr, + diagnosticEventsXdr = raw.diagnosticEventsXdr; + delete raw.errorResultXdr; + delete raw.diagnosticEventsXdr; + if (errorResultXdr) { + return _objectSpread(_objectSpread(_objectSpread({}, raw), diagnosticEventsXdr !== undefined && diagnosticEventsXdr.length > 0 && { + diagnosticEvents: diagnosticEventsXdr.map(function (evt) { + return _stellarBase.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + }) + }), {}, { + errorResult: _stellarBase.xdr.TransactionResult.fromXDR(errorResultXdr, 'base64') + }); + } + return _objectSpread({}, raw); +} +function parseTransactionInfo(raw) { + var meta = _stellarBase.xdr.TransactionMeta.fromXDR(raw.resultMetaXdr, 'base64'); + var info = { + ledger: raw.ledger, + createdAt: raw.createdAt, + applicationOrder: raw.applicationOrder, + feeBump: raw.feeBump, + envelopeXdr: _stellarBase.xdr.TransactionEnvelope.fromXDR(raw.envelopeXdr, 'base64'), + resultXdr: _stellarBase.xdr.TransactionResult.fromXDR(raw.resultXdr, 'base64'), + resultMetaXdr: meta + }; + if (meta.switch() === 3 && meta.v3().sorobanMeta() !== null) { + var _meta$v3$sorobanMeta; + info.returnValue = (_meta$v3$sorobanMeta = meta.v3().sorobanMeta()) === null || _meta$v3$sorobanMeta === void 0 ? void 0 : _meta$v3$sorobanMeta.returnValue(); + } + if ('diagnosticEventsXdr' in raw && raw.diagnosticEventsXdr) { + info.diagnosticEventsXdr = raw.diagnosticEventsXdr.map(function (diagnosticEvent) { + return _stellarBase.xdr.DiagnosticEvent.fromXDR(diagnosticEvent, 'base64'); + }); + } + return info; +} +function parseRawTransactions(r) { + return _objectSpread({ + status: r.status, + txHash: r.txHash + }, parseTransactionInfo(r)); +} +function parseRawEvents(raw) { + var _raw$events; + return { + latestLedger: raw.latestLedger, + cursor: raw.cursor, + events: ((_raw$events = raw.events) !== null && _raw$events !== void 0 ? _raw$events : []).map(function (evt) { + var clone = _objectSpread({}, evt); + delete clone.contractId; + return _objectSpread(_objectSpread(_objectSpread({}, clone), evt.contractId !== '' && { + contractId: new _stellarBase.Contract(evt.contractId) + }), {}, { + topic: evt.topic.map(function (topic) { + return _stellarBase.xdr.ScVal.fromXDR(topic, 'base64'); + }), + value: _stellarBase.xdr.ScVal.fromXDR(evt.value, 'base64') + }); + }) + }; +} +function parseRawLedgerEntries(raw) { + var _raw$entries; + return { + latestLedger: raw.latestLedger, + entries: ((_raw$entries = raw.entries) !== null && _raw$entries !== void 0 ? _raw$entries : []).map(function (rawEntry) { + if (!rawEntry.key || !rawEntry.xdr) { + throw new TypeError("invalid ledger entry: ".concat(JSON.stringify(rawEntry))); + } + return _objectSpread({ + lastModifiedLedgerSeq: rawEntry.lastModifiedLedgerSeq, + key: _stellarBase.xdr.LedgerKey.fromXDR(rawEntry.key, 'base64'), + val: _stellarBase.xdr.LedgerEntryData.fromXDR(rawEntry.xdr, 'base64') + }, rawEntry.liveUntilLedgerSeq !== undefined && { + liveUntilLedgerSeq: rawEntry.liveUntilLedgerSeq + }); + }) + }; +} +function parseSuccessful(sim, partial) { + var _sim$results$length, _sim$results, _sim$stateChanges$len, _sim$stateChanges, _sim$stateChanges2; + var success = _objectSpread(_objectSpread(_objectSpread({}, partial), {}, { + transactionData: new _stellarBase.SorobanDataBuilder(sim.transactionData), + minResourceFee: sim.minResourceFee + }, ((_sim$results$length = (_sim$results = sim.results) === null || _sim$results === void 0 ? void 0 : _sim$results.length) !== null && _sim$results$length !== void 0 ? _sim$results$length : 0 > 0) && { + result: sim.results.map(function (row) { + var _row$auth; + return { + auth: ((_row$auth = row.auth) !== null && _row$auth !== void 0 ? _row$auth : []).map(function (entry) { + return _stellarBase.xdr.SorobanAuthorizationEntry.fromXDR(entry, 'base64'); + }), + retval: row.xdr ? _stellarBase.xdr.ScVal.fromXDR(row.xdr, 'base64') : _stellarBase.xdr.ScVal.scvVoid() + }; + })[0] + }), ((_sim$stateChanges$len = (_sim$stateChanges = sim.stateChanges) === null || _sim$stateChanges === void 0 ? void 0 : _sim$stateChanges.length) !== null && _sim$stateChanges$len !== void 0 ? _sim$stateChanges$len : 0 > 0) && { + stateChanges: (_sim$stateChanges2 = sim.stateChanges) === null || _sim$stateChanges2 === void 0 ? void 0 : _sim$stateChanges2.map(function (entryChange) { + return { + type: entryChange.type, + key: _stellarBase.xdr.LedgerKey.fromXDR(entryChange.key, 'base64'), + before: entryChange.before ? _stellarBase.xdr.LedgerEntry.fromXDR(entryChange.before, 'base64') : null, + after: entryChange.after ? _stellarBase.xdr.LedgerEntry.fromXDR(entryChange.after, 'base64') : null + }; + }) + }); + if (!sim.restorePreamble || sim.restorePreamble.transactionData === '') { + return success; + } + return _objectSpread(_objectSpread({}, success), {}, { + restorePreamble: { + minResourceFee: sim.restorePreamble.minResourceFee, + transactionData: new _stellarBase.SorobanDataBuilder(sim.restorePreamble.transactionData) + } + }); +} +function parseRawSimulation(sim) { + var _sim$events$map, _sim$events; + var looksRaw = _api.Api.isSimulationRaw(sim); + if (!looksRaw) { + return sim; + } + var base = { + _parsed: true, + id: sim.id, + latestLedger: sim.latestLedger, + events: (_sim$events$map = (_sim$events = sim.events) === null || _sim$events === void 0 ? void 0 : _sim$events.map(function (evt) { + return _stellarBase.xdr.DiagnosticEvent.fromXDR(evt, 'base64'); + })) !== null && _sim$events$map !== void 0 ? _sim$events$map : [] + }; + if (typeof sim.error === 'string') { + return _objectSpread(_objectSpread({}, base), {}, { + error: sim.error + }); + } + return parseSuccessful(sim, base); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/server.d.ts b/node_modules/@stellar/stellar-sdk/lib/rpc/server.d.ts new file mode 100644 index 000000000..7b90f345d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/server.d.ts @@ -0,0 +1,622 @@ +import URI from 'urijs'; +import { Account, Address, Asset, Contract, FeeBumpTransaction, Transaction, xdr } from '@stellar/stellar-base'; +import { Api } from './api'; +/** + * Default transaction submission timeout for RPC requests, in milliseconds + * @constant {number} + * @default 60000 + * @memberof module:rpc.Server + */ +export declare const SUBMIT_TRANSACTION_TIMEOUT: number; +/** + * Specifies the durability namespace of contract-related ledger entries. + * @enum {('temporary' | 'persistent')} + * @memberof module:rpc + * + * @see {@link https://developers.stellar.org/docs/learn/smart-contract-internals/state-archival | State Archival docs} + * @see {@link https://docs.rs/soroban-sdk/latest/soroban_sdk/storage/struct.Storage.html | Rust SDK Storage docs} + */ +export declare enum Durability { + Temporary = "temporary", + Persistent = "persistent" +} +/** + * @typedef {object} GetEventsRequest Describes the complex filter combinations available for event queries. + * @property {Array.} filters Filters to use when querying events from the RPC server. + * @property {number} [startLedger] Ledger number (inclusive) to begin querying events. + * @property {string} [cursor] Page cursor (exclusive) to begin querying events. + * @property {number} [limit=100] The maximum number of events that should be returned in the RPC response. + * @memberof module:rpc.Server + */ +/** + * @typedef {object} ResourceLeeway Describes additional resource leeways for transaction simulation. + * @property {number} cpuInstructions Simulate the transaction with more CPU instructions available. + * @memberof module:rpc.Server + */ +/** + * @typedef {object} Options Options for configuring connections to RPC servers. + * @property {boolean} [allowHttp=false] Allow connecting to http servers, default: `false`. This must be set to false in production deployments! + * @property {number} [timeout=0] Allow a timeout, default: 0. Allows user to avoid nasty lag. You can also use {@link Config} class to set this globally. + * @property {Record} [headers] Additional headers that should be added to any requests to the RPC server. + * @memberof module:rpc.Server + */ +export declare namespace RpcServer { + interface GetEventsRequest { + filters: Api.EventFilter[]; + startLedger?: number; + endLedger?: number; + cursor?: string; + limit?: number; + } + interface PollingOptions { + attempts?: number; + sleepStrategy?: SleepStrategy; + } + interface ResourceLeeway { + cpuInstructions: number; + } + interface Options { + allowHttp?: boolean; + timeout?: number; + headers?: Record; + } +} +export declare const BasicSleepStrategy: SleepStrategy; +export declare const LinearSleepStrategy: SleepStrategy; +/** + * A function that returns the number of *milliseconds* to sleep + * on a given `iter`ation. + */ +export type SleepStrategy = (iter: number) => number; +/** + * Handles the network connection to a Soroban RPC instance, exposing an + * interface for requests to that instance. + * + * @alias module:rpc.Server + * @memberof module:rpc + * + * @param {string} serverURL Soroban-RPC Server URL (ex. `http://localhost:8000/soroban/rpc`). + * @param {module:rpc.Server.Options} [opts] Options object + * @param {boolean} [opts.allowHttp] Allows connecting to insecure http servers + * (default: `false`). This must be set to false in production deployments! + * You can also use {@link Config} class to set this globally. + * @param {Record} [opts.headers] Allows setting custom headers + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods | API reference docs} + */ +export declare class RpcServer { + readonly serverURL: URI; + constructor(serverURL: string, opts?: RpcServer.Options); + /** + * Fetch a minimal set of current info about a Stellar account. + * + * Needed to get the current sequence number for the account so you can build + * a successful transaction with {@link TransactionBuilder}. + * + * @param {string} address The public address of the account to load. + * @returns {Promise} A promise which resolves to the {@link Account} + * object with a populated sequence number + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs} + * + * @example + * const accountId = "GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4"; + * server.getAccount(accountId).then((account) => { + * console.log("sequence:", account.sequence); + * }); + */ + getAccount(address: string): Promise; + /** + * General node health check. + * + * @returns {Promise} A promise which resolves to the + * {@link Api.GetHealthResponse} object with the status of the + * server (e.g. "healthy"). + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getHealth | getLedgerEntries docs} + * + * @example + * server.getHealth().then((health) => { + * console.log("status:", health.status); + * }); + */ + getHealth(): Promise; + /** + * Reads the current value of contract data ledger entries directly. + * + * Allows you to directly inspect the current state of a contract. This is a + * backup way to access your contract data which may not be available via + * events or {@link module:rpc.Server#simulateTransaction}. + * + * @param {string|Address|Contract} contract The contract ID containing the + * data to load as a strkey (`C...` form), a {@link Contract}, or an + * {@link Address} instance + * @param {xdr.ScVal} key The key of the contract data to load + * @param {module:rpc.Durability} [durability=Durability.Persistent] The "durability + * keyspace" that this ledger key belongs to, which is either 'temporary' + * or 'persistent' (the default), see {@link module:rpc.Durability}. + * @returns {Promise} The current data value + * + * @warning If the data entry in question is a 'temporary' entry, it's + * entirely possible that it has expired out of existence. + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs} + * + * @example + * const contractId = "CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5"; + * const key = xdr.ScVal.scvSymbol("counter"); + * server.getContractData(contractId, key, Durability.Temporary).then(data => { + * console.log("value:", data.val); + * console.log("liveUntilLedgerSeq:", data.liveUntilLedgerSeq); + * console.log("lastModified:", data.lastModifiedLedgerSeq); + * console.log("latestLedger:", data.latestLedger); + * }); + */ + getContractData(contract: string | Address | Contract, key: xdr.ScVal, durability?: Durability): Promise; + /** + * Retrieves the WASM bytecode for a given contract. + * + * This method allows you to fetch the WASM bytecode associated with a contract + * deployed on the Soroban network. The WASM bytecode represents the executable + * code of the contract. + * + * @param {string} contractId The contract ID containing the WASM bytecode to retrieve + * @returns {Promise} A Buffer containing the WASM bytecode + * @throws {Error} If the contract or its associated WASM bytecode cannot be + * found on the network. + * + * @example + * const contractId = "CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5"; + * server.getContractWasmByContractId(contractId).then(wasmBuffer => { + * console.log("WASM bytecode length:", wasmBuffer.length); + * // ... do something with the WASM bytecode ... + * }).catch(err => { + * console.error("Error fetching WASM bytecode:", err); + * }); + */ + getContractWasmByContractId(contractId: string): Promise; + /** + * Retrieves the WASM bytecode for a given contract hash. + * + * This method allows you to fetch the WASM bytecode associated with a contract + * deployed on the Soroban network using the contract's WASM hash. The WASM bytecode + * represents the executable code of the contract. + * + * @param {Buffer} wasmHash The WASM hash of the contract + * @returns {Promise} A Buffer containing the WASM bytecode + * @throws {Error} If the contract or its associated WASM bytecode cannot be + * found on the network. + * + * @example + * const wasmHash = Buffer.from("..."); + * server.getContractWasmByHash(wasmHash).then(wasmBuffer => { + * console.log("WASM bytecode length:", wasmBuffer.length); + * // ... do something with the WASM bytecode ... + * }).catch(err => { + * console.error("Error fetching WASM bytecode:", err); + * }); + */ + getContractWasmByHash(wasmHash: Buffer | string, format?: undefined | "hex" | "base64"): Promise; + /** + * Reads the current value of arbitrary ledger entries directly. + * + * Allows you to directly inspect the current state of contracts, contract's + * code, accounts, or any other ledger entries. + * + * To fetch a contract's WASM byte-code, built the appropriate + * {@link xdr.LedgerKeyContractCode} ledger entry key (or see + * {@link Contract.getFootprint}). + * + * @param {xdr.ScVal[]} keys One or more ledger entry keys to load + * @returns {Promise} The current on-chain + * values for the given ledger keys + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs} + * @see RpcServer._getLedgerEntries + * @example + * const contractId = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM"; + * const key = xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({ + * contractId: StrKey.decodeContract(contractId), + * key: xdr.ScVal.scvSymbol("counter"), + * })); + * + * server.getLedgerEntries([key]).then(response => { + * const ledgerData = response.entries[0]; + * console.log("key:", ledgerData.key); + * console.log("value:", ledgerData.val); + * console.log("liveUntilLedgerSeq:", ledgerData.liveUntilLedgerSeq); + * console.log("lastModified:", ledgerData.lastModifiedLedgerSeq); + * console.log("latestLedger:", response.latestLedger); + * }); + */ + getLedgerEntries(...keys: xdr.LedgerKey[]): Promise; + _getLedgerEntries(...keys: xdr.LedgerKey[]): Promise; + /** + * Poll for a particular transaction with certain parameters. + * + * After submitting a transaction, clients can use this to poll for + * transaction completion and return a definitive state of success or failure. + * + * @param {string} hash the transaction you're polling for + * @param {number} [opts.attempts] (optional) the number of attempts to make + * before returning the last-seen status. By default or on invalid inputs, + * try 5 times. + * @param {SleepStrategy} [opts.sleepStrategy] (optional) the amount of time + * to wait for between each attempt. By default, sleep for 1 second between + * each attempt. + * + * @return {Promise} the response after a "found" + * response (which may be success or failure) or the last response obtained + * after polling the maximum number of specified attempts. + * + * @example + * const h = "c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a"; + * const txStatus = await server.pollTransaction(h, { + * attempts: 100, // I'm a maniac + * sleepStrategy: rpc.LinearSleepStrategy + * }); // this will take 5,050 seconds to complete + */ + pollTransaction(hash: string, opts?: RpcServer.PollingOptions): Promise; + /** + * Fetch the details of a submitted transaction. + * + * After submitting a transaction, clients should poll this to tell when the + * transaction has completed. + * + * @param {string} hash Hex-encoded hash of the transaction to check + * @returns {Promise} The status, result, and + * other details about the transaction + * + * @see + * {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransaction | getTransaction docs} + * + * @example + * const transactionHash = "c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a"; + * server.getTransaction(transactionHash).then((tx) => { + * console.log("status:", tx.status); + * console.log("envelopeXdr:", tx.envelopeXdr); + * console.log("resultMetaXdr:", tx.resultMetaXdr); + * console.log("resultXdr:", tx.resultXdr); + * }); + */ + getTransaction(hash: string): Promise; + _getTransaction(hash: string): Promise; + /** + * Fetch transactions starting from a given start ledger or a cursor. The end ledger is the latest ledger + * in that RPC instance. + * + * @param {Api.GetTransactionsRequest} request - The request parameters. + * @returns {Promise} - A promise that resolves to the transactions response. + * + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransactions + * @example + * server.getTransactions({ + * startLedger: 10000, + * limit: 10, + * }).then((response) => { + * console.log("Transactions:", response.transactions); + * console.log("Latest Ledger:", response.latestLedger); + * console.log("Cursor:", response.cursor); + * }); + */ + getTransactions(request: Api.GetTransactionsRequest): Promise; + private _getTransactions; + /** + * Fetch all events that match a given set of filters. + * + * The given filters (see {@link module:rpc.Api.EventFilter | Api.EventFilter} + * for detailed fields) are combined only in a logical OR fashion, and all of + * the fields in each filter are optional. + * + * To page through events, use the `pagingToken` field on the relevant + * {@link Api.EventResponse} object to set the `cursor` parameter. + * + * @param {module:rpc.Server.GetEventsRequest} request Event filters + * @returns {Promise} A paginatable set of the events + * matching the given event filters + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getEvents | getEvents docs} + * + * @example + * server.getEvents({ + * startLedger: 1000, + * endLedger: 2000, + * filters: [ + * { + * type: "contract", + * contractIds: [ "deadb33f..." ], + * topics: [[ "AAAABQAAAAh0cmFuc2Zlcg==", "AAAAAQB6Mcc=", "*" ]] + * }, { + * type: "system", + * contractIds: [ "...c4f3b4b3..." ], + * topics: [[ "*" ], [ "*", "AAAAAQB6Mcc=" ]] + * }, { + * contractIds: [ "...c4f3b4b3..." ], + * topics: [[ "AAAABQAAAAh0cmFuc2Zlcg==" ]] + * }, { + * type: "diagnostic", + * topics: [[ "AAAAAQB6Mcc=" ]] + * } + * ], + * limit: 10, + * }); + */ + getEvents(request: RpcServer.GetEventsRequest): Promise; + _getEvents(request: RpcServer.GetEventsRequest): Promise; + /** + * Fetch metadata about the network this Soroban RPC server is connected to. + * + * @returns {Promise} Metadata about the current + * network this RPC server is connected to + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getNetwork | getNetwork docs} + * + * @example + * server.getNetwork().then((network) => { + * console.log("friendbotUrl:", network.friendbotUrl); + * console.log("passphrase:", network.passphrase); + * console.log("protocolVersion:", network.protocolVersion); + * }); + */ + getNetwork(): Promise; + /** + * Fetch the latest ledger meta info from network which this Soroban RPC + * server is connected to. + * + * @returns {Promise} metadata about the + * latest ledger on the network that this RPC server is connected to + * + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLatestLedger | getLatestLedger docs} + * + * @example + * server.getLatestLedger().then((response) => { + * console.log("hash:", response.id); + * console.log("sequence:", response.sequence); + * console.log("protocolVersion:", response.protocolVersion); + * }); + */ + getLatestLedger(): Promise; + /** + * Submit a trial contract invocation to get back return values, expected + * ledger footprint, expected authorizations, and expected costs. + * + * @param {Transaction | FeeBumpTransaction} tx the transaction to + * simulate, which should include exactly one operation (one of + * {@link xdr.InvokeHostFunctionOp}, {@link xdr.ExtendFootprintTTLOp}, or + * {@link xdr.RestoreFootprintOp}). Any provided footprint or auth + * information will be ignored. + * @returns {Promise} An object with the + * cost, footprint, result/auth requirements (if applicable), and error of + * the transaction + * + * @see {@link https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/operations-and-transactions | transaction docs} + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction | simulateTransaction docs} + * @see module:rpc.Server#prepareTransaction + * @see module:rpc.assembleTransaction + * + * @example + * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE'; + * const contract = new StellarSdk.Contract(contractId); + * + * // Right now, this is just the default fee for this example. + * const fee = StellarSdk.BASE_FEE; + * const transaction = new StellarSdk.TransactionBuilder(account, { fee }) + * // Uncomment the following line to build transactions for the live network. Be + * // sure to also change the horizon hostname. + * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC) + * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET) + * .setTimeout(30) // valid for the next 30s + * // Add an operation to call increment() on the contract + * .addOperation(contract.call("increment")) + * .build(); + * + * server.simulateTransaction(transaction).then((sim) => { + * console.log("cost:", sim.cost); + * console.log("result:", sim.result); + * console.log("error:", sim.error); + * console.log("latestLedger:", sim.latestLedger); + * }); + */ + simulateTransaction(tx: Transaction | FeeBumpTransaction, addlResources?: RpcServer.ResourceLeeway): Promise; + _simulateTransaction(transaction: Transaction | FeeBumpTransaction, addlResources?: RpcServer.ResourceLeeway): Promise; + /** + * Submit a trial contract invocation, first run a simulation of the contract + * invocation as defined on the incoming transaction, and apply the results to + * a new copy of the transaction which is then returned. Setting the ledger + * footprint and authorization, so the resulting transaction is ready for + * signing & sending. + * + * The returned transaction will also have an updated fee that is the sum of + * fee set on incoming transaction with the contract resource fees estimated + * from simulation. It is advisable to check the fee on returned transaction + * and validate or take appropriate measures for interaction with user to + * confirm it is acceptable. + * + * You can call the {@link module:rpc.Server#simulateTransaction} method + * directly first if you want to inspect estimated fees for a given + * transaction in detail first, then re-assemble it manually or via + * {@link module:rpc.assembleTransaction}. + * + * @param {Transaction | FeeBumpTransaction} tx the transaction to + * prepare. It should include exactly one operation, which must be one of + * {@link xdr.InvokeHostFunctionOp}, {@link xdr.ExtendFootprintTTLOp}, + * or {@link xdr.RestoreFootprintOp}. + * + * Any provided footprint will be overwritten. However, if your operation + * has existing auth entries, they will be preferred over ALL auth entries + * from the simulation. In other words, if you include auth entries, you + * don't care about the auth returned from the simulation. Other fields + * (footprint, etc.) will be filled as normal. + * @returns {Promise} A copy of the + * transaction with the expected authorizations (in the case of + * invocation), resources, and ledger footprints added. The transaction fee + * will also automatically be padded with the contract's minimum resource + * fees discovered from the simulation. + * @throws {jsonrpc.Error|Error|Api.SimulateTransactionErrorResponse} + * If simulation fails + * + * @see module:rpc.assembleTransaction + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction | simulateTransaction docs} + * + * @example + * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE'; + * const contract = new StellarSdk.Contract(contractId); + * + * // Right now, this is just the default fee for this example. + * const fee = StellarSdk.BASE_FEE; + * const transaction = new StellarSdk.TransactionBuilder(account, { fee }) + * // Uncomment the following line to build transactions for the live network. Be + * // sure to also change the horizon hostname. + * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC) + * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET) + * .setTimeout(30) // valid for the next 30s + * // Add an operation to call increment() on the contract + * .addOperation(contract.call("increment")) + * .build(); + * + * const preparedTransaction = await server.prepareTransaction(transaction); + * + * // Sign this transaction with the secret key + * // NOTE: signing is transaction is network specific. Test network transactions + * // won't work in the public network. To switch networks, use the Network object + * // as explained above (look for StellarSdk.Network). + * const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey); + * preparedTransaction.sign(sourceKeypair); + * + * server.sendTransaction(transaction).then(result => { + * console.log("hash:", result.hash); + * console.log("status:", result.status); + * console.log("errorResultXdr:", result.errorResultXdr); + * }); + */ + prepareTransaction(tx: Transaction | FeeBumpTransaction): Promise, import("@stellar/stellar-base").Operation[]>>; + /** + * Submit a real transaction to the Stellar network. + * + * Unlike Horizon, Soroban RPC does not wait for transaction completion. It + * simply validates the transaction and enqueues it. Clients should call + * {@link module:rpc.Server#getTransaction} to learn about transaction + * success/failure. + * + * @param {Transaction | FeeBumpTransaction} transaction to submit + * @returns {Promise} the + * transaction id, status, and any error if available + * + * @see {@link https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/operations-and-transactions | transaction docs} + * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/sendTransaction | sendTransaction docs} + * + * @example + * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE'; + * const contract = new StellarSdk.Contract(contractId); + * + * // Right now, this is just the default fee for this example. + * const fee = StellarSdk.BASE_FEE; + * const transaction = new StellarSdk.TransactionBuilder(account, { fee }) + * // Uncomment the following line to build transactions for the live network. Be + * // sure to also change the horizon hostname. + * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC) + * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET) + * .setTimeout(30) // valid for the next 30s + * // Add an operation to call increment() on the contract + * .addOperation(contract.call("increment")) + * .build(); + * + * // Sign this transaction with the secret key + * // NOTE: signing is transaction is network specific. Test network transactions + * // won't work in the public network. To switch networks, use the Network object + * // as explained above (look for StellarSdk.Network). + * const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey); + * transaction.sign(sourceKeypair); + * + * server.sendTransaction(transaction).then((result) => { + * console.log("hash:", result.hash); + * console.log("status:", result.status); + * console.log("errorResultXdr:", result.errorResultXdr); + * }); + */ + sendTransaction(transaction: Transaction | FeeBumpTransaction): Promise; + _sendTransaction(transaction: Transaction | FeeBumpTransaction): Promise; + /** + * Fund a new account using the network's Friendbot faucet, if any. + * + * @param {string | Account} address The address or account instance that we + * want to create and fund with Friendbot + * @param {string} [friendbotUrl] Optionally, an explicit address for + * friendbot (by default: this calls the Soroban RPC + * {@link module:rpc.Server#getNetwork | getNetwork} method to try to + * discover this network's Friendbot url). + * @returns {Promise} An {@link Account} object for the created + * account, or the existing account if it's already funded with the + * populated sequence number (note that the account will not be "topped + * off" if it already exists) + * @throws If Friendbot is not configured on this network or request failure + * + * @see {@link https://developers.stellar.org/docs/learn/networks#friendbot | Friendbot docs} + * @see {@link module:Friendbot.Api.Response} + * + * @example + * server + * .requestAirdrop("GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4") + * .then((accountCreated) => { + * console.log("accountCreated:", accountCreated); + * }).catch((error) => { + * console.error("error:", error); + * }); + */ + requestAirdrop(address: string | Pick, friendbotUrl?: string): Promise; + /** + * Provides an analysis of the recent fee stats for regular and smart + * contract operations. + * + * @returns {Promise} the fee stats + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getFeeStats + */ + getFeeStats(): Promise; + /** + * Provides information about the current version details of the Soroban RPC and captive-core + * + * @returns {Promise} the version info + * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getVersionInfo + */ + getVersionInfo(): Promise; + /** + * Returns a contract's balance of a particular SAC asset, if any. + * + * This is a convenience wrapper around {@link Server.getLedgerEntries}. + * + * @param {string} contractId the contract ID (string `C...`) whose + * balance of `sac` you want to know + * @param {Asset} sac the built-in SAC token (e.g. `USDC:GABC...`) that + * you are querying from the given `contract`. + * @param {string} [networkPassphrase] optionally, the network passphrase to + * which this token applies. If omitted, a request about network + * information will be made (see {@link getNetwork}), since contract IDs + * for assets are specific to a network. You can refer to {@link Networks} + * for a list of built-in passphrases, e.g., `Networks.TESTNET`. + * + * @returns {Promise}, which will contain the balance + * entry details if and only if the request returned a valid balance ledger + * entry. If it doesn't, the `balanceEntry` field will not exist. + * + * @throws {TypeError} If `contractId` is not a valid contract strkey (C...). + * + * @see getLedgerEntries + * @see https://developers.stellar.org/docs/tokens/stellar-asset-contract + * + * @example + * // assume `contractId` is some contract with an XLM balance + * // assume server is an instantiated `Server` instance. + * const entry = (await server.getSACBalance( + * new Address(contractId), + * Asset.native(), + * Networks.PUBLIC + * )); + * + * // assumes BigInt support: + * console.log( + * entry.balanceEntry ? + * BigInt(entry.balanceEntry.amount) : + * "Contract has no XLM"); + */ + getSACBalance(contractId: string, sac: Asset, networkPassphrase?: string): Promise; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/server.js b/node_modules/@stellar/stellar-sdk/lib/rpc/server.js new file mode 100644 index 000000000..b7b367d32 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/server.js @@ -0,0 +1,896 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SUBMIT_TRANSACTION_TIMEOUT = exports.RpcServer = exports.LinearSleepStrategy = exports.Durability = exports.BasicSleepStrategy = void 0; +var _urijs = _interopRequireDefault(require("urijs")); +var _stellarBase = require("@stellar/stellar-base"); +var _axios = _interopRequireDefault(require("./axios")); +var jsonrpc = _interopRequireWildcard(require("./jsonrpc")); +var _api = require("./api"); +var _transaction = require("./transaction"); +var _parsers = require("./parsers"); +var _utils = require("../utils"); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var SUBMIT_TRANSACTION_TIMEOUT = exports.SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000; +var Durability = exports.Durability = function (Durability) { + Durability["Temporary"] = "temporary"; + Durability["Persistent"] = "persistent"; + return Durability; +}({}); +var DEFAULT_GET_TRANSACTION_TIMEOUT = 30; +var BasicSleepStrategy = exports.BasicSleepStrategy = function BasicSleepStrategy(_iter) { + return 1000; +}; +var LinearSleepStrategy = exports.LinearSleepStrategy = function LinearSleepStrategy(iter) { + return 1000 * iter; +}; +function findCreatedAccountSequenceInTransactionMeta(meta) { + var _operations$flatMap$f; + var operations = []; + switch (meta.switch()) { + case 0: + operations = meta.operations(); + break; + case 1: + case 2: + case 3: + operations = meta.value().operations(); + break; + default: + throw new Error('Unexpected transaction meta switch value'); + } + var sequenceNumber = (_operations$flatMap$f = operations.flatMap(function (op) { + return op.changes(); + }).find(function (c) { + return c.switch() === _stellarBase.xdr.LedgerEntryChangeType.ledgerEntryCreated() && c.created().data().switch() === _stellarBase.xdr.LedgerEntryType.account(); + })) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.created()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.data()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.account()) === null || _operations$flatMap$f === void 0 || (_operations$flatMap$f = _operations$flatMap$f.seqNum()) === null || _operations$flatMap$f === void 0 ? void 0 : _operations$flatMap$f.toString(); + if (sequenceNumber) { + return sequenceNumber; + } + throw new Error('No account created in transaction'); +} +var RpcServer = exports.RpcServer = function () { + function RpcServer(serverURL) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, RpcServer); + this.serverURL = (0, _urijs.default)(serverURL); + if (opts.headers && Object.keys(opts.headers).length !== 0) { + _axios.default.interceptors.request.use(function (config) { + config.headers = Object.assign(config.headers, opts.headers); + return config; + }); + } + if (this.serverURL.protocol() !== 'https' && !opts.allowHttp) { + throw new Error("Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set"); + } + } + return _createClass(RpcServer, [{ + key: "getAccount", + value: (function () { + var _getAccount = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(address) { + var ledgerKey, resp, accountEntry; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + ledgerKey = _stellarBase.xdr.LedgerKey.account(new _stellarBase.xdr.LedgerKeyAccount({ + accountId: _stellarBase.Keypair.fromPublicKey(address).xdrPublicKey() + })); + _context.next = 3; + return this.getLedgerEntries(ledgerKey); + case 3: + resp = _context.sent; + if (!(resp.entries.length === 0)) { + _context.next = 6; + break; + } + return _context.abrupt("return", Promise.reject({ + code: 404, + message: "Account not found: ".concat(address) + })); + case 6: + accountEntry = resp.entries[0].val.account(); + return _context.abrupt("return", new _stellarBase.Account(address, accountEntry.seqNum().toString())); + case 8: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function getAccount(_x) { + return _getAccount.apply(this, arguments); + } + return getAccount; + }()) + }, { + key: "getHealth", + value: (function () { + var _getHealth = _asyncToGenerator(_regeneratorRuntime().mark(function _callee2() { + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getHealth')); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function getHealth() { + return _getHealth.apply(this, arguments); + } + return getHealth; + }()) + }, { + key: "getContractData", + value: (function () { + var _getContractData = _asyncToGenerator(_regeneratorRuntime().mark(function _callee3(contract, key) { + var durability, + scAddress, + xdrDurability, + contractKey, + _args3 = arguments; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + durability = _args3.length > 2 && _args3[2] !== undefined ? _args3[2] : Durability.Persistent; + if (!(typeof contract === 'string')) { + _context3.next = 5; + break; + } + scAddress = new _stellarBase.Contract(contract).address().toScAddress(); + _context3.next = 14; + break; + case 5: + if (!(contract instanceof _stellarBase.Address)) { + _context3.next = 9; + break; + } + scAddress = contract.toScAddress(); + _context3.next = 14; + break; + case 9: + if (!(contract instanceof _stellarBase.Contract)) { + _context3.next = 13; + break; + } + scAddress = contract.address().toScAddress(); + _context3.next = 14; + break; + case 13: + throw new TypeError("unknown contract type: ".concat(contract)); + case 14: + _context3.t0 = durability; + _context3.next = _context3.t0 === Durability.Temporary ? 17 : _context3.t0 === Durability.Persistent ? 19 : 21; + break; + case 17: + xdrDurability = _stellarBase.xdr.ContractDataDurability.temporary(); + return _context3.abrupt("break", 22); + case 19: + xdrDurability = _stellarBase.xdr.ContractDataDurability.persistent(); + return _context3.abrupt("break", 22); + case 21: + throw new TypeError("invalid durability: ".concat(durability)); + case 22: + contractKey = _stellarBase.xdr.LedgerKey.contractData(new _stellarBase.xdr.LedgerKeyContractData({ + key: key, + contract: scAddress, + durability: xdrDurability + })); + return _context3.abrupt("return", this.getLedgerEntries(contractKey).then(function (r) { + if (r.entries.length === 0) { + return Promise.reject({ + code: 404, + message: "Contract data not found. Contract: ".concat(_stellarBase.Address.fromScAddress(scAddress).toString(), ", Key: ").concat(key.toXDR('base64'), ", Durability: ").concat(durability) + }); + } + return r.entries[0]; + })); + case 24: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function getContractData(_x2, _x3) { + return _getContractData.apply(this, arguments); + } + return getContractData; + }()) + }, { + key: "getContractWasmByContractId", + value: (function () { + var _getContractWasmByContractId = _asyncToGenerator(_regeneratorRuntime().mark(function _callee4(contractId) { + var _response$entries$; + var contractLedgerKey, response, wasmHash; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + contractLedgerKey = new _stellarBase.Contract(contractId).getFootprint(); + _context4.next = 3; + return this.getLedgerEntries(contractLedgerKey); + case 3: + response = _context4.sent; + if (!(!response.entries.length || !((_response$entries$ = response.entries[0]) !== null && _response$entries$ !== void 0 && _response$entries$.val))) { + _context4.next = 6; + break; + } + return _context4.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract hash from server" + })); + case 6: + wasmHash = response.entries[0].val.contractData().val().instance().executable().wasmHash(); + return _context4.abrupt("return", this.getContractWasmByHash(wasmHash)); + case 8: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function getContractWasmByContractId(_x4) { + return _getContractWasmByContractId.apply(this, arguments); + } + return getContractWasmByContractId; + }()) + }, { + key: "getContractWasmByHash", + value: (function () { + var _getContractWasmByHash = _asyncToGenerator(_regeneratorRuntime().mark(function _callee5(wasmHash) { + var _responseWasm$entries; + var format, + wasmHashBuffer, + ledgerKeyWasmHash, + responseWasm, + wasmBuffer, + _args5 = arguments; + return _regeneratorRuntime().wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + format = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : undefined; + wasmHashBuffer = typeof wasmHash === "string" ? Buffer.from(wasmHash, format) : wasmHash; + ledgerKeyWasmHash = _stellarBase.xdr.LedgerKey.contractCode(new _stellarBase.xdr.LedgerKeyContractCode({ + hash: wasmHashBuffer + })); + _context5.next = 5; + return this.getLedgerEntries(ledgerKeyWasmHash); + case 5: + responseWasm = _context5.sent; + if (!(!responseWasm.entries.length || !((_responseWasm$entries = responseWasm.entries[0]) !== null && _responseWasm$entries !== void 0 && _responseWasm$entries.val))) { + _context5.next = 8; + break; + } + return _context5.abrupt("return", Promise.reject({ + code: 404, + message: "Could not obtain contract wasm from server" + })); + case 8: + wasmBuffer = responseWasm.entries[0].val.contractCode().code(); + return _context5.abrupt("return", wasmBuffer); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function getContractWasmByHash(_x5) { + return _getContractWasmByHash.apply(this, arguments); + } + return getContractWasmByHash; + }()) + }, { + key: "getLedgerEntries", + value: (function () { + var _getLedgerEntries2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee6() { + var _args6 = arguments; + return _regeneratorRuntime().wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + return _context6.abrupt("return", this._getLedgerEntries.apply(this, _args6).then(_parsers.parseRawLedgerEntries)); + case 1: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function getLedgerEntries() { + return _getLedgerEntries2.apply(this, arguments); + } + return getLedgerEntries; + }()) + }, { + key: "_getLedgerEntries", + value: function () { + var _getLedgerEntries3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee7() { + var _len, + keys, + _key, + _args7 = arguments; + return _regeneratorRuntime().wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + for (_len = _args7.length, keys = new Array(_len), _key = 0; _key < _len; _key++) { + keys[_key] = _args7[_key]; + } + return _context7.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getLedgerEntries', { + keys: keys.map(function (k) { + return k.toXDR('base64'); + }) + })); + case 2: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function _getLedgerEntries() { + return _getLedgerEntries3.apply(this, arguments); + } + return _getLedgerEntries; + }() + }, { + key: "pollTransaction", + value: (function () { + var _pollTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee8(hash, opts) { + var _opts$attempts, _opts$attempts2; + var maxAttempts, foundInfo, attempt, _opts$sleepStrategy; + return _regeneratorRuntime().wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + maxAttempts = ((_opts$attempts = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts !== void 0 ? _opts$attempts : 0) < 1 ? DEFAULT_GET_TRANSACTION_TIMEOUT : (_opts$attempts2 = opts === null || opts === void 0 ? void 0 : opts.attempts) !== null && _opts$attempts2 !== void 0 ? _opts$attempts2 : DEFAULT_GET_TRANSACTION_TIMEOUT; + attempt = 1; + case 2: + if (!(attempt < maxAttempts)) { + _context8.next = 13; + break; + } + _context8.next = 5; + return this.getTransaction(hash); + case 5: + foundInfo = _context8.sent; + if (!(foundInfo.status !== _api.Api.GetTransactionStatus.NOT_FOUND)) { + _context8.next = 8; + break; + } + return _context8.abrupt("return", foundInfo); + case 8: + _context8.next = 10; + return _utils.Utils.sleep(((_opts$sleepStrategy = opts === null || opts === void 0 ? void 0 : opts.sleepStrategy) !== null && _opts$sleepStrategy !== void 0 ? _opts$sleepStrategy : BasicSleepStrategy)(attempt)); + case 10: + attempt++; + _context8.next = 2; + break; + case 13: + return _context8.abrupt("return", foundInfo); + case 14: + case "end": + return _context8.stop(); + } + }, _callee8, this); + })); + function pollTransaction(_x6, _x7) { + return _pollTransaction.apply(this, arguments); + } + return pollTransaction; + }()) + }, { + key: "getTransaction", + value: (function () { + var _getTransaction2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee9(hash) { + return _regeneratorRuntime().wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + return _context9.abrupt("return", this._getTransaction(hash).then(function (raw) { + var foundInfo = {}; + if (raw.status !== _api.Api.GetTransactionStatus.NOT_FOUND) { + Object.assign(foundInfo, (0, _parsers.parseTransactionInfo)(raw)); + } + var result = _objectSpread({ + status: raw.status, + txHash: hash, + latestLedger: raw.latestLedger, + latestLedgerCloseTime: raw.latestLedgerCloseTime, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTime: raw.oldestLedgerCloseTime + }, foundInfo); + return result; + })); + case 1: + case "end": + return _context9.stop(); + } + }, _callee9, this); + })); + function getTransaction(_x8) { + return _getTransaction2.apply(this, arguments); + } + return getTransaction; + }()) + }, { + key: "_getTransaction", + value: function () { + var _getTransaction3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee10(hash) { + return _regeneratorRuntime().wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + return _context10.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getTransaction', { + hash: hash + })); + case 1: + case "end": + return _context10.stop(); + } + }, _callee10, this); + })); + function _getTransaction(_x9) { + return _getTransaction3.apply(this, arguments); + } + return _getTransaction; + }() + }, { + key: "getTransactions", + value: (function () { + var _getTransactions2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee11(request) { + return _regeneratorRuntime().wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + return _context11.abrupt("return", this._getTransactions(request).then(function (raw) { + var result = { + transactions: raw.transactions.map(_parsers.parseRawTransactions), + latestLedger: raw.latestLedger, + latestLedgerCloseTimestamp: raw.latestLedgerCloseTimestamp, + oldestLedger: raw.oldestLedger, + oldestLedgerCloseTimestamp: raw.oldestLedgerCloseTimestamp, + cursor: raw.cursor + }; + return result; + })); + case 1: + case "end": + return _context11.stop(); + } + }, _callee11, this); + })); + function getTransactions(_x10) { + return _getTransactions2.apply(this, arguments); + } + return getTransactions; + }()) + }, { + key: "_getTransactions", + value: function () { + var _getTransactions3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee12(request) { + return _regeneratorRuntime().wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + return _context12.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getTransactions', request)); + case 1: + case "end": + return _context12.stop(); + } + }, _callee12, this); + })); + function _getTransactions(_x11) { + return _getTransactions3.apply(this, arguments); + } + return _getTransactions; + }() + }, { + key: "getEvents", + value: (function () { + var _getEvents2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee13(request) { + return _regeneratorRuntime().wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + return _context13.abrupt("return", this._getEvents(request).then(_parsers.parseRawEvents)); + case 1: + case "end": + return _context13.stop(); + } + }, _callee13, this); + })); + function getEvents(_x12) { + return _getEvents2.apply(this, arguments); + } + return getEvents; + }()) + }, { + key: "_getEvents", + value: function () { + var _getEvents3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee14(request) { + var _request$filters; + return _regeneratorRuntime().wrap(function _callee14$(_context14) { + while (1) switch (_context14.prev = _context14.next) { + case 0: + return _context14.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getEvents', _objectSpread(_objectSpread({ + filters: (_request$filters = request.filters) !== null && _request$filters !== void 0 ? _request$filters : [], + pagination: _objectSpread(_objectSpread({}, request.cursor && { + cursor: request.cursor + }), request.limit && { + limit: request.limit + }) + }, request.startLedger && { + startLedger: request.startLedger + }), request.endLedger && { + endLedger: request.endLedger + }))); + case 1: + case "end": + return _context14.stop(); + } + }, _callee14, this); + })); + function _getEvents(_x13) { + return _getEvents3.apply(this, arguments); + } + return _getEvents; + }() + }, { + key: "getNetwork", + value: (function () { + var _getNetwork = _asyncToGenerator(_regeneratorRuntime().mark(function _callee15() { + return _regeneratorRuntime().wrap(function _callee15$(_context15) { + while (1) switch (_context15.prev = _context15.next) { + case 0: + return _context15.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getNetwork')); + case 1: + case "end": + return _context15.stop(); + } + }, _callee15, this); + })); + function getNetwork() { + return _getNetwork.apply(this, arguments); + } + return getNetwork; + }()) + }, { + key: "getLatestLedger", + value: (function () { + var _getLatestLedger = _asyncToGenerator(_regeneratorRuntime().mark(function _callee16() { + return _regeneratorRuntime().wrap(function _callee16$(_context16) { + while (1) switch (_context16.prev = _context16.next) { + case 0: + return _context16.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getLatestLedger')); + case 1: + case "end": + return _context16.stop(); + } + }, _callee16, this); + })); + function getLatestLedger() { + return _getLatestLedger.apply(this, arguments); + } + return getLatestLedger; + }()) + }, { + key: "simulateTransaction", + value: (function () { + var _simulateTransaction2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee17(tx, addlResources) { + return _regeneratorRuntime().wrap(function _callee17$(_context17) { + while (1) switch (_context17.prev = _context17.next) { + case 0: + return _context17.abrupt("return", this._simulateTransaction(tx, addlResources).then(_parsers.parseRawSimulation)); + case 1: + case "end": + return _context17.stop(); + } + }, _callee17, this); + })); + function simulateTransaction(_x14, _x15) { + return _simulateTransaction2.apply(this, arguments); + } + return simulateTransaction; + }()) + }, { + key: "_simulateTransaction", + value: function () { + var _simulateTransaction3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee18(transaction, addlResources) { + return _regeneratorRuntime().wrap(function _callee18$(_context18) { + while (1) switch (_context18.prev = _context18.next) { + case 0: + return _context18.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'simulateTransaction', _objectSpread({ + transaction: transaction.toXDR() + }, addlResources !== undefined && { + resourceConfig: { + instructionLeeway: addlResources.cpuInstructions + } + }))); + case 1: + case "end": + return _context18.stop(); + } + }, _callee18, this); + })); + function _simulateTransaction(_x16, _x17) { + return _simulateTransaction3.apply(this, arguments); + } + return _simulateTransaction; + }() + }, { + key: "prepareTransaction", + value: (function () { + var _prepareTransaction = _asyncToGenerator(_regeneratorRuntime().mark(function _callee19(tx) { + var simResponse; + return _regeneratorRuntime().wrap(function _callee19$(_context19) { + while (1) switch (_context19.prev = _context19.next) { + case 0: + _context19.next = 2; + return this.simulateTransaction(tx); + case 2: + simResponse = _context19.sent; + if (!_api.Api.isSimulationError(simResponse)) { + _context19.next = 5; + break; + } + throw new Error(simResponse.error); + case 5: + return _context19.abrupt("return", (0, _transaction.assembleTransaction)(tx, simResponse).build()); + case 6: + case "end": + return _context19.stop(); + } + }, _callee19, this); + })); + function prepareTransaction(_x18) { + return _prepareTransaction.apply(this, arguments); + } + return prepareTransaction; + }()) + }, { + key: "sendTransaction", + value: (function () { + var _sendTransaction2 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee20(transaction) { + return _regeneratorRuntime().wrap(function _callee20$(_context20) { + while (1) switch (_context20.prev = _context20.next) { + case 0: + return _context20.abrupt("return", this._sendTransaction(transaction).then(_parsers.parseRawSendTransaction)); + case 1: + case "end": + return _context20.stop(); + } + }, _callee20, this); + })); + function sendTransaction(_x19) { + return _sendTransaction2.apply(this, arguments); + } + return sendTransaction; + }()) + }, { + key: "_sendTransaction", + value: function () { + var _sendTransaction3 = _asyncToGenerator(_regeneratorRuntime().mark(function _callee21(transaction) { + return _regeneratorRuntime().wrap(function _callee21$(_context21) { + while (1) switch (_context21.prev = _context21.next) { + case 0: + return _context21.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'sendTransaction', { + transaction: transaction.toXDR() + })); + case 1: + case "end": + return _context21.stop(); + } + }, _callee21, this); + })); + function _sendTransaction(_x20) { + return _sendTransaction3.apply(this, arguments); + } + return _sendTransaction; + }() + }, { + key: "requestAirdrop", + value: (function () { + var _requestAirdrop = _asyncToGenerator(_regeneratorRuntime().mark(function _callee22(address, friendbotUrl) { + var account, response, meta, txMeta, sequence, _error$response, _error$response$detai; + return _regeneratorRuntime().wrap(function _callee22$(_context22) { + while (1) switch (_context22.prev = _context22.next) { + case 0: + account = typeof address === 'string' ? address : address.accountId(); + _context22.t0 = friendbotUrl; + if (_context22.t0) { + _context22.next = 6; + break; + } + _context22.next = 5; + return this.getNetwork(); + case 5: + _context22.t0 = _context22.sent.friendbotUrl; + case 6: + friendbotUrl = _context22.t0; + if (friendbotUrl) { + _context22.next = 9; + break; + } + throw new Error('No friendbot URL configured for current network'); + case 9: + _context22.prev = 9; + _context22.next = 12; + return _axios.default.post("".concat(friendbotUrl, "?addr=").concat(encodeURIComponent(account))); + case 12: + response = _context22.sent; + if (response.data.result_meta_xdr) { + _context22.next = 22; + break; + } + _context22.next = 16; + return this.getTransaction(response.data.hash); + case 16: + txMeta = _context22.sent; + if (!(txMeta.status !== _api.Api.GetTransactionStatus.SUCCESS)) { + _context22.next = 19; + break; + } + throw new Error("Funding account ".concat(address, " failed")); + case 19: + meta = txMeta.resultMetaXdr; + _context22.next = 23; + break; + case 22: + meta = _stellarBase.xdr.TransactionMeta.fromXDR(response.data.result_meta_xdr, 'base64'); + case 23: + sequence = findCreatedAccountSequenceInTransactionMeta(meta); + return _context22.abrupt("return", new _stellarBase.Account(account, sequence)); + case 27: + _context22.prev = 27; + _context22.t1 = _context22["catch"](9); + if (!(((_error$response = _context22.t1.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 400)) { + _context22.next = 32; + break; + } + if (!((_error$response$detai = _context22.t1.response.detail) !== null && _error$response$detai !== void 0 && _error$response$detai.includes('createAccountAlreadyExist'))) { + _context22.next = 32; + break; + } + return _context22.abrupt("return", this.getAccount(account)); + case 32: + throw _context22.t1; + case 33: + case "end": + return _context22.stop(); + } + }, _callee22, this, [[9, 27]]); + })); + function requestAirdrop(_x21, _x22) { + return _requestAirdrop.apply(this, arguments); + } + return requestAirdrop; + }()) + }, { + key: "getFeeStats", + value: (function () { + var _getFeeStats = _asyncToGenerator(_regeneratorRuntime().mark(function _callee23() { + return _regeneratorRuntime().wrap(function _callee23$(_context23) { + while (1) switch (_context23.prev = _context23.next) { + case 0: + return _context23.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getFeeStats')); + case 1: + case "end": + return _context23.stop(); + } + }, _callee23, this); + })); + function getFeeStats() { + return _getFeeStats.apply(this, arguments); + } + return getFeeStats; + }()) + }, { + key: "getVersionInfo", + value: (function () { + var _getVersionInfo = _asyncToGenerator(_regeneratorRuntime().mark(function _callee24() { + return _regeneratorRuntime().wrap(function _callee24$(_context24) { + while (1) switch (_context24.prev = _context24.next) { + case 0: + return _context24.abrupt("return", jsonrpc.postObject(this.serverURL.toString(), 'getVersionInfo')); + case 1: + case "end": + return _context24.stop(); + } + }, _callee24, this); + })); + function getVersionInfo() { + return _getVersionInfo.apply(this, arguments); + } + return getVersionInfo; + }()) + }, { + key: "getSACBalance", + value: (function () { + var _getSACBalance = _asyncToGenerator(_regeneratorRuntime().mark(function _callee25(contractId, sac, networkPassphrase) { + var passphrase, sacId, key, ledgerKey, response, _response$entries$2, lastModifiedLedgerSeq, liveUntilLedgerSeq, val, entry; + return _regeneratorRuntime().wrap(function _callee25$(_context25) { + while (1) switch (_context25.prev = _context25.next) { + case 0: + if (_stellarBase.StrKey.isValidContract(contractId)) { + _context25.next = 2; + break; + } + throw new TypeError("expected contract ID, got ".concat(contractId)); + case 2: + if (!(networkPassphrase !== null && networkPassphrase !== void 0)) { + _context25.next = 6; + break; + } + _context25.t0 = networkPassphrase; + _context25.next = 9; + break; + case 6: + _context25.next = 8; + return this.getNetwork().then(function (n) { + return n.passphrase; + }); + case 8: + _context25.t0 = _context25.sent; + case 9: + passphrase = _context25.t0; + sacId = sac.contractId(passphrase); + key = _stellarBase.xdr.ScVal.scvVec([(0, _stellarBase.nativeToScVal)("Balance", { + type: "symbol" + }), (0, _stellarBase.nativeToScVal)(contractId, { + type: "address" + })]); + ledgerKey = _stellarBase.xdr.LedgerKey.contractData(new _stellarBase.xdr.LedgerKeyContractData({ + contract: new _stellarBase.Address(sacId).toScAddress(), + durability: _stellarBase.xdr.ContractDataDurability.persistent(), + key: key + })); + _context25.next = 15; + return this.getLedgerEntries(ledgerKey); + case 15: + response = _context25.sent; + if (!(response.entries.length === 0)) { + _context25.next = 18; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 18: + _response$entries$2 = response.entries[0], lastModifiedLedgerSeq = _response$entries$2.lastModifiedLedgerSeq, liveUntilLedgerSeq = _response$entries$2.liveUntilLedgerSeq, val = _response$entries$2.val; + if (!(val.switch().value !== _stellarBase.xdr.LedgerEntryType.contractData().value)) { + _context25.next = 21; + break; + } + return _context25.abrupt("return", { + latestLedger: response.latestLedger + }); + case 21: + entry = (0, _stellarBase.scValToNative)(val.contractData().val()); + return _context25.abrupt("return", { + latestLedger: response.latestLedger, + balanceEntry: { + liveUntilLedgerSeq: liveUntilLedgerSeq, + lastModifiedLedgerSeq: lastModifiedLedgerSeq, + amount: entry.amount.toString(), + authorized: entry.authorized, + clawback: entry.clawback + } + }); + case 23: + case "end": + return _context25.stop(); + } + }, _callee25, this); + })); + function getSACBalance(_x23, _x24, _x25) { + return _getSACBalance.apply(this, arguments); + } + return getSACBalance; + }()) + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/transaction.d.ts b/node_modules/@stellar/stellar-sdk/lib/rpc/transaction.d.ts new file mode 100644 index 000000000..c20ee31ad --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/transaction.d.ts @@ -0,0 +1,21 @@ +import { FeeBumpTransaction, Transaction, TransactionBuilder } from '@stellar/stellar-base'; +import { Api } from './api'; +/** + * Combines the given raw transaction alongside the simulation results. + * If the given transaction already has authorization entries in a host + * function invocation (see {@link Operation.invokeHostFunction}), **the + * simulation entries are ignored**. + * + * If the given transaction already has authorization entries in a host function + * invocation (see {@link Operation.invokeHostFunction}), **the simulation + * entries are ignored**. + * + * @param {Transaction|FeeBumpTransaction} raw the initial transaction, w/o simulation applied + * @param {Api.SimulateTransactionResponse|Api.RawSimulateTransactionResponse} simulation the Soroban RPC simulation result (see {@link module:rpc.Server#simulateTransaction}) + * @returns {TransactionBuilder} a new, cloned transaction with the proper auth and resource (fee, footprint) simulation data applied + * + * @memberof module:rpc + * @see {@link module:rpc.Server#simulateTransaction} + * @see {@link module:rpc.Server#prepareTransaction} + */ +export declare function assembleTransaction(raw: Transaction | FeeBumpTransaction, simulation: Api.SimulateTransactionResponse | Api.RawSimulateTransactionResponse): TransactionBuilder; diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/transaction.js b/node_modules/@stellar/stellar-sdk/lib/rpc/transaction.js new file mode 100644 index 000000000..51bc94e7b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/transaction.js @@ -0,0 +1,53 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.assembleTransaction = assembleTransaction; +var _stellarBase = require("@stellar/stellar-base"); +var _api = require("./api"); +var _parsers = require("./parsers"); +function isSorobanTransaction(tx) { + if (tx.operations.length !== 1) { + return false; + } + switch (tx.operations[0].type) { + case 'invokeHostFunction': + case 'extendFootprintTtl': + case 'restoreFootprint': + return true; + default: + return false; + } +} +function assembleTransaction(raw, simulation) { + if ('innerTransaction' in raw) { + return assembleTransaction(raw.innerTransaction, simulation); + } + if (!isSorobanTransaction(raw)) { + throw new TypeError('unsupported transaction: must contain exactly one ' + 'invokeHostFunction, extendFootprintTtl, or restoreFootprint ' + 'operation'); + } + var success = (0, _parsers.parseRawSimulation)(simulation); + if (!_api.Api.isSimulationSuccess(success)) { + throw new Error("simulation incorrect: ".concat(JSON.stringify(success))); + } + var classicFeeNum = parseInt(raw.fee) || 0; + var minResourceFeeNum = parseInt(success.minResourceFee) || 0; + var txnBuilder = _stellarBase.TransactionBuilder.cloneFrom(raw, { + fee: (classicFeeNum + minResourceFeeNum).toString(), + sorobanData: success.transactionData.build(), + networkPassphrase: raw.networkPassphrase + }); + if (raw.operations[0].type === 'invokeHostFunction') { + var _invokeOp$auth; + txnBuilder.clearOperations(); + var invokeOp = raw.operations[0]; + var existingAuth = (_invokeOp$auth = invokeOp.auth) !== null && _invokeOp$auth !== void 0 ? _invokeOp$auth : []; + txnBuilder.addOperation(_stellarBase.Operation.invokeHostFunction({ + source: invokeOp.source, + func: invokeOp.func, + auth: existingAuth.length > 0 ? existingAuth : success.result.auth + })); + } + return txnBuilder; +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/rpc/utils.d.ts new file mode 100644 index 000000000..e1cc19c4b --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/utils.d.ts @@ -0,0 +1 @@ +export declare function hasOwnProperty(obj: X, prop: Y): obj is X & Record; diff --git a/node_modules/@stellar/stellar-sdk/lib/rpc/utils.js b/node_modules/@stellar/stellar-sdk/lib/rpc/utils.js new file mode 100644 index 000000000..e2148d9bd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/rpc/utils.js @@ -0,0 +1,9 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.hasOwnProperty = hasOwnProperty; +function hasOwnProperty(obj, prop) { + return obj.hasOwnProperty(prop); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/stellartoml/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/stellartoml/index.d.ts new file mode 100644 index 000000000..9309f1dfd --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/stellartoml/index.d.ts @@ -0,0 +1,132 @@ +import { Networks } from "@stellar/stellar-base"; +/** @module StellarToml */ +/** + * The maximum size of stellar.toml file, in bytes + * @constant {number} + * @default 102400 + */ +export declare const STELLAR_TOML_MAX_SIZE: number; +/** + * Resolver allows resolving `stellar.toml` files. + * @memberof module:StellarToml + * @hideconstructor + */ +export declare class Resolver { + /** + * Returns a parsed `stellar.toml` file for a given domain. + * @see {@link https://developers.stellar.org/docs/tokens/publishing-asset-info | Stellar.toml doc} + * + * @param {string} domain Domain to get stellar.toml file for + * @param {object} [opts] Options object + * @param {boolean} [opts.allowHttp=false] - Allow connecting to http servers. This must be set to false in production deployments! + * @param {number} [opts.timeout=0] - Allow a timeout. Allows user to avoid nasty lag due to TOML resolve issue. + * @returns {Promise} A `Promise` that resolves to the parsed stellar.toml object + * + * @example + * StellarSdk.StellarToml.Resolver.resolve('acme.com') + * .then(stellarToml => { + * // stellarToml in an object representing domain stellar.toml file. + * }) + * .catch(error => { + * // stellar.toml does not exist or is invalid + * }); + */ + static resolve(domain: string, opts?: Api.StellarTomlResolveOptions): Promise; +} +export declare namespace Api { + interface StellarTomlResolveOptions { + allowHttp?: boolean; + timeout?: number; + allowedRedirects?: number; + } + type Url = string; + type PublicKey = string; + type ISODateTime = string; + interface Documentation { + ORG_NAME?: string; + ORG_DBA?: string; + ORG_URL?: Url; + ORG_PHONE_NUMBER?: string; + ORG_LOGO?: Url; + ORG_LICENSE_NUMBER?: string; + ORG_LICENSING_AUTHORITY?: string; + ORG_LICENSE_TYPE?: string; + ORG_DESCRIPTION?: string; + ORG_PHYSICAL_ADDRESS?: string; + ORG_PHYSICAL_ADDRESS_ATTESTATION?: string; + ORG_PHONE_NUMBER_ATTESTATION?: string; + ORG_OFFICIAL_EMAIL?: string; + ORG_SUPPORT_EMAIL?: string; + ORG_KEYBASE?: string; + ORG_TWITTER?: string; + ORG_GITHUB?: string; + [key: string]: unknown; + } + interface Principal { + name: string; + email: string; + github?: string; + keybase?: string; + telegram?: string; + twitter?: string; + id_photo_hash?: string; + verification_photo_hash?: string; + [key: string]: unknown; + } + interface Currency { + code?: string; + code_template?: string; + issuer?: PublicKey; + display_decimals?: number; + status?: "live" | "dead" | "test" | "private"; + name?: string; + desc?: string; + conditions?: string; + fixed_number?: number; + max_number?: number; + is_asset_anchored?: boolean; + anchor_asset_type?: "fiat" | "crypto" | "nft" | "stock" | "bond" | "commodity" | "realestate" | "other"; + anchor_asset?: string; + attestation_of_reserve?: Url; + attestation_of_reserve_amount?: string; + attestation_of_reserve_last_audit?: ISODateTime; + is_unlimited?: boolean; + redemption_instructions?: string; + image?: Url; + regulated?: boolean; + collateral_addresses?: string[]; + collateral_address_messages?: string[]; + collateral_address_signatures?: string[]; + approval_server?: Url; + approval_criteria?: string; + [key: string]: unknown; + } + interface Validator { + ALIAS?: string; + DISPLAY_NAME?: string; + PUBLIC_KEY?: PublicKey; + HOST?: string; + HISTORY?: Url; + [key: string]: unknown; + } + interface StellarToml { + VERSION?: string; + ACCOUNTS?: PublicKey[]; + NETWORK_PASSPHRASE?: Networks; + TRANSFER_SERVER_SEP0024?: Url; + TRANSFER_SERVER?: Url; + KYC_SERVER?: Url; + WEB_AUTH_ENDPOINT?: Url; + FEDERATION_SERVER?: Url; + SIGNING_KEY?: PublicKey; + HORIZON_URL?: Url; + URI_REQUEST_SIGNING_KEY?: PublicKey; + DIRECT_PAYMENT_SERVER?: Url; + ANCHOR_QUOTE_SERVER?: Url; + DOCUMENTATION?: Documentation; + PRINCIPALS?: Principal[]; + CURRENCIES?: Currency[]; + VALIDATORS?: Validator[]; + [key: string]: unknown; + } +} diff --git a/node_modules/@stellar/stellar-sdk/lib/stellartoml/index.js b/node_modules/@stellar/stellar-sdk/lib/stellartoml/index.js new file mode 100644 index 000000000..4b5aa2452 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/stellartoml/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.STELLAR_TOML_MAX_SIZE = exports.Resolver = exports.Api = void 0; +var _toml = _interopRequireDefault(require("toml")); +var _httpClient = require("../http-client"); +var _config = require("../config"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } +function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var STELLAR_TOML_MAX_SIZE = exports.STELLAR_TOML_MAX_SIZE = 100 * 1024; +var CancelToken = _httpClient.httpClient.CancelToken; +var Resolver = exports.Resolver = function () { + function Resolver() { + _classCallCheck(this, Resolver); + } + return _createClass(Resolver, null, [{ + key: "resolve", + value: (function () { + var _resolve = _asyncToGenerator(_regeneratorRuntime().mark(function _callee(domain) { + var _opts$allowedRedirect; + var opts, + allowHttp, + timeout, + protocol, + _args = arguments; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + opts = _args.length > 1 && _args[1] !== undefined ? _args[1] : {}; + allowHttp = typeof opts.allowHttp === "undefined" ? _config.Config.isAllowHttp() : opts.allowHttp; + timeout = typeof opts.timeout === "undefined" ? _config.Config.getTimeout() : opts.timeout; + protocol = allowHttp ? "http" : "https"; + return _context.abrupt("return", _httpClient.httpClient.get("".concat(protocol, "://").concat(domain, "/.well-known/stellar.toml"), { + maxRedirects: (_opts$allowedRedirect = opts.allowedRedirects) !== null && _opts$allowedRedirect !== void 0 ? _opts$allowedRedirect : 0, + maxContentLength: STELLAR_TOML_MAX_SIZE, + cancelToken: timeout ? new CancelToken(function (cancel) { + return setTimeout(function () { + return cancel("timeout of ".concat(timeout, "ms exceeded")); + }, timeout); + }) : undefined, + timeout: timeout + }).then(function (response) { + try { + var tomlObject = _toml.default.parse(response.data); + return Promise.resolve(tomlObject); + } catch (e) { + return Promise.reject(new Error("stellar.toml is invalid - Parsing error on line ".concat(e.line, ", column ").concat(e.column, ": ").concat(e.message))); + } + }).catch(function (err) { + if (err.message.match(/^maxContentLength size/)) { + throw new Error("stellar.toml file exceeds allowed size of ".concat(STELLAR_TOML_MAX_SIZE)); + } else { + throw err; + } + })); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + function resolve(_x) { + return _resolve.apply(this, arguments); + } + return resolve; + }()) + }]); +}(); +var Api; \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/utils.d.ts new file mode 100644 index 000000000..68cf6c0c2 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/utils.d.ts @@ -0,0 +1,20 @@ +import { Transaction } from "@stellar/stellar-base"; +/** + * Miscellaneous utilities. + * + * @hideconstructor + */ +export declare class Utils { + /** + * Verifies if the current date is within the transaction's timebounds + * + * @param {Transaction} transaction The transaction whose timebounds will be validated. + * @param {number} [gracePeriod=0] An additional window of time that should be considered valid on either end of the transaction's time range. + * + * @returns {boolean} Returns true if the current time is within the transaction's [minTime, maxTime] range. + * + * @static + */ + static validateTimebounds(transaction: Transaction, gracePeriod?: number): boolean; + static sleep(ms: number): Promise; +} diff --git a/node_modules/@stellar/stellar-sdk/lib/utils.js b/node_modules/@stellar/stellar-sdk/lib/utils.js new file mode 100644 index 000000000..3609eac76 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/utils.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Utils = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +var Utils = exports.Utils = function () { + function Utils() { + _classCallCheck(this, Utils); + } + return _createClass(Utils, null, [{ + key: "validateTimebounds", + value: function validateTimebounds(transaction) { + var gracePeriod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + if (!transaction.timeBounds) { + return false; + } + var now = Math.floor(Date.now() / 1000); + var _transaction$timeBoun = transaction.timeBounds, + minTime = _transaction$timeBoun.minTime, + maxTime = _transaction$timeBoun.maxTime; + return now >= Number.parseInt(minTime, 10) - gracePeriod && now <= Number.parseInt(maxTime, 10) + gracePeriod; + } + }, { + key: "sleep", + value: function sleep(ms) { + return new Promise(function (resolve) { + return setTimeout(resolve, ms); + }); + } + }]); +}(); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/webauth/errors.d.ts b/node_modules/@stellar/stellar-sdk/lib/webauth/errors.d.ts new file mode 100644 index 000000000..0e59f59ee --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/webauth/errors.d.ts @@ -0,0 +1,13 @@ +/** + * InvalidChallengeError is raised when a challenge transaction does not meet + * the requirements for a SEP-10 challenge transaction (for example, a non-zero + * sequence number). + * @memberof module:WebAuth + * @category Errors + * + * @param {string} message Human-readable error message. + */ +export declare class InvalidChallengeError extends Error { + __proto__: InvalidChallengeError; + constructor(message: string); +} diff --git a/node_modules/@stellar/stellar-sdk/lib/webauth/errors.js b/node_modules/@stellar/stellar-sdk/lib/webauth/errors.js new file mode 100644 index 000000000..2542a4449 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/webauth/errors.js @@ -0,0 +1,36 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.InvalidChallengeError = void 0; +function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } +function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } +function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } +function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } +function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } +function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } +function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } +function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } +var InvalidChallengeError = exports.InvalidChallengeError = function (_Error) { + function InvalidChallengeError(message) { + var _this; + _classCallCheck(this, InvalidChallengeError); + var trueProto = (this instanceof InvalidChallengeError ? this.constructor : void 0).prototype; + _this = _callSuper(this, InvalidChallengeError, [message]); + _this.__proto__ = trueProto; + _this.constructor = InvalidChallengeError; + _this.name = "InvalidChallengeError"; + return _this; + } + _inherits(InvalidChallengeError, _Error); + return _createClass(InvalidChallengeError); +}(_wrapNativeSuper(Error)); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/webauth/index.d.ts b/node_modules/@stellar/stellar-sdk/lib/webauth/index.d.ts new file mode 100644 index 000000000..e63282485 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/webauth/index.d.ts @@ -0,0 +1,2 @@ +export * from './utils'; +export { InvalidChallengeError } from './errors'; diff --git a/node_modules/@stellar/stellar-sdk/lib/webauth/index.js b/node_modules/@stellar/stellar-sdk/lib/webauth/index.js new file mode 100644 index 000000000..a0ee4d041 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/webauth/index.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + InvalidChallengeError: true +}; +Object.defineProperty(exports, "InvalidChallengeError", { + enumerable: true, + get: function get() { + return _errors.InvalidChallengeError; + } +}); +var _utils = require("./utils"); +Object.keys(_utils).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _utils[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utils[key]; + } + }); +}); +var _errors = require("./errors"); \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/lib/webauth/utils.d.ts b/node_modules/@stellar/stellar-sdk/lib/webauth/utils.d.ts new file mode 100644 index 000000000..a725201df --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/webauth/utils.d.ts @@ -0,0 +1,307 @@ +/** + * Stellar Web Authentication + * @module WebAuth + * @see {@link https://stellar.org/protocol-10 | SEP-10 Specification} + */ +import { FeeBumpTransaction, Keypair, Transaction } from "@stellar/stellar-base"; +import { ServerApi } from "../horizon/server_api"; +/** + * Returns a valid {@link https://stellar.org/protocol/sep-10 | SEP-10} + * challenge transaction which you can use for Stellar Web Authentication. + * + * @param {Keypair} serverKeypair Keypair for server's signing account. + * @param {string} clientAccountID The stellar account (G...) or muxed account + * (M...) that the wallet wishes to authenticate with the server. + * @param {string} homeDomain The fully qualified domain name of the service + * requiring authentication + * @param {number} [timeout=300] Challenge duration (default to 5 minutes). + * @param {string} networkPassphrase The network passphrase. If you pass this + * argument then timeout is required. + * @param {string} webAuthDomain The fully qualified domain name of the service + * issuing the challenge. + * @param {string} [memo] The memo to attach to the challenge transaction. The + * memo must be of type `id`. If the `clientaccountID` is a muxed account, + * memos cannot be used. + * @param {string} [clientDomain] The fully qualified domain of the client + * requesting the challenge. Only necessary when the the 'client_domain' + * parameter is passed. + * @param {string} [clientSigningKey] The public key assigned to the SIGNING_KEY + * attribute specified on the stellar.toml hosted on the client domain. Only + * necessary when the 'client_domain' parameter is passed. + * @returns {string} A base64 encoded string of the raw TransactionEnvelope xdr + * struct for the transaction. + * @throws {Error} Will throw if `clientAccountID is a muxed account, and `memo` + * is present. + * @throws {Error} Will throw if `clientDomain` is provided, but + * `clientSigningKey` is missing + * + * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth} + * + * @example + * import { Keypair, Networks, WebAuth } from 'stellar-sdk' + * + * let serverKeyPair = Keypair.fromSecret("server-secret") + * let challenge = WebAuth.buildChallengeTx( + * serverKeyPair, + * "client-stellar-account-id", + * "stellar.org", + * 300, + * Networks.TESTNET); + */ +export declare function buildChallengeTx(serverKeypair: Keypair, clientAccountID: string, homeDomain: string, timeout: number | undefined, networkPassphrase: string, webAuthDomain: string, memo?: string | null, clientDomain?: string | null, clientSigningKey?: string | null): string; +/** + * A parsed and validated challenge transaction, and some of its constituent details. + * @memberof module:WebAuth + */ +export type ChallengeTxDetails = { + /** The challenge transaction. */ + tx: Transaction; + /** The Stellar public key (master key) used to sign the Manage Data operation. */ + clientAccountId: string; + /** The matched home domain. */ + matchedHomeDomain: string; + /** The memo attached to the transaction, which will be null if not present */ + memo?: string; +}; +/** + * Reads a SEP-10 challenge transaction and returns the decoded transaction and + * client account ID contained within. + * + * It also verifies that the transaction has been signed by the server. + * + * It does not verify that the transaction has been signed by the client or that + * any signatures other than the server's on the transaction are valid. Use one + * of the following functions to completely verify the transaction: + * + * - {@link module:WebAuth~verifyChallengeTxThreshold} + * - {@link module:WebAuth~verifyChallengeTxSigners} + * + * @param {string} challengeTx SEP0010 challenge transaction in base64. + * @param {string} serverAccountID The server's stellar account (public key). + * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF + * Network ; September 2015' (see {@link Networks}) + * @param {string | Array.} homeDomains The home domain that is expected + * to be included in the first Manage Data operation's string key. If an + * array is provided, one of the domain names in the array must match. + * @param {string} webAuthDomain The home domain that is expected to be included + * as the value of the Manage Data operation with the 'web_auth_domain' key. + * If no such operation is included, this parameter is not used. + * @returns {module:WebAuth.ChallengeTxDetails} The actual transaction and the + * Stellar public key (master key) used to sign the Manage Data operation, + * the matched home domain, and the memo attached to the transaction, which + * will be null if not present. + * + * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth} + */ +export declare function readChallengeTx(challengeTx: string, serverAccountID: string, networkPassphrase: string, homeDomains: string | string[], webAuthDomain: string): { + tx: Transaction; + clientAccountID: string; + matchedHomeDomain: string; + memo: string | null; +}; +/** + * Verifies that for a SEP-10 challenge transaction all signatures on the + * transaction are accounted for and that the signatures meet a threshold on an + * account. A transaction is verified if it is signed by the server account, and + * all other signatures match a signer that has been provided as an argument, + * and those signatures meet a threshold on the account. + * + * Signers that are not prefixed as an address/account ID strkey (G...) will be + * ignored. + * + * Errors will be raised if: + * - The transaction is invalid according to + * {@link module:WebAuth~readChallengeTx}. + * - No client signatures are found on the transaction. + * - One or more signatures in the transaction are not identifiable as the + * server account or one of the signers provided in the arguments. + * - The signatures are all valid but do not meet the threshold. + * + * @param {string} challengeTx SEP0010 challenge transaction in base64. + * @param {string} serverAccountID The server's stellar account (public key). + * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF + * Network ; September 2015' (see {@link Networks}). + * @param {number} threshold The required signatures threshold for verifying + * this transaction. + * @param {Array.} signerSummary a map of all + * authorized signers to their weights. It's used to validate if the + * transaction signatures have met the given threshold. + * @param {string | Array.} homeDomains The home domain(s) that should + * be included in the first Manage Data operation's string key. Required in + * verifyChallengeTxSigners() => readChallengeTx(). + * @param {string} webAuthDomain The home domain that is expected to be included + * as the value of the Manage Data operation with the 'web_auth_domain' key, + * if present. Used in verifyChallengeTxSigners() => readChallengeTx(). + * @returns {Array.} The list of signers public keys that have signed + * the transaction, excluding the server account ID, given that the threshold + * was met. + * @throws {module:WebAuth.InvalidChallengeError} Will throw if the collective + * weight of the transaction's signers does not meet the necessary threshold + * to verify this transaction. + * + * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth} + * + * @example + * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk'; + * + * const serverKP = Keypair.random(); + * const clientKP1 = Keypair.random(); + * const clientKP2 = Keypair.random(); + * + * // Challenge, possibly built in the server side + * const challenge = WebAuth.buildChallengeTx( + * serverKP, + * clientKP1.publicKey(), + * "SDF", + * 300, + * Networks.TESTNET + * ); + * + * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client + * + * // Transaction gathered from a challenge, possibly from the client side + * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET); + * transaction.sign(clientKP1, clientKP2); + * const signedChallenge = transaction + * .toEnvelope() + * .toXDR("base64") + * .toString(); + * + * // Defining the threshold and signerSummary + * const threshold = 3; + * const signerSummary = [ + * { + * key: this.clientKP1.publicKey(), + * weight: 1, + * }, + * { + * key: this.clientKP2.publicKey(), + * weight: 2, + * }, + * ]; + * + * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()] + * WebAuth.verifyChallengeTxThreshold( + * signedChallenge, + * serverKP.publicKey(), + * Networks.TESTNET, + * threshold, + * signerSummary + * ); + */ +export declare function verifyChallengeTxThreshold(challengeTx: string, serverAccountID: string, networkPassphrase: string, threshold: number, signerSummary: ServerApi.AccountRecordSigners[], homeDomains: string | string[], webAuthDomain: string): string[]; +/** + * Verifies that for a SEP 10 challenge transaction all signatures on the + * transaction are accounted for. A transaction is verified if it is signed by + * the server account, and all other signatures match a signer that has been + * provided as an argument (as the accountIDs list). Additional signers can be + * provided that do not have a signature, but all signatures must be matched to + * a signer (accountIDs) for verification to succeed. If verification succeeds, + * a list of signers that were found is returned, not including the server + * account ID. + * + * Signers that are not prefixed as an address/account ID strkey (G...) will be + * ignored. + * + * Errors will be raised if: + * - The transaction is invalid according to + * {@link module:WebAuth~readChallengeTx}. + * - No client signatures are found on the transaction. + * - One or more signatures in the transaction are not identifiable as the + * server account or one of the signers provided in the arguments. + * + * @param {string} challengeTx SEP0010 challenge transaction in base64. + * @param {string} serverAccountID The server's stellar account (public key). + * @param {string} networkPassphrase The network passphrase, e.g.: 'Test SDF + * Network ; September 2015' (see {@link Networks}). + * @param {Array.} signers The signers public keys. This list should + * contain the public keys for all signers that have signed the transaction. + * @param {string | Array.} [homeDomains] The home domain(s) that should + * be included in the first Manage Data operation's string key. Required in + * readChallengeTx(). + * @param {string} webAuthDomain The home domain that is expected to be included + * as the value of the Manage Data operation with the 'web_auth_domain' key, + * if present. Used in readChallengeTx(). + * @returns {Array.} The list of signers public keys that have signed + * the transaction, excluding the server account ID. + * + * @see {@link https://stellar.org/protocol/sep-10|SEP-10: Stellar Web Auth} + * @example + * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk'; + * + * const serverKP = Keypair.random(); + * const clientKP1 = Keypair.random(); + * const clientKP2 = Keypair.random(); + * + * // Challenge, possibly built in the server side + * const challenge = WebAuth.buildChallengeTx( + * serverKP, + * clientKP1.publicKey(), + * "SDF", + * 300, + * Networks.TESTNET + * ); + * + * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client + * + * // Transaction gathered from a challenge, possibly from the client side + * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET); + * transaction.sign(clientKP1, clientKP2); + * const signedChallenge = transaction + * .toEnvelope() + * .toXDR("base64") + * .toString(); + * + * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()] + * WebAuth.verifyChallengeTxSigners( + * signedChallenge, + * serverKP.publicKey(), + * Networks.TESTNET, + * threshold, + * [clientKP1.publicKey(), clientKP2.publicKey()] + * ); + */ +export declare function verifyChallengeTxSigners(challengeTx: string, serverAccountID: string, networkPassphrase: string, signers: string[], homeDomains: string | string[], webAuthDomain: string): string[]; +/** + * Verifies if a transaction was signed by the given account id. + * + * @param {Transaction | FeeBumpTransaction} transaction The signed transaction. + * @param {string} accountID The signer's public key. + * @returns {boolean} Whether or not `accountID` was found to have signed the + * transaction. + * + * @example + * let keypair = Keypair.random(); + * const account = new StellarSdk.Account(keypair.publicKey(), "-1"); + * + * const transaction = new TransactionBuilder(account, { fee: 100 }) + * .setTimeout(30) + * .build(); + * + * transaction.sign(keypair) + * WebAuth.verifyTxSignedBy(transaction, keypair.publicKey()) + */ +export declare function verifyTxSignedBy(transaction: FeeBumpTransaction | Transaction, accountID: string): boolean; +/** + * Checks if a transaction has been signed by one or more of the given signers, + * returning a list of non-repeated signers that were found to have signed the + * given transaction. + * + * @param {Transaction | FeeBumpTransaction} transaction The signed transaction. + * @param {Array.} signers The signer's public keys. + * @returns {Array.} A list of signers that were found to have signed + * the transaction. + * + * @example + * let keypair1 = Keypair.random(); + * let keypair2 = Keypair.random(); + * const account = new StellarSdk.Account(keypair1.publicKey(), "-1"); + * + * const transaction = new TransactionBuilder(account, { fee: 100 }) + * .setTimeout(30) + * .build(); + * + * transaction.sign(keypair1, keypair2) + * WebAuth.gatherTxSigners(transaction, [keypair1.publicKey(), keypair2.publicKey()]) + */ +export declare function gatherTxSigners(transaction: FeeBumpTransaction | Transaction, signers: string[]): string[]; diff --git a/node_modules/@stellar/stellar-sdk/lib/webauth/utils.js b/node_modules/@stellar/stellar-sdk/lib/webauth/utils.js new file mode 100644 index 000000000..bc35281aa --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/lib/webauth/utils.js @@ -0,0 +1,332 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildChallengeTx = buildChallengeTx; +exports.gatherTxSigners = gatherTxSigners; +exports.readChallengeTx = readChallengeTx; +exports.verifyChallengeTxSigners = verifyChallengeTxSigners; +exports.verifyChallengeTxThreshold = verifyChallengeTxThreshold; +exports.verifyTxSignedBy = verifyTxSignedBy; +var _randombytes = _interopRequireDefault(require("randombytes")); +var _stellarBase = require("@stellar/stellar-base"); +var _utils = require("../utils"); +var _errors = require("./errors"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } +function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _toArray(r) { return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } +function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } +function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } +function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } +function buildChallengeTx(serverKeypair, clientAccountID, homeDomain) { + var timeout = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 300; + var networkPassphrase = arguments.length > 4 ? arguments[4] : undefined; + var webAuthDomain = arguments.length > 5 ? arguments[5] : undefined; + var memo = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; + var clientDomain = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; + var clientSigningKey = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; + if (clientAccountID.startsWith("M") && memo) { + throw Error("memo cannot be used if clientAccountID is a muxed account"); + } + var account = new _stellarBase.Account(serverKeypair.publicKey(), "-1"); + var now = Math.floor(Date.now() / 1000); + var value = (0, _randombytes.default)(48).toString("base64"); + var builder = new _stellarBase.TransactionBuilder(account, { + fee: _stellarBase.BASE_FEE, + networkPassphrase: networkPassphrase, + timebounds: { + minTime: now, + maxTime: now + timeout + } + }).addOperation(_stellarBase.Operation.manageData({ + name: "".concat(homeDomain, " auth"), + value: value, + source: clientAccountID + })).addOperation(_stellarBase.Operation.manageData({ + name: "web_auth_domain", + value: webAuthDomain, + source: account.accountId() + })); + if (clientDomain) { + if (!clientSigningKey) { + throw Error("clientSigningKey is required if clientDomain is provided"); + } + builder.addOperation(_stellarBase.Operation.manageData({ + name: "client_domain", + value: clientDomain, + source: clientSigningKey + })); + } + if (memo) { + builder.addMemo(_stellarBase.Memo.id(memo)); + } + var transaction = builder.build(); + transaction.sign(serverKeypair); + return transaction.toEnvelope().toXDR("base64").toString(); +} +function readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain) { + var _transaction$timeBoun; + if (serverAccountID.startsWith("M")) { + throw Error("Invalid serverAccountID: multiplexed accounts are not supported."); + } + var transaction; + try { + transaction = new _stellarBase.Transaction(challengeTx, networkPassphrase); + } catch (_unused) { + try { + transaction = new _stellarBase.FeeBumpTransaction(challengeTx, networkPassphrase); + } catch (_unused2) { + throw new _errors.InvalidChallengeError("Invalid challenge: unable to deserialize challengeTx transaction string"); + } + throw new _errors.InvalidChallengeError("Invalid challenge: expected a Transaction but received a FeeBumpTransaction"); + } + var sequence = Number.parseInt(transaction.sequence, 10); + if (sequence !== 0) { + throw new _errors.InvalidChallengeError("The transaction sequence number should be zero"); + } + if (transaction.source !== serverAccountID) { + throw new _errors.InvalidChallengeError("The transaction source account is not equal to the server's account"); + } + if (transaction.operations.length < 1) { + throw new _errors.InvalidChallengeError("The transaction should contain at least one operation"); + } + var _transaction$operatio = _toArray(transaction.operations), + operation = _transaction$operatio[0], + subsequentOperations = _transaction$operatio.slice(1); + if (!operation.source) { + throw new _errors.InvalidChallengeError("The transaction's operation should contain a source account"); + } + var clientAccountID = operation.source; + var memo = null; + if (transaction.memo.type !== _stellarBase.MemoNone) { + if (clientAccountID.startsWith("M")) { + throw new _errors.InvalidChallengeError("The transaction has a memo but the client account ID is a muxed account"); + } + if (transaction.memo.type !== _stellarBase.MemoID) { + throw new _errors.InvalidChallengeError("The transaction's memo must be of type `id`"); + } + memo = transaction.memo.value; + } + if (operation.type !== "manageData") { + throw new _errors.InvalidChallengeError("The transaction's operation type should be 'manageData'"); + } + if (transaction.timeBounds && Number.parseInt((_transaction$timeBoun = transaction.timeBounds) === null || _transaction$timeBoun === void 0 ? void 0 : _transaction$timeBoun.maxTime, 10) === _stellarBase.TimeoutInfinite) { + throw new _errors.InvalidChallengeError("The transaction requires non-infinite timebounds"); + } + if (!_utils.Utils.validateTimebounds(transaction, 60 * 5)) { + throw new _errors.InvalidChallengeError("The transaction has expired"); + } + if (operation.value === undefined) { + throw new _errors.InvalidChallengeError("The transaction's operation values should not be null"); + } + if (!operation.value) { + throw new _errors.InvalidChallengeError("The transaction's operation value should not be null"); + } + if (Buffer.from(operation.value.toString(), "base64").length !== 48) { + throw new _errors.InvalidChallengeError("The transaction's operation value should be a 64 bytes base64 random string"); + } + if (!homeDomains) { + throw new _errors.InvalidChallengeError("Invalid homeDomains: a home domain must be provided for verification"); + } + var matchedHomeDomain; + if (typeof homeDomains === "string") { + if ("".concat(homeDomains, " auth") === operation.name) { + matchedHomeDomain = homeDomains; + } + } else if (Array.isArray(homeDomains)) { + matchedHomeDomain = homeDomains.find(function (domain) { + return "".concat(domain, " auth") === operation.name; + }); + } else { + throw new _errors.InvalidChallengeError("Invalid homeDomains: homeDomains type is ".concat(_typeof(homeDomains), " but should be a string or an array")); + } + if (!matchedHomeDomain) { + throw new _errors.InvalidChallengeError("Invalid homeDomains: the transaction's operation key name does not match the expected home domain"); + } + var _iterator = _createForOfIteratorHelper(subsequentOperations), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var op = _step.value; + if (op.type !== "manageData") { + throw new _errors.InvalidChallengeError("The transaction has operations that are not of type 'manageData'"); + } + if (op.source !== serverAccountID && op.name !== "client_domain") { + throw new _errors.InvalidChallengeError("The transaction has operations that are unrecognized"); + } + if (op.name === "web_auth_domain") { + if (op.value === undefined) { + throw new _errors.InvalidChallengeError("'web_auth_domain' operation value should not be null"); + } + if (op.value.compare(Buffer.from(webAuthDomain))) { + throw new _errors.InvalidChallengeError("'web_auth_domain' operation value does not match ".concat(webAuthDomain)); + } + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + if (!verifyTxSignedBy(transaction, serverAccountID)) { + throw new _errors.InvalidChallengeError("Transaction not signed by server: '".concat(serverAccountID, "'")); + } + return { + tx: transaction, + clientAccountID: clientAccountID, + matchedHomeDomain: matchedHomeDomain, + memo: memo + }; +} +function verifyChallengeTxThreshold(challengeTx, serverAccountID, networkPassphrase, threshold, signerSummary, homeDomains, webAuthDomain) { + var signers = signerSummary.map(function (signer) { + return signer.key; + }); + var signersFound = verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain); + var weight = 0; + var _loop = function _loop() { + var _signerSummary$find; + var signer = _signersFound[_i]; + var sigWeight = ((_signerSummary$find = signerSummary.find(function (s) { + return s.key === signer; + })) === null || _signerSummary$find === void 0 ? void 0 : _signerSummary$find.weight) || 0; + weight += sigWeight; + }; + for (var _i = 0, _signersFound = signersFound; _i < _signersFound.length; _i++) { + _loop(); + } + if (weight < threshold) { + throw new _errors.InvalidChallengeError("signers with weight ".concat(weight, " do not meet threshold ").concat(threshold, "\"")); + } + return signersFound; +} +function verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain) { + var _readChallengeTx = readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain), + tx = _readChallengeTx.tx; + var serverKP; + try { + serverKP = _stellarBase.Keypair.fromPublicKey(serverAccountID); + } catch (err) { + throw new Error("Couldn't infer keypair from the provided 'serverAccountID': ".concat(err.message)); + } + var clientSigners = new Set(); + var _iterator2 = _createForOfIteratorHelper(signers), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var _signer = _step2.value; + if (_signer === serverKP.publicKey()) { + continue; + } + if (_signer.charAt(0) !== "G") { + continue; + } + clientSigners.add(_signer); + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + if (clientSigners.size === 0) { + throw new _errors.InvalidChallengeError("No verifiable client signers provided, at least one G... address must be provided"); + } + var clientSigningKey; + var _iterator3 = _createForOfIteratorHelper(tx.operations), + _step3; + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + var op = _step3.value; + if (op.type === "manageData" && op.name === "client_domain") { + if (clientSigningKey) { + throw new _errors.InvalidChallengeError("Found more than one client_domain operation"); + } + clientSigningKey = op.source; + } + } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); + } + var allSigners = [serverKP.publicKey()].concat(_toConsumableArray(Array.from(clientSigners))); + if (clientSigningKey) { + allSigners.push(clientSigningKey); + } + var signersFound = gatherTxSigners(tx, allSigners); + var serverSignatureFound = false; + var clientSigningKeySignatureFound = false; + for (var _i2 = 0, _signersFound2 = signersFound; _i2 < _signersFound2.length; _i2++) { + var signer = _signersFound2[_i2]; + if (signer === serverKP.publicKey()) { + serverSignatureFound = true; + } + if (signer === clientSigningKey) { + clientSigningKeySignatureFound = true; + } + } + if (!serverSignatureFound) { + throw new _errors.InvalidChallengeError("Transaction not signed by server: '".concat(serverKP.publicKey(), "'")); + } + if (clientSigningKey && !clientSigningKeySignatureFound) { + throw new _errors.InvalidChallengeError("Transaction not signed by the source account of the 'client_domain' " + "ManageData operation"); + } + if (signersFound.length === 1) { + throw new _errors.InvalidChallengeError("None of the given signers match the transaction signatures"); + } + if (signersFound.length !== tx.signatures.length) { + throw new _errors.InvalidChallengeError("Transaction has unrecognized signatures"); + } + signersFound.splice(signersFound.indexOf(serverKP.publicKey()), 1); + if (clientSigningKey) { + signersFound.splice(signersFound.indexOf(clientSigningKey), 1); + } + return signersFound; +} +function verifyTxSignedBy(transaction, accountID) { + return gatherTxSigners(transaction, [accountID]).length !== 0; +} +function gatherTxSigners(transaction, signers) { + var hashedSignatureBase = transaction.hash(); + var txSignatures = _toConsumableArray(transaction.signatures); + var signersFound = new Set(); + var _iterator4 = _createForOfIteratorHelper(signers), + _step4; + try { + for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { + var signer = _step4.value; + if (txSignatures.length === 0) { + break; + } + var keypair = void 0; + try { + keypair = _stellarBase.Keypair.fromPublicKey(signer); + } catch (err) { + throw new _errors.InvalidChallengeError("Signer is not a valid address: ".concat(err.message)); + } + for (var i = 0; i < txSignatures.length; i++) { + var decSig = txSignatures[i]; + if (!decSig.hint().equals(keypair.signatureHint())) { + continue; + } + if (keypair.verify(hashedSignatureBase, decSig.signature())) { + signersFound.add(signer); + txSignatures.splice(i, 1); + break; + } + } + } + } catch (err) { + _iterator4.e(err); + } finally { + _iterator4.f(); + } + return Array.from(signersFound); +} \ No newline at end of file diff --git a/node_modules/@stellar/stellar-sdk/package.json b/node_modules/@stellar/stellar-sdk/package.json new file mode 100644 index 000000000..e87484f5d --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/package.json @@ -0,0 +1,225 @@ +{ + "name": "@stellar/stellar-sdk", + "version": "13.1.0", + "description": "A library for working with the Stellar network, including communication with the Horizon and Soroban RPC servers.", + "keywords": [ + "stellar" + ], + "homepage": "https://github.com/stellar/js-stellar-sdk", + "bugs": { + "url": "https://github.com/stellar/js-stellar-sdk/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/stellar/js-stellar-sdk.git" + }, + "license": "Apache-2.0", + "author": "Stellar Development Foundation ", + "main": "./lib/index.js", + "types": "./lib/index.d.ts", + "browser": "./dist/stellar-sdk.min.js", + "files": [ + "/types", + "/lib", + "/dist" + ], + "exports": { + ".": { + "browser": "./dist/stellar-sdk.min.js", + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "./contract": { + "types": "./lib/contract/index.d.ts", + "default": "./lib/contract/index.js" + }, + "./rpc": { + "types": "./lib/rpc/index.d.ts", + "default": "./lib/rpc/index.js" + }, + "./no-axios": { + "browser": "./dist/stellar-sdk-no-axios.min.js", + "types": "./lib/no-axios/index.d.ts", + "default": "./lib/no-axios/index.js" + }, + "./no-axios/contract": { + "types": "./lib/no-axios/contract/index.d.ts", + "default": "./lib/no-axios/contract/index.js" + }, + "./no-axios/rpc": { + "types": "./lib/no-axios/rpc/index.d.ts", + "default": "./lib/no-axios/rpc/index.js" + }, + "./no-eventsource": { + "browser": "./dist/stellar-sdk-no-eventsource.min.js", + "types": "./lib/no-eventsource/index.d.ts", + "default": "./lib/no-eventsource/index.js" + }, + "./no-eventsource/contract": { + "types": "./lib/no-eventsource/contract/index.d.ts", + "default": "./lib/no-eventsource/contract/index.js" + }, + "./no-eventsource/rpc": { + "types": "./lib/no-eventsource/rpc/index.d.ts", + "default": "./lib/no-eventsource/rpc/index.js" + }, + "./minimal": { + "browser": "./dist/stellar-sdk-minimal.min.js", + "types": "./lib/minimal/index.d.ts", + "default": "./lib/minimal/index.js" + }, + "./minimal/contract": { + "types": "./lib/minimal/contract/index.d.ts", + "default": "./lib/minimal/contract/index.js" + }, + "./minimal/rpc": { + "types": "./lib/minimal/rpc/index.d.ts", + "default": "./lib/minimal/rpc/index.js" + } + }, + "scripts": { + "build": "cross-env NODE_ENV=development yarn _build", + "build:prod": "cross-env NODE_ENV=production yarn _build", + "build:node": "yarn _babel && yarn build:ts", + "build:node:no-axios": "cross-env OUTPUT_DIR=lib/no-axios USE_AXIOS=false yarn build:node", + "build:node:no-eventsource": "cross-env OUTPUT_DIR=lib/no-eventsource USE_EVENTSOURCE=false yarn build:node", + "build:node:minimal": "cross-env OUTPUT_DIR=lib/minimal USE_AXIOS=false USE_EVENTSOURCE=false yarn build:node", + "build:node:all": "yarn build:node && yarn build:node:no-axios && yarn build:node:no-eventsource && yarn build:node:minimal", + "clean:temp": "rm -f ./config/tsconfig.tmp.json", + "build:ts": "node config/set-output-dir.js && tsc -p ./config/tsconfig.tmp.json && yarn clean:temp", + "build:test": "tsc -p ./test/unit/tsconfig.json", + "build:browser": "webpack -c config/webpack.config.browser.js", + "build:browser:no-axios": "cross-env USE_AXIOS=false webpack -c config/webpack.config.browser.js", + "build:browser:no-eventsource": "cross-env USE_EVENTSOURCE=false webpack -c config/webpack.config.browser.js", + "build:browser:minimal": "cross-env USE_AXIOS=false USE_EVENTSOURCE=false webpack -c config/webpack.config.browser.js", + "build:browser:all": "yarn build:browser && cross-env no_clean=true yarn build:browser:no-axios && cross-env no_clean=true yarn build:browser:no-eventsource && cross-env no_clean=true yarn build:browser:minimal", + "build:docs": "cross-env NODE_ENV=docs yarn _babel", + "clean": "rm -rf lib/ dist/ coverage/ .nyc_output/ jsdoc/ test/e2e/.soroban", + "docs": "yarn build:docs && jsdoc -c ./config/.jsdoc.json", + "test": "yarn build:test && yarn test:node && yarn test:integration && yarn test:browser", + "test:e2e": "./test/e2e/initialize.sh && yarn _nyc mocha --recursive 'test/e2e/src/test-*.js'", + "test:node": "yarn _nyc mocha --recursive 'test/unit/**/*.js'", + "test:integration": "yarn _nyc mocha --recursive 'test/integration/**/*.js'", + "test:browser": "karma start config/karma.conf.js", + "test:browser:no-axios": "cross-env USE_AXIOS=false yarn build:browser && cross-env USE_AXIOS=false karma start config/karma.conf.js", + "fmt": "yarn _prettier && yarn eslint -c .eslintrc.js src/ --fix", + "preversion": "yarn clean && yarn _prettier && yarn build:prod && yarn test", + "prepare": "yarn build:prod", + "_build": "yarn build:node:all && yarn build:test && yarn build:browser:all", + "_babel": "babel --extensions '.ts' --out-dir ${OUTPUT_DIR:-lib} src/", + "_nyc": "nyc --nycrc-path config/.nycrc", + "_prettier": "prettier --ignore-path config/.prettierignore --write './test/**/*.js'" + }, + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "**/*.{js,json,ts}": [ + "yarn fmt" + ] + }, + "mocha": { + "reporter": "spec", + "require": [ + "@babel/register", + "test/test-nodejs.js", + "dotenv/config" + ], + "exclude": [ + "test/test-browser.js" + ], + "sort": true, + "recursive": true, + "timeout": 120000 + }, + "nyc": { + "instrument": false, + "sourceMap": false, + "reporter": [ + "text-summary" + ] + }, + "devDependencies": { + "@babel/cli": "^7.26.4", + "@babel/core": "^7.26.0", + "@babel/eslint-plugin": "^7.25.9", + "@babel/preset-env": "^7.26.0", + "@babel/preset-typescript": "^7.26.0", + "@babel/register": "^7.25.9", + "@definitelytyped/dtslint": "^0.2.28", + "@istanbuljs/nyc-config-babel": "3.0.0", + "@stellar/tsconfig": "^1.0.2", + "@types/chai": "^4.3.19", + "@types/detect-node": "^2.0.0", + "@types/eventsource": "^1.1.12", + "@types/json-schema": "^7.0.15", + "@types/lodash": "^4.17.13", + "@types/mocha": "^10.0.9", + "@types/node": "^20.14.11", + "@types/randombytes": "^2.0.1", + "@types/sinon": "^17.0.2", + "@types/urijs": "^1.19.20", + "@typescript-eslint/parser": "^7.16.1", + "axios-mock-adapter": "^1.22.0", + "babel-loader": "^9.1.3", + "babel-plugin-istanbul": "^7.0.0", + "babel-plugin-transform-define": "^2.1.4", + "better-docs": "^2.7.3", + "buffer": "^6.0.3", + "chai": "^4.3.10", + "chai-as-promised": "^7.1.1", + "chai-http": "^4.3.0", + "cross-env": "^7.0.3", + "dotenv": "^16.4.7", + "eslint": "^8.57.0", + "eslint-config-airbnb-base": "^15.0.0", + "eslint-config-airbnb-typescript": "^18.0.0", + "eslint-config-prettier": "^9.0.0", + "eslint-plugin-import": "^2.30.0", + "eslint-plugin-jsdoc": "^48.8.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-prefer-import": "^0.0.1", + "eslint-plugin-prettier": "^5.2.1", + "eslint-webpack-plugin": "^4.2.0", + "ghooks": "^2.0.4", + "husky": "^9.1.6", + "jsdoc": "^4.0.4", + "json-schema-faker": "^0.5.8", + "karma": "^6.4.3", + "karma-chai": "^0.1.0", + "karma-chrome-launcher": "^3.1.0", + "karma-coverage": "^2.2.1", + "karma-firefox-launcher": "^2.1.3", + "karma-mocha": "^2.0.0", + "karma-sinon-chai": "^2.0.2", + "karma-webpack": "^5.0.1", + "lint-staged": "^15.2.11", + "lodash": "^4.17.21", + "mocha": "^10.8.2", + "node-polyfill-webpack-plugin": "^3.0.0", + "null-loader": "^4.0.1", + "nyc": "^17.0.0", + "prettier": "^3.4.2", + "randombytes": "^2.1.0", + "sinon": "^17.0.1", + "sinon-chai": "^3.7.0", + "taffydb": "^2.7.3", + "terser-webpack-plugin": "^5.3.11", + "ts-node": "^10.9.2", + "typescript": "^5.6.3", + "webpack": "^5.97.1", + "webpack-cli": "^5.0.1" + }, + "dependencies": { + "@stellar/stellar-base": "^13.0.1", + "axios": "^1.7.9", + "bignumber.js": "^9.1.2", + "eventsource": "^2.0.2", + "feaxios": "^0.0.23", + "randombytes": "^2.1.0", + "toml": "^3.0.0", + "urijs": "^1.19.1" + } +} diff --git a/node_modules/@stellar/stellar-sdk/types/dom-monkeypatch.d.ts b/node_modules/@stellar/stellar-sdk/types/dom-monkeypatch.d.ts new file mode 100644 index 000000000..1a2287ef5 --- /dev/null +++ b/node_modules/@stellar/stellar-sdk/types/dom-monkeypatch.d.ts @@ -0,0 +1,126 @@ +/** + * Problem: stellar-sdk doesn't depend on browser env but the types do. + * Workaround: Copy/paste subset of interfaces from `dom.d.ts` (TS v3.4.5): + * - `MessageEvent` already comes from `eventsource`. + * - `EventListener` used at `src/call_builder.ts`. + * - `EventSource` used at `src/call_builder.ts`. + */ + +interface EventSourceEventMap { + error: Event; + message: MessageEvent; + open: Event; +} + +interface EventSource extends EventTarget { + onerror: ((this: EventSource, ev: Event) => any) | null; + onmessage: ((this: EventSource, ev: MessageEvent) => any) | null; + onopen: ((this: EventSource, ev: Event) => any) | null; + /** + * Returns the state of this EventSource object's connection. It can have the + * values described below. + */ + readonly readyState: number; + /** + * Returns the URL providing the event stream. + */ + readonly url: string; + /** + * Returns true if the credentials mode + * for connection requests to the URL providing the + * event stream is set to "include", and false otherwise. + */ + readonly withCredentials: boolean; + readonly CLOSED: number; + readonly CONNECTING: number; + readonly OPEN: number; + close(): void; + addEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | AddEventListenerOptions, + ): void; + addEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void; + removeEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | EventListenerOptions, + ): void; + removeEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: boolean | EventListenerOptions, + ): void; +} + +interface EventListener { + // tslint:disable-next-line: callable-types + (evt: Event): void; +} + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface EventListenerOptions { + capture?: boolean; +} + +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; +} + +/** EventTarget is an interface implemented by objects that can receive events and may have listeners for them. */ +interface EventTarget { + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * The options argument sets listener-specific options. For compatibility this can be a + * boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in §2.8 Observing event listeners. + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will + * be removed. + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + */ + addEventListener( + type: string, + listener: EventListener | EventListenerObject | null, + options?: boolean | AddEventListenerOptions, + ): void; + /** + * Dispatches a synthetic event event to target and returns true + * if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + */ + dispatchEvent(event: Event): boolean; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + */ + removeEventListener( + type: string, + callback: EventListener | EventListenerObject | null, + options?: EventListenerOptions | boolean, + ): void; +} + +/** The Event interface represents any event which takes place in the DOM; some are user-generated (such as mouse or keyboard events), while others are generated by APIs (such as events that indicate an animation has finished running, a video has been paused, and so forth). While events are usually triggered by such "external" sources, they can also be triggered programmatically, such as by calling the HTMLElement.click() method of an element, or by defining the event, then sending it to a specified target using EventTarget.dispatchEvent(). There are many types of events, some of which use other interfaces based on the main Event interface. Event itself contains the properties and methods which are common to all events. */ +interface Event { + // Already partially declared at `@types/eventsource/dom-monkeypatch.d.ts`. + + /** + * Returns the object whose event listener's callback is currently being + * invoked. + */ + readonly currentTarget: EventTarget | null; + /** @deprecated */ + readonly srcElement: EventTarget | null; + /** + * Returns the object to which event is dispatched (its target). + */ + readonly target: EventTarget | null; + composedPath(): EventTarget[]; +} diff --git a/node_modules/assertion-error/LICENSE b/node_modules/assertion-error/LICENSE new file mode 100644 index 000000000..5e9f3ac63 --- /dev/null +++ b/node_modules/assertion-error/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Jake Luer jake@qualiancy.com (http://qualiancy.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. diff --git a/node_modules/assertion-error/README.md b/node_modules/assertion-error/README.md new file mode 100644 index 000000000..37c392879 --- /dev/null +++ b/node_modules/assertion-error/README.md @@ -0,0 +1,68 @@ +

+ AssertionError and AssertionResult classes. +

+ +

+ + build:? + + downloads:? + + devDependencies:none + +

+ +## What is AssertionError? + +Assertion Error is a module that contains two classes: `AssertionError`, which +is an instance of an `Error`, and `AssertionResult` which is not an instance of +Error. + +These can be useful for returning from a function - if the function "succeeds" +return an `AssertionResult` and if the function fails return (or throw) an +`AssertionError`. + +Both `AssertionError` and `AssertionResult` implement the `Result` interface: + +```typescript +interface Result { + name: "AssertionError" | "AssertionResult"; + ok: boolean; + toJSON(...args: unknown[]): Record; +} +``` + +So if a function returns `AssertionResult | AssertionError` it is easy to check +_which_ one is returned by checking either `.name` or `.ok`, or check +`instanceof Error`. + +## Installation + +### Node.js + +`assertion-error` is available on [npm](http://npmjs.org). + +``` +$ npm install --save assertion-error +``` + +### Deno + +`assertion_error` is available on +[Deno.land](https://deno.land/x/assertion_error) + +```typescript +import { + AssertionError, + AssertionResult, +} from "https://deno.land/x/assertion_error@2.0.0/mod.ts"; +``` diff --git a/node_modules/assertion-error/index.d.ts b/node_modules/assertion-error/index.d.ts new file mode 100644 index 000000000..d8fda2c78 --- /dev/null +++ b/node_modules/assertion-error/index.d.ts @@ -0,0 +1,27 @@ +interface Result { + name: "AssertionError" | "AssertionResult"; + ok: boolean; + toJSON(...args: unknown[]): Record; +} + +declare class AssertionError extends Error implements Result { + [key: string]: unknown + name: "AssertionError"; + ok: false; + message: string; + // deno-lint-ignore ban-types + constructor(message: string, props?: T, ssf?: Function); + stack: string; + toJSON(stack?: boolean): Record; +} + +declare class AssertionResult implements Result { + [key: string]: unknown + name: "AssertionResult"; + ok: true; + message: string; + constructor(props?: T); + toJSON(): Record; +} + +export { AssertionError, AssertionResult, Result }; diff --git a/node_modules/assertion-error/index.js b/node_modules/assertion-error/index.js new file mode 100644 index 000000000..2bfcb81ed --- /dev/null +++ b/node_modules/assertion-error/index.js @@ -0,0 +1,60 @@ +// deno-fmt-ignore-file +// deno-lint-ignore-file +// This code was bundled using `deno bundle` and it's not recommended to edit it manually + +const canElideFrames = "captureStackTrace" in Error; +class AssertionError extends Error { + message; + get name() { + return "AssertionError"; + } + get ok() { + return false; + } + constructor(message = "Unspecified AssertionError", props, ssf){ + super(message); + this.message = message; + if (canElideFrames) { + Error.captureStackTrace(this, ssf || AssertionError); + } + for(const key in props){ + if (!(key in this)) { + this[key] = props[key]; + } + } + } + toJSON(stack) { + return { + ...this, + name: this.name, + message: this.message, + ok: false, + stack: stack !== false ? this.stack : undefined + }; + } +} +class AssertionResult { + get name() { + return "AssertionResult"; + } + get ok() { + return true; + } + constructor(props){ + for(const key in props){ + if (!(key in this)) { + this[key] = props[key]; + } + } + } + toJSON() { + return { + ...this, + name: this.name, + ok: this.ok + }; + } +} +export { AssertionError as AssertionError }; +export { AssertionResult as AssertionResult }; + diff --git a/node_modules/assertion-error/package.json b/node_modules/assertion-error/package.json new file mode 100644 index 000000000..02dc0f5b6 --- /dev/null +++ b/node_modules/assertion-error/package.json @@ -0,0 +1,32 @@ +{ + "name": "assertion-error", + "version": "2.0.1", + "description": "Error constructor for test and validation frameworks that implements standardized AssertionError specification.", + "author": "Jake Luer (http://qualiancy.com)", + "license": "MIT", + "types": "./index.d.ts", + "keywords": [ + "test", + "assertion", + "assertion-error" + ], + "repository": { + "type": "git", + "url": "git@github.com:chaijs/assertion-error.git" + }, + "engines": { + "node": ">=12" + }, + "files": [ + "index.d.ts" + ], + "type": "module", + "module": "index.js", + "main": "index.js", + "scripts": { + "build": "deno bundle mod.ts > index.js", + "pretest": "rm -rf coverage/", + "test": "deno test --coverage=coverage", + "posttest": "deno coverage coverage --lcov > coverage/lcov.info && lcov --summary coverage/lcov.info" + } +} diff --git a/node_modules/asynckit/LICENSE b/node_modules/asynckit/LICENSE new file mode 100644 index 000000000..c9eca5dd9 --- /dev/null +++ b/node_modules/asynckit/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Alex Indigo + +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/node_modules/asynckit/README.md b/node_modules/asynckit/README.md new file mode 100644 index 000000000..ddcc7e6b9 --- /dev/null +++ b/node_modules/asynckit/README.md @@ -0,0 +1,233 @@ +# asynckit [![NPM Module](https://img.shields.io/npm/v/asynckit.svg?style=flat)](https://www.npmjs.com/package/asynckit) + +Minimal async jobs utility library, with streams support. + +[![PhantomJS Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=browser&style=flat)](https://travis-ci.org/alexindigo/asynckit) +[![Linux Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=linux:0.12-6.x&style=flat)](https://travis-ci.org/alexindigo/asynckit) +[![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/asynckit/v0.4.0.svg?label=windows:0.12-6.x&style=flat)](https://ci.appveyor.com/project/alexindigo/asynckit) + +[![Coverage Status](https://img.shields.io/coveralls/alexindigo/asynckit/v0.4.0.svg?label=code+coverage&style=flat)](https://coveralls.io/github/alexindigo/asynckit?branch=master) +[![Dependency Status](https://img.shields.io/david/alexindigo/asynckit/v0.4.0.svg?style=flat)](https://david-dm.org/alexindigo/asynckit) +[![bitHound Overall Score](https://www.bithound.io/github/alexindigo/asynckit/badges/score.svg)](https://www.bithound.io/github/alexindigo/asynckit) + + + +AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects. +Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method. + +It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators. + +| compression | size | +| :----------------- | -------: | +| asynckit.js | 12.34 kB | +| asynckit.min.js | 4.11 kB | +| asynckit.min.js.gz | 1.47 kB | + + +## Install + +```sh +$ npm install --save asynckit +``` + +## Examples + +### Parallel Jobs + +Runs iterator over provided array in parallel. Stores output in the `result` array, +on the matching positions. In unlikely event of an error from one of the jobs, +will terminate rest of the active jobs (if abort function is provided) +and return error along with salvaged data to the main callback function. + +#### Input Array + +```javascript +var parallel = require('asynckit').parallel + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] + , target = [] + ; + +parallel(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// async job accepts one element from the array +// and a callback function +function asyncJob(item, cb) +{ + // different delays (in ms) per item + var delay = item * 25; + + // pretend different jobs take different time to finish + // and not in consequential order + var timeoutId = setTimeout(function() { + target.push(item); + cb(null, item * 2); + }, delay); + + // allow to cancel "leftover" jobs upon error + // return function, invoking of which will abort this job + return clearTimeout.bind(null, timeoutId); +} +``` + +More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js). + +#### Input Object + +Also it supports named jobs, listed via object. + +```javascript +var parallel = require('asynckit/parallel') + , assert = require('assert') + ; + +var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } + , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } + , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] + , expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ] + , target = [] + , keys = [] + ; + +parallel(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); + assert.deepEqual(keys, expectedKeys); +}); + +// supports full value, key, callback (shortcut) interface +function asyncJob(item, key, cb) +{ + // different delays (in ms) per item + var delay = item * 25; + + // pretend different jobs take different time to finish + // and not in consequential order + var timeoutId = setTimeout(function() { + keys.push(key); + target.push(item); + cb(null, item * 2); + }, delay); + + // allow to cancel "leftover" jobs upon error + // return function, invoking of which will abort this job + return clearTimeout.bind(null, timeoutId); +} +``` + +More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js). + +### Serial Jobs + +Runs iterator over provided array sequentially. Stores output in the `result` array, +on the matching positions. In unlikely event of an error from one of the jobs, +will not proceed to the rest of the items in the list +and return error along with salvaged data to the main callback function. + +#### Input Array + +```javascript +var serial = require('asynckit/serial') + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] + , target = [] + ; + +serial(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// extended interface (item, key, callback) +// also supported for arrays +function asyncJob(item, key, cb) +{ + target.push(key); + + // it will be automatically made async + // even it iterator "returns" in the same event loop + cb(null, item * 2); +} +``` + +More examples could be found in [test/test-serial-array.js](test/test-serial-array.js). + +#### Input Object + +Also it supports named jobs, listed via object. + +```javascript +var serial = require('asynckit').serial + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] + , target = [] + ; + +var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } + , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } + , expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , target = [] + ; + + +serial(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// shortcut interface (item, callback) +// works for object as well as for the arrays +function asyncJob(item, cb) +{ + target.push(item); + + // it will be automatically made async + // even it iterator "returns" in the same event loop + cb(null, item * 2); +} +``` + +More examples could be found in [test/test-serial-object.js](test/test-serial-object.js). + +_Note: Since _object_ is an _unordered_ collection of properties, +it may produce unexpected results with sequential iterations. +Whenever order of the jobs' execution is important please use `serialOrdered` method._ + +### Ordered Serial Iterations + +TBD + +For example [compare-property](compare-property) package. + +### Streaming interface + +TBD + +## Want to Know More? + +More examples can be found in [test folder](test/). + +Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions. + +## License + +AsyncKit is licensed under the MIT license. diff --git a/node_modules/asynckit/bench.js b/node_modules/asynckit/bench.js new file mode 100644 index 000000000..c612f1a55 --- /dev/null +++ b/node_modules/asynckit/bench.js @@ -0,0 +1,76 @@ +/* eslint no-console: "off" */ + +var asynckit = require('./') + , async = require('async') + , assert = require('assert') + , expected = 0 + ; + +var Benchmark = require('benchmark'); +var suite = new Benchmark.Suite; + +var source = []; +for (var z = 1; z < 100; z++) +{ + source.push(z); + expected += z; +} + +suite +// add tests + +.add('async.map', function(deferred) +{ + var total = 0; + + async.map(source, + function(i, cb) + { + setImmediate(function() + { + total += i; + cb(null, total); + }); + }, + function(err, result) + { + assert.ifError(err); + assert.equal(result[result.length - 1], expected); + deferred.resolve(); + }); +}, {'defer': true}) + + +.add('asynckit.parallel', function(deferred) +{ + var total = 0; + + asynckit.parallel(source, + function(i, cb) + { + setImmediate(function() + { + total += i; + cb(null, total); + }); + }, + function(err, result) + { + assert.ifError(err); + assert.equal(result[result.length - 1], expected); + deferred.resolve(); + }); +}, {'defer': true}) + + +// add listeners +.on('cycle', function(ev) +{ + console.log(String(ev.target)); +}) +.on('complete', function() +{ + console.log('Fastest is ' + this.filter('fastest').map('name')); +}) +// run async +.run({ 'async': true }); diff --git a/node_modules/asynckit/index.js b/node_modules/asynckit/index.js new file mode 100644 index 000000000..455f9454e --- /dev/null +++ b/node_modules/asynckit/index.js @@ -0,0 +1,6 @@ +module.exports = +{ + parallel : require('./parallel.js'), + serial : require('./serial.js'), + serialOrdered : require('./serialOrdered.js') +}; diff --git a/node_modules/asynckit/lib/abort.js b/node_modules/asynckit/lib/abort.js new file mode 100644 index 000000000..114367e5f --- /dev/null +++ b/node_modules/asynckit/lib/abort.js @@ -0,0 +1,29 @@ +// API +module.exports = abort; + +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); + + // reset leftover jobs + state.jobs = {}; +} + +/** + * Cleans up leftover job by invoking abort function for the provided job id + * + * @this state + * @param {string|number} key - job id to abort + */ +function clean(key) +{ + if (typeof this.jobs[key] == 'function') + { + this.jobs[key](); + } +} diff --git a/node_modules/asynckit/lib/async.js b/node_modules/asynckit/lib/async.js new file mode 100644 index 000000000..7f1288a4c --- /dev/null +++ b/node_modules/asynckit/lib/async.js @@ -0,0 +1,34 @@ +var defer = require('./defer.js'); + +// API +module.exports = async; + +/** + * Runs provided callback asynchronously + * even if callback itself is not + * + * @param {function} callback - callback to invoke + * @returns {function} - augmented callback + */ +function async(callback) +{ + var isAsync = false; + + // check if async happened + defer(function() { isAsync = true; }); + + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); + } + else + { + defer(function nextTick_callback() + { + callback(err, result); + }); + } + }; +} diff --git a/node_modules/asynckit/lib/defer.js b/node_modules/asynckit/lib/defer.js new file mode 100644 index 000000000..b67110c7a --- /dev/null +++ b/node_modules/asynckit/lib/defer.js @@ -0,0 +1,26 @@ +module.exports = defer; + +/** + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run + */ +function defer(fn) +{ + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof process == 'object' && typeof process.nextTick == 'function' + ? process.nextTick + : null + ); + + if (nextTick) + { + nextTick(fn); + } + else + { + setTimeout(fn, 0); + } +} diff --git a/node_modules/asynckit/lib/iterate.js b/node_modules/asynckit/lib/iterate.js new file mode 100644 index 000000000..5d2839a59 --- /dev/null +++ b/node_modules/asynckit/lib/iterate.js @@ -0,0 +1,75 @@ +var async = require('./async.js') + , abort = require('./abort.js') + ; + +// API +module.exports = iterate; + +/** + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed + */ +function iterate(list, iterator, state, callback) +{ + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; + + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } + + // clean up jobs + delete state.jobs[key]; + + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); + } + else + { + state.results[key] = output; + } + + // return salvaged results + callback(error, state.results); + }); +} + +/** + * Runs iterator over provided job element + * + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else + */ +function runJob(iterator, key, item, callback) +{ + var aborter; + + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async(callback)); + } + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async(callback)); + } + + return aborter; +} diff --git a/node_modules/asynckit/lib/readable_asynckit.js b/node_modules/asynckit/lib/readable_asynckit.js new file mode 100644 index 000000000..78ad240f0 --- /dev/null +++ b/node_modules/asynckit/lib/readable_asynckit.js @@ -0,0 +1,91 @@ +var streamify = require('./streamify.js') + , defer = require('./defer.js') + ; + +// API +module.exports = ReadableAsyncKit; + +/** + * Base constructor for all streams + * used to hold properties/methods + */ +function ReadableAsyncKit() +{ + ReadableAsyncKit.super_.apply(this, arguments); + + // list of active jobs + this.jobs = {}; + + // add stream methods + this.destroy = destroy; + this._start = _start; + this._read = _read; +} + +/** + * Destroys readable stream, + * by aborting outstanding jobs + * + * @returns {void} + */ +function destroy() +{ + if (this.destroyed) + { + return; + } + + this.destroyed = true; + + if (typeof this.terminator == 'function') + { + this.terminator(); + } +} + +/** + * Starts provided jobs in async manner + * + * @private + */ +function _start() +{ + // first argument – runner function + var runner = arguments[0] + // take away first argument + , args = Array.prototype.slice.call(arguments, 1) + // second argument - input data + , input = args[0] + // last argument - result callback + , endCb = streamify.callback.call(this, args[args.length - 1]) + ; + + args[args.length - 1] = endCb; + // third argument - iterator + args[1] = streamify.iterator.call(this, args[1]); + + // allow time for proper setup + defer(function() + { + if (!this.destroyed) + { + this.terminator = runner.apply(null, args); + } + else + { + endCb(null, Array.isArray(input) ? [] : {}); + } + }.bind(this)); +} + + +/** + * Implement _read to comply with Readable streams + * Doesn't really make sense for flowing object mode + * + * @private + */ +function _read() +{ + +} diff --git a/node_modules/asynckit/lib/readable_parallel.js b/node_modules/asynckit/lib/readable_parallel.js new file mode 100644 index 000000000..5d2929f7a --- /dev/null +++ b/node_modules/asynckit/lib/readable_parallel.js @@ -0,0 +1,25 @@ +var parallel = require('../parallel.js'); + +// API +module.exports = ReadableParallel; + +/** + * Streaming wrapper to `asynckit.parallel` + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {stream.Readable#} + */ +function ReadableParallel(list, iterator, callback) +{ + if (!(this instanceof ReadableParallel)) + { + return new ReadableParallel(list, iterator, callback); + } + + // turn on object mode + ReadableParallel.super_.call(this, {objectMode: true}); + + this._start(parallel, list, iterator, callback); +} diff --git a/node_modules/asynckit/lib/readable_serial.js b/node_modules/asynckit/lib/readable_serial.js new file mode 100644 index 000000000..782269820 --- /dev/null +++ b/node_modules/asynckit/lib/readable_serial.js @@ -0,0 +1,25 @@ +var serial = require('../serial.js'); + +// API +module.exports = ReadableSerial; + +/** + * Streaming wrapper to `asynckit.serial` + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {stream.Readable#} + */ +function ReadableSerial(list, iterator, callback) +{ + if (!(this instanceof ReadableSerial)) + { + return new ReadableSerial(list, iterator, callback); + } + + // turn on object mode + ReadableSerial.super_.call(this, {objectMode: true}); + + this._start(serial, list, iterator, callback); +} diff --git a/node_modules/asynckit/lib/readable_serial_ordered.js b/node_modules/asynckit/lib/readable_serial_ordered.js new file mode 100644 index 000000000..3de89c472 --- /dev/null +++ b/node_modules/asynckit/lib/readable_serial_ordered.js @@ -0,0 +1,29 @@ +var serialOrdered = require('../serialOrdered.js'); + +// API +module.exports = ReadableSerialOrdered; +// expose sort helpers +module.exports.ascending = serialOrdered.ascending; +module.exports.descending = serialOrdered.descending; + +/** + * Streaming wrapper to `asynckit.serialOrdered` + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {stream.Readable#} + */ +function ReadableSerialOrdered(list, iterator, sortMethod, callback) +{ + if (!(this instanceof ReadableSerialOrdered)) + { + return new ReadableSerialOrdered(list, iterator, sortMethod, callback); + } + + // turn on object mode + ReadableSerialOrdered.super_.call(this, {objectMode: true}); + + this._start(serialOrdered, list, iterator, sortMethod, callback); +} diff --git a/node_modules/asynckit/lib/state.js b/node_modules/asynckit/lib/state.js new file mode 100644 index 000000000..cbea7ad8f --- /dev/null +++ b/node_modules/asynckit/lib/state.js @@ -0,0 +1,37 @@ +// API +module.exports = state; + +/** + * Creates initial state object + * for iteration over list + * + * @param {array|object} list - list to iterate over + * @param {function|null} sortMethod - function to use for keys sort, + * or `null` to keep them as is + * @returns {object} - initial state object + */ +function state(list, sortMethod) +{ + var isNamedList = !Array.isArray(list) + , initState = + { + index : 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs : {}, + results : isNamedList ? {} : [], + size : isNamedList ? Object.keys(list).length : list.length + } + ; + + if (sortMethod) + { + // sort array keys based on it's values + // sort object's keys just on own merit + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) + { + return sortMethod(list[a], list[b]); + }); + } + + return initState; +} diff --git a/node_modules/asynckit/lib/streamify.js b/node_modules/asynckit/lib/streamify.js new file mode 100644 index 000000000..f56a1c92b --- /dev/null +++ b/node_modules/asynckit/lib/streamify.js @@ -0,0 +1,141 @@ +var async = require('./async.js'); + +// API +module.exports = { + iterator: wrapIterator, + callback: wrapCallback +}; + +/** + * Wraps iterators with long signature + * + * @this ReadableAsyncKit# + * @param {function} iterator - function to wrap + * @returns {function} - wrapped function + */ +function wrapIterator(iterator) +{ + var stream = this; + + return function(item, key, cb) + { + var aborter + , wrappedCb = async(wrapIteratorCallback.call(stream, cb, key)) + ; + + stream.jobs[key] = wrappedCb; + + // it's either shortcut (item, cb) + if (iterator.length == 2) + { + aborter = iterator(item, wrappedCb); + } + // or long format (item, key, cb) + else + { + aborter = iterator(item, key, wrappedCb); + } + + return aborter; + }; +} + +/** + * Wraps provided callback function + * allowing to execute snitch function before + * real callback + * + * @this ReadableAsyncKit# + * @param {function} callback - function to wrap + * @returns {function} - wrapped function + */ +function wrapCallback(callback) +{ + var stream = this; + + var wrapped = function(error, result) + { + return finisher.call(stream, error, result, callback); + }; + + return wrapped; +} + +/** + * Wraps provided iterator callback function + * makes sure snitch only called once, + * but passes secondary calls to the original callback + * + * @this ReadableAsyncKit# + * @param {function} callback - callback to wrap + * @param {number|string} key - iteration key + * @returns {function} wrapped callback + */ +function wrapIteratorCallback(callback, key) +{ + var stream = this; + + return function(error, output) + { + // don't repeat yourself + if (!(key in stream.jobs)) + { + callback(error, output); + return; + } + + // clean up jobs + delete stream.jobs[key]; + + return streamer.call(stream, error, {key: key, value: output}, callback); + }; +} + +/** + * Stream wrapper for iterator callback + * + * @this ReadableAsyncKit# + * @param {mixed} error - error response + * @param {mixed} output - iterator output + * @param {function} callback - callback that expects iterator results + */ +function streamer(error, output, callback) +{ + if (error && !this.error) + { + this.error = error; + this.pause(); + this.emit('error', error); + // send back value only, as expected + callback(error, output && output.value); + return; + } + + // stream stuff + this.push(output); + + // back to original track + // send back value only, as expected + callback(error, output && output.value); +} + +/** + * Stream wrapper for finishing callback + * + * @this ReadableAsyncKit# + * @param {mixed} error - error response + * @param {mixed} output - iterator output + * @param {function} callback - callback that expects final results + */ +function finisher(error, output, callback) +{ + // signal end of the stream + // only for successfully finished streams + if (!error) + { + this.push(null); + } + + // back to original track + callback(error, output); +} diff --git a/node_modules/asynckit/lib/terminator.js b/node_modules/asynckit/lib/terminator.js new file mode 100644 index 000000000..d6eb99219 --- /dev/null +++ b/node_modules/asynckit/lib/terminator.js @@ -0,0 +1,29 @@ +var abort = require('./abort.js') + , async = require('./async.js') + ; + +// API +module.exports = terminator; + +/** + * Terminates jobs in the attached state context + * + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination + */ +function terminator(callback) +{ + if (!Object.keys(this.jobs).length) + { + return; + } + + // fast forward iteration index + this.index = this.size; + + // abort jobs + abort(this); + + // send back results we have so far + async(callback)(null, this.results); +} diff --git a/node_modules/asynckit/package.json b/node_modules/asynckit/package.json new file mode 100644 index 000000000..51147d656 --- /dev/null +++ b/node_modules/asynckit/package.json @@ -0,0 +1,63 @@ +{ + "name": "asynckit", + "version": "0.4.0", + "description": "Minimal async jobs utility library, with streams support", + "main": "index.js", + "scripts": { + "clean": "rimraf coverage", + "lint": "eslint *.js lib/*.js test/*.js", + "test": "istanbul cover --reporter=json tape -- 'test/test-*.js' | tap-spec", + "win-test": "tape test/test-*.js", + "browser": "browserify -t browserify-istanbul test/lib/browserify_adjustment.js test/test-*.js | obake --coverage | tap-spec", + "report": "istanbul report", + "size": "browserify index.js | size-table asynckit", + "debug": "tape test/test-*.js" + }, + "pre-commit": [ + "clean", + "lint", + "test", + "browser", + "report", + "size" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/alexindigo/asynckit.git" + }, + "keywords": [ + "async", + "jobs", + "parallel", + "serial", + "iterator", + "array", + "object", + "stream", + "destroy", + "terminate", + "abort" + ], + "author": "Alex Indigo ", + "license": "MIT", + "bugs": { + "url": "https://github.com/alexindigo/asynckit/issues" + }, + "homepage": "https://github.com/alexindigo/asynckit#readme", + "devDependencies": { + "browserify": "^13.0.0", + "browserify-istanbul": "^2.0.0", + "coveralls": "^2.11.9", + "eslint": "^2.9.0", + "istanbul": "^0.4.3", + "obake": "^0.1.2", + "phantomjs-prebuilt": "^2.1.7", + "pre-commit": "^1.1.3", + "reamde": "^1.1.0", + "rimraf": "^2.5.2", + "size-table": "^0.2.0", + "tap-spec": "^4.1.1", + "tape": "^4.5.1" + }, + "dependencies": {} +} diff --git a/node_modules/asynckit/parallel.js b/node_modules/asynckit/parallel.js new file mode 100644 index 000000000..3c50344d8 --- /dev/null +++ b/node_modules/asynckit/parallel.js @@ -0,0 +1,43 @@ +var iterate = require('./lib/iterate.js') + , initState = require('./lib/state.js') + , terminator = require('./lib/terminator.js') + ; + +// Public API +module.exports = parallel; + +/** + * Runs iterator over provided array elements in parallel + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function parallel(list, iterator, callback) +{ + var state = initState(list); + + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } + + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); + + state.index++; + } + + return terminator.bind(state, callback); +} diff --git a/node_modules/asynckit/serial.js b/node_modules/asynckit/serial.js new file mode 100644 index 000000000..6cd949a67 --- /dev/null +++ b/node_modules/asynckit/serial.js @@ -0,0 +1,17 @@ +var serialOrdered = require('./serialOrdered.js'); + +// Public API +module.exports = serial; + +/** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); +} diff --git a/node_modules/asynckit/serialOrdered.js b/node_modules/asynckit/serialOrdered.js new file mode 100644 index 000000000..607eafea5 --- /dev/null +++ b/node_modules/asynckit/serialOrdered.js @@ -0,0 +1,75 @@ +var iterate = require('./lib/iterate.js') + , initState = require('./lib/state.js') + , terminator = require('./lib/terminator.js') + ; + +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; + +/** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serialOrdered(list, iterator, sortMethod, callback) +{ + var state = initState(list, sortMethod); + + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } + + state.index++; + + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; + } + + // done here + callback(null, state.results); + }); + + return terminator.bind(state, callback); +} + +/* + * -- Sort methods + */ + +/** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function ascending(a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function descending(a, b) +{ + return -1 * ascending(a, b); +} diff --git a/node_modules/asynckit/stream.js b/node_modules/asynckit/stream.js new file mode 100644 index 000000000..d43465f90 --- /dev/null +++ b/node_modules/asynckit/stream.js @@ -0,0 +1,21 @@ +var inherits = require('util').inherits + , Readable = require('stream').Readable + , ReadableAsyncKit = require('./lib/readable_asynckit.js') + , ReadableParallel = require('./lib/readable_parallel.js') + , ReadableSerial = require('./lib/readable_serial.js') + , ReadableSerialOrdered = require('./lib/readable_serial_ordered.js') + ; + +// API +module.exports = +{ + parallel : ReadableParallel, + serial : ReadableSerial, + serialOrdered : ReadableSerialOrdered, +}; + +inherits(ReadableAsyncKit, Readable); + +inherits(ReadableParallel, ReadableAsyncKit); +inherits(ReadableSerial, ReadableAsyncKit); +inherits(ReadableSerialOrdered, ReadableAsyncKit); diff --git a/node_modules/axios/CHANGELOG.md b/node_modules/axios/CHANGELOG.md new file mode 100644 index 000000000..4301d6258 --- /dev/null +++ b/node_modules/axios/CHANGELOG.md @@ -0,0 +1,1072 @@ +# Changelog + +## [1.7.9](https://github.com/axios/axios/compare/v1.7.8...v1.7.9) (2024-12-04) + + +### Reverts + +* Revert "fix(types): export CJS types from ESM (#6218)" (#6729) ([c44d2f2](https://github.com/axios/axios/commit/c44d2f2316ad289b38997657248ba10de11deb6c)), closes [#6218](https://github.com/axios/axios/issues/6218) [#6729](https://github.com/axios/axios/issues/6729) + +### Contributors to this release + +- avatar [Jay](https://github.com/jasonsaayman "+596/-108 (#6729 )") + +## [1.7.8](https://github.com/axios/axios/compare/v1.7.7...v1.7.8) (2024-11-25) + + +### Bug Fixes + +* allow passing a callback as paramsSerializer to buildURL ([#6680](https://github.com/axios/axios/issues/6680)) ([eac4619](https://github.com/axios/axios/commit/eac4619fe2e0926e876cd260ee21e3690381dbb5)) +* **core:** fixed config merging bug ([#6668](https://github.com/axios/axios/issues/6668)) ([5d99fe4](https://github.com/axios/axios/commit/5d99fe4491202a6268c71e5dcc09192359d73cea)) +* fixed width form to not shrink after 'Send Request' button is clicked ([#6644](https://github.com/axios/axios/issues/6644)) ([7ccd5fd](https://github.com/axios/axios/commit/7ccd5fd42402102d38712c32707bf055be72ab54)) +* **http:** add support for File objects as payload in http adapter ([#6588](https://github.com/axios/axios/issues/6588)) ([#6605](https://github.com/axios/axios/issues/6605)) ([6841d8d](https://github.com/axios/axios/commit/6841d8d18ddc71cc1bd202ffcfddb3f95622eef3)) +* **http:** fixed proxy-from-env module import ([#5222](https://github.com/axios/axios/issues/5222)) ([12b3295](https://github.com/axios/axios/commit/12b32957f1258aee94ef859809ed39f8f88f9dfa)) +* **http:** use `globalThis.TextEncoder` when available ([#6634](https://github.com/axios/axios/issues/6634)) ([df956d1](https://github.com/axios/axios/commit/df956d18febc9100a563298dfdf0f102c3d15410)) +* ios11 breaks when build ([#6608](https://github.com/axios/axios/issues/6608)) ([7638952](https://github.com/axios/axios/commit/763895270f7b50c7c780c3c9807ae8635de952cd)) +* **types:** add missing types for mergeConfig function ([#6590](https://github.com/axios/axios/issues/6590)) ([00de614](https://github.com/axios/axios/commit/00de614cd07b7149af335e202aef0e076c254f49)) +* **types:** export CJS types from ESM ([#6218](https://github.com/axios/axios/issues/6218)) ([c71811b](https://github.com/axios/axios/commit/c71811b00f2fcff558e4382ba913bdac4ad7200e)) +* updated stream aborted error message to be more clear ([#6615](https://github.com/axios/axios/issues/6615)) ([cc3217a](https://github.com/axios/axios/commit/cc3217a612024d83a663722a56d7a98d8759c6d5)) +* use URL API instead of DOM to fix a potential vulnerability warning; ([#6714](https://github.com/axios/axios/issues/6714)) ([0a8d6e1](https://github.com/axios/axios/commit/0a8d6e19da5b9899a2abafaaa06a75ee548597db)) + +### Contributors to this release + +- avatar [Remco Haszing](https://github.com/remcohaszing "+108/-596 (#6218 )") +- avatar [Jay](https://github.com/jasonsaayman "+281/-19 (#6640 #6619 )") +- avatar [Aayush Yadav](https://github.com/aayushyadav020 "+124/-111 (#6617 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+12/-65 (#6714 )") +- avatar [Ell Bradshaw](https://github.com/cincodenada "+29/-0 (#6489 )") +- avatar [Amit Saini](https://github.com/amitsainii "+13/-3 (#5237 )") +- avatar [Tommaso Paulon](https://github.com/guuido "+14/-1 (#6680 )") +- avatar [Akki](https://github.com/Aakash-Rana "+5/-5 (#6668 )") +- avatar [Sampo Silvennoinen](https://github.com/stscoundrel "+3/-3 (#6633 )") +- avatar [Kasper Isager Dalsgarð](https://github.com/kasperisager "+2/-2 (#6634 )") +- avatar [Christian Clauss](https://github.com/cclauss "+4/-0 (#6683 )") +- avatar [Pavan Welihinda](https://github.com/pavan168 "+2/-2 (#5222 )") +- avatar [Taylor Flatt](https://github.com/taylorflatt "+2/-2 (#6615 )") +- avatar [Kenzo Wada](https://github.com/Kenzo-Wada "+2/-2 (#6608 )") +- avatar [Ngole Lawson](https://github.com/echelonnought "+3/-0 (#6644 )") +- avatar [Haven](https://github.com/Baoyx007 "+3/-0 (#6590 )") +- avatar [Shrivali Dutt](https://github.com/shrivalidutt "+1/-1 (#6637 )") +- avatar [Henco Appel](https://github.com/hencoappel "+1/-1 (#6605 )") + +## [1.7.7](https://github.com/axios/axios/compare/v1.7.6...v1.7.7) (2024-08-31) + + +### Bug Fixes + +* **fetch:** fix stream handling in Safari by fallback to using a stream reader instead of an async iterator; ([#6584](https://github.com/axios/axios/issues/6584)) ([d198085](https://github.com/axios/axios/commit/d1980854fee1765cd02fa0787adf5d6e34dd9dcf)) +* **http:** fixed support for IPv6 literal strings in url ([#5731](https://github.com/axios/axios/issues/5731)) ([364993f](https://github.com/axios/axios/commit/364993f0d8bc6e0e06f76b8a35d2d0a35cab054c)) + +### Contributors to this release + +- avatar [Rishi556](https://github.com/Rishi556 "+39/-1 (#5731 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+27/-7 (#6584 )") + +## [1.7.6](https://github.com/axios/axios/compare/v1.7.5...v1.7.6) (2024-08-30) + + +### Bug Fixes + +* **fetch:** fix content length calculation for FormData payload; ([#6524](https://github.com/axios/axios/issues/6524)) ([085f568](https://github.com/axios/axios/commit/085f56861a83e9ac02c140ad9d68dac540dfeeaa)) +* **fetch:** optimize signals composing logic; ([#6582](https://github.com/axios/axios/issues/6582)) ([df9889b](https://github.com/axios/axios/commit/df9889b83c2cc37e9e6189675a73ab70c60f031f)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+98/-46 (#6582 )") +- avatar [Jacques Germishuys](https://github.com/jacquesg "+5/-1 (#6524 )") +- avatar [kuroino721](https://github.com/kuroino721 "+3/-1 (#6575 )") + +## [1.7.5](https://github.com/axios/axios/compare/v1.7.4...v1.7.5) (2024-08-23) + + +### Bug Fixes + +* **adapter:** fix undefined reference to hasBrowserEnv ([#6572](https://github.com/axios/axios/issues/6572)) ([7004707](https://github.com/axios/axios/commit/7004707c4180b416341863bd86913fe4fc2f1df1)) +* **core:** add the missed implementation of AxiosError#status property; ([#6573](https://github.com/axios/axios/issues/6573)) ([6700a8a](https://github.com/axios/axios/commit/6700a8adac06942205f6a7a21421ecb36c4e0852)) +* **core:** fix `ReferenceError: navigator is not defined` for custom environments; ([#6567](https://github.com/axios/axios/issues/6567)) ([fed1a4b](https://github.com/axios/axios/commit/fed1a4b2d78ed4a588c84e09d32749ed01dc2794)) +* **fetch:** fix credentials handling in Cloudflare workers ([#6533](https://github.com/axios/axios/issues/6533)) ([550d885](https://github.com/axios/axios/commit/550d885eb90fd156add7b93bbdc54d30d2f9a98d)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+187/-83 (#6573 #6567 #6566 #6564 #6563 #6557 #6556 #6555 #6554 #6552 )") +- avatar [Antonin Bas](https://github.com/antoninbas "+6/-6 (#6572 )") +- avatar [Hans Otto Wirtz](https://github.com/hansottowirtz "+4/-1 (#6533 )") + +## [1.7.4](https://github.com/axios/axios/compare/v1.7.3...v1.7.4) (2024-08-13) + + +### Bug Fixes + +* **sec:** CVE-2024-39338 ([#6539](https://github.com/axios/axios/issues/6539)) ([#6543](https://github.com/axios/axios/issues/6543)) ([6b6b605](https://github.com/axios/axios/commit/6b6b605eaf73852fb2dae033f1e786155959de3a)) +* **sec:** disregard protocol-relative URL to remediate SSRF ([#6539](https://github.com/axios/axios/issues/6539)) ([07a661a](https://github.com/axios/axios/commit/07a661a2a6b9092c4aa640dcc7f724ec5e65bdda)) + +### Contributors to this release + +- avatar [Lev Pachmanov](https://github.com/levpachmanov "+47/-11 (#6543 )") +- avatar [Đỗ Trọng Hải](https://github.com/hainenber "+49/-4 (#6539 )") + +## [1.7.3](https://github.com/axios/axios/compare/v1.7.2...v1.7.3) (2024-08-01) + + +### Bug Fixes + +* **adapter:** fix progress event emitting; ([#6518](https://github.com/axios/axios/issues/6518)) ([e3c76fc](https://github.com/axios/axios/commit/e3c76fc9bdd03aa4d98afaf211df943e2031453f)) +* **fetch:** fix withCredentials request config ([#6505](https://github.com/axios/axios/issues/6505)) ([85d4d0e](https://github.com/axios/axios/commit/85d4d0ea0aae91082f04e303dec46510d1b4e787)) +* **xhr:** return original config on errors from XHR adapter ([#6515](https://github.com/axios/axios/issues/6515)) ([8966ee7](https://github.com/axios/axios/commit/8966ee7ea62ecbd6cfb39a905939bcdab5cf6388)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+211/-159 (#6518 #6519 )") +- avatar [Valerii Sidorenko](https://github.com/ValeraS "+3/-3 (#6515 )") +- avatar [prianYu](https://github.com/prianyu "+2/-2 (#6505 )") + +## [1.7.2](https://github.com/axios/axios/compare/v1.7.1...v1.7.2) (2024-05-21) + + +### Bug Fixes + +* **fetch:** enhance fetch API detection; ([#6413](https://github.com/axios/axios/issues/6413)) ([4f79aef](https://github.com/axios/axios/commit/4f79aef81b7c4644328365bfc33acf0a9ef595bc)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+3/-3 (#6413 )") + +## [1.7.1](https://github.com/axios/axios/compare/v1.7.0...v1.7.1) (2024-05-20) + + +### Bug Fixes + +* **fetch:** fixed ReferenceError issue when TextEncoder is not available in the environment; ([#6410](https://github.com/axios/axios/issues/6410)) ([733f15f](https://github.com/axios/axios/commit/733f15fe5bd2d67e1fadaee82e7913b70d45dc5e)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+14/-9 (#6410 )") + +# [1.7.0](https://github.com/axios/axios/compare/v1.7.0-beta.2...v1.7.0) (2024-05-19) + + +### Features + +* **adapter:** add fetch adapter; ([#6371](https://github.com/axios/axios/issues/6371)) ([a3ff99b](https://github.com/axios/axios/commit/a3ff99b59d8ec2ab5dd049e68c043617a4072e42)) + +### Bug Fixes + +* **core/axios:** handle un-writable error stack ([#6362](https://github.com/axios/axios/issues/6362)) ([81e0455](https://github.com/axios/axios/commit/81e0455b7b57fbaf2be16a73ebe0e6591cc6d8f9)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+1015/-127 (#6371 )") +- avatar [Jay](https://github.com/jasonsaayman "+30/-14 ()") +- avatar [Alexandre ABRIOUX](https://github.com/alexandre-abrioux "+56/-6 (#6362 )") + +# [1.7.0-beta.2](https://github.com/axios/axios/compare/v1.7.0-beta.1...v1.7.0-beta.2) (2024-05-19) + + +### Bug Fixes + +* **fetch:** capitalize HTTP method names; ([#6395](https://github.com/axios/axios/issues/6395)) ([ad3174a](https://github.com/axios/axios/commit/ad3174a3515c3c2573f4bcb94818d582826f3914)) +* **fetch:** fix & optimize progress capturing for cases when the request data has a nullish value or zero data length ([#6400](https://github.com/axios/axios/issues/6400)) ([95a3e8e](https://github.com/axios/axios/commit/95a3e8e346cfd6a5548e171f2341df3235d0e26b)) +* **fetch:** fix headers getting from a stream response; ([#6401](https://github.com/axios/axios/issues/6401)) ([870e0a7](https://github.com/axios/axios/commit/870e0a76f60d0094774a6a63fa606eec52a381af)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+99/-46 (#6405 #6404 #6401 #6400 #6395 )") + +# [1.7.0-beta.1](https://github.com/axios/axios/compare/v1.7.0-beta.0...v1.7.0-beta.1) (2024-05-07) + + +### Bug Fixes + +* **core/axios:** handle un-writable error stack ([#6362](https://github.com/axios/axios/issues/6362)) ([81e0455](https://github.com/axios/axios/commit/81e0455b7b57fbaf2be16a73ebe0e6591cc6d8f9)) +* **fetch:** fix cases when ReadableStream or Response.body are not available; ([#6377](https://github.com/axios/axios/issues/6377)) ([d1d359d](https://github.com/axios/axios/commit/d1d359da347704e8b28d768e61515a3e96c5b072)) +* **fetch:** treat fetch-related TypeError as an AxiosError.ERR_NETWORK error; ([#6380](https://github.com/axios/axios/issues/6380)) ([bb5f9a5](https://github.com/axios/axios/commit/bb5f9a5ab768452de9e166dc28d0ffc234245ef1)) + +### Contributors to this release + +- avatar [Alexandre ABRIOUX](https://github.com/alexandre-abrioux "+56/-6 (#6362 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+42/-17 (#6380 #6377 )") + +# [1.7.0-beta.0](https://github.com/axios/axios/compare/v1.6.8...v1.7.0-beta.0) (2024-04-28) + + +### Features + +* **adapter:** add fetch adapter; ([#6371](https://github.com/axios/axios/issues/6371)) ([a3ff99b](https://github.com/axios/axios/commit/a3ff99b59d8ec2ab5dd049e68c043617a4072e42)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+1015/-127 (#6371 )") +- avatar [Jay](https://github.com/jasonsaayman "+30/-14 ()") + +## [1.6.8](https://github.com/axios/axios/compare/v1.6.7...v1.6.8) (2024-03-15) + + +### Bug Fixes + +* **AxiosHeaders:** fix AxiosHeaders conversion to an object during config merging ([#6243](https://github.com/axios/axios/issues/6243)) ([2656612](https://github.com/axios/axios/commit/2656612bc10fe2757e9832b708ed773ab340b5cb)) +* **import:** use named export for EventEmitter; ([7320430](https://github.com/axios/axios/commit/7320430aef2e1ba2b89488a0eaf42681165498b1)) +* **vulnerability:** update follow-redirects to 1.15.6 ([#6300](https://github.com/axios/axios/issues/6300)) ([8786e0f](https://github.com/axios/axios/commit/8786e0ff55a8c68d4ca989801ad26df924042e27)) + +### Contributors to this release + +- avatar [Jay](https://github.com/jasonsaayman "+4572/-3446 (#6238 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+30/-0 (#6231 )") +- avatar [Mitchell](https://github.com/Creaous "+9/-9 (#6300 )") +- avatar [Emmanuel](https://github.com/mannoeu "+2/-2 (#6196 )") +- avatar [Lucas Keller](https://github.com/ljkeller "+3/-0 (#6194 )") +- avatar [Aditya Mogili](https://github.com/ADITYA-176 "+1/-1 ()") +- avatar [Miroslav Petrov](https://github.com/petrovmiroslav "+1/-1 (#6243 )") + +## [1.6.7](https://github.com/axios/axios/compare/v1.6.6...v1.6.7) (2024-01-25) + + +### Bug Fixes + +* capture async stack only for rejections with native error objects; ([#6203](https://github.com/axios/axios/issues/6203)) ([1a08f90](https://github.com/axios/axios/commit/1a08f90f402336e4d00e9ee82f211c6adb1640b0)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+30/-26 (#6203 )") +- avatar [zhoulixiang](https://github.com/zh-lx "+0/-3 (#6186 )") + +## [1.6.6](https://github.com/axios/axios/compare/v1.6.5...v1.6.6) (2024-01-24) + + +### Bug Fixes + +* fixed missed dispatchBeforeRedirect argument ([#5778](https://github.com/axios/axios/issues/5778)) ([a1938ff](https://github.com/axios/axios/commit/a1938ff073fcb0f89011f001dfbc1fa1dc995e39)) +* wrap errors to improve async stack trace ([#5987](https://github.com/axios/axios/issues/5987)) ([123f354](https://github.com/axios/axios/commit/123f354b920f154a209ea99f76b7b2ef3d9ebbab)) + +### Contributors to this release + +- avatar [Ilya Priven](https://github.com/ikonst "+91/-8 (#5987 )") +- avatar [Zao Soula](https://github.com/zaosoula "+6/-6 (#5778 )") + +## [1.6.5](https://github.com/axios/axios/compare/v1.6.4...v1.6.5) (2024-01-05) + + +### Bug Fixes + +* **ci:** refactor notify action as a job of publish action; ([#6176](https://github.com/axios/axios/issues/6176)) ([0736f95](https://github.com/axios/axios/commit/0736f95ce8776366dc9ca569f49ba505feb6373c)) +* **dns:** fixed lookup error handling; ([#6175](https://github.com/axios/axios/issues/6175)) ([f4f2b03](https://github.com/axios/axios/commit/f4f2b039dd38eb4829e8583caede4ed6d2dd59be)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+41/-6 (#6176 #6175 )") +- avatar [Jay](https://github.com/jasonsaayman "+6/-1 ()") + +## [1.6.4](https://github.com/axios/axios/compare/v1.6.3...v1.6.4) (2024-01-03) + + +### Bug Fixes + +* **security:** fixed formToJSON prototype pollution vulnerability; ([#6167](https://github.com/axios/axios/issues/6167)) ([3c0c11c](https://github.com/axios/axios/commit/3c0c11cade045c4412c242b5727308cff9897a0e)) +* **security:** fixed security vulnerability in follow-redirects ([#6163](https://github.com/axios/axios/issues/6163)) ([75af1cd](https://github.com/axios/axios/commit/75af1cdff5b3a6ca3766d3d3afbc3115bb0811b8)) + +### Contributors to this release + +- avatar [Jay](https://github.com/jasonsaayman "+34/-6 ()") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+34/-3 (#6172 #6167 )") +- avatar [Guy Nesher](https://github.com/gnesher "+10/-10 (#6163 )") + +## [1.6.3](https://github.com/axios/axios/compare/v1.6.2...v1.6.3) (2023-12-26) + + +### Bug Fixes + +* Regular Expression Denial of Service (ReDoS) ([#6132](https://github.com/axios/axios/issues/6132)) ([5e7ad38](https://github.com/axios/axios/commit/5e7ad38fb0f819fceb19fb2ee5d5d38f56aa837d)) + +### Contributors to this release + +- avatar [Jay](https://github.com/jasonsaayman "+15/-6 (#6145 )") +- avatar [Willian Agostini](https://github.com/WillianAgostini "+17/-2 (#6132 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+3/-0 (#6084 )") + +## [1.6.2](https://github.com/axios/axios/compare/v1.6.1...v1.6.2) (2023-11-14) + + +### Features + +* **withXSRFToken:** added withXSRFToken option as a workaround to achieve the old `withCredentials` behavior; ([#6046](https://github.com/axios/axios/issues/6046)) ([cff9967](https://github.com/axios/axios/commit/cff996779b272a5e94c2b52f5503ccf668bc42dc)) + +### PRs +- feat(withXSRFToken): added withXSRFToken option as a workaround to achieve the old `withCredentials` behavior; ( [#6046](https://api.github.com/repos/axios/axios/pulls/6046) ) +``` + +📢 This PR added 'withXSRFToken' option as a replacement for old withCredentials behaviour. +You should now use withXSRFToken along with withCredential to get the old behavior. +This functionality is considered as a fix. +``` + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+271/-146 (#6081 #6080 #6079 #6078 #6046 #6064 #6063 )") +- avatar [Ng Choon Khon (CK)](https://github.com/ckng0221 "+4/-4 (#6073 )") +- avatar [Muhammad Noman](https://github.com/mnomanmemon "+2/-2 (#6048 )") + +## [1.6.1](https://github.com/axios/axios/compare/v1.6.0...v1.6.1) (2023-11-08) + + +### Bug Fixes + +* **formdata:** fixed content-type header normalization for non-standard browser environments; ([#6056](https://github.com/axios/axios/issues/6056)) ([dd465ab](https://github.com/axios/axios/commit/dd465ab22bbfa262c6567be6574bf46a057d5288)) +* **platform:** fixed emulated browser detection in node.js environment; ([#6055](https://github.com/axios/axios/issues/6055)) ([3dc8369](https://github.com/axios/axios/commit/3dc8369e505e32a4e12c22f154c55fd63ac67fbb)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+432/-65 (#6059 #6056 #6055 )") +- avatar [Fabian Meyer](https://github.com/meyfa "+5/-2 (#5835 )") + +### PRs +- feat(withXSRFToken): added withXSRFToken option as a workaround to achieve the old `withCredentials` behavior; ( [#6046](https://api.github.com/repos/axios/axios/pulls/6046) ) +``` + +📢 This PR added 'withXSRFToken' option as a replacement for old withCredentials behaviour. +You should now use withXSRFToken along with withCredential to get the old behavior. +This functionality is considered as a fix. +``` + +# [1.6.0](https://github.com/axios/axios/compare/v1.5.1...v1.6.0) (2023-10-26) + + +### Bug Fixes + +* **CSRF:** fixed CSRF vulnerability CVE-2023-45857 ([#6028](https://github.com/axios/axios/issues/6028)) ([96ee232](https://github.com/axios/axios/commit/96ee232bd3ee4de2e657333d4d2191cd389e14d0)) +* **dns:** fixed lookup function decorator to work properly in node v20; ([#6011](https://github.com/axios/axios/issues/6011)) ([5aaff53](https://github.com/axios/axios/commit/5aaff532a6b820bb9ab6a8cd0f77131b47e2adb8)) +* **types:** fix AxiosHeaders types; ([#5931](https://github.com/axios/axios/issues/5931)) ([a1c8ad0](https://github.com/axios/axios/commit/a1c8ad008b3c13d53e135bbd0862587fb9d3fc09)) + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+449/-114 (#6032 #6021 #6011 #5932 #5931 )") +- avatar [Valentin Panov](https://github.com/valentin-panov "+4/-4 (#6028 )") +- avatar [Rinku Chaudhari](https://github.com/therealrinku "+1/-1 (#5889 )") + +## [1.5.1](https://github.com/axios/axios/compare/v1.5.0...v1.5.1) (2023-09-26) + + +### Bug Fixes + +* **adapters:** improved adapters loading logic to have clear error messages; ([#5919](https://github.com/axios/axios/issues/5919)) ([e410779](https://github.com/axios/axios/commit/e4107797a7a1376f6209fbecfbbce73d3faa7859)) +* **formdata:** fixed automatic addition of the `Content-Type` header for FormData in non-browser environments; ([#5917](https://github.com/axios/axios/issues/5917)) ([bc9af51](https://github.com/axios/axios/commit/bc9af51b1886d1b3529617702f2a21a6c0ed5d92)) +* **headers:** allow `content-encoding` header to handle case-insensitive values ([#5890](https://github.com/axios/axios/issues/5890)) ([#5892](https://github.com/axios/axios/issues/5892)) ([4c89f25](https://github.com/axios/axios/commit/4c89f25196525e90a6e75eda9cb31ae0a2e18acd)) +* **types:** removed duplicated code ([9e62056](https://github.com/axios/axios/commit/9e6205630e1c9cf863adf141c0edb9e6d8d4b149)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+89/-18 (#5919 #5917 )") +- avatar [David Dallas](https://github.com/DavidJDallas "+11/-5 ()") +- avatar [Sean Sattler](https://github.com/fb-sean "+2/-8 ()") +- avatar [Mustafa Ateş Uzun](https://github.com/0o001 "+4/-4 ()") +- avatar [Przemyslaw Motacki](https://github.com/sfc-gh-pmotacki "+2/-1 (#5892 )") +- avatar [Michael Di Prisco](https://github.com/Cadienvan "+1/-1 ()") + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +# [1.5.0](https://github.com/axios/axios/compare/v1.4.0...v1.5.0) (2023-08-26) + + +### Bug Fixes + +* **adapter:** make adapter loading error more clear by using platform-specific adapters explicitly ([#5837](https://github.com/axios/axios/issues/5837)) ([9a414bb](https://github.com/axios/axios/commit/9a414bb6c81796a95c6c7fe668637825458e8b6d)) +* **dns:** fixed `cacheable-lookup` integration; ([#5836](https://github.com/axios/axios/issues/5836)) ([b3e327d](https://github.com/axios/axios/commit/b3e327dcc9277bdce34c7ef57beedf644b00d628)) +* **headers:** added support for setting header names that overlap with class methods; ([#5831](https://github.com/axios/axios/issues/5831)) ([d8b4ca0](https://github.com/axios/axios/commit/d8b4ca0ea5f2f05efa4edfe1e7684593f9f68273)) +* **headers:** fixed common Content-Type header merging; ([#5832](https://github.com/axios/axios/issues/5832)) ([8fda276](https://github.com/axios/axios/commit/8fda2766b1e6bcb72c3fabc146223083ef13ce17)) + + +### Features + +* export getAdapter function ([#5324](https://github.com/axios/axios/issues/5324)) ([ca73eb8](https://github.com/axios/axios/commit/ca73eb878df0ae2dace81fe3a7f1fb5986231bf1)) +* **export:** export adapters without `unsafe` prefix ([#5839](https://github.com/axios/axios/issues/5839)) ([1601f4a](https://github.com/axios/axios/commit/1601f4a27a81ab47fea228f1e244b2c4e3ce28bf)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+66/-29 (#5839 #5837 #5836 #5832 #5831 )") +- avatar [夜葬](https://github.com/geekact "+42/-0 (#5324 )") +- avatar [Jonathan Budiman](https://github.com/JBudiman00 "+30/-0 (#5788 )") +- avatar [Michael Di Prisco](https://github.com/Cadienvan "+3/-5 (#5791 )") + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +# [1.4.0](https://github.com/axios/axios/compare/v1.3.6...v1.4.0) (2023-04-27) + + +### Bug Fixes + +* **formdata:** add `multipart/form-data` content type for FormData payload on custom client environments; ([#5678](https://github.com/axios/axios/issues/5678)) ([bbb61e7](https://github.com/axios/axios/commit/bbb61e70cb1185adfb1cbbb86eaf6652c48d89d1)) +* **package:** export package internals with unsafe path prefix; ([#5677](https://github.com/axios/axios/issues/5677)) ([df38c94](https://github.com/axios/axios/commit/df38c949f26414d88ba29ec1e353c4d4f97eaf09)) + + +### Features + +* **dns:** added support for a custom lookup function; ([#5339](https://github.com/axios/axios/issues/5339)) ([2701911](https://github.com/axios/axios/commit/2701911260a1faa5cc5e1afe437121b330a3b7bb)) +* **types:** export `AxiosHeaderValue` type. ([#5525](https://github.com/axios/axios/issues/5525)) ([726f1c8](https://github.com/axios/axios/commit/726f1c8e00cffa0461a8813a9bdcb8f8b9d762cf)) + + +### Performance Improvements + +* **merge-config:** optimize mergeConfig performance by avoiding duplicate key visits; ([#5679](https://github.com/axios/axios/issues/5679)) ([e6f7053](https://github.com/axios/axios/commit/e6f7053bf1a3e87cf1f9da8677e12e3fe829d68e)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+151/-16 (#5684 #5339 #5679 #5678 #5677 )") +- avatar [Arthur Fiorette](https://github.com/arthurfiorette "+19/-19 (#5525 )") +- avatar [PIYUSH NEGI](https://github.com/npiyush97 "+2/-18 (#5670 )") + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.3.6](https://github.com/axios/axios/compare/v1.3.5...v1.3.6) (2023-04-19) + + +### Bug Fixes + +* **types:** added transport to RawAxiosRequestConfig ([#5445](https://github.com/axios/axios/issues/5445)) ([6f360a2](https://github.com/axios/axios/commit/6f360a2531d8d70363fd9becef6a45a323f170e2)) +* **utils:** make isFormData detection logic stricter to avoid unnecessary calling of the `toString` method on the target; ([#5661](https://github.com/axios/axios/issues/5661)) ([aa372f7](https://github.com/axios/axios/commit/aa372f7306295dfd1100c1c2c77ce95c95808e76)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+48/-10 (#5665 #5661 #5663 )") +- avatar [Michael Di Prisco](https://github.com/Cadienvan "+2/-0 (#5445 )") + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.3.5](https://github.com/axios/axios/compare/v1.3.4...v1.3.5) (2023-04-05) + + +### Bug Fixes + +* **headers:** fixed isValidHeaderName to support full list of allowed characters; ([#5584](https://github.com/axios/axios/issues/5584)) ([e7decef](https://github.com/axios/axios/commit/e7decef6a99f4627e27ed9ea5b00ce8e201c3841)) +* **params:** re-added the ability to set the function as `paramsSerializer` config; ([#5633](https://github.com/axios/axios/issues/5633)) ([a56c866](https://github.com/axios/axios/commit/a56c8661209d5ce5a645a05f294a0e08a6c1f6b3)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+28/-10 (#5633 #5584 )") + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.3.4](https://github.com/axios/axios/compare/v1.3.3...v1.3.4) (2023-02-22) + + +### Bug Fixes + +* **blob:** added a check to make sure the Blob class is available in the browser's global scope; ([#5548](https://github.com/axios/axios/issues/5548)) ([3772c8f](https://github.com/axios/axios/commit/3772c8fe74112a56e3e9551f894d899bc3a9443a)) +* **http:** fixed regression bug when handling synchronous errors inside the adapter; ([#5564](https://github.com/axios/axios/issues/5564)) ([a3b246c](https://github.com/axios/axios/commit/a3b246c9de5c3bc4b5a742e15add55b375479451)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+38/-26 (#5564 )") +- avatar [lcysgsg](https://github.com/lcysgsg "+4/-0 (#5548 )") +- avatar [Michael Di Prisco](https://github.com/Cadienvan "+3/-0 (#5444 )") + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.3.3](https://github.com/axios/axios/compare/v1.3.2...v1.3.3) (2023-02-13) + + +### Bug Fixes + +* **formdata:** added a check to make sure the FormData class is available in the browser's global scope; ([#5545](https://github.com/axios/axios/issues/5545)) ([a6dfa72](https://github.com/axios/axios/commit/a6dfa72010db5ad52db8bd13c0f98e537e8fd05d)) +* **formdata:** fixed setting NaN as Content-Length for form payload in some cases; ([#5535](https://github.com/axios/axios/issues/5535)) ([c19f7bf](https://github.com/axios/axios/commit/c19f7bf770f90ae8307f4ea3104f227056912da1)) +* **headers:** fixed the filtering logic of the clear method; ([#5542](https://github.com/axios/axios/issues/5542)) ([ea87ebf](https://github.com/axios/axios/commit/ea87ebfe6d1699af072b9e7cd40faf8f14b0ab93)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+11/-7 (#5545 #5535 #5542 )") +- avatar [陈若枫](https://github.com/ruofee "+2/-2 (#5467 )") + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.3.2](https://github.com/axios/axios/compare/v1.3.1...v1.3.2) (2023-02-03) + + +### Bug Fixes + +* **http:** treat http://localhost as base URL for relative paths to avoid `ERR_INVALID_URL` error; ([#5528](https://github.com/axios/axios/issues/5528)) ([128d56f](https://github.com/axios/axios/commit/128d56f4a0fb8f5f2ed6e0dd80bc9225fee9538c)) +* **http:** use explicit import instead of TextEncoder global; ([#5530](https://github.com/axios/axios/issues/5530)) ([6b3c305](https://github.com/axios/axios/commit/6b3c305fc40c56428e0afabedc6f4d29c2830f6f)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+2/-1 (#5530 #5528 )") + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.3.1](https://github.com/axios/axios/compare/v1.3.0...v1.3.1) (2023-02-01) + + +### Bug Fixes + +* **formdata:** add hotfix to use the asynchronous API to compute the content-length header value; ([#5521](https://github.com/axios/axios/issues/5521)) ([96d336f](https://github.com/axios/axios/commit/96d336f527619f21da012fe1f117eeb53e5a2120)) +* **serializer:** fixed serialization of array-like objects; ([#5518](https://github.com/axios/axios/issues/5518)) ([08104c0](https://github.com/axios/axios/commit/08104c028c0f9353897b1b6691d74c440fd0c32d)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+27/-8 (#5521 #5518 )") + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +# [1.3.0](https://github.com/axios/axios/compare/v1.2.6...v1.3.0) (2023-01-31) + + +### Bug Fixes + +* **headers:** fixed & optimized clear method; ([#5507](https://github.com/axios/axios/issues/5507)) ([9915635](https://github.com/axios/axios/commit/9915635c69d0ab70daca5738488421f67ca60959)) +* **http:** add zlib headers if missing ([#5497](https://github.com/axios/axios/issues/5497)) ([65e8d1e](https://github.com/axios/axios/commit/65e8d1e28ce829f47a837e45129730e541950d3c)) + + +### Features + +* **fomdata:** added support for spec-compliant FormData & Blob types; ([#5316](https://github.com/axios/axios/issues/5316)) ([6ac574e](https://github.com/axios/axios/commit/6ac574e00a06731288347acea1e8246091196953)) + +### Contributors to this release + +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+352/-67 (#5514 #5512 #5510 #5509 #5508 #5316 #5507 )") +- avatar [ItsNotGoodName](https://github.com/ItsNotGoodName "+43/-2 (#5497 )") + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.2.6](https://github.com/axios/axios/compare/v1.2.5...v1.2.6) (2023-01-28) + + +### Bug Fixes + +* **headers:** added missed Authorization accessor; ([#5502](https://github.com/axios/axios/issues/5502)) ([342c0ba](https://github.com/axios/axios/commit/342c0ba9a16ea50f5ed7d2366c5c1a2c877e3f26)) +* **types:** fixed `CommonRequestHeadersList` & `CommonResponseHeadersList` types to be private in commonJS; ([#5503](https://github.com/axios/axios/issues/5503)) ([5a3d0a3](https://github.com/axios/axios/commit/5a3d0a3234d77361a1bc7cedee2da1e11df08e2c)) + +### Contributors to this release + +- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+24/-9 (#5503 #5502 )") + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.2.5](https://github.com/axios/axios/compare/v1.2.4...v1.2.5) (2023-01-26) + + +### Bug Fixes + +* **types:** fixed AxiosHeaders to handle spread syntax by making all methods non-enumerable; ([#5499](https://github.com/axios/axios/issues/5499)) ([580f1e8](https://github.com/axios/axios/commit/580f1e8033a61baa38149d59fd16019de3932c22)) + +### Contributors to this release + +- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+82/-54 (#5499 )") +- ![avatar](https://avatars.githubusercontent.com/u/20516159?v=4&s=16) [Elliot Ford](https://github.com/EFord36 "+1/-1 (#5462 )") + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.2.4](https://github.com/axios/axios/compare/v1.2.3...v1.2.4) (2023-01-22) + + +### Bug Fixes + +* **types:** renamed `RawAxiosRequestConfig` back to `AxiosRequestConfig`; ([#5486](https://github.com/axios/axios/issues/5486)) ([2a71f49](https://github.com/axios/axios/commit/2a71f49bc6c68495fa419003a3107ed8bd703ad0)) +* **types:** fix `AxiosRequestConfig` generic; ([#5478](https://github.com/axios/axios/issues/5478)) ([9bce81b](https://github.com/axios/axios/commit/186ea062da8b7d578ae78b1a5c220986b9bce81b)) + +### Contributors to this release + +- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+242/-108 (#5486 #5482 )") +- ![avatar](https://avatars.githubusercontent.com/u/9430821?v=4&s=16) [Daniel Hillmann](https://github.com/hilleer "+1/-1 (#5478 )") + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.2.3](https://github.com/axios/axios/compare/1.2.2...1.2.3) (2023-01-10) + + +### Bug Fixes + +* **types:** fixed AxiosRequestConfig header interface by refactoring it to RawAxiosRequestConfig; ([#5420](https://github.com/axios/axios/issues/5420)) ([0811963](https://github.com/axios/axios/commit/08119634a22f1d5b19f5c9ea0adccb6d3eebc3bc)) + +### Contributors to this release + +- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+938/-442 (#5456 #5455 #5453 #5451 #5449 #5447 #5446 #5443 #5442 #5439 #5420 )") + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.2.2] - 2022-12-29 + +### Fixed +- fix(ci): fix release script inputs [#5392](https://github.com/axios/axios/pull/5392) +- fix(ci): prerelease scipts [#5377](https://github.com/axios/axios/pull/5377) +- fix(ci): release scripts [#5376](https://github.com/axios/axios/pull/5376) +- fix(ci): typescript tests [#5375](https://github.com/axios/axios/pull/5375) +- fix: Brotli decompression [#5353](https://github.com/axios/axios/pull/5353) +- fix: add missing HttpStatusCode [#5345](https://github.com/axios/axios/pull/5345) + +### Chores +- chore(ci): set conventional-changelog header config [#5406](https://github.com/axios/axios/pull/5406) +- chore(ci): fix automatic contributors resolving [#5403](https://github.com/axios/axios/pull/5403) +- chore(ci): improved logging for the contributors list generator [#5398](https://github.com/axios/axios/pull/5398) +- chore(ci): fix release action [#5397](https://github.com/axios/axios/pull/5397) +- chore(ci): fix version bump script by adding bump argument for target version [#5393](https://github.com/axios/axios/pull/5393) +- chore(deps): bump decode-uri-component from 0.2.0 to 0.2.2 [#5342](https://github.com/axios/axios/pull/5342) +- chore(ci): GitHub Actions Release script [#5384](https://github.com/axios/axios/pull/5384) +- chore(ci): release scripts [#5364](https://github.com/axios/axios/pull/5364) + +### Contributors to this release +- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS) +- ![avatar](https://avatars.githubusercontent.com/u/1652293?v=4&s=16) [Winnie](https://github.com/winniehell) + +## [1.2.1] - 2022-12-05 + +### Changed +- feat(exports): export mergeConfig [#5151](https://github.com/axios/axios/pull/5151) + +### Fixed +- fix(CancelledError): include config [#4922](https://github.com/axios/axios/pull/4922) +- fix(general): removing multiple/trailing/leading whitespace [#5022](https://github.com/axios/axios/pull/5022) +- fix(headers): decompression for responses without Content-Length header [#5306](https://github.com/axios/axios/pull/5306) +- fix(webWorker): exception to sending form data in web worker [#5139](https://github.com/axios/axios/pull/5139) + +### Refactors +- refactor(types): AxiosProgressEvent.event type to any [#5308](https://github.com/axios/axios/pull/5308) +- refactor(types): add missing types for static AxiosError.from method [#4956](https://github.com/axios/axios/pull/4956) + +### Chores +- chore(docs): remove README link to non-existent upgrade guide [#5307](https://github.com/axios/axios/pull/5307) +- chore(docs): typo in issue template name [#5159](https://github.com/axios/axios/pull/5159) + +### Contributors to this release + +- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS) +- [Zachary Lysobey](https://github.com/zachlysobey) +- [Kevin Ennis](https://github.com/kevincennis) +- [Philipp Loose](https://github.com/phloose) +- [secondl1ght](https://github.com/secondl1ght) +- [wenzheng](https://github.com/0x30) +- [Ivan Barsukov](https://github.com/ovarn) +- [Arthur Fiorette](https://github.com/arthurfiorette) + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.2.0] - 2022-11-10 + +### Changed + +- changed: refactored module exports [#5162](https://github.com/axios/axios/pull/5162) +- change: re-added support for loading Axios with require('axios').default [#5225](https://github.com/axios/axios/pull/5225) + +### Fixed + +- fix: improve AxiosHeaders class [#5224](https://github.com/axios/axios/pull/5224) +- fix: TypeScript type definitions for commonjs [#5196](https://github.com/axios/axios/pull/5196) +- fix: type definition of use method on AxiosInterceptorManager to match the the README [#5071](https://github.com/axios/axios/pull/5071) +- fix: __dirname is not defined in the sandbox [#5269](https://github.com/axios/axios/pull/5269) +- fix: AxiosError.toJSON method to avoid circular references [#5247](https://github.com/axios/axios/pull/5247) +- fix: Z_BUF_ERROR when content-encoding is set but the response body is empty [#5250](https://github.com/axios/axios/pull/5250) + +### Refactors +- refactor: allowing adapters to be loaded by name [#5277](https://github.com/axios/axios/pull/5277) + +### Chores + +- chore: force CI restart [#5243](https://github.com/axios/axios/pull/5243) +- chore: update ECOSYSTEM.md [#5077](https://github.com/axios/axios/pull/5077) +- chore: update get/index.html [#5116](https://github.com/axios/axios/pull/5116) +- chore: update Sandbox UI/UX [#5205](https://github.com/axios/axios/pull/5205) +- chore:(actions): remove git credentials after checkout [#5235](https://github.com/axios/axios/pull/5235) +- chore(actions): bump actions/dependency-review-action from 2 to 3 [#5266](https://github.com/axios/axios/pull/5266) +- chore(packages): bump loader-utils from 1.4.1 to 1.4.2 [#5295](https://github.com/axios/axios/pull/5295) +- chore(packages): bump engine.io from 6.2.0 to 6.2.1 [#5294](https://github.com/axios/axios/pull/5294) +- chore(packages): bump socket.io-parser from 4.0.4 to 4.0.5 [#5241](https://github.com/axios/axios/pull/5241) +- chore(packages): bump loader-utils from 1.4.0 to 1.4.1 [#5245](https://github.com/axios/axios/pull/5245) +- chore(docs): update Resources links in README [#5119](https://github.com/axios/axios/pull/5119) +- chore(docs): update the link for JSON url [#5265](https://github.com/axios/axios/pull/5265) +- chore(docs): fix broken links [#5218](https://github.com/axios/axios/pull/5218) +- chore(docs): update and rename UPGRADE_GUIDE.md to MIGRATION_GUIDE.md [#5170](https://github.com/axios/axios/pull/5170) +- chore(docs): typo fix line #856 and #920 [#5194](https://github.com/axios/axios/pull/5194) +- chore(docs): typo fix #800 [#5193](https://github.com/axios/axios/pull/5193) +- chore(docs): fix typos [#5184](https://github.com/axios/axios/pull/5184) +- chore(docs): fix punctuation in README.md [#5197](https://github.com/axios/axios/pull/5197) +- chore(docs): update readme in the Handling Errors section - issue reference #5260 [#5261](https://github.com/axios/axios/pull/5261) +- chore: remove \b from filename [#5207](https://github.com/axios/axios/pull/5207) +- chore(docs): update CHANGELOG.md [#5137](https://github.com/axios/axios/pull/5137) +- chore: add sideEffects false to package.json [#5025](https://github.com/axios/axios/pull/5025) + +### Contributors to this release + +- [Maddy Miller](https://github.com/me4502) +- [Amit Saini](https://github.com/amitsainii) +- [ecyrbe](https://github.com/ecyrbe) +- [Ikko Ashimine](https://github.com/eltociear) +- [Geeth Gunnampalli](https://github.com/thetechie7) +- [Shreem Asati](https://github.com/shreem-123) +- [Frieder Bluemle](https://github.com/friederbluemle) +- [윤세영](https://github.com/yunseyeong) +- [Claudio Busatto](https://github.com/cjcbusatto) +- [Remco Haszing](https://github.com/remcohaszing) +- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS) +- [Csaba Maulis](https://github.com/om4csaba) +- [MoPaMo](https://github.com/MoPaMo) +- [Daniel Fjeldstad](https://github.com/w3bdesign) +- [Adrien Brunet](https://github.com/adrien-may) +- [Frazer Smith](https://github.com/Fdawgs) +- [HaiTao](https://github.com/836334258) +- [AZM](https://github.com/aziyatali) +- [relbns](https://github.com/relbns) + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.1.3] - 2022-10-15 + +### Added + +- Added custom params serializer support [#5113](https://github.com/axios/axios/pull/5113) + +### Fixed + +- Fixed top-level export to keep them in-line with static properties [#5109](https://github.com/axios/axios/pull/5109) +- Stopped including null values to query string. [#5108](https://github.com/axios/axios/pull/5108) +- Restored proxy config backwards compatibility with 0.x [#5097](https://github.com/axios/axios/pull/5097) +- Added back AxiosHeaders in AxiosHeaderValue [#5103](https://github.com/axios/axios/pull/5103) +- Pin CDN install instructions to a specific version [#5060](https://github.com/axios/axios/pull/5060) +- Handling of array values fixed for AxiosHeaders [#5085](https://github.com/axios/axios/pull/5085) + +### Chores + +- docs: match badge style, add link to them [#5046](https://github.com/axios/axios/pull/5046) +- chore: fixing comments typo [#5054](https://github.com/axios/axios/pull/5054) +- chore: update issue template [#5061](https://github.com/axios/axios/pull/5061) +- chore: added progress capturing section to the docs; [#5084](https://github.com/axios/axios/pull/5084) + +### Contributors to this release + +- [Jason Saayman](https://github.com/jasonsaayman) +- [scarf](https://github.com/scarf005) +- [Lenz Weber-Tronic](https://github.com/phryneas) +- [Arvindh](https://github.com/itsarvindh) +- [Félix Legrelle](https://github.com/FelixLgr) +- [Patrick Petrovic](https://github.com/ppati000) +- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS) +- [littledian](https://github.com/littledian) +- [ChronosMasterOfAllTime](https://github.com/ChronosMasterOfAllTime) + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.1.2] - 2022-10-07 + +### Fixed + +- Fixed broken exports for UMD builds. + +### Contributors to this release + +- [Jason Saayman](https://github.com/jasonsaayman) + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.1.1] - 2022-10-07 + +### Fixed + +- Fixed broken exports for common js. This fix breaks a prior fix, I will fix both issues ASAP but the commonJS use is more impactful. + +### Contributors to this release + +- [Jason Saayman](https://github.com/jasonsaayman) + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.1.0] - 2022-10-06 + +### Fixed + +- Fixed missing exports in type definition index.d.ts [#5003](https://github.com/axios/axios/pull/5003) +- Fixed query params composing [#5018](https://github.com/axios/axios/pull/5018) +- Fixed GenericAbortSignal interface by making it more generic [#5021](https://github.com/axios/axios/pull/5021) +- Fixed adding "clear" to AxiosInterceptorManager [#5010](https://github.com/axios/axios/pull/5010) +- Fixed commonjs & umd exports [#5030](https://github.com/axios/axios/pull/5030) +- Fixed inability to access response headers when using axios 1.x with Jest [#5036](https://github.com/axios/axios/pull/5036) + +### Contributors to this release + +- [Trim21](https://github.com/trim21) +- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS) +- [shingo.sasaki](https://github.com/s-sasaki-0529) +- [Ivan Pepelko](https://github.com/ivanpepelko) +- [Richard Kořínek](https://github.com/risa) + +### PRs +- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) ) +``` + +⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459 +``` + +## [1.0.0] - 2022-10-04 + +### Added + +- Added stack trace to AxiosError [#4624](https://github.com/axios/axios/pull/4624) +- Add AxiosError to AxiosStatic [#4654](https://github.com/axios/axios/pull/4654) +- Replaced Rollup as our build runner [#4596](https://github.com/axios/axios/pull/4596) +- Added generic TS types for the exposed toFormData helper [#4668](https://github.com/axios/axios/pull/4668) +- Added listen callback function [#4096](https://github.com/axios/axios/pull/4096) +- Added instructions for installing using PNPM [#4207](https://github.com/axios/axios/pull/4207) +- Added generic AxiosAbortSignal TS interface to avoid importing AbortController polyfill [#4229](https://github.com/axios/axios/pull/4229) +- Added axios-url-template in ECOSYSTEM.md [#4238](https://github.com/axios/axios/pull/4238) +- Added a clear() function to the request and response interceptors object so a user can ensure that all interceptors have been removed from an axios instance [#4248](https://github.com/axios/axios/pull/4248) +- Added react hook plugin [#4319](https://github.com/axios/axios/pull/4319) +- Adding HTTP status code for transformResponse [#4580](https://github.com/axios/axios/pull/4580) +- Added blob to the list of protocols supported by the browser [#4678](https://github.com/axios/axios/pull/4678) +- Resolving proxy from env on redirect [#4436](https://github.com/axios/axios/pull/4436) +- Added enhanced toFormData implementation with additional options [4704](https://github.com/axios/axios/pull/4704) +- Adding Canceler parameters config and request [#4711](https://github.com/axios/axios/pull/4711) +- Added automatic payload serialization to application/x-www-form-urlencoded [#4714](https://github.com/axios/axios/pull/4714) +- Added the ability for webpack users to overwrite built-ins [#4715](https://github.com/axios/axios/pull/4715) +- Added string[] to AxiosRequestHeaders type [#4322](https://github.com/axios/axios/pull/4322) +- Added the ability for the url-encoded-form serializer to respect the formSerializer config [#4721](https://github.com/axios/axios/pull/4721) +- Added isCancel type assert [#4293](https://github.com/axios/axios/pull/4293) +- Added data URL support for node.js [#4725](https://github.com/axios/axios/pull/4725) +- Adding types for progress event callbacks [#4675](https://github.com/axios/axios/pull/4675) +- URL params serializer [#4734](https://github.com/axios/axios/pull/4734) +- Added axios.formToJSON method [#4735](https://github.com/axios/axios/pull/4735) +- Bower platform add data protocol [#4804](https://github.com/axios/axios/pull/4804) +- Use WHATWG URL API instead of url.parse() [#4852](https://github.com/axios/axios/pull/4852) +- Add ENUM containing Http Status Codes to typings [#4903](https://github.com/axios/axios/pull/4903) +- Improve typing of timeout in index.d.ts [#4934](https://github.com/axios/axios/pull/4934) + +### Changed + +- Updated AxiosError.config to be optional in the type definition [#4665](https://github.com/axios/axios/pull/4665) +- Updated README emphasizing the URLSearchParam built-in interface over other solutions [#4590](https://github.com/axios/axios/pull/4590) +- Include request and config when creating a CanceledError instance [#4659](https://github.com/axios/axios/pull/4659) +- Changed func-names eslint rule to as-needed [#4492](https://github.com/axios/axios/pull/4492) +- Replacing deprecated substr() with slice() as substr() is deprecated [#4468](https://github.com/axios/axios/pull/4468) +- Updating HTTP links in README.md to use HTTPS [#4387](https://github.com/axios/axios/pull/4387) +- Updated to a better trim() polyfill [#4072](https://github.com/axios/axios/pull/4072) +- Updated types to allow specifying partial default headers on instance create [#4185](https://github.com/axios/axios/pull/4185) +- Expanded isAxiosError types [#4344](https://github.com/axios/axios/pull/4344) +- Updated type definition for axios instance methods [#4224](https://github.com/axios/axios/pull/4224) +- Updated eslint config [#4722](https://github.com/axios/axios/pull/4722) +- Updated Docs [#4742](https://github.com/axios/axios/pull/4742) +- Refactored Axios to use ES2017 [#4787](https://github.com/axios/axios/pull/4787) + + +### Deprecated +- There are multiple deprecations, refactors and fixes provided in this release. Please read through the full release notes to see how this may impact your project and use case. + +### Removed + +- Removed incorrect argument for NetworkError constructor [#4656](https://github.com/axios/axios/pull/4656) +- Removed Webpack [#4596](https://github.com/axios/axios/pull/4596) +- Removed function that transform arguments to array [#4544](https://github.com/axios/axios/pull/4544) + +### Fixed + +- Fixed grammar in README [#4649](https://github.com/axios/axios/pull/4649) +- Fixed code error in README [#4599](https://github.com/axios/axios/pull/4599) +- Optimized the code that checks cancellation [#4587](https://github.com/axios/axios/pull/4587) +- Fix url pointing to defaults.js in README [#4532](https://github.com/axios/axios/pull/4532) +- Use type alias instead of interface for AxiosPromise [#4505](https://github.com/axios/axios/pull/4505) +- Fix some word spelling and lint style in code comments [#4500](https://github.com/axios/axios/pull/4500) +- Edited readme with 3 updated browser icons of Chrome, FireFox and Safari [#4414](https://github.com/axios/axios/pull/4414) +- Bump follow-redirects from 1.14.9 to 1.15.0 [#4673](https://github.com/axios/axios/pull/4673) +- Fixing http tests to avoid hanging when assertions fail [#4435](https://github.com/axios/axios/pull/4435) +- Fix TS definition for AxiosRequestTransformer [#4201](https://github.com/axios/axios/pull/4201) +- Fix grammatical issues in README [#4232](https://github.com/axios/axios/pull/4232) +- Fixing instance.defaults.headers type [#4557](https://github.com/axios/axios/pull/4557) +- Fixed race condition on immediate requests cancellation [#4261](https://github.com/axios/axios/pull/4261) +- Fixing Z_BUF_ERROR when no content [#4701](https://github.com/axios/axios/pull/4701) +- Fixing proxy beforeRedirect regression [#4708](https://github.com/axios/axios/pull/4708) +- Fixed AxiosError status code type [#4717](https://github.com/axios/axios/pull/4717) +- Fixed AxiosError stack capturing [#4718](https://github.com/axios/axios/pull/4718) +- Fixing AxiosRequestHeaders typings [#4334](https://github.com/axios/axios/pull/4334) +- Fixed max body length defaults [#4731](https://github.com/axios/axios/pull/4731) +- Fixed toFormData Blob issue on node>v17 [#4728](https://github.com/axios/axios/pull/4728) +- Bump grunt from 1.5.2 to 1.5.3 [#4743](https://github.com/axios/axios/pull/4743) +- Fixing content-type header repeated [#4745](https://github.com/axios/axios/pull/4745) +- Fixed timeout error message for http [4738](https://github.com/axios/axios/pull/4738) +- Request ignores false, 0 and empty string as body values [#4785](https://github.com/axios/axios/pull/4785) +- Added back missing minified builds [#4805](https://github.com/axios/axios/pull/4805) +- Fixed a type error [#4815](https://github.com/axios/axios/pull/4815) +- Fixed a regression bug with unsubscribing from cancel token; [#4819](https://github.com/axios/axios/pull/4819) +- Remove repeated compression algorithm [#4820](https://github.com/axios/axios/pull/4820) +- The error of calling extend to pass parameters [#4857](https://github.com/axios/axios/pull/4857) +- SerializerOptions.indexes allows boolean | null | undefined [#4862](https://github.com/axios/axios/pull/4862) +- Require interceptors to return values [#4874](https://github.com/axios/axios/pull/4874) +- Removed unused imports [#4949](https://github.com/axios/axios/pull/4949) +- Allow null indexes on formSerializer and paramsSerializer [#4960](https://github.com/axios/axios/pull/4960) + +### Chores +- Set permissions for GitHub actions [#4765](https://github.com/axios/axios/pull/4765) +- Included githubactions in the dependabot config [#4770](https://github.com/axios/axios/pull/4770) +- Included dependency review [#4771](https://github.com/axios/axios/pull/4771) +- Update security.md [#4784](https://github.com/axios/axios/pull/4784) +- Remove unnecessary spaces [#4854](https://github.com/axios/axios/pull/4854) +- Simplify the import path of AxiosError [#4875](https://github.com/axios/axios/pull/4875) +- Fix Gitpod dead link [#4941](https://github.com/axios/axios/pull/4941) +- Enable syntax highlighting for a code block [#4970](https://github.com/axios/axios/pull/4970) +- Using Logo Axios in Readme.md [#4993](https://github.com/axios/axios/pull/4993) +- Fix markup for note in README [#4825](https://github.com/axios/axios/pull/4825) +- Fix typo and formatting, add colons [#4853](https://github.com/axios/axios/pull/4853) +- Fix typo in readme [#4942](https://github.com/axios/axios/pull/4942) + +### Security + +- Update SECURITY.md [#4687](https://github.com/axios/axios/pull/4687) + +### Contributors to this release + +- [Bertrand Marron](https://github.com/tusbar) +- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS) +- [Dan Mooney](https://github.com/danmooney) +- [Michael Li](https://github.com/xiaoyu-tamu) +- [aong](https://github.com/yxwzaxns) +- [Des Preston](https://github.com/despreston) +- [Ted Robertson](https://github.com/tredondo) +- [zhoulixiang](https://github.com/zh-lx) +- [Arthur Fiorette](https://github.com/arthurfiorette) +- [Kumar Shanu](https://github.com/Kr-Shanu) +- [JALAL](https://github.com/JLL32) +- [Jingyi Lin](https://github.com/MageeLin) +- [Philipp Loose](https://github.com/phloose) +- [Alexander Shchukin](https://github.com/sashsvamir) +- [Dave Cardwell](https://github.com/davecardwell) +- [Cat Scarlet](https://github.com/catscarlet) +- [Luca Pizzini](https://github.com/lpizzinidev) +- [Kai](https://github.com/Schweinepriester) +- [Maxime Bargiel](https://github.com/mbargiel) +- [Brian Helba](https://github.com/brianhelba) +- [reslear](https://github.com/reslear) +- [Jamie Slome](https://github.com/JamieSlome) +- [Landro3](https://github.com/Landro3) +- [rafw87](https://github.com/rafw87) +- [Afzal Sayed](https://github.com/afzalsayed96) +- [Koki Oyatsu](https://github.com/kaishuu0123) +- [Dave](https://github.com/wangcch) +- [暴走老七](https://github.com/baozouai) +- [Spencer](https://github.com/spalger) +- [Adrian Wieprzkowicz](https://github.com/Argeento) +- [Jamie Telin](https://github.com/lejahmie) +- [毛呆](https://github.com/aweikalee) +- [Kirill Shakirov](https://github.com/turisap) +- [Rraji Abdelbari](https://github.com/estarossa0) +- [Jelle Schutter](https://github.com/jelleschutter) +- [Tom Ceuppens](https://github.com/KyorCode) +- [Johann Cooper](https://github.com/JohannCooper) +- [Dimitris Halatsis](https://github.com/mitsos1os) +- [chenjigeng](https://github.com/chenjigeng) +- [João Gabriel Quaresma](https://github.com/joaoGabriel55) +- [Victor Augusto](https://github.com/VictorAugDB) +- [neilnaveen](https://github.com/neilnaveen) +- [Pavlos](https://github.com/psmoros) +- [Kiryl Valkovich](https://github.com/visortelle) +- [Naveen](https://github.com/naveensrinivasan) +- [wenzheng](https://github.com/0x30) +- [hcwhan](https://github.com/hcwhan) +- [Bassel Rachid](https://github.com/basselworkforce) +- [Grégoire Pineau](https://github.com/lyrixx) +- [felipedamin](https://github.com/felipedamin) +- [Karl Horky](https://github.com/karlhorky) +- [Yue JIN](https://github.com/kingyue737) +- [Usman Ali Siddiqui](https://github.com/usman250994) +- [WD](https://github.com/techbirds) +- [Günther Foidl](https://github.com/gfoidl) +- [Stephen Jennings](https://github.com/jennings) +- [C.T.Lin](https://github.com/chentsulin) +- [mia-z](https://github.com/mia-z) +- [Parth Banathia](https://github.com/Parth0105) +- [parth0105pluang](https://github.com/parth0105pluang) +- [Marco Weber](https://github.com/mrcwbr) +- [Luca Pizzini](https://github.com/lpizzinidev) +- [Willian Agostini](https://github.com/WillianAgostini) +- [Huyen Nguyen](https://github.com/huyenltnguyen) \ No newline at end of file diff --git a/node_modules/axios/LICENSE b/node_modules/axios/LICENSE new file mode 100644 index 000000000..05006a51e --- /dev/null +++ b/node_modules/axios/LICENSE @@ -0,0 +1,7 @@ +# Copyright (c) 2014-present Matt Zabriskie & Collaborators + +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/node_modules/axios/MIGRATION_GUIDE.md b/node_modules/axios/MIGRATION_GUIDE.md new file mode 100644 index 000000000..ec3ae0da9 --- /dev/null +++ b/node_modules/axios/MIGRATION_GUIDE.md @@ -0,0 +1,3 @@ +# Migration Guide + +## 0.x.x -> 1.1.0 diff --git a/node_modules/axios/README.md b/node_modules/axios/README.md new file mode 100644 index 000000000..f92b3b851 --- /dev/null +++ b/node_modules/axios/README.md @@ -0,0 +1,1657 @@ + +

🥇 Gold sponsors

Stytch

API-first authentication, authorization, and fraud prevention

Website | Documentation | Node.js

+
Principal Financial Group

We’re bound by one common purpose: to give you the financial tools, resources and information you ne...

www.principal.com

+
Descope

Hi, we're Descope! We are building something in the authentication space for app developers and...

Website | Documentation | Community

+
Buzzoid - Buy Instagram Followers

At Buzzoid, you can buy Instagram followers quickly, safely, and easily with just a few clicks. Rate...

buzzoid.com

+
Famety - Buy Instagram Followers

At Famety, you can grow your social media following quickly, safely, and easily with just a few clic...

www.famety.com

+
Poprey - Buy Instagram Likes

Buy Instagram Likes

poprey.com

+
💜 Become a sponsor + 💜 Become a sponsor + 💜 Become a sponsor +
+ + +

+
+
+
+ +

Promise based HTTP client for the browser and node.js

+ +

+ Website • + Documentation +

+ +
+ +[![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios) +[![CDNJS](https://img.shields.io/cdnjs/v/axios.svg?style=flat-square)](https://cdnjs.com/libraries/axios) +[![Build status](https://img.shields.io/github/actions/workflow/status/axios/axios/ci.yml?branch=v1.x&label=CI&logo=github&style=flat-square)](https://github.com/axios/axios/actions/workflows/ci.yml) +[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod&style=flat-square)](https://gitpod.io/#https://github.com/axios/axios) +[![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios) +[![install size](https://img.shields.io/badge/dynamic/json?url=https://packagephobia.com/v2/api.json?p=axios&query=$.install.pretty&label=install%20size&style=flat-square)](https://packagephobia.now.sh/result?p=axios) +[![npm bundle size](https://img.shields.io/bundlephobia/minzip/axios?style=flat-square)](https://bundlephobia.com/package/axios@latest) +[![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](https://npm-stat.com/charts.html?package=axios) +[![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios) +[![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios) +[![Known Vulnerabilities](https://snyk.io/test/npm/axios/badge.svg)](https://snyk.io/test/npm/axios) + + + + +
+ +## Table of Contents + + - [Features](#features) + - [Browser Support](#browser-support) + - [Installing](#installing) + - [Package manager](#package-manager) + - [CDN](#cdn) + - [Example](#example) + - [Axios API](#axios-api) + - [Request method aliases](#request-method-aliases) + - [Concurrency 👎](#concurrency-deprecated) + - [Creating an instance](#creating-an-instance) + - [Instance methods](#instance-methods) + - [Request Config](#request-config) + - [Response Schema](#response-schema) + - [Config Defaults](#config-defaults) + - [Global axios defaults](#global-axios-defaults) + - [Custom instance defaults](#custom-instance-defaults) + - [Config order of precedence](#config-order-of-precedence) + - [Interceptors](#interceptors) + - [Multiple Interceptors](#multiple-interceptors) + - [Handling Errors](#handling-errors) + - [Cancellation](#cancellation) + - [AbortController](#abortcontroller) + - [CancelToken 👎](#canceltoken-deprecated) + - [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format) + - [URLSearchParams](#urlsearchparams) + - [Query string](#query-string-older-browsers) + - [🆕 Automatic serialization](#-automatic-serialization-to-urlsearchparams) + - [Using multipart/form-data format](#using-multipartform-data-format) + - [FormData](#formdata) + - [🆕 Automatic serialization](#-automatic-serialization-to-formdata) + - [Files Posting](#files-posting) + - [HTML Form Posting](#-html-form-posting-browser) + - [🆕 Progress capturing](#-progress-capturing) + - [🆕 Rate limiting](#-progress-capturing) + - [🆕 AxiosHeaders](#-axiosheaders) + - [🔥 Fetch adapter](#-fetch-adapter) + - [Semver](#semver) + - [Promises](#promises) + - [TypeScript](#typescript) + - [Resources](#resources) + - [Credits](#credits) + - [License](#license) + +## Features + +- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser +- Make [http](https://nodejs.org/api/http.html) requests from node.js +- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API +- Intercept request and response +- Transform request and response data +- Cancel requests +- Automatic transforms for [JSON](https://www.json.org/json-en.html) data +- 🆕 Automatic data object serialization to `multipart/form-data` and `x-www-form-urlencoded` body encodings +- Client side support for protecting against [XSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery) + +## Browser Support + +![Chrome](https://raw.githubusercontent.com/alrra/browser-logos/main/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.githubusercontent.com/alrra/browser-logos/main/src/firefox/firefox_48x48.png) | ![Safari](https://raw.githubusercontent.com/alrra/browser-logos/main/src/safari/safari_48x48.png) | ![Opera](https://raw.githubusercontent.com/alrra/browser-logos/main/src/opera/opera_48x48.png) | ![Edge](https://raw.githubusercontent.com/alrra/browser-logos/main/src/edge/edge_48x48.png) | +--- | --- | --- | --- | --- | +Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ | + +[![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios) + +## Installing + +### Package manager + +Using npm: + +```bash +$ npm install axios +``` + +Using bower: + +```bash +$ bower install axios +``` + +Using yarn: + +```bash +$ yarn add axios +``` + +Using pnpm: + +```bash +$ pnpm add axios +``` + +Once the package is installed, you can import the library using `import` or `require` approach: + +```js +import axios, {isCancel, AxiosError} from 'axios'; +``` + +You can also use the default export, since the named export is just a re-export from the Axios factory: + +```js +import axios from 'axios'; + +console.log(axios.isCancel('something')); +```` + +If you use `require` for importing, **only default export is available**: + +```js +const axios = require('axios'); + +console.log(axios.isCancel('something')); +``` + +For some bundlers and some ES6 linter's you may need to do the following: + +```js +import { default as axios } from 'axios'; +``` + +For cases where something went wrong when trying to import a module into a custom or legacy environment, +you can try importing the module package directly: + +```js +const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017) +// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017) +``` + +### CDN + +Using jsDelivr CDN (ES5 UMD browser module): + +```html + +``` + +Using unpkg CDN: + +```html + +``` + +## Example + +> **Note**: CommonJS usage +> In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()`, use the following approach: + +```js +import axios from 'axios'; +//const axios = require('axios'); // legacy way + +// Make a request for a user with a given ID +axios.get('/user?ID=12345') + .then(function (response) { + // handle success + console.log(response); + }) + .catch(function (error) { + // handle error + console.log(error); + }) + .finally(function () { + // always executed + }); + +// Optionally the request above could also be done as +axios.get('/user', { + params: { + ID: 12345 + } + }) + .then(function (response) { + console.log(response); + }) + .catch(function (error) { + console.log(error); + }) + .finally(function () { + // always executed + }); + +// Want to use async/await? Add the `async` keyword to your outer function/method. +async function getUser() { + try { + const response = await axios.get('/user?ID=12345'); + console.log(response); + } catch (error) { + console.error(error); + } +} +``` + +> **Note**: `async/await` is part of ECMAScript 2017 and is not supported in Internet +> Explorer and older browsers, so use with caution. + +Performing a `POST` request + +```js +axios.post('/user', { + firstName: 'Fred', + lastName: 'Flintstone' + }) + .then(function (response) { + console.log(response); + }) + .catch(function (error) { + console.log(error); + }); +``` + +Performing multiple concurrent requests + +```js +function getUserAccount() { + return axios.get('/user/12345'); +} + +function getUserPermissions() { + return axios.get('/user/12345/permissions'); +} + +Promise.all([getUserAccount(), getUserPermissions()]) + .then(function (results) { + const acct = results[0]; + const perm = results[1]; + }); +``` + +## axios API + +Requests can be made by passing the relevant config to `axios`. + +##### axios(config) + +```js +// Send a POST request +axios({ + method: 'post', + url: '/user/12345', + data: { + firstName: 'Fred', + lastName: 'Flintstone' + } +}); +``` + +```js +// GET request for remote image in node.js +axios({ + method: 'get', + url: 'https://bit.ly/2mTM3nY', + responseType: 'stream' +}) + .then(function (response) { + response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) + }); +``` + +##### axios(url[, config]) + +```js +// Send a GET request (default method) +axios('/user/12345'); +``` + +### Request method aliases + +For convenience, aliases have been provided for all common request methods. + +##### axios.request(config) +##### axios.get(url[, config]) +##### axios.delete(url[, config]) +##### axios.head(url[, config]) +##### axios.options(url[, config]) +##### axios.post(url[, data[, config]]) +##### axios.put(url[, data[, config]]) +##### axios.patch(url[, data[, config]]) + +###### NOTE +When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. + +### Concurrency (Deprecated) +Please use `Promise.all` to replace the below functions. + +Helper functions for dealing with concurrent requests. + +axios.all(iterable) +axios.spread(callback) + +### Creating an instance + +You can create a new instance of axios with a custom config. + +##### axios.create([config]) + +```js +const instance = axios.create({ + baseURL: 'https://some-domain.com/api/', + timeout: 1000, + headers: {'X-Custom-Header': 'foobar'} +}); +``` + +### Instance methods + +The available instance methods are listed below. The specified config will be merged with the instance config. + +##### axios#request(config) +##### axios#get(url[, config]) +##### axios#delete(url[, config]) +##### axios#head(url[, config]) +##### axios#options(url[, config]) +##### axios#post(url[, data[, config]]) +##### axios#put(url[, data[, config]]) +##### axios#patch(url[, data[, config]]) +##### axios#getUri([config]) + +## Request Config + +These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified. + +```js +{ + // `url` is the server URL that will be used for the request + url: '/user', + + // `method` is the request method to be used when making the request + method: 'get', // default + + // `baseURL` will be prepended to `url` unless `url` is absolute. + // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs + // to methods of that instance. + baseURL: 'https://some-domain.com/api/', + + // `transformRequest` allows changes to the request data before it is sent to the server + // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' + // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, + // FormData or Stream + // You may modify the headers object. + transformRequest: [function (data, headers) { + // Do whatever you want to transform the data + + return data; + }], + + // `transformResponse` allows changes to the response data to be made before + // it is passed to then/catch + transformResponse: [function (data) { + // Do whatever you want to transform the data + + return data; + }], + + // `headers` are custom headers to be sent + headers: {'X-Requested-With': 'XMLHttpRequest'}, + + // `params` are the URL parameters to be sent with the request + // Must be a plain object or a URLSearchParams object + params: { + ID: 12345 + }, + + // `paramsSerializer` is an optional config that allows you to customize serializing `params`. + paramsSerializer: { + + //Custom encoder function which sends key/value pairs in an iterative fashion. + encode?: (param: string): string => { /* Do custom operations here and return transformed string */ }, + + // Custom serializer function for the entire parameter. Allows user to mimic pre 1.x behaviour. + serialize?: (params: Record, options?: ParamsSerializerOptions ), + + //Configuration for formatting array indexes in the params. + indexes: false // Three available options: (1) indexes: null (leads to no brackets), (2) (default) indexes: false (leads to empty brackets), (3) indexes: true (leads to brackets with indexes). + }, + + // `data` is the data to be sent as the request body + // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH' + // When no `transformRequest` is set, must be of one of the following types: + // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams + // - Browser only: FormData, File, Blob + // - Node only: Stream, Buffer, FormData (form-data package) + data: { + firstName: 'Fred' + }, + + // syntax alternative to send data into the body + // method post + // only the value is sent, not the key + data: 'Country=Brasil&City=Belo Horizonte', + + // `timeout` specifies the number of milliseconds before the request times out. + // If the request takes longer than `timeout`, the request will be aborted. + timeout: 1000, // default is `0` (no timeout) + + // `withCredentials` indicates whether or not cross-site Access-Control requests + // should be made using credentials + withCredentials: false, // default + + // `adapter` allows custom handling of requests which makes testing easier. + // Return a promise and supply a valid response (see lib/adapters/README.md) + adapter: function (config) { + /* ... */ + }, + // Also, you can set the name of the built-in adapter, or provide an array with their names + // to choose the first available in the environment + adapter: 'xhr' // 'fetch' | 'http' | ['xhr', 'http', 'fetch'] + + // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. + // This will set an `Authorization` header, overwriting any existing + // `Authorization` custom headers you have set using `headers`. + // Please note that only HTTP Basic auth is configurable through this parameter. + // For Bearer tokens and such, use `Authorization` custom headers instead. + auth: { + username: 'janedoe', + password: 's00pers3cret' + }, + + // `responseType` indicates the type of data that the server will respond with + // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' + // browser only: 'blob' + responseType: 'json', // default + + // `responseEncoding` indicates encoding to use for decoding responses (Node.js only) + // Note: Ignored for `responseType` of 'stream' or client-side requests + // options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url', + // 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8', + // 'utf8', 'UTF8', 'utf16le', 'UTF16LE' + responseEncoding: 'utf8', // default + + // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token + xsrfCookieName: 'XSRF-TOKEN', // default + + // `xsrfHeaderName` is the name of the http header that carries the xsrf token value + xsrfHeaderName: 'X-XSRF-TOKEN', // default + + // `undefined` (default) - set XSRF header only for the same origin requests + withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined), + + // `onUploadProgress` allows handling of progress events for uploads + // browser & node.js + onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) { + // Do whatever you want with the Axios progress event + }, + + // `onDownloadProgress` allows handling of progress events for downloads + // browser & node.js + onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) { + // Do whatever you want with the Axios progress event + }, + + // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js + maxContentLength: 2000, + + // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed + maxBodyLength: 2000, + + // `validateStatus` defines whether to resolve or reject the promise for a given + // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` + // or `undefined`), the promise will be resolved; otherwise, the promise will be + // rejected. + validateStatus: function (status) { + return status >= 200 && status < 300; // default + }, + + // `maxRedirects` defines the maximum number of redirects to follow in node.js. + // If set to 0, no redirects will be followed. + maxRedirects: 21, // default + + // `beforeRedirect` defines a function that will be called before redirect. + // Use this to adjust the request options upon redirecting, + // to inspect the latest response headers, + // or to cancel the request by throwing an error + // If maxRedirects is set to 0, `beforeRedirect` is not used. + beforeRedirect: (options, { headers }) => { + if (options.hostname === "example.com") { + options.auth = "user:password"; + } + }, + + // `socketPath` defines a UNIX Socket to be used in node.js. + // e.g. '/var/run/docker.sock' to send requests to the docker daemon. + // Only either `socketPath` or `proxy` can be specified. + // If both are specified, `socketPath` is used. + socketPath: null, // default + + // `transport` determines the transport method that will be used to make the request. If defined, it will be used. Otherwise, if `maxRedirects` is 0, the default `http` or `https` library will be used, depending on the protocol specified in `protocol`. Otherwise, the `httpFollow` or `httpsFollow` library will be used, again depending on the protocol, which can handle redirects. + transport: undefined, // default + + // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http + // and https requests, respectively, in node.js. This allows options to be added like + // `keepAlive` that are not enabled by default. + httpAgent: new http.Agent({ keepAlive: true }), + httpsAgent: new https.Agent({ keepAlive: true }), + + // `proxy` defines the hostname, port, and protocol of the proxy server. + // You can also define your proxy using the conventional `http_proxy` and + // `https_proxy` environment variables. If you are using environment variables + // for your proxy configuration, you can also define a `no_proxy` environment + // variable as a comma-separated list of domains that should not be proxied. + // Use `false` to disable proxies, ignoring environment variables. + // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and + // supplies credentials. + // This will set an `Proxy-Authorization` header, overwriting any existing + // `Proxy-Authorization` custom headers you have set using `headers`. + // If the proxy server uses HTTPS, then you must set the protocol to `https`. + proxy: { + protocol: 'https', + host: '127.0.0.1', + // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined + port: 9000, + auth: { + username: 'mikeymike', + password: 'rapunz3l' + } + }, + + // `cancelToken` specifies a cancel token that can be used to cancel the request + // (see Cancellation section below for details) + cancelToken: new CancelToken(function (cancel) { + }), + + // an alternative way to cancel Axios requests using AbortController + signal: new AbortController().signal, + + // `decompress` indicates whether or not the response body should be decompressed + // automatically. If set to `true` will also remove the 'content-encoding' header + // from the responses objects of all decompressed responses + // - Node only (XHR cannot turn off decompression) + decompress: true, // default + + // `insecureHTTPParser` boolean. + // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers. + // This may allow interoperability with non-conformant HTTP implementations. + // Using the insecure parser should be avoided. + // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback + // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none + insecureHTTPParser: undefined, // default + + // transitional options for backward compatibility that may be removed in the newer versions + transitional: { + // silent JSON parsing mode + // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour) + // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json') + silentJSONParsing: true, // default value for the current Axios version + + // try to parse the response string as JSON even if `responseType` is not 'json' + forcedJSONParsing: true, + + // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts + clarifyTimeoutError: false, + }, + + env: { + // The FormData class to be used to automatically serialize the payload into a FormData object + FormData: window?.FormData || global?.FormData + }, + + formSerializer: { + visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values + dots: boolean; // use dots instead of brackets format + metaTokens: boolean; // keep special endings like {} in parameter key + indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes + }, + + // http adapter only (node.js) + maxRate: [ + 100 * 1024, // 100KB/s upload limit, + 100 * 1024 // 100KB/s download limit + ] +} +``` + +## Response Schema + +The response for a request contains the following information. + +```js +{ + // `data` is the response that was provided by the server + data: {}, + + // `status` is the HTTP status code from the server response + status: 200, + + // `statusText` is the HTTP status message from the server response + statusText: 'OK', + + // `headers` the HTTP headers that the server responded with + // All header names are lowercase and can be accessed using the bracket notation. + // Example: `response.headers['content-type']` + headers: {}, + + // `config` is the config that was provided to `axios` for the request + config: {}, + + // `request` is the request that generated this response + // It is the last ClientRequest instance in node.js (in redirects) + // and an XMLHttpRequest instance in the browser + request: {} +} +``` + +When using `then`, you will receive the response as follows: + +```js +axios.get('/user/12345') + .then(function (response) { + console.log(response.data); + console.log(response.status); + console.log(response.statusText); + console.log(response.headers); + console.log(response.config); + }); +``` + +When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section. + +## Config Defaults + +You can specify config defaults that will be applied to every request. + +### Global axios defaults + +```js +axios.defaults.baseURL = 'https://api.example.com'; + +// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them. +// See below for an example using Custom instance defaults instead. +axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; + +axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; +``` + +### Custom instance defaults + +```js +// Set config defaults when creating the instance +const instance = axios.create({ + baseURL: 'https://api.example.com' +}); + +// Alter defaults after instance has been created +instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; +``` + +### Config order of precedence + +Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults/index.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. + +```js +// Create an instance using the config defaults provided by the library +// At this point the timeout config value is `0` as is the default for the library +const instance = axios.create(); + +// Override timeout default for the library +// Now all requests using this instance will wait 2.5 seconds before timing out +instance.defaults.timeout = 2500; + +// Override timeout for this request as it's known to take a long time +instance.get('/longRequest', { + timeout: 5000 +}); +``` + +## Interceptors + +You can intercept requests or responses before they are handled by `then` or `catch`. + +```js +// Add a request interceptor +axios.interceptors.request.use(function (config) { + // Do something before request is sent + return config; + }, function (error) { + // Do something with request error + return Promise.reject(error); + }); + +// Add a response interceptor +axios.interceptors.response.use(function (response) { + // Any status code that lie within the range of 2xx cause this function to trigger + // Do something with response data + return response; + }, function (error) { + // Any status codes that falls outside the range of 2xx cause this function to trigger + // Do something with response error + return Promise.reject(error); + }); +``` + +If you need to remove an interceptor later you can. + +```js +const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); +axios.interceptors.request.eject(myInterceptor); +``` + +You can also clear all interceptors for requests or responses. +```js +const instance = axios.create(); +instance.interceptors.request.use(function () {/*...*/}); +instance.interceptors.request.clear(); // Removes interceptors from requests +instance.interceptors.response.use(function () {/*...*/}); +instance.interceptors.response.clear(); // Removes interceptors from responses +``` + +You can add interceptors to a custom instance of axios. + +```js +const instance = axios.create(); +instance.interceptors.request.use(function () {/*...*/}); +``` + +When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay +in the execution of your axios request when the main thread is blocked (a promise is created under the hood for +the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag +to the options object that will tell axios to run the code synchronously and avoid any delays in request execution. + +```js +axios.interceptors.request.use(function (config) { + config.headers.test = 'I am only a header!'; + return config; +}, null, { synchronous: true }); +``` + +If you want to execute a particular interceptor based on a runtime check, +you can add a `runWhen` function to the options object. The request interceptor will not be executed **if and only if** the return +of `runWhen` is `false`. The function will be called with the config +object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an +asynchronous request interceptor that only needs to run at certain times. + +```js +function onGetCall(config) { + return config.method === 'get'; +} +axios.interceptors.request.use(function (config) { + config.headers.test = 'special get headers'; + return config; +}, null, { runWhen: onGetCall }); +``` + +> **Note:** options parameter(having `synchronous` and `runWhen` properties) is only supported for request interceptors at the moment. + +### Multiple Interceptors + +Given you add multiple response interceptors +and when the response was fulfilled +- then each interceptor is executed +- then they are executed in the order they were added +- then only the last interceptor's result is returned +- then every interceptor receives the result of its predecessor +- and when the fulfillment-interceptor throws + - then the following fulfillment-interceptor is not called + - then the following rejection-interceptor is called + - once caught, another following fulfill-interceptor is called again (just like in a promise chain). + +Read [the interceptor tests](./test/specs/interceptors.spec.js) for seeing all this in code. + +## Error Types + +There are many different axios error messages that can appear that can provide basic information about the specifics of the error and where opportunities may lie in debugging. + +The general structure of axios errors is as follows: +| Property | Definition | +| -------- | ---------- | +| message | A quick summary of the error message and the status it failed with. | +| name | This defines where the error originated from. For axios, it will always be an 'AxiosError'. | +| stack | Provides the stack trace of the error. | +| config | An axios config object with specific instance configurations defined by the user from when the request was made | +| code | Represents an axios identified error. The table below lists out specific definitions for internal axios error. | +| status | HTTP response status code. See [here](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) for common HTTP response status code meanings. + +Below is a list of potential axios identified error +| Code | Definition | +| -------- | ---------- | +| ERR_BAD_OPTION_VALUE | Invalid or unsupported value provided in axios configuration. | +| ERR_BAD_OPTION | Invalid option provided in axios configuration. | +| ECONNABORTED | Request timed out due to exceeding timeout specified in axios configuration. | +| ETIMEDOUT | Request timed out due to exceeding default axios timelimit. | +| ERR_NETWORK | Network-related issue. +| ERR_FR_TOO_MANY_REDIRECTS | Request is redirected too many times; exceeds max redirects specified in axios configuration. +| ERR_DEPRECATED | Deprecated feature or method used in axios. +| ERR_BAD_RESPONSE | Response cannot be parsed properly or is in an unexpected format. +| ERR_BAD_REQUEST | Requested has unexpected format or missing required parameters. | +| ERR_CANCELED | Feature or method is canceled explicitly by the user. +| ERR_NOT_SUPPORT | Feature or method not supported in the current axios environment. +| ERR_INVALID_URL | Invalid URL provided for axios request. + +## Handling Errors + +the default behavior is to reject every response that returns with a status code that falls out of the range of 2xx and treat it as an error. + +```js +axios.get('/user/12345') + .catch(function (error) { + if (error.response) { + // The request was made and the server responded with a status code + // that falls out of the range of 2xx + console.log(error.response.data); + console.log(error.response.status); + console.log(error.response.headers); + } else if (error.request) { + // The request was made but no response was received + // `error.request` is an instance of XMLHttpRequest in the browser and an instance of + // http.ClientRequest in node.js + console.log(error.request); + } else { + // Something happened in setting up the request that triggered an Error + console.log('Error', error.message); + } + console.log(error.config); + }); +``` + +Using the `validateStatus` config option, you can override the default condition (status >= 200 && status < 300) and define HTTP code(s) that should throw an error. + +```js +axios.get('/user/12345', { + validateStatus: function (status) { + return status < 500; // Resolve only if the status code is less than 500 + } +}) +``` + +Using `toJSON` you get an object with more information about the HTTP error. + +```js +axios.get('/user/12345') + .catch(function (error) { + console.log(error.toJSON()); + }); +``` + +## Cancellation + +### AbortController + +Starting from `v0.22.0` Axios supports AbortController to cancel requests in fetch API way: + +```js +const controller = new AbortController(); + +axios.get('/foo/bar', { + signal: controller.signal +}).then(function(response) { + //... +}); +// cancel the request +controller.abort() +``` + +### CancelToken `👎deprecated` + +You can also cancel a request using a *CancelToken*. + +> The axios cancel token API is based on the withdrawn [cancellable promises proposal](https://github.com/tc39/proposal-cancelable-promises). + +> This API is deprecated since v0.22.0 and shouldn't be used in new projects + +You can create a cancel token using the `CancelToken.source` factory as shown below: + +```js +const CancelToken = axios.CancelToken; +const source = CancelToken.source(); + +axios.get('/user/12345', { + cancelToken: source.token +}).catch(function (thrown) { + if (axios.isCancel(thrown)) { + console.log('Request canceled', thrown.message); + } else { + // handle error + } +}); + +axios.post('/user/12345', { + name: 'new name' +}, { + cancelToken: source.token +}) + +// cancel the request (the message parameter is optional) +source.cancel('Operation canceled by the user.'); +``` + +You can also create a cancel token by passing an executor function to the `CancelToken` constructor: + +```js +const CancelToken = axios.CancelToken; +let cancel; + +axios.get('/user/12345', { + cancelToken: new CancelToken(function executor(c) { + // An executor function receives a cancel function as a parameter + cancel = c; + }) +}); + +// cancel the request +cancel(); +``` + +> **Note:** you can cancel several requests with the same cancel token/abort controller. +> If a cancellation token is already cancelled at the moment of starting an Axios request, then the request is cancelled immediately, without any attempts to make a real request. + +> During the transition period, you can use both cancellation APIs, even for the same request: + +## Using `application/x-www-form-urlencoded` format + +### URLSearchParams + +By default, axios serializes JavaScript objects to `JSON`. To send data in the [`application/x-www-form-urlencoded` format](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) instead, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API, which is [supported](http://www.caniuse.com/#feat=urlsearchparams) in the vast majority of browsers,and [ Node](https://nodejs.org/api/url.html#url_class_urlsearchparams) starting with v10 (released in 2018). + +```js +const params = new URLSearchParams({ foo: 'bar' }); +params.append('extraparam', 'value'); +axios.post('/foo', params); +``` + +### Query string (Older browsers) + +For compatibility with very old browsers, there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment). + +Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library: + +```js +const qs = require('qs'); +axios.post('/foo', qs.stringify({ 'bar': 123 })); +``` + +Or in another way (ES6), + +```js +import qs from 'qs'; +const data = { 'bar': 123 }; +const options = { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + data: qs.stringify(data), + url, +}; +axios(options); +``` + +### Older Node.js versions + +For older Node.js engines, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows: + +```js +const querystring = require('querystring'); +axios.post('https://something.com/', querystring.stringify({ foo: 'bar' })); +``` + +You can also use the [`qs`](https://github.com/ljharb/qs) library. + +> **Note**: The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has [known issues](https://github.com/nodejs/node-v0.x-archive/issues/1665) with that use case. + +### 🆕 Automatic serialization to URLSearchParams + +Axios will automatically serialize the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded". + +```js +const data = { + x: 1, + arr: [1, 2, 3], + arr2: [1, [2], 3], + users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}], +}; + +await axios.postForm('https://postman-echo.com/post', data, + {headers: {'content-type': 'application/x-www-form-urlencoded'}} +); +``` + +The server will handle it as: + +```js + { + x: '1', + 'arr[]': [ '1', '2', '3' ], + 'arr2[0]': '1', + 'arr2[1][0]': '2', + 'arr2[2]': '3', + 'arr3[]': [ '1', '2', '3' ], + 'users[0][name]': 'Peter', + 'users[0][surname]': 'griffin', + 'users[1][name]': 'Thomas', + 'users[1][surname]': 'Anderson' + } +```` + +If your backend body-parser (like `body-parser` of `express.js`) supports nested objects decoding, you will get the same object on the server-side automatically + +```js + var app = express(); + + app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies + + app.post('/', function (req, res, next) { + // echo body as JSON + res.send(JSON.stringify(req.body)); + }); + + server = app.listen(3000); +``` + +## Using `multipart/form-data` format + +### FormData + +To send the data as a `multipart/formdata` you need to pass a formData instance as a payload. +Setting the `Content-Type` header is not required as Axios guesses it based on the payload type. + +```js +const formData = new FormData(); +formData.append('foo', 'bar'); + +axios.post('https://httpbin.org/post', formData); +``` + +In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows: + +```js +const FormData = require('form-data'); + +const form = new FormData(); +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); + +axios.post('https://example.com', form) +``` + +### 🆕 Automatic serialization to FormData + +Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type` +header is set to `multipart/form-data`. + +The following request will submit the data in a FormData format (Browser & Node.js): + +```js +import axios from 'axios'; + +axios.post('https://httpbin.org/post', {x: 1}, { + headers: { + 'Content-Type': 'multipart/form-data' + } +}).then(({data}) => console.log(data)); +``` + +In the `node.js` build, the ([`form-data`](https://github.com/form-data/form-data)) polyfill is used by default. + +You can overload the FormData class by setting the `env.FormData` config variable, +but you probably won't need it in most cases: + +```js +const axios = require('axios'); +var FormData = require('form-data'); + +axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, { + headers: { + 'Content-Type': 'multipart/form-data' + } +}).then(({data}) => console.log(data)); +``` + +Axios FormData serializer supports some special endings to perform the following operations: + +- `{}` - serialize the value with JSON.stringify +- `[]` - unwrap the array-like object as separate fields with the same key + +> **Note**: unwrap/expand operation will be used by default on arrays and FileList objects + +FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases: + +- `visitor: Function` - user-defined visitor function that will be called recursively to serialize the data object +to a `FormData` object by following custom rules. + +- `dots: boolean = false` - use dot notation instead of brackets to serialize arrays and objects; + +- `metaTokens: boolean = true` - add the special ending (e.g `user{}: '{"name": "John"}'`) in the FormData key. +The back-end body-parser could potentially use this meta-information to automatically parse the value as JSON. + +- `indexes: null|false|true = false` - controls how indexes will be added to unwrapped keys of `flat` array-like objects + + - `null` - don't add brackets (`arr: 1`, `arr: 2`, `arr: 3`) + - `false`(default) - add empty brackets (`arr[]: 1`, `arr[]: 2`, `arr[]: 3`) + - `true` - add brackets with indexes (`arr[0]: 1`, `arr[1]: 2`, `arr[2]: 3`) + +Let's say we have an object like this one: + +```js +const obj = { + x: 1, + arr: [1, 2, 3], + arr2: [1, [2], 3], + users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}], + 'obj2{}': [{x:1}] +}; +``` + +The following steps will be executed by the Axios serializer internally: + +```js +const formData = new FormData(); +formData.append('x', '1'); +formData.append('arr[]', '1'); +formData.append('arr[]', '2'); +formData.append('arr[]', '3'); +formData.append('arr2[0]', '1'); +formData.append('arr2[1][0]', '2'); +formData.append('arr2[2]', '3'); +formData.append('users[0][name]', 'Peter'); +formData.append('users[0][surname]', 'Griffin'); +formData.append('users[1][name]', 'Thomas'); +formData.append('users[1][surname]', 'Anderson'); +formData.append('obj2{}', '[{"x":1}]'); +``` + +Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm` +which are just the corresponding http methods with the `Content-Type` header preset to `multipart/form-data`. + +## Files Posting + +You can easily submit a single file: + +```js +await axios.postForm('https://httpbin.org/post', { + 'myVar' : 'foo', + 'file': document.querySelector('#fileInput').files[0] +}); +``` + +or multiple files as `multipart/form-data`: + +```js +await axios.postForm('https://httpbin.org/post', { + 'files[]': document.querySelector('#fileInput').files +}); +``` + +`FileList` object can be passed directly: + +```js +await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files) +``` + +All files will be sent with the same field names: `files[]`. + +## 🆕 HTML Form Posting (browser) + +Pass HTML Form element as a payload to submit it as `multipart/form-data` content. + +```js +await axios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm')); +``` + +`FormData` and `HTMLForm` objects can also be posted as `JSON` by explicitly setting the `Content-Type` header to `application/json`: + +```js +await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), { + headers: { + 'Content-Type': 'application/json' + } +}) +``` + +For example, the Form + +```html +
+ + + + + + + + + +
+``` + +will be submitted as the following JSON object: + +```js +{ + "foo": "1", + "deep": { + "prop": { + "spaced": "3" + } + }, + "baz": [ + "4", + "5" + ], + "user": { + "age": "value2" + } +} +```` + +Sending `Blobs`/`Files` as JSON (`base64`) is not currently supported. + +## 🆕 Progress capturing + +Axios supports both browser and node environments to capture request upload/download progress. +The frequency of progress events is forced to be limited to `3` times per second. + +```js +await axios.post(url, data, { + onUploadProgress: function (axiosProgressEvent) { + /*{ + loaded: number; + total?: number; + progress?: number; // in range [0..1] + bytes: number; // how many bytes have been transferred since the last trigger (delta) + estimated?: number; // estimated time in seconds + rate?: number; // upload speed in bytes + upload: true; // upload sign + }*/ + }, + + onDownloadProgress: function (axiosProgressEvent) { + /*{ + loaded: number; + total?: number; + progress?: number; + bytes: number; + estimated?: number; + rate?: number; // download speed in bytes + download: true; // download sign + }*/ + } +}); +``` + +You can also track stream upload/download progress in node.js: + +```js +const {data} = await axios.post(SERVER_URL, readableStream, { + onUploadProgress: ({progress}) => { + console.log((progress * 100).toFixed(2)); + }, + + headers: { + 'Content-Length': contentLength + }, + + maxRedirects: 0 // avoid buffering the entire stream +}); +```` + +> **Note:** +> Capturing FormData upload progress is not currently supported in node.js environments. + +> **⚠️ Warning** +> It is recommended to disable redirects by setting maxRedirects: 0 to upload the stream in the **node.js** environment, +> as follow-redirects package will buffer the entire stream in RAM without following the "backpressure" algorithm. + + +## 🆕 Rate limiting + +Download and upload rate limits can only be set for the http adapter (node.js): + +```js +const {data} = await axios.post(LOCAL_SERVER_URL, myBuffer, { + onUploadProgress: ({progress, rate}) => { + console.log(`Upload [${(progress*100).toFixed(2)}%]: ${(rate / 1024).toFixed(2)}KB/s`) + }, + + maxRate: [100 * 1024], // 100KB/s limit +}); +``` + +## 🆕 AxiosHeaders + +Axios has its own `AxiosHeaders` class to manipulate headers using a Map-like API that guarantees caseless work. +Although HTTP is case-insensitive in headers, Axios will retain the case of the original header for stylistic reasons +and for a workaround when servers mistakenly consider the header's case. +The old approach of directly manipulating headers object is still available, but deprecated and not recommended for future usage. + +### Working with headers + +An AxiosHeaders object instance can contain different types of internal values. that control setting and merging logic. +The final headers object with string values is obtained by Axios by calling the `toJSON` method. + +> Note: By JSON here we mean an object consisting only of string values intended to be sent over the network. + +The header value can be one of the following types: +- `string` - normal string value that will be sent to the server +- `null` - skip header when rendering to JSON +- `false` - skip header when rendering to JSON, additionally indicates that `set` method must be called with `rewrite` option set to `true` + to overwrite this value (Axios uses this internally to allow users to opt out of installing certain headers like `User-Agent` or `Content-Type`) +- `undefined` - value is not set + +> Note: The header value is considered set if it is not equal to undefined. + +The headers object is always initialized inside interceptors and transformers: + +```ts + axios.interceptors.request.use((request: InternalAxiosRequestConfig) => { + request.headers.set('My-header', 'value'); + + request.headers.set({ + "My-set-header1": "my-set-value1", + "My-set-header2": "my-set-value2" + }); + + request.headers.set('User-Agent', false); // disable subsequent setting the header by Axios + + request.headers.setContentType('text/plain'); + + request.headers['My-set-header2'] = 'newValue' // direct access is deprecated + + return request; + } + ); +```` + +You can iterate over an `AxiosHeaders` instance using a `for...of` statement: + +````js +const headers = new AxiosHeaders({ + foo: '1', + bar: '2', + baz: '3' +}); + +for(const [header, value] of headers) { + console.log(header, value); +} + +// foo 1 +// bar 2 +// baz 3 +```` + +### new AxiosHeaders(headers?) + +Constructs a new `AxiosHeaders` instance. + +``` +constructor(headers?: RawAxiosHeaders | AxiosHeaders | string); +``` + +If the headers object is a string, it will be parsed as RAW HTTP headers. + +````js +const headers = new AxiosHeaders(` +Host: www.bing.com +User-Agent: curl/7.54.0 +Accept: */*`); + +console.log(headers); + +// Object [AxiosHeaders] { +// host: 'www.bing.com', +// 'user-agent': 'curl/7.54.0', +// accept: '*/*' +// } +```` + +### AxiosHeaders#set + +```ts +set(headerName, value: Axios, rewrite?: boolean); +set(headerName, value, rewrite?: (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean); +set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean); +``` + +The `rewrite` argument controls the overwriting behavior: +- `false` - do not overwrite if header's value is set (is not `undefined`) +- `undefined` (default) - overwrite the header unless its value is set to `false` +- `true` - rewrite anyway + +The option can also accept a user-defined function that determines whether the value should be overwritten or not. + +Returns `this`. + +### AxiosHeaders#get(header) + +``` + get(headerName: string, matcher?: true | AxiosHeaderMatcher): AxiosHeaderValue; + get(headerName: string, parser: RegExp): RegExpExecArray | null; +```` + +Returns the internal value of the header. It can take an extra argument to parse the header's value with `RegExp.exec`, +matcher function or internal key-value parser. + +```ts +const headers = new AxiosHeaders({ + 'Content-Type': 'multipart/form-data; boundary=Asrf456BGe4h' +}); + +console.log(headers.get('Content-Type')); +// multipart/form-data; boundary=Asrf456BGe4h + +console.log(headers.get('Content-Type', true)); // parse key-value pairs from a string separated with \s,;= delimiters: +// [Object: null prototype] { +// 'multipart/form-data': undefined, +// boundary: 'Asrf456BGe4h' +// } + + +console.log(headers.get('Content-Type', (value, name, headers) => { + return String(value).replace(/a/g, 'ZZZ'); +})); +// multipZZZrt/form-dZZZtZZZ; boundZZZry=Asrf456BGe4h + +console.log(headers.get('Content-Type', /boundary=(\w+)/)?.[0]); +// boundary=Asrf456BGe4h + +``` + +Returns the value of the header. + +### AxiosHeaders#has(header, matcher?) + +``` +has(header: string, matcher?: AxiosHeaderMatcher): boolean; +``` + +Returns `true` if the header is set (has no `undefined` value). + +### AxiosHeaders#delete(header, matcher?) + +``` +delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean; +``` + +Returns `true` if at least one header has been removed. + +### AxiosHeaders#clear(matcher?) + +``` +clear(matcher?: AxiosHeaderMatcher): boolean; +``` + +Removes all headers. +Unlike the `delete` method matcher, this optional matcher will be used to match against the header name rather than the value. + +```ts +const headers = new AxiosHeaders({ + 'foo': '1', + 'x-foo': '2', + 'x-bar': '3', +}); + +console.log(headers.clear(/^x-/)); // true + +console.log(headers.toJSON()); // [Object: null prototype] { foo: '1' } +``` + +Returns `true` if at least one header has been cleared. + +### AxiosHeaders#normalize(format); + +If the headers object was changed directly, it can have duplicates with the same name but in different cases. +This method normalizes the headers object by combining duplicate keys into one. +Axios uses this method internally after calling each interceptor. +Set `format` to true for converting headers name to lowercase and capitalize the initial letters (`cOntEnt-type` => `Content-Type`) + +```js +const headers = new AxiosHeaders({ + 'foo': '1', +}); + +headers.Foo = '2'; +headers.FOO = '3'; + +console.log(headers.toJSON()); // [Object: null prototype] { foo: '1', Foo: '2', FOO: '3' } +console.log(headers.normalize().toJSON()); // [Object: null prototype] { foo: '3' } +console.log(headers.normalize(true).toJSON()); // [Object: null prototype] { Foo: '3' } +``` + +Returns `this`. + +### AxiosHeaders#concat(...targets) + +``` +concat(...targets: Array): AxiosHeaders; +``` + +Merges the instance with targets into a new `AxiosHeaders` instance. If the target is a string, it will be parsed as RAW HTTP headers. + +Returns a new `AxiosHeaders` instance. + +### AxiosHeaders#toJSON(asStrings?) + +```` +toJSON(asStrings?: boolean): RawAxiosHeaders; +```` + +Resolve all internal headers values into a new null prototype object. +Set `asStrings` to true to resolve arrays as a string containing all elements, separated by commas. + +### AxiosHeaders.from(thing?) + +```` +from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders; +```` + +Returns a new `AxiosHeaders` instance created from the raw headers passed in, +or simply returns the given headers object if it's an `AxiosHeaders` instance. + +### AxiosHeaders.concat(...targets) + +```` +concat(...targets: Array): AxiosHeaders; +```` + +Returns a new `AxiosHeaders` instance created by merging the target objects. + +### Shortcuts + +The following shortcuts are available: + +- `setContentType`, `getContentType`, `hasContentType` + +- `setContentLength`, `getContentLength`, `hasContentLength` + +- `setAccept`, `getAccept`, `hasAccept` + +- `setUserAgent`, `getUserAgent`, `hasUserAgent` + +- `setContentEncoding`, `getContentEncoding`, `hasContentEncoding` + +## 🔥 Fetch adapter + +Fetch adapter was introduced in `v1.7.0`. By default, it will be used if `xhr` and `http` adapters are not available in the build, +or not supported by the environment. +To use it by default, it must be selected explicitly: + +```js +const {data} = axios.get(url, { + adapter: 'fetch' // by default ['xhr', 'http', 'fetch'] +}) +``` + +You can create a separate instance for this: + +```js +const fetchAxios = axios.create({ + adapter: 'fetch' +}); + +const {data} = fetchAxios.get(url); +``` + +The adapter supports the same functionality as `xhr` adapter, **including upload and download progress capturing**. +Also, it supports additional response types such as `stream` and `formdata` (if supported by the environment). + +## Semver + +Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. + +## Promises + +axios depends on a native ES6 Promise implementation to be [supported](https://caniuse.com/promises). +If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). + +## TypeScript + +axios includes [TypeScript](https://typescriptlang.org) definitions and a type guard for axios errors. + +```typescript +let user: User = null; +try { + const { data } = await axios.get('/user?ID=12345'); + user = data.userDetails; +} catch (error) { + if (axios.isAxiosError(error)) { + handleAxiosError(error); + } else { + handleUnexpectedError(error); + } +} +``` + +Because axios dual publishes with an ESM default export and a CJS `module.exports`, there are some caveats. +The recommended setting is to use `"moduleResolution": "node16"` (this is implied by `"module": "node16"`). Note that this requires TypeScript 4.7 or greater. +If use ESM, your settings should be fine. +If you compile TypeScript to CJS and you can’t use `"moduleResolution": "node 16"`, you have to enable `esModuleInterop`. +If you use TypeScript to type check CJS JavaScript code, your only option is to use `"moduleResolution": "node16"`. + +## Online one-click setup + +You can use Gitpod, an online IDE(which is free for Open Source) for contributing or running the examples online. + +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/axios/axios/blob/main/examples/server.js) + + +## Resources + +* [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md) +* [Ecosystem](https://github.com/axios/axios/blob/v1.x/ECOSYSTEM.md) +* [Contributing Guide](https://github.com/axios/axios/blob/v1.x/CONTRIBUTING.md) +* [Code of Conduct](https://github.com/axios/axios/blob/v1.x/CODE_OF_CONDUCT.md) + +## Credits + +axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [AngularJS](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of AngularJS. + +## License + +[MIT](LICENSE) diff --git a/node_modules/axios/SECURITY.md b/node_modules/axios/SECURITY.md new file mode 100644 index 000000000..a5a2b7d2e --- /dev/null +++ b/node_modules/axios/SECURITY.md @@ -0,0 +1,6 @@ +# Reporting a Vulnerability + +If you discover a security vulnerability in axios please disclose it via [our huntr page](https://huntr.dev/repos/axios/axios/). Bounty eligibility, CVE assignment, response times and past reports are all there. + + +Thank you for improving the security of axios. diff --git a/node_modules/axios/dist/axios.js b/node_modules/axios/dist/axios.js new file mode 100644 index 000000000..1fe9c6433 --- /dev/null +++ b/node_modules/axios/dist/axios.js @@ -0,0 +1,4288 @@ +// Axios v1.7.9 Copyright (c) 2024 Matt Zabriskie and contributors +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.axios = factory()); +})(this, (function () { 'use strict'; + + function _AsyncGenerator(e) { + var r, t; + function resume(r, t) { + try { + var n = e[r](t), + o = n.value, + u = o instanceof _OverloadYield; + Promise.resolve(u ? o.v : o).then(function (t) { + if (u) { + var i = "return" === r ? "return" : "next"; + if (!o.k || t.done) return resume(i, t); + t = e[i](t).value; + } + settle(n.done ? "return" : "normal", t); + }, function (e) { + resume("throw", e); + }); + } catch (e) { + settle("throw", e); + } + } + function settle(e, n) { + switch (e) { + case "return": + r.resolve({ + value: n, + done: !0 + }); + break; + case "throw": + r.reject(n); + break; + default: + r.resolve({ + value: n, + done: !1 + }); + } + (r = r.next) ? resume(r.key, r.arg) : t = null; + } + this._invoke = function (e, n) { + return new Promise(function (o, u) { + var i = { + key: e, + arg: n, + resolve: o, + reject: u, + next: null + }; + t ? t = t.next = i : (r = t = i, resume(e, n)); + }); + }, "function" != typeof e.return && (this.return = void 0); + } + _AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function () { + return this; + }, _AsyncGenerator.prototype.next = function (e) { + return this._invoke("next", e); + }, _AsyncGenerator.prototype.throw = function (e) { + return this._invoke("throw", e); + }, _AsyncGenerator.prototype.return = function (e) { + return this._invoke("return", e); + }; + function _OverloadYield(t, e) { + this.v = t, this.k = e; + } + function _asyncGeneratorDelegate(t) { + var e = {}, + n = !1; + function pump(e, r) { + return n = !0, r = new Promise(function (n) { + n(t[e](r)); + }), { + done: !1, + value: new _OverloadYield(r, 1) + }; + } + return e["undefined" != typeof Symbol && Symbol.iterator || "@@iterator"] = function () { + return this; + }, e.next = function (t) { + return n ? (n = !1, t) : pump("next", t); + }, "function" == typeof t.throw && (e.throw = function (t) { + if (n) throw n = !1, t; + return pump("throw", t); + }), "function" == typeof t.return && (e.return = function (t) { + return n ? (n = !1, t) : pump("return", t); + }), e; + } + function _asyncIterator(r) { + var n, + t, + o, + e = 2; + for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) { + if (t && null != (n = r[t])) return n.call(r); + if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r)); + t = "@@asyncIterator", o = "@@iterator"; + } + throw new TypeError("Object is not async iterable"); + } + function AsyncFromSyncIterator(r) { + function AsyncFromSyncIteratorContinuation(r) { + if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); + var n = r.done; + return Promise.resolve(r.value).then(function (r) { + return { + value: r, + done: n + }; + }); + } + return AsyncFromSyncIterator = function (r) { + this.s = r, this.n = r.next; + }, AsyncFromSyncIterator.prototype = { + s: null, + n: null, + next: function () { + return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); + }, + return: function (r) { + var n = this.s.return; + return void 0 === n ? Promise.resolve({ + value: r, + done: !0 + }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); + }, + throw: function (r) { + var n = this.s.return; + return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); + } + }, new AsyncFromSyncIterator(r); + } + function _awaitAsyncGenerator(e) { + return new _OverloadYield(e, 0); + } + function _iterableToArrayLimit(r, l) { + var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; + if (null != t) { + var e, + n, + i, + u, + a = [], + f = !0, + o = !1; + try { + if (i = (t = t.call(r)).next, 0 === l) { + if (Object(t) !== t) return; + f = !1; + } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); + } catch (r) { + o = !0, n = r; + } finally { + try { + if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; + } finally { + if (o) throw n; + } + } + return a; + } + } + function ownKeys(e, r) { + var t = Object.keys(e); + if (Object.getOwnPropertySymbols) { + var o = Object.getOwnPropertySymbols(e); + r && (o = o.filter(function (r) { + return Object.getOwnPropertyDescriptor(e, r).enumerable; + })), t.push.apply(t, o); + } + return t; + } + function _objectSpread2(e) { + for (var r = 1; r < arguments.length; r++) { + var t = null != arguments[r] ? arguments[r] : {}; + r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { + _defineProperty(e, r, t[r]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { + Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); + }); + } + return e; + } + function _regeneratorRuntime() { + _regeneratorRuntime = function () { + return e; + }; + var t, + e = {}, + r = Object.prototype, + n = r.hasOwnProperty, + o = Object.defineProperty || function (t, e, r) { + t[e] = r.value; + }, + i = "function" == typeof Symbol ? Symbol : {}, + a = i.iterator || "@@iterator", + c = i.asyncIterator || "@@asyncIterator", + u = i.toStringTag || "@@toStringTag"; + function define(t, e, r) { + return Object.defineProperty(t, e, { + value: r, + enumerable: !0, + configurable: !0, + writable: !0 + }), t[e]; + } + try { + define({}, ""); + } catch (t) { + define = function (t, e, r) { + return t[e] = r; + }; + } + function wrap(t, e, r, n) { + var i = e && e.prototype instanceof Generator ? e : Generator, + a = Object.create(i.prototype), + c = new Context(n || []); + return o(a, "_invoke", { + value: makeInvokeMethod(t, r, c) + }), a; + } + function tryCatch(t, e, r) { + try { + return { + type: "normal", + arg: t.call(e, r) + }; + } catch (t) { + return { + type: "throw", + arg: t + }; + } + } + e.wrap = wrap; + var h = "suspendedStart", + l = "suspendedYield", + f = "executing", + s = "completed", + y = {}; + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + var p = {}; + define(p, a, function () { + return this; + }); + var d = Object.getPrototypeOf, + v = d && d(d(values([]))); + v && v !== r && n.call(v, a) && (p = v); + var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); + function defineIteratorMethods(t) { + ["next", "throw", "return"].forEach(function (e) { + define(t, e, function (t) { + return this._invoke(e, t); + }); + }); + } + function AsyncIterator(t, e) { + function invoke(r, o, i, a) { + var c = tryCatch(t[r], t, o); + if ("throw" !== c.type) { + var u = c.arg, + h = u.value; + return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { + invoke("next", t, i, a); + }, function (t) { + invoke("throw", t, i, a); + }) : e.resolve(h).then(function (t) { + u.value = t, i(u); + }, function (t) { + return invoke("throw", t, i, a); + }); + } + a(c.arg); + } + var r; + o(this, "_invoke", { + value: function (t, n) { + function callInvokeWithMethodAndArg() { + return new e(function (e, r) { + invoke(t, n, e, r); + }); + } + return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); + } + }); + } + function makeInvokeMethod(e, r, n) { + var o = h; + return function (i, a) { + if (o === f) throw new Error("Generator is already running"); + if (o === s) { + if ("throw" === i) throw a; + return { + value: t, + done: !0 + }; + } + for (n.method = i, n.arg = a;;) { + var c = n.delegate; + if (c) { + var u = maybeInvokeDelegate(c, n); + if (u) { + if (u === y) continue; + return u; + } + } + if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { + if (o === h) throw o = s, n.arg; + n.dispatchException(n.arg); + } else "return" === n.method && n.abrupt("return", n.arg); + o = f; + var p = tryCatch(e, r, n); + if ("normal" === p.type) { + if (o = n.done ? s : l, p.arg === y) continue; + return { + value: p.arg, + done: n.done + }; + } + "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); + } + }; + } + function maybeInvokeDelegate(e, r) { + var n = r.method, + o = e.iterator[n]; + if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; + var i = tryCatch(o, e.iterator, r.arg); + if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; + var a = i.arg; + return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); + } + function pushTryEntry(t) { + var e = { + tryLoc: t[0] + }; + 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); + } + function resetTryEntry(t) { + var e = t.completion || {}; + e.type = "normal", delete e.arg, t.completion = e; + } + function Context(t) { + this.tryEntries = [{ + tryLoc: "root" + }], t.forEach(pushTryEntry, this), this.reset(!0); + } + function values(e) { + if (e || "" === e) { + var r = e[a]; + if (r) return r.call(e); + if ("function" == typeof e.next) return e; + if (!isNaN(e.length)) { + var o = -1, + i = function next() { + for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; + return next.value = t, next.done = !0, next; + }; + return i.next = i; + } + } + throw new TypeError(typeof e + " is not iterable"); + } + return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { + value: GeneratorFunctionPrototype, + configurable: !0 + }), o(GeneratorFunctionPrototype, "constructor", { + value: GeneratorFunction, + configurable: !0 + }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { + var e = "function" == typeof t && t.constructor; + return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); + }, e.mark = function (t) { + return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; + }, e.awrap = function (t) { + return { + __await: t + }; + }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { + return this; + }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { + void 0 === i && (i = Promise); + var a = new AsyncIterator(wrap(t, r, n, o), i); + return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { + return t.done ? t.value : a.next(); + }); + }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { + return this; + }), define(g, "toString", function () { + return "[object Generator]"; + }), e.keys = function (t) { + var e = Object(t), + r = []; + for (var n in e) r.push(n); + return r.reverse(), function next() { + for (; r.length;) { + var t = r.pop(); + if (t in e) return next.value = t, next.done = !1, next; + } + return next.done = !0, next; + }; + }, e.values = values, Context.prototype = { + constructor: Context, + reset: function (e) { + if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); + }, + stop: function () { + this.done = !0; + var t = this.tryEntries[0].completion; + if ("throw" === t.type) throw t.arg; + return this.rval; + }, + dispatchException: function (e) { + if (this.done) throw e; + var r = this; + function handle(n, o) { + return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; + } + for (var o = this.tryEntries.length - 1; o >= 0; --o) { + var i = this.tryEntries[o], + a = i.completion; + if ("root" === i.tryLoc) return handle("end"); + if (i.tryLoc <= this.prev) { + var c = n.call(i, "catchLoc"), + u = n.call(i, "finallyLoc"); + if (c && u) { + if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); + if (this.prev < i.finallyLoc) return handle(i.finallyLoc); + } else if (c) { + if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); + } else { + if (!u) throw new Error("try statement without catch or finally"); + if (this.prev < i.finallyLoc) return handle(i.finallyLoc); + } + } + } + }, + abrupt: function (t, e) { + for (var r = this.tryEntries.length - 1; r >= 0; --r) { + var o = this.tryEntries[r]; + if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { + var i = o; + break; + } + } + i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); + var a = i ? i.completion : {}; + return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); + }, + complete: function (t, e) { + if ("throw" === t.type) throw t.arg; + return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; + }, + finish: function (t) { + for (var e = this.tryEntries.length - 1; e >= 0; --e) { + var r = this.tryEntries[e]; + if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; + } + }, + catch: function (t) { + for (var e = this.tryEntries.length - 1; e >= 0; --e) { + var r = this.tryEntries[e]; + if (r.tryLoc === t) { + var n = r.completion; + if ("throw" === n.type) { + var o = n.arg; + resetTryEntry(r); + } + return o; + } + } + throw new Error("illegal catch attempt"); + }, + delegateYield: function (e, r, n) { + return this.delegate = { + iterator: values(e), + resultName: r, + nextLoc: n + }, "next" === this.method && (this.arg = t), y; + } + }, e; + } + function _toPrimitive(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r || "default"); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return ("string" === r ? String : Number)(t); + } + function _toPropertyKey(t) { + var i = _toPrimitive(t, "string"); + return "symbol" == typeof i ? i : String(i); + } + function _typeof(o) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { + return typeof o; + } : function (o) { + return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; + }, _typeof(o); + } + function _wrapAsyncGenerator(fn) { + return function () { + return new _AsyncGenerator(fn.apply(this, arguments)); + }; + } + 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 _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 _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 _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); + } + function _toArray(arr) { + return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); + } + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); + } + function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); + } + function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + return arr2; + } + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + function _createForOfIteratorHelper(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + if (!it) { + if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + var F = function () {}; + return { + s: F, + n: function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }, + e: function (e) { + throw e; + }, + f: F + }; + } + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + var normalCompletion = true, + didErr = false, + err; + return { + s: function () { + it = it.call(o); + }, + n: function () { + var step = it.next(); + normalCompletion = step.done; + return step; + }, + e: function (e) { + didErr = true; + err = e; + }, + f: function () { + try { + if (!normalCompletion && it.return != null) it.return(); + } finally { + if (didErr) throw err; + } + } + }; + } + + function bind(fn, thisArg) { + return function wrap() { + return fn.apply(thisArg, arguments); + }; + } + + // utils is a library of generic helper functions non-specific to axios + + var toString = Object.prototype.toString; + var getPrototypeOf = Object.getPrototypeOf; + var kindOf = function (cache) { + return function (thing) { + var str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); + }; + }(Object.create(null)); + var kindOfTest = function kindOfTest(type) { + type = type.toLowerCase(); + return function (thing) { + return kindOf(thing) === type; + }; + }; + var typeOfTest = function typeOfTest(type) { + return function (thing) { + return _typeof(thing) === type; + }; + }; + + /** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * + * @returns {boolean} True if value is an Array, otherwise false + */ + var isArray = Array.isArray; + + /** + * Determine if a value is undefined + * + * @param {*} val The value to test + * + * @returns {boolean} True if the value is undefined, otherwise false + */ + var isUndefined = typeOfTest('undefined'); + + /** + * Determine if a value is a Buffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Buffer, otherwise false + */ + function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); + } + + /** + * Determine if a value is an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ + var isArrayBuffer = kindOfTest('ArrayBuffer'); + + /** + * Determine if a value is a view on an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ + function isArrayBufferView(val) { + var result; + if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { + result = ArrayBuffer.isView(val); + } else { + result = val && val.buffer && isArrayBuffer(val.buffer); + } + return result; + } + + /** + * Determine if a value is a String + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a String, otherwise false + */ + var isString = typeOfTest('string'); + + /** + * Determine if a value is a Function + * + * @param {*} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ + var isFunction = typeOfTest('function'); + + /** + * Determine if a value is a Number + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Number, otherwise false + */ + var isNumber = typeOfTest('number'); + + /** + * Determine if a value is an Object + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an Object, otherwise false + */ + var isObject = function isObject(thing) { + return thing !== null && _typeof(thing) === 'object'; + }; + + /** + * Determine if a value is a Boolean + * + * @param {*} thing The value to test + * @returns {boolean} True if value is a Boolean, otherwise false + */ + var isBoolean = function isBoolean(thing) { + return thing === true || thing === false; + }; + + /** + * Determine if a value is a plain Object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a plain Object, otherwise false + */ + var isPlainObject = function isPlainObject(val) { + if (kindOf(val) !== 'object') { + return false; + } + var prototype = getPrototypeOf(val); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); + }; + + /** + * Determine if a value is a Date + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Date, otherwise false + */ + var isDate = kindOfTest('Date'); + + /** + * Determine if a value is a File + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ + var isFile = kindOfTest('File'); + + /** + * Determine if a value is a Blob + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Blob, otherwise false + */ + var isBlob = kindOfTest('Blob'); + + /** + * Determine if a value is a FileList + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ + var isFileList = kindOfTest('FileList'); + + /** + * Determine if a value is a Stream + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Stream, otherwise false + */ + var isStream = function isStream(val) { + return isObject(val) && isFunction(val.pipe); + }; + + /** + * Determine if a value is a FormData + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an FormData, otherwise false + */ + var isFormData = function isFormData(thing) { + var kind; + return thing && (typeof FormData === 'function' && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === 'formdata' || + // detect form-data instance + kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')); + }; + + /** + * Determine if a value is a URLSearchParams object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ + var isURLSearchParams = kindOfTest('URLSearchParams'); + var _map = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest), + _map2 = _slicedToArray(_map, 4), + isReadableStream = _map2[0], + isRequest = _map2[1], + isResponse = _map2[2], + isHeaders = _map2[3]; + + /** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * + * @returns {String} The String freed of excess whitespace + */ + var trim = function trim(str) { + return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + }; + + /** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + * + * @param {Boolean} [allOwnKeys = false] + * @returns {any} + */ + function forEach(obj, fn) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + _ref$allOwnKeys = _ref.allOwnKeys, + allOwnKeys = _ref$allOwnKeys === void 0 ? false : _ref$allOwnKeys; + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + var i; + var l; + + // Force an array if not already something iterable + if (_typeof(obj) !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + if (isArray(obj)) { + // Iterate over array values + for (i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + var keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + var len = keys.length; + var key; + for (i = 0; i < len; i++) { + key = keys[i]; + fn.call(null, obj[key], key, obj); + } + } + } + function findKey(obj, key) { + key = key.toLowerCase(); + var keys = Object.keys(obj); + var i = keys.length; + var _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; + } + var _global = function () { + /*eslint no-undef:0*/ + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : typeof window !== 'undefined' ? window : global; + }(); + var isContextDefined = function isContextDefined(context) { + return !isUndefined(context) && context !== _global; + }; + + /** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * + * @returns {Object} Result of all merge properties + */ + function merge( /* obj1, obj2, obj3, ... */ + ) { + var _ref2 = isContextDefined(this) && this || {}, + caseless = _ref2.caseless; + var result = {}; + var assignValue = function assignValue(val, key) { + var targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + }; + for (var i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); + } + return result; + } + + /** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * + * @param {Boolean} [allOwnKeys] + * @returns {Object} The resulting value of object a + */ + var extend = function extend(a, b, thisArg) { + var _ref3 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}, + allOwnKeys = _ref3.allOwnKeys; + forEach(b, function (val, key) { + if (thisArg && isFunction(val)) { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }, { + allOwnKeys: allOwnKeys + }); + return a; + }; + + /** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * + * @returns {string} content value without BOM + */ + var stripBOM = function stripBOM(content) { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; + }; + + /** + * Inherit the prototype methods from one constructor into another + * @param {function} constructor + * @param {function} superConstructor + * @param {object} [props] + * @param {object} [descriptors] + * + * @returns {void} + */ + var inherits = function inherits(constructor, superConstructor, props, descriptors) { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, 'super', { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); + }; + + /** + * Resolve object with deep prototype chain to a flat object + * @param {Object} sourceObj source object + * @param {Object} [destObj] + * @param {Function|Boolean} [filter] + * @param {Function} [propFilter] + * + * @returns {Object} + */ + var toFlatObject = function toFlatObject(sourceObj, destObj, filter, propFilter) { + var props; + var i; + var prop; + var merged = {}; + destObj = destObj || {}; + // eslint-disable-next-line no-eq-null,eqeqeq + if (sourceObj == null) return destObj; + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + return destObj; + }; + + /** + * Determines whether a string ends with the characters of a specified string + * + * @param {String} str + * @param {String} searchString + * @param {Number} [position= 0] + * + * @returns {boolean} + */ + var endsWith = function endsWith(str, searchString, position) { + str = String(str); + if (position === undefined || position > str.length) { + position = str.length; + } + position -= searchString.length; + var lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; + }; + + /** + * Returns new array from array like object or null if failed + * + * @param {*} [thing] + * + * @returns {?Array} + */ + var toArray = function toArray(thing) { + if (!thing) return null; + if (isArray(thing)) return thing; + var i = thing.length; + if (!isNumber(i)) return null; + var arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; + }; + + /** + * Checking if the Uint8Array exists and if it does, it returns a function that checks if the + * thing passed in is an instance of Uint8Array + * + * @param {TypedArray} + * + * @returns {Array} + */ + // eslint-disable-next-line func-names + var isTypedArray = function (TypedArray) { + // eslint-disable-next-line func-names + return function (thing) { + return TypedArray && thing instanceof TypedArray; + }; + }(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); + + /** + * For each entry in the object, call the function with the key and value. + * + * @param {Object} obj - The object to iterate over. + * @param {Function} fn - The function to call for each entry. + * + * @returns {void} + */ + var forEachEntry = function forEachEntry(obj, fn) { + var generator = obj && obj[Symbol.iterator]; + var iterator = generator.call(obj); + var result; + while ((result = iterator.next()) && !result.done) { + var pair = result.value; + fn.call(obj, pair[0], pair[1]); + } + }; + + /** + * It takes a regular expression and a string, and returns an array of all the matches + * + * @param {string} regExp - The regular expression to match against. + * @param {string} str - The string to search. + * + * @returns {Array} + */ + var matchAll = function matchAll(regExp, str) { + var matches; + var arr = []; + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + return arr; + }; + + /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ + var isHTMLForm = kindOfTest('HTMLFormElement'); + var toCamelCase = function toCamelCase(str) { + return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; + }); + }; + + /* Creating a function that will check if an object has a property. */ + var hasOwnProperty = function (_ref4) { + var hasOwnProperty = _ref4.hasOwnProperty; + return function (obj, prop) { + return hasOwnProperty.call(obj, prop); + }; + }(Object.prototype); + + /** + * Determine if a value is a RegExp object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a RegExp object, otherwise false + */ + var isRegExp = kindOfTest('RegExp'); + var reduceDescriptors = function reduceDescriptors(obj, reducer) { + var descriptors = Object.getOwnPropertyDescriptors(obj); + var reducedDescriptors = {}; + forEach(descriptors, function (descriptor, name) { + var ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); + Object.defineProperties(obj, reducedDescriptors); + }; + + /** + * Makes all methods read-only + * @param {Object} obj + */ + + var freezeMethods = function freezeMethods(obj) { + reduceDescriptors(obj, function (descriptor, name) { + // skip restricted props in strict mode + if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { + return false; + } + var value = obj[name]; + if (!isFunction(value)) return; + descriptor.enumerable = false; + if ('writable' in descriptor) { + descriptor.writable = false; + return; + } + if (!descriptor.set) { + descriptor.set = function () { + throw Error('Can not rewrite read-only method \'' + name + '\''); + }; + } + }); + }; + var toObjectSet = function toObjectSet(arrayOrString, delimiter) { + var obj = {}; + var define = function define(arr) { + arr.forEach(function (value) { + obj[value] = true; + }); + }; + isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + return obj; + }; + var noop = function noop() {}; + var toFiniteNumber = function toFiniteNumber(value, defaultValue) { + return value != null && Number.isFinite(value = +value) ? value : defaultValue; + }; + var ALPHA = 'abcdefghijklmnopqrstuvwxyz'; + var DIGIT = '0123456789'; + var ALPHABET = { + DIGIT: DIGIT, + ALPHA: ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT + }; + var generateString = function generateString() { + var size = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 16; + var alphabet = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ALPHABET.ALPHA_DIGIT; + var str = ''; + var length = alphabet.length; + while (size--) { + str += alphabet[Math.random() * length | 0]; + } + return str; + }; + + /** + * If the thing is a FormData object, return true, otherwise return false. + * + * @param {unknown} thing - The thing to check. + * + * @returns {boolean} + */ + function isSpecCompliantForm(thing) { + return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]); + } + var toJSONObject = function toJSONObject(obj) { + var stack = new Array(10); + var visit = function visit(source, i) { + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + if (!('toJSON' in source)) { + stack[i] = source; + var target = isArray(source) ? [] : {}; + forEach(source, function (value, key) { + var reducedValue = visit(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + stack[i] = undefined; + return target; + } + } + return source; + }; + return visit(obj, 0); + }; + var isAsyncFn = kindOfTest('AsyncFunction'); + var isThenable = function isThenable(thing) { + return thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing["catch"]); + }; + + // original code + // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 + + var _setImmediate = function (setImmediateSupported, postMessageSupported) { + if (setImmediateSupported) { + return setImmediate; + } + return postMessageSupported ? function (token, callbacks) { + _global.addEventListener("message", function (_ref5) { + var source = _ref5.source, + data = _ref5.data; + if (source === _global && data === token) { + callbacks.length && callbacks.shift()(); + } + }, false); + return function (cb) { + callbacks.push(cb); + _global.postMessage(token, "*"); + }; + }("axios@".concat(Math.random()), []) : function (cb) { + return setTimeout(cb); + }; + }(typeof setImmediate === 'function', isFunction(_global.postMessage)); + var asap = typeof queueMicrotask !== 'undefined' ? queueMicrotask.bind(_global) : typeof process !== 'undefined' && process.nextTick || _setImmediate; + + // ********************* + + var utils$1 = { + isArray: isArray, + isArrayBuffer: isArrayBuffer, + isBuffer: isBuffer, + isFormData: isFormData, + isArrayBufferView: isArrayBufferView, + isString: isString, + isNumber: isNumber, + isBoolean: isBoolean, + isObject: isObject, + isPlainObject: isPlainObject, + isReadableStream: isReadableStream, + isRequest: isRequest, + isResponse: isResponse, + isHeaders: isHeaders, + isUndefined: isUndefined, + isDate: isDate, + isFile: isFile, + isBlob: isBlob, + isRegExp: isRegExp, + isFunction: isFunction, + isStream: isStream, + isURLSearchParams: isURLSearchParams, + isTypedArray: isTypedArray, + isFileList: isFileList, + forEach: forEach, + merge: merge, + extend: extend, + trim: trim, + stripBOM: stripBOM, + inherits: inherits, + toFlatObject: toFlatObject, + kindOf: kindOf, + kindOfTest: kindOfTest, + endsWith: endsWith, + toArray: toArray, + forEachEntry: forEachEntry, + matchAll: matchAll, + isHTMLForm: isHTMLForm, + hasOwnProperty: hasOwnProperty, + hasOwnProp: hasOwnProperty, + // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors: reduceDescriptors, + freezeMethods: freezeMethods, + toObjectSet: toObjectSet, + toCamelCase: toCamelCase, + noop: noop, + toFiniteNumber: toFiniteNumber, + findKey: findKey, + global: _global, + isContextDefined: isContextDefined, + ALPHABET: ALPHABET, + generateString: generateString, + isSpecCompliantForm: isSpecCompliantForm, + toJSONObject: toJSONObject, + isAsyncFn: isAsyncFn, + isThenable: isThenable, + setImmediate: _setImmediate, + asap: asap + }; + + /** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [config] The config. + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * + * @returns {Error} The created error. + */ + function AxiosError(message, code, config, request, response) { + Error.call(this); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack; + } + this.message = message; + this.name = 'AxiosError'; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status ? response.status : null; + } + } + utils$1.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils$1.toJSONObject(this.config), + code: this.code, + status: this.status + }; + } + }); + var prototype$1 = AxiosError.prototype; + var descriptors = {}; + ['ERR_BAD_OPTION_VALUE', 'ERR_BAD_OPTION', 'ECONNABORTED', 'ETIMEDOUT', 'ERR_NETWORK', 'ERR_FR_TOO_MANY_REDIRECTS', 'ERR_DEPRECATED', 'ERR_BAD_RESPONSE', 'ERR_BAD_REQUEST', 'ERR_CANCELED', 'ERR_NOT_SUPPORT', 'ERR_INVALID_URL' + // eslint-disable-next-line func-names + ].forEach(function (code) { + descriptors[code] = { + value: code + }; + }); + Object.defineProperties(AxiosError, descriptors); + Object.defineProperty(prototype$1, 'isAxiosError', { + value: true + }); + + // eslint-disable-next-line func-names + AxiosError.from = function (error, code, config, request, response, customProps) { + var axiosError = Object.create(prototype$1); + utils$1.toFlatObject(error, axiosError, function filter(obj) { + return obj !== Error.prototype; + }, function (prop) { + return prop !== 'isAxiosError'; + }); + AxiosError.call(axiosError, error.message, code, config, request, response); + axiosError.cause = error; + axiosError.name = error.name; + customProps && Object.assign(axiosError, customProps); + return axiosError; + }; + + // eslint-disable-next-line strict + var httpAdapter = null; + + /** + * Determines if the given thing is a array or js object. + * + * @param {string} thing - The object or array to be visited. + * + * @returns {boolean} + */ + function isVisitable(thing) { + return utils$1.isPlainObject(thing) || utils$1.isArray(thing); + } + + /** + * It removes the brackets from the end of a string + * + * @param {string} key - The key of the parameter. + * + * @returns {string} the key without the brackets. + */ + function removeBrackets(key) { + return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key; + } + + /** + * It takes a path, a key, and a boolean, and returns a string + * + * @param {string} path - The path to the current key. + * @param {string} key - The key of the current object being iterated over. + * @param {string} dots - If true, the key will be rendered with dots instead of brackets. + * + * @returns {string} The path to the current key. + */ + function renderKey(path, key, dots) { + if (!path) return key; + return path.concat(key).map(function each(token, i) { + // eslint-disable-next-line no-param-reassign + token = removeBrackets(token); + return !dots && i ? '[' + token + ']' : token; + }).join(dots ? '.' : ''); + } + + /** + * If the array is an array and none of its elements are visitable, then it's a flat array. + * + * @param {Array} arr - The array to check + * + * @returns {boolean} + */ + function isFlatArray(arr) { + return utils$1.isArray(arr) && !arr.some(isVisitable); + } + var predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); + }); + + /** + * Convert a data object to FormData + * + * @param {Object} obj + * @param {?Object} [formData] + * @param {?Object} [options] + * @param {Function} [options.visitor] + * @param {Boolean} [options.metaTokens = true] + * @param {Boolean} [options.dots = false] + * @param {?Boolean} [options.indexes = false] + * + * @returns {Object} + **/ + + /** + * It converts an object into a FormData object + * + * @param {Object} obj - The object to convert to form data. + * @param {string} formData - The FormData object to append to. + * @param {Object} options + * + * @returns + */ + function toFormData(obj, formData, options) { + if (!utils$1.isObject(obj)) { + throw new TypeError('target must be an object'); + } + + // eslint-disable-next-line no-param-reassign + formData = formData || new (FormData)(); + + // eslint-disable-next-line no-param-reassign + options = utils$1.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + // eslint-disable-next-line no-eq-null,eqeqeq + return !utils$1.isUndefined(source[option]); + }); + var metaTokens = options.metaTokens; + // eslint-disable-next-line no-use-before-define + var visitor = options.visitor || defaultVisitor; + var dots = options.dots; + var indexes = options.indexes; + var _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; + var useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + if (!utils$1.isFunction(visitor)) { + throw new TypeError('visitor must be a function'); + } + function convertValue(value) { + if (value === null) return ''; + if (utils$1.isDate(value)) { + return value.toISOString(); + } + if (!useBlob && utils$1.isBlob(value)) { + throw new AxiosError('Blob is not supported. Use a Buffer instead.'); + } + if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { + return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + } + return value; + } + + /** + * Default visitor. + * + * @param {*} value + * @param {String|Number} key + * @param {Array} path + * @this {FormData} + * + * @returns {boolean} return true to visit the each prop of the value recursively + */ + function defaultVisitor(value, key, path) { + var arr = value; + if (value && !path && _typeof(value) === 'object') { + if (utils$1.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign + key = metaTokens ? key : key.slice(0, -2); + // eslint-disable-next-line no-param-reassign + value = JSON.stringify(value); + } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))) { + // eslint-disable-next-line no-param-reassign + key = removeBrackets(key); + arr.forEach(function each(el, index) { + !(utils$1.isUndefined(el) || el === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + '[]', convertValue(el)); + }); + return false; + } + } + if (isVisitable(value)) { + return true; + } + formData.append(renderKey(path, key, dots), convertValue(value)); + return false; + } + var stack = []; + var exposedHelpers = Object.assign(predicates, { + defaultVisitor: defaultVisitor, + convertValue: convertValue, + isVisitable: isVisitable + }); + function build(value, path) { + if (utils$1.isUndefined(value)) return; + if (stack.indexOf(value) !== -1) { + throw Error('Circular reference detected in ' + path.join('.')); + } + stack.push(value); + utils$1.forEach(value, function each(el, key) { + var result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers); + if (result === true) { + build(el, path ? path.concat(key) : [key]); + } + }); + stack.pop(); + } + if (!utils$1.isObject(obj)) { + throw new TypeError('data must be an object'); + } + build(obj); + return formData; + } + + /** + * It encodes a string by replacing all characters that are not in the unreserved set with + * their percent-encoded equivalents + * + * @param {string} str - The string to encode. + * + * @returns {string} The encoded string. + */ + function encode$1(str) { + var charMap = { + '!': '%21', + "'": '%27', + '(': '%28', + ')': '%29', + '~': '%7E', + '%20': '+', + '%00': '\x00' + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); + } + + /** + * It takes a params object and converts it to a FormData object + * + * @param {Object} params - The parameters to be converted to a FormData object. + * @param {Object} options - The options object passed to the Axios constructor. + * + * @returns {void} + */ + function AxiosURLSearchParams(params, options) { + this._pairs = []; + params && toFormData(params, this, options); + } + var prototype = AxiosURLSearchParams.prototype; + prototype.append = function append(name, value) { + this._pairs.push([name, value]); + }; + prototype.toString = function toString(encoder) { + var _encode = encoder ? function (value) { + return encoder.call(this, value, encode$1); + } : encode$1; + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + '=' + _encode(pair[1]); + }, '').join('&'); + }; + + /** + * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their + * URI encoded counterparts + * + * @param {string} val The value to be encoded. + * + * @returns {string} The encoded value. + */ + function encode(val) { + return encodeURIComponent(val).replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']'); + } + + /** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @param {?(object|Function)} options + * + * @returns {string} The formatted url + */ + function buildURL(url, params, options) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + var _encode = options && options.encode || encode; + if (utils$1.isFunction(options)) { + options = { + serialize: options + }; + } + var serializeFn = options && options.serialize; + var serializedParams; + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, options).toString(_encode); + } + if (serializedParams) { + var hashmarkIndex = url.indexOf("#"); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + return url; + } + + var InterceptorManager = /*#__PURE__*/function () { + function InterceptorManager() { + _classCallCheck(this, InterceptorManager); + this.handlers = []; + } + + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + _createClass(InterceptorManager, [{ + key: "use", + value: function use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + */ + }, { + key: "eject", + value: function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + }, { + key: "clear", + value: function clear() { + if (this.handlers) { + this.handlers = []; + } + } + + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + }, { + key: "forEach", + value: function forEach(fn) { + utils$1.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + } + }]); + return InterceptorManager; + }(); + var InterceptorManager$1 = InterceptorManager; + + var transitionalDefaults = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false + }; + + var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams; + + var FormData$1 = typeof FormData !== 'undefined' ? FormData : null; + + var Blob$1 = typeof Blob !== 'undefined' ? Blob : null; + + var platform$1 = { + isBrowser: true, + classes: { + URLSearchParams: URLSearchParams$1, + FormData: FormData$1, + Blob: Blob$1 + }, + protocols: ['http', 'https', 'file', 'blob', 'url', 'data'] + }; + + var hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; + var _navigator = (typeof navigator === "undefined" ? "undefined" : _typeof(navigator)) === 'object' && navigator || undefined; + + /** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + * + * @returns {boolean} + */ + var hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0); + + /** + * Determine if we're running in a standard browser webWorker environment + * + * Although the `isStandardBrowserEnv` method indicates that + * `allows axios to run in a web worker`, the WebWorker will still be + * filtered out due to its judgment standard + * `typeof window !== 'undefined' && typeof document !== 'undefined'`. + * This leads to a problem when axios post `FormData` in webWorker + */ + var hasStandardBrowserWebWorkerEnv = function () { + return typeof WorkerGlobalScope !== 'undefined' && + // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && typeof self.importScripts === 'function'; + }(); + var origin = hasBrowserEnv && window.location.href || 'http://localhost'; + + var utils = /*#__PURE__*/Object.freeze({ + __proto__: null, + hasBrowserEnv: hasBrowserEnv, + hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, + hasStandardBrowserEnv: hasStandardBrowserEnv, + navigator: _navigator, + origin: origin + }); + + var platform = _objectSpread2(_objectSpread2({}, utils), platform$1); + + function toURLEncodedForm(data, options) { + return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ + visitor: function visitor(value, key, path, helpers) { + if (platform.isNode && utils$1.isBuffer(value)) { + this.append(key, value.toString('base64')); + return false; + } + return helpers.defaultVisitor.apply(this, arguments); + } + }, options)); + } + + /** + * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z'] + * + * @param {string} name - The name of the property to get. + * + * @returns An array of strings. + */ + function parsePropPath(name) { + // foo[x][y][z] + // foo.x.y.z + // foo-x-y-z + // foo x y z + return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(function (match) { + return match[0] === '[]' ? '' : match[1] || match[0]; + }); + } + + /** + * Convert an array to an object. + * + * @param {Array} arr - The array to convert to an object. + * + * @returns An object with the same keys and values as the array. + */ + function arrayToObject(arr) { + var obj = {}; + var keys = Object.keys(arr); + var i; + var len = keys.length; + var key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; + } + + /** + * It takes a FormData object and returns a JavaScript object + * + * @param {string} formData The FormData object to convert to JSON. + * + * @returns {Object | null} The converted object. + */ + function formDataToJSON(formData) { + function buildPath(path, value, target, index) { + var name = path[index++]; + if (name === '__proto__') return true; + var isNumericKey = Number.isFinite(+name); + var isLast = index >= path.length; + name = !name && utils$1.isArray(target) ? target.length : name; + if (isLast) { + if (utils$1.hasOwnProp(target, name)) { + target[name] = [target[name], value]; + } else { + target[name] = value; + } + return !isNumericKey; + } + if (!target[name] || !utils$1.isObject(target[name])) { + target[name] = []; + } + var result = buildPath(path, value, target[name], index); + if (result && utils$1.isArray(target[name])) { + target[name] = arrayToObject(target[name]); + } + return !isNumericKey; + } + if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { + var obj = {}; + utils$1.forEachEntry(formData, function (name, value) { + buildPath(parsePropPath(name), value, obj, 0); + }); + return obj; + } + return null; + } + + /** + * It takes a string, tries to parse it, and if it fails, it returns the stringified version + * of the input + * + * @param {any} rawValue - The value to be stringified. + * @param {Function} parser - A function that parses a string into a JavaScript object. + * @param {Function} encoder - A function that takes a value and returns a string. + * + * @returns {string} A stringified version of the rawValue. + */ + function stringifySafely(rawValue, parser, encoder) { + if (utils$1.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils$1.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } + } + } + return (encoder || JSON.stringify)(rawValue); + } + var defaults = { + transitional: transitionalDefaults, + adapter: ['xhr', 'http', 'fetch'], + transformRequest: [function transformRequest(data, headers) { + var contentType = headers.getContentType() || ''; + var hasJSONContentType = contentType.indexOf('application/json') > -1; + var isObjectPayload = utils$1.isObject(data); + if (isObjectPayload && utils$1.isHTMLForm(data)) { + data = new FormData(data); + } + var isFormData = utils$1.isFormData(data); + if (isFormData) { + return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; + } + if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) { + return data; + } + if (utils$1.isArrayBufferView(data)) { + return data.buffer; + } + if (utils$1.isURLSearchParams(data)) { + headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); + return data.toString(); + } + var isFileList; + if (isObjectPayload) { + if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { + var _FormData = this.env && this.env.FormData; + return toFormData(isFileList ? { + 'files[]': data + } : data, _FormData && new _FormData(), this.formSerializer); + } + } + if (isObjectPayload || hasJSONContentType) { + headers.setContentType('application/json', false); + return stringifySafely(data); + } + return data; + }], + transformResponse: [function transformResponse(data) { + var transitional = this.transitional || defaults.transitional; + var forcedJSONParsing = transitional && transitional.forcedJSONParsing; + var JSONRequested = this.responseType === 'json'; + if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) { + return data; + } + if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { + var silentJSONParsing = transitional && transitional.silentJSONParsing; + var strictJSONParsing = !silentJSONParsing && JSONRequested; + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } + return data; + }], + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + maxContentLength: -1, + maxBodyLength: -1, + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + headers: { + common: { + 'Accept': 'application/json, text/plain, */*', + 'Content-Type': undefined + } + } + }; + utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], function (method) { + defaults.headers[method] = {}; + }); + var defaults$1 = defaults; + + // RawAxiosHeaders whose duplicates are ignored by node + // c.f. https://nodejs.org/api/http.html#http_message_headers + var ignoreDuplicateOf = utils$1.toObjectSet(['age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent']); + + /** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} rawHeaders Headers needing to be parsed + * + * @returns {Object} Headers parsed into an object + */ + var parseHeaders = (function (rawHeaders) { + var parsed = {}; + var key; + var val; + var i; + rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { + i = line.indexOf(':'); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + if (!key || parsed[key] && ignoreDuplicateOf[key]) { + return; + } + if (key === 'set-cookie') { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + }); + return parsed; + }); + + var $internals = Symbol('internals'); + function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); + } + function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + return utils$1.isArray(value) ? value.map(normalizeValue) : String(value); + } + function parseTokens(str) { + var tokens = Object.create(null); + var tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + var match; + while (match = tokensRE.exec(str)) { + tokens[match[1]] = match[2]; + } + return tokens; + } + var isValidHeaderName = function isValidHeaderName(str) { + return /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); + }; + function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { + if (utils$1.isFunction(filter)) { + return filter.call(this, value, header); + } + if (isHeaderNameFilter) { + value = header; + } + if (!utils$1.isString(value)) return; + if (utils$1.isString(filter)) { + return value.indexOf(filter) !== -1; + } + if (utils$1.isRegExp(filter)) { + return filter.test(value); + } + } + function formatHeader(header) { + return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, function (w, _char, str) { + return _char.toUpperCase() + str; + }); + } + function buildAccessors(obj, header) { + var accessorName = utils$1.toCamelCase(' ' + header); + ['get', 'set', 'has'].forEach(function (methodName) { + Object.defineProperty(obj, methodName + accessorName, { + value: function value(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); + } + var AxiosHeaders = /*#__PURE__*/function (_Symbol$iterator, _Symbol$toStringTag) { + function AxiosHeaders(headers) { + _classCallCheck(this, AxiosHeaders); + headers && this.set(headers); + } + _createClass(AxiosHeaders, [{ + key: "set", + value: function set(header, valueOrRewrite, rewrite) { + var self = this; + function setHeader(_value, _header, _rewrite) { + var lHeader = normalizeHeader(_header); + if (!lHeader) { + throw new Error('header name must be a non-empty string'); + } + var key = utils$1.findKey(self, lHeader); + if (!key || self[key] === undefined || _rewrite === true || _rewrite === undefined && self[key] !== false) { + self[key || _header] = normalizeValue(_value); + } + } + var setHeaders = function setHeaders(headers, _rewrite) { + return utils$1.forEach(headers, function (_value, _header) { + return setHeader(_value, _header, _rewrite); + }); + }; + if (utils$1.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else if (utils$1.isHeaders(header)) { + var _iterator = _createForOfIteratorHelper(header.entries()), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var _step$value = _slicedToArray(_step.value, 2), + key = _step$value[0], + value = _step$value[1]; + setHeader(value, key, rewrite); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + return this; + } + }, { + key: "get", + value: function get(header, parser) { + header = normalizeHeader(header); + if (header) { + var key = utils$1.findKey(this, header); + if (key) { + var value = this[key]; + if (!parser) { + return value; + } + if (parser === true) { + return parseTokens(value); + } + if (utils$1.isFunction(parser)) { + return parser.call(this, value, key); + } + if (utils$1.isRegExp(parser)) { + return parser.exec(value); + } + throw new TypeError('parser must be boolean|regexp|function'); + } + } + } + }, { + key: "has", + value: function has(header, matcher) { + header = normalizeHeader(header); + if (header) { + var key = utils$1.findKey(this, header); + return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + } + return false; + } + }, { + key: "delete", + value: function _delete(header, matcher) { + var self = this; + var deleted = false; + function deleteHeader(_header) { + _header = normalizeHeader(_header); + if (_header) { + var key = utils$1.findKey(self, _header); + if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { + delete self[key]; + deleted = true; + } + } + } + if (utils$1.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + return deleted; + } + }, { + key: "clear", + value: function clear(matcher) { + var keys = Object.keys(this); + var i = keys.length; + var deleted = false; + while (i--) { + var key = keys[i]; + if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + return deleted; + } + }, { + key: "normalize", + value: function normalize(format) { + var self = this; + var headers = {}; + utils$1.forEach(this, function (value, header) { + var key = utils$1.findKey(headers, header); + if (key) { + self[key] = normalizeValue(value); + delete self[header]; + return; + } + var normalized = format ? formatHeader(header) : String(header).trim(); + if (normalized !== header) { + delete self[header]; + } + self[normalized] = normalizeValue(value); + headers[normalized] = true; + }); + return this; + } + }, { + key: "concat", + value: function concat() { + var _this$constructor; + for (var _len = arguments.length, targets = new Array(_len), _key = 0; _key < _len; _key++) { + targets[_key] = arguments[_key]; + } + return (_this$constructor = this.constructor).concat.apply(_this$constructor, [this].concat(targets)); + } + }, { + key: "toJSON", + value: function toJSON(asStrings) { + var obj = Object.create(null); + utils$1.forEach(this, function (value, header) { + value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value); + }); + return obj; + } + }, { + key: _Symbol$iterator, + value: function value() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + }, { + key: "toString", + value: function toString() { + return Object.entries(this.toJSON()).map(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + header = _ref2[0], + value = _ref2[1]; + return header + ': ' + value; + }).join('\n'); + } + }, { + key: _Symbol$toStringTag, + get: function get() { + return 'AxiosHeaders'; + } + }], [{ + key: "from", + value: function from(thing) { + return thing instanceof this ? thing : new this(thing); + } + }, { + key: "concat", + value: function concat(first) { + var computed = new this(first); + for (var _len2 = arguments.length, targets = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + targets[_key2 - 1] = arguments[_key2]; + } + targets.forEach(function (target) { + return computed.set(target); + }); + return computed; + } + }, { + key: "accessor", + value: function accessor(header) { + var internals = this[$internals] = this[$internals] = { + accessors: {} + }; + var accessors = internals.accessors; + var prototype = this.prototype; + function defineAccessor(_header) { + var lHeader = normalizeHeader(_header); + if (!accessors[lHeader]) { + buildAccessors(prototype, _header); + accessors[lHeader] = true; + } + } + utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + return this; + } + }]); + return AxiosHeaders; + }(Symbol.iterator, Symbol.toStringTag); + AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); + + // reserved names hotfix + utils$1.reduceDescriptors(AxiosHeaders.prototype, function (_ref3, key) { + var value = _ref3.value; + var mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` + return { + get: function get() { + return value; + }, + set: function set(headerValue) { + this[mapped] = headerValue; + } + }; + }); + utils$1.freezeMethods(AxiosHeaders); + var AxiosHeaders$1 = AxiosHeaders; + + /** + * Transform the data for a request or a response + * + * @param {Array|Function} fns A single function or Array of functions + * @param {?Object} response The response object + * + * @returns {*} The resulting transformed data + */ + function transformData(fns, response) { + var config = this || defaults$1; + var context = response || config; + var headers = AxiosHeaders$1.from(context.headers); + var data = context.data; + utils$1.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); + }); + headers.normalize(); + return data; + } + + function isCancel(value) { + return !!(value && value.__CANCEL__); + } + + /** + * A `CanceledError` is an object that is thrown when an operation is canceled. + * + * @param {string=} message The message. + * @param {Object=} config The config. + * @param {Object=} request The request. + * + * @returns {CanceledError} The created error. + */ + function CanceledError(message, config, request) { + // eslint-disable-next-line no-eq-null,eqeqeq + AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); + this.name = 'CanceledError'; + } + utils$1.inherits(CanceledError, AxiosError, { + __CANCEL__: true + }); + + /** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + * + * @returns {object} The response. + */ + function settle(resolve, reject, response) { + var validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new AxiosError('Request failed with status code ' + response.status, [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], response.config, response.request, response)); + } + } + + function parseProtocol(url) { + var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ''; + } + + /** + * Calculate data maxRate + * @param {Number} [samplesCount= 10] + * @param {Number} [min= 1000] + * @returns {Function} + */ + function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + var bytes = new Array(samplesCount); + var timestamps = new Array(samplesCount); + var head = 0; + var tail = 0; + var firstSampleTS; + min = min !== undefined ? min : 1000; + return function push(chunkLength) { + var now = Date.now(); + var startedAt = timestamps[tail]; + if (!firstSampleTS) { + firstSampleTS = now; + } + bytes[head] = chunkLength; + timestamps[head] = now; + var i = tail; + var bytesCount = 0; + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + head = (head + 1) % samplesCount; + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + if (now - firstSampleTS < min) { + return; + } + var passed = startedAt && now - startedAt; + return passed ? Math.round(bytesCount * 1000 / passed) : undefined; + }; + } + + /** + * Throttle decorator + * @param {Function} fn + * @param {Number} freq + * @return {Function} + */ + function throttle(fn, freq) { + var timestamp = 0; + var threshold = 1000 / freq; + var lastArgs; + var timer; + var invoke = function invoke(args) { + var now = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Date.now(); + timestamp = now; + lastArgs = null; + if (timer) { + clearTimeout(timer); + timer = null; + } + fn.apply(null, args); + }; + var throttled = function throttled() { + var now = Date.now(); + var passed = now - timestamp; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (passed >= threshold) { + invoke(args, now); + } else { + lastArgs = args; + if (!timer) { + timer = setTimeout(function () { + timer = null; + invoke(lastArgs); + }, threshold - passed); + } + } + }; + var flush = function flush() { + return lastArgs && invoke(lastArgs); + }; + return [throttled, flush]; + } + + var progressEventReducer = function progressEventReducer(listener, isDownloadStream) { + var freq = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 3; + var bytesNotified = 0; + var _speedometer = speedometer(50, 250); + return throttle(function (e) { + var loaded = e.loaded; + var total = e.lengthComputable ? e.total : undefined; + var progressBytes = loaded - bytesNotified; + var rate = _speedometer(progressBytes); + var inRange = loaded <= total; + bytesNotified = loaded; + var data = _defineProperty({ + loaded: loaded, + total: total, + progress: total ? loaded / total : undefined, + bytes: progressBytes, + rate: rate ? rate : undefined, + estimated: rate && total && inRange ? (total - loaded) / rate : undefined, + event: e, + lengthComputable: total != null + }, isDownloadStream ? 'download' : 'upload', true); + listener(data); + }, freq); + }; + var progressEventDecorator = function progressEventDecorator(total, throttled) { + var lengthComputable = total != null; + return [function (loaded) { + return throttled[0]({ + lengthComputable: lengthComputable, + total: total, + loaded: loaded + }); + }, throttled[1]]; + }; + var asyncDecorator = function asyncDecorator(fn) { + return function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return utils$1.asap(function () { + return fn.apply(void 0, args); + }); + }; + }; + + var isURLSameOrigin = platform.hasStandardBrowserEnv ? function (origin, isMSIE) { + return function (url) { + url = new URL(url, platform.origin); + return origin.protocol === url.protocol && origin.host === url.host && (isMSIE || origin.port === url.port); + }; + }(new URL(platform.origin), platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)) : function () { + return true; + }; + + var cookies = platform.hasStandardBrowserEnv ? + // Standard browser envs support document.cookie + { + write: function write(name, value, expires, path, domain, secure) { + var cookie = [name + '=' + encodeURIComponent(value)]; + utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString()); + utils$1.isString(path) && cookie.push('path=' + path); + utils$1.isString(domain) && cookie.push('domain=' + domain); + secure === true && cookie.push('secure'); + document.cookie = cookie.join('; '); + }, + read: function read(name) { + var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return match ? decodeURIComponent(match[3]) : null; + }, + remove: function remove(name) { + this.write(name, '', Date.now() - 86400000); + } + } : + // Non-standard browser env (web workers, react-native) lack needed support. + { + write: function write() {}, + read: function read() { + return null; + }, + remove: function remove() {} + }; + + /** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ + function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); + } + + /** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * + * @returns {string} The combined URL + */ + function combineURLs(baseURL, relativeURL) { + return relativeURL ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; + } + + /** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * + * @returns {string} The combined full path + */ + function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; + } + + var headersToObject = function headersToObject(thing) { + return thing instanceof AxiosHeaders$1 ? _objectSpread2({}, thing) : thing; + }; + + /** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * + * @returns {Object} New object resulting from merging config2 to config1 + */ + function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + var config = {}; + function getMergedValue(target, source, prop, caseless) { + if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { + return utils$1.merge.call({ + caseless: caseless + }, target, source); + } else if (utils$1.isPlainObject(source)) { + return utils$1.merge({}, source); + } else if (utils$1.isArray(source)) { + return source.slice(); + } + return source; + } + + // eslint-disable-next-line consistent-return + function mergeDeepProperties(a, b, prop, caseless) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(a, b, prop, caseless); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(undefined, a, prop, caseless); + } + } + + // eslint-disable-next-line consistent-return + function valueFromConfig2(a, b) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(undefined, b); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(a, b) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(undefined, b); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(undefined, a); + } + } + + // eslint-disable-next-line consistent-return + function mergeDirectKeys(a, b, prop) { + if (prop in config2) { + return getMergedValue(a, b); + } else if (prop in config1) { + return getMergedValue(undefined, a); + } + } + var mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: function headers(a, b, prop) { + return mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true); + } + }; + utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + var merge = mergeMap[prop] || mergeDeepProperties; + var configValue = merge(config1[prop], config2[prop], prop); + utils$1.isUndefined(configValue) && merge !== mergeDirectKeys || (config[prop] = configValue); + }); + return config; + } + + var resolveConfig = (function (config) { + var newConfig = mergeConfig({}, config); + var data = newConfig.data, + withXSRFToken = newConfig.withXSRFToken, + xsrfHeaderName = newConfig.xsrfHeaderName, + xsrfCookieName = newConfig.xsrfCookieName, + headers = newConfig.headers, + auth = newConfig.auth; + newConfig.headers = headers = AxiosHeaders$1.from(headers); + newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer); + + // HTTP basic authentication + if (auth) { + headers.set('Authorization', 'Basic ' + btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))); + } + var contentType; + if (utils$1.isFormData(data)) { + if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { + headers.setContentType(undefined); // Let the browser set it + } else if ((contentType = headers.getContentType()) !== false) { + // fix semicolon duplication issue for ReactNative FormData implementation + var _ref = contentType ? contentType.split(';').map(function (token) { + return token.trim(); + }).filter(Boolean) : [], + _ref2 = _toArray(_ref), + type = _ref2[0], + tokens = _ref2.slice(1); + headers.setContentType([type || 'multipart/form-data'].concat(_toConsumableArray(tokens)).join('; ')); + } + } + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + + if (platform.hasStandardBrowserEnv) { + withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); + if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(newConfig.url)) { + // Add xsrf header + var xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); + if (xsrfValue) { + headers.set(xsrfHeaderName, xsrfValue); + } + } + } + return newConfig; + }); + + var isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; + var xhrAdapter = isXHRAdapterSupported && function (config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + var _config = resolveConfig(config); + var requestData = _config.data; + var requestHeaders = AxiosHeaders$1.from(_config.headers).normalize(); + var responseType = _config.responseType, + onUploadProgress = _config.onUploadProgress, + onDownloadProgress = _config.onDownloadProgress; + var onCanceled; + var uploadThrottled, downloadThrottled; + var flushUpload, flushDownload; + function done() { + flushUpload && flushUpload(); // flush events + flushDownload && flushDownload(); // flush events + + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + _config.signal && _config.signal.removeEventListener('abort', onCanceled); + } + var request = new XMLHttpRequest(); + request.open(_config.method.toUpperCase(), _config.url, true); + + // Set the request timeout in MS + request.timeout = _config.timeout; + function onloadend() { + if (!request) { + return; + } + // Prepare the response + var responseHeaders = AxiosHeaders$1.from('getAllResponseHeaders' in request && request.getAllResponseHeaders()); + var responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response; + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request + }; + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + + // Clean up request + request = null; + } + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + var timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded'; + var transitional = _config.transitional || transitionalDefaults; + if (_config.timeoutErrorMessage) { + timeoutErrorMessage = _config.timeoutErrorMessage; + } + reject(new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, request)); + + // Clean up request + request = null; + }; + + // Remove Content-Type if data is undefined + requestData === undefined && requestHeaders.setContentType(null); + + // Add headers to the request + if ('setRequestHeader' in request) { + utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + + // Add withCredentials to request if needed + if (!utils$1.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; + } + + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = _config.responseType; + } + + // Handle progress if needed + if (onDownloadProgress) { + var _progressEventReducer = progressEventReducer(onDownloadProgress, true); + var _progressEventReducer2 = _slicedToArray(_progressEventReducer, 2); + downloadThrottled = _progressEventReducer2[0]; + flushDownload = _progressEventReducer2[1]; + request.addEventListener('progress', downloadThrottled); + } + + // Not all browsers support upload events + if (onUploadProgress && request.upload) { + var _progressEventReducer3 = progressEventReducer(onUploadProgress); + var _progressEventReducer4 = _slicedToArray(_progressEventReducer3, 2); + uploadThrottled = _progressEventReducer4[0]; + flushUpload = _progressEventReducer4[1]; + request.upload.addEventListener('progress', uploadThrottled); + request.upload.addEventListener('loadend', flushUpload); + } + if (_config.cancelToken || _config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = function onCanceled(cancel) { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); + request.abort(); + request = null; + }; + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled); + } + } + var protocol = parseProtocol(_config.url); + if (protocol && platform.protocols.indexOf(protocol) === -1) { + reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); + return; + } + + // Send the request + request.send(requestData || null); + }); + }; + + var composeSignals = function composeSignals(signals, timeout) { + var _signals = signals = signals ? signals.filter(Boolean) : [], + length = _signals.length; + if (timeout || length) { + var controller = new AbortController(); + var aborted; + var onabort = function onabort(reason) { + if (!aborted) { + aborted = true; + unsubscribe(); + var err = reason instanceof Error ? reason : this.reason; + controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err)); + } + }; + var timer = timeout && setTimeout(function () { + timer = null; + onabort(new AxiosError("timeout ".concat(timeout, " of ms exceeded"), AxiosError.ETIMEDOUT)); + }, timeout); + var unsubscribe = function unsubscribe() { + if (signals) { + timer && clearTimeout(timer); + timer = null; + signals.forEach(function (signal) { + signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort); + }); + signals = null; + } + }; + signals.forEach(function (signal) { + return signal.addEventListener('abort', onabort); + }); + var signal = controller.signal; + signal.unsubscribe = function () { + return utils$1.asap(unsubscribe); + }; + return signal; + } + }; + var composeSignals$1 = composeSignals; + + var streamChunk = /*#__PURE__*/_regeneratorRuntime().mark(function streamChunk(chunk, chunkSize) { + var len, pos, end; + return _regeneratorRuntime().wrap(function streamChunk$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + len = chunk.byteLength; + if (!(!chunkSize || len < chunkSize)) { + _context.next = 5; + break; + } + _context.next = 4; + return chunk; + case 4: + return _context.abrupt("return"); + case 5: + pos = 0; + case 6: + if (!(pos < len)) { + _context.next = 13; + break; + } + end = pos + chunkSize; + _context.next = 10; + return chunk.slice(pos, end); + case 10: + pos = end; + _context.next = 6; + break; + case 13: + case "end": + return _context.stop(); + } + }, streamChunk); + }); + var readBytes = /*#__PURE__*/function () { + var _ref = _wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(iterable, chunkSize) { + var _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, chunk; + return _regeneratorRuntime().wrap(function _callee$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _iteratorAbruptCompletion = false; + _didIteratorError = false; + _context2.prev = 2; + _iterator = _asyncIterator(readStream(iterable)); + case 4: + _context2.next = 6; + return _awaitAsyncGenerator(_iterator.next()); + case 6: + if (!(_iteratorAbruptCompletion = !(_step = _context2.sent).done)) { + _context2.next = 12; + break; + } + chunk = _step.value; + return _context2.delegateYield(_asyncGeneratorDelegate(_asyncIterator(streamChunk(chunk, chunkSize))), "t0", 9); + case 9: + _iteratorAbruptCompletion = false; + _context2.next = 4; + break; + case 12: + _context2.next = 18; + break; + case 14: + _context2.prev = 14; + _context2.t1 = _context2["catch"](2); + _didIteratorError = true; + _iteratorError = _context2.t1; + case 18: + _context2.prev = 18; + _context2.prev = 19; + if (!(_iteratorAbruptCompletion && _iterator["return"] != null)) { + _context2.next = 23; + break; + } + _context2.next = 23; + return _awaitAsyncGenerator(_iterator["return"]()); + case 23: + _context2.prev = 23; + if (!_didIteratorError) { + _context2.next = 26; + break; + } + throw _iteratorError; + case 26: + return _context2.finish(23); + case 27: + return _context2.finish(18); + case 28: + case "end": + return _context2.stop(); + } + }, _callee, null, [[2, 14, 18, 28], [19,, 23, 27]]); + })); + return function readBytes(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + var readStream = /*#__PURE__*/function () { + var _ref2 = _wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(stream) { + var reader, _yield$_awaitAsyncGen, done, value; + return _regeneratorRuntime().wrap(function _callee2$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (!stream[Symbol.asyncIterator]) { + _context3.next = 3; + break; + } + return _context3.delegateYield(_asyncGeneratorDelegate(_asyncIterator(stream)), "t0", 2); + case 2: + return _context3.abrupt("return"); + case 3: + reader = stream.getReader(); + _context3.prev = 4; + case 5: + _context3.next = 7; + return _awaitAsyncGenerator(reader.read()); + case 7: + _yield$_awaitAsyncGen = _context3.sent; + done = _yield$_awaitAsyncGen.done; + value = _yield$_awaitAsyncGen.value; + if (!done) { + _context3.next = 12; + break; + } + return _context3.abrupt("break", 16); + case 12: + _context3.next = 14; + return value; + case 14: + _context3.next = 5; + break; + case 16: + _context3.prev = 16; + _context3.next = 19; + return _awaitAsyncGenerator(reader.cancel()); + case 19: + return _context3.finish(16); + case 20: + case "end": + return _context3.stop(); + } + }, _callee2, null, [[4,, 16, 20]]); + })); + return function readStream(_x3) { + return _ref2.apply(this, arguments); + }; + }(); + var trackStream = function trackStream(stream, chunkSize, onProgress, onFinish) { + var iterator = readBytes(stream, chunkSize); + var bytes = 0; + var done; + var _onFinish = function _onFinish(e) { + if (!done) { + done = true; + onFinish && onFinish(e); + } + }; + return new ReadableStream({ + pull: function pull(controller) { + return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { + var _yield$iterator$next, _done, value, len, loadedBytes; + return _regeneratorRuntime().wrap(function _callee3$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.prev = 0; + _context4.next = 3; + return iterator.next(); + case 3: + _yield$iterator$next = _context4.sent; + _done = _yield$iterator$next.done; + value = _yield$iterator$next.value; + if (!_done) { + _context4.next = 10; + break; + } + _onFinish(); + controller.close(); + return _context4.abrupt("return"); + case 10: + len = value.byteLength; + if (onProgress) { + loadedBytes = bytes += len; + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); + _context4.next = 19; + break; + case 15: + _context4.prev = 15; + _context4.t0 = _context4["catch"](0); + _onFinish(_context4.t0); + throw _context4.t0; + case 19: + case "end": + return _context4.stop(); + } + }, _callee3, null, [[0, 15]]); + }))(); + }, + cancel: function cancel(reason) { + _onFinish(reason); + return iterator["return"](); + } + }, { + highWaterMark: 2 + }); + }; + + var isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function'; + var isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function'; + + // used only inside the fetch adapter + var encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? function (encoder) { + return function (str) { + return encoder.encode(str); + }; + }(new TextEncoder()) : ( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(str) { + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.t0 = Uint8Array; + _context.next = 3; + return new Response(str).arrayBuffer(); + case 3: + _context.t1 = _context.sent; + return _context.abrupt("return", new _context.t0(_context.t1)); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }())); + var test = function test(fn) { + try { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + return !!fn.apply(void 0, args); + } catch (e) { + return false; + } + }; + var supportsRequestStream = isReadableStreamSupported && test(function () { + var duplexAccessed = false; + var hasContentType = new Request(platform.origin, { + body: new ReadableStream(), + method: 'POST', + get duplex() { + duplexAccessed = true; + return 'half'; + } + }).headers.has('Content-Type'); + return duplexAccessed && !hasContentType; + }); + var DEFAULT_CHUNK_SIZE = 64 * 1024; + var supportsResponseStream = isReadableStreamSupported && test(function () { + return utils$1.isReadableStream(new Response('').body); + }); + var resolvers = { + stream: supportsResponseStream && function (res) { + return res.body; + } + }; + isFetchSupported && function (res) { + ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(function (type) { + !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? function (res) { + return res[type](); + } : function (_, config) { + throw new AxiosError("Response type '".concat(type, "' is not supported"), AxiosError.ERR_NOT_SUPPORT, config); + }); + }); + }(new Response()); + var getBodyLength = /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(body) { + var _request; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (!(body == null)) { + _context2.next = 2; + break; + } + return _context2.abrupt("return", 0); + case 2: + if (!utils$1.isBlob(body)) { + _context2.next = 4; + break; + } + return _context2.abrupt("return", body.size); + case 4: + if (!utils$1.isSpecCompliantForm(body)) { + _context2.next = 9; + break; + } + _request = new Request(platform.origin, { + method: 'POST', + body: body + }); + _context2.next = 8; + return _request.arrayBuffer(); + case 8: + return _context2.abrupt("return", _context2.sent.byteLength); + case 9: + if (!(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body))) { + _context2.next = 11; + break; + } + return _context2.abrupt("return", body.byteLength); + case 11: + if (utils$1.isURLSearchParams(body)) { + body = body + ''; + } + if (!utils$1.isString(body)) { + _context2.next = 16; + break; + } + _context2.next = 15; + return encodeText(body); + case 15: + return _context2.abrupt("return", _context2.sent.byteLength); + case 16: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function getBodyLength(_x2) { + return _ref2.apply(this, arguments); + }; + }(); + var resolveBodyLength = /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(headers, body) { + var length; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + length = utils$1.toFiniteNumber(headers.getContentLength()); + return _context3.abrupt("return", length == null ? getBodyLength(body) : length); + case 2: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return function resolveBodyLength(_x3, _x4) { + return _ref3.apply(this, arguments); + }; + }(); + var fetchAdapter = isFetchSupported && ( /*#__PURE__*/function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(config) { + var _resolveConfig, url, method, data, signal, cancelToken, timeout, onDownloadProgress, onUploadProgress, responseType, headers, _resolveConfig$withCr, withCredentials, fetchOptions, composedSignal, request, unsubscribe, requestContentLength, _request, contentTypeHeader, _progressEventDecorat, _progressEventDecorat2, onProgress, flush, isCredentialsSupported, response, isStreamResponse, options, responseContentLength, _ref5, _ref6, _onProgress, _flush, responseData; + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _resolveConfig = resolveConfig(config), url = _resolveConfig.url, method = _resolveConfig.method, data = _resolveConfig.data, signal = _resolveConfig.signal, cancelToken = _resolveConfig.cancelToken, timeout = _resolveConfig.timeout, onDownloadProgress = _resolveConfig.onDownloadProgress, onUploadProgress = _resolveConfig.onUploadProgress, responseType = _resolveConfig.responseType, headers = _resolveConfig.headers, _resolveConfig$withCr = _resolveConfig.withCredentials, withCredentials = _resolveConfig$withCr === void 0 ? 'same-origin' : _resolveConfig$withCr, fetchOptions = _resolveConfig.fetchOptions; + responseType = responseType ? (responseType + '').toLowerCase() : 'text'; + composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + unsubscribe = composedSignal && composedSignal.unsubscribe && function () { + composedSignal.unsubscribe(); + }; + _context4.prev = 4; + _context4.t0 = onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head'; + if (!_context4.t0) { + _context4.next = 11; + break; + } + _context4.next = 9; + return resolveBodyLength(headers, data); + case 9: + _context4.t1 = requestContentLength = _context4.sent; + _context4.t0 = _context4.t1 !== 0; + case 11: + if (!_context4.t0) { + _context4.next = 15; + break; + } + _request = new Request(url, { + method: 'POST', + body: data, + duplex: "half" + }); + if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { + headers.setContentType(contentTypeHeader); + } + if (_request.body) { + _progressEventDecorat = progressEventDecorator(requestContentLength, progressEventReducer(asyncDecorator(onUploadProgress))), _progressEventDecorat2 = _slicedToArray(_progressEventDecorat, 2), onProgress = _progressEventDecorat2[0], flush = _progressEventDecorat2[1]; + data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); + } + case 15: + if (!utils$1.isString(withCredentials)) { + withCredentials = withCredentials ? 'include' : 'omit'; + } + + // Cloudflare Workers throws when credentials are defined + // see https://github.com/cloudflare/workerd/issues/902 + isCredentialsSupported = "credentials" in Request.prototype; + request = new Request(url, _objectSpread2(_objectSpread2({}, fetchOptions), {}, { + signal: composedSignal, + method: method.toUpperCase(), + headers: headers.normalize().toJSON(), + body: data, + duplex: "half", + credentials: isCredentialsSupported ? withCredentials : undefined + })); + _context4.next = 20; + return fetch(request); + case 20: + response = _context4.sent; + isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); + if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) { + options = {}; + ['status', 'statusText', 'headers'].forEach(function (prop) { + options[prop] = response[prop]; + }); + responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length')); + _ref5 = onDownloadProgress && progressEventDecorator(responseContentLength, progressEventReducer(asyncDecorator(onDownloadProgress), true)) || [], _ref6 = _slicedToArray(_ref5, 2), _onProgress = _ref6[0], _flush = _ref6[1]; + response = new Response(trackStream(response.body, DEFAULT_CHUNK_SIZE, _onProgress, function () { + _flush && _flush(); + unsubscribe && unsubscribe(); + }), options); + } + responseType = responseType || 'text'; + _context4.next = 26; + return resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config); + case 26: + responseData = _context4.sent; + !isStreamResponse && unsubscribe && unsubscribe(); + _context4.next = 30; + return new Promise(function (resolve, reject) { + settle(resolve, reject, { + data: responseData, + headers: AxiosHeaders$1.from(response.headers), + status: response.status, + statusText: response.statusText, + config: config, + request: request + }); + }); + case 30: + return _context4.abrupt("return", _context4.sent); + case 33: + _context4.prev = 33; + _context4.t2 = _context4["catch"](4); + unsubscribe && unsubscribe(); + if (!(_context4.t2 && _context4.t2.name === 'TypeError' && /fetch/i.test(_context4.t2.message))) { + _context4.next = 38; + break; + } + throw Object.assign(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request), { + cause: _context4.t2.cause || _context4.t2 + }); + case 38: + throw AxiosError.from(_context4.t2, _context4.t2 && _context4.t2.code, config, request); + case 39: + case "end": + return _context4.stop(); + } + }, _callee4, null, [[4, 33]]); + })); + return function (_x5) { + return _ref4.apply(this, arguments); + }; + }()); + + var knownAdapters = { + http: httpAdapter, + xhr: xhrAdapter, + fetch: fetchAdapter + }; + utils$1.forEach(knownAdapters, function (fn, value) { + if (fn) { + try { + Object.defineProperty(fn, 'name', { + value: value + }); + } catch (e) { + // eslint-disable-next-line no-empty + } + Object.defineProperty(fn, 'adapterName', { + value: value + }); + } + }); + var renderReason = function renderReason(reason) { + return "- ".concat(reason); + }; + var isResolvedHandle = function isResolvedHandle(adapter) { + return utils$1.isFunction(adapter) || adapter === null || adapter === false; + }; + var adapters = { + getAdapter: function getAdapter(adapters) { + adapters = utils$1.isArray(adapters) ? adapters : [adapters]; + var _adapters = adapters, + length = _adapters.length; + var nameOrAdapter; + var adapter; + var rejectedReasons = {}; + for (var i = 0; i < length; i++) { + nameOrAdapter = adapters[i]; + var id = void 0; + adapter = nameOrAdapter; + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + if (adapter === undefined) { + throw new AxiosError("Unknown adapter '".concat(id, "'")); + } + } + if (adapter) { + break; + } + rejectedReasons[id || '#' + i] = adapter; + } + if (!adapter) { + var reasons = Object.entries(rejectedReasons).map(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + id = _ref2[0], + state = _ref2[1]; + return "adapter ".concat(id, " ") + (state === false ? 'is not supported by the environment' : 'is not available in the build'); + }); + var s = length ? reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0]) : 'as no adapter specified'; + throw new AxiosError("There is no suitable adapter to dispatch the request " + s, 'ERR_NOT_SUPPORT'); + } + return adapter; + }, + adapters: knownAdapters + }; + + /** + * Throws a `CanceledError` if cancellation has been requested. + * + * @param {Object} config The config that is to be used for the request + * + * @returns {void} + */ + function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + if (config.signal && config.signal.aborted) { + throw new CanceledError(null, config); + } + } + + /** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * + * @returns {Promise} The Promise to be fulfilled + */ + function dispatchRequest(config) { + throwIfCancellationRequested(config); + config.headers = AxiosHeaders$1.from(config.headers); + + // Transform request data + config.data = transformData.call(config, config.transformRequest); + if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { + config.headers.setContentType('application/x-www-form-urlencoded', false); + } + var adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData.call(config, config.transformResponse, response); + response.headers = AxiosHeaders$1.from(response.headers); + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call(config, config.transformResponse, reason.response); + reason.response.headers = AxiosHeaders$1.from(reason.response.headers); + } + } + return Promise.reject(reason); + }); + } + + var VERSION = "1.7.9"; + + var validators$1 = {}; + + // eslint-disable-next-line func-names + ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function (type, i) { + validators$1[type] = function validator(thing) { + return _typeof(thing) === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; + }); + var deprecatedWarnings = {}; + + /** + * Transitional option validator + * + * @param {function|boolean?} validator - set to false if the transitional option has been removed + * @param {string?} version - deprecated version / removed since version + * @param {string?} message - some message with additional info + * + * @returns {function} + */ + validators$1.transitional = function transitional(validator, version, message) { + function formatMessage(opt, desc) { + return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + } + + // eslint-disable-next-line func-names + return function (value, opt, opts) { + if (validator === false) { + throw new AxiosError(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), AxiosError.ERR_DEPRECATED); + } + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn(formatMessage(opt, ' has been deprecated since v' + version + ' and will be removed in the near future')); + } + return validator ? validator(value, opt, opts) : true; + }; + }; + validators$1.spelling = function spelling(correctSpelling) { + return function (value, opt) { + // eslint-disable-next-line no-console + console.warn("".concat(opt, " is likely a misspelling of ").concat(correctSpelling)); + return true; + }; + }; + + /** + * Assert object's properties type + * + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown + * + * @returns {object} + */ + + function assertOptions(options, schema, allowUnknown) { + if (_typeof(options) !== 'object') { + throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); + } + var keys = Object.keys(options); + var i = keys.length; + while (i-- > 0) { + var opt = keys[i]; + var validator = schema[opt]; + if (validator) { + var value = options[opt]; + var result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); + } + } + } + var validator = { + assertOptions: assertOptions, + validators: validators$1 + }; + + var validators = validator.validators; + + /** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + * + * @return {Axios} A new instance of Axios + */ + var Axios = /*#__PURE__*/function () { + function Axios(instanceConfig) { + _classCallCheck(this, Axios); + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager$1(), + response: new InterceptorManager$1() + }; + } + + /** + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled + */ + _createClass(Axios, [{ + key: "request", + value: (function () { + var _request2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(configOrUrl, config) { + var dummy, stack; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return this._request(configOrUrl, config); + case 3: + return _context.abrupt("return", _context.sent); + case 6: + _context.prev = 6; + _context.t0 = _context["catch"](0); + if (_context.t0 instanceof Error) { + dummy = {}; + Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error(); + + // slice off the Error: ... line + stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : ''; + try { + if (!_context.t0.stack) { + _context.t0.stack = stack; + // match without the 2 top stack lines + } else if (stack && !String(_context.t0.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) { + _context.t0.stack += '\n' + stack; + } + } catch (e) { + // ignore the case where "stack" is an un-writable property + } + } + throw _context.t0; + case 10: + case "end": + return _context.stop(); + } + }, _callee, this, [[0, 6]]); + })); + function request(_x, _x2) { + return _request2.apply(this, arguments); + } + return request; + }()) + }, { + key: "_request", + value: function _request(configOrUrl, config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof configOrUrl === 'string') { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } + config = mergeConfig(this.defaults, config); + var _config = config, + transitional = _config.transitional, + paramsSerializer = _config.paramsSerializer, + headers = _config.headers; + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators["boolean"]), + forcedJSONParsing: validators.transitional(validators["boolean"]), + clarifyTimeoutError: validators.transitional(validators["boolean"]) + }, false); + } + if (paramsSerializer != null) { + if (utils$1.isFunction(paramsSerializer)) { + config.paramsSerializer = { + serialize: paramsSerializer + }; + } else { + validator.assertOptions(paramsSerializer, { + encode: validators["function"], + serialize: validators["function"] + }, true); + } + } + validator.assertOptions(config, { + baseUrl: validators.spelling('baseURL'), + withXsrfToken: validators.spelling('withXSRFToken') + }, true); + + // Set config.method + config.method = (config.method || this.defaults.method || 'get').toLowerCase(); + + // Flatten headers + var contextHeaders = headers && utils$1.merge(headers.common, headers[config.method]); + headers && utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function (method) { + delete headers[method]; + }); + config.headers = AxiosHeaders$1.concat(contextHeaders, headers); + + // filter out skipped interceptors + var requestInterceptorChain = []; + var synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + var responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + var promise; + var i = 0; + var len; + if (!synchronousRequestInterceptors) { + var chain = [dispatchRequest.bind(this), undefined]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + promise = Promise.resolve(config); + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + return promise; + } + len = requestInterceptorChain.length; + var newConfig = config; + i = 0; + while (i < len) { + var onFulfilled = requestInterceptorChain[i++]; + var onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + i = 0; + len = responseInterceptorChain.length; + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + return promise; + } + }, { + key: "getUri", + value: function getUri(config) { + config = mergeConfig(this.defaults, config); + var fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); + } + }]); + return Axios; + }(); // Provide aliases for supported request methods + utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function (url, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: (config || {}).data + })); + }; + }); + utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig(config || {}, { + method: method, + headers: isForm ? { + 'Content-Type': 'multipart/form-data' + } : {}, + url: url, + data: data + })); + }; + } + Axios.prototype[method] = generateHTTPMethod(); + Axios.prototype[method + 'Form'] = generateHTTPMethod(true); + }); + var Axios$1 = Axios; + + /** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @param {Function} executor The executor function. + * + * @returns {CancelToken} + */ + var CancelToken = /*#__PURE__*/function () { + function CancelToken(executor) { + _classCallCheck(this, CancelToken); + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + var resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + var token = this; + + // eslint-disable-next-line func-names + this.promise.then(function (cancel) { + if (!token._listeners) return; + var i = token._listeners.length; + while (i-- > 0) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + + // eslint-disable-next-line func-names + this.promise.then = function (onfulfilled) { + var _resolve; + // eslint-disable-next-line func-names + var promise = new Promise(function (resolve) { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + return promise; + }; + executor(function cancel(message, config, request) { + if (token.reason) { + // Cancellation has already been requested + return; + } + token.reason = new CanceledError(message, config, request); + resolvePromise(token.reason); + }); + } + + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + _createClass(CancelToken, [{ + key: "throwIfRequested", + value: function throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } + + /** + * Subscribe to the cancel signal + */ + }, { + key: "subscribe", + value: function subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } + + /** + * Unsubscribe from the cancel signal + */ + }, { + key: "unsubscribe", + value: function unsubscribe(listener) { + if (!this._listeners) { + return; + } + var index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } + } + }, { + key: "toAbortSignal", + value: function toAbortSignal() { + var _this = this; + var controller = new AbortController(); + var abort = function abort(err) { + controller.abort(err); + }; + this.subscribe(abort); + controller.signal.unsubscribe = function () { + return _this.unsubscribe(abort); + }; + return controller.signal; + } + + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + }], [{ + key: "source", + value: function source() { + var cancel; + var token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token: token, + cancel: cancel + }; + } + }]); + return CancelToken; + }(); + var CancelToken$1 = CancelToken; + + /** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * + * @returns {Function} + */ + function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; + } + + /** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ + function isAxiosError(payload) { + return utils$1.isObject(payload) && payload.isAxiosError === true; + } + + var HttpStatusCode = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511 + }; + Object.entries(HttpStatusCode).forEach(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + HttpStatusCode[value] = key; + }); + var HttpStatusCode$1 = HttpStatusCode; + + /** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * + * @returns {Axios} A new instance of Axios + */ + function createInstance(defaultConfig) { + var context = new Axios$1(defaultConfig); + var instance = bind(Axios$1.prototype.request, context); + + // Copy axios.prototype to instance + utils$1.extend(instance, Axios$1.prototype, context, { + allOwnKeys: true + }); + + // Copy context to instance + utils$1.extend(instance, context, null, { + allOwnKeys: true + }); + + // Factory for creating new instances + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; + return instance; + } + + // Create the default instance to be exported + var axios = createInstance(defaults$1); + + // Expose Axios class to allow class inheritance + axios.Axios = Axios$1; + + // Expose Cancel & CancelToken + axios.CanceledError = CanceledError; + axios.CancelToken = CancelToken$1; + axios.isCancel = isCancel; + axios.VERSION = VERSION; + axios.toFormData = toFormData; + + // Expose AxiosError class + axios.AxiosError = AxiosError; + + // alias for CanceledError for backward compatibility + axios.Cancel = axios.CanceledError; + + // Expose all/spread + axios.all = function all(promises) { + return Promise.all(promises); + }; + axios.spread = spread; + + // Expose isAxiosError + axios.isAxiosError = isAxiosError; + + // Expose mergeConfig + axios.mergeConfig = mergeConfig; + axios.AxiosHeaders = AxiosHeaders$1; + axios.formToJSON = function (thing) { + return formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); + }; + axios.getAdapter = adapters.getAdapter; + axios.HttpStatusCode = HttpStatusCode$1; + axios["default"] = axios; + + return axios; + +})); +//# sourceMappingURL=axios.js.map diff --git a/node_modules/axios/dist/axios.js.map b/node_modules/axios/dist/axios.js.map new file mode 100644 index 000000000..be0fac8f1 --- /dev/null +++ b/node_modules/axios/dist/axios.js.map @@ -0,0 +1 @@ +{"version":3,"file":"axios.js","sources":["../lib/helpers/bind.js","../lib/utils.js","../lib/core/AxiosError.js","../lib/helpers/null.js","../lib/helpers/toFormData.js","../lib/helpers/AxiosURLSearchParams.js","../lib/helpers/buildURL.js","../lib/core/InterceptorManager.js","../lib/defaults/transitional.js","../lib/platform/browser/classes/URLSearchParams.js","../lib/platform/browser/classes/FormData.js","../lib/platform/browser/classes/Blob.js","../lib/platform/browser/index.js","../lib/platform/common/utils.js","../lib/platform/index.js","../lib/helpers/toURLEncodedForm.js","../lib/helpers/formDataToJSON.js","../lib/defaults/index.js","../lib/helpers/parseHeaders.js","../lib/core/AxiosHeaders.js","../lib/core/transformData.js","../lib/cancel/isCancel.js","../lib/cancel/CanceledError.js","../lib/core/settle.js","../lib/helpers/parseProtocol.js","../lib/helpers/speedometer.js","../lib/helpers/throttle.js","../lib/helpers/progressEventReducer.js","../lib/helpers/isURLSameOrigin.js","../lib/helpers/cookies.js","../lib/helpers/isAbsoluteURL.js","../lib/helpers/combineURLs.js","../lib/core/buildFullPath.js","../lib/core/mergeConfig.js","../lib/helpers/resolveConfig.js","../lib/adapters/xhr.js","../lib/helpers/composeSignals.js","../lib/helpers/trackStream.js","../lib/adapters/fetch.js","../lib/adapters/adapters.js","../lib/core/dispatchRequest.js","../lib/env/data.js","../lib/helpers/validator.js","../lib/core/Axios.js","../lib/cancel/CancelToken.js","../lib/helpers/spread.js","../lib/helpers/isAxiosError.js","../lib/helpers/HttpStatusCode.js","../lib/axios.js"],"sourcesContent":["'use strict';\n\nexport default function bind(fn, thisArg) {\n return function wrap() {\n return fn.apply(thisArg, arguments);\n };\n}\n","'use strict';\n\nimport bind from './helpers/bind.js';\n\n// utils is a library of generic helper functions non-specific to axios\n\nconst {toString} = Object.prototype;\nconst {getPrototypeOf} = Object;\n\nconst kindOf = (cache => thing => {\n const str = toString.call(thing);\n return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());\n})(Object.create(null));\n\nconst kindOfTest = (type) => {\n type = type.toLowerCase();\n return (thing) => kindOf(thing) === type\n}\n\nconst typeOfTest = type => thing => typeof thing === type;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n *\n * @returns {boolean} True if value is an Array, otherwise false\n */\nconst {isArray} = Array;\n\n/**\n * Determine if a value is undefined\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nconst isUndefined = typeOfTest('undefined');\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nconst isArrayBuffer = kindOfTest('ArrayBuffer');\n\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n let result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a String, otherwise false\n */\nconst isString = typeOfTest('string');\n\n/**\n * Determine if a value is a Function\n *\n * @param {*} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nconst isFunction = typeOfTest('function');\n\n/**\n * Determine if a value is a Number\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Number, otherwise false\n */\nconst isNumber = typeOfTest('number');\n\n/**\n * Determine if a value is an Object\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an Object, otherwise false\n */\nconst isObject = (thing) => thing !== null && typeof thing === 'object';\n\n/**\n * Determine if a value is a Boolean\n *\n * @param {*} thing The value to test\n * @returns {boolean} True if value is a Boolean, otherwise false\n */\nconst isBoolean = thing => thing === true || thing === false;\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a plain Object, otherwise false\n */\nconst isPlainObject = (val) => {\n if (kindOf(val) !== 'object') {\n return false;\n }\n\n const prototype = getPrototypeOf(val);\n return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Date, otherwise false\n */\nconst isDate = kindOfTest('Date');\n\n/**\n * Determine if a value is a File\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFile = kindOfTest('File');\n\n/**\n * Determine if a value is a Blob\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nconst isBlob = kindOfTest('Blob');\n\n/**\n * Determine if a value is a FileList\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFileList = kindOfTest('FileList');\n\n/**\n * Determine if a value is a Stream\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nconst isStream = (val) => isObject(val) && isFunction(val.pipe);\n\n/**\n * Determine if a value is a FormData\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nconst isFormData = (thing) => {\n let kind;\n return thing && (\n (typeof FormData === 'function' && thing instanceof FormData) || (\n isFunction(thing.append) && (\n (kind = kindOf(thing)) === 'formdata' ||\n // detect form-data instance\n (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')\n )\n )\n )\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nconst isURLSearchParams = kindOfTest('URLSearchParams');\n\nconst [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n *\n * @returns {String} The String freed of excess whitespace\n */\nconst trim = (str) => str.trim ?\n str.trim() : str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '');\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n *\n * @param {Boolean} [allOwnKeys = false]\n * @returns {any}\n */\nfunction forEach(obj, fn, {allOwnKeys = false} = {}) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n let i;\n let l;\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);\n const len = keys.length;\n let key;\n\n for (i = 0; i < len; i++) {\n key = keys[i];\n fn.call(null, obj[key], key, obj);\n }\n }\n}\n\nfunction findKey(obj, key) {\n key = key.toLowerCase();\n const keys = Object.keys(obj);\n let i = keys.length;\n let _key;\n while (i-- > 0) {\n _key = keys[i];\n if (key === _key.toLowerCase()) {\n return _key;\n }\n }\n return null;\n}\n\nconst _global = (() => {\n /*eslint no-undef:0*/\n if (typeof globalThis !== \"undefined\") return globalThis;\n return typeof self !== \"undefined\" ? self : (typeof window !== 'undefined' ? window : global)\n})();\n\nconst isContextDefined = (context) => !isUndefined(context) && context !== _global;\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n *\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n const {caseless} = isContextDefined(this) && this || {};\n const result = {};\n const assignValue = (val, key) => {\n const targetKey = caseless && findKey(result, key) || key;\n if (isPlainObject(result[targetKey]) && isPlainObject(val)) {\n result[targetKey] = merge(result[targetKey], val);\n } else if (isPlainObject(val)) {\n result[targetKey] = merge({}, val);\n } else if (isArray(val)) {\n result[targetKey] = val.slice();\n } else {\n result[targetKey] = val;\n }\n }\n\n for (let i = 0, l = arguments.length; i < l; i++) {\n arguments[i] && forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n *\n * @param {Boolean} [allOwnKeys]\n * @returns {Object} The resulting value of object a\n */\nconst extend = (a, b, thisArg, {allOwnKeys}= {}) => {\n forEach(b, (val, key) => {\n if (thisArg && isFunction(val)) {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n }, {allOwnKeys});\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n *\n * @returns {string} content value without BOM\n */\nconst stripBOM = (content) => {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\n/**\n * Inherit the prototype methods from one constructor into another\n * @param {function} constructor\n * @param {function} superConstructor\n * @param {object} [props]\n * @param {object} [descriptors]\n *\n * @returns {void}\n */\nconst inherits = (constructor, superConstructor, props, descriptors) => {\n constructor.prototype = Object.create(superConstructor.prototype, descriptors);\n constructor.prototype.constructor = constructor;\n Object.defineProperty(constructor, 'super', {\n value: superConstructor.prototype\n });\n props && Object.assign(constructor.prototype, props);\n}\n\n/**\n * Resolve object with deep prototype chain to a flat object\n * @param {Object} sourceObj source object\n * @param {Object} [destObj]\n * @param {Function|Boolean} [filter]\n * @param {Function} [propFilter]\n *\n * @returns {Object}\n */\nconst toFlatObject = (sourceObj, destObj, filter, propFilter) => {\n let props;\n let i;\n let prop;\n const merged = {};\n\n destObj = destObj || {};\n // eslint-disable-next-line no-eq-null,eqeqeq\n if (sourceObj == null) return destObj;\n\n do {\n props = Object.getOwnPropertyNames(sourceObj);\n i = props.length;\n while (i-- > 0) {\n prop = props[i];\n if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {\n destObj[prop] = sourceObj[prop];\n merged[prop] = true;\n }\n }\n sourceObj = filter !== false && getPrototypeOf(sourceObj);\n } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);\n\n return destObj;\n}\n\n/**\n * Determines whether a string ends with the characters of a specified string\n *\n * @param {String} str\n * @param {String} searchString\n * @param {Number} [position= 0]\n *\n * @returns {boolean}\n */\nconst endsWith = (str, searchString, position) => {\n str = String(str);\n if (position === undefined || position > str.length) {\n position = str.length;\n }\n position -= searchString.length;\n const lastIndex = str.indexOf(searchString, position);\n return lastIndex !== -1 && lastIndex === position;\n}\n\n\n/**\n * Returns new array from array like object or null if failed\n *\n * @param {*} [thing]\n *\n * @returns {?Array}\n */\nconst toArray = (thing) => {\n if (!thing) return null;\n if (isArray(thing)) return thing;\n let i = thing.length;\n if (!isNumber(i)) return null;\n const arr = new Array(i);\n while (i-- > 0) {\n arr[i] = thing[i];\n }\n return arr;\n}\n\n/**\n * Checking if the Uint8Array exists and if it does, it returns a function that checks if the\n * thing passed in is an instance of Uint8Array\n *\n * @param {TypedArray}\n *\n * @returns {Array}\n */\n// eslint-disable-next-line func-names\nconst isTypedArray = (TypedArray => {\n // eslint-disable-next-line func-names\n return thing => {\n return TypedArray && thing instanceof TypedArray;\n };\n})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));\n\n/**\n * For each entry in the object, call the function with the key and value.\n *\n * @param {Object} obj - The object to iterate over.\n * @param {Function} fn - The function to call for each entry.\n *\n * @returns {void}\n */\nconst forEachEntry = (obj, fn) => {\n const generator = obj && obj[Symbol.iterator];\n\n const iterator = generator.call(obj);\n\n let result;\n\n while ((result = iterator.next()) && !result.done) {\n const pair = result.value;\n fn.call(obj, pair[0], pair[1]);\n }\n}\n\n/**\n * It takes a regular expression and a string, and returns an array of all the matches\n *\n * @param {string} regExp - The regular expression to match against.\n * @param {string} str - The string to search.\n *\n * @returns {Array}\n */\nconst matchAll = (regExp, str) => {\n let matches;\n const arr = [];\n\n while ((matches = regExp.exec(str)) !== null) {\n arr.push(matches);\n }\n\n return arr;\n}\n\n/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */\nconst isHTMLForm = kindOfTest('HTMLFormElement');\n\nconst toCamelCase = str => {\n return str.toLowerCase().replace(/[-_\\s]([a-z\\d])(\\w*)/g,\n function replacer(m, p1, p2) {\n return p1.toUpperCase() + p2;\n }\n );\n};\n\n/* Creating a function that will check if an object has a property. */\nconst hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);\n\n/**\n * Determine if a value is a RegExp object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a RegExp object, otherwise false\n */\nconst isRegExp = kindOfTest('RegExp');\n\nconst reduceDescriptors = (obj, reducer) => {\n const descriptors = Object.getOwnPropertyDescriptors(obj);\n const reducedDescriptors = {};\n\n forEach(descriptors, (descriptor, name) => {\n let ret;\n if ((ret = reducer(descriptor, name, obj)) !== false) {\n reducedDescriptors[name] = ret || descriptor;\n }\n });\n\n Object.defineProperties(obj, reducedDescriptors);\n}\n\n/**\n * Makes all methods read-only\n * @param {Object} obj\n */\n\nconst freezeMethods = (obj) => {\n reduceDescriptors(obj, (descriptor, name) => {\n // skip restricted props in strict mode\n if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {\n return false;\n }\n\n const value = obj[name];\n\n if (!isFunction(value)) return;\n\n descriptor.enumerable = false;\n\n if ('writable' in descriptor) {\n descriptor.writable = false;\n return;\n }\n\n if (!descriptor.set) {\n descriptor.set = () => {\n throw Error('Can not rewrite read-only method \\'' + name + '\\'');\n };\n }\n });\n}\n\nconst toObjectSet = (arrayOrString, delimiter) => {\n const obj = {};\n\n const define = (arr) => {\n arr.forEach(value => {\n obj[value] = true;\n });\n }\n\n isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));\n\n return obj;\n}\n\nconst noop = () => {}\n\nconst toFiniteNumber = (value, defaultValue) => {\n return value != null && Number.isFinite(value = +value) ? value : defaultValue;\n}\n\nconst ALPHA = 'abcdefghijklmnopqrstuvwxyz'\n\nconst DIGIT = '0123456789';\n\nconst ALPHABET = {\n DIGIT,\n ALPHA,\n ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT\n}\n\nconst generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {\n let str = '';\n const {length} = alphabet;\n while (size--) {\n str += alphabet[Math.random() * length|0]\n }\n\n return str;\n}\n\n/**\n * If the thing is a FormData object, return true, otherwise return false.\n *\n * @param {unknown} thing - The thing to check.\n *\n * @returns {boolean}\n */\nfunction isSpecCompliantForm(thing) {\n return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);\n}\n\nconst toJSONObject = (obj) => {\n const stack = new Array(10);\n\n const visit = (source, i) => {\n\n if (isObject(source)) {\n if (stack.indexOf(source) >= 0) {\n return;\n }\n\n if(!('toJSON' in source)) {\n stack[i] = source;\n const target = isArray(source) ? [] : {};\n\n forEach(source, (value, key) => {\n const reducedValue = visit(value, i + 1);\n !isUndefined(reducedValue) && (target[key] = reducedValue);\n });\n\n stack[i] = undefined;\n\n return target;\n }\n }\n\n return source;\n }\n\n return visit(obj, 0);\n}\n\nconst isAsyncFn = kindOfTest('AsyncFunction');\n\nconst isThenable = (thing) =>\n thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);\n\n// original code\n// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34\n\nconst _setImmediate = ((setImmediateSupported, postMessageSupported) => {\n if (setImmediateSupported) {\n return setImmediate;\n }\n\n return postMessageSupported ? ((token, callbacks) => {\n _global.addEventListener(\"message\", ({source, data}) => {\n if (source === _global && data === token) {\n callbacks.length && callbacks.shift()();\n }\n }, false);\n\n return (cb) => {\n callbacks.push(cb);\n _global.postMessage(token, \"*\");\n }\n })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);\n})(\n typeof setImmediate === 'function',\n isFunction(_global.postMessage)\n);\n\nconst asap = typeof queueMicrotask !== 'undefined' ?\n queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);\n\n// *********************\n\nexport default {\n isArray,\n isArrayBuffer,\n isBuffer,\n isFormData,\n isArrayBufferView,\n isString,\n isNumber,\n isBoolean,\n isObject,\n isPlainObject,\n isReadableStream,\n isRequest,\n isResponse,\n isHeaders,\n isUndefined,\n isDate,\n isFile,\n isBlob,\n isRegExp,\n isFunction,\n isStream,\n isURLSearchParams,\n isTypedArray,\n isFileList,\n forEach,\n merge,\n extend,\n trim,\n stripBOM,\n inherits,\n toFlatObject,\n kindOf,\n kindOfTest,\n endsWith,\n toArray,\n forEachEntry,\n matchAll,\n isHTMLForm,\n hasOwnProperty,\n hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection\n reduceDescriptors,\n freezeMethods,\n toObjectSet,\n toCamelCase,\n noop,\n toFiniteNumber,\n findKey,\n global: _global,\n isContextDefined,\n ALPHABET,\n generateString,\n isSpecCompliantForm,\n toJSONObject,\n isAsyncFn,\n isThenable,\n setImmediate: _setImmediate,\n asap\n};\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [config] The config.\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n *\n * @returns {Error} The created error.\n */\nfunction AxiosError(message, code, config, request, response) {\n Error.call(this);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error()).stack;\n }\n\n this.message = message;\n this.name = 'AxiosError';\n code && (this.code = code);\n config && (this.config = config);\n request && (this.request = request);\n if (response) {\n this.response = response;\n this.status = response.status ? response.status : null;\n }\n}\n\nutils.inherits(AxiosError, Error, {\n toJSON: function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: utils.toJSONObject(this.config),\n code: this.code,\n status: this.status\n };\n }\n});\n\nconst prototype = AxiosError.prototype;\nconst descriptors = {};\n\n[\n 'ERR_BAD_OPTION_VALUE',\n 'ERR_BAD_OPTION',\n 'ECONNABORTED',\n 'ETIMEDOUT',\n 'ERR_NETWORK',\n 'ERR_FR_TOO_MANY_REDIRECTS',\n 'ERR_DEPRECATED',\n 'ERR_BAD_RESPONSE',\n 'ERR_BAD_REQUEST',\n 'ERR_CANCELED',\n 'ERR_NOT_SUPPORT',\n 'ERR_INVALID_URL'\n// eslint-disable-next-line func-names\n].forEach(code => {\n descriptors[code] = {value: code};\n});\n\nObject.defineProperties(AxiosError, descriptors);\nObject.defineProperty(prototype, 'isAxiosError', {value: true});\n\n// eslint-disable-next-line func-names\nAxiosError.from = (error, code, config, request, response, customProps) => {\n const axiosError = Object.create(prototype);\n\n utils.toFlatObject(error, axiosError, function filter(obj) {\n return obj !== Error.prototype;\n }, prop => {\n return prop !== 'isAxiosError';\n });\n\n AxiosError.call(axiosError, error.message, code, config, request, response);\n\n axiosError.cause = error;\n\n axiosError.name = error.name;\n\n customProps && Object.assign(axiosError, customProps);\n\n return axiosError;\n};\n\nexport default AxiosError;\n","// eslint-disable-next-line strict\nexport default null;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\n// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored\nimport PlatformFormData from '../platform/node/classes/FormData.js';\n\n/**\n * Determines if the given thing is a array or js object.\n *\n * @param {string} thing - The object or array to be visited.\n *\n * @returns {boolean}\n */\nfunction isVisitable(thing) {\n return utils.isPlainObject(thing) || utils.isArray(thing);\n}\n\n/**\n * It removes the brackets from the end of a string\n *\n * @param {string} key - The key of the parameter.\n *\n * @returns {string} the key without the brackets.\n */\nfunction removeBrackets(key) {\n return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;\n}\n\n/**\n * It takes a path, a key, and a boolean, and returns a string\n *\n * @param {string} path - The path to the current key.\n * @param {string} key - The key of the current object being iterated over.\n * @param {string} dots - If true, the key will be rendered with dots instead of brackets.\n *\n * @returns {string} The path to the current key.\n */\nfunction renderKey(path, key, dots) {\n if (!path) return key;\n return path.concat(key).map(function each(token, i) {\n // eslint-disable-next-line no-param-reassign\n token = removeBrackets(token);\n return !dots && i ? '[' + token + ']' : token;\n }).join(dots ? '.' : '');\n}\n\n/**\n * If the array is an array and none of its elements are visitable, then it's a flat array.\n *\n * @param {Array} arr - The array to check\n *\n * @returns {boolean}\n */\nfunction isFlatArray(arr) {\n return utils.isArray(arr) && !arr.some(isVisitable);\n}\n\nconst predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {\n return /^is[A-Z]/.test(prop);\n});\n\n/**\n * Convert a data object to FormData\n *\n * @param {Object} obj\n * @param {?Object} [formData]\n * @param {?Object} [options]\n * @param {Function} [options.visitor]\n * @param {Boolean} [options.metaTokens = true]\n * @param {Boolean} [options.dots = false]\n * @param {?Boolean} [options.indexes = false]\n *\n * @returns {Object}\n **/\n\n/**\n * It converts an object into a FormData object\n *\n * @param {Object} obj - The object to convert to form data.\n * @param {string} formData - The FormData object to append to.\n * @param {Object} options\n *\n * @returns\n */\nfunction toFormData(obj, formData, options) {\n if (!utils.isObject(obj)) {\n throw new TypeError('target must be an object');\n }\n\n // eslint-disable-next-line no-param-reassign\n formData = formData || new (PlatformFormData || FormData)();\n\n // eslint-disable-next-line no-param-reassign\n options = utils.toFlatObject(options, {\n metaTokens: true,\n dots: false,\n indexes: false\n }, false, function defined(option, source) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n return !utils.isUndefined(source[option]);\n });\n\n const metaTokens = options.metaTokens;\n // eslint-disable-next-line no-use-before-define\n const visitor = options.visitor || defaultVisitor;\n const dots = options.dots;\n const indexes = options.indexes;\n const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;\n const useBlob = _Blob && utils.isSpecCompliantForm(formData);\n\n if (!utils.isFunction(visitor)) {\n throw new TypeError('visitor must be a function');\n }\n\n function convertValue(value) {\n if (value === null) return '';\n\n if (utils.isDate(value)) {\n return value.toISOString();\n }\n\n if (!useBlob && utils.isBlob(value)) {\n throw new AxiosError('Blob is not supported. Use a Buffer instead.');\n }\n\n if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {\n return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);\n }\n\n return value;\n }\n\n /**\n * Default visitor.\n *\n * @param {*} value\n * @param {String|Number} key\n * @param {Array} path\n * @this {FormData}\n *\n * @returns {boolean} return true to visit the each prop of the value recursively\n */\n function defaultVisitor(value, key, path) {\n let arr = value;\n\n if (value && !path && typeof value === 'object') {\n if (utils.endsWith(key, '{}')) {\n // eslint-disable-next-line no-param-reassign\n key = metaTokens ? key : key.slice(0, -2);\n // eslint-disable-next-line no-param-reassign\n value = JSON.stringify(value);\n } else if (\n (utils.isArray(value) && isFlatArray(value)) ||\n ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))\n )) {\n // eslint-disable-next-line no-param-reassign\n key = removeBrackets(key);\n\n arr.forEach(function each(el, index) {\n !(utils.isUndefined(el) || el === null) && formData.append(\n // eslint-disable-next-line no-nested-ternary\n indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),\n convertValue(el)\n );\n });\n return false;\n }\n }\n\n if (isVisitable(value)) {\n return true;\n }\n\n formData.append(renderKey(path, key, dots), convertValue(value));\n\n return false;\n }\n\n const stack = [];\n\n const exposedHelpers = Object.assign(predicates, {\n defaultVisitor,\n convertValue,\n isVisitable\n });\n\n function build(value, path) {\n if (utils.isUndefined(value)) return;\n\n if (stack.indexOf(value) !== -1) {\n throw Error('Circular reference detected in ' + path.join('.'));\n }\n\n stack.push(value);\n\n utils.forEach(value, function each(el, key) {\n const result = !(utils.isUndefined(el) || el === null) && visitor.call(\n formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers\n );\n\n if (result === true) {\n build(el, path ? path.concat(key) : [key]);\n }\n });\n\n stack.pop();\n }\n\n if (!utils.isObject(obj)) {\n throw new TypeError('data must be an object');\n }\n\n build(obj);\n\n return formData;\n}\n\nexport default toFormData;\n","'use strict';\n\nimport toFormData from './toFormData.js';\n\n/**\n * It encodes a string by replacing all characters that are not in the unreserved set with\n * their percent-encoded equivalents\n *\n * @param {string} str - The string to encode.\n *\n * @returns {string} The encoded string.\n */\nfunction encode(str) {\n const charMap = {\n '!': '%21',\n \"'\": '%27',\n '(': '%28',\n ')': '%29',\n '~': '%7E',\n '%20': '+',\n '%00': '\\x00'\n };\n return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {\n return charMap[match];\n });\n}\n\n/**\n * It takes a params object and converts it to a FormData object\n *\n * @param {Object} params - The parameters to be converted to a FormData object.\n * @param {Object} options - The options object passed to the Axios constructor.\n *\n * @returns {void}\n */\nfunction AxiosURLSearchParams(params, options) {\n this._pairs = [];\n\n params && toFormData(params, this, options);\n}\n\nconst prototype = AxiosURLSearchParams.prototype;\n\nprototype.append = function append(name, value) {\n this._pairs.push([name, value]);\n};\n\nprototype.toString = function toString(encoder) {\n const _encode = encoder ? function(value) {\n return encoder.call(this, value, encode);\n } : encode;\n\n return this._pairs.map(function each(pair) {\n return _encode(pair[0]) + '=' + _encode(pair[1]);\n }, '').join('&');\n};\n\nexport default AxiosURLSearchParams;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';\n\n/**\n * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their\n * URI encoded counterparts\n *\n * @param {string} val The value to be encoded.\n *\n * @returns {string} The encoded value.\n */\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @param {?(object|Function)} options\n *\n * @returns {string} The formatted url\n */\nexport default function buildURL(url, params, options) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n \n const _encode = options && options.encode || encode;\n\n if (utils.isFunction(options)) {\n options = {\n serialize: options\n };\n } \n\n const serializeFn = options && options.serialize;\n\n let serializedParams;\n\n if (serializeFn) {\n serializedParams = serializeFn(params, options);\n } else {\n serializedParams = utils.isURLSearchParams(params) ?\n params.toString() :\n new AxiosURLSearchParams(params, options).toString(_encode);\n }\n\n if (serializedParams) {\n const hashmarkIndex = url.indexOf(\"#\");\n\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\nclass InterceptorManager {\n constructor() {\n this.handlers = [];\n }\n\n /**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\n use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled,\n rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n }\n\n /**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n *\n * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise\n */\n eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n }\n\n /**\n * Clear all interceptors from the stack\n *\n * @returns {void}\n */\n clear() {\n if (this.handlers) {\n this.handlers = [];\n }\n }\n\n /**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n *\n * @returns {void}\n */\n forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n }\n}\n\nexport default InterceptorManager;\n","'use strict';\n\nexport default {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n};\n","'use strict';\n\nimport AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';\nexport default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;\n","'use strict';\n\nexport default typeof FormData !== 'undefined' ? FormData : null;\n","'use strict'\n\nexport default typeof Blob !== 'undefined' ? Blob : null\n","import URLSearchParams from './classes/URLSearchParams.js'\nimport FormData from './classes/FormData.js'\nimport Blob from './classes/Blob.js'\n\nexport default {\n isBrowser: true,\n classes: {\n URLSearchParams,\n FormData,\n Blob\n },\n protocols: ['http', 'https', 'file', 'blob', 'url', 'data']\n};\n","const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';\n\nconst _navigator = typeof navigator === 'object' && navigator || undefined;\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n *\n * @returns {boolean}\n */\nconst hasStandardBrowserEnv = hasBrowserEnv &&\n (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);\n\n/**\n * Determine if we're running in a standard browser webWorker environment\n *\n * Although the `isStandardBrowserEnv` method indicates that\n * `allows axios to run in a web worker`, the WebWorker will still be\n * filtered out due to its judgment standard\n * `typeof window !== 'undefined' && typeof document !== 'undefined'`.\n * This leads to a problem when axios post `FormData` in webWorker\n */\nconst hasStandardBrowserWebWorkerEnv = (() => {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n // eslint-disable-next-line no-undef\n self instanceof WorkerGlobalScope &&\n typeof self.importScripts === 'function'\n );\n})();\n\nconst origin = hasBrowserEnv && window.location.href || 'http://localhost';\n\nexport {\n hasBrowserEnv,\n hasStandardBrowserWebWorkerEnv,\n hasStandardBrowserEnv,\n _navigator as navigator,\n origin\n}\n","import platform from './node/index.js';\nimport * as utils from './common/utils.js';\n\nexport default {\n ...utils,\n ...platform\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport toFormData from './toFormData.js';\nimport platform from '../platform/index.js';\n\nexport default function toURLEncodedForm(data, options) {\n return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({\n visitor: function(value, key, path, helpers) {\n if (platform.isNode && utils.isBuffer(value)) {\n this.append(key, value.toString('base64'));\n return false;\n }\n\n return helpers.defaultVisitor.apply(this, arguments);\n }\n }, options));\n}\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']\n *\n * @param {string} name - The name of the property to get.\n *\n * @returns An array of strings.\n */\nfunction parsePropPath(name) {\n // foo[x][y][z]\n // foo.x.y.z\n // foo-x-y-z\n // foo x y z\n return utils.matchAll(/\\w+|\\[(\\w*)]/g, name).map(match => {\n return match[0] === '[]' ? '' : match[1] || match[0];\n });\n}\n\n/**\n * Convert an array to an object.\n *\n * @param {Array} arr - The array to convert to an object.\n *\n * @returns An object with the same keys and values as the array.\n */\nfunction arrayToObject(arr) {\n const obj = {};\n const keys = Object.keys(arr);\n let i;\n const len = keys.length;\n let key;\n for (i = 0; i < len; i++) {\n key = keys[i];\n obj[key] = arr[key];\n }\n return obj;\n}\n\n/**\n * It takes a FormData object and returns a JavaScript object\n *\n * @param {string} formData The FormData object to convert to JSON.\n *\n * @returns {Object | null} The converted object.\n */\nfunction formDataToJSON(formData) {\n function buildPath(path, value, target, index) {\n let name = path[index++];\n\n if (name === '__proto__') return true;\n\n const isNumericKey = Number.isFinite(+name);\n const isLast = index >= path.length;\n name = !name && utils.isArray(target) ? target.length : name;\n\n if (isLast) {\n if (utils.hasOwnProp(target, name)) {\n target[name] = [target[name], value];\n } else {\n target[name] = value;\n }\n\n return !isNumericKey;\n }\n\n if (!target[name] || !utils.isObject(target[name])) {\n target[name] = [];\n }\n\n const result = buildPath(path, value, target[name], index);\n\n if (result && utils.isArray(target[name])) {\n target[name] = arrayToObject(target[name]);\n }\n\n return !isNumericKey;\n }\n\n if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {\n const obj = {};\n\n utils.forEachEntry(formData, (name, value) => {\n buildPath(parsePropPath(name), value, obj, 0);\n });\n\n return obj;\n }\n\n return null;\n}\n\nexport default formDataToJSON;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\nimport transitionalDefaults from './transitional.js';\nimport toFormData from '../helpers/toFormData.js';\nimport toURLEncodedForm from '../helpers/toURLEncodedForm.js';\nimport platform from '../platform/index.js';\nimport formDataToJSON from '../helpers/formDataToJSON.js';\n\n/**\n * It takes a string, tries to parse it, and if it fails, it returns the stringified version\n * of the input\n *\n * @param {any} rawValue - The value to be stringified.\n * @param {Function} parser - A function that parses a string into a JavaScript object.\n * @param {Function} encoder - A function that takes a value and returns a string.\n *\n * @returns {string} A stringified version of the rawValue.\n */\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nconst defaults = {\n\n transitional: transitionalDefaults,\n\n adapter: ['xhr', 'http', 'fetch'],\n\n transformRequest: [function transformRequest(data, headers) {\n const contentType = headers.getContentType() || '';\n const hasJSONContentType = contentType.indexOf('application/json') > -1;\n const isObjectPayload = utils.isObject(data);\n\n if (isObjectPayload && utils.isHTMLForm(data)) {\n data = new FormData(data);\n }\n\n const isFormData = utils.isFormData(data);\n\n if (isFormData) {\n return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;\n }\n\n if (utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data) ||\n utils.isReadableStream(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);\n return data.toString();\n }\n\n let isFileList;\n\n if (isObjectPayload) {\n if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {\n return toURLEncodedForm(data, this.formSerializer).toString();\n }\n\n if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {\n const _FormData = this.env && this.env.FormData;\n\n return toFormData(\n isFileList ? {'files[]': data} : data,\n _FormData && new _FormData(),\n this.formSerializer\n );\n }\n }\n\n if (isObjectPayload || hasJSONContentType ) {\n headers.setContentType('application/json', false);\n return stringifySafely(data);\n }\n\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n const transitional = this.transitional || defaults.transitional;\n const forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n const JSONRequested = this.responseType === 'json';\n\n if (utils.isResponse(data) || utils.isReadableStream(data)) {\n return data;\n }\n\n if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {\n const silentJSONParsing = transitional && transitional.silentJSONParsing;\n const strictJSONParsing = !silentJSONParsing && JSONRequested;\n\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n env: {\n FormData: platform.classes.FormData,\n Blob: platform.classes.Blob\n },\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*',\n 'Content-Type': undefined\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {\n defaults.headers[method] = {};\n});\n\nexport default defaults;\n","'use strict';\n\nimport utils from './../utils.js';\n\n// RawAxiosHeaders whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nconst ignoreDuplicateOf = utils.toObjectSet([\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n]);\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} rawHeaders Headers needing to be parsed\n *\n * @returns {Object} Headers parsed into an object\n */\nexport default rawHeaders => {\n const parsed = {};\n let key;\n let val;\n let i;\n\n rawHeaders && rawHeaders.split('\\n').forEach(function parser(line) {\n i = line.indexOf(':');\n key = line.substring(0, i).trim().toLowerCase();\n val = line.substring(i + 1).trim();\n\n if (!key || (parsed[key] && ignoreDuplicateOf[key])) {\n return;\n }\n\n if (key === 'set-cookie') {\n if (parsed[key]) {\n parsed[key].push(val);\n } else {\n parsed[key] = [val];\n }\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n });\n\n return parsed;\n};\n","'use strict';\n\nimport utils from '../utils.js';\nimport parseHeaders from '../helpers/parseHeaders.js';\n\nconst $internals = Symbol('internals');\n\nfunction normalizeHeader(header) {\n return header && String(header).trim().toLowerCase();\n}\n\nfunction normalizeValue(value) {\n if (value === false || value == null) {\n return value;\n }\n\n return utils.isArray(value) ? value.map(normalizeValue) : String(value);\n}\n\nfunction parseTokens(str) {\n const tokens = Object.create(null);\n const tokensRE = /([^\\s,;=]+)\\s*(?:=\\s*([^,;]+))?/g;\n let match;\n\n while ((match = tokensRE.exec(str))) {\n tokens[match[1]] = match[2];\n }\n\n return tokens;\n}\n\nconst isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());\n\nfunction matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {\n if (utils.isFunction(filter)) {\n return filter.call(this, value, header);\n }\n\n if (isHeaderNameFilter) {\n value = header;\n }\n\n if (!utils.isString(value)) return;\n\n if (utils.isString(filter)) {\n return value.indexOf(filter) !== -1;\n }\n\n if (utils.isRegExp(filter)) {\n return filter.test(value);\n }\n}\n\nfunction formatHeader(header) {\n return header.trim()\n .toLowerCase().replace(/([a-z\\d])(\\w*)/g, (w, char, str) => {\n return char.toUpperCase() + str;\n });\n}\n\nfunction buildAccessors(obj, header) {\n const accessorName = utils.toCamelCase(' ' + header);\n\n ['get', 'set', 'has'].forEach(methodName => {\n Object.defineProperty(obj, methodName + accessorName, {\n value: function(arg1, arg2, arg3) {\n return this[methodName].call(this, header, arg1, arg2, arg3);\n },\n configurable: true\n });\n });\n}\n\nclass AxiosHeaders {\n constructor(headers) {\n headers && this.set(headers);\n }\n\n set(header, valueOrRewrite, rewrite) {\n const self = this;\n\n function setHeader(_value, _header, _rewrite) {\n const lHeader = normalizeHeader(_header);\n\n if (!lHeader) {\n throw new Error('header name must be a non-empty string');\n }\n\n const key = utils.findKey(self, lHeader);\n\n if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {\n self[key || _header] = normalizeValue(_value);\n }\n }\n\n const setHeaders = (headers, _rewrite) =>\n utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));\n\n if (utils.isPlainObject(header) || header instanceof this.constructor) {\n setHeaders(header, valueOrRewrite)\n } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {\n setHeaders(parseHeaders(header), valueOrRewrite);\n } else if (utils.isHeaders(header)) {\n for (const [key, value] of header.entries()) {\n setHeader(value, key, rewrite);\n }\n } else {\n header != null && setHeader(valueOrRewrite, header, rewrite);\n }\n\n return this;\n }\n\n get(header, parser) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n if (key) {\n const value = this[key];\n\n if (!parser) {\n return value;\n }\n\n if (parser === true) {\n return parseTokens(value);\n }\n\n if (utils.isFunction(parser)) {\n return parser.call(this, value, key);\n }\n\n if (utils.isRegExp(parser)) {\n return parser.exec(value);\n }\n\n throw new TypeError('parser must be boolean|regexp|function');\n }\n }\n }\n\n has(header, matcher) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));\n }\n\n return false;\n }\n\n delete(header, matcher) {\n const self = this;\n let deleted = false;\n\n function deleteHeader(_header) {\n _header = normalizeHeader(_header);\n\n if (_header) {\n const key = utils.findKey(self, _header);\n\n if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {\n delete self[key];\n\n deleted = true;\n }\n }\n }\n\n if (utils.isArray(header)) {\n header.forEach(deleteHeader);\n } else {\n deleteHeader(header);\n }\n\n return deleted;\n }\n\n clear(matcher) {\n const keys = Object.keys(this);\n let i = keys.length;\n let deleted = false;\n\n while (i--) {\n const key = keys[i];\n if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {\n delete this[key];\n deleted = true;\n }\n }\n\n return deleted;\n }\n\n normalize(format) {\n const self = this;\n const headers = {};\n\n utils.forEach(this, (value, header) => {\n const key = utils.findKey(headers, header);\n\n if (key) {\n self[key] = normalizeValue(value);\n delete self[header];\n return;\n }\n\n const normalized = format ? formatHeader(header) : String(header).trim();\n\n if (normalized !== header) {\n delete self[header];\n }\n\n self[normalized] = normalizeValue(value);\n\n headers[normalized] = true;\n });\n\n return this;\n }\n\n concat(...targets) {\n return this.constructor.concat(this, ...targets);\n }\n\n toJSON(asStrings) {\n const obj = Object.create(null);\n\n utils.forEach(this, (value, header) => {\n value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);\n });\n\n return obj;\n }\n\n [Symbol.iterator]() {\n return Object.entries(this.toJSON())[Symbol.iterator]();\n }\n\n toString() {\n return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\\n');\n }\n\n get [Symbol.toStringTag]() {\n return 'AxiosHeaders';\n }\n\n static from(thing) {\n return thing instanceof this ? thing : new this(thing);\n }\n\n static concat(first, ...targets) {\n const computed = new this(first);\n\n targets.forEach((target) => computed.set(target));\n\n return computed;\n }\n\n static accessor(header) {\n const internals = this[$internals] = (this[$internals] = {\n accessors: {}\n });\n\n const accessors = internals.accessors;\n const prototype = this.prototype;\n\n function defineAccessor(_header) {\n const lHeader = normalizeHeader(_header);\n\n if (!accessors[lHeader]) {\n buildAccessors(prototype, _header);\n accessors[lHeader] = true;\n }\n }\n\n utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);\n\n return this;\n }\n}\n\nAxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);\n\n// reserved names hotfix\nutils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {\n let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`\n return {\n get: () => value,\n set(headerValue) {\n this[mapped] = headerValue;\n }\n }\n});\n\nutils.freezeMethods(AxiosHeaders);\n\nexport default AxiosHeaders;\n","'use strict';\n\nimport utils from './../utils.js';\nimport defaults from '../defaults/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Array|Function} fns A single function or Array of functions\n * @param {?Object} response The response object\n *\n * @returns {*} The resulting transformed data\n */\nexport default function transformData(fns, response) {\n const config = this || defaults;\n const context = response || config;\n const headers = AxiosHeaders.from(context.headers);\n let data = context.data;\n\n utils.forEach(fns, function transform(fn) {\n data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);\n });\n\n headers.normalize();\n\n return data;\n}\n","'use strict';\n\nexport default function isCancel(value) {\n return !!(value && value.__CANCEL__);\n}\n","'use strict';\n\nimport AxiosError from '../core/AxiosError.js';\nimport utils from '../utils.js';\n\n/**\n * A `CanceledError` is an object that is thrown when an operation is canceled.\n *\n * @param {string=} message The message.\n * @param {Object=} config The config.\n * @param {Object=} request The request.\n *\n * @returns {CanceledError} The created error.\n */\nfunction CanceledError(message, config, request) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);\n this.name = 'CanceledError';\n}\n\nutils.inherits(CanceledError, AxiosError, {\n __CANCEL__: true\n});\n\nexport default CanceledError;\n","'use strict';\n\nimport AxiosError from './AxiosError.js';\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n *\n * @returns {object} The response.\n */\nexport default function settle(resolve, reject, response) {\n const validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(new AxiosError(\n 'Request failed with status code ' + response.status,\n [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],\n response.config,\n response.request,\n response\n ));\n }\n}\n","'use strict';\n\nexport default function parseProtocol(url) {\n const match = /^([-+\\w]{1,25})(:?\\/\\/|:)/.exec(url);\n return match && match[1] || '';\n}\n","'use strict';\n\n/**\n * Calculate data maxRate\n * @param {Number} [samplesCount= 10]\n * @param {Number} [min= 1000]\n * @returns {Function}\n */\nfunction speedometer(samplesCount, min) {\n samplesCount = samplesCount || 10;\n const bytes = new Array(samplesCount);\n const timestamps = new Array(samplesCount);\n let head = 0;\n let tail = 0;\n let firstSampleTS;\n\n min = min !== undefined ? min : 1000;\n\n return function push(chunkLength) {\n const now = Date.now();\n\n const startedAt = timestamps[tail];\n\n if (!firstSampleTS) {\n firstSampleTS = now;\n }\n\n bytes[head] = chunkLength;\n timestamps[head] = now;\n\n let i = tail;\n let bytesCount = 0;\n\n while (i !== head) {\n bytesCount += bytes[i++];\n i = i % samplesCount;\n }\n\n head = (head + 1) % samplesCount;\n\n if (head === tail) {\n tail = (tail + 1) % samplesCount;\n }\n\n if (now - firstSampleTS < min) {\n return;\n }\n\n const passed = startedAt && now - startedAt;\n\n return passed ? Math.round(bytesCount * 1000 / passed) : undefined;\n };\n}\n\nexport default speedometer;\n","/**\n * Throttle decorator\n * @param {Function} fn\n * @param {Number} freq\n * @return {Function}\n */\nfunction throttle(fn, freq) {\n let timestamp = 0;\n let threshold = 1000 / freq;\n let lastArgs;\n let timer;\n\n const invoke = (args, now = Date.now()) => {\n timestamp = now;\n lastArgs = null;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n fn.apply(null, args);\n }\n\n const throttled = (...args) => {\n const now = Date.now();\n const passed = now - timestamp;\n if ( passed >= threshold) {\n invoke(args, now);\n } else {\n lastArgs = args;\n if (!timer) {\n timer = setTimeout(() => {\n timer = null;\n invoke(lastArgs)\n }, threshold - passed);\n }\n }\n }\n\n const flush = () => lastArgs && invoke(lastArgs);\n\n return [throttled, flush];\n}\n\nexport default throttle;\n","import speedometer from \"./speedometer.js\";\nimport throttle from \"./throttle.js\";\nimport utils from \"../utils.js\";\n\nexport const progressEventReducer = (listener, isDownloadStream, freq = 3) => {\n let bytesNotified = 0;\n const _speedometer = speedometer(50, 250);\n\n return throttle(e => {\n const loaded = e.loaded;\n const total = e.lengthComputable ? e.total : undefined;\n const progressBytes = loaded - bytesNotified;\n const rate = _speedometer(progressBytes);\n const inRange = loaded <= total;\n\n bytesNotified = loaded;\n\n const data = {\n loaded,\n total,\n progress: total ? (loaded / total) : undefined,\n bytes: progressBytes,\n rate: rate ? rate : undefined,\n estimated: rate && total && inRange ? (total - loaded) / rate : undefined,\n event: e,\n lengthComputable: total != null,\n [isDownloadStream ? 'download' : 'upload']: true\n };\n\n listener(data);\n }, freq);\n}\n\nexport const progressEventDecorator = (total, throttled) => {\n const lengthComputable = total != null;\n\n return [(loaded) => throttled[0]({\n lengthComputable,\n total,\n loaded\n }), throttled[1]];\n}\n\nexport const asyncDecorator = (fn) => (...args) => utils.asap(() => fn(...args));\n","import platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {\n url = new URL(url, platform.origin);\n\n return (\n origin.protocol === url.protocol &&\n origin.host === url.host &&\n (isMSIE || origin.port === url.port)\n );\n})(\n new URL(platform.origin),\n platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)\n) : () => true;\n","import utils from './../utils.js';\nimport platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ?\n\n // Standard browser envs support document.cookie\n {\n write(name, value, expires, path, domain, secure) {\n const cookie = [name + '=' + encodeURIComponent(value)];\n\n utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());\n\n utils.isString(path) && cookie.push('path=' + path);\n\n utils.isString(domain) && cookie.push('domain=' + domain);\n\n secure === true && cookie.push('secure');\n\n document.cookie = cookie.join('; ');\n },\n\n read(name) {\n const match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n }\n\n :\n\n // Non-standard browser env (web workers, react-native) lack needed support.\n {\n write() {},\n read() {\n return null;\n },\n remove() {}\n };\n\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n *\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nexport default function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n}\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n *\n * @returns {string} The combined URL\n */\nexport default function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/?\\/$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n}\n","'use strict';\n\nimport isAbsoluteURL from '../helpers/isAbsoluteURL.js';\nimport combineURLs from '../helpers/combineURLs.js';\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n *\n * @returns {string} The combined full path\n */\nexport default function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosHeaders from \"./AxiosHeaders.js\";\n\nconst headersToObject = (thing) => thing instanceof AxiosHeaders ? { ...thing } : thing;\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n *\n * @returns {Object} New object resulting from merging config2 to config1\n */\nexport default function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n const config = {};\n\n function getMergedValue(target, source, prop, caseless) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge.call({caseless}, target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(a, b, prop , caseless) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(a, b, prop , caseless);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a, prop , caseless);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(a, b, prop) {\n if (prop in config2) {\n return getMergedValue(a, b);\n } else if (prop in config1) {\n return getMergedValue(undefined, a);\n }\n }\n\n const mergeMap = {\n url: valueFromConfig2,\n method: valueFromConfig2,\n data: valueFromConfig2,\n baseURL: defaultToConfig2,\n transformRequest: defaultToConfig2,\n transformResponse: defaultToConfig2,\n paramsSerializer: defaultToConfig2,\n timeout: defaultToConfig2,\n timeoutMessage: defaultToConfig2,\n withCredentials: defaultToConfig2,\n withXSRFToken: defaultToConfig2,\n adapter: defaultToConfig2,\n responseType: defaultToConfig2,\n xsrfCookieName: defaultToConfig2,\n xsrfHeaderName: defaultToConfig2,\n onUploadProgress: defaultToConfig2,\n onDownloadProgress: defaultToConfig2,\n decompress: defaultToConfig2,\n maxContentLength: defaultToConfig2,\n maxBodyLength: defaultToConfig2,\n beforeRedirect: defaultToConfig2,\n transport: defaultToConfig2,\n httpAgent: defaultToConfig2,\n httpsAgent: defaultToConfig2,\n cancelToken: defaultToConfig2,\n socketPath: defaultToConfig2,\n responseEncoding: defaultToConfig2,\n validateStatus: mergeDirectKeys,\n headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true)\n };\n\n utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {\n const merge = mergeMap[prop] || mergeDeepProperties;\n const configValue = merge(config1[prop], config2[prop], prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n}\n","import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport isURLSameOrigin from \"./isURLSameOrigin.js\";\nimport cookies from \"./cookies.js\";\nimport buildFullPath from \"../core/buildFullPath.js\";\nimport mergeConfig from \"../core/mergeConfig.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport buildURL from \"./buildURL.js\";\n\nexport default (config) => {\n const newConfig = mergeConfig({}, config);\n\n let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;\n\n newConfig.headers = headers = AxiosHeaders.from(headers);\n\n newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);\n\n // HTTP basic authentication\n if (auth) {\n headers.set('Authorization', 'Basic ' +\n btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))\n );\n }\n\n let contentType;\n\n if (utils.isFormData(data)) {\n if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {\n headers.setContentType(undefined); // Let the browser set it\n } else if ((contentType = headers.getContentType()) !== false) {\n // fix semicolon duplication issue for ReactNative FormData implementation\n const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];\n headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));\n }\n }\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n\n if (platform.hasStandardBrowserEnv) {\n withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));\n\n if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {\n // Add xsrf header\n const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);\n\n if (xsrfValue) {\n headers.set(xsrfHeaderName, xsrfValue);\n }\n }\n }\n\n return newConfig;\n}\n\n","import utils from './../utils.js';\nimport settle from './../core/settle.js';\nimport transitionalDefaults from '../defaults/transitional.js';\nimport AxiosError from '../core/AxiosError.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport parseProtocol from '../helpers/parseProtocol.js';\nimport platform from '../platform/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport {progressEventReducer} from '../helpers/progressEventReducer.js';\nimport resolveConfig from \"../helpers/resolveConfig.js\";\n\nconst isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';\n\nexport default isXHRAdapterSupported && function (config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n const _config = resolveConfig(config);\n let requestData = _config.data;\n const requestHeaders = AxiosHeaders.from(_config.headers).normalize();\n let {responseType, onUploadProgress, onDownloadProgress} = _config;\n let onCanceled;\n let uploadThrottled, downloadThrottled;\n let flushUpload, flushDownload;\n\n function done() {\n flushUpload && flushUpload(); // flush events\n flushDownload && flushDownload(); // flush events\n\n _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);\n\n _config.signal && _config.signal.removeEventListener('abort', onCanceled);\n }\n\n let request = new XMLHttpRequest();\n\n request.open(_config.method.toUpperCase(), _config.url, true);\n\n // Set the request timeout in MS\n request.timeout = _config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n const responseHeaders = AxiosHeaders.from(\n 'getAllResponseHeaders' in request && request.getAllResponseHeaders()\n );\n const responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n const response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config,\n request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';\n const transitional = _config.transitional || transitionalDefaults;\n if (_config.timeoutErrorMessage) {\n timeoutErrorMessage = _config.timeoutErrorMessage;\n }\n reject(new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n config,\n request));\n\n // Clean up request\n request = null;\n };\n\n // Remove Content-Type if data is undefined\n requestData === undefined && requestHeaders.setContentType(null);\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {\n request.setRequestHeader(key, val);\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(_config.withCredentials)) {\n request.withCredentials = !!_config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = _config.responseType;\n }\n\n // Handle progress if needed\n if (onDownloadProgress) {\n ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));\n request.addEventListener('progress', downloadThrottled);\n }\n\n // Not all browsers support upload events\n if (onUploadProgress && request.upload) {\n ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));\n\n request.upload.addEventListener('progress', uploadThrottled);\n\n request.upload.addEventListener('loadend', flushUpload);\n }\n\n if (_config.cancelToken || _config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = cancel => {\n if (!request) {\n return;\n }\n reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);\n request.abort();\n request = null;\n };\n\n _config.cancelToken && _config.cancelToken.subscribe(onCanceled);\n if (_config.signal) {\n _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n const protocol = parseProtocol(_config.url);\n\n if (protocol && platform.protocols.indexOf(protocol) === -1) {\n reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));\n return;\n }\n\n\n // Send the request\n request.send(requestData || null);\n });\n}\n","import CanceledError from \"../cancel/CanceledError.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport utils from '../utils.js';\n\nconst composeSignals = (signals, timeout) => {\n const {length} = (signals = signals ? signals.filter(Boolean) : []);\n\n if (timeout || length) {\n let controller = new AbortController();\n\n let aborted;\n\n const onabort = function (reason) {\n if (!aborted) {\n aborted = true;\n unsubscribe();\n const err = reason instanceof Error ? reason : this.reason;\n controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));\n }\n }\n\n let timer = timeout && setTimeout(() => {\n timer = null;\n onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT))\n }, timeout)\n\n const unsubscribe = () => {\n if (signals) {\n timer && clearTimeout(timer);\n timer = null;\n signals.forEach(signal => {\n signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);\n });\n signals = null;\n }\n }\n\n signals.forEach((signal) => signal.addEventListener('abort', onabort));\n\n const {signal} = controller;\n\n signal.unsubscribe = () => utils.asap(unsubscribe);\n\n return signal;\n }\n}\n\nexport default composeSignals;\n","\nexport const streamChunk = function* (chunk, chunkSize) {\n let len = chunk.byteLength;\n\n if (!chunkSize || len < chunkSize) {\n yield chunk;\n return;\n }\n\n let pos = 0;\n let end;\n\n while (pos < len) {\n end = pos + chunkSize;\n yield chunk.slice(pos, end);\n pos = end;\n }\n}\n\nexport const readBytes = async function* (iterable, chunkSize) {\n for await (const chunk of readStream(iterable)) {\n yield* streamChunk(chunk, chunkSize);\n }\n}\n\nconst readStream = async function* (stream) {\n if (stream[Symbol.asyncIterator]) {\n yield* stream;\n return;\n }\n\n const reader = stream.getReader();\n try {\n for (;;) {\n const {done, value} = await reader.read();\n if (done) {\n break;\n }\n yield value;\n }\n } finally {\n await reader.cancel();\n }\n}\n\nexport const trackStream = (stream, chunkSize, onProgress, onFinish) => {\n const iterator = readBytes(stream, chunkSize);\n\n let bytes = 0;\n let done;\n let _onFinish = (e) => {\n if (!done) {\n done = true;\n onFinish && onFinish(e);\n }\n }\n\n return new ReadableStream({\n async pull(controller) {\n try {\n const {done, value} = await iterator.next();\n\n if (done) {\n _onFinish();\n controller.close();\n return;\n }\n\n let len = value.byteLength;\n if (onProgress) {\n let loadedBytes = bytes += len;\n onProgress(loadedBytes);\n }\n controller.enqueue(new Uint8Array(value));\n } catch (err) {\n _onFinish(err);\n throw err;\n }\n },\n cancel(reason) {\n _onFinish(reason);\n return iterator.return();\n }\n }, {\n highWaterMark: 2\n })\n}\n","import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport composeSignals from \"../helpers/composeSignals.js\";\nimport {trackStream} from \"../helpers/trackStream.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport {progressEventReducer, progressEventDecorator, asyncDecorator} from \"../helpers/progressEventReducer.js\";\nimport resolveConfig from \"../helpers/resolveConfig.js\";\nimport settle from \"../core/settle.js\";\n\nconst isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';\nconst isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';\n\n// used only inside the fetch adapter\nconst encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?\n ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :\n async (str) => new Uint8Array(await new Response(str).arrayBuffer())\n);\n\nconst test = (fn, ...args) => {\n try {\n return !!fn(...args);\n } catch (e) {\n return false\n }\n}\n\nconst supportsRequestStream = isReadableStreamSupported && test(() => {\n let duplexAccessed = false;\n\n const hasContentType = new Request(platform.origin, {\n body: new ReadableStream(),\n method: 'POST',\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n }).headers.has('Content-Type');\n\n return duplexAccessed && !hasContentType;\n});\n\nconst DEFAULT_CHUNK_SIZE = 64 * 1024;\n\nconst supportsResponseStream = isReadableStreamSupported &&\n test(() => utils.isReadableStream(new Response('').body));\n\n\nconst resolvers = {\n stream: supportsResponseStream && ((res) => res.body)\n};\n\nisFetchSupported && (((res) => {\n ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {\n !resolvers[type] && (resolvers[type] = utils.isFunction(res[type]) ? (res) => res[type]() :\n (_, config) => {\n throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);\n })\n });\n})(new Response));\n\nconst getBodyLength = async (body) => {\n if (body == null) {\n return 0;\n }\n\n if(utils.isBlob(body)) {\n return body.size;\n }\n\n if(utils.isSpecCompliantForm(body)) {\n const _request = new Request(platform.origin, {\n method: 'POST',\n body,\n });\n return (await _request.arrayBuffer()).byteLength;\n }\n\n if(utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) {\n return body.byteLength;\n }\n\n if(utils.isURLSearchParams(body)) {\n body = body + '';\n }\n\n if(utils.isString(body)) {\n return (await encodeText(body)).byteLength;\n }\n}\n\nconst resolveBodyLength = async (headers, body) => {\n const length = utils.toFiniteNumber(headers.getContentLength());\n\n return length == null ? getBodyLength(body) : length;\n}\n\nexport default isFetchSupported && (async (config) => {\n let {\n url,\n method,\n data,\n signal,\n cancelToken,\n timeout,\n onDownloadProgress,\n onUploadProgress,\n responseType,\n headers,\n withCredentials = 'same-origin',\n fetchOptions\n } = resolveConfig(config);\n\n responseType = responseType ? (responseType + '').toLowerCase() : 'text';\n\n let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);\n\n let request;\n\n const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {\n composedSignal.unsubscribe();\n });\n\n let requestContentLength;\n\n try {\n if (\n onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&\n (requestContentLength = await resolveBodyLength(headers, data)) !== 0\n ) {\n let _request = new Request(url, {\n method: 'POST',\n body: data,\n duplex: \"half\"\n });\n\n let contentTypeHeader;\n\n if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {\n headers.setContentType(contentTypeHeader)\n }\n\n if (_request.body) {\n const [onProgress, flush] = progressEventDecorator(\n requestContentLength,\n progressEventReducer(asyncDecorator(onUploadProgress))\n );\n\n data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);\n }\n }\n\n if (!utils.isString(withCredentials)) {\n withCredentials = withCredentials ? 'include' : 'omit';\n }\n\n // Cloudflare Workers throws when credentials are defined\n // see https://github.com/cloudflare/workerd/issues/902\n const isCredentialsSupported = \"credentials\" in Request.prototype;\n request = new Request(url, {\n ...fetchOptions,\n signal: composedSignal,\n method: method.toUpperCase(),\n headers: headers.normalize().toJSON(),\n body: data,\n duplex: \"half\",\n credentials: isCredentialsSupported ? withCredentials : undefined\n });\n\n let response = await fetch(request);\n\n const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');\n\n if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {\n const options = {};\n\n ['status', 'statusText', 'headers'].forEach(prop => {\n options[prop] = response[prop];\n });\n\n const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length'));\n\n const [onProgress, flush] = onDownloadProgress && progressEventDecorator(\n responseContentLength,\n progressEventReducer(asyncDecorator(onDownloadProgress), true)\n ) || [];\n\n response = new Response(\n trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {\n flush && flush();\n unsubscribe && unsubscribe();\n }),\n options\n );\n }\n\n responseType = responseType || 'text';\n\n let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config);\n\n !isStreamResponse && unsubscribe && unsubscribe();\n\n return await new Promise((resolve, reject) => {\n settle(resolve, reject, {\n data: responseData,\n headers: AxiosHeaders.from(response.headers),\n status: response.status,\n statusText: response.statusText,\n config,\n request\n })\n })\n } catch (err) {\n unsubscribe && unsubscribe();\n\n if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {\n throw Object.assign(\n new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),\n {\n cause: err.cause || err\n }\n )\n }\n\n throw AxiosError.from(err, err && err.code, config, request);\n }\n});\n\n\n","import utils from '../utils.js';\nimport httpAdapter from './http.js';\nimport xhrAdapter from './xhr.js';\nimport fetchAdapter from './fetch.js';\nimport AxiosError from \"../core/AxiosError.js\";\n\nconst knownAdapters = {\n http: httpAdapter,\n xhr: xhrAdapter,\n fetch: fetchAdapter\n}\n\nutils.forEach(knownAdapters, (fn, value) => {\n if (fn) {\n try {\n Object.defineProperty(fn, 'name', {value});\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n Object.defineProperty(fn, 'adapterName', {value});\n }\n});\n\nconst renderReason = (reason) => `- ${reason}`;\n\nconst isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false;\n\nexport default {\n getAdapter: (adapters) => {\n adapters = utils.isArray(adapters) ? adapters : [adapters];\n\n const {length} = adapters;\n let nameOrAdapter;\n let adapter;\n\n const rejectedReasons = {};\n\n for (let i = 0; i < length; i++) {\n nameOrAdapter = adapters[i];\n let id;\n\n adapter = nameOrAdapter;\n\n if (!isResolvedHandle(nameOrAdapter)) {\n adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];\n\n if (adapter === undefined) {\n throw new AxiosError(`Unknown adapter '${id}'`);\n }\n }\n\n if (adapter) {\n break;\n }\n\n rejectedReasons[id || '#' + i] = adapter;\n }\n\n if (!adapter) {\n\n const reasons = Object.entries(rejectedReasons)\n .map(([id, state]) => `adapter ${id} ` +\n (state === false ? 'is not supported by the environment' : 'is not available in the build')\n );\n\n let s = length ?\n (reasons.length > 1 ? 'since :\\n' + reasons.map(renderReason).join('\\n') : ' ' + renderReason(reasons[0])) :\n 'as no adapter specified';\n\n throw new AxiosError(\n `There is no suitable adapter to dispatch the request ` + s,\n 'ERR_NOT_SUPPORT'\n );\n }\n\n return adapter;\n },\n adapters: knownAdapters\n}\n","'use strict';\n\nimport transformData from './transformData.js';\nimport isCancel from '../cancel/isCancel.js';\nimport defaults from '../defaults/index.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport adapters from \"../adapters/adapters.js\";\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n *\n * @param {Object} config The config that is to be used for the request\n *\n * @returns {void}\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new CanceledError(null, config);\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n *\n * @returns {Promise} The Promise to be fulfilled\n */\nexport default function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n config.headers = AxiosHeaders.from(config.headers);\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.transformRequest\n );\n\n if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {\n config.headers.setContentType('application/x-www-form-urlencoded', false);\n }\n\n const adapter = adapters.getAdapter(config.adapter || defaults.adapter);\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n config.transformResponse,\n response\n );\n\n response.headers = AxiosHeaders.from(response.headers);\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n config.transformResponse,\n reason.response\n );\n reason.response.headers = AxiosHeaders.from(reason.response.headers);\n }\n }\n\n return Promise.reject(reason);\n });\n}\n","export const VERSION = \"1.7.9\";","'use strict';\n\nimport {VERSION} from '../env/data.js';\nimport AxiosError from '../core/AxiosError.js';\n\nconst validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nconst deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n *\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n *\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return (value, opt, opts) => {\n if (validator === false) {\n throw new AxiosError(\n formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),\n AxiosError.ERR_DEPRECATED\n );\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\nvalidators.spelling = function spelling(correctSpelling) {\n return (value, opt) => {\n // eslint-disable-next-line no-console\n console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);\n return true;\n }\n};\n\n/**\n * Assert object's properties type\n *\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n *\n * @returns {object}\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);\n }\n const keys = Object.keys(options);\n let i = keys.length;\n while (i-- > 0) {\n const opt = keys[i];\n const validator = schema[opt];\n if (validator) {\n const value = options[opt];\n const result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);\n }\n }\n}\n\nexport default {\n assertOptions,\n validators\n};\n","'use strict';\n\nimport utils from './../utils.js';\nimport buildURL from '../helpers/buildURL.js';\nimport InterceptorManager from './InterceptorManager.js';\nimport dispatchRequest from './dispatchRequest.js';\nimport mergeConfig from './mergeConfig.js';\nimport buildFullPath from './buildFullPath.js';\nimport validator from '../helpers/validator.js';\nimport AxiosHeaders from './AxiosHeaders.js';\n\nconst validators = validator.validators;\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n *\n * @return {Axios} A new instance of Axios\n */\nclass Axios {\n constructor(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n }\n\n /**\n * Dispatch a request\n *\n * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)\n * @param {?Object} config\n *\n * @returns {Promise} The Promise to be fulfilled\n */\n async request(configOrUrl, config) {\n try {\n return await this._request(configOrUrl, config);\n } catch (err) {\n if (err instanceof Error) {\n let dummy = {};\n\n Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());\n\n // slice off the Error: ... line\n const stack = dummy.stack ? dummy.stack.replace(/^.+\\n/, '') : '';\n try {\n if (!err.stack) {\n err.stack = stack;\n // match without the 2 top stack lines\n } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\\n.+\\n/, ''))) {\n err.stack += '\\n' + stack\n }\n } catch (e) {\n // ignore the case where \"stack\" is an un-writable property\n }\n }\n\n throw err;\n }\n }\n\n _request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n const {transitional, paramsSerializer, headers} = config;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n if (paramsSerializer != null) {\n if (utils.isFunction(paramsSerializer)) {\n config.paramsSerializer = {\n serialize: paramsSerializer\n }\n } else {\n validator.assertOptions(paramsSerializer, {\n encode: validators.function,\n serialize: validators.function\n }, true);\n }\n }\n\n validator.assertOptions(config, {\n baseUrl: validators.spelling('baseURL'),\n withXsrfToken: validators.spelling('withXSRFToken')\n }, true);\n\n // Set config.method\n config.method = (config.method || this.defaults.method || 'get').toLowerCase();\n\n // Flatten headers\n let contextHeaders = headers && utils.merge(\n headers.common,\n headers[config.method]\n );\n\n headers && utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n (method) => {\n delete headers[method];\n }\n );\n\n config.headers = AxiosHeaders.concat(contextHeaders, headers);\n\n // filter out skipped interceptors\n const requestInterceptorChain = [];\n let synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n const responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n let promise;\n let i = 0;\n let len;\n\n if (!synchronousRequestInterceptors) {\n const chain = [dispatchRequest.bind(this), undefined];\n chain.unshift.apply(chain, requestInterceptorChain);\n chain.push.apply(chain, responseInterceptorChain);\n len = chain.length;\n\n promise = Promise.resolve(config);\n\n while (i < len) {\n promise = promise.then(chain[i++], chain[i++]);\n }\n\n return promise;\n }\n\n len = requestInterceptorChain.length;\n\n let newConfig = config;\n\n i = 0;\n\n while (i < len) {\n const onFulfilled = requestInterceptorChain[i++];\n const onRejected = requestInterceptorChain[i++];\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected.call(this, error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest.call(this, newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n i = 0;\n len = responseInterceptorChain.length;\n\n while (i < len) {\n promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);\n }\n\n return promise;\n }\n\n getUri(config) {\n config = mergeConfig(this.defaults, config);\n const fullPath = buildFullPath(config.baseURL, config.url);\n return buildURL(fullPath, config.params, config.paramsSerializer);\n }\n}\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n\n function generateHTTPMethod(isForm) {\n return function httpMethod(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n headers: isForm ? {\n 'Content-Type': 'multipart/form-data'\n } : {},\n url,\n data\n }));\n };\n }\n\n Axios.prototype[method] = generateHTTPMethod();\n\n Axios.prototype[method + 'Form'] = generateHTTPMethod(true);\n});\n\nexport default Axios;\n","'use strict';\n\nimport CanceledError from './CanceledError.js';\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @param {Function} executor The executor function.\n *\n * @returns {CancelToken}\n */\nclass CancelToken {\n constructor(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n let resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n const token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(cancel => {\n if (!token._listeners) return;\n\n let i = token._listeners.length;\n\n while (i-- > 0) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = onfulfilled => {\n let _resolve;\n // eslint-disable-next-line func-names\n const promise = new Promise(resolve => {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message, config, request) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new CanceledError(message, config, request);\n resolvePromise(token.reason);\n });\n }\n\n /**\n * Throws a `CanceledError` if cancellation has been requested.\n */\n throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n }\n\n /**\n * Subscribe to the cancel signal\n */\n\n subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n }\n\n /**\n * Unsubscribe from the cancel signal\n */\n\n unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n const index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n }\n\n toAbortSignal() {\n const controller = new AbortController();\n\n const abort = (err) => {\n controller.abort(err);\n };\n\n this.subscribe(abort);\n\n controller.signal.unsubscribe = () => this.unsubscribe(abort);\n\n return controller.signal;\n }\n\n /**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\n static source() {\n let cancel;\n const token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token,\n cancel\n };\n }\n}\n\nexport default CancelToken;\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n *\n * @returns {Function}\n */\nexport default function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n *\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nexport default function isAxiosError(payload) {\n return utils.isObject(payload) && (payload.isAxiosError === true);\n}\n","const HttpStatusCode = {\n Continue: 100,\n SwitchingProtocols: 101,\n Processing: 102,\n EarlyHints: 103,\n Ok: 200,\n Created: 201,\n Accepted: 202,\n NonAuthoritativeInformation: 203,\n NoContent: 204,\n ResetContent: 205,\n PartialContent: 206,\n MultiStatus: 207,\n AlreadyReported: 208,\n ImUsed: 226,\n MultipleChoices: 300,\n MovedPermanently: 301,\n Found: 302,\n SeeOther: 303,\n NotModified: 304,\n UseProxy: 305,\n Unused: 306,\n TemporaryRedirect: 307,\n PermanentRedirect: 308,\n BadRequest: 400,\n Unauthorized: 401,\n PaymentRequired: 402,\n Forbidden: 403,\n NotFound: 404,\n MethodNotAllowed: 405,\n NotAcceptable: 406,\n ProxyAuthenticationRequired: 407,\n RequestTimeout: 408,\n Conflict: 409,\n Gone: 410,\n LengthRequired: 411,\n PreconditionFailed: 412,\n PayloadTooLarge: 413,\n UriTooLong: 414,\n UnsupportedMediaType: 415,\n RangeNotSatisfiable: 416,\n ExpectationFailed: 417,\n ImATeapot: 418,\n MisdirectedRequest: 421,\n UnprocessableEntity: 422,\n Locked: 423,\n FailedDependency: 424,\n TooEarly: 425,\n UpgradeRequired: 426,\n PreconditionRequired: 428,\n TooManyRequests: 429,\n RequestHeaderFieldsTooLarge: 431,\n UnavailableForLegalReasons: 451,\n InternalServerError: 500,\n NotImplemented: 501,\n BadGateway: 502,\n ServiceUnavailable: 503,\n GatewayTimeout: 504,\n HttpVersionNotSupported: 505,\n VariantAlsoNegotiates: 506,\n InsufficientStorage: 507,\n LoopDetected: 508,\n NotExtended: 510,\n NetworkAuthenticationRequired: 511,\n};\n\nObject.entries(HttpStatusCode).forEach(([key, value]) => {\n HttpStatusCode[value] = key;\n});\n\nexport default HttpStatusCode;\n","'use strict';\n\nimport utils from './utils.js';\nimport bind from './helpers/bind.js';\nimport Axios from './core/Axios.js';\nimport mergeConfig from './core/mergeConfig.js';\nimport defaults from './defaults/index.js';\nimport formDataToJSON from './helpers/formDataToJSON.js';\nimport CanceledError from './cancel/CanceledError.js';\nimport CancelToken from './cancel/CancelToken.js';\nimport isCancel from './cancel/isCancel.js';\nimport {VERSION} from './env/data.js';\nimport toFormData from './helpers/toFormData.js';\nimport AxiosError from './core/AxiosError.js';\nimport spread from './helpers/spread.js';\nimport isAxiosError from './helpers/isAxiosError.js';\nimport AxiosHeaders from \"./core/AxiosHeaders.js\";\nimport adapters from './adapters/adapters.js';\nimport HttpStatusCode from './helpers/HttpStatusCode.js';\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n *\n * @returns {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n const context = new Axios(defaultConfig);\n const instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});\n\n // Copy context to instance\n utils.extend(instance, context, null, {allOwnKeys: true});\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nconst axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.CanceledError = CanceledError;\naxios.CancelToken = CancelToken;\naxios.isCancel = isCancel;\naxios.VERSION = VERSION;\naxios.toFormData = toFormData;\n\n// Expose AxiosError class\naxios.AxiosError = AxiosError;\n\n// alias for CanceledError for backward compatibility\naxios.Cancel = axios.CanceledError;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\n\naxios.spread = spread;\n\n// Expose isAxiosError\naxios.isAxiosError = isAxiosError;\n\n// Expose mergeConfig\naxios.mergeConfig = mergeConfig;\n\naxios.AxiosHeaders = AxiosHeaders;\n\naxios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);\n\naxios.getAdapter = adapters.getAdapter;\n\naxios.HttpStatusCode = HttpStatusCode;\n\naxios.default = axios;\n\n// this module should only have a default export\nexport default axios\n"],"names":["bind","fn","thisArg","wrap","apply","arguments","toString","Object","prototype","getPrototypeOf","kindOf","cache","thing","str","call","slice","toLowerCase","create","kindOfTest","type","typeOfTest","_typeof","isArray","Array","isUndefined","isBuffer","val","constructor","isFunction","isArrayBuffer","isArrayBufferView","result","ArrayBuffer","isView","buffer","isString","isNumber","isObject","isBoolean","isPlainObject","Symbol","toStringTag","iterator","isDate","isFile","isBlob","isFileList","isStream","pipe","isFormData","kind","FormData","append","isURLSearchParams","_map","map","_map2","_slicedToArray","isReadableStream","isRequest","isResponse","isHeaders","trim","replace","forEach","obj","_ref","length","undefined","_ref$allOwnKeys","allOwnKeys","i","l","keys","getOwnPropertyNames","len","key","findKey","_key","_global","globalThis","self","window","global","isContextDefined","context","merge","_ref2","caseless","assignValue","targetKey","extend","a","b","_ref3","stripBOM","content","charCodeAt","inherits","superConstructor","props","descriptors","defineProperty","value","assign","toFlatObject","sourceObj","destObj","filter","propFilter","prop","merged","endsWith","searchString","position","String","lastIndex","indexOf","toArray","arr","isTypedArray","TypedArray","Uint8Array","forEachEntry","generator","next","done","pair","matchAll","regExp","matches","exec","push","isHTMLForm","toCamelCase","replacer","m","p1","p2","toUpperCase","hasOwnProperty","_ref4","isRegExp","reduceDescriptors","reducer","getOwnPropertyDescriptors","reducedDescriptors","descriptor","name","ret","defineProperties","freezeMethods","enumerable","writable","set","Error","toObjectSet","arrayOrString","delimiter","define","split","noop","toFiniteNumber","defaultValue","Number","isFinite","ALPHA","DIGIT","ALPHABET","ALPHA_DIGIT","generateString","size","alphabet","Math","random","isSpecCompliantForm","toJSONObject","stack","visit","source","target","reducedValue","isAsyncFn","isThenable","then","_setImmediate","setImmediateSupported","postMessageSupported","setImmediate","token","callbacks","addEventListener","_ref5","data","shift","cb","postMessage","concat","setTimeout","asap","queueMicrotask","process","nextTick","hasOwnProp","AxiosError","message","code","config","request","response","captureStackTrace","status","utils","toJSON","description","number","fileName","lineNumber","columnNumber","from","error","customProps","axiosError","cause","isVisitable","removeBrackets","renderKey","path","dots","each","join","isFlatArray","some","predicates","test","toFormData","formData","options","TypeError","metaTokens","indexes","defined","option","visitor","defaultVisitor","_Blob","Blob","useBlob","convertValue","toISOString","Buffer","JSON","stringify","el","index","exposedHelpers","build","pop","encode","charMap","encodeURIComponent","match","AxiosURLSearchParams","params","_pairs","encoder","_encode","buildURL","url","serialize","serializeFn","serializedParams","hashmarkIndex","InterceptorManager","_classCallCheck","handlers","_createClass","use","fulfilled","rejected","synchronous","runWhen","eject","id","clear","forEachHandler","h","silentJSONParsing","forcedJSONParsing","clarifyTimeoutError","URLSearchParams","isBrowser","classes","protocols","hasBrowserEnv","document","_navigator","navigator","hasStandardBrowserEnv","product","hasStandardBrowserWebWorkerEnv","WorkerGlobalScope","importScripts","origin","location","href","_objectSpread","platform","toURLEncodedForm","helpers","isNode","parsePropPath","arrayToObject","formDataToJSON","buildPath","isNumericKey","isLast","entries","stringifySafely","rawValue","parser","parse","e","defaults","transitional","transitionalDefaults","adapter","transformRequest","headers","contentType","getContentType","hasJSONContentType","isObjectPayload","setContentType","formSerializer","_FormData","env","transformResponse","JSONRequested","responseType","strictJSONParsing","ERR_BAD_RESPONSE","timeout","xsrfCookieName","xsrfHeaderName","maxContentLength","maxBodyLength","validateStatus","common","method","ignoreDuplicateOf","rawHeaders","parsed","line","substring","$internals","normalizeHeader","header","normalizeValue","parseTokens","tokens","tokensRE","isValidHeaderName","matchHeaderValue","isHeaderNameFilter","formatHeader","w","char","buildAccessors","accessorName","methodName","arg1","arg2","arg3","configurable","AxiosHeaders","_Symbol$iterator","_Symbol$toStringTag","valueOrRewrite","rewrite","setHeader","_value","_header","_rewrite","lHeader","setHeaders","parseHeaders","_iterator","_createForOfIteratorHelper","_step","s","n","_step$value","err","f","get","has","matcher","_delete","deleted","deleteHeader","normalize","format","normalized","_this$constructor","_len","targets","asStrings","first","computed","_len2","_key2","accessor","internals","accessors","defineAccessor","mapped","headerValue","transformData","fns","transform","isCancel","__CANCEL__","CanceledError","ERR_CANCELED","settle","resolve","reject","ERR_BAD_REQUEST","floor","parseProtocol","speedometer","samplesCount","min","bytes","timestamps","head","tail","firstSampleTS","chunkLength","now","Date","startedAt","bytesCount","passed","round","throttle","freq","timestamp","threshold","lastArgs","timer","invoke","args","clearTimeout","throttled","flush","progressEventReducer","listener","isDownloadStream","bytesNotified","_speedometer","loaded","total","lengthComputable","progressBytes","rate","inRange","_defineProperty","progress","estimated","event","progressEventDecorator","asyncDecorator","isMSIE","URL","protocol","host","port","userAgent","write","expires","domain","secure","cookie","toGMTString","read","RegExp","decodeURIComponent","remove","isAbsoluteURL","combineURLs","baseURL","relativeURL","buildFullPath","requestedURL","headersToObject","mergeConfig","config1","config2","getMergedValue","mergeDeepProperties","valueFromConfig2","defaultToConfig2","mergeDirectKeys","mergeMap","paramsSerializer","timeoutMessage","withCredentials","withXSRFToken","onUploadProgress","onDownloadProgress","decompress","beforeRedirect","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding","computeConfigValue","configValue","newConfig","auth","btoa","username","password","unescape","Boolean","_toArray","_toConsumableArray","isURLSameOrigin","xsrfValue","cookies","isXHRAdapterSupported","XMLHttpRequest","Promise","dispatchXhrRequest","_config","resolveConfig","requestData","requestHeaders","onCanceled","uploadThrottled","downloadThrottled","flushUpload","flushDownload","unsubscribe","signal","removeEventListener","open","onloadend","responseHeaders","getAllResponseHeaders","responseData","responseText","statusText","_resolve","_reject","onreadystatechange","handleLoad","readyState","responseURL","onabort","handleAbort","ECONNABORTED","onerror","handleError","ERR_NETWORK","ontimeout","handleTimeout","timeoutErrorMessage","ETIMEDOUT","setRequestHeader","_progressEventReducer","_progressEventReducer2","upload","_progressEventReducer3","_progressEventReducer4","cancel","abort","subscribe","aborted","send","composeSignals","signals","_signals","controller","AbortController","reason","streamChunk","_regeneratorRuntime","mark","chunk","chunkSize","pos","end","streamChunk$","_context","prev","byteLength","abrupt","stop","readBytes","_wrapAsyncGenerator","_callee","iterable","_iteratorAbruptCompletion","_didIteratorError","_iteratorError","_callee$","_context2","_asyncIterator","readStream","_awaitAsyncGenerator","sent","delegateYield","_asyncGeneratorDelegate","t1","finish","_x","_x2","_callee2","stream","reader","_yield$_awaitAsyncGen","_callee2$","_context3","asyncIterator","getReader","_x3","trackStream","onProgress","onFinish","_onFinish","ReadableStream","pull","_asyncToGenerator","_callee3","_yield$iterator$next","_done","loadedBytes","_callee3$","_context4","close","enqueue","t0","highWaterMark","isFetchSupported","fetch","Request","Response","isReadableStreamSupported","encodeText","TextEncoder","arrayBuffer","supportsRequestStream","duplexAccessed","hasContentType","body","duplex","DEFAULT_CHUNK_SIZE","supportsResponseStream","resolvers","res","_","ERR_NOT_SUPPORT","getBodyLength","_request","resolveBodyLength","getContentLength","_x4","_callee4","_resolveConfig","_resolveConfig$withCr","fetchOptions","composedSignal","requestContentLength","contentTypeHeader","_progressEventDecorat","_progressEventDecorat2","isCredentialsSupported","isStreamResponse","responseContentLength","_ref6","_onProgress","_flush","_callee4$","toAbortSignal","credentials","t2","_x5","knownAdapters","http","httpAdapter","xhr","xhrAdapter","fetchAdapter","renderReason","isResolvedHandle","getAdapter","adapters","_adapters","nameOrAdapter","rejectedReasons","reasons","state","throwIfCancellationRequested","throwIfRequested","dispatchRequest","onAdapterResolution","onAdapterRejection","VERSION","validators","validator","deprecatedWarnings","version","formatMessage","opt","desc","opts","ERR_DEPRECATED","console","warn","spelling","correctSpelling","assertOptions","schema","allowUnknown","ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","Axios","instanceConfig","interceptors","_request2","configOrUrl","dummy","baseUrl","withXsrfToken","contextHeaders","requestInterceptorChain","synchronousRequestInterceptors","unshiftRequestInterceptors","interceptor","unshift","responseInterceptorChain","pushResponseInterceptors","promise","chain","onFulfilled","onRejected","getUri","fullPath","forEachMethodNoData","forEachMethodWithData","generateHTTPMethod","isForm","httpMethod","CancelToken","executor","resolvePromise","promiseExecutor","_listeners","onfulfilled","splice","_this","c","spread","callback","isAxiosError","payload","HttpStatusCode","Continue","SwitchingProtocols","Processing","EarlyHints","Ok","Created","Accepted","NonAuthoritativeInformation","NoContent","ResetContent","PartialContent","MultiStatus","AlreadyReported","ImUsed","MultipleChoices","MovedPermanently","Found","SeeOther","NotModified","UseProxy","Unused","TemporaryRedirect","PermanentRedirect","BadRequest","Unauthorized","PaymentRequired","Forbidden","NotFound","MethodNotAllowed","NotAcceptable","ProxyAuthenticationRequired","RequestTimeout","Conflict","Gone","LengthRequired","PreconditionFailed","PayloadTooLarge","UriTooLong","UnsupportedMediaType","RangeNotSatisfiable","ExpectationFailed","ImATeapot","MisdirectedRequest","UnprocessableEntity","Locked","FailedDependency","TooEarly","UpgradeRequired","PreconditionRequired","TooManyRequests","RequestHeaderFieldsTooLarge","UnavailableForLegalReasons","InternalServerError","NotImplemented","BadGateway","ServiceUnavailable","GatewayTimeout","HttpVersionNotSupported","VariantAlsoNegotiates","InsufficientStorage","LoopDetected","NotExtended","NetworkAuthenticationRequired","createInstance","defaultConfig","instance","axios","Cancel","all","promises","formToJSON"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAEe,SAASA,IAAIA,CAACC,EAAE,EAAEC,OAAO,EAAE;IACxC,OAAO,SAASC,IAAIA,GAAG;EACrB,IAAA,OAAOF,EAAE,CAACG,KAAK,CAACF,OAAO,EAAEG,SAAS,CAAC,CAAA;KACpC,CAAA;EACH;;ECFA;;EAEA,IAAOC,QAAQ,GAAIC,MAAM,CAACC,SAAS,CAA5BF,QAAQ,CAAA;EACf,IAAOG,cAAc,GAAIF,MAAM,CAAxBE,cAAc,CAAA;EAErB,IAAMC,MAAM,GAAI,UAAAC,KAAK,EAAA;IAAA,OAAI,UAAAC,KAAK,EAAI;EAC9B,IAAA,IAAMC,GAAG,GAAGP,QAAQ,CAACQ,IAAI,CAACF,KAAK,CAAC,CAAA;MAChC,OAAOD,KAAK,CAACE,GAAG,CAAC,KAAKF,KAAK,CAACE,GAAG,CAAC,GAAGA,GAAG,CAACE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAACC,WAAW,EAAE,CAAC,CAAA;KACrE,CAAA;EAAA,CAAA,CAAET,MAAM,CAACU,MAAM,CAAC,IAAI,CAAC,CAAC,CAAA;EAEvB,IAAMC,UAAU,GAAG,SAAbA,UAAUA,CAAIC,IAAI,EAAK;EAC3BA,EAAAA,IAAI,GAAGA,IAAI,CAACH,WAAW,EAAE,CAAA;EACzB,EAAA,OAAO,UAACJ,KAAK,EAAA;EAAA,IAAA,OAAKF,MAAM,CAACE,KAAK,CAAC,KAAKO,IAAI,CAAA;EAAA,GAAA,CAAA;EAC1C,CAAC,CAAA;EAED,IAAMC,UAAU,GAAG,SAAbA,UAAUA,CAAGD,IAAI,EAAA;EAAA,EAAA,OAAI,UAAAP,KAAK,EAAA;EAAA,IAAA,OAAIS,OAAA,CAAOT,KAAK,CAAA,KAAKO,IAAI,CAAA;EAAA,GAAA,CAAA;EAAA,CAAA,CAAA;;EAEzD;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAOG,OAAO,GAAIC,KAAK,CAAhBD,OAAO,CAAA;;EAEd;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAME,WAAW,GAAGJ,UAAU,CAAC,WAAW,CAAC,CAAA;;EAE3C;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASK,QAAQA,CAACC,GAAG,EAAE;EACrB,EAAA,OAAOA,GAAG,KAAK,IAAI,IAAI,CAACF,WAAW,CAACE,GAAG,CAAC,IAAIA,GAAG,CAACC,WAAW,KAAK,IAAI,IAAI,CAACH,WAAW,CAACE,GAAG,CAACC,WAAW,CAAC,IAChGC,UAAU,CAACF,GAAG,CAACC,WAAW,CAACF,QAAQ,CAAC,IAAIC,GAAG,CAACC,WAAW,CAACF,QAAQ,CAACC,GAAG,CAAC,CAAA;EAC5E,CAAA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMG,aAAa,GAAGX,UAAU,CAAC,aAAa,CAAC,CAAA;;EAG/C;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASY,iBAAiBA,CAACJ,GAAG,EAAE;EAC9B,EAAA,IAAIK,MAAM,CAAA;IACV,IAAK,OAAOC,WAAW,KAAK,WAAW,IAAMA,WAAW,CAACC,MAAO,EAAE;EAChEF,IAAAA,MAAM,GAAGC,WAAW,CAACC,MAAM,CAACP,GAAG,CAAC,CAAA;EAClC,GAAC,MAAM;EACLK,IAAAA,MAAM,GAAIL,GAAG,IAAMA,GAAG,CAACQ,MAAO,IAAKL,aAAa,CAACH,GAAG,CAACQ,MAAM,CAAE,CAAA;EAC/D,GAAA;EACA,EAAA,OAAOH,MAAM,CAAA;EACf,CAAA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMI,QAAQ,GAAGf,UAAU,CAAC,QAAQ,CAAC,CAAA;;EAErC;EACA;EACA;EACA;EACA;EACA;EACA,IAAMQ,UAAU,GAAGR,UAAU,CAAC,UAAU,CAAC,CAAA;;EAEzC;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMgB,QAAQ,GAAGhB,UAAU,CAAC,QAAQ,CAAC,CAAA;;EAErC;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMiB,QAAQ,GAAG,SAAXA,QAAQA,CAAIzB,KAAK,EAAA;IAAA,OAAKA,KAAK,KAAK,IAAI,IAAIS,OAAA,CAAOT,KAAK,MAAK,QAAQ,CAAA;EAAA,CAAA,CAAA;;EAEvE;EACA;EACA;EACA;EACA;EACA;EACA,IAAM0B,SAAS,GAAG,SAAZA,SAASA,CAAG1B,KAAK,EAAA;EAAA,EAAA,OAAIA,KAAK,KAAK,IAAI,IAAIA,KAAK,KAAK,KAAK,CAAA;EAAA,CAAA,CAAA;;EAE5D;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAM2B,aAAa,GAAG,SAAhBA,aAAaA,CAAIb,GAAG,EAAK;EAC7B,EAAA,IAAIhB,MAAM,CAACgB,GAAG,CAAC,KAAK,QAAQ,EAAE;EAC5B,IAAA,OAAO,KAAK,CAAA;EACd,GAAA;EAEA,EAAA,IAAMlB,SAAS,GAAGC,cAAc,CAACiB,GAAG,CAAC,CAAA;EACrC,EAAA,OAAO,CAAClB,SAAS,KAAK,IAAI,IAAIA,SAAS,KAAKD,MAAM,CAACC,SAAS,IAAID,MAAM,CAACE,cAAc,CAACD,SAAS,CAAC,KAAK,IAAI,KAAK,EAAEgC,MAAM,CAACC,WAAW,IAAIf,GAAG,CAAC,IAAI,EAAEc,MAAM,CAACE,QAAQ,IAAIhB,GAAG,CAAC,CAAA;EACzK,CAAC,CAAA;;EAED;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMiB,MAAM,GAAGzB,UAAU,CAAC,MAAM,CAAC,CAAA;;EAEjC;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAM0B,MAAM,GAAG1B,UAAU,CAAC,MAAM,CAAC,CAAA;;EAEjC;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAM2B,MAAM,GAAG3B,UAAU,CAAC,MAAM,CAAC,CAAA;;EAEjC;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAM4B,UAAU,GAAG5B,UAAU,CAAC,UAAU,CAAC,CAAA;;EAEzC;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAM6B,QAAQ,GAAG,SAAXA,QAAQA,CAAIrB,GAAG,EAAA;IAAA,OAAKW,QAAQ,CAACX,GAAG,CAAC,IAAIE,UAAU,CAACF,GAAG,CAACsB,IAAI,CAAC,CAAA;EAAA,CAAA,CAAA;;EAE/D;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMC,UAAU,GAAG,SAAbA,UAAUA,CAAIrC,KAAK,EAAK;EAC5B,EAAA,IAAIsC,IAAI,CAAA;IACR,OAAOtC,KAAK,KACT,OAAOuC,QAAQ,KAAK,UAAU,IAAIvC,KAAK,YAAYuC,QAAQ,IAC1DvB,UAAU,CAAChB,KAAK,CAACwC,MAAM,CAAC,KACtB,CAACF,IAAI,GAAGxC,MAAM,CAACE,KAAK,CAAC,MAAM,UAAU;EACrC;EACCsC,EAAAA,IAAI,KAAK,QAAQ,IAAItB,UAAU,CAAChB,KAAK,CAACN,QAAQ,CAAC,IAAIM,KAAK,CAACN,QAAQ,EAAE,KAAK,mBAAoB,CAEhG,CACF,CAAA;EACH,CAAC,CAAA;;EAED;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAM+C,iBAAiB,GAAGnC,UAAU,CAAC,iBAAiB,CAAC,CAAA;EAEvD,IAAAoC,IAAA,GAA6D,CAAC,gBAAgB,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,CAAC,CAACC,GAAG,CAACrC,UAAU,CAAC;IAAAsC,KAAA,GAAAC,cAAA,CAAAH,IAAA,EAAA,CAAA,CAAA;EAA1HI,EAAAA,gBAAgB,GAAAF,KAAA,CAAA,CAAA,CAAA;EAAEG,EAAAA,SAAS,GAAAH,KAAA,CAAA,CAAA,CAAA;EAAEI,EAAAA,UAAU,GAAAJ,KAAA,CAAA,CAAA,CAAA;EAAEK,EAAAA,SAAS,GAAAL,KAAA,CAAA,CAAA,CAAA,CAAA;;EAEzD;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMM,IAAI,GAAG,SAAPA,IAAIA,CAAIjD,GAAG,EAAA;EAAA,EAAA,OAAKA,GAAG,CAACiD,IAAI,GAC5BjD,GAAG,CAACiD,IAAI,EAAE,GAAGjD,GAAG,CAACkD,OAAO,CAAC,oCAAoC,EAAE,EAAE,CAAC,CAAA;EAAA,CAAA,CAAA;;EAEpE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASC,OAAOA,CAACC,GAAG,EAAEhE,EAAE,EAA6B;EAAA,EAAA,IAAAiE,IAAA,GAAA7D,SAAA,CAAA8D,MAAA,GAAA,CAAA,IAAA9D,SAAA,CAAA,CAAA,CAAA,KAAA+D,SAAA,GAAA/D,SAAA,CAAA,CAAA,CAAA,GAAJ,EAAE;MAAAgE,eAAA,GAAAH,IAAA,CAAxBI,UAAU;EAAVA,IAAAA,UAAU,GAAAD,eAAA,KAAG,KAAA,CAAA,GAAA,KAAK,GAAAA,eAAA,CAAA;EAC3C;IACA,IAAIJ,GAAG,KAAK,IAAI,IAAI,OAAOA,GAAG,KAAK,WAAW,EAAE;EAC9C,IAAA,OAAA;EACF,GAAA;EAEA,EAAA,IAAIM,CAAC,CAAA;EACL,EAAA,IAAIC,CAAC,CAAA;;EAEL;EACA,EAAA,IAAInD,OAAA,CAAO4C,GAAG,CAAA,KAAK,QAAQ,EAAE;EAC3B;MACAA,GAAG,GAAG,CAACA,GAAG,CAAC,CAAA;EACb,GAAA;EAEA,EAAA,IAAI3C,OAAO,CAAC2C,GAAG,CAAC,EAAE;EAChB;EACA,IAAA,KAAKM,CAAC,GAAG,CAAC,EAAEC,CAAC,GAAGP,GAAG,CAACE,MAAM,EAAEI,CAAC,GAAGC,CAAC,EAAED,CAAC,EAAE,EAAE;EACtCtE,MAAAA,EAAE,CAACa,IAAI,CAAC,IAAI,EAAEmD,GAAG,CAACM,CAAC,CAAC,EAAEA,CAAC,EAAEN,GAAG,CAAC,CAAA;EAC/B,KAAA;EACF,GAAC,MAAM;EACL;EACA,IAAA,IAAMQ,IAAI,GAAGH,UAAU,GAAG/D,MAAM,CAACmE,mBAAmB,CAACT,GAAG,CAAC,GAAG1D,MAAM,CAACkE,IAAI,CAACR,GAAG,CAAC,CAAA;EAC5E,IAAA,IAAMU,GAAG,GAAGF,IAAI,CAACN,MAAM,CAAA;EACvB,IAAA,IAAIS,GAAG,CAAA;MAEP,KAAKL,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGI,GAAG,EAAEJ,CAAC,EAAE,EAAE;EACxBK,MAAAA,GAAG,GAAGH,IAAI,CAACF,CAAC,CAAC,CAAA;EACbtE,MAAAA,EAAE,CAACa,IAAI,CAAC,IAAI,EAAEmD,GAAG,CAACW,GAAG,CAAC,EAAEA,GAAG,EAAEX,GAAG,CAAC,CAAA;EACnC,KAAA;EACF,GAAA;EACF,CAAA;EAEA,SAASY,OAAOA,CAACZ,GAAG,EAAEW,GAAG,EAAE;EACzBA,EAAAA,GAAG,GAAGA,GAAG,CAAC5D,WAAW,EAAE,CAAA;EACvB,EAAA,IAAMyD,IAAI,GAAGlE,MAAM,CAACkE,IAAI,CAACR,GAAG,CAAC,CAAA;EAC7B,EAAA,IAAIM,CAAC,GAAGE,IAAI,CAACN,MAAM,CAAA;EACnB,EAAA,IAAIW,IAAI,CAAA;EACR,EAAA,OAAOP,CAAC,EAAE,GAAG,CAAC,EAAE;EACdO,IAAAA,IAAI,GAAGL,IAAI,CAACF,CAAC,CAAC,CAAA;EACd,IAAA,IAAIK,GAAG,KAAKE,IAAI,CAAC9D,WAAW,EAAE,EAAE;EAC9B,MAAA,OAAO8D,IAAI,CAAA;EACb,KAAA;EACF,GAAA;EACA,EAAA,OAAO,IAAI,CAAA;EACb,CAAA;EAEA,IAAMC,OAAO,GAAI,YAAM;EACrB;EACA,EAAA,IAAI,OAAOC,UAAU,KAAK,WAAW,EAAE,OAAOA,UAAU,CAAA;EACxD,EAAA,OAAO,OAAOC,IAAI,KAAK,WAAW,GAAGA,IAAI,GAAI,OAAOC,MAAM,KAAK,WAAW,GAAGA,MAAM,GAAGC,MAAO,CAAA;EAC/F,CAAC,EAAG,CAAA;EAEJ,IAAMC,gBAAgB,GAAG,SAAnBA,gBAAgBA,CAAIC,OAAO,EAAA;IAAA,OAAK,CAAC7D,WAAW,CAAC6D,OAAO,CAAC,IAAIA,OAAO,KAAKN,OAAO,CAAA;EAAA,CAAA,CAAA;;EAElF;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASO,KAAKA;EAAC,EAA6B;IAC1C,IAAAC,KAAA,GAAmBH,gBAAgB,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,EAAE;MAAhDI,QAAQ,GAAAD,KAAA,CAARC,QAAQ,CAAA;IACf,IAAMzD,MAAM,GAAG,EAAE,CAAA;IACjB,IAAM0D,WAAW,GAAG,SAAdA,WAAWA,CAAI/D,GAAG,EAAEkD,GAAG,EAAK;MAChC,IAAMc,SAAS,GAAGF,QAAQ,IAAIX,OAAO,CAAC9C,MAAM,EAAE6C,GAAG,CAAC,IAAIA,GAAG,CAAA;EACzD,IAAA,IAAIrC,aAAa,CAACR,MAAM,CAAC2D,SAAS,CAAC,CAAC,IAAInD,aAAa,CAACb,GAAG,CAAC,EAAE;EAC1DK,MAAAA,MAAM,CAAC2D,SAAS,CAAC,GAAGJ,KAAK,CAACvD,MAAM,CAAC2D,SAAS,CAAC,EAAEhE,GAAG,CAAC,CAAA;EACnD,KAAC,MAAM,IAAIa,aAAa,CAACb,GAAG,CAAC,EAAE;QAC7BK,MAAM,CAAC2D,SAAS,CAAC,GAAGJ,KAAK,CAAC,EAAE,EAAE5D,GAAG,CAAC,CAAA;EACpC,KAAC,MAAM,IAAIJ,OAAO,CAACI,GAAG,CAAC,EAAE;QACvBK,MAAM,CAAC2D,SAAS,CAAC,GAAGhE,GAAG,CAACX,KAAK,EAAE,CAAA;EACjC,KAAC,MAAM;EACLgB,MAAAA,MAAM,CAAC2D,SAAS,CAAC,GAAGhE,GAAG,CAAA;EACzB,KAAA;KACD,CAAA;EAED,EAAA,KAAK,IAAI6C,CAAC,GAAG,CAAC,EAAEC,CAAC,GAAGnE,SAAS,CAAC8D,MAAM,EAAEI,CAAC,GAAGC,CAAC,EAAED,CAAC,EAAE,EAAE;EAChDlE,IAAAA,SAAS,CAACkE,CAAC,CAAC,IAAIP,OAAO,CAAC3D,SAAS,CAACkE,CAAC,CAAC,EAAEkB,WAAW,CAAC,CAAA;EACpD,GAAA;EACA,EAAA,OAAO1D,MAAM,CAAA;EACf,CAAA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAM4D,MAAM,GAAG,SAATA,MAAMA,CAAIC,CAAC,EAAEC,CAAC,EAAE3F,OAAO,EAAuB;EAAA,EAAA,IAAA4F,KAAA,GAAAzF,SAAA,CAAA8D,MAAA,GAAA,CAAA,IAAA9D,SAAA,CAAA,CAAA,CAAA,KAAA+D,SAAA,GAAA/D,SAAA,CAAA,CAAA,CAAA,GAAP,EAAE;MAAfiE,UAAU,GAAAwB,KAAA,CAAVxB,UAAU,CAAA;EACxCN,EAAAA,OAAO,CAAC6B,CAAC,EAAE,UAACnE,GAAG,EAAEkD,GAAG,EAAK;EACvB,IAAA,IAAI1E,OAAO,IAAI0B,UAAU,CAACF,GAAG,CAAC,EAAE;QAC9BkE,CAAC,CAAChB,GAAG,CAAC,GAAG5E,IAAI,CAAC0B,GAAG,EAAExB,OAAO,CAAC,CAAA;EAC7B,KAAC,MAAM;EACL0F,MAAAA,CAAC,CAAChB,GAAG,CAAC,GAAGlD,GAAG,CAAA;EACd,KAAA;EACF,GAAC,EAAE;EAAC4C,IAAAA,UAAU,EAAVA,UAAAA;EAAU,GAAC,CAAC,CAAA;EAChB,EAAA,OAAOsB,CAAC,CAAA;EACV,CAAC,CAAA;;EAED;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMG,QAAQ,GAAG,SAAXA,QAAQA,CAAIC,OAAO,EAAK;IAC5B,IAAIA,OAAO,CAACC,UAAU,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE;EACpCD,IAAAA,OAAO,GAAGA,OAAO,CAACjF,KAAK,CAAC,CAAC,CAAC,CAAA;EAC5B,GAAA;EACA,EAAA,OAAOiF,OAAO,CAAA;EAChB,CAAC,CAAA;;EAED;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAME,QAAQ,GAAG,SAAXA,QAAQA,CAAIvE,WAAW,EAAEwE,gBAAgB,EAAEC,KAAK,EAAEC,WAAW,EAAK;EACtE1E,EAAAA,WAAW,CAACnB,SAAS,GAAGD,MAAM,CAACU,MAAM,CAACkF,gBAAgB,CAAC3F,SAAS,EAAE6F,WAAW,CAAC,CAAA;EAC9E1E,EAAAA,WAAW,CAACnB,SAAS,CAACmB,WAAW,GAAGA,WAAW,CAAA;EAC/CpB,EAAAA,MAAM,CAAC+F,cAAc,CAAC3E,WAAW,EAAE,OAAO,EAAE;MAC1C4E,KAAK,EAAEJ,gBAAgB,CAAC3F,SAAAA;EAC1B,GAAC,CAAC,CAAA;IACF4F,KAAK,IAAI7F,MAAM,CAACiG,MAAM,CAAC7E,WAAW,CAACnB,SAAS,EAAE4F,KAAK,CAAC,CAAA;EACtD,CAAC,CAAA;;EAED;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMK,YAAY,GAAG,SAAfA,YAAYA,CAAIC,SAAS,EAAEC,OAAO,EAAEC,MAAM,EAAEC,UAAU,EAAK;EAC/D,EAAA,IAAIT,KAAK,CAAA;EACT,EAAA,IAAI7B,CAAC,CAAA;EACL,EAAA,IAAIuC,IAAI,CAAA;IACR,IAAMC,MAAM,GAAG,EAAE,CAAA;EAEjBJ,EAAAA,OAAO,GAAGA,OAAO,IAAI,EAAE,CAAA;EACvB;EACA,EAAA,IAAID,SAAS,IAAI,IAAI,EAAE,OAAOC,OAAO,CAAA;IAErC,GAAG;EACDP,IAAAA,KAAK,GAAG7F,MAAM,CAACmE,mBAAmB,CAACgC,SAAS,CAAC,CAAA;MAC7CnC,CAAC,GAAG6B,KAAK,CAACjC,MAAM,CAAA;EAChB,IAAA,OAAOI,CAAC,EAAE,GAAG,CAAC,EAAE;EACduC,MAAAA,IAAI,GAAGV,KAAK,CAAC7B,CAAC,CAAC,CAAA;EACf,MAAA,IAAI,CAAC,CAACsC,UAAU,IAAIA,UAAU,CAACC,IAAI,EAAEJ,SAAS,EAAEC,OAAO,CAAC,KAAK,CAACI,MAAM,CAACD,IAAI,CAAC,EAAE;EAC1EH,QAAAA,OAAO,CAACG,IAAI,CAAC,GAAGJ,SAAS,CAACI,IAAI,CAAC,CAAA;EAC/BC,QAAAA,MAAM,CAACD,IAAI,CAAC,GAAG,IAAI,CAAA;EACrB,OAAA;EACF,KAAA;MACAJ,SAAS,GAAGE,MAAM,KAAK,KAAK,IAAInG,cAAc,CAACiG,SAAS,CAAC,CAAA;EAC3D,GAAC,QAAQA,SAAS,KAAK,CAACE,MAAM,IAAIA,MAAM,CAACF,SAAS,EAAEC,OAAO,CAAC,CAAC,IAAID,SAAS,KAAKnG,MAAM,CAACC,SAAS,EAAA;EAE/F,EAAA,OAAOmG,OAAO,CAAA;EAChB,CAAC,CAAA;;EAED;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMK,QAAQ,GAAG,SAAXA,QAAQA,CAAInG,GAAG,EAAEoG,YAAY,EAAEC,QAAQ,EAAK;EAChDrG,EAAAA,GAAG,GAAGsG,MAAM,CAACtG,GAAG,CAAC,CAAA;IACjB,IAAIqG,QAAQ,KAAK9C,SAAS,IAAI8C,QAAQ,GAAGrG,GAAG,CAACsD,MAAM,EAAE;MACnD+C,QAAQ,GAAGrG,GAAG,CAACsD,MAAM,CAAA;EACvB,GAAA;IACA+C,QAAQ,IAAID,YAAY,CAAC9C,MAAM,CAAA;IAC/B,IAAMiD,SAAS,GAAGvG,GAAG,CAACwG,OAAO,CAACJ,YAAY,EAAEC,QAAQ,CAAC,CAAA;EACrD,EAAA,OAAOE,SAAS,KAAK,CAAC,CAAC,IAAIA,SAAS,KAAKF,QAAQ,CAAA;EACnD,CAAC,CAAA;;EAGD;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMI,OAAO,GAAG,SAAVA,OAAOA,CAAI1G,KAAK,EAAK;EACzB,EAAA,IAAI,CAACA,KAAK,EAAE,OAAO,IAAI,CAAA;EACvB,EAAA,IAAIU,OAAO,CAACV,KAAK,CAAC,EAAE,OAAOA,KAAK,CAAA;EAChC,EAAA,IAAI2D,CAAC,GAAG3D,KAAK,CAACuD,MAAM,CAAA;EACpB,EAAA,IAAI,CAAC/B,QAAQ,CAACmC,CAAC,CAAC,EAAE,OAAO,IAAI,CAAA;EAC7B,EAAA,IAAMgD,GAAG,GAAG,IAAIhG,KAAK,CAACgD,CAAC,CAAC,CAAA;EACxB,EAAA,OAAOA,CAAC,EAAE,GAAG,CAAC,EAAE;EACdgD,IAAAA,GAAG,CAAChD,CAAC,CAAC,GAAG3D,KAAK,CAAC2D,CAAC,CAAC,CAAA;EACnB,GAAA;EACA,EAAA,OAAOgD,GAAG,CAAA;EACZ,CAAC,CAAA;;EAED;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMC,YAAY,GAAI,UAAAC,UAAU,EAAI;EAClC;IACA,OAAO,UAAA7G,KAAK,EAAI;EACd,IAAA,OAAO6G,UAAU,IAAI7G,KAAK,YAAY6G,UAAU,CAAA;KACjD,CAAA;EACH,CAAC,CAAE,OAAOC,UAAU,KAAK,WAAW,IAAIjH,cAAc,CAACiH,UAAU,CAAC,CAAC,CAAA;;EAEnE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMC,YAAY,GAAG,SAAfA,YAAYA,CAAI1D,GAAG,EAAEhE,EAAE,EAAK;IAChC,IAAM2H,SAAS,GAAG3D,GAAG,IAAIA,GAAG,CAACzB,MAAM,CAACE,QAAQ,CAAC,CAAA;EAE7C,EAAA,IAAMA,QAAQ,GAAGkF,SAAS,CAAC9G,IAAI,CAACmD,GAAG,CAAC,CAAA;EAEpC,EAAA,IAAIlC,MAAM,CAAA;EAEV,EAAA,OAAO,CAACA,MAAM,GAAGW,QAAQ,CAACmF,IAAI,EAAE,KAAK,CAAC9F,MAAM,CAAC+F,IAAI,EAAE;EACjD,IAAA,IAAMC,IAAI,GAAGhG,MAAM,CAACwE,KAAK,CAAA;EACzBtG,IAAAA,EAAE,CAACa,IAAI,CAACmD,GAAG,EAAE8D,IAAI,CAAC,CAAC,CAAC,EAAEA,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;EAChC,GAAA;EACF,CAAC,CAAA;;EAED;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMC,QAAQ,GAAG,SAAXA,QAAQA,CAAIC,MAAM,EAAEpH,GAAG,EAAK;EAChC,EAAA,IAAIqH,OAAO,CAAA;IACX,IAAMX,GAAG,GAAG,EAAE,CAAA;IAEd,OAAO,CAACW,OAAO,GAAGD,MAAM,CAACE,IAAI,CAACtH,GAAG,CAAC,MAAM,IAAI,EAAE;EAC5C0G,IAAAA,GAAG,CAACa,IAAI,CAACF,OAAO,CAAC,CAAA;EACnB,GAAA;EAEA,EAAA,OAAOX,GAAG,CAAA;EACZ,CAAC,CAAA;;EAED;EACA,IAAMc,UAAU,GAAGnH,UAAU,CAAC,iBAAiB,CAAC,CAAA;EAEhD,IAAMoH,WAAW,GAAG,SAAdA,WAAWA,CAAGzH,GAAG,EAAI;EACzB,EAAA,OAAOA,GAAG,CAACG,WAAW,EAAE,CAAC+C,OAAO,CAAC,uBAAuB,EACtD,SAASwE,QAAQA,CAACC,CAAC,EAAEC,EAAE,EAAEC,EAAE,EAAE;EAC3B,IAAA,OAAOD,EAAE,CAACE,WAAW,EAAE,GAAGD,EAAE,CAAA;EAC9B,GACF,CAAC,CAAA;EACH,CAAC,CAAA;;EAED;EACA,IAAME,cAAc,GAAI,UAAAC,KAAA,EAAA;EAAA,EAAA,IAAED,cAAc,GAAAC,KAAA,CAAdD,cAAc,CAAA;IAAA,OAAM,UAAC3E,GAAG,EAAE6C,IAAI,EAAA;EAAA,IAAA,OAAK8B,cAAc,CAAC9H,IAAI,CAACmD,GAAG,EAAE6C,IAAI,CAAC,CAAA;EAAA,GAAA,CAAA;EAAA,CAAEvG,CAAAA,MAAM,CAACC,SAAS,CAAC,CAAA;;EAE9G;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMsI,QAAQ,GAAG5H,UAAU,CAAC,QAAQ,CAAC,CAAA;EAErC,IAAM6H,iBAAiB,GAAG,SAApBA,iBAAiBA,CAAI9E,GAAG,EAAE+E,OAAO,EAAK;EAC1C,EAAA,IAAM3C,WAAW,GAAG9F,MAAM,CAAC0I,yBAAyB,CAAChF,GAAG,CAAC,CAAA;IACzD,IAAMiF,kBAAkB,GAAG,EAAE,CAAA;EAE7BlF,EAAAA,OAAO,CAACqC,WAAW,EAAE,UAAC8C,UAAU,EAAEC,IAAI,EAAK;EACzC,IAAA,IAAIC,GAAG,CAAA;EACP,IAAA,IAAI,CAACA,GAAG,GAAGL,OAAO,CAACG,UAAU,EAAEC,IAAI,EAAEnF,GAAG,CAAC,MAAM,KAAK,EAAE;EACpDiF,MAAAA,kBAAkB,CAACE,IAAI,CAAC,GAAGC,GAAG,IAAIF,UAAU,CAAA;EAC9C,KAAA;EACF,GAAC,CAAC,CAAA;EAEF5I,EAAAA,MAAM,CAAC+I,gBAAgB,CAACrF,GAAG,EAAEiF,kBAAkB,CAAC,CAAA;EAClD,CAAC,CAAA;;EAED;EACA;EACA;EACA;;EAEA,IAAMK,aAAa,GAAG,SAAhBA,aAAaA,CAAItF,GAAG,EAAK;EAC7B8E,EAAAA,iBAAiB,CAAC9E,GAAG,EAAE,UAACkF,UAAU,EAAEC,IAAI,EAAK;EAC3C;MACA,IAAIxH,UAAU,CAACqC,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAACoD,OAAO,CAAC+B,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE;EAC7E,MAAA,OAAO,KAAK,CAAA;EACd,KAAA;EAEA,IAAA,IAAM7C,KAAK,GAAGtC,GAAG,CAACmF,IAAI,CAAC,CAAA;EAEvB,IAAA,IAAI,CAACxH,UAAU,CAAC2E,KAAK,CAAC,EAAE,OAAA;MAExB4C,UAAU,CAACK,UAAU,GAAG,KAAK,CAAA;MAE7B,IAAI,UAAU,IAAIL,UAAU,EAAE;QAC5BA,UAAU,CAACM,QAAQ,GAAG,KAAK,CAAA;EAC3B,MAAA,OAAA;EACF,KAAA;EAEA,IAAA,IAAI,CAACN,UAAU,CAACO,GAAG,EAAE;QACnBP,UAAU,CAACO,GAAG,GAAG,YAAM;EACrB,QAAA,MAAMC,KAAK,CAAC,qCAAqC,GAAGP,IAAI,GAAG,IAAI,CAAC,CAAA;SACjE,CAAA;EACH,KAAA;EACF,GAAC,CAAC,CAAA;EACJ,CAAC,CAAA;EAED,IAAMQ,WAAW,GAAG,SAAdA,WAAWA,CAAIC,aAAa,EAAEC,SAAS,EAAK;IAChD,IAAM7F,GAAG,GAAG,EAAE,CAAA;EAEd,EAAA,IAAM8F,MAAM,GAAG,SAATA,MAAMA,CAAIxC,GAAG,EAAK;EACtBA,IAAAA,GAAG,CAACvD,OAAO,CAAC,UAAAuC,KAAK,EAAI;EACnBtC,MAAAA,GAAG,CAACsC,KAAK,CAAC,GAAG,IAAI,CAAA;EACnB,KAAC,CAAC,CAAA;KACH,CAAA;IAEDjF,OAAO,CAACuI,aAAa,CAAC,GAAGE,MAAM,CAACF,aAAa,CAAC,GAAGE,MAAM,CAAC5C,MAAM,CAAC0C,aAAa,CAAC,CAACG,KAAK,CAACF,SAAS,CAAC,CAAC,CAAA;EAE/F,EAAA,OAAO7F,GAAG,CAAA;EACZ,CAAC,CAAA;EAED,IAAMgG,IAAI,GAAG,SAAPA,IAAIA,GAAS,EAAE,CAAA;EAErB,IAAMC,cAAc,GAAG,SAAjBA,cAAcA,CAAI3D,KAAK,EAAE4D,YAAY,EAAK;EAC9C,EAAA,OAAO5D,KAAK,IAAI,IAAI,IAAI6D,MAAM,CAACC,QAAQ,CAAC9D,KAAK,GAAG,CAACA,KAAK,CAAC,GAAGA,KAAK,GAAG4D,YAAY,CAAA;EAChF,CAAC,CAAA;EAED,IAAMG,KAAK,GAAG,4BAA4B,CAAA;EAE1C,IAAMC,KAAK,GAAG,YAAY,CAAA;EAE1B,IAAMC,QAAQ,GAAG;EACfD,EAAAA,KAAK,EAALA,KAAK;EACLD,EAAAA,KAAK,EAALA,KAAK;IACLG,WAAW,EAAEH,KAAK,GAAGA,KAAK,CAAC3B,WAAW,EAAE,GAAG4B,KAAAA;EAC7C,CAAC,CAAA;EAED,IAAMG,cAAc,GAAG,SAAjBA,cAAcA,GAAmD;EAAA,EAAA,IAA/CC,IAAI,GAAAtK,SAAA,CAAA8D,MAAA,GAAA,CAAA,IAAA9D,SAAA,CAAA,CAAA,CAAA,KAAA+D,SAAA,GAAA/D,SAAA,CAAA,CAAA,CAAA,GAAG,EAAE,CAAA;EAAA,EAAA,IAAEuK,QAAQ,GAAAvK,SAAA,CAAA8D,MAAA,GAAA9D,CAAAA,IAAAA,SAAA,CAAA+D,CAAAA,CAAAA,KAAAA,SAAA,GAAA/D,SAAA,CAAGmK,CAAAA,CAAAA,GAAAA,QAAQ,CAACC,WAAW,CAAA;IAChE,IAAI5J,GAAG,GAAG,EAAE,CAAA;EACZ,EAAA,IAAOsD,MAAM,GAAIyG,QAAQ,CAAlBzG,MAAM,CAAA;IACb,OAAOwG,IAAI,EAAE,EAAE;EACb9J,IAAAA,GAAG,IAAI+J,QAAQ,CAACC,IAAI,CAACC,MAAM,EAAE,GAAG3G,MAAM,GAAC,CAAC,CAAC,CAAA;EAC3C,GAAA;EAEA,EAAA,OAAOtD,GAAG,CAAA;EACZ,CAAC,CAAA;;EAED;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASkK,mBAAmBA,CAACnK,KAAK,EAAE;IAClC,OAAO,CAAC,EAAEA,KAAK,IAAIgB,UAAU,CAAChB,KAAK,CAACwC,MAAM,CAAC,IAAIxC,KAAK,CAAC4B,MAAM,CAACC,WAAW,CAAC,KAAK,UAAU,IAAI7B,KAAK,CAAC4B,MAAM,CAACE,QAAQ,CAAC,CAAC,CAAA;EACpH,CAAA;EAEA,IAAMsI,YAAY,GAAG,SAAfA,YAAYA,CAAI/G,GAAG,EAAK;EAC5B,EAAA,IAAMgH,KAAK,GAAG,IAAI1J,KAAK,CAAC,EAAE,CAAC,CAAA;IAE3B,IAAM2J,KAAK,GAAG,SAARA,KAAKA,CAAIC,MAAM,EAAE5G,CAAC,EAAK;EAE3B,IAAA,IAAIlC,QAAQ,CAAC8I,MAAM,CAAC,EAAE;QACpB,IAAIF,KAAK,CAAC5D,OAAO,CAAC8D,MAAM,CAAC,IAAI,CAAC,EAAE;EAC9B,QAAA,OAAA;EACF,OAAA;EAEA,MAAA,IAAG,EAAE,QAAQ,IAAIA,MAAM,CAAC,EAAE;EACxBF,QAAAA,KAAK,CAAC1G,CAAC,CAAC,GAAG4G,MAAM,CAAA;UACjB,IAAMC,MAAM,GAAG9J,OAAO,CAAC6J,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,CAAA;EAExCnH,QAAAA,OAAO,CAACmH,MAAM,EAAE,UAAC5E,KAAK,EAAE3B,GAAG,EAAK;YAC9B,IAAMyG,YAAY,GAAGH,KAAK,CAAC3E,KAAK,EAAEhC,CAAC,GAAG,CAAC,CAAC,CAAA;YACxC,CAAC/C,WAAW,CAAC6J,YAAY,CAAC,KAAKD,MAAM,CAACxG,GAAG,CAAC,GAAGyG,YAAY,CAAC,CAAA;EAC5D,SAAC,CAAC,CAAA;EAEFJ,QAAAA,KAAK,CAAC1G,CAAC,CAAC,GAAGH,SAAS,CAAA;EAEpB,QAAA,OAAOgH,MAAM,CAAA;EACf,OAAA;EACF,KAAA;EAEA,IAAA,OAAOD,MAAM,CAAA;KACd,CAAA;EAED,EAAA,OAAOD,KAAK,CAACjH,GAAG,EAAE,CAAC,CAAC,CAAA;EACtB,CAAC,CAAA;EAED,IAAMqH,SAAS,GAAGpK,UAAU,CAAC,eAAe,CAAC,CAAA;EAE7C,IAAMqK,UAAU,GAAG,SAAbA,UAAUA,CAAI3K,KAAK,EAAA;IAAA,OACvBA,KAAK,KAAKyB,QAAQ,CAACzB,KAAK,CAAC,IAAIgB,UAAU,CAAChB,KAAK,CAAC,CAAC,IAAIgB,UAAU,CAAChB,KAAK,CAAC4K,IAAI,CAAC,IAAI5J,UAAU,CAAChB,KAAK,CAAA,OAAA,CAAM,CAAC,CAAA;EAAA,CAAA,CAAA;;EAEtG;EACA;;EAEA,IAAM6K,aAAa,GAAI,UAACC,qBAAqB,EAAEC,oBAAoB,EAAK;EACtE,EAAA,IAAID,qBAAqB,EAAE;EACzB,IAAA,OAAOE,YAAY,CAAA;EACrB,GAAA;EAEA,EAAA,OAAOD,oBAAoB,GAAI,UAACE,KAAK,EAAEC,SAAS,EAAK;EACnD/G,IAAAA,OAAO,CAACgH,gBAAgB,CAAC,SAAS,EAAE,UAAAC,KAAA,EAAoB;EAAA,MAAA,IAAlBb,MAAM,GAAAa,KAAA,CAANb,MAAM;UAAEc,IAAI,GAAAD,KAAA,CAAJC,IAAI,CAAA;EAChD,MAAA,IAAId,MAAM,KAAKpG,OAAO,IAAIkH,IAAI,KAAKJ,KAAK,EAAE;UACxCC,SAAS,CAAC3H,MAAM,IAAI2H,SAAS,CAACI,KAAK,EAAE,EAAE,CAAA;EACzC,OAAA;OACD,EAAE,KAAK,CAAC,CAAA;MAET,OAAO,UAACC,EAAE,EAAK;EACbL,MAAAA,SAAS,CAAC1D,IAAI,CAAC+D,EAAE,CAAC,CAAA;EAClBpH,MAAAA,OAAO,CAACqH,WAAW,CAACP,KAAK,EAAE,GAAG,CAAC,CAAA;OAChC,CAAA;EACH,GAAC,CAAAQ,QAAAA,CAAAA,MAAA,CAAWxB,IAAI,CAACC,MAAM,EAAE,CAAI,EAAA,EAAE,CAAC,GAAG,UAACqB,EAAE,EAAA;MAAA,OAAKG,UAAU,CAACH,EAAE,CAAC,CAAA;EAAA,GAAA,CAAA;EAC3D,CAAC,CACC,OAAOP,YAAY,KAAK,UAAU,EAClChK,UAAU,CAACmD,OAAO,CAACqH,WAAW,CAChC,CAAC,CAAA;EAED,IAAMG,IAAI,GAAG,OAAOC,cAAc,KAAK,WAAW,GAChDA,cAAc,CAACxM,IAAI,CAAC+E,OAAO,CAAC,GAAK,OAAO0H,OAAO,KAAK,WAAW,IAAIA,OAAO,CAACC,QAAQ,IAAIjB,aAAc,CAAA;;EAEvG;;AAEA,gBAAe;EACbnK,EAAAA,OAAO,EAAPA,OAAO;EACPO,EAAAA,aAAa,EAAbA,aAAa;EACbJ,EAAAA,QAAQ,EAARA,QAAQ;EACRwB,EAAAA,UAAU,EAAVA,UAAU;EACVnB,EAAAA,iBAAiB,EAAjBA,iBAAiB;EACjBK,EAAAA,QAAQ,EAARA,QAAQ;EACRC,EAAAA,QAAQ,EAARA,QAAQ;EACRE,EAAAA,SAAS,EAATA,SAAS;EACTD,EAAAA,QAAQ,EAARA,QAAQ;EACRE,EAAAA,aAAa,EAAbA,aAAa;EACbmB,EAAAA,gBAAgB,EAAhBA,gBAAgB;EAChBC,EAAAA,SAAS,EAATA,SAAS;EACTC,EAAAA,UAAU,EAAVA,UAAU;EACVC,EAAAA,SAAS,EAATA,SAAS;EACTrC,EAAAA,WAAW,EAAXA,WAAW;EACXmB,EAAAA,MAAM,EAANA,MAAM;EACNC,EAAAA,MAAM,EAANA,MAAM;EACNC,EAAAA,MAAM,EAANA,MAAM;EACNiG,EAAAA,QAAQ,EAARA,QAAQ;EACRlH,EAAAA,UAAU,EAAVA,UAAU;EACVmB,EAAAA,QAAQ,EAARA,QAAQ;EACRM,EAAAA,iBAAiB,EAAjBA,iBAAiB;EACjBmE,EAAAA,YAAY,EAAZA,YAAY;EACZ1E,EAAAA,UAAU,EAAVA,UAAU;EACVkB,EAAAA,OAAO,EAAPA,OAAO;EACPsB,EAAAA,KAAK,EAALA,KAAK;EACLK,EAAAA,MAAM,EAANA,MAAM;EACN7B,EAAAA,IAAI,EAAJA,IAAI;EACJiC,EAAAA,QAAQ,EAARA,QAAQ;EACRG,EAAAA,QAAQ,EAARA,QAAQ;EACRO,EAAAA,YAAY,EAAZA,YAAY;EACZ/F,EAAAA,MAAM,EAANA,MAAM;EACNQ,EAAAA,UAAU,EAAVA,UAAU;EACV8F,EAAAA,QAAQ,EAARA,QAAQ;EACRM,EAAAA,OAAO,EAAPA,OAAO;EACPK,EAAAA,YAAY,EAAZA,YAAY;EACZK,EAAAA,QAAQ,EAARA,QAAQ;EACRK,EAAAA,UAAU,EAAVA,UAAU;EACVO,EAAAA,cAAc,EAAdA,cAAc;EACd+D,EAAAA,UAAU,EAAE/D,cAAc;EAAE;EAC5BG,EAAAA,iBAAiB,EAAjBA,iBAAiB;EACjBQ,EAAAA,aAAa,EAAbA,aAAa;EACbK,EAAAA,WAAW,EAAXA,WAAW;EACXtB,EAAAA,WAAW,EAAXA,WAAW;EACX2B,EAAAA,IAAI,EAAJA,IAAI;EACJC,EAAAA,cAAc,EAAdA,cAAc;EACdrF,EAAAA,OAAO,EAAPA,OAAO;EACPM,EAAAA,MAAM,EAAEJ,OAAO;EACfK,EAAAA,gBAAgB,EAAhBA,gBAAgB;EAChBoF,EAAAA,QAAQ,EAARA,QAAQ;EACRE,EAAAA,cAAc,EAAdA,cAAc;EACdK,EAAAA,mBAAmB,EAAnBA,mBAAmB;EACnBC,EAAAA,YAAY,EAAZA,YAAY;EACZM,EAAAA,SAAS,EAATA,SAAS;EACTC,EAAAA,UAAU,EAAVA,UAAU;EACVK,EAAAA,YAAY,EAAEH,aAAa;EAC3Bc,EAAAA,IAAI,EAAJA,IAAAA;EACF,CAAC;;ECnvBD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASK,UAAUA,CAACC,OAAO,EAAEC,IAAI,EAAEC,MAAM,EAAEC,OAAO,EAAEC,QAAQ,EAAE;EAC5DtD,EAAAA,KAAK,CAAC7I,IAAI,CAAC,IAAI,CAAC,CAAA;IAEhB,IAAI6I,KAAK,CAACuD,iBAAiB,EAAE;MAC3BvD,KAAK,CAACuD,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAACvL,WAAW,CAAC,CAAA;EACjD,GAAC,MAAM;MACL,IAAI,CAACsJ,KAAK,GAAI,IAAItB,KAAK,EAAE,CAAEsB,KAAK,CAAA;EAClC,GAAA;IAEA,IAAI,CAAC4B,OAAO,GAAGA,OAAO,CAAA;IACtB,IAAI,CAACzD,IAAI,GAAG,YAAY,CAAA;EACxB0D,EAAAA,IAAI,KAAK,IAAI,CAACA,IAAI,GAAGA,IAAI,CAAC,CAAA;EAC1BC,EAAAA,MAAM,KAAK,IAAI,CAACA,MAAM,GAAGA,MAAM,CAAC,CAAA;EAChCC,EAAAA,OAAO,KAAK,IAAI,CAACA,OAAO,GAAGA,OAAO,CAAC,CAAA;EACnC,EAAA,IAAIC,QAAQ,EAAE;MACZ,IAAI,CAACA,QAAQ,GAAGA,QAAQ,CAAA;MACxB,IAAI,CAACE,MAAM,GAAGF,QAAQ,CAACE,MAAM,GAAGF,QAAQ,CAACE,MAAM,GAAG,IAAI,CAAA;EACxD,GAAA;EACF,CAAA;AAEAC,SAAK,CAAClH,QAAQ,CAAC0G,UAAU,EAAEjD,KAAK,EAAE;EAChC0D,EAAAA,MAAM,EAAE,SAASA,MAAMA,GAAG;MACxB,OAAO;EACL;QACAR,OAAO,EAAE,IAAI,CAACA,OAAO;QACrBzD,IAAI,EAAE,IAAI,CAACA,IAAI;EACf;QACAkE,WAAW,EAAE,IAAI,CAACA,WAAW;QAC7BC,MAAM,EAAE,IAAI,CAACA,MAAM;EACnB;QACAC,QAAQ,EAAE,IAAI,CAACA,QAAQ;QACvBC,UAAU,EAAE,IAAI,CAACA,UAAU;QAC3BC,YAAY,EAAE,IAAI,CAACA,YAAY;QAC/BzC,KAAK,EAAE,IAAI,CAACA,KAAK;EACjB;QACA8B,MAAM,EAAEK,OAAK,CAACpC,YAAY,CAAC,IAAI,CAAC+B,MAAM,CAAC;QACvCD,IAAI,EAAE,IAAI,CAACA,IAAI;QACfK,MAAM,EAAE,IAAI,CAACA,MAAAA;OACd,CAAA;EACH,GAAA;EACF,CAAC,CAAC,CAAA;EAEF,IAAM3M,WAAS,GAAGoM,UAAU,CAACpM,SAAS,CAAA;EACtC,IAAM6F,WAAW,GAAG,EAAE,CAAA;EAEtB,CACE,sBAAsB,EACtB,gBAAgB,EAChB,cAAc,EACd,WAAW,EACX,aAAa,EACb,2BAA2B,EAC3B,gBAAgB,EAChB,kBAAkB,EAClB,iBAAiB,EACjB,cAAc,EACd,iBAAiB,EACjB,iBAAA;EACF;EAAA,CACC,CAACrC,OAAO,CAAC,UAAA8I,IAAI,EAAI;IAChBzG,WAAW,CAACyG,IAAI,CAAC,GAAG;EAACvG,IAAAA,KAAK,EAAEuG,IAAAA;KAAK,CAAA;EACnC,CAAC,CAAC,CAAA;EAEFvM,MAAM,CAAC+I,gBAAgB,CAACsD,UAAU,EAAEvG,WAAW,CAAC,CAAA;EAChD9F,MAAM,CAAC+F,cAAc,CAAC9F,WAAS,EAAE,cAAc,EAAE;EAAC+F,EAAAA,KAAK,EAAE,IAAA;EAAI,CAAC,CAAC,CAAA;;EAE/D;EACAqG,UAAU,CAACe,IAAI,GAAG,UAACC,KAAK,EAAEd,IAAI,EAAEC,MAAM,EAAEC,OAAO,EAAEC,QAAQ,EAAEY,WAAW,EAAK;EACzE,EAAA,IAAMC,UAAU,GAAGvN,MAAM,CAACU,MAAM,CAACT,WAAS,CAAC,CAAA;IAE3C4M,OAAK,CAAC3G,YAAY,CAACmH,KAAK,EAAEE,UAAU,EAAE,SAASlH,MAAMA,CAAC3C,GAAG,EAAE;EACzD,IAAA,OAAOA,GAAG,KAAK0F,KAAK,CAACnJ,SAAS,CAAA;KAC/B,EAAE,UAAAsG,IAAI,EAAI;MACT,OAAOA,IAAI,KAAK,cAAc,CAAA;EAChC,GAAC,CAAC,CAAA;EAEF8F,EAAAA,UAAU,CAAC9L,IAAI,CAACgN,UAAU,EAAEF,KAAK,CAACf,OAAO,EAAEC,IAAI,EAAEC,MAAM,EAAEC,OAAO,EAAEC,QAAQ,CAAC,CAAA;IAE3Ea,UAAU,CAACC,KAAK,GAAGH,KAAK,CAAA;EAExBE,EAAAA,UAAU,CAAC1E,IAAI,GAAGwE,KAAK,CAACxE,IAAI,CAAA;IAE5ByE,WAAW,IAAItN,MAAM,CAACiG,MAAM,CAACsH,UAAU,EAAED,WAAW,CAAC,CAAA;EAErD,EAAA,OAAOC,UAAU,CAAA;EACnB,CAAC;;ECpGD;AACA,oBAAe,IAAI;;ECMnB;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASE,WAAWA,CAACpN,KAAK,EAAE;EAC1B,EAAA,OAAOwM,OAAK,CAAC7K,aAAa,CAAC3B,KAAK,CAAC,IAAIwM,OAAK,CAAC9L,OAAO,CAACV,KAAK,CAAC,CAAA;EAC3D,CAAA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASqN,cAAcA,CAACrJ,GAAG,EAAE;EAC3B,EAAA,OAAOwI,OAAK,CAACpG,QAAQ,CAACpC,GAAG,EAAE,IAAI,CAAC,GAAGA,GAAG,CAAC7D,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG6D,GAAG,CAAA;EAC3D,CAAA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASsJ,SAASA,CAACC,IAAI,EAAEvJ,GAAG,EAAEwJ,IAAI,EAAE;EAClC,EAAA,IAAI,CAACD,IAAI,EAAE,OAAOvJ,GAAG,CAAA;EACrB,EAAA,OAAOuJ,IAAI,CAAC9B,MAAM,CAACzH,GAAG,CAAC,CAACrB,GAAG,CAAC,SAAS8K,IAAIA,CAACxC,KAAK,EAAEtH,CAAC,EAAE;EAClD;EACAsH,IAAAA,KAAK,GAAGoC,cAAc,CAACpC,KAAK,CAAC,CAAA;MAC7B,OAAO,CAACuC,IAAI,IAAI7J,CAAC,GAAG,GAAG,GAAGsH,KAAK,GAAG,GAAG,GAAGA,KAAK,CAAA;KAC9C,CAAC,CAACyC,IAAI,CAACF,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC,CAAA;EAC1B,CAAA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASG,WAAWA,CAAChH,GAAG,EAAE;EACxB,EAAA,OAAO6F,OAAK,CAAC9L,OAAO,CAACiG,GAAG,CAAC,IAAI,CAACA,GAAG,CAACiH,IAAI,CAACR,WAAW,CAAC,CAAA;EACrD,CAAA;EAEA,IAAMS,UAAU,GAAGrB,OAAK,CAAC3G,YAAY,CAAC2G,OAAK,EAAE,EAAE,EAAE,IAAI,EAAE,SAASxG,MAAMA,CAACE,IAAI,EAAE;EAC3E,EAAA,OAAO,UAAU,CAAC4H,IAAI,CAAC5H,IAAI,CAAC,CAAA;EAC9B,CAAC,CAAC,CAAA;;EAEF;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAAS6H,UAAUA,CAAC1K,GAAG,EAAE2K,QAAQ,EAAEC,OAAO,EAAE;EAC1C,EAAA,IAAI,CAACzB,OAAK,CAAC/K,QAAQ,CAAC4B,GAAG,CAAC,EAAE;EACxB,IAAA,MAAM,IAAI6K,SAAS,CAAC,0BAA0B,CAAC,CAAA;EACjD,GAAA;;EAEA;IACAF,QAAQ,GAAGA,QAAQ,IAAI,KAAyBzL,QAAQ,GAAG,CAAA;;EAE3D;EACA0L,EAAAA,OAAO,GAAGzB,OAAK,CAAC3G,YAAY,CAACoI,OAAO,EAAE;EACpCE,IAAAA,UAAU,EAAE,IAAI;EAChBX,IAAAA,IAAI,EAAE,KAAK;EACXY,IAAAA,OAAO,EAAE,KAAA;KACV,EAAE,KAAK,EAAE,SAASC,OAAOA,CAACC,MAAM,EAAE/D,MAAM,EAAE;EACzC;MACA,OAAO,CAACiC,OAAK,CAAC5L,WAAW,CAAC2J,MAAM,CAAC+D,MAAM,CAAC,CAAC,CAAA;EAC3C,GAAC,CAAC,CAAA;EAEF,EAAA,IAAMH,UAAU,GAAGF,OAAO,CAACE,UAAU,CAAA;EACrC;EACA,EAAA,IAAMI,OAAO,GAAGN,OAAO,CAACM,OAAO,IAAIC,cAAc,CAAA;EACjD,EAAA,IAAMhB,IAAI,GAAGS,OAAO,CAACT,IAAI,CAAA;EACzB,EAAA,IAAMY,OAAO,GAAGH,OAAO,CAACG,OAAO,CAAA;IAC/B,IAAMK,KAAK,GAAGR,OAAO,CAACS,IAAI,IAAI,OAAOA,IAAI,KAAK,WAAW,IAAIA,IAAI,CAAA;IACjE,IAAMC,OAAO,GAAGF,KAAK,IAAIjC,OAAK,CAACrC,mBAAmB,CAAC6D,QAAQ,CAAC,CAAA;EAE5D,EAAA,IAAI,CAACxB,OAAK,CAACxL,UAAU,CAACuN,OAAO,CAAC,EAAE;EAC9B,IAAA,MAAM,IAAIL,SAAS,CAAC,4BAA4B,CAAC,CAAA;EACnD,GAAA;IAEA,SAASU,YAAYA,CAACjJ,KAAK,EAAE;EAC3B,IAAA,IAAIA,KAAK,KAAK,IAAI,EAAE,OAAO,EAAE,CAAA;EAE7B,IAAA,IAAI6G,OAAK,CAACzK,MAAM,CAAC4D,KAAK,CAAC,EAAE;EACvB,MAAA,OAAOA,KAAK,CAACkJ,WAAW,EAAE,CAAA;EAC5B,KAAA;MAEA,IAAI,CAACF,OAAO,IAAInC,OAAK,CAACvK,MAAM,CAAC0D,KAAK,CAAC,EAAE;EACnC,MAAA,MAAM,IAAIqG,UAAU,CAAC,8CAA8C,CAAC,CAAA;EACtE,KAAA;EAEA,IAAA,IAAIQ,OAAK,CAACvL,aAAa,CAAC0E,KAAK,CAAC,IAAI6G,OAAK,CAAC5F,YAAY,CAACjB,KAAK,CAAC,EAAE;QAC3D,OAAOgJ,OAAO,IAAI,OAAOD,IAAI,KAAK,UAAU,GAAG,IAAIA,IAAI,CAAC,CAAC/I,KAAK,CAAC,CAAC,GAAGmJ,MAAM,CAAC/B,IAAI,CAACpH,KAAK,CAAC,CAAA;EACvF,KAAA;EAEA,IAAA,OAAOA,KAAK,CAAA;EACd,GAAA;;EAEA;EACF;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACE,EAAA,SAAS6I,cAAcA,CAAC7I,KAAK,EAAE3B,GAAG,EAAEuJ,IAAI,EAAE;MACxC,IAAI5G,GAAG,GAAGhB,KAAK,CAAA;MAEf,IAAIA,KAAK,IAAI,CAAC4H,IAAI,IAAI9M,OAAA,CAAOkF,KAAK,CAAK,KAAA,QAAQ,EAAE;QAC/C,IAAI6G,OAAK,CAACpG,QAAQ,CAACpC,GAAG,EAAE,IAAI,CAAC,EAAE;EAC7B;EACAA,QAAAA,GAAG,GAAGmK,UAAU,GAAGnK,GAAG,GAAGA,GAAG,CAAC7D,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;EACzC;EACAwF,QAAAA,KAAK,GAAGoJ,IAAI,CAACC,SAAS,CAACrJ,KAAK,CAAC,CAAA;EAC/B,OAAC,MAAM,IACJ6G,OAAK,CAAC9L,OAAO,CAACiF,KAAK,CAAC,IAAIgI,WAAW,CAAChI,KAAK,CAAC,IAC1C,CAAC6G,OAAK,CAACtK,UAAU,CAACyD,KAAK,CAAC,IAAI6G,OAAK,CAACpG,QAAQ,CAACpC,GAAG,EAAE,IAAI,CAAC,MAAM2C,GAAG,GAAG6F,OAAK,CAAC9F,OAAO,CAACf,KAAK,CAAC,CACrF,EAAE;EACH;EACA3B,QAAAA,GAAG,GAAGqJ,cAAc,CAACrJ,GAAG,CAAC,CAAA;UAEzB2C,GAAG,CAACvD,OAAO,CAAC,SAASqK,IAAIA,CAACwB,EAAE,EAAEC,KAAK,EAAE;EACnC,UAAA,EAAE1C,OAAK,CAAC5L,WAAW,CAACqO,EAAE,CAAC,IAAIA,EAAE,KAAK,IAAI,CAAC,IAAIjB,QAAQ,CAACxL,MAAM;EACxD;EACA4L,UAAAA,OAAO,KAAK,IAAI,GAAGd,SAAS,CAAC,CAACtJ,GAAG,CAAC,EAAEkL,KAAK,EAAE1B,IAAI,CAAC,GAAIY,OAAO,KAAK,IAAI,GAAGpK,GAAG,GAAGA,GAAG,GAAG,IAAK,EACxF4K,YAAY,CAACK,EAAE,CACjB,CAAC,CAAA;EACH,SAAC,CAAC,CAAA;EACF,QAAA,OAAO,KAAK,CAAA;EACd,OAAA;EACF,KAAA;EAEA,IAAA,IAAI7B,WAAW,CAACzH,KAAK,CAAC,EAAE;EACtB,MAAA,OAAO,IAAI,CAAA;EACb,KAAA;EAEAqI,IAAAA,QAAQ,CAACxL,MAAM,CAAC8K,SAAS,CAACC,IAAI,EAAEvJ,GAAG,EAAEwJ,IAAI,CAAC,EAAEoB,YAAY,CAACjJ,KAAK,CAAC,CAAC,CAAA;EAEhE,IAAA,OAAO,KAAK,CAAA;EACd,GAAA;IAEA,IAAM0E,KAAK,GAAG,EAAE,CAAA;EAEhB,EAAA,IAAM8E,cAAc,GAAGxP,MAAM,CAACiG,MAAM,CAACiI,UAAU,EAAE;EAC/CW,IAAAA,cAAc,EAAdA,cAAc;EACdI,IAAAA,YAAY,EAAZA,YAAY;EACZxB,IAAAA,WAAW,EAAXA,WAAAA;EACF,GAAC,CAAC,CAAA;EAEF,EAAA,SAASgC,KAAKA,CAACzJ,KAAK,EAAE4H,IAAI,EAAE;EAC1B,IAAA,IAAIf,OAAK,CAAC5L,WAAW,CAAC+E,KAAK,CAAC,EAAE,OAAA;MAE9B,IAAI0E,KAAK,CAAC5D,OAAO,CAACd,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE;QAC/B,MAAMoD,KAAK,CAAC,iCAAiC,GAAGwE,IAAI,CAACG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;EACjE,KAAA;EAEArD,IAAAA,KAAK,CAAC7C,IAAI,CAAC7B,KAAK,CAAC,CAAA;MAEjB6G,OAAK,CAACpJ,OAAO,CAACuC,KAAK,EAAE,SAAS8H,IAAIA,CAACwB,EAAE,EAAEjL,GAAG,EAAE;EAC1C,MAAA,IAAM7C,MAAM,GAAG,EAAEqL,OAAK,CAAC5L,WAAW,CAACqO,EAAE,CAAC,IAAIA,EAAE,KAAK,IAAI,CAAC,IAAIV,OAAO,CAACrO,IAAI,CACpE8N,QAAQ,EAAEiB,EAAE,EAAEzC,OAAK,CAACjL,QAAQ,CAACyC,GAAG,CAAC,GAAGA,GAAG,CAACd,IAAI,EAAE,GAAGc,GAAG,EAAEuJ,IAAI,EAAE4B,cAC9D,CAAC,CAAA;QAED,IAAIhO,MAAM,KAAK,IAAI,EAAE;EACnBiO,QAAAA,KAAK,CAACH,EAAE,EAAE1B,IAAI,GAAGA,IAAI,CAAC9B,MAAM,CAACzH,GAAG,CAAC,GAAG,CAACA,GAAG,CAAC,CAAC,CAAA;EAC5C,OAAA;EACF,KAAC,CAAC,CAAA;MAEFqG,KAAK,CAACgF,GAAG,EAAE,CAAA;EACb,GAAA;EAEA,EAAA,IAAI,CAAC7C,OAAK,CAAC/K,QAAQ,CAAC4B,GAAG,CAAC,EAAE;EACxB,IAAA,MAAM,IAAI6K,SAAS,CAAC,wBAAwB,CAAC,CAAA;EAC/C,GAAA;IAEAkB,KAAK,CAAC/L,GAAG,CAAC,CAAA;EAEV,EAAA,OAAO2K,QAAQ,CAAA;EACjB;;ECpNA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASsB,QAAMA,CAACrP,GAAG,EAAE;EACnB,EAAA,IAAMsP,OAAO,GAAG;EACd,IAAA,GAAG,EAAE,KAAK;EACV,IAAA,GAAG,EAAE,KAAK;EACV,IAAA,GAAG,EAAE,KAAK;EACV,IAAA,GAAG,EAAE,KAAK;EACV,IAAA,GAAG,EAAE,KAAK;EACV,IAAA,KAAK,EAAE,GAAG;EACV,IAAA,KAAK,EAAE,MAAA;KACR,CAAA;EACD,EAAA,OAAOC,kBAAkB,CAACvP,GAAG,CAAC,CAACkD,OAAO,CAAC,kBAAkB,EAAE,SAASwE,QAAQA,CAAC8H,KAAK,EAAE;MAClF,OAAOF,OAAO,CAACE,KAAK,CAAC,CAAA;EACvB,GAAC,CAAC,CAAA;EACJ,CAAA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASC,oBAAoBA,CAACC,MAAM,EAAE1B,OAAO,EAAE;IAC7C,IAAI,CAAC2B,MAAM,GAAG,EAAE,CAAA;IAEhBD,MAAM,IAAI5B,UAAU,CAAC4B,MAAM,EAAE,IAAI,EAAE1B,OAAO,CAAC,CAAA;EAC7C,CAAA;EAEA,IAAMrO,SAAS,GAAG8P,oBAAoB,CAAC9P,SAAS,CAAA;EAEhDA,SAAS,CAAC4C,MAAM,GAAG,SAASA,MAAMA,CAACgG,IAAI,EAAE7C,KAAK,EAAE;IAC9C,IAAI,CAACiK,MAAM,CAACpI,IAAI,CAAC,CAACgB,IAAI,EAAE7C,KAAK,CAAC,CAAC,CAAA;EACjC,CAAC,CAAA;EAED/F,SAAS,CAACF,QAAQ,GAAG,SAASA,QAAQA,CAACmQ,OAAO,EAAE;EAC9C,EAAA,IAAMC,OAAO,GAAGD,OAAO,GAAG,UAASlK,KAAK,EAAE;MACxC,OAAOkK,OAAO,CAAC3P,IAAI,CAAC,IAAI,EAAEyF,KAAK,EAAE2J,QAAM,CAAC,CAAA;EAC1C,GAAC,GAAGA,QAAM,CAAA;IAEV,OAAO,IAAI,CAACM,MAAM,CAACjN,GAAG,CAAC,SAAS8K,IAAIA,CAACtG,IAAI,EAAE;EACzC,IAAA,OAAO2I,OAAO,CAAC3I,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG2I,OAAO,CAAC3I,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;EAClD,GAAC,EAAE,EAAE,CAAC,CAACuG,IAAI,CAAC,GAAG,CAAC,CAAA;EAClB,CAAC;;EClDD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAAS4B,MAAMA,CAACxO,GAAG,EAAE;IACnB,OAAO0O,kBAAkB,CAAC1O,GAAG,CAAC,CAC5BqC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CACrBA,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CACpBA,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CACrBA,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CACpBA,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CACrBA,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;EACzB,CAAA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACe,SAAS4M,QAAQA,CAACC,GAAG,EAAEL,MAAM,EAAE1B,OAAO,EAAE;EACrD;IACA,IAAI,CAAC0B,MAAM,EAAE;EACX,IAAA,OAAOK,GAAG,CAAA;EACZ,GAAA;IAEA,IAAMF,OAAO,GAAG7B,OAAO,IAAIA,OAAO,CAACqB,MAAM,IAAIA,MAAM,CAAA;EAEnD,EAAA,IAAI9C,OAAK,CAACxL,UAAU,CAACiN,OAAO,CAAC,EAAE;EAC7BA,IAAAA,OAAO,GAAG;EACRgC,MAAAA,SAAS,EAAEhC,OAAAA;OACZ,CAAA;EACH,GAAA;EAEA,EAAA,IAAMiC,WAAW,GAAGjC,OAAO,IAAIA,OAAO,CAACgC,SAAS,CAAA;EAEhD,EAAA,IAAIE,gBAAgB,CAAA;EAEpB,EAAA,IAAID,WAAW,EAAE;EACfC,IAAAA,gBAAgB,GAAGD,WAAW,CAACP,MAAM,EAAE1B,OAAO,CAAC,CAAA;EACjD,GAAC,MAAM;MACLkC,gBAAgB,GAAG3D,OAAK,CAAC/J,iBAAiB,CAACkN,MAAM,CAAC,GAChDA,MAAM,CAACjQ,QAAQ,EAAE,GACjB,IAAIgQ,oBAAoB,CAACC,MAAM,EAAE1B,OAAO,CAAC,CAACvO,QAAQ,CAACoQ,OAAO,CAAC,CAAA;EAC/D,GAAA;EAEA,EAAA,IAAIK,gBAAgB,EAAE;EACpB,IAAA,IAAMC,aAAa,GAAGJ,GAAG,CAACvJ,OAAO,CAAC,GAAG,CAAC,CAAA;EAEtC,IAAA,IAAI2J,aAAa,KAAK,CAAC,CAAC,EAAE;QACxBJ,GAAG,GAAGA,GAAG,CAAC7P,KAAK,CAAC,CAAC,EAAEiQ,aAAa,CAAC,CAAA;EACnC,KAAA;EACAJ,IAAAA,GAAG,IAAI,CAACA,GAAG,CAACvJ,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG,IAAI0J,gBAAgB,CAAA;EACjE,GAAA;EAEA,EAAA,OAAOH,GAAG,CAAA;EACZ;;EClEkC,IAE5BK,kBAAkB,gBAAA,YAAA;EACtB,EAAA,SAAAA,qBAAc;EAAAC,IAAAA,eAAA,OAAAD,kBAAA,CAAA,CAAA;MACZ,IAAI,CAACE,QAAQ,GAAG,EAAE,CAAA;EACpB,GAAA;;EAEA;EACF;EACA;EACA;EACA;EACA;EACA;EACA;EAPEC,EAAAA,YAAA,CAAAH,kBAAA,EAAA,CAAA;MAAArM,GAAA,EAAA,KAAA;MAAA2B,KAAA,EAQA,SAAA8K,GAAIC,CAAAA,SAAS,EAAEC,QAAQ,EAAE1C,OAAO,EAAE;EAChC,MAAA,IAAI,CAACsC,QAAQ,CAAC/I,IAAI,CAAC;EACjBkJ,QAAAA,SAAS,EAATA,SAAS;EACTC,QAAAA,QAAQ,EAARA,QAAQ;EACRC,QAAAA,WAAW,EAAE3C,OAAO,GAAGA,OAAO,CAAC2C,WAAW,GAAG,KAAK;EAClDC,QAAAA,OAAO,EAAE5C,OAAO,GAAGA,OAAO,CAAC4C,OAAO,GAAG,IAAA;EACvC,OAAC,CAAC,CAAA;EACF,MAAA,OAAO,IAAI,CAACN,QAAQ,CAAChN,MAAM,GAAG,CAAC,CAAA;EACjC,KAAA;;EAEA;EACF;EACA;EACA;EACA;EACA;EACA;EANE,GAAA,EAAA;MAAAS,GAAA,EAAA,OAAA;EAAA2B,IAAAA,KAAA,EAOA,SAAAmL,KAAMC,CAAAA,EAAE,EAAE;EACR,MAAA,IAAI,IAAI,CAACR,QAAQ,CAACQ,EAAE,CAAC,EAAE;EACrB,QAAA,IAAI,CAACR,QAAQ,CAACQ,EAAE,CAAC,GAAG,IAAI,CAAA;EAC1B,OAAA;EACF,KAAA;;EAEA;EACF;EACA;EACA;EACA;EAJE,GAAA,EAAA;MAAA/M,GAAA,EAAA,OAAA;MAAA2B,KAAA,EAKA,SAAAqL,KAAAA,GAAQ;QACN,IAAI,IAAI,CAACT,QAAQ,EAAE;UACjB,IAAI,CAACA,QAAQ,GAAG,EAAE,CAAA;EACpB,OAAA;EACF,KAAA;;EAEA;EACF;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EATE,GAAA,EAAA;MAAAvM,GAAA,EAAA,SAAA;EAAA2B,IAAAA,KAAA,EAUA,SAAAvC,OAAQ/D,CAAAA,EAAE,EAAE;QACVmN,OAAK,CAACpJ,OAAO,CAAC,IAAI,CAACmN,QAAQ,EAAE,SAASU,cAAcA,CAACC,CAAC,EAAE;UACtD,IAAIA,CAAC,KAAK,IAAI,EAAE;YACd7R,EAAE,CAAC6R,CAAC,CAAC,CAAA;EACP,SAAA;EACF,OAAC,CAAC,CAAA;EACJ,KAAA;EAAC,GAAA,CAAA,CAAA,CAAA;EAAA,EAAA,OAAAb,kBAAA,CAAA;EAAA,CAAA,EAAA,CAAA;AAGH,6BAAeA,kBAAkB;;ACpEjC,6BAAe;EACbc,EAAAA,iBAAiB,EAAE,IAAI;EACvBC,EAAAA,iBAAiB,EAAE,IAAI;EACvBC,EAAAA,mBAAmB,EAAE,KAAA;EACvB,CAAC;;ACHD,0BAAe,OAAOC,eAAe,KAAK,WAAW,GAAGA,eAAe,GAAG5B,oBAAoB;;ACD9F,mBAAe,OAAOnN,QAAQ,KAAK,WAAW,GAAGA,QAAQ,GAAG,IAAI;;ACAhE,eAAe,OAAOmM,IAAI,KAAK,WAAW,GAAGA,IAAI,GAAG,IAAI;;ACExD,mBAAe;EACb6C,EAAAA,SAAS,EAAE,IAAI;EACfC,EAAAA,OAAO,EAAE;EACPF,IAAAA,eAAe,EAAfA,iBAAe;EACf/O,IAAAA,QAAQ,EAARA,UAAQ;EACRmM,IAAAA,IAAI,EAAJA,MAAAA;KACD;EACD+C,EAAAA,SAAS,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAA;EAC5D,CAAC;;ECZD,IAAMC,aAAa,GAAG,OAAOpN,MAAM,KAAK,WAAW,IAAI,OAAOqN,QAAQ,KAAK,WAAW,CAAA;EAEtF,IAAMC,UAAU,GAAG,CAAOC,OAAAA,SAAS,KAAApR,WAAAA,GAAAA,WAAAA,GAAAA,OAAA,CAAToR,SAAS,CAAK,MAAA,QAAQ,IAAIA,SAAS,IAAIrO,SAAS,CAAA;;EAE1E;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMsO,qBAAqB,GAAGJ,aAAa,KACxC,CAACE,UAAU,IAAI,CAAC,aAAa,EAAE,cAAc,EAAE,IAAI,CAAC,CAACnL,OAAO,CAACmL,UAAU,CAACG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;;EAExF;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,IAAMC,8BAA8B,GAAI,YAAM;IAC5C,OACE,OAAOC,iBAAiB,KAAK,WAAW;EACxC;IACA5N,IAAI,YAAY4N,iBAAiB,IACjC,OAAO5N,IAAI,CAAC6N,aAAa,KAAK,UAAU,CAAA;EAE5C,CAAC,EAAG,CAAA;EAEJ,IAAMC,MAAM,GAAGT,aAAa,IAAIpN,MAAM,CAAC8N,QAAQ,CAACC,IAAI,IAAI,kBAAkB;;;;;;;;;;;ACvC1E,iBAAAC,cAAA,CAAAA,cAAA,CACK9F,EAAAA,EAAAA,KAAK,GACL+F,UAAQ,CAAA;;ECCE,SAASC,gBAAgBA,CAACnH,IAAI,EAAE4C,OAAO,EAAE;EACtD,EAAA,OAAOF,UAAU,CAAC1C,IAAI,EAAE,IAAIkH,QAAQ,CAACf,OAAO,CAACF,eAAe,EAAE,EAAE3R,MAAM,CAACiG,MAAM,CAAC;MAC5E2I,OAAO,EAAE,SAAAA,OAAAA,CAAS5I,KAAK,EAAE3B,GAAG,EAAEuJ,IAAI,EAAEkF,OAAO,EAAE;QAC3C,IAAIF,QAAQ,CAACG,MAAM,IAAIlG,OAAK,CAAC3L,QAAQ,CAAC8E,KAAK,CAAC,EAAE;UAC5C,IAAI,CAACnD,MAAM,CAACwB,GAAG,EAAE2B,KAAK,CAACjG,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAA;EAC1C,QAAA,OAAO,KAAK,CAAA;EACd,OAAA;QAEA,OAAO+S,OAAO,CAACjE,cAAc,CAAChP,KAAK,CAAC,IAAI,EAAEC,SAAS,CAAC,CAAA;EACtD,KAAA;KACD,EAAEwO,OAAO,CAAC,CAAC,CAAA;EACd;;ECbA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAAS0E,aAAaA,CAACnK,IAAI,EAAE;EAC3B;EACA;EACA;EACA;EACA,EAAA,OAAOgE,OAAK,CAACpF,QAAQ,CAAC,eAAe,EAAEoB,IAAI,CAAC,CAAC7F,GAAG,CAAC,UAAA8M,KAAK,EAAI;EACxD,IAAA,OAAOA,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,EAAE,GAAGA,KAAK,CAAC,CAAC,CAAC,IAAIA,KAAK,CAAC,CAAC,CAAC,CAAA;EACtD,GAAC,CAAC,CAAA;EACJ,CAAA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASmD,aAAaA,CAACjM,GAAG,EAAE;IAC1B,IAAMtD,GAAG,GAAG,EAAE,CAAA;EACd,EAAA,IAAMQ,IAAI,GAAGlE,MAAM,CAACkE,IAAI,CAAC8C,GAAG,CAAC,CAAA;EAC7B,EAAA,IAAIhD,CAAC,CAAA;EACL,EAAA,IAAMI,GAAG,GAAGF,IAAI,CAACN,MAAM,CAAA;EACvB,EAAA,IAAIS,GAAG,CAAA;IACP,KAAKL,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGI,GAAG,EAAEJ,CAAC,EAAE,EAAE;EACxBK,IAAAA,GAAG,GAAGH,IAAI,CAACF,CAAC,CAAC,CAAA;EACbN,IAAAA,GAAG,CAACW,GAAG,CAAC,GAAG2C,GAAG,CAAC3C,GAAG,CAAC,CAAA;EACrB,GAAA;EACA,EAAA,OAAOX,GAAG,CAAA;EACZ,CAAA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASwP,cAAcA,CAAC7E,QAAQ,EAAE;IAChC,SAAS8E,SAASA,CAACvF,IAAI,EAAE5H,KAAK,EAAE6E,MAAM,EAAE0E,KAAK,EAAE;EAC7C,IAAA,IAAI1G,IAAI,GAAG+E,IAAI,CAAC2B,KAAK,EAAE,CAAC,CAAA;EAExB,IAAA,IAAI1G,IAAI,KAAK,WAAW,EAAE,OAAO,IAAI,CAAA;MAErC,IAAMuK,YAAY,GAAGvJ,MAAM,CAACC,QAAQ,CAAC,CAACjB,IAAI,CAAC,CAAA;EAC3C,IAAA,IAAMwK,MAAM,GAAG9D,KAAK,IAAI3B,IAAI,CAAChK,MAAM,CAAA;EACnCiF,IAAAA,IAAI,GAAG,CAACA,IAAI,IAAIgE,OAAK,CAAC9L,OAAO,CAAC8J,MAAM,CAAC,GAAGA,MAAM,CAACjH,MAAM,GAAGiF,IAAI,CAAA;EAE5D,IAAA,IAAIwK,MAAM,EAAE;QACV,IAAIxG,OAAK,CAACT,UAAU,CAACvB,MAAM,EAAEhC,IAAI,CAAC,EAAE;UAClCgC,MAAM,CAAChC,IAAI,CAAC,GAAG,CAACgC,MAAM,CAAChC,IAAI,CAAC,EAAE7C,KAAK,CAAC,CAAA;EACtC,OAAC,MAAM;EACL6E,QAAAA,MAAM,CAAChC,IAAI,CAAC,GAAG7C,KAAK,CAAA;EACtB,OAAA;EAEA,MAAA,OAAO,CAACoN,YAAY,CAAA;EACtB,KAAA;EAEA,IAAA,IAAI,CAACvI,MAAM,CAAChC,IAAI,CAAC,IAAI,CAACgE,OAAK,CAAC/K,QAAQ,CAAC+I,MAAM,CAAChC,IAAI,CAAC,CAAC,EAAE;EAClDgC,MAAAA,MAAM,CAAChC,IAAI,CAAC,GAAG,EAAE,CAAA;EACnB,KAAA;EAEA,IAAA,IAAMrH,MAAM,GAAG2R,SAAS,CAACvF,IAAI,EAAE5H,KAAK,EAAE6E,MAAM,CAAChC,IAAI,CAAC,EAAE0G,KAAK,CAAC,CAAA;MAE1D,IAAI/N,MAAM,IAAIqL,OAAK,CAAC9L,OAAO,CAAC8J,MAAM,CAAChC,IAAI,CAAC,CAAC,EAAE;QACzCgC,MAAM,CAAChC,IAAI,CAAC,GAAGoK,aAAa,CAACpI,MAAM,CAAChC,IAAI,CAAC,CAAC,CAAA;EAC5C,KAAA;EAEA,IAAA,OAAO,CAACuK,YAAY,CAAA;EACtB,GAAA;EAEA,EAAA,IAAIvG,OAAK,CAACnK,UAAU,CAAC2L,QAAQ,CAAC,IAAIxB,OAAK,CAACxL,UAAU,CAACgN,QAAQ,CAACiF,OAAO,CAAC,EAAE;MACpE,IAAM5P,GAAG,GAAG,EAAE,CAAA;MAEdmJ,OAAK,CAACzF,YAAY,CAACiH,QAAQ,EAAE,UAACxF,IAAI,EAAE7C,KAAK,EAAK;QAC5CmN,SAAS,CAACH,aAAa,CAACnK,IAAI,CAAC,EAAE7C,KAAK,EAAEtC,GAAG,EAAE,CAAC,CAAC,CAAA;EAC/C,KAAC,CAAC,CAAA;EAEF,IAAA,OAAOA,GAAG,CAAA;EACZ,GAAA;EAEA,EAAA,OAAO,IAAI,CAAA;EACb;;EClFA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAAS6P,eAAeA,CAACC,QAAQ,EAAEC,MAAM,EAAEvD,OAAO,EAAE;EAClD,EAAA,IAAIrD,OAAK,CAACjL,QAAQ,CAAC4R,QAAQ,CAAC,EAAE;MAC5B,IAAI;EACF,MAAA,CAACC,MAAM,IAAIrE,IAAI,CAACsE,KAAK,EAAEF,QAAQ,CAAC,CAAA;EAChC,MAAA,OAAO3G,OAAK,CAACtJ,IAAI,CAACiQ,QAAQ,CAAC,CAAA;OAC5B,CAAC,OAAOG,CAAC,EAAE;EACV,MAAA,IAAIA,CAAC,CAAC9K,IAAI,KAAK,aAAa,EAAE;EAC5B,QAAA,MAAM8K,CAAC,CAAA;EACT,OAAA;EACF,KAAA;EACF,GAAA;IAEA,OAAO,CAACzD,OAAO,IAAId,IAAI,CAACC,SAAS,EAAEmE,QAAQ,CAAC,CAAA;EAC9C,CAAA;EAEA,IAAMI,QAAQ,GAAG;EAEfC,EAAAA,YAAY,EAAEC,oBAAoB;EAElCC,EAAAA,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC;IAEjCC,gBAAgB,EAAE,CAAC,SAASA,gBAAgBA,CAACtI,IAAI,EAAEuI,OAAO,EAAE;MAC1D,IAAMC,WAAW,GAAGD,OAAO,CAACE,cAAc,EAAE,IAAI,EAAE,CAAA;MAClD,IAAMC,kBAAkB,GAAGF,WAAW,CAACpN,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAA;EACvE,IAAA,IAAMuN,eAAe,GAAGxH,OAAK,CAAC/K,QAAQ,CAAC4J,IAAI,CAAC,CAAA;MAE5C,IAAI2I,eAAe,IAAIxH,OAAK,CAAC/E,UAAU,CAAC4D,IAAI,CAAC,EAAE;EAC7CA,MAAAA,IAAI,GAAG,IAAI9I,QAAQ,CAAC8I,IAAI,CAAC,CAAA;EAC3B,KAAA;EAEA,IAAA,IAAMhJ,UAAU,GAAGmK,OAAK,CAACnK,UAAU,CAACgJ,IAAI,CAAC,CAAA;EAEzC,IAAA,IAAIhJ,UAAU,EAAE;EACd,MAAA,OAAO0R,kBAAkB,GAAGhF,IAAI,CAACC,SAAS,CAAC6D,cAAc,CAACxH,IAAI,CAAC,CAAC,GAAGA,IAAI,CAAA;EACzE,KAAA;EAEA,IAAA,IAAImB,OAAK,CAACvL,aAAa,CAACoK,IAAI,CAAC,IAC3BmB,OAAK,CAAC3L,QAAQ,CAACwK,IAAI,CAAC,IACpBmB,OAAK,CAACrK,QAAQ,CAACkJ,IAAI,CAAC,IACpBmB,OAAK,CAACxK,MAAM,CAACqJ,IAAI,CAAC,IAClBmB,OAAK,CAACvK,MAAM,CAACoJ,IAAI,CAAC,IAClBmB,OAAK,CAAC1J,gBAAgB,CAACuI,IAAI,CAAC,EAC5B;EACA,MAAA,OAAOA,IAAI,CAAA;EACb,KAAA;EACA,IAAA,IAAImB,OAAK,CAACtL,iBAAiB,CAACmK,IAAI,CAAC,EAAE;QACjC,OAAOA,IAAI,CAAC/J,MAAM,CAAA;EACpB,KAAA;EACA,IAAA,IAAIkL,OAAK,CAAC/J,iBAAiB,CAAC4I,IAAI,CAAC,EAAE;EACjCuI,MAAAA,OAAO,CAACK,cAAc,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAA;EAChF,MAAA,OAAO5I,IAAI,CAAC3L,QAAQ,EAAE,CAAA;EACxB,KAAA;EAEA,IAAA,IAAIwC,UAAU,CAAA;EAEd,IAAA,IAAI8R,eAAe,EAAE;QACnB,IAAIH,WAAW,CAACpN,OAAO,CAAC,mCAAmC,CAAC,GAAG,CAAC,CAAC,EAAE;UACjE,OAAO+L,gBAAgB,CAACnH,IAAI,EAAE,IAAI,CAAC6I,cAAc,CAAC,CAACxU,QAAQ,EAAE,CAAA;EAC/D,OAAA;EAEA,MAAA,IAAI,CAACwC,UAAU,GAAGsK,OAAK,CAACtK,UAAU,CAACmJ,IAAI,CAAC,KAAKwI,WAAW,CAACpN,OAAO,CAAC,qBAAqB,CAAC,GAAG,CAAC,CAAC,EAAE;UAC5F,IAAM0N,SAAS,GAAG,IAAI,CAACC,GAAG,IAAI,IAAI,CAACA,GAAG,CAAC7R,QAAQ,CAAA;UAE/C,OAAOwL,UAAU,CACf7L,UAAU,GAAG;EAAC,UAAA,SAAS,EAAEmJ,IAAAA;EAAI,SAAC,GAAGA,IAAI,EACrC8I,SAAS,IAAI,IAAIA,SAAS,EAAE,EAC5B,IAAI,CAACD,cACP,CAAC,CAAA;EACH,OAAA;EACF,KAAA;MAEA,IAAIF,eAAe,IAAID,kBAAkB,EAAG;EAC1CH,MAAAA,OAAO,CAACK,cAAc,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAA;QACjD,OAAOf,eAAe,CAAC7H,IAAI,CAAC,CAAA;EAC9B,KAAA;EAEA,IAAA,OAAOA,IAAI,CAAA;EACb,GAAC,CAAC;EAEFgJ,EAAAA,iBAAiB,EAAE,CAAC,SAASA,iBAAiBA,CAAChJ,IAAI,EAAE;MACnD,IAAMmI,YAAY,GAAG,IAAI,CAACA,YAAY,IAAID,QAAQ,CAACC,YAAY,CAAA;EAC/D,IAAA,IAAMpC,iBAAiB,GAAGoC,YAAY,IAAIA,YAAY,CAACpC,iBAAiB,CAAA;EACxE,IAAA,IAAMkD,aAAa,GAAG,IAAI,CAACC,YAAY,KAAK,MAAM,CAAA;EAElD,IAAA,IAAI/H,OAAK,CAACxJ,UAAU,CAACqI,IAAI,CAAC,IAAImB,OAAK,CAAC1J,gBAAgB,CAACuI,IAAI,CAAC,EAAE;EAC1D,MAAA,OAAOA,IAAI,CAAA;EACb,KAAA;EAEA,IAAA,IAAIA,IAAI,IAAImB,OAAK,CAACjL,QAAQ,CAAC8J,IAAI,CAAC,KAAM+F,iBAAiB,IAAI,CAAC,IAAI,CAACmD,YAAY,IAAKD,aAAa,CAAC,EAAE;EAChG,MAAA,IAAMnD,iBAAiB,GAAGqC,YAAY,IAAIA,YAAY,CAACrC,iBAAiB,CAAA;EACxE,MAAA,IAAMqD,iBAAiB,GAAG,CAACrD,iBAAiB,IAAImD,aAAa,CAAA;QAE7D,IAAI;EACF,QAAA,OAAOvF,IAAI,CAACsE,KAAK,CAAChI,IAAI,CAAC,CAAA;SACxB,CAAC,OAAOiI,CAAC,EAAE;EACV,QAAA,IAAIkB,iBAAiB,EAAE;EACrB,UAAA,IAAIlB,CAAC,CAAC9K,IAAI,KAAK,aAAa,EAAE;EAC5B,YAAA,MAAMwD,UAAU,CAACe,IAAI,CAACuG,CAAC,EAAEtH,UAAU,CAACyI,gBAAgB,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAACpI,QAAQ,CAAC,CAAA;EAClF,WAAA;EACA,UAAA,MAAMiH,CAAC,CAAA;EACT,SAAA;EACF,OAAA;EACF,KAAA;EAEA,IAAA,OAAOjI,IAAI,CAAA;EACb,GAAC,CAAC;EAEF;EACF;EACA;EACA;EACEqJ,EAAAA,OAAO,EAAE,CAAC;EAEVC,EAAAA,cAAc,EAAE,YAAY;EAC5BC,EAAAA,cAAc,EAAE,cAAc;IAE9BC,gBAAgB,EAAE,CAAC,CAAC;IACpBC,aAAa,EAAE,CAAC,CAAC;EAEjBV,EAAAA,GAAG,EAAE;EACH7R,IAAAA,QAAQ,EAAEgQ,QAAQ,CAACf,OAAO,CAACjP,QAAQ;EACnCmM,IAAAA,IAAI,EAAE6D,QAAQ,CAACf,OAAO,CAAC9C,IAAAA;KACxB;EAEDqG,EAAAA,cAAc,EAAE,SAASA,cAAcA,CAACxI,MAAM,EAAE;EAC9C,IAAA,OAAOA,MAAM,IAAI,GAAG,IAAIA,MAAM,GAAG,GAAG,CAAA;KACrC;EAEDqH,EAAAA,OAAO,EAAE;EACPoB,IAAAA,MAAM,EAAE;EACN,MAAA,QAAQ,EAAE,mCAAmC;EAC7C,MAAA,cAAc,EAAExR,SAAAA;EAClB,KAAA;EACF,GAAA;EACF,CAAC,CAAA;AAEDgJ,SAAK,CAACpJ,OAAO,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,UAAC6R,MAAM,EAAK;EAC3E1B,EAAAA,QAAQ,CAACK,OAAO,CAACqB,MAAM,CAAC,GAAG,EAAE,CAAA;EAC/B,CAAC,CAAC,CAAA;AAEF,mBAAe1B,QAAQ;;EC5JvB;EACA;EACA,IAAM2B,iBAAiB,GAAG1I,OAAK,CAACxD,WAAW,CAAC,CAC1C,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,EAChE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,EAAE,qBAAqB,EACrE,eAAe,EAAE,UAAU,EAAE,cAAc,EAAE,qBAAqB,EAClE,SAAS,EAAE,aAAa,EAAE,YAAY,CACvC,CAAC,CAAA;;EAEF;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AACA,qBAAe,CAAA,UAAAmM,UAAU,EAAI;IAC3B,IAAMC,MAAM,GAAG,EAAE,CAAA;EACjB,EAAA,IAAIpR,GAAG,CAAA;EACP,EAAA,IAAIlD,GAAG,CAAA;EACP,EAAA,IAAI6C,CAAC,CAAA;EAELwR,EAAAA,UAAU,IAAIA,UAAU,CAAC/L,KAAK,CAAC,IAAI,CAAC,CAAChG,OAAO,CAAC,SAASgQ,MAAMA,CAACiC,IAAI,EAAE;EACjE1R,IAAAA,CAAC,GAAG0R,IAAI,CAAC5O,OAAO,CAAC,GAAG,CAAC,CAAA;EACrBzC,IAAAA,GAAG,GAAGqR,IAAI,CAACC,SAAS,CAAC,CAAC,EAAE3R,CAAC,CAAC,CAACT,IAAI,EAAE,CAAC9C,WAAW,EAAE,CAAA;EAC/CU,IAAAA,GAAG,GAAGuU,IAAI,CAACC,SAAS,CAAC3R,CAAC,GAAG,CAAC,CAAC,CAACT,IAAI,EAAE,CAAA;EAElC,IAAA,IAAI,CAACc,GAAG,IAAKoR,MAAM,CAACpR,GAAG,CAAC,IAAIkR,iBAAiB,CAAClR,GAAG,CAAE,EAAE;EACnD,MAAA,OAAA;EACF,KAAA;MAEA,IAAIA,GAAG,KAAK,YAAY,EAAE;EACxB,MAAA,IAAIoR,MAAM,CAACpR,GAAG,CAAC,EAAE;EACfoR,QAAAA,MAAM,CAACpR,GAAG,CAAC,CAACwD,IAAI,CAAC1G,GAAG,CAAC,CAAA;EACvB,OAAC,MAAM;EACLsU,QAAAA,MAAM,CAACpR,GAAG,CAAC,GAAG,CAAClD,GAAG,CAAC,CAAA;EACrB,OAAA;EACF,KAAC,MAAM;EACLsU,MAAAA,MAAM,CAACpR,GAAG,CAAC,GAAGoR,MAAM,CAACpR,GAAG,CAAC,GAAGoR,MAAM,CAACpR,GAAG,CAAC,GAAG,IAAI,GAAGlD,GAAG,GAAGA,GAAG,CAAA;EAC5D,KAAA;EACF,GAAC,CAAC,CAAA;EAEF,EAAA,OAAOsU,MAAM,CAAA;EACf,CAAC;;ECjDD,IAAMG,UAAU,GAAG3T,MAAM,CAAC,WAAW,CAAC,CAAA;EAEtC,SAAS4T,eAAeA,CAACC,MAAM,EAAE;EAC/B,EAAA,OAAOA,MAAM,IAAIlP,MAAM,CAACkP,MAAM,CAAC,CAACvS,IAAI,EAAE,CAAC9C,WAAW,EAAE,CAAA;EACtD,CAAA;EAEA,SAASsV,cAAcA,CAAC/P,KAAK,EAAE;EAC7B,EAAA,IAAIA,KAAK,KAAK,KAAK,IAAIA,KAAK,IAAI,IAAI,EAAE;EACpC,IAAA,OAAOA,KAAK,CAAA;EACd,GAAA;EAEA,EAAA,OAAO6G,OAAK,CAAC9L,OAAO,CAACiF,KAAK,CAAC,GAAGA,KAAK,CAAChD,GAAG,CAAC+S,cAAc,CAAC,GAAGnP,MAAM,CAACZ,KAAK,CAAC,CAAA;EACzE,CAAA;EAEA,SAASgQ,WAAWA,CAAC1V,GAAG,EAAE;EACxB,EAAA,IAAM2V,MAAM,GAAGjW,MAAM,CAACU,MAAM,CAAC,IAAI,CAAC,CAAA;IAClC,IAAMwV,QAAQ,GAAG,kCAAkC,CAAA;EACnD,EAAA,IAAIpG,KAAK,CAAA;IAET,OAAQA,KAAK,GAAGoG,QAAQ,CAACtO,IAAI,CAACtH,GAAG,CAAC,EAAG;MACnC2V,MAAM,CAACnG,KAAK,CAAC,CAAC,CAAC,CAAC,GAAGA,KAAK,CAAC,CAAC,CAAC,CAAA;EAC7B,GAAA;EAEA,EAAA,OAAOmG,MAAM,CAAA;EACf,CAAA;EAEA,IAAME,iBAAiB,GAAG,SAApBA,iBAAiBA,CAAI7V,GAAG,EAAA;IAAA,OAAK,gCAAgC,CAAC6N,IAAI,CAAC7N,GAAG,CAACiD,IAAI,EAAE,CAAC,CAAA;EAAA,CAAA,CAAA;EAEpF,SAAS6S,gBAAgBA,CAACtR,OAAO,EAAEkB,KAAK,EAAE8P,MAAM,EAAEzP,MAAM,EAAEgQ,kBAAkB,EAAE;EAC5E,EAAA,IAAIxJ,OAAK,CAACxL,UAAU,CAACgF,MAAM,CAAC,EAAE;MAC5B,OAAOA,MAAM,CAAC9F,IAAI,CAAC,IAAI,EAAEyF,KAAK,EAAE8P,MAAM,CAAC,CAAA;EACzC,GAAA;EAEA,EAAA,IAAIO,kBAAkB,EAAE;EACtBrQ,IAAAA,KAAK,GAAG8P,MAAM,CAAA;EAChB,GAAA;EAEA,EAAA,IAAI,CAACjJ,OAAK,CAACjL,QAAQ,CAACoE,KAAK,CAAC,EAAE,OAAA;EAE5B,EAAA,IAAI6G,OAAK,CAACjL,QAAQ,CAACyE,MAAM,CAAC,EAAE;MAC1B,OAAOL,KAAK,CAACc,OAAO,CAACT,MAAM,CAAC,KAAK,CAAC,CAAC,CAAA;EACrC,GAAA;EAEA,EAAA,IAAIwG,OAAK,CAACtE,QAAQ,CAAClC,MAAM,CAAC,EAAE;EAC1B,IAAA,OAAOA,MAAM,CAAC8H,IAAI,CAACnI,KAAK,CAAC,CAAA;EAC3B,GAAA;EACF,CAAA;EAEA,SAASsQ,YAAYA,CAACR,MAAM,EAAE;IAC5B,OAAOA,MAAM,CAACvS,IAAI,EAAE,CACjB9C,WAAW,EAAE,CAAC+C,OAAO,CAAC,iBAAiB,EAAE,UAAC+S,CAAC,EAAEC,KAAI,EAAElW,GAAG,EAAK;EAC1D,IAAA,OAAOkW,KAAI,CAACpO,WAAW,EAAE,GAAG9H,GAAG,CAAA;EACjC,GAAC,CAAC,CAAA;EACN,CAAA;EAEA,SAASmW,cAAcA,CAAC/S,GAAG,EAAEoS,MAAM,EAAE;IACnC,IAAMY,YAAY,GAAG7J,OAAK,CAAC9E,WAAW,CAAC,GAAG,GAAG+N,MAAM,CAAC,CAAA;IAEpD,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAACrS,OAAO,CAAC,UAAAkT,UAAU,EAAI;MAC1C3W,MAAM,CAAC+F,cAAc,CAACrC,GAAG,EAAEiT,UAAU,GAAGD,YAAY,EAAE;QACpD1Q,KAAK,EAAE,SAAAA,KAAS4Q,CAAAA,IAAI,EAAEC,IAAI,EAAEC,IAAI,EAAE;EAChC,QAAA,OAAO,IAAI,CAACH,UAAU,CAAC,CAACpW,IAAI,CAAC,IAAI,EAAEuV,MAAM,EAAEc,IAAI,EAAEC,IAAI,EAAEC,IAAI,CAAC,CAAA;SAC7D;EACDC,MAAAA,YAAY,EAAE,IAAA;EAChB,KAAC,CAAC,CAAA;EACJ,GAAC,CAAC,CAAA;EACJ,CAAA;EAAC,IAEKC,YAAY,gBAAA,UAAAC,gBAAA,EAAAC,mBAAA,EAAA;IAChB,SAAAF,YAAAA,CAAY/C,OAAO,EAAE;EAAAtD,IAAAA,eAAA,OAAAqG,YAAA,CAAA,CAAA;EACnB/C,IAAAA,OAAO,IAAI,IAAI,CAAC9K,GAAG,CAAC8K,OAAO,CAAC,CAAA;EAC9B,GAAA;EAACpD,EAAAA,YAAA,CAAAmG,YAAA,EAAA,CAAA;MAAA3S,GAAA,EAAA,KAAA;MAAA2B,KAAA,EAED,SAAAmD,GAAI2M,CAAAA,MAAM,EAAEqB,cAAc,EAAEC,OAAO,EAAE;QACnC,IAAM1S,IAAI,GAAG,IAAI,CAAA;EAEjB,MAAA,SAAS2S,SAASA,CAACC,MAAM,EAAEC,OAAO,EAAEC,QAAQ,EAAE;EAC5C,QAAA,IAAMC,OAAO,GAAG5B,eAAe,CAAC0B,OAAO,CAAC,CAAA;UAExC,IAAI,CAACE,OAAO,EAAE;EACZ,UAAA,MAAM,IAAIrO,KAAK,CAAC,wCAAwC,CAAC,CAAA;EAC3D,SAAA;UAEA,IAAM/E,GAAG,GAAGwI,OAAK,CAACvI,OAAO,CAACI,IAAI,EAAE+S,OAAO,CAAC,CAAA;UAExC,IAAG,CAACpT,GAAG,IAAIK,IAAI,CAACL,GAAG,CAAC,KAAKR,SAAS,IAAI2T,QAAQ,KAAK,IAAI,IAAKA,QAAQ,KAAK3T,SAAS,IAAIa,IAAI,CAACL,GAAG,CAAC,KAAK,KAAM,EAAE;YAC1GK,IAAI,CAACL,GAAG,IAAIkT,OAAO,CAAC,GAAGxB,cAAc,CAACuB,MAAM,CAAC,CAAA;EAC/C,SAAA;EACF,OAAA;EAEA,MAAA,IAAMI,UAAU,GAAG,SAAbA,UAAUA,CAAIzD,OAAO,EAAEuD,QAAQ,EAAA;UAAA,OACnC3K,OAAK,CAACpJ,OAAO,CAACwQ,OAAO,EAAE,UAACqD,MAAM,EAAEC,OAAO,EAAA;EAAA,UAAA,OAAKF,SAAS,CAACC,MAAM,EAAEC,OAAO,EAAEC,QAAQ,CAAC,CAAA;WAAC,CAAA,CAAA;EAAA,OAAA,CAAA;EAEnF,MAAA,IAAI3K,OAAK,CAAC7K,aAAa,CAAC8T,MAAM,CAAC,IAAIA,MAAM,YAAY,IAAI,CAAC1U,WAAW,EAAE;EACrEsW,QAAAA,UAAU,CAAC5B,MAAM,EAAEqB,cAAc,CAAC,CAAA;SACnC,MAAM,IAAGtK,OAAK,CAACjL,QAAQ,CAACkU,MAAM,CAAC,KAAKA,MAAM,GAAGA,MAAM,CAACvS,IAAI,EAAE,CAAC,IAAI,CAAC4S,iBAAiB,CAACL,MAAM,CAAC,EAAE;EAC1F4B,QAAAA,UAAU,CAACC,YAAY,CAAC7B,MAAM,CAAC,EAAEqB,cAAc,CAAC,CAAA;SACjD,MAAM,IAAItK,OAAK,CAACvJ,SAAS,CAACwS,MAAM,CAAC,EAAE;UAAA,IAAA8B,SAAA,GAAAC,0BAAA,CACP/B,MAAM,CAACxC,OAAO,EAAE,CAAA;YAAAwE,KAAA,CAAA;EAAA,QAAA,IAAA;YAA3C,KAAAF,SAAA,CAAAG,CAAA,EAAAD,EAAAA,CAAAA,CAAAA,KAAA,GAAAF,SAAA,CAAAI,CAAA,EAAAzQ,EAAAA,IAAA,GAA6C;EAAA,YAAA,IAAA0Q,WAAA,GAAA/U,cAAA,CAAA4U,KAAA,CAAA9R,KAAA,EAAA,CAAA,CAAA;EAAjC3B,cAAAA,GAAG,GAAA4T,WAAA,CAAA,CAAA,CAAA;EAAEjS,cAAAA,KAAK,GAAAiS,WAAA,CAAA,CAAA,CAAA,CAAA;EACpBZ,YAAAA,SAAS,CAACrR,KAAK,EAAE3B,GAAG,EAAE+S,OAAO,CAAC,CAAA;EAChC,WAAA;EAAC,SAAA,CAAA,OAAAc,GAAA,EAAA;YAAAN,SAAA,CAAAjE,CAAA,CAAAuE,GAAA,CAAA,CAAA;EAAA,SAAA,SAAA;EAAAN,UAAAA,SAAA,CAAAO,CAAA,EAAA,CAAA;EAAA,SAAA;EACH,OAAC,MAAM;UACLrC,MAAM,IAAI,IAAI,IAAIuB,SAAS,CAACF,cAAc,EAAErB,MAAM,EAAEsB,OAAO,CAAC,CAAA;EAC9D,OAAA;EAEA,MAAA,OAAO,IAAI,CAAA;EACb,KAAA;EAAC,GAAA,EAAA;MAAA/S,GAAA,EAAA,KAAA;EAAA2B,IAAAA,KAAA,EAED,SAAAoS,GAAAA,CAAItC,MAAM,EAAErC,MAAM,EAAE;EAClBqC,MAAAA,MAAM,GAAGD,eAAe,CAACC,MAAM,CAAC,CAAA;EAEhC,MAAA,IAAIA,MAAM,EAAE;UACV,IAAMzR,GAAG,GAAGwI,OAAK,CAACvI,OAAO,CAAC,IAAI,EAAEwR,MAAM,CAAC,CAAA;EAEvC,QAAA,IAAIzR,GAAG,EAAE;EACP,UAAA,IAAM2B,KAAK,GAAG,IAAI,CAAC3B,GAAG,CAAC,CAAA;YAEvB,IAAI,CAACoP,MAAM,EAAE;EACX,YAAA,OAAOzN,KAAK,CAAA;EACd,WAAA;YAEA,IAAIyN,MAAM,KAAK,IAAI,EAAE;cACnB,OAAOuC,WAAW,CAAChQ,KAAK,CAAC,CAAA;EAC3B,WAAA;EAEA,UAAA,IAAI6G,OAAK,CAACxL,UAAU,CAACoS,MAAM,CAAC,EAAE;cAC5B,OAAOA,MAAM,CAAClT,IAAI,CAAC,IAAI,EAAEyF,KAAK,EAAE3B,GAAG,CAAC,CAAA;EACtC,WAAA;EAEA,UAAA,IAAIwI,OAAK,CAACtE,QAAQ,CAACkL,MAAM,CAAC,EAAE;EAC1B,YAAA,OAAOA,MAAM,CAAC7L,IAAI,CAAC5B,KAAK,CAAC,CAAA;EAC3B,WAAA;EAEA,UAAA,MAAM,IAAIuI,SAAS,CAAC,wCAAwC,CAAC,CAAA;EAC/D,SAAA;EACF,OAAA;EACF,KAAA;EAAC,GAAA,EAAA;MAAAlK,GAAA,EAAA,KAAA;EAAA2B,IAAAA,KAAA,EAED,SAAAqS,GAAAA,CAAIvC,MAAM,EAAEwC,OAAO,EAAE;EACnBxC,MAAAA,MAAM,GAAGD,eAAe,CAACC,MAAM,CAAC,CAAA;EAEhC,MAAA,IAAIA,MAAM,EAAE;UACV,IAAMzR,GAAG,GAAGwI,OAAK,CAACvI,OAAO,CAAC,IAAI,EAAEwR,MAAM,CAAC,CAAA;EAEvC,QAAA,OAAO,CAAC,EAAEzR,GAAG,IAAI,IAAI,CAACA,GAAG,CAAC,KAAKR,SAAS,KAAK,CAACyU,OAAO,IAAIlC,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC/R,GAAG,CAAC,EAAEA,GAAG,EAAEiU,OAAO,CAAC,CAAC,CAAC,CAAA;EAC5G,OAAA;EAEA,MAAA,OAAO,KAAK,CAAA;EACd,KAAA;EAAC,GAAA,EAAA;MAAAjU,GAAA,EAAA,QAAA;EAAA2B,IAAAA,KAAA,EAED,SAAAuS,OAAAA,CAAOzC,MAAM,EAAEwC,OAAO,EAAE;QACtB,IAAM5T,IAAI,GAAG,IAAI,CAAA;QACjB,IAAI8T,OAAO,GAAG,KAAK,CAAA;QAEnB,SAASC,YAAYA,CAAClB,OAAO,EAAE;EAC7BA,QAAAA,OAAO,GAAG1B,eAAe,CAAC0B,OAAO,CAAC,CAAA;EAElC,QAAA,IAAIA,OAAO,EAAE;YACX,IAAMlT,GAAG,GAAGwI,OAAK,CAACvI,OAAO,CAACI,IAAI,EAAE6S,OAAO,CAAC,CAAA;EAExC,UAAA,IAAIlT,GAAG,KAAK,CAACiU,OAAO,IAAIlC,gBAAgB,CAAC1R,IAAI,EAAEA,IAAI,CAACL,GAAG,CAAC,EAAEA,GAAG,EAAEiU,OAAO,CAAC,CAAC,EAAE;cACxE,OAAO5T,IAAI,CAACL,GAAG,CAAC,CAAA;EAEhBmU,YAAAA,OAAO,GAAG,IAAI,CAAA;EAChB,WAAA;EACF,SAAA;EACF,OAAA;EAEA,MAAA,IAAI3L,OAAK,CAAC9L,OAAO,CAAC+U,MAAM,CAAC,EAAE;EACzBA,QAAAA,MAAM,CAACrS,OAAO,CAACgV,YAAY,CAAC,CAAA;EAC9B,OAAC,MAAM;UACLA,YAAY,CAAC3C,MAAM,CAAC,CAAA;EACtB,OAAA;EAEA,MAAA,OAAO0C,OAAO,CAAA;EAChB,KAAA;EAAC,GAAA,EAAA;MAAAnU,GAAA,EAAA,OAAA;EAAA2B,IAAAA,KAAA,EAED,SAAAqL,KAAMiH,CAAAA,OAAO,EAAE;EACb,MAAA,IAAMpU,IAAI,GAAGlE,MAAM,CAACkE,IAAI,CAAC,IAAI,CAAC,CAAA;EAC9B,MAAA,IAAIF,CAAC,GAAGE,IAAI,CAACN,MAAM,CAAA;QACnB,IAAI4U,OAAO,GAAG,KAAK,CAAA;QAEnB,OAAOxU,CAAC,EAAE,EAAE;EACV,QAAA,IAAMK,GAAG,GAAGH,IAAI,CAACF,CAAC,CAAC,CAAA;EACnB,QAAA,IAAG,CAACsU,OAAO,IAAIlC,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC/R,GAAG,CAAC,EAAEA,GAAG,EAAEiU,OAAO,EAAE,IAAI,CAAC,EAAE;YACpE,OAAO,IAAI,CAACjU,GAAG,CAAC,CAAA;EAChBmU,UAAAA,OAAO,GAAG,IAAI,CAAA;EAChB,SAAA;EACF,OAAA;EAEA,MAAA,OAAOA,OAAO,CAAA;EAChB,KAAA;EAAC,GAAA,EAAA;MAAAnU,GAAA,EAAA,WAAA;EAAA2B,IAAAA,KAAA,EAED,SAAA0S,SAAUC,CAAAA,MAAM,EAAE;QAChB,IAAMjU,IAAI,GAAG,IAAI,CAAA;QACjB,IAAMuP,OAAO,GAAG,EAAE,CAAA;QAElBpH,OAAK,CAACpJ,OAAO,CAAC,IAAI,EAAE,UAACuC,KAAK,EAAE8P,MAAM,EAAK;UACrC,IAAMzR,GAAG,GAAGwI,OAAK,CAACvI,OAAO,CAAC2P,OAAO,EAAE6B,MAAM,CAAC,CAAA;EAE1C,QAAA,IAAIzR,GAAG,EAAE;EACPK,UAAAA,IAAI,CAACL,GAAG,CAAC,GAAG0R,cAAc,CAAC/P,KAAK,CAAC,CAAA;YACjC,OAAOtB,IAAI,CAACoR,MAAM,CAAC,CAAA;EACnB,UAAA,OAAA;EACF,SAAA;EAEA,QAAA,IAAM8C,UAAU,GAAGD,MAAM,GAAGrC,YAAY,CAACR,MAAM,CAAC,GAAGlP,MAAM,CAACkP,MAAM,CAAC,CAACvS,IAAI,EAAE,CAAA;UAExE,IAAIqV,UAAU,KAAK9C,MAAM,EAAE;YACzB,OAAOpR,IAAI,CAACoR,MAAM,CAAC,CAAA;EACrB,SAAA;EAEApR,QAAAA,IAAI,CAACkU,UAAU,CAAC,GAAG7C,cAAc,CAAC/P,KAAK,CAAC,CAAA;EAExCiO,QAAAA,OAAO,CAAC2E,UAAU,CAAC,GAAG,IAAI,CAAA;EAC5B,OAAC,CAAC,CAAA;EAEF,MAAA,OAAO,IAAI,CAAA;EACb,KAAA;EAAC,GAAA,EAAA;MAAAvU,GAAA,EAAA,QAAA;MAAA2B,KAAA,EAED,SAAA8F,MAAAA,GAAmB;EAAA,MAAA,IAAA+M,iBAAA,CAAA;EAAA,MAAA,KAAA,IAAAC,IAAA,GAAAhZ,SAAA,CAAA8D,MAAA,EAATmV,OAAO,GAAA/X,IAAAA,KAAA,CAAA8X,IAAA,GAAAvU,IAAA,GAAA,CAAA,EAAAA,IAAA,GAAAuU,IAAA,EAAAvU,IAAA,EAAA,EAAA;EAAPwU,QAAAA,OAAO,CAAAxU,IAAA,CAAAzE,GAAAA,SAAA,CAAAyE,IAAA,CAAA,CAAA;EAAA,OAAA;EACf,MAAA,OAAO,CAAAsU,iBAAA,GAAA,IAAI,CAACzX,WAAW,EAAC0K,MAAM,CAAAjM,KAAA,CAAAgZ,iBAAA,EAAC,CAAA,IAAI,EAAA/M,MAAA,CAAKiN,OAAO,CAAC,CAAA,CAAA;EAClD,KAAA;EAAC,GAAA,EAAA;MAAA1U,GAAA,EAAA,QAAA;EAAA2B,IAAAA,KAAA,EAED,SAAA8G,MAAOkM,CAAAA,SAAS,EAAE;EAChB,MAAA,IAAMtV,GAAG,GAAG1D,MAAM,CAACU,MAAM,CAAC,IAAI,CAAC,CAAA;QAE/BmM,OAAK,CAACpJ,OAAO,CAAC,IAAI,EAAE,UAACuC,KAAK,EAAE8P,MAAM,EAAK;EACrC9P,QAAAA,KAAK,IAAI,IAAI,IAAIA,KAAK,KAAK,KAAK,KAAKtC,GAAG,CAACoS,MAAM,CAAC,GAAGkD,SAAS,IAAInM,OAAK,CAAC9L,OAAO,CAACiF,KAAK,CAAC,GAAGA,KAAK,CAAC+H,IAAI,CAAC,IAAI,CAAC,GAAG/H,KAAK,CAAC,CAAA;EAClH,OAAC,CAAC,CAAA;EAEF,MAAA,OAAOtC,GAAG,CAAA;EACZ,KAAA;EAAC,GAAA,EAAA;EAAAW,IAAAA,GAAA,EAAA4S,gBAAA;MAAAjR,KAAA,EAED,SAAAA,KAAAA,GAAoB;EAClB,MAAA,OAAOhG,MAAM,CAACsT,OAAO,CAAC,IAAI,CAACxG,MAAM,EAAE,CAAC,CAAC7K,MAAM,CAACE,QAAQ,CAAC,EAAE,CAAA;EACzD,KAAA;EAAC,GAAA,EAAA;MAAAkC,GAAA,EAAA,UAAA;MAAA2B,KAAA,EAED,SAAAjG,QAAAA,GAAW;EACT,MAAA,OAAOC,MAAM,CAACsT,OAAO,CAAC,IAAI,CAACxG,MAAM,EAAE,CAAC,CAAC9J,GAAG,CAAC,UAAAW,IAAA,EAAA;EAAA,QAAA,IAAAqB,KAAA,GAAA9B,cAAA,CAAAS,IAAA,EAAA,CAAA,CAAA;EAAEmS,UAAAA,MAAM,GAAA9Q,KAAA,CAAA,CAAA,CAAA;EAAEgB,UAAAA,KAAK,GAAAhB,KAAA,CAAA,CAAA,CAAA,CAAA;EAAA,QAAA,OAAM8Q,MAAM,GAAG,IAAI,GAAG9P,KAAK,CAAA;EAAA,OAAA,CAAC,CAAC+H,IAAI,CAAC,IAAI,CAAC,CAAA;EACjG,KAAA;EAAC,GAAA,EAAA;EAAA1J,IAAAA,GAAA,EAAA6S,mBAAA;MAAAkB,GAAA,EAED,SAAAA,GAAAA,GAA2B;EACzB,MAAA,OAAO,cAAc,CAAA;EACvB,KAAA;EAAC,GAAA,CAAA,EAAA,CAAA;MAAA/T,GAAA,EAAA,MAAA;EAAA2B,IAAAA,KAAA,EAED,SAAAoH,IAAY/M,CAAAA,KAAK,EAAE;QACjB,OAAOA,KAAK,YAAY,IAAI,GAAGA,KAAK,GAAG,IAAI,IAAI,CAACA,KAAK,CAAC,CAAA;EACxD,KAAA;EAAC,GAAA,EAAA;MAAAgE,GAAA,EAAA,QAAA;EAAA2B,IAAAA,KAAA,EAED,SAAA8F,MAAcmN,CAAAA,KAAK,EAAc;EAC/B,MAAA,IAAMC,QAAQ,GAAG,IAAI,IAAI,CAACD,KAAK,CAAC,CAAA;QAAC,KAAAE,IAAAA,KAAA,GAAArZ,SAAA,CAAA8D,MAAA,EADXmV,OAAO,OAAA/X,KAAA,CAAAmY,KAAA,GAAAA,CAAAA,GAAAA,KAAA,WAAAC,KAAA,GAAA,CAAA,EAAAA,KAAA,GAAAD,KAAA,EAAAC,KAAA,EAAA,EAAA;EAAPL,QAAAA,OAAO,CAAAK,KAAA,GAAAtZ,CAAAA,CAAAA,GAAAA,SAAA,CAAAsZ,KAAA,CAAA,CAAA;EAAA,OAAA;EAG7BL,MAAAA,OAAO,CAACtV,OAAO,CAAC,UAACoH,MAAM,EAAA;EAAA,QAAA,OAAKqO,QAAQ,CAAC/P,GAAG,CAAC0B,MAAM,CAAC,CAAA;SAAC,CAAA,CAAA;EAEjD,MAAA,OAAOqO,QAAQ,CAAA;EACjB,KAAA;EAAC,GAAA,EAAA;MAAA7U,GAAA,EAAA,UAAA;EAAA2B,IAAAA,KAAA,EAED,SAAAqT,QAAgBvD,CAAAA,MAAM,EAAE;QACtB,IAAMwD,SAAS,GAAG,IAAI,CAAC1D,UAAU,CAAC,GAAI,IAAI,CAACA,UAAU,CAAC,GAAG;EACvD2D,QAAAA,SAAS,EAAE,EAAC;SACZ,CAAA;EAEF,MAAA,IAAMA,SAAS,GAAGD,SAAS,CAACC,SAAS,CAAA;EACrC,MAAA,IAAMtZ,SAAS,GAAG,IAAI,CAACA,SAAS,CAAA;QAEhC,SAASuZ,cAAcA,CAACjC,OAAO,EAAE;EAC/B,QAAA,IAAME,OAAO,GAAG5B,eAAe,CAAC0B,OAAO,CAAC,CAAA;EAExC,QAAA,IAAI,CAACgC,SAAS,CAAC9B,OAAO,CAAC,EAAE;EACvBhB,UAAAA,cAAc,CAACxW,SAAS,EAAEsX,OAAO,CAAC,CAAA;EAClCgC,UAAAA,SAAS,CAAC9B,OAAO,CAAC,GAAG,IAAI,CAAA;EAC3B,SAAA;EACF,OAAA;EAEA5K,MAAAA,OAAK,CAAC9L,OAAO,CAAC+U,MAAM,CAAC,GAAGA,MAAM,CAACrS,OAAO,CAAC+V,cAAc,CAAC,GAAGA,cAAc,CAAC1D,MAAM,CAAC,CAAA;EAE/E,MAAA,OAAO,IAAI,CAAA;EACb,KAAA;EAAC,GAAA,CAAA,CAAA,CAAA;EAAA,EAAA,OAAAkB,YAAA,CAAA;EAAA,CAAA,CA5CA/U,MAAM,CAACE,QAAQ,EAQXF,MAAM,CAACC,WAAW,CAAA,CAAA;EAuCzB8U,YAAY,CAACqC,QAAQ,CAAC,CAAC,cAAc,EAAE,gBAAgB,EAAE,QAAQ,EAAE,iBAAiB,EAAE,YAAY,EAAE,eAAe,CAAC,CAAC,CAAA;;EAErH;AACAxM,SAAK,CAACrE,iBAAiB,CAACwO,YAAY,CAAC/W,SAAS,EAAE,UAAAsF,KAAA,EAAUlB,GAAG,EAAK;EAAA,EAAA,IAAhB2B,KAAK,GAAAT,KAAA,CAALS,KAAK,CAAA;EACrD,EAAA,IAAIyT,MAAM,GAAGpV,GAAG,CAAC,CAAC,CAAC,CAAC+D,WAAW,EAAE,GAAG/D,GAAG,CAAC7D,KAAK,CAAC,CAAC,CAAC,CAAC;IACjD,OAAO;MACL4X,GAAG,EAAE,SAAAA,GAAA,GAAA;EAAA,MAAA,OAAMpS,KAAK,CAAA;EAAA,KAAA;MAChBmD,GAAG,EAAA,SAAAA,GAACuQ,CAAAA,WAAW,EAAE;EACf,MAAA,IAAI,CAACD,MAAM,CAAC,GAAGC,WAAW,CAAA;EAC5B,KAAA;KACD,CAAA;EACH,CAAC,CAAC,CAAA;AAEF7M,SAAK,CAAC7D,aAAa,CAACgO,YAAY,CAAC,CAAA;AAEjC,uBAAeA,YAAY;;ECvS3B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACe,SAAS2C,aAAaA,CAACC,GAAG,EAAElN,QAAQ,EAAE;EACnD,EAAA,IAAMF,MAAM,GAAG,IAAI,IAAIoH,UAAQ,CAAA;EAC/B,EAAA,IAAM9O,OAAO,GAAG4H,QAAQ,IAAIF,MAAM,CAAA;IAClC,IAAMyH,OAAO,GAAG+C,cAAY,CAAC5J,IAAI,CAACtI,OAAO,CAACmP,OAAO,CAAC,CAAA;EAClD,EAAA,IAAIvI,IAAI,GAAG5G,OAAO,CAAC4G,IAAI,CAAA;IAEvBmB,OAAK,CAACpJ,OAAO,CAACmW,GAAG,EAAE,SAASC,SAASA,CAACna,EAAE,EAAE;MACxCgM,IAAI,GAAGhM,EAAE,CAACa,IAAI,CAACiM,MAAM,EAAEd,IAAI,EAAEuI,OAAO,CAACyE,SAAS,EAAE,EAAEhM,QAAQ,GAAGA,QAAQ,CAACE,MAAM,GAAG/I,SAAS,CAAC,CAAA;EAC3F,GAAC,CAAC,CAAA;IAEFoQ,OAAO,CAACyE,SAAS,EAAE,CAAA;EAEnB,EAAA,OAAOhN,IAAI,CAAA;EACb;;ECzBe,SAASoO,QAAQA,CAAC9T,KAAK,EAAE;EACtC,EAAA,OAAO,CAAC,EAAEA,KAAK,IAAIA,KAAK,CAAC+T,UAAU,CAAC,CAAA;EACtC;;ECCA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASC,aAAaA,CAAC1N,OAAO,EAAEE,MAAM,EAAEC,OAAO,EAAE;EAC/C;IACAJ,UAAU,CAAC9L,IAAI,CAAC,IAAI,EAAE+L,OAAO,IAAI,IAAI,GAAG,UAAU,GAAGA,OAAO,EAAED,UAAU,CAAC4N,YAAY,EAAEzN,MAAM,EAAEC,OAAO,CAAC,CAAA;IACvG,IAAI,CAAC5D,IAAI,GAAG,eAAe,CAAA;EAC7B,CAAA;AAEAgE,SAAK,CAAClH,QAAQ,CAACqU,aAAa,EAAE3N,UAAU,EAAE;EACxC0N,EAAAA,UAAU,EAAE,IAAA;EACd,CAAC,CAAC;;EClBF;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACe,SAASG,MAAMA,CAACC,OAAO,EAAEC,MAAM,EAAE1N,QAAQ,EAAE;EACxD,EAAA,IAAM0I,cAAc,GAAG1I,QAAQ,CAACF,MAAM,CAAC4I,cAAc,CAAA;EACrD,EAAA,IAAI,CAAC1I,QAAQ,CAACE,MAAM,IAAI,CAACwI,cAAc,IAAIA,cAAc,CAAC1I,QAAQ,CAACE,MAAM,CAAC,EAAE;MAC1EuN,OAAO,CAACzN,QAAQ,CAAC,CAAA;EACnB,GAAC,MAAM;MACL0N,MAAM,CAAC,IAAI/N,UAAU,CACnB,kCAAkC,GAAGK,QAAQ,CAACE,MAAM,EACpD,CAACP,UAAU,CAACgO,eAAe,EAAEhO,UAAU,CAACyI,gBAAgB,CAAC,CAACxK,IAAI,CAACgQ,KAAK,CAAC5N,QAAQ,CAACE,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,EAChGF,QAAQ,CAACF,MAAM,EACfE,QAAQ,CAACD,OAAO,EAChBC,QACF,CAAC,CAAC,CAAA;EACJ,GAAA;EACF;;ECxBe,SAAS6N,aAAaA,CAAClK,GAAG,EAAE;EACzC,EAAA,IAAMP,KAAK,GAAG,2BAA2B,CAAClI,IAAI,CAACyI,GAAG,CAAC,CAAA;EACnD,EAAA,OAAOP,KAAK,IAAIA,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;EAChC;;ECHA;EACA;EACA;EACA;EACA;EACA;EACA,SAAS0K,WAAWA,CAACC,YAAY,EAAEC,GAAG,EAAE;IACtCD,YAAY,GAAGA,YAAY,IAAI,EAAE,CAAA;EACjC,EAAA,IAAME,KAAK,GAAG,IAAI3Z,KAAK,CAACyZ,YAAY,CAAC,CAAA;EACrC,EAAA,IAAMG,UAAU,GAAG,IAAI5Z,KAAK,CAACyZ,YAAY,CAAC,CAAA;IAC1C,IAAII,IAAI,GAAG,CAAC,CAAA;IACZ,IAAIC,IAAI,GAAG,CAAC,CAAA;EACZ,EAAA,IAAIC,aAAa,CAAA;EAEjBL,EAAAA,GAAG,GAAGA,GAAG,KAAK7W,SAAS,GAAG6W,GAAG,GAAG,IAAI,CAAA;EAEpC,EAAA,OAAO,SAAS7S,IAAIA,CAACmT,WAAW,EAAE;EAChC,IAAA,IAAMC,GAAG,GAAGC,IAAI,CAACD,GAAG,EAAE,CAAA;EAEtB,IAAA,IAAME,SAAS,GAAGP,UAAU,CAACE,IAAI,CAAC,CAAA;MAElC,IAAI,CAACC,aAAa,EAAE;EAClBA,MAAAA,aAAa,GAAGE,GAAG,CAAA;EACrB,KAAA;EAEAN,IAAAA,KAAK,CAACE,IAAI,CAAC,GAAGG,WAAW,CAAA;EACzBJ,IAAAA,UAAU,CAACC,IAAI,CAAC,GAAGI,GAAG,CAAA;MAEtB,IAAIjX,CAAC,GAAG8W,IAAI,CAAA;MACZ,IAAIM,UAAU,GAAG,CAAC,CAAA;MAElB,OAAOpX,CAAC,KAAK6W,IAAI,EAAE;EACjBO,MAAAA,UAAU,IAAIT,KAAK,CAAC3W,CAAC,EAAE,CAAC,CAAA;QACxBA,CAAC,GAAGA,CAAC,GAAGyW,YAAY,CAAA;EACtB,KAAA;EAEAI,IAAAA,IAAI,GAAG,CAACA,IAAI,GAAG,CAAC,IAAIJ,YAAY,CAAA;MAEhC,IAAII,IAAI,KAAKC,IAAI,EAAE;EACjBA,MAAAA,IAAI,GAAG,CAACA,IAAI,GAAG,CAAC,IAAIL,YAAY,CAAA;EAClC,KAAA;EAEA,IAAA,IAAIQ,GAAG,GAAGF,aAAa,GAAGL,GAAG,EAAE;EAC7B,MAAA,OAAA;EACF,KAAA;EAEA,IAAA,IAAMW,MAAM,GAAGF,SAAS,IAAIF,GAAG,GAAGE,SAAS,CAAA;EAE3C,IAAA,OAAOE,MAAM,GAAG/Q,IAAI,CAACgR,KAAK,CAACF,UAAU,GAAG,IAAI,GAAGC,MAAM,CAAC,GAAGxX,SAAS,CAAA;KACnE,CAAA;EACH;;ECpDA;EACA;EACA;EACA;EACA;EACA;EACA,SAAS0X,QAAQA,CAAC7b,EAAE,EAAE8b,IAAI,EAAE;IAC1B,IAAIC,SAAS,GAAG,CAAC,CAAA;EACjB,EAAA,IAAIC,SAAS,GAAG,IAAI,GAAGF,IAAI,CAAA;EAC3B,EAAA,IAAIG,QAAQ,CAAA;EACZ,EAAA,IAAIC,KAAK,CAAA;EAET,EAAA,IAAMC,MAAM,GAAG,SAATA,MAAMA,CAAIC,IAAI,EAAuB;EAAA,IAAA,IAArBb,GAAG,GAAAnb,SAAA,CAAA8D,MAAA,QAAA9D,SAAA,CAAA,CAAA,CAAA,KAAA+D,SAAA,GAAA/D,SAAA,CAAGob,CAAAA,CAAAA,GAAAA,IAAI,CAACD,GAAG,EAAE,CAAA;EACpCQ,IAAAA,SAAS,GAAGR,GAAG,CAAA;EACfU,IAAAA,QAAQ,GAAG,IAAI,CAAA;EACf,IAAA,IAAIC,KAAK,EAAE;QACTG,YAAY,CAACH,KAAK,CAAC,CAAA;EACnBA,MAAAA,KAAK,GAAG,IAAI,CAAA;EACd,KAAA;EACAlc,IAAAA,EAAE,CAACG,KAAK,CAAC,IAAI,EAAEic,IAAI,CAAC,CAAA;KACrB,CAAA;EAED,EAAA,IAAME,SAAS,GAAG,SAAZA,SAASA,GAAgB;EAC7B,IAAA,IAAMf,GAAG,GAAGC,IAAI,CAACD,GAAG,EAAE,CAAA;EACtB,IAAA,IAAMI,MAAM,GAAGJ,GAAG,GAAGQ,SAAS,CAAA;EAAC,IAAA,KAAA,IAAA3C,IAAA,GAAAhZ,SAAA,CAAA8D,MAAA,EAFXkY,IAAI,GAAA9a,IAAAA,KAAA,CAAA8X,IAAA,GAAAvU,IAAA,GAAA,CAAA,EAAAA,IAAA,GAAAuU,IAAA,EAAAvU,IAAA,EAAA,EAAA;EAAJuX,MAAAA,IAAI,CAAAvX,IAAA,CAAAzE,GAAAA,SAAA,CAAAyE,IAAA,CAAA,CAAA;EAAA,KAAA;MAGxB,IAAK8W,MAAM,IAAIK,SAAS,EAAE;EACxBG,MAAAA,MAAM,CAACC,IAAI,EAAEb,GAAG,CAAC,CAAA;EACnB,KAAC,MAAM;EACLU,MAAAA,QAAQ,GAAGG,IAAI,CAAA;QACf,IAAI,CAACF,KAAK,EAAE;UACVA,KAAK,GAAG7P,UAAU,CAAC,YAAM;EACvB6P,UAAAA,KAAK,GAAG,IAAI,CAAA;YACZC,MAAM,CAACF,QAAQ,CAAC,CAAA;EAClB,SAAC,EAAED,SAAS,GAAGL,MAAM,CAAC,CAAA;EACxB,OAAA;EACF,KAAA;KACD,CAAA;EAED,EAAA,IAAMY,KAAK,GAAG,SAARA,KAAKA,GAAA;EAAA,IAAA,OAASN,QAAQ,IAAIE,MAAM,CAACF,QAAQ,CAAC,CAAA;EAAA,GAAA,CAAA;EAEhD,EAAA,OAAO,CAACK,SAAS,EAAEC,KAAK,CAAC,CAAA;EAC3B;;ECrCO,IAAMC,oBAAoB,GAAG,SAAvBA,oBAAoBA,CAAIC,QAAQ,EAAEC,gBAAgB,EAAe;EAAA,EAAA,IAAbZ,IAAI,GAAA1b,SAAA,CAAA8D,MAAA,GAAA,CAAA,IAAA9D,SAAA,CAAA,CAAA,CAAA,KAAA+D,SAAA,GAAA/D,SAAA,CAAA,CAAA,CAAA,GAAG,CAAC,CAAA;IACvE,IAAIuc,aAAa,GAAG,CAAC,CAAA;EACrB,EAAA,IAAMC,YAAY,GAAG9B,WAAW,CAAC,EAAE,EAAE,GAAG,CAAC,CAAA;EAEzC,EAAA,OAAOe,QAAQ,CAAC,UAAA5H,CAAC,EAAI;EACnB,IAAA,IAAM4I,MAAM,GAAG5I,CAAC,CAAC4I,MAAM,CAAA;MACvB,IAAMC,KAAK,GAAG7I,CAAC,CAAC8I,gBAAgB,GAAG9I,CAAC,CAAC6I,KAAK,GAAG3Y,SAAS,CAAA;EACtD,IAAA,IAAM6Y,aAAa,GAAGH,MAAM,GAAGF,aAAa,CAAA;EAC5C,IAAA,IAAMM,IAAI,GAAGL,YAAY,CAACI,aAAa,CAAC,CAAA;EACxC,IAAA,IAAME,OAAO,GAAGL,MAAM,IAAIC,KAAK,CAAA;EAE/BH,IAAAA,aAAa,GAAGE,MAAM,CAAA;MAEtB,IAAM7Q,IAAI,GAAAmR,eAAA,CAAA;EACRN,MAAAA,MAAM,EAANA,MAAM;EACNC,MAAAA,KAAK,EAALA,KAAK;EACLM,MAAAA,QAAQ,EAAEN,KAAK,GAAID,MAAM,GAAGC,KAAK,GAAI3Y,SAAS;EAC9C8W,MAAAA,KAAK,EAAE+B,aAAa;EACpBC,MAAAA,IAAI,EAAEA,IAAI,GAAGA,IAAI,GAAG9Y,SAAS;EAC7BkZ,MAAAA,SAAS,EAAEJ,IAAI,IAAIH,KAAK,IAAII,OAAO,GAAG,CAACJ,KAAK,GAAGD,MAAM,IAAII,IAAI,GAAG9Y,SAAS;EACzEmZ,MAAAA,KAAK,EAAErJ,CAAC;QACR8I,gBAAgB,EAAED,KAAK,IAAI,IAAA;EAAI,KAAA,EAC9BJ,gBAAgB,GAAG,UAAU,GAAG,QAAQ,EAAG,IAAI,CACjD,CAAA;MAEDD,QAAQ,CAACzQ,IAAI,CAAC,CAAA;KACf,EAAE8P,IAAI,CAAC,CAAA;EACV,CAAC,CAAA;EAEM,IAAMyB,sBAAsB,GAAG,SAAzBA,sBAAsBA,CAAIT,KAAK,EAAER,SAAS,EAAK;EAC1D,EAAA,IAAMS,gBAAgB,GAAGD,KAAK,IAAI,IAAI,CAAA;IAEtC,OAAO,CAAC,UAACD,MAAM,EAAA;EAAA,IAAA,OAAKP,SAAS,CAAC,CAAC,CAAC,CAAC;EAC/BS,MAAAA,gBAAgB,EAAhBA,gBAAgB;EAChBD,MAAAA,KAAK,EAALA,KAAK;EACLD,MAAAA,MAAM,EAANA,MAAAA;EACF,KAAC,CAAC,CAAA;EAAA,GAAA,EAAEP,SAAS,CAAC,CAAC,CAAC,CAAC,CAAA;EACnB,CAAC,CAAA;EAEM,IAAMkB,cAAc,GAAG,SAAjBA,cAAcA,CAAIxd,EAAE,EAAA;IAAA,OAAK,YAAA;EAAA,IAAA,KAAA,IAAAoZ,IAAA,GAAAhZ,SAAA,CAAA8D,MAAA,EAAIkY,IAAI,GAAA9a,IAAAA,KAAA,CAAA8X,IAAA,GAAAvU,IAAA,GAAA,CAAA,EAAAA,IAAA,GAAAuU,IAAA,EAAAvU,IAAA,EAAA,EAAA;EAAJuX,MAAAA,IAAI,CAAAvX,IAAA,CAAAzE,GAAAA,SAAA,CAAAyE,IAAA,CAAA,CAAA;EAAA,KAAA;MAAA,OAAKsI,OAAK,CAACb,IAAI,CAAC,YAAA;EAAA,MAAA,OAAMtM,EAAE,CAAAG,KAAA,CAAA,KAAA,CAAA,EAAIic,IAAI,CAAC,CAAA;OAAC,CAAA,CAAA;EAAA,GAAA,CAAA;EAAA,CAAA;;ACzChF,wBAAelJ,QAAQ,CAACT,qBAAqB,GAAI,UAACK,MAAM,EAAE2K,MAAM,EAAA;IAAA,OAAK,UAAC9M,GAAG,EAAK;MAC5EA,GAAG,GAAG,IAAI+M,GAAG,CAAC/M,GAAG,EAAEuC,QAAQ,CAACJ,MAAM,CAAC,CAAA;MAEnC,OACEA,MAAM,CAAC6K,QAAQ,KAAKhN,GAAG,CAACgN,QAAQ,IAChC7K,MAAM,CAAC8K,IAAI,KAAKjN,GAAG,CAACiN,IAAI,KACvBH,MAAM,IAAI3K,MAAM,CAAC+K,IAAI,KAAKlN,GAAG,CAACkN,IAAI,CAAC,CAAA;KAEvC,CAAA;EAAA,CACC,CAAA,IAAIH,GAAG,CAACxK,QAAQ,CAACJ,MAAM,CAAC,EACxBI,QAAQ,CAACV,SAAS,IAAI,iBAAiB,CAAC/D,IAAI,CAACyE,QAAQ,CAACV,SAAS,CAACsL,SAAS,CAC3E,CAAC,GAAG,YAAA;EAAA,EAAA,OAAM,IAAI,CAAA;EAAA,CAAA;;ACVd,gBAAe5K,QAAQ,CAACT,qBAAqB;EAE3C;EACA;EACEsL,EAAAA,KAAK,EAAAA,SAAAA,KAAAA,CAAC5U,IAAI,EAAE7C,KAAK,EAAE0X,OAAO,EAAE9P,IAAI,EAAE+P,MAAM,EAAEC,MAAM,EAAE;MAChD,IAAMC,MAAM,GAAG,CAAChV,IAAI,GAAG,GAAG,GAAGgH,kBAAkB,CAAC7J,KAAK,CAAC,CAAC,CAAA;MAEvD6G,OAAK,CAAChL,QAAQ,CAAC6b,OAAO,CAAC,IAAIG,MAAM,CAAChW,IAAI,CAAC,UAAU,GAAG,IAAIqT,IAAI,CAACwC,OAAO,CAAC,CAACI,WAAW,EAAE,CAAC,CAAA;EAEpFjR,IAAAA,OAAK,CAACjL,QAAQ,CAACgM,IAAI,CAAC,IAAIiQ,MAAM,CAAChW,IAAI,CAAC,OAAO,GAAG+F,IAAI,CAAC,CAAA;EAEnDf,IAAAA,OAAK,CAACjL,QAAQ,CAAC+b,MAAM,CAAC,IAAIE,MAAM,CAAChW,IAAI,CAAC,SAAS,GAAG8V,MAAM,CAAC,CAAA;MAEzDC,MAAM,KAAK,IAAI,IAAIC,MAAM,CAAChW,IAAI,CAAC,QAAQ,CAAC,CAAA;MAExCmK,QAAQ,CAAC6L,MAAM,GAAGA,MAAM,CAAC9P,IAAI,CAAC,IAAI,CAAC,CAAA;KACpC;IAEDgQ,IAAI,EAAA,SAAAA,IAAClV,CAAAA,IAAI,EAAE;EACT,IAAA,IAAMiH,KAAK,GAAGkC,QAAQ,CAAC6L,MAAM,CAAC/N,KAAK,CAAC,IAAIkO,MAAM,CAAC,YAAY,GAAGnV,IAAI,GAAG,WAAW,CAAC,CAAC,CAAA;MAClF,OAAQiH,KAAK,GAAGmO,kBAAkB,CAACnO,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAA;KACpD;IAEDoO,MAAM,EAAA,SAAAA,MAACrV,CAAAA,IAAI,EAAE;EACX,IAAA,IAAI,CAAC4U,KAAK,CAAC5U,IAAI,EAAE,EAAE,EAAEqS,IAAI,CAACD,GAAG,EAAE,GAAG,QAAQ,CAAC,CAAA;EAC7C,GAAA;EACF,CAAC;EAID;EACA;EACEwC,EAAAA,KAAK,EAAAA,SAAAA,KAAAA,GAAG,EAAE;IACVM,IAAI,EAAA,SAAAA,OAAG;EACL,IAAA,OAAO,IAAI,CAAA;KACZ;IACDG,MAAM,EAAA,SAAAA,MAAA,GAAG,EAAC;EACZ,CAAC;;ECtCH;EACA;EACA;EACA;EACA;EACA;EACA;EACe,SAASC,aAAaA,CAAC9N,GAAG,EAAE;EACzC;EACA;EACA;EACA,EAAA,OAAO,6BAA6B,CAAClC,IAAI,CAACkC,GAAG,CAAC,CAAA;EAChD;;ECZA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACe,SAAS+N,WAAWA,CAACC,OAAO,EAAEC,WAAW,EAAE;IACxD,OAAOA,WAAW,GACdD,OAAO,CAAC7a,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,GAAG,GAAG,GAAG8a,WAAW,CAAC9a,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,GACrE6a,OAAO,CAAA;EACb;;ECTA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACe,SAASE,aAAaA,CAACF,OAAO,EAAEG,YAAY,EAAE;EAC3D,EAAA,IAAIH,OAAO,IAAI,CAACF,aAAa,CAACK,YAAY,CAAC,EAAE;EAC3C,IAAA,OAAOJ,WAAW,CAACC,OAAO,EAAEG,YAAY,CAAC,CAAA;EAC3C,GAAA;EACA,EAAA,OAAOA,YAAY,CAAA;EACrB;;ECfA,IAAMC,eAAe,GAAG,SAAlBA,eAAeA,CAAIpe,KAAK,EAAA;IAAA,OAAKA,KAAK,YAAY2W,cAAY,GAAArE,cAAA,CAAQtS,EAAAA,EAAAA,KAAK,IAAKA,KAAK,CAAA;EAAA,CAAA,CAAA;;EAEvF;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACe,SAASqe,WAAWA,CAACC,OAAO,EAAEC,OAAO,EAAE;EACpD;EACAA,EAAAA,OAAO,GAAGA,OAAO,IAAI,EAAE,CAAA;IACvB,IAAMpS,MAAM,GAAG,EAAE,CAAA;IAEjB,SAASqS,cAAcA,CAAChU,MAAM,EAAED,MAAM,EAAErE,IAAI,EAAEtB,QAAQ,EAAE;EACtD,IAAA,IAAI4H,OAAK,CAAC7K,aAAa,CAAC6I,MAAM,CAAC,IAAIgC,OAAK,CAAC7K,aAAa,CAAC4I,MAAM,CAAC,EAAE;EAC9D,MAAA,OAAOiC,OAAK,CAAC9H,KAAK,CAACxE,IAAI,CAAC;EAAC0E,QAAAA,QAAQ,EAARA,QAAAA;EAAQ,OAAC,EAAE4F,MAAM,EAAED,MAAM,CAAC,CAAA;OACpD,MAAM,IAAIiC,OAAK,CAAC7K,aAAa,CAAC4I,MAAM,CAAC,EAAE;QACtC,OAAOiC,OAAK,CAAC9H,KAAK,CAAC,EAAE,EAAE6F,MAAM,CAAC,CAAA;OAC/B,MAAM,IAAIiC,OAAK,CAAC9L,OAAO,CAAC6J,MAAM,CAAC,EAAE;EAChC,MAAA,OAAOA,MAAM,CAACpK,KAAK,EAAE,CAAA;EACvB,KAAA;EACA,IAAA,OAAOoK,MAAM,CAAA;EACf,GAAA;;EAEA;IACA,SAASkU,mBAAmBA,CAACzZ,CAAC,EAAEC,CAAC,EAAEiB,IAAI,EAAGtB,QAAQ,EAAE;EAClD,IAAA,IAAI,CAAC4H,OAAK,CAAC5L,WAAW,CAACqE,CAAC,CAAC,EAAE;QACzB,OAAOuZ,cAAc,CAACxZ,CAAC,EAAEC,CAAC,EAAEiB,IAAI,EAAGtB,QAAQ,CAAC,CAAA;OAC7C,MAAM,IAAI,CAAC4H,OAAK,CAAC5L,WAAW,CAACoE,CAAC,CAAC,EAAE;QAChC,OAAOwZ,cAAc,CAAChb,SAAS,EAAEwB,CAAC,EAAEkB,IAAI,EAAGtB,QAAQ,CAAC,CAAA;EACtD,KAAA;EACF,GAAA;;EAEA;EACA,EAAA,SAAS8Z,gBAAgBA,CAAC1Z,CAAC,EAAEC,CAAC,EAAE;EAC9B,IAAA,IAAI,CAACuH,OAAK,CAAC5L,WAAW,CAACqE,CAAC,CAAC,EAAE;EACzB,MAAA,OAAOuZ,cAAc,CAAChb,SAAS,EAAEyB,CAAC,CAAC,CAAA;EACrC,KAAA;EACF,GAAA;;EAEA;EACA,EAAA,SAAS0Z,gBAAgBA,CAAC3Z,CAAC,EAAEC,CAAC,EAAE;EAC9B,IAAA,IAAI,CAACuH,OAAK,CAAC5L,WAAW,CAACqE,CAAC,CAAC,EAAE;EACzB,MAAA,OAAOuZ,cAAc,CAAChb,SAAS,EAAEyB,CAAC,CAAC,CAAA;OACpC,MAAM,IAAI,CAACuH,OAAK,CAAC5L,WAAW,CAACoE,CAAC,CAAC,EAAE;EAChC,MAAA,OAAOwZ,cAAc,CAAChb,SAAS,EAAEwB,CAAC,CAAC,CAAA;EACrC,KAAA;EACF,GAAA;;EAEA;EACA,EAAA,SAAS4Z,eAAeA,CAAC5Z,CAAC,EAAEC,CAAC,EAAEiB,IAAI,EAAE;MACnC,IAAIA,IAAI,IAAIqY,OAAO,EAAE;EACnB,MAAA,OAAOC,cAAc,CAACxZ,CAAC,EAAEC,CAAC,CAAC,CAAA;EAC7B,KAAC,MAAM,IAAIiB,IAAI,IAAIoY,OAAO,EAAE;EAC1B,MAAA,OAAOE,cAAc,CAAChb,SAAS,EAAEwB,CAAC,CAAC,CAAA;EACrC,KAAA;EACF,GAAA;EAEA,EAAA,IAAM6Z,QAAQ,GAAG;EACf7O,IAAAA,GAAG,EAAE0O,gBAAgB;EACrBzJ,IAAAA,MAAM,EAAEyJ,gBAAgB;EACxBrT,IAAAA,IAAI,EAAEqT,gBAAgB;EACtBV,IAAAA,OAAO,EAAEW,gBAAgB;EACzBhL,IAAAA,gBAAgB,EAAEgL,gBAAgB;EAClCtK,IAAAA,iBAAiB,EAAEsK,gBAAgB;EACnCG,IAAAA,gBAAgB,EAAEH,gBAAgB;EAClCjK,IAAAA,OAAO,EAAEiK,gBAAgB;EACzBI,IAAAA,cAAc,EAAEJ,gBAAgB;EAChCK,IAAAA,eAAe,EAAEL,gBAAgB;EACjCM,IAAAA,aAAa,EAAEN,gBAAgB;EAC/BjL,IAAAA,OAAO,EAAEiL,gBAAgB;EACzBpK,IAAAA,YAAY,EAAEoK,gBAAgB;EAC9BhK,IAAAA,cAAc,EAAEgK,gBAAgB;EAChC/J,IAAAA,cAAc,EAAE+J,gBAAgB;EAChCO,IAAAA,gBAAgB,EAAEP,gBAAgB;EAClCQ,IAAAA,kBAAkB,EAAER,gBAAgB;EACpCS,IAAAA,UAAU,EAAET,gBAAgB;EAC5B9J,IAAAA,gBAAgB,EAAE8J,gBAAgB;EAClC7J,IAAAA,aAAa,EAAE6J,gBAAgB;EAC/BU,IAAAA,cAAc,EAAEV,gBAAgB;EAChCW,IAAAA,SAAS,EAAEX,gBAAgB;EAC3BY,IAAAA,SAAS,EAAEZ,gBAAgB;EAC3Ba,IAAAA,UAAU,EAAEb,gBAAgB;EAC5Bc,IAAAA,WAAW,EAAEd,gBAAgB;EAC7Be,IAAAA,UAAU,EAAEf,gBAAgB;EAC5BgB,IAAAA,gBAAgB,EAAEhB,gBAAgB;EAClC5J,IAAAA,cAAc,EAAE6J,eAAe;EAC/BhL,IAAAA,OAAO,EAAE,SAAAA,OAAAA,CAAC5O,CAAC,EAAEC,CAAC,EAAGiB,IAAI,EAAA;EAAA,MAAA,OAAKuY,mBAAmB,CAACL,eAAe,CAACpZ,CAAC,CAAC,EAAEoZ,eAAe,CAACnZ,CAAC,CAAC,EAACiB,IAAI,EAAE,IAAI,CAAC,CAAA;EAAA,KAAA;KACjG,CAAA;IAEDsG,OAAK,CAACpJ,OAAO,CAACzD,MAAM,CAACkE,IAAI,CAAClE,MAAM,CAACiG,MAAM,CAAC,EAAE,EAAE0Y,OAAO,EAAEC,OAAO,CAAC,CAAC,EAAE,SAASqB,kBAAkBA,CAAC1Z,IAAI,EAAE;EAChG,IAAA,IAAMxB,KAAK,GAAGma,QAAQ,CAAC3Y,IAAI,CAAC,IAAIuY,mBAAmB,CAAA;EACnD,IAAA,IAAMoB,WAAW,GAAGnb,KAAK,CAAC4Z,OAAO,CAACpY,IAAI,CAAC,EAAEqY,OAAO,CAACrY,IAAI,CAAC,EAAEA,IAAI,CAAC,CAAA;EAC5DsG,IAAAA,OAAK,CAAC5L,WAAW,CAACif,WAAW,CAAC,IAAInb,KAAK,KAAKka,eAAe,KAAMzS,MAAM,CAACjG,IAAI,CAAC,GAAG2Z,WAAW,CAAC,CAAA;EAC/F,GAAC,CAAC,CAAA;EAEF,EAAA,OAAO1T,MAAM,CAAA;EACf;;AChGA,sBAAe,CAAA,UAACA,MAAM,EAAK;IACzB,IAAM2T,SAAS,GAAGzB,WAAW,CAAC,EAAE,EAAElS,MAAM,CAAC,CAAA;EAEzC,EAAA,IAAKd,IAAI,GAAkEyU,SAAS,CAA/EzU,IAAI;MAAE4T,aAAa,GAAmDa,SAAS,CAAzEb,aAAa;MAAErK,cAAc,GAAmCkL,SAAS,CAA1DlL,cAAc;MAAED,cAAc,GAAmBmL,SAAS,CAA1CnL,cAAc;MAAEf,OAAO,GAAUkM,SAAS,CAA1BlM,OAAO;MAAEmM,IAAI,GAAID,SAAS,CAAjBC,IAAI,CAAA;IAEvED,SAAS,CAAClM,OAAO,GAAGA,OAAO,GAAG+C,cAAY,CAAC5J,IAAI,CAAC6G,OAAO,CAAC,CAAA;IAExDkM,SAAS,CAAC9P,GAAG,GAAGD,QAAQ,CAACmO,aAAa,CAAC4B,SAAS,CAAC9B,OAAO,EAAE8B,SAAS,CAAC9P,GAAG,CAAC,EAAE7D,MAAM,CAACwD,MAAM,EAAExD,MAAM,CAAC2S,gBAAgB,CAAC,CAAA;;EAEjH;EACA,EAAA,IAAIiB,IAAI,EAAE;EACRnM,IAAAA,OAAO,CAAC9K,GAAG,CAAC,eAAe,EAAE,QAAQ,GACnCkX,IAAI,CAAC,CAACD,IAAI,CAACE,QAAQ,IAAI,EAAE,IAAI,GAAG,IAAIF,IAAI,CAACG,QAAQ,GAAGC,QAAQ,CAAC3Q,kBAAkB,CAACuQ,IAAI,CAACG,QAAQ,CAAC,CAAC,GAAG,EAAE,CAAC,CACvG,CAAC,CAAA;EACH,GAAA;EAEA,EAAA,IAAIrM,WAAW,CAAA;EAEf,EAAA,IAAIrH,OAAK,CAACnK,UAAU,CAACgJ,IAAI,CAAC,EAAE;EAC1B,IAAA,IAAIkH,QAAQ,CAACT,qBAAqB,IAAIS,QAAQ,CAACP,8BAA8B,EAAE;EAC7E4B,MAAAA,OAAO,CAACK,cAAc,CAACzQ,SAAS,CAAC,CAAC;EACpC,KAAC,MAAM,IAAI,CAACqQ,WAAW,GAAGD,OAAO,CAACE,cAAc,EAAE,MAAM,KAAK,EAAE;EAC7D;EACA,MAAA,IAAAxQ,IAAA,GAA0BuQ,WAAW,GAAGA,WAAW,CAACzK,KAAK,CAAC,GAAG,CAAC,CAACzG,GAAG,CAAC,UAAAsI,KAAK,EAAA;EAAA,UAAA,OAAIA,KAAK,CAAC/H,IAAI,EAAE,CAAA;EAAA,SAAA,CAAC,CAAC8C,MAAM,CAACoa,OAAO,CAAC,GAAG,EAAE;UAAAzb,KAAA,GAAA0b,QAAA,CAAA/c,IAAA,CAAA;EAAvG/C,QAAAA,IAAI,GAAAoE,KAAA,CAAA,CAAA,CAAA;UAAKiR,MAAM,GAAAjR,KAAA,CAAAxE,KAAA,CAAA,CAAA,CAAA,CAAA;EACtByT,MAAAA,OAAO,CAACK,cAAc,CAAC,CAAC1T,IAAI,IAAI,qBAAqB,CAAAkL,CAAAA,MAAA,CAAA6U,kBAAA,CAAK1K,MAAM,CAAA,CAAA,CAAElI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;EAC/E,KAAA;EACF,GAAA;;EAEA;EACA;EACA;;IAEA,IAAI6E,QAAQ,CAACT,qBAAqB,EAAE;EAClCmN,IAAAA,aAAa,IAAIzS,OAAK,CAACxL,UAAU,CAACie,aAAa,CAAC,KAAKA,aAAa,GAAGA,aAAa,CAACa,SAAS,CAAC,CAAC,CAAA;EAE9F,IAAA,IAAIb,aAAa,IAAKA,aAAa,KAAK,KAAK,IAAIsB,eAAe,CAACT,SAAS,CAAC9P,GAAG,CAAE,EAAE;EAChF;QACA,IAAMwQ,SAAS,GAAG5L,cAAc,IAAID,cAAc,IAAI8L,OAAO,CAAC/C,IAAI,CAAC/I,cAAc,CAAC,CAAA;EAElF,MAAA,IAAI6L,SAAS,EAAE;EACb5M,QAAAA,OAAO,CAAC9K,GAAG,CAAC8L,cAAc,EAAE4L,SAAS,CAAC,CAAA;EACxC,OAAA;EACF,KAAA;EACF,GAAA;EAEA,EAAA,OAAOV,SAAS,CAAA;EAClB,CAAC;;EC5CD,IAAMY,qBAAqB,GAAG,OAAOC,cAAc,KAAK,WAAW,CAAA;AAEnE,mBAAeD,qBAAqB,IAAI,UAAUvU,MAAM,EAAE;IACxD,OAAO,IAAIyU,OAAO,CAAC,SAASC,kBAAkBA,CAAC/G,OAAO,EAAEC,MAAM,EAAE;EAC9D,IAAA,IAAM+G,OAAO,GAAGC,aAAa,CAAC5U,MAAM,CAAC,CAAA;EACrC,IAAA,IAAI6U,WAAW,GAAGF,OAAO,CAACzV,IAAI,CAAA;EAC9B,IAAA,IAAM4V,cAAc,GAAGtK,cAAY,CAAC5J,IAAI,CAAC+T,OAAO,CAAClN,OAAO,CAAC,CAACyE,SAAS,EAAE,CAAA;EACrE,IAAA,IAAK9D,YAAY,GAA0CuM,OAAO,CAA7DvM,YAAY;QAAE2K,gBAAgB,GAAwB4B,OAAO,CAA/C5B,gBAAgB;QAAEC,kBAAkB,GAAI2B,OAAO,CAA7B3B,kBAAkB,CAAA;EACvD,IAAA,IAAI+B,UAAU,CAAA;MACd,IAAIC,eAAe,EAAEC,iBAAiB,CAAA;MACtC,IAAIC,WAAW,EAAEC,aAAa,CAAA;MAE9B,SAASpa,IAAIA,GAAG;EACdma,MAAAA,WAAW,IAAIA,WAAW,EAAE,CAAC;EAC7BC,MAAAA,aAAa,IAAIA,aAAa,EAAE,CAAC;;QAEjCR,OAAO,CAACrB,WAAW,IAAIqB,OAAO,CAACrB,WAAW,CAAC8B,WAAW,CAACL,UAAU,CAAC,CAAA;EAElEJ,MAAAA,OAAO,CAACU,MAAM,IAAIV,OAAO,CAACU,MAAM,CAACC,mBAAmB,CAAC,OAAO,EAAEP,UAAU,CAAC,CAAA;EAC3E,KAAA;EAEA,IAAA,IAAI9U,OAAO,GAAG,IAAIuU,cAAc,EAAE,CAAA;EAElCvU,IAAAA,OAAO,CAACsV,IAAI,CAACZ,OAAO,CAAC7L,MAAM,CAAClN,WAAW,EAAE,EAAE+Y,OAAO,CAAC9Q,GAAG,EAAE,IAAI,CAAC,CAAA;;EAE7D;EACA5D,IAAAA,OAAO,CAACsI,OAAO,GAAGoM,OAAO,CAACpM,OAAO,CAAA;MAEjC,SAASiN,SAASA,GAAG;QACnB,IAAI,CAACvV,OAAO,EAAE;EACZ,QAAA,OAAA;EACF,OAAA;EACA;EACA,MAAA,IAAMwV,eAAe,GAAGjL,cAAY,CAAC5J,IAAI,CACvC,uBAAuB,IAAIX,OAAO,IAAIA,OAAO,CAACyV,qBAAqB,EACrE,CAAC,CAAA;EACD,MAAA,IAAMC,YAAY,GAAG,CAACvN,YAAY,IAAIA,YAAY,KAAK,MAAM,IAAIA,YAAY,KAAK,MAAM,GACtFnI,OAAO,CAAC2V,YAAY,GAAG3V,OAAO,CAACC,QAAQ,CAAA;EACzC,MAAA,IAAMA,QAAQ,GAAG;EACfhB,QAAAA,IAAI,EAAEyW,YAAY;UAClBvV,MAAM,EAAEH,OAAO,CAACG,MAAM;UACtByV,UAAU,EAAE5V,OAAO,CAAC4V,UAAU;EAC9BpO,QAAAA,OAAO,EAAEgO,eAAe;EACxBzV,QAAAA,MAAM,EAANA,MAAM;EACNC,QAAAA,OAAO,EAAPA,OAAAA;SACD,CAAA;EAEDyN,MAAAA,MAAM,CAAC,SAASoI,QAAQA,CAACtc,KAAK,EAAE;UAC9BmU,OAAO,CAACnU,KAAK,CAAC,CAAA;EACduB,QAAAA,IAAI,EAAE,CAAA;EACR,OAAC,EAAE,SAASgb,OAAOA,CAACrK,GAAG,EAAE;UACvBkC,MAAM,CAAClC,GAAG,CAAC,CAAA;EACX3Q,QAAAA,IAAI,EAAE,CAAA;SACP,EAAEmF,QAAQ,CAAC,CAAA;;EAEZ;EACAD,MAAAA,OAAO,GAAG,IAAI,CAAA;EAChB,KAAA;MAEA,IAAI,WAAW,IAAIA,OAAO,EAAE;EAC1B;QACAA,OAAO,CAACuV,SAAS,GAAGA,SAAS,CAAA;EAC/B,KAAC,MAAM;EACL;EACAvV,MAAAA,OAAO,CAAC+V,kBAAkB,GAAG,SAASC,UAAUA,GAAG;UACjD,IAAI,CAAChW,OAAO,IAAIA,OAAO,CAACiW,UAAU,KAAK,CAAC,EAAE;EACxC,UAAA,OAAA;EACF,SAAA;;EAEA;EACA;EACA;EACA;UACA,IAAIjW,OAAO,CAACG,MAAM,KAAK,CAAC,IAAI,EAAEH,OAAO,CAACkW,WAAW,IAAIlW,OAAO,CAACkW,WAAW,CAAC7b,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE;EAChG,UAAA,OAAA;EACF,SAAA;EACA;EACA;UACAiF,UAAU,CAACiW,SAAS,CAAC,CAAA;SACtB,CAAA;EACH,KAAA;;EAEA;EACAvV,IAAAA,OAAO,CAACmW,OAAO,GAAG,SAASC,WAAWA,GAAG;QACvC,IAAI,CAACpW,OAAO,EAAE;EACZ,QAAA,OAAA;EACF,OAAA;EAEA2N,MAAAA,MAAM,CAAC,IAAI/N,UAAU,CAAC,iBAAiB,EAAEA,UAAU,CAACyW,YAAY,EAAEtW,MAAM,EAAEC,OAAO,CAAC,CAAC,CAAA;;EAEnF;EACAA,MAAAA,OAAO,GAAG,IAAI,CAAA;OACf,CAAA;;EAED;EACAA,IAAAA,OAAO,CAACsW,OAAO,GAAG,SAASC,WAAWA,GAAG;EACvC;EACA;EACA5I,MAAAA,MAAM,CAAC,IAAI/N,UAAU,CAAC,eAAe,EAAEA,UAAU,CAAC4W,WAAW,EAAEzW,MAAM,EAAEC,OAAO,CAAC,CAAC,CAAA;;EAEhF;EACAA,MAAAA,OAAO,GAAG,IAAI,CAAA;OACf,CAAA;;EAED;EACAA,IAAAA,OAAO,CAACyW,SAAS,GAAG,SAASC,aAAaA,GAAG;EAC3C,MAAA,IAAIC,mBAAmB,GAAGjC,OAAO,CAACpM,OAAO,GAAG,aAAa,GAAGoM,OAAO,CAACpM,OAAO,GAAG,aAAa,GAAG,kBAAkB,CAAA;EAChH,MAAA,IAAMlB,YAAY,GAAGsN,OAAO,CAACtN,YAAY,IAAIC,oBAAoB,CAAA;QACjE,IAAIqN,OAAO,CAACiC,mBAAmB,EAAE;UAC/BA,mBAAmB,GAAGjC,OAAO,CAACiC,mBAAmB,CAAA;EACnD,OAAA;QACAhJ,MAAM,CAAC,IAAI/N,UAAU,CACnB+W,mBAAmB,EACnBvP,YAAY,CAACnC,mBAAmB,GAAGrF,UAAU,CAACgX,SAAS,GAAGhX,UAAU,CAACyW,YAAY,EACjFtW,MAAM,EACNC,OAAO,CAAC,CAAC,CAAA;;EAEX;EACAA,MAAAA,OAAO,GAAG,IAAI,CAAA;OACf,CAAA;;EAED;MACA4U,WAAW,KAAKxd,SAAS,IAAIyd,cAAc,CAAChN,cAAc,CAAC,IAAI,CAAC,CAAA;;EAEhE;MACA,IAAI,kBAAkB,IAAI7H,OAAO,EAAE;EACjCI,MAAAA,OAAK,CAACpJ,OAAO,CAAC6d,cAAc,CAACxU,MAAM,EAAE,EAAE,SAASwW,gBAAgBA,CAACniB,GAAG,EAAEkD,GAAG,EAAE;EACzEoI,QAAAA,OAAO,CAAC6W,gBAAgB,CAACjf,GAAG,EAAElD,GAAG,CAAC,CAAA;EACpC,OAAC,CAAC,CAAA;EACJ,KAAA;;EAEA;MACA,IAAI,CAAC0L,OAAK,CAAC5L,WAAW,CAACkgB,OAAO,CAAC9B,eAAe,CAAC,EAAE;EAC/C5S,MAAAA,OAAO,CAAC4S,eAAe,GAAG,CAAC,CAAC8B,OAAO,CAAC9B,eAAe,CAAA;EACrD,KAAA;;EAEA;EACA,IAAA,IAAIzK,YAAY,IAAIA,YAAY,KAAK,MAAM,EAAE;EAC3CnI,MAAAA,OAAO,CAACmI,YAAY,GAAGuM,OAAO,CAACvM,YAAY,CAAA;EAC7C,KAAA;;EAEA;EACA,IAAA,IAAI4K,kBAAkB,EAAE;EAAA,MAAA,IAAA+D,qBAAA,GACgBrH,oBAAoB,CAACsD,kBAAkB,EAAE,IAAI,CAAC,CAAA;EAAA,MAAA,IAAAgE,sBAAA,GAAAtgB,cAAA,CAAAqgB,qBAAA,EAAA,CAAA,CAAA,CAAA;EAAlF9B,MAAAA,iBAAiB,GAAA+B,sBAAA,CAAA,CAAA,CAAA,CAAA;EAAE7B,MAAAA,aAAa,GAAA6B,sBAAA,CAAA,CAAA,CAAA,CAAA;EAClC/W,MAAAA,OAAO,CAACjB,gBAAgB,CAAC,UAAU,EAAEiW,iBAAiB,CAAC,CAAA;EACzD,KAAA;;EAEA;EACA,IAAA,IAAIlC,gBAAgB,IAAI9S,OAAO,CAACgX,MAAM,EAAE;EAAA,MAAA,IAAAC,sBAAA,GACJxH,oBAAoB,CAACqD,gBAAgB,CAAC,CAAA;EAAA,MAAA,IAAAoE,sBAAA,GAAAzgB,cAAA,CAAAwgB,sBAAA,EAAA,CAAA,CAAA,CAAA;EAAtElC,MAAAA,eAAe,GAAAmC,sBAAA,CAAA,CAAA,CAAA,CAAA;EAAEjC,MAAAA,WAAW,GAAAiC,sBAAA,CAAA,CAAA,CAAA,CAAA;QAE9BlX,OAAO,CAACgX,MAAM,CAACjY,gBAAgB,CAAC,UAAU,EAAEgW,eAAe,CAAC,CAAA;QAE5D/U,OAAO,CAACgX,MAAM,CAACjY,gBAAgB,CAAC,SAAS,EAAEkW,WAAW,CAAC,CAAA;EACzD,KAAA;EAEA,IAAA,IAAIP,OAAO,CAACrB,WAAW,IAAIqB,OAAO,CAACU,MAAM,EAAE;EACzC;EACA;EACAN,MAAAA,UAAU,GAAG,SAAAA,UAAAqC,CAAAA,MAAM,EAAI;UACrB,IAAI,CAACnX,OAAO,EAAE;EACZ,UAAA,OAAA;EACF,SAAA;EACA2N,QAAAA,MAAM,CAAC,CAACwJ,MAAM,IAAIA,MAAM,CAAChjB,IAAI,GAAG,IAAIoZ,aAAa,CAAC,IAAI,EAAExN,MAAM,EAAEC,OAAO,CAAC,GAAGmX,MAAM,CAAC,CAAA;UAClFnX,OAAO,CAACoX,KAAK,EAAE,CAAA;EACfpX,QAAAA,OAAO,GAAG,IAAI,CAAA;SACf,CAAA;QAED0U,OAAO,CAACrB,WAAW,IAAIqB,OAAO,CAACrB,WAAW,CAACgE,SAAS,CAACvC,UAAU,CAAC,CAAA;QAChE,IAAIJ,OAAO,CAACU,MAAM,EAAE;EAClBV,QAAAA,OAAO,CAACU,MAAM,CAACkC,OAAO,GAAGxC,UAAU,EAAE,GAAGJ,OAAO,CAACU,MAAM,CAACrW,gBAAgB,CAAC,OAAO,EAAE+V,UAAU,CAAC,CAAA;EAC9F,OAAA;EACF,KAAA;EAEA,IAAA,IAAMlE,QAAQ,GAAG9C,aAAa,CAAC4G,OAAO,CAAC9Q,GAAG,CAAC,CAAA;EAE3C,IAAA,IAAIgN,QAAQ,IAAIzK,QAAQ,CAACd,SAAS,CAAChL,OAAO,CAACuW,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE;EAC3DjD,MAAAA,MAAM,CAAC,IAAI/N,UAAU,CAAC,uBAAuB,GAAGgR,QAAQ,GAAG,GAAG,EAAEhR,UAAU,CAACgO,eAAe,EAAE7N,MAAM,CAAC,CAAC,CAAA;EACpG,MAAA,OAAA;EACF,KAAA;;EAGA;EACAC,IAAAA,OAAO,CAACuX,IAAI,CAAC3C,WAAW,IAAI,IAAI,CAAC,CAAA;EACnC,GAAC,CAAC,CAAA;EACJ,CAAC;;EChMD,IAAM4C,cAAc,GAAG,SAAjBA,cAAcA,CAAIC,OAAO,EAAEnP,OAAO,EAAK;EAC3C,EAAA,IAAAoP,QAAA,GAAkBD,OAAO,GAAGA,OAAO,GAAGA,OAAO,CAAC7d,MAAM,CAACoa,OAAO,CAAC,GAAG,EAAE;MAA3D7c,MAAM,GAAAugB,QAAA,CAANvgB,MAAM,CAAA;IAEb,IAAImR,OAAO,IAAInR,MAAM,EAAE;EACrB,IAAA,IAAIwgB,UAAU,GAAG,IAAIC,eAAe,EAAE,CAAA;EAEtC,IAAA,IAAIN,OAAO,CAAA;EAEX,IAAA,IAAMnB,OAAO,GAAG,SAAVA,OAAOA,CAAa0B,MAAM,EAAE;QAChC,IAAI,CAACP,OAAO,EAAE;EACZA,QAAAA,OAAO,GAAG,IAAI,CAAA;EACdnC,QAAAA,WAAW,EAAE,CAAA;UACb,IAAM1J,GAAG,GAAGoM,MAAM,YAAYlb,KAAK,GAAGkb,MAAM,GAAG,IAAI,CAACA,MAAM,CAAA;UAC1DF,UAAU,CAACP,KAAK,CAAC3L,GAAG,YAAY7L,UAAU,GAAG6L,GAAG,GAAG,IAAI8B,aAAa,CAAC9B,GAAG,YAAY9O,KAAK,GAAG8O,GAAG,CAAC5L,OAAO,GAAG4L,GAAG,CAAC,CAAC,CAAA;EACjH,OAAA;OACD,CAAA;EAED,IAAA,IAAI0D,KAAK,GAAG7G,OAAO,IAAIhJ,UAAU,CAAC,YAAM;EACtC6P,MAAAA,KAAK,GAAG,IAAI,CAAA;EACZgH,MAAAA,OAAO,CAAC,IAAIvW,UAAU,CAAA,UAAA,CAAAP,MAAA,CAAYiJ,OAAO,EAAA,iBAAA,CAAA,EAAmB1I,UAAU,CAACgX,SAAS,CAAC,CAAC,CAAA;OACnF,EAAEtO,OAAO,CAAC,CAAA;EAEX,IAAA,IAAM6M,WAAW,GAAG,SAAdA,WAAWA,GAAS;EACxB,MAAA,IAAIsC,OAAO,EAAE;EACXtI,QAAAA,KAAK,IAAIG,YAAY,CAACH,KAAK,CAAC,CAAA;EAC5BA,QAAAA,KAAK,GAAG,IAAI,CAAA;EACZsI,QAAAA,OAAO,CAACzgB,OAAO,CAAC,UAAAoe,MAAM,EAAI;EACxBA,UAAAA,MAAM,CAACD,WAAW,GAAGC,MAAM,CAACD,WAAW,CAACgB,OAAO,CAAC,GAAGf,MAAM,CAACC,mBAAmB,CAAC,OAAO,EAAEc,OAAO,CAAC,CAAA;EACjG,SAAC,CAAC,CAAA;EACFsB,QAAAA,OAAO,GAAG,IAAI,CAAA;EAChB,OAAA;OACD,CAAA;EAEDA,IAAAA,OAAO,CAACzgB,OAAO,CAAC,UAACoe,MAAM,EAAA;EAAA,MAAA,OAAKA,MAAM,CAACrW,gBAAgB,CAAC,OAAO,EAAEoX,OAAO,CAAC,CAAA;OAAC,CAAA,CAAA;EAEtE,IAAA,IAAOf,MAAM,GAAIuC,UAAU,CAApBvC,MAAM,CAAA;MAEbA,MAAM,CAACD,WAAW,GAAG,YAAA;EAAA,MAAA,OAAM/U,OAAK,CAACb,IAAI,CAAC4V,WAAW,CAAC,CAAA;EAAA,KAAA,CAAA;EAElD,IAAA,OAAOC,MAAM,CAAA;EACf,GAAA;EACF,CAAC,CAAA;AAED,yBAAeoC,cAAc;;EC9CtB,IAAMM,WAAW,gBAAAC,mBAAA,EAAAC,CAAAA,IAAA,CAAG,SAAdF,WAAWA,CAAcG,KAAK,EAAEC,SAAS,EAAA;EAAA,EAAA,IAAAvgB,GAAA,EAAAwgB,GAAA,EAAAC,GAAA,CAAA;EAAA,EAAA,OAAAL,mBAAA,EAAA,CAAA5kB,IAAA,CAAA,SAAAklB,aAAAC,QAAA,EAAA;EAAA,IAAA,OAAA,CAAA,EAAA,QAAAA,QAAA,CAAAC,IAAA,GAAAD,QAAA,CAAAzd,IAAA;EAAA,MAAA,KAAA,CAAA;UAChDlD,GAAG,GAAGsgB,KAAK,CAACO,UAAU,CAAA;EAAA,QAAA,IAAA,EAEtB,CAACN,SAAS,IAAIvgB,GAAG,GAAGugB,SAAS,CAAA,EAAA;EAAAI,UAAAA,QAAA,CAAAzd,IAAA,GAAA,CAAA,CAAA;EAAA,UAAA,MAAA;EAAA,SAAA;EAAAyd,QAAAA,QAAA,CAAAzd,IAAA,GAAA,CAAA,CAAA;EAC/B,QAAA,OAAMod,KAAK,CAAA;EAAA,MAAA,KAAA,CAAA;UAAA,OAAAK,QAAA,CAAAG,MAAA,CAAA,QAAA,CAAA,CAAA;EAAA,MAAA,KAAA,CAAA;EAITN,QAAAA,GAAG,GAAG,CAAC,CAAA;EAAA,MAAA,KAAA,CAAA;UAAA,IAGJA,EAAAA,GAAG,GAAGxgB,GAAG,CAAA,EAAA;EAAA2gB,UAAAA,QAAA,CAAAzd,IAAA,GAAA,EAAA,CAAA;EAAA,UAAA,MAAA;EAAA,SAAA;UACdud,GAAG,GAAGD,GAAG,GAAGD,SAAS,CAAA;EAACI,QAAAA,QAAA,CAAAzd,IAAA,GAAA,EAAA,CAAA;EACtB,QAAA,OAAMod,KAAK,CAAClkB,KAAK,CAACokB,GAAG,EAAEC,GAAG,CAAC,CAAA;EAAA,MAAA,KAAA,EAAA;EAC3BD,QAAAA,GAAG,GAAGC,GAAG,CAAA;EAACE,QAAAA,QAAA,CAAAzd,IAAA,GAAA,CAAA,CAAA;EAAA,QAAA,MAAA;EAAA,MAAA,KAAA,EAAA,CAAA;EAAA,MAAA,KAAA,KAAA;UAAA,OAAAyd,QAAA,CAAAI,IAAA,EAAA,CAAA;EAAA,KAAA;EAAA,GAAA,EAdDZ,WAAW,CAAA,CAAA;EAAA,CAgBvB,CAAA,CAAA;EAEM,IAAMa,SAAS,gBAAA,YAAA;EAAA,EAAA,IAAAzhB,IAAA,GAAA0hB,mBAAA,eAAAb,mBAAA,EAAA,CAAAC,IAAA,CAAG,SAAAa,OAAAA,CAAiBC,QAAQ,EAAEZ,SAAS,EAAA;MAAA,IAAAa,yBAAA,EAAAC,iBAAA,EAAAC,cAAA,EAAA9N,SAAA,EAAAE,KAAA,EAAA4M,KAAA,CAAA;EAAA,IAAA,OAAAF,mBAAA,EAAA,CAAA5kB,IAAA,CAAA,SAAA+lB,SAAAC,SAAA,EAAA;EAAA,MAAA,OAAA,CAAA,EAAA,QAAAA,SAAA,CAAAZ,IAAA,GAAAY,SAAA,CAAAte,IAAA;EAAA,QAAA,KAAA,CAAA;YAAAke,yBAAA,GAAA,KAAA,CAAA;YAAAC,iBAAA,GAAA,KAAA,CAAA;EAAAG,UAAAA,SAAA,CAAAZ,IAAA,GAAA,CAAA,CAAA;EAAApN,UAAAA,SAAA,GAAAiO,cAAA,CACjCC,UAAU,CAACP,QAAQ,CAAC,CAAA,CAAA;EAAA,QAAA,KAAA,CAAA;EAAAK,UAAAA,SAAA,CAAAte,IAAA,GAAA,CAAA,CAAA;EAAA,UAAA,OAAAye,oBAAA,CAAAnO,SAAA,CAAAtQ,IAAA,EAAA,CAAA,CAAA;EAAA,QAAA,KAAA,CAAA;YAAA,IAAAke,EAAAA,yBAAA,KAAA1N,KAAA,GAAA8N,SAAA,CAAAI,IAAA,EAAAze,IAAA,CAAA,EAAA;EAAAqe,YAAAA,SAAA,CAAAte,IAAA,GAAA,EAAA,CAAA;EAAA,YAAA,MAAA;EAAA,WAAA;YAA7Bod,KAAK,GAAA5M,KAAA,CAAA9R,KAAA,CAAA;EACpB,UAAA,OAAA4f,SAAA,CAAAK,aAAA,CAAAC,uBAAA,CAAAL,cAAA,CAAOtB,WAAW,CAACG,KAAK,EAAEC,SAAS,CAAC,CAAA,CAAA,EAAA,IAAA,EAAA,CAAA,CAAA,CAAA;EAAA,QAAA,KAAA,CAAA;YAAAa,yBAAA,GAAA,KAAA,CAAA;EAAAI,UAAAA,SAAA,CAAAte,IAAA,GAAA,CAAA,CAAA;EAAA,UAAA,MAAA;EAAA,QAAA,KAAA,EAAA;EAAAse,UAAAA,SAAA,CAAAte,IAAA,GAAA,EAAA,CAAA;EAAA,UAAA,MAAA;EAAA,QAAA,KAAA,EAAA;EAAAse,UAAAA,SAAA,CAAAZ,IAAA,GAAA,EAAA,CAAA;YAAAY,SAAA,CAAAO,EAAA,GAAAP,SAAA,CAAA,OAAA,CAAA,CAAA,CAAA,CAAA,CAAA;YAAAH,iBAAA,GAAA,IAAA,CAAA;YAAAC,cAAA,GAAAE,SAAA,CAAAO,EAAA,CAAA;EAAA,QAAA,KAAA,EAAA;EAAAP,UAAAA,SAAA,CAAAZ,IAAA,GAAA,EAAA,CAAA;EAAAY,UAAAA,SAAA,CAAAZ,IAAA,GAAA,EAAA,CAAA;YAAA,IAAAQ,EAAAA,yBAAA,IAAA5N,SAAA,CAAA,QAAA,CAAA,IAAA,IAAA,CAAA,EAAA;EAAAgO,YAAAA,SAAA,CAAAte,IAAA,GAAA,EAAA,CAAA;EAAA,YAAA,MAAA;EAAA,WAAA;EAAAse,UAAAA,SAAA,CAAAte,IAAA,GAAA,EAAA,CAAA;YAAA,OAAAye,oBAAA,CAAAnO,SAAA,CAAA,QAAA,CAAA,EAAA,CAAA,CAAA;EAAA,QAAA,KAAA,EAAA;EAAAgO,UAAAA,SAAA,CAAAZ,IAAA,GAAA,EAAA,CAAA;EAAA,UAAA,IAAA,CAAAS,iBAAA,EAAA;EAAAG,YAAAA,SAAA,CAAAte,IAAA,GAAA,EAAA,CAAA;EAAA,YAAA,MAAA;EAAA,WAAA;EAAA,UAAA,MAAAoe,cAAA,CAAA;EAAA,QAAA,KAAA,EAAA;YAAA,OAAAE,SAAA,CAAAQ,MAAA,CAAA,EAAA,CAAA,CAAA;EAAA,QAAA,KAAA,EAAA;YAAA,OAAAR,SAAA,CAAAQ,MAAA,CAAA,EAAA,CAAA,CAAA;EAAA,QAAA,KAAA,EAAA,CAAA;EAAA,QAAA,KAAA,KAAA;YAAA,OAAAR,SAAA,CAAAT,IAAA,EAAA,CAAA;EAAA,OAAA;EAAA,KAAA,EAAAG,OAAA,EAAA,IAAA,EAAA,CAAA,CAAA,CAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,CAAA,EAAA,CAAA,EAAA,GAAA,EAAA,EAAA,EAAA,CAAA,CAAA,CAAA,CAAA;KAEvC,CAAA,CAAA,CAAA;EAAA,EAAA,OAAA,SAJYF,SAASA,CAAAiB,EAAA,EAAAC,GAAA,EAAA;EAAA,IAAA,OAAA3iB,IAAA,CAAA9D,KAAA,CAAA,IAAA,EAAAC,SAAA,CAAA,CAAA;EAAA,GAAA,CAAA;EAAA,CAIrB,EAAA,CAAA;EAED,IAAMgmB,UAAU,gBAAA,YAAA;IAAA,IAAA9gB,KAAA,GAAAqgB,mBAAA,eAAAb,mBAAA,GAAAC,IAAA,CAAG,SAAA8B,QAAAA,CAAiBC,MAAM,EAAA;EAAA,IAAA,IAAAC,MAAA,EAAAC,qBAAA,EAAAnf,IAAA,EAAAvB,KAAA,CAAA;EAAA,IAAA,OAAAwe,mBAAA,EAAA,CAAA5kB,IAAA,CAAA,SAAA+mB,UAAAC,SAAA,EAAA;EAAA,MAAA,OAAA,CAAA,EAAA,QAAAA,SAAA,CAAA5B,IAAA,GAAA4B,SAAA,CAAAtf,IAAA;EAAA,QAAA,KAAA,CAAA;EAAA,UAAA,IAAA,CACpCkf,MAAM,CAACvkB,MAAM,CAAC4kB,aAAa,CAAC,EAAA;EAAAD,YAAAA,SAAA,CAAAtf,IAAA,GAAA,CAAA,CAAA;EAAA,YAAA,MAAA;EAAA,WAAA;YAC9B,OAAAsf,SAAA,CAAAX,aAAA,CAAAC,uBAAA,CAAAL,cAAA,CAAOW,MAAM,CAAA,CAAA,EAAA,IAAA,EAAA,CAAA,CAAA,CAAA;EAAA,QAAA,KAAA,CAAA;YAAA,OAAAI,SAAA,CAAA1B,MAAA,CAAA,QAAA,CAAA,CAAA;EAAA,QAAA,KAAA,CAAA;EAITuB,UAAAA,MAAM,GAAGD,MAAM,CAACM,SAAS,EAAE,CAAA;EAAAF,UAAAA,SAAA,CAAA5B,IAAA,GAAA,CAAA,CAAA;EAAA,QAAA,KAAA,CAAA;EAAA4B,UAAAA,SAAA,CAAAtf,IAAA,GAAA,CAAA,CAAA;EAAA,UAAA,OAAAye,oBAAA,CAGDU,MAAM,CAAC1I,IAAI,EAAE,CAAA,CAAA;EAAA,QAAA,KAAA,CAAA;YAAA2I,qBAAA,GAAAE,SAAA,CAAAZ,IAAA,CAAA;YAAlCze,IAAI,GAAAmf,qBAAA,CAAJnf,IAAI,CAAA;YAAEvB,KAAK,GAAA0gB,qBAAA,CAAL1gB,KAAK,CAAA;EAAA,UAAA,IAAA,CACduB,IAAI,EAAA;EAAAqf,YAAAA,SAAA,CAAAtf,IAAA,GAAA,EAAA,CAAA;EAAA,YAAA,MAAA;EAAA,WAAA;YAAA,OAAAsf,SAAA,CAAA1B,MAAA,CAAA,OAAA,EAAA,EAAA,CAAA,CAAA;EAAA,QAAA,KAAA,EAAA;EAAA0B,UAAAA,SAAA,CAAAtf,IAAA,GAAA,EAAA,CAAA;EAGR,UAAA,OAAMtB,KAAK,CAAA;EAAA,QAAA,KAAA,EAAA;EAAA4gB,UAAAA,SAAA,CAAAtf,IAAA,GAAA,CAAA,CAAA;EAAA,UAAA,MAAA;EAAA,QAAA,KAAA,EAAA;EAAAsf,UAAAA,SAAA,CAAA5B,IAAA,GAAA,EAAA,CAAA;EAAA4B,UAAAA,SAAA,CAAAtf,IAAA,GAAA,EAAA,CAAA;EAAA,UAAA,OAAAye,oBAAA,CAGPU,MAAM,CAAC7C,MAAM,EAAE,CAAA,CAAA;EAAA,QAAA,KAAA,EAAA;YAAA,OAAAgD,SAAA,CAAAR,MAAA,CAAA,EAAA,CAAA,CAAA;EAAA,QAAA,KAAA,EAAA,CAAA;EAAA,QAAA,KAAA,KAAA;YAAA,OAAAQ,SAAA,CAAAzB,IAAA,EAAA,CAAA;EAAA,OAAA;EAAA,KAAA,EAAAoB,QAAA,EAAA,IAAA,EAAA,CAAA,CAAA,CAAA,GAAA,EAAA,EAAA,EAAA,CAAA,CAAA,CAAA,CAAA;KAExB,CAAA,CAAA,CAAA;IAAA,OAlBKT,SAAAA,UAAUA,CAAAiB,GAAA,EAAA;EAAA,IAAA,OAAA/hB,KAAA,CAAAnF,KAAA,CAAA,IAAA,EAAAC,SAAA,CAAA,CAAA;EAAA,GAAA,CAAA;EAAA,CAkBf,EAAA,CAAA;EAEM,IAAMknB,WAAW,GAAG,SAAdA,WAAWA,CAAIR,MAAM,EAAE7B,SAAS,EAAEsC,UAAU,EAAEC,QAAQ,EAAK;EACtE,EAAA,IAAM/kB,QAAQ,GAAGijB,SAAS,CAACoB,MAAM,EAAE7B,SAAS,CAAC,CAAA;IAE7C,IAAIhK,KAAK,GAAG,CAAC,CAAA;EACb,EAAA,IAAIpT,IAAI,CAAA;EACR,EAAA,IAAI4f,SAAS,GAAG,SAAZA,SAASA,CAAIxT,CAAC,EAAK;MACrB,IAAI,CAACpM,IAAI,EAAE;EACTA,MAAAA,IAAI,GAAG,IAAI,CAAA;EACX2f,MAAAA,QAAQ,IAAIA,QAAQ,CAACvT,CAAC,CAAC,CAAA;EACzB,KAAA;KACD,CAAA;IAED,OAAO,IAAIyT,cAAc,CAAC;MAClBC,IAAI,EAAA,SAAAA,IAACjD,CAAAA,UAAU,EAAE;EAAA,MAAA,OAAAkD,iBAAA,eAAA9C,mBAAA,EAAAC,CAAAA,IAAA,UAAA8C,QAAA,GAAA;UAAA,IAAAC,oBAAA,EAAAC,KAAA,EAAAzhB,KAAA,EAAA5B,GAAA,EAAAsjB,WAAA,CAAA;EAAA,QAAA,OAAAlD,mBAAA,EAAA,CAAA5kB,IAAA,CAAA,SAAA+nB,UAAAC,SAAA,EAAA;EAAA,UAAA,OAAA,CAAA,EAAA,QAAAA,SAAA,CAAA5C,IAAA,GAAA4C,SAAA,CAAAtgB,IAAA;EAAA,YAAA,KAAA,CAAA;EAAAsgB,cAAAA,SAAA,CAAA5C,IAAA,GAAA,CAAA,CAAA;EAAA4C,cAAAA,SAAA,CAAAtgB,IAAA,GAAA,CAAA,CAAA;EAAA,cAAA,OAESnF,QAAQ,CAACmF,IAAI,EAAE,CAAA;EAAA,YAAA,KAAA,CAAA;gBAAAkgB,oBAAA,GAAAI,SAAA,CAAA5B,IAAA,CAAA;gBAApCze,KAAI,GAAAigB,oBAAA,CAAJjgB,IAAI,CAAA;gBAAEvB,KAAK,GAAAwhB,oBAAA,CAALxhB,KAAK,CAAA;EAAA,cAAA,IAAA,CAEduB,KAAI,EAAA;EAAAqgB,gBAAAA,SAAA,CAAAtgB,IAAA,GAAA,EAAA,CAAA;EAAA,gBAAA,MAAA;EAAA,eAAA;EACP6f,cAAAA,SAAS,EAAE,CAAA;gBACV/C,UAAU,CAACyD,KAAK,EAAE,CAAA;gBAAC,OAAAD,SAAA,CAAA1C,MAAA,CAAA,QAAA,CAAA,CAAA;EAAA,YAAA,KAAA,EAAA;gBAIjB9gB,GAAG,GAAG4B,KAAK,CAACif,UAAU,CAAA;EAC1B,cAAA,IAAIgC,UAAU,EAAE;kBACVS,WAAW,GAAG/M,KAAK,IAAIvW,GAAG,CAAA;kBAC9B6iB,UAAU,CAACS,WAAW,CAAC,CAAA;EACzB,eAAA;gBACAtD,UAAU,CAAC0D,OAAO,CAAC,IAAI3gB,UAAU,CAACnB,KAAK,CAAC,CAAC,CAAA;EAAC4hB,cAAAA,SAAA,CAAAtgB,IAAA,GAAA,EAAA,CAAA;EAAA,cAAA,MAAA;EAAA,YAAA,KAAA,EAAA;EAAAsgB,cAAAA,SAAA,CAAA5C,IAAA,GAAA,EAAA,CAAA;gBAAA4C,SAAA,CAAAG,EAAA,GAAAH,SAAA,CAAA,OAAA,CAAA,CAAA,CAAA,CAAA,CAAA;EAE1CT,cAAAA,SAAS,CAAAS,SAAA,CAAAG,EAAI,CAAC,CAAA;gBAAC,MAAAH,SAAA,CAAAG,EAAA,CAAA;EAAA,YAAA,KAAA,EAAA,CAAA;EAAA,YAAA,KAAA,KAAA;gBAAA,OAAAH,SAAA,CAAAzC,IAAA,EAAA,CAAA;EAAA,WAAA;EAAA,SAAA,EAAAoC,QAAA,EAAA,IAAA,EAAA,CAAA,CAAA,CAAA,EAAA,EAAA,CAAA,CAAA,CAAA,CAAA;EAAA,OAAA,CAAA,CAAA,EAAA,CAAA;OAGlB;MACD3D,MAAM,EAAA,SAAAA,MAACU,CAAAA,MAAM,EAAE;QACb6C,SAAS,CAAC7C,MAAM,CAAC,CAAA;QACjB,OAAOniB,QAAQ,CAAO,QAAA,CAAA,EAAE,CAAA;EAC1B,KAAA;EACF,GAAC,EAAE;EACD6lB,IAAAA,aAAa,EAAE,CAAA;EACjB,GAAC,CAAC,CAAA;EACJ,CAAC;;EC5ED,IAAMC,gBAAgB,GAAG,OAAOC,KAAK,KAAK,UAAU,IAAI,OAAOC,OAAO,KAAK,UAAU,IAAI,OAAOC,QAAQ,KAAK,UAAU,CAAA;EACvH,IAAMC,yBAAyB,GAAGJ,gBAAgB,IAAI,OAAOb,cAAc,KAAK,UAAU,CAAA;;EAE1F;EACA,IAAMkB,UAAU,GAAGL,gBAAgB,KAAK,OAAOM,WAAW,KAAK,UAAU,GACpE,UAACrY,OAAO,EAAA;EAAA,EAAA,OAAK,UAAC5P,GAAG,EAAA;EAAA,IAAA,OAAK4P,OAAO,CAACP,MAAM,CAACrP,GAAG,CAAC,CAAA;EAAA,GAAA,CAAA;EAAA,CAAA,CAAE,IAAIioB,WAAW,EAAE,CAAC,kBAAA,YAAA;IAAA,IAAA5kB,IAAA,GAAA2jB,iBAAA,eAAA9C,mBAAA,GAAAC,IAAA,CAC9D,SAAAa,OAAAA,CAAOhlB,GAAG,EAAA;EAAA,IAAA,OAAAkkB,mBAAA,EAAA,CAAA5kB,IAAA,CAAA,SAAA+lB,SAAAZ,QAAA,EAAA;EAAA,MAAA,OAAA,CAAA,EAAA,QAAAA,QAAA,CAAAC,IAAA,GAAAD,QAAA,CAAAzd,IAAA;EAAA,QAAA,KAAA,CAAA;YAAAyd,QAAA,CAAAgD,EAAA,GAAS5gB,UAAU,CAAA;EAAA4d,UAAAA,QAAA,CAAAzd,IAAA,GAAA,CAAA,CAAA;YAAA,OAAO,IAAI8gB,QAAQ,CAAC9nB,GAAG,CAAC,CAACkoB,WAAW,EAAE,CAAA;EAAA,QAAA,KAAA,CAAA;EAAAzD,UAAAA,QAAA,CAAAoB,EAAA,GAAApB,QAAA,CAAAiB,IAAA,CAAA;YAAA,OAAAjB,QAAA,CAAAG,MAAA,CAAAH,QAAAA,EAAAA,IAAAA,QAAA,CAAAgD,EAAA,CAAAhD,QAAA,CAAAoB,EAAA,CAAA,CAAA,CAAA;EAAA,QAAA,KAAA,CAAA,CAAA;EAAA,QAAA,KAAA,KAAA;YAAA,OAAApB,QAAA,CAAAI,IAAA,EAAA,CAAA;EAAA,OAAA;EAAA,KAAA,EAAAG,OAAA,CAAA,CAAA;KAAC,CAAA,CAAA,CAAA;EAAA,EAAA,OAAA,UAAAe,EAAA,EAAA;EAAA,IAAA,OAAA1iB,IAAA,CAAA9D,KAAA,CAAA,IAAA,EAAAC,SAAA,CAAA,CAAA;EAAA,GAAA,CAAA;EAAA,CACvE,EAAA,CAAA,CAAA,CAAA;EAED,IAAMqO,IAAI,GAAG,SAAPA,IAAIA,CAAIzO,EAAE,EAAc;IAC5B,IAAI;MAAA,KAAAoZ,IAAAA,IAAA,GAAAhZ,SAAA,CAAA8D,MAAA,EADekY,IAAI,OAAA9a,KAAA,CAAA8X,IAAA,GAAAA,CAAAA,GAAAA,IAAA,WAAAvU,IAAA,GAAA,CAAA,EAAAA,IAAA,GAAAuU,IAAA,EAAAvU,IAAA,EAAA,EAAA;EAAJuX,MAAAA,IAAI,CAAAvX,IAAA,GAAAzE,CAAAA,CAAAA,GAAAA,SAAA,CAAAyE,IAAA,CAAA,CAAA;EAAA,KAAA;EAErB,IAAA,OAAO,CAAC,CAAC7E,EAAE,CAAAG,KAAA,CAAA,KAAA,CAAA,EAAIic,IAAI,CAAC,CAAA;KACrB,CAAC,OAAOnI,CAAC,EAAE;EACV,IAAA,OAAO,KAAK,CAAA;EACd,GAAA;EACF,CAAC,CAAA;EAED,IAAM8U,qBAAqB,GAAGJ,yBAAyB,IAAIla,IAAI,CAAC,YAAM;IACpE,IAAIua,cAAc,GAAG,KAAK,CAAA;IAE1B,IAAMC,cAAc,GAAG,IAAIR,OAAO,CAACvV,QAAQ,CAACJ,MAAM,EAAE;EAClDoW,IAAAA,IAAI,EAAE,IAAIxB,cAAc,EAAE;EAC1B9R,IAAAA,MAAM,EAAE,MAAM;MACd,IAAIuT,MAAMA,GAAG;EACXH,MAAAA,cAAc,GAAG,IAAI,CAAA;EACrB,MAAA,OAAO,MAAM,CAAA;EACf,KAAA;EACF,GAAC,CAAC,CAACzU,OAAO,CAACoE,GAAG,CAAC,cAAc,CAAC,CAAA;IAE9B,OAAOqQ,cAAc,IAAI,CAACC,cAAc,CAAA;EAC1C,CAAC,CAAC,CAAA;EAEF,IAAMG,kBAAkB,GAAG,EAAE,GAAG,IAAI,CAAA;EAEpC,IAAMC,sBAAsB,GAAGV,yBAAyB,IACtDla,IAAI,CAAC,YAAA;IAAA,OAAMtB,OAAK,CAAC1J,gBAAgB,CAAC,IAAIilB,QAAQ,CAAC,EAAE,CAAC,CAACQ,IAAI,CAAC,CAAA;EAAA,CAAC,CAAA,CAAA;EAG3D,IAAMI,SAAS,GAAG;EAChBxC,EAAAA,MAAM,EAAEuC,sBAAsB,IAAK,UAACE,GAAG,EAAA;MAAA,OAAKA,GAAG,CAACL,IAAI,CAAA;EAAA,GAAA;EACtD,CAAC,CAAA;EAEDX,gBAAgB,IAAM,UAACgB,GAAG,EAAK;EAC7B,EAAA,CAAC,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,UAAU,EAAE,QAAQ,CAAC,CAACxlB,OAAO,CAAC,UAAA7C,IAAI,EAAI;MACpE,CAACooB,SAAS,CAACpoB,IAAI,CAAC,KAAKooB,SAAS,CAACpoB,IAAI,CAAC,GAAGiM,OAAK,CAACxL,UAAU,CAAC4nB,GAAG,CAACroB,IAAI,CAAC,CAAC,GAAG,UAACqoB,GAAG,EAAA;EAAA,MAAA,OAAKA,GAAG,CAACroB,IAAI,CAAC,EAAE,CAAA;EAAA,KAAA,GACvF,UAACsoB,CAAC,EAAE1c,MAAM,EAAK;EACb,MAAA,MAAM,IAAIH,UAAU,CAAAP,iBAAAA,CAAAA,MAAA,CAAmBlL,IAAI,EAAsByL,oBAAAA,CAAAA,EAAAA,UAAU,CAAC8c,eAAe,EAAE3c,MAAM,CAAC,CAAA;EACtG,KAAC,CAAC,CAAA;EACN,GAAC,CAAC,CAAA;EACJ,CAAC,CAAE,IAAI4b,QAAQ,EAAA,CAAE,CAAA;EAEjB,IAAMgB,aAAa,gBAAA,YAAA;IAAA,IAAApkB,KAAA,GAAAsiB,iBAAA,eAAA9C,mBAAA,GAAAC,IAAA,CAAG,SAAA8B,QAAAA,CAAOqC,IAAI,EAAA;EAAA,IAAA,IAAAS,QAAA,CAAA;EAAA,IAAA,OAAA7E,mBAAA,EAAA,CAAA5kB,IAAA,CAAA,SAAA+mB,UAAAf,SAAA,EAAA;EAAA,MAAA,OAAA,CAAA,EAAA,QAAAA,SAAA,CAAAZ,IAAA,GAAAY,SAAA,CAAAte,IAAA;EAAA,QAAA,KAAA,CAAA;YAAA,IAC3BshB,EAAAA,IAAI,IAAI,IAAI,CAAA,EAAA;EAAAhD,YAAAA,SAAA,CAAAte,IAAA,GAAA,CAAA,CAAA;EAAA,YAAA,MAAA;EAAA,WAAA;EAAA,UAAA,OAAAse,SAAA,CAAAV,MAAA,CAAA,QAAA,EACP,CAAC,CAAA,CAAA;EAAA,QAAA,KAAA,CAAA;EAAA,UAAA,IAAA,CAGPrY,OAAK,CAACvK,MAAM,CAACsmB,IAAI,CAAC,EAAA;EAAAhD,YAAAA,SAAA,CAAAte,IAAA,GAAA,CAAA,CAAA;EAAA,YAAA,MAAA;EAAA,WAAA;EAAA,UAAA,OAAAse,SAAA,CAAAV,MAAA,CACZ0D,QAAAA,EAAAA,IAAI,CAACxe,IAAI,CAAA,CAAA;EAAA,QAAA,KAAA,CAAA;EAAA,UAAA,IAAA,CAGfyC,OAAK,CAACrC,mBAAmB,CAACoe,IAAI,CAAC,EAAA;EAAAhD,YAAAA,SAAA,CAAAte,IAAA,GAAA,CAAA,CAAA;EAAA,YAAA,MAAA;EAAA,WAAA;EAC1B+hB,UAAAA,QAAQ,GAAG,IAAIlB,OAAO,CAACvV,QAAQ,CAACJ,MAAM,EAAE;EAC5C8C,YAAAA,MAAM,EAAE,MAAM;EACdsT,YAAAA,IAAI,EAAJA,IAAAA;EACF,WAAC,CAAC,CAAA;EAAAhD,UAAAA,SAAA,CAAAte,IAAA,GAAA,CAAA,CAAA;EAAA,UAAA,OACY+hB,QAAQ,CAACb,WAAW,EAAE,CAAA;EAAA,QAAA,KAAA,CAAA;YAAA,OAAA5C,SAAA,CAAAV,MAAA,CAAA,QAAA,EAAAU,SAAA,CAAAI,IAAA,CAAEf,UAAU,CAAA,CAAA;EAAA,QAAA,KAAA,CAAA;EAAA,UAAA,IAAA,EAG/CpY,OAAK,CAACtL,iBAAiB,CAACqnB,IAAI,CAAC,IAAI/b,OAAK,CAACvL,aAAa,CAACsnB,IAAI,CAAC,CAAA,EAAA;EAAAhD,YAAAA,SAAA,CAAAte,IAAA,GAAA,EAAA,CAAA;EAAA,YAAA,MAAA;EAAA,WAAA;EAAA,UAAA,OAAAse,SAAA,CAAAV,MAAA,CACpD0D,QAAAA,EAAAA,IAAI,CAAC3D,UAAU,CAAA,CAAA;EAAA,QAAA,KAAA,EAAA;EAGxB,UAAA,IAAGpY,OAAK,CAAC/J,iBAAiB,CAAC8lB,IAAI,CAAC,EAAE;cAChCA,IAAI,GAAGA,IAAI,GAAG,EAAE,CAAA;EAClB,WAAA;EAAC,UAAA,IAAA,CAEE/b,OAAK,CAACjL,QAAQ,CAACgnB,IAAI,CAAC,EAAA;EAAAhD,YAAAA,SAAA,CAAAte,IAAA,GAAA,EAAA,CAAA;EAAA,YAAA,MAAA;EAAA,WAAA;EAAAse,UAAAA,SAAA,CAAAte,IAAA,GAAA,EAAA,CAAA;YAAA,OACPghB,UAAU,CAACM,IAAI,CAAC,CAAA;EAAA,QAAA,KAAA,EAAA;YAAA,OAAAhD,SAAA,CAAAV,MAAA,CAAA,QAAA,EAAAU,SAAA,CAAAI,IAAA,CAAEf,UAAU,CAAA,CAAA;EAAA,QAAA,KAAA,EAAA,CAAA;EAAA,QAAA,KAAA,KAAA;YAAA,OAAAW,SAAA,CAAAT,IAAA,EAAA,CAAA;EAAA,OAAA;EAAA,KAAA,EAAAoB,QAAA,CAAA,CAAA;KAE7C,CAAA,CAAA,CAAA;IAAA,OA5BK6C,SAAAA,aAAaA,CAAA9C,GAAA,EAAA;EAAA,IAAA,OAAAthB,KAAA,CAAAnF,KAAA,CAAA,IAAA,EAAAC,SAAA,CAAA,CAAA;EAAA,GAAA,CAAA;EAAA,CA4BlB,EAAA,CAAA;EAED,IAAMwpB,iBAAiB,gBAAA,YAAA;EAAA,EAAA,IAAA/jB,KAAA,GAAA+hB,iBAAA,eAAA9C,mBAAA,EAAA,CAAAC,IAAA,CAAG,SAAA8C,QAAAA,CAAOtT,OAAO,EAAE2U,IAAI,EAAA;EAAA,IAAA,IAAAhlB,MAAA,CAAA;EAAA,IAAA,OAAA4gB,mBAAA,EAAA,CAAA5kB,IAAA,CAAA,SAAA+nB,UAAAf,SAAA,EAAA;EAAA,MAAA,OAAA,CAAA,EAAA,QAAAA,SAAA,CAAA5B,IAAA,GAAA4B,SAAA,CAAAtf,IAAA;EAAA,QAAA,KAAA,CAAA;YACtC1D,MAAM,GAAGiJ,OAAK,CAAClD,cAAc,CAACsK,OAAO,CAACsV,gBAAgB,EAAE,CAAC,CAAA;EAAA,UAAA,OAAA3C,SAAA,CAAA1B,MAAA,CAAA,QAAA,EAExDthB,MAAM,IAAI,IAAI,GAAGwlB,aAAa,CAACR,IAAI,CAAC,GAAGhlB,MAAM,CAAA,CAAA;EAAA,QAAA,KAAA,CAAA,CAAA;EAAA,QAAA,KAAA,KAAA;YAAA,OAAAgjB,SAAA,CAAAzB,IAAA,EAAA,CAAA;EAAA,OAAA;EAAA,KAAA,EAAAoC,QAAA,CAAA,CAAA;KACrD,CAAA,CAAA,CAAA;EAAA,EAAA,OAAA,SAJK+B,iBAAiBA,CAAAvC,GAAA,EAAAyC,GAAA,EAAA;EAAA,IAAA,OAAAjkB,KAAA,CAAA1F,KAAA,CAAA,IAAA,EAAAC,SAAA,CAAA,CAAA;EAAA,GAAA,CAAA;EAAA,CAItB,EAAA,CAAA;AAED,qBAAemoB,gBAAgB,mBAAA,YAAA;IAAA,IAAA3f,KAAA,GAAAgf,iBAAA,eAAA9C,mBAAA,GAAAC,IAAA,CAAK,SAAAgF,QAAAA,CAAOjd,MAAM,EAAA;EAAA,IAAA,IAAAkd,cAAA,EAAArZ,GAAA,EAAAiF,MAAA,EAAA5J,IAAA,EAAAmW,MAAA,EAAA/B,WAAA,EAAA/K,OAAA,EAAAyK,kBAAA,EAAAD,gBAAA,EAAA3K,YAAA,EAAAX,OAAA,EAAA0V,qBAAA,EAAAtK,eAAA,EAAAuK,YAAA,EAAAC,cAAA,EAAApd,OAAA,EAAAmV,WAAA,EAAAkI,oBAAA,EAAAT,QAAA,EAAAU,iBAAA,EAAAC,qBAAA,EAAAC,sBAAA,EAAAhD,UAAA,EAAAhL,KAAA,EAAAiO,sBAAA,EAAAxd,QAAA,EAAAyd,gBAAA,EAAA7b,OAAA,EAAA8b,qBAAA,EAAA3e,KAAA,EAAA4e,KAAA,EAAAC,WAAA,EAAAC,MAAA,EAAApI,YAAA,CAAA;EAAA,IAAA,OAAAqC,mBAAA,EAAA,CAAA5kB,IAAA,CAAA,SAAA4qB,UAAA5C,SAAA,EAAA;EAAA,MAAA,OAAA,CAAA,EAAA,QAAAA,SAAA,CAAA5C,IAAA,GAAA4C,SAAA,CAAAtgB,IAAA;EAAA,QAAA,KAAA,CAAA;EAAAoiB,UAAAA,cAAA,GAc3CtI,aAAa,CAAC5U,MAAM,CAAC,EAZvB6D,GAAG,GAAAqZ,cAAA,CAAHrZ,GAAG,EACHiF,MAAM,GAAAoU,cAAA,CAANpU,MAAM,EACN5J,IAAI,GAAAge,cAAA,CAAJhe,IAAI,EACJmW,MAAM,GAAA6H,cAAA,CAAN7H,MAAM,EACN/B,WAAW,GAAA4J,cAAA,CAAX5J,WAAW,EACX/K,OAAO,GAAA2U,cAAA,CAAP3U,OAAO,EACPyK,kBAAkB,GAAAkK,cAAA,CAAlBlK,kBAAkB,EAClBD,gBAAgB,GAAAmK,cAAA,CAAhBnK,gBAAgB,EAChB3K,YAAY,GAAA8U,cAAA,CAAZ9U,YAAY,EACZX,OAAO,GAAAyV,cAAA,CAAPzV,OAAO,EAAA0V,qBAAA,GAAAD,cAAA,CACPrK,eAAe,EAAfA,eAAe,GAAAsK,qBAAA,KAAG,KAAA,CAAA,GAAA,aAAa,GAAAA,qBAAA,EAC/BC,YAAY,GAAAF,cAAA,CAAZE,YAAY,CAAA;EAGdhV,UAAAA,YAAY,GAAGA,YAAY,GAAG,CAACA,YAAY,GAAG,EAAE,EAAEnU,WAAW,EAAE,GAAG,MAAM,CAAA;EAEpEopB,UAAAA,cAAc,GAAG5F,gBAAc,CAAC,CAACpC,MAAM,EAAE/B,WAAW,IAAIA,WAAW,CAAC2K,aAAa,EAAE,CAAC,EAAE1V,OAAO,CAAC,CAAA;EAI5F6M,UAAAA,WAAW,GAAGiI,cAAc,IAAIA,cAAc,CAACjI,WAAW,IAAK,YAAM;cACvEiI,cAAc,CAACjI,WAAW,EAAE,CAAA;aAC9B,CAAA;EAAAgG,UAAAA,SAAA,CAAA5C,IAAA,GAAA,CAAA,CAAA;EAAA4C,UAAAA,SAAA,CAAAG,EAAA,GAMExI,gBAAgB,IAAIkJ,qBAAqB,IAAInT,MAAM,KAAK,KAAK,IAAIA,MAAM,KAAK,MAAM,CAAA;YAAA,IAAAsS,CAAAA,SAAA,CAAAG,EAAA,EAAA;EAAAH,YAAAA,SAAA,CAAAtgB,IAAA,GAAA,EAAA,CAAA;EAAA,YAAA,MAAA;EAAA,WAAA;EAAAsgB,UAAAA,SAAA,CAAAtgB,IAAA,GAAA,CAAA,CAAA;EAAA,UAAA,OACpDgiB,iBAAiB,CAACrV,OAAO,EAAEvI,IAAI,CAAC,CAAA;EAAA,QAAA,KAAA,CAAA;EAAAkc,UAAAA,SAAA,CAAAzB,EAAA,GAA7D2D,oBAAoB,GAAAlC,SAAA,CAAA5B,IAAA,CAAA;EAAA4B,UAAAA,SAAA,CAAAG,EAAA,GAAAH,SAAA,CAAAzB,EAAA,KAA+C,CAAC,CAAA;EAAA,QAAA,KAAA,EAAA;YAAA,IAAAyB,CAAAA,SAAA,CAAAG,EAAA,EAAA;EAAAH,YAAAA,SAAA,CAAAtgB,IAAA,GAAA,EAAA,CAAA;EAAA,YAAA,MAAA;EAAA,WAAA;EAEjE+hB,UAAAA,QAAQ,GAAG,IAAIlB,OAAO,CAAC9X,GAAG,EAAE;EAC9BiF,YAAAA,MAAM,EAAE,MAAM;EACdsT,YAAAA,IAAI,EAAEld,IAAI;EACVmd,YAAAA,MAAM,EAAE,MAAA;EACV,WAAC,CAAC,CAAA;EAIF,UAAA,IAAIhc,OAAK,CAACnK,UAAU,CAACgJ,IAAI,CAAC,KAAKqe,iBAAiB,GAAGV,QAAQ,CAACpV,OAAO,CAACmE,GAAG,CAAC,cAAc,CAAC,CAAC,EAAE;EACxFnE,YAAAA,OAAO,CAACK,cAAc,CAACyV,iBAAiB,CAAC,CAAA;EAC3C,WAAA;YAEA,IAAIV,QAAQ,CAACT,IAAI,EAAE;cAAAoB,qBAAA,GACW/M,sBAAsB,CAChD6M,oBAAoB,EACpB5N,oBAAoB,CAACgB,cAAc,CAACqC,gBAAgB,CAAC,CACvD,CAAC,EAAA0K,sBAAA,GAAA/mB,cAAA,CAAA8mB,qBAAA,EAAA,CAAA,CAAA,EAHM/C,UAAU,GAAAgD,sBAAA,CAAA,CAAA,CAAA,EAAEhO,KAAK,GAAAgO,sBAAA,CAAA,CAAA,CAAA,CAAA;EAKxBve,YAAAA,IAAI,GAAGsb,WAAW,CAACqC,QAAQ,CAACT,IAAI,EAAEE,kBAAkB,EAAE7B,UAAU,EAAEhL,KAAK,CAAC,CAAA;EAC1E,WAAA;EAAC,QAAA,KAAA,EAAA;EAGH,UAAA,IAAI,CAACpP,OAAK,CAACjL,QAAQ,CAACyd,eAAe,CAAC,EAAE;EACpCA,YAAAA,eAAe,GAAGA,eAAe,GAAG,SAAS,GAAG,MAAM,CAAA;EACxD,WAAA;;EAEA;EACA;EACM6K,UAAAA,sBAAsB,GAAG,aAAa,IAAI/B,OAAO,CAACloB,SAAS,CAAA;YACjEwM,OAAO,GAAG,IAAI0b,OAAO,CAAC9X,GAAG,EAAAsC,cAAA,CAAAA,cAAA,CAAA,EAAA,EACpBiX,YAAY,CAAA,EAAA,EAAA,EAAA;EACf/H,YAAAA,MAAM,EAAEgI,cAAc;EACtBvU,YAAAA,MAAM,EAAEA,MAAM,CAAClN,WAAW,EAAE;cAC5B6L,OAAO,EAAEA,OAAO,CAACyE,SAAS,EAAE,CAAC5L,MAAM,EAAE;EACrC8b,YAAAA,IAAI,EAAEld,IAAI;EACVmd,YAAAA,MAAM,EAAE,MAAM;EACd6B,YAAAA,WAAW,EAAER,sBAAsB,GAAG7K,eAAe,GAAGxb,SAAAA;EAAS,WAAA,CAClE,CAAC,CAAA;EAAC+jB,UAAAA,SAAA,CAAAtgB,IAAA,GAAA,EAAA,CAAA;YAAA,OAEkB4gB,KAAK,CAACzb,OAAO,CAAC,CAAA;EAAA,QAAA,KAAA,EAAA;YAA/BC,QAAQ,GAAAkb,SAAA,CAAA5B,IAAA,CAAA;YAENmE,gBAAgB,GAAGpB,sBAAsB,KAAKnU,YAAY,KAAK,QAAQ,IAAIA,YAAY,KAAK,UAAU,CAAC,CAAA;YAE7G,IAAImU,sBAAsB,KAAKvJ,kBAAkB,IAAK2K,gBAAgB,IAAIvI,WAAY,CAAC,EAAE;cACjFtT,OAAO,GAAG,EAAE,CAAA;cAElB,CAAC,QAAQ,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC7K,OAAO,CAAC,UAAA8C,IAAI,EAAI;EAClD+H,cAAAA,OAAO,CAAC/H,IAAI,CAAC,GAAGmG,QAAQ,CAACnG,IAAI,CAAC,CAAA;EAChC,aAAC,CAAC,CAAA;EAEI6jB,YAAAA,qBAAqB,GAAGvd,OAAK,CAAClD,cAAc,CAAC+C,QAAQ,CAACuH,OAAO,CAACmE,GAAG,CAAC,gBAAgB,CAAC,CAAC,CAAA;EAAA3M,YAAAA,KAAA,GAE9D+T,kBAAkB,IAAIvC,sBAAsB,CACtEmN,qBAAqB,EACrBlO,oBAAoB,CAACgB,cAAc,CAACsC,kBAAkB,CAAC,EAAE,IAAI,CAC/D,CAAC,IAAI,EAAE,EAAA6K,KAAA,GAAAnnB,cAAA,CAAAuI,KAAA,EAHAwb,CAAAA,CAAAA,EAAAA,WAAU,GAAAoD,KAAA,CAAEpO,CAAAA,CAAAA,EAAAA,MAAK,GAAAoO,KAAA,CAAA,CAAA,CAAA,CAAA;EAKxB3d,YAAAA,QAAQ,GAAG,IAAI0b,QAAQ,CACrBpB,WAAW,CAACta,QAAQ,CAACkc,IAAI,EAAEE,kBAAkB,EAAE7B,WAAU,EAAE,YAAM;gBAC/DhL,MAAK,IAAIA,MAAK,EAAE,CAAA;gBAChB2F,WAAW,IAAIA,WAAW,EAAE,CAAA;eAC7B,CAAC,EACFtT,OACF,CAAC,CAAA;EACH,WAAA;YAEAsG,YAAY,GAAGA,YAAY,IAAI,MAAM,CAAA;EAACgT,UAAAA,SAAA,CAAAtgB,IAAA,GAAA,EAAA,CAAA;EAAA,UAAA,OAEb0hB,SAAS,CAACnc,OAAK,CAACvI,OAAO,CAAC0kB,SAAS,EAAEpU,YAAY,CAAC,IAAI,MAAM,CAAC,CAAClI,QAAQ,EAAEF,MAAM,CAAC,CAAA;EAAA,QAAA,KAAA,EAAA;YAAlG2V,YAAY,GAAAyF,SAAA,CAAA5B,IAAA,CAAA;EAEhB,UAAA,CAACmE,gBAAgB,IAAIvI,WAAW,IAAIA,WAAW,EAAE,CAAA;EAACgG,UAAAA,SAAA,CAAAtgB,IAAA,GAAA,EAAA,CAAA;EAAA,UAAA,OAErC,IAAI2Z,OAAO,CAAC,UAAC9G,OAAO,EAAEC,MAAM,EAAK;EAC5CF,YAAAA,MAAM,CAACC,OAAO,EAAEC,MAAM,EAAE;EACtB1O,cAAAA,IAAI,EAAEyW,YAAY;gBAClBlO,OAAO,EAAE+C,cAAY,CAAC5J,IAAI,CAACV,QAAQ,CAACuH,OAAO,CAAC;gBAC5CrH,MAAM,EAAEF,QAAQ,CAACE,MAAM;gBACvByV,UAAU,EAAE3V,QAAQ,CAAC2V,UAAU;EAC/B7V,cAAAA,MAAM,EAANA,MAAM;EACNC,cAAAA,OAAO,EAAPA,OAAAA;EACF,aAAC,CAAC,CAAA;EACJ,WAAC,CAAC,CAAA;EAAA,QAAA,KAAA,EAAA;EAAA,UAAA,OAAAmb,SAAA,CAAA1C,MAAA,CAAA0C,QAAAA,EAAAA,SAAA,CAAA5B,IAAA,CAAA,CAAA;EAAA,QAAA,KAAA,EAAA;EAAA4B,UAAAA,SAAA,CAAA5C,IAAA,GAAA,EAAA,CAAA;YAAA4C,SAAA,CAAA+C,EAAA,GAAA/C,SAAA,CAAA,OAAA,CAAA,CAAA,CAAA,CAAA,CAAA;YAEFhG,WAAW,IAAIA,WAAW,EAAE,CAAA;YAAC,IAEzBgG,EAAAA,SAAA,CAAA+C,EAAA,IAAO/C,SAAA,CAAA+C,EAAA,CAAI9hB,IAAI,KAAK,WAAW,IAAI,QAAQ,CAACsF,IAAI,CAACyZ,SAAA,CAAA+C,EAAA,CAAIre,OAAO,CAAC,CAAA,EAAA;EAAAsb,YAAAA,SAAA,CAAAtgB,IAAA,GAAA,EAAA,CAAA;EAAA,YAAA,MAAA;EAAA,WAAA;EAAA,UAAA,MACzDtH,MAAM,CAACiG,MAAM,CACjB,IAAIoG,UAAU,CAAC,eAAe,EAAEA,UAAU,CAAC4W,WAAW,EAAEzW,MAAM,EAAEC,OAAO,CAAC,EACxE;cACEe,KAAK,EAAEoa,SAAA,CAAA+C,EAAA,CAAInd,KAAK,IAAAoa,SAAA,CAAA+C,EAAAA;EAClB,WACF,CAAC,CAAA;EAAA,QAAA,KAAA,EAAA;YAAA,MAGGte,UAAU,CAACe,IAAI,CAAAwa,SAAA,CAAA+C,EAAA,EAAM/C,SAAA,CAAA+C,EAAA,IAAO/C,SAAA,CAAA+C,EAAA,CAAIpe,IAAI,EAAEC,MAAM,EAAEC,OAAO,CAAC,CAAA;EAAA,QAAA,KAAA,EAAA,CAAA;EAAA,QAAA,KAAA,KAAA;YAAA,OAAAmb,SAAA,CAAAzC,IAAA,EAAA,CAAA;EAAA,OAAA;EAAA,KAAA,EAAAsE,QAAA,EAAA,IAAA,EAAA,CAAA,CAAA,CAAA,EAAA,EAAA,CAAA,CAAA,CAAA,CAAA;KAE/D,CAAA,CAAA,CAAA;EAAA,EAAA,OAAA,UAAAmB,GAAA,EAAA;EAAA,IAAA,OAAAtiB,KAAA,CAAAzI,KAAA,CAAA,IAAA,EAAAC,SAAA,CAAA,CAAA;EAAA,GAAA,CAAA;EAAA,CAAC,EAAA,CAAA;;EC5NF,IAAM+qB,aAAa,GAAG;EACpBC,EAAAA,IAAI,EAAEC,WAAW;EACjBC,EAAAA,GAAG,EAAEC,UAAU;EACf/C,EAAAA,KAAK,EAAEgD,YAAAA;EACT,CAAC,CAAA;AAEDre,SAAK,CAACpJ,OAAO,CAAConB,aAAa,EAAE,UAACnrB,EAAE,EAAEsG,KAAK,EAAK;EAC1C,EAAA,IAAItG,EAAE,EAAE;MACN,IAAI;EACFM,MAAAA,MAAM,CAAC+F,cAAc,CAACrG,EAAE,EAAE,MAAM,EAAE;EAACsG,QAAAA,KAAK,EAALA,KAAAA;EAAK,OAAC,CAAC,CAAA;OAC3C,CAAC,OAAO2N,CAAC,EAAE;EACV;EAAA,KAAA;EAEF3T,IAAAA,MAAM,CAAC+F,cAAc,CAACrG,EAAE,EAAE,aAAa,EAAE;EAACsG,MAAAA,KAAK,EAALA,KAAAA;EAAK,KAAC,CAAC,CAAA;EACnD,GAAA;EACF,CAAC,CAAC,CAAA;EAEF,IAAMmlB,YAAY,GAAG,SAAfA,YAAYA,CAAI7G,MAAM,EAAA;IAAA,OAAAxY,IAAAA,CAAAA,MAAA,CAAUwY,MAAM,CAAA,CAAA;EAAA,CAAE,CAAA;EAE9C,IAAM8G,gBAAgB,GAAG,SAAnBA,gBAAgBA,CAAIrX,OAAO,EAAA;EAAA,EAAA,OAAKlH,OAAK,CAACxL,UAAU,CAAC0S,OAAO,CAAC,IAAIA,OAAO,KAAK,IAAI,IAAIA,OAAO,KAAK,KAAK,CAAA;EAAA,CAAA,CAAA;AAExG,iBAAe;EACbsX,EAAAA,UAAU,EAAE,SAAAA,UAACC,CAAAA,QAAQ,EAAK;EACxBA,IAAAA,QAAQ,GAAGze,OAAK,CAAC9L,OAAO,CAACuqB,QAAQ,CAAC,GAAGA,QAAQ,GAAG,CAACA,QAAQ,CAAC,CAAA;MAE1D,IAAAC,SAAA,GAAiBD,QAAQ;QAAlB1nB,MAAM,GAAA2nB,SAAA,CAAN3nB,MAAM,CAAA;EACb,IAAA,IAAI4nB,aAAa,CAAA;EACjB,IAAA,IAAIzX,OAAO,CAAA;MAEX,IAAM0X,eAAe,GAAG,EAAE,CAAA;MAE1B,KAAK,IAAIznB,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGJ,MAAM,EAAEI,CAAC,EAAE,EAAE;EAC/BwnB,MAAAA,aAAa,GAAGF,QAAQ,CAACtnB,CAAC,CAAC,CAAA;EAC3B,MAAA,IAAIoN,EAAE,GAAA,KAAA,CAAA,CAAA;EAEN2C,MAAAA,OAAO,GAAGyX,aAAa,CAAA;EAEvB,MAAA,IAAI,CAACJ,gBAAgB,CAACI,aAAa,CAAC,EAAE;EACpCzX,QAAAA,OAAO,GAAG8W,aAAa,CAAC,CAACzZ,EAAE,GAAGxK,MAAM,CAAC4kB,aAAa,CAAC,EAAE/qB,WAAW,EAAE,CAAC,CAAA;UAEnE,IAAIsT,OAAO,KAAKlQ,SAAS,EAAE;EACzB,UAAA,MAAM,IAAIwI,UAAU,CAAA,mBAAA,CAAAP,MAAA,CAAqBsF,EAAE,MAAG,CAAC,CAAA;EACjD,SAAA;EACF,OAAA;EAEA,MAAA,IAAI2C,OAAO,EAAE;EACX,QAAA,MAAA;EACF,OAAA;QAEA0X,eAAe,CAACra,EAAE,IAAI,GAAG,GAAGpN,CAAC,CAAC,GAAG+P,OAAO,CAAA;EAC1C,KAAA;MAEA,IAAI,CAACA,OAAO,EAAE;EAEZ,MAAA,IAAM2X,OAAO,GAAG1rB,MAAM,CAACsT,OAAO,CAACmY,eAAe,CAAC,CAC5CzoB,GAAG,CAAC,UAAAW,IAAA,EAAA;EAAA,QAAA,IAAAqB,KAAA,GAAA9B,cAAA,CAAAS,IAAA,EAAA,CAAA,CAAA;EAAEyN,UAAAA,EAAE,GAAApM,KAAA,CAAA,CAAA,CAAA;EAAE2mB,UAAAA,KAAK,GAAA3mB,KAAA,CAAA,CAAA,CAAA,CAAA;EAAA,QAAA,OAAM,UAAA8G,CAAAA,MAAA,CAAWsF,EAAE,EAChCua,GAAAA,CAAAA,IAAAA,KAAK,KAAK,KAAK,GAAG,qCAAqC,GAAG,+BAA+B,CAAC,CAAA;EAAA,OAC7F,CAAC,CAAA;EAEH,MAAA,IAAI5T,CAAC,GAAGnU,MAAM,GACX8nB,OAAO,CAAC9nB,MAAM,GAAG,CAAC,GAAG,WAAW,GAAG8nB,OAAO,CAAC1oB,GAAG,CAACmoB,YAAY,CAAC,CAACpd,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,GAAGod,YAAY,CAACO,OAAO,CAAC,CAAC,CAAC,CAAC,GACzG,yBAAyB,CAAA;EAE3B,MAAA,MAAM,IAAIrf,UAAU,CAClB,0DAA0D0L,CAAC,EAC3D,iBACF,CAAC,CAAA;EACH,KAAA;EAEA,IAAA,OAAOhE,OAAO,CAAA;KACf;EACDuX,EAAAA,QAAQ,EAAET,aAAAA;EACZ,CAAC;;ECrED;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASe,4BAA4BA,CAACpf,MAAM,EAAE;IAC5C,IAAIA,MAAM,CAACsT,WAAW,EAAE;EACtBtT,IAAAA,MAAM,CAACsT,WAAW,CAAC+L,gBAAgB,EAAE,CAAA;EACvC,GAAA;IAEA,IAAIrf,MAAM,CAACqV,MAAM,IAAIrV,MAAM,CAACqV,MAAM,CAACkC,OAAO,EAAE;EAC1C,IAAA,MAAM,IAAI/J,aAAa,CAAC,IAAI,EAAExN,MAAM,CAAC,CAAA;EACvC,GAAA;EACF,CAAA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACe,SAASsf,eAAeA,CAACtf,MAAM,EAAE;IAC9Cof,4BAA4B,CAACpf,MAAM,CAAC,CAAA;IAEpCA,MAAM,CAACyH,OAAO,GAAG+C,cAAY,CAAC5J,IAAI,CAACZ,MAAM,CAACyH,OAAO,CAAC,CAAA;;EAElD;EACAzH,EAAAA,MAAM,CAACd,IAAI,GAAGiO,aAAa,CAACpZ,IAAI,CAC9BiM,MAAM,EACNA,MAAM,CAACwH,gBACT,CAAC,CAAA;EAED,EAAA,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,CAAClN,OAAO,CAAC0F,MAAM,CAAC8I,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE;MAC1D9I,MAAM,CAACyH,OAAO,CAACK,cAAc,CAAC,mCAAmC,EAAE,KAAK,CAAC,CAAA;EAC3E,GAAA;EAEA,EAAA,IAAMP,OAAO,GAAGuX,QAAQ,CAACD,UAAU,CAAC7e,MAAM,CAACuH,OAAO,IAAIH,UAAQ,CAACG,OAAO,CAAC,CAAA;IAEvE,OAAOA,OAAO,CAACvH,MAAM,CAAC,CAACvB,IAAI,CAAC,SAAS8gB,mBAAmBA,CAACrf,QAAQ,EAAE;MACjEkf,4BAA4B,CAACpf,MAAM,CAAC,CAAA;;EAEpC;EACAE,IAAAA,QAAQ,CAAChB,IAAI,GAAGiO,aAAa,CAACpZ,IAAI,CAChCiM,MAAM,EACNA,MAAM,CAACkI,iBAAiB,EACxBhI,QACF,CAAC,CAAA;MAEDA,QAAQ,CAACuH,OAAO,GAAG+C,cAAY,CAAC5J,IAAI,CAACV,QAAQ,CAACuH,OAAO,CAAC,CAAA;EAEtD,IAAA,OAAOvH,QAAQ,CAAA;EACjB,GAAC,EAAE,SAASsf,kBAAkBA,CAAC1H,MAAM,EAAE;EACrC,IAAA,IAAI,CAACxK,QAAQ,CAACwK,MAAM,CAAC,EAAE;QACrBsH,4BAA4B,CAACpf,MAAM,CAAC,CAAA;;EAEpC;EACA,MAAA,IAAI8X,MAAM,IAAIA,MAAM,CAAC5X,QAAQ,EAAE;EAC7B4X,QAAAA,MAAM,CAAC5X,QAAQ,CAAChB,IAAI,GAAGiO,aAAa,CAACpZ,IAAI,CACvCiM,MAAM,EACNA,MAAM,CAACkI,iBAAiB,EACxB4P,MAAM,CAAC5X,QACT,CAAC,CAAA;EACD4X,QAAAA,MAAM,CAAC5X,QAAQ,CAACuH,OAAO,GAAG+C,cAAY,CAAC5J,IAAI,CAACkX,MAAM,CAAC5X,QAAQ,CAACuH,OAAO,CAAC,CAAA;EACtE,OAAA;EACF,KAAA;EAEA,IAAA,OAAOgN,OAAO,CAAC7G,MAAM,CAACkK,MAAM,CAAC,CAAA;EAC/B,GAAC,CAAC,CAAA;EACJ;;EChFO,IAAM2H,OAAO,GAAG,OAAO;;ECK9B,IAAMC,YAAU,GAAG,EAAE,CAAA;;EAErB;EACA,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAACzoB,OAAO,CAAC,UAAC7C,IAAI,EAAEoD,CAAC,EAAK;IACnFkoB,YAAU,CAACtrB,IAAI,CAAC,GAAG,SAASurB,SAASA,CAAC9rB,KAAK,EAAE;EAC3C,IAAA,OAAOS,OAAA,CAAOT,KAAK,CAAKO,KAAAA,IAAI,IAAI,GAAG,IAAIoD,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,GAAG,CAAC,GAAGpD,IAAI,CAAA;KAClE,CAAA;EACH,CAAC,CAAC,CAAA;EAEF,IAAMwrB,kBAAkB,GAAG,EAAE,CAAA;;EAE7B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AACAF,cAAU,CAACrY,YAAY,GAAG,SAASA,YAAYA,CAACsY,SAAS,EAAEE,OAAO,EAAE/f,OAAO,EAAE;EAC3E,EAAA,SAASggB,aAAaA,CAACC,GAAG,EAAEC,IAAI,EAAE;EAChC,IAAA,OAAO,UAAU,GAAGP,OAAO,GAAG,0BAA0B,GAAGM,GAAG,GAAG,IAAI,GAAGC,IAAI,IAAIlgB,OAAO,GAAG,IAAI,GAAGA,OAAO,GAAG,EAAE,CAAC,CAAA;EAChH,GAAA;;EAEA;EACA,EAAA,OAAO,UAACtG,KAAK,EAAEumB,GAAG,EAAEE,IAAI,EAAK;MAC3B,IAAIN,SAAS,KAAK,KAAK,EAAE;QACvB,MAAM,IAAI9f,UAAU,CAClBigB,aAAa,CAACC,GAAG,EAAE,mBAAmB,IAAIF,OAAO,GAAG,MAAM,GAAGA,OAAO,GAAG,EAAE,CAAC,CAAC,EAC3EhgB,UAAU,CAACqgB,cACb,CAAC,CAAA;EACH,KAAA;EAEA,IAAA,IAAIL,OAAO,IAAI,CAACD,kBAAkB,CAACG,GAAG,CAAC,EAAE;EACvCH,MAAAA,kBAAkB,CAACG,GAAG,CAAC,GAAG,IAAI,CAAA;EAC9B;EACAI,MAAAA,OAAO,CAACC,IAAI,CACVN,aAAa,CACXC,GAAG,EACH,8BAA8B,GAAGF,OAAO,GAAG,yCAC7C,CACF,CAAC,CAAA;EACH,KAAA;MAEA,OAAOF,SAAS,GAAGA,SAAS,CAACnmB,KAAK,EAAEumB,GAAG,EAAEE,IAAI,CAAC,GAAG,IAAI,CAAA;KACtD,CAAA;EACH,CAAC,CAAA;AAEDP,cAAU,CAACW,QAAQ,GAAG,SAASA,QAAQA,CAACC,eAAe,EAAE;EACvD,EAAA,OAAO,UAAC9mB,KAAK,EAAEumB,GAAG,EAAK;EACrB;MACAI,OAAO,CAACC,IAAI,CAAA,EAAA,CAAA9gB,MAAA,CAAIygB,GAAG,EAAA,8BAAA,CAAA,CAAAzgB,MAAA,CAA+BghB,eAAe,CAAE,CAAC,CAAA;EACpE,IAAA,OAAO,IAAI,CAAA;KACZ,CAAA;EACH,CAAC,CAAA;;EAED;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA,SAASC,aAAaA,CAACze,OAAO,EAAE0e,MAAM,EAAEC,YAAY,EAAE;EACpD,EAAA,IAAInsB,OAAA,CAAOwN,OAAO,CAAA,KAAK,QAAQ,EAAE;MAC/B,MAAM,IAAIjC,UAAU,CAAC,2BAA2B,EAAEA,UAAU,CAAC6gB,oBAAoB,CAAC,CAAA;EACpF,GAAA;EACA,EAAA,IAAMhpB,IAAI,GAAGlE,MAAM,CAACkE,IAAI,CAACoK,OAAO,CAAC,CAAA;EACjC,EAAA,IAAItK,CAAC,GAAGE,IAAI,CAACN,MAAM,CAAA;EACnB,EAAA,OAAOI,CAAC,EAAE,GAAG,CAAC,EAAE;EACd,IAAA,IAAMuoB,GAAG,GAAGroB,IAAI,CAACF,CAAC,CAAC,CAAA;EACnB,IAAA,IAAMmoB,SAAS,GAAGa,MAAM,CAACT,GAAG,CAAC,CAAA;EAC7B,IAAA,IAAIJ,SAAS,EAAE;EACb,MAAA,IAAMnmB,KAAK,GAAGsI,OAAO,CAACie,GAAG,CAAC,CAAA;EAC1B,MAAA,IAAM/qB,MAAM,GAAGwE,KAAK,KAAKnC,SAAS,IAAIsoB,SAAS,CAACnmB,KAAK,EAAEumB,GAAG,EAAEje,OAAO,CAAC,CAAA;QACpE,IAAI9M,MAAM,KAAK,IAAI,EAAE;EACnB,QAAA,MAAM,IAAI6K,UAAU,CAAC,SAAS,GAAGkgB,GAAG,GAAG,WAAW,GAAG/qB,MAAM,EAAE6K,UAAU,CAAC6gB,oBAAoB,CAAC,CAAA;EAC/F,OAAA;EACA,MAAA,SAAA;EACF,KAAA;MACA,IAAID,YAAY,KAAK,IAAI,EAAE;QACzB,MAAM,IAAI5gB,UAAU,CAAC,iBAAiB,GAAGkgB,GAAG,EAAElgB,UAAU,CAAC8gB,cAAc,CAAC,CAAA;EAC1E,KAAA;EACF,GAAA;EACF,CAAA;AAEA,kBAAe;EACbJ,EAAAA,aAAa,EAAbA,aAAa;EACbb,EAAAA,UAAU,EAAVA,YAAAA;EACF,CAAC;;ECvFD,IAAMA,UAAU,GAAGC,SAAS,CAACD,UAAU,CAAA;;EAEvC;EACA;EACA;EACA;EACA;EACA;EACA;EANA,IAOMkB,KAAK,gBAAA,YAAA;IACT,SAAAA,KAAAA,CAAYC,cAAc,EAAE;EAAA1c,IAAAA,eAAA,OAAAyc,KAAA,CAAA,CAAA;MAC1B,IAAI,CAACxZ,QAAQ,GAAGyZ,cAAc,CAAA;MAC9B,IAAI,CAACC,YAAY,GAAG;EAClB7gB,MAAAA,OAAO,EAAE,IAAIiE,oBAAkB,EAAE;QACjChE,QAAQ,EAAE,IAAIgE,oBAAkB,EAAC;OAClC,CAAA;EACH,GAAA;;EAEA;EACF;EACA;EACA;EACA;EACA;EACA;EACA;EAPEG,EAAAA,YAAA,CAAAuc,KAAA,EAAA,CAAA;MAAA/oB,GAAA,EAAA,SAAA;MAAA2B,KAAA,GAAA,YAAA;EAAA,MAAA,IAAAunB,SAAA,GAAAjG,iBAAA,eAAA9C,mBAAA,EAAA,CAAAC,IAAA,CAQA,SAAAa,OAAAA,CAAckI,WAAW,EAAEhhB,MAAM,EAAA;UAAA,IAAAihB,KAAA,EAAA/iB,KAAA,CAAA;EAAA,QAAA,OAAA8Z,mBAAA,EAAA,CAAA5kB,IAAA,CAAA,SAAA+lB,SAAAZ,QAAA,EAAA;EAAA,UAAA,OAAA,CAAA,EAAA,QAAAA,QAAA,CAAAC,IAAA,GAAAD,QAAA,CAAAzd,IAAA;EAAA,YAAA,KAAA,CAAA;EAAAyd,cAAAA,QAAA,CAAAC,IAAA,GAAA,CAAA,CAAA;EAAAD,cAAAA,QAAA,CAAAzd,IAAA,GAAA,CAAA,CAAA;EAAA,cAAA,OAEhB,IAAI,CAAC+hB,QAAQ,CAACmE,WAAW,EAAEhhB,MAAM,CAAC,CAAA;EAAA,YAAA,KAAA,CAAA;EAAA,cAAA,OAAAuY,QAAA,CAAAG,MAAA,CAAAH,QAAAA,EAAAA,QAAA,CAAAiB,IAAA,CAAA,CAAA;EAAA,YAAA,KAAA,CAAA;EAAAjB,cAAAA,QAAA,CAAAC,IAAA,GAAA,CAAA,CAAA;gBAAAD,QAAA,CAAAgD,EAAA,GAAAhD,QAAA,CAAA,OAAA,CAAA,CAAA,CAAA,CAAA,CAAA;EAE/C,cAAA,IAAIA,QAAA,CAAAgD,EAAA,YAAe3e,KAAK,EAAE;kBACpBqkB,KAAK,GAAG,EAAE,CAAA;EAEdrkB,gBAAAA,KAAK,CAACuD,iBAAiB,GAAGvD,KAAK,CAACuD,iBAAiB,CAAC8gB,KAAK,CAAC,GAAIA,KAAK,GAAG,IAAIrkB,KAAK,EAAG,CAAA;;EAEhF;EACMsB,gBAAAA,KAAK,GAAG+iB,KAAK,CAAC/iB,KAAK,GAAG+iB,KAAK,CAAC/iB,KAAK,CAAClH,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,EAAE,CAAA;kBACjE,IAAI;EACF,kBAAA,IAAI,CAACuhB,QAAA,CAAAgD,EAAA,CAAIrd,KAAK,EAAE;EACdqa,oBAAAA,QAAA,CAAAgD,EAAA,CAAIrd,KAAK,GAAGA,KAAK,CAAA;EACjB;qBACD,MAAM,IAAIA,KAAK,IAAI,CAAC9D,MAAM,CAACme,QAAA,CAAAgD,EAAA,CAAIrd,KAAK,CAAC,CAACjE,QAAQ,CAACiE,KAAK,CAAClH,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,EAAE;EAC/EuhB,oBAAAA,QAAA,CAAAgD,EAAA,CAAIrd,KAAK,IAAI,IAAI,GAAGA,KAAK,CAAA;EAC3B,mBAAA;mBACD,CAAC,OAAOiJ,CAAC,EAAE;EACV;EAAA,iBAAA;EAEJ,eAAA;gBAAC,MAAAoR,QAAA,CAAAgD,EAAA,CAAA;EAAA,YAAA,KAAA,EAAA,CAAA;EAAA,YAAA,KAAA,KAAA;gBAAA,OAAAhD,QAAA,CAAAI,IAAA,EAAA,CAAA;EAAA,WAAA;EAAA,SAAA,EAAAG,OAAA,EAAA,IAAA,EAAA,CAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA;SAIJ,CAAA,CAAA,CAAA;QAAA,SAAA7Y,OAAAA,CAAA4Z,EAAA,EAAAC,GAAA,EAAA;EAAA,QAAA,OAAAiH,SAAA,CAAA1tB,KAAA,CAAA,IAAA,EAAAC,SAAA,CAAA,CAAA;EAAA,OAAA;EAAA,MAAA,OAAA2M,OAAA,CAAA;EAAA,KAAA,EAAA,CAAA;EAAA,GAAA,EAAA;MAAApI,GAAA,EAAA,UAAA;EAAA2B,IAAAA,KAAA,EAED,SAAAqjB,QAAAA,CAASmE,WAAW,EAAEhhB,MAAM,EAAE;EAC5B;EACA;EACA,MAAA,IAAI,OAAOghB,WAAW,KAAK,QAAQ,EAAE;EACnChhB,QAAAA,MAAM,GAAGA,MAAM,IAAI,EAAE,CAAA;UACrBA,MAAM,CAAC6D,GAAG,GAAGmd,WAAW,CAAA;EAC1B,OAAC,MAAM;EACLhhB,QAAAA,MAAM,GAAGghB,WAAW,IAAI,EAAE,CAAA;EAC5B,OAAA;QAEAhhB,MAAM,GAAGkS,WAAW,CAAC,IAAI,CAAC9K,QAAQ,EAAEpH,MAAM,CAAC,CAAA;QAE3C,IAAA2U,OAAA,GAAkD3U,MAAM;UAAjDqH,YAAY,GAAAsN,OAAA,CAAZtN,YAAY;UAAEsL,gBAAgB,GAAAgC,OAAA,CAAhBhC,gBAAgB;UAAElL,OAAO,GAAAkN,OAAA,CAAPlN,OAAO,CAAA;QAE9C,IAAIJ,YAAY,KAAKhQ,SAAS,EAAE;EAC9BsoB,QAAAA,SAAS,CAACY,aAAa,CAAClZ,YAAY,EAAE;EACpCrC,UAAAA,iBAAiB,EAAE0a,UAAU,CAACrY,YAAY,CAACqY,UAAU,WAAQ,CAAC;EAC9Dza,UAAAA,iBAAiB,EAAEya,UAAU,CAACrY,YAAY,CAACqY,UAAU,WAAQ,CAAC;EAC9Dxa,UAAAA,mBAAmB,EAAEwa,UAAU,CAACrY,YAAY,CAACqY,UAAU,CAAQ,SAAA,CAAA,CAAA;WAChE,EAAE,KAAK,CAAC,CAAA;EACX,OAAA;QAEA,IAAI/M,gBAAgB,IAAI,IAAI,EAAE;EAC5B,QAAA,IAAItS,OAAK,CAACxL,UAAU,CAAC8d,gBAAgB,CAAC,EAAE;YACtC3S,MAAM,CAAC2S,gBAAgB,GAAG;EACxB7O,YAAAA,SAAS,EAAE6O,gBAAAA;aACZ,CAAA;EACH,SAAC,MAAM;EACLgN,UAAAA,SAAS,CAACY,aAAa,CAAC5N,gBAAgB,EAAE;cACxCxP,MAAM,EAAEuc,UAAU,CAAS,UAAA,CAAA;EAC3B5b,YAAAA,SAAS,EAAE4b,UAAU,CAAA,UAAA,CAAA;aACtB,EAAE,IAAI,CAAC,CAAA;EACV,SAAA;EACF,OAAA;EAEAC,MAAAA,SAAS,CAACY,aAAa,CAACvgB,MAAM,EAAE;EAC9BkhB,QAAAA,OAAO,EAAExB,UAAU,CAACW,QAAQ,CAAC,SAAS,CAAC;EACvCc,QAAAA,aAAa,EAAEzB,UAAU,CAACW,QAAQ,CAAC,eAAe,CAAA;SACnD,EAAE,IAAI,CAAC,CAAA;;EAER;EACArgB,MAAAA,MAAM,CAAC8I,MAAM,GAAG,CAAC9I,MAAM,CAAC8I,MAAM,IAAI,IAAI,CAAC1B,QAAQ,CAAC0B,MAAM,IAAI,KAAK,EAAE7U,WAAW,EAAE,CAAA;;EAE9E;EACA,MAAA,IAAImtB,cAAc,GAAG3Z,OAAO,IAAIpH,OAAK,CAAC9H,KAAK,CACzCkP,OAAO,CAACoB,MAAM,EACdpB,OAAO,CAACzH,MAAM,CAAC8I,MAAM,CACvB,CAAC,CAAA;QAEDrB,OAAO,IAAIpH,OAAK,CAACpJ,OAAO,CACtB,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,CAAC,EAC3D,UAAC6R,MAAM,EAAK;UACV,OAAOrB,OAAO,CAACqB,MAAM,CAAC,CAAA;EACxB,OACF,CAAC,CAAA;QAED9I,MAAM,CAACyH,OAAO,GAAG+C,cAAY,CAAClL,MAAM,CAAC8hB,cAAc,EAAE3Z,OAAO,CAAC,CAAA;;EAE7D;QACA,IAAM4Z,uBAAuB,GAAG,EAAE,CAAA;QAClC,IAAIC,8BAA8B,GAAG,IAAI,CAAA;QACzC,IAAI,CAACR,YAAY,CAAC7gB,OAAO,CAAChJ,OAAO,CAAC,SAASsqB,0BAA0BA,CAACC,WAAW,EAAE;EACjF,QAAA,IAAI,OAAOA,WAAW,CAAC9c,OAAO,KAAK,UAAU,IAAI8c,WAAW,CAAC9c,OAAO,CAAC1E,MAAM,CAAC,KAAK,KAAK,EAAE;EACtF,UAAA,OAAA;EACF,SAAA;EAEAshB,QAAAA,8BAA8B,GAAGA,8BAA8B,IAAIE,WAAW,CAAC/c,WAAW,CAAA;UAE1F4c,uBAAuB,CAACI,OAAO,CAACD,WAAW,CAACjd,SAAS,EAAEid,WAAW,CAAChd,QAAQ,CAAC,CAAA;EAC9E,OAAC,CAAC,CAAA;QAEF,IAAMkd,wBAAwB,GAAG,EAAE,CAAA;QACnC,IAAI,CAACZ,YAAY,CAAC5gB,QAAQ,CAACjJ,OAAO,CAAC,SAAS0qB,wBAAwBA,CAACH,WAAW,EAAE;UAChFE,wBAAwB,CAACrmB,IAAI,CAACmmB,WAAW,CAACjd,SAAS,EAAEid,WAAW,CAAChd,QAAQ,CAAC,CAAA;EAC5E,OAAC,CAAC,CAAA;EAEF,MAAA,IAAIod,OAAO,CAAA;QACX,IAAIpqB,CAAC,GAAG,CAAC,CAAA;EACT,MAAA,IAAII,GAAG,CAAA;QAEP,IAAI,CAAC0pB,8BAA8B,EAAE;UACnC,IAAMO,KAAK,GAAG,CAACvC,eAAe,CAACrsB,IAAI,CAAC,IAAI,CAAC,EAAEoE,SAAS,CAAC,CAAA;UACrDwqB,KAAK,CAACJ,OAAO,CAACpuB,KAAK,CAACwuB,KAAK,EAAER,uBAAuB,CAAC,CAAA;UACnDQ,KAAK,CAACxmB,IAAI,CAAChI,KAAK,CAACwuB,KAAK,EAAEH,wBAAwB,CAAC,CAAA;UACjD9pB,GAAG,GAAGiqB,KAAK,CAACzqB,MAAM,CAAA;EAElBwqB,QAAAA,OAAO,GAAGnN,OAAO,CAAC9G,OAAO,CAAC3N,MAAM,CAAC,CAAA;UAEjC,OAAOxI,CAAC,GAAGI,GAAG,EAAE;EACdgqB,UAAAA,OAAO,GAAGA,OAAO,CAACnjB,IAAI,CAACojB,KAAK,CAACrqB,CAAC,EAAE,CAAC,EAAEqqB,KAAK,CAACrqB,CAAC,EAAE,CAAC,CAAC,CAAA;EAChD,SAAA;EAEA,QAAA,OAAOoqB,OAAO,CAAA;EAChB,OAAA;QAEAhqB,GAAG,GAAGypB,uBAAuB,CAACjqB,MAAM,CAAA;QAEpC,IAAIuc,SAAS,GAAG3T,MAAM,CAAA;EAEtBxI,MAAAA,CAAC,GAAG,CAAC,CAAA;QAEL,OAAOA,CAAC,GAAGI,GAAG,EAAE;EACd,QAAA,IAAMkqB,WAAW,GAAGT,uBAAuB,CAAC7pB,CAAC,EAAE,CAAC,CAAA;EAChD,QAAA,IAAMuqB,UAAU,GAAGV,uBAAuB,CAAC7pB,CAAC,EAAE,CAAC,CAAA;UAC/C,IAAI;EACFmc,UAAAA,SAAS,GAAGmO,WAAW,CAACnO,SAAS,CAAC,CAAA;WACnC,CAAC,OAAO9S,KAAK,EAAE;EACdkhB,UAAAA,UAAU,CAAChuB,IAAI,CAAC,IAAI,EAAE8M,KAAK,CAAC,CAAA;EAC5B,UAAA,MAAA;EACF,SAAA;EACF,OAAA;QAEA,IAAI;UACF+gB,OAAO,GAAGtC,eAAe,CAACvrB,IAAI,CAAC,IAAI,EAAE4f,SAAS,CAAC,CAAA;SAChD,CAAC,OAAO9S,KAAK,EAAE;EACd,QAAA,OAAO4T,OAAO,CAAC7G,MAAM,CAAC/M,KAAK,CAAC,CAAA;EAC9B,OAAA;EAEArJ,MAAAA,CAAC,GAAG,CAAC,CAAA;QACLI,GAAG,GAAG8pB,wBAAwB,CAACtqB,MAAM,CAAA;QAErC,OAAOI,CAAC,GAAGI,GAAG,EAAE;EACdgqB,QAAAA,OAAO,GAAGA,OAAO,CAACnjB,IAAI,CAACijB,wBAAwB,CAAClqB,CAAC,EAAE,CAAC,EAAEkqB,wBAAwB,CAAClqB,CAAC,EAAE,CAAC,CAAC,CAAA;EACtF,OAAA;EAEA,MAAA,OAAOoqB,OAAO,CAAA;EAChB,KAAA;EAAC,GAAA,EAAA;MAAA/pB,GAAA,EAAA,QAAA;EAAA2B,IAAAA,KAAA,EAED,SAAAwoB,MAAOhiB,CAAAA,MAAM,EAAE;QACbA,MAAM,GAAGkS,WAAW,CAAC,IAAI,CAAC9K,QAAQ,EAAEpH,MAAM,CAAC,CAAA;QAC3C,IAAMiiB,QAAQ,GAAGlQ,aAAa,CAAC/R,MAAM,CAAC6R,OAAO,EAAE7R,MAAM,CAAC6D,GAAG,CAAC,CAAA;QAC1D,OAAOD,QAAQ,CAACqe,QAAQ,EAAEjiB,MAAM,CAACwD,MAAM,EAAExD,MAAM,CAAC2S,gBAAgB,CAAC,CAAA;EACnE,KAAA;EAAC,GAAA,CAAA,CAAA,CAAA;EAAA,EAAA,OAAAiO,KAAA,CAAA;EAAA,CAGH,EAAA,CAAA;AACAvgB,SAAK,CAACpJ,OAAO,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,SAASirB,mBAAmBA,CAACpZ,MAAM,EAAE;EACvF;IACA8X,KAAK,CAACntB,SAAS,CAACqV,MAAM,CAAC,GAAG,UAASjF,GAAG,EAAE7D,MAAM,EAAE;MAC9C,OAAO,IAAI,CAACC,OAAO,CAACiS,WAAW,CAAClS,MAAM,IAAI,EAAE,EAAE;EAC5C8I,MAAAA,MAAM,EAANA,MAAM;EACNjF,MAAAA,GAAG,EAAHA,GAAG;EACH3E,MAAAA,IAAI,EAAE,CAACc,MAAM,IAAI,EAAE,EAAEd,IAAAA;EACvB,KAAC,CAAC,CAAC,CAAA;KACJ,CAAA;EACH,CAAC,CAAC,CAAA;AAEFmB,SAAK,CAACpJ,OAAO,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,SAASkrB,qBAAqBA,CAACrZ,MAAM,EAAE;EAC7E;;IAEA,SAASsZ,kBAAkBA,CAACC,MAAM,EAAE;MAClC,OAAO,SAASC,UAAUA,CAACze,GAAG,EAAE3E,IAAI,EAAEc,MAAM,EAAE;QAC5C,OAAO,IAAI,CAACC,OAAO,CAACiS,WAAW,CAAClS,MAAM,IAAI,EAAE,EAAE;EAC5C8I,QAAAA,MAAM,EAANA,MAAM;UACNrB,OAAO,EAAE4a,MAAM,GAAG;EAChB,UAAA,cAAc,EAAE,qBAAA;WACjB,GAAG,EAAE;EACNxe,QAAAA,GAAG,EAAHA,GAAG;EACH3E,QAAAA,IAAI,EAAJA,IAAAA;EACF,OAAC,CAAC,CAAC,CAAA;OACJ,CAAA;EACH,GAAA;IAEA0hB,KAAK,CAACntB,SAAS,CAACqV,MAAM,CAAC,GAAGsZ,kBAAkB,EAAE,CAAA;IAE9CxB,KAAK,CAACntB,SAAS,CAACqV,MAAM,GAAG,MAAM,CAAC,GAAGsZ,kBAAkB,CAAC,IAAI,CAAC,CAAA;EAC7D,CAAC,CAAC,CAAA;AAEF,gBAAexB,KAAK;;ECpOpB;EACA;EACA;EACA;EACA;EACA;EACA;EANA,IAOM2B,WAAW,gBAAA,YAAA;IACf,SAAAA,WAAAA,CAAYC,QAAQ,EAAE;EAAAre,IAAAA,eAAA,OAAAoe,WAAA,CAAA,CAAA;EACpB,IAAA,IAAI,OAAOC,QAAQ,KAAK,UAAU,EAAE;EAClC,MAAA,MAAM,IAAIzgB,SAAS,CAAC,8BAA8B,CAAC,CAAA;EACrD,KAAA;EAEA,IAAA,IAAI0gB,cAAc,CAAA;MAElB,IAAI,CAACb,OAAO,GAAG,IAAInN,OAAO,CAAC,SAASiO,eAAeA,CAAC/U,OAAO,EAAE;EAC3D8U,MAAAA,cAAc,GAAG9U,OAAO,CAAA;EAC1B,KAAC,CAAC,CAAA;MAEF,IAAM7O,KAAK,GAAG,IAAI,CAAA;;EAElB;EACA,IAAA,IAAI,CAAC8iB,OAAO,CAACnjB,IAAI,CAAC,UAAA2Y,MAAM,EAAI;EAC1B,MAAA,IAAI,CAACtY,KAAK,CAAC6jB,UAAU,EAAE,OAAA;EAEvB,MAAA,IAAInrB,CAAC,GAAGsH,KAAK,CAAC6jB,UAAU,CAACvrB,MAAM,CAAA;EAE/B,MAAA,OAAOI,CAAC,EAAE,GAAG,CAAC,EAAE;EACdsH,QAAAA,KAAK,CAAC6jB,UAAU,CAACnrB,CAAC,CAAC,CAAC4f,MAAM,CAAC,CAAA;EAC7B,OAAA;QACAtY,KAAK,CAAC6jB,UAAU,GAAG,IAAI,CAAA;EACzB,KAAC,CAAC,CAAA;;EAEF;EACA,IAAA,IAAI,CAACf,OAAO,CAACnjB,IAAI,GAAG,UAAAmkB,WAAW,EAAI;EACjC,MAAA,IAAI9M,QAAQ,CAAA;EACZ;EACA,MAAA,IAAM8L,OAAO,GAAG,IAAInN,OAAO,CAAC,UAAA9G,OAAO,EAAI;EACrC7O,QAAAA,KAAK,CAACwY,SAAS,CAAC3J,OAAO,CAAC,CAAA;EACxBmI,QAAAA,QAAQ,GAAGnI,OAAO,CAAA;EACpB,OAAC,CAAC,CAAClP,IAAI,CAACmkB,WAAW,CAAC,CAAA;EAEpBhB,MAAAA,OAAO,CAACxK,MAAM,GAAG,SAASxJ,MAAMA,GAAG;EACjC9O,QAAAA,KAAK,CAACsW,WAAW,CAACU,QAAQ,CAAC,CAAA;SAC5B,CAAA;EAED,MAAA,OAAO8L,OAAO,CAAA;OACf,CAAA;MAEDY,QAAQ,CAAC,SAASpL,MAAMA,CAACtX,OAAO,EAAEE,MAAM,EAAEC,OAAO,EAAE;QACjD,IAAInB,KAAK,CAACgZ,MAAM,EAAE;EAChB;EACA,QAAA,OAAA;EACF,OAAA;QAEAhZ,KAAK,CAACgZ,MAAM,GAAG,IAAItK,aAAa,CAAC1N,OAAO,EAAEE,MAAM,EAAEC,OAAO,CAAC,CAAA;EAC1DwiB,MAAAA,cAAc,CAAC3jB,KAAK,CAACgZ,MAAM,CAAC,CAAA;EAC9B,KAAC,CAAC,CAAA;EACJ,GAAA;;EAEA;EACF;EACA;EAFEzT,EAAAA,YAAA,CAAAke,WAAA,EAAA,CAAA;MAAA1qB,GAAA,EAAA,kBAAA;MAAA2B,KAAA,EAGA,SAAA6lB,gBAAAA,GAAmB;QACjB,IAAI,IAAI,CAACvH,MAAM,EAAE;UACf,MAAM,IAAI,CAACA,MAAM,CAAA;EACnB,OAAA;EACF,KAAA;;EAEA;EACF;EACA;EAFE,GAAA,EAAA;MAAAjgB,GAAA,EAAA,WAAA;EAAA2B,IAAAA,KAAA,EAIA,SAAA8d,SAAU3H,CAAAA,QAAQ,EAAE;QAClB,IAAI,IAAI,CAACmI,MAAM,EAAE;EACfnI,QAAAA,QAAQ,CAAC,IAAI,CAACmI,MAAM,CAAC,CAAA;EACrB,QAAA,OAAA;EACF,OAAA;QAEA,IAAI,IAAI,CAAC6K,UAAU,EAAE;EACnB,QAAA,IAAI,CAACA,UAAU,CAACtnB,IAAI,CAACsU,QAAQ,CAAC,CAAA;EAChC,OAAC,MAAM;EACL,QAAA,IAAI,CAACgT,UAAU,GAAG,CAAChT,QAAQ,CAAC,CAAA;EAC9B,OAAA;EACF,KAAA;;EAEA;EACF;EACA;EAFE,GAAA,EAAA;MAAA9X,GAAA,EAAA,aAAA;EAAA2B,IAAAA,KAAA,EAIA,SAAA4b,WAAYzF,CAAAA,QAAQ,EAAE;EACpB,MAAA,IAAI,CAAC,IAAI,CAACgT,UAAU,EAAE;EACpB,QAAA,OAAA;EACF,OAAA;QACA,IAAM5f,KAAK,GAAG,IAAI,CAAC4f,UAAU,CAACroB,OAAO,CAACqV,QAAQ,CAAC,CAAA;EAC/C,MAAA,IAAI5M,KAAK,KAAK,CAAC,CAAC,EAAE;UAChB,IAAI,CAAC4f,UAAU,CAACE,MAAM,CAAC9f,KAAK,EAAE,CAAC,CAAC,CAAA;EAClC,OAAA;EACF,KAAA;EAAC,GAAA,EAAA;MAAAlL,GAAA,EAAA,eAAA;MAAA2B,KAAA,EAED,SAAAykB,aAAAA,GAAgB;EAAA,MAAA,IAAA6E,KAAA,GAAA,IAAA,CAAA;EACd,MAAA,IAAMlL,UAAU,GAAG,IAAIC,eAAe,EAAE,CAAA;EAExC,MAAA,IAAMR,KAAK,GAAG,SAARA,KAAKA,CAAI3L,GAAG,EAAK;EACrBkM,QAAAA,UAAU,CAACP,KAAK,CAAC3L,GAAG,CAAC,CAAA;SACtB,CAAA;EAED,MAAA,IAAI,CAAC4L,SAAS,CAACD,KAAK,CAAC,CAAA;EAErBO,MAAAA,UAAU,CAACvC,MAAM,CAACD,WAAW,GAAG,YAAA;EAAA,QAAA,OAAM0N,KAAI,CAAC1N,WAAW,CAACiC,KAAK,CAAC,CAAA;EAAA,OAAA,CAAA;QAE7D,OAAOO,UAAU,CAACvC,MAAM,CAAA;EAC1B,KAAA;;EAEA;EACF;EACA;EACA;EAHE,GAAA,CAAA,EAAA,CAAA;MAAAxd,GAAA,EAAA,QAAA;MAAA2B,KAAA,EAIA,SAAA4E,MAAAA,GAAgB;EACd,MAAA,IAAIgZ,MAAM,CAAA;QACV,IAAMtY,KAAK,GAAG,IAAIyjB,WAAW,CAAC,SAASC,QAAQA,CAACO,CAAC,EAAE;EACjD3L,QAAAA,MAAM,GAAG2L,CAAC,CAAA;EACZ,OAAC,CAAC,CAAA;QACF,OAAO;EACLjkB,QAAAA,KAAK,EAALA,KAAK;EACLsY,QAAAA,MAAM,EAANA,MAAAA;SACD,CAAA;EACH,KAAA;EAAC,GAAA,CAAA,CAAA,CAAA;EAAA,EAAA,OAAAmL,WAAA,CAAA;EAAA,CAAA,EAAA,CAAA;AAGH,sBAAeA,WAAW;;ECpI1B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACe,SAASS,MAAMA,CAACC,QAAQ,EAAE;EACvC,EAAA,OAAO,SAAS7vB,IAAIA,CAACoH,GAAG,EAAE;EACxB,IAAA,OAAOyoB,QAAQ,CAAC5vB,KAAK,CAAC,IAAI,EAAEmH,GAAG,CAAC,CAAA;KACjC,CAAA;EACH;;ECvBA;EACA;EACA;EACA;EACA;EACA;EACA;EACe,SAAS0oB,YAAYA,CAACC,OAAO,EAAE;IAC5C,OAAO9iB,OAAK,CAAC/K,QAAQ,CAAC6tB,OAAO,CAAC,IAAKA,OAAO,CAACD,YAAY,KAAK,IAAK,CAAA;EACnE;;ECbA,IAAME,cAAc,GAAG;EACrBC,EAAAA,QAAQ,EAAE,GAAG;EACbC,EAAAA,kBAAkB,EAAE,GAAG;EACvBC,EAAAA,UAAU,EAAE,GAAG;EACfC,EAAAA,UAAU,EAAE,GAAG;EACfC,EAAAA,EAAE,EAAE,GAAG;EACPC,EAAAA,OAAO,EAAE,GAAG;EACZC,EAAAA,QAAQ,EAAE,GAAG;EACbC,EAAAA,2BAA2B,EAAE,GAAG;EAChCC,EAAAA,SAAS,EAAE,GAAG;EACdC,EAAAA,YAAY,EAAE,GAAG;EACjBC,EAAAA,cAAc,EAAE,GAAG;EACnBC,EAAAA,WAAW,EAAE,GAAG;EAChBC,EAAAA,eAAe,EAAE,GAAG;EACpBC,EAAAA,MAAM,EAAE,GAAG;EACXC,EAAAA,eAAe,EAAE,GAAG;EACpBC,EAAAA,gBAAgB,EAAE,GAAG;EACrBC,EAAAA,KAAK,EAAE,GAAG;EACVC,EAAAA,QAAQ,EAAE,GAAG;EACbC,EAAAA,WAAW,EAAE,GAAG;EAChBC,EAAAA,QAAQ,EAAE,GAAG;EACbC,EAAAA,MAAM,EAAE,GAAG;EACXC,EAAAA,iBAAiB,EAAE,GAAG;EACtBC,EAAAA,iBAAiB,EAAE,GAAG;EACtBC,EAAAA,UAAU,EAAE,GAAG;EACfC,EAAAA,YAAY,EAAE,GAAG;EACjBC,EAAAA,eAAe,EAAE,GAAG;EACpBC,EAAAA,SAAS,EAAE,GAAG;EACdC,EAAAA,QAAQ,EAAE,GAAG;EACbC,EAAAA,gBAAgB,EAAE,GAAG;EACrBC,EAAAA,aAAa,EAAE,GAAG;EAClBC,EAAAA,2BAA2B,EAAE,GAAG;EAChCC,EAAAA,cAAc,EAAE,GAAG;EACnBC,EAAAA,QAAQ,EAAE,GAAG;EACbC,EAAAA,IAAI,EAAE,GAAG;EACTC,EAAAA,cAAc,EAAE,GAAG;EACnBC,EAAAA,kBAAkB,EAAE,GAAG;EACvBC,EAAAA,eAAe,EAAE,GAAG;EACpBC,EAAAA,UAAU,EAAE,GAAG;EACfC,EAAAA,oBAAoB,EAAE,GAAG;EACzBC,EAAAA,mBAAmB,EAAE,GAAG;EACxBC,EAAAA,iBAAiB,EAAE,GAAG;EACtBC,EAAAA,SAAS,EAAE,GAAG;EACdC,EAAAA,kBAAkB,EAAE,GAAG;EACvBC,EAAAA,mBAAmB,EAAE,GAAG;EACxBC,EAAAA,MAAM,EAAE,GAAG;EACXC,EAAAA,gBAAgB,EAAE,GAAG;EACrBC,EAAAA,QAAQ,EAAE,GAAG;EACbC,EAAAA,eAAe,EAAE,GAAG;EACpBC,EAAAA,oBAAoB,EAAE,GAAG;EACzBC,EAAAA,eAAe,EAAE,GAAG;EACpBC,EAAAA,2BAA2B,EAAE,GAAG;EAChCC,EAAAA,0BAA0B,EAAE,GAAG;EAC/BC,EAAAA,mBAAmB,EAAE,GAAG;EACxBC,EAAAA,cAAc,EAAE,GAAG;EACnBC,EAAAA,UAAU,EAAE,GAAG;EACfC,EAAAA,kBAAkB,EAAE,GAAG;EACvBC,EAAAA,cAAc,EAAE,GAAG;EACnBC,EAAAA,uBAAuB,EAAE,GAAG;EAC5BC,EAAAA,qBAAqB,EAAE,GAAG;EAC1BC,EAAAA,mBAAmB,EAAE,GAAG;EACxBC,EAAAA,YAAY,EAAE,GAAG;EACjBC,EAAAA,WAAW,EAAE,GAAG;EAChBC,EAAAA,6BAA6B,EAAE,GAAA;EACjC,CAAC,CAAA;EAED3zB,MAAM,CAACsT,OAAO,CAACsc,cAAc,CAAC,CAACnsB,OAAO,CAAC,UAAAE,IAAA,EAAkB;EAAA,EAAA,IAAAqB,KAAA,GAAA9B,cAAA,CAAAS,IAAA,EAAA,CAAA,CAAA;EAAhBU,IAAAA,GAAG,GAAAW,KAAA,CAAA,CAAA,CAAA;EAAEgB,IAAAA,KAAK,GAAAhB,KAAA,CAAA,CAAA,CAAA,CAAA;EACjD4qB,EAAAA,cAAc,CAAC5pB,KAAK,CAAC,GAAG3B,GAAG,CAAA;EAC7B,CAAC,CAAC,CAAA;AAEF,yBAAeurB,cAAc;;EClD7B;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASgE,cAAcA,CAACC,aAAa,EAAE;EACrC,EAAA,IAAM/uB,OAAO,GAAG,IAAIsoB,OAAK,CAACyG,aAAa,CAAC,CAAA;IACxC,IAAMC,QAAQ,GAAGr0B,IAAI,CAAC2tB,OAAK,CAACntB,SAAS,CAACwM,OAAO,EAAE3H,OAAO,CAAC,CAAA;;EAEvD;IACA+H,OAAK,CAACzH,MAAM,CAAC0uB,QAAQ,EAAE1G,OAAK,CAACntB,SAAS,EAAE6E,OAAO,EAAE;EAACf,IAAAA,UAAU,EAAE,IAAA;EAAI,GAAC,CAAC,CAAA;;EAEpE;IACA8I,OAAK,CAACzH,MAAM,CAAC0uB,QAAQ,EAAEhvB,OAAO,EAAE,IAAI,EAAE;EAACf,IAAAA,UAAU,EAAE,IAAA;EAAI,GAAC,CAAC,CAAA;;EAEzD;EACA+vB,EAAAA,QAAQ,CAACpzB,MAAM,GAAG,SAASA,MAAMA,CAAC2sB,cAAc,EAAE;MAChD,OAAOuG,cAAc,CAAClV,WAAW,CAACmV,aAAa,EAAExG,cAAc,CAAC,CAAC,CAAA;KAClE,CAAA;EAED,EAAA,OAAOyG,QAAQ,CAAA;EACjB,CAAA;;EAEA;AACA,MAAMC,KAAK,GAAGH,cAAc,CAAChgB,UAAQ,EAAC;;EAEtC;EACAmgB,KAAK,CAAC3G,KAAK,GAAGA,OAAK,CAAA;;EAEnB;EACA2G,KAAK,CAAC/Z,aAAa,GAAGA,aAAa,CAAA;EACnC+Z,KAAK,CAAChF,WAAW,GAAGA,aAAW,CAAA;EAC/BgF,KAAK,CAACja,QAAQ,GAAGA,QAAQ,CAAA;EACzBia,KAAK,CAAC9H,OAAO,GAAGA,OAAO,CAAA;EACvB8H,KAAK,CAAC3lB,UAAU,GAAGA,UAAU,CAAA;;EAE7B;EACA2lB,KAAK,CAAC1nB,UAAU,GAAGA,UAAU,CAAA;;EAE7B;EACA0nB,KAAK,CAACC,MAAM,GAAGD,KAAK,CAAC/Z,aAAa,CAAA;;EAElC;EACA+Z,KAAK,CAACE,GAAG,GAAG,SAASA,GAAGA,CAACC,QAAQ,EAAE;EACjC,EAAA,OAAOjT,OAAO,CAACgT,GAAG,CAACC,QAAQ,CAAC,CAAA;EAC9B,CAAC,CAAA;EAEDH,KAAK,CAACvE,MAAM,GAAGA,MAAM,CAAA;;EAErB;EACAuE,KAAK,CAACrE,YAAY,GAAGA,YAAY,CAAA;;EAEjC;EACAqE,KAAK,CAACrV,WAAW,GAAGA,WAAW,CAAA;EAE/BqV,KAAK,CAAC/c,YAAY,GAAGA,cAAY,CAAA;EAEjC+c,KAAK,CAACI,UAAU,GAAG,UAAA9zB,KAAK,EAAA;EAAA,EAAA,OAAI6S,cAAc,CAACrG,OAAK,CAAC/E,UAAU,CAACzH,KAAK,CAAC,GAAG,IAAIuC,QAAQ,CAACvC,KAAK,CAAC,GAAGA,KAAK,CAAC,CAAA;EAAA,CAAA,CAAA;EAEjG0zB,KAAK,CAAC1I,UAAU,GAAGC,QAAQ,CAACD,UAAU,CAAA;EAEtC0I,KAAK,CAACnE,cAAc,GAAGA,gBAAc,CAAA;EAErCmE,KAAK,CAAA,SAAA,CAAQ,GAAGA,KAAK;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/axios/dist/axios.min.js b/node_modules/axios/dist/axios.min.js new file mode 100644 index 000000000..0ac6c5022 --- /dev/null +++ b/node_modules/axios/dist/axios.min.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).axios=t()}(this,(function(){"use strict";function e(e){var r,n;function o(r,n){try{var a=e[r](n),u=a.value,s=u instanceof t;Promise.resolve(s?u.v:u).then((function(t){if(s){var n="return"===r?"return":"next";if(!u.k||t.done)return o(n,t);t=e[n](t).value}i(a.done?"return":"normal",t)}),(function(e){o("throw",e)}))}catch(e){i("throw",e)}}function i(e,t){switch(e){case"return":r.resolve({value:t,done:!0});break;case"throw":r.reject(t);break;default:r.resolve({value:t,done:!1})}(r=r.next)?o(r.key,r.arg):n=null}this._invoke=function(e,t){return new Promise((function(i,a){var u={key:e,arg:t,resolve:i,reject:a,next:null};n?n=n.next=u:(r=n=u,o(e,t))}))},"function"!=typeof e.return&&(this.return=void 0)}function t(e,t){this.v=e,this.k=t}function r(e){var r={},n=!1;function o(r,o){return n=!0,o=new Promise((function(t){t(e[r](o))})),{done:!1,value:new t(o,1)}}return r["undefined"!=typeof Symbol&&Symbol.iterator||"@@iterator"]=function(){return this},r.next=function(e){return n?(n=!1,e):o("next",e)},"function"==typeof e.throw&&(r.throw=function(e){if(n)throw n=!1,e;return o("throw",e)}),"function"==typeof e.return&&(r.return=function(e){return n?(n=!1,e):o("return",e)}),r}function n(e){var t,r,n,i=2;for("undefined"!=typeof Symbol&&(r=Symbol.asyncIterator,n=Symbol.iterator);i--;){if(r&&null!=(t=e[r]))return t.call(e);if(n&&null!=(t=e[n]))return new o(t.call(e));r="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function o(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then((function(e){return{value:e,done:t}}))}return o=function(e){this.s=e,this.n=e.next},o.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var r=this.s.return;return void 0===r?Promise.resolve({value:e,done:!0}):t(r.apply(this.s,arguments))},throw:function(e){var r=this.s.return;return void 0===r?Promise.reject(e):t(r.apply(this.s,arguments))}},new o(e)}function i(e){return new t(e,0)}function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function u(e){for(var t=1;t=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),c=n.call(a,"finallyLoc");if(s&&c){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),A(r),y}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;A(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:L(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),y}},t}function c(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}function f(e){return f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},f(e)}function l(t){return function(){return new e(t.apply(this,arguments))}}function p(e,t,r,n,o,i,a){try{var u=e[i](a),s=u.value}catch(e){return void r(e)}u.done?t(s):Promise.resolve(s).then(n,o)}function h(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var i=e.apply(t,r);function a(e){p(i,n,o,a,u,"next",e)}function u(e){p(i,n,o,a,u,"throw",e)}a(void 0)}))}}function d(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function v(e,t){for(var r=0;re.length)&&(t=e.length);for(var r=0,n=new Array(t);r2&&void 0!==arguments[2]?arguments[2]:{},i=o.allOwnKeys,a=void 0!==i&&i;if(null!=e)if("object"!==f(e)&&(e=[e]),N(e))for(r=0,n=e.length;r0;)if(t===(r=n[o]).toLowerCase())return r;return null}var Q="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Z=function(e){return!_(e)&&e!==Q};var ee,te=(ee="undefined"!=typeof Uint8Array&&j(Uint8Array),function(e){return ee&&e instanceof ee}),re=P("HTMLFormElement"),ne=function(e){var t=Object.prototype.hasOwnProperty;return function(e,r){return t.call(e,r)}}(),oe=P("RegExp"),ie=function(e,t){var r=Object.getOwnPropertyDescriptors(e),n={};$(r,(function(r,o){var i;!1!==(i=t(r,o,e))&&(n[o]=i||r)})),Object.defineProperties(e,n)},ae="abcdefghijklmnopqrstuvwxyz",ue="0123456789",se={DIGIT:ue,ALPHA:ae,ALPHA_DIGIT:ae+ae.toUpperCase()+ue};var ce,fe,le,pe,he=P("AsyncFunction"),de=(ce="function"==typeof setImmediate,fe=U(Q.postMessage),ce?setImmediate:fe?(le="axios@".concat(Math.random()),pe=[],Q.addEventListener("message",(function(e){var t=e.source,r=e.data;t===Q&&r===le&&pe.length&&pe.shift()()}),!1),function(e){pe.push(e),Q.postMessage(le,"*")}):function(e){return setTimeout(e)}),ve="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Q):"undefined"!=typeof process&&process.nextTick||de,ye={isArray:N,isArrayBuffer:C,isBuffer:function(e){return null!==e&&!_(e)&&null!==e.constructor&&!_(e.constructor)&&U(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:function(e){var t;return e&&("function"==typeof FormData&&e instanceof FormData||U(e.append)&&("formdata"===(t=A(e))||"object"===t&&U(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&C(e.buffer)},isString:F,isNumber:B,isBoolean:function(e){return!0===e||!1===e},isObject:D,isPlainObject:I,isReadableStream:G,isRequest:K,isResponse:V,isHeaders:X,isUndefined:_,isDate:q,isFile:M,isBlob:z,isRegExp:oe,isFunction:U,isStream:function(e){return D(e)&&U(e.pipe)},isURLSearchParams:J,isTypedArray:te,isFileList:H,forEach:$,merge:function e(){for(var t=Z(this)&&this||{},r=t.caseless,n={},o=function(t,o){var i=r&&Y(n,o)||o;I(n[i])&&I(t)?n[i]=e(n[i],t):I(t)?n[i]=e({},t):N(t)?n[i]=t.slice():n[i]=t},i=0,a=arguments.length;i3&&void 0!==arguments[3]?arguments[3]:{},o=n.allOwnKeys;return $(t,(function(t,n){r&&U(t)?e[n]=R(t,r):e[n]=t}),{allOwnKeys:o}),e},trim:function(e){return e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e},inherits:function(e,t,r,n){e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:function(e,t,r,n){var o,i,a,u={};if(t=t||{},null==e)return t;do{for(i=(o=Object.getOwnPropertyNames(e)).length;i-- >0;)a=o[i],n&&!n(a,e,t)||u[a]||(t[a]=e[a],u[a]=!0);e=!1!==r&&j(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:A,kindOfTest:P,endsWith:function(e,t,r){e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;var n=e.indexOf(t,r);return-1!==n&&n===r},toArray:function(e){if(!e)return null;if(N(e))return e;var t=e.length;if(!B(t))return null;for(var r=new Array(t);t-- >0;)r[t]=e[t];return r},forEachEntry:function(e,t){for(var r,n=(e&&e[Symbol.iterator]).call(e);(r=n.next())&&!r.done;){var o=r.value;t.call(e,o[0],o[1])}},matchAll:function(e,t){for(var r,n=[];null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:re,hasOwnProperty:ne,hasOwnProp:ne,reduceDescriptors:ie,freezeMethods:function(e){ie(e,(function(t,r){if(U(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;var n=e[r];U(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=function(){throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:function(e,t){var r={},n=function(e){e.forEach((function(e){r[e]=!0}))};return N(e)?n(e):n(String(e).split(t)),r},toCamelCase:function(e){return e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r}))},noop:function(){},toFiniteNumber:function(e,t){return null!=e&&Number.isFinite(e=+e)?e:t},findKey:Y,global:Q,isContextDefined:Z,ALPHABET:se,generateString:function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:se.ALPHA_DIGIT,r="",n=t.length;e--;)r+=t[Math.random()*n|0];return r},isSpecCompliantForm:function(e){return!!(e&&U(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:function(e){var t=new Array(10);return function e(r,n){if(D(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[n]=r;var o=N(r)?[]:{};return $(r,(function(t,r){var i=e(t,n+1);!_(i)&&(o[r]=i)})),t[n]=void 0,o}}return r}(e,0)},isAsyncFn:he,isThenable:function(e){return e&&(D(e)||U(e))&&U(e.then)&&U(e.catch)},setImmediate:de,asap:ve};function me(e,t,r,n,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),o&&(this.response=o,this.status=o.status?o.status:null)}ye.inherits(me,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ye.toJSONObject(this.config),code:this.code,status:this.status}}});var be=me.prototype,ge={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((function(e){ge[e]={value:e}})),Object.defineProperties(me,ge),Object.defineProperty(be,"isAxiosError",{value:!0}),me.from=function(e,t,r,n,o,i){var a=Object.create(be);return ye.toFlatObject(e,a,(function(e){return e!==Error.prototype}),(function(e){return"isAxiosError"!==e})),me.call(a,e.message,t,r,n,o),a.cause=e,a.name=e.name,i&&Object.assign(a,i),a};function we(e){return ye.isPlainObject(e)||ye.isArray(e)}function Ee(e){return ye.endsWith(e,"[]")?e.slice(0,-2):e}function Oe(e,t,r){return e?e.concat(t).map((function(e,t){return e=Ee(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}var Se=ye.toFlatObject(ye,{},null,(function(e){return/^is[A-Z]/.test(e)}));function xe(e,t,r){if(!ye.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;var n=(r=ye.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!ye.isUndefined(t[e])}))).metaTokens,o=r.visitor||c,i=r.dots,a=r.indexes,u=(r.Blob||"undefined"!=typeof Blob&&Blob)&&ye.isSpecCompliantForm(t);if(!ye.isFunction(o))throw new TypeError("visitor must be a function");function s(e){if(null===e)return"";if(ye.isDate(e))return e.toISOString();if(!u&&ye.isBlob(e))throw new me("Blob is not supported. Use a Buffer instead.");return ye.isArrayBuffer(e)||ye.isTypedArray(e)?u&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function c(e,r,o){var u=e;if(e&&!o&&"object"===f(e))if(ye.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(ye.isArray(e)&&function(e){return ye.isArray(e)&&!e.some(we)}(e)||(ye.isFileList(e)||ye.endsWith(r,"[]"))&&(u=ye.toArray(e)))return r=Ee(r),u.forEach((function(e,n){!ye.isUndefined(e)&&null!==e&&t.append(!0===a?Oe([r],n,i):null===a?r:r+"[]",s(e))})),!1;return!!we(e)||(t.append(Oe(o,r,i),s(e)),!1)}var l=[],p=Object.assign(Se,{defaultVisitor:c,convertValue:s,isVisitable:we});if(!ye.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!ye.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+n.join("."));l.push(r),ye.forEach(r,(function(r,i){!0===(!(ye.isUndefined(r)||null===r)&&o.call(t,r,ye.isString(i)?i.trim():i,n,p))&&e(r,n?n.concat(i):[i])})),l.pop()}}(e),t}function Re(e){var t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function Te(e,t){this._pairs=[],e&&xe(e,this,t)}var ke=Te.prototype;function je(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Ae(e,t,r){if(!t)return e;var n=r&&r.encode||je;ye.isFunction(r)&&(r={serialize:r});var o,i=r&&r.serialize;if(o=i?i(t,r):ye.isURLSearchParams(t)?t.toString():new Te(t,r).toString(n)){var a=e.indexOf("#");-1!==a&&(e=e.slice(0,a)),e+=(-1===e.indexOf("?")?"?":"&")+o}return e}ke.append=function(e,t){this._pairs.push([e,t])},ke.toString=function(e){var t=e?function(t){return e.call(this,t,Re)}:Re;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var Pe=function(){function e(){d(this,e),this.handlers=[]}return y(e,[{key:"use",value:function(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}},{key:"eject",value:function(e){this.handlers[e]&&(this.handlers[e]=null)}},{key:"clear",value:function(){this.handlers&&(this.handlers=[])}},{key:"forEach",value:function(e){ye.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}]),e}(),Le={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ne={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Te,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},_e="undefined"!=typeof window&&"undefined"!=typeof document,Ce="object"===("undefined"==typeof navigator?"undefined":f(navigator))&&navigator||void 0,Fe=_e&&(!Ce||["ReactNative","NativeScript","NS"].indexOf(Ce.product)<0),Ue="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Be=_e&&window.location.href||"http://localhost",De=u(u({},Object.freeze({__proto__:null,hasBrowserEnv:_e,hasStandardBrowserWebWorkerEnv:Ue,hasStandardBrowserEnv:Fe,navigator:Ce,origin:Be})),Ne);function Ie(e){function t(e,r,n,o){var i=e[o++];if("__proto__"===i)return!0;var a=Number.isFinite(+i),u=o>=e.length;return i=!i&&ye.isArray(n)?n.length:i,u?(ye.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!a):(n[i]&&ye.isObject(n[i])||(n[i]=[]),t(e,r,n[i],o)&&ye.isArray(n[i])&&(n[i]=function(e){var t,r,n={},o=Object.keys(e),i=o.length;for(t=0;t-1,i=ye.isObject(e);if(i&&ye.isHTMLForm(e)&&(e=new FormData(e)),ye.isFormData(e))return o?JSON.stringify(Ie(e)):e;if(ye.isArrayBuffer(e)||ye.isBuffer(e)||ye.isStream(e)||ye.isFile(e)||ye.isBlob(e)||ye.isReadableStream(e))return e;if(ye.isArrayBufferView(e))return e.buffer;if(ye.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();if(i){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return xe(e,new De.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return De.isNode&&ye.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((r=ye.isFileList(e))||n.indexOf("multipart/form-data")>-1){var a=this.env&&this.env.FormData;return xe(r?{"files[]":e}:e,a&&new a,this.formSerializer)}}return i||o?(t.setContentType("application/json",!1),function(e,t,r){if(ye.isString(e))try{return(t||JSON.parse)(e),ye.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||qe.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(ye.isResponse(e)||ye.isReadableStream(e))return e;if(e&&ye.isString(e)&&(r&&!this.responseType||n)){var o=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(o){if("SyntaxError"===e.name)throw me.from(e,me.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:De.classes.FormData,Blob:De.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ye.forEach(["delete","get","head","post","put","patch"],(function(e){qe.headers[e]={}}));var Me=qe,ze=ye.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),He=Symbol("internals");function Je(e){return e&&String(e).trim().toLowerCase()}function We(e){return!1===e||null==e?e:ye.isArray(e)?e.map(We):String(e)}function Ge(e,t,r,n,o){return ye.isFunction(n)?n.call(this,t,r):(o&&(t=r),ye.isString(t)?ye.isString(n)?-1!==t.indexOf(n):ye.isRegExp(n)?n.test(t):void 0:void 0)}var Ke=function(e,t){function r(e){d(this,r),e&&this.set(e)}return y(r,[{key:"set",value:function(e,t,r){var n=this;function o(e,t,r){var o=Je(t);if(!o)throw new Error("header name must be a non-empty string");var i=ye.findKey(n,o);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=We(e))}var i=function(e,t){return ye.forEach(e,(function(e,r){return o(e,r,t)}))};if(ye.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(ye.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))i(function(e){var t,r,n,o={};return e&&e.split("\n").forEach((function(e){n=e.indexOf(":"),t=e.substring(0,n).trim().toLowerCase(),r=e.substring(n+1).trim(),!t||o[t]&&ze[t]||("set-cookie"===t?o[t]?o[t].push(r):o[t]=[r]:o[t]=o[t]?o[t]+", "+r:r)})),o}(e),t);else if(ye.isHeaders(e)){var a,u=function(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=O(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,o=function(){};return{s:o,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,u=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){u=!0,i=e},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw i}}}}(e.entries());try{for(u.s();!(a=u.n()).done;){var s=b(a.value,2),c=s[0];o(s[1],c,r)}}catch(e){u.e(e)}finally{u.f()}}else null!=e&&o(t,e,r);return this}},{key:"get",value:function(e,t){if(e=Je(e)){var r=ye.findKey(this,e);if(r){var n=this[r];if(!t)return n;if(!0===t)return function(e){for(var t,r=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;t=n.exec(e);)r[t[1]]=t[2];return r}(n);if(ye.isFunction(t))return t.call(this,n,r);if(ye.isRegExp(t))return t.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}},{key:"has",value:function(e,t){if(e=Je(e)){var r=ye.findKey(this,e);return!(!r||void 0===this[r]||t&&!Ge(0,this[r],r,t))}return!1}},{key:"delete",value:function(e,t){var r=this,n=!1;function o(e){if(e=Je(e)){var o=ye.findKey(r,e);!o||t&&!Ge(0,r[o],o,t)||(delete r[o],n=!0)}}return ye.isArray(e)?e.forEach(o):o(e),n}},{key:"clear",value:function(e){for(var t=Object.keys(this),r=t.length,n=!1;r--;){var o=t[r];e&&!Ge(0,this[o],o,e,!0)||(delete this[o],n=!0)}return n}},{key:"normalize",value:function(e){var t=this,r={};return ye.forEach(this,(function(n,o){var i=ye.findKey(r,o);if(i)return t[i]=We(n),void delete t[o];var a=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r}))}(o):String(o).trim();a!==o&&delete t[o],t[a]=We(n),r[a]=!0})),this}},{key:"concat",value:function(){for(var e,t=arguments.length,r=new Array(t),n=0;n1?r-1:0),o=1;o1&&void 0!==arguments[1]?arguments[1]:Date.now();o=i,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[function(){for(var e=Date.now(),t=e-o,u=arguments.length,s=new Array(u),c=0;c=i?a(s,e):(r=s,n||(n=setTimeout((function(){n=null,a(r)}),i-t)))},function(){return r&&a(r)}]}ye.inherits(Ye,me,{__CANCEL__:!0});var tt=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,n=0,o=Ze(50,250);return et((function(r){var i=r.loaded,a=r.lengthComputable?r.total:void 0,u=i-n,s=o(u);n=i;var c=m({loaded:i,total:a,progress:a?i/a:void 0,bytes:u,rate:s||void 0,estimated:s&&a&&i<=a?(a-i)/s:void 0,event:r,lengthComputable:null!=a},t?"download":"upload",!0);e(c)}),r)},rt=function(e,t){var r=null!=e;return[function(n){return t[0]({lengthComputable:r,total:e,loaded:n})},t[1]]},nt=function(e){return function(){for(var t=arguments.length,r=new Array(t),n=0;n1?t-1:0),n=1;n1?"since :\n"+u.map(At).join("\n"):" "+At(u[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return r};function Nt(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Ye(null,e)}function _t(e){return Nt(e),e.headers=Ve.from(e.headers),e.data=Xe.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Lt(e.adapter||Me.adapter)(e).then((function(t){return Nt(e),t.data=Xe.call(e,e.transformResponse,t),t.headers=Ve.from(t.headers),t}),(function(t){return $e(t)||(Nt(e),t&&t.response&&(t.response.data=Xe.call(e,e.transformResponse,t.response),t.response.headers=Ve.from(t.response.headers))),Promise.reject(t)}))}var Ct="1.7.9",Ft={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){Ft[e]=function(r){return f(r)===e||"a"+(t<1?"n ":" ")+e}}));var Ut={};Ft.transitional=function(e,t,r){function n(e,t){return"[Axios v1.7.9] Transitional option '"+e+"'"+t+(r?". "+r:"")}return function(r,o,i){if(!1===e)throw new me(n(o," has been removed"+(t?" in "+t:"")),me.ERR_DEPRECATED);return t&&!Ut[o]&&(Ut[o]=!0,console.warn(n(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,o,i)}},Ft.spelling=function(e){return function(t,r){return console.warn("".concat(r," is likely a misspelling of ").concat(e)),!0}};var Bt={assertOptions:function(e,t,r){if("object"!==f(e))throw new me("options must be an object",me.ERR_BAD_OPTION_VALUE);for(var n=Object.keys(e),o=n.length;o-- >0;){var i=n[o],a=t[i];if(a){var u=e[i],s=void 0===u||a(u,i,e);if(!0!==s)throw new me("option "+i+" must be "+s,me.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new me("Unknown option "+i,me.ERR_BAD_OPTION)}},validators:Ft},Dt=Bt.validators,It=function(){function e(t){d(this,e),this.defaults=t,this.interceptors={request:new Pe,response:new Pe}}var t;return y(e,[{key:"request",value:(t=h(s().mark((function e(t,r){var n,o;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this._request(t,r);case 3:return e.abrupt("return",e.sent);case 6:if(e.prev=6,e.t0=e.catch(0),e.t0 instanceof Error){n={},Error.captureStackTrace?Error.captureStackTrace(n):n=new Error,o=n.stack?n.stack.replace(/^.+\n/,""):"";try{e.t0.stack?o&&!String(e.t0.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(e.t0.stack+="\n"+o):e.t0.stack=o}catch(e){}}throw e.t0;case 10:case"end":return e.stop()}}),e,this,[[0,6]])}))),function(e,r){return t.apply(this,arguments)})},{key:"_request",value:function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{};var r=t=st(this.defaults,t),n=r.transitional,o=r.paramsSerializer,i=r.headers;void 0!==n&&Bt.assertOptions(n,{silentJSONParsing:Dt.transitional(Dt.boolean),forcedJSONParsing:Dt.transitional(Dt.boolean),clarifyTimeoutError:Dt.transitional(Dt.boolean)},!1),null!=o&&(ye.isFunction(o)?t.paramsSerializer={serialize:o}:Bt.assertOptions(o,{encode:Dt.function,serialize:Dt.function},!0)),Bt.assertOptions(t,{baseUrl:Dt.spelling("baseURL"),withXsrfToken:Dt.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();var a=i&&ye.merge(i.common,i[t.method]);i&&ye.forEach(["delete","get","head","post","put","patch","common"],(function(e){delete i[e]})),t.headers=Ve.concat(a,i);var u=[],s=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(s=s&&e.synchronous,u.unshift(e.fulfilled,e.rejected))}));var c,f=[];this.interceptors.response.forEach((function(e){f.push(e.fulfilled,e.rejected)}));var l,p=0;if(!s){var h=[_t.bind(this),void 0];for(h.unshift.apply(h,u),h.push.apply(h,f),l=h.length,c=Promise.resolve(t);p0;)n._listeners[t](e);n._listeners=null}})),this.promise.then=function(e){var t,r=new Promise((function(e){n.subscribe(e),t=e})).then(e);return r.cancel=function(){n.unsubscribe(t)},r},t((function(e,t,o){n.reason||(n.reason=new Ye(e,t,o),r(n.reason))}))}return y(e,[{key:"throwIfRequested",value:function(){if(this.reason)throw this.reason}},{key:"subscribe",value:function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}},{key:"unsubscribe",value:function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}}},{key:"toAbortSignal",value:function(){var e=this,t=new AbortController,r=function(e){t.abort(e)};return this.subscribe(r),t.signal.unsubscribe=function(){return e.unsubscribe(r)},t.signal}}],[{key:"source",value:function(){var t;return{token:new e((function(e){t=e})),cancel:t}}}]),e}(),zt=Mt;var Ht={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Ht).forEach((function(e){var t=b(e,2),r=t[0],n=t[1];Ht[n]=r}));var Jt=Ht;var Wt=function e(t){var r=new qt(t),n=R(qt.prototype.request,r);return ye.extend(n,qt.prototype,r,{allOwnKeys:!0}),ye.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(st(t,r))},n}(Me);return Wt.Axios=qt,Wt.CanceledError=Ye,Wt.CancelToken=zt,Wt.isCancel=$e,Wt.VERSION=Ct,Wt.toFormData=xe,Wt.AxiosError=me,Wt.Cancel=Wt.CanceledError,Wt.all=function(e){return Promise.all(e)},Wt.spread=function(e){return function(t){return e.apply(null,t)}},Wt.isAxiosError=function(e){return ye.isObject(e)&&!0===e.isAxiosError},Wt.mergeConfig=st,Wt.AxiosHeaders=Ve,Wt.formToJSON=function(e){return Ie(ye.isHTMLForm(e)?new FormData(e):e)},Wt.getAdapter=Lt,Wt.HttpStatusCode=Jt,Wt.default=Wt,Wt})); +//# sourceMappingURL=axios.min.js.map diff --git a/node_modules/axios/dist/axios.min.js.map b/node_modules/axios/dist/axios.min.js.map new file mode 100644 index 000000000..49c5dc44a --- /dev/null +++ b/node_modules/axios/dist/axios.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"axios.min.js","sources":["../lib/helpers/bind.js","../lib/utils.js","../lib/core/AxiosError.js","../lib/helpers/toFormData.js","../lib/helpers/AxiosURLSearchParams.js","../lib/helpers/buildURL.js","../lib/core/InterceptorManager.js","../lib/defaults/transitional.js","../lib/platform/browser/index.js","../lib/platform/browser/classes/URLSearchParams.js","../lib/platform/browser/classes/FormData.js","../lib/platform/browser/classes/Blob.js","../lib/platform/common/utils.js","../lib/platform/index.js","../lib/helpers/formDataToJSON.js","../lib/defaults/index.js","../lib/helpers/toURLEncodedForm.js","../lib/helpers/parseHeaders.js","../lib/core/AxiosHeaders.js","../lib/core/transformData.js","../lib/cancel/isCancel.js","../lib/cancel/CanceledError.js","../lib/core/settle.js","../lib/helpers/speedometer.js","../lib/helpers/throttle.js","../lib/helpers/progressEventReducer.js","../lib/helpers/isURLSameOrigin.js","../lib/helpers/cookies.js","../lib/core/buildFullPath.js","../lib/helpers/isAbsoluteURL.js","../lib/helpers/combineURLs.js","../lib/core/mergeConfig.js","../lib/helpers/resolveConfig.js","../lib/adapters/fetch.js","../lib/adapters/xhr.js","../lib/helpers/parseProtocol.js","../lib/helpers/composeSignals.js","../lib/helpers/trackStream.js","../lib/adapters/adapters.js","../lib/helpers/null.js","../lib/core/dispatchRequest.js","../lib/env/data.js","../lib/helpers/validator.js","../lib/core/Axios.js","../lib/cancel/CancelToken.js","../lib/helpers/HttpStatusCode.js","../lib/axios.js","../lib/helpers/spread.js","../lib/helpers/isAxiosError.js"],"sourcesContent":["'use strict';\n\nexport default function bind(fn, thisArg) {\n return function wrap() {\n return fn.apply(thisArg, arguments);\n };\n}\n","'use strict';\n\nimport bind from './helpers/bind.js';\n\n// utils is a library of generic helper functions non-specific to axios\n\nconst {toString} = Object.prototype;\nconst {getPrototypeOf} = Object;\n\nconst kindOf = (cache => thing => {\n const str = toString.call(thing);\n return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());\n})(Object.create(null));\n\nconst kindOfTest = (type) => {\n type = type.toLowerCase();\n return (thing) => kindOf(thing) === type\n}\n\nconst typeOfTest = type => thing => typeof thing === type;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n *\n * @returns {boolean} True if value is an Array, otherwise false\n */\nconst {isArray} = Array;\n\n/**\n * Determine if a value is undefined\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nconst isUndefined = typeOfTest('undefined');\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nconst isArrayBuffer = kindOfTest('ArrayBuffer');\n\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n let result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a String, otherwise false\n */\nconst isString = typeOfTest('string');\n\n/**\n * Determine if a value is a Function\n *\n * @param {*} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nconst isFunction = typeOfTest('function');\n\n/**\n * Determine if a value is a Number\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Number, otherwise false\n */\nconst isNumber = typeOfTest('number');\n\n/**\n * Determine if a value is an Object\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an Object, otherwise false\n */\nconst isObject = (thing) => thing !== null && typeof thing === 'object';\n\n/**\n * Determine if a value is a Boolean\n *\n * @param {*} thing The value to test\n * @returns {boolean} True if value is a Boolean, otherwise false\n */\nconst isBoolean = thing => thing === true || thing === false;\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a plain Object, otherwise false\n */\nconst isPlainObject = (val) => {\n if (kindOf(val) !== 'object') {\n return false;\n }\n\n const prototype = getPrototypeOf(val);\n return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Date, otherwise false\n */\nconst isDate = kindOfTest('Date');\n\n/**\n * Determine if a value is a File\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFile = kindOfTest('File');\n\n/**\n * Determine if a value is a Blob\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nconst isBlob = kindOfTest('Blob');\n\n/**\n * Determine if a value is a FileList\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFileList = kindOfTest('FileList');\n\n/**\n * Determine if a value is a Stream\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nconst isStream = (val) => isObject(val) && isFunction(val.pipe);\n\n/**\n * Determine if a value is a FormData\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nconst isFormData = (thing) => {\n let kind;\n return thing && (\n (typeof FormData === 'function' && thing instanceof FormData) || (\n isFunction(thing.append) && (\n (kind = kindOf(thing)) === 'formdata' ||\n // detect form-data instance\n (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')\n )\n )\n )\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nconst isURLSearchParams = kindOfTest('URLSearchParams');\n\nconst [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n *\n * @returns {String} The String freed of excess whitespace\n */\nconst trim = (str) => str.trim ?\n str.trim() : str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '');\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n *\n * @param {Boolean} [allOwnKeys = false]\n * @returns {any}\n */\nfunction forEach(obj, fn, {allOwnKeys = false} = {}) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n let i;\n let l;\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);\n const len = keys.length;\n let key;\n\n for (i = 0; i < len; i++) {\n key = keys[i];\n fn.call(null, obj[key], key, obj);\n }\n }\n}\n\nfunction findKey(obj, key) {\n key = key.toLowerCase();\n const keys = Object.keys(obj);\n let i = keys.length;\n let _key;\n while (i-- > 0) {\n _key = keys[i];\n if (key === _key.toLowerCase()) {\n return _key;\n }\n }\n return null;\n}\n\nconst _global = (() => {\n /*eslint no-undef:0*/\n if (typeof globalThis !== \"undefined\") return globalThis;\n return typeof self !== \"undefined\" ? self : (typeof window !== 'undefined' ? window : global)\n})();\n\nconst isContextDefined = (context) => !isUndefined(context) && context !== _global;\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n *\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n const {caseless} = isContextDefined(this) && this || {};\n const result = {};\n const assignValue = (val, key) => {\n const targetKey = caseless && findKey(result, key) || key;\n if (isPlainObject(result[targetKey]) && isPlainObject(val)) {\n result[targetKey] = merge(result[targetKey], val);\n } else if (isPlainObject(val)) {\n result[targetKey] = merge({}, val);\n } else if (isArray(val)) {\n result[targetKey] = val.slice();\n } else {\n result[targetKey] = val;\n }\n }\n\n for (let i = 0, l = arguments.length; i < l; i++) {\n arguments[i] && forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n *\n * @param {Boolean} [allOwnKeys]\n * @returns {Object} The resulting value of object a\n */\nconst extend = (a, b, thisArg, {allOwnKeys}= {}) => {\n forEach(b, (val, key) => {\n if (thisArg && isFunction(val)) {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n }, {allOwnKeys});\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n *\n * @returns {string} content value without BOM\n */\nconst stripBOM = (content) => {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\n/**\n * Inherit the prototype methods from one constructor into another\n * @param {function} constructor\n * @param {function} superConstructor\n * @param {object} [props]\n * @param {object} [descriptors]\n *\n * @returns {void}\n */\nconst inherits = (constructor, superConstructor, props, descriptors) => {\n constructor.prototype = Object.create(superConstructor.prototype, descriptors);\n constructor.prototype.constructor = constructor;\n Object.defineProperty(constructor, 'super', {\n value: superConstructor.prototype\n });\n props && Object.assign(constructor.prototype, props);\n}\n\n/**\n * Resolve object with deep prototype chain to a flat object\n * @param {Object} sourceObj source object\n * @param {Object} [destObj]\n * @param {Function|Boolean} [filter]\n * @param {Function} [propFilter]\n *\n * @returns {Object}\n */\nconst toFlatObject = (sourceObj, destObj, filter, propFilter) => {\n let props;\n let i;\n let prop;\n const merged = {};\n\n destObj = destObj || {};\n // eslint-disable-next-line no-eq-null,eqeqeq\n if (sourceObj == null) return destObj;\n\n do {\n props = Object.getOwnPropertyNames(sourceObj);\n i = props.length;\n while (i-- > 0) {\n prop = props[i];\n if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {\n destObj[prop] = sourceObj[prop];\n merged[prop] = true;\n }\n }\n sourceObj = filter !== false && getPrototypeOf(sourceObj);\n } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);\n\n return destObj;\n}\n\n/**\n * Determines whether a string ends with the characters of a specified string\n *\n * @param {String} str\n * @param {String} searchString\n * @param {Number} [position= 0]\n *\n * @returns {boolean}\n */\nconst endsWith = (str, searchString, position) => {\n str = String(str);\n if (position === undefined || position > str.length) {\n position = str.length;\n }\n position -= searchString.length;\n const lastIndex = str.indexOf(searchString, position);\n return lastIndex !== -1 && lastIndex === position;\n}\n\n\n/**\n * Returns new array from array like object or null if failed\n *\n * @param {*} [thing]\n *\n * @returns {?Array}\n */\nconst toArray = (thing) => {\n if (!thing) return null;\n if (isArray(thing)) return thing;\n let i = thing.length;\n if (!isNumber(i)) return null;\n const arr = new Array(i);\n while (i-- > 0) {\n arr[i] = thing[i];\n }\n return arr;\n}\n\n/**\n * Checking if the Uint8Array exists and if it does, it returns a function that checks if the\n * thing passed in is an instance of Uint8Array\n *\n * @param {TypedArray}\n *\n * @returns {Array}\n */\n// eslint-disable-next-line func-names\nconst isTypedArray = (TypedArray => {\n // eslint-disable-next-line func-names\n return thing => {\n return TypedArray && thing instanceof TypedArray;\n };\n})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));\n\n/**\n * For each entry in the object, call the function with the key and value.\n *\n * @param {Object} obj - The object to iterate over.\n * @param {Function} fn - The function to call for each entry.\n *\n * @returns {void}\n */\nconst forEachEntry = (obj, fn) => {\n const generator = obj && obj[Symbol.iterator];\n\n const iterator = generator.call(obj);\n\n let result;\n\n while ((result = iterator.next()) && !result.done) {\n const pair = result.value;\n fn.call(obj, pair[0], pair[1]);\n }\n}\n\n/**\n * It takes a regular expression and a string, and returns an array of all the matches\n *\n * @param {string} regExp - The regular expression to match against.\n * @param {string} str - The string to search.\n *\n * @returns {Array}\n */\nconst matchAll = (regExp, str) => {\n let matches;\n const arr = [];\n\n while ((matches = regExp.exec(str)) !== null) {\n arr.push(matches);\n }\n\n return arr;\n}\n\n/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */\nconst isHTMLForm = kindOfTest('HTMLFormElement');\n\nconst toCamelCase = str => {\n return str.toLowerCase().replace(/[-_\\s]([a-z\\d])(\\w*)/g,\n function replacer(m, p1, p2) {\n return p1.toUpperCase() + p2;\n }\n );\n};\n\n/* Creating a function that will check if an object has a property. */\nconst hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);\n\n/**\n * Determine if a value is a RegExp object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a RegExp object, otherwise false\n */\nconst isRegExp = kindOfTest('RegExp');\n\nconst reduceDescriptors = (obj, reducer) => {\n const descriptors = Object.getOwnPropertyDescriptors(obj);\n const reducedDescriptors = {};\n\n forEach(descriptors, (descriptor, name) => {\n let ret;\n if ((ret = reducer(descriptor, name, obj)) !== false) {\n reducedDescriptors[name] = ret || descriptor;\n }\n });\n\n Object.defineProperties(obj, reducedDescriptors);\n}\n\n/**\n * Makes all methods read-only\n * @param {Object} obj\n */\n\nconst freezeMethods = (obj) => {\n reduceDescriptors(obj, (descriptor, name) => {\n // skip restricted props in strict mode\n if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {\n return false;\n }\n\n const value = obj[name];\n\n if (!isFunction(value)) return;\n\n descriptor.enumerable = false;\n\n if ('writable' in descriptor) {\n descriptor.writable = false;\n return;\n }\n\n if (!descriptor.set) {\n descriptor.set = () => {\n throw Error('Can not rewrite read-only method \\'' + name + '\\'');\n };\n }\n });\n}\n\nconst toObjectSet = (arrayOrString, delimiter) => {\n const obj = {};\n\n const define = (arr) => {\n arr.forEach(value => {\n obj[value] = true;\n });\n }\n\n isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));\n\n return obj;\n}\n\nconst noop = () => {}\n\nconst toFiniteNumber = (value, defaultValue) => {\n return value != null && Number.isFinite(value = +value) ? value : defaultValue;\n}\n\nconst ALPHA = 'abcdefghijklmnopqrstuvwxyz'\n\nconst DIGIT = '0123456789';\n\nconst ALPHABET = {\n DIGIT,\n ALPHA,\n ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT\n}\n\nconst generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {\n let str = '';\n const {length} = alphabet;\n while (size--) {\n str += alphabet[Math.random() * length|0]\n }\n\n return str;\n}\n\n/**\n * If the thing is a FormData object, return true, otherwise return false.\n *\n * @param {unknown} thing - The thing to check.\n *\n * @returns {boolean}\n */\nfunction isSpecCompliantForm(thing) {\n return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);\n}\n\nconst toJSONObject = (obj) => {\n const stack = new Array(10);\n\n const visit = (source, i) => {\n\n if (isObject(source)) {\n if (stack.indexOf(source) >= 0) {\n return;\n }\n\n if(!('toJSON' in source)) {\n stack[i] = source;\n const target = isArray(source) ? [] : {};\n\n forEach(source, (value, key) => {\n const reducedValue = visit(value, i + 1);\n !isUndefined(reducedValue) && (target[key] = reducedValue);\n });\n\n stack[i] = undefined;\n\n return target;\n }\n }\n\n return source;\n }\n\n return visit(obj, 0);\n}\n\nconst isAsyncFn = kindOfTest('AsyncFunction');\n\nconst isThenable = (thing) =>\n thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);\n\n// original code\n// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34\n\nconst _setImmediate = ((setImmediateSupported, postMessageSupported) => {\n if (setImmediateSupported) {\n return setImmediate;\n }\n\n return postMessageSupported ? ((token, callbacks) => {\n _global.addEventListener(\"message\", ({source, data}) => {\n if (source === _global && data === token) {\n callbacks.length && callbacks.shift()();\n }\n }, false);\n\n return (cb) => {\n callbacks.push(cb);\n _global.postMessage(token, \"*\");\n }\n })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);\n})(\n typeof setImmediate === 'function',\n isFunction(_global.postMessage)\n);\n\nconst asap = typeof queueMicrotask !== 'undefined' ?\n queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);\n\n// *********************\n\nexport default {\n isArray,\n isArrayBuffer,\n isBuffer,\n isFormData,\n isArrayBufferView,\n isString,\n isNumber,\n isBoolean,\n isObject,\n isPlainObject,\n isReadableStream,\n isRequest,\n isResponse,\n isHeaders,\n isUndefined,\n isDate,\n isFile,\n isBlob,\n isRegExp,\n isFunction,\n isStream,\n isURLSearchParams,\n isTypedArray,\n isFileList,\n forEach,\n merge,\n extend,\n trim,\n stripBOM,\n inherits,\n toFlatObject,\n kindOf,\n kindOfTest,\n endsWith,\n toArray,\n forEachEntry,\n matchAll,\n isHTMLForm,\n hasOwnProperty,\n hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection\n reduceDescriptors,\n freezeMethods,\n toObjectSet,\n toCamelCase,\n noop,\n toFiniteNumber,\n findKey,\n global: _global,\n isContextDefined,\n ALPHABET,\n generateString,\n isSpecCompliantForm,\n toJSONObject,\n isAsyncFn,\n isThenable,\n setImmediate: _setImmediate,\n asap\n};\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [config] The config.\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n *\n * @returns {Error} The created error.\n */\nfunction AxiosError(message, code, config, request, response) {\n Error.call(this);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error()).stack;\n }\n\n this.message = message;\n this.name = 'AxiosError';\n code && (this.code = code);\n config && (this.config = config);\n request && (this.request = request);\n if (response) {\n this.response = response;\n this.status = response.status ? response.status : null;\n }\n}\n\nutils.inherits(AxiosError, Error, {\n toJSON: function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: utils.toJSONObject(this.config),\n code: this.code,\n status: this.status\n };\n }\n});\n\nconst prototype = AxiosError.prototype;\nconst descriptors = {};\n\n[\n 'ERR_BAD_OPTION_VALUE',\n 'ERR_BAD_OPTION',\n 'ECONNABORTED',\n 'ETIMEDOUT',\n 'ERR_NETWORK',\n 'ERR_FR_TOO_MANY_REDIRECTS',\n 'ERR_DEPRECATED',\n 'ERR_BAD_RESPONSE',\n 'ERR_BAD_REQUEST',\n 'ERR_CANCELED',\n 'ERR_NOT_SUPPORT',\n 'ERR_INVALID_URL'\n// eslint-disable-next-line func-names\n].forEach(code => {\n descriptors[code] = {value: code};\n});\n\nObject.defineProperties(AxiosError, descriptors);\nObject.defineProperty(prototype, 'isAxiosError', {value: true});\n\n// eslint-disable-next-line func-names\nAxiosError.from = (error, code, config, request, response, customProps) => {\n const axiosError = Object.create(prototype);\n\n utils.toFlatObject(error, axiosError, function filter(obj) {\n return obj !== Error.prototype;\n }, prop => {\n return prop !== 'isAxiosError';\n });\n\n AxiosError.call(axiosError, error.message, code, config, request, response);\n\n axiosError.cause = error;\n\n axiosError.name = error.name;\n\n customProps && Object.assign(axiosError, customProps);\n\n return axiosError;\n};\n\nexport default AxiosError;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\n// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored\nimport PlatformFormData from '../platform/node/classes/FormData.js';\n\n/**\n * Determines if the given thing is a array or js object.\n *\n * @param {string} thing - The object or array to be visited.\n *\n * @returns {boolean}\n */\nfunction isVisitable(thing) {\n return utils.isPlainObject(thing) || utils.isArray(thing);\n}\n\n/**\n * It removes the brackets from the end of a string\n *\n * @param {string} key - The key of the parameter.\n *\n * @returns {string} the key without the brackets.\n */\nfunction removeBrackets(key) {\n return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;\n}\n\n/**\n * It takes a path, a key, and a boolean, and returns a string\n *\n * @param {string} path - The path to the current key.\n * @param {string} key - The key of the current object being iterated over.\n * @param {string} dots - If true, the key will be rendered with dots instead of brackets.\n *\n * @returns {string} The path to the current key.\n */\nfunction renderKey(path, key, dots) {\n if (!path) return key;\n return path.concat(key).map(function each(token, i) {\n // eslint-disable-next-line no-param-reassign\n token = removeBrackets(token);\n return !dots && i ? '[' + token + ']' : token;\n }).join(dots ? '.' : '');\n}\n\n/**\n * If the array is an array and none of its elements are visitable, then it's a flat array.\n *\n * @param {Array} arr - The array to check\n *\n * @returns {boolean}\n */\nfunction isFlatArray(arr) {\n return utils.isArray(arr) && !arr.some(isVisitable);\n}\n\nconst predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {\n return /^is[A-Z]/.test(prop);\n});\n\n/**\n * Convert a data object to FormData\n *\n * @param {Object} obj\n * @param {?Object} [formData]\n * @param {?Object} [options]\n * @param {Function} [options.visitor]\n * @param {Boolean} [options.metaTokens = true]\n * @param {Boolean} [options.dots = false]\n * @param {?Boolean} [options.indexes = false]\n *\n * @returns {Object}\n **/\n\n/**\n * It converts an object into a FormData object\n *\n * @param {Object} obj - The object to convert to form data.\n * @param {string} formData - The FormData object to append to.\n * @param {Object} options\n *\n * @returns\n */\nfunction toFormData(obj, formData, options) {\n if (!utils.isObject(obj)) {\n throw new TypeError('target must be an object');\n }\n\n // eslint-disable-next-line no-param-reassign\n formData = formData || new (PlatformFormData || FormData)();\n\n // eslint-disable-next-line no-param-reassign\n options = utils.toFlatObject(options, {\n metaTokens: true,\n dots: false,\n indexes: false\n }, false, function defined(option, source) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n return !utils.isUndefined(source[option]);\n });\n\n const metaTokens = options.metaTokens;\n // eslint-disable-next-line no-use-before-define\n const visitor = options.visitor || defaultVisitor;\n const dots = options.dots;\n const indexes = options.indexes;\n const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;\n const useBlob = _Blob && utils.isSpecCompliantForm(formData);\n\n if (!utils.isFunction(visitor)) {\n throw new TypeError('visitor must be a function');\n }\n\n function convertValue(value) {\n if (value === null) return '';\n\n if (utils.isDate(value)) {\n return value.toISOString();\n }\n\n if (!useBlob && utils.isBlob(value)) {\n throw new AxiosError('Blob is not supported. Use a Buffer instead.');\n }\n\n if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {\n return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);\n }\n\n return value;\n }\n\n /**\n * Default visitor.\n *\n * @param {*} value\n * @param {String|Number} key\n * @param {Array} path\n * @this {FormData}\n *\n * @returns {boolean} return true to visit the each prop of the value recursively\n */\n function defaultVisitor(value, key, path) {\n let arr = value;\n\n if (value && !path && typeof value === 'object') {\n if (utils.endsWith(key, '{}')) {\n // eslint-disable-next-line no-param-reassign\n key = metaTokens ? key : key.slice(0, -2);\n // eslint-disable-next-line no-param-reassign\n value = JSON.stringify(value);\n } else if (\n (utils.isArray(value) && isFlatArray(value)) ||\n ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))\n )) {\n // eslint-disable-next-line no-param-reassign\n key = removeBrackets(key);\n\n arr.forEach(function each(el, index) {\n !(utils.isUndefined(el) || el === null) && formData.append(\n // eslint-disable-next-line no-nested-ternary\n indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),\n convertValue(el)\n );\n });\n return false;\n }\n }\n\n if (isVisitable(value)) {\n return true;\n }\n\n formData.append(renderKey(path, key, dots), convertValue(value));\n\n return false;\n }\n\n const stack = [];\n\n const exposedHelpers = Object.assign(predicates, {\n defaultVisitor,\n convertValue,\n isVisitable\n });\n\n function build(value, path) {\n if (utils.isUndefined(value)) return;\n\n if (stack.indexOf(value) !== -1) {\n throw Error('Circular reference detected in ' + path.join('.'));\n }\n\n stack.push(value);\n\n utils.forEach(value, function each(el, key) {\n const result = !(utils.isUndefined(el) || el === null) && visitor.call(\n formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers\n );\n\n if (result === true) {\n build(el, path ? path.concat(key) : [key]);\n }\n });\n\n stack.pop();\n }\n\n if (!utils.isObject(obj)) {\n throw new TypeError('data must be an object');\n }\n\n build(obj);\n\n return formData;\n}\n\nexport default toFormData;\n","'use strict';\n\nimport toFormData from './toFormData.js';\n\n/**\n * It encodes a string by replacing all characters that are not in the unreserved set with\n * their percent-encoded equivalents\n *\n * @param {string} str - The string to encode.\n *\n * @returns {string} The encoded string.\n */\nfunction encode(str) {\n const charMap = {\n '!': '%21',\n \"'\": '%27',\n '(': '%28',\n ')': '%29',\n '~': '%7E',\n '%20': '+',\n '%00': '\\x00'\n };\n return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {\n return charMap[match];\n });\n}\n\n/**\n * It takes a params object and converts it to a FormData object\n *\n * @param {Object} params - The parameters to be converted to a FormData object.\n * @param {Object} options - The options object passed to the Axios constructor.\n *\n * @returns {void}\n */\nfunction AxiosURLSearchParams(params, options) {\n this._pairs = [];\n\n params && toFormData(params, this, options);\n}\n\nconst prototype = AxiosURLSearchParams.prototype;\n\nprototype.append = function append(name, value) {\n this._pairs.push([name, value]);\n};\n\nprototype.toString = function toString(encoder) {\n const _encode = encoder ? function(value) {\n return encoder.call(this, value, encode);\n } : encode;\n\n return this._pairs.map(function each(pair) {\n return _encode(pair[0]) + '=' + _encode(pair[1]);\n }, '').join('&');\n};\n\nexport default AxiosURLSearchParams;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';\n\n/**\n * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their\n * URI encoded counterparts\n *\n * @param {string} val The value to be encoded.\n *\n * @returns {string} The encoded value.\n */\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @param {?(object|Function)} options\n *\n * @returns {string} The formatted url\n */\nexport default function buildURL(url, params, options) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n \n const _encode = options && options.encode || encode;\n\n if (utils.isFunction(options)) {\n options = {\n serialize: options\n };\n } \n\n const serializeFn = options && options.serialize;\n\n let serializedParams;\n\n if (serializeFn) {\n serializedParams = serializeFn(params, options);\n } else {\n serializedParams = utils.isURLSearchParams(params) ?\n params.toString() :\n new AxiosURLSearchParams(params, options).toString(_encode);\n }\n\n if (serializedParams) {\n const hashmarkIndex = url.indexOf(\"#\");\n\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\nclass InterceptorManager {\n constructor() {\n this.handlers = [];\n }\n\n /**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\n use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled,\n rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n }\n\n /**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n *\n * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise\n */\n eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n }\n\n /**\n * Clear all interceptors from the stack\n *\n * @returns {void}\n */\n clear() {\n if (this.handlers) {\n this.handlers = [];\n }\n }\n\n /**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n *\n * @returns {void}\n */\n forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n }\n}\n\nexport default InterceptorManager;\n","'use strict';\n\nexport default {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n};\n","import URLSearchParams from './classes/URLSearchParams.js'\nimport FormData from './classes/FormData.js'\nimport Blob from './classes/Blob.js'\n\nexport default {\n isBrowser: true,\n classes: {\n URLSearchParams,\n FormData,\n Blob\n },\n protocols: ['http', 'https', 'file', 'blob', 'url', 'data']\n};\n","'use strict';\n\nimport AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';\nexport default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;\n","'use strict';\n\nexport default typeof FormData !== 'undefined' ? FormData : null;\n","'use strict'\n\nexport default typeof Blob !== 'undefined' ? Blob : null\n","const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';\n\nconst _navigator = typeof navigator === 'object' && navigator || undefined;\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n *\n * @returns {boolean}\n */\nconst hasStandardBrowserEnv = hasBrowserEnv &&\n (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);\n\n/**\n * Determine if we're running in a standard browser webWorker environment\n *\n * Although the `isStandardBrowserEnv` method indicates that\n * `allows axios to run in a web worker`, the WebWorker will still be\n * filtered out due to its judgment standard\n * `typeof window !== 'undefined' && typeof document !== 'undefined'`.\n * This leads to a problem when axios post `FormData` in webWorker\n */\nconst hasStandardBrowserWebWorkerEnv = (() => {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n // eslint-disable-next-line no-undef\n self instanceof WorkerGlobalScope &&\n typeof self.importScripts === 'function'\n );\n})();\n\nconst origin = hasBrowserEnv && window.location.href || 'http://localhost';\n\nexport {\n hasBrowserEnv,\n hasStandardBrowserWebWorkerEnv,\n hasStandardBrowserEnv,\n _navigator as navigator,\n origin\n}\n","import platform from './node/index.js';\nimport * as utils from './common/utils.js';\n\nexport default {\n ...utils,\n ...platform\n}\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']\n *\n * @param {string} name - The name of the property to get.\n *\n * @returns An array of strings.\n */\nfunction parsePropPath(name) {\n // foo[x][y][z]\n // foo.x.y.z\n // foo-x-y-z\n // foo x y z\n return utils.matchAll(/\\w+|\\[(\\w*)]/g, name).map(match => {\n return match[0] === '[]' ? '' : match[1] || match[0];\n });\n}\n\n/**\n * Convert an array to an object.\n *\n * @param {Array} arr - The array to convert to an object.\n *\n * @returns An object with the same keys and values as the array.\n */\nfunction arrayToObject(arr) {\n const obj = {};\n const keys = Object.keys(arr);\n let i;\n const len = keys.length;\n let key;\n for (i = 0; i < len; i++) {\n key = keys[i];\n obj[key] = arr[key];\n }\n return obj;\n}\n\n/**\n * It takes a FormData object and returns a JavaScript object\n *\n * @param {string} formData The FormData object to convert to JSON.\n *\n * @returns {Object | null} The converted object.\n */\nfunction formDataToJSON(formData) {\n function buildPath(path, value, target, index) {\n let name = path[index++];\n\n if (name === '__proto__') return true;\n\n const isNumericKey = Number.isFinite(+name);\n const isLast = index >= path.length;\n name = !name && utils.isArray(target) ? target.length : name;\n\n if (isLast) {\n if (utils.hasOwnProp(target, name)) {\n target[name] = [target[name], value];\n } else {\n target[name] = value;\n }\n\n return !isNumericKey;\n }\n\n if (!target[name] || !utils.isObject(target[name])) {\n target[name] = [];\n }\n\n const result = buildPath(path, value, target[name], index);\n\n if (result && utils.isArray(target[name])) {\n target[name] = arrayToObject(target[name]);\n }\n\n return !isNumericKey;\n }\n\n if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {\n const obj = {};\n\n utils.forEachEntry(formData, (name, value) => {\n buildPath(parsePropPath(name), value, obj, 0);\n });\n\n return obj;\n }\n\n return null;\n}\n\nexport default formDataToJSON;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\nimport transitionalDefaults from './transitional.js';\nimport toFormData from '../helpers/toFormData.js';\nimport toURLEncodedForm from '../helpers/toURLEncodedForm.js';\nimport platform from '../platform/index.js';\nimport formDataToJSON from '../helpers/formDataToJSON.js';\n\n/**\n * It takes a string, tries to parse it, and if it fails, it returns the stringified version\n * of the input\n *\n * @param {any} rawValue - The value to be stringified.\n * @param {Function} parser - A function that parses a string into a JavaScript object.\n * @param {Function} encoder - A function that takes a value and returns a string.\n *\n * @returns {string} A stringified version of the rawValue.\n */\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nconst defaults = {\n\n transitional: transitionalDefaults,\n\n adapter: ['xhr', 'http', 'fetch'],\n\n transformRequest: [function transformRequest(data, headers) {\n const contentType = headers.getContentType() || '';\n const hasJSONContentType = contentType.indexOf('application/json') > -1;\n const isObjectPayload = utils.isObject(data);\n\n if (isObjectPayload && utils.isHTMLForm(data)) {\n data = new FormData(data);\n }\n\n const isFormData = utils.isFormData(data);\n\n if (isFormData) {\n return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;\n }\n\n if (utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data) ||\n utils.isReadableStream(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);\n return data.toString();\n }\n\n let isFileList;\n\n if (isObjectPayload) {\n if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {\n return toURLEncodedForm(data, this.formSerializer).toString();\n }\n\n if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {\n const _FormData = this.env && this.env.FormData;\n\n return toFormData(\n isFileList ? {'files[]': data} : data,\n _FormData && new _FormData(),\n this.formSerializer\n );\n }\n }\n\n if (isObjectPayload || hasJSONContentType ) {\n headers.setContentType('application/json', false);\n return stringifySafely(data);\n }\n\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n const transitional = this.transitional || defaults.transitional;\n const forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n const JSONRequested = this.responseType === 'json';\n\n if (utils.isResponse(data) || utils.isReadableStream(data)) {\n return data;\n }\n\n if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {\n const silentJSONParsing = transitional && transitional.silentJSONParsing;\n const strictJSONParsing = !silentJSONParsing && JSONRequested;\n\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n env: {\n FormData: platform.classes.FormData,\n Blob: platform.classes.Blob\n },\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*',\n 'Content-Type': undefined\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {\n defaults.headers[method] = {};\n});\n\nexport default defaults;\n","'use strict';\n\nimport utils from '../utils.js';\nimport toFormData from './toFormData.js';\nimport platform from '../platform/index.js';\n\nexport default function toURLEncodedForm(data, options) {\n return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({\n visitor: function(value, key, path, helpers) {\n if (platform.isNode && utils.isBuffer(value)) {\n this.append(key, value.toString('base64'));\n return false;\n }\n\n return helpers.defaultVisitor.apply(this, arguments);\n }\n }, options));\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\n// RawAxiosHeaders whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nconst ignoreDuplicateOf = utils.toObjectSet([\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n]);\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} rawHeaders Headers needing to be parsed\n *\n * @returns {Object} Headers parsed into an object\n */\nexport default rawHeaders => {\n const parsed = {};\n let key;\n let val;\n let i;\n\n rawHeaders && rawHeaders.split('\\n').forEach(function parser(line) {\n i = line.indexOf(':');\n key = line.substring(0, i).trim().toLowerCase();\n val = line.substring(i + 1).trim();\n\n if (!key || (parsed[key] && ignoreDuplicateOf[key])) {\n return;\n }\n\n if (key === 'set-cookie') {\n if (parsed[key]) {\n parsed[key].push(val);\n } else {\n parsed[key] = [val];\n }\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n });\n\n return parsed;\n};\n","'use strict';\n\nimport utils from '../utils.js';\nimport parseHeaders from '../helpers/parseHeaders.js';\n\nconst $internals = Symbol('internals');\n\nfunction normalizeHeader(header) {\n return header && String(header).trim().toLowerCase();\n}\n\nfunction normalizeValue(value) {\n if (value === false || value == null) {\n return value;\n }\n\n return utils.isArray(value) ? value.map(normalizeValue) : String(value);\n}\n\nfunction parseTokens(str) {\n const tokens = Object.create(null);\n const tokensRE = /([^\\s,;=]+)\\s*(?:=\\s*([^,;]+))?/g;\n let match;\n\n while ((match = tokensRE.exec(str))) {\n tokens[match[1]] = match[2];\n }\n\n return tokens;\n}\n\nconst isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());\n\nfunction matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {\n if (utils.isFunction(filter)) {\n return filter.call(this, value, header);\n }\n\n if (isHeaderNameFilter) {\n value = header;\n }\n\n if (!utils.isString(value)) return;\n\n if (utils.isString(filter)) {\n return value.indexOf(filter) !== -1;\n }\n\n if (utils.isRegExp(filter)) {\n return filter.test(value);\n }\n}\n\nfunction formatHeader(header) {\n return header.trim()\n .toLowerCase().replace(/([a-z\\d])(\\w*)/g, (w, char, str) => {\n return char.toUpperCase() + str;\n });\n}\n\nfunction buildAccessors(obj, header) {\n const accessorName = utils.toCamelCase(' ' + header);\n\n ['get', 'set', 'has'].forEach(methodName => {\n Object.defineProperty(obj, methodName + accessorName, {\n value: function(arg1, arg2, arg3) {\n return this[methodName].call(this, header, arg1, arg2, arg3);\n },\n configurable: true\n });\n });\n}\n\nclass AxiosHeaders {\n constructor(headers) {\n headers && this.set(headers);\n }\n\n set(header, valueOrRewrite, rewrite) {\n const self = this;\n\n function setHeader(_value, _header, _rewrite) {\n const lHeader = normalizeHeader(_header);\n\n if (!lHeader) {\n throw new Error('header name must be a non-empty string');\n }\n\n const key = utils.findKey(self, lHeader);\n\n if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {\n self[key || _header] = normalizeValue(_value);\n }\n }\n\n const setHeaders = (headers, _rewrite) =>\n utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));\n\n if (utils.isPlainObject(header) || header instanceof this.constructor) {\n setHeaders(header, valueOrRewrite)\n } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {\n setHeaders(parseHeaders(header), valueOrRewrite);\n } else if (utils.isHeaders(header)) {\n for (const [key, value] of header.entries()) {\n setHeader(value, key, rewrite);\n }\n } else {\n header != null && setHeader(valueOrRewrite, header, rewrite);\n }\n\n return this;\n }\n\n get(header, parser) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n if (key) {\n const value = this[key];\n\n if (!parser) {\n return value;\n }\n\n if (parser === true) {\n return parseTokens(value);\n }\n\n if (utils.isFunction(parser)) {\n return parser.call(this, value, key);\n }\n\n if (utils.isRegExp(parser)) {\n return parser.exec(value);\n }\n\n throw new TypeError('parser must be boolean|regexp|function');\n }\n }\n }\n\n has(header, matcher) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));\n }\n\n return false;\n }\n\n delete(header, matcher) {\n const self = this;\n let deleted = false;\n\n function deleteHeader(_header) {\n _header = normalizeHeader(_header);\n\n if (_header) {\n const key = utils.findKey(self, _header);\n\n if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {\n delete self[key];\n\n deleted = true;\n }\n }\n }\n\n if (utils.isArray(header)) {\n header.forEach(deleteHeader);\n } else {\n deleteHeader(header);\n }\n\n return deleted;\n }\n\n clear(matcher) {\n const keys = Object.keys(this);\n let i = keys.length;\n let deleted = false;\n\n while (i--) {\n const key = keys[i];\n if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {\n delete this[key];\n deleted = true;\n }\n }\n\n return deleted;\n }\n\n normalize(format) {\n const self = this;\n const headers = {};\n\n utils.forEach(this, (value, header) => {\n const key = utils.findKey(headers, header);\n\n if (key) {\n self[key] = normalizeValue(value);\n delete self[header];\n return;\n }\n\n const normalized = format ? formatHeader(header) : String(header).trim();\n\n if (normalized !== header) {\n delete self[header];\n }\n\n self[normalized] = normalizeValue(value);\n\n headers[normalized] = true;\n });\n\n return this;\n }\n\n concat(...targets) {\n return this.constructor.concat(this, ...targets);\n }\n\n toJSON(asStrings) {\n const obj = Object.create(null);\n\n utils.forEach(this, (value, header) => {\n value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);\n });\n\n return obj;\n }\n\n [Symbol.iterator]() {\n return Object.entries(this.toJSON())[Symbol.iterator]();\n }\n\n toString() {\n return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\\n');\n }\n\n get [Symbol.toStringTag]() {\n return 'AxiosHeaders';\n }\n\n static from(thing) {\n return thing instanceof this ? thing : new this(thing);\n }\n\n static concat(first, ...targets) {\n const computed = new this(first);\n\n targets.forEach((target) => computed.set(target));\n\n return computed;\n }\n\n static accessor(header) {\n const internals = this[$internals] = (this[$internals] = {\n accessors: {}\n });\n\n const accessors = internals.accessors;\n const prototype = this.prototype;\n\n function defineAccessor(_header) {\n const lHeader = normalizeHeader(_header);\n\n if (!accessors[lHeader]) {\n buildAccessors(prototype, _header);\n accessors[lHeader] = true;\n }\n }\n\n utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);\n\n return this;\n }\n}\n\nAxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);\n\n// reserved names hotfix\nutils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {\n let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`\n return {\n get: () => value,\n set(headerValue) {\n this[mapped] = headerValue;\n }\n }\n});\n\nutils.freezeMethods(AxiosHeaders);\n\nexport default AxiosHeaders;\n","'use strict';\n\nimport utils from './../utils.js';\nimport defaults from '../defaults/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Array|Function} fns A single function or Array of functions\n * @param {?Object} response The response object\n *\n * @returns {*} The resulting transformed data\n */\nexport default function transformData(fns, response) {\n const config = this || defaults;\n const context = response || config;\n const headers = AxiosHeaders.from(context.headers);\n let data = context.data;\n\n utils.forEach(fns, function transform(fn) {\n data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);\n });\n\n headers.normalize();\n\n return data;\n}\n","'use strict';\n\nexport default function isCancel(value) {\n return !!(value && value.__CANCEL__);\n}\n","'use strict';\n\nimport AxiosError from '../core/AxiosError.js';\nimport utils from '../utils.js';\n\n/**\n * A `CanceledError` is an object that is thrown when an operation is canceled.\n *\n * @param {string=} message The message.\n * @param {Object=} config The config.\n * @param {Object=} request The request.\n *\n * @returns {CanceledError} The created error.\n */\nfunction CanceledError(message, config, request) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);\n this.name = 'CanceledError';\n}\n\nutils.inherits(CanceledError, AxiosError, {\n __CANCEL__: true\n});\n\nexport default CanceledError;\n","'use strict';\n\nimport AxiosError from './AxiosError.js';\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n *\n * @returns {object} The response.\n */\nexport default function settle(resolve, reject, response) {\n const validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(new AxiosError(\n 'Request failed with status code ' + response.status,\n [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],\n response.config,\n response.request,\n response\n ));\n }\n}\n","'use strict';\n\n/**\n * Calculate data maxRate\n * @param {Number} [samplesCount= 10]\n * @param {Number} [min= 1000]\n * @returns {Function}\n */\nfunction speedometer(samplesCount, min) {\n samplesCount = samplesCount || 10;\n const bytes = new Array(samplesCount);\n const timestamps = new Array(samplesCount);\n let head = 0;\n let tail = 0;\n let firstSampleTS;\n\n min = min !== undefined ? min : 1000;\n\n return function push(chunkLength) {\n const now = Date.now();\n\n const startedAt = timestamps[tail];\n\n if (!firstSampleTS) {\n firstSampleTS = now;\n }\n\n bytes[head] = chunkLength;\n timestamps[head] = now;\n\n let i = tail;\n let bytesCount = 0;\n\n while (i !== head) {\n bytesCount += bytes[i++];\n i = i % samplesCount;\n }\n\n head = (head + 1) % samplesCount;\n\n if (head === tail) {\n tail = (tail + 1) % samplesCount;\n }\n\n if (now - firstSampleTS < min) {\n return;\n }\n\n const passed = startedAt && now - startedAt;\n\n return passed ? Math.round(bytesCount * 1000 / passed) : undefined;\n };\n}\n\nexport default speedometer;\n","/**\n * Throttle decorator\n * @param {Function} fn\n * @param {Number} freq\n * @return {Function}\n */\nfunction throttle(fn, freq) {\n let timestamp = 0;\n let threshold = 1000 / freq;\n let lastArgs;\n let timer;\n\n const invoke = (args, now = Date.now()) => {\n timestamp = now;\n lastArgs = null;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n fn.apply(null, args);\n }\n\n const throttled = (...args) => {\n const now = Date.now();\n const passed = now - timestamp;\n if ( passed >= threshold) {\n invoke(args, now);\n } else {\n lastArgs = args;\n if (!timer) {\n timer = setTimeout(() => {\n timer = null;\n invoke(lastArgs)\n }, threshold - passed);\n }\n }\n }\n\n const flush = () => lastArgs && invoke(lastArgs);\n\n return [throttled, flush];\n}\n\nexport default throttle;\n","import speedometer from \"./speedometer.js\";\nimport throttle from \"./throttle.js\";\nimport utils from \"../utils.js\";\n\nexport const progressEventReducer = (listener, isDownloadStream, freq = 3) => {\n let bytesNotified = 0;\n const _speedometer = speedometer(50, 250);\n\n return throttle(e => {\n const loaded = e.loaded;\n const total = e.lengthComputable ? e.total : undefined;\n const progressBytes = loaded - bytesNotified;\n const rate = _speedometer(progressBytes);\n const inRange = loaded <= total;\n\n bytesNotified = loaded;\n\n const data = {\n loaded,\n total,\n progress: total ? (loaded / total) : undefined,\n bytes: progressBytes,\n rate: rate ? rate : undefined,\n estimated: rate && total && inRange ? (total - loaded) / rate : undefined,\n event: e,\n lengthComputable: total != null,\n [isDownloadStream ? 'download' : 'upload']: true\n };\n\n listener(data);\n }, freq);\n}\n\nexport const progressEventDecorator = (total, throttled) => {\n const lengthComputable = total != null;\n\n return [(loaded) => throttled[0]({\n lengthComputable,\n total,\n loaded\n }), throttled[1]];\n}\n\nexport const asyncDecorator = (fn) => (...args) => utils.asap(() => fn(...args));\n","import platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {\n url = new URL(url, platform.origin);\n\n return (\n origin.protocol === url.protocol &&\n origin.host === url.host &&\n (isMSIE || origin.port === url.port)\n );\n})(\n new URL(platform.origin),\n platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)\n) : () => true;\n","import utils from './../utils.js';\nimport platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ?\n\n // Standard browser envs support document.cookie\n {\n write(name, value, expires, path, domain, secure) {\n const cookie = [name + '=' + encodeURIComponent(value)];\n\n utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());\n\n utils.isString(path) && cookie.push('path=' + path);\n\n utils.isString(domain) && cookie.push('domain=' + domain);\n\n secure === true && cookie.push('secure');\n\n document.cookie = cookie.join('; ');\n },\n\n read(name) {\n const match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n }\n\n :\n\n // Non-standard browser env (web workers, react-native) lack needed support.\n {\n write() {},\n read() {\n return null;\n },\n remove() {}\n };\n\n","'use strict';\n\nimport isAbsoluteURL from '../helpers/isAbsoluteURL.js';\nimport combineURLs from '../helpers/combineURLs.js';\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n *\n * @returns {string} The combined full path\n */\nexport default function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n}\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n *\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nexport default function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n}\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n *\n * @returns {string} The combined URL\n */\nexport default function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/?\\/$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosHeaders from \"./AxiosHeaders.js\";\n\nconst headersToObject = (thing) => thing instanceof AxiosHeaders ? { ...thing } : thing;\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n *\n * @returns {Object} New object resulting from merging config2 to config1\n */\nexport default function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n const config = {};\n\n function getMergedValue(target, source, prop, caseless) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge.call({caseless}, target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(a, b, prop , caseless) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(a, b, prop , caseless);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a, prop , caseless);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(a, b, prop) {\n if (prop in config2) {\n return getMergedValue(a, b);\n } else if (prop in config1) {\n return getMergedValue(undefined, a);\n }\n }\n\n const mergeMap = {\n url: valueFromConfig2,\n method: valueFromConfig2,\n data: valueFromConfig2,\n baseURL: defaultToConfig2,\n transformRequest: defaultToConfig2,\n transformResponse: defaultToConfig2,\n paramsSerializer: defaultToConfig2,\n timeout: defaultToConfig2,\n timeoutMessage: defaultToConfig2,\n withCredentials: defaultToConfig2,\n withXSRFToken: defaultToConfig2,\n adapter: defaultToConfig2,\n responseType: defaultToConfig2,\n xsrfCookieName: defaultToConfig2,\n xsrfHeaderName: defaultToConfig2,\n onUploadProgress: defaultToConfig2,\n onDownloadProgress: defaultToConfig2,\n decompress: defaultToConfig2,\n maxContentLength: defaultToConfig2,\n maxBodyLength: defaultToConfig2,\n beforeRedirect: defaultToConfig2,\n transport: defaultToConfig2,\n httpAgent: defaultToConfig2,\n httpsAgent: defaultToConfig2,\n cancelToken: defaultToConfig2,\n socketPath: defaultToConfig2,\n responseEncoding: defaultToConfig2,\n validateStatus: mergeDirectKeys,\n headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true)\n };\n\n utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {\n const merge = mergeMap[prop] || mergeDeepProperties;\n const configValue = merge(config1[prop], config2[prop], prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n}\n","import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport isURLSameOrigin from \"./isURLSameOrigin.js\";\nimport cookies from \"./cookies.js\";\nimport buildFullPath from \"../core/buildFullPath.js\";\nimport mergeConfig from \"../core/mergeConfig.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport buildURL from \"./buildURL.js\";\n\nexport default (config) => {\n const newConfig = mergeConfig({}, config);\n\n let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;\n\n newConfig.headers = headers = AxiosHeaders.from(headers);\n\n newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);\n\n // HTTP basic authentication\n if (auth) {\n headers.set('Authorization', 'Basic ' +\n btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))\n );\n }\n\n let contentType;\n\n if (utils.isFormData(data)) {\n if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {\n headers.setContentType(undefined); // Let the browser set it\n } else if ((contentType = headers.getContentType()) !== false) {\n // fix semicolon duplication issue for ReactNative FormData implementation\n const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];\n headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));\n }\n }\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n\n if (platform.hasStandardBrowserEnv) {\n withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));\n\n if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {\n // Add xsrf header\n const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);\n\n if (xsrfValue) {\n headers.set(xsrfHeaderName, xsrfValue);\n }\n }\n }\n\n return newConfig;\n}\n\n","import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport composeSignals from \"../helpers/composeSignals.js\";\nimport {trackStream} from \"../helpers/trackStream.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport {progressEventReducer, progressEventDecorator, asyncDecorator} from \"../helpers/progressEventReducer.js\";\nimport resolveConfig from \"../helpers/resolveConfig.js\";\nimport settle from \"../core/settle.js\";\n\nconst isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';\nconst isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';\n\n// used only inside the fetch adapter\nconst encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?\n ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :\n async (str) => new Uint8Array(await new Response(str).arrayBuffer())\n);\n\nconst test = (fn, ...args) => {\n try {\n return !!fn(...args);\n } catch (e) {\n return false\n }\n}\n\nconst supportsRequestStream = isReadableStreamSupported && test(() => {\n let duplexAccessed = false;\n\n const hasContentType = new Request(platform.origin, {\n body: new ReadableStream(),\n method: 'POST',\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n }).headers.has('Content-Type');\n\n return duplexAccessed && !hasContentType;\n});\n\nconst DEFAULT_CHUNK_SIZE = 64 * 1024;\n\nconst supportsResponseStream = isReadableStreamSupported &&\n test(() => utils.isReadableStream(new Response('').body));\n\n\nconst resolvers = {\n stream: supportsResponseStream && ((res) => res.body)\n};\n\nisFetchSupported && (((res) => {\n ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {\n !resolvers[type] && (resolvers[type] = utils.isFunction(res[type]) ? (res) => res[type]() :\n (_, config) => {\n throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);\n })\n });\n})(new Response));\n\nconst getBodyLength = async (body) => {\n if (body == null) {\n return 0;\n }\n\n if(utils.isBlob(body)) {\n return body.size;\n }\n\n if(utils.isSpecCompliantForm(body)) {\n const _request = new Request(platform.origin, {\n method: 'POST',\n body,\n });\n return (await _request.arrayBuffer()).byteLength;\n }\n\n if(utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) {\n return body.byteLength;\n }\n\n if(utils.isURLSearchParams(body)) {\n body = body + '';\n }\n\n if(utils.isString(body)) {\n return (await encodeText(body)).byteLength;\n }\n}\n\nconst resolveBodyLength = async (headers, body) => {\n const length = utils.toFiniteNumber(headers.getContentLength());\n\n return length == null ? getBodyLength(body) : length;\n}\n\nexport default isFetchSupported && (async (config) => {\n let {\n url,\n method,\n data,\n signal,\n cancelToken,\n timeout,\n onDownloadProgress,\n onUploadProgress,\n responseType,\n headers,\n withCredentials = 'same-origin',\n fetchOptions\n } = resolveConfig(config);\n\n responseType = responseType ? (responseType + '').toLowerCase() : 'text';\n\n let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);\n\n let request;\n\n const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {\n composedSignal.unsubscribe();\n });\n\n let requestContentLength;\n\n try {\n if (\n onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&\n (requestContentLength = await resolveBodyLength(headers, data)) !== 0\n ) {\n let _request = new Request(url, {\n method: 'POST',\n body: data,\n duplex: \"half\"\n });\n\n let contentTypeHeader;\n\n if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {\n headers.setContentType(contentTypeHeader)\n }\n\n if (_request.body) {\n const [onProgress, flush] = progressEventDecorator(\n requestContentLength,\n progressEventReducer(asyncDecorator(onUploadProgress))\n );\n\n data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);\n }\n }\n\n if (!utils.isString(withCredentials)) {\n withCredentials = withCredentials ? 'include' : 'omit';\n }\n\n // Cloudflare Workers throws when credentials are defined\n // see https://github.com/cloudflare/workerd/issues/902\n const isCredentialsSupported = \"credentials\" in Request.prototype;\n request = new Request(url, {\n ...fetchOptions,\n signal: composedSignal,\n method: method.toUpperCase(),\n headers: headers.normalize().toJSON(),\n body: data,\n duplex: \"half\",\n credentials: isCredentialsSupported ? withCredentials : undefined\n });\n\n let response = await fetch(request);\n\n const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');\n\n if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {\n const options = {};\n\n ['status', 'statusText', 'headers'].forEach(prop => {\n options[prop] = response[prop];\n });\n\n const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length'));\n\n const [onProgress, flush] = onDownloadProgress && progressEventDecorator(\n responseContentLength,\n progressEventReducer(asyncDecorator(onDownloadProgress), true)\n ) || [];\n\n response = new Response(\n trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {\n flush && flush();\n unsubscribe && unsubscribe();\n }),\n options\n );\n }\n\n responseType = responseType || 'text';\n\n let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config);\n\n !isStreamResponse && unsubscribe && unsubscribe();\n\n return await new Promise((resolve, reject) => {\n settle(resolve, reject, {\n data: responseData,\n headers: AxiosHeaders.from(response.headers),\n status: response.status,\n statusText: response.statusText,\n config,\n request\n })\n })\n } catch (err) {\n unsubscribe && unsubscribe();\n\n if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {\n throw Object.assign(\n new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),\n {\n cause: err.cause || err\n }\n )\n }\n\n throw AxiosError.from(err, err && err.code, config, request);\n }\n});\n\n\n","import utils from './../utils.js';\nimport settle from './../core/settle.js';\nimport transitionalDefaults from '../defaults/transitional.js';\nimport AxiosError from '../core/AxiosError.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport parseProtocol from '../helpers/parseProtocol.js';\nimport platform from '../platform/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport {progressEventReducer} from '../helpers/progressEventReducer.js';\nimport resolveConfig from \"../helpers/resolveConfig.js\";\n\nconst isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';\n\nexport default isXHRAdapterSupported && function (config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n const _config = resolveConfig(config);\n let requestData = _config.data;\n const requestHeaders = AxiosHeaders.from(_config.headers).normalize();\n let {responseType, onUploadProgress, onDownloadProgress} = _config;\n let onCanceled;\n let uploadThrottled, downloadThrottled;\n let flushUpload, flushDownload;\n\n function done() {\n flushUpload && flushUpload(); // flush events\n flushDownload && flushDownload(); // flush events\n\n _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);\n\n _config.signal && _config.signal.removeEventListener('abort', onCanceled);\n }\n\n let request = new XMLHttpRequest();\n\n request.open(_config.method.toUpperCase(), _config.url, true);\n\n // Set the request timeout in MS\n request.timeout = _config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n const responseHeaders = AxiosHeaders.from(\n 'getAllResponseHeaders' in request && request.getAllResponseHeaders()\n );\n const responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n const response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config,\n request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';\n const transitional = _config.transitional || transitionalDefaults;\n if (_config.timeoutErrorMessage) {\n timeoutErrorMessage = _config.timeoutErrorMessage;\n }\n reject(new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n config,\n request));\n\n // Clean up request\n request = null;\n };\n\n // Remove Content-Type if data is undefined\n requestData === undefined && requestHeaders.setContentType(null);\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {\n request.setRequestHeader(key, val);\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(_config.withCredentials)) {\n request.withCredentials = !!_config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = _config.responseType;\n }\n\n // Handle progress if needed\n if (onDownloadProgress) {\n ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));\n request.addEventListener('progress', downloadThrottled);\n }\n\n // Not all browsers support upload events\n if (onUploadProgress && request.upload) {\n ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));\n\n request.upload.addEventListener('progress', uploadThrottled);\n\n request.upload.addEventListener('loadend', flushUpload);\n }\n\n if (_config.cancelToken || _config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = cancel => {\n if (!request) {\n return;\n }\n reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);\n request.abort();\n request = null;\n };\n\n _config.cancelToken && _config.cancelToken.subscribe(onCanceled);\n if (_config.signal) {\n _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n const protocol = parseProtocol(_config.url);\n\n if (protocol && platform.protocols.indexOf(protocol) === -1) {\n reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));\n return;\n }\n\n\n // Send the request\n request.send(requestData || null);\n });\n}\n","'use strict';\n\nexport default function parseProtocol(url) {\n const match = /^([-+\\w]{1,25})(:?\\/\\/|:)/.exec(url);\n return match && match[1] || '';\n}\n","import CanceledError from \"../cancel/CanceledError.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport utils from '../utils.js';\n\nconst composeSignals = (signals, timeout) => {\n const {length} = (signals = signals ? signals.filter(Boolean) : []);\n\n if (timeout || length) {\n let controller = new AbortController();\n\n let aborted;\n\n const onabort = function (reason) {\n if (!aborted) {\n aborted = true;\n unsubscribe();\n const err = reason instanceof Error ? reason : this.reason;\n controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));\n }\n }\n\n let timer = timeout && setTimeout(() => {\n timer = null;\n onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT))\n }, timeout)\n\n const unsubscribe = () => {\n if (signals) {\n timer && clearTimeout(timer);\n timer = null;\n signals.forEach(signal => {\n signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);\n });\n signals = null;\n }\n }\n\n signals.forEach((signal) => signal.addEventListener('abort', onabort));\n\n const {signal} = controller;\n\n signal.unsubscribe = () => utils.asap(unsubscribe);\n\n return signal;\n }\n}\n\nexport default composeSignals;\n","\nexport const streamChunk = function* (chunk, chunkSize) {\n let len = chunk.byteLength;\n\n if (!chunkSize || len < chunkSize) {\n yield chunk;\n return;\n }\n\n let pos = 0;\n let end;\n\n while (pos < len) {\n end = pos + chunkSize;\n yield chunk.slice(pos, end);\n pos = end;\n }\n}\n\nexport const readBytes = async function* (iterable, chunkSize) {\n for await (const chunk of readStream(iterable)) {\n yield* streamChunk(chunk, chunkSize);\n }\n}\n\nconst readStream = async function* (stream) {\n if (stream[Symbol.asyncIterator]) {\n yield* stream;\n return;\n }\n\n const reader = stream.getReader();\n try {\n for (;;) {\n const {done, value} = await reader.read();\n if (done) {\n break;\n }\n yield value;\n }\n } finally {\n await reader.cancel();\n }\n}\n\nexport const trackStream = (stream, chunkSize, onProgress, onFinish) => {\n const iterator = readBytes(stream, chunkSize);\n\n let bytes = 0;\n let done;\n let _onFinish = (e) => {\n if (!done) {\n done = true;\n onFinish && onFinish(e);\n }\n }\n\n return new ReadableStream({\n async pull(controller) {\n try {\n const {done, value} = await iterator.next();\n\n if (done) {\n _onFinish();\n controller.close();\n return;\n }\n\n let len = value.byteLength;\n if (onProgress) {\n let loadedBytes = bytes += len;\n onProgress(loadedBytes);\n }\n controller.enqueue(new Uint8Array(value));\n } catch (err) {\n _onFinish(err);\n throw err;\n }\n },\n cancel(reason) {\n _onFinish(reason);\n return iterator.return();\n }\n }, {\n highWaterMark: 2\n })\n}\n","import utils from '../utils.js';\nimport httpAdapter from './http.js';\nimport xhrAdapter from './xhr.js';\nimport fetchAdapter from './fetch.js';\nimport AxiosError from \"../core/AxiosError.js\";\n\nconst knownAdapters = {\n http: httpAdapter,\n xhr: xhrAdapter,\n fetch: fetchAdapter\n}\n\nutils.forEach(knownAdapters, (fn, value) => {\n if (fn) {\n try {\n Object.defineProperty(fn, 'name', {value});\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n Object.defineProperty(fn, 'adapterName', {value});\n }\n});\n\nconst renderReason = (reason) => `- ${reason}`;\n\nconst isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false;\n\nexport default {\n getAdapter: (adapters) => {\n adapters = utils.isArray(adapters) ? adapters : [adapters];\n\n const {length} = adapters;\n let nameOrAdapter;\n let adapter;\n\n const rejectedReasons = {};\n\n for (let i = 0; i < length; i++) {\n nameOrAdapter = adapters[i];\n let id;\n\n adapter = nameOrAdapter;\n\n if (!isResolvedHandle(nameOrAdapter)) {\n adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];\n\n if (adapter === undefined) {\n throw new AxiosError(`Unknown adapter '${id}'`);\n }\n }\n\n if (adapter) {\n break;\n }\n\n rejectedReasons[id || '#' + i] = adapter;\n }\n\n if (!adapter) {\n\n const reasons = Object.entries(rejectedReasons)\n .map(([id, state]) => `adapter ${id} ` +\n (state === false ? 'is not supported by the environment' : 'is not available in the build')\n );\n\n let s = length ?\n (reasons.length > 1 ? 'since :\\n' + reasons.map(renderReason).join('\\n') : ' ' + renderReason(reasons[0])) :\n 'as no adapter specified';\n\n throw new AxiosError(\n `There is no suitable adapter to dispatch the request ` + s,\n 'ERR_NOT_SUPPORT'\n );\n }\n\n return adapter;\n },\n adapters: knownAdapters\n}\n","// eslint-disable-next-line strict\nexport default null;\n","'use strict';\n\nimport transformData from './transformData.js';\nimport isCancel from '../cancel/isCancel.js';\nimport defaults from '../defaults/index.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport adapters from \"../adapters/adapters.js\";\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n *\n * @param {Object} config The config that is to be used for the request\n *\n * @returns {void}\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new CanceledError(null, config);\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n *\n * @returns {Promise} The Promise to be fulfilled\n */\nexport default function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n config.headers = AxiosHeaders.from(config.headers);\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.transformRequest\n );\n\n if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {\n config.headers.setContentType('application/x-www-form-urlencoded', false);\n }\n\n const adapter = adapters.getAdapter(config.adapter || defaults.adapter);\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n config.transformResponse,\n response\n );\n\n response.headers = AxiosHeaders.from(response.headers);\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n config.transformResponse,\n reason.response\n );\n reason.response.headers = AxiosHeaders.from(reason.response.headers);\n }\n }\n\n return Promise.reject(reason);\n });\n}\n","export const VERSION = \"1.7.9\";","'use strict';\n\nimport {VERSION} from '../env/data.js';\nimport AxiosError from '../core/AxiosError.js';\n\nconst validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nconst deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n *\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n *\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return (value, opt, opts) => {\n if (validator === false) {\n throw new AxiosError(\n formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),\n AxiosError.ERR_DEPRECATED\n );\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\nvalidators.spelling = function spelling(correctSpelling) {\n return (value, opt) => {\n // eslint-disable-next-line no-console\n console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);\n return true;\n }\n};\n\n/**\n * Assert object's properties type\n *\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n *\n * @returns {object}\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);\n }\n const keys = Object.keys(options);\n let i = keys.length;\n while (i-- > 0) {\n const opt = keys[i];\n const validator = schema[opt];\n if (validator) {\n const value = options[opt];\n const result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);\n }\n }\n}\n\nexport default {\n assertOptions,\n validators\n};\n","'use strict';\n\nimport utils from './../utils.js';\nimport buildURL from '../helpers/buildURL.js';\nimport InterceptorManager from './InterceptorManager.js';\nimport dispatchRequest from './dispatchRequest.js';\nimport mergeConfig from './mergeConfig.js';\nimport buildFullPath from './buildFullPath.js';\nimport validator from '../helpers/validator.js';\nimport AxiosHeaders from './AxiosHeaders.js';\n\nconst validators = validator.validators;\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n *\n * @return {Axios} A new instance of Axios\n */\nclass Axios {\n constructor(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n }\n\n /**\n * Dispatch a request\n *\n * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)\n * @param {?Object} config\n *\n * @returns {Promise} The Promise to be fulfilled\n */\n async request(configOrUrl, config) {\n try {\n return await this._request(configOrUrl, config);\n } catch (err) {\n if (err instanceof Error) {\n let dummy = {};\n\n Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());\n\n // slice off the Error: ... line\n const stack = dummy.stack ? dummy.stack.replace(/^.+\\n/, '') : '';\n try {\n if (!err.stack) {\n err.stack = stack;\n // match without the 2 top stack lines\n } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\\n.+\\n/, ''))) {\n err.stack += '\\n' + stack\n }\n } catch (e) {\n // ignore the case where \"stack\" is an un-writable property\n }\n }\n\n throw err;\n }\n }\n\n _request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n const {transitional, paramsSerializer, headers} = config;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n if (paramsSerializer != null) {\n if (utils.isFunction(paramsSerializer)) {\n config.paramsSerializer = {\n serialize: paramsSerializer\n }\n } else {\n validator.assertOptions(paramsSerializer, {\n encode: validators.function,\n serialize: validators.function\n }, true);\n }\n }\n\n validator.assertOptions(config, {\n baseUrl: validators.spelling('baseURL'),\n withXsrfToken: validators.spelling('withXSRFToken')\n }, true);\n\n // Set config.method\n config.method = (config.method || this.defaults.method || 'get').toLowerCase();\n\n // Flatten headers\n let contextHeaders = headers && utils.merge(\n headers.common,\n headers[config.method]\n );\n\n headers && utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n (method) => {\n delete headers[method];\n }\n );\n\n config.headers = AxiosHeaders.concat(contextHeaders, headers);\n\n // filter out skipped interceptors\n const requestInterceptorChain = [];\n let synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n const responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n let promise;\n let i = 0;\n let len;\n\n if (!synchronousRequestInterceptors) {\n const chain = [dispatchRequest.bind(this), undefined];\n chain.unshift.apply(chain, requestInterceptorChain);\n chain.push.apply(chain, responseInterceptorChain);\n len = chain.length;\n\n promise = Promise.resolve(config);\n\n while (i < len) {\n promise = promise.then(chain[i++], chain[i++]);\n }\n\n return promise;\n }\n\n len = requestInterceptorChain.length;\n\n let newConfig = config;\n\n i = 0;\n\n while (i < len) {\n const onFulfilled = requestInterceptorChain[i++];\n const onRejected = requestInterceptorChain[i++];\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected.call(this, error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest.call(this, newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n i = 0;\n len = responseInterceptorChain.length;\n\n while (i < len) {\n promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);\n }\n\n return promise;\n }\n\n getUri(config) {\n config = mergeConfig(this.defaults, config);\n const fullPath = buildFullPath(config.baseURL, config.url);\n return buildURL(fullPath, config.params, config.paramsSerializer);\n }\n}\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n\n function generateHTTPMethod(isForm) {\n return function httpMethod(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n headers: isForm ? {\n 'Content-Type': 'multipart/form-data'\n } : {},\n url,\n data\n }));\n };\n }\n\n Axios.prototype[method] = generateHTTPMethod();\n\n Axios.prototype[method + 'Form'] = generateHTTPMethod(true);\n});\n\nexport default Axios;\n","'use strict';\n\nimport CanceledError from './CanceledError.js';\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @param {Function} executor The executor function.\n *\n * @returns {CancelToken}\n */\nclass CancelToken {\n constructor(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n let resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n const token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(cancel => {\n if (!token._listeners) return;\n\n let i = token._listeners.length;\n\n while (i-- > 0) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = onfulfilled => {\n let _resolve;\n // eslint-disable-next-line func-names\n const promise = new Promise(resolve => {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message, config, request) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new CanceledError(message, config, request);\n resolvePromise(token.reason);\n });\n }\n\n /**\n * Throws a `CanceledError` if cancellation has been requested.\n */\n throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n }\n\n /**\n * Subscribe to the cancel signal\n */\n\n subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n }\n\n /**\n * Unsubscribe from the cancel signal\n */\n\n unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n const index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n }\n\n toAbortSignal() {\n const controller = new AbortController();\n\n const abort = (err) => {\n controller.abort(err);\n };\n\n this.subscribe(abort);\n\n controller.signal.unsubscribe = () => this.unsubscribe(abort);\n\n return controller.signal;\n }\n\n /**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\n static source() {\n let cancel;\n const token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token,\n cancel\n };\n }\n}\n\nexport default CancelToken;\n","const HttpStatusCode = {\n Continue: 100,\n SwitchingProtocols: 101,\n Processing: 102,\n EarlyHints: 103,\n Ok: 200,\n Created: 201,\n Accepted: 202,\n NonAuthoritativeInformation: 203,\n NoContent: 204,\n ResetContent: 205,\n PartialContent: 206,\n MultiStatus: 207,\n AlreadyReported: 208,\n ImUsed: 226,\n MultipleChoices: 300,\n MovedPermanently: 301,\n Found: 302,\n SeeOther: 303,\n NotModified: 304,\n UseProxy: 305,\n Unused: 306,\n TemporaryRedirect: 307,\n PermanentRedirect: 308,\n BadRequest: 400,\n Unauthorized: 401,\n PaymentRequired: 402,\n Forbidden: 403,\n NotFound: 404,\n MethodNotAllowed: 405,\n NotAcceptable: 406,\n ProxyAuthenticationRequired: 407,\n RequestTimeout: 408,\n Conflict: 409,\n Gone: 410,\n LengthRequired: 411,\n PreconditionFailed: 412,\n PayloadTooLarge: 413,\n UriTooLong: 414,\n UnsupportedMediaType: 415,\n RangeNotSatisfiable: 416,\n ExpectationFailed: 417,\n ImATeapot: 418,\n MisdirectedRequest: 421,\n UnprocessableEntity: 422,\n Locked: 423,\n FailedDependency: 424,\n TooEarly: 425,\n UpgradeRequired: 426,\n PreconditionRequired: 428,\n TooManyRequests: 429,\n RequestHeaderFieldsTooLarge: 431,\n UnavailableForLegalReasons: 451,\n InternalServerError: 500,\n NotImplemented: 501,\n BadGateway: 502,\n ServiceUnavailable: 503,\n GatewayTimeout: 504,\n HttpVersionNotSupported: 505,\n VariantAlsoNegotiates: 506,\n InsufficientStorage: 507,\n LoopDetected: 508,\n NotExtended: 510,\n NetworkAuthenticationRequired: 511,\n};\n\nObject.entries(HttpStatusCode).forEach(([key, value]) => {\n HttpStatusCode[value] = key;\n});\n\nexport default HttpStatusCode;\n","'use strict';\n\nimport utils from './utils.js';\nimport bind from './helpers/bind.js';\nimport Axios from './core/Axios.js';\nimport mergeConfig from './core/mergeConfig.js';\nimport defaults from './defaults/index.js';\nimport formDataToJSON from './helpers/formDataToJSON.js';\nimport CanceledError from './cancel/CanceledError.js';\nimport CancelToken from './cancel/CancelToken.js';\nimport isCancel from './cancel/isCancel.js';\nimport {VERSION} from './env/data.js';\nimport toFormData from './helpers/toFormData.js';\nimport AxiosError from './core/AxiosError.js';\nimport spread from './helpers/spread.js';\nimport isAxiosError from './helpers/isAxiosError.js';\nimport AxiosHeaders from \"./core/AxiosHeaders.js\";\nimport adapters from './adapters/adapters.js';\nimport HttpStatusCode from './helpers/HttpStatusCode.js';\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n *\n * @returns {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n const context = new Axios(defaultConfig);\n const instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});\n\n // Copy context to instance\n utils.extend(instance, context, null, {allOwnKeys: true});\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nconst axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.CanceledError = CanceledError;\naxios.CancelToken = CancelToken;\naxios.isCancel = isCancel;\naxios.VERSION = VERSION;\naxios.toFormData = toFormData;\n\n// Expose AxiosError class\naxios.AxiosError = AxiosError;\n\n// alias for CanceledError for backward compatibility\naxios.Cancel = axios.CanceledError;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\n\naxios.spread = spread;\n\n// Expose isAxiosError\naxios.isAxiosError = isAxiosError;\n\n// Expose mergeConfig\naxios.mergeConfig = mergeConfig;\n\naxios.AxiosHeaders = AxiosHeaders;\n\naxios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);\n\naxios.getAdapter = adapters.getAdapter;\n\naxios.HttpStatusCode = HttpStatusCode;\n\naxios.default = axios;\n\n// this module should only have a default export\nexport default axios\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n *\n * @returns {Function}\n */\nexport default function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n *\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nexport default function isAxiosError(payload) {\n return utils.isObject(payload) && (payload.isAxiosError === true);\n}\n"],"names":["bind","fn","thisArg","apply","arguments","cache","toString","Object","prototype","getPrototypeOf","kindOf","create","thing","str","call","slice","toLowerCase","kindOfTest","type","typeOfTest","_typeof","isArray","Array","isUndefined","isArrayBuffer","isString","isFunction","isNumber","isObject","isPlainObject","val","Symbol","toStringTag","iterator","isDate","isFile","isBlob","isFileList","isURLSearchParams","_map2","_slicedToArray","map","isReadableStream","isRequest","isResponse","isHeaders","forEach","obj","i","l","_ref","length","undefined","_ref$allOwnKeys","allOwnKeys","key","keys","getOwnPropertyNames","len","findKey","_key","_global","globalThis","self","window","global","isContextDefined","context","TypedArray","isTypedArray","Uint8Array","isHTMLForm","hasOwnProperty","_ref4","prop","isRegExp","reduceDescriptors","reducer","descriptors","getOwnPropertyDescriptors","reducedDescriptors","descriptor","name","ret","defineProperties","ALPHA","DIGIT","ALPHABET","ALPHA_DIGIT","toUpperCase","setImmediateSupported","postMessageSupported","token","callbacks","isAsyncFn","_setImmediate","setImmediate","postMessage","concat","Math","random","addEventListener","_ref5","source","data","shift","cb","push","setTimeout","asap","queueMicrotask","process","nextTick","utils$1","isBuffer","constructor","isFormData","kind","FormData","append","isArrayBufferView","ArrayBuffer","isView","buffer","isBoolean","isStream","pipe","merge","_ref2","this","caseless","result","assignValue","targetKey","extend","a","b","_ref3","trim","replace","stripBOM","content","charCodeAt","inherits","superConstructor","props","defineProperty","value","assign","toFlatObject","sourceObj","destObj","filter","propFilter","merged","endsWith","searchString","position","String","lastIndex","indexOf","toArray","arr","forEachEntry","next","done","pair","matchAll","regExp","matches","exec","hasOwnProp","freezeMethods","enumerable","writable","set","Error","toObjectSet","arrayOrString","delimiter","define","split","toCamelCase","m","p1","p2","noop","toFiniteNumber","defaultValue","Number","isFinite","generateString","size","alphabet","isSpecCompliantForm","toJSONObject","stack","visit","target","reducedValue","isThenable","then","AxiosError","message","code","config","request","response","captureStackTrace","status","utils","toJSON","description","number","fileName","lineNumber","columnNumber","from","error","customProps","axiosError","cause","isVisitable","removeBrackets","renderKey","path","dots","join","predicates","test","toFormData","formData","options","TypeError","metaTokens","indexes","option","visitor","defaultVisitor","useBlob","Blob","convertValue","toISOString","Buffer","JSON","stringify","some","isFlatArray","el","index","exposedHelpers","build","pop","encode","charMap","encodeURIComponent","match","AxiosURLSearchParams","params","_pairs","buildURL","url","_encode","serialize","serializedParams","serializeFn","hashmarkIndex","encoder","InterceptorManager$1","InterceptorManager","_classCallCheck","handlers","_createClass","fulfilled","rejected","synchronous","runWhen","id","h","transitionalDefaults","silentJSONParsing","forcedJSONParsing","clarifyTimeoutError","platform$1","isBrowser","classes","URLSearchParams","protocols","hasBrowserEnv","document","_navigator","navigator","hasStandardBrowserEnv","product","hasStandardBrowserWebWorkerEnv","WorkerGlobalScope","importScripts","origin","location","href","_objectSpread","platform","formDataToJSON","buildPath","isNumericKey","isLast","arrayToObject","entries","parsePropPath","defaults","transitional","adapter","transformRequest","headers","contentType","getContentType","hasJSONContentType","isObjectPayload","setContentType","helpers","isNode","toURLEncodedForm","formSerializer","_FormData","env","rawValue","parser","parse","e","stringifySafely","transformResponse","JSONRequested","responseType","strictJSONParsing","ERR_BAD_RESPONSE","timeout","xsrfCookieName","xsrfHeaderName","maxContentLength","maxBodyLength","validateStatus","common","Accept","method","defaults$1","ignoreDuplicateOf","$internals","normalizeHeader","header","normalizeValue","matchHeaderValue","isHeaderNameFilter","AxiosHeaders","_Symbol$iterator","_Symbol$toStringTag","valueOrRewrite","rewrite","setHeader","_value","_header","_rewrite","lHeader","setHeaders","rawHeaders","parsed","line","substring","parseHeaders","_step","_iterator","_createForOfIteratorHelper","s","n","_step$value","err","f","tokens","tokensRE","parseTokens","matcher","deleted","deleteHeader","format","normalized","w","char","formatHeader","_this$constructor","_len","targets","asStrings","get","first","computed","_len2","_key2","accessors","defineAccessor","accessorName","methodName","arg1","arg2","arg3","configurable","buildAccessors","accessor","mapped","headerValue","AxiosHeaders$1","transformData","fns","normalize","isCancel","__CANCEL__","CanceledError","ERR_CANCELED","settle","resolve","reject","ERR_BAD_REQUEST","floor","speedometer","samplesCount","min","firstSampleTS","bytes","timestamps","head","tail","chunkLength","now","Date","startedAt","bytesCount","passed","round","throttle","freq","lastArgs","timer","timestamp","threshold","invoke","args","clearTimeout","progressEventReducer","listener","isDownloadStream","bytesNotified","_speedometer","loaded","total","lengthComputable","progressBytes","rate","_defineProperty","progress","estimated","event","progressEventDecorator","throttled","asyncDecorator","isMSIE","URL","protocol","host","port","userAgent","write","expires","domain","secure","cookie","toGMTString","read","RegExp","decodeURIComponent","remove","buildFullPath","baseURL","requestedURL","relativeURL","combineURLs","headersToObject","mergeConfig","config1","config2","getMergedValue","mergeDeepProperties","valueFromConfig2","defaultToConfig2","mergeDirectKeys","mergeMap","paramsSerializer","timeoutMessage","withCredentials","withXSRFToken","onUploadProgress","onDownloadProgress","decompress","beforeRedirect","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding","configValue","res","resolveConfig","newConfig","auth","btoa","username","password","unescape","Boolean","_toConsumableArray","isURLSameOrigin","xsrfValue","cookies","xhrAdapter","XMLHttpRequest","Promise","onCanceled","uploadThrottled","downloadThrottled","flushUpload","flushDownload","_config","requestData","requestHeaders","unsubscribe","signal","removeEventListener","onloadend","responseHeaders","getAllResponseHeaders","responseText","statusText","open","onreadystatechange","readyState","responseURL","onabort","ECONNABORTED","onerror","ERR_NETWORK","ontimeout","timeoutErrorMessage","ETIMEDOUT","setRequestHeader","_progressEventReducer2","upload","_progressEventReducer4","cancel","abort","subscribe","aborted","send","composeSignals$1","signals","controller","AbortController","reason","streamChunk","_regeneratorRuntime","mark","chunk","chunkSize","pos","end","wrap","_context","prev","byteLength","abrupt","stop","readBytes","_wrapAsyncGenerator","_callee","iterable","_iteratorAbruptCompletion","_didIteratorError","_iteratorError","_context2","_asyncIterator","readStream","_awaitAsyncGenerator","sent","delegateYield","_asyncGeneratorDelegate","t1","finish","_x","_x2","_callee2","stream","reader","_yield$_awaitAsyncGen","_context3","asyncIterator","getReader","_x3","trackStream","onProgress","onFinish","_onFinish","ReadableStream","pull","_asyncToGenerator","_callee3","_yield$iterator$next","_done","loadedBytes","_context4","close","enqueue","t0","highWaterMark","isFetchSupported","fetch","Request","Response","isReadableStreamSupported","encodeText","TextEncoder","arrayBuffer","supportsRequestStream","duplexAccessed","hasContentType","body","duplex","has","supportsResponseStream","resolvers","_","ERR_NOT_SUPPORT","getBodyLength","_request","resolveBodyLength","getContentLength","_x4","_callee4","_resolveConfig","_resolveConfig$withCr","fetchOptions","composedSignal","requestContentLength","contentTypeHeader","_progressEventDecorat","_progressEventDecorat2","flush","isCredentialsSupported","isStreamResponse","responseContentLength","_ref6","_onProgress","_flush","responseData","composeSignals","toAbortSignal","credentials","t2","_x5","knownAdapters","http","xhr","fetchAdapter","renderReason","isResolvedHandle","adapters","nameOrAdapter","rejectedReasons","reasons","state","throwIfCancellationRequested","throwIfRequested","dispatchRequest","VERSION","validators","deprecatedWarnings","validators$1","validator","version","formatMessage","opt","desc","opts","ERR_DEPRECATED","console","warn","spelling","correctSpelling","assertOptions","schema","allowUnknown","ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","Axios","instanceConfig","interceptors","_request2","configOrUrl","dummy","baseUrl","withXsrfToken","contextHeaders","requestInterceptorChain","synchronousRequestInterceptors","interceptor","unshift","promise","responseInterceptorChain","chain","onFulfilled","onRejected","generateHTTPMethod","isForm","Axios$1","CancelToken","executor","resolvePromise","_listeners","onfulfilled","_resolve","splice","_this","c","CancelToken$1","HttpStatusCode","Continue","SwitchingProtocols","Processing","EarlyHints","Ok","Created","Accepted","NonAuthoritativeInformation","NoContent","ResetContent","PartialContent","MultiStatus","AlreadyReported","ImUsed","MultipleChoices","MovedPermanently","Found","SeeOther","NotModified","UseProxy","Unused","TemporaryRedirect","PermanentRedirect","BadRequest","Unauthorized","PaymentRequired","Forbidden","NotFound","MethodNotAllowed","NotAcceptable","ProxyAuthenticationRequired","RequestTimeout","Conflict","Gone","LengthRequired","PreconditionFailed","PayloadTooLarge","UriTooLong","UnsupportedMediaType","RangeNotSatisfiable","ExpectationFailed","ImATeapot","MisdirectedRequest","UnprocessableEntity","Locked","FailedDependency","TooEarly","UpgradeRequired","PreconditionRequired","TooManyRequests","RequestHeaderFieldsTooLarge","UnavailableForLegalReasons","InternalServerError","NotImplemented","BadGateway","ServiceUnavailable","GatewayTimeout","HttpVersionNotSupported","VariantAlsoNegotiates","InsufficientStorage","LoopDetected","NotExtended","NetworkAuthenticationRequired","HttpStatusCode$1","axios","createInstance","defaultConfig","instance","Cancel","all","promises","spread","callback","isAxiosError","payload","formToJSON","getAdapter"],"mappings":"w5XAEe,SAASA,EAAKC,EAAIC,GAC/B,OAAO,WACL,OAAOD,EAAGE,MAAMD,EAASE,WAE7B,mSCAA,IAGgBC,EAHTC,EAAYC,OAAOC,UAAnBF,SACAG,EAAkBF,OAAlBE,eAEDC,GAAUL,EAGbE,OAAOI,OAAO,MAHQ,SAAAC,GACrB,IAAMC,EAAMP,EAASQ,KAAKF,GAC1B,OAAOP,EAAMQ,KAASR,EAAMQ,GAAOA,EAAIE,MAAM,GAAI,GAAGC,iBAGlDC,EAAa,SAACC,GAElB,OADAA,EAAOA,EAAKF,cACL,SAACJ,GAAK,OAAKF,EAAOE,KAAWM,CAAI,CAC1C,EAEMC,EAAa,SAAAD,GAAI,OAAI,SAAAN,GAAK,OAAIQ,EAAOR,KAAUM,CAAI,CAAA,EASlDG,EAAWC,MAAXD,QASDE,EAAcJ,EAAW,aAqB/B,IAAMK,EAAgBP,EAAW,eA2BjC,IAAMQ,EAAWN,EAAW,UAQtBO,EAAaP,EAAW,YASxBQ,EAAWR,EAAW,UAStBS,EAAW,SAAChB,GAAK,OAAe,OAAVA,GAAmC,WAAjBQ,EAAOR,EAAkB,EAiBjEiB,EAAgB,SAACC,GACrB,GAAoB,WAAhBpB,EAAOoB,GACT,OAAO,EAGT,IAAMtB,EAAYC,EAAeqB,GACjC,QAAsB,OAAdtB,GAAsBA,IAAcD,OAAOC,WAAkD,OAArCD,OAAOE,eAAeD,IAA0BuB,OAAOC,eAAeF,GAAUC,OAAOE,YAAYH,EACrK,EASMI,EAASjB,EAAW,QASpBkB,EAASlB,EAAW,QASpBmB,EAASnB,EAAW,QASpBoB,EAAapB,EAAW,YAsCxBqB,EAAoBrB,EAAW,mBAE4FsB,EAAAC,EAApE,CAAC,iBAAkB,UAAW,WAAY,WAAWC,IAAIxB,GAAW,GAA1HyB,EAAgBH,EAAA,GAAEI,EAASJ,EAAA,GAAEK,EAAUL,EAAA,GAAEM,EAASN,EAAA,GA2BzD,SAASO,EAAQC,EAAK9C,GAA+B,IAM/C+C,EACAC,EAP+CC,EAAA9C,UAAA+C,OAAA,QAAAC,IAAAhD,UAAA,GAAAA,UAAA,GAAJ,CAAE,EAAAiD,EAAAH,EAAxBI,WAAAA,OAAa,IAAHD,GAAQA,EAE3C,GAAIN,QAaJ,GALmB,WAAf3B,EAAO2B,KAETA,EAAM,CAACA,IAGL1B,EAAQ0B,GAEV,IAAKC,EAAI,EAAGC,EAAIF,EAAII,OAAQH,EAAIC,EAAGD,IACjC/C,EAAGa,KAAK,KAAMiC,EAAIC,GAAIA,EAAGD,OAEtB,CAEL,IAEIQ,EAFEC,EAAOF,EAAa/C,OAAOkD,oBAAoBV,GAAOxC,OAAOiD,KAAKT,GAClEW,EAAMF,EAAKL,OAGjB,IAAKH,EAAI,EAAGA,EAAIU,EAAKV,IACnBO,EAAMC,EAAKR,GACX/C,EAAGa,KAAK,KAAMiC,EAAIQ,GAAMA,EAAKR,EAEjC,CACF,CAEA,SAASY,EAAQZ,EAAKQ,GACpBA,EAAMA,EAAIvC,cAIV,IAHA,IAEI4C,EAFEJ,EAAOjD,OAAOiD,KAAKT,GACrBC,EAAIQ,EAAKL,OAENH,KAAM,GAEX,GAAIO,KADJK,EAAOJ,EAAKR,IACKhC,cACf,OAAO4C,EAGX,OAAO,IACT,CAEA,IAAMC,EAEsB,oBAAfC,WAAmCA,WACvB,oBAATC,KAAuBA,KAA0B,oBAAXC,OAAyBA,OAASC,OAGlFC,EAAmB,SAACC,GAAO,OAAM5C,EAAY4C,IAAYA,IAAYN,CAAO,EAoDlF,IA8HsBO,GAAhBC,IAAgBD,GAKG,oBAAfE,YAA8B7D,EAAe6D,YAH9C,SAAA1D,GACL,OAAOwD,IAAcxD,aAAiBwD,KA6CpCG,GAAatD,EAAW,mBAWxBuD,GAAkB,SAAAC,GAAA,IAAED,EAAmEjE,OAAOC,UAA1EgE,eAAc,OAAM,SAACzB,EAAK2B,GAAI,OAAKF,EAAe1D,KAAKiC,EAAK2B,EAAK,CAAA,CAAnE,GASlBC,GAAW1D,EAAW,UAEtB2D,GAAoB,SAAC7B,EAAK8B,GAC9B,IAAMC,EAAcvE,OAAOwE,0BAA0BhC,GAC/CiC,EAAqB,CAAA,EAE3BlC,EAAQgC,GAAa,SAACG,EAAYC,GAChC,IAAIC,GAC2C,KAA1CA,EAAMN,EAAQI,EAAYC,EAAMnC,MACnCiC,EAAmBE,GAAQC,GAAOF,EAEtC,IAEA1E,OAAO6E,iBAAiBrC,EAAKiC,EAC/B,EAqDMK,GAAQ,6BAERC,GAAQ,aAERC,GAAW,CACfD,MAAAA,GACAD,MAAAA,GACAG,YAAaH,GAAQA,GAAMI,cAAgBH,IAwB7C,IAuCwBI,GAAuBC,GAKbC,GAAOC,GAbnCC,GAAY7E,EAAW,iBAQvB8E,IAAkBL,GAkBE,mBAAjBM,aAlBsCL,GAmB7CjE,EAAWmC,EAAQoC,aAlBfP,GACKM,aAGFL,IAAyBC,GAW/BM,SAAAA,OAAWC,KAAKC,UAXsBP,GAWV,GAV3BhC,EAAQwC,iBAAiB,WAAW,SAAAC,GAAoB,IAAlBC,EAAMD,EAANC,OAAQC,EAAIF,EAAJE,KACxCD,IAAW1C,GAAW2C,IAASZ,IACjCC,GAAU1C,QAAU0C,GAAUY,OAAVZ,EAEvB,IAAE,GAEI,SAACa,GACNb,GAAUc,KAAKD,GACf7C,EAAQoC,YAAYL,GAAO,OAEI,SAACc,GAAE,OAAKE,WAAWF,EAAG,GAMrDG,GAAiC,oBAAnBC,eAClBA,eAAe9G,KAAK6D,GAAgC,oBAAZkD,SAA2BA,QAAQC,UAAYjB,GAI1EkB,GAAA,CACb5F,QAAAA,EACAG,cAAAA,EACA0F,SAlpBF,SAAkBpF,GAChB,OAAe,OAARA,IAAiBP,EAAYO,IAA4B,OAApBA,EAAIqF,cAAyB5F,EAAYO,EAAIqF,cACpFzF,EAAWI,EAAIqF,YAAYD,WAAapF,EAAIqF,YAAYD,SAASpF,EACxE,EAgpBEsF,WApgBiB,SAACxG,GAClB,IAAIyG,EACJ,OAAOzG,IACgB,mBAAb0G,UAA2B1G,aAAiB0G,UAClD5F,EAAWd,EAAM2G,UACY,cAA1BF,EAAO3G,EAAOE,KAEL,WAATyG,GAAqB3F,EAAWd,EAAMN,WAAkC,sBAArBM,EAAMN,YAIlE,EA0fEkH,kBA9nBF,SAA2B1F,GAOzB,MAL4B,oBAAhB2F,aAAiCA,YAAYC,OAC9CD,YAAYC,OAAO5F,GAElBA,GAASA,EAAI6F,QAAYnG,EAAcM,EAAI6F,OAGzD,EAunBElG,SAAAA,EACAE,SAAAA,EACAiG,UA9kBgB,SAAAhH,GAAK,OAAc,IAAVA,IAA4B,IAAVA,CAAe,EA+kB1DgB,SAAAA,EACAC,cAAAA,EACAa,iBAAAA,EACAC,UAAAA,EACAC,WAAAA,EACAC,UAAAA,EACAtB,YAAAA,EACAW,OAAAA,EACAC,OAAAA,EACAC,OAAAA,EACAuC,SAAAA,GACAjD,WAAAA,EACAmG,SA9hBe,SAAC/F,GAAG,OAAKF,EAASE,IAAQJ,EAAWI,EAAIgG,KAAK,EA+hB7DxF,kBAAAA,EACA+B,aAAAA,GACAhC,WAAAA,EACAS,QAAAA,EACAiF,MAhaF,SAASA,IAgBP,IAfA,IAAAC,EAAmB9D,EAAiB+D,OAASA,MAAQ,CAAE,EAAhDC,EAAQF,EAARE,SACDC,EAAS,CAAA,EACTC,EAAc,SAACtG,EAAKyB,GACxB,IAAM8E,EAAYH,GAAYvE,EAAQwE,EAAQ5E,IAAQA,EAClD1B,EAAcsG,EAAOE,KAAexG,EAAcC,GACpDqG,EAAOE,GAAaN,EAAMI,EAAOE,GAAYvG,GACpCD,EAAcC,GACvBqG,EAAOE,GAAaN,EAAM,CAAE,EAAEjG,GACrBT,EAAQS,GACjBqG,EAAOE,GAAavG,EAAIf,QAExBoH,EAAOE,GAAavG,GAIfkB,EAAI,EAAGC,EAAI7C,UAAU+C,OAAQH,EAAIC,EAAGD,IAC3C5C,UAAU4C,IAAMF,EAAQ1C,UAAU4C,GAAIoF,GAExC,OAAOD,CACT,EA6YEG,OAjYa,SAACC,EAAGC,EAAGtI,GAA8B,IAAAuI,EAAArI,UAAA+C,OAAA,QAAAC,IAAAhD,UAAA,GAAAA,UAAA,GAAP,CAAE,EAAfkD,EAAUmF,EAAVnF,WAQ9B,OAPAR,EAAQ0F,GAAG,SAAC1G,EAAKyB,GACXrD,GAAWwB,EAAWI,GACxByG,EAAEhF,GAAOvD,EAAK8B,EAAK5B,GAEnBqI,EAAEhF,GAAOzB,CAEb,GAAG,CAACwB,WAAAA,IACGiF,CACT,EAyXEG,KA7fW,SAAC7H,GAAG,OAAKA,EAAI6H,KACxB7H,EAAI6H,OAAS7H,EAAI8H,QAAQ,qCAAsC,GAAG,EA6flEC,SAjXe,SAACC,GAIhB,OAH8B,QAA1BA,EAAQC,WAAW,KACrBD,EAAUA,EAAQ9H,MAAM,IAEnB8H,CACT,EA6WEE,SAlWe,SAAC5B,EAAa6B,EAAkBC,EAAOnE,GACtDqC,EAAY3G,UAAYD,OAAOI,OAAOqI,EAAiBxI,UAAWsE,GAClEqC,EAAY3G,UAAU2G,YAAcA,EACpC5G,OAAO2I,eAAe/B,EAAa,QAAS,CAC1CgC,MAAOH,EAAiBxI,YAE1ByI,GAAS1I,OAAO6I,OAAOjC,EAAY3G,UAAWyI,EAChD,EA4VEI,aAjVmB,SAACC,EAAWC,EAASC,EAAQC,GAChD,IAAIR,EACAjG,EACA0B,EACEgF,EAAS,CAAA,EAIf,GAFAH,EAAUA,GAAW,GAEJ,MAAbD,EAAmB,OAAOC,EAE9B,EAAG,CAGD,IADAvG,GADAiG,EAAQ1I,OAAOkD,oBAAoB6F,IACzBnG,OACHH,KAAM,GACX0B,EAAOuE,EAAMjG,GACPyG,IAAcA,EAAW/E,EAAM4E,EAAWC,IAAcG,EAAOhF,KACnE6E,EAAQ7E,GAAQ4E,EAAU5E,GAC1BgF,EAAOhF,IAAQ,GAGnB4E,GAAuB,IAAXE,GAAoB/I,EAAe6I,EACjD,OAASA,KAAeE,GAAUA,EAAOF,EAAWC,KAAaD,IAAc/I,OAAOC,WAEtF,OAAO+I,CACT,EA0TE7I,OAAAA,EACAO,WAAAA,EACA0I,SAjTe,SAAC9I,EAAK+I,EAAcC,GACnChJ,EAAMiJ,OAAOjJ,SACIuC,IAAbyG,GAA0BA,EAAWhJ,EAAIsC,UAC3C0G,EAAWhJ,EAAIsC,QAEjB0G,GAAYD,EAAazG,OACzB,IAAM4G,EAAYlJ,EAAImJ,QAAQJ,EAAcC,GAC5C,OAAsB,IAAfE,GAAoBA,IAAcF,CAC3C,EA0SEI,QAhSc,SAACrJ,GACf,IAAKA,EAAO,OAAO,KACnB,GAAIS,EAAQT,GAAQ,OAAOA,EAC3B,IAAIoC,EAAIpC,EAAMuC,OACd,IAAKxB,EAASqB,GAAI,OAAO,KAEzB,IADA,IAAMkH,EAAM,IAAI5I,MAAM0B,GACfA,KAAM,GACXkH,EAAIlH,GAAKpC,EAAMoC,GAEjB,OAAOkH,CACT,EAuREC,aA7PmB,SAACpH,EAAK9C,GAOzB,IANA,IAIIkI,EAFElG,GAFYc,GAAOA,EAAIhB,OAAOE,WAETnB,KAAKiC,IAIxBoF,EAASlG,EAASmI,UAAYjC,EAAOkC,MAAM,CACjD,IAAMC,EAAOnC,EAAOgB,MACpBlJ,EAAGa,KAAKiC,EAAKuH,EAAK,GAAIA,EAAK,GAC7B,CACF,EAmPEC,SAzOe,SAACC,EAAQ3J,GAIxB,IAHA,IAAI4J,EACEP,EAAM,GAE4B,QAAhCO,EAAUD,EAAOE,KAAK7J,KAC5BqJ,EAAIvD,KAAK8D,GAGX,OAAOP,CACT,EAiOE3F,WAAAA,GACAC,eAAAA,GACAmG,WAAYnG,GACZI,kBAAAA,GACAgG,cAzLoB,SAAC7H,GACrB6B,GAAkB7B,GAAK,SAACkC,EAAYC,GAElC,GAAIxD,EAAWqB,KAA6D,IAArD,CAAC,YAAa,SAAU,UAAUiH,QAAQ9E,GAC/D,OAAO,EAGT,IAAMiE,EAAQpG,EAAImC,GAEbxD,EAAWyH,KAEhBlE,EAAW4F,YAAa,EAEpB,aAAc5F,EAChBA,EAAW6F,UAAW,EAInB7F,EAAW8F,MACd9F,EAAW8F,IAAM,WACf,MAAMC,MAAM,qCAAwC9F,EAAO,OAGjE,GACF,EAkKE+F,YAhKkB,SAACC,EAAeC,GAClC,IAAMpI,EAAM,CAAA,EAENqI,EAAS,SAAClB,GACdA,EAAIpH,SAAQ,SAAAqG,GACVpG,EAAIoG,IAAS,CACf,KAKF,OAFA9H,EAAQ6J,GAAiBE,EAAOF,GAAiBE,EAAOtB,OAAOoB,GAAeG,MAAMF,IAE7EpI,CACT,EAqJEuI,YAlOkB,SAAAzK,GAClB,OAAOA,EAAIG,cAAc2H,QAAQ,yBAC/B,SAAkB4C,EAAGC,EAAIC,GACvB,OAAOD,EAAG/F,cAAgBgG,CAC5B,GAEJ,EA6NEC,KApJW,aAqJXC,eAnJqB,SAACxC,EAAOyC,GAC7B,OAAgB,MAATzC,GAAiB0C,OAAOC,SAAS3C,GAASA,GAASA,EAAQyC,CACpE,EAkJEjI,QAAAA,EACAM,OAAQJ,EACRK,iBAAAA,EACAqB,SAAAA,GACAwG,eA1IqB,WAGrB,IAHqE,IAA/CC,EAAI5L,UAAA+C,OAAA,QAAAC,IAAAhD,UAAA,GAAAA,UAAA,GAAG,GAAI6L,EAAQ7L,UAAA+C,OAAA/C,QAAAgD,IAAAhD,UAAAgD,GAAAhD,UAAGmF,GAAAA,GAASC,YACjD3E,EAAM,GACHsC,EAAU8I,EAAV9I,OACA6I,KACLnL,GAAOoL,EAAS9F,KAAKC,SAAWjD,EAAO,GAGzC,OAAOtC,CACT,EAmIEqL,oBA1HF,SAA6BtL,GAC3B,SAAUA,GAASc,EAAWd,EAAM2G,SAAyC,aAA9B3G,EAAMmB,OAAOC,cAA+BpB,EAAMmB,OAAOE,UAC1G,EAyHEkK,aAvHmB,SAACpJ,GACpB,IAAMqJ,EAAQ,IAAI9K,MAAM,IA2BxB,OAzBc,SAAR+K,EAAS9F,EAAQvD,GAErB,GAAIpB,EAAS2E,GAAS,CACpB,GAAI6F,EAAMpC,QAAQzD,IAAW,EAC3B,OAGF,KAAK,WAAYA,GAAS,CACxB6F,EAAMpJ,GAAKuD,EACX,IAAM+F,EAASjL,EAAQkF,GAAU,GAAK,CAAA,EAStC,OAPAzD,EAAQyD,GAAQ,SAAC4C,EAAO5F,GACtB,IAAMgJ,EAAeF,EAAMlD,EAAOnG,EAAI,IACrCzB,EAAYgL,KAAkBD,EAAO/I,GAAOgJ,EAC/C,IAEAH,EAAMpJ,QAAKI,EAEJkJ,CACT,CACF,CAEA,OAAO/F,EAGF8F,CAAMtJ,EAAK,EACpB,EA2FE+C,UAAAA,GACA0G,WAxFiB,SAAC5L,GAAK,OACvBA,IAAUgB,EAAShB,IAAUc,EAAWd,KAAWc,EAAWd,EAAM6L,OAAS/K,EAAWd,EAAK,MAAO,EAwFpGoF,aAAcD,GACdc,KAAAA,ICvuBF,SAAS6F,GAAWC,EAASC,EAAMC,EAAQC,EAASC,GAClD/B,MAAMlK,KAAKmH,MAEP+C,MAAMgC,kBACRhC,MAAMgC,kBAAkB/E,KAAMA,KAAKd,aAEnCc,KAAKmE,OAAS,IAAIpB,OAASoB,MAG7BnE,KAAK0E,QAAUA,EACf1E,KAAK/C,KAAO,aACZ0H,IAAS3E,KAAK2E,KAAOA,GACrBC,IAAW5E,KAAK4E,OAASA,GACzBC,IAAY7E,KAAK6E,QAAUA,GACvBC,IACF9E,KAAK8E,SAAWA,EAChB9E,KAAKgF,OAASF,EAASE,OAASF,EAASE,OAAS,KAEtD,CAEAC,GAAMnE,SAAS2D,GAAY1B,MAAO,CAChCmC,OAAQ,WACN,MAAO,CAELR,QAAS1E,KAAK0E,QACdzH,KAAM+C,KAAK/C,KAEXkI,YAAanF,KAAKmF,YAClBC,OAAQpF,KAAKoF,OAEbC,SAAUrF,KAAKqF,SACfC,WAAYtF,KAAKsF,WACjBC,aAAcvF,KAAKuF,aACnBpB,MAAOnE,KAAKmE,MAEZS,OAAQK,GAAMf,aAAalE,KAAK4E,QAChCD,KAAM3E,KAAK2E,KACXK,OAAQhF,KAAKgF,OAEjB,IAGF,IAAMzM,GAAYkM,GAAWlM,UACvBsE,GAAc,CAAA,EAEpB,CACE,uBACA,iBACA,eACA,YACA,cACA,4BACA,iBACA,mBACA,kBACA,eACA,kBACA,mBAEAhC,SAAQ,SAAA8J,GACR9H,GAAY8H,GAAQ,CAACzD,MAAOyD,EAC9B,IAEArM,OAAO6E,iBAAiBsH,GAAY5H,IACpCvE,OAAO2I,eAAe1I,GAAW,eAAgB,CAAC2I,OAAO,IAGzDuD,GAAWe,KAAO,SAACC,EAAOd,EAAMC,EAAQC,EAASC,EAAUY,GACzD,IAAMC,EAAarN,OAAOI,OAAOH,IAgBjC,OAdA0M,GAAM7D,aAAaqE,EAAOE,GAAY,SAAgB7K,GACpD,OAAOA,IAAQiI,MAAMxK,SACtB,IAAE,SAAAkE,GACD,MAAgB,iBAATA,CACT,IAEAgI,GAAW5L,KAAK8M,EAAYF,EAAMf,QAASC,EAAMC,EAAQC,EAASC,GAElEa,EAAWC,MAAQH,EAEnBE,EAAW1I,KAAOwI,EAAMxI,KAExByI,GAAepN,OAAO6I,OAAOwE,EAAYD,GAElCC,CACT,ECtFA,SAASE,GAAYlN,GACnB,OAAOsM,GAAMrL,cAAcjB,IAAUsM,GAAM7L,QAAQT,EACrD,CASA,SAASmN,GAAexK,GACtB,OAAO2J,GAAMvD,SAASpG,EAAK,MAAQA,EAAIxC,MAAM,GAAI,GAAKwC,CACxD,CAWA,SAASyK,GAAUC,EAAM1K,EAAK2K,GAC5B,OAAKD,EACEA,EAAK/H,OAAO3C,GAAKd,KAAI,SAAcmD,EAAO5C,GAG/C,OADA4C,EAAQmI,GAAenI,IACfsI,GAAQlL,EAAI,IAAM4C,EAAQ,IAAMA,CACzC,IAAEuI,KAAKD,EAAO,IAAM,IALH3K,CAMpB,CAaA,IAAM6K,GAAalB,GAAM7D,aAAa6D,GAAO,CAAE,EAAE,MAAM,SAAgBxI,GACrE,MAAO,WAAW2J,KAAK3J,EACzB,IAyBA,SAAS4J,GAAWvL,EAAKwL,EAAUC,GACjC,IAAKtB,GAAMtL,SAASmB,GAClB,MAAM,IAAI0L,UAAU,4BAItBF,EAAWA,GAAY,IAAyBjH,SAYhD,IAAMoH,GATNF,EAAUtB,GAAM7D,aAAamF,EAAS,CACpCE,YAAY,EACZR,MAAM,EACNS,SAAS,IACR,GAAO,SAAiBC,EAAQrI,GAEjC,OAAQ2G,GAAM3L,YAAYgF,EAAOqI,GACnC,KAE2BF,WAErBG,EAAUL,EAAQK,SAAWC,EAC7BZ,EAAOM,EAAQN,KACfS,EAAUH,EAAQG,QAElBI,GADQP,EAAQQ,MAAwB,oBAATA,MAAwBA,OACpC9B,GAAMhB,oBAAoBqC,GAEnD,IAAKrB,GAAMxL,WAAWmN,GACpB,MAAM,IAAIJ,UAAU,8BAGtB,SAASQ,EAAa9F,GACpB,GAAc,OAAVA,EAAgB,MAAO,GAE3B,GAAI+D,GAAMhL,OAAOiH,GACf,OAAOA,EAAM+F,cAGf,IAAKH,GAAW7B,GAAM9K,OAAO+G,GAC3B,MAAM,IAAIuD,GAAW,gDAGvB,OAAIQ,GAAM1L,cAAc2H,IAAU+D,GAAM7I,aAAa8E,GAC5C4F,GAA2B,mBAATC,KAAsB,IAAIA,KAAK,CAAC7F,IAAUgG,OAAO1B,KAAKtE,GAG1EA,CACT,CAYA,SAAS2F,EAAe3F,EAAO5F,EAAK0K,GAClC,IAAI/D,EAAMf,EAEV,GAAIA,IAAU8E,GAAyB,WAAjB7M,EAAO+H,GAC3B,GAAI+D,GAAMvD,SAASpG,EAAK,MAEtBA,EAAMmL,EAAanL,EAAMA,EAAIxC,MAAM,GAAI,GAEvCoI,EAAQiG,KAAKC,UAAUlG,QAClB,GACJ+D,GAAM7L,QAAQ8H,IAnGvB,SAAqBe,GACnB,OAAOgD,GAAM7L,QAAQ6I,KAASA,EAAIoF,KAAKxB,GACzC,CAiGiCyB,CAAYpG,KACnC+D,GAAM7K,WAAW8G,IAAU+D,GAAMvD,SAASpG,EAAK,SAAW2G,EAAMgD,GAAMjD,QAAQd,IAYhF,OATA5F,EAAMwK,GAAexK,GAErB2G,EAAIpH,SAAQ,SAAc0M,EAAIC,IAC1BvC,GAAM3L,YAAYiO,IAAc,OAAPA,GAAgBjB,EAAShH,QAEtC,IAAZoH,EAAmBX,GAAU,CAACzK,GAAMkM,EAAOvB,GAAqB,OAAZS,EAAmBpL,EAAMA,EAAM,KACnF0L,EAAaO,GAEjB,KACO,EAIX,QAAI1B,GAAY3E,KAIhBoF,EAAShH,OAAOyG,GAAUC,EAAM1K,EAAK2K,GAAOe,EAAa9F,KAElD,EACT,CAEA,IAAMiD,EAAQ,GAERsD,EAAiBnP,OAAO6I,OAAOgF,GAAY,CAC/CU,eAAAA,EACAG,aAAAA,EACAnB,YAAAA,KAyBF,IAAKZ,GAAMtL,SAASmB,GAClB,MAAM,IAAI0L,UAAU,0BAKtB,OA5BA,SAASkB,EAAMxG,EAAO8E,GACpB,IAAIf,GAAM3L,YAAY4H,GAAtB,CAEA,IAA8B,IAA1BiD,EAAMpC,QAAQb,GAChB,MAAM6B,MAAM,kCAAoCiD,EAAKE,KAAK,MAG5D/B,EAAMzF,KAAKwC,GAEX+D,GAAMpK,QAAQqG,GAAO,SAAcqG,EAAIjM,IAKtB,OAJE2J,GAAM3L,YAAYiO,IAAc,OAAPA,IAAgBX,EAAQ/N,KAChEyN,EAAUiB,EAAItC,GAAMzL,SAAS8B,GAAOA,EAAImF,OAASnF,EAAK0K,EAAMyB,KAI5DC,EAAMH,EAAIvB,EAAOA,EAAK/H,OAAO3C,GAAO,CAACA,GAEzC,IAEA6I,EAAMwD,KAlBwB,CAmBhC,CAMAD,CAAM5M,GAECwL,CACT,CC5MA,SAASsB,GAAOhP,GACd,IAAMiP,EAAU,CACd,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,MAAO,IACP,MAAO,MAET,OAAOC,mBAAmBlP,GAAK8H,QAAQ,oBAAoB,SAAkBqH,GAC3E,OAAOF,EAAQE,EACjB,GACF,CAUA,SAASC,GAAqBC,EAAQ1B,GACpCvG,KAAKkI,OAAS,GAEdD,GAAU5B,GAAW4B,EAAQjI,KAAMuG,EACrC,CAEA,IAAMhO,GAAYyP,GAAqBzP,UC5BvC,SAASqP,GAAO/N,GACd,OAAOiO,mBAAmBjO,GACxB6G,QAAQ,QAAS,KACjBA,QAAQ,OAAQ,KAChBA,QAAQ,QAAS,KACjBA,QAAQ,OAAQ,KAChBA,QAAQ,QAAS,KACjBA,QAAQ,QAAS,IACrB,CAWe,SAASyH,GAASC,EAAKH,EAAQ1B,GAE5C,IAAK0B,EACH,OAAOG,EAGT,IAAMC,EAAU9B,GAAWA,EAAQqB,QAAUA,GAEzC3C,GAAMxL,WAAW8M,KACnBA,EAAU,CACR+B,UAAW/B,IAIf,IAEIgC,EAFEC,EAAcjC,GAAWA,EAAQ+B,UAYvC,GAPEC,EADEC,EACiBA,EAAYP,EAAQ1B,GAEpBtB,GAAM5K,kBAAkB4N,GACzCA,EAAO5P,WACP,IAAI2P,GAAqBC,EAAQ1B,GAASlO,SAASgQ,GAGjC,CACpB,IAAMI,EAAgBL,EAAIrG,QAAQ,MAEX,IAAnB0G,IACFL,EAAMA,EAAItP,MAAM,EAAG2P,IAErBL,KAA8B,IAAtBA,EAAIrG,QAAQ,KAAc,IAAM,KAAOwG,CACjD,CAEA,OAAOH,CACT,CDzBA7P,GAAU+G,OAAS,SAAgBrC,EAAMiE,GACvClB,KAAKkI,OAAOxJ,KAAK,CAACzB,EAAMiE,GAC1B,EAEA3I,GAAUF,SAAW,SAAkBqQ,GACrC,IAAML,EAAUK,EAAU,SAASxH,GACjC,OAAOwH,EAAQ7P,KAAKmH,KAAMkB,EAAO0G,GAClC,EAAGA,GAEJ,OAAO5H,KAAKkI,OAAO1N,KAAI,SAAc6H,GACnC,OAAOgG,EAAQhG,EAAK,IAAM,IAAMgG,EAAQhG,EAAK,GAC9C,GAAE,IAAI6D,KAAK,IACd,EErDkC,IAoElCyC,GAlEwB,WACtB,SAAAC,IAAcC,OAAAD,GACZ5I,KAAK8I,SAAW,EAClB,CA4DC,OA1DDC,EAAAH,EAAA,CAAA,CAAAtN,IAAA,MAAA4F,MAQA,SAAI8H,EAAWC,EAAU1C,GAOvB,OANAvG,KAAK8I,SAASpK,KAAK,CACjBsK,UAAAA,EACAC,SAAAA,EACAC,cAAa3C,GAAUA,EAAQ2C,YAC/BC,QAAS5C,EAAUA,EAAQ4C,QAAU,OAEhCnJ,KAAK8I,SAAS5N,OAAS,CAChC,GAEA,CAAAI,IAAA,QAAA4F,MAOA,SAAMkI,GACApJ,KAAK8I,SAASM,KAChBpJ,KAAK8I,SAASM,GAAM,KAExB,GAEA,CAAA9N,IAAA,QAAA4F,MAKA,WACMlB,KAAK8I,WACP9I,KAAK8I,SAAW,GAEpB,GAEA,CAAAxN,IAAA,UAAA4F,MAUA,SAAQlJ,GACNiN,GAAMpK,QAAQmF,KAAK8I,UAAU,SAAwBO,GACzC,OAANA,GACFrR,EAAGqR,EAEP,GACF,KAACT,CAAA,CA/DqB,GCFTU,GAAA,CACbC,mBAAmB,EACnBC,mBAAmB,EACnBC,qBAAqB,GCDRC,GAAA,CACbC,WAAW,EACXC,QAAS,CACPC,gBCJsC,oBAApBA,gBAAkCA,gBAAkB7B,GDKtE3I,SEN+B,oBAAbA,SAA2BA,SAAW,KFOxD0H,KGP2B,oBAATA,KAAuBA,KAAO,MHSlD+C,UAAW,CAAC,OAAQ,QAAS,OAAQ,OAAQ,MAAO,SIXhDC,GAAkC,oBAAXhO,QAA8C,oBAAbiO,SAExDC,GAAkC,YAAL9Q,oBAAT+Q,UAAS/Q,YAAAA,EAAT+Q,aAA0BA,gBAAa/O,EAmB3DgP,GAAwBJ,MAC1BE,IAAc,CAAC,cAAe,eAAgB,MAAMlI,QAAQkI,GAAWG,SAAW,GAWhFC,GAE2B,oBAAtBC,mBAEPxO,gBAAgBwO,mBACc,mBAAvBxO,KAAKyO,cAIVC,GAAST,IAAiBhO,OAAO0O,SAASC,MAAQ,mBCvCxDC,GAAAA,EAAAA,EACK1F,CAAAA,sIACA2F,IC2CL,SAASC,GAAevE,GACtB,SAASwE,EAAU9E,EAAM9E,EAAOmD,EAAQmD,GACtC,IAAIvK,EAAO+I,EAAKwB,KAEhB,GAAa,cAATvK,EAAsB,OAAO,EAEjC,IAAM8N,EAAenH,OAAOC,UAAU5G,GAChC+N,EAASxD,GAASxB,EAAK9K,OAG7B,OAFA+B,GAAQA,GAAQgI,GAAM7L,QAAQiL,GAAUA,EAAOnJ,OAAS+B,EAEpD+N,GACE/F,GAAMvC,WAAW2B,EAAQpH,GAC3BoH,EAAOpH,GAAQ,CAACoH,EAAOpH,GAAOiE,GAE9BmD,EAAOpH,GAAQiE,GAGT6J,IAGL1G,EAAOpH,IAAUgI,GAAMtL,SAAS0K,EAAOpH,MAC1CoH,EAAOpH,GAAQ,IAGF6N,EAAU9E,EAAM9E,EAAOmD,EAAOpH,GAAOuK,IAEtCvC,GAAM7L,QAAQiL,EAAOpH,MACjCoH,EAAOpH,GA/Cb,SAAuBgF,GACrB,IAEIlH,EAEAO,EAJER,EAAM,CAAA,EACNS,EAAOjD,OAAOiD,KAAK0G,GAEnBxG,EAAMF,EAAKL,OAEjB,IAAKH,EAAI,EAAGA,EAAIU,EAAKV,IAEnBD,EADAQ,EAAMC,EAAKR,IACAkH,EAAI3G,GAEjB,OAAOR,CACT,CAoCqBmQ,CAAc5G,EAAOpH,MAG9B8N,EACV,CAEA,GAAI9F,GAAM9F,WAAWmH,IAAarB,GAAMxL,WAAW6M,EAAS4E,SAAU,CACpE,IAAMpQ,EAAM,CAAA,EAMZ,OAJAmK,GAAM/C,aAAaoE,GAAU,SAACrJ,EAAMiE,GAClC4J,EA1EN,SAAuB7N,GAKrB,OAAOgI,GAAM3C,SAAS,gBAAiBrF,GAAMzC,KAAI,SAAAuN,GAC/C,MAAoB,OAAbA,EAAM,GAAc,GAAKA,EAAM,IAAMA,EAAM,EACpD,GACF,CAkEgBoD,CAAclO,GAAOiE,EAAOpG,EAAK,EAC7C,IAEOA,CACT,CAEA,OAAO,IACT,CCzDA,IAAMsQ,GAAW,CAEfC,aAAc/B,GAEdgC,QAAS,CAAC,MAAO,OAAQ,SAEzBC,iBAAkB,CAAC,SAA0BhN,EAAMiN,GACjD,IA+BIpR,EA/BEqR,EAAcD,EAAQE,kBAAoB,GAC1CC,EAAqBF,EAAY1J,QAAQ,qBAAuB,EAChE6J,EAAkB3G,GAAMtL,SAAS4E,GAQvC,GANIqN,GAAmB3G,GAAM3I,WAAWiC,KACtCA,EAAO,IAAIc,SAASd,IAGH0G,GAAM9F,WAAWZ,GAGlC,OAAOoN,EAAqBxE,KAAKC,UAAUyD,GAAetM,IAASA,EAGrE,GAAI0G,GAAM1L,cAAcgF,IACtB0G,GAAMhG,SAASV,IACf0G,GAAMrF,SAASrB,IACf0G,GAAM/K,OAAOqE,IACb0G,GAAM9K,OAAOoE,IACb0G,GAAMxK,iBAAiB8D,GAEvB,OAAOA,EAET,GAAI0G,GAAM1F,kBAAkBhB,GAC1B,OAAOA,EAAKmB,OAEd,GAAIuF,GAAM5K,kBAAkBkE,GAE1B,OADAiN,EAAQK,eAAe,mDAAmD,GACnEtN,EAAKlG,WAKd,GAAIuT,EAAiB,CACnB,GAAIH,EAAY1J,QAAQ,sCAAwC,EAC9D,OCvEO,SAA0BxD,EAAMgI,GAC7C,OAAOF,GAAW9H,EAAM,IAAIqM,GAAShB,QAAQC,gBAAmBvR,OAAO6I,OAAO,CAC5EyF,QAAS,SAAS1F,EAAO5F,EAAK0K,EAAM8F,GAClC,OAAIlB,GAASmB,QAAU9G,GAAMhG,SAASiC,IACpClB,KAAKV,OAAOhE,EAAK4F,EAAM7I,SAAS,YACzB,GAGFyT,EAAQjF,eAAe3O,MAAM8H,KAAM7H,UAC5C,GACCoO,GACL,CD4DeyF,CAAiBzN,EAAMyB,KAAKiM,gBAAgB5T,WAGrD,IAAK+B,EAAa6K,GAAM7K,WAAWmE,KAAUkN,EAAY1J,QAAQ,wBAA0B,EAAG,CAC5F,IAAMmK,EAAYlM,KAAKmM,KAAOnM,KAAKmM,IAAI9M,SAEvC,OAAOgH,GACLjM,EAAa,CAAC,UAAWmE,GAAQA,EACjC2N,GAAa,IAAIA,EACjBlM,KAAKiM,eAET,CACF,CAEA,OAAIL,GAAmBD,GACrBH,EAAQK,eAAe,oBAAoB,GAxEjD,SAAyBO,EAAUC,EAAQ3D,GACzC,GAAIzD,GAAMzL,SAAS4S,GACjB,IAEE,OADCC,GAAUlF,KAAKmF,OAAOF,GAChBnH,GAAMxE,KAAK2L,EAKpB,CAJE,MAAOG,GACP,GAAe,gBAAXA,EAAEtP,KACJ,MAAMsP,CAEV,CAGF,OAAQ7D,GAAWvB,KAAKC,WAAWgF,EACrC,CA4DaI,CAAgBjO,IAGlBA,CACT,GAEAkO,kBAAmB,CAAC,SAA2BlO,GAC7C,IAAM8M,EAAerL,KAAKqL,cAAgBD,GAASC,aAC7C7B,EAAoB6B,GAAgBA,EAAa7B,kBACjDkD,EAAsC,SAAtB1M,KAAK2M,aAE3B,GAAI1H,GAAMtK,WAAW4D,IAAS0G,GAAMxK,iBAAiB8D,GACnD,OAAOA,EAGT,GAAIA,GAAQ0G,GAAMzL,SAAS+E,KAAWiL,IAAsBxJ,KAAK2M,cAAiBD,GAAgB,CAChG,IACME,IADoBvB,GAAgBA,EAAa9B,oBACPmD,EAEhD,IACE,OAAOvF,KAAKmF,MAAM/N,EAQpB,CAPE,MAAOgO,GACP,GAAIK,EAAmB,CACrB,GAAe,gBAAXL,EAAEtP,KACJ,MAAMwH,GAAWe,KAAK+G,EAAG9H,GAAWoI,iBAAkB7M,KAAM,KAAMA,KAAK8E,UAEzE,MAAMyH,CACR,CACF,CACF,CAEA,OAAOhO,CACT,GAMAuO,QAAS,EAETC,eAAgB,aAChBC,eAAgB,eAEhBC,kBAAmB,EACnBC,eAAgB,EAEhBf,IAAK,CACH9M,SAAUuL,GAAShB,QAAQvK,SAC3B0H,KAAM6D,GAAShB,QAAQ7C,MAGzBoG,eAAgB,SAAwBnI,GACtC,OAAOA,GAAU,KAAOA,EAAS,GAClC,EAEDwG,QAAS,CACP4B,OAAQ,CACNC,OAAU,oCACV,oBAAgBlS,KAKtB8J,GAAMpK,QAAQ,CAAC,SAAU,MAAO,OAAQ,OAAQ,MAAO,UAAU,SAACyS,GAChElC,GAASI,QAAQ8B,GAAU,EAC7B,IAEA,IAAAC,GAAenC,GE1JToC,GAAoBvI,GAAMjC,YAAY,CAC1C,MAAO,gBAAiB,iBAAkB,eAAgB,OAC1D,UAAW,OAAQ,OAAQ,oBAAqB,sBAChD,gBAAiB,WAAY,eAAgB,sBAC7C,UAAW,cAAe,eCLtByK,GAAa3T,OAAO,aAE1B,SAAS4T,GAAgBC,GACvB,OAAOA,GAAU9L,OAAO8L,GAAQlN,OAAO1H,aACzC,CAEA,SAAS6U,GAAe1M,GACtB,OAAc,IAAVA,GAA4B,MAATA,EACdA,EAGF+D,GAAM7L,QAAQ8H,GAASA,EAAM1G,IAAIoT,IAAkB/L,OAAOX,EACnE,CAgBA,SAAS2M,GAAiB3R,EAASgF,EAAOyM,EAAQpM,EAAQuM,GACxD,OAAI7I,GAAMxL,WAAW8H,GACZA,EAAO1I,KAAKmH,KAAMkB,EAAOyM,IAG9BG,IACF5M,EAAQyM,GAGL1I,GAAMzL,SAAS0H,GAEhB+D,GAAMzL,SAAS+H,IACiB,IAA3BL,EAAMa,QAAQR,GAGnB0D,GAAMvI,SAAS6E,GACVA,EAAO6E,KAAKlF,QADrB,OANA,EASF,CAoBC,IAEK6M,GAAY,SAAAC,EAAAC,GAChB,SAAAF,EAAYvC,GAAS3C,OAAAkF,GACnBvC,GAAWxL,KAAK8C,IAAI0I,EACtB,CA+MC,OA/MAzC,EAAAgF,EAAA,CAAA,CAAAzS,IAAA,MAAA4F,MAED,SAAIyM,EAAQO,EAAgBC,GAC1B,IAAMrS,EAAOkE,KAEb,SAASoO,EAAUC,EAAQC,EAASC,GAClC,IAAMC,EAAUd,GAAgBY,GAEhC,IAAKE,EACH,MAAM,IAAIzL,MAAM,0CAGlB,IAAMzH,EAAM2J,GAAMvJ,QAAQI,EAAM0S,KAE5BlT,QAAqBH,IAAdW,EAAKR,KAAmC,IAAbiT,QAAmCpT,IAAboT,IAAwC,IAAdzS,EAAKR,MACzFQ,EAAKR,GAAOgT,GAAWV,GAAeS,GAE1C,CAEA,IAAMI,EAAa,SAACjD,EAAS+C,GAAQ,OACnCtJ,GAAMpK,QAAQ2Q,GAAS,SAAC6C,EAAQC,GAAO,OAAKF,EAAUC,EAAQC,EAASC,KAAU,EAEnF,GAAItJ,GAAMrL,cAAc+T,IAAWA,aAAkB3N,KAAKd,YACxDuP,EAAWd,EAAQO,QACd,GAAGjJ,GAAMzL,SAASmU,KAAYA,EAASA,EAAOlN,UArEtB,iCAAiC2F,KAqEmBuH,EArEVlN,QAsEvEgO,ED1ES,SAAAC,GACb,IACIpT,EACAzB,EACAkB,EAHE4T,EAAS,CAAA,EAyBf,OApBAD,GAAcA,EAAWtL,MAAM,MAAMvI,SAAQ,SAAgB+T,GAC3D7T,EAAI6T,EAAK7M,QAAQ,KACjBzG,EAAMsT,EAAKC,UAAU,EAAG9T,GAAG0F,OAAO1H,cAClCc,EAAM+U,EAAKC,UAAU9T,EAAI,GAAG0F,QAEvBnF,GAAQqT,EAAOrT,IAAQkS,GAAkBlS,KAIlC,eAARA,EACEqT,EAAOrT,GACTqT,EAAOrT,GAAKoD,KAAK7E,GAEjB8U,EAAOrT,GAAO,CAACzB,GAGjB8U,EAAOrT,GAAOqT,EAAOrT,GAAOqT,EAAOrT,GAAO,KAAOzB,EAAMA,EAE3D,IAEO8U,CACR,CC+CgBG,CAAanB,GAASO,QAC5B,GAAIjJ,GAAMrK,UAAU+S,GAAS,CAAA,IACSoB,EADTC,koBAAAC,CACPtB,EAAOzC,WAAS,IAA3C,IAAA8D,EAAAE,MAAAH,EAAAC,EAAAG,KAAA/M,MAA6C,CAAA,IAAAgN,EAAA7U,EAAAwU,EAAA7N,MAAA,GAAjC5F,EAAG8T,EAAA,GACbhB,EADoBgB,EAAA,GACH9T,EAAK6S,EACxB,CAAC,CAAA,MAAAkB,GAAAL,EAAAzC,EAAA8C,EAAA,CAAA,QAAAL,EAAAM,GAAA,CACH,MACY,MAAV3B,GAAkBS,EAAUF,EAAgBP,EAAQQ,GAGtD,OAAOnO,IACT,GAAC,CAAA1E,IAAA,MAAA4F,MAED,SAAIyM,EAAQtB,GAGV,GAFAsB,EAASD,GAAgBC,GAEb,CACV,IAAMrS,EAAM2J,GAAMvJ,QAAQsE,KAAM2N,GAEhC,GAAIrS,EAAK,CACP,IAAM4F,EAAQlB,KAAK1E,GAEnB,IAAK+Q,EACH,OAAOnL,EAGT,IAAe,IAAXmL,EACF,OA5GV,SAAqBzT,GAKnB,IAJA,IAEImP,EAFEwH,EAASjX,OAAOI,OAAO,MACvB8W,EAAW,mCAGTzH,EAAQyH,EAAS/M,KAAK7J,IAC5B2W,EAAOxH,EAAM,IAAMA,EAAM,GAG3B,OAAOwH,CACT,CAkGiBE,CAAYvO,GAGrB,GAAI+D,GAAMxL,WAAW4S,GACnB,OAAOA,EAAOxT,KAAKmH,KAAMkB,EAAO5F,GAGlC,GAAI2J,GAAMvI,SAAS2P,GACjB,OAAOA,EAAO5J,KAAKvB,GAGrB,MAAM,IAAIsF,UAAU,yCACtB,CACF,CACF,GAAC,CAAAlL,IAAA,MAAA4F,MAED,SAAIyM,EAAQ+B,GAGV,GAFA/B,EAASD,GAAgBC,GAEb,CACV,IAAMrS,EAAM2J,GAAMvJ,QAAQsE,KAAM2N,GAEhC,SAAUrS,QAAqBH,IAAd6E,KAAK1E,IAAwBoU,IAAW7B,GAAiB7N,EAAMA,KAAK1E,GAAMA,EAAKoU,GAClG,CAEA,OAAO,CACT,GAAC,CAAApU,IAAA,SAAA4F,MAED,SAAOyM,EAAQ+B,GACb,IAAM5T,EAAOkE,KACT2P,GAAU,EAEd,SAASC,EAAatB,GAGpB,GAFAA,EAAUZ,GAAgBY,GAEb,CACX,IAAMhT,EAAM2J,GAAMvJ,QAAQI,EAAMwS,IAE5BhT,GAASoU,IAAW7B,GAAiB/R,EAAMA,EAAKR,GAAMA,EAAKoU,YACtD5T,EAAKR,GAEZqU,GAAU,EAEd,CACF,CAQA,OANI1K,GAAM7L,QAAQuU,GAChBA,EAAO9S,QAAQ+U,GAEfA,EAAajC,GAGRgC,CACT,GAAC,CAAArU,IAAA,QAAA4F,MAED,SAAMwO,GAKJ,IAJA,IAAMnU,EAAOjD,OAAOiD,KAAKyE,MACrBjF,EAAIQ,EAAKL,OACTyU,GAAU,EAEP5U,KAAK,CACV,IAAMO,EAAMC,EAAKR,GACb2U,IAAW7B,GAAiB7N,EAAMA,KAAK1E,GAAMA,EAAKoU,GAAS,YACtD1P,KAAK1E,GACZqU,GAAU,EAEd,CAEA,OAAOA,CACT,GAAC,CAAArU,IAAA,YAAA4F,MAED,SAAU2O,GACR,IAAM/T,EAAOkE,KACPwL,EAAU,CAAA,EAsBhB,OApBAvG,GAAMpK,QAAQmF,MAAM,SAACkB,EAAOyM,GAC1B,IAAMrS,EAAM2J,GAAMvJ,QAAQ8P,EAASmC,GAEnC,GAAIrS,EAGF,OAFAQ,EAAKR,GAAOsS,GAAe1M,eACpBpF,EAAK6R,GAId,IAAMmC,EAAaD,EA9JzB,SAAsBlC,GACpB,OAAOA,EAAOlN,OACX1H,cAAc2H,QAAQ,mBAAmB,SAACqP,EAAGC,EAAMpX,GAClD,OAAOoX,EAAKxS,cAAgB5E,CAC9B,GACJ,CAyJkCqX,CAAatC,GAAU9L,OAAO8L,GAAQlN,OAE9DqP,IAAenC,UACV7R,EAAK6R,GAGd7R,EAAKgU,GAAclC,GAAe1M,GAElCsK,EAAQsE,IAAc,CACxB,IAEO9P,IACT,GAAC,CAAA1E,IAAA,SAAA4F,MAED,WAAmB,IAAA,IAAAgP,EAAAC,EAAAhY,UAAA+C,OAATkV,EAAO/W,IAAAA,MAAA8W,GAAAxU,EAAA,EAAAA,EAAAwU,EAAAxU,IAAPyU,EAAOzU,GAAAxD,UAAAwD,GACf,OAAOuU,EAAAlQ,KAAKd,aAAYjB,OAAM/F,MAAAgY,EAAC,CAAAlQ,MAAI/B,OAAKmS,GAC1C,GAAC,CAAA9U,IAAA,SAAA4F,MAED,SAAOmP,GACL,IAAMvV,EAAMxC,OAAOI,OAAO,MAM1B,OAJAuM,GAAMpK,QAAQmF,MAAM,SAACkB,EAAOyM,GACjB,MAATzM,IAA2B,IAAVA,IAAoBpG,EAAI6S,GAAU0C,GAAapL,GAAM7L,QAAQ8H,GAASA,EAAMgF,KAAK,MAAQhF,EAC5G,IAEOpG,CACT,GAAC,CAAAQ,IAEAxB,OAAOE,SAFPkH,MAED,WACE,OAAO5I,OAAO4S,QAAQlL,KAAKkF,UAAUpL,OAAOE,WAC9C,GAAC,CAAAsB,IAAA,WAAA4F,MAED,WACE,OAAO5I,OAAO4S,QAAQlL,KAAKkF,UAAU1K,KAAI,SAAAS,GAAA,IAAA8E,EAAAxF,EAAAU,EAAA,GAAe,OAAP8E,EAAA,GAAsB,KAAfA,EAAA,EAA2B,IAAEmG,KAAK,KAC5F,GAAC,CAAA5K,IAEIxB,OAAOC,YAFXuW,IAED,WACE,MAAO,cACT,IAAC,CAAA,CAAAhV,IAAA,OAAA4F,MAED,SAAYvI,GACV,OAAOA,aAAiBqH,KAAOrH,EAAQ,IAAIqH,KAAKrH,EAClD,GAAC,CAAA2C,IAAA,SAAA4F,MAED,SAAcqP,GACqB,IAAjC,IAAMC,EAAW,IAAIxQ,KAAKuQ,GAAOE,EAAAtY,UAAA+C,OADXkV,MAAO/W,MAAAoX,EAAAA,EAAAA,OAAAC,EAAA,EAAAA,EAAAD,EAAAC,IAAPN,EAAOM,EAAAvY,GAAAA,UAAAuY,GAK7B,OAFAN,EAAQvV,SAAQ,SAACwJ,GAAM,OAAKmM,EAAS1N,IAAIuB,MAElCmM,CACT,GAAC,CAAAlV,IAAA,WAAA4F,MAED,SAAgByM,GACd,IAIMgD,GAJY3Q,KAAKyN,IAAezN,KAAKyN,IAAc,CACvDkD,UAAW,CAAC,IAGcA,UACtBpY,EAAYyH,KAAKzH,UAEvB,SAASqY,EAAetC,GACtB,IAAME,EAAUd,GAAgBY,GAE3BqC,EAAUnC,MAtNrB,SAAwB1T,EAAK6S,GAC3B,IAAMkD,EAAe5L,GAAM5B,YAAY,IAAMsK,GAE7C,CAAC,MAAO,MAAO,OAAO9S,SAAQ,SAAAiW,GAC5BxY,OAAO2I,eAAenG,EAAKgW,EAAaD,EAAc,CACpD3P,MAAO,SAAS6P,EAAMC,EAAMC,GAC1B,OAAOjR,KAAK8Q,GAAYjY,KAAKmH,KAAM2N,EAAQoD,EAAMC,EAAMC,EACxD,EACDC,cAAc,GAElB,GACF,CA4MQC,CAAe5Y,EAAW+V,GAC1BqC,EAAUnC,IAAW,EAEzB,CAIA,OAFAvJ,GAAM7L,QAAQuU,GAAUA,EAAO9S,QAAQ+V,GAAkBA,EAAejD,GAEjE3N,IACT,KAAC+N,CAAA,CAlNe,GAqNlBA,GAAaqD,SAAS,CAAC,eAAgB,iBAAkB,SAAU,kBAAmB,aAAc,kBAG/FpS,GAACrC,kBAAkBoR,GAAaxV,WAAW,SAAAiI,EAAUlF,GAAQ,IAAhB4F,EAAKV,EAALU,MAC5CmQ,EAAS/V,EAAI,GAAGkC,cAAgBlC,EAAIxC,MAAM,GAC9C,MAAO,CACLwX,IAAK,WAAA,OAAMpP,CAAK,EAChB4B,IAAG,SAACwO,GACFtR,KAAKqR,GAAUC,CACjB,EAEJ,IAEArM,GAAMtC,cAAcoL,IAEpB,IAAAwD,GAAexD,GC/RA,SAASyD,GAAcC,EAAK3M,GACzC,IAAMF,EAAS5E,MAAQoL,GACjBlP,EAAU4I,GAAYF,EACtB4G,EAAUuC,GAAavI,KAAKtJ,EAAQsP,SACtCjN,EAAOrC,EAAQqC,KAQnB,OANA0G,GAAMpK,QAAQ4W,GAAK,SAAmBzZ,GACpCuG,EAAOvG,EAAGa,KAAK+L,EAAQrG,EAAMiN,EAAQkG,YAAa5M,EAAWA,EAASE,YAAS7J,EACjF,IAEAqQ,EAAQkG,YAEDnT,CACT,CCzBe,SAASoT,GAASzQ,GAC/B,SAAUA,IAASA,EAAM0Q,WAC3B,CCUA,SAASC,GAAcnN,EAASE,EAAQC,GAEtCJ,GAAW5L,KAAKmH,KAAiB,MAAX0E,EAAkB,WAAaA,EAASD,GAAWqN,aAAclN,EAAQC,GAC/F7E,KAAK/C,KAAO,eACd,CCLe,SAAS8U,GAAOC,EAASC,EAAQnN,GAC9C,IAAMqI,EAAiBrI,EAASF,OAAOuI,eAClCrI,EAASE,QAAWmI,IAAkBA,EAAerI,EAASE,QAGjEiN,EAAO,IAAIxN,GACT,mCAAqCK,EAASE,OAC9C,CAACP,GAAWyN,gBAAiBzN,GAAWoI,kBAAkB3O,KAAKiU,MAAMrN,EAASE,OAAS,KAAO,GAC9FF,EAASF,OACTE,EAASD,QACTC,IAPFkN,EAAQlN,EAUZ,CClBA,SAASsN,GAAYC,EAAcC,GACjCD,EAAeA,GAAgB,GAC/B,IAIIE,EAJEC,EAAQ,IAAInZ,MAAMgZ,GAClBI,EAAa,IAAIpZ,MAAMgZ,GACzBK,EAAO,EACPC,EAAO,EAKX,OAFAL,OAAcnX,IAARmX,EAAoBA,EAAM,IAEzB,SAAcM,GACnB,IAAMC,EAAMC,KAAKD,MAEXE,EAAYN,EAAWE,GAExBJ,IACHA,EAAgBM,GAGlBL,EAAME,GAAQE,EACdH,EAAWC,GAAQG,EAKnB,IAHA,IAAI9X,EAAI4X,EACJK,EAAa,EAEVjY,IAAM2X,GACXM,GAAcR,EAAMzX,KACpBA,GAAQsX,EASV,IANAK,GAAQA,EAAO,GAAKL,KAEPM,IACXA,GAAQA,EAAO,GAAKN,KAGlBQ,EAAMN,EAAgBD,GAA1B,CAIA,IAAMW,EAASF,GAAaF,EAAME,EAElC,OAAOE,EAAS/U,KAAKgV,MAAmB,IAAbF,EAAoBC,QAAU9X,CAJzD,EAMJ,CC9CA,SAASgY,GAASnb,EAAIob,GACpB,IAEIC,EACAC,EAHAC,EAAY,EACZC,EAAY,IAAOJ,EAIjBK,EAAS,SAACC,GAA2B,IAArBb,EAAG1a,UAAA+C,eAAAC,IAAAhD,UAAA,GAAAA,UAAG2a,GAAAA,KAAKD,MAC/BU,EAAYV,EACZQ,EAAW,KACPC,IACFK,aAAaL,GACbA,EAAQ,MAEVtb,EAAGE,MAAM,KAAMwb,IAqBjB,MAAO,CAlBW,WAEe,IAD/B,IAAMb,EAAMC,KAAKD,MACXI,EAASJ,EAAMU,EAAUpD,EAAAhY,UAAA+C,OAFXwY,EAAIra,IAAAA,MAAA8W,GAAAxU,EAAA,EAAAA,EAAAwU,EAAAxU,IAAJ+X,EAAI/X,GAAAxD,UAAAwD,GAGnBsX,GAAUO,EACbC,EAAOC,EAAMb,IAEbQ,EAAWK,EACNJ,IACHA,EAAQ3U,YAAW,WACjB2U,EAAQ,KACRG,EAAOJ,EACT,GAAGG,EAAYP,MAKP,WAAH,OAASI,GAAYI,EAAOJ,EAAS,EAGlD,CHrBApO,GAAMnE,SAAS+Q,GAAepN,GAAY,CACxCmN,YAAY,IIjBP,IAAMgC,GAAuB,SAACC,EAAUC,GAA+B,IAAbV,EAAIjb,UAAA+C,OAAA,QAAAC,IAAAhD,UAAA,GAAAA,UAAA,GAAG,EAClE4b,EAAgB,EACdC,EAAe5B,GAAY,GAAI,KAErC,OAAOe,IAAS,SAAA5G,GACd,IAAM0H,EAAS1H,EAAE0H,OACXC,EAAQ3H,EAAE4H,iBAAmB5H,EAAE2H,WAAQ/Y,EACvCiZ,EAAgBH,EAASF,EACzBM,EAAOL,EAAaI,GAG1BL,EAAgBE,EAEhB,IAAM1V,EAAI+V,EAAA,CACRL,OAAAA,EACAC,MAAAA,EACAK,SAAUL,EAASD,EAASC,OAAS/Y,EACrCqX,MAAO4B,EACPC,KAAMA,QAAclZ,EACpBqZ,UAAWH,GAAQH,GAVLD,GAAUC,GAUeA,EAAQD,GAAUI,OAAOlZ,EAChEsZ,MAAOlI,EACP4H,iBAA2B,MAATD,GACjBJ,EAAmB,WAAa,UAAW,GAG9CD,EAAStV,EACV,GAAE6U,EACL,EAEasB,GAAyB,SAACR,EAAOS,GAC5C,IAAMR,EAA4B,MAATD,EAEzB,MAAO,CAAC,SAACD,GAAM,OAAKU,EAAU,GAAG,CAC/BR,iBAAAA,EACAD,MAAAA,EACAD,OAAAA,GACA,EAAEU,EAAU,GAChB,EAEaC,GAAiB,SAAC5c,GAAE,OAAK,WAAA,IAAA,IAAAmY,EAAAhY,UAAA+C,OAAIwY,EAAIra,IAAAA,MAAA8W,GAAAxU,EAAA,EAAAA,EAAAwU,EAAAxU,IAAJ+X,EAAI/X,GAAAxD,UAAAwD,GAAA,OAAKsJ,GAAMrG,MAAK,WAAA,OAAM5G,EAAEE,WAAA,EAAIwb,KAAM,CAAA,ECzCjE9I,GAAAA,GAAST,sBAAyB,SAACK,EAAQqK,GAAM,OAAK,SAACzM,GAGpE,OAFAA,EAAM,IAAI0M,IAAI1M,EAAKwC,GAASJ,QAG1BA,EAAOuK,WAAa3M,EAAI2M,UACxBvK,EAAOwK,OAAS5M,EAAI4M,OACnBH,GAAUrK,EAAOyK,OAAS7M,EAAI6M,MAElC,CARgD,CAS/C,IAAIH,IAAIlK,GAASJ,QACjBI,GAASV,WAAa,kBAAkB9D,KAAKwE,GAASV,UAAUgL,YAC9D,WAAA,OAAM,CAAI,ECVCtK,GAAAA,GAAST,sBAGtB,CACEgL,MAAKA,SAAClY,EAAMiE,EAAOkU,EAASpP,EAAMqP,EAAQC,GACxC,IAAMC,EAAS,CAACtY,EAAO,IAAM6K,mBAAmB5G,IAEhD+D,GAAMvL,SAAS0b,IAAYG,EAAO7W,KAAK,WAAa,IAAIoU,KAAKsC,GAASI,eAEtEvQ,GAAMzL,SAASwM,IAASuP,EAAO7W,KAAK,QAAUsH,GAE9Cf,GAAMzL,SAAS6b,IAAWE,EAAO7W,KAAK,UAAY2W,IAEvC,IAAXC,GAAmBC,EAAO7W,KAAK,UAE/BsL,SAASuL,OAASA,EAAOrP,KAAK,KAC/B,EAEDuP,KAAI,SAACxY,GACH,IAAM8K,EAAQiC,SAASuL,OAAOxN,MAAM,IAAI2N,OAAO,aAAezY,EAAO,cACrE,OAAQ8K,EAAQ4N,mBAAmB5N,EAAM,IAAM,IAChD,EAED6N,OAAM,SAAC3Y,GACL+C,KAAKmV,MAAMlY,EAAM,GAAI6V,KAAKD,MAAQ,MACpC,GAMF,CACEsC,MAAKA,WAAK,EACVM,KAAI,WACF,OAAO,IACR,EACDG,OAAM,WAAI,GCxBC,SAASC,GAAcC,EAASC,GAC7C,OAAID,ICHG,8BAA8B1P,KDGP2P,GENjB,SAAqBD,EAASE,GAC3C,OAAOA,EACHF,EAAQpV,QAAQ,SAAU,IAAM,IAAMsV,EAAYtV,QAAQ,OAAQ,IAClEoV,CACN,CFGWG,CAAYH,EAASC,GAEvBA,CACT,CGfA,IAAMG,GAAkB,SAACvd,GAAK,OAAKA,aAAiBoV,GAAYpD,EAAQhS,CAAAA,EAAAA,GAAUA,CAAK,EAWxE,SAASwd,GAAYC,EAASC,GAE3CA,EAAUA,GAAW,GACrB,IAAMzR,EAAS,CAAA,EAEf,SAAS0R,EAAejS,EAAQ/F,EAAQ7B,EAAMwD,GAC5C,OAAIgF,GAAMrL,cAAcyK,IAAWY,GAAMrL,cAAc0E,GAC9C2G,GAAMnF,MAAMjH,KAAK,CAACoH,SAAAA,GAAWoE,EAAQ/F,GACnC2G,GAAMrL,cAAc0E,GACtB2G,GAAMnF,MAAM,CAAE,EAAExB,GACd2G,GAAM7L,QAAQkF,GAChBA,EAAOxF,QAETwF,CACT,CAGA,SAASiY,EAAoBjW,EAAGC,EAAG9D,EAAOwD,GACxC,OAAKgF,GAAM3L,YAAYiH,GAEX0E,GAAM3L,YAAYgH,QAAvB,EACEgW,OAAenb,EAAWmF,EAAG7D,EAAOwD,GAFpCqW,EAAehW,EAAGC,EAAG9D,EAAOwD,EAIvC,CAGA,SAASuW,EAAiBlW,EAAGC,GAC3B,IAAK0E,GAAM3L,YAAYiH,GACrB,OAAO+V,OAAenb,EAAWoF,EAErC,CAGA,SAASkW,EAAiBnW,EAAGC,GAC3B,OAAK0E,GAAM3L,YAAYiH,GAEX0E,GAAM3L,YAAYgH,QAAvB,EACEgW,OAAenb,EAAWmF,GAF1BgW,OAAenb,EAAWoF,EAIrC,CAGA,SAASmW,EAAgBpW,EAAGC,EAAG9D,GAC7B,OAAIA,KAAQ4Z,EACHC,EAAehW,EAAGC,GAChB9D,KAAQ2Z,EACVE,OAAenb,EAAWmF,QAD5B,CAGT,CAEA,IAAMqW,EAAW,CACfvO,IAAKoO,EACLlJ,OAAQkJ,EACRjY,KAAMiY,EACNV,QAASW,EACTlL,iBAAkBkL,EAClBhK,kBAAmBgK,EACnBG,iBAAkBH,EAClB3J,QAAS2J,EACTI,eAAgBJ,EAChBK,gBAAiBL,EACjBM,cAAeN,EACfnL,QAASmL,EACT9J,aAAc8J,EACd1J,eAAgB0J,EAChBzJ,eAAgByJ,EAChBO,iBAAkBP,EAClBQ,mBAAoBR,EACpBS,WAAYT,EACZxJ,iBAAkBwJ,EAClBvJ,cAAeuJ,EACfU,eAAgBV,EAChBW,UAAWX,EACXY,UAAWZ,EACXa,WAAYb,EACZc,YAAad,EACbe,WAAYf,EACZgB,iBAAkBhB,EAClBtJ,eAAgBuJ,EAChBlL,QAAS,SAAClL,EAAGC,EAAI9D,GAAI,OAAK8Z,EAAoBL,GAAgB5V,GAAI4V,GAAgB3V,GAAG9D,GAAM,EAAK,GASlG,OANAwI,GAAMpK,QAAQvC,OAAOiD,KAAKjD,OAAO6I,OAAO,GAAIiV,EAASC,KAAW,SAA4B5Z,GAC1F,IAAMqD,EAAQ6W,EAASla,IAAS8Z,EAC1BmB,EAAc5X,EAAMsW,EAAQ3Z,GAAO4Z,EAAQ5Z,GAAOA,GACvDwI,GAAM3L,YAAYoe,IAAgB5X,IAAU4W,IAAqB9R,EAAOnI,GAAQib,EACnF,IAEO9S,CACT,CChGe,ICMT8D,GAqCiBiP,GD3CRC,GAAA,SAAChT,GACd,IAeI6G,IAfEoM,EAAY1B,GAAY,CAAE,EAAEvR,GAE7BrG,EAAsEsZ,EAAtEtZ,KAAMwY,EAAgEc,EAAhEd,cAAe/J,EAAiD6K,EAAjD7K,eAAgBD,EAAiC8K,EAAjC9K,eAAgBvB,EAAiBqM,EAAjBrM,QAASsM,EAAQD,EAARC,KAenE,GAbAD,EAAUrM,QAAUA,EAAUuC,GAAavI,KAAKgG,GAEhDqM,EAAUzP,IAAMD,GAAS0N,GAAcgC,EAAU/B,QAAS+B,EAAUzP,KAAMxD,EAAOqD,OAAQrD,EAAOgS,kBAG5FkB,GACFtM,EAAQ1I,IAAI,gBAAiB,SAC3BiV,MAAMD,EAAKE,UAAY,IAAM,KAAOF,EAAKG,SAAWC,SAASpQ,mBAAmBgQ,EAAKG,WAAa,MAMlGhT,GAAM9F,WAAWZ,GACnB,GAAIqM,GAAST,uBAAyBS,GAASP,+BAC7CmB,EAAQK,oBAAe1Q,QAClB,IAAiD,KAA5CsQ,EAAcD,EAAQE,kBAA6B,CAE7D,IAAAzQ,EAA0BwQ,EAAcA,EAAYrI,MAAM,KAAK5I,KAAI,SAAAmD,GAAK,OAAIA,EAAM8C,MAAM,IAAEc,OAAO4W,SAAW,GAAEpY,MAAA9E,oBAAvGhC,EAAI8G,EAAA,GAAKwP,EAAMxP,EAAAjH,MAAA,GACtB0S,EAAQK,eAAe,CAAC5S,GAAQ,uBAAqBgF,OAAAma,EAAK7I,IAAQrJ,KAAK,MACzE,CAOF,GAAI0E,GAAST,wBACX4M,GAAiB9R,GAAMxL,WAAWsd,KAAmBA,EAAgBA,EAAcc,IAE/Ed,IAAoC,IAAlBA,GAA2BsB,GAAgBR,EAAUzP,MAAO,CAEhF,IAAMkQ,EAAYtL,GAAkBD,GAAkBwL,GAAQ9C,KAAK1I,GAE/DuL,GACF9M,EAAQ1I,IAAIkK,EAAgBsL,EAEhC,CAGF,OAAOT,CACR,EE1CDW,GAFwD,oBAAnBC,gBAEG,SAAU7T,GAChD,OAAO,IAAI8T,SAAQ,SAA4B1G,EAASC,GACtD,IAII0G,EACAC,EAAiBC,EACjBC,EAAaC,EANXC,EAAUpB,GAAchT,GAC1BqU,EAAcD,EAAQza,KACpB2a,EAAiBnL,GAAavI,KAAKwT,EAAQxN,SAASkG,YACrD/E,EAAsDqM,EAAtDrM,aAAcqK,EAAwCgC,EAAxChC,iBAAkBC,EAAsB+B,EAAtB/B,mBAKrC,SAAS7U,IACP0W,GAAeA,IACfC,GAAiBA,IAEjBC,EAAQzB,aAAeyB,EAAQzB,YAAY4B,YAAYR,GAEvDK,EAAQI,QAAUJ,EAAQI,OAAOC,oBAAoB,QAASV,EAChE,CAEA,IAAI9T,EAAU,IAAI4T,eAOlB,SAASa,IACP,GAAKzU,EAAL,CAIA,IAAM0U,EAAkBxL,GAAavI,KACnC,0BAA2BX,GAAWA,EAAQ2U,yBAahDzH,IAAO,SAAkB7Q,GACvB8Q,EAAQ9Q,GACRkB,GACF,IAAG,SAAiBiN,GAClB4C,EAAO5C,GACPjN,GACD,GAfgB,CACf7D,KAHoBoO,GAAiC,SAAjBA,GAA4C,SAAjBA,EACxC9H,EAAQC,SAA/BD,EAAQ4U,aAGRzU,OAAQH,EAAQG,OAChB0U,WAAY7U,EAAQ6U,WACpBlO,QAAS+N,EACT3U,OAAAA,EACAC,QAAAA,IAYFA,EAAU,IAzBV,CA0BF,CAqFA,GAvHAA,EAAQ8U,KAAKX,EAAQ1L,OAAO9P,cAAewb,EAAQ5Q,KAAK,GAGxDvD,EAAQiI,QAAUkM,EAAQlM,QAiCtB,cAAejI,EAEjBA,EAAQyU,UAAYA,EAGpBzU,EAAQ+U,mBAAqB,WACtB/U,GAAkC,IAAvBA,EAAQgV,aAQD,IAAnBhV,EAAQG,QAAkBH,EAAQiV,aAAwD,IAAzCjV,EAAQiV,YAAY/X,QAAQ,WAKjFpD,WAAW2a,IAKfzU,EAAQkV,QAAU,WACXlV,IAILoN,EAAO,IAAIxN,GAAW,kBAAmBA,GAAWuV,aAAcpV,EAAQC,IAG1EA,EAAU,OAIZA,EAAQoV,QAAU,WAGhBhI,EAAO,IAAIxN,GAAW,gBAAiBA,GAAWyV,YAAatV,EAAQC,IAGvEA,EAAU,MAIZA,EAAQsV,UAAY,WAClB,IAAIC,EAAsBpB,EAAQlM,QAAU,cAAgBkM,EAAQlM,QAAU,cAAgB,mBACxFzB,EAAe2N,EAAQ3N,cAAgB/B,GACzC0P,EAAQoB,sBACVA,EAAsBpB,EAAQoB,qBAEhCnI,EAAO,IAAIxN,GACT2V,EACA/O,EAAa5B,oBAAsBhF,GAAW4V,UAAY5V,GAAWuV,aACrEpV,EACAC,IAGFA,EAAU,WAII1J,IAAhB8d,GAA6BC,EAAerN,eAAe,MAGvD,qBAAsBhH,GACxBI,GAAMpK,QAAQqe,EAAehU,UAAU,SAA0BrL,EAAKyB,GACpEuJ,EAAQyV,iBAAiBhf,EAAKzB,EAChC,IAIGoL,GAAM3L,YAAY0f,EAAQlC,mBAC7BjS,EAAQiS,kBAAoBkC,EAAQlC,iBAIlCnK,GAAiC,SAAjBA,IAClB9H,EAAQ8H,aAAeqM,EAAQrM,cAI7BsK,EAAoB,CAAA,IAC8DsD,EAAAhgB,EAA9CqZ,GAAqBqD,GAAoB,GAAK,GAAlF4B,EAAiB0B,EAAA,GAAExB,EAAawB,EAAA,GAClC1V,EAAQzG,iBAAiB,WAAYya,EACvC,CAGA,GAAI7B,GAAoBnS,EAAQ2V,OAAQ,CAAA,IACkCC,EAAAlgB,EAAtCqZ,GAAqBoD,GAAiB,GAAtE4B,EAAe6B,EAAA,GAAE3B,EAAW2B,EAAA,GAE9B5V,EAAQ2V,OAAOpc,iBAAiB,WAAYwa,GAE5C/T,EAAQ2V,OAAOpc,iBAAiB,UAAW0a,EAC7C,EAEIE,EAAQzB,aAAeyB,EAAQI,UAGjCT,EAAa,SAAA+B,GACN7V,IAGLoN,GAAQyI,GAAUA,EAAOzhB,KAAO,IAAI4Y,GAAc,KAAMjN,EAAQC,GAAW6V,GAC3E7V,EAAQ8V,QACR9V,EAAU,OAGZmU,EAAQzB,aAAeyB,EAAQzB,YAAYqD,UAAUjC,GACjDK,EAAQI,SACVJ,EAAQI,OAAOyB,QAAUlC,IAAeK,EAAQI,OAAOhb,iBAAiB,QAASua,KAIrF,ICvLkCvQ,EAC9BL,EDsLEgN,GCvL4B3M,EDuLH4Q,EAAQ5Q,KCtLnCL,EAAQ,4BAA4BtF,KAAK2F,KAC/BL,EAAM,IAAM,IDuLtBgN,IAAsD,IAA1CnK,GAASd,UAAU/H,QAAQgT,GACzC9C,EAAO,IAAIxN,GAAW,wBAA0BsQ,EAAW,IAAKtQ,GAAWyN,gBAAiBtN,IAM9FC,EAAQiW,KAAK7B,GAAe,KAC9B,GACF,EErJA8B,GA3CuB,SAACC,EAASlO,GAC/B,IAAO5R,GAAW8f,EAAUA,EAAUA,EAAQzZ,OAAO4W,SAAW,IAAzDjd,OAEP,GAAI4R,GAAW5R,EAAQ,CACrB,IAEI2f,EAFAI,EAAa,IAAIC,gBAIfnB,EAAU,SAAUoB,GACxB,IAAKN,EAAS,CACZA,GAAU,EACV1B,IACA,IAAM9J,EAAM8L,aAAkBpY,MAAQoY,EAASnb,KAAKmb,OACpDF,EAAWN,MAAMtL,aAAe5K,GAAa4K,EAAM,IAAIwC,GAAcxC,aAAetM,MAAQsM,EAAI3K,QAAU2K,GAC5G,GAGEiE,EAAQxG,GAAWnO,YAAW,WAChC2U,EAAQ,KACRyG,EAAQ,IAAItV,GAAU,WAAAxG,OAAY6O,EAAO,mBAAmBrI,GAAW4V,WACxE,GAAEvN,GAEGqM,EAAc,WACd6B,IACF1H,GAASK,aAAaL,GACtBA,EAAQ,KACR0H,EAAQngB,SAAQ,SAAAue,GACdA,EAAOD,YAAcC,EAAOD,YAAYY,GAAWX,EAAOC,oBAAoB,QAASU,EACzF,IACAiB,EAAU,OAIdA,EAAQngB,SAAQ,SAACue,GAAM,OAAKA,EAAOhb,iBAAiB,QAAS2b,MAE7D,IAAOX,EAAU6B,EAAV7B,OAIP,OAFAA,EAAOD,YAAc,WAAA,OAAMlU,GAAMrG,KAAKua,EAAY,EAE3CC,CACT,CACF,EC5CagC,GAAWC,IAAAC,MAAG,SAAdF,EAAyBG,EAAOC,GAAS,IAAA/f,EAAAggB,EAAAC,EAAA,OAAAL,IAAAM,MAAA,SAAAC,GAAA,cAAAA,EAAAC,KAAAD,EAAAzZ,MAAA,KAAA,EAC1B,GAAtB1G,EAAM8f,EAAMO,WAEXN,KAAa/f,EAAM+f,GAAS,CAAAI,EAAAzZ,KAAA,EAAA,KAAA,CAC/B,OAD+ByZ,EAAAzZ,KAAA,EACzBoZ,EAAK,KAAA,EAAA,OAAAK,EAAAG,OAAA,UAAA,KAAA,EAITN,EAAM,EAAC,KAAA,EAAA,KAGJA,EAAMhgB,GAAG,CAAAmgB,EAAAzZ,KAAA,GAAA,KAAA,CAEd,OADAuZ,EAAMD,EAAMD,EAAUI,EAAAzZ,KAAA,GAChBoZ,EAAMziB,MAAM2iB,EAAKC,GAAI,KAAA,GAC3BD,EAAMC,EAAIE,EAAAzZ,KAAA,EAAA,MAAA,KAAA,GAAA,IAAA,MAAA,OAAAyZ,EAAAI,OAAA,GAdDZ,EAAW,IAkBXa,GAAS,WAAA,IAAAhhB,EAAAihB,EAAAb,IAAAC,MAAG,SAAAa,EAAiBC,EAAUZ,GAAS,IAAAa,EAAAC,EAAAC,EAAAvN,EAAAD,EAAAwM,EAAA,OAAAF,IAAAM,MAAA,SAAAa,GAAA,cAAAA,EAAAX,KAAAW,EAAAra,MAAA,KAAA,EAAAka,GAAA,EAAAC,GAAA,EAAAE,EAAAX,KAAA,EAAA7M,EAAAyN,EACjCC,GAAWN,IAAS,KAAA,EAAA,OAAAI,EAAAra,KAAA,EAAAwa,EAAA3N,EAAA7M,QAAA,KAAA,EAAA,KAAAka,IAAAtN,EAAAyN,EAAAI,MAAAxa,MAAA,CAAAoa,EAAAra,KAAA,GAAA,KAAA,CAC5C,OADeoZ,EAAKxM,EAAA7N,MACpBsb,EAAAK,cAAAC,EAAAL,EAAOrB,GAAYG,EAAOC,KAAU,KAAA,GAAA,KAAA,EAAAa,GAAA,EAAAG,EAAAra,KAAA,EAAA,MAAA,KAAA,GAAAqa,EAAAra,KAAA,GAAA,MAAA,KAAA,GAAAqa,EAAAX,KAAA,GAAAW,EAAAO,GAAAP,EAAA,MAAA,GAAAF,GAAA,EAAAC,EAAAC,EAAAO,GAAA,KAAA,GAAA,GAAAP,EAAAX,KAAA,GAAAW,EAAAX,KAAA,IAAAQ,GAAA,MAAArN,EAAA,OAAA,CAAAwN,EAAAra,KAAA,GAAA,KAAA,CAAA,OAAAqa,EAAAra,KAAA,GAAAwa,EAAA3N,EAAA,UAAA,KAAA,GAAA,GAAAwN,EAAAX,KAAA,IAAAS,EAAA,CAAAE,EAAAra,KAAA,GAAA,KAAA,CAAA,MAAAoa,EAAA,KAAA,GAAA,OAAAC,EAAAQ,OAAA,IAAA,KAAA,GAAA,OAAAR,EAAAQ,OAAA,IAAA,KAAA,GAAA,IAAA,MAAA,OAAAR,EAAAR,OAAA,GAAAG,EAAA,KAAA,CAAA,CAAA,EAAA,GAAA,GAAA,IAAA,CAAA,GAAA,CAAA,GAAA,KAEvC,KAAA,OAAA,SAJqBc,EAAAC,GAAA,OAAAjiB,EAAA/C,MAAA8H,KAAA7H,UAAA,CAAA,CAAA,GAMhBukB,GAAU,WAAA,IAAA3c,EAAAmc,EAAAb,IAAAC,MAAG,SAAA6B,EAAiBC,GAAM,IAAAC,EAAAC,EAAAlb,EAAAlB,EAAA,OAAAma,IAAAM,MAAA,SAAA4B,GAAA,cAAAA,EAAA1B,KAAA0B,EAAApb,MAAA,KAAA,EAAA,IACpCib,EAAOtjB,OAAO0jB,eAAc,CAAAD,EAAApb,KAAA,EAAA,KAAA,CAC9B,OAAAob,EAAAV,cAAAC,EAAAL,EAAOW,IAAM,KAAA,GAAA,KAAA,EAAA,OAAAG,EAAAxB,OAAA,UAAA,KAAA,EAITsB,EAASD,EAAOK,YAAWF,EAAA1B,KAAA,EAAA,KAAA,EAAA,OAAA0B,EAAApb,KAAA,EAAAwa,EAGDU,EAAO5H,QAAM,KAAA,EAAvB,GAAuB6H,EAAAC,EAAAX,KAAlCxa,EAAIkb,EAAJlb,KAAMlB,EAAKoc,EAALpc,OACTkB,EAAI,CAAAmb,EAAApb,KAAA,GAAA,KAAA,CAAA,OAAAob,EAAAxB,OAAA,QAAA,IAAA,KAAA,GAGR,OAHQwB,EAAApb,KAAA,GAGFjB,EAAK,KAAA,GAAAqc,EAAApb,KAAA,EAAA,MAAA,KAAA,GAAA,OAAAob,EAAA1B,KAAA,GAAA0B,EAAApb,KAAA,GAAAwa,EAGPU,EAAO3C,UAAQ,KAAA,GAAA,OAAA6C,EAAAP,OAAA,IAAA,KAAA,GAAA,IAAA,MAAA,OAAAO,EAAAvB,OAAA,GAAAmB,EAAA,KAAA,CAAA,CAAA,EAAA,CAAA,GAAA,KAExB,KAAA,OAlBKT,SAAUgB,GAAA,OAAA3d,EAAA7H,MAAA8H,KAAA7H,UAAA,CAAA,CAAA,GAoBHwlB,GAAc,SAACP,EAAQ5B,EAAWoC,EAAYC,GACzD,IAGIzb,EAHEpI,EAAWiiB,GAAUmB,EAAQ5B,GAE/BhJ,EAAQ,EAERsL,EAAY,SAACvR,GACVnK,IACHA,GAAO,EACPyb,GAAYA,EAAStR,KAIzB,OAAO,IAAIwR,eAAe,CAClBC,KAAI,SAAC/C,GAAY,OAAAgD,EAAA5C,IAAAC,eAAA4C,IAAA,IAAAC,EAAAC,EAAAld,EAAAzF,EAAA4iB,EAAA,OAAAhD,IAAAM,MAAA,SAAA2C,GAAA,cAAAA,EAAAzC,KAAAyC,EAAAnc,MAAA,KAAA,EAAA,OAAAmc,EAAAzC,KAAA,EAAAyC,EAAAnc,KAAA,EAESnI,EAASmI,OAAM,KAAA,EAAzB,GAAyBgc,EAAAG,EAAA1B,KAApCxa,EAAI+b,EAAJ/b,KAAMlB,EAAKid,EAALjd,OAETkB,EAAI,CAAAkc,EAAAnc,KAAA,GAAA,KAAA,CAEa,OADpB2b,IACC7C,EAAWsD,QAAQD,EAAAvC,OAAA,UAAA,KAAA,GAIjBtgB,EAAMyF,EAAM4a,WACZ8B,IACES,EAAc7L,GAAS/W,EAC3BmiB,EAAWS,IAEbpD,EAAWuD,QAAQ,IAAIniB,WAAW6E,IAAQod,EAAAnc,KAAA,GAAA,MAAA,KAAA,GAE3B,MAF2Bmc,EAAAzC,KAAA,GAAAyC,EAAAG,GAAAH,EAAA,MAAA,GAE1CR,EAASQ,EAAAG,IAAMH,EAAAG,GAAA,KAAA,GAAA,IAAA,MAAA,OAAAH,EAAAtC,OAAA,GAAAkC,EAAA,KAAA,CAAA,CAAA,EAAA,KAAA,IAjBID,EAoBtB,EACDvD,OAAM,SAACS,GAEL,OADA2C,EAAU3C,GACHnhB,EAAe,QACxB,GACC,CACD0kB,cAAe,GAEnB,EJ5EMC,GAAoC,mBAAVC,OAA2C,mBAAZC,SAA8C,mBAAbC,SAC1FC,GAA4BJ,IAA8C,mBAAnBZ,eAGvDiB,GAAaL,KAA4C,mBAAhBM,aACzCvW,GAA0C,IAAIuW,YAAlC,SAACrmB,GAAG,OAAK8P,GAAQd,OAAOhP,EAAI,GAAoB,WAAA,IAAAqC,EAAAgjB,EAAA5C,IAAAC,MAC9D,SAAAa,EAAOvjB,GAAG,OAAAyiB,IAAAM,MAAA,SAAAC,GAAA,cAAAA,EAAAC,KAAAD,EAAAzZ,MAAA,KAAA,EAAmB,OAAnByZ,EAAA6C,GAASpiB,WAAUuf,EAAAzZ,KAAA,EAAO,IAAI2c,SAASlmB,GAAKsmB,cAAa,KAAA,EAAA,OAAAtD,EAAAmB,GAAAnB,EAAAgB,KAAAhB,EAAAG,OAAAH,SAAAA,IAAAA,EAAA6C,GAAA7C,EAAAmB,KAAA,KAAA,EAAA,IAAA,MAAA,OAAAnB,EAAAI,OAAA,GAAAG,EAAC,KAAA,OAAA,SAAAc,GAAA,OAAAhiB,EAAA/C,MAAA8H,KAAA7H,UAAA,CAAA,KAGlEiO,GAAO,SAACpO,GACZ,IAAI,IAAAmY,IAAAA,EAAAhY,UAAA+C,OADewY,MAAIra,MAAA8W,EAAAA,EAAAA,OAAAxU,EAAA,EAAAA,EAAAwU,EAAAxU,IAAJ+X,EAAI/X,EAAAxD,GAAAA,UAAAwD,GAErB,QAAS3D,EAAEE,WAAA,EAAIwb,EAGjB,CAFE,MAAOnH,GACP,OAAO,CACT,CACF,EAEM4S,GAAwBJ,IAA6B3Y,IAAK,WAC9D,IAAIgZ,GAAiB,EAEfC,EAAiB,IAAIR,QAAQjU,GAASJ,OAAQ,CAClD8U,KAAM,IAAIvB,eACVzQ,OAAQ,OACJiS,aAEF,OADAH,GAAiB,EACV,MACT,IACC5T,QAAQgU,IAAI,gBAEf,OAAOJ,IAAmBC,CAC5B,IAIMI,GAAyBV,IAC7B3Y,IAAK,WAAA,OAAMnB,GAAMxK,iBAAiB,IAAIqkB,SAAS,IAAIQ,KAAK,IAGpDI,GAAY,CAChBtC,OAAQqC,IAA2B,SAAC9H,GAAG,OAAKA,EAAI2H,IAAI,GAGtDX,KAAuBhH,GAOpB,IAAImH,SANL,CAAC,OAAQ,cAAe,OAAQ,WAAY,UAAUjkB,SAAQ,SAAA5B,IAC3DymB,GAAUzmB,KAAUymB,GAAUzmB,GAAQgM,GAAMxL,WAAWke,GAAI1e,IAAS,SAAC0e,GAAG,OAAKA,EAAI1e,IAAO,EACvF,SAAC0mB,EAAG/a,GACF,MAAM,IAAIH,GAAUxG,kBAAAA,OAAmBhF,EAA0BwL,sBAAAA,GAAWmb,gBAAiBhb,EAC/F,EACJ,KAGF,IAAMib,GAAa,WAAA,IAAA9f,EAAAke,EAAA5C,IAAAC,MAAG,SAAA6B,EAAOmC,GAAI,IAAAQ,EAAA,OAAAzE,IAAAM,MAAA,SAAAa,GAAA,cAAAA,EAAAX,KAAAW,EAAAra,MAAA,KAAA,EAAA,GACnB,MAARmd,EAAY,CAAA9C,EAAAra,KAAA,EAAA,KAAA,CAAA,OAAAqa,EAAAT,OAAA,SACP,GAAC,KAAA,EAAA,IAGP9W,GAAM9K,OAAOmlB,GAAK,CAAA9C,EAAAra,KAAA,EAAA,KAAA,CAAA,OAAAqa,EAAAT,OACZuD,SAAAA,EAAKvb,MAAI,KAAA,EAAA,IAGfkB,GAAMhB,oBAAoBqb,GAAK,CAAA9C,EAAAra,KAAA,EAAA,KAAA,CAI9B,OAHI2d,EAAW,IAAIjB,QAAQjU,GAASJ,OAAQ,CAC5C8C,OAAQ,OACRgS,KAAAA,IACA9C,EAAAra,KAAA,EACY2d,EAASZ,cAAa,KAAA,EAYN,KAAA,GAAA,OAAA1C,EAAAT,OAAA,SAAAS,EAAAI,KAAEd,YAZgB,KAAA,EAAA,IAG/C7W,GAAM1F,kBAAkB+f,KAASra,GAAM1L,cAAc+lB,GAAK,CAAA9C,EAAAra,KAAA,GAAA,KAAA,CAAA,OAAAqa,EAAAT,OACpDuD,SAAAA,EAAKxD,YAAU,KAAA,GAKvB,GAFE7W,GAAM5K,kBAAkBilB,KACzBA,GAAc,KAGbra,GAAMzL,SAAS8lB,GAAK,CAAA9C,EAAAra,KAAA,GAAA,KAAA,CAAA,OAAAqa,EAAAra,KAAA,GACP6c,GAAWM,GAAiB,KAAA,GAAA,IAAA,MAAA,OAAA9C,EAAAR,OAAA,GAAAmB,EAE7C,KAAA,OA5BK0C,SAAa3C,GAAA,OAAAnd,EAAA7H,MAAA8H,KAAA7H,UAAA,CAAA,CAAA,GA8Bb4nB,GAAiB,WAAA,IAAAvf,EAAAyd,EAAA5C,IAAAC,MAAG,SAAA4C,EAAO1S,EAAS8T,GAAI,IAAApkB,EAAA,OAAAmgB,IAAAM,MAAA,SAAA4B,GAAA,cAAAA,EAAA1B,KAAA0B,EAAApb,MAAA,KAAA,EACmB,OAAzDjH,EAAS+J,GAAMvB,eAAe8H,EAAQwU,oBAAmBzC,EAAAxB,OAAA,SAE9C,MAAV7gB,EAAiB2kB,GAAcP,GAAQpkB,GAAM,KAAA,EAAA,IAAA,MAAA,OAAAqiB,EAAAvB,OAAA,GAAAkC,EACrD,KAAA,OAAA,SAJsBR,EAAAuC,GAAA,OAAAzf,EAAAtI,MAAA8H,KAAA7H,UAAA,CAAA,CAAA,GAMRwmB,GAAAA,IAAgB,WAAA,IAAAniB,EAAAyhB,EAAA5C,IAAAC,MAAK,SAAA4E,EAAOtb,GAAM,IAAAub,EAAA/X,EAAAkF,EAAA/O,EAAA6a,EAAA7B,EAAAzK,EAAAmK,EAAAD,EAAArK,EAAAnB,EAAA4U,EAAAtJ,EAAAuJ,EAAAC,EAAAzb,EAAAsU,EAAAoH,EAAAT,EAAAU,EAAAC,EAAAC,EAAA9C,EAAA+C,EAAAC,EAAA9b,EAAA+b,EAAAta,EAAAua,EAAAziB,EAAA0iB,EAAAC,EAAAC,EAAAC,EAAA,OAAA7F,IAAAM,MAAA,SAAA2C,GAAA,cAAAA,EAAAzC,KAAAyC,EAAAnc,MAAA,KAAA,EA8BuC,GA9BvCge,EAc3CvI,GAAchT,GAZhBwD,EAAG+X,EAAH/X,IACAkF,EAAM6S,EAAN7S,OACA/O,EAAI4hB,EAAJ5hB,KACA6a,EAAM+G,EAAN/G,OACA7B,EAAW4I,EAAX5I,YACAzK,EAAOqT,EAAPrT,QACAmK,EAAkBkJ,EAAlBlJ,mBACAD,EAAgBmJ,EAAhBnJ,iBACArK,EAAYwT,EAAZxT,aACAnB,EAAO2U,EAAP3U,QAAO4U,EAAAD,EACPrJ,gBAAAA,OAAkB,IAAHsJ,EAAG,cAAaA,EAC/BC,EAAYF,EAAZE,aAGF1T,EAAeA,GAAgBA,EAAe,IAAI5T,cAAgB,OAE9DunB,EAAiBa,GAAe,CAAC/H,EAAQ7B,GAAeA,EAAY6J,iBAAkBtU,GAIpFqM,EAAcmH,GAAkBA,EAAenH,aAAgB,WACjEmH,EAAenH,eACjBmF,EAAAzC,KAAA,EAAAyC,EAAAG,GAMEzH,GAAoBmI,IAAoC,QAAX7R,GAA+B,SAAXA,GAAiBgR,EAAAG,GAAA,CAAAH,EAAAnc,KAAA,GAAA,KAAA,CAAA,OAAAmc,EAAAnc,KAAA,EACpD4d,GAAkBvU,EAASjN,GAAK,KAAA,EAAA+f,EAAAvB,GAA7DwD,EAAoBjC,EAAA1B,KAAA0B,EAAAG,GAA+C,IAA/CH,EAAAvB,GAAgD,KAAA,GAAA,IAAAuB,EAAAG,GAAA,CAAAH,EAAAnc,KAAA,GAAA,KAAA,CAEjE2d,EAAW,IAAIjB,QAAQzW,EAAK,CAC9BkF,OAAQ,OACRgS,KAAM/gB,EACNghB,OAAQ,SAKNta,GAAM9F,WAAWZ,KAAUiiB,EAAoBV,EAAStU,QAAQ8E,IAAI,kBACtE9E,EAAQK,eAAe2U,GAGrBV,EAASR,OAAMmB,EACW/L,GAC1B6L,EACA3M,GAAqBgB,GAAeoC,KACrC0J,EAAAnmB,EAAAkmB,EAAA,GAHM7C,EAAU8C,EAAA,GAAEC,EAAKD,EAAA,GAKxBniB,EAAOof,GAAYmC,EAASR,KA1GT,MA0GmC1B,EAAY+C,IACnE,KAAA,GAkBA,OAfE1b,GAAMzL,SAASsd,KAClBA,EAAkBA,EAAkB,UAAY,QAK5C8J,EAAyB,gBAAiB/B,QAAQtmB,UACxDsM,EAAU,IAAIga,QAAQzW,EAAGuC,EAAAA,EAAA,CAAA,EACpB0V,GAAY,GAAA,CACfjH,OAAQkH,EACRhT,OAAQA,EAAO9P,cACfgO,QAASA,EAAQkG,YAAYxM,SAC7Boa,KAAM/gB,EACNghB,OAAQ,OACR8B,YAAaT,EAAyB9J,OAAkB3b,KACvDmjB,EAAAnc,KAAA,GAEkByc,MAAM/Z,GAAQ,KAAA,GA2BG,OA3BlCC,EAAQwZ,EAAA1B,KAENiE,EAAmBpB,KAA4C,WAAjB9S,GAA8C,aAAjBA,GAE7E8S,KAA2BxI,GAAuB4J,GAAoB1H,KAClE5S,EAAU,CAAA,EAEhB,CAAC,SAAU,aAAc,WAAW1L,SAAQ,SAAA4B,GAC1C8J,EAAQ9J,GAAQqI,EAASrI,EAC3B,IAEMqkB,EAAwB7b,GAAMvB,eAAeoB,EAAS0G,QAAQ8E,IAAI,mBAAkBjS,EAE9D4Y,GAAsBvC,GAChDoM,EACAlN,GAAqBgB,GAAeqC,IAAqB,KACtD,GAAE8J,EAAAxmB,EAAA8D,EAHAuf,GAAAA,EAAUmD,EAAEJ,GAAAA,EAAKI,EAAA,GAKxBjc,EAAW,IAAIga,SACbnB,GAAY7Y,EAASwa,KAlJF,MAkJ4B1B,GAAY,WACzD+C,GAASA,IACTxH,GAAeA,OAEjB5S,IAIJoG,EAAeA,GAAgB,OAAO2R,EAAAnc,KAAA,GAEbud,GAAUza,GAAMvJ,QAAQgkB,GAAW/S,IAAiB,QAAQ7H,EAAUF,GAAO,KAAA,GAEpD,OAF9Csc,EAAY5C,EAAA1B,MAEfiE,GAAoB1H,GAAeA,IAAcmF,EAAAnc,KAAA,GAErC,IAAIuW,SAAQ,SAAC1G,EAASC,GACjCF,GAAOC,EAASC,EAAQ,CACtB1T,KAAM2iB,EACN1V,QAASuC,GAAavI,KAAKV,EAAS0G,SACpCxG,OAAQF,EAASE,OACjB0U,WAAY5U,EAAS4U,WACrB9U,OAAAA,EACAC,QAAAA,GAEJ,IAAE,KAAA,GAAA,OAAAyZ,EAAAvC,OAAAuC,SAAAA,EAAA1B,MAAA,KAAA,GAE2B,GAF3B0B,EAAAzC,KAAA,GAAAyC,EAAAgD,GAAAhD,EAAA,MAAA,GAEFnF,GAAeA,KAEXmF,EAAAgD,IAAoB,cAAbhD,EAAAgD,GAAIrkB,OAAwB,SAASmJ,KAAKkY,EAAAgD,GAAI5c,SAAQ,CAAA4Z,EAAAnc,KAAA,GAAA,KAAA,CAAA,MACzD7J,OAAO6I,OACX,IAAIsD,GAAW,gBAAiBA,GAAWyV,YAAatV,EAAQC,GAChE,CACEe,MAAO0Y,EAAAgD,GAAI1b,OAAK0Y,EAAAgD,KAEnB,KAAA,GAAA,MAGG7c,GAAWe,KAAI8Y,EAAAgD,GAAMhD,EAAAgD,IAAOhD,EAAAgD,GAAI3c,KAAMC,EAAQC,GAAQ,KAAA,GAAA,IAAA,MAAA,OAAAyZ,EAAAtC,OAAA,GAAAkE,EAAA,KAAA,CAAA,CAAA,EAAA,KAE/D,KAAA,OAAA,SAAAqB,GAAA,OAAA/kB,EAAAtE,MAAA8H,KAAA7H,UAAA,CAAA,IK5NKqpB,GAAgB,CACpBC,KCNa,KDObC,IAAKlJ,GACLoG,MAAO+C,IAGJ3iB,GAACnE,QAAQ2mB,IAAe,SAACxpB,EAAIkJ,GAChC,GAAIlJ,EAAI,CACN,IACEM,OAAO2I,eAAejJ,EAAI,OAAQ,CAACkJ,MAAAA,GAEnC,CADA,MAAOqL,GACP,CAEFjU,OAAO2I,eAAejJ,EAAI,cAAe,CAACkJ,MAAAA,GAC5C,CACF,IAEA,IAAM0gB,GAAe,SAACzG,GAAM,MAAAld,KAAAA,OAAUkd,EAAM,EAEtC0G,GAAmB,SAACvW,GAAO,OAAKrG,GAAMxL,WAAW6R,IAAwB,OAAZA,IAAgC,IAAZA,CAAiB,EAEzFwW,GACD,SAACA,GASX,IANA,IACIC,EACAzW,EAFGpQ,GAFP4mB,EAAW7c,GAAM7L,QAAQ0oB,GAAYA,EAAW,CAACA,IAE1C5mB,OAID8mB,EAAkB,CAAA,EAEfjnB,EAAI,EAAGA,EAAIG,EAAQH,IAAK,CAE/B,IAAIqO,OAAE,EAIN,GAFAkC,EAHAyW,EAAgBD,EAAS/mB,IAKpB8mB,GAAiBE,SAGJ5mB,KAFhBmQ,EAAUkW,IAAepY,EAAKvH,OAAOkgB,IAAgBhpB,gBAGnD,MAAM,IAAI0L,GAAU,oBAAAxG,OAAqBmL,QAI7C,GAAIkC,EACF,MAGF0W,EAAgB5Y,GAAM,IAAMrO,GAAKuQ,CACnC,CAEA,IAAKA,EAAS,CAEZ,IAAM2W,EAAU3pB,OAAO4S,QAAQ8W,GAC5BxnB,KAAI,SAAAS,GAAA,IAAA8E,EAAAxF,EAAAU,EAAA,GAAEmO,EAAErJ,EAAA,GAAEmiB,EAAKniB,EAAA,GAAA,MAAM,WAAA9B,OAAWmL,EAC9B8Y,OAAU,IAAVA,EAAkB,sCAAwC,gCAAgC,IAO/F,MAAM,IAAIzd,GACR,yDALMvJ,EACL+mB,EAAQ/mB,OAAS,EAAI,YAAc+mB,EAAQznB,IAAIonB,IAAc1b,KAAK,MAAQ,IAAM0b,GAAaK,EAAQ,IACtG,2BAIA,kBAEJ,CAEA,OAAO3W,CACR,EE5DH,SAAS6W,GAA6Bvd,GAKpC,GAJIA,EAAO2S,aACT3S,EAAO2S,YAAY6K,mBAGjBxd,EAAOwU,QAAUxU,EAAOwU,OAAOyB,QACjC,MAAM,IAAIhJ,GAAc,KAAMjN,EAElC,CASe,SAASyd,GAAgBzd,GAiBtC,OAhBAud,GAA6Bvd,GAE7BA,EAAO4G,QAAUuC,GAAavI,KAAKZ,EAAO4G,SAG1C5G,EAAOrG,KAAOiT,GAAc3Y,KAC1B+L,EACAA,EAAO2G,mBAGgD,IAArD,CAAC,OAAQ,MAAO,SAASxJ,QAAQ6C,EAAO0I,SAC1C1I,EAAO4G,QAAQK,eAAe,qCAAqC,GAGrDiW,GAAoBld,EAAO0G,SAAWF,GAASE,QAExDA,CAAQ1G,GAAQJ,MAAK,SAA6BM,GAYvD,OAXAqd,GAA6Bvd,GAG7BE,EAASvG,KAAOiT,GAAc3Y,KAC5B+L,EACAA,EAAO6H,kBACP3H,GAGFA,EAAS0G,QAAUuC,GAAavI,KAAKV,EAAS0G,SAEvC1G,CACT,IAAG,SAA4BqW,GAe7B,OAdKxJ,GAASwJ,KACZgH,GAA6Bvd,GAGzBuW,GAAUA,EAAOrW,WACnBqW,EAAOrW,SAASvG,KAAOiT,GAAc3Y,KACnC+L,EACAA,EAAO6H,kBACP0O,EAAOrW,UAETqW,EAAOrW,SAAS0G,QAAUuC,GAAavI,KAAK2V,EAAOrW,SAAS0G,WAIzDkN,QAAQzG,OAAOkJ,EACxB,GACF,CChFO,IAAMmH,GAAU,QCKjBC,GAAa,CAAA,EAGnB,CAAC,SAAU,UAAW,SAAU,WAAY,SAAU,UAAU1nB,SAAQ,SAAC5B,EAAM8B,GAC7EwnB,GAAWtpB,GAAQ,SAAmBN,GACpC,OAAOQ,EAAOR,KAAUM,GAAQ,KAAO8B,EAAI,EAAI,KAAO,KAAO9B,EAEjE,IAEA,IAAMupB,GAAqB,CAAA,EAWjBC,GAACpX,aAAe,SAAsBqX,EAAWC,EAASje,GAClE,SAASke,EAAcC,EAAKC,GAC1B,MAAO,uCAAoDD,EAAM,IAAOC,GAAQpe,EAAU,KAAOA,EAAU,GAC7G,CAGA,OAAO,SAACxD,EAAO2hB,EAAKE,GAClB,IAAkB,IAAdL,EACF,MAAM,IAAIje,GACRme,EAAcC,EAAK,qBAAuBF,EAAU,OAASA,EAAU,KACvEle,GAAWue,gBAef,OAXIL,IAAYH,GAAmBK,KACjCL,GAAmBK,IAAO,EAE1BI,QAAQC,KACNN,EACEC,EACA,+BAAiCF,EAAU,8CAK1CD,GAAYA,EAAUxhB,EAAO2hB,EAAKE,GAE7C,EAEAR,GAAWY,SAAW,SAAkBC,GACtC,OAAO,SAACliB,EAAO2hB,GAGb,OADAI,QAAQC,KAAI,GAAAjlB,OAAI4kB,EAAG,gCAAA5kB,OAA+BmlB,KAC3C,EAEX,EAmCe,IAAAV,GAAA,CACbW,cAxBF,SAAuB9c,EAAS+c,EAAQC,GACtC,GAAuB,WAAnBpqB,EAAOoN,GACT,MAAM,IAAI9B,GAAW,4BAA6BA,GAAW+e,sBAI/D,IAFA,IAAMjoB,EAAOjD,OAAOiD,KAAKgL,GACrBxL,EAAIQ,EAAKL,OACNH,KAAM,GAAG,CACd,IAAM8nB,EAAMtnB,EAAKR,GACX2nB,EAAYY,EAAOT,GACzB,GAAIH,EAAJ,CACE,IAAMxhB,EAAQqF,EAAQsc,GAChB3iB,OAAmB/E,IAAV+F,GAAuBwhB,EAAUxhB,EAAO2hB,EAAKtc,GAC5D,IAAe,IAAXrG,EACF,MAAM,IAAIuE,GAAW,UAAYoe,EAAM,YAAc3iB,EAAQuE,GAAW+e,qBAG5E,MACA,IAAqB,IAAjBD,EACF,MAAM,IAAI9e,GAAW,kBAAoBoe,EAAKpe,GAAWgf,eAE7D,CACF,EAIElB,WAAAA,ICtFIA,GAAaG,GAAUH,WASvBmB,GAAK,WACT,SAAAA,EAAYC,GAAgB9a,OAAA6a,GAC1B1jB,KAAKoL,SAAWuY,EAChB3jB,KAAK4jB,aAAe,CAClB/e,QAAS,IAAI+D,GACb9D,SAAU,IAAI8D,GAElB,CAEA,IAAAib,EAuKC,OAvKD9a,EAAA2a,EAAA,CAAA,CAAApoB,IAAA,UAAA4F,OAAA2iB,EAAA5F,EAAA5C,IAAAC,MAQA,SAAAa,EAAc2H,EAAalf,GAAM,IAAAmf,EAAA5f,EAAA,OAAAkX,IAAAM,MAAA,SAAAC,GAAA,cAAAA,EAAAC,KAAAD,EAAAzZ,MAAA,KAAA,EAAA,OAAAyZ,EAAAC,KAAA,EAAAD,EAAAzZ,KAAA,EAEhBnC,KAAK8f,SAASgE,EAAalf,GAAO,KAAA,EAAA,OAAAgX,EAAAG,OAAAH,SAAAA,EAAAgB,MAAA,KAAA,EAE/C,GAF+ChB,EAAAC,KAAA,EAAAD,EAAA6C,GAAA7C,EAAA,MAAA,GAE3CA,EAAA6C,cAAe1b,MAAO,CACpBghB,EAAQ,CAAA,EAEZhhB,MAAMgC,kBAAoBhC,MAAMgC,kBAAkBgf,GAAUA,EAAQ,IAAIhhB,MAGlEoB,EAAQ4f,EAAM5f,MAAQ4f,EAAM5f,MAAMzD,QAAQ,QAAS,IAAM,GAC/D,IACOkb,EAAA6C,GAAIta,MAGEA,IAAUtC,OAAO+Z,EAAA6C,GAAIta,OAAOzC,SAASyC,EAAMzD,QAAQ,YAAa,OACzEkb,EAAA6C,GAAIta,OAAS,KAAOA,GAHpByX,EAAA6C,GAAIta,MAAQA,CAMd,CADA,MAAOoI,GACP,CAEJ,CAAC,MAAAqP,EAAA6C,GAAA,KAAA,GAAA,IAAA,MAAA,OAAA7C,EAAAI,OAAA,GAAAG,EAAAnc,KAAA,CAAA,CAAA,EAAA,IAIJ,KAAA,SAAAid,EAAAC,GAAA,OAAA2G,EAAA3rB,MAAA8H,KAAA7H,UAAA,IAAA,CAAAmD,IAAA,WAAA4F,MAED,SAAS4iB,EAAalf,GAGO,iBAAhBkf,GACTlf,EAASA,GAAU,IACZwD,IAAM0b,EAEblf,EAASkf,GAAe,GAK1B,IAAA9K,EAFApU,EAASuR,GAAYnW,KAAKoL,SAAUxG,GAE7ByG,EAAY2N,EAAZ3N,aAAcuL,EAAgBoC,EAAhBpC,iBAAkBpL,EAAOwN,EAAPxN,aAElBrQ,IAAjBkQ,GACFqX,GAAUW,cAAchY,EAAc,CACpC9B,kBAAmBgZ,GAAWlX,aAAakX,YAC3C/Y,kBAAmB+Y,GAAWlX,aAAakX,YAC3C9Y,oBAAqB8Y,GAAWlX,aAAakX,GAAkB,WAC9D,GAGmB,MAApB3L,IACE3R,GAAMxL,WAAWmd,GACnBhS,EAAOgS,iBAAmB,CACxBtO,UAAWsO,GAGb8L,GAAUW,cAAczM,EAAkB,CACxChP,OAAQ2a,GAAmB,SAC3Bja,UAAWia,GAAU,WACpB,IAIPG,GAAUW,cAAcze,EAAQ,CAC9Bof,QAASzB,GAAWY,SAAS,WAC7Bc,cAAe1B,GAAWY,SAAS,mBAClC,GAGHve,EAAO0I,QAAU1I,EAAO0I,QAAUtN,KAAKoL,SAASkC,QAAU,OAAOvU,cAGjE,IAAImrB,EAAiB1Y,GAAWvG,GAAMnF,MACpC0L,EAAQ4B,OACR5B,EAAQ5G,EAAO0I,SAGjB9B,GAAWvG,GAAMpK,QACf,CAAC,SAAU,MAAO,OAAQ,OAAQ,MAAO,QAAS,WAClD,SAACyS,UACQ9B,EAAQ8B,EACjB,IAGF1I,EAAO4G,QAAUuC,GAAa9P,OAAOimB,EAAgB1Y,GAGrD,IAAM2Y,EAA0B,GAC5BC,GAAiC,EACrCpkB,KAAK4jB,aAAa/e,QAAQhK,SAAQ,SAAoCwpB,GACjC,mBAAxBA,EAAYlb,UAA0D,IAAhCkb,EAAYlb,QAAQvE,KAIrEwf,EAAiCA,GAAkCC,EAAYnb,YAE/Eib,EAAwBG,QAAQD,EAAYrb,UAAWqb,EAAYpb,UACrE,IAEA,IAKIsb,EALEC,EAA2B,GACjCxkB,KAAK4jB,aAAa9e,SAASjK,SAAQ,SAAkCwpB,GACnEG,EAAyB9lB,KAAK2lB,EAAYrb,UAAWqb,EAAYpb,SACnE,IAGA,IACIxN,EADAV,EAAI,EAGR,IAAKqpB,EAAgC,CACnC,IAAMK,EAAQ,CAACpC,GAAgBtqB,KAAKiI,WAAO7E,GAO3C,IANAspB,EAAMH,QAAQpsB,MAAMusB,EAAON,GAC3BM,EAAM/lB,KAAKxG,MAAMusB,EAAOD,GACxB/oB,EAAMgpB,EAAMvpB,OAEZqpB,EAAU7L,QAAQ1G,QAAQpN,GAEnB7J,EAAIU,GACT8oB,EAAUA,EAAQ/f,KAAKigB,EAAM1pB,KAAM0pB,EAAM1pB,MAG3C,OAAOwpB,CACT,CAEA9oB,EAAM0oB,EAAwBjpB,OAE9B,IAAI2c,EAAYjT,EAIhB,IAFA7J,EAAI,EAEGA,EAAIU,GAAK,CACd,IAAMipB,EAAcP,EAAwBppB,KACtC4pB,EAAaR,EAAwBppB,KAC3C,IACE8c,EAAY6M,EAAY7M,EAI1B,CAHE,MAAOpS,GACPkf,EAAW9rB,KAAKmH,KAAMyF,GACtB,KACF,CACF,CAEA,IACE8e,EAAUlC,GAAgBxpB,KAAKmH,KAAM6X,EAGvC,CAFE,MAAOpS,GACP,OAAOiT,QAAQzG,OAAOxM,EACxB,CAKA,IAHA1K,EAAI,EACJU,EAAM+oB,EAAyBtpB,OAExBH,EAAIU,GACT8oB,EAAUA,EAAQ/f,KAAKggB,EAAyBzpB,KAAMypB,EAAyBzpB,MAGjF,OAAOwpB,CACT,GAAC,CAAAjpB,IAAA,SAAA4F,MAED,SAAO0D,GAGL,OAAOuD,GADU0N,IADjBjR,EAASuR,GAAYnW,KAAKoL,SAAUxG,IACEkR,QAASlR,EAAOwD,KAC5BxD,EAAOqD,OAAQrD,EAAOgS,iBAClD,KAAC8M,CAAA,CAhLQ,GAoLXze,GAAMpK,QAAQ,CAAC,SAAU,MAAO,OAAQ,YAAY,SAA6ByS,GAE/EoW,GAAMnrB,UAAU+U,GAAU,SAASlF,EAAKxD,GACtC,OAAO5E,KAAK6E,QAAQsR,GAAYvR,GAAU,CAAA,EAAI,CAC5C0I,OAAAA,EACAlF,IAAAA,EACA7J,MAAOqG,GAAU,CAAA,GAAIrG,QAG3B,IAEA0G,GAAMpK,QAAQ,CAAC,OAAQ,MAAO,UAAU,SAA+ByS,GAGrE,SAASsX,EAAmBC,GAC1B,OAAO,SAAoBzc,EAAK7J,EAAMqG,GACpC,OAAO5E,KAAK6E,QAAQsR,GAAYvR,GAAU,CAAA,EAAI,CAC5C0I,OAAAA,EACA9B,QAASqZ,EAAS,CAChB,eAAgB,uBACd,CAAE,EACNzc,IAAAA,EACA7J,KAAAA,KAGN,CAEAmlB,GAAMnrB,UAAU+U,GAAUsX,IAE1BlB,GAAMnrB,UAAU+U,EAAS,QAAUsX,GAAmB,EACxD,IAEA,IAAAE,GAAepB,GC7NTqB,GAAW,WACf,SAAAA,EAAYC,GACV,GADoBnc,OAAAkc,GACI,mBAAbC,EACT,MAAM,IAAIxe,UAAU,gCAGtB,IAAIye,EAEJjlB,KAAKukB,QAAU,IAAI7L,SAAQ,SAAyB1G,GAClDiT,EAAiBjT,CACnB,IAEA,IAAMrU,EAAQqC,KAGdA,KAAKukB,QAAQ/f,MAAK,SAAAkW,GAChB,GAAK/c,EAAMunB,WAAX,CAIA,IAFA,IAAInqB,EAAI4C,EAAMunB,WAAWhqB,OAElBH,KAAM,GACX4C,EAAMunB,WAAWnqB,GAAG2f,GAEtB/c,EAAMunB,WAAa,IAPI,CAQzB,IAGAllB,KAAKukB,QAAQ/f,KAAO,SAAA2gB,GAClB,IAAIC,EAEEb,EAAU,IAAI7L,SAAQ,SAAA1G,GAC1BrU,EAAMid,UAAU5I,GAChBoT,EAAWpT,CACb,IAAGxN,KAAK2gB,GAMR,OAJAZ,EAAQ7J,OAAS,WACf/c,EAAMwb,YAAYiM,IAGbb,GAGTS,GAAS,SAAgBtgB,EAASE,EAAQC,GACpClH,EAAMwd,SAKVxd,EAAMwd,OAAS,IAAItJ,GAAcnN,EAASE,EAAQC,GAClDogB,EAAetnB,EAAMwd,QACvB,GACF,CAqEC,OAnEDpS,EAAAgc,EAAA,CAAA,CAAAzpB,IAAA,mBAAA4F,MAGA,WACE,GAAIlB,KAAKmb,OACP,MAAMnb,KAAKmb,MAEf,GAEA,CAAA7f,IAAA,YAAA4F,MAIA,SAAU2S,GACJ7T,KAAKmb,OACPtH,EAAS7T,KAAKmb,QAIZnb,KAAKklB,WACPllB,KAAKklB,WAAWxmB,KAAKmV,GAErB7T,KAAKklB,WAAa,CAACrR,EAEvB,GAEA,CAAAvY,IAAA,cAAA4F,MAIA,SAAY2S,GACV,GAAK7T,KAAKklB,WAAV,CAGA,IAAM1d,EAAQxH,KAAKklB,WAAWnjB,QAAQ8R,IACvB,IAAXrM,GACFxH,KAAKklB,WAAWG,OAAO7d,EAAO,EAHhC,CAKF,GAAC,CAAAlM,IAAA,gBAAA4F,MAED,WAAgB,IAAAokB,EAAAtlB,KACRib,EAAa,IAAIC,gBAEjBP,EAAQ,SAACtL,GACb4L,EAAWN,MAAMtL,IAOnB,OAJArP,KAAK4a,UAAUD,GAEfM,EAAW7B,OAAOD,YAAc,WAAA,OAAMmM,EAAKnM,YAAYwB,EAAM,EAEtDM,EAAW7B,MACpB,IAEA,CAAA,CAAA9d,IAAA,SAAA4F,MAIA,WACE,IAAIwZ,EAIJ,MAAO,CACL/c,MAJY,IAAIonB,GAAY,SAAkBQ,GAC9C7K,EAAS6K,CACX,IAGE7K,OAAAA,EAEJ,KAACqK,CAAA,CAxHc,GA2HjBS,GAAeT,GCtIf,IAAMU,GAAiB,CACrBC,SAAU,IACVC,mBAAoB,IACpBC,WAAY,IACZC,WAAY,IACZC,GAAI,IACJC,QAAS,IACTC,SAAU,IACVC,4BAA6B,IAC7BC,UAAW,IACXC,aAAc,IACdC,eAAgB,IAChBC,YAAa,IACbC,gBAAiB,IACjBC,OAAQ,IACRC,gBAAiB,IACjBC,iBAAkB,IAClBC,MAAO,IACPC,SAAU,IACVC,YAAa,IACbC,SAAU,IACVC,OAAQ,IACRC,kBAAmB,IACnBC,kBAAmB,IACnBC,WAAY,IACZC,aAAc,IACdC,gBAAiB,IACjBC,UAAW,IACXC,SAAU,IACVC,iBAAkB,IAClBC,cAAe,IACfC,4BAA6B,IAC7BC,eAAgB,IAChBC,SAAU,IACVC,KAAM,IACNC,eAAgB,IAChBC,mBAAoB,IACpBC,gBAAiB,IACjBC,WAAY,IACZC,qBAAsB,IACtBC,oBAAqB,IACrBC,kBAAmB,IACnBC,UAAW,IACXC,mBAAoB,IACpBC,oBAAqB,IACrBC,OAAQ,IACRC,iBAAkB,IAClBC,SAAU,IACVC,gBAAiB,IACjBC,qBAAsB,IACtBC,gBAAiB,IACjBC,4BAA6B,IAC7BC,2BAA4B,IAC5BC,oBAAqB,IACrBC,eAAgB,IAChBC,WAAY,IACZC,mBAAoB,IACpBC,eAAgB,IAChBC,wBAAyB,IACzBC,sBAAuB,IACvBC,oBAAqB,IACrBC,aAAc,IACdC,YAAa,IACbC,8BAA+B,KAGjClxB,OAAO4S,QAAQua,IAAgB5qB,SAAQ,SAAAI,GAAkB,IAAA8E,EAAAxF,EAAAU,EAAA,GAAhBK,EAAGyE,EAAA,GAAEmB,EAAKnB,EAAA,GACjD0lB,GAAevkB,GAAS5F,CAC1B,IAEA,IAAAmuB,GAAehE,GCxBf,IAAMiE,GAnBN,SAASC,EAAeC,GACtB,IAAM1tB,EAAU,IAAIwnB,GAAMkG,GACpBC,EAAW9xB,EAAK2rB,GAAMnrB,UAAUsM,QAAS3I,GAa/C,OAVA+I,GAAM5E,OAAOwpB,EAAUnG,GAAMnrB,UAAW2D,EAAS,CAACb,YAAY,IAG9D4J,GAAM5E,OAAOwpB,EAAU3tB,EAAS,KAAM,CAACb,YAAY,IAGnDwuB,EAASnxB,OAAS,SAAgBirB,GAChC,OAAOgG,EAAexT,GAAYyT,EAAejG,KAG5CkG,CACT,CAGcF,CAAeve,WAG7Bse,GAAMhG,MAAQA,GAGdgG,GAAM7X,cAAgBA,GACtB6X,GAAM3E,YAAcA,GACpB2E,GAAM/X,SAAWA,GACjB+X,GAAMpH,QAAUA,GAChBoH,GAAMrjB,WAAaA,GAGnBqjB,GAAMjlB,WAAaA,GAGnBilB,GAAMI,OAASJ,GAAM7X,cAGrB6X,GAAMK,IAAM,SAAaC,GACvB,OAAOtR,QAAQqR,IAAIC,EACrB,EAEAN,GAAMO,OC9CS,SAAgBC,GAC7B,OAAO,SAAcjoB,GACnB,OAAOioB,EAAShyB,MAAM,KAAM+J,GAEhC,ED6CAynB,GAAMS,aE7DS,SAAsBC,GACnC,OAAOnlB,GAAMtL,SAASywB,KAAsC,IAAzBA,EAAQD,YAC7C,EF8DAT,GAAMvT,YAAcA,GAEpBuT,GAAM3b,aAAeA,GAErB2b,GAAMW,WAAa,SAAA1xB,GAAK,OAAIkS,GAAe5F,GAAM3I,WAAW3D,GAAS,IAAI0G,SAAS1G,GAASA,EAAM,EAEjG+wB,GAAMY,WAAaxI,GAEnB4H,GAAMjE,eAAiBA,GAEvBiE,GAAK,QAAWA"} \ No newline at end of file diff --git a/node_modules/axios/dist/browser/axios.cjs b/node_modules/axios/dist/browser/axios.cjs new file mode 100644 index 000000000..3305d6635 --- /dev/null +++ b/node_modules/axios/dist/browser/axios.cjs @@ -0,0 +1,3722 @@ +// Axios v1.7.9 Copyright (c) 2024 Matt Zabriskie and contributors +'use strict'; + +function bind(fn, thisArg) { + return function wrap() { + return fn.apply(thisArg, arguments); + }; +} + +// utils is a library of generic helper functions non-specific to axios + +const {toString} = Object.prototype; +const {getPrototypeOf} = Object; + +const kindOf = (cache => thing => { + const str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); +})(Object.create(null)); + +const kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type +}; + +const typeOfTest = type => thing => typeof thing === type; + +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * + * @returns {boolean} True if value is an Array, otherwise false + */ +const {isArray} = Array; + +/** + * Determine if a value is undefined + * + * @param {*} val The value to test + * + * @returns {boolean} True if the value is undefined, otherwise false + */ +const isUndefined = typeOfTest('undefined'); + +/** + * Determine if a value is a Buffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); +} + +/** + * Determine if a value is an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +const isArrayBuffer = kindOfTest('ArrayBuffer'); + + +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + let result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); + } + return result; +} + +/** + * Determine if a value is a String + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a String, otherwise false + */ +const isString = typeOfTest('string'); + +/** + * Determine if a value is a Function + * + * @param {*} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +const isFunction = typeOfTest('function'); + +/** + * Determine if a value is a Number + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Number, otherwise false + */ +const isNumber = typeOfTest('number'); + +/** + * Determine if a value is an Object + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an Object, otherwise false + */ +const isObject = (thing) => thing !== null && typeof thing === 'object'; + +/** + * Determine if a value is a Boolean + * + * @param {*} thing The value to test + * @returns {boolean} True if value is a Boolean, otherwise false + */ +const isBoolean = thing => thing === true || thing === false; + +/** + * Determine if a value is a plain Object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a plain Object, otherwise false + */ +const isPlainObject = (val) => { + if (kindOf(val) !== 'object') { + return false; + } + + const prototype = getPrototypeOf(val); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); +}; + +/** + * Determine if a value is a Date + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Date, otherwise false + */ +const isDate = kindOfTest('Date'); + +/** + * Determine if a value is a File + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFile = kindOfTest('File'); + +/** + * Determine if a value is a Blob + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Blob, otherwise false + */ +const isBlob = kindOfTest('Blob'); + +/** + * Determine if a value is a FileList + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFileList = kindOfTest('FileList'); + +/** + * Determine if a value is a Stream + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Stream, otherwise false + */ +const isStream = (val) => isObject(val) && isFunction(val.pipe); + +/** + * Determine if a value is a FormData + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an FormData, otherwise false + */ +const isFormData = (thing) => { + let kind; + return thing && ( + (typeof FormData === 'function' && thing instanceof FormData) || ( + isFunction(thing.append) && ( + (kind = kindOf(thing)) === 'formdata' || + // detect form-data instance + (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]') + ) + ) + ) +}; + +/** + * Determine if a value is a URLSearchParams object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +const isURLSearchParams = kindOfTest('URLSearchParams'); + +const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest); + +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * + * @returns {String} The String freed of excess whitespace + */ +const trim = (str) => str.trim ? + str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + * + * @param {Boolean} [allOwnKeys = false] + * @returns {any} + */ +function forEach(obj, fn, {allOwnKeys = false} = {}) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + let i; + let l; + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; + + for (i = 0; i < len; i++) { + key = keys[i]; + fn.call(null, obj[key], key, obj); + } + } +} + +function findKey(obj, key) { + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; +} + +const _global = (() => { + /*eslint no-undef:0*/ + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global) +})(); + +const isContextDefined = (context) => !isUndefined(context) && context !== _global; + +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + const {caseless} = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + }; + + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); + } + return result; +} + +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * + * @param {Boolean} [allOwnKeys] + * @returns {Object} The resulting value of object a + */ +const extend = (a, b, thisArg, {allOwnKeys}= {}) => { + forEach(b, (val, key) => { + if (thisArg && isFunction(val)) { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }, {allOwnKeys}); + return a; +}; + +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * + * @returns {string} content value without BOM + */ +const stripBOM = (content) => { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +}; + +/** + * Inherit the prototype methods from one constructor into another + * @param {function} constructor + * @param {function} superConstructor + * @param {object} [props] + * @param {object} [descriptors] + * + * @returns {void} + */ +const inherits = (constructor, superConstructor, props, descriptors) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, 'super', { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); +}; + +/** + * Resolve object with deep prototype chain to a flat object + * @param {Object} sourceObj source object + * @param {Object} [destObj] + * @param {Function|Boolean} [filter] + * @param {Function} [propFilter] + * + * @returns {Object} + */ +const toFlatObject = (sourceObj, destObj, filter, propFilter) => { + let props; + let i; + let prop; + const merged = {}; + + destObj = destObj || {}; + // eslint-disable-next-line no-eq-null,eqeqeq + if (sourceObj == null) return destObj; + + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + + return destObj; +}; + +/** + * Determines whether a string ends with the characters of a specified string + * + * @param {String} str + * @param {String} searchString + * @param {Number} [position= 0] + * + * @returns {boolean} + */ +const endsWith = (str, searchString, position) => { + str = String(str); + if (position === undefined || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; +}; + + +/** + * Returns new array from array like object or null if failed + * + * @param {*} [thing] + * + * @returns {?Array} + */ +const toArray = (thing) => { + if (!thing) return null; + if (isArray(thing)) return thing; + let i = thing.length; + if (!isNumber(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; +}; + +/** + * Checking if the Uint8Array exists and if it does, it returns a function that checks if the + * thing passed in is an instance of Uint8Array + * + * @param {TypedArray} + * + * @returns {Array} + */ +// eslint-disable-next-line func-names +const isTypedArray = (TypedArray => { + // eslint-disable-next-line func-names + return thing => { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); + +/** + * For each entry in the object, call the function with the key and value. + * + * @param {Object} obj - The object to iterate over. + * @param {Function} fn - The function to call for each entry. + * + * @returns {void} + */ +const forEachEntry = (obj, fn) => { + const generator = obj && obj[Symbol.iterator]; + + const iterator = generator.call(obj); + + let result; + + while ((result = iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); + } +}; + +/** + * It takes a regular expression and a string, and returns an array of all the matches + * + * @param {string} regExp - The regular expression to match against. + * @param {string} str - The string to search. + * + * @returns {Array} + */ +const matchAll = (regExp, str) => { + let matches; + const arr = []; + + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + + return arr; +}; + +/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ +const isHTMLForm = kindOfTest('HTMLFormElement'); + +const toCamelCase = str => { + return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, + function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; + } + ); +}; + +/* Creating a function that will check if an object has a property. */ +const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); + +/** + * Determine if a value is a RegExp object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a RegExp object, otherwise false + */ +const isRegExp = kindOfTest('RegExp'); + +const reduceDescriptors = (obj, reducer) => { + const descriptors = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + + forEach(descriptors, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); + + Object.defineProperties(obj, reducedDescriptors); +}; + +/** + * Makes all methods read-only + * @param {Object} obj + */ + +const freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name) => { + // skip restricted props in strict mode + if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { + return false; + } + + const value = obj[name]; + + if (!isFunction(value)) return; + + descriptor.enumerable = false; + + if ('writable' in descriptor) { + descriptor.writable = false; + return; + } + + if (!descriptor.set) { + descriptor.set = () => { + throw Error('Can not rewrite read-only method \'' + name + '\''); + }; + } + }); +}; + +const toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; + + const define = (arr) => { + arr.forEach(value => { + obj[value] = true; + }); + }; + + isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + + return obj; +}; + +const noop = () => {}; + +const toFiniteNumber = (value, defaultValue) => { + return value != null && Number.isFinite(value = +value) ? value : defaultValue; +}; + +const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; + +const DIGIT = '0123456789'; + +const ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT +}; + +const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { + let str = ''; + const {length} = alphabet; + while (size--) { + str += alphabet[Math.random() * length|0]; + } + + return str; +}; + +/** + * If the thing is a FormData object, return true, otherwise return false. + * + * @param {unknown} thing - The thing to check. + * + * @returns {boolean} + */ +function isSpecCompliantForm(thing) { + return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]); +} + +const toJSONObject = (obj) => { + const stack = new Array(10); + + const visit = (source, i) => { + + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + + if(!('toJSON' in source)) { + stack[i] = source; + const target = isArray(source) ? [] : {}; + + forEach(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + + stack[i] = undefined; + + return target; + } + } + + return source; + }; + + return visit(obj, 0); +}; + +const isAsyncFn = kindOfTest('AsyncFunction'); + +const isThenable = (thing) => + thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); + +// original code +// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 + +const _setImmediate = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; + } + + return postMessageSupported ? ((token, callbacks) => { + _global.addEventListener("message", ({source, data}) => { + if (source === _global && data === token) { + callbacks.length && callbacks.shift()(); + } + }, false); + + return (cb) => { + callbacks.push(cb); + _global.postMessage(token, "*"); + } + })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); +})( + typeof setImmediate === 'function', + isFunction(_global.postMessage) +); + +const asap = typeof queueMicrotask !== 'undefined' ? + queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate); + +// ********************* + +var utils$1 = { + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString, + isNumber, + isBoolean, + isObject, + isPlainObject, + isReadableStream, + isRequest, + isResponse, + isHeaders, + isUndefined, + isDate, + isFile, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty, + hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + ALPHABET, + generateString, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable, + setImmediate: _setImmediate, + asap +}; + +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [config] The config. + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * + * @returns {Error} The created error. + */ +function AxiosError(message, code, config, request, response) { + Error.call(this); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = (new Error()).stack; + } + + this.message = message; + this.name = 'AxiosError'; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status ? response.status : null; + } +} + +utils$1.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils$1.toJSONObject(this.config), + code: this.code, + status: this.status + }; + } +}); + +const prototype$1 = AxiosError.prototype; +const descriptors = {}; + +[ + 'ERR_BAD_OPTION_VALUE', + 'ERR_BAD_OPTION', + 'ECONNABORTED', + 'ETIMEDOUT', + 'ERR_NETWORK', + 'ERR_FR_TOO_MANY_REDIRECTS', + 'ERR_DEPRECATED', + 'ERR_BAD_RESPONSE', + 'ERR_BAD_REQUEST', + 'ERR_CANCELED', + 'ERR_NOT_SUPPORT', + 'ERR_INVALID_URL' +// eslint-disable-next-line func-names +].forEach(code => { + descriptors[code] = {value: code}; +}); + +Object.defineProperties(AxiosError, descriptors); +Object.defineProperty(prototype$1, 'isAxiosError', {value: true}); + +// eslint-disable-next-line func-names +AxiosError.from = (error, code, config, request, response, customProps) => { + const axiosError = Object.create(prototype$1); + + utils$1.toFlatObject(error, axiosError, function filter(obj) { + return obj !== Error.prototype; + }, prop => { + return prop !== 'isAxiosError'; + }); + + AxiosError.call(axiosError, error.message, code, config, request, response); + + axiosError.cause = error; + + axiosError.name = error.name; + + customProps && Object.assign(axiosError, customProps); + + return axiosError; +}; + +// eslint-disable-next-line strict +var httpAdapter = null; + +/** + * Determines if the given thing is a array or js object. + * + * @param {string} thing - The object or array to be visited. + * + * @returns {boolean} + */ +function isVisitable(thing) { + return utils$1.isPlainObject(thing) || utils$1.isArray(thing); +} + +/** + * It removes the brackets from the end of a string + * + * @param {string} key - The key of the parameter. + * + * @returns {string} the key without the brackets. + */ +function removeBrackets(key) { + return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key; +} + +/** + * It takes a path, a key, and a boolean, and returns a string + * + * @param {string} path - The path to the current key. + * @param {string} key - The key of the current object being iterated over. + * @param {string} dots - If true, the key will be rendered with dots instead of brackets. + * + * @returns {string} The path to the current key. + */ +function renderKey(path, key, dots) { + if (!path) return key; + return path.concat(key).map(function each(token, i) { + // eslint-disable-next-line no-param-reassign + token = removeBrackets(token); + return !dots && i ? '[' + token + ']' : token; + }).join(dots ? '.' : ''); +} + +/** + * If the array is an array and none of its elements are visitable, then it's a flat array. + * + * @param {Array} arr - The array to check + * + * @returns {boolean} + */ +function isFlatArray(arr) { + return utils$1.isArray(arr) && !arr.some(isVisitable); +} + +const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); +}); + +/** + * Convert a data object to FormData + * + * @param {Object} obj + * @param {?Object} [formData] + * @param {?Object} [options] + * @param {Function} [options.visitor] + * @param {Boolean} [options.metaTokens = true] + * @param {Boolean} [options.dots = false] + * @param {?Boolean} [options.indexes = false] + * + * @returns {Object} + **/ + +/** + * It converts an object into a FormData object + * + * @param {Object} obj - The object to convert to form data. + * @param {string} formData - The FormData object to append to. + * @param {Object} options + * + * @returns + */ +function toFormData(obj, formData, options) { + if (!utils$1.isObject(obj)) { + throw new TypeError('target must be an object'); + } + + // eslint-disable-next-line no-param-reassign + formData = formData || new (FormData)(); + + // eslint-disable-next-line no-param-reassign + options = utils$1.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + // eslint-disable-next-line no-eq-null,eqeqeq + return !utils$1.isUndefined(source[option]); + }); + + const metaTokens = options.metaTokens; + // eslint-disable-next-line no-use-before-define + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; + const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + + if (!utils$1.isFunction(visitor)) { + throw new TypeError('visitor must be a function'); + } + + function convertValue(value) { + if (value === null) return ''; + + if (utils$1.isDate(value)) { + return value.toISOString(); + } + + if (!useBlob && utils$1.isBlob(value)) { + throw new AxiosError('Blob is not supported. Use a Buffer instead.'); + } + + if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { + return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + } + + return value; + } + + /** + * Default visitor. + * + * @param {*} value + * @param {String|Number} key + * @param {Array} path + * @this {FormData} + * + * @returns {boolean} return true to visit the each prop of the value recursively + */ + function defaultVisitor(value, key, path) { + let arr = value; + + if (value && !path && typeof value === 'object') { + if (utils$1.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign + key = metaTokens ? key : key.slice(0, -2); + // eslint-disable-next-line no-param-reassign + value = JSON.stringify(value); + } else if ( + (utils$1.isArray(value) && isFlatArray(value)) || + ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)) + )) { + // eslint-disable-next-line no-param-reassign + key = removeBrackets(key); + + arr.forEach(function each(el, index) { + !(utils$1.isUndefined(el) || el === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), + convertValue(el) + ); + }); + return false; + } + } + + if (isVisitable(value)) { + return true; + } + + formData.append(renderKey(path, key, dots), convertValue(value)); + + return false; + } + + const stack = []; + + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable + }); + + function build(value, path) { + if (utils$1.isUndefined(value)) return; + + if (stack.indexOf(value) !== -1) { + throw Error('Circular reference detected in ' + path.join('.')); + } + + stack.push(value); + + utils$1.forEach(value, function each(el, key) { + const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( + formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers + ); + + if (result === true) { + build(el, path ? path.concat(key) : [key]); + } + }); + + stack.pop(); + } + + if (!utils$1.isObject(obj)) { + throw new TypeError('data must be an object'); + } + + build(obj); + + return formData; +} + +/** + * It encodes a string by replacing all characters that are not in the unreserved set with + * their percent-encoded equivalents + * + * @param {string} str - The string to encode. + * + * @returns {string} The encoded string. + */ +function encode$1(str) { + const charMap = { + '!': '%21', + "'": '%27', + '(': '%28', + ')': '%29', + '~': '%7E', + '%20': '+', + '%00': '\x00' + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); +} + +/** + * It takes a params object and converts it to a FormData object + * + * @param {Object} params - The parameters to be converted to a FormData object. + * @param {Object} options - The options object passed to the Axios constructor. + * + * @returns {void} + */ +function AxiosURLSearchParams(params, options) { + this._pairs = []; + + params && toFormData(params, this, options); +} + +const prototype = AxiosURLSearchParams.prototype; + +prototype.append = function append(name, value) { + this._pairs.push([name, value]); +}; + +prototype.toString = function toString(encoder) { + const _encode = encoder ? function(value) { + return encoder.call(this, value, encode$1); + } : encode$1; + + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + '=' + _encode(pair[1]); + }, '').join('&'); +}; + +/** + * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their + * URI encoded counterparts + * + * @param {string} val The value to be encoded. + * + * @returns {string} The encoded value. + */ +function encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} + +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @param {?(object|Function)} options + * + * @returns {string} The formatted url + */ +function buildURL(url, params, options) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + + const _encode = options && options.encode || encode; + + if (utils$1.isFunction(options)) { + options = { + serialize: options + }; + } + + const serializeFn = options && options.serialize; + + let serializedParams; + + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils$1.isURLSearchParams(params) ? + params.toString() : + new AxiosURLSearchParams(params, options).toString(_encode); + } + + if (serializedParams) { + const hashmarkIndex = url.indexOf("#"); + + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + + return url; +} + +class InterceptorManager { + constructor() { + this.handlers = []; + } + + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + */ + eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; + } + } + + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn) { + utils$1.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + } +} + +var InterceptorManager$1 = InterceptorManager; + +var transitionalDefaults = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false +}; + +var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams; + +var FormData$1 = typeof FormData !== 'undefined' ? FormData : null; + +var Blob$1 = typeof Blob !== 'undefined' ? Blob : null; + +var platform$1 = { + isBrowser: true, + classes: { + URLSearchParams: URLSearchParams$1, + FormData: FormData$1, + Blob: Blob$1 + }, + protocols: ['http', 'https', 'file', 'blob', 'url', 'data'] +}; + +const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; + +const _navigator = typeof navigator === 'object' && navigator || undefined; + +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + * + * @returns {boolean} + */ +const hasStandardBrowserEnv = hasBrowserEnv && + (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0); + +/** + * Determine if we're running in a standard browser webWorker environment + * + * Although the `isStandardBrowserEnv` method indicates that + * `allows axios to run in a web worker`, the WebWorker will still be + * filtered out due to its judgment standard + * `typeof window !== 'undefined' && typeof document !== 'undefined'`. + * This leads to a problem when axios post `FormData` in webWorker + */ +const hasStandardBrowserWebWorkerEnv = (() => { + return ( + typeof WorkerGlobalScope !== 'undefined' && + // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && + typeof self.importScripts === 'function' + ); +})(); + +const origin = hasBrowserEnv && window.location.href || 'http://localhost'; + +var utils = /*#__PURE__*/Object.freeze({ + __proto__: null, + hasBrowserEnv: hasBrowserEnv, + hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, + hasStandardBrowserEnv: hasStandardBrowserEnv, + navigator: _navigator, + origin: origin +}); + +var platform = { + ...utils, + ...platform$1 +}; + +function toURLEncodedForm(data, options) { + return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (platform.isNode && utils$1.isBuffer(value)) { + this.append(key, value.toString('base64')); + return false; + } + + return helpers.defaultVisitor.apply(this, arguments); + } + }, options)); +} + +/** + * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z'] + * + * @param {string} name - The name of the property to get. + * + * @returns An array of strings. + */ +function parsePropPath(name) { + // foo[x][y][z] + // foo.x.y.z + // foo-x-y-z + // foo x y z + return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => { + return match[0] === '[]' ? '' : match[1] || match[0]; + }); +} + +/** + * Convert an array to an object. + * + * @param {Array} arr - The array to convert to an object. + * + * @returns An object with the same keys and values as the array. + */ +function arrayToObject(arr) { + const obj = {}; + const keys = Object.keys(arr); + let i; + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; +} + +/** + * It takes a FormData object and returns a JavaScript object + * + * @param {string} formData The FormData object to convert to JSON. + * + * @returns {Object | null} The converted object. + */ +function formDataToJSON(formData) { + function buildPath(path, value, target, index) { + let name = path[index++]; + + if (name === '__proto__') return true; + + const isNumericKey = Number.isFinite(+name); + const isLast = index >= path.length; + name = !name && utils$1.isArray(target) ? target.length : name; + + if (isLast) { + if (utils$1.hasOwnProp(target, name)) { + target[name] = [target[name], value]; + } else { + target[name] = value; + } + + return !isNumericKey; + } + + if (!target[name] || !utils$1.isObject(target[name])) { + target[name] = []; + } + + const result = buildPath(path, value, target[name], index); + + if (result && utils$1.isArray(target[name])) { + target[name] = arrayToObject(target[name]); + } + + return !isNumericKey; + } + + if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { + const obj = {}; + + utils$1.forEachEntry(formData, (name, value) => { + buildPath(parsePropPath(name), value, obj, 0); + }); + + return obj; + } + + return null; +} + +/** + * It takes a string, tries to parse it, and if it fails, it returns the stringified version + * of the input + * + * @param {any} rawValue - The value to be stringified. + * @param {Function} parser - A function that parses a string into a JavaScript object. + * @param {Function} encoder - A function that takes a value and returns a string. + * + * @returns {string} A stringified version of the rawValue. + */ +function stringifySafely(rawValue, parser, encoder) { + if (utils$1.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils$1.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } + } + } + + return (encoder || JSON.stringify)(rawValue); +} + +const defaults = { + + transitional: transitionalDefaults, + + adapter: ['xhr', 'http', 'fetch'], + + transformRequest: [function transformRequest(data, headers) { + const contentType = headers.getContentType() || ''; + const hasJSONContentType = contentType.indexOf('application/json') > -1; + const isObjectPayload = utils$1.isObject(data); + + if (isObjectPayload && utils$1.isHTMLForm(data)) { + data = new FormData(data); + } + + const isFormData = utils$1.isFormData(data); + + if (isFormData) { + return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; + } + + if (utils$1.isArrayBuffer(data) || + utils$1.isBuffer(data) || + utils$1.isStream(data) || + utils$1.isFile(data) || + utils$1.isBlob(data) || + utils$1.isReadableStream(data) + ) { + return data; + } + if (utils$1.isArrayBufferView(data)) { + return data.buffer; + } + if (utils$1.isURLSearchParams(data)) { + headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); + return data.toString(); + } + + let isFileList; + + if (isObjectPayload) { + if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + + if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { + const _FormData = this.env && this.env.FormData; + + return toFormData( + isFileList ? {'files[]': data} : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + + if (isObjectPayload || hasJSONContentType ) { + headers.setContentType('application/json', false); + return stringifySafely(data); + } + + return data; + }], + + transformResponse: [function transformResponse(data) { + const transitional = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional && transitional.forcedJSONParsing; + const JSONRequested = this.responseType === 'json'; + + if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) { + return data; + } + + if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { + const silentJSONParsing = transitional && transitional.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } + + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + + headers: { + common: { + 'Accept': 'application/json, text/plain, */*', + 'Content-Type': undefined + } + } +}; + +utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { + defaults.headers[method] = {}; +}); + +var defaults$1 = defaults; + +// RawAxiosHeaders whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +const ignoreDuplicateOf = utils$1.toObjectSet([ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]); + +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} rawHeaders Headers needing to be parsed + * + * @returns {Object} Headers parsed into an object + */ +var parseHeaders = rawHeaders => { + const parsed = {}; + let key; + let val; + let i; + + rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { + i = line.indexOf(':'); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + + if (!key || (parsed[key] && ignoreDuplicateOf[key])) { + return; + } + + if (key === 'set-cookie') { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + }); + + return parsed; +}; + +const $internals = Symbol('internals'); + +function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); +} + +function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + + return utils$1.isArray(value) ? value.map(normalizeValue) : String(value); +} + +function parseTokens(str) { + const tokens = Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + + while ((match = tokensRE.exec(str))) { + tokens[match[1]] = match[2]; + } + + return tokens; +} + +const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); + +function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { + if (utils$1.isFunction(filter)) { + return filter.call(this, value, header); + } + + if (isHeaderNameFilter) { + value = header; + } + + if (!utils$1.isString(value)) return; + + if (utils$1.isString(filter)) { + return value.indexOf(filter) !== -1; + } + + if (utils$1.isRegExp(filter)) { + return filter.test(value); + } +} + +function formatHeader(header) { + return header.trim() + .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { + return char.toUpperCase() + str; + }); +} + +function buildAccessors(obj, header) { + const accessorName = utils$1.toCamelCase(' ' + header); + + ['get', 'set', 'has'].forEach(methodName => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); +} + +class AxiosHeaders { + constructor(headers) { + headers && this.set(headers); + } + + set(header, valueOrRewrite, rewrite) { + const self = this; + + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); + + if (!lHeader) { + throw new Error('header name must be a non-empty string'); + } + + const key = utils$1.findKey(self, lHeader); + + if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { + self[key || _header] = normalizeValue(_value); + } + } + + const setHeaders = (headers, _rewrite) => + utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + + if (utils$1.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else if (utils$1.isHeaders(header)) { + for (const [key, value] of header.entries()) { + setHeader(value, key, rewrite); + } + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + + return this; + } + + get(header, parser) { + header = normalizeHeader(header); + + if (header) { + const key = utils$1.findKey(this, header); + + if (key) { + const value = this[key]; + + if (!parser) { + return value; + } + + if (parser === true) { + return parseTokens(value); + } + + if (utils$1.isFunction(parser)) { + return parser.call(this, value, key); + } + + if (utils$1.isRegExp(parser)) { + return parser.exec(value); + } + + throw new TypeError('parser must be boolean|regexp|function'); + } + } + } + + has(header, matcher) { + header = normalizeHeader(header); + + if (header) { + const key = utils$1.findKey(this, header); + + return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + } + + return false; + } + + delete(header, matcher) { + const self = this; + let deleted = false; + + function deleteHeader(_header) { + _header = normalizeHeader(_header); + + if (_header) { + const key = utils$1.findKey(self, _header); + + if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { + delete self[key]; + + deleted = true; + } + } + } + + if (utils$1.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + + return deleted; + } + + clear(matcher) { + const keys = Object.keys(this); + let i = keys.length; + let deleted = false; + + while (i--) { + const key = keys[i]; + if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + + return deleted; + } + + normalize(format) { + const self = this; + const headers = {}; + + utils$1.forEach(this, (value, header) => { + const key = utils$1.findKey(headers, header); + + if (key) { + self[key] = normalizeValue(value); + delete self[header]; + return; + } + + const normalized = format ? formatHeader(header) : String(header).trim(); + + if (normalized !== header) { + delete self[header]; + } + + self[normalized] = normalizeValue(value); + + headers[normalized] = true; + }); + + return this; + } + + concat(...targets) { + return this.constructor.concat(this, ...targets); + } + + toJSON(asStrings) { + const obj = Object.create(null); + + utils$1.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value); + }); + + return obj; + } + + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n'); + } + + get [Symbol.toStringTag]() { + return 'AxiosHeaders'; + } + + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + + static concat(first, ...targets) { + const computed = new this(first); + + targets.forEach((target) => computed.set(target)); + + return computed; + } + + static accessor(header) { + const internals = this[$internals] = (this[$internals] = { + accessors: {} + }); + + const accessors = internals.accessors; + const prototype = this.prototype; + + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); + + if (!accessors[lHeader]) { + buildAccessors(prototype, _header); + accessors[lHeader] = true; + } + } + + utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + + return this; + } +} + +AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); + +// reserved names hotfix +utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } + } +}); + +utils$1.freezeMethods(AxiosHeaders); + +var AxiosHeaders$1 = AxiosHeaders; + +/** + * Transform the data for a request or a response + * + * @param {Array|Function} fns A single function or Array of functions + * @param {?Object} response The response object + * + * @returns {*} The resulting transformed data + */ +function transformData(fns, response) { + const config = this || defaults$1; + const context = response || config; + const headers = AxiosHeaders$1.from(context.headers); + let data = context.data; + + utils$1.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); + }); + + headers.normalize(); + + return data; +} + +function isCancel(value) { + return !!(value && value.__CANCEL__); +} + +/** + * A `CanceledError` is an object that is thrown when an operation is canceled. + * + * @param {string=} message The message. + * @param {Object=} config The config. + * @param {Object=} request The request. + * + * @returns {CanceledError} The created error. + */ +function CanceledError(message, config, request) { + // eslint-disable-next-line no-eq-null,eqeqeq + AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); + this.name = 'CanceledError'; +} + +utils$1.inherits(CanceledError, AxiosError, { + __CANCEL__: true +}); + +/** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + * + * @returns {object} The response. + */ +function settle(resolve, reject, response) { + const validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new AxiosError( + 'Request failed with status code ' + response.status, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } +} + +function parseProtocol(url) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ''; +} + +/** + * Calculate data maxRate + * @param {Number} [samplesCount= 10] + * @param {Number} [min= 1000] + * @returns {Function} + */ +function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + + min = min !== undefined ? min : 1000; + + return function push(chunkLength) { + const now = Date.now(); + + const startedAt = timestamps[tail]; + + if (!firstSampleTS) { + firstSampleTS = now; + } + + bytes[head] = chunkLength; + timestamps[head] = now; + + let i = tail; + let bytesCount = 0; + + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + + head = (head + 1) % samplesCount; + + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + + if (now - firstSampleTS < min) { + return; + } + + const passed = startedAt && now - startedAt; + + return passed ? Math.round(bytesCount * 1000 / passed) : undefined; + }; +} + +/** + * Throttle decorator + * @param {Function} fn + * @param {Number} freq + * @return {Function} + */ +function throttle(fn, freq) { + let timestamp = 0; + let threshold = 1000 / freq; + let lastArgs; + let timer; + + const invoke = (args, now = Date.now()) => { + timestamp = now; + lastArgs = null; + if (timer) { + clearTimeout(timer); + timer = null; + } + fn.apply(null, args); + }; + + const throttled = (...args) => { + const now = Date.now(); + const passed = now - timestamp; + if ( passed >= threshold) { + invoke(args, now); + } else { + lastArgs = args; + if (!timer) { + timer = setTimeout(() => { + timer = null; + invoke(lastArgs); + }, threshold - passed); + } + } + }; + + const flush = () => lastArgs && invoke(lastArgs); + + return [throttled, flush]; +} + +const progressEventReducer = (listener, isDownloadStream, freq = 3) => { + let bytesNotified = 0; + const _speedometer = speedometer(50, 250); + + return throttle(e => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : undefined; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange = loaded <= total; + + bytesNotified = loaded; + + const data = { + loaded, + total, + progress: total ? (loaded / total) : undefined, + bytes: progressBytes, + rate: rate ? rate : undefined, + estimated: rate && total && inRange ? (total - loaded) / rate : undefined, + event: e, + lengthComputable: total != null, + [isDownloadStream ? 'download' : 'upload']: true + }; + + listener(data); + }, freq); +}; + +const progressEventDecorator = (total, throttled) => { + const lengthComputable = total != null; + + return [(loaded) => throttled[0]({ + lengthComputable, + total, + loaded + }), throttled[1]]; +}; + +const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args)); + +var isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => { + url = new URL(url, platform.origin); + + return ( + origin.protocol === url.protocol && + origin.host === url.host && + (isMSIE || origin.port === url.port) + ); +})( + new URL(platform.origin), + platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) +) : () => true; + +var cookies = platform.hasStandardBrowserEnv ? + + // Standard browser envs support document.cookie + { + write(name, value, expires, path, domain, secure) { + const cookie = [name + '=' + encodeURIComponent(value)]; + + utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString()); + + utils$1.isString(path) && cookie.push('path=' + path); + + utils$1.isString(domain) && cookie.push('domain=' + domain); + + secure === true && cookie.push('secure'); + + document.cookie = cookie.join('; '); + }, + + read(name) { + const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, + + remove(name) { + this.write(name, '', Date.now() - 86400000); + } + } + + : + + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() {}, + read() { + return null; + }, + remove() {} + }; + +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); +} + +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * + * @returns {string} The combined URL + */ +function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +} + +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * + * @returns {string} The combined full path + */ +function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +} + +const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; + +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * + * @returns {Object} New object resulting from merging config2 to config1 + */ +function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + const config = {}; + + function getMergedValue(target, source, prop, caseless) { + if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { + return utils$1.merge.call({caseless}, target, source); + } else if (utils$1.isPlainObject(source)) { + return utils$1.merge({}, source); + } else if (utils$1.isArray(source)) { + return source.slice(); + } + return source; + } + + // eslint-disable-next-line consistent-return + function mergeDeepProperties(a, b, prop , caseless) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(a, b, prop , caseless); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(undefined, a, prop , caseless); + } + } + + // eslint-disable-next-line consistent-return + function valueFromConfig2(a, b) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(undefined, b); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(a, b) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(undefined, b); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(undefined, a); + } + } + + // eslint-disable-next-line consistent-return + function mergeDirectKeys(a, b, prop) { + if (prop in config2) { + return getMergedValue(a, b); + } else if (prop in config1) { + return getMergedValue(undefined, a); + } + } + + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true) + }; + + utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + const merge = mergeMap[prop] || mergeDeepProperties; + const configValue = merge(config1[prop], config2[prop], prop); + (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); + + return config; +} + +var resolveConfig = (config) => { + const newConfig = mergeConfig({}, config); + + let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig; + + newConfig.headers = headers = AxiosHeaders$1.from(headers); + + newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer); + + // HTTP basic authentication + if (auth) { + headers.set('Authorization', 'Basic ' + + btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : '')) + ); + } + + let contentType; + + if (utils$1.isFormData(data)) { + if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { + headers.setContentType(undefined); // Let the browser set it + } else if ((contentType = headers.getContentType()) !== false) { + // fix semicolon duplication issue for ReactNative FormData implementation + const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : []; + headers.setContentType([type || 'multipart/form-data', ...tokens].join('; ')); + } + } + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + + if (platform.hasStandardBrowserEnv) { + withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); + + if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) { + // Add xsrf header + const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); + + if (xsrfValue) { + headers.set(xsrfHeaderName, xsrfValue); + } + } + } + + return newConfig; +}; + +const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; + +var xhrAdapter = isXHRAdapterSupported && function (config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + const _config = resolveConfig(config); + let requestData = _config.data; + const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize(); + let {responseType, onUploadProgress, onDownloadProgress} = _config; + let onCanceled; + let uploadThrottled, downloadThrottled; + let flushUpload, flushDownload; + + function done() { + flushUpload && flushUpload(); // flush events + flushDownload && flushDownload(); // flush events + + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + + _config.signal && _config.signal.removeEventListener('abort', onCanceled); + } + + let request = new XMLHttpRequest(); + + request.open(_config.method.toUpperCase(), _config.url, true); + + // Set the request timeout in MS + request.timeout = _config.timeout; + + function onloadend() { + if (!request) { + return; + } + // Prepare the response + const responseHeaders = AxiosHeaders$1.from( + 'getAllResponseHeaders' in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === 'text' || responseType === 'json' ? + request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config, + request + }; + + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + + // Clean up request + request = null; + } + + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded'; + const transitional = _config.transitional || transitionalDefaults; + if (_config.timeoutErrorMessage) { + timeoutErrorMessage = _config.timeoutErrorMessage; + } + reject(new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + request)); + + // Clean up request + request = null; + }; + + // Remove Content-Type if data is undefined + requestData === undefined && requestHeaders.setContentType(null); + + // Add headers to the request + if ('setRequestHeader' in request) { + utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + + // Add withCredentials to request if needed + if (!utils$1.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; + } + + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = _config.responseType; + } + + // Handle progress if needed + if (onDownloadProgress) { + ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true)); + request.addEventListener('progress', downloadThrottled); + } + + // Not all browsers support upload events + if (onUploadProgress && request.upload) { + ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress)); + + request.upload.addEventListener('progress', uploadThrottled); + + request.upload.addEventListener('loadend', flushUpload); + } + + if (_config.cancelToken || _config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = cancel => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); + request.abort(); + request = null; + }; + + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled); + } + } + + const protocol = parseProtocol(_config.url); + + if (protocol && platform.protocols.indexOf(protocol) === -1) { + reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); + return; + } + + + // Send the request + request.send(requestData || null); + }); +}; + +const composeSignals = (signals, timeout) => { + const {length} = (signals = signals ? signals.filter(Boolean) : []); + + if (timeout || length) { + let controller = new AbortController(); + + let aborted; + + const onabort = function (reason) { + if (!aborted) { + aborted = true; + unsubscribe(); + const err = reason instanceof Error ? reason : this.reason; + controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err)); + } + }; + + let timer = timeout && setTimeout(() => { + timer = null; + onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT)); + }, timeout); + + const unsubscribe = () => { + if (signals) { + timer && clearTimeout(timer); + timer = null; + signals.forEach(signal => { + signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort); + }); + signals = null; + } + }; + + signals.forEach((signal) => signal.addEventListener('abort', onabort)); + + const {signal} = controller; + + signal.unsubscribe = () => utils$1.asap(unsubscribe); + + return signal; + } +}; + +var composeSignals$1 = composeSignals; + +const streamChunk = function* (chunk, chunkSize) { + let len = chunk.byteLength; + + if (!chunkSize || len < chunkSize) { + yield chunk; + return; + } + + let pos = 0; + let end; + + while (pos < len) { + end = pos + chunkSize; + yield chunk.slice(pos, end); + pos = end; + } +}; + +const readBytes = async function* (iterable, chunkSize) { + for await (const chunk of readStream(iterable)) { + yield* streamChunk(chunk, chunkSize); + } +}; + +const readStream = async function* (stream) { + if (stream[Symbol.asyncIterator]) { + yield* stream; + return; + } + + const reader = stream.getReader(); + try { + for (;;) { + const {done, value} = await reader.read(); + if (done) { + break; + } + yield value; + } + } finally { + await reader.cancel(); + } +}; + +const trackStream = (stream, chunkSize, onProgress, onFinish) => { + const iterator = readBytes(stream, chunkSize); + + let bytes = 0; + let done; + let _onFinish = (e) => { + if (!done) { + done = true; + onFinish && onFinish(e); + } + }; + + return new ReadableStream({ + async pull(controller) { + try { + const {done, value} = await iterator.next(); + + if (done) { + _onFinish(); + controller.close(); + return; + } + + let len = value.byteLength; + if (onProgress) { + let loadedBytes = bytes += len; + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); + } catch (err) { + _onFinish(err); + throw err; + } + }, + cancel(reason) { + _onFinish(reason); + return iterator.return(); + } + }, { + highWaterMark: 2 + }) +}; + +const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function'; +const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function'; + +// used only inside the fetch adapter +const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? + ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : + async (str) => new Uint8Array(await new Response(str).arrayBuffer()) +); + +const test = (fn, ...args) => { + try { + return !!fn(...args); + } catch (e) { + return false + } +}; + +const supportsRequestStream = isReadableStreamSupported && test(() => { + let duplexAccessed = false; + + const hasContentType = new Request(platform.origin, { + body: new ReadableStream(), + method: 'POST', + get duplex() { + duplexAccessed = true; + return 'half'; + }, + }).headers.has('Content-Type'); + + return duplexAccessed && !hasContentType; +}); + +const DEFAULT_CHUNK_SIZE = 64 * 1024; + +const supportsResponseStream = isReadableStreamSupported && + test(() => utils$1.isReadableStream(new Response('').body)); + + +const resolvers = { + stream: supportsResponseStream && ((res) => res.body) +}; + +isFetchSupported && (((res) => { + ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => { + !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() : + (_, config) => { + throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config); + }); + }); +})(new Response)); + +const getBodyLength = async (body) => { + if (body == null) { + return 0; + } + + if(utils$1.isBlob(body)) { + return body.size; + } + + if(utils$1.isSpecCompliantForm(body)) { + const _request = new Request(platform.origin, { + method: 'POST', + body, + }); + return (await _request.arrayBuffer()).byteLength; + } + + if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) { + return body.byteLength; + } + + if(utils$1.isURLSearchParams(body)) { + body = body + ''; + } + + if(utils$1.isString(body)) { + return (await encodeText(body)).byteLength; + } +}; + +const resolveBodyLength = async (headers, body) => { + const length = utils$1.toFiniteNumber(headers.getContentLength()); + + return length == null ? getBodyLength(body) : length; +}; + +var fetchAdapter = isFetchSupported && (async (config) => { + let { + url, + method, + data, + signal, + cancelToken, + timeout, + onDownloadProgress, + onUploadProgress, + responseType, + headers, + withCredentials = 'same-origin', + fetchOptions + } = resolveConfig(config); + + responseType = responseType ? (responseType + '').toLowerCase() : 'text'; + + let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + + let request; + + const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { + composedSignal.unsubscribe(); + }); + + let requestContentLength; + + try { + if ( + onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && + (requestContentLength = await resolveBodyLength(headers, data)) !== 0 + ) { + let _request = new Request(url, { + method: 'POST', + body: data, + duplex: "half" + }); + + let contentTypeHeader; + + if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { + headers.setContentType(contentTypeHeader); + } + + if (_request.body) { + const [onProgress, flush] = progressEventDecorator( + requestContentLength, + progressEventReducer(asyncDecorator(onUploadProgress)) + ); + + data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); + } + } + + if (!utils$1.isString(withCredentials)) { + withCredentials = withCredentials ? 'include' : 'omit'; + } + + // Cloudflare Workers throws when credentials are defined + // see https://github.com/cloudflare/workerd/issues/902 + const isCredentialsSupported = "credentials" in Request.prototype; + request = new Request(url, { + ...fetchOptions, + signal: composedSignal, + method: method.toUpperCase(), + headers: headers.normalize().toJSON(), + body: data, + duplex: "half", + credentials: isCredentialsSupported ? withCredentials : undefined + }); + + let response = await fetch(request); + + const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); + + if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) { + const options = {}; + + ['status', 'statusText', 'headers'].forEach(prop => { + options[prop] = response[prop]; + }); + + const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length')); + + const [onProgress, flush] = onDownloadProgress && progressEventDecorator( + responseContentLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true) + ) || []; + + response = new Response( + trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { + flush && flush(); + unsubscribe && unsubscribe(); + }), + options + ); + } + + responseType = responseType || 'text'; + + let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config); + + !isStreamResponse && unsubscribe && unsubscribe(); + + return await new Promise((resolve, reject) => { + settle(resolve, reject, { + data: responseData, + headers: AxiosHeaders$1.from(response.headers), + status: response.status, + statusText: response.statusText, + config, + request + }); + }) + } catch (err) { + unsubscribe && unsubscribe(); + + if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) { + throw Object.assign( + new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request), + { + cause: err.cause || err + } + ) + } + + throw AxiosError.from(err, err && err.code, config, request); + } +}); + +const knownAdapters = { + http: httpAdapter, + xhr: xhrAdapter, + fetch: fetchAdapter +}; + +utils$1.forEach(knownAdapters, (fn, value) => { + if (fn) { + try { + Object.defineProperty(fn, 'name', {value}); + } catch (e) { + // eslint-disable-next-line no-empty + } + Object.defineProperty(fn, 'adapterName', {value}); + } +}); + +const renderReason = (reason) => `- ${reason}`; + +const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; + +var adapters = { + getAdapter: (adapters) => { + adapters = utils$1.isArray(adapters) ? adapters : [adapters]; + + const {length} = adapters; + let nameOrAdapter; + let adapter; + + const rejectedReasons = {}; + + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters[i]; + let id; + + adapter = nameOrAdapter; + + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + + if (adapter === undefined) { + throw new AxiosError(`Unknown adapter '${id}'`); + } + } + + if (adapter) { + break; + } + + rejectedReasons[id || '#' + i] = adapter; + } + + if (!adapter) { + + const reasons = Object.entries(rejectedReasons) + .map(([id, state]) => `adapter ${id} ` + + (state === false ? 'is not supported by the environment' : 'is not available in the build') + ); + + let s = length ? + (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : + 'as no adapter specified'; + + throw new AxiosError( + `There is no suitable adapter to dispatch the request ` + s, + 'ERR_NOT_SUPPORT' + ); + } + + return adapter; + }, + adapters: knownAdapters +}; + +/** + * Throws a `CanceledError` if cancellation has been requested. + * + * @param {Object} config The config that is to be used for the request + * + * @returns {void} + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + + if (config.signal && config.signal.aborted) { + throw new CanceledError(null, config); + } +} + +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * + * @returns {Promise} The Promise to be fulfilled + */ +function dispatchRequest(config) { + throwIfCancellationRequested(config); + + config.headers = AxiosHeaders$1.from(config.headers); + + // Transform request data + config.data = transformData.call( + config, + config.transformRequest + ); + + if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { + config.headers.setContentType('application/x-www-form-urlencoded', false); + } + + const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData.call( + config, + config.transformResponse, + response + ); + + response.headers = AxiosHeaders$1.from(response.headers); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + config.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders$1.from(reason.response.headers); + } + } + + return Promise.reject(reason); + }); +} + +const VERSION = "1.7.9"; + +const validators$1 = {}; + +// eslint-disable-next-line func-names +['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => { + validators$1[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; +}); + +const deprecatedWarnings = {}; + +/** + * Transitional option validator + * + * @param {function|boolean?} validator - set to false if the transitional option has been removed + * @param {string?} version - deprecated version / removed since version + * @param {string?} message - some message with additional info + * + * @returns {function} + */ +validators$1.transitional = function transitional(validator, version, message) { + function formatMessage(opt, desc) { + return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + } + + // eslint-disable-next-line func-names + return (value, opt, opts) => { + if (validator === false) { + throw new AxiosError( + formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), + AxiosError.ERR_DEPRECATED + ); + } + + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); + } + + return validator ? validator(value, opt, opts) : true; + }; +}; + +validators$1.spelling = function spelling(correctSpelling) { + return (value, opt) => { + // eslint-disable-next-line no-console + console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); + return true; + } +}; + +/** + * Assert object's properties type + * + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown + * + * @returns {object} + */ + +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== 'object') { + throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); + } + const keys = Object.keys(options); + let i = keys.length; + while (i-- > 0) { + const opt = keys[i]; + const validator = schema[opt]; + if (validator) { + const value = options[opt]; + const result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); + } + } +} + +var validator = { + assertOptions, + validators: validators$1 +}; + +const validators = validator.validators; + +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + * + * @return {Axios} A new instance of Axios + */ +class Axios { + constructor(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager$1(), + response: new InterceptorManager$1() + }; + } + + /** + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled + */ + async request(configOrUrl, config) { + try { + return await this._request(configOrUrl, config); + } catch (err) { + if (err instanceof Error) { + let dummy = {}; + + Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error()); + + // slice off the Error: ... line + const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : ''; + try { + if (!err.stack) { + err.stack = stack; + // match without the 2 top stack lines + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) { + err.stack += '\n' + stack; + } + } catch (e) { + // ignore the case where "stack" is an un-writable property + } + } + + throw err; + } + } + + _request(configOrUrl, config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof configOrUrl === 'string') { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } + + config = mergeConfig(this.defaults, config); + + const {transitional, paramsSerializer, headers} = config; + + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators.boolean), + forcedJSONParsing: validators.transitional(validators.boolean), + clarifyTimeoutError: validators.transitional(validators.boolean) + }, false); + } + + if (paramsSerializer != null) { + if (utils$1.isFunction(paramsSerializer)) { + config.paramsSerializer = { + serialize: paramsSerializer + }; + } else { + validator.assertOptions(paramsSerializer, { + encode: validators.function, + serialize: validators.function + }, true); + } + } + + validator.assertOptions(config, { + baseUrl: validators.spelling('baseURL'), + withXsrfToken: validators.spelling('withXSRFToken') + }, true); + + // Set config.method + config.method = (config.method || this.defaults.method || 'get').toLowerCase(); + + // Flatten headers + let contextHeaders = headers && utils$1.merge( + headers.common, + headers[config.method] + ); + + headers && utils$1.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + (method) => { + delete headers[method]; + } + ); + + config.headers = AxiosHeaders$1.concat(contextHeaders, headers); + + // filter out skipped interceptors + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + + let promise; + let i = 0; + let len; + + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), undefined]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + + promise = Promise.resolve(config); + + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + + return promise; + } + + len = requestInterceptorChain.length; + + let newConfig = config; + + i = 0; + + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + + i = 0; + len = responseInterceptorChain.length; + + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + + return promise; + } + + getUri(config) { + config = mergeConfig(this.defaults, config); + const fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); + } +} + +// Provide aliases for supported request methods +utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method, + url, + data: (config || {}).data + })); + }; +}); + +utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig(config || {}, { + method, + headers: isForm ? { + 'Content-Type': 'multipart/form-data' + } : {}, + url, + data + })); + }; + } + + Axios.prototype[method] = generateHTTPMethod(); + + Axios.prototype[method + 'Form'] = generateHTTPMethod(true); +}); + +var Axios$1 = Axios; + +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @param {Function} executor The executor function. + * + * @returns {CancelToken} + */ +class CancelToken { + constructor(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + let resolvePromise; + + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + const token = this; + + // eslint-disable-next-line func-names + this.promise.then(cancel => { + if (!token._listeners) return; + + let i = token._listeners.length; + + while (i-- > 0) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + + // eslint-disable-next-line func-names + this.promise.then = onfulfilled => { + let _resolve; + // eslint-disable-next-line func-names + const promise = new Promise(resolve => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + + return promise; + }; + + executor(function cancel(message, config, request) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new CanceledError(message, config, request); + resolvePromise(token.reason); + }); + } + + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } + + /** + * Subscribe to the cancel signal + */ + + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } + + /** + * Unsubscribe from the cancel signal + */ + + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } + } + + toAbortSignal() { + const controller = new AbortController(); + + const abort = (err) => { + controller.abort(err); + }; + + this.subscribe(abort); + + controller.signal.unsubscribe = () => this.unsubscribe(abort); + + return controller.signal; + } + + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + static source() { + let cancel; + const token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token, + cancel + }; + } +} + +var CancelToken$1 = CancelToken; + +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * + * @returns {Function} + */ +function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +} + +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +function isAxiosError(payload) { + return utils$1.isObject(payload) && (payload.isAxiosError === true); +} + +const HttpStatusCode = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511, +}; + +Object.entries(HttpStatusCode).forEach(([key, value]) => { + HttpStatusCode[value] = key; +}); + +var HttpStatusCode$1 = HttpStatusCode; + +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * + * @returns {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + const context = new Axios$1(defaultConfig); + const instance = bind(Axios$1.prototype.request, context); + + // Copy axios.prototype to instance + utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true}); + + // Copy context to instance + utils$1.extend(instance, context, null, {allOwnKeys: true}); + + // Factory for creating new instances + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; + + return instance; +} + +// Create the default instance to be exported +const axios = createInstance(defaults$1); + +// Expose Axios class to allow class inheritance +axios.Axios = Axios$1; + +// Expose Cancel & CancelToken +axios.CanceledError = CanceledError; +axios.CancelToken = CancelToken$1; +axios.isCancel = isCancel; +axios.VERSION = VERSION; +axios.toFormData = toFormData; + +// Expose AxiosError class +axios.AxiosError = AxiosError; + +// alias for CanceledError for backward compatibility +axios.Cancel = axios.CanceledError; + +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; + +axios.spread = spread; + +// Expose isAxiosError +axios.isAxiosError = isAxiosError; + +// Expose mergeConfig +axios.mergeConfig = mergeConfig; + +axios.AxiosHeaders = AxiosHeaders$1; + +axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); + +axios.getAdapter = adapters.getAdapter; + +axios.HttpStatusCode = HttpStatusCode$1; + +axios.default = axios; + +module.exports = axios; +//# sourceMappingURL=axios.cjs.map diff --git a/node_modules/axios/dist/browser/axios.cjs.map b/node_modules/axios/dist/browser/axios.cjs.map new file mode 100644 index 000000000..f1be83dbe --- /dev/null +++ b/node_modules/axios/dist/browser/axios.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"axios.cjs","sources":["../../lib/helpers/bind.js","../../lib/utils.js","../../lib/core/AxiosError.js","../../lib/helpers/null.js","../../lib/helpers/toFormData.js","../../lib/helpers/AxiosURLSearchParams.js","../../lib/helpers/buildURL.js","../../lib/core/InterceptorManager.js","../../lib/defaults/transitional.js","../../lib/platform/browser/classes/URLSearchParams.js","../../lib/platform/browser/classes/FormData.js","../../lib/platform/browser/classes/Blob.js","../../lib/platform/browser/index.js","../../lib/platform/common/utils.js","../../lib/platform/index.js","../../lib/helpers/toURLEncodedForm.js","../../lib/helpers/formDataToJSON.js","../../lib/defaults/index.js","../../lib/helpers/parseHeaders.js","../../lib/core/AxiosHeaders.js","../../lib/core/transformData.js","../../lib/cancel/isCancel.js","../../lib/cancel/CanceledError.js","../../lib/core/settle.js","../../lib/helpers/parseProtocol.js","../../lib/helpers/speedometer.js","../../lib/helpers/throttle.js","../../lib/helpers/progressEventReducer.js","../../lib/helpers/isURLSameOrigin.js","../../lib/helpers/cookies.js","../../lib/helpers/isAbsoluteURL.js","../../lib/helpers/combineURLs.js","../../lib/core/buildFullPath.js","../../lib/core/mergeConfig.js","../../lib/helpers/resolveConfig.js","../../lib/adapters/xhr.js","../../lib/helpers/composeSignals.js","../../lib/helpers/trackStream.js","../../lib/adapters/fetch.js","../../lib/adapters/adapters.js","../../lib/core/dispatchRequest.js","../../lib/env/data.js","../../lib/helpers/validator.js","../../lib/core/Axios.js","../../lib/cancel/CancelToken.js","../../lib/helpers/spread.js","../../lib/helpers/isAxiosError.js","../../lib/helpers/HttpStatusCode.js","../../lib/axios.js"],"sourcesContent":["'use strict';\n\nexport default function bind(fn, thisArg) {\n return function wrap() {\n return fn.apply(thisArg, arguments);\n };\n}\n","'use strict';\n\nimport bind from './helpers/bind.js';\n\n// utils is a library of generic helper functions non-specific to axios\n\nconst {toString} = Object.prototype;\nconst {getPrototypeOf} = Object;\n\nconst kindOf = (cache => thing => {\n const str = toString.call(thing);\n return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());\n})(Object.create(null));\n\nconst kindOfTest = (type) => {\n type = type.toLowerCase();\n return (thing) => kindOf(thing) === type\n}\n\nconst typeOfTest = type => thing => typeof thing === type;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n *\n * @returns {boolean} True if value is an Array, otherwise false\n */\nconst {isArray} = Array;\n\n/**\n * Determine if a value is undefined\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nconst isUndefined = typeOfTest('undefined');\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nconst isArrayBuffer = kindOfTest('ArrayBuffer');\n\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n let result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a String, otherwise false\n */\nconst isString = typeOfTest('string');\n\n/**\n * Determine if a value is a Function\n *\n * @param {*} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nconst isFunction = typeOfTest('function');\n\n/**\n * Determine if a value is a Number\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Number, otherwise false\n */\nconst isNumber = typeOfTest('number');\n\n/**\n * Determine if a value is an Object\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an Object, otherwise false\n */\nconst isObject = (thing) => thing !== null && typeof thing === 'object';\n\n/**\n * Determine if a value is a Boolean\n *\n * @param {*} thing The value to test\n * @returns {boolean} True if value is a Boolean, otherwise false\n */\nconst isBoolean = thing => thing === true || thing === false;\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a plain Object, otherwise false\n */\nconst isPlainObject = (val) => {\n if (kindOf(val) !== 'object') {\n return false;\n }\n\n const prototype = getPrototypeOf(val);\n return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Date, otherwise false\n */\nconst isDate = kindOfTest('Date');\n\n/**\n * Determine if a value is a File\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFile = kindOfTest('File');\n\n/**\n * Determine if a value is a Blob\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nconst isBlob = kindOfTest('Blob');\n\n/**\n * Determine if a value is a FileList\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFileList = kindOfTest('FileList');\n\n/**\n * Determine if a value is a Stream\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nconst isStream = (val) => isObject(val) && isFunction(val.pipe);\n\n/**\n * Determine if a value is a FormData\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nconst isFormData = (thing) => {\n let kind;\n return thing && (\n (typeof FormData === 'function' && thing instanceof FormData) || (\n isFunction(thing.append) && (\n (kind = kindOf(thing)) === 'formdata' ||\n // detect form-data instance\n (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')\n )\n )\n )\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nconst isURLSearchParams = kindOfTest('URLSearchParams');\n\nconst [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n *\n * @returns {String} The String freed of excess whitespace\n */\nconst trim = (str) => str.trim ?\n str.trim() : str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '');\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n *\n * @param {Boolean} [allOwnKeys = false]\n * @returns {any}\n */\nfunction forEach(obj, fn, {allOwnKeys = false} = {}) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n let i;\n let l;\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);\n const len = keys.length;\n let key;\n\n for (i = 0; i < len; i++) {\n key = keys[i];\n fn.call(null, obj[key], key, obj);\n }\n }\n}\n\nfunction findKey(obj, key) {\n key = key.toLowerCase();\n const keys = Object.keys(obj);\n let i = keys.length;\n let _key;\n while (i-- > 0) {\n _key = keys[i];\n if (key === _key.toLowerCase()) {\n return _key;\n }\n }\n return null;\n}\n\nconst _global = (() => {\n /*eslint no-undef:0*/\n if (typeof globalThis !== \"undefined\") return globalThis;\n return typeof self !== \"undefined\" ? self : (typeof window !== 'undefined' ? window : global)\n})();\n\nconst isContextDefined = (context) => !isUndefined(context) && context !== _global;\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n *\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n const {caseless} = isContextDefined(this) && this || {};\n const result = {};\n const assignValue = (val, key) => {\n const targetKey = caseless && findKey(result, key) || key;\n if (isPlainObject(result[targetKey]) && isPlainObject(val)) {\n result[targetKey] = merge(result[targetKey], val);\n } else if (isPlainObject(val)) {\n result[targetKey] = merge({}, val);\n } else if (isArray(val)) {\n result[targetKey] = val.slice();\n } else {\n result[targetKey] = val;\n }\n }\n\n for (let i = 0, l = arguments.length; i < l; i++) {\n arguments[i] && forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n *\n * @param {Boolean} [allOwnKeys]\n * @returns {Object} The resulting value of object a\n */\nconst extend = (a, b, thisArg, {allOwnKeys}= {}) => {\n forEach(b, (val, key) => {\n if (thisArg && isFunction(val)) {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n }, {allOwnKeys});\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n *\n * @returns {string} content value without BOM\n */\nconst stripBOM = (content) => {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\n/**\n * Inherit the prototype methods from one constructor into another\n * @param {function} constructor\n * @param {function} superConstructor\n * @param {object} [props]\n * @param {object} [descriptors]\n *\n * @returns {void}\n */\nconst inherits = (constructor, superConstructor, props, descriptors) => {\n constructor.prototype = Object.create(superConstructor.prototype, descriptors);\n constructor.prototype.constructor = constructor;\n Object.defineProperty(constructor, 'super', {\n value: superConstructor.prototype\n });\n props && Object.assign(constructor.prototype, props);\n}\n\n/**\n * Resolve object with deep prototype chain to a flat object\n * @param {Object} sourceObj source object\n * @param {Object} [destObj]\n * @param {Function|Boolean} [filter]\n * @param {Function} [propFilter]\n *\n * @returns {Object}\n */\nconst toFlatObject = (sourceObj, destObj, filter, propFilter) => {\n let props;\n let i;\n let prop;\n const merged = {};\n\n destObj = destObj || {};\n // eslint-disable-next-line no-eq-null,eqeqeq\n if (sourceObj == null) return destObj;\n\n do {\n props = Object.getOwnPropertyNames(sourceObj);\n i = props.length;\n while (i-- > 0) {\n prop = props[i];\n if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {\n destObj[prop] = sourceObj[prop];\n merged[prop] = true;\n }\n }\n sourceObj = filter !== false && getPrototypeOf(sourceObj);\n } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);\n\n return destObj;\n}\n\n/**\n * Determines whether a string ends with the characters of a specified string\n *\n * @param {String} str\n * @param {String} searchString\n * @param {Number} [position= 0]\n *\n * @returns {boolean}\n */\nconst endsWith = (str, searchString, position) => {\n str = String(str);\n if (position === undefined || position > str.length) {\n position = str.length;\n }\n position -= searchString.length;\n const lastIndex = str.indexOf(searchString, position);\n return lastIndex !== -1 && lastIndex === position;\n}\n\n\n/**\n * Returns new array from array like object or null if failed\n *\n * @param {*} [thing]\n *\n * @returns {?Array}\n */\nconst toArray = (thing) => {\n if (!thing) return null;\n if (isArray(thing)) return thing;\n let i = thing.length;\n if (!isNumber(i)) return null;\n const arr = new Array(i);\n while (i-- > 0) {\n arr[i] = thing[i];\n }\n return arr;\n}\n\n/**\n * Checking if the Uint8Array exists and if it does, it returns a function that checks if the\n * thing passed in is an instance of Uint8Array\n *\n * @param {TypedArray}\n *\n * @returns {Array}\n */\n// eslint-disable-next-line func-names\nconst isTypedArray = (TypedArray => {\n // eslint-disable-next-line func-names\n return thing => {\n return TypedArray && thing instanceof TypedArray;\n };\n})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));\n\n/**\n * For each entry in the object, call the function with the key and value.\n *\n * @param {Object} obj - The object to iterate over.\n * @param {Function} fn - The function to call for each entry.\n *\n * @returns {void}\n */\nconst forEachEntry = (obj, fn) => {\n const generator = obj && obj[Symbol.iterator];\n\n const iterator = generator.call(obj);\n\n let result;\n\n while ((result = iterator.next()) && !result.done) {\n const pair = result.value;\n fn.call(obj, pair[0], pair[1]);\n }\n}\n\n/**\n * It takes a regular expression and a string, and returns an array of all the matches\n *\n * @param {string} regExp - The regular expression to match against.\n * @param {string} str - The string to search.\n *\n * @returns {Array}\n */\nconst matchAll = (regExp, str) => {\n let matches;\n const arr = [];\n\n while ((matches = regExp.exec(str)) !== null) {\n arr.push(matches);\n }\n\n return arr;\n}\n\n/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */\nconst isHTMLForm = kindOfTest('HTMLFormElement');\n\nconst toCamelCase = str => {\n return str.toLowerCase().replace(/[-_\\s]([a-z\\d])(\\w*)/g,\n function replacer(m, p1, p2) {\n return p1.toUpperCase() + p2;\n }\n );\n};\n\n/* Creating a function that will check if an object has a property. */\nconst hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);\n\n/**\n * Determine if a value is a RegExp object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a RegExp object, otherwise false\n */\nconst isRegExp = kindOfTest('RegExp');\n\nconst reduceDescriptors = (obj, reducer) => {\n const descriptors = Object.getOwnPropertyDescriptors(obj);\n const reducedDescriptors = {};\n\n forEach(descriptors, (descriptor, name) => {\n let ret;\n if ((ret = reducer(descriptor, name, obj)) !== false) {\n reducedDescriptors[name] = ret || descriptor;\n }\n });\n\n Object.defineProperties(obj, reducedDescriptors);\n}\n\n/**\n * Makes all methods read-only\n * @param {Object} obj\n */\n\nconst freezeMethods = (obj) => {\n reduceDescriptors(obj, (descriptor, name) => {\n // skip restricted props in strict mode\n if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {\n return false;\n }\n\n const value = obj[name];\n\n if (!isFunction(value)) return;\n\n descriptor.enumerable = false;\n\n if ('writable' in descriptor) {\n descriptor.writable = false;\n return;\n }\n\n if (!descriptor.set) {\n descriptor.set = () => {\n throw Error('Can not rewrite read-only method \\'' + name + '\\'');\n };\n }\n });\n}\n\nconst toObjectSet = (arrayOrString, delimiter) => {\n const obj = {};\n\n const define = (arr) => {\n arr.forEach(value => {\n obj[value] = true;\n });\n }\n\n isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));\n\n return obj;\n}\n\nconst noop = () => {}\n\nconst toFiniteNumber = (value, defaultValue) => {\n return value != null && Number.isFinite(value = +value) ? value : defaultValue;\n}\n\nconst ALPHA = 'abcdefghijklmnopqrstuvwxyz'\n\nconst DIGIT = '0123456789';\n\nconst ALPHABET = {\n DIGIT,\n ALPHA,\n ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT\n}\n\nconst generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {\n let str = '';\n const {length} = alphabet;\n while (size--) {\n str += alphabet[Math.random() * length|0]\n }\n\n return str;\n}\n\n/**\n * If the thing is a FormData object, return true, otherwise return false.\n *\n * @param {unknown} thing - The thing to check.\n *\n * @returns {boolean}\n */\nfunction isSpecCompliantForm(thing) {\n return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);\n}\n\nconst toJSONObject = (obj) => {\n const stack = new Array(10);\n\n const visit = (source, i) => {\n\n if (isObject(source)) {\n if (stack.indexOf(source) >= 0) {\n return;\n }\n\n if(!('toJSON' in source)) {\n stack[i] = source;\n const target = isArray(source) ? [] : {};\n\n forEach(source, (value, key) => {\n const reducedValue = visit(value, i + 1);\n !isUndefined(reducedValue) && (target[key] = reducedValue);\n });\n\n stack[i] = undefined;\n\n return target;\n }\n }\n\n return source;\n }\n\n return visit(obj, 0);\n}\n\nconst isAsyncFn = kindOfTest('AsyncFunction');\n\nconst isThenable = (thing) =>\n thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);\n\n// original code\n// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34\n\nconst _setImmediate = ((setImmediateSupported, postMessageSupported) => {\n if (setImmediateSupported) {\n return setImmediate;\n }\n\n return postMessageSupported ? ((token, callbacks) => {\n _global.addEventListener(\"message\", ({source, data}) => {\n if (source === _global && data === token) {\n callbacks.length && callbacks.shift()();\n }\n }, false);\n\n return (cb) => {\n callbacks.push(cb);\n _global.postMessage(token, \"*\");\n }\n })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);\n})(\n typeof setImmediate === 'function',\n isFunction(_global.postMessage)\n);\n\nconst asap = typeof queueMicrotask !== 'undefined' ?\n queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);\n\n// *********************\n\nexport default {\n isArray,\n isArrayBuffer,\n isBuffer,\n isFormData,\n isArrayBufferView,\n isString,\n isNumber,\n isBoolean,\n isObject,\n isPlainObject,\n isReadableStream,\n isRequest,\n isResponse,\n isHeaders,\n isUndefined,\n isDate,\n isFile,\n isBlob,\n isRegExp,\n isFunction,\n isStream,\n isURLSearchParams,\n isTypedArray,\n isFileList,\n forEach,\n merge,\n extend,\n trim,\n stripBOM,\n inherits,\n toFlatObject,\n kindOf,\n kindOfTest,\n endsWith,\n toArray,\n forEachEntry,\n matchAll,\n isHTMLForm,\n hasOwnProperty,\n hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection\n reduceDescriptors,\n freezeMethods,\n toObjectSet,\n toCamelCase,\n noop,\n toFiniteNumber,\n findKey,\n global: _global,\n isContextDefined,\n ALPHABET,\n generateString,\n isSpecCompliantForm,\n toJSONObject,\n isAsyncFn,\n isThenable,\n setImmediate: _setImmediate,\n asap\n};\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [config] The config.\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n *\n * @returns {Error} The created error.\n */\nfunction AxiosError(message, code, config, request, response) {\n Error.call(this);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error()).stack;\n }\n\n this.message = message;\n this.name = 'AxiosError';\n code && (this.code = code);\n config && (this.config = config);\n request && (this.request = request);\n if (response) {\n this.response = response;\n this.status = response.status ? response.status : null;\n }\n}\n\nutils.inherits(AxiosError, Error, {\n toJSON: function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: utils.toJSONObject(this.config),\n code: this.code,\n status: this.status\n };\n }\n});\n\nconst prototype = AxiosError.prototype;\nconst descriptors = {};\n\n[\n 'ERR_BAD_OPTION_VALUE',\n 'ERR_BAD_OPTION',\n 'ECONNABORTED',\n 'ETIMEDOUT',\n 'ERR_NETWORK',\n 'ERR_FR_TOO_MANY_REDIRECTS',\n 'ERR_DEPRECATED',\n 'ERR_BAD_RESPONSE',\n 'ERR_BAD_REQUEST',\n 'ERR_CANCELED',\n 'ERR_NOT_SUPPORT',\n 'ERR_INVALID_URL'\n// eslint-disable-next-line func-names\n].forEach(code => {\n descriptors[code] = {value: code};\n});\n\nObject.defineProperties(AxiosError, descriptors);\nObject.defineProperty(prototype, 'isAxiosError', {value: true});\n\n// eslint-disable-next-line func-names\nAxiosError.from = (error, code, config, request, response, customProps) => {\n const axiosError = Object.create(prototype);\n\n utils.toFlatObject(error, axiosError, function filter(obj) {\n return obj !== Error.prototype;\n }, prop => {\n return prop !== 'isAxiosError';\n });\n\n AxiosError.call(axiosError, error.message, code, config, request, response);\n\n axiosError.cause = error;\n\n axiosError.name = error.name;\n\n customProps && Object.assign(axiosError, customProps);\n\n return axiosError;\n};\n\nexport default AxiosError;\n","// eslint-disable-next-line strict\nexport default null;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\n// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored\nimport PlatformFormData from '../platform/node/classes/FormData.js';\n\n/**\n * Determines if the given thing is a array or js object.\n *\n * @param {string} thing - The object or array to be visited.\n *\n * @returns {boolean}\n */\nfunction isVisitable(thing) {\n return utils.isPlainObject(thing) || utils.isArray(thing);\n}\n\n/**\n * It removes the brackets from the end of a string\n *\n * @param {string} key - The key of the parameter.\n *\n * @returns {string} the key without the brackets.\n */\nfunction removeBrackets(key) {\n return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;\n}\n\n/**\n * It takes a path, a key, and a boolean, and returns a string\n *\n * @param {string} path - The path to the current key.\n * @param {string} key - The key of the current object being iterated over.\n * @param {string} dots - If true, the key will be rendered with dots instead of brackets.\n *\n * @returns {string} The path to the current key.\n */\nfunction renderKey(path, key, dots) {\n if (!path) return key;\n return path.concat(key).map(function each(token, i) {\n // eslint-disable-next-line no-param-reassign\n token = removeBrackets(token);\n return !dots && i ? '[' + token + ']' : token;\n }).join(dots ? '.' : '');\n}\n\n/**\n * If the array is an array and none of its elements are visitable, then it's a flat array.\n *\n * @param {Array} arr - The array to check\n *\n * @returns {boolean}\n */\nfunction isFlatArray(arr) {\n return utils.isArray(arr) && !arr.some(isVisitable);\n}\n\nconst predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {\n return /^is[A-Z]/.test(prop);\n});\n\n/**\n * Convert a data object to FormData\n *\n * @param {Object} obj\n * @param {?Object} [formData]\n * @param {?Object} [options]\n * @param {Function} [options.visitor]\n * @param {Boolean} [options.metaTokens = true]\n * @param {Boolean} [options.dots = false]\n * @param {?Boolean} [options.indexes = false]\n *\n * @returns {Object}\n **/\n\n/**\n * It converts an object into a FormData object\n *\n * @param {Object} obj - The object to convert to form data.\n * @param {string} formData - The FormData object to append to.\n * @param {Object} options\n *\n * @returns\n */\nfunction toFormData(obj, formData, options) {\n if (!utils.isObject(obj)) {\n throw new TypeError('target must be an object');\n }\n\n // eslint-disable-next-line no-param-reassign\n formData = formData || new (PlatformFormData || FormData)();\n\n // eslint-disable-next-line no-param-reassign\n options = utils.toFlatObject(options, {\n metaTokens: true,\n dots: false,\n indexes: false\n }, false, function defined(option, source) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n return !utils.isUndefined(source[option]);\n });\n\n const metaTokens = options.metaTokens;\n // eslint-disable-next-line no-use-before-define\n const visitor = options.visitor || defaultVisitor;\n const dots = options.dots;\n const indexes = options.indexes;\n const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;\n const useBlob = _Blob && utils.isSpecCompliantForm(formData);\n\n if (!utils.isFunction(visitor)) {\n throw new TypeError('visitor must be a function');\n }\n\n function convertValue(value) {\n if (value === null) return '';\n\n if (utils.isDate(value)) {\n return value.toISOString();\n }\n\n if (!useBlob && utils.isBlob(value)) {\n throw new AxiosError('Blob is not supported. Use a Buffer instead.');\n }\n\n if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {\n return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);\n }\n\n return value;\n }\n\n /**\n * Default visitor.\n *\n * @param {*} value\n * @param {String|Number} key\n * @param {Array} path\n * @this {FormData}\n *\n * @returns {boolean} return true to visit the each prop of the value recursively\n */\n function defaultVisitor(value, key, path) {\n let arr = value;\n\n if (value && !path && typeof value === 'object') {\n if (utils.endsWith(key, '{}')) {\n // eslint-disable-next-line no-param-reassign\n key = metaTokens ? key : key.slice(0, -2);\n // eslint-disable-next-line no-param-reassign\n value = JSON.stringify(value);\n } else if (\n (utils.isArray(value) && isFlatArray(value)) ||\n ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))\n )) {\n // eslint-disable-next-line no-param-reassign\n key = removeBrackets(key);\n\n arr.forEach(function each(el, index) {\n !(utils.isUndefined(el) || el === null) && formData.append(\n // eslint-disable-next-line no-nested-ternary\n indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),\n convertValue(el)\n );\n });\n return false;\n }\n }\n\n if (isVisitable(value)) {\n return true;\n }\n\n formData.append(renderKey(path, key, dots), convertValue(value));\n\n return false;\n }\n\n const stack = [];\n\n const exposedHelpers = Object.assign(predicates, {\n defaultVisitor,\n convertValue,\n isVisitable\n });\n\n function build(value, path) {\n if (utils.isUndefined(value)) return;\n\n if (stack.indexOf(value) !== -1) {\n throw Error('Circular reference detected in ' + path.join('.'));\n }\n\n stack.push(value);\n\n utils.forEach(value, function each(el, key) {\n const result = !(utils.isUndefined(el) || el === null) && visitor.call(\n formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers\n );\n\n if (result === true) {\n build(el, path ? path.concat(key) : [key]);\n }\n });\n\n stack.pop();\n }\n\n if (!utils.isObject(obj)) {\n throw new TypeError('data must be an object');\n }\n\n build(obj);\n\n return formData;\n}\n\nexport default toFormData;\n","'use strict';\n\nimport toFormData from './toFormData.js';\n\n/**\n * It encodes a string by replacing all characters that are not in the unreserved set with\n * their percent-encoded equivalents\n *\n * @param {string} str - The string to encode.\n *\n * @returns {string} The encoded string.\n */\nfunction encode(str) {\n const charMap = {\n '!': '%21',\n \"'\": '%27',\n '(': '%28',\n ')': '%29',\n '~': '%7E',\n '%20': '+',\n '%00': '\\x00'\n };\n return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {\n return charMap[match];\n });\n}\n\n/**\n * It takes a params object and converts it to a FormData object\n *\n * @param {Object} params - The parameters to be converted to a FormData object.\n * @param {Object} options - The options object passed to the Axios constructor.\n *\n * @returns {void}\n */\nfunction AxiosURLSearchParams(params, options) {\n this._pairs = [];\n\n params && toFormData(params, this, options);\n}\n\nconst prototype = AxiosURLSearchParams.prototype;\n\nprototype.append = function append(name, value) {\n this._pairs.push([name, value]);\n};\n\nprototype.toString = function toString(encoder) {\n const _encode = encoder ? function(value) {\n return encoder.call(this, value, encode);\n } : encode;\n\n return this._pairs.map(function each(pair) {\n return _encode(pair[0]) + '=' + _encode(pair[1]);\n }, '').join('&');\n};\n\nexport default AxiosURLSearchParams;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';\n\n/**\n * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their\n * URI encoded counterparts\n *\n * @param {string} val The value to be encoded.\n *\n * @returns {string} The encoded value.\n */\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @param {?(object|Function)} options\n *\n * @returns {string} The formatted url\n */\nexport default function buildURL(url, params, options) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n \n const _encode = options && options.encode || encode;\n\n if (utils.isFunction(options)) {\n options = {\n serialize: options\n };\n } \n\n const serializeFn = options && options.serialize;\n\n let serializedParams;\n\n if (serializeFn) {\n serializedParams = serializeFn(params, options);\n } else {\n serializedParams = utils.isURLSearchParams(params) ?\n params.toString() :\n new AxiosURLSearchParams(params, options).toString(_encode);\n }\n\n if (serializedParams) {\n const hashmarkIndex = url.indexOf(\"#\");\n\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\nclass InterceptorManager {\n constructor() {\n this.handlers = [];\n }\n\n /**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\n use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled,\n rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n }\n\n /**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n *\n * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise\n */\n eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n }\n\n /**\n * Clear all interceptors from the stack\n *\n * @returns {void}\n */\n clear() {\n if (this.handlers) {\n this.handlers = [];\n }\n }\n\n /**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n *\n * @returns {void}\n */\n forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n }\n}\n\nexport default InterceptorManager;\n","'use strict';\n\nexport default {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n};\n","'use strict';\n\nimport AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';\nexport default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;\n","'use strict';\n\nexport default typeof FormData !== 'undefined' ? FormData : null;\n","'use strict'\n\nexport default typeof Blob !== 'undefined' ? Blob : null\n","import URLSearchParams from './classes/URLSearchParams.js'\nimport FormData from './classes/FormData.js'\nimport Blob from './classes/Blob.js'\n\nexport default {\n isBrowser: true,\n classes: {\n URLSearchParams,\n FormData,\n Blob\n },\n protocols: ['http', 'https', 'file', 'blob', 'url', 'data']\n};\n","const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';\n\nconst _navigator = typeof navigator === 'object' && navigator || undefined;\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n *\n * @returns {boolean}\n */\nconst hasStandardBrowserEnv = hasBrowserEnv &&\n (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);\n\n/**\n * Determine if we're running in a standard browser webWorker environment\n *\n * Although the `isStandardBrowserEnv` method indicates that\n * `allows axios to run in a web worker`, the WebWorker will still be\n * filtered out due to its judgment standard\n * `typeof window !== 'undefined' && typeof document !== 'undefined'`.\n * This leads to a problem when axios post `FormData` in webWorker\n */\nconst hasStandardBrowserWebWorkerEnv = (() => {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n // eslint-disable-next-line no-undef\n self instanceof WorkerGlobalScope &&\n typeof self.importScripts === 'function'\n );\n})();\n\nconst origin = hasBrowserEnv && window.location.href || 'http://localhost';\n\nexport {\n hasBrowserEnv,\n hasStandardBrowserWebWorkerEnv,\n hasStandardBrowserEnv,\n _navigator as navigator,\n origin\n}\n","import platform from './node/index.js';\nimport * as utils from './common/utils.js';\n\nexport default {\n ...utils,\n ...platform\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport toFormData from './toFormData.js';\nimport platform from '../platform/index.js';\n\nexport default function toURLEncodedForm(data, options) {\n return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({\n visitor: function(value, key, path, helpers) {\n if (platform.isNode && utils.isBuffer(value)) {\n this.append(key, value.toString('base64'));\n return false;\n }\n\n return helpers.defaultVisitor.apply(this, arguments);\n }\n }, options));\n}\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']\n *\n * @param {string} name - The name of the property to get.\n *\n * @returns An array of strings.\n */\nfunction parsePropPath(name) {\n // foo[x][y][z]\n // foo.x.y.z\n // foo-x-y-z\n // foo x y z\n return utils.matchAll(/\\w+|\\[(\\w*)]/g, name).map(match => {\n return match[0] === '[]' ? '' : match[1] || match[0];\n });\n}\n\n/**\n * Convert an array to an object.\n *\n * @param {Array} arr - The array to convert to an object.\n *\n * @returns An object with the same keys and values as the array.\n */\nfunction arrayToObject(arr) {\n const obj = {};\n const keys = Object.keys(arr);\n let i;\n const len = keys.length;\n let key;\n for (i = 0; i < len; i++) {\n key = keys[i];\n obj[key] = arr[key];\n }\n return obj;\n}\n\n/**\n * It takes a FormData object and returns a JavaScript object\n *\n * @param {string} formData The FormData object to convert to JSON.\n *\n * @returns {Object | null} The converted object.\n */\nfunction formDataToJSON(formData) {\n function buildPath(path, value, target, index) {\n let name = path[index++];\n\n if (name === '__proto__') return true;\n\n const isNumericKey = Number.isFinite(+name);\n const isLast = index >= path.length;\n name = !name && utils.isArray(target) ? target.length : name;\n\n if (isLast) {\n if (utils.hasOwnProp(target, name)) {\n target[name] = [target[name], value];\n } else {\n target[name] = value;\n }\n\n return !isNumericKey;\n }\n\n if (!target[name] || !utils.isObject(target[name])) {\n target[name] = [];\n }\n\n const result = buildPath(path, value, target[name], index);\n\n if (result && utils.isArray(target[name])) {\n target[name] = arrayToObject(target[name]);\n }\n\n return !isNumericKey;\n }\n\n if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {\n const obj = {};\n\n utils.forEachEntry(formData, (name, value) => {\n buildPath(parsePropPath(name), value, obj, 0);\n });\n\n return obj;\n }\n\n return null;\n}\n\nexport default formDataToJSON;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\nimport transitionalDefaults from './transitional.js';\nimport toFormData from '../helpers/toFormData.js';\nimport toURLEncodedForm from '../helpers/toURLEncodedForm.js';\nimport platform from '../platform/index.js';\nimport formDataToJSON from '../helpers/formDataToJSON.js';\n\n/**\n * It takes a string, tries to parse it, and if it fails, it returns the stringified version\n * of the input\n *\n * @param {any} rawValue - The value to be stringified.\n * @param {Function} parser - A function that parses a string into a JavaScript object.\n * @param {Function} encoder - A function that takes a value and returns a string.\n *\n * @returns {string} A stringified version of the rawValue.\n */\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nconst defaults = {\n\n transitional: transitionalDefaults,\n\n adapter: ['xhr', 'http', 'fetch'],\n\n transformRequest: [function transformRequest(data, headers) {\n const contentType = headers.getContentType() || '';\n const hasJSONContentType = contentType.indexOf('application/json') > -1;\n const isObjectPayload = utils.isObject(data);\n\n if (isObjectPayload && utils.isHTMLForm(data)) {\n data = new FormData(data);\n }\n\n const isFormData = utils.isFormData(data);\n\n if (isFormData) {\n return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;\n }\n\n if (utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data) ||\n utils.isReadableStream(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);\n return data.toString();\n }\n\n let isFileList;\n\n if (isObjectPayload) {\n if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {\n return toURLEncodedForm(data, this.formSerializer).toString();\n }\n\n if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {\n const _FormData = this.env && this.env.FormData;\n\n return toFormData(\n isFileList ? {'files[]': data} : data,\n _FormData && new _FormData(),\n this.formSerializer\n );\n }\n }\n\n if (isObjectPayload || hasJSONContentType ) {\n headers.setContentType('application/json', false);\n return stringifySafely(data);\n }\n\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n const transitional = this.transitional || defaults.transitional;\n const forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n const JSONRequested = this.responseType === 'json';\n\n if (utils.isResponse(data) || utils.isReadableStream(data)) {\n return data;\n }\n\n if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {\n const silentJSONParsing = transitional && transitional.silentJSONParsing;\n const strictJSONParsing = !silentJSONParsing && JSONRequested;\n\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n env: {\n FormData: platform.classes.FormData,\n Blob: platform.classes.Blob\n },\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*',\n 'Content-Type': undefined\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {\n defaults.headers[method] = {};\n});\n\nexport default defaults;\n","'use strict';\n\nimport utils from './../utils.js';\n\n// RawAxiosHeaders whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nconst ignoreDuplicateOf = utils.toObjectSet([\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n]);\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} rawHeaders Headers needing to be parsed\n *\n * @returns {Object} Headers parsed into an object\n */\nexport default rawHeaders => {\n const parsed = {};\n let key;\n let val;\n let i;\n\n rawHeaders && rawHeaders.split('\\n').forEach(function parser(line) {\n i = line.indexOf(':');\n key = line.substring(0, i).trim().toLowerCase();\n val = line.substring(i + 1).trim();\n\n if (!key || (parsed[key] && ignoreDuplicateOf[key])) {\n return;\n }\n\n if (key === 'set-cookie') {\n if (parsed[key]) {\n parsed[key].push(val);\n } else {\n parsed[key] = [val];\n }\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n });\n\n return parsed;\n};\n","'use strict';\n\nimport utils from '../utils.js';\nimport parseHeaders from '../helpers/parseHeaders.js';\n\nconst $internals = Symbol('internals');\n\nfunction normalizeHeader(header) {\n return header && String(header).trim().toLowerCase();\n}\n\nfunction normalizeValue(value) {\n if (value === false || value == null) {\n return value;\n }\n\n return utils.isArray(value) ? value.map(normalizeValue) : String(value);\n}\n\nfunction parseTokens(str) {\n const tokens = Object.create(null);\n const tokensRE = /([^\\s,;=]+)\\s*(?:=\\s*([^,;]+))?/g;\n let match;\n\n while ((match = tokensRE.exec(str))) {\n tokens[match[1]] = match[2];\n }\n\n return tokens;\n}\n\nconst isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());\n\nfunction matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {\n if (utils.isFunction(filter)) {\n return filter.call(this, value, header);\n }\n\n if (isHeaderNameFilter) {\n value = header;\n }\n\n if (!utils.isString(value)) return;\n\n if (utils.isString(filter)) {\n return value.indexOf(filter) !== -1;\n }\n\n if (utils.isRegExp(filter)) {\n return filter.test(value);\n }\n}\n\nfunction formatHeader(header) {\n return header.trim()\n .toLowerCase().replace(/([a-z\\d])(\\w*)/g, (w, char, str) => {\n return char.toUpperCase() + str;\n });\n}\n\nfunction buildAccessors(obj, header) {\n const accessorName = utils.toCamelCase(' ' + header);\n\n ['get', 'set', 'has'].forEach(methodName => {\n Object.defineProperty(obj, methodName + accessorName, {\n value: function(arg1, arg2, arg3) {\n return this[methodName].call(this, header, arg1, arg2, arg3);\n },\n configurable: true\n });\n });\n}\n\nclass AxiosHeaders {\n constructor(headers) {\n headers && this.set(headers);\n }\n\n set(header, valueOrRewrite, rewrite) {\n const self = this;\n\n function setHeader(_value, _header, _rewrite) {\n const lHeader = normalizeHeader(_header);\n\n if (!lHeader) {\n throw new Error('header name must be a non-empty string');\n }\n\n const key = utils.findKey(self, lHeader);\n\n if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {\n self[key || _header] = normalizeValue(_value);\n }\n }\n\n const setHeaders = (headers, _rewrite) =>\n utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));\n\n if (utils.isPlainObject(header) || header instanceof this.constructor) {\n setHeaders(header, valueOrRewrite)\n } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {\n setHeaders(parseHeaders(header), valueOrRewrite);\n } else if (utils.isHeaders(header)) {\n for (const [key, value] of header.entries()) {\n setHeader(value, key, rewrite);\n }\n } else {\n header != null && setHeader(valueOrRewrite, header, rewrite);\n }\n\n return this;\n }\n\n get(header, parser) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n if (key) {\n const value = this[key];\n\n if (!parser) {\n return value;\n }\n\n if (parser === true) {\n return parseTokens(value);\n }\n\n if (utils.isFunction(parser)) {\n return parser.call(this, value, key);\n }\n\n if (utils.isRegExp(parser)) {\n return parser.exec(value);\n }\n\n throw new TypeError('parser must be boolean|regexp|function');\n }\n }\n }\n\n has(header, matcher) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));\n }\n\n return false;\n }\n\n delete(header, matcher) {\n const self = this;\n let deleted = false;\n\n function deleteHeader(_header) {\n _header = normalizeHeader(_header);\n\n if (_header) {\n const key = utils.findKey(self, _header);\n\n if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {\n delete self[key];\n\n deleted = true;\n }\n }\n }\n\n if (utils.isArray(header)) {\n header.forEach(deleteHeader);\n } else {\n deleteHeader(header);\n }\n\n return deleted;\n }\n\n clear(matcher) {\n const keys = Object.keys(this);\n let i = keys.length;\n let deleted = false;\n\n while (i--) {\n const key = keys[i];\n if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {\n delete this[key];\n deleted = true;\n }\n }\n\n return deleted;\n }\n\n normalize(format) {\n const self = this;\n const headers = {};\n\n utils.forEach(this, (value, header) => {\n const key = utils.findKey(headers, header);\n\n if (key) {\n self[key] = normalizeValue(value);\n delete self[header];\n return;\n }\n\n const normalized = format ? formatHeader(header) : String(header).trim();\n\n if (normalized !== header) {\n delete self[header];\n }\n\n self[normalized] = normalizeValue(value);\n\n headers[normalized] = true;\n });\n\n return this;\n }\n\n concat(...targets) {\n return this.constructor.concat(this, ...targets);\n }\n\n toJSON(asStrings) {\n const obj = Object.create(null);\n\n utils.forEach(this, (value, header) => {\n value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);\n });\n\n return obj;\n }\n\n [Symbol.iterator]() {\n return Object.entries(this.toJSON())[Symbol.iterator]();\n }\n\n toString() {\n return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\\n');\n }\n\n get [Symbol.toStringTag]() {\n return 'AxiosHeaders';\n }\n\n static from(thing) {\n return thing instanceof this ? thing : new this(thing);\n }\n\n static concat(first, ...targets) {\n const computed = new this(first);\n\n targets.forEach((target) => computed.set(target));\n\n return computed;\n }\n\n static accessor(header) {\n const internals = this[$internals] = (this[$internals] = {\n accessors: {}\n });\n\n const accessors = internals.accessors;\n const prototype = this.prototype;\n\n function defineAccessor(_header) {\n const lHeader = normalizeHeader(_header);\n\n if (!accessors[lHeader]) {\n buildAccessors(prototype, _header);\n accessors[lHeader] = true;\n }\n }\n\n utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);\n\n return this;\n }\n}\n\nAxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);\n\n// reserved names hotfix\nutils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {\n let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`\n return {\n get: () => value,\n set(headerValue) {\n this[mapped] = headerValue;\n }\n }\n});\n\nutils.freezeMethods(AxiosHeaders);\n\nexport default AxiosHeaders;\n","'use strict';\n\nimport utils from './../utils.js';\nimport defaults from '../defaults/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Array|Function} fns A single function or Array of functions\n * @param {?Object} response The response object\n *\n * @returns {*} The resulting transformed data\n */\nexport default function transformData(fns, response) {\n const config = this || defaults;\n const context = response || config;\n const headers = AxiosHeaders.from(context.headers);\n let data = context.data;\n\n utils.forEach(fns, function transform(fn) {\n data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);\n });\n\n headers.normalize();\n\n return data;\n}\n","'use strict';\n\nexport default function isCancel(value) {\n return !!(value && value.__CANCEL__);\n}\n","'use strict';\n\nimport AxiosError from '../core/AxiosError.js';\nimport utils from '../utils.js';\n\n/**\n * A `CanceledError` is an object that is thrown when an operation is canceled.\n *\n * @param {string=} message The message.\n * @param {Object=} config The config.\n * @param {Object=} request The request.\n *\n * @returns {CanceledError} The created error.\n */\nfunction CanceledError(message, config, request) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);\n this.name = 'CanceledError';\n}\n\nutils.inherits(CanceledError, AxiosError, {\n __CANCEL__: true\n});\n\nexport default CanceledError;\n","'use strict';\n\nimport AxiosError from './AxiosError.js';\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n *\n * @returns {object} The response.\n */\nexport default function settle(resolve, reject, response) {\n const validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(new AxiosError(\n 'Request failed with status code ' + response.status,\n [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],\n response.config,\n response.request,\n response\n ));\n }\n}\n","'use strict';\n\nexport default function parseProtocol(url) {\n const match = /^([-+\\w]{1,25})(:?\\/\\/|:)/.exec(url);\n return match && match[1] || '';\n}\n","'use strict';\n\n/**\n * Calculate data maxRate\n * @param {Number} [samplesCount= 10]\n * @param {Number} [min= 1000]\n * @returns {Function}\n */\nfunction speedometer(samplesCount, min) {\n samplesCount = samplesCount || 10;\n const bytes = new Array(samplesCount);\n const timestamps = new Array(samplesCount);\n let head = 0;\n let tail = 0;\n let firstSampleTS;\n\n min = min !== undefined ? min : 1000;\n\n return function push(chunkLength) {\n const now = Date.now();\n\n const startedAt = timestamps[tail];\n\n if (!firstSampleTS) {\n firstSampleTS = now;\n }\n\n bytes[head] = chunkLength;\n timestamps[head] = now;\n\n let i = tail;\n let bytesCount = 0;\n\n while (i !== head) {\n bytesCount += bytes[i++];\n i = i % samplesCount;\n }\n\n head = (head + 1) % samplesCount;\n\n if (head === tail) {\n tail = (tail + 1) % samplesCount;\n }\n\n if (now - firstSampleTS < min) {\n return;\n }\n\n const passed = startedAt && now - startedAt;\n\n return passed ? Math.round(bytesCount * 1000 / passed) : undefined;\n };\n}\n\nexport default speedometer;\n","/**\n * Throttle decorator\n * @param {Function} fn\n * @param {Number} freq\n * @return {Function}\n */\nfunction throttle(fn, freq) {\n let timestamp = 0;\n let threshold = 1000 / freq;\n let lastArgs;\n let timer;\n\n const invoke = (args, now = Date.now()) => {\n timestamp = now;\n lastArgs = null;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n fn.apply(null, args);\n }\n\n const throttled = (...args) => {\n const now = Date.now();\n const passed = now - timestamp;\n if ( passed >= threshold) {\n invoke(args, now);\n } else {\n lastArgs = args;\n if (!timer) {\n timer = setTimeout(() => {\n timer = null;\n invoke(lastArgs)\n }, threshold - passed);\n }\n }\n }\n\n const flush = () => lastArgs && invoke(lastArgs);\n\n return [throttled, flush];\n}\n\nexport default throttle;\n","import speedometer from \"./speedometer.js\";\nimport throttle from \"./throttle.js\";\nimport utils from \"../utils.js\";\n\nexport const progressEventReducer = (listener, isDownloadStream, freq = 3) => {\n let bytesNotified = 0;\n const _speedometer = speedometer(50, 250);\n\n return throttle(e => {\n const loaded = e.loaded;\n const total = e.lengthComputable ? e.total : undefined;\n const progressBytes = loaded - bytesNotified;\n const rate = _speedometer(progressBytes);\n const inRange = loaded <= total;\n\n bytesNotified = loaded;\n\n const data = {\n loaded,\n total,\n progress: total ? (loaded / total) : undefined,\n bytes: progressBytes,\n rate: rate ? rate : undefined,\n estimated: rate && total && inRange ? (total - loaded) / rate : undefined,\n event: e,\n lengthComputable: total != null,\n [isDownloadStream ? 'download' : 'upload']: true\n };\n\n listener(data);\n }, freq);\n}\n\nexport const progressEventDecorator = (total, throttled) => {\n const lengthComputable = total != null;\n\n return [(loaded) => throttled[0]({\n lengthComputable,\n total,\n loaded\n }), throttled[1]];\n}\n\nexport const asyncDecorator = (fn) => (...args) => utils.asap(() => fn(...args));\n","import platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {\n url = new URL(url, platform.origin);\n\n return (\n origin.protocol === url.protocol &&\n origin.host === url.host &&\n (isMSIE || origin.port === url.port)\n );\n})(\n new URL(platform.origin),\n platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)\n) : () => true;\n","import utils from './../utils.js';\nimport platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ?\n\n // Standard browser envs support document.cookie\n {\n write(name, value, expires, path, domain, secure) {\n const cookie = [name + '=' + encodeURIComponent(value)];\n\n utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());\n\n utils.isString(path) && cookie.push('path=' + path);\n\n utils.isString(domain) && cookie.push('domain=' + domain);\n\n secure === true && cookie.push('secure');\n\n document.cookie = cookie.join('; ');\n },\n\n read(name) {\n const match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n }\n\n :\n\n // Non-standard browser env (web workers, react-native) lack needed support.\n {\n write() {},\n read() {\n return null;\n },\n remove() {}\n };\n\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n *\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nexport default function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n}\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n *\n * @returns {string} The combined URL\n */\nexport default function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/?\\/$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n}\n","'use strict';\n\nimport isAbsoluteURL from '../helpers/isAbsoluteURL.js';\nimport combineURLs from '../helpers/combineURLs.js';\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n *\n * @returns {string} The combined full path\n */\nexport default function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosHeaders from \"./AxiosHeaders.js\";\n\nconst headersToObject = (thing) => thing instanceof AxiosHeaders ? { ...thing } : thing;\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n *\n * @returns {Object} New object resulting from merging config2 to config1\n */\nexport default function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n const config = {};\n\n function getMergedValue(target, source, prop, caseless) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge.call({caseless}, target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(a, b, prop , caseless) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(a, b, prop , caseless);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a, prop , caseless);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(a, b, prop) {\n if (prop in config2) {\n return getMergedValue(a, b);\n } else if (prop in config1) {\n return getMergedValue(undefined, a);\n }\n }\n\n const mergeMap = {\n url: valueFromConfig2,\n method: valueFromConfig2,\n data: valueFromConfig2,\n baseURL: defaultToConfig2,\n transformRequest: defaultToConfig2,\n transformResponse: defaultToConfig2,\n paramsSerializer: defaultToConfig2,\n timeout: defaultToConfig2,\n timeoutMessage: defaultToConfig2,\n withCredentials: defaultToConfig2,\n withXSRFToken: defaultToConfig2,\n adapter: defaultToConfig2,\n responseType: defaultToConfig2,\n xsrfCookieName: defaultToConfig2,\n xsrfHeaderName: defaultToConfig2,\n onUploadProgress: defaultToConfig2,\n onDownloadProgress: defaultToConfig2,\n decompress: defaultToConfig2,\n maxContentLength: defaultToConfig2,\n maxBodyLength: defaultToConfig2,\n beforeRedirect: defaultToConfig2,\n transport: defaultToConfig2,\n httpAgent: defaultToConfig2,\n httpsAgent: defaultToConfig2,\n cancelToken: defaultToConfig2,\n socketPath: defaultToConfig2,\n responseEncoding: defaultToConfig2,\n validateStatus: mergeDirectKeys,\n headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true)\n };\n\n utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {\n const merge = mergeMap[prop] || mergeDeepProperties;\n const configValue = merge(config1[prop], config2[prop], prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n}\n","import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport isURLSameOrigin from \"./isURLSameOrigin.js\";\nimport cookies from \"./cookies.js\";\nimport buildFullPath from \"../core/buildFullPath.js\";\nimport mergeConfig from \"../core/mergeConfig.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport buildURL from \"./buildURL.js\";\n\nexport default (config) => {\n const newConfig = mergeConfig({}, config);\n\n let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;\n\n newConfig.headers = headers = AxiosHeaders.from(headers);\n\n newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);\n\n // HTTP basic authentication\n if (auth) {\n headers.set('Authorization', 'Basic ' +\n btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))\n );\n }\n\n let contentType;\n\n if (utils.isFormData(data)) {\n if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {\n headers.setContentType(undefined); // Let the browser set it\n } else if ((contentType = headers.getContentType()) !== false) {\n // fix semicolon duplication issue for ReactNative FormData implementation\n const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];\n headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));\n }\n }\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n\n if (platform.hasStandardBrowserEnv) {\n withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));\n\n if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {\n // Add xsrf header\n const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);\n\n if (xsrfValue) {\n headers.set(xsrfHeaderName, xsrfValue);\n }\n }\n }\n\n return newConfig;\n}\n\n","import utils from './../utils.js';\nimport settle from './../core/settle.js';\nimport transitionalDefaults from '../defaults/transitional.js';\nimport AxiosError from '../core/AxiosError.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport parseProtocol from '../helpers/parseProtocol.js';\nimport platform from '../platform/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport {progressEventReducer} from '../helpers/progressEventReducer.js';\nimport resolveConfig from \"../helpers/resolveConfig.js\";\n\nconst isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';\n\nexport default isXHRAdapterSupported && function (config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n const _config = resolveConfig(config);\n let requestData = _config.data;\n const requestHeaders = AxiosHeaders.from(_config.headers).normalize();\n let {responseType, onUploadProgress, onDownloadProgress} = _config;\n let onCanceled;\n let uploadThrottled, downloadThrottled;\n let flushUpload, flushDownload;\n\n function done() {\n flushUpload && flushUpload(); // flush events\n flushDownload && flushDownload(); // flush events\n\n _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);\n\n _config.signal && _config.signal.removeEventListener('abort', onCanceled);\n }\n\n let request = new XMLHttpRequest();\n\n request.open(_config.method.toUpperCase(), _config.url, true);\n\n // Set the request timeout in MS\n request.timeout = _config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n const responseHeaders = AxiosHeaders.from(\n 'getAllResponseHeaders' in request && request.getAllResponseHeaders()\n );\n const responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n const response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config,\n request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';\n const transitional = _config.transitional || transitionalDefaults;\n if (_config.timeoutErrorMessage) {\n timeoutErrorMessage = _config.timeoutErrorMessage;\n }\n reject(new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n config,\n request));\n\n // Clean up request\n request = null;\n };\n\n // Remove Content-Type if data is undefined\n requestData === undefined && requestHeaders.setContentType(null);\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {\n request.setRequestHeader(key, val);\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(_config.withCredentials)) {\n request.withCredentials = !!_config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = _config.responseType;\n }\n\n // Handle progress if needed\n if (onDownloadProgress) {\n ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));\n request.addEventListener('progress', downloadThrottled);\n }\n\n // Not all browsers support upload events\n if (onUploadProgress && request.upload) {\n ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));\n\n request.upload.addEventListener('progress', uploadThrottled);\n\n request.upload.addEventListener('loadend', flushUpload);\n }\n\n if (_config.cancelToken || _config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = cancel => {\n if (!request) {\n return;\n }\n reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);\n request.abort();\n request = null;\n };\n\n _config.cancelToken && _config.cancelToken.subscribe(onCanceled);\n if (_config.signal) {\n _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n const protocol = parseProtocol(_config.url);\n\n if (protocol && platform.protocols.indexOf(protocol) === -1) {\n reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));\n return;\n }\n\n\n // Send the request\n request.send(requestData || null);\n });\n}\n","import CanceledError from \"../cancel/CanceledError.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport utils from '../utils.js';\n\nconst composeSignals = (signals, timeout) => {\n const {length} = (signals = signals ? signals.filter(Boolean) : []);\n\n if (timeout || length) {\n let controller = new AbortController();\n\n let aborted;\n\n const onabort = function (reason) {\n if (!aborted) {\n aborted = true;\n unsubscribe();\n const err = reason instanceof Error ? reason : this.reason;\n controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));\n }\n }\n\n let timer = timeout && setTimeout(() => {\n timer = null;\n onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT))\n }, timeout)\n\n const unsubscribe = () => {\n if (signals) {\n timer && clearTimeout(timer);\n timer = null;\n signals.forEach(signal => {\n signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);\n });\n signals = null;\n }\n }\n\n signals.forEach((signal) => signal.addEventListener('abort', onabort));\n\n const {signal} = controller;\n\n signal.unsubscribe = () => utils.asap(unsubscribe);\n\n return signal;\n }\n}\n\nexport default composeSignals;\n","\nexport const streamChunk = function* (chunk, chunkSize) {\n let len = chunk.byteLength;\n\n if (!chunkSize || len < chunkSize) {\n yield chunk;\n return;\n }\n\n let pos = 0;\n let end;\n\n while (pos < len) {\n end = pos + chunkSize;\n yield chunk.slice(pos, end);\n pos = end;\n }\n}\n\nexport const readBytes = async function* (iterable, chunkSize) {\n for await (const chunk of readStream(iterable)) {\n yield* streamChunk(chunk, chunkSize);\n }\n}\n\nconst readStream = async function* (stream) {\n if (stream[Symbol.asyncIterator]) {\n yield* stream;\n return;\n }\n\n const reader = stream.getReader();\n try {\n for (;;) {\n const {done, value} = await reader.read();\n if (done) {\n break;\n }\n yield value;\n }\n } finally {\n await reader.cancel();\n }\n}\n\nexport const trackStream = (stream, chunkSize, onProgress, onFinish) => {\n const iterator = readBytes(stream, chunkSize);\n\n let bytes = 0;\n let done;\n let _onFinish = (e) => {\n if (!done) {\n done = true;\n onFinish && onFinish(e);\n }\n }\n\n return new ReadableStream({\n async pull(controller) {\n try {\n const {done, value} = await iterator.next();\n\n if (done) {\n _onFinish();\n controller.close();\n return;\n }\n\n let len = value.byteLength;\n if (onProgress) {\n let loadedBytes = bytes += len;\n onProgress(loadedBytes);\n }\n controller.enqueue(new Uint8Array(value));\n } catch (err) {\n _onFinish(err);\n throw err;\n }\n },\n cancel(reason) {\n _onFinish(reason);\n return iterator.return();\n }\n }, {\n highWaterMark: 2\n })\n}\n","import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport composeSignals from \"../helpers/composeSignals.js\";\nimport {trackStream} from \"../helpers/trackStream.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport {progressEventReducer, progressEventDecorator, asyncDecorator} from \"../helpers/progressEventReducer.js\";\nimport resolveConfig from \"../helpers/resolveConfig.js\";\nimport settle from \"../core/settle.js\";\n\nconst isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';\nconst isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';\n\n// used only inside the fetch adapter\nconst encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?\n ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :\n async (str) => new Uint8Array(await new Response(str).arrayBuffer())\n);\n\nconst test = (fn, ...args) => {\n try {\n return !!fn(...args);\n } catch (e) {\n return false\n }\n}\n\nconst supportsRequestStream = isReadableStreamSupported && test(() => {\n let duplexAccessed = false;\n\n const hasContentType = new Request(platform.origin, {\n body: new ReadableStream(),\n method: 'POST',\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n }).headers.has('Content-Type');\n\n return duplexAccessed && !hasContentType;\n});\n\nconst DEFAULT_CHUNK_SIZE = 64 * 1024;\n\nconst supportsResponseStream = isReadableStreamSupported &&\n test(() => utils.isReadableStream(new Response('').body));\n\n\nconst resolvers = {\n stream: supportsResponseStream && ((res) => res.body)\n};\n\nisFetchSupported && (((res) => {\n ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {\n !resolvers[type] && (resolvers[type] = utils.isFunction(res[type]) ? (res) => res[type]() :\n (_, config) => {\n throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);\n })\n });\n})(new Response));\n\nconst getBodyLength = async (body) => {\n if (body == null) {\n return 0;\n }\n\n if(utils.isBlob(body)) {\n return body.size;\n }\n\n if(utils.isSpecCompliantForm(body)) {\n const _request = new Request(platform.origin, {\n method: 'POST',\n body,\n });\n return (await _request.arrayBuffer()).byteLength;\n }\n\n if(utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) {\n return body.byteLength;\n }\n\n if(utils.isURLSearchParams(body)) {\n body = body + '';\n }\n\n if(utils.isString(body)) {\n return (await encodeText(body)).byteLength;\n }\n}\n\nconst resolveBodyLength = async (headers, body) => {\n const length = utils.toFiniteNumber(headers.getContentLength());\n\n return length == null ? getBodyLength(body) : length;\n}\n\nexport default isFetchSupported && (async (config) => {\n let {\n url,\n method,\n data,\n signal,\n cancelToken,\n timeout,\n onDownloadProgress,\n onUploadProgress,\n responseType,\n headers,\n withCredentials = 'same-origin',\n fetchOptions\n } = resolveConfig(config);\n\n responseType = responseType ? (responseType + '').toLowerCase() : 'text';\n\n let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);\n\n let request;\n\n const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {\n composedSignal.unsubscribe();\n });\n\n let requestContentLength;\n\n try {\n if (\n onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&\n (requestContentLength = await resolveBodyLength(headers, data)) !== 0\n ) {\n let _request = new Request(url, {\n method: 'POST',\n body: data,\n duplex: \"half\"\n });\n\n let contentTypeHeader;\n\n if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {\n headers.setContentType(contentTypeHeader)\n }\n\n if (_request.body) {\n const [onProgress, flush] = progressEventDecorator(\n requestContentLength,\n progressEventReducer(asyncDecorator(onUploadProgress))\n );\n\n data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);\n }\n }\n\n if (!utils.isString(withCredentials)) {\n withCredentials = withCredentials ? 'include' : 'omit';\n }\n\n // Cloudflare Workers throws when credentials are defined\n // see https://github.com/cloudflare/workerd/issues/902\n const isCredentialsSupported = \"credentials\" in Request.prototype;\n request = new Request(url, {\n ...fetchOptions,\n signal: composedSignal,\n method: method.toUpperCase(),\n headers: headers.normalize().toJSON(),\n body: data,\n duplex: \"half\",\n credentials: isCredentialsSupported ? withCredentials : undefined\n });\n\n let response = await fetch(request);\n\n const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');\n\n if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {\n const options = {};\n\n ['status', 'statusText', 'headers'].forEach(prop => {\n options[prop] = response[prop];\n });\n\n const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length'));\n\n const [onProgress, flush] = onDownloadProgress && progressEventDecorator(\n responseContentLength,\n progressEventReducer(asyncDecorator(onDownloadProgress), true)\n ) || [];\n\n response = new Response(\n trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {\n flush && flush();\n unsubscribe && unsubscribe();\n }),\n options\n );\n }\n\n responseType = responseType || 'text';\n\n let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config);\n\n !isStreamResponse && unsubscribe && unsubscribe();\n\n return await new Promise((resolve, reject) => {\n settle(resolve, reject, {\n data: responseData,\n headers: AxiosHeaders.from(response.headers),\n status: response.status,\n statusText: response.statusText,\n config,\n request\n })\n })\n } catch (err) {\n unsubscribe && unsubscribe();\n\n if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {\n throw Object.assign(\n new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),\n {\n cause: err.cause || err\n }\n )\n }\n\n throw AxiosError.from(err, err && err.code, config, request);\n }\n});\n\n\n","import utils from '../utils.js';\nimport httpAdapter from './http.js';\nimport xhrAdapter from './xhr.js';\nimport fetchAdapter from './fetch.js';\nimport AxiosError from \"../core/AxiosError.js\";\n\nconst knownAdapters = {\n http: httpAdapter,\n xhr: xhrAdapter,\n fetch: fetchAdapter\n}\n\nutils.forEach(knownAdapters, (fn, value) => {\n if (fn) {\n try {\n Object.defineProperty(fn, 'name', {value});\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n Object.defineProperty(fn, 'adapterName', {value});\n }\n});\n\nconst renderReason = (reason) => `- ${reason}`;\n\nconst isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false;\n\nexport default {\n getAdapter: (adapters) => {\n adapters = utils.isArray(adapters) ? adapters : [adapters];\n\n const {length} = adapters;\n let nameOrAdapter;\n let adapter;\n\n const rejectedReasons = {};\n\n for (let i = 0; i < length; i++) {\n nameOrAdapter = adapters[i];\n let id;\n\n adapter = nameOrAdapter;\n\n if (!isResolvedHandle(nameOrAdapter)) {\n adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];\n\n if (adapter === undefined) {\n throw new AxiosError(`Unknown adapter '${id}'`);\n }\n }\n\n if (adapter) {\n break;\n }\n\n rejectedReasons[id || '#' + i] = adapter;\n }\n\n if (!adapter) {\n\n const reasons = Object.entries(rejectedReasons)\n .map(([id, state]) => `adapter ${id} ` +\n (state === false ? 'is not supported by the environment' : 'is not available in the build')\n );\n\n let s = length ?\n (reasons.length > 1 ? 'since :\\n' + reasons.map(renderReason).join('\\n') : ' ' + renderReason(reasons[0])) :\n 'as no adapter specified';\n\n throw new AxiosError(\n `There is no suitable adapter to dispatch the request ` + s,\n 'ERR_NOT_SUPPORT'\n );\n }\n\n return adapter;\n },\n adapters: knownAdapters\n}\n","'use strict';\n\nimport transformData from './transformData.js';\nimport isCancel from '../cancel/isCancel.js';\nimport defaults from '../defaults/index.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport adapters from \"../adapters/adapters.js\";\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n *\n * @param {Object} config The config that is to be used for the request\n *\n * @returns {void}\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new CanceledError(null, config);\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n *\n * @returns {Promise} The Promise to be fulfilled\n */\nexport default function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n config.headers = AxiosHeaders.from(config.headers);\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.transformRequest\n );\n\n if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {\n config.headers.setContentType('application/x-www-form-urlencoded', false);\n }\n\n const adapter = adapters.getAdapter(config.adapter || defaults.adapter);\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n config.transformResponse,\n response\n );\n\n response.headers = AxiosHeaders.from(response.headers);\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n config.transformResponse,\n reason.response\n );\n reason.response.headers = AxiosHeaders.from(reason.response.headers);\n }\n }\n\n return Promise.reject(reason);\n });\n}\n","export const VERSION = \"1.7.9\";","'use strict';\n\nimport {VERSION} from '../env/data.js';\nimport AxiosError from '../core/AxiosError.js';\n\nconst validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nconst deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n *\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n *\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return (value, opt, opts) => {\n if (validator === false) {\n throw new AxiosError(\n formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),\n AxiosError.ERR_DEPRECATED\n );\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\nvalidators.spelling = function spelling(correctSpelling) {\n return (value, opt) => {\n // eslint-disable-next-line no-console\n console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);\n return true;\n }\n};\n\n/**\n * Assert object's properties type\n *\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n *\n * @returns {object}\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);\n }\n const keys = Object.keys(options);\n let i = keys.length;\n while (i-- > 0) {\n const opt = keys[i];\n const validator = schema[opt];\n if (validator) {\n const value = options[opt];\n const result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);\n }\n }\n}\n\nexport default {\n assertOptions,\n validators\n};\n","'use strict';\n\nimport utils from './../utils.js';\nimport buildURL from '../helpers/buildURL.js';\nimport InterceptorManager from './InterceptorManager.js';\nimport dispatchRequest from './dispatchRequest.js';\nimport mergeConfig from './mergeConfig.js';\nimport buildFullPath from './buildFullPath.js';\nimport validator from '../helpers/validator.js';\nimport AxiosHeaders from './AxiosHeaders.js';\n\nconst validators = validator.validators;\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n *\n * @return {Axios} A new instance of Axios\n */\nclass Axios {\n constructor(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n }\n\n /**\n * Dispatch a request\n *\n * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)\n * @param {?Object} config\n *\n * @returns {Promise} The Promise to be fulfilled\n */\n async request(configOrUrl, config) {\n try {\n return await this._request(configOrUrl, config);\n } catch (err) {\n if (err instanceof Error) {\n let dummy = {};\n\n Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());\n\n // slice off the Error: ... line\n const stack = dummy.stack ? dummy.stack.replace(/^.+\\n/, '') : '';\n try {\n if (!err.stack) {\n err.stack = stack;\n // match without the 2 top stack lines\n } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\\n.+\\n/, ''))) {\n err.stack += '\\n' + stack\n }\n } catch (e) {\n // ignore the case where \"stack\" is an un-writable property\n }\n }\n\n throw err;\n }\n }\n\n _request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n const {transitional, paramsSerializer, headers} = config;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n if (paramsSerializer != null) {\n if (utils.isFunction(paramsSerializer)) {\n config.paramsSerializer = {\n serialize: paramsSerializer\n }\n } else {\n validator.assertOptions(paramsSerializer, {\n encode: validators.function,\n serialize: validators.function\n }, true);\n }\n }\n\n validator.assertOptions(config, {\n baseUrl: validators.spelling('baseURL'),\n withXsrfToken: validators.spelling('withXSRFToken')\n }, true);\n\n // Set config.method\n config.method = (config.method || this.defaults.method || 'get').toLowerCase();\n\n // Flatten headers\n let contextHeaders = headers && utils.merge(\n headers.common,\n headers[config.method]\n );\n\n headers && utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n (method) => {\n delete headers[method];\n }\n );\n\n config.headers = AxiosHeaders.concat(contextHeaders, headers);\n\n // filter out skipped interceptors\n const requestInterceptorChain = [];\n let synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n const responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n let promise;\n let i = 0;\n let len;\n\n if (!synchronousRequestInterceptors) {\n const chain = [dispatchRequest.bind(this), undefined];\n chain.unshift.apply(chain, requestInterceptorChain);\n chain.push.apply(chain, responseInterceptorChain);\n len = chain.length;\n\n promise = Promise.resolve(config);\n\n while (i < len) {\n promise = promise.then(chain[i++], chain[i++]);\n }\n\n return promise;\n }\n\n len = requestInterceptorChain.length;\n\n let newConfig = config;\n\n i = 0;\n\n while (i < len) {\n const onFulfilled = requestInterceptorChain[i++];\n const onRejected = requestInterceptorChain[i++];\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected.call(this, error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest.call(this, newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n i = 0;\n len = responseInterceptorChain.length;\n\n while (i < len) {\n promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);\n }\n\n return promise;\n }\n\n getUri(config) {\n config = mergeConfig(this.defaults, config);\n const fullPath = buildFullPath(config.baseURL, config.url);\n return buildURL(fullPath, config.params, config.paramsSerializer);\n }\n}\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n\n function generateHTTPMethod(isForm) {\n return function httpMethod(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n headers: isForm ? {\n 'Content-Type': 'multipart/form-data'\n } : {},\n url,\n data\n }));\n };\n }\n\n Axios.prototype[method] = generateHTTPMethod();\n\n Axios.prototype[method + 'Form'] = generateHTTPMethod(true);\n});\n\nexport default Axios;\n","'use strict';\n\nimport CanceledError from './CanceledError.js';\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @param {Function} executor The executor function.\n *\n * @returns {CancelToken}\n */\nclass CancelToken {\n constructor(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n let resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n const token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(cancel => {\n if (!token._listeners) return;\n\n let i = token._listeners.length;\n\n while (i-- > 0) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = onfulfilled => {\n let _resolve;\n // eslint-disable-next-line func-names\n const promise = new Promise(resolve => {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message, config, request) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new CanceledError(message, config, request);\n resolvePromise(token.reason);\n });\n }\n\n /**\n * Throws a `CanceledError` if cancellation has been requested.\n */\n throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n }\n\n /**\n * Subscribe to the cancel signal\n */\n\n subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n }\n\n /**\n * Unsubscribe from the cancel signal\n */\n\n unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n const index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n }\n\n toAbortSignal() {\n const controller = new AbortController();\n\n const abort = (err) => {\n controller.abort(err);\n };\n\n this.subscribe(abort);\n\n controller.signal.unsubscribe = () => this.unsubscribe(abort);\n\n return controller.signal;\n }\n\n /**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\n static source() {\n let cancel;\n const token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token,\n cancel\n };\n }\n}\n\nexport default CancelToken;\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n *\n * @returns {Function}\n */\nexport default function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n *\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nexport default function isAxiosError(payload) {\n return utils.isObject(payload) && (payload.isAxiosError === true);\n}\n","const HttpStatusCode = {\n Continue: 100,\n SwitchingProtocols: 101,\n Processing: 102,\n EarlyHints: 103,\n Ok: 200,\n Created: 201,\n Accepted: 202,\n NonAuthoritativeInformation: 203,\n NoContent: 204,\n ResetContent: 205,\n PartialContent: 206,\n MultiStatus: 207,\n AlreadyReported: 208,\n ImUsed: 226,\n MultipleChoices: 300,\n MovedPermanently: 301,\n Found: 302,\n SeeOther: 303,\n NotModified: 304,\n UseProxy: 305,\n Unused: 306,\n TemporaryRedirect: 307,\n PermanentRedirect: 308,\n BadRequest: 400,\n Unauthorized: 401,\n PaymentRequired: 402,\n Forbidden: 403,\n NotFound: 404,\n MethodNotAllowed: 405,\n NotAcceptable: 406,\n ProxyAuthenticationRequired: 407,\n RequestTimeout: 408,\n Conflict: 409,\n Gone: 410,\n LengthRequired: 411,\n PreconditionFailed: 412,\n PayloadTooLarge: 413,\n UriTooLong: 414,\n UnsupportedMediaType: 415,\n RangeNotSatisfiable: 416,\n ExpectationFailed: 417,\n ImATeapot: 418,\n MisdirectedRequest: 421,\n UnprocessableEntity: 422,\n Locked: 423,\n FailedDependency: 424,\n TooEarly: 425,\n UpgradeRequired: 426,\n PreconditionRequired: 428,\n TooManyRequests: 429,\n RequestHeaderFieldsTooLarge: 431,\n UnavailableForLegalReasons: 451,\n InternalServerError: 500,\n NotImplemented: 501,\n BadGateway: 502,\n ServiceUnavailable: 503,\n GatewayTimeout: 504,\n HttpVersionNotSupported: 505,\n VariantAlsoNegotiates: 506,\n InsufficientStorage: 507,\n LoopDetected: 508,\n NotExtended: 510,\n NetworkAuthenticationRequired: 511,\n};\n\nObject.entries(HttpStatusCode).forEach(([key, value]) => {\n HttpStatusCode[value] = key;\n});\n\nexport default HttpStatusCode;\n","'use strict';\n\nimport utils from './utils.js';\nimport bind from './helpers/bind.js';\nimport Axios from './core/Axios.js';\nimport mergeConfig from './core/mergeConfig.js';\nimport defaults from './defaults/index.js';\nimport formDataToJSON from './helpers/formDataToJSON.js';\nimport CanceledError from './cancel/CanceledError.js';\nimport CancelToken from './cancel/CancelToken.js';\nimport isCancel from './cancel/isCancel.js';\nimport {VERSION} from './env/data.js';\nimport toFormData from './helpers/toFormData.js';\nimport AxiosError from './core/AxiosError.js';\nimport spread from './helpers/spread.js';\nimport isAxiosError from './helpers/isAxiosError.js';\nimport AxiosHeaders from \"./core/AxiosHeaders.js\";\nimport adapters from './adapters/adapters.js';\nimport HttpStatusCode from './helpers/HttpStatusCode.js';\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n *\n * @returns {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n const context = new Axios(defaultConfig);\n const instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});\n\n // Copy context to instance\n utils.extend(instance, context, null, {allOwnKeys: true});\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nconst axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.CanceledError = CanceledError;\naxios.CancelToken = CancelToken;\naxios.isCancel = isCancel;\naxios.VERSION = VERSION;\naxios.toFormData = toFormData;\n\n// Expose AxiosError class\naxios.AxiosError = AxiosError;\n\n// alias for CanceledError for backward compatibility\naxios.Cancel = axios.CanceledError;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\n\naxios.spread = spread;\n\n// Expose isAxiosError\naxios.isAxiosError = isAxiosError;\n\n// Expose mergeConfig\naxios.mergeConfig = mergeConfig;\n\naxios.AxiosHeaders = AxiosHeaders;\n\naxios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);\n\naxios.getAdapter = adapters.getAdapter;\n\naxios.HttpStatusCode = HttpStatusCode;\n\naxios.default = axios;\n\n// this module should only have a default export\nexport default axios\n"],"names":["utils","prototype","encode","URLSearchParams","FormData","Blob","platform","defaults","AxiosHeaders","composeSignals","validators","InterceptorManager","Axios","CancelToken","HttpStatusCode"],"mappings":";;;AAEe,SAAS,IAAI,CAAC,EAAE,EAAE,OAAO,EAAE;AAC1C,EAAE,OAAO,SAAS,IAAI,GAAG;AACzB,IAAI,OAAO,EAAE,CAAC,KAAK,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;AACxC,GAAG,CAAC;AACJ;;ACFA;AACA;AACA,MAAM,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC,SAAS,CAAC;AACpC,MAAM,CAAC,cAAc,CAAC,GAAG,MAAM,CAAC;AAChC;AACA,MAAM,MAAM,GAAG,CAAC,KAAK,IAAI,KAAK,IAAI;AAClC,IAAI,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACrC,IAAI,OAAO,KAAK,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AACvE,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACxB;AACA,MAAM,UAAU,GAAG,CAAC,IAAI,KAAK;AAC7B,EAAE,IAAI,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;AAC5B,EAAE,OAAO,CAAC,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,KAAK,IAAI;AAC1C,EAAC;AACD;AACA,MAAM,UAAU,GAAG,IAAI,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,IAAI,CAAC;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,WAAW,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,QAAQ,CAAC,GAAG,EAAE;AACvB,EAAE,OAAO,GAAG,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,WAAW,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,WAAW,CAAC;AACvG,OAAO,UAAU,CAAC,GAAG,CAAC,WAAW,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC,WAAW,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AAC7E,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,UAAU,CAAC,aAAa,CAAC,CAAC;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,iBAAiB,CAAC,GAAG,EAAE;AAChC,EAAE,IAAI,MAAM,CAAC;AACb,EAAE,IAAI,CAAC,OAAO,WAAW,KAAK,WAAW,MAAM,WAAW,CAAC,MAAM,CAAC,EAAE;AACpE,IAAI,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACrC,GAAG,MAAM;AACT,IAAI,MAAM,GAAG,CAAC,GAAG,MAAM,GAAG,CAAC,MAAM,CAAC,KAAK,aAAa,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;AAClE,GAAG;AACH,EAAE,OAAO,MAAM,CAAC;AAChB,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,UAAU,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,KAAK,KAAK,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,SAAS,GAAG,KAAK,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,KAAK,CAAC;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,GAAG,KAAK;AAC/B,EAAE,IAAI,MAAM,CAAC,GAAG,CAAC,KAAK,QAAQ,EAAE;AAChC,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA,EAAE,MAAM,SAAS,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC;AACxC,EAAE,OAAO,CAAC,SAAS,KAAK,IAAI,IAAI,SAAS,KAAK,MAAM,CAAC,SAAS,IAAI,MAAM,CAAC,cAAc,CAAC,SAAS,CAAC,KAAK,IAAI,KAAK,EAAE,MAAM,CAAC,WAAW,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,QAAQ,IAAI,GAAG,CAAC,CAAC;AAC1K,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,UAAU,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,GAAG,KAAK,QAAQ,CAAC,GAAG,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AAChE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,UAAU,GAAG,CAAC,KAAK,KAAK;AAC9B,EAAE,IAAI,IAAI,CAAC;AACX,EAAE,OAAO,KAAK;AACd,IAAI,CAAC,OAAO,QAAQ,KAAK,UAAU,IAAI,KAAK,YAAY,QAAQ;AAChE,MAAM,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC;AAC9B,QAAQ,CAAC,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,UAAU;AAC7C;AACA,SAAS,IAAI,KAAK,QAAQ,IAAI,UAAU,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,KAAK,CAAC,QAAQ,EAAE,KAAK,mBAAmB,CAAC;AACrG,OAAO;AACP,KAAK;AACL,GAAG;AACH,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,iBAAiB,GAAG,UAAU,CAAC,iBAAiB,CAAC,CAAC;AACxD;AACA,MAAM,CAAC,gBAAgB,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,CAAC,GAAG,CAAC,gBAAgB,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;AAClI;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,IAAI;AAC9B,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,oCAAoC,EAAE,EAAE,CAAC,CAAC;AACrE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,OAAO,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC,UAAU,GAAG,KAAK,CAAC,GAAG,EAAE,EAAE;AACrD;AACA,EAAE,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,WAAW,EAAE;AAClD,IAAI,OAAO;AACX,GAAG;AACH;AACA,EAAE,IAAI,CAAC,CAAC;AACR,EAAE,IAAI,CAAC,CAAC;AACR;AACA;AACA,EAAE,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;AAC/B;AACA,IAAI,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;AAChB,GAAG;AACH;AACA,EAAE,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE;AACpB;AACA,IAAI,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AAC5C,MAAM,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AACpC,KAAK;AACL,GAAG,MAAM;AACT;AACA,IAAI,MAAM,IAAI,GAAG,UAAU,GAAG,MAAM,CAAC,mBAAmB,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjF,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC;AAC5B,IAAI,IAAI,GAAG,CAAC;AACZ;AACA,IAAI,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;AAC9B,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,MAAM,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AACxC,KAAK;AACL,GAAG;AACH,CAAC;AACD;AACA,SAAS,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE;AAC3B,EAAE,GAAG,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;AAC1B,EAAE,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAChC,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;AACtB,EAAE,IAAI,IAAI,CAAC;AACX,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AAClB,IAAI,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AACnB,IAAI,IAAI,GAAG,KAAK,IAAI,CAAC,WAAW,EAAE,EAAE;AACpC,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL,GAAG;AACH,EAAE,OAAO,IAAI,CAAC;AACd,CAAC;AACD;AACA,MAAM,OAAO,GAAG,CAAC,MAAM;AACvB;AACA,EAAE,IAAI,OAAO,UAAU,KAAK,WAAW,EAAE,OAAO,UAAU,CAAC;AAC3D,EAAE,OAAO,OAAO,IAAI,KAAK,WAAW,GAAG,IAAI,IAAI,OAAO,MAAM,KAAK,WAAW,GAAG,MAAM,GAAG,MAAM,CAAC;AAC/F,CAAC,GAAG,CAAC;AACL;AACA,MAAM,gBAAgB,GAAG,CAAC,OAAO,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,OAAO,KAAK,OAAO,CAAC;AACnF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,KAAK,8BAA8B;AAC5C,EAAE,MAAM,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,EAAE,CAAC;AAC1D,EAAE,MAAM,MAAM,GAAG,EAAE,CAAC;AACpB,EAAE,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,GAAG,KAAK;AACpC,IAAI,MAAM,SAAS,GAAG,QAAQ,IAAI,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,GAAG,CAAC;AAC9D,IAAI,IAAI,aAAa,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,IAAI,aAAa,CAAC,GAAG,CAAC,EAAE;AAChE,MAAM,MAAM,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,GAAG,CAAC,CAAC;AACxD,KAAK,MAAM,IAAI,aAAa,CAAC,GAAG,CAAC,EAAE;AACnC,MAAM,MAAM,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;AACzC,KAAK,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE;AAC7B,MAAM,MAAM,CAAC,SAAS,CAAC,GAAG,GAAG,CAAC,KAAK,EAAE,CAAC;AACtC,KAAK,MAAM;AACX,MAAM,MAAM,CAAC,SAAS,CAAC,GAAG,GAAG,CAAC;AAC9B,KAAK;AACL,IAAG;AACH;AACA,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AACpD,IAAI,SAAS,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC;AACvD,GAAG;AACH,EAAE,OAAO,MAAM,CAAC;AAChB,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,UAAU,CAAC,EAAE,EAAE,KAAK;AACpD,EAAE,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK;AAC3B,IAAI,IAAI,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,EAAE;AACpC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;AAClC,KAAK,MAAM;AACX,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC;AACnB,KAAK;AACL,GAAG,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;AACnB,EAAE,OAAO,CAAC,CAAC;AACX,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,OAAO,KAAK;AAC9B,EAAE,IAAI,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE;AACxC,IAAI,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAC/B,GAAG;AACH,EAAE,OAAO,OAAO,CAAC;AACjB,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,WAAW,EAAE,gBAAgB,EAAE,KAAK,EAAE,WAAW,KAAK;AACxE,EAAE,WAAW,CAAC,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;AACjF,EAAE,WAAW,CAAC,SAAS,CAAC,WAAW,GAAG,WAAW,CAAC;AAClD,EAAE,MAAM,CAAC,cAAc,CAAC,WAAW,EAAE,OAAO,EAAE;AAC9C,IAAI,KAAK,EAAE,gBAAgB,CAAC,SAAS;AACrC,GAAG,CAAC,CAAC;AACL,EAAE,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AACvD,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,YAAY,GAAG,CAAC,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,KAAK;AACjE,EAAE,IAAI,KAAK,CAAC;AACZ,EAAE,IAAI,CAAC,CAAC;AACR,EAAE,IAAI,IAAI,CAAC;AACX,EAAE,MAAM,MAAM,GAAG,EAAE,CAAC;AACpB;AACA,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;AAC1B;AACA,EAAE,IAAI,SAAS,IAAI,IAAI,EAAE,OAAO,OAAO,CAAC;AACxC;AACA,EAAE,GAAG;AACL,IAAI,KAAK,GAAG,MAAM,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC;AAClD,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC;AACrB,IAAI,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AACpB,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,IAAI,CAAC,CAAC,UAAU,IAAI,UAAU,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;AAClF,QAAQ,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;AACxC,QAAQ,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAC5B,OAAO;AACP,KAAK;AACL,IAAI,SAAS,GAAG,MAAM,KAAK,KAAK,IAAI,cAAc,CAAC,SAAS,CAAC,CAAC;AAC9D,GAAG,QAAQ,SAAS,KAAK,CAAC,MAAM,IAAI,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,SAAS,KAAK,MAAM,CAAC,SAAS,EAAE;AACnG;AACA,EAAE,OAAO,OAAO,CAAC;AACjB,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,GAAG,EAAE,YAAY,EAAE,QAAQ,KAAK;AAClD,EAAE,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AACpB,EAAE,IAAI,QAAQ,KAAK,SAAS,IAAI,QAAQ,GAAG,GAAG,CAAC,MAAM,EAAE;AACvD,IAAI,QAAQ,GAAG,GAAG,CAAC,MAAM,CAAC;AAC1B,GAAG;AACH,EAAE,QAAQ,IAAI,YAAY,CAAC,MAAM,CAAC;AAClC,EAAE,MAAM,SAAS,GAAG,GAAG,CAAC,OAAO,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC;AACxD,EAAE,OAAO,SAAS,KAAK,CAAC,CAAC,IAAI,SAAS,KAAK,QAAQ,CAAC;AACpD,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,OAAO,GAAG,CAAC,KAAK,KAAK;AAC3B,EAAE,IAAI,CAAC,KAAK,EAAE,OAAO,IAAI,CAAC;AAC1B,EAAE,IAAI,OAAO,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;AACnC,EAAE,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC;AACvB,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,OAAO,IAAI,CAAC;AAChC,EAAE,MAAM,GAAG,GAAG,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC;AAC3B,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AAClB,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AACtB,GAAG;AACH,EAAE,OAAO,GAAG,CAAC;AACb,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,YAAY,GAAG,CAAC,UAAU,IAAI;AACpC;AACA,EAAE,OAAO,KAAK,IAAI;AAClB,IAAI,OAAO,UAAU,IAAI,KAAK,YAAY,UAAU,CAAC;AACrD,GAAG,CAAC;AACJ,CAAC,EAAE,OAAO,UAAU,KAAK,WAAW,IAAI,cAAc,CAAC,UAAU,CAAC,CAAC,CAAC;AACpE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,YAAY,GAAG,CAAC,GAAG,EAAE,EAAE,KAAK;AAClC,EAAE,MAAM,SAAS,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAChD;AACA,EAAE,MAAM,QAAQ,GAAG,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACvC;AACA,EAAE,IAAI,MAAM,CAAC;AACb;AACA,EAAE,OAAO,CAAC,MAAM,GAAG,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE;AACrD,IAAI,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC;AAC9B,IAAI,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AACnC,GAAG;AACH,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,MAAM,EAAE,GAAG,KAAK;AAClC,EAAE,IAAI,OAAO,CAAC;AACd,EAAE,MAAM,GAAG,GAAG,EAAE,CAAC;AACjB;AACA,EAAE,OAAO,CAAC,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,IAAI,EAAE;AAChD,IAAI,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACtB,GAAG;AACH;AACA,EAAE,OAAO,GAAG,CAAC;AACb,EAAC;AACD;AACA;AACA,MAAM,UAAU,GAAG,UAAU,CAAC,iBAAiB,CAAC,CAAC;AACjD;AACA,MAAM,WAAW,GAAG,GAAG,IAAI;AAC3B,EAAE,OAAO,GAAG,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,uBAAuB;AAC1D,IAAI,SAAS,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE;AACjC,MAAM,OAAO,EAAE,CAAC,WAAW,EAAE,GAAG,EAAE,CAAC;AACnC,KAAK;AACL,GAAG,CAAC;AACJ,CAAC,CAAC;AACF;AACA;AACA,MAAM,cAAc,GAAG,CAAC,CAAC,CAAC,cAAc,CAAC,KAAK,CAAC,GAAG,EAAE,IAAI,KAAK,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC;AAC/G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;AACtC;AACA,MAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,OAAO,KAAK;AAC5C,EAAE,MAAM,WAAW,GAAG,MAAM,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC;AAC5D,EAAE,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAChC;AACA,EAAE,OAAO,CAAC,WAAW,EAAE,CAAC,UAAU,EAAE,IAAI,KAAK;AAC7C,IAAI,IAAI,GAAG,CAAC;AACZ,IAAI,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,UAAU,EAAE,IAAI,EAAE,GAAG,CAAC,MAAM,KAAK,EAAE;AAC1D,MAAM,kBAAkB,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,UAAU,CAAC;AACnD,KAAK;AACL,GAAG,CAAC,CAAC;AACL;AACA,EAAE,MAAM,CAAC,gBAAgB,CAAC,GAAG,EAAE,kBAAkB,CAAC,CAAC;AACnD,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,GAAG,KAAK;AAC/B,EAAE,iBAAiB,CAAC,GAAG,EAAE,CAAC,UAAU,EAAE,IAAI,KAAK;AAC/C;AACA,IAAI,IAAI,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE;AACnF,MAAM,OAAO,KAAK,CAAC;AACnB,KAAK;AACL;AACA,IAAI,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC;AAC5B;AACA,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,OAAO;AACnC;AACA,IAAI,UAAU,CAAC,UAAU,GAAG,KAAK,CAAC;AAClC;AACA,IAAI,IAAI,UAAU,IAAI,UAAU,EAAE;AAClC,MAAM,UAAU,CAAC,QAAQ,GAAG,KAAK,CAAC;AAClC,MAAM,OAAO;AACb,KAAK;AACL;AACA,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE;AACzB,MAAM,UAAU,CAAC,GAAG,GAAG,MAAM;AAC7B,QAAQ,MAAM,KAAK,CAAC,qCAAqC,GAAG,IAAI,GAAG,IAAI,CAAC,CAAC;AACzE,OAAO,CAAC;AACR,KAAK;AACL,GAAG,CAAC,CAAC;AACL,EAAC;AACD;AACA,MAAM,WAAW,GAAG,CAAC,aAAa,EAAE,SAAS,KAAK;AAClD,EAAE,MAAM,GAAG,GAAG,EAAE,CAAC;AACjB;AACA,EAAE,MAAM,MAAM,GAAG,CAAC,GAAG,KAAK;AAC1B,IAAI,GAAG,CAAC,OAAO,CAAC,KAAK,IAAI;AACzB,MAAM,GAAG,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC;AACxB,KAAK,CAAC,CAAC;AACP,IAAG;AACH;AACA,EAAE,OAAO,CAAC,aAAa,CAAC,GAAG,MAAM,CAAC,aAAa,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC;AAClG;AACA,EAAE,OAAO,GAAG,CAAC;AACb,EAAC;AACD;AACA,MAAM,IAAI,GAAG,MAAM,GAAE;AACrB;AACA,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,YAAY,KAAK;AAChD,EAAE,OAAO,KAAK,IAAI,IAAI,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,GAAG,CAAC,KAAK,CAAC,GAAG,KAAK,GAAG,YAAY,CAAC;AACjF,EAAC;AACD;AACA,MAAM,KAAK,GAAG,6BAA4B;AAC1C;AACA,MAAM,KAAK,GAAG,YAAY,CAAC;AAC3B;AACA,MAAM,QAAQ,GAAG;AACjB,EAAE,KAAK;AACP,EAAE,KAAK;AACP,EAAE,WAAW,EAAE,KAAK,GAAG,KAAK,CAAC,WAAW,EAAE,GAAG,KAAK;AAClD,EAAC;AACD;AACA,MAAM,cAAc,GAAG,CAAC,IAAI,GAAG,EAAE,EAAE,QAAQ,GAAG,QAAQ,CAAC,WAAW,KAAK;AACvE,EAAE,IAAI,GAAG,GAAG,EAAE,CAAC;AACf,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC;AAC5B,EAAE,OAAO,IAAI,EAAE,EAAE;AACjB,IAAI,GAAG,IAAI,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,MAAM,CAAC,CAAC,EAAC;AAC7C,GAAG;AACH;AACA,EAAE,OAAO,GAAG,CAAC;AACb,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,mBAAmB,CAAC,KAAK,EAAE;AACpC,EAAE,OAAO,CAAC,EAAE,KAAK,IAAI,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,WAAW,CAAC,KAAK,UAAU,IAAI,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;AACrH,CAAC;AACD;AACA,MAAM,YAAY,GAAG,CAAC,GAAG,KAAK;AAC9B,EAAE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC;AAC9B;AACA,EAAE,MAAM,KAAK,GAAG,CAAC,MAAM,EAAE,CAAC,KAAK;AAC/B;AACA,IAAI,IAAI,QAAQ,CAAC,MAAM,CAAC,EAAE;AAC1B,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;AACtC,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,GAAG,EAAE,QAAQ,IAAI,MAAM,CAAC,EAAE;AAChC,QAAQ,KAAK,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC;AAC1B,QAAQ,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;AACjD;AACA,QAAQ,OAAO,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK;AACxC,UAAU,MAAM,YAAY,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;AACnD,UAAU,CAAC,WAAW,CAAC,YAAY,CAAC,KAAK,MAAM,CAAC,GAAG,CAAC,GAAG,YAAY,CAAC,CAAC;AACrE,SAAS,CAAC,CAAC;AACX;AACA,QAAQ,KAAK,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC;AAC7B;AACA,QAAQ,OAAO,MAAM,CAAC;AACtB,OAAO;AACP,KAAK;AACL;AACA,IAAI,OAAO,MAAM,CAAC;AAClB,IAAG;AACH;AACA,EAAE,OAAO,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;AACvB,EAAC;AACD;AACA,MAAM,SAAS,GAAG,UAAU,CAAC,eAAe,CAAC,CAAC;AAC9C;AACA,MAAM,UAAU,GAAG,CAAC,KAAK;AACzB,EAAE,KAAK,KAAK,QAAQ,CAAC,KAAK,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACvG;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,CAAC,qBAAqB,EAAE,oBAAoB,KAAK;AACxE,EAAE,IAAI,qBAAqB,EAAE;AAC7B,IAAI,OAAO,YAAY,CAAC;AACxB,GAAG;AACH;AACA,EAAE,OAAO,oBAAoB,GAAG,CAAC,CAAC,KAAK,EAAE,SAAS,KAAK;AACvD,IAAI,OAAO,CAAC,gBAAgB,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK;AAC5D,MAAM,IAAI,MAAM,KAAK,OAAO,IAAI,IAAI,KAAK,KAAK,EAAE;AAChD,QAAQ,SAAS,CAAC,MAAM,IAAI,SAAS,CAAC,KAAK,EAAE,EAAE,CAAC;AAChD,OAAO;AACP,KAAK,EAAE,KAAK,CAAC,CAAC;AACd;AACA,IAAI,OAAO,CAAC,EAAE,KAAK;AACnB,MAAM,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACzB,MAAM,OAAO,CAAC,WAAW,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AACtC,KAAK;AACL,GAAG,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,UAAU,CAAC,EAAE,CAAC,CAAC;AAC5D,CAAC;AACD,EAAE,OAAO,YAAY,KAAK,UAAU;AACpC,EAAE,UAAU,CAAC,OAAO,CAAC,WAAW,CAAC;AACjC,CAAC,CAAC;AACF;AACA,MAAM,IAAI,GAAG,OAAO,cAAc,KAAK,WAAW;AAClD,EAAE,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,CAAC,QAAQ,IAAI,aAAa,CAAC,CAAC;AACxG;AACA;AACA;AACA,cAAe;AACf,EAAE,OAAO;AACT,EAAE,aAAa;AACf,EAAE,QAAQ;AACV,EAAE,UAAU;AACZ,EAAE,iBAAiB;AACnB,EAAE,QAAQ;AACV,EAAE,QAAQ;AACV,EAAE,SAAS;AACX,EAAE,QAAQ;AACV,EAAE,aAAa;AACf,EAAE,gBAAgB;AAClB,EAAE,SAAS;AACX,EAAE,UAAU;AACZ,EAAE,SAAS;AACX,EAAE,WAAW;AACb,EAAE,MAAM;AACR,EAAE,MAAM;AACR,EAAE,MAAM;AACR,EAAE,QAAQ;AACV,EAAE,UAAU;AACZ,EAAE,QAAQ;AACV,EAAE,iBAAiB;AACnB,EAAE,YAAY;AACd,EAAE,UAAU;AACZ,EAAE,OAAO;AACT,EAAE,KAAK;AACP,EAAE,MAAM;AACR,EAAE,IAAI;AACN,EAAE,QAAQ;AACV,EAAE,QAAQ;AACV,EAAE,YAAY;AACd,EAAE,MAAM;AACR,EAAE,UAAU;AACZ,EAAE,QAAQ;AACV,EAAE,OAAO;AACT,EAAE,YAAY;AACd,EAAE,QAAQ;AACV,EAAE,UAAU;AACZ,EAAE,cAAc;AAChB,EAAE,UAAU,EAAE,cAAc;AAC5B,EAAE,iBAAiB;AACnB,EAAE,aAAa;AACf,EAAE,WAAW;AACb,EAAE,WAAW;AACb,EAAE,IAAI;AACN,EAAE,cAAc;AAChB,EAAE,OAAO;AACT,EAAE,MAAM,EAAE,OAAO;AACjB,EAAE,gBAAgB;AAClB,EAAE,QAAQ;AACV,EAAE,cAAc;AAChB,EAAE,mBAAmB;AACrB,EAAE,YAAY;AACd,EAAE,SAAS;AACX,EAAE,UAAU;AACZ,EAAE,YAAY,EAAE,aAAa;AAC7B,EAAE,IAAI;AACN,CAAC;;ACnvBD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,UAAU,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE;AAC9D,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACnB;AACA,EAAE,IAAI,KAAK,CAAC,iBAAiB,EAAE;AAC/B,IAAI,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;AACpD,GAAG,MAAM;AACT,IAAI,IAAI,CAAC,KAAK,GAAG,CAAC,IAAI,KAAK,EAAE,EAAE,KAAK,CAAC;AACrC,GAAG;AACH;AACA,EAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;AACzB,EAAE,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;AAC3B,EAAE,IAAI,KAAK,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC;AAC7B,EAAE,MAAM,KAAK,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC;AACnC,EAAE,OAAO,KAAK,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,CAAC;AACtC,EAAE,IAAI,QAAQ,EAAE;AAChB,IAAI,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAC7B,IAAI,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC,MAAM,GAAG,IAAI,CAAC;AAC3D,GAAG;AACH,CAAC;AACD;AACAA,OAAK,CAAC,QAAQ,CAAC,UAAU,EAAE,KAAK,EAAE;AAClC,EAAE,MAAM,EAAE,SAAS,MAAM,GAAG;AAC5B,IAAI,OAAO;AACX;AACA,MAAM,OAAO,EAAE,IAAI,CAAC,OAAO;AAC3B,MAAM,IAAI,EAAE,IAAI,CAAC,IAAI;AACrB;AACA,MAAM,WAAW,EAAE,IAAI,CAAC,WAAW;AACnC,MAAM,MAAM,EAAE,IAAI,CAAC,MAAM;AACzB;AACA,MAAM,QAAQ,EAAE,IAAI,CAAC,QAAQ;AAC7B,MAAM,UAAU,EAAE,IAAI,CAAC,UAAU;AACjC,MAAM,YAAY,EAAE,IAAI,CAAC,YAAY;AACrC,MAAM,KAAK,EAAE,IAAI,CAAC,KAAK;AACvB;AACA,MAAM,MAAM,EAAEA,OAAK,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC;AAC7C,MAAM,IAAI,EAAE,IAAI,CAAC,IAAI;AACrB,MAAM,MAAM,EAAE,IAAI,CAAC,MAAM;AACzB,KAAK,CAAC;AACN,GAAG;AACH,CAAC,CAAC,CAAC;AACH;AACA,MAAMC,WAAS,GAAG,UAAU,CAAC,SAAS,CAAC;AACvC,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB;AACA;AACA,EAAE,sBAAsB;AACxB,EAAE,gBAAgB;AAClB,EAAE,cAAc;AAChB,EAAE,WAAW;AACb,EAAE,aAAa;AACf,EAAE,2BAA2B;AAC7B,EAAE,gBAAgB;AAClB,EAAE,kBAAkB;AACpB,EAAE,iBAAiB;AACnB,EAAE,cAAc;AAChB,EAAE,iBAAiB;AACnB,EAAE,iBAAiB;AACnB;AACA,CAAC,CAAC,OAAO,CAAC,IAAI,IAAI;AAClB,EAAE,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACpC,CAAC,CAAC,CAAC;AACH;AACA,MAAM,CAAC,gBAAgB,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;AACjD,MAAM,CAAC,cAAc,CAACA,WAAS,EAAE,cAAc,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;AAChE;AACA;AACA,UAAU,CAAC,IAAI,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,WAAW,KAAK;AAC3E,EAAE,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAACA,WAAS,CAAC,CAAC;AAC9C;AACA,EAAED,OAAK,CAAC,YAAY,CAAC,KAAK,EAAE,UAAU,EAAE,SAAS,MAAM,CAAC,GAAG,EAAE;AAC7D,IAAI,OAAO,GAAG,KAAK,KAAK,CAAC,SAAS,CAAC;AACnC,GAAG,EAAE,IAAI,IAAI;AACb,IAAI,OAAO,IAAI,KAAK,cAAc,CAAC;AACnC,GAAG,CAAC,CAAC;AACL;AACA,EAAE,UAAU,CAAC,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC9E;AACA,EAAE,UAAU,CAAC,KAAK,GAAG,KAAK,CAAC;AAC3B;AACA,EAAE,UAAU,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;AAC/B;AACA,EAAE,WAAW,IAAI,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;AACxD;AACA,EAAE,OAAO,UAAU,CAAC;AACpB,CAAC;;ACpGD;AACA,kBAAe,IAAI;;ACMnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,WAAW,CAAC,KAAK,EAAE;AAC5B,EAAE,OAAOA,OAAK,CAAC,aAAa,CAAC,KAAK,CAAC,IAAIA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,cAAc,CAAC,GAAG,EAAE;AAC7B,EAAE,OAAOA,OAAK,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC;AAC5D,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,SAAS,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE;AACpC,EAAE,IAAI,CAAC,IAAI,EAAE,OAAO,GAAG,CAAC;AACxB,EAAE,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,KAAK,EAAE,CAAC,EAAE;AACtD;AACA,IAAI,KAAK,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;AAClC,IAAI,OAAO,CAAC,IAAI,IAAI,CAAC,GAAG,GAAG,GAAG,KAAK,GAAG,GAAG,GAAG,KAAK,CAAC;AAClD,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC,CAAC;AAC3B,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,WAAW,CAAC,GAAG,EAAE;AAC1B,EAAE,OAAOA,OAAK,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AACtD,CAAC;AACD;AACA,MAAM,UAAU,GAAGA,OAAK,CAAC,YAAY,CAACA,OAAK,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,MAAM,CAAC,IAAI,EAAE;AAC7E,EAAE,OAAO,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC/B,CAAC,CAAC,CAAC;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,UAAU,CAAC,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE;AAC5C,EAAE,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;AAC5B,IAAI,MAAM,IAAI,SAAS,CAAC,0BAA0B,CAAC,CAAC;AACpD,GAAG;AACH;AACA;AACA,EAAE,QAAQ,GAAG,QAAQ,IAAI,KAAyB,QAAQ,GAAG,CAAC;AAC9D;AACA;AACA,EAAE,OAAO,GAAGA,OAAK,CAAC,YAAY,CAAC,OAAO,EAAE;AACxC,IAAI,UAAU,EAAE,IAAI;AACpB,IAAI,IAAI,EAAE,KAAK;AACf,IAAI,OAAO,EAAE,KAAK;AAClB,GAAG,EAAE,KAAK,EAAE,SAAS,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE;AAC7C;AACA,IAAI,OAAO,CAACA,OAAK,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;AAC9C,GAAG,CAAC,CAAC;AACL;AACA,EAAE,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;AACxC;AACA,EAAE,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,cAAc,CAAC;AACpD,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;AAC5B,EAAE,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;AAClC,EAAE,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,WAAW,IAAI,IAAI,CAAC;AACpE,EAAE,MAAM,OAAO,GAAG,KAAK,IAAIA,OAAK,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAC;AAC/D;AACA,EAAE,IAAI,CAACA,OAAK,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE;AAClC,IAAI,MAAM,IAAI,SAAS,CAAC,4BAA4B,CAAC,CAAC;AACtD,GAAG;AACH;AACA,EAAE,SAAS,YAAY,CAAC,KAAK,EAAE;AAC/B,IAAI,IAAI,KAAK,KAAK,IAAI,EAAE,OAAO,EAAE,CAAC;AAClC;AACA,IAAI,IAAIA,OAAK,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;AAC7B,MAAM,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;AACjC,KAAK;AACL;AACA,IAAI,IAAI,CAAC,OAAO,IAAIA,OAAK,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;AACzC,MAAM,MAAM,IAAI,UAAU,CAAC,8CAA8C,CAAC,CAAC;AAC3E,KAAK;AACL;AACA,IAAI,IAAIA,OAAK,CAAC,aAAa,CAAC,KAAK,CAAC,IAAIA,OAAK,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE;AACjE,MAAM,OAAO,OAAO,IAAI,OAAO,IAAI,KAAK,UAAU,GAAG,IAAI,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC5F,KAAK;AACL;AACA,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,SAAS,cAAc,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE;AAC5C,IAAI,IAAI,GAAG,GAAG,KAAK,CAAC;AACpB;AACA,IAAI,IAAI,KAAK,IAAI,CAAC,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;AACrD,MAAM,IAAIA,OAAK,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE;AACrC;AACA,QAAQ,GAAG,GAAG,UAAU,GAAG,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAClD;AACA,QAAQ,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AACtC,OAAO,MAAM;AACb,QAAQ,CAACA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,WAAW,CAAC,KAAK,CAAC;AACnD,SAAS,CAACA,OAAK,CAAC,UAAU,CAAC,KAAK,CAAC,IAAIA,OAAK,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC/F,SAAS,EAAE;AACX;AACA,QAAQ,GAAG,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC;AAClC;AACA,QAAQ,GAAG,CAAC,OAAO,CAAC,SAAS,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE;AAC7C,UAAU,EAAEA,OAAK,CAAC,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,KAAK,IAAI,CAAC,IAAI,QAAQ,CAAC,MAAM;AACpE;AACA,YAAY,OAAO,KAAK,IAAI,GAAG,SAAS,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,OAAO,KAAK,IAAI,GAAG,GAAG,GAAG,GAAG,GAAG,IAAI,CAAC;AACpG,YAAY,YAAY,CAAC,EAAE,CAAC;AAC5B,WAAW,CAAC;AACZ,SAAS,CAAC,CAAC;AACX,QAAQ,OAAO,KAAK,CAAC;AACrB,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE;AAC5B,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL;AACA,IAAI,QAAQ,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC;AACrE;AACA,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA,EAAE,MAAM,KAAK,GAAG,EAAE,CAAC;AACnB;AACA,EAAE,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE;AACnD,IAAI,cAAc;AAClB,IAAI,YAAY;AAChB,IAAI,WAAW;AACf,GAAG,CAAC,CAAC;AACL;AACA,EAAE,SAAS,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE;AAC9B,IAAI,IAAIA,OAAK,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE,OAAO;AACzC;AACA,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE;AACrC,MAAM,MAAM,KAAK,CAAC,iCAAiC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AACtE,KAAK;AACL;AACA,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACtB;AACA,IAAIA,OAAK,CAAC,OAAO,CAAC,KAAK,EAAE,SAAS,IAAI,CAAC,EAAE,EAAE,GAAG,EAAE;AAChD,MAAM,MAAM,MAAM,GAAG,EAAEA,OAAK,CAAC,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,KAAK,IAAI,CAAC,IAAI,OAAO,CAAC,IAAI;AAC5E,QAAQ,QAAQ,EAAE,EAAE,EAAEA,OAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,GAAG,GAAG,EAAE,IAAI,EAAE,cAAc;AAClF,OAAO,CAAC;AACR;AACA,MAAM,IAAI,MAAM,KAAK,IAAI,EAAE;AAC3B,QAAQ,KAAK,CAAC,EAAE,EAAE,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;AACnD,OAAO;AACP,KAAK,CAAC,CAAC;AACP;AACA,IAAI,KAAK,CAAC,GAAG,EAAE,CAAC;AAChB,GAAG;AACH;AACA,EAAE,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;AAC5B,IAAI,MAAM,IAAI,SAAS,CAAC,wBAAwB,CAAC,CAAC;AAClD,GAAG;AACH;AACA,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;AACb;AACA,EAAE,OAAO,QAAQ,CAAC;AAClB;;ACpNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASE,QAAM,CAAC,GAAG,EAAE;AACrB,EAAE,MAAM,OAAO,GAAG;AAClB,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,KAAK,EAAE,GAAG;AACd,IAAI,KAAK,EAAE,MAAM;AACjB,GAAG,CAAC;AACJ,EAAE,OAAO,kBAAkB,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,kBAAkB,EAAE,SAAS,QAAQ,CAAC,KAAK,EAAE;AACtF,IAAI,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC;AAC1B,GAAG,CAAC,CAAC;AACL,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,oBAAoB,CAAC,MAAM,EAAE,OAAO,EAAE;AAC/C,EAAE,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;AACnB;AACA,EAAE,MAAM,IAAI,UAAU,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;AAC9C,CAAC;AACD;AACA,MAAM,SAAS,GAAG,oBAAoB,CAAC,SAAS,CAAC;AACjD;AACA,SAAS,CAAC,MAAM,GAAG,SAAS,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE;AAChD,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;AAClC,CAAC,CAAC;AACF;AACA,SAAS,CAAC,QAAQ,GAAG,SAAS,QAAQ,CAAC,OAAO,EAAE;AAChD,EAAE,MAAM,OAAO,GAAG,OAAO,GAAG,SAAS,KAAK,EAAE;AAC5C,IAAI,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAEA,QAAM,CAAC,CAAC;AAC7C,GAAG,GAAGA,QAAM,CAAC;AACb;AACA,EAAE,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,IAAI,EAAE;AAC7C,IAAI,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AACrD,GAAG,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACnB,CAAC;;AClDD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,MAAM,CAAC,GAAG,EAAE;AACrB,EAAE,OAAO,kBAAkB,CAAC,GAAG,CAAC;AAChC,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;AACzB,IAAI,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;AACxB,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;AACzB,IAAI,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;AACxB,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;AACzB,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AAC1B,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE;AACvD;AACA,EAAE,IAAI,CAAC,MAAM,EAAE;AACf,IAAI,OAAO,GAAG,CAAC;AACf,GAAG;AACH;AACA,EAAE,MAAM,OAAO,GAAG,OAAO,IAAI,OAAO,CAAC,MAAM,IAAI,MAAM,CAAC;AACtD;AACA,EAAE,IAAIF,OAAK,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE;AACjC,IAAI,OAAO,GAAG;AACd,MAAM,SAAS,EAAE,OAAO;AACxB,KAAK,CAAC;AACN,GAAG;AACH;AACA,EAAE,MAAM,WAAW,GAAG,OAAO,IAAI,OAAO,CAAC,SAAS,CAAC;AACnD;AACA,EAAE,IAAI,gBAAgB,CAAC;AACvB;AACA,EAAE,IAAI,WAAW,EAAE;AACnB,IAAI,gBAAgB,GAAG,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AACpD,GAAG,MAAM;AACT,IAAI,gBAAgB,GAAGA,OAAK,CAAC,iBAAiB,CAAC,MAAM,CAAC;AACtD,MAAM,MAAM,CAAC,QAAQ,EAAE;AACvB,MAAM,IAAI,oBAAoB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAClE,GAAG;AACH;AACA,EAAE,IAAI,gBAAgB,EAAE;AACxB,IAAI,MAAM,aAAa,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AAC3C;AACA,IAAI,IAAI,aAAa,KAAK,CAAC,CAAC,EAAE;AAC9B,MAAM,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC;AACxC,KAAK;AACL,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG,IAAI,gBAAgB,CAAC;AACpE,GAAG;AACH;AACA,EAAE,OAAO,GAAG,CAAC;AACb;;AChEA,MAAM,kBAAkB,CAAC;AACzB,EAAE,WAAW,GAAG;AAChB,IAAI,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;AACvB,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,GAAG,CAAC,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE;AACpC,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;AACvB,MAAM,SAAS;AACf,MAAM,QAAQ;AACd,MAAM,WAAW,EAAE,OAAO,GAAG,OAAO,CAAC,WAAW,GAAG,KAAK;AACxD,MAAM,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI;AAC/C,KAAK,CAAC,CAAC;AACP,IAAI,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;AACpC,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,KAAK,CAAC,EAAE,EAAE;AACZ,IAAI,IAAI,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE;AAC3B,MAAM,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC;AAC/B,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,KAAK,GAAG;AACV,IAAI,IAAI,IAAI,CAAC,QAAQ,EAAE;AACvB,MAAM,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;AACzB,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,OAAO,CAAC,EAAE,EAAE;AACd,IAAIA,OAAK,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,SAAS,cAAc,CAAC,CAAC,EAAE;AAC5D,MAAM,IAAI,CAAC,KAAK,IAAI,EAAE;AACtB,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC;AACd,OAAO;AACP,KAAK,CAAC,CAAC;AACP,GAAG;AACH,CAAC;AACD;AACA,2BAAe,kBAAkB;;ACpEjC,2BAAe;AACf,EAAE,iBAAiB,EAAE,IAAI;AACzB,EAAE,iBAAiB,EAAE,IAAI;AACzB,EAAE,mBAAmB,EAAE,KAAK;AAC5B,CAAC;;ACHD,wBAAe,OAAO,eAAe,KAAK,WAAW,GAAG,eAAe,GAAG,oBAAoB;;ACD9F,iBAAe,OAAO,QAAQ,KAAK,WAAW,GAAG,QAAQ,GAAG,IAAI;;ACAhE,aAAe,OAAO,IAAI,KAAK,WAAW,GAAG,IAAI,GAAG;;ACEpD,iBAAe;AACf,EAAE,SAAS,EAAE,IAAI;AACjB,EAAE,OAAO,EAAE;AACX,qBAAIG,iBAAe;AACnB,cAAIC,UAAQ;AACZ,UAAIC,MAAI;AACR,GAAG;AACH,EAAE,SAAS,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC;AAC7D,CAAC;;ACZD,MAAM,aAAa,GAAG,OAAO,MAAM,KAAK,WAAW,IAAI,OAAO,QAAQ,KAAK,WAAW,CAAC;AACvF;AACA,MAAM,UAAU,GAAG,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,IAAI,SAAS,CAAC;AAC3E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,qBAAqB,GAAG,aAAa;AAC3C,GAAG,CAAC,UAAU,IAAI,CAAC,aAAa,EAAE,cAAc,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;AACzF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,8BAA8B,GAAG,CAAC,MAAM;AAC9C,EAAE;AACF,IAAI,OAAO,iBAAiB,KAAK,WAAW;AAC5C;AACA,IAAI,IAAI,YAAY,iBAAiB;AACrC,IAAI,OAAO,IAAI,CAAC,aAAa,KAAK,UAAU;AAC5C,IAAI;AACJ,CAAC,GAAG,CAAC;AACL;AACA,MAAM,MAAM,GAAG,aAAa,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,IAAI,kBAAkB;;;;;;;;;;;ACvC1E,eAAe;AACf,EAAE,GAAG,KAAK;AACV,EAAE,GAAGC,UAAQ;AACb;;ACAe,SAAS,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE;AACxD,EAAE,OAAO,UAAU,CAAC,IAAI,EAAE,IAAI,QAAQ,CAAC,OAAO,CAAC,eAAe,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC;AAChF,IAAI,OAAO,EAAE,SAAS,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE;AACjD,MAAM,IAAI,QAAQ,CAAC,MAAM,IAAIN,OAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;AACpD,QAAQ,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC;AACnD,QAAQ,OAAO,KAAK,CAAC;AACrB,OAAO;AACP;AACA,MAAM,OAAO,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;AAC3D,KAAK;AACL,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AACf;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,aAAa,CAAC,IAAI,EAAE;AAC7B;AACA;AACA;AACA;AACA,EAAE,OAAOA,OAAK,CAAC,QAAQ,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,IAAI;AAC5D,IAAI,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC;AACzD,GAAG,CAAC,CAAC;AACL,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,aAAa,CAAC,GAAG,EAAE;AAC5B,EAAE,MAAM,GAAG,GAAG,EAAE,CAAC;AACjB,EAAE,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAChC,EAAE,IAAI,CAAC,CAAC;AACR,EAAE,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC;AAC1B,EAAE,IAAI,GAAG,CAAC;AACV,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;AAC5B,IAAI,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;AACxB,GAAG;AACH,EAAE,OAAO,GAAG,CAAC;AACb,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,cAAc,CAAC,QAAQ,EAAE;AAClC,EAAE,SAAS,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE;AACjD,IAAI,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;AAC7B;AACA,IAAI,IAAI,IAAI,KAAK,WAAW,EAAE,OAAO,IAAI,CAAC;AAC1C;AACA,IAAI,MAAM,YAAY,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC;AAChD,IAAI,MAAM,MAAM,GAAG,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC;AACxC,IAAI,IAAI,GAAG,CAAC,IAAI,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC;AACjE;AACA,IAAI,IAAI,MAAM,EAAE;AAChB,MAAM,IAAIA,OAAK,CAAC,UAAU,CAAC,MAAM,EAAE,IAAI,CAAC,EAAE;AAC1C,QAAQ,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC;AAC7C,OAAO,MAAM;AACb,QAAQ,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;AAC7B,OAAO;AACP;AACA,MAAM,OAAO,CAAC,YAAY,CAAC;AAC3B,KAAK;AACL;AACA,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE;AACxD,MAAM,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;AACxB,KAAK;AACL;AACA,IAAI,MAAM,MAAM,GAAG,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC;AAC/D;AACA,IAAI,IAAI,MAAM,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE;AAC/C,MAAM,MAAM,CAAC,IAAI,CAAC,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACjD,KAAK;AACL;AACA,IAAI,OAAO,CAAC,YAAY,CAAC;AACzB,GAAG;AACH;AACA,EAAE,IAAIA,OAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAIA,OAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;AACxE,IAAI,MAAM,GAAG,GAAG,EAAE,CAAC;AACnB;AACA,IAAIA,OAAK,CAAC,YAAY,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK;AAClD,MAAM,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;AACpD,KAAK,CAAC,CAAC;AACP;AACA,IAAI,OAAO,GAAG,CAAC;AACf,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC;AACd;;AClFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE;AACpD,EAAE,IAAIA,OAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE;AAChC,IAAI,IAAI;AACR,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;AACvC,MAAM,OAAOA,OAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAClC,KAAK,CAAC,OAAO,CAAC,EAAE;AAChB,MAAM,IAAI,CAAC,CAAC,IAAI,KAAK,aAAa,EAAE;AACpC,QAAQ,MAAM,CAAC,CAAC;AAChB,OAAO;AACP,KAAK;AACL,GAAG;AACH;AACA,EAAE,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;AAC/C,CAAC;AACD;AACA,MAAM,QAAQ,GAAG;AACjB;AACA,EAAE,YAAY,EAAE,oBAAoB;AACpC;AACA,EAAE,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC;AACnC;AACA,EAAE,gBAAgB,EAAE,CAAC,SAAS,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE;AAC9D,IAAI,MAAM,WAAW,GAAG,OAAO,CAAC,cAAc,EAAE,IAAI,EAAE,CAAC;AACvD,IAAI,MAAM,kBAAkB,GAAG,WAAW,CAAC,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC;AAC5E,IAAI,MAAM,eAAe,GAAGA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AACjD;AACA,IAAI,IAAI,eAAe,IAAIA,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;AACnD,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC;AAChC,KAAK;AACL;AACA,IAAI,MAAM,UAAU,GAAGA,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAC9C;AACA,IAAI,IAAI,UAAU,EAAE;AACpB,MAAM,OAAO,kBAAkB,GAAG,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC;AAC9E,KAAK;AACL;AACA,IAAI,IAAIA,OAAK,CAAC,aAAa,CAAC,IAAI,CAAC;AACjC,MAAMA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;AAC1B,MAAMA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;AAC1B,MAAMA,OAAK,CAAC,MAAM,CAAC,IAAI,CAAC;AACxB,MAAMA,OAAK,CAAC,MAAM,CAAC,IAAI,CAAC;AACxB,MAAMA,OAAK,CAAC,gBAAgB,CAAC,IAAI,CAAC;AAClC,MAAM;AACN,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL,IAAI,IAAIA,OAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE;AACvC,MAAM,OAAO,IAAI,CAAC,MAAM,CAAC;AACzB,KAAK;AACL,IAAI,IAAIA,OAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE;AACvC,MAAM,OAAO,CAAC,cAAc,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;AACvF,MAAM,OAAO,IAAI,CAAC,QAAQ,EAAE,CAAC;AAC7B,KAAK;AACL;AACA,IAAI,IAAI,UAAU,CAAC;AACnB;AACA,IAAI,IAAI,eAAe,EAAE;AACzB,MAAM,IAAI,WAAW,CAAC,OAAO,CAAC,mCAAmC,CAAC,GAAG,CAAC,CAAC,EAAE;AACzE,QAAQ,OAAO,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC,QAAQ,EAAE,CAAC;AACtE,OAAO;AACP;AACA,MAAM,IAAI,CAAC,UAAU,GAAGA,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,WAAW,CAAC,OAAO,CAAC,qBAAqB,CAAC,GAAG,CAAC,CAAC,EAAE;AACpG,QAAQ,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC;AACxD;AACA,QAAQ,OAAO,UAAU;AACzB,UAAU,UAAU,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,GAAG,IAAI;AAC/C,UAAU,SAAS,IAAI,IAAI,SAAS,EAAE;AACtC,UAAU,IAAI,CAAC,cAAc;AAC7B,SAAS,CAAC;AACV,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAI,eAAe,IAAI,kBAAkB,GAAG;AAChD,MAAM,OAAO,CAAC,cAAc,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;AACxD,MAAM,OAAO,eAAe,CAAC,IAAI,CAAC,CAAC;AACnC,KAAK;AACL;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG,CAAC;AACJ;AACA,EAAE,iBAAiB,EAAE,CAAC,SAAS,iBAAiB,CAAC,IAAI,EAAE;AACvD,IAAI,MAAM,YAAY,GAAG,IAAI,CAAC,YAAY,IAAI,QAAQ,CAAC,YAAY,CAAC;AACpE,IAAI,MAAM,iBAAiB,GAAG,YAAY,IAAI,YAAY,CAAC,iBAAiB,CAAC;AAC7E,IAAI,MAAM,aAAa,GAAG,IAAI,CAAC,YAAY,KAAK,MAAM,CAAC;AACvD;AACA,IAAI,IAAIA,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,IAAIA,OAAK,CAAC,gBAAgB,CAAC,IAAI,CAAC,EAAE;AAChE,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL;AACA,IAAI,IAAI,IAAI,IAAIA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,iBAAiB,IAAI,CAAC,IAAI,CAAC,YAAY,KAAK,aAAa,CAAC,EAAE;AACtG,MAAM,MAAM,iBAAiB,GAAG,YAAY,IAAI,YAAY,CAAC,iBAAiB,CAAC;AAC/E,MAAM,MAAM,iBAAiB,GAAG,CAAC,iBAAiB,IAAI,aAAa,CAAC;AACpE;AACA,MAAM,IAAI;AACV,QAAQ,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAChC,OAAO,CAAC,OAAO,CAAC,EAAE;AAClB,QAAQ,IAAI,iBAAiB,EAAE;AAC/B,UAAU,IAAI,CAAC,CAAC,IAAI,KAAK,aAAa,EAAE;AACxC,YAAY,MAAM,UAAU,CAAC,IAAI,CAAC,CAAC,EAAE,UAAU,CAAC,gBAAgB,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC7F,WAAW;AACX,UAAU,MAAM,CAAC,CAAC;AAClB,SAAS;AACT,OAAO;AACP,KAAK;AACL;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG,CAAC;AACJ;AACA;AACA;AACA;AACA;AACA,EAAE,OAAO,EAAE,CAAC;AACZ;AACA,EAAE,cAAc,EAAE,YAAY;AAC9B,EAAE,cAAc,EAAE,cAAc;AAChC;AACA,EAAE,gBAAgB,EAAE,CAAC,CAAC;AACtB,EAAE,aAAa,EAAE,CAAC,CAAC;AACnB;AACA,EAAE,GAAG,EAAE;AACP,IAAI,QAAQ,EAAE,QAAQ,CAAC,OAAO,CAAC,QAAQ;AACvC,IAAI,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,IAAI;AAC/B,GAAG;AACH;AACA,EAAE,cAAc,EAAE,SAAS,cAAc,CAAC,MAAM,EAAE;AAClD,IAAI,OAAO,MAAM,IAAI,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC;AACzC,GAAG;AACH;AACA,EAAE,OAAO,EAAE;AACX,IAAI,MAAM,EAAE;AACZ,MAAM,QAAQ,EAAE,mCAAmC;AACnD,MAAM,cAAc,EAAE,SAAS;AAC/B,KAAK;AACL,GAAG;AACH,CAAC,CAAC;AACF;AACAA,OAAK,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC,MAAM,KAAK;AAC7E,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;AAChC,CAAC,CAAC,CAAC;AACH;AACA,iBAAe,QAAQ;;AC5JvB;AACA;AACA,MAAM,iBAAiB,GAAGA,OAAK,CAAC,WAAW,CAAC;AAC5C,EAAE,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM;AAClE,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,EAAE,qBAAqB;AACvE,EAAE,eAAe,EAAE,UAAU,EAAE,cAAc,EAAE,qBAAqB;AACpE,EAAE,SAAS,EAAE,aAAa,EAAE,YAAY;AACxC,CAAC,CAAC,CAAC;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAe,UAAU,IAAI;AAC7B,EAAE,MAAM,MAAM,GAAG,EAAE,CAAC;AACpB,EAAE,IAAI,GAAG,CAAC;AACV,EAAE,IAAI,GAAG,CAAC;AACV,EAAE,IAAI,CAAC,CAAC;AACR;AACA,EAAE,UAAU,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,SAAS,MAAM,CAAC,IAAI,EAAE;AACrE,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AAC1B,IAAI,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AACpD,IAAI,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;AACvC;AACA,IAAI,IAAI,CAAC,GAAG,KAAK,MAAM,CAAC,GAAG,CAAC,IAAI,iBAAiB,CAAC,GAAG,CAAC,CAAC,EAAE;AACzD,MAAM,OAAO;AACb,KAAK;AACL;AACA,IAAI,IAAI,GAAG,KAAK,YAAY,EAAE;AAC9B,MAAM,IAAI,MAAM,CAAC,GAAG,CAAC,EAAE;AACvB,QAAQ,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC9B,OAAO,MAAM;AACb,QAAQ,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAC5B,OAAO;AACP,KAAK,MAAM;AACX,MAAM,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,GAAG,GAAG,GAAG,CAAC;AACjE,KAAK;AACL,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO,MAAM,CAAC;AAChB,CAAC;;ACjDD,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC;AACA,SAAS,eAAe,CAAC,MAAM,EAAE;AACjC,EAAE,OAAO,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AACvD,CAAC;AACD;AACA,SAAS,cAAc,CAAC,KAAK,EAAE;AAC/B,EAAE,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,IAAI,IAAI,EAAE;AACxC,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA,EAAE,OAAOA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;AAC1E,CAAC;AACD;AACA,SAAS,WAAW,CAAC,GAAG,EAAE;AAC1B,EAAE,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AACrC,EAAE,MAAM,QAAQ,GAAG,kCAAkC,CAAC;AACtD,EAAE,IAAI,KAAK,CAAC;AACZ;AACA,EAAE,QAAQ,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG;AACvC,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAChC,GAAG;AACH;AACA,EAAE,OAAO,MAAM,CAAC;AAChB,CAAC;AACD;AACA,MAAM,iBAAiB,GAAG,CAAC,GAAG,KAAK,gCAAgC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;AACrF;AACA,SAAS,gBAAgB,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,kBAAkB,EAAE;AAC9E,EAAE,IAAIA,OAAK,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE;AAChC,IAAI,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAC5C,GAAG;AACH;AACA,EAAE,IAAI,kBAAkB,EAAE;AAC1B,IAAI,KAAK,GAAG,MAAM,CAAC;AACnB,GAAG;AACH;AACA,EAAE,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO;AACrC;AACA,EAAE,IAAIA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;AAC9B,IAAI,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AACxC,GAAG;AACH;AACA,EAAE,IAAIA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;AAC9B,IAAI,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC9B,GAAG;AACH,CAAC;AACD;AACA,SAAS,YAAY,CAAC,MAAM,EAAE;AAC9B,EAAE,OAAO,MAAM,CAAC,IAAI,EAAE;AACtB,KAAK,WAAW,EAAE,CAAC,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,KAAK;AAChE,MAAM,OAAO,IAAI,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC;AACtC,KAAK,CAAC,CAAC;AACP,CAAC;AACD;AACA,SAAS,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE;AACrC,EAAE,MAAM,YAAY,GAAGA,OAAK,CAAC,WAAW,CAAC,GAAG,GAAG,MAAM,CAAC,CAAC;AACvD;AACA,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,UAAU,IAAI;AAC9C,IAAI,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,UAAU,GAAG,YAAY,EAAE;AAC1D,MAAM,KAAK,EAAE,SAAS,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE;AACxC,QAAQ,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AACrE,OAAO;AACP,MAAM,YAAY,EAAE,IAAI;AACxB,KAAK,CAAC,CAAC;AACP,GAAG,CAAC,CAAC;AACL,CAAC;AACD;AACA,MAAM,YAAY,CAAC;AACnB,EAAE,WAAW,CAAC,OAAO,EAAE;AACvB,IAAI,OAAO,IAAI,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AACjC,GAAG;AACH;AACA,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE;AACvC,IAAI,MAAM,IAAI,GAAG,IAAI,CAAC;AACtB;AACA,IAAI,SAAS,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE;AAClD,MAAM,MAAM,OAAO,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;AAC/C;AACA,MAAM,IAAI,CAAC,OAAO,EAAE;AACpB,QAAQ,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAClE,OAAO;AACP;AACA,MAAM,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AAC/C;AACA,MAAM,GAAG,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,SAAS,IAAI,QAAQ,KAAK,IAAI,KAAK,QAAQ,KAAK,SAAS,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,EAAE;AAClH,QAAQ,IAAI,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;AACtD,OAAO;AACP,KAAK;AACL;AACA,IAAI,MAAM,UAAU,GAAG,CAAC,OAAO,EAAE,QAAQ;AACzC,MAAMA,OAAK,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC;AACxF;AACA,IAAI,IAAIA,OAAK,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,MAAM,YAAY,IAAI,CAAC,WAAW,EAAE;AAC3E,MAAM,UAAU,CAAC,MAAM,EAAE,cAAc,EAAC;AACxC,KAAK,MAAM,GAAGA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,MAAM,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,EAAE;AAChG,MAAM,UAAU,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE,cAAc,CAAC,CAAC;AACvD,KAAK,MAAM,IAAIA,OAAK,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE;AACxC,MAAM,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,EAAE,EAAE;AACnD,QAAQ,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;AACvC,OAAO;AACP,KAAK,MAAM;AACX,MAAM,MAAM,IAAI,IAAI,IAAI,SAAS,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACnE,KAAK;AACL;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG;AACH;AACA,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE;AACtB,IAAI,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC;AACrC;AACA,IAAI,IAAI,MAAM,EAAE;AAChB,MAAM,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC9C;AACA,MAAM,IAAI,GAAG,EAAE;AACf,QAAQ,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;AAChC;AACA,QAAQ,IAAI,CAAC,MAAM,EAAE;AACrB,UAAU,OAAO,KAAK,CAAC;AACvB,SAAS;AACT;AACA,QAAQ,IAAI,MAAM,KAAK,IAAI,EAAE;AAC7B,UAAU,OAAO,WAAW,CAAC,KAAK,CAAC,CAAC;AACpC,SAAS;AACT;AACA,QAAQ,IAAIA,OAAK,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE;AACtC,UAAU,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;AAC/C,SAAS;AACT;AACA,QAAQ,IAAIA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;AACpC,UAAU,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACpC,SAAS;AACT;AACA,QAAQ,MAAM,IAAI,SAAS,CAAC,wCAAwC,CAAC,CAAC;AACtE,OAAO;AACP,KAAK;AACL,GAAG;AACH;AACA,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE;AACvB,IAAI,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC;AACrC;AACA,IAAI,IAAI,MAAM,EAAE;AAChB,MAAM,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC9C;AACA,MAAM,OAAO,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,SAAS,KAAK,CAAC,OAAO,IAAI,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;AACjH,KAAK;AACL;AACA,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE;AAC1B,IAAI,MAAM,IAAI,GAAG,IAAI,CAAC;AACtB,IAAI,IAAI,OAAO,GAAG,KAAK,CAAC;AACxB;AACA,IAAI,SAAS,YAAY,CAAC,OAAO,EAAE;AACnC,MAAM,OAAO,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;AACzC;AACA,MAAM,IAAI,OAAO,EAAE;AACnB,QAAQ,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AACjD;AACA,QAAQ,IAAI,GAAG,KAAK,CAAC,OAAO,IAAI,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,EAAE;AAClF,UAAU,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AAC3B;AACA,UAAU,OAAO,GAAG,IAAI,CAAC;AACzB,SAAS;AACT,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;AAC/B,MAAM,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;AACnC,KAAK,MAAM;AACX,MAAM,YAAY,CAAC,MAAM,CAAC,CAAC;AAC3B,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC;AACnB,GAAG;AACH;AACA,EAAE,KAAK,CAAC,OAAO,EAAE;AACjB,IAAI,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACnC,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;AACxB,IAAI,IAAI,OAAO,GAAG,KAAK,CAAC;AACxB;AACA,IAAI,OAAO,CAAC,EAAE,EAAE;AAChB,MAAM,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AAC1B,MAAM,GAAG,CAAC,OAAO,IAAI,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE;AAC5E,QAAQ,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AACzB,QAAQ,OAAO,GAAG,IAAI,CAAC;AACvB,OAAO;AACP,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC;AACnB,GAAG;AACH;AACA,EAAE,SAAS,CAAC,MAAM,EAAE;AACpB,IAAI,MAAM,IAAI,GAAG,IAAI,CAAC;AACtB,IAAI,MAAM,OAAO,GAAG,EAAE,CAAC;AACvB;AACA,IAAIA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK;AAC3C,MAAM,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AACjD;AACA,MAAM,IAAI,GAAG,EAAE;AACf,QAAQ,IAAI,CAAC,GAAG,CAAC,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;AAC1C,QAAQ,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,YAAY,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;AAC/E;AACA,MAAM,IAAI,UAAU,KAAK,MAAM,EAAE;AACjC,QAAQ,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,OAAO;AACP;AACA,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;AAC/C;AACA,MAAM,OAAO,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC;AACjC,KAAK,CAAC,CAAC;AACP;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG;AACH;AACA,EAAE,MAAM,CAAC,GAAG,OAAO,EAAE;AACrB,IAAI,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,OAAO,CAAC,CAAC;AACrD,GAAG;AACH;AACA,EAAE,MAAM,CAAC,SAAS,EAAE;AACpB,IAAI,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AACpC;AACA,IAAIA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK;AAC3C,MAAM,KAAK,IAAI,IAAI,IAAI,KAAK,KAAK,KAAK,KAAK,GAAG,CAAC,MAAM,CAAC,GAAG,SAAS,IAAIA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC;AACvH,KAAK,CAAC,CAAC;AACP;AACA,IAAI,OAAO,GAAG,CAAC;AACf,GAAG;AACH;AACA,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG;AACtB,IAAI,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;AAC5D,GAAG;AACH;AACA,EAAE,QAAQ,GAAG;AACb,IAAI,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,KAAK,CAAC,KAAK,MAAM,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACpG,GAAG;AACH;AACA,EAAE,KAAK,MAAM,CAAC,WAAW,CAAC,GAAG;AAC7B,IAAI,OAAO,cAAc,CAAC;AAC1B,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC,KAAK,EAAE;AACrB,IAAI,OAAO,KAAK,YAAY,IAAI,GAAG,KAAK,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;AAC3D,GAAG;AACH;AACA,EAAE,OAAO,MAAM,CAAC,KAAK,EAAE,GAAG,OAAO,EAAE;AACnC,IAAI,MAAM,QAAQ,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;AACrC;AACA,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;AACtD;AACA,IAAI,OAAO,QAAQ,CAAC;AACpB,GAAG;AACH;AACA,EAAE,OAAO,QAAQ,CAAC,MAAM,EAAE;AAC1B,IAAI,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG;AAC7D,MAAM,SAAS,EAAE,EAAE;AACnB,KAAK,CAAC,CAAC;AACP;AACA,IAAI,MAAM,SAAS,GAAG,SAAS,CAAC,SAAS,CAAC;AAC1C,IAAI,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;AACrC;AACA,IAAI,SAAS,cAAc,CAAC,OAAO,EAAE;AACrC,MAAM,MAAM,OAAO,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;AAC/C;AACA,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE;AAC/B,QAAQ,cAAc,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;AAC3C,QAAQ,SAAS,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;AAClC,OAAO;AACP,KAAK;AACL;AACA,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;AACpF;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG;AACH,CAAC;AACD;AACA,YAAY,CAAC,QAAQ,CAAC,CAAC,cAAc,EAAE,gBAAgB,EAAE,QAAQ,EAAE,iBAAiB,EAAE,YAAY,EAAE,eAAe,CAAC,CAAC,CAAC;AACtH;AACA;AACAA,OAAK,CAAC,iBAAiB,CAAC,YAAY,CAAC,SAAS,EAAE,CAAC,CAAC,KAAK,CAAC,EAAE,GAAG,KAAK;AAClE,EAAE,IAAI,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnD,EAAE,OAAO;AACT,IAAI,GAAG,EAAE,MAAM,KAAK;AACpB,IAAI,GAAG,CAAC,WAAW,EAAE;AACrB,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,WAAW,CAAC;AACjC,KAAK;AACL,GAAG;AACH,CAAC,CAAC,CAAC;AACH;AACAA,OAAK,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC;AAClC;AACA,qBAAe,YAAY;;ACvS3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,aAAa,CAAC,GAAG,EAAE,QAAQ,EAAE;AACrD,EAAE,MAAM,MAAM,GAAG,IAAI,IAAIO,UAAQ,CAAC;AAClC,EAAE,MAAM,OAAO,GAAG,QAAQ,IAAI,MAAM,CAAC;AACrC,EAAE,MAAM,OAAO,GAAGC,cAAY,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AACrD,EAAE,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;AAC1B;AACA,EAAER,OAAK,CAAC,OAAO,CAAC,GAAG,EAAE,SAAS,SAAS,CAAC,EAAE,EAAE;AAC5C,IAAI,IAAI,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,SAAS,EAAE,EAAE,QAAQ,GAAG,QAAQ,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;AAC9F,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC;AACtB;AACA,EAAE,OAAO,IAAI,CAAC;AACd;;ACzBe,SAAS,QAAQ,CAAC,KAAK,EAAE;AACxC,EAAE,OAAO,CAAC,EAAE,KAAK,IAAI,KAAK,CAAC,UAAU,CAAC,CAAC;AACvC;;ACCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE;AACjD;AACA,EAAE,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,IAAI,IAAI,GAAG,UAAU,GAAG,OAAO,EAAE,UAAU,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AAC1G,EAAE,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;AAC9B,CAAC;AACD;AACAA,OAAK,CAAC,QAAQ,CAAC,aAAa,EAAE,UAAU,EAAE;AAC1C,EAAE,UAAU,EAAE,IAAI;AAClB,CAAC,CAAC;;AClBF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE;AAC1D,EAAE,MAAM,cAAc,GAAG,QAAQ,CAAC,MAAM,CAAC,cAAc,CAAC;AACxD,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,IAAI,CAAC,cAAc,IAAI,cAAc,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;AAC9E,IAAI,OAAO,CAAC,QAAQ,CAAC,CAAC;AACtB,GAAG,MAAM;AACT,IAAI,MAAM,CAAC,IAAI,UAAU;AACzB,MAAM,kCAAkC,GAAG,QAAQ,CAAC,MAAM;AAC1D,MAAM,CAAC,UAAU,CAAC,eAAe,EAAE,UAAU,CAAC,gBAAgB,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;AACtG,MAAM,QAAQ,CAAC,MAAM;AACrB,MAAM,QAAQ,CAAC,OAAO;AACtB,MAAM,QAAQ;AACd,KAAK,CAAC,CAAC;AACP,GAAG;AACH;;ACxBe,SAAS,aAAa,CAAC,GAAG,EAAE;AAC3C,EAAE,MAAM,KAAK,GAAG,2BAA2B,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACtD,EAAE,OAAO,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;AACjC;;ACHA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,WAAW,CAAC,YAAY,EAAE,GAAG,EAAE;AACxC,EAAE,YAAY,GAAG,YAAY,IAAI,EAAE,CAAC;AACpC,EAAE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;AACxC,EAAE,MAAM,UAAU,GAAG,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;AAC7C,EAAE,IAAI,IAAI,GAAG,CAAC,CAAC;AACf,EAAE,IAAI,IAAI,GAAG,CAAC,CAAC;AACf,EAAE,IAAI,aAAa,CAAC;AACpB;AACA,EAAE,GAAG,GAAG,GAAG,KAAK,SAAS,GAAG,GAAG,GAAG,IAAI,CAAC;AACvC;AACA,EAAE,OAAO,SAAS,IAAI,CAAC,WAAW,EAAE;AACpC,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;AAC3B;AACA,IAAI,MAAM,SAAS,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC;AACvC;AACA,IAAI,IAAI,CAAC,aAAa,EAAE;AACxB,MAAM,aAAa,GAAG,GAAG,CAAC;AAC1B,KAAK;AACL;AACA,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC;AAC9B,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC;AAC3B;AACA,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC;AACjB,IAAI,IAAI,UAAU,GAAG,CAAC,CAAC;AACvB;AACA,IAAI,OAAO,CAAC,KAAK,IAAI,EAAE;AACvB,MAAM,UAAU,IAAI,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;AAC/B,MAAM,CAAC,GAAG,CAAC,GAAG,YAAY,CAAC;AAC3B,KAAK;AACL;AACA,IAAI,IAAI,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,YAAY,CAAC;AACrC;AACA,IAAI,IAAI,IAAI,KAAK,IAAI,EAAE;AACvB,MAAM,IAAI,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,YAAY,CAAC;AACvC,KAAK;AACL;AACA,IAAI,IAAI,GAAG,GAAG,aAAa,GAAG,GAAG,EAAE;AACnC,MAAM,OAAO;AACb,KAAK;AACL;AACA,IAAI,MAAM,MAAM,GAAG,SAAS,IAAI,GAAG,GAAG,SAAS,CAAC;AAChD;AACA,IAAI,OAAO,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,GAAG,IAAI,GAAG,MAAM,CAAC,GAAG,SAAS,CAAC;AACvE,GAAG,CAAC;AACJ;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,QAAQ,CAAC,EAAE,EAAE,IAAI,EAAE;AAC5B,EAAE,IAAI,SAAS,GAAG,CAAC,CAAC;AACpB,EAAE,IAAI,SAAS,GAAG,IAAI,GAAG,IAAI,CAAC;AAC9B,EAAE,IAAI,QAAQ,CAAC;AACf,EAAE,IAAI,KAAK,CAAC;AACZ;AACA,EAAE,MAAM,MAAM,GAAG,CAAC,IAAI,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,KAAK;AAC7C,IAAI,SAAS,GAAG,GAAG,CAAC;AACpB,IAAI,QAAQ,GAAG,IAAI,CAAC;AACpB,IAAI,IAAI,KAAK,EAAE;AACf,MAAM,YAAY,CAAC,KAAK,CAAC,CAAC;AAC1B,MAAM,KAAK,GAAG,IAAI,CAAC;AACnB,KAAK;AACL,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AACzB,IAAG;AACH;AACA,EAAE,MAAM,SAAS,GAAG,CAAC,GAAG,IAAI,KAAK;AACjC,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;AAC3B,IAAI,MAAM,MAAM,GAAG,GAAG,GAAG,SAAS,CAAC;AACnC,IAAI,KAAK,MAAM,IAAI,SAAS,EAAE;AAC9B,MAAM,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AACxB,KAAK,MAAM;AACX,MAAM,QAAQ,GAAG,IAAI,CAAC;AACtB,MAAM,IAAI,CAAC,KAAK,EAAE;AAClB,QAAQ,KAAK,GAAG,UAAU,CAAC,MAAM;AACjC,UAAU,KAAK,GAAG,IAAI,CAAC;AACvB,UAAU,MAAM,CAAC,QAAQ,EAAC;AAC1B,SAAS,EAAE,SAAS,GAAG,MAAM,CAAC,CAAC;AAC/B,OAAO;AACP,KAAK;AACL,IAAG;AACH;AACA,EAAE,MAAM,KAAK,GAAG,MAAM,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC;AACnD;AACA,EAAE,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC5B;;ACrCO,MAAM,oBAAoB,GAAG,CAAC,QAAQ,EAAE,gBAAgB,EAAE,IAAI,GAAG,CAAC,KAAK;AAC9E,EAAE,IAAI,aAAa,GAAG,CAAC,CAAC;AACxB,EAAE,MAAM,YAAY,GAAG,WAAW,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;AAC5C;AACA,EAAE,OAAO,QAAQ,CAAC,CAAC,IAAI;AACvB,IAAI,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC;AAC5B,IAAI,MAAM,KAAK,GAAG,CAAC,CAAC,gBAAgB,GAAG,CAAC,CAAC,KAAK,GAAG,SAAS,CAAC;AAC3D,IAAI,MAAM,aAAa,GAAG,MAAM,GAAG,aAAa,CAAC;AACjD,IAAI,MAAM,IAAI,GAAG,YAAY,CAAC,aAAa,CAAC,CAAC;AAC7C,IAAI,MAAM,OAAO,GAAG,MAAM,IAAI,KAAK,CAAC;AACpC;AACA,IAAI,aAAa,GAAG,MAAM,CAAC;AAC3B;AACA,IAAI,MAAM,IAAI,GAAG;AACjB,MAAM,MAAM;AACZ,MAAM,KAAK;AACX,MAAM,QAAQ,EAAE,KAAK,IAAI,MAAM,GAAG,KAAK,IAAI,SAAS;AACpD,MAAM,KAAK,EAAE,aAAa;AAC1B,MAAM,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,SAAS;AACnC,MAAM,SAAS,EAAE,IAAI,IAAI,KAAK,IAAI,OAAO,GAAG,CAAC,KAAK,GAAG,MAAM,IAAI,IAAI,GAAG,SAAS;AAC/E,MAAM,KAAK,EAAE,CAAC;AACd,MAAM,gBAAgB,EAAE,KAAK,IAAI,IAAI;AACrC,MAAM,CAAC,gBAAgB,GAAG,UAAU,GAAG,QAAQ,GAAG,IAAI;AACtD,KAAK,CAAC;AACN;AACA,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC;AACnB,GAAG,EAAE,IAAI,CAAC,CAAC;AACX,EAAC;AACD;AACO,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK;AAC5D,EAAE,MAAM,gBAAgB,GAAG,KAAK,IAAI,IAAI,CAAC;AACzC;AACA,EAAE,OAAO,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC;AACnC,IAAI,gBAAgB;AACpB,IAAI,KAAK;AACT,IAAI,MAAM;AACV,GAAG,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;AACpB,EAAC;AACD;AACO,MAAM,cAAc,GAAG,CAAC,EAAE,KAAK,CAAC,GAAG,IAAI,KAAKA,OAAK,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;;ACzChF,sBAAe,QAAQ,CAAC,qBAAqB,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,KAAK,CAAC,GAAG,KAAK;AAC9E,EAAE,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;AACtC;AACA,EAAE;AACF,IAAI,MAAM,CAAC,QAAQ,KAAK,GAAG,CAAC,QAAQ;AACpC,IAAI,MAAM,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI;AAC5B,KAAK,MAAM,IAAI,MAAM,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,CAAC;AACxC,IAAI;AACJ,CAAC;AACD,EAAE,IAAI,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC1B,EAAE,QAAQ,CAAC,SAAS,IAAI,iBAAiB,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,SAAS,CAAC;AAC5E,CAAC,GAAG,MAAM,IAAI;;ACVd,cAAe,QAAQ,CAAC,qBAAqB;AAC7C;AACA;AACA,EAAE;AACF,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE;AACtD,MAAM,MAAM,MAAM,GAAG,CAAC,IAAI,GAAG,GAAG,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC;AAC9D;AACA,MAAMA,OAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,GAAG,IAAI,IAAI,CAAC,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AAC3F;AACA,MAAMA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;AAC1D;AACA,MAAMA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,CAAC;AAChE;AACA,MAAM,MAAM,KAAK,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC/C;AACA,MAAM,QAAQ,CAAC,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1C,KAAK;AACL;AACA,IAAI,IAAI,CAAC,IAAI,EAAE;AACf,MAAM,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,YAAY,GAAG,IAAI,GAAG,WAAW,CAAC,CAAC,CAAC;AACzF,MAAM,QAAQ,KAAK,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,EAAE;AAC3D,KAAK;AACL;AACA,IAAI,MAAM,CAAC,IAAI,EAAE;AACjB,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,QAAQ,CAAC,CAAC;AAClD,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA,EAAE;AACF,IAAI,KAAK,GAAG,EAAE;AACd,IAAI,IAAI,GAAG;AACX,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL,IAAI,MAAM,GAAG,EAAE;AACf,GAAG;;ACtCH;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,aAAa,CAAC,GAAG,EAAE;AAC3C;AACA;AACA;AACA,EAAE,OAAO,6BAA6B,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjD;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,WAAW,CAAC,OAAO,EAAE,WAAW,EAAE;AAC1D,EAAE,OAAO,WAAW;AACpB,MAAM,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,GAAG,GAAG,GAAG,WAAW,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;AAC3E,MAAM,OAAO,CAAC;AACd;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE;AAC7D,EAAE,IAAI,OAAO,IAAI,CAAC,aAAa,CAAC,YAAY,CAAC,EAAE;AAC/C,IAAI,OAAO,WAAW,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;AAC9C,GAAG;AACH,EAAE,OAAO,YAAY,CAAC;AACtB;;ACfA,MAAM,eAAe,GAAG,CAAC,KAAK,KAAK,KAAK,YAAYQ,cAAY,GAAG,EAAE,GAAG,KAAK,EAAE,GAAG,KAAK,CAAC;AACxF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE;AACtD;AACA,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;AAC1B,EAAE,MAAM,MAAM,GAAG,EAAE,CAAC;AACpB;AACA,EAAE,SAAS,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE;AAC1D,IAAI,IAAIR,OAAK,CAAC,aAAa,CAAC,MAAM,CAAC,IAAIA,OAAK,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE;AACpE,MAAM,OAAOA,OAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC1D,KAAK,MAAM,IAAIA,OAAK,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE;AAC5C,MAAM,OAAOA,OAAK,CAAC,KAAK,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;AACrC,KAAK,MAAM,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;AACtC,MAAM,OAAO,MAAM,CAAC,KAAK,EAAE,CAAC;AAC5B,KAAK;AACL,IAAI,OAAO,MAAM,CAAC;AAClB,GAAG;AACH;AACA;AACA,EAAE,SAAS,mBAAmB,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,QAAQ,EAAE;AACtD,IAAI,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AAC/B,MAAM,OAAO,cAAc,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,QAAQ,CAAC,CAAC;AACnD,KAAK,MAAM,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AACtC,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,EAAE,IAAI,GAAG,QAAQ,CAAC,CAAC;AAC3D,KAAK;AACL,GAAG;AACH;AACA;AACA,EAAE,SAAS,gBAAgB,CAAC,CAAC,EAAE,CAAC,EAAE;AAClC,IAAI,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AAC/B,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;AAC1C,KAAK;AACL,GAAG;AACH;AACA;AACA,EAAE,SAAS,gBAAgB,CAAC,CAAC,EAAE,CAAC,EAAE;AAClC,IAAI,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AAC/B,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;AAC1C,KAAK,MAAM,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AACtC,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;AAC1C,KAAK;AACL,GAAG;AACH;AACA;AACA,EAAE,SAAS,eAAe,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE;AACvC,IAAI,IAAI,IAAI,IAAI,OAAO,EAAE;AACzB,MAAM,OAAO,cAAc,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAClC,KAAK,MAAM,IAAI,IAAI,IAAI,OAAO,EAAE;AAChC,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;AAC1C,KAAK;AACL,GAAG;AACH;AACA,EAAE,MAAM,QAAQ,GAAG;AACnB,IAAI,GAAG,EAAE,gBAAgB;AACzB,IAAI,MAAM,EAAE,gBAAgB;AAC5B,IAAI,IAAI,EAAE,gBAAgB;AAC1B,IAAI,OAAO,EAAE,gBAAgB;AAC7B,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,iBAAiB,EAAE,gBAAgB;AACvC,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,OAAO,EAAE,gBAAgB;AAC7B,IAAI,cAAc,EAAE,gBAAgB;AACpC,IAAI,eAAe,EAAE,gBAAgB;AACrC,IAAI,aAAa,EAAE,gBAAgB;AACnC,IAAI,OAAO,EAAE,gBAAgB;AAC7B,IAAI,YAAY,EAAE,gBAAgB;AAClC,IAAI,cAAc,EAAE,gBAAgB;AACpC,IAAI,cAAc,EAAE,gBAAgB;AACpC,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,kBAAkB,EAAE,gBAAgB;AACxC,IAAI,UAAU,EAAE,gBAAgB;AAChC,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,aAAa,EAAE,gBAAgB;AACnC,IAAI,cAAc,EAAE,gBAAgB;AACpC,IAAI,SAAS,EAAE,gBAAgB;AAC/B,IAAI,SAAS,EAAE,gBAAgB;AAC/B,IAAI,UAAU,EAAE,gBAAgB;AAChC,IAAI,WAAW,EAAE,gBAAgB;AACjC,IAAI,UAAU,EAAE,gBAAgB;AAChC,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,cAAc,EAAE,eAAe;AACnC,IAAI,OAAO,EAAE,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,KAAK,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC;AACpG,GAAG,CAAC;AACJ;AACA,EAAEA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,EAAE,SAAS,kBAAkB,CAAC,IAAI,EAAE;AACpG,IAAI,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,IAAI,mBAAmB,CAAC;AACxD,IAAI,MAAM,WAAW,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;AAClE,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,WAAW,CAAC,IAAI,KAAK,KAAK,eAAe,MAAM,MAAM,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,CAAC;AAClG,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO,MAAM,CAAC;AAChB;;AChGA,oBAAe,CAAC,MAAM,KAAK;AAC3B,EAAE,MAAM,SAAS,GAAG,WAAW,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;AAC5C;AACA,EAAE,IAAI,CAAC,IAAI,EAAE,aAAa,EAAE,cAAc,EAAE,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC,GAAG,SAAS,CAAC;AACvF;AACA,EAAE,SAAS,CAAC,OAAO,GAAG,OAAO,GAAGQ,cAAY,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAC3D;AACA,EAAE,SAAS,CAAC,GAAG,GAAG,QAAQ,CAAC,aAAa,CAAC,SAAS,CAAC,OAAO,EAAE,SAAS,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,gBAAgB,CAAC,CAAC;AACpH;AACA;AACA,EAAE,IAAI,IAAI,EAAE;AACZ,IAAI,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,QAAQ;AACzC,MAAM,IAAI,CAAC,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC,kBAAkB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;AAC5G,KAAK,CAAC;AACN,GAAG;AACH;AACA,EAAE,IAAI,WAAW,CAAC;AAClB;AACA,EAAE,IAAIR,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;AAC9B,IAAI,IAAI,QAAQ,CAAC,qBAAqB,IAAI,QAAQ,CAAC,8BAA8B,EAAE;AACnF,MAAM,OAAO,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC;AACxC,KAAK,MAAM,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,cAAc,EAAE,MAAM,KAAK,EAAE;AACnE;AACA,MAAM,MAAM,CAAC,IAAI,EAAE,GAAG,MAAM,CAAC,GAAG,WAAW,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;AACrH,MAAM,OAAO,CAAC,cAAc,CAAC,CAAC,IAAI,IAAI,qBAAqB,EAAE,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AACpF,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,EAAE,IAAI,QAAQ,CAAC,qBAAqB,EAAE;AACtC,IAAI,aAAa,IAAIA,OAAK,CAAC,UAAU,CAAC,aAAa,CAAC,KAAK,aAAa,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC,CAAC;AACnG;AACA,IAAI,IAAI,aAAa,KAAK,aAAa,KAAK,KAAK,IAAI,eAAe,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,EAAE;AACtF;AACA,MAAM,MAAM,SAAS,GAAG,cAAc,IAAI,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;AACzF;AACA,MAAM,IAAI,SAAS,EAAE;AACrB,QAAQ,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,SAAS,CAAC,CAAC;AAC/C,OAAO;AACP,KAAK;AACL,GAAG;AACH;AACA,EAAE,OAAO,SAAS,CAAC;AACnB;;AC5CA,MAAM,qBAAqB,GAAG,OAAO,cAAc,KAAK,WAAW,CAAC;AACpE;AACA,iBAAe,qBAAqB,IAAI,UAAU,MAAM,EAAE;AAC1D,EAAE,OAAO,IAAI,OAAO,CAAC,SAAS,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE;AAClE,IAAI,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;AAC1C,IAAI,IAAI,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;AACnC,IAAI,MAAM,cAAc,GAAGQ,cAAY,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC;AAC1E,IAAI,IAAI,CAAC,YAAY,EAAE,gBAAgB,EAAE,kBAAkB,CAAC,GAAG,OAAO,CAAC;AACvE,IAAI,IAAI,UAAU,CAAC;AACnB,IAAI,IAAI,eAAe,EAAE,iBAAiB,CAAC;AAC3C,IAAI,IAAI,WAAW,EAAE,aAAa,CAAC;AACnC;AACA,IAAI,SAAS,IAAI,GAAG;AACpB,MAAM,WAAW,IAAI,WAAW,EAAE,CAAC;AACnC,MAAM,aAAa,IAAI,aAAa,EAAE,CAAC;AACvC;AACA,MAAM,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;AACzE;AACA,MAAM,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;AAChF,KAAK;AACL;AACA,IAAI,IAAI,OAAO,GAAG,IAAI,cAAc,EAAE,CAAC;AACvC;AACA,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,WAAW,EAAE,EAAE,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AAClE;AACA;AACA,IAAI,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;AACtC;AACA,IAAI,SAAS,SAAS,GAAG;AACzB,MAAM,IAAI,CAAC,OAAO,EAAE;AACpB,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,MAAM,eAAe,GAAGA,cAAY,CAAC,IAAI;AAC/C,QAAQ,uBAAuB,IAAI,OAAO,IAAI,OAAO,CAAC,qBAAqB,EAAE;AAC7E,OAAO,CAAC;AACR,MAAM,MAAM,YAAY,GAAG,CAAC,YAAY,IAAI,YAAY,KAAK,MAAM,IAAI,YAAY,KAAK,MAAM;AAC9F,QAAQ,OAAO,CAAC,YAAY,GAAG,OAAO,CAAC,QAAQ,CAAC;AAChD,MAAM,MAAM,QAAQ,GAAG;AACvB,QAAQ,IAAI,EAAE,YAAY;AAC1B,QAAQ,MAAM,EAAE,OAAO,CAAC,MAAM;AAC9B,QAAQ,UAAU,EAAE,OAAO,CAAC,UAAU;AACtC,QAAQ,OAAO,EAAE,eAAe;AAChC,QAAQ,MAAM;AACd,QAAQ,OAAO;AACf,OAAO,CAAC;AACR;AACA,MAAM,MAAM,CAAC,SAAS,QAAQ,CAAC,KAAK,EAAE;AACtC,QAAQ,OAAO,CAAC,KAAK,CAAC,CAAC;AACvB,QAAQ,IAAI,EAAE,CAAC;AACf,OAAO,EAAE,SAAS,OAAO,CAAC,GAAG,EAAE;AAC/B,QAAQ,MAAM,CAAC,GAAG,CAAC,CAAC;AACpB,QAAQ,IAAI,EAAE,CAAC;AACf,OAAO,EAAE,QAAQ,CAAC,CAAC;AACnB;AACA;AACA,MAAM,OAAO,GAAG,IAAI,CAAC;AACrB,KAAK;AACL;AACA,IAAI,IAAI,WAAW,IAAI,OAAO,EAAE;AAChC;AACA,MAAM,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC;AACpC,KAAK,MAAM;AACX;AACA,MAAM,OAAO,CAAC,kBAAkB,GAAG,SAAS,UAAU,GAAG;AACzD,QAAQ,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,UAAU,KAAK,CAAC,EAAE;AAClD,UAAU,OAAO;AACjB,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,QAAQ,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE;AAC1G,UAAU,OAAO;AACjB,SAAS;AACT;AACA;AACA,QAAQ,UAAU,CAAC,SAAS,CAAC,CAAC;AAC9B,OAAO,CAAC;AACR,KAAK;AACL;AACA;AACA,IAAI,OAAO,CAAC,OAAO,GAAG,SAAS,WAAW,GAAG;AAC7C,MAAM,IAAI,CAAC,OAAO,EAAE;AACpB,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,MAAM,CAAC,IAAI,UAAU,CAAC,iBAAiB,EAAE,UAAU,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AAC1F;AACA;AACA,MAAM,OAAO,GAAG,IAAI,CAAC;AACrB,KAAK,CAAC;AACN;AACA;AACA,IAAI,OAAO,CAAC,OAAO,GAAG,SAAS,WAAW,GAAG;AAC7C;AACA;AACA,MAAM,MAAM,CAAC,IAAI,UAAU,CAAC,eAAe,EAAE,UAAU,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AACvF;AACA;AACA,MAAM,OAAO,GAAG,IAAI,CAAC;AACrB,KAAK,CAAC;AACN;AACA;AACA,IAAI,OAAO,CAAC,SAAS,GAAG,SAAS,aAAa,GAAG;AACjD,MAAM,IAAI,mBAAmB,GAAG,OAAO,CAAC,OAAO,GAAG,aAAa,GAAG,OAAO,CAAC,OAAO,GAAG,aAAa,GAAG,kBAAkB,CAAC;AACvH,MAAM,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,oBAAoB,CAAC;AACxE,MAAM,IAAI,OAAO,CAAC,mBAAmB,EAAE;AACvC,QAAQ,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,CAAC;AAC1D,OAAO;AACP,MAAM,MAAM,CAAC,IAAI,UAAU;AAC3B,QAAQ,mBAAmB;AAC3B,QAAQ,YAAY,CAAC,mBAAmB,GAAG,UAAU,CAAC,SAAS,GAAG,UAAU,CAAC,YAAY;AACzF,QAAQ,MAAM;AACd,QAAQ,OAAO,CAAC,CAAC,CAAC;AAClB;AACA;AACA,MAAM,OAAO,GAAG,IAAI,CAAC;AACrB,KAAK,CAAC;AACN;AACA;AACA,IAAI,WAAW,KAAK,SAAS,IAAI,cAAc,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;AACrE;AACA;AACA,IAAI,IAAI,kBAAkB,IAAI,OAAO,EAAE;AACvC,MAAMR,OAAK,CAAC,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,EAAE,SAAS,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE;AACjF,QAAQ,OAAO,CAAC,gBAAgB,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAC3C,OAAO,CAAC,CAAC;AACT,KAAK;AACL;AACA;AACA,IAAI,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE;AACrD,MAAM,OAAO,CAAC,eAAe,GAAG,CAAC,CAAC,OAAO,CAAC,eAAe,CAAC;AAC1D,KAAK;AACL;AACA;AACA,IAAI,IAAI,YAAY,IAAI,YAAY,KAAK,MAAM,EAAE;AACjD,MAAM,OAAO,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;AAClD,KAAK;AACL;AACA;AACA,IAAI,IAAI,kBAAkB,EAAE;AAC5B,MAAM,CAAC,CAAC,iBAAiB,EAAE,aAAa,CAAC,GAAG,oBAAoB,CAAC,kBAAkB,EAAE,IAAI,CAAC,EAAE;AAC5F,MAAM,OAAO,CAAC,gBAAgB,CAAC,UAAU,EAAE,iBAAiB,CAAC,CAAC;AAC9D,KAAK;AACL;AACA;AACA,IAAI,IAAI,gBAAgB,IAAI,OAAO,CAAC,MAAM,EAAE;AAC5C,MAAM,CAAC,CAAC,eAAe,EAAE,WAAW,CAAC,GAAG,oBAAoB,CAAC,gBAAgB,CAAC,EAAE;AAChF;AACA,MAAM,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;AACnE;AACA,MAAM,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;AAC9D,KAAK;AACL;AACA,IAAI,IAAI,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,MAAM,EAAE;AAC/C;AACA;AACA,MAAM,UAAU,GAAG,MAAM,IAAI;AAC7B,QAAQ,IAAI,CAAC,OAAO,EAAE;AACtB,UAAU,OAAO;AACjB,SAAS;AACT,QAAQ,MAAM,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,IAAI,GAAG,IAAI,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC;AAC3F,QAAQ,OAAO,CAAC,KAAK,EAAE,CAAC;AACxB,QAAQ,OAAO,GAAG,IAAI,CAAC;AACvB,OAAO,CAAC;AACR;AACA,MAAM,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;AACvE,MAAM,IAAI,OAAO,CAAC,MAAM,EAAE;AAC1B,QAAQ,OAAO,CAAC,MAAM,CAAC,OAAO,GAAG,UAAU,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;AACrG,OAAO;AACP,KAAK;AACL;AACA,IAAI,MAAM,QAAQ,GAAG,aAAa,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AAChD;AACA,IAAI,IAAI,QAAQ,IAAI,QAAQ,CAAC,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE;AACjE,MAAM,MAAM,CAAC,IAAI,UAAU,CAAC,uBAAuB,GAAG,QAAQ,GAAG,GAAG,EAAE,UAAU,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC,CAAC;AAC3G,MAAM,OAAO;AACb,KAAK;AACL;AACA;AACA;AACA,IAAI,OAAO,CAAC,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,CAAC;AACtC,GAAG,CAAC,CAAC;AACL;;AChMA,MAAM,cAAc,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK;AAC7C,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,OAAO,GAAG,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;AACtE;AACA,EAAE,IAAI,OAAO,IAAI,MAAM,EAAE;AACzB,IAAI,IAAI,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;AAC3C;AACA,IAAI,IAAI,OAAO,CAAC;AAChB;AACA,IAAI,MAAM,OAAO,GAAG,UAAU,MAAM,EAAE;AACtC,MAAM,IAAI,CAAC,OAAO,EAAE;AACpB,QAAQ,OAAO,GAAG,IAAI,CAAC;AACvB,QAAQ,WAAW,EAAE,CAAC;AACtB,QAAQ,MAAM,GAAG,GAAG,MAAM,YAAY,KAAK,GAAG,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;AACnE,QAAQ,UAAU,CAAC,KAAK,CAAC,GAAG,YAAY,UAAU,GAAG,GAAG,GAAG,IAAI,aAAa,CAAC,GAAG,YAAY,KAAK,GAAG,GAAG,CAAC,OAAO,GAAG,GAAG,CAAC,CAAC,CAAC;AACxH,OAAO;AACP,MAAK;AACL;AACA,IAAI,IAAI,KAAK,GAAG,OAAO,IAAI,UAAU,CAAC,MAAM;AAC5C,MAAM,KAAK,GAAG,IAAI,CAAC;AACnB,MAAM,OAAO,CAAC,IAAI,UAAU,CAAC,CAAC,QAAQ,EAAE,OAAO,CAAC,eAAe,CAAC,EAAE,UAAU,CAAC,SAAS,CAAC,EAAC;AACxF,KAAK,EAAE,OAAO,EAAC;AACf;AACA,IAAI,MAAM,WAAW,GAAG,MAAM;AAC9B,MAAM,IAAI,OAAO,EAAE;AACnB,QAAQ,KAAK,IAAI,YAAY,CAAC,KAAK,CAAC,CAAC;AACrC,QAAQ,KAAK,GAAG,IAAI,CAAC;AACrB,QAAQ,OAAO,CAAC,OAAO,CAAC,MAAM,IAAI;AAClC,UAAU,MAAM,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAC1G,SAAS,CAAC,CAAC;AACX,QAAQ,OAAO,GAAG,IAAI,CAAC;AACvB,OAAO;AACP,MAAK;AACL;AACA,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;AAC3E;AACA,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,UAAU,CAAC;AAChC;AACA,IAAI,MAAM,CAAC,WAAW,GAAG,MAAMA,OAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AACvD;AACA,IAAI,OAAO,MAAM,CAAC;AAClB,GAAG;AACH,EAAC;AACD;AACA,uBAAe,cAAc;;AC9CtB,MAAM,WAAW,GAAG,WAAW,KAAK,EAAE,SAAS,EAAE;AACxD,EAAE,IAAI,GAAG,GAAG,KAAK,CAAC,UAAU,CAAC;AAC7B;AACA,EAAE,IAAI,CAAC,SAAS,IAAI,GAAG,GAAG,SAAS,EAAE;AACrC,IAAI,MAAM,KAAK,CAAC;AAChB,IAAI,OAAO;AACX,GAAG;AACH;AACA,EAAE,IAAI,GAAG,GAAG,CAAC,CAAC;AACd,EAAE,IAAI,GAAG,CAAC;AACV;AACA,EAAE,OAAO,GAAG,GAAG,GAAG,EAAE;AACpB,IAAI,GAAG,GAAG,GAAG,GAAG,SAAS,CAAC;AAC1B,IAAI,MAAM,KAAK,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAChC,IAAI,GAAG,GAAG,GAAG,CAAC;AACd,GAAG;AACH,EAAC;AACD;AACO,MAAM,SAAS,GAAG,iBAAiB,QAAQ,EAAE,SAAS,EAAE;AAC/D,EAAE,WAAW,MAAM,KAAK,IAAI,UAAU,CAAC,QAAQ,CAAC,EAAE;AAClD,IAAI,OAAO,WAAW,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AACzC,GAAG;AACH,EAAC;AACD;AACA,MAAM,UAAU,GAAG,iBAAiB,MAAM,EAAE;AAC5C,EAAE,IAAI,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE;AACpC,IAAI,OAAO,MAAM,CAAC;AAClB,IAAI,OAAO;AACX,GAAG;AACH;AACA,EAAE,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;AACpC,EAAE,IAAI;AACN,IAAI,SAAS;AACb,MAAM,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;AAChD,MAAM,IAAI,IAAI,EAAE;AAChB,QAAQ,MAAM;AACd,OAAO;AACP,MAAM,MAAM,KAAK,CAAC;AAClB,KAAK;AACL,GAAG,SAAS;AACZ,IAAI,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC;AAC1B,GAAG;AACH,EAAC;AACD;AACO,MAAM,WAAW,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,KAAK;AACxE,EAAE,MAAM,QAAQ,GAAG,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAChD;AACA,EAAE,IAAI,KAAK,GAAG,CAAC,CAAC;AAChB,EAAE,IAAI,IAAI,CAAC;AACX,EAAE,IAAI,SAAS,GAAG,CAAC,CAAC,KAAK;AACzB,IAAI,IAAI,CAAC,IAAI,EAAE;AACf,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,MAAM,QAAQ,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC9B,KAAK;AACL,IAAG;AACH;AACA,EAAE,OAAO,IAAI,cAAc,CAAC;AAC5B,IAAI,MAAM,IAAI,CAAC,UAAU,EAAE;AAC3B,MAAM,IAAI;AACV,QAAQ,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;AACpD;AACA,QAAQ,IAAI,IAAI,EAAE;AAClB,SAAS,SAAS,EAAE,CAAC;AACrB,UAAU,UAAU,CAAC,KAAK,EAAE,CAAC;AAC7B,UAAU,OAAO;AACjB,SAAS;AACT;AACA,QAAQ,IAAI,GAAG,GAAG,KAAK,CAAC,UAAU,CAAC;AACnC,QAAQ,IAAI,UAAU,EAAE;AACxB,UAAU,IAAI,WAAW,GAAG,KAAK,IAAI,GAAG,CAAC;AACzC,UAAU,UAAU,CAAC,WAAW,CAAC,CAAC;AAClC,SAAS;AACT,QAAQ,UAAU,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;AAClD,OAAO,CAAC,OAAO,GAAG,EAAE;AACpB,QAAQ,SAAS,CAAC,GAAG,CAAC,CAAC;AACvB,QAAQ,MAAM,GAAG,CAAC;AAClB,OAAO;AACP,KAAK;AACL,IAAI,MAAM,CAAC,MAAM,EAAE;AACnB,MAAM,SAAS,CAAC,MAAM,CAAC,CAAC;AACxB,MAAM,OAAO,QAAQ,CAAC,MAAM,EAAE,CAAC;AAC/B,KAAK;AACL,GAAG,EAAE;AACL,IAAI,aAAa,EAAE,CAAC;AACpB,GAAG,CAAC;AACJ;;AC5EA,MAAM,gBAAgB,GAAG,OAAO,KAAK,KAAK,UAAU,IAAI,OAAO,OAAO,KAAK,UAAU,IAAI,OAAO,QAAQ,KAAK,UAAU,CAAC;AACxH,MAAM,yBAAyB,GAAG,gBAAgB,IAAI,OAAO,cAAc,KAAK,UAAU,CAAC;AAC3F;AACA;AACA,MAAM,UAAU,GAAG,gBAAgB,KAAK,OAAO,WAAW,KAAK,UAAU;AACzE,IAAI,CAAC,CAAC,OAAO,KAAK,CAAC,GAAG,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,IAAI,WAAW,EAAE,CAAC;AAClE,IAAI,OAAO,GAAG,KAAK,IAAI,UAAU,CAAC,MAAM,IAAI,QAAQ,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;AACxE,CAAC,CAAC;AACF;AACA,MAAM,IAAI,GAAG,CAAC,EAAE,EAAE,GAAG,IAAI,KAAK;AAC9B,EAAE,IAAI;AACN,IAAI,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;AACzB,GAAG,CAAC,OAAO,CAAC,EAAE;AACd,IAAI,OAAO,KAAK;AAChB,GAAG;AACH,EAAC;AACD;AACA,MAAM,qBAAqB,GAAG,yBAAyB,IAAI,IAAI,CAAC,MAAM;AACtE,EAAE,IAAI,cAAc,GAAG,KAAK,CAAC;AAC7B;AACA,EAAE,MAAM,cAAc,GAAG,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,EAAE;AACtD,IAAI,IAAI,EAAE,IAAI,cAAc,EAAE;AAC9B,IAAI,MAAM,EAAE,MAAM;AAClB,IAAI,IAAI,MAAM,GAAG;AACjB,MAAM,cAAc,GAAG,IAAI,CAAC;AAC5B,MAAM,OAAO,MAAM,CAAC;AACpB,KAAK;AACL,GAAG,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;AACjC;AACA,EAAE,OAAO,cAAc,IAAI,CAAC,cAAc,CAAC;AAC3C,CAAC,CAAC,CAAC;AACH;AACA,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,CAAC;AACrC;AACA,MAAM,sBAAsB,GAAG,yBAAyB;AACxD,EAAE,IAAI,CAAC,MAAMA,OAAK,CAAC,gBAAgB,CAAC,IAAI,QAAQ,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;AAC5D;AACA;AACA,MAAM,SAAS,GAAG;AAClB,EAAE,MAAM,EAAE,sBAAsB,KAAK,CAAC,GAAG,KAAK,GAAG,CAAC,IAAI,CAAC;AACvD,CAAC,CAAC;AACF;AACA,gBAAgB,KAAK,CAAC,CAAC,GAAG,KAAK;AAC/B,EAAE,CAAC,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,IAAI;AACxE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,SAAS,CAAC,IAAI,CAAC,GAAGA,OAAK,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,IAAI,CAAC,EAAE;AAC7F,MAAM,CAAC,CAAC,EAAE,MAAM,KAAK;AACrB,QAAQ,MAAM,IAAI,UAAU,CAAC,CAAC,eAAe,EAAE,IAAI,CAAC,kBAAkB,CAAC,EAAE,UAAU,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC;AAC7G,OAAO,EAAC;AACR,GAAG,CAAC,CAAC;AACL,CAAC,EAAE,IAAI,QAAQ,CAAC,CAAC,CAAC;AAClB;AACA,MAAM,aAAa,GAAG,OAAO,IAAI,KAAK;AACtC,EAAE,IAAI,IAAI,IAAI,IAAI,EAAE;AACpB,IAAI,OAAO,CAAC,CAAC;AACb,GAAG;AACH;AACA,EAAE,GAAGA,OAAK,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;AACzB,IAAI,OAAO,IAAI,CAAC,IAAI,CAAC;AACrB,GAAG;AACH;AACA,EAAE,GAAGA,OAAK,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE;AACtC,IAAI,MAAM,QAAQ,GAAG,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,EAAE;AAClD,MAAM,MAAM,EAAE,MAAM;AACpB,MAAM,IAAI;AACV,KAAK,CAAC,CAAC;AACP,IAAI,OAAO,CAAC,MAAM,QAAQ,CAAC,WAAW,EAAE,EAAE,UAAU,CAAC;AACrD,GAAG;AACH;AACA,EAAE,GAAGA,OAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,IAAIA,OAAK,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE;AACjE,IAAI,OAAO,IAAI,CAAC,UAAU,CAAC;AAC3B,GAAG;AACH;AACA,EAAE,GAAGA,OAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE;AACpC,IAAI,IAAI,GAAG,IAAI,GAAG,EAAE,CAAC;AACrB,GAAG;AACH;AACA,EAAE,GAAGA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;AAC3B,IAAI,OAAO,CAAC,MAAM,UAAU,CAAC,IAAI,CAAC,EAAE,UAAU,CAAC;AAC/C,GAAG;AACH,EAAC;AACD;AACA,MAAM,iBAAiB,GAAG,OAAO,OAAO,EAAE,IAAI,KAAK;AACnD,EAAE,MAAM,MAAM,GAAGA,OAAK,CAAC,cAAc,CAAC,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;AAClE;AACA,EAAE,OAAO,MAAM,IAAI,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC;AACvD,EAAC;AACD;AACA,mBAAe,gBAAgB,KAAK,OAAO,MAAM,KAAK;AACtD,EAAE,IAAI;AACN,IAAI,GAAG;AACP,IAAI,MAAM;AACV,IAAI,IAAI;AACR,IAAI,MAAM;AACV,IAAI,WAAW;AACf,IAAI,OAAO;AACX,IAAI,kBAAkB;AACtB,IAAI,gBAAgB;AACpB,IAAI,YAAY;AAChB,IAAI,OAAO;AACX,IAAI,eAAe,GAAG,aAAa;AACnC,IAAI,YAAY;AAChB,GAAG,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;AAC5B;AACA,EAAE,YAAY,GAAG,YAAY,GAAG,CAAC,YAAY,GAAG,EAAE,EAAE,WAAW,EAAE,GAAG,MAAM,CAAC;AAC3E;AACA,EAAE,IAAI,cAAc,GAAGS,gBAAc,CAAC,CAAC,MAAM,EAAE,WAAW,IAAI,WAAW,CAAC,aAAa,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC;AACrG;AACA,EAAE,IAAI,OAAO,CAAC;AACd;AACA,EAAE,MAAM,WAAW,GAAG,cAAc,IAAI,cAAc,CAAC,WAAW,KAAK,MAAM;AAC7E,MAAM,cAAc,CAAC,WAAW,EAAE,CAAC;AACnC,GAAG,CAAC,CAAC;AACL;AACA,EAAE,IAAI,oBAAoB,CAAC;AAC3B;AACA,EAAE,IAAI;AACN,IAAI;AACJ,MAAM,gBAAgB,IAAI,qBAAqB,IAAI,MAAM,KAAK,KAAK,IAAI,MAAM,KAAK,MAAM;AACxF,MAAM,CAAC,oBAAoB,GAAG,MAAM,iBAAiB,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC;AAC3E,MAAM;AACN,MAAM,IAAI,QAAQ,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE;AACtC,QAAQ,MAAM,EAAE,MAAM;AACtB,QAAQ,IAAI,EAAE,IAAI;AAClB,QAAQ,MAAM,EAAE,MAAM;AACtB,OAAO,CAAC,CAAC;AACT;AACA,MAAM,IAAI,iBAAiB,CAAC;AAC5B;AACA,MAAM,IAAIT,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,iBAAiB,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,EAAE;AAChG,QAAQ,OAAO,CAAC,cAAc,CAAC,iBAAiB,EAAC;AACjD,OAAO;AACP;AACA,MAAM,IAAI,QAAQ,CAAC,IAAI,EAAE;AACzB,QAAQ,MAAM,CAAC,UAAU,EAAE,KAAK,CAAC,GAAG,sBAAsB;AAC1D,UAAU,oBAAoB;AAC9B,UAAU,oBAAoB,CAAC,cAAc,CAAC,gBAAgB,CAAC,CAAC;AAChE,SAAS,CAAC;AACV;AACA,QAAQ,IAAI,GAAG,WAAW,CAAC,QAAQ,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;AACjF,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,eAAe,CAAC,EAAE;AAC1C,MAAM,eAAe,GAAG,eAAe,GAAG,SAAS,GAAG,MAAM,CAAC;AAC7D,KAAK;AACL;AACA;AACA;AACA,IAAI,MAAM,sBAAsB,GAAG,aAAa,IAAI,OAAO,CAAC,SAAS,CAAC;AACtE,IAAI,OAAO,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE;AAC/B,MAAM,GAAG,YAAY;AACrB,MAAM,MAAM,EAAE,cAAc;AAC5B,MAAM,MAAM,EAAE,MAAM,CAAC,WAAW,EAAE;AAClC,MAAM,OAAO,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC,MAAM,EAAE;AAC3C,MAAM,IAAI,EAAE,IAAI;AAChB,MAAM,MAAM,EAAE,MAAM;AACpB,MAAM,WAAW,EAAE,sBAAsB,GAAG,eAAe,GAAG,SAAS;AACvE,KAAK,CAAC,CAAC;AACP;AACA,IAAI,IAAI,QAAQ,GAAG,MAAM,KAAK,CAAC,OAAO,CAAC,CAAC;AACxC;AACA,IAAI,MAAM,gBAAgB,GAAG,sBAAsB,KAAK,YAAY,KAAK,QAAQ,IAAI,YAAY,KAAK,UAAU,CAAC,CAAC;AAClH;AACA,IAAI,IAAI,sBAAsB,KAAK,kBAAkB,KAAK,gBAAgB,IAAI,WAAW,CAAC,CAAC,EAAE;AAC7F,MAAM,MAAM,OAAO,GAAG,EAAE,CAAC;AACzB;AACA,MAAM,CAAC,QAAQ,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,IAAI;AAC1D,QAAQ,OAAO,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;AACvC,OAAO,CAAC,CAAC;AACT;AACA,MAAM,MAAM,qBAAqB,GAAGA,OAAK,CAAC,cAAc,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC,CAAC;AACjG;AACA,MAAM,MAAM,CAAC,UAAU,EAAE,KAAK,CAAC,GAAG,kBAAkB,IAAI,sBAAsB;AAC9E,QAAQ,qBAAqB;AAC7B,QAAQ,oBAAoB,CAAC,cAAc,CAAC,kBAAkB,CAAC,EAAE,IAAI,CAAC;AACtE,OAAO,IAAI,EAAE,CAAC;AACd;AACA,MAAM,QAAQ,GAAG,IAAI,QAAQ;AAC7B,QAAQ,WAAW,CAAC,QAAQ,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,MAAM;AACzE,UAAU,KAAK,IAAI,KAAK,EAAE,CAAC;AAC3B,UAAU,WAAW,IAAI,WAAW,EAAE,CAAC;AACvC,SAAS,CAAC;AACV,QAAQ,OAAO;AACf,OAAO,CAAC;AACR,KAAK;AACL;AACA,IAAI,YAAY,GAAG,YAAY,IAAI,MAAM,CAAC;AAC1C;AACA,IAAI,IAAI,YAAY,GAAG,MAAM,SAAS,CAACA,OAAK,CAAC,OAAO,CAAC,SAAS,EAAE,YAAY,CAAC,IAAI,MAAM,CAAC,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AAC3G;AACA,IAAI,CAAC,gBAAgB,IAAI,WAAW,IAAI,WAAW,EAAE,CAAC;AACtD;AACA,IAAI,OAAO,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK;AAClD,MAAM,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE;AAC9B,QAAQ,IAAI,EAAE,YAAY;AAC1B,QAAQ,OAAO,EAAEQ,cAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;AACpD,QAAQ,MAAM,EAAE,QAAQ,CAAC,MAAM;AAC/B,QAAQ,UAAU,EAAE,QAAQ,CAAC,UAAU;AACvC,QAAQ,MAAM;AACd,QAAQ,OAAO;AACf,OAAO,EAAC;AACR,KAAK,CAAC;AACN,GAAG,CAAC,OAAO,GAAG,EAAE;AAChB,IAAI,WAAW,IAAI,WAAW,EAAE,CAAC;AACjC;AACA,IAAI,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,WAAW,IAAI,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE;AACvE,MAAM,MAAM,MAAM,CAAC,MAAM;AACzB,QAAQ,IAAI,UAAU,CAAC,eAAe,EAAE,UAAU,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC;AAChF,QAAQ;AACR,UAAU,KAAK,EAAE,GAAG,CAAC,KAAK,IAAI,GAAG;AACjC,SAAS;AACT,OAAO;AACP,KAAK;AACL;AACA,IAAI,MAAM,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACjE,GAAG;AACH,CAAC,CAAC;;AC5NF,MAAM,aAAa,GAAG;AACtB,EAAE,IAAI,EAAE,WAAW;AACnB,EAAE,GAAG,EAAE,UAAU;AACjB,EAAE,KAAK,EAAE,YAAY;AACrB,EAAC;AACD;AACAR,OAAK,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,EAAE,EAAE,KAAK,KAAK;AAC5C,EAAE,IAAI,EAAE,EAAE;AACV,IAAI,IAAI;AACR,MAAM,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AACjD,KAAK,CAAC,OAAO,CAAC,EAAE;AAChB;AACA,KAAK;AACL,IAAI,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,aAAa,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AACtD,GAAG;AACH,CAAC,CAAC,CAAC;AACH;AACA,MAAM,YAAY,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;AAC/C;AACA,MAAM,gBAAgB,GAAG,CAAC,OAAO,KAAKA,OAAK,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,CAAC;AACzG;AACA,eAAe;AACf,EAAE,UAAU,EAAE,CAAC,QAAQ,KAAK;AAC5B,IAAI,QAAQ,GAAGA,OAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,QAAQ,GAAG,CAAC,QAAQ,CAAC,CAAC;AAC/D;AACA,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC;AAC9B,IAAI,IAAI,aAAa,CAAC;AACtB,IAAI,IAAI,OAAO,CAAC;AAChB;AACA,IAAI,MAAM,eAAe,GAAG,EAAE,CAAC;AAC/B;AACA,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC,EAAE,EAAE;AACrC,MAAM,aAAa,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;AAClC,MAAM,IAAI,EAAE,CAAC;AACb;AACA,MAAM,OAAO,GAAG,aAAa,CAAC;AAC9B;AACA,MAAM,IAAI,CAAC,gBAAgB,CAAC,aAAa,CAAC,EAAE;AAC5C,QAAQ,OAAO,GAAG,aAAa,CAAC,CAAC,EAAE,GAAG,MAAM,CAAC,aAAa,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;AAC5E;AACA,QAAQ,IAAI,OAAO,KAAK,SAAS,EAAE;AACnC,UAAU,MAAM,IAAI,UAAU,CAAC,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;AAC1D,SAAS;AACT,OAAO;AACP;AACA,MAAM,IAAI,OAAO,EAAE;AACnB,QAAQ,MAAM;AACd,OAAO;AACP;AACA,MAAM,eAAe,CAAC,EAAE,IAAI,GAAG,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;AAC/C,KAAK;AACL;AACA,IAAI,IAAI,CAAC,OAAO,EAAE;AAClB;AACA,MAAM,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC;AACrD,SAAS,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC;AAC9C,WAAW,KAAK,KAAK,KAAK,GAAG,qCAAqC,GAAG,+BAA+B,CAAC;AACrG,SAAS,CAAC;AACV;AACA,MAAM,IAAI,CAAC,GAAG,MAAM;AACpB,SAAS,OAAO,CAAC,MAAM,GAAG,CAAC,GAAG,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AACjH,QAAQ,yBAAyB,CAAC;AAClC;AACA,MAAM,MAAM,IAAI,UAAU;AAC1B,QAAQ,CAAC,qDAAqD,CAAC,GAAG,CAAC;AACnE,QAAQ,iBAAiB;AACzB,OAAO,CAAC;AACR,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC;AACnB,GAAG;AACH,EAAE,QAAQ,EAAE,aAAa;AACzB;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,4BAA4B,CAAC,MAAM,EAAE;AAC9C,EAAE,IAAI,MAAM,CAAC,WAAW,EAAE;AAC1B,IAAI,MAAM,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC;AAC1C,GAAG;AACH;AACA,EAAE,IAAI,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE;AAC9C,IAAI,MAAM,IAAI,aAAa,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC1C,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,eAAe,CAAC,MAAM,EAAE;AAChD,EAAE,4BAA4B,CAAC,MAAM,CAAC,CAAC;AACvC;AACA,EAAE,MAAM,CAAC,OAAO,GAAGQ,cAAY,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AACrD;AACA;AACA,EAAE,MAAM,CAAC,IAAI,GAAG,aAAa,CAAC,IAAI;AAClC,IAAI,MAAM;AACV,IAAI,MAAM,CAAC,gBAAgB;AAC3B,GAAG,CAAC;AACJ;AACA,EAAE,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE;AAC9D,IAAI,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,mCAAmC,EAAE,KAAK,CAAC,CAAC;AAC9E,GAAG;AACH;AACA,EAAE,MAAM,OAAO,GAAG,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,OAAO,IAAID,UAAQ,CAAC,OAAO,CAAC,CAAC;AAC1E;AACA,EAAE,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,SAAS,mBAAmB,CAAC,QAAQ,EAAE;AACrE,IAAI,4BAA4B,CAAC,MAAM,CAAC,CAAC;AACzC;AACA;AACA,IAAI,QAAQ,CAAC,IAAI,GAAG,aAAa,CAAC,IAAI;AACtC,MAAM,MAAM;AACZ,MAAM,MAAM,CAAC,iBAAiB;AAC9B,MAAM,QAAQ;AACd,KAAK,CAAC;AACN;AACA,IAAI,QAAQ,CAAC,OAAO,GAAGC,cAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAC3D;AACA,IAAI,OAAO,QAAQ,CAAC;AACpB,GAAG,EAAE,SAAS,kBAAkB,CAAC,MAAM,EAAE;AACzC,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;AAC3B,MAAM,4BAA4B,CAAC,MAAM,CAAC,CAAC;AAC3C;AACA;AACA,MAAM,IAAI,MAAM,IAAI,MAAM,CAAC,QAAQ,EAAE;AACrC,QAAQ,MAAM,CAAC,QAAQ,CAAC,IAAI,GAAG,aAAa,CAAC,IAAI;AACjD,UAAU,MAAM;AAChB,UAAU,MAAM,CAAC,iBAAiB;AAClC,UAAU,MAAM,CAAC,QAAQ;AACzB,SAAS,CAAC;AACV,QAAQ,MAAM,CAAC,QAAQ,CAAC,OAAO,GAAGA,cAAY,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAC7E,OAAO;AACP,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAClC,GAAG,CAAC,CAAC;AACL;;AChFO,MAAM,OAAO,GAAG,OAAO;;ACK9B,MAAME,YAAU,GAAG,EAAE,CAAC;AACtB;AACA;AACA,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC,KAAK;AACrF,EAAEA,YAAU,CAAC,IAAI,CAAC,GAAG,SAAS,SAAS,CAAC,KAAK,EAAE;AAC/C,IAAI,OAAO,OAAO,KAAK,KAAK,IAAI,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC;AACtE,GAAG,CAAC;AACJ,CAAC,CAAC,CAAC;AACH;AACA,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAA,YAAU,CAAC,YAAY,GAAG,SAAS,YAAY,CAAC,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE;AAC7E,EAAE,SAAS,aAAa,CAAC,GAAG,EAAE,IAAI,EAAE;AACpC,IAAI,OAAO,UAAU,GAAG,OAAO,GAAG,0BAA0B,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,IAAI,OAAO,GAAG,IAAI,GAAG,OAAO,GAAG,EAAE,CAAC,CAAC;AACnH,GAAG;AACH;AACA;AACA,EAAE,OAAO,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,KAAK;AAC/B,IAAI,IAAI,SAAS,KAAK,KAAK,EAAE;AAC7B,MAAM,MAAM,IAAI,UAAU;AAC1B,QAAQ,aAAa,CAAC,GAAG,EAAE,mBAAmB,IAAI,OAAO,GAAG,MAAM,GAAG,OAAO,GAAG,EAAE,CAAC,CAAC;AACnF,QAAQ,UAAU,CAAC,cAAc;AACjC,OAAO,CAAC;AACR,KAAK;AACL;AACA,IAAI,IAAI,OAAO,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAE;AAC7C,MAAM,kBAAkB,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;AACrC;AACA,MAAM,OAAO,CAAC,IAAI;AAClB,QAAQ,aAAa;AACrB,UAAU,GAAG;AACb,UAAU,8BAA8B,GAAG,OAAO,GAAG,yCAAyC;AAC9F,SAAS;AACT,OAAO,CAAC;AACR,KAAK;AACL;AACA,IAAI,OAAO,SAAS,GAAG,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC;AAC1D,GAAG,CAAC;AACJ,CAAC,CAAC;AACF;AACAA,YAAU,CAAC,QAAQ,GAAG,SAAS,QAAQ,CAAC,eAAe,EAAE;AACzD,EAAE,OAAO,CAAC,KAAK,EAAE,GAAG,KAAK;AACzB;AACA,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,CAAC,4BAA4B,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC;AACzE,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG;AACH,CAAC,CAAC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE;AACtD,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;AACnC,IAAI,MAAM,IAAI,UAAU,CAAC,2BAA2B,EAAE,UAAU,CAAC,oBAAoB,CAAC,CAAC;AACvF,GAAG;AACH,EAAE,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACpC,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;AACtB,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AAClB,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AACxB,IAAI,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AAClC,IAAI,IAAI,SAAS,EAAE;AACnB,MAAM,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;AACjC,MAAM,MAAM,MAAM,GAAG,KAAK,KAAK,SAAS,IAAI,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;AAC3E,MAAM,IAAI,MAAM,KAAK,IAAI,EAAE;AAC3B,QAAQ,MAAM,IAAI,UAAU,CAAC,SAAS,GAAG,GAAG,GAAG,WAAW,GAAG,MAAM,EAAE,UAAU,CAAC,oBAAoB,CAAC,CAAC;AACtG,OAAO;AACP,MAAM,SAAS;AACf,KAAK;AACL,IAAI,IAAI,YAAY,KAAK,IAAI,EAAE;AAC/B,MAAM,MAAM,IAAI,UAAU,CAAC,iBAAiB,GAAG,GAAG,EAAE,UAAU,CAAC,cAAc,CAAC,CAAC;AAC/E,KAAK;AACL,GAAG;AACH,CAAC;AACD;AACA,gBAAe;AACf,EAAE,aAAa;AACf,cAAEA,YAAU;AACZ,CAAC;;ACvFD,MAAM,UAAU,GAAG,SAAS,CAAC,UAAU,CAAC;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,KAAK,CAAC;AACZ,EAAE,WAAW,CAAC,cAAc,EAAE;AAC9B,IAAI,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;AACnC,IAAI,IAAI,CAAC,YAAY,GAAG;AACxB,MAAM,OAAO,EAAE,IAAIC,oBAAkB,EAAE;AACvC,MAAM,QAAQ,EAAE,IAAIA,oBAAkB,EAAE;AACxC,KAAK,CAAC;AACN,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,MAAM,OAAO,CAAC,WAAW,EAAE,MAAM,EAAE;AACrC,IAAI,IAAI;AACR,MAAM,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;AACtD,KAAK,CAAC,OAAO,GAAG,EAAE;AAClB,MAAM,IAAI,GAAG,YAAY,KAAK,EAAE;AAChC,QAAQ,IAAI,KAAK,GAAG,EAAE,CAAC;AACvB;AACA,QAAQ,KAAK,CAAC,iBAAiB,GAAG,KAAK,CAAC,iBAAiB,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC,CAAC;AACzF;AACA;AACA,QAAQ,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC;AAC1E,QAAQ,IAAI;AACZ,UAAU,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE;AAC1B,YAAY,GAAG,CAAC,KAAK,GAAG,KAAK,CAAC;AAC9B;AACA,WAAW,MAAM,IAAI,KAAK,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,EAAE;AAC3F,YAAY,GAAG,CAAC,KAAK,IAAI,IAAI,GAAG,MAAK;AACrC,WAAW;AACX,SAAS,CAAC,OAAO,CAAC,EAAE;AACpB;AACA,SAAS;AACT,OAAO;AACP;AACA,MAAM,MAAM,GAAG,CAAC;AAChB,KAAK;AACL,GAAG;AACH;AACA,EAAE,QAAQ,CAAC,WAAW,EAAE,MAAM,EAAE;AAChC;AACA;AACA,IAAI,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;AACzC,MAAM,MAAM,GAAG,MAAM,IAAI,EAAE,CAAC;AAC5B,MAAM,MAAM,CAAC,GAAG,GAAG,WAAW,CAAC;AAC/B,KAAK,MAAM;AACX,MAAM,MAAM,GAAG,WAAW,IAAI,EAAE,CAAC;AACjC,KAAK;AACL;AACA,IAAI,MAAM,GAAG,WAAW,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AAChD;AACA,IAAI,MAAM,CAAC,YAAY,EAAE,gBAAgB,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC;AAC7D;AACA,IAAI,IAAI,YAAY,KAAK,SAAS,EAAE;AACpC,MAAM,SAAS,CAAC,aAAa,CAAC,YAAY,EAAE;AAC5C,QAAQ,iBAAiB,EAAE,UAAU,CAAC,YAAY,CAAC,UAAU,CAAC,OAAO,CAAC;AACtE,QAAQ,iBAAiB,EAAE,UAAU,CAAC,YAAY,CAAC,UAAU,CAAC,OAAO,CAAC;AACtE,QAAQ,mBAAmB,EAAE,UAAU,CAAC,YAAY,CAAC,UAAU,CAAC,OAAO,CAAC;AACxE,OAAO,EAAE,KAAK,CAAC,CAAC;AAChB,KAAK;AACL;AACA,IAAI,IAAI,gBAAgB,IAAI,IAAI,EAAE;AAClC,MAAM,IAAIX,OAAK,CAAC,UAAU,CAAC,gBAAgB,CAAC,EAAE;AAC9C,QAAQ,MAAM,CAAC,gBAAgB,GAAG;AAClC,UAAU,SAAS,EAAE,gBAAgB;AACrC,UAAS;AACT,OAAO,MAAM;AACb,QAAQ,SAAS,CAAC,aAAa,CAAC,gBAAgB,EAAE;AAClD,UAAU,MAAM,EAAE,UAAU,CAAC,QAAQ;AACrC,UAAU,SAAS,EAAE,UAAU,CAAC,QAAQ;AACxC,SAAS,EAAE,IAAI,CAAC,CAAC;AACjB,OAAO;AACP,KAAK;AACL;AACA,IAAI,SAAS,CAAC,aAAa,CAAC,MAAM,EAAE;AACpC,MAAM,OAAO,EAAE,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC;AAC7C,MAAM,aAAa,EAAE,UAAU,CAAC,QAAQ,CAAC,eAAe,CAAC;AACzD,KAAK,EAAE,IAAI,CAAC,CAAC;AACb;AACA;AACA,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,IAAI,KAAK,EAAE,WAAW,EAAE,CAAC;AACnF;AACA;AACA,IAAI,IAAI,cAAc,GAAG,OAAO,IAAIA,OAAK,CAAC,KAAK;AAC/C,MAAM,OAAO,CAAC,MAAM;AACpB,MAAM,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC;AAC5B,KAAK,CAAC;AACN;AACA,IAAI,OAAO,IAAIA,OAAK,CAAC,OAAO;AAC5B,MAAM,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,CAAC;AACjE,MAAM,CAAC,MAAM,KAAK;AAClB,QAAQ,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC;AAC/B,OAAO;AACP,KAAK,CAAC;AACN;AACA,IAAI,MAAM,CAAC,OAAO,GAAGQ,cAAY,CAAC,MAAM,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;AAClE;AACA;AACA,IAAI,MAAM,uBAAuB,GAAG,EAAE,CAAC;AACvC,IAAI,IAAI,8BAA8B,GAAG,IAAI,CAAC;AAC9C,IAAI,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,0BAA0B,CAAC,WAAW,EAAE;AACvF,MAAM,IAAI,OAAO,WAAW,CAAC,OAAO,KAAK,UAAU,IAAI,WAAW,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,KAAK,EAAE;AAC9F,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,8BAA8B,GAAG,8BAA8B,IAAI,WAAW,CAAC,WAAW,CAAC;AACjG;AACA,MAAM,uBAAuB,CAAC,OAAO,CAAC,WAAW,CAAC,SAAS,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;AACnF,KAAK,CAAC,CAAC;AACP;AACA,IAAI,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACxC,IAAI,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,OAAO,CAAC,SAAS,wBAAwB,CAAC,WAAW,EAAE;AACtF,MAAM,wBAAwB,CAAC,IAAI,CAAC,WAAW,CAAC,SAAS,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;AACjF,KAAK,CAAC,CAAC;AACP;AACA,IAAI,IAAI,OAAO,CAAC;AAChB,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC;AACd,IAAI,IAAI,GAAG,CAAC;AACZ;AACA,IAAI,IAAI,CAAC,8BAA8B,EAAE;AACzC,MAAM,MAAM,KAAK,GAAG,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC,CAAC;AAC5D,MAAM,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,uBAAuB,CAAC,CAAC;AAC1D,MAAM,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,wBAAwB,CAAC,CAAC;AACxD,MAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC;AACzB;AACA,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AACxC;AACA,MAAM,OAAO,CAAC,GAAG,GAAG,EAAE;AACtB,QAAQ,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACvD,OAAO;AACP;AACA,MAAM,OAAO,OAAO,CAAC;AACrB,KAAK;AACL;AACA,IAAI,GAAG,GAAG,uBAAuB,CAAC,MAAM,CAAC;AACzC;AACA,IAAI,IAAI,SAAS,GAAG,MAAM,CAAC;AAC3B;AACA,IAAI,CAAC,GAAG,CAAC,CAAC;AACV;AACA,IAAI,OAAO,CAAC,GAAG,GAAG,EAAE;AACpB,MAAM,MAAM,WAAW,GAAG,uBAAuB,CAAC,CAAC,EAAE,CAAC,CAAC;AACvD,MAAM,MAAM,UAAU,GAAG,uBAAuB,CAAC,CAAC,EAAE,CAAC,CAAC;AACtD,MAAM,IAAI;AACV,QAAQ,SAAS,GAAG,WAAW,CAAC,SAAS,CAAC,CAAC;AAC3C,OAAO,CAAC,OAAO,KAAK,EAAE;AACtB,QAAQ,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;AACrC,QAAQ,MAAM;AACd,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAI;AACR,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;AACtD,KAAK,CAAC,OAAO,KAAK,EAAE;AACpB,MAAM,OAAO,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACnC,KAAK;AACL;AACA,IAAI,CAAC,GAAG,CAAC,CAAC;AACV,IAAI,GAAG,GAAG,wBAAwB,CAAC,MAAM,CAAC;AAC1C;AACA,IAAI,OAAO,CAAC,GAAG,GAAG,EAAE;AACpB,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC,EAAE,CAAC,EAAE,wBAAwB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAC3F,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC;AACnB,GAAG;AACH;AACA,EAAE,MAAM,CAAC,MAAM,EAAE;AACjB,IAAI,MAAM,GAAG,WAAW,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AAChD,IAAI,MAAM,QAAQ,GAAG,aAAa,CAAC,MAAM,CAAC,OAAO,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;AAC/D,IAAI,OAAO,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,gBAAgB,CAAC,CAAC;AACtE,GAAG;AACH,CAAC;AACD;AACA;AACAR,OAAK,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,SAAS,mBAAmB,CAAC,MAAM,EAAE;AACzF;AACA,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,SAAS,GAAG,EAAE,MAAM,EAAE;AAClD,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,MAAM,IAAI,EAAE,EAAE;AAClD,MAAM,MAAM;AACZ,MAAM,GAAG;AACT,MAAM,IAAI,EAAE,CAAC,MAAM,IAAI,EAAE,EAAE,IAAI;AAC/B,KAAK,CAAC,CAAC,CAAC;AACR,GAAG,CAAC;AACJ,CAAC,CAAC,CAAC;AACH;AACAA,OAAK,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,SAAS,qBAAqB,CAAC,MAAM,EAAE;AAC/E;AACA;AACA,EAAE,SAAS,kBAAkB,CAAC,MAAM,EAAE;AACtC,IAAI,OAAO,SAAS,UAAU,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE;AAClD,MAAM,OAAO,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,MAAM,IAAI,EAAE,EAAE;AACpD,QAAQ,MAAM;AACd,QAAQ,OAAO,EAAE,MAAM,GAAG;AAC1B,UAAU,cAAc,EAAE,qBAAqB;AAC/C,SAAS,GAAG,EAAE;AACd,QAAQ,GAAG;AACX,QAAQ,IAAI;AACZ,OAAO,CAAC,CAAC,CAAC;AACV,KAAK,CAAC;AACN,GAAG;AACH;AACA,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,kBAAkB,EAAE,CAAC;AACjD;AACA,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;AAC9D,CAAC,CAAC,CAAC;AACH;AACA,cAAe,KAAK;;ACpOpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,WAAW,CAAC;AAClB,EAAE,WAAW,CAAC,QAAQ,EAAE;AACxB,IAAI,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;AACxC,MAAM,MAAM,IAAI,SAAS,CAAC,8BAA8B,CAAC,CAAC;AAC1D,KAAK;AACL;AACA,IAAI,IAAI,cAAc,CAAC;AACvB;AACA,IAAI,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC,SAAS,eAAe,CAAC,OAAO,EAAE;AACjE,MAAM,cAAc,GAAG,OAAO,CAAC;AAC/B,KAAK,CAAC,CAAC;AACP;AACA,IAAI,MAAM,KAAK,GAAG,IAAI,CAAC;AACvB;AACA;AACA,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI;AAChC,MAAM,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO;AACpC;AACA,MAAM,IAAI,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC;AACtC;AACA,MAAM,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AACtB,QAAQ,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;AACpC,OAAO;AACP,MAAM,KAAK,CAAC,UAAU,GAAG,IAAI,CAAC;AAC9B,KAAK,CAAC,CAAC;AACP;AACA;AACA,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,WAAW,IAAI;AACvC,MAAM,IAAI,QAAQ,CAAC;AACnB;AACA,MAAM,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,OAAO,IAAI;AAC7C,QAAQ,KAAK,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;AACjC,QAAQ,QAAQ,GAAG,OAAO,CAAC;AAC3B,OAAO,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AAC3B;AACA,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,MAAM,GAAG;AACzC,QAAQ,KAAK,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;AACpC,OAAO,CAAC;AACR;AACA,MAAM,OAAO,OAAO,CAAC;AACrB,KAAK,CAAC;AACN;AACA,IAAI,QAAQ,CAAC,SAAS,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE;AACvD,MAAM,IAAI,KAAK,CAAC,MAAM,EAAE;AACxB;AACA,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,KAAK,CAAC,MAAM,GAAG,IAAI,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACjE,MAAM,cAAc,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AACnC,KAAK,CAAC,CAAC;AACP,GAAG;AACH;AACA;AACA;AACA;AACA,EAAE,gBAAgB,GAAG;AACrB,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE;AACrB,MAAM,MAAM,IAAI,CAAC,MAAM,CAAC;AACxB,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,EAAE,SAAS,CAAC,QAAQ,EAAE;AACtB,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE;AACrB,MAAM,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,MAAM,OAAO;AACb,KAAK;AACL;AACA,IAAI,IAAI,IAAI,CAAC,UAAU,EAAE;AACzB,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AACrC,KAAK,MAAM;AACX,MAAM,IAAI,CAAC,UAAU,GAAG,CAAC,QAAQ,CAAC,CAAC;AACnC,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,EAAE,WAAW,CAAC,QAAQ,EAAE;AACxB,IAAI,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE;AAC1B,MAAM,OAAO;AACb,KAAK;AACL,IAAI,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;AACpD,IAAI,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE;AACtB,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;AACvC,KAAK;AACL,GAAG;AACH;AACA,EAAE,aAAa,GAAG;AAClB,IAAI,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;AAC7C;AACA,IAAI,MAAM,KAAK,GAAG,CAAC,GAAG,KAAK;AAC3B,MAAM,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC5B,KAAK,CAAC;AACN;AACA,IAAI,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC1B;AACA,IAAI,UAAU,CAAC,MAAM,CAAC,WAAW,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;AAClE;AACA,IAAI,OAAO,UAAU,CAAC,MAAM,CAAC;AAC7B,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,EAAE,OAAO,MAAM,GAAG;AAClB,IAAI,IAAI,MAAM,CAAC;AACf,IAAI,MAAM,KAAK,GAAG,IAAI,WAAW,CAAC,SAAS,QAAQ,CAAC,CAAC,EAAE;AACvD,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,KAAK,CAAC,CAAC;AACP,IAAI,OAAO;AACX,MAAM,KAAK;AACX,MAAM,MAAM;AACZ,KAAK,CAAC;AACN,GAAG;AACH,CAAC;AACD;AACA,oBAAe,WAAW;;ACpI1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,MAAM,CAAC,QAAQ,EAAE;AACzC,EAAE,OAAO,SAAS,IAAI,CAAC,GAAG,EAAE;AAC5B,IAAI,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AACrC,GAAG,CAAC;AACJ;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,YAAY,CAAC,OAAO,EAAE;AAC9C,EAAE,OAAOA,OAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,OAAO,CAAC,YAAY,KAAK,IAAI,CAAC,CAAC;AACpE;;ACbA,MAAM,cAAc,GAAG;AACvB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,kBAAkB,EAAE,GAAG;AACzB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,EAAE,EAAE,GAAG;AACT,EAAE,OAAO,EAAE,GAAG;AACd,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,2BAA2B,EAAE,GAAG;AAClC,EAAE,SAAS,EAAE,GAAG;AAChB,EAAE,YAAY,EAAE,GAAG;AACnB,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,WAAW,EAAE,GAAG;AAClB,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,MAAM,EAAE,GAAG;AACb,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,gBAAgB,EAAE,GAAG;AACvB,EAAE,KAAK,EAAE,GAAG;AACZ,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,WAAW,EAAE,GAAG;AAClB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,MAAM,EAAE,GAAG;AACb,EAAE,iBAAiB,EAAE,GAAG;AACxB,EAAE,iBAAiB,EAAE,GAAG;AACxB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,YAAY,EAAE,GAAG;AACnB,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,SAAS,EAAE,GAAG;AAChB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,gBAAgB,EAAE,GAAG;AACvB,EAAE,aAAa,EAAE,GAAG;AACpB,EAAE,2BAA2B,EAAE,GAAG;AAClC,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,IAAI,EAAE,GAAG;AACX,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,kBAAkB,EAAE,GAAG;AACzB,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,oBAAoB,EAAE,GAAG;AAC3B,EAAE,mBAAmB,EAAE,GAAG;AAC1B,EAAE,iBAAiB,EAAE,GAAG;AACxB,EAAE,SAAS,EAAE,GAAG;AAChB,EAAE,kBAAkB,EAAE,GAAG;AACzB,EAAE,mBAAmB,EAAE,GAAG;AAC1B,EAAE,MAAM,EAAE,GAAG;AACb,EAAE,gBAAgB,EAAE,GAAG;AACvB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,oBAAoB,EAAE,GAAG;AAC3B,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,2BAA2B,EAAE,GAAG;AAClC,EAAE,0BAA0B,EAAE,GAAG;AACjC,EAAE,mBAAmB,EAAE,GAAG;AAC1B,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,kBAAkB,EAAE,GAAG;AACzB,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,uBAAuB,EAAE,GAAG;AAC9B,EAAE,qBAAqB,EAAE,GAAG;AAC5B,EAAE,mBAAmB,EAAE,GAAG;AAC1B,EAAE,YAAY,EAAE,GAAG;AACnB,EAAE,WAAW,EAAE,GAAG;AAClB,EAAE,6BAA6B,EAAE,GAAG;AACpC,CAAC,CAAC;AACF;AACA,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,KAAK;AACzD,EAAE,cAAc,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC;AAC9B,CAAC,CAAC,CAAC;AACH;AACA,uBAAe,cAAc;;AClD7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,cAAc,CAAC,aAAa,EAAE;AACvC,EAAE,MAAM,OAAO,GAAG,IAAIY,OAAK,CAAC,aAAa,CAAC,CAAC;AAC3C,EAAE,MAAM,QAAQ,GAAG,IAAI,CAACA,OAAK,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAC1D;AACA;AACA,EAAEZ,OAAK,CAAC,MAAM,CAAC,QAAQ,EAAEY,OAAK,CAAC,SAAS,EAAE,OAAO,EAAE,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC;AACvE;AACA;AACA,EAAEZ,OAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC;AAC5D;AACA;AACA,EAAE,QAAQ,CAAC,MAAM,GAAG,SAAS,MAAM,CAAC,cAAc,EAAE;AACpD,IAAI,OAAO,cAAc,CAAC,WAAW,CAAC,aAAa,EAAE,cAAc,CAAC,CAAC,CAAC;AACtE,GAAG,CAAC;AACJ;AACA,EAAE,OAAO,QAAQ,CAAC;AAClB,CAAC;AACD;AACA;AACK,MAAC,KAAK,GAAG,cAAc,CAACO,UAAQ,EAAE;AACvC;AACA;AACA,KAAK,CAAC,KAAK,GAAGK,OAAK,CAAC;AACpB;AACA;AACA,KAAK,CAAC,aAAa,GAAG,aAAa,CAAC;AACpC,KAAK,CAAC,WAAW,GAAGC,aAAW,CAAC;AAChC,KAAK,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAC1B,KAAK,CAAC,OAAO,GAAG,OAAO,CAAC;AACxB,KAAK,CAAC,UAAU,GAAG,UAAU,CAAC;AAC9B;AACA;AACA,KAAK,CAAC,UAAU,GAAG,UAAU,CAAC;AAC9B;AACA;AACA,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,aAAa,CAAC;AACnC;AACA;AACA,KAAK,CAAC,GAAG,GAAG,SAAS,GAAG,CAAC,QAAQ,EAAE;AACnC,EAAE,OAAO,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AAC/B,CAAC,CAAC;AACF;AACA,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC;AACtB;AACA;AACA,KAAK,CAAC,YAAY,GAAG,YAAY,CAAC;AAClC;AACA;AACA,KAAK,CAAC,WAAW,GAAG,WAAW,CAAC;AAChC;AACA,KAAK,CAAC,YAAY,GAAGL,cAAY,CAAC;AAClC;AACA,KAAK,CAAC,UAAU,GAAG,KAAK,IAAI,cAAc,CAACR,OAAK,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,IAAI,QAAQ,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC;AAClG;AACA,KAAK,CAAC,UAAU,GAAG,QAAQ,CAAC,UAAU,CAAC;AACvC;AACA,KAAK,CAAC,cAAc,GAAGc,gBAAc,CAAC;AACtC;AACA,KAAK,CAAC,OAAO,GAAG,KAAK;;;;"} \ No newline at end of file diff --git a/node_modules/axios/dist/esm/axios.js b/node_modules/axios/dist/esm/axios.js new file mode 100644 index 000000000..1bc318dce --- /dev/null +++ b/node_modules/axios/dist/esm/axios.js @@ -0,0 +1,3745 @@ +// Axios v1.7.9 Copyright (c) 2024 Matt Zabriskie and contributors +function bind(fn, thisArg) { + return function wrap() { + return fn.apply(thisArg, arguments); + }; +} + +// utils is a library of generic helper functions non-specific to axios + +const {toString} = Object.prototype; +const {getPrototypeOf} = Object; + +const kindOf = (cache => thing => { + const str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); +})(Object.create(null)); + +const kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type +}; + +const typeOfTest = type => thing => typeof thing === type; + +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * + * @returns {boolean} True if value is an Array, otherwise false + */ +const {isArray} = Array; + +/** + * Determine if a value is undefined + * + * @param {*} val The value to test + * + * @returns {boolean} True if the value is undefined, otherwise false + */ +const isUndefined = typeOfTest('undefined'); + +/** + * Determine if a value is a Buffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); +} + +/** + * Determine if a value is an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +const isArrayBuffer = kindOfTest('ArrayBuffer'); + + +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + let result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); + } + return result; +} + +/** + * Determine if a value is a String + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a String, otherwise false + */ +const isString = typeOfTest('string'); + +/** + * Determine if a value is a Function + * + * @param {*} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +const isFunction = typeOfTest('function'); + +/** + * Determine if a value is a Number + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Number, otherwise false + */ +const isNumber = typeOfTest('number'); + +/** + * Determine if a value is an Object + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an Object, otherwise false + */ +const isObject = (thing) => thing !== null && typeof thing === 'object'; + +/** + * Determine if a value is a Boolean + * + * @param {*} thing The value to test + * @returns {boolean} True if value is a Boolean, otherwise false + */ +const isBoolean = thing => thing === true || thing === false; + +/** + * Determine if a value is a plain Object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a plain Object, otherwise false + */ +const isPlainObject = (val) => { + if (kindOf(val) !== 'object') { + return false; + } + + const prototype = getPrototypeOf(val); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); +}; + +/** + * Determine if a value is a Date + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Date, otherwise false + */ +const isDate = kindOfTest('Date'); + +/** + * Determine if a value is a File + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFile = kindOfTest('File'); + +/** + * Determine if a value is a Blob + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Blob, otherwise false + */ +const isBlob = kindOfTest('Blob'); + +/** + * Determine if a value is a FileList + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFileList = kindOfTest('FileList'); + +/** + * Determine if a value is a Stream + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Stream, otherwise false + */ +const isStream = (val) => isObject(val) && isFunction(val.pipe); + +/** + * Determine if a value is a FormData + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an FormData, otherwise false + */ +const isFormData = (thing) => { + let kind; + return thing && ( + (typeof FormData === 'function' && thing instanceof FormData) || ( + isFunction(thing.append) && ( + (kind = kindOf(thing)) === 'formdata' || + // detect form-data instance + (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]') + ) + ) + ) +}; + +/** + * Determine if a value is a URLSearchParams object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +const isURLSearchParams = kindOfTest('URLSearchParams'); + +const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest); + +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * + * @returns {String} The String freed of excess whitespace + */ +const trim = (str) => str.trim ? + str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + * + * @param {Boolean} [allOwnKeys = false] + * @returns {any} + */ +function forEach(obj, fn, {allOwnKeys = false} = {}) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + let i; + let l; + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; + + for (i = 0; i < len; i++) { + key = keys[i]; + fn.call(null, obj[key], key, obj); + } + } +} + +function findKey(obj, key) { + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; +} + +const _global = (() => { + /*eslint no-undef:0*/ + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global) +})(); + +const isContextDefined = (context) => !isUndefined(context) && context !== _global; + +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + const {caseless} = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + }; + + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); + } + return result; +} + +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * + * @param {Boolean} [allOwnKeys] + * @returns {Object} The resulting value of object a + */ +const extend = (a, b, thisArg, {allOwnKeys}= {}) => { + forEach(b, (val, key) => { + if (thisArg && isFunction(val)) { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }, {allOwnKeys}); + return a; +}; + +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * + * @returns {string} content value without BOM + */ +const stripBOM = (content) => { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +}; + +/** + * Inherit the prototype methods from one constructor into another + * @param {function} constructor + * @param {function} superConstructor + * @param {object} [props] + * @param {object} [descriptors] + * + * @returns {void} + */ +const inherits = (constructor, superConstructor, props, descriptors) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, 'super', { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); +}; + +/** + * Resolve object with deep prototype chain to a flat object + * @param {Object} sourceObj source object + * @param {Object} [destObj] + * @param {Function|Boolean} [filter] + * @param {Function} [propFilter] + * + * @returns {Object} + */ +const toFlatObject = (sourceObj, destObj, filter, propFilter) => { + let props; + let i; + let prop; + const merged = {}; + + destObj = destObj || {}; + // eslint-disable-next-line no-eq-null,eqeqeq + if (sourceObj == null) return destObj; + + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + + return destObj; +}; + +/** + * Determines whether a string ends with the characters of a specified string + * + * @param {String} str + * @param {String} searchString + * @param {Number} [position= 0] + * + * @returns {boolean} + */ +const endsWith = (str, searchString, position) => { + str = String(str); + if (position === undefined || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; +}; + + +/** + * Returns new array from array like object or null if failed + * + * @param {*} [thing] + * + * @returns {?Array} + */ +const toArray = (thing) => { + if (!thing) return null; + if (isArray(thing)) return thing; + let i = thing.length; + if (!isNumber(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; +}; + +/** + * Checking if the Uint8Array exists and if it does, it returns a function that checks if the + * thing passed in is an instance of Uint8Array + * + * @param {TypedArray} + * + * @returns {Array} + */ +// eslint-disable-next-line func-names +const isTypedArray = (TypedArray => { + // eslint-disable-next-line func-names + return thing => { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); + +/** + * For each entry in the object, call the function with the key and value. + * + * @param {Object} obj - The object to iterate over. + * @param {Function} fn - The function to call for each entry. + * + * @returns {void} + */ +const forEachEntry = (obj, fn) => { + const generator = obj && obj[Symbol.iterator]; + + const iterator = generator.call(obj); + + let result; + + while ((result = iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); + } +}; + +/** + * It takes a regular expression and a string, and returns an array of all the matches + * + * @param {string} regExp - The regular expression to match against. + * @param {string} str - The string to search. + * + * @returns {Array} + */ +const matchAll = (regExp, str) => { + let matches; + const arr = []; + + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + + return arr; +}; + +/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ +const isHTMLForm = kindOfTest('HTMLFormElement'); + +const toCamelCase = str => { + return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, + function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; + } + ); +}; + +/* Creating a function that will check if an object has a property. */ +const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); + +/** + * Determine if a value is a RegExp object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a RegExp object, otherwise false + */ +const isRegExp = kindOfTest('RegExp'); + +const reduceDescriptors = (obj, reducer) => { + const descriptors = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + + forEach(descriptors, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); + + Object.defineProperties(obj, reducedDescriptors); +}; + +/** + * Makes all methods read-only + * @param {Object} obj + */ + +const freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name) => { + // skip restricted props in strict mode + if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { + return false; + } + + const value = obj[name]; + + if (!isFunction(value)) return; + + descriptor.enumerable = false; + + if ('writable' in descriptor) { + descriptor.writable = false; + return; + } + + if (!descriptor.set) { + descriptor.set = () => { + throw Error('Can not rewrite read-only method \'' + name + '\''); + }; + } + }); +}; + +const toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; + + const define = (arr) => { + arr.forEach(value => { + obj[value] = true; + }); + }; + + isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + + return obj; +}; + +const noop = () => {}; + +const toFiniteNumber = (value, defaultValue) => { + return value != null && Number.isFinite(value = +value) ? value : defaultValue; +}; + +const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; + +const DIGIT = '0123456789'; + +const ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT +}; + +const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { + let str = ''; + const {length} = alphabet; + while (size--) { + str += alphabet[Math.random() * length|0]; + } + + return str; +}; + +/** + * If the thing is a FormData object, return true, otherwise return false. + * + * @param {unknown} thing - The thing to check. + * + * @returns {boolean} + */ +function isSpecCompliantForm(thing) { + return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]); +} + +const toJSONObject = (obj) => { + const stack = new Array(10); + + const visit = (source, i) => { + + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + + if(!('toJSON' in source)) { + stack[i] = source; + const target = isArray(source) ? [] : {}; + + forEach(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + + stack[i] = undefined; + + return target; + } + } + + return source; + }; + + return visit(obj, 0); +}; + +const isAsyncFn = kindOfTest('AsyncFunction'); + +const isThenable = (thing) => + thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); + +// original code +// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 + +const _setImmediate = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; + } + + return postMessageSupported ? ((token, callbacks) => { + _global.addEventListener("message", ({source, data}) => { + if (source === _global && data === token) { + callbacks.length && callbacks.shift()(); + } + }, false); + + return (cb) => { + callbacks.push(cb); + _global.postMessage(token, "*"); + } + })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); +})( + typeof setImmediate === 'function', + isFunction(_global.postMessage) +); + +const asap = typeof queueMicrotask !== 'undefined' ? + queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate); + +// ********************* + +const utils$1 = { + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString, + isNumber, + isBoolean, + isObject, + isPlainObject, + isReadableStream, + isRequest, + isResponse, + isHeaders, + isUndefined, + isDate, + isFile, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty, + hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + ALPHABET, + generateString, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable, + setImmediate: _setImmediate, + asap +}; + +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [config] The config. + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * + * @returns {Error} The created error. + */ +function AxiosError$1(message, code, config, request, response) { + Error.call(this); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = (new Error()).stack; + } + + this.message = message; + this.name = 'AxiosError'; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status ? response.status : null; + } +} + +utils$1.inherits(AxiosError$1, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils$1.toJSONObject(this.config), + code: this.code, + status: this.status + }; + } +}); + +const prototype$1 = AxiosError$1.prototype; +const descriptors = {}; + +[ + 'ERR_BAD_OPTION_VALUE', + 'ERR_BAD_OPTION', + 'ECONNABORTED', + 'ETIMEDOUT', + 'ERR_NETWORK', + 'ERR_FR_TOO_MANY_REDIRECTS', + 'ERR_DEPRECATED', + 'ERR_BAD_RESPONSE', + 'ERR_BAD_REQUEST', + 'ERR_CANCELED', + 'ERR_NOT_SUPPORT', + 'ERR_INVALID_URL' +// eslint-disable-next-line func-names +].forEach(code => { + descriptors[code] = {value: code}; +}); + +Object.defineProperties(AxiosError$1, descriptors); +Object.defineProperty(prototype$1, 'isAxiosError', {value: true}); + +// eslint-disable-next-line func-names +AxiosError$1.from = (error, code, config, request, response, customProps) => { + const axiosError = Object.create(prototype$1); + + utils$1.toFlatObject(error, axiosError, function filter(obj) { + return obj !== Error.prototype; + }, prop => { + return prop !== 'isAxiosError'; + }); + + AxiosError$1.call(axiosError, error.message, code, config, request, response); + + axiosError.cause = error; + + axiosError.name = error.name; + + customProps && Object.assign(axiosError, customProps); + + return axiosError; +}; + +// eslint-disable-next-line strict +const httpAdapter = null; + +/** + * Determines if the given thing is a array or js object. + * + * @param {string} thing - The object or array to be visited. + * + * @returns {boolean} + */ +function isVisitable(thing) { + return utils$1.isPlainObject(thing) || utils$1.isArray(thing); +} + +/** + * It removes the brackets from the end of a string + * + * @param {string} key - The key of the parameter. + * + * @returns {string} the key without the brackets. + */ +function removeBrackets(key) { + return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key; +} + +/** + * It takes a path, a key, and a boolean, and returns a string + * + * @param {string} path - The path to the current key. + * @param {string} key - The key of the current object being iterated over. + * @param {string} dots - If true, the key will be rendered with dots instead of brackets. + * + * @returns {string} The path to the current key. + */ +function renderKey(path, key, dots) { + if (!path) return key; + return path.concat(key).map(function each(token, i) { + // eslint-disable-next-line no-param-reassign + token = removeBrackets(token); + return !dots && i ? '[' + token + ']' : token; + }).join(dots ? '.' : ''); +} + +/** + * If the array is an array and none of its elements are visitable, then it's a flat array. + * + * @param {Array} arr - The array to check + * + * @returns {boolean} + */ +function isFlatArray(arr) { + return utils$1.isArray(arr) && !arr.some(isVisitable); +} + +const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); +}); + +/** + * Convert a data object to FormData + * + * @param {Object} obj + * @param {?Object} [formData] + * @param {?Object} [options] + * @param {Function} [options.visitor] + * @param {Boolean} [options.metaTokens = true] + * @param {Boolean} [options.dots = false] + * @param {?Boolean} [options.indexes = false] + * + * @returns {Object} + **/ + +/** + * It converts an object into a FormData object + * + * @param {Object} obj - The object to convert to form data. + * @param {string} formData - The FormData object to append to. + * @param {Object} options + * + * @returns + */ +function toFormData$1(obj, formData, options) { + if (!utils$1.isObject(obj)) { + throw new TypeError('target must be an object'); + } + + // eslint-disable-next-line no-param-reassign + formData = formData || new (FormData)(); + + // eslint-disable-next-line no-param-reassign + options = utils$1.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + // eslint-disable-next-line no-eq-null,eqeqeq + return !utils$1.isUndefined(source[option]); + }); + + const metaTokens = options.metaTokens; + // eslint-disable-next-line no-use-before-define + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; + const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + + if (!utils$1.isFunction(visitor)) { + throw new TypeError('visitor must be a function'); + } + + function convertValue(value) { + if (value === null) return ''; + + if (utils$1.isDate(value)) { + return value.toISOString(); + } + + if (!useBlob && utils$1.isBlob(value)) { + throw new AxiosError$1('Blob is not supported. Use a Buffer instead.'); + } + + if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { + return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + } + + return value; + } + + /** + * Default visitor. + * + * @param {*} value + * @param {String|Number} key + * @param {Array} path + * @this {FormData} + * + * @returns {boolean} return true to visit the each prop of the value recursively + */ + function defaultVisitor(value, key, path) { + let arr = value; + + if (value && !path && typeof value === 'object') { + if (utils$1.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign + key = metaTokens ? key : key.slice(0, -2); + // eslint-disable-next-line no-param-reassign + value = JSON.stringify(value); + } else if ( + (utils$1.isArray(value) && isFlatArray(value)) || + ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)) + )) { + // eslint-disable-next-line no-param-reassign + key = removeBrackets(key); + + arr.forEach(function each(el, index) { + !(utils$1.isUndefined(el) || el === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), + convertValue(el) + ); + }); + return false; + } + } + + if (isVisitable(value)) { + return true; + } + + formData.append(renderKey(path, key, dots), convertValue(value)); + + return false; + } + + const stack = []; + + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable + }); + + function build(value, path) { + if (utils$1.isUndefined(value)) return; + + if (stack.indexOf(value) !== -1) { + throw Error('Circular reference detected in ' + path.join('.')); + } + + stack.push(value); + + utils$1.forEach(value, function each(el, key) { + const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( + formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers + ); + + if (result === true) { + build(el, path ? path.concat(key) : [key]); + } + }); + + stack.pop(); + } + + if (!utils$1.isObject(obj)) { + throw new TypeError('data must be an object'); + } + + build(obj); + + return formData; +} + +/** + * It encodes a string by replacing all characters that are not in the unreserved set with + * their percent-encoded equivalents + * + * @param {string} str - The string to encode. + * + * @returns {string} The encoded string. + */ +function encode$1(str) { + const charMap = { + '!': '%21', + "'": '%27', + '(': '%28', + ')': '%29', + '~': '%7E', + '%20': '+', + '%00': '\x00' + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); +} + +/** + * It takes a params object and converts it to a FormData object + * + * @param {Object} params - The parameters to be converted to a FormData object. + * @param {Object} options - The options object passed to the Axios constructor. + * + * @returns {void} + */ +function AxiosURLSearchParams(params, options) { + this._pairs = []; + + params && toFormData$1(params, this, options); +} + +const prototype = AxiosURLSearchParams.prototype; + +prototype.append = function append(name, value) { + this._pairs.push([name, value]); +}; + +prototype.toString = function toString(encoder) { + const _encode = encoder ? function(value) { + return encoder.call(this, value, encode$1); + } : encode$1; + + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + '=' + _encode(pair[1]); + }, '').join('&'); +}; + +/** + * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their + * URI encoded counterparts + * + * @param {string} val The value to be encoded. + * + * @returns {string} The encoded value. + */ +function encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} + +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @param {?(object|Function)} options + * + * @returns {string} The formatted url + */ +function buildURL(url, params, options) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + + const _encode = options && options.encode || encode; + + if (utils$1.isFunction(options)) { + options = { + serialize: options + }; + } + + const serializeFn = options && options.serialize; + + let serializedParams; + + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils$1.isURLSearchParams(params) ? + params.toString() : + new AxiosURLSearchParams(params, options).toString(_encode); + } + + if (serializedParams) { + const hashmarkIndex = url.indexOf("#"); + + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + + return url; +} + +class InterceptorManager { + constructor() { + this.handlers = []; + } + + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + */ + eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; + } + } + + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn) { + utils$1.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + } +} + +const InterceptorManager$1 = InterceptorManager; + +const transitionalDefaults = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false +}; + +const URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams; + +const FormData$1 = typeof FormData !== 'undefined' ? FormData : null; + +const Blob$1 = typeof Blob !== 'undefined' ? Blob : null; + +const platform$1 = { + isBrowser: true, + classes: { + URLSearchParams: URLSearchParams$1, + FormData: FormData$1, + Blob: Blob$1 + }, + protocols: ['http', 'https', 'file', 'blob', 'url', 'data'] +}; + +const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; + +const _navigator = typeof navigator === 'object' && navigator || undefined; + +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + * + * @returns {boolean} + */ +const hasStandardBrowserEnv = hasBrowserEnv && + (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0); + +/** + * Determine if we're running in a standard browser webWorker environment + * + * Although the `isStandardBrowserEnv` method indicates that + * `allows axios to run in a web worker`, the WebWorker will still be + * filtered out due to its judgment standard + * `typeof window !== 'undefined' && typeof document !== 'undefined'`. + * This leads to a problem when axios post `FormData` in webWorker + */ +const hasStandardBrowserWebWorkerEnv = (() => { + return ( + typeof WorkerGlobalScope !== 'undefined' && + // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && + typeof self.importScripts === 'function' + ); +})(); + +const origin = hasBrowserEnv && window.location.href || 'http://localhost'; + +const utils = /*#__PURE__*/Object.freeze({ + __proto__: null, + hasBrowserEnv: hasBrowserEnv, + hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, + hasStandardBrowserEnv: hasStandardBrowserEnv, + navigator: _navigator, + origin: origin +}); + +const platform = { + ...utils, + ...platform$1 +}; + +function toURLEncodedForm(data, options) { + return toFormData$1(data, new platform.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (platform.isNode && utils$1.isBuffer(value)) { + this.append(key, value.toString('base64')); + return false; + } + + return helpers.defaultVisitor.apply(this, arguments); + } + }, options)); +} + +/** + * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z'] + * + * @param {string} name - The name of the property to get. + * + * @returns An array of strings. + */ +function parsePropPath(name) { + // foo[x][y][z] + // foo.x.y.z + // foo-x-y-z + // foo x y z + return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => { + return match[0] === '[]' ? '' : match[1] || match[0]; + }); +} + +/** + * Convert an array to an object. + * + * @param {Array} arr - The array to convert to an object. + * + * @returns An object with the same keys and values as the array. + */ +function arrayToObject(arr) { + const obj = {}; + const keys = Object.keys(arr); + let i; + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; +} + +/** + * It takes a FormData object and returns a JavaScript object + * + * @param {string} formData The FormData object to convert to JSON. + * + * @returns {Object | null} The converted object. + */ +function formDataToJSON(formData) { + function buildPath(path, value, target, index) { + let name = path[index++]; + + if (name === '__proto__') return true; + + const isNumericKey = Number.isFinite(+name); + const isLast = index >= path.length; + name = !name && utils$1.isArray(target) ? target.length : name; + + if (isLast) { + if (utils$1.hasOwnProp(target, name)) { + target[name] = [target[name], value]; + } else { + target[name] = value; + } + + return !isNumericKey; + } + + if (!target[name] || !utils$1.isObject(target[name])) { + target[name] = []; + } + + const result = buildPath(path, value, target[name], index); + + if (result && utils$1.isArray(target[name])) { + target[name] = arrayToObject(target[name]); + } + + return !isNumericKey; + } + + if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { + const obj = {}; + + utils$1.forEachEntry(formData, (name, value) => { + buildPath(parsePropPath(name), value, obj, 0); + }); + + return obj; + } + + return null; +} + +/** + * It takes a string, tries to parse it, and if it fails, it returns the stringified version + * of the input + * + * @param {any} rawValue - The value to be stringified. + * @param {Function} parser - A function that parses a string into a JavaScript object. + * @param {Function} encoder - A function that takes a value and returns a string. + * + * @returns {string} A stringified version of the rawValue. + */ +function stringifySafely(rawValue, parser, encoder) { + if (utils$1.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils$1.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } + } + } + + return (encoder || JSON.stringify)(rawValue); +} + +const defaults = { + + transitional: transitionalDefaults, + + adapter: ['xhr', 'http', 'fetch'], + + transformRequest: [function transformRequest(data, headers) { + const contentType = headers.getContentType() || ''; + const hasJSONContentType = contentType.indexOf('application/json') > -1; + const isObjectPayload = utils$1.isObject(data); + + if (isObjectPayload && utils$1.isHTMLForm(data)) { + data = new FormData(data); + } + + const isFormData = utils$1.isFormData(data); + + if (isFormData) { + return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; + } + + if (utils$1.isArrayBuffer(data) || + utils$1.isBuffer(data) || + utils$1.isStream(data) || + utils$1.isFile(data) || + utils$1.isBlob(data) || + utils$1.isReadableStream(data) + ) { + return data; + } + if (utils$1.isArrayBufferView(data)) { + return data.buffer; + } + if (utils$1.isURLSearchParams(data)) { + headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); + return data.toString(); + } + + let isFileList; + + if (isObjectPayload) { + if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + + if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { + const _FormData = this.env && this.env.FormData; + + return toFormData$1( + isFileList ? {'files[]': data} : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + + if (isObjectPayload || hasJSONContentType ) { + headers.setContentType('application/json', false); + return stringifySafely(data); + } + + return data; + }], + + transformResponse: [function transformResponse(data) { + const transitional = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional && transitional.forcedJSONParsing; + const JSONRequested = this.responseType === 'json'; + + if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) { + return data; + } + + if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { + const silentJSONParsing = transitional && transitional.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } + + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + + headers: { + common: { + 'Accept': 'application/json, text/plain, */*', + 'Content-Type': undefined + } + } +}; + +utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { + defaults.headers[method] = {}; +}); + +const defaults$1 = defaults; + +// RawAxiosHeaders whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +const ignoreDuplicateOf = utils$1.toObjectSet([ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]); + +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} rawHeaders Headers needing to be parsed + * + * @returns {Object} Headers parsed into an object + */ +const parseHeaders = rawHeaders => { + const parsed = {}; + let key; + let val; + let i; + + rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { + i = line.indexOf(':'); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + + if (!key || (parsed[key] && ignoreDuplicateOf[key])) { + return; + } + + if (key === 'set-cookie') { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + }); + + return parsed; +}; + +const $internals = Symbol('internals'); + +function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); +} + +function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + + return utils$1.isArray(value) ? value.map(normalizeValue) : String(value); +} + +function parseTokens(str) { + const tokens = Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + + while ((match = tokensRE.exec(str))) { + tokens[match[1]] = match[2]; + } + + return tokens; +} + +const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); + +function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { + if (utils$1.isFunction(filter)) { + return filter.call(this, value, header); + } + + if (isHeaderNameFilter) { + value = header; + } + + if (!utils$1.isString(value)) return; + + if (utils$1.isString(filter)) { + return value.indexOf(filter) !== -1; + } + + if (utils$1.isRegExp(filter)) { + return filter.test(value); + } +} + +function formatHeader(header) { + return header.trim() + .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { + return char.toUpperCase() + str; + }); +} + +function buildAccessors(obj, header) { + const accessorName = utils$1.toCamelCase(' ' + header); + + ['get', 'set', 'has'].forEach(methodName => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); +} + +class AxiosHeaders$1 { + constructor(headers) { + headers && this.set(headers); + } + + set(header, valueOrRewrite, rewrite) { + const self = this; + + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); + + if (!lHeader) { + throw new Error('header name must be a non-empty string'); + } + + const key = utils$1.findKey(self, lHeader); + + if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { + self[key || _header] = normalizeValue(_value); + } + } + + const setHeaders = (headers, _rewrite) => + utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + + if (utils$1.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else if (utils$1.isHeaders(header)) { + for (const [key, value] of header.entries()) { + setHeader(value, key, rewrite); + } + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + + return this; + } + + get(header, parser) { + header = normalizeHeader(header); + + if (header) { + const key = utils$1.findKey(this, header); + + if (key) { + const value = this[key]; + + if (!parser) { + return value; + } + + if (parser === true) { + return parseTokens(value); + } + + if (utils$1.isFunction(parser)) { + return parser.call(this, value, key); + } + + if (utils$1.isRegExp(parser)) { + return parser.exec(value); + } + + throw new TypeError('parser must be boolean|regexp|function'); + } + } + } + + has(header, matcher) { + header = normalizeHeader(header); + + if (header) { + const key = utils$1.findKey(this, header); + + return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + } + + return false; + } + + delete(header, matcher) { + const self = this; + let deleted = false; + + function deleteHeader(_header) { + _header = normalizeHeader(_header); + + if (_header) { + const key = utils$1.findKey(self, _header); + + if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { + delete self[key]; + + deleted = true; + } + } + } + + if (utils$1.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + + return deleted; + } + + clear(matcher) { + const keys = Object.keys(this); + let i = keys.length; + let deleted = false; + + while (i--) { + const key = keys[i]; + if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + + return deleted; + } + + normalize(format) { + const self = this; + const headers = {}; + + utils$1.forEach(this, (value, header) => { + const key = utils$1.findKey(headers, header); + + if (key) { + self[key] = normalizeValue(value); + delete self[header]; + return; + } + + const normalized = format ? formatHeader(header) : String(header).trim(); + + if (normalized !== header) { + delete self[header]; + } + + self[normalized] = normalizeValue(value); + + headers[normalized] = true; + }); + + return this; + } + + concat(...targets) { + return this.constructor.concat(this, ...targets); + } + + toJSON(asStrings) { + const obj = Object.create(null); + + utils$1.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value); + }); + + return obj; + } + + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n'); + } + + get [Symbol.toStringTag]() { + return 'AxiosHeaders'; + } + + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + + static concat(first, ...targets) { + const computed = new this(first); + + targets.forEach((target) => computed.set(target)); + + return computed; + } + + static accessor(header) { + const internals = this[$internals] = (this[$internals] = { + accessors: {} + }); + + const accessors = internals.accessors; + const prototype = this.prototype; + + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); + + if (!accessors[lHeader]) { + buildAccessors(prototype, _header); + accessors[lHeader] = true; + } + } + + utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + + return this; + } +} + +AxiosHeaders$1.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); + +// reserved names hotfix +utils$1.reduceDescriptors(AxiosHeaders$1.prototype, ({value}, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } + } +}); + +utils$1.freezeMethods(AxiosHeaders$1); + +const AxiosHeaders$2 = AxiosHeaders$1; + +/** + * Transform the data for a request or a response + * + * @param {Array|Function} fns A single function or Array of functions + * @param {?Object} response The response object + * + * @returns {*} The resulting transformed data + */ +function transformData(fns, response) { + const config = this || defaults$1; + const context = response || config; + const headers = AxiosHeaders$2.from(context.headers); + let data = context.data; + + utils$1.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); + }); + + headers.normalize(); + + return data; +} + +function isCancel$1(value) { + return !!(value && value.__CANCEL__); +} + +/** + * A `CanceledError` is an object that is thrown when an operation is canceled. + * + * @param {string=} message The message. + * @param {Object=} config The config. + * @param {Object=} request The request. + * + * @returns {CanceledError} The created error. + */ +function CanceledError$1(message, config, request) { + // eslint-disable-next-line no-eq-null,eqeqeq + AxiosError$1.call(this, message == null ? 'canceled' : message, AxiosError$1.ERR_CANCELED, config, request); + this.name = 'CanceledError'; +} + +utils$1.inherits(CanceledError$1, AxiosError$1, { + __CANCEL__: true +}); + +/** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + * + * @returns {object} The response. + */ +function settle(resolve, reject, response) { + const validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new AxiosError$1( + 'Request failed with status code ' + response.status, + [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } +} + +function parseProtocol(url) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ''; +} + +/** + * Calculate data maxRate + * @param {Number} [samplesCount= 10] + * @param {Number} [min= 1000] + * @returns {Function} + */ +function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + + min = min !== undefined ? min : 1000; + + return function push(chunkLength) { + const now = Date.now(); + + const startedAt = timestamps[tail]; + + if (!firstSampleTS) { + firstSampleTS = now; + } + + bytes[head] = chunkLength; + timestamps[head] = now; + + let i = tail; + let bytesCount = 0; + + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + + head = (head + 1) % samplesCount; + + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + + if (now - firstSampleTS < min) { + return; + } + + const passed = startedAt && now - startedAt; + + return passed ? Math.round(bytesCount * 1000 / passed) : undefined; + }; +} + +/** + * Throttle decorator + * @param {Function} fn + * @param {Number} freq + * @return {Function} + */ +function throttle(fn, freq) { + let timestamp = 0; + let threshold = 1000 / freq; + let lastArgs; + let timer; + + const invoke = (args, now = Date.now()) => { + timestamp = now; + lastArgs = null; + if (timer) { + clearTimeout(timer); + timer = null; + } + fn.apply(null, args); + }; + + const throttled = (...args) => { + const now = Date.now(); + const passed = now - timestamp; + if ( passed >= threshold) { + invoke(args, now); + } else { + lastArgs = args; + if (!timer) { + timer = setTimeout(() => { + timer = null; + invoke(lastArgs); + }, threshold - passed); + } + } + }; + + const flush = () => lastArgs && invoke(lastArgs); + + return [throttled, flush]; +} + +const progressEventReducer = (listener, isDownloadStream, freq = 3) => { + let bytesNotified = 0; + const _speedometer = speedometer(50, 250); + + return throttle(e => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : undefined; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange = loaded <= total; + + bytesNotified = loaded; + + const data = { + loaded, + total, + progress: total ? (loaded / total) : undefined, + bytes: progressBytes, + rate: rate ? rate : undefined, + estimated: rate && total && inRange ? (total - loaded) / rate : undefined, + event: e, + lengthComputable: total != null, + [isDownloadStream ? 'download' : 'upload']: true + }; + + listener(data); + }, freq); +}; + +const progressEventDecorator = (total, throttled) => { + const lengthComputable = total != null; + + return [(loaded) => throttled[0]({ + lengthComputable, + total, + loaded + }), throttled[1]]; +}; + +const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args)); + +const isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => { + url = new URL(url, platform.origin); + + return ( + origin.protocol === url.protocol && + origin.host === url.host && + (isMSIE || origin.port === url.port) + ); +})( + new URL(platform.origin), + platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) +) : () => true; + +const cookies = platform.hasStandardBrowserEnv ? + + // Standard browser envs support document.cookie + { + write(name, value, expires, path, domain, secure) { + const cookie = [name + '=' + encodeURIComponent(value)]; + + utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString()); + + utils$1.isString(path) && cookie.push('path=' + path); + + utils$1.isString(domain) && cookie.push('domain=' + domain); + + secure === true && cookie.push('secure'); + + document.cookie = cookie.join('; '); + }, + + read(name) { + const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, + + remove(name) { + this.write(name, '', Date.now() - 86400000); + } + } + + : + + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() {}, + read() { + return null; + }, + remove() {} + }; + +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); +} + +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * + * @returns {string} The combined URL + */ +function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +} + +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * + * @returns {string} The combined full path + */ +function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +} + +const headersToObject = (thing) => thing instanceof AxiosHeaders$2 ? { ...thing } : thing; + +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * + * @returns {Object} New object resulting from merging config2 to config1 + */ +function mergeConfig$1(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + const config = {}; + + function getMergedValue(target, source, prop, caseless) { + if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { + return utils$1.merge.call({caseless}, target, source); + } else if (utils$1.isPlainObject(source)) { + return utils$1.merge({}, source); + } else if (utils$1.isArray(source)) { + return source.slice(); + } + return source; + } + + // eslint-disable-next-line consistent-return + function mergeDeepProperties(a, b, prop , caseless) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(a, b, prop , caseless); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(undefined, a, prop , caseless); + } + } + + // eslint-disable-next-line consistent-return + function valueFromConfig2(a, b) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(undefined, b); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(a, b) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(undefined, b); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(undefined, a); + } + } + + // eslint-disable-next-line consistent-return + function mergeDirectKeys(a, b, prop) { + if (prop in config2) { + return getMergedValue(a, b); + } else if (prop in config1) { + return getMergedValue(undefined, a); + } + } + + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true) + }; + + utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + const merge = mergeMap[prop] || mergeDeepProperties; + const configValue = merge(config1[prop], config2[prop], prop); + (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); + + return config; +} + +const resolveConfig = (config) => { + const newConfig = mergeConfig$1({}, config); + + let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig; + + newConfig.headers = headers = AxiosHeaders$2.from(headers); + + newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer); + + // HTTP basic authentication + if (auth) { + headers.set('Authorization', 'Basic ' + + btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : '')) + ); + } + + let contentType; + + if (utils$1.isFormData(data)) { + if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { + headers.setContentType(undefined); // Let the browser set it + } else if ((contentType = headers.getContentType()) !== false) { + // fix semicolon duplication issue for ReactNative FormData implementation + const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : []; + headers.setContentType([type || 'multipart/form-data', ...tokens].join('; ')); + } + } + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + + if (platform.hasStandardBrowserEnv) { + withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); + + if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) { + // Add xsrf header + const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); + + if (xsrfValue) { + headers.set(xsrfHeaderName, xsrfValue); + } + } + } + + return newConfig; +}; + +const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; + +const xhrAdapter = isXHRAdapterSupported && function (config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + const _config = resolveConfig(config); + let requestData = _config.data; + const requestHeaders = AxiosHeaders$2.from(_config.headers).normalize(); + let {responseType, onUploadProgress, onDownloadProgress} = _config; + let onCanceled; + let uploadThrottled, downloadThrottled; + let flushUpload, flushDownload; + + function done() { + flushUpload && flushUpload(); // flush events + flushDownload && flushDownload(); // flush events + + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + + _config.signal && _config.signal.removeEventListener('abort', onCanceled); + } + + let request = new XMLHttpRequest(); + + request.open(_config.method.toUpperCase(), _config.url, true); + + // Set the request timeout in MS + request.timeout = _config.timeout; + + function onloadend() { + if (!request) { + return; + } + // Prepare the response + const responseHeaders = AxiosHeaders$2.from( + 'getAllResponseHeaders' in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === 'text' || responseType === 'json' ? + request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config, + request + }; + + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + + // Clean up request + request = null; + } + + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(new AxiosError$1('Request aborted', AxiosError$1.ECONNABORTED, config, request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded'; + const transitional = _config.transitional || transitionalDefaults; + if (_config.timeoutErrorMessage) { + timeoutErrorMessage = _config.timeoutErrorMessage; + } + reject(new AxiosError$1( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED, + config, + request)); + + // Clean up request + request = null; + }; + + // Remove Content-Type if data is undefined + requestData === undefined && requestHeaders.setContentType(null); + + // Add headers to the request + if ('setRequestHeader' in request) { + utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + + // Add withCredentials to request if needed + if (!utils$1.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; + } + + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = _config.responseType; + } + + // Handle progress if needed + if (onDownloadProgress) { + ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true)); + request.addEventListener('progress', downloadThrottled); + } + + // Not all browsers support upload events + if (onUploadProgress && request.upload) { + ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress)); + + request.upload.addEventListener('progress', uploadThrottled); + + request.upload.addEventListener('loadend', flushUpload); + } + + if (_config.cancelToken || _config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = cancel => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError$1(null, config, request) : cancel); + request.abort(); + request = null; + }; + + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled); + } + } + + const protocol = parseProtocol(_config.url); + + if (protocol && platform.protocols.indexOf(protocol) === -1) { + reject(new AxiosError$1('Unsupported protocol ' + protocol + ':', AxiosError$1.ERR_BAD_REQUEST, config)); + return; + } + + + // Send the request + request.send(requestData || null); + }); +}; + +const composeSignals = (signals, timeout) => { + const {length} = (signals = signals ? signals.filter(Boolean) : []); + + if (timeout || length) { + let controller = new AbortController(); + + let aborted; + + const onabort = function (reason) { + if (!aborted) { + aborted = true; + unsubscribe(); + const err = reason instanceof Error ? reason : this.reason; + controller.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err)); + } + }; + + let timer = timeout && setTimeout(() => { + timer = null; + onabort(new AxiosError$1(`timeout ${timeout} of ms exceeded`, AxiosError$1.ETIMEDOUT)); + }, timeout); + + const unsubscribe = () => { + if (signals) { + timer && clearTimeout(timer); + timer = null; + signals.forEach(signal => { + signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort); + }); + signals = null; + } + }; + + signals.forEach((signal) => signal.addEventListener('abort', onabort)); + + const {signal} = controller; + + signal.unsubscribe = () => utils$1.asap(unsubscribe); + + return signal; + } +}; + +const composeSignals$1 = composeSignals; + +const streamChunk = function* (chunk, chunkSize) { + let len = chunk.byteLength; + + if (!chunkSize || len < chunkSize) { + yield chunk; + return; + } + + let pos = 0; + let end; + + while (pos < len) { + end = pos + chunkSize; + yield chunk.slice(pos, end); + pos = end; + } +}; + +const readBytes = async function* (iterable, chunkSize) { + for await (const chunk of readStream(iterable)) { + yield* streamChunk(chunk, chunkSize); + } +}; + +const readStream = async function* (stream) { + if (stream[Symbol.asyncIterator]) { + yield* stream; + return; + } + + const reader = stream.getReader(); + try { + for (;;) { + const {done, value} = await reader.read(); + if (done) { + break; + } + yield value; + } + } finally { + await reader.cancel(); + } +}; + +const trackStream = (stream, chunkSize, onProgress, onFinish) => { + const iterator = readBytes(stream, chunkSize); + + let bytes = 0; + let done; + let _onFinish = (e) => { + if (!done) { + done = true; + onFinish && onFinish(e); + } + }; + + return new ReadableStream({ + async pull(controller) { + try { + const {done, value} = await iterator.next(); + + if (done) { + _onFinish(); + controller.close(); + return; + } + + let len = value.byteLength; + if (onProgress) { + let loadedBytes = bytes += len; + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); + } catch (err) { + _onFinish(err); + throw err; + } + }, + cancel(reason) { + _onFinish(reason); + return iterator.return(); + } + }, { + highWaterMark: 2 + }) +}; + +const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function'; +const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function'; + +// used only inside the fetch adapter +const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? + ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : + async (str) => new Uint8Array(await new Response(str).arrayBuffer()) +); + +const test = (fn, ...args) => { + try { + return !!fn(...args); + } catch (e) { + return false + } +}; + +const supportsRequestStream = isReadableStreamSupported && test(() => { + let duplexAccessed = false; + + const hasContentType = new Request(platform.origin, { + body: new ReadableStream(), + method: 'POST', + get duplex() { + duplexAccessed = true; + return 'half'; + }, + }).headers.has('Content-Type'); + + return duplexAccessed && !hasContentType; +}); + +const DEFAULT_CHUNK_SIZE = 64 * 1024; + +const supportsResponseStream = isReadableStreamSupported && + test(() => utils$1.isReadableStream(new Response('').body)); + + +const resolvers = { + stream: supportsResponseStream && ((res) => res.body) +}; + +isFetchSupported && (((res) => { + ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => { + !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() : + (_, config) => { + throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config); + }); + }); +})(new Response)); + +const getBodyLength = async (body) => { + if (body == null) { + return 0; + } + + if(utils$1.isBlob(body)) { + return body.size; + } + + if(utils$1.isSpecCompliantForm(body)) { + const _request = new Request(platform.origin, { + method: 'POST', + body, + }); + return (await _request.arrayBuffer()).byteLength; + } + + if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) { + return body.byteLength; + } + + if(utils$1.isURLSearchParams(body)) { + body = body + ''; + } + + if(utils$1.isString(body)) { + return (await encodeText(body)).byteLength; + } +}; + +const resolveBodyLength = async (headers, body) => { + const length = utils$1.toFiniteNumber(headers.getContentLength()); + + return length == null ? getBodyLength(body) : length; +}; + +const fetchAdapter = isFetchSupported && (async (config) => { + let { + url, + method, + data, + signal, + cancelToken, + timeout, + onDownloadProgress, + onUploadProgress, + responseType, + headers, + withCredentials = 'same-origin', + fetchOptions + } = resolveConfig(config); + + responseType = responseType ? (responseType + '').toLowerCase() : 'text'; + + let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + + let request; + + const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { + composedSignal.unsubscribe(); + }); + + let requestContentLength; + + try { + if ( + onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && + (requestContentLength = await resolveBodyLength(headers, data)) !== 0 + ) { + let _request = new Request(url, { + method: 'POST', + body: data, + duplex: "half" + }); + + let contentTypeHeader; + + if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { + headers.setContentType(contentTypeHeader); + } + + if (_request.body) { + const [onProgress, flush] = progressEventDecorator( + requestContentLength, + progressEventReducer(asyncDecorator(onUploadProgress)) + ); + + data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); + } + } + + if (!utils$1.isString(withCredentials)) { + withCredentials = withCredentials ? 'include' : 'omit'; + } + + // Cloudflare Workers throws when credentials are defined + // see https://github.com/cloudflare/workerd/issues/902 + const isCredentialsSupported = "credentials" in Request.prototype; + request = new Request(url, { + ...fetchOptions, + signal: composedSignal, + method: method.toUpperCase(), + headers: headers.normalize().toJSON(), + body: data, + duplex: "half", + credentials: isCredentialsSupported ? withCredentials : undefined + }); + + let response = await fetch(request); + + const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); + + if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) { + const options = {}; + + ['status', 'statusText', 'headers'].forEach(prop => { + options[prop] = response[prop]; + }); + + const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length')); + + const [onProgress, flush] = onDownloadProgress && progressEventDecorator( + responseContentLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true) + ) || []; + + response = new Response( + trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { + flush && flush(); + unsubscribe && unsubscribe(); + }), + options + ); + } + + responseType = responseType || 'text'; + + let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config); + + !isStreamResponse && unsubscribe && unsubscribe(); + + return await new Promise((resolve, reject) => { + settle(resolve, reject, { + data: responseData, + headers: AxiosHeaders$2.from(response.headers), + status: response.status, + statusText: response.statusText, + config, + request + }); + }) + } catch (err) { + unsubscribe && unsubscribe(); + + if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) { + throw Object.assign( + new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request), + { + cause: err.cause || err + } + ) + } + + throw AxiosError$1.from(err, err && err.code, config, request); + } +}); + +const knownAdapters = { + http: httpAdapter, + xhr: xhrAdapter, + fetch: fetchAdapter +}; + +utils$1.forEach(knownAdapters, (fn, value) => { + if (fn) { + try { + Object.defineProperty(fn, 'name', {value}); + } catch (e) { + // eslint-disable-next-line no-empty + } + Object.defineProperty(fn, 'adapterName', {value}); + } +}); + +const renderReason = (reason) => `- ${reason}`; + +const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; + +const adapters = { + getAdapter: (adapters) => { + adapters = utils$1.isArray(adapters) ? adapters : [adapters]; + + const {length} = adapters; + let nameOrAdapter; + let adapter; + + const rejectedReasons = {}; + + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters[i]; + let id; + + adapter = nameOrAdapter; + + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + + if (adapter === undefined) { + throw new AxiosError$1(`Unknown adapter '${id}'`); + } + } + + if (adapter) { + break; + } + + rejectedReasons[id || '#' + i] = adapter; + } + + if (!adapter) { + + const reasons = Object.entries(rejectedReasons) + .map(([id, state]) => `adapter ${id} ` + + (state === false ? 'is not supported by the environment' : 'is not available in the build') + ); + + let s = length ? + (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : + 'as no adapter specified'; + + throw new AxiosError$1( + `There is no suitable adapter to dispatch the request ` + s, + 'ERR_NOT_SUPPORT' + ); + } + + return adapter; + }, + adapters: knownAdapters +}; + +/** + * Throws a `CanceledError` if cancellation has been requested. + * + * @param {Object} config The config that is to be used for the request + * + * @returns {void} + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + + if (config.signal && config.signal.aborted) { + throw new CanceledError$1(null, config); + } +} + +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * + * @returns {Promise} The Promise to be fulfilled + */ +function dispatchRequest(config) { + throwIfCancellationRequested(config); + + config.headers = AxiosHeaders$2.from(config.headers); + + // Transform request data + config.data = transformData.call( + config, + config.transformRequest + ); + + if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { + config.headers.setContentType('application/x-www-form-urlencoded', false); + } + + const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData.call( + config, + config.transformResponse, + response + ); + + response.headers = AxiosHeaders$2.from(response.headers); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel$1(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + config.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders$2.from(reason.response.headers); + } + } + + return Promise.reject(reason); + }); +} + +const VERSION$1 = "1.7.9"; + +const validators$1 = {}; + +// eslint-disable-next-line func-names +['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => { + validators$1[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; +}); + +const deprecatedWarnings = {}; + +/** + * Transitional option validator + * + * @param {function|boolean?} validator - set to false if the transitional option has been removed + * @param {string?} version - deprecated version / removed since version + * @param {string?} message - some message with additional info + * + * @returns {function} + */ +validators$1.transitional = function transitional(validator, version, message) { + function formatMessage(opt, desc) { + return '[Axios v' + VERSION$1 + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + } + + // eslint-disable-next-line func-names + return (value, opt, opts) => { + if (validator === false) { + throw new AxiosError$1( + formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), + AxiosError$1.ERR_DEPRECATED + ); + } + + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); + } + + return validator ? validator(value, opt, opts) : true; + }; +}; + +validators$1.spelling = function spelling(correctSpelling) { + return (value, opt) => { + // eslint-disable-next-line no-console + console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); + return true; + } +}; + +/** + * Assert object's properties type + * + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown + * + * @returns {object} + */ + +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== 'object') { + throw new AxiosError$1('options must be an object', AxiosError$1.ERR_BAD_OPTION_VALUE); + } + const keys = Object.keys(options); + let i = keys.length; + while (i-- > 0) { + const opt = keys[i]; + const validator = schema[opt]; + if (validator) { + const value = options[opt]; + const result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new AxiosError$1('option ' + opt + ' must be ' + result, AxiosError$1.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError$1('Unknown option ' + opt, AxiosError$1.ERR_BAD_OPTION); + } + } +} + +const validator = { + assertOptions, + validators: validators$1 +}; + +const validators = validator.validators; + +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + * + * @return {Axios} A new instance of Axios + */ +class Axios$1 { + constructor(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager$1(), + response: new InterceptorManager$1() + }; + } + + /** + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled + */ + async request(configOrUrl, config) { + try { + return await this._request(configOrUrl, config); + } catch (err) { + if (err instanceof Error) { + let dummy = {}; + + Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error()); + + // slice off the Error: ... line + const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : ''; + try { + if (!err.stack) { + err.stack = stack; + // match without the 2 top stack lines + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) { + err.stack += '\n' + stack; + } + } catch (e) { + // ignore the case where "stack" is an un-writable property + } + } + + throw err; + } + } + + _request(configOrUrl, config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof configOrUrl === 'string') { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } + + config = mergeConfig$1(this.defaults, config); + + const {transitional, paramsSerializer, headers} = config; + + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators.boolean), + forcedJSONParsing: validators.transitional(validators.boolean), + clarifyTimeoutError: validators.transitional(validators.boolean) + }, false); + } + + if (paramsSerializer != null) { + if (utils$1.isFunction(paramsSerializer)) { + config.paramsSerializer = { + serialize: paramsSerializer + }; + } else { + validator.assertOptions(paramsSerializer, { + encode: validators.function, + serialize: validators.function + }, true); + } + } + + validator.assertOptions(config, { + baseUrl: validators.spelling('baseURL'), + withXsrfToken: validators.spelling('withXSRFToken') + }, true); + + // Set config.method + config.method = (config.method || this.defaults.method || 'get').toLowerCase(); + + // Flatten headers + let contextHeaders = headers && utils$1.merge( + headers.common, + headers[config.method] + ); + + headers && utils$1.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + (method) => { + delete headers[method]; + } + ); + + config.headers = AxiosHeaders$2.concat(contextHeaders, headers); + + // filter out skipped interceptors + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + + let promise; + let i = 0; + let len; + + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), undefined]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + + promise = Promise.resolve(config); + + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + + return promise; + } + + len = requestInterceptorChain.length; + + let newConfig = config; + + i = 0; + + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + + i = 0; + len = responseInterceptorChain.length; + + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + + return promise; + } + + getUri(config) { + config = mergeConfig$1(this.defaults, config); + const fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); + } +} + +// Provide aliases for supported request methods +utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios$1.prototype[method] = function(url, config) { + return this.request(mergeConfig$1(config || {}, { + method, + url, + data: (config || {}).data + })); + }; +}); + +utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig$1(config || {}, { + method, + headers: isForm ? { + 'Content-Type': 'multipart/form-data' + } : {}, + url, + data + })); + }; + } + + Axios$1.prototype[method] = generateHTTPMethod(); + + Axios$1.prototype[method + 'Form'] = generateHTTPMethod(true); +}); + +const Axios$2 = Axios$1; + +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @param {Function} executor The executor function. + * + * @returns {CancelToken} + */ +class CancelToken$1 { + constructor(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + let resolvePromise; + + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + const token = this; + + // eslint-disable-next-line func-names + this.promise.then(cancel => { + if (!token._listeners) return; + + let i = token._listeners.length; + + while (i-- > 0) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + + // eslint-disable-next-line func-names + this.promise.then = onfulfilled => { + let _resolve; + // eslint-disable-next-line func-names + const promise = new Promise(resolve => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + + return promise; + }; + + executor(function cancel(message, config, request) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new CanceledError$1(message, config, request); + resolvePromise(token.reason); + }); + } + + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } + + /** + * Subscribe to the cancel signal + */ + + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } + + /** + * Unsubscribe from the cancel signal + */ + + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } + } + + toAbortSignal() { + const controller = new AbortController(); + + const abort = (err) => { + controller.abort(err); + }; + + this.subscribe(abort); + + controller.signal.unsubscribe = () => this.unsubscribe(abort); + + return controller.signal; + } + + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + static source() { + let cancel; + const token = new CancelToken$1(function executor(c) { + cancel = c; + }); + return { + token, + cancel + }; + } +} + +const CancelToken$2 = CancelToken$1; + +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * + * @returns {Function} + */ +function spread$1(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +} + +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +function isAxiosError$1(payload) { + return utils$1.isObject(payload) && (payload.isAxiosError === true); +} + +const HttpStatusCode$1 = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511, +}; + +Object.entries(HttpStatusCode$1).forEach(([key, value]) => { + HttpStatusCode$1[value] = key; +}); + +const HttpStatusCode$2 = HttpStatusCode$1; + +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * + * @returns {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + const context = new Axios$2(defaultConfig); + const instance = bind(Axios$2.prototype.request, context); + + // Copy axios.prototype to instance + utils$1.extend(instance, Axios$2.prototype, context, {allOwnKeys: true}); + + // Copy context to instance + utils$1.extend(instance, context, null, {allOwnKeys: true}); + + // Factory for creating new instances + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig$1(defaultConfig, instanceConfig)); + }; + + return instance; +} + +// Create the default instance to be exported +const axios = createInstance(defaults$1); + +// Expose Axios class to allow class inheritance +axios.Axios = Axios$2; + +// Expose Cancel & CancelToken +axios.CanceledError = CanceledError$1; +axios.CancelToken = CancelToken$2; +axios.isCancel = isCancel$1; +axios.VERSION = VERSION$1; +axios.toFormData = toFormData$1; + +// Expose AxiosError class +axios.AxiosError = AxiosError$1; + +// alias for CanceledError for backward compatibility +axios.Cancel = axios.CanceledError; + +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; + +axios.spread = spread$1; + +// Expose isAxiosError +axios.isAxiosError = isAxiosError$1; + +// Expose mergeConfig +axios.mergeConfig = mergeConfig$1; + +axios.AxiosHeaders = AxiosHeaders$2; + +axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); + +axios.getAdapter = adapters.getAdapter; + +axios.HttpStatusCode = HttpStatusCode$2; + +axios.default = axios; + +// this module should only have a default export +const axios$1 = axios; + +// This module is intended to unwrap Axios default export as named. +// Keep top-level export same with static properties +// so that it can keep same with es module or cjs +const { + Axios, + AxiosError, + CanceledError, + isCancel, + CancelToken, + VERSION, + all, + Cancel, + isAxiosError, + spread, + toFormData, + AxiosHeaders, + HttpStatusCode, + formToJSON, + getAdapter, + mergeConfig +} = axios$1; + +export { Axios, AxiosError, AxiosHeaders, Cancel, CancelToken, CanceledError, HttpStatusCode, VERSION, all, axios$1 as default, formToJSON, getAdapter, isAxiosError, isCancel, mergeConfig, spread, toFormData }; +//# sourceMappingURL=axios.js.map diff --git a/node_modules/axios/dist/esm/axios.js.map b/node_modules/axios/dist/esm/axios.js.map new file mode 100644 index 000000000..cf8f508ef --- /dev/null +++ b/node_modules/axios/dist/esm/axios.js.map @@ -0,0 +1 @@ +{"version":3,"file":"axios.js","sources":["../../lib/helpers/bind.js","../../lib/utils.js","../../lib/core/AxiosError.js","../../lib/helpers/null.js","../../lib/helpers/toFormData.js","../../lib/helpers/AxiosURLSearchParams.js","../../lib/helpers/buildURL.js","../../lib/core/InterceptorManager.js","../../lib/defaults/transitional.js","../../lib/platform/browser/classes/URLSearchParams.js","../../lib/platform/browser/classes/FormData.js","../../lib/platform/browser/classes/Blob.js","../../lib/platform/browser/index.js","../../lib/platform/common/utils.js","../../lib/platform/index.js","../../lib/helpers/toURLEncodedForm.js","../../lib/helpers/formDataToJSON.js","../../lib/defaults/index.js","../../lib/helpers/parseHeaders.js","../../lib/core/AxiosHeaders.js","../../lib/core/transformData.js","../../lib/cancel/isCancel.js","../../lib/cancel/CanceledError.js","../../lib/core/settle.js","../../lib/helpers/parseProtocol.js","../../lib/helpers/speedometer.js","../../lib/helpers/throttle.js","../../lib/helpers/progressEventReducer.js","../../lib/helpers/isURLSameOrigin.js","../../lib/helpers/cookies.js","../../lib/helpers/isAbsoluteURL.js","../../lib/helpers/combineURLs.js","../../lib/core/buildFullPath.js","../../lib/core/mergeConfig.js","../../lib/helpers/resolveConfig.js","../../lib/adapters/xhr.js","../../lib/helpers/composeSignals.js","../../lib/helpers/trackStream.js","../../lib/adapters/fetch.js","../../lib/adapters/adapters.js","../../lib/core/dispatchRequest.js","../../lib/env/data.js","../../lib/helpers/validator.js","../../lib/core/Axios.js","../../lib/cancel/CancelToken.js","../../lib/helpers/spread.js","../../lib/helpers/isAxiosError.js","../../lib/helpers/HttpStatusCode.js","../../lib/axios.js","../../index.js"],"sourcesContent":["'use strict';\n\nexport default function bind(fn, thisArg) {\n return function wrap() {\n return fn.apply(thisArg, arguments);\n };\n}\n","'use strict';\n\nimport bind from './helpers/bind.js';\n\n// utils is a library of generic helper functions non-specific to axios\n\nconst {toString} = Object.prototype;\nconst {getPrototypeOf} = Object;\n\nconst kindOf = (cache => thing => {\n const str = toString.call(thing);\n return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());\n})(Object.create(null));\n\nconst kindOfTest = (type) => {\n type = type.toLowerCase();\n return (thing) => kindOf(thing) === type\n}\n\nconst typeOfTest = type => thing => typeof thing === type;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n *\n * @returns {boolean} True if value is an Array, otherwise false\n */\nconst {isArray} = Array;\n\n/**\n * Determine if a value is undefined\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nconst isUndefined = typeOfTest('undefined');\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nconst isArrayBuffer = kindOfTest('ArrayBuffer');\n\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n let result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a String, otherwise false\n */\nconst isString = typeOfTest('string');\n\n/**\n * Determine if a value is a Function\n *\n * @param {*} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nconst isFunction = typeOfTest('function');\n\n/**\n * Determine if a value is a Number\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Number, otherwise false\n */\nconst isNumber = typeOfTest('number');\n\n/**\n * Determine if a value is an Object\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an Object, otherwise false\n */\nconst isObject = (thing) => thing !== null && typeof thing === 'object';\n\n/**\n * Determine if a value is a Boolean\n *\n * @param {*} thing The value to test\n * @returns {boolean} True if value is a Boolean, otherwise false\n */\nconst isBoolean = thing => thing === true || thing === false;\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a plain Object, otherwise false\n */\nconst isPlainObject = (val) => {\n if (kindOf(val) !== 'object') {\n return false;\n }\n\n const prototype = getPrototypeOf(val);\n return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Date, otherwise false\n */\nconst isDate = kindOfTest('Date');\n\n/**\n * Determine if a value is a File\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFile = kindOfTest('File');\n\n/**\n * Determine if a value is a Blob\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nconst isBlob = kindOfTest('Blob');\n\n/**\n * Determine if a value is a FileList\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFileList = kindOfTest('FileList');\n\n/**\n * Determine if a value is a Stream\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nconst isStream = (val) => isObject(val) && isFunction(val.pipe);\n\n/**\n * Determine if a value is a FormData\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nconst isFormData = (thing) => {\n let kind;\n return thing && (\n (typeof FormData === 'function' && thing instanceof FormData) || (\n isFunction(thing.append) && (\n (kind = kindOf(thing)) === 'formdata' ||\n // detect form-data instance\n (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')\n )\n )\n )\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nconst isURLSearchParams = kindOfTest('URLSearchParams');\n\nconst [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n *\n * @returns {String} The String freed of excess whitespace\n */\nconst trim = (str) => str.trim ?\n str.trim() : str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '');\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n *\n * @param {Boolean} [allOwnKeys = false]\n * @returns {any}\n */\nfunction forEach(obj, fn, {allOwnKeys = false} = {}) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n let i;\n let l;\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);\n const len = keys.length;\n let key;\n\n for (i = 0; i < len; i++) {\n key = keys[i];\n fn.call(null, obj[key], key, obj);\n }\n }\n}\n\nfunction findKey(obj, key) {\n key = key.toLowerCase();\n const keys = Object.keys(obj);\n let i = keys.length;\n let _key;\n while (i-- > 0) {\n _key = keys[i];\n if (key === _key.toLowerCase()) {\n return _key;\n }\n }\n return null;\n}\n\nconst _global = (() => {\n /*eslint no-undef:0*/\n if (typeof globalThis !== \"undefined\") return globalThis;\n return typeof self !== \"undefined\" ? self : (typeof window !== 'undefined' ? window : global)\n})();\n\nconst isContextDefined = (context) => !isUndefined(context) && context !== _global;\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n *\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n const {caseless} = isContextDefined(this) && this || {};\n const result = {};\n const assignValue = (val, key) => {\n const targetKey = caseless && findKey(result, key) || key;\n if (isPlainObject(result[targetKey]) && isPlainObject(val)) {\n result[targetKey] = merge(result[targetKey], val);\n } else if (isPlainObject(val)) {\n result[targetKey] = merge({}, val);\n } else if (isArray(val)) {\n result[targetKey] = val.slice();\n } else {\n result[targetKey] = val;\n }\n }\n\n for (let i = 0, l = arguments.length; i < l; i++) {\n arguments[i] && forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n *\n * @param {Boolean} [allOwnKeys]\n * @returns {Object} The resulting value of object a\n */\nconst extend = (a, b, thisArg, {allOwnKeys}= {}) => {\n forEach(b, (val, key) => {\n if (thisArg && isFunction(val)) {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n }, {allOwnKeys});\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n *\n * @returns {string} content value without BOM\n */\nconst stripBOM = (content) => {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\n/**\n * Inherit the prototype methods from one constructor into another\n * @param {function} constructor\n * @param {function} superConstructor\n * @param {object} [props]\n * @param {object} [descriptors]\n *\n * @returns {void}\n */\nconst inherits = (constructor, superConstructor, props, descriptors) => {\n constructor.prototype = Object.create(superConstructor.prototype, descriptors);\n constructor.prototype.constructor = constructor;\n Object.defineProperty(constructor, 'super', {\n value: superConstructor.prototype\n });\n props && Object.assign(constructor.prototype, props);\n}\n\n/**\n * Resolve object with deep prototype chain to a flat object\n * @param {Object} sourceObj source object\n * @param {Object} [destObj]\n * @param {Function|Boolean} [filter]\n * @param {Function} [propFilter]\n *\n * @returns {Object}\n */\nconst toFlatObject = (sourceObj, destObj, filter, propFilter) => {\n let props;\n let i;\n let prop;\n const merged = {};\n\n destObj = destObj || {};\n // eslint-disable-next-line no-eq-null,eqeqeq\n if (sourceObj == null) return destObj;\n\n do {\n props = Object.getOwnPropertyNames(sourceObj);\n i = props.length;\n while (i-- > 0) {\n prop = props[i];\n if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {\n destObj[prop] = sourceObj[prop];\n merged[prop] = true;\n }\n }\n sourceObj = filter !== false && getPrototypeOf(sourceObj);\n } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);\n\n return destObj;\n}\n\n/**\n * Determines whether a string ends with the characters of a specified string\n *\n * @param {String} str\n * @param {String} searchString\n * @param {Number} [position= 0]\n *\n * @returns {boolean}\n */\nconst endsWith = (str, searchString, position) => {\n str = String(str);\n if (position === undefined || position > str.length) {\n position = str.length;\n }\n position -= searchString.length;\n const lastIndex = str.indexOf(searchString, position);\n return lastIndex !== -1 && lastIndex === position;\n}\n\n\n/**\n * Returns new array from array like object or null if failed\n *\n * @param {*} [thing]\n *\n * @returns {?Array}\n */\nconst toArray = (thing) => {\n if (!thing) return null;\n if (isArray(thing)) return thing;\n let i = thing.length;\n if (!isNumber(i)) return null;\n const arr = new Array(i);\n while (i-- > 0) {\n arr[i] = thing[i];\n }\n return arr;\n}\n\n/**\n * Checking if the Uint8Array exists and if it does, it returns a function that checks if the\n * thing passed in is an instance of Uint8Array\n *\n * @param {TypedArray}\n *\n * @returns {Array}\n */\n// eslint-disable-next-line func-names\nconst isTypedArray = (TypedArray => {\n // eslint-disable-next-line func-names\n return thing => {\n return TypedArray && thing instanceof TypedArray;\n };\n})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));\n\n/**\n * For each entry in the object, call the function with the key and value.\n *\n * @param {Object} obj - The object to iterate over.\n * @param {Function} fn - The function to call for each entry.\n *\n * @returns {void}\n */\nconst forEachEntry = (obj, fn) => {\n const generator = obj && obj[Symbol.iterator];\n\n const iterator = generator.call(obj);\n\n let result;\n\n while ((result = iterator.next()) && !result.done) {\n const pair = result.value;\n fn.call(obj, pair[0], pair[1]);\n }\n}\n\n/**\n * It takes a regular expression and a string, and returns an array of all the matches\n *\n * @param {string} regExp - The regular expression to match against.\n * @param {string} str - The string to search.\n *\n * @returns {Array}\n */\nconst matchAll = (regExp, str) => {\n let matches;\n const arr = [];\n\n while ((matches = regExp.exec(str)) !== null) {\n arr.push(matches);\n }\n\n return arr;\n}\n\n/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */\nconst isHTMLForm = kindOfTest('HTMLFormElement');\n\nconst toCamelCase = str => {\n return str.toLowerCase().replace(/[-_\\s]([a-z\\d])(\\w*)/g,\n function replacer(m, p1, p2) {\n return p1.toUpperCase() + p2;\n }\n );\n};\n\n/* Creating a function that will check if an object has a property. */\nconst hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);\n\n/**\n * Determine if a value is a RegExp object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a RegExp object, otherwise false\n */\nconst isRegExp = kindOfTest('RegExp');\n\nconst reduceDescriptors = (obj, reducer) => {\n const descriptors = Object.getOwnPropertyDescriptors(obj);\n const reducedDescriptors = {};\n\n forEach(descriptors, (descriptor, name) => {\n let ret;\n if ((ret = reducer(descriptor, name, obj)) !== false) {\n reducedDescriptors[name] = ret || descriptor;\n }\n });\n\n Object.defineProperties(obj, reducedDescriptors);\n}\n\n/**\n * Makes all methods read-only\n * @param {Object} obj\n */\n\nconst freezeMethods = (obj) => {\n reduceDescriptors(obj, (descriptor, name) => {\n // skip restricted props in strict mode\n if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {\n return false;\n }\n\n const value = obj[name];\n\n if (!isFunction(value)) return;\n\n descriptor.enumerable = false;\n\n if ('writable' in descriptor) {\n descriptor.writable = false;\n return;\n }\n\n if (!descriptor.set) {\n descriptor.set = () => {\n throw Error('Can not rewrite read-only method \\'' + name + '\\'');\n };\n }\n });\n}\n\nconst toObjectSet = (arrayOrString, delimiter) => {\n const obj = {};\n\n const define = (arr) => {\n arr.forEach(value => {\n obj[value] = true;\n });\n }\n\n isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));\n\n return obj;\n}\n\nconst noop = () => {}\n\nconst toFiniteNumber = (value, defaultValue) => {\n return value != null && Number.isFinite(value = +value) ? value : defaultValue;\n}\n\nconst ALPHA = 'abcdefghijklmnopqrstuvwxyz'\n\nconst DIGIT = '0123456789';\n\nconst ALPHABET = {\n DIGIT,\n ALPHA,\n ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT\n}\n\nconst generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {\n let str = '';\n const {length} = alphabet;\n while (size--) {\n str += alphabet[Math.random() * length|0]\n }\n\n return str;\n}\n\n/**\n * If the thing is a FormData object, return true, otherwise return false.\n *\n * @param {unknown} thing - The thing to check.\n *\n * @returns {boolean}\n */\nfunction isSpecCompliantForm(thing) {\n return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);\n}\n\nconst toJSONObject = (obj) => {\n const stack = new Array(10);\n\n const visit = (source, i) => {\n\n if (isObject(source)) {\n if (stack.indexOf(source) >= 0) {\n return;\n }\n\n if(!('toJSON' in source)) {\n stack[i] = source;\n const target = isArray(source) ? [] : {};\n\n forEach(source, (value, key) => {\n const reducedValue = visit(value, i + 1);\n !isUndefined(reducedValue) && (target[key] = reducedValue);\n });\n\n stack[i] = undefined;\n\n return target;\n }\n }\n\n return source;\n }\n\n return visit(obj, 0);\n}\n\nconst isAsyncFn = kindOfTest('AsyncFunction');\n\nconst isThenable = (thing) =>\n thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);\n\n// original code\n// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34\n\nconst _setImmediate = ((setImmediateSupported, postMessageSupported) => {\n if (setImmediateSupported) {\n return setImmediate;\n }\n\n return postMessageSupported ? ((token, callbacks) => {\n _global.addEventListener(\"message\", ({source, data}) => {\n if (source === _global && data === token) {\n callbacks.length && callbacks.shift()();\n }\n }, false);\n\n return (cb) => {\n callbacks.push(cb);\n _global.postMessage(token, \"*\");\n }\n })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);\n})(\n typeof setImmediate === 'function',\n isFunction(_global.postMessage)\n);\n\nconst asap = typeof queueMicrotask !== 'undefined' ?\n queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);\n\n// *********************\n\nexport default {\n isArray,\n isArrayBuffer,\n isBuffer,\n isFormData,\n isArrayBufferView,\n isString,\n isNumber,\n isBoolean,\n isObject,\n isPlainObject,\n isReadableStream,\n isRequest,\n isResponse,\n isHeaders,\n isUndefined,\n isDate,\n isFile,\n isBlob,\n isRegExp,\n isFunction,\n isStream,\n isURLSearchParams,\n isTypedArray,\n isFileList,\n forEach,\n merge,\n extend,\n trim,\n stripBOM,\n inherits,\n toFlatObject,\n kindOf,\n kindOfTest,\n endsWith,\n toArray,\n forEachEntry,\n matchAll,\n isHTMLForm,\n hasOwnProperty,\n hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection\n reduceDescriptors,\n freezeMethods,\n toObjectSet,\n toCamelCase,\n noop,\n toFiniteNumber,\n findKey,\n global: _global,\n isContextDefined,\n ALPHABET,\n generateString,\n isSpecCompliantForm,\n toJSONObject,\n isAsyncFn,\n isThenable,\n setImmediate: _setImmediate,\n asap\n};\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [config] The config.\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n *\n * @returns {Error} The created error.\n */\nfunction AxiosError(message, code, config, request, response) {\n Error.call(this);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error()).stack;\n }\n\n this.message = message;\n this.name = 'AxiosError';\n code && (this.code = code);\n config && (this.config = config);\n request && (this.request = request);\n if (response) {\n this.response = response;\n this.status = response.status ? response.status : null;\n }\n}\n\nutils.inherits(AxiosError, Error, {\n toJSON: function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: utils.toJSONObject(this.config),\n code: this.code,\n status: this.status\n };\n }\n});\n\nconst prototype = AxiosError.prototype;\nconst descriptors = {};\n\n[\n 'ERR_BAD_OPTION_VALUE',\n 'ERR_BAD_OPTION',\n 'ECONNABORTED',\n 'ETIMEDOUT',\n 'ERR_NETWORK',\n 'ERR_FR_TOO_MANY_REDIRECTS',\n 'ERR_DEPRECATED',\n 'ERR_BAD_RESPONSE',\n 'ERR_BAD_REQUEST',\n 'ERR_CANCELED',\n 'ERR_NOT_SUPPORT',\n 'ERR_INVALID_URL'\n// eslint-disable-next-line func-names\n].forEach(code => {\n descriptors[code] = {value: code};\n});\n\nObject.defineProperties(AxiosError, descriptors);\nObject.defineProperty(prototype, 'isAxiosError', {value: true});\n\n// eslint-disable-next-line func-names\nAxiosError.from = (error, code, config, request, response, customProps) => {\n const axiosError = Object.create(prototype);\n\n utils.toFlatObject(error, axiosError, function filter(obj) {\n return obj !== Error.prototype;\n }, prop => {\n return prop !== 'isAxiosError';\n });\n\n AxiosError.call(axiosError, error.message, code, config, request, response);\n\n axiosError.cause = error;\n\n axiosError.name = error.name;\n\n customProps && Object.assign(axiosError, customProps);\n\n return axiosError;\n};\n\nexport default AxiosError;\n","// eslint-disable-next-line strict\nexport default null;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\n// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored\nimport PlatformFormData from '../platform/node/classes/FormData.js';\n\n/**\n * Determines if the given thing is a array or js object.\n *\n * @param {string} thing - The object or array to be visited.\n *\n * @returns {boolean}\n */\nfunction isVisitable(thing) {\n return utils.isPlainObject(thing) || utils.isArray(thing);\n}\n\n/**\n * It removes the brackets from the end of a string\n *\n * @param {string} key - The key of the parameter.\n *\n * @returns {string} the key without the brackets.\n */\nfunction removeBrackets(key) {\n return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;\n}\n\n/**\n * It takes a path, a key, and a boolean, and returns a string\n *\n * @param {string} path - The path to the current key.\n * @param {string} key - The key of the current object being iterated over.\n * @param {string} dots - If true, the key will be rendered with dots instead of brackets.\n *\n * @returns {string} The path to the current key.\n */\nfunction renderKey(path, key, dots) {\n if (!path) return key;\n return path.concat(key).map(function each(token, i) {\n // eslint-disable-next-line no-param-reassign\n token = removeBrackets(token);\n return !dots && i ? '[' + token + ']' : token;\n }).join(dots ? '.' : '');\n}\n\n/**\n * If the array is an array and none of its elements are visitable, then it's a flat array.\n *\n * @param {Array} arr - The array to check\n *\n * @returns {boolean}\n */\nfunction isFlatArray(arr) {\n return utils.isArray(arr) && !arr.some(isVisitable);\n}\n\nconst predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {\n return /^is[A-Z]/.test(prop);\n});\n\n/**\n * Convert a data object to FormData\n *\n * @param {Object} obj\n * @param {?Object} [formData]\n * @param {?Object} [options]\n * @param {Function} [options.visitor]\n * @param {Boolean} [options.metaTokens = true]\n * @param {Boolean} [options.dots = false]\n * @param {?Boolean} [options.indexes = false]\n *\n * @returns {Object}\n **/\n\n/**\n * It converts an object into a FormData object\n *\n * @param {Object} obj - The object to convert to form data.\n * @param {string} formData - The FormData object to append to.\n * @param {Object} options\n *\n * @returns\n */\nfunction toFormData(obj, formData, options) {\n if (!utils.isObject(obj)) {\n throw new TypeError('target must be an object');\n }\n\n // eslint-disable-next-line no-param-reassign\n formData = formData || new (PlatformFormData || FormData)();\n\n // eslint-disable-next-line no-param-reassign\n options = utils.toFlatObject(options, {\n metaTokens: true,\n dots: false,\n indexes: false\n }, false, function defined(option, source) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n return !utils.isUndefined(source[option]);\n });\n\n const metaTokens = options.metaTokens;\n // eslint-disable-next-line no-use-before-define\n const visitor = options.visitor || defaultVisitor;\n const dots = options.dots;\n const indexes = options.indexes;\n const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;\n const useBlob = _Blob && utils.isSpecCompliantForm(formData);\n\n if (!utils.isFunction(visitor)) {\n throw new TypeError('visitor must be a function');\n }\n\n function convertValue(value) {\n if (value === null) return '';\n\n if (utils.isDate(value)) {\n return value.toISOString();\n }\n\n if (!useBlob && utils.isBlob(value)) {\n throw new AxiosError('Blob is not supported. Use a Buffer instead.');\n }\n\n if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {\n return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);\n }\n\n return value;\n }\n\n /**\n * Default visitor.\n *\n * @param {*} value\n * @param {String|Number} key\n * @param {Array} path\n * @this {FormData}\n *\n * @returns {boolean} return true to visit the each prop of the value recursively\n */\n function defaultVisitor(value, key, path) {\n let arr = value;\n\n if (value && !path && typeof value === 'object') {\n if (utils.endsWith(key, '{}')) {\n // eslint-disable-next-line no-param-reassign\n key = metaTokens ? key : key.slice(0, -2);\n // eslint-disable-next-line no-param-reassign\n value = JSON.stringify(value);\n } else if (\n (utils.isArray(value) && isFlatArray(value)) ||\n ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))\n )) {\n // eslint-disable-next-line no-param-reassign\n key = removeBrackets(key);\n\n arr.forEach(function each(el, index) {\n !(utils.isUndefined(el) || el === null) && formData.append(\n // eslint-disable-next-line no-nested-ternary\n indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),\n convertValue(el)\n );\n });\n return false;\n }\n }\n\n if (isVisitable(value)) {\n return true;\n }\n\n formData.append(renderKey(path, key, dots), convertValue(value));\n\n return false;\n }\n\n const stack = [];\n\n const exposedHelpers = Object.assign(predicates, {\n defaultVisitor,\n convertValue,\n isVisitable\n });\n\n function build(value, path) {\n if (utils.isUndefined(value)) return;\n\n if (stack.indexOf(value) !== -1) {\n throw Error('Circular reference detected in ' + path.join('.'));\n }\n\n stack.push(value);\n\n utils.forEach(value, function each(el, key) {\n const result = !(utils.isUndefined(el) || el === null) && visitor.call(\n formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers\n );\n\n if (result === true) {\n build(el, path ? path.concat(key) : [key]);\n }\n });\n\n stack.pop();\n }\n\n if (!utils.isObject(obj)) {\n throw new TypeError('data must be an object');\n }\n\n build(obj);\n\n return formData;\n}\n\nexport default toFormData;\n","'use strict';\n\nimport toFormData from './toFormData.js';\n\n/**\n * It encodes a string by replacing all characters that are not in the unreserved set with\n * their percent-encoded equivalents\n *\n * @param {string} str - The string to encode.\n *\n * @returns {string} The encoded string.\n */\nfunction encode(str) {\n const charMap = {\n '!': '%21',\n \"'\": '%27',\n '(': '%28',\n ')': '%29',\n '~': '%7E',\n '%20': '+',\n '%00': '\\x00'\n };\n return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {\n return charMap[match];\n });\n}\n\n/**\n * It takes a params object and converts it to a FormData object\n *\n * @param {Object} params - The parameters to be converted to a FormData object.\n * @param {Object} options - The options object passed to the Axios constructor.\n *\n * @returns {void}\n */\nfunction AxiosURLSearchParams(params, options) {\n this._pairs = [];\n\n params && toFormData(params, this, options);\n}\n\nconst prototype = AxiosURLSearchParams.prototype;\n\nprototype.append = function append(name, value) {\n this._pairs.push([name, value]);\n};\n\nprototype.toString = function toString(encoder) {\n const _encode = encoder ? function(value) {\n return encoder.call(this, value, encode);\n } : encode;\n\n return this._pairs.map(function each(pair) {\n return _encode(pair[0]) + '=' + _encode(pair[1]);\n }, '').join('&');\n};\n\nexport default AxiosURLSearchParams;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';\n\n/**\n * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their\n * URI encoded counterparts\n *\n * @param {string} val The value to be encoded.\n *\n * @returns {string} The encoded value.\n */\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @param {?(object|Function)} options\n *\n * @returns {string} The formatted url\n */\nexport default function buildURL(url, params, options) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n \n const _encode = options && options.encode || encode;\n\n if (utils.isFunction(options)) {\n options = {\n serialize: options\n };\n } \n\n const serializeFn = options && options.serialize;\n\n let serializedParams;\n\n if (serializeFn) {\n serializedParams = serializeFn(params, options);\n } else {\n serializedParams = utils.isURLSearchParams(params) ?\n params.toString() :\n new AxiosURLSearchParams(params, options).toString(_encode);\n }\n\n if (serializedParams) {\n const hashmarkIndex = url.indexOf(\"#\");\n\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\nclass InterceptorManager {\n constructor() {\n this.handlers = [];\n }\n\n /**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\n use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled,\n rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n }\n\n /**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n *\n * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise\n */\n eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n }\n\n /**\n * Clear all interceptors from the stack\n *\n * @returns {void}\n */\n clear() {\n if (this.handlers) {\n this.handlers = [];\n }\n }\n\n /**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n *\n * @returns {void}\n */\n forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n }\n}\n\nexport default InterceptorManager;\n","'use strict';\n\nexport default {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n};\n","'use strict';\n\nimport AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';\nexport default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;\n","'use strict';\n\nexport default typeof FormData !== 'undefined' ? FormData : null;\n","'use strict'\n\nexport default typeof Blob !== 'undefined' ? Blob : null\n","import URLSearchParams from './classes/URLSearchParams.js'\nimport FormData from './classes/FormData.js'\nimport Blob from './classes/Blob.js'\n\nexport default {\n isBrowser: true,\n classes: {\n URLSearchParams,\n FormData,\n Blob\n },\n protocols: ['http', 'https', 'file', 'blob', 'url', 'data']\n};\n","const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';\n\nconst _navigator = typeof navigator === 'object' && navigator || undefined;\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n *\n * @returns {boolean}\n */\nconst hasStandardBrowserEnv = hasBrowserEnv &&\n (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);\n\n/**\n * Determine if we're running in a standard browser webWorker environment\n *\n * Although the `isStandardBrowserEnv` method indicates that\n * `allows axios to run in a web worker`, the WebWorker will still be\n * filtered out due to its judgment standard\n * `typeof window !== 'undefined' && typeof document !== 'undefined'`.\n * This leads to a problem when axios post `FormData` in webWorker\n */\nconst hasStandardBrowserWebWorkerEnv = (() => {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n // eslint-disable-next-line no-undef\n self instanceof WorkerGlobalScope &&\n typeof self.importScripts === 'function'\n );\n})();\n\nconst origin = hasBrowserEnv && window.location.href || 'http://localhost';\n\nexport {\n hasBrowserEnv,\n hasStandardBrowserWebWorkerEnv,\n hasStandardBrowserEnv,\n _navigator as navigator,\n origin\n}\n","import platform from './node/index.js';\nimport * as utils from './common/utils.js';\n\nexport default {\n ...utils,\n ...platform\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport toFormData from './toFormData.js';\nimport platform from '../platform/index.js';\n\nexport default function toURLEncodedForm(data, options) {\n return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({\n visitor: function(value, key, path, helpers) {\n if (platform.isNode && utils.isBuffer(value)) {\n this.append(key, value.toString('base64'));\n return false;\n }\n\n return helpers.defaultVisitor.apply(this, arguments);\n }\n }, options));\n}\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']\n *\n * @param {string} name - The name of the property to get.\n *\n * @returns An array of strings.\n */\nfunction parsePropPath(name) {\n // foo[x][y][z]\n // foo.x.y.z\n // foo-x-y-z\n // foo x y z\n return utils.matchAll(/\\w+|\\[(\\w*)]/g, name).map(match => {\n return match[0] === '[]' ? '' : match[1] || match[0];\n });\n}\n\n/**\n * Convert an array to an object.\n *\n * @param {Array} arr - The array to convert to an object.\n *\n * @returns An object with the same keys and values as the array.\n */\nfunction arrayToObject(arr) {\n const obj = {};\n const keys = Object.keys(arr);\n let i;\n const len = keys.length;\n let key;\n for (i = 0; i < len; i++) {\n key = keys[i];\n obj[key] = arr[key];\n }\n return obj;\n}\n\n/**\n * It takes a FormData object and returns a JavaScript object\n *\n * @param {string} formData The FormData object to convert to JSON.\n *\n * @returns {Object | null} The converted object.\n */\nfunction formDataToJSON(formData) {\n function buildPath(path, value, target, index) {\n let name = path[index++];\n\n if (name === '__proto__') return true;\n\n const isNumericKey = Number.isFinite(+name);\n const isLast = index >= path.length;\n name = !name && utils.isArray(target) ? target.length : name;\n\n if (isLast) {\n if (utils.hasOwnProp(target, name)) {\n target[name] = [target[name], value];\n } else {\n target[name] = value;\n }\n\n return !isNumericKey;\n }\n\n if (!target[name] || !utils.isObject(target[name])) {\n target[name] = [];\n }\n\n const result = buildPath(path, value, target[name], index);\n\n if (result && utils.isArray(target[name])) {\n target[name] = arrayToObject(target[name]);\n }\n\n return !isNumericKey;\n }\n\n if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {\n const obj = {};\n\n utils.forEachEntry(formData, (name, value) => {\n buildPath(parsePropPath(name), value, obj, 0);\n });\n\n return obj;\n }\n\n return null;\n}\n\nexport default formDataToJSON;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\nimport transitionalDefaults from './transitional.js';\nimport toFormData from '../helpers/toFormData.js';\nimport toURLEncodedForm from '../helpers/toURLEncodedForm.js';\nimport platform from '../platform/index.js';\nimport formDataToJSON from '../helpers/formDataToJSON.js';\n\n/**\n * It takes a string, tries to parse it, and if it fails, it returns the stringified version\n * of the input\n *\n * @param {any} rawValue - The value to be stringified.\n * @param {Function} parser - A function that parses a string into a JavaScript object.\n * @param {Function} encoder - A function that takes a value and returns a string.\n *\n * @returns {string} A stringified version of the rawValue.\n */\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nconst defaults = {\n\n transitional: transitionalDefaults,\n\n adapter: ['xhr', 'http', 'fetch'],\n\n transformRequest: [function transformRequest(data, headers) {\n const contentType = headers.getContentType() || '';\n const hasJSONContentType = contentType.indexOf('application/json') > -1;\n const isObjectPayload = utils.isObject(data);\n\n if (isObjectPayload && utils.isHTMLForm(data)) {\n data = new FormData(data);\n }\n\n const isFormData = utils.isFormData(data);\n\n if (isFormData) {\n return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;\n }\n\n if (utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data) ||\n utils.isReadableStream(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);\n return data.toString();\n }\n\n let isFileList;\n\n if (isObjectPayload) {\n if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {\n return toURLEncodedForm(data, this.formSerializer).toString();\n }\n\n if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {\n const _FormData = this.env && this.env.FormData;\n\n return toFormData(\n isFileList ? {'files[]': data} : data,\n _FormData && new _FormData(),\n this.formSerializer\n );\n }\n }\n\n if (isObjectPayload || hasJSONContentType ) {\n headers.setContentType('application/json', false);\n return stringifySafely(data);\n }\n\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n const transitional = this.transitional || defaults.transitional;\n const forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n const JSONRequested = this.responseType === 'json';\n\n if (utils.isResponse(data) || utils.isReadableStream(data)) {\n return data;\n }\n\n if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {\n const silentJSONParsing = transitional && transitional.silentJSONParsing;\n const strictJSONParsing = !silentJSONParsing && JSONRequested;\n\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n env: {\n FormData: platform.classes.FormData,\n Blob: platform.classes.Blob\n },\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*',\n 'Content-Type': undefined\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {\n defaults.headers[method] = {};\n});\n\nexport default defaults;\n","'use strict';\n\nimport utils from './../utils.js';\n\n// RawAxiosHeaders whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nconst ignoreDuplicateOf = utils.toObjectSet([\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n]);\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} rawHeaders Headers needing to be parsed\n *\n * @returns {Object} Headers parsed into an object\n */\nexport default rawHeaders => {\n const parsed = {};\n let key;\n let val;\n let i;\n\n rawHeaders && rawHeaders.split('\\n').forEach(function parser(line) {\n i = line.indexOf(':');\n key = line.substring(0, i).trim().toLowerCase();\n val = line.substring(i + 1).trim();\n\n if (!key || (parsed[key] && ignoreDuplicateOf[key])) {\n return;\n }\n\n if (key === 'set-cookie') {\n if (parsed[key]) {\n parsed[key].push(val);\n } else {\n parsed[key] = [val];\n }\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n });\n\n return parsed;\n};\n","'use strict';\n\nimport utils from '../utils.js';\nimport parseHeaders from '../helpers/parseHeaders.js';\n\nconst $internals = Symbol('internals');\n\nfunction normalizeHeader(header) {\n return header && String(header).trim().toLowerCase();\n}\n\nfunction normalizeValue(value) {\n if (value === false || value == null) {\n return value;\n }\n\n return utils.isArray(value) ? value.map(normalizeValue) : String(value);\n}\n\nfunction parseTokens(str) {\n const tokens = Object.create(null);\n const tokensRE = /([^\\s,;=]+)\\s*(?:=\\s*([^,;]+))?/g;\n let match;\n\n while ((match = tokensRE.exec(str))) {\n tokens[match[1]] = match[2];\n }\n\n return tokens;\n}\n\nconst isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());\n\nfunction matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {\n if (utils.isFunction(filter)) {\n return filter.call(this, value, header);\n }\n\n if (isHeaderNameFilter) {\n value = header;\n }\n\n if (!utils.isString(value)) return;\n\n if (utils.isString(filter)) {\n return value.indexOf(filter) !== -1;\n }\n\n if (utils.isRegExp(filter)) {\n return filter.test(value);\n }\n}\n\nfunction formatHeader(header) {\n return header.trim()\n .toLowerCase().replace(/([a-z\\d])(\\w*)/g, (w, char, str) => {\n return char.toUpperCase() + str;\n });\n}\n\nfunction buildAccessors(obj, header) {\n const accessorName = utils.toCamelCase(' ' + header);\n\n ['get', 'set', 'has'].forEach(methodName => {\n Object.defineProperty(obj, methodName + accessorName, {\n value: function(arg1, arg2, arg3) {\n return this[methodName].call(this, header, arg1, arg2, arg3);\n },\n configurable: true\n });\n });\n}\n\nclass AxiosHeaders {\n constructor(headers) {\n headers && this.set(headers);\n }\n\n set(header, valueOrRewrite, rewrite) {\n const self = this;\n\n function setHeader(_value, _header, _rewrite) {\n const lHeader = normalizeHeader(_header);\n\n if (!lHeader) {\n throw new Error('header name must be a non-empty string');\n }\n\n const key = utils.findKey(self, lHeader);\n\n if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {\n self[key || _header] = normalizeValue(_value);\n }\n }\n\n const setHeaders = (headers, _rewrite) =>\n utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));\n\n if (utils.isPlainObject(header) || header instanceof this.constructor) {\n setHeaders(header, valueOrRewrite)\n } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {\n setHeaders(parseHeaders(header), valueOrRewrite);\n } else if (utils.isHeaders(header)) {\n for (const [key, value] of header.entries()) {\n setHeader(value, key, rewrite);\n }\n } else {\n header != null && setHeader(valueOrRewrite, header, rewrite);\n }\n\n return this;\n }\n\n get(header, parser) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n if (key) {\n const value = this[key];\n\n if (!parser) {\n return value;\n }\n\n if (parser === true) {\n return parseTokens(value);\n }\n\n if (utils.isFunction(parser)) {\n return parser.call(this, value, key);\n }\n\n if (utils.isRegExp(parser)) {\n return parser.exec(value);\n }\n\n throw new TypeError('parser must be boolean|regexp|function');\n }\n }\n }\n\n has(header, matcher) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));\n }\n\n return false;\n }\n\n delete(header, matcher) {\n const self = this;\n let deleted = false;\n\n function deleteHeader(_header) {\n _header = normalizeHeader(_header);\n\n if (_header) {\n const key = utils.findKey(self, _header);\n\n if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {\n delete self[key];\n\n deleted = true;\n }\n }\n }\n\n if (utils.isArray(header)) {\n header.forEach(deleteHeader);\n } else {\n deleteHeader(header);\n }\n\n return deleted;\n }\n\n clear(matcher) {\n const keys = Object.keys(this);\n let i = keys.length;\n let deleted = false;\n\n while (i--) {\n const key = keys[i];\n if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {\n delete this[key];\n deleted = true;\n }\n }\n\n return deleted;\n }\n\n normalize(format) {\n const self = this;\n const headers = {};\n\n utils.forEach(this, (value, header) => {\n const key = utils.findKey(headers, header);\n\n if (key) {\n self[key] = normalizeValue(value);\n delete self[header];\n return;\n }\n\n const normalized = format ? formatHeader(header) : String(header).trim();\n\n if (normalized !== header) {\n delete self[header];\n }\n\n self[normalized] = normalizeValue(value);\n\n headers[normalized] = true;\n });\n\n return this;\n }\n\n concat(...targets) {\n return this.constructor.concat(this, ...targets);\n }\n\n toJSON(asStrings) {\n const obj = Object.create(null);\n\n utils.forEach(this, (value, header) => {\n value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);\n });\n\n return obj;\n }\n\n [Symbol.iterator]() {\n return Object.entries(this.toJSON())[Symbol.iterator]();\n }\n\n toString() {\n return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\\n');\n }\n\n get [Symbol.toStringTag]() {\n return 'AxiosHeaders';\n }\n\n static from(thing) {\n return thing instanceof this ? thing : new this(thing);\n }\n\n static concat(first, ...targets) {\n const computed = new this(first);\n\n targets.forEach((target) => computed.set(target));\n\n return computed;\n }\n\n static accessor(header) {\n const internals = this[$internals] = (this[$internals] = {\n accessors: {}\n });\n\n const accessors = internals.accessors;\n const prototype = this.prototype;\n\n function defineAccessor(_header) {\n const lHeader = normalizeHeader(_header);\n\n if (!accessors[lHeader]) {\n buildAccessors(prototype, _header);\n accessors[lHeader] = true;\n }\n }\n\n utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);\n\n return this;\n }\n}\n\nAxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);\n\n// reserved names hotfix\nutils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {\n let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`\n return {\n get: () => value,\n set(headerValue) {\n this[mapped] = headerValue;\n }\n }\n});\n\nutils.freezeMethods(AxiosHeaders);\n\nexport default AxiosHeaders;\n","'use strict';\n\nimport utils from './../utils.js';\nimport defaults from '../defaults/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Array|Function} fns A single function or Array of functions\n * @param {?Object} response The response object\n *\n * @returns {*} The resulting transformed data\n */\nexport default function transformData(fns, response) {\n const config = this || defaults;\n const context = response || config;\n const headers = AxiosHeaders.from(context.headers);\n let data = context.data;\n\n utils.forEach(fns, function transform(fn) {\n data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);\n });\n\n headers.normalize();\n\n return data;\n}\n","'use strict';\n\nexport default function isCancel(value) {\n return !!(value && value.__CANCEL__);\n}\n","'use strict';\n\nimport AxiosError from '../core/AxiosError.js';\nimport utils from '../utils.js';\n\n/**\n * A `CanceledError` is an object that is thrown when an operation is canceled.\n *\n * @param {string=} message The message.\n * @param {Object=} config The config.\n * @param {Object=} request The request.\n *\n * @returns {CanceledError} The created error.\n */\nfunction CanceledError(message, config, request) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);\n this.name = 'CanceledError';\n}\n\nutils.inherits(CanceledError, AxiosError, {\n __CANCEL__: true\n});\n\nexport default CanceledError;\n","'use strict';\n\nimport AxiosError from './AxiosError.js';\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n *\n * @returns {object} The response.\n */\nexport default function settle(resolve, reject, response) {\n const validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(new AxiosError(\n 'Request failed with status code ' + response.status,\n [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],\n response.config,\n response.request,\n response\n ));\n }\n}\n","'use strict';\n\nexport default function parseProtocol(url) {\n const match = /^([-+\\w]{1,25})(:?\\/\\/|:)/.exec(url);\n return match && match[1] || '';\n}\n","'use strict';\n\n/**\n * Calculate data maxRate\n * @param {Number} [samplesCount= 10]\n * @param {Number} [min= 1000]\n * @returns {Function}\n */\nfunction speedometer(samplesCount, min) {\n samplesCount = samplesCount || 10;\n const bytes = new Array(samplesCount);\n const timestamps = new Array(samplesCount);\n let head = 0;\n let tail = 0;\n let firstSampleTS;\n\n min = min !== undefined ? min : 1000;\n\n return function push(chunkLength) {\n const now = Date.now();\n\n const startedAt = timestamps[tail];\n\n if (!firstSampleTS) {\n firstSampleTS = now;\n }\n\n bytes[head] = chunkLength;\n timestamps[head] = now;\n\n let i = tail;\n let bytesCount = 0;\n\n while (i !== head) {\n bytesCount += bytes[i++];\n i = i % samplesCount;\n }\n\n head = (head + 1) % samplesCount;\n\n if (head === tail) {\n tail = (tail + 1) % samplesCount;\n }\n\n if (now - firstSampleTS < min) {\n return;\n }\n\n const passed = startedAt && now - startedAt;\n\n return passed ? Math.round(bytesCount * 1000 / passed) : undefined;\n };\n}\n\nexport default speedometer;\n","/**\n * Throttle decorator\n * @param {Function} fn\n * @param {Number} freq\n * @return {Function}\n */\nfunction throttle(fn, freq) {\n let timestamp = 0;\n let threshold = 1000 / freq;\n let lastArgs;\n let timer;\n\n const invoke = (args, now = Date.now()) => {\n timestamp = now;\n lastArgs = null;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n fn.apply(null, args);\n }\n\n const throttled = (...args) => {\n const now = Date.now();\n const passed = now - timestamp;\n if ( passed >= threshold) {\n invoke(args, now);\n } else {\n lastArgs = args;\n if (!timer) {\n timer = setTimeout(() => {\n timer = null;\n invoke(lastArgs)\n }, threshold - passed);\n }\n }\n }\n\n const flush = () => lastArgs && invoke(lastArgs);\n\n return [throttled, flush];\n}\n\nexport default throttle;\n","import speedometer from \"./speedometer.js\";\nimport throttle from \"./throttle.js\";\nimport utils from \"../utils.js\";\n\nexport const progressEventReducer = (listener, isDownloadStream, freq = 3) => {\n let bytesNotified = 0;\n const _speedometer = speedometer(50, 250);\n\n return throttle(e => {\n const loaded = e.loaded;\n const total = e.lengthComputable ? e.total : undefined;\n const progressBytes = loaded - bytesNotified;\n const rate = _speedometer(progressBytes);\n const inRange = loaded <= total;\n\n bytesNotified = loaded;\n\n const data = {\n loaded,\n total,\n progress: total ? (loaded / total) : undefined,\n bytes: progressBytes,\n rate: rate ? rate : undefined,\n estimated: rate && total && inRange ? (total - loaded) / rate : undefined,\n event: e,\n lengthComputable: total != null,\n [isDownloadStream ? 'download' : 'upload']: true\n };\n\n listener(data);\n }, freq);\n}\n\nexport const progressEventDecorator = (total, throttled) => {\n const lengthComputable = total != null;\n\n return [(loaded) => throttled[0]({\n lengthComputable,\n total,\n loaded\n }), throttled[1]];\n}\n\nexport const asyncDecorator = (fn) => (...args) => utils.asap(() => fn(...args));\n","import platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {\n url = new URL(url, platform.origin);\n\n return (\n origin.protocol === url.protocol &&\n origin.host === url.host &&\n (isMSIE || origin.port === url.port)\n );\n})(\n new URL(platform.origin),\n platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)\n) : () => true;\n","import utils from './../utils.js';\nimport platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ?\n\n // Standard browser envs support document.cookie\n {\n write(name, value, expires, path, domain, secure) {\n const cookie = [name + '=' + encodeURIComponent(value)];\n\n utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());\n\n utils.isString(path) && cookie.push('path=' + path);\n\n utils.isString(domain) && cookie.push('domain=' + domain);\n\n secure === true && cookie.push('secure');\n\n document.cookie = cookie.join('; ');\n },\n\n read(name) {\n const match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n }\n\n :\n\n // Non-standard browser env (web workers, react-native) lack needed support.\n {\n write() {},\n read() {\n return null;\n },\n remove() {}\n };\n\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n *\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nexport default function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n}\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n *\n * @returns {string} The combined URL\n */\nexport default function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/?\\/$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n}\n","'use strict';\n\nimport isAbsoluteURL from '../helpers/isAbsoluteURL.js';\nimport combineURLs from '../helpers/combineURLs.js';\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n *\n * @returns {string} The combined full path\n */\nexport default function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosHeaders from \"./AxiosHeaders.js\";\n\nconst headersToObject = (thing) => thing instanceof AxiosHeaders ? { ...thing } : thing;\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n *\n * @returns {Object} New object resulting from merging config2 to config1\n */\nexport default function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n const config = {};\n\n function getMergedValue(target, source, prop, caseless) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge.call({caseless}, target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(a, b, prop , caseless) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(a, b, prop , caseless);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a, prop , caseless);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(a, b, prop) {\n if (prop in config2) {\n return getMergedValue(a, b);\n } else if (prop in config1) {\n return getMergedValue(undefined, a);\n }\n }\n\n const mergeMap = {\n url: valueFromConfig2,\n method: valueFromConfig2,\n data: valueFromConfig2,\n baseURL: defaultToConfig2,\n transformRequest: defaultToConfig2,\n transformResponse: defaultToConfig2,\n paramsSerializer: defaultToConfig2,\n timeout: defaultToConfig2,\n timeoutMessage: defaultToConfig2,\n withCredentials: defaultToConfig2,\n withXSRFToken: defaultToConfig2,\n adapter: defaultToConfig2,\n responseType: defaultToConfig2,\n xsrfCookieName: defaultToConfig2,\n xsrfHeaderName: defaultToConfig2,\n onUploadProgress: defaultToConfig2,\n onDownloadProgress: defaultToConfig2,\n decompress: defaultToConfig2,\n maxContentLength: defaultToConfig2,\n maxBodyLength: defaultToConfig2,\n beforeRedirect: defaultToConfig2,\n transport: defaultToConfig2,\n httpAgent: defaultToConfig2,\n httpsAgent: defaultToConfig2,\n cancelToken: defaultToConfig2,\n socketPath: defaultToConfig2,\n responseEncoding: defaultToConfig2,\n validateStatus: mergeDirectKeys,\n headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true)\n };\n\n utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {\n const merge = mergeMap[prop] || mergeDeepProperties;\n const configValue = merge(config1[prop], config2[prop], prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n}\n","import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport isURLSameOrigin from \"./isURLSameOrigin.js\";\nimport cookies from \"./cookies.js\";\nimport buildFullPath from \"../core/buildFullPath.js\";\nimport mergeConfig from \"../core/mergeConfig.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport buildURL from \"./buildURL.js\";\n\nexport default (config) => {\n const newConfig = mergeConfig({}, config);\n\n let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;\n\n newConfig.headers = headers = AxiosHeaders.from(headers);\n\n newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);\n\n // HTTP basic authentication\n if (auth) {\n headers.set('Authorization', 'Basic ' +\n btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))\n );\n }\n\n let contentType;\n\n if (utils.isFormData(data)) {\n if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {\n headers.setContentType(undefined); // Let the browser set it\n } else if ((contentType = headers.getContentType()) !== false) {\n // fix semicolon duplication issue for ReactNative FormData implementation\n const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];\n headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));\n }\n }\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n\n if (platform.hasStandardBrowserEnv) {\n withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));\n\n if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {\n // Add xsrf header\n const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);\n\n if (xsrfValue) {\n headers.set(xsrfHeaderName, xsrfValue);\n }\n }\n }\n\n return newConfig;\n}\n\n","import utils from './../utils.js';\nimport settle from './../core/settle.js';\nimport transitionalDefaults from '../defaults/transitional.js';\nimport AxiosError from '../core/AxiosError.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport parseProtocol from '../helpers/parseProtocol.js';\nimport platform from '../platform/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport {progressEventReducer} from '../helpers/progressEventReducer.js';\nimport resolveConfig from \"../helpers/resolveConfig.js\";\n\nconst isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';\n\nexport default isXHRAdapterSupported && function (config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n const _config = resolveConfig(config);\n let requestData = _config.data;\n const requestHeaders = AxiosHeaders.from(_config.headers).normalize();\n let {responseType, onUploadProgress, onDownloadProgress} = _config;\n let onCanceled;\n let uploadThrottled, downloadThrottled;\n let flushUpload, flushDownload;\n\n function done() {\n flushUpload && flushUpload(); // flush events\n flushDownload && flushDownload(); // flush events\n\n _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);\n\n _config.signal && _config.signal.removeEventListener('abort', onCanceled);\n }\n\n let request = new XMLHttpRequest();\n\n request.open(_config.method.toUpperCase(), _config.url, true);\n\n // Set the request timeout in MS\n request.timeout = _config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n const responseHeaders = AxiosHeaders.from(\n 'getAllResponseHeaders' in request && request.getAllResponseHeaders()\n );\n const responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n const response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config,\n request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';\n const transitional = _config.transitional || transitionalDefaults;\n if (_config.timeoutErrorMessage) {\n timeoutErrorMessage = _config.timeoutErrorMessage;\n }\n reject(new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n config,\n request));\n\n // Clean up request\n request = null;\n };\n\n // Remove Content-Type if data is undefined\n requestData === undefined && requestHeaders.setContentType(null);\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {\n request.setRequestHeader(key, val);\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(_config.withCredentials)) {\n request.withCredentials = !!_config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = _config.responseType;\n }\n\n // Handle progress if needed\n if (onDownloadProgress) {\n ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));\n request.addEventListener('progress', downloadThrottled);\n }\n\n // Not all browsers support upload events\n if (onUploadProgress && request.upload) {\n ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));\n\n request.upload.addEventListener('progress', uploadThrottled);\n\n request.upload.addEventListener('loadend', flushUpload);\n }\n\n if (_config.cancelToken || _config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = cancel => {\n if (!request) {\n return;\n }\n reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);\n request.abort();\n request = null;\n };\n\n _config.cancelToken && _config.cancelToken.subscribe(onCanceled);\n if (_config.signal) {\n _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n const protocol = parseProtocol(_config.url);\n\n if (protocol && platform.protocols.indexOf(protocol) === -1) {\n reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));\n return;\n }\n\n\n // Send the request\n request.send(requestData || null);\n });\n}\n","import CanceledError from \"../cancel/CanceledError.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport utils from '../utils.js';\n\nconst composeSignals = (signals, timeout) => {\n const {length} = (signals = signals ? signals.filter(Boolean) : []);\n\n if (timeout || length) {\n let controller = new AbortController();\n\n let aborted;\n\n const onabort = function (reason) {\n if (!aborted) {\n aborted = true;\n unsubscribe();\n const err = reason instanceof Error ? reason : this.reason;\n controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));\n }\n }\n\n let timer = timeout && setTimeout(() => {\n timer = null;\n onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT))\n }, timeout)\n\n const unsubscribe = () => {\n if (signals) {\n timer && clearTimeout(timer);\n timer = null;\n signals.forEach(signal => {\n signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);\n });\n signals = null;\n }\n }\n\n signals.forEach((signal) => signal.addEventListener('abort', onabort));\n\n const {signal} = controller;\n\n signal.unsubscribe = () => utils.asap(unsubscribe);\n\n return signal;\n }\n}\n\nexport default composeSignals;\n","\nexport const streamChunk = function* (chunk, chunkSize) {\n let len = chunk.byteLength;\n\n if (!chunkSize || len < chunkSize) {\n yield chunk;\n return;\n }\n\n let pos = 0;\n let end;\n\n while (pos < len) {\n end = pos + chunkSize;\n yield chunk.slice(pos, end);\n pos = end;\n }\n}\n\nexport const readBytes = async function* (iterable, chunkSize) {\n for await (const chunk of readStream(iterable)) {\n yield* streamChunk(chunk, chunkSize);\n }\n}\n\nconst readStream = async function* (stream) {\n if (stream[Symbol.asyncIterator]) {\n yield* stream;\n return;\n }\n\n const reader = stream.getReader();\n try {\n for (;;) {\n const {done, value} = await reader.read();\n if (done) {\n break;\n }\n yield value;\n }\n } finally {\n await reader.cancel();\n }\n}\n\nexport const trackStream = (stream, chunkSize, onProgress, onFinish) => {\n const iterator = readBytes(stream, chunkSize);\n\n let bytes = 0;\n let done;\n let _onFinish = (e) => {\n if (!done) {\n done = true;\n onFinish && onFinish(e);\n }\n }\n\n return new ReadableStream({\n async pull(controller) {\n try {\n const {done, value} = await iterator.next();\n\n if (done) {\n _onFinish();\n controller.close();\n return;\n }\n\n let len = value.byteLength;\n if (onProgress) {\n let loadedBytes = bytes += len;\n onProgress(loadedBytes);\n }\n controller.enqueue(new Uint8Array(value));\n } catch (err) {\n _onFinish(err);\n throw err;\n }\n },\n cancel(reason) {\n _onFinish(reason);\n return iterator.return();\n }\n }, {\n highWaterMark: 2\n })\n}\n","import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport composeSignals from \"../helpers/composeSignals.js\";\nimport {trackStream} from \"../helpers/trackStream.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport {progressEventReducer, progressEventDecorator, asyncDecorator} from \"../helpers/progressEventReducer.js\";\nimport resolveConfig from \"../helpers/resolveConfig.js\";\nimport settle from \"../core/settle.js\";\n\nconst isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';\nconst isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';\n\n// used only inside the fetch adapter\nconst encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?\n ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :\n async (str) => new Uint8Array(await new Response(str).arrayBuffer())\n);\n\nconst test = (fn, ...args) => {\n try {\n return !!fn(...args);\n } catch (e) {\n return false\n }\n}\n\nconst supportsRequestStream = isReadableStreamSupported && test(() => {\n let duplexAccessed = false;\n\n const hasContentType = new Request(platform.origin, {\n body: new ReadableStream(),\n method: 'POST',\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n }).headers.has('Content-Type');\n\n return duplexAccessed && !hasContentType;\n});\n\nconst DEFAULT_CHUNK_SIZE = 64 * 1024;\n\nconst supportsResponseStream = isReadableStreamSupported &&\n test(() => utils.isReadableStream(new Response('').body));\n\n\nconst resolvers = {\n stream: supportsResponseStream && ((res) => res.body)\n};\n\nisFetchSupported && (((res) => {\n ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {\n !resolvers[type] && (resolvers[type] = utils.isFunction(res[type]) ? (res) => res[type]() :\n (_, config) => {\n throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);\n })\n });\n})(new Response));\n\nconst getBodyLength = async (body) => {\n if (body == null) {\n return 0;\n }\n\n if(utils.isBlob(body)) {\n return body.size;\n }\n\n if(utils.isSpecCompliantForm(body)) {\n const _request = new Request(platform.origin, {\n method: 'POST',\n body,\n });\n return (await _request.arrayBuffer()).byteLength;\n }\n\n if(utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) {\n return body.byteLength;\n }\n\n if(utils.isURLSearchParams(body)) {\n body = body + '';\n }\n\n if(utils.isString(body)) {\n return (await encodeText(body)).byteLength;\n }\n}\n\nconst resolveBodyLength = async (headers, body) => {\n const length = utils.toFiniteNumber(headers.getContentLength());\n\n return length == null ? getBodyLength(body) : length;\n}\n\nexport default isFetchSupported && (async (config) => {\n let {\n url,\n method,\n data,\n signal,\n cancelToken,\n timeout,\n onDownloadProgress,\n onUploadProgress,\n responseType,\n headers,\n withCredentials = 'same-origin',\n fetchOptions\n } = resolveConfig(config);\n\n responseType = responseType ? (responseType + '').toLowerCase() : 'text';\n\n let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);\n\n let request;\n\n const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {\n composedSignal.unsubscribe();\n });\n\n let requestContentLength;\n\n try {\n if (\n onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&\n (requestContentLength = await resolveBodyLength(headers, data)) !== 0\n ) {\n let _request = new Request(url, {\n method: 'POST',\n body: data,\n duplex: \"half\"\n });\n\n let contentTypeHeader;\n\n if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {\n headers.setContentType(contentTypeHeader)\n }\n\n if (_request.body) {\n const [onProgress, flush] = progressEventDecorator(\n requestContentLength,\n progressEventReducer(asyncDecorator(onUploadProgress))\n );\n\n data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);\n }\n }\n\n if (!utils.isString(withCredentials)) {\n withCredentials = withCredentials ? 'include' : 'omit';\n }\n\n // Cloudflare Workers throws when credentials are defined\n // see https://github.com/cloudflare/workerd/issues/902\n const isCredentialsSupported = \"credentials\" in Request.prototype;\n request = new Request(url, {\n ...fetchOptions,\n signal: composedSignal,\n method: method.toUpperCase(),\n headers: headers.normalize().toJSON(),\n body: data,\n duplex: \"half\",\n credentials: isCredentialsSupported ? withCredentials : undefined\n });\n\n let response = await fetch(request);\n\n const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');\n\n if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {\n const options = {};\n\n ['status', 'statusText', 'headers'].forEach(prop => {\n options[prop] = response[prop];\n });\n\n const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length'));\n\n const [onProgress, flush] = onDownloadProgress && progressEventDecorator(\n responseContentLength,\n progressEventReducer(asyncDecorator(onDownloadProgress), true)\n ) || [];\n\n response = new Response(\n trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {\n flush && flush();\n unsubscribe && unsubscribe();\n }),\n options\n );\n }\n\n responseType = responseType || 'text';\n\n let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config);\n\n !isStreamResponse && unsubscribe && unsubscribe();\n\n return await new Promise((resolve, reject) => {\n settle(resolve, reject, {\n data: responseData,\n headers: AxiosHeaders.from(response.headers),\n status: response.status,\n statusText: response.statusText,\n config,\n request\n })\n })\n } catch (err) {\n unsubscribe && unsubscribe();\n\n if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {\n throw Object.assign(\n new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),\n {\n cause: err.cause || err\n }\n )\n }\n\n throw AxiosError.from(err, err && err.code, config, request);\n }\n});\n\n\n","import utils from '../utils.js';\nimport httpAdapter from './http.js';\nimport xhrAdapter from './xhr.js';\nimport fetchAdapter from './fetch.js';\nimport AxiosError from \"../core/AxiosError.js\";\n\nconst knownAdapters = {\n http: httpAdapter,\n xhr: xhrAdapter,\n fetch: fetchAdapter\n}\n\nutils.forEach(knownAdapters, (fn, value) => {\n if (fn) {\n try {\n Object.defineProperty(fn, 'name', {value});\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n Object.defineProperty(fn, 'adapterName', {value});\n }\n});\n\nconst renderReason = (reason) => `- ${reason}`;\n\nconst isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false;\n\nexport default {\n getAdapter: (adapters) => {\n adapters = utils.isArray(adapters) ? adapters : [adapters];\n\n const {length} = adapters;\n let nameOrAdapter;\n let adapter;\n\n const rejectedReasons = {};\n\n for (let i = 0; i < length; i++) {\n nameOrAdapter = adapters[i];\n let id;\n\n adapter = nameOrAdapter;\n\n if (!isResolvedHandle(nameOrAdapter)) {\n adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];\n\n if (adapter === undefined) {\n throw new AxiosError(`Unknown adapter '${id}'`);\n }\n }\n\n if (adapter) {\n break;\n }\n\n rejectedReasons[id || '#' + i] = adapter;\n }\n\n if (!adapter) {\n\n const reasons = Object.entries(rejectedReasons)\n .map(([id, state]) => `adapter ${id} ` +\n (state === false ? 'is not supported by the environment' : 'is not available in the build')\n );\n\n let s = length ?\n (reasons.length > 1 ? 'since :\\n' + reasons.map(renderReason).join('\\n') : ' ' + renderReason(reasons[0])) :\n 'as no adapter specified';\n\n throw new AxiosError(\n `There is no suitable adapter to dispatch the request ` + s,\n 'ERR_NOT_SUPPORT'\n );\n }\n\n return adapter;\n },\n adapters: knownAdapters\n}\n","'use strict';\n\nimport transformData from './transformData.js';\nimport isCancel from '../cancel/isCancel.js';\nimport defaults from '../defaults/index.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport adapters from \"../adapters/adapters.js\";\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n *\n * @param {Object} config The config that is to be used for the request\n *\n * @returns {void}\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new CanceledError(null, config);\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n *\n * @returns {Promise} The Promise to be fulfilled\n */\nexport default function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n config.headers = AxiosHeaders.from(config.headers);\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.transformRequest\n );\n\n if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {\n config.headers.setContentType('application/x-www-form-urlencoded', false);\n }\n\n const adapter = adapters.getAdapter(config.adapter || defaults.adapter);\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n config.transformResponse,\n response\n );\n\n response.headers = AxiosHeaders.from(response.headers);\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n config.transformResponse,\n reason.response\n );\n reason.response.headers = AxiosHeaders.from(reason.response.headers);\n }\n }\n\n return Promise.reject(reason);\n });\n}\n","export const VERSION = \"1.7.9\";","'use strict';\n\nimport {VERSION} from '../env/data.js';\nimport AxiosError from '../core/AxiosError.js';\n\nconst validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nconst deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n *\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n *\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return (value, opt, opts) => {\n if (validator === false) {\n throw new AxiosError(\n formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),\n AxiosError.ERR_DEPRECATED\n );\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\nvalidators.spelling = function spelling(correctSpelling) {\n return (value, opt) => {\n // eslint-disable-next-line no-console\n console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);\n return true;\n }\n};\n\n/**\n * Assert object's properties type\n *\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n *\n * @returns {object}\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);\n }\n const keys = Object.keys(options);\n let i = keys.length;\n while (i-- > 0) {\n const opt = keys[i];\n const validator = schema[opt];\n if (validator) {\n const value = options[opt];\n const result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);\n }\n }\n}\n\nexport default {\n assertOptions,\n validators\n};\n","'use strict';\n\nimport utils from './../utils.js';\nimport buildURL from '../helpers/buildURL.js';\nimport InterceptorManager from './InterceptorManager.js';\nimport dispatchRequest from './dispatchRequest.js';\nimport mergeConfig from './mergeConfig.js';\nimport buildFullPath from './buildFullPath.js';\nimport validator from '../helpers/validator.js';\nimport AxiosHeaders from './AxiosHeaders.js';\n\nconst validators = validator.validators;\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n *\n * @return {Axios} A new instance of Axios\n */\nclass Axios {\n constructor(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n }\n\n /**\n * Dispatch a request\n *\n * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)\n * @param {?Object} config\n *\n * @returns {Promise} The Promise to be fulfilled\n */\n async request(configOrUrl, config) {\n try {\n return await this._request(configOrUrl, config);\n } catch (err) {\n if (err instanceof Error) {\n let dummy = {};\n\n Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());\n\n // slice off the Error: ... line\n const stack = dummy.stack ? dummy.stack.replace(/^.+\\n/, '') : '';\n try {\n if (!err.stack) {\n err.stack = stack;\n // match without the 2 top stack lines\n } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\\n.+\\n/, ''))) {\n err.stack += '\\n' + stack\n }\n } catch (e) {\n // ignore the case where \"stack\" is an un-writable property\n }\n }\n\n throw err;\n }\n }\n\n _request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n const {transitional, paramsSerializer, headers} = config;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n if (paramsSerializer != null) {\n if (utils.isFunction(paramsSerializer)) {\n config.paramsSerializer = {\n serialize: paramsSerializer\n }\n } else {\n validator.assertOptions(paramsSerializer, {\n encode: validators.function,\n serialize: validators.function\n }, true);\n }\n }\n\n validator.assertOptions(config, {\n baseUrl: validators.spelling('baseURL'),\n withXsrfToken: validators.spelling('withXSRFToken')\n }, true);\n\n // Set config.method\n config.method = (config.method || this.defaults.method || 'get').toLowerCase();\n\n // Flatten headers\n let contextHeaders = headers && utils.merge(\n headers.common,\n headers[config.method]\n );\n\n headers && utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n (method) => {\n delete headers[method];\n }\n );\n\n config.headers = AxiosHeaders.concat(contextHeaders, headers);\n\n // filter out skipped interceptors\n const requestInterceptorChain = [];\n let synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n const responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n let promise;\n let i = 0;\n let len;\n\n if (!synchronousRequestInterceptors) {\n const chain = [dispatchRequest.bind(this), undefined];\n chain.unshift.apply(chain, requestInterceptorChain);\n chain.push.apply(chain, responseInterceptorChain);\n len = chain.length;\n\n promise = Promise.resolve(config);\n\n while (i < len) {\n promise = promise.then(chain[i++], chain[i++]);\n }\n\n return promise;\n }\n\n len = requestInterceptorChain.length;\n\n let newConfig = config;\n\n i = 0;\n\n while (i < len) {\n const onFulfilled = requestInterceptorChain[i++];\n const onRejected = requestInterceptorChain[i++];\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected.call(this, error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest.call(this, newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n i = 0;\n len = responseInterceptorChain.length;\n\n while (i < len) {\n promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);\n }\n\n return promise;\n }\n\n getUri(config) {\n config = mergeConfig(this.defaults, config);\n const fullPath = buildFullPath(config.baseURL, config.url);\n return buildURL(fullPath, config.params, config.paramsSerializer);\n }\n}\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n\n function generateHTTPMethod(isForm) {\n return function httpMethod(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n headers: isForm ? {\n 'Content-Type': 'multipart/form-data'\n } : {},\n url,\n data\n }));\n };\n }\n\n Axios.prototype[method] = generateHTTPMethod();\n\n Axios.prototype[method + 'Form'] = generateHTTPMethod(true);\n});\n\nexport default Axios;\n","'use strict';\n\nimport CanceledError from './CanceledError.js';\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @param {Function} executor The executor function.\n *\n * @returns {CancelToken}\n */\nclass CancelToken {\n constructor(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n let resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n const token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(cancel => {\n if (!token._listeners) return;\n\n let i = token._listeners.length;\n\n while (i-- > 0) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = onfulfilled => {\n let _resolve;\n // eslint-disable-next-line func-names\n const promise = new Promise(resolve => {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message, config, request) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new CanceledError(message, config, request);\n resolvePromise(token.reason);\n });\n }\n\n /**\n * Throws a `CanceledError` if cancellation has been requested.\n */\n throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n }\n\n /**\n * Subscribe to the cancel signal\n */\n\n subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n }\n\n /**\n * Unsubscribe from the cancel signal\n */\n\n unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n const index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n }\n\n toAbortSignal() {\n const controller = new AbortController();\n\n const abort = (err) => {\n controller.abort(err);\n };\n\n this.subscribe(abort);\n\n controller.signal.unsubscribe = () => this.unsubscribe(abort);\n\n return controller.signal;\n }\n\n /**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\n static source() {\n let cancel;\n const token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token,\n cancel\n };\n }\n}\n\nexport default CancelToken;\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n *\n * @returns {Function}\n */\nexport default function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n *\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nexport default function isAxiosError(payload) {\n return utils.isObject(payload) && (payload.isAxiosError === true);\n}\n","const HttpStatusCode = {\n Continue: 100,\n SwitchingProtocols: 101,\n Processing: 102,\n EarlyHints: 103,\n Ok: 200,\n Created: 201,\n Accepted: 202,\n NonAuthoritativeInformation: 203,\n NoContent: 204,\n ResetContent: 205,\n PartialContent: 206,\n MultiStatus: 207,\n AlreadyReported: 208,\n ImUsed: 226,\n MultipleChoices: 300,\n MovedPermanently: 301,\n Found: 302,\n SeeOther: 303,\n NotModified: 304,\n UseProxy: 305,\n Unused: 306,\n TemporaryRedirect: 307,\n PermanentRedirect: 308,\n BadRequest: 400,\n Unauthorized: 401,\n PaymentRequired: 402,\n Forbidden: 403,\n NotFound: 404,\n MethodNotAllowed: 405,\n NotAcceptable: 406,\n ProxyAuthenticationRequired: 407,\n RequestTimeout: 408,\n Conflict: 409,\n Gone: 410,\n LengthRequired: 411,\n PreconditionFailed: 412,\n PayloadTooLarge: 413,\n UriTooLong: 414,\n UnsupportedMediaType: 415,\n RangeNotSatisfiable: 416,\n ExpectationFailed: 417,\n ImATeapot: 418,\n MisdirectedRequest: 421,\n UnprocessableEntity: 422,\n Locked: 423,\n FailedDependency: 424,\n TooEarly: 425,\n UpgradeRequired: 426,\n PreconditionRequired: 428,\n TooManyRequests: 429,\n RequestHeaderFieldsTooLarge: 431,\n UnavailableForLegalReasons: 451,\n InternalServerError: 500,\n NotImplemented: 501,\n BadGateway: 502,\n ServiceUnavailable: 503,\n GatewayTimeout: 504,\n HttpVersionNotSupported: 505,\n VariantAlsoNegotiates: 506,\n InsufficientStorage: 507,\n LoopDetected: 508,\n NotExtended: 510,\n NetworkAuthenticationRequired: 511,\n};\n\nObject.entries(HttpStatusCode).forEach(([key, value]) => {\n HttpStatusCode[value] = key;\n});\n\nexport default HttpStatusCode;\n","'use strict';\n\nimport utils from './utils.js';\nimport bind from './helpers/bind.js';\nimport Axios from './core/Axios.js';\nimport mergeConfig from './core/mergeConfig.js';\nimport defaults from './defaults/index.js';\nimport formDataToJSON from './helpers/formDataToJSON.js';\nimport CanceledError from './cancel/CanceledError.js';\nimport CancelToken from './cancel/CancelToken.js';\nimport isCancel from './cancel/isCancel.js';\nimport {VERSION} from './env/data.js';\nimport toFormData from './helpers/toFormData.js';\nimport AxiosError from './core/AxiosError.js';\nimport spread from './helpers/spread.js';\nimport isAxiosError from './helpers/isAxiosError.js';\nimport AxiosHeaders from \"./core/AxiosHeaders.js\";\nimport adapters from './adapters/adapters.js';\nimport HttpStatusCode from './helpers/HttpStatusCode.js';\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n *\n * @returns {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n const context = new Axios(defaultConfig);\n const instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});\n\n // Copy context to instance\n utils.extend(instance, context, null, {allOwnKeys: true});\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nconst axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.CanceledError = CanceledError;\naxios.CancelToken = CancelToken;\naxios.isCancel = isCancel;\naxios.VERSION = VERSION;\naxios.toFormData = toFormData;\n\n// Expose AxiosError class\naxios.AxiosError = AxiosError;\n\n// alias for CanceledError for backward compatibility\naxios.Cancel = axios.CanceledError;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\n\naxios.spread = spread;\n\n// Expose isAxiosError\naxios.isAxiosError = isAxiosError;\n\n// Expose mergeConfig\naxios.mergeConfig = mergeConfig;\n\naxios.AxiosHeaders = AxiosHeaders;\n\naxios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);\n\naxios.getAdapter = adapters.getAdapter;\n\naxios.HttpStatusCode = HttpStatusCode;\n\naxios.default = axios;\n\n// this module should only have a default export\nexport default axios\n","import axios from './lib/axios.js';\n\n// This module is intended to unwrap Axios default export as named.\n// Keep top-level export same with static properties\n// so that it can keep same with es module or cjs\nconst {\n Axios,\n AxiosError,\n CanceledError,\n isCancel,\n CancelToken,\n VERSION,\n all,\n Cancel,\n isAxiosError,\n spread,\n toFormData,\n AxiosHeaders,\n HttpStatusCode,\n formToJSON,\n getAdapter,\n mergeConfig\n} = axios;\n\nexport {\n axios as default,\n Axios,\n AxiosError,\n CanceledError,\n isCancel,\n CancelToken,\n VERSION,\n all,\n Cancel,\n isAxiosError,\n spread,\n toFormData,\n AxiosHeaders,\n HttpStatusCode,\n formToJSON,\n getAdapter,\n mergeConfig\n}\n"],"names":["AxiosError","utils","prototype","toFormData","encode","URLSearchParams","FormData","Blob","platform","AxiosHeaders","defaults","isCancel","CanceledError","mergeConfig","composeSignals","VERSION","validators","Axios","InterceptorManager","CancelToken","spread","isAxiosError","HttpStatusCode","axios"],"mappings":";AAEe,SAAS,IAAI,CAAC,EAAE,EAAE,OAAO,EAAE;AAC1C,EAAE,OAAO,SAAS,IAAI,GAAG;AACzB,IAAI,OAAO,EAAE,CAAC,KAAK,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;AACxC,GAAG,CAAC;AACJ;;ACFA;AACA;AACA,MAAM,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC,SAAS,CAAC;AACpC,MAAM,CAAC,cAAc,CAAC,GAAG,MAAM,CAAC;AAChC;AACA,MAAM,MAAM,GAAG,CAAC,KAAK,IAAI,KAAK,IAAI;AAClC,IAAI,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACrC,IAAI,OAAO,KAAK,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AACvE,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACxB;AACA,MAAM,UAAU,GAAG,CAAC,IAAI,KAAK;AAC7B,EAAE,IAAI,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;AAC5B,EAAE,OAAO,CAAC,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,KAAK,IAAI;AAC1C,EAAC;AACD;AACA,MAAM,UAAU,GAAG,IAAI,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,IAAI,CAAC;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,WAAW,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,QAAQ,CAAC,GAAG,EAAE;AACvB,EAAE,OAAO,GAAG,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,WAAW,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,WAAW,CAAC;AACvG,OAAO,UAAU,CAAC,GAAG,CAAC,WAAW,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC,WAAW,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AAC7E,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,UAAU,CAAC,aAAa,CAAC,CAAC;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,iBAAiB,CAAC,GAAG,EAAE;AAChC,EAAE,IAAI,MAAM,CAAC;AACb,EAAE,IAAI,CAAC,OAAO,WAAW,KAAK,WAAW,MAAM,WAAW,CAAC,MAAM,CAAC,EAAE;AACpE,IAAI,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACrC,GAAG,MAAM;AACT,IAAI,MAAM,GAAG,CAAC,GAAG,MAAM,GAAG,CAAC,MAAM,CAAC,KAAK,aAAa,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;AAClE,GAAG;AACH,EAAE,OAAO,MAAM,CAAC;AAChB,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,UAAU,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,KAAK,KAAK,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,SAAS,GAAG,KAAK,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,KAAK,CAAC;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,GAAG,KAAK;AAC/B,EAAE,IAAI,MAAM,CAAC,GAAG,CAAC,KAAK,QAAQ,EAAE;AAChC,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA,EAAE,MAAM,SAAS,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC;AACxC,EAAE,OAAO,CAAC,SAAS,KAAK,IAAI,IAAI,SAAS,KAAK,MAAM,CAAC,SAAS,IAAI,MAAM,CAAC,cAAc,CAAC,SAAS,CAAC,KAAK,IAAI,KAAK,EAAE,MAAM,CAAC,WAAW,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,QAAQ,IAAI,GAAG,CAAC,CAAC;AAC1K,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,UAAU,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,GAAG,KAAK,QAAQ,CAAC,GAAG,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AAChE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,UAAU,GAAG,CAAC,KAAK,KAAK;AAC9B,EAAE,IAAI,IAAI,CAAC;AACX,EAAE,OAAO,KAAK;AACd,IAAI,CAAC,OAAO,QAAQ,KAAK,UAAU,IAAI,KAAK,YAAY,QAAQ;AAChE,MAAM,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC;AAC9B,QAAQ,CAAC,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,UAAU;AAC7C;AACA,SAAS,IAAI,KAAK,QAAQ,IAAI,UAAU,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,KAAK,CAAC,QAAQ,EAAE,KAAK,mBAAmB,CAAC;AACrG,OAAO;AACP,KAAK;AACL,GAAG;AACH,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,iBAAiB,GAAG,UAAU,CAAC,iBAAiB,CAAC,CAAC;AACxD;AACA,MAAM,CAAC,gBAAgB,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,CAAC,GAAG,CAAC,gBAAgB,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;AAClI;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,IAAI;AAC9B,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,oCAAoC,EAAE,EAAE,CAAC,CAAC;AACrE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,OAAO,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC,UAAU,GAAG,KAAK,CAAC,GAAG,EAAE,EAAE;AACrD;AACA,EAAE,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,WAAW,EAAE;AAClD,IAAI,OAAO;AACX,GAAG;AACH;AACA,EAAE,IAAI,CAAC,CAAC;AACR,EAAE,IAAI,CAAC,CAAC;AACR;AACA;AACA,EAAE,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;AAC/B;AACA,IAAI,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;AAChB,GAAG;AACH;AACA,EAAE,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE;AACpB;AACA,IAAI,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AAC5C,MAAM,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AACpC,KAAK;AACL,GAAG,MAAM;AACT;AACA,IAAI,MAAM,IAAI,GAAG,UAAU,GAAG,MAAM,CAAC,mBAAmB,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjF,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC;AAC5B,IAAI,IAAI,GAAG,CAAC;AACZ;AACA,IAAI,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;AAC9B,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,MAAM,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AACxC,KAAK;AACL,GAAG;AACH,CAAC;AACD;AACA,SAAS,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE;AAC3B,EAAE,GAAG,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;AAC1B,EAAE,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAChC,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;AACtB,EAAE,IAAI,IAAI,CAAC;AACX,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AAClB,IAAI,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AACnB,IAAI,IAAI,GAAG,KAAK,IAAI,CAAC,WAAW,EAAE,EAAE;AACpC,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL,GAAG;AACH,EAAE,OAAO,IAAI,CAAC;AACd,CAAC;AACD;AACA,MAAM,OAAO,GAAG,CAAC,MAAM;AACvB;AACA,EAAE,IAAI,OAAO,UAAU,KAAK,WAAW,EAAE,OAAO,UAAU,CAAC;AAC3D,EAAE,OAAO,OAAO,IAAI,KAAK,WAAW,GAAG,IAAI,IAAI,OAAO,MAAM,KAAK,WAAW,GAAG,MAAM,GAAG,MAAM,CAAC;AAC/F,CAAC,GAAG,CAAC;AACL;AACA,MAAM,gBAAgB,GAAG,CAAC,OAAO,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,OAAO,KAAK,OAAO,CAAC;AACnF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,KAAK,8BAA8B;AAC5C,EAAE,MAAM,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,EAAE,CAAC;AAC1D,EAAE,MAAM,MAAM,GAAG,EAAE,CAAC;AACpB,EAAE,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,GAAG,KAAK;AACpC,IAAI,MAAM,SAAS,GAAG,QAAQ,IAAI,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,GAAG,CAAC;AAC9D,IAAI,IAAI,aAAa,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,IAAI,aAAa,CAAC,GAAG,CAAC,EAAE;AAChE,MAAM,MAAM,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,GAAG,CAAC,CAAC;AACxD,KAAK,MAAM,IAAI,aAAa,CAAC,GAAG,CAAC,EAAE;AACnC,MAAM,MAAM,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;AACzC,KAAK,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE;AAC7B,MAAM,MAAM,CAAC,SAAS,CAAC,GAAG,GAAG,CAAC,KAAK,EAAE,CAAC;AACtC,KAAK,MAAM;AACX,MAAM,MAAM,CAAC,SAAS,CAAC,GAAG,GAAG,CAAC;AAC9B,KAAK;AACL,IAAG;AACH;AACA,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AACpD,IAAI,SAAS,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC;AACvD,GAAG;AACH,EAAE,OAAO,MAAM,CAAC;AAChB,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,UAAU,CAAC,EAAE,EAAE,KAAK;AACpD,EAAE,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK;AAC3B,IAAI,IAAI,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,EAAE;AACpC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;AAClC,KAAK,MAAM;AACX,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC;AACnB,KAAK;AACL,GAAG,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;AACnB,EAAE,OAAO,CAAC,CAAC;AACX,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,OAAO,KAAK;AAC9B,EAAE,IAAI,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE;AACxC,IAAI,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAC/B,GAAG;AACH,EAAE,OAAO,OAAO,CAAC;AACjB,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,WAAW,EAAE,gBAAgB,EAAE,KAAK,EAAE,WAAW,KAAK;AACxE,EAAE,WAAW,CAAC,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;AACjF,EAAE,WAAW,CAAC,SAAS,CAAC,WAAW,GAAG,WAAW,CAAC;AAClD,EAAE,MAAM,CAAC,cAAc,CAAC,WAAW,EAAE,OAAO,EAAE;AAC9C,IAAI,KAAK,EAAE,gBAAgB,CAAC,SAAS;AACrC,GAAG,CAAC,CAAC;AACL,EAAE,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AACvD,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,YAAY,GAAG,CAAC,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,KAAK;AACjE,EAAE,IAAI,KAAK,CAAC;AACZ,EAAE,IAAI,CAAC,CAAC;AACR,EAAE,IAAI,IAAI,CAAC;AACX,EAAE,MAAM,MAAM,GAAG,EAAE,CAAC;AACpB;AACA,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;AAC1B;AACA,EAAE,IAAI,SAAS,IAAI,IAAI,EAAE,OAAO,OAAO,CAAC;AACxC;AACA,EAAE,GAAG;AACL,IAAI,KAAK,GAAG,MAAM,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC;AAClD,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC;AACrB,IAAI,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AACpB,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,IAAI,CAAC,CAAC,UAAU,IAAI,UAAU,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;AAClF,QAAQ,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;AACxC,QAAQ,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAC5B,OAAO;AACP,KAAK;AACL,IAAI,SAAS,GAAG,MAAM,KAAK,KAAK,IAAI,cAAc,CAAC,SAAS,CAAC,CAAC;AAC9D,GAAG,QAAQ,SAAS,KAAK,CAAC,MAAM,IAAI,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,SAAS,KAAK,MAAM,CAAC,SAAS,EAAE;AACnG;AACA,EAAE,OAAO,OAAO,CAAC;AACjB,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,GAAG,EAAE,YAAY,EAAE,QAAQ,KAAK;AAClD,EAAE,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AACpB,EAAE,IAAI,QAAQ,KAAK,SAAS,IAAI,QAAQ,GAAG,GAAG,CAAC,MAAM,EAAE;AACvD,IAAI,QAAQ,GAAG,GAAG,CAAC,MAAM,CAAC;AAC1B,GAAG;AACH,EAAE,QAAQ,IAAI,YAAY,CAAC,MAAM,CAAC;AAClC,EAAE,MAAM,SAAS,GAAG,GAAG,CAAC,OAAO,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC;AACxD,EAAE,OAAO,SAAS,KAAK,CAAC,CAAC,IAAI,SAAS,KAAK,QAAQ,CAAC;AACpD,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,OAAO,GAAG,CAAC,KAAK,KAAK;AAC3B,EAAE,IAAI,CAAC,KAAK,EAAE,OAAO,IAAI,CAAC;AAC1B,EAAE,IAAI,OAAO,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;AACnC,EAAE,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC;AACvB,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,OAAO,IAAI,CAAC;AAChC,EAAE,MAAM,GAAG,GAAG,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC;AAC3B,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AAClB,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AACtB,GAAG;AACH,EAAE,OAAO,GAAG,CAAC;AACb,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,YAAY,GAAG,CAAC,UAAU,IAAI;AACpC;AACA,EAAE,OAAO,KAAK,IAAI;AAClB,IAAI,OAAO,UAAU,IAAI,KAAK,YAAY,UAAU,CAAC;AACrD,GAAG,CAAC;AACJ,CAAC,EAAE,OAAO,UAAU,KAAK,WAAW,IAAI,cAAc,CAAC,UAAU,CAAC,CAAC,CAAC;AACpE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,YAAY,GAAG,CAAC,GAAG,EAAE,EAAE,KAAK;AAClC,EAAE,MAAM,SAAS,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAChD;AACA,EAAE,MAAM,QAAQ,GAAG,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACvC;AACA,EAAE,IAAI,MAAM,CAAC;AACb;AACA,EAAE,OAAO,CAAC,MAAM,GAAG,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE;AACrD,IAAI,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC;AAC9B,IAAI,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AACnC,GAAG;AACH,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,MAAM,EAAE,GAAG,KAAK;AAClC,EAAE,IAAI,OAAO,CAAC;AACd,EAAE,MAAM,GAAG,GAAG,EAAE,CAAC;AACjB;AACA,EAAE,OAAO,CAAC,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,IAAI,EAAE;AAChD,IAAI,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACtB,GAAG;AACH;AACA,EAAE,OAAO,GAAG,CAAC;AACb,EAAC;AACD;AACA;AACA,MAAM,UAAU,GAAG,UAAU,CAAC,iBAAiB,CAAC,CAAC;AACjD;AACA,MAAM,WAAW,GAAG,GAAG,IAAI;AAC3B,EAAE,OAAO,GAAG,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,uBAAuB;AAC1D,IAAI,SAAS,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE;AACjC,MAAM,OAAO,EAAE,CAAC,WAAW,EAAE,GAAG,EAAE,CAAC;AACnC,KAAK;AACL,GAAG,CAAC;AACJ,CAAC,CAAC;AACF;AACA;AACA,MAAM,cAAc,GAAG,CAAC,CAAC,CAAC,cAAc,CAAC,KAAK,CAAC,GAAG,EAAE,IAAI,KAAK,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC;AAC/G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;AACtC;AACA,MAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,OAAO,KAAK;AAC5C,EAAE,MAAM,WAAW,GAAG,MAAM,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC;AAC5D,EAAE,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAChC;AACA,EAAE,OAAO,CAAC,WAAW,EAAE,CAAC,UAAU,EAAE,IAAI,KAAK;AAC7C,IAAI,IAAI,GAAG,CAAC;AACZ,IAAI,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,UAAU,EAAE,IAAI,EAAE,GAAG,CAAC,MAAM,KAAK,EAAE;AAC1D,MAAM,kBAAkB,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,UAAU,CAAC;AACnD,KAAK;AACL,GAAG,CAAC,CAAC;AACL;AACA,EAAE,MAAM,CAAC,gBAAgB,CAAC,GAAG,EAAE,kBAAkB,CAAC,CAAC;AACnD,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,GAAG,KAAK;AAC/B,EAAE,iBAAiB,CAAC,GAAG,EAAE,CAAC,UAAU,EAAE,IAAI,KAAK;AAC/C;AACA,IAAI,IAAI,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE;AACnF,MAAM,OAAO,KAAK,CAAC;AACnB,KAAK;AACL;AACA,IAAI,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC;AAC5B;AACA,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,OAAO;AACnC;AACA,IAAI,UAAU,CAAC,UAAU,GAAG,KAAK,CAAC;AAClC;AACA,IAAI,IAAI,UAAU,IAAI,UAAU,EAAE;AAClC,MAAM,UAAU,CAAC,QAAQ,GAAG,KAAK,CAAC;AAClC,MAAM,OAAO;AACb,KAAK;AACL;AACA,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE;AACzB,MAAM,UAAU,CAAC,GAAG,GAAG,MAAM;AAC7B,QAAQ,MAAM,KAAK,CAAC,qCAAqC,GAAG,IAAI,GAAG,IAAI,CAAC,CAAC;AACzE,OAAO,CAAC;AACR,KAAK;AACL,GAAG,CAAC,CAAC;AACL,EAAC;AACD;AACA,MAAM,WAAW,GAAG,CAAC,aAAa,EAAE,SAAS,KAAK;AAClD,EAAE,MAAM,GAAG,GAAG,EAAE,CAAC;AACjB;AACA,EAAE,MAAM,MAAM,GAAG,CAAC,GAAG,KAAK;AAC1B,IAAI,GAAG,CAAC,OAAO,CAAC,KAAK,IAAI;AACzB,MAAM,GAAG,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC;AACxB,KAAK,CAAC,CAAC;AACP,IAAG;AACH;AACA,EAAE,OAAO,CAAC,aAAa,CAAC,GAAG,MAAM,CAAC,aAAa,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC;AAClG;AACA,EAAE,OAAO,GAAG,CAAC;AACb,EAAC;AACD;AACA,MAAM,IAAI,GAAG,MAAM,GAAE;AACrB;AACA,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,YAAY,KAAK;AAChD,EAAE,OAAO,KAAK,IAAI,IAAI,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,GAAG,CAAC,KAAK,CAAC,GAAG,KAAK,GAAG,YAAY,CAAC;AACjF,EAAC;AACD;AACA,MAAM,KAAK,GAAG,6BAA4B;AAC1C;AACA,MAAM,KAAK,GAAG,YAAY,CAAC;AAC3B;AACA,MAAM,QAAQ,GAAG;AACjB,EAAE,KAAK;AACP,EAAE,KAAK;AACP,EAAE,WAAW,EAAE,KAAK,GAAG,KAAK,CAAC,WAAW,EAAE,GAAG,KAAK;AAClD,EAAC;AACD;AACA,MAAM,cAAc,GAAG,CAAC,IAAI,GAAG,EAAE,EAAE,QAAQ,GAAG,QAAQ,CAAC,WAAW,KAAK;AACvE,EAAE,IAAI,GAAG,GAAG,EAAE,CAAC;AACf,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC;AAC5B,EAAE,OAAO,IAAI,EAAE,EAAE;AACjB,IAAI,GAAG,IAAI,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,MAAM,CAAC,CAAC,EAAC;AAC7C,GAAG;AACH;AACA,EAAE,OAAO,GAAG,CAAC;AACb,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,mBAAmB,CAAC,KAAK,EAAE;AACpC,EAAE,OAAO,CAAC,EAAE,KAAK,IAAI,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,WAAW,CAAC,KAAK,UAAU,IAAI,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;AACrH,CAAC;AACD;AACA,MAAM,YAAY,GAAG,CAAC,GAAG,KAAK;AAC9B,EAAE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC;AAC9B;AACA,EAAE,MAAM,KAAK,GAAG,CAAC,MAAM,EAAE,CAAC,KAAK;AAC/B;AACA,IAAI,IAAI,QAAQ,CAAC,MAAM,CAAC,EAAE;AAC1B,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;AACtC,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,GAAG,EAAE,QAAQ,IAAI,MAAM,CAAC,EAAE;AAChC,QAAQ,KAAK,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC;AAC1B,QAAQ,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;AACjD;AACA,QAAQ,OAAO,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK;AACxC,UAAU,MAAM,YAAY,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;AACnD,UAAU,CAAC,WAAW,CAAC,YAAY,CAAC,KAAK,MAAM,CAAC,GAAG,CAAC,GAAG,YAAY,CAAC,CAAC;AACrE,SAAS,CAAC,CAAC;AACX;AACA,QAAQ,KAAK,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC;AAC7B;AACA,QAAQ,OAAO,MAAM,CAAC;AACtB,OAAO;AACP,KAAK;AACL;AACA,IAAI,OAAO,MAAM,CAAC;AAClB,IAAG;AACH;AACA,EAAE,OAAO,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;AACvB,EAAC;AACD;AACA,MAAM,SAAS,GAAG,UAAU,CAAC,eAAe,CAAC,CAAC;AAC9C;AACA,MAAM,UAAU,GAAG,CAAC,KAAK;AACzB,EAAE,KAAK,KAAK,QAAQ,CAAC,KAAK,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACvG;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,CAAC,qBAAqB,EAAE,oBAAoB,KAAK;AACxE,EAAE,IAAI,qBAAqB,EAAE;AAC7B,IAAI,OAAO,YAAY,CAAC;AACxB,GAAG;AACH;AACA,EAAE,OAAO,oBAAoB,GAAG,CAAC,CAAC,KAAK,EAAE,SAAS,KAAK;AACvD,IAAI,OAAO,CAAC,gBAAgB,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK;AAC5D,MAAM,IAAI,MAAM,KAAK,OAAO,IAAI,IAAI,KAAK,KAAK,EAAE;AAChD,QAAQ,SAAS,CAAC,MAAM,IAAI,SAAS,CAAC,KAAK,EAAE,EAAE,CAAC;AAChD,OAAO;AACP,KAAK,EAAE,KAAK,CAAC,CAAC;AACd;AACA,IAAI,OAAO,CAAC,EAAE,KAAK;AACnB,MAAM,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACzB,MAAM,OAAO,CAAC,WAAW,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AACtC,KAAK;AACL,GAAG,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,UAAU,CAAC,EAAE,CAAC,CAAC;AAC5D,CAAC;AACD,EAAE,OAAO,YAAY,KAAK,UAAU;AACpC,EAAE,UAAU,CAAC,OAAO,CAAC,WAAW,CAAC;AACjC,CAAC,CAAC;AACF;AACA,MAAM,IAAI,GAAG,OAAO,cAAc,KAAK,WAAW;AAClD,EAAE,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,CAAC,QAAQ,IAAI,aAAa,CAAC,CAAC;AACxG;AACA;AACA;AACA,gBAAe;AACf,EAAE,OAAO;AACT,EAAE,aAAa;AACf,EAAE,QAAQ;AACV,EAAE,UAAU;AACZ,EAAE,iBAAiB;AACnB,EAAE,QAAQ;AACV,EAAE,QAAQ;AACV,EAAE,SAAS;AACX,EAAE,QAAQ;AACV,EAAE,aAAa;AACf,EAAE,gBAAgB;AAClB,EAAE,SAAS;AACX,EAAE,UAAU;AACZ,EAAE,SAAS;AACX,EAAE,WAAW;AACb,EAAE,MAAM;AACR,EAAE,MAAM;AACR,EAAE,MAAM;AACR,EAAE,QAAQ;AACV,EAAE,UAAU;AACZ,EAAE,QAAQ;AACV,EAAE,iBAAiB;AACnB,EAAE,YAAY;AACd,EAAE,UAAU;AACZ,EAAE,OAAO;AACT,EAAE,KAAK;AACP,EAAE,MAAM;AACR,EAAE,IAAI;AACN,EAAE,QAAQ;AACV,EAAE,QAAQ;AACV,EAAE,YAAY;AACd,EAAE,MAAM;AACR,EAAE,UAAU;AACZ,EAAE,QAAQ;AACV,EAAE,OAAO;AACT,EAAE,YAAY;AACd,EAAE,QAAQ;AACV,EAAE,UAAU;AACZ,EAAE,cAAc;AAChB,EAAE,UAAU,EAAE,cAAc;AAC5B,EAAE,iBAAiB;AACnB,EAAE,aAAa;AACf,EAAE,WAAW;AACb,EAAE,WAAW;AACb,EAAE,IAAI;AACN,EAAE,cAAc;AAChB,EAAE,OAAO;AACT,EAAE,MAAM,EAAE,OAAO;AACjB,EAAE,gBAAgB;AAClB,EAAE,QAAQ;AACV,EAAE,cAAc;AAChB,EAAE,mBAAmB;AACrB,EAAE,YAAY;AACd,EAAE,SAAS;AACX,EAAE,UAAU;AACZ,EAAE,YAAY,EAAE,aAAa;AAC7B,EAAE,IAAI;AACN,CAAC;;ACnvBD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,YAAU,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE;AAC9D,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACnB;AACA,EAAE,IAAI,KAAK,CAAC,iBAAiB,EAAE;AAC/B,IAAI,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;AACpD,GAAG,MAAM;AACT,IAAI,IAAI,CAAC,KAAK,GAAG,CAAC,IAAI,KAAK,EAAE,EAAE,KAAK,CAAC;AACrC,GAAG;AACH;AACA,EAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;AACzB,EAAE,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;AAC3B,EAAE,IAAI,KAAK,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC;AAC7B,EAAE,MAAM,KAAK,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC;AACnC,EAAE,OAAO,KAAK,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,CAAC;AACtC,EAAE,IAAI,QAAQ,EAAE;AAChB,IAAI,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAC7B,IAAI,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC,MAAM,GAAG,IAAI,CAAC;AAC3D,GAAG;AACH,CAAC;AACD;AACAC,OAAK,CAAC,QAAQ,CAACD,YAAU,EAAE,KAAK,EAAE;AAClC,EAAE,MAAM,EAAE,SAAS,MAAM,GAAG;AAC5B,IAAI,OAAO;AACX;AACA,MAAM,OAAO,EAAE,IAAI,CAAC,OAAO;AAC3B,MAAM,IAAI,EAAE,IAAI,CAAC,IAAI;AACrB;AACA,MAAM,WAAW,EAAE,IAAI,CAAC,WAAW;AACnC,MAAM,MAAM,EAAE,IAAI,CAAC,MAAM;AACzB;AACA,MAAM,QAAQ,EAAE,IAAI,CAAC,QAAQ;AAC7B,MAAM,UAAU,EAAE,IAAI,CAAC,UAAU;AACjC,MAAM,YAAY,EAAE,IAAI,CAAC,YAAY;AACrC,MAAM,KAAK,EAAE,IAAI,CAAC,KAAK;AACvB;AACA,MAAM,MAAM,EAAEC,OAAK,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC;AAC7C,MAAM,IAAI,EAAE,IAAI,CAAC,IAAI;AACrB,MAAM,MAAM,EAAE,IAAI,CAAC,MAAM;AACzB,KAAK,CAAC;AACN,GAAG;AACH,CAAC,CAAC,CAAC;AACH;AACA,MAAMC,WAAS,GAAGF,YAAU,CAAC,SAAS,CAAC;AACvC,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB;AACA;AACA,EAAE,sBAAsB;AACxB,EAAE,gBAAgB;AAClB,EAAE,cAAc;AAChB,EAAE,WAAW;AACb,EAAE,aAAa;AACf,EAAE,2BAA2B;AAC7B,EAAE,gBAAgB;AAClB,EAAE,kBAAkB;AACpB,EAAE,iBAAiB;AACnB,EAAE,cAAc;AAChB,EAAE,iBAAiB;AACnB,EAAE,iBAAiB;AACnB;AACA,CAAC,CAAC,OAAO,CAAC,IAAI,IAAI;AAClB,EAAE,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACpC,CAAC,CAAC,CAAC;AACH;AACA,MAAM,CAAC,gBAAgB,CAACA,YAAU,EAAE,WAAW,CAAC,CAAC;AACjD,MAAM,CAAC,cAAc,CAACE,WAAS,EAAE,cAAc,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;AAChE;AACA;AACAF,YAAU,CAAC,IAAI,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,WAAW,KAAK;AAC3E,EAAE,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAACE,WAAS,CAAC,CAAC;AAC9C;AACA,EAAED,OAAK,CAAC,YAAY,CAAC,KAAK,EAAE,UAAU,EAAE,SAAS,MAAM,CAAC,GAAG,EAAE;AAC7D,IAAI,OAAO,GAAG,KAAK,KAAK,CAAC,SAAS,CAAC;AACnC,GAAG,EAAE,IAAI,IAAI;AACb,IAAI,OAAO,IAAI,KAAK,cAAc,CAAC;AACnC,GAAG,CAAC,CAAC;AACL;AACA,EAAED,YAAU,CAAC,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC9E;AACA,EAAE,UAAU,CAAC,KAAK,GAAG,KAAK,CAAC;AAC3B;AACA,EAAE,UAAU,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;AAC/B;AACA,EAAE,WAAW,IAAI,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;AACxD;AACA,EAAE,OAAO,UAAU,CAAC;AACpB,CAAC;;ACpGD;AACA,oBAAe,IAAI;;ACMnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,WAAW,CAAC,KAAK,EAAE;AAC5B,EAAE,OAAOC,OAAK,CAAC,aAAa,CAAC,KAAK,CAAC,IAAIA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,cAAc,CAAC,GAAG,EAAE;AAC7B,EAAE,OAAOA,OAAK,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC;AAC5D,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,SAAS,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE;AACpC,EAAE,IAAI,CAAC,IAAI,EAAE,OAAO,GAAG,CAAC;AACxB,EAAE,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,KAAK,EAAE,CAAC,EAAE;AACtD;AACA,IAAI,KAAK,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;AAClC,IAAI,OAAO,CAAC,IAAI,IAAI,CAAC,GAAG,GAAG,GAAG,KAAK,GAAG,GAAG,GAAG,KAAK,CAAC;AAClD,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC,CAAC;AAC3B,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,WAAW,CAAC,GAAG,EAAE;AAC1B,EAAE,OAAOA,OAAK,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AACtD,CAAC;AACD;AACA,MAAM,UAAU,GAAGA,OAAK,CAAC,YAAY,CAACA,OAAK,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,MAAM,CAAC,IAAI,EAAE;AAC7E,EAAE,OAAO,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC/B,CAAC,CAAC,CAAC;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASE,YAAU,CAAC,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE;AAC5C,EAAE,IAAI,CAACF,OAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;AAC5B,IAAI,MAAM,IAAI,SAAS,CAAC,0BAA0B,CAAC,CAAC;AACpD,GAAG;AACH;AACA;AACA,EAAE,QAAQ,GAAG,QAAQ,IAAI,KAAyB,QAAQ,GAAG,CAAC;AAC9D;AACA;AACA,EAAE,OAAO,GAAGA,OAAK,CAAC,YAAY,CAAC,OAAO,EAAE;AACxC,IAAI,UAAU,EAAE,IAAI;AACpB,IAAI,IAAI,EAAE,KAAK;AACf,IAAI,OAAO,EAAE,KAAK;AAClB,GAAG,EAAE,KAAK,EAAE,SAAS,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE;AAC7C;AACA,IAAI,OAAO,CAACA,OAAK,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;AAC9C,GAAG,CAAC,CAAC;AACL;AACA,EAAE,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;AACxC;AACA,EAAE,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,cAAc,CAAC;AACpD,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;AAC5B,EAAE,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;AAClC,EAAE,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,WAAW,IAAI,IAAI,CAAC;AACpE,EAAE,MAAM,OAAO,GAAG,KAAK,IAAIA,OAAK,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAC;AAC/D;AACA,EAAE,IAAI,CAACA,OAAK,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE;AAClC,IAAI,MAAM,IAAI,SAAS,CAAC,4BAA4B,CAAC,CAAC;AACtD,GAAG;AACH;AACA,EAAE,SAAS,YAAY,CAAC,KAAK,EAAE;AAC/B,IAAI,IAAI,KAAK,KAAK,IAAI,EAAE,OAAO,EAAE,CAAC;AAClC;AACA,IAAI,IAAIA,OAAK,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;AAC7B,MAAM,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;AACjC,KAAK;AACL;AACA,IAAI,IAAI,CAAC,OAAO,IAAIA,OAAK,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;AACzC,MAAM,MAAM,IAAID,YAAU,CAAC,8CAA8C,CAAC,CAAC;AAC3E,KAAK;AACL;AACA,IAAI,IAAIC,OAAK,CAAC,aAAa,CAAC,KAAK,CAAC,IAAIA,OAAK,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE;AACjE,MAAM,OAAO,OAAO,IAAI,OAAO,IAAI,KAAK,UAAU,GAAG,IAAI,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC5F,KAAK;AACL;AACA,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,SAAS,cAAc,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE;AAC5C,IAAI,IAAI,GAAG,GAAG,KAAK,CAAC;AACpB;AACA,IAAI,IAAI,KAAK,IAAI,CAAC,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;AACrD,MAAM,IAAIA,OAAK,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE;AACrC;AACA,QAAQ,GAAG,GAAG,UAAU,GAAG,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAClD;AACA,QAAQ,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AACtC,OAAO,MAAM;AACb,QAAQ,CAACA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,WAAW,CAAC,KAAK,CAAC;AACnD,SAAS,CAACA,OAAK,CAAC,UAAU,CAAC,KAAK,CAAC,IAAIA,OAAK,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC/F,SAAS,EAAE;AACX;AACA,QAAQ,GAAG,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC;AAClC;AACA,QAAQ,GAAG,CAAC,OAAO,CAAC,SAAS,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE;AAC7C,UAAU,EAAEA,OAAK,CAAC,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,KAAK,IAAI,CAAC,IAAI,QAAQ,CAAC,MAAM;AACpE;AACA,YAAY,OAAO,KAAK,IAAI,GAAG,SAAS,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,OAAO,KAAK,IAAI,GAAG,GAAG,GAAG,GAAG,GAAG,IAAI,CAAC;AACpG,YAAY,YAAY,CAAC,EAAE,CAAC;AAC5B,WAAW,CAAC;AACZ,SAAS,CAAC,CAAC;AACX,QAAQ,OAAO,KAAK,CAAC;AACrB,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE;AAC5B,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL;AACA,IAAI,QAAQ,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC;AACrE;AACA,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA,EAAE,MAAM,KAAK,GAAG,EAAE,CAAC;AACnB;AACA,EAAE,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE;AACnD,IAAI,cAAc;AAClB,IAAI,YAAY;AAChB,IAAI,WAAW;AACf,GAAG,CAAC,CAAC;AACL;AACA,EAAE,SAAS,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE;AAC9B,IAAI,IAAIA,OAAK,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE,OAAO;AACzC;AACA,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE;AACrC,MAAM,MAAM,KAAK,CAAC,iCAAiC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AACtE,KAAK;AACL;AACA,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACtB;AACA,IAAIA,OAAK,CAAC,OAAO,CAAC,KAAK,EAAE,SAAS,IAAI,CAAC,EAAE,EAAE,GAAG,EAAE;AAChD,MAAM,MAAM,MAAM,GAAG,EAAEA,OAAK,CAAC,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,KAAK,IAAI,CAAC,IAAI,OAAO,CAAC,IAAI;AAC5E,QAAQ,QAAQ,EAAE,EAAE,EAAEA,OAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,GAAG,GAAG,EAAE,IAAI,EAAE,cAAc;AAClF,OAAO,CAAC;AACR;AACA,MAAM,IAAI,MAAM,KAAK,IAAI,EAAE;AAC3B,QAAQ,KAAK,CAAC,EAAE,EAAE,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;AACnD,OAAO;AACP,KAAK,CAAC,CAAC;AACP;AACA,IAAI,KAAK,CAAC,GAAG,EAAE,CAAC;AAChB,GAAG;AACH;AACA,EAAE,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;AAC5B,IAAI,MAAM,IAAI,SAAS,CAAC,wBAAwB,CAAC,CAAC;AAClD,GAAG;AACH;AACA,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;AACb;AACA,EAAE,OAAO,QAAQ,CAAC;AAClB;;ACpNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASG,QAAM,CAAC,GAAG,EAAE;AACrB,EAAE,MAAM,OAAO,GAAG;AAClB,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,KAAK,EAAE,GAAG;AACd,IAAI,KAAK,EAAE,MAAM;AACjB,GAAG,CAAC;AACJ,EAAE,OAAO,kBAAkB,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,kBAAkB,EAAE,SAAS,QAAQ,CAAC,KAAK,EAAE;AACtF,IAAI,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC;AAC1B,GAAG,CAAC,CAAC;AACL,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,oBAAoB,CAAC,MAAM,EAAE,OAAO,EAAE;AAC/C,EAAE,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;AACnB;AACA,EAAE,MAAM,IAAID,YAAU,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;AAC9C,CAAC;AACD;AACA,MAAM,SAAS,GAAG,oBAAoB,CAAC,SAAS,CAAC;AACjD;AACA,SAAS,CAAC,MAAM,GAAG,SAAS,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE;AAChD,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;AAClC,CAAC,CAAC;AACF;AACA,SAAS,CAAC,QAAQ,GAAG,SAAS,QAAQ,CAAC,OAAO,EAAE;AAChD,EAAE,MAAM,OAAO,GAAG,OAAO,GAAG,SAAS,KAAK,EAAE;AAC5C,IAAI,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAEC,QAAM,CAAC,CAAC;AAC7C,GAAG,GAAGA,QAAM,CAAC;AACb;AACA,EAAE,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,IAAI,EAAE;AAC7C,IAAI,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AACrD,GAAG,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACnB,CAAC;;AClDD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,MAAM,CAAC,GAAG,EAAE;AACrB,EAAE,OAAO,kBAAkB,CAAC,GAAG,CAAC;AAChC,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;AACzB,IAAI,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;AACxB,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;AACzB,IAAI,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;AACxB,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;AACzB,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AAC1B,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE;AACvD;AACA,EAAE,IAAI,CAAC,MAAM,EAAE;AACf,IAAI,OAAO,GAAG,CAAC;AACf,GAAG;AACH;AACA,EAAE,MAAM,OAAO,GAAG,OAAO,IAAI,OAAO,CAAC,MAAM,IAAI,MAAM,CAAC;AACtD;AACA,EAAE,IAAIH,OAAK,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE;AACjC,IAAI,OAAO,GAAG;AACd,MAAM,SAAS,EAAE,OAAO;AACxB,KAAK,CAAC;AACN,GAAG;AACH;AACA,EAAE,MAAM,WAAW,GAAG,OAAO,IAAI,OAAO,CAAC,SAAS,CAAC;AACnD;AACA,EAAE,IAAI,gBAAgB,CAAC;AACvB;AACA,EAAE,IAAI,WAAW,EAAE;AACnB,IAAI,gBAAgB,GAAG,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AACpD,GAAG,MAAM;AACT,IAAI,gBAAgB,GAAGA,OAAK,CAAC,iBAAiB,CAAC,MAAM,CAAC;AACtD,MAAM,MAAM,CAAC,QAAQ,EAAE;AACvB,MAAM,IAAI,oBAAoB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAClE,GAAG;AACH;AACA,EAAE,IAAI,gBAAgB,EAAE;AACxB,IAAI,MAAM,aAAa,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AAC3C;AACA,IAAI,IAAI,aAAa,KAAK,CAAC,CAAC,EAAE;AAC9B,MAAM,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC;AACxC,KAAK;AACL,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG,IAAI,gBAAgB,CAAC;AACpE,GAAG;AACH;AACA,EAAE,OAAO,GAAG,CAAC;AACb;;AChEA,MAAM,kBAAkB,CAAC;AACzB,EAAE,WAAW,GAAG;AAChB,IAAI,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;AACvB,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,GAAG,CAAC,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE;AACpC,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;AACvB,MAAM,SAAS;AACf,MAAM,QAAQ;AACd,MAAM,WAAW,EAAE,OAAO,GAAG,OAAO,CAAC,WAAW,GAAG,KAAK;AACxD,MAAM,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI;AAC/C,KAAK,CAAC,CAAC;AACP,IAAI,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;AACpC,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,KAAK,CAAC,EAAE,EAAE;AACZ,IAAI,IAAI,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE;AAC3B,MAAM,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC;AAC/B,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,KAAK,GAAG;AACV,IAAI,IAAI,IAAI,CAAC,QAAQ,EAAE;AACvB,MAAM,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;AACzB,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,OAAO,CAAC,EAAE,EAAE;AACd,IAAIA,OAAK,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,SAAS,cAAc,CAAC,CAAC,EAAE;AAC5D,MAAM,IAAI,CAAC,KAAK,IAAI,EAAE;AACtB,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC;AACd,OAAO;AACP,KAAK,CAAC,CAAC;AACP,GAAG;AACH,CAAC;AACD;AACA,6BAAe,kBAAkB;;ACpEjC,6BAAe;AACf,EAAE,iBAAiB,EAAE,IAAI;AACzB,EAAE,iBAAiB,EAAE,IAAI;AACzB,EAAE,mBAAmB,EAAE,KAAK;AAC5B,CAAC;;ACHD,0BAAe,OAAO,eAAe,KAAK,WAAW,GAAG,eAAe,GAAG,oBAAoB;;ACD9F,mBAAe,OAAO,QAAQ,KAAK,WAAW,GAAG,QAAQ,GAAG,IAAI;;ACAhE,eAAe,OAAO,IAAI,KAAK,WAAW,GAAG,IAAI,GAAG;;ACEpD,mBAAe;AACf,EAAE,SAAS,EAAE,IAAI;AACjB,EAAE,OAAO,EAAE;AACX,qBAAII,iBAAe;AACnB,cAAIC,UAAQ;AACZ,UAAIC,MAAI;AACR,GAAG;AACH,EAAE,SAAS,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC;AAC7D,CAAC;;ACZD,MAAM,aAAa,GAAG,OAAO,MAAM,KAAK,WAAW,IAAI,OAAO,QAAQ,KAAK,WAAW,CAAC;AACvF;AACA,MAAM,UAAU,GAAG,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,IAAI,SAAS,CAAC;AAC3E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,qBAAqB,GAAG,aAAa;AAC3C,GAAG,CAAC,UAAU,IAAI,CAAC,aAAa,EAAE,cAAc,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;AACzF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,8BAA8B,GAAG,CAAC,MAAM;AAC9C,EAAE;AACF,IAAI,OAAO,iBAAiB,KAAK,WAAW;AAC5C;AACA,IAAI,IAAI,YAAY,iBAAiB;AACrC,IAAI,OAAO,IAAI,CAAC,aAAa,KAAK,UAAU;AAC5C,IAAI;AACJ,CAAC,GAAG,CAAC;AACL;AACA,MAAM,MAAM,GAAG,aAAa,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,IAAI,kBAAkB;;;;;;;;;;;ACvC1E,iBAAe;AACf,EAAE,GAAG,KAAK;AACV,EAAE,GAAGC,UAAQ;AACb;;ACAe,SAAS,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE;AACxD,EAAE,OAAOL,YAAU,CAAC,IAAI,EAAE,IAAI,QAAQ,CAAC,OAAO,CAAC,eAAe,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC;AAChF,IAAI,OAAO,EAAE,SAAS,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE;AACjD,MAAM,IAAI,QAAQ,CAAC,MAAM,IAAIF,OAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;AACpD,QAAQ,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC;AACnD,QAAQ,OAAO,KAAK,CAAC;AACrB,OAAO;AACP;AACA,MAAM,OAAO,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;AAC3D,KAAK;AACL,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AACf;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,aAAa,CAAC,IAAI,EAAE;AAC7B;AACA;AACA;AACA;AACA,EAAE,OAAOA,OAAK,CAAC,QAAQ,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,IAAI;AAC5D,IAAI,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC;AACzD,GAAG,CAAC,CAAC;AACL,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,aAAa,CAAC,GAAG,EAAE;AAC5B,EAAE,MAAM,GAAG,GAAG,EAAE,CAAC;AACjB,EAAE,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAChC,EAAE,IAAI,CAAC,CAAC;AACR,EAAE,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC;AAC1B,EAAE,IAAI,GAAG,CAAC;AACV,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;AAC5B,IAAI,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;AACxB,GAAG;AACH,EAAE,OAAO,GAAG,CAAC;AACb,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,cAAc,CAAC,QAAQ,EAAE;AAClC,EAAE,SAAS,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE;AACjD,IAAI,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;AAC7B;AACA,IAAI,IAAI,IAAI,KAAK,WAAW,EAAE,OAAO,IAAI,CAAC;AAC1C;AACA,IAAI,MAAM,YAAY,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC;AAChD,IAAI,MAAM,MAAM,GAAG,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC;AACxC,IAAI,IAAI,GAAG,CAAC,IAAI,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC;AACjE;AACA,IAAI,IAAI,MAAM,EAAE;AAChB,MAAM,IAAIA,OAAK,CAAC,UAAU,CAAC,MAAM,EAAE,IAAI,CAAC,EAAE;AAC1C,QAAQ,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC;AAC7C,OAAO,MAAM;AACb,QAAQ,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;AAC7B,OAAO;AACP;AACA,MAAM,OAAO,CAAC,YAAY,CAAC;AAC3B,KAAK;AACL;AACA,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE;AACxD,MAAM,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;AACxB,KAAK;AACL;AACA,IAAI,MAAM,MAAM,GAAG,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC;AAC/D;AACA,IAAI,IAAI,MAAM,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE;AAC/C,MAAM,MAAM,CAAC,IAAI,CAAC,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACjD,KAAK;AACL;AACA,IAAI,OAAO,CAAC,YAAY,CAAC;AACzB,GAAG;AACH;AACA,EAAE,IAAIA,OAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAIA,OAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;AACxE,IAAI,MAAM,GAAG,GAAG,EAAE,CAAC;AACnB;AACA,IAAIA,OAAK,CAAC,YAAY,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK;AAClD,MAAM,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;AACpD,KAAK,CAAC,CAAC;AACP;AACA,IAAI,OAAO,GAAG,CAAC;AACf,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC;AACd;;AClFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE;AACpD,EAAE,IAAIA,OAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE;AAChC,IAAI,IAAI;AACR,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;AACvC,MAAM,OAAOA,OAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAClC,KAAK,CAAC,OAAO,CAAC,EAAE;AAChB,MAAM,IAAI,CAAC,CAAC,IAAI,KAAK,aAAa,EAAE;AACpC,QAAQ,MAAM,CAAC,CAAC;AAChB,OAAO;AACP,KAAK;AACL,GAAG;AACH;AACA,EAAE,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;AAC/C,CAAC;AACD;AACA,MAAM,QAAQ,GAAG;AACjB;AACA,EAAE,YAAY,EAAE,oBAAoB;AACpC;AACA,EAAE,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC;AACnC;AACA,EAAE,gBAAgB,EAAE,CAAC,SAAS,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE;AAC9D,IAAI,MAAM,WAAW,GAAG,OAAO,CAAC,cAAc,EAAE,IAAI,EAAE,CAAC;AACvD,IAAI,MAAM,kBAAkB,GAAG,WAAW,CAAC,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC;AAC5E,IAAI,MAAM,eAAe,GAAGA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AACjD;AACA,IAAI,IAAI,eAAe,IAAIA,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;AACnD,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC;AAChC,KAAK;AACL;AACA,IAAI,MAAM,UAAU,GAAGA,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAC9C;AACA,IAAI,IAAI,UAAU,EAAE;AACpB,MAAM,OAAO,kBAAkB,GAAG,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC;AAC9E,KAAK;AACL;AACA,IAAI,IAAIA,OAAK,CAAC,aAAa,CAAC,IAAI,CAAC;AACjC,MAAMA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;AAC1B,MAAMA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;AAC1B,MAAMA,OAAK,CAAC,MAAM,CAAC,IAAI,CAAC;AACxB,MAAMA,OAAK,CAAC,MAAM,CAAC,IAAI,CAAC;AACxB,MAAMA,OAAK,CAAC,gBAAgB,CAAC,IAAI,CAAC;AAClC,MAAM;AACN,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL,IAAI,IAAIA,OAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE;AACvC,MAAM,OAAO,IAAI,CAAC,MAAM,CAAC;AACzB,KAAK;AACL,IAAI,IAAIA,OAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE;AACvC,MAAM,OAAO,CAAC,cAAc,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;AACvF,MAAM,OAAO,IAAI,CAAC,QAAQ,EAAE,CAAC;AAC7B,KAAK;AACL;AACA,IAAI,IAAI,UAAU,CAAC;AACnB;AACA,IAAI,IAAI,eAAe,EAAE;AACzB,MAAM,IAAI,WAAW,CAAC,OAAO,CAAC,mCAAmC,CAAC,GAAG,CAAC,CAAC,EAAE;AACzE,QAAQ,OAAO,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC,QAAQ,EAAE,CAAC;AACtE,OAAO;AACP;AACA,MAAM,IAAI,CAAC,UAAU,GAAGA,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,WAAW,CAAC,OAAO,CAAC,qBAAqB,CAAC,GAAG,CAAC,CAAC,EAAE;AACpG,QAAQ,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC;AACxD;AACA,QAAQ,OAAOE,YAAU;AACzB,UAAU,UAAU,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,GAAG,IAAI;AAC/C,UAAU,SAAS,IAAI,IAAI,SAAS,EAAE;AACtC,UAAU,IAAI,CAAC,cAAc;AAC7B,SAAS,CAAC;AACV,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAI,eAAe,IAAI,kBAAkB,GAAG;AAChD,MAAM,OAAO,CAAC,cAAc,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;AACxD,MAAM,OAAO,eAAe,CAAC,IAAI,CAAC,CAAC;AACnC,KAAK;AACL;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG,CAAC;AACJ;AACA,EAAE,iBAAiB,EAAE,CAAC,SAAS,iBAAiB,CAAC,IAAI,EAAE;AACvD,IAAI,MAAM,YAAY,GAAG,IAAI,CAAC,YAAY,IAAI,QAAQ,CAAC,YAAY,CAAC;AACpE,IAAI,MAAM,iBAAiB,GAAG,YAAY,IAAI,YAAY,CAAC,iBAAiB,CAAC;AAC7E,IAAI,MAAM,aAAa,GAAG,IAAI,CAAC,YAAY,KAAK,MAAM,CAAC;AACvD;AACA,IAAI,IAAIF,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,IAAIA,OAAK,CAAC,gBAAgB,CAAC,IAAI,CAAC,EAAE;AAChE,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL;AACA,IAAI,IAAI,IAAI,IAAIA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,iBAAiB,IAAI,CAAC,IAAI,CAAC,YAAY,KAAK,aAAa,CAAC,EAAE;AACtG,MAAM,MAAM,iBAAiB,GAAG,YAAY,IAAI,YAAY,CAAC,iBAAiB,CAAC;AAC/E,MAAM,MAAM,iBAAiB,GAAG,CAAC,iBAAiB,IAAI,aAAa,CAAC;AACpE;AACA,MAAM,IAAI;AACV,QAAQ,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAChC,OAAO,CAAC,OAAO,CAAC,EAAE;AAClB,QAAQ,IAAI,iBAAiB,EAAE;AAC/B,UAAU,IAAI,CAAC,CAAC,IAAI,KAAK,aAAa,EAAE;AACxC,YAAY,MAAMD,YAAU,CAAC,IAAI,CAAC,CAAC,EAAEA,YAAU,CAAC,gBAAgB,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC7F,WAAW;AACX,UAAU,MAAM,CAAC,CAAC;AAClB,SAAS;AACT,OAAO;AACP,KAAK;AACL;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG,CAAC;AACJ;AACA;AACA;AACA;AACA;AACA,EAAE,OAAO,EAAE,CAAC;AACZ;AACA,EAAE,cAAc,EAAE,YAAY;AAC9B,EAAE,cAAc,EAAE,cAAc;AAChC;AACA,EAAE,gBAAgB,EAAE,CAAC,CAAC;AACtB,EAAE,aAAa,EAAE,CAAC,CAAC;AACnB;AACA,EAAE,GAAG,EAAE;AACP,IAAI,QAAQ,EAAE,QAAQ,CAAC,OAAO,CAAC,QAAQ;AACvC,IAAI,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,IAAI;AAC/B,GAAG;AACH;AACA,EAAE,cAAc,EAAE,SAAS,cAAc,CAAC,MAAM,EAAE;AAClD,IAAI,OAAO,MAAM,IAAI,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC;AACzC,GAAG;AACH;AACA,EAAE,OAAO,EAAE;AACX,IAAI,MAAM,EAAE;AACZ,MAAM,QAAQ,EAAE,mCAAmC;AACnD,MAAM,cAAc,EAAE,SAAS;AAC/B,KAAK;AACL,GAAG;AACH,CAAC,CAAC;AACF;AACAC,OAAK,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC,MAAM,KAAK;AAC7E,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;AAChC,CAAC,CAAC,CAAC;AACH;AACA,mBAAe,QAAQ;;AC5JvB;AACA;AACA,MAAM,iBAAiB,GAAGA,OAAK,CAAC,WAAW,CAAC;AAC5C,EAAE,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM;AAClE,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,EAAE,qBAAqB;AACvE,EAAE,eAAe,EAAE,UAAU,EAAE,cAAc,EAAE,qBAAqB;AACpE,EAAE,SAAS,EAAE,aAAa,EAAE,YAAY;AACxC,CAAC,CAAC,CAAC;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAe,UAAU,IAAI;AAC7B,EAAE,MAAM,MAAM,GAAG,EAAE,CAAC;AACpB,EAAE,IAAI,GAAG,CAAC;AACV,EAAE,IAAI,GAAG,CAAC;AACV,EAAE,IAAI,CAAC,CAAC;AACR;AACA,EAAE,UAAU,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,SAAS,MAAM,CAAC,IAAI,EAAE;AACrE,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AAC1B,IAAI,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AACpD,IAAI,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;AACvC;AACA,IAAI,IAAI,CAAC,GAAG,KAAK,MAAM,CAAC,GAAG,CAAC,IAAI,iBAAiB,CAAC,GAAG,CAAC,CAAC,EAAE;AACzD,MAAM,OAAO;AACb,KAAK;AACL;AACA,IAAI,IAAI,GAAG,KAAK,YAAY,EAAE;AAC9B,MAAM,IAAI,MAAM,CAAC,GAAG,CAAC,EAAE;AACvB,QAAQ,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC9B,OAAO,MAAM;AACb,QAAQ,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAC5B,OAAO;AACP,KAAK,MAAM;AACX,MAAM,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,GAAG,GAAG,GAAG,CAAC;AACjE,KAAK;AACL,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO,MAAM,CAAC;AAChB,CAAC;;ACjDD,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC;AACA,SAAS,eAAe,CAAC,MAAM,EAAE;AACjC,EAAE,OAAO,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AACvD,CAAC;AACD;AACA,SAAS,cAAc,CAAC,KAAK,EAAE;AAC/B,EAAE,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,IAAI,IAAI,EAAE;AACxC,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA,EAAE,OAAOA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;AAC1E,CAAC;AACD;AACA,SAAS,WAAW,CAAC,GAAG,EAAE;AAC1B,EAAE,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AACrC,EAAE,MAAM,QAAQ,GAAG,kCAAkC,CAAC;AACtD,EAAE,IAAI,KAAK,CAAC;AACZ;AACA,EAAE,QAAQ,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG;AACvC,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAChC,GAAG;AACH;AACA,EAAE,OAAO,MAAM,CAAC;AAChB,CAAC;AACD;AACA,MAAM,iBAAiB,GAAG,CAAC,GAAG,KAAK,gCAAgC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;AACrF;AACA,SAAS,gBAAgB,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,kBAAkB,EAAE;AAC9E,EAAE,IAAIA,OAAK,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE;AAChC,IAAI,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAC5C,GAAG;AACH;AACA,EAAE,IAAI,kBAAkB,EAAE;AAC1B,IAAI,KAAK,GAAG,MAAM,CAAC;AACnB,GAAG;AACH;AACA,EAAE,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO;AACrC;AACA,EAAE,IAAIA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;AAC9B,IAAI,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AACxC,GAAG;AACH;AACA,EAAE,IAAIA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;AAC9B,IAAI,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC9B,GAAG;AACH,CAAC;AACD;AACA,SAAS,YAAY,CAAC,MAAM,EAAE;AAC9B,EAAE,OAAO,MAAM,CAAC,IAAI,EAAE;AACtB,KAAK,WAAW,EAAE,CAAC,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,KAAK;AAChE,MAAM,OAAO,IAAI,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC;AACtC,KAAK,CAAC,CAAC;AACP,CAAC;AACD;AACA,SAAS,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE;AACrC,EAAE,MAAM,YAAY,GAAGA,OAAK,CAAC,WAAW,CAAC,GAAG,GAAG,MAAM,CAAC,CAAC;AACvD;AACA,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,UAAU,IAAI;AAC9C,IAAI,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,UAAU,GAAG,YAAY,EAAE;AAC1D,MAAM,KAAK,EAAE,SAAS,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE;AACxC,QAAQ,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AACrE,OAAO;AACP,MAAM,YAAY,EAAE,IAAI;AACxB,KAAK,CAAC,CAAC;AACP,GAAG,CAAC,CAAC;AACL,CAAC;AACD;AACA,MAAMQ,cAAY,CAAC;AACnB,EAAE,WAAW,CAAC,OAAO,EAAE;AACvB,IAAI,OAAO,IAAI,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AACjC,GAAG;AACH;AACA,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE;AACvC,IAAI,MAAM,IAAI,GAAG,IAAI,CAAC;AACtB;AACA,IAAI,SAAS,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE;AAClD,MAAM,MAAM,OAAO,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;AAC/C;AACA,MAAM,IAAI,CAAC,OAAO,EAAE;AACpB,QAAQ,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAClE,OAAO;AACP;AACA,MAAM,MAAM,GAAG,GAAGR,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AAC/C;AACA,MAAM,GAAG,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,SAAS,IAAI,QAAQ,KAAK,IAAI,KAAK,QAAQ,KAAK,SAAS,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,EAAE;AAClH,QAAQ,IAAI,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;AACtD,OAAO;AACP,KAAK;AACL;AACA,IAAI,MAAM,UAAU,GAAG,CAAC,OAAO,EAAE,QAAQ;AACzC,MAAMA,OAAK,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC;AACxF;AACA,IAAI,IAAIA,OAAK,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,MAAM,YAAY,IAAI,CAAC,WAAW,EAAE;AAC3E,MAAM,UAAU,CAAC,MAAM,EAAE,cAAc,EAAC;AACxC,KAAK,MAAM,GAAGA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,MAAM,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,EAAE;AAChG,MAAM,UAAU,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE,cAAc,CAAC,CAAC;AACvD,KAAK,MAAM,IAAIA,OAAK,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE;AACxC,MAAM,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,EAAE,EAAE;AACnD,QAAQ,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;AACvC,OAAO;AACP,KAAK,MAAM;AACX,MAAM,MAAM,IAAI,IAAI,IAAI,SAAS,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACnE,KAAK;AACL;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG;AACH;AACA,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE;AACtB,IAAI,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC;AACrC;AACA,IAAI,IAAI,MAAM,EAAE;AAChB,MAAM,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC9C;AACA,MAAM,IAAI,GAAG,EAAE;AACf,QAAQ,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;AAChC;AACA,QAAQ,IAAI,CAAC,MAAM,EAAE;AACrB,UAAU,OAAO,KAAK,CAAC;AACvB,SAAS;AACT;AACA,QAAQ,IAAI,MAAM,KAAK,IAAI,EAAE;AAC7B,UAAU,OAAO,WAAW,CAAC,KAAK,CAAC,CAAC;AACpC,SAAS;AACT;AACA,QAAQ,IAAIA,OAAK,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE;AACtC,UAAU,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;AAC/C,SAAS;AACT;AACA,QAAQ,IAAIA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;AACpC,UAAU,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACpC,SAAS;AACT;AACA,QAAQ,MAAM,IAAI,SAAS,CAAC,wCAAwC,CAAC,CAAC;AACtE,OAAO;AACP,KAAK;AACL,GAAG;AACH;AACA,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE;AACvB,IAAI,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC;AACrC;AACA,IAAI,IAAI,MAAM,EAAE;AAChB,MAAM,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC9C;AACA,MAAM,OAAO,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,SAAS,KAAK,CAAC,OAAO,IAAI,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;AACjH,KAAK;AACL;AACA,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE;AAC1B,IAAI,MAAM,IAAI,GAAG,IAAI,CAAC;AACtB,IAAI,IAAI,OAAO,GAAG,KAAK,CAAC;AACxB;AACA,IAAI,SAAS,YAAY,CAAC,OAAO,EAAE;AACnC,MAAM,OAAO,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;AACzC;AACA,MAAM,IAAI,OAAO,EAAE;AACnB,QAAQ,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AACjD;AACA,QAAQ,IAAI,GAAG,KAAK,CAAC,OAAO,IAAI,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,EAAE;AAClF,UAAU,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AAC3B;AACA,UAAU,OAAO,GAAG,IAAI,CAAC;AACzB,SAAS;AACT,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;AAC/B,MAAM,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;AACnC,KAAK,MAAM;AACX,MAAM,YAAY,CAAC,MAAM,CAAC,CAAC;AAC3B,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC;AACnB,GAAG;AACH;AACA,EAAE,KAAK,CAAC,OAAO,EAAE;AACjB,IAAI,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACnC,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;AACxB,IAAI,IAAI,OAAO,GAAG,KAAK,CAAC;AACxB;AACA,IAAI,OAAO,CAAC,EAAE,EAAE;AAChB,MAAM,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AAC1B,MAAM,GAAG,CAAC,OAAO,IAAI,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE;AAC5E,QAAQ,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AACzB,QAAQ,OAAO,GAAG,IAAI,CAAC;AACvB,OAAO;AACP,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC;AACnB,GAAG;AACH;AACA,EAAE,SAAS,CAAC,MAAM,EAAE;AACpB,IAAI,MAAM,IAAI,GAAG,IAAI,CAAC;AACtB,IAAI,MAAM,OAAO,GAAG,EAAE,CAAC;AACvB;AACA,IAAIA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK;AAC3C,MAAM,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AACjD;AACA,MAAM,IAAI,GAAG,EAAE;AACf,QAAQ,IAAI,CAAC,GAAG,CAAC,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;AAC1C,QAAQ,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,YAAY,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;AAC/E;AACA,MAAM,IAAI,UAAU,KAAK,MAAM,EAAE;AACjC,QAAQ,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,OAAO;AACP;AACA,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;AAC/C;AACA,MAAM,OAAO,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC;AACjC,KAAK,CAAC,CAAC;AACP;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG;AACH;AACA,EAAE,MAAM,CAAC,GAAG,OAAO,EAAE;AACrB,IAAI,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,OAAO,CAAC,CAAC;AACrD,GAAG;AACH;AACA,EAAE,MAAM,CAAC,SAAS,EAAE;AACpB,IAAI,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AACpC;AACA,IAAIA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK;AAC3C,MAAM,KAAK,IAAI,IAAI,IAAI,KAAK,KAAK,KAAK,KAAK,GAAG,CAAC,MAAM,CAAC,GAAG,SAAS,IAAIA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC;AACvH,KAAK,CAAC,CAAC;AACP;AACA,IAAI,OAAO,GAAG,CAAC;AACf,GAAG;AACH;AACA,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG;AACtB,IAAI,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;AAC5D,GAAG;AACH;AACA,EAAE,QAAQ,GAAG;AACb,IAAI,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,KAAK,CAAC,KAAK,MAAM,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACpG,GAAG;AACH;AACA,EAAE,KAAK,MAAM,CAAC,WAAW,CAAC,GAAG;AAC7B,IAAI,OAAO,cAAc,CAAC;AAC1B,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC,KAAK,EAAE;AACrB,IAAI,OAAO,KAAK,YAAY,IAAI,GAAG,KAAK,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;AAC3D,GAAG;AACH;AACA,EAAE,OAAO,MAAM,CAAC,KAAK,EAAE,GAAG,OAAO,EAAE;AACnC,IAAI,MAAM,QAAQ,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;AACrC;AACA,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;AACtD;AACA,IAAI,OAAO,QAAQ,CAAC;AACpB,GAAG;AACH;AACA,EAAE,OAAO,QAAQ,CAAC,MAAM,EAAE;AAC1B,IAAI,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG;AAC7D,MAAM,SAAS,EAAE,EAAE;AACnB,KAAK,CAAC,CAAC;AACP;AACA,IAAI,MAAM,SAAS,GAAG,SAAS,CAAC,SAAS,CAAC;AAC1C,IAAI,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;AACrC;AACA,IAAI,SAAS,cAAc,CAAC,OAAO,EAAE;AACrC,MAAM,MAAM,OAAO,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;AAC/C;AACA,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE;AAC/B,QAAQ,cAAc,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;AAC3C,QAAQ,SAAS,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;AAClC,OAAO;AACP,KAAK;AACL;AACA,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;AACpF;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG;AACH,CAAC;AACD;AACAQ,cAAY,CAAC,QAAQ,CAAC,CAAC,cAAc,EAAE,gBAAgB,EAAE,QAAQ,EAAE,iBAAiB,EAAE,YAAY,EAAE,eAAe,CAAC,CAAC,CAAC;AACtH;AACA;AACAR,OAAK,CAAC,iBAAiB,CAACQ,cAAY,CAAC,SAAS,EAAE,CAAC,CAAC,KAAK,CAAC,EAAE,GAAG,KAAK;AAClE,EAAE,IAAI,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnD,EAAE,OAAO;AACT,IAAI,GAAG,EAAE,MAAM,KAAK;AACpB,IAAI,GAAG,CAAC,WAAW,EAAE;AACrB,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,WAAW,CAAC;AACjC,KAAK;AACL,GAAG;AACH,CAAC,CAAC,CAAC;AACH;AACAR,OAAK,CAAC,aAAa,CAACQ,cAAY,CAAC,CAAC;AAClC;AACA,uBAAeA,cAAY;;ACvS3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,aAAa,CAAC,GAAG,EAAE,QAAQ,EAAE;AACrD,EAAE,MAAM,MAAM,GAAG,IAAI,IAAIC,UAAQ,CAAC;AAClC,EAAE,MAAM,OAAO,GAAG,QAAQ,IAAI,MAAM,CAAC;AACrC,EAAE,MAAM,OAAO,GAAGD,cAAY,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AACrD,EAAE,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;AAC1B;AACA,EAAER,OAAK,CAAC,OAAO,CAAC,GAAG,EAAE,SAAS,SAAS,CAAC,EAAE,EAAE;AAC5C,IAAI,IAAI,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,SAAS,EAAE,EAAE,QAAQ,GAAG,QAAQ,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;AAC9F,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC;AACtB;AACA,EAAE,OAAO,IAAI,CAAC;AACd;;ACzBe,SAASU,UAAQ,CAAC,KAAK,EAAE;AACxC,EAAE,OAAO,CAAC,EAAE,KAAK,IAAI,KAAK,CAAC,UAAU,CAAC,CAAC;AACvC;;ACCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,eAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE;AACjD;AACA,EAAEZ,YAAU,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,IAAI,IAAI,GAAG,UAAU,GAAG,OAAO,EAAEA,YAAU,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AAC1G,EAAE,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;AAC9B,CAAC;AACD;AACAC,OAAK,CAAC,QAAQ,CAACW,eAAa,EAAEZ,YAAU,EAAE;AAC1C,EAAE,UAAU,EAAE,IAAI;AAClB,CAAC,CAAC;;AClBF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE;AAC1D,EAAE,MAAM,cAAc,GAAG,QAAQ,CAAC,MAAM,CAAC,cAAc,CAAC;AACxD,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,IAAI,CAAC,cAAc,IAAI,cAAc,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;AAC9E,IAAI,OAAO,CAAC,QAAQ,CAAC,CAAC;AACtB,GAAG,MAAM;AACT,IAAI,MAAM,CAAC,IAAIA,YAAU;AACzB,MAAM,kCAAkC,GAAG,QAAQ,CAAC,MAAM;AAC1D,MAAM,CAACA,YAAU,CAAC,eAAe,EAAEA,YAAU,CAAC,gBAAgB,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;AACtG,MAAM,QAAQ,CAAC,MAAM;AACrB,MAAM,QAAQ,CAAC,OAAO;AACtB,MAAM,QAAQ;AACd,KAAK,CAAC,CAAC;AACP,GAAG;AACH;;ACxBe,SAAS,aAAa,CAAC,GAAG,EAAE;AAC3C,EAAE,MAAM,KAAK,GAAG,2BAA2B,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACtD,EAAE,OAAO,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;AACjC;;ACHA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,WAAW,CAAC,YAAY,EAAE,GAAG,EAAE;AACxC,EAAE,YAAY,GAAG,YAAY,IAAI,EAAE,CAAC;AACpC,EAAE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;AACxC,EAAE,MAAM,UAAU,GAAG,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;AAC7C,EAAE,IAAI,IAAI,GAAG,CAAC,CAAC;AACf,EAAE,IAAI,IAAI,GAAG,CAAC,CAAC;AACf,EAAE,IAAI,aAAa,CAAC;AACpB;AACA,EAAE,GAAG,GAAG,GAAG,KAAK,SAAS,GAAG,GAAG,GAAG,IAAI,CAAC;AACvC;AACA,EAAE,OAAO,SAAS,IAAI,CAAC,WAAW,EAAE;AACpC,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;AAC3B;AACA,IAAI,MAAM,SAAS,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC;AACvC;AACA,IAAI,IAAI,CAAC,aAAa,EAAE;AACxB,MAAM,aAAa,GAAG,GAAG,CAAC;AAC1B,KAAK;AACL;AACA,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC;AAC9B,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC;AAC3B;AACA,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC;AACjB,IAAI,IAAI,UAAU,GAAG,CAAC,CAAC;AACvB;AACA,IAAI,OAAO,CAAC,KAAK,IAAI,EAAE;AACvB,MAAM,UAAU,IAAI,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;AAC/B,MAAM,CAAC,GAAG,CAAC,GAAG,YAAY,CAAC;AAC3B,KAAK;AACL;AACA,IAAI,IAAI,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,YAAY,CAAC;AACrC;AACA,IAAI,IAAI,IAAI,KAAK,IAAI,EAAE;AACvB,MAAM,IAAI,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,YAAY,CAAC;AACvC,KAAK;AACL;AACA,IAAI,IAAI,GAAG,GAAG,aAAa,GAAG,GAAG,EAAE;AACnC,MAAM,OAAO;AACb,KAAK;AACL;AACA,IAAI,MAAM,MAAM,GAAG,SAAS,IAAI,GAAG,GAAG,SAAS,CAAC;AAChD;AACA,IAAI,OAAO,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,GAAG,IAAI,GAAG,MAAM,CAAC,GAAG,SAAS,CAAC;AACvE,GAAG,CAAC;AACJ;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,QAAQ,CAAC,EAAE,EAAE,IAAI,EAAE;AAC5B,EAAE,IAAI,SAAS,GAAG,CAAC,CAAC;AACpB,EAAE,IAAI,SAAS,GAAG,IAAI,GAAG,IAAI,CAAC;AAC9B,EAAE,IAAI,QAAQ,CAAC;AACf,EAAE,IAAI,KAAK,CAAC;AACZ;AACA,EAAE,MAAM,MAAM,GAAG,CAAC,IAAI,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,KAAK;AAC7C,IAAI,SAAS,GAAG,GAAG,CAAC;AACpB,IAAI,QAAQ,GAAG,IAAI,CAAC;AACpB,IAAI,IAAI,KAAK,EAAE;AACf,MAAM,YAAY,CAAC,KAAK,CAAC,CAAC;AAC1B,MAAM,KAAK,GAAG,IAAI,CAAC;AACnB,KAAK;AACL,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AACzB,IAAG;AACH;AACA,EAAE,MAAM,SAAS,GAAG,CAAC,GAAG,IAAI,KAAK;AACjC,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;AAC3B,IAAI,MAAM,MAAM,GAAG,GAAG,GAAG,SAAS,CAAC;AACnC,IAAI,KAAK,MAAM,IAAI,SAAS,EAAE;AAC9B,MAAM,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AACxB,KAAK,MAAM;AACX,MAAM,QAAQ,GAAG,IAAI,CAAC;AACtB,MAAM,IAAI,CAAC,KAAK,EAAE;AAClB,QAAQ,KAAK,GAAG,UAAU,CAAC,MAAM;AACjC,UAAU,KAAK,GAAG,IAAI,CAAC;AACvB,UAAU,MAAM,CAAC,QAAQ,EAAC;AAC1B,SAAS,EAAE,SAAS,GAAG,MAAM,CAAC,CAAC;AAC/B,OAAO;AACP,KAAK;AACL,IAAG;AACH;AACA,EAAE,MAAM,KAAK,GAAG,MAAM,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC;AACnD;AACA,EAAE,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC5B;;ACrCO,MAAM,oBAAoB,GAAG,CAAC,QAAQ,EAAE,gBAAgB,EAAE,IAAI,GAAG,CAAC,KAAK;AAC9E,EAAE,IAAI,aAAa,GAAG,CAAC,CAAC;AACxB,EAAE,MAAM,YAAY,GAAG,WAAW,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;AAC5C;AACA,EAAE,OAAO,QAAQ,CAAC,CAAC,IAAI;AACvB,IAAI,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC;AAC5B,IAAI,MAAM,KAAK,GAAG,CAAC,CAAC,gBAAgB,GAAG,CAAC,CAAC,KAAK,GAAG,SAAS,CAAC;AAC3D,IAAI,MAAM,aAAa,GAAG,MAAM,GAAG,aAAa,CAAC;AACjD,IAAI,MAAM,IAAI,GAAG,YAAY,CAAC,aAAa,CAAC,CAAC;AAC7C,IAAI,MAAM,OAAO,GAAG,MAAM,IAAI,KAAK,CAAC;AACpC;AACA,IAAI,aAAa,GAAG,MAAM,CAAC;AAC3B;AACA,IAAI,MAAM,IAAI,GAAG;AACjB,MAAM,MAAM;AACZ,MAAM,KAAK;AACX,MAAM,QAAQ,EAAE,KAAK,IAAI,MAAM,GAAG,KAAK,IAAI,SAAS;AACpD,MAAM,KAAK,EAAE,aAAa;AAC1B,MAAM,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,SAAS;AACnC,MAAM,SAAS,EAAE,IAAI,IAAI,KAAK,IAAI,OAAO,GAAG,CAAC,KAAK,GAAG,MAAM,IAAI,IAAI,GAAG,SAAS;AAC/E,MAAM,KAAK,EAAE,CAAC;AACd,MAAM,gBAAgB,EAAE,KAAK,IAAI,IAAI;AACrC,MAAM,CAAC,gBAAgB,GAAG,UAAU,GAAG,QAAQ,GAAG,IAAI;AACtD,KAAK,CAAC;AACN;AACA,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC;AACnB,GAAG,EAAE,IAAI,CAAC,CAAC;AACX,EAAC;AACD;AACO,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK;AAC5D,EAAE,MAAM,gBAAgB,GAAG,KAAK,IAAI,IAAI,CAAC;AACzC;AACA,EAAE,OAAO,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC;AACnC,IAAI,gBAAgB;AACpB,IAAI,KAAK;AACT,IAAI,MAAM;AACV,GAAG,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;AACpB,EAAC;AACD;AACO,MAAM,cAAc,GAAG,CAAC,EAAE,KAAK,CAAC,GAAG,IAAI,KAAKC,OAAK,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;;ACzChF,wBAAe,QAAQ,CAAC,qBAAqB,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,KAAK,CAAC,GAAG,KAAK;AAC9E,EAAE,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;AACtC;AACA,EAAE;AACF,IAAI,MAAM,CAAC,QAAQ,KAAK,GAAG,CAAC,QAAQ;AACpC,IAAI,MAAM,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI;AAC5B,KAAK,MAAM,IAAI,MAAM,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,CAAC;AACxC,IAAI;AACJ,CAAC;AACD,EAAE,IAAI,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC1B,EAAE,QAAQ,CAAC,SAAS,IAAI,iBAAiB,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,SAAS,CAAC;AAC5E,CAAC,GAAG,MAAM,IAAI;;ACVd,gBAAe,QAAQ,CAAC,qBAAqB;AAC7C;AACA;AACA,EAAE;AACF,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE;AACtD,MAAM,MAAM,MAAM,GAAG,CAAC,IAAI,GAAG,GAAG,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC;AAC9D;AACA,MAAMA,OAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,GAAG,IAAI,IAAI,CAAC,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AAC3F;AACA,MAAMA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;AAC1D;AACA,MAAMA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,CAAC;AAChE;AACA,MAAM,MAAM,KAAK,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC/C;AACA,MAAM,QAAQ,CAAC,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1C,KAAK;AACL;AACA,IAAI,IAAI,CAAC,IAAI,EAAE;AACf,MAAM,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,YAAY,GAAG,IAAI,GAAG,WAAW,CAAC,CAAC,CAAC;AACzF,MAAM,QAAQ,KAAK,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,EAAE;AAC3D,KAAK;AACL;AACA,IAAI,MAAM,CAAC,IAAI,EAAE;AACjB,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,QAAQ,CAAC,CAAC;AAClD,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA,EAAE;AACF,IAAI,KAAK,GAAG,EAAE;AACd,IAAI,IAAI,GAAG;AACX,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL,IAAI,MAAM,GAAG,EAAE;AACf,GAAG;;ACtCH;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,aAAa,CAAC,GAAG,EAAE;AAC3C;AACA;AACA;AACA,EAAE,OAAO,6BAA6B,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjD;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,WAAW,CAAC,OAAO,EAAE,WAAW,EAAE;AAC1D,EAAE,OAAO,WAAW;AACpB,MAAM,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,GAAG,GAAG,GAAG,WAAW,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;AAC3E,MAAM,OAAO,CAAC;AACd;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE;AAC7D,EAAE,IAAI,OAAO,IAAI,CAAC,aAAa,CAAC,YAAY,CAAC,EAAE;AAC/C,IAAI,OAAO,WAAW,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;AAC9C,GAAG;AACH,EAAE,OAAO,YAAY,CAAC;AACtB;;ACfA,MAAM,eAAe,GAAG,CAAC,KAAK,KAAK,KAAK,YAAYQ,cAAY,GAAG,EAAE,GAAG,KAAK,EAAE,GAAG,KAAK,CAAC;AACxF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAASI,aAAW,CAAC,OAAO,EAAE,OAAO,EAAE;AACtD;AACA,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;AAC1B,EAAE,MAAM,MAAM,GAAG,EAAE,CAAC;AACpB;AACA,EAAE,SAAS,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE;AAC1D,IAAI,IAAIZ,OAAK,CAAC,aAAa,CAAC,MAAM,CAAC,IAAIA,OAAK,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE;AACpE,MAAM,OAAOA,OAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC1D,KAAK,MAAM,IAAIA,OAAK,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE;AAC5C,MAAM,OAAOA,OAAK,CAAC,KAAK,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;AACrC,KAAK,MAAM,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;AACtC,MAAM,OAAO,MAAM,CAAC,KAAK,EAAE,CAAC;AAC5B,KAAK;AACL,IAAI,OAAO,MAAM,CAAC;AAClB,GAAG;AACH;AACA;AACA,EAAE,SAAS,mBAAmB,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,QAAQ,EAAE;AACtD,IAAI,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AAC/B,MAAM,OAAO,cAAc,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,QAAQ,CAAC,CAAC;AACnD,KAAK,MAAM,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AACtC,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,EAAE,IAAI,GAAG,QAAQ,CAAC,CAAC;AAC3D,KAAK;AACL,GAAG;AACH;AACA;AACA,EAAE,SAAS,gBAAgB,CAAC,CAAC,EAAE,CAAC,EAAE;AAClC,IAAI,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AAC/B,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;AAC1C,KAAK;AACL,GAAG;AACH;AACA;AACA,EAAE,SAAS,gBAAgB,CAAC,CAAC,EAAE,CAAC,EAAE;AAClC,IAAI,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AAC/B,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;AAC1C,KAAK,MAAM,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AACtC,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;AAC1C,KAAK;AACL,GAAG;AACH;AACA;AACA,EAAE,SAAS,eAAe,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE;AACvC,IAAI,IAAI,IAAI,IAAI,OAAO,EAAE;AACzB,MAAM,OAAO,cAAc,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAClC,KAAK,MAAM,IAAI,IAAI,IAAI,OAAO,EAAE;AAChC,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;AAC1C,KAAK;AACL,GAAG;AACH;AACA,EAAE,MAAM,QAAQ,GAAG;AACnB,IAAI,GAAG,EAAE,gBAAgB;AACzB,IAAI,MAAM,EAAE,gBAAgB;AAC5B,IAAI,IAAI,EAAE,gBAAgB;AAC1B,IAAI,OAAO,EAAE,gBAAgB;AAC7B,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,iBAAiB,EAAE,gBAAgB;AACvC,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,OAAO,EAAE,gBAAgB;AAC7B,IAAI,cAAc,EAAE,gBAAgB;AACpC,IAAI,eAAe,EAAE,gBAAgB;AACrC,IAAI,aAAa,EAAE,gBAAgB;AACnC,IAAI,OAAO,EAAE,gBAAgB;AAC7B,IAAI,YAAY,EAAE,gBAAgB;AAClC,IAAI,cAAc,EAAE,gBAAgB;AACpC,IAAI,cAAc,EAAE,gBAAgB;AACpC,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,kBAAkB,EAAE,gBAAgB;AACxC,IAAI,UAAU,EAAE,gBAAgB;AAChC,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,aAAa,EAAE,gBAAgB;AACnC,IAAI,cAAc,EAAE,gBAAgB;AACpC,IAAI,SAAS,EAAE,gBAAgB;AAC/B,IAAI,SAAS,EAAE,gBAAgB;AAC/B,IAAI,UAAU,EAAE,gBAAgB;AAChC,IAAI,WAAW,EAAE,gBAAgB;AACjC,IAAI,UAAU,EAAE,gBAAgB;AAChC,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,cAAc,EAAE,eAAe;AACnC,IAAI,OAAO,EAAE,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,KAAK,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC;AACpG,GAAG,CAAC;AACJ;AACA,EAAEA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,EAAE,SAAS,kBAAkB,CAAC,IAAI,EAAE;AACpG,IAAI,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,IAAI,mBAAmB,CAAC;AACxD,IAAI,MAAM,WAAW,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;AAClE,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,WAAW,CAAC,IAAI,KAAK,KAAK,eAAe,MAAM,MAAM,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,CAAC;AAClG,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO,MAAM,CAAC;AAChB;;AChGA,sBAAe,CAAC,MAAM,KAAK;AAC3B,EAAE,MAAM,SAAS,GAAGY,aAAW,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;AAC5C;AACA,EAAE,IAAI,CAAC,IAAI,EAAE,aAAa,EAAE,cAAc,EAAE,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC,GAAG,SAAS,CAAC;AACvF;AACA,EAAE,SAAS,CAAC,OAAO,GAAG,OAAO,GAAGJ,cAAY,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAC3D;AACA,EAAE,SAAS,CAAC,GAAG,GAAG,QAAQ,CAAC,aAAa,CAAC,SAAS,CAAC,OAAO,EAAE,SAAS,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,gBAAgB,CAAC,CAAC;AACpH;AACA;AACA,EAAE,IAAI,IAAI,EAAE;AACZ,IAAI,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,QAAQ;AACzC,MAAM,IAAI,CAAC,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC,kBAAkB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;AAC5G,KAAK,CAAC;AACN,GAAG;AACH;AACA,EAAE,IAAI,WAAW,CAAC;AAClB;AACA,EAAE,IAAIR,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;AAC9B,IAAI,IAAI,QAAQ,CAAC,qBAAqB,IAAI,QAAQ,CAAC,8BAA8B,EAAE;AACnF,MAAM,OAAO,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC;AACxC,KAAK,MAAM,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,cAAc,EAAE,MAAM,KAAK,EAAE;AACnE;AACA,MAAM,MAAM,CAAC,IAAI,EAAE,GAAG,MAAM,CAAC,GAAG,WAAW,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;AACrH,MAAM,OAAO,CAAC,cAAc,CAAC,CAAC,IAAI,IAAI,qBAAqB,EAAE,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AACpF,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,EAAE,IAAI,QAAQ,CAAC,qBAAqB,EAAE;AACtC,IAAI,aAAa,IAAIA,OAAK,CAAC,UAAU,CAAC,aAAa,CAAC,KAAK,aAAa,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC,CAAC;AACnG;AACA,IAAI,IAAI,aAAa,KAAK,aAAa,KAAK,KAAK,IAAI,eAAe,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,EAAE;AACtF;AACA,MAAM,MAAM,SAAS,GAAG,cAAc,IAAI,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;AACzF;AACA,MAAM,IAAI,SAAS,EAAE;AACrB,QAAQ,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,SAAS,CAAC,CAAC;AAC/C,OAAO;AACP,KAAK;AACL,GAAG;AACH;AACA,EAAE,OAAO,SAAS,CAAC;AACnB;;AC5CA,MAAM,qBAAqB,GAAG,OAAO,cAAc,KAAK,WAAW,CAAC;AACpE;AACA,mBAAe,qBAAqB,IAAI,UAAU,MAAM,EAAE;AAC1D,EAAE,OAAO,IAAI,OAAO,CAAC,SAAS,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE;AAClE,IAAI,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;AAC1C,IAAI,IAAI,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;AACnC,IAAI,MAAM,cAAc,GAAGQ,cAAY,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC;AAC1E,IAAI,IAAI,CAAC,YAAY,EAAE,gBAAgB,EAAE,kBAAkB,CAAC,GAAG,OAAO,CAAC;AACvE,IAAI,IAAI,UAAU,CAAC;AACnB,IAAI,IAAI,eAAe,EAAE,iBAAiB,CAAC;AAC3C,IAAI,IAAI,WAAW,EAAE,aAAa,CAAC;AACnC;AACA,IAAI,SAAS,IAAI,GAAG;AACpB,MAAM,WAAW,IAAI,WAAW,EAAE,CAAC;AACnC,MAAM,aAAa,IAAI,aAAa,EAAE,CAAC;AACvC;AACA,MAAM,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;AACzE;AACA,MAAM,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;AAChF,KAAK;AACL;AACA,IAAI,IAAI,OAAO,GAAG,IAAI,cAAc,EAAE,CAAC;AACvC;AACA,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,WAAW,EAAE,EAAE,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AAClE;AACA;AACA,IAAI,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;AACtC;AACA,IAAI,SAAS,SAAS,GAAG;AACzB,MAAM,IAAI,CAAC,OAAO,EAAE;AACpB,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,MAAM,eAAe,GAAGA,cAAY,CAAC,IAAI;AAC/C,QAAQ,uBAAuB,IAAI,OAAO,IAAI,OAAO,CAAC,qBAAqB,EAAE;AAC7E,OAAO,CAAC;AACR,MAAM,MAAM,YAAY,GAAG,CAAC,YAAY,IAAI,YAAY,KAAK,MAAM,IAAI,YAAY,KAAK,MAAM;AAC9F,QAAQ,OAAO,CAAC,YAAY,GAAG,OAAO,CAAC,QAAQ,CAAC;AAChD,MAAM,MAAM,QAAQ,GAAG;AACvB,QAAQ,IAAI,EAAE,YAAY;AAC1B,QAAQ,MAAM,EAAE,OAAO,CAAC,MAAM;AAC9B,QAAQ,UAAU,EAAE,OAAO,CAAC,UAAU;AACtC,QAAQ,OAAO,EAAE,eAAe;AAChC,QAAQ,MAAM;AACd,QAAQ,OAAO;AACf,OAAO,CAAC;AACR;AACA,MAAM,MAAM,CAAC,SAAS,QAAQ,CAAC,KAAK,EAAE;AACtC,QAAQ,OAAO,CAAC,KAAK,CAAC,CAAC;AACvB,QAAQ,IAAI,EAAE,CAAC;AACf,OAAO,EAAE,SAAS,OAAO,CAAC,GAAG,EAAE;AAC/B,QAAQ,MAAM,CAAC,GAAG,CAAC,CAAC;AACpB,QAAQ,IAAI,EAAE,CAAC;AACf,OAAO,EAAE,QAAQ,CAAC,CAAC;AACnB;AACA;AACA,MAAM,OAAO,GAAG,IAAI,CAAC;AACrB,KAAK;AACL;AACA,IAAI,IAAI,WAAW,IAAI,OAAO,EAAE;AAChC;AACA,MAAM,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC;AACpC,KAAK,MAAM;AACX;AACA,MAAM,OAAO,CAAC,kBAAkB,GAAG,SAAS,UAAU,GAAG;AACzD,QAAQ,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,UAAU,KAAK,CAAC,EAAE;AAClD,UAAU,OAAO;AACjB,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,QAAQ,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE;AAC1G,UAAU,OAAO;AACjB,SAAS;AACT;AACA;AACA,QAAQ,UAAU,CAAC,SAAS,CAAC,CAAC;AAC9B,OAAO,CAAC;AACR,KAAK;AACL;AACA;AACA,IAAI,OAAO,CAAC,OAAO,GAAG,SAAS,WAAW,GAAG;AAC7C,MAAM,IAAI,CAAC,OAAO,EAAE;AACpB,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,MAAM,CAAC,IAAIT,YAAU,CAAC,iBAAiB,EAAEA,YAAU,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AAC1F;AACA;AACA,MAAM,OAAO,GAAG,IAAI,CAAC;AACrB,KAAK,CAAC;AACN;AACA;AACA,IAAI,OAAO,CAAC,OAAO,GAAG,SAAS,WAAW,GAAG;AAC7C;AACA;AACA,MAAM,MAAM,CAAC,IAAIA,YAAU,CAAC,eAAe,EAAEA,YAAU,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AACvF;AACA;AACA,MAAM,OAAO,GAAG,IAAI,CAAC;AACrB,KAAK,CAAC;AACN;AACA;AACA,IAAI,OAAO,CAAC,SAAS,GAAG,SAAS,aAAa,GAAG;AACjD,MAAM,IAAI,mBAAmB,GAAG,OAAO,CAAC,OAAO,GAAG,aAAa,GAAG,OAAO,CAAC,OAAO,GAAG,aAAa,GAAG,kBAAkB,CAAC;AACvH,MAAM,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,oBAAoB,CAAC;AACxE,MAAM,IAAI,OAAO,CAAC,mBAAmB,EAAE;AACvC,QAAQ,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,CAAC;AAC1D,OAAO;AACP,MAAM,MAAM,CAAC,IAAIA,YAAU;AAC3B,QAAQ,mBAAmB;AAC3B,QAAQ,YAAY,CAAC,mBAAmB,GAAGA,YAAU,CAAC,SAAS,GAAGA,YAAU,CAAC,YAAY;AACzF,QAAQ,MAAM;AACd,QAAQ,OAAO,CAAC,CAAC,CAAC;AAClB;AACA;AACA,MAAM,OAAO,GAAG,IAAI,CAAC;AACrB,KAAK,CAAC;AACN;AACA;AACA,IAAI,WAAW,KAAK,SAAS,IAAI,cAAc,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;AACrE;AACA;AACA,IAAI,IAAI,kBAAkB,IAAI,OAAO,EAAE;AACvC,MAAMC,OAAK,CAAC,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,EAAE,SAAS,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE;AACjF,QAAQ,OAAO,CAAC,gBAAgB,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAC3C,OAAO,CAAC,CAAC;AACT,KAAK;AACL;AACA;AACA,IAAI,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE;AACrD,MAAM,OAAO,CAAC,eAAe,GAAG,CAAC,CAAC,OAAO,CAAC,eAAe,CAAC;AAC1D,KAAK;AACL;AACA;AACA,IAAI,IAAI,YAAY,IAAI,YAAY,KAAK,MAAM,EAAE;AACjD,MAAM,OAAO,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;AAClD,KAAK;AACL;AACA;AACA,IAAI,IAAI,kBAAkB,EAAE;AAC5B,MAAM,CAAC,CAAC,iBAAiB,EAAE,aAAa,CAAC,GAAG,oBAAoB,CAAC,kBAAkB,EAAE,IAAI,CAAC,EAAE;AAC5F,MAAM,OAAO,CAAC,gBAAgB,CAAC,UAAU,EAAE,iBAAiB,CAAC,CAAC;AAC9D,KAAK;AACL;AACA;AACA,IAAI,IAAI,gBAAgB,IAAI,OAAO,CAAC,MAAM,EAAE;AAC5C,MAAM,CAAC,CAAC,eAAe,EAAE,WAAW,CAAC,GAAG,oBAAoB,CAAC,gBAAgB,CAAC,EAAE;AAChF;AACA,MAAM,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;AACnE;AACA,MAAM,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;AAC9D,KAAK;AACL;AACA,IAAI,IAAI,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,MAAM,EAAE;AAC/C;AACA;AACA,MAAM,UAAU,GAAG,MAAM,IAAI;AAC7B,QAAQ,IAAI,CAAC,OAAO,EAAE;AACtB,UAAU,OAAO;AACjB,SAAS;AACT,QAAQ,MAAM,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,IAAI,GAAG,IAAIW,eAAa,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC;AAC3F,QAAQ,OAAO,CAAC,KAAK,EAAE,CAAC;AACxB,QAAQ,OAAO,GAAG,IAAI,CAAC;AACvB,OAAO,CAAC;AACR;AACA,MAAM,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;AACvE,MAAM,IAAI,OAAO,CAAC,MAAM,EAAE;AAC1B,QAAQ,OAAO,CAAC,MAAM,CAAC,OAAO,GAAG,UAAU,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;AACrG,OAAO;AACP,KAAK;AACL;AACA,IAAI,MAAM,QAAQ,GAAG,aAAa,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AAChD;AACA,IAAI,IAAI,QAAQ,IAAI,QAAQ,CAAC,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE;AACjE,MAAM,MAAM,CAAC,IAAIZ,YAAU,CAAC,uBAAuB,GAAG,QAAQ,GAAG,GAAG,EAAEA,YAAU,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC,CAAC;AAC3G,MAAM,OAAO;AACb,KAAK;AACL;AACA;AACA;AACA,IAAI,OAAO,CAAC,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,CAAC;AACtC,GAAG,CAAC,CAAC;AACL;;AChMA,MAAM,cAAc,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK;AAC7C,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,OAAO,GAAG,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;AACtE;AACA,EAAE,IAAI,OAAO,IAAI,MAAM,EAAE;AACzB,IAAI,IAAI,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;AAC3C;AACA,IAAI,IAAI,OAAO,CAAC;AAChB;AACA,IAAI,MAAM,OAAO,GAAG,UAAU,MAAM,EAAE;AACtC,MAAM,IAAI,CAAC,OAAO,EAAE;AACpB,QAAQ,OAAO,GAAG,IAAI,CAAC;AACvB,QAAQ,WAAW,EAAE,CAAC;AACtB,QAAQ,MAAM,GAAG,GAAG,MAAM,YAAY,KAAK,GAAG,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;AACnE,QAAQ,UAAU,CAAC,KAAK,CAAC,GAAG,YAAYA,YAAU,GAAG,GAAG,GAAG,IAAIY,eAAa,CAAC,GAAG,YAAY,KAAK,GAAG,GAAG,CAAC,OAAO,GAAG,GAAG,CAAC,CAAC,CAAC;AACxH,OAAO;AACP,MAAK;AACL;AACA,IAAI,IAAI,KAAK,GAAG,OAAO,IAAI,UAAU,CAAC,MAAM;AAC5C,MAAM,KAAK,GAAG,IAAI,CAAC;AACnB,MAAM,OAAO,CAAC,IAAIZ,YAAU,CAAC,CAAC,QAAQ,EAAE,OAAO,CAAC,eAAe,CAAC,EAAEA,YAAU,CAAC,SAAS,CAAC,EAAC;AACxF,KAAK,EAAE,OAAO,EAAC;AACf;AACA,IAAI,MAAM,WAAW,GAAG,MAAM;AAC9B,MAAM,IAAI,OAAO,EAAE;AACnB,QAAQ,KAAK,IAAI,YAAY,CAAC,KAAK,CAAC,CAAC;AACrC,QAAQ,KAAK,GAAG,IAAI,CAAC;AACrB,QAAQ,OAAO,CAAC,OAAO,CAAC,MAAM,IAAI;AAClC,UAAU,MAAM,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAC1G,SAAS,CAAC,CAAC;AACX,QAAQ,OAAO,GAAG,IAAI,CAAC;AACvB,OAAO;AACP,MAAK;AACL;AACA,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;AAC3E;AACA,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,UAAU,CAAC;AAChC;AACA,IAAI,MAAM,CAAC,WAAW,GAAG,MAAMC,OAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AACvD;AACA,IAAI,OAAO,MAAM,CAAC;AAClB,GAAG;AACH,EAAC;AACD;AACA,yBAAe,cAAc;;AC9CtB,MAAM,WAAW,GAAG,WAAW,KAAK,EAAE,SAAS,EAAE;AACxD,EAAE,IAAI,GAAG,GAAG,KAAK,CAAC,UAAU,CAAC;AAC7B;AACA,EAAE,IAAI,CAAC,SAAS,IAAI,GAAG,GAAG,SAAS,EAAE;AACrC,IAAI,MAAM,KAAK,CAAC;AAChB,IAAI,OAAO;AACX,GAAG;AACH;AACA,EAAE,IAAI,GAAG,GAAG,CAAC,CAAC;AACd,EAAE,IAAI,GAAG,CAAC;AACV;AACA,EAAE,OAAO,GAAG,GAAG,GAAG,EAAE;AACpB,IAAI,GAAG,GAAG,GAAG,GAAG,SAAS,CAAC;AAC1B,IAAI,MAAM,KAAK,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAChC,IAAI,GAAG,GAAG,GAAG,CAAC;AACd,GAAG;AACH,EAAC;AACD;AACO,MAAM,SAAS,GAAG,iBAAiB,QAAQ,EAAE,SAAS,EAAE;AAC/D,EAAE,WAAW,MAAM,KAAK,IAAI,UAAU,CAAC,QAAQ,CAAC,EAAE;AAClD,IAAI,OAAO,WAAW,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AACzC,GAAG;AACH,EAAC;AACD;AACA,MAAM,UAAU,GAAG,iBAAiB,MAAM,EAAE;AAC5C,EAAE,IAAI,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE;AACpC,IAAI,OAAO,MAAM,CAAC;AAClB,IAAI,OAAO;AACX,GAAG;AACH;AACA,EAAE,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;AACpC,EAAE,IAAI;AACN,IAAI,SAAS;AACb,MAAM,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;AAChD,MAAM,IAAI,IAAI,EAAE;AAChB,QAAQ,MAAM;AACd,OAAO;AACP,MAAM,MAAM,KAAK,CAAC;AAClB,KAAK;AACL,GAAG,SAAS;AACZ,IAAI,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC;AAC1B,GAAG;AACH,EAAC;AACD;AACO,MAAM,WAAW,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,KAAK;AACxE,EAAE,MAAM,QAAQ,GAAG,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAChD;AACA,EAAE,IAAI,KAAK,GAAG,CAAC,CAAC;AAChB,EAAE,IAAI,IAAI,CAAC;AACX,EAAE,IAAI,SAAS,GAAG,CAAC,CAAC,KAAK;AACzB,IAAI,IAAI,CAAC,IAAI,EAAE;AACf,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,MAAM,QAAQ,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC9B,KAAK;AACL,IAAG;AACH;AACA,EAAE,OAAO,IAAI,cAAc,CAAC;AAC5B,IAAI,MAAM,IAAI,CAAC,UAAU,EAAE;AAC3B,MAAM,IAAI;AACV,QAAQ,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;AACpD;AACA,QAAQ,IAAI,IAAI,EAAE;AAClB,SAAS,SAAS,EAAE,CAAC;AACrB,UAAU,UAAU,CAAC,KAAK,EAAE,CAAC;AAC7B,UAAU,OAAO;AACjB,SAAS;AACT;AACA,QAAQ,IAAI,GAAG,GAAG,KAAK,CAAC,UAAU,CAAC;AACnC,QAAQ,IAAI,UAAU,EAAE;AACxB,UAAU,IAAI,WAAW,GAAG,KAAK,IAAI,GAAG,CAAC;AACzC,UAAU,UAAU,CAAC,WAAW,CAAC,CAAC;AAClC,SAAS;AACT,QAAQ,UAAU,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;AAClD,OAAO,CAAC,OAAO,GAAG,EAAE;AACpB,QAAQ,SAAS,CAAC,GAAG,CAAC,CAAC;AACvB,QAAQ,MAAM,GAAG,CAAC;AAClB,OAAO;AACP,KAAK;AACL,IAAI,MAAM,CAAC,MAAM,EAAE;AACnB,MAAM,SAAS,CAAC,MAAM,CAAC,CAAC;AACxB,MAAM,OAAO,QAAQ,CAAC,MAAM,EAAE,CAAC;AAC/B,KAAK;AACL,GAAG,EAAE;AACL,IAAI,aAAa,EAAE,CAAC;AACpB,GAAG,CAAC;AACJ;;AC5EA,MAAM,gBAAgB,GAAG,OAAO,KAAK,KAAK,UAAU,IAAI,OAAO,OAAO,KAAK,UAAU,IAAI,OAAO,QAAQ,KAAK,UAAU,CAAC;AACxH,MAAM,yBAAyB,GAAG,gBAAgB,IAAI,OAAO,cAAc,KAAK,UAAU,CAAC;AAC3F;AACA;AACA,MAAM,UAAU,GAAG,gBAAgB,KAAK,OAAO,WAAW,KAAK,UAAU;AACzE,IAAI,CAAC,CAAC,OAAO,KAAK,CAAC,GAAG,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,IAAI,WAAW,EAAE,CAAC;AAClE,IAAI,OAAO,GAAG,KAAK,IAAI,UAAU,CAAC,MAAM,IAAI,QAAQ,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;AACxE,CAAC,CAAC;AACF;AACA,MAAM,IAAI,GAAG,CAAC,EAAE,EAAE,GAAG,IAAI,KAAK;AAC9B,EAAE,IAAI;AACN,IAAI,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;AACzB,GAAG,CAAC,OAAO,CAAC,EAAE;AACd,IAAI,OAAO,KAAK;AAChB,GAAG;AACH,EAAC;AACD;AACA,MAAM,qBAAqB,GAAG,yBAAyB,IAAI,IAAI,CAAC,MAAM;AACtE,EAAE,IAAI,cAAc,GAAG,KAAK,CAAC;AAC7B;AACA,EAAE,MAAM,cAAc,GAAG,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,EAAE;AACtD,IAAI,IAAI,EAAE,IAAI,cAAc,EAAE;AAC9B,IAAI,MAAM,EAAE,MAAM;AAClB,IAAI,IAAI,MAAM,GAAG;AACjB,MAAM,cAAc,GAAG,IAAI,CAAC;AAC5B,MAAM,OAAO,MAAM,CAAC;AACpB,KAAK;AACL,GAAG,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;AACjC;AACA,EAAE,OAAO,cAAc,IAAI,CAAC,cAAc,CAAC;AAC3C,CAAC,CAAC,CAAC;AACH;AACA,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,CAAC;AACrC;AACA,MAAM,sBAAsB,GAAG,yBAAyB;AACxD,EAAE,IAAI,CAAC,MAAMA,OAAK,CAAC,gBAAgB,CAAC,IAAI,QAAQ,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;AAC5D;AACA;AACA,MAAM,SAAS,GAAG;AAClB,EAAE,MAAM,EAAE,sBAAsB,KAAK,CAAC,GAAG,KAAK,GAAG,CAAC,IAAI,CAAC;AACvD,CAAC,CAAC;AACF;AACA,gBAAgB,KAAK,CAAC,CAAC,GAAG,KAAK;AAC/B,EAAE,CAAC,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,IAAI;AACxE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,SAAS,CAAC,IAAI,CAAC,GAAGA,OAAK,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,IAAI,CAAC,EAAE;AAC7F,MAAM,CAAC,CAAC,EAAE,MAAM,KAAK;AACrB,QAAQ,MAAM,IAAID,YAAU,CAAC,CAAC,eAAe,EAAE,IAAI,CAAC,kBAAkB,CAAC,EAAEA,YAAU,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC;AAC7G,OAAO,EAAC;AACR,GAAG,CAAC,CAAC;AACL,CAAC,EAAE,IAAI,QAAQ,CAAC,CAAC,CAAC;AAClB;AACA,MAAM,aAAa,GAAG,OAAO,IAAI,KAAK;AACtC,EAAE,IAAI,IAAI,IAAI,IAAI,EAAE;AACpB,IAAI,OAAO,CAAC,CAAC;AACb,GAAG;AACH;AACA,EAAE,GAAGC,OAAK,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;AACzB,IAAI,OAAO,IAAI,CAAC,IAAI,CAAC;AACrB,GAAG;AACH;AACA,EAAE,GAAGA,OAAK,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE;AACtC,IAAI,MAAM,QAAQ,GAAG,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,EAAE;AAClD,MAAM,MAAM,EAAE,MAAM;AACpB,MAAM,IAAI;AACV,KAAK,CAAC,CAAC;AACP,IAAI,OAAO,CAAC,MAAM,QAAQ,CAAC,WAAW,EAAE,EAAE,UAAU,CAAC;AACrD,GAAG;AACH;AACA,EAAE,GAAGA,OAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,IAAIA,OAAK,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE;AACjE,IAAI,OAAO,IAAI,CAAC,UAAU,CAAC;AAC3B,GAAG;AACH;AACA,EAAE,GAAGA,OAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE;AACpC,IAAI,IAAI,GAAG,IAAI,GAAG,EAAE,CAAC;AACrB,GAAG;AACH;AACA,EAAE,GAAGA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;AAC3B,IAAI,OAAO,CAAC,MAAM,UAAU,CAAC,IAAI,CAAC,EAAE,UAAU,CAAC;AAC/C,GAAG;AACH,EAAC;AACD;AACA,MAAM,iBAAiB,GAAG,OAAO,OAAO,EAAE,IAAI,KAAK;AACnD,EAAE,MAAM,MAAM,GAAGA,OAAK,CAAC,cAAc,CAAC,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;AAClE;AACA,EAAE,OAAO,MAAM,IAAI,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC;AACvD,EAAC;AACD;AACA,qBAAe,gBAAgB,KAAK,OAAO,MAAM,KAAK;AACtD,EAAE,IAAI;AACN,IAAI,GAAG;AACP,IAAI,MAAM;AACV,IAAI,IAAI;AACR,IAAI,MAAM;AACV,IAAI,WAAW;AACf,IAAI,OAAO;AACX,IAAI,kBAAkB;AACtB,IAAI,gBAAgB;AACpB,IAAI,YAAY;AAChB,IAAI,OAAO;AACX,IAAI,eAAe,GAAG,aAAa;AACnC,IAAI,YAAY;AAChB,GAAG,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;AAC5B;AACA,EAAE,YAAY,GAAG,YAAY,GAAG,CAAC,YAAY,GAAG,EAAE,EAAE,WAAW,EAAE,GAAG,MAAM,CAAC;AAC3E;AACA,EAAE,IAAI,cAAc,GAAGa,gBAAc,CAAC,CAAC,MAAM,EAAE,WAAW,IAAI,WAAW,CAAC,aAAa,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC;AACrG;AACA,EAAE,IAAI,OAAO,CAAC;AACd;AACA,EAAE,MAAM,WAAW,GAAG,cAAc,IAAI,cAAc,CAAC,WAAW,KAAK,MAAM;AAC7E,MAAM,cAAc,CAAC,WAAW,EAAE,CAAC;AACnC,GAAG,CAAC,CAAC;AACL;AACA,EAAE,IAAI,oBAAoB,CAAC;AAC3B;AACA,EAAE,IAAI;AACN,IAAI;AACJ,MAAM,gBAAgB,IAAI,qBAAqB,IAAI,MAAM,KAAK,KAAK,IAAI,MAAM,KAAK,MAAM;AACxF,MAAM,CAAC,oBAAoB,GAAG,MAAM,iBAAiB,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC;AAC3E,MAAM;AACN,MAAM,IAAI,QAAQ,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE;AACtC,QAAQ,MAAM,EAAE,MAAM;AACtB,QAAQ,IAAI,EAAE,IAAI;AAClB,QAAQ,MAAM,EAAE,MAAM;AACtB,OAAO,CAAC,CAAC;AACT;AACA,MAAM,IAAI,iBAAiB,CAAC;AAC5B;AACA,MAAM,IAAIb,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,iBAAiB,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,EAAE;AAChG,QAAQ,OAAO,CAAC,cAAc,CAAC,iBAAiB,EAAC;AACjD,OAAO;AACP;AACA,MAAM,IAAI,QAAQ,CAAC,IAAI,EAAE;AACzB,QAAQ,MAAM,CAAC,UAAU,EAAE,KAAK,CAAC,GAAG,sBAAsB;AAC1D,UAAU,oBAAoB;AAC9B,UAAU,oBAAoB,CAAC,cAAc,CAAC,gBAAgB,CAAC,CAAC;AAChE,SAAS,CAAC;AACV;AACA,QAAQ,IAAI,GAAG,WAAW,CAAC,QAAQ,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;AACjF,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,eAAe,CAAC,EAAE;AAC1C,MAAM,eAAe,GAAG,eAAe,GAAG,SAAS,GAAG,MAAM,CAAC;AAC7D,KAAK;AACL;AACA;AACA;AACA,IAAI,MAAM,sBAAsB,GAAG,aAAa,IAAI,OAAO,CAAC,SAAS,CAAC;AACtE,IAAI,OAAO,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE;AAC/B,MAAM,GAAG,YAAY;AACrB,MAAM,MAAM,EAAE,cAAc;AAC5B,MAAM,MAAM,EAAE,MAAM,CAAC,WAAW,EAAE;AAClC,MAAM,OAAO,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC,MAAM,EAAE;AAC3C,MAAM,IAAI,EAAE,IAAI;AAChB,MAAM,MAAM,EAAE,MAAM;AACpB,MAAM,WAAW,EAAE,sBAAsB,GAAG,eAAe,GAAG,SAAS;AACvE,KAAK,CAAC,CAAC;AACP;AACA,IAAI,IAAI,QAAQ,GAAG,MAAM,KAAK,CAAC,OAAO,CAAC,CAAC;AACxC;AACA,IAAI,MAAM,gBAAgB,GAAG,sBAAsB,KAAK,YAAY,KAAK,QAAQ,IAAI,YAAY,KAAK,UAAU,CAAC,CAAC;AAClH;AACA,IAAI,IAAI,sBAAsB,KAAK,kBAAkB,KAAK,gBAAgB,IAAI,WAAW,CAAC,CAAC,EAAE;AAC7F,MAAM,MAAM,OAAO,GAAG,EAAE,CAAC;AACzB;AACA,MAAM,CAAC,QAAQ,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,IAAI;AAC1D,QAAQ,OAAO,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;AACvC,OAAO,CAAC,CAAC;AACT;AACA,MAAM,MAAM,qBAAqB,GAAGA,OAAK,CAAC,cAAc,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC,CAAC;AACjG;AACA,MAAM,MAAM,CAAC,UAAU,EAAE,KAAK,CAAC,GAAG,kBAAkB,IAAI,sBAAsB;AAC9E,QAAQ,qBAAqB;AAC7B,QAAQ,oBAAoB,CAAC,cAAc,CAAC,kBAAkB,CAAC,EAAE,IAAI,CAAC;AACtE,OAAO,IAAI,EAAE,CAAC;AACd;AACA,MAAM,QAAQ,GAAG,IAAI,QAAQ;AAC7B,QAAQ,WAAW,CAAC,QAAQ,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,MAAM;AACzE,UAAU,KAAK,IAAI,KAAK,EAAE,CAAC;AAC3B,UAAU,WAAW,IAAI,WAAW,EAAE,CAAC;AACvC,SAAS,CAAC;AACV,QAAQ,OAAO;AACf,OAAO,CAAC;AACR,KAAK;AACL;AACA,IAAI,YAAY,GAAG,YAAY,IAAI,MAAM,CAAC;AAC1C;AACA,IAAI,IAAI,YAAY,GAAG,MAAM,SAAS,CAACA,OAAK,CAAC,OAAO,CAAC,SAAS,EAAE,YAAY,CAAC,IAAI,MAAM,CAAC,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AAC3G;AACA,IAAI,CAAC,gBAAgB,IAAI,WAAW,IAAI,WAAW,EAAE,CAAC;AACtD;AACA,IAAI,OAAO,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK;AAClD,MAAM,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE;AAC9B,QAAQ,IAAI,EAAE,YAAY;AAC1B,QAAQ,OAAO,EAAEQ,cAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;AACpD,QAAQ,MAAM,EAAE,QAAQ,CAAC,MAAM;AAC/B,QAAQ,UAAU,EAAE,QAAQ,CAAC,UAAU;AACvC,QAAQ,MAAM;AACd,QAAQ,OAAO;AACf,OAAO,EAAC;AACR,KAAK,CAAC;AACN,GAAG,CAAC,OAAO,GAAG,EAAE;AAChB,IAAI,WAAW,IAAI,WAAW,EAAE,CAAC;AACjC;AACA,IAAI,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,WAAW,IAAI,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE;AACvE,MAAM,MAAM,MAAM,CAAC,MAAM;AACzB,QAAQ,IAAIT,YAAU,CAAC,eAAe,EAAEA,YAAU,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC;AAChF,QAAQ;AACR,UAAU,KAAK,EAAE,GAAG,CAAC,KAAK,IAAI,GAAG;AACjC,SAAS;AACT,OAAO;AACP,KAAK;AACL;AACA,IAAI,MAAMA,YAAU,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACjE,GAAG;AACH,CAAC,CAAC;;AC5NF,MAAM,aAAa,GAAG;AACtB,EAAE,IAAI,EAAE,WAAW;AACnB,EAAE,GAAG,EAAE,UAAU;AACjB,EAAE,KAAK,EAAE,YAAY;AACrB,EAAC;AACD;AACAC,OAAK,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,EAAE,EAAE,KAAK,KAAK;AAC5C,EAAE,IAAI,EAAE,EAAE;AACV,IAAI,IAAI;AACR,MAAM,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AACjD,KAAK,CAAC,OAAO,CAAC,EAAE;AAChB;AACA,KAAK;AACL,IAAI,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,aAAa,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AACtD,GAAG;AACH,CAAC,CAAC,CAAC;AACH;AACA,MAAM,YAAY,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;AAC/C;AACA,MAAM,gBAAgB,GAAG,CAAC,OAAO,KAAKA,OAAK,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,CAAC;AACzG;AACA,iBAAe;AACf,EAAE,UAAU,EAAE,CAAC,QAAQ,KAAK;AAC5B,IAAI,QAAQ,GAAGA,OAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,QAAQ,GAAG,CAAC,QAAQ,CAAC,CAAC;AAC/D;AACA,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC;AAC9B,IAAI,IAAI,aAAa,CAAC;AACtB,IAAI,IAAI,OAAO,CAAC;AAChB;AACA,IAAI,MAAM,eAAe,GAAG,EAAE,CAAC;AAC/B;AACA,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC,EAAE,EAAE;AACrC,MAAM,aAAa,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;AAClC,MAAM,IAAI,EAAE,CAAC;AACb;AACA,MAAM,OAAO,GAAG,aAAa,CAAC;AAC9B;AACA,MAAM,IAAI,CAAC,gBAAgB,CAAC,aAAa,CAAC,EAAE;AAC5C,QAAQ,OAAO,GAAG,aAAa,CAAC,CAAC,EAAE,GAAG,MAAM,CAAC,aAAa,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;AAC5E;AACA,QAAQ,IAAI,OAAO,KAAK,SAAS,EAAE;AACnC,UAAU,MAAM,IAAID,YAAU,CAAC,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;AAC1D,SAAS;AACT,OAAO;AACP;AACA,MAAM,IAAI,OAAO,EAAE;AACnB,QAAQ,MAAM;AACd,OAAO;AACP;AACA,MAAM,eAAe,CAAC,EAAE,IAAI,GAAG,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;AAC/C,KAAK;AACL;AACA,IAAI,IAAI,CAAC,OAAO,EAAE;AAClB;AACA,MAAM,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC;AACrD,SAAS,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC;AAC9C,WAAW,KAAK,KAAK,KAAK,GAAG,qCAAqC,GAAG,+BAA+B,CAAC;AACrG,SAAS,CAAC;AACV;AACA,MAAM,IAAI,CAAC,GAAG,MAAM;AACpB,SAAS,OAAO,CAAC,MAAM,GAAG,CAAC,GAAG,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AACjH,QAAQ,yBAAyB,CAAC;AAClC;AACA,MAAM,MAAM,IAAIA,YAAU;AAC1B,QAAQ,CAAC,qDAAqD,CAAC,GAAG,CAAC;AACnE,QAAQ,iBAAiB;AACzB,OAAO,CAAC;AACR,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC;AACnB,GAAG;AACH,EAAE,QAAQ,EAAE,aAAa;AACzB;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,4BAA4B,CAAC,MAAM,EAAE;AAC9C,EAAE,IAAI,MAAM,CAAC,WAAW,EAAE;AAC1B,IAAI,MAAM,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC;AAC1C,GAAG;AACH;AACA,EAAE,IAAI,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE;AAC9C,IAAI,MAAM,IAAIY,eAAa,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC1C,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,eAAe,CAAC,MAAM,EAAE;AAChD,EAAE,4BAA4B,CAAC,MAAM,CAAC,CAAC;AACvC;AACA,EAAE,MAAM,CAAC,OAAO,GAAGH,cAAY,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AACrD;AACA;AACA,EAAE,MAAM,CAAC,IAAI,GAAG,aAAa,CAAC,IAAI;AAClC,IAAI,MAAM;AACV,IAAI,MAAM,CAAC,gBAAgB;AAC3B,GAAG,CAAC;AACJ;AACA,EAAE,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE;AAC9D,IAAI,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,mCAAmC,EAAE,KAAK,CAAC,CAAC;AAC9E,GAAG;AACH;AACA,EAAE,MAAM,OAAO,GAAG,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,OAAO,IAAIC,UAAQ,CAAC,OAAO,CAAC,CAAC;AAC1E;AACA,EAAE,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,SAAS,mBAAmB,CAAC,QAAQ,EAAE;AACrE,IAAI,4BAA4B,CAAC,MAAM,CAAC,CAAC;AACzC;AACA;AACA,IAAI,QAAQ,CAAC,IAAI,GAAG,aAAa,CAAC,IAAI;AACtC,MAAM,MAAM;AACZ,MAAM,MAAM,CAAC,iBAAiB;AAC9B,MAAM,QAAQ;AACd,KAAK,CAAC;AACN;AACA,IAAI,QAAQ,CAAC,OAAO,GAAGD,cAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAC3D;AACA,IAAI,OAAO,QAAQ,CAAC;AACpB,GAAG,EAAE,SAAS,kBAAkB,CAAC,MAAM,EAAE;AACzC,IAAI,IAAI,CAACE,UAAQ,CAAC,MAAM,CAAC,EAAE;AAC3B,MAAM,4BAA4B,CAAC,MAAM,CAAC,CAAC;AAC3C;AACA;AACA,MAAM,IAAI,MAAM,IAAI,MAAM,CAAC,QAAQ,EAAE;AACrC,QAAQ,MAAM,CAAC,QAAQ,CAAC,IAAI,GAAG,aAAa,CAAC,IAAI;AACjD,UAAU,MAAM;AAChB,UAAU,MAAM,CAAC,iBAAiB;AAClC,UAAU,MAAM,CAAC,QAAQ;AACzB,SAAS,CAAC;AACV,QAAQ,MAAM,CAAC,QAAQ,CAAC,OAAO,GAAGF,cAAY,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAC7E,OAAO;AACP,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAClC,GAAG,CAAC,CAAC;AACL;;AChFO,MAAMM,SAAO,GAAG,OAAO;;ACK9B,MAAMC,YAAU,GAAG,EAAE,CAAC;AACtB;AACA;AACA,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC,KAAK;AACrF,EAAEA,YAAU,CAAC,IAAI,CAAC,GAAG,SAAS,SAAS,CAAC,KAAK,EAAE;AAC/C,IAAI,OAAO,OAAO,KAAK,KAAK,IAAI,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC;AACtE,GAAG,CAAC;AACJ,CAAC,CAAC,CAAC;AACH;AACA,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAA,YAAU,CAAC,YAAY,GAAG,SAAS,YAAY,CAAC,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE;AAC7E,EAAE,SAAS,aAAa,CAAC,GAAG,EAAE,IAAI,EAAE;AACpC,IAAI,OAAO,UAAU,GAAGD,SAAO,GAAG,0BAA0B,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,IAAI,OAAO,GAAG,IAAI,GAAG,OAAO,GAAG,EAAE,CAAC,CAAC;AACnH,GAAG;AACH;AACA;AACA,EAAE,OAAO,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,KAAK;AAC/B,IAAI,IAAI,SAAS,KAAK,KAAK,EAAE;AAC7B,MAAM,MAAM,IAAIf,YAAU;AAC1B,QAAQ,aAAa,CAAC,GAAG,EAAE,mBAAmB,IAAI,OAAO,GAAG,MAAM,GAAG,OAAO,GAAG,EAAE,CAAC,CAAC;AACnF,QAAQA,YAAU,CAAC,cAAc;AACjC,OAAO,CAAC;AACR,KAAK;AACL;AACA,IAAI,IAAI,OAAO,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAE;AAC7C,MAAM,kBAAkB,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;AACrC;AACA,MAAM,OAAO,CAAC,IAAI;AAClB,QAAQ,aAAa;AACrB,UAAU,GAAG;AACb,UAAU,8BAA8B,GAAG,OAAO,GAAG,yCAAyC;AAC9F,SAAS;AACT,OAAO,CAAC;AACR,KAAK;AACL;AACA,IAAI,OAAO,SAAS,GAAG,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC;AAC1D,GAAG,CAAC;AACJ,CAAC,CAAC;AACF;AACAgB,YAAU,CAAC,QAAQ,GAAG,SAAS,QAAQ,CAAC,eAAe,EAAE;AACzD,EAAE,OAAO,CAAC,KAAK,EAAE,GAAG,KAAK;AACzB;AACA,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,CAAC,4BAA4B,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC;AACzE,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG;AACH,CAAC,CAAC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE;AACtD,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;AACnC,IAAI,MAAM,IAAIhB,YAAU,CAAC,2BAA2B,EAAEA,YAAU,CAAC,oBAAoB,CAAC,CAAC;AACvF,GAAG;AACH,EAAE,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACpC,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;AACtB,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AAClB,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AACxB,IAAI,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AAClC,IAAI,IAAI,SAAS,EAAE;AACnB,MAAM,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;AACjC,MAAM,MAAM,MAAM,GAAG,KAAK,KAAK,SAAS,IAAI,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;AAC3E,MAAM,IAAI,MAAM,KAAK,IAAI,EAAE;AAC3B,QAAQ,MAAM,IAAIA,YAAU,CAAC,SAAS,GAAG,GAAG,GAAG,WAAW,GAAG,MAAM,EAAEA,YAAU,CAAC,oBAAoB,CAAC,CAAC;AACtG,OAAO;AACP,MAAM,SAAS;AACf,KAAK;AACL,IAAI,IAAI,YAAY,KAAK,IAAI,EAAE;AAC/B,MAAM,MAAM,IAAIA,YAAU,CAAC,iBAAiB,GAAG,GAAG,EAAEA,YAAU,CAAC,cAAc,CAAC,CAAC;AAC/E,KAAK;AACL,GAAG;AACH,CAAC;AACD;AACA,kBAAe;AACf,EAAE,aAAa;AACf,cAAEgB,YAAU;AACZ,CAAC;;ACvFD,MAAM,UAAU,GAAG,SAAS,CAAC,UAAU,CAAC;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,OAAK,CAAC;AACZ,EAAE,WAAW,CAAC,cAAc,EAAE;AAC9B,IAAI,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;AACnC,IAAI,IAAI,CAAC,YAAY,GAAG;AACxB,MAAM,OAAO,EAAE,IAAIC,oBAAkB,EAAE;AACvC,MAAM,QAAQ,EAAE,IAAIA,oBAAkB,EAAE;AACxC,KAAK,CAAC;AACN,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,MAAM,OAAO,CAAC,WAAW,EAAE,MAAM,EAAE;AACrC,IAAI,IAAI;AACR,MAAM,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;AACtD,KAAK,CAAC,OAAO,GAAG,EAAE;AAClB,MAAM,IAAI,GAAG,YAAY,KAAK,EAAE;AAChC,QAAQ,IAAI,KAAK,GAAG,EAAE,CAAC;AACvB;AACA,QAAQ,KAAK,CAAC,iBAAiB,GAAG,KAAK,CAAC,iBAAiB,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC,CAAC;AACzF;AACA;AACA,QAAQ,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC;AAC1E,QAAQ,IAAI;AACZ,UAAU,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE;AAC1B,YAAY,GAAG,CAAC,KAAK,GAAG,KAAK,CAAC;AAC9B;AACA,WAAW,MAAM,IAAI,KAAK,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,EAAE;AAC3F,YAAY,GAAG,CAAC,KAAK,IAAI,IAAI,GAAG,MAAK;AACrC,WAAW;AACX,SAAS,CAAC,OAAO,CAAC,EAAE;AACpB;AACA,SAAS;AACT,OAAO;AACP;AACA,MAAM,MAAM,GAAG,CAAC;AAChB,KAAK;AACL,GAAG;AACH;AACA,EAAE,QAAQ,CAAC,WAAW,EAAE,MAAM,EAAE;AAChC;AACA;AACA,IAAI,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;AACzC,MAAM,MAAM,GAAG,MAAM,IAAI,EAAE,CAAC;AAC5B,MAAM,MAAM,CAAC,GAAG,GAAG,WAAW,CAAC;AAC/B,KAAK,MAAM;AACX,MAAM,MAAM,GAAG,WAAW,IAAI,EAAE,CAAC;AACjC,KAAK;AACL;AACA,IAAI,MAAM,GAAGL,aAAW,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AAChD;AACA,IAAI,MAAM,CAAC,YAAY,EAAE,gBAAgB,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC;AAC7D;AACA,IAAI,IAAI,YAAY,KAAK,SAAS,EAAE;AACpC,MAAM,SAAS,CAAC,aAAa,CAAC,YAAY,EAAE;AAC5C,QAAQ,iBAAiB,EAAE,UAAU,CAAC,YAAY,CAAC,UAAU,CAAC,OAAO,CAAC;AACtE,QAAQ,iBAAiB,EAAE,UAAU,CAAC,YAAY,CAAC,UAAU,CAAC,OAAO,CAAC;AACtE,QAAQ,mBAAmB,EAAE,UAAU,CAAC,YAAY,CAAC,UAAU,CAAC,OAAO,CAAC;AACxE,OAAO,EAAE,KAAK,CAAC,CAAC;AAChB,KAAK;AACL;AACA,IAAI,IAAI,gBAAgB,IAAI,IAAI,EAAE;AAClC,MAAM,IAAIZ,OAAK,CAAC,UAAU,CAAC,gBAAgB,CAAC,EAAE;AAC9C,QAAQ,MAAM,CAAC,gBAAgB,GAAG;AAClC,UAAU,SAAS,EAAE,gBAAgB;AACrC,UAAS;AACT,OAAO,MAAM;AACb,QAAQ,SAAS,CAAC,aAAa,CAAC,gBAAgB,EAAE;AAClD,UAAU,MAAM,EAAE,UAAU,CAAC,QAAQ;AACrC,UAAU,SAAS,EAAE,UAAU,CAAC,QAAQ;AACxC,SAAS,EAAE,IAAI,CAAC,CAAC;AACjB,OAAO;AACP,KAAK;AACL;AACA,IAAI,SAAS,CAAC,aAAa,CAAC,MAAM,EAAE;AACpC,MAAM,OAAO,EAAE,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC;AAC7C,MAAM,aAAa,EAAE,UAAU,CAAC,QAAQ,CAAC,eAAe,CAAC;AACzD,KAAK,EAAE,IAAI,CAAC,CAAC;AACb;AACA;AACA,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,IAAI,KAAK,EAAE,WAAW,EAAE,CAAC;AACnF;AACA;AACA,IAAI,IAAI,cAAc,GAAG,OAAO,IAAIA,OAAK,CAAC,KAAK;AAC/C,MAAM,OAAO,CAAC,MAAM;AACpB,MAAM,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC;AAC5B,KAAK,CAAC;AACN;AACA,IAAI,OAAO,IAAIA,OAAK,CAAC,OAAO;AAC5B,MAAM,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,CAAC;AACjE,MAAM,CAAC,MAAM,KAAK;AAClB,QAAQ,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC;AAC/B,OAAO;AACP,KAAK,CAAC;AACN;AACA,IAAI,MAAM,CAAC,OAAO,GAAGQ,cAAY,CAAC,MAAM,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;AAClE;AACA;AACA,IAAI,MAAM,uBAAuB,GAAG,EAAE,CAAC;AACvC,IAAI,IAAI,8BAA8B,GAAG,IAAI,CAAC;AAC9C,IAAI,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,0BAA0B,CAAC,WAAW,EAAE;AACvF,MAAM,IAAI,OAAO,WAAW,CAAC,OAAO,KAAK,UAAU,IAAI,WAAW,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,KAAK,EAAE;AAC9F,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,8BAA8B,GAAG,8BAA8B,IAAI,WAAW,CAAC,WAAW,CAAC;AACjG;AACA,MAAM,uBAAuB,CAAC,OAAO,CAAC,WAAW,CAAC,SAAS,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;AACnF,KAAK,CAAC,CAAC;AACP;AACA,IAAI,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACxC,IAAI,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,OAAO,CAAC,SAAS,wBAAwB,CAAC,WAAW,EAAE;AACtF,MAAM,wBAAwB,CAAC,IAAI,CAAC,WAAW,CAAC,SAAS,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;AACjF,KAAK,CAAC,CAAC;AACP;AACA,IAAI,IAAI,OAAO,CAAC;AAChB,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC;AACd,IAAI,IAAI,GAAG,CAAC;AACZ;AACA,IAAI,IAAI,CAAC,8BAA8B,EAAE;AACzC,MAAM,MAAM,KAAK,GAAG,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC,CAAC;AAC5D,MAAM,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,uBAAuB,CAAC,CAAC;AAC1D,MAAM,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,wBAAwB,CAAC,CAAC;AACxD,MAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC;AACzB;AACA,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AACxC;AACA,MAAM,OAAO,CAAC,GAAG,GAAG,EAAE;AACtB,QAAQ,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACvD,OAAO;AACP;AACA,MAAM,OAAO,OAAO,CAAC;AACrB,KAAK;AACL;AACA,IAAI,GAAG,GAAG,uBAAuB,CAAC,MAAM,CAAC;AACzC;AACA,IAAI,IAAI,SAAS,GAAG,MAAM,CAAC;AAC3B;AACA,IAAI,CAAC,GAAG,CAAC,CAAC;AACV;AACA,IAAI,OAAO,CAAC,GAAG,GAAG,EAAE;AACpB,MAAM,MAAM,WAAW,GAAG,uBAAuB,CAAC,CAAC,EAAE,CAAC,CAAC;AACvD,MAAM,MAAM,UAAU,GAAG,uBAAuB,CAAC,CAAC,EAAE,CAAC,CAAC;AACtD,MAAM,IAAI;AACV,QAAQ,SAAS,GAAG,WAAW,CAAC,SAAS,CAAC,CAAC;AAC3C,OAAO,CAAC,OAAO,KAAK,EAAE;AACtB,QAAQ,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;AACrC,QAAQ,MAAM;AACd,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAI;AACR,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;AACtD,KAAK,CAAC,OAAO,KAAK,EAAE;AACpB,MAAM,OAAO,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACnC,KAAK;AACL;AACA,IAAI,CAAC,GAAG,CAAC,CAAC;AACV,IAAI,GAAG,GAAG,wBAAwB,CAAC,MAAM,CAAC;AAC1C;AACA,IAAI,OAAO,CAAC,GAAG,GAAG,EAAE;AACpB,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC,EAAE,CAAC,EAAE,wBAAwB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAC3F,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC;AACnB,GAAG;AACH;AACA,EAAE,MAAM,CAAC,MAAM,EAAE;AACjB,IAAI,MAAM,GAAGI,aAAW,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AAChD,IAAI,MAAM,QAAQ,GAAG,aAAa,CAAC,MAAM,CAAC,OAAO,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;AAC/D,IAAI,OAAO,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,gBAAgB,CAAC,CAAC;AACtE,GAAG;AACH,CAAC;AACD;AACA;AACAZ,OAAK,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,SAAS,mBAAmB,CAAC,MAAM,EAAE;AACzF;AACA,EAAEgB,OAAK,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,SAAS,GAAG,EAAE,MAAM,EAAE;AAClD,IAAI,OAAO,IAAI,CAAC,OAAO,CAACJ,aAAW,CAAC,MAAM,IAAI,EAAE,EAAE;AAClD,MAAM,MAAM;AACZ,MAAM,GAAG;AACT,MAAM,IAAI,EAAE,CAAC,MAAM,IAAI,EAAE,EAAE,IAAI;AAC/B,KAAK,CAAC,CAAC,CAAC;AACR,GAAG,CAAC;AACJ,CAAC,CAAC,CAAC;AACH;AACAZ,OAAK,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,SAAS,qBAAqB,CAAC,MAAM,EAAE;AAC/E;AACA;AACA,EAAE,SAAS,kBAAkB,CAAC,MAAM,EAAE;AACtC,IAAI,OAAO,SAAS,UAAU,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE;AAClD,MAAM,OAAO,IAAI,CAAC,OAAO,CAACY,aAAW,CAAC,MAAM,IAAI,EAAE,EAAE;AACpD,QAAQ,MAAM;AACd,QAAQ,OAAO,EAAE,MAAM,GAAG;AAC1B,UAAU,cAAc,EAAE,qBAAqB;AAC/C,SAAS,GAAG,EAAE;AACd,QAAQ,GAAG;AACX,QAAQ,IAAI;AACZ,OAAO,CAAC,CAAC,CAAC;AACV,KAAK,CAAC;AACN,GAAG;AACH;AACA,EAAEI,OAAK,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,kBAAkB,EAAE,CAAC;AACjD;AACA,EAAEA,OAAK,CAAC,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;AAC9D,CAAC,CAAC,CAAC;AACH;AACA,gBAAeA,OAAK;;ACpOpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAME,aAAW,CAAC;AAClB,EAAE,WAAW,CAAC,QAAQ,EAAE;AACxB,IAAI,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;AACxC,MAAM,MAAM,IAAI,SAAS,CAAC,8BAA8B,CAAC,CAAC;AAC1D,KAAK;AACL;AACA,IAAI,IAAI,cAAc,CAAC;AACvB;AACA,IAAI,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC,SAAS,eAAe,CAAC,OAAO,EAAE;AACjE,MAAM,cAAc,GAAG,OAAO,CAAC;AAC/B,KAAK,CAAC,CAAC;AACP;AACA,IAAI,MAAM,KAAK,GAAG,IAAI,CAAC;AACvB;AACA;AACA,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI;AAChC,MAAM,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO;AACpC;AACA,MAAM,IAAI,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC;AACtC;AACA,MAAM,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AACtB,QAAQ,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;AACpC,OAAO;AACP,MAAM,KAAK,CAAC,UAAU,GAAG,IAAI,CAAC;AAC9B,KAAK,CAAC,CAAC;AACP;AACA;AACA,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,WAAW,IAAI;AACvC,MAAM,IAAI,QAAQ,CAAC;AACnB;AACA,MAAM,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,OAAO,IAAI;AAC7C,QAAQ,KAAK,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;AACjC,QAAQ,QAAQ,GAAG,OAAO,CAAC;AAC3B,OAAO,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AAC3B;AACA,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,MAAM,GAAG;AACzC,QAAQ,KAAK,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;AACpC,OAAO,CAAC;AACR;AACA,MAAM,OAAO,OAAO,CAAC;AACrB,KAAK,CAAC;AACN;AACA,IAAI,QAAQ,CAAC,SAAS,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE;AACvD,MAAM,IAAI,KAAK,CAAC,MAAM,EAAE;AACxB;AACA,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,KAAK,CAAC,MAAM,GAAG,IAAIP,eAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACjE,MAAM,cAAc,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AACnC,KAAK,CAAC,CAAC;AACP,GAAG;AACH;AACA;AACA;AACA;AACA,EAAE,gBAAgB,GAAG;AACrB,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE;AACrB,MAAM,MAAM,IAAI,CAAC,MAAM,CAAC;AACxB,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,EAAE,SAAS,CAAC,QAAQ,EAAE;AACtB,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE;AACrB,MAAM,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,MAAM,OAAO;AACb,KAAK;AACL;AACA,IAAI,IAAI,IAAI,CAAC,UAAU,EAAE;AACzB,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AACrC,KAAK,MAAM;AACX,MAAM,IAAI,CAAC,UAAU,GAAG,CAAC,QAAQ,CAAC,CAAC;AACnC,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,EAAE,WAAW,CAAC,QAAQ,EAAE;AACxB,IAAI,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE;AAC1B,MAAM,OAAO;AACb,KAAK;AACL,IAAI,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;AACpD,IAAI,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE;AACtB,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;AACvC,KAAK;AACL,GAAG;AACH;AACA,EAAE,aAAa,GAAG;AAClB,IAAI,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;AAC7C;AACA,IAAI,MAAM,KAAK,GAAG,CAAC,GAAG,KAAK;AAC3B,MAAM,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC5B,KAAK,CAAC;AACN;AACA,IAAI,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC1B;AACA,IAAI,UAAU,CAAC,MAAM,CAAC,WAAW,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;AAClE;AACA,IAAI,OAAO,UAAU,CAAC,MAAM,CAAC;AAC7B,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,EAAE,OAAO,MAAM,GAAG;AAClB,IAAI,IAAI,MAAM,CAAC;AACf,IAAI,MAAM,KAAK,GAAG,IAAIO,aAAW,CAAC,SAAS,QAAQ,CAAC,CAAC,EAAE;AACvD,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,KAAK,CAAC,CAAC;AACP,IAAI,OAAO;AACX,MAAM,KAAK;AACX,MAAM,MAAM;AACZ,KAAK,CAAC;AACN,GAAG;AACH,CAAC;AACD;AACA,sBAAeA,aAAW;;ACpI1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAASC,QAAM,CAAC,QAAQ,EAAE;AACzC,EAAE,OAAO,SAAS,IAAI,CAAC,GAAG,EAAE;AAC5B,IAAI,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AACrC,GAAG,CAAC;AACJ;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAASC,cAAY,CAAC,OAAO,EAAE;AAC9C,EAAE,OAAOpB,OAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,OAAO,CAAC,YAAY,KAAK,IAAI,CAAC,CAAC;AACpE;;ACbA,MAAMqB,gBAAc,GAAG;AACvB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,kBAAkB,EAAE,GAAG;AACzB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,EAAE,EAAE,GAAG;AACT,EAAE,OAAO,EAAE,GAAG;AACd,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,2BAA2B,EAAE,GAAG;AAClC,EAAE,SAAS,EAAE,GAAG;AAChB,EAAE,YAAY,EAAE,GAAG;AACnB,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,WAAW,EAAE,GAAG;AAClB,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,MAAM,EAAE,GAAG;AACb,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,gBAAgB,EAAE,GAAG;AACvB,EAAE,KAAK,EAAE,GAAG;AACZ,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,WAAW,EAAE,GAAG;AAClB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,MAAM,EAAE,GAAG;AACb,EAAE,iBAAiB,EAAE,GAAG;AACxB,EAAE,iBAAiB,EAAE,GAAG;AACxB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,YAAY,EAAE,GAAG;AACnB,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,SAAS,EAAE,GAAG;AAChB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,gBAAgB,EAAE,GAAG;AACvB,EAAE,aAAa,EAAE,GAAG;AACpB,EAAE,2BAA2B,EAAE,GAAG;AAClC,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,IAAI,EAAE,GAAG;AACX,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,kBAAkB,EAAE,GAAG;AACzB,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,oBAAoB,EAAE,GAAG;AAC3B,EAAE,mBAAmB,EAAE,GAAG;AAC1B,EAAE,iBAAiB,EAAE,GAAG;AACxB,EAAE,SAAS,EAAE,GAAG;AAChB,EAAE,kBAAkB,EAAE,GAAG;AACzB,EAAE,mBAAmB,EAAE,GAAG;AAC1B,EAAE,MAAM,EAAE,GAAG;AACb,EAAE,gBAAgB,EAAE,GAAG;AACvB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,oBAAoB,EAAE,GAAG;AAC3B,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,2BAA2B,EAAE,GAAG;AAClC,EAAE,0BAA0B,EAAE,GAAG;AACjC,EAAE,mBAAmB,EAAE,GAAG;AAC1B,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,kBAAkB,EAAE,GAAG;AACzB,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,uBAAuB,EAAE,GAAG;AAC9B,EAAE,qBAAqB,EAAE,GAAG;AAC5B,EAAE,mBAAmB,EAAE,GAAG;AAC1B,EAAE,YAAY,EAAE,GAAG;AACnB,EAAE,WAAW,EAAE,GAAG;AAClB,EAAE,6BAA6B,EAAE,GAAG;AACpC,CAAC,CAAC;AACF;AACA,MAAM,CAAC,OAAO,CAACA,gBAAc,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,KAAK;AACzD,EAAEA,gBAAc,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC;AAC9B,CAAC,CAAC,CAAC;AACH;AACA,yBAAeA,gBAAc;;AClD7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,cAAc,CAAC,aAAa,EAAE;AACvC,EAAE,MAAM,OAAO,GAAG,IAAIL,OAAK,CAAC,aAAa,CAAC,CAAC;AAC3C,EAAE,MAAM,QAAQ,GAAG,IAAI,CAACA,OAAK,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAC1D;AACA;AACA,EAAEhB,OAAK,CAAC,MAAM,CAAC,QAAQ,EAAEgB,OAAK,CAAC,SAAS,EAAE,OAAO,EAAE,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC;AACvE;AACA;AACA,EAAEhB,OAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC;AAC5D;AACA;AACA,EAAE,QAAQ,CAAC,MAAM,GAAG,SAAS,MAAM,CAAC,cAAc,EAAE;AACpD,IAAI,OAAO,cAAc,CAACY,aAAW,CAAC,aAAa,EAAE,cAAc,CAAC,CAAC,CAAC;AACtE,GAAG,CAAC;AACJ;AACA,EAAE,OAAO,QAAQ,CAAC;AAClB,CAAC;AACD;AACA;AACA,MAAM,KAAK,GAAG,cAAc,CAACH,UAAQ,CAAC,CAAC;AACvC;AACA;AACA,KAAK,CAAC,KAAK,GAAGO,OAAK,CAAC;AACpB;AACA;AACA,KAAK,CAAC,aAAa,GAAGL,eAAa,CAAC;AACpC,KAAK,CAAC,WAAW,GAAGO,aAAW,CAAC;AAChC,KAAK,CAAC,QAAQ,GAAGR,UAAQ,CAAC;AAC1B,KAAK,CAAC,OAAO,GAAGI,SAAO,CAAC;AACxB,KAAK,CAAC,UAAU,GAAGZ,YAAU,CAAC;AAC9B;AACA;AACA,KAAK,CAAC,UAAU,GAAGH,YAAU,CAAC;AAC9B;AACA;AACA,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,aAAa,CAAC;AACnC;AACA;AACA,KAAK,CAAC,GAAG,GAAG,SAAS,GAAG,CAAC,QAAQ,EAAE;AACnC,EAAE,OAAO,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AAC/B,CAAC,CAAC;AACF;AACA,KAAK,CAAC,MAAM,GAAGoB,QAAM,CAAC;AACtB;AACA;AACA,KAAK,CAAC,YAAY,GAAGC,cAAY,CAAC;AAClC;AACA;AACA,KAAK,CAAC,WAAW,GAAGR,aAAW,CAAC;AAChC;AACA,KAAK,CAAC,YAAY,GAAGJ,cAAY,CAAC;AAClC;AACA,KAAK,CAAC,UAAU,GAAG,KAAK,IAAI,cAAc,CAACR,OAAK,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,IAAI,QAAQ,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC;AAClG;AACA,KAAK,CAAC,UAAU,GAAG,QAAQ,CAAC,UAAU,CAAC;AACvC;AACA,KAAK,CAAC,cAAc,GAAGqB,gBAAc,CAAC;AACtC;AACA,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC;AACtB;AACA;AACA,gBAAe;;ACtFf;AACA;AACA;AACK,MAAC;AACN,EAAE,KAAK;AACP,EAAE,UAAU;AACZ,EAAE,aAAa;AACf,EAAE,QAAQ;AACV,EAAE,WAAW;AACb,EAAE,OAAO;AACT,EAAE,GAAG;AACL,EAAE,MAAM;AACR,EAAE,YAAY;AACd,EAAE,MAAM;AACR,EAAE,UAAU;AACZ,EAAE,YAAY;AACd,EAAE,cAAc;AAChB,EAAE,UAAU;AACZ,EAAE,UAAU;AACZ,EAAE,WAAW;AACb,CAAC,GAAGC;;;;"} \ No newline at end of file diff --git a/node_modules/axios/dist/esm/axios.min.js b/node_modules/axios/dist/esm/axios.min.js new file mode 100644 index 000000000..ed844d0e6 --- /dev/null +++ b/node_modules/axios/dist/esm/axios.min.js @@ -0,0 +1,2 @@ +function e(e,t){return function(){return e.apply(t,arguments)}}const{toString:t}=Object.prototype,{getPrototypeOf:n}=Object,r=(o=Object.create(null),e=>{const n=t.call(e);return o[n]||(o[n]=n.slice(8,-1).toLowerCase())});var o;const s=e=>(e=e.toLowerCase(),t=>r(t)===e),i=e=>t=>typeof t===e,{isArray:a}=Array,c=i("undefined");const u=s("ArrayBuffer");const l=i("string"),f=i("function"),d=i("number"),p=e=>null!==e&&"object"==typeof e,h=e=>{if("object"!==r(e))return!1;const t=n(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},m=s("Date"),y=s("File"),b=s("Blob"),g=s("FileList"),w=s("URLSearchParams"),[E,R,O,S]=["ReadableStream","Request","Response","Headers"].map(s);function T(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let r,o;if("object"!=typeof e&&(e=[e]),a(e))for(r=0,o=e.length;r0;)if(r=n[o],t===r.toLowerCase())return r;return null}const v="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,x=e=>!c(e)&&e!==v;const C=(N="undefined"!=typeof Uint8Array&&n(Uint8Array),e=>N&&e instanceof N);var N;const j=s("HTMLFormElement"),P=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),_=s("RegExp"),L=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};T(n,((n,o)=>{let s;!1!==(s=t(n,o,e))&&(r[o]=s||n)})),Object.defineProperties(e,r)},U="abcdefghijklmnopqrstuvwxyz",F={DIGIT:"0123456789",ALPHA:U,ALPHA_DIGIT:U+U.toUpperCase()+"0123456789"};const B=s("AsyncFunction"),k=(D="function"==typeof setImmediate,q=f(v.postMessage),D?setImmediate:q?(I=`axios@${Math.random()}`,M=[],v.addEventListener("message",(({source:e,data:t})=>{e===v&&t===I&&M.length&&M.shift()()}),!1),e=>{M.push(e),v.postMessage(I,"*")}):e=>setTimeout(e));var D,q,I,M;const z="undefined"!=typeof queueMicrotask?queueMicrotask.bind(v):"undefined"!=typeof process&&process.nextTick||k,H={isArray:a,isArrayBuffer:u,isBuffer:function(e){return null!==e&&!c(e)&&null!==e.constructor&&!c(e.constructor)&&f(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||f(e.append)&&("formdata"===(t=r(e))||"object"===t&&f(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&u(e.buffer),t},isString:l,isNumber:d,isBoolean:e=>!0===e||!1===e,isObject:p,isPlainObject:h,isReadableStream:E,isRequest:R,isResponse:O,isHeaders:S,isUndefined:c,isDate:m,isFile:y,isBlob:b,isRegExp:_,isFunction:f,isStream:e=>p(e)&&f(e.pipe),isURLSearchParams:w,isTypedArray:C,isFileList:g,forEach:T,merge:function e(){const{caseless:t}=x(this)&&this||{},n={},r=(r,o)=>{const s=t&&A(n,o)||o;h(n[s])&&h(r)?n[s]=e(n[s],r):h(r)?n[s]=e({},r):a(r)?n[s]=r.slice():n[s]=r};for(let e=0,t=arguments.length;e(T(n,((n,o)=>{r&&f(n)?t[o]=e(n,r):t[o]=n}),{allOwnKeys:o}),t),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,r,o)=>{let s,i,a;const c={};if(t=t||{},null==e)return t;do{for(s=Object.getOwnPropertyNames(e),i=s.length;i-- >0;)a=s[i],o&&!o(a,e,t)||c[a]||(t[a]=e[a],c[a]=!0);e=!1!==r&&n(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:r,kindOfTest:s,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return-1!==r&&r===n},toArray:e=>{if(!e)return null;if(a(e))return e;let t=e.length;if(!d(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[Symbol.iterator]).call(e);let r;for(;(r=n.next())&&!r.done;){const n=r.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const r=[];for(;null!==(n=e.exec(t));)r.push(n);return r},isHTMLForm:j,hasOwnProperty:P,hasOwnProp:P,reduceDescriptors:L,freezeMethods:e=>{L(e,((t,n)=>{if(f(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const r=e[n];f(r)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))}))},toObjectSet:(e,t)=>{const n={},r=e=>{e.forEach((e=>{n[e]=!0}))};return a(e)?r(e):r(String(e).split(t)),n},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,n){return t.toUpperCase()+n})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:A,global:v,isContextDefined:x,ALPHABET:F,generateString:(e=16,t=F.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n},isSpecCompliantForm:function(e){return!!(e&&f(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:e=>{const t=new Array(10),n=(e,r)=>{if(p(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[r]=e;const o=a(e)?[]:{};return T(e,((e,t)=>{const s=n(e,r+1);!c(s)&&(o[t]=s)})),t[r]=void 0,o}}return e};return n(e,0)},isAsyncFn:B,isThenable:e=>e&&(p(e)||f(e))&&f(e.then)&&f(e.catch),setImmediate:k,asap:z};function J(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o,this.status=o.status?o.status:null)}H.inherits(J,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:H.toJSONObject(this.config),code:this.code,status:this.status}}});const W=J.prototype,K={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{K[e]={value:e}})),Object.defineProperties(J,K),Object.defineProperty(W,"isAxiosError",{value:!0}),J.from=(e,t,n,r,o,s)=>{const i=Object.create(W);return H.toFlatObject(e,i,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),J.call(i,e.message,t,n,r,o),i.cause=e,i.name=e.name,s&&Object.assign(i,s),i};function V(e){return H.isPlainObject(e)||H.isArray(e)}function $(e){return H.endsWith(e,"[]")?e.slice(0,-2):e}function G(e,t,n){return e?e.concat(t).map((function(e,t){return e=$(e),!n&&t?"["+e+"]":e})).join(n?".":""):t}const X=H.toFlatObject(H,{},null,(function(e){return/^is[A-Z]/.test(e)}));function Q(e,t,n){if(!H.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const r=(n=H.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!H.isUndefined(t[e])}))).metaTokens,o=n.visitor||u,s=n.dots,i=n.indexes,a=(n.Blob||"undefined"!=typeof Blob&&Blob)&&H.isSpecCompliantForm(t);if(!H.isFunction(o))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(H.isDate(e))return e.toISOString();if(!a&&H.isBlob(e))throw new J("Blob is not supported. Use a Buffer instead.");return H.isArrayBuffer(e)||H.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function u(e,n,o){let a=e;if(e&&!o&&"object"==typeof e)if(H.endsWith(n,"{}"))n=r?n:n.slice(0,-2),e=JSON.stringify(e);else if(H.isArray(e)&&function(e){return H.isArray(e)&&!e.some(V)}(e)||(H.isFileList(e)||H.endsWith(n,"[]"))&&(a=H.toArray(e)))return n=$(n),a.forEach((function(e,r){!H.isUndefined(e)&&null!==e&&t.append(!0===i?G([n],r,s):null===i?n:n+"[]",c(e))})),!1;return!!V(e)||(t.append(G(o,n,s),c(e)),!1)}const l=[],f=Object.assign(X,{defaultVisitor:u,convertValue:c,isVisitable:V});if(!H.isObject(e))throw new TypeError("data must be an object");return function e(n,r){if(!H.isUndefined(n)){if(-1!==l.indexOf(n))throw Error("Circular reference detected in "+r.join("."));l.push(n),H.forEach(n,(function(n,s){!0===(!(H.isUndefined(n)||null===n)&&o.call(t,n,H.isString(s)?s.trim():s,r,f))&&e(n,r?r.concat(s):[s])})),l.pop()}}(e),t}function Z(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function Y(e,t){this._pairs=[],e&&Q(e,this,t)}const ee=Y.prototype;function te(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ne(e,t,n){if(!t)return e;const r=n&&n.encode||te;H.isFunction(n)&&(n={serialize:n});const o=n&&n.serialize;let s;if(s=o?o(t,n):H.isURLSearchParams(t)?t.toString():new Y(t,n).toString(r),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}ee.append=function(e,t){this._pairs.push([e,t])},ee.toString=function(e){const t=e?function(t){return e.call(this,t,Z)}:Z;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};const re=class{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){H.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},oe={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},se={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Y,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},ie="undefined"!=typeof window&&"undefined"!=typeof document,ae="object"==typeof navigator&&navigator||void 0,ce=ie&&(!ae||["ReactNative","NativeScript","NS"].indexOf(ae.product)<0),ue="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,le=ie&&window.location.href||"http://localhost",fe={...Object.freeze({__proto__:null,hasBrowserEnv:ie,hasStandardBrowserWebWorkerEnv:ue,hasStandardBrowserEnv:ce,navigator:ae,origin:le}),...se};function de(e){function t(e,n,r,o){let s=e[o++];if("__proto__"===s)return!0;const i=Number.isFinite(+s),a=o>=e.length;if(s=!s&&H.isArray(r)?r.length:s,a)return H.hasOwnProp(r,s)?r[s]=[r[s],n]:r[s]=n,!i;r[s]&&H.isObject(r[s])||(r[s]=[]);return t(e,n,r[s],o)&&H.isArray(r[s])&&(r[s]=function(e){const t={},n=Object.keys(e);let r;const o=n.length;let s;for(r=0;r{t(function(e){return H.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),r,n,0)})),n}return null}const pe={transitional:oe,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",r=n.indexOf("application/json")>-1,o=H.isObject(e);o&&H.isHTMLForm(e)&&(e=new FormData(e));if(H.isFormData(e))return r?JSON.stringify(de(e)):e;if(H.isArrayBuffer(e)||H.isBuffer(e)||H.isStream(e)||H.isFile(e)||H.isBlob(e)||H.isReadableStream(e))return e;if(H.isArrayBufferView(e))return e.buffer;if(H.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(o){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Q(e,new fe.classes.URLSearchParams,Object.assign({visitor:function(e,t,n,r){return fe.isNode&&H.isBuffer(e)?(this.append(t,e.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=H.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Q(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||r?(t.setContentType("application/json",!1),function(e,t,n){if(H.isString(e))try{return(t||JSON.parse)(e),H.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||pe.transitional,n=t&&t.forcedJSONParsing,r="json"===this.responseType;if(H.isResponse(e)||H.isReadableStream(e))return e;if(e&&H.isString(e)&&(n&&!this.responseType||r)){const n=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e)}catch(e){if(n){if("SyntaxError"===e.name)throw J.from(e,J.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:fe.classes.FormData,Blob:fe.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};H.forEach(["delete","get","head","post","put","patch"],(e=>{pe.headers[e]={}}));const he=pe,me=H.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),ye=Symbol("internals");function be(e){return e&&String(e).trim().toLowerCase()}function ge(e){return!1===e||null==e?e:H.isArray(e)?e.map(ge):String(e)}function we(e,t,n,r,o){return H.isFunction(r)?r.call(this,t,n):(o&&(t=n),H.isString(t)?H.isString(r)?-1!==t.indexOf(r):H.isRegExp(r)?r.test(t):void 0:void 0)}class Ee{constructor(e){e&&this.set(e)}set(e,t,n){const r=this;function o(e,t,n){const o=be(t);if(!o)throw new Error("header name must be a non-empty string");const s=H.findKey(r,o);(!s||void 0===r[s]||!0===n||void 0===n&&!1!==r[s])&&(r[s||t]=ge(e))}const s=(e,t)=>H.forEach(e,((e,n)=>o(e,n,t)));if(H.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(H.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let n,r,o;return e&&e.split("\n").forEach((function(e){o=e.indexOf(":"),n=e.substring(0,o).trim().toLowerCase(),r=e.substring(o+1).trim(),!n||t[n]&&me[n]||("set-cookie"===n?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)})),t})(e),t);else if(H.isHeaders(e))for(const[t,r]of e.entries())o(r,t,n);else null!=e&&o(t,e,n);return this}get(e,t){if(e=be(e)){const n=H.findKey(this,e);if(n){const e=this[n];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}(e);if(H.isFunction(t))return t.call(this,e,n);if(H.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=be(e)){const n=H.findKey(this,e);return!(!n||void 0===this[n]||t&&!we(0,this[n],n,t))}return!1}delete(e,t){const n=this;let r=!1;function o(e){if(e=be(e)){const o=H.findKey(n,e);!o||t&&!we(0,n[o],o,t)||(delete n[o],r=!0)}}return H.isArray(e)?e.forEach(o):o(e),r}clear(e){const t=Object.keys(this);let n=t.length,r=!1;for(;n--;){const o=t[n];e&&!we(0,this[o],o,e,!0)||(delete this[o],r=!0)}return r}normalize(e){const t=this,n={};return H.forEach(this,((r,o)=>{const s=H.findKey(n,o);if(s)return t[s]=ge(r),void delete t[o];const i=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,n)=>t.toUpperCase()+n))}(o):String(o).trim();i!==o&&delete t[o],t[i]=ge(r),n[i]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return H.forEach(this,((n,r)=>{null!=n&&!1!==n&&(t[r]=e&&H.isArray(n)?n.join(", "):n)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const n=new this(e);return t.forEach((e=>n.set(e))),n}static accessor(e){const t=(this[ye]=this[ye]={accessors:{}}).accessors,n=this.prototype;function r(e){const r=be(e);t[r]||(!function(e,t){const n=H.toCamelCase(" "+t);["get","set","has"].forEach((r=>{Object.defineProperty(e,r+n,{value:function(e,n,o){return this[r].call(this,t,e,n,o)},configurable:!0})}))}(n,e),t[r]=!0)}return H.isArray(e)?e.forEach(r):r(e),this}}Ee.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),H.reduceDescriptors(Ee.prototype,(({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}})),H.freezeMethods(Ee);const Re=Ee;function Oe(e,t){const n=this||he,r=t||n,o=Re.from(r.headers);let s=r.data;return H.forEach(e,(function(e){s=e.call(n,s,o.normalize(),t?t.status:void 0)})),o.normalize(),s}function Se(e){return!(!e||!e.__CANCEL__)}function Te(e,t,n){J.call(this,null==e?"canceled":e,J.ERR_CANCELED,t,n),this.name="CanceledError"}function Ae(e,t,n){const r=n.config.validateStatus;n.status&&r&&!r(n.status)?t(new J("Request failed with status code "+n.status,[J.ERR_BAD_REQUEST,J.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}H.inherits(Te,J,{__CANCEL__:!0});const ve=(e,t,n=3)=>{let r=0;const o=function(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o,s=0,i=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),u=r[i];o||(o=c),n[s]=a,r[s]=c;let l=i,f=0;for(;l!==s;)f+=n[l++],l%=e;if(s=(s+1)%e,s===i&&(i=(i+1)%e),c-o{o=s,n=null,r&&(clearTimeout(r),r=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-o;a>=s?i(e,t):(n=e,r||(r=setTimeout((()=>{r=null,i(n)}),s-a)))},()=>n&&i(n)]}((n=>{const s=n.loaded,i=n.lengthComputable?n.total:void 0,a=s-r,c=o(a);r=s;e({loaded:s,total:i,progress:i?s/i:void 0,bytes:a,rate:c||void 0,estimated:c&&i&&s<=i?(i-s)/c:void 0,event:n,lengthComputable:null!=i,[t?"download":"upload"]:!0})}),n)},xe=(e,t)=>{const n=null!=e;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Ce=e=>(...t)=>H.asap((()=>e(...t))),Ne=fe.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,fe.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(fe.origin),fe.navigator&&/(msie|trident)/i.test(fe.navigator.userAgent)):()=>!0,je=fe.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];H.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),H.isString(r)&&i.push("path="+r),H.isString(o)&&i.push("domain="+o),!0===s&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Pe(e,t){return e&&!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const _e=e=>e instanceof Re?{...e}:e;function Le(e,t){t=t||{};const n={};function r(e,t,n,r){return H.isPlainObject(e)&&H.isPlainObject(t)?H.merge.call({caseless:r},e,t):H.isPlainObject(t)?H.merge({},t):H.isArray(t)?t.slice():t}function o(e,t,n,o){return H.isUndefined(t)?H.isUndefined(e)?void 0:r(void 0,e,0,o):r(e,t,0,o)}function s(e,t){if(!H.isUndefined(t))return r(void 0,t)}function i(e,t){return H.isUndefined(t)?H.isUndefined(e)?void 0:r(void 0,e):r(void 0,t)}function a(n,o,s){return s in t?r(n,o):s in e?r(void 0,n):void 0}const c={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(e,t,n)=>o(_e(e),_e(t),0,!0)};return H.forEach(Object.keys(Object.assign({},e,t)),(function(r){const s=c[r]||o,i=s(e[r],t[r],r);H.isUndefined(i)&&s!==a||(n[r]=i)})),n}const Ue=e=>{const t=Le({},e);let n,{data:r,withXSRFToken:o,xsrfHeaderName:s,xsrfCookieName:i,headers:a,auth:c}=t;if(t.headers=a=Re.from(a),t.url=ne(Pe(t.baseURL,t.url),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),H.isFormData(r))if(fe.hasStandardBrowserEnv||fe.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(n=a.getContentType())){const[e,...t]=n?n.split(";").map((e=>e.trim())).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(fe.hasStandardBrowserEnv&&(o&&H.isFunction(o)&&(o=o(t)),o||!1!==o&&Ne(t.url))){const e=s&&i&&je.read(i);e&&a.set(s,e)}return t},Fe="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,n){const r=Ue(e);let o=r.data;const s=Re.from(r.headers).normalize();let i,a,c,u,l,{responseType:f,onUploadProgress:d,onDownloadProgress:p}=r;function h(){u&&u(),l&&l(),r.cancelToken&&r.cancelToken.unsubscribe(i),r.signal&&r.signal.removeEventListener("abort",i)}let m=new XMLHttpRequest;function y(){if(!m)return;const r=Re.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());Ae((function(e){t(e),h()}),(function(e){n(e),h()}),{data:f&&"text"!==f&&"json"!==f?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:r,config:e,request:m}),m=null}m.open(r.method.toUpperCase(),r.url,!0),m.timeout=r.timeout,"onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(y)},m.onabort=function(){m&&(n(new J("Request aborted",J.ECONNABORTED,e,m)),m=null)},m.onerror=function(){n(new J("Network Error",J.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=r.timeout?"timeout of "+r.timeout+"ms exceeded":"timeout exceeded";const o=r.transitional||oe;r.timeoutErrorMessage&&(t=r.timeoutErrorMessage),n(new J(t,o.clarifyTimeoutError?J.ETIMEDOUT:J.ECONNABORTED,e,m)),m=null},void 0===o&&s.setContentType(null),"setRequestHeader"in m&&H.forEach(s.toJSON(),(function(e,t){m.setRequestHeader(t,e)})),H.isUndefined(r.withCredentials)||(m.withCredentials=!!r.withCredentials),f&&"json"!==f&&(m.responseType=r.responseType),p&&([c,l]=ve(p,!0),m.addEventListener("progress",c)),d&&m.upload&&([a,u]=ve(d),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",u)),(r.cancelToken||r.signal)&&(i=t=>{m&&(n(!t||t.type?new Te(null,e,m):t),m.abort(),m=null)},r.cancelToken&&r.cancelToken.subscribe(i),r.signal&&(r.signal.aborted?i():r.signal.addEventListener("abort",i)));const b=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(r.url);b&&-1===fe.protocols.indexOf(b)?n(new J("Unsupported protocol "+b+":",J.ERR_BAD_REQUEST,e)):m.send(o||null)}))},Be=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n,r=new AbortController;const o=function(e){if(!n){n=!0,i();const t=e instanceof Error?e:this.reason;r.abort(t instanceof J?t:new Te(t instanceof Error?t.message:t))}};let s=t&&setTimeout((()=>{s=null,o(new J(`timeout ${t} of ms exceeded`,J.ETIMEDOUT))}),t);const i=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(o):e.removeEventListener("abort",o)})),e=null)};e.forEach((e=>e.addEventListener("abort",o)));const{signal:a}=r;return a.unsubscribe=()=>H.asap(i),a}},ke=function*(e,t){let n=e.byteLength;if(!t||n{const o=async function*(e,t){for await(const n of De(e))yield*ke(n,t)}(e,t);let s,i=0,a=e=>{s||(s=!0,r&&r(e))};return new ReadableStream({async pull(e){try{const{done:t,value:r}=await o.next();if(t)return a(),void e.close();let s=r.byteLength;if(n){let e=i+=s;n(e)}e.enqueue(new Uint8Array(r))}catch(e){throw a(e),e}},cancel:e=>(a(e),o.return())},{highWaterMark:2})},Ie="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Me=Ie&&"function"==typeof ReadableStream,ze=Ie&&("function"==typeof TextEncoder?(He=new TextEncoder,e=>He.encode(e)):async e=>new Uint8Array(await new Response(e).arrayBuffer()));var He;const Je=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},We=Me&&Je((()=>{let e=!1;const t=new Request(fe.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),Ke=Me&&Je((()=>H.isReadableStream(new Response("").body))),Ve={stream:Ke&&(e=>e.body)};var $e;Ie&&($e=new Response,["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!Ve[e]&&(Ve[e]=H.isFunction($e[e])?t=>t[e]():(t,n)=>{throw new J(`Response type '${e}' is not supported`,J.ERR_NOT_SUPPORT,n)})})));const Ge=async(e,t)=>{const n=H.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(H.isBlob(e))return e.size;if(H.isSpecCompliantForm(e)){const t=new Request(fe.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return H.isArrayBufferView(e)||H.isArrayBuffer(e)?e.byteLength:(H.isURLSearchParams(e)&&(e+=""),H.isString(e)?(await ze(e)).byteLength:void 0)})(t):n},Xe={http:null,xhr:Fe,fetch:Ie&&(async e=>{let{url:t,method:n,data:r,signal:o,cancelToken:s,timeout:i,onDownloadProgress:a,onUploadProgress:c,responseType:u,headers:l,withCredentials:f="same-origin",fetchOptions:d}=Ue(e);u=u?(u+"").toLowerCase():"text";let p,h=Be([o,s&&s.toAbortSignal()],i);const m=h&&h.unsubscribe&&(()=>{h.unsubscribe()});let y;try{if(c&&We&&"get"!==n&&"head"!==n&&0!==(y=await Ge(l,r))){let e,n=new Request(t,{method:"POST",body:r,duplex:"half"});if(H.isFormData(r)&&(e=n.headers.get("content-type"))&&l.setContentType(e),n.body){const[e,t]=xe(y,ve(Ce(c)));r=qe(n.body,65536,e,t)}}H.isString(f)||(f=f?"include":"omit");const o="credentials"in Request.prototype;p=new Request(t,{...d,signal:h,method:n.toUpperCase(),headers:l.normalize().toJSON(),body:r,duplex:"half",credentials:o?f:void 0});let s=await fetch(p);const i=Ke&&("stream"===u||"response"===u);if(Ke&&(a||i&&m)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=s[t]}));const t=H.toFiniteNumber(s.headers.get("content-length")),[n,r]=a&&xe(t,ve(Ce(a),!0))||[];s=new Response(qe(s.body,65536,n,(()=>{r&&r(),m&&m()})),e)}u=u||"text";let b=await Ve[H.findKey(Ve,u)||"text"](s,e);return!i&&m&&m(),await new Promise(((t,n)=>{Ae(t,n,{data:b,headers:Re.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:p})}))}catch(t){if(m&&m(),t&&"TypeError"===t.name&&/fetch/i.test(t.message))throw Object.assign(new J("Network Error",J.ERR_NETWORK,e,p),{cause:t.cause||t});throw J.from(t,t&&t.code,e,p)}})};H.forEach(Xe,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const Qe=e=>`- ${e}`,Ze=e=>H.isFunction(e)||null===e||!1===e,Ye=e=>{e=H.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let s=0;s`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new J("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Qe).join("\n"):" "+Qe(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return r};function et(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Te(null,e)}function tt(e){et(e),e.headers=Re.from(e.headers),e.data=Oe.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Ye(e.adapter||he.adapter)(e).then((function(t){return et(e),t.data=Oe.call(e,e.transformResponse,t),t.headers=Re.from(t.headers),t}),(function(t){return Se(t)||(et(e),t&&t.response&&(t.response.data=Oe.call(e,e.transformResponse,t.response),t.response.headers=Re.from(t.response.headers))),Promise.reject(t)}))}const nt={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{nt[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}}));const rt={};nt.transitional=function(e,t,n){function r(e,t){return"[Axios v1.7.9] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,o,s)=>{if(!1===e)throw new J(r(o," has been removed"+(t?" in "+t:"")),J.ERR_DEPRECATED);return t&&!rt[o]&&(rt[o]=!0,console.warn(r(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,o,s)}},nt.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const ot={assertOptions:function(e,t,n){if("object"!=typeof e)throw new J("options must be an object",J.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],i=t[s];if(i){const t=e[s],n=void 0===t||i(t,s,e);if(!0!==n)throw new J("option "+s+" must be "+n,J.ERR_BAD_OPTION_VALUE)}else if(!0!==n)throw new J("Unknown option "+s,J.ERR_BAD_OPTION)}},validators:nt},st=ot.validators;class it{constructor(e){this.defaults=e,this.interceptors={request:new re,response:new re}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const n=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?n&&!String(e.stack).endsWith(n.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+n):e.stack=n}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Le(this.defaults,t);const{transitional:n,paramsSerializer:r,headers:o}=t;void 0!==n&&ot.assertOptions(n,{silentJSONParsing:st.transitional(st.boolean),forcedJSONParsing:st.transitional(st.boolean),clarifyTimeoutError:st.transitional(st.boolean)},!1),null!=r&&(H.isFunction(r)?t.paramsSerializer={serialize:r}:ot.assertOptions(r,{encode:st.function,serialize:st.function},!0)),ot.assertOptions(t,{baseUrl:st.spelling("baseURL"),withXsrfToken:st.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=o&&H.merge(o.common,o[t.method]);o&&H.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete o[e]})),t.headers=Re.concat(s,o);const i=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,i.unshift(e.fulfilled,e.rejected))}));const c=[];let u;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let l,f=0;if(!a){const e=[tt.bind(this),void 0];for(e.unshift.apply(e,i),e.push.apply(e,c),l=e.length,u=Promise.resolve(t);f{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null})),this.promise.then=e=>{let t;const r=new Promise((e=>{n.subscribe(e),t=e})).then(e);return r.cancel=function(){n.unsubscribe(t)},r},e((function(e,r,o){n.reason||(n.reason=new Te(e,r,o),t(n.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new ct((function(t){e=t})),cancel:e}}}const ut=ct;const lt={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(lt).forEach((([e,t])=>{lt[t]=e}));const ft=lt;const dt=function t(n){const r=new at(n),o=e(at.prototype.request,r);return H.extend(o,at.prototype,r,{allOwnKeys:!0}),H.extend(o,r,null,{allOwnKeys:!0}),o.create=function(e){return t(Le(n,e))},o}(he);dt.Axios=at,dt.CanceledError=Te,dt.CancelToken=ut,dt.isCancel=Se,dt.VERSION="1.7.9",dt.toFormData=Q,dt.AxiosError=J,dt.Cancel=dt.CanceledError,dt.all=function(e){return Promise.all(e)},dt.spread=function(e){return function(t){return e.apply(null,t)}},dt.isAxiosError=function(e){return H.isObject(e)&&!0===e.isAxiosError},dt.mergeConfig=Le,dt.AxiosHeaders=Re,dt.formToJSON=e=>de(H.isHTMLForm(e)?new FormData(e):e),dt.getAdapter=Ye,dt.HttpStatusCode=ft,dt.default=dt;const pt=dt,{Axios:ht,AxiosError:mt,CanceledError:yt,isCancel:bt,CancelToken:gt,VERSION:wt,all:Et,Cancel:Rt,isAxiosError:Ot,spread:St,toFormData:Tt,AxiosHeaders:At,HttpStatusCode:vt,formToJSON:xt,getAdapter:Ct,mergeConfig:Nt}=pt;export{ht as Axios,mt as AxiosError,At as AxiosHeaders,Rt as Cancel,gt as CancelToken,yt as CanceledError,vt as HttpStatusCode,wt as VERSION,Et as all,pt as default,xt as formToJSON,Ct as getAdapter,Ot as isAxiosError,bt as isCancel,Nt as mergeConfig,St as spread,Tt as toFormData}; +//# sourceMappingURL=axios.min.js.map diff --git a/node_modules/axios/dist/esm/axios.min.js.map b/node_modules/axios/dist/esm/axios.min.js.map new file mode 100644 index 000000000..a3d96a5bd --- /dev/null +++ b/node_modules/axios/dist/esm/axios.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"axios.min.js","sources":["../../lib/helpers/bind.js","../../lib/utils.js","../../lib/core/AxiosError.js","../../lib/helpers/toFormData.js","../../lib/helpers/AxiosURLSearchParams.js","../../lib/helpers/buildURL.js","../../lib/core/InterceptorManager.js","../../lib/defaults/transitional.js","../../lib/platform/browser/index.js","../../lib/platform/browser/classes/URLSearchParams.js","../../lib/platform/browser/classes/FormData.js","../../lib/platform/browser/classes/Blob.js","../../lib/platform/common/utils.js","../../lib/platform/index.js","../../lib/helpers/formDataToJSON.js","../../lib/defaults/index.js","../../lib/helpers/toURLEncodedForm.js","../../lib/helpers/parseHeaders.js","../../lib/core/AxiosHeaders.js","../../lib/core/transformData.js","../../lib/cancel/isCancel.js","../../lib/cancel/CanceledError.js","../../lib/core/settle.js","../../lib/helpers/progressEventReducer.js","../../lib/helpers/speedometer.js","../../lib/helpers/throttle.js","../../lib/helpers/isURLSameOrigin.js","../../lib/helpers/cookies.js","../../lib/core/buildFullPath.js","../../lib/helpers/isAbsoluteURL.js","../../lib/helpers/combineURLs.js","../../lib/core/mergeConfig.js","../../lib/helpers/resolveConfig.js","../../lib/adapters/xhr.js","../../lib/helpers/parseProtocol.js","../../lib/helpers/composeSignals.js","../../lib/helpers/trackStream.js","../../lib/adapters/fetch.js","../../lib/adapters/adapters.js","../../lib/helpers/null.js","../../lib/core/dispatchRequest.js","../../lib/env/data.js","../../lib/helpers/validator.js","../../lib/core/Axios.js","../../lib/cancel/CancelToken.js","../../lib/helpers/HttpStatusCode.js","../../lib/axios.js","../../lib/helpers/spread.js","../../lib/helpers/isAxiosError.js","../../index.js"],"sourcesContent":["'use strict';\n\nexport default function bind(fn, thisArg) {\n return function wrap() {\n return fn.apply(thisArg, arguments);\n };\n}\n","'use strict';\n\nimport bind from './helpers/bind.js';\n\n// utils is a library of generic helper functions non-specific to axios\n\nconst {toString} = Object.prototype;\nconst {getPrototypeOf} = Object;\n\nconst kindOf = (cache => thing => {\n const str = toString.call(thing);\n return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());\n})(Object.create(null));\n\nconst kindOfTest = (type) => {\n type = type.toLowerCase();\n return (thing) => kindOf(thing) === type\n}\n\nconst typeOfTest = type => thing => typeof thing === type;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n *\n * @returns {boolean} True if value is an Array, otherwise false\n */\nconst {isArray} = Array;\n\n/**\n * Determine if a value is undefined\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nconst isUndefined = typeOfTest('undefined');\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nconst isArrayBuffer = kindOfTest('ArrayBuffer');\n\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n let result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a String, otherwise false\n */\nconst isString = typeOfTest('string');\n\n/**\n * Determine if a value is a Function\n *\n * @param {*} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nconst isFunction = typeOfTest('function');\n\n/**\n * Determine if a value is a Number\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Number, otherwise false\n */\nconst isNumber = typeOfTest('number');\n\n/**\n * Determine if a value is an Object\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an Object, otherwise false\n */\nconst isObject = (thing) => thing !== null && typeof thing === 'object';\n\n/**\n * Determine if a value is a Boolean\n *\n * @param {*} thing The value to test\n * @returns {boolean} True if value is a Boolean, otherwise false\n */\nconst isBoolean = thing => thing === true || thing === false;\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a plain Object, otherwise false\n */\nconst isPlainObject = (val) => {\n if (kindOf(val) !== 'object') {\n return false;\n }\n\n const prototype = getPrototypeOf(val);\n return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Date, otherwise false\n */\nconst isDate = kindOfTest('Date');\n\n/**\n * Determine if a value is a File\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFile = kindOfTest('File');\n\n/**\n * Determine if a value is a Blob\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nconst isBlob = kindOfTest('Blob');\n\n/**\n * Determine if a value is a FileList\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFileList = kindOfTest('FileList');\n\n/**\n * Determine if a value is a Stream\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nconst isStream = (val) => isObject(val) && isFunction(val.pipe);\n\n/**\n * Determine if a value is a FormData\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nconst isFormData = (thing) => {\n let kind;\n return thing && (\n (typeof FormData === 'function' && thing instanceof FormData) || (\n isFunction(thing.append) && (\n (kind = kindOf(thing)) === 'formdata' ||\n // detect form-data instance\n (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')\n )\n )\n )\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nconst isURLSearchParams = kindOfTest('URLSearchParams');\n\nconst [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n *\n * @returns {String} The String freed of excess whitespace\n */\nconst trim = (str) => str.trim ?\n str.trim() : str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '');\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n *\n * @param {Boolean} [allOwnKeys = false]\n * @returns {any}\n */\nfunction forEach(obj, fn, {allOwnKeys = false} = {}) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n let i;\n let l;\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);\n const len = keys.length;\n let key;\n\n for (i = 0; i < len; i++) {\n key = keys[i];\n fn.call(null, obj[key], key, obj);\n }\n }\n}\n\nfunction findKey(obj, key) {\n key = key.toLowerCase();\n const keys = Object.keys(obj);\n let i = keys.length;\n let _key;\n while (i-- > 0) {\n _key = keys[i];\n if (key === _key.toLowerCase()) {\n return _key;\n }\n }\n return null;\n}\n\nconst _global = (() => {\n /*eslint no-undef:0*/\n if (typeof globalThis !== \"undefined\") return globalThis;\n return typeof self !== \"undefined\" ? self : (typeof window !== 'undefined' ? window : global)\n})();\n\nconst isContextDefined = (context) => !isUndefined(context) && context !== _global;\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n *\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n const {caseless} = isContextDefined(this) && this || {};\n const result = {};\n const assignValue = (val, key) => {\n const targetKey = caseless && findKey(result, key) || key;\n if (isPlainObject(result[targetKey]) && isPlainObject(val)) {\n result[targetKey] = merge(result[targetKey], val);\n } else if (isPlainObject(val)) {\n result[targetKey] = merge({}, val);\n } else if (isArray(val)) {\n result[targetKey] = val.slice();\n } else {\n result[targetKey] = val;\n }\n }\n\n for (let i = 0, l = arguments.length; i < l; i++) {\n arguments[i] && forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n *\n * @param {Boolean} [allOwnKeys]\n * @returns {Object} The resulting value of object a\n */\nconst extend = (a, b, thisArg, {allOwnKeys}= {}) => {\n forEach(b, (val, key) => {\n if (thisArg && isFunction(val)) {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n }, {allOwnKeys});\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n *\n * @returns {string} content value without BOM\n */\nconst stripBOM = (content) => {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\n/**\n * Inherit the prototype methods from one constructor into another\n * @param {function} constructor\n * @param {function} superConstructor\n * @param {object} [props]\n * @param {object} [descriptors]\n *\n * @returns {void}\n */\nconst inherits = (constructor, superConstructor, props, descriptors) => {\n constructor.prototype = Object.create(superConstructor.prototype, descriptors);\n constructor.prototype.constructor = constructor;\n Object.defineProperty(constructor, 'super', {\n value: superConstructor.prototype\n });\n props && Object.assign(constructor.prototype, props);\n}\n\n/**\n * Resolve object with deep prototype chain to a flat object\n * @param {Object} sourceObj source object\n * @param {Object} [destObj]\n * @param {Function|Boolean} [filter]\n * @param {Function} [propFilter]\n *\n * @returns {Object}\n */\nconst toFlatObject = (sourceObj, destObj, filter, propFilter) => {\n let props;\n let i;\n let prop;\n const merged = {};\n\n destObj = destObj || {};\n // eslint-disable-next-line no-eq-null,eqeqeq\n if (sourceObj == null) return destObj;\n\n do {\n props = Object.getOwnPropertyNames(sourceObj);\n i = props.length;\n while (i-- > 0) {\n prop = props[i];\n if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {\n destObj[prop] = sourceObj[prop];\n merged[prop] = true;\n }\n }\n sourceObj = filter !== false && getPrototypeOf(sourceObj);\n } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);\n\n return destObj;\n}\n\n/**\n * Determines whether a string ends with the characters of a specified string\n *\n * @param {String} str\n * @param {String} searchString\n * @param {Number} [position= 0]\n *\n * @returns {boolean}\n */\nconst endsWith = (str, searchString, position) => {\n str = String(str);\n if (position === undefined || position > str.length) {\n position = str.length;\n }\n position -= searchString.length;\n const lastIndex = str.indexOf(searchString, position);\n return lastIndex !== -1 && lastIndex === position;\n}\n\n\n/**\n * Returns new array from array like object or null if failed\n *\n * @param {*} [thing]\n *\n * @returns {?Array}\n */\nconst toArray = (thing) => {\n if (!thing) return null;\n if (isArray(thing)) return thing;\n let i = thing.length;\n if (!isNumber(i)) return null;\n const arr = new Array(i);\n while (i-- > 0) {\n arr[i] = thing[i];\n }\n return arr;\n}\n\n/**\n * Checking if the Uint8Array exists and if it does, it returns a function that checks if the\n * thing passed in is an instance of Uint8Array\n *\n * @param {TypedArray}\n *\n * @returns {Array}\n */\n// eslint-disable-next-line func-names\nconst isTypedArray = (TypedArray => {\n // eslint-disable-next-line func-names\n return thing => {\n return TypedArray && thing instanceof TypedArray;\n };\n})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));\n\n/**\n * For each entry in the object, call the function with the key and value.\n *\n * @param {Object} obj - The object to iterate over.\n * @param {Function} fn - The function to call for each entry.\n *\n * @returns {void}\n */\nconst forEachEntry = (obj, fn) => {\n const generator = obj && obj[Symbol.iterator];\n\n const iterator = generator.call(obj);\n\n let result;\n\n while ((result = iterator.next()) && !result.done) {\n const pair = result.value;\n fn.call(obj, pair[0], pair[1]);\n }\n}\n\n/**\n * It takes a regular expression and a string, and returns an array of all the matches\n *\n * @param {string} regExp - The regular expression to match against.\n * @param {string} str - The string to search.\n *\n * @returns {Array}\n */\nconst matchAll = (regExp, str) => {\n let matches;\n const arr = [];\n\n while ((matches = regExp.exec(str)) !== null) {\n arr.push(matches);\n }\n\n return arr;\n}\n\n/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */\nconst isHTMLForm = kindOfTest('HTMLFormElement');\n\nconst toCamelCase = str => {\n return str.toLowerCase().replace(/[-_\\s]([a-z\\d])(\\w*)/g,\n function replacer(m, p1, p2) {\n return p1.toUpperCase() + p2;\n }\n );\n};\n\n/* Creating a function that will check if an object has a property. */\nconst hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);\n\n/**\n * Determine if a value is a RegExp object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a RegExp object, otherwise false\n */\nconst isRegExp = kindOfTest('RegExp');\n\nconst reduceDescriptors = (obj, reducer) => {\n const descriptors = Object.getOwnPropertyDescriptors(obj);\n const reducedDescriptors = {};\n\n forEach(descriptors, (descriptor, name) => {\n let ret;\n if ((ret = reducer(descriptor, name, obj)) !== false) {\n reducedDescriptors[name] = ret || descriptor;\n }\n });\n\n Object.defineProperties(obj, reducedDescriptors);\n}\n\n/**\n * Makes all methods read-only\n * @param {Object} obj\n */\n\nconst freezeMethods = (obj) => {\n reduceDescriptors(obj, (descriptor, name) => {\n // skip restricted props in strict mode\n if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {\n return false;\n }\n\n const value = obj[name];\n\n if (!isFunction(value)) return;\n\n descriptor.enumerable = false;\n\n if ('writable' in descriptor) {\n descriptor.writable = false;\n return;\n }\n\n if (!descriptor.set) {\n descriptor.set = () => {\n throw Error('Can not rewrite read-only method \\'' + name + '\\'');\n };\n }\n });\n}\n\nconst toObjectSet = (arrayOrString, delimiter) => {\n const obj = {};\n\n const define = (arr) => {\n arr.forEach(value => {\n obj[value] = true;\n });\n }\n\n isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));\n\n return obj;\n}\n\nconst noop = () => {}\n\nconst toFiniteNumber = (value, defaultValue) => {\n return value != null && Number.isFinite(value = +value) ? value : defaultValue;\n}\n\nconst ALPHA = 'abcdefghijklmnopqrstuvwxyz'\n\nconst DIGIT = '0123456789';\n\nconst ALPHABET = {\n DIGIT,\n ALPHA,\n ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT\n}\n\nconst generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {\n let str = '';\n const {length} = alphabet;\n while (size--) {\n str += alphabet[Math.random() * length|0]\n }\n\n return str;\n}\n\n/**\n * If the thing is a FormData object, return true, otherwise return false.\n *\n * @param {unknown} thing - The thing to check.\n *\n * @returns {boolean}\n */\nfunction isSpecCompliantForm(thing) {\n return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);\n}\n\nconst toJSONObject = (obj) => {\n const stack = new Array(10);\n\n const visit = (source, i) => {\n\n if (isObject(source)) {\n if (stack.indexOf(source) >= 0) {\n return;\n }\n\n if(!('toJSON' in source)) {\n stack[i] = source;\n const target = isArray(source) ? [] : {};\n\n forEach(source, (value, key) => {\n const reducedValue = visit(value, i + 1);\n !isUndefined(reducedValue) && (target[key] = reducedValue);\n });\n\n stack[i] = undefined;\n\n return target;\n }\n }\n\n return source;\n }\n\n return visit(obj, 0);\n}\n\nconst isAsyncFn = kindOfTest('AsyncFunction');\n\nconst isThenable = (thing) =>\n thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);\n\n// original code\n// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34\n\nconst _setImmediate = ((setImmediateSupported, postMessageSupported) => {\n if (setImmediateSupported) {\n return setImmediate;\n }\n\n return postMessageSupported ? ((token, callbacks) => {\n _global.addEventListener(\"message\", ({source, data}) => {\n if (source === _global && data === token) {\n callbacks.length && callbacks.shift()();\n }\n }, false);\n\n return (cb) => {\n callbacks.push(cb);\n _global.postMessage(token, \"*\");\n }\n })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);\n})(\n typeof setImmediate === 'function',\n isFunction(_global.postMessage)\n);\n\nconst asap = typeof queueMicrotask !== 'undefined' ?\n queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);\n\n// *********************\n\nexport default {\n isArray,\n isArrayBuffer,\n isBuffer,\n isFormData,\n isArrayBufferView,\n isString,\n isNumber,\n isBoolean,\n isObject,\n isPlainObject,\n isReadableStream,\n isRequest,\n isResponse,\n isHeaders,\n isUndefined,\n isDate,\n isFile,\n isBlob,\n isRegExp,\n isFunction,\n isStream,\n isURLSearchParams,\n isTypedArray,\n isFileList,\n forEach,\n merge,\n extend,\n trim,\n stripBOM,\n inherits,\n toFlatObject,\n kindOf,\n kindOfTest,\n endsWith,\n toArray,\n forEachEntry,\n matchAll,\n isHTMLForm,\n hasOwnProperty,\n hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection\n reduceDescriptors,\n freezeMethods,\n toObjectSet,\n toCamelCase,\n noop,\n toFiniteNumber,\n findKey,\n global: _global,\n isContextDefined,\n ALPHABET,\n generateString,\n isSpecCompliantForm,\n toJSONObject,\n isAsyncFn,\n isThenable,\n setImmediate: _setImmediate,\n asap\n};\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [config] The config.\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n *\n * @returns {Error} The created error.\n */\nfunction AxiosError(message, code, config, request, response) {\n Error.call(this);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error()).stack;\n }\n\n this.message = message;\n this.name = 'AxiosError';\n code && (this.code = code);\n config && (this.config = config);\n request && (this.request = request);\n if (response) {\n this.response = response;\n this.status = response.status ? response.status : null;\n }\n}\n\nutils.inherits(AxiosError, Error, {\n toJSON: function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: utils.toJSONObject(this.config),\n code: this.code,\n status: this.status\n };\n }\n});\n\nconst prototype = AxiosError.prototype;\nconst descriptors = {};\n\n[\n 'ERR_BAD_OPTION_VALUE',\n 'ERR_BAD_OPTION',\n 'ECONNABORTED',\n 'ETIMEDOUT',\n 'ERR_NETWORK',\n 'ERR_FR_TOO_MANY_REDIRECTS',\n 'ERR_DEPRECATED',\n 'ERR_BAD_RESPONSE',\n 'ERR_BAD_REQUEST',\n 'ERR_CANCELED',\n 'ERR_NOT_SUPPORT',\n 'ERR_INVALID_URL'\n// eslint-disable-next-line func-names\n].forEach(code => {\n descriptors[code] = {value: code};\n});\n\nObject.defineProperties(AxiosError, descriptors);\nObject.defineProperty(prototype, 'isAxiosError', {value: true});\n\n// eslint-disable-next-line func-names\nAxiosError.from = (error, code, config, request, response, customProps) => {\n const axiosError = Object.create(prototype);\n\n utils.toFlatObject(error, axiosError, function filter(obj) {\n return obj !== Error.prototype;\n }, prop => {\n return prop !== 'isAxiosError';\n });\n\n AxiosError.call(axiosError, error.message, code, config, request, response);\n\n axiosError.cause = error;\n\n axiosError.name = error.name;\n\n customProps && Object.assign(axiosError, customProps);\n\n return axiosError;\n};\n\nexport default AxiosError;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\n// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored\nimport PlatformFormData from '../platform/node/classes/FormData.js';\n\n/**\n * Determines if the given thing is a array or js object.\n *\n * @param {string} thing - The object or array to be visited.\n *\n * @returns {boolean}\n */\nfunction isVisitable(thing) {\n return utils.isPlainObject(thing) || utils.isArray(thing);\n}\n\n/**\n * It removes the brackets from the end of a string\n *\n * @param {string} key - The key of the parameter.\n *\n * @returns {string} the key without the brackets.\n */\nfunction removeBrackets(key) {\n return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;\n}\n\n/**\n * It takes a path, a key, and a boolean, and returns a string\n *\n * @param {string} path - The path to the current key.\n * @param {string} key - The key of the current object being iterated over.\n * @param {string} dots - If true, the key will be rendered with dots instead of brackets.\n *\n * @returns {string} The path to the current key.\n */\nfunction renderKey(path, key, dots) {\n if (!path) return key;\n return path.concat(key).map(function each(token, i) {\n // eslint-disable-next-line no-param-reassign\n token = removeBrackets(token);\n return !dots && i ? '[' + token + ']' : token;\n }).join(dots ? '.' : '');\n}\n\n/**\n * If the array is an array and none of its elements are visitable, then it's a flat array.\n *\n * @param {Array} arr - The array to check\n *\n * @returns {boolean}\n */\nfunction isFlatArray(arr) {\n return utils.isArray(arr) && !arr.some(isVisitable);\n}\n\nconst predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {\n return /^is[A-Z]/.test(prop);\n});\n\n/**\n * Convert a data object to FormData\n *\n * @param {Object} obj\n * @param {?Object} [formData]\n * @param {?Object} [options]\n * @param {Function} [options.visitor]\n * @param {Boolean} [options.metaTokens = true]\n * @param {Boolean} [options.dots = false]\n * @param {?Boolean} [options.indexes = false]\n *\n * @returns {Object}\n **/\n\n/**\n * It converts an object into a FormData object\n *\n * @param {Object} obj - The object to convert to form data.\n * @param {string} formData - The FormData object to append to.\n * @param {Object} options\n *\n * @returns\n */\nfunction toFormData(obj, formData, options) {\n if (!utils.isObject(obj)) {\n throw new TypeError('target must be an object');\n }\n\n // eslint-disable-next-line no-param-reassign\n formData = formData || new (PlatformFormData || FormData)();\n\n // eslint-disable-next-line no-param-reassign\n options = utils.toFlatObject(options, {\n metaTokens: true,\n dots: false,\n indexes: false\n }, false, function defined(option, source) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n return !utils.isUndefined(source[option]);\n });\n\n const metaTokens = options.metaTokens;\n // eslint-disable-next-line no-use-before-define\n const visitor = options.visitor || defaultVisitor;\n const dots = options.dots;\n const indexes = options.indexes;\n const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;\n const useBlob = _Blob && utils.isSpecCompliantForm(formData);\n\n if (!utils.isFunction(visitor)) {\n throw new TypeError('visitor must be a function');\n }\n\n function convertValue(value) {\n if (value === null) return '';\n\n if (utils.isDate(value)) {\n return value.toISOString();\n }\n\n if (!useBlob && utils.isBlob(value)) {\n throw new AxiosError('Blob is not supported. Use a Buffer instead.');\n }\n\n if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {\n return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);\n }\n\n return value;\n }\n\n /**\n * Default visitor.\n *\n * @param {*} value\n * @param {String|Number} key\n * @param {Array} path\n * @this {FormData}\n *\n * @returns {boolean} return true to visit the each prop of the value recursively\n */\n function defaultVisitor(value, key, path) {\n let arr = value;\n\n if (value && !path && typeof value === 'object') {\n if (utils.endsWith(key, '{}')) {\n // eslint-disable-next-line no-param-reassign\n key = metaTokens ? key : key.slice(0, -2);\n // eslint-disable-next-line no-param-reassign\n value = JSON.stringify(value);\n } else if (\n (utils.isArray(value) && isFlatArray(value)) ||\n ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))\n )) {\n // eslint-disable-next-line no-param-reassign\n key = removeBrackets(key);\n\n arr.forEach(function each(el, index) {\n !(utils.isUndefined(el) || el === null) && formData.append(\n // eslint-disable-next-line no-nested-ternary\n indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),\n convertValue(el)\n );\n });\n return false;\n }\n }\n\n if (isVisitable(value)) {\n return true;\n }\n\n formData.append(renderKey(path, key, dots), convertValue(value));\n\n return false;\n }\n\n const stack = [];\n\n const exposedHelpers = Object.assign(predicates, {\n defaultVisitor,\n convertValue,\n isVisitable\n });\n\n function build(value, path) {\n if (utils.isUndefined(value)) return;\n\n if (stack.indexOf(value) !== -1) {\n throw Error('Circular reference detected in ' + path.join('.'));\n }\n\n stack.push(value);\n\n utils.forEach(value, function each(el, key) {\n const result = !(utils.isUndefined(el) || el === null) && visitor.call(\n formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers\n );\n\n if (result === true) {\n build(el, path ? path.concat(key) : [key]);\n }\n });\n\n stack.pop();\n }\n\n if (!utils.isObject(obj)) {\n throw new TypeError('data must be an object');\n }\n\n build(obj);\n\n return formData;\n}\n\nexport default toFormData;\n","'use strict';\n\nimport toFormData from './toFormData.js';\n\n/**\n * It encodes a string by replacing all characters that are not in the unreserved set with\n * their percent-encoded equivalents\n *\n * @param {string} str - The string to encode.\n *\n * @returns {string} The encoded string.\n */\nfunction encode(str) {\n const charMap = {\n '!': '%21',\n \"'\": '%27',\n '(': '%28',\n ')': '%29',\n '~': '%7E',\n '%20': '+',\n '%00': '\\x00'\n };\n return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {\n return charMap[match];\n });\n}\n\n/**\n * It takes a params object and converts it to a FormData object\n *\n * @param {Object} params - The parameters to be converted to a FormData object.\n * @param {Object} options - The options object passed to the Axios constructor.\n *\n * @returns {void}\n */\nfunction AxiosURLSearchParams(params, options) {\n this._pairs = [];\n\n params && toFormData(params, this, options);\n}\n\nconst prototype = AxiosURLSearchParams.prototype;\n\nprototype.append = function append(name, value) {\n this._pairs.push([name, value]);\n};\n\nprototype.toString = function toString(encoder) {\n const _encode = encoder ? function(value) {\n return encoder.call(this, value, encode);\n } : encode;\n\n return this._pairs.map(function each(pair) {\n return _encode(pair[0]) + '=' + _encode(pair[1]);\n }, '').join('&');\n};\n\nexport default AxiosURLSearchParams;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';\n\n/**\n * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their\n * URI encoded counterparts\n *\n * @param {string} val The value to be encoded.\n *\n * @returns {string} The encoded value.\n */\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @param {?(object|Function)} options\n *\n * @returns {string} The formatted url\n */\nexport default function buildURL(url, params, options) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n \n const _encode = options && options.encode || encode;\n\n if (utils.isFunction(options)) {\n options = {\n serialize: options\n };\n } \n\n const serializeFn = options && options.serialize;\n\n let serializedParams;\n\n if (serializeFn) {\n serializedParams = serializeFn(params, options);\n } else {\n serializedParams = utils.isURLSearchParams(params) ?\n params.toString() :\n new AxiosURLSearchParams(params, options).toString(_encode);\n }\n\n if (serializedParams) {\n const hashmarkIndex = url.indexOf(\"#\");\n\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\nclass InterceptorManager {\n constructor() {\n this.handlers = [];\n }\n\n /**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\n use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled,\n rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n }\n\n /**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n *\n * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise\n */\n eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n }\n\n /**\n * Clear all interceptors from the stack\n *\n * @returns {void}\n */\n clear() {\n if (this.handlers) {\n this.handlers = [];\n }\n }\n\n /**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n *\n * @returns {void}\n */\n forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n }\n}\n\nexport default InterceptorManager;\n","'use strict';\n\nexport default {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n};\n","import URLSearchParams from './classes/URLSearchParams.js'\nimport FormData from './classes/FormData.js'\nimport Blob from './classes/Blob.js'\n\nexport default {\n isBrowser: true,\n classes: {\n URLSearchParams,\n FormData,\n Blob\n },\n protocols: ['http', 'https', 'file', 'blob', 'url', 'data']\n};\n","'use strict';\n\nimport AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';\nexport default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;\n","'use strict';\n\nexport default typeof FormData !== 'undefined' ? FormData : null;\n","'use strict'\n\nexport default typeof Blob !== 'undefined' ? Blob : null\n","const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';\n\nconst _navigator = typeof navigator === 'object' && navigator || undefined;\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n *\n * @returns {boolean}\n */\nconst hasStandardBrowserEnv = hasBrowserEnv &&\n (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);\n\n/**\n * Determine if we're running in a standard browser webWorker environment\n *\n * Although the `isStandardBrowserEnv` method indicates that\n * `allows axios to run in a web worker`, the WebWorker will still be\n * filtered out due to its judgment standard\n * `typeof window !== 'undefined' && typeof document !== 'undefined'`.\n * This leads to a problem when axios post `FormData` in webWorker\n */\nconst hasStandardBrowserWebWorkerEnv = (() => {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n // eslint-disable-next-line no-undef\n self instanceof WorkerGlobalScope &&\n typeof self.importScripts === 'function'\n );\n})();\n\nconst origin = hasBrowserEnv && window.location.href || 'http://localhost';\n\nexport {\n hasBrowserEnv,\n hasStandardBrowserWebWorkerEnv,\n hasStandardBrowserEnv,\n _navigator as navigator,\n origin\n}\n","import platform from './node/index.js';\nimport * as utils from './common/utils.js';\n\nexport default {\n ...utils,\n ...platform\n}\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']\n *\n * @param {string} name - The name of the property to get.\n *\n * @returns An array of strings.\n */\nfunction parsePropPath(name) {\n // foo[x][y][z]\n // foo.x.y.z\n // foo-x-y-z\n // foo x y z\n return utils.matchAll(/\\w+|\\[(\\w*)]/g, name).map(match => {\n return match[0] === '[]' ? '' : match[1] || match[0];\n });\n}\n\n/**\n * Convert an array to an object.\n *\n * @param {Array} arr - The array to convert to an object.\n *\n * @returns An object with the same keys and values as the array.\n */\nfunction arrayToObject(arr) {\n const obj = {};\n const keys = Object.keys(arr);\n let i;\n const len = keys.length;\n let key;\n for (i = 0; i < len; i++) {\n key = keys[i];\n obj[key] = arr[key];\n }\n return obj;\n}\n\n/**\n * It takes a FormData object and returns a JavaScript object\n *\n * @param {string} formData The FormData object to convert to JSON.\n *\n * @returns {Object | null} The converted object.\n */\nfunction formDataToJSON(formData) {\n function buildPath(path, value, target, index) {\n let name = path[index++];\n\n if (name === '__proto__') return true;\n\n const isNumericKey = Number.isFinite(+name);\n const isLast = index >= path.length;\n name = !name && utils.isArray(target) ? target.length : name;\n\n if (isLast) {\n if (utils.hasOwnProp(target, name)) {\n target[name] = [target[name], value];\n } else {\n target[name] = value;\n }\n\n return !isNumericKey;\n }\n\n if (!target[name] || !utils.isObject(target[name])) {\n target[name] = [];\n }\n\n const result = buildPath(path, value, target[name], index);\n\n if (result && utils.isArray(target[name])) {\n target[name] = arrayToObject(target[name]);\n }\n\n return !isNumericKey;\n }\n\n if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {\n const obj = {};\n\n utils.forEachEntry(formData, (name, value) => {\n buildPath(parsePropPath(name), value, obj, 0);\n });\n\n return obj;\n }\n\n return null;\n}\n\nexport default formDataToJSON;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\nimport transitionalDefaults from './transitional.js';\nimport toFormData from '../helpers/toFormData.js';\nimport toURLEncodedForm from '../helpers/toURLEncodedForm.js';\nimport platform from '../platform/index.js';\nimport formDataToJSON from '../helpers/formDataToJSON.js';\n\n/**\n * It takes a string, tries to parse it, and if it fails, it returns the stringified version\n * of the input\n *\n * @param {any} rawValue - The value to be stringified.\n * @param {Function} parser - A function that parses a string into a JavaScript object.\n * @param {Function} encoder - A function that takes a value and returns a string.\n *\n * @returns {string} A stringified version of the rawValue.\n */\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nconst defaults = {\n\n transitional: transitionalDefaults,\n\n adapter: ['xhr', 'http', 'fetch'],\n\n transformRequest: [function transformRequest(data, headers) {\n const contentType = headers.getContentType() || '';\n const hasJSONContentType = contentType.indexOf('application/json') > -1;\n const isObjectPayload = utils.isObject(data);\n\n if (isObjectPayload && utils.isHTMLForm(data)) {\n data = new FormData(data);\n }\n\n const isFormData = utils.isFormData(data);\n\n if (isFormData) {\n return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;\n }\n\n if (utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data) ||\n utils.isReadableStream(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);\n return data.toString();\n }\n\n let isFileList;\n\n if (isObjectPayload) {\n if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {\n return toURLEncodedForm(data, this.formSerializer).toString();\n }\n\n if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {\n const _FormData = this.env && this.env.FormData;\n\n return toFormData(\n isFileList ? {'files[]': data} : data,\n _FormData && new _FormData(),\n this.formSerializer\n );\n }\n }\n\n if (isObjectPayload || hasJSONContentType ) {\n headers.setContentType('application/json', false);\n return stringifySafely(data);\n }\n\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n const transitional = this.transitional || defaults.transitional;\n const forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n const JSONRequested = this.responseType === 'json';\n\n if (utils.isResponse(data) || utils.isReadableStream(data)) {\n return data;\n }\n\n if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {\n const silentJSONParsing = transitional && transitional.silentJSONParsing;\n const strictJSONParsing = !silentJSONParsing && JSONRequested;\n\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n env: {\n FormData: platform.classes.FormData,\n Blob: platform.classes.Blob\n },\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*',\n 'Content-Type': undefined\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {\n defaults.headers[method] = {};\n});\n\nexport default defaults;\n","'use strict';\n\nimport utils from '../utils.js';\nimport toFormData from './toFormData.js';\nimport platform from '../platform/index.js';\n\nexport default function toURLEncodedForm(data, options) {\n return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({\n visitor: function(value, key, path, helpers) {\n if (platform.isNode && utils.isBuffer(value)) {\n this.append(key, value.toString('base64'));\n return false;\n }\n\n return helpers.defaultVisitor.apply(this, arguments);\n }\n }, options));\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\n// RawAxiosHeaders whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nconst ignoreDuplicateOf = utils.toObjectSet([\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n]);\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} rawHeaders Headers needing to be parsed\n *\n * @returns {Object} Headers parsed into an object\n */\nexport default rawHeaders => {\n const parsed = {};\n let key;\n let val;\n let i;\n\n rawHeaders && rawHeaders.split('\\n').forEach(function parser(line) {\n i = line.indexOf(':');\n key = line.substring(0, i).trim().toLowerCase();\n val = line.substring(i + 1).trim();\n\n if (!key || (parsed[key] && ignoreDuplicateOf[key])) {\n return;\n }\n\n if (key === 'set-cookie') {\n if (parsed[key]) {\n parsed[key].push(val);\n } else {\n parsed[key] = [val];\n }\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n });\n\n return parsed;\n};\n","'use strict';\n\nimport utils from '../utils.js';\nimport parseHeaders from '../helpers/parseHeaders.js';\n\nconst $internals = Symbol('internals');\n\nfunction normalizeHeader(header) {\n return header && String(header).trim().toLowerCase();\n}\n\nfunction normalizeValue(value) {\n if (value === false || value == null) {\n return value;\n }\n\n return utils.isArray(value) ? value.map(normalizeValue) : String(value);\n}\n\nfunction parseTokens(str) {\n const tokens = Object.create(null);\n const tokensRE = /([^\\s,;=]+)\\s*(?:=\\s*([^,;]+))?/g;\n let match;\n\n while ((match = tokensRE.exec(str))) {\n tokens[match[1]] = match[2];\n }\n\n return tokens;\n}\n\nconst isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());\n\nfunction matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {\n if (utils.isFunction(filter)) {\n return filter.call(this, value, header);\n }\n\n if (isHeaderNameFilter) {\n value = header;\n }\n\n if (!utils.isString(value)) return;\n\n if (utils.isString(filter)) {\n return value.indexOf(filter) !== -1;\n }\n\n if (utils.isRegExp(filter)) {\n return filter.test(value);\n }\n}\n\nfunction formatHeader(header) {\n return header.trim()\n .toLowerCase().replace(/([a-z\\d])(\\w*)/g, (w, char, str) => {\n return char.toUpperCase() + str;\n });\n}\n\nfunction buildAccessors(obj, header) {\n const accessorName = utils.toCamelCase(' ' + header);\n\n ['get', 'set', 'has'].forEach(methodName => {\n Object.defineProperty(obj, methodName + accessorName, {\n value: function(arg1, arg2, arg3) {\n return this[methodName].call(this, header, arg1, arg2, arg3);\n },\n configurable: true\n });\n });\n}\n\nclass AxiosHeaders {\n constructor(headers) {\n headers && this.set(headers);\n }\n\n set(header, valueOrRewrite, rewrite) {\n const self = this;\n\n function setHeader(_value, _header, _rewrite) {\n const lHeader = normalizeHeader(_header);\n\n if (!lHeader) {\n throw new Error('header name must be a non-empty string');\n }\n\n const key = utils.findKey(self, lHeader);\n\n if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {\n self[key || _header] = normalizeValue(_value);\n }\n }\n\n const setHeaders = (headers, _rewrite) =>\n utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));\n\n if (utils.isPlainObject(header) || header instanceof this.constructor) {\n setHeaders(header, valueOrRewrite)\n } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {\n setHeaders(parseHeaders(header), valueOrRewrite);\n } else if (utils.isHeaders(header)) {\n for (const [key, value] of header.entries()) {\n setHeader(value, key, rewrite);\n }\n } else {\n header != null && setHeader(valueOrRewrite, header, rewrite);\n }\n\n return this;\n }\n\n get(header, parser) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n if (key) {\n const value = this[key];\n\n if (!parser) {\n return value;\n }\n\n if (parser === true) {\n return parseTokens(value);\n }\n\n if (utils.isFunction(parser)) {\n return parser.call(this, value, key);\n }\n\n if (utils.isRegExp(parser)) {\n return parser.exec(value);\n }\n\n throw new TypeError('parser must be boolean|regexp|function');\n }\n }\n }\n\n has(header, matcher) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));\n }\n\n return false;\n }\n\n delete(header, matcher) {\n const self = this;\n let deleted = false;\n\n function deleteHeader(_header) {\n _header = normalizeHeader(_header);\n\n if (_header) {\n const key = utils.findKey(self, _header);\n\n if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {\n delete self[key];\n\n deleted = true;\n }\n }\n }\n\n if (utils.isArray(header)) {\n header.forEach(deleteHeader);\n } else {\n deleteHeader(header);\n }\n\n return deleted;\n }\n\n clear(matcher) {\n const keys = Object.keys(this);\n let i = keys.length;\n let deleted = false;\n\n while (i--) {\n const key = keys[i];\n if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {\n delete this[key];\n deleted = true;\n }\n }\n\n return deleted;\n }\n\n normalize(format) {\n const self = this;\n const headers = {};\n\n utils.forEach(this, (value, header) => {\n const key = utils.findKey(headers, header);\n\n if (key) {\n self[key] = normalizeValue(value);\n delete self[header];\n return;\n }\n\n const normalized = format ? formatHeader(header) : String(header).trim();\n\n if (normalized !== header) {\n delete self[header];\n }\n\n self[normalized] = normalizeValue(value);\n\n headers[normalized] = true;\n });\n\n return this;\n }\n\n concat(...targets) {\n return this.constructor.concat(this, ...targets);\n }\n\n toJSON(asStrings) {\n const obj = Object.create(null);\n\n utils.forEach(this, (value, header) => {\n value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);\n });\n\n return obj;\n }\n\n [Symbol.iterator]() {\n return Object.entries(this.toJSON())[Symbol.iterator]();\n }\n\n toString() {\n return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\\n');\n }\n\n get [Symbol.toStringTag]() {\n return 'AxiosHeaders';\n }\n\n static from(thing) {\n return thing instanceof this ? thing : new this(thing);\n }\n\n static concat(first, ...targets) {\n const computed = new this(first);\n\n targets.forEach((target) => computed.set(target));\n\n return computed;\n }\n\n static accessor(header) {\n const internals = this[$internals] = (this[$internals] = {\n accessors: {}\n });\n\n const accessors = internals.accessors;\n const prototype = this.prototype;\n\n function defineAccessor(_header) {\n const lHeader = normalizeHeader(_header);\n\n if (!accessors[lHeader]) {\n buildAccessors(prototype, _header);\n accessors[lHeader] = true;\n }\n }\n\n utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);\n\n return this;\n }\n}\n\nAxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);\n\n// reserved names hotfix\nutils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {\n let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`\n return {\n get: () => value,\n set(headerValue) {\n this[mapped] = headerValue;\n }\n }\n});\n\nutils.freezeMethods(AxiosHeaders);\n\nexport default AxiosHeaders;\n","'use strict';\n\nimport utils from './../utils.js';\nimport defaults from '../defaults/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Array|Function} fns A single function or Array of functions\n * @param {?Object} response The response object\n *\n * @returns {*} The resulting transformed data\n */\nexport default function transformData(fns, response) {\n const config = this || defaults;\n const context = response || config;\n const headers = AxiosHeaders.from(context.headers);\n let data = context.data;\n\n utils.forEach(fns, function transform(fn) {\n data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);\n });\n\n headers.normalize();\n\n return data;\n}\n","'use strict';\n\nexport default function isCancel(value) {\n return !!(value && value.__CANCEL__);\n}\n","'use strict';\n\nimport AxiosError from '../core/AxiosError.js';\nimport utils from '../utils.js';\n\n/**\n * A `CanceledError` is an object that is thrown when an operation is canceled.\n *\n * @param {string=} message The message.\n * @param {Object=} config The config.\n * @param {Object=} request The request.\n *\n * @returns {CanceledError} The created error.\n */\nfunction CanceledError(message, config, request) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);\n this.name = 'CanceledError';\n}\n\nutils.inherits(CanceledError, AxiosError, {\n __CANCEL__: true\n});\n\nexport default CanceledError;\n","'use strict';\n\nimport AxiosError from './AxiosError.js';\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n *\n * @returns {object} The response.\n */\nexport default function settle(resolve, reject, response) {\n const validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(new AxiosError(\n 'Request failed with status code ' + response.status,\n [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],\n response.config,\n response.request,\n response\n ));\n }\n}\n","import speedometer from \"./speedometer.js\";\nimport throttle from \"./throttle.js\";\nimport utils from \"../utils.js\";\n\nexport const progressEventReducer = (listener, isDownloadStream, freq = 3) => {\n let bytesNotified = 0;\n const _speedometer = speedometer(50, 250);\n\n return throttle(e => {\n const loaded = e.loaded;\n const total = e.lengthComputable ? e.total : undefined;\n const progressBytes = loaded - bytesNotified;\n const rate = _speedometer(progressBytes);\n const inRange = loaded <= total;\n\n bytesNotified = loaded;\n\n const data = {\n loaded,\n total,\n progress: total ? (loaded / total) : undefined,\n bytes: progressBytes,\n rate: rate ? rate : undefined,\n estimated: rate && total && inRange ? (total - loaded) / rate : undefined,\n event: e,\n lengthComputable: total != null,\n [isDownloadStream ? 'download' : 'upload']: true\n };\n\n listener(data);\n }, freq);\n}\n\nexport const progressEventDecorator = (total, throttled) => {\n const lengthComputable = total != null;\n\n return [(loaded) => throttled[0]({\n lengthComputable,\n total,\n loaded\n }), throttled[1]];\n}\n\nexport const asyncDecorator = (fn) => (...args) => utils.asap(() => fn(...args));\n","'use strict';\n\n/**\n * Calculate data maxRate\n * @param {Number} [samplesCount= 10]\n * @param {Number} [min= 1000]\n * @returns {Function}\n */\nfunction speedometer(samplesCount, min) {\n samplesCount = samplesCount || 10;\n const bytes = new Array(samplesCount);\n const timestamps = new Array(samplesCount);\n let head = 0;\n let tail = 0;\n let firstSampleTS;\n\n min = min !== undefined ? min : 1000;\n\n return function push(chunkLength) {\n const now = Date.now();\n\n const startedAt = timestamps[tail];\n\n if (!firstSampleTS) {\n firstSampleTS = now;\n }\n\n bytes[head] = chunkLength;\n timestamps[head] = now;\n\n let i = tail;\n let bytesCount = 0;\n\n while (i !== head) {\n bytesCount += bytes[i++];\n i = i % samplesCount;\n }\n\n head = (head + 1) % samplesCount;\n\n if (head === tail) {\n tail = (tail + 1) % samplesCount;\n }\n\n if (now - firstSampleTS < min) {\n return;\n }\n\n const passed = startedAt && now - startedAt;\n\n return passed ? Math.round(bytesCount * 1000 / passed) : undefined;\n };\n}\n\nexport default speedometer;\n","/**\n * Throttle decorator\n * @param {Function} fn\n * @param {Number} freq\n * @return {Function}\n */\nfunction throttle(fn, freq) {\n let timestamp = 0;\n let threshold = 1000 / freq;\n let lastArgs;\n let timer;\n\n const invoke = (args, now = Date.now()) => {\n timestamp = now;\n lastArgs = null;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n fn.apply(null, args);\n }\n\n const throttled = (...args) => {\n const now = Date.now();\n const passed = now - timestamp;\n if ( passed >= threshold) {\n invoke(args, now);\n } else {\n lastArgs = args;\n if (!timer) {\n timer = setTimeout(() => {\n timer = null;\n invoke(lastArgs)\n }, threshold - passed);\n }\n }\n }\n\n const flush = () => lastArgs && invoke(lastArgs);\n\n return [throttled, flush];\n}\n\nexport default throttle;\n","import platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {\n url = new URL(url, platform.origin);\n\n return (\n origin.protocol === url.protocol &&\n origin.host === url.host &&\n (isMSIE || origin.port === url.port)\n );\n})(\n new URL(platform.origin),\n platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)\n) : () => true;\n","import utils from './../utils.js';\nimport platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ?\n\n // Standard browser envs support document.cookie\n {\n write(name, value, expires, path, domain, secure) {\n const cookie = [name + '=' + encodeURIComponent(value)];\n\n utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());\n\n utils.isString(path) && cookie.push('path=' + path);\n\n utils.isString(domain) && cookie.push('domain=' + domain);\n\n secure === true && cookie.push('secure');\n\n document.cookie = cookie.join('; ');\n },\n\n read(name) {\n const match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n }\n\n :\n\n // Non-standard browser env (web workers, react-native) lack needed support.\n {\n write() {},\n read() {\n return null;\n },\n remove() {}\n };\n\n","'use strict';\n\nimport isAbsoluteURL from '../helpers/isAbsoluteURL.js';\nimport combineURLs from '../helpers/combineURLs.js';\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n *\n * @returns {string} The combined full path\n */\nexport default function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n}\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n *\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nexport default function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n}\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n *\n * @returns {string} The combined URL\n */\nexport default function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/?\\/$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosHeaders from \"./AxiosHeaders.js\";\n\nconst headersToObject = (thing) => thing instanceof AxiosHeaders ? { ...thing } : thing;\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n *\n * @returns {Object} New object resulting from merging config2 to config1\n */\nexport default function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n const config = {};\n\n function getMergedValue(target, source, prop, caseless) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge.call({caseless}, target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(a, b, prop , caseless) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(a, b, prop , caseless);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a, prop , caseless);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(a, b, prop) {\n if (prop in config2) {\n return getMergedValue(a, b);\n } else if (prop in config1) {\n return getMergedValue(undefined, a);\n }\n }\n\n const mergeMap = {\n url: valueFromConfig2,\n method: valueFromConfig2,\n data: valueFromConfig2,\n baseURL: defaultToConfig2,\n transformRequest: defaultToConfig2,\n transformResponse: defaultToConfig2,\n paramsSerializer: defaultToConfig2,\n timeout: defaultToConfig2,\n timeoutMessage: defaultToConfig2,\n withCredentials: defaultToConfig2,\n withXSRFToken: defaultToConfig2,\n adapter: defaultToConfig2,\n responseType: defaultToConfig2,\n xsrfCookieName: defaultToConfig2,\n xsrfHeaderName: defaultToConfig2,\n onUploadProgress: defaultToConfig2,\n onDownloadProgress: defaultToConfig2,\n decompress: defaultToConfig2,\n maxContentLength: defaultToConfig2,\n maxBodyLength: defaultToConfig2,\n beforeRedirect: defaultToConfig2,\n transport: defaultToConfig2,\n httpAgent: defaultToConfig2,\n httpsAgent: defaultToConfig2,\n cancelToken: defaultToConfig2,\n socketPath: defaultToConfig2,\n responseEncoding: defaultToConfig2,\n validateStatus: mergeDirectKeys,\n headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true)\n };\n\n utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {\n const merge = mergeMap[prop] || mergeDeepProperties;\n const configValue = merge(config1[prop], config2[prop], prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n}\n","import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport isURLSameOrigin from \"./isURLSameOrigin.js\";\nimport cookies from \"./cookies.js\";\nimport buildFullPath from \"../core/buildFullPath.js\";\nimport mergeConfig from \"../core/mergeConfig.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport buildURL from \"./buildURL.js\";\n\nexport default (config) => {\n const newConfig = mergeConfig({}, config);\n\n let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;\n\n newConfig.headers = headers = AxiosHeaders.from(headers);\n\n newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);\n\n // HTTP basic authentication\n if (auth) {\n headers.set('Authorization', 'Basic ' +\n btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))\n );\n }\n\n let contentType;\n\n if (utils.isFormData(data)) {\n if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {\n headers.setContentType(undefined); // Let the browser set it\n } else if ((contentType = headers.getContentType()) !== false) {\n // fix semicolon duplication issue for ReactNative FormData implementation\n const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];\n headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));\n }\n }\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n\n if (platform.hasStandardBrowserEnv) {\n withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));\n\n if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {\n // Add xsrf header\n const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);\n\n if (xsrfValue) {\n headers.set(xsrfHeaderName, xsrfValue);\n }\n }\n }\n\n return newConfig;\n}\n\n","import utils from './../utils.js';\nimport settle from './../core/settle.js';\nimport transitionalDefaults from '../defaults/transitional.js';\nimport AxiosError from '../core/AxiosError.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport parseProtocol from '../helpers/parseProtocol.js';\nimport platform from '../platform/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport {progressEventReducer} from '../helpers/progressEventReducer.js';\nimport resolveConfig from \"../helpers/resolveConfig.js\";\n\nconst isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';\n\nexport default isXHRAdapterSupported && function (config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n const _config = resolveConfig(config);\n let requestData = _config.data;\n const requestHeaders = AxiosHeaders.from(_config.headers).normalize();\n let {responseType, onUploadProgress, onDownloadProgress} = _config;\n let onCanceled;\n let uploadThrottled, downloadThrottled;\n let flushUpload, flushDownload;\n\n function done() {\n flushUpload && flushUpload(); // flush events\n flushDownload && flushDownload(); // flush events\n\n _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);\n\n _config.signal && _config.signal.removeEventListener('abort', onCanceled);\n }\n\n let request = new XMLHttpRequest();\n\n request.open(_config.method.toUpperCase(), _config.url, true);\n\n // Set the request timeout in MS\n request.timeout = _config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n const responseHeaders = AxiosHeaders.from(\n 'getAllResponseHeaders' in request && request.getAllResponseHeaders()\n );\n const responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n const response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config,\n request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';\n const transitional = _config.transitional || transitionalDefaults;\n if (_config.timeoutErrorMessage) {\n timeoutErrorMessage = _config.timeoutErrorMessage;\n }\n reject(new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n config,\n request));\n\n // Clean up request\n request = null;\n };\n\n // Remove Content-Type if data is undefined\n requestData === undefined && requestHeaders.setContentType(null);\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {\n request.setRequestHeader(key, val);\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(_config.withCredentials)) {\n request.withCredentials = !!_config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = _config.responseType;\n }\n\n // Handle progress if needed\n if (onDownloadProgress) {\n ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));\n request.addEventListener('progress', downloadThrottled);\n }\n\n // Not all browsers support upload events\n if (onUploadProgress && request.upload) {\n ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));\n\n request.upload.addEventListener('progress', uploadThrottled);\n\n request.upload.addEventListener('loadend', flushUpload);\n }\n\n if (_config.cancelToken || _config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = cancel => {\n if (!request) {\n return;\n }\n reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);\n request.abort();\n request = null;\n };\n\n _config.cancelToken && _config.cancelToken.subscribe(onCanceled);\n if (_config.signal) {\n _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n const protocol = parseProtocol(_config.url);\n\n if (protocol && platform.protocols.indexOf(protocol) === -1) {\n reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));\n return;\n }\n\n\n // Send the request\n request.send(requestData || null);\n });\n}\n","'use strict';\n\nexport default function parseProtocol(url) {\n const match = /^([-+\\w]{1,25})(:?\\/\\/|:)/.exec(url);\n return match && match[1] || '';\n}\n","import CanceledError from \"../cancel/CanceledError.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport utils from '../utils.js';\n\nconst composeSignals = (signals, timeout) => {\n const {length} = (signals = signals ? signals.filter(Boolean) : []);\n\n if (timeout || length) {\n let controller = new AbortController();\n\n let aborted;\n\n const onabort = function (reason) {\n if (!aborted) {\n aborted = true;\n unsubscribe();\n const err = reason instanceof Error ? reason : this.reason;\n controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));\n }\n }\n\n let timer = timeout && setTimeout(() => {\n timer = null;\n onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT))\n }, timeout)\n\n const unsubscribe = () => {\n if (signals) {\n timer && clearTimeout(timer);\n timer = null;\n signals.forEach(signal => {\n signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);\n });\n signals = null;\n }\n }\n\n signals.forEach((signal) => signal.addEventListener('abort', onabort));\n\n const {signal} = controller;\n\n signal.unsubscribe = () => utils.asap(unsubscribe);\n\n return signal;\n }\n}\n\nexport default composeSignals;\n","\nexport const streamChunk = function* (chunk, chunkSize) {\n let len = chunk.byteLength;\n\n if (!chunkSize || len < chunkSize) {\n yield chunk;\n return;\n }\n\n let pos = 0;\n let end;\n\n while (pos < len) {\n end = pos + chunkSize;\n yield chunk.slice(pos, end);\n pos = end;\n }\n}\n\nexport const readBytes = async function* (iterable, chunkSize) {\n for await (const chunk of readStream(iterable)) {\n yield* streamChunk(chunk, chunkSize);\n }\n}\n\nconst readStream = async function* (stream) {\n if (stream[Symbol.asyncIterator]) {\n yield* stream;\n return;\n }\n\n const reader = stream.getReader();\n try {\n for (;;) {\n const {done, value} = await reader.read();\n if (done) {\n break;\n }\n yield value;\n }\n } finally {\n await reader.cancel();\n }\n}\n\nexport const trackStream = (stream, chunkSize, onProgress, onFinish) => {\n const iterator = readBytes(stream, chunkSize);\n\n let bytes = 0;\n let done;\n let _onFinish = (e) => {\n if (!done) {\n done = true;\n onFinish && onFinish(e);\n }\n }\n\n return new ReadableStream({\n async pull(controller) {\n try {\n const {done, value} = await iterator.next();\n\n if (done) {\n _onFinish();\n controller.close();\n return;\n }\n\n let len = value.byteLength;\n if (onProgress) {\n let loadedBytes = bytes += len;\n onProgress(loadedBytes);\n }\n controller.enqueue(new Uint8Array(value));\n } catch (err) {\n _onFinish(err);\n throw err;\n }\n },\n cancel(reason) {\n _onFinish(reason);\n return iterator.return();\n }\n }, {\n highWaterMark: 2\n })\n}\n","import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport composeSignals from \"../helpers/composeSignals.js\";\nimport {trackStream} from \"../helpers/trackStream.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport {progressEventReducer, progressEventDecorator, asyncDecorator} from \"../helpers/progressEventReducer.js\";\nimport resolveConfig from \"../helpers/resolveConfig.js\";\nimport settle from \"../core/settle.js\";\n\nconst isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';\nconst isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';\n\n// used only inside the fetch adapter\nconst encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?\n ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :\n async (str) => new Uint8Array(await new Response(str).arrayBuffer())\n);\n\nconst test = (fn, ...args) => {\n try {\n return !!fn(...args);\n } catch (e) {\n return false\n }\n}\n\nconst supportsRequestStream = isReadableStreamSupported && test(() => {\n let duplexAccessed = false;\n\n const hasContentType = new Request(platform.origin, {\n body: new ReadableStream(),\n method: 'POST',\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n }).headers.has('Content-Type');\n\n return duplexAccessed && !hasContentType;\n});\n\nconst DEFAULT_CHUNK_SIZE = 64 * 1024;\n\nconst supportsResponseStream = isReadableStreamSupported &&\n test(() => utils.isReadableStream(new Response('').body));\n\n\nconst resolvers = {\n stream: supportsResponseStream && ((res) => res.body)\n};\n\nisFetchSupported && (((res) => {\n ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {\n !resolvers[type] && (resolvers[type] = utils.isFunction(res[type]) ? (res) => res[type]() :\n (_, config) => {\n throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);\n })\n });\n})(new Response));\n\nconst getBodyLength = async (body) => {\n if (body == null) {\n return 0;\n }\n\n if(utils.isBlob(body)) {\n return body.size;\n }\n\n if(utils.isSpecCompliantForm(body)) {\n const _request = new Request(platform.origin, {\n method: 'POST',\n body,\n });\n return (await _request.arrayBuffer()).byteLength;\n }\n\n if(utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) {\n return body.byteLength;\n }\n\n if(utils.isURLSearchParams(body)) {\n body = body + '';\n }\n\n if(utils.isString(body)) {\n return (await encodeText(body)).byteLength;\n }\n}\n\nconst resolveBodyLength = async (headers, body) => {\n const length = utils.toFiniteNumber(headers.getContentLength());\n\n return length == null ? getBodyLength(body) : length;\n}\n\nexport default isFetchSupported && (async (config) => {\n let {\n url,\n method,\n data,\n signal,\n cancelToken,\n timeout,\n onDownloadProgress,\n onUploadProgress,\n responseType,\n headers,\n withCredentials = 'same-origin',\n fetchOptions\n } = resolveConfig(config);\n\n responseType = responseType ? (responseType + '').toLowerCase() : 'text';\n\n let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);\n\n let request;\n\n const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {\n composedSignal.unsubscribe();\n });\n\n let requestContentLength;\n\n try {\n if (\n onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&\n (requestContentLength = await resolveBodyLength(headers, data)) !== 0\n ) {\n let _request = new Request(url, {\n method: 'POST',\n body: data,\n duplex: \"half\"\n });\n\n let contentTypeHeader;\n\n if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {\n headers.setContentType(contentTypeHeader)\n }\n\n if (_request.body) {\n const [onProgress, flush] = progressEventDecorator(\n requestContentLength,\n progressEventReducer(asyncDecorator(onUploadProgress))\n );\n\n data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);\n }\n }\n\n if (!utils.isString(withCredentials)) {\n withCredentials = withCredentials ? 'include' : 'omit';\n }\n\n // Cloudflare Workers throws when credentials are defined\n // see https://github.com/cloudflare/workerd/issues/902\n const isCredentialsSupported = \"credentials\" in Request.prototype;\n request = new Request(url, {\n ...fetchOptions,\n signal: composedSignal,\n method: method.toUpperCase(),\n headers: headers.normalize().toJSON(),\n body: data,\n duplex: \"half\",\n credentials: isCredentialsSupported ? withCredentials : undefined\n });\n\n let response = await fetch(request);\n\n const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');\n\n if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {\n const options = {};\n\n ['status', 'statusText', 'headers'].forEach(prop => {\n options[prop] = response[prop];\n });\n\n const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length'));\n\n const [onProgress, flush] = onDownloadProgress && progressEventDecorator(\n responseContentLength,\n progressEventReducer(asyncDecorator(onDownloadProgress), true)\n ) || [];\n\n response = new Response(\n trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {\n flush && flush();\n unsubscribe && unsubscribe();\n }),\n options\n );\n }\n\n responseType = responseType || 'text';\n\n let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config);\n\n !isStreamResponse && unsubscribe && unsubscribe();\n\n return await new Promise((resolve, reject) => {\n settle(resolve, reject, {\n data: responseData,\n headers: AxiosHeaders.from(response.headers),\n status: response.status,\n statusText: response.statusText,\n config,\n request\n })\n })\n } catch (err) {\n unsubscribe && unsubscribe();\n\n if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {\n throw Object.assign(\n new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),\n {\n cause: err.cause || err\n }\n )\n }\n\n throw AxiosError.from(err, err && err.code, config, request);\n }\n});\n\n\n","import utils from '../utils.js';\nimport httpAdapter from './http.js';\nimport xhrAdapter from './xhr.js';\nimport fetchAdapter from './fetch.js';\nimport AxiosError from \"../core/AxiosError.js\";\n\nconst knownAdapters = {\n http: httpAdapter,\n xhr: xhrAdapter,\n fetch: fetchAdapter\n}\n\nutils.forEach(knownAdapters, (fn, value) => {\n if (fn) {\n try {\n Object.defineProperty(fn, 'name', {value});\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n Object.defineProperty(fn, 'adapterName', {value});\n }\n});\n\nconst renderReason = (reason) => `- ${reason}`;\n\nconst isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false;\n\nexport default {\n getAdapter: (adapters) => {\n adapters = utils.isArray(adapters) ? adapters : [adapters];\n\n const {length} = adapters;\n let nameOrAdapter;\n let adapter;\n\n const rejectedReasons = {};\n\n for (let i = 0; i < length; i++) {\n nameOrAdapter = adapters[i];\n let id;\n\n adapter = nameOrAdapter;\n\n if (!isResolvedHandle(nameOrAdapter)) {\n adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];\n\n if (adapter === undefined) {\n throw new AxiosError(`Unknown adapter '${id}'`);\n }\n }\n\n if (adapter) {\n break;\n }\n\n rejectedReasons[id || '#' + i] = adapter;\n }\n\n if (!adapter) {\n\n const reasons = Object.entries(rejectedReasons)\n .map(([id, state]) => `adapter ${id} ` +\n (state === false ? 'is not supported by the environment' : 'is not available in the build')\n );\n\n let s = length ?\n (reasons.length > 1 ? 'since :\\n' + reasons.map(renderReason).join('\\n') : ' ' + renderReason(reasons[0])) :\n 'as no adapter specified';\n\n throw new AxiosError(\n `There is no suitable adapter to dispatch the request ` + s,\n 'ERR_NOT_SUPPORT'\n );\n }\n\n return adapter;\n },\n adapters: knownAdapters\n}\n","// eslint-disable-next-line strict\nexport default null;\n","'use strict';\n\nimport transformData from './transformData.js';\nimport isCancel from '../cancel/isCancel.js';\nimport defaults from '../defaults/index.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport adapters from \"../adapters/adapters.js\";\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n *\n * @param {Object} config The config that is to be used for the request\n *\n * @returns {void}\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new CanceledError(null, config);\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n *\n * @returns {Promise} The Promise to be fulfilled\n */\nexport default function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n config.headers = AxiosHeaders.from(config.headers);\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.transformRequest\n );\n\n if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {\n config.headers.setContentType('application/x-www-form-urlencoded', false);\n }\n\n const adapter = adapters.getAdapter(config.adapter || defaults.adapter);\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n config.transformResponse,\n response\n );\n\n response.headers = AxiosHeaders.from(response.headers);\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n config.transformResponse,\n reason.response\n );\n reason.response.headers = AxiosHeaders.from(reason.response.headers);\n }\n }\n\n return Promise.reject(reason);\n });\n}\n","export const VERSION = \"1.7.9\";","'use strict';\n\nimport {VERSION} from '../env/data.js';\nimport AxiosError from '../core/AxiosError.js';\n\nconst validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nconst deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n *\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n *\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return (value, opt, opts) => {\n if (validator === false) {\n throw new AxiosError(\n formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),\n AxiosError.ERR_DEPRECATED\n );\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\nvalidators.spelling = function spelling(correctSpelling) {\n return (value, opt) => {\n // eslint-disable-next-line no-console\n console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);\n return true;\n }\n};\n\n/**\n * Assert object's properties type\n *\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n *\n * @returns {object}\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);\n }\n const keys = Object.keys(options);\n let i = keys.length;\n while (i-- > 0) {\n const opt = keys[i];\n const validator = schema[opt];\n if (validator) {\n const value = options[opt];\n const result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);\n }\n }\n}\n\nexport default {\n assertOptions,\n validators\n};\n","'use strict';\n\nimport utils from './../utils.js';\nimport buildURL from '../helpers/buildURL.js';\nimport InterceptorManager from './InterceptorManager.js';\nimport dispatchRequest from './dispatchRequest.js';\nimport mergeConfig from './mergeConfig.js';\nimport buildFullPath from './buildFullPath.js';\nimport validator from '../helpers/validator.js';\nimport AxiosHeaders from './AxiosHeaders.js';\n\nconst validators = validator.validators;\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n *\n * @return {Axios} A new instance of Axios\n */\nclass Axios {\n constructor(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n }\n\n /**\n * Dispatch a request\n *\n * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)\n * @param {?Object} config\n *\n * @returns {Promise} The Promise to be fulfilled\n */\n async request(configOrUrl, config) {\n try {\n return await this._request(configOrUrl, config);\n } catch (err) {\n if (err instanceof Error) {\n let dummy = {};\n\n Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());\n\n // slice off the Error: ... line\n const stack = dummy.stack ? dummy.stack.replace(/^.+\\n/, '') : '';\n try {\n if (!err.stack) {\n err.stack = stack;\n // match without the 2 top stack lines\n } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\\n.+\\n/, ''))) {\n err.stack += '\\n' + stack\n }\n } catch (e) {\n // ignore the case where \"stack\" is an un-writable property\n }\n }\n\n throw err;\n }\n }\n\n _request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n const {transitional, paramsSerializer, headers} = config;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n if (paramsSerializer != null) {\n if (utils.isFunction(paramsSerializer)) {\n config.paramsSerializer = {\n serialize: paramsSerializer\n }\n } else {\n validator.assertOptions(paramsSerializer, {\n encode: validators.function,\n serialize: validators.function\n }, true);\n }\n }\n\n validator.assertOptions(config, {\n baseUrl: validators.spelling('baseURL'),\n withXsrfToken: validators.spelling('withXSRFToken')\n }, true);\n\n // Set config.method\n config.method = (config.method || this.defaults.method || 'get').toLowerCase();\n\n // Flatten headers\n let contextHeaders = headers && utils.merge(\n headers.common,\n headers[config.method]\n );\n\n headers && utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n (method) => {\n delete headers[method];\n }\n );\n\n config.headers = AxiosHeaders.concat(contextHeaders, headers);\n\n // filter out skipped interceptors\n const requestInterceptorChain = [];\n let synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n const responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n let promise;\n let i = 0;\n let len;\n\n if (!synchronousRequestInterceptors) {\n const chain = [dispatchRequest.bind(this), undefined];\n chain.unshift.apply(chain, requestInterceptorChain);\n chain.push.apply(chain, responseInterceptorChain);\n len = chain.length;\n\n promise = Promise.resolve(config);\n\n while (i < len) {\n promise = promise.then(chain[i++], chain[i++]);\n }\n\n return promise;\n }\n\n len = requestInterceptorChain.length;\n\n let newConfig = config;\n\n i = 0;\n\n while (i < len) {\n const onFulfilled = requestInterceptorChain[i++];\n const onRejected = requestInterceptorChain[i++];\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected.call(this, error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest.call(this, newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n i = 0;\n len = responseInterceptorChain.length;\n\n while (i < len) {\n promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);\n }\n\n return promise;\n }\n\n getUri(config) {\n config = mergeConfig(this.defaults, config);\n const fullPath = buildFullPath(config.baseURL, config.url);\n return buildURL(fullPath, config.params, config.paramsSerializer);\n }\n}\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n\n function generateHTTPMethod(isForm) {\n return function httpMethod(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n headers: isForm ? {\n 'Content-Type': 'multipart/form-data'\n } : {},\n url,\n data\n }));\n };\n }\n\n Axios.prototype[method] = generateHTTPMethod();\n\n Axios.prototype[method + 'Form'] = generateHTTPMethod(true);\n});\n\nexport default Axios;\n","'use strict';\n\nimport CanceledError from './CanceledError.js';\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @param {Function} executor The executor function.\n *\n * @returns {CancelToken}\n */\nclass CancelToken {\n constructor(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n let resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n const token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(cancel => {\n if (!token._listeners) return;\n\n let i = token._listeners.length;\n\n while (i-- > 0) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = onfulfilled => {\n let _resolve;\n // eslint-disable-next-line func-names\n const promise = new Promise(resolve => {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message, config, request) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new CanceledError(message, config, request);\n resolvePromise(token.reason);\n });\n }\n\n /**\n * Throws a `CanceledError` if cancellation has been requested.\n */\n throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n }\n\n /**\n * Subscribe to the cancel signal\n */\n\n subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n }\n\n /**\n * Unsubscribe from the cancel signal\n */\n\n unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n const index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n }\n\n toAbortSignal() {\n const controller = new AbortController();\n\n const abort = (err) => {\n controller.abort(err);\n };\n\n this.subscribe(abort);\n\n controller.signal.unsubscribe = () => this.unsubscribe(abort);\n\n return controller.signal;\n }\n\n /**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\n static source() {\n let cancel;\n const token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token,\n cancel\n };\n }\n}\n\nexport default CancelToken;\n","const HttpStatusCode = {\n Continue: 100,\n SwitchingProtocols: 101,\n Processing: 102,\n EarlyHints: 103,\n Ok: 200,\n Created: 201,\n Accepted: 202,\n NonAuthoritativeInformation: 203,\n NoContent: 204,\n ResetContent: 205,\n PartialContent: 206,\n MultiStatus: 207,\n AlreadyReported: 208,\n ImUsed: 226,\n MultipleChoices: 300,\n MovedPermanently: 301,\n Found: 302,\n SeeOther: 303,\n NotModified: 304,\n UseProxy: 305,\n Unused: 306,\n TemporaryRedirect: 307,\n PermanentRedirect: 308,\n BadRequest: 400,\n Unauthorized: 401,\n PaymentRequired: 402,\n Forbidden: 403,\n NotFound: 404,\n MethodNotAllowed: 405,\n NotAcceptable: 406,\n ProxyAuthenticationRequired: 407,\n RequestTimeout: 408,\n Conflict: 409,\n Gone: 410,\n LengthRequired: 411,\n PreconditionFailed: 412,\n PayloadTooLarge: 413,\n UriTooLong: 414,\n UnsupportedMediaType: 415,\n RangeNotSatisfiable: 416,\n ExpectationFailed: 417,\n ImATeapot: 418,\n MisdirectedRequest: 421,\n UnprocessableEntity: 422,\n Locked: 423,\n FailedDependency: 424,\n TooEarly: 425,\n UpgradeRequired: 426,\n PreconditionRequired: 428,\n TooManyRequests: 429,\n RequestHeaderFieldsTooLarge: 431,\n UnavailableForLegalReasons: 451,\n InternalServerError: 500,\n NotImplemented: 501,\n BadGateway: 502,\n ServiceUnavailable: 503,\n GatewayTimeout: 504,\n HttpVersionNotSupported: 505,\n VariantAlsoNegotiates: 506,\n InsufficientStorage: 507,\n LoopDetected: 508,\n NotExtended: 510,\n NetworkAuthenticationRequired: 511,\n};\n\nObject.entries(HttpStatusCode).forEach(([key, value]) => {\n HttpStatusCode[value] = key;\n});\n\nexport default HttpStatusCode;\n","'use strict';\n\nimport utils from './utils.js';\nimport bind from './helpers/bind.js';\nimport Axios from './core/Axios.js';\nimport mergeConfig from './core/mergeConfig.js';\nimport defaults from './defaults/index.js';\nimport formDataToJSON from './helpers/formDataToJSON.js';\nimport CanceledError from './cancel/CanceledError.js';\nimport CancelToken from './cancel/CancelToken.js';\nimport isCancel from './cancel/isCancel.js';\nimport {VERSION} from './env/data.js';\nimport toFormData from './helpers/toFormData.js';\nimport AxiosError from './core/AxiosError.js';\nimport spread from './helpers/spread.js';\nimport isAxiosError from './helpers/isAxiosError.js';\nimport AxiosHeaders from \"./core/AxiosHeaders.js\";\nimport adapters from './adapters/adapters.js';\nimport HttpStatusCode from './helpers/HttpStatusCode.js';\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n *\n * @returns {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n const context = new Axios(defaultConfig);\n const instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});\n\n // Copy context to instance\n utils.extend(instance, context, null, {allOwnKeys: true});\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nconst axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.CanceledError = CanceledError;\naxios.CancelToken = CancelToken;\naxios.isCancel = isCancel;\naxios.VERSION = VERSION;\naxios.toFormData = toFormData;\n\n// Expose AxiosError class\naxios.AxiosError = AxiosError;\n\n// alias for CanceledError for backward compatibility\naxios.Cancel = axios.CanceledError;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\n\naxios.spread = spread;\n\n// Expose isAxiosError\naxios.isAxiosError = isAxiosError;\n\n// Expose mergeConfig\naxios.mergeConfig = mergeConfig;\n\naxios.AxiosHeaders = AxiosHeaders;\n\naxios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);\n\naxios.getAdapter = adapters.getAdapter;\n\naxios.HttpStatusCode = HttpStatusCode;\n\naxios.default = axios;\n\n// this module should only have a default export\nexport default axios\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n *\n * @returns {Function}\n */\nexport default function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n *\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nexport default function isAxiosError(payload) {\n return utils.isObject(payload) && (payload.isAxiosError === true);\n}\n","import axios from './lib/axios.js';\n\n// This module is intended to unwrap Axios default export as named.\n// Keep top-level export same with static properties\n// so that it can keep same with es module or cjs\nconst {\n Axios,\n AxiosError,\n CanceledError,\n isCancel,\n CancelToken,\n VERSION,\n all,\n Cancel,\n isAxiosError,\n spread,\n toFormData,\n AxiosHeaders,\n HttpStatusCode,\n formToJSON,\n getAdapter,\n mergeConfig\n} = axios;\n\nexport {\n axios as default,\n Axios,\n AxiosError,\n CanceledError,\n isCancel,\n CancelToken,\n VERSION,\n all,\n Cancel,\n isAxiosError,\n spread,\n toFormData,\n AxiosHeaders,\n HttpStatusCode,\n formToJSON,\n getAdapter,\n mergeConfig\n}\n"],"names":["bind","fn","thisArg","apply","arguments","toString","Object","prototype","getPrototypeOf","kindOf","cache","create","thing","str","call","slice","toLowerCase","kindOfTest","type","typeOfTest","isArray","Array","isUndefined","isArrayBuffer","isString","isFunction","isNumber","isObject","isPlainObject","val","Symbol","toStringTag","iterator","isDate","isFile","isBlob","isFileList","isURLSearchParams","isReadableStream","isRequest","isResponse","isHeaders","map","forEach","obj","allOwnKeys","i","l","length","keys","getOwnPropertyNames","len","key","findKey","_key","_global","globalThis","self","window","global","isContextDefined","context","isTypedArray","TypedArray","Uint8Array","isHTMLForm","hasOwnProperty","prop","isRegExp","reduceDescriptors","reducer","descriptors","getOwnPropertyDescriptors","reducedDescriptors","descriptor","name","ret","defineProperties","ALPHA","ALPHABET","DIGIT","ALPHA_DIGIT","toUpperCase","isAsyncFn","_setImmediate","setImmediateSupported","setImmediate","postMessageSupported","postMessage","token","Math","random","callbacks","addEventListener","source","data","shift","cb","push","setTimeout","asap","queueMicrotask","process","nextTick","utils$1","isBuffer","constructor","isFormData","kind","FormData","append","isArrayBufferView","result","ArrayBuffer","isView","buffer","isBoolean","isStream","pipe","merge","caseless","this","assignValue","targetKey","extend","a","b","trim","replace","stripBOM","content","charCodeAt","inherits","superConstructor","props","defineProperty","value","assign","toFlatObject","sourceObj","destObj","filter","propFilter","merged","endsWith","searchString","position","String","undefined","lastIndex","indexOf","toArray","arr","forEachEntry","next","done","pair","matchAll","regExp","matches","exec","hasOwnProp","freezeMethods","enumerable","writable","set","Error","toObjectSet","arrayOrString","delimiter","define","split","toCamelCase","m","p1","p2","noop","toFiniteNumber","defaultValue","Number","isFinite","generateString","size","alphabet","isSpecCompliantForm","toJSONObject","stack","visit","target","reducedValue","isThenable","then","catch","AxiosError","message","code","config","request","response","captureStackTrace","status","utils","toJSON","description","number","fileName","lineNumber","columnNumber","from","error","customProps","axiosError","cause","isVisitable","removeBrackets","renderKey","path","dots","concat","join","predicates","test","toFormData","formData","options","TypeError","metaTokens","indexes","option","visitor","defaultVisitor","useBlob","Blob","convertValue","toISOString","Buffer","JSON","stringify","some","isFlatArray","el","index","exposedHelpers","build","pop","encode","charMap","encodeURIComponent","match","AxiosURLSearchParams","params","_pairs","buildURL","url","_encode","serialize","serializeFn","serializedParams","hashmarkIndex","encoder","InterceptorManager$1","handlers","use","fulfilled","rejected","synchronous","runWhen","eject","id","clear","h","transitionalDefaults","silentJSONParsing","forcedJSONParsing","clarifyTimeoutError","platform$1","isBrowser","classes","URLSearchParams","protocols","hasBrowserEnv","document","_navigator","navigator","hasStandardBrowserEnv","product","hasStandardBrowserWebWorkerEnv","WorkerGlobalScope","importScripts","origin","location","href","platform","formDataToJSON","buildPath","isNumericKey","isLast","arrayToObject","entries","parsePropPath","defaults","transitional","adapter","transformRequest","headers","contentType","getContentType","hasJSONContentType","isObjectPayload","setContentType","helpers","isNode","toURLEncodedForm","formSerializer","_FormData","env","rawValue","parser","parse","e","stringifySafely","transformResponse","JSONRequested","responseType","strictJSONParsing","ERR_BAD_RESPONSE","timeout","xsrfCookieName","xsrfHeaderName","maxContentLength","maxBodyLength","validateStatus","common","Accept","method","defaults$1","ignoreDuplicateOf","$internals","normalizeHeader","header","normalizeValue","matchHeaderValue","isHeaderNameFilter","AxiosHeaders","valueOrRewrite","rewrite","setHeader","_value","_header","_rewrite","lHeader","setHeaders","rawHeaders","parsed","line","substring","parseHeaders","get","tokens","tokensRE","parseTokens","has","matcher","delete","deleted","deleteHeader","normalize","format","normalized","w","char","formatHeader","targets","asStrings","static","first","computed","accessors","defineAccessor","accessorName","methodName","arg1","arg2","arg3","configurable","buildAccessors","accessor","mapped","headerValue","AxiosHeaders$2","transformData","fns","isCancel","__CANCEL__","CanceledError","ERR_CANCELED","settle","resolve","reject","ERR_BAD_REQUEST","floor","progressEventReducer","listener","isDownloadStream","freq","bytesNotified","_speedometer","samplesCount","min","bytes","timestamps","firstSampleTS","head","tail","chunkLength","now","Date","startedAt","bytesCount","passed","round","speedometer","lastArgs","timer","timestamp","threshold","invoke","args","clearTimeout","throttle","loaded","total","lengthComputable","progressBytes","rate","progress","estimated","event","progressEventDecorator","throttled","asyncDecorator","isURLSameOrigin","isMSIE","URL","protocol","host","port","userAgent","cookies","write","expires","domain","secure","cookie","toGMTString","read","RegExp","decodeURIComponent","remove","buildFullPath","baseURL","requestedURL","relativeURL","combineURLs","headersToObject","mergeConfig","config1","config2","getMergedValue","mergeDeepProperties","valueFromConfig2","defaultToConfig2","mergeDirectKeys","mergeMap","paramsSerializer","timeoutMessage","withCredentials","withXSRFToken","onUploadProgress","onDownloadProgress","decompress","beforeRedirect","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding","configValue","resolveConfig","newConfig","auth","btoa","username","password","unescape","Boolean","xsrfValue","xhrAdapter","XMLHttpRequest","Promise","_config","requestData","requestHeaders","onCanceled","uploadThrottled","downloadThrottled","flushUpload","flushDownload","unsubscribe","signal","removeEventListener","onloadend","responseHeaders","getAllResponseHeaders","err","responseText","statusText","open","onreadystatechange","readyState","responseURL","onabort","ECONNABORTED","onerror","ERR_NETWORK","ontimeout","timeoutErrorMessage","ETIMEDOUT","setRequestHeader","upload","cancel","abort","subscribe","aborted","parseProtocol","send","composeSignals$1","signals","controller","AbortController","reason","streamChunk","chunk","chunkSize","byteLength","end","pos","readStream","async","stream","asyncIterator","reader","getReader","trackStream","onProgress","onFinish","iterable","readBytes","_onFinish","ReadableStream","close","loadedBytes","enqueue","return","highWaterMark","isFetchSupported","fetch","Request","Response","isReadableStreamSupported","encodeText","TextEncoder","arrayBuffer","supportsRequestStream","duplexAccessed","hasContentType","body","duplex","supportsResponseStream","resolvers","res","_","ERR_NOT_SUPPORT","resolveBodyLength","getContentLength","_request","getBodyLength","knownAdapters","http","xhr","fetchOptions","composedSignal","composeSignals","toAbortSignal","requestContentLength","contentTypeHeader","flush","isCredentialsSupported","credentials","isStreamResponse","responseContentLength","responseData","renderReason","isResolvedHandle","adapters","nameOrAdapter","rejectedReasons","reasons","state","throwIfCancellationRequested","throwIfRequested","dispatchRequest","validators","deprecatedWarnings","validator","version","formatMessage","opt","desc","opts","ERR_DEPRECATED","console","warn","spelling","correctSpelling","assertOptions","schema","allowUnknown","ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","Axios","instanceConfig","interceptors","InterceptorManager","configOrUrl","dummy","boolean","function","baseUrl","withXsrfToken","contextHeaders","requestInterceptorChain","synchronousRequestInterceptors","interceptor","unshift","responseInterceptorChain","promise","chain","onFulfilled","onRejected","getUri","generateHTTPMethod","isForm","Axios$2","CancelToken","executor","resolvePromise","_listeners","onfulfilled","_resolve","splice","c","CancelToken$2","HttpStatusCode","Continue","SwitchingProtocols","Processing","EarlyHints","Ok","Created","Accepted","NonAuthoritativeInformation","NoContent","ResetContent","PartialContent","MultiStatus","AlreadyReported","ImUsed","MultipleChoices","MovedPermanently","Found","SeeOther","NotModified","UseProxy","Unused","TemporaryRedirect","PermanentRedirect","BadRequest","Unauthorized","PaymentRequired","Forbidden","NotFound","MethodNotAllowed","NotAcceptable","ProxyAuthenticationRequired","RequestTimeout","Conflict","Gone","LengthRequired","PreconditionFailed","PayloadTooLarge","UriTooLong","UnsupportedMediaType","RangeNotSatisfiable","ExpectationFailed","ImATeapot","MisdirectedRequest","UnprocessableEntity","Locked","FailedDependency","TooEarly","UpgradeRequired","PreconditionRequired","TooManyRequests","RequestHeaderFieldsTooLarge","UnavailableForLegalReasons","InternalServerError","NotImplemented","BadGateway","ServiceUnavailable","GatewayTimeout","HttpVersionNotSupported","VariantAlsoNegotiates","InsufficientStorage","LoopDetected","NotExtended","NetworkAuthenticationRequired","HttpStatusCode$2","axios","createInstance","defaultConfig","instance","VERSION","Cancel","all","promises","spread","callback","isAxiosError","payload","formToJSON","getAdapter","default","axios$1"],"mappings":"AAEe,SAASA,EAAKC,EAAIC,GAC/B,OAAO,WACL,OAAOD,EAAGE,MAAMD,EAASE,UAC7B,CACA,CCAA,MAAMC,SAACA,GAAYC,OAAOC,WACpBC,eAACA,GAAkBF,OAEnBG,GAAUC,EAGbJ,OAAOK,OAAO,MAHQC,IACrB,MAAMC,EAAMR,EAASS,KAAKF,GAC1B,OAAOF,EAAMG,KAASH,EAAMG,GAAOA,EAAIE,MAAM,GAAI,GAAGC,cAAc,GAFvD,IAACN,EAKhB,MAAMO,EAAcC,IAClBA,EAAOA,EAAKF,cACJJ,GAAUH,EAAOG,KAAWM,GAGhCC,EAAaD,GAAQN,UAAgBA,IAAUM,GAS/CE,QAACA,GAAWC,MASZC,EAAcH,EAAW,aAqB/B,MAAMI,EAAgBN,EAAW,eA2BjC,MAAMO,EAAWL,EAAW,UAQtBM,EAAaN,EAAW,YASxBO,EAAWP,EAAW,UAStBQ,EAAYf,GAAoB,OAAVA,GAAmC,iBAAVA,EAiB/CgB,EAAiBC,IACrB,GAAoB,WAAhBpB,EAAOoB,GACT,OAAO,EAGT,MAAMtB,EAAYC,EAAeqB,GACjC,QAAsB,OAAdtB,GAAsBA,IAAcD,OAAOC,WAAkD,OAArCD,OAAOE,eAAeD,IAA0BuB,OAAOC,eAAeF,GAAUC,OAAOE,YAAYH,EAAI,EAUnKI,EAAShB,EAAW,QASpBiB,EAASjB,EAAW,QASpBkB,EAASlB,EAAW,QASpBmB,EAAanB,EAAW,YAsCxBoB,EAAoBpB,EAAW,oBAE9BqB,EAAkBC,EAAWC,EAAYC,GAAa,CAAC,iBAAkB,UAAW,WAAY,WAAWC,IAAIzB,GA2BtH,SAAS0B,EAAQC,EAAK3C,GAAI4C,WAACA,GAAa,GAAS,IAE/C,GAAID,QACF,OAGF,IAAIE,EACAC,EAQJ,GALmB,iBAARH,IAETA,EAAM,CAACA,IAGLxB,EAAQwB,GAEV,IAAKE,EAAI,EAAGC,EAAIH,EAAII,OAAQF,EAAIC,EAAGD,IACjC7C,EAAGa,KAAK,KAAM8B,EAAIE,GAAIA,EAAGF,OAEtB,CAEL,MAAMK,EAAOJ,EAAavC,OAAO4C,oBAAoBN,GAAOtC,OAAO2C,KAAKL,GAClEO,EAAMF,EAAKD,OACjB,IAAII,EAEJ,IAAKN,EAAI,EAAGA,EAAIK,EAAKL,IACnBM,EAAMH,EAAKH,GACX7C,EAAGa,KAAK,KAAM8B,EAAIQ,GAAMA,EAAKR,EAEhC,CACH,CAEA,SAASS,EAAQT,EAAKQ,GACpBA,EAAMA,EAAIpC,cACV,MAAMiC,EAAO3C,OAAO2C,KAAKL,GACzB,IACIU,EADAR,EAAIG,EAAKD,OAEb,KAAOF,KAAM,GAEX,GADAQ,EAAOL,EAAKH,GACRM,IAAQE,EAAKtC,cACf,OAAOsC,EAGX,OAAO,IACT,CAEA,MAAMC,EAEsB,oBAAfC,WAAmCA,WACvB,oBAATC,KAAuBA,KAA0B,oBAAXC,OAAyBA,OAASC,OAGlFC,EAAoBC,IAAavC,EAAYuC,IAAYA,IAAYN,EAoD3E,MA8HMO,GAAgBC,EAKG,oBAAfC,YAA8BxD,EAAewD,YAH9CpD,GACEmD,GAAcnD,aAAiBmD,GAHrB,IAACA,EAetB,MAiCME,EAAahD,EAAW,mBAWxBiD,EAAiB,GAAGA,oBAAoB,CAACtB,EAAKuB,IAASD,EAAepD,KAAK8B,EAAKuB,GAA/D,CAAsE7D,OAAOC,WAS9F6D,EAAWnD,EAAW,UAEtBoD,EAAoB,CAACzB,EAAK0B,KAC9B,MAAMC,EAAcjE,OAAOkE,0BAA0B5B,GAC/C6B,EAAqB,CAAA,EAE3B9B,EAAQ4B,GAAa,CAACG,EAAYC,KAChC,IAAIC,GAC2C,KAA1CA,EAAMN,EAAQI,EAAYC,EAAM/B,MACnC6B,EAAmBE,GAAQC,GAAOF,EACnC,IAGHpE,OAAOuE,iBAAiBjC,EAAK6B,EAAmB,EAsD5CK,EAAQ,6BAIRC,EAAW,CACfC,MAHY,aAIZF,QACAG,YAAaH,EAAQA,EAAMI,cALf,cA6Bd,MA+BMC,EAAYlE,EAAW,iBAQvBmE,GAAkBC,EAkBE,mBAAjBC,aAlBsCC,EAmB7C9D,EAAW8B,EAAQiC,aAlBfH,EACKC,aAGFC,GAAyBE,EAW7B,SAASC,KAAKC,WAXsBC,EAWV,GAV3BrC,EAAQsC,iBAAiB,WAAW,EAAEC,SAAQC,WACxCD,IAAWvC,GAAWwC,IAASN,GACjCG,EAAU5C,QAAU4C,EAAUI,OAAVJ,EACrB,IACA,GAEKK,IACNL,EAAUM,KAAKD,GACf1C,EAAQiC,YAAYC,EAAO,IAAI,GAECQ,GAAOE,WAAWF,IAhBlC,IAAEZ,EAAuBE,EAKbE,EAAOG,EAiBzC,MAAMQ,EAAiC,oBAAnBC,eAClBA,eAAerG,KAAKuD,GAAgC,oBAAZ+C,SAA2BA,QAAQC,UAAYnB,EAI1EoB,EAAA,CACbpF,UACAG,gBACAkF,SAlpBF,SAAkB5E,GAChB,OAAe,OAARA,IAAiBP,EAAYO,IAA4B,OAApBA,EAAI6E,cAAyBpF,EAAYO,EAAI6E,cACpFjF,EAAWI,EAAI6E,YAAYD,WAAa5E,EAAI6E,YAAYD,SAAS5E,EACxE,EAgpBE8E,WApgBkB/F,IAClB,IAAIgG,EACJ,OAAOhG,IACgB,mBAAbiG,UAA2BjG,aAAiBiG,UAClDpF,EAAWb,EAAMkG,UACY,cAA1BF,EAAOnG,EAAOG,KAEL,WAATgG,GAAqBnF,EAAWb,EAAMP,WAAkC,sBAArBO,EAAMP,YAG/D,EA2fD0G,kBA9nBF,SAA2BlF,GACzB,IAAImF,EAMJ,OAJEA,EAD0B,oBAAhBC,aAAiCA,YAAkB,OACpDA,YAAYC,OAAOrF,GAEnB,GAAUA,EAAU,QAAMN,EAAcM,EAAIsF,QAEhDH,CACT,EAunBExF,WACAE,WACA0F,UA9kBgBxG,IAAmB,IAAVA,IAA4B,IAAVA,EA+kB3Ce,WACAC,gBACAU,mBACAC,YACAC,aACAC,YACAnB,cACAW,SACAC,SACAC,SACAiC,WACA3C,aACA4F,SA9hBgBxF,GAAQF,EAASE,IAAQJ,EAAWI,EAAIyF,MA+hBxDjF,oBACAyB,eACA1B,aACAO,UACA4E,MAhaF,SAASA,IACP,MAAMC,SAACA,GAAY5D,EAAiB6D,OAASA,MAAQ,GAC/CT,EAAS,CAAA,EACTU,EAAc,CAAC7F,EAAKuB,KACxB,MAAMuE,EAAYH,GAAYnE,EAAQ2D,EAAQ5D,IAAQA,EAClDxB,EAAcoF,EAAOW,KAAe/F,EAAcC,GACpDmF,EAAOW,GAAaJ,EAAMP,EAAOW,GAAY9F,GACpCD,EAAcC,GACvBmF,EAAOW,GAAaJ,EAAM,CAAE,EAAE1F,GACrBT,EAAQS,GACjBmF,EAAOW,GAAa9F,EAAId,QAExBiG,EAAOW,GAAa9F,CACrB,EAGH,IAAK,IAAIiB,EAAI,EAAGC,EAAI3C,UAAU4C,OAAQF,EAAIC,EAAGD,IAC3C1C,UAAU0C,IAAMH,EAAQvC,UAAU0C,GAAI4E,GAExC,OAAOV,CACT,EA6YEY,OAjYa,CAACC,EAAGC,EAAG5H,GAAU2C,cAAa,MAC3CF,EAAQmF,GAAG,CAACjG,EAAKuB,KACXlD,GAAWuB,EAAWI,GACxBgG,EAAEzE,GAAOpD,EAAK6B,EAAK3B,GAEnB2H,EAAEzE,GAAOvB,CACV,GACA,CAACgB,eACGgF,GA0XPE,KA7fYlH,GAAQA,EAAIkH,KACxBlH,EAAIkH,OAASlH,EAAImH,QAAQ,qCAAsC,IA6f/DC,SAjXgBC,IACc,QAA1BA,EAAQC,WAAW,KACrBD,EAAUA,EAAQnH,MAAM,IAEnBmH,GA8WPE,SAlWe,CAAC1B,EAAa2B,EAAkBC,EAAO/D,KACtDmC,EAAYnG,UAAYD,OAAOK,OAAO0H,EAAiB9H,UAAWgE,GAClEmC,EAAYnG,UAAUmG,YAAcA,EACpCpG,OAAOiI,eAAe7B,EAAa,QAAS,CAC1C8B,MAAOH,EAAiB9H,YAE1B+H,GAAShI,OAAOmI,OAAO/B,EAAYnG,UAAW+H,EAAM,EA6VpDI,aAjVmB,CAACC,EAAWC,EAASC,EAAQC,KAChD,IAAIR,EACAxF,EACAqB,EACJ,MAAM4E,EAAS,CAAA,EAIf,GAFAH,EAAUA,GAAW,GAEJ,MAAbD,EAAmB,OAAOC,EAE9B,EAAG,CAGD,IAFAN,EAAQhI,OAAO4C,oBAAoByF,GACnC7F,EAAIwF,EAAMtF,OACHF,KAAM,GACXqB,EAAOmE,EAAMxF,GACPgG,IAAcA,EAAW3E,EAAMwE,EAAWC,IAAcG,EAAO5E,KACnEyE,EAAQzE,GAAQwE,EAAUxE,GAC1B4E,EAAO5E,IAAQ,GAGnBwE,GAAuB,IAAXE,GAAoBrI,EAAemI,EACnD,OAAWA,KAAeE,GAAUA,EAAOF,EAAWC,KAAaD,IAAcrI,OAAOC,WAEtF,OAAOqI,CAAO,EA2TdnI,SACAQ,aACA+H,SAjTe,CAACnI,EAAKoI,EAAcC,KACnCrI,EAAMsI,OAAOtI,SACIuI,IAAbF,GAA0BA,EAAWrI,EAAImC,UAC3CkG,EAAWrI,EAAImC,QAEjBkG,GAAYD,EAAajG,OACzB,MAAMqG,EAAYxI,EAAIyI,QAAQL,EAAcC,GAC5C,OAAsB,IAAfG,GAAoBA,IAAcH,CAAQ,EA2SjDK,QAhSe3I,IACf,IAAKA,EAAO,OAAO,KACnB,GAAIQ,EAAQR,GAAQ,OAAOA,EAC3B,IAAIkC,EAAIlC,EAAMoC,OACd,IAAKtB,EAASoB,GAAI,OAAO,KACzB,MAAM0G,EAAM,IAAInI,MAAMyB,GACtB,KAAOA,KAAM,GACX0G,EAAI1G,GAAKlC,EAAMkC,GAEjB,OAAO0G,CAAG,EAwRVC,aA7PmB,CAAC7G,EAAK3C,KACzB,MAEM+B,GAFYY,GAAOA,EAAId,OAAOE,WAETlB,KAAK8B,GAEhC,IAAIoE,EAEJ,MAAQA,EAAShF,EAAS0H,UAAY1C,EAAO2C,MAAM,CACjD,MAAMC,EAAO5C,EAAOwB,MACpBvI,EAAGa,KAAK8B,EAAKgH,EAAK,GAAIA,EAAK,GAC5B,GAoPDC,SAzOe,CAACC,EAAQjJ,KACxB,IAAIkJ,EACJ,MAAMP,EAAM,GAEZ,KAAwC,QAAhCO,EAAUD,EAAOE,KAAKnJ,KAC5B2I,EAAItD,KAAK6D,GAGX,OAAOP,CAAG,EAkOVvF,aACAC,iBACA+F,WAAY/F,EACZG,oBACA6F,cAzLqBtH,IACrByB,EAAkBzB,GAAK,CAAC8B,EAAYC,KAElC,GAAIlD,EAAWmB,KAA6D,IAArD,CAAC,YAAa,SAAU,UAAU0G,QAAQ3E,GAC/D,OAAO,EAGT,MAAM6D,EAAQ5F,EAAI+B,GAEblD,EAAW+G,KAEhB9D,EAAWyF,YAAa,EAEpB,aAAczF,EAChBA,EAAW0F,UAAW,EAInB1F,EAAW2F,MACd3F,EAAW2F,IAAM,KACf,MAAMC,MAAM,qCAAwC3F,EAAO,IAAK,GAEnE,GACD,EAmKF4F,YAhKkB,CAACC,EAAeC,KAClC,MAAM7H,EAAM,CAAA,EAEN8H,EAAUlB,IACdA,EAAI7G,SAAQ6F,IACV5F,EAAI4F,IAAS,CAAI,GACjB,EAKJ,OAFApH,EAAQoJ,GAAiBE,EAAOF,GAAiBE,EAAOvB,OAAOqB,GAAeG,MAAMF,IAE7E7H,CAAG,EAsJVgI,YAlOkB/J,GACXA,EAAIG,cAAcgH,QAAQ,yBAC/B,SAAkB6C,EAAGC,EAAIC,GACvB,OAAOD,EAAG5F,cAAgB6F,CAC3B,IA+NHC,KApJW,OAqJXC,eAnJqB,CAACzC,EAAO0C,IACb,MAAT1C,GAAiB2C,OAAOC,SAAS5C,GAASA,GAASA,EAAQ0C,EAmJlE7H,UACAM,OAAQJ,EACRK,mBACAmB,WACAsG,eA1IqB,CAACC,EAAO,GAAIC,EAAWxG,EAASE,eACrD,IAAIpE,EAAM,GACV,MAAMmC,OAACA,GAAUuI,EACjB,KAAOD,KACLzK,GAAO0K,EAAS7F,KAAKC,SAAW3C,EAAO,GAGzC,OAAOnC,CAAG,EAoIV2K,oBA1HF,SAA6B5K,GAC3B,SAAUA,GAASa,EAAWb,EAAMkG,SAAyC,aAA9BlG,EAAMkB,OAAOC,cAA+BnB,EAAMkB,OAAOE,UAC1G,EAyHEyJ,aAvHoB7I,IACpB,MAAM8I,EAAQ,IAAIrK,MAAM,IAElBsK,EAAQ,CAAC7F,EAAQhD,KAErB,GAAInB,EAASmE,GAAS,CACpB,GAAI4F,EAAMpC,QAAQxD,IAAW,EAC3B,OAGF,KAAK,WAAYA,GAAS,CACxB4F,EAAM5I,GAAKgD,EACX,MAAM8F,EAASxK,EAAQ0E,GAAU,GAAK,CAAA,EAStC,OAPAnD,EAAQmD,GAAQ,CAAC0C,EAAOpF,KACtB,MAAMyI,EAAeF,EAAMnD,EAAO1F,EAAI,IACrCxB,EAAYuK,KAAkBD,EAAOxI,GAAOyI,EAAa,IAG5DH,EAAM5I,QAAKsG,EAEJwC,CACR,CACF,CAED,OAAO9F,CAAM,EAGf,OAAO6F,EAAM/I,EAAK,EAAE,EA4FpBuC,YACA2G,WAxFkBlL,GAClBA,IAAUe,EAASf,IAAUa,EAAWb,KAAWa,EAAWb,EAAMmL,OAAStK,EAAWb,EAAMoL,OAwF9F1G,aAAcF,EACdgB,QCvuBF,SAAS6F,EAAWC,EAASC,EAAMC,EAAQC,EAASC,GAClDhC,MAAMxJ,KAAK2G,MAEP6C,MAAMiC,kBACRjC,MAAMiC,kBAAkB9E,KAAMA,KAAKf,aAEnCe,KAAKiE,OAAQ,IAAKpB,OAASoB,MAG7BjE,KAAKyE,QAAUA,EACfzE,KAAK9C,KAAO,aACZwH,IAAS1E,KAAK0E,KAAOA,GACrBC,IAAW3E,KAAK2E,OAASA,GACzBC,IAAY5E,KAAK4E,QAAUA,GACvBC,IACF7E,KAAK6E,SAAWA,EAChB7E,KAAK+E,OAASF,EAASE,OAASF,EAASE,OAAS,KAEtD,CAEAC,EAAMrE,SAAS6D,EAAY3B,MAAO,CAChCoC,OAAQ,WACN,MAAO,CAELR,QAASzE,KAAKyE,QACdvH,KAAM8C,KAAK9C,KAEXgI,YAAalF,KAAKkF,YAClBC,OAAQnF,KAAKmF,OAEbC,SAAUpF,KAAKoF,SACfC,WAAYrF,KAAKqF,WACjBC,aAActF,KAAKsF,aACnBrB,MAAOjE,KAAKiE,MAEZU,OAAQK,EAAMhB,aAAahE,KAAK2E,QAChCD,KAAM1E,KAAK0E,KACXK,OAAQ/E,KAAK+E,OAEhB,IAGH,MAAMjM,EAAY0L,EAAW1L,UACvBgE,EAAc,CAAA,EAEpB,CACE,uBACA,iBACA,eACA,YACA,cACA,4BACA,iBACA,mBACA,kBACA,eACA,kBACA,mBAEA5B,SAAQwJ,IACR5H,EAAY4H,GAAQ,CAAC3D,MAAO2D,EAAK,IAGnC7L,OAAOuE,iBAAiBoH,EAAY1H,GACpCjE,OAAOiI,eAAehI,EAAW,eAAgB,CAACiI,OAAO,IAGzDyD,EAAWe,KAAO,CAACC,EAAOd,EAAMC,EAAQC,EAASC,EAAUY,KACzD,MAAMC,EAAa7M,OAAOK,OAAOJ,GAgBjC,OAdAkM,EAAM/D,aAAauE,EAAOE,GAAY,SAAgBvK,GACpD,OAAOA,IAAQ0H,MAAM/J,SACtB,IAAE4D,GACe,iBAATA,IAGT8H,EAAWnL,KAAKqM,EAAYF,EAAMf,QAASC,EAAMC,EAAQC,EAASC,GAElEa,EAAWC,MAAQH,EAEnBE,EAAWxI,KAAOsI,EAAMtI,KAExBuI,GAAe5M,OAAOmI,OAAO0E,EAAYD,GAElCC,CAAU,ECrFnB,SAASE,EAAYzM,GACnB,OAAO6L,EAAM7K,cAAchB,IAAU6L,EAAMrL,QAAQR,EACrD,CASA,SAAS0M,EAAelK,GACtB,OAAOqJ,EAAMzD,SAAS5F,EAAK,MAAQA,EAAIrC,MAAM,GAAI,GAAKqC,CACxD,CAWA,SAASmK,EAAUC,EAAMpK,EAAKqK,GAC5B,OAAKD,EACEA,EAAKE,OAAOtK,GAAKV,KAAI,SAAc+C,EAAO3C,GAG/C,OADA2C,EAAQ6H,EAAe7H,IACfgI,GAAQ3K,EAAI,IAAM2C,EAAQ,IAAMA,CACzC,IAAEkI,KAAKF,EAAO,IAAM,IALHrK,CAMpB,CAaA,MAAMwK,EAAanB,EAAM/D,aAAa+D,EAAO,CAAE,EAAE,MAAM,SAAgBtI,GACrE,MAAO,WAAW0J,KAAK1J,EACzB,IAyBA,SAAS2J,EAAWlL,EAAKmL,EAAUC,GACjC,IAAKvB,EAAM9K,SAASiB,GAClB,MAAM,IAAIqL,UAAU,4BAItBF,EAAWA,GAAY,IAAyB,SAYhD,MAAMG,GATNF,EAAUvB,EAAM/D,aAAasF,EAAS,CACpCE,YAAY,EACZT,MAAM,EACNU,SAAS,IACR,GAAO,SAAiBC,EAAQtI,GAEjC,OAAQ2G,EAAMnL,YAAYwE,EAAOsI,GACrC,KAE6BF,WAErBG,EAAUL,EAAQK,SAAWC,EAC7Bb,EAAOO,EAAQP,KACfU,EAAUH,EAAQG,QAElBI,GADQP,EAAQQ,MAAwB,oBAATA,MAAwBA,OACpC/B,EAAMjB,oBAAoBuC,GAEnD,IAAKtB,EAAMhL,WAAW4M,GACpB,MAAM,IAAIJ,UAAU,8BAGtB,SAASQ,EAAajG,GACpB,GAAc,OAAVA,EAAgB,MAAO,GAE3B,GAAIiE,EAAMxK,OAAOuG,GACf,OAAOA,EAAMkG,cAGf,IAAKH,GAAW9B,EAAMtK,OAAOqG,GAC3B,MAAM,IAAIyD,EAAW,gDAGvB,OAAIQ,EAAMlL,cAAciH,IAAUiE,EAAM3I,aAAa0E,GAC5C+F,GAA2B,mBAATC,KAAsB,IAAIA,KAAK,CAAChG,IAAUmG,OAAO3B,KAAKxE,GAG1EA,CACR,CAYD,SAAS8F,EAAe9F,EAAOpF,EAAKoK,GAClC,IAAIhE,EAAMhB,EAEV,GAAIA,IAAUgF,GAAyB,iBAAVhF,EAC3B,GAAIiE,EAAMzD,SAAS5F,EAAK,MAEtBA,EAAM8K,EAAa9K,EAAMA,EAAIrC,MAAM,GAAI,GAEvCyH,EAAQoG,KAAKC,UAAUrG,QAClB,GACJiE,EAAMrL,QAAQoH,IAnGvB,SAAqBgB,GACnB,OAAOiD,EAAMrL,QAAQoI,KAASA,EAAIsF,KAAKzB,EACzC,CAiGiC0B,CAAYvG,KACnCiE,EAAMrK,WAAWoG,IAAUiE,EAAMzD,SAAS5F,EAAK,SAAWoG,EAAMiD,EAAMlD,QAAQf,IAYhF,OATApF,EAAMkK,EAAelK,GAErBoG,EAAI7G,SAAQ,SAAcqM,EAAIC,IAC1BxC,EAAMnL,YAAY0N,IAAc,OAAPA,GAAgBjB,EAASjH,QAEtC,IAAZqH,EAAmBZ,EAAU,CAACnK,GAAM6L,EAAOxB,GAAqB,OAAZU,EAAmB/K,EAAMA,EAAM,KACnFqL,EAAaO,GAEzB,KACe,EAIX,QAAI3B,EAAY7E,KAIhBuF,EAASjH,OAAOyG,EAAUC,EAAMpK,EAAKqK,GAAOgB,EAAajG,KAElD,EACR,CAED,MAAMkD,EAAQ,GAERwD,EAAiB5O,OAAOmI,OAAOmF,EAAY,CAC/CU,iBACAG,eACApB,gBAyBF,IAAKZ,EAAM9K,SAASiB,GAClB,MAAM,IAAIqL,UAAU,0BAKtB,OA5BA,SAASkB,EAAM3G,EAAOgF,GACpB,IAAIf,EAAMnL,YAAYkH,GAAtB,CAEA,IAA8B,IAA1BkD,EAAMpC,QAAQd,GAChB,MAAM8B,MAAM,kCAAoCkD,EAAKG,KAAK,MAG5DjC,EAAMxF,KAAKsC,GAEXiE,EAAM9J,QAAQ6F,GAAO,SAAcwG,EAAI5L,IAKtB,OAJEqJ,EAAMnL,YAAY0N,IAAc,OAAPA,IAAgBX,EAAQvN,KAChEiN,EAAUiB,EAAIvC,EAAMjL,SAAS4B,GAAOA,EAAI2E,OAAS3E,EAAKoK,EAAM0B,KAI5DC,EAAMH,EAAIxB,EAAOA,EAAKE,OAAOtK,GAAO,CAACA,GAE7C,IAEIsI,EAAM0D,KAlB+B,CAmBtC,CAMDD,CAAMvM,GAECmL,CACT,CC5MA,SAASsB,EAAOxO,GACd,MAAMyO,EAAU,CACd,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,MAAO,IACP,MAAO,MAET,OAAOC,mBAAmB1O,GAAKmH,QAAQ,oBAAoB,SAAkBwH,GAC3E,OAAOF,EAAQE,EACnB,GACA,CAUA,SAASC,EAAqBC,EAAQ1B,GACpCvG,KAAKkI,OAAS,GAEdD,GAAU5B,EAAW4B,EAAQjI,KAAMuG,EACrC,CAEA,MAAMzN,GAAYkP,EAAqBlP,UC5BvC,SAAS8O,GAAOxN,GACd,OAAO0N,mBAAmB1N,GACxBmG,QAAQ,QAAS,KACjBA,QAAQ,OAAQ,KAChBA,QAAQ,QAAS,KACjBA,QAAQ,OAAQ,KAChBA,QAAQ,QAAS,KACjBA,QAAQ,QAAS,IACrB,CAWe,SAAS4H,GAASC,EAAKH,EAAQ1B,GAE5C,IAAK0B,EACH,OAAOG,EAGT,MAAMC,EAAU9B,GAAWA,EAAQqB,QAAUA,GAEzC5C,EAAMhL,WAAWuM,KACnBA,EAAU,CACR+B,UAAW/B,IAIf,MAAMgC,EAAchC,GAAWA,EAAQ+B,UAEvC,IAAIE,EAUJ,GAPEA,EADED,EACiBA,EAAYN,EAAQ1B,GAEpBvB,EAAMpK,kBAAkBqN,GACzCA,EAAOrP,WACP,IAAIoP,EAAqBC,EAAQ1B,GAAS3N,SAASyP,GAGnDG,EAAkB,CACpB,MAAMC,EAAgBL,EAAIvG,QAAQ,MAEX,IAAnB4G,IACFL,EAAMA,EAAI9O,MAAM,EAAGmP,IAErBL,KAA8B,IAAtBA,EAAIvG,QAAQ,KAAc,IAAM,KAAO2G,CAChD,CAED,OAAOJ,CACT,CDzBAtP,GAAUuG,OAAS,SAAgBnC,EAAM6D,GACvCf,KAAKkI,OAAOzJ,KAAK,CAACvB,EAAM6D,GAC1B,EAEAjI,GAAUF,SAAW,SAAkB8P,GACrC,MAAML,EAAUK,EAAU,SAAS3H,GACjC,OAAO2H,EAAQrP,KAAK2G,KAAMe,EAAO6G,EAClC,EAAGA,EAEJ,OAAO5H,KAAKkI,OAAOjN,KAAI,SAAckH,GACnC,OAAOkG,EAAQlG,EAAK,IAAM,IAAMkG,EAAQlG,EAAK,GAC9C,GAAE,IAAI+D,KAAK,IACd,EEeA,MAAAyC,GAlEA,MACE1J,cACEe,KAAK4I,SAAW,EACjB,CAUDC,IAAIC,EAAWC,EAAUxC,GAOvB,OANAvG,KAAK4I,SAASnK,KAAK,CACjBqK,YACAC,WACAC,cAAazC,GAAUA,EAAQyC,YAC/BC,QAAS1C,EAAUA,EAAQ0C,QAAU,OAEhCjJ,KAAK4I,SAASrN,OAAS,CAC/B,CASD2N,MAAMC,GACAnJ,KAAK4I,SAASO,KAChBnJ,KAAK4I,SAASO,GAAM,KAEvB,CAODC,QACMpJ,KAAK4I,WACP5I,KAAK4I,SAAW,GAEnB,CAYD1N,QAAQ1C,GACNwM,EAAM9J,QAAQ8E,KAAK4I,UAAU,SAAwBS,GACzC,OAANA,GACF7Q,EAAG6Q,EAEX,GACG,GCjEYC,GAAA,CACbC,mBAAmB,EACnBC,mBAAmB,EACnBC,qBAAqB,GCDRC,GAAA,CACbC,WAAW,EACXC,QAAS,CACXC,gBCJ0C,oBAApBA,gBAAkCA,gBAAkB7B,EDK1E5I,SENmC,oBAAbA,SAA2BA,SAAW,KFO5D2H,KGP+B,oBAATA,KAAuBA,KAAO,MHSlD+C,UAAW,CAAC,OAAQ,QAAS,OAAQ,OAAQ,MAAO,SIXhDC,GAAkC,oBAAX9N,QAA8C,oBAAb+N,SAExDC,GAAkC,iBAAdC,WAA0BA,gBAAavI,EAmB3DwI,GAAwBJ,MAC1BE,IAAc,CAAC,cAAe,eAAgB,MAAMpI,QAAQoI,GAAWG,SAAW,GAWhFC,GAE2B,oBAAtBC,mBAEPtO,gBAAgBsO,mBACc,mBAAvBtO,KAAKuO,cAIVC,GAAST,IAAiB9N,OAAOwO,SAASC,MAAQ,mBCvCzCC,GAAA,0IAEVA,IC2CL,SAASC,GAAetE,GACtB,SAASuE,EAAU9E,EAAMhF,EAAOoD,EAAQqD,GACtC,IAAItK,EAAO6I,EAAKyB,KAEhB,GAAa,cAATtK,EAAsB,OAAO,EAEjC,MAAM4N,EAAepH,OAAOC,UAAUzG,GAChC6N,EAASvD,GAASzB,EAAKxK,OAG7B,GAFA2B,GAAQA,GAAQ8H,EAAMrL,QAAQwK,GAAUA,EAAO5I,OAAS2B,EAEpD6N,EAOF,OANI/F,EAAMxC,WAAW2B,EAAQjH,GAC3BiH,EAAOjH,GAAQ,CAACiH,EAAOjH,GAAO6D,GAE9BoD,EAAOjH,GAAQ6D,GAGT+J,EAGL3G,EAAOjH,IAAU8H,EAAM9K,SAASiK,EAAOjH,MAC1CiH,EAAOjH,GAAQ,IASjB,OANe2N,EAAU9E,EAAMhF,EAAOoD,EAAOjH,GAAOsK,IAEtCxC,EAAMrL,QAAQwK,EAAOjH,MACjCiH,EAAOjH,GA/Cb,SAAuB6E,GACrB,MAAM5G,EAAM,CAAA,EACNK,EAAO3C,OAAO2C,KAAKuG,GACzB,IAAI1G,EACJ,MAAMK,EAAMF,EAAKD,OACjB,IAAII,EACJ,IAAKN,EAAI,EAAGA,EAAIK,EAAKL,IACnBM,EAAMH,EAAKH,GACXF,EAAIQ,GAAOoG,EAAIpG,GAEjB,OAAOR,CACT,CAoCqB6P,CAAc7G,EAAOjH,MAG9B4N,CACT,CAED,GAAI9F,EAAM9F,WAAWoH,IAAatB,EAAMhL,WAAWsM,EAAS2E,SAAU,CACpE,MAAM9P,EAAM,CAAA,EAMZ,OAJA6J,EAAMhD,aAAasE,GAAU,CAACpJ,EAAM6D,KAClC8J,EA1EN,SAAuB3N,GAKrB,OAAO8H,EAAM5C,SAAS,gBAAiBlF,GAAMjC,KAAI8M,GAC3B,OAAbA,EAAM,GAAc,GAAKA,EAAM,IAAMA,EAAM,IAEtD,CAkEgBmD,CAAchO,GAAO6D,EAAO5F,EAAK,EAAE,IAGxCA,CACR,CAED,OAAO,IACT,CCzDA,MAAMgQ,GAAW,CAEfC,aAAc9B,GAEd+B,QAAS,CAAC,MAAO,OAAQ,SAEzBC,iBAAkB,CAAC,SAA0BhN,EAAMiN,GACjD,MAAMC,EAAcD,EAAQE,kBAAoB,GAC1CC,EAAqBF,EAAY3J,QAAQ,qBAAuB,EAChE8J,EAAkB3G,EAAM9K,SAASoE,GAEnCqN,GAAmB3G,EAAMxI,WAAW8B,KACtCA,EAAO,IAAIc,SAASd,IAKtB,GAFmB0G,EAAM9F,WAAWZ,GAGlC,OAAOoN,EAAqBvE,KAAKC,UAAUwD,GAAetM,IAASA,EAGrE,GAAI0G,EAAMlL,cAAcwE,IACtB0G,EAAMhG,SAASV,IACf0G,EAAMpF,SAAStB,IACf0G,EAAMvK,OAAO6D,IACb0G,EAAMtK,OAAO4D,IACb0G,EAAMnK,iBAAiByD,GAEvB,OAAOA,EAET,GAAI0G,EAAM1F,kBAAkBhB,GAC1B,OAAOA,EAAKoB,OAEd,GAAIsF,EAAMpK,kBAAkB0D,GAE1B,OADAiN,EAAQK,eAAe,mDAAmD,GACnEtN,EAAK1F,WAGd,IAAI+B,EAEJ,GAAIgR,EAAiB,CACnB,GAAIH,EAAY3J,QAAQ,sCAAwC,EAC9D,OCvEO,SAA0BvD,EAAMiI,GAC7C,OAAOF,EAAW/H,EAAM,IAAIqM,GAASf,QAAQC,gBAAmBhR,OAAOmI,OAAO,CAC5E4F,QAAS,SAAS7F,EAAOpF,EAAKoK,EAAM8F,GAClC,OAAIlB,GAASmB,QAAU9G,EAAMhG,SAAS+B,IACpCf,KAAKX,OAAO1D,EAAKoF,EAAMnI,SAAS,YACzB,GAGFiT,EAAQhF,eAAenO,MAAMsH,KAAMrH,UAC3C,GACA4N,GACL,CD4DewF,CAAiBzN,EAAM0B,KAAKgM,gBAAgBpT,WAGrD,IAAK+B,EAAaqK,EAAMrK,WAAW2D,KAAUkN,EAAY3J,QAAQ,wBAA0B,EAAG,CAC5F,MAAMoK,EAAYjM,KAAKkM,KAAOlM,KAAKkM,IAAI9M,SAEvC,OAAOiH,EACL1L,EAAa,CAAC,UAAW2D,GAAQA,EACjC2N,GAAa,IAAIA,EACjBjM,KAAKgM,eAER,CACF,CAED,OAAIL,GAAmBD,GACrBH,EAAQK,eAAe,oBAAoB,GAxEjD,SAAyBO,EAAUC,EAAQ1D,GACzC,GAAI1D,EAAMjL,SAASoS,GACjB,IAEE,OADCC,GAAUjF,KAAKkF,OAAOF,GAChBnH,EAAM1E,KAAK6L,EAKnB,CAJC,MAAOG,GACP,GAAe,gBAAXA,EAAEpP,KACJ,MAAMoP,CAET,CAGH,OAAQ5D,GAAWvB,KAAKC,WAAW+E,EACrC,CA4DaI,CAAgBjO,IAGlBA,CACX,GAEEkO,kBAAmB,CAAC,SAA2BlO,GAC7C,MAAM8M,EAAepL,KAAKoL,cAAgBD,GAASC,aAC7C5B,EAAoB4B,GAAgBA,EAAa5B,kBACjDiD,EAAsC,SAAtBzM,KAAK0M,aAE3B,GAAI1H,EAAMjK,WAAWuD,IAAS0G,EAAMnK,iBAAiByD,GACnD,OAAOA,EAGT,GAAIA,GAAQ0G,EAAMjL,SAASuE,KAAWkL,IAAsBxJ,KAAK0M,cAAiBD,GAAgB,CAChG,MACME,IADoBvB,GAAgBA,EAAa7B,oBACPkD,EAEhD,IACE,OAAOtF,KAAKkF,MAAM/N,EAQnB,CAPC,MAAOgO,GACP,GAAIK,EAAmB,CACrB,GAAe,gBAAXL,EAAEpP,KACJ,MAAMsH,EAAWe,KAAK+G,EAAG9H,EAAWoI,iBAAkB5M,KAAM,KAAMA,KAAK6E,UAEzE,MAAMyH,CACP,CACF,CACF,CAED,OAAOhO,CACX,GAMEuO,QAAS,EAETC,eAAgB,aAChBC,eAAgB,eAEhBC,kBAAmB,EACnBC,eAAgB,EAEhBf,IAAK,CACH9M,SAAUuL,GAASf,QAAQxK,SAC3B2H,KAAM4D,GAASf,QAAQ7C,MAGzBmG,eAAgB,SAAwBnI,GACtC,OAAOA,GAAU,KAAOA,EAAS,GAClC,EAEDwG,QAAS,CACP4B,OAAQ,CACNC,OAAU,oCACV,oBAAgBzL,KAKtBqD,EAAM9J,QAAQ,CAAC,SAAU,MAAO,OAAQ,OAAQ,MAAO,UAAWmS,IAChElC,GAASI,QAAQ8B,GAAU,EAAE,IAG/B,MAAAC,GAAenC,GE1JToC,GAAoBvI,EAAMlC,YAAY,CAC1C,MAAO,gBAAiB,iBAAkB,eAAgB,OAC1D,UAAW,OAAQ,OAAQ,oBAAqB,sBAChD,gBAAiB,WAAY,eAAgB,sBAC7C,UAAW,cAAe,eCLtB0K,GAAanT,OAAO,aAE1B,SAASoT,GAAgBC,GACvB,OAAOA,GAAUhM,OAAOgM,GAAQpN,OAAO/G,aACzC,CAEA,SAASoU,GAAe5M,GACtB,OAAc,IAAVA,GAA4B,MAATA,EACdA,EAGFiE,EAAMrL,QAAQoH,GAASA,EAAM9F,IAAI0S,IAAkBjM,OAAOX,EACnE,CAgBA,SAAS6M,GAAiBxR,EAAS2E,EAAO2M,EAAQtM,EAAQyM,GACxD,OAAI7I,EAAMhL,WAAWoH,GACZA,EAAO/H,KAAK2G,KAAMe,EAAO2M,IAG9BG,IACF9M,EAAQ2M,GAGL1I,EAAMjL,SAASgH,GAEhBiE,EAAMjL,SAASqH,IACiB,IAA3BL,EAAMc,QAAQT,GAGnB4D,EAAMrI,SAASyE,GACVA,EAAOgF,KAAKrF,QADrB,OANA,EASF,CAsBA,MAAM+M,GACJ7O,YAAYsM,GACVA,GAAWvL,KAAK4C,IAAI2I,EACrB,CAED3I,IAAI8K,EAAQK,EAAgBC,GAC1B,MAAMhS,EAAOgE,KAEb,SAASiO,EAAUC,EAAQC,EAASC,GAClC,MAAMC,EAAUZ,GAAgBU,GAEhC,IAAKE,EACH,MAAM,IAAIxL,MAAM,0CAGlB,MAAMlH,EAAMqJ,EAAMpJ,QAAQI,EAAMqS,KAE5B1S,QAAqBgG,IAAd3F,EAAKL,KAAmC,IAAbyS,QAAmCzM,IAAbyM,IAAwC,IAAdpS,EAAKL,MACzFK,EAAKL,GAAOwS,GAAWR,GAAeO,GAEzC,CAED,MAAMI,EAAa,CAAC/C,EAAS6C,IAC3BpJ,EAAM9J,QAAQqQ,GAAS,CAAC2C,EAAQC,IAAYF,EAAUC,EAAQC,EAASC,KAEzE,GAAIpJ,EAAM7K,cAAcuT,IAAWA,aAAkB1N,KAAKf,YACxDqP,EAAWZ,EAAQK,QACd,GAAG/I,EAAMjL,SAAS2T,KAAYA,EAASA,EAAOpN,UArEtB,iCAAiC8F,KAqEmBsH,EArEVpN,QAsEvEgO,ED1ESC,KACb,MAAMC,EAAS,CAAA,EACf,IAAI7S,EACAvB,EACAiB,EAsBJ,OApBAkT,GAAcA,EAAWrL,MAAM,MAAMhI,SAAQ,SAAgBuT,GAC3DpT,EAAIoT,EAAK5M,QAAQ,KACjBlG,EAAM8S,EAAKC,UAAU,EAAGrT,GAAGiF,OAAO/G,cAClCa,EAAMqU,EAAKC,UAAUrT,EAAI,GAAGiF,QAEvB3E,GAAQ6S,EAAO7S,IAAQ4R,GAAkB5R,KAIlC,eAARA,EACE6S,EAAO7S,GACT6S,EAAO7S,GAAK8C,KAAKrE,GAEjBoU,EAAO7S,GAAO,CAACvB,GAGjBoU,EAAO7S,GAAO6S,EAAO7S,GAAO6S,EAAO7S,GAAO,KAAOvB,EAAMA,EAE7D,IAESoU,CAAM,ECgDEG,CAAajB,GAASK,QAC5B,GAAI/I,EAAMhK,UAAU0S,GACzB,IAAK,MAAO/R,EAAKoF,KAAU2M,EAAOzC,UAChCgD,EAAUlN,EAAOpF,EAAKqS,QAGd,MAAVN,GAAkBO,EAAUF,EAAgBL,EAAQM,GAGtD,OAAOhO,IACR,CAED4O,IAAIlB,EAAQtB,GAGV,GAFAsB,EAASD,GAAgBC,GAEb,CACV,MAAM/R,EAAMqJ,EAAMpJ,QAAQoE,KAAM0N,GAEhC,GAAI/R,EAAK,CACP,MAAMoF,EAAQf,KAAKrE,GAEnB,IAAKyQ,EACH,OAAOrL,EAGT,IAAe,IAAXqL,EACF,OA5GV,SAAqBhT,GACnB,MAAMyV,EAAShW,OAAOK,OAAO,MACvB4V,EAAW,mCACjB,IAAI/G,EAEJ,KAAQA,EAAQ+G,EAASvM,KAAKnJ,IAC5ByV,EAAO9G,EAAM,IAAMA,EAAM,GAG3B,OAAO8G,CACT,CAkGiBE,CAAYhO,GAGrB,GAAIiE,EAAMhL,WAAWoS,GACnB,OAAOA,EAAO/S,KAAK2G,KAAMe,EAAOpF,GAGlC,GAAIqJ,EAAMrI,SAASyP,GACjB,OAAOA,EAAO7J,KAAKxB,GAGrB,MAAM,IAAIyF,UAAU,yCACrB,CACF,CACF,CAEDwI,IAAItB,EAAQuB,GAGV,GAFAvB,EAASD,GAAgBC,GAEb,CACV,MAAM/R,EAAMqJ,EAAMpJ,QAAQoE,KAAM0N,GAEhC,SAAU/R,QAAqBgG,IAAd3B,KAAKrE,IAAwBsT,IAAWrB,GAAiB5N,EAAMA,KAAKrE,GAAMA,EAAKsT,GACjG,CAED,OAAO,CACR,CAEDC,OAAOxB,EAAQuB,GACb,MAAMjT,EAAOgE,KACb,IAAImP,GAAU,EAEd,SAASC,EAAajB,GAGpB,GAFAA,EAAUV,GAAgBU,GAEb,CACX,MAAMxS,EAAMqJ,EAAMpJ,QAAQI,EAAMmS,IAE5BxS,GAASsT,IAAWrB,GAAiB5R,EAAMA,EAAKL,GAAMA,EAAKsT,YACtDjT,EAAKL,GAEZwT,GAAU,EAEb,CACF,CAQD,OANInK,EAAMrL,QAAQ+T,GAChBA,EAAOxS,QAAQkU,GAEfA,EAAa1B,GAGRyB,CACR,CAED/F,MAAM6F,GACJ,MAAMzT,EAAO3C,OAAO2C,KAAKwE,MACzB,IAAI3E,EAAIG,EAAKD,OACT4T,GAAU,EAEd,KAAO9T,KAAK,CACV,MAAMM,EAAMH,EAAKH,GACb4T,IAAWrB,GAAiB5N,EAAMA,KAAKrE,GAAMA,EAAKsT,GAAS,YACtDjP,KAAKrE,GACZwT,GAAU,EAEb,CAED,OAAOA,CACR,CAEDE,UAAUC,GACR,MAAMtT,EAAOgE,KACPuL,EAAU,CAAA,EAsBhB,OApBAvG,EAAM9J,QAAQ8E,MAAM,CAACe,EAAO2M,KAC1B,MAAM/R,EAAMqJ,EAAMpJ,QAAQ2P,EAASmC,GAEnC,GAAI/R,EAGF,OAFAK,EAAKL,GAAOgS,GAAe5M,eACpB/E,EAAK0R,GAId,MAAM6B,EAAaD,EA9JzB,SAAsB5B,GACpB,OAAOA,EAAOpN,OACX/G,cAAcgH,QAAQ,mBAAmB,CAACiP,EAAGC,EAAMrW,IAC3CqW,EAAKhS,cAAgBrE,GAElC,CAyJkCsW,CAAahC,GAAUhM,OAAOgM,GAAQpN,OAE9DiP,IAAe7B,UACV1R,EAAK0R,GAGd1R,EAAKuT,GAAc5B,GAAe5M,GAElCwK,EAAQgE,IAAc,CAAI,IAGrBvP,IACR,CAEDiG,UAAU0J,GACR,OAAO3P,KAAKf,YAAYgH,OAAOjG,QAAS2P,EACzC,CAED1K,OAAO2K,GACL,MAAMzU,EAAMtC,OAAOK,OAAO,MAM1B,OAJA8L,EAAM9J,QAAQ8E,MAAM,CAACe,EAAO2M,KACjB,MAAT3M,IAA2B,IAAVA,IAAoB5F,EAAIuS,GAAUkC,GAAa5K,EAAMrL,QAAQoH,GAASA,EAAMmF,KAAK,MAAQnF,EAAM,IAG3G5F,CACR,CAED,CAACd,OAAOE,YACN,OAAO1B,OAAOoS,QAAQjL,KAAKiF,UAAU5K,OAAOE,WAC7C,CAED3B,WACE,OAAOC,OAAOoS,QAAQjL,KAAKiF,UAAUhK,KAAI,EAAEyS,EAAQ3M,KAAW2M,EAAS,KAAO3M,IAAOmF,KAAK,KAC3F,CAEW5L,IAAPD,OAAOC,eACV,MAAO,cACR,CAEDuV,YAAY1W,GACV,OAAOA,aAAiB6G,KAAO7G,EAAQ,IAAI6G,KAAK7G,EACjD,CAED0W,cAAcC,KAAUH,GACtB,MAAMI,EAAW,IAAI/P,KAAK8P,GAI1B,OAFAH,EAAQzU,SAASiJ,GAAW4L,EAASnN,IAAIuB,KAElC4L,CACR,CAEDF,gBAAgBnC,GACd,MAIMsC,GAJYhQ,KAAKwN,IAAexN,KAAKwN,IAAc,CACvDwC,UAAW,CAAE,IAGaA,UACtBlX,EAAYkH,KAAKlH,UAEvB,SAASmX,EAAe9B,GACtB,MAAME,EAAUZ,GAAgBU,GAE3B6B,EAAU3B,MAtNrB,SAAwBlT,EAAKuS,GAC3B,MAAMwC,EAAelL,EAAM7B,YAAY,IAAMuK,GAE7C,CAAC,MAAO,MAAO,OAAOxS,SAAQiV,IAC5BtX,OAAOiI,eAAe3F,EAAKgV,EAAaD,EAAc,CACpDnP,MAAO,SAASqP,EAAMC,EAAMC,GAC1B,OAAOtQ,KAAKmQ,GAAY9W,KAAK2G,KAAM0N,EAAQ0C,EAAMC,EAAMC,EACxD,EACDC,cAAc,GACd,GAEN,CA4MQC,CAAe1X,EAAWqV,GAC1B6B,EAAU3B,IAAW,EAExB,CAID,OAFArJ,EAAMrL,QAAQ+T,GAAUA,EAAOxS,QAAQ+U,GAAkBA,EAAevC,GAEjE1N,IACR,EAGH8N,GAAa2C,SAAS,CAAC,eAAgB,iBAAkB,SAAU,kBAAmB,aAAc,kBAGpGzL,EAAMpI,kBAAkBkR,GAAahV,WAAW,EAAEiI,SAAQpF,KACxD,IAAI+U,EAAS/U,EAAI,GAAG8B,cAAgB9B,EAAIrC,MAAM,GAC9C,MAAO,CACLsV,IAAK,IAAM7N,EACX6B,IAAI+N,GACF3Q,KAAK0Q,GAAUC,CAChB,EACF,IAGH3L,EAAMvC,cAAcqL,IAEpB,MAAA8C,GAAe9C,GC/RA,SAAS+C,GAAcC,EAAKjM,GACzC,MAAMF,EAAS3E,MAAQmL,GACjB/O,EAAUyI,GAAYF,EACtB4G,EAAUuC,GAAavI,KAAKnJ,EAAQmP,SAC1C,IAAIjN,EAAOlC,EAAQkC,KAQnB,OANA0G,EAAM9J,QAAQ4V,GAAK,SAAmBtY,GACpC8F,EAAO9F,EAAGa,KAAKsL,EAAQrG,EAAMiN,EAAQ8D,YAAaxK,EAAWA,EAASE,YAASpD,EACnF,IAEE4J,EAAQ8D,YAED/Q,CACT,CCzBe,SAASyS,GAAShQ,GAC/B,SAAUA,IAASA,EAAMiQ,WAC3B,CCUA,SAASC,GAAcxM,EAASE,EAAQC,GAEtCJ,EAAWnL,KAAK2G,KAAiB,MAAXyE,EAAkB,WAAaA,EAASD,EAAW0M,aAAcvM,EAAQC,GAC/F5E,KAAK9C,KAAO,eACd,CCLe,SAASiU,GAAOC,EAASC,EAAQxM,GAC9C,MAAMqI,EAAiBrI,EAASF,OAAOuI,eAClCrI,EAASE,QAAWmI,IAAkBA,EAAerI,EAASE,QAGjEsM,EAAO,IAAI7M,EACT,mCAAqCK,EAASE,OAC9C,CAACP,EAAW8M,gBAAiB9M,EAAWoI,kBAAkB3O,KAAKsT,MAAM1M,EAASE,OAAS,KAAO,GAC9FF,EAASF,OACTE,EAASD,QACTC,IAPFuM,EAAQvM,EAUZ,CDNAG,EAAMrE,SAASsQ,GAAezM,EAAY,CACxCwM,YAAY,IEjBP,MAAMQ,GAAuB,CAACC,EAAUC,EAAkBC,EAAO,KACtE,IAAIC,EAAgB,EACpB,MAAMC,ECER,SAAqBC,EAAcC,GACjCD,EAAeA,GAAgB,GAC/B,MAAME,EAAQ,IAAIpY,MAAMkY,GAClBG,EAAa,IAAIrY,MAAMkY,GAC7B,IAEII,EAFAC,EAAO,EACPC,EAAO,EAKX,OAFAL,OAAcpQ,IAARoQ,EAAoBA,EAAM,IAEzB,SAAcM,GACnB,MAAMC,EAAMC,KAAKD,MAEXE,EAAYP,EAAWG,GAExBF,IACHA,EAAgBI,GAGlBN,EAAMG,GAAQE,EACdJ,EAAWE,GAAQG,EAEnB,IAAIjX,EAAI+W,EACJK,EAAa,EAEjB,KAAOpX,IAAM8W,GACXM,GAAcT,EAAM3W,KACpBA,GAAQyW,EASV,GANAK,GAAQA,EAAO,GAAKL,EAEhBK,IAASC,IACXA,GAAQA,EAAO,GAAKN,GAGlBQ,EAAMJ,EAAgBH,EACxB,OAGF,MAAMW,EAASF,GAAaF,EAAME,EAElC,OAAOE,EAASzU,KAAK0U,MAAmB,IAAbF,EAAoBC,QAAU/Q,CAC7D,CACA,CD9CuBiR,CAAY,GAAI,KAErC,OEFF,SAAkBpa,EAAImZ,GACpB,IAEIkB,EACAC,EAHAC,EAAY,EACZC,EAAY,IAAOrB,EAIvB,MAAMsB,EAAS,CAACC,EAAMZ,EAAMC,KAAKD,SAC/BS,EAAYT,EACZO,EAAW,KACPC,IACFK,aAAaL,GACbA,EAAQ,MAEVta,EAAGE,MAAM,KAAMwa,EAAK,EAqBtB,MAAO,CAlBW,IAAIA,KACpB,MAAMZ,EAAMC,KAAKD,MACXI,EAASJ,EAAMS,EAChBL,GAAUM,EACbC,EAAOC,EAAMZ,IAEbO,EAAWK,EACNJ,IACHA,EAAQpU,YAAW,KACjBoU,EAAQ,KACRG,EAAOJ,EAAS,GACfG,EAAYN,IAElB,EAGW,IAAMG,GAAYI,EAAOJ,GAGzC,CFjCSO,EAAS9G,IACd,MAAM+G,EAAS/G,EAAE+G,OACXC,EAAQhH,EAAEiH,iBAAmBjH,EAAEgH,WAAQ3R,EACvC6R,EAAgBH,EAASzB,EACzB6B,EAAO5B,EAAa2B,GAG1B5B,EAAgByB,EAchB5B,EAZa,CACX4B,SACAC,QACAI,SAAUJ,EAASD,EAASC,OAAS3R,EACrCqQ,MAAOwB,EACPC,KAAMA,QAAc9R,EACpBgS,UAAWF,GAAQH,GAVLD,GAAUC,GAUeA,EAAQD,GAAUI,OAAO9R,EAChEiS,MAAOtH,EACPiH,iBAA2B,MAATD,EAClB,CAAC5B,EAAmB,WAAa,WAAW,GAGhC,GACbC,EAAK,EAGGkC,GAAyB,CAACP,EAAOQ,KAC5C,MAAMP,EAA4B,MAATD,EAEzB,MAAO,CAAED,GAAWS,EAAU,GAAG,CAC/BP,mBACAD,QACAD,WACES,EAAU,GAAG,EAGNC,GAAkBvb,GAAO,IAAI0a,IAASlO,EAAMrG,MAAK,IAAMnG,KAAM0a,KGzC1Ec,GAAerJ,GAASR,sBAAwB,EAAEK,EAAQyJ,IAAY7L,IACpEA,EAAM,IAAI8L,IAAI9L,EAAKuC,GAASH,QAG1BA,EAAO2J,WAAa/L,EAAI+L,UACxB3J,EAAO4J,OAAShM,EAAIgM,OACnBH,GAAUzJ,EAAO6J,OAASjM,EAAIiM,OANa,CAS9C,IAAIH,IAAIvJ,GAASH,QACjBG,GAAST,WAAa,kBAAkB9D,KAAKuE,GAAST,UAAUoK,YAC9D,KAAM,ECVKC,GAAA5J,GAASR,sBAGtB,CACEqK,MAAMtX,EAAM6D,EAAO0T,EAAS1O,EAAM2O,EAAQC,GACxC,MAAMC,EAAS,CAAC1X,EAAO,IAAM4K,mBAAmB/G,IAEhDiE,EAAM/K,SAASwa,IAAYG,EAAOnW,KAAK,WAAa,IAAI8T,KAAKkC,GAASI,eAEtE7P,EAAMjL,SAASgM,IAAS6O,EAAOnW,KAAK,QAAUsH,GAE9Cf,EAAMjL,SAAS2a,IAAWE,EAAOnW,KAAK,UAAYiW,IAEvC,IAAXC,GAAmBC,EAAOnW,KAAK,UAE/BuL,SAAS4K,OAASA,EAAO1O,KAAK,KAC/B,EAED4O,KAAK5X,GACH,MAAM6K,EAAQiC,SAAS4K,OAAO7M,MAAM,IAAIgN,OAAO,aAAe7X,EAAO,cACrE,OAAQ6K,EAAQiN,mBAAmBjN,EAAM,IAAM,IAChD,EAEDkN,OAAO/X,GACL8C,KAAKwU,MAAMtX,EAAM,GAAIqV,KAAKD,MAAQ,MACnC,GAMH,CACEkC,QAAU,EACVM,KAAI,IACK,KAETG,SAAW,GCxBA,SAASC,GAAcC,EAASC,GAC7C,OAAID,ICHG,8BAA8B/O,KDGPgP,GENjB,SAAqBD,EAASE,GAC3C,OAAOA,EACHF,EAAQ5U,QAAQ,SAAU,IAAM,IAAM8U,EAAY9U,QAAQ,OAAQ,IAClE4U,CACN,CFGWG,CAAYH,EAASC,GAEvBA,CACT,CGfA,MAAMG,GAAmBpc,GAAUA,aAAiB2U,GAAe,IAAK3U,GAAUA,EAWnE,SAASqc,GAAYC,EAASC,GAE3CA,EAAUA,GAAW,GACrB,MAAM/Q,EAAS,CAAA,EAEf,SAASgR,EAAexR,EAAQ9F,EAAQ3B,EAAMqD,GAC5C,OAAIiF,EAAM7K,cAAcgK,IAAWa,EAAM7K,cAAckE,GAC9C2G,EAAMlF,MAAMzG,KAAK,CAAC0G,YAAWoE,EAAQ9F,GACnC2G,EAAM7K,cAAckE,GACtB2G,EAAMlF,MAAM,CAAE,EAAEzB,GACd2G,EAAMrL,QAAQ0E,GAChBA,EAAO/E,QAET+E,CACR,CAGD,SAASuX,EAAoBxV,EAAGC,EAAG3D,EAAOqD,GACxC,OAAKiF,EAAMnL,YAAYwG,GAEX2E,EAAMnL,YAAYuG,QAAvB,EACEuV,OAAehU,EAAWvB,EAAG1D,EAAOqD,GAFpC4V,EAAevV,EAAGC,EAAG3D,EAAOqD,EAItC,CAGD,SAAS8V,EAAiBzV,EAAGC,GAC3B,IAAK2E,EAAMnL,YAAYwG,GACrB,OAAOsV,OAAehU,EAAWtB,EAEpC,CAGD,SAASyV,EAAiB1V,EAAGC,GAC3B,OAAK2E,EAAMnL,YAAYwG,GAEX2E,EAAMnL,YAAYuG,QAAvB,EACEuV,OAAehU,EAAWvB,GAF1BuV,OAAehU,EAAWtB,EAIpC,CAGD,SAAS0V,EAAgB3V,EAAGC,EAAG3D,GAC7B,OAAIA,KAAQgZ,EACHC,EAAevV,EAAGC,GAChB3D,KAAQ+Y,EACVE,OAAehU,EAAWvB,QAD5B,CAGR,CAED,MAAM4V,EAAW,CACf5N,IAAKyN,EACLxI,OAAQwI,EACRvX,KAAMuX,EACNV,QAASW,EACTxK,iBAAkBwK,EAClBtJ,kBAAmBsJ,EACnBG,iBAAkBH,EAClBjJ,QAASiJ,EACTI,eAAgBJ,EAChBK,gBAAiBL,EACjBM,cAAeN,EACfzK,QAASyK,EACTpJ,aAAcoJ,EACdhJ,eAAgBgJ,EAChB/I,eAAgB+I,EAChBO,iBAAkBP,EAClBQ,mBAAoBR,EACpBS,WAAYT,EACZ9I,iBAAkB8I,EAClB7I,cAAe6I,EACfU,eAAgBV,EAChBW,UAAWX,EACXY,UAAWZ,EACXa,WAAYb,EACZc,YAAad,EACbe,WAAYf,EACZgB,iBAAkBhB,EAClB5I,eAAgB6I,EAChBxK,QAAS,CAACnL,EAAGC,EAAI3D,IAASkZ,EAAoBL,GAAgBnV,GAAImV,GAAgBlV,GAAG3D,GAAM,IAS7F,OANAsI,EAAM9J,QAAQrC,OAAO2C,KAAK3C,OAAOmI,OAAO,GAAIyU,EAASC,KAAW,SAA4BhZ,GAC1F,MAAMoD,EAAQkW,EAAStZ,IAASkZ,EAC1BmB,EAAcjX,EAAM2V,EAAQ/Y,GAAOgZ,EAAQhZ,GAAOA,GACvDsI,EAAMnL,YAAYkd,IAAgBjX,IAAUiW,IAAqBpR,EAAOjI,GAAQqa,EACrF,IAESpS,CACT,CChGA,MAAeqS,GAACrS,IACd,MAAMsS,EAAYzB,GAAY,CAAE,EAAE7Q,GAElC,IAaI6G,GAbAlN,KAACA,EAAI8X,cAAEA,EAAarJ,eAAEA,EAAcD,eAAEA,EAAcvB,QAAEA,EAAO2L,KAAEA,GAAQD,EAe3E,GAbAA,EAAU1L,QAAUA,EAAUuC,GAAavI,KAAKgG,GAEhD0L,EAAU7O,IAAMD,GAAS+M,GAAc+B,EAAU9B,QAAS8B,EAAU7O,KAAMzD,EAAOsD,OAAQtD,EAAOsR,kBAG5FiB,GACF3L,EAAQ3I,IAAI,gBAAiB,SAC3BuU,MAAMD,EAAKE,UAAY,IAAM,KAAOF,EAAKG,SAAWC,SAASxP,mBAAmBoP,EAAKG,WAAa,MAMlGrS,EAAM9F,WAAWZ,GACnB,GAAIqM,GAASR,uBAAyBQ,GAASN,+BAC7CkB,EAAQK,oBAAejK,QAClB,IAAiD,KAA5C6J,EAAcD,EAAQE,kBAA6B,CAE7D,MAAOhS,KAASoV,GAAUrD,EAAcA,EAAYtI,MAAM,KAAKjI,KAAI+C,GAASA,EAAMsC,SAAQc,OAAOmW,SAAW,GAC5GhM,EAAQK,eAAe,CAACnS,GAAQ,yBAA0BoV,GAAQ3I,KAAK,MACxE,CAOH,GAAIyE,GAASR,wBACXiM,GAAiBpR,EAAMhL,WAAWoc,KAAmBA,EAAgBA,EAAca,IAE/Eb,IAAoC,IAAlBA,GAA2BpC,GAAgBiD,EAAU7O,MAAO,CAEhF,MAAMoP,EAAYzK,GAAkBD,GAAkByH,GAAQO,KAAKhI,GAE/D0K,GACFjM,EAAQ3I,IAAImK,EAAgByK,EAE/B,CAGH,OAAOP,CAAS,ECzClBQ,GAFwD,oBAAnBC,gBAEG,SAAU/S,GAChD,OAAO,IAAIgT,SAAQ,SAA4BvG,EAASC,GACtD,MAAMuG,EAAUZ,GAAcrS,GAC9B,IAAIkT,EAAcD,EAAQtZ,KAC1B,MAAMwZ,EAAiBhK,GAAavI,KAAKqS,EAAQrM,SAAS8D,YAC1D,IACI0I,EACAC,EAAiBC,EACjBC,EAAaC,GAHbzL,aAACA,EAAY2J,iBAAEA,EAAgBC,mBAAEA,GAAsBsB,EAK3D,SAAS1V,IACPgW,GAAeA,IACfC,GAAiBA,IAEjBP,EAAQhB,aAAegB,EAAQhB,YAAYwB,YAAYL,GAEvDH,EAAQS,QAAUT,EAAQS,OAAOC,oBAAoB,QAASP,EAC/D,CAED,IAAInT,EAAU,IAAI8S,eAOlB,SAASa,IACP,IAAK3T,EACH,OAGF,MAAM4T,EAAkB1K,GAAavI,KACnC,0BAA2BX,GAAWA,EAAQ6T,yBAahDtH,IAAO,SAAkBpQ,GACvBqQ,EAAQrQ,GACRmB,GACR,IAAS,SAAiBwW,GAClBrH,EAAOqH,GACPxW,GACD,GAfgB,CACf5D,KAHoBoO,GAAiC,SAAjBA,GAA4C,SAAjBA,EACxC9H,EAAQC,SAA/BD,EAAQ+T,aAGR5T,OAAQH,EAAQG,OAChB6T,WAAYhU,EAAQgU,WACpBrN,QAASiN,EACT7T,SACAC,YAYFA,EAAU,IACX,CAlCDA,EAAQiU,KAAKjB,EAAQvK,OAAO5P,cAAema,EAAQxP,KAAK,GAGxDxD,EAAQiI,QAAU+K,EAAQ/K,QAiCtB,cAAejI,EAEjBA,EAAQ2T,UAAYA,EAGpB3T,EAAQkU,mBAAqB,WACtBlU,GAAkC,IAAvBA,EAAQmU,aAQD,IAAnBnU,EAAQG,QAAkBH,EAAQoU,aAAwD,IAAzCpU,EAAQoU,YAAYnX,QAAQ,WAKjFnD,WAAW6Z,EACnB,EAII3T,EAAQqU,QAAU,WACXrU,IAILyM,EAAO,IAAI7M,EAAW,kBAAmBA,EAAW0U,aAAcvU,EAAQC,IAG1EA,EAAU,KAChB,EAGIA,EAAQuU,QAAU,WAGhB9H,EAAO,IAAI7M,EAAW,gBAAiBA,EAAW4U,YAAazU,EAAQC,IAGvEA,EAAU,IAChB,EAGIA,EAAQyU,UAAY,WAClB,IAAIC,EAAsB1B,EAAQ/K,QAAU,cAAgB+K,EAAQ/K,QAAU,cAAgB,mBAC9F,MAAMzB,EAAewM,EAAQxM,cAAgB9B,GACzCsO,EAAQ0B,sBACVA,EAAsB1B,EAAQ0B,qBAEhCjI,EAAO,IAAI7M,EACT8U,EACAlO,EAAa3B,oBAAsBjF,EAAW+U,UAAY/U,EAAW0U,aACrEvU,EACAC,IAGFA,EAAU,IAChB,OAGoBjD,IAAhBkW,GAA6BC,EAAelM,eAAe,MAGvD,qBAAsBhH,GACxBI,EAAM9J,QAAQ4c,EAAe7S,UAAU,SAA0B7K,EAAKuB,GACpEiJ,EAAQ4U,iBAAiB7d,EAAKvB,EACtC,IAIS4K,EAAMnL,YAAY+d,EAAQzB,mBAC7BvR,EAAQuR,kBAAoByB,EAAQzB,iBAIlCzJ,GAAiC,SAAjBA,IAClB9H,EAAQ8H,aAAekL,EAAQlL,cAI7B4J,KACA2B,EAAmBE,GAAiB3G,GAAqB8E,GAAoB,GAC/E1R,EAAQxG,iBAAiB,WAAY6Z,IAInC5B,GAAoBzR,EAAQ6U,UAC5BzB,EAAiBE,GAAe1G,GAAqB6E,GAEvDzR,EAAQ6U,OAAOrb,iBAAiB,WAAY4Z,GAE5CpT,EAAQ6U,OAAOrb,iBAAiB,UAAW8Z,KAGzCN,EAAQhB,aAAegB,EAAQS,UAGjCN,EAAa2B,IACN9U,IAGLyM,GAAQqI,GAAUA,EAAOjgB,KAAO,IAAIwX,GAAc,KAAMtM,EAAQC,GAAW8U,GAC3E9U,EAAQ+U,QACR/U,EAAU,KAAI,EAGhBgT,EAAQhB,aAAegB,EAAQhB,YAAYgD,UAAU7B,GACjDH,EAAQS,SACVT,EAAQS,OAAOwB,QAAU9B,IAAeH,EAAQS,OAAOja,iBAAiB,QAAS2Z,KAIrF,MAAM5D,ECvLK,SAAuB/L,GACpC,MAAML,EAAQ,4BAA4BxF,KAAK6F,GAC/C,OAAOL,GAASA,EAAM,IAAM,EAC9B,CDoLqB+R,CAAclC,EAAQxP,KAEnC+L,IAAsD,IAA1CxJ,GAASb,UAAUjI,QAAQsS,GACzC9C,EAAO,IAAI7M,EAAW,wBAA0B2P,EAAW,IAAK3P,EAAW8M,gBAAiB3M,IAM9FC,EAAQmV,KAAKlC,GAAe,KAChC,GACA,EErJAmC,GA3CuB,CAACC,EAASpN,KAC/B,MAAMtR,OAACA,GAAW0e,EAAUA,EAAUA,EAAQ7Y,OAAOmW,SAAW,GAEhE,GAAI1K,GAAWtR,EAAQ,CACrB,IAEIse,EAFAK,EAAa,IAAIC,gBAIrB,MAAMlB,EAAU,SAAUmB,GACxB,IAAKP,EAAS,CACZA,GAAU,EACVzB,IACA,MAAMM,EAAM0B,aAAkBvX,MAAQuX,EAASpa,KAAKoa,OACpDF,EAAWP,MAAMjB,aAAelU,EAAakU,EAAM,IAAIzH,GAAcyH,aAAe7V,MAAQ6V,EAAIjU,QAAUiU,GAC3G,CACF,EAED,IAAI5F,EAAQjG,GAAWnO,YAAW,KAChCoU,EAAQ,KACRmG,EAAQ,IAAIzU,EAAW,WAAWqI,mBAA0BrI,EAAW+U,WAAW,GACjF1M,GAEH,MAAMuL,EAAc,KACd6B,IACFnH,GAASK,aAAaL,GACtBA,EAAQ,KACRmH,EAAQ/e,SAAQmd,IACdA,EAAOD,YAAcC,EAAOD,YAAYa,GAAWZ,EAAOC,oBAAoB,QAASW,EAAQ,IAEjGgB,EAAU,KACX,EAGHA,EAAQ/e,SAASmd,GAAWA,EAAOja,iBAAiB,QAAS6a,KAE7D,MAAMZ,OAACA,GAAU6B,EAIjB,OAFA7B,EAAOD,YAAc,IAAMpT,EAAMrG,KAAKyZ,GAE/BC,CACR,GC3CUgC,GAAc,UAAWC,EAAOC,GAC3C,IAAI7e,EAAM4e,EAAME,WAEhB,IAAKD,GAAa7e,EAAM6e,EAEtB,kBADMD,GAIR,IACIG,EADAC,EAAM,EAGV,KAAOA,EAAMhf,GACX+e,EAAMC,EAAMH,QACND,EAAMhhB,MAAMohB,EAAKD,GACvBC,EAAMD,CAEV,EAQME,GAAaC,gBAAiBC,GAClC,GAAIA,EAAOxgB,OAAOygB,eAEhB,kBADOD,GAIT,MAAME,EAASF,EAAOG,YACtB,IACE,OAAS,CACP,MAAM9Y,KAACA,EAAInB,MAAEA,SAAega,EAAOjG,OACnC,GAAI5S,EACF,YAEInB,CACP,CAGF,CAFS,cACFga,EAAOrB,QACd,CACH,EAEauB,GAAc,CAACJ,EAAQN,EAAWW,EAAYC,KACzD,MAAM5gB,EA3BiBqgB,gBAAiBQ,EAAUb,GAClD,UAAW,MAAMD,KAASK,GAAWS,SAC5Bf,GAAYC,EAAOC,EAE9B,CAuBmBc,CAAUR,EAAQN,GAEnC,IACIrY,EADA8P,EAAQ,EAERsJ,EAAahP,IACVpK,IACHA,GAAO,EACPiZ,GAAYA,EAAS7O,GACtB,EAGH,OAAO,IAAIiP,eAAe,CACxBX,WAAWV,GACT,IACE,MAAMhY,KAACA,EAAInB,MAAEA,SAAexG,EAAS0H,OAErC,GAAIC,EAGF,OAFDoZ,SACCpB,EAAWsB,QAIb,IAAI9f,EAAMqF,EAAMyZ,WAChB,GAAIU,EAAY,CACd,IAAIO,EAAczJ,GAAStW,EAC3Bwf,EAAWO,EACZ,CACDvB,EAAWwB,QAAQ,IAAInf,WAAWwE,GAInC,CAHC,MAAO2X,GAEP,MADA4C,EAAU5C,GACJA,CACP,CACF,EACDgB,OAAOU,IACLkB,EAAUlB,GACH7f,EAASohB,WAEjB,CACDC,cAAe,GAChB,EC3EGC,GAAoC,mBAAVC,OAA2C,mBAAZC,SAA8C,mBAAbC,SAC1FC,GAA4BJ,IAA8C,mBAAnBN,eAGvDW,GAAaL,KAA4C,mBAAhBM,aACzCzT,GAA0C,IAAIyT,YAAjC/iB,GAAQsP,GAAQd,OAAOxO,IACtCwhB,MAAOxhB,GAAQ,IAAImD,iBAAiB,IAAIyf,SAAS5iB,GAAKgjB,gBADtD,IAAE1T,GAIN,MAAMtC,GAAO,CAAC5N,KAAO0a,KACnB,IACE,QAAS1a,KAAM0a,EAGhB,CAFC,MAAO5G,GACP,OAAO,CACR,GAGG+P,GAAwBJ,IAA6B7V,IAAK,KAC9D,IAAIkW,GAAiB,EAErB,MAAMC,EAAiB,IAAIR,QAAQpR,GAASH,OAAQ,CAClDgS,KAAM,IAAIjB,eACVlO,OAAQ,OACJoP,aAEF,OADAH,GAAiB,EACV,MACR,IACA/Q,QAAQyD,IAAI,gBAEf,OAAOsN,IAAmBC,CAAc,IAKpCG,GAAyBT,IAC7B7V,IAAK,IAAMpB,EAAMnK,iBAAiB,IAAImhB,SAAS,IAAIQ,QAG/CG,GAAY,CAChB9B,OAAQ6B,IAA2B,CAACE,GAAQA,EAAIJ,OAG7B,IAAEI,GAAvBf,KAAuBe,GAOpB,IAAIZ,SANL,CAAC,OAAQ,cAAe,OAAQ,WAAY,UAAU9gB,SAAQzB,KAC3DkjB,GAAUljB,KAAUkjB,GAAUljB,GAAQuL,EAAMhL,WAAW4iB,GAAInjB,IAAUmjB,GAAQA,EAAInjB,KAChF,CAACojB,EAAGlY,KACF,MAAM,IAAIH,EAAW,kBAAkB/K,sBAA0B+K,EAAWsY,gBAAiBnY,EAAO,EACpG,KAIR,MA8BMoY,GAAoBnC,MAAOrP,EAASiR,KACxC,MAAMjhB,EAASyJ,EAAMxB,eAAe+H,EAAQyR,oBAE5C,OAAiB,MAAVzhB,EAjCaqf,OAAO4B,IAC3B,GAAY,MAARA,EACF,OAAO,EAGT,GAAGxX,EAAMtK,OAAO8hB,GACd,OAAOA,EAAK3Y,KAGd,GAAGmB,EAAMjB,oBAAoByY,GAAO,CAClC,MAAMS,EAAW,IAAIlB,QAAQpR,GAASH,OAAQ,CAC5C6C,OAAQ,OACRmP,SAEF,aAAcS,EAASb,eAAe5B,UACvC,CAED,OAAGxV,EAAM1F,kBAAkBkd,IAASxX,EAAMlL,cAAc0iB,GAC/CA,EAAKhC,YAGXxV,EAAMpK,kBAAkB4hB,KACzBA,GAAc,IAGbxX,EAAMjL,SAASyiB,UACFN,GAAWM,IAAOhC,gBADlC,EAEC,EAMuB0C,CAAcV,GAAQjhB,CAAM,ECxFhD4hB,GAAgB,CACpBC,KCNa,KDObC,IAAK5F,GACLqE,MDwFaD,IAAgB,OAAYlX,IACzC,IAAIyD,IACFA,EAAGiF,OACHA,EAAM/O,KACNA,EAAI+Z,OACJA,EAAMzB,YACNA,EAAW/J,QACXA,EAAOyJ,mBACPA,EAAkBD,iBAClBA,EAAgB3J,aAChBA,EAAYnB,QACZA,EAAO4K,gBACPA,EAAkB,cAAamH,aAC/BA,GACEtG,GAAcrS,GAElB+H,EAAeA,GAAgBA,EAAe,IAAInT,cAAgB,OAElE,IAEIqL,EAFA2Y,EAAiBC,GAAe,CAACnF,EAAQzB,GAAeA,EAAY6G,iBAAkB5Q,GAI1F,MAAMuL,EAAcmF,GAAkBA,EAAenF,aAAW,MAC5DmF,EAAenF,aAClB,GAED,IAAIsF,EAEJ,IACE,GACErH,GAAoBgG,IAAoC,QAAXhP,GAA+B,SAAXA,GACG,KAAnEqQ,QAA6BX,GAAkBxR,EAASjN,IACzD,CACA,IAMIqf,EANAV,EAAW,IAAIlB,QAAQ3T,EAAK,CAC9BiF,OAAQ,OACRmP,KAAMle,EACNme,OAAQ,SASV,GAJIzX,EAAM9F,WAAWZ,KAAUqf,EAAoBV,EAAS1R,QAAQqD,IAAI,kBACtErD,EAAQK,eAAe+R,GAGrBV,EAAST,KAAM,CACjB,MAAOtB,EAAY0C,GAAS/J,GAC1B6J,EACAlM,GAAqBuC,GAAesC,KAGtC/X,EAAO2c,GAAYgC,EAAST,KA1GT,MA0GmCtB,EAAY0C,EACnE,CACF,CAEI5Y,EAAMjL,SAASoc,KAClBA,EAAkBA,EAAkB,UAAY,QAKlD,MAAM0H,EAAyB,gBAAiB9B,QAAQjjB,UACxD8L,EAAU,IAAImX,QAAQ3T,EAAK,IACtBkV,EACHjF,OAAQkF,EACRlQ,OAAQA,EAAO5P,cACf8N,QAASA,EAAQ8D,YAAYpK,SAC7BuX,KAAMle,EACNme,OAAQ,OACRqB,YAAaD,EAAyB1H,OAAkBxU,IAG1D,IAAIkD,QAAiBiX,MAAMlX,GAE3B,MAAMmZ,EAAmBrB,KAA4C,WAAjBhQ,GAA8C,aAAjBA,GAEjF,GAAIgQ,KAA2BpG,GAAuByH,GAAoB3F,GAAe,CACvF,MAAM7R,EAAU,CAAA,EAEhB,CAAC,SAAU,aAAc,WAAWrL,SAAQwB,IAC1C6J,EAAQ7J,GAAQmI,EAASnI,EAAK,IAGhC,MAAMshB,EAAwBhZ,EAAMxB,eAAeqB,EAAS0G,QAAQqD,IAAI,oBAEjEsM,EAAY0C,GAAStH,GAAsBzC,GAChDmK,EACAxM,GAAqBuC,GAAeuC,IAAqB,KACtD,GAELzR,EAAW,IAAImX,SACbf,GAAYpW,EAAS2X,KAlJF,MAkJ4BtB,GAAY,KACzD0C,GAASA,IACTxF,GAAeA,GAAa,IAE9B7R,EAEH,CAEDmG,EAAeA,GAAgB,OAE/B,IAAIuR,QAAqBtB,GAAU3X,EAAMpJ,QAAQ+gB,GAAWjQ,IAAiB,QAAQ7H,EAAUF,GAI/F,OAFCoZ,GAAoB3F,GAAeA,UAEvB,IAAIT,SAAQ,CAACvG,EAASC,KACjCF,GAAOC,EAASC,EAAQ,CACtB/S,KAAM2f,EACN1S,QAASuC,GAAavI,KAAKV,EAAS0G,SACpCxG,OAAQF,EAASE,OACjB6T,WAAY/T,EAAS+T,WACrBjU,SACAC,WACA,GAeL,CAbC,MAAO8T,GAGP,GAFAN,GAAeA,IAEXM,GAAoB,cAAbA,EAAIxb,MAAwB,SAASkJ,KAAKsS,EAAIjU,SACvD,MAAM5L,OAAOmI,OACX,IAAIwD,EAAW,gBAAiBA,EAAW4U,YAAazU,EAAQC,GAChE,CACEe,MAAO+S,EAAI/S,OAAS+S,IAK1B,MAAMlU,EAAWe,KAAKmT,EAAKA,GAAOA,EAAIhU,KAAMC,EAAQC,EACrD,CACF,ICtNDI,EAAM9J,QAAQiiB,IAAe,CAAC3kB,EAAIuI,KAChC,GAAIvI,EAAI,CACN,IACEK,OAAOiI,eAAetI,EAAI,OAAQ,CAACuI,SAGpC,CAFC,MAAOuL,GAER,CACDzT,OAAOiI,eAAetI,EAAI,cAAe,CAACuI,SAC3C,KAGH,MAAMmd,GAAgB9D,GAAW,KAAKA,IAEhC+D,GAAoB9S,GAAYrG,EAAMhL,WAAWqR,IAAwB,OAAZA,IAAgC,IAAZA,EAExE+S,GACAA,IACXA,EAAWpZ,EAAMrL,QAAQykB,GAAYA,EAAW,CAACA,GAEjD,MAAM7iB,OAACA,GAAU6iB,EACjB,IAAIC,EACAhT,EAEJ,MAAMiT,EAAkB,CAAA,EAExB,IAAK,IAAIjjB,EAAI,EAAGA,EAAIE,EAAQF,IAAK,CAE/B,IAAI8N,EAIJ,GALAkV,EAAgBD,EAAS/iB,GAGzBgQ,EAAUgT,GAELF,GAAiBE,KACpBhT,EAAU8R,IAAehU,EAAKzH,OAAO2c,IAAgB9kB,oBAErCoI,IAAZ0J,GACF,MAAM,IAAI7G,EAAW,oBAAoB2E,MAI7C,GAAIkC,EACF,MAGFiT,EAAgBnV,GAAM,IAAM9N,GAAKgQ,CAClC,CAED,IAAKA,EAAS,CAEZ,MAAMkT,EAAU1lB,OAAOoS,QAAQqT,GAC5BrjB,KAAI,EAAEkO,EAAIqV,KAAW,WAAWrV,OACpB,IAAVqV,EAAkB,sCAAwC,mCAO/D,MAAM,IAAIha,EACR,yDALMjJ,EACLgjB,EAAQhjB,OAAS,EAAI,YAAcgjB,EAAQtjB,IAAIijB,IAAchY,KAAK,MAAQ,IAAMgY,GAAaK,EAAQ,IACtG,2BAIA,kBAEH,CAED,OAAOlT,CAAO,EE3DlB,SAASoT,GAA6B9Z,GAKpC,GAJIA,EAAOiS,aACTjS,EAAOiS,YAAY8H,mBAGjB/Z,EAAO0T,QAAU1T,EAAO0T,OAAOwB,QACjC,MAAM,IAAI5I,GAAc,KAAMtM,EAElC,CASe,SAASga,GAAgBha,GACtC8Z,GAA6B9Z,GAE7BA,EAAO4G,QAAUuC,GAAavI,KAAKZ,EAAO4G,SAG1C5G,EAAOrG,KAAOuS,GAAcxX,KAC1BsL,EACAA,EAAO2G,mBAGgD,IAArD,CAAC,OAAQ,MAAO,SAASzJ,QAAQ8C,EAAO0I,SAC1C1I,EAAO4G,QAAQK,eAAe,qCAAqC,GAKrE,OAFgBwS,GAAoBzZ,EAAO0G,SAAWF,GAASE,QAExDA,CAAQ1G,GAAQL,MAAK,SAA6BO,GAYvD,OAXA4Z,GAA6B9Z,GAG7BE,EAASvG,KAAOuS,GAAcxX,KAC5BsL,EACAA,EAAO6H,kBACP3H,GAGFA,EAAS0G,QAAUuC,GAAavI,KAAKV,EAAS0G,SAEvC1G,CACX,IAAK,SAA4BuV,GAe7B,OAdKrJ,GAASqJ,KACZqE,GAA6B9Z,GAGzByV,GAAUA,EAAOvV,WACnBuV,EAAOvV,SAASvG,KAAOuS,GAAcxX,KACnCsL,EACAA,EAAO6H,kBACP4N,EAAOvV,UAETuV,EAAOvV,SAAS0G,QAAUuC,GAAavI,KAAK6U,EAAOvV,SAAS0G,WAIzDoM,QAAQtG,OAAO+I,EAC1B,GACA,CChFO,MCKDwE,GAAa,CAAA,EAGnB,CAAC,SAAU,UAAW,SAAU,WAAY,SAAU,UAAU1jB,SAAQ,CAACzB,EAAM4B,KAC7EujB,GAAWnlB,GAAQ,SAAmBN,GACpC,cAAcA,IAAUM,GAAQ,KAAO4B,EAAI,EAAI,KAAO,KAAO5B,CACjE,CAAG,IAGH,MAAMolB,GAAqB,CAAA,EAW3BD,GAAWxT,aAAe,SAAsB0T,EAAWC,EAASta,GAClE,SAASua,EAAcC,EAAKC,GAC1B,MAAO,uCAAoDD,EAAM,IAAOC,GAAQza,EAAU,KAAOA,EAAU,GAC5G,CAGD,MAAO,CAAC1D,EAAOke,EAAKE,KAClB,IAAkB,IAAdL,EACF,MAAM,IAAIta,EACRwa,EAAcC,EAAK,qBAAuBF,EAAU,OAASA,EAAU,KACvEva,EAAW4a,gBAef,OAXIL,IAAYF,GAAmBI,KACjCJ,GAAmBI,IAAO,EAE1BI,QAAQC,KACNN,EACEC,EACA,+BAAiCF,EAAU,8CAK1CD,GAAYA,EAAU/d,EAAOke,EAAKE,EAAY,CAEzD,EAEAP,GAAWW,SAAW,SAAkBC,GACtC,MAAO,CAACze,EAAOke,KAEbI,QAAQC,KAAK,GAAGL,gCAAkCO,MAC3C,EAEX,EAmCA,MAAeV,GAAA,CACbW,cAxBF,SAAuBlZ,EAASmZ,EAAQC,GACtC,GAAuB,iBAAZpZ,EACT,MAAM,IAAI/B,EAAW,4BAA6BA,EAAWob,sBAE/D,MAAMpkB,EAAO3C,OAAO2C,KAAK+K,GACzB,IAAIlL,EAAIG,EAAKD,OACb,KAAOF,KAAM,GAAG,CACd,MAAM4jB,EAAMzjB,EAAKH,GACXyjB,EAAYY,EAAOT,GACzB,GAAIH,EAAJ,CACE,MAAM/d,EAAQwF,EAAQ0Y,GAChB1f,OAAmBoC,IAAVZ,GAAuB+d,EAAU/d,EAAOke,EAAK1Y,GAC5D,IAAe,IAAXhH,EACF,MAAM,IAAIiF,EAAW,UAAYya,EAAM,YAAc1f,EAAQiF,EAAWob,qBAG3E,MACD,IAAqB,IAAjBD,EACF,MAAM,IAAInb,EAAW,kBAAoBya,EAAKza,EAAWqb,eAE5D,CACH,EAIAjB,WAAEA,ICtFIA,GAAaE,GAAUF,WAS7B,MAAMkB,GACJ7gB,YAAY8gB,GACV/f,KAAKmL,SAAW4U,EAChB/f,KAAKggB,aAAe,CAClBpb,QAAS,IAAIqb,GACbpb,SAAU,IAAIob,GAEjB,CAUDrF,cAAcsF,EAAavb,GACzB,IACE,aAAa3E,KAAKid,SAASiD,EAAavb,EAsBzC,CArBC,MAAO+T,GACP,GAAIA,aAAe7V,MAAO,CACxB,IAAIsd,EAAQ,CAAA,EAEZtd,MAAMiC,kBAAoBjC,MAAMiC,kBAAkBqb,GAAUA,EAAQ,IAAItd,MAGxE,MAAMoB,EAAQkc,EAAMlc,MAAQkc,EAAMlc,MAAM1D,QAAQ,QAAS,IAAM,GAC/D,IACOmY,EAAIzU,MAGEA,IAAUvC,OAAOgX,EAAIzU,OAAO1C,SAAS0C,EAAM1D,QAAQ,YAAa,OACzEmY,EAAIzU,OAAS,KAAOA,GAHpByU,EAAIzU,MAAQA,CAOf,CAFC,MAAOqI,GAER,CACF,CAED,MAAMoM,CACP,CACF,CAEDuE,SAASiD,EAAavb,GAGO,iBAAhBub,GACTvb,EAASA,GAAU,IACZyD,IAAM8X,EAEbvb,EAASub,GAAe,GAG1Bvb,EAAS6Q,GAAYxV,KAAKmL,SAAUxG,GAEpC,MAAMyG,aAACA,EAAY6K,iBAAEA,EAAgB1K,QAAEA,GAAW5G,OAE7BhD,IAAjByJ,GACF0T,GAAUW,cAAcrU,EAAc,CACpC7B,kBAAmBqV,GAAWxT,aAAawT,GAAWwB,SACtD5W,kBAAmBoV,GAAWxT,aAAawT,GAAWwB,SACtD3W,oBAAqBmV,GAAWxT,aAAawT,GAAWwB,WACvD,GAGmB,MAApBnK,IACEjR,EAAMhL,WAAWic,GACnBtR,EAAOsR,iBAAmB,CACxB3N,UAAW2N,GAGb6I,GAAUW,cAAcxJ,EAAkB,CACxCrO,OAAQgX,GAAWyB,SACnB/X,UAAWsW,GAAWyB,WACrB,IAIPvB,GAAUW,cAAc9a,EAAQ,CAC9B2b,QAAS1B,GAAWW,SAAS,WAC7BgB,cAAe3B,GAAWW,SAAS,mBAClC,GAGH5a,EAAO0I,QAAU1I,EAAO0I,QAAUrN,KAAKmL,SAASkC,QAAU,OAAO9T,cAGjE,IAAIinB,EAAiBjV,GAAWvG,EAAMlF,MACpCyL,EAAQ4B,OACR5B,EAAQ5G,EAAO0I,SAGjB9B,GAAWvG,EAAM9J,QACf,CAAC,SAAU,MAAO,OAAQ,OAAQ,MAAO,QAAS,WACjDmS,WACQ9B,EAAQ8B,EAAO,IAI1B1I,EAAO4G,QAAUuC,GAAa7H,OAAOua,EAAgBjV,GAGrD,MAAMkV,EAA0B,GAChC,IAAIC,GAAiC,EACrC1gB,KAAKggB,aAAapb,QAAQ1J,SAAQ,SAAoCylB,GACjC,mBAAxBA,EAAY1X,UAA0D,IAAhC0X,EAAY1X,QAAQtE,KAIrE+b,EAAiCA,GAAkCC,EAAY3X,YAE/EyX,EAAwBG,QAAQD,EAAY7X,UAAW6X,EAAY5X,UACzE,IAEI,MAAM8X,EAA2B,GAKjC,IAAIC,EAJJ9gB,KAAKggB,aAAanb,SAAS3J,SAAQ,SAAkCylB,GACnEE,EAAyBpiB,KAAKkiB,EAAY7X,UAAW6X,EAAY5X,SACvE,IAGI,IACIrN,EADAL,EAAI,EAGR,IAAKqlB,EAAgC,CACnC,MAAMK,EAAQ,CAACpC,GAAgBpmB,KAAKyH,WAAO2B,GAO3C,IANAof,EAAMH,QAAQloB,MAAMqoB,EAAON,GAC3BM,EAAMtiB,KAAK/F,MAAMqoB,EAAOF,GACxBnlB,EAAMqlB,EAAMxlB,OAEZulB,EAAUnJ,QAAQvG,QAAQzM,GAEnBtJ,EAAIK,GACTolB,EAAUA,EAAQxc,KAAKyc,EAAM1lB,KAAM0lB,EAAM1lB,MAG3C,OAAOylB,CACR,CAEDplB,EAAM+kB,EAAwBllB,OAE9B,IAAI0b,EAAYtS,EAIhB,IAFAtJ,EAAI,EAEGA,EAAIK,GAAK,CACd,MAAMslB,EAAcP,EAAwBplB,KACtC4lB,EAAaR,EAAwBplB,KAC3C,IACE4b,EAAY+J,EAAY/J,EAIzB,CAHC,MAAOzR,GACPyb,EAAW5nB,KAAK2G,KAAMwF,GACtB,KACD,CACF,CAED,IACEsb,EAAUnC,GAAgBtlB,KAAK2G,KAAMiX,EAGtC,CAFC,MAAOzR,GACP,OAAOmS,QAAQtG,OAAO7L,EACvB,CAKD,IAHAnK,EAAI,EACJK,EAAMmlB,EAAyBtlB,OAExBF,EAAIK,GACTolB,EAAUA,EAAQxc,KAAKuc,EAAyBxlB,KAAMwlB,EAAyBxlB,MAGjF,OAAOylB,CACR,CAEDI,OAAOvc,GAGL,OAAOwD,GADU+M,IADjBvQ,EAAS6Q,GAAYxV,KAAKmL,SAAUxG,IACEwQ,QAASxQ,EAAOyD,KAC5BzD,EAAOsD,OAAQtD,EAAOsR,iBACjD,EAIHjR,EAAM9J,QAAQ,CAAC,SAAU,MAAO,OAAQ,YAAY,SAA6BmS,GAE/EyS,GAAMhnB,UAAUuU,GAAU,SAASjF,EAAKzD,GACtC,OAAO3E,KAAK4E,QAAQ4Q,GAAY7Q,GAAU,CAAA,EAAI,CAC5C0I,SACAjF,MACA9J,MAAOqG,GAAU,CAAA,GAAIrG,OAE3B,CACA,IAEA0G,EAAM9J,QAAQ,CAAC,OAAQ,MAAO,UAAU,SAA+BmS,GAGrE,SAAS8T,EAAmBC,GAC1B,OAAO,SAAoBhZ,EAAK9J,EAAMqG,GACpC,OAAO3E,KAAK4E,QAAQ4Q,GAAY7Q,GAAU,CAAA,EAAI,CAC5C0I,SACA9B,QAAS6V,EAAS,CAChB,eAAgB,uBACd,CAAE,EACNhZ,MACA9J,SAER,CACG,CAEDwhB,GAAMhnB,UAAUuU,GAAU8T,IAE1BrB,GAAMhnB,UAAUuU,EAAS,QAAU8T,GAAmB,EACxD,IAEA,MAAAE,GAAevB,GC7Nf,MAAMwB,GACJriB,YAAYsiB,GACV,GAAwB,mBAAbA,EACT,MAAM,IAAI/a,UAAU,gCAGtB,IAAIgb,EAEJxhB,KAAK8gB,QAAU,IAAInJ,SAAQ,SAAyBvG,GAClDoQ,EAAiBpQ,CACvB,IAEI,MAAMpT,EAAQgC,KAGdA,KAAK8gB,QAAQxc,MAAKoV,IAChB,IAAK1b,EAAMyjB,WAAY,OAEvB,IAAIpmB,EAAI2C,EAAMyjB,WAAWlmB,OAEzB,KAAOF,KAAM,GACX2C,EAAMyjB,WAAWpmB,GAAGqe,GAEtB1b,EAAMyjB,WAAa,IAAI,IAIzBzhB,KAAK8gB,QAAQxc,KAAOod,IAClB,IAAIC,EAEJ,MAAMb,EAAU,IAAInJ,SAAQvG,IAC1BpT,EAAM4b,UAAUxI,GAChBuQ,EAAWvQ,CAAO,IACjB9M,KAAKod,GAMR,OAJAZ,EAAQpH,OAAS,WACf1b,EAAMoa,YAAYuJ,EAC1B,EAEab,CAAO,EAGhBS,GAAS,SAAgB9c,EAASE,EAAQC,GACpC5G,EAAMoc,SAKVpc,EAAMoc,OAAS,IAAInJ,GAAcxM,EAASE,EAAQC,GAClD4c,EAAexjB,EAAMoc,QAC3B,GACG,CAKDsE,mBACE,GAAI1e,KAAKoa,OACP,MAAMpa,KAAKoa,MAEd,CAMDR,UAAUnI,GACJzR,KAAKoa,OACP3I,EAASzR,KAAKoa,QAIZpa,KAAKyhB,WACPzhB,KAAKyhB,WAAWhjB,KAAKgT,GAErBzR,KAAKyhB,WAAa,CAAChQ,EAEtB,CAMD2G,YAAY3G,GACV,IAAKzR,KAAKyhB,WACR,OAEF,MAAMja,EAAQxH,KAAKyhB,WAAW5f,QAAQ4P,IACvB,IAAXjK,GACFxH,KAAKyhB,WAAWG,OAAOpa,EAAO,EAEjC,CAEDiW,gBACE,MAAMvD,EAAa,IAAIC,gBAEjBR,EAASjB,IACbwB,EAAWP,MAAMjB,EAAI,EAOvB,OAJA1Y,KAAK4Z,UAAUD,GAEfO,EAAW7B,OAAOD,YAAc,IAAMpY,KAAKoY,YAAYuB,GAEhDO,EAAW7B,MACnB,CAMDxI,gBACE,IAAI6J,EAIJ,MAAO,CACL1b,MAJY,IAAIsjB,IAAY,SAAkBO,GAC9CnI,EAASmI,CACf,IAGMnI,SAEH,EAGH,MAAAoI,GAAeR,GCtIf,MAAMS,GAAiB,CACrBC,SAAU,IACVC,mBAAoB,IACpBC,WAAY,IACZC,WAAY,IACZC,GAAI,IACJC,QAAS,IACTC,SAAU,IACVC,4BAA6B,IAC7BC,UAAW,IACXC,aAAc,IACdC,eAAgB,IAChBC,YAAa,IACbC,gBAAiB,IACjBC,OAAQ,IACRC,gBAAiB,IACjBC,iBAAkB,IAClBC,MAAO,IACPC,SAAU,IACVC,YAAa,IACbC,SAAU,IACVC,OAAQ,IACRC,kBAAmB,IACnBC,kBAAmB,IACnBC,WAAY,IACZC,aAAc,IACdC,gBAAiB,IACjBC,UAAW,IACXC,SAAU,IACVC,iBAAkB,IAClBC,cAAe,IACfC,4BAA6B,IAC7BC,eAAgB,IAChBC,SAAU,IACVC,KAAM,IACNC,eAAgB,IAChBC,mBAAoB,IACpBC,gBAAiB,IACjBC,WAAY,IACZC,qBAAsB,IACtBC,oBAAqB,IACrBC,kBAAmB,IACnBC,UAAW,IACXC,mBAAoB,IACpBC,oBAAqB,IACrBC,OAAQ,IACRC,iBAAkB,IAClBC,SAAU,IACVC,gBAAiB,IACjBC,qBAAsB,IACtBC,gBAAiB,IACjBC,4BAA6B,IAC7BC,2BAA4B,IAC5BC,oBAAqB,IACrBC,eAAgB,IAChBC,WAAY,IACZC,mBAAoB,IACpBC,eAAgB,IAChBC,wBAAyB,IACzBC,sBAAuB,IACvBC,oBAAqB,IACrBC,aAAc,IACdC,YAAa,IACbC,8BAA+B,KAGjCjtB,OAAOoS,QAAQ8W,IAAgB7mB,SAAQ,EAAES,EAAKoF,MAC5CghB,GAAehhB,GAASpF,CAAG,IAG7B,MAAAoqB,GAAehE,GCxBf,MAAMiE,GAnBN,SAASC,EAAeC,GACtB,MAAM9pB,EAAU,IAAI0jB,GAAMoG,GACpBC,EAAW5tB,EAAKunB,GAAMhnB,UAAU8L,QAASxI,GAa/C,OAVA4I,EAAM7E,OAAOgmB,EAAUrG,GAAMhnB,UAAWsD,EAAS,CAAChB,YAAY,IAG9D4J,EAAM7E,OAAOgmB,EAAU/pB,EAAS,KAAM,CAAChB,YAAY,IAGnD+qB,EAASjtB,OAAS,SAAgB6mB,GAChC,OAAOkG,EAAezQ,GAAY0Q,EAAenG,GACrD,EAESoG,CACT,CAGcF,CAAe9a,IAG7B6a,GAAMlG,MAAQA,GAGdkG,GAAM/U,cAAgBA,GACtB+U,GAAM1E,YAAcA,GACpB0E,GAAMjV,SAAWA,GACjBiV,GAAMI,QLvDiB,QKwDvBJ,GAAM3f,WAAaA,EAGnB2f,GAAMxhB,WAAaA,EAGnBwhB,GAAMK,OAASL,GAAM/U,cAGrB+U,GAAMM,IAAM,SAAaC,GACvB,OAAO5O,QAAQ2O,IAAIC,EACrB,EAEAP,GAAMQ,OC9CS,SAAgBC,GAC7B,OAAO,SAAc1kB,GACnB,OAAO0kB,EAAS/tB,MAAM,KAAMqJ,EAChC,CACA,ED6CAikB,GAAMU,aE7DS,SAAsBC,GACnC,OAAO3hB,EAAM9K,SAASysB,KAAsC,IAAzBA,EAAQD,YAC7C,EF8DAV,GAAMxQ,YAAcA,GAEpBwQ,GAAMlY,aAAeA,GAErBkY,GAAMY,WAAaztB,GAASyR,GAAe5F,EAAMxI,WAAWrD,GAAS,IAAIiG,SAASjG,GAASA,GAE3F6sB,GAAMa,WAAazI,GAEnB4H,GAAMjE,eAAiBA,GAEvBiE,GAAMc,QAAUd,GAGhB,MAAee,GAAAf,IGnFTlG,MACJA,GAAKtb,WACLA,GAAUyM,cACVA,GAAaF,SACbA,GAAQuQ,YACRA,GAAW8E,QACXA,GAAOE,IACPA,GAAGD,OACHA,GAAMK,aACNA,GAAYF,OACZA,GAAMngB,WACNA,GAAUyH,aACVA,GAAYiU,eACZA,GAAc6E,WACdA,GAAUC,WACVA,GAAUrR,YACVA,IACEwQ"} \ No newline at end of file diff --git a/node_modules/axios/dist/node/axios.cjs b/node_modules/axios/dist/node/axios.cjs new file mode 100644 index 000000000..30c6c096c --- /dev/null +++ b/node_modules/axios/dist/node/axios.cjs @@ -0,0 +1,4752 @@ +// Axios v1.7.9 Copyright (c) 2024 Matt Zabriskie and contributors +'use strict'; + +const FormData$1 = require('form-data'); +const url = require('url'); +const proxyFromEnv = require('proxy-from-env'); +const http = require('http'); +const https = require('https'); +const util = require('util'); +const followRedirects = require('follow-redirects'); +const zlib = require('zlib'); +const stream = require('stream'); +const events = require('events'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +const FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData$1); +const url__default = /*#__PURE__*/_interopDefaultLegacy(url); +const proxyFromEnv__default = /*#__PURE__*/_interopDefaultLegacy(proxyFromEnv); +const http__default = /*#__PURE__*/_interopDefaultLegacy(http); +const https__default = /*#__PURE__*/_interopDefaultLegacy(https); +const util__default = /*#__PURE__*/_interopDefaultLegacy(util); +const followRedirects__default = /*#__PURE__*/_interopDefaultLegacy(followRedirects); +const zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib); +const stream__default = /*#__PURE__*/_interopDefaultLegacy(stream); + +function bind(fn, thisArg) { + return function wrap() { + return fn.apply(thisArg, arguments); + }; +} + +// utils is a library of generic helper functions non-specific to axios + +const {toString} = Object.prototype; +const {getPrototypeOf} = Object; + +const kindOf = (cache => thing => { + const str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); +})(Object.create(null)); + +const kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type +}; + +const typeOfTest = type => thing => typeof thing === type; + +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * + * @returns {boolean} True if value is an Array, otherwise false + */ +const {isArray} = Array; + +/** + * Determine if a value is undefined + * + * @param {*} val The value to test + * + * @returns {boolean} True if the value is undefined, otherwise false + */ +const isUndefined = typeOfTest('undefined'); + +/** + * Determine if a value is a Buffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); +} + +/** + * Determine if a value is an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +const isArrayBuffer = kindOfTest('ArrayBuffer'); + + +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + let result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); + } + return result; +} + +/** + * Determine if a value is a String + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a String, otherwise false + */ +const isString = typeOfTest('string'); + +/** + * Determine if a value is a Function + * + * @param {*} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +const isFunction = typeOfTest('function'); + +/** + * Determine if a value is a Number + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Number, otherwise false + */ +const isNumber = typeOfTest('number'); + +/** + * Determine if a value is an Object + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an Object, otherwise false + */ +const isObject = (thing) => thing !== null && typeof thing === 'object'; + +/** + * Determine if a value is a Boolean + * + * @param {*} thing The value to test + * @returns {boolean} True if value is a Boolean, otherwise false + */ +const isBoolean = thing => thing === true || thing === false; + +/** + * Determine if a value is a plain Object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a plain Object, otherwise false + */ +const isPlainObject = (val) => { + if (kindOf(val) !== 'object') { + return false; + } + + const prototype = getPrototypeOf(val); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); +}; + +/** + * Determine if a value is a Date + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Date, otherwise false + */ +const isDate = kindOfTest('Date'); + +/** + * Determine if a value is a File + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFile = kindOfTest('File'); + +/** + * Determine if a value is a Blob + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Blob, otherwise false + */ +const isBlob = kindOfTest('Blob'); + +/** + * Determine if a value is a FileList + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFileList = kindOfTest('FileList'); + +/** + * Determine if a value is a Stream + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Stream, otherwise false + */ +const isStream = (val) => isObject(val) && isFunction(val.pipe); + +/** + * Determine if a value is a FormData + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an FormData, otherwise false + */ +const isFormData = (thing) => { + let kind; + return thing && ( + (typeof FormData === 'function' && thing instanceof FormData) || ( + isFunction(thing.append) && ( + (kind = kindOf(thing)) === 'formdata' || + // detect form-data instance + (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]') + ) + ) + ) +}; + +/** + * Determine if a value is a URLSearchParams object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +const isURLSearchParams = kindOfTest('URLSearchParams'); + +const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest); + +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * + * @returns {String} The String freed of excess whitespace + */ +const trim = (str) => str.trim ? + str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + * + * @param {Boolean} [allOwnKeys = false] + * @returns {any} + */ +function forEach(obj, fn, {allOwnKeys = false} = {}) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + let i; + let l; + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; + + for (i = 0; i < len; i++) { + key = keys[i]; + fn.call(null, obj[key], key, obj); + } + } +} + +function findKey(obj, key) { + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; +} + +const _global = (() => { + /*eslint no-undef:0*/ + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global) +})(); + +const isContextDefined = (context) => !isUndefined(context) && context !== _global; + +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + const {caseless} = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + }; + + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); + } + return result; +} + +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * + * @param {Boolean} [allOwnKeys] + * @returns {Object} The resulting value of object a + */ +const extend = (a, b, thisArg, {allOwnKeys}= {}) => { + forEach(b, (val, key) => { + if (thisArg && isFunction(val)) { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }, {allOwnKeys}); + return a; +}; + +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * + * @returns {string} content value without BOM + */ +const stripBOM = (content) => { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +}; + +/** + * Inherit the prototype methods from one constructor into another + * @param {function} constructor + * @param {function} superConstructor + * @param {object} [props] + * @param {object} [descriptors] + * + * @returns {void} + */ +const inherits = (constructor, superConstructor, props, descriptors) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, 'super', { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); +}; + +/** + * Resolve object with deep prototype chain to a flat object + * @param {Object} sourceObj source object + * @param {Object} [destObj] + * @param {Function|Boolean} [filter] + * @param {Function} [propFilter] + * + * @returns {Object} + */ +const toFlatObject = (sourceObj, destObj, filter, propFilter) => { + let props; + let i; + let prop; + const merged = {}; + + destObj = destObj || {}; + // eslint-disable-next-line no-eq-null,eqeqeq + if (sourceObj == null) return destObj; + + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + + return destObj; +}; + +/** + * Determines whether a string ends with the characters of a specified string + * + * @param {String} str + * @param {String} searchString + * @param {Number} [position= 0] + * + * @returns {boolean} + */ +const endsWith = (str, searchString, position) => { + str = String(str); + if (position === undefined || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; +}; + + +/** + * Returns new array from array like object or null if failed + * + * @param {*} [thing] + * + * @returns {?Array} + */ +const toArray = (thing) => { + if (!thing) return null; + if (isArray(thing)) return thing; + let i = thing.length; + if (!isNumber(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; +}; + +/** + * Checking if the Uint8Array exists and if it does, it returns a function that checks if the + * thing passed in is an instance of Uint8Array + * + * @param {TypedArray} + * + * @returns {Array} + */ +// eslint-disable-next-line func-names +const isTypedArray = (TypedArray => { + // eslint-disable-next-line func-names + return thing => { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); + +/** + * For each entry in the object, call the function with the key and value. + * + * @param {Object} obj - The object to iterate over. + * @param {Function} fn - The function to call for each entry. + * + * @returns {void} + */ +const forEachEntry = (obj, fn) => { + const generator = obj && obj[Symbol.iterator]; + + const iterator = generator.call(obj); + + let result; + + while ((result = iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); + } +}; + +/** + * It takes a regular expression and a string, and returns an array of all the matches + * + * @param {string} regExp - The regular expression to match against. + * @param {string} str - The string to search. + * + * @returns {Array} + */ +const matchAll = (regExp, str) => { + let matches; + const arr = []; + + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + + return arr; +}; + +/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ +const isHTMLForm = kindOfTest('HTMLFormElement'); + +const toCamelCase = str => { + return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, + function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; + } + ); +}; + +/* Creating a function that will check if an object has a property. */ +const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); + +/** + * Determine if a value is a RegExp object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a RegExp object, otherwise false + */ +const isRegExp = kindOfTest('RegExp'); + +const reduceDescriptors = (obj, reducer) => { + const descriptors = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + + forEach(descriptors, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); + + Object.defineProperties(obj, reducedDescriptors); +}; + +/** + * Makes all methods read-only + * @param {Object} obj + */ + +const freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name) => { + // skip restricted props in strict mode + if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { + return false; + } + + const value = obj[name]; + + if (!isFunction(value)) return; + + descriptor.enumerable = false; + + if ('writable' in descriptor) { + descriptor.writable = false; + return; + } + + if (!descriptor.set) { + descriptor.set = () => { + throw Error('Can not rewrite read-only method \'' + name + '\''); + }; + } + }); +}; + +const toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; + + const define = (arr) => { + arr.forEach(value => { + obj[value] = true; + }); + }; + + isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + + return obj; +}; + +const noop = () => {}; + +const toFiniteNumber = (value, defaultValue) => { + return value != null && Number.isFinite(value = +value) ? value : defaultValue; +}; + +const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; + +const DIGIT = '0123456789'; + +const ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT +}; + +const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { + let str = ''; + const {length} = alphabet; + while (size--) { + str += alphabet[Math.random() * length|0]; + } + + return str; +}; + +/** + * If the thing is a FormData object, return true, otherwise return false. + * + * @param {unknown} thing - The thing to check. + * + * @returns {boolean} + */ +function isSpecCompliantForm(thing) { + return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]); +} + +const toJSONObject = (obj) => { + const stack = new Array(10); + + const visit = (source, i) => { + + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + + if(!('toJSON' in source)) { + stack[i] = source; + const target = isArray(source) ? [] : {}; + + forEach(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + + stack[i] = undefined; + + return target; + } + } + + return source; + }; + + return visit(obj, 0); +}; + +const isAsyncFn = kindOfTest('AsyncFunction'); + +const isThenable = (thing) => + thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); + +// original code +// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 + +const _setImmediate = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; + } + + return postMessageSupported ? ((token, callbacks) => { + _global.addEventListener("message", ({source, data}) => { + if (source === _global && data === token) { + callbacks.length && callbacks.shift()(); + } + }, false); + + return (cb) => { + callbacks.push(cb); + _global.postMessage(token, "*"); + } + })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); +})( + typeof setImmediate === 'function', + isFunction(_global.postMessage) +); + +const asap = typeof queueMicrotask !== 'undefined' ? + queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate); + +// ********************* + +const utils$1 = { + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString, + isNumber, + isBoolean, + isObject, + isPlainObject, + isReadableStream, + isRequest, + isResponse, + isHeaders, + isUndefined, + isDate, + isFile, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty, + hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + ALPHABET, + generateString, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable, + setImmediate: _setImmediate, + asap +}; + +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [config] The config. + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * + * @returns {Error} The created error. + */ +function AxiosError(message, code, config, request, response) { + Error.call(this); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = (new Error()).stack; + } + + this.message = message; + this.name = 'AxiosError'; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status ? response.status : null; + } +} + +utils$1.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils$1.toJSONObject(this.config), + code: this.code, + status: this.status + }; + } +}); + +const prototype$1 = AxiosError.prototype; +const descriptors = {}; + +[ + 'ERR_BAD_OPTION_VALUE', + 'ERR_BAD_OPTION', + 'ECONNABORTED', + 'ETIMEDOUT', + 'ERR_NETWORK', + 'ERR_FR_TOO_MANY_REDIRECTS', + 'ERR_DEPRECATED', + 'ERR_BAD_RESPONSE', + 'ERR_BAD_REQUEST', + 'ERR_CANCELED', + 'ERR_NOT_SUPPORT', + 'ERR_INVALID_URL' +// eslint-disable-next-line func-names +].forEach(code => { + descriptors[code] = {value: code}; +}); + +Object.defineProperties(AxiosError, descriptors); +Object.defineProperty(prototype$1, 'isAxiosError', {value: true}); + +// eslint-disable-next-line func-names +AxiosError.from = (error, code, config, request, response, customProps) => { + const axiosError = Object.create(prototype$1); + + utils$1.toFlatObject(error, axiosError, function filter(obj) { + return obj !== Error.prototype; + }, prop => { + return prop !== 'isAxiosError'; + }); + + AxiosError.call(axiosError, error.message, code, config, request, response); + + axiosError.cause = error; + + axiosError.name = error.name; + + customProps && Object.assign(axiosError, customProps); + + return axiosError; +}; + +/** + * Determines if the given thing is a array or js object. + * + * @param {string} thing - The object or array to be visited. + * + * @returns {boolean} + */ +function isVisitable(thing) { + return utils$1.isPlainObject(thing) || utils$1.isArray(thing); +} + +/** + * It removes the brackets from the end of a string + * + * @param {string} key - The key of the parameter. + * + * @returns {string} the key without the brackets. + */ +function removeBrackets(key) { + return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key; +} + +/** + * It takes a path, a key, and a boolean, and returns a string + * + * @param {string} path - The path to the current key. + * @param {string} key - The key of the current object being iterated over. + * @param {string} dots - If true, the key will be rendered with dots instead of brackets. + * + * @returns {string} The path to the current key. + */ +function renderKey(path, key, dots) { + if (!path) return key; + return path.concat(key).map(function each(token, i) { + // eslint-disable-next-line no-param-reassign + token = removeBrackets(token); + return !dots && i ? '[' + token + ']' : token; + }).join(dots ? '.' : ''); +} + +/** + * If the array is an array and none of its elements are visitable, then it's a flat array. + * + * @param {Array} arr - The array to check + * + * @returns {boolean} + */ +function isFlatArray(arr) { + return utils$1.isArray(arr) && !arr.some(isVisitable); +} + +const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); +}); + +/** + * Convert a data object to FormData + * + * @param {Object} obj + * @param {?Object} [formData] + * @param {?Object} [options] + * @param {Function} [options.visitor] + * @param {Boolean} [options.metaTokens = true] + * @param {Boolean} [options.dots = false] + * @param {?Boolean} [options.indexes = false] + * + * @returns {Object} + **/ + +/** + * It converts an object into a FormData object + * + * @param {Object} obj - The object to convert to form data. + * @param {string} formData - The FormData object to append to. + * @param {Object} options + * + * @returns + */ +function toFormData(obj, formData, options) { + if (!utils$1.isObject(obj)) { + throw new TypeError('target must be an object'); + } + + // eslint-disable-next-line no-param-reassign + formData = formData || new (FormData__default["default"] || FormData)(); + + // eslint-disable-next-line no-param-reassign + options = utils$1.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + // eslint-disable-next-line no-eq-null,eqeqeq + return !utils$1.isUndefined(source[option]); + }); + + const metaTokens = options.metaTokens; + // eslint-disable-next-line no-use-before-define + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; + const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + + if (!utils$1.isFunction(visitor)) { + throw new TypeError('visitor must be a function'); + } + + function convertValue(value) { + if (value === null) return ''; + + if (utils$1.isDate(value)) { + return value.toISOString(); + } + + if (!useBlob && utils$1.isBlob(value)) { + throw new AxiosError('Blob is not supported. Use a Buffer instead.'); + } + + if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { + return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + } + + return value; + } + + /** + * Default visitor. + * + * @param {*} value + * @param {String|Number} key + * @param {Array} path + * @this {FormData} + * + * @returns {boolean} return true to visit the each prop of the value recursively + */ + function defaultVisitor(value, key, path) { + let arr = value; + + if (value && !path && typeof value === 'object') { + if (utils$1.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign + key = metaTokens ? key : key.slice(0, -2); + // eslint-disable-next-line no-param-reassign + value = JSON.stringify(value); + } else if ( + (utils$1.isArray(value) && isFlatArray(value)) || + ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)) + )) { + // eslint-disable-next-line no-param-reassign + key = removeBrackets(key); + + arr.forEach(function each(el, index) { + !(utils$1.isUndefined(el) || el === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), + convertValue(el) + ); + }); + return false; + } + } + + if (isVisitable(value)) { + return true; + } + + formData.append(renderKey(path, key, dots), convertValue(value)); + + return false; + } + + const stack = []; + + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable + }); + + function build(value, path) { + if (utils$1.isUndefined(value)) return; + + if (stack.indexOf(value) !== -1) { + throw Error('Circular reference detected in ' + path.join('.')); + } + + stack.push(value); + + utils$1.forEach(value, function each(el, key) { + const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( + formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers + ); + + if (result === true) { + build(el, path ? path.concat(key) : [key]); + } + }); + + stack.pop(); + } + + if (!utils$1.isObject(obj)) { + throw new TypeError('data must be an object'); + } + + build(obj); + + return formData; +} + +/** + * It encodes a string by replacing all characters that are not in the unreserved set with + * their percent-encoded equivalents + * + * @param {string} str - The string to encode. + * + * @returns {string} The encoded string. + */ +function encode$1(str) { + const charMap = { + '!': '%21', + "'": '%27', + '(': '%28', + ')': '%29', + '~': '%7E', + '%20': '+', + '%00': '\x00' + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); +} + +/** + * It takes a params object and converts it to a FormData object + * + * @param {Object} params - The parameters to be converted to a FormData object. + * @param {Object} options - The options object passed to the Axios constructor. + * + * @returns {void} + */ +function AxiosURLSearchParams(params, options) { + this._pairs = []; + + params && toFormData(params, this, options); +} + +const prototype = AxiosURLSearchParams.prototype; + +prototype.append = function append(name, value) { + this._pairs.push([name, value]); +}; + +prototype.toString = function toString(encoder) { + const _encode = encoder ? function(value) { + return encoder.call(this, value, encode$1); + } : encode$1; + + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + '=' + _encode(pair[1]); + }, '').join('&'); +}; + +/** + * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their + * URI encoded counterparts + * + * @param {string} val The value to be encoded. + * + * @returns {string} The encoded value. + */ +function encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} + +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @param {?(object|Function)} options + * + * @returns {string} The formatted url + */ +function buildURL(url, params, options) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + + const _encode = options && options.encode || encode; + + if (utils$1.isFunction(options)) { + options = { + serialize: options + }; + } + + const serializeFn = options && options.serialize; + + let serializedParams; + + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils$1.isURLSearchParams(params) ? + params.toString() : + new AxiosURLSearchParams(params, options).toString(_encode); + } + + if (serializedParams) { + const hashmarkIndex = url.indexOf("#"); + + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + + return url; +} + +class InterceptorManager { + constructor() { + this.handlers = []; + } + + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + */ + eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; + } + } + + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn) { + utils$1.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + } +} + +const InterceptorManager$1 = InterceptorManager; + +const transitionalDefaults = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false +}; + +const URLSearchParams = url__default["default"].URLSearchParams; + +const platform$1 = { + isNode: true, + classes: { + URLSearchParams, + FormData: FormData__default["default"], + Blob: typeof Blob !== 'undefined' && Blob || null + }, + protocols: [ 'http', 'https', 'file', 'data' ] +}; + +const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; + +const _navigator = typeof navigator === 'object' && navigator || undefined; + +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + * + * @returns {boolean} + */ +const hasStandardBrowserEnv = hasBrowserEnv && + (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0); + +/** + * Determine if we're running in a standard browser webWorker environment + * + * Although the `isStandardBrowserEnv` method indicates that + * `allows axios to run in a web worker`, the WebWorker will still be + * filtered out due to its judgment standard + * `typeof window !== 'undefined' && typeof document !== 'undefined'`. + * This leads to a problem when axios post `FormData` in webWorker + */ +const hasStandardBrowserWebWorkerEnv = (() => { + return ( + typeof WorkerGlobalScope !== 'undefined' && + // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && + typeof self.importScripts === 'function' + ); +})(); + +const origin = hasBrowserEnv && window.location.href || 'http://localhost'; + +const utils = /*#__PURE__*/Object.freeze({ + __proto__: null, + hasBrowserEnv: hasBrowserEnv, + hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, + hasStandardBrowserEnv: hasStandardBrowserEnv, + navigator: _navigator, + origin: origin +}); + +const platform = { + ...utils, + ...platform$1 +}; + +function toURLEncodedForm(data, options) { + return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (platform.isNode && utils$1.isBuffer(value)) { + this.append(key, value.toString('base64')); + return false; + } + + return helpers.defaultVisitor.apply(this, arguments); + } + }, options)); +} + +/** + * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z'] + * + * @param {string} name - The name of the property to get. + * + * @returns An array of strings. + */ +function parsePropPath(name) { + // foo[x][y][z] + // foo.x.y.z + // foo-x-y-z + // foo x y z + return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => { + return match[0] === '[]' ? '' : match[1] || match[0]; + }); +} + +/** + * Convert an array to an object. + * + * @param {Array} arr - The array to convert to an object. + * + * @returns An object with the same keys and values as the array. + */ +function arrayToObject(arr) { + const obj = {}; + const keys = Object.keys(arr); + let i; + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; +} + +/** + * It takes a FormData object and returns a JavaScript object + * + * @param {string} formData The FormData object to convert to JSON. + * + * @returns {Object | null} The converted object. + */ +function formDataToJSON(formData) { + function buildPath(path, value, target, index) { + let name = path[index++]; + + if (name === '__proto__') return true; + + const isNumericKey = Number.isFinite(+name); + const isLast = index >= path.length; + name = !name && utils$1.isArray(target) ? target.length : name; + + if (isLast) { + if (utils$1.hasOwnProp(target, name)) { + target[name] = [target[name], value]; + } else { + target[name] = value; + } + + return !isNumericKey; + } + + if (!target[name] || !utils$1.isObject(target[name])) { + target[name] = []; + } + + const result = buildPath(path, value, target[name], index); + + if (result && utils$1.isArray(target[name])) { + target[name] = arrayToObject(target[name]); + } + + return !isNumericKey; + } + + if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { + const obj = {}; + + utils$1.forEachEntry(formData, (name, value) => { + buildPath(parsePropPath(name), value, obj, 0); + }); + + return obj; + } + + return null; +} + +/** + * It takes a string, tries to parse it, and if it fails, it returns the stringified version + * of the input + * + * @param {any} rawValue - The value to be stringified. + * @param {Function} parser - A function that parses a string into a JavaScript object. + * @param {Function} encoder - A function that takes a value and returns a string. + * + * @returns {string} A stringified version of the rawValue. + */ +function stringifySafely(rawValue, parser, encoder) { + if (utils$1.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils$1.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } + } + } + + return (encoder || JSON.stringify)(rawValue); +} + +const defaults = { + + transitional: transitionalDefaults, + + adapter: ['xhr', 'http', 'fetch'], + + transformRequest: [function transformRequest(data, headers) { + const contentType = headers.getContentType() || ''; + const hasJSONContentType = contentType.indexOf('application/json') > -1; + const isObjectPayload = utils$1.isObject(data); + + if (isObjectPayload && utils$1.isHTMLForm(data)) { + data = new FormData(data); + } + + const isFormData = utils$1.isFormData(data); + + if (isFormData) { + return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; + } + + if (utils$1.isArrayBuffer(data) || + utils$1.isBuffer(data) || + utils$1.isStream(data) || + utils$1.isFile(data) || + utils$1.isBlob(data) || + utils$1.isReadableStream(data) + ) { + return data; + } + if (utils$1.isArrayBufferView(data)) { + return data.buffer; + } + if (utils$1.isURLSearchParams(data)) { + headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); + return data.toString(); + } + + let isFileList; + + if (isObjectPayload) { + if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + + if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { + const _FormData = this.env && this.env.FormData; + + return toFormData( + isFileList ? {'files[]': data} : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + + if (isObjectPayload || hasJSONContentType ) { + headers.setContentType('application/json', false); + return stringifySafely(data); + } + + return data; + }], + + transformResponse: [function transformResponse(data) { + const transitional = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional && transitional.forcedJSONParsing; + const JSONRequested = this.responseType === 'json'; + + if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) { + return data; + } + + if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { + const silentJSONParsing = transitional && transitional.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } + + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + + headers: { + common: { + 'Accept': 'application/json, text/plain, */*', + 'Content-Type': undefined + } + } +}; + +utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { + defaults.headers[method] = {}; +}); + +const defaults$1 = defaults; + +// RawAxiosHeaders whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +const ignoreDuplicateOf = utils$1.toObjectSet([ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]); + +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} rawHeaders Headers needing to be parsed + * + * @returns {Object} Headers parsed into an object + */ +const parseHeaders = rawHeaders => { + const parsed = {}; + let key; + let val; + let i; + + rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { + i = line.indexOf(':'); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + + if (!key || (parsed[key] && ignoreDuplicateOf[key])) { + return; + } + + if (key === 'set-cookie') { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + }); + + return parsed; +}; + +const $internals = Symbol('internals'); + +function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); +} + +function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + + return utils$1.isArray(value) ? value.map(normalizeValue) : String(value); +} + +function parseTokens(str) { + const tokens = Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + + while ((match = tokensRE.exec(str))) { + tokens[match[1]] = match[2]; + } + + return tokens; +} + +const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); + +function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { + if (utils$1.isFunction(filter)) { + return filter.call(this, value, header); + } + + if (isHeaderNameFilter) { + value = header; + } + + if (!utils$1.isString(value)) return; + + if (utils$1.isString(filter)) { + return value.indexOf(filter) !== -1; + } + + if (utils$1.isRegExp(filter)) { + return filter.test(value); + } +} + +function formatHeader(header) { + return header.trim() + .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { + return char.toUpperCase() + str; + }); +} + +function buildAccessors(obj, header) { + const accessorName = utils$1.toCamelCase(' ' + header); + + ['get', 'set', 'has'].forEach(methodName => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); +} + +class AxiosHeaders { + constructor(headers) { + headers && this.set(headers); + } + + set(header, valueOrRewrite, rewrite) { + const self = this; + + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); + + if (!lHeader) { + throw new Error('header name must be a non-empty string'); + } + + const key = utils$1.findKey(self, lHeader); + + if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { + self[key || _header] = normalizeValue(_value); + } + } + + const setHeaders = (headers, _rewrite) => + utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + + if (utils$1.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else if (utils$1.isHeaders(header)) { + for (const [key, value] of header.entries()) { + setHeader(value, key, rewrite); + } + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + + return this; + } + + get(header, parser) { + header = normalizeHeader(header); + + if (header) { + const key = utils$1.findKey(this, header); + + if (key) { + const value = this[key]; + + if (!parser) { + return value; + } + + if (parser === true) { + return parseTokens(value); + } + + if (utils$1.isFunction(parser)) { + return parser.call(this, value, key); + } + + if (utils$1.isRegExp(parser)) { + return parser.exec(value); + } + + throw new TypeError('parser must be boolean|regexp|function'); + } + } + } + + has(header, matcher) { + header = normalizeHeader(header); + + if (header) { + const key = utils$1.findKey(this, header); + + return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + } + + return false; + } + + delete(header, matcher) { + const self = this; + let deleted = false; + + function deleteHeader(_header) { + _header = normalizeHeader(_header); + + if (_header) { + const key = utils$1.findKey(self, _header); + + if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { + delete self[key]; + + deleted = true; + } + } + } + + if (utils$1.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + + return deleted; + } + + clear(matcher) { + const keys = Object.keys(this); + let i = keys.length; + let deleted = false; + + while (i--) { + const key = keys[i]; + if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + + return deleted; + } + + normalize(format) { + const self = this; + const headers = {}; + + utils$1.forEach(this, (value, header) => { + const key = utils$1.findKey(headers, header); + + if (key) { + self[key] = normalizeValue(value); + delete self[header]; + return; + } + + const normalized = format ? formatHeader(header) : String(header).trim(); + + if (normalized !== header) { + delete self[header]; + } + + self[normalized] = normalizeValue(value); + + headers[normalized] = true; + }); + + return this; + } + + concat(...targets) { + return this.constructor.concat(this, ...targets); + } + + toJSON(asStrings) { + const obj = Object.create(null); + + utils$1.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value); + }); + + return obj; + } + + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n'); + } + + get [Symbol.toStringTag]() { + return 'AxiosHeaders'; + } + + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + + static concat(first, ...targets) { + const computed = new this(first); + + targets.forEach((target) => computed.set(target)); + + return computed; + } + + static accessor(header) { + const internals = this[$internals] = (this[$internals] = { + accessors: {} + }); + + const accessors = internals.accessors; + const prototype = this.prototype; + + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); + + if (!accessors[lHeader]) { + buildAccessors(prototype, _header); + accessors[lHeader] = true; + } + } + + utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + + return this; + } +} + +AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); + +// reserved names hotfix +utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } + } +}); + +utils$1.freezeMethods(AxiosHeaders); + +const AxiosHeaders$1 = AxiosHeaders; + +/** + * Transform the data for a request or a response + * + * @param {Array|Function} fns A single function or Array of functions + * @param {?Object} response The response object + * + * @returns {*} The resulting transformed data + */ +function transformData(fns, response) { + const config = this || defaults$1; + const context = response || config; + const headers = AxiosHeaders$1.from(context.headers); + let data = context.data; + + utils$1.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); + }); + + headers.normalize(); + + return data; +} + +function isCancel(value) { + return !!(value && value.__CANCEL__); +} + +/** + * A `CanceledError` is an object that is thrown when an operation is canceled. + * + * @param {string=} message The message. + * @param {Object=} config The config. + * @param {Object=} request The request. + * + * @returns {CanceledError} The created error. + */ +function CanceledError(message, config, request) { + // eslint-disable-next-line no-eq-null,eqeqeq + AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); + this.name = 'CanceledError'; +} + +utils$1.inherits(CanceledError, AxiosError, { + __CANCEL__: true +}); + +/** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + * + * @returns {object} The response. + */ +function settle(resolve, reject, response) { + const validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new AxiosError( + 'Request failed with status code ' + response.status, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } +} + +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); +} + +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * + * @returns {string} The combined URL + */ +function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +} + +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * + * @returns {string} The combined full path + */ +function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +} + +const VERSION = "1.7.9"; + +function parseProtocol(url) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ''; +} + +const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; + +/** + * Parse data uri to a Buffer or Blob + * + * @param {String} uri + * @param {?Boolean} asBlob + * @param {?Object} options + * @param {?Function} options.Blob + * + * @returns {Buffer|Blob} + */ +function fromDataURI(uri, asBlob, options) { + const _Blob = options && options.Blob || platform.classes.Blob; + const protocol = parseProtocol(uri); + + if (asBlob === undefined && _Blob) { + asBlob = true; + } + + if (protocol === 'data') { + uri = protocol.length ? uri.slice(protocol.length + 1) : uri; + + const match = DATA_URL_PATTERN.exec(uri); + + if (!match) { + throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL); + } + + const mime = match[1]; + const isBase64 = match[2]; + const body = match[3]; + const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8'); + + if (asBlob) { + if (!_Blob) { + throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT); + } + + return new _Blob([buffer], {type: mime}); + } + + return buffer; + } + + throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT); +} + +const kInternals = Symbol('internals'); + +class AxiosTransformStream extends stream__default["default"].Transform{ + constructor(options) { + options = utils$1.toFlatObject(options, { + maxRate: 0, + chunkSize: 64 * 1024, + minChunkSize: 100, + timeWindow: 500, + ticksRate: 2, + samplesCount: 15 + }, null, (prop, source) => { + return !utils$1.isUndefined(source[prop]); + }); + + super({ + readableHighWaterMark: options.chunkSize + }); + + const internals = this[kInternals] = { + timeWindow: options.timeWindow, + chunkSize: options.chunkSize, + maxRate: options.maxRate, + minChunkSize: options.minChunkSize, + bytesSeen: 0, + isCaptured: false, + notifiedBytesLoaded: 0, + ts: Date.now(), + bytes: 0, + onReadCallback: null + }; + + this.on('newListener', event => { + if (event === 'progress') { + if (!internals.isCaptured) { + internals.isCaptured = true; + } + } + }); + } + + _read(size) { + const internals = this[kInternals]; + + if (internals.onReadCallback) { + internals.onReadCallback(); + } + + return super._read(size); + } + + _transform(chunk, encoding, callback) { + const internals = this[kInternals]; + const maxRate = internals.maxRate; + + const readableHighWaterMark = this.readableHighWaterMark; + + const timeWindow = internals.timeWindow; + + const divider = 1000 / timeWindow; + const bytesThreshold = (maxRate / divider); + const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; + + const pushChunk = (_chunk, _callback) => { + const bytes = Buffer.byteLength(_chunk); + internals.bytesSeen += bytes; + internals.bytes += bytes; + + internals.isCaptured && this.emit('progress', internals.bytesSeen); + + if (this.push(_chunk)) { + process.nextTick(_callback); + } else { + internals.onReadCallback = () => { + internals.onReadCallback = null; + process.nextTick(_callback); + }; + } + }; + + const transformChunk = (_chunk, _callback) => { + const chunkSize = Buffer.byteLength(_chunk); + let chunkRemainder = null; + let maxChunkSize = readableHighWaterMark; + let bytesLeft; + let passed = 0; + + if (maxRate) { + const now = Date.now(); + + if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) { + internals.ts = now; + bytesLeft = bytesThreshold - internals.bytes; + internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; + passed = 0; + } + + bytesLeft = bytesThreshold - internals.bytes; + } + + if (maxRate) { + if (bytesLeft <= 0) { + // next time window + return setTimeout(() => { + _callback(null, _chunk); + }, timeWindow - passed); + } + + if (bytesLeft < maxChunkSize) { + maxChunkSize = bytesLeft; + } + } + + if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) { + chunkRemainder = _chunk.subarray(maxChunkSize); + _chunk = _chunk.subarray(0, maxChunkSize); + } + + pushChunk(_chunk, chunkRemainder ? () => { + process.nextTick(_callback, null, chunkRemainder); + } : _callback); + }; + + transformChunk(chunk, function transformNextChunk(err, _chunk) { + if (err) { + return callback(err); + } + + if (_chunk) { + transformChunk(_chunk, transformNextChunk); + } else { + callback(null); + } + }); + } +} + +const AxiosTransformStream$1 = AxiosTransformStream; + +const {asyncIterator} = Symbol; + +const readBlob = async function* (blob) { + if (blob.stream) { + yield* blob.stream(); + } else if (blob.arrayBuffer) { + yield await blob.arrayBuffer(); + } else if (blob[asyncIterator]) { + yield* blob[asyncIterator](); + } else { + yield blob; + } +}; + +const readBlob$1 = readBlob; + +const BOUNDARY_ALPHABET = utils$1.ALPHABET.ALPHA_DIGIT + '-_'; + +const textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : new util__default["default"].TextEncoder(); + +const CRLF = '\r\n'; +const CRLF_BYTES = textEncoder.encode(CRLF); +const CRLF_BYTES_COUNT = 2; + +class FormDataPart { + constructor(name, value) { + const {escapeName} = this.constructor; + const isStringValue = utils$1.isString(value); + + let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${ + !isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : '' + }${CRLF}`; + + if (isStringValue) { + value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); + } else { + headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`; + } + + this.headers = textEncoder.encode(headers + CRLF); + + this.contentLength = isStringValue ? value.byteLength : value.size; + + this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT; + + this.name = name; + this.value = value; + } + + async *encode(){ + yield this.headers; + + const {value} = this; + + if(utils$1.isTypedArray(value)) { + yield value; + } else { + yield* readBlob$1(value); + } + + yield CRLF_BYTES; + } + + static escapeName(name) { + return String(name).replace(/[\r\n"]/g, (match) => ({ + '\r' : '%0D', + '\n' : '%0A', + '"' : '%22', + }[match])); + } +} + +const formDataToStream = (form, headersHandler, options) => { + const { + tag = 'form-data-boundary', + size = 25, + boundary = tag + '-' + utils$1.generateString(size, BOUNDARY_ALPHABET) + } = options || {}; + + if(!utils$1.isFormData(form)) { + throw TypeError('FormData instance required'); + } + + if (boundary.length < 1 || boundary.length > 70) { + throw Error('boundary must be 10-70 characters long') + } + + const boundaryBytes = textEncoder.encode('--' + boundary + CRLF); + const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF + CRLF); + let contentLength = footerBytes.byteLength; + + const parts = Array.from(form.entries()).map(([name, value]) => { + const part = new FormDataPart(name, value); + contentLength += part.size; + return part; + }); + + contentLength += boundaryBytes.byteLength * parts.length; + + contentLength = utils$1.toFiniteNumber(contentLength); + + const computedHeaders = { + 'Content-Type': `multipart/form-data; boundary=${boundary}` + }; + + if (Number.isFinite(contentLength)) { + computedHeaders['Content-Length'] = contentLength; + } + + headersHandler && headersHandler(computedHeaders); + + return stream.Readable.from((async function *() { + for(const part of parts) { + yield boundaryBytes; + yield* part.encode(); + } + + yield footerBytes; + })()); +}; + +const formDataToStream$1 = formDataToStream; + +class ZlibHeaderTransformStream extends stream__default["default"].Transform { + __transform(chunk, encoding, callback) { + this.push(chunk); + callback(); + } + + _transform(chunk, encoding, callback) { + if (chunk.length !== 0) { + this._transform = this.__transform; + + // Add Default Compression headers if no zlib headers are present + if (chunk[0] !== 120) { // Hex: 78 + const header = Buffer.alloc(2); + header[0] = 120; // Hex: 78 + header[1] = 156; // Hex: 9C + this.push(header, encoding); + } + } + + this.__transform(chunk, encoding, callback); + } +} + +const ZlibHeaderTransformStream$1 = ZlibHeaderTransformStream; + +const callbackify = (fn, reducer) => { + return utils$1.isAsyncFn(fn) ? function (...args) { + const cb = args.pop(); + fn.apply(this, args).then((value) => { + try { + reducer ? cb(null, ...reducer(value)) : cb(null, value); + } catch (err) { + cb(err); + } + }, cb); + } : fn; +}; + +const callbackify$1 = callbackify; + +/** + * Calculate data maxRate + * @param {Number} [samplesCount= 10] + * @param {Number} [min= 1000] + * @returns {Function} + */ +function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + + min = min !== undefined ? min : 1000; + + return function push(chunkLength) { + const now = Date.now(); + + const startedAt = timestamps[tail]; + + if (!firstSampleTS) { + firstSampleTS = now; + } + + bytes[head] = chunkLength; + timestamps[head] = now; + + let i = tail; + let bytesCount = 0; + + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + + head = (head + 1) % samplesCount; + + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + + if (now - firstSampleTS < min) { + return; + } + + const passed = startedAt && now - startedAt; + + return passed ? Math.round(bytesCount * 1000 / passed) : undefined; + }; +} + +/** + * Throttle decorator + * @param {Function} fn + * @param {Number} freq + * @return {Function} + */ +function throttle(fn, freq) { + let timestamp = 0; + let threshold = 1000 / freq; + let lastArgs; + let timer; + + const invoke = (args, now = Date.now()) => { + timestamp = now; + lastArgs = null; + if (timer) { + clearTimeout(timer); + timer = null; + } + fn.apply(null, args); + }; + + const throttled = (...args) => { + const now = Date.now(); + const passed = now - timestamp; + if ( passed >= threshold) { + invoke(args, now); + } else { + lastArgs = args; + if (!timer) { + timer = setTimeout(() => { + timer = null; + invoke(lastArgs); + }, threshold - passed); + } + } + }; + + const flush = () => lastArgs && invoke(lastArgs); + + return [throttled, flush]; +} + +const progressEventReducer = (listener, isDownloadStream, freq = 3) => { + let bytesNotified = 0; + const _speedometer = speedometer(50, 250); + + return throttle(e => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : undefined; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange = loaded <= total; + + bytesNotified = loaded; + + const data = { + loaded, + total, + progress: total ? (loaded / total) : undefined, + bytes: progressBytes, + rate: rate ? rate : undefined, + estimated: rate && total && inRange ? (total - loaded) / rate : undefined, + event: e, + lengthComputable: total != null, + [isDownloadStream ? 'download' : 'upload']: true + }; + + listener(data); + }, freq); +}; + +const progressEventDecorator = (total, throttled) => { + const lengthComputable = total != null; + + return [(loaded) => throttled[0]({ + lengthComputable, + total, + loaded + }), throttled[1]]; +}; + +const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args)); + +const zlibOptions = { + flush: zlib__default["default"].constants.Z_SYNC_FLUSH, + finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH +}; + +const brotliOptions = { + flush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH +}; + +const isBrotliSupported = utils$1.isFunction(zlib__default["default"].createBrotliDecompress); + +const {http: httpFollow, https: httpsFollow} = followRedirects__default["default"]; + +const isHttps = /https:?/; + +const supportedProtocols = platform.protocols.map(protocol => { + return protocol + ':'; +}); + +const flushOnFinish = (stream, [throttled, flush]) => { + stream + .on('end', flush) + .on('error', flush); + + return throttled; +}; + +/** + * If the proxy or config beforeRedirects functions are defined, call them with the options + * object. + * + * @param {Object} options - The options object that was passed to the request. + * + * @returns {Object} + */ +function dispatchBeforeRedirect(options, responseDetails) { + if (options.beforeRedirects.proxy) { + options.beforeRedirects.proxy(options); + } + if (options.beforeRedirects.config) { + options.beforeRedirects.config(options, responseDetails); + } +} + +/** + * If the proxy or config afterRedirects functions are defined, call them with the options + * + * @param {http.ClientRequestArgs} options + * @param {AxiosProxyConfig} configProxy configuration from Axios options object + * @param {string} location + * + * @returns {http.ClientRequestArgs} + */ +function setProxy(options, configProxy, location) { + let proxy = configProxy; + if (!proxy && proxy !== false) { + const proxyUrl = proxyFromEnv__default["default"].getProxyForUrl(location); + if (proxyUrl) { + proxy = new URL(proxyUrl); + } + } + if (proxy) { + // Basic proxy authorization + if (proxy.username) { + proxy.auth = (proxy.username || '') + ':' + (proxy.password || ''); + } + + if (proxy.auth) { + // Support proxy auth object form + if (proxy.auth.username || proxy.auth.password) { + proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || ''); + } + const base64 = Buffer + .from(proxy.auth, 'utf8') + .toString('base64'); + options.headers['Proxy-Authorization'] = 'Basic ' + base64; + } + + options.headers.host = options.hostname + (options.port ? ':' + options.port : ''); + const proxyHost = proxy.hostname || proxy.host; + options.hostname = proxyHost; + // Replace 'host' since options is not a URL object + options.host = proxyHost; + options.port = proxy.port; + options.path = location; + if (proxy.protocol) { + options.protocol = proxy.protocol.includes(':') ? proxy.protocol : `${proxy.protocol}:`; + } + } + + options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) { + // Configure proxy for redirected request, passing the original config proxy to apply + // the exact same logic as if the redirected request was performed by axios directly. + setProxy(redirectOptions, configProxy, redirectOptions.href); + }; +} + +const isHttpAdapterSupported = typeof process !== 'undefined' && utils$1.kindOf(process) === 'process'; + +// temporary hotfix + +const wrapAsync = (asyncExecutor) => { + return new Promise((resolve, reject) => { + let onDone; + let isDone; + + const done = (value, isRejected) => { + if (isDone) return; + isDone = true; + onDone && onDone(value, isRejected); + }; + + const _resolve = (value) => { + done(value); + resolve(value); + }; + + const _reject = (reason) => { + done(reason, true); + reject(reason); + }; + + asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject); + }) +}; + +const resolveFamily = ({address, family}) => { + if (!utils$1.isString(address)) { + throw TypeError('address must be a string'); + } + return ({ + address, + family: family || (address.indexOf('.') < 0 ? 6 : 4) + }); +}; + +const buildAddressEntry = (address, family) => resolveFamily(utils$1.isObject(address) ? address : {address, family}); + +/*eslint consistent-return:0*/ +const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { + return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) { + let {data, lookup, family} = config; + const {responseType, responseEncoding} = config; + const method = config.method.toUpperCase(); + let isDone; + let rejected = false; + let req; + + if (lookup) { + const _lookup = callbackify$1(lookup, (value) => utils$1.isArray(value) ? value : [value]); + // hotfix to support opt.all option which is required for node 20.x + lookup = (hostname, opt, cb) => { + _lookup(hostname, opt, (err, arg0, arg1) => { + if (err) { + return cb(err); + } + + const addresses = utils$1.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)]; + + opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); + }); + }; + } + + // temporary internal emitter until the AxiosRequest class will be implemented + const emitter = new events.EventEmitter(); + + const onFinished = () => { + if (config.cancelToken) { + config.cancelToken.unsubscribe(abort); + } + + if (config.signal) { + config.signal.removeEventListener('abort', abort); + } + + emitter.removeAllListeners(); + }; + + onDone((value, isRejected) => { + isDone = true; + if (isRejected) { + rejected = true; + onFinished(); + } + }); + + function abort(reason) { + emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason); + } + + emitter.once('abort', reject); + + if (config.cancelToken || config.signal) { + config.cancelToken && config.cancelToken.subscribe(abort); + if (config.signal) { + config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort); + } + } + + // Parse url + const fullPath = buildFullPath(config.baseURL, config.url); + const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined); + const protocol = parsed.protocol || supportedProtocols[0]; + + if (protocol === 'data:') { + let convertedData; + + if (method !== 'GET') { + return settle(resolve, reject, { + status: 405, + statusText: 'method not allowed', + headers: {}, + config + }); + } + + try { + convertedData = fromDataURI(config.url, responseType === 'blob', { + Blob: config.env && config.env.Blob + }); + } catch (err) { + throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config); + } + + if (responseType === 'text') { + convertedData = convertedData.toString(responseEncoding); + + if (!responseEncoding || responseEncoding === 'utf8') { + convertedData = utils$1.stripBOM(convertedData); + } + } else if (responseType === 'stream') { + convertedData = stream__default["default"].Readable.from(convertedData); + } + + return settle(resolve, reject, { + data: convertedData, + status: 200, + statusText: 'OK', + headers: new AxiosHeaders$1(), + config + }); + } + + if (supportedProtocols.indexOf(protocol) === -1) { + return reject(new AxiosError( + 'Unsupported protocol ' + protocol, + AxiosError.ERR_BAD_REQUEST, + config + )); + } + + const headers = AxiosHeaders$1.from(config.headers).normalize(); + + // Set User-Agent (required by some servers) + // See https://github.com/axios/axios/issues/69 + // User-Agent is specified; handle case where no UA header is desired + // Only set header if it hasn't been set in config + headers.set('User-Agent', 'axios/' + VERSION, false); + + const {onUploadProgress, onDownloadProgress} = config; + const maxRate = config.maxRate; + let maxUploadRate = undefined; + let maxDownloadRate = undefined; + + // support for spec compliant FormData objects + if (utils$1.isSpecCompliantForm(data)) { + const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); + + data = formDataToStream$1(data, (formHeaders) => { + headers.set(formHeaders); + }, { + tag: `axios-${VERSION}-boundary`, + boundary: userBoundary && userBoundary[1] || undefined + }); + // support for https://www.npmjs.com/package/form-data api + } else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders)) { + headers.set(data.getHeaders()); + + if (!headers.hasContentLength()) { + try { + const knownLength = await util__default["default"].promisify(data.getLength).call(data); + Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength); + /*eslint no-empty:0*/ + } catch (e) { + } + } + } else if (utils$1.isBlob(data) || utils$1.isFile(data)) { + data.size && headers.setContentType(data.type || 'application/octet-stream'); + headers.setContentLength(data.size || 0); + data = stream__default["default"].Readable.from(readBlob$1(data)); + } else if (data && !utils$1.isStream(data)) { + if (Buffer.isBuffer(data)) ; else if (utils$1.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils$1.isString(data)) { + data = Buffer.from(data, 'utf-8'); + } else { + return reject(new AxiosError( + 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', + AxiosError.ERR_BAD_REQUEST, + config + )); + } + + // Add Content-Length header if data exists + headers.setContentLength(data.length, false); + + if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) { + return reject(new AxiosError( + 'Request body larger than maxBodyLength limit', + AxiosError.ERR_BAD_REQUEST, + config + )); + } + } + + const contentLength = utils$1.toFiniteNumber(headers.getContentLength()); + + if (utils$1.isArray(maxRate)) { + maxUploadRate = maxRate[0]; + maxDownloadRate = maxRate[1]; + } else { + maxUploadRate = maxDownloadRate = maxRate; + } + + if (data && (onUploadProgress || maxUploadRate)) { + if (!utils$1.isStream(data)) { + data = stream__default["default"].Readable.from(data, {objectMode: false}); + } + + data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({ + maxRate: utils$1.toFiniteNumber(maxUploadRate) + })], utils$1.noop); + + onUploadProgress && data.on('progress', flushOnFinish( + data, + progressEventDecorator( + contentLength, + progressEventReducer(asyncDecorator(onUploadProgress), false, 3) + ) + )); + } + + // HTTP basic authentication + let auth = undefined; + if (config.auth) { + const username = config.auth.username || ''; + const password = config.auth.password || ''; + auth = username + ':' + password; + } + + if (!auth && parsed.username) { + const urlUsername = parsed.username; + const urlPassword = parsed.password; + auth = urlUsername + ':' + urlPassword; + } + + auth && headers.delete('authorization'); + + let path; + + try { + path = buildURL( + parsed.pathname + parsed.search, + config.params, + config.paramsSerializer + ).replace(/^\?/, ''); + } catch (err) { + const customErr = new Error(err.message); + customErr.config = config; + customErr.url = config.url; + customErr.exists = true; + return reject(customErr); + } + + headers.set( + 'Accept-Encoding', + 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false + ); + + const options = { + path, + method: method, + headers: headers.toJSON(), + agents: { http: config.httpAgent, https: config.httpsAgent }, + auth, + protocol, + family, + beforeRedirect: dispatchBeforeRedirect, + beforeRedirects: {} + }; + + // cacheable-lookup integration hotfix + !utils$1.isUndefined(lookup) && (options.lookup = lookup); + + if (config.socketPath) { + options.socketPath = config.socketPath; + } else { + options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname; + options.port = parsed.port; + setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); + } + + let transport; + const isHttpsRequest = isHttps.test(options.protocol); + options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; + if (config.transport) { + transport = config.transport; + } else if (config.maxRedirects === 0) { + transport = isHttpsRequest ? https__default["default"] : http__default["default"]; + } else { + if (config.maxRedirects) { + options.maxRedirects = config.maxRedirects; + } + if (config.beforeRedirect) { + options.beforeRedirects.config = config.beforeRedirect; + } + transport = isHttpsRequest ? httpsFollow : httpFollow; + } + + if (config.maxBodyLength > -1) { + options.maxBodyLength = config.maxBodyLength; + } else { + // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited + options.maxBodyLength = Infinity; + } + + if (config.insecureHTTPParser) { + options.insecureHTTPParser = config.insecureHTTPParser; + } + + // Create the request + req = transport.request(options, function handleResponse(res) { + if (req.destroyed) return; + + const streams = [res]; + + const responseLength = +res.headers['content-length']; + + if (onDownloadProgress || maxDownloadRate) { + const transformStream = new AxiosTransformStream$1({ + maxRate: utils$1.toFiniteNumber(maxDownloadRate) + }); + + onDownloadProgress && transformStream.on('progress', flushOnFinish( + transformStream, + progressEventDecorator( + responseLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) + ) + )); + + streams.push(transformStream); + } + + // decompress the response body transparently if required + let responseStream = res; + + // return the last request in case of redirects + const lastRequest = res.req || req; + + // if decompress disabled we should not decompress + if (config.decompress !== false && res.headers['content-encoding']) { + // if no content, but headers still say that it is encoded, + // remove the header not confuse downstream operations + if (method === 'HEAD' || res.statusCode === 204) { + delete res.headers['content-encoding']; + } + + switch ((res.headers['content-encoding'] || '').toLowerCase()) { + /*eslint default-case:0*/ + case 'gzip': + case 'x-gzip': + case 'compress': + case 'x-compress': + // add the unzipper to the body stream processing pipeline + streams.push(zlib__default["default"].createUnzip(zlibOptions)); + + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; + case 'deflate': + streams.push(new ZlibHeaderTransformStream$1()); + + // add the unzipper to the body stream processing pipeline + streams.push(zlib__default["default"].createUnzip(zlibOptions)); + + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; + case 'br': + if (isBrotliSupported) { + streams.push(zlib__default["default"].createBrotliDecompress(brotliOptions)); + delete res.headers['content-encoding']; + } + } + } + + responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils$1.noop) : streams[0]; + + const offListeners = stream__default["default"].finished(responseStream, () => { + offListeners(); + onFinished(); + }); + + const response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: new AxiosHeaders$1(res.headers), + config, + request: lastRequest + }; + + if (responseType === 'stream') { + response.data = responseStream; + settle(resolve, reject, response); + } else { + const responseBuffer = []; + let totalResponseBytes = 0; + + responseStream.on('data', function handleStreamData(chunk) { + responseBuffer.push(chunk); + totalResponseBytes += chunk.length; + + // make sure the content length is not over the maxContentLength if specified + if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) { + // stream.destroy() emit aborted event before calling reject() on Node.js v16 + rejected = true; + responseStream.destroy(); + reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, config, lastRequest)); + } + }); + + responseStream.on('aborted', function handlerStreamAborted() { + if (rejected) { + return; + } + + const err = new AxiosError( + 'stream has been aborted', + AxiosError.ERR_BAD_RESPONSE, + config, + lastRequest + ); + responseStream.destroy(err); + reject(err); + }); + + responseStream.on('error', function handleStreamError(err) { + if (req.destroyed) return; + reject(AxiosError.from(err, null, config, lastRequest)); + }); + + responseStream.on('end', function handleStreamEnd() { + try { + let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); + if (responseType !== 'arraybuffer') { + responseData = responseData.toString(responseEncoding); + if (!responseEncoding || responseEncoding === 'utf8') { + responseData = utils$1.stripBOM(responseData); + } + } + response.data = responseData; + } catch (err) { + return reject(AxiosError.from(err, null, config, response.request, response)); + } + settle(resolve, reject, response); + }); + } + + emitter.once('abort', err => { + if (!responseStream.destroyed) { + responseStream.emit('error', err); + responseStream.destroy(); + } + }); + }); + + emitter.once('abort', err => { + reject(err); + req.destroy(err); + }); + + // Handle errors + req.on('error', function handleRequestError(err) { + // @todo remove + // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return; + reject(AxiosError.from(err, null, config, req)); + }); + + // set tcp keep alive to prevent drop connection by peer + req.on('socket', function handleRequestSocket(socket) { + // default interval of sending ack packet is 1 minute + socket.setKeepAlive(true, 1000 * 60); + }); + + // Handle request timeout + if (config.timeout) { + // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types. + const timeout = parseInt(config.timeout, 10); + + if (Number.isNaN(timeout)) { + reject(new AxiosError( + 'error trying to parse `config.timeout` to int', + AxiosError.ERR_BAD_OPTION_VALUE, + config, + req + )); + + return; + } + + // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. + // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. + // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. + // And then these socket which be hang up will devouring CPU little by little. + // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. + req.setTimeout(timeout, function handleRequestTimeout() { + if (isDone) return; + let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; + const transitional = config.transitional || transitionalDefaults; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + req + )); + abort(); + }); + } + + + // Send the request + if (utils$1.isStream(data)) { + let ended = false; + let errored = false; + + data.on('end', () => { + ended = true; + }); + + data.once('error', err => { + errored = true; + req.destroy(err); + }); + + data.on('close', () => { + if (!ended && !errored) { + abort(new CanceledError('Request stream has been aborted', config, req)); + } + }); + + data.pipe(req); + } else { + req.end(data); + } + }); +}; + +const isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => { + url = new URL(url, platform.origin); + + return ( + origin.protocol === url.protocol && + origin.host === url.host && + (isMSIE || origin.port === url.port) + ); +})( + new URL(platform.origin), + platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) +) : () => true; + +const cookies = platform.hasStandardBrowserEnv ? + + // Standard browser envs support document.cookie + { + write(name, value, expires, path, domain, secure) { + const cookie = [name + '=' + encodeURIComponent(value)]; + + utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString()); + + utils$1.isString(path) && cookie.push('path=' + path); + + utils$1.isString(domain) && cookie.push('domain=' + domain); + + secure === true && cookie.push('secure'); + + document.cookie = cookie.join('; '); + }, + + read(name) { + const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, + + remove(name) { + this.write(name, '', Date.now() - 86400000); + } + } + + : + + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() {}, + read() { + return null; + }, + remove() {} + }; + +const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; + +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * + * @returns {Object} New object resulting from merging config2 to config1 + */ +function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + const config = {}; + + function getMergedValue(target, source, prop, caseless) { + if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { + return utils$1.merge.call({caseless}, target, source); + } else if (utils$1.isPlainObject(source)) { + return utils$1.merge({}, source); + } else if (utils$1.isArray(source)) { + return source.slice(); + } + return source; + } + + // eslint-disable-next-line consistent-return + function mergeDeepProperties(a, b, prop , caseless) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(a, b, prop , caseless); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(undefined, a, prop , caseless); + } + } + + // eslint-disable-next-line consistent-return + function valueFromConfig2(a, b) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(undefined, b); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(a, b) { + if (!utils$1.isUndefined(b)) { + return getMergedValue(undefined, b); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(undefined, a); + } + } + + // eslint-disable-next-line consistent-return + function mergeDirectKeys(a, b, prop) { + if (prop in config2) { + return getMergedValue(a, b); + } else if (prop in config1) { + return getMergedValue(undefined, a); + } + } + + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true) + }; + + utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + const merge = mergeMap[prop] || mergeDeepProperties; + const configValue = merge(config1[prop], config2[prop], prop); + (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); + + return config; +} + +const resolveConfig = (config) => { + const newConfig = mergeConfig({}, config); + + let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig; + + newConfig.headers = headers = AxiosHeaders$1.from(headers); + + newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer); + + // HTTP basic authentication + if (auth) { + headers.set('Authorization', 'Basic ' + + btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : '')) + ); + } + + let contentType; + + if (utils$1.isFormData(data)) { + if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { + headers.setContentType(undefined); // Let the browser set it + } else if ((contentType = headers.getContentType()) !== false) { + // fix semicolon duplication issue for ReactNative FormData implementation + const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : []; + headers.setContentType([type || 'multipart/form-data', ...tokens].join('; ')); + } + } + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + + if (platform.hasStandardBrowserEnv) { + withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); + + if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) { + // Add xsrf header + const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); + + if (xsrfValue) { + headers.set(xsrfHeaderName, xsrfValue); + } + } + } + + return newConfig; +}; + +const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; + +const xhrAdapter = isXHRAdapterSupported && function (config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + const _config = resolveConfig(config); + let requestData = _config.data; + const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize(); + let {responseType, onUploadProgress, onDownloadProgress} = _config; + let onCanceled; + let uploadThrottled, downloadThrottled; + let flushUpload, flushDownload; + + function done() { + flushUpload && flushUpload(); // flush events + flushDownload && flushDownload(); // flush events + + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + + _config.signal && _config.signal.removeEventListener('abort', onCanceled); + } + + let request = new XMLHttpRequest(); + + request.open(_config.method.toUpperCase(), _config.url, true); + + // Set the request timeout in MS + request.timeout = _config.timeout; + + function onloadend() { + if (!request) { + return; + } + // Prepare the response + const responseHeaders = AxiosHeaders$1.from( + 'getAllResponseHeaders' in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === 'text' || responseType === 'json' ? + request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config, + request + }; + + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + + // Clean up request + request = null; + } + + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded'; + const transitional = _config.transitional || transitionalDefaults; + if (_config.timeoutErrorMessage) { + timeoutErrorMessage = _config.timeoutErrorMessage; + } + reject(new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + request)); + + // Clean up request + request = null; + }; + + // Remove Content-Type if data is undefined + requestData === undefined && requestHeaders.setContentType(null); + + // Add headers to the request + if ('setRequestHeader' in request) { + utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + + // Add withCredentials to request if needed + if (!utils$1.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; + } + + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = _config.responseType; + } + + // Handle progress if needed + if (onDownloadProgress) { + ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true)); + request.addEventListener('progress', downloadThrottled); + } + + // Not all browsers support upload events + if (onUploadProgress && request.upload) { + ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress)); + + request.upload.addEventListener('progress', uploadThrottled); + + request.upload.addEventListener('loadend', flushUpload); + } + + if (_config.cancelToken || _config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = cancel => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); + request.abort(); + request = null; + }; + + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled); + } + } + + const protocol = parseProtocol(_config.url); + + if (protocol && platform.protocols.indexOf(protocol) === -1) { + reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); + return; + } + + + // Send the request + request.send(requestData || null); + }); +}; + +const composeSignals = (signals, timeout) => { + const {length} = (signals = signals ? signals.filter(Boolean) : []); + + if (timeout || length) { + let controller = new AbortController(); + + let aborted; + + const onabort = function (reason) { + if (!aborted) { + aborted = true; + unsubscribe(); + const err = reason instanceof Error ? reason : this.reason; + controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err)); + } + }; + + let timer = timeout && setTimeout(() => { + timer = null; + onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT)); + }, timeout); + + const unsubscribe = () => { + if (signals) { + timer && clearTimeout(timer); + timer = null; + signals.forEach(signal => { + signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort); + }); + signals = null; + } + }; + + signals.forEach((signal) => signal.addEventListener('abort', onabort)); + + const {signal} = controller; + + signal.unsubscribe = () => utils$1.asap(unsubscribe); + + return signal; + } +}; + +const composeSignals$1 = composeSignals; + +const streamChunk = function* (chunk, chunkSize) { + let len = chunk.byteLength; + + if (!chunkSize || len < chunkSize) { + yield chunk; + return; + } + + let pos = 0; + let end; + + while (pos < len) { + end = pos + chunkSize; + yield chunk.slice(pos, end); + pos = end; + } +}; + +const readBytes = async function* (iterable, chunkSize) { + for await (const chunk of readStream(iterable)) { + yield* streamChunk(chunk, chunkSize); + } +}; + +const readStream = async function* (stream) { + if (stream[Symbol.asyncIterator]) { + yield* stream; + return; + } + + const reader = stream.getReader(); + try { + for (;;) { + const {done, value} = await reader.read(); + if (done) { + break; + } + yield value; + } + } finally { + await reader.cancel(); + } +}; + +const trackStream = (stream, chunkSize, onProgress, onFinish) => { + const iterator = readBytes(stream, chunkSize); + + let bytes = 0; + let done; + let _onFinish = (e) => { + if (!done) { + done = true; + onFinish && onFinish(e); + } + }; + + return new ReadableStream({ + async pull(controller) { + try { + const {done, value} = await iterator.next(); + + if (done) { + _onFinish(); + controller.close(); + return; + } + + let len = value.byteLength; + if (onProgress) { + let loadedBytes = bytes += len; + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); + } catch (err) { + _onFinish(err); + throw err; + } + }, + cancel(reason) { + _onFinish(reason); + return iterator.return(); + } + }, { + highWaterMark: 2 + }) +}; + +const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function'; +const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function'; + +// used only inside the fetch adapter +const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? + ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : + async (str) => new Uint8Array(await new Response(str).arrayBuffer()) +); + +const test = (fn, ...args) => { + try { + return !!fn(...args); + } catch (e) { + return false + } +}; + +const supportsRequestStream = isReadableStreamSupported && test(() => { + let duplexAccessed = false; + + const hasContentType = new Request(platform.origin, { + body: new ReadableStream(), + method: 'POST', + get duplex() { + duplexAccessed = true; + return 'half'; + }, + }).headers.has('Content-Type'); + + return duplexAccessed && !hasContentType; +}); + +const DEFAULT_CHUNK_SIZE = 64 * 1024; + +const supportsResponseStream = isReadableStreamSupported && + test(() => utils$1.isReadableStream(new Response('').body)); + + +const resolvers = { + stream: supportsResponseStream && ((res) => res.body) +}; + +isFetchSupported && (((res) => { + ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => { + !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() : + (_, config) => { + throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config); + }); + }); +})(new Response)); + +const getBodyLength = async (body) => { + if (body == null) { + return 0; + } + + if(utils$1.isBlob(body)) { + return body.size; + } + + if(utils$1.isSpecCompliantForm(body)) { + const _request = new Request(platform.origin, { + method: 'POST', + body, + }); + return (await _request.arrayBuffer()).byteLength; + } + + if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) { + return body.byteLength; + } + + if(utils$1.isURLSearchParams(body)) { + body = body + ''; + } + + if(utils$1.isString(body)) { + return (await encodeText(body)).byteLength; + } +}; + +const resolveBodyLength = async (headers, body) => { + const length = utils$1.toFiniteNumber(headers.getContentLength()); + + return length == null ? getBodyLength(body) : length; +}; + +const fetchAdapter = isFetchSupported && (async (config) => { + let { + url, + method, + data, + signal, + cancelToken, + timeout, + onDownloadProgress, + onUploadProgress, + responseType, + headers, + withCredentials = 'same-origin', + fetchOptions + } = resolveConfig(config); + + responseType = responseType ? (responseType + '').toLowerCase() : 'text'; + + let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + + let request; + + const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { + composedSignal.unsubscribe(); + }); + + let requestContentLength; + + try { + if ( + onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && + (requestContentLength = await resolveBodyLength(headers, data)) !== 0 + ) { + let _request = new Request(url, { + method: 'POST', + body: data, + duplex: "half" + }); + + let contentTypeHeader; + + if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { + headers.setContentType(contentTypeHeader); + } + + if (_request.body) { + const [onProgress, flush] = progressEventDecorator( + requestContentLength, + progressEventReducer(asyncDecorator(onUploadProgress)) + ); + + data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); + } + } + + if (!utils$1.isString(withCredentials)) { + withCredentials = withCredentials ? 'include' : 'omit'; + } + + // Cloudflare Workers throws when credentials are defined + // see https://github.com/cloudflare/workerd/issues/902 + const isCredentialsSupported = "credentials" in Request.prototype; + request = new Request(url, { + ...fetchOptions, + signal: composedSignal, + method: method.toUpperCase(), + headers: headers.normalize().toJSON(), + body: data, + duplex: "half", + credentials: isCredentialsSupported ? withCredentials : undefined + }); + + let response = await fetch(request); + + const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); + + if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) { + const options = {}; + + ['status', 'statusText', 'headers'].forEach(prop => { + options[prop] = response[prop]; + }); + + const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length')); + + const [onProgress, flush] = onDownloadProgress && progressEventDecorator( + responseContentLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true) + ) || []; + + response = new Response( + trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { + flush && flush(); + unsubscribe && unsubscribe(); + }), + options + ); + } + + responseType = responseType || 'text'; + + let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config); + + !isStreamResponse && unsubscribe && unsubscribe(); + + return await new Promise((resolve, reject) => { + settle(resolve, reject, { + data: responseData, + headers: AxiosHeaders$1.from(response.headers), + status: response.status, + statusText: response.statusText, + config, + request + }); + }) + } catch (err) { + unsubscribe && unsubscribe(); + + if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) { + throw Object.assign( + new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request), + { + cause: err.cause || err + } + ) + } + + throw AxiosError.from(err, err && err.code, config, request); + } +}); + +const knownAdapters = { + http: httpAdapter, + xhr: xhrAdapter, + fetch: fetchAdapter +}; + +utils$1.forEach(knownAdapters, (fn, value) => { + if (fn) { + try { + Object.defineProperty(fn, 'name', {value}); + } catch (e) { + // eslint-disable-next-line no-empty + } + Object.defineProperty(fn, 'adapterName', {value}); + } +}); + +const renderReason = (reason) => `- ${reason}`; + +const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; + +const adapters = { + getAdapter: (adapters) => { + adapters = utils$1.isArray(adapters) ? adapters : [adapters]; + + const {length} = adapters; + let nameOrAdapter; + let adapter; + + const rejectedReasons = {}; + + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters[i]; + let id; + + adapter = nameOrAdapter; + + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + + if (adapter === undefined) { + throw new AxiosError(`Unknown adapter '${id}'`); + } + } + + if (adapter) { + break; + } + + rejectedReasons[id || '#' + i] = adapter; + } + + if (!adapter) { + + const reasons = Object.entries(rejectedReasons) + .map(([id, state]) => `adapter ${id} ` + + (state === false ? 'is not supported by the environment' : 'is not available in the build') + ); + + let s = length ? + (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : + 'as no adapter specified'; + + throw new AxiosError( + `There is no suitable adapter to dispatch the request ` + s, + 'ERR_NOT_SUPPORT' + ); + } + + return adapter; + }, + adapters: knownAdapters +}; + +/** + * Throws a `CanceledError` if cancellation has been requested. + * + * @param {Object} config The config that is to be used for the request + * + * @returns {void} + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + + if (config.signal && config.signal.aborted) { + throw new CanceledError(null, config); + } +} + +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * + * @returns {Promise} The Promise to be fulfilled + */ +function dispatchRequest(config) { + throwIfCancellationRequested(config); + + config.headers = AxiosHeaders$1.from(config.headers); + + // Transform request data + config.data = transformData.call( + config, + config.transformRequest + ); + + if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { + config.headers.setContentType('application/x-www-form-urlencoded', false); + } + + const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData.call( + config, + config.transformResponse, + response + ); + + response.headers = AxiosHeaders$1.from(response.headers); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + config.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders$1.from(reason.response.headers); + } + } + + return Promise.reject(reason); + }); +} + +const validators$1 = {}; + +// eslint-disable-next-line func-names +['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => { + validators$1[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; +}); + +const deprecatedWarnings = {}; + +/** + * Transitional option validator + * + * @param {function|boolean?} validator - set to false if the transitional option has been removed + * @param {string?} version - deprecated version / removed since version + * @param {string?} message - some message with additional info + * + * @returns {function} + */ +validators$1.transitional = function transitional(validator, version, message) { + function formatMessage(opt, desc) { + return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + } + + // eslint-disable-next-line func-names + return (value, opt, opts) => { + if (validator === false) { + throw new AxiosError( + formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), + AxiosError.ERR_DEPRECATED + ); + } + + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); + } + + return validator ? validator(value, opt, opts) : true; + }; +}; + +validators$1.spelling = function spelling(correctSpelling) { + return (value, opt) => { + // eslint-disable-next-line no-console + console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); + return true; + } +}; + +/** + * Assert object's properties type + * + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown + * + * @returns {object} + */ + +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== 'object') { + throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); + } + const keys = Object.keys(options); + let i = keys.length; + while (i-- > 0) { + const opt = keys[i]; + const validator = schema[opt]; + if (validator) { + const value = options[opt]; + const result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); + } + } +} + +const validator = { + assertOptions, + validators: validators$1 +}; + +const validators = validator.validators; + +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + * + * @return {Axios} A new instance of Axios + */ +class Axios { + constructor(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager$1(), + response: new InterceptorManager$1() + }; + } + + /** + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled + */ + async request(configOrUrl, config) { + try { + return await this._request(configOrUrl, config); + } catch (err) { + if (err instanceof Error) { + let dummy = {}; + + Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error()); + + // slice off the Error: ... line + const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : ''; + try { + if (!err.stack) { + err.stack = stack; + // match without the 2 top stack lines + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) { + err.stack += '\n' + stack; + } + } catch (e) { + // ignore the case where "stack" is an un-writable property + } + } + + throw err; + } + } + + _request(configOrUrl, config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof configOrUrl === 'string') { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } + + config = mergeConfig(this.defaults, config); + + const {transitional, paramsSerializer, headers} = config; + + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators.boolean), + forcedJSONParsing: validators.transitional(validators.boolean), + clarifyTimeoutError: validators.transitional(validators.boolean) + }, false); + } + + if (paramsSerializer != null) { + if (utils$1.isFunction(paramsSerializer)) { + config.paramsSerializer = { + serialize: paramsSerializer + }; + } else { + validator.assertOptions(paramsSerializer, { + encode: validators.function, + serialize: validators.function + }, true); + } + } + + validator.assertOptions(config, { + baseUrl: validators.spelling('baseURL'), + withXsrfToken: validators.spelling('withXSRFToken') + }, true); + + // Set config.method + config.method = (config.method || this.defaults.method || 'get').toLowerCase(); + + // Flatten headers + let contextHeaders = headers && utils$1.merge( + headers.common, + headers[config.method] + ); + + headers && utils$1.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + (method) => { + delete headers[method]; + } + ); + + config.headers = AxiosHeaders$1.concat(contextHeaders, headers); + + // filter out skipped interceptors + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + + let promise; + let i = 0; + let len; + + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), undefined]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + + promise = Promise.resolve(config); + + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + + return promise; + } + + len = requestInterceptorChain.length; + + let newConfig = config; + + i = 0; + + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + + i = 0; + len = responseInterceptorChain.length; + + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + + return promise; + } + + getUri(config) { + config = mergeConfig(this.defaults, config); + const fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); + } +} + +// Provide aliases for supported request methods +utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method, + url, + data: (config || {}).data + })); + }; +}); + +utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig(config || {}, { + method, + headers: isForm ? { + 'Content-Type': 'multipart/form-data' + } : {}, + url, + data + })); + }; + } + + Axios.prototype[method] = generateHTTPMethod(); + + Axios.prototype[method + 'Form'] = generateHTTPMethod(true); +}); + +const Axios$1 = Axios; + +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @param {Function} executor The executor function. + * + * @returns {CancelToken} + */ +class CancelToken { + constructor(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + let resolvePromise; + + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + const token = this; + + // eslint-disable-next-line func-names + this.promise.then(cancel => { + if (!token._listeners) return; + + let i = token._listeners.length; + + while (i-- > 0) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + + // eslint-disable-next-line func-names + this.promise.then = onfulfilled => { + let _resolve; + // eslint-disable-next-line func-names + const promise = new Promise(resolve => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + + return promise; + }; + + executor(function cancel(message, config, request) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new CanceledError(message, config, request); + resolvePromise(token.reason); + }); + } + + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } + + /** + * Subscribe to the cancel signal + */ + + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } + + /** + * Unsubscribe from the cancel signal + */ + + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } + } + + toAbortSignal() { + const controller = new AbortController(); + + const abort = (err) => { + controller.abort(err); + }; + + this.subscribe(abort); + + controller.signal.unsubscribe = () => this.unsubscribe(abort); + + return controller.signal; + } + + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + static source() { + let cancel; + const token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token, + cancel + }; + } +} + +const CancelToken$1 = CancelToken; + +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * + * @returns {Function} + */ +function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +} + +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +function isAxiosError(payload) { + return utils$1.isObject(payload) && (payload.isAxiosError === true); +} + +const HttpStatusCode = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511, +}; + +Object.entries(HttpStatusCode).forEach(([key, value]) => { + HttpStatusCode[value] = key; +}); + +const HttpStatusCode$1 = HttpStatusCode; + +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * + * @returns {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + const context = new Axios$1(defaultConfig); + const instance = bind(Axios$1.prototype.request, context); + + // Copy axios.prototype to instance + utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true}); + + // Copy context to instance + utils$1.extend(instance, context, null, {allOwnKeys: true}); + + // Factory for creating new instances + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; + + return instance; +} + +// Create the default instance to be exported +const axios = createInstance(defaults$1); + +// Expose Axios class to allow class inheritance +axios.Axios = Axios$1; + +// Expose Cancel & CancelToken +axios.CanceledError = CanceledError; +axios.CancelToken = CancelToken$1; +axios.isCancel = isCancel; +axios.VERSION = VERSION; +axios.toFormData = toFormData; + +// Expose AxiosError class +axios.AxiosError = AxiosError; + +// alias for CanceledError for backward compatibility +axios.Cancel = axios.CanceledError; + +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; + +axios.spread = spread; + +// Expose isAxiosError +axios.isAxiosError = isAxiosError; + +// Expose mergeConfig +axios.mergeConfig = mergeConfig; + +axios.AxiosHeaders = AxiosHeaders$1; + +axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); + +axios.getAdapter = adapters.getAdapter; + +axios.HttpStatusCode = HttpStatusCode$1; + +axios.default = axios; + +module.exports = axios; +//# sourceMappingURL=axios.cjs.map diff --git a/node_modules/axios/dist/node/axios.cjs.map b/node_modules/axios/dist/node/axios.cjs.map new file mode 100644 index 000000000..0abce248f --- /dev/null +++ b/node_modules/axios/dist/node/axios.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"axios.cjs","sources":["../../lib/helpers/bind.js","../../lib/utils.js","../../lib/core/AxiosError.js","../../lib/helpers/toFormData.js","../../lib/helpers/AxiosURLSearchParams.js","../../lib/helpers/buildURL.js","../../lib/core/InterceptorManager.js","../../lib/defaults/transitional.js","../../lib/platform/node/classes/URLSearchParams.js","../../lib/platform/node/index.js","../../lib/platform/common/utils.js","../../lib/platform/index.js","../../lib/helpers/toURLEncodedForm.js","../../lib/helpers/formDataToJSON.js","../../lib/defaults/index.js","../../lib/helpers/parseHeaders.js","../../lib/core/AxiosHeaders.js","../../lib/core/transformData.js","../../lib/cancel/isCancel.js","../../lib/cancel/CanceledError.js","../../lib/core/settle.js","../../lib/helpers/isAbsoluteURL.js","../../lib/helpers/combineURLs.js","../../lib/core/buildFullPath.js","../../lib/env/data.js","../../lib/helpers/parseProtocol.js","../../lib/helpers/fromDataURI.js","../../lib/helpers/AxiosTransformStream.js","../../lib/helpers/readBlob.js","../../lib/helpers/formDataToStream.js","../../lib/helpers/ZlibHeaderTransformStream.js","../../lib/helpers/callbackify.js","../../lib/helpers/speedometer.js","../../lib/helpers/throttle.js","../../lib/helpers/progressEventReducer.js","../../lib/adapters/http.js","../../lib/helpers/isURLSameOrigin.js","../../lib/helpers/cookies.js","../../lib/core/mergeConfig.js","../../lib/helpers/resolveConfig.js","../../lib/adapters/xhr.js","../../lib/helpers/composeSignals.js","../../lib/helpers/trackStream.js","../../lib/adapters/fetch.js","../../lib/adapters/adapters.js","../../lib/core/dispatchRequest.js","../../lib/helpers/validator.js","../../lib/core/Axios.js","../../lib/cancel/CancelToken.js","../../lib/helpers/spread.js","../../lib/helpers/isAxiosError.js","../../lib/helpers/HttpStatusCode.js","../../lib/axios.js"],"sourcesContent":["'use strict';\n\nexport default function bind(fn, thisArg) {\n return function wrap() {\n return fn.apply(thisArg, arguments);\n };\n}\n","'use strict';\n\nimport bind from './helpers/bind.js';\n\n// utils is a library of generic helper functions non-specific to axios\n\nconst {toString} = Object.prototype;\nconst {getPrototypeOf} = Object;\n\nconst kindOf = (cache => thing => {\n const str = toString.call(thing);\n return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());\n})(Object.create(null));\n\nconst kindOfTest = (type) => {\n type = type.toLowerCase();\n return (thing) => kindOf(thing) === type\n}\n\nconst typeOfTest = type => thing => typeof thing === type;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n *\n * @returns {boolean} True if value is an Array, otherwise false\n */\nconst {isArray} = Array;\n\n/**\n * Determine if a value is undefined\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nconst isUndefined = typeOfTest('undefined');\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nconst isArrayBuffer = kindOfTest('ArrayBuffer');\n\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n let result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a String, otherwise false\n */\nconst isString = typeOfTest('string');\n\n/**\n * Determine if a value is a Function\n *\n * @param {*} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nconst isFunction = typeOfTest('function');\n\n/**\n * Determine if a value is a Number\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Number, otherwise false\n */\nconst isNumber = typeOfTest('number');\n\n/**\n * Determine if a value is an Object\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an Object, otherwise false\n */\nconst isObject = (thing) => thing !== null && typeof thing === 'object';\n\n/**\n * Determine if a value is a Boolean\n *\n * @param {*} thing The value to test\n * @returns {boolean} True if value is a Boolean, otherwise false\n */\nconst isBoolean = thing => thing === true || thing === false;\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a plain Object, otherwise false\n */\nconst isPlainObject = (val) => {\n if (kindOf(val) !== 'object') {\n return false;\n }\n\n const prototype = getPrototypeOf(val);\n return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Date, otherwise false\n */\nconst isDate = kindOfTest('Date');\n\n/**\n * Determine if a value is a File\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFile = kindOfTest('File');\n\n/**\n * Determine if a value is a Blob\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nconst isBlob = kindOfTest('Blob');\n\n/**\n * Determine if a value is a FileList\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFileList = kindOfTest('FileList');\n\n/**\n * Determine if a value is a Stream\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nconst isStream = (val) => isObject(val) && isFunction(val.pipe);\n\n/**\n * Determine if a value is a FormData\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nconst isFormData = (thing) => {\n let kind;\n return thing && (\n (typeof FormData === 'function' && thing instanceof FormData) || (\n isFunction(thing.append) && (\n (kind = kindOf(thing)) === 'formdata' ||\n // detect form-data instance\n (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')\n )\n )\n )\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nconst isURLSearchParams = kindOfTest('URLSearchParams');\n\nconst [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n *\n * @returns {String} The String freed of excess whitespace\n */\nconst trim = (str) => str.trim ?\n str.trim() : str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '');\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n *\n * @param {Boolean} [allOwnKeys = false]\n * @returns {any}\n */\nfunction forEach(obj, fn, {allOwnKeys = false} = {}) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n let i;\n let l;\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);\n const len = keys.length;\n let key;\n\n for (i = 0; i < len; i++) {\n key = keys[i];\n fn.call(null, obj[key], key, obj);\n }\n }\n}\n\nfunction findKey(obj, key) {\n key = key.toLowerCase();\n const keys = Object.keys(obj);\n let i = keys.length;\n let _key;\n while (i-- > 0) {\n _key = keys[i];\n if (key === _key.toLowerCase()) {\n return _key;\n }\n }\n return null;\n}\n\nconst _global = (() => {\n /*eslint no-undef:0*/\n if (typeof globalThis !== \"undefined\") return globalThis;\n return typeof self !== \"undefined\" ? self : (typeof window !== 'undefined' ? window : global)\n})();\n\nconst isContextDefined = (context) => !isUndefined(context) && context !== _global;\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n *\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n const {caseless} = isContextDefined(this) && this || {};\n const result = {};\n const assignValue = (val, key) => {\n const targetKey = caseless && findKey(result, key) || key;\n if (isPlainObject(result[targetKey]) && isPlainObject(val)) {\n result[targetKey] = merge(result[targetKey], val);\n } else if (isPlainObject(val)) {\n result[targetKey] = merge({}, val);\n } else if (isArray(val)) {\n result[targetKey] = val.slice();\n } else {\n result[targetKey] = val;\n }\n }\n\n for (let i = 0, l = arguments.length; i < l; i++) {\n arguments[i] && forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n *\n * @param {Boolean} [allOwnKeys]\n * @returns {Object} The resulting value of object a\n */\nconst extend = (a, b, thisArg, {allOwnKeys}= {}) => {\n forEach(b, (val, key) => {\n if (thisArg && isFunction(val)) {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n }, {allOwnKeys});\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n *\n * @returns {string} content value without BOM\n */\nconst stripBOM = (content) => {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\n/**\n * Inherit the prototype methods from one constructor into another\n * @param {function} constructor\n * @param {function} superConstructor\n * @param {object} [props]\n * @param {object} [descriptors]\n *\n * @returns {void}\n */\nconst inherits = (constructor, superConstructor, props, descriptors) => {\n constructor.prototype = Object.create(superConstructor.prototype, descriptors);\n constructor.prototype.constructor = constructor;\n Object.defineProperty(constructor, 'super', {\n value: superConstructor.prototype\n });\n props && Object.assign(constructor.prototype, props);\n}\n\n/**\n * Resolve object with deep prototype chain to a flat object\n * @param {Object} sourceObj source object\n * @param {Object} [destObj]\n * @param {Function|Boolean} [filter]\n * @param {Function} [propFilter]\n *\n * @returns {Object}\n */\nconst toFlatObject = (sourceObj, destObj, filter, propFilter) => {\n let props;\n let i;\n let prop;\n const merged = {};\n\n destObj = destObj || {};\n // eslint-disable-next-line no-eq-null,eqeqeq\n if (sourceObj == null) return destObj;\n\n do {\n props = Object.getOwnPropertyNames(sourceObj);\n i = props.length;\n while (i-- > 0) {\n prop = props[i];\n if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {\n destObj[prop] = sourceObj[prop];\n merged[prop] = true;\n }\n }\n sourceObj = filter !== false && getPrototypeOf(sourceObj);\n } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);\n\n return destObj;\n}\n\n/**\n * Determines whether a string ends with the characters of a specified string\n *\n * @param {String} str\n * @param {String} searchString\n * @param {Number} [position= 0]\n *\n * @returns {boolean}\n */\nconst endsWith = (str, searchString, position) => {\n str = String(str);\n if (position === undefined || position > str.length) {\n position = str.length;\n }\n position -= searchString.length;\n const lastIndex = str.indexOf(searchString, position);\n return lastIndex !== -1 && lastIndex === position;\n}\n\n\n/**\n * Returns new array from array like object or null if failed\n *\n * @param {*} [thing]\n *\n * @returns {?Array}\n */\nconst toArray = (thing) => {\n if (!thing) return null;\n if (isArray(thing)) return thing;\n let i = thing.length;\n if (!isNumber(i)) return null;\n const arr = new Array(i);\n while (i-- > 0) {\n arr[i] = thing[i];\n }\n return arr;\n}\n\n/**\n * Checking if the Uint8Array exists and if it does, it returns a function that checks if the\n * thing passed in is an instance of Uint8Array\n *\n * @param {TypedArray}\n *\n * @returns {Array}\n */\n// eslint-disable-next-line func-names\nconst isTypedArray = (TypedArray => {\n // eslint-disable-next-line func-names\n return thing => {\n return TypedArray && thing instanceof TypedArray;\n };\n})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));\n\n/**\n * For each entry in the object, call the function with the key and value.\n *\n * @param {Object} obj - The object to iterate over.\n * @param {Function} fn - The function to call for each entry.\n *\n * @returns {void}\n */\nconst forEachEntry = (obj, fn) => {\n const generator = obj && obj[Symbol.iterator];\n\n const iterator = generator.call(obj);\n\n let result;\n\n while ((result = iterator.next()) && !result.done) {\n const pair = result.value;\n fn.call(obj, pair[0], pair[1]);\n }\n}\n\n/**\n * It takes a regular expression and a string, and returns an array of all the matches\n *\n * @param {string} regExp - The regular expression to match against.\n * @param {string} str - The string to search.\n *\n * @returns {Array}\n */\nconst matchAll = (regExp, str) => {\n let matches;\n const arr = [];\n\n while ((matches = regExp.exec(str)) !== null) {\n arr.push(matches);\n }\n\n return arr;\n}\n\n/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */\nconst isHTMLForm = kindOfTest('HTMLFormElement');\n\nconst toCamelCase = str => {\n return str.toLowerCase().replace(/[-_\\s]([a-z\\d])(\\w*)/g,\n function replacer(m, p1, p2) {\n return p1.toUpperCase() + p2;\n }\n );\n};\n\n/* Creating a function that will check if an object has a property. */\nconst hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);\n\n/**\n * Determine if a value is a RegExp object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a RegExp object, otherwise false\n */\nconst isRegExp = kindOfTest('RegExp');\n\nconst reduceDescriptors = (obj, reducer) => {\n const descriptors = Object.getOwnPropertyDescriptors(obj);\n const reducedDescriptors = {};\n\n forEach(descriptors, (descriptor, name) => {\n let ret;\n if ((ret = reducer(descriptor, name, obj)) !== false) {\n reducedDescriptors[name] = ret || descriptor;\n }\n });\n\n Object.defineProperties(obj, reducedDescriptors);\n}\n\n/**\n * Makes all methods read-only\n * @param {Object} obj\n */\n\nconst freezeMethods = (obj) => {\n reduceDescriptors(obj, (descriptor, name) => {\n // skip restricted props in strict mode\n if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {\n return false;\n }\n\n const value = obj[name];\n\n if (!isFunction(value)) return;\n\n descriptor.enumerable = false;\n\n if ('writable' in descriptor) {\n descriptor.writable = false;\n return;\n }\n\n if (!descriptor.set) {\n descriptor.set = () => {\n throw Error('Can not rewrite read-only method \\'' + name + '\\'');\n };\n }\n });\n}\n\nconst toObjectSet = (arrayOrString, delimiter) => {\n const obj = {};\n\n const define = (arr) => {\n arr.forEach(value => {\n obj[value] = true;\n });\n }\n\n isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));\n\n return obj;\n}\n\nconst noop = () => {}\n\nconst toFiniteNumber = (value, defaultValue) => {\n return value != null && Number.isFinite(value = +value) ? value : defaultValue;\n}\n\nconst ALPHA = 'abcdefghijklmnopqrstuvwxyz'\n\nconst DIGIT = '0123456789';\n\nconst ALPHABET = {\n DIGIT,\n ALPHA,\n ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT\n}\n\nconst generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {\n let str = '';\n const {length} = alphabet;\n while (size--) {\n str += alphabet[Math.random() * length|0]\n }\n\n return str;\n}\n\n/**\n * If the thing is a FormData object, return true, otherwise return false.\n *\n * @param {unknown} thing - The thing to check.\n *\n * @returns {boolean}\n */\nfunction isSpecCompliantForm(thing) {\n return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);\n}\n\nconst toJSONObject = (obj) => {\n const stack = new Array(10);\n\n const visit = (source, i) => {\n\n if (isObject(source)) {\n if (stack.indexOf(source) >= 0) {\n return;\n }\n\n if(!('toJSON' in source)) {\n stack[i] = source;\n const target = isArray(source) ? [] : {};\n\n forEach(source, (value, key) => {\n const reducedValue = visit(value, i + 1);\n !isUndefined(reducedValue) && (target[key] = reducedValue);\n });\n\n stack[i] = undefined;\n\n return target;\n }\n }\n\n return source;\n }\n\n return visit(obj, 0);\n}\n\nconst isAsyncFn = kindOfTest('AsyncFunction');\n\nconst isThenable = (thing) =>\n thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);\n\n// original code\n// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34\n\nconst _setImmediate = ((setImmediateSupported, postMessageSupported) => {\n if (setImmediateSupported) {\n return setImmediate;\n }\n\n return postMessageSupported ? ((token, callbacks) => {\n _global.addEventListener(\"message\", ({source, data}) => {\n if (source === _global && data === token) {\n callbacks.length && callbacks.shift()();\n }\n }, false);\n\n return (cb) => {\n callbacks.push(cb);\n _global.postMessage(token, \"*\");\n }\n })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);\n})(\n typeof setImmediate === 'function',\n isFunction(_global.postMessage)\n);\n\nconst asap = typeof queueMicrotask !== 'undefined' ?\n queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);\n\n// *********************\n\nexport default {\n isArray,\n isArrayBuffer,\n isBuffer,\n isFormData,\n isArrayBufferView,\n isString,\n isNumber,\n isBoolean,\n isObject,\n isPlainObject,\n isReadableStream,\n isRequest,\n isResponse,\n isHeaders,\n isUndefined,\n isDate,\n isFile,\n isBlob,\n isRegExp,\n isFunction,\n isStream,\n isURLSearchParams,\n isTypedArray,\n isFileList,\n forEach,\n merge,\n extend,\n trim,\n stripBOM,\n inherits,\n toFlatObject,\n kindOf,\n kindOfTest,\n endsWith,\n toArray,\n forEachEntry,\n matchAll,\n isHTMLForm,\n hasOwnProperty,\n hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection\n reduceDescriptors,\n freezeMethods,\n toObjectSet,\n toCamelCase,\n noop,\n toFiniteNumber,\n findKey,\n global: _global,\n isContextDefined,\n ALPHABET,\n generateString,\n isSpecCompliantForm,\n toJSONObject,\n isAsyncFn,\n isThenable,\n setImmediate: _setImmediate,\n asap\n};\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [config] The config.\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n *\n * @returns {Error} The created error.\n */\nfunction AxiosError(message, code, config, request, response) {\n Error.call(this);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error()).stack;\n }\n\n this.message = message;\n this.name = 'AxiosError';\n code && (this.code = code);\n config && (this.config = config);\n request && (this.request = request);\n if (response) {\n this.response = response;\n this.status = response.status ? response.status : null;\n }\n}\n\nutils.inherits(AxiosError, Error, {\n toJSON: function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: utils.toJSONObject(this.config),\n code: this.code,\n status: this.status\n };\n }\n});\n\nconst prototype = AxiosError.prototype;\nconst descriptors = {};\n\n[\n 'ERR_BAD_OPTION_VALUE',\n 'ERR_BAD_OPTION',\n 'ECONNABORTED',\n 'ETIMEDOUT',\n 'ERR_NETWORK',\n 'ERR_FR_TOO_MANY_REDIRECTS',\n 'ERR_DEPRECATED',\n 'ERR_BAD_RESPONSE',\n 'ERR_BAD_REQUEST',\n 'ERR_CANCELED',\n 'ERR_NOT_SUPPORT',\n 'ERR_INVALID_URL'\n// eslint-disable-next-line func-names\n].forEach(code => {\n descriptors[code] = {value: code};\n});\n\nObject.defineProperties(AxiosError, descriptors);\nObject.defineProperty(prototype, 'isAxiosError', {value: true});\n\n// eslint-disable-next-line func-names\nAxiosError.from = (error, code, config, request, response, customProps) => {\n const axiosError = Object.create(prototype);\n\n utils.toFlatObject(error, axiosError, function filter(obj) {\n return obj !== Error.prototype;\n }, prop => {\n return prop !== 'isAxiosError';\n });\n\n AxiosError.call(axiosError, error.message, code, config, request, response);\n\n axiosError.cause = error;\n\n axiosError.name = error.name;\n\n customProps && Object.assign(axiosError, customProps);\n\n return axiosError;\n};\n\nexport default AxiosError;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\n// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored\nimport PlatformFormData from '../platform/node/classes/FormData.js';\n\n/**\n * Determines if the given thing is a array or js object.\n *\n * @param {string} thing - The object or array to be visited.\n *\n * @returns {boolean}\n */\nfunction isVisitable(thing) {\n return utils.isPlainObject(thing) || utils.isArray(thing);\n}\n\n/**\n * It removes the brackets from the end of a string\n *\n * @param {string} key - The key of the parameter.\n *\n * @returns {string} the key without the brackets.\n */\nfunction removeBrackets(key) {\n return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;\n}\n\n/**\n * It takes a path, a key, and a boolean, and returns a string\n *\n * @param {string} path - The path to the current key.\n * @param {string} key - The key of the current object being iterated over.\n * @param {string} dots - If true, the key will be rendered with dots instead of brackets.\n *\n * @returns {string} The path to the current key.\n */\nfunction renderKey(path, key, dots) {\n if (!path) return key;\n return path.concat(key).map(function each(token, i) {\n // eslint-disable-next-line no-param-reassign\n token = removeBrackets(token);\n return !dots && i ? '[' + token + ']' : token;\n }).join(dots ? '.' : '');\n}\n\n/**\n * If the array is an array and none of its elements are visitable, then it's a flat array.\n *\n * @param {Array} arr - The array to check\n *\n * @returns {boolean}\n */\nfunction isFlatArray(arr) {\n return utils.isArray(arr) && !arr.some(isVisitable);\n}\n\nconst predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {\n return /^is[A-Z]/.test(prop);\n});\n\n/**\n * Convert a data object to FormData\n *\n * @param {Object} obj\n * @param {?Object} [formData]\n * @param {?Object} [options]\n * @param {Function} [options.visitor]\n * @param {Boolean} [options.metaTokens = true]\n * @param {Boolean} [options.dots = false]\n * @param {?Boolean} [options.indexes = false]\n *\n * @returns {Object}\n **/\n\n/**\n * It converts an object into a FormData object\n *\n * @param {Object} obj - The object to convert to form data.\n * @param {string} formData - The FormData object to append to.\n * @param {Object} options\n *\n * @returns\n */\nfunction toFormData(obj, formData, options) {\n if (!utils.isObject(obj)) {\n throw new TypeError('target must be an object');\n }\n\n // eslint-disable-next-line no-param-reassign\n formData = formData || new (PlatformFormData || FormData)();\n\n // eslint-disable-next-line no-param-reassign\n options = utils.toFlatObject(options, {\n metaTokens: true,\n dots: false,\n indexes: false\n }, false, function defined(option, source) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n return !utils.isUndefined(source[option]);\n });\n\n const metaTokens = options.metaTokens;\n // eslint-disable-next-line no-use-before-define\n const visitor = options.visitor || defaultVisitor;\n const dots = options.dots;\n const indexes = options.indexes;\n const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;\n const useBlob = _Blob && utils.isSpecCompliantForm(formData);\n\n if (!utils.isFunction(visitor)) {\n throw new TypeError('visitor must be a function');\n }\n\n function convertValue(value) {\n if (value === null) return '';\n\n if (utils.isDate(value)) {\n return value.toISOString();\n }\n\n if (!useBlob && utils.isBlob(value)) {\n throw new AxiosError('Blob is not supported. Use a Buffer instead.');\n }\n\n if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {\n return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);\n }\n\n return value;\n }\n\n /**\n * Default visitor.\n *\n * @param {*} value\n * @param {String|Number} key\n * @param {Array} path\n * @this {FormData}\n *\n * @returns {boolean} return true to visit the each prop of the value recursively\n */\n function defaultVisitor(value, key, path) {\n let arr = value;\n\n if (value && !path && typeof value === 'object') {\n if (utils.endsWith(key, '{}')) {\n // eslint-disable-next-line no-param-reassign\n key = metaTokens ? key : key.slice(0, -2);\n // eslint-disable-next-line no-param-reassign\n value = JSON.stringify(value);\n } else if (\n (utils.isArray(value) && isFlatArray(value)) ||\n ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))\n )) {\n // eslint-disable-next-line no-param-reassign\n key = removeBrackets(key);\n\n arr.forEach(function each(el, index) {\n !(utils.isUndefined(el) || el === null) && formData.append(\n // eslint-disable-next-line no-nested-ternary\n indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),\n convertValue(el)\n );\n });\n return false;\n }\n }\n\n if (isVisitable(value)) {\n return true;\n }\n\n formData.append(renderKey(path, key, dots), convertValue(value));\n\n return false;\n }\n\n const stack = [];\n\n const exposedHelpers = Object.assign(predicates, {\n defaultVisitor,\n convertValue,\n isVisitable\n });\n\n function build(value, path) {\n if (utils.isUndefined(value)) return;\n\n if (stack.indexOf(value) !== -1) {\n throw Error('Circular reference detected in ' + path.join('.'));\n }\n\n stack.push(value);\n\n utils.forEach(value, function each(el, key) {\n const result = !(utils.isUndefined(el) || el === null) && visitor.call(\n formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers\n );\n\n if (result === true) {\n build(el, path ? path.concat(key) : [key]);\n }\n });\n\n stack.pop();\n }\n\n if (!utils.isObject(obj)) {\n throw new TypeError('data must be an object');\n }\n\n build(obj);\n\n return formData;\n}\n\nexport default toFormData;\n","'use strict';\n\nimport toFormData from './toFormData.js';\n\n/**\n * It encodes a string by replacing all characters that are not in the unreserved set with\n * their percent-encoded equivalents\n *\n * @param {string} str - The string to encode.\n *\n * @returns {string} The encoded string.\n */\nfunction encode(str) {\n const charMap = {\n '!': '%21',\n \"'\": '%27',\n '(': '%28',\n ')': '%29',\n '~': '%7E',\n '%20': '+',\n '%00': '\\x00'\n };\n return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {\n return charMap[match];\n });\n}\n\n/**\n * It takes a params object and converts it to a FormData object\n *\n * @param {Object} params - The parameters to be converted to a FormData object.\n * @param {Object} options - The options object passed to the Axios constructor.\n *\n * @returns {void}\n */\nfunction AxiosURLSearchParams(params, options) {\n this._pairs = [];\n\n params && toFormData(params, this, options);\n}\n\nconst prototype = AxiosURLSearchParams.prototype;\n\nprototype.append = function append(name, value) {\n this._pairs.push([name, value]);\n};\n\nprototype.toString = function toString(encoder) {\n const _encode = encoder ? function(value) {\n return encoder.call(this, value, encode);\n } : encode;\n\n return this._pairs.map(function each(pair) {\n return _encode(pair[0]) + '=' + _encode(pair[1]);\n }, '').join('&');\n};\n\nexport default AxiosURLSearchParams;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';\n\n/**\n * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their\n * URI encoded counterparts\n *\n * @param {string} val The value to be encoded.\n *\n * @returns {string} The encoded value.\n */\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @param {?(object|Function)} options\n *\n * @returns {string} The formatted url\n */\nexport default function buildURL(url, params, options) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n \n const _encode = options && options.encode || encode;\n\n if (utils.isFunction(options)) {\n options = {\n serialize: options\n };\n } \n\n const serializeFn = options && options.serialize;\n\n let serializedParams;\n\n if (serializeFn) {\n serializedParams = serializeFn(params, options);\n } else {\n serializedParams = utils.isURLSearchParams(params) ?\n params.toString() :\n new AxiosURLSearchParams(params, options).toString(_encode);\n }\n\n if (serializedParams) {\n const hashmarkIndex = url.indexOf(\"#\");\n\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\nclass InterceptorManager {\n constructor() {\n this.handlers = [];\n }\n\n /**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\n use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled,\n rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n }\n\n /**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n *\n * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise\n */\n eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n }\n\n /**\n * Clear all interceptors from the stack\n *\n * @returns {void}\n */\n clear() {\n if (this.handlers) {\n this.handlers = [];\n }\n }\n\n /**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n *\n * @returns {void}\n */\n forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n }\n}\n\nexport default InterceptorManager;\n","'use strict';\n\nexport default {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n};\n","'use strict';\n\nimport url from 'url';\nexport default url.URLSearchParams;\n","import URLSearchParams from './classes/URLSearchParams.js'\nimport FormData from './classes/FormData.js'\n\nexport default {\n isNode: true,\n classes: {\n URLSearchParams,\n FormData,\n Blob: typeof Blob !== 'undefined' && Blob || null\n },\n protocols: [ 'http', 'https', 'file', 'data' ]\n};\n","const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';\n\nconst _navigator = typeof navigator === 'object' && navigator || undefined;\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n *\n * @returns {boolean}\n */\nconst hasStandardBrowserEnv = hasBrowserEnv &&\n (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);\n\n/**\n * Determine if we're running in a standard browser webWorker environment\n *\n * Although the `isStandardBrowserEnv` method indicates that\n * `allows axios to run in a web worker`, the WebWorker will still be\n * filtered out due to its judgment standard\n * `typeof window !== 'undefined' && typeof document !== 'undefined'`.\n * This leads to a problem when axios post `FormData` in webWorker\n */\nconst hasStandardBrowserWebWorkerEnv = (() => {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n // eslint-disable-next-line no-undef\n self instanceof WorkerGlobalScope &&\n typeof self.importScripts === 'function'\n );\n})();\n\nconst origin = hasBrowserEnv && window.location.href || 'http://localhost';\n\nexport {\n hasBrowserEnv,\n hasStandardBrowserWebWorkerEnv,\n hasStandardBrowserEnv,\n _navigator as navigator,\n origin\n}\n","import platform from './node/index.js';\nimport * as utils from './common/utils.js';\n\nexport default {\n ...utils,\n ...platform\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport toFormData from './toFormData.js';\nimport platform from '../platform/index.js';\n\nexport default function toURLEncodedForm(data, options) {\n return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({\n visitor: function(value, key, path, helpers) {\n if (platform.isNode && utils.isBuffer(value)) {\n this.append(key, value.toString('base64'));\n return false;\n }\n\n return helpers.defaultVisitor.apply(this, arguments);\n }\n }, options));\n}\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']\n *\n * @param {string} name - The name of the property to get.\n *\n * @returns An array of strings.\n */\nfunction parsePropPath(name) {\n // foo[x][y][z]\n // foo.x.y.z\n // foo-x-y-z\n // foo x y z\n return utils.matchAll(/\\w+|\\[(\\w*)]/g, name).map(match => {\n return match[0] === '[]' ? '' : match[1] || match[0];\n });\n}\n\n/**\n * Convert an array to an object.\n *\n * @param {Array} arr - The array to convert to an object.\n *\n * @returns An object with the same keys and values as the array.\n */\nfunction arrayToObject(arr) {\n const obj = {};\n const keys = Object.keys(arr);\n let i;\n const len = keys.length;\n let key;\n for (i = 0; i < len; i++) {\n key = keys[i];\n obj[key] = arr[key];\n }\n return obj;\n}\n\n/**\n * It takes a FormData object and returns a JavaScript object\n *\n * @param {string} formData The FormData object to convert to JSON.\n *\n * @returns {Object | null} The converted object.\n */\nfunction formDataToJSON(formData) {\n function buildPath(path, value, target, index) {\n let name = path[index++];\n\n if (name === '__proto__') return true;\n\n const isNumericKey = Number.isFinite(+name);\n const isLast = index >= path.length;\n name = !name && utils.isArray(target) ? target.length : name;\n\n if (isLast) {\n if (utils.hasOwnProp(target, name)) {\n target[name] = [target[name], value];\n } else {\n target[name] = value;\n }\n\n return !isNumericKey;\n }\n\n if (!target[name] || !utils.isObject(target[name])) {\n target[name] = [];\n }\n\n const result = buildPath(path, value, target[name], index);\n\n if (result && utils.isArray(target[name])) {\n target[name] = arrayToObject(target[name]);\n }\n\n return !isNumericKey;\n }\n\n if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {\n const obj = {};\n\n utils.forEachEntry(formData, (name, value) => {\n buildPath(parsePropPath(name), value, obj, 0);\n });\n\n return obj;\n }\n\n return null;\n}\n\nexport default formDataToJSON;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\nimport transitionalDefaults from './transitional.js';\nimport toFormData from '../helpers/toFormData.js';\nimport toURLEncodedForm from '../helpers/toURLEncodedForm.js';\nimport platform from '../platform/index.js';\nimport formDataToJSON from '../helpers/formDataToJSON.js';\n\n/**\n * It takes a string, tries to parse it, and if it fails, it returns the stringified version\n * of the input\n *\n * @param {any} rawValue - The value to be stringified.\n * @param {Function} parser - A function that parses a string into a JavaScript object.\n * @param {Function} encoder - A function that takes a value and returns a string.\n *\n * @returns {string} A stringified version of the rawValue.\n */\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nconst defaults = {\n\n transitional: transitionalDefaults,\n\n adapter: ['xhr', 'http', 'fetch'],\n\n transformRequest: [function transformRequest(data, headers) {\n const contentType = headers.getContentType() || '';\n const hasJSONContentType = contentType.indexOf('application/json') > -1;\n const isObjectPayload = utils.isObject(data);\n\n if (isObjectPayload && utils.isHTMLForm(data)) {\n data = new FormData(data);\n }\n\n const isFormData = utils.isFormData(data);\n\n if (isFormData) {\n return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;\n }\n\n if (utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data) ||\n utils.isReadableStream(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);\n return data.toString();\n }\n\n let isFileList;\n\n if (isObjectPayload) {\n if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {\n return toURLEncodedForm(data, this.formSerializer).toString();\n }\n\n if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {\n const _FormData = this.env && this.env.FormData;\n\n return toFormData(\n isFileList ? {'files[]': data} : data,\n _FormData && new _FormData(),\n this.formSerializer\n );\n }\n }\n\n if (isObjectPayload || hasJSONContentType ) {\n headers.setContentType('application/json', false);\n return stringifySafely(data);\n }\n\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n const transitional = this.transitional || defaults.transitional;\n const forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n const JSONRequested = this.responseType === 'json';\n\n if (utils.isResponse(data) || utils.isReadableStream(data)) {\n return data;\n }\n\n if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {\n const silentJSONParsing = transitional && transitional.silentJSONParsing;\n const strictJSONParsing = !silentJSONParsing && JSONRequested;\n\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n env: {\n FormData: platform.classes.FormData,\n Blob: platform.classes.Blob\n },\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*',\n 'Content-Type': undefined\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {\n defaults.headers[method] = {};\n});\n\nexport default defaults;\n","'use strict';\n\nimport utils from './../utils.js';\n\n// RawAxiosHeaders whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nconst ignoreDuplicateOf = utils.toObjectSet([\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n]);\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} rawHeaders Headers needing to be parsed\n *\n * @returns {Object} Headers parsed into an object\n */\nexport default rawHeaders => {\n const parsed = {};\n let key;\n let val;\n let i;\n\n rawHeaders && rawHeaders.split('\\n').forEach(function parser(line) {\n i = line.indexOf(':');\n key = line.substring(0, i).trim().toLowerCase();\n val = line.substring(i + 1).trim();\n\n if (!key || (parsed[key] && ignoreDuplicateOf[key])) {\n return;\n }\n\n if (key === 'set-cookie') {\n if (parsed[key]) {\n parsed[key].push(val);\n } else {\n parsed[key] = [val];\n }\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n });\n\n return parsed;\n};\n","'use strict';\n\nimport utils from '../utils.js';\nimport parseHeaders from '../helpers/parseHeaders.js';\n\nconst $internals = Symbol('internals');\n\nfunction normalizeHeader(header) {\n return header && String(header).trim().toLowerCase();\n}\n\nfunction normalizeValue(value) {\n if (value === false || value == null) {\n return value;\n }\n\n return utils.isArray(value) ? value.map(normalizeValue) : String(value);\n}\n\nfunction parseTokens(str) {\n const tokens = Object.create(null);\n const tokensRE = /([^\\s,;=]+)\\s*(?:=\\s*([^,;]+))?/g;\n let match;\n\n while ((match = tokensRE.exec(str))) {\n tokens[match[1]] = match[2];\n }\n\n return tokens;\n}\n\nconst isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());\n\nfunction matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {\n if (utils.isFunction(filter)) {\n return filter.call(this, value, header);\n }\n\n if (isHeaderNameFilter) {\n value = header;\n }\n\n if (!utils.isString(value)) return;\n\n if (utils.isString(filter)) {\n return value.indexOf(filter) !== -1;\n }\n\n if (utils.isRegExp(filter)) {\n return filter.test(value);\n }\n}\n\nfunction formatHeader(header) {\n return header.trim()\n .toLowerCase().replace(/([a-z\\d])(\\w*)/g, (w, char, str) => {\n return char.toUpperCase() + str;\n });\n}\n\nfunction buildAccessors(obj, header) {\n const accessorName = utils.toCamelCase(' ' + header);\n\n ['get', 'set', 'has'].forEach(methodName => {\n Object.defineProperty(obj, methodName + accessorName, {\n value: function(arg1, arg2, arg3) {\n return this[methodName].call(this, header, arg1, arg2, arg3);\n },\n configurable: true\n });\n });\n}\n\nclass AxiosHeaders {\n constructor(headers) {\n headers && this.set(headers);\n }\n\n set(header, valueOrRewrite, rewrite) {\n const self = this;\n\n function setHeader(_value, _header, _rewrite) {\n const lHeader = normalizeHeader(_header);\n\n if (!lHeader) {\n throw new Error('header name must be a non-empty string');\n }\n\n const key = utils.findKey(self, lHeader);\n\n if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {\n self[key || _header] = normalizeValue(_value);\n }\n }\n\n const setHeaders = (headers, _rewrite) =>\n utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));\n\n if (utils.isPlainObject(header) || header instanceof this.constructor) {\n setHeaders(header, valueOrRewrite)\n } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {\n setHeaders(parseHeaders(header), valueOrRewrite);\n } else if (utils.isHeaders(header)) {\n for (const [key, value] of header.entries()) {\n setHeader(value, key, rewrite);\n }\n } else {\n header != null && setHeader(valueOrRewrite, header, rewrite);\n }\n\n return this;\n }\n\n get(header, parser) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n if (key) {\n const value = this[key];\n\n if (!parser) {\n return value;\n }\n\n if (parser === true) {\n return parseTokens(value);\n }\n\n if (utils.isFunction(parser)) {\n return parser.call(this, value, key);\n }\n\n if (utils.isRegExp(parser)) {\n return parser.exec(value);\n }\n\n throw new TypeError('parser must be boolean|regexp|function');\n }\n }\n }\n\n has(header, matcher) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));\n }\n\n return false;\n }\n\n delete(header, matcher) {\n const self = this;\n let deleted = false;\n\n function deleteHeader(_header) {\n _header = normalizeHeader(_header);\n\n if (_header) {\n const key = utils.findKey(self, _header);\n\n if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {\n delete self[key];\n\n deleted = true;\n }\n }\n }\n\n if (utils.isArray(header)) {\n header.forEach(deleteHeader);\n } else {\n deleteHeader(header);\n }\n\n return deleted;\n }\n\n clear(matcher) {\n const keys = Object.keys(this);\n let i = keys.length;\n let deleted = false;\n\n while (i--) {\n const key = keys[i];\n if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {\n delete this[key];\n deleted = true;\n }\n }\n\n return deleted;\n }\n\n normalize(format) {\n const self = this;\n const headers = {};\n\n utils.forEach(this, (value, header) => {\n const key = utils.findKey(headers, header);\n\n if (key) {\n self[key] = normalizeValue(value);\n delete self[header];\n return;\n }\n\n const normalized = format ? formatHeader(header) : String(header).trim();\n\n if (normalized !== header) {\n delete self[header];\n }\n\n self[normalized] = normalizeValue(value);\n\n headers[normalized] = true;\n });\n\n return this;\n }\n\n concat(...targets) {\n return this.constructor.concat(this, ...targets);\n }\n\n toJSON(asStrings) {\n const obj = Object.create(null);\n\n utils.forEach(this, (value, header) => {\n value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);\n });\n\n return obj;\n }\n\n [Symbol.iterator]() {\n return Object.entries(this.toJSON())[Symbol.iterator]();\n }\n\n toString() {\n return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\\n');\n }\n\n get [Symbol.toStringTag]() {\n return 'AxiosHeaders';\n }\n\n static from(thing) {\n return thing instanceof this ? thing : new this(thing);\n }\n\n static concat(first, ...targets) {\n const computed = new this(first);\n\n targets.forEach((target) => computed.set(target));\n\n return computed;\n }\n\n static accessor(header) {\n const internals = this[$internals] = (this[$internals] = {\n accessors: {}\n });\n\n const accessors = internals.accessors;\n const prototype = this.prototype;\n\n function defineAccessor(_header) {\n const lHeader = normalizeHeader(_header);\n\n if (!accessors[lHeader]) {\n buildAccessors(prototype, _header);\n accessors[lHeader] = true;\n }\n }\n\n utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);\n\n return this;\n }\n}\n\nAxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);\n\n// reserved names hotfix\nutils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {\n let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`\n return {\n get: () => value,\n set(headerValue) {\n this[mapped] = headerValue;\n }\n }\n});\n\nutils.freezeMethods(AxiosHeaders);\n\nexport default AxiosHeaders;\n","'use strict';\n\nimport utils from './../utils.js';\nimport defaults from '../defaults/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Array|Function} fns A single function or Array of functions\n * @param {?Object} response The response object\n *\n * @returns {*} The resulting transformed data\n */\nexport default function transformData(fns, response) {\n const config = this || defaults;\n const context = response || config;\n const headers = AxiosHeaders.from(context.headers);\n let data = context.data;\n\n utils.forEach(fns, function transform(fn) {\n data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);\n });\n\n headers.normalize();\n\n return data;\n}\n","'use strict';\n\nexport default function isCancel(value) {\n return !!(value && value.__CANCEL__);\n}\n","'use strict';\n\nimport AxiosError from '../core/AxiosError.js';\nimport utils from '../utils.js';\n\n/**\n * A `CanceledError` is an object that is thrown when an operation is canceled.\n *\n * @param {string=} message The message.\n * @param {Object=} config The config.\n * @param {Object=} request The request.\n *\n * @returns {CanceledError} The created error.\n */\nfunction CanceledError(message, config, request) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);\n this.name = 'CanceledError';\n}\n\nutils.inherits(CanceledError, AxiosError, {\n __CANCEL__: true\n});\n\nexport default CanceledError;\n","'use strict';\n\nimport AxiosError from './AxiosError.js';\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n *\n * @returns {object} The response.\n */\nexport default function settle(resolve, reject, response) {\n const validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(new AxiosError(\n 'Request failed with status code ' + response.status,\n [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],\n response.config,\n response.request,\n response\n ));\n }\n}\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n *\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nexport default function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n}\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n *\n * @returns {string} The combined URL\n */\nexport default function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/?\\/$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n}\n","'use strict';\n\nimport isAbsoluteURL from '../helpers/isAbsoluteURL.js';\nimport combineURLs from '../helpers/combineURLs.js';\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n *\n * @returns {string} The combined full path\n */\nexport default function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n}\n","export const VERSION = \"1.7.9\";","'use strict';\n\nexport default function parseProtocol(url) {\n const match = /^([-+\\w]{1,25})(:?\\/\\/|:)/.exec(url);\n return match && match[1] || '';\n}\n","'use strict';\n\nimport AxiosError from '../core/AxiosError.js';\nimport parseProtocol from './parseProtocol.js';\nimport platform from '../platform/index.js';\n\nconst DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\\s\\S]*)$/;\n\n/**\n * Parse data uri to a Buffer or Blob\n *\n * @param {String} uri\n * @param {?Boolean} asBlob\n * @param {?Object} options\n * @param {?Function} options.Blob\n *\n * @returns {Buffer|Blob}\n */\nexport default function fromDataURI(uri, asBlob, options) {\n const _Blob = options && options.Blob || platform.classes.Blob;\n const protocol = parseProtocol(uri);\n\n if (asBlob === undefined && _Blob) {\n asBlob = true;\n }\n\n if (protocol === 'data') {\n uri = protocol.length ? uri.slice(protocol.length + 1) : uri;\n\n const match = DATA_URL_PATTERN.exec(uri);\n\n if (!match) {\n throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);\n }\n\n const mime = match[1];\n const isBase64 = match[2];\n const body = match[3];\n const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');\n\n if (asBlob) {\n if (!_Blob) {\n throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);\n }\n\n return new _Blob([buffer], {type: mime});\n }\n\n return buffer;\n }\n\n throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);\n}\n","'use strict';\n\nimport stream from 'stream';\nimport utils from '../utils.js';\n\nconst kInternals = Symbol('internals');\n\nclass AxiosTransformStream extends stream.Transform{\n constructor(options) {\n options = utils.toFlatObject(options, {\n maxRate: 0,\n chunkSize: 64 * 1024,\n minChunkSize: 100,\n timeWindow: 500,\n ticksRate: 2,\n samplesCount: 15\n }, null, (prop, source) => {\n return !utils.isUndefined(source[prop]);\n });\n\n super({\n readableHighWaterMark: options.chunkSize\n });\n\n const internals = this[kInternals] = {\n timeWindow: options.timeWindow,\n chunkSize: options.chunkSize,\n maxRate: options.maxRate,\n minChunkSize: options.minChunkSize,\n bytesSeen: 0,\n isCaptured: false,\n notifiedBytesLoaded: 0,\n ts: Date.now(),\n bytes: 0,\n onReadCallback: null\n };\n\n this.on('newListener', event => {\n if (event === 'progress') {\n if (!internals.isCaptured) {\n internals.isCaptured = true;\n }\n }\n });\n }\n\n _read(size) {\n const internals = this[kInternals];\n\n if (internals.onReadCallback) {\n internals.onReadCallback();\n }\n\n return super._read(size);\n }\n\n _transform(chunk, encoding, callback) {\n const internals = this[kInternals];\n const maxRate = internals.maxRate;\n\n const readableHighWaterMark = this.readableHighWaterMark;\n\n const timeWindow = internals.timeWindow;\n\n const divider = 1000 / timeWindow;\n const bytesThreshold = (maxRate / divider);\n const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;\n\n const pushChunk = (_chunk, _callback) => {\n const bytes = Buffer.byteLength(_chunk);\n internals.bytesSeen += bytes;\n internals.bytes += bytes;\n\n internals.isCaptured && this.emit('progress', internals.bytesSeen);\n\n if (this.push(_chunk)) {\n process.nextTick(_callback);\n } else {\n internals.onReadCallback = () => {\n internals.onReadCallback = null;\n process.nextTick(_callback);\n };\n }\n }\n\n const transformChunk = (_chunk, _callback) => {\n const chunkSize = Buffer.byteLength(_chunk);\n let chunkRemainder = null;\n let maxChunkSize = readableHighWaterMark;\n let bytesLeft;\n let passed = 0;\n\n if (maxRate) {\n const now = Date.now();\n\n if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) {\n internals.ts = now;\n bytesLeft = bytesThreshold - internals.bytes;\n internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;\n passed = 0;\n }\n\n bytesLeft = bytesThreshold - internals.bytes;\n }\n\n if (maxRate) {\n if (bytesLeft <= 0) {\n // next time window\n return setTimeout(() => {\n _callback(null, _chunk);\n }, timeWindow - passed);\n }\n\n if (bytesLeft < maxChunkSize) {\n maxChunkSize = bytesLeft;\n }\n }\n\n if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) {\n chunkRemainder = _chunk.subarray(maxChunkSize);\n _chunk = _chunk.subarray(0, maxChunkSize);\n }\n\n pushChunk(_chunk, chunkRemainder ? () => {\n process.nextTick(_callback, null, chunkRemainder);\n } : _callback);\n };\n\n transformChunk(chunk, function transformNextChunk(err, _chunk) {\n if (err) {\n return callback(err);\n }\n\n if (_chunk) {\n transformChunk(_chunk, transformNextChunk);\n } else {\n callback(null);\n }\n });\n }\n}\n\nexport default AxiosTransformStream;\n","const {asyncIterator} = Symbol;\n\nconst readBlob = async function* (blob) {\n if (blob.stream) {\n yield* blob.stream()\n } else if (blob.arrayBuffer) {\n yield await blob.arrayBuffer()\n } else if (blob[asyncIterator]) {\n yield* blob[asyncIterator]();\n } else {\n yield blob;\n }\n}\n\nexport default readBlob;\n","import util from 'util';\nimport {Readable} from 'stream';\nimport utils from \"../utils.js\";\nimport readBlob from \"./readBlob.js\";\n\nconst BOUNDARY_ALPHABET = utils.ALPHABET.ALPHA_DIGIT + '-_';\n\nconst textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : new util.TextEncoder();\n\nconst CRLF = '\\r\\n';\nconst CRLF_BYTES = textEncoder.encode(CRLF);\nconst CRLF_BYTES_COUNT = 2;\n\nclass FormDataPart {\n constructor(name, value) {\n const {escapeName} = this.constructor;\n const isStringValue = utils.isString(value);\n\n let headers = `Content-Disposition: form-data; name=\"${escapeName(name)}\"${\n !isStringValue && value.name ? `; filename=\"${escapeName(value.name)}\"` : ''\n }${CRLF}`;\n\n if (isStringValue) {\n value = textEncoder.encode(String(value).replace(/\\r?\\n|\\r\\n?/g, CRLF));\n } else {\n headers += `Content-Type: ${value.type || \"application/octet-stream\"}${CRLF}`\n }\n\n this.headers = textEncoder.encode(headers + CRLF);\n\n this.contentLength = isStringValue ? value.byteLength : value.size;\n\n this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;\n\n this.name = name;\n this.value = value;\n }\n\n async *encode(){\n yield this.headers;\n\n const {value} = this;\n\n if(utils.isTypedArray(value)) {\n yield value;\n } else {\n yield* readBlob(value);\n }\n\n yield CRLF_BYTES;\n }\n\n static escapeName(name) {\n return String(name).replace(/[\\r\\n\"]/g, (match) => ({\n '\\r' : '%0D',\n '\\n' : '%0A',\n '\"' : '%22',\n }[match]));\n }\n}\n\nconst formDataToStream = (form, headersHandler, options) => {\n const {\n tag = 'form-data-boundary',\n size = 25,\n boundary = tag + '-' + utils.generateString(size, BOUNDARY_ALPHABET)\n } = options || {};\n\n if(!utils.isFormData(form)) {\n throw TypeError('FormData instance required');\n }\n\n if (boundary.length < 1 || boundary.length > 70) {\n throw Error('boundary must be 10-70 characters long')\n }\n\n const boundaryBytes = textEncoder.encode('--' + boundary + CRLF);\n const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF + CRLF);\n let contentLength = footerBytes.byteLength;\n\n const parts = Array.from(form.entries()).map(([name, value]) => {\n const part = new FormDataPart(name, value);\n contentLength += part.size;\n return part;\n });\n\n contentLength += boundaryBytes.byteLength * parts.length;\n\n contentLength = utils.toFiniteNumber(contentLength);\n\n const computedHeaders = {\n 'Content-Type': `multipart/form-data; boundary=${boundary}`\n }\n\n if (Number.isFinite(contentLength)) {\n computedHeaders['Content-Length'] = contentLength;\n }\n\n headersHandler && headersHandler(computedHeaders);\n\n return Readable.from((async function *() {\n for(const part of parts) {\n yield boundaryBytes;\n yield* part.encode();\n }\n\n yield footerBytes;\n })());\n};\n\nexport default formDataToStream;\n","\"use strict\";\n\nimport stream from \"stream\";\n\nclass ZlibHeaderTransformStream extends stream.Transform {\n __transform(chunk, encoding, callback) {\n this.push(chunk);\n callback();\n }\n\n _transform(chunk, encoding, callback) {\n if (chunk.length !== 0) {\n this._transform = this.__transform;\n\n // Add Default Compression headers if no zlib headers are present\n if (chunk[0] !== 120) { // Hex: 78\n const header = Buffer.alloc(2);\n header[0] = 120; // Hex: 78\n header[1] = 156; // Hex: 9C \n this.push(header, encoding);\n }\n }\n\n this.__transform(chunk, encoding, callback);\n }\n}\n\nexport default ZlibHeaderTransformStream;\n","import utils from \"../utils.js\";\n\nconst callbackify = (fn, reducer) => {\n return utils.isAsyncFn(fn) ? function (...args) {\n const cb = args.pop();\n fn.apply(this, args).then((value) => {\n try {\n reducer ? cb(null, ...reducer(value)) : cb(null, value);\n } catch (err) {\n cb(err);\n }\n }, cb);\n } : fn;\n}\n\nexport default callbackify;\n","'use strict';\n\n/**\n * Calculate data maxRate\n * @param {Number} [samplesCount= 10]\n * @param {Number} [min= 1000]\n * @returns {Function}\n */\nfunction speedometer(samplesCount, min) {\n samplesCount = samplesCount || 10;\n const bytes = new Array(samplesCount);\n const timestamps = new Array(samplesCount);\n let head = 0;\n let tail = 0;\n let firstSampleTS;\n\n min = min !== undefined ? min : 1000;\n\n return function push(chunkLength) {\n const now = Date.now();\n\n const startedAt = timestamps[tail];\n\n if (!firstSampleTS) {\n firstSampleTS = now;\n }\n\n bytes[head] = chunkLength;\n timestamps[head] = now;\n\n let i = tail;\n let bytesCount = 0;\n\n while (i !== head) {\n bytesCount += bytes[i++];\n i = i % samplesCount;\n }\n\n head = (head + 1) % samplesCount;\n\n if (head === tail) {\n tail = (tail + 1) % samplesCount;\n }\n\n if (now - firstSampleTS < min) {\n return;\n }\n\n const passed = startedAt && now - startedAt;\n\n return passed ? Math.round(bytesCount * 1000 / passed) : undefined;\n };\n}\n\nexport default speedometer;\n","/**\n * Throttle decorator\n * @param {Function} fn\n * @param {Number} freq\n * @return {Function}\n */\nfunction throttle(fn, freq) {\n let timestamp = 0;\n let threshold = 1000 / freq;\n let lastArgs;\n let timer;\n\n const invoke = (args, now = Date.now()) => {\n timestamp = now;\n lastArgs = null;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n fn.apply(null, args);\n }\n\n const throttled = (...args) => {\n const now = Date.now();\n const passed = now - timestamp;\n if ( passed >= threshold) {\n invoke(args, now);\n } else {\n lastArgs = args;\n if (!timer) {\n timer = setTimeout(() => {\n timer = null;\n invoke(lastArgs)\n }, threshold - passed);\n }\n }\n }\n\n const flush = () => lastArgs && invoke(lastArgs);\n\n return [throttled, flush];\n}\n\nexport default throttle;\n","import speedometer from \"./speedometer.js\";\nimport throttle from \"./throttle.js\";\nimport utils from \"../utils.js\";\n\nexport const progressEventReducer = (listener, isDownloadStream, freq = 3) => {\n let bytesNotified = 0;\n const _speedometer = speedometer(50, 250);\n\n return throttle(e => {\n const loaded = e.loaded;\n const total = e.lengthComputable ? e.total : undefined;\n const progressBytes = loaded - bytesNotified;\n const rate = _speedometer(progressBytes);\n const inRange = loaded <= total;\n\n bytesNotified = loaded;\n\n const data = {\n loaded,\n total,\n progress: total ? (loaded / total) : undefined,\n bytes: progressBytes,\n rate: rate ? rate : undefined,\n estimated: rate && total && inRange ? (total - loaded) / rate : undefined,\n event: e,\n lengthComputable: total != null,\n [isDownloadStream ? 'download' : 'upload']: true\n };\n\n listener(data);\n }, freq);\n}\n\nexport const progressEventDecorator = (total, throttled) => {\n const lengthComputable = total != null;\n\n return [(loaded) => throttled[0]({\n lengthComputable,\n total,\n loaded\n }), throttled[1]];\n}\n\nexport const asyncDecorator = (fn) => (...args) => utils.asap(() => fn(...args));\n","'use strict';\n\nimport utils from './../utils.js';\nimport settle from './../core/settle.js';\nimport buildFullPath from '../core/buildFullPath.js';\nimport buildURL from './../helpers/buildURL.js';\nimport proxyFromEnv from 'proxy-from-env';\nimport http from 'http';\nimport https from 'https';\nimport util from 'util';\nimport followRedirects from 'follow-redirects';\nimport zlib from 'zlib';\nimport {VERSION} from '../env/data.js';\nimport transitionalDefaults from '../defaults/transitional.js';\nimport AxiosError from '../core/AxiosError.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport platform from '../platform/index.js';\nimport fromDataURI from '../helpers/fromDataURI.js';\nimport stream from 'stream';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport AxiosTransformStream from '../helpers/AxiosTransformStream.js';\nimport {EventEmitter} from 'events';\nimport formDataToStream from \"../helpers/formDataToStream.js\";\nimport readBlob from \"../helpers/readBlob.js\";\nimport ZlibHeaderTransformStream from '../helpers/ZlibHeaderTransformStream.js';\nimport callbackify from \"../helpers/callbackify.js\";\nimport {progressEventReducer, progressEventDecorator, asyncDecorator} from \"../helpers/progressEventReducer.js\";\n\nconst zlibOptions = {\n flush: zlib.constants.Z_SYNC_FLUSH,\n finishFlush: zlib.constants.Z_SYNC_FLUSH\n};\n\nconst brotliOptions = {\n flush: zlib.constants.BROTLI_OPERATION_FLUSH,\n finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH\n}\n\nconst isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress);\n\nconst {http: httpFollow, https: httpsFollow} = followRedirects;\n\nconst isHttps = /https:?/;\n\nconst supportedProtocols = platform.protocols.map(protocol => {\n return protocol + ':';\n});\n\nconst flushOnFinish = (stream, [throttled, flush]) => {\n stream\n .on('end', flush)\n .on('error', flush);\n\n return throttled;\n}\n\n/**\n * If the proxy or config beforeRedirects functions are defined, call them with the options\n * object.\n *\n * @param {Object} options - The options object that was passed to the request.\n *\n * @returns {Object}\n */\nfunction dispatchBeforeRedirect(options, responseDetails) {\n if (options.beforeRedirects.proxy) {\n options.beforeRedirects.proxy(options);\n }\n if (options.beforeRedirects.config) {\n options.beforeRedirects.config(options, responseDetails);\n }\n}\n\n/**\n * If the proxy or config afterRedirects functions are defined, call them with the options\n *\n * @param {http.ClientRequestArgs} options\n * @param {AxiosProxyConfig} configProxy configuration from Axios options object\n * @param {string} location\n *\n * @returns {http.ClientRequestArgs}\n */\nfunction setProxy(options, configProxy, location) {\n let proxy = configProxy;\n if (!proxy && proxy !== false) {\n const proxyUrl = proxyFromEnv.getProxyForUrl(location);\n if (proxyUrl) {\n proxy = new URL(proxyUrl);\n }\n }\n if (proxy) {\n // Basic proxy authorization\n if (proxy.username) {\n proxy.auth = (proxy.username || '') + ':' + (proxy.password || '');\n }\n\n if (proxy.auth) {\n // Support proxy auth object form\n if (proxy.auth.username || proxy.auth.password) {\n proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || '');\n }\n const base64 = Buffer\n .from(proxy.auth, 'utf8')\n .toString('base64');\n options.headers['Proxy-Authorization'] = 'Basic ' + base64;\n }\n\n options.headers.host = options.hostname + (options.port ? ':' + options.port : '');\n const proxyHost = proxy.hostname || proxy.host;\n options.hostname = proxyHost;\n // Replace 'host' since options is not a URL object\n options.host = proxyHost;\n options.port = proxy.port;\n options.path = location;\n if (proxy.protocol) {\n options.protocol = proxy.protocol.includes(':') ? proxy.protocol : `${proxy.protocol}:`;\n }\n }\n\n options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {\n // Configure proxy for redirected request, passing the original config proxy to apply\n // the exact same logic as if the redirected request was performed by axios directly.\n setProxy(redirectOptions, configProxy, redirectOptions.href);\n };\n}\n\nconst isHttpAdapterSupported = typeof process !== 'undefined' && utils.kindOf(process) === 'process';\n\n// temporary hotfix\n\nconst wrapAsync = (asyncExecutor) => {\n return new Promise((resolve, reject) => {\n let onDone;\n let isDone;\n\n const done = (value, isRejected) => {\n if (isDone) return;\n isDone = true;\n onDone && onDone(value, isRejected);\n }\n\n const _resolve = (value) => {\n done(value);\n resolve(value);\n };\n\n const _reject = (reason) => {\n done(reason, true);\n reject(reason);\n }\n\n asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject);\n })\n};\n\nconst resolveFamily = ({address, family}) => {\n if (!utils.isString(address)) {\n throw TypeError('address must be a string');\n }\n return ({\n address,\n family: family || (address.indexOf('.') < 0 ? 6 : 4)\n });\n}\n\nconst buildAddressEntry = (address, family) => resolveFamily(utils.isObject(address) ? address : {address, family});\n\n/*eslint consistent-return:0*/\nexport default isHttpAdapterSupported && function httpAdapter(config) {\n return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {\n let {data, lookup, family} = config;\n const {responseType, responseEncoding} = config;\n const method = config.method.toUpperCase();\n let isDone;\n let rejected = false;\n let req;\n\n if (lookup) {\n const _lookup = callbackify(lookup, (value) => utils.isArray(value) ? value : [value]);\n // hotfix to support opt.all option which is required for node 20.x\n lookup = (hostname, opt, cb) => {\n _lookup(hostname, opt, (err, arg0, arg1) => {\n if (err) {\n return cb(err);\n }\n\n const addresses = utils.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];\n\n opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);\n });\n }\n }\n\n // temporary internal emitter until the AxiosRequest class will be implemented\n const emitter = new EventEmitter();\n\n const onFinished = () => {\n if (config.cancelToken) {\n config.cancelToken.unsubscribe(abort);\n }\n\n if (config.signal) {\n config.signal.removeEventListener('abort', abort);\n }\n\n emitter.removeAllListeners();\n }\n\n onDone((value, isRejected) => {\n isDone = true;\n if (isRejected) {\n rejected = true;\n onFinished();\n }\n });\n\n function abort(reason) {\n emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);\n }\n\n emitter.once('abort', reject);\n\n if (config.cancelToken || config.signal) {\n config.cancelToken && config.cancelToken.subscribe(abort);\n if (config.signal) {\n config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);\n }\n }\n\n // Parse url\n const fullPath = buildFullPath(config.baseURL, config.url);\n const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined);\n const protocol = parsed.protocol || supportedProtocols[0];\n\n if (protocol === 'data:') {\n let convertedData;\n\n if (method !== 'GET') {\n return settle(resolve, reject, {\n status: 405,\n statusText: 'method not allowed',\n headers: {},\n config\n });\n }\n\n try {\n convertedData = fromDataURI(config.url, responseType === 'blob', {\n Blob: config.env && config.env.Blob\n });\n } catch (err) {\n throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);\n }\n\n if (responseType === 'text') {\n convertedData = convertedData.toString(responseEncoding);\n\n if (!responseEncoding || responseEncoding === 'utf8') {\n convertedData = utils.stripBOM(convertedData);\n }\n } else if (responseType === 'stream') {\n convertedData = stream.Readable.from(convertedData);\n }\n\n return settle(resolve, reject, {\n data: convertedData,\n status: 200,\n statusText: 'OK',\n headers: new AxiosHeaders(),\n config\n });\n }\n\n if (supportedProtocols.indexOf(protocol) === -1) {\n return reject(new AxiosError(\n 'Unsupported protocol ' + protocol,\n AxiosError.ERR_BAD_REQUEST,\n config\n ));\n }\n\n const headers = AxiosHeaders.from(config.headers).normalize();\n\n // Set User-Agent (required by some servers)\n // See https://github.com/axios/axios/issues/69\n // User-Agent is specified; handle case where no UA header is desired\n // Only set header if it hasn't been set in config\n headers.set('User-Agent', 'axios/' + VERSION, false);\n\n const {onUploadProgress, onDownloadProgress} = config;\n const maxRate = config.maxRate;\n let maxUploadRate = undefined;\n let maxDownloadRate = undefined;\n\n // support for spec compliant FormData objects\n if (utils.isSpecCompliantForm(data)) {\n const userBoundary = headers.getContentType(/boundary=([-_\\w\\d]{10,70})/i);\n\n data = formDataToStream(data, (formHeaders) => {\n headers.set(formHeaders);\n }, {\n tag: `axios-${VERSION}-boundary`,\n boundary: userBoundary && userBoundary[1] || undefined\n });\n // support for https://www.npmjs.com/package/form-data api\n } else if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {\n headers.set(data.getHeaders());\n\n if (!headers.hasContentLength()) {\n try {\n const knownLength = await util.promisify(data.getLength).call(data);\n Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);\n /*eslint no-empty:0*/\n } catch (e) {\n }\n }\n } else if (utils.isBlob(data) || utils.isFile(data)) {\n data.size && headers.setContentType(data.type || 'application/octet-stream');\n headers.setContentLength(data.size || 0);\n data = stream.Readable.from(readBlob(data));\n } else if (data && !utils.isStream(data)) {\n if (Buffer.isBuffer(data)) {\n // Nothing to do...\n } else if (utils.isArrayBuffer(data)) {\n data = Buffer.from(new Uint8Array(data));\n } else if (utils.isString(data)) {\n data = Buffer.from(data, 'utf-8');\n } else {\n return reject(new AxiosError(\n 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',\n AxiosError.ERR_BAD_REQUEST,\n config\n ));\n }\n\n // Add Content-Length header if data exists\n headers.setContentLength(data.length, false);\n\n if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {\n return reject(new AxiosError(\n 'Request body larger than maxBodyLength limit',\n AxiosError.ERR_BAD_REQUEST,\n config\n ));\n }\n }\n\n const contentLength = utils.toFiniteNumber(headers.getContentLength());\n\n if (utils.isArray(maxRate)) {\n maxUploadRate = maxRate[0];\n maxDownloadRate = maxRate[1];\n } else {\n maxUploadRate = maxDownloadRate = maxRate;\n }\n\n if (data && (onUploadProgress || maxUploadRate)) {\n if (!utils.isStream(data)) {\n data = stream.Readable.from(data, {objectMode: false});\n }\n\n data = stream.pipeline([data, new AxiosTransformStream({\n maxRate: utils.toFiniteNumber(maxUploadRate)\n })], utils.noop);\n\n onUploadProgress && data.on('progress', flushOnFinish(\n data,\n progressEventDecorator(\n contentLength,\n progressEventReducer(asyncDecorator(onUploadProgress), false, 3)\n )\n ));\n }\n\n // HTTP basic authentication\n let auth = undefined;\n if (config.auth) {\n const username = config.auth.username || '';\n const password = config.auth.password || '';\n auth = username + ':' + password;\n }\n\n if (!auth && parsed.username) {\n const urlUsername = parsed.username;\n const urlPassword = parsed.password;\n auth = urlUsername + ':' + urlPassword;\n }\n\n auth && headers.delete('authorization');\n\n let path;\n\n try {\n path = buildURL(\n parsed.pathname + parsed.search,\n config.params,\n config.paramsSerializer\n ).replace(/^\\?/, '');\n } catch (err) {\n const customErr = new Error(err.message);\n customErr.config = config;\n customErr.url = config.url;\n customErr.exists = true;\n return reject(customErr);\n }\n\n headers.set(\n 'Accept-Encoding',\n 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false\n );\n\n const options = {\n path,\n method: method,\n headers: headers.toJSON(),\n agents: { http: config.httpAgent, https: config.httpsAgent },\n auth,\n protocol,\n family,\n beforeRedirect: dispatchBeforeRedirect,\n beforeRedirects: {}\n };\n\n // cacheable-lookup integration hotfix\n !utils.isUndefined(lookup) && (options.lookup = lookup);\n\n if (config.socketPath) {\n options.socketPath = config.socketPath;\n } else {\n options.hostname = parsed.hostname.startsWith(\"[\") ? parsed.hostname.slice(1, -1) : parsed.hostname;\n options.port = parsed.port;\n setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);\n }\n\n let transport;\n const isHttpsRequest = isHttps.test(options.protocol);\n options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;\n if (config.transport) {\n transport = config.transport;\n } else if (config.maxRedirects === 0) {\n transport = isHttpsRequest ? https : http;\n } else {\n if (config.maxRedirects) {\n options.maxRedirects = config.maxRedirects;\n }\n if (config.beforeRedirect) {\n options.beforeRedirects.config = config.beforeRedirect;\n }\n transport = isHttpsRequest ? httpsFollow : httpFollow;\n }\n\n if (config.maxBodyLength > -1) {\n options.maxBodyLength = config.maxBodyLength;\n } else {\n // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited\n options.maxBodyLength = Infinity;\n }\n\n if (config.insecureHTTPParser) {\n options.insecureHTTPParser = config.insecureHTTPParser;\n }\n\n // Create the request\n req = transport.request(options, function handleResponse(res) {\n if (req.destroyed) return;\n\n const streams = [res];\n\n const responseLength = +res.headers['content-length'];\n\n if (onDownloadProgress || maxDownloadRate) {\n const transformStream = new AxiosTransformStream({\n maxRate: utils.toFiniteNumber(maxDownloadRate)\n });\n\n onDownloadProgress && transformStream.on('progress', flushOnFinish(\n transformStream,\n progressEventDecorator(\n responseLength,\n progressEventReducer(asyncDecorator(onDownloadProgress), true, 3)\n )\n ));\n\n streams.push(transformStream);\n }\n\n // decompress the response body transparently if required\n let responseStream = res;\n\n // return the last request in case of redirects\n const lastRequest = res.req || req;\n\n // if decompress disabled we should not decompress\n if (config.decompress !== false && res.headers['content-encoding']) {\n // if no content, but headers still say that it is encoded,\n // remove the header not confuse downstream operations\n if (method === 'HEAD' || res.statusCode === 204) {\n delete res.headers['content-encoding'];\n }\n\n switch ((res.headers['content-encoding'] || '').toLowerCase()) {\n /*eslint default-case:0*/\n case 'gzip':\n case 'x-gzip':\n case 'compress':\n case 'x-compress':\n // add the unzipper to the body stream processing pipeline\n streams.push(zlib.createUnzip(zlibOptions));\n\n // remove the content-encoding in order to not confuse downstream operations\n delete res.headers['content-encoding'];\n break;\n case 'deflate':\n streams.push(new ZlibHeaderTransformStream());\n\n // add the unzipper to the body stream processing pipeline\n streams.push(zlib.createUnzip(zlibOptions));\n\n // remove the content-encoding in order to not confuse downstream operations\n delete res.headers['content-encoding'];\n break;\n case 'br':\n if (isBrotliSupported) {\n streams.push(zlib.createBrotliDecompress(brotliOptions));\n delete res.headers['content-encoding'];\n }\n }\n }\n\n responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0];\n\n const offListeners = stream.finished(responseStream, () => {\n offListeners();\n onFinished();\n });\n\n const response = {\n status: res.statusCode,\n statusText: res.statusMessage,\n headers: new AxiosHeaders(res.headers),\n config,\n request: lastRequest\n };\n\n if (responseType === 'stream') {\n response.data = responseStream;\n settle(resolve, reject, response);\n } else {\n const responseBuffer = [];\n let totalResponseBytes = 0;\n\n responseStream.on('data', function handleStreamData(chunk) {\n responseBuffer.push(chunk);\n totalResponseBytes += chunk.length;\n\n // make sure the content length is not over the maxContentLength if specified\n if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {\n // stream.destroy() emit aborted event before calling reject() on Node.js v16\n rejected = true;\n responseStream.destroy();\n reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded',\n AxiosError.ERR_BAD_RESPONSE, config, lastRequest));\n }\n });\n\n responseStream.on('aborted', function handlerStreamAborted() {\n if (rejected) {\n return;\n }\n\n const err = new AxiosError(\n 'stream has been aborted',\n AxiosError.ERR_BAD_RESPONSE,\n config,\n lastRequest\n );\n responseStream.destroy(err);\n reject(err);\n });\n\n responseStream.on('error', function handleStreamError(err) {\n if (req.destroyed) return;\n reject(AxiosError.from(err, null, config, lastRequest));\n });\n\n responseStream.on('end', function handleStreamEnd() {\n try {\n let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);\n if (responseType !== 'arraybuffer') {\n responseData = responseData.toString(responseEncoding);\n if (!responseEncoding || responseEncoding === 'utf8') {\n responseData = utils.stripBOM(responseData);\n }\n }\n response.data = responseData;\n } catch (err) {\n return reject(AxiosError.from(err, null, config, response.request, response));\n }\n settle(resolve, reject, response);\n });\n }\n\n emitter.once('abort', err => {\n if (!responseStream.destroyed) {\n responseStream.emit('error', err);\n responseStream.destroy();\n }\n });\n });\n\n emitter.once('abort', err => {\n reject(err);\n req.destroy(err);\n });\n\n // Handle errors\n req.on('error', function handleRequestError(err) {\n // @todo remove\n // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return;\n reject(AxiosError.from(err, null, config, req));\n });\n\n // set tcp keep alive to prevent drop connection by peer\n req.on('socket', function handleRequestSocket(socket) {\n // default interval of sending ack packet is 1 minute\n socket.setKeepAlive(true, 1000 * 60);\n });\n\n // Handle request timeout\n if (config.timeout) {\n // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.\n const timeout = parseInt(config.timeout, 10);\n\n if (Number.isNaN(timeout)) {\n reject(new AxiosError(\n 'error trying to parse `config.timeout` to int',\n AxiosError.ERR_BAD_OPTION_VALUE,\n config,\n req\n ));\n\n return;\n }\n\n // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.\n // And timer callback will be fired, and abort() will be invoked before connection, then get \"socket hang up\" and code ECONNRESET.\n // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.\n // And then these socket which be hang up will devouring CPU little by little.\n // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.\n req.setTimeout(timeout, function handleRequestTimeout() {\n if (isDone) return;\n let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';\n const transitional = config.transitional || transitionalDefaults;\n if (config.timeoutErrorMessage) {\n timeoutErrorMessage = config.timeoutErrorMessage;\n }\n reject(new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n config,\n req\n ));\n abort();\n });\n }\n\n\n // Send the request\n if (utils.isStream(data)) {\n let ended = false;\n let errored = false;\n\n data.on('end', () => {\n ended = true;\n });\n\n data.once('error', err => {\n errored = true;\n req.destroy(err);\n });\n\n data.on('close', () => {\n if (!ended && !errored) {\n abort(new CanceledError('Request stream has been aborted', config, req));\n }\n });\n\n data.pipe(req);\n } else {\n req.end(data);\n }\n });\n}\n\nexport const __setProxy = setProxy;\n","import platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {\n url = new URL(url, platform.origin);\n\n return (\n origin.protocol === url.protocol &&\n origin.host === url.host &&\n (isMSIE || origin.port === url.port)\n );\n})(\n new URL(platform.origin),\n platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)\n) : () => true;\n","import utils from './../utils.js';\nimport platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ?\n\n // Standard browser envs support document.cookie\n {\n write(name, value, expires, path, domain, secure) {\n const cookie = [name + '=' + encodeURIComponent(value)];\n\n utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());\n\n utils.isString(path) && cookie.push('path=' + path);\n\n utils.isString(domain) && cookie.push('domain=' + domain);\n\n secure === true && cookie.push('secure');\n\n document.cookie = cookie.join('; ');\n },\n\n read(name) {\n const match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n }\n\n :\n\n // Non-standard browser env (web workers, react-native) lack needed support.\n {\n write() {},\n read() {\n return null;\n },\n remove() {}\n };\n\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosHeaders from \"./AxiosHeaders.js\";\n\nconst headersToObject = (thing) => thing instanceof AxiosHeaders ? { ...thing } : thing;\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n *\n * @returns {Object} New object resulting from merging config2 to config1\n */\nexport default function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n const config = {};\n\n function getMergedValue(target, source, prop, caseless) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge.call({caseless}, target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(a, b, prop , caseless) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(a, b, prop , caseless);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a, prop , caseless);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(a, b, prop) {\n if (prop in config2) {\n return getMergedValue(a, b);\n } else if (prop in config1) {\n return getMergedValue(undefined, a);\n }\n }\n\n const mergeMap = {\n url: valueFromConfig2,\n method: valueFromConfig2,\n data: valueFromConfig2,\n baseURL: defaultToConfig2,\n transformRequest: defaultToConfig2,\n transformResponse: defaultToConfig2,\n paramsSerializer: defaultToConfig2,\n timeout: defaultToConfig2,\n timeoutMessage: defaultToConfig2,\n withCredentials: defaultToConfig2,\n withXSRFToken: defaultToConfig2,\n adapter: defaultToConfig2,\n responseType: defaultToConfig2,\n xsrfCookieName: defaultToConfig2,\n xsrfHeaderName: defaultToConfig2,\n onUploadProgress: defaultToConfig2,\n onDownloadProgress: defaultToConfig2,\n decompress: defaultToConfig2,\n maxContentLength: defaultToConfig2,\n maxBodyLength: defaultToConfig2,\n beforeRedirect: defaultToConfig2,\n transport: defaultToConfig2,\n httpAgent: defaultToConfig2,\n httpsAgent: defaultToConfig2,\n cancelToken: defaultToConfig2,\n socketPath: defaultToConfig2,\n responseEncoding: defaultToConfig2,\n validateStatus: mergeDirectKeys,\n headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true)\n };\n\n utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {\n const merge = mergeMap[prop] || mergeDeepProperties;\n const configValue = merge(config1[prop], config2[prop], prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n}\n","import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport isURLSameOrigin from \"./isURLSameOrigin.js\";\nimport cookies from \"./cookies.js\";\nimport buildFullPath from \"../core/buildFullPath.js\";\nimport mergeConfig from \"../core/mergeConfig.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport buildURL from \"./buildURL.js\";\n\nexport default (config) => {\n const newConfig = mergeConfig({}, config);\n\n let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;\n\n newConfig.headers = headers = AxiosHeaders.from(headers);\n\n newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);\n\n // HTTP basic authentication\n if (auth) {\n headers.set('Authorization', 'Basic ' +\n btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))\n );\n }\n\n let contentType;\n\n if (utils.isFormData(data)) {\n if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {\n headers.setContentType(undefined); // Let the browser set it\n } else if ((contentType = headers.getContentType()) !== false) {\n // fix semicolon duplication issue for ReactNative FormData implementation\n const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];\n headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));\n }\n }\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n\n if (platform.hasStandardBrowserEnv) {\n withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));\n\n if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {\n // Add xsrf header\n const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);\n\n if (xsrfValue) {\n headers.set(xsrfHeaderName, xsrfValue);\n }\n }\n }\n\n return newConfig;\n}\n\n","import utils from './../utils.js';\nimport settle from './../core/settle.js';\nimport transitionalDefaults from '../defaults/transitional.js';\nimport AxiosError from '../core/AxiosError.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport parseProtocol from '../helpers/parseProtocol.js';\nimport platform from '../platform/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport {progressEventReducer} from '../helpers/progressEventReducer.js';\nimport resolveConfig from \"../helpers/resolveConfig.js\";\n\nconst isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';\n\nexport default isXHRAdapterSupported && function (config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n const _config = resolveConfig(config);\n let requestData = _config.data;\n const requestHeaders = AxiosHeaders.from(_config.headers).normalize();\n let {responseType, onUploadProgress, onDownloadProgress} = _config;\n let onCanceled;\n let uploadThrottled, downloadThrottled;\n let flushUpload, flushDownload;\n\n function done() {\n flushUpload && flushUpload(); // flush events\n flushDownload && flushDownload(); // flush events\n\n _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);\n\n _config.signal && _config.signal.removeEventListener('abort', onCanceled);\n }\n\n let request = new XMLHttpRequest();\n\n request.open(_config.method.toUpperCase(), _config.url, true);\n\n // Set the request timeout in MS\n request.timeout = _config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n const responseHeaders = AxiosHeaders.from(\n 'getAllResponseHeaders' in request && request.getAllResponseHeaders()\n );\n const responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n const response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config,\n request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';\n const transitional = _config.transitional || transitionalDefaults;\n if (_config.timeoutErrorMessage) {\n timeoutErrorMessage = _config.timeoutErrorMessage;\n }\n reject(new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n config,\n request));\n\n // Clean up request\n request = null;\n };\n\n // Remove Content-Type if data is undefined\n requestData === undefined && requestHeaders.setContentType(null);\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {\n request.setRequestHeader(key, val);\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(_config.withCredentials)) {\n request.withCredentials = !!_config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = _config.responseType;\n }\n\n // Handle progress if needed\n if (onDownloadProgress) {\n ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));\n request.addEventListener('progress', downloadThrottled);\n }\n\n // Not all browsers support upload events\n if (onUploadProgress && request.upload) {\n ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));\n\n request.upload.addEventListener('progress', uploadThrottled);\n\n request.upload.addEventListener('loadend', flushUpload);\n }\n\n if (_config.cancelToken || _config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = cancel => {\n if (!request) {\n return;\n }\n reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);\n request.abort();\n request = null;\n };\n\n _config.cancelToken && _config.cancelToken.subscribe(onCanceled);\n if (_config.signal) {\n _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n const protocol = parseProtocol(_config.url);\n\n if (protocol && platform.protocols.indexOf(protocol) === -1) {\n reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));\n return;\n }\n\n\n // Send the request\n request.send(requestData || null);\n });\n}\n","import CanceledError from \"../cancel/CanceledError.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport utils from '../utils.js';\n\nconst composeSignals = (signals, timeout) => {\n const {length} = (signals = signals ? signals.filter(Boolean) : []);\n\n if (timeout || length) {\n let controller = new AbortController();\n\n let aborted;\n\n const onabort = function (reason) {\n if (!aborted) {\n aborted = true;\n unsubscribe();\n const err = reason instanceof Error ? reason : this.reason;\n controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));\n }\n }\n\n let timer = timeout && setTimeout(() => {\n timer = null;\n onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT))\n }, timeout)\n\n const unsubscribe = () => {\n if (signals) {\n timer && clearTimeout(timer);\n timer = null;\n signals.forEach(signal => {\n signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);\n });\n signals = null;\n }\n }\n\n signals.forEach((signal) => signal.addEventListener('abort', onabort));\n\n const {signal} = controller;\n\n signal.unsubscribe = () => utils.asap(unsubscribe);\n\n return signal;\n }\n}\n\nexport default composeSignals;\n","\nexport const streamChunk = function* (chunk, chunkSize) {\n let len = chunk.byteLength;\n\n if (!chunkSize || len < chunkSize) {\n yield chunk;\n return;\n }\n\n let pos = 0;\n let end;\n\n while (pos < len) {\n end = pos + chunkSize;\n yield chunk.slice(pos, end);\n pos = end;\n }\n}\n\nexport const readBytes = async function* (iterable, chunkSize) {\n for await (const chunk of readStream(iterable)) {\n yield* streamChunk(chunk, chunkSize);\n }\n}\n\nconst readStream = async function* (stream) {\n if (stream[Symbol.asyncIterator]) {\n yield* stream;\n return;\n }\n\n const reader = stream.getReader();\n try {\n for (;;) {\n const {done, value} = await reader.read();\n if (done) {\n break;\n }\n yield value;\n }\n } finally {\n await reader.cancel();\n }\n}\n\nexport const trackStream = (stream, chunkSize, onProgress, onFinish) => {\n const iterator = readBytes(stream, chunkSize);\n\n let bytes = 0;\n let done;\n let _onFinish = (e) => {\n if (!done) {\n done = true;\n onFinish && onFinish(e);\n }\n }\n\n return new ReadableStream({\n async pull(controller) {\n try {\n const {done, value} = await iterator.next();\n\n if (done) {\n _onFinish();\n controller.close();\n return;\n }\n\n let len = value.byteLength;\n if (onProgress) {\n let loadedBytes = bytes += len;\n onProgress(loadedBytes);\n }\n controller.enqueue(new Uint8Array(value));\n } catch (err) {\n _onFinish(err);\n throw err;\n }\n },\n cancel(reason) {\n _onFinish(reason);\n return iterator.return();\n }\n }, {\n highWaterMark: 2\n })\n}\n","import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport composeSignals from \"../helpers/composeSignals.js\";\nimport {trackStream} from \"../helpers/trackStream.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport {progressEventReducer, progressEventDecorator, asyncDecorator} from \"../helpers/progressEventReducer.js\";\nimport resolveConfig from \"../helpers/resolveConfig.js\";\nimport settle from \"../core/settle.js\";\n\nconst isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';\nconst isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';\n\n// used only inside the fetch adapter\nconst encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?\n ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :\n async (str) => new Uint8Array(await new Response(str).arrayBuffer())\n);\n\nconst test = (fn, ...args) => {\n try {\n return !!fn(...args);\n } catch (e) {\n return false\n }\n}\n\nconst supportsRequestStream = isReadableStreamSupported && test(() => {\n let duplexAccessed = false;\n\n const hasContentType = new Request(platform.origin, {\n body: new ReadableStream(),\n method: 'POST',\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n }).headers.has('Content-Type');\n\n return duplexAccessed && !hasContentType;\n});\n\nconst DEFAULT_CHUNK_SIZE = 64 * 1024;\n\nconst supportsResponseStream = isReadableStreamSupported &&\n test(() => utils.isReadableStream(new Response('').body));\n\n\nconst resolvers = {\n stream: supportsResponseStream && ((res) => res.body)\n};\n\nisFetchSupported && (((res) => {\n ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {\n !resolvers[type] && (resolvers[type] = utils.isFunction(res[type]) ? (res) => res[type]() :\n (_, config) => {\n throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);\n })\n });\n})(new Response));\n\nconst getBodyLength = async (body) => {\n if (body == null) {\n return 0;\n }\n\n if(utils.isBlob(body)) {\n return body.size;\n }\n\n if(utils.isSpecCompliantForm(body)) {\n const _request = new Request(platform.origin, {\n method: 'POST',\n body,\n });\n return (await _request.arrayBuffer()).byteLength;\n }\n\n if(utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) {\n return body.byteLength;\n }\n\n if(utils.isURLSearchParams(body)) {\n body = body + '';\n }\n\n if(utils.isString(body)) {\n return (await encodeText(body)).byteLength;\n }\n}\n\nconst resolveBodyLength = async (headers, body) => {\n const length = utils.toFiniteNumber(headers.getContentLength());\n\n return length == null ? getBodyLength(body) : length;\n}\n\nexport default isFetchSupported && (async (config) => {\n let {\n url,\n method,\n data,\n signal,\n cancelToken,\n timeout,\n onDownloadProgress,\n onUploadProgress,\n responseType,\n headers,\n withCredentials = 'same-origin',\n fetchOptions\n } = resolveConfig(config);\n\n responseType = responseType ? (responseType + '').toLowerCase() : 'text';\n\n let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);\n\n let request;\n\n const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {\n composedSignal.unsubscribe();\n });\n\n let requestContentLength;\n\n try {\n if (\n onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&\n (requestContentLength = await resolveBodyLength(headers, data)) !== 0\n ) {\n let _request = new Request(url, {\n method: 'POST',\n body: data,\n duplex: \"half\"\n });\n\n let contentTypeHeader;\n\n if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {\n headers.setContentType(contentTypeHeader)\n }\n\n if (_request.body) {\n const [onProgress, flush] = progressEventDecorator(\n requestContentLength,\n progressEventReducer(asyncDecorator(onUploadProgress))\n );\n\n data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);\n }\n }\n\n if (!utils.isString(withCredentials)) {\n withCredentials = withCredentials ? 'include' : 'omit';\n }\n\n // Cloudflare Workers throws when credentials are defined\n // see https://github.com/cloudflare/workerd/issues/902\n const isCredentialsSupported = \"credentials\" in Request.prototype;\n request = new Request(url, {\n ...fetchOptions,\n signal: composedSignal,\n method: method.toUpperCase(),\n headers: headers.normalize().toJSON(),\n body: data,\n duplex: \"half\",\n credentials: isCredentialsSupported ? withCredentials : undefined\n });\n\n let response = await fetch(request);\n\n const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');\n\n if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {\n const options = {};\n\n ['status', 'statusText', 'headers'].forEach(prop => {\n options[prop] = response[prop];\n });\n\n const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length'));\n\n const [onProgress, flush] = onDownloadProgress && progressEventDecorator(\n responseContentLength,\n progressEventReducer(asyncDecorator(onDownloadProgress), true)\n ) || [];\n\n response = new Response(\n trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {\n flush && flush();\n unsubscribe && unsubscribe();\n }),\n options\n );\n }\n\n responseType = responseType || 'text';\n\n let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config);\n\n !isStreamResponse && unsubscribe && unsubscribe();\n\n return await new Promise((resolve, reject) => {\n settle(resolve, reject, {\n data: responseData,\n headers: AxiosHeaders.from(response.headers),\n status: response.status,\n statusText: response.statusText,\n config,\n request\n })\n })\n } catch (err) {\n unsubscribe && unsubscribe();\n\n if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {\n throw Object.assign(\n new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),\n {\n cause: err.cause || err\n }\n )\n }\n\n throw AxiosError.from(err, err && err.code, config, request);\n }\n});\n\n\n","import utils from '../utils.js';\nimport httpAdapter from './http.js';\nimport xhrAdapter from './xhr.js';\nimport fetchAdapter from './fetch.js';\nimport AxiosError from \"../core/AxiosError.js\";\n\nconst knownAdapters = {\n http: httpAdapter,\n xhr: xhrAdapter,\n fetch: fetchAdapter\n}\n\nutils.forEach(knownAdapters, (fn, value) => {\n if (fn) {\n try {\n Object.defineProperty(fn, 'name', {value});\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n Object.defineProperty(fn, 'adapterName', {value});\n }\n});\n\nconst renderReason = (reason) => `- ${reason}`;\n\nconst isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false;\n\nexport default {\n getAdapter: (adapters) => {\n adapters = utils.isArray(adapters) ? adapters : [adapters];\n\n const {length} = adapters;\n let nameOrAdapter;\n let adapter;\n\n const rejectedReasons = {};\n\n for (let i = 0; i < length; i++) {\n nameOrAdapter = adapters[i];\n let id;\n\n adapter = nameOrAdapter;\n\n if (!isResolvedHandle(nameOrAdapter)) {\n adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];\n\n if (adapter === undefined) {\n throw new AxiosError(`Unknown adapter '${id}'`);\n }\n }\n\n if (adapter) {\n break;\n }\n\n rejectedReasons[id || '#' + i] = adapter;\n }\n\n if (!adapter) {\n\n const reasons = Object.entries(rejectedReasons)\n .map(([id, state]) => `adapter ${id} ` +\n (state === false ? 'is not supported by the environment' : 'is not available in the build')\n );\n\n let s = length ?\n (reasons.length > 1 ? 'since :\\n' + reasons.map(renderReason).join('\\n') : ' ' + renderReason(reasons[0])) :\n 'as no adapter specified';\n\n throw new AxiosError(\n `There is no suitable adapter to dispatch the request ` + s,\n 'ERR_NOT_SUPPORT'\n );\n }\n\n return adapter;\n },\n adapters: knownAdapters\n}\n","'use strict';\n\nimport transformData from './transformData.js';\nimport isCancel from '../cancel/isCancel.js';\nimport defaults from '../defaults/index.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport adapters from \"../adapters/adapters.js\";\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n *\n * @param {Object} config The config that is to be used for the request\n *\n * @returns {void}\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new CanceledError(null, config);\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n *\n * @returns {Promise} The Promise to be fulfilled\n */\nexport default function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n config.headers = AxiosHeaders.from(config.headers);\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.transformRequest\n );\n\n if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {\n config.headers.setContentType('application/x-www-form-urlencoded', false);\n }\n\n const adapter = adapters.getAdapter(config.adapter || defaults.adapter);\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n config.transformResponse,\n response\n );\n\n response.headers = AxiosHeaders.from(response.headers);\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n config.transformResponse,\n reason.response\n );\n reason.response.headers = AxiosHeaders.from(reason.response.headers);\n }\n }\n\n return Promise.reject(reason);\n });\n}\n","'use strict';\n\nimport {VERSION} from '../env/data.js';\nimport AxiosError from '../core/AxiosError.js';\n\nconst validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nconst deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n *\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n *\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return (value, opt, opts) => {\n if (validator === false) {\n throw new AxiosError(\n formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),\n AxiosError.ERR_DEPRECATED\n );\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\nvalidators.spelling = function spelling(correctSpelling) {\n return (value, opt) => {\n // eslint-disable-next-line no-console\n console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);\n return true;\n }\n};\n\n/**\n * Assert object's properties type\n *\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n *\n * @returns {object}\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);\n }\n const keys = Object.keys(options);\n let i = keys.length;\n while (i-- > 0) {\n const opt = keys[i];\n const validator = schema[opt];\n if (validator) {\n const value = options[opt];\n const result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);\n }\n }\n}\n\nexport default {\n assertOptions,\n validators\n};\n","'use strict';\n\nimport utils from './../utils.js';\nimport buildURL from '../helpers/buildURL.js';\nimport InterceptorManager from './InterceptorManager.js';\nimport dispatchRequest from './dispatchRequest.js';\nimport mergeConfig from './mergeConfig.js';\nimport buildFullPath from './buildFullPath.js';\nimport validator from '../helpers/validator.js';\nimport AxiosHeaders from './AxiosHeaders.js';\n\nconst validators = validator.validators;\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n *\n * @return {Axios} A new instance of Axios\n */\nclass Axios {\n constructor(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n }\n\n /**\n * Dispatch a request\n *\n * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)\n * @param {?Object} config\n *\n * @returns {Promise} The Promise to be fulfilled\n */\n async request(configOrUrl, config) {\n try {\n return await this._request(configOrUrl, config);\n } catch (err) {\n if (err instanceof Error) {\n let dummy = {};\n\n Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());\n\n // slice off the Error: ... line\n const stack = dummy.stack ? dummy.stack.replace(/^.+\\n/, '') : '';\n try {\n if (!err.stack) {\n err.stack = stack;\n // match without the 2 top stack lines\n } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\\n.+\\n/, ''))) {\n err.stack += '\\n' + stack\n }\n } catch (e) {\n // ignore the case where \"stack\" is an un-writable property\n }\n }\n\n throw err;\n }\n }\n\n _request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n const {transitional, paramsSerializer, headers} = config;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n if (paramsSerializer != null) {\n if (utils.isFunction(paramsSerializer)) {\n config.paramsSerializer = {\n serialize: paramsSerializer\n }\n } else {\n validator.assertOptions(paramsSerializer, {\n encode: validators.function,\n serialize: validators.function\n }, true);\n }\n }\n\n validator.assertOptions(config, {\n baseUrl: validators.spelling('baseURL'),\n withXsrfToken: validators.spelling('withXSRFToken')\n }, true);\n\n // Set config.method\n config.method = (config.method || this.defaults.method || 'get').toLowerCase();\n\n // Flatten headers\n let contextHeaders = headers && utils.merge(\n headers.common,\n headers[config.method]\n );\n\n headers && utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n (method) => {\n delete headers[method];\n }\n );\n\n config.headers = AxiosHeaders.concat(contextHeaders, headers);\n\n // filter out skipped interceptors\n const requestInterceptorChain = [];\n let synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n const responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n let promise;\n let i = 0;\n let len;\n\n if (!synchronousRequestInterceptors) {\n const chain = [dispatchRequest.bind(this), undefined];\n chain.unshift.apply(chain, requestInterceptorChain);\n chain.push.apply(chain, responseInterceptorChain);\n len = chain.length;\n\n promise = Promise.resolve(config);\n\n while (i < len) {\n promise = promise.then(chain[i++], chain[i++]);\n }\n\n return promise;\n }\n\n len = requestInterceptorChain.length;\n\n let newConfig = config;\n\n i = 0;\n\n while (i < len) {\n const onFulfilled = requestInterceptorChain[i++];\n const onRejected = requestInterceptorChain[i++];\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected.call(this, error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest.call(this, newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n i = 0;\n len = responseInterceptorChain.length;\n\n while (i < len) {\n promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);\n }\n\n return promise;\n }\n\n getUri(config) {\n config = mergeConfig(this.defaults, config);\n const fullPath = buildFullPath(config.baseURL, config.url);\n return buildURL(fullPath, config.params, config.paramsSerializer);\n }\n}\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n\n function generateHTTPMethod(isForm) {\n return function httpMethod(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n headers: isForm ? {\n 'Content-Type': 'multipart/form-data'\n } : {},\n url,\n data\n }));\n };\n }\n\n Axios.prototype[method] = generateHTTPMethod();\n\n Axios.prototype[method + 'Form'] = generateHTTPMethod(true);\n});\n\nexport default Axios;\n","'use strict';\n\nimport CanceledError from './CanceledError.js';\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @param {Function} executor The executor function.\n *\n * @returns {CancelToken}\n */\nclass CancelToken {\n constructor(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n let resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n const token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(cancel => {\n if (!token._listeners) return;\n\n let i = token._listeners.length;\n\n while (i-- > 0) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = onfulfilled => {\n let _resolve;\n // eslint-disable-next-line func-names\n const promise = new Promise(resolve => {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message, config, request) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new CanceledError(message, config, request);\n resolvePromise(token.reason);\n });\n }\n\n /**\n * Throws a `CanceledError` if cancellation has been requested.\n */\n throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n }\n\n /**\n * Subscribe to the cancel signal\n */\n\n subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n }\n\n /**\n * Unsubscribe from the cancel signal\n */\n\n unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n const index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n }\n\n toAbortSignal() {\n const controller = new AbortController();\n\n const abort = (err) => {\n controller.abort(err);\n };\n\n this.subscribe(abort);\n\n controller.signal.unsubscribe = () => this.unsubscribe(abort);\n\n return controller.signal;\n }\n\n /**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\n static source() {\n let cancel;\n const token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token,\n cancel\n };\n }\n}\n\nexport default CancelToken;\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n *\n * @returns {Function}\n */\nexport default function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n *\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nexport default function isAxiosError(payload) {\n return utils.isObject(payload) && (payload.isAxiosError === true);\n}\n","const HttpStatusCode = {\n Continue: 100,\n SwitchingProtocols: 101,\n Processing: 102,\n EarlyHints: 103,\n Ok: 200,\n Created: 201,\n Accepted: 202,\n NonAuthoritativeInformation: 203,\n NoContent: 204,\n ResetContent: 205,\n PartialContent: 206,\n MultiStatus: 207,\n AlreadyReported: 208,\n ImUsed: 226,\n MultipleChoices: 300,\n MovedPermanently: 301,\n Found: 302,\n SeeOther: 303,\n NotModified: 304,\n UseProxy: 305,\n Unused: 306,\n TemporaryRedirect: 307,\n PermanentRedirect: 308,\n BadRequest: 400,\n Unauthorized: 401,\n PaymentRequired: 402,\n Forbidden: 403,\n NotFound: 404,\n MethodNotAllowed: 405,\n NotAcceptable: 406,\n ProxyAuthenticationRequired: 407,\n RequestTimeout: 408,\n Conflict: 409,\n Gone: 410,\n LengthRequired: 411,\n PreconditionFailed: 412,\n PayloadTooLarge: 413,\n UriTooLong: 414,\n UnsupportedMediaType: 415,\n RangeNotSatisfiable: 416,\n ExpectationFailed: 417,\n ImATeapot: 418,\n MisdirectedRequest: 421,\n UnprocessableEntity: 422,\n Locked: 423,\n FailedDependency: 424,\n TooEarly: 425,\n UpgradeRequired: 426,\n PreconditionRequired: 428,\n TooManyRequests: 429,\n RequestHeaderFieldsTooLarge: 431,\n UnavailableForLegalReasons: 451,\n InternalServerError: 500,\n NotImplemented: 501,\n BadGateway: 502,\n ServiceUnavailable: 503,\n GatewayTimeout: 504,\n HttpVersionNotSupported: 505,\n VariantAlsoNegotiates: 506,\n InsufficientStorage: 507,\n LoopDetected: 508,\n NotExtended: 510,\n NetworkAuthenticationRequired: 511,\n};\n\nObject.entries(HttpStatusCode).forEach(([key, value]) => {\n HttpStatusCode[value] = key;\n});\n\nexport default HttpStatusCode;\n","'use strict';\n\nimport utils from './utils.js';\nimport bind from './helpers/bind.js';\nimport Axios from './core/Axios.js';\nimport mergeConfig from './core/mergeConfig.js';\nimport defaults from './defaults/index.js';\nimport formDataToJSON from './helpers/formDataToJSON.js';\nimport CanceledError from './cancel/CanceledError.js';\nimport CancelToken from './cancel/CancelToken.js';\nimport isCancel from './cancel/isCancel.js';\nimport {VERSION} from './env/data.js';\nimport toFormData from './helpers/toFormData.js';\nimport AxiosError from './core/AxiosError.js';\nimport spread from './helpers/spread.js';\nimport isAxiosError from './helpers/isAxiosError.js';\nimport AxiosHeaders from \"./core/AxiosHeaders.js\";\nimport adapters from './adapters/adapters.js';\nimport HttpStatusCode from './helpers/HttpStatusCode.js';\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n *\n * @returns {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n const context = new Axios(defaultConfig);\n const instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});\n\n // Copy context to instance\n utils.extend(instance, context, null, {allOwnKeys: true});\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nconst axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.CanceledError = CanceledError;\naxios.CancelToken = CancelToken;\naxios.isCancel = isCancel;\naxios.VERSION = VERSION;\naxios.toFormData = toFormData;\n\n// Expose AxiosError class\naxios.AxiosError = AxiosError;\n\n// alias for CanceledError for backward compatibility\naxios.Cancel = axios.CanceledError;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\n\naxios.spread = spread;\n\n// Expose isAxiosError\naxios.isAxiosError = isAxiosError;\n\n// Expose mergeConfig\naxios.mergeConfig = mergeConfig;\n\naxios.AxiosHeaders = AxiosHeaders;\n\naxios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);\n\naxios.getAdapter = adapters.getAdapter;\n\naxios.HttpStatusCode = HttpStatusCode;\n\naxios.default = axios;\n\n// this module should only have a default export\nexport default axios\n"],"names":["utils","prototype","PlatformFormData","encode","url","FormData","platform","defaults","AxiosHeaders","stream","util","readBlob","Readable","zlib","followRedirects","proxyFromEnv","callbackify","EventEmitter","formDataToStream","AxiosTransformStream","https","http","ZlibHeaderTransformStream","composeSignals","validators","InterceptorManager","Axios","CancelToken","HttpStatusCode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAEe,SAAS,IAAI,CAAC,EAAE,EAAE,OAAO,EAAE;AAC1C,EAAE,OAAO,SAAS,IAAI,GAAG;AACzB,IAAI,OAAO,EAAE,CAAC,KAAK,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;AACxC,GAAG,CAAC;AACJ;;ACFA;AACA;AACA,MAAM,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC,SAAS,CAAC;AACpC,MAAM,CAAC,cAAc,CAAC,GAAG,MAAM,CAAC;AAChC;AACA,MAAM,MAAM,GAAG,CAAC,KAAK,IAAI,KAAK,IAAI;AAClC,IAAI,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACrC,IAAI,OAAO,KAAK,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AACvE,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACxB;AACA,MAAM,UAAU,GAAG,CAAC,IAAI,KAAK;AAC7B,EAAE,IAAI,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;AAC5B,EAAE,OAAO,CAAC,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,KAAK,IAAI;AAC1C,EAAC;AACD;AACA,MAAM,UAAU,GAAG,IAAI,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,IAAI,CAAC;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,WAAW,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,QAAQ,CAAC,GAAG,EAAE;AACvB,EAAE,OAAO,GAAG,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,WAAW,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,WAAW,CAAC;AACvG,OAAO,UAAU,CAAC,GAAG,CAAC,WAAW,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC,WAAW,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AAC7E,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,UAAU,CAAC,aAAa,CAAC,CAAC;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,iBAAiB,CAAC,GAAG,EAAE;AAChC,EAAE,IAAI,MAAM,CAAC;AACb,EAAE,IAAI,CAAC,OAAO,WAAW,KAAK,WAAW,MAAM,WAAW,CAAC,MAAM,CAAC,EAAE;AACpE,IAAI,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACrC,GAAG,MAAM;AACT,IAAI,MAAM,GAAG,CAAC,GAAG,MAAM,GAAG,CAAC,MAAM,CAAC,KAAK,aAAa,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;AAClE,GAAG;AACH,EAAE,OAAO,MAAM,CAAC;AAChB,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,UAAU,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,KAAK,KAAK,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,SAAS,GAAG,KAAK,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,KAAK,CAAC;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,GAAG,KAAK;AAC/B,EAAE,IAAI,MAAM,CAAC,GAAG,CAAC,KAAK,QAAQ,EAAE;AAChC,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA,EAAE,MAAM,SAAS,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC;AACxC,EAAE,OAAO,CAAC,SAAS,KAAK,IAAI,IAAI,SAAS,KAAK,MAAM,CAAC,SAAS,IAAI,MAAM,CAAC,cAAc,CAAC,SAAS,CAAC,KAAK,IAAI,KAAK,EAAE,MAAM,CAAC,WAAW,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,QAAQ,IAAI,GAAG,CAAC,CAAC;AAC1K,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,UAAU,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,GAAG,KAAK,QAAQ,CAAC,GAAG,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AAChE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,UAAU,GAAG,CAAC,KAAK,KAAK;AAC9B,EAAE,IAAI,IAAI,CAAC;AACX,EAAE,OAAO,KAAK;AACd,IAAI,CAAC,OAAO,QAAQ,KAAK,UAAU,IAAI,KAAK,YAAY,QAAQ;AAChE,MAAM,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC;AAC9B,QAAQ,CAAC,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,UAAU;AAC7C;AACA,SAAS,IAAI,KAAK,QAAQ,IAAI,UAAU,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,KAAK,CAAC,QAAQ,EAAE,KAAK,mBAAmB,CAAC;AACrG,OAAO;AACP,KAAK;AACL,GAAG;AACH,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,iBAAiB,GAAG,UAAU,CAAC,iBAAiB,CAAC,CAAC;AACxD;AACA,MAAM,CAAC,gBAAgB,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,CAAC,GAAG,CAAC,gBAAgB,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;AAClI;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,IAAI;AAC9B,EAAE,GAAG,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,oCAAoC,EAAE,EAAE,CAAC,CAAC;AACrE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,OAAO,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC,UAAU,GAAG,KAAK,CAAC,GAAG,EAAE,EAAE;AACrD;AACA,EAAE,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,WAAW,EAAE;AAClD,IAAI,OAAO;AACX,GAAG;AACH;AACA,EAAE,IAAI,CAAC,CAAC;AACR,EAAE,IAAI,CAAC,CAAC;AACR;AACA;AACA,EAAE,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;AAC/B;AACA,IAAI,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;AAChB,GAAG;AACH;AACA,EAAE,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE;AACpB;AACA,IAAI,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AAC5C,MAAM,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AACpC,KAAK;AACL,GAAG,MAAM;AACT;AACA,IAAI,MAAM,IAAI,GAAG,UAAU,GAAG,MAAM,CAAC,mBAAmB,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjF,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC;AAC5B,IAAI,IAAI,GAAG,CAAC;AACZ;AACA,IAAI,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;AAC9B,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,MAAM,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AACxC,KAAK;AACL,GAAG;AACH,CAAC;AACD;AACA,SAAS,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE;AAC3B,EAAE,GAAG,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;AAC1B,EAAE,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAChC,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;AACtB,EAAE,IAAI,IAAI,CAAC;AACX,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AAClB,IAAI,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AACnB,IAAI,IAAI,GAAG,KAAK,IAAI,CAAC,WAAW,EAAE,EAAE;AACpC,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL,GAAG;AACH,EAAE,OAAO,IAAI,CAAC;AACd,CAAC;AACD;AACA,MAAM,OAAO,GAAG,CAAC,MAAM;AACvB;AACA,EAAE,IAAI,OAAO,UAAU,KAAK,WAAW,EAAE,OAAO,UAAU,CAAC;AAC3D,EAAE,OAAO,OAAO,IAAI,KAAK,WAAW,GAAG,IAAI,IAAI,OAAO,MAAM,KAAK,WAAW,GAAG,MAAM,GAAG,MAAM,CAAC;AAC/F,CAAC,GAAG,CAAC;AACL;AACA,MAAM,gBAAgB,GAAG,CAAC,OAAO,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,OAAO,KAAK,OAAO,CAAC;AACnF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,KAAK,8BAA8B;AAC5C,EAAE,MAAM,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,EAAE,CAAC;AAC1D,EAAE,MAAM,MAAM,GAAG,EAAE,CAAC;AACpB,EAAE,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,GAAG,KAAK;AACpC,IAAI,MAAM,SAAS,GAAG,QAAQ,IAAI,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,GAAG,CAAC;AAC9D,IAAI,IAAI,aAAa,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,IAAI,aAAa,CAAC,GAAG,CAAC,EAAE;AAChE,MAAM,MAAM,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,GAAG,CAAC,CAAC;AACxD,KAAK,MAAM,IAAI,aAAa,CAAC,GAAG,CAAC,EAAE;AACnC,MAAM,MAAM,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;AACzC,KAAK,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE;AAC7B,MAAM,MAAM,CAAC,SAAS,CAAC,GAAG,GAAG,CAAC,KAAK,EAAE,CAAC;AACtC,KAAK,MAAM;AACX,MAAM,MAAM,CAAC,SAAS,CAAC,GAAG,GAAG,CAAC;AAC9B,KAAK;AACL,IAAG;AACH;AACA,EAAE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AACpD,IAAI,SAAS,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC;AACvD,GAAG;AACH,EAAE,OAAO,MAAM,CAAC;AAChB,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,UAAU,CAAC,EAAE,EAAE,KAAK;AACpD,EAAE,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK;AAC3B,IAAI,IAAI,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,EAAE;AACpC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;AAClC,KAAK,MAAM;AACX,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC;AACnB,KAAK;AACL,GAAG,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;AACnB,EAAE,OAAO,CAAC,CAAC;AACX,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,OAAO,KAAK;AAC9B,EAAE,IAAI,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE;AACxC,IAAI,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAC/B,GAAG;AACH,EAAE,OAAO,OAAO,CAAC;AACjB,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,WAAW,EAAE,gBAAgB,EAAE,KAAK,EAAE,WAAW,KAAK;AACxE,EAAE,WAAW,CAAC,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;AACjF,EAAE,WAAW,CAAC,SAAS,CAAC,WAAW,GAAG,WAAW,CAAC;AAClD,EAAE,MAAM,CAAC,cAAc,CAAC,WAAW,EAAE,OAAO,EAAE;AAC9C,IAAI,KAAK,EAAE,gBAAgB,CAAC,SAAS;AACrC,GAAG,CAAC,CAAC;AACL,EAAE,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AACvD,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,YAAY,GAAG,CAAC,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,KAAK;AACjE,EAAE,IAAI,KAAK,CAAC;AACZ,EAAE,IAAI,CAAC,CAAC;AACR,EAAE,IAAI,IAAI,CAAC;AACX,EAAE,MAAM,MAAM,GAAG,EAAE,CAAC;AACpB;AACA,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;AAC1B;AACA,EAAE,IAAI,SAAS,IAAI,IAAI,EAAE,OAAO,OAAO,CAAC;AACxC;AACA,EAAE,GAAG;AACL,IAAI,KAAK,GAAG,MAAM,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC;AAClD,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC;AACrB,IAAI,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AACpB,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,IAAI,CAAC,CAAC,UAAU,IAAI,UAAU,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;AAClF,QAAQ,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;AACxC,QAAQ,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAC5B,OAAO;AACP,KAAK;AACL,IAAI,SAAS,GAAG,MAAM,KAAK,KAAK,IAAI,cAAc,CAAC,SAAS,CAAC,CAAC;AAC9D,GAAG,QAAQ,SAAS,KAAK,CAAC,MAAM,IAAI,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,SAAS,KAAK,MAAM,CAAC,SAAS,EAAE;AACnG;AACA,EAAE,OAAO,OAAO,CAAC;AACjB,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,GAAG,EAAE,YAAY,EAAE,QAAQ,KAAK;AAClD,EAAE,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AACpB,EAAE,IAAI,QAAQ,KAAK,SAAS,IAAI,QAAQ,GAAG,GAAG,CAAC,MAAM,EAAE;AACvD,IAAI,QAAQ,GAAG,GAAG,CAAC,MAAM,CAAC;AAC1B,GAAG;AACH,EAAE,QAAQ,IAAI,YAAY,CAAC,MAAM,CAAC;AAClC,EAAE,MAAM,SAAS,GAAG,GAAG,CAAC,OAAO,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC;AACxD,EAAE,OAAO,SAAS,KAAK,CAAC,CAAC,IAAI,SAAS,KAAK,QAAQ,CAAC;AACpD,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,OAAO,GAAG,CAAC,KAAK,KAAK;AAC3B,EAAE,IAAI,CAAC,KAAK,EAAE,OAAO,IAAI,CAAC;AAC1B,EAAE,IAAI,OAAO,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;AACnC,EAAE,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC;AACvB,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,OAAO,IAAI,CAAC;AAChC,EAAE,MAAM,GAAG,GAAG,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC;AAC3B,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AAClB,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AACtB,GAAG;AACH,EAAE,OAAO,GAAG,CAAC;AACb,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,YAAY,GAAG,CAAC,UAAU,IAAI;AACpC;AACA,EAAE,OAAO,KAAK,IAAI;AAClB,IAAI,OAAO,UAAU,IAAI,KAAK,YAAY,UAAU,CAAC;AACrD,GAAG,CAAC;AACJ,CAAC,EAAE,OAAO,UAAU,KAAK,WAAW,IAAI,cAAc,CAAC,UAAU,CAAC,CAAC,CAAC;AACpE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,YAAY,GAAG,CAAC,GAAG,EAAE,EAAE,KAAK;AAClC,EAAE,MAAM,SAAS,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAChD;AACA,EAAE,MAAM,QAAQ,GAAG,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACvC;AACA,EAAE,IAAI,MAAM,CAAC;AACb;AACA,EAAE,OAAO,CAAC,MAAM,GAAG,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE;AACrD,IAAI,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC;AAC9B,IAAI,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AACnC,GAAG;AACH,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,CAAC,MAAM,EAAE,GAAG,KAAK;AAClC,EAAE,IAAI,OAAO,CAAC;AACd,EAAE,MAAM,GAAG,GAAG,EAAE,CAAC;AACjB;AACA,EAAE,OAAO,CAAC,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,IAAI,EAAE;AAChD,IAAI,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACtB,GAAG;AACH;AACA,EAAE,OAAO,GAAG,CAAC;AACb,EAAC;AACD;AACA;AACA,MAAM,UAAU,GAAG,UAAU,CAAC,iBAAiB,CAAC,CAAC;AACjD;AACA,MAAM,WAAW,GAAG,GAAG,IAAI;AAC3B,EAAE,OAAO,GAAG,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,uBAAuB;AAC1D,IAAI,SAAS,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE;AACjC,MAAM,OAAO,EAAE,CAAC,WAAW,EAAE,GAAG,EAAE,CAAC;AACnC,KAAK;AACL,GAAG,CAAC;AACJ,CAAC,CAAC;AACF;AACA;AACA,MAAM,cAAc,GAAG,CAAC,CAAC,CAAC,cAAc,CAAC,KAAK,CAAC,GAAG,EAAE,IAAI,KAAK,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC;AAC/G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;AACtC;AACA,MAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,OAAO,KAAK;AAC5C,EAAE,MAAM,WAAW,GAAG,MAAM,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC;AAC5D,EAAE,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAChC;AACA,EAAE,OAAO,CAAC,WAAW,EAAE,CAAC,UAAU,EAAE,IAAI,KAAK;AAC7C,IAAI,IAAI,GAAG,CAAC;AACZ,IAAI,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,UAAU,EAAE,IAAI,EAAE,GAAG,CAAC,MAAM,KAAK,EAAE;AAC1D,MAAM,kBAAkB,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,UAAU,CAAC;AACnD,KAAK;AACL,GAAG,CAAC,CAAC;AACL;AACA,EAAE,MAAM,CAAC,gBAAgB,CAAC,GAAG,EAAE,kBAAkB,CAAC,CAAC;AACnD,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,GAAG,KAAK;AAC/B,EAAE,iBAAiB,CAAC,GAAG,EAAE,CAAC,UAAU,EAAE,IAAI,KAAK;AAC/C;AACA,IAAI,IAAI,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE;AACnF,MAAM,OAAO,KAAK,CAAC;AACnB,KAAK;AACL;AACA,IAAI,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC;AAC5B;AACA,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,OAAO;AACnC;AACA,IAAI,UAAU,CAAC,UAAU,GAAG,KAAK,CAAC;AAClC;AACA,IAAI,IAAI,UAAU,IAAI,UAAU,EAAE;AAClC,MAAM,UAAU,CAAC,QAAQ,GAAG,KAAK,CAAC;AAClC,MAAM,OAAO;AACb,KAAK;AACL;AACA,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE;AACzB,MAAM,UAAU,CAAC,GAAG,GAAG,MAAM;AAC7B,QAAQ,MAAM,KAAK,CAAC,qCAAqC,GAAG,IAAI,GAAG,IAAI,CAAC,CAAC;AACzE,OAAO,CAAC;AACR,KAAK;AACL,GAAG,CAAC,CAAC;AACL,EAAC;AACD;AACA,MAAM,WAAW,GAAG,CAAC,aAAa,EAAE,SAAS,KAAK;AAClD,EAAE,MAAM,GAAG,GAAG,EAAE,CAAC;AACjB;AACA,EAAE,MAAM,MAAM,GAAG,CAAC,GAAG,KAAK;AAC1B,IAAI,GAAG,CAAC,OAAO,CAAC,KAAK,IAAI;AACzB,MAAM,GAAG,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC;AACxB,KAAK,CAAC,CAAC;AACP,IAAG;AACH;AACA,EAAE,OAAO,CAAC,aAAa,CAAC,GAAG,MAAM,CAAC,aAAa,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC;AAClG;AACA,EAAE,OAAO,GAAG,CAAC;AACb,EAAC;AACD;AACA,MAAM,IAAI,GAAG,MAAM,GAAE;AACrB;AACA,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,YAAY,KAAK;AAChD,EAAE,OAAO,KAAK,IAAI,IAAI,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,GAAG,CAAC,KAAK,CAAC,GAAG,KAAK,GAAG,YAAY,CAAC;AACjF,EAAC;AACD;AACA,MAAM,KAAK,GAAG,6BAA4B;AAC1C;AACA,MAAM,KAAK,GAAG,YAAY,CAAC;AAC3B;AACA,MAAM,QAAQ,GAAG;AACjB,EAAE,KAAK;AACP,EAAE,KAAK;AACP,EAAE,WAAW,EAAE,KAAK,GAAG,KAAK,CAAC,WAAW,EAAE,GAAG,KAAK;AAClD,EAAC;AACD;AACA,MAAM,cAAc,GAAG,CAAC,IAAI,GAAG,EAAE,EAAE,QAAQ,GAAG,QAAQ,CAAC,WAAW,KAAK;AACvE,EAAE,IAAI,GAAG,GAAG,EAAE,CAAC;AACf,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC;AAC5B,EAAE,OAAO,IAAI,EAAE,EAAE;AACjB,IAAI,GAAG,IAAI,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,MAAM,CAAC,CAAC,EAAC;AAC7C,GAAG;AACH;AACA,EAAE,OAAO,GAAG,CAAC;AACb,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,mBAAmB,CAAC,KAAK,EAAE;AACpC,EAAE,OAAO,CAAC,EAAE,KAAK,IAAI,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,WAAW,CAAC,KAAK,UAAU,IAAI,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;AACrH,CAAC;AACD;AACA,MAAM,YAAY,GAAG,CAAC,GAAG,KAAK;AAC9B,EAAE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC;AAC9B;AACA,EAAE,MAAM,KAAK,GAAG,CAAC,MAAM,EAAE,CAAC,KAAK;AAC/B;AACA,IAAI,IAAI,QAAQ,CAAC,MAAM,CAAC,EAAE;AAC1B,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;AACtC,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,GAAG,EAAE,QAAQ,IAAI,MAAM,CAAC,EAAE;AAChC,QAAQ,KAAK,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC;AAC1B,QAAQ,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;AACjD;AACA,QAAQ,OAAO,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK;AACxC,UAAU,MAAM,YAAY,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;AACnD,UAAU,CAAC,WAAW,CAAC,YAAY,CAAC,KAAK,MAAM,CAAC,GAAG,CAAC,GAAG,YAAY,CAAC,CAAC;AACrE,SAAS,CAAC,CAAC;AACX;AACA,QAAQ,KAAK,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC;AAC7B;AACA,QAAQ,OAAO,MAAM,CAAC;AACtB,OAAO;AACP,KAAK;AACL;AACA,IAAI,OAAO,MAAM,CAAC;AAClB,IAAG;AACH;AACA,EAAE,OAAO,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;AACvB,EAAC;AACD;AACA,MAAM,SAAS,GAAG,UAAU,CAAC,eAAe,CAAC,CAAC;AAC9C;AACA,MAAM,UAAU,GAAG,CAAC,KAAK;AACzB,EAAE,KAAK,KAAK,QAAQ,CAAC,KAAK,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACvG;AACA;AACA;AACA;AACA,MAAM,aAAa,GAAG,CAAC,CAAC,qBAAqB,EAAE,oBAAoB,KAAK;AACxE,EAAE,IAAI,qBAAqB,EAAE;AAC7B,IAAI,OAAO,YAAY,CAAC;AACxB,GAAG;AACH;AACA,EAAE,OAAO,oBAAoB,GAAG,CAAC,CAAC,KAAK,EAAE,SAAS,KAAK;AACvD,IAAI,OAAO,CAAC,gBAAgB,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK;AAC5D,MAAM,IAAI,MAAM,KAAK,OAAO,IAAI,IAAI,KAAK,KAAK,EAAE;AAChD,QAAQ,SAAS,CAAC,MAAM,IAAI,SAAS,CAAC,KAAK,EAAE,EAAE,CAAC;AAChD,OAAO;AACP,KAAK,EAAE,KAAK,CAAC,CAAC;AACd;AACA,IAAI,OAAO,CAAC,EAAE,KAAK;AACnB,MAAM,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACzB,MAAM,OAAO,CAAC,WAAW,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AACtC,KAAK;AACL,GAAG,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,UAAU,CAAC,EAAE,CAAC,CAAC;AAC5D,CAAC;AACD,EAAE,OAAO,YAAY,KAAK,UAAU;AACpC,EAAE,UAAU,CAAC,OAAO,CAAC,WAAW,CAAC;AACjC,CAAC,CAAC;AACF;AACA,MAAM,IAAI,GAAG,OAAO,cAAc,KAAK,WAAW;AAClD,EAAE,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,CAAC,QAAQ,IAAI,aAAa,CAAC,CAAC;AACxG;AACA;AACA;AACA,gBAAe;AACf,EAAE,OAAO;AACT,EAAE,aAAa;AACf,EAAE,QAAQ;AACV,EAAE,UAAU;AACZ,EAAE,iBAAiB;AACnB,EAAE,QAAQ;AACV,EAAE,QAAQ;AACV,EAAE,SAAS;AACX,EAAE,QAAQ;AACV,EAAE,aAAa;AACf,EAAE,gBAAgB;AAClB,EAAE,SAAS;AACX,EAAE,UAAU;AACZ,EAAE,SAAS;AACX,EAAE,WAAW;AACb,EAAE,MAAM;AACR,EAAE,MAAM;AACR,EAAE,MAAM;AACR,EAAE,QAAQ;AACV,EAAE,UAAU;AACZ,EAAE,QAAQ;AACV,EAAE,iBAAiB;AACnB,EAAE,YAAY;AACd,EAAE,UAAU;AACZ,EAAE,OAAO;AACT,EAAE,KAAK;AACP,EAAE,MAAM;AACR,EAAE,IAAI;AACN,EAAE,QAAQ;AACV,EAAE,QAAQ;AACV,EAAE,YAAY;AACd,EAAE,MAAM;AACR,EAAE,UAAU;AACZ,EAAE,QAAQ;AACV,EAAE,OAAO;AACT,EAAE,YAAY;AACd,EAAE,QAAQ;AACV,EAAE,UAAU;AACZ,EAAE,cAAc;AAChB,EAAE,UAAU,EAAE,cAAc;AAC5B,EAAE,iBAAiB;AACnB,EAAE,aAAa;AACf,EAAE,WAAW;AACb,EAAE,WAAW;AACb,EAAE,IAAI;AACN,EAAE,cAAc;AAChB,EAAE,OAAO;AACT,EAAE,MAAM,EAAE,OAAO;AACjB,EAAE,gBAAgB;AAClB,EAAE,QAAQ;AACV,EAAE,cAAc;AAChB,EAAE,mBAAmB;AACrB,EAAE,YAAY;AACd,EAAE,SAAS;AACX,EAAE,UAAU;AACZ,EAAE,YAAY,EAAE,aAAa;AAC7B,EAAE,IAAI;AACN,CAAC;;ACnvBD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,UAAU,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE;AAC9D,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACnB;AACA,EAAE,IAAI,KAAK,CAAC,iBAAiB,EAAE;AAC/B,IAAI,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;AACpD,GAAG,MAAM;AACT,IAAI,IAAI,CAAC,KAAK,GAAG,CAAC,IAAI,KAAK,EAAE,EAAE,KAAK,CAAC;AACrC,GAAG;AACH;AACA,EAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;AACzB,EAAE,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;AAC3B,EAAE,IAAI,KAAK,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC;AAC7B,EAAE,MAAM,KAAK,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC;AACnC,EAAE,OAAO,KAAK,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,CAAC;AACtC,EAAE,IAAI,QAAQ,EAAE;AAChB,IAAI,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAC7B,IAAI,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC,MAAM,GAAG,IAAI,CAAC;AAC3D,GAAG;AACH,CAAC;AACD;AACAA,OAAK,CAAC,QAAQ,CAAC,UAAU,EAAE,KAAK,EAAE;AAClC,EAAE,MAAM,EAAE,SAAS,MAAM,GAAG;AAC5B,IAAI,OAAO;AACX;AACA,MAAM,OAAO,EAAE,IAAI,CAAC,OAAO;AAC3B,MAAM,IAAI,EAAE,IAAI,CAAC,IAAI;AACrB;AACA,MAAM,WAAW,EAAE,IAAI,CAAC,WAAW;AACnC,MAAM,MAAM,EAAE,IAAI,CAAC,MAAM;AACzB;AACA,MAAM,QAAQ,EAAE,IAAI,CAAC,QAAQ;AAC7B,MAAM,UAAU,EAAE,IAAI,CAAC,UAAU;AACjC,MAAM,YAAY,EAAE,IAAI,CAAC,YAAY;AACrC,MAAM,KAAK,EAAE,IAAI,CAAC,KAAK;AACvB;AACA,MAAM,MAAM,EAAEA,OAAK,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC;AAC7C,MAAM,IAAI,EAAE,IAAI,CAAC,IAAI;AACrB,MAAM,MAAM,EAAE,IAAI,CAAC,MAAM;AACzB,KAAK,CAAC;AACN,GAAG;AACH,CAAC,CAAC,CAAC;AACH;AACA,MAAMC,WAAS,GAAG,UAAU,CAAC,SAAS,CAAC;AACvC,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB;AACA;AACA,EAAE,sBAAsB;AACxB,EAAE,gBAAgB;AAClB,EAAE,cAAc;AAChB,EAAE,WAAW;AACb,EAAE,aAAa;AACf,EAAE,2BAA2B;AAC7B,EAAE,gBAAgB;AAClB,EAAE,kBAAkB;AACpB,EAAE,iBAAiB;AACnB,EAAE,cAAc;AAChB,EAAE,iBAAiB;AACnB,EAAE,iBAAiB;AACnB;AACA,CAAC,CAAC,OAAO,CAAC,IAAI,IAAI;AAClB,EAAE,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACpC,CAAC,CAAC,CAAC;AACH;AACA,MAAM,CAAC,gBAAgB,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;AACjD,MAAM,CAAC,cAAc,CAACA,WAAS,EAAE,cAAc,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;AAChE;AACA;AACA,UAAU,CAAC,IAAI,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,WAAW,KAAK;AAC3E,EAAE,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAACA,WAAS,CAAC,CAAC;AAC9C;AACA,EAAED,OAAK,CAAC,YAAY,CAAC,KAAK,EAAE,UAAU,EAAE,SAAS,MAAM,CAAC,GAAG,EAAE;AAC7D,IAAI,OAAO,GAAG,KAAK,KAAK,CAAC,SAAS,CAAC;AACnC,GAAG,EAAE,IAAI,IAAI;AACb,IAAI,OAAO,IAAI,KAAK,cAAc,CAAC;AACnC,GAAG,CAAC,CAAC;AACL;AACA,EAAE,UAAU,CAAC,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC9E;AACA,EAAE,UAAU,CAAC,KAAK,GAAG,KAAK,CAAC;AAC3B;AACA,EAAE,UAAU,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;AAC/B;AACA,EAAE,WAAW,IAAI,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;AACxD;AACA,EAAE,OAAO,UAAU,CAAC;AACpB,CAAC;;AC7FD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,WAAW,CAAC,KAAK,EAAE;AAC5B,EAAE,OAAOA,OAAK,CAAC,aAAa,CAAC,KAAK,CAAC,IAAIA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,cAAc,CAAC,GAAG,EAAE;AAC7B,EAAE,OAAOA,OAAK,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC;AAC5D,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,SAAS,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE;AACpC,EAAE,IAAI,CAAC,IAAI,EAAE,OAAO,GAAG,CAAC;AACxB,EAAE,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,KAAK,EAAE,CAAC,EAAE;AACtD;AACA,IAAI,KAAK,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;AAClC,IAAI,OAAO,CAAC,IAAI,IAAI,CAAC,GAAG,GAAG,GAAG,KAAK,GAAG,GAAG,GAAG,KAAK,CAAC;AAClD,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC,CAAC;AAC3B,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,WAAW,CAAC,GAAG,EAAE;AAC1B,EAAE,OAAOA,OAAK,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AACtD,CAAC;AACD;AACA,MAAM,UAAU,GAAGA,OAAK,CAAC,YAAY,CAACA,OAAK,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,MAAM,CAAC,IAAI,EAAE;AAC7E,EAAE,OAAO,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC/B,CAAC,CAAC,CAAC;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,UAAU,CAAC,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE;AAC5C,EAAE,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;AAC5B,IAAI,MAAM,IAAI,SAAS,CAAC,0BAA0B,CAAC,CAAC;AACpD,GAAG;AACH;AACA;AACA,EAAE,QAAQ,GAAG,QAAQ,IAAI,KAAKE,4BAAgB,IAAI,QAAQ,GAAG,CAAC;AAC9D;AACA;AACA,EAAE,OAAO,GAAGF,OAAK,CAAC,YAAY,CAAC,OAAO,EAAE;AACxC,IAAI,UAAU,EAAE,IAAI;AACpB,IAAI,IAAI,EAAE,KAAK;AACf,IAAI,OAAO,EAAE,KAAK;AAClB,GAAG,EAAE,KAAK,EAAE,SAAS,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE;AAC7C;AACA,IAAI,OAAO,CAACA,OAAK,CAAC,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;AAC9C,GAAG,CAAC,CAAC;AACL;AACA,EAAE,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;AACxC;AACA,EAAE,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,cAAc,CAAC;AACpD,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;AAC5B,EAAE,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;AAClC,EAAE,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,WAAW,IAAI,IAAI,CAAC;AACpE,EAAE,MAAM,OAAO,GAAG,KAAK,IAAIA,OAAK,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAC;AAC/D;AACA,EAAE,IAAI,CAACA,OAAK,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE;AAClC,IAAI,MAAM,IAAI,SAAS,CAAC,4BAA4B,CAAC,CAAC;AACtD,GAAG;AACH;AACA,EAAE,SAAS,YAAY,CAAC,KAAK,EAAE;AAC/B,IAAI,IAAI,KAAK,KAAK,IAAI,EAAE,OAAO,EAAE,CAAC;AAClC;AACA,IAAI,IAAIA,OAAK,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;AAC7B,MAAM,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;AACjC,KAAK;AACL;AACA,IAAI,IAAI,CAAC,OAAO,IAAIA,OAAK,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;AACzC,MAAM,MAAM,IAAI,UAAU,CAAC,8CAA8C,CAAC,CAAC;AAC3E,KAAK;AACL;AACA,IAAI,IAAIA,OAAK,CAAC,aAAa,CAAC,KAAK,CAAC,IAAIA,OAAK,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE;AACjE,MAAM,OAAO,OAAO,IAAI,OAAO,IAAI,KAAK,UAAU,GAAG,IAAI,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC5F,KAAK;AACL;AACA,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,SAAS,cAAc,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE;AAC5C,IAAI,IAAI,GAAG,GAAG,KAAK,CAAC;AACpB;AACA,IAAI,IAAI,KAAK,IAAI,CAAC,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;AACrD,MAAM,IAAIA,OAAK,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE;AACrC;AACA,QAAQ,GAAG,GAAG,UAAU,GAAG,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAClD;AACA,QAAQ,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AACtC,OAAO,MAAM;AACb,QAAQ,CAACA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,WAAW,CAAC,KAAK,CAAC;AACnD,SAAS,CAACA,OAAK,CAAC,UAAU,CAAC,KAAK,CAAC,IAAIA,OAAK,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC/F,SAAS,EAAE;AACX;AACA,QAAQ,GAAG,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC;AAClC;AACA,QAAQ,GAAG,CAAC,OAAO,CAAC,SAAS,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE;AAC7C,UAAU,EAAEA,OAAK,CAAC,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,KAAK,IAAI,CAAC,IAAI,QAAQ,CAAC,MAAM;AACpE;AACA,YAAY,OAAO,KAAK,IAAI,GAAG,SAAS,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,OAAO,KAAK,IAAI,GAAG,GAAG,GAAG,GAAG,GAAG,IAAI,CAAC;AACpG,YAAY,YAAY,CAAC,EAAE,CAAC;AAC5B,WAAW,CAAC;AACZ,SAAS,CAAC,CAAC;AACX,QAAQ,OAAO,KAAK,CAAC;AACrB,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE;AAC5B,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL;AACA,IAAI,QAAQ,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC;AACrE;AACA,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA,EAAE,MAAM,KAAK,GAAG,EAAE,CAAC;AACnB;AACA,EAAE,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE;AACnD,IAAI,cAAc;AAClB,IAAI,YAAY;AAChB,IAAI,WAAW;AACf,GAAG,CAAC,CAAC;AACL;AACA,EAAE,SAAS,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE;AAC9B,IAAI,IAAIA,OAAK,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE,OAAO;AACzC;AACA,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE;AACrC,MAAM,MAAM,KAAK,CAAC,iCAAiC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AACtE,KAAK;AACL;AACA,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACtB;AACA,IAAIA,OAAK,CAAC,OAAO,CAAC,KAAK,EAAE,SAAS,IAAI,CAAC,EAAE,EAAE,GAAG,EAAE;AAChD,MAAM,MAAM,MAAM,GAAG,EAAEA,OAAK,CAAC,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,KAAK,IAAI,CAAC,IAAI,OAAO,CAAC,IAAI;AAC5E,QAAQ,QAAQ,EAAE,EAAE,EAAEA,OAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,GAAG,GAAG,EAAE,IAAI,EAAE,cAAc;AAClF,OAAO,CAAC;AACR;AACA,MAAM,IAAI,MAAM,KAAK,IAAI,EAAE;AAC3B,QAAQ,KAAK,CAAC,EAAE,EAAE,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;AACnD,OAAO;AACP,KAAK,CAAC,CAAC;AACP;AACA,IAAI,KAAK,CAAC,GAAG,EAAE,CAAC;AAChB,GAAG;AACH;AACA,EAAE,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;AAC5B,IAAI,MAAM,IAAI,SAAS,CAAC,wBAAwB,CAAC,CAAC;AAClD,GAAG;AACH;AACA,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;AACb;AACA,EAAE,OAAO,QAAQ,CAAC;AAClB;;ACpNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASG,QAAM,CAAC,GAAG,EAAE;AACrB,EAAE,MAAM,OAAO,GAAG;AAClB,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,GAAG,EAAE,KAAK;AACd,IAAI,KAAK,EAAE,GAAG;AACd,IAAI,KAAK,EAAE,MAAM;AACjB,GAAG,CAAC;AACJ,EAAE,OAAO,kBAAkB,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,kBAAkB,EAAE,SAAS,QAAQ,CAAC,KAAK,EAAE;AACtF,IAAI,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC;AAC1B,GAAG,CAAC,CAAC;AACL,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,oBAAoB,CAAC,MAAM,EAAE,OAAO,EAAE;AAC/C,EAAE,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;AACnB;AACA,EAAE,MAAM,IAAI,UAAU,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;AAC9C,CAAC;AACD;AACA,MAAM,SAAS,GAAG,oBAAoB,CAAC,SAAS,CAAC;AACjD;AACA,SAAS,CAAC,MAAM,GAAG,SAAS,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE;AAChD,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;AAClC,CAAC,CAAC;AACF;AACA,SAAS,CAAC,QAAQ,GAAG,SAAS,QAAQ,CAAC,OAAO,EAAE;AAChD,EAAE,MAAM,OAAO,GAAG,OAAO,GAAG,SAAS,KAAK,EAAE;AAC5C,IAAI,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAEA,QAAM,CAAC,CAAC;AAC7C,GAAG,GAAGA,QAAM,CAAC;AACb;AACA,EAAE,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,IAAI,EAAE;AAC7C,IAAI,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AACrD,GAAG,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACnB,CAAC;;AClDD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,MAAM,CAAC,GAAG,EAAE;AACrB,EAAE,OAAO,kBAAkB,CAAC,GAAG,CAAC;AAChC,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;AACzB,IAAI,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;AACxB,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;AACzB,IAAI,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;AACxB,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC;AACzB,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AAC1B,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE;AACvD;AACA,EAAE,IAAI,CAAC,MAAM,EAAE;AACf,IAAI,OAAO,GAAG,CAAC;AACf,GAAG;AACH;AACA,EAAE,MAAM,OAAO,GAAG,OAAO,IAAI,OAAO,CAAC,MAAM,IAAI,MAAM,CAAC;AACtD;AACA,EAAE,IAAIH,OAAK,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE;AACjC,IAAI,OAAO,GAAG;AACd,MAAM,SAAS,EAAE,OAAO;AACxB,KAAK,CAAC;AACN,GAAG;AACH;AACA,EAAE,MAAM,WAAW,GAAG,OAAO,IAAI,OAAO,CAAC,SAAS,CAAC;AACnD;AACA,EAAE,IAAI,gBAAgB,CAAC;AACvB;AACA,EAAE,IAAI,WAAW,EAAE;AACnB,IAAI,gBAAgB,GAAG,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AACpD,GAAG,MAAM;AACT,IAAI,gBAAgB,GAAGA,OAAK,CAAC,iBAAiB,CAAC,MAAM,CAAC;AACtD,MAAM,MAAM,CAAC,QAAQ,EAAE;AACvB,MAAM,IAAI,oBAAoB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAClE,GAAG;AACH;AACA,EAAE,IAAI,gBAAgB,EAAE;AACxB,IAAI,MAAM,aAAa,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AAC3C;AACA,IAAI,IAAI,aAAa,KAAK,CAAC,CAAC,EAAE;AAC9B,MAAM,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC,CAAC;AACxC,KAAK;AACL,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG,IAAI,gBAAgB,CAAC;AACpE,GAAG;AACH;AACA,EAAE,OAAO,GAAG,CAAC;AACb;;AChEA,MAAM,kBAAkB,CAAC;AACzB,EAAE,WAAW,GAAG;AAChB,IAAI,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;AACvB,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,GAAG,CAAC,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE;AACpC,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;AACvB,MAAM,SAAS;AACf,MAAM,QAAQ;AACd,MAAM,WAAW,EAAE,OAAO,GAAG,OAAO,CAAC,WAAW,GAAG,KAAK;AACxD,MAAM,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI;AAC/C,KAAK,CAAC,CAAC;AACP,IAAI,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;AACpC,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,KAAK,CAAC,EAAE,EAAE;AACZ,IAAI,IAAI,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE;AAC3B,MAAM,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC;AAC/B,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,KAAK,GAAG;AACV,IAAI,IAAI,IAAI,CAAC,QAAQ,EAAE;AACvB,MAAM,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;AACzB,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,OAAO,CAAC,EAAE,EAAE;AACd,IAAIA,OAAK,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,SAAS,cAAc,CAAC,CAAC,EAAE;AAC5D,MAAM,IAAI,CAAC,KAAK,IAAI,EAAE;AACtB,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC;AACd,OAAO;AACP,KAAK,CAAC,CAAC;AACP,GAAG;AACH,CAAC;AACD;AACA,6BAAe,kBAAkB;;ACpEjC,6BAAe;AACf,EAAE,iBAAiB,EAAE,IAAI;AACzB,EAAE,iBAAiB,EAAE,IAAI;AACzB,EAAE,mBAAmB,EAAE,KAAK;AAC5B,CAAC;;ACHD,wBAAeI,uBAAG,CAAC,eAAe;;ACAlC,mBAAe;AACf,EAAE,MAAM,EAAE,IAAI;AACd,EAAE,OAAO,EAAE;AACX,IAAI,eAAe;AACnB,cAAIC,4BAAQ;AACZ,IAAI,IAAI,EAAE,OAAO,IAAI,KAAK,WAAW,IAAI,IAAI,IAAI,IAAI;AACrD,GAAG;AACH,EAAE,SAAS,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE;AAChD,CAAC;;ACXD,MAAM,aAAa,GAAG,OAAO,MAAM,KAAK,WAAW,IAAI,OAAO,QAAQ,KAAK,WAAW,CAAC;AACvF;AACA,MAAM,UAAU,GAAG,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,IAAI,SAAS,CAAC;AAC3E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,qBAAqB,GAAG,aAAa;AAC3C,GAAG,CAAC,UAAU,IAAI,CAAC,aAAa,EAAE,cAAc,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;AACzF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,8BAA8B,GAAG,CAAC,MAAM;AAC9C,EAAE;AACF,IAAI,OAAO,iBAAiB,KAAK,WAAW;AAC5C;AACA,IAAI,IAAI,YAAY,iBAAiB;AACrC,IAAI,OAAO,IAAI,CAAC,aAAa,KAAK,UAAU;AAC5C,IAAI;AACJ,CAAC,GAAG,CAAC;AACL;AACA,MAAM,MAAM,GAAG,aAAa,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,IAAI,kBAAkB;;;;;;;;;;;ACvC1E,iBAAe;AACf,EAAE,GAAG,KAAK;AACV,EAAE,GAAGC,UAAQ;AACb;;ACAe,SAAS,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE;AACxD,EAAE,OAAO,UAAU,CAAC,IAAI,EAAE,IAAI,QAAQ,CAAC,OAAO,CAAC,eAAe,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC;AAChF,IAAI,OAAO,EAAE,SAAS,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE;AACjD,MAAM,IAAI,QAAQ,CAAC,MAAM,IAAIN,OAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;AACpD,QAAQ,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC;AACnD,QAAQ,OAAO,KAAK,CAAC;AACrB,OAAO;AACP;AACA,MAAM,OAAO,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;AAC3D,KAAK;AACL,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AACf;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,aAAa,CAAC,IAAI,EAAE;AAC7B;AACA;AACA;AACA;AACA,EAAE,OAAOA,OAAK,CAAC,QAAQ,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,IAAI;AAC5D,IAAI,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC;AACzD,GAAG,CAAC,CAAC;AACL,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,aAAa,CAAC,GAAG,EAAE;AAC5B,EAAE,MAAM,GAAG,GAAG,EAAE,CAAC;AACjB,EAAE,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAChC,EAAE,IAAI,CAAC,CAAC;AACR,EAAE,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC;AAC1B,EAAE,IAAI,GAAG,CAAC;AACV,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;AAC5B,IAAI,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;AACxB,GAAG;AACH,EAAE,OAAO,GAAG,CAAC;AACb,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,cAAc,CAAC,QAAQ,EAAE;AAClC,EAAE,SAAS,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE;AACjD,IAAI,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;AAC7B;AACA,IAAI,IAAI,IAAI,KAAK,WAAW,EAAE,OAAO,IAAI,CAAC;AAC1C;AACA,IAAI,MAAM,YAAY,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC;AAChD,IAAI,MAAM,MAAM,GAAG,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC;AACxC,IAAI,IAAI,GAAG,CAAC,IAAI,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC;AACjE;AACA,IAAI,IAAI,MAAM,EAAE;AAChB,MAAM,IAAIA,OAAK,CAAC,UAAU,CAAC,MAAM,EAAE,IAAI,CAAC,EAAE;AAC1C,QAAQ,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC;AAC7C,OAAO,MAAM;AACb,QAAQ,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;AAC7B,OAAO;AACP;AACA,MAAM,OAAO,CAAC,YAAY,CAAC;AAC3B,KAAK;AACL;AACA,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE;AACxD,MAAM,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;AACxB,KAAK;AACL;AACA,IAAI,MAAM,MAAM,GAAG,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC;AAC/D;AACA,IAAI,IAAI,MAAM,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE;AAC/C,MAAM,MAAM,CAAC,IAAI,CAAC,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACjD,KAAK;AACL;AACA,IAAI,OAAO,CAAC,YAAY,CAAC;AACzB,GAAG;AACH;AACA,EAAE,IAAIA,OAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAIA,OAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;AACxE,IAAI,MAAM,GAAG,GAAG,EAAE,CAAC;AACnB;AACA,IAAIA,OAAK,CAAC,YAAY,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK;AAClD,MAAM,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;AACpD,KAAK,CAAC,CAAC;AACP;AACA,IAAI,OAAO,GAAG,CAAC;AACf,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC;AACd;;AClFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE;AACpD,EAAE,IAAIA,OAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE;AAChC,IAAI,IAAI;AACR,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;AACvC,MAAM,OAAOA,OAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAClC,KAAK,CAAC,OAAO,CAAC,EAAE;AAChB,MAAM,IAAI,CAAC,CAAC,IAAI,KAAK,aAAa,EAAE;AACpC,QAAQ,MAAM,CAAC,CAAC;AAChB,OAAO;AACP,KAAK;AACL,GAAG;AACH;AACA,EAAE,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;AAC/C,CAAC;AACD;AACA,MAAM,QAAQ,GAAG;AACjB;AACA,EAAE,YAAY,EAAE,oBAAoB;AACpC;AACA,EAAE,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC;AACnC;AACA,EAAE,gBAAgB,EAAE,CAAC,SAAS,gBAAgB,CAAC,IAAI,EAAE,OAAO,EAAE;AAC9D,IAAI,MAAM,WAAW,GAAG,OAAO,CAAC,cAAc,EAAE,IAAI,EAAE,CAAC;AACvD,IAAI,MAAM,kBAAkB,GAAG,WAAW,CAAC,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC;AAC5E,IAAI,MAAM,eAAe,GAAGA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AACjD;AACA,IAAI,IAAI,eAAe,IAAIA,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;AACnD,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC;AAChC,KAAK;AACL;AACA,IAAI,MAAM,UAAU,GAAGA,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAC9C;AACA,IAAI,IAAI,UAAU,EAAE;AACpB,MAAM,OAAO,kBAAkB,GAAG,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC;AAC9E,KAAK;AACL;AACA,IAAI,IAAIA,OAAK,CAAC,aAAa,CAAC,IAAI,CAAC;AACjC,MAAMA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;AAC1B,MAAMA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;AAC1B,MAAMA,OAAK,CAAC,MAAM,CAAC,IAAI,CAAC;AACxB,MAAMA,OAAK,CAAC,MAAM,CAAC,IAAI,CAAC;AACxB,MAAMA,OAAK,CAAC,gBAAgB,CAAC,IAAI,CAAC;AAClC,MAAM;AACN,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL,IAAI,IAAIA,OAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE;AACvC,MAAM,OAAO,IAAI,CAAC,MAAM,CAAC;AACzB,KAAK;AACL,IAAI,IAAIA,OAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE;AACvC,MAAM,OAAO,CAAC,cAAc,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;AACvF,MAAM,OAAO,IAAI,CAAC,QAAQ,EAAE,CAAC;AAC7B,KAAK;AACL;AACA,IAAI,IAAI,UAAU,CAAC;AACnB;AACA,IAAI,IAAI,eAAe,EAAE;AACzB,MAAM,IAAI,WAAW,CAAC,OAAO,CAAC,mCAAmC,CAAC,GAAG,CAAC,CAAC,EAAE;AACzE,QAAQ,OAAO,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC,QAAQ,EAAE,CAAC;AACtE,OAAO;AACP;AACA,MAAM,IAAI,CAAC,UAAU,GAAGA,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,WAAW,CAAC,OAAO,CAAC,qBAAqB,CAAC,GAAG,CAAC,CAAC,EAAE;AACpG,QAAQ,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC;AACxD;AACA,QAAQ,OAAO,UAAU;AACzB,UAAU,UAAU,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,GAAG,IAAI;AAC/C,UAAU,SAAS,IAAI,IAAI,SAAS,EAAE;AACtC,UAAU,IAAI,CAAC,cAAc;AAC7B,SAAS,CAAC;AACV,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAI,eAAe,IAAI,kBAAkB,GAAG;AAChD,MAAM,OAAO,CAAC,cAAc,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;AACxD,MAAM,OAAO,eAAe,CAAC,IAAI,CAAC,CAAC;AACnC,KAAK;AACL;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG,CAAC;AACJ;AACA,EAAE,iBAAiB,EAAE,CAAC,SAAS,iBAAiB,CAAC,IAAI,EAAE;AACvD,IAAI,MAAM,YAAY,GAAG,IAAI,CAAC,YAAY,IAAI,QAAQ,CAAC,YAAY,CAAC;AACpE,IAAI,MAAM,iBAAiB,GAAG,YAAY,IAAI,YAAY,CAAC,iBAAiB,CAAC;AAC7E,IAAI,MAAM,aAAa,GAAG,IAAI,CAAC,YAAY,KAAK,MAAM,CAAC;AACvD;AACA,IAAI,IAAIA,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,IAAIA,OAAK,CAAC,gBAAgB,CAAC,IAAI,CAAC,EAAE;AAChE,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL;AACA,IAAI,IAAI,IAAI,IAAIA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,iBAAiB,IAAI,CAAC,IAAI,CAAC,YAAY,KAAK,aAAa,CAAC,EAAE;AACtG,MAAM,MAAM,iBAAiB,GAAG,YAAY,IAAI,YAAY,CAAC,iBAAiB,CAAC;AAC/E,MAAM,MAAM,iBAAiB,GAAG,CAAC,iBAAiB,IAAI,aAAa,CAAC;AACpE;AACA,MAAM,IAAI;AACV,QAAQ,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAChC,OAAO,CAAC,OAAO,CAAC,EAAE;AAClB,QAAQ,IAAI,iBAAiB,EAAE;AAC/B,UAAU,IAAI,CAAC,CAAC,IAAI,KAAK,aAAa,EAAE;AACxC,YAAY,MAAM,UAAU,CAAC,IAAI,CAAC,CAAC,EAAE,UAAU,CAAC,gBAAgB,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC7F,WAAW;AACX,UAAU,MAAM,CAAC,CAAC;AAClB,SAAS;AACT,OAAO;AACP,KAAK;AACL;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG,CAAC;AACJ;AACA;AACA;AACA;AACA;AACA,EAAE,OAAO,EAAE,CAAC;AACZ;AACA,EAAE,cAAc,EAAE,YAAY;AAC9B,EAAE,cAAc,EAAE,cAAc;AAChC;AACA,EAAE,gBAAgB,EAAE,CAAC,CAAC;AACtB,EAAE,aAAa,EAAE,CAAC,CAAC;AACnB;AACA,EAAE,GAAG,EAAE;AACP,IAAI,QAAQ,EAAE,QAAQ,CAAC,OAAO,CAAC,QAAQ;AACvC,IAAI,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,IAAI;AAC/B,GAAG;AACH;AACA,EAAE,cAAc,EAAE,SAAS,cAAc,CAAC,MAAM,EAAE;AAClD,IAAI,OAAO,MAAM,IAAI,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC;AACzC,GAAG;AACH;AACA,EAAE,OAAO,EAAE;AACX,IAAI,MAAM,EAAE;AACZ,MAAM,QAAQ,EAAE,mCAAmC;AACnD,MAAM,cAAc,EAAE,SAAS;AAC/B,KAAK;AACL,GAAG;AACH,CAAC,CAAC;AACF;AACAA,OAAK,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC,MAAM,KAAK;AAC7E,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;AAChC,CAAC,CAAC,CAAC;AACH;AACA,mBAAe,QAAQ;;AC5JvB;AACA;AACA,MAAM,iBAAiB,GAAGA,OAAK,CAAC,WAAW,CAAC;AAC5C,EAAE,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM;AAClE,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,EAAE,qBAAqB;AACvE,EAAE,eAAe,EAAE,UAAU,EAAE,cAAc,EAAE,qBAAqB;AACpE,EAAE,SAAS,EAAE,aAAa,EAAE,YAAY;AACxC,CAAC,CAAC,CAAC;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAe,UAAU,IAAI;AAC7B,EAAE,MAAM,MAAM,GAAG,EAAE,CAAC;AACpB,EAAE,IAAI,GAAG,CAAC;AACV,EAAE,IAAI,GAAG,CAAC;AACV,EAAE,IAAI,CAAC,CAAC;AACR;AACA,EAAE,UAAU,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,SAAS,MAAM,CAAC,IAAI,EAAE;AACrE,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AAC1B,IAAI,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AACpD,IAAI,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;AACvC;AACA,IAAI,IAAI,CAAC,GAAG,KAAK,MAAM,CAAC,GAAG,CAAC,IAAI,iBAAiB,CAAC,GAAG,CAAC,CAAC,EAAE;AACzD,MAAM,OAAO;AACb,KAAK;AACL;AACA,IAAI,IAAI,GAAG,KAAK,YAAY,EAAE;AAC9B,MAAM,IAAI,MAAM,CAAC,GAAG,CAAC,EAAE;AACvB,QAAQ,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC9B,OAAO,MAAM;AACb,QAAQ,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAC5B,OAAO;AACP,KAAK,MAAM;AACX,MAAM,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,GAAG,GAAG,GAAG,CAAC;AACjE,KAAK;AACL,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO,MAAM,CAAC;AAChB,CAAC;;ACjDD,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC;AACA,SAAS,eAAe,CAAC,MAAM,EAAE;AACjC,EAAE,OAAO,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AACvD,CAAC;AACD;AACA,SAAS,cAAc,CAAC,KAAK,EAAE;AAC/B,EAAE,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,IAAI,IAAI,EAAE;AACxC,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA,EAAE,OAAOA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;AAC1E,CAAC;AACD;AACA,SAAS,WAAW,CAAC,GAAG,EAAE;AAC1B,EAAE,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AACrC,EAAE,MAAM,QAAQ,GAAG,kCAAkC,CAAC;AACtD,EAAE,IAAI,KAAK,CAAC;AACZ;AACA,EAAE,QAAQ,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG;AACvC,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAChC,GAAG;AACH;AACA,EAAE,OAAO,MAAM,CAAC;AAChB,CAAC;AACD;AACA,MAAM,iBAAiB,GAAG,CAAC,GAAG,KAAK,gCAAgC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;AACrF;AACA,SAAS,gBAAgB,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,kBAAkB,EAAE;AAC9E,EAAE,IAAIA,OAAK,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE;AAChC,IAAI,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAC5C,GAAG;AACH;AACA,EAAE,IAAI,kBAAkB,EAAE;AAC1B,IAAI,KAAK,GAAG,MAAM,CAAC;AACnB,GAAG;AACH;AACA,EAAE,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO;AACrC;AACA,EAAE,IAAIA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;AAC9B,IAAI,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AACxC,GAAG;AACH;AACA,EAAE,IAAIA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;AAC9B,IAAI,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC9B,GAAG;AACH,CAAC;AACD;AACA,SAAS,YAAY,CAAC,MAAM,EAAE;AAC9B,EAAE,OAAO,MAAM,CAAC,IAAI,EAAE;AACtB,KAAK,WAAW,EAAE,CAAC,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,KAAK;AAChE,MAAM,OAAO,IAAI,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC;AACtC,KAAK,CAAC,CAAC;AACP,CAAC;AACD;AACA,SAAS,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE;AACrC,EAAE,MAAM,YAAY,GAAGA,OAAK,CAAC,WAAW,CAAC,GAAG,GAAG,MAAM,CAAC,CAAC;AACvD;AACA,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,UAAU,IAAI;AAC9C,IAAI,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,UAAU,GAAG,YAAY,EAAE;AAC1D,MAAM,KAAK,EAAE,SAAS,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE;AACxC,QAAQ,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AACrE,OAAO;AACP,MAAM,YAAY,EAAE,IAAI;AACxB,KAAK,CAAC,CAAC;AACP,GAAG,CAAC,CAAC;AACL,CAAC;AACD;AACA,MAAM,YAAY,CAAC;AACnB,EAAE,WAAW,CAAC,OAAO,EAAE;AACvB,IAAI,OAAO,IAAI,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AACjC,GAAG;AACH;AACA,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE;AACvC,IAAI,MAAM,IAAI,GAAG,IAAI,CAAC;AACtB;AACA,IAAI,SAAS,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE;AAClD,MAAM,MAAM,OAAO,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;AAC/C;AACA,MAAM,IAAI,CAAC,OAAO,EAAE;AACpB,QAAQ,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAClE,OAAO;AACP;AACA,MAAM,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AAC/C;AACA,MAAM,GAAG,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,SAAS,IAAI,QAAQ,KAAK,IAAI,KAAK,QAAQ,KAAK,SAAS,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,EAAE;AAClH,QAAQ,IAAI,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;AACtD,OAAO;AACP,KAAK;AACL;AACA,IAAI,MAAM,UAAU,GAAG,CAAC,OAAO,EAAE,QAAQ;AACzC,MAAMA,OAAK,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC;AACxF;AACA,IAAI,IAAIA,OAAK,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,MAAM,YAAY,IAAI,CAAC,WAAW,EAAE;AAC3E,MAAM,UAAU,CAAC,MAAM,EAAE,cAAc,EAAC;AACxC,KAAK,MAAM,GAAGA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,MAAM,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,EAAE;AAChG,MAAM,UAAU,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE,cAAc,CAAC,CAAC;AACvD,KAAK,MAAM,IAAIA,OAAK,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE;AACxC,MAAM,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,EAAE,EAAE;AACnD,QAAQ,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;AACvC,OAAO;AACP,KAAK,MAAM;AACX,MAAM,MAAM,IAAI,IAAI,IAAI,SAAS,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACnE,KAAK;AACL;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG;AACH;AACA,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE;AACtB,IAAI,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC;AACrC;AACA,IAAI,IAAI,MAAM,EAAE;AAChB,MAAM,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC9C;AACA,MAAM,IAAI,GAAG,EAAE;AACf,QAAQ,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;AAChC;AACA,QAAQ,IAAI,CAAC,MAAM,EAAE;AACrB,UAAU,OAAO,KAAK,CAAC;AACvB,SAAS;AACT;AACA,QAAQ,IAAI,MAAM,KAAK,IAAI,EAAE;AAC7B,UAAU,OAAO,WAAW,CAAC,KAAK,CAAC,CAAC;AACpC,SAAS;AACT;AACA,QAAQ,IAAIA,OAAK,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE;AACtC,UAAU,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;AAC/C,SAAS;AACT;AACA,QAAQ,IAAIA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;AACpC,UAAU,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACpC,SAAS;AACT;AACA,QAAQ,MAAM,IAAI,SAAS,CAAC,wCAAwC,CAAC,CAAC;AACtE,OAAO;AACP,KAAK;AACL,GAAG;AACH;AACA,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE;AACvB,IAAI,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC;AACrC;AACA,IAAI,IAAI,MAAM,EAAE;AAChB,MAAM,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC9C;AACA,MAAM,OAAO,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,SAAS,KAAK,CAAC,OAAO,IAAI,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;AACjH,KAAK;AACL;AACA,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;AACA,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE;AAC1B,IAAI,MAAM,IAAI,GAAG,IAAI,CAAC;AACtB,IAAI,IAAI,OAAO,GAAG,KAAK,CAAC;AACxB;AACA,IAAI,SAAS,YAAY,CAAC,OAAO,EAAE;AACnC,MAAM,OAAO,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;AACzC;AACA,MAAM,IAAI,OAAO,EAAE;AACnB,QAAQ,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AACjD;AACA,QAAQ,IAAI,GAAG,KAAK,CAAC,OAAO,IAAI,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,EAAE;AAClF,UAAU,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AAC3B;AACA,UAAU,OAAO,GAAG,IAAI,CAAC;AACzB,SAAS;AACT,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;AAC/B,MAAM,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;AACnC,KAAK,MAAM;AACX,MAAM,YAAY,CAAC,MAAM,CAAC,CAAC;AAC3B,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC;AACnB,GAAG;AACH;AACA,EAAE,KAAK,CAAC,OAAO,EAAE;AACjB,IAAI,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACnC,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;AACxB,IAAI,IAAI,OAAO,GAAG,KAAK,CAAC;AACxB;AACA,IAAI,OAAO,CAAC,EAAE,EAAE;AAChB,MAAM,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AAC1B,MAAM,GAAG,CAAC,OAAO,IAAI,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE;AAC5E,QAAQ,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AACzB,QAAQ,OAAO,GAAG,IAAI,CAAC;AACvB,OAAO;AACP,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC;AACnB,GAAG;AACH;AACA,EAAE,SAAS,CAAC,MAAM,EAAE;AACpB,IAAI,MAAM,IAAI,GAAG,IAAI,CAAC;AACtB,IAAI,MAAM,OAAO,GAAG,EAAE,CAAC;AACvB;AACA,IAAIA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK;AAC3C,MAAM,MAAM,GAAG,GAAGA,OAAK,CAAC,OAAO,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AACjD;AACA,MAAM,IAAI,GAAG,EAAE;AACf,QAAQ,IAAI,CAAC,GAAG,CAAC,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;AAC1C,QAAQ,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,YAAY,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;AAC/E;AACA,MAAM,IAAI,UAAU,KAAK,MAAM,EAAE;AACjC,QAAQ,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,OAAO;AACP;AACA,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;AAC/C;AACA,MAAM,OAAO,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC;AACjC,KAAK,CAAC,CAAC;AACP;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG;AACH;AACA,EAAE,MAAM,CAAC,GAAG,OAAO,EAAE;AACrB,IAAI,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,OAAO,CAAC,CAAC;AACrD,GAAG;AACH;AACA,EAAE,MAAM,CAAC,SAAS,EAAE;AACpB,IAAI,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AACpC;AACA,IAAIA,OAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK;AAC3C,MAAM,KAAK,IAAI,IAAI,IAAI,KAAK,KAAK,KAAK,KAAK,GAAG,CAAC,MAAM,CAAC,GAAG,SAAS,IAAIA,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC;AACvH,KAAK,CAAC,CAAC;AACP;AACA,IAAI,OAAO,GAAG,CAAC;AACf,GAAG;AACH;AACA,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG;AACtB,IAAI,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;AAC5D,GAAG;AACH;AACA,EAAE,QAAQ,GAAG;AACb,IAAI,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,KAAK,CAAC,KAAK,MAAM,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACpG,GAAG;AACH;AACA,EAAE,KAAK,MAAM,CAAC,WAAW,CAAC,GAAG;AAC7B,IAAI,OAAO,cAAc,CAAC;AAC1B,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC,KAAK,EAAE;AACrB,IAAI,OAAO,KAAK,YAAY,IAAI,GAAG,KAAK,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;AAC3D,GAAG;AACH;AACA,EAAE,OAAO,MAAM,CAAC,KAAK,EAAE,GAAG,OAAO,EAAE;AACnC,IAAI,MAAM,QAAQ,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;AACrC;AACA,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;AACtD;AACA,IAAI,OAAO,QAAQ,CAAC;AACpB,GAAG;AACH;AACA,EAAE,OAAO,QAAQ,CAAC,MAAM,EAAE;AAC1B,IAAI,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG;AAC7D,MAAM,SAAS,EAAE,EAAE;AACnB,KAAK,CAAC,CAAC;AACP;AACA,IAAI,MAAM,SAAS,GAAG,SAAS,CAAC,SAAS,CAAC;AAC1C,IAAI,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;AACrC;AACA,IAAI,SAAS,cAAc,CAAC,OAAO,EAAE;AACrC,MAAM,MAAM,OAAO,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;AAC/C;AACA,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE;AAC/B,QAAQ,cAAc,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;AAC3C,QAAQ,SAAS,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;AAClC,OAAO;AACP,KAAK;AACL;AACA,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;AACpF;AACA,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG;AACH,CAAC;AACD;AACA,YAAY,CAAC,QAAQ,CAAC,CAAC,cAAc,EAAE,gBAAgB,EAAE,QAAQ,EAAE,iBAAiB,EAAE,YAAY,EAAE,eAAe,CAAC,CAAC,CAAC;AACtH;AACA;AACAA,OAAK,CAAC,iBAAiB,CAAC,YAAY,CAAC,SAAS,EAAE,CAAC,CAAC,KAAK,CAAC,EAAE,GAAG,KAAK;AAClE,EAAE,IAAI,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnD,EAAE,OAAO;AACT,IAAI,GAAG,EAAE,MAAM,KAAK;AACpB,IAAI,GAAG,CAAC,WAAW,EAAE;AACrB,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,WAAW,CAAC;AACjC,KAAK;AACL,GAAG;AACH,CAAC,CAAC,CAAC;AACH;AACAA,OAAK,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC;AAClC;AACA,uBAAe,YAAY;;ACvS3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,aAAa,CAAC,GAAG,EAAE,QAAQ,EAAE;AACrD,EAAE,MAAM,MAAM,GAAG,IAAI,IAAIO,UAAQ,CAAC;AAClC,EAAE,MAAM,OAAO,GAAG,QAAQ,IAAI,MAAM,CAAC;AACrC,EAAE,MAAM,OAAO,GAAGC,cAAY,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AACrD,EAAE,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;AAC1B;AACA,EAAER,OAAK,CAAC,OAAO,CAAC,GAAG,EAAE,SAAS,SAAS,CAAC,EAAE,EAAE;AAC5C,IAAI,IAAI,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,SAAS,EAAE,EAAE,QAAQ,GAAG,QAAQ,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;AAC9F,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC;AACtB;AACA,EAAE,OAAO,IAAI,CAAC;AACd;;ACzBe,SAAS,QAAQ,CAAC,KAAK,EAAE;AACxC,EAAE,OAAO,CAAC,EAAE,KAAK,IAAI,KAAK,CAAC,UAAU,CAAC,CAAC;AACvC;;ACCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE;AACjD;AACA,EAAE,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,IAAI,IAAI,GAAG,UAAU,GAAG,OAAO,EAAE,UAAU,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AAC1G,EAAE,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;AAC9B,CAAC;AACD;AACAA,OAAK,CAAC,QAAQ,CAAC,aAAa,EAAE,UAAU,EAAE;AAC1C,EAAE,UAAU,EAAE,IAAI;AAClB,CAAC,CAAC;;AClBF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE;AAC1D,EAAE,MAAM,cAAc,GAAG,QAAQ,CAAC,MAAM,CAAC,cAAc,CAAC;AACxD,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,IAAI,CAAC,cAAc,IAAI,cAAc,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;AAC9E,IAAI,OAAO,CAAC,QAAQ,CAAC,CAAC;AACtB,GAAG,MAAM;AACT,IAAI,MAAM,CAAC,IAAI,UAAU;AACzB,MAAM,kCAAkC,GAAG,QAAQ,CAAC,MAAM;AAC1D,MAAM,CAAC,UAAU,CAAC,eAAe,EAAE,UAAU,CAAC,gBAAgB,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;AACtG,MAAM,QAAQ,CAAC,MAAM;AACrB,MAAM,QAAQ,CAAC,OAAO;AACtB,MAAM,QAAQ;AACd,KAAK,CAAC,CAAC;AACP,GAAG;AACH;;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,aAAa,CAAC,GAAG,EAAE;AAC3C;AACA;AACA;AACA,EAAE,OAAO,6BAA6B,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjD;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,WAAW,CAAC,OAAO,EAAE,WAAW,EAAE;AAC1D,EAAE,OAAO,WAAW;AACpB,MAAM,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,GAAG,GAAG,GAAG,WAAW,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;AAC3E,MAAM,OAAO,CAAC;AACd;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE;AAC7D,EAAE,IAAI,OAAO,IAAI,CAAC,aAAa,CAAC,YAAY,CAAC,EAAE;AAC/C,IAAI,OAAO,WAAW,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;AAC9C,GAAG;AACH,EAAE,OAAO,YAAY,CAAC;AACtB;;ACpBO,MAAM,OAAO,GAAG,OAAO;;ACEf,SAAS,aAAa,CAAC,GAAG,EAAE;AAC3C,EAAE,MAAM,KAAK,GAAG,2BAA2B,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACtD,EAAE,OAAO,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;AACjC;;ACCA,MAAM,gBAAgB,GAAG,+CAA+C,CAAC;AACzE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE;AAC1D,EAAE,MAAM,KAAK,GAAG,OAAO,IAAI,OAAO,CAAC,IAAI,IAAI,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC;AACjE,EAAE,MAAM,QAAQ,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC;AACtC;AACA,EAAE,IAAI,MAAM,KAAK,SAAS,IAAI,KAAK,EAAE;AACrC,IAAI,MAAM,GAAG,IAAI,CAAC;AAClB,GAAG;AACH;AACA,EAAE,IAAI,QAAQ,KAAK,MAAM,EAAE;AAC3B,IAAI,GAAG,GAAG,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC;AACjE;AACA,IAAI,MAAM,KAAK,GAAG,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC7C;AACA,IAAI,IAAI,CAAC,KAAK,EAAE;AAChB,MAAM,MAAM,IAAI,UAAU,CAAC,aAAa,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;AACtE,KAAK;AACL;AACA,IAAI,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAC1B,IAAI,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAC9B,IAAI,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAC1B,IAAI,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,EAAE,QAAQ,GAAG,QAAQ,GAAG,MAAM,CAAC,CAAC;AACvF;AACA,IAAI,IAAI,MAAM,EAAE;AAChB,MAAM,IAAI,CAAC,KAAK,EAAE;AAClB,QAAQ,MAAM,IAAI,UAAU,CAAC,uBAAuB,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;AAClF,OAAO;AACP;AACA,MAAM,OAAO,IAAI,KAAK,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;AAC/C,KAAK;AACL;AACA,IAAI,OAAO,MAAM,CAAC;AAClB,GAAG;AACH;AACA,EAAE,MAAM,IAAI,UAAU,CAAC,uBAAuB,GAAG,QAAQ,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;AACvF;;AC/CA,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC;AACA,MAAM,oBAAoB,SAASS,0BAAM,CAAC,SAAS;AACnD,EAAE,WAAW,CAAC,OAAO,EAAE;AACvB,IAAI,OAAO,GAAGT,OAAK,CAAC,YAAY,CAAC,OAAO,EAAE;AAC1C,MAAM,OAAO,EAAE,CAAC;AAChB,MAAM,SAAS,EAAE,EAAE,GAAG,IAAI;AAC1B,MAAM,YAAY,EAAE,GAAG;AACvB,MAAM,UAAU,EAAE,GAAG;AACrB,MAAM,SAAS,EAAE,CAAC;AAClB,MAAM,YAAY,EAAE,EAAE;AACtB,KAAK,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK;AAC/B,MAAM,OAAO,CAACA,OAAK,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AAC9C,KAAK,CAAC,CAAC;AACP;AACA,IAAI,KAAK,CAAC;AACV,MAAM,qBAAqB,EAAE,OAAO,CAAC,SAAS;AAC9C,KAAK,CAAC,CAAC;AACP;AACA,IAAI,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG;AACzC,MAAM,UAAU,EAAE,OAAO,CAAC,UAAU;AACpC,MAAM,SAAS,EAAE,OAAO,CAAC,SAAS;AAClC,MAAM,OAAO,EAAE,OAAO,CAAC,OAAO;AAC9B,MAAM,YAAY,EAAE,OAAO,CAAC,YAAY;AACxC,MAAM,SAAS,EAAE,CAAC;AAClB,MAAM,UAAU,EAAE,KAAK;AACvB,MAAM,mBAAmB,EAAE,CAAC;AAC5B,MAAM,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE;AACpB,MAAM,KAAK,EAAE,CAAC;AACd,MAAM,cAAc,EAAE,IAAI;AAC1B,KAAK,CAAC;AACN;AACA,IAAI,IAAI,CAAC,EAAE,CAAC,aAAa,EAAE,KAAK,IAAI;AACpC,MAAM,IAAI,KAAK,KAAK,UAAU,EAAE;AAChC,QAAQ,IAAI,CAAC,SAAS,CAAC,UAAU,EAAE;AACnC,UAAU,SAAS,CAAC,UAAU,GAAG,IAAI,CAAC;AACtC,SAAS;AACT,OAAO;AACP,KAAK,CAAC,CAAC;AACP,GAAG;AACH;AACA,EAAE,KAAK,CAAC,IAAI,EAAE;AACd,IAAI,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC;AACvC;AACA,IAAI,IAAI,SAAS,CAAC,cAAc,EAAE;AAClC,MAAM,SAAS,CAAC,cAAc,EAAE,CAAC;AACjC,KAAK;AACL;AACA,IAAI,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAC7B,GAAG;AACH;AACA,EAAE,UAAU,CAAC,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE;AACxC,IAAI,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC;AACvC,IAAI,MAAM,OAAO,GAAG,SAAS,CAAC,OAAO,CAAC;AACtC;AACA,IAAI,MAAM,qBAAqB,GAAG,IAAI,CAAC,qBAAqB,CAAC;AAC7D;AACA,IAAI,MAAM,UAAU,GAAG,SAAS,CAAC,UAAU,CAAC;AAC5C;AACA,IAAI,MAAM,OAAO,GAAG,IAAI,GAAG,UAAU,CAAC;AACtC,IAAI,MAAM,cAAc,IAAI,OAAO,GAAG,OAAO,CAAC,CAAC;AAC/C,IAAI,MAAM,YAAY,GAAG,SAAS,CAAC,YAAY,KAAK,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,YAAY,EAAE,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;AACxH;AACA,IAAI,MAAM,SAAS,GAAG,CAAC,MAAM,EAAE,SAAS,KAAK;AAC7C,MAAM,MAAM,KAAK,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;AAC9C,MAAM,SAAS,CAAC,SAAS,IAAI,KAAK,CAAC;AACnC,MAAM,SAAS,CAAC,KAAK,IAAI,KAAK,CAAC;AAC/B;AACA,MAAM,SAAS,CAAC,UAAU,IAAI,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,SAAS,CAAC,SAAS,CAAC,CAAC;AACzE;AACA,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;AAC7B,QAAQ,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AACpC,OAAO,MAAM;AACb,QAAQ,SAAS,CAAC,cAAc,GAAG,MAAM;AACzC,UAAU,SAAS,CAAC,cAAc,GAAG,IAAI,CAAC;AAC1C,UAAU,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AACtC,SAAS,CAAC;AACV,OAAO;AACP,MAAK;AACL;AACA,IAAI,MAAM,cAAc,GAAG,CAAC,MAAM,EAAE,SAAS,KAAK;AAClD,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;AAClD,MAAM,IAAI,cAAc,GAAG,IAAI,CAAC;AAChC,MAAM,IAAI,YAAY,GAAG,qBAAqB,CAAC;AAC/C,MAAM,IAAI,SAAS,CAAC;AACpB,MAAM,IAAI,MAAM,GAAG,CAAC,CAAC;AACrB;AACA,MAAM,IAAI,OAAO,EAAE;AACnB,QAAQ,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;AAC/B;AACA,QAAQ,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,MAAM,IAAI,GAAG,GAAG,SAAS,CAAC,EAAE,CAAC,KAAK,UAAU,EAAE;AAC5E,UAAU,SAAS,CAAC,EAAE,GAAG,GAAG,CAAC;AAC7B,UAAU,SAAS,GAAG,cAAc,GAAG,SAAS,CAAC,KAAK,CAAC;AACvD,UAAU,SAAS,CAAC,KAAK,GAAG,SAAS,GAAG,CAAC,GAAG,CAAC,SAAS,GAAG,CAAC,CAAC;AAC3D,UAAU,MAAM,GAAG,CAAC,CAAC;AACrB,SAAS;AACT;AACA,QAAQ,SAAS,GAAG,cAAc,GAAG,SAAS,CAAC,KAAK,CAAC;AACrD,OAAO;AACP;AACA,MAAM,IAAI,OAAO,EAAE;AACnB,QAAQ,IAAI,SAAS,IAAI,CAAC,EAAE;AAC5B;AACA,UAAU,OAAO,UAAU,CAAC,MAAM;AAClC,YAAY,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AACpC,WAAW,EAAE,UAAU,GAAG,MAAM,CAAC,CAAC;AAClC,SAAS;AACT;AACA,QAAQ,IAAI,SAAS,GAAG,YAAY,EAAE;AACtC,UAAU,YAAY,GAAG,SAAS,CAAC;AACnC,SAAS;AACT,OAAO;AACP;AACA,MAAM,IAAI,YAAY,IAAI,SAAS,GAAG,YAAY,IAAI,CAAC,SAAS,GAAG,YAAY,IAAI,YAAY,EAAE;AACjG,QAAQ,cAAc,GAAG,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;AACvD,QAAQ,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC;AAClD,OAAO;AACP;AACA,MAAM,SAAS,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM;AAC/C,QAAQ,OAAO,CAAC,QAAQ,CAAC,SAAS,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC;AAC1D,OAAO,GAAG,SAAS,CAAC,CAAC;AACrB,KAAK,CAAC;AACN;AACA,IAAI,cAAc,CAAC,KAAK,EAAE,SAAS,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE;AACnE,MAAM,IAAI,GAAG,EAAE;AACf,QAAQ,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;AAC7B,OAAO;AACP;AACA,MAAM,IAAI,MAAM,EAAE;AAClB,QAAQ,cAAc,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC;AACnD,OAAO,MAAM;AACb,QAAQ,QAAQ,CAAC,IAAI,CAAC,CAAC;AACvB,OAAO;AACP,KAAK,CAAC,CAAC;AACP,GAAG;AACH,CAAC;AACD;AACA,+BAAe,oBAAoB;;AC9InC,MAAM,CAAC,aAAa,CAAC,GAAG,MAAM,CAAC;AAC/B;AACA,MAAM,QAAQ,GAAG,iBAAiB,IAAI,EAAE;AACxC,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE;AACnB,IAAI,OAAO,IAAI,CAAC,MAAM,GAAE;AACxB,GAAG,MAAM,IAAI,IAAI,CAAC,WAAW,EAAE;AAC/B,IAAI,MAAM,MAAM,IAAI,CAAC,WAAW,GAAE;AAClC,GAAG,MAAM,IAAI,IAAI,CAAC,aAAa,CAAC,EAAE;AAClC,IAAI,OAAO,IAAI,CAAC,aAAa,CAAC,EAAE,CAAC;AACjC,GAAG,MAAM;AACT,IAAI,MAAM,IAAI,CAAC;AACf,GAAG;AACH,EAAC;AACD;AACA,mBAAe,QAAQ;;ACTvB,MAAM,iBAAiB,GAAGA,OAAK,CAAC,QAAQ,CAAC,WAAW,GAAG,IAAI,CAAC;AAC5D;AACA,MAAM,WAAW,GAAG,OAAO,WAAW,KAAK,UAAU,GAAG,IAAI,WAAW,EAAE,GAAG,IAAIU,wBAAI,CAAC,WAAW,EAAE,CAAC;AACnG;AACA,MAAM,IAAI,GAAG,MAAM,CAAC;AACpB,MAAM,UAAU,GAAG,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AAC5C,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAC3B;AACA,MAAM,YAAY,CAAC;AACnB,EAAE,WAAW,CAAC,IAAI,EAAE,KAAK,EAAE;AAC3B,IAAI,MAAM,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC;AAC1C,IAAI,MAAM,aAAa,GAAGV,OAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAChD;AACA,IAAI,IAAI,OAAO,GAAG,CAAC,sCAAsC,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;AAC7E,MAAM,CAAC,aAAa,IAAI,KAAK,CAAC,IAAI,GAAG,CAAC,YAAY,EAAE,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE;AAClF,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;AACd;AACA,IAAI,IAAI,aAAa,EAAE;AACvB,MAAM,KAAK,GAAG,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC,CAAC;AAC9E,KAAK,MAAM;AACX,MAAM,OAAO,IAAI,CAAC,cAAc,EAAE,KAAK,CAAC,IAAI,IAAI,0BAA0B,CAAC,EAAE,IAAI,CAAC,EAAC;AACnF,KAAK;AACL;AACA,IAAI,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC,MAAM,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;AACtD;AACA,IAAI,IAAI,CAAC,aAAa,GAAG,aAAa,GAAG,KAAK,CAAC,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC;AACvE;AACA,IAAI,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,aAAa,GAAG,gBAAgB,CAAC;AAChF;AACA,IAAI,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACrB,IAAI,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;AACvB,GAAG;AACH;AACA,EAAE,OAAO,MAAM,EAAE;AACjB,IAAI,MAAM,IAAI,CAAC,OAAO,CAAC;AACvB;AACA,IAAI,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC;AACzB;AACA,IAAI,GAAGA,OAAK,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE;AAClC,MAAM,MAAM,KAAK,CAAC;AAClB,KAAK,MAAM;AACX,MAAM,OAAOW,UAAQ,CAAC,KAAK,CAAC,CAAC;AAC7B,KAAK;AACL;AACA,IAAI,MAAM,UAAU,CAAC;AACrB,GAAG;AACH;AACA,EAAE,OAAO,UAAU,CAAC,IAAI,EAAE;AAC1B,MAAM,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,KAAK,MAAM;AAC1D,QAAQ,IAAI,GAAG,KAAK;AACpB,QAAQ,IAAI,GAAG,KAAK;AACpB,QAAQ,GAAG,GAAG,KAAK;AACnB,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACjB,GAAG;AACH,CAAC;AACD;AACA,MAAM,gBAAgB,GAAG,CAAC,IAAI,EAAE,cAAc,EAAE,OAAO,KAAK;AAC5D,EAAE,MAAM;AACR,IAAI,GAAG,GAAG,oBAAoB;AAC9B,IAAI,IAAI,GAAG,EAAE;AACb,IAAI,QAAQ,GAAG,GAAG,GAAG,GAAG,GAAGX,OAAK,CAAC,cAAc,CAAC,IAAI,EAAE,iBAAiB,CAAC;AACxE,GAAG,GAAG,OAAO,IAAI,EAAE,CAAC;AACpB;AACA,EAAE,GAAG,CAACA,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;AAC9B,IAAI,MAAM,SAAS,CAAC,4BAA4B,CAAC,CAAC;AAClD,GAAG;AACH;AACA,EAAE,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,QAAQ,CAAC,MAAM,GAAG,EAAE,EAAE;AACnD,IAAI,MAAM,KAAK,CAAC,wCAAwC,CAAC;AACzD,GAAG;AACH;AACA,EAAE,MAAM,aAAa,GAAG,WAAW,CAAC,MAAM,CAAC,IAAI,GAAG,QAAQ,GAAG,IAAI,CAAC,CAAC;AACnE,EAAE,MAAM,WAAW,GAAG,WAAW,CAAC,MAAM,CAAC,IAAI,GAAG,QAAQ,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC,CAAC;AAC/E,EAAE,IAAI,aAAa,GAAG,WAAW,CAAC,UAAU,CAAC;AAC7C;AACA,EAAE,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK;AAClE,IAAI,MAAM,IAAI,GAAG,IAAI,YAAY,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;AAC/C,IAAI,aAAa,IAAI,IAAI,CAAC,IAAI,CAAC;AAC/B,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG,CAAC,CAAC;AACL;AACA,EAAE,aAAa,IAAI,aAAa,CAAC,UAAU,GAAG,KAAK,CAAC,MAAM,CAAC;AAC3D;AACA,EAAE,aAAa,GAAGA,OAAK,CAAC,cAAc,CAAC,aAAa,CAAC,CAAC;AACtD;AACA,EAAE,MAAM,eAAe,GAAG;AAC1B,IAAI,cAAc,EAAE,CAAC,8BAA8B,EAAE,QAAQ,CAAC,CAAC;AAC/D,IAAG;AACH;AACA,EAAE,IAAI,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE;AACtC,IAAI,eAAe,CAAC,gBAAgB,CAAC,GAAG,aAAa,CAAC;AACtD,GAAG;AACH;AACA,EAAE,cAAc,IAAI,cAAc,CAAC,eAAe,CAAC,CAAC;AACpD;AACA,EAAE,OAAOY,eAAQ,CAAC,IAAI,CAAC,CAAC,mBAAmB;AAC3C,IAAI,IAAI,MAAM,IAAI,IAAI,KAAK,EAAE;AAC7B,MAAM,MAAM,aAAa,CAAC;AAC1B,MAAM,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC;AAC3B,KAAK;AACL;AACA,IAAI,MAAM,WAAW,CAAC;AACtB,GAAG,GAAG,CAAC,CAAC;AACR,CAAC,CAAC;AACF;AACA,2BAAe,gBAAgB;;AC1G/B,MAAM,yBAAyB,SAASH,0BAAM,CAAC,SAAS,CAAC;AACzD,EAAE,WAAW,CAAC,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE;AACzC,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACrB,IAAI,QAAQ,EAAE,CAAC;AACf,GAAG;AACH;AACA,EAAE,UAAU,CAAC,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE;AACxC,IAAI,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;AAC5B,MAAM,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,WAAW,CAAC;AACzC;AACA;AACA,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;AAC5B,QAAQ,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACvC,QAAQ,MAAM,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC;AACxB,QAAQ,MAAM,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC;AACxB,QAAQ,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AACpC,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;AAChD,GAAG;AACH,CAAC;AACD;AACA,oCAAe,yBAAyB;;ACzBxC,MAAM,WAAW,GAAG,CAAC,EAAE,EAAE,OAAO,KAAK;AACrC,EAAE,OAAOT,OAAK,CAAC,SAAS,CAAC,EAAE,CAAC,GAAG,UAAU,GAAG,IAAI,EAAE;AAClD,IAAI,MAAM,EAAE,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;AAC1B,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,KAAK;AACzC,MAAM,IAAI;AACV,QAAQ,OAAO,GAAG,EAAE,CAAC,IAAI,EAAE,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;AAChE,OAAO,CAAC,OAAO,GAAG,EAAE;AACpB,QAAQ,EAAE,CAAC,GAAG,CAAC,CAAC;AAChB,OAAO;AACP,KAAK,EAAE,EAAE,CAAC,CAAC;AACX,GAAG,GAAG,EAAE,CAAC;AACT,EAAC;AACD;AACA,sBAAe,WAAW;;ACb1B;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,WAAW,CAAC,YAAY,EAAE,GAAG,EAAE;AACxC,EAAE,YAAY,GAAG,YAAY,IAAI,EAAE,CAAC;AACpC,EAAE,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;AACxC,EAAE,MAAM,UAAU,GAAG,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;AAC7C,EAAE,IAAI,IAAI,GAAG,CAAC,CAAC;AACf,EAAE,IAAI,IAAI,GAAG,CAAC,CAAC;AACf,EAAE,IAAI,aAAa,CAAC;AACpB;AACA,EAAE,GAAG,GAAG,GAAG,KAAK,SAAS,GAAG,GAAG,GAAG,IAAI,CAAC;AACvC;AACA,EAAE,OAAO,SAAS,IAAI,CAAC,WAAW,EAAE;AACpC,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;AAC3B;AACA,IAAI,MAAM,SAAS,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC;AACvC;AACA,IAAI,IAAI,CAAC,aAAa,EAAE;AACxB,MAAM,aAAa,GAAG,GAAG,CAAC;AAC1B,KAAK;AACL;AACA,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC;AAC9B,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC;AAC3B;AACA,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC;AACjB,IAAI,IAAI,UAAU,GAAG,CAAC,CAAC;AACvB;AACA,IAAI,OAAO,CAAC,KAAK,IAAI,EAAE;AACvB,MAAM,UAAU,IAAI,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;AAC/B,MAAM,CAAC,GAAG,CAAC,GAAG,YAAY,CAAC;AAC3B,KAAK;AACL;AACA,IAAI,IAAI,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,YAAY,CAAC;AACrC;AACA,IAAI,IAAI,IAAI,KAAK,IAAI,EAAE;AACvB,MAAM,IAAI,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,YAAY,CAAC;AACvC,KAAK;AACL;AACA,IAAI,IAAI,GAAG,GAAG,aAAa,GAAG,GAAG,EAAE;AACnC,MAAM,OAAO;AACb,KAAK;AACL;AACA,IAAI,MAAM,MAAM,GAAG,SAAS,IAAI,GAAG,GAAG,SAAS,CAAC;AAChD;AACA,IAAI,OAAO,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,GAAG,IAAI,GAAG,MAAM,CAAC,GAAG,SAAS,CAAC;AACvE,GAAG,CAAC;AACJ;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,QAAQ,CAAC,EAAE,EAAE,IAAI,EAAE;AAC5B,EAAE,IAAI,SAAS,GAAG,CAAC,CAAC;AACpB,EAAE,IAAI,SAAS,GAAG,IAAI,GAAG,IAAI,CAAC;AAC9B,EAAE,IAAI,QAAQ,CAAC;AACf,EAAE,IAAI,KAAK,CAAC;AACZ;AACA,EAAE,MAAM,MAAM,GAAG,CAAC,IAAI,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,KAAK;AAC7C,IAAI,SAAS,GAAG,GAAG,CAAC;AACpB,IAAI,QAAQ,GAAG,IAAI,CAAC;AACpB,IAAI,IAAI,KAAK,EAAE;AACf,MAAM,YAAY,CAAC,KAAK,CAAC,CAAC;AAC1B,MAAM,KAAK,GAAG,IAAI,CAAC;AACnB,KAAK;AACL,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AACzB,IAAG;AACH;AACA,EAAE,MAAM,SAAS,GAAG,CAAC,GAAG,IAAI,KAAK;AACjC,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;AAC3B,IAAI,MAAM,MAAM,GAAG,GAAG,GAAG,SAAS,CAAC;AACnC,IAAI,KAAK,MAAM,IAAI,SAAS,EAAE;AAC9B,MAAM,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AACxB,KAAK,MAAM;AACX,MAAM,QAAQ,GAAG,IAAI,CAAC;AACtB,MAAM,IAAI,CAAC,KAAK,EAAE;AAClB,QAAQ,KAAK,GAAG,UAAU,CAAC,MAAM;AACjC,UAAU,KAAK,GAAG,IAAI,CAAC;AACvB,UAAU,MAAM,CAAC,QAAQ,EAAC;AAC1B,SAAS,EAAE,SAAS,GAAG,MAAM,CAAC,CAAC;AAC/B,OAAO;AACP,KAAK;AACL,IAAG;AACH;AACA,EAAE,MAAM,KAAK,GAAG,MAAM,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC;AACnD;AACA,EAAE,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC5B;;ACrCO,MAAM,oBAAoB,GAAG,CAAC,QAAQ,EAAE,gBAAgB,EAAE,IAAI,GAAG,CAAC,KAAK;AAC9E,EAAE,IAAI,aAAa,GAAG,CAAC,CAAC;AACxB,EAAE,MAAM,YAAY,GAAG,WAAW,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;AAC5C;AACA,EAAE,OAAO,QAAQ,CAAC,CAAC,IAAI;AACvB,IAAI,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC;AAC5B,IAAI,MAAM,KAAK,GAAG,CAAC,CAAC,gBAAgB,GAAG,CAAC,CAAC,KAAK,GAAG,SAAS,CAAC;AAC3D,IAAI,MAAM,aAAa,GAAG,MAAM,GAAG,aAAa,CAAC;AACjD,IAAI,MAAM,IAAI,GAAG,YAAY,CAAC,aAAa,CAAC,CAAC;AAC7C,IAAI,MAAM,OAAO,GAAG,MAAM,IAAI,KAAK,CAAC;AACpC;AACA,IAAI,aAAa,GAAG,MAAM,CAAC;AAC3B;AACA,IAAI,MAAM,IAAI,GAAG;AACjB,MAAM,MAAM;AACZ,MAAM,KAAK;AACX,MAAM,QAAQ,EAAE,KAAK,IAAI,MAAM,GAAG,KAAK,IAAI,SAAS;AACpD,MAAM,KAAK,EAAE,aAAa;AAC1B,MAAM,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,SAAS;AACnC,MAAM,SAAS,EAAE,IAAI,IAAI,KAAK,IAAI,OAAO,GAAG,CAAC,KAAK,GAAG,MAAM,IAAI,IAAI,GAAG,SAAS;AAC/E,MAAM,KAAK,EAAE,CAAC;AACd,MAAM,gBAAgB,EAAE,KAAK,IAAI,IAAI;AACrC,MAAM,CAAC,gBAAgB,GAAG,UAAU,GAAG,QAAQ,GAAG,IAAI;AACtD,KAAK,CAAC;AACN;AACA,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC;AACnB,GAAG,EAAE,IAAI,CAAC,CAAC;AACX,EAAC;AACD;AACO,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK;AAC5D,EAAE,MAAM,gBAAgB,GAAG,KAAK,IAAI,IAAI,CAAC;AACzC;AACA,EAAE,OAAO,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC;AACnC,IAAI,gBAAgB;AACpB,IAAI,KAAK;AACT,IAAI,MAAM;AACV,GAAG,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;AACpB,EAAC;AACD;AACO,MAAM,cAAc,GAAG,CAAC,EAAE,KAAK,CAAC,GAAG,IAAI,KAAKA,OAAK,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;;ACfhF,MAAM,WAAW,GAAG;AACpB,EAAE,KAAK,EAAEa,wBAAI,CAAC,SAAS,CAAC,YAAY;AACpC,EAAE,WAAW,EAAEA,wBAAI,CAAC,SAAS,CAAC,YAAY;AAC1C,CAAC,CAAC;AACF;AACA,MAAM,aAAa,GAAG;AACtB,EAAE,KAAK,EAAEA,wBAAI,CAAC,SAAS,CAAC,sBAAsB;AAC9C,EAAE,WAAW,EAAEA,wBAAI,CAAC,SAAS,CAAC,sBAAsB;AACpD,EAAC;AACD;AACA,MAAM,iBAAiB,GAAGb,OAAK,CAAC,UAAU,CAACa,wBAAI,CAAC,sBAAsB,CAAC,CAAC;AACxE;AACA,MAAM,CAAC,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,CAAC,GAAGC,mCAAe,CAAC;AAC/D;AACA,MAAM,OAAO,GAAG,SAAS,CAAC;AAC1B;AACA,MAAM,kBAAkB,GAAG,QAAQ,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,IAAI;AAC9D,EAAE,OAAO,QAAQ,GAAG,GAAG,CAAC;AACxB,CAAC,CAAC,CAAC;AACH;AACA,MAAM,aAAa,GAAG,CAAC,MAAM,EAAE,CAAC,SAAS,EAAE,KAAK,CAAC,KAAK;AACtD,EAAE,MAAM;AACR,KAAK,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC;AACrB,KAAK,EAAE,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AACxB;AACA,EAAE,OAAO,SAAS,CAAC;AACnB,EAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,sBAAsB,CAAC,OAAO,EAAE,eAAe,EAAE;AAC1D,EAAE,IAAI,OAAO,CAAC,eAAe,CAAC,KAAK,EAAE;AACrC,IAAI,OAAO,CAAC,eAAe,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AAC3C,GAAG;AACH,EAAE,IAAI,OAAO,CAAC,eAAe,CAAC,MAAM,EAAE;AACtC,IAAI,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;AAC7D,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,QAAQ,CAAC,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE;AAClD,EAAE,IAAI,KAAK,GAAG,WAAW,CAAC;AAC1B,EAAE,IAAI,CAAC,KAAK,IAAI,KAAK,KAAK,KAAK,EAAE;AACjC,IAAI,MAAM,QAAQ,GAAGC,gCAAY,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;AAC3D,IAAI,IAAI,QAAQ,EAAE;AAClB,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;AAChC,KAAK;AACL,GAAG;AACH,EAAE,IAAI,KAAK,EAAE;AACb;AACA,IAAI,IAAI,KAAK,CAAC,QAAQ,EAAE;AACxB,MAAM,KAAK,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,QAAQ,IAAI,EAAE,IAAI,GAAG,IAAI,KAAK,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC;AACzE,KAAK;AACL;AACA,IAAI,IAAI,KAAK,CAAC,IAAI,EAAE;AACpB;AACA,MAAM,IAAI,KAAK,CAAC,IAAI,CAAC,QAAQ,IAAI,KAAK,CAAC,IAAI,CAAC,QAAQ,EAAE;AACtD,QAAQ,KAAK,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,IAAI,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC;AACrF,OAAO;AACP,MAAM,MAAM,MAAM,GAAG,MAAM;AAC3B,SAAS,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC;AACjC,SAAS,QAAQ,CAAC,QAAQ,CAAC,CAAC;AAC5B,MAAM,OAAO,CAAC,OAAO,CAAC,qBAAqB,CAAC,GAAG,QAAQ,GAAG,MAAM,CAAC;AACjE,KAAK;AACL;AACA,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,QAAQ,IAAI,OAAO,CAAC,IAAI,GAAG,GAAG,GAAG,OAAO,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC;AACvF,IAAI,MAAM,SAAS,GAAG,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,IAAI,CAAC;AACnD,IAAI,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC;AACjC;AACA,IAAI,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC;AAC7B,IAAI,OAAO,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;AAC9B,IAAI,OAAO,CAAC,IAAI,GAAG,QAAQ,CAAC;AAC5B,IAAI,IAAI,KAAK,CAAC,QAAQ,EAAE;AACxB,MAAM,OAAO,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,QAAQ,GAAG,CAAC,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC9F,KAAK;AACL,GAAG;AACH;AACA,EAAE,OAAO,CAAC,eAAe,CAAC,KAAK,GAAG,SAAS,cAAc,CAAC,eAAe,EAAE;AAC3E;AACA;AACA,IAAI,QAAQ,CAAC,eAAe,EAAE,WAAW,EAAE,eAAe,CAAC,IAAI,CAAC,CAAC;AACjE,GAAG,CAAC;AACJ,CAAC;AACD;AACA,MAAM,sBAAsB,GAAG,OAAO,OAAO,KAAK,WAAW,IAAIf,OAAK,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,SAAS,CAAC;AACrG;AACA;AACA;AACA,MAAM,SAAS,GAAG,CAAC,aAAa,KAAK;AACrC,EAAE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK;AAC1C,IAAI,IAAI,MAAM,CAAC;AACf,IAAI,IAAI,MAAM,CAAC;AACf;AACA,IAAI,MAAM,IAAI,GAAG,CAAC,KAAK,EAAE,UAAU,KAAK;AACxC,MAAM,IAAI,MAAM,EAAE,OAAO;AACzB,MAAM,MAAM,GAAG,IAAI,CAAC;AACpB,MAAM,MAAM,IAAI,MAAM,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;AAC1C,MAAK;AACL;AACA,IAAI,MAAM,QAAQ,GAAG,CAAC,KAAK,KAAK;AAChC,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC;AAClB,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;AACrB,KAAK,CAAC;AACN;AACA,IAAI,MAAM,OAAO,GAAG,CAAC,MAAM,KAAK;AAChC,MAAM,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AACzB,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC;AACrB,MAAK;AACL;AACA,IAAI,aAAa,CAAC,QAAQ,EAAE,OAAO,EAAE,CAAC,aAAa,MAAM,MAAM,GAAG,aAAa,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AACjG,GAAG,CAAC;AACJ,CAAC,CAAC;AACF;AACA,MAAM,aAAa,GAAG,CAAC,CAAC,OAAO,EAAE,MAAM,CAAC,KAAK;AAC7C,EAAE,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;AAChC,IAAI,MAAM,SAAS,CAAC,0BAA0B,CAAC,CAAC;AAChD,GAAG;AACH,EAAE,QAAQ;AACV,IAAI,OAAO;AACX,IAAI,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACxD,GAAG,EAAE;AACL,EAAC;AACD;AACA,MAAM,iBAAiB,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,aAAa,CAACA,OAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,OAAO,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;AACpH;AACA;AACA,oBAAe,sBAAsB,IAAI,SAAS,WAAW,CAAC,MAAM,EAAE;AACtE,EAAE,OAAO,SAAS,CAAC,eAAe,mBAAmB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE;AAC/E,IAAI,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAAC;AACxC,IAAI,MAAM,CAAC,YAAY,EAAE,gBAAgB,CAAC,GAAG,MAAM,CAAC;AACpD,IAAI,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC;AAC/C,IAAI,IAAI,MAAM,CAAC;AACf,IAAI,IAAI,QAAQ,GAAG,KAAK,CAAC;AACzB,IAAI,IAAI,GAAG,CAAC;AACZ;AACA,IAAI,IAAI,MAAM,EAAE;AAChB,MAAM,MAAM,OAAO,GAAGgB,aAAW,CAAC,MAAM,EAAE,CAAC,KAAK,KAAKhB,OAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;AAC7F;AACA,MAAM,MAAM,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,KAAK;AACtC,QAAQ,OAAO,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,KAAK;AACpD,UAAU,IAAI,GAAG,EAAE;AACnB,YAAY,OAAO,EAAE,CAAC,GAAG,CAAC,CAAC;AAC3B,WAAW;AACX;AACA,UAAU,MAAM,SAAS,GAAGA,OAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,IAAI,iBAAiB,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;AAC9H;AACA,UAAU,GAAG,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,EAAE,SAAS,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;AAC5F,SAAS,CAAC,CAAC;AACX,QAAO;AACP,KAAK;AACL;AACA;AACA,IAAI,MAAM,OAAO,GAAG,IAAIiB,mBAAY,EAAE,CAAC;AACvC;AACA,IAAI,MAAM,UAAU,GAAG,MAAM;AAC7B,MAAM,IAAI,MAAM,CAAC,WAAW,EAAE;AAC9B,QAAQ,MAAM,CAAC,WAAW,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;AAC9C,OAAO;AACP;AACA,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE;AACzB,QAAQ,MAAM,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AAC1D,OAAO;AACP;AACA,MAAM,OAAO,CAAC,kBAAkB,EAAE,CAAC;AACnC,MAAK;AACL;AACA,IAAI,MAAM,CAAC,CAAC,KAAK,EAAE,UAAU,KAAK;AAClC,MAAM,MAAM,GAAG,IAAI,CAAC;AACpB,MAAM,IAAI,UAAU,EAAE;AACtB,QAAQ,QAAQ,GAAG,IAAI,CAAC;AACxB,QAAQ,UAAU,EAAE,CAAC;AACrB,OAAO;AACP,KAAK,CAAC,CAAC;AACP;AACA,IAAI,SAAS,KAAK,CAAC,MAAM,EAAE;AAC3B,MAAM,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,MAAM,IAAI,MAAM,CAAC,IAAI,GAAG,IAAI,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC,CAAC;AACpG,KAAK;AACL;AACA,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AAClC;AACA,IAAI,IAAI,MAAM,CAAC,WAAW,IAAI,MAAM,CAAC,MAAM,EAAE;AAC7C,MAAM,MAAM,CAAC,WAAW,IAAI,MAAM,CAAC,WAAW,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAChE,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE;AACzB,QAAQ,MAAM,CAAC,MAAM,CAAC,OAAO,GAAG,KAAK,EAAE,GAAG,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AACzF,OAAO;AACP,KAAK;AACL;AACA;AACA,IAAI,MAAM,QAAQ,GAAG,aAAa,CAAC,MAAM,CAAC,OAAO,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;AAC/D,IAAI,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,QAAQ,EAAE,QAAQ,CAAC,aAAa,GAAG,QAAQ,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;AAC3F,IAAI,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,IAAI,kBAAkB,CAAC,CAAC,CAAC,CAAC;AAC9D;AACA,IAAI,IAAI,QAAQ,KAAK,OAAO,EAAE;AAC9B,MAAM,IAAI,aAAa,CAAC;AACxB;AACA,MAAM,IAAI,MAAM,KAAK,KAAK,EAAE;AAC5B,QAAQ,OAAO,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE;AACvC,UAAU,MAAM,EAAE,GAAG;AACrB,UAAU,UAAU,EAAE,oBAAoB;AAC1C,UAAU,OAAO,EAAE,EAAE;AACrB,UAAU,MAAM;AAChB,SAAS,CAAC,CAAC;AACX,OAAO;AACP;AACA,MAAM,IAAI;AACV,QAAQ,aAAa,GAAG,WAAW,CAAC,MAAM,CAAC,GAAG,EAAE,YAAY,KAAK,MAAM,EAAE;AACzE,UAAU,IAAI,EAAE,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,GAAG,CAAC,IAAI;AAC7C,SAAS,CAAC,CAAC;AACX,OAAO,CAAC,OAAO,GAAG,EAAE;AACpB,QAAQ,MAAM,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,UAAU,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC;AACvE,OAAO;AACP;AACA,MAAM,IAAI,YAAY,KAAK,MAAM,EAAE;AACnC,QAAQ,aAAa,GAAG,aAAa,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;AACjE;AACA,QAAQ,IAAI,CAAC,gBAAgB,IAAI,gBAAgB,KAAK,MAAM,EAAE;AAC9D,UAAU,aAAa,GAAGjB,OAAK,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;AACxD,SAAS;AACT,OAAO,MAAM,IAAI,YAAY,KAAK,QAAQ,EAAE;AAC5C,QAAQ,aAAa,GAAGS,0BAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;AAC5D,OAAO;AACP;AACA,MAAM,OAAO,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE;AACrC,QAAQ,IAAI,EAAE,aAAa;AAC3B,QAAQ,MAAM,EAAE,GAAG;AACnB,QAAQ,UAAU,EAAE,IAAI;AACxB,QAAQ,OAAO,EAAE,IAAID,cAAY,EAAE;AACnC,QAAQ,MAAM;AACd,OAAO,CAAC,CAAC;AACT,KAAK;AACL;AACA,IAAI,IAAI,kBAAkB,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE;AACrD,MAAM,OAAO,MAAM,CAAC,IAAI,UAAU;AAClC,QAAQ,uBAAuB,GAAG,QAAQ;AAC1C,QAAQ,UAAU,CAAC,eAAe;AAClC,QAAQ,MAAM;AACd,OAAO,CAAC,CAAC;AACT,KAAK;AACL;AACA,IAAI,MAAM,OAAO,GAAGA,cAAY,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC;AAClE;AACA;AACA;AACA;AACA;AACA,IAAI,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,QAAQ,GAAG,OAAO,EAAE,KAAK,CAAC,CAAC;AACzD;AACA,IAAI,MAAM,CAAC,gBAAgB,EAAE,kBAAkB,CAAC,GAAG,MAAM,CAAC;AAC1D,IAAI,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;AACnC,IAAI,IAAI,aAAa,GAAG,SAAS,CAAC;AAClC,IAAI,IAAI,eAAe,GAAG,SAAS,CAAC;AACpC;AACA;AACA,IAAI,IAAIR,OAAK,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE;AACzC,MAAM,MAAM,YAAY,GAAG,OAAO,CAAC,cAAc,CAAC,6BAA6B,CAAC,CAAC;AACjF;AACA,MAAM,IAAI,GAAGkB,kBAAgB,CAAC,IAAI,EAAE,CAAC,WAAW,KAAK;AACrD,QAAQ,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;AACjC,OAAO,EAAE;AACT,QAAQ,GAAG,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC;AACxC,QAAQ,QAAQ,EAAE,YAAY,IAAI,YAAY,CAAC,CAAC,CAAC,IAAI,SAAS;AAC9D,OAAO,CAAC,CAAC;AACT;AACA,KAAK,MAAM,IAAIlB,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,IAAIA,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE;AAC5E,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;AACrC;AACA,MAAM,IAAI,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE;AACvC,QAAQ,IAAI;AACZ,UAAU,MAAM,WAAW,GAAG,MAAMU,wBAAI,CAAC,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC9E,UAAU,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,IAAI,WAAW,IAAI,CAAC,IAAI,OAAO,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAC;AACpG;AACA,SAAS,CAAC,OAAO,CAAC,EAAE;AACpB,SAAS;AACT,OAAO;AACP,KAAK,MAAM,IAAIV,OAAK,CAAC,MAAM,CAAC,IAAI,CAAC,IAAIA,OAAK,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;AACzD,MAAM,IAAI,CAAC,IAAI,IAAI,OAAO,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,IAAI,0BAA0B,CAAC,CAAC;AACnF,MAAM,OAAO,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC;AAC/C,MAAM,IAAI,GAAGS,0BAAM,CAAC,QAAQ,CAAC,IAAI,CAACE,UAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;AAClD,KAAK,MAAM,IAAI,IAAI,IAAI,CAACX,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;AAC9C,MAAM,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAE1B,MAAM,IAAIA,OAAK,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE;AAC5C,QAAQ,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;AACjD,OAAO,MAAM,IAAIA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;AACvC,QAAQ,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AAC1C,OAAO,MAAM;AACb,QAAQ,OAAO,MAAM,CAAC,IAAI,UAAU;AACpC,UAAU,mFAAmF;AAC7F,UAAU,UAAU,CAAC,eAAe;AACpC,UAAU,MAAM;AAChB,SAAS,CAAC,CAAC;AACX,OAAO;AACP;AACA;AACA,MAAM,OAAO,CAAC,gBAAgB,CAAC,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AACnD;AACA,MAAM,IAAI,MAAM,CAAC,aAAa,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,aAAa,EAAE;AAC3E,QAAQ,OAAO,MAAM,CAAC,IAAI,UAAU;AACpC,UAAU,8CAA8C;AACxD,UAAU,UAAU,CAAC,eAAe;AACpC,UAAU,MAAM;AAChB,SAAS,CAAC,CAAC;AACX,OAAO;AACP,KAAK;AACL;AACA,IAAI,MAAM,aAAa,GAAGA,OAAK,CAAC,cAAc,CAAC,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;AAC3E;AACA,IAAI,IAAIA,OAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;AAChC,MAAM,aAAa,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AACjC,MAAM,eAAe,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AACnC,KAAK,MAAM;AACX,MAAM,aAAa,GAAG,eAAe,GAAG,OAAO,CAAC;AAChD,KAAK;AACL;AACA,IAAI,IAAI,IAAI,KAAK,gBAAgB,IAAI,aAAa,CAAC,EAAE;AACrD,MAAM,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;AACjC,QAAQ,IAAI,GAAGS,0BAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC,CAAC;AAC/D,OAAO;AACP;AACA,MAAM,IAAI,GAAGA,0BAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,IAAIU,sBAAoB,CAAC;AAC7D,QAAQ,OAAO,EAAEnB,OAAK,CAAC,cAAc,CAAC,aAAa,CAAC;AACpD,OAAO,CAAC,CAAC,EAAEA,OAAK,CAAC,IAAI,CAAC,CAAC;AACvB;AACA,MAAM,gBAAgB,IAAI,IAAI,CAAC,EAAE,CAAC,UAAU,EAAE,aAAa;AAC3D,QAAQ,IAAI;AACZ,QAAQ,sBAAsB;AAC9B,UAAU,aAAa;AACvB,UAAU,oBAAoB,CAAC,cAAc,CAAC,gBAAgB,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;AAC1E,SAAS;AACT,OAAO,CAAC,CAAC;AACT,KAAK;AACL;AACA;AACA,IAAI,IAAI,IAAI,GAAG,SAAS,CAAC;AACzB,IAAI,IAAI,MAAM,CAAC,IAAI,EAAE;AACrB,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC;AAClD,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC;AAClD,MAAM,IAAI,GAAG,QAAQ,GAAG,GAAG,GAAG,QAAQ,CAAC;AACvC,KAAK;AACL;AACA,IAAI,IAAI,CAAC,IAAI,IAAI,MAAM,CAAC,QAAQ,EAAE;AAClC,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC1C,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC1C,MAAM,IAAI,GAAG,WAAW,GAAG,GAAG,GAAG,WAAW,CAAC;AAC7C,KAAK;AACL;AACA,IAAI,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC;AAC5C;AACA,IAAI,IAAI,IAAI,CAAC;AACb;AACA,IAAI,IAAI;AACR,MAAM,IAAI,GAAG,QAAQ;AACrB,QAAQ,MAAM,CAAC,QAAQ,GAAG,MAAM,CAAC,MAAM;AACvC,QAAQ,MAAM,CAAC,MAAM;AACrB,QAAQ,MAAM,CAAC,gBAAgB;AAC/B,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AAC3B,KAAK,CAAC,OAAO,GAAG,EAAE;AAClB,MAAM,MAAM,SAAS,GAAG,IAAI,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC/C,MAAM,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC;AAChC,MAAM,SAAS,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC;AACjC,MAAM,SAAS,CAAC,MAAM,GAAG,IAAI,CAAC;AAC9B,MAAM,OAAO,MAAM,CAAC,SAAS,CAAC,CAAC;AAC/B,KAAK;AACL;AACA,IAAI,OAAO,CAAC,GAAG;AACf,MAAM,iBAAiB;AACvB,MAAM,yBAAyB,IAAI,iBAAiB,GAAG,MAAM,GAAG,EAAE,CAAC,EAAE,KAAK;AAC1E,OAAO,CAAC;AACR;AACA,IAAI,MAAM,OAAO,GAAG;AACpB,MAAM,IAAI;AACV,MAAM,MAAM,EAAE,MAAM;AACpB,MAAM,OAAO,EAAE,OAAO,CAAC,MAAM,EAAE;AAC/B,MAAM,MAAM,EAAE,EAAE,IAAI,EAAE,MAAM,CAAC,SAAS,EAAE,KAAK,EAAE,MAAM,CAAC,UAAU,EAAE;AAClE,MAAM,IAAI;AACV,MAAM,QAAQ;AACd,MAAM,MAAM;AACZ,MAAM,cAAc,EAAE,sBAAsB;AAC5C,MAAM,eAAe,EAAE,EAAE;AACzB,KAAK,CAAC;AACN;AACA;AACA,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,MAAM,CAAC,KAAK,OAAO,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC;AAC5D;AACA,IAAI,IAAI,MAAM,CAAC,UAAU,EAAE;AAC3B,MAAM,OAAO,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;AAC7C,KAAK,MAAM;AACX,MAAM,OAAO,CAAC,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC1G,MAAM,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;AACjC,MAAM,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,KAAK,EAAE,QAAQ,GAAG,IAAI,GAAG,MAAM,CAAC,QAAQ,IAAI,MAAM,CAAC,IAAI,GAAG,GAAG,GAAG,MAAM,CAAC,IAAI,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AACjI,KAAK;AACL;AACA,IAAI,IAAI,SAAS,CAAC;AAClB,IAAI,MAAM,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;AAC1D,IAAI,OAAO,CAAC,KAAK,GAAG,cAAc,GAAG,MAAM,CAAC,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC;AAC1E,IAAI,IAAI,MAAM,CAAC,SAAS,EAAE;AAC1B,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC;AACnC,KAAK,MAAM,IAAI,MAAM,CAAC,YAAY,KAAK,CAAC,EAAE;AAC1C,MAAM,SAAS,GAAG,cAAc,GAAGoB,yBAAK,GAAGC,wBAAI,CAAC;AAChD,KAAK,MAAM;AACX,MAAM,IAAI,MAAM,CAAC,YAAY,EAAE;AAC/B,QAAQ,OAAO,CAAC,YAAY,GAAG,MAAM,CAAC,YAAY,CAAC;AACnD,OAAO;AACP,MAAM,IAAI,MAAM,CAAC,cAAc,EAAE;AACjC,QAAQ,OAAO,CAAC,eAAe,CAAC,MAAM,GAAG,MAAM,CAAC,cAAc,CAAC;AAC/D,OAAO;AACP,MAAM,SAAS,GAAG,cAAc,GAAG,WAAW,GAAG,UAAU,CAAC;AAC5D,KAAK;AACL;AACA,IAAI,IAAI,MAAM,CAAC,aAAa,GAAG,CAAC,CAAC,EAAE;AACnC,MAAM,OAAO,CAAC,aAAa,GAAG,MAAM,CAAC,aAAa,CAAC;AACnD,KAAK,MAAM;AACX;AACA,MAAM,OAAO,CAAC,aAAa,GAAG,QAAQ,CAAC;AACvC,KAAK;AACL;AACA,IAAI,IAAI,MAAM,CAAC,kBAAkB,EAAE;AACnC,MAAM,OAAO,CAAC,kBAAkB,GAAG,MAAM,CAAC,kBAAkB,CAAC;AAC7D,KAAK;AACL;AACA;AACA,IAAI,GAAG,GAAG,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,SAAS,cAAc,CAAC,GAAG,EAAE;AAClE,MAAM,IAAI,GAAG,CAAC,SAAS,EAAE,OAAO;AAChC;AACA,MAAM,MAAM,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC;AAC5B;AACA,MAAM,MAAM,cAAc,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC;AAC5D;AACA,MAAM,IAAI,kBAAkB,IAAI,eAAe,EAAE;AACjD,QAAQ,MAAM,eAAe,GAAG,IAAIF,sBAAoB,CAAC;AACzD,UAAU,OAAO,EAAEnB,OAAK,CAAC,cAAc,CAAC,eAAe,CAAC;AACxD,SAAS,CAAC,CAAC;AACX;AACA,QAAQ,kBAAkB,IAAI,eAAe,CAAC,EAAE,CAAC,UAAU,EAAE,aAAa;AAC1E,UAAU,eAAe;AACzB,UAAU,sBAAsB;AAChC,YAAY,cAAc;AAC1B,YAAY,oBAAoB,CAAC,cAAc,CAAC,kBAAkB,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;AAC7E,WAAW;AACX,SAAS,CAAC,CAAC;AACX;AACA,QAAQ,OAAO,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;AACtC,OAAO;AACP;AACA;AACA,MAAM,IAAI,cAAc,GAAG,GAAG,CAAC;AAC/B;AACA;AACA,MAAM,MAAM,WAAW,GAAG,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC;AACzC;AACA;AACA,MAAM,IAAI,MAAM,CAAC,UAAU,KAAK,KAAK,IAAI,GAAG,CAAC,OAAO,CAAC,kBAAkB,CAAC,EAAE;AAC1E;AACA;AACA,QAAQ,IAAI,MAAM,KAAK,MAAM,IAAI,GAAG,CAAC,UAAU,KAAK,GAAG,EAAE;AACzD,UAAU,OAAO,GAAG,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;AACjD,SAAS;AACT;AACA,QAAQ,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,kBAAkB,CAAC,IAAI,EAAE,EAAE,WAAW,EAAE;AACrE;AACA,QAAQ,KAAK,MAAM,CAAC;AACpB,QAAQ,KAAK,QAAQ,CAAC;AACtB,QAAQ,KAAK,UAAU,CAAC;AACxB,QAAQ,KAAK,YAAY;AACzB;AACA,UAAU,OAAO,CAAC,IAAI,CAACa,wBAAI,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC,CAAC;AACtD;AACA;AACA,UAAU,OAAO,GAAG,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;AACjD,UAAU,MAAM;AAChB,QAAQ,KAAK,SAAS;AACtB,UAAU,OAAO,CAAC,IAAI,CAAC,IAAIS,2BAAyB,EAAE,CAAC,CAAC;AACxD;AACA;AACA,UAAU,OAAO,CAAC,IAAI,CAACT,wBAAI,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC,CAAC;AACtD;AACA;AACA,UAAU,OAAO,GAAG,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;AACjD,UAAU,MAAM;AAChB,QAAQ,KAAK,IAAI;AACjB,UAAU,IAAI,iBAAiB,EAAE;AACjC,YAAY,OAAO,CAAC,IAAI,CAACA,wBAAI,CAAC,sBAAsB,CAAC,aAAa,CAAC,CAAC,CAAC;AACrE,YAAY,OAAO,GAAG,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;AACnD,WAAW;AACX,SAAS;AACT,OAAO;AACP;AACA,MAAM,cAAc,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC,GAAGJ,0BAAM,CAAC,QAAQ,CAAC,OAAO,EAAET,OAAK,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAC9F;AACA,MAAM,MAAM,YAAY,GAAGS,0BAAM,CAAC,QAAQ,CAAC,cAAc,EAAE,MAAM;AACjE,QAAQ,YAAY,EAAE,CAAC;AACvB,QAAQ,UAAU,EAAE,CAAC;AACrB,OAAO,CAAC,CAAC;AACT;AACA,MAAM,MAAM,QAAQ,GAAG;AACvB,QAAQ,MAAM,EAAE,GAAG,CAAC,UAAU;AAC9B,QAAQ,UAAU,EAAE,GAAG,CAAC,aAAa;AACrC,QAAQ,OAAO,EAAE,IAAID,cAAY,CAAC,GAAG,CAAC,OAAO,CAAC;AAC9C,QAAQ,MAAM;AACd,QAAQ,OAAO,EAAE,WAAW;AAC5B,OAAO,CAAC;AACR;AACA,MAAM,IAAI,YAAY,KAAK,QAAQ,EAAE;AACrC,QAAQ,QAAQ,CAAC,IAAI,GAAG,cAAc,CAAC;AACvC,QAAQ,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;AAC1C,OAAO,MAAM;AACb,QAAQ,MAAM,cAAc,GAAG,EAAE,CAAC;AAClC,QAAQ,IAAI,kBAAkB,GAAG,CAAC,CAAC;AACnC;AACA,QAAQ,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,SAAS,gBAAgB,CAAC,KAAK,EAAE;AACnE,UAAU,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACrC,UAAU,kBAAkB,IAAI,KAAK,CAAC,MAAM,CAAC;AAC7C;AACA;AACA,UAAU,IAAI,MAAM,CAAC,gBAAgB,GAAG,CAAC,CAAC,IAAI,kBAAkB,GAAG,MAAM,CAAC,gBAAgB,EAAE;AAC5F;AACA,YAAY,QAAQ,GAAG,IAAI,CAAC;AAC5B,YAAY,cAAc,CAAC,OAAO,EAAE,CAAC;AACrC,YAAY,MAAM,CAAC,IAAI,UAAU,CAAC,2BAA2B,GAAG,MAAM,CAAC,gBAAgB,GAAG,WAAW;AACrG,cAAc,UAAU,CAAC,gBAAgB,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC;AACjE,WAAW;AACX,SAAS,CAAC,CAAC;AACX;AACA,QAAQ,cAAc,CAAC,EAAE,CAAC,SAAS,EAAE,SAAS,oBAAoB,GAAG;AACrE,UAAU,IAAI,QAAQ,EAAE;AACxB,YAAY,OAAO;AACnB,WAAW;AACX;AACA,UAAU,MAAM,GAAG,GAAG,IAAI,UAAU;AACpC,YAAY,yBAAyB;AACrC,YAAY,UAAU,CAAC,gBAAgB;AACvC,YAAY,MAAM;AAClB,YAAY,WAAW;AACvB,WAAW,CAAC;AACZ,UAAU,cAAc,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AACtC,UAAU,MAAM,CAAC,GAAG,CAAC,CAAC;AACtB,SAAS,CAAC,CAAC;AACX;AACA,QAAQ,cAAc,CAAC,EAAE,CAAC,OAAO,EAAE,SAAS,iBAAiB,CAAC,GAAG,EAAE;AACnE,UAAU,IAAI,GAAG,CAAC,SAAS,EAAE,OAAO;AACpC,UAAU,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC;AAClE,SAAS,CAAC,CAAC;AACX;AACA,QAAQ,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,eAAe,GAAG;AAC5D,UAAU,IAAI;AACd,YAAY,IAAI,YAAY,GAAG,cAAc,CAAC,MAAM,KAAK,CAAC,GAAG,cAAc,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;AAC/G,YAAY,IAAI,YAAY,KAAK,aAAa,EAAE;AAChD,cAAc,YAAY,GAAG,YAAY,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;AACrE,cAAc,IAAI,CAAC,gBAAgB,IAAI,gBAAgB,KAAK,MAAM,EAAE;AACpE,gBAAgB,YAAY,GAAGR,OAAK,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;AAC5D,eAAe;AACf,aAAa;AACb,YAAY,QAAQ,CAAC,IAAI,GAAG,YAAY,CAAC;AACzC,WAAW,CAAC,OAAO,GAAG,EAAE;AACxB,YAAY,OAAO,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC;AAC1F,WAAW;AACX,UAAU,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;AAC5C,SAAS,CAAC,CAAC;AACX,OAAO;AACP;AACA,MAAM,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,IAAI;AACnC,QAAQ,IAAI,CAAC,cAAc,CAAC,SAAS,EAAE;AACvC,UAAU,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AAC5C,UAAU,cAAc,CAAC,OAAO,EAAE,CAAC;AACnC,SAAS;AACT,OAAO,CAAC,CAAC;AACT,KAAK,CAAC,CAAC;AACP;AACA,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,IAAI;AACjC,MAAM,MAAM,CAAC,GAAG,CAAC,CAAC;AAClB,MAAM,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AACvB,KAAK,CAAC,CAAC;AACP;AACA;AACA,IAAI,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,SAAS,kBAAkB,CAAC,GAAG,EAAE;AACrD;AACA;AACA,MAAM,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;AACtD,KAAK,CAAC,CAAC;AACP;AACA;AACA,IAAI,GAAG,CAAC,EAAE,CAAC,QAAQ,EAAE,SAAS,mBAAmB,CAAC,MAAM,EAAE;AAC1D;AACA,MAAM,MAAM,CAAC,YAAY,CAAC,IAAI,EAAE,IAAI,GAAG,EAAE,CAAC,CAAC;AAC3C,KAAK,CAAC,CAAC;AACP;AACA;AACA,IAAI,IAAI,MAAM,CAAC,OAAO,EAAE;AACxB;AACA,MAAM,MAAM,OAAO,GAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AACnD;AACA,MAAM,IAAI,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE;AACjC,QAAQ,MAAM,CAAC,IAAI,UAAU;AAC7B,UAAU,+CAA+C;AACzD,UAAU,UAAU,CAAC,oBAAoB;AACzC,UAAU,MAAM;AAChB,UAAU,GAAG;AACb,SAAS,CAAC,CAAC;AACX;AACA,QAAQ,OAAO;AACf,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,GAAG,CAAC,UAAU,CAAC,OAAO,EAAE,SAAS,oBAAoB,GAAG;AAC9D,QAAQ,IAAI,MAAM,EAAE,OAAO;AAC3B,QAAQ,IAAI,mBAAmB,GAAG,MAAM,CAAC,OAAO,GAAG,aAAa,GAAG,MAAM,CAAC,OAAO,GAAG,aAAa,GAAG,kBAAkB,CAAC;AACvH,QAAQ,MAAM,YAAY,GAAG,MAAM,CAAC,YAAY,IAAI,oBAAoB,CAAC;AACzE,QAAQ,IAAI,MAAM,CAAC,mBAAmB,EAAE;AACxC,UAAU,mBAAmB,GAAG,MAAM,CAAC,mBAAmB,CAAC;AAC3D,SAAS;AACT,QAAQ,MAAM,CAAC,IAAI,UAAU;AAC7B,UAAU,mBAAmB;AAC7B,UAAU,YAAY,CAAC,mBAAmB,GAAG,UAAU,CAAC,SAAS,GAAG,UAAU,CAAC,YAAY;AAC3F,UAAU,MAAM;AAChB,UAAU,GAAG;AACb,SAAS,CAAC,CAAC;AACX,QAAQ,KAAK,EAAE,CAAC;AAChB,OAAO,CAAC,CAAC;AACT,KAAK;AACL;AACA;AACA;AACA,IAAI,IAAIA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;AAC9B,MAAM,IAAI,KAAK,GAAG,KAAK,CAAC;AACxB,MAAM,IAAI,OAAO,GAAG,KAAK,CAAC;AAC1B;AACA,MAAM,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM;AAC3B,QAAQ,KAAK,GAAG,IAAI,CAAC;AACrB,OAAO,CAAC,CAAC;AACT;AACA,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,IAAI;AAChC,QAAQ,OAAO,GAAG,IAAI,CAAC;AACvB,QAAQ,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AACzB,OAAO,CAAC,CAAC;AACT;AACA,MAAM,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM;AAC7B,QAAQ,IAAI,CAAC,KAAK,IAAI,CAAC,OAAO,EAAE;AAChC,UAAU,KAAK,CAAC,IAAI,aAAa,CAAC,iCAAiC,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;AACnF,SAAS;AACT,OAAO,CAAC,CAAC;AACT;AACA,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACrB,KAAK,MAAM;AACX,MAAM,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AACpB,KAAK;AACL,GAAG,CAAC,CAAC;AACL;;AClrBA,wBAAe,QAAQ,CAAC,qBAAqB,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,KAAK,CAAC,GAAG,KAAK;AAC9E,EAAE,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;AACtC;AACA,EAAE;AACF,IAAI,MAAM,CAAC,QAAQ,KAAK,GAAG,CAAC,QAAQ;AACpC,IAAI,MAAM,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI;AAC5B,KAAK,MAAM,IAAI,MAAM,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,CAAC;AACxC,IAAI;AACJ,CAAC;AACD,EAAE,IAAI,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC1B,EAAE,QAAQ,CAAC,SAAS,IAAI,iBAAiB,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,SAAS,CAAC;AAC5E,CAAC,GAAG,MAAM,IAAI;;ACVd,gBAAe,QAAQ,CAAC,qBAAqB;AAC7C;AACA;AACA,EAAE;AACF,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE;AACtD,MAAM,MAAM,MAAM,GAAG,CAAC,IAAI,GAAG,GAAG,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC;AAC9D;AACA,MAAMA,OAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,GAAG,IAAI,IAAI,CAAC,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AAC3F;AACA,MAAMA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;AAC1D;AACA,MAAMA,OAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,CAAC;AAChE;AACA,MAAM,MAAM,KAAK,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC/C;AACA,MAAM,QAAQ,CAAC,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1C,KAAK;AACL;AACA,IAAI,IAAI,CAAC,IAAI,EAAE;AACf,MAAM,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,YAAY,GAAG,IAAI,GAAG,WAAW,CAAC,CAAC,CAAC;AACzF,MAAM,QAAQ,KAAK,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,EAAE;AAC3D,KAAK;AACL;AACA,IAAI,MAAM,CAAC,IAAI,EAAE;AACjB,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,QAAQ,CAAC,CAAC;AAClD,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA,EAAE;AACF,IAAI,KAAK,GAAG,EAAE;AACd,IAAI,IAAI,GAAG;AACX,MAAM,OAAO,IAAI,CAAC;AAClB,KAAK;AACL,IAAI,MAAM,GAAG,EAAE;AACf,GAAG;;ACnCH,MAAM,eAAe,GAAG,CAAC,KAAK,KAAK,KAAK,YAAYQ,cAAY,GAAG,EAAE,GAAG,KAAK,EAAE,GAAG,KAAK,CAAC;AACxF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE;AACtD;AACA,EAAE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;AAC1B,EAAE,MAAM,MAAM,GAAG,EAAE,CAAC;AACpB;AACA,EAAE,SAAS,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE;AAC1D,IAAI,IAAIR,OAAK,CAAC,aAAa,CAAC,MAAM,CAAC,IAAIA,OAAK,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE;AACpE,MAAM,OAAOA,OAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC1D,KAAK,MAAM,IAAIA,OAAK,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE;AAC5C,MAAM,OAAOA,OAAK,CAAC,KAAK,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;AACrC,KAAK,MAAM,IAAIA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;AACtC,MAAM,OAAO,MAAM,CAAC,KAAK,EAAE,CAAC;AAC5B,KAAK;AACL,IAAI,OAAO,MAAM,CAAC;AAClB,GAAG;AACH;AACA;AACA,EAAE,SAAS,mBAAmB,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,QAAQ,EAAE;AACtD,IAAI,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AAC/B,MAAM,OAAO,cAAc,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,QAAQ,CAAC,CAAC;AACnD,KAAK,MAAM,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AACtC,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,EAAE,IAAI,GAAG,QAAQ,CAAC,CAAC;AAC3D,KAAK;AACL,GAAG;AACH;AACA;AACA,EAAE,SAAS,gBAAgB,CAAC,CAAC,EAAE,CAAC,EAAE;AAClC,IAAI,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AAC/B,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;AAC1C,KAAK;AACL,GAAG;AACH;AACA;AACA,EAAE,SAAS,gBAAgB,CAAC,CAAC,EAAE,CAAC,EAAE;AAClC,IAAI,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AAC/B,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;AAC1C,KAAK,MAAM,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;AACtC,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;AAC1C,KAAK;AACL,GAAG;AACH;AACA;AACA,EAAE,SAAS,eAAe,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE;AACvC,IAAI,IAAI,IAAI,IAAI,OAAO,EAAE;AACzB,MAAM,OAAO,cAAc,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAClC,KAAK,MAAM,IAAI,IAAI,IAAI,OAAO,EAAE;AAChC,MAAM,OAAO,cAAc,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;AAC1C,KAAK;AACL,GAAG;AACH;AACA,EAAE,MAAM,QAAQ,GAAG;AACnB,IAAI,GAAG,EAAE,gBAAgB;AACzB,IAAI,MAAM,EAAE,gBAAgB;AAC5B,IAAI,IAAI,EAAE,gBAAgB;AAC1B,IAAI,OAAO,EAAE,gBAAgB;AAC7B,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,iBAAiB,EAAE,gBAAgB;AACvC,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,OAAO,EAAE,gBAAgB;AAC7B,IAAI,cAAc,EAAE,gBAAgB;AACpC,IAAI,eAAe,EAAE,gBAAgB;AACrC,IAAI,aAAa,EAAE,gBAAgB;AACnC,IAAI,OAAO,EAAE,gBAAgB;AAC7B,IAAI,YAAY,EAAE,gBAAgB;AAClC,IAAI,cAAc,EAAE,gBAAgB;AACpC,IAAI,cAAc,EAAE,gBAAgB;AACpC,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,kBAAkB,EAAE,gBAAgB;AACxC,IAAI,UAAU,EAAE,gBAAgB;AAChC,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,aAAa,EAAE,gBAAgB;AACnC,IAAI,cAAc,EAAE,gBAAgB;AACpC,IAAI,SAAS,EAAE,gBAAgB;AAC/B,IAAI,SAAS,EAAE,gBAAgB;AAC/B,IAAI,UAAU,EAAE,gBAAgB;AAChC,IAAI,WAAW,EAAE,gBAAgB;AACjC,IAAI,UAAU,EAAE,gBAAgB;AAChC,IAAI,gBAAgB,EAAE,gBAAgB;AACtC,IAAI,cAAc,EAAE,eAAe;AACnC,IAAI,OAAO,EAAE,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,KAAK,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC;AACpG,GAAG,CAAC;AACJ;AACA,EAAEA,OAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,EAAE,SAAS,kBAAkB,CAAC,IAAI,EAAE;AACpG,IAAI,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,IAAI,mBAAmB,CAAC;AACxD,IAAI,MAAM,WAAW,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;AAClE,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,WAAW,CAAC,IAAI,KAAK,KAAK,eAAe,MAAM,MAAM,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,CAAC;AAClG,GAAG,CAAC,CAAC;AACL;AACA,EAAE,OAAO,MAAM,CAAC;AAChB;;AChGA,sBAAe,CAAC,MAAM,KAAK;AAC3B,EAAE,MAAM,SAAS,GAAG,WAAW,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;AAC5C;AACA,EAAE,IAAI,CAAC,IAAI,EAAE,aAAa,EAAE,cAAc,EAAE,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC,GAAG,SAAS,CAAC;AACvF;AACA,EAAE,SAAS,CAAC,OAAO,GAAG,OAAO,GAAGQ,cAAY,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAC3D;AACA,EAAE,SAAS,CAAC,GAAG,GAAG,QAAQ,CAAC,aAAa,CAAC,SAAS,CAAC,OAAO,EAAE,SAAS,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,gBAAgB,CAAC,CAAC;AACpH;AACA;AACA,EAAE,IAAI,IAAI,EAAE;AACZ,IAAI,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,QAAQ;AACzC,MAAM,IAAI,CAAC,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC,kBAAkB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;AAC5G,KAAK,CAAC;AACN,GAAG;AACH;AACA,EAAE,IAAI,WAAW,CAAC;AAClB;AACA,EAAE,IAAIR,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;AAC9B,IAAI,IAAI,QAAQ,CAAC,qBAAqB,IAAI,QAAQ,CAAC,8BAA8B,EAAE;AACnF,MAAM,OAAO,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC;AACxC,KAAK,MAAM,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,cAAc,EAAE,MAAM,KAAK,EAAE;AACnE;AACA,MAAM,MAAM,CAAC,IAAI,EAAE,GAAG,MAAM,CAAC,GAAG,WAAW,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;AACrH,MAAM,OAAO,CAAC,cAAc,CAAC,CAAC,IAAI,IAAI,qBAAqB,EAAE,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AACpF,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,EAAE,IAAI,QAAQ,CAAC,qBAAqB,EAAE;AACtC,IAAI,aAAa,IAAIA,OAAK,CAAC,UAAU,CAAC,aAAa,CAAC,KAAK,aAAa,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC,CAAC;AACnG;AACA,IAAI,IAAI,aAAa,KAAK,aAAa,KAAK,KAAK,IAAI,eAAe,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,EAAE;AACtF;AACA,MAAM,MAAM,SAAS,GAAG,cAAc,IAAI,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;AACzF;AACA,MAAM,IAAI,SAAS,EAAE;AACrB,QAAQ,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,SAAS,CAAC,CAAC;AAC/C,OAAO;AACP,KAAK;AACL,GAAG;AACH;AACA,EAAE,OAAO,SAAS,CAAC;AACnB;;AC5CA,MAAM,qBAAqB,GAAG,OAAO,cAAc,KAAK,WAAW,CAAC;AACpE;AACA,mBAAe,qBAAqB,IAAI,UAAU,MAAM,EAAE;AAC1D,EAAE,OAAO,IAAI,OAAO,CAAC,SAAS,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE;AAClE,IAAI,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;AAC1C,IAAI,IAAI,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;AACnC,IAAI,MAAM,cAAc,GAAGQ,cAAY,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC;AAC1E,IAAI,IAAI,CAAC,YAAY,EAAE,gBAAgB,EAAE,kBAAkB,CAAC,GAAG,OAAO,CAAC;AACvE,IAAI,IAAI,UAAU,CAAC;AACnB,IAAI,IAAI,eAAe,EAAE,iBAAiB,CAAC;AAC3C,IAAI,IAAI,WAAW,EAAE,aAAa,CAAC;AACnC;AACA,IAAI,SAAS,IAAI,GAAG;AACpB,MAAM,WAAW,IAAI,WAAW,EAAE,CAAC;AACnC,MAAM,aAAa,IAAI,aAAa,EAAE,CAAC;AACvC;AACA,MAAM,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;AACzE;AACA,MAAM,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;AAChF,KAAK;AACL;AACA,IAAI,IAAI,OAAO,GAAG,IAAI,cAAc,EAAE,CAAC;AACvC;AACA,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,WAAW,EAAE,EAAE,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AAClE;AACA;AACA,IAAI,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;AACtC;AACA,IAAI,SAAS,SAAS,GAAG;AACzB,MAAM,IAAI,CAAC,OAAO,EAAE;AACpB,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,MAAM,eAAe,GAAGA,cAAY,CAAC,IAAI;AAC/C,QAAQ,uBAAuB,IAAI,OAAO,IAAI,OAAO,CAAC,qBAAqB,EAAE;AAC7E,OAAO,CAAC;AACR,MAAM,MAAM,YAAY,GAAG,CAAC,YAAY,IAAI,YAAY,KAAK,MAAM,IAAI,YAAY,KAAK,MAAM;AAC9F,QAAQ,OAAO,CAAC,YAAY,GAAG,OAAO,CAAC,QAAQ,CAAC;AAChD,MAAM,MAAM,QAAQ,GAAG;AACvB,QAAQ,IAAI,EAAE,YAAY;AAC1B,QAAQ,MAAM,EAAE,OAAO,CAAC,MAAM;AAC9B,QAAQ,UAAU,EAAE,OAAO,CAAC,UAAU;AACtC,QAAQ,OAAO,EAAE,eAAe;AAChC,QAAQ,MAAM;AACd,QAAQ,OAAO;AACf,OAAO,CAAC;AACR;AACA,MAAM,MAAM,CAAC,SAAS,QAAQ,CAAC,KAAK,EAAE;AACtC,QAAQ,OAAO,CAAC,KAAK,CAAC,CAAC;AACvB,QAAQ,IAAI,EAAE,CAAC;AACf,OAAO,EAAE,SAAS,OAAO,CAAC,GAAG,EAAE;AAC/B,QAAQ,MAAM,CAAC,GAAG,CAAC,CAAC;AACpB,QAAQ,IAAI,EAAE,CAAC;AACf,OAAO,EAAE,QAAQ,CAAC,CAAC;AACnB;AACA;AACA,MAAM,OAAO,GAAG,IAAI,CAAC;AACrB,KAAK;AACL;AACA,IAAI,IAAI,WAAW,IAAI,OAAO,EAAE;AAChC;AACA,MAAM,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC;AACpC,KAAK,MAAM;AACX;AACA,MAAM,OAAO,CAAC,kBAAkB,GAAG,SAAS,UAAU,GAAG;AACzD,QAAQ,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,UAAU,KAAK,CAAC,EAAE;AAClD,UAAU,OAAO;AACjB,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,QAAQ,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE;AAC1G,UAAU,OAAO;AACjB,SAAS;AACT;AACA;AACA,QAAQ,UAAU,CAAC,SAAS,CAAC,CAAC;AAC9B,OAAO,CAAC;AACR,KAAK;AACL;AACA;AACA,IAAI,OAAO,CAAC,OAAO,GAAG,SAAS,WAAW,GAAG;AAC7C,MAAM,IAAI,CAAC,OAAO,EAAE;AACpB,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,MAAM,CAAC,IAAI,UAAU,CAAC,iBAAiB,EAAE,UAAU,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AAC1F;AACA;AACA,MAAM,OAAO,GAAG,IAAI,CAAC;AACrB,KAAK,CAAC;AACN;AACA;AACA,IAAI,OAAO,CAAC,OAAO,GAAG,SAAS,WAAW,GAAG;AAC7C;AACA;AACA,MAAM,MAAM,CAAC,IAAI,UAAU,CAAC,eAAe,EAAE,UAAU,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AACvF;AACA;AACA,MAAM,OAAO,GAAG,IAAI,CAAC;AACrB,KAAK,CAAC;AACN;AACA;AACA,IAAI,OAAO,CAAC,SAAS,GAAG,SAAS,aAAa,GAAG;AACjD,MAAM,IAAI,mBAAmB,GAAG,OAAO,CAAC,OAAO,GAAG,aAAa,GAAG,OAAO,CAAC,OAAO,GAAG,aAAa,GAAG,kBAAkB,CAAC;AACvH,MAAM,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,oBAAoB,CAAC;AACxE,MAAM,IAAI,OAAO,CAAC,mBAAmB,EAAE;AACvC,QAAQ,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,CAAC;AAC1D,OAAO;AACP,MAAM,MAAM,CAAC,IAAI,UAAU;AAC3B,QAAQ,mBAAmB;AAC3B,QAAQ,YAAY,CAAC,mBAAmB,GAAG,UAAU,CAAC,SAAS,GAAG,UAAU,CAAC,YAAY;AACzF,QAAQ,MAAM;AACd,QAAQ,OAAO,CAAC,CAAC,CAAC;AAClB;AACA;AACA,MAAM,OAAO,GAAG,IAAI,CAAC;AACrB,KAAK,CAAC;AACN;AACA;AACA,IAAI,WAAW,KAAK,SAAS,IAAI,cAAc,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;AACrE;AACA;AACA,IAAI,IAAI,kBAAkB,IAAI,OAAO,EAAE;AACvC,MAAMR,OAAK,CAAC,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,EAAE,SAAS,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE;AACjF,QAAQ,OAAO,CAAC,gBAAgB,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAC3C,OAAO,CAAC,CAAC;AACT,KAAK;AACL;AACA;AACA,IAAI,IAAI,CAACA,OAAK,CAAC,WAAW,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE;AACrD,MAAM,OAAO,CAAC,eAAe,GAAG,CAAC,CAAC,OAAO,CAAC,eAAe,CAAC;AAC1D,KAAK;AACL;AACA;AACA,IAAI,IAAI,YAAY,IAAI,YAAY,KAAK,MAAM,EAAE;AACjD,MAAM,OAAO,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;AAClD,KAAK;AACL;AACA;AACA,IAAI,IAAI,kBAAkB,EAAE;AAC5B,MAAM,CAAC,CAAC,iBAAiB,EAAE,aAAa,CAAC,GAAG,oBAAoB,CAAC,kBAAkB,EAAE,IAAI,CAAC,EAAE;AAC5F,MAAM,OAAO,CAAC,gBAAgB,CAAC,UAAU,EAAE,iBAAiB,CAAC,CAAC;AAC9D,KAAK;AACL;AACA;AACA,IAAI,IAAI,gBAAgB,IAAI,OAAO,CAAC,MAAM,EAAE;AAC5C,MAAM,CAAC,CAAC,eAAe,EAAE,WAAW,CAAC,GAAG,oBAAoB,CAAC,gBAAgB,CAAC,EAAE;AAChF;AACA,MAAM,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;AACnE;AACA,MAAM,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;AAC9D,KAAK;AACL;AACA,IAAI,IAAI,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,MAAM,EAAE;AAC/C;AACA;AACA,MAAM,UAAU,GAAG,MAAM,IAAI;AAC7B,QAAQ,IAAI,CAAC,OAAO,EAAE;AACtB,UAAU,OAAO;AACjB,SAAS;AACT,QAAQ,MAAM,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,IAAI,GAAG,IAAI,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC;AAC3F,QAAQ,OAAO,CAAC,KAAK,EAAE,CAAC;AACxB,QAAQ,OAAO,GAAG,IAAI,CAAC;AACvB,OAAO,CAAC;AACR;AACA,MAAM,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;AACvE,MAAM,IAAI,OAAO,CAAC,MAAM,EAAE;AAC1B,QAAQ,OAAO,CAAC,MAAM,CAAC,OAAO,GAAG,UAAU,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;AACrG,OAAO;AACP,KAAK;AACL;AACA,IAAI,MAAM,QAAQ,GAAG,aAAa,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AAChD;AACA,IAAI,IAAI,QAAQ,IAAI,QAAQ,CAAC,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE;AACjE,MAAM,MAAM,CAAC,IAAI,UAAU,CAAC,uBAAuB,GAAG,QAAQ,GAAG,GAAG,EAAE,UAAU,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC,CAAC;AAC3G,MAAM,OAAO;AACb,KAAK;AACL;AACA;AACA;AACA,IAAI,OAAO,CAAC,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,CAAC;AACtC,GAAG,CAAC,CAAC;AACL;;AChMA,MAAM,cAAc,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK;AAC7C,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,OAAO,GAAG,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;AACtE;AACA,EAAE,IAAI,OAAO,IAAI,MAAM,EAAE;AACzB,IAAI,IAAI,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;AAC3C;AACA,IAAI,IAAI,OAAO,CAAC;AAChB;AACA,IAAI,MAAM,OAAO,GAAG,UAAU,MAAM,EAAE;AACtC,MAAM,IAAI,CAAC,OAAO,EAAE;AACpB,QAAQ,OAAO,GAAG,IAAI,CAAC;AACvB,QAAQ,WAAW,EAAE,CAAC;AACtB,QAAQ,MAAM,GAAG,GAAG,MAAM,YAAY,KAAK,GAAG,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;AACnE,QAAQ,UAAU,CAAC,KAAK,CAAC,GAAG,YAAY,UAAU,GAAG,GAAG,GAAG,IAAI,aAAa,CAAC,GAAG,YAAY,KAAK,GAAG,GAAG,CAAC,OAAO,GAAG,GAAG,CAAC,CAAC,CAAC;AACxH,OAAO;AACP,MAAK;AACL;AACA,IAAI,IAAI,KAAK,GAAG,OAAO,IAAI,UAAU,CAAC,MAAM;AAC5C,MAAM,KAAK,GAAG,IAAI,CAAC;AACnB,MAAM,OAAO,CAAC,IAAI,UAAU,CAAC,CAAC,QAAQ,EAAE,OAAO,CAAC,eAAe,CAAC,EAAE,UAAU,CAAC,SAAS,CAAC,EAAC;AACxF,KAAK,EAAE,OAAO,EAAC;AACf;AACA,IAAI,MAAM,WAAW,GAAG,MAAM;AAC9B,MAAM,IAAI,OAAO,EAAE;AACnB,QAAQ,KAAK,IAAI,YAAY,CAAC,KAAK,CAAC,CAAC;AACrC,QAAQ,KAAK,GAAG,IAAI,CAAC;AACrB,QAAQ,OAAO,CAAC,OAAO,CAAC,MAAM,IAAI;AAClC,UAAU,MAAM,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAC1G,SAAS,CAAC,CAAC;AACX,QAAQ,OAAO,GAAG,IAAI,CAAC;AACvB,OAAO;AACP,MAAK;AACL;AACA,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;AAC3E;AACA,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,UAAU,CAAC;AAChC;AACA,IAAI,MAAM,CAAC,WAAW,GAAG,MAAMA,OAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AACvD;AACA,IAAI,OAAO,MAAM,CAAC;AAClB,GAAG;AACH,EAAC;AACD;AACA,yBAAe,cAAc;;AC9CtB,MAAM,WAAW,GAAG,WAAW,KAAK,EAAE,SAAS,EAAE;AACxD,EAAE,IAAI,GAAG,GAAG,KAAK,CAAC,UAAU,CAAC;AAC7B;AACA,EAAE,IAAI,CAAC,SAAS,IAAI,GAAG,GAAG,SAAS,EAAE;AACrC,IAAI,MAAM,KAAK,CAAC;AAChB,IAAI,OAAO;AACX,GAAG;AACH;AACA,EAAE,IAAI,GAAG,GAAG,CAAC,CAAC;AACd,EAAE,IAAI,GAAG,CAAC;AACV;AACA,EAAE,OAAO,GAAG,GAAG,GAAG,EAAE;AACpB,IAAI,GAAG,GAAG,GAAG,GAAG,SAAS,CAAC;AAC1B,IAAI,MAAM,KAAK,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAChC,IAAI,GAAG,GAAG,GAAG,CAAC;AACd,GAAG;AACH,EAAC;AACD;AACO,MAAM,SAAS,GAAG,iBAAiB,QAAQ,EAAE,SAAS,EAAE;AAC/D,EAAE,WAAW,MAAM,KAAK,IAAI,UAAU,CAAC,QAAQ,CAAC,EAAE;AAClD,IAAI,OAAO,WAAW,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AACzC,GAAG;AACH,EAAC;AACD;AACA,MAAM,UAAU,GAAG,iBAAiB,MAAM,EAAE;AAC5C,EAAE,IAAI,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE;AACpC,IAAI,OAAO,MAAM,CAAC;AAClB,IAAI,OAAO;AACX,GAAG;AACH;AACA,EAAE,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;AACpC,EAAE,IAAI;AACN,IAAI,SAAS;AACb,MAAM,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;AAChD,MAAM,IAAI,IAAI,EAAE;AAChB,QAAQ,MAAM;AACd,OAAO;AACP,MAAM,MAAM,KAAK,CAAC;AAClB,KAAK;AACL,GAAG,SAAS;AACZ,IAAI,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC;AAC1B,GAAG;AACH,EAAC;AACD;AACO,MAAM,WAAW,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,KAAK;AACxE,EAAE,MAAM,QAAQ,GAAG,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAChD;AACA,EAAE,IAAI,KAAK,GAAG,CAAC,CAAC;AAChB,EAAE,IAAI,IAAI,CAAC;AACX,EAAE,IAAI,SAAS,GAAG,CAAC,CAAC,KAAK;AACzB,IAAI,IAAI,CAAC,IAAI,EAAE;AACf,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,MAAM,QAAQ,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC9B,KAAK;AACL,IAAG;AACH;AACA,EAAE,OAAO,IAAI,cAAc,CAAC;AAC5B,IAAI,MAAM,IAAI,CAAC,UAAU,EAAE;AAC3B,MAAM,IAAI;AACV,QAAQ,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;AACpD;AACA,QAAQ,IAAI,IAAI,EAAE;AAClB,SAAS,SAAS,EAAE,CAAC;AACrB,UAAU,UAAU,CAAC,KAAK,EAAE,CAAC;AAC7B,UAAU,OAAO;AACjB,SAAS;AACT;AACA,QAAQ,IAAI,GAAG,GAAG,KAAK,CAAC,UAAU,CAAC;AACnC,QAAQ,IAAI,UAAU,EAAE;AACxB,UAAU,IAAI,WAAW,GAAG,KAAK,IAAI,GAAG,CAAC;AACzC,UAAU,UAAU,CAAC,WAAW,CAAC,CAAC;AAClC,SAAS;AACT,QAAQ,UAAU,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;AAClD,OAAO,CAAC,OAAO,GAAG,EAAE;AACpB,QAAQ,SAAS,CAAC,GAAG,CAAC,CAAC;AACvB,QAAQ,MAAM,GAAG,CAAC;AAClB,OAAO;AACP,KAAK;AACL,IAAI,MAAM,CAAC,MAAM,EAAE;AACnB,MAAM,SAAS,CAAC,MAAM,CAAC,CAAC;AACxB,MAAM,OAAO,QAAQ,CAAC,MAAM,EAAE,CAAC;AAC/B,KAAK;AACL,GAAG,EAAE;AACL,IAAI,aAAa,EAAE,CAAC;AACpB,GAAG,CAAC;AACJ;;AC5EA,MAAM,gBAAgB,GAAG,OAAO,KAAK,KAAK,UAAU,IAAI,OAAO,OAAO,KAAK,UAAU,IAAI,OAAO,QAAQ,KAAK,UAAU,CAAC;AACxH,MAAM,yBAAyB,GAAG,gBAAgB,IAAI,OAAO,cAAc,KAAK,UAAU,CAAC;AAC3F;AACA;AACA,MAAM,UAAU,GAAG,gBAAgB,KAAK,OAAO,WAAW,KAAK,UAAU;AACzE,IAAI,CAAC,CAAC,OAAO,KAAK,CAAC,GAAG,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,IAAI,WAAW,EAAE,CAAC;AAClE,IAAI,OAAO,GAAG,KAAK,IAAI,UAAU,CAAC,MAAM,IAAI,QAAQ,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;AACxE,CAAC,CAAC;AACF;AACA,MAAM,IAAI,GAAG,CAAC,EAAE,EAAE,GAAG,IAAI,KAAK;AAC9B,EAAE,IAAI;AACN,IAAI,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;AACzB,GAAG,CAAC,OAAO,CAAC,EAAE;AACd,IAAI,OAAO,KAAK;AAChB,GAAG;AACH,EAAC;AACD;AACA,MAAM,qBAAqB,GAAG,yBAAyB,IAAI,IAAI,CAAC,MAAM;AACtE,EAAE,IAAI,cAAc,GAAG,KAAK,CAAC;AAC7B;AACA,EAAE,MAAM,cAAc,GAAG,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,EAAE;AACtD,IAAI,IAAI,EAAE,IAAI,cAAc,EAAE;AAC9B,IAAI,MAAM,EAAE,MAAM;AAClB,IAAI,IAAI,MAAM,GAAG;AACjB,MAAM,cAAc,GAAG,IAAI,CAAC;AAC5B,MAAM,OAAO,MAAM,CAAC;AACpB,KAAK;AACL,GAAG,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;AACjC;AACA,EAAE,OAAO,cAAc,IAAI,CAAC,cAAc,CAAC;AAC3C,CAAC,CAAC,CAAC;AACH;AACA,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,CAAC;AACrC;AACA,MAAM,sBAAsB,GAAG,yBAAyB;AACxD,EAAE,IAAI,CAAC,MAAMA,OAAK,CAAC,gBAAgB,CAAC,IAAI,QAAQ,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;AAC5D;AACA;AACA,MAAM,SAAS,GAAG;AAClB,EAAE,MAAM,EAAE,sBAAsB,KAAK,CAAC,GAAG,KAAK,GAAG,CAAC,IAAI,CAAC;AACvD,CAAC,CAAC;AACF;AACA,gBAAgB,KAAK,CAAC,CAAC,GAAG,KAAK;AAC/B,EAAE,CAAC,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,IAAI;AACxE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,SAAS,CAAC,IAAI,CAAC,GAAGA,OAAK,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,IAAI,CAAC,EAAE;AAC7F,MAAM,CAAC,CAAC,EAAE,MAAM,KAAK;AACrB,QAAQ,MAAM,IAAI,UAAU,CAAC,CAAC,eAAe,EAAE,IAAI,CAAC,kBAAkB,CAAC,EAAE,UAAU,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC;AAC7G,OAAO,EAAC;AACR,GAAG,CAAC,CAAC;AACL,CAAC,EAAE,IAAI,QAAQ,CAAC,CAAC,CAAC;AAClB;AACA,MAAM,aAAa,GAAG,OAAO,IAAI,KAAK;AACtC,EAAE,IAAI,IAAI,IAAI,IAAI,EAAE;AACpB,IAAI,OAAO,CAAC,CAAC;AACb,GAAG;AACH;AACA,EAAE,GAAGA,OAAK,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;AACzB,IAAI,OAAO,IAAI,CAAC,IAAI,CAAC;AACrB,GAAG;AACH;AACA,EAAE,GAAGA,OAAK,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE;AACtC,IAAI,MAAM,QAAQ,GAAG,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,EAAE;AAClD,MAAM,MAAM,EAAE,MAAM;AACpB,MAAM,IAAI;AACV,KAAK,CAAC,CAAC;AACP,IAAI,OAAO,CAAC,MAAM,QAAQ,CAAC,WAAW,EAAE,EAAE,UAAU,CAAC;AACrD,GAAG;AACH;AACA,EAAE,GAAGA,OAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,IAAIA,OAAK,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE;AACjE,IAAI,OAAO,IAAI,CAAC,UAAU,CAAC;AAC3B,GAAG;AACH;AACA,EAAE,GAAGA,OAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE;AACpC,IAAI,IAAI,GAAG,IAAI,GAAG,EAAE,CAAC;AACrB,GAAG;AACH;AACA,EAAE,GAAGA,OAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;AAC3B,IAAI,OAAO,CAAC,MAAM,UAAU,CAAC,IAAI,CAAC,EAAE,UAAU,CAAC;AAC/C,GAAG;AACH,EAAC;AACD;AACA,MAAM,iBAAiB,GAAG,OAAO,OAAO,EAAE,IAAI,KAAK;AACnD,EAAE,MAAM,MAAM,GAAGA,OAAK,CAAC,cAAc,CAAC,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;AAClE;AACA,EAAE,OAAO,MAAM,IAAI,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC;AACvD,EAAC;AACD;AACA,qBAAe,gBAAgB,KAAK,OAAO,MAAM,KAAK;AACtD,EAAE,IAAI;AACN,IAAI,GAAG;AACP,IAAI,MAAM;AACV,IAAI,IAAI;AACR,IAAI,MAAM;AACV,IAAI,WAAW;AACf,IAAI,OAAO;AACX,IAAI,kBAAkB;AACtB,IAAI,gBAAgB;AACpB,IAAI,YAAY;AAChB,IAAI,OAAO;AACX,IAAI,eAAe,GAAG,aAAa;AACnC,IAAI,YAAY;AAChB,GAAG,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;AAC5B;AACA,EAAE,YAAY,GAAG,YAAY,GAAG,CAAC,YAAY,GAAG,EAAE,EAAE,WAAW,EAAE,GAAG,MAAM,CAAC;AAC3E;AACA,EAAE,IAAI,cAAc,GAAGuB,gBAAc,CAAC,CAAC,MAAM,EAAE,WAAW,IAAI,WAAW,CAAC,aAAa,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC;AACrG;AACA,EAAE,IAAI,OAAO,CAAC;AACd;AACA,EAAE,MAAM,WAAW,GAAG,cAAc,IAAI,cAAc,CAAC,WAAW,KAAK,MAAM;AAC7E,MAAM,cAAc,CAAC,WAAW,EAAE,CAAC;AACnC,GAAG,CAAC,CAAC;AACL;AACA,EAAE,IAAI,oBAAoB,CAAC;AAC3B;AACA,EAAE,IAAI;AACN,IAAI;AACJ,MAAM,gBAAgB,IAAI,qBAAqB,IAAI,MAAM,KAAK,KAAK,IAAI,MAAM,KAAK,MAAM;AACxF,MAAM,CAAC,oBAAoB,GAAG,MAAM,iBAAiB,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC;AAC3E,MAAM;AACN,MAAM,IAAI,QAAQ,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE;AACtC,QAAQ,MAAM,EAAE,MAAM;AACtB,QAAQ,IAAI,EAAE,IAAI;AAClB,QAAQ,MAAM,EAAE,MAAM;AACtB,OAAO,CAAC,CAAC;AACT;AACA,MAAM,IAAI,iBAAiB,CAAC;AAC5B;AACA,MAAM,IAAIvB,OAAK,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,iBAAiB,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,EAAE;AAChG,QAAQ,OAAO,CAAC,cAAc,CAAC,iBAAiB,EAAC;AACjD,OAAO;AACP;AACA,MAAM,IAAI,QAAQ,CAAC,IAAI,EAAE;AACzB,QAAQ,MAAM,CAAC,UAAU,EAAE,KAAK,CAAC,GAAG,sBAAsB;AAC1D,UAAU,oBAAoB;AAC9B,UAAU,oBAAoB,CAAC,cAAc,CAAC,gBAAgB,CAAC,CAAC;AAChE,SAAS,CAAC;AACV;AACA,QAAQ,IAAI,GAAG,WAAW,CAAC,QAAQ,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;AACjF,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAI,CAACA,OAAK,CAAC,QAAQ,CAAC,eAAe,CAAC,EAAE;AAC1C,MAAM,eAAe,GAAG,eAAe,GAAG,SAAS,GAAG,MAAM,CAAC;AAC7D,KAAK;AACL;AACA;AACA;AACA,IAAI,MAAM,sBAAsB,GAAG,aAAa,IAAI,OAAO,CAAC,SAAS,CAAC;AACtE,IAAI,OAAO,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE;AAC/B,MAAM,GAAG,YAAY;AACrB,MAAM,MAAM,EAAE,cAAc;AAC5B,MAAM,MAAM,EAAE,MAAM,CAAC,WAAW,EAAE;AAClC,MAAM,OAAO,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC,MAAM,EAAE;AAC3C,MAAM,IAAI,EAAE,IAAI;AAChB,MAAM,MAAM,EAAE,MAAM;AACpB,MAAM,WAAW,EAAE,sBAAsB,GAAG,eAAe,GAAG,SAAS;AACvE,KAAK,CAAC,CAAC;AACP;AACA,IAAI,IAAI,QAAQ,GAAG,MAAM,KAAK,CAAC,OAAO,CAAC,CAAC;AACxC;AACA,IAAI,MAAM,gBAAgB,GAAG,sBAAsB,KAAK,YAAY,KAAK,QAAQ,IAAI,YAAY,KAAK,UAAU,CAAC,CAAC;AAClH;AACA,IAAI,IAAI,sBAAsB,KAAK,kBAAkB,KAAK,gBAAgB,IAAI,WAAW,CAAC,CAAC,EAAE;AAC7F,MAAM,MAAM,OAAO,GAAG,EAAE,CAAC;AACzB;AACA,MAAM,CAAC,QAAQ,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,IAAI;AAC1D,QAAQ,OAAO,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;AACvC,OAAO,CAAC,CAAC;AACT;AACA,MAAM,MAAM,qBAAqB,GAAGA,OAAK,CAAC,cAAc,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC,CAAC;AACjG;AACA,MAAM,MAAM,CAAC,UAAU,EAAE,KAAK,CAAC,GAAG,kBAAkB,IAAI,sBAAsB;AAC9E,QAAQ,qBAAqB;AAC7B,QAAQ,oBAAoB,CAAC,cAAc,CAAC,kBAAkB,CAAC,EAAE,IAAI,CAAC;AACtE,OAAO,IAAI,EAAE,CAAC;AACd;AACA,MAAM,QAAQ,GAAG,IAAI,QAAQ;AAC7B,QAAQ,WAAW,CAAC,QAAQ,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,MAAM;AACzE,UAAU,KAAK,IAAI,KAAK,EAAE,CAAC;AAC3B,UAAU,WAAW,IAAI,WAAW,EAAE,CAAC;AACvC,SAAS,CAAC;AACV,QAAQ,OAAO;AACf,OAAO,CAAC;AACR,KAAK;AACL;AACA,IAAI,YAAY,GAAG,YAAY,IAAI,MAAM,CAAC;AAC1C;AACA,IAAI,IAAI,YAAY,GAAG,MAAM,SAAS,CAACA,OAAK,CAAC,OAAO,CAAC,SAAS,EAAE,YAAY,CAAC,IAAI,MAAM,CAAC,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AAC3G;AACA,IAAI,CAAC,gBAAgB,IAAI,WAAW,IAAI,WAAW,EAAE,CAAC;AACtD;AACA,IAAI,OAAO,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK;AAClD,MAAM,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE;AAC9B,QAAQ,IAAI,EAAE,YAAY;AAC1B,QAAQ,OAAO,EAAEQ,cAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;AACpD,QAAQ,MAAM,EAAE,QAAQ,CAAC,MAAM;AAC/B,QAAQ,UAAU,EAAE,QAAQ,CAAC,UAAU;AACvC,QAAQ,MAAM;AACd,QAAQ,OAAO;AACf,OAAO,EAAC;AACR,KAAK,CAAC;AACN,GAAG,CAAC,OAAO,GAAG,EAAE;AAChB,IAAI,WAAW,IAAI,WAAW,EAAE,CAAC;AACjC;AACA,IAAI,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,WAAW,IAAI,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE;AACvE,MAAM,MAAM,MAAM,CAAC,MAAM;AACzB,QAAQ,IAAI,UAAU,CAAC,eAAe,EAAE,UAAU,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC;AAChF,QAAQ;AACR,UAAU,KAAK,EAAE,GAAG,CAAC,KAAK,IAAI,GAAG;AACjC,SAAS;AACT,OAAO;AACP,KAAK;AACL;AACA,IAAI,MAAM,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACjE,GAAG;AACH,CAAC,CAAC;;AC5NF,MAAM,aAAa,GAAG;AACtB,EAAE,IAAI,EAAE,WAAW;AACnB,EAAE,GAAG,EAAE,UAAU;AACjB,EAAE,KAAK,EAAE,YAAY;AACrB,EAAC;AACD;AACAR,OAAK,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,EAAE,EAAE,KAAK,KAAK;AAC5C,EAAE,IAAI,EAAE,EAAE;AACV,IAAI,IAAI;AACR,MAAM,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AACjD,KAAK,CAAC,OAAO,CAAC,EAAE;AAChB;AACA,KAAK;AACL,IAAI,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,aAAa,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AACtD,GAAG;AACH,CAAC,CAAC,CAAC;AACH;AACA,MAAM,YAAY,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;AAC/C;AACA,MAAM,gBAAgB,GAAG,CAAC,OAAO,KAAKA,OAAK,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,CAAC;AACzG;AACA,iBAAe;AACf,EAAE,UAAU,EAAE,CAAC,QAAQ,KAAK;AAC5B,IAAI,QAAQ,GAAGA,OAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,QAAQ,GAAG,CAAC,QAAQ,CAAC,CAAC;AAC/D;AACA,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC;AAC9B,IAAI,IAAI,aAAa,CAAC;AACtB,IAAI,IAAI,OAAO,CAAC;AAChB;AACA,IAAI,MAAM,eAAe,GAAG,EAAE,CAAC;AAC/B;AACA,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC,EAAE,EAAE;AACrC,MAAM,aAAa,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;AAClC,MAAM,IAAI,EAAE,CAAC;AACb;AACA,MAAM,OAAO,GAAG,aAAa,CAAC;AAC9B;AACA,MAAM,IAAI,CAAC,gBAAgB,CAAC,aAAa,CAAC,EAAE;AAC5C,QAAQ,OAAO,GAAG,aAAa,CAAC,CAAC,EAAE,GAAG,MAAM,CAAC,aAAa,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;AAC5E;AACA,QAAQ,IAAI,OAAO,KAAK,SAAS,EAAE;AACnC,UAAU,MAAM,IAAI,UAAU,CAAC,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;AAC1D,SAAS;AACT,OAAO;AACP;AACA,MAAM,IAAI,OAAO,EAAE;AACnB,QAAQ,MAAM;AACd,OAAO;AACP;AACA,MAAM,eAAe,CAAC,EAAE,IAAI,GAAG,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;AAC/C,KAAK;AACL;AACA,IAAI,IAAI,CAAC,OAAO,EAAE;AAClB;AACA,MAAM,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC;AACrD,SAAS,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC;AAC9C,WAAW,KAAK,KAAK,KAAK,GAAG,qCAAqC,GAAG,+BAA+B,CAAC;AACrG,SAAS,CAAC;AACV;AACA,MAAM,IAAI,CAAC,GAAG,MAAM;AACpB,SAAS,OAAO,CAAC,MAAM,GAAG,CAAC,GAAG,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AACjH,QAAQ,yBAAyB,CAAC;AAClC;AACA,MAAM,MAAM,IAAI,UAAU;AAC1B,QAAQ,CAAC,qDAAqD,CAAC,GAAG,CAAC;AACnE,QAAQ,iBAAiB;AACzB,OAAO,CAAC;AACR,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC;AACnB,GAAG;AACH,EAAE,QAAQ,EAAE,aAAa;AACzB;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,4BAA4B,CAAC,MAAM,EAAE;AAC9C,EAAE,IAAI,MAAM,CAAC,WAAW,EAAE;AAC1B,IAAI,MAAM,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC;AAC1C,GAAG;AACH;AACA,EAAE,IAAI,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE;AAC9C,IAAI,MAAM,IAAI,aAAa,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC1C,GAAG;AACH,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,eAAe,CAAC,MAAM,EAAE;AAChD,EAAE,4BAA4B,CAAC,MAAM,CAAC,CAAC;AACvC;AACA,EAAE,MAAM,CAAC,OAAO,GAAGQ,cAAY,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AACrD;AACA;AACA,EAAE,MAAM,CAAC,IAAI,GAAG,aAAa,CAAC,IAAI;AAClC,IAAI,MAAM;AACV,IAAI,MAAM,CAAC,gBAAgB;AAC3B,GAAG,CAAC;AACJ;AACA,EAAE,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE;AAC9D,IAAI,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,mCAAmC,EAAE,KAAK,CAAC,CAAC;AAC9E,GAAG;AACH;AACA,EAAE,MAAM,OAAO,GAAG,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,OAAO,IAAID,UAAQ,CAAC,OAAO,CAAC,CAAC;AAC1E;AACA,EAAE,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,SAAS,mBAAmB,CAAC,QAAQ,EAAE;AACrE,IAAI,4BAA4B,CAAC,MAAM,CAAC,CAAC;AACzC;AACA;AACA,IAAI,QAAQ,CAAC,IAAI,GAAG,aAAa,CAAC,IAAI;AACtC,MAAM,MAAM;AACZ,MAAM,MAAM,CAAC,iBAAiB;AAC9B,MAAM,QAAQ;AACd,KAAK,CAAC;AACN;AACA,IAAI,QAAQ,CAAC,OAAO,GAAGC,cAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAC3D;AACA,IAAI,OAAO,QAAQ,CAAC;AACpB,GAAG,EAAE,SAAS,kBAAkB,CAAC,MAAM,EAAE;AACzC,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;AAC3B,MAAM,4BAA4B,CAAC,MAAM,CAAC,CAAC;AAC3C;AACA;AACA,MAAM,IAAI,MAAM,IAAI,MAAM,CAAC,QAAQ,EAAE;AACrC,QAAQ,MAAM,CAAC,QAAQ,CAAC,IAAI,GAAG,aAAa,CAAC,IAAI;AACjD,UAAU,MAAM;AAChB,UAAU,MAAM,CAAC,iBAAiB;AAClC,UAAU,MAAM,CAAC,QAAQ;AACzB,SAAS,CAAC;AACV,QAAQ,MAAM,CAAC,QAAQ,CAAC,OAAO,GAAGA,cAAY,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAC7E,OAAO;AACP,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAClC,GAAG,CAAC,CAAC;AACL;;AC3EA,MAAMgB,YAAU,GAAG,EAAE,CAAC;AACtB;AACA;AACA,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC,KAAK;AACrF,EAAEA,YAAU,CAAC,IAAI,CAAC,GAAG,SAAS,SAAS,CAAC,KAAK,EAAE;AAC/C,IAAI,OAAO,OAAO,KAAK,KAAK,IAAI,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC;AACtE,GAAG,CAAC;AACJ,CAAC,CAAC,CAAC;AACH;AACA,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAA,YAAU,CAAC,YAAY,GAAG,SAAS,YAAY,CAAC,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE;AAC7E,EAAE,SAAS,aAAa,CAAC,GAAG,EAAE,IAAI,EAAE;AACpC,IAAI,OAAO,UAAU,GAAG,OAAO,GAAG,0BAA0B,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,IAAI,OAAO,GAAG,IAAI,GAAG,OAAO,GAAG,EAAE,CAAC,CAAC;AACnH,GAAG;AACH;AACA;AACA,EAAE,OAAO,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,KAAK;AAC/B,IAAI,IAAI,SAAS,KAAK,KAAK,EAAE;AAC7B,MAAM,MAAM,IAAI,UAAU;AAC1B,QAAQ,aAAa,CAAC,GAAG,EAAE,mBAAmB,IAAI,OAAO,GAAG,MAAM,GAAG,OAAO,GAAG,EAAE,CAAC,CAAC;AACnF,QAAQ,UAAU,CAAC,cAAc;AACjC,OAAO,CAAC;AACR,KAAK;AACL;AACA,IAAI,IAAI,OAAO,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAE;AAC7C,MAAM,kBAAkB,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;AACrC;AACA,MAAM,OAAO,CAAC,IAAI;AAClB,QAAQ,aAAa;AACrB,UAAU,GAAG;AACb,UAAU,8BAA8B,GAAG,OAAO,GAAG,yCAAyC;AAC9F,SAAS;AACT,OAAO,CAAC;AACR,KAAK;AACL;AACA,IAAI,OAAO,SAAS,GAAG,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC;AAC1D,GAAG,CAAC;AACJ,CAAC,CAAC;AACF;AACAA,YAAU,CAAC,QAAQ,GAAG,SAAS,QAAQ,CAAC,eAAe,EAAE;AACzD,EAAE,OAAO,CAAC,KAAK,EAAE,GAAG,KAAK;AACzB;AACA,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,CAAC,4BAA4B,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC;AACzE,IAAI,OAAO,IAAI,CAAC;AAChB,GAAG;AACH,CAAC,CAAC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE;AACtD,EAAE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;AACnC,IAAI,MAAM,IAAI,UAAU,CAAC,2BAA2B,EAAE,UAAU,CAAC,oBAAoB,CAAC,CAAC;AACvF,GAAG;AACH,EAAE,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACpC,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;AACtB,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AAClB,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AACxB,IAAI,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AAClC,IAAI,IAAI,SAAS,EAAE;AACnB,MAAM,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;AACjC,MAAM,MAAM,MAAM,GAAG,KAAK,KAAK,SAAS,IAAI,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;AAC3E,MAAM,IAAI,MAAM,KAAK,IAAI,EAAE;AAC3B,QAAQ,MAAM,IAAI,UAAU,CAAC,SAAS,GAAG,GAAG,GAAG,WAAW,GAAG,MAAM,EAAE,UAAU,CAAC,oBAAoB,CAAC,CAAC;AACtG,OAAO;AACP,MAAM,SAAS;AACf,KAAK;AACL,IAAI,IAAI,YAAY,KAAK,IAAI,EAAE;AAC/B,MAAM,MAAM,IAAI,UAAU,CAAC,iBAAiB,GAAG,GAAG,EAAE,UAAU,CAAC,cAAc,CAAC,CAAC;AAC/E,KAAK;AACL,GAAG;AACH,CAAC;AACD;AACA,kBAAe;AACf,EAAE,aAAa;AACf,cAAEA,YAAU;AACZ,CAAC;;ACvFD,MAAM,UAAU,GAAG,SAAS,CAAC,UAAU,CAAC;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,KAAK,CAAC;AACZ,EAAE,WAAW,CAAC,cAAc,EAAE;AAC9B,IAAI,IAAI,CAAC,QAAQ,GAAG,cAAc,CAAC;AACnC,IAAI,IAAI,CAAC,YAAY,GAAG;AACxB,MAAM,OAAO,EAAE,IAAIC,oBAAkB,EAAE;AACvC,MAAM,QAAQ,EAAE,IAAIA,oBAAkB,EAAE;AACxC,KAAK,CAAC;AACN,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,MAAM,OAAO,CAAC,WAAW,EAAE,MAAM,EAAE;AACrC,IAAI,IAAI;AACR,MAAM,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;AACtD,KAAK,CAAC,OAAO,GAAG,EAAE;AAClB,MAAM,IAAI,GAAG,YAAY,KAAK,EAAE;AAChC,QAAQ,IAAI,KAAK,GAAG,EAAE,CAAC;AACvB;AACA,QAAQ,KAAK,CAAC,iBAAiB,GAAG,KAAK,CAAC,iBAAiB,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC,CAAC;AACzF;AACA;AACA,QAAQ,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC;AAC1E,QAAQ,IAAI;AACZ,UAAU,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE;AAC1B,YAAY,GAAG,CAAC,KAAK,GAAG,KAAK,CAAC;AAC9B;AACA,WAAW,MAAM,IAAI,KAAK,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,EAAE;AAC3F,YAAY,GAAG,CAAC,KAAK,IAAI,IAAI,GAAG,MAAK;AACrC,WAAW;AACX,SAAS,CAAC,OAAO,CAAC,EAAE;AACpB;AACA,SAAS;AACT,OAAO;AACP;AACA,MAAM,MAAM,GAAG,CAAC;AAChB,KAAK;AACL,GAAG;AACH;AACA,EAAE,QAAQ,CAAC,WAAW,EAAE,MAAM,EAAE;AAChC;AACA;AACA,IAAI,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;AACzC,MAAM,MAAM,GAAG,MAAM,IAAI,EAAE,CAAC;AAC5B,MAAM,MAAM,CAAC,GAAG,GAAG,WAAW,CAAC;AAC/B,KAAK,MAAM;AACX,MAAM,MAAM,GAAG,WAAW,IAAI,EAAE,CAAC;AACjC,KAAK;AACL;AACA,IAAI,MAAM,GAAG,WAAW,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AAChD;AACA,IAAI,MAAM,CAAC,YAAY,EAAE,gBAAgB,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC;AAC7D;AACA,IAAI,IAAI,YAAY,KAAK,SAAS,EAAE;AACpC,MAAM,SAAS,CAAC,aAAa,CAAC,YAAY,EAAE;AAC5C,QAAQ,iBAAiB,EAAE,UAAU,CAAC,YAAY,CAAC,UAAU,CAAC,OAAO,CAAC;AACtE,QAAQ,iBAAiB,EAAE,UAAU,CAAC,YAAY,CAAC,UAAU,CAAC,OAAO,CAAC;AACtE,QAAQ,mBAAmB,EAAE,UAAU,CAAC,YAAY,CAAC,UAAU,CAAC,OAAO,CAAC;AACxE,OAAO,EAAE,KAAK,CAAC,CAAC;AAChB,KAAK;AACL;AACA,IAAI,IAAI,gBAAgB,IAAI,IAAI,EAAE;AAClC,MAAM,IAAIzB,OAAK,CAAC,UAAU,CAAC,gBAAgB,CAAC,EAAE;AAC9C,QAAQ,MAAM,CAAC,gBAAgB,GAAG;AAClC,UAAU,SAAS,EAAE,gBAAgB;AACrC,UAAS;AACT,OAAO,MAAM;AACb,QAAQ,SAAS,CAAC,aAAa,CAAC,gBAAgB,EAAE;AAClD,UAAU,MAAM,EAAE,UAAU,CAAC,QAAQ;AACrC,UAAU,SAAS,EAAE,UAAU,CAAC,QAAQ;AACxC,SAAS,EAAE,IAAI,CAAC,CAAC;AACjB,OAAO;AACP,KAAK;AACL;AACA,IAAI,SAAS,CAAC,aAAa,CAAC,MAAM,EAAE;AACpC,MAAM,OAAO,EAAE,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC;AAC7C,MAAM,aAAa,EAAE,UAAU,CAAC,QAAQ,CAAC,eAAe,CAAC;AACzD,KAAK,EAAE,IAAI,CAAC,CAAC;AACb;AACA;AACA,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,IAAI,KAAK,EAAE,WAAW,EAAE,CAAC;AACnF;AACA;AACA,IAAI,IAAI,cAAc,GAAG,OAAO,IAAIA,OAAK,CAAC,KAAK;AAC/C,MAAM,OAAO,CAAC,MAAM;AACpB,MAAM,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC;AAC5B,KAAK,CAAC;AACN;AACA,IAAI,OAAO,IAAIA,OAAK,CAAC,OAAO;AAC5B,MAAM,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,CAAC;AACjE,MAAM,CAAC,MAAM,KAAK;AAClB,QAAQ,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC;AAC/B,OAAO;AACP,KAAK,CAAC;AACN;AACA,IAAI,MAAM,CAAC,OAAO,GAAGQ,cAAY,CAAC,MAAM,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;AAClE;AACA;AACA,IAAI,MAAM,uBAAuB,GAAG,EAAE,CAAC;AACvC,IAAI,IAAI,8BAA8B,GAAG,IAAI,CAAC;AAC9C,IAAI,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,0BAA0B,CAAC,WAAW,EAAE;AACvF,MAAM,IAAI,OAAO,WAAW,CAAC,OAAO,KAAK,UAAU,IAAI,WAAW,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,KAAK,EAAE;AAC9F,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,8BAA8B,GAAG,8BAA8B,IAAI,WAAW,CAAC,WAAW,CAAC;AACjG;AACA,MAAM,uBAAuB,CAAC,OAAO,CAAC,WAAW,CAAC,SAAS,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;AACnF,KAAK,CAAC,CAAC;AACP;AACA,IAAI,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACxC,IAAI,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,OAAO,CAAC,SAAS,wBAAwB,CAAC,WAAW,EAAE;AACtF,MAAM,wBAAwB,CAAC,IAAI,CAAC,WAAW,CAAC,SAAS,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;AACjF,KAAK,CAAC,CAAC;AACP;AACA,IAAI,IAAI,OAAO,CAAC;AAChB,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC;AACd,IAAI,IAAI,GAAG,CAAC;AACZ;AACA,IAAI,IAAI,CAAC,8BAA8B,EAAE;AACzC,MAAM,MAAM,KAAK,GAAG,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC,CAAC;AAC5D,MAAM,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,uBAAuB,CAAC,CAAC;AAC1D,MAAM,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,wBAAwB,CAAC,CAAC;AACxD,MAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC;AACzB;AACA,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AACxC;AACA,MAAM,OAAO,CAAC,GAAG,GAAG,EAAE;AACtB,QAAQ,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACvD,OAAO;AACP;AACA,MAAM,OAAO,OAAO,CAAC;AACrB,KAAK;AACL;AACA,IAAI,GAAG,GAAG,uBAAuB,CAAC,MAAM,CAAC;AACzC;AACA,IAAI,IAAI,SAAS,GAAG,MAAM,CAAC;AAC3B;AACA,IAAI,CAAC,GAAG,CAAC,CAAC;AACV;AACA,IAAI,OAAO,CAAC,GAAG,GAAG,EAAE;AACpB,MAAM,MAAM,WAAW,GAAG,uBAAuB,CAAC,CAAC,EAAE,CAAC,CAAC;AACvD,MAAM,MAAM,UAAU,GAAG,uBAAuB,CAAC,CAAC,EAAE,CAAC,CAAC;AACtD,MAAM,IAAI;AACV,QAAQ,SAAS,GAAG,WAAW,CAAC,SAAS,CAAC,CAAC;AAC3C,OAAO,CAAC,OAAO,KAAK,EAAE;AACtB,QAAQ,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;AACrC,QAAQ,MAAM;AACd,OAAO;AACP,KAAK;AACL;AACA,IAAI,IAAI;AACR,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;AACtD,KAAK,CAAC,OAAO,KAAK,EAAE;AACpB,MAAM,OAAO,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACnC,KAAK;AACL;AACA,IAAI,CAAC,GAAG,CAAC,CAAC;AACV,IAAI,GAAG,GAAG,wBAAwB,CAAC,MAAM,CAAC;AAC1C;AACA,IAAI,OAAO,CAAC,GAAG,GAAG,EAAE;AACpB,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC,EAAE,CAAC,EAAE,wBAAwB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAC3F,KAAK;AACL;AACA,IAAI,OAAO,OAAO,CAAC;AACnB,GAAG;AACH;AACA,EAAE,MAAM,CAAC,MAAM,EAAE;AACjB,IAAI,MAAM,GAAG,WAAW,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AAChD,IAAI,MAAM,QAAQ,GAAG,aAAa,CAAC,MAAM,CAAC,OAAO,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;AAC/D,IAAI,OAAO,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,gBAAgB,CAAC,CAAC;AACtE,GAAG;AACH,CAAC;AACD;AACA;AACAR,OAAK,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,SAAS,mBAAmB,CAAC,MAAM,EAAE;AACzF;AACA,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,SAAS,GAAG,EAAE,MAAM,EAAE;AAClD,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,MAAM,IAAI,EAAE,EAAE;AAClD,MAAM,MAAM;AACZ,MAAM,GAAG;AACT,MAAM,IAAI,EAAE,CAAC,MAAM,IAAI,EAAE,EAAE,IAAI;AAC/B,KAAK,CAAC,CAAC,CAAC;AACR,GAAG,CAAC;AACJ,CAAC,CAAC,CAAC;AACH;AACAA,OAAK,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,SAAS,qBAAqB,CAAC,MAAM,EAAE;AAC/E;AACA;AACA,EAAE,SAAS,kBAAkB,CAAC,MAAM,EAAE;AACtC,IAAI,OAAO,SAAS,UAAU,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE;AAClD,MAAM,OAAO,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,MAAM,IAAI,EAAE,EAAE;AACpD,QAAQ,MAAM;AACd,QAAQ,OAAO,EAAE,MAAM,GAAG;AAC1B,UAAU,cAAc,EAAE,qBAAqB;AAC/C,SAAS,GAAG,EAAE;AACd,QAAQ,GAAG;AACX,QAAQ,IAAI;AACZ,OAAO,CAAC,CAAC,CAAC;AACV,KAAK,CAAC;AACN,GAAG;AACH;AACA,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,kBAAkB,EAAE,CAAC;AACjD;AACA,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;AAC9D,CAAC,CAAC,CAAC;AACH;AACA,gBAAe,KAAK;;ACpOpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,WAAW,CAAC;AAClB,EAAE,WAAW,CAAC,QAAQ,EAAE;AACxB,IAAI,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;AACxC,MAAM,MAAM,IAAI,SAAS,CAAC,8BAA8B,CAAC,CAAC;AAC1D,KAAK;AACL;AACA,IAAI,IAAI,cAAc,CAAC;AACvB;AACA,IAAI,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC,SAAS,eAAe,CAAC,OAAO,EAAE;AACjE,MAAM,cAAc,GAAG,OAAO,CAAC;AAC/B,KAAK,CAAC,CAAC;AACP;AACA,IAAI,MAAM,KAAK,GAAG,IAAI,CAAC;AACvB;AACA;AACA,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI;AAChC,MAAM,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO;AACpC;AACA,MAAM,IAAI,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC;AACtC;AACA,MAAM,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE;AACtB,QAAQ,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;AACpC,OAAO;AACP,MAAM,KAAK,CAAC,UAAU,GAAG,IAAI,CAAC;AAC9B,KAAK,CAAC,CAAC;AACP;AACA;AACA,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,WAAW,IAAI;AACvC,MAAM,IAAI,QAAQ,CAAC;AACnB;AACA,MAAM,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,OAAO,IAAI;AAC7C,QAAQ,KAAK,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;AACjC,QAAQ,QAAQ,GAAG,OAAO,CAAC;AAC3B,OAAO,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AAC3B;AACA,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,MAAM,GAAG;AACzC,QAAQ,KAAK,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;AACpC,OAAO,CAAC;AACR;AACA,MAAM,OAAO,OAAO,CAAC;AACrB,KAAK,CAAC;AACN;AACA,IAAI,QAAQ,CAAC,SAAS,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE;AACvD,MAAM,IAAI,KAAK,CAAC,MAAM,EAAE;AACxB;AACA,QAAQ,OAAO;AACf,OAAO;AACP;AACA,MAAM,KAAK,CAAC,MAAM,GAAG,IAAI,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACjE,MAAM,cAAc,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AACnC,KAAK,CAAC,CAAC;AACP,GAAG;AACH;AACA;AACA;AACA;AACA,EAAE,gBAAgB,GAAG;AACrB,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE;AACrB,MAAM,MAAM,IAAI,CAAC,MAAM,CAAC;AACxB,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,EAAE,SAAS,CAAC,QAAQ,EAAE;AACtB,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE;AACrB,MAAM,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,MAAM,OAAO;AACb,KAAK;AACL;AACA,IAAI,IAAI,IAAI,CAAC,UAAU,EAAE;AACzB,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AACrC,KAAK,MAAM;AACX,MAAM,IAAI,CAAC,UAAU,GAAG,CAAC,QAAQ,CAAC,CAAC;AACnC,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,EAAE,WAAW,CAAC,QAAQ,EAAE;AACxB,IAAI,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE;AAC1B,MAAM,OAAO;AACb,KAAK;AACL,IAAI,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;AACpD,IAAI,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE;AACtB,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;AACvC,KAAK;AACL,GAAG;AACH;AACA,EAAE,aAAa,GAAG;AAClB,IAAI,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;AAC7C;AACA,IAAI,MAAM,KAAK,GAAG,CAAC,GAAG,KAAK;AAC3B,MAAM,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC5B,KAAK,CAAC;AACN;AACA,IAAI,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC1B;AACA,IAAI,UAAU,CAAC,MAAM,CAAC,WAAW,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;AAClE;AACA,IAAI,OAAO,UAAU,CAAC,MAAM,CAAC;AAC7B,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,EAAE,OAAO,MAAM,GAAG;AAClB,IAAI,IAAI,MAAM,CAAC;AACf,IAAI,MAAM,KAAK,GAAG,IAAI,WAAW,CAAC,SAAS,QAAQ,CAAC,CAAC,EAAE;AACvD,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,KAAK,CAAC,CAAC;AACP,IAAI,OAAO;AACX,MAAM,KAAK;AACX,MAAM,MAAM;AACZ,KAAK,CAAC;AACN,GAAG;AACH,CAAC;AACD;AACA,sBAAe,WAAW;;ACpI1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,MAAM,CAAC,QAAQ,EAAE;AACzC,EAAE,OAAO,SAAS,IAAI,CAAC,GAAG,EAAE;AAC5B,IAAI,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AACrC,GAAG,CAAC;AACJ;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACe,SAAS,YAAY,CAAC,OAAO,EAAE;AAC9C,EAAE,OAAOA,OAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,OAAO,CAAC,YAAY,KAAK,IAAI,CAAC,CAAC;AACpE;;ACbA,MAAM,cAAc,GAAG;AACvB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,kBAAkB,EAAE,GAAG;AACzB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,EAAE,EAAE,GAAG;AACT,EAAE,OAAO,EAAE,GAAG;AACd,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,2BAA2B,EAAE,GAAG;AAClC,EAAE,SAAS,EAAE,GAAG;AAChB,EAAE,YAAY,EAAE,GAAG;AACnB,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,WAAW,EAAE,GAAG;AAClB,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,MAAM,EAAE,GAAG;AACb,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,gBAAgB,EAAE,GAAG;AACvB,EAAE,KAAK,EAAE,GAAG;AACZ,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,WAAW,EAAE,GAAG;AAClB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,MAAM,EAAE,GAAG;AACb,EAAE,iBAAiB,EAAE,GAAG;AACxB,EAAE,iBAAiB,EAAE,GAAG;AACxB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,YAAY,EAAE,GAAG;AACnB,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,SAAS,EAAE,GAAG;AAChB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,gBAAgB,EAAE,GAAG;AACvB,EAAE,aAAa,EAAE,GAAG;AACpB,EAAE,2BAA2B,EAAE,GAAG;AAClC,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,IAAI,EAAE,GAAG;AACX,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,kBAAkB,EAAE,GAAG;AACzB,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,oBAAoB,EAAE,GAAG;AAC3B,EAAE,mBAAmB,EAAE,GAAG;AAC1B,EAAE,iBAAiB,EAAE,GAAG;AACxB,EAAE,SAAS,EAAE,GAAG;AAChB,EAAE,kBAAkB,EAAE,GAAG;AACzB,EAAE,mBAAmB,EAAE,GAAG;AAC1B,EAAE,MAAM,EAAE,GAAG;AACb,EAAE,gBAAgB,EAAE,GAAG;AACvB,EAAE,QAAQ,EAAE,GAAG;AACf,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,oBAAoB,EAAE,GAAG;AAC3B,EAAE,eAAe,EAAE,GAAG;AACtB,EAAE,2BAA2B,EAAE,GAAG;AAClC,EAAE,0BAA0B,EAAE,GAAG;AACjC,EAAE,mBAAmB,EAAE,GAAG;AAC1B,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,UAAU,EAAE,GAAG;AACjB,EAAE,kBAAkB,EAAE,GAAG;AACzB,EAAE,cAAc,EAAE,GAAG;AACrB,EAAE,uBAAuB,EAAE,GAAG;AAC9B,EAAE,qBAAqB,EAAE,GAAG;AAC5B,EAAE,mBAAmB,EAAE,GAAG;AAC1B,EAAE,YAAY,EAAE,GAAG;AACnB,EAAE,WAAW,EAAE,GAAG;AAClB,EAAE,6BAA6B,EAAE,GAAG;AACpC,CAAC,CAAC;AACF;AACA,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,KAAK;AACzD,EAAE,cAAc,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC;AAC9B,CAAC,CAAC,CAAC;AACH;AACA,yBAAe,cAAc;;AClD7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,cAAc,CAAC,aAAa,EAAE;AACvC,EAAE,MAAM,OAAO,GAAG,IAAI0B,OAAK,CAAC,aAAa,CAAC,CAAC;AAC3C,EAAE,MAAM,QAAQ,GAAG,IAAI,CAACA,OAAK,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAC1D;AACA;AACA,EAAE1B,OAAK,CAAC,MAAM,CAAC,QAAQ,EAAE0B,OAAK,CAAC,SAAS,EAAE,OAAO,EAAE,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC;AACvE;AACA;AACA,EAAE1B,OAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC;AAC5D;AACA;AACA,EAAE,QAAQ,CAAC,MAAM,GAAG,SAAS,MAAM,CAAC,cAAc,EAAE;AACpD,IAAI,OAAO,cAAc,CAAC,WAAW,CAAC,aAAa,EAAE,cAAc,CAAC,CAAC,CAAC;AACtE,GAAG,CAAC;AACJ;AACA,EAAE,OAAO,QAAQ,CAAC;AAClB,CAAC;AACD;AACA;AACK,MAAC,KAAK,GAAG,cAAc,CAACO,UAAQ,EAAE;AACvC;AACA;AACA,KAAK,CAAC,KAAK,GAAGmB,OAAK,CAAC;AACpB;AACA;AACA,KAAK,CAAC,aAAa,GAAG,aAAa,CAAC;AACpC,KAAK,CAAC,WAAW,GAAGC,aAAW,CAAC;AAChC,KAAK,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAC1B,KAAK,CAAC,OAAO,GAAG,OAAO,CAAC;AACxB,KAAK,CAAC,UAAU,GAAG,UAAU,CAAC;AAC9B;AACA;AACA,KAAK,CAAC,UAAU,GAAG,UAAU,CAAC;AAC9B;AACA;AACA,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,aAAa,CAAC;AACnC;AACA;AACA,KAAK,CAAC,GAAG,GAAG,SAAS,GAAG,CAAC,QAAQ,EAAE;AACnC,EAAE,OAAO,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AAC/B,CAAC,CAAC;AACF;AACA,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC;AACtB;AACA;AACA,KAAK,CAAC,YAAY,GAAG,YAAY,CAAC;AAClC;AACA;AACA,KAAK,CAAC,WAAW,GAAG,WAAW,CAAC;AAChC;AACA,KAAK,CAAC,YAAY,GAAGnB,cAAY,CAAC;AAClC;AACA,KAAK,CAAC,UAAU,GAAG,KAAK,IAAI,cAAc,CAACR,OAAK,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,IAAI,QAAQ,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC;AAClG;AACA,KAAK,CAAC,UAAU,GAAG,QAAQ,CAAC,UAAU,CAAC;AACvC;AACA,KAAK,CAAC,cAAc,GAAG4B,gBAAc,CAAC;AACtC;AACA,KAAK,CAAC,OAAO,GAAG,KAAK;;;;"} \ No newline at end of file diff --git a/node_modules/axios/index.d.cts b/node_modules/axios/index.d.cts new file mode 100644 index 000000000..d5136170d --- /dev/null +++ b/node_modules/axios/index.d.cts @@ -0,0 +1,549 @@ +interface RawAxiosHeaders { + [key: string]: axios.AxiosHeaderValue; +} + +type MethodsHeaders = Partial<{ + [Key in axios.Method as Lowercase]: AxiosHeaders; +} & {common: AxiosHeaders}>; + +type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean; + +type AxiosHeaderParser = (this: AxiosHeaders, value: axios.AxiosHeaderValue, header: string) => any; + +type CommonRequestHeadersList = 'Accept' | 'Content-Length' | 'User-Agent'| 'Content-Encoding' | 'Authorization'; + +type ContentType = axios.AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data' | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream'; + +type CommonResponseHeadersList = 'Server' | 'Content-Type' | 'Content-Length' | 'Cache-Control'| 'Content-Encoding'; + +declare class AxiosHeaders { + constructor( + headers?: RawAxiosHeaders | AxiosHeaders | string + ); + + [key: string]: any; + + set(headerName?: string, value?: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders; + + get(headerName: string, parser: RegExp): RegExpExecArray | null; + get(headerName: string, matcher?: true | AxiosHeaderParser): axios.AxiosHeaderValue; + + has(header: string, matcher?: AxiosHeaderMatcher): boolean; + + delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean; + + clear(matcher?: AxiosHeaderMatcher): boolean; + + normalize(format: boolean): AxiosHeaders; + + concat(...targets: Array): AxiosHeaders; + + toJSON(asStrings?: boolean): RawAxiosHeaders; + + static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders; + + static accessor(header: string | string[]): AxiosHeaders; + + static concat(...targets: Array): AxiosHeaders; + + setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentType(parser?: RegExp): RegExpExecArray | null; + getContentType(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; + hasContentType(matcher?: AxiosHeaderMatcher): boolean; + + setContentLength(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentLength(parser?: RegExp): RegExpExecArray | null; + getContentLength(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; + hasContentLength(matcher?: AxiosHeaderMatcher): boolean; + + setAccept(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getAccept(parser?: RegExp): RegExpExecArray | null; + getAccept(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; + hasAccept(matcher?: AxiosHeaderMatcher): boolean; + + setUserAgent(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getUserAgent(parser?: RegExp): RegExpExecArray | null; + getUserAgent(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; + hasUserAgent(matcher?: AxiosHeaderMatcher): boolean; + + setContentEncoding(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentEncoding(parser?: RegExp): RegExpExecArray | null; + getContentEncoding(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; + hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean; + + setAuthorization(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getAuthorization(parser?: RegExp): RegExpExecArray | null; + getAuthorization(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; + hasAuthorization(matcher?: AxiosHeaderMatcher): boolean; + + [Symbol.iterator](): IterableIterator<[string, axios.AxiosHeaderValue]>; +} + +declare class AxiosError extends Error { + constructor( + message?: string, + code?: string, + config?: axios.InternalAxiosRequestConfig, + request?: any, + response?: axios.AxiosResponse + ); + + config?: axios.InternalAxiosRequestConfig; + code?: string; + request?: any; + response?: axios.AxiosResponse; + isAxiosError: boolean; + status?: number; + toJSON: () => object; + cause?: Error; + static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS"; + static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE"; + static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION"; + static readonly ERR_NETWORK = "ERR_NETWORK"; + static readonly ERR_DEPRECATED = "ERR_DEPRECATED"; + static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE"; + static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST"; + static readonly ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT"; + static readonly ERR_INVALID_URL = "ERR_INVALID_URL"; + static readonly ERR_CANCELED = "ERR_CANCELED"; + static readonly ECONNABORTED = "ECONNABORTED"; + static readonly ETIMEDOUT = "ETIMEDOUT"; +} + +declare class CanceledError extends AxiosError { +} + +declare class Axios { + constructor(config?: axios.AxiosRequestConfig); + defaults: axios.AxiosDefaults; + interceptors: { + request: axios.AxiosInterceptorManager; + response: axios.AxiosInterceptorManager; + }; + getUri(config?: axios.AxiosRequestConfig): string; + request, D = any>(config: axios.AxiosRequestConfig): Promise; + get, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; + delete, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; + head, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; + options, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; + post, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + put, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + patch, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + postForm, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + putForm, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + patchForm, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; +} + +declare enum HttpStatusCode { + Continue = 100, + SwitchingProtocols = 101, + Processing = 102, + EarlyHints = 103, + Ok = 200, + Created = 201, + Accepted = 202, + NonAuthoritativeInformation = 203, + NoContent = 204, + ResetContent = 205, + PartialContent = 206, + MultiStatus = 207, + AlreadyReported = 208, + ImUsed = 226, + MultipleChoices = 300, + MovedPermanently = 301, + Found = 302, + SeeOther = 303, + NotModified = 304, + UseProxy = 305, + Unused = 306, + TemporaryRedirect = 307, + PermanentRedirect = 308, + BadRequest = 400, + Unauthorized = 401, + PaymentRequired = 402, + Forbidden = 403, + NotFound = 404, + MethodNotAllowed = 405, + NotAcceptable = 406, + ProxyAuthenticationRequired = 407, + RequestTimeout = 408, + Conflict = 409, + Gone = 410, + LengthRequired = 411, + PreconditionFailed = 412, + PayloadTooLarge = 413, + UriTooLong = 414, + UnsupportedMediaType = 415, + RangeNotSatisfiable = 416, + ExpectationFailed = 417, + ImATeapot = 418, + MisdirectedRequest = 421, + UnprocessableEntity = 422, + Locked = 423, + FailedDependency = 424, + TooEarly = 425, + UpgradeRequired = 426, + PreconditionRequired = 428, + TooManyRequests = 429, + RequestHeaderFieldsTooLarge = 431, + UnavailableForLegalReasons = 451, + InternalServerError = 500, + NotImplemented = 501, + BadGateway = 502, + ServiceUnavailable = 503, + GatewayTimeout = 504, + HttpVersionNotSupported = 505, + VariantAlsoNegotiates = 506, + InsufficientStorage = 507, + LoopDetected = 508, + NotExtended = 510, + NetworkAuthenticationRequired = 511, +} + +type InternalAxiosError = AxiosError; + +declare namespace axios { + type AxiosError = InternalAxiosError; + + type RawAxiosRequestHeaders = Partial; + + type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders; + + type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null; + + type RawCommonResponseHeaders = { + [Key in CommonResponseHeadersList]: AxiosHeaderValue; + } & { + "set-cookie": string[]; + }; + + type RawAxiosResponseHeaders = Partial; + + type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders; + + interface AxiosRequestTransformer { + (this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any; + } + + interface AxiosResponseTransformer { + (this: InternalAxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any; + } + + interface AxiosAdapter { + (config: InternalAxiosRequestConfig): AxiosPromise; + } + + interface AxiosBasicCredentials { + username: string; + password: string; + } + + interface AxiosProxyConfig { + host: string; + port: number; + auth?: AxiosBasicCredentials; + protocol?: string; + } + + type Method = + | 'get' | 'GET' + | 'delete' | 'DELETE' + | 'head' | 'HEAD' + | 'options' | 'OPTIONS' + | 'post' | 'POST' + | 'put' | 'PUT' + | 'patch' | 'PATCH' + | 'purge' | 'PURGE' + | 'link' | 'LINK' + | 'unlink' | 'UNLINK'; + + type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream' + | 'formdata'; + + type responseEncoding = + | 'ascii' | 'ASCII' + | 'ansi' | 'ANSI' + | 'binary' | 'BINARY' + | 'base64' | 'BASE64' + | 'base64url' | 'BASE64URL' + | 'hex' | 'HEX' + | 'latin1' | 'LATIN1' + | 'ucs-2' | 'UCS-2' + | 'ucs2' | 'UCS2' + | 'utf-8' | 'UTF-8' + | 'utf8' | 'UTF8' + | 'utf16le' | 'UTF16LE'; + + interface TransitionalOptions { + silentJSONParsing?: boolean; + forcedJSONParsing?: boolean; + clarifyTimeoutError?: boolean; + } + + interface GenericAbortSignal { + readonly aborted: boolean; + onabort?: ((...args: any) => any) | null; + addEventListener?: (...args: any) => any; + removeEventListener?: (...args: any) => any; + } + + interface FormDataVisitorHelpers { + defaultVisitor: SerializerVisitor; + convertValue: (value: any) => any; + isVisitable: (value: any) => boolean; + } + + interface SerializerVisitor { + ( + this: GenericFormData, + value: any, + key: string | number, + path: null | Array, + helpers: FormDataVisitorHelpers + ): boolean; + } + + interface SerializerOptions { + visitor?: SerializerVisitor; + dots?: boolean; + metaTokens?: boolean; + indexes?: boolean | null; + } + + // tslint:disable-next-line + interface FormSerializerOptions extends SerializerOptions { + } + + interface ParamEncoder { + (value: any, defaultEncoder: (value: any) => any): any; + } + + interface CustomParamsSerializer { + (params: Record, options?: ParamsSerializerOptions): string; + } + + interface ParamsSerializerOptions extends SerializerOptions { + encode?: ParamEncoder; + serialize?: CustomParamsSerializer; + } + + type MaxUploadRate = number; + + type MaxDownloadRate = number; + + type BrowserProgressEvent = any; + + interface AxiosProgressEvent { + loaded: number; + total?: number; + progress?: number; + bytes: number; + rate?: number; + estimated?: number; + upload?: boolean; + download?: boolean; + event?: BrowserProgressEvent; + lengthComputable: boolean; + } + + type Milliseconds = number; + + type AxiosAdapterName = 'fetch' | 'xhr' | 'http' | string; + + type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName; + + type AddressFamily = 4 | 6 | undefined; + + interface LookupAddressEntry { + address: string; + family?: AddressFamily; + } + + type LookupAddress = string | LookupAddressEntry; + + interface AxiosRequestConfig { + url?: string; + method?: Method | string; + baseURL?: string; + transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; + transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; + headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders; + params?: any; + paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer; + data?: D; + timeout?: Milliseconds; + timeoutErrorMessage?: string; + withCredentials?: boolean; + adapter?: AxiosAdapterConfig | AxiosAdapterConfig[]; + auth?: AxiosBasicCredentials; + responseType?: ResponseType; + responseEncoding?: responseEncoding | string; + xsrfCookieName?: string; + xsrfHeaderName?: string; + onUploadProgress?: (progressEvent: AxiosProgressEvent) => void; + onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void; + maxContentLength?: number; + validateStatus?: ((status: number) => boolean) | null; + maxBodyLength?: number; + maxRedirects?: number; + maxRate?: number | [MaxUploadRate, MaxDownloadRate]; + beforeRedirect?: (options: Record, responseDetails: {headers: Record, statusCode: HttpStatusCode}) => void; + socketPath?: string | null; + transport?: any; + httpAgent?: any; + httpsAgent?: any; + proxy?: AxiosProxyConfig | false; + cancelToken?: CancelToken; + decompress?: boolean; + transitional?: TransitionalOptions; + signal?: GenericAbortSignal; + insecureHTTPParser?: boolean; + env?: { + FormData?: new (...args: any[]) => object; + }; + formSerializer?: FormSerializerOptions; + family?: AddressFamily; + lookup?: ((hostname: string, options: object, cb: (err: Error | null, address: LookupAddress | LookupAddress[], family?: AddressFamily) => void) => void) | + ((hostname: string, options: object) => Promise<[address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily] | LookupAddress>); + withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined); + fetchOptions?: Record; + } + + // Alias + type RawAxiosRequestConfig = AxiosRequestConfig; + + interface InternalAxiosRequestConfig extends AxiosRequestConfig { + headers: AxiosRequestHeaders; + } + + interface HeadersDefaults { + common: RawAxiosRequestHeaders; + delete: RawAxiosRequestHeaders; + get: RawAxiosRequestHeaders; + head: RawAxiosRequestHeaders; + post: RawAxiosRequestHeaders; + put: RawAxiosRequestHeaders; + patch: RawAxiosRequestHeaders; + options?: RawAxiosRequestHeaders; + purge?: RawAxiosRequestHeaders; + link?: RawAxiosRequestHeaders; + unlink?: RawAxiosRequestHeaders; + } + + interface AxiosDefaults extends Omit, 'headers'> { + headers: HeadersDefaults; + } + + interface CreateAxiosDefaults extends Omit, 'headers'> { + headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial; + } + + interface AxiosResponse { + data: T; + status: number; + statusText: string; + headers: RawAxiosResponseHeaders | AxiosResponseHeaders; + config: InternalAxiosRequestConfig; + request?: any; + } + + type AxiosPromise = Promise>; + + interface CancelStatic { + new (message?: string): Cancel; + } + + interface Cancel { + message: string | undefined; + } + + interface Canceler { + (message?: string, config?: AxiosRequestConfig, request?: any): void; + } + + interface CancelTokenStatic { + new (executor: (cancel: Canceler) => void): CancelToken; + source(): CancelTokenSource; + } + + interface CancelToken { + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; + } + + interface CancelTokenSource { + token: CancelToken; + cancel: Canceler; + } + + interface AxiosInterceptorOptions { + synchronous?: boolean; + runWhen?: (config: InternalAxiosRequestConfig) => boolean; + } + + type AxiosRequestInterceptorUse = (onFulfilled?: ((value: T) => T | Promise) | null, onRejected?: ((error: any) => any) | null, options?: AxiosInterceptorOptions) => number; + + type AxiosResponseInterceptorUse = (onFulfilled?: ((value: T) => T | Promise) | null, onRejected?: ((error: any) => any) | null) => number; + + interface AxiosInterceptorManager { + use: V extends AxiosResponse ? AxiosResponseInterceptorUse : AxiosRequestInterceptorUse; + eject(id: number): void; + clear(): void; + } + + interface AxiosInstance extends Axios { + , D = any>(config: AxiosRequestConfig): Promise; + , D = any>(url: string, config?: AxiosRequestConfig): Promise; + + defaults: Omit & { + headers: HeadersDefaults & { + [key: string]: AxiosHeaderValue + } + }; + } + + interface GenericFormData { + append(name: string, value: any, options?: any): any; + } + + interface GenericHTMLFormElement { + name: string; + method: string; + submit(): void; + } + + interface AxiosStatic extends AxiosInstance { + create(config?: CreateAxiosDefaults): AxiosInstance; + Cancel: CancelStatic; + CancelToken: CancelTokenStatic; + Axios: typeof Axios; + AxiosError: typeof AxiosError; + CanceledError: typeof CanceledError; + HttpStatusCode: typeof HttpStatusCode; + readonly VERSION: string; + isCancel(value: any): value is Cancel; + all(values: Array>): Promise; + spread(callback: (...args: T[]) => R): (array: T[]) => R; + isAxiosError(payload: any): payload is AxiosError; + toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData; + formToJSON(form: GenericFormData|GenericHTMLFormElement): object; + getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined): AxiosAdapter; + AxiosHeaders: typeof AxiosHeaders; + } +} + +declare const axios: axios.AxiosStatic; + +export = axios; diff --git a/node_modules/axios/index.d.ts b/node_modules/axios/index.d.ts new file mode 100644 index 000000000..21bb581b6 --- /dev/null +++ b/node_modules/axios/index.d.ts @@ -0,0 +1,569 @@ +// TypeScript Version: 4.7 +export type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null; + +interface RawAxiosHeaders { + [key: string]: AxiosHeaderValue; +} + +type MethodsHeaders = Partial<{ + [Key in Method as Lowercase]: AxiosHeaders; +} & {common: AxiosHeaders}>; + +type AxiosHeaderMatcher = string | RegExp | ((this: AxiosHeaders, value: string, name: string) => boolean); + +type AxiosHeaderParser = (this: AxiosHeaders, value: AxiosHeaderValue, header: string) => any; + +export class AxiosHeaders { + constructor( + headers?: RawAxiosHeaders | AxiosHeaders | string + ); + + [key: string]: any; + + set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders; + + get(headerName: string, parser: RegExp): RegExpExecArray | null; + get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue; + + has(header: string, matcher?: AxiosHeaderMatcher): boolean; + + delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean; + + clear(matcher?: AxiosHeaderMatcher): boolean; + + normalize(format: boolean): AxiosHeaders; + + concat(...targets: Array): AxiosHeaders; + + toJSON(asStrings?: boolean): RawAxiosHeaders; + + static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders; + + static accessor(header: string | string[]): AxiosHeaders; + + static concat(...targets: Array): AxiosHeaders; + + setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentType(parser?: RegExp): RegExpExecArray | null; + getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasContentType(matcher?: AxiosHeaderMatcher): boolean; + + setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentLength(parser?: RegExp): RegExpExecArray | null; + getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasContentLength(matcher?: AxiosHeaderMatcher): boolean; + + setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getAccept(parser?: RegExp): RegExpExecArray | null; + getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasAccept(matcher?: AxiosHeaderMatcher): boolean; + + setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getUserAgent(parser?: RegExp): RegExpExecArray | null; + getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasUserAgent(matcher?: AxiosHeaderMatcher): boolean; + + setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getContentEncoding(parser?: RegExp): RegExpExecArray | null; + getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean; + + setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + getAuthorization(parser?: RegExp): RegExpExecArray | null; + getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; + hasAuthorization(matcher?: AxiosHeaderMatcher): boolean; + + [Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>; +} + +type CommonRequestHeadersList = 'Accept' | 'Content-Length' | 'User-Agent' | 'Content-Encoding' | 'Authorization'; + +type ContentType = AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data' | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream'; + +export type RawAxiosRequestHeaders = Partial; + +export type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders; + +type CommonResponseHeadersList = 'Server' | 'Content-Type' | 'Content-Length' | 'Cache-Control'| 'Content-Encoding'; + +type RawCommonResponseHeaders = { + [Key in CommonResponseHeadersList]: AxiosHeaderValue; +} & { + "set-cookie": string[]; +}; + +export type RawAxiosResponseHeaders = Partial; + +export type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders; + +export interface AxiosRequestTransformer { + (this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any; +} + +export interface AxiosResponseTransformer { + (this: InternalAxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any; +} + +export interface AxiosAdapter { + (config: InternalAxiosRequestConfig): AxiosPromise; +} + +export interface AxiosBasicCredentials { + username: string; + password: string; +} + +export interface AxiosProxyConfig { + host: string; + port: number; + auth?: AxiosBasicCredentials; + protocol?: string; +} + +export enum HttpStatusCode { + Continue = 100, + SwitchingProtocols = 101, + Processing = 102, + EarlyHints = 103, + Ok = 200, + Created = 201, + Accepted = 202, + NonAuthoritativeInformation = 203, + NoContent = 204, + ResetContent = 205, + PartialContent = 206, + MultiStatus = 207, + AlreadyReported = 208, + ImUsed = 226, + MultipleChoices = 300, + MovedPermanently = 301, + Found = 302, + SeeOther = 303, + NotModified = 304, + UseProxy = 305, + Unused = 306, + TemporaryRedirect = 307, + PermanentRedirect = 308, + BadRequest = 400, + Unauthorized = 401, + PaymentRequired = 402, + Forbidden = 403, + NotFound = 404, + MethodNotAllowed = 405, + NotAcceptable = 406, + ProxyAuthenticationRequired = 407, + RequestTimeout = 408, + Conflict = 409, + Gone = 410, + LengthRequired = 411, + PreconditionFailed = 412, + PayloadTooLarge = 413, + UriTooLong = 414, + UnsupportedMediaType = 415, + RangeNotSatisfiable = 416, + ExpectationFailed = 417, + ImATeapot = 418, + MisdirectedRequest = 421, + UnprocessableEntity = 422, + Locked = 423, + FailedDependency = 424, + TooEarly = 425, + UpgradeRequired = 426, + PreconditionRequired = 428, + TooManyRequests = 429, + RequestHeaderFieldsTooLarge = 431, + UnavailableForLegalReasons = 451, + InternalServerError = 500, + NotImplemented = 501, + BadGateway = 502, + ServiceUnavailable = 503, + GatewayTimeout = 504, + HttpVersionNotSupported = 505, + VariantAlsoNegotiates = 506, + InsufficientStorage = 507, + LoopDetected = 508, + NotExtended = 510, + NetworkAuthenticationRequired = 511, +} + +export type Method = + | 'get' | 'GET' + | 'delete' | 'DELETE' + | 'head' | 'HEAD' + | 'options' | 'OPTIONS' + | 'post' | 'POST' + | 'put' | 'PUT' + | 'patch' | 'PATCH' + | 'purge' | 'PURGE' + | 'link' | 'LINK' + | 'unlink' | 'UNLINK'; + +export type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream' + | 'formdata'; + +export type responseEncoding = + | 'ascii' | 'ASCII' + | 'ansi' | 'ANSI' + | 'binary' | 'BINARY' + | 'base64' | 'BASE64' + | 'base64url' | 'BASE64URL' + | 'hex' | 'HEX' + | 'latin1' | 'LATIN1' + | 'ucs-2' | 'UCS-2' + | 'ucs2' | 'UCS2' + | 'utf-8' | 'UTF-8' + | 'utf8' | 'UTF8' + | 'utf16le' | 'UTF16LE'; + +export interface TransitionalOptions { + silentJSONParsing?: boolean; + forcedJSONParsing?: boolean; + clarifyTimeoutError?: boolean; +} + +export interface GenericAbortSignal { + readonly aborted: boolean; + onabort?: ((...args: any) => any) | null; + addEventListener?: (...args: any) => any; + removeEventListener?: (...args: any) => any; +} + +export interface FormDataVisitorHelpers { + defaultVisitor: SerializerVisitor; + convertValue: (value: any) => any; + isVisitable: (value: any) => boolean; +} + +export interface SerializerVisitor { + ( + this: GenericFormData, + value: any, + key: string | number, + path: null | Array, + helpers: FormDataVisitorHelpers + ): boolean; +} + +export interface SerializerOptions { + visitor?: SerializerVisitor; + dots?: boolean; + metaTokens?: boolean; + indexes?: boolean | null; +} + +// tslint:disable-next-line +export interface FormSerializerOptions extends SerializerOptions { +} + +export interface ParamEncoder { + (value: any, defaultEncoder: (value: any) => any): any; +} + +export interface CustomParamsSerializer { + (params: Record, options?: ParamsSerializerOptions): string; +} + +export interface ParamsSerializerOptions extends SerializerOptions { + encode?: ParamEncoder; + serialize?: CustomParamsSerializer; +} + +type MaxUploadRate = number; + +type MaxDownloadRate = number; + +type BrowserProgressEvent = any; + +export interface AxiosProgressEvent { + loaded: number; + total?: number; + progress?: number; + bytes: number; + rate?: number; + estimated?: number; + upload?: boolean; + download?: boolean; + event?: BrowserProgressEvent; + lengthComputable: boolean; +} + +type Milliseconds = number; + +type AxiosAdapterName = 'fetch' | 'xhr' | 'http' | string; + +type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName; + +export type AddressFamily = 4 | 6 | undefined; + +export interface LookupAddressEntry { + address: string; + family?: AddressFamily; +} + +export type LookupAddress = string | LookupAddressEntry; + +export interface AxiosRequestConfig { + url?: string; + method?: Method | string; + baseURL?: string; + transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; + transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; + headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders; + params?: any; + paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer; + data?: D; + timeout?: Milliseconds; + timeoutErrorMessage?: string; + withCredentials?: boolean; + adapter?: AxiosAdapterConfig | AxiosAdapterConfig[]; + auth?: AxiosBasicCredentials; + responseType?: ResponseType; + responseEncoding?: responseEncoding | string; + xsrfCookieName?: string; + xsrfHeaderName?: string; + onUploadProgress?: (progressEvent: AxiosProgressEvent) => void; + onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void; + maxContentLength?: number; + validateStatus?: ((status: number) => boolean) | null; + maxBodyLength?: number; + maxRedirects?: number; + maxRate?: number | [MaxUploadRate, MaxDownloadRate]; + beforeRedirect?: (options: Record, responseDetails: {headers: Record, statusCode: HttpStatusCode}) => void; + socketPath?: string | null; + transport?: any; + httpAgent?: any; + httpsAgent?: any; + proxy?: AxiosProxyConfig | false; + cancelToken?: CancelToken; + decompress?: boolean; + transitional?: TransitionalOptions; + signal?: GenericAbortSignal; + insecureHTTPParser?: boolean; + env?: { + FormData?: new (...args: any[]) => object; + }; + formSerializer?: FormSerializerOptions; + family?: AddressFamily; + lookup?: ((hostname: string, options: object, cb: (err: Error | null, address: LookupAddress | LookupAddress[], family?: AddressFamily) => void) => void) | + ((hostname: string, options: object) => Promise<[address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily] | LookupAddress>); + withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined); + fetchOptions?: Record; +} + +// Alias +export type RawAxiosRequestConfig = AxiosRequestConfig; + +export interface InternalAxiosRequestConfig extends AxiosRequestConfig { + headers: AxiosRequestHeaders; +} + +export interface HeadersDefaults { + common: RawAxiosRequestHeaders; + delete: RawAxiosRequestHeaders; + get: RawAxiosRequestHeaders; + head: RawAxiosRequestHeaders; + post: RawAxiosRequestHeaders; + put: RawAxiosRequestHeaders; + patch: RawAxiosRequestHeaders; + options?: RawAxiosRequestHeaders; + purge?: RawAxiosRequestHeaders; + link?: RawAxiosRequestHeaders; + unlink?: RawAxiosRequestHeaders; +} + +export interface AxiosDefaults extends Omit, 'headers'> { + headers: HeadersDefaults; +} + +export interface CreateAxiosDefaults extends Omit, 'headers'> { + headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial; +} + +export interface AxiosResponse { + data: T; + status: number; + statusText: string; + headers: RawAxiosResponseHeaders | AxiosResponseHeaders; + config: InternalAxiosRequestConfig; + request?: any; +} + +export class AxiosError extends Error { + constructor( + message?: string, + code?: string, + config?: InternalAxiosRequestConfig, + request?: any, + response?: AxiosResponse + ); + + config?: InternalAxiosRequestConfig; + code?: string; + request?: any; + response?: AxiosResponse; + isAxiosError: boolean; + status?: number; + toJSON: () => object; + cause?: Error; + static from( + error: Error | unknown, + code?: string, + config?: InternalAxiosRequestConfig, + request?: any, + response?: AxiosResponse, + customProps?: object, +): AxiosError; + static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS"; + static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE"; + static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION"; + static readonly ERR_NETWORK = "ERR_NETWORK"; + static readonly ERR_DEPRECATED = "ERR_DEPRECATED"; + static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE"; + static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST"; + static readonly ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT"; + static readonly ERR_INVALID_URL = "ERR_INVALID_URL"; + static readonly ERR_CANCELED = "ERR_CANCELED"; + static readonly ECONNABORTED = "ECONNABORTED"; + static readonly ETIMEDOUT = "ETIMEDOUT"; +} + +export class CanceledError extends AxiosError { +} + +export type AxiosPromise = Promise>; + +export interface CancelStatic { + new (message?: string): Cancel; +} + +export interface Cancel { + message: string | undefined; +} + +export interface Canceler { + (message?: string, config?: AxiosRequestConfig, request?: any): void; +} + +export interface CancelTokenStatic { + new (executor: (cancel: Canceler) => void): CancelToken; + source(): CancelTokenSource; +} + +export interface CancelToken { + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; +} + +export interface CancelTokenSource { + token: CancelToken; + cancel: Canceler; +} + +export interface AxiosInterceptorOptions { + synchronous?: boolean; + runWhen?: (config: InternalAxiosRequestConfig) => boolean; +} + +type AxiosRequestInterceptorUse = (onFulfilled?: ((value: T) => T | Promise) | null, onRejected?: ((error: any) => any) | null, options?: AxiosInterceptorOptions) => number; + +type AxiosResponseInterceptorUse = (onFulfilled?: ((value: T) => T | Promise) | null, onRejected?: ((error: any) => any) | null) => number; + +export interface AxiosInterceptorManager { + use: V extends AxiosResponse ? AxiosResponseInterceptorUse : AxiosRequestInterceptorUse; + eject(id: number): void; + clear(): void; +} + +export class Axios { + constructor(config?: AxiosRequestConfig); + defaults: AxiosDefaults; + interceptors: { + request: AxiosInterceptorManager; + response: AxiosInterceptorManager; + }; + getUri(config?: AxiosRequestConfig): string; + request, D = any>(config: AxiosRequestConfig): Promise; + get, D = any>(url: string, config?: AxiosRequestConfig): Promise; + delete, D = any>(url: string, config?: AxiosRequestConfig): Promise; + head, D = any>(url: string, config?: AxiosRequestConfig): Promise; + options, D = any>(url: string, config?: AxiosRequestConfig): Promise; + post, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; + put, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; + patch, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; + postForm, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; + putForm, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; + patchForm, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; +} + +export interface AxiosInstance extends Axios { + , D = any>(config: AxiosRequestConfig): Promise; + , D = any>(url: string, config?: AxiosRequestConfig): Promise; + + defaults: Omit & { + headers: HeadersDefaults & { + [key: string]: AxiosHeaderValue + } + }; +} + +export interface GenericFormData { + append(name: string, value: any, options?: any): any; +} + +export interface GenericHTMLFormElement { + name: string; + method: string; + submit(): void; +} + +export function getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined): AxiosAdapter; + +export function toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData; + +export function formToJSON(form: GenericFormData|GenericHTMLFormElement): object; + +export function isAxiosError(payload: any): payload is AxiosError; + +export function spread(callback: (...args: T[]) => R): (array: T[]) => R; + +export function isCancel(value: any): value is Cancel; + +export function all(values: Array>): Promise; + +export function mergeConfig(config1: AxiosRequestConfig, config2: AxiosRequestConfig): AxiosRequestConfig; + +export interface AxiosStatic extends AxiosInstance { + create(config?: CreateAxiosDefaults): AxiosInstance; + Cancel: CancelStatic; + CancelToken: CancelTokenStatic; + Axios: typeof Axios; + AxiosError: typeof AxiosError; + HttpStatusCode: typeof HttpStatusCode; + readonly VERSION: string; + isCancel: typeof isCancel; + all: typeof all; + spread: typeof spread; + isAxiosError: typeof isAxiosError; + toFormData: typeof toFormData; + formToJSON: typeof formToJSON; + getAdapter: typeof getAdapter; + CanceledError: typeof CanceledError; + AxiosHeaders: typeof AxiosHeaders; + mergeConfig: typeof mergeConfig; +} + +declare const axios: AxiosStatic; + +export default axios; diff --git a/node_modules/axios/index.js b/node_modules/axios/index.js new file mode 100644 index 000000000..fba3990d8 --- /dev/null +++ b/node_modules/axios/index.js @@ -0,0 +1,43 @@ +import axios from './lib/axios.js'; + +// This module is intended to unwrap Axios default export as named. +// Keep top-level export same with static properties +// so that it can keep same with es module or cjs +const { + Axios, + AxiosError, + CanceledError, + isCancel, + CancelToken, + VERSION, + all, + Cancel, + isAxiosError, + spread, + toFormData, + AxiosHeaders, + HttpStatusCode, + formToJSON, + getAdapter, + mergeConfig +} = axios; + +export { + axios as default, + Axios, + AxiosError, + CanceledError, + isCancel, + CancelToken, + VERSION, + all, + Cancel, + isAxiosError, + spread, + toFormData, + AxiosHeaders, + HttpStatusCode, + formToJSON, + getAdapter, + mergeConfig +} diff --git a/node_modules/axios/lib/adapters/README.md b/node_modules/axios/lib/adapters/README.md new file mode 100644 index 000000000..68f111895 --- /dev/null +++ b/node_modules/axios/lib/adapters/README.md @@ -0,0 +1,37 @@ +# axios // adapters + +The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received. + +## Example + +```js +var settle = require('./../core/settle'); + +module.exports = function myAdapter(config) { + // At this point: + // - config has been merged with defaults + // - request transformers have already run + // - request interceptors have already run + + // Make the request using config provided + // Upon response settle the Promise + + return new Promise(function(resolve, reject) { + + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request + }; + + settle(resolve, reject, response); + + // From here: + // - response transformers will run + // - response interceptors will run + }); +} +``` diff --git a/node_modules/axios/lib/adapters/adapters.js b/node_modules/axios/lib/adapters/adapters.js new file mode 100644 index 000000000..b466dd516 --- /dev/null +++ b/node_modules/axios/lib/adapters/adapters.js @@ -0,0 +1,79 @@ +import utils from '../utils.js'; +import httpAdapter from './http.js'; +import xhrAdapter from './xhr.js'; +import fetchAdapter from './fetch.js'; +import AxiosError from "../core/AxiosError.js"; + +const knownAdapters = { + http: httpAdapter, + xhr: xhrAdapter, + fetch: fetchAdapter +} + +utils.forEach(knownAdapters, (fn, value) => { + if (fn) { + try { + Object.defineProperty(fn, 'name', {value}); + } catch (e) { + // eslint-disable-next-line no-empty + } + Object.defineProperty(fn, 'adapterName', {value}); + } +}); + +const renderReason = (reason) => `- ${reason}`; + +const isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false; + +export default { + getAdapter: (adapters) => { + adapters = utils.isArray(adapters) ? adapters : [adapters]; + + const {length} = adapters; + let nameOrAdapter; + let adapter; + + const rejectedReasons = {}; + + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters[i]; + let id; + + adapter = nameOrAdapter; + + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + + if (adapter === undefined) { + throw new AxiosError(`Unknown adapter '${id}'`); + } + } + + if (adapter) { + break; + } + + rejectedReasons[id || '#' + i] = adapter; + } + + if (!adapter) { + + const reasons = Object.entries(rejectedReasons) + .map(([id, state]) => `adapter ${id} ` + + (state === false ? 'is not supported by the environment' : 'is not available in the build') + ); + + let s = length ? + (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : + 'as no adapter specified'; + + throw new AxiosError( + `There is no suitable adapter to dispatch the request ` + s, + 'ERR_NOT_SUPPORT' + ); + } + + return adapter; + }, + adapters: knownAdapters +} diff --git a/node_modules/axios/lib/adapters/fetch.js b/node_modules/axios/lib/adapters/fetch.js new file mode 100644 index 000000000..f871a0524 --- /dev/null +++ b/node_modules/axios/lib/adapters/fetch.js @@ -0,0 +1,229 @@ +import platform from "../platform/index.js"; +import utils from "../utils.js"; +import AxiosError from "../core/AxiosError.js"; +import composeSignals from "../helpers/composeSignals.js"; +import {trackStream} from "../helpers/trackStream.js"; +import AxiosHeaders from "../core/AxiosHeaders.js"; +import {progressEventReducer, progressEventDecorator, asyncDecorator} from "../helpers/progressEventReducer.js"; +import resolveConfig from "../helpers/resolveConfig.js"; +import settle from "../core/settle.js"; + +const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function'; +const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function'; + +// used only inside the fetch adapter +const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? + ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : + async (str) => new Uint8Array(await new Response(str).arrayBuffer()) +); + +const test = (fn, ...args) => { + try { + return !!fn(...args); + } catch (e) { + return false + } +} + +const supportsRequestStream = isReadableStreamSupported && test(() => { + let duplexAccessed = false; + + const hasContentType = new Request(platform.origin, { + body: new ReadableStream(), + method: 'POST', + get duplex() { + duplexAccessed = true; + return 'half'; + }, + }).headers.has('Content-Type'); + + return duplexAccessed && !hasContentType; +}); + +const DEFAULT_CHUNK_SIZE = 64 * 1024; + +const supportsResponseStream = isReadableStreamSupported && + test(() => utils.isReadableStream(new Response('').body)); + + +const resolvers = { + stream: supportsResponseStream && ((res) => res.body) +}; + +isFetchSupported && (((res) => { + ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => { + !resolvers[type] && (resolvers[type] = utils.isFunction(res[type]) ? (res) => res[type]() : + (_, config) => { + throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config); + }) + }); +})(new Response)); + +const getBodyLength = async (body) => { + if (body == null) { + return 0; + } + + if(utils.isBlob(body)) { + return body.size; + } + + if(utils.isSpecCompliantForm(body)) { + const _request = new Request(platform.origin, { + method: 'POST', + body, + }); + return (await _request.arrayBuffer()).byteLength; + } + + if(utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) { + return body.byteLength; + } + + if(utils.isURLSearchParams(body)) { + body = body + ''; + } + + if(utils.isString(body)) { + return (await encodeText(body)).byteLength; + } +} + +const resolveBodyLength = async (headers, body) => { + const length = utils.toFiniteNumber(headers.getContentLength()); + + return length == null ? getBodyLength(body) : length; +} + +export default isFetchSupported && (async (config) => { + let { + url, + method, + data, + signal, + cancelToken, + timeout, + onDownloadProgress, + onUploadProgress, + responseType, + headers, + withCredentials = 'same-origin', + fetchOptions + } = resolveConfig(config); + + responseType = responseType ? (responseType + '').toLowerCase() : 'text'; + + let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + + let request; + + const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { + composedSignal.unsubscribe(); + }); + + let requestContentLength; + + try { + if ( + onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && + (requestContentLength = await resolveBodyLength(headers, data)) !== 0 + ) { + let _request = new Request(url, { + method: 'POST', + body: data, + duplex: "half" + }); + + let contentTypeHeader; + + if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { + headers.setContentType(contentTypeHeader) + } + + if (_request.body) { + const [onProgress, flush] = progressEventDecorator( + requestContentLength, + progressEventReducer(asyncDecorator(onUploadProgress)) + ); + + data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); + } + } + + if (!utils.isString(withCredentials)) { + withCredentials = withCredentials ? 'include' : 'omit'; + } + + // Cloudflare Workers throws when credentials are defined + // see https://github.com/cloudflare/workerd/issues/902 + const isCredentialsSupported = "credentials" in Request.prototype; + request = new Request(url, { + ...fetchOptions, + signal: composedSignal, + method: method.toUpperCase(), + headers: headers.normalize().toJSON(), + body: data, + duplex: "half", + credentials: isCredentialsSupported ? withCredentials : undefined + }); + + let response = await fetch(request); + + const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); + + if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) { + const options = {}; + + ['status', 'statusText', 'headers'].forEach(prop => { + options[prop] = response[prop]; + }); + + const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length')); + + const [onProgress, flush] = onDownloadProgress && progressEventDecorator( + responseContentLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true) + ) || []; + + response = new Response( + trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { + flush && flush(); + unsubscribe && unsubscribe(); + }), + options + ); + } + + responseType = responseType || 'text'; + + let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config); + + !isStreamResponse && unsubscribe && unsubscribe(); + + return await new Promise((resolve, reject) => { + settle(resolve, reject, { + data: responseData, + headers: AxiosHeaders.from(response.headers), + status: response.status, + statusText: response.statusText, + config, + request + }) + }) + } catch (err) { + unsubscribe && unsubscribe(); + + if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) { + throw Object.assign( + new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request), + { + cause: err.cause || err + } + ) + } + + throw AxiosError.from(err, err && err.code, config, request); + } +}); + + diff --git a/node_modules/axios/lib/adapters/http.js b/node_modules/axios/lib/adapters/http.js new file mode 100755 index 000000000..da0a42d91 --- /dev/null +++ b/node_modules/axios/lib/adapters/http.js @@ -0,0 +1,695 @@ +'use strict'; + +import utils from './../utils.js'; +import settle from './../core/settle.js'; +import buildFullPath from '../core/buildFullPath.js'; +import buildURL from './../helpers/buildURL.js'; +import proxyFromEnv from 'proxy-from-env'; +import http from 'http'; +import https from 'https'; +import util from 'util'; +import followRedirects from 'follow-redirects'; +import zlib from 'zlib'; +import {VERSION} from '../env/data.js'; +import transitionalDefaults from '../defaults/transitional.js'; +import AxiosError from '../core/AxiosError.js'; +import CanceledError from '../cancel/CanceledError.js'; +import platform from '../platform/index.js'; +import fromDataURI from '../helpers/fromDataURI.js'; +import stream from 'stream'; +import AxiosHeaders from '../core/AxiosHeaders.js'; +import AxiosTransformStream from '../helpers/AxiosTransformStream.js'; +import {EventEmitter} from 'events'; +import formDataToStream from "../helpers/formDataToStream.js"; +import readBlob from "../helpers/readBlob.js"; +import ZlibHeaderTransformStream from '../helpers/ZlibHeaderTransformStream.js'; +import callbackify from "../helpers/callbackify.js"; +import {progressEventReducer, progressEventDecorator, asyncDecorator} from "../helpers/progressEventReducer.js"; + +const zlibOptions = { + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH +}; + +const brotliOptions = { + flush: zlib.constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH +} + +const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress); + +const {http: httpFollow, https: httpsFollow} = followRedirects; + +const isHttps = /https:?/; + +const supportedProtocols = platform.protocols.map(protocol => { + return protocol + ':'; +}); + +const flushOnFinish = (stream, [throttled, flush]) => { + stream + .on('end', flush) + .on('error', flush); + + return throttled; +} + +/** + * If the proxy or config beforeRedirects functions are defined, call them with the options + * object. + * + * @param {Object} options - The options object that was passed to the request. + * + * @returns {Object} + */ +function dispatchBeforeRedirect(options, responseDetails) { + if (options.beforeRedirects.proxy) { + options.beforeRedirects.proxy(options); + } + if (options.beforeRedirects.config) { + options.beforeRedirects.config(options, responseDetails); + } +} + +/** + * If the proxy or config afterRedirects functions are defined, call them with the options + * + * @param {http.ClientRequestArgs} options + * @param {AxiosProxyConfig} configProxy configuration from Axios options object + * @param {string} location + * + * @returns {http.ClientRequestArgs} + */ +function setProxy(options, configProxy, location) { + let proxy = configProxy; + if (!proxy && proxy !== false) { + const proxyUrl = proxyFromEnv.getProxyForUrl(location); + if (proxyUrl) { + proxy = new URL(proxyUrl); + } + } + if (proxy) { + // Basic proxy authorization + if (proxy.username) { + proxy.auth = (proxy.username || '') + ':' + (proxy.password || ''); + } + + if (proxy.auth) { + // Support proxy auth object form + if (proxy.auth.username || proxy.auth.password) { + proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || ''); + } + const base64 = Buffer + .from(proxy.auth, 'utf8') + .toString('base64'); + options.headers['Proxy-Authorization'] = 'Basic ' + base64; + } + + options.headers.host = options.hostname + (options.port ? ':' + options.port : ''); + const proxyHost = proxy.hostname || proxy.host; + options.hostname = proxyHost; + // Replace 'host' since options is not a URL object + options.host = proxyHost; + options.port = proxy.port; + options.path = location; + if (proxy.protocol) { + options.protocol = proxy.protocol.includes(':') ? proxy.protocol : `${proxy.protocol}:`; + } + } + + options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) { + // Configure proxy for redirected request, passing the original config proxy to apply + // the exact same logic as if the redirected request was performed by axios directly. + setProxy(redirectOptions, configProxy, redirectOptions.href); + }; +} + +const isHttpAdapterSupported = typeof process !== 'undefined' && utils.kindOf(process) === 'process'; + +// temporary hotfix + +const wrapAsync = (asyncExecutor) => { + return new Promise((resolve, reject) => { + let onDone; + let isDone; + + const done = (value, isRejected) => { + if (isDone) return; + isDone = true; + onDone && onDone(value, isRejected); + } + + const _resolve = (value) => { + done(value); + resolve(value); + }; + + const _reject = (reason) => { + done(reason, true); + reject(reason); + } + + asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject); + }) +}; + +const resolveFamily = ({address, family}) => { + if (!utils.isString(address)) { + throw TypeError('address must be a string'); + } + return ({ + address, + family: family || (address.indexOf('.') < 0 ? 6 : 4) + }); +} + +const buildAddressEntry = (address, family) => resolveFamily(utils.isObject(address) ? address : {address, family}); + +/*eslint consistent-return:0*/ +export default isHttpAdapterSupported && function httpAdapter(config) { + return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) { + let {data, lookup, family} = config; + const {responseType, responseEncoding} = config; + const method = config.method.toUpperCase(); + let isDone; + let rejected = false; + let req; + + if (lookup) { + const _lookup = callbackify(lookup, (value) => utils.isArray(value) ? value : [value]); + // hotfix to support opt.all option which is required for node 20.x + lookup = (hostname, opt, cb) => { + _lookup(hostname, opt, (err, arg0, arg1) => { + if (err) { + return cb(err); + } + + const addresses = utils.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)]; + + opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); + }); + } + } + + // temporary internal emitter until the AxiosRequest class will be implemented + const emitter = new EventEmitter(); + + const onFinished = () => { + if (config.cancelToken) { + config.cancelToken.unsubscribe(abort); + } + + if (config.signal) { + config.signal.removeEventListener('abort', abort); + } + + emitter.removeAllListeners(); + } + + onDone((value, isRejected) => { + isDone = true; + if (isRejected) { + rejected = true; + onFinished(); + } + }); + + function abort(reason) { + emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason); + } + + emitter.once('abort', reject); + + if (config.cancelToken || config.signal) { + config.cancelToken && config.cancelToken.subscribe(abort); + if (config.signal) { + config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort); + } + } + + // Parse url + const fullPath = buildFullPath(config.baseURL, config.url); + const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined); + const protocol = parsed.protocol || supportedProtocols[0]; + + if (protocol === 'data:') { + let convertedData; + + if (method !== 'GET') { + return settle(resolve, reject, { + status: 405, + statusText: 'method not allowed', + headers: {}, + config + }); + } + + try { + convertedData = fromDataURI(config.url, responseType === 'blob', { + Blob: config.env && config.env.Blob + }); + } catch (err) { + throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config); + } + + if (responseType === 'text') { + convertedData = convertedData.toString(responseEncoding); + + if (!responseEncoding || responseEncoding === 'utf8') { + convertedData = utils.stripBOM(convertedData); + } + } else if (responseType === 'stream') { + convertedData = stream.Readable.from(convertedData); + } + + return settle(resolve, reject, { + data: convertedData, + status: 200, + statusText: 'OK', + headers: new AxiosHeaders(), + config + }); + } + + if (supportedProtocols.indexOf(protocol) === -1) { + return reject(new AxiosError( + 'Unsupported protocol ' + protocol, + AxiosError.ERR_BAD_REQUEST, + config + )); + } + + const headers = AxiosHeaders.from(config.headers).normalize(); + + // Set User-Agent (required by some servers) + // See https://github.com/axios/axios/issues/69 + // User-Agent is specified; handle case where no UA header is desired + // Only set header if it hasn't been set in config + headers.set('User-Agent', 'axios/' + VERSION, false); + + const {onUploadProgress, onDownloadProgress} = config; + const maxRate = config.maxRate; + let maxUploadRate = undefined; + let maxDownloadRate = undefined; + + // support for spec compliant FormData objects + if (utils.isSpecCompliantForm(data)) { + const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); + + data = formDataToStream(data, (formHeaders) => { + headers.set(formHeaders); + }, { + tag: `axios-${VERSION}-boundary`, + boundary: userBoundary && userBoundary[1] || undefined + }); + // support for https://www.npmjs.com/package/form-data api + } else if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) { + headers.set(data.getHeaders()); + + if (!headers.hasContentLength()) { + try { + const knownLength = await util.promisify(data.getLength).call(data); + Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength); + /*eslint no-empty:0*/ + } catch (e) { + } + } + } else if (utils.isBlob(data) || utils.isFile(data)) { + data.size && headers.setContentType(data.type || 'application/octet-stream'); + headers.setContentLength(data.size || 0); + data = stream.Readable.from(readBlob(data)); + } else if (data && !utils.isStream(data)) { + if (Buffer.isBuffer(data)) { + // Nothing to do... + } else if (utils.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils.isString(data)) { + data = Buffer.from(data, 'utf-8'); + } else { + return reject(new AxiosError( + 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', + AxiosError.ERR_BAD_REQUEST, + config + )); + } + + // Add Content-Length header if data exists + headers.setContentLength(data.length, false); + + if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) { + return reject(new AxiosError( + 'Request body larger than maxBodyLength limit', + AxiosError.ERR_BAD_REQUEST, + config + )); + } + } + + const contentLength = utils.toFiniteNumber(headers.getContentLength()); + + if (utils.isArray(maxRate)) { + maxUploadRate = maxRate[0]; + maxDownloadRate = maxRate[1]; + } else { + maxUploadRate = maxDownloadRate = maxRate; + } + + if (data && (onUploadProgress || maxUploadRate)) { + if (!utils.isStream(data)) { + data = stream.Readable.from(data, {objectMode: false}); + } + + data = stream.pipeline([data, new AxiosTransformStream({ + maxRate: utils.toFiniteNumber(maxUploadRate) + })], utils.noop); + + onUploadProgress && data.on('progress', flushOnFinish( + data, + progressEventDecorator( + contentLength, + progressEventReducer(asyncDecorator(onUploadProgress), false, 3) + ) + )); + } + + // HTTP basic authentication + let auth = undefined; + if (config.auth) { + const username = config.auth.username || ''; + const password = config.auth.password || ''; + auth = username + ':' + password; + } + + if (!auth && parsed.username) { + const urlUsername = parsed.username; + const urlPassword = parsed.password; + auth = urlUsername + ':' + urlPassword; + } + + auth && headers.delete('authorization'); + + let path; + + try { + path = buildURL( + parsed.pathname + parsed.search, + config.params, + config.paramsSerializer + ).replace(/^\?/, ''); + } catch (err) { + const customErr = new Error(err.message); + customErr.config = config; + customErr.url = config.url; + customErr.exists = true; + return reject(customErr); + } + + headers.set( + 'Accept-Encoding', + 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false + ); + + const options = { + path, + method: method, + headers: headers.toJSON(), + agents: { http: config.httpAgent, https: config.httpsAgent }, + auth, + protocol, + family, + beforeRedirect: dispatchBeforeRedirect, + beforeRedirects: {} + }; + + // cacheable-lookup integration hotfix + !utils.isUndefined(lookup) && (options.lookup = lookup); + + if (config.socketPath) { + options.socketPath = config.socketPath; + } else { + options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname; + options.port = parsed.port; + setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); + } + + let transport; + const isHttpsRequest = isHttps.test(options.protocol); + options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; + if (config.transport) { + transport = config.transport; + } else if (config.maxRedirects === 0) { + transport = isHttpsRequest ? https : http; + } else { + if (config.maxRedirects) { + options.maxRedirects = config.maxRedirects; + } + if (config.beforeRedirect) { + options.beforeRedirects.config = config.beforeRedirect; + } + transport = isHttpsRequest ? httpsFollow : httpFollow; + } + + if (config.maxBodyLength > -1) { + options.maxBodyLength = config.maxBodyLength; + } else { + // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited + options.maxBodyLength = Infinity; + } + + if (config.insecureHTTPParser) { + options.insecureHTTPParser = config.insecureHTTPParser; + } + + // Create the request + req = transport.request(options, function handleResponse(res) { + if (req.destroyed) return; + + const streams = [res]; + + const responseLength = +res.headers['content-length']; + + if (onDownloadProgress || maxDownloadRate) { + const transformStream = new AxiosTransformStream({ + maxRate: utils.toFiniteNumber(maxDownloadRate) + }); + + onDownloadProgress && transformStream.on('progress', flushOnFinish( + transformStream, + progressEventDecorator( + responseLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) + ) + )); + + streams.push(transformStream); + } + + // decompress the response body transparently if required + let responseStream = res; + + // return the last request in case of redirects + const lastRequest = res.req || req; + + // if decompress disabled we should not decompress + if (config.decompress !== false && res.headers['content-encoding']) { + // if no content, but headers still say that it is encoded, + // remove the header not confuse downstream operations + if (method === 'HEAD' || res.statusCode === 204) { + delete res.headers['content-encoding']; + } + + switch ((res.headers['content-encoding'] || '').toLowerCase()) { + /*eslint default-case:0*/ + case 'gzip': + case 'x-gzip': + case 'compress': + case 'x-compress': + // add the unzipper to the body stream processing pipeline + streams.push(zlib.createUnzip(zlibOptions)); + + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; + case 'deflate': + streams.push(new ZlibHeaderTransformStream()); + + // add the unzipper to the body stream processing pipeline + streams.push(zlib.createUnzip(zlibOptions)); + + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; + case 'br': + if (isBrotliSupported) { + streams.push(zlib.createBrotliDecompress(brotliOptions)); + delete res.headers['content-encoding']; + } + } + } + + responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0]; + + const offListeners = stream.finished(responseStream, () => { + offListeners(); + onFinished(); + }); + + const response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: new AxiosHeaders(res.headers), + config, + request: lastRequest + }; + + if (responseType === 'stream') { + response.data = responseStream; + settle(resolve, reject, response); + } else { + const responseBuffer = []; + let totalResponseBytes = 0; + + responseStream.on('data', function handleStreamData(chunk) { + responseBuffer.push(chunk); + totalResponseBytes += chunk.length; + + // make sure the content length is not over the maxContentLength if specified + if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) { + // stream.destroy() emit aborted event before calling reject() on Node.js v16 + rejected = true; + responseStream.destroy(); + reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, config, lastRequest)); + } + }); + + responseStream.on('aborted', function handlerStreamAborted() { + if (rejected) { + return; + } + + const err = new AxiosError( + 'stream has been aborted', + AxiosError.ERR_BAD_RESPONSE, + config, + lastRequest + ); + responseStream.destroy(err); + reject(err); + }); + + responseStream.on('error', function handleStreamError(err) { + if (req.destroyed) return; + reject(AxiosError.from(err, null, config, lastRequest)); + }); + + responseStream.on('end', function handleStreamEnd() { + try { + let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); + if (responseType !== 'arraybuffer') { + responseData = responseData.toString(responseEncoding); + if (!responseEncoding || responseEncoding === 'utf8') { + responseData = utils.stripBOM(responseData); + } + } + response.data = responseData; + } catch (err) { + return reject(AxiosError.from(err, null, config, response.request, response)); + } + settle(resolve, reject, response); + }); + } + + emitter.once('abort', err => { + if (!responseStream.destroyed) { + responseStream.emit('error', err); + responseStream.destroy(); + } + }); + }); + + emitter.once('abort', err => { + reject(err); + req.destroy(err); + }); + + // Handle errors + req.on('error', function handleRequestError(err) { + // @todo remove + // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return; + reject(AxiosError.from(err, null, config, req)); + }); + + // set tcp keep alive to prevent drop connection by peer + req.on('socket', function handleRequestSocket(socket) { + // default interval of sending ack packet is 1 minute + socket.setKeepAlive(true, 1000 * 60); + }); + + // Handle request timeout + if (config.timeout) { + // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types. + const timeout = parseInt(config.timeout, 10); + + if (Number.isNaN(timeout)) { + reject(new AxiosError( + 'error trying to parse `config.timeout` to int', + AxiosError.ERR_BAD_OPTION_VALUE, + config, + req + )); + + return; + } + + // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. + // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. + // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. + // And then these socket which be hang up will devouring CPU little by little. + // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. + req.setTimeout(timeout, function handleRequestTimeout() { + if (isDone) return; + let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; + const transitional = config.transitional || transitionalDefaults; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + req + )); + abort(); + }); + } + + + // Send the request + if (utils.isStream(data)) { + let ended = false; + let errored = false; + + data.on('end', () => { + ended = true; + }); + + data.once('error', err => { + errored = true; + req.destroy(err); + }); + + data.on('close', () => { + if (!ended && !errored) { + abort(new CanceledError('Request stream has been aborted', config, req)); + } + }); + + data.pipe(req); + } else { + req.end(data); + } + }); +} + +export const __setProxy = setProxy; diff --git a/node_modules/axios/lib/adapters/xhr.js b/node_modules/axios/lib/adapters/xhr.js new file mode 100644 index 000000000..a7ee548ce --- /dev/null +++ b/node_modules/axios/lib/adapters/xhr.js @@ -0,0 +1,197 @@ +import utils from './../utils.js'; +import settle from './../core/settle.js'; +import transitionalDefaults from '../defaults/transitional.js'; +import AxiosError from '../core/AxiosError.js'; +import CanceledError from '../cancel/CanceledError.js'; +import parseProtocol from '../helpers/parseProtocol.js'; +import platform from '../platform/index.js'; +import AxiosHeaders from '../core/AxiosHeaders.js'; +import {progressEventReducer} from '../helpers/progressEventReducer.js'; +import resolveConfig from "../helpers/resolveConfig.js"; + +const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; + +export default isXHRAdapterSupported && function (config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + const _config = resolveConfig(config); + let requestData = _config.data; + const requestHeaders = AxiosHeaders.from(_config.headers).normalize(); + let {responseType, onUploadProgress, onDownloadProgress} = _config; + let onCanceled; + let uploadThrottled, downloadThrottled; + let flushUpload, flushDownload; + + function done() { + flushUpload && flushUpload(); // flush events + flushDownload && flushDownload(); // flush events + + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + + _config.signal && _config.signal.removeEventListener('abort', onCanceled); + } + + let request = new XMLHttpRequest(); + + request.open(_config.method.toUpperCase(), _config.url, true); + + // Set the request timeout in MS + request.timeout = _config.timeout; + + function onloadend() { + if (!request) { + return; + } + // Prepare the response + const responseHeaders = AxiosHeaders.from( + 'getAllResponseHeaders' in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === 'text' || responseType === 'json' ? + request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config, + request + }; + + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + + // Clean up request + request = null; + } + + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded'; + const transitional = _config.transitional || transitionalDefaults; + if (_config.timeoutErrorMessage) { + timeoutErrorMessage = _config.timeoutErrorMessage; + } + reject(new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + request)); + + // Clean up request + request = null; + }; + + // Remove Content-Type if data is undefined + requestData === undefined && requestHeaders.setContentType(null); + + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + + // Add withCredentials to request if needed + if (!utils.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; + } + + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = _config.responseType; + } + + // Handle progress if needed + if (onDownloadProgress) { + ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true)); + request.addEventListener('progress', downloadThrottled); + } + + // Not all browsers support upload events + if (onUploadProgress && request.upload) { + ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress)); + + request.upload.addEventListener('progress', uploadThrottled); + + request.upload.addEventListener('loadend', flushUpload); + } + + if (_config.cancelToken || _config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = cancel => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); + request.abort(); + request = null; + }; + + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled); + } + } + + const protocol = parseProtocol(_config.url); + + if (protocol && platform.protocols.indexOf(protocol) === -1) { + reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); + return; + } + + + // Send the request + request.send(requestData || null); + }); +} diff --git a/node_modules/axios/lib/axios.js b/node_modules/axios/lib/axios.js new file mode 100644 index 000000000..873f246da --- /dev/null +++ b/node_modules/axios/lib/axios.js @@ -0,0 +1,89 @@ +'use strict'; + +import utils from './utils.js'; +import bind from './helpers/bind.js'; +import Axios from './core/Axios.js'; +import mergeConfig from './core/mergeConfig.js'; +import defaults from './defaults/index.js'; +import formDataToJSON from './helpers/formDataToJSON.js'; +import CanceledError from './cancel/CanceledError.js'; +import CancelToken from './cancel/CancelToken.js'; +import isCancel from './cancel/isCancel.js'; +import {VERSION} from './env/data.js'; +import toFormData from './helpers/toFormData.js'; +import AxiosError from './core/AxiosError.js'; +import spread from './helpers/spread.js'; +import isAxiosError from './helpers/isAxiosError.js'; +import AxiosHeaders from "./core/AxiosHeaders.js"; +import adapters from './adapters/adapters.js'; +import HttpStatusCode from './helpers/HttpStatusCode.js'; + +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * + * @returns {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + const context = new Axios(defaultConfig); + const instance = bind(Axios.prototype.request, context); + + // Copy axios.prototype to instance + utils.extend(instance, Axios.prototype, context, {allOwnKeys: true}); + + // Copy context to instance + utils.extend(instance, context, null, {allOwnKeys: true}); + + // Factory for creating new instances + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; + + return instance; +} + +// Create the default instance to be exported +const axios = createInstance(defaults); + +// Expose Axios class to allow class inheritance +axios.Axios = Axios; + +// Expose Cancel & CancelToken +axios.CanceledError = CanceledError; +axios.CancelToken = CancelToken; +axios.isCancel = isCancel; +axios.VERSION = VERSION; +axios.toFormData = toFormData; + +// Expose AxiosError class +axios.AxiosError = AxiosError; + +// alias for CanceledError for backward compatibility +axios.Cancel = axios.CanceledError; + +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; + +axios.spread = spread; + +// Expose isAxiosError +axios.isAxiosError = isAxiosError; + +// Expose mergeConfig +axios.mergeConfig = mergeConfig; + +axios.AxiosHeaders = AxiosHeaders; + +axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing); + +axios.getAdapter = adapters.getAdapter; + +axios.HttpStatusCode = HttpStatusCode; + +axios.default = axios; + +// this module should only have a default export +export default axios diff --git a/node_modules/axios/lib/cancel/CancelToken.js b/node_modules/axios/lib/cancel/CancelToken.js new file mode 100644 index 000000000..0fc202525 --- /dev/null +++ b/node_modules/axios/lib/cancel/CancelToken.js @@ -0,0 +1,135 @@ +'use strict'; + +import CanceledError from './CanceledError.js'; + +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @param {Function} executor The executor function. + * + * @returns {CancelToken} + */ +class CancelToken { + constructor(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + let resolvePromise; + + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + const token = this; + + // eslint-disable-next-line func-names + this.promise.then(cancel => { + if (!token._listeners) return; + + let i = token._listeners.length; + + while (i-- > 0) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + + // eslint-disable-next-line func-names + this.promise.then = onfulfilled => { + let _resolve; + // eslint-disable-next-line func-names + const promise = new Promise(resolve => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + + return promise; + }; + + executor(function cancel(message, config, request) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new CanceledError(message, config, request); + resolvePromise(token.reason); + }); + } + + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } + + /** + * Subscribe to the cancel signal + */ + + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } + + /** + * Unsubscribe from the cancel signal + */ + + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } + } + + toAbortSignal() { + const controller = new AbortController(); + + const abort = (err) => { + controller.abort(err); + }; + + this.subscribe(abort); + + controller.signal.unsubscribe = () => this.unsubscribe(abort); + + return controller.signal; + } + + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + static source() { + let cancel; + const token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token, + cancel + }; + } +} + +export default CancelToken; diff --git a/node_modules/axios/lib/cancel/CanceledError.js b/node_modules/axios/lib/cancel/CanceledError.js new file mode 100644 index 000000000..880066edf --- /dev/null +++ b/node_modules/axios/lib/cancel/CanceledError.js @@ -0,0 +1,25 @@ +'use strict'; + +import AxiosError from '../core/AxiosError.js'; +import utils from '../utils.js'; + +/** + * A `CanceledError` is an object that is thrown when an operation is canceled. + * + * @param {string=} message The message. + * @param {Object=} config The config. + * @param {Object=} request The request. + * + * @returns {CanceledError} The created error. + */ +function CanceledError(message, config, request) { + // eslint-disable-next-line no-eq-null,eqeqeq + AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); + this.name = 'CanceledError'; +} + +utils.inherits(CanceledError, AxiosError, { + __CANCEL__: true +}); + +export default CanceledError; diff --git a/node_modules/axios/lib/cancel/isCancel.js b/node_modules/axios/lib/cancel/isCancel.js new file mode 100644 index 000000000..a444a129d --- /dev/null +++ b/node_modules/axios/lib/cancel/isCancel.js @@ -0,0 +1,5 @@ +'use strict'; + +export default function isCancel(value) { + return !!(value && value.__CANCEL__); +} diff --git a/node_modules/axios/lib/core/Axios.js b/node_modules/axios/lib/core/Axios.js new file mode 100644 index 000000000..6dd3c2cbd --- /dev/null +++ b/node_modules/axios/lib/core/Axios.js @@ -0,0 +1,233 @@ +'use strict'; + +import utils from './../utils.js'; +import buildURL from '../helpers/buildURL.js'; +import InterceptorManager from './InterceptorManager.js'; +import dispatchRequest from './dispatchRequest.js'; +import mergeConfig from './mergeConfig.js'; +import buildFullPath from './buildFullPath.js'; +import validator from '../helpers/validator.js'; +import AxiosHeaders from './AxiosHeaders.js'; + +const validators = validator.validators; + +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + * + * @return {Axios} A new instance of Axios + */ +class Axios { + constructor(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager(), + response: new InterceptorManager() + }; + } + + /** + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled + */ + async request(configOrUrl, config) { + try { + return await this._request(configOrUrl, config); + } catch (err) { + if (err instanceof Error) { + let dummy = {}; + + Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error()); + + // slice off the Error: ... line + const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : ''; + try { + if (!err.stack) { + err.stack = stack; + // match without the 2 top stack lines + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) { + err.stack += '\n' + stack + } + } catch (e) { + // ignore the case where "stack" is an un-writable property + } + } + + throw err; + } + } + + _request(configOrUrl, config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof configOrUrl === 'string') { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } + + config = mergeConfig(this.defaults, config); + + const {transitional, paramsSerializer, headers} = config; + + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators.boolean), + forcedJSONParsing: validators.transitional(validators.boolean), + clarifyTimeoutError: validators.transitional(validators.boolean) + }, false); + } + + if (paramsSerializer != null) { + if (utils.isFunction(paramsSerializer)) { + config.paramsSerializer = { + serialize: paramsSerializer + } + } else { + validator.assertOptions(paramsSerializer, { + encode: validators.function, + serialize: validators.function + }, true); + } + } + + validator.assertOptions(config, { + baseUrl: validators.spelling('baseURL'), + withXsrfToken: validators.spelling('withXSRFToken') + }, true); + + // Set config.method + config.method = (config.method || this.defaults.method || 'get').toLowerCase(); + + // Flatten headers + let contextHeaders = headers && utils.merge( + headers.common, + headers[config.method] + ); + + headers && utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + (method) => { + delete headers[method]; + } + ); + + config.headers = AxiosHeaders.concat(contextHeaders, headers); + + // filter out skipped interceptors + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + + let promise; + let i = 0; + let len; + + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), undefined]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + + promise = Promise.resolve(config); + + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + + return promise; + } + + len = requestInterceptorChain.length; + + let newConfig = config; + + i = 0; + + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + + i = 0; + len = responseInterceptorChain.length; + + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + + return promise; + } + + getUri(config) { + config = mergeConfig(this.defaults, config); + const fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); + } +} + +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method, + url, + data: (config || {}).data + })); + }; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig(config || {}, { + method, + headers: isForm ? { + 'Content-Type': 'multipart/form-data' + } : {}, + url, + data + })); + }; + } + + Axios.prototype[method] = generateHTTPMethod(); + + Axios.prototype[method + 'Form'] = generateHTTPMethod(true); +}); + +export default Axios; diff --git a/node_modules/axios/lib/core/AxiosError.js b/node_modules/axios/lib/core/AxiosError.js new file mode 100644 index 000000000..73da248bb --- /dev/null +++ b/node_modules/axios/lib/core/AxiosError.js @@ -0,0 +1,103 @@ +'use strict'; + +import utils from '../utils.js'; + +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [config] The config. + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * + * @returns {Error} The created error. + */ +function AxiosError(message, code, config, request, response) { + Error.call(this); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = (new Error()).stack; + } + + this.message = message; + this.name = 'AxiosError'; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status ? response.status : null; + } +} + +utils.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils.toJSONObject(this.config), + code: this.code, + status: this.status + }; + } +}); + +const prototype = AxiosError.prototype; +const descriptors = {}; + +[ + 'ERR_BAD_OPTION_VALUE', + 'ERR_BAD_OPTION', + 'ECONNABORTED', + 'ETIMEDOUT', + 'ERR_NETWORK', + 'ERR_FR_TOO_MANY_REDIRECTS', + 'ERR_DEPRECATED', + 'ERR_BAD_RESPONSE', + 'ERR_BAD_REQUEST', + 'ERR_CANCELED', + 'ERR_NOT_SUPPORT', + 'ERR_INVALID_URL' +// eslint-disable-next-line func-names +].forEach(code => { + descriptors[code] = {value: code}; +}); + +Object.defineProperties(AxiosError, descriptors); +Object.defineProperty(prototype, 'isAxiosError', {value: true}); + +// eslint-disable-next-line func-names +AxiosError.from = (error, code, config, request, response, customProps) => { + const axiosError = Object.create(prototype); + + utils.toFlatObject(error, axiosError, function filter(obj) { + return obj !== Error.prototype; + }, prop => { + return prop !== 'isAxiosError'; + }); + + AxiosError.call(axiosError, error.message, code, config, request, response); + + axiosError.cause = error; + + axiosError.name = error.name; + + customProps && Object.assign(axiosError, customProps); + + return axiosError; +}; + +export default AxiosError; diff --git a/node_modules/axios/lib/core/AxiosHeaders.js b/node_modules/axios/lib/core/AxiosHeaders.js new file mode 100644 index 000000000..7b576e9e1 --- /dev/null +++ b/node_modules/axios/lib/core/AxiosHeaders.js @@ -0,0 +1,302 @@ +'use strict'; + +import utils from '../utils.js'; +import parseHeaders from '../helpers/parseHeaders.js'; + +const $internals = Symbol('internals'); + +function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); +} + +function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + + return utils.isArray(value) ? value.map(normalizeValue) : String(value); +} + +function parseTokens(str) { + const tokens = Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + + while ((match = tokensRE.exec(str))) { + tokens[match[1]] = match[2]; + } + + return tokens; +} + +const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); + +function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { + if (utils.isFunction(filter)) { + return filter.call(this, value, header); + } + + if (isHeaderNameFilter) { + value = header; + } + + if (!utils.isString(value)) return; + + if (utils.isString(filter)) { + return value.indexOf(filter) !== -1; + } + + if (utils.isRegExp(filter)) { + return filter.test(value); + } +} + +function formatHeader(header) { + return header.trim() + .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { + return char.toUpperCase() + str; + }); +} + +function buildAccessors(obj, header) { + const accessorName = utils.toCamelCase(' ' + header); + + ['get', 'set', 'has'].forEach(methodName => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); +} + +class AxiosHeaders { + constructor(headers) { + headers && this.set(headers); + } + + set(header, valueOrRewrite, rewrite) { + const self = this; + + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); + + if (!lHeader) { + throw new Error('header name must be a non-empty string'); + } + + const key = utils.findKey(self, lHeader); + + if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { + self[key || _header] = normalizeValue(_value); + } + } + + const setHeaders = (headers, _rewrite) => + utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + + if (utils.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite) + } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else if (utils.isHeaders(header)) { + for (const [key, value] of header.entries()) { + setHeader(value, key, rewrite); + } + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + + return this; + } + + get(header, parser) { + header = normalizeHeader(header); + + if (header) { + const key = utils.findKey(this, header); + + if (key) { + const value = this[key]; + + if (!parser) { + return value; + } + + if (parser === true) { + return parseTokens(value); + } + + if (utils.isFunction(parser)) { + return parser.call(this, value, key); + } + + if (utils.isRegExp(parser)) { + return parser.exec(value); + } + + throw new TypeError('parser must be boolean|regexp|function'); + } + } + } + + has(header, matcher) { + header = normalizeHeader(header); + + if (header) { + const key = utils.findKey(this, header); + + return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + } + + return false; + } + + delete(header, matcher) { + const self = this; + let deleted = false; + + function deleteHeader(_header) { + _header = normalizeHeader(_header); + + if (_header) { + const key = utils.findKey(self, _header); + + if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { + delete self[key]; + + deleted = true; + } + } + } + + if (utils.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + + return deleted; + } + + clear(matcher) { + const keys = Object.keys(this); + let i = keys.length; + let deleted = false; + + while (i--) { + const key = keys[i]; + if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + + return deleted; + } + + normalize(format) { + const self = this; + const headers = {}; + + utils.forEach(this, (value, header) => { + const key = utils.findKey(headers, header); + + if (key) { + self[key] = normalizeValue(value); + delete self[header]; + return; + } + + const normalized = format ? formatHeader(header) : String(header).trim(); + + if (normalized !== header) { + delete self[header]; + } + + self[normalized] = normalizeValue(value); + + headers[normalized] = true; + }); + + return this; + } + + concat(...targets) { + return this.constructor.concat(this, ...targets); + } + + toJSON(asStrings) { + const obj = Object.create(null); + + utils.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value); + }); + + return obj; + } + + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n'); + } + + get [Symbol.toStringTag]() { + return 'AxiosHeaders'; + } + + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + + static concat(first, ...targets) { + const computed = new this(first); + + targets.forEach((target) => computed.set(target)); + + return computed; + } + + static accessor(header) { + const internals = this[$internals] = (this[$internals] = { + accessors: {} + }); + + const accessors = internals.accessors; + const prototype = this.prototype; + + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); + + if (!accessors[lHeader]) { + buildAccessors(prototype, _header); + accessors[lHeader] = true; + } + } + + utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + + return this; + } +} + +AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); + +// reserved names hotfix +utils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } + } +}); + +utils.freezeMethods(AxiosHeaders); + +export default AxiosHeaders; diff --git a/node_modules/axios/lib/core/InterceptorManager.js b/node_modules/axios/lib/core/InterceptorManager.js new file mode 100644 index 000000000..6657a9d2d --- /dev/null +++ b/node_modules/axios/lib/core/InterceptorManager.js @@ -0,0 +1,71 @@ +'use strict'; + +import utils from './../utils.js'; + +class InterceptorManager { + constructor() { + this.handlers = []; + } + + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + */ + eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; + } + } + + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + } +} + +export default InterceptorManager; diff --git a/node_modules/axios/lib/core/README.md b/node_modules/axios/lib/core/README.md new file mode 100644 index 000000000..84559ce7c --- /dev/null +++ b/node_modules/axios/lib/core/README.md @@ -0,0 +1,8 @@ +# axios // core + +The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are: + +- Dispatching requests + - Requests sent via `adapters/` (see lib/adapters/README.md) +- Managing interceptors +- Handling config diff --git a/node_modules/axios/lib/core/buildFullPath.js b/node_modules/axios/lib/core/buildFullPath.js new file mode 100644 index 000000000..b60927c0a --- /dev/null +++ b/node_modules/axios/lib/core/buildFullPath.js @@ -0,0 +1,21 @@ +'use strict'; + +import isAbsoluteURL from '../helpers/isAbsoluteURL.js'; +import combineURLs from '../helpers/combineURLs.js'; + +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * + * @returns {string} The combined full path + */ +export default function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +} diff --git a/node_modules/axios/lib/core/dispatchRequest.js b/node_modules/axios/lib/core/dispatchRequest.js new file mode 100644 index 000000000..9e306aac4 --- /dev/null +++ b/node_modules/axios/lib/core/dispatchRequest.js @@ -0,0 +1,81 @@ +'use strict'; + +import transformData from './transformData.js'; +import isCancel from '../cancel/isCancel.js'; +import defaults from '../defaults/index.js'; +import CanceledError from '../cancel/CanceledError.js'; +import AxiosHeaders from '../core/AxiosHeaders.js'; +import adapters from "../adapters/adapters.js"; + +/** + * Throws a `CanceledError` if cancellation has been requested. + * + * @param {Object} config The config that is to be used for the request + * + * @returns {void} + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + + if (config.signal && config.signal.aborted) { + throw new CanceledError(null, config); + } +} + +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * + * @returns {Promise} The Promise to be fulfilled + */ +export default function dispatchRequest(config) { + throwIfCancellationRequested(config); + + config.headers = AxiosHeaders.from(config.headers); + + // Transform request data + config.data = transformData.call( + config, + config.transformRequest + ); + + if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { + config.headers.setContentType('application/x-www-form-urlencoded', false); + } + + const adapter = adapters.getAdapter(config.adapter || defaults.adapter); + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData.call( + config, + config.transformResponse, + response + ); + + response.headers = AxiosHeaders.from(response.headers); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + config.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders.from(reason.response.headers); + } + } + + return Promise.reject(reason); + }); +} diff --git a/node_modules/axios/lib/core/mergeConfig.js b/node_modules/axios/lib/core/mergeConfig.js new file mode 100644 index 000000000..c510073fc --- /dev/null +++ b/node_modules/axios/lib/core/mergeConfig.js @@ -0,0 +1,106 @@ +'use strict'; + +import utils from '../utils.js'; +import AxiosHeaders from "./AxiosHeaders.js"; + +const headersToObject = (thing) => thing instanceof AxiosHeaders ? { ...thing } : thing; + +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * + * @returns {Object} New object resulting from merging config2 to config1 + */ +export default function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + const config = {}; + + function getMergedValue(target, source, prop, caseless) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge.call({caseless}, target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } + + // eslint-disable-next-line consistent-return + function mergeDeepProperties(a, b, prop , caseless) { + if (!utils.isUndefined(b)) { + return getMergedValue(a, b, prop , caseless); + } else if (!utils.isUndefined(a)) { + return getMergedValue(undefined, a, prop , caseless); + } + } + + // eslint-disable-next-line consistent-return + function valueFromConfig2(a, b) { + if (!utils.isUndefined(b)) { + return getMergedValue(undefined, b); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(a, b) { + if (!utils.isUndefined(b)) { + return getMergedValue(undefined, b); + } else if (!utils.isUndefined(a)) { + return getMergedValue(undefined, a); + } + } + + // eslint-disable-next-line consistent-return + function mergeDirectKeys(a, b, prop) { + if (prop in config2) { + return getMergedValue(a, b); + } else if (prop in config1) { + return getMergedValue(undefined, a); + } + } + + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true) + }; + + utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + const merge = mergeMap[prop] || mergeDeepProperties; + const configValue = merge(config1[prop], config2[prop], prop); + (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); + + return config; +} diff --git a/node_modules/axios/lib/core/settle.js b/node_modules/axios/lib/core/settle.js new file mode 100644 index 000000000..ac905c432 --- /dev/null +++ b/node_modules/axios/lib/core/settle.js @@ -0,0 +1,27 @@ +'use strict'; + +import AxiosError from './AxiosError.js'; + +/** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + * + * @returns {object} The response. + */ +export default function settle(resolve, reject, response) { + const validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new AxiosError( + 'Request failed with status code ' + response.status, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } +} diff --git a/node_modules/axios/lib/core/transformData.js b/node_modules/axios/lib/core/transformData.js new file mode 100644 index 000000000..eeb5a8a18 --- /dev/null +++ b/node_modules/axios/lib/core/transformData.js @@ -0,0 +1,28 @@ +'use strict'; + +import utils from './../utils.js'; +import defaults from '../defaults/index.js'; +import AxiosHeaders from '../core/AxiosHeaders.js'; + +/** + * Transform the data for a request or a response + * + * @param {Array|Function} fns A single function or Array of functions + * @param {?Object} response The response object + * + * @returns {*} The resulting transformed data + */ +export default function transformData(fns, response) { + const config = this || defaults; + const context = response || config; + const headers = AxiosHeaders.from(context.headers); + let data = context.data; + + utils.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); + }); + + headers.normalize(); + + return data; +} diff --git a/node_modules/axios/lib/defaults/index.js b/node_modules/axios/lib/defaults/index.js new file mode 100644 index 000000000..e543fea27 --- /dev/null +++ b/node_modules/axios/lib/defaults/index.js @@ -0,0 +1,161 @@ +'use strict'; + +import utils from '../utils.js'; +import AxiosError from '../core/AxiosError.js'; +import transitionalDefaults from './transitional.js'; +import toFormData from '../helpers/toFormData.js'; +import toURLEncodedForm from '../helpers/toURLEncodedForm.js'; +import platform from '../platform/index.js'; +import formDataToJSON from '../helpers/formDataToJSON.js'; + +/** + * It takes a string, tries to parse it, and if it fails, it returns the stringified version + * of the input + * + * @param {any} rawValue - The value to be stringified. + * @param {Function} parser - A function that parses a string into a JavaScript object. + * @param {Function} encoder - A function that takes a value and returns a string. + * + * @returns {string} A stringified version of the rawValue. + */ +function stringifySafely(rawValue, parser, encoder) { + if (utils.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } + } + } + + return (encoder || JSON.stringify)(rawValue); +} + +const defaults = { + + transitional: transitionalDefaults, + + adapter: ['xhr', 'http', 'fetch'], + + transformRequest: [function transformRequest(data, headers) { + const contentType = headers.getContentType() || ''; + const hasJSONContentType = contentType.indexOf('application/json') > -1; + const isObjectPayload = utils.isObject(data); + + if (isObjectPayload && utils.isHTMLForm(data)) { + data = new FormData(data); + } + + const isFormData = utils.isFormData(data); + + if (isFormData) { + return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; + } + + if (utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) || + utils.isReadableStream(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); + return data.toString(); + } + + let isFileList; + + if (isObjectPayload) { + if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + + if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { + const _FormData = this.env && this.env.FormData; + + return toFormData( + isFileList ? {'files[]': data} : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + + if (isObjectPayload || hasJSONContentType ) { + headers.setContentType('application/json', false); + return stringifySafely(data); + } + + return data; + }], + + transformResponse: [function transformResponse(data) { + const transitional = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional && transitional.forcedJSONParsing; + const JSONRequested = this.responseType === 'json'; + + if (utils.isResponse(data) || utils.isReadableStream(data)) { + return data; + } + + if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { + const silentJSONParsing = transitional && transitional.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } + + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + + headers: { + common: { + 'Accept': 'application/json, text/plain, */*', + 'Content-Type': undefined + } + } +}; + +utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { + defaults.headers[method] = {}; +}); + +export default defaults; diff --git a/node_modules/axios/lib/defaults/transitional.js b/node_modules/axios/lib/defaults/transitional.js new file mode 100644 index 000000000..f89133196 --- /dev/null +++ b/node_modules/axios/lib/defaults/transitional.js @@ -0,0 +1,7 @@ +'use strict'; + +export default { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false +}; diff --git a/node_modules/axios/lib/env/README.md b/node_modules/axios/lib/env/README.md new file mode 100644 index 000000000..b41baff3c --- /dev/null +++ b/node_modules/axios/lib/env/README.md @@ -0,0 +1,3 @@ +# axios // env + +The `data.js` file is updated automatically when the package version is upgrading. Please do not edit it manually. diff --git a/node_modules/axios/lib/env/classes/FormData.js b/node_modules/axios/lib/env/classes/FormData.js new file mode 100644 index 000000000..862adb93c --- /dev/null +++ b/node_modules/axios/lib/env/classes/FormData.js @@ -0,0 +1,2 @@ +import _FormData from 'form-data'; +export default typeof FormData !== 'undefined' ? FormData : _FormData; diff --git a/node_modules/axios/lib/env/data.js b/node_modules/axios/lib/env/data.js new file mode 100644 index 000000000..28eb8d1d1 --- /dev/null +++ b/node_modules/axios/lib/env/data.js @@ -0,0 +1 @@ +export const VERSION = "1.7.9"; \ No newline at end of file diff --git a/node_modules/axios/lib/helpers/AxiosTransformStream.js b/node_modules/axios/lib/helpers/AxiosTransformStream.js new file mode 100644 index 000000000..414007121 --- /dev/null +++ b/node_modules/axios/lib/helpers/AxiosTransformStream.js @@ -0,0 +1,143 @@ +'use strict'; + +import stream from 'stream'; +import utils from '../utils.js'; + +const kInternals = Symbol('internals'); + +class AxiosTransformStream extends stream.Transform{ + constructor(options) { + options = utils.toFlatObject(options, { + maxRate: 0, + chunkSize: 64 * 1024, + minChunkSize: 100, + timeWindow: 500, + ticksRate: 2, + samplesCount: 15 + }, null, (prop, source) => { + return !utils.isUndefined(source[prop]); + }); + + super({ + readableHighWaterMark: options.chunkSize + }); + + const internals = this[kInternals] = { + timeWindow: options.timeWindow, + chunkSize: options.chunkSize, + maxRate: options.maxRate, + minChunkSize: options.minChunkSize, + bytesSeen: 0, + isCaptured: false, + notifiedBytesLoaded: 0, + ts: Date.now(), + bytes: 0, + onReadCallback: null + }; + + this.on('newListener', event => { + if (event === 'progress') { + if (!internals.isCaptured) { + internals.isCaptured = true; + } + } + }); + } + + _read(size) { + const internals = this[kInternals]; + + if (internals.onReadCallback) { + internals.onReadCallback(); + } + + return super._read(size); + } + + _transform(chunk, encoding, callback) { + const internals = this[kInternals]; + const maxRate = internals.maxRate; + + const readableHighWaterMark = this.readableHighWaterMark; + + const timeWindow = internals.timeWindow; + + const divider = 1000 / timeWindow; + const bytesThreshold = (maxRate / divider); + const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; + + const pushChunk = (_chunk, _callback) => { + const bytes = Buffer.byteLength(_chunk); + internals.bytesSeen += bytes; + internals.bytes += bytes; + + internals.isCaptured && this.emit('progress', internals.bytesSeen); + + if (this.push(_chunk)) { + process.nextTick(_callback); + } else { + internals.onReadCallback = () => { + internals.onReadCallback = null; + process.nextTick(_callback); + }; + } + } + + const transformChunk = (_chunk, _callback) => { + const chunkSize = Buffer.byteLength(_chunk); + let chunkRemainder = null; + let maxChunkSize = readableHighWaterMark; + let bytesLeft; + let passed = 0; + + if (maxRate) { + const now = Date.now(); + + if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) { + internals.ts = now; + bytesLeft = bytesThreshold - internals.bytes; + internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; + passed = 0; + } + + bytesLeft = bytesThreshold - internals.bytes; + } + + if (maxRate) { + if (bytesLeft <= 0) { + // next time window + return setTimeout(() => { + _callback(null, _chunk); + }, timeWindow - passed); + } + + if (bytesLeft < maxChunkSize) { + maxChunkSize = bytesLeft; + } + } + + if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) { + chunkRemainder = _chunk.subarray(maxChunkSize); + _chunk = _chunk.subarray(0, maxChunkSize); + } + + pushChunk(_chunk, chunkRemainder ? () => { + process.nextTick(_callback, null, chunkRemainder); + } : _callback); + }; + + transformChunk(chunk, function transformNextChunk(err, _chunk) { + if (err) { + return callback(err); + } + + if (_chunk) { + transformChunk(_chunk, transformNextChunk); + } else { + callback(null); + } + }); + } +} + +export default AxiosTransformStream; diff --git a/node_modules/axios/lib/helpers/AxiosURLSearchParams.js b/node_modules/axios/lib/helpers/AxiosURLSearchParams.js new file mode 100644 index 000000000..b9aa9f02b --- /dev/null +++ b/node_modules/axios/lib/helpers/AxiosURLSearchParams.js @@ -0,0 +1,58 @@ +'use strict'; + +import toFormData from './toFormData.js'; + +/** + * It encodes a string by replacing all characters that are not in the unreserved set with + * their percent-encoded equivalents + * + * @param {string} str - The string to encode. + * + * @returns {string} The encoded string. + */ +function encode(str) { + const charMap = { + '!': '%21', + "'": '%27', + '(': '%28', + ')': '%29', + '~': '%7E', + '%20': '+', + '%00': '\x00' + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); +} + +/** + * It takes a params object and converts it to a FormData object + * + * @param {Object} params - The parameters to be converted to a FormData object. + * @param {Object} options - The options object passed to the Axios constructor. + * + * @returns {void} + */ +function AxiosURLSearchParams(params, options) { + this._pairs = []; + + params && toFormData(params, this, options); +} + +const prototype = AxiosURLSearchParams.prototype; + +prototype.append = function append(name, value) { + this._pairs.push([name, value]); +}; + +prototype.toString = function toString(encoder) { + const _encode = encoder ? function(value) { + return encoder.call(this, value, encode); + } : encode; + + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + '=' + _encode(pair[1]); + }, '').join('&'); +}; + +export default AxiosURLSearchParams; diff --git a/node_modules/axios/lib/helpers/HttpStatusCode.js b/node_modules/axios/lib/helpers/HttpStatusCode.js new file mode 100644 index 000000000..b3e7adcab --- /dev/null +++ b/node_modules/axios/lib/helpers/HttpStatusCode.js @@ -0,0 +1,71 @@ +const HttpStatusCode = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511, +}; + +Object.entries(HttpStatusCode).forEach(([key, value]) => { + HttpStatusCode[value] = key; +}); + +export default HttpStatusCode; diff --git a/node_modules/axios/lib/helpers/README.md b/node_modules/axios/lib/helpers/README.md new file mode 100644 index 000000000..4ae34193a --- /dev/null +++ b/node_modules/axios/lib/helpers/README.md @@ -0,0 +1,7 @@ +# axios // helpers + +The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like: + +- Browser polyfills +- Managing cookies +- Parsing HTTP headers diff --git a/node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js b/node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js new file mode 100644 index 000000000..d1791f0b8 --- /dev/null +++ b/node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js @@ -0,0 +1,28 @@ +"use strict"; + +import stream from "stream"; + +class ZlibHeaderTransformStream extends stream.Transform { + __transform(chunk, encoding, callback) { + this.push(chunk); + callback(); + } + + _transform(chunk, encoding, callback) { + if (chunk.length !== 0) { + this._transform = this.__transform; + + // Add Default Compression headers if no zlib headers are present + if (chunk[0] !== 120) { // Hex: 78 + const header = Buffer.alloc(2); + header[0] = 120; // Hex: 78 + header[1] = 156; // Hex: 9C + this.push(header, encoding); + } + } + + this.__transform(chunk, encoding, callback); + } +} + +export default ZlibHeaderTransformStream; diff --git a/node_modules/axios/lib/helpers/bind.js b/node_modules/axios/lib/helpers/bind.js new file mode 100644 index 000000000..b3aa83b75 --- /dev/null +++ b/node_modules/axios/lib/helpers/bind.js @@ -0,0 +1,7 @@ +'use strict'; + +export default function bind(fn, thisArg) { + return function wrap() { + return fn.apply(thisArg, arguments); + }; +} diff --git a/node_modules/axios/lib/helpers/buildURL.js b/node_modules/axios/lib/helpers/buildURL.js new file mode 100644 index 000000000..5c5eb5798 --- /dev/null +++ b/node_modules/axios/lib/helpers/buildURL.js @@ -0,0 +1,69 @@ +'use strict'; + +import utils from '../utils.js'; +import AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js'; + +/** + * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their + * URI encoded counterparts + * + * @param {string} val The value to be encoded. + * + * @returns {string} The encoded value. + */ +function encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} + +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @param {?(object|Function)} options + * + * @returns {string} The formatted url + */ +export default function buildURL(url, params, options) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + + const _encode = options && options.encode || encode; + + if (utils.isFunction(options)) { + options = { + serialize: options + }; + } + + const serializeFn = options && options.serialize; + + let serializedParams; + + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils.isURLSearchParams(params) ? + params.toString() : + new AxiosURLSearchParams(params, options).toString(_encode); + } + + if (serializedParams) { + const hashmarkIndex = url.indexOf("#"); + + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + + return url; +} diff --git a/node_modules/axios/lib/helpers/callbackify.js b/node_modules/axios/lib/helpers/callbackify.js new file mode 100644 index 000000000..4603badc3 --- /dev/null +++ b/node_modules/axios/lib/helpers/callbackify.js @@ -0,0 +1,16 @@ +import utils from "../utils.js"; + +const callbackify = (fn, reducer) => { + return utils.isAsyncFn(fn) ? function (...args) { + const cb = args.pop(); + fn.apply(this, args).then((value) => { + try { + reducer ? cb(null, ...reducer(value)) : cb(null, value); + } catch (err) { + cb(err); + } + }, cb); + } : fn; +} + +export default callbackify; diff --git a/node_modules/axios/lib/helpers/combineURLs.js b/node_modules/axios/lib/helpers/combineURLs.js new file mode 100644 index 000000000..9f04f0202 --- /dev/null +++ b/node_modules/axios/lib/helpers/combineURLs.js @@ -0,0 +1,15 @@ +'use strict'; + +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * + * @returns {string} The combined URL + */ +export default function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +} diff --git a/node_modules/axios/lib/helpers/composeSignals.js b/node_modules/axios/lib/helpers/composeSignals.js new file mode 100644 index 000000000..84087c806 --- /dev/null +++ b/node_modules/axios/lib/helpers/composeSignals.js @@ -0,0 +1,48 @@ +import CanceledError from "../cancel/CanceledError.js"; +import AxiosError from "../core/AxiosError.js"; +import utils from '../utils.js'; + +const composeSignals = (signals, timeout) => { + const {length} = (signals = signals ? signals.filter(Boolean) : []); + + if (timeout || length) { + let controller = new AbortController(); + + let aborted; + + const onabort = function (reason) { + if (!aborted) { + aborted = true; + unsubscribe(); + const err = reason instanceof Error ? reason : this.reason; + controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err)); + } + } + + let timer = timeout && setTimeout(() => { + timer = null; + onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT)) + }, timeout) + + const unsubscribe = () => { + if (signals) { + timer && clearTimeout(timer); + timer = null; + signals.forEach(signal => { + signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort); + }); + signals = null; + } + } + + signals.forEach((signal) => signal.addEventListener('abort', onabort)); + + const {signal} = controller; + + signal.unsubscribe = () => utils.asap(unsubscribe); + + return signal; + } +} + +export default composeSignals; diff --git a/node_modules/axios/lib/helpers/cookies.js b/node_modules/axios/lib/helpers/cookies.js new file mode 100644 index 000000000..d039ac4f8 --- /dev/null +++ b/node_modules/axios/lib/helpers/cookies.js @@ -0,0 +1,42 @@ +import utils from './../utils.js'; +import platform from '../platform/index.js'; + +export default platform.hasStandardBrowserEnv ? + + // Standard browser envs support document.cookie + { + write(name, value, expires, path, domain, secure) { + const cookie = [name + '=' + encodeURIComponent(value)]; + + utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString()); + + utils.isString(path) && cookie.push('path=' + path); + + utils.isString(domain) && cookie.push('domain=' + domain); + + secure === true && cookie.push('secure'); + + document.cookie = cookie.join('; '); + }, + + read(name) { + const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, + + remove(name) { + this.write(name, '', Date.now() - 86400000); + } + } + + : + + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() {}, + read() { + return null; + }, + remove() {} + }; + diff --git a/node_modules/axios/lib/helpers/deprecatedMethod.js b/node_modules/axios/lib/helpers/deprecatedMethod.js new file mode 100644 index 000000000..9e8fae6bf --- /dev/null +++ b/node_modules/axios/lib/helpers/deprecatedMethod.js @@ -0,0 +1,26 @@ +'use strict'; + +/*eslint no-console:0*/ + +/** + * Supply a warning to the developer that a method they are using + * has been deprecated. + * + * @param {string} method The name of the deprecated method + * @param {string} [instead] The alternate method to use if applicable + * @param {string} [docs] The documentation URL to get further details + * + * @returns {void} + */ +export default function deprecatedMethod(method, instead, docs) { + try { + console.warn( + 'DEPRECATED method `' + method + '`.' + + (instead ? ' Use `' + instead + '` instead.' : '') + + ' This method will be removed in a future release.'); + + if (docs) { + console.warn('For more information about usage see ' + docs); + } + } catch (e) { /* Ignore */ } +} diff --git a/node_modules/axios/lib/helpers/formDataToJSON.js b/node_modules/axios/lib/helpers/formDataToJSON.js new file mode 100644 index 000000000..906ce6025 --- /dev/null +++ b/node_modules/axios/lib/helpers/formDataToJSON.js @@ -0,0 +1,95 @@ +'use strict'; + +import utils from '../utils.js'; + +/** + * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z'] + * + * @param {string} name - The name of the property to get. + * + * @returns An array of strings. + */ +function parsePropPath(name) { + // foo[x][y][z] + // foo.x.y.z + // foo-x-y-z + // foo x y z + return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => { + return match[0] === '[]' ? '' : match[1] || match[0]; + }); +} + +/** + * Convert an array to an object. + * + * @param {Array} arr - The array to convert to an object. + * + * @returns An object with the same keys and values as the array. + */ +function arrayToObject(arr) { + const obj = {}; + const keys = Object.keys(arr); + let i; + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; +} + +/** + * It takes a FormData object and returns a JavaScript object + * + * @param {string} formData The FormData object to convert to JSON. + * + * @returns {Object | null} The converted object. + */ +function formDataToJSON(formData) { + function buildPath(path, value, target, index) { + let name = path[index++]; + + if (name === '__proto__') return true; + + const isNumericKey = Number.isFinite(+name); + const isLast = index >= path.length; + name = !name && utils.isArray(target) ? target.length : name; + + if (isLast) { + if (utils.hasOwnProp(target, name)) { + target[name] = [target[name], value]; + } else { + target[name] = value; + } + + return !isNumericKey; + } + + if (!target[name] || !utils.isObject(target[name])) { + target[name] = []; + } + + const result = buildPath(path, value, target[name], index); + + if (result && utils.isArray(target[name])) { + target[name] = arrayToObject(target[name]); + } + + return !isNumericKey; + } + + if (utils.isFormData(formData) && utils.isFunction(formData.entries)) { + const obj = {}; + + utils.forEachEntry(formData, (name, value) => { + buildPath(parsePropPath(name), value, obj, 0); + }); + + return obj; + } + + return null; +} + +export default formDataToJSON; diff --git a/node_modules/axios/lib/helpers/formDataToStream.js b/node_modules/axios/lib/helpers/formDataToStream.js new file mode 100644 index 000000000..77ffab1ba --- /dev/null +++ b/node_modules/axios/lib/helpers/formDataToStream.js @@ -0,0 +1,111 @@ +import util from 'util'; +import {Readable} from 'stream'; +import utils from "../utils.js"; +import readBlob from "./readBlob.js"; + +const BOUNDARY_ALPHABET = utils.ALPHABET.ALPHA_DIGIT + '-_'; + +const textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : new util.TextEncoder(); + +const CRLF = '\r\n'; +const CRLF_BYTES = textEncoder.encode(CRLF); +const CRLF_BYTES_COUNT = 2; + +class FormDataPart { + constructor(name, value) { + const {escapeName} = this.constructor; + const isStringValue = utils.isString(value); + + let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${ + !isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : '' + }${CRLF}`; + + if (isStringValue) { + value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); + } else { + headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}` + } + + this.headers = textEncoder.encode(headers + CRLF); + + this.contentLength = isStringValue ? value.byteLength : value.size; + + this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT; + + this.name = name; + this.value = value; + } + + async *encode(){ + yield this.headers; + + const {value} = this; + + if(utils.isTypedArray(value)) { + yield value; + } else { + yield* readBlob(value); + } + + yield CRLF_BYTES; + } + + static escapeName(name) { + return String(name).replace(/[\r\n"]/g, (match) => ({ + '\r' : '%0D', + '\n' : '%0A', + '"' : '%22', + }[match])); + } +} + +const formDataToStream = (form, headersHandler, options) => { + const { + tag = 'form-data-boundary', + size = 25, + boundary = tag + '-' + utils.generateString(size, BOUNDARY_ALPHABET) + } = options || {}; + + if(!utils.isFormData(form)) { + throw TypeError('FormData instance required'); + } + + if (boundary.length < 1 || boundary.length > 70) { + throw Error('boundary must be 10-70 characters long') + } + + const boundaryBytes = textEncoder.encode('--' + boundary + CRLF); + const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF + CRLF); + let contentLength = footerBytes.byteLength; + + const parts = Array.from(form.entries()).map(([name, value]) => { + const part = new FormDataPart(name, value); + contentLength += part.size; + return part; + }); + + contentLength += boundaryBytes.byteLength * parts.length; + + contentLength = utils.toFiniteNumber(contentLength); + + const computedHeaders = { + 'Content-Type': `multipart/form-data; boundary=${boundary}` + } + + if (Number.isFinite(contentLength)) { + computedHeaders['Content-Length'] = contentLength; + } + + headersHandler && headersHandler(computedHeaders); + + return Readable.from((async function *() { + for(const part of parts) { + yield boundaryBytes; + yield* part.encode(); + } + + yield footerBytes; + })()); +}; + +export default formDataToStream; diff --git a/node_modules/axios/lib/helpers/fromDataURI.js b/node_modules/axios/lib/helpers/fromDataURI.js new file mode 100644 index 000000000..eb71d3f3b --- /dev/null +++ b/node_modules/axios/lib/helpers/fromDataURI.js @@ -0,0 +1,53 @@ +'use strict'; + +import AxiosError from '../core/AxiosError.js'; +import parseProtocol from './parseProtocol.js'; +import platform from '../platform/index.js'; + +const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; + +/** + * Parse data uri to a Buffer or Blob + * + * @param {String} uri + * @param {?Boolean} asBlob + * @param {?Object} options + * @param {?Function} options.Blob + * + * @returns {Buffer|Blob} + */ +export default function fromDataURI(uri, asBlob, options) { + const _Blob = options && options.Blob || platform.classes.Blob; + const protocol = parseProtocol(uri); + + if (asBlob === undefined && _Blob) { + asBlob = true; + } + + if (protocol === 'data') { + uri = protocol.length ? uri.slice(protocol.length + 1) : uri; + + const match = DATA_URL_PATTERN.exec(uri); + + if (!match) { + throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL); + } + + const mime = match[1]; + const isBase64 = match[2]; + const body = match[3]; + const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8'); + + if (asBlob) { + if (!_Blob) { + throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT); + } + + return new _Blob([buffer], {type: mime}); + } + + return buffer; + } + + throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT); +} diff --git a/node_modules/axios/lib/helpers/isAbsoluteURL.js b/node_modules/axios/lib/helpers/isAbsoluteURL.js new file mode 100644 index 000000000..4747a4576 --- /dev/null +++ b/node_modules/axios/lib/helpers/isAbsoluteURL.js @@ -0,0 +1,15 @@ +'use strict'; + +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +export default function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); +} diff --git a/node_modules/axios/lib/helpers/isAxiosError.js b/node_modules/axios/lib/helpers/isAxiosError.js new file mode 100644 index 000000000..da6cd63fd --- /dev/null +++ b/node_modules/axios/lib/helpers/isAxiosError.js @@ -0,0 +1,14 @@ +'use strict'; + +import utils from './../utils.js'; + +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +export default function isAxiosError(payload) { + return utils.isObject(payload) && (payload.isAxiosError === true); +} diff --git a/node_modules/axios/lib/helpers/isURLSameOrigin.js b/node_modules/axios/lib/helpers/isURLSameOrigin.js new file mode 100644 index 000000000..6a92aa152 --- /dev/null +++ b/node_modules/axios/lib/helpers/isURLSameOrigin.js @@ -0,0 +1,14 @@ +import platform from '../platform/index.js'; + +export default platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => { + url = new URL(url, platform.origin); + + return ( + origin.protocol === url.protocol && + origin.host === url.host && + (isMSIE || origin.port === url.port) + ); +})( + new URL(platform.origin), + platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) +) : () => true; diff --git a/node_modules/axios/lib/helpers/null.js b/node_modules/axios/lib/helpers/null.js new file mode 100644 index 000000000..b9f82c464 --- /dev/null +++ b/node_modules/axios/lib/helpers/null.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line strict +export default null; diff --git a/node_modules/axios/lib/helpers/parseHeaders.js b/node_modules/axios/lib/helpers/parseHeaders.js new file mode 100644 index 000000000..50af9480c --- /dev/null +++ b/node_modules/axios/lib/helpers/parseHeaders.js @@ -0,0 +1,55 @@ +'use strict'; + +import utils from './../utils.js'; + +// RawAxiosHeaders whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +const ignoreDuplicateOf = utils.toObjectSet([ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]); + +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} rawHeaders Headers needing to be parsed + * + * @returns {Object} Headers parsed into an object + */ +export default rawHeaders => { + const parsed = {}; + let key; + let val; + let i; + + rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { + i = line.indexOf(':'); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + + if (!key || (parsed[key] && ignoreDuplicateOf[key])) { + return; + } + + if (key === 'set-cookie') { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + }); + + return parsed; +}; diff --git a/node_modules/axios/lib/helpers/parseProtocol.js b/node_modules/axios/lib/helpers/parseProtocol.js new file mode 100644 index 000000000..586ec9647 --- /dev/null +++ b/node_modules/axios/lib/helpers/parseProtocol.js @@ -0,0 +1,6 @@ +'use strict'; + +export default function parseProtocol(url) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ''; +} diff --git a/node_modules/axios/lib/helpers/progressEventReducer.js b/node_modules/axios/lib/helpers/progressEventReducer.js new file mode 100644 index 000000000..ff601cc4f --- /dev/null +++ b/node_modules/axios/lib/helpers/progressEventReducer.js @@ -0,0 +1,44 @@ +import speedometer from "./speedometer.js"; +import throttle from "./throttle.js"; +import utils from "../utils.js"; + +export const progressEventReducer = (listener, isDownloadStream, freq = 3) => { + let bytesNotified = 0; + const _speedometer = speedometer(50, 250); + + return throttle(e => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : undefined; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange = loaded <= total; + + bytesNotified = loaded; + + const data = { + loaded, + total, + progress: total ? (loaded / total) : undefined, + bytes: progressBytes, + rate: rate ? rate : undefined, + estimated: rate && total && inRange ? (total - loaded) / rate : undefined, + event: e, + lengthComputable: total != null, + [isDownloadStream ? 'download' : 'upload']: true + }; + + listener(data); + }, freq); +} + +export const progressEventDecorator = (total, throttled) => { + const lengthComputable = total != null; + + return [(loaded) => throttled[0]({ + lengthComputable, + total, + loaded + }), throttled[1]]; +} + +export const asyncDecorator = (fn) => (...args) => utils.asap(() => fn(...args)); diff --git a/node_modules/axios/lib/helpers/readBlob.js b/node_modules/axios/lib/helpers/readBlob.js new file mode 100644 index 000000000..6de748e8e --- /dev/null +++ b/node_modules/axios/lib/helpers/readBlob.js @@ -0,0 +1,15 @@ +const {asyncIterator} = Symbol; + +const readBlob = async function* (blob) { + if (blob.stream) { + yield* blob.stream() + } else if (blob.arrayBuffer) { + yield await blob.arrayBuffer() + } else if (blob[asyncIterator]) { + yield* blob[asyncIterator](); + } else { + yield blob; + } +} + +export default readBlob; diff --git a/node_modules/axios/lib/helpers/resolveConfig.js b/node_modules/axios/lib/helpers/resolveConfig.js new file mode 100644 index 000000000..5e84c5cc8 --- /dev/null +++ b/node_modules/axios/lib/helpers/resolveConfig.js @@ -0,0 +1,57 @@ +import platform from "../platform/index.js"; +import utils from "../utils.js"; +import isURLSameOrigin from "./isURLSameOrigin.js"; +import cookies from "./cookies.js"; +import buildFullPath from "../core/buildFullPath.js"; +import mergeConfig from "../core/mergeConfig.js"; +import AxiosHeaders from "../core/AxiosHeaders.js"; +import buildURL from "./buildURL.js"; + +export default (config) => { + const newConfig = mergeConfig({}, config); + + let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig; + + newConfig.headers = headers = AxiosHeaders.from(headers); + + newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer); + + // HTTP basic authentication + if (auth) { + headers.set('Authorization', 'Basic ' + + btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : '')) + ); + } + + let contentType; + + if (utils.isFormData(data)) { + if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { + headers.setContentType(undefined); // Let the browser set it + } else if ((contentType = headers.getContentType()) !== false) { + // fix semicolon duplication issue for ReactNative FormData implementation + const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : []; + headers.setContentType([type || 'multipart/form-data', ...tokens].join('; ')); + } + } + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + + if (platform.hasStandardBrowserEnv) { + withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); + + if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) { + // Add xsrf header + const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); + + if (xsrfValue) { + headers.set(xsrfHeaderName, xsrfValue); + } + } + } + + return newConfig; +} + diff --git a/node_modules/axios/lib/helpers/speedometer.js b/node_modules/axios/lib/helpers/speedometer.js new file mode 100644 index 000000000..3b3c6662f --- /dev/null +++ b/node_modules/axios/lib/helpers/speedometer.js @@ -0,0 +1,55 @@ +'use strict'; + +/** + * Calculate data maxRate + * @param {Number} [samplesCount= 10] + * @param {Number} [min= 1000] + * @returns {Function} + */ +function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + + min = min !== undefined ? min : 1000; + + return function push(chunkLength) { + const now = Date.now(); + + const startedAt = timestamps[tail]; + + if (!firstSampleTS) { + firstSampleTS = now; + } + + bytes[head] = chunkLength; + timestamps[head] = now; + + let i = tail; + let bytesCount = 0; + + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + + head = (head + 1) % samplesCount; + + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + + if (now - firstSampleTS < min) { + return; + } + + const passed = startedAt && now - startedAt; + + return passed ? Math.round(bytesCount * 1000 / passed) : undefined; + }; +} + +export default speedometer; diff --git a/node_modules/axios/lib/helpers/spread.js b/node_modules/axios/lib/helpers/spread.js new file mode 100644 index 000000000..13479cb25 --- /dev/null +++ b/node_modules/axios/lib/helpers/spread.js @@ -0,0 +1,28 @@ +'use strict'; + +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * + * @returns {Function} + */ +export default function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +} diff --git a/node_modules/axios/lib/helpers/throttle.js b/node_modules/axios/lib/helpers/throttle.js new file mode 100644 index 000000000..e2562720c --- /dev/null +++ b/node_modules/axios/lib/helpers/throttle.js @@ -0,0 +1,44 @@ +/** + * Throttle decorator + * @param {Function} fn + * @param {Number} freq + * @return {Function} + */ +function throttle(fn, freq) { + let timestamp = 0; + let threshold = 1000 / freq; + let lastArgs; + let timer; + + const invoke = (args, now = Date.now()) => { + timestamp = now; + lastArgs = null; + if (timer) { + clearTimeout(timer); + timer = null; + } + fn.apply(null, args); + } + + const throttled = (...args) => { + const now = Date.now(); + const passed = now - timestamp; + if ( passed >= threshold) { + invoke(args, now); + } else { + lastArgs = args; + if (!timer) { + timer = setTimeout(() => { + timer = null; + invoke(lastArgs) + }, threshold - passed); + } + } + } + + const flush = () => lastArgs && invoke(lastArgs); + + return [throttled, flush]; +} + +export default throttle; diff --git a/node_modules/axios/lib/helpers/toFormData.js b/node_modules/axios/lib/helpers/toFormData.js new file mode 100644 index 000000000..a41e966c0 --- /dev/null +++ b/node_modules/axios/lib/helpers/toFormData.js @@ -0,0 +1,219 @@ +'use strict'; + +import utils from '../utils.js'; +import AxiosError from '../core/AxiosError.js'; +// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored +import PlatformFormData from '../platform/node/classes/FormData.js'; + +/** + * Determines if the given thing is a array or js object. + * + * @param {string} thing - The object or array to be visited. + * + * @returns {boolean} + */ +function isVisitable(thing) { + return utils.isPlainObject(thing) || utils.isArray(thing); +} + +/** + * It removes the brackets from the end of a string + * + * @param {string} key - The key of the parameter. + * + * @returns {string} the key without the brackets. + */ +function removeBrackets(key) { + return utils.endsWith(key, '[]') ? key.slice(0, -2) : key; +} + +/** + * It takes a path, a key, and a boolean, and returns a string + * + * @param {string} path - The path to the current key. + * @param {string} key - The key of the current object being iterated over. + * @param {string} dots - If true, the key will be rendered with dots instead of brackets. + * + * @returns {string} The path to the current key. + */ +function renderKey(path, key, dots) { + if (!path) return key; + return path.concat(key).map(function each(token, i) { + // eslint-disable-next-line no-param-reassign + token = removeBrackets(token); + return !dots && i ? '[' + token + ']' : token; + }).join(dots ? '.' : ''); +} + +/** + * If the array is an array and none of its elements are visitable, then it's a flat array. + * + * @param {Array} arr - The array to check + * + * @returns {boolean} + */ +function isFlatArray(arr) { + return utils.isArray(arr) && !arr.some(isVisitable); +} + +const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); +}); + +/** + * Convert a data object to FormData + * + * @param {Object} obj + * @param {?Object} [formData] + * @param {?Object} [options] + * @param {Function} [options.visitor] + * @param {Boolean} [options.metaTokens = true] + * @param {Boolean} [options.dots = false] + * @param {?Boolean} [options.indexes = false] + * + * @returns {Object} + **/ + +/** + * It converts an object into a FormData object + * + * @param {Object} obj - The object to convert to form data. + * @param {string} formData - The FormData object to append to. + * @param {Object} options + * + * @returns + */ +function toFormData(obj, formData, options) { + if (!utils.isObject(obj)) { + throw new TypeError('target must be an object'); + } + + // eslint-disable-next-line no-param-reassign + formData = formData || new (PlatformFormData || FormData)(); + + // eslint-disable-next-line no-param-reassign + options = utils.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + // eslint-disable-next-line no-eq-null,eqeqeq + return !utils.isUndefined(source[option]); + }); + + const metaTokens = options.metaTokens; + // eslint-disable-next-line no-use-before-define + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; + const useBlob = _Blob && utils.isSpecCompliantForm(formData); + + if (!utils.isFunction(visitor)) { + throw new TypeError('visitor must be a function'); + } + + function convertValue(value) { + if (value === null) return ''; + + if (utils.isDate(value)) { + return value.toISOString(); + } + + if (!useBlob && utils.isBlob(value)) { + throw new AxiosError('Blob is not supported. Use a Buffer instead.'); + } + + if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) { + return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + } + + return value; + } + + /** + * Default visitor. + * + * @param {*} value + * @param {String|Number} key + * @param {Array} path + * @this {FormData} + * + * @returns {boolean} return true to visit the each prop of the value recursively + */ + function defaultVisitor(value, key, path) { + let arr = value; + + if (value && !path && typeof value === 'object') { + if (utils.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign + key = metaTokens ? key : key.slice(0, -2); + // eslint-disable-next-line no-param-reassign + value = JSON.stringify(value); + } else if ( + (utils.isArray(value) && isFlatArray(value)) || + ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value)) + )) { + // eslint-disable-next-line no-param-reassign + key = removeBrackets(key); + + arr.forEach(function each(el, index) { + !(utils.isUndefined(el) || el === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), + convertValue(el) + ); + }); + return false; + } + } + + if (isVisitable(value)) { + return true; + } + + formData.append(renderKey(path, key, dots), convertValue(value)); + + return false; + } + + const stack = []; + + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable + }); + + function build(value, path) { + if (utils.isUndefined(value)) return; + + if (stack.indexOf(value) !== -1) { + throw Error('Circular reference detected in ' + path.join('.')); + } + + stack.push(value); + + utils.forEach(value, function each(el, key) { + const result = !(utils.isUndefined(el) || el === null) && visitor.call( + formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers + ); + + if (result === true) { + build(el, path ? path.concat(key) : [key]); + } + }); + + stack.pop(); + } + + if (!utils.isObject(obj)) { + throw new TypeError('data must be an object'); + } + + build(obj); + + return formData; +} + +export default toFormData; diff --git a/node_modules/axios/lib/helpers/toURLEncodedForm.js b/node_modules/axios/lib/helpers/toURLEncodedForm.js new file mode 100644 index 000000000..988a38a16 --- /dev/null +++ b/node_modules/axios/lib/helpers/toURLEncodedForm.js @@ -0,0 +1,18 @@ +'use strict'; + +import utils from '../utils.js'; +import toFormData from './toFormData.js'; +import platform from '../platform/index.js'; + +export default function toURLEncodedForm(data, options) { + return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (platform.isNode && utils.isBuffer(value)) { + this.append(key, value.toString('base64')); + return false; + } + + return helpers.defaultVisitor.apply(this, arguments); + } + }, options)); +} diff --git a/node_modules/axios/lib/helpers/trackStream.js b/node_modules/axios/lib/helpers/trackStream.js new file mode 100644 index 000000000..95d60081f --- /dev/null +++ b/node_modules/axios/lib/helpers/trackStream.js @@ -0,0 +1,87 @@ + +export const streamChunk = function* (chunk, chunkSize) { + let len = chunk.byteLength; + + if (!chunkSize || len < chunkSize) { + yield chunk; + return; + } + + let pos = 0; + let end; + + while (pos < len) { + end = pos + chunkSize; + yield chunk.slice(pos, end); + pos = end; + } +} + +export const readBytes = async function* (iterable, chunkSize) { + for await (const chunk of readStream(iterable)) { + yield* streamChunk(chunk, chunkSize); + } +} + +const readStream = async function* (stream) { + if (stream[Symbol.asyncIterator]) { + yield* stream; + return; + } + + const reader = stream.getReader(); + try { + for (;;) { + const {done, value} = await reader.read(); + if (done) { + break; + } + yield value; + } + } finally { + await reader.cancel(); + } +} + +export const trackStream = (stream, chunkSize, onProgress, onFinish) => { + const iterator = readBytes(stream, chunkSize); + + let bytes = 0; + let done; + let _onFinish = (e) => { + if (!done) { + done = true; + onFinish && onFinish(e); + } + } + + return new ReadableStream({ + async pull(controller) { + try { + const {done, value} = await iterator.next(); + + if (done) { + _onFinish(); + controller.close(); + return; + } + + let len = value.byteLength; + if (onProgress) { + let loadedBytes = bytes += len; + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); + } catch (err) { + _onFinish(err); + throw err; + } + }, + cancel(reason) { + _onFinish(reason); + return iterator.return(); + } + }, { + highWaterMark: 2 + }) +} diff --git a/node_modules/axios/lib/helpers/validator.js b/node_modules/axios/lib/helpers/validator.js new file mode 100644 index 000000000..127056872 --- /dev/null +++ b/node_modules/axios/lib/helpers/validator.js @@ -0,0 +1,99 @@ +'use strict'; + +import {VERSION} from '../env/data.js'; +import AxiosError from '../core/AxiosError.js'; + +const validators = {}; + +// eslint-disable-next-line func-names +['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => { + validators[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; +}); + +const deprecatedWarnings = {}; + +/** + * Transitional option validator + * + * @param {function|boolean?} validator - set to false if the transitional option has been removed + * @param {string?} version - deprecated version / removed since version + * @param {string?} message - some message with additional info + * + * @returns {function} + */ +validators.transitional = function transitional(validator, version, message) { + function formatMessage(opt, desc) { + return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + } + + // eslint-disable-next-line func-names + return (value, opt, opts) => { + if (validator === false) { + throw new AxiosError( + formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), + AxiosError.ERR_DEPRECATED + ); + } + + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); + } + + return validator ? validator(value, opt, opts) : true; + }; +}; + +validators.spelling = function spelling(correctSpelling) { + return (value, opt) => { + // eslint-disable-next-line no-console + console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); + return true; + } +}; + +/** + * Assert object's properties type + * + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown + * + * @returns {object} + */ + +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== 'object') { + throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); + } + const keys = Object.keys(options); + let i = keys.length; + while (i-- > 0) { + const opt = keys[i]; + const validator = schema[opt]; + if (validator) { + const value = options[opt]; + const result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); + } + } +} + +export default { + assertOptions, + validators +}; diff --git a/node_modules/axios/lib/platform/browser/classes/Blob.js b/node_modules/axios/lib/platform/browser/classes/Blob.js new file mode 100644 index 000000000..6c506c48a --- /dev/null +++ b/node_modules/axios/lib/platform/browser/classes/Blob.js @@ -0,0 +1,3 @@ +'use strict' + +export default typeof Blob !== 'undefined' ? Blob : null diff --git a/node_modules/axios/lib/platform/browser/classes/FormData.js b/node_modules/axios/lib/platform/browser/classes/FormData.js new file mode 100644 index 000000000..f36d31b29 --- /dev/null +++ b/node_modules/axios/lib/platform/browser/classes/FormData.js @@ -0,0 +1,3 @@ +'use strict'; + +export default typeof FormData !== 'undefined' ? FormData : null; diff --git a/node_modules/axios/lib/platform/browser/classes/URLSearchParams.js b/node_modules/axios/lib/platform/browser/classes/URLSearchParams.js new file mode 100644 index 000000000..b7dae9533 --- /dev/null +++ b/node_modules/axios/lib/platform/browser/classes/URLSearchParams.js @@ -0,0 +1,4 @@ +'use strict'; + +import AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js'; +export default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams; diff --git a/node_modules/axios/lib/platform/browser/index.js b/node_modules/axios/lib/platform/browser/index.js new file mode 100644 index 000000000..08c206f3c --- /dev/null +++ b/node_modules/axios/lib/platform/browser/index.js @@ -0,0 +1,13 @@ +import URLSearchParams from './classes/URLSearchParams.js' +import FormData from './classes/FormData.js' +import Blob from './classes/Blob.js' + +export default { + isBrowser: true, + classes: { + URLSearchParams, + FormData, + Blob + }, + protocols: ['http', 'https', 'file', 'blob', 'url', 'data'] +}; diff --git a/node_modules/axios/lib/platform/common/utils.js b/node_modules/axios/lib/platform/common/utils.js new file mode 100644 index 000000000..52a3186e3 --- /dev/null +++ b/node_modules/axios/lib/platform/common/utils.js @@ -0,0 +1,51 @@ +const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; + +const _navigator = typeof navigator === 'object' && navigator || undefined; + +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + * + * @returns {boolean} + */ +const hasStandardBrowserEnv = hasBrowserEnv && + (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0); + +/** + * Determine if we're running in a standard browser webWorker environment + * + * Although the `isStandardBrowserEnv` method indicates that + * `allows axios to run in a web worker`, the WebWorker will still be + * filtered out due to its judgment standard + * `typeof window !== 'undefined' && typeof document !== 'undefined'`. + * This leads to a problem when axios post `FormData` in webWorker + */ +const hasStandardBrowserWebWorkerEnv = (() => { + return ( + typeof WorkerGlobalScope !== 'undefined' && + // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && + typeof self.importScripts === 'function' + ); +})(); + +const origin = hasBrowserEnv && window.location.href || 'http://localhost'; + +export { + hasBrowserEnv, + hasStandardBrowserWebWorkerEnv, + hasStandardBrowserEnv, + _navigator as navigator, + origin +} diff --git a/node_modules/axios/lib/platform/index.js b/node_modules/axios/lib/platform/index.js new file mode 100644 index 000000000..860ba21a1 --- /dev/null +++ b/node_modules/axios/lib/platform/index.js @@ -0,0 +1,7 @@ +import platform from './node/index.js'; +import * as utils from './common/utils.js'; + +export default { + ...utils, + ...platform +} diff --git a/node_modules/axios/lib/platform/node/classes/FormData.js b/node_modules/axios/lib/platform/node/classes/FormData.js new file mode 100644 index 000000000..b07f9476d --- /dev/null +++ b/node_modules/axios/lib/platform/node/classes/FormData.js @@ -0,0 +1,3 @@ +import FormData from 'form-data'; + +export default FormData; diff --git a/node_modules/axios/lib/platform/node/classes/URLSearchParams.js b/node_modules/axios/lib/platform/node/classes/URLSearchParams.js new file mode 100644 index 000000000..fba584289 --- /dev/null +++ b/node_modules/axios/lib/platform/node/classes/URLSearchParams.js @@ -0,0 +1,4 @@ +'use strict'; + +import url from 'url'; +export default url.URLSearchParams; diff --git a/node_modules/axios/lib/platform/node/index.js b/node_modules/axios/lib/platform/node/index.js new file mode 100644 index 000000000..aef514aa3 --- /dev/null +++ b/node_modules/axios/lib/platform/node/index.js @@ -0,0 +1,12 @@ +import URLSearchParams from './classes/URLSearchParams.js' +import FormData from './classes/FormData.js' + +export default { + isNode: true, + classes: { + URLSearchParams, + FormData, + Blob: typeof Blob !== 'undefined' && Blob || null + }, + protocols: [ 'http', 'https', 'file', 'data' ] +}; diff --git a/node_modules/axios/lib/utils.js b/node_modules/axios/lib/utils.js new file mode 100644 index 000000000..32679dad2 --- /dev/null +++ b/node_modules/axios/lib/utils.js @@ -0,0 +1,760 @@ +'use strict'; + +import bind from './helpers/bind.js'; + +// utils is a library of generic helper functions non-specific to axios + +const {toString} = Object.prototype; +const {getPrototypeOf} = Object; + +const kindOf = (cache => thing => { + const str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); +})(Object.create(null)); + +const kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type +} + +const typeOfTest = type => thing => typeof thing === type; + +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * + * @returns {boolean} True if value is an Array, otherwise false + */ +const {isArray} = Array; + +/** + * Determine if a value is undefined + * + * @param {*} val The value to test + * + * @returns {boolean} True if the value is undefined, otherwise false + */ +const isUndefined = typeOfTest('undefined'); + +/** + * Determine if a value is a Buffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); +} + +/** + * Determine if a value is an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +const isArrayBuffer = kindOfTest('ArrayBuffer'); + + +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + let result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); + } + return result; +} + +/** + * Determine if a value is a String + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a String, otherwise false + */ +const isString = typeOfTest('string'); + +/** + * Determine if a value is a Function + * + * @param {*} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +const isFunction = typeOfTest('function'); + +/** + * Determine if a value is a Number + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Number, otherwise false + */ +const isNumber = typeOfTest('number'); + +/** + * Determine if a value is an Object + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an Object, otherwise false + */ +const isObject = (thing) => thing !== null && typeof thing === 'object'; + +/** + * Determine if a value is a Boolean + * + * @param {*} thing The value to test + * @returns {boolean} True if value is a Boolean, otherwise false + */ +const isBoolean = thing => thing === true || thing === false; + +/** + * Determine if a value is a plain Object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a plain Object, otherwise false + */ +const isPlainObject = (val) => { + if (kindOf(val) !== 'object') { + return false; + } + + const prototype = getPrototypeOf(val); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); +} + +/** + * Determine if a value is a Date + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Date, otherwise false + */ +const isDate = kindOfTest('Date'); + +/** + * Determine if a value is a File + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFile = kindOfTest('File'); + +/** + * Determine if a value is a Blob + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Blob, otherwise false + */ +const isBlob = kindOfTest('Blob'); + +/** + * Determine if a value is a FileList + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFileList = kindOfTest('FileList'); + +/** + * Determine if a value is a Stream + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Stream, otherwise false + */ +const isStream = (val) => isObject(val) && isFunction(val.pipe); + +/** + * Determine if a value is a FormData + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an FormData, otherwise false + */ +const isFormData = (thing) => { + let kind; + return thing && ( + (typeof FormData === 'function' && thing instanceof FormData) || ( + isFunction(thing.append) && ( + (kind = kindOf(thing)) === 'formdata' || + // detect form-data instance + (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]') + ) + ) + ) +} + +/** + * Determine if a value is a URLSearchParams object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +const isURLSearchParams = kindOfTest('URLSearchParams'); + +const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest); + +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * + * @returns {String} The String freed of excess whitespace + */ +const trim = (str) => str.trim ? + str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + * + * @param {Boolean} [allOwnKeys = false] + * @returns {any} + */ +function forEach(obj, fn, {allOwnKeys = false} = {}) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + let i; + let l; + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; + + for (i = 0; i < len; i++) { + key = keys[i]; + fn.call(null, obj[key], key, obj); + } + } +} + +function findKey(obj, key) { + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; +} + +const _global = (() => { + /*eslint no-undef:0*/ + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global) +})(); + +const isContextDefined = (context) => !isUndefined(context) && context !== _global; + +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + const {caseless} = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + } + + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); + } + return result; +} + +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * + * @param {Boolean} [allOwnKeys] + * @returns {Object} The resulting value of object a + */ +const extend = (a, b, thisArg, {allOwnKeys}= {}) => { + forEach(b, (val, key) => { + if (thisArg && isFunction(val)) { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }, {allOwnKeys}); + return a; +} + +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * + * @returns {string} content value without BOM + */ +const stripBOM = (content) => { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +} + +/** + * Inherit the prototype methods from one constructor into another + * @param {function} constructor + * @param {function} superConstructor + * @param {object} [props] + * @param {object} [descriptors] + * + * @returns {void} + */ +const inherits = (constructor, superConstructor, props, descriptors) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, 'super', { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); +} + +/** + * Resolve object with deep prototype chain to a flat object + * @param {Object} sourceObj source object + * @param {Object} [destObj] + * @param {Function|Boolean} [filter] + * @param {Function} [propFilter] + * + * @returns {Object} + */ +const toFlatObject = (sourceObj, destObj, filter, propFilter) => { + let props; + let i; + let prop; + const merged = {}; + + destObj = destObj || {}; + // eslint-disable-next-line no-eq-null,eqeqeq + if (sourceObj == null) return destObj; + + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + + return destObj; +} + +/** + * Determines whether a string ends with the characters of a specified string + * + * @param {String} str + * @param {String} searchString + * @param {Number} [position= 0] + * + * @returns {boolean} + */ +const endsWith = (str, searchString, position) => { + str = String(str); + if (position === undefined || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; +} + + +/** + * Returns new array from array like object or null if failed + * + * @param {*} [thing] + * + * @returns {?Array} + */ +const toArray = (thing) => { + if (!thing) return null; + if (isArray(thing)) return thing; + let i = thing.length; + if (!isNumber(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; +} + +/** + * Checking if the Uint8Array exists and if it does, it returns a function that checks if the + * thing passed in is an instance of Uint8Array + * + * @param {TypedArray} + * + * @returns {Array} + */ +// eslint-disable-next-line func-names +const isTypedArray = (TypedArray => { + // eslint-disable-next-line func-names + return thing => { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); + +/** + * For each entry in the object, call the function with the key and value. + * + * @param {Object} obj - The object to iterate over. + * @param {Function} fn - The function to call for each entry. + * + * @returns {void} + */ +const forEachEntry = (obj, fn) => { + const generator = obj && obj[Symbol.iterator]; + + const iterator = generator.call(obj); + + let result; + + while ((result = iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); + } +} + +/** + * It takes a regular expression and a string, and returns an array of all the matches + * + * @param {string} regExp - The regular expression to match against. + * @param {string} str - The string to search. + * + * @returns {Array} + */ +const matchAll = (regExp, str) => { + let matches; + const arr = []; + + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + + return arr; +} + +/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ +const isHTMLForm = kindOfTest('HTMLFormElement'); + +const toCamelCase = str => { + return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, + function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; + } + ); +}; + +/* Creating a function that will check if an object has a property. */ +const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); + +/** + * Determine if a value is a RegExp object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a RegExp object, otherwise false + */ +const isRegExp = kindOfTest('RegExp'); + +const reduceDescriptors = (obj, reducer) => { + const descriptors = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + + forEach(descriptors, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); + + Object.defineProperties(obj, reducedDescriptors); +} + +/** + * Makes all methods read-only + * @param {Object} obj + */ + +const freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name) => { + // skip restricted props in strict mode + if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { + return false; + } + + const value = obj[name]; + + if (!isFunction(value)) return; + + descriptor.enumerable = false; + + if ('writable' in descriptor) { + descriptor.writable = false; + return; + } + + if (!descriptor.set) { + descriptor.set = () => { + throw Error('Can not rewrite read-only method \'' + name + '\''); + }; + } + }); +} + +const toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; + + const define = (arr) => { + arr.forEach(value => { + obj[value] = true; + }); + } + + isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + + return obj; +} + +const noop = () => {} + +const toFiniteNumber = (value, defaultValue) => { + return value != null && Number.isFinite(value = +value) ? value : defaultValue; +} + +const ALPHA = 'abcdefghijklmnopqrstuvwxyz' + +const DIGIT = '0123456789'; + +const ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT +} + +const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { + let str = ''; + const {length} = alphabet; + while (size--) { + str += alphabet[Math.random() * length|0] + } + + return str; +} + +/** + * If the thing is a FormData object, return true, otherwise return false. + * + * @param {unknown} thing - The thing to check. + * + * @returns {boolean} + */ +function isSpecCompliantForm(thing) { + return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]); +} + +const toJSONObject = (obj) => { + const stack = new Array(10); + + const visit = (source, i) => { + + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + + if(!('toJSON' in source)) { + stack[i] = source; + const target = isArray(source) ? [] : {}; + + forEach(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + + stack[i] = undefined; + + return target; + } + } + + return source; + } + + return visit(obj, 0); +} + +const isAsyncFn = kindOfTest('AsyncFunction'); + +const isThenable = (thing) => + thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); + +// original code +// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 + +const _setImmediate = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; + } + + return postMessageSupported ? ((token, callbacks) => { + _global.addEventListener("message", ({source, data}) => { + if (source === _global && data === token) { + callbacks.length && callbacks.shift()(); + } + }, false); + + return (cb) => { + callbacks.push(cb); + _global.postMessage(token, "*"); + } + })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); +})( + typeof setImmediate === 'function', + isFunction(_global.postMessage) +); + +const asap = typeof queueMicrotask !== 'undefined' ? + queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate); + +// ********************* + +export default { + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString, + isNumber, + isBoolean, + isObject, + isPlainObject, + isReadableStream, + isRequest, + isResponse, + isHeaders, + isUndefined, + isDate, + isFile, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty, + hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + ALPHABET, + generateString, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable, + setImmediate: _setImmediate, + asap +}; diff --git a/node_modules/axios/package.json b/node_modules/axios/package.json new file mode 100644 index 000000000..feb4bb078 --- /dev/null +++ b/node_modules/axios/package.json @@ -0,0 +1,219 @@ +{ + "name": "axios", + "version": "1.7.9", + "description": "Promise based HTTP client for the browser and node.js", + "main": "index.js", + "exports": { + ".": { + "types": { + "require": "./index.d.cts", + "default": "./index.d.ts" + }, + "browser": { + "require": "./dist/browser/axios.cjs", + "default": "./index.js" + }, + "default": { + "require": "./dist/node/axios.cjs", + "default": "./index.js" + } + }, + "./lib/adapters/http.js": "./lib/adapters/http.js", + "./lib/adapters/xhr.js": "./lib/adapters/xhr.js", + "./unsafe/*": "./lib/*", + "./unsafe/core/settle.js": "./lib/core/settle.js", + "./unsafe/core/buildFullPath.js": "./lib/core/buildFullPath.js", + "./unsafe/helpers/isAbsoluteURL.js": "./lib/helpers/isAbsoluteURL.js", + "./unsafe/helpers/buildURL.js": "./lib/helpers/buildURL.js", + "./unsafe/helpers/combineURLs.js": "./lib/helpers/combineURLs.js", + "./unsafe/adapters/http.js": "./lib/adapters/http.js", + "./unsafe/adapters/xhr.js": "./lib/adapters/xhr.js", + "./unsafe/utils.js": "./lib/utils.js", + "./package.json": "./package.json" + }, + "type": "module", + "types": "index.d.ts", + "scripts": { + "test": "npm run test:eslint && npm run test:mocha && npm run test:karma && npm run test:dtslint && npm run test:exports", + "test:eslint": "node bin/ssl_hotfix.js eslint lib/**/*.js", + "test:dtslint": "dtslint --localTs node_modules/typescript/lib", + "test:mocha": "node bin/ssl_hotfix.js mocha test/unit/**/*.js --timeout 30000 --exit", + "test:exports": "node bin/ssl_hotfix.js mocha test/module/test.js --timeout 30000 --exit", + "test:karma": "node bin/ssl_hotfix.js cross-env LISTEN_ADDR=:: karma start karma.conf.cjs --single-run", + "test:karma:firefox": "node bin/ssl_hotfix.js cross-env LISTEN_ADDR=:: Browsers=Firefox karma start karma.conf.cjs --single-run", + "test:karma:server": "node bin/ssl_hotfix.js cross-env karma start karma.conf.cjs", + "test:build:version": "node ./bin/check-build-version.js", + "start": "node ./sandbox/server.js", + "preversion": "gulp version", + "version": "npm run build && git add dist && git add package.json", + "prepublishOnly": "npm run test:build:version", + "postpublish": "git push && git push --tags", + "build": "gulp clear && cross-env NODE_ENV=production rollup -c -m", + "examples": "node ./examples/server.js", + "coveralls": "cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js", + "fix": "eslint --fix lib/**/*.js", + "prepare": "husky install && npm run prepare:hooks", + "prepare:hooks": "npx husky set .husky/commit-msg \"npx commitlint --edit $1\"", + "release:dry": "release-it --dry-run --no-npm", + "release:info": "release-it --release-version", + "release:beta:no-npm": "release-it --preRelease=beta --no-npm", + "release:beta": "release-it --preRelease=beta", + "release:no-npm": "release-it --no-npm", + "release:changelog:fix": "node ./bin/injectContributorsList.js && git add CHANGELOG.md", + "release": "release-it" + }, + "repository": { + "type": "git", + "url": "https://github.com/axios/axios.git" + }, + "keywords": [ + "xhr", + "http", + "ajax", + "promise", + "node" + ], + "author": "Matt Zabriskie", + "license": "MIT", + "bugs": { + "url": "https://github.com/axios/axios/issues" + }, + "homepage": "https://axios-http.com", + "devDependencies": { + "@babel/core": "^7.23.9", + "@babel/preset-env": "^7.23.9", + "@commitlint/cli": "^17.8.1", + "@commitlint/config-conventional": "^17.8.1", + "@release-it/conventional-changelog": "^5.1.1", + "@rollup/plugin-babel": "^5.3.1", + "@rollup/plugin-commonjs": "^15.1.0", + "@rollup/plugin-json": "^4.1.0", + "@rollup/plugin-multi-entry": "^4.1.0", + "@rollup/plugin-node-resolve": "^9.0.0", + "abortcontroller-polyfill": "^1.7.5", + "auto-changelog": "^2.4.0", + "body-parser": "^1.20.2", + "chalk": "^5.3.0", + "coveralls": "^3.1.1", + "cross-env": "^7.0.3", + "dev-null": "^0.1.1", + "dtslint": "^4.2.1", + "es6-promise": "^4.2.8", + "eslint": "^8.56.0", + "express": "^4.18.2", + "formdata-node": "^5.0.1", + "formidable": "^2.1.2", + "fs-extra": "^10.1.0", + "get-stream": "^3.0.0", + "gulp": "^4.0.2", + "gzip-size": "^7.0.0", + "handlebars": "^4.7.8", + "husky": "^8.0.3", + "istanbul-instrumenter-loader": "^3.0.1", + "jasmine-core": "^2.99.1", + "karma": "^6.3.17", + "karma-chrome-launcher": "^3.2.0", + "karma-firefox-launcher": "^2.1.2", + "karma-jasmine": "^1.1.2", + "karma-jasmine-ajax": "^0.1.13", + "karma-rollup-preprocessor": "^7.0.8", + "karma-safari-launcher": "^1.0.0", + "karma-sauce-launcher": "^4.3.6", + "karma-sinon": "^1.0.5", + "karma-sourcemap-loader": "^0.3.8", + "memoizee": "^0.4.15", + "minimist": "^1.2.8", + "mocha": "^10.3.0", + "multer": "^1.4.4", + "pretty-bytes": "^6.1.1", + "release-it": "^15.11.0", + "rollup": "^2.79.1", + "rollup-plugin-auto-external": "^2.0.0", + "rollup-plugin-bundle-size": "^1.0.3", + "rollup-plugin-terser": "^7.0.2", + "sinon": "^4.5.0", + "stream-throttle": "^0.1.3", + "string-replace-async": "^3.0.2", + "terser-webpack-plugin": "^4.2.3", + "typescript": "^4.9.5", + "@rollup/plugin-alias": "^5.1.0" + }, + "browser": { + "./lib/adapters/http.js": "./lib/helpers/null.js", + "./lib/platform/node/index.js": "./lib/platform/browser/index.js", + "./lib/platform/node/classes/FormData.js": "./lib/helpers/null.js" + }, + "jsdelivr": "dist/axios.min.js", + "unpkg": "dist/axios.min.js", + "typings": "./index.d.ts", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + }, + "bundlesize": [ + { + "path": "./dist/axios.min.js", + "threshold": "5kB" + } + ], + "contributors": [ + "Matt Zabriskie (https://github.com/mzabriskie)", + "Nick Uraltsev (https://github.com/nickuraltsev)", + "Dmitriy Mozgovoy (https://github.com/DigitalBrainJS)", + "Jay (https://github.com/jasonsaayman)", + "Emily Morehouse (https://github.com/emilyemorehouse)", + "Justin Beckwith (https://github.com/JustinBeckwith)", + "Rubén Norte (https://github.com/rubennorte)", + "Martti Laine (https://github.com/codeclown)", + "Xianming Zhong (https://github.com/chinesedfan)", + "Remco Haszing (https://github.com/remcohaszing)", + "Rikki Gibson (https://github.com/RikkiGibson)", + "Yasu Flores (https://github.com/yasuf)", + "Ben Carp (https://github.com/carpben)" + ], + "sideEffects": false, + "release-it": { + "git": { + "commitMessage": "chore(release): v${version}", + "push": true, + "commit": true, + "tag": true, + "requireCommits": false, + "requireCleanWorkingDir": false + }, + "github": { + "release": true, + "draft": true + }, + "npm": { + "publish": false, + "ignoreVersion": false + }, + "plugins": { + "@release-it/conventional-changelog": { + "preset": "angular", + "infile": "CHANGELOG.md", + "header": "# Changelog" + } + }, + "hooks": { + "before:init": "npm test", + "after:bump": "gulp version --bump ${version} && npm run build && npm run test:build:version && git add ./dist && git add ./package-lock.json", + "before:release": "npm run release:changelog:fix", + "after:release": "echo Successfully released ${name} v${version} to ${repo.repository}." + } + }, + "commitlint": { + "rules": { + "header-max-length": [ + 2, + "always", + 130 + ] + }, + "extends": [ + "@commitlint/config-conventional" + ] + } +} \ No newline at end of file diff --git a/node_modules/base32.js/.npmignore b/node_modules/base32.js/.npmignore new file mode 100644 index 000000000..039729173 --- /dev/null +++ b/node_modules/base32.js/.npmignore @@ -0,0 +1,4 @@ +bower_components +node_modules +public +webpack.stats.json diff --git a/node_modules/base32.js/.travis.yml b/node_modules/base32.js/.travis.yml new file mode 100644 index 000000000..b127718a1 --- /dev/null +++ b/node_modules/base32.js/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.12 + - iojs diff --git a/node_modules/base32.js/HISTORY.md b/node_modules/base32.js/HISTORY.md new file mode 100644 index 000000000..aca8598a8 --- /dev/null +++ b/node_modules/base32.js/HISTORY.md @@ -0,0 +1,4 @@ +0.0.1 / 2015-02-15 +================== + + * Initial release diff --git a/node_modules/base32.js/README.md b/node_modules/base32.js/README.md new file mode 100644 index 000000000..8db86b5d4 --- /dev/null +++ b/node_modules/base32.js/README.md @@ -0,0 +1,71 @@ +# Base 32 for JavaScript [![Build Status](https://travis-ci.org/mikepb/base32.js.svg)](http://travis-ci.org/mikepb/base32.js) + +[Wikipedia](https://en.wikipedia.org/wiki/Base32): + +> Base32 is a base 32 transfer encoding using the twenty-six letters A–Z and six digits 2–7. It is primarily used to encode binary data, but is able to encode binary text like ASCII. +> +> Base32 has number of advantages over Base64: +> +> 1. The resulting character set is all one case (usually represented as uppercase), which can often be beneficial when using a case-insensitive filesystem, spoken language, or human memory. +> +> 2. The result can be used as file name because it can not possibly contain '/' symbol which is usually acts as path separator in Unix-based operating systems. +> +> 3. The alphabet was selected to avoid similar-looking pairs of different symbols, so the strings can be accurately transcribed by hand. (For example, the symbol set omits the symbols for 1, 8 and zero, since they could be confused with the letters 'I', 'B', and 'O'.) +> +> 4. A result without padding can be included in a URL without encoding any characters. +> +> However, Base32 representation takes roughly 20% more space than Base64. + +## Documentation + +Full documentation at http://mikepb.github.io/base32.js/ + +## Installation + +```sh +$ npm install base32.js +``` + +## Usage + +Encoding an array of bytes using [Crockford][crock32]: + +```js +var base32 = require("base32.js"); + +var buf = [1, 2, 3, 4]; +var encoder = new base32.Encoder({ type: "crockford", lc: true }); +var str = encoder.write(buf).finalize(); +// str = "04106173" + +var decoder = new base32.Decoder({ type: "crockford" }); +var out = decoder.write(str).finalize(); +// out = [1, 2, 3, 4] +``` + +The default Base32 variant if no `type` is provided is `"rfc4648"` without +padding. + +## Browser support + +The browser versions of the library may be found under the `dist/` directory. +The browser files are updated on each versioned release, but not for +development. [Karma][karma] is used to run the [mocha][] tests in the browser. + +```sh +$ npm install -g karma-cli +$ npm run karma +``` + +## Related projects + +- [agnoster/base32-js][agnoster] + +## License + +MIT + +[agnoster]: https://github.com/agnoster/base32-js +[crock32]: http://www.crockford.com/wrmg/base32.html +[karma]: http://karma-runner.github.io +[mocha]: http://mochajs.org diff --git a/node_modules/base32.js/base32.js b/node_modules/base32.js/base32.js new file mode 100644 index 000000000..e64f8964d --- /dev/null +++ b/node_modules/base32.js/base32.js @@ -0,0 +1,312 @@ +"use strict"; + +/** + * Generate a character map. + * @param {string} alphabet e.g. "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" + * @param {object} mappings map overrides from key to value + * @method + */ + +var charmap = function (alphabet, mappings) { + mappings || (mappings = {}); + alphabet.split("").forEach(function (c, i) { + if (!(c in mappings)) mappings[c] = i; + }); + return mappings; +} + +/** + * The RFC 4648 base 32 alphabet and character map. + * @see {@link https://tools.ietf.org/html/rfc4648} + */ + +var rfc4648 = { + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", + charmap: { + 0: 14, + 1: 8 + } +}; + +rfc4648.charmap = charmap(rfc4648.alphabet, rfc4648.charmap); + +/** + * The Crockford base 32 alphabet and character map. + * @see {@link http://www.crockford.com/wrmg/base32.html} + */ + +var crockford = { + alphabet: "0123456789ABCDEFGHJKMNPQRSTVWXYZ", + charmap: { + O: 0, + I: 1, + L: 1 + } +}; + +crockford.charmap = charmap(crockford.alphabet, crockford.charmap); + +/** + * base32hex + * @see {@link https://en.wikipedia.org/wiki/Base32#base32hex} + */ + +var base32hex = { + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", + charmap: {} +}; + +base32hex.charmap = charmap(base32hex.alphabet, base32hex.charmap); + +/** + * Create a new `Decoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [charmap] Override the character map used in decoding. + * @constructor + */ + +function Decoder (options) { + this.buf = []; + this.shift = 8; + this.carry = 0; + + if (options) { + + switch (options.type) { + case "rfc4648": + this.charmap = exports.rfc4648.charmap; + break; + case "crockford": + this.charmap = exports.crockford.charmap; + break; + case "base32hex": + this.charmap = exports.base32hex.charmap; + break; + default: + throw new Error("invalid type"); + } + + if (options.charmap) this.charmap = options.charmap; + } +} + +/** + * The default character map coresponds to RFC4648. + */ + +Decoder.prototype.charmap = rfc4648.charmap; + +/** + * Decode a string, continuing from the previous state. + * + * @param {string} str + * @return {Decoder} this + */ + +Decoder.prototype.write = function (str) { + var charmap = this.charmap; + var buf = this.buf; + var shift = this.shift; + var carry = this.carry; + + // decode string + str.toUpperCase().split("").forEach(function (char) { + + // ignore padding + if (char == "=") return; + + // lookup symbol + var symbol = charmap[char] & 0xff; + + // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 + + shift -= 5; + if (shift > 0) { + carry |= symbol << shift; + } else if (shift < 0) { + buf.push(carry | (symbol >> -shift)); + shift += 8; + carry = (symbol << shift) & 0xff; + } else { + buf.push(carry | symbol); + shift = 8; + carry = 0; + } + }); + + // save state + this.shift = shift; + this.carry = carry; + + // for chaining + return this; +}; + +/** + * Finish decoding. + * + * @param {string} [str] The final string to decode. + * @return {Array} Decoded byte array. + */ + +Decoder.prototype.finalize = function (str) { + if (str) { + this.write(str); + } + if (this.shift !== 8 && this.carry !== 0) { + this.buf.push(this.carry); + this.shift = 8; + this.carry = 0; + } + return this.buf; +}; + +/** + * Create a new `Encoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [alphabet] Override the alphabet used in encoding. + * @constructor + */ + +function Encoder (options) { + this.buf = ""; + this.shift = 3; + this.carry = 0; + + if (options) { + + switch (options.type) { + case "rfc4648": + this.alphabet = exports.rfc4648.alphabet; + break; + case "crockford": + this.alphabet = exports.crockford.alphabet; + break; + case "base32hex": + this.alphabet = exports.base32hex.alphabet; + break; + default: + throw new Error("invalid type"); + } + + if (options.alphabet) this.alphabet = options.alphabet; + else if (options.lc) this.alphabet = this.alphabet.toLowerCase(); + } +} + +/** + * The default alphabet coresponds to RFC4648. + */ + +Encoder.prototype.alphabet = rfc4648.alphabet; + +/** + * Encode a byte array, continuing from the previous state. + * + * @param {byte[]} buf The byte array to encode. + * @return {Encoder} this + */ + +Encoder.prototype.write = function (buf) { + var shift = this.shift; + var carry = this.carry; + var symbol; + var byte; + var i; + + // encode each byte in buf + for (i = 0; i < buf.length; i++) { + byte = buf[i]; + + // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 + + symbol = carry | (byte >> shift); + this.buf += this.alphabet[symbol & 0x1f]; + + if (shift > 5) { + shift -= 5; + symbol = byte >> shift; + this.buf += this.alphabet[symbol & 0x1f]; + } + + shift = 5 - shift; + carry = byte << shift; + shift = 8 - shift; + } + + // save state + this.shift = shift; + this.carry = carry; + + // for chaining + return this; +}; + +/** + * Finish encoding. + * + * @param {byte[]} [buf] The final byte array to encode. + * @return {string} The encoded byte array. + */ + +Encoder.prototype.finalize = function (buf) { + if (buf) { + this.write(buf); + } + if (this.shift !== 3) { + this.buf += this.alphabet[this.carry & 0x1f]; + this.shift = 3; + this.carry = 0; + } + return this.buf; +}; + +/** + * Convenience encoder. + * + * @param {byte[]} buf The byte array to encode. + * @param {object} [options] Options to pass to the encoder. + * @return {string} The encoded string. + */ + +exports.encode = function (buf, options) { + return new Encoder(options).finalize(buf); +}; + +/** + * Convenience decoder. + * + * @param {string} str The string to decode. + * @param {object} [options] Options to pass to the decoder. + * @return {byte[]} The decoded byte array. + */ + +exports.decode = function (str, options) { + return new Decoder(options).finalize(str); +}; + +// Exports. +exports.Decoder = Decoder; +exports.Encoder = Encoder; +exports.charmap = charmap; +exports.crockford = crockford; +exports.rfc4648 = rfc4648; +exports.base32hex = base32hex; diff --git a/node_modules/base32.js/dist/.gitkeep b/node_modules/base32.js/dist/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/base32.js/dist/base32.js b/node_modules/base32.js/dist/base32.js new file mode 100644 index 000000000..0a5884439 --- /dev/null +++ b/node_modules/base32.js/dist/base32.js @@ -0,0 +1,364 @@ +this["base32"] = +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; +/******/ +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + +"use strict"; + +/** + * Generate a character map. + * @param {string} alphabet e.g. "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" + * @param {object} mappings map overrides from key to value + * @method + */ + +var charmap = function (alphabet, mappings) { + mappings || (mappings = {}); + alphabet.split("").forEach(function (c, i) { + if (!(c in mappings)) mappings[c] = i; + }); + return mappings; +} + +/** + * The RFC 4648 base 32 alphabet and character map. + * @see {@link https://tools.ietf.org/html/rfc4648} + */ + +var rfc4648 = { + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", + charmap: { + 0: 14, + 1: 8 + } +}; + +rfc4648.charmap = charmap(rfc4648.alphabet, rfc4648.charmap); + +/** + * The Crockford base 32 alphabet and character map. + * @see {@link http://www.crockford.com/wrmg/base32.html} + */ + +var crockford = { + alphabet: "0123456789ABCDEFGHJKMNPQRSTVWXYZ", + charmap: { + O: 0, + I: 1, + L: 1 + } +}; + +crockford.charmap = charmap(crockford.alphabet, crockford.charmap); + +/** + * base32hex + * @see {@link https://en.wikipedia.org/wiki/Base32#base32hex} + */ + +var base32hex = { + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", + charmap: {} +}; + +base32hex.charmap = charmap(base32hex.alphabet, base32hex.charmap); + +/** + * Create a new `Decoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [charmap] Override the character map used in decoding. + * @constructor + */ + +function Decoder (options) { + this.buf = []; + this.shift = 8; + this.carry = 0; + + if (options) { + + switch (options.type) { + case "rfc4648": + this.charmap = exports.rfc4648.charmap; + break; + case "crockford": + this.charmap = exports.crockford.charmap; + break; + case "base32hex": + this.charmap = exports.base32hex.charmap; + break; + default: + throw new Error("invalid type"); + } + + if (options.charmap) this.charmap = options.charmap; + } +} + +/** + * The default character map coresponds to RFC4648. + */ + +Decoder.prototype.charmap = rfc4648.charmap; + +/** + * Decode a string, continuing from the previous state. + * + * @param {string} str + * @return {Decoder} this + */ + +Decoder.prototype.write = function (str) { + var charmap = this.charmap; + var buf = this.buf; + var shift = this.shift; + var carry = this.carry; + + // decode string + str.toUpperCase().split("").forEach(function (char) { + + // ignore padding + if (char == "=") return; + + // lookup symbol + var symbol = charmap[char] & 0xff; + + // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 + + shift -= 5; + if (shift > 0) { + carry |= symbol << shift; + } else if (shift < 0) { + buf.push(carry | (symbol >> -shift)); + shift += 8; + carry = (symbol << shift) & 0xff; + } else { + buf.push(carry | symbol); + shift = 8; + carry = 0; + } + }); + + // save state + this.shift = shift; + this.carry = carry; + + // for chaining + return this; +}; + +/** + * Finish decoding. + * + * @param {string} [str] The final string to decode. + * @return {Array} Decoded byte array. + */ + +Decoder.prototype.finalize = function (str) { + if (str) { + this.write(str); + } + if (this.shift !== 8 && this.carry !== 0) { + this.buf.push(this.carry); + this.shift = 8; + this.carry = 0; + } + return this.buf; +}; + +/** + * Create a new `Encoder` with the given options. + * + * @param {object} [options] + * @param {string} [type] Supported Base-32 variants are "rfc4648" and + * "crockford". + * @param {object} [alphabet] Override the alphabet used in encoding. + * @constructor + */ + +function Encoder (options) { + this.buf = ""; + this.shift = 3; + this.carry = 0; + + if (options) { + + switch (options.type) { + case "rfc4648": + this.alphabet = exports.rfc4648.alphabet; + break; + case "crockford": + this.alphabet = exports.crockford.alphabet; + break; + case "base32hex": + this.alphabet = exports.base32hex.alphabet; + break; + default: + throw new Error("invalid type"); + } + + if (options.alphabet) this.alphabet = options.alphabet; + else if (options.lc) this.alphabet = this.alphabet.toLowerCase(); + } +} + +/** + * The default alphabet coresponds to RFC4648. + */ + +Encoder.prototype.alphabet = rfc4648.alphabet; + +/** + * Encode a byte array, continuing from the previous state. + * + * @param {byte[]} buf The byte array to encode. + * @return {Encoder} this + */ + +Encoder.prototype.write = function (buf) { + var shift = this.shift; + var carry = this.carry; + var symbol; + var byte; + var i; + + // encode each byte in buf + for (i = 0; i < buf.length; i++) { + byte = buf[i]; + + // 1: 00000 000 + // 2: 00 00000 0 + // 3: 0000 0000 + // 4: 0 00000 00 + // 5: 000 00000 + // 6: 00000 000 + // 7: 00 00000 0 + + symbol = carry | (byte >> shift); + this.buf += this.alphabet[symbol & 0x1f]; + + if (shift > 5) { + shift -= 5; + symbol = byte >> shift; + this.buf += this.alphabet[symbol & 0x1f]; + } + + shift = 5 - shift; + carry = byte << shift; + shift = 8 - shift; + } + + // save state + this.shift = shift; + this.carry = carry; + + // for chaining + return this; +}; + +/** + * Finish encoding. + * + * @param {byte[]} [buf] The final byte array to encode. + * @return {string} The encoded byte array. + */ + +Encoder.prototype.finalize = function (buf) { + if (buf) { + this.write(buf); + } + if (this.shift !== 3) { + this.buf += this.alphabet[this.carry & 0x1f]; + this.shift = 3; + this.carry = 0; + } + return this.buf; +}; + +/** + * Convenience encoder. + * + * @param {byte[]} buf The byte array to encode. + * @param {object} [options] Options to pass to the encoder. + * @return {string} The encoded string. + */ + +exports.encode = function (buf, options) { + return new Encoder(options).finalize(buf); +}; + +/** + * Convenience decoder. + * + * @param {string} str The string to decode. + * @param {object} [options] Options to pass to the decoder. + * @return {byte[]} The decoded byte array. + */ + +exports.decode = function (str, options) { + return new Decoder(options).finalize(str); +}; + +// Exports. +exports.Decoder = Decoder; +exports.Encoder = Encoder; +exports.charmap = charmap; +exports.crockford = crockford; +exports.rfc4648 = rfc4648; +exports.base32hex = base32hex; + + +/***/ } +/******/ ]) +//# sourceMappingURL=base32.js.map \ No newline at end of file diff --git a/node_modules/base32.js/dist/base32.js.map b/node_modules/base32.js/dist/base32.js.map new file mode 100644 index 000000000..53cede265 --- /dev/null +++ b/node_modules/base32.js/dist/base32.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/bootstrap 221c6ffea9706b5be457","webpack:///./base32.js"],"names":[],"mappings":";;AAAA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,uBAAe;AACf;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA,wC;;;;;;;ACtCA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB;AACA;;AAEA;AACA,4BAA4B;AAC5B;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA,SAAS;AACT;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,SAAS;AACT;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,SAAS;AACT;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA,aAAa,OAAO;AACpB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,MAAM;AAClB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA,aAAa,OAAO;AACpB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,aAAa,gBAAgB;AAC7B;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,OAAO;AACnB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,YAAY,OAAO;AACnB;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,YAAY,OAAO;AACnB;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n/** WEBPACK FOOTER **\n ** webpack/bootstrap 221c6ffea9706b5be457\n **/","\"use strict\";\n\n/**\n * Generate a character map.\n * @param {string} alphabet e.g. \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\"\n * @param {object} mappings map overrides from key to value\n * @method\n */\n\nvar charmap = function (alphabet, mappings) {\n mappings || (mappings = {});\n alphabet.split(\"\").forEach(function (c, i) {\n if (!(c in mappings)) mappings[c] = i;\n });\n return mappings;\n}\n\n/**\n * The RFC 4648 base 32 alphabet and character map.\n * @see {@link https://tools.ietf.org/html/rfc4648}\n */\n\nvar rfc4648 = {\n alphabet: \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\",\n charmap: {\n 0: 14,\n 1: 8\n }\n};\n\nrfc4648.charmap = charmap(rfc4648.alphabet, rfc4648.charmap);\n\n/**\n * The Crockford base 32 alphabet and character map.\n * @see {@link http://www.crockford.com/wrmg/base32.html}\n */\n\nvar crockford = {\n alphabet: \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\",\n charmap: {\n O: 0,\n I: 1,\n L: 1\n }\n};\n\ncrockford.charmap = charmap(crockford.alphabet, crockford.charmap);\n\n/**\n * base32hex\n * @see {@link https://en.wikipedia.org/wiki/Base32#base32hex}\n */\n\nvar base32hex = {\n alphabet: \"0123456789ABCDEFGHIJKLMNOPQRSTUV\",\n charmap: {}\n};\n\nbase32hex.charmap = charmap(base32hex.alphabet, base32hex.charmap);\n\n/**\n * Create a new `Decoder` with the given options.\n *\n * @param {object} [options]\n * @param {string} [type] Supported Base-32 variants are \"rfc4648\" and\n * \"crockford\".\n * @param {object} [charmap] Override the character map used in decoding.\n * @constructor\n */\n\nfunction Decoder (options) {\n this.buf = [];\n this.shift = 8;\n this.carry = 0;\n\n if (options) {\n\n switch (options.type) {\n case \"rfc4648\":\n this.charmap = exports.rfc4648.charmap;\n break;\n case \"crockford\":\n this.charmap = exports.crockford.charmap;\n break;\n case \"base32hex\":\n this.charmap = exports.base32hex.charmap;\n break;\n default:\n throw new Error(\"invalid type\");\n }\n\n if (options.charmap) this.charmap = options.charmap;\n }\n}\n\n/**\n * The default character map coresponds to RFC4648.\n */\n\nDecoder.prototype.charmap = rfc4648.charmap;\n\n/**\n * Decode a string, continuing from the previous state.\n *\n * @param {string} str\n * @return {Decoder} this\n */\n\nDecoder.prototype.write = function (str) {\n var charmap = this.charmap;\n var buf = this.buf;\n var shift = this.shift;\n var carry = this.carry;\n\n // decode string\n str.toUpperCase().split(\"\").forEach(function (char) {\n\n // ignore padding\n if (char == \"=\") return;\n\n // lookup symbol\n var symbol = charmap[char] & 0xff;\n\n // 1: 00000 000\n // 2: 00 00000 0\n // 3: 0000 0000\n // 4: 0 00000 00\n // 5: 000 00000\n // 6: 00000 000\n // 7: 00 00000 0\n\n shift -= 5;\n if (shift > 0) {\n carry |= symbol << shift;\n } else if (shift < 0) {\n buf.push(carry | (symbol >> -shift));\n shift += 8;\n carry = (symbol << shift) & 0xff;\n } else {\n buf.push(carry | symbol);\n shift = 8;\n carry = 0;\n }\n });\n\n // save state\n this.shift = shift;\n this.carry = carry;\n\n // for chaining\n return this;\n};\n\n/**\n * Finish decoding.\n *\n * @param {string} [str] The final string to decode.\n * @return {Array} Decoded byte array.\n */\n\nDecoder.prototype.finalize = function (str) {\n if (str) {\n this.write(str);\n }\n if (this.shift !== 8 && this.carry !== 0) {\n this.buf.push(this.carry);\n this.shift = 8;\n this.carry = 0;\n }\n return this.buf;\n};\n\n/**\n * Create a new `Encoder` with the given options.\n *\n * @param {object} [options]\n * @param {string} [type] Supported Base-32 variants are \"rfc4648\" and\n * \"crockford\".\n * @param {object} [alphabet] Override the alphabet used in encoding.\n * @constructor\n */\n\nfunction Encoder (options) {\n this.buf = \"\";\n this.shift = 3;\n this.carry = 0;\n\n if (options) {\n\n switch (options.type) {\n case \"rfc4648\":\n this.alphabet = exports.rfc4648.alphabet;\n break;\n case \"crockford\":\n this.alphabet = exports.crockford.alphabet;\n break;\n case \"base32hex\":\n this.alphabet = exports.base32hex.alphabet;\n break;\n default:\n throw new Error(\"invalid type\");\n }\n\n if (options.alphabet) this.alphabet = options.alphabet;\n else if (options.lc) this.alphabet = this.alphabet.toLowerCase();\n }\n}\n\n/**\n * The default alphabet coresponds to RFC4648.\n */\n\nEncoder.prototype.alphabet = rfc4648.alphabet;\n\n/**\n * Encode a byte array, continuing from the previous state.\n *\n * @param {byte[]} buf The byte array to encode.\n * @return {Encoder} this\n */\n\nEncoder.prototype.write = function (buf) {\n var shift = this.shift;\n var carry = this.carry;\n var symbol;\n var byte;\n var i;\n\n // encode each byte in buf\n for (i = 0; i < buf.length; i++) {\n byte = buf[i];\n\n // 1: 00000 000\n // 2: 00 00000 0\n // 3: 0000 0000\n // 4: 0 00000 00\n // 5: 000 00000\n // 6: 00000 000\n // 7: 00 00000 0\n\n symbol = carry | (byte >> shift);\n this.buf += this.alphabet[symbol & 0x1f];\n\n if (shift > 5) {\n shift -= 5;\n symbol = byte >> shift;\n this.buf += this.alphabet[symbol & 0x1f];\n }\n\n shift = 5 - shift;\n carry = byte << shift;\n shift = 8 - shift;\n }\n\n // save state\n this.shift = shift;\n this.carry = carry;\n\n // for chaining\n return this;\n};\n\n/**\n * Finish encoding.\n *\n * @param {byte[]} [buf] The final byte array to encode.\n * @return {string} The encoded byte array.\n */\n\nEncoder.prototype.finalize = function (buf) {\n if (buf) {\n this.write(buf);\n }\n if (this.shift !== 3) {\n this.buf += this.alphabet[this.carry & 0x1f];\n this.shift = 3;\n this.carry = 0;\n }\n return this.buf;\n};\n\n/**\n * Convenience encoder.\n *\n * @param {byte[]} buf The byte array to encode.\n * @param {object} [options] Options to pass to the encoder.\n * @return {string} The encoded string.\n */\n\nexports.encode = function (buf, options) {\n return new Encoder(options).finalize(buf);\n};\n\n/**\n * Convenience decoder.\n *\n * @param {string} str The string to decode.\n * @param {object} [options] Options to pass to the decoder.\n * @return {byte[]} The decoded byte array.\n */\n\nexports.decode = function (str, options) {\n return new Decoder(options).finalize(str);\n};\n\n// Exports.\nexports.Decoder = Decoder;\nexports.Encoder = Encoder;\nexports.charmap = charmap;\nexports.crockford = crockford;\nexports.rfc4648 = rfc4648;\nexports.base32hex = base32hex;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./base32.js\n ** module id = 0\n ** module chunks = 0\n **/"],"sourceRoot":"","file":"base32.js"} \ No newline at end of file diff --git a/node_modules/base32.js/dist/base32.min.js b/node_modules/base32.js/dist/base32.min.js new file mode 100644 index 000000000..d09753551 --- /dev/null +++ b/node_modules/base32.js/dist/base32.min.js @@ -0,0 +1,2 @@ +this.base32=function(t){function a(h){if(r[h])return r[h].exports;var i=r[h]={exports:{},id:h,loaded:!1};return t[h].call(i.exports,i,i.exports,a),i.loaded=!0,i.exports}var r={};return a.m=t,a.c=r,a.p="",a(0)}([function(t,a){"use strict";function r(t){if(this.buf=[],this.shift=8,this.carry=0,t){switch(t.type){case"rfc4648":this.charmap=a.rfc4648.charmap;break;case"crockford":this.charmap=a.crockford.charmap;break;case"base32hex":this.charmap=a.base32hex.charmap;break;default:throw new Error("invalid type")}t.charmap&&(this.charmap=t.charmap)}}function h(t){if(this.buf="",this.shift=3,this.carry=0,t){switch(t.type){case"rfc4648":this.alphabet=a.rfc4648.alphabet;break;case"crockford":this.alphabet=a.crockford.alphabet;break;case"base32hex":this.alphabet=a.base32hex.alphabet;break;default:throw new Error("invalid type")}t.alphabet?this.alphabet=t.alphabet:t.lc&&(this.alphabet=this.alphabet.toLowerCase())}}var i=function(t,a){return a||(a={}),t.split("").forEach(function(t,r){t in a||(a[t]=r)}),a},e={alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",charmap:{0:14,1:8}};e.charmap=i(e.alphabet,e.charmap);var s={alphabet:"0123456789ABCDEFGHJKMNPQRSTVWXYZ",charmap:{O:0,I:1,L:1}};s.charmap=i(s.alphabet,s.charmap);var c={alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",charmap:{}};c.charmap=i(c.alphabet,c.charmap),r.prototype.charmap=e.charmap,r.prototype.write=function(t){var a=this.charmap,r=this.buf,h=this.shift,i=this.carry;return t.toUpperCase().split("").forEach(function(t){if("="!=t){var e=255&a[t];h-=5,h>0?i|=e<h?(r.push(i|e>>-h),h+=8,i=e<>i,this.buf+=this.alphabet[31&a],i>5&&(i-=5,a=r>>i,this.buf+=this.alphabet[31&a]),i=5-i,e=r< 0) {\n carry |= symbol << shift;\n } else if (shift < 0) {\n buf.push(carry | (symbol >> -shift));\n shift += 8;\n carry = (symbol << shift) & 0xff;\n } else {\n buf.push(carry | symbol);\n shift = 8;\n carry = 0;\n }\n });\n\n // save state\n this.shift = shift;\n this.carry = carry;\n\n // for chaining\n return this;\n};\n\n/**\n * Finish decoding.\n *\n * @param {string} [str] The final string to decode.\n * @return {Array} Decoded byte array.\n */\n\nDecoder.prototype.finalize = function (str) {\n if (str) {\n this.write(str);\n }\n if (this.shift !== 8 && this.carry !== 0) {\n this.buf.push(this.carry);\n this.shift = 8;\n this.carry = 0;\n }\n return this.buf;\n};\n\n/**\n * Create a new `Encoder` with the given options.\n *\n * @param {object} [options]\n * @param {string} [type] Supported Base-32 variants are \"rfc4648\" and\n * \"crockford\".\n * @param {object} [alphabet] Override the alphabet used in encoding.\n * @constructor\n */\n\nfunction Encoder (options) {\n this.buf = \"\";\n this.shift = 3;\n this.carry = 0;\n\n if (options) {\n\n switch (options.type) {\n case \"rfc4648\":\n this.alphabet = exports.rfc4648.alphabet;\n break;\n case \"crockford\":\n this.alphabet = exports.crockford.alphabet;\n break;\n case \"base32hex\":\n this.alphabet = exports.base32hex.alphabet;\n break;\n default:\n throw new Error(\"invalid type\");\n }\n\n if (options.alphabet) this.alphabet = options.alphabet;\n else if (options.lc) this.alphabet = this.alphabet.toLowerCase();\n }\n}\n\n/**\n * The default alphabet coresponds to RFC4648.\n */\n\nEncoder.prototype.alphabet = rfc4648.alphabet;\n\n/**\n * Encode a byte array, continuing from the previous state.\n *\n * @param {byte[]} buf The byte array to encode.\n * @return {Encoder} this\n */\n\nEncoder.prototype.write = function (buf) {\n var shift = this.shift;\n var carry = this.carry;\n var symbol;\n var byte;\n var i;\n\n // encode each byte in buf\n for (i = 0; i < buf.length; i++) {\n byte = buf[i];\n\n // 1: 00000 000\n // 2: 00 00000 0\n // 3: 0000 0000\n // 4: 0 00000 00\n // 5: 000 00000\n // 6: 00000 000\n // 7: 00 00000 0\n\n symbol = carry | (byte >> shift);\n this.buf += this.alphabet[symbol & 0x1f];\n\n if (shift > 5) {\n shift -= 5;\n symbol = byte >> shift;\n this.buf += this.alphabet[symbol & 0x1f];\n }\n\n shift = 5 - shift;\n carry = byte << shift;\n shift = 8 - shift;\n }\n\n // save state\n this.shift = shift;\n this.carry = carry;\n\n // for chaining\n return this;\n};\n\n/**\n * Finish encoding.\n *\n * @param {byte[]} [buf] The final byte array to encode.\n * @return {string} The encoded byte array.\n */\n\nEncoder.prototype.finalize = function (buf) {\n if (buf) {\n this.write(buf);\n }\n if (this.shift !== 3) {\n this.buf += this.alphabet[this.carry & 0x1f];\n this.shift = 3;\n this.carry = 0;\n }\n return this.buf;\n};\n\n/**\n * Convenience encoder.\n *\n * @param {byte[]} buf The byte array to encode.\n * @param {object} [options] Options to pass to the encoder.\n * @return {string} The encoded string.\n */\n\nexports.encode = function (buf, options) {\n return new Encoder(options).finalize(buf);\n};\n\n/**\n * Convenience decoder.\n *\n * @param {string} str The string to decode.\n * @param {object} [options] Options to pass to the decoder.\n * @return {byte[]} The decoded byte array.\n */\n\nexports.decode = function (str, options) {\n return new Decoder(options).finalize(str);\n};\n\n// Exports.\nexports.Decoder = Decoder;\nexports.Encoder = Encoder;\nexports.charmap = charmap;\nexports.crockford = crockford;\nexports.rfc4648 = rfc4648;\nexports.base32hex = base32hex;\n\n\n/***/ }\n/******/ ])\n\n\n/** WEBPACK FOOTER **\n ** base32.min.js\n **/"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n/** WEBPACK FOOTER **\n ** webpack/bootstrap da2e7e41f8f005e65df6\n **/","\"use strict\";\n\n/**\n * Generate a character map.\n * @param {string} alphabet e.g. \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\"\n * @param {object} mappings map overrides from key to value\n * @method\n */\n\nvar charmap = function (alphabet, mappings) {\n mappings || (mappings = {});\n alphabet.split(\"\").forEach(function (c, i) {\n if (!(c in mappings)) mappings[c] = i;\n });\n return mappings;\n}\n\n/**\n * The RFC 4648 base 32 alphabet and character map.\n * @see {@link https://tools.ietf.org/html/rfc4648}\n */\n\nvar rfc4648 = {\n alphabet: \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\",\n charmap: {\n 0: 14,\n 1: 8\n }\n};\n\nrfc4648.charmap = charmap(rfc4648.alphabet, rfc4648.charmap);\n\n/**\n * The Crockford base 32 alphabet and character map.\n * @see {@link http://www.crockford.com/wrmg/base32.html}\n */\n\nvar crockford = {\n alphabet: \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\",\n charmap: {\n O: 0,\n I: 1,\n L: 1\n }\n};\n\ncrockford.charmap = charmap(crockford.alphabet, crockford.charmap);\n\n/**\n * base32hex\n * @see {@link https://en.wikipedia.org/wiki/Base32#base32hex}\n */\n\nvar base32hex = {\n alphabet: \"0123456789ABCDEFGHIJKLMNOPQRSTUV\",\n charmap: {}\n};\n\nbase32hex.charmap = charmap(base32hex.alphabet, base32hex.charmap);\n\n/**\n * Create a new `Decoder` with the given options.\n *\n * @param {object} [options]\n * @param {string} [type] Supported Base-32 variants are \"rfc4648\" and\n * \"crockford\".\n * @param {object} [charmap] Override the character map used in decoding.\n * @constructor\n */\n\nfunction Decoder (options) {\n this.buf = [];\n this.shift = 8;\n this.carry = 0;\n\n if (options) {\n\n switch (options.type) {\n case \"rfc4648\":\n this.charmap = exports.rfc4648.charmap;\n break;\n case \"crockford\":\n this.charmap = exports.crockford.charmap;\n break;\n case \"base32hex\":\n this.charmap = exports.base32hex.charmap;\n break;\n default:\n throw new Error(\"invalid type\");\n }\n\n if (options.charmap) this.charmap = options.charmap;\n }\n}\n\n/**\n * The default character map coresponds to RFC4648.\n */\n\nDecoder.prototype.charmap = rfc4648.charmap;\n\n/**\n * Decode a string, continuing from the previous state.\n *\n * @param {string} str\n * @return {Decoder} this\n */\n\nDecoder.prototype.write = function (str) {\n var charmap = this.charmap;\n var buf = this.buf;\n var shift = this.shift;\n var carry = this.carry;\n\n // decode string\n str.toUpperCase().split(\"\").forEach(function (char) {\n\n // ignore padding\n if (char == \"=\") return;\n\n // lookup symbol\n var symbol = charmap[char] & 0xff;\n\n // 1: 00000 000\n // 2: 00 00000 0\n // 3: 0000 0000\n // 4: 0 00000 00\n // 5: 000 00000\n // 6: 00000 000\n // 7: 00 00000 0\n\n shift -= 5;\n if (shift > 0) {\n carry |= symbol << shift;\n } else if (shift < 0) {\n buf.push(carry | (symbol >> -shift));\n shift += 8;\n carry = (symbol << shift) & 0xff;\n } else {\n buf.push(carry | symbol);\n shift = 8;\n carry = 0;\n }\n });\n\n // save state\n this.shift = shift;\n this.carry = carry;\n\n // for chaining\n return this;\n};\n\n/**\n * Finish decoding.\n *\n * @param {string} [str] The final string to decode.\n * @return {Array} Decoded byte array.\n */\n\nDecoder.prototype.finalize = function (str) {\n if (str) {\n this.write(str);\n }\n if (this.shift !== 8 && this.carry !== 0) {\n this.buf.push(this.carry);\n this.shift = 8;\n this.carry = 0;\n }\n return this.buf;\n};\n\n/**\n * Create a new `Encoder` with the given options.\n *\n * @param {object} [options]\n * @param {string} [type] Supported Base-32 variants are \"rfc4648\" and\n * \"crockford\".\n * @param {object} [alphabet] Override the alphabet used in encoding.\n * @constructor\n */\n\nfunction Encoder (options) {\n this.buf = \"\";\n this.shift = 3;\n this.carry = 0;\n\n if (options) {\n\n switch (options.type) {\n case \"rfc4648\":\n this.alphabet = exports.rfc4648.alphabet;\n break;\n case \"crockford\":\n this.alphabet = exports.crockford.alphabet;\n break;\n case \"base32hex\":\n this.alphabet = exports.base32hex.alphabet;\n break;\n default:\n throw new Error(\"invalid type\");\n }\n\n if (options.alphabet) this.alphabet = options.alphabet;\n else if (options.lc) this.alphabet = this.alphabet.toLowerCase();\n }\n}\n\n/**\n * The default alphabet coresponds to RFC4648.\n */\n\nEncoder.prototype.alphabet = rfc4648.alphabet;\n\n/**\n * Encode a byte array, continuing from the previous state.\n *\n * @param {byte[]} buf The byte array to encode.\n * @return {Encoder} this\n */\n\nEncoder.prototype.write = function (buf) {\n var shift = this.shift;\n var carry = this.carry;\n var symbol;\n var byte;\n var i;\n\n // encode each byte in buf\n for (i = 0; i < buf.length; i++) {\n byte = buf[i];\n\n // 1: 00000 000\n // 2: 00 00000 0\n // 3: 0000 0000\n // 4: 0 00000 00\n // 5: 000 00000\n // 6: 00000 000\n // 7: 00 00000 0\n\n symbol = carry | (byte >> shift);\n this.buf += this.alphabet[symbol & 0x1f];\n\n if (shift > 5) {\n shift -= 5;\n symbol = byte >> shift;\n this.buf += this.alphabet[symbol & 0x1f];\n }\n\n shift = 5 - shift;\n carry = byte << shift;\n shift = 8 - shift;\n }\n\n // save state\n this.shift = shift;\n this.carry = carry;\n\n // for chaining\n return this;\n};\n\n/**\n * Finish encoding.\n *\n * @param {byte[]} [buf] The final byte array to encode.\n * @return {string} The encoded byte array.\n */\n\nEncoder.prototype.finalize = function (buf) {\n if (buf) {\n this.write(buf);\n }\n if (this.shift !== 3) {\n this.buf += this.alphabet[this.carry & 0x1f];\n this.shift = 3;\n this.carry = 0;\n }\n return this.buf;\n};\n\n/**\n * Convenience encoder.\n *\n * @param {byte[]} buf The byte array to encode.\n * @param {object} [options] Options to pass to the encoder.\n * @return {string} The encoded string.\n */\n\nexports.encode = function (buf, options) {\n return new Encoder(options).finalize(buf);\n};\n\n/**\n * Convenience decoder.\n *\n * @param {string} str The string to decode.\n * @param {object} [options] Options to pass to the decoder.\n * @return {byte[]} The decoded byte array.\n */\n\nexports.decode = function (str, options) {\n return new Decoder(options).finalize(str);\n};\n\n// Exports.\nexports.Decoder = Decoder;\nexports.Encoder = Encoder;\nexports.charmap = charmap;\nexports.crockford = crockford;\nexports.rfc4648 = rfc4648;\nexports.base32hex = base32hex;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./base32.js\n ** module id = 0\n ** module chunks = 0\n **/"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/base32.js/index.js b/node_modules/base32.js/index.js new file mode 100644 index 000000000..e380c1686 --- /dev/null +++ b/node_modules/base32.js/index.js @@ -0,0 +1,16 @@ +"use strict"; + +// Module dependencies. +var base32 = require("./base32"); + + +// Wrap decoder finalize to return a buffer; +var finalizeDecode = base32.Decoder.prototype.finalize; +base32.Decoder.prototype.finalize = function (buf) { + var bytes = finalizeDecode.call(this, buf); + return new Buffer(bytes); +}; + + +// Export Base32. +module.exports = base32; diff --git a/node_modules/base32.js/jsdoc.json b/node_modules/base32.js/jsdoc.json new file mode 100644 index 000000000..d576a708f --- /dev/null +++ b/node_modules/base32.js/jsdoc.json @@ -0,0 +1,33 @@ +{ + "source": { + "include": [ + "base32.js", + "package.json", + "README.md" + ] + }, + "plugins": ["plugins/markdown"], + "templates": { + "applicationName": "base32.js", + "meta": { + "title": "base32.js", + "description": "base32.js - Base 32 for JavaScript", + "keyword": [ + "base32", + "base32hex", + "crockford", + "rfc2938", + "rfc4648", + "encoding", + "decoding" + ] + }, + "default": { + "outputSourceFiles": true + }, + "linenums": true + }, + "opts": { + "destination": "docs" + } +} diff --git a/node_modules/base32.js/karma.conf.js b/node_modules/base32.js/karma.conf.js new file mode 100644 index 000000000..498312f61 --- /dev/null +++ b/node_modules/base32.js/karma.conf.js @@ -0,0 +1,33 @@ +"use strict"; + +/** + * Karma configuration. + */ + +module.exports = function (config) { + config.set({ + + frameworks: ["mocha"], + + files: [ + "test/**_test.js" + ], + + preprocessors: { + "test/**_test.js": ["webpack"] + }, + + reporters: ["progress"], + + browsers: ["Chrome"], + + webpack: require("./webpack.config"), + + plugins: [ + "karma-chrome-launcher", + "karma-mocha", + "karma-webpack" + ] + + }); +}; diff --git a/node_modules/base32.js/package.json b/node_modules/base32.js/package.json new file mode 100644 index 000000000..3252bbf43 --- /dev/null +++ b/node_modules/base32.js/package.json @@ -0,0 +1,42 @@ +{ + "name": "base32.js", + "version": "0.1.0", + "author": "Michael Phan-Ba ", + "description": "Base 32 encodings for JavaScript", + "keywords": [ + "base32", + "base32hex", + "crockford", + "rfc2938", + "rfc4648", + "encoding", + "decoding" + ], + "license": "MIT", + "main": "index.js", + "browser": "base32.js", + "engines": { + "node": ">=0.12.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/mikepb/base32.js.git" + }, + "scripts": { + "test": "mocha --reporter dot", + "karma": "karma start --single-run", + "dist": "webpack base32.js dist/base32.js && webpack --optimize-minimize base32.js dist/base32.min.js", + "doc": "jsdoc -c jsdoc.json" + }, + "dependencies": { + }, + "devDependencies": { + "jsdoc": "*", + "karma": "*", + "karma-chrome-launcher": "*", + "karma-mocha": "*", + "karma-webpack": "*", + "mocha": "*", + "webpack": "*" + } +} diff --git a/node_modules/base32.js/test/base32_test.js b/node_modules/base32.js/test/base32_test.js new file mode 100644 index 000000000..0cfb33b80 --- /dev/null +++ b/node_modules/base32.js/test/base32_test.js @@ -0,0 +1,87 @@ +"use strict"; + +var assert = require("assert"); +var base32 = require(".."); +var fixtures = require("./fixtures"); + +describe("Decoder", function () { + + fixtures.forEach(function (subject) { + var test = subject.buf; + + subject.rfc4648.forEach(function (str) { + it("should decode rfc4648 " + str, function () { + var decoder = new base32.Decoder({ type: "rfc4648" }); + var decoded = decoder.write(str).finalize(); + compare(decoded, test); + var s = new base32.Decoder().write(str).finalize(); + compare(s, test); + }); + }); + + subject.crock32.forEach(function (str) { + it("should decode crock32 " + str, function () { + var decoder = new base32.Decoder({ type: "crockford" }); + var decoded = decoder.write(str).finalize(); + compare(decoded, test); + }); + }); + + subject.base32hex.forEach(function (str) { + it("should decode base32hex " + str, function () { + var decoder = new base32.Decoder({ type: "base32hex" }); + var decoded = decoder.write(str).finalize(); + compare(decoded, test); + }); + }); + + }); + +}); + +describe("Encoder", function () { + + fixtures.forEach(function (subject) { + var buf = subject.buf; + + it("should encode rfc4648 " + buf, function () { + var test = subject.rfc4648[0]; + var encoder = new base32.Encoder({ type: "rfc4648" }); + var encode = encoder.write(buf).finalize(); + assert.equal(encode, test); + var s = new base32.Encoder().write(buf).finalize(); + assert.equal(s, test); + }); + + it("should encode crock32 " + buf, function () { + var test = subject.crock32[0]; + var encoder = new base32.Encoder({ type: "crockford" }); + var encoded = encoder.write(buf).finalize(); + assert.equal(encoded, test); + }); + + it("should encode crock32 " + buf + " with lower case", function () { + var test = subject.crock32[0]; + var encoder = new base32.Encoder({ type: "crockford", lc: true }); + var encoded = encoder.write(buf).finalize(); + assert.equal(encoded, test.toLowerCase()); + }); + + it("should encode base32hex " + buf + " with lower case", function () { + var test = subject.base32hex[0]; + var encoder = new base32.Encoder({ type: "base32hex", lc: true }); + var encoded = encoder.write(buf).finalize(); + assert.equal(encoded, test.toLowerCase()); + }); + + }); + +}); + +function compare (a, b) { + if (typeof Buffer != "undefined") { + b = new Buffer(b); + return assert.strictEqual(b.compare(a), 0); + } + assert.deepEqual(a, b); +} diff --git a/node_modules/base32.js/test/fixtures.js b/node_modules/base32.js/test/fixtures.js new file mode 100644 index 000000000..172630ee0 --- /dev/null +++ b/node_modules/base32.js/test/fixtures.js @@ -0,0 +1,294 @@ +"use strict"; + +module.exports = [ + { + buf: [0], + rfc4648: ["AA", "aa"], + crock32: ["00", "0O", "0o"], + crock32int: ["0", "O", "o"], + base32hex: ["00"] + }, + { + buf: [1], + rfc4648: ["AE"], + crock32: ["04"], + crock32int: ["1", "I", "i", "L", "l"], + base32hex: ["04"] + }, + { + buf: [2], + rfc4648: ["AI", "ai", "aI", "Ai"], + crock32: ["08"], + crock32int: ["2"], + base32hex: ["08"] + }, + { + buf: [3], + rfc4648: ["AM", "am", "aM", "Am"], + crock32: ["0C"], + crock32int: ["3"], + base32hex: ["0C"] + }, + { + buf: [4], + rfc4648: ["AQ", "aq", "aQ", "Aq"], + crock32: ["0G"], + crock32int: ["4"], + base32hex: ["0G"] + }, + { + buf: [5], + rfc4648: ["AU", "au", "aU", "Au"], + crock32: ["0M"], + crock32int: ["5"], + base32hex: ["0K"] + }, + { + buf: [6], + rfc4648: ["AY", "ay", "aY", "Ay"], + crock32: ["0R"], + crock32int: ["6"], + base32hex: ["0O"] + }, + { + buf: [7], + rfc4648: ["A4", "a4"], + crock32: ["0W"], + crock32int: ["7"], + base32hex: ["0S"] + }, + { + buf: [8], + rfc4648: ["BA", "ba", "bA", "Ba"], + crock32: ["10"], + crock32int: ["8"], + base32hex: ["10"] + }, + { + buf: [9], + rfc4648: ["BE", "be", "bE", "Be"], + crock32: ["14"], + crock32int: ["9"], + base32hex: ["14"] + }, + { + buf: [10], + rfc4648: ["BI", "bi", "bI", "Bi"], + crock32: ["18"], + crock32int: ["A", "a"], + base32hex: ["18"] + }, + { + buf: [11], + rfc4648: ["BM", "bm", "bM", "Bm"], + crock32: ["1C"], + crock32int: ["B", "b"], + base32hex: ["1C"] + }, + { + buf: [12], + rfc4648: ["BQ", "bq", "bQ", "Bq"], + crock32: ["1G"], + crock32int: ["C", "c"], + base32hex: ["1G"] + }, + { + buf: [13], + rfc4648: ["BU", "bu", "bU", "Bu"], + crock32: ["1M"], + crock32int: ["D", "d"], + base32hex: ["1K"] + }, + { + buf: [14], + rfc4648: ["BY", "by", "bY", "By"], + crock32: ["1R"], + crock32int: ["E", "e"], + base32hex: ["1O"] + }, + { + buf: [15], + rfc4648: ["B4", "b4"], + crock32: ["1W"], + crock32int: ["F", "f"], + base32hex: ["1S"] + }, + { + buf: [16], + rfc4648: ["CA", "ca", "cA", "Ca"], + crock32: ["20"], + crock32int: ["G", "g"], + base32hex: ["20"] + }, + { + buf: [17], + rfc4648: ["CE", "ce", "cE", "Ce"], + crock32: ["24"], + crock32int: ["H", "h"], + base32hex: ["24"] + }, + { + buf: [18], + rfc4648: ["CI", "ci", "cI", "Ci"], + crock32: ["28"], + crock32int: ["J", "j"], + base32hex: ["28"] + }, + { + buf: [19], + rfc4648: ["CM", "cm", "cM", "Cm"], + crock32: ["2C"], + crock32int: ["K", "k"], + base32hex: ["2C"] + }, + { + buf: [20], + rfc4648: ["CQ", "cq", "cQ", "Cq"], + crock32: ["2G"], + crock32int: ["M", "m"], + base32hex: ["2G"] + }, + { + buf: [21], + rfc4648: ["CU", "cu", "cU", "Cu"], + crock32: ["2M"], + crock32int: ["N", "n"], + base32hex: ["2K"] + }, + { + buf: [22], + rfc4648: ["CY", "cy", "cY", "Cy"], + crock32: ["2R"], + crock32int: ["P", "p"], + base32hex: ["2O"] + }, + { + buf: [23], + rfc4648: ["C4", "c4"], + crock32: ["2W"], + crock32int: ["Q", "q"], + base32hex: ["2S"] + }, + { + buf: [24], + rfc4648: ["DA", "da", "dA", "Da"], + crock32: ["30"], + crock32int: ["R", "r"], + base32hex: ["30"] + }, + { + buf: [25], + rfc4648: ["DE", "de", "dE", "De"], + crock32: ["34"], + crock32int: ["S", "s"], + base32hex: ["34"] + }, + { + buf: [26], + rfc4648: ["DI", "di", "dI", "Di"], + crock32: ["38"], + crock32int: ["T", "t"], + base32hex: ["38"] + }, + { + buf: [27], + rfc4648: ["DM", "dm", "dM", "Dm"], + crock32: ["3C"], + crock32int: ["V", "v"], + base32hex: ["3C"] + }, + { + buf: [28], + rfc4648: ["DQ", "dq", "dQ", "Dq"], + crock32: ["3G"], + crock32int: ["W", "w"], + base32hex: ["3G"] + }, + { + buf: [29], + rfc4648: ["DU", "du", "dU", "Du"], + crock32: ["3M"], + crock32int: ["X", "x"], + base32hex: ["3k"] + }, + { + buf: [30], + rfc4648: ["DY", "dy", "dY", "Dy"], + crock32: ["3R"], + crock32int: ["Y", "y"], + base32hex: ["3O"] + }, + { + buf: [31], + rfc4648: ["D4", "d4"], + crock32: ["3W"], + crock32int: ["Z", "z"], + base32hex: ["3S"] + }, + { + buf: [0, 0], + rfc4648: ["AAAA", "aaaa", "AaAa", "aAAa"], + crock32: ["0000", "oooo", "OOOO", "0oO0"], + base32hex: ["0000"] + }, + { + buf: [1, 0], + rfc4648: ["AEAA", "aeaa", "AeAa", "aEAa"], + crock32: ["0400", "o4oo", "O4OO", "04oO"], + base32hex: ["0400"] + }, + { + buf: [0, 1], + rfc4648: ["AAAQ", "aaaq", "AaAQ", "aAAq"], + crock32: ["000G", "ooog", "OOOG", "0oOg"], + base32hex: ["000G"] + }, + { + buf: [1, 1], + rfc4648: ["AEAQ", "aeaq", "AeAQ", "aEAq"], + crock32: ["040G", "o4og", "O4og", "04Og"], + base32hex: ["040G"] + }, + { + buf: [136, 64], + rfc4648: ["RBAA", "rbaa", "RbAA", "rBAa"], + crock32: ["H100", "hio0", "HLOo"], + base32hex: ["H100"] + }, + { + buf: [139, 188], + rfc4648: ["RO6A", "r06a", "Ro6A", "r06A"], + crock32: ["HEY0", "heyo", "HeYO"], + base32hex: ["HEU0"] + }, + { + buf: [54, 31, 127], + rfc4648: ["GYPX6", "gypx6"], + crock32: ["6RFQY", "6rfqy"], + base32hex: ["6OFNU"] + }, + { + buf: [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33], + rfc4648: ["JBSWY3DPEBLW64TMMQQQ", "jbswy3dpeblw64tmmqqq"], + crock32: ["91JPRV3F41BPYWKCCGGG", "91jprv3f41bpywkccggg", "9Ljprv3f4ibpywkccggg"], + base32hex: ["91IMOR3F41BMUSJCCGGG"] + }, + { + buf: [139, 130, 16, 112, 24, 11, 64], + rfc4648: ["ROBBA4AYBNAA", "robba4aybnaa", "R0BBA4aybnaa"], + crock32: ["HE110W0R1D00", "helloworld00", "heiiOw0RidoO"], + base32hex: ["HE110S0O1D00"] + }, + { + buf: [139, 130, 16, 112, 24, 11], + rfc4648: ["ROBBA4AYBM", "robba4aybm", "R0BBA4aybm"], + crock32: ["HE110W0R1C", "helloworlc", "heiiOw0RiC"], + base32hex: ["HE110S0O1C"] + }, + { + buf: [139, 130, 16, 112, 24, 11, 0], + rfc4648: ["ROBBA4AYBMAA", "robba4aybmaa", "R0BBA4aybmaa"], + crock32: ["HE110W0R1C00", "helloworlc00", "heiiOw0RiC00"], + base32hex: ["HE110S0O1C00"] + } +]; diff --git a/node_modules/base32.js/webpack.config.js b/node_modules/base32.js/webpack.config.js new file mode 100644 index 000000000..c7bc92657 --- /dev/null +++ b/node_modules/base32.js/webpack.config.js @@ -0,0 +1,17 @@ +"use strict"; + +/** + * Webpack configuration. + */ + +exports = module.exports = { + output: { + library: "base32", + libraryTarget: "this", + sourcePrefix: "" + }, + devtool: "source-map", + node: { + Buffer: false + } +}; diff --git a/node_modules/base64-js/LICENSE b/node_modules/base64-js/LICENSE new file mode 100644 index 000000000..6d52b8acf --- /dev/null +++ b/node_modules/base64-js/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jameson Little + +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/node_modules/base64-js/README.md b/node_modules/base64-js/README.md new file mode 100644 index 000000000..b42a48f41 --- /dev/null +++ b/node_modules/base64-js/README.md @@ -0,0 +1,34 @@ +base64-js +========= + +`base64-js` does basic base64 encoding/decoding in pure JS. + +[![build status](https://secure.travis-ci.org/beatgammit/base64-js.png)](http://travis-ci.org/beatgammit/base64-js) + +Many browsers already have base64 encoding/decoding functionality, but it is for text data, not all-purpose binary data. + +Sometimes encoding/decoding binary data in the browser is useful, and that is what this module does. + +## install + +With [npm](https://npmjs.org) do: + +`npm install base64-js` and `var base64js = require('base64-js')` + +For use in web browsers do: + +`` + +[Get supported base64-js with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-base64-js?utm_source=npm-base64-js&utm_medium=referral&utm_campaign=readme) + +## methods + +`base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument. + +* `byteLength` - Takes a base64 string and returns length of byte array +* `toByteArray` - Takes a base64 string and returns a byte array +* `fromByteArray` - Takes a byte array and returns a base64 string + +## license + +MIT diff --git a/node_modules/base64-js/base64js.min.js b/node_modules/base64-js/base64js.min.js new file mode 100644 index 000000000..908ac83fd --- /dev/null +++ b/node_modules/base64-js/base64js.min.js @@ -0,0 +1 @@ +(function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,b.base64js=a()}})(function(){return function(){function b(d,e,g){function a(j,i){if(!e[j]){if(!d[j]){var f="function"==typeof require&&require;if(!i&&f)return f(j,!0);if(h)return h(j,!0);var c=new Error("Cannot find module '"+j+"'");throw c.code="MODULE_NOT_FOUND",c}var k=e[j]={exports:{}};d[j][0].call(k.exports,function(b){var c=d[j][1][b];return a(c||b)},k,k.exports,b,d,e,g)}return e[j].exports}for(var h="function"==typeof require&&require,c=0;c>16,j[k++]=255&b>>8,j[k++]=255&b;return 2===h&&(b=l[a.charCodeAt(c)]<<2|l[a.charCodeAt(c+1)]>>4,j[k++]=255&b),1===h&&(b=l[a.charCodeAt(c)]<<10|l[a.charCodeAt(c+1)]<<4|l[a.charCodeAt(c+2)]>>2,j[k++]=255&b>>8,j[k++]=255&b),j}function g(a){return k[63&a>>18]+k[63&a>>12]+k[63&a>>6]+k[63&a]}function h(a,b,c){for(var d,e=[],f=b;fj?j:g+f));return 1===d?(b=a[c-1],e.push(k[b>>2]+k[63&b<<4]+"==")):2===d&&(b=(a[c-2]<<8)+a[c-1],e.push(k[b>>10]+k[63&b>>4]+k[63&b<<2]+"=")),e.join("")}c.byteLength=function(a){var b=d(a),c=b[0],e=b[1];return 3*(c+e)/4-e},c.toByteArray=f,c.fromByteArray=j;for(var k=[],l=[],m="undefined"==typeof Uint8Array?Array:Uint8Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,p=n.length;o 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} diff --git a/node_modules/base64-js/package.json b/node_modules/base64-js/package.json new file mode 100644 index 000000000..c3972e39f --- /dev/null +++ b/node_modules/base64-js/package.json @@ -0,0 +1,47 @@ +{ + "name": "base64-js", + "description": "Base64 encoding/decoding in pure JS", + "version": "1.5.1", + "author": "T. Jameson Little ", + "typings": "index.d.ts", + "bugs": { + "url": "https://github.com/beatgammit/base64-js/issues" + }, + "devDependencies": { + "babel-minify": "^0.5.1", + "benchmark": "^2.1.4", + "browserify": "^16.3.0", + "standard": "*", + "tape": "4.x" + }, + "homepage": "https://github.com/beatgammit/base64-js", + "keywords": [ + "base64" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/beatgammit/base64-js.git" + }, + "scripts": { + "build": "browserify -s base64js -r ./ | minify > base64js.min.js", + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "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/node_modules/bignumber.js/CHANGELOG.md b/node_modules/bignumber.js/CHANGELOG.md new file mode 100644 index 000000000..b3adbb9b8 --- /dev/null +++ b/node_modules/bignumber.js/CHANGELOG.md @@ -0,0 +1,295 @@ +#### 9.1.2 +* 28/08/23 +* #354 Amend `round` to avoid bug in v8 Maglev compiler. +* [BUGFIX] #344 `minumum(0, -0)` should be `-0`. + +#### 9.1.1 +* 04/12/22 +* #338 [BUGFIX] `exponentiatedBy`: ensure `0**-n === Infinity` for very large `n`. + +#### 9.1.0 +* 08/08/22 +* #329 Remove `import` example. +* #277 Resolve lint warnings and add number `toString` note. +* Correct `decimalPlaces()` return type in *bignumber.d.ts*. +* Add ES module global `crypto` example. +* #322 Add `exports` field to *package.json*. +* #251 (#308) Amend *bignumber.d.ts* to allow instantiating a BigNumber without `new`. + +#### 9.0.2 +* 12/12/21 +* #250 [BUGFIX] Allow use of user-defined alphabet for base 10. +* #295 Remove *bignumber.min.js* and amend *README.md*. +* Update *.travis.yml* and *LICENCE.md*. + +#### 9.0.1 +* 28/09/20 +* [BUGFIX] #276 Correct `sqrt` initial estimate. +* Update *.travis.yml*, *LICENCE.md* and *README.md*. + +#### 9.0.0 +* 27/05/2019 +* For compatibility with legacy browsers, remove `Symbol` references. + +#### 8.1.1 +* 24/02/2019 +* [BUGFIX] #222 Restore missing `var` to `export BigNumber`. +* Allow any key in BigNumber.Instance in *bignumber.d.ts*. + +#### 8.1.0 +* 23/02/2019 +* [NEW FEATURE] #220 Create a BigNumber using `{s, e, c}`. +* [NEW FEATURE] `isBigNumber`: if `BigNumber.DEBUG` is `true`, also check that the BigNumber instance is well-formed. +* Remove `instanceof` checks; just use `_isBigNumber` to identify a BigNumber instance. +* Add `_isBigNumber` to prototype in *bignumber.mjs*. +* Add tests for BigNumber creation from object. +* Update *API.html*. + +#### 8.0.2 +* 13/01/2019 +* #209 `toPrecision` without argument should follow `toString`. +* Improve *Use* section of *README*. +* Optimise `toString(10)`. +* Add verson number to API doc. + +#### 8.0.1 +* 01/11/2018 +* Rest parameter must be array type in *bignumber.d.ts*. + +#### 8.0.0 +* 01/11/2018 +* [NEW FEATURE] Add `BigNumber.sum` method. +* [NEW FEATURE]`toFormat`: add `prefix` and `suffix` options. +* [NEW FEATURE] #178 Pass custom formatting to `toFormat`. +* [BREAKING CHANGE] #184 `toFraction`: return array of BigNumbers not strings. +* [NEW FEATURE] #185 Enable overwrite of `valueOf` to prevent accidental addition to string. +* #183 Add Node.js `crypto` requirement to documentation. +* [BREAKING CHANGE] #198 Disallow signs and whitespace in custom alphabet. +* [NEW FEATURE] #188 Implement `util.inspect.custom` for Node.js REPL. +* #170 Make `isBigNumber` a type guard in *bignumber.d.ts*. +* [BREAKING CHANGE] `BigNumber.min` and `BigNumber.max`: don't accept an array. +* Update *.travis.yml*. +* Remove *bower.json*. + +#### 7.2.1 +* 24/05/2018 +* Add `browser` field to *package.json*. + +#### 7.2.0 +* 22/05/2018 +* #166 Correct *.mjs* file. Remove extension from `main` field in *package.json*. + +#### 7.1.0 +* 18/05/2018 +* Add `module` field to *package.json* for *bignumber.mjs*. + +#### 7.0.2 +* 17/05/2018 +* #165 Bugfix: upper-case letters for bases 11-36 in a custom alphabet. +* Add note to *README* regarding creating BigNumbers from Number values. + +#### 7.0.1 +* 26/04/2018 +* #158 Fix global object variable name typo. + +#### 7.0.0 +* 26/04/2018 +* #143 Remove global BigNumber from typings. +* #144 Enable compatibility with `Object.freeze(Object.prototype)`. +* #148 #123 #11 Only throw on a number primitive with more than 15 significant digits if `BigNumber.DEBUG` is `true`. +* Only throw on an invalid BigNumber value if `BigNumber.DEBUG` is `true`. Return BigNumber `NaN` instead. +* #154 `exponentiatedBy`: allow BigNumber exponent. +* #156 Prevent Content Security Policy *unsafe-eval* issue. +* `toFraction`: allow `Infinity` maximum denominator. +* Comment-out some excess tests to reduce test time. +* Amend indentation and other spacing. + +#### 6.0.0 +* 26/01/2018 +* #137 Implement `APLHABET` configuration option. +* Remove `ERRORS` configuration option. +* Remove `toDigits` method; extend `precision` method accordingly. +* Remove s`round` method; extend `decimalPlaces` method accordingly. +* Remove methods: `ceil`, `floor`, and `truncated`. +* Remove method aliases: `add`, `cmp`, `isInt`, `isNeg`, `trunc`, `mul`, `neg` and `sub`. +* Rename methods: `shift` to `shiftedBy`, `another` to `clone`, `toPower` to `exponentiatedBy`, and `equals` to `isEqualTo`. +* Rename methods: add `is` prefix to `greaterThan`, `greaterThanOrEqualTo`, `lessThan` and `lessThanOrEqualTo`. +* Add methods: `multipliedBy`, `isBigNumber`, `isPositive`, `integerValue`, `maximum` and `minimum`. +* Refactor test suite. +* Add *CHANGELOG.md*. +* Rewrite *bignumber.d.ts*. +* Redo API image. + +#### 5.0.0 +* 27/11/2017 +* #81 Don't throw on constructor call without `new`. + +#### 4.1.0 +* 26/09/2017 +* Remove node 0.6 from *.travis.yml*. +* Add *bignumber.mjs*. + +#### 4.0.4 +* 03/09/2017 +* Add missing aliases to *bignumber.d.ts*. + +#### 4.0.3 +* 30/08/2017 +* Add types: *bignumber.d.ts*. + +#### 4.0.2 +* 03/05/2017 +* #120 Workaround Safari/Webkit bug. + +#### 4.0.1 +* 05/04/2017 +* #121 BigNumber.default to BigNumber['default']. + +#### 4.0.0 +* 09/01/2017 +* Replace BigNumber.isBigNumber method with isBigNumber prototype property. + +#### 3.1.2 +* 08/01/2017 +* Minor documentation edit. + +#### 3.1.1 +* 08/01/2017 +* Uncomment `isBigNumber` tests. +* Ignore dot files. + +#### 3.1.0 +* 08/01/2017 +* Add `isBigNumber` method. + +#### 3.0.2 +* 08/01/2017 +* Bugfix: Possible incorrect value of `ERRORS` after a `BigNumber.another` call (due to `parseNumeric` declaration in outer scope). + +#### 3.0.1 +* 23/11/2016 +* Apply fix for old ipads with `%` issue, see #57 and #102. +* Correct error message. + +#### 3.0.0 +* 09/11/2016 +* Remove `require('crypto')` - leave it to the user. +* Add `BigNumber.set` as `BigNumber.config` alias. +* Default `POW_PRECISION` to `0`. + +#### 2.4.0 +* 14/07/2016 +* #97 Add exports to support ES6 imports. + +#### 2.3.0 +* 07/03/2016 +* #86 Add modulus parameter to `toPower`. + +#### 2.2.0 +* 03/03/2016 +* #91 Permit larger JS integers. + +#### 2.1.4 +* 15/12/2015 +* Correct UMD. + +#### 2.1.3 +* 13/12/2015 +* Refactor re global object and crypto availability when bundling. + +#### 2.1.2 +* 10/12/2015 +* Bugfix: `window.crypto` not assigned to `crypto`. + +#### 2.1.1 +* 09/12/2015 +* Prevent code bundler from adding `crypto` shim. + +#### 2.1.0 +* 26/10/2015 +* For `valueOf` and `toJSON`, include the minus sign with negative zero. + +#### 2.0.8 +* 2/10/2015 +* Internal round function bugfix. + +#### 2.0.6 +* 31/03/2015 +* Add bower.json. Tweak division after in-depth review. + +#### 2.0.5 +* 25/03/2015 +* Amend README. Remove bitcoin address. + +#### 2.0.4 +* 25/03/2015 +* Critical bugfix #58: division. + +#### 2.0.3 +* 18/02/2015 +* Amend README. Add source map. + +#### 2.0.2 +* 18/02/2015 +* Correct links. + +#### 2.0.1 +* 18/02/2015 +* Add `max`, `min`, `precision`, `random`, `shiftedBy`, `toDigits` and `truncated` methods. +* Add the short-forms: `add`, `mul`, `sd`, `sub` and `trunc`. +* Add an `another` method to enable multiple independent constructors to be created. +* Add support for the base 2, 8 and 16 prefixes `0b`, `0o` and `0x`. +* Enable a rounding mode to be specified as a second parameter to `toExponential`, `toFixed`, `toFormat` and `toPrecision`. +* Add a `CRYPTO` configuration property so cryptographically-secure pseudo-random number generation can be specified. +* Add a `MODULO_MODE` configuration property to enable the rounding mode used by the `modulo` operation to be specified. +* Add a `POW_PRECISION` configuration property to enable the number of significant digits calculated by the power operation to be limited. +* Improve code quality. +* Improve documentation. + +#### 2.0.0 +* 29/12/2014 +* Add `dividedToIntegerBy`, `isInteger` and `toFormat` methods. +* Remove the following short-forms: `isF`, `isZ`, `toE`, `toF`, `toFr`, `toN`, `toP`, `toS`. +* Store a BigNumber's coefficient in base 1e14, rather than base 10. +* Add fast path for integers to BigNumber constructor. +* Incorporate the library into the online documentation. + +#### 1.5.0 +* 13/11/2014 +* Add `toJSON` and `decimalPlaces` methods. + +#### 1.4.1 +* 08/06/2014 +* Amend README. + +#### 1.4.0 +* 08/05/2014 +* Add `toNumber`. + +#### 1.3.0 +* 08/11/2013 +* Ensure correct rounding of `sqrt` in all, rather than almost all, cases. +* Maximum radix to 64. + +#### 1.2.1 +* 17/10/2013 +* Sign of zero when x < 0 and x + (-x) = 0. + +#### 1.2.0 +* 19/9/2013 +* Throw Error objects for stack. + +#### 1.1.1 +* 22/8/2013 +* Show original value in constructor error message. + +#### 1.1.0 +* 1/8/2013 +* Allow numbers with trailing radix point. + +#### 1.0.1 +* Bugfix: error messages with incorrect method name + +#### 1.0.0 +* 8/11/2012 +* Initial release diff --git a/node_modules/bignumber.js/LICENCE.md b/node_modules/bignumber.js/LICENCE.md new file mode 100644 index 000000000..fbe16cc9e --- /dev/null +++ b/node_modules/bignumber.js/LICENCE.md @@ -0,0 +1,26 @@ +The MIT License (MIT) +===================== + +Copyright © `<2023>` `Michael Mclaughlin` + +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/node_modules/bignumber.js/README.md b/node_modules/bignumber.js/README.md new file mode 100644 index 000000000..f5fb16853 --- /dev/null +++ b/node_modules/bignumber.js/README.md @@ -0,0 +1,286 @@ +![bignumber.js](https://raw.githubusercontent.com/MikeMcl/bignumber.js/gh-pages/bignumberjs.png) + +A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic. + +[![npm version](https://img.shields.io/npm/v/bignumber.js.svg)](https://www.npmjs.com/package/bignumber.js) +[![npm downloads](https://img.shields.io/npm/dw/bignumber.js)](https://www.npmjs.com/package/bignumber.js) + +
+ +## Features + +- Integers and decimals +- Simple API but full-featured +- Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal +- 8 KB minified and gzipped +- Replicates the `toExponential`, `toFixed`, `toPrecision` and `toString` methods of JavaScript's Number type +- Includes a `toFraction` and a correctly-rounded `squareRoot` method +- Supports cryptographically-secure pseudo-random number generation +- No dependencies +- Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only +- Comprehensive [documentation](http://mikemcl.github.io/bignumber.js/) and test set + +![API](https://raw.githubusercontent.com/MikeMcl/bignumber.js/gh-pages/API.png) + +If a smaller and simpler library is required see [big.js](https://github.com/MikeMcl/big.js/). +It's less than half the size but only works with decimal numbers and only has half the methods. +It also has fewer configuration options than this library, and does not allow `NaN` or `Infinity`. + +See also [decimal.js](https://github.com/MikeMcl/decimal.js/), which among other things adds support for non-integer powers, and performs all operations to a specified number of significant digits. + +## Load + +The library is the single JavaScript file *bignumber.js* or ES module *bignumber.mjs*. + +### Browser + +```html + +``` + +> ES module + +```html + +``` + +### [Node.js](http://nodejs.org) + +```bash +npm install bignumber.js +``` + +```javascript +const BigNumber = require('bignumber.js'); +``` + +> ES module + +```javascript +import BigNumber from "bignumber.js"; +import { BigNumber } from "./node_modules/bignumber.js/bignumber.mjs"; +``` + +### [Deno](https://deno.land/) + +```javascript +import BigNumber from 'https://raw.githubusercontent.com/mikemcl/bignumber.js/v9.1.2/bignumber.mjs'; +import BigNumber from 'https://unpkg.com/bignumber.js@latest/bignumber.mjs'; +``` + +## Use + +The library exports a single constructor function, [`BigNumber`](http://mikemcl.github.io/bignumber.js/#bignumber), which accepts a value of type Number, String or BigNumber, + +```javascript +let x = new BigNumber(123.4567); +let y = BigNumber('123456.7e-3'); +let z = new BigNumber(x); +x.isEqualTo(y) && y.isEqualTo(z) && x.isEqualTo(z); // true +``` + +To get the string value of a BigNumber use [`toString()`](http://mikemcl.github.io/bignumber.js/#toS) or [`toFixed()`](http://mikemcl.github.io/bignumber.js/#toFix). Using `toFixed()` prevents exponential notation being returned, no matter how large or small the value. + +```javascript +let x = new BigNumber('1111222233334444555566'); +x.toString(); // "1.111222233334444555566e+21" +x.toFixed(); // "1111222233334444555566" +``` + +If the limited precision of Number values is not well understood, it is recommended to create BigNumbers from String values rather than Number values to avoid a potential loss of precision. + +*In all further examples below, `let`, semicolons and `toString` calls are not shown. If a commented-out value is in quotes it means `toString` has been called on the preceding expression.* + +```javascript +// Precision loss from using numeric literals with more than 15 significant digits. +new BigNumber(1.0000000000000001) // '1' +new BigNumber(88259496234518.57) // '88259496234518.56' +new BigNumber(99999999999999999999) // '100000000000000000000' + +// Precision loss from using numeric literals outside the range of Number values. +new BigNumber(2e+308) // 'Infinity' +new BigNumber(1e-324) // '0' + +// Precision loss from the unexpected result of arithmetic with Number values. +new BigNumber(0.7 + 0.1) // '0.7999999999999999' +``` + +When creating a BigNumber from a Number, note that a BigNumber is created from a Number's decimal `toString()` value not from its underlying binary value. If the latter is required, then pass the Number's `toString(2)` value and specify base 2. + +```javascript +new BigNumber(Number.MAX_VALUE.toString(2), 2) +``` + +BigNumbers can be created from values in bases from 2 to 36. See [`ALPHABET`](http://mikemcl.github.io/bignumber.js/#alphabet) to extend this range. + +```javascript +a = new BigNumber(1011, 2) // "11" +b = new BigNumber('zz.9', 36) // "1295.25" +c = a.plus(b) // "1306.25" +``` + +*Performance is better if base 10 is NOT specified for decimal values. Only specify base 10 when you want to limit the number of decimal places of the input value to the current [`DECIMAL_PLACES`](http://mikemcl.github.io/bignumber.js/#decimal-places) setting.* + +A BigNumber is immutable in the sense that it is not changed by its methods. + +```javascript +0.3 - 0.1 // 0.19999999999999998 +x = new BigNumber(0.3) +x.minus(0.1) // "0.2" +x // "0.3" +``` + +The methods that return a BigNumber can be chained. + +```javascript +x.dividedBy(y).plus(z).times(9) +x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').integerValue() +``` + +Some of the longer method names have a shorter alias. + +```javascript +x.squareRoot().dividedBy(y).exponentiatedBy(3).isEqualTo(x.sqrt().div(y).pow(3)) // true +x.modulo(y).multipliedBy(z).eq(x.mod(y).times(z)) // true +``` + +As with JavaScript's Number type, there are [`toExponential`](http://mikemcl.github.io/bignumber.js/#toE), [`toFixed`](http://mikemcl.github.io/bignumber.js/#toFix) and [`toPrecision`](http://mikemcl.github.io/bignumber.js/#toP) methods. + +```javascript +x = new BigNumber(255.5) +x.toExponential(5) // "2.55500e+2" +x.toFixed(5) // "255.50000" +x.toPrecision(5) // "255.50" +x.toNumber() // 255.5 +``` + + A base can be specified for [`toString`](http://mikemcl.github.io/bignumber.js/#toS). + +*Performance is better if base 10 is NOT specified, i.e. use `toString()` not `toString(10)`. Only specify base 10 when you want to limit the number of decimal places of the string to the current [`DECIMAL_PLACES`](http://mikemcl.github.io/bignumber.js/#decimal-places) setting.* + + ```javascript + x.toString(16) // "ff.8" + ``` + +There is a [`toFormat`](http://mikemcl.github.io/bignumber.js/#toFor) method which may be useful for internationalisation. + +```javascript +y = new BigNumber('1234567.898765') +y.toFormat(2) // "1,234,567.90" +``` + +The maximum number of decimal places of the result of an operation involving division (i.e. a division, square root, base conversion or negative power operation) is set using the `set` or `config` method of the `BigNumber` constructor. + +The other arithmetic operations always give the exact result. + +```javascript +BigNumber.set({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 }) + +x = new BigNumber(2) +y = new BigNumber(3) +z = x.dividedBy(y) // "0.6666666667" +z.squareRoot() // "0.8164965809" +z.exponentiatedBy(-3) // "3.3749999995" +z.toString(2) // "0.1010101011" +z.multipliedBy(z) // "0.44444444448888888889" +z.multipliedBy(z).decimalPlaces(10) // "0.4444444445" +``` + +There is a [`toFraction`](http://mikemcl.github.io/bignumber.js/#toFr) method with an optional *maximum denominator* argument + +```javascript +y = new BigNumber(355) +pi = y.dividedBy(113) // "3.1415929204" +pi.toFraction() // [ "7853982301", "2500000000" ] +pi.toFraction(1000) // [ "355", "113" ] +``` + +and [`isNaN`](http://mikemcl.github.io/bignumber.js/#isNaN) and [`isFinite`](http://mikemcl.github.io/bignumber.js/#isF) methods, as `NaN` and `Infinity` are valid `BigNumber` values. + +```javascript +x = new BigNumber(NaN) // "NaN" +y = new BigNumber(Infinity) // "Infinity" +x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true +``` + +The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign. + +```javascript +x = new BigNumber(-123.456); +x.c // [ 123, 45600000000000 ] coefficient (i.e. significand) +x.e // 2 exponent +x.s // -1 sign +``` + +For advanced usage, multiple BigNumber constructors can be created, each with its own independent configuration. + +```javascript +// Set DECIMAL_PLACES for the original BigNumber constructor +BigNumber.set({ DECIMAL_PLACES: 10 }) + +// Create another BigNumber constructor, optionally passing in a configuration object +BN = BigNumber.clone({ DECIMAL_PLACES: 5 }) + +x = new BigNumber(1) +y = new BN(1) + +x.div(3) // '0.3333333333' +y.div(3) // '0.33333' +``` + +To avoid having to call `toString` or `valueOf` on a BigNumber to get its value in the Node.js REPL or when using `console.log` use + +```javascript +BigNumber.prototype[require('util').inspect.custom] = BigNumber.prototype.valueOf; +``` + +For further information see the [API](http://mikemcl.github.io/bignumber.js/) reference in the *doc* directory. + +## Test + +The *test/modules* directory contains the test scripts for each method. + +The tests can be run with Node.js or a browser. For Node.js use + +```bash +npm test +``` + +or + +```bash +node test/test +``` + +To test a single method, use, for example + +```bash +node test/methods/toFraction +``` + +For the browser, open *test/test.html*. + +## Minify + +To minify using, for example, [terser](https://github.com/terser/terser) + +```bash +npm install -g terser +``` + +```bash +terser big.js -c -m -o big.min.js +``` + +## Licence + +The MIT Licence. + +See [LICENCE](https://github.com/MikeMcl/bignumber.js/blob/master/LICENCE). diff --git a/node_modules/bignumber.js/bignumber.d.ts b/node_modules/bignumber.js/bignumber.d.ts new file mode 100644 index 000000000..f75f8bfa5 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.d.ts @@ -0,0 +1,1831 @@ +// Type definitions for bignumber.js >=8.1.0 +// Project: https://github.com/MikeMcl/bignumber.js +// Definitions by: Michael Mclaughlin +// Definitions: https://github.com/MikeMcl/bignumber.js + +// Documentation: http://mikemcl.github.io/bignumber.js/ +// +// Exports: +// +// class BigNumber (default export) +// type BigNumber.Constructor +// type BigNumber.ModuloMode +// type BigNumber.RoundingMode +// type BigNumber.Value +// interface BigNumber.Config +// interface BigNumber.Format +// interface BigNumber.Instance +// +// Example: +// +// import {BigNumber} from "bignumber.js" +// //import BigNumber from "bignumber.js" +// +// let rm: BigNumber.RoundingMode = BigNumber.ROUND_UP; +// let f: BigNumber.Format = { decimalSeparator: ',' }; +// let c: BigNumber.Config = { DECIMAL_PLACES: 4, ROUNDING_MODE: rm, FORMAT: f }; +// BigNumber.config(c); +// +// let v: BigNumber.Value = '12345.6789'; +// let b: BigNumber = new BigNumber(v); +// +// The use of compiler option `--strictNullChecks` is recommended. + +export default BigNumber; + +export namespace BigNumber { + + /** See `BigNumber.config` (alias `BigNumber.set`) and `BigNumber.clone`. */ + interface Config { + + /** + * An integer, 0 to 1e+9. Default value: 20. + * + * The maximum number of decimal places of the result of operations involving division, i.e. + * division, square root and base conversion operations, and exponentiation when the exponent is + * negative. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * BigNumber.set({ DECIMAL_PLACES: 5 }) + * ``` + */ + DECIMAL_PLACES?: number; + + /** + * An integer, 0 to 8. Default value: `BigNumber.ROUND_HALF_UP` (4). + * + * The rounding mode used in operations that involve division (see `DECIMAL_PLACES`) and the + * default rounding mode of the `decimalPlaces`, `precision`, `toExponential`, `toFixed`, + * `toFormat` and `toPrecision` methods. + * + * The modes are available as enumerated properties of the BigNumber constructor. + * + * ```ts + * BigNumber.config({ ROUNDING_MODE: 0 }) + * BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP }) + * ``` + */ + ROUNDING_MODE?: BigNumber.RoundingMode; + + /** + * An integer, 0 to 1e+9, or an array, [-1e+9 to 0, 0 to 1e+9]. + * Default value: `[-7, 20]`. + * + * The exponent value(s) at which `toString` returns exponential notation. + * + * If a single number is assigned, the value is the exponent magnitude. + * + * If an array of two numbers is assigned then the first number is the negative exponent value at + * and beneath which exponential notation is used, and the second number is the positive exponent + * value at and above which exponential notation is used. + * + * For example, to emulate JavaScript numbers in terms of the exponent values at which they begin + * to use exponential notation, use `[-7, 20]`. + * + * ```ts + * BigNumber.config({ EXPONENTIAL_AT: 2 }) + * new BigNumber(12.3) // '12.3' e is only 1 + * new BigNumber(123) // '1.23e+2' + * new BigNumber(0.123) // '0.123' e is only -1 + * new BigNumber(0.0123) // '1.23e-2' + * + * BigNumber.config({ EXPONENTIAL_AT: [-7, 20] }) + * new BigNumber(123456789) // '123456789' e is only 8 + * new BigNumber(0.000000123) // '1.23e-7' + * + * // Almost never return exponential notation: + * BigNumber.config({ EXPONENTIAL_AT: 1e+9 }) + * + * // Always return exponential notation: + * BigNumber.config({ EXPONENTIAL_AT: 0 }) + * ``` + * + * Regardless of the value of `EXPONENTIAL_AT`, the `toFixed` method will always return a value in + * normal notation and the `toExponential` method will always return a value in exponential form. + * Calling `toString` with a base argument, e.g. `toString(10)`, will also always return normal + * notation. + */ + EXPONENTIAL_AT?: number | [number, number]; + + /** + * An integer, magnitude 1 to 1e+9, or an array, [-1e+9 to -1, 1 to 1e+9]. + * Default value: `[-1e+9, 1e+9]`. + * + * The exponent value(s) beyond which overflow to Infinity and underflow to zero occurs. + * + * If a single number is assigned, it is the maximum exponent magnitude: values wth a positive + * exponent of greater magnitude become Infinity and those with a negative exponent of greater + * magnitude become zero. + * + * If an array of two numbers is assigned then the first number is the negative exponent limit and + * the second number is the positive exponent limit. + * + * For example, to emulate JavaScript numbers in terms of the exponent values at which they + * become zero and Infinity, use [-324, 308]. + * + * ```ts + * BigNumber.config({ RANGE: 500 }) + * BigNumber.config().RANGE // [ -500, 500 ] + * new BigNumber('9.999e499') // '9.999e+499' + * new BigNumber('1e500') // 'Infinity' + * new BigNumber('1e-499') // '1e-499' + * new BigNumber('1e-500') // '0' + * + * BigNumber.config({ RANGE: [-3, 4] }) + * new BigNumber(99999) // '99999' e is only 4 + * new BigNumber(100000) // 'Infinity' e is 5 + * new BigNumber(0.001) // '0.01' e is only -3 + * new BigNumber(0.0001) // '0' e is -4 + * ``` + * The largest possible magnitude of a finite BigNumber is 9.999...e+1000000000. + * The smallest possible magnitude of a non-zero BigNumber is 1e-1000000000. + */ + RANGE?: number | [number, number]; + + /** + * A boolean: `true` or `false`. Default value: `false`. + * + * The value that determines whether cryptographically-secure pseudo-random number generation is + * used. If `CRYPTO` is set to true then the random method will generate random digits using + * `crypto.getRandomValues` in browsers that support it, or `crypto.randomBytes` if using a + * version of Node.js that supports it. + * + * If neither function is supported by the host environment then attempting to set `CRYPTO` to + * `true` will fail and an exception will be thrown. + * + * If `CRYPTO` is `false` then the source of randomness used will be `Math.random` (which is + * assumed to generate at least 30 bits of randomness). + * + * See `BigNumber.random`. + * + * ```ts + * // Node.js + * global.crypto = require('crypto') + * + * BigNumber.config({ CRYPTO: true }) + * BigNumber.config().CRYPTO // true + * BigNumber.random() // 0.54340758610486147524 + * ``` + */ + CRYPTO?: boolean; + + /** + * An integer, 0, 1, 3, 6 or 9. Default value: `BigNumber.ROUND_DOWN` (1). + * + * The modulo mode used when calculating the modulus: `a mod n`. + * The quotient, `q = a / n`, is calculated according to the `ROUNDING_MODE` that corresponds to + * the chosen `MODULO_MODE`. + * The remainder, `r`, is calculated as: `r = a - n * q`. + * + * The modes that are most commonly used for the modulus/remainder operation are shown in the + * following table. Although the other rounding modes can be used, they may not give useful + * results. + * + * Property | Value | Description + * :------------------|:------|:------------------------------------------------------------------ + * `ROUND_UP` | 0 | The remainder is positive if the dividend is negative. + * `ROUND_DOWN` | 1 | The remainder has the same sign as the dividend. + * | | Uses 'truncating division' and matches JavaScript's `%` operator . + * `ROUND_FLOOR` | 3 | The remainder has the same sign as the divisor. + * | | This matches Python's `%` operator. + * `ROUND_HALF_EVEN` | 6 | The IEEE 754 remainder function. + * `EUCLID` | 9 | The remainder is always positive. + * | | Euclidian division: `q = sign(n) * floor(a / abs(n))` + * + * The rounding/modulo modes are available as enumerated properties of the BigNumber constructor. + * + * See `modulo`. + * + * ```ts + * BigNumber.config({ MODULO_MODE: BigNumber.EUCLID }) + * BigNumber.set({ MODULO_MODE: 9 }) // equivalent + * ``` + */ + MODULO_MODE?: BigNumber.ModuloMode; + + /** + * An integer, 0 to 1e+9. Default value: 0. + * + * The maximum precision, i.e. number of significant digits, of the result of the power operation + * - unless a modulus is specified. + * + * If set to 0, the number of significant digits will not be limited. + * + * See `exponentiatedBy`. + * + * ```ts + * BigNumber.config({ POW_PRECISION: 100 }) + * ``` + */ + POW_PRECISION?: number; + + /** + * An object including any number of the properties shown below. + * + * The object configures the format of the string returned by the `toFormat` method. + * The example below shows the properties of the object that are recognised, and + * their default values. + * + * Unlike the other configuration properties, the values of the properties of the `FORMAT` object + * will not be checked for validity - the existing object will simply be replaced by the object + * that is passed in. + * + * See `toFormat`. + * + * ```ts + * BigNumber.config({ + * FORMAT: { + * // string to prepend + * prefix: '', + * // the decimal separator + * decimalSeparator: '.', + * // the grouping separator of the integer part + * groupSeparator: ',', + * // the primary grouping size of the integer part + * groupSize: 3, + * // the secondary grouping size of the integer part + * secondaryGroupSize: 0, + * // the grouping separator of the fraction part + * fractionGroupSeparator: ' ', + * // the grouping size of the fraction part + * fractionGroupSize: 0, + * // string to append + * suffix: '' + * } + * }) + * ``` + */ + FORMAT?: BigNumber.Format; + + /** + * The alphabet used for base conversion. The length of the alphabet corresponds to the maximum + * value of the base argument that can be passed to the BigNumber constructor or `toString`. + * + * Default value: `'0123456789abcdefghijklmnopqrstuvwxyz'`. + * + * There is no maximum length for the alphabet, but it must be at least 2 characters long, + * and it must not contain whitespace or a repeated character, or the sign indicators '+' and + * '-', or the decimal separator '.'. + * + * ```ts + * // duodecimal (base 12) + * BigNumber.config({ ALPHABET: '0123456789TE' }) + * x = new BigNumber('T', 12) + * x.toString() // '10' + * x.toString(12) // 'T' + * ``` + */ + ALPHABET?: string; + } + + /** See `FORMAT` and `toFormat`. */ + interface Format { + + /** The string to prepend. */ + prefix?: string; + + /** The decimal separator. */ + decimalSeparator?: string; + + /** The grouping separator of the integer part. */ + groupSeparator?: string; + + /** The primary grouping size of the integer part. */ + groupSize?: number; + + /** The secondary grouping size of the integer part. */ + secondaryGroupSize?: number; + + /** The grouping separator of the fraction part. */ + fractionGroupSeparator?: string; + + /** The grouping size of the fraction part. */ + fractionGroupSize?: number; + + /** The string to append. */ + suffix?: string; + } + + interface Instance { + + /** The coefficient of the value of this BigNumber, an array of base 1e14 integer numbers, or null. */ + readonly c: number[] | null; + + /** The exponent of the value of this BigNumber, an integer number, -1000000000 to 1000000000, or null. */ + readonly e: number | null; + + /** The sign of the value of this BigNumber, -1, 1, or null. */ + readonly s: number | null; + + [key: string]: any; + } + + type Constructor = typeof BigNumber; + type ModuloMode = 0 | 1 | 3 | 6 | 9; + type RoundingMode = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; + type Value = string | number | Instance; +} + +export declare class BigNumber implements BigNumber.Instance { + + /** Used internally to identify a BigNumber instance. */ + private readonly _isBigNumber: true; + + /** The coefficient of the value of this BigNumber, an array of base 1e14 integer numbers, or null. */ + readonly c: number[] | null; + + /** The exponent of the value of this BigNumber, an integer number, -1000000000 to 1000000000, or null. */ + readonly e: number | null; + + /** The sign of the value of this BigNumber, -1, 1, or null. */ + readonly s: number | null; + + /** + * Returns a new instance of a BigNumber object with value `n`, where `n` is a numeric value in + * the specified `base`, or base 10 if `base` is omitted or is `null` or `undefined`. + * + * ```ts + * x = new BigNumber(123.4567) // '123.4567' + * // 'new' is optional + * y = BigNumber(x) // '123.4567' + * ``` + * + * If `n` is a base 10 value it can be in normal (fixed-point) or exponential notation. + * Values in other bases must be in normal notation. Values in any base can have fraction digits, + * i.e. digits after the decimal point. + * + * ```ts + * new BigNumber(43210) // '43210' + * new BigNumber('4.321e+4') // '43210' + * new BigNumber('-735.0918e-430') // '-7.350918e-428' + * new BigNumber('123412421.234324', 5) // '607236.557696' + * ``` + * + * Signed `0`, signed `Infinity` and `NaN` are supported. + * + * ```ts + * new BigNumber('-Infinity') // '-Infinity' + * new BigNumber(NaN) // 'NaN' + * new BigNumber(-0) // '0' + * new BigNumber('.5') // '0.5' + * new BigNumber('+2') // '2' + * ``` + * + * String values in hexadecimal literal form, e.g. `'0xff'`, are valid, as are string values with + * the octal and binary prefixs `'0o'` and `'0b'`. String values in octal literal form without the + * prefix will be interpreted as decimals, e.g. `'011'` is interpreted as 11, not 9. + * + * ```ts + * new BigNumber(-10110100.1, 2) // '-180.5' + * new BigNumber('-0b10110100.1') // '-180.5' + * new BigNumber('ff.8', 16) // '255.5' + * new BigNumber('0xff.8') // '255.5' + * ``` + * + * If a base is specified, `n` is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. This includes base 10, so don't include a `base` parameter for decimal + * values unless this behaviour is desired. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * new BigNumber(1.23456789) // '1.23456789' + * new BigNumber(1.23456789, 10) // '1.23457' + * ``` + * + * An error is thrown if `base` is invalid. + * + * There is no limit to the number of digits of a value of type string (other than that of + * JavaScript's maximum array size). See `RANGE` to set the maximum and minimum possible exponent + * value of a BigNumber. + * + * ```ts + * new BigNumber('5032485723458348569331745.33434346346912144534543') + * new BigNumber('4.321e10000000') + * ``` + * + * BigNumber `NaN` is returned if `n` is invalid (unless `BigNumber.DEBUG` is `true`, see below). + * + * ```ts + * new BigNumber('.1*') // 'NaN' + * new BigNumber('blurgh') // 'NaN' + * new BigNumber(9, 2) // 'NaN' + * ``` + * + * To aid in debugging, if `BigNumber.DEBUG` is `true` then an error will be thrown on an + * invalid `n`. An error will also be thrown if `n` is of type number with more than 15 + * significant digits, as calling `toString` or `valueOf` on these numbers may not result in the + * intended value. + * + * ```ts + * console.log(823456789123456.3) // 823456789123456.2 + * new BigNumber(823456789123456.3) // '823456789123456.2' + * BigNumber.DEBUG = true + * // 'Error: Number has more than 15 significant digits' + * new BigNumber(823456789123456.3) + * // 'Error: Not a base 2 number' + * new BigNumber(9, 2) + * ``` + * + * A BigNumber can also be created from an object literal. + * Use `isBigNumber` to check that it is well-formed. + * + * ```ts + * new BigNumber({ s: 1, e: 2, c: [ 777, 12300000000000 ], _isBigNumber: true }) // '777.123' + * ``` + * + * @param n A numeric value. + * @param base The base of `n`, integer, 2 to 36 (or `ALPHABET.length`, see `ALPHABET`). + */ + constructor(n: BigNumber.Value, base?: number); + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this + * BigNumber. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber(-0.8) + * x.absoluteValue() // '0.8' + * ``` + */ + absoluteValue(): BigNumber; + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this + * BigNumber. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber(-0.8) + * x.abs() // '0.8' + * ``` + */ + abs(): BigNumber; + + /** + * Returns | | + * :-------:|:--------------------------------------------------------------| + * 1 | If the value of this BigNumber is greater than the value of `n` + * -1 | If the value of this BigNumber is less than the value of `n` + * 0 | If this BigNumber and `n` have the same value + * `null` | If the value of either this BigNumber or `n` is `NaN` + * + * ```ts + * + * x = new BigNumber(Infinity) + * y = new BigNumber(5) + * x.comparedTo(y) // 1 + * x.comparedTo(x.minus(1)) // 0 + * y.comparedTo(NaN) // null + * y.comparedTo('110', 2) // -1 + * ``` + * @param n A numeric value. + * @param [base] The base of n. + */ + comparedTo(n: BigNumber.Value, base?: number): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode + * `roundingMode` to a maximum of `decimalPlaces` decimal places. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the return value is the number of + * decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is + * ±`Infinity` or `NaN`. + * + * If `roundingMode` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(1234.56) + * x.decimalPlaces() // 2 + * x.decimalPlaces(1) // '1234.6' + * x.decimalPlaces(2) // '1234.56' + * x.decimalPlaces(10) // '1234.56' + * x.decimalPlaces(0, 1) // '1234' + * x.decimalPlaces(0, 6) // '1235' + * x.decimalPlaces(1, 1) // '1234.5' + * x.decimalPlaces(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' + * x // '1234.56' + * y = new BigNumber('9.9e-101') + * y.decimalPlaces() // 102 + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + decimalPlaces(): number | null; + decimalPlaces(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode + * `roundingMode` to a maximum of `decimalPlaces` decimal places. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the return value is the number of + * decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is + * ±`Infinity` or `NaN`. + * + * If `roundingMode` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(1234.56) + * x.dp() // 2 + * x.dp(1) // '1234.6' + * x.dp(2) // '1234.56' + * x.dp(10) // '1234.56' + * x.dp(0, 1) // '1234' + * x.dp(0, 6) // '1235' + * x.dp(1, 1) // '1234.5' + * x.dp(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' + * x // '1234.56' + * y = new BigNumber('9.9e-101') + * y.dp() // 102 + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + dp(): number | null; + dp(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by `n`, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * ```ts + * x = new BigNumber(355) + * y = new BigNumber(113) + * x.dividedBy(y) // '3.14159292035398230088' + * x.dividedBy(5) // '71' + * x.dividedBy(47, 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + dividedBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by `n`, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * ```ts + * x = new BigNumber(355) + * y = new BigNumber(113) + * x.div(y) // '3.14159292035398230088' + * x.div(5) // '71' + * x.div(47, 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + div(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + * `n`. + * + * ```ts + * x = new BigNumber(5) + * y = new BigNumber(3) + * x.dividedToIntegerBy(y) // '1' + * x.dividedToIntegerBy(0.7) // '7' + * x.dividedToIntegerBy('0.f', 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + dividedToIntegerBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + * `n`. + * + * ```ts + * x = new BigNumber(5) + * y = new BigNumber(3) + * x.idiv(y) // '1' + * x.idiv(0.7) // '7' + * x.idiv('0.f', 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + idiv(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber exponentiated by `n`, i.e. + * raised to the power `n`, and optionally modulo a modulus `m`. + * + * If `n` is negative the result is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. + * + * As the number of digits of the result of the power operation can grow so large so quickly, + * e.g. 123.456**10000 has over 50000 digits, the number of significant digits calculated is + * limited to the value of the `POW_PRECISION` setting (unless a modulus `m` is specified). + * + * By default `POW_PRECISION` is set to 0. This means that an unlimited number of significant + * digits will be calculated, and that the method's performance will decrease dramatically for + * larger exponents. + * + * If `m` is specified and the value of `m`, `n` and this BigNumber are integers and `n` is + * positive, then a fast modular exponentiation algorithm is used, otherwise the operation will + * be performed as `x.exponentiatedBy(n).modulo(m)` with a `POW_PRECISION` of 0. + * + * Throws if `n` is not an integer. + * + * ```ts + * Math.pow(0.7, 2) // 0.48999999999999994 + * x = new BigNumber(0.7) + * x.exponentiatedBy(2) // '0.49' + * BigNumber(3).exponentiatedBy(-2) // '0.11111111111111111111' + * ``` + * + * @param n The exponent, an integer. + * @param [m] The modulus. + */ + exponentiatedBy(n: BigNumber.Value, m?: BigNumber.Value): BigNumber; + exponentiatedBy(n: number, m?: BigNumber.Value): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber exponentiated by `n`, i.e. + * raised to the power `n`, and optionally modulo a modulus `m`. + * + * If `n` is negative the result is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. + * + * As the number of digits of the result of the power operation can grow so large so quickly, + * e.g. 123.456**10000 has over 50000 digits, the number of significant digits calculated is + * limited to the value of the `POW_PRECISION` setting (unless a modulus `m` is specified). + * + * By default `POW_PRECISION` is set to 0. This means that an unlimited number of significant + * digits will be calculated, and that the method's performance will decrease dramatically for + * larger exponents. + * + * If `m` is specified and the value of `m`, `n` and this BigNumber are integers and `n` is + * positive, then a fast modular exponentiation algorithm is used, otherwise the operation will + * be performed as `x.pow(n).modulo(m)` with a `POW_PRECISION` of 0. + * + * Throws if `n` is not an integer. + * + * ```ts + * Math.pow(0.7, 2) // 0.48999999999999994 + * x = new BigNumber(0.7) + * x.pow(2) // '0.49' + * BigNumber(3).pow(-2) // '0.11111111111111111111' + * ``` + * + * @param n The exponent, an integer. + * @param [m] The modulus. + */ + pow(n: BigNumber.Value, m?: BigNumber.Value): BigNumber; + pow(n: number, m?: BigNumber.Value): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to an integer using + * rounding mode `rm`. + * + * If `rm` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `rm` is invalid. + * + * ```ts + * x = new BigNumber(123.456) + * x.integerValue() // '123' + * x.integerValue(BigNumber.ROUND_CEIL) // '124' + * y = new BigNumber(-12.7) + * y.integerValue() // '-13' + * x.integerValue(BigNumber.ROUND_DOWN) // '-12' + * ``` + * + * @param {BigNumber.RoundingMode} [rm] The roundng mode, an integer, 0 to 8. + */ + integerValue(rm?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns `true` if the value of this BigNumber is equal to the value of `n`, otherwise returns + * `false`. + * + * As with JavaScript, `NaN` does not equal `NaN`. + * + * ```ts + * 0 === 1e-324 // true + * x = new BigNumber(0) + * x.isEqualTo('1e-324') // false + * BigNumber(-0).isEqualTo(x) // true ( -0 === 0 ) + * BigNumber(255).isEqualTo('ff', 16) // true + * + * y = new BigNumber(NaN) + * y.isEqualTo(NaN) // false + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is equal to the value of `n`, otherwise returns + * `false`. + * + * As with JavaScript, `NaN` does not equal `NaN`. + * + * ```ts + * 0 === 1e-324 // true + * x = new BigNumber(0) + * x.eq('1e-324') // false + * BigNumber(-0).eq(x) // true ( -0 === 0 ) + * BigNumber(255).eq('ff', 16) // true + * + * y = new BigNumber(NaN) + * y.eq(NaN) // false + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + eq(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is a finite number, otherwise returns `false`. + * + * The only possible non-finite values of a BigNumber are `NaN`, `Infinity` and `-Infinity`. + * + * ```ts + * x = new BigNumber(1) + * x.isFinite() // true + * y = new BigNumber(Infinity) + * y.isFinite() // false + * ``` + */ + isFinite(): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise + * returns `false`. + * + * ```ts + * 0.1 > (0.3 - 0.2) // true + * x = new BigNumber(0.1) + * x.isGreaterThan(BigNumber(0.3).minus(0.2)) // false + * BigNumber(0).isGreaterThan(x) // false + * BigNumber(11, 3).isGreaterThan(11.1, 2) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isGreaterThan(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise + * returns `false`. + * + * ```ts + * 0.1 > (0.3 - 0 // true + * x = new BigNumber(0.1) + * x.gt(BigNumber(0.3).minus(0.2)) // false + * BigNumber(0).gt(x) // false + * BigNumber(11, 3).gt(11.1, 2) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + gt(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * (0.3 - 0.2) >= 0.1 // false + * x = new BigNumber(0.3).minus(0.2) + * x.isGreaterThanOrEqualTo(0.1) // true + * BigNumber(1).isGreaterThanOrEqualTo(x) // true + * BigNumber(10, 18).isGreaterThanOrEqualTo('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isGreaterThanOrEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * (0.3 - 0.2) >= 0.1 // false + * x = new BigNumber(0.3).minus(0.2) + * x.gte(0.1) // true + * BigNumber(1).gte(x) // true + * BigNumber(10, 18).gte('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + gte(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is an integer, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(1) + * x.isInteger() // true + * y = new BigNumber(123.456) + * y.isInteger() // false + * ``` + */ + isInteger(): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than the value of `n`, otherwise returns + * `false`. + * + * ```ts + * (0.3 - 0.2) < 0.1 // true + * x = new BigNumber(0.3).minus(0.2) + * x.isLessThan(0.1) // false + * BigNumber(0).isLessThan(x) // true + * BigNumber(11.1, 2).isLessThan(11, 3) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isLessThan(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than the value of `n`, otherwise returns + * `false`. + * + * ```ts + * (0.3 - 0.2) < 0.1 // true + * x = new BigNumber(0.3).minus(0.2) + * x.lt(0.1) // false + * BigNumber(0).lt(x) // true + * BigNumber(11.1, 2).lt(11, 3) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + lt(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * 0.1 <= (0.3 - 0.2) // false + * x = new BigNumber(0.1) + * x.isLessThanOrEqualTo(BigNumber(0.3).minus(0.2)) // true + * BigNumber(-1).isLessThanOrEqualTo(x) // true + * BigNumber(10, 18).isLessThanOrEqualTo('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isLessThanOrEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * 0.1 <= (0.3 - 0.2) // false + * x = new BigNumber(0.1) + * x.lte(BigNumber(0.3).minus(0.2)) // true + * BigNumber(-1).lte(x) // true + * BigNumber(10, 18).lte('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + lte(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is `NaN`, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(NaN) + * x.isNaN() // true + * y = new BigNumber('Infinity') + * y.isNaN() // false + * ``` + */ + isNaN(): boolean; + + /** + * Returns `true` if the value of this BigNumber is negative, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isNegative() // true + * y = new BigNumber(2) + * y.isNegative() // false + * ``` + */ + isNegative(): boolean; + + /** + * Returns `true` if the value of this BigNumber is positive, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isPositive() // false + * y = new BigNumber(2) + * y.isPositive() // true + * ``` + */ + isPositive(): boolean; + + /** + * Returns `true` if the value of this BigNumber is zero or minus zero, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isZero() // true + * ``` + */ + isZero(): boolean; + + /** + * Returns a BigNumber whose value is the value of this BigNumber minus `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.3 - 0.1 // 0.19999999999999998 + * x = new BigNumber(0.3) + * x.minus(0.1) // '0.2' + * x.minus(0.6, 20) // '0' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + minus(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo `n`, i.e. the integer + * remainder of dividing this BigNumber by `n`. + * + * The value returned, and in particular its sign, is dependent on the value of the `MODULO_MODE` + * setting of this BigNumber constructor. If it is 1 (default value), the result will have the + * same sign as this BigNumber, and it will match that of Javascript's `%` operator (within the + * limits of double precision) and BigDecimal's `remainder` method. + * + * The return value is always exact and unrounded. + * + * See `MODULO_MODE` for a description of the other modulo modes. + * + * ```ts + * 1 % 0.9 // 0.09999999999999998 + * x = new BigNumber(1) + * x.modulo(0.9) // '0.1' + * y = new BigNumber(33) + * y.modulo('a', 33) // '3' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + modulo(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo `n`, i.e. the integer + * remainder of dividing this BigNumber by `n`. + * + * The value returned, and in particular its sign, is dependent on the value of the `MODULO_MODE` + * setting of this BigNumber constructor. If it is 1 (default value), the result will have the + * same sign as this BigNumber, and it will match that of Javascript's `%` operator (within the + * limits of double precision) and BigDecimal's `remainder` method. + * + * The return value is always exact and unrounded. + * + * See `MODULO_MODE` for a description of the other modulo modes. + * + * ```ts + * 1 % 0.9 // 0.09999999999999998 + * x = new BigNumber(1) + * x.mod(0.9) // '0.1' + * y = new BigNumber(33) + * y.mod('a', 33) // '3' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + mod(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber multiplied by `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.6 * 3 // 1.7999999999999998 + * x = new BigNumber(0.6) + * y = x.multipliedBy(3) // '1.8' + * BigNumber('7e+500').multipliedBy(y) // '1.26e+501' + * x.multipliedBy('-a', 16) // '-6' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + multipliedBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber multiplied by `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.6 * 3 // 1.7999999999999998 + * x = new BigNumber(0.6) + * y = x.times(3) // '1.8' + * BigNumber('7e+500').times(y) // '1.26e+501' + * x.times('-a', 16) // '-6' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + times(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by -1. + * + * ```ts + * x = new BigNumber(1.8) + * x.negated() // '-1.8' + * y = new BigNumber(-1.3) + * y.negated() // '1.3' + * ``` + */ + negated(): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber plus `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.1 + 0.2 // 0.30000000000000004 + * x = new BigNumber(0.1) + * y = x.plus(0.2) // '0.3' + * BigNumber(0.7).plus(x).plus(y) // '1.1' + * x.plus('0.1', 8) // '0.225' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + plus(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns the number of significant digits of the value of this BigNumber, or `null` if the value + * of this BigNumber is ±`Infinity` or `NaN`. + * + * If `includeZeros` is true then any trailing zeros of the integer part of the value of this + * BigNumber are counted as significant digits, otherwise they are not. + * + * Throws if `includeZeros` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.precision() // 9 + * y = new BigNumber(987000) + * y.precision(false) // 3 + * y.precision(true) // 6 + * ``` + * + * @param [includeZeros] Whether to include integer trailing zeros in the significant digit count. + */ + precision(includeZeros?: boolean): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a precision of + * `significantDigits` significant digits using rounding mode `roundingMode`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` will be used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.precision(6) // '9876.54' + * x.precision(6, BigNumber.ROUND_UP) // '9876.55' + * x.precision(2) // '9900' + * x.precision(2, 1) // '9800' + * x // '9876.54321' + * ``` + * + * @param significantDigits Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + precision(significantDigits: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns the number of significant digits of the value of this BigNumber, + * or `null` if the value of this BigNumber is ±`Infinity` or `NaN`. + * + * If `includeZeros` is true then any trailing zeros of the integer part of + * the value of this BigNumber are counted as significant digits, otherwise + * they are not. + * + * Throws if `includeZeros` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.sd() // 9 + * y = new BigNumber(987000) + * y.sd(false) // 3 + * y.sd(true) // 6 + * ``` + * + * @param [includeZeros] Whether to include integer trailing zeros in the significant digit count. + */ + sd(includeZeros?: boolean): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a precision of + * `significantDigits` significant digits using rounding mode `roundingMode`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` will be used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.sd(6) // '9876.54' + * x.sd(6, BigNumber.ROUND_UP) // '9876.55' + * x.sd(2) // '9900' + * x.sd(2, 1) // '9800' + * x // '9876.54321' + * ``` + * + * @param significantDigits Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + sd(significantDigits: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber shifted by `n` places. + * + * The shift is of the decimal point, i.e. of powers of ten, and is to the left if `n` is negative + * or to the right if `n` is positive. + * + * The return value is always exact and unrounded. + * + * Throws if `n` is invalid. + * + * ```ts + * x = new BigNumber(1.23) + * x.shiftedBy(3) // '1230' + * x.shiftedBy(-3) // '0.00123' + * ``` + * + * @param n The shift value, integer, -9007199254740991 to 9007199254740991. + */ + shiftedBy(n: number): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * The return value will be correctly rounded, i.e. rounded as if the result was first calculated + * to an infinite number of correct digits before rounding. + * + * ```ts + * x = new BigNumber(16) + * x.squareRoot() // '4' + * y = new BigNumber(3) + * y.squareRoot() // '1.73205080756887729353' + * ``` + */ + squareRoot(): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * The return value will be correctly rounded, i.e. rounded as if the result was first calculated + * to an infinite number of correct digits before rounding. + * + * ```ts + * x = new BigNumber(16) + * x.sqrt() // '4' + * y = new BigNumber(3) + * y.sqrt() // '1.73205080756887729353' + * ``` + */ + sqrt(): BigNumber; + + /** + * Returns a string representing the value of this BigNumber in exponential notation rounded using + * rounding mode `roundingMode` to `decimalPlaces` decimal places, i.e with one digit before the + * decimal point and `decimalPlaces` digits after it. + * + * If the value of this BigNumber in exponential notation has fewer than `decimalPlaces` fraction + * digits, the return value will be appended with zeros accordingly. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the number of digits after the + * decimal point defaults to the minimum number of digits necessary to represent the value + * exactly. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = 45.6 + * y = new BigNumber(x) + * x.toExponential() // '4.56e+1' + * y.toExponential() // '4.56e+1' + * x.toExponential(0) // '5e+1' + * y.toExponential(0) // '5e+1' + * x.toExponential(1) // '4.6e+1' + * y.toExponential(1) // '4.6e+1' + * y.toExponential(1, 1) // '4.5e+1' (ROUND_DOWN) + * x.toExponential(3) // '4.560e+1' + * y.toExponential(3) // '4.560e+1' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + toExponential(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toExponential(): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation + * rounded to `decimalPlaces` decimal places using rounding mode `roundingMode`. + * + * If the value of this BigNumber in normal notation has fewer than `decimalPlaces` fraction + * digits, the return value will be appended with zeros accordingly. + * + * Unlike `Number.prototype.toFixed`, which returns exponential notation if a number is greater or + * equal to 10**21, this method will always return normal notation. + * + * If `decimalPlaces` is omitted or is `null` or `undefined`, the return value will be unrounded + * and in normal notation. This is also unlike `Number.prototype.toFixed`, which returns the value + * to zero decimal places. It is useful when normal notation is required and the current + * `EXPONENTIAL_AT` setting causes `toString` to return exponential notation. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = 3.456 + * y = new BigNumber(x) + * x.toFixed() // '3' + * y.toFixed() // '3.456' + * y.toFixed(0) // '3' + * x.toFixed(2) // '3.46' + * y.toFixed(2) // '3.46' + * y.toFixed(2, 1) // '3.45' (ROUND_DOWN) + * x.toFixed(5) // '3.45600' + * y.toFixed(5) // '3.45600' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + toFixed(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toFixed(): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation + * rounded to `decimalPlaces` decimal places using rounding mode `roundingMode`, and formatted + * according to the properties of the `format` or `FORMAT` object. + * + * The formatting object may contain some or all of the properties shown in the examples below. + * + * If `decimalPlaces` is omitted or is `null` or `undefined`, then the return value is not + * rounded to a fixed number of decimal places. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * If `format` is omitted or is `null` or `undefined`, `FORMAT` is used. + * + * Throws if `decimalPlaces`, `roundingMode`, or `format` is invalid. + * + * ```ts + * fmt = { + * decimalSeparator: '.', + * groupSeparator: ',', + * groupSize: 3, + * secondaryGroupSize: 0, + * fractionGroupSeparator: ' ', + * fractionGroupSize: 0 + * } + * + * x = new BigNumber('123456789.123456789') + * + * // Set the global formatting options + * BigNumber.config({ FORMAT: fmt }) + * + * x.toFormat() // '123,456,789.123456789' + * x.toFormat(3) // '123,456,789.123' + * + * // If a reference to the object assigned to FORMAT has been retained, + * // the format properties can be changed directly + * fmt.groupSeparator = ' ' + * fmt.fractionGroupSize = 5 + * x.toFormat() // '123 456 789.12345 6789' + * + * // Alternatively, pass the formatting options as an argument + * fmt = { + * decimalSeparator: ',', + * groupSeparator: '.', + * groupSize: 3, + * secondaryGroupSize: 2 + * } + * + * x.toFormat() // '123 456 789.12345 6789' + * x.toFormat(fmt) // '12.34.56.789,123456789' + * x.toFormat(2, fmt) // '12.34.56.789,12' + * x.toFormat(3, BigNumber.ROUND_UP, fmt) // '12.34.56.789,124' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + * @param [format] Formatting options object. See `BigNumber.Format`. + */ + toFormat(decimalPlaces: number, roundingMode: BigNumber.RoundingMode, format?: BigNumber.Format): string; + toFormat(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): string; + toFormat(decimalPlaces?: number): string; + toFormat(decimalPlaces: number, format: BigNumber.Format): string; + toFormat(format: BigNumber.Format): string; + + /** + * Returns an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to `max_denominator`. + * If a maximum denominator, `max_denominator`, is not specified, or is `null` or `undefined`, the + * denominator will be the lowest value necessary to represent the number exactly. + * + * Throws if `max_denominator` is invalid. + * + * ```ts + * x = new BigNumber(1.75) + * x.toFraction() // '7, 4' + * + * pi = new BigNumber('3.14159265358') + * pi.toFraction() // '157079632679,50000000000' + * pi.toFraction(100000) // '312689, 99532' + * pi.toFraction(10000) // '355, 113' + * pi.toFraction(100) // '311, 99' + * pi.toFraction(10) // '22, 7' + * pi.toFraction(1) // '3, 1' + * ``` + * + * @param [max_denominator] The maximum denominator, integer > 0, or Infinity. + */ + toFraction(max_denominator?: BigNumber.Value): [BigNumber, BigNumber]; + + /** As `valueOf`. */ + toJSON(): string; + + /** + * Returns the value of this BigNumber as a JavaScript primitive number. + * + * Using the unary plus operator gives the same result. + * + * ```ts + * x = new BigNumber(456.789) + * x.toNumber() // 456.789 + * +x // 456.789 + * + * y = new BigNumber('45987349857634085409857349856430985') + * y.toNumber() // 4.598734985763409e+34 + * + * z = new BigNumber(-0) + * 1 / z.toNumber() // -Infinity + * 1 / +z // -Infinity + * ``` + */ + toNumber(): number; + + /** + * Returns a string representing the value of this BigNumber rounded to `significantDigits` + * significant digits using rounding mode `roundingMode`. + * + * If `significantDigits` is less than the number of digits necessary to represent the integer + * part of the value in normal (fixed-point) notation, then exponential notation is used. + * + * If `significantDigits` is omitted, or is `null` or `undefined`, then the return value is the + * same as `n.toString()`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = 45.6 + * y = new BigNumber(x) + * x.toPrecision() // '45.6' + * y.toPrecision() // '45.6' + * x.toPrecision(1) // '5e+1' + * y.toPrecision(1) // '5e+1' + * y.toPrecision(2, 0) // '4.6e+1' (ROUND_UP) + * y.toPrecision(2, 1) // '4.5e+1' (ROUND_DOWN) + * x.toPrecision(5) // '45.600' + * y.toPrecision(5) // '45.600' + * ``` + * + * @param [significantDigits] Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer 0 to 8. + */ + toPrecision(significantDigits: number, roundingMode?: BigNumber.RoundingMode): string; + toPrecision(): string; + + /** + * Returns a string representing the value of this BigNumber in base `base`, or base 10 if `base` + * is omitted or is `null` or `undefined`. + * + * For bases above 10, and using the default base conversion alphabet (see `ALPHABET`), values + * from 10 to 35 are represented by a-z (the same as `Number.prototype.toString`). + * + * If a base is specified the value is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings, otherwise it is not. + * + * If a base is not specified, and this BigNumber has a positive exponent that is equal to or + * greater than the positive component of the current `EXPONENTIAL_AT` setting, or a negative + * exponent equal to or less than the negative component of the setting, then exponential notation + * is returned. + * + * If `base` is `null` or `undefined` it is ignored. + * + * Throws if `base` is invalid. + * + * ```ts + * x = new BigNumber(750000) + * x.toString() // '750000' + * BigNumber.config({ EXPONENTIAL_AT: 5 }) + * x.toString() // '7.5e+5' + * + * y = new BigNumber(362.875) + * y.toString(2) // '101101010.111' + * y.toString(9) // '442.77777777777777777778' + * y.toString(32) // 'ba.s' + * + * BigNumber.config({ DECIMAL_PLACES: 4 }); + * z = new BigNumber('1.23456789') + * z.toString() // '1.23456789' + * z.toString(10) // '1.2346' + * ``` + * + * @param [base] The base, integer, 2 to 36 (or `ALPHABET.length`, see `ALPHABET`). + */ + toString(base?: number): string; + + /** + * As `toString`, but does not accept a base argument and includes the minus sign for negative + * zero. + * + * ``ts + * x = new BigNumber('-0') + * x.toString() // '0' + * x.valueOf() // '-0' + * y = new BigNumber('1.777e+457') + * y.valueOf() // '1.777e+457' + * ``` + */ + valueOf(): string; + + /** Helps ES6 import. */ + private static readonly default?: BigNumber.Constructor; + + /** Helps ES6 import. */ + private static readonly BigNumber?: BigNumber.Constructor; + + /** Rounds away from zero. */ + static readonly ROUND_UP: 0; + + /** Rounds towards zero. */ + static readonly ROUND_DOWN: 1; + + /** Rounds towards Infinity. */ + static readonly ROUND_CEIL: 2; + + /** Rounds towards -Infinity. */ + static readonly ROUND_FLOOR: 3; + + /** Rounds towards nearest neighbour. If equidistant, rounds away from zero . */ + static readonly ROUND_HALF_UP: 4; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards zero. */ + static readonly ROUND_HALF_DOWN: 5; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards even neighbour. */ + static readonly ROUND_HALF_EVEN: 6; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards Infinity. */ + static readonly ROUND_HALF_CEIL: 7; + + /** Rounds towards nearest neighbour. If equidistant, rounds towards -Infinity. */ + static readonly ROUND_HALF_FLOOR: 8; + + /** See `MODULO_MODE`. */ + static readonly EUCLID: 9; + + /** + * To aid in debugging, if a `BigNumber.DEBUG` property is `true` then an error will be thrown + * if the BigNumber constructor receives an invalid `BigNumber.Value`, or if `BigNumber.isBigNumber` + * receives a BigNumber instance that is malformed. + * + * ```ts + * // No error, and BigNumber NaN is returned. + * new BigNumber('blurgh') // 'NaN' + * new BigNumber(9, 2) // 'NaN' + * BigNumber.DEBUG = true + * new BigNumber('blurgh') // '[BigNumber Error] Not a number' + * new BigNumber(9, 2) // '[BigNumber Error] Not a base 2 number' + * ``` + * + * An error will also be thrown if a `BigNumber.Value` is of type number with more than 15 + * significant digits, as calling `toString` or `valueOf` on such numbers may not result + * in the intended value. + * + * ```ts + * console.log(823456789123456.3) // 823456789123456.2 + * // No error, and the returned BigNumber does not have the same value as the number literal. + * new BigNumber(823456789123456.3) // '823456789123456.2' + * BigNumber.DEBUG = true + * new BigNumber(823456789123456.3) + * // '[BigNumber Error] Number primitive has more than 15 significant digits' + * ``` + * + * Check that a BigNumber instance is well-formed: + * + * ```ts + * x = new BigNumber(10) + * + * BigNumber.DEBUG = false + * // Change x.c to an illegitimate value. + * x.c = NaN + * // No error, as BigNumber.DEBUG is false. + * BigNumber.isBigNumber(x) // true + * + * BigNumber.DEBUG = true + * BigNumber.isBigNumber(x) // '[BigNumber Error] Invalid BigNumber' + * ``` + */ + static DEBUG?: boolean; + + /** + * Returns a new independent BigNumber constructor with configuration as described by `object`, or + * with the default configuration if object is `null` or `undefined`. + * + * Throws if `object` is not an object. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) + * + * x = new BigNumber(1) + * y = new BN(1) + * + * x.div(3) // 0.33333 + * y.div(3) // 0.333333333 + * + * // BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to: + * BN = BigNumber.clone() + * BN.config({ DECIMAL_PLACES: 9 }) + * ``` + * + * @param [object] The configuration object. + */ + static clone(object?: BigNumber.Config): BigNumber.Constructor; + + /** + * Configures the settings that apply to this BigNumber constructor. + * + * The configuration object, `object`, contains any number of the properties shown in the example + * below. + * + * Returns an object with the above properties and their current values. + * + * Throws if `object` is not an object, or if an invalid value is assigned to one or more of the + * properties. + * + * ```ts + * BigNumber.config({ + * DECIMAL_PLACES: 40, + * ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL, + * EXPONENTIAL_AT: [-10, 20], + * RANGE: [-500, 500], + * CRYPTO: true, + * MODULO_MODE: BigNumber.ROUND_FLOOR, + * POW_PRECISION: 80, + * FORMAT: { + * groupSize: 3, + * groupSeparator: ' ', + * decimalSeparator: ',' + * }, + * ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + * }); + * + * BigNumber.config().DECIMAL_PLACES // 40 + * ``` + * + * @param object The configuration object. + */ + static config(object?: BigNumber.Config): BigNumber.Config; + + /** + * Returns `true` if `value` is a BigNumber instance, otherwise returns `false`. + * + * If `BigNumber.DEBUG` is `true`, throws if a BigNumber instance is not well-formed. + * + * ```ts + * x = 42 + * y = new BigNumber(x) + * + * BigNumber.isBigNumber(x) // false + * y instanceof BigNumber // true + * BigNumber.isBigNumber(y) // true + * + * BN = BigNumber.clone(); + * z = new BN(x) + * z instanceof BigNumber // false + * BigNumber.isBigNumber(z) // true + * ``` + * + * @param value The value to test. + */ + static isBigNumber(value: any): value is BigNumber; + + /** + * Returns a BigNumber whose value is the maximum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.maximum(4e9, x, '123456789.9') // '4000000000' + * + * arr = [12, '13', new BigNumber(14)] + * BigNumber.maximum.apply(null, arr) // '14' + * ``` + * + * @param n A numeric value. + */ + static maximum(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the maximum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.max(4e9, x, '123456789.9') // '4000000000' + * + * arr = [12, '13', new BigNumber(14)] + * BigNumber.max.apply(null, arr) // '14' + * ``` + * + * @param n A numeric value. + */ + static max(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the minimum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.minimum(4e9, x, '123456789.9') // '123456789.9' + * + * arr = [2, new BigNumber(-14), '-15.9999', -12] + * BigNumber.minimum.apply(null, arr) // '-15.9999' + * ``` + * + * @param n A numeric value. + */ + static minimum(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the minimum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.min(4e9, x, '123456789.9') // '123456789.9' + * + * arr = [2, new BigNumber(-14), '-15.9999', -12] + * BigNumber.min.apply(null, arr) // '-15.9999' + * ``` + * + * @param n A numeric value. + */ + static min(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and less than 1. + * + * The return value will have `decimalPlaces` decimal places, or less if trailing zeros are + * produced. If `decimalPlaces` is omitted, the current `DECIMAL_PLACES` setting will be used. + * + * Depending on the value of this BigNumber constructor's `CRYPTO` setting and the support for the + * `crypto` object in the host environment, the random digits of the return value are generated by + * either `Math.random` (fastest), `crypto.getRandomValues` (Web Cryptography API in recent + * browsers) or `crypto.randomBytes` (Node.js). + * + * To be able to set `CRYPTO` to true when using Node.js, the `crypto` object must be available + * globally: + * + * ```ts + * global.crypto = require('crypto') + * ``` + * + * If `CRYPTO` is true, i.e. one of the `crypto` methods is to be used, the value of a returned + * BigNumber should be cryptographically secure and statistically indistinguishable from a random + * value. + * + * Throws if `decimalPlaces` is invalid. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 10 }) + * BigNumber.random() // '0.4117936847' + * BigNumber.random(20) // '0.78193327636914089009' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + */ + static random(decimalPlaces?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the sum of the arguments. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.sum(4e9, x, '123456789.9') // '7381326134.9378653' + * + * arr = [2, new BigNumber(14), '15.9999', 12] + * BigNumber.sum.apply(null, arr) // '43.9999' + * ``` + * + * @param n A numeric value. + */ + static sum(...n: BigNumber.Value[]): BigNumber; + + /** + * Configures the settings that apply to this BigNumber constructor. + * + * The configuration object, `object`, contains any number of the properties shown in the example + * below. + * + * Returns an object with the above properties and their current values. + * + * Throws if `object` is not an object, or if an invalid value is assigned to one or more of the + * properties. + * + * ```ts + * BigNumber.set({ + * DECIMAL_PLACES: 40, + * ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL, + * EXPONENTIAL_AT: [-10, 20], + * RANGE: [-500, 500], + * CRYPTO: true, + * MODULO_MODE: BigNumber.ROUND_FLOOR, + * POW_PRECISION: 80, + * FORMAT: { + * groupSize: 3, + * groupSeparator: ' ', + * decimalSeparator: ',' + * }, + * ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + * }); + * + * BigNumber.set().DECIMAL_PLACES // 40 + * ``` + * + * @param object The configuration object. + */ + static set(object?: BigNumber.Config): BigNumber.Config; +} + +export function BigNumber(n: BigNumber.Value, base?: number): BigNumber; diff --git a/node_modules/bignumber.js/bignumber.js b/node_modules/bignumber.js/bignumber.js new file mode 100644 index 000000000..007f06400 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.js @@ -0,0 +1,2922 @@ +;(function (globalObject) { + 'use strict'; + +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + + var BigNumber, + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + + /* + * Create and return a BigNumber constructor. + */ + function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; + } + + + // PRIVATE HELPER FUNCTIONS + + // These functions don't need access to variables, + // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + + function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; + } + + + // Return a coefficient array as a string of base 10 digits. + function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); + } + + + // Compare the value of BigNumbers x and y. + function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; + } + + + /* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ + function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } + } + + + // Assumes finite n. + function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; + } + + + function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; + } + + + function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; + } + + + // EXPORT + + + BigNumber = clone(); + BigNumber['default'] = BigNumber.BigNumber = BigNumber; + + // AMD. + if (typeof define == 'function' && define.amd) { + define(function () { return BigNumber; }); + + // Node.js and other environments that support module.exports. + } else if (typeof module != 'undefined' && module.exports) { + module.exports = BigNumber; + + // Browser. + } else { + if (!globalObject) { + globalObject = typeof self != 'undefined' && self ? self : window; + } + + globalObject.BigNumber = BigNumber; + } +})(this); diff --git a/node_modules/bignumber.js/bignumber.mjs b/node_modules/bignumber.js/bignumber.mjs new file mode 100644 index 000000000..d5e02e9c0 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.mjs @@ -0,0 +1,2907 @@ +/* + * bignumber.js v9.1.2 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | sum + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + +var + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + +/* + * Create and return a BigNumber constructor. + */ +function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + prefix: '', + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ',', + decimalSeparator: '.', + fractionGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + suffix: '' + }, + + // The alphabet used for base conversion. It must be at least 2 characters long, with no '+', + // '-', '.', whitespace, or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz', + alphabetHasNormalDecimalDigits = true; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * v {number|string|BigNumber} A numeric value. + * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(v, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor call without `new`. + if (!(x instanceof BigNumber)) return new BigNumber(v, b); + + if (b == null) { + + if (v && v._isBigNumber === true) { + x.s = v.s; + + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + + return; + } + + if ((isNum = typeof v == 'number') && v * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + + // Fast path for integers, where n < 2147483648 (2**31). + if (v === ~~v) { + for (e = 0, i = v; i >= 10; i /= 10, e++); + + if (e > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e; + x.c = [v]; + } + + return; + } + + str = String(v); + } else { + + if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum); + + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + str = String(v); + + if (isNum = typeof v == 'number') { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (v * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp, so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, String(v), isNum, b); + } + } + + // Prevent later check for length on converted number. + isNum = false; + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + if (str = str.slice(i, ++len)) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error + (tooManyDigits + (x.s * v)); + } + + // Overflow? + if ((e = e - i - 1) > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; // i < 1 + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * prefix {string} + * groupSize {number} + * secondaryGroupSize {number} + * groupSeparator {string} + * decimalSeparator {string} + * fractionGroupSize {number} + * fractionGroupSeparator {string} + * suffix {string} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if less than two characters, + // or if it contains '+', '-', '.', whitespace, or a repeated character. + if (typeof v == 'string' && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789'; + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed. + * + * v {any} + * + * '[BigNumber Error] Invalid BigNumber: {v}' + */ + BigNumber.isBigNumber = function (v) { + if (!v || v._isBigNumber !== true) return false; + if (!BigNumber.DEBUG) return true; + + var i, n, + c = v.c, + e = v.e, + s = v.s; + + out: if ({}.toString.call(c) == '[object Array]') { + + if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) { + + // If the first element is zero, the BigNumber value must be zero. + if (c[0] === 0) { + if (e === 0 && c.length === 1) return true; + break out; + } + + // Calculate number of digits that c[0] should have, based on the exponent. + i = (e + 1) % LOG_BASE; + if (i < 1) i += LOG_BASE; + + // Calculate number of digits of c[0]. + //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) { + if (String(c[0]).length == i) { + + for (i = 0; i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) break out; + } + + // Last element cannot be zero, unless it is the only element. + if (n !== 0) return true; + } + } + + // Infinity/NaN + } else if (c === null && e === null && (s === null || s === 1 || s === -1)) { + return true; + } + + throw Error + (bignumberError + 'Invalid BigNumber: ' + v); + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, -1); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, 1); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + /* + * Return a BigNumber whose value is the sum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.sum = function () { + var i = 1, + args = arguments, + sum = new BigNumber(args[0]); + for (; i < args.length;) sum = sum.plus(args[i++]); + return sum; + }; + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + // If any number is NaN, return NaN. + function maxOrMin(args, n) { + var k, y, + i = 1, + x = new BigNumber(args[0]); + + for (; i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; + } + } + + return x; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.s = null; + } + + x.c = x.e = null; + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + function valueOf(n) { + var str, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + valueOf(n)); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; + } + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (i) { + i = mathfloor(i / 2); + if (i === 0) break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) break; + nIsOdd = i % 2; + } + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y.s = -y.s; + } + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) { + t = yc; + yc = xc; + xc = t; + b = a; + } + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+valueOf(x)); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(+n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '5e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the format or FORMAT object (see BigNumber.set). + * + * The formatting object may contain some or all of the properties shown below. + * + * FORMAT = { + * prefix: '', + * groupSize: 3, + * secondaryGroupSize: 0, + * groupSeparator: ',', + * decimalSeparator: '.', + * fractionGroupSize: 0, + * fractionGroupSeparator: '\xA0', // non-breaking space + * suffix: '' + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * [format] {object} Formatting options. See FORMAT pbject above. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + * '[BigNumber Error] Argument not an object: {format}' + */ + P.toFormat = function (dp, rm, format) { + var str, + x = this; + + if (format == null) { + if (dp != null && rm && typeof rm == 'object') { + format = rm; + rm = null; + } else if (dp && typeof dp == 'object') { + format = dp; + dp = rm = null; + } else { + format = FORMAT; + } + } else if (typeof format != 'object') { + throw Error + (bignumberError + 'Argument not an object: ' + format); + } + + str = x.toFixed(dp, rm); + + if (x.c) { + var i, + arr = str.split('.'), + g1 = +format.groupSize, + g2 = +format.secondaryGroupSize, + groupSeparator = format.groupSeparator || '', + intPart = arr[0], + fractionPart = arr[1], + isNeg = x.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + (format.fractionGroupSeparator || '')) + : fractionPart) + : intPart; + } + + return (format.prefix || '') + str + (format.suffix || ''); + }; + + + /* + * Return an array of two BigNumbers representing the value of this BigNumber as a simple + * fraction with an integer numerator and an integer denominator. + * The denominator will be a positive non-zero value less than or equal to the specified + * maximum denominator. If a maximum denominator is not specified, the denominator will be + * the lowest value necessary to represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); + } + } + + if (!xc) return new BigNumber(x); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e = e * 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + + MAX_EXP = exp; + + return r; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +valueOf(this); + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(coeffToString(n.c), e) + : toFixedPoint(coeffToString(n.c), e, '0'); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + return valueOf(this); + }; + + + P._isBigNumber = true; + + P[Symbol.toStringTag] = 'BigNumber'; + + // Node.js v10.12.0+ + P[Symbol.for('nodejs.util.inspect.custom')] = P.valueOf; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; +} + + +// PRIVATE HELPER FUNCTIONS + +// These functions don't need access to variables, +// e.g. DECIMAL_PLACES, in the scope of the `clone` function above. + + +function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; +} + + +// Return a coefficient array as a string of base 10 digits. +function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + + return r.slice(0, j + 1 || 1); +} + + +// Compare the value of BigNumbers x and y. +function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; +} + + +/* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ +function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + String(n)); + } +} + + +// Assumes finite n. +function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; +} + + +function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; +} + + +function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; +} + + +// EXPORT + + +export var BigNumber = clone(); + +export default BigNumber; diff --git a/node_modules/bignumber.js/doc/API.html b/node_modules/bignumber.js/doc/API.html new file mode 100644 index 000000000..a16c034be --- /dev/null +++ b/node_modules/bignumber.js/doc/API.html @@ -0,0 +1,2249 @@ + + + + + + +bignumber.js API + + + + + + +
+ +

bignumber.js

+ +

A JavaScript library for arbitrary-precision arithmetic.

+

Hosted on GitHub.

+ +

API

+ +

+ See the README on GitHub for a + quick-start introduction. +

+

+ In all examples below, var and semicolons are not shown, and if a commented-out + value is in quotes it means toString has been called on the preceding expression. +

+ + +

CONSTRUCTOR

+ + +
+ BigNumberBigNumber(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number: integer, 2 to 36 inclusive. (See + ALPHABET to extend this range). +

+

+ Returns a new instance of a BigNumber object with value n, where n + is a numeric value in the specified base, or base 10 if + base is omitted or is null or undefined. +

+

+ Note that the BigNnumber constructor accepts an n of type number purely + as a convenience so that string quotes don't have to be typed when entering literal values, + and that it is the toString value of n that is used rather than its + underlying binary floating point value converted to decimal. +

+
+x = new BigNumber(123.4567)                // '123.4567'
+// 'new' is optional
+y = BigNumber(x)                           // '123.4567'
+

+ If n is a base 10 value it can be in normal or exponential notation. + Values in other bases must be in normal notation. Values in any base can have fraction digits, + i.e. digits after the decimal point. +

+
+new BigNumber(43210)                       // '43210'
+new BigNumber('4.321e+4')                  // '43210'
+new BigNumber('-735.0918e-430')            // '-7.350918e-428'
+new BigNumber('123412421.234324', 5)       // '607236.557696'
+

+ Signed 0, signed Infinity and NaN are supported. +

+
+new BigNumber('-Infinity')                 // '-Infinity'
+new BigNumber(NaN)                         // 'NaN'
+new BigNumber(-0)                          // '0'
+new BigNumber('.5')                        // '0.5'
+new BigNumber('+2')                        // '2'
+

+ String values in hexadecimal literal form, e.g. '0xff' or '0xFF' + (but not '0xfF'), are valid, as are string values with the octal and binary + prefixs '0o' and '0b'. String values in octal literal form without + the prefix will be interpreted as decimals, e.g. '011' is interpreted as 11, not 9. +

+
+new BigNumber(-10110100.1, 2)              // '-180.5'
+new BigNumber('-0b10110100.1')             // '-180.5'
+new BigNumber('ff.8', 16)                  // '255.5'
+new BigNumber('0xff.8')                    // '255.5'
+

+ If a base is specified, n is rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. This includes base + 10 so don't include a base parameter for decimal values unless + this behaviour is wanted. +

+
BigNumber.config({ DECIMAL_PLACES: 5 })
+new BigNumber(1.23456789)                  // '1.23456789'
+new BigNumber(1.23456789, 10)              // '1.23457'
+

An error is thrown if base is invalid. See Errors.

+

+ There is no limit to the number of digits of a value of type string (other than + that of JavaScript's maximum array size). See RANGE to set + the maximum and minimum possible exponent value of a BigNumber. +

+
+new BigNumber('5032485723458348569331745.33434346346912144534543')
+new BigNumber('4.321e10000000')
+

BigNumber NaN is returned if n is invalid + (unless BigNumber.DEBUG is true, see below).

+
+new BigNumber('.1*')                       // 'NaN'
+new BigNumber('blurgh')                    // 'NaN'
+new BigNumber(9, 2)                        // 'NaN'
+

+ To aid in debugging, if BigNumber.DEBUG is true then an error will + be thrown on an invalid n. An error will also be thrown if n is of + type number and has more than 15 significant digits, as calling + toString or valueOf on + these numbers may not result in the intended value. +

+
+console.log(823456789123456.3)            //  823456789123456.2
+new BigNumber(823456789123456.3)          // '823456789123456.2'
+BigNumber.DEBUG = true
+// '[BigNumber Error] Number primitive has more than 15 significant digits'
+new BigNumber(823456789123456.3)
+// '[BigNumber Error] Not a base 2 number'
+new BigNumber(9, 2)
+

+ A BigNumber can also be created from an object literal. + Use isBigNumber to check that it is well-formed. +

+
new BigNumber({ s: 1, e: 2, c: [ 777, 12300000000000 ], _isBigNumber: true })    // '777.123'
+ + + + +

Methods

+

The static methods of a BigNumber constructor.

+ + + + +
clone + .clone([object]) ⇒ BigNumber constructor +
+

object: object

+

+ Returns a new independent BigNumber constructor with configuration as described by + object (see config), or with the default + configuration if object is null or undefined. +

+

+ Throws if object is not an object. See Errors. +

+
BigNumber.config({ DECIMAL_PLACES: 5 })
+BN = BigNumber.clone({ DECIMAL_PLACES: 9 })
+
+x = new BigNumber(1)
+y = new BN(1)
+
+x.div(3)                        // 0.33333
+y.div(3)                        // 0.333333333
+
+// BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to:
+BN = BigNumber.clone()
+BN.config({ DECIMAL_PLACES: 9 })
+ + + +
configset([object]) ⇒ object
+

+ object: object: an object that contains some or all of the following + properties. +

+

Configures the settings for this particular BigNumber constructor.

+ +
+
DECIMAL_PLACES
+
+ number: integer, 0 to 1e+9 inclusive
+ Default value: 20 +
+
+ The maximum number of decimal places of the results of operations involving + division, i.e. division, square root and base conversion operations, and power operations + with negative exponents.
+
+
+
BigNumber.config({ DECIMAL_PLACES: 5 })
+BigNumber.set({ DECIMAL_PLACES: 5 })    // equivalent
+
+ + + +
ROUNDING_MODE
+
+ number: integer, 0 to 8 inclusive
+ Default value: 4 (ROUND_HALF_UP) +
+
+ The rounding mode used in the above operations and the default rounding mode of + decimalPlaces, + precision, + toExponential, + toFixed, + toFormat and + toPrecision. +
+
The modes are available as enumerated properties of the BigNumber constructor.
+
+
BigNumber.config({ ROUNDING_MODE: 0 })
+BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP })    // equivalent
+
+ + + +
EXPONENTIAL_AT
+
+ number: integer, magnitude 0 to 1e+9 inclusive, or +
+ number[]: [ integer -1e+9 to 0 inclusive, integer + 0 to 1e+9 inclusive ]
+ Default value: [-7, 20] +
+
+ The exponent value(s) at which toString returns exponential notation. +
+
+ If a single number is assigned, the value is the exponent magnitude.
+ If an array of two numbers is assigned then the first number is the negative exponent + value at and beneath which exponential notation is used, and the second number is the + positive exponent value at and above which the same. +
+
+ For example, to emulate JavaScript numbers in terms of the exponent values at which they + begin to use exponential notation, use [-7, 20]. +
+
+
BigNumber.config({ EXPONENTIAL_AT: 2 })
+new BigNumber(12.3)         // '12.3'        e is only 1
+new BigNumber(123)          // '1.23e+2'
+new BigNumber(0.123)        // '0.123'       e is only -1
+new BigNumber(0.0123)       // '1.23e-2'
+
+BigNumber.config({ EXPONENTIAL_AT: [-7, 20] })
+new BigNumber(123456789)    // '123456789'   e is only 8
+new BigNumber(0.000000123)  // '1.23e-7'
+
+// Almost never return exponential notation:
+BigNumber.config({ EXPONENTIAL_AT: 1e+9 })
+
+// Always return exponential notation:
+BigNumber.config({ EXPONENTIAL_AT: 0 })
+
+
+ Regardless of the value of EXPONENTIAL_AT, the toFixed method + will always return a value in normal notation and the toExponential method + will always return a value in exponential form. +
+
+ Calling toString with a base argument, e.g. toString(10), will + also always return normal notation. +
+ + + +
RANGE
+
+ number: integer, magnitude 1 to 1e+9 inclusive, or +
+ number[]: [ integer -1e+9 to -1 inclusive, integer + 1 to 1e+9 inclusive ]
+ Default value: [-1e+9, 1e+9] +
+
+ The exponent value(s) beyond which overflow to Infinity and underflow to + zero occurs. +
+
+ If a single number is assigned, it is the maximum exponent magnitude: values wth a + positive exponent of greater magnitude become Infinity and those with a + negative exponent of greater magnitude become zero. +
+ If an array of two numbers is assigned then the first number is the negative exponent + limit and the second number is the positive exponent limit. +
+
+ For example, to emulate JavaScript numbers in terms of the exponent values at which they + become zero and Infinity, use [-324, 308]. +
+
+
BigNumber.config({ RANGE: 500 })
+BigNumber.config().RANGE     // [ -500, 500 ]
+new BigNumber('9.999e499')   // '9.999e+499'
+new BigNumber('1e500')       // 'Infinity'
+new BigNumber('1e-499')      // '1e-499'
+new BigNumber('1e-500')      // '0'
+
+BigNumber.config({ RANGE: [-3, 4] })
+new BigNumber(99999)         // '99999'      e is only 4
+new BigNumber(100000)        // 'Infinity'   e is 5
+new BigNumber(0.001)         // '0.01'       e is only -3
+new BigNumber(0.0001)        // '0'          e is -4
+
+
+ The largest possible magnitude of a finite BigNumber is + 9.999...e+1000000000.
+ The smallest possible magnitude of a non-zero BigNumber is 1e-1000000000. +
+ + + +
CRYPTO
+
+ boolean: true or false.
+ Default value: false +
+
+ The value that determines whether cryptographically-secure pseudo-random number + generation is used. +
+
+ If CRYPTO is set to true then the + random method will generate random digits using + crypto.getRandomValues in browsers that support it, or + crypto.randomBytes if using Node.js. +
+
+ If neither function is supported by the host environment then attempting to set + CRYPTO to true will fail and an exception will be thrown. +
+
+ If CRYPTO is false then the source of randomness used will be + Math.random (which is assumed to generate at least 30 bits of + randomness). +
+
See random.
+
+
+// Node.js
+const crypto = require('crypto');   // CommonJS
+import * as crypto from 'crypto';   // ES module
+
+global.crypto = crypto;
+
+BigNumber.config({ CRYPTO: true })
+BigNumber.config().CRYPTO       // true
+BigNumber.random()              // 0.54340758610486147524
+
+ + + +
MODULO_MODE
+
+ number: integer, 0 to 9 inclusive
+ Default value: 1 (ROUND_DOWN) +
+
The modulo mode used when calculating the modulus: a mod n.
+
+ The quotient, q = a / n, is calculated according to the + ROUNDING_MODE that corresponds to the chosen + MODULO_MODE. +
+
The remainder, r, is calculated as: r = a - n * q.
+
+ The modes that are most commonly used for the modulus/remainder operation are shown in + the following table. Although the other rounding modes can be used, they may not give + useful results. +
+
+ + + + + + + + + + + + + + + + + + + + + + +
PropertyValueDescription
ROUND_UP0 + The remainder is positive if the dividend is negative, otherwise it is negative. +
ROUND_DOWN1 + The remainder has the same sign as the dividend.
+ This uses 'truncating division' and matches the behaviour of JavaScript's + remainder operator %. +
ROUND_FLOOR3 + The remainder has the same sign as the divisor.
+ This matches Python's % operator. +
ROUND_HALF_EVEN6The IEEE 754 remainder function.
EUCLID9 + The remainder is always positive. Euclidian division:
+ q = sign(n) * floor(a / abs(n)) +
+
+
+ The rounding/modulo modes are available as enumerated properties of the BigNumber + constructor. +
+
See modulo.
+
+
BigNumber.config({ MODULO_MODE: BigNumber.EUCLID })
+BigNumber.config({ MODULO_MODE: 9 })          // equivalent
+
+ + + +
POW_PRECISION
+
+ number: integer, 0 to 1e+9 inclusive.
+ Default value: 0 +
+
+ The maximum precision, i.e. number of significant digits, of the result of the power + operation (unless a modulus is specified). +
+
If set to 0, the number of significant digits will not be limited.
+
See exponentiatedBy.
+
BigNumber.config({ POW_PRECISION: 100 })
+ + + +
FORMAT
+
object
+
+ The FORMAT object configures the format of the string returned by the + toFormat method. +
+
+ The example below shows the properties of the FORMAT object that are + recognised, and their default values. +
+
+ Unlike the other configuration properties, the values of the properties of the + FORMAT object will not be checked for validity. The existing + FORMAT object will simply be replaced by the object that is passed in. + The object can include any number of the properties shown below. +
+
See toFormat for examples of usage.
+
+
+BigNumber.config({
+  FORMAT: {
+    // string to prepend
+    prefix: '',
+    // decimal separator
+    decimalSeparator: '.',
+    // grouping separator of the integer part
+    groupSeparator: ',',
+    // primary grouping size of the integer part
+    groupSize: 3,
+    // secondary grouping size of the integer part
+    secondaryGroupSize: 0,
+    // grouping separator of the fraction part
+    fractionGroupSeparator: ' ',
+    // grouping size of the fraction part
+    fractionGroupSize: 0,
+    // string to append
+    suffix: ''
+  }
+});
+
+ + + +
ALPHABET
+
+ string
+ Default value: '0123456789abcdefghijklmnopqrstuvwxyz' +
+
+ The alphabet used for base conversion. The length of the alphabet corresponds to the + maximum value of the base argument that can be passed to the + BigNumber constructor or + toString. +
+
+ There is no maximum length for the alphabet, but it must be at least 2 characters long, and + it must not contain whitespace or a repeated character, or the sign indicators + '+' and '-', or the decimal separator '.'. +
+
+
// duodecimal (base 12)
+BigNumber.config({ ALPHABET: '0123456789TE' })
+x = new BigNumber('T', 12)
+x.toString()                // '10'
+x.toString(12)              // 'T'
+
+ + + +
+

+

Returns an object with the above properties and their current values.

+

+ Throws if object is not an object, or if an invalid value is assigned to + one or more of the above properties. See Errors. +

+
+BigNumber.config({
+  DECIMAL_PLACES: 40,
+  ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL,
+  EXPONENTIAL_AT: [-10, 20],
+  RANGE: [-500, 500],
+  CRYPTO: true,
+  MODULO_MODE: BigNumber.ROUND_FLOOR,
+  POW_PRECISION: 80,
+  FORMAT: {
+    groupSize: 3,
+    groupSeparator: ' ',
+    decimalSeparator: ','
+  },
+  ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'
+});
+
+obj = BigNumber.config();
+obj.DECIMAL_PLACES        // 40
+obj.RANGE                 // [-500, 500]
+ + + +
+ isBigNumber.isBigNumber(value) ⇒ boolean +
+

value: any

+

+ Returns true if value is a BigNumber instance, otherwise returns + false. +

+
x = 42
+y = new BigNumber(x)
+
+BigNumber.isBigNumber(x)             // false
+y instanceof BigNumber               // true
+BigNumber.isBigNumber(y)             // true
+
+BN = BigNumber.clone();
+z = new BN(x)
+z instanceof BigNumber               // false
+BigNumber.isBigNumber(z)             // true
+

+ If value is a BigNumber instance and BigNumber.DEBUG is true, + then this method will also check if value is well-formed, and throw if it is not. + See Errors. +

+

+ The check can be useful if creating a BigNumber from an object literal. + See BigNumber. +

+
+x = new BigNumber(10)
+
+// Change x.c to an illegitimate value.
+x.c = NaN
+
+BigNumber.DEBUG = false
+
+// No error.
+BigNumber.isBigNumber(x)    // true
+
+BigNumber.DEBUG = true
+
+// Error.
+BigNumber.isBigNumber(x)    // '[BigNumber Error] Invalid BigNumber'
+ + + +
maximum.max(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the maximum of the arguments. +

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.maximum(4e9, x, '123456789.9')      // '4000000000'
+
+arr = [12, '13', new BigNumber(14)]
+BigNumber.max.apply(null, arr)                // '14'
+ + + +
minimum.min(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the minimum of the arguments. +

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.minimum(4e9, x, '123456789.9')      // '123456789.9'
+
+arr = [2, new BigNumber(-14), '-15.9999', -12]
+BigNumber.min.apply(null, arr)                // '-15.9999'
+ + + +
+ random.random([dp]) ⇒ BigNumber +
+

dp: number: integer, 0 to 1e+9 inclusive

+

+ Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and + less than 1. +

+

+ The return value will have dp decimal places (or less if trailing zeros are + produced).
+ If dp is omitted then the number of decimal places will default to the current + DECIMAL_PLACES setting. +

+

+ Depending on the value of this BigNumber constructor's + CRYPTO setting and the support for the + crypto object in the host environment, the random digits of the return value are + generated by either Math.random (fastest), crypto.getRandomValues + (Web Cryptography API in recent browsers) or crypto.randomBytes (Node.js). +

+

+ To be able to set CRYPTO to true when using + Node.js, the crypto object must be available globally: +

+
// Node.js
+const crypto = require('crypto');   // CommonJS
+import * as crypto from 'crypto';   // ES module
+global.crypto = crypto;
+

+ If CRYPTO is true, i.e. one of the + crypto methods is to be used, the value of a returned BigNumber should be + cryptographically-secure and statistically indistinguishable from a random value. +

+

+ Throws if dp is invalid. See Errors. +

+
BigNumber.config({ DECIMAL_PLACES: 10 })
+BigNumber.random()              // '0.4117936847'
+BigNumber.random(20)            // '0.78193327636914089009'
+ + + +
sum.sum(n...) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the sum of the arguments.

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.sum(4e9, x, '123456789.9')      // '7381326134.9378653'
+
+arr = [2, new BigNumber(14), '15.9999', 12]
+BigNumber.sum.apply(null, arr)            // '43.9999'
+ + + +

Properties

+

+ The library's enumerated rounding modes are stored as properties of the constructor.
+ (They are not referenced internally by the library itself.) +

+

+ Rounding modes 0 to 6 (inclusive) are the same as those of Java's + BigDecimal class. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyValueDescription
ROUND_UP0Rounds away from zero
ROUND_DOWN1Rounds towards zero
ROUND_CEIL2Rounds towards Infinity
ROUND_FLOOR3Rounds towards -Infinity
ROUND_HALF_UP4 + Rounds towards nearest neighbour.
+ If equidistant, rounds away from zero +
ROUND_HALF_DOWN5 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards zero +
ROUND_HALF_EVEN6 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards even neighbour +
ROUND_HALF_CEIL7 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards Infinity +
ROUND_HALF_FLOOR8 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards -Infinity +
+
+BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_CEIL })
+BigNumber.config({ ROUNDING_MODE: 2 })     // equivalent
+ +
DEBUG
+

undefined|false|true

+

+ If BigNumber.DEBUG is set true then an error will be thrown + if this BigNumber constructor receives an invalid value, such as + a value of type number with more than 15 significant digits. + See BigNumber. +

+

+ An error will also be thrown if the isBigNumber + method receives a BigNumber that is not well-formed. + See isBigNumber. +

+
BigNumber.DEBUG = true
+ + +

INSTANCE

+ + +

Methods

+

The methods inherited by a BigNumber instance from its constructor's prototype object.

+

A BigNumber is immutable in the sense that it is not changed by its methods.

+

+ The treatment of ±0, ±Infinity and NaN is + consistent with how JavaScript treats these values. +

+

Many method names have a shorter alias.

+ + + +
absoluteValue.abs() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of + this BigNumber. +

+

The return value is always exact and unrounded.

+
+x = new BigNumber(-0.8)
+y = x.absoluteValue()           // '0.8'
+z = y.abs()                     // '0.8'
+ + + +
+ comparedTo.comparedTo(n [, base]) ⇒ number +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+ + + + + + + + + + + + + + + + + + +
Returns 
1If the value of this BigNumber is greater than the value of n
-1If the value of this BigNumber is less than the value of n
0If this BigNumber and n have the same value
nullIf the value of either this BigNumber or n is NaN
+
+x = new BigNumber(Infinity)
+y = new BigNumber(5)
+x.comparedTo(y)                 // 1
+x.comparedTo(x.minus(1))        // 0
+y.comparedTo(NaN)               // null
+y.comparedTo('110', 2)          // -1
+ + + +
+ decimalPlaces.dp([dp [, rm]]) ⇒ BigNumber|number +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ If dp is a number, returns a BigNumber whose value is the value of this BigNumber + rounded by rounding mode rm to a maximum of dp decimal places. +

+

+ If dp is omitted, or is null or undefined, the return + value is the number of decimal places of the value of this BigNumber, or null if + the value of this BigNumber is ±Infinity or NaN. +

+

+ If rm is omitted, or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = new BigNumber(1234.56)
+x.decimalPlaces(1)                     // '1234.6'
+x.dp()                                 // 2
+x.decimalPlaces(2)                     // '1234.56'
+x.dp(10)                               // '1234.56'
+x.decimalPlaces(0, 1)                  // '1234'
+x.dp(0, 6)                             // '1235'
+x.decimalPlaces(1, 1)                  // '1234.5'
+x.dp(1, BigNumber.ROUND_HALF_EVEN)     // '1234.6'
+x                                      // '1234.56'
+y = new BigNumber('9.9e-101')
+y.dp()                                 // 102
+ + + +
dividedBy.div(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber divided by + n, rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+
+x = new BigNumber(355)
+y = new BigNumber(113)
+x.dividedBy(y)                  // '3.14159292035398230088'
+x.div(5)                        // '71'
+x.div(47, 16)                   // '5'
+ + + +
+ dividedToIntegerBy.idiv(n [, base]) ⇒ + BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + n. +

+
+x = new BigNumber(5)
+y = new BigNumber(3)
+x.dividedToIntegerBy(y)         // '1'
+x.idiv(0.7)                     // '7'
+x.idiv('0.f', 16)               // '5'
+ + + +
+ exponentiatedBy.pow(n [, m]) ⇒ BigNumber +
+

+ n: number|string|BigNumber: integer
+ m: number|string|BigNumber +

+

+ Returns a BigNumber whose value is the value of this BigNumber exponentiated by + n, i.e. raised to the power n, and optionally modulo a modulus + m. +

+

+ Throws if n is not an integer. See Errors. +

+

+ If n is negative the result is rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+

+ As the number of digits of the result of the power operation can grow so large so quickly, + e.g. 123.45610000 has over 50000 digits, the number of significant + digits calculated is limited to the value of the + POW_PRECISION setting (unless a modulus + m is specified). +

+

+ By default POW_PRECISION is set to 0. + This means that an unlimited number of significant digits will be calculated, and that the + method's performance will decrease dramatically for larger exponents. +

+

+ If m is specified and the value of m, n and this + BigNumber are integers, and n is positive, then a fast modular exponentiation + algorithm is used, otherwise the operation will be performed as + x.exponentiatedBy(n).modulo(m) with a + POW_PRECISION of 0. +

+
+Math.pow(0.7, 2)                // 0.48999999999999994
+x = new BigNumber(0.7)
+x.exponentiatedBy(2)            // '0.49'
+BigNumber(3).pow(-2)            // '0.11111111111111111111'
+ + + +
+ integerValue.integerValue([rm]) ⇒ BigNumber +
+

+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a BigNumber whose value is the value of this BigNumber rounded to an integer using + rounding mode rm. +

+

+ If rm is omitted, or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if rm is invalid. See Errors. +

+
+x = new BigNumber(123.456)
+x.integerValue()                        // '123'
+x.integerValue(BigNumber.ROUND_CEIL)    // '124'
+y = new BigNumber(-12.7)
+y.integerValue()                        // '-13'
+y.integerValue(BigNumber.ROUND_DOWN)    // '-12'
+

+ The following is an example of how to add a prototype method that emulates JavaScript's + Math.round function. Math.ceil, Math.floor and + Math.trunc can be emulated in the same way with + BigNumber.ROUND_CEIL, BigNumber.ROUND_FLOOR and + BigNumber.ROUND_DOWN respectively. +

+
+BigNumber.prototype.round = function () {
+  return this.integerValue(BigNumber.ROUND_HALF_CEIL);
+};
+x.round()                               // '123'
+ + + +
isEqualTo.eq(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is equal to the value of + n, otherwise returns false.
+ As with JavaScript, NaN does not equal NaN. +

+

Note: This method uses the comparedTo method internally.

+
+0 === 1e-324                    // true
+x = new BigNumber(0)
+x.isEqualTo('1e-324')           // false
+BigNumber(-0).eq(x)             // true  ( -0 === 0 )
+BigNumber(255).eq('ff', 16)     // true
+
+y = new BigNumber(NaN)
+y.isEqualTo(NaN)                // false
+ + + +
isFinite.isFinite() ⇒ boolean
+

+ Returns true if the value of this BigNumber is a finite number, otherwise + returns false. +

+

+ The only possible non-finite values of a BigNumber are NaN, Infinity + and -Infinity. +

+
+x = new BigNumber(1)
+x.isFinite()                    // true
+y = new BigNumber(Infinity)
+y.isFinite()                    // false
+

+ Note: The native method isFinite() can be used if + n <= Number.MAX_VALUE. +

+ + + +
isGreaterThan.gt(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is greater than the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+0.1 > (0.3 - 0.2)                             // true
+x = new BigNumber(0.1)
+x.isGreaterThan(BigNumber(0.3).minus(0.2))    // false
+BigNumber(0).gt(x)                            // false
+BigNumber(11, 3).gt(11.1, 2)                  // true
+ + + +
+ isGreaterThanOrEqualTo.gte(n [, base]) ⇒ boolean +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is greater than or equal to the value + of n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+(0.3 - 0.2) >= 0.1                     // false
+x = new BigNumber(0.3).minus(0.2)
+x.isGreaterThanOrEqualTo(0.1)          // true
+BigNumber(1).gte(x)                    // true
+BigNumber(10, 18).gte('i', 36)         // true
+ + + +
isInteger.isInteger() ⇒ boolean
+

+ Returns true if the value of this BigNumber is an integer, otherwise returns + false. +

+
+x = new BigNumber(1)
+x.isInteger()                   // true
+y = new BigNumber(123.456)
+y.isInteger()                   // false
+ + + +
isLessThan.lt(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is less than the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+(0.3 - 0.2) < 0.1                       // true
+x = new BigNumber(0.3).minus(0.2)
+x.isLessThan(0.1)                       // false
+BigNumber(0).lt(x)                      // true
+BigNumber(11.1, 2).lt(11, 3)            // true
+ + + +
+ isLessThanOrEqualTo.lte(n [, base]) ⇒ boolean +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is less than or equal to the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+0.1 <= (0.3 - 0.2)                                // false
+x = new BigNumber(0.1)
+x.isLessThanOrEqualTo(BigNumber(0.3).minus(0.2))  // true
+BigNumber(-1).lte(x)                              // true
+BigNumber(10, 18).lte('i', 36)                    // true
+ + + +
isNaN.isNaN() ⇒ boolean
+

+ Returns true if the value of this BigNumber is NaN, otherwise + returns false. +

+
+x = new BigNumber(NaN)
+x.isNaN()                       // true
+y = new BigNumber('Infinity')
+y.isNaN()                       // false
+

Note: The native method isNaN() can also be used.

+ + + +
isNegative.isNegative() ⇒ boolean
+

+ Returns true if the sign of this BigNumber is negative, otherwise returns + false. +

+
+x = new BigNumber(-0)
+x.isNegative()                  // true
+y = new BigNumber(2)
+y.isNegative()                  // false
+

Note: n < 0 can be used if n <= -Number.MIN_VALUE.

+ + + +
isPositive.isPositive() ⇒ boolean
+

+ Returns true if the sign of this BigNumber is positive, otherwise returns + false. +

+
+x = new BigNumber(-0)
+x.isPositive()                  // false
+y = new BigNumber(2)
+y.isPositive()                  // true
+ + + +
isZero.isZero() ⇒ boolean
+

+ Returns true if the value of this BigNumber is zero or minus zero, otherwise + returns false. +

+
+x = new BigNumber(-0)
+x.isZero() && x.isNegative()         // true
+y = new BigNumber(Infinity)
+y.isZero()                      // false
+

Note: n == 0 can be used if n >= Number.MIN_VALUE.

+ + + +
+ minus.minus(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the value of this BigNumber minus n.

+

The return value is always exact and unrounded.

+
+0.3 - 0.1                       // 0.19999999999999998
+x = new BigNumber(0.3)
+x.minus(0.1)                    // '0.2'
+x.minus(0.6, 20)                // '0'
+ + + +
modulo.mod(n [, base]) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber modulo n, i.e. + the integer remainder of dividing this BigNumber by n. +

+

+ The value returned, and in particular its sign, is dependent on the value of the + MODULO_MODE setting of this BigNumber constructor. + If it is 1 (default value), the result will have the same sign as this BigNumber, + and it will match that of Javascript's % operator (within the limits of double + precision) and BigDecimal's remainder method. +

+

The return value is always exact and unrounded.

+

+ See MODULO_MODE for a description of the other + modulo modes. +

+
+1 % 0.9                         // 0.09999999999999998
+x = new BigNumber(1)
+x.modulo(0.9)                   // '0.1'
+y = new BigNumber(33)
+y.mod('a', 33)                  // '3'
+ + + +
+ multipliedBy.times(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber multiplied by n. +

+

The return value is always exact and unrounded.

+
+0.6 * 3                         // 1.7999999999999998
+x = new BigNumber(0.6)
+y = x.multipliedBy(3)           // '1.8'
+BigNumber('7e+500').times(y)    // '1.26e+501'
+x.multipliedBy('-a', 16)        // '-6'
+ + + +
negated.negated() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by + -1. +

+
+x = new BigNumber(1.8)
+x.negated()                     // '-1.8'
+y = new BigNumber(-1.3)
+y.negated()                     // '1.3'
+ + + +
plus.plus(n [, base]) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the value of this BigNumber plus n.

+

The return value is always exact and unrounded.

+
+0.1 + 0.2                       // 0.30000000000000004
+x = new BigNumber(0.1)
+y = x.plus(0.2)                 // '0.3'
+BigNumber(0.7).plus(x).plus(y)  // '1.1'
+x.plus('0.1', 8)                // '0.225'
+ + + +
+ precision.sd([d [, rm]]) ⇒ BigNumber|number +
+

+ d: number|boolean: integer, 1 to 1e+9 + inclusive, or true or false
+ rm: number: integer, 0 to 8 inclusive. +

+

+ If d is a number, returns a BigNumber whose value is the value of this BigNumber + rounded to a precision of d significant digits using rounding mode + rm. +

+

+ If d is omitted or is null or undefined, the return + value is the number of significant digits of the value of this BigNumber, or null + if the value of this BigNumber is ±Infinity or NaN. +

+

+ If d is true then any trailing zeros of the integer + part of a number are counted as significant digits, otherwise they are not. +

+

+ If rm is omitted or is null or undefined, + ROUNDING_MODE will be used. +

+

+ Throws if d or rm is invalid. See Errors. +

+
+x = new BigNumber(9876.54321)
+x.precision(6)                         // '9876.54'
+x.sd()                                 // 9
+x.precision(6, BigNumber.ROUND_UP)     // '9876.55'
+x.sd(2)                                // '9900'
+x.precision(2, 1)                      // '9800'
+x                                      // '9876.54321'
+y = new BigNumber(987000)
+y.precision()                          // 3
+y.sd(true)                             // 6
+ + + +
shiftedBy.shiftedBy(n) ⇒ BigNumber
+

+ n: number: integer, + -9007199254740991 to 9007199254740991 inclusive +

+

+ Returns a BigNumber whose value is the value of this BigNumber shifted by n + places. +

+ The shift is of the decimal point, i.e. of powers of ten, and is to the left if n + is negative or to the right if n is positive. +

+

The return value is always exact and unrounded.

+

+ Throws if n is invalid. See Errors. +

+
+x = new BigNumber(1.23)
+x.shiftedBy(3)                      // '1230'
+x.shiftedBy(-3)                     // '0.00123'
+ + + +
squareRoot.sqrt() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the square root of the value of this BigNumber, + rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+

+ The return value will be correctly rounded, i.e. rounded as if the result was first calculated + to an infinite number of correct digits before rounding. +

+
+x = new BigNumber(16)
+x.squareRoot()                  // '4'
+y = new BigNumber(3)
+y.sqrt()                        // '1.73205080756887729353'
+ + + +
+ toExponential.toExponential([dp [, rm]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber in exponential notation rounded + using rounding mode rm to dp decimal places, i.e with one digit + before the decimal point and dp digits after it. +

+

+ If the value of this BigNumber in exponential notation has fewer than dp fraction + digits, the return value will be appended with zeros accordingly. +

+

+ If dp is omitted, or is null or undefined, the number + of digits after the decimal point defaults to the minimum number of digits necessary to + represent the value exactly.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = 45.6
+y = new BigNumber(x)
+x.toExponential()               // '4.56e+1'
+y.toExponential()               // '4.56e+1'
+x.toExponential(0)              // '5e+1'
+y.toExponential(0)              // '5e+1'
+x.toExponential(1)              // '4.6e+1'
+y.toExponential(1)              // '4.6e+1'
+y.toExponential(1, 1)           // '4.5e+1'  (ROUND_DOWN)
+x.toExponential(3)              // '4.560e+1'
+y.toExponential(3)              // '4.560e+1'
+ + + +
+ toFixed.toFixed([dp [, rm]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber in normal (fixed-point) notation + rounded to dp decimal places using rounding mode rm. +

+

+ If the value of this BigNumber in normal notation has fewer than dp fraction + digits, the return value will be appended with zeros accordingly. +

+

+ Unlike Number.prototype.toFixed, which returns exponential notation if a number + is greater or equal to 1021, this method will always return normal + notation. +

+

+ If dp is omitted or is null or undefined, the return + value will be unrounded and in normal notation. This is also unlike + Number.prototype.toFixed, which returns the value to zero decimal places.
+ It is useful when fixed-point notation is required and the current + EXPONENTIAL_AT setting causes + toString to return exponential notation.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = 3.456
+y = new BigNumber(x)
+x.toFixed()                     // '3'
+y.toFixed()                     // '3.456'
+y.toFixed(0)                    // '3'
+x.toFixed(2)                    // '3.46'
+y.toFixed(2)                    // '3.46'
+y.toFixed(2, 1)                 // '3.45'  (ROUND_DOWN)
+x.toFixed(5)                    // '3.45600'
+y.toFixed(5)                    // '3.45600'
+ + + +
+ toFormat.toFormat([dp [, rm[, format]]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive
+ format: object: see FORMAT +

+

+

+ Returns a string representing the value of this BigNumber in normal (fixed-point) notation + rounded to dp decimal places using rounding mode rm, and formatted + according to the properties of the format object. +

+

+ See FORMAT and the examples below for the properties of the + format object, their types, and their usage. A formatting object may contain + some or all of the recognised properties. +

+

+ If dp is omitted or is null or undefined, then the + return value is not rounded to a fixed number of decimal places.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used.
+ If format is omitted or is null or undefined, the + FORMAT object is used. +

+

+ Throws if dp, rm or format is invalid. See + Errors. +

+
+fmt = {
+  prefix: '',
+  decimalSeparator: '.',
+  groupSeparator: ',',
+  groupSize: 3,
+  secondaryGroupSize: 0,
+  fractionGroupSeparator: ' ',
+  fractionGroupSize: 0,
+  suffix: ''
+}
+
+x = new BigNumber('123456789.123456789')
+
+// Set the global formatting options
+BigNumber.config({ FORMAT: fmt })
+
+x.toFormat()                              // '123,456,789.123456789'
+x.toFormat(3)                             // '123,456,789.123'
+
+// If a reference to the object assigned to FORMAT has been retained,
+// the format properties can be changed directly
+fmt.groupSeparator = ' '
+fmt.fractionGroupSize = 5
+x.toFormat()                              // '123 456 789.12345 6789'
+
+// Alternatively, pass the formatting options as an argument
+fmt = {
+  prefix: '=> ',
+  decimalSeparator: ',',
+  groupSeparator: '.',
+  groupSize: 3,
+  secondaryGroupSize: 2
+}
+
+x.toFormat()                              // '123 456 789.12345 6789'
+x.toFormat(fmt)                           // '=> 12.34.56.789,123456789'
+x.toFormat(2, fmt)                        // '=> 12.34.56.789,12'
+x.toFormat(3, BigNumber.ROUND_UP, fmt)    // '=> 12.34.56.789,124'
+ + + +
+ toFraction.toFraction([maximum_denominator]) + ⇒ [BigNumber, BigNumber] +
+

+ maximum_denominator: + number|string|BigNumber: integer >= 1 and <= + Infinity +

+

+ Returns an array of two BigNumbers representing the value of this BigNumber as a simple + fraction with an integer numerator and an integer denominator. The denominator will be a + positive non-zero value less than or equal to maximum_denominator. +

+

+ If a maximum_denominator is not specified, or is null or + undefined, the denominator will be the lowest value necessary to represent the + number exactly. +

+

+ Throws if maximum_denominator is invalid. See Errors. +

+
+x = new BigNumber(1.75)
+x.toFraction()                  // '7, 4'
+
+pi = new BigNumber('3.14159265358')
+pi.toFraction()                 // '157079632679,50000000000'
+pi.toFraction(100000)           // '312689, 99532'
+pi.toFraction(10000)            // '355, 113'
+pi.toFraction(100)              // '311, 99'
+pi.toFraction(10)               // '22, 7'
+pi.toFraction(1)                // '3, 1'
+ + + +
toJSON.toJSON() ⇒ string
+

As valueOf.

+
+x = new BigNumber('177.7e+457')
+y = new BigNumber(235.4325)
+z = new BigNumber('0.0098074')
+
+// Serialize an array of three BigNumbers
+str = JSON.stringify( [x, y, z] )
+// "["1.777e+459","235.4325","0.0098074"]"
+
+// Return an array of three BigNumbers
+JSON.parse(str, function (key, val) {
+    return key === '' ? val : new BigNumber(val)
+})
+ + + +
toNumber.toNumber() ⇒ number
+

Returns the value of this BigNumber as a JavaScript number primitive.

+

+ This method is identical to using type coercion with the unary plus operator. +

+
+x = new BigNumber(456.789)
+x.toNumber()                    // 456.789
++x                              // 456.789
+
+y = new BigNumber('45987349857634085409857349856430985')
+y.toNumber()                    // 4.598734985763409e+34
+
+z = new BigNumber(-0)
+1 / z.toNumber()                // -Infinity
+1 / +z                          // -Infinity
+ + + +
+ toPrecision.toPrecision([sd [, rm]]) ⇒ string +
+

+ sd: number: integer, 1 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber rounded to sd + significant digits using rounding mode rm. +

+

+ If sd is less than the number of digits necessary to represent the integer part + of the value in normal (fixed-point) notation, then exponential notation is used. +

+

+ If sd is omitted, or is null or undefined, then the + return value is the same as n.toString().
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if sd or rm is invalid. See Errors. +

+
+x = 45.6
+y = new BigNumber(x)
+x.toPrecision()                 // '45.6'
+y.toPrecision()                 // '45.6'
+x.toPrecision(1)                // '5e+1'
+y.toPrecision(1)                // '5e+1'
+y.toPrecision(2, 0)             // '4.6e+1'  (ROUND_UP)
+y.toPrecision(2, 1)             // '4.5e+1'  (ROUND_DOWN)
+x.toPrecision(5)                // '45.600'
+y.toPrecision(5)                // '45.600'
+ + + +
toString.toString([base]) ⇒ string
+

+ base: number: integer, 2 to ALPHABET.length + inclusive (see ALPHABET). +

+

+ Returns a string representing the value of this BigNumber in the specified base, or base + 10 if base is omitted or is null or + undefined. +

+

+ For bases above 10, and using the default base conversion alphabet + (see ALPHABET), values from 10 to + 35 are represented by a-z + (as with Number.prototype.toString). +

+

+ If a base is specified the value is rounded according to the current + DECIMAL_PLACES + and ROUNDING_MODE settings. +

+

+ If a base is not specified, and this BigNumber has a positive + exponent that is equal to or greater than the positive component of the + current EXPONENTIAL_AT setting, + or a negative exponent equal to or less than the negative component of the + setting, then exponential notation is returned. +

+

If base is null or undefined it is ignored.

+

+ Throws if base is invalid. See Errors. +

+
+x = new BigNumber(750000)
+x.toString()                    // '750000'
+BigNumber.config({ EXPONENTIAL_AT: 5 })
+x.toString()                    // '7.5e+5'
+
+y = new BigNumber(362.875)
+y.toString(2)                   // '101101010.111'
+y.toString(9)                   // '442.77777777777777777778'
+y.toString(32)                  // 'ba.s'
+
+BigNumber.config({ DECIMAL_PLACES: 4 });
+z = new BigNumber('1.23456789')
+z.toString()                    // '1.23456789'
+z.toString(10)                  // '1.2346'
+ + + +
valueOf.valueOf() ⇒ string
+

+ As toString, but does not accept a base argument and includes + the minus sign for negative zero. +

+
+x = new BigNumber('-0')
+x.toString()                    // '0'
+x.valueOf()                     // '-0'
+y = new BigNumber('1.777e+457')
+y.valueOf()                     // '1.777e+457'
+ + + +

Properties

+

The properties of a BigNumber instance:

+ + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescriptionTypeValue
ccoefficient*number[] Array of base 1e14 numbers
eexponentnumberInteger, -1000000000 to 1000000000 inclusive
ssignnumber-1 or 1
+

*significand

+

+ The value of any of the c, e and s properties may also + be null. +

+

+ The above properties are best considered to be read-only. In early versions of this library it + was okay to change the exponent of a BigNumber by writing to its exponent property directly, + but this is no longer reliable as the value of the first element of the coefficient array is + now dependent on the exponent. +

+

+ Note that, as with JavaScript numbers, the original exponent and fractional trailing zeros are + not necessarily preserved. +

+
x = new BigNumber(0.123)              // '0.123'
+x.toExponential()                     // '1.23e-1'
+x.c                                   // '1,2,3'
+x.e                                   // -1
+x.s                                   // 1
+
+y = new Number(-123.4567000e+2)       // '-12345.67'
+y.toExponential()                     // '-1.234567e+4'
+z = new BigNumber('-123.4567000e+2')  // '-12345.67'
+z.toExponential()                     // '-1.234567e+4'
+z.c                                   // '1,2,3,4,5,6,7'
+z.e                                   // 4
+z.s                                   // -1
+ + + +

Zero, NaN and Infinity

+

+ The table below shows how ±0, NaN and + ±Infinity are stored. +

+ + + + + + + + + + + + + + + + + + + + + + + + + +
ces
±0[0]0±1
NaNnullnullnull
±Infinitynullnull±1
+
+x = new Number(-0)              // 0
+1 / x == -Infinity              // true
+
+y = new BigNumber(-0)           // '0'
+y.c                             // '0' ( [0].toString() )
+y.e                             // 0
+y.s                             // -1
+ + + +

Errors

+

The table below shows the errors that are thrown.

+

+ The errors are generic Error objects whose message begins + '[BigNumber Error]'. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodThrows
+ BigNumber
+ comparedTo
+ dividedBy
+ dividedToIntegerBy
+ isEqualTo
+ isGreaterThan
+ isGreaterThanOrEqualTo
+ isLessThan
+ isLessThanOrEqualTo
+ minus
+ modulo
+ plus
+ multipliedBy +
Base not a primitive number
Base not an integer
Base out of range
Number primitive has more than 15 significant digits*
Not a base... number*
Not a number*
cloneObject expected
configObject expected
DECIMAL_PLACES not a primitive number
DECIMAL_PLACES not an integer
DECIMAL_PLACES out of range
ROUNDING_MODE not a primitive number
ROUNDING_MODE not an integer
ROUNDING_MODE out of range
EXPONENTIAL_AT not a primitive number
EXPONENTIAL_AT not an integer
EXPONENTIAL_AT out of range
RANGE not a primitive number
RANGE not an integer
RANGE cannot be zero
RANGE cannot be zero
CRYPTO not true or false
crypto unavailable
MODULO_MODE not a primitive number
MODULO_MODE not an integer
MODULO_MODE out of range
POW_PRECISION not a primitive number
POW_PRECISION not an integer
POW_PRECISION out of range
FORMAT not an object
ALPHABET invalid
+ decimalPlaces
+ precision
+ random
+ shiftedBy
+ toExponential
+ toFixed
+ toFormat
+ toPrecision +
Argument not a primitive number
Argument not an integer
Argument out of range
+ decimalPlaces
+ precision +
Argument not true or false
exponentiatedByArgument not an integer
isBigNumberInvalid BigNumber*
+ minimum
+ maximum +
Not a number*
+ random + crypto unavailable
+ toFormat + Argument not an object
toFractionArgument not an integer
Argument out of range
toStringBase not a primitive number
Base not an integer
Base out of range
+

*Only thrown if BigNumber.DEBUG is true.

+

To determine if an exception is a BigNumber Error:

+
+try {
+  // ...
+} catch (e) {
+  if (e instanceof Error && e.message.indexOf('[BigNumber Error]') === 0) {
+      // ...
+  }
+}
+ + + +

Type coercion

+

+ To prevent the accidental use of a BigNumber in primitive number operations, or the + accidental addition of a BigNumber to a string, the valueOf method can be safely + overwritten as shown below. +

+

+ The valueOf method is the same as the + toJSON method, and both are the same as the + toString method except they do not take a base + argument and they include the minus sign for negative zero. +

+
+BigNumber.prototype.valueOf = function () {
+  throw Error('valueOf called!')
+}
+
+x = new BigNumber(1)
+x / 2                    // '[BigNumber Error] valueOf called!'
+x + 'abc'                // '[BigNumber Error] valueOf called!'
+
+ + + +

FAQ

+ +
Why are trailing fractional zeros removed from BigNumbers?
+

+ Some arbitrary-precision libraries retain trailing fractional zeros as they can indicate the + precision of a value. This can be useful but the results of arithmetic operations can be + misleading. +

+
+x = new BigDecimal("1.0")
+y = new BigDecimal("1.1000")
+z = x.add(y)                      // 2.1000
+
+x = new BigDecimal("1.20")
+y = new BigDecimal("3.45000")
+z = x.multiply(y)                 // 4.1400000
+

+ To specify the precision of a value is to specify that the value lies + within a certain range. +

+

+ In the first example, x has a value of 1.0. The trailing zero shows + the precision of the value, implying that it is in the range 0.95 to + 1.05. Similarly, the precision indicated by the trailing zeros of y + indicates that the value is in the range 1.09995 to 1.10005. +

+

+ If we add the two lowest values in the ranges we have, 0.95 + 1.09995 = 2.04995, + and if we add the two highest values we have, 1.05 + 1.10005 = 2.15005, so the + range of the result of the addition implied by the precision of its operands is + 2.04995 to 2.15005. +

+

+ The result given by BigDecimal of 2.1000 however, indicates that the value is in + the range 2.09995 to 2.10005 and therefore the precision implied by + its trailing zeros may be misleading. +

+

+ In the second example, the true range is 4.122744 to 4.157256 yet + the BigDecimal answer of 4.1400000 indicates a range of 4.13999995 + to 4.14000005. Again, the precision implied by the trailing zeros may be + misleading. +

+

+ This library, like binary floating point and most calculators, does not retain trailing + fractional zeros. Instead, the toExponential, toFixed and + toPrecision methods enable trailing zeros to be added if and when required.
+

+
+ + + diff --git a/node_modules/bignumber.js/package.json b/node_modules/bignumber.js/package.json new file mode 100644 index 000000000..71fc0d177 --- /dev/null +++ b/node_modules/bignumber.js/package.json @@ -0,0 +1,50 @@ +{ + "name": "bignumber.js", + "description": "A library for arbitrary-precision decimal and non-decimal arithmetic", + "version": "9.1.2", + "keywords": [ + "arbitrary", + "precision", + "arithmetic", + "big", + "number", + "decimal", + "float", + "biginteger", + "bigdecimal", + "bignumber", + "bigint", + "bignum" + ], + "repository": { + "type": "git", + "url": "https://github.com/MikeMcl/bignumber.js.git" + }, + "main": "bignumber", + "module": "bignumber.mjs", + "browser": "bignumber.js", + "types": "bignumber.d.ts", + "exports": { + ".": { + "types": "./bignumber.d.ts", + "require": "./bignumber.js", + "import": "./bignumber.mjs", + "browser": "./bignumber.js" + }, + "./bignumber.mjs": "./bignumber.mjs", + "./bignumber.js": "./bignumber.js", + "./package.json": "./package.json" + }, + "author": { + "name": "Michael Mclaughlin", + "email": "M8ch88l@gmail.com" + }, + "engines": { + "node": "*" + }, + "license": "MIT", + "scripts": { + "test": "node test/test" + }, + "dependencies": {} +} diff --git a/node_modules/buffer/AUTHORS.md b/node_modules/buffer/AUTHORS.md new file mode 100644 index 000000000..468aa1908 --- /dev/null +++ b/node_modules/buffer/AUTHORS.md @@ -0,0 +1,73 @@ +# Authors + +#### Ordered by first contribution. + +- Romain Beauxis (toots@rastageeks.org) +- Tobias Koppers (tobias.koppers@googlemail.com) +- Janus (ysangkok@gmail.com) +- Rainer Dreyer (rdrey1@gmail.com) +- Tõnis Tiigi (tonistiigi@gmail.com) +- James Halliday (mail@substack.net) +- Michael Williamson (mike@zwobble.org) +- elliottcable (github@elliottcable.name) +- rafael (rvalle@livelens.net) +- Andrew Kelley (superjoe30@gmail.com) +- Andreas Madsen (amwebdk@gmail.com) +- Mike Brevoort (mike.brevoort@pearson.com) +- Brian White (mscdex@mscdex.net) +- Feross Aboukhadijeh (feross@feross.org) +- Ruben Verborgh (ruben@verborgh.org) +- eliang (eliang.cs@gmail.com) +- Jesse Tane (jesse.tane@gmail.com) +- Alfonso Boza (alfonso@cloud.com) +- Mathias Buus (mathiasbuus@gmail.com) +- Devon Govett (devongovett@gmail.com) +- Daniel Cousens (github@dcousens.com) +- Joseph Dykstra (josephdykstra@gmail.com) +- Parsha Pourkhomami (parshap+git@gmail.com) +- Damjan Košir (damjan.kosir@gmail.com) +- daverayment (dave.rayment@gmail.com) +- kawanet (u-suke@kawa.net) +- Linus Unnebäck (linus@folkdatorn.se) +- Nolan Lawson (nolan.lawson@gmail.com) +- Calvin Metcalf (calvin.metcalf@gmail.com) +- Koki Takahashi (hakatasiloving@gmail.com) +- Guy Bedford (guybedford@gmail.com) +- Jan Schär (jscissr@gmail.com) +- RaulTsc (tomescu.raul@gmail.com) +- Matthieu Monsch (monsch@alum.mit.edu) +- Dan Ehrenberg (littledan@chromium.org) +- Kirill Fomichev (fanatid@ya.ru) +- Yusuke Kawasaki (u-suke@kawa.net) +- DC (dcposch@dcpos.ch) +- John-David Dalton (john.david.dalton@gmail.com) +- adventure-yunfei (adventure030@gmail.com) +- Emil Bay (github@tixz.dk) +- Sam Sudar (sudar.sam@gmail.com) +- Volker Mische (volker.mische@gmail.com) +- David Walton (support@geekstocks.com) +- Сковорода Никита Андреевич (chalkerx@gmail.com) +- greenkeeper[bot] (greenkeeper[bot]@users.noreply.github.com) +- ukstv (sergey.ukustov@machinomy.com) +- Renée Kooi (renee@kooi.me) +- ranbochen (ranbochen@qq.com) +- Vladimir Borovik (bobahbdb@gmail.com) +- greenkeeper[bot] (23040076+greenkeeper[bot]@users.noreply.github.com) +- kumavis (aaron@kumavis.me) +- Sergey Ukustov (sergey.ukustov@machinomy.com) +- Fei Liu (liu.feiwood@gmail.com) +- Blaine Bublitz (blaine.bublitz@gmail.com) +- clement (clement@seald.io) +- Koushik Dutta (koushd@gmail.com) +- Jordan Harband (ljharb@gmail.com) +- Niklas Mischkulnig (mischnic@users.noreply.github.com) +- Nikolai Vavilov (vvnicholas@gmail.com) +- Fedor Nezhivoi (gyzerok@users.noreply.github.com) +- shuse2 (shus.toda@gmail.com) +- Peter Newman (peternewman@users.noreply.github.com) +- mathmakgakpak (44949126+mathmakgakpak@users.noreply.github.com) +- jkkang (jkkang@smartauth.kr) +- Deklan Webster (deklanw@gmail.com) +- Martin Heidegger (martin.heidegger@gmail.com) + +#### Generated by bin/update-authors.sh. diff --git a/node_modules/buffer/LICENSE b/node_modules/buffer/LICENSE new file mode 100644 index 000000000..d6bf75dcf --- /dev/null +++ b/node_modules/buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh, and other 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/node_modules/buffer/README.md b/node_modules/buffer/README.md new file mode 100644 index 000000000..451e23576 --- /dev/null +++ b/node_modules/buffer/README.md @@ -0,0 +1,410 @@ +# 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/buffer/master.svg +[travis-url]: https://travis-ci.org/feross/buffer +[npm-image]: https://img.shields.io/npm/v/buffer.svg +[npm-url]: https://npmjs.org/package/buffer +[downloads-image]: https://img.shields.io/npm/dm/buffer.svg +[downloads-url]: https://npmjs.org/package/buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### The buffer module from [node.js](https://nodejs.org/), for the browser. + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg +[saucelabs-url]: https://saucelabs.com/u/buffer + +With [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module. + +The goal is to provide an API that is 100% identical to +[node's Buffer API](https://nodejs.org/api/buffer.html). Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +## features + +- Manipulate binary data like a boss, in all browsers! +- Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`) +- Extremely small bundle size (**6.75KB minified + gzipped**, 51.9KB with comments) +- Excellent browser support (Chrome, Firefox, Edge, Safari 11+, iOS 11+, Android, etc.) +- Preserves Node API exactly, with one minor difference (see below) +- Square-bracket `buf[4]` notation works! +- Does not modify any browser prototypes or put anything on `window` +- Comprehensive test suite (including all buffer tests from node.js core) + +## install + +To use this module directly (without browserify), install it: + +```bash +npm install buffer +``` + +This module was previously called **native-buffer-browserify**, but please use **buffer** +from now on. + +If you do not use a bundler, you can use the [standalone script](https://bundle.run/buffer). + +## usage + +The module's API is identical to node's `Buffer` API. Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +As mentioned above, `require('buffer')` or use the `Buffer` global with +[browserify](http://browserify.org) and this module will automatically be included +in your bundle. Almost any npm module will work in the browser, even if it assumes that +the node `Buffer` API will be available. + +To depend on this module explicitly (without browserify), require it like this: + +```js +var Buffer = require('buffer/').Buffer // note: the trailing slash is important! +``` + +To require this module explicitly, use `require('buffer/')` which tells the node.js module +lookup algorithm (also used by browserify) to use the **npm module** named `buffer` +instead of the **node.js core** module named `buffer`! + + +## how does it work? + +The Buffer constructor returns instances of `Uint8Array` that have their prototype +changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, +so the returned instances will have all the node `Buffer` methods and the +`Uint8Array` methods. Square bracket notation works as expected -- it returns a +single octet. + +The `Uint8Array` prototype remains unmodified. + + +## tracking the latest node api + +This module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer +API is considered **stable** in the +[node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index), +so it is unlikely that there will ever be breaking changes. +Nonetheless, when/if the Buffer API changes in node, this module's API will change +accordingly. + +## related packages + +- [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - Reverse a buffer +- [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - Bitwise xor a buffer +- [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package + +## conversion packages + +### convert typed array to buffer + +Use [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) to convert any kind of typed array to a `Buffer`. Does not perform a copy, so it's super fast. + +### convert buffer to typed array + +`Buffer` is a subclass of `Uint8Array` (which is a typed array). So there is no need to explicitly convert to typed array. Just use the buffer as a `Uint8Array`. + +### convert blob to buffer + +Use [`blob-to-buffer`](https://www.npmjs.com/package/blob-to-buffer) to convert a `Blob` to a `Buffer`. + +### convert buffer to blob + +To convert a `Buffer` to a `Blob`, use the `Blob` constructor: + +```js +var blob = new Blob([ buffer ]) +``` + +Optionally, specify a mimetype: + +```js +var blob = new Blob([ buffer ], { type: 'text/html' }) +``` + +### convert arraybuffer to buffer + +To convert an `ArrayBuffer` to a `Buffer`, use the `Buffer.from` function. Does not perform a copy, so it's super fast. + +```js +var buffer = Buffer.from(arrayBuffer) +``` + +### convert buffer to arraybuffer + +To convert a `Buffer` to an `ArrayBuffer`, use the `.buffer` property (which is present on all `Uint8Array` objects): + +```js +var arrayBuffer = buffer.buffer.slice( + buffer.byteOffset, buffer.byteOffset + buffer.byteLength +) +``` + +Alternatively, use the [`to-arraybuffer`](https://www.npmjs.com/package/to-arraybuffer) module. + +## performance + +See perf tests in `/perf`. + +`BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a +sanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will +always be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module, +which is included to compare against. + +NOTE: Performance has improved since these benchmarks were taken. PR welcome to update the README. + +### Chrome 38 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ | +| Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | | +| | | | | +| BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | | +| Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | | +| Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | | +| Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | | +| Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | | +| Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ | +| DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | | +| | | | | +| BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ | +| DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | | +| | | | | +| BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ | +| DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | | +| | | | | +| BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | | +| Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | | +| DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ | + + +### Firefox 33 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | | +| Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ | +| | | | | +| BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | | +| Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | | +| Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | | +| Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | | +| Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | | +| Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | | +| DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | | +| DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ | +| DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | | +| | | | | +| BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | | +| Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | | +| DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ | + +### Safari 8 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ | +| Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | | +| | | | | +| BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | | +| Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | | +| Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | | +| Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | | +| Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | | +| Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | | +| DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | | +| DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | | +| DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ | +| | | | | +| BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | | +| Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | | +| DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ | + + +### Node 0.11.14 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | | +| Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ | +| NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | | +| | | | | +| BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | | +| Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ | +| NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | | +| | | | | +| BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | | +| Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ | +| NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | | +| | | | | +| BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | | +| Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ | +| NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | | +| | | | | +| BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | | +| Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | | +| NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | | +| Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ | +| NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | | +| | | | | +| BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ | +| DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | | +| NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | | +| | | | | +| BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ | +| DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | | +| NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | | +| | | | | +| BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | | +| DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | | +| NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ | +| | | | | +| BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | | +| Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ | +| NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | | +| | | | | +| BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | | +| DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ | +| NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | | + +### iojs 1.8.1 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | | +| Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | | +| NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ | +| | | | | +| BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | | +| Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | | +| NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | | +| Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | | +| NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | | +| Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ | +| NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | | +| | | | | +| BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | | +| Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | | +| NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | | +| Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ | +| NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | | +| | | | | +| BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ | +| DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | | +| NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | | +| | | | | +| BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ | +| DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | | +| NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | | +| | | | | +| BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | | +| DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | | +| NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ | +| | | | | +| BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | | +| Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | | +| NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | | +| DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ | +| NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | | +| | | | | + +## Testing the project + +First, install the project: + + npm install + +Then, to run tests in Node.js, run: + + npm run test-node + +To test locally in a browser, you can run: + + npm run test-browser-es5-local # For ES5 browsers that don't support ES6 + npm run test-browser-es6-local # For ES6 compliant browsers + +This will print out a URL that you can then open in a browser to run the tests, using [airtap](https://www.npmjs.com/package/airtap). + +To run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run: + + npm test + +This is what's run in Travis, to check against various browsers. The list of browsers is kept in the `bin/airtap-es5.yml` and `bin/airtap-es6.yml` files. + +## JavaScript Standard Style + +This module uses [JavaScript Standard Style](https://github.com/feross/standard). + +[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +To test that the code conforms to the style, `npm install` and run: + + ./node_modules/.bin/standard + +## credit + +This was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify). + +## Security Policies and Procedures + +The `buffer` team and community take all security bugs in `buffer` seriously. Please see our [security policies and procedures](https://github.com/feross/security) document to learn how to report issues. + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis. diff --git a/node_modules/buffer/index.d.ts b/node_modules/buffer/index.d.ts new file mode 100644 index 000000000..07096a2f7 --- /dev/null +++ b/node_modules/buffer/index.d.ts @@ -0,0 +1,194 @@ +export class Buffer extends Uint8Array { + 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: Uint8Array, 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; + readBigUInt64LE(offset: number): BigInt; + readBigUInt64BE(offset: number): BigInt; + 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; + readBigInt64LE(offset: number): BigInt; + readBigInt64BE(offset: number): BigInt; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + reverse(): this; + 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; + writeBigUInt64LE(value: number, offset: number): BigInt; + writeBigUInt64BE(value: number, offset: number): BigInt; + 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; + writeBigInt64LE(value: number, offset: number): BigInt; + writeBigInt64BE(value: number, offset: number): BigInt; + 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 | Uint8Array): 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: Uint8Array[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Uint8Array, buf2: Uint8Array): 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 initializing + */ + 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; +} diff --git a/node_modules/buffer/index.js b/node_modules/buffer/index.js new file mode 100644 index 000000000..7a0e9c2a1 --- /dev/null +++ b/node_modules/buffer/index.js @@ -0,0 +1,2106 @@ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +const base64 = require('base64-js') +const ieee754 = require('ieee754') +const customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +const K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + const arr = new Uint8Array(1) + const proto = { foo: function () { return 42 } } + Object.setPrototypeOf(proto, Uint8Array.prototype) + Object.setPrototypeOf(arr, proto) + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + const buf = new Uint8Array(length) + Object.setPrototypeOf(buf, Buffer.prototype) + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + const valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + const b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) +Object.setPrototypeOf(Buffer, Uint8Array) + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + const length = byteLength(string, encoding) | 0 + let buf = createBuffer(length) + + const actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0 + const buf = createBuffer(length) + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView) + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + let buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype) + + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + const len = checked(obj.length) | 0 + const buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + let x = a.length + let y = b.length + + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + let i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + const buffer = Buffer.allocUnsafe(length) + let pos = 0 + for (i = 0; i < list.length; ++i) { + let buf = list[i] + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) + buf.copy(buffer, pos) + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ) + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos) + } + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + const len = string.length + const mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + let loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + let loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + const i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + const len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + const len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + const len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + const length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + let str = '' + const max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + let x = thisEnd - thisStart + let y = end - start + const len = Math.min(x, y) + + const thisCopy = this.slice(thisStart, thisEnd) + const targetCopy = target.slice(start, end) + + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + let indexSize = 1 + let arrLength = arr.length + let valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + let i + if (dir) { + let foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + let found = true + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + const remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + const strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + let i + for (i = 0; i < length; ++i) { + const parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + const remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + let loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + const res = [] + + let i = start + while (i < end) { + const firstByte = buf[i] + let codePoint = null + let bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +const MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + const len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + let res = '' + let i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + const len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + let out = '' + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]] + } + return out +} + +function utf16leSlice (buf, start, end) { + const bytes = buf.slice(start, end) + let res = '' + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + const len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + const newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype) + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + let val = this[offset + --byteLength] + let mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const lo = first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24 + + const hi = this[++offset] + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + last * 2 ** 24 + + return BigInt(lo) + (BigInt(hi) << BigInt(32)) +}) + +Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const hi = first * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + const lo = this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last + + return (BigInt(hi) << BigInt(32)) + BigInt(lo) +}) + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let i = byteLength + let mul = 1 + let val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = this[offset + 4] + + this[offset + 5] * 2 ** 8 + + this[offset + 6] * 2 ** 16 + + (last << 24) // Overflow + + return (BigInt(val) << BigInt(32)) + + BigInt(first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24) +}) + +Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } + + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] + + return (BigInt(val) << BigInt(32)) + + BigInt(this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last) +}) + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let mul = 1 + let i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + let i = byteLength - 1 + let mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function wrtBigUInt64LE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + return offset +} + +function wrtBigUInt64BE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) + + let lo = Number(value & BigInt(0xffffffff)) + buf[offset + 7] = lo + lo = lo >> 8 + buf[offset + 6] = lo + lo = lo >> 8 + buf[offset + 5] = lo + lo = lo >> 8 + buf[offset + 4] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset + 3] = hi + hi = hi >> 8 + buf[offset + 2] = hi + hi = hi >> 8 + buf[offset + 1] = hi + hi = hi >> 8 + buf[offset] = hi + return offset + 8 +} + +Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = 0 + let mul = 1 + let sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + let i = byteLength - 1 + let mul = 1 + let sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + const len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + const code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } else if (typeof val === 'boolean') { + val = Number(val) + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + let i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + const bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + const len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// CUSTOM ERRORS +// ============= + +// Simplified versions from Node, changed for Buffer-only usage +const errors = {} +function E (sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor () { + super() + + Object.defineProperty(this, 'message', { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }) + + // Add the error code to the name to include it in the stack trace. + this.name = `${this.name} [${sym}]` + // Access the stack to generate the error message including the error code + // from the name. + this.stack // eslint-disable-line no-unused-expressions + // Reset the name to the actual name. + delete this.name + } + + get code () { + return sym + } + + set code (value) { + Object.defineProperty(this, 'code', { + configurable: true, + enumerable: true, + value, + writable: true + }) + } + + toString () { + return `${this.name} [${sym}]: ${this.message}` + } + } +} + +E('ERR_BUFFER_OUT_OF_BOUNDS', + function (name) { + if (name) { + return `${name} is outside of buffer bounds` + } + + return 'Attempt to access memory outside buffer bounds' + }, RangeError) +E('ERR_INVALID_ARG_TYPE', + function (name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}` + }, TypeError) +E('ERR_OUT_OF_RANGE', + function (str, range, input) { + let msg = `The value of "${str}" is out of range.` + let received = input + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)) + } else if (typeof input === 'bigint') { + received = String(input) + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received) + } + received += 'n' + } + msg += ` It must be ${range}. Received ${received}` + return msg + }, RangeError) + +function addNumericalSeparator (val) { + let res = '' + let i = val.length + const start = val[0] === '-' ? 1 : 0 + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}` + } + return `${val.slice(0, i)}${res}` +} + +// CHECK FUNCTIONS +// =============== + +function checkBounds (buf, offset, byteLength) { + validateNumber(offset, 'offset') + if (buf[offset] === undefined || buf[offset + byteLength] === undefined) { + boundsError(offset, buf.length - (byteLength + 1)) + } +} + +function checkIntBI (value, min, max, buf, offset, byteLength) { + if (value > max || value < min) { + const n = typeof min === 'bigint' ? 'n' : '' + let range + if (byteLength > 3) { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}` + } else { + range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` + + `${(byteLength + 1) * 8 - 1}${n}` + } + } else { + range = `>= ${min}${n} and <= ${max}${n}` + } + throw new errors.ERR_OUT_OF_RANGE('value', range, value) + } + checkBounds(buf, offset, byteLength) +} + +function validateNumber (value, name) { + if (typeof value !== 'number') { + throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value) + } +} + +function boundsError (value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type) + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value) + } + + if (length < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS() + } + + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', + `>= ${type ? 1 : 0} and <= ${length}`, + value) +} + +// HELPER FUNCTIONS +// ================ + +const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function utf8ToBytes (string, units) { + units = units || Infinity + let codePoint + const length = string.length + let leadSurrogate = null + const bytes = [] + + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + let c, hi, lo + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + let i + for (i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +const hexSliceLookupTable = (function () { + const alphabet = '0123456789abcdef' + const table = new Array(256) + for (let i = 0; i < 16; ++i) { + const i16 = i * 16 + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})() + +// Return not function with Error if BigInt not supported +function defineBigIntMethod (fn) { + return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn +} + +function BufferBigIntNotDefined () { + throw new Error('BigInt not supported') +} diff --git a/node_modules/buffer/package.json b/node_modules/buffer/package.json new file mode 100644 index 000000000..ca1ad9a70 --- /dev/null +++ b/node_modules/buffer/package.json @@ -0,0 +1,93 @@ +{ + "name": "buffer", + "description": "Node.js Buffer API, for the browser", + "version": "6.0.3", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/buffer/issues" + }, + "contributors": [ + "Romain Beauxis ", + "James Halliday " + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + }, + "devDependencies": { + "airtap": "^3.0.0", + "benchmark": "^2.1.4", + "browserify": "^17.0.0", + "concat-stream": "^2.0.0", + "hyperquest": "^2.1.3", + "is-buffer": "^2.0.5", + "is-nan": "^1.3.0", + "split": "^1.0.1", + "standard": "*", + "tape": "^5.0.1", + "through2": "^4.0.2", + "uglify-js": "^3.11.5" + }, + "homepage": "https://github.com/feross/buffer", + "jspm": { + "map": { + "./index.js": { + "node": "@node/buffer" + } + } + }, + "keywords": [ + "arraybuffer", + "browser", + "browserify", + "buffer", + "compatible", + "dataview", + "uint8array" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/buffer.git" + }, + "scripts": { + "perf": "browserify --debug perf/bracket-notation.js > perf/bundle.js && open perf/index.html", + "perf-node": "node perf/bracket-notation.js && node perf/concat.js && node perf/copy-big.js && node perf/copy.js && node perf/new-big.js && node perf/new.js && node perf/readDoubleBE.js && node perf/readFloatBE.js && node perf/readUInt32LE.js && node perf/slice.js && node perf/writeFloatBE.js", + "size": "browserify -r ./ | uglifyjs -c -m | gzip | wc -c", + "test": "standard && node ./bin/test.js", + "test-browser-old": "airtap -- test/*.js", + "test-browser-old-local": "airtap --local -- test/*.js", + "test-browser-new": "airtap -- test/*.js test/node/*.js", + "test-browser-new-local": "airtap --local -- test/*.js test/node/*.js", + "test-node": "tape test/*.js test/node/*.js", + "update-authors": "./bin/update-authors.sh" + }, + "standard": { + "ignore": [ + "test/node/**/*.js", + "test/common.js", + "test/_polyfill.js", + "perf/**/*.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/node_modules/chai/CODEOWNERS b/node_modules/chai/CODEOWNERS new file mode 100644 index 000000000..ea74b66ed --- /dev/null +++ b/node_modules/chai/CODEOWNERS @@ -0,0 +1 @@ +* @chaijs/chai diff --git a/node_modules/chai/CODE_OF_CONDUCT.md b/node_modules/chai/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..074addcc2 --- /dev/null +++ b/node_modules/chai/CODE_OF_CONDUCT.md @@ -0,0 +1,58 @@ +# Contributor Code of Conduct + +> Read in: [Español](http://contributor-covenant.org/version/1/3/0/es/) | +[Français](http://contributor-covenant.org/version/1/3/0/fr/) | +[Italiano](http://contributor-covenant.org/version/1/3/0/it/) | +[Magyar](http://contributor-covenant.org/version/1/3/0/hu/) | +[Polskie](http://contributor-covenant.org/version/1/3/0/pl/) | +[Português](http://contributor-covenant.org/version/1/3/0/pt/) | +[Português do Brasil](http://contributor-covenant.org/version/1/3/0/pt_br/) + +As contributors and maintainers of this project, and in the interest of +fostering an open and welcoming community, we pledge to respect all people who +contribute through reporting issues, posting feature requests, updating +documentation, submitting pull requests or patches, and other activities. + +We are committed to making participation in this project a harassment-free +experience for everyone, regardless of level of experience, gender, gender +identity and expression, sexual orientation, disability, personal appearance, +body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, such as physical or electronic + addresses, without explicit permission +* Other unethical or unprofessional conduct + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +By adopting this Code of Conduct, project maintainers commit themselves to +fairly and consistently applying these principles to every aspect of managing +this project. Project maintainers who do not follow or enforce the Code of +Conduct may be permanently removed from the project team. + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting a project maintainer at chaijs@keithcirkel.co.uk. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. Maintainers are +obligated to maintain confidentiality with regard to the reporter of an +incident. + + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 1.3.0, available at +[http://contributor-covenant.org/version/1/3/0/][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/3/0/ diff --git a/node_modules/chai/CONTRIBUTING.md b/node_modules/chai/CONTRIBUTING.md new file mode 100644 index 000000000..88072d45e --- /dev/null +++ b/node_modules/chai/CONTRIBUTING.md @@ -0,0 +1,218 @@ +# Chai Contribution Guidelines + +We like to encourage you to contribute to the Chai.js repository. This should be as easy as possible for you but there are a few things to consider when contributing. The following guidelines for contribution should be followed if you want to submit a pull request or open an issue. + +Following these guidelines helps to communicate that you respect the time of the developers managing and developing this open source project. In return, they should reciprocate that respect in addressing your issue or assessing patches and features. + +#### Table of Contents + +- [TLDR;](#tldr) +- [Contributing](#contributing) + - [Bug Reports](#bugs) + - [Feature Requests](#features) + - [Pull Requests](#pull-requests) +- [Releasing](#releasing) +- [Support](#support) + - [Resources](#resources) + - [Core Contributors](#contributors) + + +## TLDR; + +- Creating an Issue or Pull Request requires a [GitHub](http://github.com) account. +- Issue reports should be **clear**, **concise** and **reproducible**. Check to see if your issue has already been resolved in the [master]() branch or already reported in Chai's [GitHub Issue Tracker](https://github.com/chaijs/chai/issues). +- Pull Requests must adhere to strict [coding style guidelines](https://github.com/chaijs/chai/wiki/Chai-Coding-Style-Guide). +- In general, avoid submitting PRs for new Assertions without asking core contributors first. More than likely it would be better implemented as a plugin. +- Additional support is available via the [Google Group](http://groups.google.com/group/chaijs) or on irc.freenode.net#chaijs. +- **IMPORTANT**: By submitting a patch, you agree to allow the project owner to license your work under the same license as that used by the project. + + + + +## Contributing + +The issue tracker is the preferred channel for [bug reports](#bugs), +[feature requests](#features) and [submitting pull +requests](#pull-requests), but please respect the following restrictions: + +* Please **do not** use the issue tracker for personal support requests (use + [Google Group](https://groups.google.com/forum/#!forum/chaijs) or IRC). +* Please **do not** derail or troll issues. Keep the discussion on topic and + respect the opinions of others + + +### Bug Reports + +A bug is a **demonstrable problem** that is caused by the code in the repository. + +Guidelines for bug reports: + +1. **Use the GitHub issue search** — check if the issue has already been reported. +2. **Check if the issue has been fixed** — try to reproduce it using the latest `master` or development branch in the repository. +3. **Isolate the problem** — create a test case to demonstrate your issue. Provide either a repo, gist, or code sample to demonstrate you problem. + +A good bug report shouldn't leave others needing to chase you up for more information. Please try to be as detailed as possible in your report. What is your environment? What steps will reproduce the issue? What browser(s) and/or Node.js versions experience the problem? What would you expect to be the outcome? All these details will help people to fix any potential bugs. + +Example: + +> Short and descriptive example bug report title +> +> A summary of the issue and the browser/OS environment in which it occurs. If suitable, include the steps required to reproduce the bug. +> +> 1. This is the first step +> 2. This is the second step +> 3. Further steps, etc. +> +> `` - a link to the reduced test case OR +> ```js +> expect(a).to.equal('a'); +> // code sample +> ``` +> +> Any other information you want to share that is relevant to the issue being reported. This might include the lines of code that you have identified as causing the bug, and potential solutions (and your opinions on their merits). + + +### Feature Requests + +Feature requests are welcome. But take a moment to find out whether your idea fits with the scope and aims of the project. It's up to *you* to make a strong case to convince the project's developers of the merits of this feature. Please provide as much detail and context as possible. + +Furthermore, since Chai.js has a [robust plugin API](http://chaijs.com/guide/plugins/), we encourage you to publish **new Assertions** as plugins. If your feature is an enhancement to an **existing Assertion**, please propose your changes as an issue prior to opening a pull request. If the core Chai.js contributors feel your plugin would be better suited as a core assertion, they will invite you to open a PR in [chaijs/chai](https://github.com/chaijs/chai). + + +### Pull Requests + +- PRs for new core-assertions are advised against. +- PRs for core-assertion bug fixes are always welcome. +- PRs for enhancing the interfaces are always welcome. +- PRs that increase test coverage are always welcome. +- PRs are scrutinized for coding-style. + +Good pull requests - patches, improvements, new features - are a fantastic help. They should remain focused in scope and avoid containing unrelated commits. + +**Please ask first** before embarking on any significant pull request (e.g. implementing features, refactoring code), otherwise you risk spending a lot of time working on something that the project's developers might not want to merge into the project. + +Please adhere to the coding conventions used throughout a project (indentation, accurate comments, etc.) and any other requirements (such as test coverage). Please review the [Chai.js Coding Style Guide](https://github.com/chaijs/chai/wiki/Chai-Coding-Style-Guide). + +Follow this process if you'd like your work considered for inclusion in the project: + +1. [Fork](http://help.github.com/fork-a-repo/) the project, clone your fork, and configure the remotes: + +```bash +# Clone your fork of the repo into the current directory +git clone https://github.com// +# Navigate to the newly cloned directory +cd +# Assign the original repo to a remote called "upstream" +git remote add upstream https://github.com// +``` + +2. If you cloned a while ago, get the latest changes from upstream: + +```bash +git checkout +git pull upstream +``` + +3. Create a new topic branch (off the main project development branch) to contain your feature, change, or fix: + +```bash +git checkout -b +``` + +4. Commit your changes in logical chunks. Use Git's [interactive rebase](https://help.github.com/articles/interactive-rebase) feature to tidy up your commits before making them public. + +5. Run you code to make sure it works. If you're still having problems please try to run `make clean` and then test your code again. + +```bash +npm test +# when finished running tests... +git checkout chai.js +``` + +6. Locally merge (or rebase) the upstream development branch into your topic branch: + +```bash +git pull [--rebase] upstream +``` + +7. Push your topic branch up to your fork: + +```bash +git push origin +``` + +8. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/) with a clear title and description. + +**IMPORTANT**: By submitting a patch, you agree to allow the project owner to license your work under the same license as that used by the project. + + +## Releasing + +Releases can be **prepared** by anyone with access to the code. + +Simply run `make release-major`, `make release-minor`, or `make-release-patch` +and it will automatically do the following: + + - Build chai.js + - Bump the version numbers across the project + - Make a commit within git + +All you need to do is push the commit up and make a pull request, one of the core contributors will merge it and publish a release. + +### Publishing a Release + +Anyone who is a core contributor (see the [Core Contributors Heading in the Readme](https://github.com/chaijs/chai#core-contributors)) can publish a release: + +1. Go to the [Releases page on Github](https://github.com/chaijs/chai/releases) +2. Hit "Draft a new release" (if you can't see this, you're not a core contributor!) +3. Write human-friendly Release Notes based on changelog. + - The release title is "x.x.x / YYYY-MM-DD" (where x.x.x is the version number) + - If breaking changes, write migration tutorial(s) and reasoning. + - Callouts for community contributions (PRs) with links to PR and contributing user. + - Callouts for other fixes made by core contributors with links to issue. +4. Hit "Save Draft" and get other core contributors to check your work, or alternatively hit "Publish release" +5. That's it! + + +## Support + + +### Resources + +For most of the documentation you are going to want to visit [ChaiJS.com](http://chaijs.com). + +- [Getting Started Guide](http://chaijs.com/guide/) +- [API Reference](http://chaijs.com/api/) +- [Plugins](http://chaijs.com/plugins/) + +Alternatively, the [wiki](https://github.com/chaijs/chai/wiki) might be what you are looking for. + +- [Chai Coding Style Guide](https://github.com/chaijs/chai/wiki/Chai-Coding-Style-Guide) +- [Third-party Resources](https://github.com/chaijs/chai/wiki/Third-Party-Resources) + +Or finally, you may find a core-contributor or like-minded developer in any of our support channels. + +- IRC: irc.freenode.org #chaijs +- [Mailing List / Google Group](https://groups.google.com/forum/#!forum/chaijs) + + +### Core Contributors + +Feel free to reach out to any of the core-contributors with you questions or concerns. We will do our best to respond in a timely manner. + +- Jake Luer + - GH: [@logicalparadox](https://github.com/logicalparadox) + - TW: [@jakeluer](http://twitter.com/jakeluer) + - IRC: logicalparadox +- Veselin Todorov + - GH: [@vesln](https://github.com/vesln/) + - TW: [@vesln](http://twitter.com/vesln) + - IRC: vesln +- Keith Cirkel + - GH: [@keithamus](https://github.com/keithamus) + - TW: [@keithamus](http://twitter.com/keithamus) + - IRC: keithamus +- Lucas Fernandes da Costa + - GH: [@lucasfcosta](https://github.com/lucasfcosta) + - TW: [@lfernandescosta](https://twitter.com/lfernandescosta) + - IRC: lucasfcosta diff --git a/node_modules/chai/History.md b/node_modules/chai/History.md new file mode 100644 index 000000000..5b5ae7b02 --- /dev/null +++ b/node_modules/chai/History.md @@ -0,0 +1,1059 @@ +### Note + +As of 3.0.0, the History.md file has been deprecated. [Please refer to the full +commit logs available on GitHub](https://github.com/chaijs/chai/commits). + +--- + +2.3.0 / 2015-04-26 +================== + + * Merge pull request #423 from ehntoo/patch-1 + * Merge pull request #422 from ljharb/fix_descriptor_tests + * Fix a small bug in the .null assertion docs + * Use a regex to account for property ordering issues across engines. + * Add `make test-firefox` + * Merge pull request #417 from astorije/astorije/minimalist-typo + * Remove trailing whitespaces + * Fix super minor typo in an example + * Merge pull request #408 from ljharb/enumerableProperty + * Add `ownPropertyDescriptor` assertion. + +2.2.0 / 2015-03-26 +================== + + * Merge pull request #405 from chaijs/deep-escape-doc-tweaks + * Tweak documentation on `.deep` flag. + * Merge pull request #402 from umireon/escaping-dot-should-be-taken + * Documentation of escaping in `.deep` flag. + * take regular expression apart + * Feature: backslash-escaping in `.deep.property` + * Escaping dot should be taken in deep property + +2.1.2 / 2015-03-15 +================== + + * Merge pull request #396 from chaijs/add-keith-cirkel-contributing-md + * Add Keith Cirkel to CONTRIBUTING.md + * Merge pull request #395 from cjqed/386-assert-operator-no-eval + * No longer using eval on assert operator #386 + * Merge pull request #389 from chaijs/update-git-summary + * Update `git summary` in README + +2.1.1 / 2015-03-04 +================== + + * Merge pull request #385 from eldritch-fossicker/master + * updates to reflect code style preference from @keithamus + * fix indexing into array with deep propery + * Merge pull request #382 from astorije/patch-2 + * Merge pull request #383 from gurdiga/config-doc-wording-improvement + * config.truncateThreshold docs: simpler wording + * Add missing docstring for showDiff argument of assert + * Merge pull request #381 from astorije/patch-1 + * Add a minor precision that empty asserts on strings too. + * Merge pull request #379 from dcneiner/should-primitive-fix + * Primitives now use valueOf in shouldGetter + +2.1.0 / 2015-02-23 +================== + + * Merge pull request #374 from jmm/v2.0.1 + * Increment version to 2.0.1. + * Merge pull request #365 from chaijs/fix-travis + * Fix travis.yml deploy + * Merge pull request #356 from Soviut/master + * documented fail methods for expect and should interfaces + * fail method added directly to expect + +2.0.0 / 2015-02-09 +================== + + * Merge pull request #361 from gregglind/b265-keys-object + * fix #359. Add `.keys(object)` + * Merge pull request #359 from gregglind/b359-unexpected-keys-sort + * Fix #359 keys() sorts input unexpectedly + * contrib: publish release strategy and travis npm creds #337 + * Merge pull request #357 from danilovaz/master + * Update copyright date + * Merge pull request #349 from toastynerd/add-which-chain-method + * add the which chain method as per issue #347 + * Merge pull request #333 from cmpolis/change-assertions + * more `by` cleanup + * cleaned out `.by` for #333 + * Merge pull request #335 from DingoEatingFuzz/expose-util + * Expose chai util through the chai object + * cleanup (per notes on pr #333) + * updated `change` to work w/ non-number values + tests + * Merge pull request #334 from hurrymaplelad/patch-1 + * Typo, the flag is called 'contains' with an 's' + * updated assertion interface with `change` (#330) + * added `change`,`increase`,`decrease` assertions (#330) + * assert tests for `change`,`increase`,`decrease` + * expect/should tests for `change`,`increase`,`decrease` + * Merge pull request #328 from lo1tuma/issue-327 + * Add includes and contains alias (fixes #327) + * Merge pull request #325 from chasenlehara/overwriteChainableMethodDocs + * Fix docs for overwriteChainableMethod parameters + * Merge pull request #317 from jasonkarns/patch-2 + * Merge pull request #318 from jasonkarns/patch-3 + * Merge pull request #316 from jasonkarns/patch-1 + * typos in docs + * minor docs typo + * update docs: getAllFlags -> transferFlags + * Merge pull request #313 from cjqed/254-expect-any-all + * Added the all and any flags for keys assertion, with all being the default behavior + * Merge pull request #312 from cjqed/291-assert-same-deep-members + * Changed public comment of sameDeepMemebers to be more clear + * Fixes issue #291, adds assert.sameDeepMembers + * Merge pull request #311 from cjqed/305-above-below-on-assert + * Merge pull request #308 from prodatakey/hasproperty + * Issue #305 fixed, added assert.isAbove and assert.isBelow + * Fix typo + * More unit tests for new utility functions + * Refactor common functionality, document, test + * Refactor if statement out + * Small unit test fix + * Handle array indexing terminating paths + * Merge pull request #309 from ericdouglas/iterableEqual-couting-once + * couting variables just once + * Fix properties with `undefined` value pass property assertion + * Merge pull request #306 from chaijs/revert-297-noopchainfunc + * Revert "Allows writing lint-friendly tests" + +1.10.0 / 2014-11-10 +================== + + * Merge pull request #297 from prodatakey/noopchainfunc + * Merge pull request #300 from julienw/299-fix-getMessage-test + * Fix #299: the test is defining global variables + * Add a couple more unit tests + * Add unit tests for chained terminating property asserts + * Revise documentation wording + * Add docs for function style NOOP asserts + * Make the NOOP function a shared constant + * Merge pull request #298 from dasilvacontin/negativeZeroLogging + * why not more assertions + * added test for inspecting `-0` + * a more readable/simple condition statement, as pointed out by @keithamus + * added check for logging negative zero + * Change test to not trigger argument bug + * Allows writing lint-friendly tests + * readme: update contributors for 1.9.2 + +1.9.2 / 2014-09-29 +================== + + * Merge pull request #268 from charlierudolph/cr-lazyMessages + * Merge pull request #269 from charlierudolph/cr-codeCleanup + * Merge pull request #277 from charlierudolph/fix-doc + * Merge pull request #279 from mohayonao/fix-closeTo + * Merge pull request #292 from boneskull/mocha + * resolves #255: upgrade mocha + * Merge pull request #289 from charlierudolph/cr-dryUpCode + * Dry up code + * Merge pull request #275 from DrRataplan/master + * assert: .closeTo() verify value's type before assertion + * Rewrite pretty-printing HTML elements to prevent throwing internal errors Fixes errors occuring when using a non-native DOM implementation + * Fix assert documentation + * Remove unused argument + * Allow messages to be functions + * Merge pull request #267 from shinnn/master + * Use SVG badge + * Merge pull request #264 from cjthompson/keys_diff + * Show diff for keys assertion + +1.9.1 / 2014-03-19 +================== + + * deps update + * util: [getActual] select actual logic now allows undefined for actual. Closes #183 + * docs: [config] make public, express param type + * Merge pull request #251 from romario333/threshold3 + * Fix issue #166 - configurable threshold in objDisplay. + * Move configuration options to config.js. + * Merge pull request #233 from Empeeric/master + * Merge pull request #244 from leider/fix_for_contains + * Merge pull request #247 from didoarellano/typo-fixes + * Fix typos + * Merge pull request #245 from lfac-pt/patch-1 + * Update `exports.version` to 1.9.0 + * aborting loop on finding + * declaring variable only once + * additional test finds incomplete implementation + * simplified code + * fixing #239 (without changing chai.js) + * ssfi as it should be + * Merge pull request #228 from duncanbeevers/deep_members + * Deep equality check for collection membership + +1.9.0 / 2014-01-29 +================== + + * docs: add contributing.md #238 + * assert: .throws() returns thrown error. Closes #185 + * Merge pull request #232 from laconbass/assert-throws + * assert: .fail() parameter mismatch. Closes #206 + * Merge branch 'karma-fixes' + * Add karma phantomjs launcher + * Use latest karma and sauce launcher + * Karma tweaks + * Merge pull request #230 from jkroso/include + * Merge pull request #237 from chaijs/coverage + * Add coverage to npmignore + * Remove lib-cov from test-travisci dependents + * Remove the not longer needed lcov reporter + * Test coverage with istanbul + * Remove jscoverage + * Remove coveralls + * Merge pull request #226 from duncanbeevers/add_has + * Avoid error instantiation if possible on assert.throws + * Merge pull request #231 from duncanbeevers/update_copyright_year + * Update Copyright notices to 2014 + * handle negation correctly + * add failing test case + * support `{a:1,b:2}.should.include({a:1})` + * Merge pull request #224 from vbardales/master + * Add `has` to language chains + * Merge pull request #219 from demands/overwrite_chainable + * return error on throw method to chain on error properties, possibly different from message + * util: store chainable behavior in a __methods object on ctx + * util: code style fix + * util: add overwriteChainableMethod utility (for #215) + * Merge pull request #217 from demands/test_cleanup + * test: make it possible to run utilities tests with --watch + * makefile: change location of karma-runner bin script + * Merge pull request #202 from andreineculau/patch-2 + * test: add tests for throwing custom errors + * Merge pull request #201 from andreineculau/patch-1 + * test: updated for the new assertion errors + * core: improve message for assertion errors (throw assertion) + +1.8.1 / 2013-10-10 +================== + + * pkg: update deep-eql version + +1.8.0 / 2013-09-18 +================== + + * test: [sauce] add a few more browsers + * Merge branch 'refactor/deep-equal' + * util: remove embedded deep equal utility + * util: replace embedded deep equal with external module + * Merge branch 'feature/karma' + * docs: add sauce badge to readme [ci skip] + * test: [sauce] use karma@canary to prevent timeouts + * travis: only run on node 0.10 + * test: [karma] use karma phantomjs runner + * Merge pull request #181 from tricknotes/fix-highlight + * Fix highlight for example code + +1.7.2 / 2013-06-27 +================== + + * coverage: add coveralls badge + * test: [coveralls] add coveralls api integration. testing travis-ci integration + * Merge branch 'master' of github.com:chaijs/chai + * Merge branch 'feature/bower' + * Merge pull request #180 from tricknotes/modify-method-title + * Merge pull request #179 from tricknotes/highlight-code-example + * Modify method title to include argument name + * Fix to highlight code example + * bower: granular ignores + +1.7.1 / 2013-06-24 +================== + + * Merge branch 'feature/bower'. #175 + * bower: add json file + * build: browser + +1.7.0 / 2013-06-17 +================== + + * error: remove internal assertion error constructor + * core: [assertion-error] replace internal assertion error with dep + * deps: add chaijs/assertion-error@1.0.0 + * docs: fix typo in source file. #174 + * Merge pull request #174 from piecioshka/master + * typo + * Merge branch 'master' of github.com:chaijs/chai + * pkg: lock mocha/mocha-phantomjs versions (for now) + * Merge pull request #173 from chaijs/inspect-fix + * Fix `utils.inspect` with custom object-returning inspect()s. + * Merge pull request #171 from Bartvds/master + * replaced tabs with 2 spaces + * added assert.notOk() + * Merge pull request #169 from katsgeorgeek/topics/master + * Fix comparison objects. + +1.6.1 / 2013-06-05 +================== + + * Merge pull request #168 from katsgeorgeek/topics/master + * Add test for different RegExp flags. + * Add test for regexp comparison. + * Downgrade mocha version for fix running Phantom tests. + * Fix comparison equality of two regexps. + * Merge pull request #161 from brandonpayton/master + * Fix documented name for assert interfaces isDefined method + +1.6.0 / 2013-04-29 +================== + + * build: browser + * assert: [(not)include] throw on incompatible haystack. Closes #142 + * assert: [notInclude] add assert.notInclude. Closes #158 + * browser build + * makefile: force browser build on browser-test + * makefile: use component for browser build + * core: [assertions] remove extraneous comments + * Merge branch 'master' of github.com:chaijs/chai + * test: [assert] deep equal ordering + * Merge pull request #153 from NickHeiner/array-assertions + * giving members a no-flag assertion + * Code review comments - changing syntax + * Code review comments + * Adding members and memberEquals assertions for checking for subsets and set equality. Implements chaijs/chai#148. + * Merge pull request #140 from RubenVerborgh/function-prototype + * Restore the `call` and `apply` methods of Function when adding a chainable method. + * readme: 2013 + * notes: migration notes for deep equal changes + * test: for ever err() there must be a passing version + +1.5.0 / 2013-02-03 +================== + + * docs: add Release Notes for non-gitlog summary of changes. + * lib: update copyright to 2013 + * Merge branch 'refactor/travis' + * makefile: remove test-component for full test run + * pkg: script test now runs make test so travis will test browser + * browser: build + * tests: refactor some tests to support new objDisplay output + * test: [bootstrap] normalize boostrap across all test scenarios + * assertions: refactor some assertions to use objDisplay instead of inspect + * util: [objDisplay] normalize output of functions + * makefile: refactor for full build scenarios + * component: fix build bug where missing util:type file + * assertions: [throw] code cleanup + * Merge branch 'refactor/typeDetection' + * browser: build + * makefile: chai.js is .PHONY so it builds every time + * test: [expect] add arguments type detection test + * core/assertions: [type] (a/an) refactor to use type detection utility + * util: add cross-browser type detection utility + * Merge branch 'feature/component' + * browser: build + * component: add component.json file + * makefile: refactor for fine grain control of testing scenarios + * test: add mochaPhantomJS support and component test file + * deps: add component and mocha-phantomjs for browser testing + * ignore: update ignore files for component support + * travis: run for all branches + * Merge branch 'feature/showDiff' + * test: [Assertion] configruable showDiff flag. Closes #132 + * lib: [Assertion] add configurable showDiff flag. #132 + * Merge branch 'feature/saucelabs' + * Merge branch 'master' into feature/saucelabs + * browser: build + * support: add mocha cloud runner, client, and html test page + * test: [saucelabs] add auth placeholder + * deps: add mocha-cloud + * Merge pull request #136 from whatthejeff/message_fix + * Merge pull request #138 from timnew/master + * Fix issue #137, test message existence by using message!=null rather than using message + * Fixed backwards negation messages. + * Merge pull request #133 from RubenVerborgh/throw + * Functions throwing strings can reliably be tested. + * Merge pull request #131 from RubenVerborgh/proto + * Cache whether __proto__ is supported. + * Use __proto__ if available. + * Determine the property names to exclude beforehand. + * Merge pull request #126 from RubenVerborgh/eqls + * Add alias eqls for eql. + * Use inherited enumerable properties in deep equality comparison. + * Show inherited properties when inspecting an object. + * Add new getProperties and getEnumerableProperties utils. + * showDiff: force true for equal and eql + +1.4.2 / 2012-12-21 +================== + + * browser build: (object diff support when used with mocha) #106 + * test: [display] array test for mocha object diff + * browser: no longer need different AssertionError constructor + +1.4.1 / 2012-12-21 +================== + + * showDiff: force diff for equal and eql. #106 + * test: [expect] type null. #122 + * Merge pull request #115 from eshao/fix-assert-Throw + * FIX: assert.Throw checks error type/message + * TST: assert.Throw should check error type/message + +1.4.0 / 2012-11-29 +================== + + * pre-release browser build + * clean up index.js to not check for cov, revert package.json to use index.js + * convert tests to use new bootstrap + * refactor testing bootstrap + * use spaces (not tabs). Clean up #114 + * Merge pull request #114 from trantorLiu/master + * Add most() (alias: lte) and least() (alias: gte) to the API with new chainers "at" and "of". + * Change `main` to ./lib/chai. Fixes #28. + * Merge pull request #104 from connec/deep_equals_circular_references_ + * Merge pull request #109 from nnarhinen/patch-1 + * Check for 'actual' type + * Added support for circular references when checking deep (in)equality. + +1.3.0 / 2012-10-01 +================== + + * browser build w/ folio >= 0.3.4. Closes #99 + * add back buffer test for deep equal + * do not write flags to assertion.prototype + * remove buffer test from expect + * browser build + * improve documentation of custom error messages + * Merge branch 'master' of git://github.com/Liffft/chai into Liffft-master + * browser build + * improved buffer deep equal checking + * mocha is npm test command + * Cleaning up the js style… + * expect tests now include message pass-through + * packaging up browser-side changes… + * Increasing Throws error message verbosity + * Should syntax: piping message through + * Make globalShould test work in browser too. + * Add a setter for `Object.prototype.should`. Closes #86. + +1.2.0 / 2012-08-07 +================== + + * Merge branch 'feature/errmsg' + * browser build + * comment updates for utilities + * tweak objDislay to only kick in if object inspection is too long + * Merge branch 'master' into feature/errmsg + * add display sample for error message refactor + * first draft of error message refactor. #93 + * add `closeTo` assertion to `assert` interface. Closes #89. + * update folio build for better require.js handling. Closes #85 + * Merge pull request #92 from paulmillr/topics/add-dom-checks + * Add check for DOM objects. + * browser build + * Merge branch 'master' of github.com:chaijs/chai + * bug - getActual not defaulting to assertion subject + * Merge pull request #88 from pwnall/master + * Don't inspect() assertion arguments if the assertion passes. + +1.1.1 / 2012-07-09 +================== + + * improve commonjs support on browser build + * Merge pull request #83 from tkazec/equals + * Document .equals + * Add .equals as an alias of .equal + * remove unused browser prefix/suffix + * Merge branch 'feature/folio-build' + * browser build + * using folio to compile + * clean up makefile + * early folio 0.3.x support + +1.1.0 / 2012-06-26 +================== + + * browser build + * Disable "Assertion.includeStack is false" test in IE. + * Use `utils.getName` for all function inspections. + * Merge pull request #80 from kilianc/closeTo + * fixes #79 + * browser build + * expand docs to indicate change of subject for chaining. Closes #78 + * add `that` chain noop + * Merge branch 'bug/74' + * comments on how to property use `length` as chain. Closes #74 + * tests for length as chainable property. #74 + * add support for `length` as chainable prop/method. + * Merge branch 'bug/77' + * tests for getPathValue when working with nested arrays. Closes #77 + * add getPathValue support for nested arrays + * browser build + * fix bug for missing browser utils + * compile tool aware of new folder layout + * Merge branch 'refactor/1dot1' + * move core assertions to own file and refactor all using utils + * rearrange folder structure + +1.0.4 / 2012-06-03 +================== + + * Merge pull request #68 from fizker/itself + * Added itself chain. + * simplify error inspections for cross browser compatibility + * fix safari `addChainableMethod` errors. Closes #69 + +1.0.3 / 2012-05-27 +================== + + * Point Travis badge to the right place. + * Make error message for eql/deep.equal more clear. + * Fix .not.deep.equal. + * contributors list + +1.0.2 / 2012-05-26 +================== + + * Merge pull request #67 from chaijs/chaining-and-flags + * Browser build. + * Use `addChainableMethod` to get away from `__proto__` manipulation. + * New `addChainableMethod` utility. + * Replace `getAllFlags` with `transferFlags` utility. + * browser build + * test - get all flags + * utility - get all flags + * Add .mailmap to .npmignore. + * Add a .mailmap file to fix my name in shortlogs. + +1.0.1 / 2012-05-18 +================== + + * browser build + * Fixing "an" vs. "a" grammar in type assertions. + * Uniformize `assert` interface inline docs. + * Don't use `instanceof` for `assert.isArray`. + * Add `deep` flag for equality and property value. + * Merge pull request #64 from chaijs/assertion-docs + * Uniformize assertion inline docs. + * Add npm-debug.log to .gitignore. + * no reserved words as actuals. #62 + +1.0.0 / 2012-05-15 +================== + + * readme cleanup + * browser build + * utility comments + * removed docs + * update to package.json + * docs build + * comments / docs updates + * plugins app cleanup + * Merge pull request #61 from joliss/doc + * Fix and improve documentation of assert.equal and friends + * browser build + * doc checkpoint - texture + * Update chai-jquery link + * Use defined return value of Assertion extension functions + * Update utility docs + +1.0.0-rc3 / 2012-05-09 +================== + + * Merge branch 'feature/rc3' + * docs update + * browser build + * assert test conformity for minor refactor api + * assert minor refactor + * update util tests for new add/overwrite prop/method format + * added chai.Assertion.add/overwrite prop/method for plugin toolbox + * add/overwrite prop/method don't make assumptions about context + * doc test suite + * docs don't need coverage + * refactor all simple chains into one forEach loop, for clean documentation + * updated npm ignore + * remove old docs + * docs checkpoint - guide styled + * Merge pull request #59 from joliss/doc + * Document how to run the test suite + * don't need to rebuild docs to view + * dep update + * docs checkpoint - api section + * comment updates for docs + * new doc site checkpoint - plugin directory! + * Merge pull request #57 from kossnocorp/patch-1 + * Fix typo: devDependancies → devDependencies + * Using message flag in `getMessage` util instead of old `msg` property. + * Adding self to package.json contributors. + * `getMessage` shouldn't choke on null/omitted messages. + * `return this` not necessary in example. + * `return this` not necessary in example. + * Sinon–Chai has a dash + * updated plugins list for docs + +1.0.0-rc2 / 2012-05-06 +================== + + * Merge branch 'feature/test-cov' + * browser build + * missing assert tests for ownProperty + * appropriate assert equivalent for expect.to.have.property(key, val) + * reset AssertionError to include full stack + * test for plugin utilities + * overwrite Property and Method now ensure chain + * version notes in readme + +1.0.0-rc1 / 2012-05-04 +================== + + * browser build (rc1) + * assert match/notMatch tests + * assert interface - notMatch, ownProperty, notOwnProperty, ownPropertyVal, ownPropertyNotVal + * cleaner should interface export. + * added chai.Assertion.prototype._obj (getter) for quick access to object flag + * moved almostEqual / almostDeepEqual to stats plugin + * added mocha.opts + * Add test for `utils.addMethod` + * Fix a typo + * Add test for `utils.overwriteMethod` + * Fix a typo + * Browser build + * Add undefined assertion + * Add null assertion + * Fix an issue with `mocha --watch` + * travis no longer tests on node 0.4.x + * removing unnecissary carbon dep + * Merge branch 'feature/plugins-app' + * docs build + * templates for docs express app for plugin directory + * express app for plugin and static serving + * added web server deps + * Merge pull request #54 from josher19/master + * Remove old test.assert code + * Use util.inspect instead of inspect for deepAlmostEqual and almostEqual + * browser build + * Added almostEqual and deepAlmostEqual to assert test suite. + * bug - context determinants for utils + * dec=0 means rounding, so assert.deepAlmostEqual({pi: 3.1416}, {pi: 3}, 0) is true + * wrong travis link + * readme updates for version information + * travis tests 0.5.x branch as well + * [bug] util `addProperty` not correctly exporting + * read me version notes + * browser build 1.0.0alpha1 + * not using reserved words in internal assertions. #52 + * version tick + * clean up redundant tests + * Merge branch 'refs/heads/0.6.x' + * update version tag in package 1.0.0alpha1 + * browser build + * added utility tests to browser specs + * beginning utility testing + * updated utility comments + * utility - overwriteMethod + * utility - overwriteProperty + * utility - addMethod + * utility - addProperty + * missing ; + * contributors list update + * Merge branch 'refs/heads/0.6.x-docs' into 0.6.x + * Added guide link to docs. WIP + * Include/contain are now both properties and methods + * Add an alias annotation + * Remove usless function wrapper + * Fix a typo + * A/an are now both properties and methods + * [docs] new site homepage layout / color checkpoint + * Ignore IE-specific error properties. + * Fixing order of error message test. + * New cross-browser `getName` util. + * Fixing up `AssertionError` inheritance. + * backup docs + * Add doctypes + * [bug] was still using `constructor.name` in `throw` assertion + * [bug] flag Object.create(null) instead of new Object + * [test] browser build + * [refactor] all usage of Assertion.prototype.assert now uses template tags and flags + * [refactor] remove Assertion.prototype.inspect for testable object inspection + * [refactor] object to test is now stored in flag, with ssfi and custom message + * [bug] flag util - don't return on `set` + * [docs] comments for getMessage utility + * [feature] getMessage + * [feature] testing utilities + * [refactor] flag doesn't require `call` + * Make order of source files well-defined + * Added support for throw(errorInstance). + * Use a foolproof method of grabbing an error's name. + * Removed constructor.name check from throw. + * disabled stackTrack configuration tests until api is stable again + * first version of line displayed error for node js (unstable) + * refactor core Assertion to use flag utility for negation + * added flag utility + * tests for assert interface negatives. Closed #42 + * added assertion negatives that were missing. #42 + * Support for expected and actual parameters in assert-style error object + * chai as promised - readme + * Added assert.fail. Closes #40 + * better error message for assert.operator. Closes #39 + * [refactor] Assertion#property to use getPathValue property + * added getPathValue utility helper + * removed todo about browser build + * version notes + * version bumb 0.6.0 + * browser build + * [refactor] browser compile function to replace with `require('./error')' with 'require('./browser/error')' + * [feature] browser uses different error.js + * [refactor] error without chai.fail + * Assertion & interfaces use new utils helper export + * [refactor] primary export for new plugin util usage + * added util index.js helper + * added 2012 to copyright headers + * Added DeepEqual assertions + +0.5.3 / 2012-04-21 +================== + + * Merge branch 'refs/heads/jgonera-oldbrowsers' + * browser build + * fixed reserved names for old browsers in interface/assert + * fixed reserved names for old browsers in interface/should + * fixed: chai.js no longer contains fail() + * fixed reserved names for old browsers in Assertion + * Merge pull request #49 from joliss/build-order + * Make order of source files well-defined + * Merge pull request #43 from zzen/patch-1 + * Support for expected and actual parameters in assert-style error object + * chai as promised - readme + +0.5.2 / 2012-03-21 +================== + + * browser build + * Merge branch 'feature/assert-fail' + * Added assert.fail. Closes #40 + * Merge branch 'bug/operator-msg' + * better error message for assert.operator. Closes #39 + * version notes + +0.5.1 / 2012-03-14 +================== + + * chai.fail no longer exists + * Merge branch 'feature/assertdefined' + * Added asset#isDefined. Closes #37. + * dev docs update for Assertion#assert + +0.5.0 / 2012-03-07 +================== + + * [bug] on inspect of reg on n 0.4.12 + * Merge branch 'bug/33-throws' + * Merge pull request #35 from logicalparadox/empty-object + * browser build + * updated #throw docs + * Assertion#throw `should` tests updated + * Assertion#throw `expect` tests + * Should interface supports multiple throw parameters + * Update Assertion#throw to support strings and type checks. + * Add more tests for `empty` in `should`. + * Add more tests for `empty` in `expect`. + * Merge branch 'master' into empty-object + * don't switch act/exp + * Merge pull request #34 from logicalparadox/assert-operator + * Update the compiled verison. + * Add `assert.operator`. + * Notes on messages. #22 + * browser build + * have been test + * below tests + * Merge branch 'feature/actexp' + * browser build + * remove unnecessary fail export + * full support for actual/expected where relevant + * Assertion.assert support expected value + * clean up error + * Update the compiled version. + * Add object & sane arguments support to `Assertion#empty`. + +0.4.2 / 2012-02-28 +================== + + * fix for `process` not available in browser when used via browserify. Closes #28 + * Merge pull request #31 from joliss/doc + * Document that "should" works in browsers other than IE + * Merge pull request #30 from logicalparadox/assert-tests + * Update the browser version of chai. + * Update `assert.doesNotThrow` test in order to check the use case when type is a string. + * Add test for `assert.ifError`. + * Falsey -> falsy. + * Full coverage for `assert.throws` and `assert.doesNotThrow`. + * Add test for `assert.doesNotThrow`. + * Add test for `assert.throws`. + * Add test for `assert.length`. + * Add test for `assert.include`. + * Add test for `assert.isBoolean`. + * Fix the implementation of `assert.isNumber`. + * Add test for `assert.isNumber`. + * Add test for `assert.isString`. + * Add test for `assert.isArray`. + * Add test for `assert.isUndefined`. + * Add test for `assert.isNotNull`. + * Fix `assert.isNotNull` implementation. + * Fix `assert.isNull` implementation. + * Add test for `assert.isNull`. + * Add test for `assert.notDeepEqual`. + * Add test for `assert.deepEqual`. + * Add test for `assert.notStrictEqual`. + * Add test for `assert.strictEqual`. + * Add test for `assert.notEqual`. + +0.4.1 / 2012-02-26 +================== + + * Merge pull request #27 from logicalparadox/type-fix + * Update the browser version. + * Add should tests for type checks. + * Add function type check test. + * Add more type checks tests. + * Add test for `new Number` type check. + * Fix type of actual checks. + +0.4.0 / 2012-02-25 +================== + + * docs and readme for upcoming 0.4.0 + * docs generated + * putting coverage and tests for docs in docs/out/support + * make docs + * makefile copy necessary resources for tests in docs + * rename configuration test + * Merge pull request #21 from logicalparadox/close-to + * Update the browser version. + * Update `closeTo()` docs. + * Add `Assertion.closeTo()` method. + * Add `.closeTo()` should test. + * Add `.closeTo()` expect test. + * Merge pull request #20 from logicalparadox/satisfy + * Update the browser version. + * `..` -> `()` in `.satisfy()` should test. + * Update example for `.satisfy()`. + * Update the compiled browser version. + * Add `Assertion.satisfy()` method. + * Add `.satisfy()` should test. + * Add `.satisfy()` expect test. + * Merge pull request #19 from logicalparadox/respond-to + * Update the compiled browser version. + * Add `respondTo` Assertion. + * Add `respondTo` should test. + * Add `respondTo` expect test. + * Merge branch 'feature/coverage' + * mocha coverage support + * doc contributors + * README contributors + +0.3.4 / 2012-02-23 +================== + + * inline comment typos for #15 + * Merge branch 'refs/heads/jeffbski-configErrorStackCompat' + * includeStack documentation for all interfaces + * suite name more generic + * Update test to be compatible with browsers that do not support err.stack + * udpated compiled chai.js and added to browser tests + * Allow inclusion of stack trace for Assert error messages to be configurable + * docs sharing buttons + * sinon-chai link + * doc updates + * read me updates include plugins + +0.3.3 / 2012-02-12 +================== + + * Merge pull request #14 from jfirebaugh/configurable_properties + * Make Assertion.prototype properties configurable + +0.3.2 / 2012-02-10 +================== + + * codex version + * docs + * docs cleanup + +0.3.1 / 2012-02-07 +================== + + * node 0.4.x compat + +0.3.0 / 2012-02-07 +================== + + * Merge branch 'feature/03x' + * browser build + * remove html/json/headers testign + * regex error.message testing + * tests for using plugins + * Merge pull request #11 from domenic/master + * Make `chai.use` a no-op if the function has already been used. + +0.2.4 / 2012-02-02 +================== + + * added in past tense switch for `been` + +0.2.3 / 2012-02-01 +================== + + * try that again + +0.2.2 / 2012-02-01 +================== + + * added `been` (past of `be`) alias + +0.2.1 / 2012-01-29 +================== + + * added Throw, with a capital T, as an alias to `throw` (#7) + +0.2.0 / 2012-01-26 +================== + + * update gitignore for vim *.swp + * Merge branch 'feature/plugins' + * browser build + * interfaces now work with use + * simple .use function. See #9. + * readme notice on browser compat + +0.1.7 / 2012-01-25 +================== + + * added assert tests to browser test runner + * browser update + * `should` interface patch for primitives support in FF + * fix isObject() Thanks @milewise + * travis only on branch `master` + * add instanceof alias `instanceOf`. #6 + * some tests for assert module + +0.1.6 / 2012-01-02 +================== + + * commenting for assert interface + * updated codex dep + +0.1.5 / 2012-01-02 +================== + + * browser tests pass + * type in should.not.equal + * test for should (not) exist + * added should.exist and should.not.exist + * browser uses tdd + * convert tests to tdd + +0.1.4 / 2011-12-26 +================== + + * browser lib update for new assert interface compatiblitiy + * inspect typos + * added strict equal + negatives and ifError + * interface assert had doesNotThrow + * added should tests to browser + * new expect empty tests + * should test browser compat + * Fix typo for instanceof docs. Closes #3 [ci skip] + +0.1.3 / 2011-12-18 +================== + + * much cleaner reporting string on error. + +0.1.2 / 2011-12-18 +================== + + * [docs] for upcoming 0.1.2 + * browser version built with pre/suffix … all tests passing + * make / compile now use prefix/suffix correctly + * code clean + * prefix/suffix to wrap browser output to prevent conflicts with other `require` methods. + * Merge branch 'feature/should4xcompatibility' + * compile for browser tests.. all pass + * added header/status/html/json + * throw tests + * should.throw & should.not.throw shortcuts + * improved `throw` type detection and messaging + * contain is now `include` … keys modifier is now `contain` + * removed object() test + * removed #respondTo + * Merge branch 'bug/2' + * replaced __defineGetter__ with defineProperty for all uses + * [docs] change mp tracking code + * docs site updated with assert (TDD) interface + * updated doc comments for assert interface + +0.1.1 / 2011-12-16 +================== + + * docs ready for upcoming 0.1.1 + * readme image fixed [ci skip] + * more readme tweaks [ci skip] + * réadmet image fixed [ci skip] + * documentation + * codex locked in version 0.0.5 + * more comments to assertions for docs + * assertions fully commented, browser library updated + * adding codex as doc dependancy + * prepping for docs + * assertion component completely commented for documentation + * added exist test + * var expect outside of browser if check + * added keywords to package.json + +0.1.0 / 2011-12-15 +================== + + * failing on purpose successful .. back to normal + * testing travis failure + * assert#arguments getter + * readme typo + * updated README + * added travis and npmignore + * copyright notices … think i got them all + * moved expect interface to own file for consistency + * assert ui deepEqual + * browser tests expect (all working) + * browser version built + * chai.fail (should ui) + * expect tests browser compatible + * tests for should and expect (all pass) + * moved fail to primary export + * should compatibility testing + * within, greaterThan, object, keys, + * Aliases + * Assertion#property now correctly works with negate and undefined values + * error message language matches should + * Assertion#respondTo + * Assertion now uses inspect util + * git ignore node modules + * should is exported + * AssertionError __proto__ from Error.prototype + * add should interface for should.js compatibility + * moved eql to until folder and added inspect from (joyent/node) + * added mocha for testing + * browser build for current api + * multiple .property assertions + * added deep equal from node + +0.0.2 / 2011-12-07 +================== + + * cleaner output on error + * improved exists detection + * package remnant artifact + * empty deep equal + * test browser build + * assertion cleanup + * client compile script + * makefile + * most of the basic assertions + * allow no parameters to assertion error + * name change + * assertion error instance + * main exports: assert() & expect() + * initialize diff --git a/node_modules/chai/LICENSE b/node_modules/chai/LICENSE new file mode 100644 index 000000000..eedbe238a --- /dev/null +++ b/node_modules/chai/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Chai.js Assertion Library + +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/node_modules/chai/README.md b/node_modules/chai/README.md new file mode 100644 index 000000000..242497189 --- /dev/null +++ b/node_modules/chai/README.md @@ -0,0 +1,154 @@ +

+ + ChaiJS + +
+ chai +

+ +

+ Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework. +

+ +

+ + downloads:? + + + node:? + +
+ + Join the Slack chat + + + Join the Gitter chat + + + OpenCollective Backers + +

+ +For more information or to download plugins, view the [documentation](http://chaijs.com). + +## What is Chai? + +Chai is an _assertion library_, similar to Node's built-in `assert`. It makes testing much easier by giving you lots of assertions you can run against your code. + +## Installation + +### Node.js + +`chai` is available on [npm](http://npmjs.org). To install it, type: + + $ npm install --save-dev chai + +### Browsers + +You can also use it within the browser; install via npm and use the `chai.js` file found within the download. For example: + +```html + +``` + +## Usage + +Import the library in your code, and then pick one of the styles you'd like to use - either `assert`, `expect` or `should`: + +```js +import { assert } from 'chai'; // Using Assert style +import { expect } from 'chai'; // Using Expect style +import { should } from 'chai'; // Using Should style +``` + +### Register the chai testing style globally + +```js +import 'chai/register-assert'; // Using Assert style +import 'chai/register-expect'; // Using Expect style +import 'chai/register-should'; // Using Should style +``` + +### Import assertion styles as local variables + +```js +import { assert } from 'chai'; // Using Assert style +import { expect } from 'chai'; // Using Expect style +import { should } from 'chai'; // Using Should style +should(); // Modifies `Object.prototype` + +import { expect, use } from 'chai'; // Creates local variables `expect` and `use`; useful for plugin use +``` + +### Usage with Mocha + +```bash +mocha spec.js --require chai/register-assert.js # Using Assert style +mocha spec.js --require chai/register-expect.js # Using Expect style +mocha spec.js --require chai/register-should.js # Using Should style +``` + +[Read more about these styles in our docs](http://chaijs.com/guide/styles/). + +## Plugins + +Chai offers a robust Plugin architecture for extending Chai's assertions and interfaces. + +- Need a plugin? View the [official plugin list](http://chaijs.com/plugins). +- Want to build a plugin? Read the [plugin api documentation](http://chaijs.com/guide/plugins/). +- Have a plugin and want it listed? Simply add the following keywords to your package.json: + - `chai-plugin` + - `browser` if your plugin works in the browser as well as Node.js + - `browser-only` if your plugin does not work with Node.js + +### Related Projects + +- [chaijs / chai-docs](https://github.com/chaijs/chai-docs): The chaijs.com website source code. +- [chaijs / assertion-error](https://github.com/chaijs/assertion-error): Custom `Error` constructor thrown upon an assertion failing. +- [chaijs / deep-eql](https://github.com/chaijs/deep-eql): Improved deep equality testing for Node.js and the browser. +- [chaijs / check-error](https://github.com/chaijs/check-error): Error comparison and information related utility for Node.js and the browser. +- [chaijs / loupe](https://github.com/chaijs/loupe): Inspect utility for Node.js and browsers. +- [chaijs / pathval](https://github.com/chaijs/pathval): Object value retrieval given a string path. + +### Contributing + +Thank you very much for considering to contribute! + +Please make sure you follow our [Code Of Conduct](https://github.com/chaijs/chai/blob/master/CODE_OF_CONDUCT.md) and we also strongly recommend reading our [Contributing Guide](https://github.com/chaijs/chai/blob/master/CONTRIBUTING.md). + +Here are a few issues other contributors frequently ran into when opening pull requests: + +- Please do not commit changes to the `chai.js` build. We do it once per release. +- Before pushing your commits, please make sure you [rebase](https://github.com/chaijs/chai/blob/master/CONTRIBUTING.md#pull-requests) them. + +### Contributors + +Please see the full +[Contributors Graph](https://github.com/chaijs/chai/graphs/contributors) for our +list of contributors. + +### Core Contributors + +Feel free to reach out to any of the core contributors with your questions or +concerns. We will do our best to respond in a timely manner. + +[![Jake Luer](https://avatars3.githubusercontent.com/u/58988?v=3&s=50)](https://github.com/logicalparadox) +[![Veselin Todorov](https://avatars3.githubusercontent.com/u/330048?v=3&s=50)](https://github.com/vesln) +[![Keith Cirkel](https://avatars3.githubusercontent.com/u/118266?v=3&s=50)](https://github.com/keithamus) +[![Lucas Fernandes da Costa](https://avatars3.githubusercontent.com/u/6868147?v=3&s=50)](https://github.com/lucasfcosta) +[![Grant Snodgrass](https://avatars3.githubusercontent.com/u/17260989?v=3&s=50)](https://github.com/meeber) diff --git a/node_modules/chai/ReleaseNotes.md b/node_modules/chai/ReleaseNotes.md new file mode 100644 index 000000000..2a80d5cec --- /dev/null +++ b/node_modules/chai/ReleaseNotes.md @@ -0,0 +1,737 @@ +# Release Notes + +## Note + +As of 3.0.0, the ReleaseNotes.md file has been deprecated. [Please refer to the release notes available on Github](https://github.com/chaijs/chai/releases). Or +[the release notes on the chaijs.com website](https://chaijs.com/releases). + +--- + +## 2.3.0 / 2015-04-26 + +Added `ownPropertyDescriptor` assertion: + +```js +expect('test').to.have.ownPropertyDescriptor('length'); +expect('test').to.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 4 }); +expect('test').not.to.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 3 }); +expect('test').ownPropertyDescriptor('length').to.have.property('enumerable', false); +expect('test').ownPropertyDescriptor('length').to.have.keys('value'); +``` + +### Community Contributions + +#### Code Features & Fixes + + * [#408](https://github.com/chaijs/chai/pull/408) Add `ownPropertyDescriptor` + assertion. + By [@ljharb](https://github.com/ljharb) + * [#422](https://github.com/chaijs/chai/pull/422) Improve ownPropertyDescriptor + tests. + By [@ljharb](https://github.com/ljharb) + +#### Documentation fixes + + * [#417](https://github.com/chaijs/chai/pull/417) Fix documentation typo + By [@astorije](https://github.com/astorije) + * [#423](https://github.com/chaijs/chai/pull/423) Fix inconsistency in docs. + By [@ehntoo](https://github.com/ehntoo) + + +## 2.2.0 / 2015-03-26 + +Deep property strings can now be escaped using `\\` - for example: + +```js +var deepCss = { '.link': { '[target]': 42 }}; +expect(deepCss).to.have.deep.property('\\.link.\\[target\\]', 42) +``` + +### Community Contributions + +#### Code Features & Fixes + + * [#402](https://github.com/chaijs/chai/pull/402) Allow escaping of deep + property keys. + By [@umireon](https://github.com/umireon) + +#### Documentation fixes + + * [#405](https://github.com/chaijs/chai/pull/405) Tweak documentation around + deep property escaping. + By [@keithamus](https://github.com/keithamus) + + +## 2.1.2 / 2015-03-15 + +A minor bug fix. No new features. + +### Community Contributions + +#### Code Features & Fixes + + * [#395](https://github.com/chaijs/chai/pull/395) Fix eval-related bugs with + assert.operator ([#386](https://github.com/chaijs/chai/pull/386)). + By [@cjqed](https://github.com/cjqed) + +## 2.1.1 / 2015-03-04 + +Two minor bugfixes. No new features. + +### Community Contributions + +#### Code Features & Fixes + + * [#385](https://github.com/chaijs/chai/pull/385) Fix a bug (also described in + [#387](https://github.com/chaijs/chai/pull/385)) where `deep.property` would not work with single + key names. By [@eldritch-fossicker](https://github.com/eldritch-fossicker) + * [#379](https://github.com/chaijs/chai/pull/379) Fix bug where tools which overwrite + primitive prototypes, such as Babel or core-js would fail. + By [@dcneiner](https://github.com/dcneiner) + +#### Documentation fixes + + * [#382](https://github.com/chaijs/chai/pull/382) Add doc for showDiff argument in assert. + By [@astorije](https://github.com/astorije) + * [#383](https://github.com/chaijs/chai/pull/383) Improve wording for truncateTreshold docs + By [@gurdiga](https://github.com/gurdiga) + * [#381](https://github.com/chaijs/chai/pull/381) Improve wording for assert.empty docs + By [@astorije](https://github.com/astorije) + +## 2.1.0 / 2015-02-23 + +Small release; fixes an issue where the Chai lib was incorrectly reporting the +version number. + +Adds new `should.fail()` and `expect.fail()` methods, which are convinience +methods to throw Assertion Errors. + +### Community Contributions + +#### Code Features & Fixes + + * [#356](https://github.com/chaijs/chai/pull/356) Add should.fail(), expect.fail(). By [@Soviut](https://github.com/Soviut) + * [#374](https://github.com/chaijs/chai/pull/374) Increment version. By [@jmm](https://github.com/jmm) + +## 2.0.0 / 2015-02-09 + +Unfortunately with 1.10.0 - compatibility broke with older versions because of +the `addChainableNoop`. This change has been reverted. + +Any plugins using `addChainableNoop` should cease to do so. + +Any developers wishing for this behaviour can use [dirty-chai](https://www.npmjs.com/package/dirty-chai) +by [@joshperry](https://github.com/joshperry) + +### Community Contributions + +#### Code Features & Fixes + + * [#361](https://github.com/chaijs/chai/pull/361) `.keys()` now accepts Objects, extracting keys from them. By [@gregglind](https://github.com/gregglind) + * [#359](https://github.com/chaijs/chai/pull/359) `.keys()` no longer mutates passed arrays. By [@gregglind](https://github.com/gregglind) + * [#349](https://github.com/chaijs/chai/pull/349) Add a new chainable keyword - `.which`. By [@toastynerd](https://github.com/toastynerd) + * [#333](https://github.com/chaijs/chai/pull/333) Add `.change`, `.increase` and `.decrease` assertions. By [@cmpolis](https://github.com/cmpolis) + * [#335](https://github.com/chaijs/chai/pull/335) `chai.util` is now exposed [@DingoEatingFuzz](https://github.com/DingoEatingFuzz) + * [#328](https://github.com/chaijs/chai/pull/328) Add `.includes` and `.contains` aliases (for `.include` and `.contain`). By [@lo1tuma](https://github.com/lo1tuma) + * [#313](https://github.com/chaijs/chai/pull/313) Add `.any.keys()` and `.all.keys()` qualifiers. By [@cjqed](https://github.com/cjqed) + * [#312](https://github.com/chaijs/chai/pull/312) Add `assert.sameDeepMembers()`. By [@cjqed](https://github.com/cjqed) + * [#311](https://github.com/chaijs/chai/pull/311) Add `assert.isAbove()` and `assert.isBelow()`. By [@cjqed](https://github.com/cjqed) + * [#308](https://github.com/chaijs/chai/pull/308) `property` and `deep.property` now pass if a value is set to `undefined`. By [@prodatakey](https://github.com/prodatakey) + * [#309](https://github.com/chaijs/chai/pull/309) optimize deep equal in Arrays. By [@ericdouglas](https://github.com/ericdouglas) + * [#306](https://github.com/chaijs/chai/pull/306) revert #297 - allowing lint-friendly tests. By [@keithamus](https://github.com/keithamus) + +#### Documentation fixes + + * [#357](https://github.com/chaijs/chai/pull/357) Copyright year updated in docs. By [@danilovaz](https://github.com/danilovaz) + * [#325](https://github.com/chaijs/chai/pull/325) Fix documentation for overwriteChainableMethod. By [@chasenlehara](https://github.com/chasenlehara) + * [#334](https://github.com/chaijs/chai/pull/334) Typo fix. By [@hurrymaplelad](https://github.com/hurrymaplelad) + * [#317](https://github.com/chaijs/chai/pull/317) Typo fix. By [@jasonkarns](https://github.com/jasonkarns) + * [#318](https://github.com/chaijs/chai/pull/318) Typo fix. By [@jasonkarns](https://github.com/jasonkarns) + * [#316](https://github.com/chaijs/chai/pull/316) Typo fix. By [@jasonkarns](https://github.com/jasonkarns) + + +## 1.10.0 / 2014-11-10 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required +- **Plugin Developers:** + - Review `addChainableNoop` notes below. +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Noop Function for Terminating Assertion Properties + +The following assertions can now also be used in the function-call form: + +* ok +* true +* false +* null +* undefined +* exist +* empty +* arguments +* Arguments + +The above list of assertions are property getters that assert immediately on +access. Because of that, they were written to be used by terminating the assertion +chain with a property access. + +```js +expect(true).to.be.true; +foo.should.be.ok; +``` + +This syntax is definitely aesthetically pleasing but, if you are linting your +test code, your linter will complain with an error something like "Expected an +assignment or function call and instead saw an expression." Since the linter +doesn't know about the property getter it assumes this line has no side-effects, +and throws a warning in case you made a mistake. + +Squelching these errors is not a good solution as test code is getting to be +just as important as, if not more than, production code. Catching syntactical +errors in tests using static analysis is a great tool to help make sure that your +tests are well-defined and free of typos. + +A better option was to provide a function-call form for these assertions so that +the code's intent is more clear and the linters stop complaining about something +looking off. This form is added in addition to the existing property access form +and does not impact existing test code. + +```js +expect(true).to.be.true(); +foo.should.be.ok(); +``` + +These forms can also be mixed in any way, these are all functionally identical: + +```js +expect(true).to.be.true.and.not.false(); +expect(true).to.be.true().and.not.false; +expect(true).to.be.true.and.not.false; +``` + +#### Plugin Authors + +If you would like to provide this function-call form for your terminating assertion +properties, there is a new function to register these types of asserts. Instead +of using `addProperty` to register terminating assertions, simply use `addChainableNoop` +instead; the arguments to both are identical. The latter will make the assertion +available in both the attribute and function-call forms and should have no impact +on existing users of your plugin. + +### Community Contributions + +- [#297](https://github.com/chaijs/chai/pull/297) Allow writing lint-friendly tests. [@joshperry](https://github.com/joshperry) +- [#298](https://github.com/chaijs/chai/pull/298) Add check for logging `-0`. [@dasilvacontin](https://github.com/dasilvacontin) +- [#300](https://github.com/chaijs/chai/pull/300) Fix #299: the test is defining global variables [@julienw](https://github.com/julienw) + +Thank you to all who took time to contribute! + +## 1.9.2 / 2014-09-29 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required +- **Plugin Developers:** + - No changes required +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Community Contributions + +- [#264](https://github.com/chaijs/chai/pull/264) Show diff for keys assertions [@cjthompson](https://github.com/cjthompson) +- [#267](https://github.com/chaijs/chai/pull/267) Use SVG badges [@shinnn](https://github.com/shinnn) +- [#268](https://github.com/chaijs/chai/pull/268) Allow messages to be functions (sinon-compat) [@charlierudolph](https://github.com/charlierudolph) +- [#269](https://github.com/chaijs/chai/pull/269) Remove unused argument for #lengthOf [@charlierudolph](https://github.com/charlierudolph) +- [#275](https://github.com/chaijs/chai/pull/275) Rewrite pretty-printing HTML elements to prevent throwing internal errors [@DrRataplan](https://github.com/DrRataplan) +- [#277](https://github.com/chaijs/chai/pull/277) Fix assert documentation for #sameMembers [@charlierudolph](https://github.com/charlierudolph) +- [#279](https://github.com/chaijs/chai/pull/279) closeTo should check value's type before assertion [@mohayonao](https://github.com/mohayonao) +- [#289](https://github.com/chaijs/chai/pull/289) satisfy is called twice [@charlierudolph](https://github.com/charlierudolph) +- [#292](https://github.com/chaijs/chai/pull/292) resolve conflicts with node-webkit and global usage [@boneskull](https://github.com/boneskull) + +Thank you to all who took time to contribute! + +## 1.9.1 / 2014-03-19 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - Migrate configuration options to new interface. (see notes) +- **Plugin Developers:** + - No changes required +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Configuration + +There have been requests for changes and additions to the configuration mechanisms +and their impact in the Chai architecture. As such, we have decoupled the +configuration from the `Assertion` constructor. This not only allows for centralized +configuration, but will allow us to shift the responsibility from the `Assertion` +constructor to the `assert` interface in future releases. + +These changes have been implemented in a non-breaking way, but a depretiation +warning will be presented to users until they migrate. The old config method will +be removed in either `v1.11.0` or `v2.0.0`, whichever comes first. + +#### Quick Migration + +```js +// change this: +chai.Assertion.includeStack = true; +chai.Assertion.showDiff = false; + +// ... to this: +chai.config.includeStack = true; +chai.config.showDiff = false; +``` + +#### All Config Options + +##### config.includeStack + +- **@param** _{Boolean}_ +- **@default** `false` + +User configurable property, influences whether stack trace is included in +Assertion error message. Default of `false` suppresses stack trace in the error +message. + +##### config.showDiff + +- **@param** _{Boolean}_ +- **@default** `true` + +User configurable property, influences whether or not the `showDiff` flag +should be included in the thrown AssertionErrors. `false` will always be `false`; +`true` will be true when the assertion has requested a diff be shown. + +##### config.truncateThreshold **(NEW)** + +- **@param** _{Number}_ +- **@default** `40` + +User configurable property, sets length threshold for actual and expected values +in assertion errors. If this threshold is exceeded, the value is truncated. + +Set it to zero if you want to disable truncating altogether. + +```js +chai.config.truncateThreshold = 0; // disable truncating +``` + +### Community Contributions + +- [#228](https://github.com/chaijs/chai/pull/228) Deep equality check for memebers. [@duncanbeevers](https://github.com/duncanbeevers) +- [#247](https://github.com/chaijs/chai/pull/247) Proofreading. [@didorellano](https://github.com/didoarellano) +- [#244](https://github.com/chaijs/chai/pull/244) Fix `contain`/`include` 1.9.0 regression. [@leider](https://github.com/leider) +- [#233](https://github.com/chaijs/chai/pull/233) Improvements to `ssfi` for `assert` interface. [@refack](https://github.com/refack) +- [#251](https://github.com/chaijs/chai/pull/251) New config option: object display threshold. [@romario333](https://github.com/romario333) + +Thank you to all who took time to contribute! + +### Other Bug Fixes + +- [#183](https://github.com/chaijs/chai/issues/183) Allow `undefined` for actual. (internal api) +- Update Karam(+plugins)/Istanbul to most recent versions. + +## 1.9.0 / 2014-01-29 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required +- **Plugin Developers:** + - Review [#219](https://github.com/chaijs/chai/pull/219). +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Community Contributions + +- [#202](https://github.com/chaijs/chai/pull/201) Improve error message for .throw(). [@andreineculau](https://github.com/andreineculau) +- [#217](https://github.com/chaijs/chai/pull/217) Chai tests can be run with `--watch`. [@demands](https://github.com/demands) +- [#219](https://github.com/chaijs/chai/pull/219) Add overwriteChainableMethod utility. [@demands](https://github.com/demands) +- [#224](https://github.com/chaijs/chai/pull/224) Return error on throw method to chain on error properties. [@vbardales](https://github.com/vbardales) +- [#226](https://github.com/chaijs/chai/pull/226) Add `has` to language chains. [@duncanbeevers](https://github.com/duncanbeevers) +- [#230](https://github.com/chaijs/chai/pull/230) Support `{a:1,b:2}.should.include({a:1})` [@jkroso](https://github.com/jkroso) +- [#231](https://github.com/chaijs/chai/pull/231) Update Copyright notices to 2014 [@duncanbeevers](https://github.com/duncanbeevers) +- [#232](https://github.com/chaijs/chai/pull/232) Avoid error instantiation if possible on assert.throws. [@laconbass](https://github.com/laconbass) + +Thank you to all who took time to contribute! + +### Other Bug Fixes + +- [#225](https://github.com/chaijs/chai/pull/225) Improved AMD wrapper provided by upstream `component(1)`. +- [#185](https://github.com/chaijs/chai/issues/185) `assert.throws()` returns thrown error for further assertions. +- [#237](https://github.com/chaijs/chai/pull/237) Remove coveralls/jscoverage, include istanbul coverage report in travis test. +- Update Karma and Sauce runner versions for consistent CI results. No more karma@canary. + +## 1.8.1 / 2013-10-10 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - Refresh `node_modules` folder for updated dependencies. +- **Plugin Developers:** + - No changes required +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Browserify + +This is a small patch that updates the dependency tree so browserify users can install +chai. (Remove conditional requires) + +## 1.8.0 / 2013-09-18 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - See `deep.equal` notes. +- **Plugin Developers:** + - No changes required +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Deep Equals + +This version of Chai focused on a overhaul to the deep equal utility. The code for this +tool has been removed from the core lib and can now be found at: +[chai / deep-eql](https://github.com/chaijs/deep-eql). As stated in previous releases, +this is part of a larger initiative to provide transparency, independent testing, and coverage for +some of the more complicated internal tools. + +For the most part `.deep.equal` will behave the same as it has. However, in order to provide a +consistent ruleset across all types being tested, the following changes have been made and _might_ +require changes to your tests. + +**1.** Strict equality for non-traversable nodes according to [egal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). + +_Previously:_ Non-traversable equal via `===`. + +```js +expect(NaN).to.deep.equal(NaN); +expect(-0).to.not.deep.equal(+0); +``` + +**2.** Arguments are not Arrays (and all types must be equal): + +_Previously:_ Some crazy nonsense that led to empty arrays deep equaling empty objects deep equaling dates. + +```js +expect(arguments).to.not.deep.equal([]); +expect(Array.prototype.slice.call(arguments)).to.deep.equal([]); +``` + +- [#156](https://github.com/chaijs/chai/issues/156) Empty object is eql to empty array +- [#192](https://github.com/chaijs/chai/issues/192) empty object is eql to a Date object +- [#194](https://github.com/chaijs/chai/issues/194) refactor deep-equal utility + +### CI and Browser Testing + +Chai now runs the browser CI suite using [Karma](http://karma-runner.github.io/) directed at +[SauceLabs](https://saucelabs.com/). This means we get to know where our browser support stands... +and we get a cool badge: + +[![Selenium Test Status](https://saucelabs.com/browser-matrix/logicalparadox.svg)](https://saucelabs.com/u/logicalparadox) + +Look for the list of browsers/versions to expand over the coming releases. + +- [#195](https://github.com/chaijs/chai/issues/195) karma test framework + +## 1.7.2 / 2013-06-27 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required. +- **Plugin Developers:** + - No changes required +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Coverage Reporting + +Coverage reporting has always been available for core-developers but the data has never been published +for our end users. In our ongoing effort to improve accountability this data will now be published via +the [coveralls.io](https://coveralls.io/) service. A badge has been added to the README and the full report +can be viewed online at the [chai coveralls project](https://coveralls.io/r/chaijs/chai). Furthermore, PRs +will receive automated messages indicating how their PR impacts test coverage. This service is tied to TravisCI. + +### Other Fixes + +- [#175](https://github.com/chaijs/chai/issues/175) Add `bower.json`. (Fix ignore all) + +## 1.7.1 / 2013-06-24 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required. +- **Plugin Developers:** + - No changes required +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### Official Bower Support + +Support has been added for the Bower Package Manager ([bower.io])(http://bower.io/). Though +Chai could be installed via Bower in the past, this update adds official support via the `bower.json` +specification file. + +- [#175](https://github.com/chaijs/chai/issues/175) Add `bower.json`. + +## 1.7.0 / 2013-06-17 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required. +- **Plugin Developers:** + - Review AssertionError update notice. +- **Core Contributors:** + - Refresh `node_modules` folder for updated dependencies. + +### AssertionError Update Notice + +Chai now uses [chaijs/assertion-error](https://github.com/chaijs/assertion-error) instead an internal +constructor. This will allow for further iteration/experimentation of the AssertionError constructor +independant of Chai. Future plans include stack parsing for callsite support. + +This update constructor has a different constructor param signature that conforms more with the standard +`Error` object. If your plugin throws and `AssertionError` directly you will need to update your plugin +with the new signature. + +```js +var AssertionError = require('chai').AssertionError; + +/** + * previous + * + * @param {Object} options + */ + +throw new AssertionError({ + message: 'An assertion error occurred' + , actual: actual + , expect: expect + , startStackFunction: arguments.callee + , showStack: true +}); + +/** + * new + * + * @param {String} message + * @param {Object} options + * @param {Function} start stack function + */ + +throw new AssertionError('An assertion error occurred', { + actual: actual + , expect: expect + , showStack: true +}, arguments.callee); + +// other signatures +throw new AssertionError('An assertion error occurred'); +throw new AssertionError('An assertion error occurred', null, arguments.callee); +``` + +#### External Dependencies + +This is the first non-developement dependency for Chai. As Chai continues to evolve we will begin adding +more; the next will likely be improved type detection and deep equality. With Chai's userbase continually growing +there is an higher need for accountability and documentation. External dependencies will allow us to iterate and +test on features independent from our interfaces. + +Note: The browser packaged version `chai.js` will ALWAYS contain all dependencies needed to run Chai. + +### Community Contributions + +- [#169](https://github.com/chaijs/chai/pull/169) Fix deep equal comparison for Date/Regexp types. [@katsgeorgeek](https://github.com/katsgeorgeek) +- [#171](https://github.com/chaijs/chai/pull/171) Add `assert.notOk()`. [@Bartvds](https://github.com/Bartvds) +- [#173](https://github.com/chaijs/chai/pull/173) Fix `inspect` utility. [@domenic](https://github.com/domenic) + +Thank you to all who took the time to contribute! + +## 1.6.1 / 2013-06-05 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required. +- **Plugin Developers:** + - No changes required. +- **Core Contributors:** + - Refresh `node_modules` folder for updated developement dependencies. + +### Deep Equality + +Regular Expressions are now tested as part of all deep equality assertions. In previous versions +they silently passed for all scenarios. Thanks to [@katsgeorgeek](https://github.com/katsgeorgeek) for the contribution. + +### Community Contributions + +- [#161](https://github.com/chaijs/chai/pull/161) Fix documented name for assert interface's isDefined method. [@brandonpayton](https://github.com/brandonpayton) +- [#168](https://github.com/chaijs/chai/pull/168) Fix comparison equality of two regexps for when using deep equality. [@katsgeorgeek](https://github.com/katsgeorgeek) + +Thank you to all who took the time to contribute! + +### Additional Notes + +- Mocha has been locked at version `1.8.x` to ensure `mocha-phantomjs` compatibility. + +## 1.6.0 / 2013-04-29 + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - No changes required. +- **Plugin Developers:** + - No changes required. +- **Core Contributors:** + - Refresh `node_modules` folder for updated developement dependencies. + +### New Assertions + +#### Array Members Inclusion + +Asserts that the target is a superset of `set`, or that the target and `set` have the same members. +Order is not taken into account. Thanks to [@NickHeiner](https://github.com/NickHeiner) for the contribution. + +```js +// (expect/should) full set +expect([4, 2]).to.have.members([2, 4]); +expect([5, 2]).to.not.have.members([5, 2, 1]); + +// (expect/should) inclusion +expect([1, 2, 3]).to.include.members([3, 2]); +expect([1, 2, 3]).to.not.include.members([3, 2, 8]); + +// (assert) full set +assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members'); + +// (assert) inclusion +assert.includeMembers([ 1, 2, 3 ], [ 2, 1 ], 'include members'); + +``` + +#### Non-inclusion for Assert Interface + +Most `assert` functions have a negative version, like `instanceOf()` has a corresponding `notInstaceOf()`. +However `include()` did not have a corresponding `notInclude()`. This has been added. + +```js +assert.notInclude([ 1, 2, 3 ], 8); +assert.notInclude('foobar', 'baz'); +``` + +### Community Contributions + +- [#140](https://github.com/chaijs/chai/pull/140) Restore `call`/`apply` methods for plugin interface. [@RubenVerborgh](https://github.com/RubenVerborgh) +- [#148](https://github.com/chaijs/chai/issues/148)/[#153](https://github.com/chaijs/chai/pull/153) Add `members` and `include.members` assertions. [#NickHeiner](https://github.com/NickHeiner) + +Thank you to all who took time to contribute! + +### Other Bug Fixes + +- [#142](https://github.com/chaijs/chai/issues/142) `assert#include` will no longer silently pass on wrong-type haystack. +- [#158](https://github.com/chaijs/chai/issues/158) `assert#notInclude` has been added. +- Travis-CI now tests Node.js `v0.10.x`. Support for `v0.6.x` has been removed. `v0.8.x` is still tested as before. + +## 1.5.0 / 2013-02-03 + +### Migration Requirements + +The following changes are required if you are upgrading from the previous version: + +- **Users:** + - _Update [2013-02-04]:_ Some users may notice a small subset of deep equality assertions will no longer pass. This is the result of + [#120](https://github.com/chaijs/chai/issues/120), an improvement to our deep equality algorithm. Users will need to revise their assertions + to be more granular should this occur. Further information: [#139](https://github.com/chaijs/chai/issues/139). +- **Plugin Developers:** + - No changes required. +- **Core Contributors:** + - Refresh `node_modules` folder for updated developement dependencies. + +### Community Contributions + +- [#126](https://github.com/chaijs/chai/pull/126): Add `eqls` alias for `eql`. [@RubenVerborgh](https://github.com/RubenVerborgh) +- [#127](https://github.com/chaijs/chai/issues/127): Performance refactor for chainable methods. [@RubenVerborgh](https://github.com/RubenVerborgh) +- [#133](https://github.com/chaijs/chai/pull/133): Assertion `.throw` support for primitives. [@RubenVerborgh](https://github.com/RubenVerborgh) +- [#137](https://github.com/chaijs/chai/issues/137): Assertion `.throw` support for empty messages. [@timnew](https://github.com/timnew) +- [#136](https://github.com/chaijs/chai/pull/136): Fix backward negation messages when using `.above()` and `.below()`. [@whatthejeff](https://github.com/whatthejeff) + +Thank you to all who took time to contribute! + +### Other Bug Fixes + +- Improve type detection of `.a()`/`.an()` to work in cross-browser scenarios. +- [#116](https://github.com/chaijs/chai/issues/116): `.throw()` has cleaner display of errors when WebKit browsers. +- [#120](https://github.com/chaijs/chai/issues/120): `.eql()` now works to compare dom nodes in browsers. + + +### Usage Updates + +#### For Users + +**1. Component Support:** Chai now included the proper configuration to be installed as a +[component](https://github.com/component/component). Component users are encouraged to consult +[chaijs.com](http://chaijs.com) for the latest version number as using the master branch +does not gaurantee stability. + +```js +// relevant component.json + devDependencies: { + "chaijs/chai": "1.5.0" + } +``` + +Alternatively, bleeding-edge is available: + + $ component install chaijs/chai + +**2. Configurable showDiff:** Some test runners (such as [mocha](http://visionmedia.github.com/mocha/)) +include support for showing the diff of strings and objects when an equality error occurs. Chai has +already included support for this, however some users may not prefer this display behavior. To revert to +no diff display, the following configuration is available: + +```js +chai.Assertion.showDiff = false; // diff output disabled +chai.Assertion.showDiff = true; // default, diff output enabled +``` + +#### For Plugin Developers + +**1. New Utility - type**: The new utility `.type()` is available as a better implementation of `typeof` +that can be used cross-browser. It handles the inconsistencies of Array, `null`, and `undefined` detection. + +- **@param** _{Mixed}_ object to detect type of +- **@return** _{String}_ object type + +```js +chai.use(function (c, utils) { + // some examples + utils.type({}); // 'object' + utils.type(null); // `null' + utils.type(undefined); // `undefined` + utils.type([]); // `array` +}); +``` + +#### For Core Contributors + +**1. Browser Testing**: Browser testing of the `./chai.js` file is now available in the command line +via PhantomJS. `make test` and Travis-CI will now also rebuild and test `./chai.js`. Consequently, all +pull requests will now be browser tested in this way. + +_Note: Contributors opening pull requests should still NOT include the browser build._ + +**2. SauceLabs Testing**: Early SauceLab support has been enabled with the file `./support/mocha-cloud.js`. +Those interested in trying it out should create a free [Open Sauce](https://saucelabs.com/signup/plan) account +and include their credentials in `./test/auth/sauce.json`. diff --git a/node_modules/chai/chai.js b/node_modules/chai/chai.js new file mode 100644 index 000000000..ce5261dac --- /dev/null +++ b/node_modules/chai/chai.js @@ -0,0 +1,4051 @@ +var __defProp = Object.defineProperty; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; + +// (disabled):util +var require_util = __commonJS({ + "(disabled):util"() { + } +}); + +// lib/chai/utils/index.js +var utils_exports = {}; +__export(utils_exports, { + addChainableMethod: () => addChainableMethod, + addLengthGuard: () => addLengthGuard, + addMethod: () => addMethod, + addProperty: () => addProperty, + checkError: () => check_error_exports, + compareByInspect: () => compareByInspect, + eql: () => deep_eql_default, + expectTypes: () => expectTypes, + flag: () => flag, + getActual: () => getActual, + getMessage: () => getMessage2, + getName: () => getName, + getOperator: () => getOperator, + getOwnEnumerableProperties: () => getOwnEnumerableProperties, + getOwnEnumerablePropertySymbols: () => getOwnEnumerablePropertySymbols, + getPathInfo: () => getPathInfo, + hasProperty: () => hasProperty, + inspect: () => inspect2, + isNaN: () => isNaN2, + isNumeric: () => isNumeric, + isProxyEnabled: () => isProxyEnabled, + isRegExp: () => isRegExp2, + objDisplay: () => objDisplay, + overwriteChainableMethod: () => overwriteChainableMethod, + overwriteMethod: () => overwriteMethod, + overwriteProperty: () => overwriteProperty, + proxify: () => proxify, + test: () => test, + transferFlags: () => transferFlags, + type: () => type +}); + +// node_modules/check-error/index.js +var check_error_exports = {}; +__export(check_error_exports, { + compatibleConstructor: () => compatibleConstructor, + compatibleInstance: () => compatibleInstance, + compatibleMessage: () => compatibleMessage, + getConstructorName: () => getConstructorName, + getMessage: () => getMessage +}); +function isErrorInstance(obj) { + return obj instanceof Error || Object.prototype.toString.call(obj) === "[object Error]"; +} +__name(isErrorInstance, "isErrorInstance"); +function isRegExp(obj) { + return Object.prototype.toString.call(obj) === "[object RegExp]"; +} +__name(isRegExp, "isRegExp"); +function compatibleInstance(thrown, errorLike) { + return isErrorInstance(errorLike) && thrown === errorLike; +} +__name(compatibleInstance, "compatibleInstance"); +function compatibleConstructor(thrown, errorLike) { + if (isErrorInstance(errorLike)) { + return thrown.constructor === errorLike.constructor || thrown instanceof errorLike.constructor; + } else if ((typeof errorLike === "object" || typeof errorLike === "function") && errorLike.prototype) { + return thrown.constructor === errorLike || thrown instanceof errorLike; + } + return false; +} +__name(compatibleConstructor, "compatibleConstructor"); +function compatibleMessage(thrown, errMatcher) { + const comparisonString = typeof thrown === "string" ? thrown : thrown.message; + if (isRegExp(errMatcher)) { + return errMatcher.test(comparisonString); + } else if (typeof errMatcher === "string") { + return comparisonString.indexOf(errMatcher) !== -1; + } + return false; +} +__name(compatibleMessage, "compatibleMessage"); +function getConstructorName(errorLike) { + let constructorName = errorLike; + if (isErrorInstance(errorLike)) { + constructorName = errorLike.constructor.name; + } else if (typeof errorLike === "function") { + constructorName = errorLike.name; + if (constructorName === "") { + const newConstructorName = new errorLike().name; + constructorName = newConstructorName || constructorName; + } + } + return constructorName; +} +__name(getConstructorName, "getConstructorName"); +function getMessage(errorLike) { + let msg = ""; + if (errorLike && errorLike.message) { + msg = errorLike.message; + } else if (typeof errorLike === "string") { + msg = errorLike; + } + return msg; +} +__name(getMessage, "getMessage"); + +// lib/chai/utils/flag.js +function flag(obj, key, value) { + var flags = obj.__flags || (obj.__flags = /* @__PURE__ */ Object.create(null)); + if (arguments.length === 3) { + flags[key] = value; + } else { + return flags[key]; + } +} +__name(flag, "flag"); + +// lib/chai/utils/test.js +function test(obj, args) { + var negate = flag(obj, "negate"), expr = args[0]; + return negate ? !expr : expr; +} +__name(test, "test"); + +// lib/chai/utils/type-detect.js +function type(obj) { + if (typeof obj === "undefined") { + return "undefined"; + } + if (obj === null) { + return "null"; + } + const stringTag = obj[Symbol.toStringTag]; + if (typeof stringTag === "string") { + return stringTag; + } + const type3 = Object.prototype.toString.call(obj).slice(8, -1); + return type3; +} +__name(type, "type"); + +// node_modules/assertion-error/index.js +var canElideFrames = "captureStackTrace" in Error; +var AssertionError = class _AssertionError extends Error { + static { + __name(this, "AssertionError"); + } + message; + get name() { + return "AssertionError"; + } + get ok() { + return false; + } + constructor(message = "Unspecified AssertionError", props, ssf) { + super(message); + this.message = message; + if (canElideFrames) { + Error.captureStackTrace(this, ssf || _AssertionError); + } + for (const key in props) { + if (!(key in this)) { + this[key] = props[key]; + } + } + } + toJSON(stack) { + return { + ...this, + name: this.name, + message: this.message, + ok: false, + stack: stack !== false ? this.stack : void 0 + }; + } +}; + +// lib/chai/utils/expectTypes.js +function expectTypes(obj, types) { + var flagMsg = flag(obj, "message"); + var ssfi = flag(obj, "ssfi"); + flagMsg = flagMsg ? flagMsg + ": " : ""; + obj = flag(obj, "object"); + types = types.map(function(t) { + return t.toLowerCase(); + }); + types.sort(); + var str = types.map(function(t, index) { + var art = ~["a", "e", "i", "o", "u"].indexOf(t.charAt(0)) ? "an" : "a"; + var or = types.length > 1 && index === types.length - 1 ? "or " : ""; + return or + art + " " + t; + }).join(", "); + var objType = type(obj).toLowerCase(); + if (!types.some(function(expected) { + return objType === expected; + })) { + throw new AssertionError( + flagMsg + "object tested must be " + str + ", but " + objType + " given", + void 0, + ssfi + ); + } +} +__name(expectTypes, "expectTypes"); + +// lib/chai/utils/getActual.js +function getActual(obj, args) { + return args.length > 4 ? args[4] : obj._obj; +} +__name(getActual, "getActual"); + +// node_modules/loupe/lib/helpers.js +var ansiColors = { + bold: ["1", "22"], + dim: ["2", "22"], + italic: ["3", "23"], + underline: ["4", "24"], + // 5 & 6 are blinking + inverse: ["7", "27"], + hidden: ["8", "28"], + strike: ["9", "29"], + // 10-20 are fonts + // 21-29 are resets for 1-9 + black: ["30", "39"], + red: ["31", "39"], + green: ["32", "39"], + yellow: ["33", "39"], + blue: ["34", "39"], + magenta: ["35", "39"], + cyan: ["36", "39"], + white: ["37", "39"], + brightblack: ["30;1", "39"], + brightred: ["31;1", "39"], + brightgreen: ["32;1", "39"], + brightyellow: ["33;1", "39"], + brightblue: ["34;1", "39"], + brightmagenta: ["35;1", "39"], + brightcyan: ["36;1", "39"], + brightwhite: ["37;1", "39"], + grey: ["90", "39"] +}; +var styles = { + special: "cyan", + number: "yellow", + bigint: "yellow", + boolean: "yellow", + undefined: "grey", + null: "bold", + string: "green", + symbol: "green", + date: "magenta", + regexp: "red" +}; +var truncator = "\u2026"; +function colorise(value, styleType) { + const color = ansiColors[styles[styleType]] || ansiColors[styleType] || ""; + if (!color) { + return String(value); + } + return `\x1B[${color[0]}m${String(value)}\x1B[${color[1]}m`; +} +__name(colorise, "colorise"); +function normaliseOptions({ + showHidden = false, + depth = 2, + colors = false, + customInspect = true, + showProxy = false, + maxArrayLength = Infinity, + breakLength = Infinity, + seen = [], + // eslint-disable-next-line no-shadow + truncate: truncate2 = Infinity, + stylize = String +} = {}, inspect3) { + const options = { + showHidden: Boolean(showHidden), + depth: Number(depth), + colors: Boolean(colors), + customInspect: Boolean(customInspect), + showProxy: Boolean(showProxy), + maxArrayLength: Number(maxArrayLength), + breakLength: Number(breakLength), + truncate: Number(truncate2), + seen, + inspect: inspect3, + stylize + }; + if (options.colors) { + options.stylize = colorise; + } + return options; +} +__name(normaliseOptions, "normaliseOptions"); +function isHighSurrogate(char) { + return char >= "\uD800" && char <= "\uDBFF"; +} +__name(isHighSurrogate, "isHighSurrogate"); +function truncate(string, length, tail = truncator) { + string = String(string); + const tailLength = tail.length; + const stringLength = string.length; + if (tailLength > length && stringLength > tailLength) { + return tail; + } + if (stringLength > length && stringLength > tailLength) { + let end = length - tailLength; + if (end > 0 && isHighSurrogate(string[end - 1])) { + end = end - 1; + } + return `${string.slice(0, end)}${tail}`; + } + return string; +} +__name(truncate, "truncate"); +function inspectList(list, options, inspectItem, separator = ", ") { + inspectItem = inspectItem || options.inspect; + const size = list.length; + if (size === 0) + return ""; + const originalLength = options.truncate; + let output = ""; + let peek = ""; + let truncated = ""; + for (let i = 0; i < size; i += 1) { + const last = i + 1 === list.length; + const secondToLast = i + 2 === list.length; + truncated = `${truncator}(${list.length - i})`; + const value = list[i]; + options.truncate = originalLength - output.length - (last ? 0 : separator.length); + const string = peek || inspectItem(value, options) + (last ? "" : separator); + const nextLength = output.length + string.length; + const truncatedLength = nextLength + truncated.length; + if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) { + break; + } + if (!last && !secondToLast && truncatedLength > originalLength) { + break; + } + peek = last ? "" : inspectItem(list[i + 1], options) + (secondToLast ? "" : separator); + if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) { + break; + } + output += string; + if (!last && !secondToLast && nextLength + peek.length >= originalLength) { + truncated = `${truncator}(${list.length - i - 1})`; + break; + } + truncated = ""; + } + return `${output}${truncated}`; +} +__name(inspectList, "inspectList"); +function quoteComplexKey(key) { + if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) { + return key; + } + return JSON.stringify(key).replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); +} +__name(quoteComplexKey, "quoteComplexKey"); +function inspectProperty([key, value], options) { + options.truncate -= 2; + if (typeof key === "string") { + key = quoteComplexKey(key); + } else if (typeof key !== "number") { + key = `[${options.inspect(key, options)}]`; + } + options.truncate -= key.length; + value = options.inspect(value, options); + return `${key}: ${value}`; +} +__name(inspectProperty, "inspectProperty"); + +// node_modules/loupe/lib/array.js +function inspectArray(array, options) { + const nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) + return "[]"; + options.truncate -= 4; + const listContents = inspectList(array, options); + options.truncate -= listContents.length; + let propertyContents = ""; + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map((key) => [key, array[key]]), options, inspectProperty); + } + return `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ""} ]`; +} +__name(inspectArray, "inspectArray"); + +// node_modules/loupe/lib/typedarray.js +var getArrayName = /* @__PURE__ */ __name((array) => { + if (typeof Buffer === "function" && array instanceof Buffer) { + return "Buffer"; + } + if (array[Symbol.toStringTag]) { + return array[Symbol.toStringTag]; + } + return array.constructor.name; +}, "getArrayName"); +function inspectTypedArray(array, options) { + const name = getArrayName(array); + options.truncate -= name.length + 4; + const nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) + return `${name}[]`; + let output = ""; + for (let i = 0; i < array.length; i++) { + const string = `${options.stylize(truncate(array[i], options.truncate), "number")}${i === array.length - 1 ? "" : ", "}`; + options.truncate -= string.length; + if (array[i] !== array.length && options.truncate <= 3) { + output += `${truncator}(${array.length - array[i] + 1})`; + break; + } + output += string; + } + let propertyContents = ""; + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map((key) => [key, array[key]]), options, inspectProperty); + } + return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ""} ]`; +} +__name(inspectTypedArray, "inspectTypedArray"); + +// node_modules/loupe/lib/date.js +function inspectDate(dateObject, options) { + const stringRepresentation = dateObject.toJSON(); + if (stringRepresentation === null) { + return "Invalid Date"; + } + const split = stringRepresentation.split("T"); + const date = split[0]; + return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, "date"); +} +__name(inspectDate, "inspectDate"); + +// node_modules/loupe/lib/function.js +function inspectFunction(func, options) { + const functionType = func[Symbol.toStringTag] || "Function"; + const name = func.name; + if (!name) { + return options.stylize(`[${functionType}]`, "special"); + } + return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, "special"); +} +__name(inspectFunction, "inspectFunction"); + +// node_modules/loupe/lib/map.js +function inspectMapEntry([key, value], options) { + options.truncate -= 4; + key = options.inspect(key, options); + options.truncate -= key.length; + value = options.inspect(value, options); + return `${key} => ${value}`; +} +__name(inspectMapEntry, "inspectMapEntry"); +function mapToEntries(map) { + const entries = []; + map.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +} +__name(mapToEntries, "mapToEntries"); +function inspectMap(map, options) { + const size = map.size - 1; + if (size <= 0) { + return "Map{}"; + } + options.truncate -= 7; + return `Map{ ${inspectList(mapToEntries(map), options, inspectMapEntry)} }`; +} +__name(inspectMap, "inspectMap"); + +// node_modules/loupe/lib/number.js +var isNaN = Number.isNaN || ((i) => i !== i); +function inspectNumber(number, options) { + if (isNaN(number)) { + return options.stylize("NaN", "number"); + } + if (number === Infinity) { + return options.stylize("Infinity", "number"); + } + if (number === -Infinity) { + return options.stylize("-Infinity", "number"); + } + if (number === 0) { + return options.stylize(1 / number === Infinity ? "+0" : "-0", "number"); + } + return options.stylize(truncate(String(number), options.truncate), "number"); +} +__name(inspectNumber, "inspectNumber"); + +// node_modules/loupe/lib/bigint.js +function inspectBigInt(number, options) { + let nums = truncate(number.toString(), options.truncate - 1); + if (nums !== truncator) + nums += "n"; + return options.stylize(nums, "bigint"); +} +__name(inspectBigInt, "inspectBigInt"); + +// node_modules/loupe/lib/regexp.js +function inspectRegExp(value, options) { + const flags = value.toString().split("/")[2]; + const sourceLength = options.truncate - (2 + flags.length); + const source = value.source; + return options.stylize(`/${truncate(source, sourceLength)}/${flags}`, "regexp"); +} +__name(inspectRegExp, "inspectRegExp"); + +// node_modules/loupe/lib/set.js +function arrayFromSet(set2) { + const values = []; + set2.forEach((value) => { + values.push(value); + }); + return values; +} +__name(arrayFromSet, "arrayFromSet"); +function inspectSet(set2, options) { + if (set2.size === 0) + return "Set{}"; + options.truncate -= 7; + return `Set{ ${inspectList(arrayFromSet(set2), options)} }`; +} +__name(inspectSet, "inspectSet"); + +// node_modules/loupe/lib/string.js +var stringEscapeChars = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]", "g"); +var escapeCharacters = { + "\b": "\\b", + " ": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + "'": "\\'", + "\\": "\\\\" +}; +var hex = 16; +var unicodeLength = 4; +function escape(char) { + return escapeCharacters[char] || `\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-unicodeLength)}`; +} +__name(escape, "escape"); +function inspectString(string, options) { + if (stringEscapeChars.test(string)) { + string = string.replace(stringEscapeChars, escape); + } + return options.stylize(`'${truncate(string, options.truncate - 2)}'`, "string"); +} +__name(inspectString, "inspectString"); + +// node_modules/loupe/lib/symbol.js +function inspectSymbol(value) { + if ("description" in Symbol.prototype) { + return value.description ? `Symbol(${value.description})` : "Symbol()"; + } + return value.toString(); +} +__name(inspectSymbol, "inspectSymbol"); + +// node_modules/loupe/lib/promise.js +var getPromiseValue = /* @__PURE__ */ __name(() => "Promise{\u2026}", "getPromiseValue"); +try { + const { getPromiseDetails, kPending, kRejected } = process.binding("util"); + if (Array.isArray(getPromiseDetails(Promise.resolve()))) { + getPromiseValue = /* @__PURE__ */ __name((value, options) => { + const [state, innerValue] = getPromiseDetails(value); + if (state === kPending) { + return "Promise{}"; + } + return `Promise${state === kRejected ? "!" : ""}{${options.inspect(innerValue, options)}}`; + }, "getPromiseValue"); + } +} catch (notNode) { +} +var promise_default = getPromiseValue; + +// node_modules/loupe/lib/object.js +function inspectObject(object, options) { + const properties = Object.getOwnPropertyNames(object); + const symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : []; + if (properties.length === 0 && symbols.length === 0) { + return "{}"; + } + options.truncate -= 4; + options.seen = options.seen || []; + if (options.seen.includes(object)) { + return "[Circular]"; + } + options.seen.push(object); + const propertyContents = inspectList(properties.map((key) => [key, object[key]]), options, inspectProperty); + const symbolContents = inspectList(symbols.map((key) => [key, object[key]]), options, inspectProperty); + options.seen.pop(); + let sep = ""; + if (propertyContents && symbolContents) { + sep = ", "; + } + return `{ ${propertyContents}${sep}${symbolContents} }`; +} +__name(inspectObject, "inspectObject"); + +// node_modules/loupe/lib/class.js +var toStringTag = typeof Symbol !== "undefined" && Symbol.toStringTag ? Symbol.toStringTag : false; +function inspectClass(value, options) { + let name = ""; + if (toStringTag && toStringTag in value) { + name = value[toStringTag]; + } + name = name || value.constructor.name; + if (!name || name === "_class") { + name = ""; + } + options.truncate -= name.length; + return `${name}${inspectObject(value, options)}`; +} +__name(inspectClass, "inspectClass"); + +// node_modules/loupe/lib/arguments.js +function inspectArguments(args, options) { + if (args.length === 0) + return "Arguments[]"; + options.truncate -= 13; + return `Arguments[ ${inspectList(args, options)} ]`; +} +__name(inspectArguments, "inspectArguments"); + +// node_modules/loupe/lib/error.js +var errorKeys = [ + "stack", + "line", + "column", + "name", + "message", + "fileName", + "lineNumber", + "columnNumber", + "number", + "description", + "cause" +]; +function inspectObject2(error, options) { + const properties = Object.getOwnPropertyNames(error).filter((key) => errorKeys.indexOf(key) === -1); + const name = error.name; + options.truncate -= name.length; + let message = ""; + if (typeof error.message === "string") { + message = truncate(error.message, options.truncate); + } else { + properties.unshift("message"); + } + message = message ? `: ${message}` : ""; + options.truncate -= message.length + 5; + options.seen = options.seen || []; + if (options.seen.includes(error)) { + return "[Circular]"; + } + options.seen.push(error); + const propertyContents = inspectList(properties.map((key) => [key, error[key]]), options, inspectProperty); + return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ""}`; +} +__name(inspectObject2, "inspectObject"); + +// node_modules/loupe/lib/html.js +function inspectAttribute([key, value], options) { + options.truncate -= 3; + if (!value) { + return `${options.stylize(String(key), "yellow")}`; + } + return `${options.stylize(String(key), "yellow")}=${options.stylize(`"${value}"`, "string")}`; +} +__name(inspectAttribute, "inspectAttribute"); +function inspectHTMLCollection(collection, options) { + return inspectList(collection, options, inspectHTML, "\n"); +} +__name(inspectHTMLCollection, "inspectHTMLCollection"); +function inspectHTML(element, options) { + const properties = element.getAttributeNames(); + const name = element.tagName.toLowerCase(); + const head = options.stylize(`<${name}`, "special"); + const headClose = options.stylize(`>`, "special"); + const tail = options.stylize(``, "special"); + options.truncate -= name.length * 2 + 5; + let propertyContents = ""; + if (properties.length > 0) { + propertyContents += " "; + propertyContents += inspectList(properties.map((key) => [key, element.getAttribute(key)]), options, inspectAttribute, " "); + } + options.truncate -= propertyContents.length; + const truncate2 = options.truncate; + let children = inspectHTMLCollection(element.children, options); + if (children && children.length > truncate2) { + children = `${truncator}(${element.children.length})`; + } + return `${head}${propertyContents}${headClose}${children}${tail}`; +} +__name(inspectHTML, "inspectHTML"); + +// node_modules/loupe/lib/index.js +var symbolsSupported = typeof Symbol === "function" && typeof Symbol.for === "function"; +var chaiInspect = symbolsSupported ? Symbol.for("chai/inspect") : "@@chai/inspect"; +var nodeInspect = false; +try { + const nodeUtil = require_util(); + nodeInspect = nodeUtil.inspect ? nodeUtil.inspect.custom : false; +} catch (noNodeInspect) { + nodeInspect = false; +} +var constructorMap = /* @__PURE__ */ new WeakMap(); +var stringTagMap = {}; +var baseTypesMap = { + undefined: (value, options) => options.stylize("undefined", "undefined"), + null: (value, options) => options.stylize("null", "null"), + boolean: (value, options) => options.stylize(String(value), "boolean"), + Boolean: (value, options) => options.stylize(String(value), "boolean"), + number: inspectNumber, + Number: inspectNumber, + bigint: inspectBigInt, + BigInt: inspectBigInt, + string: inspectString, + String: inspectString, + function: inspectFunction, + Function: inspectFunction, + symbol: inspectSymbol, + // A Symbol polyfill will return `Symbol` not `symbol` from typedetect + Symbol: inspectSymbol, + Array: inspectArray, + Date: inspectDate, + Map: inspectMap, + Set: inspectSet, + RegExp: inspectRegExp, + Promise: promise_default, + // WeakSet, WeakMap are totally opaque to us + WeakSet: (value, options) => options.stylize("WeakSet{\u2026}", "special"), + WeakMap: (value, options) => options.stylize("WeakMap{\u2026}", "special"), + Arguments: inspectArguments, + Int8Array: inspectTypedArray, + Uint8Array: inspectTypedArray, + Uint8ClampedArray: inspectTypedArray, + Int16Array: inspectTypedArray, + Uint16Array: inspectTypedArray, + Int32Array: inspectTypedArray, + Uint32Array: inspectTypedArray, + Float32Array: inspectTypedArray, + Float64Array: inspectTypedArray, + Generator: () => "", + DataView: () => "", + ArrayBuffer: () => "", + Error: inspectObject2, + HTMLCollection: inspectHTMLCollection, + NodeList: inspectHTMLCollection +}; +var inspectCustom = /* @__PURE__ */ __name((value, options, type3) => { + if (chaiInspect in value && typeof value[chaiInspect] === "function") { + return value[chaiInspect](options); + } + if (nodeInspect && nodeInspect in value && typeof value[nodeInspect] === "function") { + return value[nodeInspect](options.depth, options); + } + if ("inspect" in value && typeof value.inspect === "function") { + return value.inspect(options.depth, options); + } + if ("constructor" in value && constructorMap.has(value.constructor)) { + return constructorMap.get(value.constructor)(value, options); + } + if (stringTagMap[type3]) { + return stringTagMap[type3](value, options); + } + return ""; +}, "inspectCustom"); +var toString = Object.prototype.toString; +function inspect(value, opts = {}) { + const options = normaliseOptions(opts, inspect); + const { customInspect } = options; + let type3 = value === null ? "null" : typeof value; + if (type3 === "object") { + type3 = toString.call(value).slice(8, -1); + } + if (type3 in baseTypesMap) { + return baseTypesMap[type3](value, options); + } + if (customInspect && value) { + const output = inspectCustom(value, options, type3); + if (output) { + if (typeof output === "string") + return output; + return inspect(output, options); + } + } + const proto = value ? Object.getPrototypeOf(value) : false; + if (proto === Object.prototype || proto === null) { + return inspectObject(value, options); + } + if (value && typeof HTMLElement === "function" && value instanceof HTMLElement) { + return inspectHTML(value, options); + } + if ("constructor" in value) { + if (value.constructor !== Object) { + return inspectClass(value, options); + } + return inspectObject(value, options); + } + if (value === Object(value)) { + return inspectObject(value, options); + } + return options.stylize(String(value), type3); +} +__name(inspect, "inspect"); + +// lib/chai/config.js +var config = { + /** + * ### config.includeStack + * + * User configurable property, influences whether stack trace + * is included in Assertion error message. Default of false + * suppresses stack trace in the error message. + * + * chai.config.includeStack = true; // enable stack on error + * + * @param {boolean} + * @public + */ + includeStack: false, + /** + * ### config.showDiff + * + * User configurable property, influences whether or not + * the `showDiff` flag should be included in the thrown + * AssertionErrors. `false` will always be `false`; `true` + * will be true when the assertion has requested a diff + * be shown. + * + * @param {boolean} + * @public + */ + showDiff: true, + /** + * ### config.truncateThreshold + * + * User configurable property, sets length threshold for actual and + * expected values in assertion errors. If this threshold is exceeded, for + * example for large data structures, the value is replaced with something + * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`. + * + * Set it to zero if you want to disable truncating altogether. + * + * This is especially userful when doing assertions on arrays: having this + * set to a reasonable large value makes the failure messages readily + * inspectable. + * + * chai.config.truncateThreshold = 0; // disable truncating + * + * @param {number} + * @public + */ + truncateThreshold: 40, + /** + * ### config.useProxy + * + * User configurable property, defines if chai will use a Proxy to throw + * an error when a non-existent property is read, which protects users + * from typos when using property-based assertions. + * + * Set it to false if you want to disable this feature. + * + * chai.config.useProxy = false; // disable use of Proxy + * + * This feature is automatically disabled regardless of this config value + * in environments that don't support proxies. + * + * @param {boolean} + * @public + */ + useProxy: true, + /** + * ### config.proxyExcludedKeys + * + * User configurable property, defines which properties should be ignored + * instead of throwing an error if they do not exist on the assertion. + * This is only applied if the environment Chai is running in supports proxies and + * if the `useProxy` configuration setting is enabled. + * By default, `then` and `inspect` will not throw an error if they do not exist on the + * assertion object because the `.inspect` property is read by `util.inspect` (for example, when + * using `console.log` on the assertion object) and `.then` is necessary for promise type-checking. + * + * // By default these keys will not throw an error if they do not exist on the assertion object + * chai.config.proxyExcludedKeys = ['then', 'inspect']; + * + * @param {Array} + * @public + */ + proxyExcludedKeys: ["then", "catch", "inspect", "toJSON"], + /** + * ### config.deepEqual + * + * User configurable property, defines which a custom function to use for deepEqual + * comparisons. + * By default, the function used is the one from the `deep-eql` package without custom comparator. + * + * // use a custom comparator + * chai.config.deepEqual = (expected, actual) => { + * return chai.util.eql(expected, actual, { + * comparator: (expected, actual) => { + * // for non number comparison, use the default behavior + * if(typeof expected !== 'number') return null; + * // allow a difference of 10 between compared numbers + * return typeof actual === 'number' && Math.abs(actual - expected) < 10 + * } + * }) + * }; + * + * @param {Function} + * @public + */ + deepEqual: null +}; + +// lib/chai/utils/inspect.js +function inspect2(obj, showHidden, depth, colors) { + var options = { + colors, + depth: typeof depth === "undefined" ? 2 : depth, + showHidden, + truncate: config.truncateThreshold ? config.truncateThreshold : Infinity + }; + return inspect(obj, options); +} +__name(inspect2, "inspect"); + +// lib/chai/utils/objDisplay.js +function objDisplay(obj) { + var str = inspect2(obj), type3 = Object.prototype.toString.call(obj); + if (config.truncateThreshold && str.length >= config.truncateThreshold) { + if (type3 === "[object Function]") { + return !obj.name || obj.name === "" ? "[Function]" : "[Function: " + obj.name + "]"; + } else if (type3 === "[object Array]") { + return "[ Array(" + obj.length + ") ]"; + } else if (type3 === "[object Object]") { + var keys = Object.keys(obj), kstr = keys.length > 2 ? keys.splice(0, 2).join(", ") + ", ..." : keys.join(", "); + return "{ Object (" + kstr + ") }"; + } else { + return str; + } + } else { + return str; + } +} +__name(objDisplay, "objDisplay"); + +// lib/chai/utils/getMessage.js +function getMessage2(obj, args) { + var negate = flag(obj, "negate"), val = flag(obj, "object"), expected = args[3], actual = getActual(obj, args), msg = negate ? args[2] : args[1], flagMsg = flag(obj, "message"); + if (typeof msg === "function") + msg = msg(); + msg = msg || ""; + msg = msg.replace(/#\{this\}/g, function() { + return objDisplay(val); + }).replace(/#\{act\}/g, function() { + return objDisplay(actual); + }).replace(/#\{exp\}/g, function() { + return objDisplay(expected); + }); + return flagMsg ? flagMsg + ": " + msg : msg; +} +__name(getMessage2, "getMessage"); + +// lib/chai/utils/transferFlags.js +function transferFlags(assertion, object, includeAll) { + var flags = assertion.__flags || (assertion.__flags = /* @__PURE__ */ Object.create(null)); + if (!object.__flags) { + object.__flags = /* @__PURE__ */ Object.create(null); + } + includeAll = arguments.length === 3 ? includeAll : true; + for (var flag3 in flags) { + if (includeAll || flag3 !== "object" && flag3 !== "ssfi" && flag3 !== "lockSsfi" && flag3 != "message") { + object.__flags[flag3] = flags[flag3]; + } + } +} +__name(transferFlags, "transferFlags"); + +// node_modules/deep-eql/index.js +function type2(obj) { + if (typeof obj === "undefined") { + return "undefined"; + } + if (obj === null) { + return "null"; + } + const stringTag = obj[Symbol.toStringTag]; + if (typeof stringTag === "string") { + return stringTag; + } + const sliceStart = 8; + const sliceEnd = -1; + return Object.prototype.toString.call(obj).slice(sliceStart, sliceEnd); +} +__name(type2, "type"); +function FakeMap() { + this._key = "chai/deep-eql__" + Math.random() + Date.now(); +} +__name(FakeMap, "FakeMap"); +FakeMap.prototype = { + get: /* @__PURE__ */ __name(function get(key) { + return key[this._key]; + }, "get"), + set: /* @__PURE__ */ __name(function set(key, value) { + if (Object.isExtensible(key)) { + Object.defineProperty(key, this._key, { + value, + configurable: true + }); + } + }, "set") +}; +var MemoizeMap = typeof WeakMap === "function" ? WeakMap : FakeMap; +function memoizeCompare(leftHandOperand, rightHandOperand, memoizeMap) { + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return null; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + var result = leftHandMap.get(rightHandOperand); + if (typeof result === "boolean") { + return result; + } + } + return null; +} +__name(memoizeCompare, "memoizeCompare"); +function memoizeSet(leftHandOperand, rightHandOperand, memoizeMap, result) { + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + leftHandMap.set(rightHandOperand, result); + } else { + leftHandMap = new MemoizeMap(); + leftHandMap.set(rightHandOperand, result); + memoizeMap.set(leftHandOperand, leftHandMap); + } +} +__name(memoizeSet, "memoizeSet"); +var deep_eql_default = deepEqual; +function deepEqual(leftHandOperand, rightHandOperand, options) { + if (options && options.comparator) { + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); + } + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + return simpleResult; + } + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); +} +__name(deepEqual, "deepEqual"); +function simpleEqual(leftHandOperand, rightHandOperand) { + if (leftHandOperand === rightHandOperand) { + return leftHandOperand !== 0 || 1 / leftHandOperand === 1 / rightHandOperand; + } + if (leftHandOperand !== leftHandOperand && // eslint-disable-line no-self-compare + rightHandOperand !== rightHandOperand) { + return true; + } + if (isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return false; + } + return null; +} +__name(simpleEqual, "simpleEqual"); +function extensiveDeepEqual(leftHandOperand, rightHandOperand, options) { + options = options || {}; + options.memoize = options.memoize === false ? false : options.memoize || new MemoizeMap(); + var comparator = options && options.comparator; + var memoizeResultLeft = memoizeCompare(leftHandOperand, rightHandOperand, options.memoize); + if (memoizeResultLeft !== null) { + return memoizeResultLeft; + } + var memoizeResultRight = memoizeCompare(rightHandOperand, leftHandOperand, options.memoize); + if (memoizeResultRight !== null) { + return memoizeResultRight; + } + if (comparator) { + var comparatorResult = comparator(leftHandOperand, rightHandOperand); + if (comparatorResult === false || comparatorResult === true) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, comparatorResult); + return comparatorResult; + } + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + return simpleResult; + } + } + var leftHandType = type2(leftHandOperand); + if (leftHandType !== type2(rightHandOperand)) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, false); + return false; + } + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, true); + var result = extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options); + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, result); + return result; +} +__name(extensiveDeepEqual, "extensiveDeepEqual"); +function extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options) { + switch (leftHandType) { + case "String": + case "Number": + case "Boolean": + case "Date": + return deepEqual(leftHandOperand.valueOf(), rightHandOperand.valueOf()); + case "Promise": + case "Symbol": + case "function": + case "WeakMap": + case "WeakSet": + return leftHandOperand === rightHandOperand; + case "Error": + return keysEqual(leftHandOperand, rightHandOperand, ["name", "message", "code"], options); + case "Arguments": + case "Int8Array": + case "Uint8Array": + case "Uint8ClampedArray": + case "Int16Array": + case "Uint16Array": + case "Int32Array": + case "Uint32Array": + case "Float32Array": + case "Float64Array": + case "Array": + return iterableEqual(leftHandOperand, rightHandOperand, options); + case "RegExp": + return regexpEqual(leftHandOperand, rightHandOperand); + case "Generator": + return generatorEqual(leftHandOperand, rightHandOperand, options); + case "DataView": + return iterableEqual(new Uint8Array(leftHandOperand.buffer), new Uint8Array(rightHandOperand.buffer), options); + case "ArrayBuffer": + return iterableEqual(new Uint8Array(leftHandOperand), new Uint8Array(rightHandOperand), options); + case "Set": + return entriesEqual(leftHandOperand, rightHandOperand, options); + case "Map": + return entriesEqual(leftHandOperand, rightHandOperand, options); + case "Temporal.PlainDate": + case "Temporal.PlainTime": + case "Temporal.PlainDateTime": + case "Temporal.Instant": + case "Temporal.ZonedDateTime": + case "Temporal.PlainYearMonth": + case "Temporal.PlainMonthDay": + return leftHandOperand.equals(rightHandOperand); + case "Temporal.Duration": + return leftHandOperand.total("nanoseconds") === rightHandOperand.total("nanoseconds"); + case "Temporal.TimeZone": + case "Temporal.Calendar": + return leftHandOperand.toString() === rightHandOperand.toString(); + default: + return objectEqual(leftHandOperand, rightHandOperand, options); + } +} +__name(extensiveDeepEqualByType, "extensiveDeepEqualByType"); +function regexpEqual(leftHandOperand, rightHandOperand) { + return leftHandOperand.toString() === rightHandOperand.toString(); +} +__name(regexpEqual, "regexpEqual"); +function entriesEqual(leftHandOperand, rightHandOperand, options) { + try { + if (leftHandOperand.size !== rightHandOperand.size) { + return false; + } + if (leftHandOperand.size === 0) { + return true; + } + } catch (sizeError) { + return false; + } + var leftHandItems = []; + var rightHandItems = []; + leftHandOperand.forEach(/* @__PURE__ */ __name(function gatherEntries(key, value) { + leftHandItems.push([key, value]); + }, "gatherEntries")); + rightHandOperand.forEach(/* @__PURE__ */ __name(function gatherEntries(key, value) { + rightHandItems.push([key, value]); + }, "gatherEntries")); + return iterableEqual(leftHandItems.sort(), rightHandItems.sort(), options); +} +__name(entriesEqual, "entriesEqual"); +function iterableEqual(leftHandOperand, rightHandOperand, options) { + var length = leftHandOperand.length; + if (length !== rightHandOperand.length) { + return false; + } + if (length === 0) { + return true; + } + var index = -1; + while (++index < length) { + if (deepEqual(leftHandOperand[index], rightHandOperand[index], options) === false) { + return false; + } + } + return true; +} +__name(iterableEqual, "iterableEqual"); +function generatorEqual(leftHandOperand, rightHandOperand, options) { + return iterableEqual(getGeneratorEntries(leftHandOperand), getGeneratorEntries(rightHandOperand), options); +} +__name(generatorEqual, "generatorEqual"); +function hasIteratorFunction(target) { + return typeof Symbol !== "undefined" && typeof target === "object" && typeof Symbol.iterator !== "undefined" && typeof target[Symbol.iterator] === "function"; +} +__name(hasIteratorFunction, "hasIteratorFunction"); +function getIteratorEntries(target) { + if (hasIteratorFunction(target)) { + try { + return getGeneratorEntries(target[Symbol.iterator]()); + } catch (iteratorError) { + return []; + } + } + return []; +} +__name(getIteratorEntries, "getIteratorEntries"); +function getGeneratorEntries(generator) { + var generatorResult = generator.next(); + var accumulator = [generatorResult.value]; + while (generatorResult.done === false) { + generatorResult = generator.next(); + accumulator.push(generatorResult.value); + } + return accumulator; +} +__name(getGeneratorEntries, "getGeneratorEntries"); +function getEnumerableKeys(target) { + var keys = []; + for (var key in target) { + keys.push(key); + } + return keys; +} +__name(getEnumerableKeys, "getEnumerableKeys"); +function getEnumerableSymbols(target) { + var keys = []; + var allKeys = Object.getOwnPropertySymbols(target); + for (var i = 0; i < allKeys.length; i += 1) { + var key = allKeys[i]; + if (Object.getOwnPropertyDescriptor(target, key).enumerable) { + keys.push(key); + } + } + return keys; +} +__name(getEnumerableSymbols, "getEnumerableSymbols"); +function keysEqual(leftHandOperand, rightHandOperand, keys, options) { + var length = keys.length; + if (length === 0) { + return true; + } + for (var i = 0; i < length; i += 1) { + if (deepEqual(leftHandOperand[keys[i]], rightHandOperand[keys[i]], options) === false) { + return false; + } + } + return true; +} +__name(keysEqual, "keysEqual"); +function objectEqual(leftHandOperand, rightHandOperand, options) { + var leftHandKeys = getEnumerableKeys(leftHandOperand); + var rightHandKeys = getEnumerableKeys(rightHandOperand); + var leftHandSymbols = getEnumerableSymbols(leftHandOperand); + var rightHandSymbols = getEnumerableSymbols(rightHandOperand); + leftHandKeys = leftHandKeys.concat(leftHandSymbols); + rightHandKeys = rightHandKeys.concat(rightHandSymbols); + if (leftHandKeys.length && leftHandKeys.length === rightHandKeys.length) { + if (iterableEqual(mapSymbols(leftHandKeys).sort(), mapSymbols(rightHandKeys).sort()) === false) { + return false; + } + return keysEqual(leftHandOperand, rightHandOperand, leftHandKeys, options); + } + var leftHandEntries = getIteratorEntries(leftHandOperand); + var rightHandEntries = getIteratorEntries(rightHandOperand); + if (leftHandEntries.length && leftHandEntries.length === rightHandEntries.length) { + leftHandEntries.sort(); + rightHandEntries.sort(); + return iterableEqual(leftHandEntries, rightHandEntries, options); + } + if (leftHandKeys.length === 0 && leftHandEntries.length === 0 && rightHandKeys.length === 0 && rightHandEntries.length === 0) { + return true; + } + return false; +} +__name(objectEqual, "objectEqual"); +function isPrimitive(value) { + return value === null || typeof value !== "object"; +} +__name(isPrimitive, "isPrimitive"); +function mapSymbols(arr) { + return arr.map(/* @__PURE__ */ __name(function mapSymbol(entry) { + if (typeof entry === "symbol") { + return entry.toString(); + } + return entry; + }, "mapSymbol")); +} +__name(mapSymbols, "mapSymbols"); + +// node_modules/pathval/index.js +function hasProperty(obj, name) { + if (typeof obj === "undefined" || obj === null) { + return false; + } + return name in Object(obj); +} +__name(hasProperty, "hasProperty"); +function parsePath(path) { + const str = path.replace(/([^\\])\[/g, "$1.["); + const parts = str.match(/(\\\.|[^.]+?)+/g); + return parts.map((value) => { + if (value === "constructor" || value === "__proto__" || value === "prototype") { + return {}; + } + const regexp = /^\[(\d+)\]$/; + const mArr = regexp.exec(value); + let parsed = null; + if (mArr) { + parsed = { i: parseFloat(mArr[1]) }; + } else { + parsed = { p: value.replace(/\\([.[\]])/g, "$1") }; + } + return parsed; + }); +} +__name(parsePath, "parsePath"); +function internalGetPathValue(obj, parsed, pathDepth) { + let temporaryValue = obj; + let res = null; + pathDepth = typeof pathDepth === "undefined" ? parsed.length : pathDepth; + for (let i = 0; i < pathDepth; i++) { + const part = parsed[i]; + if (temporaryValue) { + if (typeof part.p === "undefined") { + temporaryValue = temporaryValue[part.i]; + } else { + temporaryValue = temporaryValue[part.p]; + } + if (i === pathDepth - 1) { + res = temporaryValue; + } + } + } + return res; +} +__name(internalGetPathValue, "internalGetPathValue"); +function getPathInfo(obj, path) { + const parsed = parsePath(path); + const last = parsed[parsed.length - 1]; + const info = { + parent: parsed.length > 1 ? internalGetPathValue(obj, parsed, parsed.length - 1) : obj, + name: last.p || last.i, + value: internalGetPathValue(obj, parsed) + }; + info.exists = hasProperty(info.parent, info.name); + return info; +} +__name(getPathInfo, "getPathInfo"); + +// lib/chai/assertion.js +function Assertion(obj, msg, ssfi, lockSsfi) { + flag(this, "ssfi", ssfi || Assertion); + flag(this, "lockSsfi", lockSsfi); + flag(this, "object", obj); + flag(this, "message", msg); + flag(this, "eql", config.deepEqual || deep_eql_default); + return proxify(this); +} +__name(Assertion, "Assertion"); +Object.defineProperty(Assertion, "includeStack", { + get: function() { + console.warn("Assertion.includeStack is deprecated, use chai.config.includeStack instead."); + return config.includeStack; + }, + set: function(value) { + console.warn("Assertion.includeStack is deprecated, use chai.config.includeStack instead."); + config.includeStack = value; + } +}); +Object.defineProperty(Assertion, "showDiff", { + get: function() { + console.warn("Assertion.showDiff is deprecated, use chai.config.showDiff instead."); + return config.showDiff; + }, + set: function(value) { + console.warn("Assertion.showDiff is deprecated, use chai.config.showDiff instead."); + config.showDiff = value; + } +}); +Assertion.addProperty = function(name, fn) { + addProperty(this.prototype, name, fn); +}; +Assertion.addMethod = function(name, fn) { + addMethod(this.prototype, name, fn); +}; +Assertion.addChainableMethod = function(name, fn, chainingBehavior) { + addChainableMethod(this.prototype, name, fn, chainingBehavior); +}; +Assertion.overwriteProperty = function(name, fn) { + overwriteProperty(this.prototype, name, fn); +}; +Assertion.overwriteMethod = function(name, fn) { + overwriteMethod(this.prototype, name, fn); +}; +Assertion.overwriteChainableMethod = function(name, fn, chainingBehavior) { + overwriteChainableMethod(this.prototype, name, fn, chainingBehavior); +}; +Assertion.prototype.assert = function(expr, msg, negateMsg, expected, _actual, showDiff) { + var ok = test(this, arguments); + if (false !== showDiff) + showDiff = true; + if (void 0 === expected && void 0 === _actual) + showDiff = false; + if (true !== config.showDiff) + showDiff = false; + if (!ok) { + msg = getMessage2(this, arguments); + var actual = getActual(this, arguments); + var assertionErrorObjectProperties = { + actual, + expected, + showDiff + }; + var operator = getOperator(this, arguments); + if (operator) { + assertionErrorObjectProperties.operator = operator; + } + throw new AssertionError( + msg, + assertionErrorObjectProperties, + config.includeStack ? this.assert : flag(this, "ssfi") + ); + } +}; +Object.defineProperty( + Assertion.prototype, + "_obj", + { + get: function() { + return flag(this, "object"); + }, + set: function(val) { + flag(this, "object", val); + } + } +); + +// lib/chai/utils/isProxyEnabled.js +function isProxyEnabled() { + return config.useProxy && typeof Proxy !== "undefined" && typeof Reflect !== "undefined"; +} +__name(isProxyEnabled, "isProxyEnabled"); + +// lib/chai/utils/addProperty.js +function addProperty(ctx, name, getter) { + getter = getter === void 0 ? function() { + } : getter; + Object.defineProperty( + ctx, + name, + { + get: /* @__PURE__ */ __name(function propertyGetter() { + if (!isProxyEnabled() && !flag(this, "lockSsfi")) { + flag(this, "ssfi", propertyGetter); + } + var result = getter.call(this); + if (result !== void 0) + return result; + var newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "propertyGetter"), + configurable: true + } + ); +} +__name(addProperty, "addProperty"); + +// lib/chai/utils/addLengthGuard.js +var fnLengthDesc = Object.getOwnPropertyDescriptor(function() { +}, "length"); +function addLengthGuard(fn, assertionName, isChainable) { + if (!fnLengthDesc.configurable) + return fn; + Object.defineProperty(fn, "length", { + get: function() { + if (isChainable) { + throw Error("Invalid Chai property: " + assertionName + '.length. Due to a compatibility issue, "length" cannot directly follow "' + assertionName + '". Use "' + assertionName + '.lengthOf" instead.'); + } + throw Error("Invalid Chai property: " + assertionName + '.length. See docs for proper usage of "' + assertionName + '".'); + } + }); + return fn; +} +__name(addLengthGuard, "addLengthGuard"); + +// lib/chai/utils/getProperties.js +function getProperties(object) { + var result = Object.getOwnPropertyNames(object); + function addProperty2(property) { + if (result.indexOf(property) === -1) { + result.push(property); + } + } + __name(addProperty2, "addProperty"); + var proto = Object.getPrototypeOf(object); + while (proto !== null) { + Object.getOwnPropertyNames(proto).forEach(addProperty2); + proto = Object.getPrototypeOf(proto); + } + return result; +} +__name(getProperties, "getProperties"); + +// lib/chai/utils/proxify.js +var builtins = ["__flags", "__methods", "_obj", "assert"]; +function proxify(obj, nonChainableMethodName) { + if (!isProxyEnabled()) + return obj; + return new Proxy(obj, { + get: /* @__PURE__ */ __name(function proxyGetter(target, property) { + if (typeof property === "string" && config.proxyExcludedKeys.indexOf(property) === -1 && !Reflect.has(target, property)) { + if (nonChainableMethodName) { + throw Error("Invalid Chai property: " + nonChainableMethodName + "." + property + '. See docs for proper usage of "' + nonChainableMethodName + '".'); + } + var suggestion = null; + var suggestionDistance = 4; + getProperties(target).forEach(function(prop) { + if (!Object.prototype.hasOwnProperty(prop) && builtins.indexOf(prop) === -1) { + var dist = stringDistanceCapped( + property, + prop, + suggestionDistance + ); + if (dist < suggestionDistance) { + suggestion = prop; + suggestionDistance = dist; + } + } + }); + if (suggestion !== null) { + throw Error("Invalid Chai property: " + property + '. Did you mean "' + suggestion + '"?'); + } else { + throw Error("Invalid Chai property: " + property); + } + } + if (builtins.indexOf(property) === -1 && !flag(target, "lockSsfi")) { + flag(target, "ssfi", proxyGetter); + } + return Reflect.get(target, property); + }, "proxyGetter") + }); +} +__name(proxify, "proxify"); +function stringDistanceCapped(strA, strB, cap) { + if (Math.abs(strA.length - strB.length) >= cap) { + return cap; + } + var memo = []; + for (var i = 0; i <= strA.length; i++) { + memo[i] = Array(strB.length + 1).fill(0); + memo[i][0] = i; + } + for (var j = 0; j < strB.length; j++) { + memo[0][j] = j; + } + for (var i = 1; i <= strA.length; i++) { + var ch = strA.charCodeAt(i - 1); + for (var j = 1; j <= strB.length; j++) { + if (Math.abs(i - j) >= cap) { + memo[i][j] = cap; + continue; + } + memo[i][j] = Math.min( + memo[i - 1][j] + 1, + memo[i][j - 1] + 1, + memo[i - 1][j - 1] + (ch === strB.charCodeAt(j - 1) ? 0 : 1) + ); + } + } + return memo[strA.length][strB.length]; +} +__name(stringDistanceCapped, "stringDistanceCapped"); + +// lib/chai/utils/addMethod.js +function addMethod(ctx, name, method) { + var methodWrapper = /* @__PURE__ */ __name(function() { + if (!flag(this, "lockSsfi")) { + flag(this, "ssfi", methodWrapper); + } + var result = method.apply(this, arguments); + if (result !== void 0) + return result; + var newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "methodWrapper"); + addLengthGuard(methodWrapper, name, false); + ctx[name] = proxify(methodWrapper, name); +} +__name(addMethod, "addMethod"); + +// lib/chai/utils/overwriteProperty.js +function overwriteProperty(ctx, name, getter) { + var _get = Object.getOwnPropertyDescriptor(ctx, name), _super = /* @__PURE__ */ __name(function() { + }, "_super"); + if (_get && "function" === typeof _get.get) + _super = _get.get; + Object.defineProperty( + ctx, + name, + { + get: /* @__PURE__ */ __name(function overwritingPropertyGetter() { + if (!isProxyEnabled() && !flag(this, "lockSsfi")) { + flag(this, "ssfi", overwritingPropertyGetter); + } + var origLockSsfi = flag(this, "lockSsfi"); + flag(this, "lockSsfi", true); + var result = getter(_super).call(this); + flag(this, "lockSsfi", origLockSsfi); + if (result !== void 0) { + return result; + } + var newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "overwritingPropertyGetter"), + configurable: true + } + ); +} +__name(overwriteProperty, "overwriteProperty"); + +// lib/chai/utils/overwriteMethod.js +function overwriteMethod(ctx, name, method) { + var _method = ctx[name], _super = /* @__PURE__ */ __name(function() { + throw new Error(name + " is not a function"); + }, "_super"); + if (_method && "function" === typeof _method) + _super = _method; + var overwritingMethodWrapper = /* @__PURE__ */ __name(function() { + if (!flag(this, "lockSsfi")) { + flag(this, "ssfi", overwritingMethodWrapper); + } + var origLockSsfi = flag(this, "lockSsfi"); + flag(this, "lockSsfi", true); + var result = method(_super).apply(this, arguments); + flag(this, "lockSsfi", origLockSsfi); + if (result !== void 0) { + return result; + } + var newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "overwritingMethodWrapper"); + addLengthGuard(overwritingMethodWrapper, name, false); + ctx[name] = proxify(overwritingMethodWrapper, name); +} +__name(overwriteMethod, "overwriteMethod"); + +// lib/chai/utils/addChainableMethod.js +var canSetPrototype = typeof Object.setPrototypeOf === "function"; +var testFn = /* @__PURE__ */ __name(function() { +}, "testFn"); +var excludeNames = Object.getOwnPropertyNames(testFn).filter(function(name) { + var propDesc = Object.getOwnPropertyDescriptor(testFn, name); + if (typeof propDesc !== "object") + return true; + return !propDesc.configurable; +}); +var call = Function.prototype.call; +var apply = Function.prototype.apply; +function addChainableMethod(ctx, name, method, chainingBehavior) { + if (typeof chainingBehavior !== "function") { + chainingBehavior = /* @__PURE__ */ __name(function() { + }, "chainingBehavior"); + } + var chainableBehavior = { + method, + chainingBehavior + }; + if (!ctx.__methods) { + ctx.__methods = {}; + } + ctx.__methods[name] = chainableBehavior; + Object.defineProperty( + ctx, + name, + { + get: /* @__PURE__ */ __name(function chainableMethodGetter() { + chainableBehavior.chainingBehavior.call(this); + var chainableMethodWrapper = /* @__PURE__ */ __name(function() { + if (!flag(this, "lockSsfi")) { + flag(this, "ssfi", chainableMethodWrapper); + } + var result = chainableBehavior.method.apply(this, arguments); + if (result !== void 0) { + return result; + } + var newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "chainableMethodWrapper"); + addLengthGuard(chainableMethodWrapper, name, true); + if (canSetPrototype) { + var prototype = Object.create(this); + prototype.call = call; + prototype.apply = apply; + Object.setPrototypeOf(chainableMethodWrapper, prototype); + } else { + var asserterNames = Object.getOwnPropertyNames(ctx); + asserterNames.forEach(function(asserterName) { + if (excludeNames.indexOf(asserterName) !== -1) { + return; + } + var pd = Object.getOwnPropertyDescriptor(ctx, asserterName); + Object.defineProperty(chainableMethodWrapper, asserterName, pd); + }); + } + transferFlags(this, chainableMethodWrapper); + return proxify(chainableMethodWrapper); + }, "chainableMethodGetter"), + configurable: true + } + ); +} +__name(addChainableMethod, "addChainableMethod"); + +// lib/chai/utils/overwriteChainableMethod.js +function overwriteChainableMethod(ctx, name, method, chainingBehavior) { + var chainableBehavior = ctx.__methods[name]; + var _chainingBehavior = chainableBehavior.chainingBehavior; + chainableBehavior.chainingBehavior = /* @__PURE__ */ __name(function overwritingChainableMethodGetter() { + var result = chainingBehavior(_chainingBehavior).call(this); + if (result !== void 0) { + return result; + } + var newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "overwritingChainableMethodGetter"); + var _method = chainableBehavior.method; + chainableBehavior.method = /* @__PURE__ */ __name(function overwritingChainableMethodWrapper() { + var result = method(_method).apply(this, arguments); + if (result !== void 0) { + return result; + } + var newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }, "overwritingChainableMethodWrapper"); +} +__name(overwriteChainableMethod, "overwriteChainableMethod"); + +// lib/chai/utils/compareByInspect.js +function compareByInspect(a, b) { + return inspect2(a) < inspect2(b) ? -1 : 1; +} +__name(compareByInspect, "compareByInspect"); + +// lib/chai/utils/getOwnEnumerablePropertySymbols.js +function getOwnEnumerablePropertySymbols(obj) { + if (typeof Object.getOwnPropertySymbols !== "function") + return []; + return Object.getOwnPropertySymbols(obj).filter(function(sym) { + return Object.getOwnPropertyDescriptor(obj, sym).enumerable; + }); +} +__name(getOwnEnumerablePropertySymbols, "getOwnEnumerablePropertySymbols"); + +// lib/chai/utils/getOwnEnumerableProperties.js +function getOwnEnumerableProperties(obj) { + return Object.keys(obj).concat(getOwnEnumerablePropertySymbols(obj)); +} +__name(getOwnEnumerableProperties, "getOwnEnumerableProperties"); + +// lib/chai/utils/isNaN.js +function _isNaN(value) { + return value !== value; +} +__name(_isNaN, "_isNaN"); +var isNaN2 = Number.isNaN || _isNaN; + +// lib/chai/utils/getOperator.js +function isObjectType(obj) { + var objectType = type(obj); + var objectTypes = ["Array", "Object", "Function"]; + return objectTypes.indexOf(objectType) !== -1; +} +__name(isObjectType, "isObjectType"); +function getOperator(obj, args) { + var operator = flag(obj, "operator"); + var negate = flag(obj, "negate"); + var expected = args[3]; + var msg = negate ? args[2] : args[1]; + if (operator) { + return operator; + } + if (typeof msg === "function") + msg = msg(); + msg = msg || ""; + if (!msg) { + return void 0; + } + if (/\shave\s/.test(msg)) { + return void 0; + } + var isObject = isObjectType(expected); + if (/\snot\s/.test(msg)) { + return isObject ? "notDeepStrictEqual" : "notStrictEqual"; + } + return isObject ? "deepStrictEqual" : "strictEqual"; +} +__name(getOperator, "getOperator"); + +// lib/chai/utils/index.js +function getName(fn) { + return fn.name; +} +__name(getName, "getName"); +function isRegExp2(obj) { + return Object.prototype.toString.call(obj) === "[object RegExp]"; +} +__name(isRegExp2, "isRegExp"); +function isNumeric(obj) { + return ["Number", "BigInt"].includes(type(obj)); +} +__name(isNumeric, "isNumeric"); + +// lib/chai/core/assertions.js +var { flag: flag2 } = utils_exports; +[ + "to", + "be", + "been", + "is", + "and", + "has", + "have", + "with", + "that", + "which", + "at", + "of", + "same", + "but", + "does", + "still", + "also" +].forEach(function(chain) { + Assertion.addProperty(chain); +}); +Assertion.addProperty("not", function() { + flag2(this, "negate", true); +}); +Assertion.addProperty("deep", function() { + flag2(this, "deep", true); +}); +Assertion.addProperty("nested", function() { + flag2(this, "nested", true); +}); +Assertion.addProperty("own", function() { + flag2(this, "own", true); +}); +Assertion.addProperty("ordered", function() { + flag2(this, "ordered", true); +}); +Assertion.addProperty("any", function() { + flag2(this, "any", true); + flag2(this, "all", false); +}); +Assertion.addProperty("all", function() { + flag2(this, "all", true); + flag2(this, "any", false); +}); +var functionTypes = { + "function": ["function", "asyncfunction", "generatorfunction", "asyncgeneratorfunction"], + "asyncfunction": ["asyncfunction", "asyncgeneratorfunction"], + "generatorfunction": ["generatorfunction", "asyncgeneratorfunction"], + "asyncgeneratorfunction": ["asyncgeneratorfunction"] +}; +function an(type3, msg) { + if (msg) + flag2(this, "message", msg); + type3 = type3.toLowerCase(); + var obj = flag2(this, "object"), article = ~["a", "e", "i", "o", "u"].indexOf(type3.charAt(0)) ? "an " : "a "; + const detectedType = type(obj).toLowerCase(); + if (functionTypes["function"].includes(type3)) { + this.assert( + functionTypes[type3].includes(detectedType), + "expected #{this} to be " + article + type3, + "expected #{this} not to be " + article + type3 + ); + } else { + this.assert( + type3 === detectedType, + "expected #{this} to be " + article + type3, + "expected #{this} not to be " + article + type3 + ); + } +} +__name(an, "an"); +Assertion.addChainableMethod("an", an); +Assertion.addChainableMethod("a", an); +function SameValueZero(a, b) { + return isNaN2(a) && isNaN2(b) || a === b; +} +__name(SameValueZero, "SameValueZero"); +function includeChainingBehavior() { + flag2(this, "contains", true); +} +__name(includeChainingBehavior, "includeChainingBehavior"); +function include(val, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"), objType = type(obj).toLowerCase(), flagMsg = flag2(this, "message"), negate = flag2(this, "negate"), ssfi = flag2(this, "ssfi"), isDeep = flag2(this, "deep"), descriptor = isDeep ? "deep " : "", isEql = isDeep ? flag2(this, "eql") : SameValueZero; + flagMsg = flagMsg ? flagMsg + ": " : ""; + var included = false; + switch (objType) { + case "string": + included = obj.indexOf(val) !== -1; + break; + case "weakset": + if (isDeep) { + throw new AssertionError( + flagMsg + "unable to use .deep.include with WeakSet", + void 0, + ssfi + ); + } + included = obj.has(val); + break; + case "map": + obj.forEach(function(item) { + included = included || isEql(item, val); + }); + break; + case "set": + if (isDeep) { + obj.forEach(function(item) { + included = included || isEql(item, val); + }); + } else { + included = obj.has(val); + } + break; + case "array": + if (isDeep) { + included = obj.some(function(item) { + return isEql(item, val); + }); + } else { + included = obj.indexOf(val) !== -1; + } + break; + default: + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + "the given combination of arguments (" + objType + " and " + type(val).toLowerCase() + ") is invalid for this assertion. You can use an array, a map, an object, a set, a string, or a weakset instead of a " + type(val).toLowerCase(), + void 0, + ssfi + ); + } + var props = Object.keys(val), firstErr = null, numErrs = 0; + props.forEach(function(prop) { + var propAssertion = new Assertion(obj); + transferFlags(this, propAssertion, true); + flag2(propAssertion, "lockSsfi", true); + if (!negate || props.length === 1) { + propAssertion.property(prop, val[prop]); + return; + } + try { + propAssertion.property(prop, val[prop]); + } catch (err) { + if (!check_error_exports.compatibleConstructor(err, AssertionError)) { + throw err; + } + if (firstErr === null) + firstErr = err; + numErrs++; + } + }, this); + if (negate && props.length > 1 && numErrs === props.length) { + throw firstErr; + } + return; + } + this.assert( + included, + "expected #{this} to " + descriptor + "include " + inspect2(val), + "expected #{this} to not " + descriptor + "include " + inspect2(val) + ); +} +__name(include, "include"); +Assertion.addChainableMethod("include", include, includeChainingBehavior); +Assertion.addChainableMethod("contain", include, includeChainingBehavior); +Assertion.addChainableMethod("contains", include, includeChainingBehavior); +Assertion.addChainableMethod("includes", include, includeChainingBehavior); +Assertion.addProperty("ok", function() { + this.assert( + flag2(this, "object"), + "expected #{this} to be truthy", + "expected #{this} to be falsy" + ); +}); +Assertion.addProperty("true", function() { + this.assert( + true === flag2(this, "object"), + "expected #{this} to be true", + "expected #{this} to be false", + flag2(this, "negate") ? false : true + ); +}); +Assertion.addProperty("numeric", function() { + const object = flag2(this, "object"); + this.assert( + ["Number", "BigInt"].includes(type(object)), + "expected #{this} to be numeric", + "expected #{this} to not be numeric", + flag2(this, "negate") ? false : true + ); +}); +Assertion.addProperty("callable", function() { + const val = flag2(this, "object"); + const ssfi = flag2(this, "ssfi"); + const message = flag2(this, "message"); + const msg = message ? `${message}: ` : ""; + const negate = flag2(this, "negate"); + const assertionMessage = negate ? `${msg}expected ${inspect2(val)} not to be a callable function` : `${msg}expected ${inspect2(val)} to be a callable function`; + const isCallable = ["Function", "AsyncFunction", "GeneratorFunction", "AsyncGeneratorFunction"].includes(type(val)); + if (isCallable && negate || !isCallable && !negate) { + throw new AssertionError( + assertionMessage, + void 0, + ssfi + ); + } +}); +Assertion.addProperty("false", function() { + this.assert( + false === flag2(this, "object"), + "expected #{this} to be false", + "expected #{this} to be true", + flag2(this, "negate") ? true : false + ); +}); +Assertion.addProperty("null", function() { + this.assert( + null === flag2(this, "object"), + "expected #{this} to be null", + "expected #{this} not to be null" + ); +}); +Assertion.addProperty("undefined", function() { + this.assert( + void 0 === flag2(this, "object"), + "expected #{this} to be undefined", + "expected #{this} not to be undefined" + ); +}); +Assertion.addProperty("NaN", function() { + this.assert( + isNaN2(flag2(this, "object")), + "expected #{this} to be NaN", + "expected #{this} not to be NaN" + ); +}); +function assertExist() { + var val = flag2(this, "object"); + this.assert( + val !== null && val !== void 0, + "expected #{this} to exist", + "expected #{this} to not exist" + ); +} +__name(assertExist, "assertExist"); +Assertion.addProperty("exist", assertExist); +Assertion.addProperty("exists", assertExist); +Assertion.addProperty("empty", function() { + var val = flag2(this, "object"), ssfi = flag2(this, "ssfi"), flagMsg = flag2(this, "message"), itemsCount; + flagMsg = flagMsg ? flagMsg + ": " : ""; + switch (type(val).toLowerCase()) { + case "array": + case "string": + itemsCount = val.length; + break; + case "map": + case "set": + itemsCount = val.size; + break; + case "weakmap": + case "weakset": + throw new AssertionError( + flagMsg + ".empty was passed a weak collection", + void 0, + ssfi + ); + case "function": + var msg = flagMsg + ".empty was passed a function " + getName(val); + throw new AssertionError(msg.trim(), void 0, ssfi); + default: + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + ".empty was passed non-string primitive " + inspect2(val), + void 0, + ssfi + ); + } + itemsCount = Object.keys(val).length; + } + this.assert( + 0 === itemsCount, + "expected #{this} to be empty", + "expected #{this} not to be empty" + ); +}); +function checkArguments() { + var obj = flag2(this, "object"), type3 = type(obj); + this.assert( + "Arguments" === type3, + "expected #{this} to be arguments but got " + type3, + "expected #{this} to not be arguments" + ); +} +__name(checkArguments, "checkArguments"); +Assertion.addProperty("arguments", checkArguments); +Assertion.addProperty("Arguments", checkArguments); +function assertEqual(val, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"); + if (flag2(this, "deep")) { + var prevLockSsfi = flag2(this, "lockSsfi"); + flag2(this, "lockSsfi", true); + this.eql(val); + flag2(this, "lockSsfi", prevLockSsfi); + } else { + this.assert( + val === obj, + "expected #{this} to equal #{exp}", + "expected #{this} to not equal #{exp}", + val, + this._obj, + true + ); + } +} +__name(assertEqual, "assertEqual"); +Assertion.addMethod("equal", assertEqual); +Assertion.addMethod("equals", assertEqual); +Assertion.addMethod("eq", assertEqual); +function assertEql(obj, msg) { + if (msg) + flag2(this, "message", msg); + var eql = flag2(this, "eql"); + this.assert( + eql(obj, flag2(this, "object")), + "expected #{this} to deeply equal #{exp}", + "expected #{this} to not deeply equal #{exp}", + obj, + this._obj, + true + ); +} +__name(assertEql, "assertEql"); +Assertion.addMethod("eql", assertEql); +Assertion.addMethod("eqls", assertEql); +function assertAbove(n, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(); + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && (objType === "date" && nType !== "date")) { + throw new AssertionError(msgPrefix + "the argument to above must be a date", void 0, ssfi); + } else if (!isNumeric(n) && (doLength || isNumeric(obj))) { + throw new AssertionError(msgPrefix + "the argument to above must be a number", void 0, ssfi); + } else if (!doLength && (objType !== "date" && !isNumeric(obj))) { + var printObj = objType === "string" ? "'" + obj + "'" : obj; + throw new AssertionError(msgPrefix + "expected " + printObj + " to be a number or a date", void 0, ssfi); + } + if (doLength) { + var descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount > n, + "expected #{this} to have a " + descriptor + " above #{exp} but got #{act}", + "expected #{this} to not have a " + descriptor + " above #{exp}", + n, + itemsCount + ); + } else { + this.assert( + obj > n, + "expected #{this} to be above #{exp}", + "expected #{this} to be at most #{exp}", + n + ); + } +} +__name(assertAbove, "assertAbove"); +Assertion.addMethod("above", assertAbove); +Assertion.addMethod("gt", assertAbove); +Assertion.addMethod("greaterThan", assertAbove); +function assertLeast(n, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(), errorMessage, shouldThrow = true; + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && (objType === "date" && nType !== "date")) { + errorMessage = msgPrefix + "the argument to least must be a date"; + } else if (!isNumeric(n) && (doLength || isNumeric(obj))) { + errorMessage = msgPrefix + "the argument to least must be a number"; + } else if (!doLength && (objType !== "date" && !isNumeric(obj))) { + var printObj = objType === "string" ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date"; + } else { + shouldThrow = false; + } + if (shouldThrow) { + throw new AssertionError(errorMessage, void 0, ssfi); + } + if (doLength) { + var descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= n, + "expected #{this} to have a " + descriptor + " at least #{exp} but got #{act}", + "expected #{this} to have a " + descriptor + " below #{exp}", + n, + itemsCount + ); + } else { + this.assert( + obj >= n, + "expected #{this} to be at least #{exp}", + "expected #{this} to be below #{exp}", + n + ); + } +} +__name(assertLeast, "assertLeast"); +Assertion.addMethod("least", assertLeast); +Assertion.addMethod("gte", assertLeast); +Assertion.addMethod("greaterThanOrEqual", assertLeast); +function assertBelow(n, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(), errorMessage, shouldThrow = true; + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && (objType === "date" && nType !== "date")) { + errorMessage = msgPrefix + "the argument to below must be a date"; + } else if (!isNumeric(n) && (doLength || isNumeric(obj))) { + errorMessage = msgPrefix + "the argument to below must be a number"; + } else if (!doLength && (objType !== "date" && !isNumeric(obj))) { + var printObj = objType === "string" ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date"; + } else { + shouldThrow = false; + } + if (shouldThrow) { + throw new AssertionError(errorMessage, void 0, ssfi); + } + if (doLength) { + var descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount < n, + "expected #{this} to have a " + descriptor + " below #{exp} but got #{act}", + "expected #{this} to not have a " + descriptor + " below #{exp}", + n, + itemsCount + ); + } else { + this.assert( + obj < n, + "expected #{this} to be below #{exp}", + "expected #{this} to be at least #{exp}", + n + ); + } +} +__name(assertBelow, "assertBelow"); +Assertion.addMethod("below", assertBelow); +Assertion.addMethod("lt", assertBelow); +Assertion.addMethod("lessThan", assertBelow); +function assertMost(n, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), nType = type(n).toLowerCase(), errorMessage, shouldThrow = true; + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && (objType === "date" && nType !== "date")) { + errorMessage = msgPrefix + "the argument to most must be a date"; + } else if (!isNumeric(n) && (doLength || isNumeric(obj))) { + errorMessage = msgPrefix + "the argument to most must be a number"; + } else if (!doLength && (objType !== "date" && !isNumeric(obj))) { + var printObj = objType === "string" ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date"; + } else { + shouldThrow = false; + } + if (shouldThrow) { + throw new AssertionError(errorMessage, void 0, ssfi); + } + if (doLength) { + var descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount <= n, + "expected #{this} to have a " + descriptor + " at most #{exp} but got #{act}", + "expected #{this} to have a " + descriptor + " above #{exp}", + n, + itemsCount + ); + } else { + this.assert( + obj <= n, + "expected #{this} to be at most #{exp}", + "expected #{this} to be above #{exp}", + n + ); + } +} +__name(assertMost, "assertMost"); +Assertion.addMethod("most", assertMost); +Assertion.addMethod("lte", assertMost); +Assertion.addMethod("lessThanOrEqual", assertMost); +Assertion.addMethod("within", function(start, finish, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"), doLength = flag2(this, "doLength"), flagMsg = flag2(this, "message"), msgPrefix = flagMsg ? flagMsg + ": " : "", ssfi = flag2(this, "ssfi"), objType = type(obj).toLowerCase(), startType = type(start).toLowerCase(), finishType = type(finish).toLowerCase(), errorMessage, shouldThrow = true, range = startType === "date" && finishType === "date" ? start.toISOString() + ".." + finish.toISOString() : start + ".." + finish; + if (doLength && objType !== "map" && objType !== "set") { + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + } + if (!doLength && (objType === "date" && (startType !== "date" || finishType !== "date"))) { + errorMessage = msgPrefix + "the arguments to within must be dates"; + } else if ((!isNumeric(start) || !isNumeric(finish)) && (doLength || isNumeric(obj))) { + errorMessage = msgPrefix + "the arguments to within must be numbers"; + } else if (!doLength && (objType !== "date" && !isNumeric(obj))) { + var printObj = objType === "string" ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + "expected " + printObj + " to be a number or a date"; + } else { + shouldThrow = false; + } + if (shouldThrow) { + throw new AssertionError(errorMessage, void 0, ssfi); + } + if (doLength) { + var descriptor = "length", itemsCount; + if (objType === "map" || objType === "set") { + descriptor = "size"; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= start && itemsCount <= finish, + "expected #{this} to have a " + descriptor + " within " + range, + "expected #{this} to not have a " + descriptor + " within " + range + ); + } else { + this.assert( + obj >= start && obj <= finish, + "expected #{this} to be within " + range, + "expected #{this} to not be within " + range + ); + } +}); +function assertInstanceOf(constructor, msg) { + if (msg) + flag2(this, "message", msg); + var target = flag2(this, "object"); + var ssfi = flag2(this, "ssfi"); + var flagMsg = flag2(this, "message"); + try { + var isInstanceOf = target instanceof constructor; + } catch (err) { + if (err instanceof TypeError) { + flagMsg = flagMsg ? flagMsg + ": " : ""; + throw new AssertionError( + flagMsg + "The instanceof assertion needs a constructor but " + type(constructor) + " was given.", + void 0, + ssfi + ); + } + throw err; + } + var name = getName(constructor); + if (name == null) { + name = "an unnamed constructor"; + } + this.assert( + isInstanceOf, + "expected #{this} to be an instance of " + name, + "expected #{this} to not be an instance of " + name + ); +} +__name(assertInstanceOf, "assertInstanceOf"); +Assertion.addMethod("instanceof", assertInstanceOf); +Assertion.addMethod("instanceOf", assertInstanceOf); +function assertProperty(name, val, msg) { + if (msg) + flag2(this, "message", msg); + var isNested = flag2(this, "nested"), isOwn = flag2(this, "own"), flagMsg = flag2(this, "message"), obj = flag2(this, "object"), ssfi = flag2(this, "ssfi"), nameType = typeof name; + flagMsg = flagMsg ? flagMsg + ": " : ""; + if (isNested) { + if (nameType !== "string") { + throw new AssertionError( + flagMsg + "the argument to property must be a string when using nested syntax", + void 0, + ssfi + ); + } + } else { + if (nameType !== "string" && nameType !== "number" && nameType !== "symbol") { + throw new AssertionError( + flagMsg + "the argument to property must be a string, number, or symbol", + void 0, + ssfi + ); + } + } + if (isNested && isOwn) { + throw new AssertionError( + flagMsg + 'The "nested" and "own" flags cannot be combined.', + void 0, + ssfi + ); + } + if (obj === null || obj === void 0) { + throw new AssertionError( + flagMsg + "Target cannot be null or undefined.", + void 0, + ssfi + ); + } + var isDeep = flag2(this, "deep"), negate = flag2(this, "negate"), pathInfo = isNested ? getPathInfo(obj, name) : null, value = isNested ? pathInfo.value : obj[name], isEql = isDeep ? flag2(this, "eql") : (val1, val2) => val1 === val2; + var descriptor = ""; + if (isDeep) + descriptor += "deep "; + if (isOwn) + descriptor += "own "; + if (isNested) + descriptor += "nested "; + descriptor += "property "; + var hasProperty2; + if (isOwn) + hasProperty2 = Object.prototype.hasOwnProperty.call(obj, name); + else if (isNested) + hasProperty2 = pathInfo.exists; + else + hasProperty2 = hasProperty(obj, name); + if (!negate || arguments.length === 1) { + this.assert( + hasProperty2, + "expected #{this} to have " + descriptor + inspect2(name), + "expected #{this} to not have " + descriptor + inspect2(name) + ); + } + if (arguments.length > 1) { + this.assert( + hasProperty2 && isEql(val, value), + "expected #{this} to have " + descriptor + inspect2(name) + " of #{exp}, but got #{act}", + "expected #{this} to not have " + descriptor + inspect2(name) + " of #{act}", + val, + value + ); + } + flag2(this, "object", value); +} +__name(assertProperty, "assertProperty"); +Assertion.addMethod("property", assertProperty); +function assertOwnProperty(name, value, msg) { + flag2(this, "own", true); + assertProperty.apply(this, arguments); +} +__name(assertOwnProperty, "assertOwnProperty"); +Assertion.addMethod("ownProperty", assertOwnProperty); +Assertion.addMethod("haveOwnProperty", assertOwnProperty); +function assertOwnPropertyDescriptor(name, descriptor, msg) { + if (typeof descriptor === "string") { + msg = descriptor; + descriptor = null; + } + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"); + var actualDescriptor = Object.getOwnPropertyDescriptor(Object(obj), name); + var eql = flag2(this, "eql"); + if (actualDescriptor && descriptor) { + this.assert( + eql(descriptor, actualDescriptor), + "expected the own property descriptor for " + inspect2(name) + " on #{this} to match " + inspect2(descriptor) + ", got " + inspect2(actualDescriptor), + "expected the own property descriptor for " + inspect2(name) + " on #{this} to not match " + inspect2(descriptor), + descriptor, + actualDescriptor, + true + ); + } else { + this.assert( + actualDescriptor, + "expected #{this} to have an own property descriptor for " + inspect2(name), + "expected #{this} to not have an own property descriptor for " + inspect2(name) + ); + } + flag2(this, "object", actualDescriptor); +} +__name(assertOwnPropertyDescriptor, "assertOwnPropertyDescriptor"); +Assertion.addMethod("ownPropertyDescriptor", assertOwnPropertyDescriptor); +Assertion.addMethod("haveOwnPropertyDescriptor", assertOwnPropertyDescriptor); +function assertLengthChain() { + flag2(this, "doLength", true); +} +__name(assertLengthChain, "assertLengthChain"); +function assertLength(n, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"), objType = type(obj).toLowerCase(), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"), descriptor = "length", itemsCount; + switch (objType) { + case "map": + case "set": + descriptor = "size"; + itemsCount = obj.size; + break; + default: + new Assertion(obj, flagMsg, ssfi, true).to.have.property("length"); + itemsCount = obj.length; + } + this.assert( + itemsCount == n, + "expected #{this} to have a " + descriptor + " of #{exp} but got #{act}", + "expected #{this} to not have a " + descriptor + " of #{act}", + n, + itemsCount + ); +} +__name(assertLength, "assertLength"); +Assertion.addChainableMethod("length", assertLength, assertLengthChain); +Assertion.addChainableMethod("lengthOf", assertLength, assertLengthChain); +function assertMatch(re, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"); + this.assert( + re.exec(obj), + "expected #{this} to match " + re, + "expected #{this} not to match " + re + ); +} +__name(assertMatch, "assertMatch"); +Assertion.addMethod("match", assertMatch); +Assertion.addMethod("matches", assertMatch); +Assertion.addMethod("string", function(str, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(obj, flagMsg, ssfi, true).is.a("string"); + this.assert( + ~obj.indexOf(str), + "expected #{this} to contain " + inspect2(str), + "expected #{this} to not contain " + inspect2(str) + ); +}); +function assertKeys(keys) { + var obj = flag2(this, "object"), objType = type(obj), keysType = type(keys), ssfi = flag2(this, "ssfi"), isDeep = flag2(this, "deep"), str, deepStr = "", actual, ok = true, flagMsg = flag2(this, "message"); + flagMsg = flagMsg ? flagMsg + ": " : ""; + var mixedArgsMsg = flagMsg + "when testing keys against an object or an array you must give a single Array|Object|String argument or multiple String arguments"; + if (objType === "Map" || objType === "Set") { + deepStr = isDeep ? "deeply " : ""; + actual = []; + obj.forEach(function(val, key) { + actual.push(key); + }); + if (keysType !== "Array") { + keys = Array.prototype.slice.call(arguments); + } + } else { + actual = getOwnEnumerableProperties(obj); + switch (keysType) { + case "Array": + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, void 0, ssfi); + } + break; + case "Object": + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, void 0, ssfi); + } + keys = Object.keys(keys); + break; + default: + keys = Array.prototype.slice.call(arguments); + } + keys = keys.map(function(val) { + return typeof val === "symbol" ? val : String(val); + }); + } + if (!keys.length) { + throw new AssertionError(flagMsg + "keys required", void 0, ssfi); + } + var len = keys.length, any = flag2(this, "any"), all = flag2(this, "all"), expected = keys, isEql = isDeep ? flag2(this, "eql") : (val1, val2) => val1 === val2; + if (!any && !all) { + all = true; + } + if (any) { + ok = expected.some(function(expectedKey) { + return actual.some(function(actualKey) { + return isEql(expectedKey, actualKey); + }); + }); + } + if (all) { + ok = expected.every(function(expectedKey) { + return actual.some(function(actualKey) { + return isEql(expectedKey, actualKey); + }); + }); + if (!flag2(this, "contains")) { + ok = ok && keys.length == actual.length; + } + } + if (len > 1) { + keys = keys.map(function(key) { + return inspect2(key); + }); + var last = keys.pop(); + if (all) { + str = keys.join(", ") + ", and " + last; + } + if (any) { + str = keys.join(", ") + ", or " + last; + } + } else { + str = inspect2(keys[0]); + } + str = (len > 1 ? "keys " : "key ") + str; + str = (flag2(this, "contains") ? "contain " : "have ") + str; + this.assert( + ok, + "expected #{this} to " + deepStr + str, + "expected #{this} to not " + deepStr + str, + expected.slice(0).sort(compareByInspect), + actual.sort(compareByInspect), + true + ); +} +__name(assertKeys, "assertKeys"); +Assertion.addMethod("keys", assertKeys); +Assertion.addMethod("key", assertKeys); +function assertThrows(errorLike, errMsgMatcher, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"), ssfi = flag2(this, "ssfi"), flagMsg = flag2(this, "message"), negate = flag2(this, "negate") || false; + new Assertion(obj, flagMsg, ssfi, true).is.a("function"); + if (isRegExp2(errorLike) || typeof errorLike === "string") { + errMsgMatcher = errorLike; + errorLike = null; + } + let caughtErr; + let errorWasThrown = false; + try { + obj(); + } catch (err) { + errorWasThrown = true; + caughtErr = err; + } + var everyArgIsUndefined = errorLike === void 0 && errMsgMatcher === void 0; + var everyArgIsDefined = Boolean(errorLike && errMsgMatcher); + var errorLikeFail = false; + var errMsgMatcherFail = false; + if (everyArgIsUndefined || !everyArgIsUndefined && !negate) { + var errorLikeString = "an error"; + if (errorLike instanceof Error) { + errorLikeString = "#{exp}"; + } else if (errorLike) { + errorLikeString = check_error_exports.getConstructorName(errorLike); + } + let actual = caughtErr; + if (caughtErr instanceof Error) { + actual = caughtErr.toString(); + } else if (typeof caughtErr === "string") { + actual = caughtErr; + } else if (caughtErr && (typeof caughtErr === "object" || typeof caughtErr === "function")) { + try { + actual = check_error_exports.getConstructorName(caughtErr); + } catch (_err) { + } + } + this.assert( + errorWasThrown, + "expected #{this} to throw " + errorLikeString, + "expected #{this} to not throw an error but #{act} was thrown", + errorLike && errorLike.toString(), + actual + ); + } + if (errorLike && caughtErr) { + if (errorLike instanceof Error) { + var isCompatibleInstance = check_error_exports.compatibleInstance(caughtErr, errorLike); + if (isCompatibleInstance === negate) { + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate, + "expected #{this} to throw #{exp} but #{act} was thrown", + "expected #{this} to not throw #{exp}" + (caughtErr && !negate ? " but #{act} was thrown" : ""), + errorLike.toString(), + caughtErr.toString() + ); + } + } + } + var isCompatibleConstructor = check_error_exports.compatibleConstructor(caughtErr, errorLike); + if (isCompatibleConstructor === negate) { + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate, + "expected #{this} to throw #{exp} but #{act} was thrown", + "expected #{this} to not throw #{exp}" + (caughtErr ? " but #{act} was thrown" : ""), + errorLike instanceof Error ? errorLike.toString() : errorLike && check_error_exports.getConstructorName(errorLike), + caughtErr instanceof Error ? caughtErr.toString() : caughtErr && check_error_exports.getConstructorName(caughtErr) + ); + } + } + } + if (caughtErr && errMsgMatcher !== void 0 && errMsgMatcher !== null) { + var placeholder = "including"; + if (isRegExp2(errMsgMatcher)) { + placeholder = "matching"; + } + var isCompatibleMessage = check_error_exports.compatibleMessage(caughtErr, errMsgMatcher); + if (isCompatibleMessage === negate) { + if (everyArgIsDefined && negate) { + errMsgMatcherFail = true; + } else { + this.assert( + negate, + "expected #{this} to throw error " + placeholder + " #{exp} but got #{act}", + "expected #{this} to throw error not " + placeholder + " #{exp}", + errMsgMatcher, + check_error_exports.getMessage(caughtErr) + ); + } + } + } + if (errorLikeFail && errMsgMatcherFail) { + this.assert( + negate, + "expected #{this} to throw #{exp} but #{act} was thrown", + "expected #{this} to not throw #{exp}" + (caughtErr ? " but #{act} was thrown" : ""), + errorLike instanceof Error ? errorLike.toString() : errorLike && check_error_exports.getConstructorName(errorLike), + caughtErr instanceof Error ? caughtErr.toString() : caughtErr && check_error_exports.getConstructorName(caughtErr) + ); + } + flag2(this, "object", caughtErr); +} +__name(assertThrows, "assertThrows"); +Assertion.addMethod("throw", assertThrows); +Assertion.addMethod("throws", assertThrows); +Assertion.addMethod("Throw", assertThrows); +function respondTo(method, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"), itself = flag2(this, "itself"), context = "function" === typeof obj && !itself ? obj.prototype[method] : obj[method]; + this.assert( + "function" === typeof context, + "expected #{this} to respond to " + inspect2(method), + "expected #{this} to not respond to " + inspect2(method) + ); +} +__name(respondTo, "respondTo"); +Assertion.addMethod("respondTo", respondTo); +Assertion.addMethod("respondsTo", respondTo); +Assertion.addProperty("itself", function() { + flag2(this, "itself", true); +}); +function satisfy(matcher, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"); + var result = matcher(obj); + this.assert( + result, + "expected #{this} to satisfy " + objDisplay(matcher), + "expected #{this} to not satisfy" + objDisplay(matcher), + flag2(this, "negate") ? false : true, + result + ); +} +__name(satisfy, "satisfy"); +Assertion.addMethod("satisfy", satisfy); +Assertion.addMethod("satisfies", satisfy); +function closeTo(expected, delta, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(obj, flagMsg, ssfi, true).is.numeric; + let message = "A `delta` value is required for `closeTo`"; + if (delta == void 0) + throw new AssertionError(flagMsg ? `${flagMsg}: ${message}` : message, void 0, ssfi); + new Assertion(delta, flagMsg, ssfi, true).is.numeric; + message = "A `expected` value is required for `closeTo`"; + if (expected == void 0) + throw new AssertionError(flagMsg ? `${flagMsg}: ${message}` : message, void 0, ssfi); + new Assertion(expected, flagMsg, ssfi, true).is.numeric; + const abs = /* @__PURE__ */ __name((x) => x < 0n ? -x : x, "abs"); + this.assert( + abs(obj - expected) <= delta, + "expected #{this} to be close to " + expected + " +/- " + delta, + "expected #{this} not to be close to " + expected + " +/- " + delta + ); +} +__name(closeTo, "closeTo"); +Assertion.addMethod("closeTo", closeTo); +Assertion.addMethod("approximately", closeTo); +function isSubsetOf(_subset, _superset, cmp, contains, ordered) { + let superset = Array.from(_superset); + let subset = Array.from(_subset); + if (!contains) { + if (subset.length !== superset.length) + return false; + superset = superset.slice(); + } + return subset.every(function(elem, idx) { + if (ordered) + return cmp ? cmp(elem, superset[idx]) : elem === superset[idx]; + if (!cmp) { + var matchIdx = superset.indexOf(elem); + if (matchIdx === -1) + return false; + if (!contains) + superset.splice(matchIdx, 1); + return true; + } + return superset.some(function(elem2, matchIdx2) { + if (!cmp(elem, elem2)) + return false; + if (!contains) + superset.splice(matchIdx2, 1); + return true; + }); + }); +} +__name(isSubsetOf, "isSubsetOf"); +Assertion.addMethod("members", function(subset, msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(obj, flagMsg, ssfi, true).to.be.iterable; + new Assertion(subset, flagMsg, ssfi, true).to.be.iterable; + var contains = flag2(this, "contains"); + var ordered = flag2(this, "ordered"); + var subject, failMsg, failNegateMsg; + if (contains) { + subject = ordered ? "an ordered superset" : "a superset"; + failMsg = "expected #{this} to be " + subject + " of #{exp}"; + failNegateMsg = "expected #{this} to not be " + subject + " of #{exp}"; + } else { + subject = ordered ? "ordered members" : "members"; + failMsg = "expected #{this} to have the same " + subject + " as #{exp}"; + failNegateMsg = "expected #{this} to not have the same " + subject + " as #{exp}"; + } + var cmp = flag2(this, "deep") ? flag2(this, "eql") : void 0; + this.assert( + isSubsetOf(subset, obj, cmp, contains, ordered), + failMsg, + failNegateMsg, + subset, + obj, + true + ); +}); +Assertion.addProperty("iterable", function(msg) { + if (msg) + flag2(this, "message", msg); + var obj = flag2(this, "object"); + this.assert( + obj != void 0 && obj[Symbol.iterator], + "expected #{this} to be an iterable", + "expected #{this} to not be an iterable", + obj + ); +}); +function oneOf(list, msg) { + if (msg) + flag2(this, "message", msg); + var expected = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"), contains = flag2(this, "contains"), isDeep = flag2(this, "deep"), eql = flag2(this, "eql"); + new Assertion(list, flagMsg, ssfi, true).to.be.an("array"); + if (contains) { + this.assert( + list.some(function(possibility) { + return expected.indexOf(possibility) > -1; + }), + "expected #{this} to contain one of #{exp}", + "expected #{this} to not contain one of #{exp}", + list, + expected + ); + } else { + if (isDeep) { + this.assert( + list.some(function(possibility) { + return eql(expected, possibility); + }), + "expected #{this} to deeply equal one of #{exp}", + "expected #{this} to deeply equal one of #{exp}", + list, + expected + ); + } else { + this.assert( + list.indexOf(expected) > -1, + "expected #{this} to be one of #{exp}", + "expected #{this} to not be one of #{exp}", + list, + expected + ); + } + } +} +__name(oneOf, "oneOf"); +Assertion.addMethod("oneOf", oneOf); +function assertChanges(subject, prop, msg) { + if (msg) + flag2(this, "message", msg); + var fn = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(fn, flagMsg, ssfi, true).is.a("function"); + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a("function"); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + fn(); + var final = prop === void 0 || prop === null ? subject() : subject[prop]; + var msgObj = prop === void 0 || prop === null ? initial : "." + prop; + flag2(this, "deltaMsgObj", msgObj); + flag2(this, "initialDeltaValue", initial); + flag2(this, "finalDeltaValue", final); + flag2(this, "deltaBehavior", "change"); + flag2(this, "realDelta", final !== initial); + this.assert( + initial !== final, + "expected " + msgObj + " to change", + "expected " + msgObj + " to not change" + ); +} +__name(assertChanges, "assertChanges"); +Assertion.addMethod("change", assertChanges); +Assertion.addMethod("changes", assertChanges); +function assertIncreases(subject, prop, msg) { + if (msg) + flag2(this, "message", msg); + var fn = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(fn, flagMsg, ssfi, true).is.a("function"); + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a("function"); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + new Assertion(initial, flagMsg, ssfi, true).is.a("number"); + fn(); + var final = prop === void 0 || prop === null ? subject() : subject[prop]; + var msgObj = prop === void 0 || prop === null ? initial : "." + prop; + flag2(this, "deltaMsgObj", msgObj); + flag2(this, "initialDeltaValue", initial); + flag2(this, "finalDeltaValue", final); + flag2(this, "deltaBehavior", "increase"); + flag2(this, "realDelta", final - initial); + this.assert( + final - initial > 0, + "expected " + msgObj + " to increase", + "expected " + msgObj + " to not increase" + ); +} +__name(assertIncreases, "assertIncreases"); +Assertion.addMethod("increase", assertIncreases); +Assertion.addMethod("increases", assertIncreases); +function assertDecreases(subject, prop, msg) { + if (msg) + flag2(this, "message", msg); + var fn = flag2(this, "object"), flagMsg = flag2(this, "message"), ssfi = flag2(this, "ssfi"); + new Assertion(fn, flagMsg, ssfi, true).is.a("function"); + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a("function"); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + new Assertion(initial, flagMsg, ssfi, true).is.a("number"); + fn(); + var final = prop === void 0 || prop === null ? subject() : subject[prop]; + var msgObj = prop === void 0 || prop === null ? initial : "." + prop; + flag2(this, "deltaMsgObj", msgObj); + flag2(this, "initialDeltaValue", initial); + flag2(this, "finalDeltaValue", final); + flag2(this, "deltaBehavior", "decrease"); + flag2(this, "realDelta", initial - final); + this.assert( + final - initial < 0, + "expected " + msgObj + " to decrease", + "expected " + msgObj + " to not decrease" + ); +} +__name(assertDecreases, "assertDecreases"); +Assertion.addMethod("decrease", assertDecreases); +Assertion.addMethod("decreases", assertDecreases); +function assertDelta(delta, msg) { + if (msg) + flag2(this, "message", msg); + var msgObj = flag2(this, "deltaMsgObj"); + var initial = flag2(this, "initialDeltaValue"); + var final = flag2(this, "finalDeltaValue"); + var behavior = flag2(this, "deltaBehavior"); + var realDelta = flag2(this, "realDelta"); + var expression; + if (behavior === "change") { + expression = Math.abs(final - initial) === Math.abs(delta); + } else { + expression = realDelta === Math.abs(delta); + } + this.assert( + expression, + "expected " + msgObj + " to " + behavior + " by " + delta, + "expected " + msgObj + " to not " + behavior + " by " + delta + ); +} +__name(assertDelta, "assertDelta"); +Assertion.addMethod("by", assertDelta); +Assertion.addProperty("extensible", function() { + var obj = flag2(this, "object"); + var isExtensible = obj === Object(obj) && Object.isExtensible(obj); + this.assert( + isExtensible, + "expected #{this} to be extensible", + "expected #{this} to not be extensible" + ); +}); +Assertion.addProperty("sealed", function() { + var obj = flag2(this, "object"); + var isSealed = obj === Object(obj) ? Object.isSealed(obj) : true; + this.assert( + isSealed, + "expected #{this} to be sealed", + "expected #{this} to not be sealed" + ); +}); +Assertion.addProperty("frozen", function() { + var obj = flag2(this, "object"); + var isFrozen = obj === Object(obj) ? Object.isFrozen(obj) : true; + this.assert( + isFrozen, + "expected #{this} to be frozen", + "expected #{this} to not be frozen" + ); +}); +Assertion.addProperty("finite", function(msg) { + var obj = flag2(this, "object"); + this.assert( + typeof obj === "number" && isFinite(obj), + "expected #{this} to be a finite number", + "expected #{this} to not be a finite number" + ); +}); + +// lib/chai/interface/expect.js +function expect(val, message) { + return new Assertion(val, message); +} +__name(expect, "expect"); +expect.fail = function(actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = void 0; + } + message = message || "expect.fail()"; + throw new AssertionError(message, { + actual, + expected, + operator + }, expect.fail); +}; + +// lib/chai/interface/should.js +var should_exports = {}; +__export(should_exports, { + Should: () => Should, + should: () => should +}); +function loadShould() { + function shouldGetter() { + if (this instanceof String || this instanceof Number || this instanceof Boolean || typeof Symbol === "function" && this instanceof Symbol || typeof BigInt === "function" && this instanceof BigInt) { + return new Assertion(this.valueOf(), null, shouldGetter); + } + return new Assertion(this, null, shouldGetter); + } + __name(shouldGetter, "shouldGetter"); + function shouldSetter(value) { + Object.defineProperty(this, "should", { + value, + enumerable: true, + configurable: true, + writable: true + }); + } + __name(shouldSetter, "shouldSetter"); + Object.defineProperty(Object.prototype, "should", { + set: shouldSetter, + get: shouldGetter, + configurable: true + }); + var should2 = {}; + should2.fail = function(actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = void 0; + } + message = message || "should.fail()"; + throw new AssertionError(message, { + actual, + expected, + operator + }, should2.fail); + }; + should2.equal = function(actual, expected, message) { + new Assertion(actual, message).to.equal(expected); + }; + should2.Throw = function(fn, errt, errs, msg) { + new Assertion(fn, msg).to.Throw(errt, errs); + }; + should2.exist = function(val, msg) { + new Assertion(val, msg).to.exist; + }; + should2.not = {}; + should2.not.equal = function(actual, expected, msg) { + new Assertion(actual, msg).to.not.equal(expected); + }; + should2.not.Throw = function(fn, errt, errs, msg) { + new Assertion(fn, msg).to.not.Throw(errt, errs); + }; + should2.not.exist = function(val, msg) { + new Assertion(val, msg).to.not.exist; + }; + should2["throw"] = should2["Throw"]; + should2.not["throw"] = should2.not["Throw"]; + return should2; +} +__name(loadShould, "loadShould"); +var should = loadShould; +var Should = loadShould; + +// lib/chai/interface/assert.js +function assert(express, errmsg) { + var test2 = new Assertion(null, null, assert, true); + test2.assert( + express, + errmsg, + "[ negation message unavailable ]" + ); +} +__name(assert, "assert"); +assert.fail = function(actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = void 0; + } + message = message || "assert.fail()"; + throw new AssertionError(message, { + actual, + expected, + operator + }, assert.fail); +}; +assert.isOk = function(val, msg) { + new Assertion(val, msg, assert.isOk, true).is.ok; +}; +assert.isNotOk = function(val, msg) { + new Assertion(val, msg, assert.isNotOk, true).is.not.ok; +}; +assert.equal = function(act, exp, msg) { + var test2 = new Assertion(act, msg, assert.equal, true); + test2.assert( + exp == flag(test2, "object"), + "expected #{this} to equal #{exp}", + "expected #{this} to not equal #{act}", + exp, + act, + true + ); +}; +assert.notEqual = function(act, exp, msg) { + var test2 = new Assertion(act, msg, assert.notEqual, true); + test2.assert( + exp != flag(test2, "object"), + "expected #{this} to not equal #{exp}", + "expected #{this} to equal #{act}", + exp, + act, + true + ); +}; +assert.strictEqual = function(act, exp, msg) { + new Assertion(act, msg, assert.strictEqual, true).to.equal(exp); +}; +assert.notStrictEqual = function(act, exp, msg) { + new Assertion(act, msg, assert.notStrictEqual, true).to.not.equal(exp); +}; +assert.deepEqual = assert.deepStrictEqual = function(act, exp, msg) { + new Assertion(act, msg, assert.deepEqual, true).to.eql(exp); +}; +assert.notDeepEqual = function(act, exp, msg) { + new Assertion(act, msg, assert.notDeepEqual, true).to.not.eql(exp); +}; +assert.isAbove = function(val, abv, msg) { + new Assertion(val, msg, assert.isAbove, true).to.be.above(abv); +}; +assert.isAtLeast = function(val, atlst, msg) { + new Assertion(val, msg, assert.isAtLeast, true).to.be.least(atlst); +}; +assert.isBelow = function(val, blw, msg) { + new Assertion(val, msg, assert.isBelow, true).to.be.below(blw); +}; +assert.isAtMost = function(val, atmst, msg) { + new Assertion(val, msg, assert.isAtMost, true).to.be.most(atmst); +}; +assert.isTrue = function(val, msg) { + new Assertion(val, msg, assert.isTrue, true).is["true"]; +}; +assert.isNotTrue = function(val, msg) { + new Assertion(val, msg, assert.isNotTrue, true).to.not.equal(true); +}; +assert.isFalse = function(val, msg) { + new Assertion(val, msg, assert.isFalse, true).is["false"]; +}; +assert.isNotFalse = function(val, msg) { + new Assertion(val, msg, assert.isNotFalse, true).to.not.equal(false); +}; +assert.isNull = function(val, msg) { + new Assertion(val, msg, assert.isNull, true).to.equal(null); +}; +assert.isNotNull = function(val, msg) { + new Assertion(val, msg, assert.isNotNull, true).to.not.equal(null); +}; +assert.isNaN = function(val, msg) { + new Assertion(val, msg, assert.isNaN, true).to.be.NaN; +}; +assert.isNotNaN = function(value, message) { + new Assertion(value, message, assert.isNotNaN, true).not.to.be.NaN; +}; +assert.exists = function(val, msg) { + new Assertion(val, msg, assert.exists, true).to.exist; +}; +assert.notExists = function(val, msg) { + new Assertion(val, msg, assert.notExists, true).to.not.exist; +}; +assert.isUndefined = function(val, msg) { + new Assertion(val, msg, assert.isUndefined, true).to.equal(void 0); +}; +assert.isDefined = function(val, msg) { + new Assertion(val, msg, assert.isDefined, true).to.not.equal(void 0); +}; +assert.isCallable = function(value, message) { + new Assertion(value, message, assert.isCallable, true).is.callable; +}; +assert.isNotCallable = function(value, message) { + new Assertion(value, message, assert.isNotCallable, true).is.not.callable; +}; +assert.isObject = function(val, msg) { + new Assertion(val, msg, assert.isObject, true).to.be.a("object"); +}; +assert.isNotObject = function(val, msg) { + new Assertion(val, msg, assert.isNotObject, true).to.not.be.a("object"); +}; +assert.isArray = function(val, msg) { + new Assertion(val, msg, assert.isArray, true).to.be.an("array"); +}; +assert.isNotArray = function(val, msg) { + new Assertion(val, msg, assert.isNotArray, true).to.not.be.an("array"); +}; +assert.isString = function(val, msg) { + new Assertion(val, msg, assert.isString, true).to.be.a("string"); +}; +assert.isNotString = function(val, msg) { + new Assertion(val, msg, assert.isNotString, true).to.not.be.a("string"); +}; +assert.isNumber = function(val, msg) { + new Assertion(val, msg, assert.isNumber, true).to.be.a("number"); +}; +assert.isNotNumber = function(val, msg) { + new Assertion(val, msg, assert.isNotNumber, true).to.not.be.a("number"); +}; +assert.isNumeric = function(val, msg) { + new Assertion(val, msg, assert.isNumeric, true).is.numeric; +}; +assert.isNotNumeric = function(val, msg) { + new Assertion(val, msg, assert.isNotNumeric, true).is.not.numeric; +}; +assert.isFinite = function(val, msg) { + new Assertion(val, msg, assert.isFinite, true).to.be.finite; +}; +assert.isBoolean = function(val, msg) { + new Assertion(val, msg, assert.isBoolean, true).to.be.a("boolean"); +}; +assert.isNotBoolean = function(val, msg) { + new Assertion(val, msg, assert.isNotBoolean, true).to.not.be.a("boolean"); +}; +assert.typeOf = function(val, type3, msg) { + new Assertion(val, msg, assert.typeOf, true).to.be.a(type3); +}; +assert.notTypeOf = function(value, type3, message) { + new Assertion(value, message, assert.notTypeOf, true).to.not.be.a(type3); +}; +assert.instanceOf = function(val, type3, msg) { + new Assertion(val, msg, assert.instanceOf, true).to.be.instanceOf(type3); +}; +assert.notInstanceOf = function(val, type3, msg) { + new Assertion(val, msg, assert.notInstanceOf, true).to.not.be.instanceOf(type3); +}; +assert.include = function(exp, inc, msg) { + new Assertion(exp, msg, assert.include, true).include(inc); +}; +assert.notInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notInclude, true).not.include(inc); +}; +assert.deepInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepInclude, true).deep.include(inc); +}; +assert.notDeepInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepInclude, true).not.deep.include(inc); +}; +assert.nestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.nestedInclude, true).nested.include(inc); +}; +assert.notNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notNestedInclude, true).not.nested.include(inc); +}; +assert.deepNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepNestedInclude, true).deep.nested.include(inc); +}; +assert.notDeepNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepNestedInclude, true).not.deep.nested.include(inc); +}; +assert.ownInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.ownInclude, true).own.include(inc); +}; +assert.notOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notOwnInclude, true).not.own.include(inc); +}; +assert.deepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepOwnInclude, true).deep.own.include(inc); +}; +assert.notDeepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepOwnInclude, true).not.deep.own.include(inc); +}; +assert.match = function(exp, re, msg) { + new Assertion(exp, msg, assert.match, true).to.match(re); +}; +assert.notMatch = function(exp, re, msg) { + new Assertion(exp, msg, assert.notMatch, true).to.not.match(re); +}; +assert.property = function(obj, prop, msg) { + new Assertion(obj, msg, assert.property, true).to.have.property(prop); +}; +assert.notProperty = function(obj, prop, msg) { + new Assertion(obj, msg, assert.notProperty, true).to.not.have.property(prop); +}; +assert.propertyVal = function(obj, prop, val, msg) { + new Assertion(obj, msg, assert.propertyVal, true).to.have.property(prop, val); +}; +assert.notPropertyVal = function(obj, prop, val, msg) { + new Assertion(obj, msg, assert.notPropertyVal, true).to.not.have.property(prop, val); +}; +assert.deepPropertyVal = function(obj, prop, val, msg) { + new Assertion(obj, msg, assert.deepPropertyVal, true).to.have.deep.property(prop, val); +}; +assert.notDeepPropertyVal = function(obj, prop, val, msg) { + new Assertion(obj, msg, assert.notDeepPropertyVal, true).to.not.have.deep.property(prop, val); +}; +assert.ownProperty = function(obj, prop, msg) { + new Assertion(obj, msg, assert.ownProperty, true).to.have.own.property(prop); +}; +assert.notOwnProperty = function(obj, prop, msg) { + new Assertion(obj, msg, assert.notOwnProperty, true).to.not.have.own.property(prop); +}; +assert.ownPropertyVal = function(obj, prop, value, msg) { + new Assertion(obj, msg, assert.ownPropertyVal, true).to.have.own.property(prop, value); +}; +assert.notOwnPropertyVal = function(obj, prop, value, msg) { + new Assertion(obj, msg, assert.notOwnPropertyVal, true).to.not.have.own.property(prop, value); +}; +assert.deepOwnPropertyVal = function(obj, prop, value, msg) { + new Assertion(obj, msg, assert.deepOwnPropertyVal, true).to.have.deep.own.property(prop, value); +}; +assert.notDeepOwnPropertyVal = function(obj, prop, value, msg) { + new Assertion(obj, msg, assert.notDeepOwnPropertyVal, true).to.not.have.deep.own.property(prop, value); +}; +assert.nestedProperty = function(obj, prop, msg) { + new Assertion(obj, msg, assert.nestedProperty, true).to.have.nested.property(prop); +}; +assert.notNestedProperty = function(obj, prop, msg) { + new Assertion(obj, msg, assert.notNestedProperty, true).to.not.have.nested.property(prop); +}; +assert.nestedPropertyVal = function(obj, prop, val, msg) { + new Assertion(obj, msg, assert.nestedPropertyVal, true).to.have.nested.property(prop, val); +}; +assert.notNestedPropertyVal = function(obj, prop, val, msg) { + new Assertion(obj, msg, assert.notNestedPropertyVal, true).to.not.have.nested.property(prop, val); +}; +assert.deepNestedPropertyVal = function(obj, prop, val, msg) { + new Assertion(obj, msg, assert.deepNestedPropertyVal, true).to.have.deep.nested.property(prop, val); +}; +assert.notDeepNestedPropertyVal = function(obj, prop, val, msg) { + new Assertion(obj, msg, assert.notDeepNestedPropertyVal, true).to.not.have.deep.nested.property(prop, val); +}; +assert.lengthOf = function(exp, len, msg) { + new Assertion(exp, msg, assert.lengthOf, true).to.have.lengthOf(len); +}; +assert.hasAnyKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyKeys, true).to.have.any.keys(keys); +}; +assert.hasAllKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllKeys, true).to.have.all.keys(keys); +}; +assert.containsAllKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.containsAllKeys, true).to.contain.all.keys(keys); +}; +assert.doesNotHaveAnyKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAnyKeys, true).to.not.have.any.keys(keys); +}; +assert.doesNotHaveAllKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAllKeys, true).to.not.have.all.keys(keys); +}; +assert.hasAnyDeepKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyDeepKeys, true).to.have.any.deep.keys(keys); +}; +assert.hasAllDeepKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllDeepKeys, true).to.have.all.deep.keys(keys); +}; +assert.containsAllDeepKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.containsAllDeepKeys, true).to.contain.all.deep.keys(keys); +}; +assert.doesNotHaveAnyDeepKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAnyDeepKeys, true).to.not.have.any.deep.keys(keys); +}; +assert.doesNotHaveAllDeepKeys = function(obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAllDeepKeys, true).to.not.have.all.deep.keys(keys); +}; +assert.throws = function(fn, errorLike, errMsgMatcher, msg) { + if ("string" === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + var assertErr = new Assertion(fn, msg, assert.throws, true).to.throw(errorLike, errMsgMatcher); + return flag(assertErr, "object"); +}; +assert.doesNotThrow = function(fn, errorLike, errMsgMatcher, message) { + if ("string" === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + new Assertion(fn, message, assert.doesNotThrow, true).to.not.throw(errorLike, errMsgMatcher); +}; +assert.operator = function(val, operator, val2, msg) { + var ok; + switch (operator) { + case "==": + ok = val == val2; + break; + case "===": + ok = val === val2; + break; + case ">": + ok = val > val2; + break; + case ">=": + ok = val >= val2; + break; + case "<": + ok = val < val2; + break; + case "<=": + ok = val <= val2; + break; + case "!=": + ok = val != val2; + break; + case "!==": + ok = val !== val2; + break; + default: + msg = msg ? msg + ": " : msg; + throw new AssertionError( + msg + 'Invalid operator "' + operator + '"', + void 0, + assert.operator + ); + } + var test2 = new Assertion(ok, msg, assert.operator, true); + test2.assert( + true === flag(test2, "object"), + "expected " + inspect2(val) + " to be " + operator + " " + inspect2(val2), + "expected " + inspect2(val) + " to not be " + operator + " " + inspect2(val2) + ); +}; +assert.closeTo = function(act, exp, delta, msg) { + new Assertion(act, msg, assert.closeTo, true).to.be.closeTo(exp, delta); +}; +assert.approximately = function(act, exp, delta, msg) { + new Assertion(act, msg, assert.approximately, true).to.be.approximately(exp, delta); +}; +assert.sameMembers = function(set1, set2, msg) { + new Assertion(set1, msg, assert.sameMembers, true).to.have.same.members(set2); +}; +assert.notSameMembers = function(set1, set2, msg) { + new Assertion(set1, msg, assert.notSameMembers, true).to.not.have.same.members(set2); +}; +assert.sameDeepMembers = function(set1, set2, msg) { + new Assertion(set1, msg, assert.sameDeepMembers, true).to.have.same.deep.members(set2); +}; +assert.notSameDeepMembers = function(set1, set2, msg) { + new Assertion(set1, msg, assert.notSameDeepMembers, true).to.not.have.same.deep.members(set2); +}; +assert.sameOrderedMembers = function(set1, set2, msg) { + new Assertion(set1, msg, assert.sameOrderedMembers, true).to.have.same.ordered.members(set2); +}; +assert.notSameOrderedMembers = function(set1, set2, msg) { + new Assertion(set1, msg, assert.notSameOrderedMembers, true).to.not.have.same.ordered.members(set2); +}; +assert.sameDeepOrderedMembers = function(set1, set2, msg) { + new Assertion(set1, msg, assert.sameDeepOrderedMembers, true).to.have.same.deep.ordered.members(set2); +}; +assert.notSameDeepOrderedMembers = function(set1, set2, msg) { + new Assertion(set1, msg, assert.notSameDeepOrderedMembers, true).to.not.have.same.deep.ordered.members(set2); +}; +assert.includeMembers = function(superset, subset, msg) { + new Assertion(superset, msg, assert.includeMembers, true).to.include.members(subset); +}; +assert.notIncludeMembers = function(superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeMembers, true).to.not.include.members(subset); +}; +assert.includeDeepMembers = function(superset, subset, msg) { + new Assertion(superset, msg, assert.includeDeepMembers, true).to.include.deep.members(subset); +}; +assert.notIncludeDeepMembers = function(superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeDeepMembers, true).to.not.include.deep.members(subset); +}; +assert.includeOrderedMembers = function(superset, subset, msg) { + new Assertion(superset, msg, assert.includeOrderedMembers, true).to.include.ordered.members(subset); +}; +assert.notIncludeOrderedMembers = function(superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeOrderedMembers, true).to.not.include.ordered.members(subset); +}; +assert.includeDeepOrderedMembers = function(superset, subset, msg) { + new Assertion(superset, msg, assert.includeDeepOrderedMembers, true).to.include.deep.ordered.members(subset); +}; +assert.notIncludeDeepOrderedMembers = function(superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeDeepOrderedMembers, true).to.not.include.deep.ordered.members(subset); +}; +assert.oneOf = function(inList, list, msg) { + new Assertion(inList, msg, assert.oneOf, true).to.be.oneOf(list); +}; +assert.isIterable = function(obj, msg) { + if (obj == void 0 || !obj[Symbol.iterator]) { + msg = msg ? `${msg} expected ${inspect2(obj)} to be an iterable` : `expected ${inspect2(obj)} to be an iterable`; + throw new AssertionError( + msg, + void 0, + assert.isIterable + ); + } +}; +assert.changes = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + new Assertion(fn, msg, assert.changes, true).to.change(obj, prop); +}; +assert.changesBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.changesBy, true).to.change(obj, prop).by(delta); +}; +assert.doesNotChange = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.doesNotChange, true).to.not.change(obj, prop); +}; +assert.changesButNotBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.changesButNotBy, true).to.change(obj, prop).but.not.by(delta); +}; +assert.increases = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.increases, true).to.increase(obj, prop); +}; +assert.increasesBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.increasesBy, true).to.increase(obj, prop).by(delta); +}; +assert.doesNotIncrease = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.doesNotIncrease, true).to.not.increase(obj, prop); +}; +assert.increasesButNotBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.increasesButNotBy, true).to.increase(obj, prop).but.not.by(delta); +}; +assert.decreases = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.decreases, true).to.decrease(obj, prop); +}; +assert.decreasesBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.decreasesBy, true).to.decrease(obj, prop).by(delta); +}; +assert.doesNotDecrease = function(fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === "function") { + msg = prop; + prop = null; + } + return new Assertion(fn, msg, assert.doesNotDecrease, true).to.not.decrease(obj, prop); +}; +assert.doesNotDecreaseBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + return new Assertion(fn, msg, assert.doesNotDecreaseBy, true).to.not.decrease(obj, prop).by(delta); +}; +assert.decreasesButNotBy = function(fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === "function") { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + new Assertion(fn, msg, assert.decreasesButNotBy, true).to.decrease(obj, prop).but.not.by(delta); +}; +assert.ifError = function(val) { + if (val) { + throw val; + } +}; +assert.isExtensible = function(obj, msg) { + new Assertion(obj, msg, assert.isExtensible, true).to.be.extensible; +}; +assert.isNotExtensible = function(obj, msg) { + new Assertion(obj, msg, assert.isNotExtensible, true).to.not.be.extensible; +}; +assert.isSealed = function(obj, msg) { + new Assertion(obj, msg, assert.isSealed, true).to.be.sealed; +}; +assert.isNotSealed = function(obj, msg) { + new Assertion(obj, msg, assert.isNotSealed, true).to.not.be.sealed; +}; +assert.isFrozen = function(obj, msg) { + new Assertion(obj, msg, assert.isFrozen, true).to.be.frozen; +}; +assert.isNotFrozen = function(obj, msg) { + new Assertion(obj, msg, assert.isNotFrozen, true).to.not.be.frozen; +}; +assert.isEmpty = function(val, msg) { + new Assertion(val, msg, assert.isEmpty, true).to.be.empty; +}; +assert.isNotEmpty = function(val, msg) { + new Assertion(val, msg, assert.isNotEmpty, true).to.not.be.empty; +}; +(/* @__PURE__ */ __name(function alias(name, as) { + assert[as] = assert[name]; + return alias; +}, "alias"))("isOk", "ok")("isNotOk", "notOk")("throws", "throw")("throws", "Throw")("isExtensible", "extensible")("isNotExtensible", "notExtensible")("isSealed", "sealed")("isNotSealed", "notSealed")("isFrozen", "frozen")("isNotFrozen", "notFrozen")("isEmpty", "empty")("isNotEmpty", "notEmpty")("isCallable", "isFunction")("isNotCallable", "isNotFunction"); + +// lib/chai.js +var used = []; +function use(fn) { + const exports = { + AssertionError, + util: utils_exports, + config, + expect, + assert, + Assertion, + ...should_exports + }; + if (!~used.indexOf(fn)) { + fn(exports, utils_exports); + used.push(fn); + } + return exports; +} +__name(use, "use"); +export { + Assertion, + AssertionError, + Should, + assert, + config, + expect, + should, + use, + utils_exports as util +}; +/*! + * Chai - flag utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - test utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - expectTypes utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - getActual utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - message composition utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - transferFlags utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - isProxyEnabled helper + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - addProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - addLengthGuard utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - getProperties utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - proxify utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - addMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - overwriteProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - overwriteMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - addChainingMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - overwriteChainableMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ +/*! + * Chai - compareByInspect utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ +/*! + * Chai - getOwnEnumerablePropertySymbols utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ +/*! + * Chai - getOwnEnumerableProperties utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ +/*! + * Chai - isNaN utility + * Copyright(c) 2012-2015 Sakthipriyan Vairamani + * MIT Licensed + */ +/*! + * chai + * Copyright(c) 2011 Jake Luer + * MIT Licensed + */ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ +/*! Bundled license information: + +deep-eql/index.js: + (*! + * deep-eql + * Copyright(c) 2013 Jake Luer + * MIT Licensed + *) + (*! + * Check to see if the MemoizeMap has recorded a result of the two operands + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {MemoizeMap} memoizeMap + * @returns {Boolean|null} result + *) + (*! + * Set the result of the equality into the MemoizeMap + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {MemoizeMap} memoizeMap + * @param {Boolean} result + *) + (*! + * Primary Export + *) + (*! + * The main logic of the `deepEqual` function. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (optional) Additional options + * @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality. + * @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of + complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular + references to blow the stack. + * @return {Boolean} equal match + *) + (*! + * Compare two Regular Expressions for equality. + * + * @param {RegExp} leftHandOperand + * @param {RegExp} rightHandOperand + * @return {Boolean} result + *) + (*! + * Compare two Sets/Maps for equality. Faster than other equality functions. + * + * @param {Set} leftHandOperand + * @param {Set} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + *) + (*! + * Simple equality for flat iterable objects such as Arrays, TypedArrays or Node.js buffers. + * + * @param {Iterable} leftHandOperand + * @param {Iterable} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + *) + (*! + * Simple equality for generator objects such as those returned by generator functions. + * + * @param {Iterable} leftHandOperand + * @param {Iterable} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + *) + (*! + * Determine if the given object has an @@iterator function. + * + * @param {Object} target + * @return {Boolean} `true` if the object has an @@iterator function. + *) + (*! + * Gets all iterator entries from the given Object. If the Object has no @@iterator function, returns an empty array. + * This will consume the iterator - which could have side effects depending on the @@iterator implementation. + * + * @param {Object} target + * @returns {Array} an array of entries from the @@iterator function + *) + (*! + * Gets all entries from a Generator. This will consume the generator - which could have side effects. + * + * @param {Generator} target + * @returns {Array} an array of entries from the Generator. + *) + (*! + * Gets all own and inherited enumerable keys from a target. + * + * @param {Object} target + * @returns {Array} an array of own and inherited enumerable keys from the target. + *) + (*! + * Determines if two objects have matching values, given a set of keys. Defers to deepEqual for the equality check of + * each key. If any value of the given key is not equal, the function will return false (early). + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Array} keys An array of keys to compare the values of leftHandOperand and rightHandOperand against + * @param {Object} [options] (Optional) + * @return {Boolean} result + *) + (*! + * Recursively check the equality of two Objects. Once basic sameness has been established it will defer to `deepEqual` + * for each enumerable key in the object. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + *) + (*! + * Returns true if the argument is a primitive. + * + * This intentionally returns true for all objects that can be compared by reference, + * including functions and symbols. + * + * @param {Mixed} value + * @return {Boolean} result + *) +*/ diff --git a/node_modules/chai/eslint.config.js b/node_modules/chai/eslint.config.js new file mode 100644 index 000000000..c9017f6c4 --- /dev/null +++ b/node_modules/chai/eslint.config.js @@ -0,0 +1,12 @@ +import jsdoc from "eslint-plugin-jsdoc"; + +export default [ + jsdoc.configs["flat/recommended"], + { + rules: { + "jsdoc/require-param-description": "off", + "jsdoc/require-returns-description": "off", + "jsdoc/tag-lines": ["error", "any", { startLines: 1 }], + }, + }, +]; diff --git a/node_modules/chai/index.js b/node_modules/chai/index.js new file mode 100644 index 000000000..ea4874863 --- /dev/null +++ b/node_modules/chai/index.js @@ -0,0 +1 @@ +export * from './lib/chai.js'; diff --git a/node_modules/chai/lib/chai.js b/node_modules/chai/lib/chai.js new file mode 100644 index 000000000..507d9c763 --- /dev/null +++ b/node_modules/chai/lib/chai.js @@ -0,0 +1,65 @@ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +import * as util from './chai/utils/index.js'; +import {AssertionError} from 'assertion-error'; +import {config} from './chai/config.js'; +import './chai/core/assertions.js'; +import {expect} from './chai/interface/expect.js'; +import {Assertion} from './chai/assertion.js'; +import * as should from './chai/interface/should.js'; +import {assert} from './chai/interface/assert.js'; + +const used = []; + +// Assertion Error +export {AssertionError}; + +/** + * # .use(function) + * + * Provides a way to extend the internals of Chai. + * + * @param {Function} fn + * @returns {this} for chaining + * @public + */ +export function use(fn) { + const exports = { + AssertionError, + util, + config, + expect, + assert, + Assertion, + ...should + }; + + if (!~used.indexOf(fn)) { + fn(exports, util); + used.push(fn); + } + + return exports; +}; + +// Utility Functions +export {util}; + +// Configuration +export {config}; + +// Primary `Assertion` prototype +export * from './chai/assertion.js'; + +// Expect interface +export * from './chai/interface/expect.js'; + +// Should interface +export * from './chai/interface/should.js'; + +// Assert interface +export * from './chai/interface/assert.js'; diff --git a/node_modules/chai/lib/chai/assertion.js b/node_modules/chai/lib/chai/assertion.js new file mode 100644 index 000000000..7cc17cda8 --- /dev/null +++ b/node_modules/chai/lib/chai/assertion.js @@ -0,0 +1,164 @@ +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +import {config} from './config.js'; +import {AssertionError} from 'assertion-error'; +import * as util from './utils/index.js'; + +/** + * Assertion Constructor + * + * Creates object for chaining. + * + * `Assertion` objects contain metadata in the form of flags. Three flags can + * be assigned during instantiation by passing arguments to this constructor: + * + * - `object`: This flag contains the target of the assertion. For example, in + * the assertion `expect(numKittens).to.equal(7);`, the `object` flag will + * contain `numKittens` so that the `equal` assertion can reference it when + * needed. + * + * - `message`: This flag contains an optional custom error message to be + * prepended to the error message that's generated by the assertion when it + * fails. + * + * - `ssfi`: This flag stands for "start stack function indicator". It + * contains a function reference that serves as the starting point for + * removing frames from the stack trace of the error that's created by the + * assertion when it fails. The goal is to provide a cleaner stack trace to + * end users by removing Chai's internal functions. Note that it only works + * in environments that support `Error.captureStackTrace`, and only when + * `Chai.config.includeStack` hasn't been set to `false`. + * + * - `lockSsfi`: This flag controls whether or not the given `ssfi` flag + * should retain its current value, even as assertions are chained off of + * this object. This is usually set to `true` when creating a new assertion + * from within another assertion. It's also temporarily set to `true` before + * an overwritten assertion gets called by the overwriting assertion. + * + * - `eql`: This flag contains the deepEqual function to be used by the assertion. + * + * @param {unknown} obj target of the assertion + * @param {string} msg (optional) custom error message + * @param {Function} ssfi (optional) starting point for removing stack frames + * @param {boolean} lockSsfi (optional) whether or not the ssfi flag is locked + * @returns {unknown} + * @private + */ +export function Assertion (obj, msg, ssfi, lockSsfi) { + util.flag(this, 'ssfi', ssfi || Assertion); + util.flag(this, 'lockSsfi', lockSsfi); + util.flag(this, 'object', obj); + util.flag(this, 'message', msg); + util.flag(this, 'eql', config.deepEqual || util.eql); + + return util.proxify(this); +} + +Object.defineProperty(Assertion, 'includeStack', { + get: function() { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + return config.includeStack; + }, + set: function(value) { + console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.'); + config.includeStack = value; + } +}); + +Object.defineProperty(Assertion, 'showDiff', { + get: function() { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + return config.showDiff; + }, + set: function(value) { + console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.'); + config.showDiff = value; + } +}); + +Assertion.addProperty = function (name, fn) { + util.addProperty(this.prototype, name, fn); +}; + +Assertion.addMethod = function (name, fn) { + util.addMethod(this.prototype, name, fn); +}; + +Assertion.addChainableMethod = function (name, fn, chainingBehavior) { + util.addChainableMethod(this.prototype, name, fn, chainingBehavior); +}; + +Assertion.overwriteProperty = function (name, fn) { + util.overwriteProperty(this.prototype, name, fn); +}; + +Assertion.overwriteMethod = function (name, fn) { + util.overwriteMethod(this.prototype, name, fn); +}; + +Assertion.overwriteChainableMethod = function (name, fn, chainingBehavior) { + util.overwriteChainableMethod(this.prototype, name, fn, chainingBehavior); +}; + +/** + * ### .assert(expression, message, negateMessage, expected, actual, showDiff) + * + * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. + * + * @name assert + * @param {unknown} expression to be tested + * @param {string | Function} message or function that returns message to display if expression fails + * @param {string | Function} negatedMessage or function that returns negatedMessage to display if negated expression fails + * @param {unknown} expected value (remember to check for negation) + * @param {unknown} actual (optional) will default to `this.obj` + * @param {boolean} showDiff (optional) when set to `true`, assert will display a diff in addition to the message if expression fails + * @private + */ + +Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) { + var ok = util.test(this, arguments); + if (false !== showDiff) showDiff = true; + if (undefined === expected && undefined === _actual) showDiff = false; + if (true !== config.showDiff) showDiff = false; + + if (!ok) { + msg = util.getMessage(this, arguments); + var actual = util.getActual(this, arguments); + var assertionErrorObjectProperties = { + actual: actual + , expected: expected + , showDiff: showDiff + }; + + var operator = util.getOperator(this, arguments); + if (operator) { + assertionErrorObjectProperties.operator = operator; + } + + throw new AssertionError( + msg, + assertionErrorObjectProperties, + (config.includeStack) ? this.assert : util.flag(this, 'ssfi')); + } +}; + +/** + * ### ._obj + * + * Quick reference to stored `actual` value for plugin developers. + * + * @private + */ +Object.defineProperty(Assertion.prototype, '_obj', + { get: function () { + return util.flag(this, 'object'); + } + , set: function (val) { + util.flag(this, 'object', val); + } +}); diff --git a/node_modules/chai/lib/chai/config.js b/node_modules/chai/lib/chai/config.js new file mode 100644 index 000000000..afeae596b --- /dev/null +++ b/node_modules/chai/lib/chai/config.js @@ -0,0 +1,114 @@ +export const config = { + + /** + * ### config.includeStack + * + * User configurable property, influences whether stack trace + * is included in Assertion error message. Default of false + * suppresses stack trace in the error message. + * + * chai.config.includeStack = true; // enable stack on error + * + * @param {boolean} + * @public + */ + includeStack: false, + + /** + * ### config.showDiff + * + * User configurable property, influences whether or not + * the `showDiff` flag should be included in the thrown + * AssertionErrors. `false` will always be `false`; `true` + * will be true when the assertion has requested a diff + * be shown. + * + * @param {boolean} + * @public + */ + showDiff: true, + + /** + * ### config.truncateThreshold + * + * User configurable property, sets length threshold for actual and + * expected values in assertion errors. If this threshold is exceeded, for + * example for large data structures, the value is replaced with something + * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`. + * + * Set it to zero if you want to disable truncating altogether. + * + * This is especially userful when doing assertions on arrays: having this + * set to a reasonable large value makes the failure messages readily + * inspectable. + * + * chai.config.truncateThreshold = 0; // disable truncating + * + * @param {number} + * @public + */ + truncateThreshold: 40, + + /** + * ### config.useProxy + * + * User configurable property, defines if chai will use a Proxy to throw + * an error when a non-existent property is read, which protects users + * from typos when using property-based assertions. + * + * Set it to false if you want to disable this feature. + * + * chai.config.useProxy = false; // disable use of Proxy + * + * This feature is automatically disabled regardless of this config value + * in environments that don't support proxies. + * + * @param {boolean} + * @public + */ + useProxy: true, + + /** + * ### config.proxyExcludedKeys + * + * User configurable property, defines which properties should be ignored + * instead of throwing an error if they do not exist on the assertion. + * This is only applied if the environment Chai is running in supports proxies and + * if the `useProxy` configuration setting is enabled. + * By default, `then` and `inspect` will not throw an error if they do not exist on the + * assertion object because the `.inspect` property is read by `util.inspect` (for example, when + * using `console.log` on the assertion object) and `.then` is necessary for promise type-checking. + * + * // By default these keys will not throw an error if they do not exist on the assertion object + * chai.config.proxyExcludedKeys = ['then', 'inspect']; + * + * @param {Array} + * @public + */ + proxyExcludedKeys: ['then', 'catch', 'inspect', 'toJSON'], + + /** + * ### config.deepEqual + * + * User configurable property, defines which a custom function to use for deepEqual + * comparisons. + * By default, the function used is the one from the `deep-eql` package without custom comparator. + * + * // use a custom comparator + * chai.config.deepEqual = (expected, actual) => { + * return chai.util.eql(expected, actual, { + * comparator: (expected, actual) => { + * // for non number comparison, use the default behavior + * if(typeof expected !== 'number') return null; + * // allow a difference of 10 between compared numbers + * return typeof actual === 'number' && Math.abs(actual - expected) < 10 + * } + * }) + * }; + * + * @param {Function} + * @public + */ + deepEqual: null + +}; diff --git a/node_modules/chai/lib/chai/core/assertions.js b/node_modules/chai/lib/chai/core/assertions.js new file mode 100644 index 000000000..e2971726b --- /dev/null +++ b/node_modules/chai/lib/chai/core/assertions.js @@ -0,0 +1,3934 @@ +/*! + * chai + * http://chaijs.com + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +import {Assertion} from '../assertion.js'; +import {AssertionError} from 'assertion-error'; +import * as _ from '../utils/index.js'; + +const {flag} = _; + +/** + * ### Language Chains + * + * The following are provided as chainable getters to improve the readability + * of your assertions. + * + * **Chains** + * + * - to + * - be + * - been + * - is + * - that + * - which + * - and + * - has + * - have + * - with + * - at + * - of + * - same + * - but + * - does + * - still + * - also + * + * @name language chains + * @namespace BDD + * @public + */ + +[ 'to', 'be', 'been', 'is' +, 'and', 'has', 'have', 'with' +, 'that', 'which', 'at', 'of' +, 'same', 'but', 'does', 'still', "also" ].forEach(function (chain) { + Assertion.addProperty(chain); +}); + +/** + * ### .not + * + * Negates all assertions that follow in the chain. + * + * expect(function () {}).to.not.throw(); + * expect({a: 1}).to.not.have.property('b'); + * expect([1, 2]).to.be.an('array').that.does.not.include(3); + * + * Just because you can negate any assertion with `.not` doesn't mean you + * should. With great power comes great responsibility. It's often best to + * assert that the one expected output was produced, rather than asserting + * that one of countless unexpected outputs wasn't produced. See individual + * assertions for specific guidance. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.equal(1); // Not recommended + * + * @name not + * @namespace BDD + * @public + */ + +Assertion.addProperty('not', function () { + flag(this, 'negate', true); +}); + +/** + * ### .deep + * + * Causes all `.equal`, `.include`, `.members`, `.keys`, and `.property` + * assertions that follow in the chain to use deep equality instead of strict + * (`===`) equality. See the `deep-eql` project page for info on the deep + * equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) equals `{a: 1}` + * expect({a: 1}).to.deep.equal({a: 1}); + * expect({a: 1}).to.not.equal({a: 1}); + * + * // Target array deeply (but not strictly) includes `{a: 1}` + * expect([{a: 1}]).to.deep.include({a: 1}); + * expect([{a: 1}]).to.not.include({a: 1}); + * + * // Target object deeply (but not strictly) includes `x: {a: 1}` + * expect({x: {a: 1}}).to.deep.include({x: {a: 1}}); + * expect({x: {a: 1}}).to.not.include({x: {a: 1}}); + * + * // Target array deeply (but not strictly) has member `{a: 1}` + * expect([{a: 1}]).to.have.deep.members([{a: 1}]); + * expect([{a: 1}]).to.not.have.members([{a: 1}]); + * + * // Target set deeply (but not strictly) has key `{a: 1}` + * expect(new Set([{a: 1}])).to.have.deep.keys([{a: 1}]); + * expect(new Set([{a: 1}])).to.not.have.keys([{a: 1}]); + * + * // Target object deeply (but not strictly) has property `x: {a: 1}` + * expect({x: {a: 1}}).to.have.deep.property('x', {a: 1}); + * expect({x: {a: 1}}).to.not.have.property('x', {a: 1}); + * + * @name deep + * @namespace BDD + * @public + */ + +Assertion.addProperty('deep', function () { + flag(this, 'deep', true); +}); + +/** + * ### .nested + * + * Enables dot- and bracket-notation in all `.property` and `.include` + * assertions that follow in the chain. + * + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); + * expect({a: {b: ['x', 'y']}}).to.nested.include({'a.b[1]': 'y'}); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 'x'}}).to.have.nested.property('\\.a.\\[b\\]'); + * expect({'.a': {'[b]': 'x'}}).to.nested.include({'\\.a.\\[b\\]': 'x'}); + * + * `.nested` cannot be combined with `.own`. + * + * @name nested + * @namespace BDD + * @public + */ + +Assertion.addProperty('nested', function () { + flag(this, 'nested', true); +}); + +/** + * ### .own + * + * Causes all `.property` and `.include` assertions that follow in the chain + * to ignore inherited properties. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.have.own.property('a'); + * expect({a: 1}).to.have.property('b'); + * expect({a: 1}).to.not.have.own.property('b'); + * + * expect({a: 1}).to.own.include({a: 1}); + * expect({a: 1}).to.include({b: 2}).but.not.own.include({b: 2}); + * + * `.own` cannot be combined with `.nested`. + * + * @name own + * @namespace BDD + * @public + */ + +Assertion.addProperty('own', function () { + flag(this, 'own', true); +}); + +/** + * ### .ordered + * + * Causes all `.members` assertions that follow in the chain to require that + * members be in the same order. + * + * expect([1, 2]).to.have.ordered.members([1, 2]) + * .but.not.have.ordered.members([2, 1]); + * + * When `.include` and `.ordered` are combined, the ordering begins at the + * start of both arrays. + * + * expect([1, 2, 3]).to.include.ordered.members([1, 2]) + * .but.not.include.ordered.members([2, 3]); + * + * @name ordered + * @namespace BDD + * @public + */ + +Assertion.addProperty('ordered', function () { + flag(this, 'ordered', true); +}); + +/** + * ### .any + * + * Causes all `.keys` assertions that follow in the chain to only require that + * the target have at least one of the given keys. This is the opposite of + * `.all`, which requires that the target have all of the given keys. + * + * expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); + * + * See the `.keys` doc for guidance on when to use `.any` or `.all`. + * + * @name any + * @namespace BDD + * @public + */ + +Assertion.addProperty('any', function () { + flag(this, 'any', true); + flag(this, 'all', false); +}); + +/** + * ### .all + * + * Causes all `.keys` assertions that follow in the chain to require that the + * target have all of the given keys. This is the opposite of `.any`, which + * only requires that the target have at least one of the given keys. + * + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * + * Note that `.all` is used by default when neither `.all` nor `.any` are + * added earlier in the chain. However, it's often best to add `.all` anyway + * because it improves readability. + * + * See the `.keys` doc for guidance on when to use `.any` or `.all`. + * + * @name all + * @namespace BDD + * @public + */ +Assertion.addProperty('all', function () { + flag(this, 'all', true); + flag(this, 'any', false); +}); + +const functionTypes = { + 'function': ['function', 'asyncfunction', 'generatorfunction', 'asyncgeneratorfunction'], + 'asyncfunction': ['asyncfunction', 'asyncgeneratorfunction'], + 'generatorfunction': ['generatorfunction', 'asyncgeneratorfunction'], + 'asyncgeneratorfunction': ['asyncgeneratorfunction'] +} + +/** + * ### .a(type[, msg]) + * + * Asserts that the target's type is equal to the given string `type`. Types + * are case insensitive. See the utility file `./type-detect.js` for info on the + * type detection algorithm. + * + * expect('foo').to.be.a('string'); + * expect({a: 1}).to.be.an('object'); + * expect(null).to.be.a('null'); + * expect(undefined).to.be.an('undefined'); + * expect(new Error).to.be.an('error'); + * expect(Promise.resolve()).to.be.a('promise'); + * expect(new Float32Array).to.be.a('float32array'); + * expect(Symbol()).to.be.a('symbol'); + * + * `.a` supports objects that have a custom type set via `Symbol.toStringTag`. + * + * var myObj = { + * [Symbol.toStringTag]: 'myCustomType' + * }; + * + * expect(myObj).to.be.a('myCustomType').but.not.an('object'); + * + * It's often best to use `.a` to check a target's type before making more + * assertions on the same target. That way, you avoid unexpected behavior from + * any assertion that does different things based on the target's type. + * + * expect([1, 2, 3]).to.be.an('array').that.includes(2); + * expect([]).to.be.an('array').that.is.empty; + * + * Add `.not` earlier in the chain to negate `.a`. However, it's often best to + * assert that the target is the expected type, rather than asserting that it + * isn't one of many unexpected types. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.an('array'); // Not recommended + * + * `.a` accepts an optional `msg` argument which is a custom error message to + * show when the assertion fails. The message can also be given as the second + * argument to `expect`. + * + * expect(1).to.be.a('string', 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.a('string'); + * + * `.a` can also be used as a language chain to improve the readability of + * your assertions. + * + * expect({b: 2}).to.have.a.property('b'); + * + * The alias `.an` can be used interchangeably with `.a`. + * + * @name a + * @alias an + * @param {string} type + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function an (type, msg) { + if (msg) flag(this, 'message', msg); + type = type.toLowerCase(); + var obj = flag(this, 'object') + , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; + + const detectedType = _.type(obj).toLowerCase(); + + if (functionTypes['function'].includes(type)) { + this.assert( + functionTypes[type].includes(detectedType) + , 'expected #{this} to be ' + article + type + , 'expected #{this} not to be ' + article + type + ); + } else { + this.assert( + type === detectedType + , 'expected #{this} to be ' + article + type + , 'expected #{this} not to be ' + article + type + ); + } +} + +Assertion.addChainableMethod('an', an); +Assertion.addChainableMethod('a', an); + +/** + * + * @param {unknown} a + * @param {unknown} b + * @returns {boolean} + */ +function SameValueZero(a, b) { + return (_.isNaN(a) && _.isNaN(b)) || a === b; +} + +/** + * + */ +function includeChainingBehavior () { + flag(this, 'contains', true); +} + +/** + * ### .include(val[, msg]) + * + * When the target is a string, `.include` asserts that the given string `val` + * is a substring of the target. + * + * expect('foobar').to.include('foo'); + * + * When the target is an array, `.include` asserts that the given `val` is a + * member of the target. + * + * expect([1, 2, 3]).to.include(2); + * + * When the target is an object, `.include` asserts that the given object + * `val`'s properties are a subset of the target's properties. + * + * expect({a: 1, b: 2, c: 3}).to.include({a: 1, b: 2}); + * + * When the target is a Set or WeakSet, `.include` asserts that the given `val` is a + * member of the target. SameValueZero equality algorithm is used. + * + * expect(new Set([1, 2])).to.include(2); + * + * When the target is a Map, `.include` asserts that the given `val` is one of + * the values of the target. SameValueZero equality algorithm is used. + * + * expect(new Map([['a', 1], ['b', 2]])).to.include(2); + * + * Because `.include` does different things based on the target's type, it's + * important to check the target's type before using `.include`. See the `.a` + * doc for info on testing a target's type. + * + * expect([1, 2, 3]).to.be.an('array').that.includes(2); + * + * By default, strict (`===`) equality is used to compare array members and + * object properties. Add `.deep` earlier in the chain to use deep equality + * instead (WeakSet targets are not supported). See the `deep-eql` project + * page for info on the deep equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target array deeply (but not strictly) includes `{a: 1}` + * expect([{a: 1}]).to.deep.include({a: 1}); + * expect([{a: 1}]).to.not.include({a: 1}); + * + * // Target object deeply (but not strictly) includes `x: {a: 1}` + * expect({x: {a: 1}}).to.deep.include({x: {a: 1}}); + * expect({x: {a: 1}}).to.not.include({x: {a: 1}}); + * + * By default, all of the target's properties are searched when working with + * objects. This includes properties that are inherited and/or non-enumerable. + * Add `.own` earlier in the chain to exclude the target's inherited + * properties from the search. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.own.include({a: 1}); + * expect({a: 1}).to.include({b: 2}).but.not.own.include({b: 2}); + * + * Note that a target object is always only searched for `val`'s own + * enumerable properties. + * + * `.deep` and `.own` can be combined. + * + * expect({a: {b: 2}}).to.deep.own.include({a: {b: 2}}); + * + * Add `.nested` earlier in the chain to enable dot- and bracket-notation when + * referencing nested properties. + * + * expect({a: {b: ['x', 'y']}}).to.nested.include({'a.b[1]': 'y'}); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 2}}).to.nested.include({'\\.a.\\[b\\]': 2}); + * + * `.deep` and `.nested` can be combined. + * + * expect({a: {b: [{c: 3}]}}).to.deep.nested.include({'a.b[0]': {c: 3}}); + * + * `.own` and `.nested` cannot be combined. + * + * Add `.not` earlier in the chain to negate `.include`. + * + * expect('foobar').to.not.include('taco'); + * expect([1, 2, 3]).to.not.include(4); + * + * However, it's dangerous to negate `.include` when the target is an object. + * The problem is that it creates uncertain expectations by asserting that the + * target object doesn't have all of `val`'s key/value pairs but may or may + * not have some of them. It's often best to identify the exact output that's + * expected, and then write an assertion that only accepts that exact output. + * + * When the target object isn't even expected to have `val`'s keys, it's + * often best to assert exactly that. + * + * expect({c: 3}).to.not.have.any.keys('a', 'b'); // Recommended + * expect({c: 3}).to.not.include({a: 1, b: 2}); // Not recommended + * + * When the target object is expected to have `val`'s keys, it's often best to + * assert that each of the properties has its expected value, rather than + * asserting that each property doesn't have one of many unexpected values. + * + * expect({a: 3, b: 4}).to.include({a: 3, b: 4}); // Recommended + * expect({a: 3, b: 4}).to.not.include({a: 1, b: 2}); // Not recommended + * + * `.include` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2, 3]).to.include(4, 'nooo why fail??'); + * expect([1, 2, 3], 'nooo why fail??').to.include(4); + * + * `.include` can also be used as a language chain, causing all `.members` and + * `.keys` assertions that follow in the chain to require the target to be a + * superset of the expected set, rather than an identical set. Note that + * `.members` ignores duplicates in the subset when `.include` is added. + * + * // Target object's keys are a superset of ['a', 'b'] but not identical + * expect({a: 1, b: 2, c: 3}).to.include.all.keys('a', 'b'); + * expect({a: 1, b: 2, c: 3}).to.not.have.all.keys('a', 'b'); + * + * // Target array is a superset of [1, 2] but not identical + * expect([1, 2, 3]).to.include.members([1, 2]); + * expect([1, 2, 3]).to.not.have.members([1, 2]); + * + * // Duplicates in the subset are ignored + * expect([1, 2, 3]).to.include.members([1, 2, 2, 2]); + * + * Note that adding `.any` earlier in the chain causes the `.keys` assertion + * to ignore `.include`. + * + * // Both assertions are identical + * expect({a: 1}).to.include.any.keys('a', 'b'); + * expect({a: 1}).to.have.any.keys('a', 'b'); + * + * The aliases `.includes`, `.contain`, and `.contains` can be used + * interchangeably with `.include`. + * + * @name include + * @alias contain + * @alias includes + * @alias contains + * @param {unknown} val + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function include (val, msg) { + if (msg) flag(this, 'message', msg); + + var obj = flag(this, 'object') + , objType = _.type(obj).toLowerCase() + , flagMsg = flag(this, 'message') + , negate = flag(this, 'negate') + , ssfi = flag(this, 'ssfi') + , isDeep = flag(this, 'deep') + , descriptor = isDeep ? 'deep ' : '' + , isEql = isDeep ? flag(this, 'eql') : SameValueZero; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + var included = false; + + switch (objType) { + case 'string': + included = obj.indexOf(val) !== -1; + break; + + case 'weakset': + if (isDeep) { + throw new AssertionError( + flagMsg + 'unable to use .deep.include with WeakSet', + undefined, + ssfi + ); + } + + included = obj.has(val); + break; + + case 'map': + obj.forEach(function (item) { + included = included || isEql(item, val); + }); + break; + + case 'set': + if (isDeep) { + obj.forEach(function (item) { + included = included || isEql(item, val); + }); + } else { + included = obj.has(val); + } + break; + + case 'array': + if (isDeep) { + included = obj.some(function (item) { + return isEql(item, val); + }) + } else { + included = obj.indexOf(val) !== -1; + } + break; + + default: + // This block is for asserting a subset of properties in an object. + // `_.expectTypes` isn't used here because `.include` should work with + // objects with a custom `@@toStringTag`. + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + 'the given combination of arguments (' + + objType + ' and ' + + _.type(val).toLowerCase() + ')' + + ' is invalid for this assertion. ' + + 'You can use an array, a map, an object, a set, a string, ' + + 'or a weakset instead of a ' + + _.type(val).toLowerCase(), + undefined, + ssfi + ); + } + + var props = Object.keys(val) + , firstErr = null + , numErrs = 0; + + props.forEach(function (prop) { + var propAssertion = new Assertion(obj); + _.transferFlags(this, propAssertion, true); + flag(propAssertion, 'lockSsfi', true); + + if (!negate || props.length === 1) { + propAssertion.property(prop, val[prop]); + return; + } + + try { + propAssertion.property(prop, val[prop]); + } catch (err) { + if (!_.checkError.compatibleConstructor(err, AssertionError)) { + throw err; + } + if (firstErr === null) firstErr = err; + numErrs++; + } + }, this); + + // When validating .not.include with multiple properties, we only want + // to throw an assertion error if all of the properties are included, + // in which case we throw the first property assertion error that we + // encountered. + if (negate && props.length > 1 && numErrs === props.length) { + throw firstErr; + } + return; + } + + // Assert inclusion in collection or substring in a string. + this.assert( + included + , 'expected #{this} to ' + descriptor + 'include ' + _.inspect(val) + , 'expected #{this} to not ' + descriptor + 'include ' + _.inspect(val)); +} + +Assertion.addChainableMethod('include', include, includeChainingBehavior); +Assertion.addChainableMethod('contain', include, includeChainingBehavior); +Assertion.addChainableMethod('contains', include, includeChainingBehavior); +Assertion.addChainableMethod('includes', include, includeChainingBehavior); + +/** + * ### .ok + * + * Asserts that the target is a truthy value (considered `true` in boolean context). + * However, it's often best to assert that the target is strictly (`===`) or + * deeply equal to its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.ok; // Not recommended + * + * expect(true).to.be.true; // Recommended + * expect(true).to.be.ok; // Not recommended + * + * Add `.not` earlier in the chain to negate `.ok`. + * + * expect(0).to.equal(0); // Recommended + * expect(0).to.not.be.ok; // Not recommended + * + * expect(false).to.be.false; // Recommended + * expect(false).to.not.be.ok; // Not recommended + * + * expect(null).to.be.null; // Recommended + * expect(null).to.not.be.ok; // Not recommended + * + * expect(undefined).to.be.undefined; // Recommended + * expect(undefined).to.not.be.ok; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(false, 'nooo why fail??').to.be.ok; + * + * @name ok + * @namespace BDD + * @public + */ +Assertion.addProperty('ok', function () { + this.assert( + flag(this, 'object') + , 'expected #{this} to be truthy' + , 'expected #{this} to be falsy'); +}); + +/** + * ### .true + * + * Asserts that the target is strictly (`===`) equal to `true`. + * + * expect(true).to.be.true; + * + * Add `.not` earlier in the chain to negate `.true`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `true`. + * + * expect(false).to.be.false; // Recommended + * expect(false).to.not.be.true; // Not recommended + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.true; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(false, 'nooo why fail??').to.be.true; + * + * @name true + * @namespace BDD + * @public + */ +Assertion.addProperty('true', function () { + this.assert( + true === flag(this, 'object') + , 'expected #{this} to be true' + , 'expected #{this} to be false' + , flag(this, 'negate') ? false : true + ); +}); + +Assertion.addProperty('numeric', function () { + const object = flag(this, 'object'); + + this.assert( + ['Number', 'BigInt'].includes(_.type(object)) + , 'expected #{this} to be numeric' + , 'expected #{this} to not be numeric' + , flag(this, 'negate') ? false : true + ); +}); + +/** + * ### .callable + * + * Asserts that the target a callable function. + * + * expect(console.log).to.be.callable; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect('not a function', 'nooo why fail??').to.be.callable; + * + * @name callable + * @namespace BDD + * @public + */ +Assertion.addProperty('callable', function () { + const val = flag(this, 'object') + const ssfi = flag(this, 'ssfi') + const message = flag(this, 'message') + const msg = message ? `${message}: ` : '' + const negate = flag(this, 'negate'); + + const assertionMessage = negate ? + `${msg}expected ${_.inspect(val)} not to be a callable function` : + `${msg}expected ${_.inspect(val)} to be a callable function`; + + const isCallable = ['Function', 'AsyncFunction', 'GeneratorFunction', 'AsyncGeneratorFunction'].includes(_.type(val)); + + if ((isCallable && negate) || (!isCallable && !negate)) { + throw new AssertionError( + assertionMessage, + undefined, + ssfi + ); + } +}); + +/** + * ### .false + * + * Asserts that the target is strictly (`===`) equal to `false`. + * + * expect(false).to.be.false; + * + * Add `.not` earlier in the chain to negate `.false`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to `false`. + * + * expect(true).to.be.true; // Recommended + * expect(true).to.not.be.false; // Not recommended + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.false; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(true, 'nooo why fail??').to.be.false; + * + * @name false + * @namespace BDD + * @public + */ +Assertion.addProperty('false', function () { + this.assert( + false === flag(this, 'object') + , 'expected #{this} to be false' + , 'expected #{this} to be true' + , flag(this, 'negate') ? true : false + ); +}); + +/** + * ### .null + * + * Asserts that the target is strictly (`===`) equal to `null`. + * + * expect(null).to.be.null; + * + * Add `.not` earlier in the chain to negate `.null`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `null`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.null; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.null; + * + * @name null + * @namespace BDD + * @public + */ +Assertion.addProperty('null', function () { + this.assert( + null === flag(this, 'object') + , 'expected #{this} to be null' + , 'expected #{this} not to be null' + ); +}); + +/** + * ### .undefined + * + * Asserts that the target is strictly (`===`) equal to `undefined`. + * + * expect(undefined).to.be.undefined; + * + * Add `.not` earlier in the chain to negate `.undefined`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to `undefined`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.undefined; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.undefined; + * + * @name undefined + * @namespace BDD + * @public + */ +Assertion.addProperty('undefined', function () { + this.assert( + undefined === flag(this, 'object') + , 'expected #{this} to be undefined' + , 'expected #{this} not to be undefined' + ); +}); + +/** + * ### .NaN + * + * Asserts that the target is exactly `NaN`. + * + * expect(NaN).to.be.NaN; + * + * Add `.not` earlier in the chain to negate `.NaN`. However, it's often best + * to assert that the target is equal to its expected value, rather than not + * equal to `NaN`. + * + * expect('foo').to.equal('foo'); // Recommended + * expect('foo').to.not.be.NaN; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(42, 'nooo why fail??').to.be.NaN; + * + * @name NaN + * @namespace BDD + * @public + */ +Assertion.addProperty('NaN', function () { + this.assert( + _.isNaN(flag(this, 'object')) + , 'expected #{this} to be NaN' + , 'expected #{this} not to be NaN' + ); +}); + +/** + * ### .exist + * + * Asserts that the target is not strictly (`===`) equal to either `null` or + * `undefined`. However, it's often best to assert that the target is equal to + * its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.exist; // Not recommended + * + * expect(0).to.equal(0); // Recommended + * expect(0).to.exist; // Not recommended + * + * Add `.not` earlier in the chain to negate `.exist`. + * + * expect(null).to.be.null; // Recommended + * expect(null).to.not.exist; // Not recommended + * + * expect(undefined).to.be.undefined; // Recommended + * expect(undefined).to.not.exist; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(null, 'nooo why fail??').to.exist; + * + * The alias `.exists` can be used interchangeably with `.exist`. + * + * @name exist + * @alias exists + * @namespace BDD + * @public + */ +function assertExist () { + var val = flag(this, 'object'); + this.assert( + val !== null && val !== undefined + , 'expected #{this} to exist' + , 'expected #{this} to not exist' + ); +} + +Assertion.addProperty('exist', assertExist); +Assertion.addProperty('exists', assertExist); + +/** + * ### .empty + * + * When the target is a string or array, `.empty` asserts that the target's + * `length` property is strictly (`===`) equal to `0`. + * + * expect([]).to.be.empty; + * expect('').to.be.empty; + * + * When the target is a map or set, `.empty` asserts that the target's `size` + * property is strictly equal to `0`. + * + * expect(new Set()).to.be.empty; + * expect(new Map()).to.be.empty; + * + * When the target is a non-function object, `.empty` asserts that the target + * doesn't have any own enumerable properties. Properties with Symbol-based + * keys are excluded from the count. + * + * expect({}).to.be.empty; + * + * Because `.empty` does different things based on the target's type, it's + * important to check the target's type before using `.empty`. See the `.a` + * doc for info on testing a target's type. + * + * expect([]).to.be.an('array').that.is.empty; + * + * Add `.not` earlier in the chain to negate `.empty`. However, it's often + * best to assert that the target contains its expected number of values, + * rather than asserting that it's not empty. + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.not.be.empty; // Not recommended + * + * expect(new Set([1, 2, 3])).to.have.property('size', 3); // Recommended + * expect(new Set([1, 2, 3])).to.not.be.empty; // Not recommended + * + * expect(Object.keys({a: 1})).to.have.lengthOf(1); // Recommended + * expect({a: 1}).to.not.be.empty; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect([1, 2, 3], 'nooo why fail??').to.be.empty; + * + * @name empty + * @namespace BDD + * @public + */ +Assertion.addProperty('empty', function () { + var val = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , flagMsg = flag(this, 'message') + , itemsCount; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + switch (_.type(val).toLowerCase()) { + case 'array': + case 'string': + itemsCount = val.length; + break; + case 'map': + case 'set': + itemsCount = val.size; + break; + case 'weakmap': + case 'weakset': + throw new AssertionError( + flagMsg + '.empty was passed a weak collection', + undefined, + ssfi + ); + case 'function': + var msg = flagMsg + '.empty was passed a function ' + _.getName(val); + throw new AssertionError(msg.trim(), undefined, ssfi); + default: + if (val !== Object(val)) { + throw new AssertionError( + flagMsg + '.empty was passed non-string primitive ' + _.inspect(val), + undefined, + ssfi + ); + } + itemsCount = Object.keys(val).length; + } + + this.assert( + 0 === itemsCount + , 'expected #{this} to be empty' + , 'expected #{this} not to be empty' + ); +}); + +/** + * ### .arguments + * + * Asserts that the target is an `arguments` object. + * + * function test () { + * expect(arguments).to.be.arguments; + * } + * + * test(); + * + * Add `.not` earlier in the chain to negate `.arguments`. However, it's often + * best to assert which type the target is expected to be, rather than + * asserting that it’s not an `arguments` object. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.arguments; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({}, 'nooo why fail??').to.be.arguments; + * + * The alias `.Arguments` can be used interchangeably with `.arguments`. + * + * @name arguments + * @alias Arguments + * @namespace BDD + * @public + */ +function checkArguments () { + var obj = flag(this, 'object') + , type = _.type(obj); + this.assert( + 'Arguments' === type + , 'expected #{this} to be arguments but got ' + type + , 'expected #{this} to not be arguments' + ); +} + +Assertion.addProperty('arguments', checkArguments); +Assertion.addProperty('Arguments', checkArguments); + +/** + * ### .equal(val[, msg]) + * + * Asserts that the target is strictly (`===`) equal to the given `val`. + * + * expect(1).to.equal(1); + * expect('foo').to.equal('foo'); + * + * Add `.deep` earlier in the chain to use deep equality instead. See the + * `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) equals `{a: 1}` + * expect({a: 1}).to.deep.equal({a: 1}); + * expect({a: 1}).to.not.equal({a: 1}); + * + * // Target array deeply (but not strictly) equals `[1, 2]` + * expect([1, 2]).to.deep.equal([1, 2]); + * expect([1, 2]).to.not.equal([1, 2]); + * + * Add `.not` earlier in the chain to negate `.equal`. However, it's often + * best to assert that the target is equal to its expected value, rather than + * not equal to one of countless unexpected values. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.equal(2); // Not recommended + * + * `.equal` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.equal(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.equal(2); + * + * The aliases `.equals` and `eq` can be used interchangeably with `.equal`. + * + * @name equal + * @alias equals + * @alias eq + * @param {unknown} val + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function assertEqual (val, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + if (flag(this, 'deep')) { + var prevLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + this.eql(val); + flag(this, 'lockSsfi', prevLockSsfi); + } else { + this.assert( + val === obj + , 'expected #{this} to equal #{exp}' + , 'expected #{this} to not equal #{exp}' + , val + , this._obj + , true + ); + } +} + +Assertion.addMethod('equal', assertEqual); +Assertion.addMethod('equals', assertEqual); +Assertion.addMethod('eq', assertEqual); + +/** + * ### .eql(obj[, msg]) + * + * Asserts that the target is deeply equal to the given `obj`. See the + * `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target object is deeply (but not strictly) equal to {a: 1} + * expect({a: 1}).to.eql({a: 1}).but.not.equal({a: 1}); + * + * // Target array is deeply (but not strictly) equal to [1, 2] + * expect([1, 2]).to.eql([1, 2]).but.not.equal([1, 2]); + * + * Add `.not` earlier in the chain to negate `.eql`. However, it's often best + * to assert that the target is deeply equal to its expected value, rather + * than not deeply equal to one of countless unexpected values. + * + * expect({a: 1}).to.eql({a: 1}); // Recommended + * expect({a: 1}).to.not.eql({b: 2}); // Not recommended + * + * `.eql` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect({a: 1}).to.eql({b: 2}, 'nooo why fail??'); + * expect({a: 1}, 'nooo why fail??').to.eql({b: 2}); + * + * The alias `.eqls` can be used interchangeably with `.eql`. + * + * The `.deep.equal` assertion is almost identical to `.eql` but with one + * difference: `.deep.equal` causes deep equality comparisons to also be used + * for any other assertions that follow in the chain. + * + * @name eql + * @alias eqls + * @param {unknown} obj + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function assertEql(obj, msg) { + if (msg) flag(this, 'message', msg); + var eql = flag(this, 'eql'); + this.assert( + eql(obj, flag(this, 'object')) + , 'expected #{this} to deeply equal #{exp}' + , 'expected #{this} to not deeply equal #{exp}' + , obj + , this._obj + , true + ); +} + +Assertion.addMethod('eql', assertEql); +Assertion.addMethod('eqls', assertEql); + +/** + * ### .above(n[, msg]) + * + * Asserts that the target is a number or a date greater than the given number or date `n` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.above(1); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.above(2); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.above(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.above`. + * + * expect(2).to.equal(2); // Recommended + * expect(1).to.not.be.above(2); // Not recommended + * + * `.above` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.above(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.above(2); + * + * The aliases `.gt` and `.greaterThan` can be used interchangeably with + * `.above`. + * + * @name above + * @alias gt + * @alias greaterThan + * @param {number} n + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function assertAbove (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase(); + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + throw new AssertionError(msgPrefix + 'the argument to above must be a date', undefined, ssfi); + } else if (!_.isNumeric(n) && (doLength || _.isNumeric(obj))) { + throw new AssertionError(msgPrefix + 'the argument to above must be a number', undefined, ssfi); + } else if (!doLength && (objType !== 'date' && !_.isNumeric(obj))) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + throw new AssertionError(msgPrefix + 'expected ' + printObj + ' to be a number or a date', undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount > n + , 'expected #{this} to have a ' + descriptor + ' above #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' above #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj > n + , 'expected #{this} to be above #{exp}' + , 'expected #{this} to be at most #{exp}' + , n + ); + } +} + +Assertion.addMethod('above', assertAbove); +Assertion.addMethod('gt', assertAbove); +Assertion.addMethod('greaterThan', assertAbove); + +/** + * ### .least(n[, msg]) + * + * Asserts that the target is a number or a date greater than or equal to the given + * number or date `n` respectively. However, it's often best to assert that the target is equal to + * its expected value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.at.least(1); // Not recommended + * expect(2).to.be.at.least(2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than or equal to the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.at.least(2); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.at.least(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.least`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.at.least(2); // Not recommended + * + * `.least` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.at.least(2, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.at.least(2); + * + * The aliases `.gte` and `.greaterThanOrEqual` can be used interchangeably with + * `.least`. + * + * @name least + * @alias gte + * @alias greaterThanOrEqual + * @param {unknown} n + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function assertLeast (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to least must be a date'; + } else if (!_.isNumeric(n) && (doLength || _.isNumeric(obj))) { + errorMessage = msgPrefix + 'the argument to least must be a number'; + } else if (!doLength && (objType !== 'date' && !_.isNumeric(obj))) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= n + , 'expected #{this} to have a ' + descriptor + ' at least #{exp} but got #{act}' + , 'expected #{this} to have a ' + descriptor + ' below #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj >= n + , 'expected #{this} to be at least #{exp}' + , 'expected #{this} to be below #{exp}' + , n + ); + } +} + +Assertion.addMethod('least', assertLeast); +Assertion.addMethod('gte', assertLeast); +Assertion.addMethod('greaterThanOrEqual', assertLeast); + +/** + * ### .below(n[, msg]) + * + * Asserts that the target is a number or a date less than the given number or date `n` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.below(2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is less than the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.below(4); // Not recommended + * + * expect([1, 2, 3]).to.have.length(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.below(4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.below`. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.be.below(1); // Not recommended + * + * `.below` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(2).to.be.below(1, 'nooo why fail??'); + * expect(2, 'nooo why fail??').to.be.below(1); + * + * The aliases `.lt` and `.lessThan` can be used interchangeably with + * `.below`. + * + * @name below + * @alias lt + * @alias lessThan + * @param {unknown} n + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function assertBelow (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to below must be a date'; + } else if (!_.isNumeric(n) && (doLength || _.isNumeric(obj))) { + errorMessage = msgPrefix + 'the argument to below must be a number'; + } else if (!doLength && (objType !== 'date' && !_.isNumeric(obj))) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount < n + , 'expected #{this} to have a ' + descriptor + ' below #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' below #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj < n + , 'expected #{this} to be below #{exp}' + , 'expected #{this} to be at least #{exp}' + , n + ); + } +} + +Assertion.addMethod('below', assertBelow); +Assertion.addMethod('lt', assertBelow); +Assertion.addMethod('lessThan', assertBelow); + +/** + * ### .most(n[, msg]) + * + * Asserts that the target is a number or a date less than or equal to the given number + * or date `n` respectively. However, it's often best to assert that the target is equal to its + * expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.at.most(2); // Not recommended + * expect(1).to.be.at.most(1); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is less than or equal to the given number `n`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.at.most(4); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.at.most(4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.most`. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.not.be.at.most(1); // Not recommended + * + * `.most` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(2).to.be.at.most(1, 'nooo why fail??'); + * expect(2, 'nooo why fail??').to.be.at.most(1); + * + * The aliases `.lte` and `.lessThanOrEqual` can be used interchangeably with + * `.most`. + * + * @name most + * @alias lte + * @alias lessThanOrEqual + * @param {unknown} n + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function assertMost (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , nType = _.type(n).toLowerCase() + , errorMessage + , shouldThrow = true; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && nType !== 'date')) { + errorMessage = msgPrefix + 'the argument to most must be a date'; + } else if (!_.isNumeric(n) && (doLength || _.isNumeric(obj))) { + errorMessage = msgPrefix + 'the argument to most must be a number'; + } else if (!doLength && (objType !== 'date' && !_.isNumeric(obj))) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount <= n + , 'expected #{this} to have a ' + descriptor + ' at most #{exp} but got #{act}' + , 'expected #{this} to have a ' + descriptor + ' above #{exp}' + , n + , itemsCount + ); + } else { + this.assert( + obj <= n + , 'expected #{this} to be at most #{exp}' + , 'expected #{this} to be above #{exp}' + , n + ); + } +} + +Assertion.addMethod('most', assertMost); +Assertion.addMethod('lte', assertMost); +Assertion.addMethod('lessThanOrEqual', assertMost); + +/** + * ### .within(start, finish[, msg]) + * + * Asserts that the target is a number or a date greater than or equal to the given + * number or date `start`, and less than or equal to the given number or date `finish` respectively. + * However, it's often best to assert that the target is equal to its expected + * value. + * + * expect(2).to.equal(2); // Recommended + * expect(2).to.be.within(1, 3); // Not recommended + * expect(2).to.be.within(2, 3); // Not recommended + * expect(2).to.be.within(1, 2); // Not recommended + * + * Add `.lengthOf` earlier in the chain to assert that the target's `length` + * or `size` is greater than or equal to the given number `start`, and less + * than or equal to the given number `finish`. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.have.lengthOf.within(2, 4); // Not recommended + * + * expect([1, 2, 3]).to.have.lengthOf(3); // Recommended + * expect([1, 2, 3]).to.have.lengthOf.within(2, 4); // Not recommended + * + * Add `.not` earlier in the chain to negate `.within`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.within(2, 4); // Not recommended + * + * `.within` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(4).to.be.within(1, 3, 'nooo why fail??'); + * expect(4, 'nooo why fail??').to.be.within(1, 3); + * + * @name within + * @param {unknown} start lower bound inclusive + * @param {unknown} finish upper bound inclusive + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +Assertion.addMethod('within', function (start, finish, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , doLength = flag(this, 'doLength') + , flagMsg = flag(this, 'message') + , msgPrefix = ((flagMsg) ? flagMsg + ': ' : '') + , ssfi = flag(this, 'ssfi') + , objType = _.type(obj).toLowerCase() + , startType = _.type(start).toLowerCase() + , finishType = _.type(finish).toLowerCase() + , errorMessage + , shouldThrow = true + , range = (startType === 'date' && finishType === 'date') + ? start.toISOString() + '..' + finish.toISOString() + : start + '..' + finish; + + if (doLength && objType !== 'map' && objType !== 'set') { + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + } + + if (!doLength && (objType === 'date' && (startType !== 'date' || finishType !== 'date'))) { + errorMessage = msgPrefix + 'the arguments to within must be dates'; + } else if ((!_.isNumeric(start) || !_.isNumeric(finish)) && (doLength || _.isNumeric(obj))) { + errorMessage = msgPrefix + 'the arguments to within must be numbers'; + } else if (!doLength && (objType !== 'date' && !_.isNumeric(obj))) { + var printObj = (objType === 'string') ? "'" + obj + "'" : obj; + errorMessage = msgPrefix + 'expected ' + printObj + ' to be a number or a date'; + } else { + shouldThrow = false; + } + + if (shouldThrow) { + throw new AssertionError(errorMessage, undefined, ssfi); + } + + if (doLength) { + var descriptor = 'length' + , itemsCount; + if (objType === 'map' || objType === 'set') { + descriptor = 'size'; + itemsCount = obj.size; + } else { + itemsCount = obj.length; + } + this.assert( + itemsCount >= start && itemsCount <= finish + , 'expected #{this} to have a ' + descriptor + ' within ' + range + , 'expected #{this} to not have a ' + descriptor + ' within ' + range + ); + } else { + this.assert( + obj >= start && obj <= finish + , 'expected #{this} to be within ' + range + , 'expected #{this} to not be within ' + range + ); + } +}); + +/** + * ### .instanceof(constructor[, msg]) + * + * Asserts that the target is an instance of the given `constructor`. + * + * function Cat () { } + * + * expect(new Cat()).to.be.an.instanceof(Cat); + * expect([1, 2]).to.be.an.instanceof(Array); + * + * Add `.not` earlier in the chain to negate `.instanceof`. + * + * expect({a: 1}).to.not.be.an.instanceof(Array); + * + * `.instanceof` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1).to.be.an.instanceof(Array, 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.an.instanceof(Array); + * + * Due to limitations in ES5, `.instanceof` may not always work as expected + * when using a transpiler such as Babel or TypeScript. In particular, it may + * produce unexpected results when subclassing built-in object such as + * `Array`, `Error`, and `Map`. See your transpiler's docs for details: + * + * - ([Babel](https://babeljs.io/docs/usage/caveats/#classes)) + * - ([TypeScript](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work)) + * + * The alias `.instanceOf` can be used interchangeably with `.instanceof`. + * + * @name instanceof + * @param {unknown} constructor + * @param {string} msg _optional_ + * @alias instanceOf + * @namespace BDD + * @public + */ +function assertInstanceOf (constructor, msg) { + if (msg) flag(this, 'message', msg); + + var target = flag(this, 'object') + var ssfi = flag(this, 'ssfi'); + var flagMsg = flag(this, 'message'); + + try { + var isInstanceOf = target instanceof constructor; + } catch (err) { + if (err instanceof TypeError) { + flagMsg = flagMsg ? flagMsg + ': ' : ''; + throw new AssertionError( + flagMsg + 'The instanceof assertion needs a constructor but ' + + _.type(constructor) + ' was given.', + undefined, + ssfi + ); + } + throw err; + } + + var name = _.getName(constructor); + if (name == null) { + name = 'an unnamed constructor'; + } + + this.assert( + isInstanceOf + , 'expected #{this} to be an instance of ' + name + , 'expected #{this} to not be an instance of ' + name + ); +}; + +Assertion.addMethod('instanceof', assertInstanceOf); +Assertion.addMethod('instanceOf', assertInstanceOf); + +/** + * ### .property(name[, val[, msg]]) + * + * Asserts that the target has a property with the given key `name`. + * + * expect({a: 1}).to.have.property('a'); + * + * When `val` is provided, `.property` also asserts that the property's value + * is equal to the given `val`. + * + * expect({a: 1}).to.have.property('a', 1); + * + * By default, strict (`===`) equality is used. Add `.deep` earlier in the + * chain to use deep equality instead. See the `deep-eql` project page for + * info on the deep equality algorithm: https://github.com/chaijs/deep-eql. + * + * // Target object deeply (but not strictly) has property `x: {a: 1}` + * expect({x: {a: 1}}).to.have.deep.property('x', {a: 1}); + * expect({x: {a: 1}}).to.not.have.property('x', {a: 1}); + * + * The target's enumerable and non-enumerable properties are always included + * in the search. By default, both own and inherited properties are included. + * Add `.own` earlier in the chain to exclude inherited properties from the + * search. + * + * Object.prototype.b = 2; + * + * expect({a: 1}).to.have.own.property('a'); + * expect({a: 1}).to.have.own.property('a', 1); + * expect({a: 1}).to.have.property('b'); + * expect({a: 1}).to.not.have.own.property('b'); + * + * `.deep` and `.own` can be combined. + * + * expect({x: {a: 1}}).to.have.deep.own.property('x', {a: 1}); + * + * Add `.nested` earlier in the chain to enable dot- and bracket-notation when + * referencing nested properties. + * + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); + * expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]', 'y'); + * + * If `.` or `[]` are part of an actual property name, they can be escaped by + * adding two backslashes before them. + * + * expect({'.a': {'[b]': 'x'}}).to.have.nested.property('\\.a.\\[b\\]'); + * + * `.deep` and `.nested` can be combined. + * + * expect({a: {b: [{c: 3}]}}) + * .to.have.deep.nested.property('a.b[0]', {c: 3}); + * + * `.own` and `.nested` cannot be combined. + * + * Add `.not` earlier in the chain to negate `.property`. + * + * expect({a: 1}).to.not.have.property('b'); + * + * However, it's dangerous to negate `.property` when providing `val`. The + * problem is that it creates uncertain expectations by asserting that the + * target either doesn't have a property with the given key `name`, or that it + * does have a property with the given key `name` but its value isn't equal to + * the given `val`. It's often best to identify the exact output that's + * expected, and then write an assertion that only accepts that exact output. + * + * When the target isn't expected to have a property with the given key + * `name`, it's often best to assert exactly that. + * + * expect({b: 2}).to.not.have.property('a'); // Recommended + * expect({b: 2}).to.not.have.property('a', 1); // Not recommended + * + * When the target is expected to have a property with the given key `name`, + * it's often best to assert that the property has its expected value, rather + * than asserting that it doesn't have one of many unexpected values. + * + * expect({a: 3}).to.have.property('a', 3); // Recommended + * expect({a: 3}).to.not.have.property('a', 1); // Not recommended + * + * `.property` changes the target of any assertions that follow in the chain + * to be the value of the property from the original target object. + * + * expect({a: 1}).to.have.property('a').that.is.a('number'); + * + * `.property` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing `val`, only use the + * second form. + * + * // Recommended + * expect({a: 1}).to.have.property('a', 2, 'nooo why fail??'); + * expect({a: 1}, 'nooo why fail??').to.have.property('a', 2); + * expect({a: 1}, 'nooo why fail??').to.have.property('b'); + * + * // Not recommended + * expect({a: 1}).to.have.property('b', undefined, 'nooo why fail??'); + * + * The above assertion isn't the same thing as not providing `val`. Instead, + * it's asserting that the target object has a `b` property that's equal to + * `undefined`. + * + * The assertions `.ownProperty` and `.haveOwnProperty` can be used + * interchangeably with `.own.property`. + * + * @name property + * @param {string} name + * @param {unknown} val (optional) + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function assertProperty (name, val, msg) { + if (msg) flag(this, 'message', msg); + + var isNested = flag(this, 'nested') + , isOwn = flag(this, 'own') + , flagMsg = flag(this, 'message') + , obj = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , nameType = typeof name; + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + if (isNested) { + if (nameType !== 'string') { + throw new AssertionError( + flagMsg + 'the argument to property must be a string when using nested syntax', + undefined, + ssfi + ); + } + } else { + if (nameType !== 'string' && nameType !== 'number' && nameType !== 'symbol') { + throw new AssertionError( + flagMsg + 'the argument to property must be a string, number, or symbol', + undefined, + ssfi + ); + } + } + + if (isNested && isOwn) { + throw new AssertionError( + flagMsg + 'The "nested" and "own" flags cannot be combined.', + undefined, + ssfi + ); + } + + if (obj === null || obj === undefined) { + throw new AssertionError( + flagMsg + 'Target cannot be null or undefined.', + undefined, + ssfi + ); + } + + var isDeep = flag(this, 'deep') + , negate = flag(this, 'negate') + , pathInfo = isNested ? _.getPathInfo(obj, name) : null + , value = isNested ? pathInfo.value : obj[name] + , isEql = isDeep ? flag(this, 'eql') : (val1, val2) => val1 === val2; + + var descriptor = ''; + if (isDeep) descriptor += 'deep '; + if (isOwn) descriptor += 'own '; + if (isNested) descriptor += 'nested '; + descriptor += 'property '; + + var hasProperty; + if (isOwn) hasProperty = Object.prototype.hasOwnProperty.call(obj, name); + else if (isNested) hasProperty = pathInfo.exists; + else hasProperty = _.hasProperty(obj, name); + + // When performing a negated assertion for both name and val, merely having + // a property with the given name isn't enough to cause the assertion to + // fail. It must both have a property with the given name, and the value of + // that property must equal the given val. Therefore, skip this assertion in + // favor of the next. + if (!negate || arguments.length === 1) { + this.assert( + hasProperty + , 'expected #{this} to have ' + descriptor + _.inspect(name) + , 'expected #{this} to not have ' + descriptor + _.inspect(name)); + } + + if (arguments.length > 1) { + this.assert( + hasProperty && isEql(val, value) + , 'expected #{this} to have ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' + , 'expected #{this} to not have ' + descriptor + _.inspect(name) + ' of #{act}' + , val + , value + ); + } + + flag(this, 'object', value); +} + +Assertion.addMethod('property', assertProperty); + +/** + * + * @param {unknown} name + * @param {unknown} value + * @param {string} msg + */ +function assertOwnProperty (name, value, msg) { + flag(this, 'own', true); + assertProperty.apply(this, arguments); +} + +Assertion.addMethod('ownProperty', assertOwnProperty); +Assertion.addMethod('haveOwnProperty', assertOwnProperty); + +/** + * ### .ownPropertyDescriptor(name[, descriptor[, msg]]) + * + * Asserts that the target has its own property descriptor with the given key + * `name`. Enumerable and non-enumerable properties are included in the + * search. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a'); + * + * When `descriptor` is provided, `.ownPropertyDescriptor` also asserts that + * the property's descriptor is deeply equal to the given `descriptor`. See + * the `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * Add `.not` earlier in the chain to negate `.ownPropertyDescriptor`. + * + * expect({a: 1}).to.not.have.ownPropertyDescriptor('b'); + * + * However, it's dangerous to negate `.ownPropertyDescriptor` when providing + * a `descriptor`. The problem is that it creates uncertain expectations by + * asserting that the target either doesn't have a property descriptor with + * the given key `name`, or that it does have a property descriptor with the + * given key `name` but it’s not deeply equal to the given `descriptor`. It's + * often best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to have a property descriptor with the given + * key `name`, it's often best to assert exactly that. + * + * // Recommended + * expect({b: 2}).to.not.have.ownPropertyDescriptor('a'); + * + * // Not recommended + * expect({b: 2}).to.not.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * When the target is expected to have a property descriptor with the given + * key `name`, it's often best to assert that the property has its expected + * descriptor, rather than asserting that it doesn't have one of many + * unexpected descriptors. + * + * // Recommended + * expect({a: 3}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 3, + * }); + * + * // Not recommended + * expect({a: 3}).to.not.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 1, + * }); + * + * `.ownPropertyDescriptor` changes the target of any assertions that follow + * in the chain to be the value of the property descriptor from the original + * target object. + * + * expect({a: 1}).to.have.ownPropertyDescriptor('a') + * .that.has.property('enumerable', true); + * + * `.ownPropertyDescriptor` accepts an optional `msg` argument which is a + * custom error message to show when the assertion fails. The message can also + * be given as the second argument to `expect`. When not providing + * `descriptor`, only use the second form. + * + * // Recommended + * expect({a: 1}).to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 2, + * }, 'nooo why fail??'); + * + * // Recommended + * expect({a: 1}, 'nooo why fail??').to.have.ownPropertyDescriptor('a', { + * configurable: true, + * enumerable: true, + * writable: true, + * value: 2, + * }); + * + * // Recommended + * expect({a: 1}, 'nooo why fail??').to.have.ownPropertyDescriptor('b'); + * + * // Not recommended + * expect({a: 1}) + * .to.have.ownPropertyDescriptor('b', undefined, 'nooo why fail??'); + * + * The above assertion isn't the same thing as not providing `descriptor`. + * Instead, it's asserting that the target object has a `b` property + * descriptor that's deeply equal to `undefined`. + * + * The alias `.haveOwnPropertyDescriptor` can be used interchangeably with + * `.ownPropertyDescriptor`. + * + * @name ownPropertyDescriptor + * @alias haveOwnPropertyDescriptor + * @param {string} name + * @param {object} descriptor _optional_ + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function assertOwnPropertyDescriptor (name, descriptor, msg) { + if (typeof descriptor === 'string') { + msg = descriptor; + descriptor = null; + } + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var actualDescriptor = Object.getOwnPropertyDescriptor(Object(obj), name); + var eql = flag(this, 'eql'); + if (actualDescriptor && descriptor) { + this.assert( + eql(descriptor, actualDescriptor) + , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to match ' + _.inspect(descriptor) + ', got ' + _.inspect(actualDescriptor) + , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to not match ' + _.inspect(descriptor) + , descriptor + , actualDescriptor + , true + ); + } else { + this.assert( + actualDescriptor + , 'expected #{this} to have an own property descriptor for ' + _.inspect(name) + , 'expected #{this} to not have an own property descriptor for ' + _.inspect(name) + ); + } + flag(this, 'object', actualDescriptor); +} + +Assertion.addMethod('ownPropertyDescriptor', assertOwnPropertyDescriptor); +Assertion.addMethod('haveOwnPropertyDescriptor', assertOwnPropertyDescriptor); + +/** + * + */ +function assertLengthChain () { + flag(this, 'doLength', true); +} + +/** + * ### .lengthOf(n[, msg]) + * + * Asserts that the target's `length` or `size` is equal to the given number + * `n`. + * + * expect([1, 2, 3]).to.have.lengthOf(3); + * expect('foo').to.have.lengthOf(3); + * expect(new Set([1, 2, 3])).to.have.lengthOf(3); + * expect(new Map([['a', 1], ['b', 2], ['c', 3]])).to.have.lengthOf(3); + * + * Add `.not` earlier in the chain to negate `.lengthOf`. However, it's often + * best to assert that the target's `length` property is equal to its expected + * value, rather than not equal to one of many unexpected values. + * + * expect('foo').to.have.lengthOf(3); // Recommended + * expect('foo').to.not.have.lengthOf(4); // Not recommended + * + * `.lengthOf` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2, 3]).to.have.lengthOf(2, 'nooo why fail??'); + * expect([1, 2, 3], 'nooo why fail??').to.have.lengthOf(2); + * + * `.lengthOf` can also be used as a language chain, causing all `.above`, + * `.below`, `.least`, `.most`, and `.within` assertions that follow in the + * chain to use the target's `length` property as the target. However, it's + * often best to assert that the target's `length` property is equal to its + * expected length, rather than asserting that its `length` property falls + * within some range of values. + * + * // Recommended + * expect([1, 2, 3]).to.have.lengthOf(3); + * + * // Not recommended + * expect([1, 2, 3]).to.have.lengthOf.above(2); + * expect([1, 2, 3]).to.have.lengthOf.below(4); + * expect([1, 2, 3]).to.have.lengthOf.at.least(3); + * expect([1, 2, 3]).to.have.lengthOf.at.most(3); + * expect([1, 2, 3]).to.have.lengthOf.within(2,4); + * + * Due to a compatibility issue, the alias `.length` can't be chained directly + * off of an uninvoked method such as `.a`. Therefore, `.length` can't be used + * interchangeably with `.lengthOf` in every situation. It's recommended to + * always use `.lengthOf` instead of `.length`. + * + * expect([1, 2, 3]).to.have.a.length(3); // incompatible; throws error + * expect([1, 2, 3]).to.have.a.lengthOf(3); // passes as expected + * + * @name lengthOf + * @alias length + * @param {number} n + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function assertLength (n, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , objType = _.type(obj).toLowerCase() + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi') + , descriptor = 'length' + , itemsCount; + + switch (objType) { + case 'map': + case 'set': + descriptor = 'size'; + itemsCount = obj.size; + break; + default: + new Assertion(obj, flagMsg, ssfi, true).to.have.property('length'); + itemsCount = obj.length; + } + + this.assert( + itemsCount == n + , 'expected #{this} to have a ' + descriptor + ' of #{exp} but got #{act}' + , 'expected #{this} to not have a ' + descriptor + ' of #{act}' + , n + , itemsCount + ); +} + +Assertion.addChainableMethod('length', assertLength, assertLengthChain); +Assertion.addChainableMethod('lengthOf', assertLength, assertLengthChain); + +/** + * ### .match(re[, msg]) + * + * Asserts that the target matches the given regular expression `re`. + * + * expect('foobar').to.match(/^foo/); + * + * Add `.not` earlier in the chain to negate `.match`. + * + * expect('foobar').to.not.match(/taco/); + * + * `.match` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect('foobar').to.match(/taco/, 'nooo why fail??'); + * expect('foobar', 'nooo why fail??').to.match(/taco/); + * + * The alias `.matches` can be used interchangeably with `.match`. + * + * @name match + * @alias matches + * @param {RegExp} re + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function assertMatch(re, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + this.assert( + re.exec(obj) + , 'expected #{this} to match ' + re + , 'expected #{this} not to match ' + re + ); +} + +Assertion.addMethod('match', assertMatch); +Assertion.addMethod('matches', assertMatch); + +/** + * ### .string(str[, msg]) + * + * Asserts that the target string contains the given substring `str`. + * + * expect('foobar').to.have.string('bar'); + * + * Add `.not` earlier in the chain to negate `.string`. + * + * expect('foobar').to.not.have.string('taco'); + * + * `.string` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect('foobar').to.have.string('taco', 'nooo why fail??'); + * expect('foobar', 'nooo why fail??').to.have.string('taco'); + * + * @name string + * @param {string} str + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +Assertion.addMethod('string', function (str, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(obj, flagMsg, ssfi, true).is.a('string'); + + this.assert( + ~obj.indexOf(str) + , 'expected #{this} to contain ' + _.inspect(str) + , 'expected #{this} to not contain ' + _.inspect(str) + ); +}); + +/** + * ### .keys(key1[, key2[, ...]]) + * + * Asserts that the target object, array, map, or set has the given keys. Only + * the target's own inherited properties are included in the search. + * + * When the target is an object or array, keys can be provided as one or more + * string arguments, a single array argument, or a single object argument. In + * the latter case, only the keys in the given object matter; the values are + * ignored. + * + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * expect(['x', 'y']).to.have.all.keys(0, 1); + * + * expect({a: 1, b: 2}).to.have.all.keys(['a', 'b']); + * expect(['x', 'y']).to.have.all.keys([0, 1]); + * + * expect({a: 1, b: 2}).to.have.all.keys({a: 4, b: 5}); // ignore 4 and 5 + * expect(['x', 'y']).to.have.all.keys({0: 4, 1: 5}); // ignore 4 and 5 + * + * When the target is a map or set, each key must be provided as a separate + * argument. + * + * expect(new Map([['a', 1], ['b', 2]])).to.have.all.keys('a', 'b'); + * expect(new Set(['a', 'b'])).to.have.all.keys('a', 'b'); + * + * Because `.keys` does different things based on the target's type, it's + * important to check the target's type before using `.keys`. See the `.a` doc + * for info on testing a target's type. + * + * expect({a: 1, b: 2}).to.be.an('object').that.has.all.keys('a', 'b'); + * + * By default, strict (`===`) equality is used to compare keys of maps and + * sets. Add `.deep` earlier in the chain to use deep equality instead. See + * the `deep-eql` project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target set deeply (but not strictly) has key `{a: 1}` + * expect(new Set([{a: 1}])).to.have.all.deep.keys([{a: 1}]); + * expect(new Set([{a: 1}])).to.not.have.all.keys([{a: 1}]); + * + * By default, the target must have all of the given keys and no more. Add + * `.any` earlier in the chain to only require that the target have at least + * one of the given keys. Also, add `.not` earlier in the chain to negate + * `.keys`. It's often best to add `.any` when negating `.keys`, and to use + * `.all` when asserting `.keys` without negation. + * + * When negating `.keys`, `.any` is preferred because `.not.any.keys` asserts + * exactly what's expected of the output, whereas `.not.all.keys` creates + * uncertain expectations. + * + * // Recommended; asserts that target doesn't have any of the given keys + * expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); + * + * // Not recommended; asserts that target doesn't have all of the given + * // keys but may or may not have some of them + * expect({a: 1, b: 2}).to.not.have.all.keys('c', 'd'); + * + * When asserting `.keys` without negation, `.all` is preferred because + * `.all.keys` asserts exactly what's expected of the output, whereas + * `.any.keys` creates uncertain expectations. + * + * // Recommended; asserts that target has all the given keys + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); + * + * // Not recommended; asserts that target has at least one of the given + * // keys but may or may not have more of them + * expect({a: 1, b: 2}).to.have.any.keys('a', 'b'); + * + * Note that `.all` is used by default when neither `.all` nor `.any` appear + * earlier in the chain. However, it's often best to add `.all` anyway because + * it improves readability. + * + * // Both assertions are identical + * expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); // Recommended + * expect({a: 1, b: 2}).to.have.keys('a', 'b'); // Not recommended + * + * Add `.include` earlier in the chain to require that the target's keys be a + * superset of the expected keys, rather than identical sets. + * + * // Target object's keys are a superset of ['a', 'b'] but not identical + * expect({a: 1, b: 2, c: 3}).to.include.all.keys('a', 'b'); + * expect({a: 1, b: 2, c: 3}).to.not.have.all.keys('a', 'b'); + * + * However, if `.any` and `.include` are combined, only the `.any` takes + * effect. The `.include` is ignored in this case. + * + * // Both assertions are identical + * expect({a: 1}).to.have.any.keys('a', 'b'); + * expect({a: 1}).to.include.any.keys('a', 'b'); + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.have.key('b'); + * + * The alias `.key` can be used interchangeably with `.keys`. + * + * @name keys + * @alias key + * @param {...string | Array | object} keys + * @namespace BDD + * @public + */ +function assertKeys (keys) { + var obj = flag(this, 'object') + , objType = _.type(obj) + , keysType = _.type(keys) + , ssfi = flag(this, 'ssfi') + , isDeep = flag(this, 'deep') + , str + , deepStr = '' + , actual + , ok = true + , flagMsg = flag(this, 'message'); + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + var mixedArgsMsg = flagMsg + 'when testing keys against an object or an array you must give a single Array|Object|String argument or multiple String arguments'; + + if (objType === 'Map' || objType === 'Set') { + deepStr = isDeep ? 'deeply ' : ''; + actual = []; + + // Map and Set '.keys' aren't supported in IE 11. Therefore, use .forEach. + obj.forEach(function (val, key) { actual.push(key) }); + + if (keysType !== 'Array') { + keys = Array.prototype.slice.call(arguments); + } + } else { + actual = _.getOwnEnumerableProperties(obj); + + switch (keysType) { + case 'Array': + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, undefined, ssfi); + } + break; + case 'Object': + if (arguments.length > 1) { + throw new AssertionError(mixedArgsMsg, undefined, ssfi); + } + keys = Object.keys(keys); + break; + default: + keys = Array.prototype.slice.call(arguments); + } + + // Only stringify non-Symbols because Symbols would become "Symbol()" + keys = keys.map(function (val) { + return typeof val === 'symbol' ? val : String(val); + }); + } + + if (!keys.length) { + throw new AssertionError(flagMsg + 'keys required', undefined, ssfi); + } + + var len = keys.length + , any = flag(this, 'any') + , all = flag(this, 'all') + , expected = keys + , isEql = isDeep ? flag(this, 'eql') : (val1, val2) => val1 === val2; + + if (!any && !all) { + all = true; + } + + // Has any + if (any) { + ok = expected.some(function(expectedKey) { + return actual.some(function(actualKey) { + return isEql(expectedKey, actualKey); + }); + }); + } + + // Has all + if (all) { + ok = expected.every(function(expectedKey) { + return actual.some(function(actualKey) { + return isEql(expectedKey, actualKey); + }); + }); + + if (!flag(this, 'contains')) { + ok = ok && keys.length == actual.length; + } + } + + // Key string + if (len > 1) { + keys = keys.map(function(key) { + return _.inspect(key); + }); + var last = keys.pop(); + if (all) { + str = keys.join(', ') + ', and ' + last; + } + if (any) { + str = keys.join(', ') + ', or ' + last; + } + } else { + str = _.inspect(keys[0]); + } + + // Form + str = (len > 1 ? 'keys ' : 'key ') + str; + + // Have / include + str = (flag(this, 'contains') ? 'contain ' : 'have ') + str; + + // Assertion + this.assert( + ok + , 'expected #{this} to ' + deepStr + str + , 'expected #{this} to not ' + deepStr + str + , expected.slice(0).sort(_.compareByInspect) + , actual.sort(_.compareByInspect) + , true + ); +} + +Assertion.addMethod('keys', assertKeys); +Assertion.addMethod('key', assertKeys); + +/** + * ### .throw([errorLike], [errMsgMatcher], [msg]) + * + * When no arguments are provided, `.throw` invokes the target function and + * asserts that an error is thrown. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * expect(badFn).to.throw(); + * + * When one argument is provided, and it's an error constructor, `.throw` + * invokes the target function and asserts that an error is thrown that's an + * instance of that error constructor. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * expect(badFn).to.throw(TypeError); + * + * When one argument is provided, and it's an error instance, `.throw` invokes + * the target function and asserts that an error is thrown that's strictly + * (`===`) equal to that error instance. + * + * var err = new TypeError('Illegal salmon!'); + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(err); + * + * When one argument is provided, and it's a string, `.throw` invokes the + * target function and asserts that an error is thrown with a message that + * contains that string. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * expect(badFn).to.throw('salmon'); + * + * When one argument is provided, and it's a regular expression, `.throw` + * invokes the target function and asserts that an error is thrown with a + * message that matches that regular expression. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * expect(badFn).to.throw(/salmon/); + * + * When two arguments are provided, and the first is an error instance or + * constructor, and the second is a string or regular expression, `.throw` + * invokes the function and asserts that an error is thrown that fulfills both + * conditions as described above. + * + * var err = new TypeError('Illegal salmon!'); + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(TypeError, 'salmon'); + * expect(badFn).to.throw(TypeError, /salmon/); + * expect(badFn).to.throw(err, 'salmon'); + * expect(badFn).to.throw(err, /salmon/); + * + * Add `.not` earlier in the chain to negate `.throw`. + * + * var goodFn = function () {}; + * expect(goodFn).to.not.throw(); + * + * However, it's dangerous to negate `.throw` when providing any arguments. + * The problem is that it creates uncertain expectations by asserting that the + * target either doesn't throw an error, or that it throws an error but of a + * different type than the given type, or that it throws an error of the given + * type but with a message that doesn't include the given string. It's often + * best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to throw an error, it's often best to assert + * exactly that. + * + * var goodFn = function () {}; + * + * expect(goodFn).to.not.throw(); // Recommended + * expect(goodFn).to.not.throw(ReferenceError, 'x'); // Not recommended + * + * When the target is expected to throw an error, it's often best to assert + * that the error is of its expected type, and has a message that includes an + * expected string, rather than asserting that it doesn't have one of many + * unexpected types, and doesn't have a message that includes some string. + * + * var badFn = function () { throw new TypeError('Illegal salmon!'); }; + * + * expect(badFn).to.throw(TypeError, 'salmon'); // Recommended + * expect(badFn).to.not.throw(ReferenceError, 'x'); // Not recommended + * + * `.throw` changes the target of any assertions that follow in the chain to + * be the error object that's thrown. + * + * var err = new TypeError('Illegal salmon!'); + * err.code = 42; + * var badFn = function () { throw err; }; + * + * expect(badFn).to.throw(TypeError).with.property('code', 42); + * + * `.throw` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. When not providing two arguments, always use + * the second form. + * + * var goodFn = function () {}; + * + * expect(goodFn).to.throw(TypeError, 'x', 'nooo why fail??'); + * expect(goodFn, 'nooo why fail??').to.throw(); + * + * Due to limitations in ES5, `.throw` may not always work as expected when + * using a transpiler such as Babel or TypeScript. In particular, it may + * produce unexpected results when subclassing the built-in `Error` object and + * then passing the subclassed constructor to `.throw`. See your transpiler's + * docs for details: + * + * - ([Babel](https://babeljs.io/docs/usage/caveats/#classes)) + * - ([TypeScript](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work)) + * + * Beware of some common mistakes when using the `throw` assertion. One common + * mistake is to accidentally invoke the function yourself instead of letting + * the `throw` assertion invoke the function for you. For example, when + * testing if a function named `fn` throws, provide `fn` instead of `fn()` as + * the target for the assertion. + * + * expect(fn).to.throw(); // Good! Tests `fn` as desired + * expect(fn()).to.throw(); // Bad! Tests result of `fn()`, not `fn` + * + * If you need to assert that your function `fn` throws when passed certain + * arguments, then wrap a call to `fn` inside of another function. + * + * expect(function () { fn(42); }).to.throw(); // Function expression + * expect(() => fn(42)).to.throw(); // ES6 arrow function + * + * Another common mistake is to provide an object method (or any stand-alone + * function that relies on `this`) as the target of the assertion. Doing so is + * problematic because the `this` context will be lost when the function is + * invoked by `.throw`; there's no way for it to know what `this` is supposed + * to be. There are two ways around this problem. One solution is to wrap the + * method or function call inside of another function. Another solution is to + * use `bind`. + * + * expect(function () { cat.meow(); }).to.throw(); // Function expression + * expect(() => cat.meow()).to.throw(); // ES6 arrow function + * expect(cat.meow.bind(cat)).to.throw(); // Bind + * + * Finally, it's worth mentioning that it's a best practice in JavaScript to + * only throw `Error` and derivatives of `Error` such as `ReferenceError`, + * `TypeError`, and user-defined objects that extend `Error`. No other type of + * value will generate a stack trace when initialized. With that said, the + * `throw` assertion does technically support any type of value being thrown, + * not just `Error` and its derivatives. + * + * The aliases `.throws` and `.Throw` can be used interchangeably with + * `.throw`. + * + * @name throw + * @alias throws + * @alias Throw + * @param {Error} errorLike + * @param {string | RegExp} errMsgMatcher error message + * @param {string} msg _optional_ + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @returns {void} error for chaining (null if no error) + * @namespace BDD + * @public + */ +function assertThrows (errorLike, errMsgMatcher, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , ssfi = flag(this, 'ssfi') + , flagMsg = flag(this, 'message') + , negate = flag(this, 'negate') || false; + new Assertion(obj, flagMsg, ssfi, true).is.a('function'); + + if (_.isRegExp(errorLike) || typeof errorLike === 'string') { + errMsgMatcher = errorLike; + errorLike = null; + } + + let caughtErr; + let errorWasThrown = false; + try { + obj(); + } catch (err) { + errorWasThrown = true; + caughtErr = err; + } + + // If we have the negate flag enabled and at least one valid argument it means we do expect an error + // but we want it to match a given set of criteria + var everyArgIsUndefined = errorLike === undefined && errMsgMatcher === undefined; + + // If we've got the negate flag enabled and both args, we should only fail if both aren't compatible + // See Issue #551 and PR #683@GitHub + var everyArgIsDefined = Boolean(errorLike && errMsgMatcher); + var errorLikeFail = false; + var errMsgMatcherFail = false; + + // Checking if error was thrown + if (everyArgIsUndefined || !everyArgIsUndefined && !negate) { + // We need this to display results correctly according to their types + var errorLikeString = 'an error'; + if (errorLike instanceof Error) { + errorLikeString = '#{exp}'; + } else if (errorLike) { + errorLikeString = _.checkError.getConstructorName(errorLike); + } + + let actual = caughtErr; + if (caughtErr instanceof Error) { + actual = caughtErr.toString(); + } else if (typeof caughtErr === 'string') { + actual = caughtErr; + } else if (caughtErr && (typeof caughtErr === 'object' || typeof caughtErr === 'function')) { + try { + actual = _.checkError.getConstructorName(caughtErr); + } catch (_err) { + // somehow wasn't a constructor, maybe we got a function thrown + // or similar + } + } + + this.assert( + errorWasThrown + , 'expected #{this} to throw ' + errorLikeString + , 'expected #{this} to not throw an error but #{act} was thrown' + , errorLike && errorLike.toString() + , actual + ); + } + + if (errorLike && caughtErr) { + // We should compare instances only if `errorLike` is an instance of `Error` + if (errorLike instanceof Error) { + var isCompatibleInstance = _.checkError.compatibleInstance(caughtErr, errorLike); + + if (isCompatibleInstance === negate) { + // These checks were created to ensure we won't fail too soon when we've got both args and a negate + // See Issue #551 and PR #683@GitHub + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr && !negate ? ' but #{act} was thrown' : '') + , errorLike.toString() + , caughtErr.toString() + ); + } + } + } + + var isCompatibleConstructor = _.checkError.compatibleConstructor(caughtErr, errorLike); + if (isCompatibleConstructor === negate) { + if (everyArgIsDefined && negate) { + errorLikeFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr ? ' but #{act} was thrown' : '') + , (errorLike instanceof Error ? errorLike.toString() : errorLike && _.checkError.getConstructorName(errorLike)) + , (caughtErr instanceof Error ? caughtErr.toString() : caughtErr && _.checkError.getConstructorName(caughtErr)) + ); + } + } + } + + if (caughtErr && errMsgMatcher !== undefined && errMsgMatcher !== null) { + // Here we check compatible messages + var placeholder = 'including'; + if (_.isRegExp(errMsgMatcher)) { + placeholder = 'matching' + } + + var isCompatibleMessage = _.checkError.compatibleMessage(caughtErr, errMsgMatcher); + if (isCompatibleMessage === negate) { + if (everyArgIsDefined && negate) { + errMsgMatcherFail = true; + } else { + this.assert( + negate + , 'expected #{this} to throw error ' + placeholder + ' #{exp} but got #{act}' + , 'expected #{this} to throw error not ' + placeholder + ' #{exp}' + , errMsgMatcher + , _.checkError.getMessage(caughtErr) + ); + } + } + } + + // If both assertions failed and both should've matched we throw an error + if (errorLikeFail && errMsgMatcherFail) { + this.assert( + negate + , 'expected #{this} to throw #{exp} but #{act} was thrown' + , 'expected #{this} to not throw #{exp}' + (caughtErr ? ' but #{act} was thrown' : '') + , (errorLike instanceof Error ? errorLike.toString() : errorLike && _.checkError.getConstructorName(errorLike)) + , (caughtErr instanceof Error ? caughtErr.toString() : caughtErr && _.checkError.getConstructorName(caughtErr)) + ); + } + + flag(this, 'object', caughtErr); +}; + +Assertion.addMethod('throw', assertThrows); +Assertion.addMethod('throws', assertThrows); +Assertion.addMethod('Throw', assertThrows); + +/** + * ### .respondTo(method[, msg]) + * + * When the target is a non-function object, `.respondTo` asserts that the + * target has a method with the given name `method`. The method can be own or + * inherited, and it can be enumerable or non-enumerable. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(new Cat()).to.respondTo('meow'); + * + * When the target is a function, `.respondTo` asserts that the target's + * `prototype` property has a method with the given name `method`. Again, the + * method can be own or inherited, and it can be enumerable or non-enumerable. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(Cat).to.respondTo('meow'); + * + * Add `.itself` earlier in the chain to force `.respondTo` to treat the + * target as a non-function object, even if it's a function. Thus, it asserts + * that the target has a method with the given name `method`, rather than + * asserting that the target's `prototype` property has a method with the + * given name `method`. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * Cat.hiss = function () {}; + * + * expect(Cat).itself.to.respondTo('hiss').but.not.respondTo('meow'); + * + * When not adding `.itself`, it's important to check the target's type before + * using `.respondTo`. See the `.a` doc for info on checking a target's type. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * + * expect(new Cat()).to.be.an('object').that.respondsTo('meow'); + * + * Add `.not` earlier in the chain to negate `.respondTo`. + * + * function Dog () {} + * Dog.prototype.bark = function () {}; + * + * expect(new Dog()).to.not.respondTo('meow'); + * + * `.respondTo` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect({}).to.respondTo('meow', 'nooo why fail??'); + * expect({}, 'nooo why fail??').to.respondTo('meow'); + * + * The alias `.respondsTo` can be used interchangeably with `.respondTo`. + * + * @name respondTo + * @alias respondsTo + * @param {string} method + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function respondTo (method, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , itself = flag(this, 'itself') + , context = ('function' === typeof obj && !itself) + ? obj.prototype[method] + : obj[method]; + + this.assert( + 'function' === typeof context + , 'expected #{this} to respond to ' + _.inspect(method) + , 'expected #{this} to not respond to ' + _.inspect(method) + ); +} + +Assertion.addMethod('respondTo', respondTo); +Assertion.addMethod('respondsTo', respondTo); + +/** + * ### .itself + * + * Forces all `.respondTo` assertions that follow in the chain to behave as if + * the target is a non-function object, even if it's a function. Thus, it + * causes `.respondTo` to assert that the target has a method with the given + * name, rather than asserting that the target's `prototype` property has a + * method with the given name. + * + * function Cat () {} + * Cat.prototype.meow = function () {}; + * Cat.hiss = function () {}; + * + * expect(Cat).itself.to.respondTo('hiss').but.not.respondTo('meow'); + * + * @name itself + * @namespace BDD + * @public + */ +Assertion.addProperty('itself', function () { + flag(this, 'itself', true); +}); + +/** + * ### .satisfy(matcher[, msg]) + * + * Invokes the given `matcher` function with the target being passed as the + * first argument, and asserts that the value returned is truthy. + * + * expect(1).to.satisfy(function(num) { + * return num > 0; + * }); + * + * Add `.not` earlier in the chain to negate `.satisfy`. + * + * expect(1).to.not.satisfy(function(num) { + * return num > 2; + * }); + * + * `.satisfy` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1).to.satisfy(function(num) { + * return num > 2; + * }, 'nooo why fail??'); + * + * expect(1, 'nooo why fail??').to.satisfy(function(num) { + * return num > 2; + * }); + * + * The alias `.satisfies` can be used interchangeably with `.satisfy`. + * + * @name satisfy + * @alias satisfies + * @param {Function} matcher + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function satisfy (matcher, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + var result = matcher(obj); + this.assert( + result + , 'expected #{this} to satisfy ' + _.objDisplay(matcher) + , 'expected #{this} to not satisfy' + _.objDisplay(matcher) + , flag(this, 'negate') ? false : true + , result + ); +} + +Assertion.addMethod('satisfy', satisfy); +Assertion.addMethod('satisfies', satisfy); + +/** + * ### .closeTo(expected, delta[, msg]) + * + * Asserts that the target is a number that's within a given +/- `delta` range + * of the given number `expected`. However, it's often best to assert that the + * target is equal to its expected value. + * + * // Recommended + * expect(1.5).to.equal(1.5); + * + * // Not recommended + * expect(1.5).to.be.closeTo(1, 0.5); + * expect(1.5).to.be.closeTo(2, 0.5); + * expect(1.5).to.be.closeTo(1, 1); + * + * Add `.not` earlier in the chain to negate `.closeTo`. + * + * expect(1.5).to.equal(1.5); // Recommended + * expect(1.5).to.not.be.closeTo(3, 1); // Not recommended + * + * `.closeTo` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect(1.5).to.be.closeTo(3, 1, 'nooo why fail??'); + * expect(1.5, 'nooo why fail??').to.be.closeTo(3, 1); + * + * The alias `.approximately` can be used interchangeably with `.closeTo`. + * + * @name closeTo + * @alias approximately + * @param {number} expected + * @param {number} delta + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function closeTo(expected, delta, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + + new Assertion(obj, flagMsg, ssfi, true).is.numeric; + let message = 'A `delta` value is required for `closeTo`'; + if (delta == undefined) throw new AssertionError(flagMsg ? `${flagMsg}: ${message}` : message, undefined, ssfi); + new Assertion(delta, flagMsg, ssfi, true).is.numeric; + message = 'A `expected` value is required for `closeTo`'; + if (expected == undefined) throw new AssertionError(flagMsg ? `${flagMsg}: ${message}` : message, undefined, ssfi); + new Assertion(expected, flagMsg, ssfi, true).is.numeric; + + const abs = (x) => x < 0n ? -x : x; + + this.assert( + abs(obj - expected) <= delta + , 'expected #{this} to be close to ' + expected + ' +/- ' + delta + , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta + ); +} + +Assertion.addMethod('closeTo', closeTo); +Assertion.addMethod('approximately', closeTo); + +/** + * @param {unknown} _subset + * @param {unknown} _superset + * @param {unknown} cmp + * @param {unknown} contains + * @param {unknown} ordered + * @returns {boolean} + */ +function isSubsetOf(_subset, _superset, cmp, contains, ordered) { + let superset = Array.from(_superset); + let subset = Array.from(_subset); + if (!contains) { + if (subset.length !== superset.length) return false; + superset = superset.slice(); + } + + return subset.every(function(elem, idx) { + if (ordered) return cmp ? cmp(elem, superset[idx]) : elem === superset[idx]; + + if (!cmp) { + var matchIdx = superset.indexOf(elem); + if (matchIdx === -1) return false; + + // Remove match from superset so not counted twice if duplicate in subset. + if (!contains) superset.splice(matchIdx, 1); + return true; + } + + return superset.some(function(elem2, matchIdx) { + if (!cmp(elem, elem2)) return false; + + // Remove match from superset so not counted twice if duplicate in subset. + if (!contains) superset.splice(matchIdx, 1); + return true; + }); + }); +} + +/** + * ### .members(set[, msg]) + * + * Asserts that the target array has the same members as the given array + * `set`. + * + * expect([1, 2, 3]).to.have.members([2, 1, 3]); + * expect([1, 2, 2]).to.have.members([2, 1, 2]); + * + * By default, members are compared using strict (`===`) equality. Add `.deep` + * earlier in the chain to use deep equality instead. See the `deep-eql` + * project page for info on the deep equality algorithm: + * https://github.com/chaijs/deep-eql. + * + * // Target array deeply (but not strictly) has member `{a: 1}` + * expect([{a: 1}]).to.have.deep.members([{a: 1}]); + * expect([{a: 1}]).to.not.have.members([{a: 1}]); + * + * By default, order doesn't matter. Add `.ordered` earlier in the chain to + * require that members appear in the same order. + * + * expect([1, 2, 3]).to.have.ordered.members([1, 2, 3]); + * expect([1, 2, 3]).to.have.members([2, 1, 3]) + * .but.not.ordered.members([2, 1, 3]); + * + * By default, both arrays must be the same size. Add `.include` earlier in + * the chain to require that the target's members be a superset of the + * expected members. Note that duplicates are ignored in the subset when + * `.include` is added. + * + * // Target array is a superset of [1, 2] but not identical + * expect([1, 2, 3]).to.include.members([1, 2]); + * expect([1, 2, 3]).to.not.have.members([1, 2]); + * + * // Duplicates in the subset are ignored + * expect([1, 2, 3]).to.include.members([1, 2, 2, 2]); + * + * `.deep`, `.ordered`, and `.include` can all be combined. However, if + * `.include` and `.ordered` are combined, the ordering begins at the start of + * both arrays. + * + * expect([{a: 1}, {b: 2}, {c: 3}]) + * .to.include.deep.ordered.members([{a: 1}, {b: 2}]) + * .but.not.include.deep.ordered.members([{b: 2}, {c: 3}]); + * + * Add `.not` earlier in the chain to negate `.members`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the target array doesn't have all of the same members as + * the given array `set` but may or may not have some of them. It's often best + * to identify the exact output that's expected, and then write an assertion + * that only accepts that exact output. + * + * expect([1, 2]).to.not.include(3).and.not.include(4); // Recommended + * expect([1, 2]).to.not.have.members([3, 4]); // Not recommended + * + * `.members` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. + * + * expect([1, 2]).to.have.members([1, 2, 3], 'nooo why fail??'); + * expect([1, 2], 'nooo why fail??').to.have.members([1, 2, 3]); + * + * @name members + * @param {Array} set + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +Assertion.addMethod('members', function (subset, msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + + new Assertion(obj, flagMsg, ssfi, true).to.be.iterable; + new Assertion(subset, flagMsg, ssfi, true).to.be.iterable; + + var contains = flag(this, 'contains'); + var ordered = flag(this, 'ordered'); + + var subject, failMsg, failNegateMsg; + + if (contains) { + subject = ordered ? 'an ordered superset' : 'a superset'; + failMsg = 'expected #{this} to be ' + subject + ' of #{exp}'; + failNegateMsg = 'expected #{this} to not be ' + subject + ' of #{exp}'; + } else { + subject = ordered ? 'ordered members' : 'members'; + failMsg = 'expected #{this} to have the same ' + subject + ' as #{exp}'; + failNegateMsg = 'expected #{this} to not have the same ' + subject + ' as #{exp}'; + } + + var cmp = flag(this, 'deep') ? flag(this, 'eql') : undefined; + + this.assert( + isSubsetOf(subset, obj, cmp, contains, ordered) + , failMsg + , failNegateMsg + , subset + , obj + , true + ); +}); + +/** + * ### .iterable + * + * Asserts that the target is an iterable, which means that it has a iterator. + * + * expect([1, 2]).to.be.iterable; + * expect("foobar").to.be.iterable; + * + * Add `.not` earlier in the chain to negate `.iterable`. + * + * expect(1).to.not.be.iterable; + * expect(true).to.not.be.iterable; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(1, 'nooo why fail??').to.be.iterable; + * + * @name iterable + * @namespace BDD + * @public + */ +Assertion.addProperty('iterable', function(msg) { + if (msg) flag(this, 'message', msg); + var obj = flag(this, 'object'); + + this.assert( + obj != undefined && obj[Symbol.iterator] + , 'expected #{this} to be an iterable' + , 'expected #{this} to not be an iterable' + , obj + ); +}); + +/** + * ### .oneOf(list[, msg]) + * + * Asserts that the target is a member of the given array `list`. However, + * it's often best to assert that the target is equal to its expected value. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.be.oneOf([1, 2, 3]); // Not recommended + * + * Comparisons are performed using strict (`===`) equality. + * + * Add `.not` earlier in the chain to negate `.oneOf`. + * + * expect(1).to.equal(1); // Recommended + * expect(1).to.not.be.oneOf([2, 3, 4]); // Not recommended + * + * It can also be chained with `.contain` or `.include`, which will work with + * both arrays and strings: + * + * expect('Today is sunny').to.contain.oneOf(['sunny', 'cloudy']) + * expect('Today is rainy').to.not.contain.oneOf(['sunny', 'cloudy']) + * expect([1,2,3]).to.contain.oneOf([3,4,5]) + * expect([1,2,3]).to.not.contain.oneOf([4,5,6]) + * + * `.oneOf` accepts an optional `msg` argument which is a custom error message + * to show when the assertion fails. The message can also be given as the + * second argument to `expect`. + * + * expect(1).to.be.oneOf([2, 3, 4], 'nooo why fail??'); + * expect(1, 'nooo why fail??').to.be.oneOf([2, 3, 4]); + * + * @name oneOf + * @param {Array<*>} list + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function oneOf (list, msg) { + if (msg) flag(this, 'message', msg); + var expected = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi') + , contains = flag(this, 'contains') + , isDeep = flag(this, 'deep') + , eql = flag(this, 'eql'); + new Assertion(list, flagMsg, ssfi, true).to.be.an('array'); + + if (contains) { + this.assert( + list.some(function(possibility) { return expected.indexOf(possibility) > -1 }) + , 'expected #{this} to contain one of #{exp}' + , 'expected #{this} to not contain one of #{exp}' + , list + , expected + ); + } else { + if (isDeep) { + this.assert( + list.some(function(possibility) { return eql(expected, possibility) }) + , 'expected #{this} to deeply equal one of #{exp}' + , 'expected #{this} to deeply equal one of #{exp}' + , list + , expected + ); + } else { + this.assert( + list.indexOf(expected) > -1 + , 'expected #{this} to be one of #{exp}' + , 'expected #{this} to not be one of #{exp}' + , list + , expected + ); + } + } +} + +Assertion.addMethod('oneOf', oneOf); + +/** + * ### .change(subject[, prop[, msg]]) + * + * When one argument is provided, `.change` asserts that the given function + * `subject` returns a different value when it's invoked before the target + * function compared to when it's invoked afterward. However, it's often best + * to assert that `subject` is equal to its expected value. + * + * var dots = '' + * , addDot = function () { dots += '.'; } + * , getDots = function () { return dots; }; + * + * // Recommended + * expect(getDots()).to.equal(''); + * addDot(); + * expect(getDots()).to.equal('.'); + * + * // Not recommended + * expect(addDot).to.change(getDots); + * + * When two arguments are provided, `.change` asserts that the value of the + * given object `subject`'s `prop` property is different before invoking the + * target function compared to afterward. + * + * var myObj = {dots: ''} + * , addDot = function () { myObj.dots += '.'; }; + * + * // Recommended + * expect(myObj).to.have.property('dots', ''); + * addDot(); + * expect(myObj).to.have.property('dots', '.'); + * + * // Not recommended + * expect(addDot).to.change(myObj, 'dots'); + * + * Strict (`===`) equality is used to compare before and after values. + * + * Add `.not` earlier in the chain to negate `.change`. + * + * var dots = '' + * , noop = function () {} + * , getDots = function () { return dots; }; + * + * expect(noop).to.not.change(getDots); + * + * var myObj = {dots: ''} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'dots'); + * + * `.change` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {dots: ''} + * , addDot = function () { myObj.dots += '.'; }; + * + * expect(addDot).to.not.change(myObj, 'dots', 'nooo why fail??'); + * + * var dots = '' + * , addDot = function () { dots += '.'; } + * , getDots = function () { return dots; }; + * + * expect(addDot, 'nooo why fail??').to.not.change(getDots); + * + * `.change` also causes all `.by` assertions that follow in the chain to + * assert how much a numeric subject was increased or decreased by. However, + * it's dangerous to use `.change.by`. The problem is that it creates + * uncertain expectations by asserting that the subject either increases by + * the given delta, or that it decreases by the given delta. It's often best + * to identify the exact output that's expected, and then write an assertion + * that only accepts that exact output. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; } + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * The alias `.changes` can be used interchangeably with `.change`. + * + * @name change + * @alias changes + * @param {string} subject + * @param {string} prop name _optional_ + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function assertChanges (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + // This gets flagged because of the .by(delta) assertion + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'change'); + flag(this, 'realDelta', final !== initial); + + this.assert( + initial !== final + , 'expected ' + msgObj + ' to change' + , 'expected ' + msgObj + ' to not change' + ); +} + +Assertion.addMethod('change', assertChanges); +Assertion.addMethod('changes', assertChanges); + +/** + * ### .increase(subject[, prop[, msg]]) + * + * When one argument is provided, `.increase` asserts that the given function + * `subject` returns a greater number when it's invoked after invoking the + * target function compared to when it's invoked beforehand. `.increase` also + * causes all `.by` assertions that follow in the chain to assert how much + * greater of a number is returned. It's often best to assert that the return + * value increased by the expected amount, rather than asserting it increased + * by any amount. + * + * var val = 1 + * , addTwo = function () { val += 2; } + * , getVal = function () { return val; }; + * + * expect(addTwo).to.increase(getVal).by(2); // Recommended + * expect(addTwo).to.increase(getVal); // Not recommended + * + * When two arguments are provided, `.increase` asserts that the value of the + * given object `subject`'s `prop` property is greater after invoking the + * target function compared to beforehand. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.increase(myObj, 'val'); // Not recommended + * + * Add `.not` earlier in the chain to negate `.increase`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either decreases, or that it stays the same. + * It's often best to identify the exact output that's expected, and then + * write an assertion that only accepts that exact output. + * + * When the subject is expected to decrease, it's often best to assert that it + * decreased by the expected amount. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.not.increase(myObj, 'val'); // Not recommended + * + * When the subject is expected to stay the same, it's often best to assert + * exactly that. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'val'); // Recommended + * expect(noop).to.not.increase(myObj, 'val'); // Not recommended + * + * `.increase` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.increase(myObj, 'val', 'nooo why fail??'); + * + * var val = 1 + * , noop = function () {} + * , getVal = function () { return val; }; + * + * expect(noop, 'nooo why fail??').to.increase(getVal); + * + * The alias `.increases` can be used interchangeably with `.increase`. + * + * @name increase + * @alias increases + * @param {string | Function} subject + * @param {string} prop name _optional_ + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function assertIncreases (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + // Make sure that the target is a number + new Assertion(initial, flagMsg, ssfi, true).is.a('number'); + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'increase'); + flag(this, 'realDelta', final - initial); + + this.assert( + final - initial > 0 + , 'expected ' + msgObj + ' to increase' + , 'expected ' + msgObj + ' to not increase' + ); +} + +Assertion.addMethod('increase', assertIncreases); +Assertion.addMethod('increases', assertIncreases); + +/** + * ### .decrease(subject[, prop[, msg]]) + * + * When one argument is provided, `.decrease` asserts that the given function + * `subject` returns a lesser number when it's invoked after invoking the + * target function compared to when it's invoked beforehand. `.decrease` also + * causes all `.by` assertions that follow in the chain to assert how much + * lesser of a number is returned. It's often best to assert that the return + * value decreased by the expected amount, rather than asserting it decreased + * by any amount. + * + * var val = 1 + * , subtractTwo = function () { val -= 2; } + * , getVal = function () { return val; }; + * + * expect(subtractTwo).to.decrease(getVal).by(2); // Recommended + * expect(subtractTwo).to.decrease(getVal); // Not recommended + * + * When two arguments are provided, `.decrease` asserts that the value of the + * given object `subject`'s `prop` property is lesser after invoking the + * target function compared to beforehand. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.decrease(myObj, 'val'); // Not recommended + * + * Add `.not` earlier in the chain to negate `.decrease`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either increases, or that it stays the same. + * It's often best to identify the exact output that's expected, and then + * write an assertion that only accepts that exact output. + * + * When the subject is expected to increase, it's often best to assert that it + * increased by the expected amount. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.not.decrease(myObj, 'val'); // Not recommended + * + * When the subject is expected to stay the same, it's often best to assert + * exactly that. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.not.change(myObj, 'val'); // Recommended + * expect(noop).to.not.decrease(myObj, 'val'); // Not recommended + * + * `.decrease` accepts an optional `msg` argument which is a custom error + * message to show when the assertion fails. The message can also be given as + * the second argument to `expect`. When not providing two arguments, always + * use the second form. + * + * var myObj = {val: 1} + * , noop = function () {}; + * + * expect(noop).to.decrease(myObj, 'val', 'nooo why fail??'); + * + * var val = 1 + * , noop = function () {} + * , getVal = function () { return val; }; + * + * expect(noop, 'nooo why fail??').to.decrease(getVal); + * + * The alias `.decreases` can be used interchangeably with `.decrease`. + * + * @name decrease + * @alias decreases + * @param {string | Function} subject + * @param {string} prop name _optional_ + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function assertDecreases (subject, prop, msg) { + if (msg) flag(this, 'message', msg); + var fn = flag(this, 'object') + , flagMsg = flag(this, 'message') + , ssfi = flag(this, 'ssfi'); + new Assertion(fn, flagMsg, ssfi, true).is.a('function'); + + var initial; + if (!prop) { + new Assertion(subject, flagMsg, ssfi, true).is.a('function'); + initial = subject(); + } else { + new Assertion(subject, flagMsg, ssfi, true).to.have.property(prop); + initial = subject[prop]; + } + + // Make sure that the target is a number + new Assertion(initial, flagMsg, ssfi, true).is.a('number'); + + fn(); + + var final = prop === undefined || prop === null ? subject() : subject[prop]; + var msgObj = prop === undefined || prop === null ? initial : '.' + prop; + + flag(this, 'deltaMsgObj', msgObj); + flag(this, 'initialDeltaValue', initial); + flag(this, 'finalDeltaValue', final); + flag(this, 'deltaBehavior', 'decrease'); + flag(this, 'realDelta', initial - final); + + this.assert( + final - initial < 0 + , 'expected ' + msgObj + ' to decrease' + , 'expected ' + msgObj + ' to not decrease' + ); +} + +Assertion.addMethod('decrease', assertDecreases); +Assertion.addMethod('decreases', assertDecreases); + +/** + * ### .by(delta[, msg]) + * + * When following an `.increase` assertion in the chain, `.by` asserts that + * the subject of the `.increase` assertion increased by the given `delta`. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); + * + * When following a `.decrease` assertion in the chain, `.by` asserts that the + * subject of the `.decrease` assertion decreased by the given `delta`. + * + * var myObj = {val: 1} + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); + * + * When following a `.change` assertion in the chain, `.by` asserts that the + * subject of the `.change` assertion either increased or decreased by the + * given `delta`. However, it's dangerous to use `.change.by`. The problem is + * that it creates uncertain expectations. It's often best to identify the + * exact output that's expected, and then write an assertion that only accepts + * that exact output. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; } + * , subtractTwo = function () { myObj.val -= 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(2); // Recommended + * expect(addTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * expect(subtractTwo).to.decrease(myObj, 'val').by(2); // Recommended + * expect(subtractTwo).to.change(myObj, 'val').by(2); // Not recommended + * + * Add `.not` earlier in the chain to negate `.by`. However, it's often best + * to assert that the subject changed by its expected delta, rather than + * asserting that it didn't change by one of countless unexpected deltas. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * // Recommended + * expect(addTwo).to.increase(myObj, 'val').by(2); + * + * // Not recommended + * expect(addTwo).to.increase(myObj, 'val').but.not.by(3); + * + * `.by` accepts an optional `msg` argument which is a custom error message to + * show when the assertion fails. The message can also be given as the second + * argument to `expect`. + * + * var myObj = {val: 1} + * , addTwo = function () { myObj.val += 2; }; + * + * expect(addTwo).to.increase(myObj, 'val').by(3, 'nooo why fail??'); + * expect(addTwo, 'nooo why fail??').to.increase(myObj, 'val').by(3); + * + * @name by + * @param {number} delta + * @param {string} msg _optional_ + * @namespace BDD + * @public + */ +function assertDelta(delta, msg) { + if (msg) flag(this, 'message', msg); + + var msgObj = flag(this, 'deltaMsgObj'); + var initial = flag(this, 'initialDeltaValue'); + var final = flag(this, 'finalDeltaValue'); + var behavior = flag(this, 'deltaBehavior'); + var realDelta = flag(this, 'realDelta'); + + var expression; + if (behavior === 'change') { + expression = Math.abs(final - initial) === Math.abs(delta); + } else { + expression = realDelta === Math.abs(delta); + } + + this.assert( + expression + , 'expected ' + msgObj + ' to ' + behavior + ' by ' + delta + , 'expected ' + msgObj + ' to not ' + behavior + ' by ' + delta + ); +} + +Assertion.addMethod('by', assertDelta); + +/** + * ### .extensible + * + * Asserts that the target is extensible, which means that new properties can + * be added to it. Primitives are never extensible. + * + * expect({a: 1}).to.be.extensible; + * + * Add `.not` earlier in the chain to negate `.extensible`. + * + * var nonExtensibleObject = Object.preventExtensions({}) + * , sealedObject = Object.seal({}) + * , frozenObject = Object.freeze({}); + * + * expect(nonExtensibleObject).to.not.be.extensible; + * expect(sealedObject).to.not.be.extensible; + * expect(frozenObject).to.not.be.extensible; + * expect(1).to.not.be.extensible; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect(1, 'nooo why fail??').to.be.extensible; + * + * @name extensible + * @namespace BDD + * @public + */ +Assertion.addProperty('extensible', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return false. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible + // The following provides ES6 behavior for ES5 environments. + + var isExtensible = obj === Object(obj) && Object.isExtensible(obj); + + this.assert( + isExtensible + , 'expected #{this} to be extensible' + , 'expected #{this} to not be extensible' + ); +}); + +/** + * ### .sealed + * + * Asserts that the target is sealed, which means that new properties can't be + * added to it, and its existing properties can't be reconfigured or deleted. + * However, it's possible that its existing properties can still be reassigned + * to different values. Primitives are always sealed. + * + * var sealedObject = Object.seal({}); + * var frozenObject = Object.freeze({}); + * + * expect(sealedObject).to.be.sealed; + * expect(frozenObject).to.be.sealed; + * expect(1).to.be.sealed; + * + * Add `.not` earlier in the chain to negate `.sealed`. + * + * expect({a: 1}).to.not.be.sealed; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.be.sealed; + * + * @name sealed + * @namespace BDD + * @public + */ +Assertion.addProperty('sealed', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a sealed ordinary object, simply return true. + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed + // The following provides ES6 behavior for ES5 environments. + + var isSealed = obj === Object(obj) ? Object.isSealed(obj) : true; + + this.assert( + isSealed + , 'expected #{this} to be sealed' + , 'expected #{this} to not be sealed' + ); +}); + +/** + * ### .frozen + * + * Asserts that the target is frozen, which means that new properties can't be + * added to it, and its existing properties can't be reassigned to different + * values, reconfigured, or deleted. Primitives are always frozen. + * + * var frozenObject = Object.freeze({}); + * + * expect(frozenObject).to.be.frozen; + * expect(1).to.be.frozen; + * + * Add `.not` earlier in the chain to negate `.frozen`. + * + * expect({a: 1}).to.not.be.frozen; + * + * A custom error message can be given as the second argument to `expect`. + * + * expect({a: 1}, 'nooo why fail??').to.be.frozen; + * + * @name frozen + * @namespace BDD + * @public + */ +Assertion.addProperty('frozen', function() { + var obj = flag(this, 'object'); + + // In ES5, if the argument to this method is a primitive, then it will cause a TypeError. + // In ES6, a non-object argument will be treated as if it was a frozen ordinary object, simply return true. + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen + // The following provides ES6 behavior for ES5 environments. + + var isFrozen = obj === Object(obj) ? Object.isFrozen(obj) : true; + + this.assert( + isFrozen + , 'expected #{this} to be frozen' + , 'expected #{this} to not be frozen' + ); +}); + +/** + * ### .finite + * + * Asserts that the target is a number, and isn't `NaN` or positive/negative + * `Infinity`. + * + * expect(1).to.be.finite; + * + * Add `.not` earlier in the chain to negate `.finite`. However, it's + * dangerous to do so. The problem is that it creates uncertain expectations + * by asserting that the subject either isn't a number, or that it's `NaN`, or + * that it's positive `Infinity`, or that it's negative `Infinity`. It's often + * best to identify the exact output that's expected, and then write an + * assertion that only accepts that exact output. + * + * When the target isn't expected to be a number, it's often best to assert + * that it's the expected type, rather than asserting that it isn't one of + * many unexpected types. + * + * expect('foo').to.be.a('string'); // Recommended + * expect('foo').to.not.be.finite; // Not recommended + * + * When the target is expected to be `NaN`, it's often best to assert exactly + * that. + * + * expect(NaN).to.be.NaN; // Recommended + * expect(NaN).to.not.be.finite; // Not recommended + * + * When the target is expected to be positive infinity, it's often best to + * assert exactly that. + * + * expect(Infinity).to.equal(Infinity); // Recommended + * expect(Infinity).to.not.be.finite; // Not recommended + * + * When the target is expected to be negative infinity, it's often best to + * assert exactly that. + * + * expect(-Infinity).to.equal(-Infinity); // Recommended + * expect(-Infinity).to.not.be.finite; // Not recommended + * + * A custom error message can be given as the second argument to `expect`. + * + * expect('foo', 'nooo why fail??').to.be.finite; + * + * @name finite + * @namespace BDD + * @public + */ +Assertion.addProperty('finite', function(msg) { + var obj = flag(this, 'object'); + + this.assert( + typeof obj === 'number' && isFinite(obj) + , 'expected #{this} to be a finite number' + , 'expected #{this} to not be a finite number' + ); +}); diff --git a/node_modules/chai/lib/chai/interface/assert.js b/node_modules/chai/lib/chai/interface/assert.js new file mode 100644 index 000000000..721ec2a3a --- /dev/null +++ b/node_modules/chai/lib/chai/interface/assert.js @@ -0,0 +1,3051 @@ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +import * as chai from '../../../index.js'; +import {Assertion} from '../assertion.js'; +import {flag, inspect} from '../utils/index.js'; +import {AssertionError} from 'assertion-error'; + +/** + * ### assert(expression, message) + * + * Write your own test expressions. + * + * assert('foo' !== 'bar', 'foo is not bar'); + * assert(Array.isArray([]), 'empty arrays are arrays'); + * + * @param {unknown} express - expression to test for truthiness + * @param {string} errmsg - message to display on error + * @name assert + * @namespace Assert + * @public + */ +export function assert(express, errmsg) { + var test = new Assertion(null, null, chai.assert, true); + test.assert( + express + , errmsg + , '[ negation message unavailable ]' + ); +} + +/** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. Node.js `assert` module-compatible. + * + * assert.fail(); + * assert.fail("custom error message"); + * assert.fail(1, 2); + * assert.fail(1, 2, "custom error message"); + * assert.fail(1, 2, "custom error message", ">"); + * assert.fail(1, 2, undefined, ">"); + * + * @name fail + * @param {unknown} actual + * @param {unknown} expected + * @param {string} message + * @param {string} operator + * @namespace Assert + * @public + */ +assert.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + // Comply with Node's fail([message]) interface + + message = actual; + actual = undefined; + } + + message = message || 'assert.fail()'; + throw new AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, assert.fail); +}; + +/** + * ### .isOk(object, [message]) + * + * Asserts that `object` is truthy. + * + * assert.isOk('everything', 'everything is ok'); + * assert.isOk(false, 'this will fail'); + * + * @name isOk + * @alias ok + * @param {unknown} val object to test + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isOk = function (val, msg) { + new Assertion(val, msg, assert.isOk, true).is.ok; +}; + +/** + * ### .isNotOk(object, [message]) + * + * Asserts that `object` is falsy. + * + * assert.isNotOk('everything', 'this will fail'); + * assert.isNotOk(false, 'this will pass'); + * + * @name isNotOk + * @alias notOk + * @param {unknown} val object to test + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isNotOk = function (val, msg) { + new Assertion(val, msg, assert.isNotOk, true).is.not.ok; +}; + +/** + * ### .equal(actual, expected, [message]) + * + * Asserts non-strict equality (`==`) of `actual` and `expected`. + * + * assert.equal(3, '3', '== coerces values to strings'); + * + * @name equal + * @param {unknown} act + * @param {unknown} exp + * @param {string} msg + * @namespace Assert + * @public + */ +assert.equal = function (act, exp, msg) { + var test = new Assertion(act, msg, assert.equal, true); + + test.assert( + exp == flag(test, 'object') + , 'expected #{this} to equal #{exp}' + , 'expected #{this} to not equal #{act}' + , exp + , act + , true + ); +}; + +/** + * ### .notEqual(actual, expected, [message]) + * + * Asserts non-strict inequality (`!=`) of `actual` and `expected`. + * + * assert.notEqual(3, 4, 'these numbers are not equal'); + * + * @name notEqual + * @param {unknown} act + * @param {unknown} exp + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notEqual = function (act, exp, msg) { + var test = new Assertion(act, msg, assert.notEqual, true); + + test.assert( + exp != flag(test, 'object') + , 'expected #{this} to not equal #{exp}' + , 'expected #{this} to equal #{act}' + , exp + , act + , true + ); +}; + +/** + * ### .strictEqual(actual, expected, [message]) + * + * Asserts strict equality (`===`) of `actual` and `expected`. + * + * assert.strictEqual(true, true, 'these booleans are strictly equal'); + * + * @name strictEqual + * @param {unknown} act + * @param {unknown} exp + * @param {string} msg + * @namespace Assert + * @public + */ +assert.strictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.strictEqual, true).to.equal(exp); +}; + +/** + * ### .notStrictEqual(actual, expected, [message]) + * + * Asserts strict inequality (`!==`) of `actual` and `expected`. + * + * assert.notStrictEqual(3, '3', 'no coercion for strict equality'); + * + * @name notStrictEqual + * @param {unknown} act + * @param {unknown} exp + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notStrictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.notStrictEqual, true).to.not.equal(exp); +}; + +/** + * ### .deepEqual(actual, expected, [message]) + * + * Asserts that `actual` is deeply equal to `expected`. + * + * assert.deepEqual({ tea: 'green' }, { tea: 'green' }); + * + * @name deepEqual + * @param {unknown} act + * @param {unknown} exp + * @param {string} msg + * @alias deepStrictEqual + * @namespace Assert + * @public + */ +assert.deepEqual = assert.deepStrictEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.deepEqual, true).to.eql(exp); +}; + +/** + * ### .notDeepEqual(actual, expected, [message]) + * + * Assert that `actual` is not deeply equal to `expected`. + * + * assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' }); + * + * @name notDeepEqual + * @param {unknown} act + * @param {unknown} exp + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notDeepEqual = function (act, exp, msg) { + new Assertion(act, msg, assert.notDeepEqual, true).to.not.eql(exp); +}; + +/** + * ### .isAbove(valueToCheck, valueToBeAbove, [message]) + * + * Asserts `valueToCheck` is strictly greater than (>) `valueToBeAbove`. + * + * assert.isAbove(5, 2, '5 is strictly greater than 2'); + * + * @name isAbove + * @param {unknown} val + * @param {unknown} abv + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isAbove = function (val, abv, msg) { + new Assertion(val, msg, assert.isAbove, true).to.be.above(abv); +}; + +/** + * ### .isAtLeast(valueToCheck, valueToBeAtLeast, [message]) + * + * Asserts `valueToCheck` is greater than or equal to (>=) `valueToBeAtLeast`. + * + * assert.isAtLeast(5, 2, '5 is greater or equal to 2'); + * assert.isAtLeast(3, 3, '3 is greater or equal to 3'); + * + * @name isAtLeast + * @param {unknown} val + * @param {unknown} atlst + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isAtLeast = function (val, atlst, msg) { + new Assertion(val, msg, assert.isAtLeast, true).to.be.least(atlst); +}; + +/** + * ### .isBelow(valueToCheck, valueToBeBelow, [message]) + * + * Asserts `valueToCheck` is strictly less than (<) `valueToBeBelow`. + * + * assert.isBelow(3, 6, '3 is strictly less than 6'); + * + * @name isBelow + * @param {unknown} val + * @param {unknown} blw + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isBelow = function (val, blw, msg) { + new Assertion(val, msg, assert.isBelow, true).to.be.below(blw); +}; + +/** + * ### .isAtMost(valueToCheck, valueToBeAtMost, [message]) + * + * Asserts `valueToCheck` is less than or equal to (<=) `valueToBeAtMost`. + * + * assert.isAtMost(3, 6, '3 is less than or equal to 6'); + * assert.isAtMost(4, 4, '4 is less than or equal to 4'); + * + * @name isAtMost + * @param {unknown} val + * @param {unknown} atmst + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isAtMost = function (val, atmst, msg) { + new Assertion(val, msg, assert.isAtMost, true).to.be.most(atmst); +}; + +/** + * ### .isTrue(value, [message]) + * + * Asserts that `value` is true. + * + * var teaServed = true; + * assert.isTrue(teaServed, 'the tea has been served'); + * + * @name isTrue + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isTrue = function (val, msg) { + new Assertion(val, msg, assert.isTrue, true).is['true']; +}; + +/** + * ### .isNotTrue(value, [message]) + * + * Asserts that `value` is not true. + * + * var tea = 'tasty chai'; + * assert.isNotTrue(tea, 'great, time for tea!'); + * + * @name isNotTrue + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isNotTrue = function (val, msg) { + new Assertion(val, msg, assert.isNotTrue, true).to.not.equal(true); +}; + +/** + * ### .isFalse(value, [message]) + * + * Asserts that `value` is false. + * + * var teaServed = false; + * assert.isFalse(teaServed, 'no tea yet? hmm...'); + * + * @name isFalse + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isFalse = function (val, msg) { + new Assertion(val, msg, assert.isFalse, true).is['false']; +}; + +/** + * ### .isNotFalse(value, [message]) + * + * Asserts that `value` is not false. + * + * var tea = 'tasty chai'; + * assert.isNotFalse(tea, 'great, time for tea!'); + * + * @name isNotFalse + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isNotFalse = function (val, msg) { + new Assertion(val, msg, assert.isNotFalse, true).to.not.equal(false); +}; + +/** + * ### .isNull(value, [message]) + * + * Asserts that `value` is null. + * + * assert.isNull(err, 'there was no error'); + * + * @name isNull + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isNull = function (val, msg) { + new Assertion(val, msg, assert.isNull, true).to.equal(null); +}; + +/** + * ### .isNotNull(value, [message]) + * + * Asserts that `value` is not null. + * + * var tea = 'tasty chai'; + * assert.isNotNull(tea, 'great, time for tea!'); + * + * @name isNotNull + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isNotNull = function (val, msg) { + new Assertion(val, msg, assert.isNotNull, true).to.not.equal(null); +}; + +/** + * ### .isNaN + * + * Asserts that value is NaN. + * + * assert.isNaN(NaN, 'NaN is NaN'); + * + * @name isNaN + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isNaN = function (val, msg) { + new Assertion(val, msg, assert.isNaN, true).to.be.NaN; +}; + +/** + * ### .isNotNaN + * + * Asserts that value is not NaN. + * + * assert.isNotNaN(4, '4 is not NaN'); + * + * @name isNotNaN + * @param {unknown} value + * @param {string} message + * @namespace Assert + * @public + */ +assert.isNotNaN = function (value, message) { + new Assertion(value, message, assert.isNotNaN, true).not.to.be.NaN; +}; + +/** + * ### .exists + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var foo = 'hi'; + * assert.exists(foo, 'foo is neither `null` nor `undefined`'); + * + * @name exists + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.exists = function (val, msg) { + new Assertion(val, msg, assert.exists, true).to.exist; +}; + +/** + * ### .notExists + * + * Asserts that the target is either `null` or `undefined`. + * + * var bar = null + * , baz; + * + * assert.notExists(bar); + * assert.notExists(baz, 'baz is either null or undefined'); + * + * @name notExists + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notExists = function (val, msg) { + new Assertion(val, msg, assert.notExists, true).to.not.exist; +}; + +/** + * ### .isUndefined(value, [message]) + * + * Asserts that `value` is `undefined`. + * + * var tea; + * assert.isUndefined(tea, 'no tea defined'); + * + * @name isUndefined + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isUndefined = function (val, msg) { + new Assertion(val, msg, assert.isUndefined, true).to.equal(undefined); +}; + +/** + * ### .isDefined(value, [message]) + * + * Asserts that `value` is not `undefined`. + * + * var tea = 'cup of chai'; + * assert.isDefined(tea, 'tea has been defined'); + * + * @name isDefined + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isDefined = function (val, msg) { + new Assertion(val, msg, assert.isDefined, true).to.not.equal(undefined); +}; + +/** + * ### .isCallable(value, [message]) + * + * Asserts that `value` is a callable function. + * + * function serveTea() { return 'cup of tea'; }; + * assert.isCallable(serveTea, 'great, we can have tea now'); + * + * @name isCallable + * @param {unknown} value + * @param {string} message + * @namespace Assert + * @public + */ +assert.isCallable = function (value, message) { + new Assertion(value, message, assert.isCallable, true).is.callable; +} + +/** + * ### .isNotCallable(value, [message]) + * + * Asserts that `value` is _not_ a callable function. + * + * var serveTea = [ 'heat', 'pour', 'sip' ]; + * assert.isNotCallable(serveTea, 'great, we have listed the steps'); + * + * @name isNotCallable + * @param {unknown} value + * @param {string} message + * @namespace Assert + * @public + */ +assert.isNotCallable = function (value, message) { + new Assertion(value, message, assert.isNotCallable, true).is.not.callable; +}; + +/** + * ### .isObject(value, [message]) + * + * Asserts that `value` is an object of type 'Object' (as revealed by `Object.prototype.toString`). + * _The assertion does not match subclassed objects._ + * + * var selection = { name: 'Chai', serve: 'with spices' }; + * assert.isObject(selection, 'tea selection is an object'); + * + * @name isObject + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isObject = function (val, msg) { + new Assertion(val, msg, assert.isObject, true).to.be.a('object'); +}; + +/** + * ### .isNotObject(value, [message]) + * + * Asserts that `value` is _not_ an object of type 'Object' (as revealed by `Object.prototype.toString`). + * + * var selection = 'chai' + * assert.isNotObject(selection, 'tea selection is not an object'); + * assert.isNotObject(null, 'null is not an object'); + * + * @name isNotObject + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isNotObject = function (val, msg) { + new Assertion(val, msg, assert.isNotObject, true).to.not.be.a('object'); +}; + +/** + * ### .isArray(value, [message]) + * + * Asserts that `value` is an array. + * + * var menu = [ 'green', 'chai', 'oolong' ]; + * assert.isArray(menu, 'what kind of tea do we want?'); + * + * @name isArray + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isArray = function (val, msg) { + new Assertion(val, msg, assert.isArray, true).to.be.an('array'); +}; + +/** + * ### .isNotArray(value, [message]) + * + * Asserts that `value` is _not_ an array. + * + * var menu = 'green|chai|oolong'; + * assert.isNotArray(menu, 'what kind of tea do we want?'); + * + * @name isNotArray + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isNotArray = function (val, msg) { + new Assertion(val, msg, assert.isNotArray, true).to.not.be.an('array'); +}; + +/** + * ### .isString(value, [message]) + * + * Asserts that `value` is a string. + * + * var teaOrder = 'chai'; + * assert.isString(teaOrder, 'order placed'); + * + * @name isString + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isString = function (val, msg) { + new Assertion(val, msg, assert.isString, true).to.be.a('string'); +}; + +/** + * ### .isNotString(value, [message]) + * + * Asserts that `value` is _not_ a string. + * + * var teaOrder = 4; + * assert.isNotString(teaOrder, 'order placed'); + * + * @name isNotString + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isNotString = function (val, msg) { + new Assertion(val, msg, assert.isNotString, true).to.not.be.a('string'); +}; + +/** + * ### .isNumber(value, [message]) + * + * Asserts that `value` is a number. + * + * var cups = 2; + * assert.isNumber(cups, 'how many cups'); + * + * @name isNumber + * @param {number} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isNumber = function (val, msg) { + new Assertion(val, msg, assert.isNumber, true).to.be.a('number'); +}; + +/** + * ### .isNotNumber(value, [message]) + * + * Asserts that `value` is _not_ a number. + * + * var cups = '2 cups please'; + * assert.isNotNumber(cups, 'how many cups'); + * + * @name isNotNumber + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isNotNumber = function (val, msg) { + new Assertion(val, msg, assert.isNotNumber, true).to.not.be.a('number'); +}; + +/** + * ### .isNumeric(value, [message]) + * + * Asserts that `value` is a number or BigInt. + * + * var cups = 2; + * assert.isNumeric(cups, 'how many cups'); + * + * var cups = 10n; + * assert.isNumeric(cups, 'how many cups'); + * + * @name isNumeric + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isNumeric = function (val, msg) { + new Assertion(val, msg, assert.isNumeric, true).is.numeric; +}; + +/** + * ### .isNotNumeric(value, [message]) + * + * Asserts that `value` is _not_ a number or BigInt. + * + * var cups = '2 cups please'; + * assert.isNotNumeric(cups, 'how many cups'); + * + * @name isNotNumeric + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isNotNumeric = function (val, msg) { + new Assertion(val, msg, assert.isNotNumeric, true).is.not.numeric; +}; + + /** + * ### .isFinite(value, [message]) + * + * Asserts that `value` is a finite number. Unlike `.isNumber`, this will fail for `NaN` and `Infinity`. + * + * var cups = 2; + * assert.isFinite(cups, 'how many cups'); + * assert.isFinite(NaN); // throws + * + * @name isFinite + * @param {number} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isFinite = function (val, msg) { + new Assertion(val, msg, assert.isFinite, true).to.be.finite; +}; + +/** + * ### .isBoolean(value, [message]) + * + * Asserts that `value` is a boolean. + * + * var teaReady = true + * , teaServed = false; + * + * assert.isBoolean(teaReady, 'is the tea ready'); + * assert.isBoolean(teaServed, 'has tea been served'); + * + * @name isBoolean + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isBoolean = function (val, msg) { + new Assertion(val, msg, assert.isBoolean, true).to.be.a('boolean'); +}; + +/** + * ### .isNotBoolean(value, [message]) + * + * Asserts that `value` is _not_ a boolean. + * + * var teaReady = 'yep' + * , teaServed = 'nope'; + * + * assert.isNotBoolean(teaReady, 'is the tea ready'); + * assert.isNotBoolean(teaServed, 'has tea been served'); + * + * @name isNotBoolean + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.isNotBoolean = function (val, msg) { + new Assertion(val, msg, assert.isNotBoolean, true).to.not.be.a('boolean'); +}; + +/** + * ### .typeOf(value, name, [message]) + * + * Asserts that `value`'s type is `name`, as determined by + * `Object.prototype.toString`. + * + * assert.typeOf({ tea: 'chai' }, 'object', 'we have an object'); + * assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array'); + * assert.typeOf('tea', 'string', 'we have a string'); + * assert.typeOf(/tea/, 'regexp', 'we have a regular expression'); + * assert.typeOf(null, 'null', 'we have a null'); + * assert.typeOf(undefined, 'undefined', 'we have an undefined'); + * + * @name typeOf + * @param {unknown} val + * @param {string} type + * @param {string} msg + * @namespace Assert + * @public + */ +assert.typeOf = function (val, type, msg) { + new Assertion(val, msg, assert.typeOf, true).to.be.a(type); +}; + +/** + * ### .notTypeOf(value, name, [message]) + * + * Asserts that `value`'s type is _not_ `name`, as determined by + * `Object.prototype.toString`. + * + * assert.notTypeOf('tea', 'number', 'strings are not numbers'); + * + * @name notTypeOf + * @param {unknown} value + * @param {string} type + * @param {string} message + * @namespace Assert + * @public + */ +assert.notTypeOf = function (value, type, message) { + new Assertion(value, message, assert.notTypeOf, true).to.not.be.a(type); +}; + +/** + * ### .instanceOf(object, constructor, [message]) + * + * Asserts that `value` is an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , chai = new Tea('chai'); + * + * assert.instanceOf(chai, Tea, 'chai is an instance of tea'); + * + * @name instanceOf + * @param {object} val + * @param {object} type + * @param {string} msg + * @namespace Assert + * @public + */ +assert.instanceOf = function (val, type, msg) { + new Assertion(val, msg, assert.instanceOf, true).to.be.instanceOf(type); +}; + +/** + * ### .notInstanceOf(object, constructor, [message]) + * + * Asserts `value` is not an instance of `constructor`. + * + * var Tea = function (name) { this.name = name; } + * , chai = new String('chai'); + * + * assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea'); + * + * @name notInstanceOf + * @param {object} val + * @param {object} type + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notInstanceOf = function (val, type, msg) { + new Assertion(val, msg, assert.notInstanceOf, true) + .to.not.be.instanceOf(type); +}; + +/** + * ### .include(haystack, needle, [message]) + * + * Asserts that `haystack` includes `needle`. Can be used to assert the + * inclusion of a value in an array, a substring in a string, or a subset of + * properties in an object. + * + * assert.include([1,2,3], 2, 'array contains value'); + * assert.include('foobar', 'foo', 'string contains substring'); + * assert.include({ foo: 'bar', hello: 'universe' }, { foo: 'bar' }, 'object contains property'); + * + * Strict equality (===) is used. When asserting the inclusion of a value in + * an array, the array is searched for an element that's strictly equal to the + * given value. When asserting a subset of properties in an object, the object + * is searched for the given property keys, checking that each one is present + * and strictly equal to the given property value. For instance: + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.include([obj1, obj2], obj1); + * assert.include({foo: obj1, bar: obj2}, {foo: obj1}); + * assert.include({foo: obj1, bar: obj2}, {foo: obj1, bar: obj2}); + * + * @name include + * @param {Array | string} exp + * @param {unknown} inc + * @param {string} msg + * @namespace Assert + * @public + */ +assert.include = function (exp, inc, msg) { + new Assertion(exp, msg, assert.include, true).include(inc); +}; + +/** + * ### .notInclude(haystack, needle, [message]) + * + * Asserts that `haystack` does not include `needle`. Can be used to assert + * the absence of a value in an array, a substring in a string, or a subset of + * properties in an object. + * + * assert.notInclude([1,2,3], 4, "array doesn't contain value"); + * assert.notInclude('foobar', 'baz', "string doesn't contain substring"); + * assert.notInclude({ foo: 'bar', hello: 'universe' }, { foo: 'baz' }, 'object doesn't contain property'); + * + * Strict equality (===) is used. When asserting the absence of a value in an + * array, the array is searched to confirm the absence of an element that's + * strictly equal to the given value. When asserting a subset of properties in + * an object, the object is searched to confirm that at least one of the given + * property keys is either not present or not strictly equal to the given + * property value. For instance: + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.notInclude([obj1, obj2], {a: 1}); + * assert.notInclude({foo: obj1, bar: obj2}, {foo: {a: 1}}); + * assert.notInclude({foo: obj1, bar: obj2}, {foo: obj1, bar: {b: 2}}); + * + * @name notInclude + * @param {Array | string} exp + * @param {unknown} inc + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notInclude, true).not.include(inc); +}; + +/** + * ### .deepInclude(haystack, needle, [message]) + * + * Asserts that `haystack` includes `needle`. Can be used to assert the + * inclusion of a value in an array or a subset of properties in an object. + * Deep equality is used. + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.deepInclude([obj1, obj2], {a: 1}); + * assert.deepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}}); + * assert.deepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}, bar: {b: 2}}); + * + * @name deepInclude + * @param {Array | string} exp + * @param {unknown} inc + * @param {string} msg + * @namespace Assert + * @public + */ +assert.deepInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.deepInclude, true).deep.include(inc); +}; + +/** + * ### .notDeepInclude(haystack, needle, [message]) + * + * Asserts that `haystack` does not include `needle`. Can be used to assert + * the absence of a value in an array or a subset of properties in an object. + * Deep equality is used. + * + * var obj1 = {a: 1} + * , obj2 = {b: 2}; + * assert.notDeepInclude([obj1, obj2], {a: 9}); + * assert.notDeepInclude({foo: obj1, bar: obj2}, {foo: {a: 9}}); + * assert.notDeepInclude({foo: obj1, bar: obj2}, {foo: {a: 1}, bar: {b: 9}}); + * + * @name notDeepInclude + * @param {Array | string} exp + * @param {unknown} inc + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notDeepInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepInclude, true).not.deep.include(inc); +}; + +/** + * ### .nestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.nestedInclude({'.a': {'b': 'x'}}, {'\\.a.[b]': 'x'}); + * assert.nestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'x'}); + * + * @name nestedInclude + * @param {object} exp + * @param {object} inc + * @param {string} msg + * @namespace Assert + * @public + */ +assert.nestedInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.nestedInclude, true).nested.include(inc); +}; + +/** + * ### .notNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' does not include 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.notNestedInclude({'.a': {'b': 'x'}}, {'\\.a.b': 'y'}); + * assert.notNestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'y'}); + * + * @name notNestedInclude + * @param {object} exp + * @param {object} inc + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notNestedInclude = function (exp, inc, msg) { + new Assertion(exp, msg, assert.notNestedInclude, true) + .not.nested.include(inc); +}; + +/** + * ### .deepNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while checking for deep equality. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.deepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {x: 1}}); + * assert.deepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {x: 1}}); + * + * @name deepNestedInclude + * @param {object} exp + * @param {object} inc + * @param {string} msg + * @namespace Assert + * @public + */ +assert.deepNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepNestedInclude, true) + .deep.nested.include(inc); +}; + +/** + * ### .notDeepNestedInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' does not include 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while checking for deep equality. + * Enables the use of dot- and bracket-notation for referencing nested + * properties. + * '[]' and '.' in property names can be escaped using double backslashes. + * + * assert.notDeepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {y: 1}}) + * assert.notDeepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {y: 2}}); + * + * @name notDeepNestedInclude + * @param {object} exp + * @param {object} inc + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notDeepNestedInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepNestedInclude, true) + .not.deep.nested.include(inc); +}; + +/** + * ### .ownInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while ignoring inherited properties. + * + * assert.ownInclude({ a: 1 }, { a: 1 }); + * + * @name ownInclude + * @param {object} exp + * @param {object} inc + * @param {string} msg + * @namespace Assert + * @public + */ +assert.ownInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.ownInclude, true).own.include(inc); +}; + +/** + * ### .notOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' does not include 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while ignoring inherited properties. + * + * Object.prototype.b = 2; + * assert.notOwnInclude({ a: 1 }, { b: 2 }); + * + * @name notOwnInclude + * @param {object} exp + * @param {object} inc + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notOwnInclude, true).not.own.include(inc); +}; + +/** + * ### .deepOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the inclusion of a subset of properties in an + * object while ignoring inherited properties and checking for deep equality. + * + * assert.deepOwnInclude({a: {b: 2}}, {a: {b: 2}}); + * + * @name deepOwnInclude + * @param {object} exp + * @param {object} inc + * @param {string} msg + * @namespace Assert + * @public + */ +assert.deepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.deepOwnInclude, true) + .deep.own.include(inc); +}; + +/** + * ### .notDeepOwnInclude(haystack, needle, [message]) + * + * Asserts that 'haystack' includes 'needle'. + * Can be used to assert the absence of a subset of properties in an + * object while ignoring inherited properties and checking for deep equality. + * + * assert.notDeepOwnInclude({a: {b: 2}}, {a: {c: 3}}); + * + * @name notDeepOwnInclude + * @param {object} exp + * @param {object} inc + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notDeepOwnInclude = function(exp, inc, msg) { + new Assertion(exp, msg, assert.notDeepOwnInclude, true) + .not.deep.own.include(inc); +}; + +/** + * ### .match(value, regexp, [message]) + * + * Asserts that `value` matches the regular expression `regexp`. + * + * assert.match('foobar', /^foo/, 'regexp matches'); + * + * @name match + * @param {unknown} exp + * @param {RegExp} re + * @param {string} msg + * @namespace Assert + * @public + */ +assert.match = function (exp, re, msg) { + new Assertion(exp, msg, assert.match, true).to.match(re); +}; + +/** + * ### .notMatch(value, regexp, [message]) + * + * Asserts that `value` does not match the regular expression `regexp`. + * + * assert.notMatch('foobar', /^foo/, 'regexp does not match'); + * + * @name notMatch + * @param {unknown} exp + * @param {RegExp} re + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notMatch = function (exp, re, msg) { + new Assertion(exp, msg, assert.notMatch, true).to.not.match(re); +}; + +/** + * ### .property(object, property, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property`. + * + * assert.property({ tea: { green: 'matcha' }}, 'tea'); + * assert.property({ tea: { green: 'matcha' }}, 'toString'); + * + * @name property + * @param {object} obj + * @param {string} prop + * @param {string} msg + * @namespace Assert + * @public + */ +assert.property = function (obj, prop, msg) { + new Assertion(obj, msg, assert.property, true).to.have.property(prop); +}; + +/** + * ### .notProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property`. + * + * assert.notProperty({ tea: { green: 'matcha' }}, 'coffee'); + * + * @name notProperty + * @param {object} obj + * @param {string} prop + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notProperty, true) + .to.not.have.property(prop); +}; + +/** + * ### .propertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property` with a value given by `value`. Uses a strict equality check + * (===). + * + * assert.propertyVal({ tea: 'is good' }, 'tea', 'is good'); + * + * @name propertyVal + * @param {object} obj + * @param {string} prop + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.propertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.propertyVal, true) + .to.have.property(prop, val); +}; + +/** + * ### .notPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property` with value given by `value`. Uses a strict equality check + * (===). + * + * assert.notPropertyVal({ tea: 'is good' }, 'tea', 'is bad'); + * assert.notPropertyVal({ tea: 'is good' }, 'coffee', 'is good'); + * + * @name notPropertyVal + * @param {object} obj + * @param {string} prop + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notPropertyVal, true) + .to.not.have.property(prop, val); +}; + +/** + * ### .deepPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property` with a value given by `value`. Uses a deep equality check. + * + * assert.deepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' }); + * + * @name deepPropertyVal + * @param {object} obj + * @param {string} prop + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.deepPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.deepPropertyVal, true) + .to.have.deep.property(prop, val); +}; + +/** + * ### .notDeepPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct or inherited property named + * by `property` with value given by `value`. Uses a deep equality check. + * + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' }); + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' }); + * assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' }); + * + * @name notDeepPropertyVal + * @param {object} obj + * @param {string} prop + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notDeepPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notDeepPropertyVal, true) + .to.not.have.deep.property(prop, val); +}; + +/** + * ### .ownProperty(object, property, [message]) + * + * Asserts that `object` has a direct property named by `property`. Inherited + * properties aren't checked. + * + * assert.ownProperty({ tea: { green: 'matcha' }}, 'tea'); + * + * @name ownProperty + * @param {object} obj + * @param {string} prop + * @param {string} msg + * @public + */ +assert.ownProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.ownProperty, true) + .to.have.own.property(prop); +}; + +/** + * ### .notOwnProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a direct property named by + * `property`. Inherited properties aren't checked. + * + * assert.notOwnProperty({ tea: { green: 'matcha' }}, 'coffee'); + * assert.notOwnProperty({}, 'toString'); + * + * @name notOwnProperty + * @param {object} obj + * @param {string} prop + * @param {string} msg + * @public + */ +assert.notOwnProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notOwnProperty, true) + .to.not.have.own.property(prop); +}; + +/** + * ### .ownPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct property named by `property` and a value + * equal to the provided `value`. Uses a strict equality check (===). + * Inherited properties aren't checked. + * + * assert.ownPropertyVal({ coffee: 'is good'}, 'coffee', 'is good'); + * + * @name ownPropertyVal + * @param {object} obj + * @param {string} prop + * @param {unknown} value + * @param {string} msg + * @public + */ +assert.ownPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.ownPropertyVal, true) + .to.have.own.property(prop, value); +}; + +/** + * ### .notOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct property named by `property` + * with a value equal to the provided `value`. Uses a strict equality check + * (===). Inherited properties aren't checked. + * + * assert.notOwnPropertyVal({ tea: 'is better'}, 'tea', 'is worse'); + * assert.notOwnPropertyVal({}, 'toString', Object.prototype.toString); + * + * @name notOwnPropertyVal + * @param {object} obj + * @param {string} prop + * @param {unknown} value + * @param {string} msg + * @public + */ +assert.notOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.notOwnPropertyVal, true) + .to.not.have.own.property(prop, value); +}; + +/** + * ### .deepOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a direct property named by `property` and a value + * equal to the provided `value`. Uses a deep equality check. Inherited + * properties aren't checked. + * + * assert.deepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' }); + * + * @name deepOwnPropertyVal + * @param {object} obj + * @param {string} prop + * @param {unknown} value + * @param {string} msg + * @public + */ +assert.deepOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.deepOwnPropertyVal, true) + .to.have.deep.own.property(prop, value); +}; + +/** + * ### .notDeepOwnPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a direct property named by `property` + * with a value equal to the provided `value`. Uses a deep equality check. + * Inherited properties aren't checked. + * + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' }); + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' }); + * assert.notDeepOwnPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' }); + * assert.notDeepOwnPropertyVal({}, 'toString', Object.prototype.toString); + * + * @name notDeepOwnPropertyVal + * @param {object} obj + * @param {string} prop + * @param {unknown} value + * @param {string} msg + * @public + */ +assert.notDeepOwnPropertyVal = function (obj, prop, value, msg) { + new Assertion(obj, msg, assert.notDeepOwnPropertyVal, true) + .to.not.have.deep.own.property(prop, value); +}; + +/** + * ### .nestedProperty(object, property, [message]) + * + * Asserts that `object` has a direct or inherited property named by + * `property`, which can be a string using dot- and bracket-notation for + * nested reference. + * + * assert.nestedProperty({ tea: { green: 'matcha' }}, 'tea.green'); + * + * @name nestedProperty + * @param {object} obj + * @param {string} prop + * @param {string} msg + * @namespace Assert + * @public + */ +assert.nestedProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.nestedProperty, true) + .to.have.nested.property(prop); +}; + +/** + * ### .notNestedProperty(object, property, [message]) + * + * Asserts that `object` does _not_ have a property named by `property`, which + * can be a string using dot- and bracket-notation for nested reference. The + * property cannot exist on the object nor anywhere in its prototype chain. + * + * assert.notNestedProperty({ tea: { green: 'matcha' }}, 'tea.oolong'); + * + * @name notNestedProperty + * @param {object} obj + * @param {string} prop + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notNestedProperty = function (obj, prop, msg) { + new Assertion(obj, msg, assert.notNestedProperty, true) + .to.not.have.nested.property(prop); +}; + +/** + * ### .nestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a property named by `property` with value given + * by `value`. `property` can use dot- and bracket-notation for nested + * reference. Uses a strict equality check (===). + * + * assert.nestedPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha'); + * + * @name nestedPropertyVal + * @param {object} obj + * @param {string} prop + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.nestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.nestedPropertyVal, true) + .to.have.nested.property(prop, val); +}; + +/** + * ### .notNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a property named by `property` with + * value given by `value`. `property` can use dot- and bracket-notation for + * nested reference. Uses a strict equality check (===). + * + * assert.notNestedPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha'); + * assert.notNestedPropertyVal({ tea: { green: 'matcha' }}, 'coffee.green', 'matcha'); + * + * @name notNestedPropertyVal + * @param {object} obj + * @param {string} prop + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notNestedPropertyVal, true) + .to.not.have.nested.property(prop, val); +}; + +/** + * ### .deepNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` has a property named by `property` with a value given + * by `value`. `property` can use dot- and bracket-notation for nested + * reference. Uses a deep equality check. + * + * assert.deepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yum' }); + * + * @name deepNestedPropertyVal + * @param {object} obj + * @param {string} prop + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.deepNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.deepNestedPropertyVal, true) + .to.have.deep.nested.property(prop, val); +}; + +/** + * ### .notDeepNestedPropertyVal(object, property, value, [message]) + * + * Asserts that `object` does _not_ have a property named by `property` with + * value given by `value`. `property` can use dot- and bracket-notation for + * nested reference. Uses a deep equality check. + * + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { oolong: 'yum' }); + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yuck' }); + * assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.black', { matcha: 'yum' }); + * + * @name notDeepNestedPropertyVal + * @param {object} obj + * @param {string} prop + * @param {unknown} val + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notDeepNestedPropertyVal = function (obj, prop, val, msg) { + new Assertion(obj, msg, assert.notDeepNestedPropertyVal, true) + .to.not.have.deep.nested.property(prop, val); +} + +/** + * ### .lengthOf(object, length, [message]) + * + * Asserts that `object` has a `length` or `size` with the expected value. + * + * assert.lengthOf([1,2,3], 3, 'array has length of 3'); + * assert.lengthOf('foobar', 6, 'string has length of 6'); + * assert.lengthOf(new Set([1,2,3]), 3, 'set has size of 3'); + * assert.lengthOf(new Map([['a',1],['b',2],['c',3]]), 3, 'map has size of 3'); + * + * @name lengthOf + * @param {unknown} exp + * @param {number} len + * @param {string} msg + * @namespace Assert + * @public + */ +assert.lengthOf = function (exp, len, msg) { + new Assertion(exp, msg, assert.lengthOf, true).to.have.lengthOf(len); +}; + +/** + * ### .hasAnyKeys(object, [keys], [message]) + * + * Asserts that `object` has at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'iDontExist', 'baz']); + * assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, iDontExist: 99, baz: 1337}); + * assert.hasAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.hasAnyKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); + * + * @name hasAnyKeys + * @param {unknown} obj + * @param {Array | object} keys + * @param {string} msg + * @namespace Assert + * @public + */ +assert.hasAnyKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyKeys, true).to.have.any.keys(keys); +} + +/** + * ### .hasAllKeys(object, [keys], [message]) + * + * Asserts that `object` has all and only all of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); + * assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337]); + * assert.hasAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.hasAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); + * + * @name hasAllKeys + * @param {unknown} obj + * @param {string[]} keys + * @param {string} msg + * @namespace Assert + * @public + */ +assert.hasAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllKeys, true).to.have.all.keys(keys); +} + +/** + * ### .containsAllKeys(object, [keys], [message]) + * + * Asserts that `object` has all of the `keys` provided but may have more keys not listed. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'baz']); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, baz: 1337}); + * assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337}); + * assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}]); + * assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + * assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}]); + * assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); + * + * @name containsAllKeys + * @param {unknown} obj + * @param {string[]} keys + * @param {string} msg + * @namespace Assert + * @public + */ +assert.containsAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.containsAllKeys, true) + .to.contain.all.keys(keys); +} + +/** + * ### .doesNotHaveAnyKeys(object, [keys], [message]) + * + * Asserts that `object` has none of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); + * assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); + * assert.doesNotHaveAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + * assert.doesNotHaveAnyKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{one: 'two'}, 'example']); + * + * @name doesNotHaveAnyKeys + * @param {unknown} obj + * @param {string[]} keys + * @param {string} msg + * @namespace Assert + * @public + */ +assert.doesNotHaveAnyKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAnyKeys, true) + .to.not.have.any.keys(keys); +} + +/** + * ### .doesNotHaveAllKeys(object, [keys], [message]) + * + * Asserts that `object` does not have at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); + * assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); + * assert.doesNotHaveAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + * assert.doesNotHaveAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{one: 'two'}, 'example']); + * + * @name doesNotHaveAllKeys + * @param {unknown} obj + * @param {string[]} keys + * @param {string} msg + * @namespace Assert + * @public + */ +assert.doesNotHaveAllKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAllKeys, true) + .to.not.have.all.keys(keys); +} + +/** + * ### .hasAnyDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {three: 'three'}]); + * assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name hasAnyDeepKeys + * @param {unknown} obj + * @param {Array | object} keys + * @param {string} msg + * @namespace Assert + * @public + */ +assert.hasAnyDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAnyDeepKeys, true) + .to.have.any.deep.keys(keys); +} + +/** + * ### .hasAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has all and only all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne']]), {one: 'one'}); + * assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.hasAllDeepKeys(new Set([{one: 'one'}]), {one: 'one'}); + * assert.hasAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name hasAllDeepKeys + * @param {unknown} obj + * @param {Array | object} keys + * @param {string} msg + * @namespace Assert + * @public + */ +assert.hasAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.hasAllDeepKeys, true) + .to.have.all.deep.keys(keys); +} + +/** + * ### .containsAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + * assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + * assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); + * assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + * + * @name containsAllDeepKeys + * @param {unknown} obj + * @param {Array | object} keys + * @param {string} msg + * @namespace Assert + * @public + */ +assert.containsAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.containsAllDeepKeys, true) + .to.contain.all.deep.keys(keys); +} + +/** + * ### .doesNotHaveAnyDeepKeys(object, [keys], [message]) + * + * Asserts that `object` has none of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + * assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + * assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); + * assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + * + * @name doesNotHaveAnyDeepKeys + * @param {unknown} obj + * @param {Array | object} keys + * @param {string} msg + * @namespace Assert + * @public + */ +assert.doesNotHaveAnyDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAnyDeepKeys, true) + .to.not.have.any.deep.keys(keys); +} + +/** + * ### .doesNotHaveAllDeepKeys(object, [keys], [message]) + * + * Asserts that `object` does not have at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + * assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {one: 'one'}]); + * assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); + * assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {fifty: 'fifty'}]); + * + * @name doesNotHaveAllDeepKeys + * @param {unknown} obj + * @param {Array | object} keys + * @param {string} msg + * @namespace Assert + * @public + */ +assert.doesNotHaveAllDeepKeys = function (obj, keys, msg) { + new Assertion(obj, msg, assert.doesNotHaveAllDeepKeys, true) + .to.not.have.all.deep.keys(keys); +} + +/** + * ### .throws(fn, [errorLike/string/regexp], [string/regexp], [message]) + * + * If `errorLike` is an `Error` constructor, asserts that `fn` will throw an error that is an + * instance of `errorLike`. + * If `errorLike` is an `Error` instance, asserts that the error thrown is the same + * instance as `errorLike`. + * If `errMsgMatcher` is provided, it also asserts that the error thrown will have a + * message matching `errMsgMatcher`. + * + * assert.throws(fn, 'Error thrown must have this msg'); + * assert.throws(fn, /Error thrown must have a msg that matches this/); + * assert.throws(fn, ReferenceError); + * assert.throws(fn, errorInstance); + * assert.throws(fn, ReferenceError, 'Error thrown must be a ReferenceError and have this msg'); + * assert.throws(fn, errorInstance, 'Error thrown must be the same errorInstance and have this msg'); + * assert.throws(fn, ReferenceError, /Error thrown must be a ReferenceError and match this/); + * assert.throws(fn, errorInstance, /Error thrown must be the same errorInstance and match this/); + * + * @name throws + * @alias throw + * @alias Throw + * @param {Function} fn + * @param {Error} errorLike + * @param {RegExp | string} errMsgMatcher + * @param {string} msg + * @returns {unknown} + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Assert + * @public + */ +assert.throws = function (fn, errorLike, errMsgMatcher, msg) { + if ('string' === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + + var assertErr = new Assertion(fn, msg, assert.throws, true) + .to.throw(errorLike, errMsgMatcher); + return flag(assertErr, 'object'); +}; + +/** + * ### .doesNotThrow(fn, [errorLike/string/regexp], [string/regexp], [message]) + * + * If `errorLike` is an `Error` constructor, asserts that `fn` will _not_ throw an error that is an + * instance of `errorLike`. + * If `errorLike` is an `Error` instance, asserts that the error thrown is _not_ the same + * instance as `errorLike`. + * If `errMsgMatcher` is provided, it also asserts that the error thrown will _not_ have a + * message matching `errMsgMatcher`. + * + * assert.doesNotThrow(fn, 'Any Error thrown must not have this message'); + * assert.doesNotThrow(fn, /Any Error thrown must not match this/); + * assert.doesNotThrow(fn, Error); + * assert.doesNotThrow(fn, errorInstance); + * assert.doesNotThrow(fn, Error, 'Error must not have this message'); + * assert.doesNotThrow(fn, errorInstance, 'Error must not have this message'); + * assert.doesNotThrow(fn, Error, /Error must not match this/); + * assert.doesNotThrow(fn, errorInstance, /Error must not match this/); + * + * @name doesNotThrow + * @param {Function} fn + * @param {Error} errorLike + * @param {RegExp | string} errMsgMatcher + * @param {string} message + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Assert + * @public + */ +assert.doesNotThrow = function (fn, errorLike, errMsgMatcher, message) { + if ('string' === typeof errorLike || errorLike instanceof RegExp) { + errMsgMatcher = errorLike; + errorLike = null; + } + + new Assertion(fn, message, assert.doesNotThrow, true) + .to.not.throw(errorLike, errMsgMatcher); +}; + +/** + * ### .operator(val1, operator, val2, [message]) + * + * Compares two values using `operator`. + * + * assert.operator(1, '<', 2, 'everything is ok'); + * assert.operator(1, '>', 2, 'this will fail'); + * + * @name operator + * @param {unknown} val + * @param {string} operator + * @param {unknown} val2 + * @param {string} msg + * @namespace Assert + * @public + */ +assert.operator = function (val, operator, val2, msg) { + var ok; + switch(operator) { + case '==': + ok = val == val2; + break; + case '===': + ok = val === val2; + break; + case '>': + ok = val > val2; + break; + case '>=': + ok = val >= val2; + break; + case '<': + ok = val < val2; + break; + case '<=': + ok = val <= val2; + break; + case '!=': + ok = val != val2; + break; + case '!==': + ok = val !== val2; + break; + default: + msg = msg ? msg + ': ' : msg; + throw new AssertionError( + msg + 'Invalid operator "' + operator + '"', + undefined, + assert.operator + ); + } + var test = new Assertion(ok, msg, assert.operator, true); + test.assert( + true === flag(test, 'object') + , 'expected ' + inspect(val) + ' to be ' + operator + ' ' + inspect(val2) + , 'expected ' + inspect(val) + ' to not be ' + operator + ' ' + inspect(val2) ); +}; + +/** + * ### .closeTo(actual, expected, delta, [message]) + * + * Asserts that the target is equal `expected`, to within a +/- `delta` range. + * + * assert.closeTo(1.5, 1, 0.5, 'numbers are close'); + * + * @name closeTo + * @param {number} act + * @param {number} exp + * @param {number} delta + * @param {string} msg + * @namespace Assert + * @public + */ +assert.closeTo = function (act, exp, delta, msg) { + new Assertion(act, msg, assert.closeTo, true).to.be.closeTo(exp, delta); +}; + +/** + * ### .approximately(actual, expected, delta, [message]) + * + * Asserts that the target is equal `expected`, to within a +/- `delta` range. + * + * assert.approximately(1.5, 1, 0.5, 'numbers are close'); + * + * @name approximately + * @param {number} act + * @param {number} exp + * @param {number} delta + * @param {string} msg + * @namespace Assert + * @public + */ +assert.approximately = function (act, exp, delta, msg) { + new Assertion(act, msg, assert.approximately, true) + .to.be.approximately(exp, delta); +}; + +/** + * ### .sameMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in any order. Uses a + * strict equality check (===). + * + * assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members'); + * + * @name sameMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {string} msg + * @namespace Assert + * @public + */ +assert.sameMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameMembers, true) + .to.have.same.members(set2); +} + +/** + * ### .notSameMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in any order. + * Uses a strict equality check (===). + * + * assert.notSameMembers([ 1, 2, 3 ], [ 5, 1, 3 ], 'not same members'); + * + * @name notSameMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notSameMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameMembers, true) + .to.not.have.same.members(set2); +} + +/** + * ### .sameDeepMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in any order. Uses a + * deep equality check. + * + * assert.sameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { c: 3 }], 'same deep members'); + * + * @name sameDeepMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {string} msg + * @namespace Assert + * @public + */ +assert.sameDeepMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameDeepMembers, true) + .to.have.same.deep.members(set2); +} + +/** + * ### .notSameDeepMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in any order. + * Uses a deep equality check. + * + * assert.notSameDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [{ b: 2 }, { a: 1 }, { f: 5 }], 'not same deep members'); + * + * @name notSameDeepMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notSameDeepMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameDeepMembers, true) + .to.not.have.same.deep.members(set2); +} + +/** + * ### .sameOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in the same order. + * Uses a strict equality check (===). + * + * assert.sameOrderedMembers([ 1, 2, 3 ], [ 1, 2, 3 ], 'same ordered members'); + * + * @name sameOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {string} msg + * @namespace Assert + * @public + */ +assert.sameOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameOrderedMembers, true) + .to.have.same.ordered.members(set2); +} + +/** + * ### .notSameOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in the same + * order. Uses a strict equality check (===). + * + * assert.notSameOrderedMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'not same ordered members'); + * + * @name notSameOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notSameOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameOrderedMembers, true) + .to.not.have.same.ordered.members(set2); +} + +/** + * ### .sameDeepOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` have the same members in the same order. + * Uses a deep equality check. + * + * assert.sameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { c: 3 } ], 'same deep ordered members'); + * + * @name sameDeepOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {string} msg + * @namespace Assert + * @public + */ +assert.sameDeepOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.sameDeepOrderedMembers, true) + .to.have.same.deep.ordered.members(set2); +} + +/** + * ### .notSameDeepOrderedMembers(set1, set2, [message]) + * + * Asserts that `set1` and `set2` don't have the same members in the same + * order. Uses a deep equality check. + * + * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { z: 5 } ], 'not same deep ordered members'); + * assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { c: 3 } ], 'not same deep ordered members'); + * + * @name notSameDeepOrderedMembers + * @param {Array} set1 + * @param {Array} set2 + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notSameDeepOrderedMembers = function (set1, set2, msg) { + new Assertion(set1, msg, assert.notSameDeepOrderedMembers, true) + .to.not.have.same.deep.ordered.members(set2); +} + +/** + * ### .includeMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in any order. Uses a + * strict equality check (===). Duplicates are ignored. + * + * assert.includeMembers([ 1, 2, 3 ], [ 2, 1, 2 ], 'include members'); + * + * @name includeMembers + * @param {Array} superset + * @param {Array} subset + * @param {string} msg + * @namespace Assert + * @public + */ +assert.includeMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeMembers, true) + .to.include.members(subset); +} + +/** + * ### .notIncludeMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in any order. Uses a + * strict equality check (===). Duplicates are ignored. + * + * assert.notIncludeMembers([ 1, 2, 3 ], [ 5, 1 ], 'not include members'); + * + * @name notIncludeMembers + * @param {Array} superset + * @param {Array} subset + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notIncludeMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeMembers, true) + .to.not.include.members(subset); +} + +/** + * ### .includeDeepMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in any order. Uses a deep + * equality check. Duplicates are ignored. + * + * assert.includeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { b: 2 } ], 'include deep members'); + * + * @name includeDeepMembers + * @param {Array} superset + * @param {Array} subset + * @param {string} msg + * @namespace Assert + * @public + */ +assert.includeDeepMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeDeepMembers, true) + .to.include.deep.members(subset); +} + +/** + * ### .notIncludeDeepMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in any order. Uses a + * deep equality check. Duplicates are ignored. + * + * assert.notIncludeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { f: 5 } ], 'not include deep members'); + * + * @name notIncludeDeepMembers + * @param {Array} superset + * @param {Array} subset + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notIncludeDeepMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeDeepMembers, true) + .to.not.include.deep.members(subset); +} + +/** + * ### .includeOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in the same order + * beginning with the first element in `superset`. Uses a strict equality + * check (===). + * + * assert.includeOrderedMembers([ 1, 2, 3 ], [ 1, 2 ], 'include ordered members'); + * + * @name includeOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {string} msg + * @namespace Assert + * @public + */ +assert.includeOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeOrderedMembers, true) + .to.include.ordered.members(subset); +} + +/** + * ### .notIncludeOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in the same order + * beginning with the first element in `superset`. Uses a strict equality + * check (===). + * + * assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 1 ], 'not include ordered members'); + * assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 3 ], 'not include ordered members'); + * + * @name notIncludeOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notIncludeOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeOrderedMembers, true) + .to.not.include.ordered.members(subset); +} + +/** + * ### .includeDeepOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` is included in `superset` in the same order + * beginning with the first element in `superset`. Uses a deep equality + * check. + * + * assert.includeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 } ], 'include deep ordered members'); + * + * @name includeDeepOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {string} msg + * @namespace Assert + * @public + */ +assert.includeDeepOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.includeDeepOrderedMembers, true) + .to.include.deep.ordered.members(subset); +} + +/** + * ### .notIncludeDeepOrderedMembers(superset, subset, [message]) + * + * Asserts that `subset` isn't included in `superset` in the same order + * beginning with the first element in `superset`. Uses a deep equality + * check. + * + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { f: 5 } ], 'not include deep ordered members'); + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 } ], 'not include deep ordered members'); + * assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { c: 3 } ], 'not include deep ordered members'); + * + * @name notIncludeDeepOrderedMembers + * @param {Array} superset + * @param {Array} subset + * @param {string} msg + * @namespace Assert + * @public + */ +assert.notIncludeDeepOrderedMembers = function (superset, subset, msg) { + new Assertion(superset, msg, assert.notIncludeDeepOrderedMembers, true) + .to.not.include.deep.ordered.members(subset); +} + +/** + * ### .oneOf(inList, list, [message]) + * + * Asserts that non-object, non-array value `inList` appears in the flat array `list`. + * + * assert.oneOf(1, [ 2, 1 ], 'Not found in list'); + * + * @name oneOf + * @param {*} inList + * @param {Array<*>} list + * @param {string} msg + * @namespace Assert + * @public + */ +assert.oneOf = function (inList, list, msg) { + new Assertion(inList, msg, assert.oneOf, true).to.be.oneOf(list); +} + +/** + * ### isIterable(obj, [message]) + * + * Asserts that the target is an iterable, which means that it has a iterator + * with the exception of `String.` + * + * assert.isIterable([1, 2]); + * + * @param {unknown} obj + * @param {string} [msg] + * @namespace Assert + * @public + */ +assert.isIterable = function(obj, msg) { + if (obj == undefined || !obj[Symbol.iterator]) { + msg = msg ? + `${msg} expected ${inspect(obj)} to be an iterable` : + `expected ${inspect(obj)} to be an iterable`; + + throw new AssertionError( + msg, + undefined, + assert.isIterable + ); + } +} + +/** + * ### .changes(function, object, property, [message]) + * + * Asserts that a function changes the value of a property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 22 }; + * assert.changes(fn, obj, 'val'); + * + * @name changes + * @param {Function} fn modifier function + * @param {object} obj object or getter function + * @param {string} prop property name _optional_ + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.changes = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changes, true).to.change(obj, prop); +} + +/** + * ### .changesBy(function, object, property, delta, [message]) + * + * Asserts that a function changes the value of a property by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 2 }; + * assert.changesBy(fn, obj, 'val', 2); + * + * @name changesBy + * @param {Function} fn modifier function + * @param {object} obj object or getter function + * @param {string} prop property name _optional_ + * @param {number} delta msg change amount (delta) + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.changesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changesBy, true) + .to.change(obj, prop).by(delta); +} + +/** + * ### .doesNotChange(function, object, property, [message]) + * + * Asserts that a function does not change the value of a property. + * + * var obj = { val: 10 }; + * var fn = function() { console.log('foo'); }; + * assert.doesNotChange(fn, obj, 'val'); + * + * @name doesNotChange + * @param {Function} fn modifier function + * @param {object} obj object or getter function + * @param {string} prop property name _optional_ + * @param {string} msg _optional_ + * @returns {unknown} + * @namespace Assert + * @public + */ +assert.doesNotChange = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotChange, true) + .to.not.change(obj, prop); +} + +/** + * ### .changesButNotBy(function, object, property, delta, [message]) + * + * Asserts that a function does not change the value of a property or of a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 10 }; + * assert.changesButNotBy(fn, obj, 'val', 5); + * + * @name changesButNotBy + * @param {Function} fn - modifier function + * @param {object} obj - object or getter function + * @param {string} prop - property name _optional_ + * @param {number} delta - change amount (delta) + * @param {string} msg - message _optional_ + * @namespace Assert + * @public + */ +assert.changesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.changesButNotBy, true) + .to.change(obj, prop).but.not.by(delta); +} + +/** + * ### .increases(function, object, property, [message]) + * + * Asserts that a function increases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 13 }; + * assert.increases(fn, obj, 'val'); + * + * @public + * @namespace Assert + * @name increases + * @param {Function} fn - modifier function + * @param {object} obj - object or getter function + * @param {string} prop - property name _optional_ + * @param {string} msg - message _optional_ + * @returns {unknown} + */ +assert.increases = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.increases, true) + .to.increase(obj, prop); +} + +/** + * ### .increasesBy(function, object, property, delta, [message]) + * + * Asserts that a function increases a numeric object property or a function's return value by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val += 10 }; + * assert.increasesBy(fn, obj, 'val', 10); + * + * @public + * @name increasesBy + * @namespace Assert + * @param {Function} fn - modifier function + * @param {object} obj - object or getter function + * @param {string} prop - property name _optional_ + * @param {number} delta - change amount (delta) + * @param {string} msg - message _optional_ + */ +assert.increasesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.increasesBy, true) + .to.increase(obj, prop).by(delta); +} + +/** + * ### .doesNotIncrease(function, object, property, [message]) + * + * Asserts that a function does not increase a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 8 }; + * assert.doesNotIncrease(fn, obj, 'val'); + * + * @name doesNotIncrease + * @param {Function} fn modifier function + * @param {object} obj object or getter function + * @param {string} prop property name _optional_ + * @returns {Assertion} + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.doesNotIncrease = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotIncrease, true) + .to.not.increase(obj, prop); +} + +/** + * ### .increasesButNotBy(function, object, property, delta, [message]) + * + * Asserts that a function does not increase a numeric object property or function's return value by an amount (delta). + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 15 }; + * assert.increasesButNotBy(fn, obj, 'val', 10); + * + * @name increasesButNotBy + * @param {Function} fn modifier function + * @param {object} obj object or getter function + * @param {string} prop property name _optional_ + * @param {number} delta change amount (delta) + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.increasesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.increasesButNotBy, true) + .to.increase(obj, prop).but.not.by(delta); +} + +/** + * ### .decreases(function, object, property, [message]) + * + * Asserts that a function decreases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.decreases(fn, obj, 'val'); + * + * @name decreases + * @param {Function} fn modifier function + * @param {object} obj object or getter function + * @param {string} prop property name _optional_ + * @returns {Assertion} + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.decreases = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.decreases, true) + .to.decrease(obj, prop); +} + +/** + * ### .decreasesBy(function, object, property, delta, [message]) + * + * Asserts that a function decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val -= 5 }; + * assert.decreasesBy(fn, obj, 'val', 5); + * + * @name decreasesBy + * @param {Function} fn modifier function + * @param {object} obj object or getter function + * @param {string} prop property name _optional_ + * @param {number} delta change amount (delta) + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.decreasesBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.decreasesBy, true) + .to.decrease(obj, prop).by(delta); +} + +/** + * ### .doesNotDecrease(function, object, property, [message]) + * + * Asserts that a function does not decreases a numeric object property. + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 15 }; + * assert.doesNotDecrease(fn, obj, 'val'); + * + * @name doesNotDecrease + * @param {Function} fn modifier function + * @param {object} obj object or getter function + * @param {string} prop property name _optional_ + * @returns {Assertion} + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.doesNotDecrease = function (fn, obj, prop, msg) { + if (arguments.length === 3 && typeof obj === 'function') { + msg = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotDecrease, true) + .to.not.decrease(obj, prop); +} + +/** + * ### .doesNotDecreaseBy(function, object, property, delta, [message]) + * + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.doesNotDecreaseBy(fn, obj, 'val', 1); + * + * @name doesNotDecreaseBy + * @param {Function} fn modifier function + * @param {object} obj object or getter function + * @param {string} prop property name _optional_ + * @param {number} delta change amount (delta) + * @returns {Assertion} + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.doesNotDecreaseBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + return new Assertion(fn, msg, assert.doesNotDecreaseBy, true) + .to.not.decrease(obj, prop).by(delta); +} + +/** + * ### .decreasesButNotBy(function, object, property, delta, [message]) + * + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * var obj = { val: 10 }; + * var fn = function() { obj.val = 5 }; + * assert.decreasesButNotBy(fn, obj, 'val', 1); + * + * @name decreasesButNotBy + * @param {Function} fn modifier function + * @param {object} obj object or getter function + * @param {string} prop property name _optional_ + * @param {number} delta change amount (delta) + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.decreasesButNotBy = function (fn, obj, prop, delta, msg) { + if (arguments.length === 4 && typeof obj === 'function') { + var tmpMsg = delta; + delta = prop; + msg = tmpMsg; + } else if (arguments.length === 3) { + delta = prop; + prop = null; + } + + new Assertion(fn, msg, assert.decreasesButNotBy, true) + .to.decrease(obj, prop).but.not.by(delta); +} + +/** + * ### .ifError(object) + * + * Asserts if value is not a false value, and throws if it is a true value. + * This is added to allow for chai to be a drop-in replacement for Node's + * assert class. + * + * var err = new Error('I am a custom error'); + * assert.ifError(err); // Rethrows err! + * + * @name ifError + * @param {object} val + * @namespace Assert + * @public + */ +assert.ifError = function (val) { + if (val) { + throw(val); + } +}; + +/** + * ### .isExtensible(object) + * + * Asserts that `object` is extensible (can have new properties added to it). + * + * assert.isExtensible({}); + * + * @name isExtensible + * @alias extensible + * @param {object} obj + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.isExtensible = function (obj, msg) { + new Assertion(obj, msg, assert.isExtensible, true).to.be.extensible; +}; + +/** + * ### .isNotExtensible(object) + * + * Asserts that `object` is _not_ extensible. + * + * var nonExtensibleObject = Object.preventExtensions({}); + * var sealedObject = Object.seal({}); + * var frozenObject = Object.freeze({}); + * + * assert.isNotExtensible(nonExtensibleObject); + * assert.isNotExtensible(sealedObject); + * assert.isNotExtensible(frozenObject); + * + * @name isNotExtensible + * @alias notExtensible + * @param {object} obj + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.isNotExtensible = function (obj, msg) { + new Assertion(obj, msg, assert.isNotExtensible, true).to.not.be.extensible; +}; + +/** + * ### .isSealed(object) + * + * Asserts that `object` is sealed (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * var sealedObject = Object.seal({}); + * var frozenObject = Object.seal({}); + * + * assert.isSealed(sealedObject); + * assert.isSealed(frozenObject); + * + * @name isSealed + * @alias sealed + * @param {object} obj + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.isSealed = function (obj, msg) { + new Assertion(obj, msg, assert.isSealed, true).to.be.sealed; +}; + +/** + * ### .isNotSealed(object) + * + * Asserts that `object` is _not_ sealed. + * + * assert.isNotSealed({}); + * + * @name isNotSealed + * @alias notSealed + * @param {object} obj + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.isNotSealed = function (obj, msg) { + new Assertion(obj, msg, assert.isNotSealed, true).to.not.be.sealed; +}; + +/** + * ### .isFrozen(object) + * + * Asserts that `object` is frozen (cannot have new properties added to it + * and its existing properties cannot be modified). + * + * var frozenObject = Object.freeze({}); + * assert.frozen(frozenObject); + * + * @name isFrozen + * @alias frozen + * @param {object} obj + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.isFrozen = function (obj, msg) { + new Assertion(obj, msg, assert.isFrozen, true).to.be.frozen; +}; + +/** + * ### .isNotFrozen(object) + * + * Asserts that `object` is _not_ frozen. + * + * assert.isNotFrozen({}); + * + * @name isNotFrozen + * @alias notFrozen + * @param {object} obj + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.isNotFrozen = function (obj, msg) { + new Assertion(obj, msg, assert.isNotFrozen, true).to.not.be.frozen; +}; + +/** + * ### .isEmpty(target) + * + * Asserts that the target does not contain any values. + * For arrays and strings, it checks the `length` property. + * For `Map` and `Set` instances, it checks the `size` property. + * For non-function objects, it gets the count of own + * enumerable string keys. + * + * assert.isEmpty([]); + * assert.isEmpty(''); + * assert.isEmpty(new Map); + * assert.isEmpty({}); + * + * @name isEmpty + * @alias empty + * @param {object | Array | string | Map | Set} val + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.isEmpty = function(val, msg) { + new Assertion(val, msg, assert.isEmpty, true).to.be.empty; +}; + +/** + * ### .isNotEmpty(target) + * + * Asserts that the target contains values. + * For arrays and strings, it checks the `length` property. + * For `Map` and `Set` instances, it checks the `size` property. + * For non-function objects, it gets the count of own + * enumerable string keys. + * + * assert.isNotEmpty([1, 2]); + * assert.isNotEmpty('34'); + * assert.isNotEmpty(new Set([5, 6])); + * assert.isNotEmpty({ key: 7 }); + * + * @name isNotEmpty + * @alias notEmpty + * @param {object | Array | string | Map | Set} val + * @param {string} msg _optional_ + * @namespace Assert + * @public + */ +assert.isNotEmpty = function(val, msg) { + new Assertion(val, msg, assert.isNotEmpty, true).to.not.be.empty; +}; + +/** + * Aliases. + * + * @param {unknown} name + * @param {unknown} as + * @returns {unknown} + */ +(function alias(name, as){ + assert[as] = assert[name]; + return alias; +}) +('isOk', 'ok') +('isNotOk', 'notOk') +('throws', 'throw') +('throws', 'Throw') +('isExtensible', 'extensible') +('isNotExtensible', 'notExtensible') +('isSealed', 'sealed') +('isNotSealed', 'notSealed') +('isFrozen', 'frozen') +('isNotFrozen', 'notFrozen') +('isEmpty', 'empty') +('isNotEmpty', 'notEmpty') +('isCallable', 'isFunction') +('isNotCallable', 'isNotFunction') diff --git a/node_modules/chai/lib/chai/interface/expect.js b/node_modules/chai/lib/chai/interface/expect.js new file mode 100644 index 000000000..fbaabf84d --- /dev/null +++ b/node_modules/chai/lib/chai/interface/expect.js @@ -0,0 +1,55 @@ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +import * as chai from '../../../index.js'; +import {Assertion} from '../assertion.js'; +import {AssertionError} from 'assertion-error'; + +/** + * @param {unknown} val + * @param {string} message + * @returns {Assertion} + */ +function expect(val, message) { + return new Assertion(val, message); +} + +export {expect}; + +/** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. + * + * expect.fail(); + * expect.fail("custom error message"); + * expect.fail(1, 2); + * expect.fail(1, 2, "custom error message"); + * expect.fail(1, 2, "custom error message", ">"); + * expect.fail(1, 2, undefined, ">"); + * + * @name fail + * @param {unknown} actual + * @param {unknown} expected + * @param {string} message + * @param {string} operator + * @namespace expect + * @public + */ +expect.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = undefined; + } + + message = message || 'expect.fail()'; + throw new AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, chai.expect.fail); +}; diff --git a/node_modules/chai/lib/chai/interface/should.js b/node_modules/chai/lib/chai/interface/should.js new file mode 100644 index 000000000..0efef3c64 --- /dev/null +++ b/node_modules/chai/lib/chai/interface/should.js @@ -0,0 +1,221 @@ +/*! + * chai + * Copyright(c) 2011-2014 Jake Luer + * MIT Licensed + */ + +import {Assertion} from '../assertion.js'; +import {AssertionError} from 'assertion-error'; + +/** + * @returns {void} + */ +function loadShould () { + // explicitly define this method as function as to have it's name to include as `ssfi` + /** + * @returns {Assertion} + */ + function shouldGetter() { + if (this instanceof String + || this instanceof Number + || this instanceof Boolean + || typeof Symbol === 'function' && this instanceof Symbol + || typeof BigInt === 'function' && this instanceof BigInt) { + return new Assertion(this.valueOf(), null, shouldGetter); + } + return new Assertion(this, null, shouldGetter); + } + /** + * @param {unknown} value + */ + function shouldSetter(value) { + // See https://github.com/chaijs/chai/issues/86: this makes + // `whatever.should = someValue` actually set `someValue`, which is + // especially useful for `global.should = require('chai').should()`. + // + // Note that we have to use [[DefineProperty]] instead of [[Put]] + // since otherwise we would trigger this very setter! + Object.defineProperty(this, 'should', { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } + // modify Object.prototype to have `should` + Object.defineProperty(Object.prototype, 'should', { + set: shouldSetter + , get: shouldGetter + , configurable: true + }); + + var should = {}; + + /** + * ### .fail([message]) + * ### .fail(actual, expected, [message], [operator]) + * + * Throw a failure. + * + * should.fail(); + * should.fail("custom error message"); + * should.fail(1, 2); + * should.fail(1, 2, "custom error message"); + * should.fail(1, 2, "custom error message", ">"); + * should.fail(1, 2, undefined, ">"); + * + * @name fail + * @param {unknown} actual + * @param {unknown} expected + * @param {string} message + * @param {string} operator + * @namespace BDD + * @public + */ + should.fail = function (actual, expected, message, operator) { + if (arguments.length < 2) { + message = actual; + actual = undefined; + } + + message = message || 'should.fail()'; + throw new AssertionError(message, { + actual: actual + , expected: expected + , operator: operator + }, should.fail); + }; + + /** + * ### .equal(actual, expected, [message]) + * + * Asserts non-strict equality (`==`) of `actual` and `expected`. + * + * should.equal(3, '3', '== coerces values to strings'); + * + * @name equal + * @param {unknown} actual + * @param {unknown} expected + * @param {string} message + * @namespace Should + * @public + */ + should.equal = function (actual, expected, message) { + new Assertion(actual, message).to.equal(expected); + }; + + /** + * ### .throw(function, [constructor/string/regexp], [string/regexp], [message]) + * + * Asserts that `function` will throw an error that is an instance of + * `constructor`, or alternately that it will throw an error with message + * matching `regexp`. + * + * should.throw(fn, 'function throws a reference error'); + * should.throw(fn, /function throws a reference error/); + * should.throw(fn, ReferenceError); + * should.throw(fn, ReferenceError, 'function throws a reference error'); + * should.throw(fn, ReferenceError, /function throws a reference error/); + * + * @name throw + * @alias Throw + * @param {Function} fn + * @param {Error} errt + * @param {RegExp} errs + * @param {string} msg + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Should + * @public + */ + should.Throw = function (fn, errt, errs, msg) { + new Assertion(fn, msg).to.Throw(errt, errs); + }; + + /** + * ### .exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var foo = 'hi'; + * should.exist(foo, 'foo exists'); + * + * @param {unknown} val + * @param {string} msg + * @name exist + * @namespace Should + * @public + */ + should.exist = function (val, msg) { + new Assertion(val, msg).to.exist; + } + + // negation + should.not = {} + + /** + * ### .not.equal(actual, expected, [message]) + * + * Asserts non-strict inequality (`!=`) of `actual` and `expected`. + * + * should.not.equal(3, 4, 'these numbers are not equal'); + * + * @name not.equal + * @param {unknown} actual + * @param {unknown} expected + * @param {string} msg + * @namespace Should + * @public + */ + should.not.equal = function (actual, expected, msg) { + new Assertion(actual, msg).to.not.equal(expected); + }; + + /** + * ### .throw(function, [constructor/regexp], [message]) + * + * Asserts that `function` will _not_ throw an error that is an instance of + * `constructor`, or alternately that it will not throw an error with message + * matching `regexp`. + * + * should.not.throw(fn, Error, 'function does not throw'); + * + * @name not.throw + * @alias not.Throw + * @param {Function} fn + * @param {Error} errt + * @param {RegExp} errs + * @param {string} msg + * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types + * @namespace Should + * @public + */ + should.not.Throw = function (fn, errt, errs, msg) { + new Assertion(fn, msg).to.not.Throw(errt, errs); + }; + + /** + * ### .not.exist + * + * Asserts that the target is neither `null` nor `undefined`. + * + * var bar = null; + * should.not.exist(bar, 'bar does not exist'); + * + * @namespace Should + * @name not.exist + * @param {unknown} val + * @param {string} msg + * @public + */ + should.not.exist = function (val, msg) { + new Assertion(val, msg).to.not.exist; + } + + should['throw'] = should['Throw']; + should.not['throw'] = should.not['Throw']; + + return should; +}; + +export const should = loadShould; +export const Should = loadShould; diff --git a/node_modules/chai/lib/chai/utils/addChainableMethod.js b/node_modules/chai/lib/chai/utils/addChainableMethod.js new file mode 100644 index 000000000..8de2b21ae --- /dev/null +++ b/node_modules/chai/lib/chai/utils/addChainableMethod.js @@ -0,0 +1,147 @@ +/*! + * Chai - addChainingMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +import {Assertion} from '../assertion.js'; +import {addLengthGuard} from './addLengthGuard.js'; +import {flag} from './flag.js'; +import {proxify} from './proxify.js'; +import {transferFlags} from './transferFlags.js'; + +/** + * Module variables + */ + +// Check whether `Object.setPrototypeOf` is supported +var canSetPrototype = typeof Object.setPrototypeOf === 'function'; + +// Without `Object.setPrototypeOf` support, this module will need to add properties to a function. +// However, some of functions' own props are not configurable and should be skipped. +var testFn = function() {}; +var excludeNames = Object.getOwnPropertyNames(testFn).filter(function(name) { + var propDesc = Object.getOwnPropertyDescriptor(testFn, name); + + // Note: PhantomJS 1.x includes `callee` as one of `testFn`'s own properties, + // but then returns `undefined` as the property descriptor for `callee`. As a + // workaround, we perform an otherwise unnecessary type-check for `propDesc`, + // and then filter it out if it's not an object as it should be. + if (typeof propDesc !== 'object') + return true; + + return !propDesc.configurable; +}); + +// Cache `Function` properties +var call = Function.prototype.call, + apply = Function.prototype.apply; + +/** + * ### .addChainableMethod(ctx, name, method, chainingBehavior) + * + * Adds a method to an object, such that the method can also be chained. + * + * utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.equal(str); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addChainableMethod('foo', fn, chainingBehavior); + * + * The result can then be used as both a method assertion, executing both `method` and + * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`. + * + * expect(fooStr).to.be.foo('bar'); + * expect(fooStr).to.be.foo.equal('foo'); + * + * @param {object} ctx object to which the method is added + * @param {string} name of method to add + * @param {Function} method function to be used for `name`, when called + * @param {Function} chainingBehavior function to be called every time the property is accessed + * @namespace Utils + * @name addChainableMethod + * @public + */ +export function addChainableMethod(ctx, name, method, chainingBehavior) { + if (typeof chainingBehavior !== 'function') { + chainingBehavior = function () { }; + } + + var chainableBehavior = { + method: method + , chainingBehavior: chainingBehavior + }; + + // save the methods so we can overwrite them later, if we need to. + if (!ctx.__methods) { + ctx.__methods = {}; + } + ctx.__methods[name] = chainableBehavior; + + Object.defineProperty(ctx, name, + { get: function chainableMethodGetter() { + chainableBehavior.chainingBehavior.call(this); + + var chainableMethodWrapper = function () { + // Setting the `ssfi` flag to `chainableMethodWrapper` causes this + // function to be the starting point for removing implementation + // frames from the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then this assertion is being + // invoked from inside of another assertion. In this case, the `ssfi` + // flag has already been set by the outer assertion. + // + // Note that overwriting a chainable method merely replaces the saved + // methods in `ctx.__methods` instead of completely replacing the + // overwritten assertion. Therefore, an overwriting assertion won't + // set the `ssfi` or `lockSsfi` flags. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', chainableMethodWrapper); + } + + var result = chainableBehavior.method.apply(this, arguments); + if (result !== undefined) { + return result; + } + + var newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + addLengthGuard(chainableMethodWrapper, name, true); + + // Use `Object.setPrototypeOf` if available + if (canSetPrototype) { + // Inherit all properties from the object by replacing the `Function` prototype + var prototype = Object.create(this); + // Restore the `call` and `apply` methods from `Function` + prototype.call = call; + prototype.apply = apply; + Object.setPrototypeOf(chainableMethodWrapper, prototype); + } + // Otherwise, redefine all properties (slow!) + else { + var asserterNames = Object.getOwnPropertyNames(ctx); + asserterNames.forEach(function (asserterName) { + if (excludeNames.indexOf(asserterName) !== -1) { + return; + } + + var pd = Object.getOwnPropertyDescriptor(ctx, asserterName); + Object.defineProperty(chainableMethodWrapper, asserterName, pd); + }); + } + + transferFlags(this, chainableMethodWrapper); + return proxify(chainableMethodWrapper); + } + , configurable: true + }); +} diff --git a/node_modules/chai/lib/chai/utils/addLengthGuard.js b/node_modules/chai/lib/chai/utils/addLengthGuard.js new file mode 100644 index 000000000..621d74004 --- /dev/null +++ b/node_modules/chai/lib/chai/utils/addLengthGuard.js @@ -0,0 +1,60 @@ +const fnLengthDesc = Object.getOwnPropertyDescriptor(function () {}, 'length'); + +/*! + * Chai - addLengthGuard utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .addLengthGuard(fn, assertionName, isChainable) + * + * Define `length` as a getter on the given uninvoked method assertion. The + * getter acts as a guard against chaining `length` directly off of an uninvoked + * method assertion, which is a problem because it references `function`'s + * built-in `length` property instead of Chai's `length` assertion. When the + * getter catches the user making this mistake, it throws an error with a + * helpful message. + * + * There are two ways in which this mistake can be made. The first way is by + * chaining the `length` assertion directly off of an uninvoked chainable + * method. In this case, Chai suggests that the user use `lengthOf` instead. The + * second way is by chaining the `length` assertion directly off of an uninvoked + * non-chainable method. Non-chainable methods must be invoked prior to + * chaining. In this case, Chai suggests that the user consult the docs for the + * given assertion. + * + * If the `length` property of functions is unconfigurable, then return `fn` + * without modification. + * + * Note that in ES6, the function's `length` property is configurable, so once + * support for legacy environments is dropped, Chai's `length` property can + * replace the built-in function's `length` property, and this length guard will + * no longer be necessary. In the mean time, maintaining consistency across all + * environments is the priority. + * + * @param {Function} fn + * @param {string} assertionName + * @param {boolean} isChainable + * @returns {unknown} + * @namespace Utils + * @name addLengthGuard + */ +export function addLengthGuard(fn, assertionName, isChainable) { + if (!fnLengthDesc.configurable) return fn; + + Object.defineProperty(fn, 'length', { + get: function () { + if (isChainable) { + throw Error('Invalid Chai property: ' + assertionName + '.length. Due' + + ' to a compatibility issue, "length" cannot directly follow "' + + assertionName + '". Use "' + assertionName + '.lengthOf" instead.'); + } + + throw Error('Invalid Chai property: ' + assertionName + '.length. See' + + ' docs for proper usage of "' + assertionName + '".'); + } + }); + + return fn; +} diff --git a/node_modules/chai/lib/chai/utils/addMethod.js b/node_modules/chai/lib/chai/utils/addMethod.js new file mode 100644 index 000000000..90b9546c9 --- /dev/null +++ b/node_modules/chai/lib/chai/utils/addMethod.js @@ -0,0 +1,67 @@ +/*! + * Chai - addMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +import {addLengthGuard} from './addLengthGuard.js'; +import {flag} from './flag.js'; +import {proxify} from './proxify.js'; +import {transferFlags} from './transferFlags.js'; +import {Assertion} from '../assertion.js'; + +/** + * ### .addMethod(ctx, name, method) + * + * Adds a method to the prototype of an object. + * + * utils.addMethod(chai.Assertion.prototype, 'foo', function (str) { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.equal(str); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addMethod('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(fooStr).to.be.foo('bar'); + * + * @param {object} ctx object to which the method is added + * @param {string} name of method to add + * @param {Function} method function to be used for name + * @namespace Utils + * @name addMethod + * @public + */ +export function addMethod(ctx, name, method) { + var methodWrapper = function () { + // Setting the `ssfi` flag to `methodWrapper` causes this function to be the + // starting point for removing implementation frames from the stack trace of + // a failed assertion. + // + // However, we only want to use this function as the starting point if the + // `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked from + // inside of another assertion. In the first case, the `ssfi` flag has + // already been set by the overwriting assertion. In the second case, the + // `ssfi` flag has already been set by the outer assertion. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', methodWrapper); + } + + var result = method.apply(this, arguments); + if (result !== undefined) + return result; + + var newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + addLengthGuard(methodWrapper, name, false); + ctx[name] = proxify(methodWrapper, name); +} diff --git a/node_modules/chai/lib/chai/utils/addProperty.js b/node_modules/chai/lib/chai/utils/addProperty.js new file mode 100644 index 000000000..fa59d23e1 --- /dev/null +++ b/node_modules/chai/lib/chai/utils/addProperty.js @@ -0,0 +1,71 @@ +/*! + * Chai - addProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +import {Assertion} from '../assertion.js'; +import {flag} from './flag.js'; +import {isProxyEnabled} from './isProxyEnabled.js'; +import {transferFlags} from './transferFlags.js'; + +/** + * ### .addProperty(ctx, name, getter) + * + * Adds a property to the prototype of an object. + * + * utils.addProperty(chai.Assertion.prototype, 'foo', function () { + * var obj = utils.flag(this, 'object'); + * new chai.Assertion(obj).to.be.instanceof(Foo); + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.addProperty('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.be.foo; + * + * @param {object} ctx object to which the property is added + * @param {string} name of property to add + * @param {Function} getter function to be used for name + * @namespace Utils + * @name addProperty + * @public + */ +export function addProperty(ctx, name, getter) { + getter = getter === undefined ? function () {} : getter; + + Object.defineProperty(ctx, name, + { get: function propertyGetter() { + // Setting the `ssfi` flag to `propertyGetter` causes this function to + // be the starting point for removing implementation frames from the + // stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set and proxy protection is disabled. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked + // from inside of another assertion. In the first case, the `ssfi` flag + // has already been set by the overwriting assertion. In the second + // case, the `ssfi` flag has already been set by the outer assertion. + // + // If proxy protection is enabled, then the `ssfi` flag has already been + // set by the proxy getter. + if (!isProxyEnabled() && !flag(this, 'lockSsfi')) { + flag(this, 'ssfi', propertyGetter); + } + + var result = getter.call(this); + if (result !== undefined) + return result; + + var newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + , configurable: true + }); +} diff --git a/node_modules/chai/lib/chai/utils/compareByInspect.js b/node_modules/chai/lib/chai/utils/compareByInspect.js new file mode 100644 index 000000000..5ab27a206 --- /dev/null +++ b/node_modules/chai/lib/chai/utils/compareByInspect.js @@ -0,0 +1,26 @@ +/*! + * Chai - compareByInspect utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + +import {inspect} from './inspect.js'; + +/** + * ### .compareByInspect(mixed, mixed) + * + * To be used as a compareFunction with Array.prototype.sort. Compares elements + * using inspect instead of default behavior of using toString so that Symbols + * and objects with irregular/missing toString can still be sorted without a + * TypeError. + * + * @param {unknown} a first element to compare + * @param {unknown} b second element to compare + * @returns {number} -1 if 'a' should come before 'b'; otherwise 1 + * @name compareByInspect + * @namespace Utils + * @public + */ +export function compareByInspect(a, b) { + return inspect(a) < inspect(b) ? -1 : 1; +} diff --git a/node_modules/chai/lib/chai/utils/expectTypes.js b/node_modules/chai/lib/chai/utils/expectTypes.js new file mode 100644 index 000000000..4f99532f7 --- /dev/null +++ b/node_modules/chai/lib/chai/utils/expectTypes.js @@ -0,0 +1,50 @@ +/*! + * Chai - expectTypes utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +import {AssertionError} from 'assertion-error'; +import {flag} from './flag.js'; +import {type} from './type-detect.js'; + +/** + * ### .expectTypes(obj, types) + * + * Ensures that the object being tested against is of a valid type. + * + * utils.expectTypes(this, ['array', 'object', 'string']); + * + * @param {unknown} obj constructed Assertion + * @param {Array} types A list of allowed types for this assertion + * @namespace Utils + * @name expectTypes + * @public + */ +export function expectTypes(obj, types) { + var flagMsg = flag(obj, 'message'); + var ssfi = flag(obj, 'ssfi'); + + flagMsg = flagMsg ? flagMsg + ': ' : ''; + + obj = flag(obj, 'object'); + types = types.map(function (t) { return t.toLowerCase(); }); + types.sort(); + + // Transforms ['lorem', 'ipsum'] into 'a lorem, or an ipsum' + var str = types.map(function (t, index) { + var art = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(t.charAt(0)) ? 'an' : 'a'; + var or = types.length > 1 && index === types.length - 1 ? 'or ' : ''; + return or + art + ' ' + t; + }).join(', '); + + var objType = type(obj).toLowerCase(); + + if (!types.some(function (expected) { return objType === expected; })) { + throw new AssertionError( + flagMsg + 'object tested must be ' + str + ', but ' + objType + ' given', + undefined, + ssfi + ); + } +} diff --git a/node_modules/chai/lib/chai/utils/flag.js b/node_modules/chai/lib/chai/utils/flag.js new file mode 100644 index 000000000..89434b71c --- /dev/null +++ b/node_modules/chai/lib/chai/utils/flag.js @@ -0,0 +1,33 @@ +/*! + * Chai - flag utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .flag(object, key, [value]) + * + * Get or set a flag value on an object. If a + * value is provided it will be set, else it will + * return the currently set value or `undefined` if + * the value is not set. + * + * utils.flag(this, 'foo', 'bar'); // setter + * utils.flag(this, 'foo'); // getter, returns `bar` + * + * @param {object} obj object constructed Assertion + * @param {string} key + * @param {unknown} value (optional) + * @namespace Utils + * @name flag + * @returns {unknown | undefined} + * @private + */ +export function flag(obj, key, value) { + var flags = obj.__flags || (obj.__flags = Object.create(null)); + if (arguments.length === 3) { + flags[key] = value; + } else { + return flags[key]; + } +} diff --git a/node_modules/chai/lib/chai/utils/getActual.js b/node_modules/chai/lib/chai/utils/getActual.js new file mode 100644 index 000000000..1b4b3aa21 --- /dev/null +++ b/node_modules/chai/lib/chai/utils/getActual.js @@ -0,0 +1,20 @@ +/*! + * Chai - getActual utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .getActual(object, [actual]) + * + * Returns the `actual` value for an Assertion. + * + * @param {object} obj object (constructed Assertion) + * @param {unknown} args chai.Assertion.prototype.assert arguments + * @returns {unknown} + * @namespace Utils + * @name getActual + */ +export function getActual(obj, args) { + return args.length > 4 ? args[4] : obj._obj; +} diff --git a/node_modules/chai/lib/chai/utils/getEnumerableProperties.js b/node_modules/chai/lib/chai/utils/getEnumerableProperties.js new file mode 100644 index 000000000..46960524c --- /dev/null +++ b/node_modules/chai/lib/chai/utils/getEnumerableProperties.js @@ -0,0 +1,25 @@ +/*! + * Chai - getEnumerableProperties utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .getEnumerableProperties(object) + * + * This allows the retrieval of enumerable property names of an object, + * inherited or not. + * + * @param {object} object + * @returns {Array} + * @namespace Utils + * @name getEnumerableProperties + * @public + */ +module.exports = function getEnumerableProperties(object) { + var result = []; + for (var name in object) { + result.push(name); + } + return result; +}; diff --git a/node_modules/chai/lib/chai/utils/getMessage.js b/node_modules/chai/lib/chai/utils/getMessage.js new file mode 100644 index 000000000..b184c990b --- /dev/null +++ b/node_modules/chai/lib/chai/utils/getMessage.js @@ -0,0 +1,46 @@ +/*! + * Chai - message composition utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +import {flag} from './flag.js'; +import {getActual} from './getActual.js'; +import {objDisplay} from './objDisplay.js'; + +/** + * ### .getMessage(object, message, negateMessage) + * + * Construct the error message based on flags + * and template tags. Template tags will return + * a stringified inspection of the object referenced. + * + * Message template tags: + * - `#{this}` current asserted object + * - `#{act}` actual value + * - `#{exp}` expected value + * + * @param {object} obj object (constructed Assertion) + * @param {unknown} args chai.Assertion.prototype.assert arguments + * @returns {unknown} + * @namespace Utils + * @name getMessage + * @public + */ +export function getMessage(obj, args) { + var negate = flag(obj, 'negate') + , val = flag(obj, 'object') + , expected = args[3] + , actual = getActual(obj, args) + , msg = negate ? args[2] : args[1] + , flagMsg = flag(obj, 'message'); + + if(typeof msg === "function") msg = msg(); + msg = msg || ''; + msg = msg + .replace(/#\{this\}/g, function () { return objDisplay(val); }) + .replace(/#\{act\}/g, function () { return objDisplay(actual); }) + .replace(/#\{exp\}/g, function () { return objDisplay(expected); }); + + return flagMsg ? flagMsg + ': ' + msg : msg; +} diff --git a/node_modules/chai/lib/chai/utils/getOperator.js b/node_modules/chai/lib/chai/utils/getOperator.js new file mode 100644 index 000000000..7a57d786f --- /dev/null +++ b/node_modules/chai/lib/chai/utils/getOperator.js @@ -0,0 +1,58 @@ +import {flag} from './flag.js'; +import {type} from './type-detect.js'; + +/** + * @param {unknown} obj + * @returns {boolean} + */ +function isObjectType(obj) { + var objectType = type(obj); + var objectTypes = ['Array', 'Object', 'Function']; + + return objectTypes.indexOf(objectType) !== -1; +} + +/** + * ### .getOperator(message) + * + * Extract the operator from error message. + * Operator defined is based on below link + * https://nodejs.org/api/assert.html#assert_assert. + * + * Returns the `operator` or `undefined` value for an Assertion. + * + * @param {object} obj object (constructed Assertion) + * @param {unknown} args chai.Assertion.prototype.assert arguments + * @returns {unknown} + * @namespace Utils + * @name getOperator + * @public + */ +export function getOperator(obj, args) { + var operator = flag(obj, 'operator'); + var negate = flag(obj, 'negate'); + var expected = args[3]; + var msg = negate ? args[2] : args[1]; + + if (operator) { + return operator; + } + + if (typeof msg === 'function') msg = msg(); + + msg = msg || ''; + if (!msg) { + return undefined; + } + + if (/\shave\s/.test(msg)) { + return undefined; + } + + var isObject = isObjectType(expected); + if (/\snot\s/.test(msg)) { + return isObject ? 'notDeepStrictEqual' : 'notStrictEqual'; + } + + return isObject ? 'deepStrictEqual' : 'strictEqual'; +} diff --git a/node_modules/chai/lib/chai/utils/getOwnEnumerableProperties.js b/node_modules/chai/lib/chai/utils/getOwnEnumerableProperties.js new file mode 100644 index 000000000..9e8e830bf --- /dev/null +++ b/node_modules/chai/lib/chai/utils/getOwnEnumerableProperties.js @@ -0,0 +1,24 @@ +/*! + * Chai - getOwnEnumerableProperties utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + +import {getOwnEnumerablePropertySymbols} from './getOwnEnumerablePropertySymbols.js'; + +/** + * ### .getOwnEnumerableProperties(object) + * + * This allows the retrieval of directly-owned enumerable property names and + * symbols of an object. This function is necessary because Object.keys only + * returns enumerable property names, not enumerable property symbols. + * + * @param {object} obj + * @returns {Array} + * @namespace Utils + * @name getOwnEnumerableProperties + * @public + */ +export function getOwnEnumerableProperties(obj) { + return Object.keys(obj).concat(getOwnEnumerablePropertySymbols(obj)); +} diff --git a/node_modules/chai/lib/chai/utils/getOwnEnumerablePropertySymbols.js b/node_modules/chai/lib/chai/utils/getOwnEnumerablePropertySymbols.js new file mode 100644 index 000000000..d8d6d0964 --- /dev/null +++ b/node_modules/chai/lib/chai/utils/getOwnEnumerablePropertySymbols.js @@ -0,0 +1,26 @@ +/*! + * Chai - getOwnEnumerablePropertySymbols utility + * Copyright(c) 2011-2016 Jake Luer + * MIT Licensed + */ + +/** + * ### .getOwnEnumerablePropertySymbols(object) + * + * This allows the retrieval of directly-owned enumerable property symbols of an + * object. This function is necessary because Object.getOwnPropertySymbols + * returns both enumerable and non-enumerable property symbols. + * + * @param {object} obj + * @returns {Array} + * @namespace Utils + * @name getOwnEnumerablePropertySymbols + * @public + */ +export function getOwnEnumerablePropertySymbols(obj) { + if (typeof Object.getOwnPropertySymbols !== 'function') return []; + + return Object.getOwnPropertySymbols(obj).filter(function (sym) { + return Object.getOwnPropertyDescriptor(obj, sym).enumerable; + }); +} diff --git a/node_modules/chai/lib/chai/utils/getProperties.js b/node_modules/chai/lib/chai/utils/getProperties.js new file mode 100644 index 000000000..b43c71049 --- /dev/null +++ b/node_modules/chai/lib/chai/utils/getProperties.js @@ -0,0 +1,38 @@ +/*! + * Chai - getProperties utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .getProperties(object) + * + * This allows the retrieval of property names of an object, enumerable or not, + * inherited or not. + * + * @param {object} object + * @returns {Array} + * @namespace Utils + * @name getProperties + * @public + */ +export function getProperties(object) { + var result = Object.getOwnPropertyNames(object); + + /** + * @param {unknown} property + */ + function addProperty(property) { + if (result.indexOf(property) === -1) { + result.push(property); + } + } + + var proto = Object.getPrototypeOf(object); + while (proto !== null) { + Object.getOwnPropertyNames(proto).forEach(addProperty); + proto = Object.getPrototypeOf(proto); + } + + return result; +} diff --git a/node_modules/chai/lib/chai/utils/index.js b/node_modules/chai/lib/chai/utils/index.js new file mode 100644 index 000000000..fd4e63581 --- /dev/null +++ b/node_modules/chai/lib/chai/utils/index.js @@ -0,0 +1,112 @@ +/*! + * chai + * Copyright(c) 2011 Jake Luer + * MIT Licensed + */ + +// Dependencies that are used for multiple exports are required here only once +import * as checkError from 'check-error'; + +// test utility +export {test} from './test.js'; + +// type utility +import {type} from './type-detect.js'; +export {type}; + +// expectTypes utility +export {expectTypes} from './expectTypes.js'; + +// message utility +export {getMessage} from './getMessage.js'; + +// actual utility +export {getActual} from './getActual.js'; + +// Inspect util +export {inspect} from './inspect.js'; + +// Object Display util +export {objDisplay} from './objDisplay.js'; + +// Flag utility +export {flag} from './flag.js'; + +// Flag transferring utility +export {transferFlags} from './transferFlags.js'; + +// Deep equal utility +export {default as eql} from 'deep-eql'; + +// Deep path info +export {getPathInfo, hasProperty} from 'pathval'; + +/** + * Function name + * + * @param {Function} fn + * @returns {string} + */ +export function getName(fn) { + return fn.name +} + +// add Property +export {addProperty} from './addProperty.js'; + +// add Method +export {addMethod} from './addMethod.js'; + +// overwrite Property +export {overwriteProperty} from './overwriteProperty.js'; + +// overwrite Method +export {overwriteMethod} from './overwriteMethod.js'; + +// Add a chainable method +export {addChainableMethod} from './addChainableMethod.js'; + +// Overwrite chainable method +export {overwriteChainableMethod} from './overwriteChainableMethod.js'; + +// Compare by inspect method +export {compareByInspect} from './compareByInspect.js'; + +// Get own enumerable property symbols method +export {getOwnEnumerablePropertySymbols} from './getOwnEnumerablePropertySymbols.js'; + +// Get own enumerable properties method +export {getOwnEnumerableProperties} from './getOwnEnumerableProperties.js'; + +// Checks error against a given set of criteria +export {checkError}; + +// Proxify util +export {proxify} from './proxify.js'; + +// addLengthGuard util +export {addLengthGuard} from './addLengthGuard.js'; + +// isProxyEnabled helper +export {isProxyEnabled} from './isProxyEnabled.js'; + +// isNaN method +export {isNaN} from './isNaN.js'; + +// getOperator method +export {getOperator} from './getOperator.js'; + +/** + * Determines if an object is a `RegExp` + * This is used since `instanceof` will not work in virtual contexts + * + * @param {*} obj Object to test + * @returns {boolean} + */ +export function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +} + +export function isNumeric(obj) { + return ['Number', 'BigInt'].includes(type(obj)) +} diff --git a/node_modules/chai/lib/chai/utils/inspect.js b/node_modules/chai/lib/chai/utils/inspect.js new file mode 100644 index 000000000..dcd9ad797 --- /dev/null +++ b/node_modules/chai/lib/chai/utils/inspect.js @@ -0,0 +1,31 @@ +// This is (almost) directly from Node.js utils +// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js + +import {inspect as _inspect} from 'loupe'; +import {config} from '../config.js'; + +/** + * ### .inspect(obj, [showHidden], [depth], [colors]) + * + * Echoes the value of a value. Tries to print the value out + * in the best way possible given the different types. + * + * @param {object} obj The object to print out. + * @param {boolean} showHidden Flag that shows hidden (not enumerable) + * properties of objects. Default is false. + * @param {number} depth Depth in which to descend in object. Default is 2. + * @param {boolean} colors Flag to turn on ANSI escape codes to color the + * output. Default is false (no coloring). + * @returns {string} + * @namespace Utils + * @name inspect + */ +export function inspect(obj, showHidden, depth, colors) { + var options = { + colors: colors, + depth: (typeof depth === 'undefined' ? 2 : depth), + showHidden: showHidden, + truncate: config.truncateThreshold ? config.truncateThreshold : Infinity, + }; + return _inspect(obj, options); +} diff --git a/node_modules/chai/lib/chai/utils/isNaN.js b/node_modules/chai/lib/chai/utils/isNaN.js new file mode 100644 index 000000000..acc10d6f4 --- /dev/null +++ b/node_modules/chai/lib/chai/utils/isNaN.js @@ -0,0 +1,26 @@ +/*! + * Chai - isNaN utility + * Copyright(c) 2012-2015 Sakthipriyan Vairamani + * MIT Licensed + */ + +/** + * ### .isNaN(value) + * + * Checks if the given value is NaN or not. + * + * utils.isNaN(NaN); // true + * + * @param {unknown} value The value which has to be checked if it is NaN + * @returns {boolean} + * @name isNaN + * @private + */ +function _isNaN(value) { + // Refer http://www.ecma-international.org/ecma-262/6.0/#sec-isnan-number + // section's NOTE. + return value !== value; +} + +// If ECMAScript 6's Number.isNaN is present, prefer that. +export const isNaN = Number.isNaN || _isNaN; diff --git a/node_modules/chai/lib/chai/utils/isProxyEnabled.js b/node_modules/chai/lib/chai/utils/isProxyEnabled.js new file mode 100644 index 000000000..5b6b62aac --- /dev/null +++ b/node_modules/chai/lib/chai/utils/isProxyEnabled.js @@ -0,0 +1,24 @@ +import {config} from '../config.js'; + +/*! + * Chai - isProxyEnabled helper + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .isProxyEnabled() + * + * Helper function to check if Chai's proxy protection feature is enabled. If + * proxies are unsupported or disabled via the user's Chai config, then return + * false. Otherwise, return true. + * + * @namespace Utils + * @name isProxyEnabled + * @returns {boolean} + */ +export function isProxyEnabled() { + return config.useProxy && + typeof Proxy !== 'undefined' && + typeof Reflect !== 'undefined'; +} diff --git a/node_modules/chai/lib/chai/utils/objDisplay.js b/node_modules/chai/lib/chai/utils/objDisplay.js new file mode 100644 index 000000000..76f014a82 --- /dev/null +++ b/node_modules/chai/lib/chai/utils/objDisplay.js @@ -0,0 +1,46 @@ +/*! + * Chai - flag utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +import {inspect} from './inspect.js'; +import {config} from '../config.js'; + +/** + * ### .objDisplay(object) + * + * Determines if an object or an array matches + * criteria to be inspected in-line for error + * messages or should be truncated. + * + * @param {unknown} obj javascript object to inspect + * @returns {string} stringified object + * @name objDisplay + * @namespace Utils + * @public + */ +export function objDisplay(obj) { + var str = inspect(obj) + , type = Object.prototype.toString.call(obj); + + if (config.truncateThreshold && str.length >= config.truncateThreshold) { + if (type === '[object Function]') { + return !obj.name || obj.name === '' + ? '[Function]' + : '[Function: ' + obj.name + ']'; + } else if (type === '[object Array]') { + return '[ Array(' + obj.length + ') ]'; + } else if (type === '[object Object]') { + var keys = Object.keys(obj) + , kstr = keys.length > 2 + ? keys.splice(0, 2).join(', ') + ', ...' + : keys.join(', '); + return '{ Object (' + kstr + ') }'; + } else { + return str; + } + } else { + return str; + } +} diff --git a/node_modules/chai/lib/chai/utils/overwriteChainableMethod.js b/node_modules/chai/lib/chai/utils/overwriteChainableMethod.js new file mode 100644 index 000000000..68fc89f65 --- /dev/null +++ b/node_modules/chai/lib/chai/utils/overwriteChainableMethod.js @@ -0,0 +1,68 @@ +/*! + * Chai - overwriteChainableMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +import {Assertion} from '../assertion.js'; +import {transferFlags} from './transferFlags.js'; + +/** + * ### .overwriteChainableMethod(ctx, name, method, chainingBehavior) + * + * Overwrites an already existing chainable method + * and provides access to the previous function or + * property. Must return functions to be used for + * name. + * + * utils.overwriteChainableMethod(chai.Assertion.prototype, 'lengthOf', + * function (_super) { + * } + * , function (_super) { + * } + * ); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteChainableMethod('foo', fn, fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.have.lengthOf(3); + * expect(myFoo).to.have.lengthOf.above(3); + * + * @param {object} ctx object whose method / property is to be overwritten + * @param {string} name of method / property to overwrite + * @param {Function} method function that returns a function to be used for name + * @param {Function} chainingBehavior function that returns a function to be used for property + * @namespace Utils + * @name overwriteChainableMethod + * @public + */ +export function overwriteChainableMethod(ctx, name, method, chainingBehavior) { + var chainableBehavior = ctx.__methods[name]; + + var _chainingBehavior = chainableBehavior.chainingBehavior; + chainableBehavior.chainingBehavior = function overwritingChainableMethodGetter() { + var result = chainingBehavior(_chainingBehavior).call(this); + if (result !== undefined) { + return result; + } + + var newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; + + var _method = chainableBehavior.method; + chainableBehavior.method = function overwritingChainableMethodWrapper() { + var result = method(_method).apply(this, arguments); + if (result !== undefined) { + return result; + } + + var newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + }; +} diff --git a/node_modules/chai/lib/chai/utils/overwriteMethod.js b/node_modules/chai/lib/chai/utils/overwriteMethod.js new file mode 100644 index 000000000..d101f3b0d --- /dev/null +++ b/node_modules/chai/lib/chai/utils/overwriteMethod.js @@ -0,0 +1,91 @@ +/*! + * Chai - overwriteMethod utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +import {Assertion} from '../assertion.js'; +import {addLengthGuard} from './addLengthGuard.js'; +import {flag} from './flag.js'; +import {proxify} from './proxify.js'; +import {transferFlags} from './transferFlags.js'; + +/** + * ### .overwriteMethod(ctx, name, fn) + * + * Overwrites an already existing method and provides + * access to previous function. Must return function + * to be used for name. + * + * utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) { + * return function (str) { + * var obj = utils.flag(this, 'object'); + * if (obj instanceof Foo) { + * new chai.Assertion(obj.value).to.equal(str); + * } else { + * _super.apply(this, arguments); + * } + * } + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteMethod('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.equal('bar'); + * + * @param {object} ctx object whose method is to be overwritten + * @param {string} name of method to overwrite + * @param {Function} method function that returns a function to be used for name + * @namespace Utils + * @name overwriteMethod + * @public + */ +export function overwriteMethod(ctx, name, method) { + var _method = ctx[name] + , _super = function () { + throw new Error(name + ' is not a function'); + }; + + if (_method && 'function' === typeof _method) + _super = _method; + + var overwritingMethodWrapper = function () { + // Setting the `ssfi` flag to `overwritingMethodWrapper` causes this + // function to be the starting point for removing implementation frames from + // the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if the + // `lockSsfi` flag isn't set. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked from + // inside of another assertion. In the first case, the `ssfi` flag has + // already been set by the overwriting assertion. In the second case, the + // `ssfi` flag has already been set by the outer assertion. + if (!flag(this, 'lockSsfi')) { + flag(this, 'ssfi', overwritingMethodWrapper); + } + + // Setting the `lockSsfi` flag to `true` prevents the overwritten assertion + // from changing the `ssfi` flag. By this point, the `ssfi` flag is already + // set to the correct starting point for this assertion. + var origLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + var result = method(_super).apply(this, arguments); + flag(this, 'lockSsfi', origLockSsfi); + + if (result !== undefined) { + return result; + } + + var newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + + addLengthGuard(overwritingMethodWrapper, name, false); + ctx[name] = proxify(overwritingMethodWrapper, name); +} diff --git a/node_modules/chai/lib/chai/utils/overwriteProperty.js b/node_modules/chai/lib/chai/utils/overwriteProperty.js new file mode 100644 index 000000000..97f3486af --- /dev/null +++ b/node_modules/chai/lib/chai/utils/overwriteProperty.js @@ -0,0 +1,90 @@ +/*! + * Chai - overwriteProperty utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +import {Assertion} from '../assertion.js'; +import {flag} from './flag.js'; +import {isProxyEnabled} from './isProxyEnabled.js'; +import {transferFlags} from './transferFlags.js'; + +/** + * ### .overwriteProperty(ctx, name, fn) + * + * Overwrites an already existing property getter and provides + * access to previous value. Must return function to use as getter. + * + * utils.overwriteProperty(chai.Assertion.prototype, 'ok', function (_super) { + * return function () { + * var obj = utils.flag(this, 'object'); + * if (obj instanceof Foo) { + * new chai.Assertion(obj.name).to.equal('bar'); + * } else { + * _super.call(this); + * } + * } + * }); + * + * Can also be accessed directly from `chai.Assertion`. + * + * chai.Assertion.overwriteProperty('foo', fn); + * + * Then can be used as any other assertion. + * + * expect(myFoo).to.be.ok; + * + * @param {object} ctx object whose property is to be overwritten + * @param {string} name of property to overwrite + * @param {Function} getter function that returns a getter function to be used for name + * @namespace Utils + * @name overwriteProperty + * @public + */ +export function overwriteProperty(ctx, name, getter) { + var _get = Object.getOwnPropertyDescriptor(ctx, name) + , _super = function () {}; + + if (_get && 'function' === typeof _get.get) + _super = _get.get + + Object.defineProperty(ctx, name, + { get: function overwritingPropertyGetter() { + // Setting the `ssfi` flag to `overwritingPropertyGetter` causes this + // function to be the starting point for removing implementation frames + // from the stack trace of a failed assertion. + // + // However, we only want to use this function as the starting point if + // the `lockSsfi` flag isn't set and proxy protection is disabled. + // + // If the `lockSsfi` flag is set, then either this assertion has been + // overwritten by another assertion, or this assertion is being invoked + // from inside of another assertion. In the first case, the `ssfi` flag + // has already been set by the overwriting assertion. In the second + // case, the `ssfi` flag has already been set by the outer assertion. + // + // If proxy protection is enabled, then the `ssfi` flag has already been + // set by the proxy getter. + if (!isProxyEnabled() && !flag(this, 'lockSsfi')) { + flag(this, 'ssfi', overwritingPropertyGetter); + } + + // Setting the `lockSsfi` flag to `true` prevents the overwritten + // assertion from changing the `ssfi` flag. By this point, the `ssfi` + // flag is already set to the correct starting point for this assertion. + var origLockSsfi = flag(this, 'lockSsfi'); + flag(this, 'lockSsfi', true); + var result = getter(_super).call(this); + flag(this, 'lockSsfi', origLockSsfi); + + if (result !== undefined) { + return result; + } + + var newAssertion = new Assertion(); + transferFlags(this, newAssertion); + return newAssertion; + } + , configurable: true + }); +} diff --git a/node_modules/chai/lib/chai/utils/proxify.js b/node_modules/chai/lib/chai/utils/proxify.js new file mode 100644 index 000000000..3789892f5 --- /dev/null +++ b/node_modules/chai/lib/chai/utils/proxify.js @@ -0,0 +1,147 @@ +import {config} from '../config.js'; +import {flag} from './flag.js'; +import {getProperties} from './getProperties.js'; +import {isProxyEnabled} from './isProxyEnabled.js'; + +/*! + * Chai - proxify utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +const builtins = ['__flags', '__methods', '_obj', 'assert']; + +/** + * ### .proxify(object) + * + * Return a proxy of given object that throws an error when a non-existent + * property is read. By default, the root cause is assumed to be a misspelled + * property, and thus an attempt is made to offer a reasonable suggestion from + * the list of existing properties. However, if a nonChainableMethodName is + * provided, then the root cause is instead a failure to invoke a non-chainable + * method prior to reading the non-existent property. + * + * If proxies are unsupported or disabled via the user's Chai config, then + * return object without modification. + * + * @param {object} obj + * @param {string} nonChainableMethodName + * @returns {unknown} + * @namespace Utils + * @name proxify + */ +export function proxify(obj ,nonChainableMethodName) { + if (!isProxyEnabled()) return obj; + + return new Proxy(obj, { + get: function proxyGetter(target, property) { + // This check is here because we should not throw errors on Symbol properties + // such as `Symbol.toStringTag`. + // The values for which an error should be thrown can be configured using + // the `config.proxyExcludedKeys` setting. + if (typeof property === 'string' && + config.proxyExcludedKeys.indexOf(property) === -1 && + !Reflect.has(target, property)) { + // Special message for invalid property access of non-chainable methods. + if (nonChainableMethodName) { + throw Error('Invalid Chai property: ' + nonChainableMethodName + '.' + + property + '. See docs for proper usage of "' + + nonChainableMethodName + '".'); + } + + // If the property is reasonably close to an existing Chai property, + // suggest that property to the user. Only suggest properties with a + // distance less than 4. + var suggestion = null; + var suggestionDistance = 4; + getProperties(target).forEach(function(prop) { + if ( + !Object.prototype.hasOwnProperty(prop) && + builtins.indexOf(prop) === -1 + ) { + var dist = stringDistanceCapped( + property, + prop, + suggestionDistance + ); + if (dist < suggestionDistance) { + suggestion = prop; + suggestionDistance = dist; + } + } + }); + + if (suggestion !== null) { + throw Error('Invalid Chai property: ' + property + + '. Did you mean "' + suggestion + '"?'); + } else { + throw Error('Invalid Chai property: ' + property); + } + } + + // Use this proxy getter as the starting point for removing implementation + // frames from the stack trace of a failed assertion. For property + // assertions, this prevents the proxy getter from showing up in the stack + // trace since it's invoked before the property getter. For method and + // chainable method assertions, this flag will end up getting changed to + // the method wrapper, which is good since this frame will no longer be in + // the stack once the method is invoked. Note that Chai builtin assertion + // properties such as `__flags` are skipped since this is only meant to + // capture the starting point of an assertion. This step is also skipped + // if the `lockSsfi` flag is set, thus indicating that this assertion is + // being called from within another assertion. In that case, the `ssfi` + // flag is already set to the outer assertion's starting point. + if (builtins.indexOf(property) === -1 && !flag(target, 'lockSsfi')) { + flag(target, 'ssfi', proxyGetter); + } + + return Reflect.get(target, property); + } + }); +} + +/** + * # stringDistanceCapped(strA, strB, cap) + * Return the Levenshtein distance between two strings, but no more than cap. + * + * @param {string} strA + * @param {string} strB + * @param {number} cap + * @returns {number} min(string distance between strA and strB, cap) + * @private + */ +function stringDistanceCapped(strA, strB, cap) { + if (Math.abs(strA.length - strB.length) >= cap) { + return cap; + } + + var memo = []; + // `memo` is a two-dimensional array containing distances. + // memo[i][j] is the distance between strA.slice(0, i) and + // strB.slice(0, j). + for (var i = 0; i <= strA.length; i++) { + memo[i] = Array(strB.length + 1).fill(0); + memo[i][0] = i; + } + for (var j = 0; j < strB.length; j++) { + memo[0][j] = j; + } + + for (var i = 1; i <= strA.length; i++) { + var ch = strA.charCodeAt(i - 1); + for (var j = 1; j <= strB.length; j++) { + if (Math.abs(i - j) >= cap) { + memo[i][j] = cap; + continue; + } + memo[i][j] = Math.min( + memo[i - 1][j] + 1, + memo[i][j - 1] + 1, + memo[i - 1][j - 1] + + (ch === strB.charCodeAt(j - 1) ? 0 : 1) + ); + } + } + + return memo[strA.length][strB.length]; +} diff --git a/node_modules/chai/lib/chai/utils/test.js b/node_modules/chai/lib/chai/utils/test.js new file mode 100644 index 000000000..2fc98ceca --- /dev/null +++ b/node_modules/chai/lib/chai/utils/test.js @@ -0,0 +1,24 @@ +/*! + * Chai - test utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +import {flag} from './flag.js'; + +/** + * ### .test(object, expression) + * + * Test an object for expression. + * + * @param {object} obj (constructed Assertion) + * @param {unknown} args + * @returns {unknown} + * @namespace Utils + * @name test + */ +export function test(obj, args) { + var negate = flag(obj, 'negate') + , expr = args[0]; + return negate ? !expr : expr; +} diff --git a/node_modules/chai/lib/chai/utils/transferFlags.js b/node_modules/chai/lib/chai/utils/transferFlags.js new file mode 100644 index 000000000..2669941ce --- /dev/null +++ b/node_modules/chai/lib/chai/utils/transferFlags.js @@ -0,0 +1,43 @@ +/*! + * Chai - transferFlags utility + * Copyright(c) 2012-2014 Jake Luer + * MIT Licensed + */ + +/** + * ### .transferFlags(assertion, object, includeAll = true) + * + * Transfer all the flags for `assertion` to `object`. If + * `includeAll` is set to `false`, then the base Chai + * assertion flags (namely `object`, `ssfi`, `lockSsfi`, + * and `message`) will not be transferred. + * + * var newAssertion = new Assertion(); + * utils.transferFlags(assertion, newAssertion); + * + * var anotherAssertion = new Assertion(myObj); + * utils.transferFlags(assertion, anotherAssertion, false); + * + * @param {import('../assertion.js').Assertion} assertion the assertion to transfer the flags from + * @param {object} object the object to transfer the flags to; usually a new assertion + * @param {boolean} includeAll + * @namespace Utils + * @name transferFlags + * @private + */ +export function transferFlags(assertion, object, includeAll) { + var flags = assertion.__flags || (assertion.__flags = Object.create(null)); + + if (!object.__flags) { + object.__flags = Object.create(null); + } + + includeAll = arguments.length === 3 ? includeAll : true; + + for (var flag in flags) { + if (includeAll || + (flag !== 'object' && flag !== 'ssfi' && flag !== 'lockSsfi' && flag != 'message')) { + object.__flags[flag] = flags[flag]; + } + } +} diff --git a/node_modules/chai/lib/chai/utils/type-detect.js b/node_modules/chai/lib/chai/utils/type-detect.js new file mode 100644 index 000000000..995332b2d --- /dev/null +++ b/node_modules/chai/lib/chai/utils/type-detect.js @@ -0,0 +1,20 @@ +/** + * @param {unknown} obj + * @returns {string} + */ +export function type(obj) { + if (typeof obj === 'undefined') { + return 'undefined'; + } + + if (obj === null) { + return 'null'; + } + + const stringTag = obj[Symbol.toStringTag]; + if (typeof stringTag === 'string') { + return stringTag; + } + const type = Object.prototype.toString.call(obj).slice(8, -1); + return type; +} diff --git a/node_modules/chai/package.json b/node_modules/chai/package.json new file mode 100644 index 000000000..48a673c97 --- /dev/null +++ b/node_modules/chai/package.json @@ -0,0 +1,61 @@ +{ + "author": "Jake Luer ", + "name": "chai", + "type": "module", + "description": "BDD/TDD assertion library for node.js and the browser. Test framework agnostic.", + "keywords": [ + "test", + "assertion", + "assert", + "testing", + "chai" + ], + "homepage": "http://chaijs.com", + "license": "MIT", + "contributors": [ + "Jake Luer ", + "Domenic Denicola (http://domenicdenicola.com)", + "Veselin Todorov ", + "John Firebaugh " + ], + "version": "5.1.2", + "repository": { + "type": "git", + "url": "https://github.com/chaijs/chai" + }, + "bugs": { + "url": "https://github.com/chaijs/chai/issues" + }, + "main": "./chai.js", + "scripts": { + "prebuild": "npm run clean", + "build": "npm run build:esm", + "build:esm": "esbuild --bundle --format=esm --keep-names --outfile=chai.js index.js", + "pretest": "npm run lint && npm run build", + "test": "npm run test-node && npm run test-chrome", + "test-node": "mocha --require ./test/bootstrap/index.js --reporter dot test/*.js", + "test-chrome": "web-test-runner --playwright", + "lint": "eslint lib/", + "clean": "rm -f chai.js coverage" + }, + "engines": { + "node": ">=12" + }, + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "devDependencies": { + "@rollup/plugin-commonjs": "^25.0.7", + "@web/dev-server-rollup": "^0.6.1", + "@web/test-runner": "^0.18.0", + "@web/test-runner-playwright": "^0.11.0", + "esbuild": "^0.19.10", + "eslint": "^8.56.0", + "eslint-plugin-jsdoc": "^48.0.4", + "mocha": "^10.2.0" + } +} diff --git a/node_modules/chai/register-assert.cjs b/node_modules/chai/register-assert.cjs new file mode 100644 index 000000000..85949392c --- /dev/null +++ b/node_modules/chai/register-assert.cjs @@ -0,0 +1,3 @@ +const {assert} = require('./chai.cjs'); + +globalThis.assert = assert; diff --git a/node_modules/chai/register-assert.js b/node_modules/chai/register-assert.js new file mode 100644 index 000000000..f593717e0 --- /dev/null +++ b/node_modules/chai/register-assert.js @@ -0,0 +1,3 @@ +import {assert} from './index.js'; + +globalThis.assert = assert; diff --git a/node_modules/chai/register-expect.cjs b/node_modules/chai/register-expect.cjs new file mode 100644 index 000000000..03a92e995 --- /dev/null +++ b/node_modules/chai/register-expect.cjs @@ -0,0 +1,3 @@ +const {expect} = require('./chai.cjs'); + +globalThis.expect = expect; diff --git a/node_modules/chai/register-expect.js b/node_modules/chai/register-expect.js new file mode 100644 index 000000000..2807b89be --- /dev/null +++ b/node_modules/chai/register-expect.js @@ -0,0 +1,3 @@ +import {expect} from './index.js'; + +globalThis.expect = expect; diff --git a/node_modules/chai/register-should.cjs b/node_modules/chai/register-should.cjs new file mode 100644 index 000000000..f935dccdb --- /dev/null +++ b/node_modules/chai/register-should.cjs @@ -0,0 +1,3 @@ +const {should} = require('./chai.cjs'); + +globalThis.should = should(); diff --git a/node_modules/chai/register-should.js b/node_modules/chai/register-should.js new file mode 100644 index 000000000..1339ee4c4 --- /dev/null +++ b/node_modules/chai/register-should.js @@ -0,0 +1,3 @@ +import {should} from './index.js'; + +globalThis.should = should(); diff --git a/node_modules/chai/web-test-runner.config.js b/node_modules/chai/web-test-runner.config.js new file mode 100644 index 000000000..b9b6cb255 --- /dev/null +++ b/node_modules/chai/web-test-runner.config.js @@ -0,0 +1,20 @@ +import { fromRollup } from "@web/dev-server-rollup"; +import rollupCommonjs from "@rollup/plugin-commonjs"; + +const commonjs = fromRollup(rollupCommonjs); + +export default { + nodeResolve: true, + files: [ + "test/*.js", + "!test/virtual-machines.js" + ], + plugins: [ + commonjs({ + include: [ + // the commonjs plugin is slow, list the required packages explicitly: + "**/node_modules/type-detect/**/*", + ], + }), + ], +}; diff --git a/node_modules/check-error/LICENSE b/node_modules/check-error/LICENSE new file mode 100644 index 000000000..7ea799f0e --- /dev/null +++ b/node_modules/check-error/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013 Jake Luer (http://alogicalparadox.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. diff --git a/node_modules/check-error/README.md b/node_modules/check-error/README.md new file mode 100644 index 000000000..95c320002 --- /dev/null +++ b/node_modules/check-error/README.md @@ -0,0 +1,144 @@ +

+ + ChaiJS + +
+ check-error +

+ +

+ Error comparison and information related utility for node and the browser. +

+ +## What is Check-Error? + +Check-Error is a module which you can use to retrieve an Error's information such as its `message` or `constructor` name and also to check whether two Errors are compatible based on their messages, constructors or even instances. + +## Installation + +### Node.js + +`check-error` is available on [npm](http://npmjs.org). To install it, type: + + $ npm install check-error + +### Browsers + +You can also use it within the browser; install via npm and use the `check-error.js` file found within the download. For example: + +```html + +``` + +## Usage + +The primary export of `check-error` is an object which has the following methods: + +* `compatibleInstance(err, errorLike)` - Checks if an error is compatible with another `errorLike` object. If `errorLike` is an error instance we do a strict comparison, otherwise we return `false` by default, because instances of objects can only be compatible if they're both error instances. +* `compatibleConstructor(err, errorLike)` - Checks if an error's constructor is compatible with another `errorLike` object. If `err` has the same constructor as `errorLike` or if `err` is an instance of `errorLike`. +* `compatibleMessage(err, errMatcher)` - Checks if an error message is compatible with an `errMatcher` RegExp or String (we check if the message contains the String). +* `getConstructorName(errorLike)` - Retrieves the name of a constructor, an error's constructor or `errorLike` itself if it's not an error instance or constructor. +* `getMessage(err)` - Retrieves the message of an error or `err` itself if it's a String. If `err` or `err.message` is undefined we return an empty String. + +```js +var checkError = require('check-error'); +``` + +#### .compatibleInstance(err, errorLike) + +```js +var checkError = require('check-error'); + +var funcThatThrows = function() { throw new TypeError('I am a TypeError') }; +var caughtErr; + +try { + funcThatThrows(); +} catch(e) { + caughtErr = e; +} + +var sameInstance = caughtErr; + +checkError.compatibleInstance(caughtErr, sameInstance); // true +checkError.compatibleInstance(caughtErr, new TypeError('Another error')); // false +``` + +#### .compatibleConstructor(err, errorLike) + +```js +var checkError = require('check-error'); + +var funcThatThrows = function() { throw new TypeError('I am a TypeError') }; +var caughtErr; + +try { + funcThatThrows(); +} catch(e) { + caughtErr = e; +} + +checkError.compatibleConstructor(caughtErr, Error); // true +checkError.compatibleConstructor(caughtErr, TypeError); // true +checkError.compatibleConstructor(caughtErr, RangeError); // false +``` + +#### .compatibleMessage(err, errMatcher) + +```js +var checkError = require('check-error'); + +var funcThatThrows = function() { throw new TypeError('I am a TypeError') }; +var caughtErr; + +try { + funcThatThrows(); +} catch(e) { + caughtErr = e; +} + +var sameInstance = caughtErr; + +checkError.compatibleMessage(caughtErr, /TypeError$/); // true +checkError.compatibleMessage(caughtErr, 'I am a'); // true +checkError.compatibleMessage(caughtErr, /unicorn/); // false +checkError.compatibleMessage(caughtErr, 'I do not exist'); // false +``` + +#### .getConstructorName(errorLike) + +```js +var checkError = require('check-error'); + +var funcThatThrows = function() { throw new TypeError('I am a TypeError') }; +var caughtErr; + +try { + funcThatThrows(); +} catch(e) { + caughtErr = e; +} + +var sameInstance = caughtErr; + +checkError.getConstructorName(caughtErr) // 'TypeError' +``` + +#### .getMessage(err) + +```js +var checkError = require('check-error'); + +var funcThatThrows = function() { throw new TypeError('I am a TypeError') }; +var caughtErr; + +try { + funcThatThrows(); +} catch(e) { + caughtErr = e; +} + +var sameInstance = caughtErr; + +checkError.getMessage(caughtErr) // 'I am a TypeError' +``` diff --git a/node_modules/check-error/index.js b/node_modules/check-error/index.js new file mode 100644 index 000000000..872a7b6c1 --- /dev/null +++ b/node_modules/check-error/index.js @@ -0,0 +1,135 @@ +function isErrorInstance(obj) { + // eslint-disable-next-line prefer-reflect + return obj instanceof Error || Object.prototype.toString.call(obj) === '[object Error]'; +} + +function isRegExp(obj) { + // eslint-disable-next-line prefer-reflect + return Object.prototype.toString.call(obj) === '[object RegExp]'; +} + +/** + * ### .compatibleInstance(thrown, errorLike) + * + * Checks if two instances are compatible (strict equal). + * Returns false if errorLike is not an instance of Error, because instances + * can only be compatible if they're both error instances. + * + * @name compatibleInstance + * @param {Error} thrown error + * @param {Error|ErrorConstructor} errorLike object to compare against + * @namespace Utils + * @api public + */ + +function compatibleInstance(thrown, errorLike) { + return isErrorInstance(errorLike) && thrown === errorLike; +} + +/** + * ### .compatibleConstructor(thrown, errorLike) + * + * Checks if two constructors are compatible. + * This function can receive either an error constructor or + * an error instance as the `errorLike` argument. + * Constructors are compatible if they're the same or if one is + * an instance of another. + * + * @name compatibleConstructor + * @param {Error} thrown error + * @param {Error|ErrorConstructor} errorLike object to compare against + * @namespace Utils + * @api public + */ + +function compatibleConstructor(thrown, errorLike) { + if (isErrorInstance(errorLike)) { + // If `errorLike` is an instance of any error we compare their constructors + return thrown.constructor === errorLike.constructor || thrown instanceof errorLike.constructor; + } else if ((typeof errorLike === 'object' || typeof errorLike === 'function') && errorLike.prototype) { + // If `errorLike` is a constructor that inherits from Error, we compare `thrown` to `errorLike` directly + return thrown.constructor === errorLike || thrown instanceof errorLike; + } + + return false; +} + +/** + * ### .compatibleMessage(thrown, errMatcher) + * + * Checks if an error's message is compatible with a matcher (String or RegExp). + * If the message contains the String or passes the RegExp test, + * it is considered compatible. + * + * @name compatibleMessage + * @param {Error} thrown error + * @param {String|RegExp} errMatcher to look for into the message + * @namespace Utils + * @api public + */ + +function compatibleMessage(thrown, errMatcher) { + const comparisonString = typeof thrown === 'string' ? thrown : thrown.message; + if (isRegExp(errMatcher)) { + return errMatcher.test(comparisonString); + } else if (typeof errMatcher === 'string') { + return comparisonString.indexOf(errMatcher) !== -1; // eslint-disable-line no-magic-numbers + } + + return false; +} + +/** + * ### .getConstructorName(errorLike) + * + * Gets the constructor name for an Error instance or constructor itself. + * + * @name getConstructorName + * @param {Error|ErrorConstructor} errorLike + * @namespace Utils + * @api public + */ + +function getConstructorName(errorLike) { + let constructorName = errorLike; + if (isErrorInstance(errorLike)) { + constructorName = errorLike.constructor.name; + } else if (typeof errorLike === 'function') { + // If `err` is not an instance of Error it is an error constructor itself or another function. + // If we've got a common function we get its name, otherwise we may need to create a new instance + // of the error just in case it's a poorly-constructed error. Please see chaijs/chai/issues/45 to know more. + constructorName = errorLike.name; + if (constructorName === '') { + const newConstructorName = (new errorLike().name); // eslint-disable-line new-cap + constructorName = newConstructorName || constructorName; + } + } + + return constructorName; +} + +/** + * ### .getMessage(errorLike) + * + * Gets the error message from an error. + * If `err` is a String itself, we return it. + * If the error has no message, we return an empty string. + * + * @name getMessage + * @param {Error|String} errorLike + * @namespace Utils + * @api public + */ + +function getMessage(errorLike) { + let msg = ''; + if (errorLike && errorLike.message) { + msg = errorLike.message; + } else if (typeof errorLike === 'string') { + msg = errorLike; + } + + return msg; +} + +export { compatibleInstance, compatibleConstructor, compatibleMessage, getMessage, getConstructorName }; diff --git a/node_modules/check-error/package.json b/node_modules/check-error/package.json new file mode 100644 index 000000000..d2dcbaf1e --- /dev/null +++ b/node_modules/check-error/package.json @@ -0,0 +1,66 @@ +{ + "version": "2.1.1", + "name": "check-error", + "description": "Error comparison and information related utility for node and the browser", + "keywords": ["check-error", "error", "chai util"], + "license": "MIT", + "author": "Jake Luer (http://alogicalparadox.com)", + "contributors": [ + "David Losert (https://github.com/davelosert)", + "Keith Cirkel (https://github.com/keithamus)", + "Miroslav Bajtoš (https://github.com/bajtos)", + "Lucas Fernandes da Costa (https://github.com/lucasfcosta)" + ], + "files": ["index.js", "check-error.js"], + "type": "module", + "main": "./index.js", + "module": "./index.js", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/chaijs/check-error.git" + }, + "scripts": { + "lint": "eslint --ignore-path .gitignore index.js test/", + "semantic-release": "semantic-release pre && npm publish && semantic-release post", + "pretest": "npm run lint", + "test": "npm run test:node && npm run test:browser", + "test:browser": "web-test-runner", + "test:node": "mocha" + }, + "config": { + "ghooks": { + "commit-msg": "validate-commit-msg" + } + }, + "eslintConfig": { + "extends": ["strict/es6"], + "env": { + "es6": true + }, + "globals": { + "HTMLElement": false + }, + "rules": { + "complexity": "off", + "max-statements": "off", + "prefer-arrow-callback": "off", + "prefer-reflect": "off" + } + }, + "devDependencies": { + "@web/test-runner": "^0.17.0", + "browserify": "^13.0.0", + "browserify-istanbul": "^1.0.0", + "eslint": "^2.4.0", + "eslint-config-strict": "^8.5.0", + "eslint-plugin-filenames": "^0.2.0", + "ghooks": "^1.0.1", + "mocha": "^9.1.2", + "semantic-release": "^4.3.5", + "simple-assert": "^2.0.0", + "validate-commit-msg": "^2.3.1" + }, + "engines": { + "node": ">= 16" + } +} diff --git a/node_modules/combined-stream/License b/node_modules/combined-stream/License new file mode 100644 index 000000000..4804b7ab4 --- /dev/null +++ b/node_modules/combined-stream/License @@ -0,0 +1,19 @@ +Copyright (c) 2011 Debuggable Limited + +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/node_modules/combined-stream/Readme.md b/node_modules/combined-stream/Readme.md new file mode 100644 index 000000000..9e367b5bc --- /dev/null +++ b/node_modules/combined-stream/Readme.md @@ -0,0 +1,138 @@ +# combined-stream + +A stream that emits multiple other streams one after another. + +**NB** Currently `combined-stream` works with streams version 1 only. There is ongoing effort to switch this library to streams version 2. Any help is welcome. :) Meanwhile you can explore other libraries that provide streams2 support with more or less compatibility with `combined-stream`. + +- [combined-stream2](https://www.npmjs.com/package/combined-stream2): A drop-in streams2-compatible replacement for the combined-stream module. + +- [multistream](https://www.npmjs.com/package/multistream): A stream that emits multiple other streams one after another. + +## Installation + +``` bash +npm install combined-stream +``` + +## Usage + +Here is a simple example that shows how you can use combined-stream to combine +two files into one: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create(); +combinedStream.append(fs.createReadStream('file1.txt')); +combinedStream.append(fs.createReadStream('file2.txt')); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +While the example above works great, it will pause all source streams until +they are needed. If you don't want that to happen, you can set `pauseStreams` +to `false`: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create({pauseStreams: false}); +combinedStream.append(fs.createReadStream('file1.txt')); +combinedStream.append(fs.createReadStream('file2.txt')); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +However, what if you don't have all the source streams yet, or you don't want +to allocate the resources (file descriptors, memory, etc.) for them right away? +Well, in that case you can simply provide a callback that supplies the stream +by calling a `next()` function: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create(); +combinedStream.append(function(next) { + next(fs.createReadStream('file1.txt')); +}); +combinedStream.append(function(next) { + next(fs.createReadStream('file2.txt')); +}); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +## API + +### CombinedStream.create([options]) + +Returns a new combined stream object. Available options are: + +* `maxDataSize` +* `pauseStreams` + +The effect of those options is described below. + +### combinedStream.pauseStreams = `true` + +Whether to apply back pressure to the underlaying streams. If set to `false`, +the underlaying streams will never be paused. If set to `true`, the +underlaying streams will be paused right after being appended, as well as when +`delayedStream.pipe()` wants to throttle. + +### combinedStream.maxDataSize = `2 * 1024 * 1024` + +The maximum amount of bytes (or characters) to buffer for all source streams. +If this value is exceeded, `combinedStream` emits an `'error'` event. + +### combinedStream.dataSize = `0` + +The amount of bytes (or characters) currently buffered by `combinedStream`. + +### combinedStream.append(stream) + +Appends the given `stream` to the combinedStream object. If `pauseStreams` is +set to `true, this stream will also be paused right away. + +`streams` can also be a function that takes one parameter called `next`. `next` +is a function that must be invoked in order to provide the `next` stream, see +example above. + +Regardless of how the `stream` is appended, combined-stream always attaches an +`'error'` listener to it, so you don't have to do that manually. + +Special case: `stream` can also be a String or Buffer. + +### combinedStream.write(data) + +You should not call this, `combinedStream` takes care of piping the appended +streams into itself for you. + +### combinedStream.resume() + +Causes `combinedStream` to start drain the streams it manages. The function is +idempotent, and also emits a `'resume'` event each time which usually goes to +the stream that is currently being drained. + +### combinedStream.pause(); + +If `combinedStream.pauseStreams` is set to `false`, this does nothing. +Otherwise a `'pause'` event is emitted, this goes to the stream that is +currently being drained, so you can use it to apply back pressure. + +### combinedStream.end(); + +Sets `combinedStream.writable` to false, emits an `'end'` event, and removes +all streams from the queue. + +### combinedStream.destroy(); + +Same as `combinedStream.end()`, except it emits a `'close'` event instead of +`'end'`. + +## License + +combined-stream is licensed under the MIT license. diff --git a/node_modules/combined-stream/lib/combined_stream.js b/node_modules/combined-stream/lib/combined_stream.js new file mode 100644 index 000000000..125f097f3 --- /dev/null +++ b/node_modules/combined-stream/lib/combined_stream.js @@ -0,0 +1,208 @@ +var util = require('util'); +var Stream = require('stream').Stream; +var DelayedStream = require('delayed-stream'); + +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; +} +util.inherits(CombinedStream, Stream); + +CombinedStream.create = function(options) { + var combinedStream = new this(); + + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } + + return combinedStream; +}; + +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; + +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; + } + + this._handleErrors(stream); + + if (this.pauseStreams) { + stream.pause(); + } + } + + this._streams.push(stream); + return this; +}; + +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; + +CombinedStream.prototype._getNext = function() { + this._currentStream = null; + + if (this._insideLoop) { + this._pendingNext = true; + return; // defer call + } + + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; + } +}; + +CombinedStream.prototype._realGetNext = function() { + var stream = this._streams.shift(); + + + if (typeof stream == 'undefined') { + this.end(); + return; + } + + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } + + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } + + this._pipeNext(stream); + }.bind(this)); +}; + +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; + + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } + + var value = stream; + this.write(value); + this._getNext(); +}; + +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; + +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; + +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; + +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; + +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; + +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; + +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; + +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } + + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; + +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; + + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } + + self.dataSize += stream.dataSize; + }); + + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } +}; + +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; diff --git a/node_modules/combined-stream/package.json b/node_modules/combined-stream/package.json new file mode 100644 index 000000000..6982b6da1 --- /dev/null +++ b/node_modules/combined-stream/package.json @@ -0,0 +1,25 @@ +{ + "author": "Felix Geisendörfer (http://debuggable.com/)", + "name": "combined-stream", + "description": "A stream that emits multiple other streams one after another.", + "version": "1.0.8", + "homepage": "https://github.com/felixge/node-combined-stream", + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-combined-stream.git" + }, + "main": "./lib/combined_stream", + "scripts": { + "test": "node test/run.js" + }, + "engines": { + "node": ">= 0.8" + }, + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "devDependencies": { + "far": "~0.0.7" + }, + "license": "MIT" +} diff --git a/node_modules/combined-stream/yarn.lock b/node_modules/combined-stream/yarn.lock new file mode 100644 index 000000000..7edf41840 --- /dev/null +++ b/node_modules/combined-stream/yarn.lock @@ -0,0 +1,17 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +delayed-stream@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" + +far@~0.0.7: + version "0.0.7" + resolved "https://registry.yarnpkg.com/far/-/far-0.0.7.tgz#01c1fd362bcd26ce9cf161af3938aa34619f79a7" + dependencies: + oop "0.0.3" + +oop@0.0.3: + version "0.0.3" + resolved "https://registry.yarnpkg.com/oop/-/oop-0.0.3.tgz#70fa405a5650891a194fdc82ca68dad6dabf4401" diff --git a/node_modules/deep-eql/LICENSE b/node_modules/deep-eql/LICENSE new file mode 100644 index 000000000..7ea799f0e --- /dev/null +++ b/node_modules/deep-eql/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013 Jake Luer (http://alogicalparadox.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. diff --git a/node_modules/deep-eql/README.md b/node_modules/deep-eql/README.md new file mode 100644 index 000000000..f6e1b85cf --- /dev/null +++ b/node_modules/deep-eql/README.md @@ -0,0 +1,93 @@ +

+ + deep-eql + +

+ +

+ Improved deep equality testing for node and the browser. +

+ +

+ + build:? + + coverage:? + + dependencies:? + + devDependencies:? + +
+ + Join the Slack chat + + + Join the Gitter chat + +

+ +## What is Deep-Eql? + +Deep Eql is a module which you can use to determine if two objects are "deeply" equal - that is, rather than having referential equality (`a === b`), this module checks an object's keys recursively, until it finds primitives to check for referential equality. For more on equality in JavaScript, read [the comparison operators article on mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators). + +As an example, take the following: + +```js +1 === 1 // These are primitives, they hold the same reference - they are strictly equal +1 == '1' // These are two different primitives, through type coercion they hold the same value - they are loosely equal +{ a: 1 } !== { a: 1 } // These are two different objects, they hold different references and so are not strictly equal - even though they hold the same values inside +{ a: 1 } != { a: 1 } // They have the same type, meaning loose equality performs the same check as strict equality - they are still not equal. + +var deepEql = require("deep-eql"); +deepEql({ a: 1 }, { a: 1 }) === true // deepEql can determine that they share the same keys and those keys share the same values, therefore they are deeply equal! +``` + +## Installation + +### Node.js + +`deep-eql` is available on [npm](http://npmjs.org). + + $ npm install deep-eql + +## Usage + +The primary export of `deep-eql` is function that can be given two objects to compare. It will always return a boolean which can be used to determine if two objects are deeply equal. + +### Rules + +- Strict equality for non-traversable nodes according to [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is): + - `eql(NaN, NaN).should.be.true;` + - `eql(-0, +0).should.be.false;` +- All own and inherited enumerable properties are considered: + - `eql(Object.create({ foo: { a: 1 } }), Object.create({ foo: { a: 1 } })).should.be.true;` + - `eql(Object.create({ foo: { a: 1 } }), Object.create({ foo: { a: 2 } })).should.be.false;` +- When comparing `Error` objects, only `name`, `message`, and `code` properties are considered, regardless of enumerability: + - `eql(Error('foo'), Error('foo')).should.be.true;` + - `eql(Error('foo'), Error('bar')).should.be.false;` + - `eql(Error('foo'), TypeError('foo')).should.be.false;` + - `eql(Object.assign(Error('foo'), { code: 42 }), Object.assign(Error('foo'), { code: 42 })).should.be.true;` + - `eql(Object.assign(Error('foo'), { code: 42 }), Object.assign(Error('foo'), { code: 13 })).should.be.false;` + - `eql(Object.assign(Error('foo'), { otherProp: 42 }), Object.assign(Error('foo'), { otherProp: 13 })).should.be.true;` +- Arguments are not Arrays: + - `eql([], arguments).should.be.false;` + - `eql([], Array.prototype.slice.call(arguments)).should.be.true;` diff --git a/node_modules/deep-eql/index.js b/node_modules/deep-eql/index.js new file mode 100644 index 000000000..8e5e333dd --- /dev/null +++ b/node_modules/deep-eql/index.js @@ -0,0 +1,513 @@ +/* globals Symbol: false, Uint8Array: false, WeakMap: false */ +/*! + * deep-eql + * Copyright(c) 2013 Jake Luer + * MIT Licensed + */ + +function type(obj) { + if (typeof obj === 'undefined') { + return 'undefined'; + } + + if (obj === null) { + return 'null'; + } + + const stringTag = obj[Symbol.toStringTag]; + if (typeof stringTag === 'string') { + return stringTag; + } + const sliceStart = 8; + const sliceEnd = -1; + return Object.prototype.toString.call(obj).slice(sliceStart, sliceEnd); +} + +function FakeMap() { + this._key = 'chai/deep-eql__' + Math.random() + Date.now(); +} + +FakeMap.prototype = { + get: function get(key) { + return key[this._key]; + }, + set: function set(key, value) { + if (Object.isExtensible(key)) { + Object.defineProperty(key, this._key, { + value: value, + configurable: true, + }); + } + }, +}; + +export var MemoizeMap = typeof WeakMap === 'function' ? WeakMap : FakeMap; +/*! + * Check to see if the MemoizeMap has recorded a result of the two operands + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {MemoizeMap} memoizeMap + * @returns {Boolean|null} result +*/ +function memoizeCompare(leftHandOperand, rightHandOperand, memoizeMap) { + // Technically, WeakMap keys can *only* be objects, not primitives. + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return null; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + var result = leftHandMap.get(rightHandOperand); + if (typeof result === 'boolean') { + return result; + } + } + return null; +} + +/*! + * Set the result of the equality into the MemoizeMap + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {MemoizeMap} memoizeMap + * @param {Boolean} result +*/ +function memoizeSet(leftHandOperand, rightHandOperand, memoizeMap, result) { + // Technically, WeakMap keys can *only* be objects, not primitives. + if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + return; + } + var leftHandMap = memoizeMap.get(leftHandOperand); + if (leftHandMap) { + leftHandMap.set(rightHandOperand, result); + } else { + leftHandMap = new MemoizeMap(); + leftHandMap.set(rightHandOperand, result); + memoizeMap.set(leftHandOperand, leftHandMap); + } +} + +/*! + * Primary Export + */ + +export default deepEqual; + +/** + * Assert deeply nested sameValue equality between two objects of any type. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (optional) Additional options + * @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality. + * @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of + complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular + references to blow the stack. + * @return {Boolean} equal match + */ +function deepEqual(leftHandOperand, rightHandOperand, options) { + // If we have a comparator, we can't assume anything; so bail to its check first. + if (options && options.comparator) { + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); + } + + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + return simpleResult; + } + + // Deeper comparisons are pushed through to a larger function + return extensiveDeepEqual(leftHandOperand, rightHandOperand, options); +} + +/** + * Many comparisons can be canceled out early via simple equality or primitive checks. + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @return {Boolean|null} equal match + */ +function simpleEqual(leftHandOperand, rightHandOperand) { + // Equal references (except for Numbers) can be returned early + if (leftHandOperand === rightHandOperand) { + // Handle +-0 cases + return leftHandOperand !== 0 || 1 / leftHandOperand === 1 / rightHandOperand; + } + + // handle NaN cases + if ( + leftHandOperand !== leftHandOperand && // eslint-disable-line no-self-compare + rightHandOperand !== rightHandOperand // eslint-disable-line no-self-compare + ) { + return true; + } + + // Anything that is not an 'object', i.e. symbols, functions, booleans, numbers, + // strings, and undefined, can be compared by reference. + if (isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) { + // Easy out b/c it would have passed the first equality check + return false; + } + return null; +} + +/*! + * The main logic of the `deepEqual` function. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (optional) Additional options + * @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality. + * @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of + complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular + references to blow the stack. + * @return {Boolean} equal match +*/ +function extensiveDeepEqual(leftHandOperand, rightHandOperand, options) { + options = options || {}; + options.memoize = options.memoize === false ? false : options.memoize || new MemoizeMap(); + var comparator = options && options.comparator; + + // Check if a memoized result exists. + var memoizeResultLeft = memoizeCompare(leftHandOperand, rightHandOperand, options.memoize); + if (memoizeResultLeft !== null) { + return memoizeResultLeft; + } + var memoizeResultRight = memoizeCompare(rightHandOperand, leftHandOperand, options.memoize); + if (memoizeResultRight !== null) { + return memoizeResultRight; + } + + // If a comparator is present, use it. + if (comparator) { + var comparatorResult = comparator(leftHandOperand, rightHandOperand); + // Comparators may return null, in which case we want to go back to default behavior. + if (comparatorResult === false || comparatorResult === true) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, comparatorResult); + return comparatorResult; + } + // To allow comparators to override *any* behavior, we ran them first. Since it didn't decide + // what to do, we need to make sure to return the basic tests first before we move on. + var simpleResult = simpleEqual(leftHandOperand, rightHandOperand); + if (simpleResult !== null) { + // Don't memoize this, it takes longer to set/retrieve than to just compare. + return simpleResult; + } + } + + var leftHandType = type(leftHandOperand); + if (leftHandType !== type(rightHandOperand)) { + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, false); + return false; + } + + // Temporarily set the operands in the memoize object to prevent blowing the stack + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, true); + + var result = extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options); + memoizeSet(leftHandOperand, rightHandOperand, options.memoize, result); + return result; +} + +function extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options) { + switch (leftHandType) { + case 'String': + case 'Number': + case 'Boolean': + case 'Date': + // If these types are their instance types (e.g. `new Number`) then re-deepEqual against their values + return deepEqual(leftHandOperand.valueOf(), rightHandOperand.valueOf()); + case 'Promise': + case 'Symbol': + case 'function': + case 'WeakMap': + case 'WeakSet': + return leftHandOperand === rightHandOperand; + case 'Error': + return keysEqual(leftHandOperand, rightHandOperand, [ 'name', 'message', 'code' ], options); + case 'Arguments': + case 'Int8Array': + case 'Uint8Array': + case 'Uint8ClampedArray': + case 'Int16Array': + case 'Uint16Array': + case 'Int32Array': + case 'Uint32Array': + case 'Float32Array': + case 'Float64Array': + case 'Array': + return iterableEqual(leftHandOperand, rightHandOperand, options); + case 'RegExp': + return regexpEqual(leftHandOperand, rightHandOperand); + case 'Generator': + return generatorEqual(leftHandOperand, rightHandOperand, options); + case 'DataView': + return iterableEqual(new Uint8Array(leftHandOperand.buffer), new Uint8Array(rightHandOperand.buffer), options); + case 'ArrayBuffer': + return iterableEqual(new Uint8Array(leftHandOperand), new Uint8Array(rightHandOperand), options); + case 'Set': + return entriesEqual(leftHandOperand, rightHandOperand, options); + case 'Map': + return entriesEqual(leftHandOperand, rightHandOperand, options); + case 'Temporal.PlainDate': + case 'Temporal.PlainTime': + case 'Temporal.PlainDateTime': + case 'Temporal.Instant': + case 'Temporal.ZonedDateTime': + case 'Temporal.PlainYearMonth': + case 'Temporal.PlainMonthDay': + return leftHandOperand.equals(rightHandOperand); + case 'Temporal.Duration': + return leftHandOperand.total('nanoseconds') === rightHandOperand.total('nanoseconds'); + case 'Temporal.TimeZone': + case 'Temporal.Calendar': + return leftHandOperand.toString() === rightHandOperand.toString(); + default: + return objectEqual(leftHandOperand, rightHandOperand, options); + } +} + +/*! + * Compare two Regular Expressions for equality. + * + * @param {RegExp} leftHandOperand + * @param {RegExp} rightHandOperand + * @return {Boolean} result + */ + +function regexpEqual(leftHandOperand, rightHandOperand) { + return leftHandOperand.toString() === rightHandOperand.toString(); +} + +/*! + * Compare two Sets/Maps for equality. Faster than other equality functions. + * + * @param {Set} leftHandOperand + * @param {Set} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + +function entriesEqual(leftHandOperand, rightHandOperand, options) { + try { + // IE11 doesn't support Set#entries or Set#@@iterator, so we need manually populate using Set#forEach + if (leftHandOperand.size !== rightHandOperand.size) { + return false; + } + if (leftHandOperand.size === 0) { + return true; + } + } catch (sizeError) { + // things that aren't actual Maps or Sets will throw here + return false; + } + var leftHandItems = []; + var rightHandItems = []; + leftHandOperand.forEach(function gatherEntries(key, value) { + leftHandItems.push([ key, value ]); + }); + rightHandOperand.forEach(function gatherEntries(key, value) { + rightHandItems.push([ key, value ]); + }); + return iterableEqual(leftHandItems.sort(), rightHandItems.sort(), options); +} + +/*! + * Simple equality for flat iterable objects such as Arrays, TypedArrays or Node.js buffers. + * + * @param {Iterable} leftHandOperand + * @param {Iterable} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + +function iterableEqual(leftHandOperand, rightHandOperand, options) { + var length = leftHandOperand.length; + if (length !== rightHandOperand.length) { + return false; + } + if (length === 0) { + return true; + } + var index = -1; + while (++index < length) { + if (deepEqual(leftHandOperand[index], rightHandOperand[index], options) === false) { + return false; + } + } + return true; +} + +/*! + * Simple equality for generator objects such as those returned by generator functions. + * + * @param {Iterable} leftHandOperand + * @param {Iterable} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ + +function generatorEqual(leftHandOperand, rightHandOperand, options) { + return iterableEqual(getGeneratorEntries(leftHandOperand), getGeneratorEntries(rightHandOperand), options); +} + +/*! + * Determine if the given object has an @@iterator function. + * + * @param {Object} target + * @return {Boolean} `true` if the object has an @@iterator function. + */ +function hasIteratorFunction(target) { + return typeof Symbol !== 'undefined' && + typeof target === 'object' && + typeof Symbol.iterator !== 'undefined' && + typeof target[Symbol.iterator] === 'function'; +} + +/*! + * Gets all iterator entries from the given Object. If the Object has no @@iterator function, returns an empty array. + * This will consume the iterator - which could have side effects depending on the @@iterator implementation. + * + * @param {Object} target + * @returns {Array} an array of entries from the @@iterator function + */ +function getIteratorEntries(target) { + if (hasIteratorFunction(target)) { + try { + return getGeneratorEntries(target[Symbol.iterator]()); + } catch (iteratorError) { + return []; + } + } + return []; +} + +/*! + * Gets all entries from a Generator. This will consume the generator - which could have side effects. + * + * @param {Generator} target + * @returns {Array} an array of entries from the Generator. + */ +function getGeneratorEntries(generator) { + var generatorResult = generator.next(); + var accumulator = [ generatorResult.value ]; + while (generatorResult.done === false) { + generatorResult = generator.next(); + accumulator.push(generatorResult.value); + } + return accumulator; +} + +/*! + * Gets all own and inherited enumerable keys from a target. + * + * @param {Object} target + * @returns {Array} an array of own and inherited enumerable keys from the target. + */ +function getEnumerableKeys(target) { + var keys = []; + for (var key in target) { + keys.push(key); + } + return keys; +} + +function getEnumerableSymbols(target) { + var keys = []; + var allKeys = Object.getOwnPropertySymbols(target); + for (var i = 0; i < allKeys.length; i += 1) { + var key = allKeys[i]; + if (Object.getOwnPropertyDescriptor(target, key).enumerable) { + keys.push(key); + } + } + return keys; +} + +/*! + * Determines if two objects have matching values, given a set of keys. Defers to deepEqual for the equality check of + * each key. If any value of the given key is not equal, the function will return false (early). + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Array} keys An array of keys to compare the values of leftHandOperand and rightHandOperand against + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ +function keysEqual(leftHandOperand, rightHandOperand, keys, options) { + var length = keys.length; + if (length === 0) { + return true; + } + for (var i = 0; i < length; i += 1) { + if (deepEqual(leftHandOperand[keys[i]], rightHandOperand[keys[i]], options) === false) { + return false; + } + } + return true; +} + +/*! + * Recursively check the equality of two Objects. Once basic sameness has been established it will defer to `deepEqual` + * for each enumerable key in the object. + * + * @param {Mixed} leftHandOperand + * @param {Mixed} rightHandOperand + * @param {Object} [options] (Optional) + * @return {Boolean} result + */ +function objectEqual(leftHandOperand, rightHandOperand, options) { + var leftHandKeys = getEnumerableKeys(leftHandOperand); + var rightHandKeys = getEnumerableKeys(rightHandOperand); + var leftHandSymbols = getEnumerableSymbols(leftHandOperand); + var rightHandSymbols = getEnumerableSymbols(rightHandOperand); + leftHandKeys = leftHandKeys.concat(leftHandSymbols); + rightHandKeys = rightHandKeys.concat(rightHandSymbols); + + if (leftHandKeys.length && leftHandKeys.length === rightHandKeys.length) { + if (iterableEqual(mapSymbols(leftHandKeys).sort(), mapSymbols(rightHandKeys).sort()) === false) { + return false; + } + return keysEqual(leftHandOperand, rightHandOperand, leftHandKeys, options); + } + + var leftHandEntries = getIteratorEntries(leftHandOperand); + var rightHandEntries = getIteratorEntries(rightHandOperand); + if (leftHandEntries.length && leftHandEntries.length === rightHandEntries.length) { + leftHandEntries.sort(); + rightHandEntries.sort(); + return iterableEqual(leftHandEntries, rightHandEntries, options); + } + + if (leftHandKeys.length === 0 && + leftHandEntries.length === 0 && + rightHandKeys.length === 0 && + rightHandEntries.length === 0) { + return true; + } + + return false; +} + +/*! + * Returns true if the argument is a primitive. + * + * This intentionally returns true for all objects that can be compared by reference, + * including functions and symbols. + * + * @param {Mixed} value + * @return {Boolean} result + */ +function isPrimitive(value) { + return value === null || typeof value !== 'object'; +} + +function mapSymbols(arr) { + return arr.map(function mapSymbol(entry) { + if (typeof entry === 'symbol') { + return entry.toString(); + } + + return entry; + }); +} diff --git a/node_modules/deep-eql/package.json b/node_modules/deep-eql/package.json new file mode 100644 index 000000000..c88004316 --- /dev/null +++ b/node_modules/deep-eql/package.json @@ -0,0 +1,73 @@ +{ + "name": "deep-eql", + "version": "5.0.2", + "description": "Improved deep equality testing for Node.js and the browser.", + "keywords": [ + "chai util", + "deep equal", + "object equal", + "testing" + ], + "repository": { + "type": "git", + "url": "git@github.com:chaijs/deep-eql.git" + }, + "license": "MIT", + "author": "Jake Luer ", + "contributors": [ + "Keith Cirkel (https://github.com/keithamus)", + "dougluce (https://github.com/dougluce)", + "Lorenz Leutgeb (https://github.com/flowlo)" + ], + "type": "module", + "main": "./index.js", + "files": [ + "index.js", + "deep-eql.js" + ], + "scripts": { + "bench": "node bench", + "lint": "eslint --ignore-path .gitignore .", + "semantic-release": "semantic-release pre && semantic-release post", + "pretest": "npm run lint", + "test": "npm run test:node && npm run test:browser", + "test:browser": "web-test-runner", + "test:node": "istanbul cover _mocha", + "upload-coverage": "lcov-result-merger 'coverage/**/lcov.info' | coveralls; exit 0", + "watch": "web-test-runner --watch" + }, + "eslintConfig": { + "extends": [ + "strict/es5" + ], + "rules": { + "complexity": 0, + "no-underscore-dangle": 0, + "no-use-before-define": 0, + "spaced-comment": 0 + }, + "parserOptions": { + "sourceType": "module", + "ecmaVersion": 2015 + } + }, + "devDependencies": { + "@js-temporal/polyfill": "^0.4.3", + "@rollup/plugin-commonjs": "^24.1.0", + "@web/test-runner": "^0.16.1", + "benchmark": "^2.1.0", + "coveralls": "^3.1.1", + "eslint": "^7.32.0", + "eslint-config-strict": "^14.0.1", + "eslint-plugin-filenames": "^1.3.2", + "istanbul": "^0.4.2", + "kewlr": "^0.4.1", + "lcov-result-merger": "^1.0.2", + "lodash.isequal": "^4.4.0", + "mocha": "^9.1.1", + "simple-assert": "^2.0.0" + }, + "engines": { + "node": ">=6" + } +} diff --git a/node_modules/delayed-stream/.npmignore b/node_modules/delayed-stream/.npmignore new file mode 100644 index 000000000..9daeafb98 --- /dev/null +++ b/node_modules/delayed-stream/.npmignore @@ -0,0 +1 @@ +test diff --git a/node_modules/delayed-stream/License b/node_modules/delayed-stream/License new file mode 100644 index 000000000..4804b7ab4 --- /dev/null +++ b/node_modules/delayed-stream/License @@ -0,0 +1,19 @@ +Copyright (c) 2011 Debuggable Limited + +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/node_modules/delayed-stream/Makefile b/node_modules/delayed-stream/Makefile new file mode 100644 index 000000000..b4ff85a33 --- /dev/null +++ b/node_modules/delayed-stream/Makefile @@ -0,0 +1,7 @@ +SHELL := /bin/bash + +test: + @./test/run.js + +.PHONY: test + diff --git a/node_modules/delayed-stream/Readme.md b/node_modules/delayed-stream/Readme.md new file mode 100644 index 000000000..aca36f9f0 --- /dev/null +++ b/node_modules/delayed-stream/Readme.md @@ -0,0 +1,141 @@ +# delayed-stream + +Buffers events from a stream until you are ready to handle them. + +## Installation + +``` bash +npm install delayed-stream +``` + +## Usage + +The following example shows how to write a http echo server that delays its +response by 1000 ms. + +``` javascript +var DelayedStream = require('delayed-stream'); +var http = require('http'); + +http.createServer(function(req, res) { + var delayed = DelayedStream.create(req); + + setTimeout(function() { + res.writeHead(200); + delayed.pipe(res); + }, 1000); +}); +``` + +If you are not using `Stream#pipe`, you can also manually release the buffered +events by calling `delayedStream.resume()`: + +``` javascript +var delayed = DelayedStream.create(req); + +setTimeout(function() { + // Emit all buffered events and resume underlaying source + delayed.resume(); +}, 1000); +``` + +## Implementation + +In order to use this meta stream properly, here are a few things you should +know about the implementation. + +### Event Buffering / Proxying + +All events of the `source` stream are hijacked by overwriting the `source.emit` +method. Until node implements a catch-all event listener, this is the only way. + +However, delayed-stream still continues to emit all events it captures on the +`source`, regardless of whether you have released the delayed stream yet or +not. + +Upon creation, delayed-stream captures all `source` events and stores them in +an internal event buffer. Once `delayedStream.release()` is called, all +buffered events are emitted on the `delayedStream`, and the event buffer is +cleared. After that, delayed-stream merely acts as a proxy for the underlaying +source. + +### Error handling + +Error events on `source` are buffered / proxied just like any other events. +However, `delayedStream.create` attaches a no-op `'error'` listener to the +`source`. This way you only have to handle errors on the `delayedStream` +object, rather than in two places. + +### Buffer limits + +delayed-stream provides a `maxDataSize` property that can be used to limit +the amount of data being buffered. In order to protect you from bad `source` +streams that don't react to `source.pause()`, this feature is enabled by +default. + +## API + +### DelayedStream.create(source, [options]) + +Returns a new `delayedStream`. Available options are: + +* `pauseStream` +* `maxDataSize` + +The description for those properties can be found below. + +### delayedStream.source + +The `source` stream managed by this object. This is useful if you are +passing your `delayedStream` around, and you still want to access properties +on the `source` object. + +### delayedStream.pauseStream = true + +Whether to pause the underlaying `source` when calling +`DelayedStream.create()`. Modifying this property afterwards has no effect. + +### delayedStream.maxDataSize = 1024 * 1024 + +The amount of data to buffer before emitting an `error`. + +If the underlaying source is emitting `Buffer` objects, the `maxDataSize` +refers to bytes. + +If the underlaying source is emitting JavaScript strings, the size refers to +characters. + +If you know what you are doing, you can set this property to `Infinity` to +disable this feature. You can also modify this property during runtime. + +### delayedStream.dataSize = 0 + +The amount of data buffered so far. + +### delayedStream.readable + +An ECMA5 getter that returns the value of `source.readable`. + +### delayedStream.resume() + +If the `delayedStream` has not been released so far, `delayedStream.release()` +is called. + +In either case, `source.resume()` is called. + +### delayedStream.pause() + +Calls `source.pause()`. + +### delayedStream.pipe(dest) + +Calls `delayedStream.resume()` and then proxies the arguments to `source.pipe`. + +### delayedStream.release() + +Emits and clears all events that have been buffered up so far. This does not +resume the underlaying source, use `delayedStream.resume()` instead. + +## License + +delayed-stream is licensed under the MIT license. diff --git a/node_modules/delayed-stream/lib/delayed_stream.js b/node_modules/delayed-stream/lib/delayed_stream.js new file mode 100644 index 000000000..b38fc85ff --- /dev/null +++ b/node_modules/delayed-stream/lib/delayed_stream.js @@ -0,0 +1,107 @@ +var Stream = require('stream').Stream; +var util = require('util'); + +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; +} +util.inherits(DelayedStream, Stream); + +DelayedStream.create = function(source, options) { + var delayedStream = new this(); + + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; + } + + delayedStream.source = source; + + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; + + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); + } + + return delayedStream; +}; + +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; + } +}); + +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); +}; + +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); + } + + this.source.resume(); +}; + +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; + +DelayedStream.prototype.release = function() { + this._released = true; + + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; +}; + +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; +}; + +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } + + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } + + this._bufferedEvents.push(args); +}; + +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; + } + + if (this.dataSize <= this.maxDataSize) { + return; + } + + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); +}; diff --git a/node_modules/delayed-stream/package.json b/node_modules/delayed-stream/package.json new file mode 100644 index 000000000..eea3291c5 --- /dev/null +++ b/node_modules/delayed-stream/package.json @@ -0,0 +1,27 @@ +{ + "author": "Felix Geisendörfer (http://debuggable.com/)", + "contributors": [ + "Mike Atkins " + ], + "name": "delayed-stream", + "description": "Buffers events from a stream until you are ready to handle them.", + "license": "MIT", + "version": "1.0.0", + "homepage": "https://github.com/felixge/node-delayed-stream", + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-delayed-stream.git" + }, + "main": "./lib/delayed_stream", + "engines": { + "node": ">=0.4.0" + }, + "scripts": { + "test": "make test" + }, + "dependencies": {}, + "devDependencies": { + "fake": "0.2.0", + "far": "0.0.1" + } +} diff --git a/node_modules/eventsource/.editorconfig b/node_modules/eventsource/.editorconfig new file mode 100644 index 000000000..88f10ae83 --- /dev/null +++ b/node_modules/eventsource/.editorconfig @@ -0,0 +1,27 @@ +# http://editorconfig.org +root = true + +[*] +# Use hard or soft tabs +indent_style = space + +# Size of a single indent +indent_size = tab + +# Number of columns representing a tab character +tab_width = 2 + +# Use line-feed as EOL indicator +end_of_line = lf + +# Use UTF-8 character encoding for all files +charset = utf-8 + +# Remove any whitespace characters preceding newline characters +trim_trailing_whitespace = true + +# Ensure file ends with a newline when saving +insert_final_newline = true + +[*.md] +trim_trailing_whitespace = false diff --git a/node_modules/eventsource/CONTRIBUTING.md b/node_modules/eventsource/CONTRIBUTING.md new file mode 100644 index 000000000..f66db3b0e --- /dev/null +++ b/node_modules/eventsource/CONTRIBUTING.md @@ -0,0 +1,13 @@ +# Contributing to EventSource + +If you add or fix something, add tests. + +## Release process + +Update `HISTORY.md`, Then: + + npm outdated --depth 0 # See if you can upgrade something + npm run polyfill + git commit ... + npm version [major|minor|patch] + npm publish diff --git a/node_modules/eventsource/HISTORY.md b/node_modules/eventsource/HISTORY.md new file mode 100644 index 000000000..d5e662a3d --- /dev/null +++ b/node_modules/eventsource/HISTORY.md @@ -0,0 +1,161 @@ +# [2.0.2](https://github.com/EventSource/eventsource/compare/v2.0.1...v2.0.2) + +* Do not include authorization and cookie headers on redirect to different origin ([#273](https://github.com/EventSource/eventsource/pull/273) Espen Hovlandsdal) + +# [2.0.1](https://github.com/EventSource/eventsource/compare/v2.0.0...v2.0.1) + +* Fix `URL is not a constructor` error for browser ([#268](https://github.com/EventSource/eventsource/pull/268) Ajinkya Rajput) + +# [2.0.0](https://github.com/EventSource/eventsource/compare/v1.1.0...v2.0.0) + +* BREAKING: Node >= 12 now required ([#152](https://github.com/EventSource/eventsource/pull/152) @HonkingGoose) +* Preallocate buffer size when reading data for increased performance with large messages ([#239](https://github.com/EventSource/eventsource/pull/239) Pau Freixes) +* Removed dependency on url-parser. Fixes [CVE-2022-0512](https://www.whitesourcesoftware.com/vulnerability-database/CVE-2022-0512) & [CVE-2022-0691](https://nvd.nist.gov/vuln/detail/CVE-2022-0691) ([#249](https://github.com/EventSource/eventsource/pull/249) Alex Hladin) + +# [1.1.1](https://github.com/EventSource/eventsource/compare/v1.1.0...v1.1.1) + +* Do not include authorization and cookie headers on redirect to different origin ([#273](https://github.com/EventSource/eventsource/pull/273) Espen Hovlandsdal) + +# [1.1.0](https://github.com/EventSource/eventsource/compare/v1.0.7...v1.1.0) + +* Improve performance for large messages across many chunks ([#130](https://github.com/EventSource/eventsource/pull/130) Trent Willis) +* Add `createConnection` option for http or https requests ([#120](https://github.com/EventSource/eventsource/pull/120) Vasily Lavrov) +* Support HTTP 302 redirects ([#116](https://github.com/EventSource/eventsource/pull/116) Ryan Bonte) +* Prevent sequential errors from attempting multiple reconnections ([#125](https://github.com/EventSource/eventsource/pull/125) David Patty) +* Add `new` to correct test ([#111](https://github.com/EventSource/eventsource/pull/101) Stéphane Alnet) +* Fix reconnections attempts now happen more than once ([#136](https://github.com/EventSource/eventsource/pull/136) Icy Fish) + +# [1.0.7](https://github.com/EventSource/eventsource/compare/v1.0.6...v1.0.7) + +* Add dispatchEvent to EventSource ([#101](https://github.com/EventSource/eventsource/pull/101) Ali Afroozeh) +* Added `checkServerIdentity` option ([#104](https://github.com/EventSource/eventsource/pull/104) cintolas) +* Surface request error message ([#107](https://github.com/EventSource/eventsource/pull/107) RasPhilCo) + +# [1.0.6](https://github.com/EventSource/eventsource/compare/v1.0.5...v1.0.6) + +* Fix issue where a unicode sequence split in two chunks would lead to invalid messages ([#108](https://github.com/EventSource/eventsource/pull/108) Espen Hovlandsdal) +* Change example to use `eventsource/ssestream` (Aslak Hellesøy) + +# [1.0.5](https://github.com/EventSource/eventsource/compare/v1.0.4...v1.0.5) + +* Check for `window` existing before polyfilling. ([#80](https://github.com/EventSource/eventsource/pull/80) Neftaly Hernandez) + +# [1.0.4](https://github.com/EventSource/eventsource/compare/v1.0.2...v1.0.4) + +* Pass withCredentials on to the XHR. ([#79](https://github.com/EventSource/eventsource/pull/79) Ken Mayer) + +# [1.0.2](https://github.com/EventSource/eventsource/compare/v1.0.1...v1.0.2) + +* Fix proxy not working when proxy and target URL uses different protocols. ([#76](https://github.com/EventSource/eventsource/pull/76) Espen Hovlandsdal) +* Make `close()` a prototype method instead of an instance method. ([#77](https://github.com/EventSource/eventsource/pull/77) Espen Hovlandsdal) + +# [1.0.1](https://github.com/EventSource/eventsource/compare/v1.0.0...v1.0.1) + +* Reconnect if server responds with HTTP 500, 502, 503 or 504. ([#74](https://github.com/EventSource/eventsource/pull/74) Vykintas Narmontas) + +# [1.0.0](https://github.com/EventSource/eventsource/compare/v0.2.3...v1.0.0) + +* Add missing `removeEventListener`-method. ([#51](https://github.com/EventSource/eventsource/pull/51) Yucheng Tu / Espen Hovlandsdal) +* Fix EventSource reconnecting on non-200 responses. ([af84476](https://github.com/EventSource/eventsource/commit/af84476b519a01e61b8c80727261df52ae40022c) Espen Hovlandsdal) +* Add ability to customize https options. ([#53](https://github.com/EventSource/eventsource/pull/53) Rafael Alfaro) +* Add readyState constants to EventSource instances. ([#66](https://github.com/EventSource/eventsource/pull/66) Espen Hovlandsdal) + +# [0.2.3](https://github.com/EventSource/eventsource/compare/v0.2.2...v0.2.3) + +* Fix `onConnectionClosed` firing multiple times resulting in multiple connections. ([#61](https://github.com/EventSource/eventsource/pull/61) Phil Strong / Duncan Wong) +* Remove unneeded isPlainObject check for headers. ([#64](https://github.com/EventSource/eventsource/pull/64) David Mark) + +# [0.2.2](https://github.com/EventSource/eventsource/compare/v0.2.1...v0.2.2) + +* Don't include test files in npm package. ([#56](https://github.com/EventSource/eventsource/pull/56) eanplatter) + +# [0.2.1](https://github.com/EventSource/eventsource/compare/v0.2.0...v0.2.1) + +* Fix `close()` for polyfill. ([#52](https://github.com/EventSource/eventsource/pull/52) brian-medendorp) +* Add http/https proxy function. ([#46](https://github.com/EventSource/eventsource/pull/46) Eric Lu) +* Fix reconnect for polyfill. Only disable reconnect when server status is 204. (Aslak Hellesøy). +* Drop support for Node 0.10.x and older (Aslak Hellesøy). + +# [0.2.0](https://github.com/EventSource/eventsource/compare/v0.1.6...v0.2.0) + +* Renamed repository to `eventsource` (since it's not just Node, but also browser polyfill). (Aslak Hellesøy). +* Compatibility with webpack/browserify. ([#44](https://github.com/EventSource/eventsource/pull/44) Adriano Raiano). + +# [0.1.6](https://github.com/EventSource/eventsource/compare/v0.1.5...v0.1.6) + +* Ignore headers without a value. ([#41](https://github.com/EventSource/eventsource/issues/41), [#43](https://github.com/EventSource/eventsource/pull/43) Adriano Raiano) + +# [0.1.5](https://github.com/EventSource/eventsource/compare/v0.1.4...v0.1.5) + +* Refactor tests to support Node.js 0.12.0 and Io.js 1.1.0. (Aslak Hellesøy) + +# [0.1.4](https://github.com/EventSource/eventsource/compare/v0.1.3...master) + +* Bugfix: Added missing origin property. ([#39](https://github.com/EventSource/eventsource/pull/39), [#38](https://github.com/EventSource/eventsource/issues/38) Arnout Kazemier) +* Expose `status` property on `error` events. ([#40](https://github.com/EventSource/eventsource/pull/40) Adriano Raiano) + +# [0.1.3](https://github.com/EventSource/eventsource/compare/v0.1.2...v0.1.3) + +* Bugfix: Made message properties enumerable. ([#37](https://github.com/EventSource/eventsource/pull/37) Golo Roden) + +# [0.1.2](https://github.com/EventSource/eventsource/compare/v0.1.1...v0.1.2) + +* Bugfix: Blank lines not read. ([#35](https://github.com/EventSource/eventsource/issues/35), [#36](https://github.com/EventSource/eventsource/pull/36) Lesterpig) + +# [0.1.1](https://github.com/EventSource/eventsource/compare/v0.1.0...v0.1.1) + +* Bugfix: Fix message type. ([#33](https://github.com/EventSource/eventsource/pull/33) Romain Gauthier) + +# [0.1.0](https://github.com/EventSource/eventsource/compare/v0.0.10...v0.1.0) + +* Bugfix: High CPU usage by replacing Jison with port of WebKit's parser. ([#25](https://github.com/EventSource/eventsource/issues/25), [#32](https://github.com/EventSource/eventsource/pull/32), [#18](https://github.com/EventSource/eventsource/issues/18) qqueue) +* Reformatted all code to 2 spaces. + +# [0.0.10](https://github.com/EventSource/eventsource/compare/v0.0.9...v0.0.10) + +* Provide `Event` argument on `open` and `error` event ([#30](https://github.com/EventSource/eventsource/issues/30), [#31](https://github.com/EventSource/eventsource/pull/31) Donghwan Kim) +* Expose `lastEventId` on messages. ([#28](https://github.com/EventSource/eventsource/pull/28) mbieser) + +# [0.0.9](https://github.com/EventSource/eventsource/compare/v0.0.8...v0.0.9) + +* Bugfix: old "last-event-id" used on reconnect ([#27](https://github.com/EventSource/eventsource/pull/27) Aslak Hellesøy) + +# [0.0.8](https://github.com/EventSource/eventsource/compare/v0.0.7...v0.0.8) + +* Bugfix: EventSource still reconnected when closed ([#24](https://github.com/EventSource/eventsource/pull/24) FrozenCow) +* Allow unauthorized HTTPS connections by setting `rejectUnauthorized` to false. (Aslak Hellesøy) + +# [0.0.7](https://github.com/EventSource/eventsource/compare/v0.0.6...v0.0.7) + +* Explicitly raise an error when server returns http 403 and don't continue ([#20](https://github.com/EventSource/eventsource/pull/20) Scott Moak) +* Added ability to send custom http headers to server ([#21](https://github.com/EventSource/eventsource/pull/21), [#9](https://github.com/EventSource/eventsource/issues/9) Scott Moak) +* Fix Unicode support to cope with Javascript Unicode size limitations ([#23](https://github.com/EventSource/eventsource/pull/23), [#22](https://github.com/EventSource/eventsource/issues/22) Devon Adkisson) +* Graceful handling of parse errors ([#19](https://github.com/EventSource/eventsource/issues/19) Aslak Hellesøy) +* Switched from testing with Nodeunit to Mocha (Aslak Hellesøy) + +# [0.0.6](https://github.com/EventSource/eventsource/compare/v0.0.5...v0.0.6) + +* Add Accept: text/event-stream header ([#17](https://github.com/EventSource/eventsource/pull/17) William Wicks) + +# [0.0.5](https://github.com/EventSource/eventsource/compare/v0.0.4...v0.0.5) + +* Add no-cache and https support ([#10](https://github.com/EventSource/eventsource/pull/10) Einar Otto Stangvik) +* Ensure that Last-Event-ID is sent to the server for reconnects, as defined in the spec ([#8](https://github.com/EventSource/eventsource/pull/8) Einar Otto Stangvik) +* Verify that CR and CRLF are accepted alongside LF ([#7](https://github.com/EventSource/eventsource/pull/7) Einar Otto Stangvik) +* Emit 'open' event ([#4](https://github.com/EventSource/eventsource/issues/4) Einar Otto Stangvik) + +# [0.0.4](https://github.com/EventSource/eventsource/compare/v0.0.3...v0.0.4) + +* Automatic reconnect every second if the server is down. Reconnect interval can be set with `reconnectInterval` (not in W3C spec). (Aslak Hellesøy) + +# [0.0.3](https://github.com/EventSource/eventsource/compare/v0.0.2...v0.0.3) + +* Jison based eventstream parser ([#2](https://github.com/EventSource/eventsource/pull/2) Einar Otto Stangvik) + +# [0.0.2](https://github.com/EventSource/eventsource/compare/v0.0.1...v0.0.2) + +* Use native EventListener (Aslak Hellesøy) + +# 0.0.1 + +* First release diff --git a/node_modules/eventsource/LICENSE b/node_modules/eventsource/LICENSE new file mode 100644 index 000000000..505b0d90b --- /dev/null +++ b/node_modules/eventsource/LICENSE @@ -0,0 +1,22 @@ +The MIT License + +Copyright (c) EventSource GitHub organisation + +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/node_modules/eventsource/README.md b/node_modules/eventsource/README.md new file mode 100644 index 000000000..a6b6d2f4d --- /dev/null +++ b/node_modules/eventsource/README.md @@ -0,0 +1,91 @@ +# EventSource [![npm version](http://img.shields.io/npm/v/eventsource.svg?style=flat-square)](https://www.npmjs.com/package/eventsource)[![NPM Downloads](https://img.shields.io/npm/dm/eventsource.svg?style=flat-square)](http://npm-stat.com/charts.html?package=eventsource&from=2015-09-01)[![Dependencies](https://img.shields.io/david/EventSource/eventsource.svg?style=flat-square)](https://david-dm.org/EventSource/eventsource) + +![Build](https://github.com/EventSource/eventsource/actions/workflows/build.yml/badge.svg) + +This library is a pure JavaScript implementation of the [EventSource](https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events) client. The API aims to be W3C compatible. + +You can use it with Node.js or as a browser polyfill for +[browsers that don't have native `EventSource` support](http://caniuse.com/#feat=eventsource). + +## Install + + npm install eventsource + +## Example + + npm install + node ./example/sse-server.js + node ./example/sse-client.js # Node.js client + open http://localhost:8080 # Browser client - both native and polyfill + curl http://localhost:8080/sse # Enjoy the simplicity of SSE + +## Browser Polyfill + +Just add `example/eventsource-polyfill.js` file to your web page: + +```html + +``` + +Now you will have two global constructors: + +```javascript +window.EventSourcePolyfill +window.EventSource // Unchanged if browser has defined it. Otherwise, same as window.EventSourcePolyfill +``` + +If you're using [webpack](https://webpack.github.io/) or [browserify](http://browserify.org/) +you can of course build your own. (The `example/eventsource-polyfill.js` is built with webpack). + +## Extensions to the W3C API + +### Setting HTTP request headers + +You can define custom HTTP headers for the initial HTTP request. This can be useful for e.g. sending cookies +or to specify an initial `Last-Event-ID` value. + +HTTP headers are defined by assigning a `headers` attribute to the optional `eventSourceInitDict` argument: + +```javascript +var eventSourceInitDict = {headers: {'Cookie': 'test=test'}}; +var es = new EventSource(url, eventSourceInitDict); +``` + +### Allow unauthorized HTTPS requests + +By default, https requests that cannot be authorized will cause the connection to fail and an exception +to be emitted. You can override this behaviour, along with other https options: + +```javascript +var eventSourceInitDict = {https: {rejectUnauthorized: false}}; +var es = new EventSource(url, eventSourceInitDict); +``` + +Note that for Node.js < v0.10.x this option has no effect - unauthorized HTTPS requests are *always* allowed. + +### HTTP status code on error events + +Unauthorized and redirect error status codes (for example 401, 403, 301, 307) are available in the `status` property in the error event. + +```javascript +es.onerror = function (err) { + if (err) { + if (err.status === 401 || err.status === 403) { + console.log('not authorized'); + } + } +}; +``` + +### HTTP/HTTPS proxy + +You can define a `proxy` option for the HTTP request to be used. This is typically useful if you are behind a corporate firewall. + +```javascript +var es = new EventSource(url, {proxy: 'http://your.proxy.com'}); +``` + + +## License + +MIT-licensed. See LICENSE diff --git a/node_modules/eventsource/example/eventsource-polyfill.js b/node_modules/eventsource/example/eventsource-polyfill.js new file mode 100644 index 000000000..50fda2c4b --- /dev/null +++ b/node_modules/eventsource/example/eventsource-polyfill.js @@ -0,0 +1,9736 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 21); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports) { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports) { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, 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) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) {/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + + + +var base64 = __webpack_require__(23) +var ieee754 = __webpack_require__(24) +var isArray = __webpack_require__(10) + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() + +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +} + +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +} + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that +} + +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 4 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +// 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. + + + +/**/ + +var pna = __webpack_require__(6); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = Object.create(__webpack_require__(5)); +util.inherits = __webpack_require__(2); +/**/ + +var Readable = __webpack_require__(15); +var Writable = __webpack_require__(18); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + 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); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && 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 () { + return this._writableState.highWaterMark; + } +}); + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (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; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); +}; + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(Buffer) {// 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. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3).Buffer)) + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) { + +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1))) + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(3) +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) +} + +// 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) +} + + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +// 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. + + + +var punycode = __webpack_require__(25); +var util = __webpack_require__(27); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = __webpack_require__(28); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +// 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. + + + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; +module.exports.once = once; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + checkListener(listener); + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + checkListener(listener); + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function once(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } + + function resolver() { + if (typeof emitter.removeListener === 'function') { + emitter.removeListener('error', errorListener); + } + resolve([].slice.call(arguments)); + }; + + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== 'error') { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); +} + +function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + } +} + +function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === 'function') { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === 'function') { + // EventTarget does not have `error` event semantics like Node + // EventEmitters, we do not listen for `error` events here. + emitter.addEventListener(name, function wrapListener(arg) { + // IE does not have builtin `{ once: true }` support so we + // have to do it manually. + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } +} + + +/***/ }), +/* 10 */ +/***/ (function(module, exports) { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {var ClientRequest = __webpack_require__(32) +var response = __webpack_require__(13) +var extend = __webpack_require__(41) +var statusCodes = __webpack_require__(42) +var url = __webpack_require__(8) + +var http = exports + +http.request = function (opts, cb) { + if (typeof opts === 'string') + opts = url.parse(opts) + else + opts = extend(opts) + + // Normally, the page is loaded from http or https, so not specifying a protocol + // will result in a (valid) protocol-relative url. However, this won't work if + // the protocol is something else, like 'file:' + var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' + + var protocol = opts.protocol || defaultProtocol + var host = opts.hostname || opts.host + var port = opts.port + var path = opts.path || '/' + + // Necessary for IPv6 addresses + if (host && host.indexOf(':') !== -1) + host = '[' + host + ']' + + // This may be a relative url. The browser should always be able to interpret it correctly. + opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path + opts.method = (opts.method || 'GET').toUpperCase() + opts.headers = opts.headers || {} + + // Also valid opts.auth, opts.mode + + var req = new ClientRequest(opts) + if (cb) + req.on('response', cb) + return req +} + +http.get = function get (opts, cb) { + var req = http.request(opts, cb) + req.end() + return req +} + +http.ClientRequest = ClientRequest +http.IncomingMessage = response.IncomingMessage + +http.Agent = function () {} +http.Agent.defaultMaxSockets = 4 + +http.globalAgent = new http.Agent() + +http.STATUS_CODES = statusCodes + +http.METHODS = [ + 'CHECKOUT', + 'CONNECT', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LOCK', + 'M-SEARCH', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MOVE', + 'NOTIFY', + 'OPTIONS', + 'PATCH', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PURGE', + 'PUT', + 'REPORT', + 'SEARCH', + 'SUBSCRIBE', + 'TRACE', + 'UNLOCK', + 'UNSUBSCRIBE' +] +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream) + +exports.writableStream = isFunction(global.WritableStream) + +exports.abortController = isFunction(global.AbortController) + +exports.blobConstructor = false +try { + new Blob([new ArrayBuffer(1)]) + exports.blobConstructor = true +} catch (e) {} + +// The xhr request to example.com may violate some restrictive CSP configurations, +// so if we're running in a browser that supports `fetch`, avoid calling getXHR() +// and assume support for certain features below. +var xhr +function getXHR () { + // Cache the xhr value + if (xhr !== undefined) return xhr + + if (global.XMLHttpRequest) { + xhr = new global.XMLHttpRequest() + // If XDomainRequest is available (ie only, where xhr might not work + // cross domain), use the page location. Otherwise use example.com + // Note: this doesn't actually make an http request. + try { + xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com') + } catch(e) { + xhr = null + } + } else { + // Service workers don't have XHR + xhr = null + } + return xhr +} + +function checkTypeSupport (type) { + var xhr = getXHR() + if (!xhr) return false + try { + xhr.responseType = type + return xhr.responseType === type + } catch (e) {} + return false +} + +// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'. +// Safari 7.1 appears to have fixed this bug. +var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined' +var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice) + +// If fetch is supported, then arraybuffer will be supported too. Skip calling +// checkTypeSupport(), since that calls getXHR(). +exports.arraybuffer = exports.fetch || (haveArrayBuffer && checkTypeSupport('arraybuffer')) + +// These next two tests unavoidably show warnings in Chrome. Since fetch will always +// be used if it's available, just return false for these to avoid the warnings. +exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream') +exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer && + checkTypeSupport('moz-chunked-arraybuffer') + +// If fetch is supported, then overrideMimeType will be supported too. Skip calling +// getXHR(). +exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false) + +exports.vbArray = isFunction(global.VBArray) + +function isFunction (value) { + return typeof value === 'function' +} + +xhr = null // Help gc + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(process, Buffer, global) {var capability = __webpack_require__(12) +var inherits = __webpack_require__(2) +var stream = __webpack_require__(14) + +var rStates = exports.readyStates = { + UNSENT: 0, + OPENED: 1, + HEADERS_RECEIVED: 2, + LOADING: 3, + DONE: 4 +} + +var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, fetchTimer) { + var self = this + stream.Readable.call(self) + + self._mode = mode + self.headers = {} + self.rawHeaders = [] + self.trailers = {} + self.rawTrailers = [] + + // Fake the 'close' event, but only once 'end' fires + self.on('end', function () { + // The nextTick is necessary to prevent the 'request' module from causing an infinite loop + process.nextTick(function () { + self.emit('close') + }) + }) + + if (mode === 'fetch') { + self._fetchResponse = response + + self.url = response.url + self.statusCode = response.status + self.statusMessage = response.statusText + + response.headers.forEach(function (header, key){ + self.headers[key.toLowerCase()] = header + self.rawHeaders.push(key, header) + }) + + if (capability.writableStream) { + var writable = new WritableStream({ + write: function (chunk) { + return new Promise(function (resolve, reject) { + if (self._destroyed) { + reject() + } else if(self.push(new Buffer(chunk))) { + resolve() + } else { + self._resumeFetch = resolve + } + }) + }, + close: function () { + global.clearTimeout(fetchTimer) + if (!self._destroyed) + self.push(null) + }, + abort: function (err) { + if (!self._destroyed) + self.emit('error', err) + } + }) + + try { + response.body.pipeTo(writable).catch(function (err) { + global.clearTimeout(fetchTimer) + if (!self._destroyed) + self.emit('error', err) + }) + return + } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this + } + // fallback for when writableStream or pipeTo aren't available + var reader = response.body.getReader() + function read () { + reader.read().then(function (result) { + if (self._destroyed) + return + if (result.done) { + global.clearTimeout(fetchTimer) + self.push(null) + return + } + self.push(new Buffer(result.value)) + read() + }).catch(function (err) { + global.clearTimeout(fetchTimer) + if (!self._destroyed) + self.emit('error', err) + }) + } + read() + } else { + self._xhr = xhr + self._pos = 0 + + self.url = xhr.responseURL + self.statusCode = xhr.status + self.statusMessage = xhr.statusText + var headers = xhr.getAllResponseHeaders().split(/\r?\n/) + headers.forEach(function (header) { + var matches = header.match(/^([^:]+):\s*(.*)/) + if (matches) { + var key = matches[1].toLowerCase() + if (key === 'set-cookie') { + if (self.headers[key] === undefined) { + self.headers[key] = [] + } + self.headers[key].push(matches[2]) + } else if (self.headers[key] !== undefined) { + self.headers[key] += ', ' + matches[2] + } else { + self.headers[key] = matches[2] + } + self.rawHeaders.push(matches[1], matches[2]) + } + }) + + self._charset = 'x-user-defined' + if (!capability.overrideMimeType) { + var mimeType = self.rawHeaders['mime-type'] + if (mimeType) { + var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) + if (charsetMatch) { + self._charset = charsetMatch[1].toLowerCase() + } + } + if (!self._charset) + self._charset = 'utf-8' // best guess + } + } +} + +inherits(IncomingMessage, stream.Readable) + +IncomingMessage.prototype._read = function () { + var self = this + + var resolve = self._resumeFetch + if (resolve) { + self._resumeFetch = null + resolve() + } +} + +IncomingMessage.prototype._onXHRProgress = function () { + var self = this + + var xhr = self._xhr + + var response = null + switch (self._mode) { + case 'text:vbarray': // For IE9 + if (xhr.readyState !== rStates.DONE) + break + try { + // This fails in IE8 + response = new global.VBArray(xhr.responseBody).toArray() + } catch (e) {} + if (response !== null) { + self.push(new Buffer(response)) + break + } + // Falls through in IE8 + case 'text': + try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4 + response = xhr.responseText + } catch (e) { + self._mode = 'text:vbarray' + break + } + if (response.length > self._pos) { + var newData = response.substr(self._pos) + if (self._charset === 'x-user-defined') { + var buffer = new Buffer(newData.length) + for (var i = 0; i < newData.length; i++) + buffer[i] = newData.charCodeAt(i) & 0xff + + self.push(buffer) + } else { + self.push(newData, self._charset) + } + self._pos = response.length + } + break + case 'arraybuffer': + if (xhr.readyState !== rStates.DONE || !xhr.response) + break + response = xhr.response + self.push(new Buffer(new Uint8Array(response))) + break + case 'moz-chunked-arraybuffer': // take whole + response = xhr.response + if (xhr.readyState !== rStates.LOADING || !response) + break + self.push(new Buffer(new Uint8Array(response))) + break + case 'ms-stream': + response = xhr.response + if (xhr.readyState !== rStates.LOADING) + break + var reader = new global.MSStreamReader() + reader.onprogress = function () { + if (reader.result.byteLength > self._pos) { + self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))) + self._pos = reader.result.byteLength + } + } + reader.onload = function () { + self.push(null) + } + // reader.onerror = ??? // TODO: this + reader.readAsArrayBuffer(response) + break + } + + // The ms-stream case handles end separately in reader.onload() + if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { + self.push(null) + } +} + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3).Buffer, __webpack_require__(0))) + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + +exports = module.exports = __webpack_require__(15); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = __webpack_require__(18); +exports.Duplex = __webpack_require__(4); +exports.Transform = __webpack_require__(20); +exports.PassThrough = __webpack_require__(39); + + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global, process) {// 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. + + + +/**/ + +var pna = __webpack_require__(6); +/**/ + +module.exports = Readable; + +/**/ +var isArray = __webpack_require__(10); +/**/ + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = __webpack_require__(9).EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = __webpack_require__(16); +/**/ + +/**/ + +var Buffer = __webpack_require__(7).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +/**/ +var util = Object.create(__webpack_require__(5)); +util.inherits = __webpack_require__(2); +/**/ + +/**/ +var debugUtil = __webpack_require__(33); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = __webpack_require__(34); +var destroyImpl = __webpack_require__(17); +var StringDecoder; + +util.inherits(Readable, Stream); + +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 (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream) { + Duplex = Duplex || __webpack_require__(4); + + 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. + var 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" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // 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; + + // 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 = __webpack_require__(19).StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || __webpack_require__(4); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // 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', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (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) { + this.push(null); + 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) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', 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) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } 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; + } + } + + return needMoreData(state); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } 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 TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +// if it's past the high water mark, we can push in some more. +// 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. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = __webpack_require__(19).StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + 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.length >= state.highWaterMark || 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 = true; + n = 0; + } else { + state.length -= n; + } + + 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) { + 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; + + // emit 'readable' now to make sure it gets picked up. + 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; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + 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; + pna.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + 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) { + this.emit('error', new Error('_read() is not implemented')); +}; + +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) pna.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(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // 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', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + 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) dest.emit('error', 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 () { + 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, unpipeInfo); + }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); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +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'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + 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 (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + 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 (method) { + return function () { + 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; +}; + +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 () { + return this._readableState.highWaterMark; + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// 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.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.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) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.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) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0), __webpack_require__(1))) + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = __webpack_require__(9).EventEmitter; + + +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/**/ + +var pna = __webpack_require__(6); +/**/ + +// 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 && (!this._writableState || !this._writableState.errorEmitted)) { + pna.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) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); + + return this; +} + +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.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process, setImmediate, global) {// 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. + + + +/**/ + +var pna = __webpack_require__(6); +/**/ + +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 asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = Object.create(__webpack_require__(5)); +util.inherits = __webpack_require__(2); +/**/ + +/**/ +var internalUtil = { + deprecate: __webpack_require__(38) +}; +/**/ + +/**/ +var Stream = __webpack_require__(16); +/**/ + +/**/ + +var Buffer = __webpack_require__(7).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +var destroyImpl = __webpack_require__(17); + +util.inherits(Writable, Stream); + +function nop() {} + +function WritableState(options, stream) { + Duplex = Duplex || __webpack_require__(4); + + 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. + var 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() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // 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; + + // 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 () { + 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 (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || __webpack_require__(4); + + // 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. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // 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 () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.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 valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; +} + +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.ended) 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 () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !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 TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +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 () { + 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 (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 + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', 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; + + 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); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(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 Error('_write() is not implemented')); +}; + +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 && !state.finished) endWritable(this, state, cb); +}; + +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) { + stream.emit('error', 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.pendingcb++; + state.finalCalled = true; + pna.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'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.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; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (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) { + this.end(); + cb(err); +}; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(36).setImmediate, __webpack_require__(0))) + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +// 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. + + + +/**/ + +var Buffer = __webpack_require__(7).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) : ''; +} + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +// 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. + + + +module.exports = Transform; + +var Duplex = __webpack_require__(4); + +/**/ +var util = Object.create(__webpack_require__(5)); +util.inherits = __webpack_require__(2); +/**/ + +util.inherits(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + 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._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) { + throw new Error('_transform() is not implemented'); +}; + +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.writecb && !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) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; + +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); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +/***/ }), +/* 21 */ +/***/ (function(module, exports, __webpack_require__) { + +var EventSource = __webpack_require__(22) + +if (typeof window === 'object') { + window.EventSourcePolyfill = EventSource + if (!window.EventSource) window.EventSource = EventSource + module.exports = window.EventSource +} else { + module.exports = EventSource +} + + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(process, Buffer) {var parse = __webpack_require__(8).parse +var events = __webpack_require__(9) +var https = __webpack_require__(31) +var http = __webpack_require__(11) +var util = __webpack_require__(43) + +var httpsOptions = [ + 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers', + 'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity' +] + +var bom = [239, 187, 191] +var colon = 58 +var space = 32 +var lineFeed = 10 +var carriageReturn = 13 +// Beyond 256KB we could not observe any gain in performance +var maxBufferAheadAllocation = 1024 * 256 +// Headers matching the pattern should be removed when redirecting to different origin +var reUnsafeHeader = /^(cookie|authorization)$/i + +function hasBom (buf) { + return bom.every(function (charCode, index) { + return buf[index] === charCode + }) +} + +/** + * Creates a new EventSource object + * + * @param {String} url the URL to which to connect + * @param {Object} [eventSourceInitDict] extra init params. See README for details. + * @api public + **/ +function EventSource (url, eventSourceInitDict) { + var readyState = EventSource.CONNECTING + var headers = eventSourceInitDict && eventSourceInitDict.headers + var hasNewOrigin = false + Object.defineProperty(this, 'readyState', { + get: function () { + return readyState + } + }) + + Object.defineProperty(this, 'url', { + get: function () { + return url + } + }) + + var self = this + self.reconnectInterval = 1000 + self.connectionInProgress = false + + function onConnectionClosed (message) { + if (readyState === EventSource.CLOSED) return + readyState = EventSource.CONNECTING + _emit('error', new Event('error', {message: message})) + + // The url may have been changed by a temporary redirect. If that's the case, + // revert it now, and flag that we are no longer pointing to a new origin + if (reconnectUrl) { + url = reconnectUrl + reconnectUrl = null + hasNewOrigin = false + } + setTimeout(function () { + if (readyState !== EventSource.CONNECTING || self.connectionInProgress) { + return + } + self.connectionInProgress = true + connect() + }, self.reconnectInterval) + } + + var req + var lastEventId = '' + if (headers && headers['Last-Event-ID']) { + lastEventId = headers['Last-Event-ID'] + delete headers['Last-Event-ID'] + } + + var discardTrailingNewline = false + var data = '' + var eventName = '' + + var reconnectUrl = null + + function connect () { + var options = parse(url) + var isSecure = options.protocol === 'https:' + options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' } + if (lastEventId) options.headers['Last-Event-ID'] = lastEventId + if (headers) { + var reqHeaders = hasNewOrigin ? removeUnsafeHeaders(headers) : headers + for (var i in reqHeaders) { + var header = reqHeaders[i] + if (header) { + options.headers[i] = header + } + } + } + + // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`, + // but for now exists as a backwards-compatibility layer + options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized) + + if (eventSourceInitDict && eventSourceInitDict.createConnection !== undefined) { + options.createConnection = eventSourceInitDict.createConnection + } + + // If specify http proxy, make the request to sent to the proxy server, + // and include the original url in path and Host headers + var useProxy = eventSourceInitDict && eventSourceInitDict.proxy + if (useProxy) { + var proxy = parse(eventSourceInitDict.proxy) + isSecure = proxy.protocol === 'https:' + + options.protocol = isSecure ? 'https:' : 'http:' + options.path = url + options.headers.Host = options.host + options.hostname = proxy.hostname + options.host = proxy.host + options.port = proxy.port + } + + // If https options are specified, merge them into the request options + if (eventSourceInitDict && eventSourceInitDict.https) { + for (var optName in eventSourceInitDict.https) { + if (httpsOptions.indexOf(optName) === -1) { + continue + } + + var option = eventSourceInitDict.https[optName] + if (option !== undefined) { + options[optName] = option + } + } + } + + // Pass this on to the XHR + if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) { + options.withCredentials = eventSourceInitDict.withCredentials + } + + req = (isSecure ? https : http).request(options, function (res) { + self.connectionInProgress = false + // Handle HTTP errors + if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) { + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + onConnectionClosed() + return + } + + // Handle HTTP redirects + if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) { + var location = res.headers.location + if (!location) { + // Server sent redirect response without Location header. + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + return + } + var prevOrigin = new URL(url).origin + var nextOrigin = new URL(location).origin + hasNewOrigin = prevOrigin !== nextOrigin + if (res.statusCode === 307) reconnectUrl = url + url = location + process.nextTick(connect) + return + } + + if (res.statusCode !== 200) { + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + return self.close() + } + + readyState = EventSource.OPEN + res.on('close', function () { + res.removeAllListeners('close') + res.removeAllListeners('end') + onConnectionClosed() + }) + + res.on('end', function () { + res.removeAllListeners('close') + res.removeAllListeners('end') + onConnectionClosed() + }) + _emit('open', new Event('open')) + + // text/event-stream parser adapted from webkit's + // Source/WebCore/page/EventSource.cpp + var buf + var newBuffer + var startingPos = 0 + var startingFieldLength = -1 + var newBufferSize = 0 + var bytesUsed = 0 + + res.on('data', function (chunk) { + if (!buf) { + buf = chunk + if (hasBom(buf)) { + buf = buf.slice(bom.length) + } + bytesUsed = buf.length + } else { + if (chunk.length > buf.length - bytesUsed) { + newBufferSize = (buf.length * 2) + chunk.length + if (newBufferSize > maxBufferAheadAllocation) { + newBufferSize = buf.length + chunk.length + maxBufferAheadAllocation + } + newBuffer = Buffer.alloc(newBufferSize) + buf.copy(newBuffer, 0, 0, bytesUsed) + buf = newBuffer + } + chunk.copy(buf, bytesUsed) + bytesUsed += chunk.length + } + + var pos = 0 + var length = bytesUsed + + while (pos < length) { + if (discardTrailingNewline) { + if (buf[pos] === lineFeed) { + ++pos + } + discardTrailingNewline = false + } + + var lineLength = -1 + var fieldLength = startingFieldLength + var c + + for (var i = startingPos; lineLength < 0 && i < length; ++i) { + c = buf[i] + if (c === colon) { + if (fieldLength < 0) { + fieldLength = i - pos + } + } else if (c === carriageReturn) { + discardTrailingNewline = true + lineLength = i - pos + } else if (c === lineFeed) { + lineLength = i - pos + } + } + + if (lineLength < 0) { + startingPos = length - pos + startingFieldLength = fieldLength + break + } else { + startingPos = 0 + startingFieldLength = -1 + } + + parseEventStreamLine(buf, pos, fieldLength, lineLength) + + pos += lineLength + 1 + } + + if (pos === length) { + buf = void 0 + bytesUsed = 0 + } else if (pos > 0) { + buf = buf.slice(pos, bytesUsed) + bytesUsed = buf.length + } + }) + }) + + req.on('error', function (err) { + self.connectionInProgress = false + onConnectionClosed(err.message) + }) + + if (req.setNoDelay) req.setNoDelay(true) + req.end() + } + + connect() + + function _emit () { + if (self.listeners(arguments[0]).length > 0) { + self.emit.apply(self, arguments) + } + } + + this._close = function () { + if (readyState === EventSource.CLOSED) return + readyState = EventSource.CLOSED + if (req.abort) req.abort() + if (req.xhr && req.xhr.abort) req.xhr.abort() + } + + function parseEventStreamLine (buf, pos, fieldLength, lineLength) { + if (lineLength === 0) { + if (data.length > 0) { + var type = eventName || 'message' + _emit(type, new MessageEvent(type, { + data: data.slice(0, -1), // remove trailing newline + lastEventId: lastEventId, + origin: new URL(url).origin + })) + data = '' + } + eventName = void 0 + } else if (fieldLength > 0) { + var noValue = fieldLength < 0 + var step = 0 + var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString() + + if (noValue) { + step = lineLength + } else if (buf[pos + fieldLength + 1] !== space) { + step = fieldLength + 1 + } else { + step = fieldLength + 2 + } + pos += step + + var valueLength = lineLength - step + var value = buf.slice(pos, pos + valueLength).toString() + + if (field === 'data') { + data += value + '\n' + } else if (field === 'event') { + eventName = value + } else if (field === 'id') { + lastEventId = value + } else if (field === 'retry') { + var retry = parseInt(value, 10) + if (!Number.isNaN(retry)) { + self.reconnectInterval = retry + } + } + } + } +} + +module.exports = EventSource + +util.inherits(EventSource, events.EventEmitter) +EventSource.prototype.constructor = EventSource; // make stacktraces readable + +['open', 'error', 'message'].forEach(function (method) { + Object.defineProperty(EventSource.prototype, 'on' + method, { + /** + * Returns the current listener + * + * @return {Mixed} the set function or undefined + * @api private + */ + get: function get () { + var listener = this.listeners(method)[0] + return listener ? (listener._listener ? listener._listener : listener) : undefined + }, + + /** + * Start listening for events + * + * @param {Function} listener the listener + * @return {Mixed} the set function or undefined + * @api private + */ + set: function set (listener) { + this.removeAllListeners(method) + this.addEventListener(method, listener) + } + }) +}) + +/** + * Ready states + */ +Object.defineProperty(EventSource, 'CONNECTING', {enumerable: true, value: 0}) +Object.defineProperty(EventSource, 'OPEN', {enumerable: true, value: 1}) +Object.defineProperty(EventSource, 'CLOSED', {enumerable: true, value: 2}) + +EventSource.prototype.CONNECTING = 0 +EventSource.prototype.OPEN = 1 +EventSource.prototype.CLOSED = 2 + +/** + * Closes the connection, if one is made, and sets the readyState attribute to 2 (closed) + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close + * @api public + */ +EventSource.prototype.close = function () { + this._close() +} + +/** + * Emulates the W3C Browser based WebSocket interface using addEventListener. + * + * @param {String} type A string representing the event type to listen out for + * @param {Function} listener callback + * @see https://developer.mozilla.org/en/DOM/element.addEventListener + * @see http://dev.w3.org/html5/websockets/#the-websocket-interface + * @api public + */ +EventSource.prototype.addEventListener = function addEventListener (type, listener) { + if (typeof listener === 'function') { + // store a reference so we can return the original function again + listener._listener = listener + this.on(type, listener) + } +} + +/** + * Emulates the W3C Browser based WebSocket interface using dispatchEvent. + * + * @param {Event} event An event to be dispatched + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent + * @api public + */ +EventSource.prototype.dispatchEvent = function dispatchEvent (event) { + if (!event.type) { + throw new Error('UNSPECIFIED_EVENT_TYPE_ERR') + } + // if event is instance of an CustomEvent (or has 'details' property), + // send the detail object as the payload for the event + this.emit(event.type, event.detail) +} + +/** + * Emulates the W3C Browser based WebSocket interface using removeEventListener. + * + * @param {String} type A string representing the event type to remove + * @param {Function} listener callback + * @see https://developer.mozilla.org/en/DOM/element.removeEventListener + * @see http://dev.w3.org/html5/websockets/#the-websocket-interface + * @api public + */ +EventSource.prototype.removeEventListener = function removeEventListener (type, listener) { + if (typeof listener === 'function') { + listener._listener = undefined + this.removeListener(type, listener) + } +} + +/** + * W3C Event + * + * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event + * @api private + */ +function Event (type, optionalProperties) { + Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) + if (optionalProperties) { + for (var f in optionalProperties) { + if (optionalProperties.hasOwnProperty(f)) { + Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true }) + } + } + } +} + +/** + * W3C MessageEvent + * + * @see http://www.w3.org/TR/webmessaging/#event-definitions + * @api private + */ +function MessageEvent (type, eventInitDict) { + Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) + for (var f in eventInitDict) { + if (eventInitDict.hasOwnProperty(f)) { + Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true }) + } + } +} + +/** + * Returns a new object of headers that does not include any authorization and cookie headers + * + * @param {Object} headers An object of headers ({[headerName]: headerValue}) + * @return {Object} a new object of headers + * @api private + */ +function removeUnsafeHeaders (headers) { + var safe = {} + for (var key in headers) { + if (reUnsafeHeader.test(key)) { + continue + } + + safe[key] = headers[key] + } + + return safe +} + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3).Buffer)) + +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + + +/***/ }), +/* 24 */ +/***/ (function(module, exports) { + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + true + ) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { + return punycode; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(26)(module), __webpack_require__(0))) + +/***/ }), +/* 26 */ +/***/ (function(module, exports) { + +module.exports = function(module) { + if(!module.webpackPolyfill) { + module.deprecate = function() {}; + module.paths = []; + // module.parent = undefined by default + if(!module.children) module.children = []; + Object.defineProperty(module, "loaded", { + enumerable: true, + get: function() { + return module.l; + } + }); + Object.defineProperty(module, "id", { + enumerable: true, + get: function() { + return module.i; + } + }); + module.webpackPolyfill = 1; + } + return module; +}; + + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + + +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.decode = exports.parse = __webpack_require__(29); +exports.encode = exports.stringify = __webpack_require__(30); + + +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +// 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. + + + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +// 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. + + + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + +var http = __webpack_require__(11) +var url = __webpack_require__(8) + +var https = module.exports + +for (var key in http) { + if (http.hasOwnProperty(key)) https[key] = http[key] +} + +https.request = function (params, cb) { + params = validateParams(params) + return http.request.call(this, params, cb) +} + +https.get = function (params, cb) { + params = validateParams(params) + return http.get.call(this, params, cb) +} + +function validateParams (params) { + if (typeof params === 'string') { + params = url.parse(params) + } + if (!params.protocol) { + params.protocol = 'https:' + } + if (params.protocol !== 'https:') { + throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"') + } + return params +} + + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(Buffer, global, process) {var capability = __webpack_require__(12) +var inherits = __webpack_require__(2) +var response = __webpack_require__(13) +var stream = __webpack_require__(14) +var toArrayBuffer = __webpack_require__(40) + +var IncomingMessage = response.IncomingMessage +var rStates = response.readyStates + +function decideMode (preferBinary, useFetch) { + if (capability.fetch && useFetch) { + return 'fetch' + } else if (capability.mozchunkedarraybuffer) { + return 'moz-chunked-arraybuffer' + } else if (capability.msstream) { + return 'ms-stream' + } else if (capability.arraybuffer && preferBinary) { + return 'arraybuffer' + } else if (capability.vbArray && preferBinary) { + return 'text:vbarray' + } else { + return 'text' + } +} + +var ClientRequest = module.exports = function (opts) { + var self = this + stream.Writable.call(self) + + self._opts = opts + self._body = [] + self._headers = {} + if (opts.auth) + self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64')) + Object.keys(opts.headers).forEach(function (name) { + self.setHeader(name, opts.headers[name]) + }) + + var preferBinary + var useFetch = true + if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) { + // If the use of XHR should be preferred. Not typically needed. + useFetch = false + preferBinary = true + } else if (opts.mode === 'prefer-streaming') { + // If streaming is a high priority but binary compatibility and + // the accuracy of the 'content-type' header aren't + preferBinary = false + } else if (opts.mode === 'allow-wrong-content-type') { + // If streaming is more important than preserving the 'content-type' header + preferBinary = !capability.overrideMimeType + } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { + // Use binary if text streaming may corrupt data or the content-type header, or for speed + preferBinary = true + } else { + throw new Error('Invalid value for opts.mode') + } + self._mode = decideMode(preferBinary, useFetch) + self._fetchTimer = null + + self.on('finish', function () { + self._onFinish() + }) +} + +inherits(ClientRequest, stream.Writable) + +ClientRequest.prototype.setHeader = function (name, value) { + var self = this + var lowerName = name.toLowerCase() + // This check is not necessary, but it prevents warnings from browsers about setting unsafe + // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but + // http-browserify did it, so I will too. + if (unsafeHeaders.indexOf(lowerName) !== -1) + return + + self._headers[lowerName] = { + name: name, + value: value + } +} + +ClientRequest.prototype.getHeader = function (name) { + var header = this._headers[name.toLowerCase()] + if (header) + return header.value + return null +} + +ClientRequest.prototype.removeHeader = function (name) { + var self = this + delete self._headers[name.toLowerCase()] +} + +ClientRequest.prototype._onFinish = function () { + var self = this + + if (self._destroyed) + return + var opts = self._opts + + var headersObj = self._headers + var body = null + if (opts.method !== 'GET' && opts.method !== 'HEAD') { + if (capability.arraybuffer) { + body = toArrayBuffer(Buffer.concat(self._body)) + } else if (capability.blobConstructor) { + body = new global.Blob(self._body.map(function (buffer) { + return toArrayBuffer(buffer) + }), { + type: (headersObj['content-type'] || {}).value || '' + }) + } else { + // get utf8 string + body = Buffer.concat(self._body).toString() + } + } + + // create flattened list of headers + var headersList = [] + Object.keys(headersObj).forEach(function (keyName) { + var name = headersObj[keyName].name + var value = headersObj[keyName].value + if (Array.isArray(value)) { + value.forEach(function (v) { + headersList.push([name, v]) + }) + } else { + headersList.push([name, value]) + } + }) + + if (self._mode === 'fetch') { + var signal = null + var fetchTimer = null + if (capability.abortController) { + var controller = new AbortController() + signal = controller.signal + self._fetchAbortController = controller + + if ('requestTimeout' in opts && opts.requestTimeout !== 0) { + self._fetchTimer = global.setTimeout(function () { + self.emit('requestTimeout') + if (self._fetchAbortController) + self._fetchAbortController.abort() + }, opts.requestTimeout) + } + } + + global.fetch(self._opts.url, { + method: self._opts.method, + headers: headersList, + body: body || undefined, + mode: 'cors', + credentials: opts.withCredentials ? 'include' : 'same-origin', + signal: signal + }).then(function (response) { + self._fetchResponse = response + self._connect() + }, function (reason) { + global.clearTimeout(self._fetchTimer) + if (!self._destroyed) + self.emit('error', reason) + }) + } else { + var xhr = self._xhr = new global.XMLHttpRequest() + try { + xhr.open(self._opts.method, self._opts.url, true) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + + // Can't set responseType on really old browsers + if ('responseType' in xhr) + xhr.responseType = self._mode.split(':')[0] + + if ('withCredentials' in xhr) + xhr.withCredentials = !!opts.withCredentials + + if (self._mode === 'text' && 'overrideMimeType' in xhr) + xhr.overrideMimeType('text/plain; charset=x-user-defined') + + if ('requestTimeout' in opts) { + xhr.timeout = opts.requestTimeout + xhr.ontimeout = function () { + self.emit('requestTimeout') + } + } + + headersList.forEach(function (header) { + xhr.setRequestHeader(header[0], header[1]) + }) + + self._response = null + xhr.onreadystatechange = function () { + switch (xhr.readyState) { + case rStates.LOADING: + case rStates.DONE: + self._onXHRProgress() + break + } + } + // Necessary for streaming in Firefox, since xhr.response is ONLY defined + // in onprogress, not in onreadystatechange with xhr.readyState = 3 + if (self._mode === 'moz-chunked-arraybuffer') { + xhr.onprogress = function () { + self._onXHRProgress() + } + } + + xhr.onerror = function () { + if (self._destroyed) + return + self.emit('error', new Error('XHR error')) + } + + try { + xhr.send(body) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + } +} + +/** + * Checks if xhr.status is readable and non-zero, indicating no error. + * Even though the spec says it should be available in readyState 3, + * accessing it throws an exception in IE8 + */ +function statusValid (xhr) { + try { + var status = xhr.status + return (status !== null && status !== 0) + } catch (e) { + return false + } +} + +ClientRequest.prototype._onXHRProgress = function () { + var self = this + + if (!statusValid(self._xhr) || self._destroyed) + return + + if (!self._response) + self._connect() + + self._response._onXHRProgress() +} + +ClientRequest.prototype._connect = function () { + var self = this + + if (self._destroyed) + return + + self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._fetchTimer) + self._response.on('error', function(err) { + self.emit('error', err) + }) + + self.emit('response', self._response) +} + +ClientRequest.prototype._write = function (chunk, encoding, cb) { + var self = this + + self._body.push(chunk) + cb() +} + +ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () { + var self = this + self._destroyed = true + global.clearTimeout(self._fetchTimer) + if (self._response) + self._response._destroyed = true + if (self._xhr) + self._xhr.abort() + else if (self._fetchAbortController) + self._fetchAbortController.abort() +} + +ClientRequest.prototype.end = function (data, encoding, cb) { + var self = this + if (typeof data === 'function') { + cb = data + data = undefined + } + + stream.Writable.prototype.end.call(self, data, encoding, cb) +} + +ClientRequest.prototype.flushHeaders = function () {} +ClientRequest.prototype.setTimeout = function () {} +ClientRequest.prototype.setNoDelay = function () {} +ClientRequest.prototype.setSocketKeepAlive = function () {} + +// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method +var unsafeHeaders = [ + 'accept-charset', + 'accept-encoding', + 'access-control-request-headers', + 'access-control-request-method', + 'connection', + 'content-length', + 'cookie', + 'cookie2', + 'date', + 'dnt', + 'expect', + 'host', + 'keep-alive', + 'origin', + 'referer', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'via' +] + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3).Buffer, __webpack_require__(0), __webpack_require__(1))) + +/***/ }), +/* 33 */ +/***/ (function(module, exports) { + +/* (ignored) */ + +/***/ }), +/* 34 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = __webpack_require__(7).Buffer; +var util = __webpack_require__(35); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = 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; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = 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; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = 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; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + 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; + }; + + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} + +/***/ }), +/* 35 */ +/***/ (function(module, exports) { + +/* (ignored) */ + +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) || + (typeof self !== "undefined" && self) || + window; +var apply = Function.prototype.apply; + +// DOM APIs, for completeness + +exports.setTimeout = function() { + return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout); +}; +exports.setInterval = function() { + return new Timeout(apply.call(setInterval, scope, arguments), clearInterval); +}; +exports.clearTimeout = +exports.clearInterval = function(timeout) { + if (timeout) { + timeout.close(); + } +}; + +function Timeout(id, clearFn) { + this._id = id; + this._clearFn = clearFn; +} +Timeout.prototype.unref = Timeout.prototype.ref = function() {}; +Timeout.prototype.close = function() { + this._clearFn.call(scope, this._id); +}; + +// Does not start the time, just sets up the members needed. +exports.enroll = function(item, msecs) { + clearTimeout(item._idleTimeoutId); + item._idleTimeout = msecs; +}; + +exports.unenroll = function(item) { + clearTimeout(item._idleTimeoutId); + item._idleTimeout = -1; +}; + +exports._unrefActive = exports.active = function(item) { + clearTimeout(item._idleTimeoutId); + + var msecs = item._idleTimeout; + if (msecs >= 0) { + item._idleTimeoutId = setTimeout(function onTimeout() { + if (item._onTimeout) + item._onTimeout(); + }, msecs); + } +}; + +// setimmediate attaches itself to the global object +__webpack_require__(37); +// On some exotic environments, it's not clear which object `setimmediate` was +// able to install onto. Search each possibility in the same order as the +// `setimmediate` library. +exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) || + (typeof global !== "undefined" && global.setImmediate) || + (this && this.setImmediate); +exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) || + (typeof global !== "undefined" && global.clearImmediate) || + (this && this.clearImmediate); + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { + "use strict"; + + if (global.setImmediate) { + return; + } + + var nextHandle = 1; // Spec says greater than zero + var tasksByHandle = {}; + var currentlyRunningATask = false; + var doc = global.document; + var registerImmediate; + + function setImmediate(callback) { + // Callback can either be a function or a string + if (typeof callback !== "function") { + callback = new Function("" + callback); + } + // Copy function arguments + var args = new Array(arguments.length - 1); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i + 1]; + } + // Store and register the task + var task = { callback: callback, args: args }; + tasksByHandle[nextHandle] = task; + registerImmediate(nextHandle); + return nextHandle++; + } + + function clearImmediate(handle) { + delete tasksByHandle[handle]; + } + + function run(task) { + var callback = task.callback; + var args = task.args; + switch (args.length) { + case 0: + callback(); + break; + case 1: + callback(args[0]); + break; + case 2: + callback(args[0], args[1]); + break; + case 3: + callback(args[0], args[1], args[2]); + break; + default: + callback.apply(undefined, args); + break; + } + } + + function runIfPresent(handle) { + // From the spec: "Wait until any invocations of this algorithm started before this one have completed." + // So if we're currently running a task, we'll need to delay this invocation. + if (currentlyRunningATask) { + // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a + // "too much recursion" error. + setTimeout(runIfPresent, 0, handle); + } else { + var task = tasksByHandle[handle]; + if (task) { + currentlyRunningATask = true; + try { + run(task); + } finally { + clearImmediate(handle); + currentlyRunningATask = false; + } + } + } + } + + function installNextTickImplementation() { + registerImmediate = function(handle) { + process.nextTick(function () { runIfPresent(handle); }); + }; + } + + function canUsePostMessage() { + // The test against `importScripts` prevents this implementation from being installed inside a web worker, + // where `global.postMessage` means something completely different and can't be used for this purpose. + if (global.postMessage && !global.importScripts) { + var postMessageIsAsynchronous = true; + var oldOnMessage = global.onmessage; + global.onmessage = function() { + postMessageIsAsynchronous = false; + }; + global.postMessage("", "*"); + global.onmessage = oldOnMessage; + return postMessageIsAsynchronous; + } + } + + function installPostMessageImplementation() { + // Installs an event handler on `global` for the `message` event: see + // * https://developer.mozilla.org/en/DOM/window.postMessage + // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages + + var messagePrefix = "setImmediate$" + Math.random() + "$"; + var onGlobalMessage = function(event) { + if (event.source === global && + typeof event.data === "string" && + event.data.indexOf(messagePrefix) === 0) { + runIfPresent(+event.data.slice(messagePrefix.length)); + } + }; + + if (global.addEventListener) { + global.addEventListener("message", onGlobalMessage, false); + } else { + global.attachEvent("onmessage", onGlobalMessage); + } + + registerImmediate = function(handle) { + global.postMessage(messagePrefix + handle, "*"); + }; + } + + function installMessageChannelImplementation() { + var channel = new MessageChannel(); + channel.port1.onmessage = function(event) { + var handle = event.data; + runIfPresent(handle); + }; + + registerImmediate = function(handle) { + channel.port2.postMessage(handle); + }; + } + + function installReadyStateChangeImplementation() { + var html = doc.documentElement; + registerImmediate = function(handle) { + // Create a + + + diff --git a/node_modules/eventsource/example/sse-client.js b/node_modules/eventsource/example/sse-client.js new file mode 100644 index 000000000..72c49a912 --- /dev/null +++ b/node_modules/eventsource/example/sse-client.js @@ -0,0 +1,5 @@ +var EventSource = require('..') +var es = new EventSource('http://localhost:8080/sse') +es.addEventListener('server-time', function (e) { + console.log(e.data) +}) diff --git a/node_modules/eventsource/example/sse-server.js b/node_modules/eventsource/example/sse-server.js new file mode 100644 index 000000000..034e3b46f --- /dev/null +++ b/node_modules/eventsource/example/sse-server.js @@ -0,0 +1,29 @@ +const express = require('express') +const serveStatic = require('serve-static') +const SseStream = require('ssestream') + +const app = express() +app.use(serveStatic(__dirname)) +app.get('/sse', (req, res) => { + console.log('new connection') + + const sseStream = new SseStream(req) + sseStream.pipe(res) + const pusher = setInterval(() => { + sseStream.write({ + event: 'server-time', + data: new Date().toTimeString() + }) + }, 1000) + + res.on('close', () => { + console.log('lost connection') + clearInterval(pusher) + sseStream.unpipe(res) + }) +}) + +app.listen(8080, (err) => { + if (err) throw err + console.log('server ready on http://localhost:8080') +}) diff --git a/node_modules/eventsource/lib/eventsource-polyfill.js b/node_modules/eventsource/lib/eventsource-polyfill.js new file mode 100644 index 000000000..6ed439681 --- /dev/null +++ b/node_modules/eventsource/lib/eventsource-polyfill.js @@ -0,0 +1,9 @@ +var EventSource = require('./eventsource') + +if (typeof window === 'object') { + window.EventSourcePolyfill = EventSource + if (!window.EventSource) window.EventSource = EventSource + module.exports = window.EventSource +} else { + module.exports = EventSource +} diff --git a/node_modules/eventsource/lib/eventsource.js b/node_modules/eventsource/lib/eventsource.js new file mode 100644 index 000000000..bd401a106 --- /dev/null +++ b/node_modules/eventsource/lib/eventsource.js @@ -0,0 +1,495 @@ +var parse = require('url').parse +var events = require('events') +var https = require('https') +var http = require('http') +var util = require('util') + +var httpsOptions = [ + 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers', + 'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity' +] + +var bom = [239, 187, 191] +var colon = 58 +var space = 32 +var lineFeed = 10 +var carriageReturn = 13 +// Beyond 256KB we could not observe any gain in performance +var maxBufferAheadAllocation = 1024 * 256 +// Headers matching the pattern should be removed when redirecting to different origin +var reUnsafeHeader = /^(cookie|authorization)$/i + +function hasBom (buf) { + return bom.every(function (charCode, index) { + return buf[index] === charCode + }) +} + +/** + * Creates a new EventSource object + * + * @param {String} url the URL to which to connect + * @param {Object} [eventSourceInitDict] extra init params. See README for details. + * @api public + **/ +function EventSource (url, eventSourceInitDict) { + var readyState = EventSource.CONNECTING + var headers = eventSourceInitDict && eventSourceInitDict.headers + var hasNewOrigin = false + Object.defineProperty(this, 'readyState', { + get: function () { + return readyState + } + }) + + Object.defineProperty(this, 'url', { + get: function () { + return url + } + }) + + var self = this + self.reconnectInterval = 1000 + self.connectionInProgress = false + + function onConnectionClosed (message) { + if (readyState === EventSource.CLOSED) return + readyState = EventSource.CONNECTING + _emit('error', new Event('error', {message: message})) + + // The url may have been changed by a temporary redirect. If that's the case, + // revert it now, and flag that we are no longer pointing to a new origin + if (reconnectUrl) { + url = reconnectUrl + reconnectUrl = null + hasNewOrigin = false + } + setTimeout(function () { + if (readyState !== EventSource.CONNECTING || self.connectionInProgress) { + return + } + self.connectionInProgress = true + connect() + }, self.reconnectInterval) + } + + var req + var lastEventId = '' + if (headers && headers['Last-Event-ID']) { + lastEventId = headers['Last-Event-ID'] + delete headers['Last-Event-ID'] + } + + var discardTrailingNewline = false + var data = '' + var eventName = '' + + var reconnectUrl = null + + function connect () { + var options = parse(url) + var isSecure = options.protocol === 'https:' + options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' } + if (lastEventId) options.headers['Last-Event-ID'] = lastEventId + if (headers) { + var reqHeaders = hasNewOrigin ? removeUnsafeHeaders(headers) : headers + for (var i in reqHeaders) { + var header = reqHeaders[i] + if (header) { + options.headers[i] = header + } + } + } + + // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`, + // but for now exists as a backwards-compatibility layer + options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized) + + if (eventSourceInitDict && eventSourceInitDict.createConnection !== undefined) { + options.createConnection = eventSourceInitDict.createConnection + } + + // If specify http proxy, make the request to sent to the proxy server, + // and include the original url in path and Host headers + var useProxy = eventSourceInitDict && eventSourceInitDict.proxy + if (useProxy) { + var proxy = parse(eventSourceInitDict.proxy) + isSecure = proxy.protocol === 'https:' + + options.protocol = isSecure ? 'https:' : 'http:' + options.path = url + options.headers.Host = options.host + options.hostname = proxy.hostname + options.host = proxy.host + options.port = proxy.port + } + + // If https options are specified, merge them into the request options + if (eventSourceInitDict && eventSourceInitDict.https) { + for (var optName in eventSourceInitDict.https) { + if (httpsOptions.indexOf(optName) === -1) { + continue + } + + var option = eventSourceInitDict.https[optName] + if (option !== undefined) { + options[optName] = option + } + } + } + + // Pass this on to the XHR + if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) { + options.withCredentials = eventSourceInitDict.withCredentials + } + + req = (isSecure ? https : http).request(options, function (res) { + self.connectionInProgress = false + // Handle HTTP errors + if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) { + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + onConnectionClosed() + return + } + + // Handle HTTP redirects + if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) { + var location = res.headers.location + if (!location) { + // Server sent redirect response without Location header. + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + return + } + var prevOrigin = new URL(url).origin + var nextOrigin = new URL(location).origin + hasNewOrigin = prevOrigin !== nextOrigin + if (res.statusCode === 307) reconnectUrl = url + url = location + process.nextTick(connect) + return + } + + if (res.statusCode !== 200) { + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + return self.close() + } + + readyState = EventSource.OPEN + res.on('close', function () { + res.removeAllListeners('close') + res.removeAllListeners('end') + onConnectionClosed() + }) + + res.on('end', function () { + res.removeAllListeners('close') + res.removeAllListeners('end') + onConnectionClosed() + }) + _emit('open', new Event('open')) + + // text/event-stream parser adapted from webkit's + // Source/WebCore/page/EventSource.cpp + var buf + var newBuffer + var startingPos = 0 + var startingFieldLength = -1 + var newBufferSize = 0 + var bytesUsed = 0 + + res.on('data', function (chunk) { + if (!buf) { + buf = chunk + if (hasBom(buf)) { + buf = buf.slice(bom.length) + } + bytesUsed = buf.length + } else { + if (chunk.length > buf.length - bytesUsed) { + newBufferSize = (buf.length * 2) + chunk.length + if (newBufferSize > maxBufferAheadAllocation) { + newBufferSize = buf.length + chunk.length + maxBufferAheadAllocation + } + newBuffer = Buffer.alloc(newBufferSize) + buf.copy(newBuffer, 0, 0, bytesUsed) + buf = newBuffer + } + chunk.copy(buf, bytesUsed) + bytesUsed += chunk.length + } + + var pos = 0 + var length = bytesUsed + + while (pos < length) { + if (discardTrailingNewline) { + if (buf[pos] === lineFeed) { + ++pos + } + discardTrailingNewline = false + } + + var lineLength = -1 + var fieldLength = startingFieldLength + var c + + for (var i = startingPos; lineLength < 0 && i < length; ++i) { + c = buf[i] + if (c === colon) { + if (fieldLength < 0) { + fieldLength = i - pos + } + } else if (c === carriageReturn) { + discardTrailingNewline = true + lineLength = i - pos + } else if (c === lineFeed) { + lineLength = i - pos + } + } + + if (lineLength < 0) { + startingPos = length - pos + startingFieldLength = fieldLength + break + } else { + startingPos = 0 + startingFieldLength = -1 + } + + parseEventStreamLine(buf, pos, fieldLength, lineLength) + + pos += lineLength + 1 + } + + if (pos === length) { + buf = void 0 + bytesUsed = 0 + } else if (pos > 0) { + buf = buf.slice(pos, bytesUsed) + bytesUsed = buf.length + } + }) + }) + + req.on('error', function (err) { + self.connectionInProgress = false + onConnectionClosed(err.message) + }) + + if (req.setNoDelay) req.setNoDelay(true) + req.end() + } + + connect() + + function _emit () { + if (self.listeners(arguments[0]).length > 0) { + self.emit.apply(self, arguments) + } + } + + this._close = function () { + if (readyState === EventSource.CLOSED) return + readyState = EventSource.CLOSED + if (req.abort) req.abort() + if (req.xhr && req.xhr.abort) req.xhr.abort() + } + + function parseEventStreamLine (buf, pos, fieldLength, lineLength) { + if (lineLength === 0) { + if (data.length > 0) { + var type = eventName || 'message' + _emit(type, new MessageEvent(type, { + data: data.slice(0, -1), // remove trailing newline + lastEventId: lastEventId, + origin: new URL(url).origin + })) + data = '' + } + eventName = void 0 + } else if (fieldLength > 0) { + var noValue = fieldLength < 0 + var step = 0 + var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString() + + if (noValue) { + step = lineLength + } else if (buf[pos + fieldLength + 1] !== space) { + step = fieldLength + 1 + } else { + step = fieldLength + 2 + } + pos += step + + var valueLength = lineLength - step + var value = buf.slice(pos, pos + valueLength).toString() + + if (field === 'data') { + data += value + '\n' + } else if (field === 'event') { + eventName = value + } else if (field === 'id') { + lastEventId = value + } else if (field === 'retry') { + var retry = parseInt(value, 10) + if (!Number.isNaN(retry)) { + self.reconnectInterval = retry + } + } + } + } +} + +module.exports = EventSource + +util.inherits(EventSource, events.EventEmitter) +EventSource.prototype.constructor = EventSource; // make stacktraces readable + +['open', 'error', 'message'].forEach(function (method) { + Object.defineProperty(EventSource.prototype, 'on' + method, { + /** + * Returns the current listener + * + * @return {Mixed} the set function or undefined + * @api private + */ + get: function get () { + var listener = this.listeners(method)[0] + return listener ? (listener._listener ? listener._listener : listener) : undefined + }, + + /** + * Start listening for events + * + * @param {Function} listener the listener + * @return {Mixed} the set function or undefined + * @api private + */ + set: function set (listener) { + this.removeAllListeners(method) + this.addEventListener(method, listener) + } + }) +}) + +/** + * Ready states + */ +Object.defineProperty(EventSource, 'CONNECTING', {enumerable: true, value: 0}) +Object.defineProperty(EventSource, 'OPEN', {enumerable: true, value: 1}) +Object.defineProperty(EventSource, 'CLOSED', {enumerable: true, value: 2}) + +EventSource.prototype.CONNECTING = 0 +EventSource.prototype.OPEN = 1 +EventSource.prototype.CLOSED = 2 + +/** + * Closes the connection, if one is made, and sets the readyState attribute to 2 (closed) + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close + * @api public + */ +EventSource.prototype.close = function () { + this._close() +} + +/** + * Emulates the W3C Browser based WebSocket interface using addEventListener. + * + * @param {String} type A string representing the event type to listen out for + * @param {Function} listener callback + * @see https://developer.mozilla.org/en/DOM/element.addEventListener + * @see http://dev.w3.org/html5/websockets/#the-websocket-interface + * @api public + */ +EventSource.prototype.addEventListener = function addEventListener (type, listener) { + if (typeof listener === 'function') { + // store a reference so we can return the original function again + listener._listener = listener + this.on(type, listener) + } +} + +/** + * Emulates the W3C Browser based WebSocket interface using dispatchEvent. + * + * @param {Event} event An event to be dispatched + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent + * @api public + */ +EventSource.prototype.dispatchEvent = function dispatchEvent (event) { + if (!event.type) { + throw new Error('UNSPECIFIED_EVENT_TYPE_ERR') + } + // if event is instance of an CustomEvent (or has 'details' property), + // send the detail object as the payload for the event + this.emit(event.type, event.detail) +} + +/** + * Emulates the W3C Browser based WebSocket interface using removeEventListener. + * + * @param {String} type A string representing the event type to remove + * @param {Function} listener callback + * @see https://developer.mozilla.org/en/DOM/element.removeEventListener + * @see http://dev.w3.org/html5/websockets/#the-websocket-interface + * @api public + */ +EventSource.prototype.removeEventListener = function removeEventListener (type, listener) { + if (typeof listener === 'function') { + listener._listener = undefined + this.removeListener(type, listener) + } +} + +/** + * W3C Event + * + * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event + * @api private + */ +function Event (type, optionalProperties) { + Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) + if (optionalProperties) { + for (var f in optionalProperties) { + if (optionalProperties.hasOwnProperty(f)) { + Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true }) + } + } + } +} + +/** + * W3C MessageEvent + * + * @see http://www.w3.org/TR/webmessaging/#event-definitions + * @api private + */ +function MessageEvent (type, eventInitDict) { + Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) + for (var f in eventInitDict) { + if (eventInitDict.hasOwnProperty(f)) { + Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true }) + } + } +} + +/** + * Returns a new object of headers that does not include any authorization and cookie headers + * + * @param {Object} headers An object of headers ({[headerName]: headerValue}) + * @return {Object} a new object of headers + * @api private + */ +function removeUnsafeHeaders (headers) { + var safe = {} + for (var key in headers) { + if (reUnsafeHeader.test(key)) { + continue + } + + safe[key] = headers[key] + } + + return safe +} diff --git a/node_modules/eventsource/package.json b/node_modules/eventsource/package.json new file mode 100644 index 000000000..ad903213c --- /dev/null +++ b/node_modules/eventsource/package.json @@ -0,0 +1,60 @@ +{ + "name": "eventsource", + "version": "2.0.2", + "description": "W3C compliant EventSource client for Node.js and browser (polyfill)", + "keywords": [ + "eventsource", + "http", + "streaming", + "sse", + "polyfill" + ], + "homepage": "http://github.com/EventSource/eventsource", + "author": "Aslak Hellesøy ", + "repository": { + "type": "git", + "url": "git://github.com/EventSource/eventsource.git" + }, + "bugs": { + "url": "http://github.com/EventSource/eventsource/issues" + }, + "directories": { + "lib": "./lib" + }, + "main": "./lib/eventsource", + "license": "MIT", + "licenses": [ + { + "type": "MIT", + "url": "http://github.com/EventSource/eventsource/raw/master/LICENSE" + } + ], + "devDependencies": { + "buffer-from": "^1.1.1", + "express": "^4.15.3", + "mocha": "^3.5.3", + "nyc": "^11.2.1", + "serve-static": "^1.12.3", + "ssestream": "^1.0.0", + "standard": "^10.0.2", + "webpack": "^3.5.6" + }, + "scripts": { + "test": "mocha --reporter spec && standard", + "polyfill": "webpack lib/eventsource-polyfill.js example/eventsource-polyfill.js", + "postpublish": "git push && git push --tags", + "coverage": "nyc --reporter=html --reporter=text _mocha --reporter spec" + }, + "engines": { + "node": ">=12.0.0" + }, + "dependencies": {}, + "standard": { + "ignore": [ + "example/eventsource-polyfill.js" + ], + "globals": [ + "URL" + ] + } +} diff --git a/node_modules/feaxios/LICENSE b/node_modules/feaxios/LICENSE new file mode 100644 index 000000000..cd436825a --- /dev/null +++ b/node_modules/feaxios/LICENSE @@ -0,0 +1,35 @@ +MIT License + +Copyright (c) 2024 divyam234 + +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 2019 Softonic International S.A. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/node_modules/feaxios/README.md b/node_modules/feaxios/README.md new file mode 100644 index 000000000..4de653480 --- /dev/null +++ b/node_modules/feaxios/README.md @@ -0,0 +1,131 @@ +# feaxios + +`feaxios` is a lightweight alternative to **Axios**, providing the same familiar API with a significantly reduced footprint of **2KB**. It leverages the native `fetch()` API supported in all modern browsers, delivering a performant and minimalistic solution. This makes it an ideal choice for projects where minimizing bundle size is a priority. + +### Key Features + +- **Lightweight:** With a size of less than 1/5th of Axios, `feaxios` is an efficient choice for projects with strict size constraints. + +- **Native Fetch API:** Utilizes the browser's native fetch, ensuring broad compatibility and seamless integration with modern web development tools. + +- **Interceptor Support:** `feaxios` supports interceptors, allowing you to customize and augment the request and response handling process. + +- **Timeouts:** Easily configure timeouts for requests, ensuring your application remains responsive and resilient. + +- **Retries:** Axios retry package is integrated with feaxios. + + +### When to Use feaxios + +While [Axios] remains an excellent module, `feaxios` provides a compelling option in scenarios where minimizing dependencies is crucial. By offering a similar API to Axios, `feaxios` bridges the gap between Axios and the native `fetch()` API. + +```sh +npm install feaxios +``` + +**_Request Config_** + +```ts +{ + +url: '/user', + +method: 'get', // default + +baseURL: 'https://some-domain.com/api/', + +transformRequest: [function (data, headers) { + return data; +}], + +transformResponse: [function (data) { + + return data; +}], + +headers: {'test': 'test'}, + +params: { + ID: 12345 +}, + + paramsSerializer: { + + encode?: (param: string): string => {}, + + serialize?: (params: Record, options?: ParamsSerializerOptions ), + + indexes: false + }, + + data: {}, + + timeout: 1000, // default is 0ms + + withCredentials: false, + + responseType: 'json', // default + + validateStatus: function (status) { + return status >= 200 && status < 300; + }, + + signal: new AbortController().signal, + + fetchOptions: { + redirect: "follow" + }, + retry: { retries: 3 } +``` + +**In fetchOptions you can pass custom options like proxy , agents etc supported on nodejs** + +### Usage + +```js +import axios from "feaxios"; + +axios + .get("https://api.example.com/data") + .then((response) => { + // Handle the response + console.log(response.data); + }) + .catch((error) => { + // Handle errors + console.error(error); + }); +``` + +**_With Interceptors_** + +```js +import axios from "feaxios"; + +axios.interceptors.request.use((config) => { + config.headers.set("Authorization", "Bearer *"); + return config; +}); +axios.interceptors.response.use( + function (response) { + return response; + }, + function (error) { + //do something with error + return Promise.reject(error); + }, +); +``` +**Axios Retry Package is also ported to feaxios** + +```ts +import axios from "feaxios" +import axiosRetry from "feaxios/retry" + +const http = axios.create({ + timeout: 3 * 1000 * 60, +}) + +axiosRetry(http, { retryDelay: axiosRetry.exponentialDelay }) +``` +Visit: https://github.com/softonic/axios-retry to see more options. diff --git a/node_modules/feaxios/dist/client-DGpL0cYy.d.mts b/node_modules/feaxios/dist/client-DGpL0cYy.d.mts new file mode 100644 index 000000000..13d7506fa --- /dev/null +++ b/node_modules/feaxios/dist/client-DGpL0cYy.d.mts @@ -0,0 +1,162 @@ +interface AxiosRetryConfig { + retries?: number; + shouldResetTimeout?: boolean; + retryCondition?: (error: AxiosError) => boolean | Promise; + retryDelay?: (retryCount: number, error: AxiosError) => number; + onRetry?: (retryCount: number, error: AxiosError, requestConfig: AxiosRequestConfig) => Promise | void; +} +interface AxiosRetryConfigExtended extends AxiosRetryConfig { + retryCount?: number; + lastRequestTime?: number; +} +interface AxiosRetryReturn { + requestInterceptorId: number; + responseInterceptorId: number; +} +interface AxiosRetry { + (axiosInstance: AxiosStatic | AxiosInstance, axiosRetryConfig?: AxiosRetryConfig): AxiosRetryReturn; + isNetworkError(error: AxiosError): boolean; + isRetryableError(error: AxiosError): boolean; + isSafeRequestError(error: AxiosError): boolean; + isIdempotentRequestError(error: AxiosError): boolean; + isNetworkOrIdempotentRequestError(error: AxiosError): boolean; + exponentialDelay(retryNumber?: number, error?: AxiosError, delayFactor?: number): number; +} +declare function isNetworkError(error: AxiosError): boolean; +declare function isRetryableError(error: AxiosError): boolean; +declare function isSafeRequestError(error: AxiosError): boolean; +declare function isIdempotentRequestError(error: AxiosError): boolean; +declare function isNetworkOrIdempotentRequestError(error: AxiosError): boolean; +declare function exponentialDelay(retryNumber?: number, _error?: AxiosError | undefined, delayFactor?: number): number; +declare const DEFAULT_OPTIONS: Required; +declare const axiosRetry: AxiosRetry; + +type AxiosRequestTransformer = (this: InternalAxiosRequestConfig, data: any, headers: Headers) => any; +type AxiosResponseTransformer = (this: InternalAxiosRequestConfig, data: any, headers: HeadersInit, status?: number) => any; +type ResponseType = "arrayBuffer" | "blob" | "json" | "text" | "stream"; +type Method = 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS' | 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH' | 'purge' | 'PURGE' | 'link' | 'LINK' | 'unlink' | 'UNLINK'; +interface FormDataVisitorHelpers { + defaultVisitor: SerializerVisitor; + convertValue: (value: any) => any; + isVisitable: (value: any) => boolean; +} +type SerializerVisitor = (this: GenericFormData, value: any, key: string | number, path: null | Array, helpers: FormDataVisitorHelpers) => boolean; +interface GenericFormData { + append(name: string, value: any, options?: any): any; +} +interface SerializerOptions { + visitor?: SerializerVisitor; + dots?: boolean; + metaTokens?: boolean; + indexes?: boolean | null; +} +type ParamEncoder = (value: any, defaultEncoder: (value: any) => any) => any; +type CustomParamsSerializer = (params: Record, options?: ParamsSerializerOptions) => string; +interface ParamsSerializerOptions extends SerializerOptions { + encode?: ParamEncoder; + serialize?: CustomParamsSerializer; +} +interface AxiosRequestConfig { + url?: string; + method?: Method | string; + baseURL?: string; + transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; + transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; + headers?: HeadersInit; + params?: Record; + paramsSerializer?: CustomParamsSerializer; + data?: D; + timeout?: number; + timeoutErrorMessage?: string; + withCredentials?: boolean; + responseType?: ResponseType; + validateStatus?: ((status: number) => boolean) | null; + signal?: AbortSignal; + fetchOptions?: RequestInit; + retry?: AxiosRetryConfigExtended; +} +type RawAxiosRequestConfig = AxiosRequestConfig; +interface InternalAxiosRequestConfig extends Omit, "headers"> { + headers: Headers; +} +interface AxiosDefaults extends Omit, "headers"> { + headers: HeadersInit; +} +interface CreateAxiosDefaults extends Omit, "headers"> { + headers?: HeadersInit; +} +interface AxiosResponse { + data: T; + status: number; + statusText: string; + headers: Headers; + config: InternalAxiosRequestConfig; + request?: Request; +} +type AxiosPromise = Promise>; +interface AxiosInterceptorOptions { + runWhen?: (config: InternalAxiosRequestConfig) => boolean; +} +type FulfillCallback = ((value: V) => V | Promise) | null; +type RejectCallback = ((error: any) => any) | null; +interface AxiosInterceptorManager { + use(onFulfilled?: FulfillCallback, onRejected?: RejectCallback, options?: AxiosInterceptorOptions): number; + eject(id: number): void; + clear(): void; +} +type AxiosInterceptor = { + fulfilled?: FulfillCallback; + rejected?: RejectCallback; + synchronous?: boolean; + runWhen?: (config: InternalAxiosRequestConfig) => boolean; +}; +interface AxiosInstance { + defaults: CreateAxiosDefaults; + interceptors: { + request: AxiosInterceptorManager; + response: AxiosInterceptorManager; + }; + getUri: (config?: AxiosRequestConfig) => string; + request: , D = any>(config: AxiosRequestConfig) => Promise; + get: , D = any>(url: string, config?: AxiosRequestConfig | undefined) => Promise; + delete: , D = any>(url: string, config?: AxiosRequestConfig | undefined) => Promise; + head: , D = any>(url: string, config?: AxiosRequestConfig | undefined) => Promise; + options: , D = any>(url: string, config?: AxiosRequestConfig | undefined) => Promise; + post: , D = any>(url: string, data?: D | undefined, config?: AxiosRequestConfig | undefined) => Promise; + put: , D = any>(url: string, data?: D | undefined, config?: AxiosRequestConfig | undefined) => Promise; + patch: , D = any>(url: string, data?: D | undefined, config?: AxiosRequestConfig | undefined) => Promise; + postForm: , D = any>(url: string, data?: D | undefined, config?: AxiosRequestConfig | undefined) => Promise; + putForm: , D = any>(url: string, data?: D | undefined, config?: AxiosRequestConfig | undefined) => Promise; + patchForm: , D = any>(url: string, data?: D | undefined, config?: AxiosRequestConfig | undefined) => Promise; + , D = any>(config: AxiosRequestConfig): Promise; + , D = any>(url: string, config?: AxiosRequestConfig): Promise; +} +interface AxiosStatic extends AxiosInstance { + create: (defaults?: CreateAxiosDefaults) => AxiosInstance; +} + +declare class AxiosError extends Error { + config?: InternalAxiosRequestConfig; + code?: string; + request?: any; + response?: AxiosResponse; + status?: number; + isAxiosError: boolean; + constructor(message?: string, code?: string, config?: InternalAxiosRequestConfig, request?: any, response?: AxiosResponse); + static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE"; + static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION"; + static readonly ERR_NETWORK = "ERR_NETWORK"; + static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE"; + static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST"; + static readonly ERR_INVALID_URL = "ERR_INVALID_URL"; + static readonly ERR_CANCELED = "ERR_CANCELED"; + static readonly ECONNABORTED = "ECONNABORTED"; + static readonly ETIMEDOUT = "ETIMEDOUT"; +} +declare class CanceledError extends AxiosError { + constructor(message: string | null | undefined, config?: InternalAxiosRequestConfig, request?: any); +} +declare function isAxiosError(payload: any): payload is AxiosError; +declare const axios: AxiosStatic; + +export { AxiosError as A, isRetryableError as B, CanceledError as C, isSafeRequestError as D, isIdempotentRequestError as E, type FormDataVisitorHelpers as F, isNetworkOrIdempotentRequestError as G, exponentialDelay as H, type InternalAxiosRequestConfig as I, DEFAULT_OPTIONS as J, type Method as M, type ParamEncoder as P, type ResponseType as R, type SerializerVisitor as S, axios as a, type AxiosRequestTransformer as b, type AxiosResponseTransformer as c, type SerializerOptions as d, type CustomParamsSerializer as e, type ParamsSerializerOptions as f, type AxiosRequestConfig as g, type RawAxiosRequestConfig as h, isAxiosError as i, type AxiosDefaults as j, type CreateAxiosDefaults as k, type AxiosResponse as l, type AxiosPromise as m, type AxiosInterceptorOptions as n, type FulfillCallback as o, type RejectCallback as p, type AxiosInterceptorManager as q, type AxiosInterceptor as r, type AxiosInstance as s, type AxiosStatic as t, axiosRetry as u, type AxiosRetryConfig as v, type AxiosRetryConfigExtended as w, type AxiosRetryReturn as x, type AxiosRetry as y, isNetworkError as z }; diff --git a/node_modules/feaxios/dist/client-DGpL0cYy.d.ts b/node_modules/feaxios/dist/client-DGpL0cYy.d.ts new file mode 100644 index 000000000..13d7506fa --- /dev/null +++ b/node_modules/feaxios/dist/client-DGpL0cYy.d.ts @@ -0,0 +1,162 @@ +interface AxiosRetryConfig { + retries?: number; + shouldResetTimeout?: boolean; + retryCondition?: (error: AxiosError) => boolean | Promise; + retryDelay?: (retryCount: number, error: AxiosError) => number; + onRetry?: (retryCount: number, error: AxiosError, requestConfig: AxiosRequestConfig) => Promise | void; +} +interface AxiosRetryConfigExtended extends AxiosRetryConfig { + retryCount?: number; + lastRequestTime?: number; +} +interface AxiosRetryReturn { + requestInterceptorId: number; + responseInterceptorId: number; +} +interface AxiosRetry { + (axiosInstance: AxiosStatic | AxiosInstance, axiosRetryConfig?: AxiosRetryConfig): AxiosRetryReturn; + isNetworkError(error: AxiosError): boolean; + isRetryableError(error: AxiosError): boolean; + isSafeRequestError(error: AxiosError): boolean; + isIdempotentRequestError(error: AxiosError): boolean; + isNetworkOrIdempotentRequestError(error: AxiosError): boolean; + exponentialDelay(retryNumber?: number, error?: AxiosError, delayFactor?: number): number; +} +declare function isNetworkError(error: AxiosError): boolean; +declare function isRetryableError(error: AxiosError): boolean; +declare function isSafeRequestError(error: AxiosError): boolean; +declare function isIdempotentRequestError(error: AxiosError): boolean; +declare function isNetworkOrIdempotentRequestError(error: AxiosError): boolean; +declare function exponentialDelay(retryNumber?: number, _error?: AxiosError | undefined, delayFactor?: number): number; +declare const DEFAULT_OPTIONS: Required; +declare const axiosRetry: AxiosRetry; + +type AxiosRequestTransformer = (this: InternalAxiosRequestConfig, data: any, headers: Headers) => any; +type AxiosResponseTransformer = (this: InternalAxiosRequestConfig, data: any, headers: HeadersInit, status?: number) => any; +type ResponseType = "arrayBuffer" | "blob" | "json" | "text" | "stream"; +type Method = 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS' | 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH' | 'purge' | 'PURGE' | 'link' | 'LINK' | 'unlink' | 'UNLINK'; +interface FormDataVisitorHelpers { + defaultVisitor: SerializerVisitor; + convertValue: (value: any) => any; + isVisitable: (value: any) => boolean; +} +type SerializerVisitor = (this: GenericFormData, value: any, key: string | number, path: null | Array, helpers: FormDataVisitorHelpers) => boolean; +interface GenericFormData { + append(name: string, value: any, options?: any): any; +} +interface SerializerOptions { + visitor?: SerializerVisitor; + dots?: boolean; + metaTokens?: boolean; + indexes?: boolean | null; +} +type ParamEncoder = (value: any, defaultEncoder: (value: any) => any) => any; +type CustomParamsSerializer = (params: Record, options?: ParamsSerializerOptions) => string; +interface ParamsSerializerOptions extends SerializerOptions { + encode?: ParamEncoder; + serialize?: CustomParamsSerializer; +} +interface AxiosRequestConfig { + url?: string; + method?: Method | string; + baseURL?: string; + transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; + transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; + headers?: HeadersInit; + params?: Record; + paramsSerializer?: CustomParamsSerializer; + data?: D; + timeout?: number; + timeoutErrorMessage?: string; + withCredentials?: boolean; + responseType?: ResponseType; + validateStatus?: ((status: number) => boolean) | null; + signal?: AbortSignal; + fetchOptions?: RequestInit; + retry?: AxiosRetryConfigExtended; +} +type RawAxiosRequestConfig = AxiosRequestConfig; +interface InternalAxiosRequestConfig extends Omit, "headers"> { + headers: Headers; +} +interface AxiosDefaults extends Omit, "headers"> { + headers: HeadersInit; +} +interface CreateAxiosDefaults extends Omit, "headers"> { + headers?: HeadersInit; +} +interface AxiosResponse { + data: T; + status: number; + statusText: string; + headers: Headers; + config: InternalAxiosRequestConfig; + request?: Request; +} +type AxiosPromise = Promise>; +interface AxiosInterceptorOptions { + runWhen?: (config: InternalAxiosRequestConfig) => boolean; +} +type FulfillCallback = ((value: V) => V | Promise) | null; +type RejectCallback = ((error: any) => any) | null; +interface AxiosInterceptorManager { + use(onFulfilled?: FulfillCallback, onRejected?: RejectCallback, options?: AxiosInterceptorOptions): number; + eject(id: number): void; + clear(): void; +} +type AxiosInterceptor = { + fulfilled?: FulfillCallback; + rejected?: RejectCallback; + synchronous?: boolean; + runWhen?: (config: InternalAxiosRequestConfig) => boolean; +}; +interface AxiosInstance { + defaults: CreateAxiosDefaults; + interceptors: { + request: AxiosInterceptorManager; + response: AxiosInterceptorManager; + }; + getUri: (config?: AxiosRequestConfig) => string; + request: , D = any>(config: AxiosRequestConfig) => Promise; + get: , D = any>(url: string, config?: AxiosRequestConfig | undefined) => Promise; + delete: , D = any>(url: string, config?: AxiosRequestConfig | undefined) => Promise; + head: , D = any>(url: string, config?: AxiosRequestConfig | undefined) => Promise; + options: , D = any>(url: string, config?: AxiosRequestConfig | undefined) => Promise; + post: , D = any>(url: string, data?: D | undefined, config?: AxiosRequestConfig | undefined) => Promise; + put: , D = any>(url: string, data?: D | undefined, config?: AxiosRequestConfig | undefined) => Promise; + patch: , D = any>(url: string, data?: D | undefined, config?: AxiosRequestConfig | undefined) => Promise; + postForm: , D = any>(url: string, data?: D | undefined, config?: AxiosRequestConfig | undefined) => Promise; + putForm: , D = any>(url: string, data?: D | undefined, config?: AxiosRequestConfig | undefined) => Promise; + patchForm: , D = any>(url: string, data?: D | undefined, config?: AxiosRequestConfig | undefined) => Promise; + , D = any>(config: AxiosRequestConfig): Promise; + , D = any>(url: string, config?: AxiosRequestConfig): Promise; +} +interface AxiosStatic extends AxiosInstance { + create: (defaults?: CreateAxiosDefaults) => AxiosInstance; +} + +declare class AxiosError extends Error { + config?: InternalAxiosRequestConfig; + code?: string; + request?: any; + response?: AxiosResponse; + status?: number; + isAxiosError: boolean; + constructor(message?: string, code?: string, config?: InternalAxiosRequestConfig, request?: any, response?: AxiosResponse); + static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE"; + static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION"; + static readonly ERR_NETWORK = "ERR_NETWORK"; + static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE"; + static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST"; + static readonly ERR_INVALID_URL = "ERR_INVALID_URL"; + static readonly ERR_CANCELED = "ERR_CANCELED"; + static readonly ECONNABORTED = "ECONNABORTED"; + static readonly ETIMEDOUT = "ETIMEDOUT"; +} +declare class CanceledError extends AxiosError { + constructor(message: string | null | undefined, config?: InternalAxiosRequestConfig, request?: any); +} +declare function isAxiosError(payload: any): payload is AxiosError; +declare const axios: AxiosStatic; + +export { AxiosError as A, isRetryableError as B, CanceledError as C, isSafeRequestError as D, isIdempotentRequestError as E, type FormDataVisitorHelpers as F, isNetworkOrIdempotentRequestError as G, exponentialDelay as H, type InternalAxiosRequestConfig as I, DEFAULT_OPTIONS as J, type Method as M, type ParamEncoder as P, type ResponseType as R, type SerializerVisitor as S, axios as a, type AxiosRequestTransformer as b, type AxiosResponseTransformer as c, type SerializerOptions as d, type CustomParamsSerializer as e, type ParamsSerializerOptions as f, type AxiosRequestConfig as g, type RawAxiosRequestConfig as h, isAxiosError as i, type AxiosDefaults as j, type CreateAxiosDefaults as k, type AxiosResponse as l, type AxiosPromise as m, type AxiosInterceptorOptions as n, type FulfillCallback as o, type RejectCallback as p, type AxiosInterceptorManager as q, type AxiosInterceptor as r, type AxiosInstance as s, type AxiosStatic as t, axiosRetry as u, type AxiosRetryConfig as v, type AxiosRetryConfigExtended as w, type AxiosRetryReturn as x, type AxiosRetry as y, isNetworkError as z }; diff --git a/node_modules/feaxios/dist/index.d.mts b/node_modules/feaxios/dist/index.d.mts new file mode 100644 index 000000000..7b218f598 --- /dev/null +++ b/node_modules/feaxios/dist/index.d.mts @@ -0,0 +1,6 @@ +import { a as axios } from './client-DGpL0cYy.mjs'; +export { j as AxiosDefaults, A as AxiosError, s as AxiosInstance, r as AxiosInterceptor, q as AxiosInterceptorManager, n as AxiosInterceptorOptions, m as AxiosPromise, g as AxiosRequestConfig, b as AxiosRequestTransformer, l as AxiosResponse, c as AxiosResponseTransformer, t as AxiosStatic, C as CanceledError, k as CreateAxiosDefaults, e as CustomParamsSerializer, F as FormDataVisitorHelpers, o as FulfillCallback, I as InternalAxiosRequestConfig, M as Method, P as ParamEncoder, f as ParamsSerializerOptions, h as RawAxiosRequestConfig, p as RejectCallback, R as ResponseType, d as SerializerOptions, S as SerializerVisitor, i as isAxiosError } from './client-DGpL0cYy.mjs'; + + + +export { axios as default }; diff --git a/node_modules/feaxios/dist/index.d.ts b/node_modules/feaxios/dist/index.d.ts new file mode 100644 index 000000000..c5b84be81 --- /dev/null +++ b/node_modules/feaxios/dist/index.d.ts @@ -0,0 +1,6 @@ +import { a as axios } from './client-DGpL0cYy.js'; +export { j as AxiosDefaults, A as AxiosError, s as AxiosInstance, r as AxiosInterceptor, q as AxiosInterceptorManager, n as AxiosInterceptorOptions, m as AxiosPromise, g as AxiosRequestConfig, b as AxiosRequestTransformer, l as AxiosResponse, c as AxiosResponseTransformer, t as AxiosStatic, C as CanceledError, k as CreateAxiosDefaults, e as CustomParamsSerializer, F as FormDataVisitorHelpers, o as FulfillCallback, I as InternalAxiosRequestConfig, M as Method, P as ParamEncoder, f as ParamsSerializerOptions, h as RawAxiosRequestConfig, p as RejectCallback, R as ResponseType, d as SerializerOptions, S as SerializerVisitor, i as isAxiosError } from './client-DGpL0cYy.js'; + + + +export { axios as default }; diff --git a/node_modules/feaxios/dist/index.js b/node_modules/feaxios/dist/index.js new file mode 100644 index 000000000..50e09ff54 --- /dev/null +++ b/node_modules/feaxios/dist/index.js @@ -0,0 +1,321 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +// src/client.ts +async function prepareAxiosResponse(options, res) { + const response = { config: options }; + response.status = res.status; + response.statusText = res.statusText; + response.headers = res.headers; + if (options.responseType === "stream") { + response.data = res.body; + return response; + } + return res[options.responseType || "text"]().then((data) => { + if (options.transformResponse) { + Array.isArray(options.transformResponse) ? options.transformResponse.map( + (fn) => data = fn.call(options, data, res?.headers, res?.status) + ) : data = options.transformResponse(data, res?.headers, res?.status); + response.data = data; + } else { + response.data = data; + response.data = JSON.parse(data); + } + }).catch(Object).then(() => response); +} +async function handleFetch(options, fetchOptions) { + let res = null; + if ("any" in AbortSignal) { + const signals = []; + if (options.timeout) { + signals.push(AbortSignal.timeout(options.timeout)); + } + if (options.signal) { + signals.push(options.signal); + } + if (signals.length > 0) { + fetchOptions.signal = AbortSignal.any(signals); + } + } else { + if (options.timeout) { + fetchOptions.signal = AbortSignal.timeout(options.timeout); + } + } + try { + res = await fetch(options.url, fetchOptions); + const ok = options.validateStatus ? options.validateStatus(res.status) : res.ok; + if (!ok) { + return Promise.reject( + new AxiosError( + `Request failed with status code ${res?.status}`, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(res?.status / 100) - 4], + options, + new Request(options.url, fetchOptions), + await prepareAxiosResponse(options, res) + ) + ); + } + return await prepareAxiosResponse(options, res); + } catch (error) { + if (error.name === "AbortError" || error.name === "TimeoutError") { + const isTimeoutError = error.name === "TimeoutError"; + return Promise.reject( + isTimeoutError ? new AxiosError( + options.timeoutErrorMessage || `timeout of ${options.timeout} ms exceeded`, + AxiosError.ECONNABORTED, + options, + request + ) : new CanceledError(null, options) + ); + } + return Promise.reject( + new AxiosError( + error.message, + void 0, + options, + request, + void 0 + ) + ); + } +} +function buildURL(options) { + let url = options.url || ""; + if (options.baseURL && options.url) { + url = options.url.replace(/^(?!.*\/\/)\/?/, `${options.baseURL}/`); + } + if (options.params && Object.keys(options.params).length > 0 && options.url) { + url += (~options.url.indexOf("?") ? "&" : "?") + (options.paramsSerializer ? options.paramsSerializer(options.params) : new URLSearchParams(options.params)); + } + return url; +} +function mergeAxiosOptions(input, defaults) { + const merged = { + ...defaults, + ...input + }; + if (defaults?.params && input?.params) { + merged.params = { + ...defaults?.params, + ...input?.params + }; + } + if (defaults?.headers && input?.headers) { + merged.headers = new Headers(defaults.headers || {}); + const headers = new Headers(input.headers || {}); + headers.forEach((value, key) => { + merged.headers.set(key, value); + }); + } + return merged; +} +function mergeFetchOptions(input, defaults) { + const merged = { + ...defaults, + ...input + }; + if (defaults?.headers && input?.headers) { + merged.headers = new Headers(defaults.headers || {}); + const headers = new Headers(input.headers || {}); + headers.forEach((value, key) => { + merged.headers.set(key, value); + }); + } + return merged; +} +function defaultTransformer(data, headers) { + const contentType = headers.get("content-type"); + if (!contentType) { + if (typeof data === "string") { + headers.set("content-type", "text/plain"); + } else if (data instanceof URLSearchParams) { + headers.set("content-type", "application/x-www-form-urlencoded"); + } else if (data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data)) { + headers.set("content-type", "application/octet-stream"); + } else if (typeof data === "object" && typeof data.append !== "function" && typeof data.text !== "function") { + data = JSON.stringify(data); + headers.set("content-type", "application/json"); + } + } else { + if (contentType === "application/x-www-form-urlencoded" && !(data instanceof URLSearchParams)) { + data = new URLSearchParams(data); + } else if (contentType === "application/json" && typeof data === "object") { + data = JSON.stringify(data); + } + } + return data; +} +async function request(configOrUrl, config, defaults, method, interceptors, data) { + if (typeof configOrUrl === "string") { + config = config || {}; + config.url = configOrUrl; + } else + config = configOrUrl || {}; + const options = mergeAxiosOptions(config, defaults || {}); + options.fetchOptions = options.fetchOptions || {}; + options.timeout = options.timeout || 0; + options.headers = new Headers(options.headers || {}); + options.transformRequest = options.transformRequest ?? defaultTransformer; + data = data || options.data; + if (options.transformRequest && data) { + Array.isArray(options.transformRequest) ? options.transformRequest.map( + (fn) => data = fn.call(options, data, options.headers) + ) : data = options.transformRequest(data, options.headers); + } + options.url = buildURL(options); + options.method = method || options.method || "get"; + if (interceptors && interceptors.request.handlers.length > 0) { + const chain = interceptors.request.handlers.filter( + (interceptor) => !interceptor?.runWhen || typeof interceptor.runWhen === "function" && interceptor.runWhen(options) + ).flatMap((interceptor) => [interceptor.fulfilled, interceptor.rejected]); + let result = options; + for (let i = 0, len = chain.length; i < len; i += 2) { + const onFulfilled = chain[i]; + const onRejected = chain[i + 1]; + try { + if (onFulfilled) + result = onFulfilled(result); + } catch (error) { + if (onRejected) + onRejected?.(error); + break; + } + } + } + const init = mergeFetchOptions( + { + method: options.method?.toUpperCase(), + body: data, + headers: options.headers, + credentials: options.withCredentials ? "include" : void 0, + signal: options.signal + }, + options.fetchOptions + ); + let resp = handleFetch(options, init); + if (interceptors && interceptors.response.handlers.length > 0) { + const chain = interceptors.response.handlers.flatMap((interceptor) => [ + interceptor.fulfilled, + interceptor.rejected + ]); + for (let i = 0, len = chain.length; i < len; i += 2) { + resp = resp.then(chain[i], chain[i + 1]); + } + } + return resp; +} +var AxiosInterceptorManager = class { + handlers = []; + constructor() { + this.handlers = []; + } + use = (onFulfilled, onRejected, options) => { + this.handlers.push({ + fulfilled: onFulfilled, + rejected: onRejected, + runWhen: options?.runWhen + }); + return this.handlers.length - 1; + }; + eject = (id) => { + if (this.handlers[id]) { + this.handlers[id] = null; + } + }; + clear = () => { + this.handlers = []; + }; +}; +function createAxiosInstance(defaults) { + defaults = defaults || {}; + const interceptors = { + request: new AxiosInterceptorManager(), + response: new AxiosInterceptorManager() + }; + const axios2 = (url, config) => request(url, config, defaults, void 0, interceptors); + axios2.defaults = defaults; + axios2.interceptors = interceptors; + axios2.getUri = (config) => { + const merged = mergeAxiosOptions(config || {}, defaults); + return buildURL(merged); + }; + axios2.request = (config) => request(config, void 0, defaults, void 0, interceptors); + ["get", "delete", "head", "options"].forEach((method) => { + axios2[method] = (url, config) => request(url, config, defaults, method, interceptors); + }); + ["post", "put", "patch"].forEach((method) => { + axios2[method] = (url, data, config) => request(url, config, defaults, method, interceptors, data); + }); + ["postForm", "putForm", "patchForm"].forEach((method) => { + axios2[method] = (url, data, config) => { + config = config || {}; + config.headers = new Headers(config.headers || {}); + config.headers.set("content-type", "application/x-www-form-urlencoded"); + return request( + url, + config, + defaults, + method.replace("Form", ""), + interceptors, + data + ); + }; + }); + return axios2; +} +var AxiosError = class extends Error { + config; + code; + request; + response; + status; + isAxiosError; + constructor(message, code, config, request2, response) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack; + } + this.name = "AxiosError"; + this.code = code; + this.config = config; + this.request = request2; + this.response = response; + this.isAxiosError = true; + } + static ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE"; + static ERR_BAD_OPTION = "ERR_BAD_OPTION"; + static ERR_NETWORK = "ERR_NETWORK"; + static ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE"; + static ERR_BAD_REQUEST = "ERR_BAD_REQUEST"; + static ERR_INVALID_URL = "ERR_INVALID_URL"; + static ERR_CANCELED = "ERR_CANCELED"; + static ECONNABORTED = "ECONNABORTED"; + static ETIMEDOUT = "ETIMEDOUT"; +}; +var CanceledError = class extends AxiosError { + constructor(message, config, request2) { + super( + !message ? "canceled" : message, + AxiosError.ERR_CANCELED, + config, + request2 + ); + this.name = "CanceledError"; + } +}; +function isAxiosError(payload) { + return payload !== null && typeof payload === "object" && payload.isAxiosError; +} +var axios = createAxiosInstance(); +axios.create = (defaults) => createAxiosInstance(defaults); + +// src/index.ts +var src_default = axios; + +exports.AxiosError = AxiosError; +exports.CanceledError = CanceledError; +exports.default = src_default; +exports.isAxiosError = isAxiosError; diff --git a/node_modules/feaxios/dist/index.mjs b/node_modules/feaxios/dist/index.mjs new file mode 100644 index 000000000..579f0587f --- /dev/null +++ b/node_modules/feaxios/dist/index.mjs @@ -0,0 +1,314 @@ +// src/client.ts +async function prepareAxiosResponse(options, res) { + const response = { config: options }; + response.status = res.status; + response.statusText = res.statusText; + response.headers = res.headers; + if (options.responseType === "stream") { + response.data = res.body; + return response; + } + return res[options.responseType || "text"]().then((data) => { + if (options.transformResponse) { + Array.isArray(options.transformResponse) ? options.transformResponse.map( + (fn) => data = fn.call(options, data, res?.headers, res?.status) + ) : data = options.transformResponse(data, res?.headers, res?.status); + response.data = data; + } else { + response.data = data; + response.data = JSON.parse(data); + } + }).catch(Object).then(() => response); +} +async function handleFetch(options, fetchOptions) { + let res = null; + if ("any" in AbortSignal) { + const signals = []; + if (options.timeout) { + signals.push(AbortSignal.timeout(options.timeout)); + } + if (options.signal) { + signals.push(options.signal); + } + if (signals.length > 0) { + fetchOptions.signal = AbortSignal.any(signals); + } + } else { + if (options.timeout) { + fetchOptions.signal = AbortSignal.timeout(options.timeout); + } + } + try { + res = await fetch(options.url, fetchOptions); + const ok = options.validateStatus ? options.validateStatus(res.status) : res.ok; + if (!ok) { + return Promise.reject( + new AxiosError( + `Request failed with status code ${res?.status}`, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(res?.status / 100) - 4], + options, + new Request(options.url, fetchOptions), + await prepareAxiosResponse(options, res) + ) + ); + } + return await prepareAxiosResponse(options, res); + } catch (error) { + if (error.name === "AbortError" || error.name === "TimeoutError") { + const isTimeoutError = error.name === "TimeoutError"; + return Promise.reject( + isTimeoutError ? new AxiosError( + options.timeoutErrorMessage || `timeout of ${options.timeout} ms exceeded`, + AxiosError.ECONNABORTED, + options, + request + ) : new CanceledError(null, options) + ); + } + return Promise.reject( + new AxiosError( + error.message, + void 0, + options, + request, + void 0 + ) + ); + } +} +function buildURL(options) { + let url = options.url || ""; + if (options.baseURL && options.url) { + url = options.url.replace(/^(?!.*\/\/)\/?/, `${options.baseURL}/`); + } + if (options.params && Object.keys(options.params).length > 0 && options.url) { + url += (~options.url.indexOf("?") ? "&" : "?") + (options.paramsSerializer ? options.paramsSerializer(options.params) : new URLSearchParams(options.params)); + } + return url; +} +function mergeAxiosOptions(input, defaults) { + const merged = { + ...defaults, + ...input + }; + if (defaults?.params && input?.params) { + merged.params = { + ...defaults?.params, + ...input?.params + }; + } + if (defaults?.headers && input?.headers) { + merged.headers = new Headers(defaults.headers || {}); + const headers = new Headers(input.headers || {}); + headers.forEach((value, key) => { + merged.headers.set(key, value); + }); + } + return merged; +} +function mergeFetchOptions(input, defaults) { + const merged = { + ...defaults, + ...input + }; + if (defaults?.headers && input?.headers) { + merged.headers = new Headers(defaults.headers || {}); + const headers = new Headers(input.headers || {}); + headers.forEach((value, key) => { + merged.headers.set(key, value); + }); + } + return merged; +} +function defaultTransformer(data, headers) { + const contentType = headers.get("content-type"); + if (!contentType) { + if (typeof data === "string") { + headers.set("content-type", "text/plain"); + } else if (data instanceof URLSearchParams) { + headers.set("content-type", "application/x-www-form-urlencoded"); + } else if (data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data)) { + headers.set("content-type", "application/octet-stream"); + } else if (typeof data === "object" && typeof data.append !== "function" && typeof data.text !== "function") { + data = JSON.stringify(data); + headers.set("content-type", "application/json"); + } + } else { + if (contentType === "application/x-www-form-urlencoded" && !(data instanceof URLSearchParams)) { + data = new URLSearchParams(data); + } else if (contentType === "application/json" && typeof data === "object") { + data = JSON.stringify(data); + } + } + return data; +} +async function request(configOrUrl, config, defaults, method, interceptors, data) { + if (typeof configOrUrl === "string") { + config = config || {}; + config.url = configOrUrl; + } else + config = configOrUrl || {}; + const options = mergeAxiosOptions(config, defaults || {}); + options.fetchOptions = options.fetchOptions || {}; + options.timeout = options.timeout || 0; + options.headers = new Headers(options.headers || {}); + options.transformRequest = options.transformRequest ?? defaultTransformer; + data = data || options.data; + if (options.transformRequest && data) { + Array.isArray(options.transformRequest) ? options.transformRequest.map( + (fn) => data = fn.call(options, data, options.headers) + ) : data = options.transformRequest(data, options.headers); + } + options.url = buildURL(options); + options.method = method || options.method || "get"; + if (interceptors && interceptors.request.handlers.length > 0) { + const chain = interceptors.request.handlers.filter( + (interceptor) => !interceptor?.runWhen || typeof interceptor.runWhen === "function" && interceptor.runWhen(options) + ).flatMap((interceptor) => [interceptor.fulfilled, interceptor.rejected]); + let result = options; + for (let i = 0, len = chain.length; i < len; i += 2) { + const onFulfilled = chain[i]; + const onRejected = chain[i + 1]; + try { + if (onFulfilled) + result = onFulfilled(result); + } catch (error) { + if (onRejected) + onRejected?.(error); + break; + } + } + } + const init = mergeFetchOptions( + { + method: options.method?.toUpperCase(), + body: data, + headers: options.headers, + credentials: options.withCredentials ? "include" : void 0, + signal: options.signal + }, + options.fetchOptions + ); + let resp = handleFetch(options, init); + if (interceptors && interceptors.response.handlers.length > 0) { + const chain = interceptors.response.handlers.flatMap((interceptor) => [ + interceptor.fulfilled, + interceptor.rejected + ]); + for (let i = 0, len = chain.length; i < len; i += 2) { + resp = resp.then(chain[i], chain[i + 1]); + } + } + return resp; +} +var AxiosInterceptorManager = class { + handlers = []; + constructor() { + this.handlers = []; + } + use = (onFulfilled, onRejected, options) => { + this.handlers.push({ + fulfilled: onFulfilled, + rejected: onRejected, + runWhen: options?.runWhen + }); + return this.handlers.length - 1; + }; + eject = (id) => { + if (this.handlers[id]) { + this.handlers[id] = null; + } + }; + clear = () => { + this.handlers = []; + }; +}; +function createAxiosInstance(defaults) { + defaults = defaults || {}; + const interceptors = { + request: new AxiosInterceptorManager(), + response: new AxiosInterceptorManager() + }; + const axios2 = (url, config) => request(url, config, defaults, void 0, interceptors); + axios2.defaults = defaults; + axios2.interceptors = interceptors; + axios2.getUri = (config) => { + const merged = mergeAxiosOptions(config || {}, defaults); + return buildURL(merged); + }; + axios2.request = (config) => request(config, void 0, defaults, void 0, interceptors); + ["get", "delete", "head", "options"].forEach((method) => { + axios2[method] = (url, config) => request(url, config, defaults, method, interceptors); + }); + ["post", "put", "patch"].forEach((method) => { + axios2[method] = (url, data, config) => request(url, config, defaults, method, interceptors, data); + }); + ["postForm", "putForm", "patchForm"].forEach((method) => { + axios2[method] = (url, data, config) => { + config = config || {}; + config.headers = new Headers(config.headers || {}); + config.headers.set("content-type", "application/x-www-form-urlencoded"); + return request( + url, + config, + defaults, + method.replace("Form", ""), + interceptors, + data + ); + }; + }); + return axios2; +} +var AxiosError = class extends Error { + config; + code; + request; + response; + status; + isAxiosError; + constructor(message, code, config, request2, response) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack; + } + this.name = "AxiosError"; + this.code = code; + this.config = config; + this.request = request2; + this.response = response; + this.isAxiosError = true; + } + static ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE"; + static ERR_BAD_OPTION = "ERR_BAD_OPTION"; + static ERR_NETWORK = "ERR_NETWORK"; + static ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE"; + static ERR_BAD_REQUEST = "ERR_BAD_REQUEST"; + static ERR_INVALID_URL = "ERR_INVALID_URL"; + static ERR_CANCELED = "ERR_CANCELED"; + static ECONNABORTED = "ECONNABORTED"; + static ETIMEDOUT = "ETIMEDOUT"; +}; +var CanceledError = class extends AxiosError { + constructor(message, config, request2) { + super( + !message ? "canceled" : message, + AxiosError.ERR_CANCELED, + config, + request2 + ); + this.name = "CanceledError"; + } +}; +function isAxiosError(payload) { + return payload !== null && typeof payload === "object" && payload.isAxiosError; +} +var axios = createAxiosInstance(); +axios.create = (defaults) => createAxiosInstance(defaults); + +// src/index.ts +var src_default = axios; + +export { AxiosError, CanceledError, src_default as default, isAxiosError }; diff --git a/node_modules/feaxios/dist/retry.d.mts b/node_modules/feaxios/dist/retry.d.mts new file mode 100644 index 000000000..140908009 --- /dev/null +++ b/node_modules/feaxios/dist/retry.d.mts @@ -0,0 +1 @@ +export { y as AxiosRetry, v as AxiosRetryConfig, w as AxiosRetryConfigExtended, x as AxiosRetryReturn, J as DEFAULT_OPTIONS, u as default, H as exponentialDelay, E as isIdempotentRequestError, z as isNetworkError, G as isNetworkOrIdempotentRequestError, B as isRetryableError, D as isSafeRequestError } from './client-DGpL0cYy.mjs'; diff --git a/node_modules/feaxios/dist/retry.d.ts b/node_modules/feaxios/dist/retry.d.ts new file mode 100644 index 000000000..80066b7b7 --- /dev/null +++ b/node_modules/feaxios/dist/retry.d.ts @@ -0,0 +1 @@ +export { y as AxiosRetry, v as AxiosRetryConfig, w as AxiosRetryConfigExtended, x as AxiosRetryReturn, J as DEFAULT_OPTIONS, u as default, H as exponentialDelay, E as isIdempotentRequestError, z as isNetworkError, G as isNetworkOrIdempotentRequestError, B as isRetryableError, D as isSafeRequestError } from './client-DGpL0cYy.js'; diff --git a/node_modules/feaxios/dist/retry.js b/node_modules/feaxios/dist/retry.js new file mode 100644 index 000000000..4ebbe64d0 --- /dev/null +++ b/node_modules/feaxios/dist/retry.js @@ -0,0 +1,137 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var isRetryAllowed = require('is-retry-allowed'); + +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } + +var isRetryAllowed__default = /*#__PURE__*/_interopDefault(isRetryAllowed); + +// src/retry.ts +function isNetworkError(error) { + const CODE_EXCLUDE_LIST = ["ERR_CANCELED", "ECONNABORTED"]; + if (error.response) { + return false; + } + if (!error.code) { + return false; + } + if (CODE_EXCLUDE_LIST.includes(error.code)) { + return false; + } + return isRetryAllowed__default.default(error); +} +var SAFE_HTTP_METHODS = ["get", "head", "options"]; +var IDEMPOTENT_HTTP_METHODS = SAFE_HTTP_METHODS.concat(["put", "delete"]); +function isRetryableError(error) { + return error.code !== "ECONNABORTED" && (!error.response || error.response.status >= 500 && error.response.status <= 599); +} +function isSafeRequestError(error) { + if (!error.config?.method) { + return false; + } + return isRetryableError(error) && SAFE_HTTP_METHODS.indexOf(error.config.method) !== -1; +} +function isIdempotentRequestError(error) { + if (!error.config?.method) { + return false; + } + return isRetryableError(error) && IDEMPOTENT_HTTP_METHODS.indexOf(error.config.method) !== -1; +} +function isNetworkOrIdempotentRequestError(error) { + return isNetworkError(error) || isIdempotentRequestError(error); +} +function noDelay() { + return 0; +} +function exponentialDelay(retryNumber = 0, _error = void 0, delayFactor = 100) { + const delay = 2 ** retryNumber * delayFactor; + const randomSum = delay * 0.2 * Math.random(); + return delay + randomSum; +} +var DEFAULT_OPTIONS = { + retries: 3, + retryCondition: isNetworkOrIdempotentRequestError, + retryDelay: noDelay, + shouldResetTimeout: false, + onRetry: () => { + } +}; +function getRequestOptions(config, defaultOptions) { + return { ...DEFAULT_OPTIONS, ...defaultOptions, ...config.retry }; +} +function setCurrentState(config, defaultOptions) { + const currentState = getRequestOptions(config, defaultOptions || {}); + currentState.retryCount = currentState.retryCount || 0; + currentState.lastRequestTime = currentState.lastRequestTime || Date.now(); + config.retry = currentState; + return currentState; +} +async function shouldRetry(currentState, error) { + const { retries, retryCondition } = currentState; + const shouldRetryOrPromise = (currentState.retryCount || 0) < retries && retryCondition(error); + if (typeof shouldRetryOrPromise === "object") { + try { + const shouldRetryPromiseResult = await shouldRetryOrPromise; + return shouldRetryPromiseResult !== false; + } catch (_err) { + return false; + } + } + return shouldRetryOrPromise; +} +var axiosRetry = (axiosInstance, defaultOptions) => { + const requestInterceptorId = axiosInstance.interceptors.request.use( + (config) => { + setCurrentState(config, defaultOptions); + return config; + } + ); + const responseInterceptorId = axiosInstance.interceptors.response.use( + null, + async (error) => { + const { config } = error; + if (!config) { + return Promise.reject(error); + } + const currentState = setCurrentState(config, defaultOptions); + if (await shouldRetry(currentState, error)) { + currentState.retryCount += 1; + const { retryDelay, shouldResetTimeout, onRetry } = currentState; + const delay = retryDelay(currentState.retryCount, error); + if (!shouldResetTimeout && config.timeout && currentState.lastRequestTime) { + const lastRequestDuration = Date.now() - currentState.lastRequestTime; + const timeout = config.timeout - lastRequestDuration - delay; + if (timeout <= 0) { + return Promise.reject(error); + } + config.timeout = timeout; + } + config.transformRequest = [(data) => data]; + await onRetry(currentState.retryCount, error, config); + return new Promise((resolve) => { + setTimeout(() => resolve(axiosInstance(config)), delay); + }); + } + return Promise.reject(error); + } + ); + return { requestInterceptorId, responseInterceptorId }; +}; +axiosRetry.isNetworkError = isNetworkError; +axiosRetry.isSafeRequestError = isSafeRequestError; +axiosRetry.isIdempotentRequestError = isIdempotentRequestError; +axiosRetry.isNetworkOrIdempotentRequestError = isNetworkOrIdempotentRequestError; +axiosRetry.exponentialDelay = exponentialDelay; +axiosRetry.isRetryableError = isRetryableError; +var retry_default = axiosRetry; + +exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS; +exports.default = retry_default; +exports.exponentialDelay = exponentialDelay; +exports.isIdempotentRequestError = isIdempotentRequestError; +exports.isNetworkError = isNetworkError; +exports.isNetworkOrIdempotentRequestError = isNetworkOrIdempotentRequestError; +exports.isRetryableError = isRetryableError; +exports.isSafeRequestError = isSafeRequestError; diff --git a/node_modules/feaxios/dist/retry.mjs b/node_modules/feaxios/dist/retry.mjs new file mode 100644 index 000000000..b0d4a9120 --- /dev/null +++ b/node_modules/feaxios/dist/retry.mjs @@ -0,0 +1,122 @@ +import isRetryAllowed from 'is-retry-allowed'; + +// src/retry.ts +function isNetworkError(error) { + const CODE_EXCLUDE_LIST = ["ERR_CANCELED", "ECONNABORTED"]; + if (error.response) { + return false; + } + if (!error.code) { + return false; + } + if (CODE_EXCLUDE_LIST.includes(error.code)) { + return false; + } + return isRetryAllowed(error); +} +var SAFE_HTTP_METHODS = ["get", "head", "options"]; +var IDEMPOTENT_HTTP_METHODS = SAFE_HTTP_METHODS.concat(["put", "delete"]); +function isRetryableError(error) { + return error.code !== "ECONNABORTED" && (!error.response || error.response.status >= 500 && error.response.status <= 599); +} +function isSafeRequestError(error) { + if (!error.config?.method) { + return false; + } + return isRetryableError(error) && SAFE_HTTP_METHODS.indexOf(error.config.method) !== -1; +} +function isIdempotentRequestError(error) { + if (!error.config?.method) { + return false; + } + return isRetryableError(error) && IDEMPOTENT_HTTP_METHODS.indexOf(error.config.method) !== -1; +} +function isNetworkOrIdempotentRequestError(error) { + return isNetworkError(error) || isIdempotentRequestError(error); +} +function noDelay() { + return 0; +} +function exponentialDelay(retryNumber = 0, _error = void 0, delayFactor = 100) { + const delay = 2 ** retryNumber * delayFactor; + const randomSum = delay * 0.2 * Math.random(); + return delay + randomSum; +} +var DEFAULT_OPTIONS = { + retries: 3, + retryCondition: isNetworkOrIdempotentRequestError, + retryDelay: noDelay, + shouldResetTimeout: false, + onRetry: () => { + } +}; +function getRequestOptions(config, defaultOptions) { + return { ...DEFAULT_OPTIONS, ...defaultOptions, ...config.retry }; +} +function setCurrentState(config, defaultOptions) { + const currentState = getRequestOptions(config, defaultOptions || {}); + currentState.retryCount = currentState.retryCount || 0; + currentState.lastRequestTime = currentState.lastRequestTime || Date.now(); + config.retry = currentState; + return currentState; +} +async function shouldRetry(currentState, error) { + const { retries, retryCondition } = currentState; + const shouldRetryOrPromise = (currentState.retryCount || 0) < retries && retryCondition(error); + if (typeof shouldRetryOrPromise === "object") { + try { + const shouldRetryPromiseResult = await shouldRetryOrPromise; + return shouldRetryPromiseResult !== false; + } catch (_err) { + return false; + } + } + return shouldRetryOrPromise; +} +var axiosRetry = (axiosInstance, defaultOptions) => { + const requestInterceptorId = axiosInstance.interceptors.request.use( + (config) => { + setCurrentState(config, defaultOptions); + return config; + } + ); + const responseInterceptorId = axiosInstance.interceptors.response.use( + null, + async (error) => { + const { config } = error; + if (!config) { + return Promise.reject(error); + } + const currentState = setCurrentState(config, defaultOptions); + if (await shouldRetry(currentState, error)) { + currentState.retryCount += 1; + const { retryDelay, shouldResetTimeout, onRetry } = currentState; + const delay = retryDelay(currentState.retryCount, error); + if (!shouldResetTimeout && config.timeout && currentState.lastRequestTime) { + const lastRequestDuration = Date.now() - currentState.lastRequestTime; + const timeout = config.timeout - lastRequestDuration - delay; + if (timeout <= 0) { + return Promise.reject(error); + } + config.timeout = timeout; + } + config.transformRequest = [(data) => data]; + await onRetry(currentState.retryCount, error, config); + return new Promise((resolve) => { + setTimeout(() => resolve(axiosInstance(config)), delay); + }); + } + return Promise.reject(error); + } + ); + return { requestInterceptorId, responseInterceptorId }; +}; +axiosRetry.isNetworkError = isNetworkError; +axiosRetry.isSafeRequestError = isSafeRequestError; +axiosRetry.isIdempotentRequestError = isIdempotentRequestError; +axiosRetry.isNetworkOrIdempotentRequestError = isNetworkOrIdempotentRequestError; +axiosRetry.exponentialDelay = exponentialDelay; +axiosRetry.isRetryableError = isRetryableError; +var retry_default = axiosRetry; + +export { DEFAULT_OPTIONS, retry_default as default, exponentialDelay, isIdempotentRequestError, isNetworkError, isNetworkOrIdempotentRequestError, isRetryableError, isSafeRequestError }; diff --git a/node_modules/feaxios/package.json b/node_modules/feaxios/package.json new file mode 100644 index 000000000..21034ed82 --- /dev/null +++ b/node_modules/feaxios/package.json @@ -0,0 +1,71 @@ +{ + "name": "feaxios", + "version": "0.0.23", + "description": "Tiny Fetch wrapper that provides a similar API to Axios", + "main": "dist/index.js", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "./retry": { + "import": { + "types": "./dist/retry.d.ts", + "default": "./dist/retry.mjs" + }, + "require": { + "types": "./dist/retry.d.ts", + "default": "./dist/retry.js" + } + } + }, + "typesVersions": { + "*": { + "retry": [ + "./dist/retry.d.ts" + ] + } + }, + "files": [ + "dist" + ], + "eslintConfig": { + "extends": [ + "prettier" + ] + }, + "repository": "divyam234/feaxios", + "keywords": [ + "axios", + "fetch" + ], + "license": "MIT", + "homepage": "https://github.com/divyam234/feaxios", + "devDependencies": { + "@types/node": "^20.11.17", + "@vitest/ui": "^1.2.2", + "msw": "^2.2.0", + "nock": "^13.5.1", + "prettier": "^3.2.5", + "tsup": "^8.0.2", + "typescript": "^5.3.3", + "vitest": "^1.2.2" + }, + "dependencies": { + "is-retry-allowed": "^3.0.0" + }, + "scripts": { + "build": "tsup", + "typecheck": "tsc --noEmit", + "test": "vitest", + "test-ui": "vitest --ui", + "format": "prettier --write './**/*.{ts,md}'", + "format:check": "prettier --check './**/*.{ts,md}'" + } +} \ No newline at end of file diff --git a/node_modules/follow-redirects/LICENSE b/node_modules/follow-redirects/LICENSE new file mode 100644 index 000000000..742cbada5 --- /dev/null +++ b/node_modules/follow-redirects/LICENSE @@ -0,0 +1,18 @@ +Copyright 2014–present Olivier Lalonde , James Talmage , Ruben Verborgh + +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/node_modules/follow-redirects/README.md b/node_modules/follow-redirects/README.md new file mode 100644 index 000000000..eb869a6f0 --- /dev/null +++ b/node_modules/follow-redirects/README.md @@ -0,0 +1,155 @@ +## Follow Redirects + +Drop-in replacement for Node's `http` and `https` modules that automatically follows redirects. + +[![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) +[![Build Status](https://github.com/follow-redirects/follow-redirects/workflows/CI/badge.svg)](https://github.com/follow-redirects/follow-redirects/actions) +[![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master) +[![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) +[![Sponsor on GitHub](https://img.shields.io/static/v1?label=Sponsor&message=%F0%9F%92%96&logo=GitHub)](https://github.com/sponsors/RubenVerborgh) + +`follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback) + methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback) + modules, with the exception that they will seamlessly follow redirects. + +```javascript +const { http, https } = require('follow-redirects'); + +http.get('http://bit.ly/900913', response => { + response.on('data', chunk => { + console.log(chunk); + }); +}).on('error', err => { + console.error(err); +}); +``` + +You can inspect the final redirected URL through the `responseUrl` property on the `response`. +If no redirection happened, `responseUrl` is the original request URL. + +```javascript +const request = https.request({ + host: 'bitly.com', + path: '/UHfDGO', +}, response => { + console.log(response.responseUrl); + // 'http://duckduckgo.com/robots.txt' +}); +request.end(); +``` + +## Options +### Global options +Global options are set directly on the `follow-redirects` module: + +```javascript +const followRedirects = require('follow-redirects'); +followRedirects.maxRedirects = 10; +followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB +``` + +The following global options are supported: + +- `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. + +- `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. + +### Per-request options +Per-request options are set by passing an `options` object: + +```javascript +const url = require('url'); +const { http, https } = require('follow-redirects'); + +const options = url.parse('http://bit.ly/900913'); +options.maxRedirects = 10; +options.beforeRedirect = (options, response, request) => { + // Use this to adjust the request options upon redirecting, + // to inspect the latest response headers, + // or to cancel the request by throwing an error + + // response.headers = the redirect response headers + // response.statusCode = the redirect response code (eg. 301, 307, etc.) + + // request.url = the requested URL that resulted in a redirect + // request.headers = the headers in the request that resulted in a redirect + // request.method = the method of the request that resulted in a redirect + if (options.hostname === "example.com") { + options.auth = "user:password"; + } +}; +http.request(options); +``` + +In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback), +the following per-request options are supported: +- `followRedirects` (default: `true`) – whether redirects should be followed. + +- `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. + +- `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. + +- `beforeRedirect` (default: `undefined`) – optionally change the request `options` on redirects, or abort the request by throwing an error. + +- `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }` + +- `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object. + + +### Advanced usage +By default, `follow-redirects` will use the Node.js default implementations +of [`http`](https://nodejs.org/api/http.html) +and [`https`](https://nodejs.org/api/https.html). +To enable features such as caching and/or intermediate request tracking, +you might instead want to wrap `follow-redirects` around custom protocol implementations: + +```javascript +const { http, https } = require('follow-redirects').wrap({ + http: require('your-custom-http'), + https: require('your-custom-https'), +}); +``` + +Such custom protocols only need an implementation of the `request` method. + +## Browser Usage + +Due to the way the browser works, +the `http` and `https` browser equivalents perform redirects by default. + +By requiring `follow-redirects` this way: +```javascript +const http = require('follow-redirects/http'); +const https = require('follow-redirects/https'); +``` +you can easily tell webpack and friends to replace +`follow-redirect` by the built-in versions: + +```json +{ + "follow-redirects/http" : "http", + "follow-redirects/https" : "https" +} +``` + +## Contributing + +Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues) + detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied + by tests. You can run the test suite locally with a simple `npm test` command. + +## Debug Logging + +`follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging + set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test + suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well. + +## Authors + +- [Ruben Verborgh](https://ruben.verborgh.org/) +- [Olivier Lalonde](mailto:olalonde@gmail.com) +- [James Talmage](mailto:james@talmage.io) + +## License + +[MIT License](https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE) diff --git a/node_modules/follow-redirects/debug.js b/node_modules/follow-redirects/debug.js new file mode 100644 index 000000000..decb77ded --- /dev/null +++ b/node_modules/follow-redirects/debug.js @@ -0,0 +1,15 @@ +var debug; + +module.exports = function () { + if (!debug) { + try { + /* eslint global-require: off */ + debug = require("debug")("follow-redirects"); + } + catch (error) { /* */ } + if (typeof debug !== "function") { + debug = function () { /* */ }; + } + } + debug.apply(null, arguments); +}; diff --git a/node_modules/follow-redirects/http.js b/node_modules/follow-redirects/http.js new file mode 100644 index 000000000..695e35617 --- /dev/null +++ b/node_modules/follow-redirects/http.js @@ -0,0 +1 @@ +module.exports = require("./").http; diff --git a/node_modules/follow-redirects/https.js b/node_modules/follow-redirects/https.js new file mode 100644 index 000000000..d21c921d9 --- /dev/null +++ b/node_modules/follow-redirects/https.js @@ -0,0 +1 @@ +module.exports = require("./").https; diff --git a/node_modules/follow-redirects/index.js b/node_modules/follow-redirects/index.js new file mode 100644 index 000000000..a30b32cdf --- /dev/null +++ b/node_modules/follow-redirects/index.js @@ -0,0 +1,686 @@ +var url = require("url"); +var URL = url.URL; +var http = require("http"); +var https = require("https"); +var Writable = require("stream").Writable; +var assert = require("assert"); +var debug = require("./debug"); + +// Preventive platform detection +// istanbul ignore next +(function detectUnsupportedEnvironment() { + var looksLikeNode = typeof process !== "undefined"; + var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined"; + var looksLikeV8 = isFunction(Error.captureStackTrace); + if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) { + console.warn("The follow-redirects package should be excluded from browser builds."); + } +}()); + +// Whether to use the native URL object or the legacy url module +var useNativeURL = false; +try { + assert(new URL("")); +} +catch (error) { + useNativeURL = error.code === "ERR_INVALID_URL"; +} + +// URL fields to preserve in copy operations +var preservedUrlFields = [ + "auth", + "host", + "hostname", + "href", + "path", + "pathname", + "port", + "protocol", + "query", + "search", + "hash", +]; + +// Create handlers that pass events from native requests +var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; +var eventHandlers = Object.create(null); +events.forEach(function (event) { + eventHandlers[event] = function (arg1, arg2, arg3) { + this._redirectable.emit(event, arg1, arg2, arg3); + }; +}); + +// Error types with codes +var InvalidUrlError = createErrorType( + "ERR_INVALID_URL", + "Invalid URL", + TypeError +); +var RedirectionError = createErrorType( + "ERR_FR_REDIRECTION_FAILURE", + "Redirected request failed" +); +var TooManyRedirectsError = createErrorType( + "ERR_FR_TOO_MANY_REDIRECTS", + "Maximum number of redirects exceeded", + RedirectionError +); +var MaxBodyLengthExceededError = createErrorType( + "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", + "Request body larger than maxBodyLength limit" +); +var WriteAfterEndError = createErrorType( + "ERR_STREAM_WRITE_AFTER_END", + "write after end" +); + +// istanbul ignore next +var destroy = Writable.prototype.destroy || noop; + +// An HTTP(S) request that can be redirected +function RedirectableRequest(options, responseCallback) { + // Initialize the request + Writable.call(this); + this._sanitizeOptions(options); + this._options = options; + this._ended = false; + this._ending = false; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; + + // Attach a callback if passed + if (responseCallback) { + this.on("response", responseCallback); + } + + // React to responses of native requests + var self = this; + this._onNativeResponse = function (response) { + try { + self._processResponse(response); + } + catch (cause) { + self.emit("error", cause instanceof RedirectionError ? + cause : new RedirectionError({ cause: cause })); + } + }; + + // Perform the first request + this._performRequest(); +} +RedirectableRequest.prototype = Object.create(Writable.prototype); + +RedirectableRequest.prototype.abort = function () { + destroyRequest(this._currentRequest); + this._currentRequest.abort(); + this.emit("abort"); +}; + +RedirectableRequest.prototype.destroy = function (error) { + destroyRequest(this._currentRequest, error); + destroy.call(this, error); + return this; +}; + +// Writes buffered data to the current native request +RedirectableRequest.prototype.write = function (data, encoding, callback) { + // Writing is not allowed if end has been called + if (this._ending) { + throw new WriteAfterEndError(); + } + + // Validate input and shift parameters if necessary + if (!isString(data) && !isBuffer(data)) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); + } + if (isFunction(encoding)) { + callback = encoding; + encoding = null; + } + + // Ignore empty buffers, since writing them doesn't invoke the callback + // https://github.com/nodejs/node/issues/22066 + if (data.length === 0) { + if (callback) { + callback(); + } + return; + } + // Only write when we don't exceed the maximum body length + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data: data, encoding: encoding }); + this._currentRequest.write(data, encoding, callback); + } + // Error when we exceed the maximum body length + else { + this.emit("error", new MaxBodyLengthExceededError()); + this.abort(); + } +}; + +// Ends the current native request +RedirectableRequest.prototype.end = function (data, encoding, callback) { + // Shift parameters if necessary + if (isFunction(data)) { + callback = data; + data = encoding = null; + } + else if (isFunction(encoding)) { + callback = encoding; + encoding = null; + } + + // Write data if needed and end + if (!data) { + this._ended = this._ending = true; + this._currentRequest.end(null, null, callback); + } + else { + var self = this; + var currentRequest = this._currentRequest; + this.write(data, encoding, function () { + self._ended = true; + currentRequest.end(null, null, callback); + }); + this._ending = true; + } +}; + +// Sets a header value on the current native request +RedirectableRequest.prototype.setHeader = function (name, value) { + this._options.headers[name] = value; + this._currentRequest.setHeader(name, value); +}; + +// Clears a header value on the current native request +RedirectableRequest.prototype.removeHeader = function (name) { + delete this._options.headers[name]; + this._currentRequest.removeHeader(name); +}; + +// Global timeout for all underlying requests +RedirectableRequest.prototype.setTimeout = function (msecs, callback) { + var self = this; + + // Destroys the socket on timeout + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); + } + + // Sets up a timer to trigger a timeout event + function startTimer(socket) { + if (self._timeout) { + clearTimeout(self._timeout); + } + self._timeout = setTimeout(function () { + self.emit("timeout"); + clearTimer(); + }, msecs); + destroyOnTimeout(socket); + } + + // Stops a timeout from triggering + function clearTimer() { + // Clear the timeout + if (self._timeout) { + clearTimeout(self._timeout); + self._timeout = null; + } + + // Clean up all attached listeners + self.removeListener("abort", clearTimer); + self.removeListener("error", clearTimer); + self.removeListener("response", clearTimer); + self.removeListener("close", clearTimer); + if (callback) { + self.removeListener("timeout", callback); + } + if (!self.socket) { + self._currentRequest.removeListener("socket", startTimer); + } + } + + // Attach callback if passed + if (callback) { + this.on("timeout", callback); + } + + // Start the timer if or when the socket is opened + if (this.socket) { + startTimer(this.socket); + } + else { + this._currentRequest.once("socket", startTimer); + } + + // Clean up on events + this.on("socket", destroyOnTimeout); + this.on("abort", clearTimer); + this.on("error", clearTimer); + this.on("response", clearTimer); + this.on("close", clearTimer); + + return this; +}; + +// Proxy all other public ClientRequest methods +[ + "flushHeaders", "getHeader", + "setNoDelay", "setSocketKeepAlive", +].forEach(function (method) { + RedirectableRequest.prototype[method] = function (a, b) { + return this._currentRequest[method](a, b); + }; +}); + +// Proxy all public ClientRequest properties +["aborted", "connection", "socket"].forEach(function (property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function () { return this._currentRequest[property]; }, + }); +}); + +RedirectableRequest.prototype._sanitizeOptions = function (options) { + // Ensure headers are always present + if (!options.headers) { + options.headers = {}; + } + + // Since http.request treats host as an alias of hostname, + // but the url module interprets host as hostname plus port, + // eliminate the host property to avoid confusion. + if (options.host) { + // Use hostname if set, because it has precedence + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } + + // Complete the URL object when necessary + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; + } + else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } + } +}; + + +// Executes the next native request (initial or redirect) +RedirectableRequest.prototype._performRequest = function () { + // Load the native protocol + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + throw new TypeError("Unsupported protocol " + protocol); + } + + // If specified, use the agent corresponding to the protocol + // (HTTP and HTTPS use different types of agents) + if (this._options.agents) { + var scheme = protocol.slice(0, -1); + this._options.agent = this._options.agents[scheme]; + } + + // Create the native request and set up its event handlers + var request = this._currentRequest = + nativeProtocol.request(this._options, this._onNativeResponse); + request._redirectable = this; + for (var event of events) { + request.on(event, eventHandlers[event]); + } + + // RFC7230§5.3.1: When making a request directly to an origin server, […] + // a client MUST send only the absolute path […] as the request-target. + this._currentUrl = /^\//.test(this._options.path) ? + url.format(this._options) : + // When making a request to a proxy, […] + // a client MUST send the target URI in absolute-form […]. + this._options.path; + + // End a redirected request + // (The first request must be ended explicitly with RedirectableRequest#end) + if (this._isRedirect) { + // Write the request entity and end + var i = 0; + var self = this; + var buffers = this._requestBodyBuffers; + (function writeNext(error) { + // Only write if this request has not been redirected yet + // istanbul ignore else + if (request === self._currentRequest) { + // Report any write errors + // istanbul ignore if + if (error) { + self.emit("error", error); + } + // Write the next buffer if there are still left + else if (i < buffers.length) { + var buffer = buffers[i++]; + // istanbul ignore else + if (!request.finished) { + request.write(buffer.data, buffer.encoding, writeNext); + } + } + // End the request if `end` has been called on us + else if (self._ended) { + request.end(); + } + } + }()); + } +}; + +// Processes a response from the current native request +RedirectableRequest.prototype._processResponse = function (response) { + // Store the redirected response + var statusCode = response.statusCode; + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode: statusCode, + }); + } + + // RFC7231§6.4: The 3xx (Redirection) class of status code indicates + // that further action needs to be taken by the user agent in order to + // fulfill the request. If a Location header field is provided, + // the user agent MAY automatically redirect its request to the URI + // referenced by the Location field value, + // even if the specific status code is not understood. + + // If the response is not a redirect; return it as-is + var location = response.headers.location; + if (!location || this._options.followRedirects === false || + statusCode < 300 || statusCode >= 400) { + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); + + // Clean up + this._requestBodyBuffers = []; + return; + } + + // The response is a redirect, so abort the current request + destroyRequest(this._currentRequest); + // Discard the remainder of the response to avoid waiting for data + response.destroy(); + + // RFC7231§6.4: A client SHOULD detect and intervene + // in cyclical redirections (i.e., "infinite" redirection loops). + if (++this._redirectCount > this._options.maxRedirects) { + throw new TooManyRedirectsError(); + } + + // Store the request headers if applicable + var requestHeaders; + var beforeRedirect = this._options.beforeRedirect; + if (beforeRedirect) { + requestHeaders = Object.assign({ + // The Host header was set by nativeProtocol.request + Host: response.req.getHeader("host"), + }, this._options.headers); + } + + // RFC7231§6.4: Automatic redirection needs to done with + // care for methods not known to be safe, […] + // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change + // the request method from POST to GET for the subsequent request. + var method = this._options.method; + if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || + // RFC7231§6.4.4: The 303 (See Other) status code indicates that + // the server is redirecting the user agent to a different resource […] + // A user agent can perform a retrieval request targeting that URI + // (a GET or HEAD request if using HTTP) […] + (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { + this._options.method = "GET"; + // Drop a possible entity and headers related to it + this._requestBodyBuffers = []; + removeMatchingHeaders(/^content-/i, this._options.headers); + } + + // Drop the Host header, as the redirect might lead to a different host + var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); + + // If the redirect is relative, carry over the host of the last request + var currentUrlParts = parseUrl(this._currentUrl); + var currentHost = currentHostHeader || currentUrlParts.host; + var currentUrl = /^\w+:/.test(location) ? this._currentUrl : + url.format(Object.assign(currentUrlParts, { host: currentHost })); + + // Create the redirected request + var redirectUrl = resolveUrl(location, currentUrl); + debug("redirecting to", redirectUrl.href); + this._isRedirect = true; + spreadUrlObject(redirectUrl, this._options); + + // Drop confidential headers when redirecting to a less secure protocol + // or to a different domain that is not a superdomain + if (redirectUrl.protocol !== currentUrlParts.protocol && + redirectUrl.protocol !== "https:" || + redirectUrl.host !== currentHost && + !isSubdomain(redirectUrl.host, currentHost)) { + removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers); + } + + // Evaluate the beforeRedirect callback + if (isFunction(beforeRedirect)) { + var responseDetails = { + headers: response.headers, + statusCode: statusCode, + }; + var requestDetails = { + url: currentUrl, + method: method, + headers: requestHeaders, + }; + beforeRedirect(this._options, responseDetails, requestDetails); + this._sanitizeOptions(this._options); + } + + // Perform the redirected request + this._performRequest(); +}; + +// Wraps the key/value object of protocols with redirect functionality +function wrap(protocols) { + // Default settings + var exports = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024, + }; + + // Wrap each protocol + var nativeProtocols = {}; + Object.keys(protocols).forEach(function (scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); + + // Executes a request, following redirects + function request(input, options, callback) { + // Parse parameters, ensuring that input is an object + if (isURL(input)) { + input = spreadUrlObject(input); + } + else if (isString(input)) { + input = spreadUrlObject(parseUrl(input)); + } + else { + callback = options; + options = validateUrl(input); + input = { protocol: protocol }; + } + if (isFunction(options)) { + callback = options; + options = null; + } + + // Set defaults + options = Object.assign({ + maxRedirects: exports.maxRedirects, + maxBodyLength: exports.maxBodyLength, + }, input, options); + options.nativeProtocols = nativeProtocols; + if (!isString(options.host) && !isString(options.hostname)) { + options.hostname = "::1"; + } + + assert.equal(options.protocol, protocol, "protocol mismatch"); + debug("options", options); + return new RedirectableRequest(options, callback); + } + + // Executes a GET request, following redirects + function get(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } + + // Expose the properties on the wrapped protocol + Object.defineProperties(wrappedProtocol, { + request: { value: request, configurable: true, enumerable: true, writable: true }, + get: { value: get, configurable: true, enumerable: true, writable: true }, + }); + }); + return exports; +} + +function noop() { /* empty */ } + +function parseUrl(input) { + var parsed; + // istanbul ignore else + if (useNativeURL) { + parsed = new URL(input); + } + else { + // Ensure the URL is valid and absolute + parsed = validateUrl(url.parse(input)); + if (!isString(parsed.protocol)) { + throw new InvalidUrlError({ input }); + } + } + return parsed; +} + +function resolveUrl(relative, base) { + // istanbul ignore next + return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative)); +} + +function validateUrl(input) { + if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { + throw new InvalidUrlError({ input: input.href || input }); + } + if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { + throw new InvalidUrlError({ input: input.href || input }); + } + return input; +} + +function spreadUrlObject(urlObject, target) { + var spread = target || {}; + for (var key of preservedUrlFields) { + spread[key] = urlObject[key]; + } + + // Fix IPv6 hostname + if (spread.hostname.startsWith("[")) { + spread.hostname = spread.hostname.slice(1, -1); + } + // Ensure port is a number + if (spread.port !== "") { + spread.port = Number(spread.port); + } + // Concatenate path + spread.path = spread.search ? spread.pathname + spread.search : spread.pathname; + + return spread; +} + +function removeMatchingHeaders(regex, headers) { + var lastValue; + for (var header in headers) { + if (regex.test(header)) { + lastValue = headers[header]; + delete headers[header]; + } + } + return (lastValue === null || typeof lastValue === "undefined") ? + undefined : String(lastValue).trim(); +} + +function createErrorType(code, message, baseClass) { + // Create constructor + function CustomError(properties) { + // istanbul ignore else + if (isFunction(Error.captureStackTrace)) { + Error.captureStackTrace(this, this.constructor); + } + Object.assign(this, properties || {}); + this.code = code; + this.message = this.cause ? message + ": " + this.cause.message : message; + } + + // Attach constructor and set default properties + CustomError.prototype = new (baseClass || Error)(); + Object.defineProperties(CustomError.prototype, { + constructor: { + value: CustomError, + enumerable: false, + }, + name: { + value: "Error [" + code + "]", + enumerable: false, + }, + }); + return CustomError; +} + +function destroyRequest(request, error) { + for (var event of events) { + request.removeListener(event, eventHandlers[event]); + } + request.on("error", noop); + request.destroy(error); +} + +function isSubdomain(subdomain, domain) { + assert(isString(subdomain) && isString(domain)); + var dot = subdomain.length - domain.length - 1; + return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); +} + +function isString(value) { + return typeof value === "string" || value instanceof String; +} + +function isFunction(value) { + return typeof value === "function"; +} + +function isBuffer(value) { + return typeof value === "object" && ("length" in value); +} + +function isURL(value) { + return URL && value instanceof URL; +} + +// Exports +module.exports = wrap({ http: http, https: https }); +module.exports.wrap = wrap; diff --git a/node_modules/follow-redirects/package.json b/node_modules/follow-redirects/package.json new file mode 100644 index 000000000..6f491e18e --- /dev/null +++ b/node_modules/follow-redirects/package.json @@ -0,0 +1,58 @@ +{ + "name": "follow-redirects", + "version": "1.15.9", + "description": "HTTP and HTTPS modules that follow redirects.", + "license": "MIT", + "main": "index.js", + "files": [ + "*.js" + ], + "engines": { + "node": ">=4.0" + }, + "scripts": { + "lint": "eslint *.js test", + "test": "nyc mocha" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/follow-redirects/follow-redirects.git" + }, + "homepage": "https://github.com/follow-redirects/follow-redirects", + "bugs": { + "url": "https://github.com/follow-redirects/follow-redirects/issues" + }, + "keywords": [ + "http", + "https", + "url", + "redirect", + "client", + "location", + "utility" + ], + "author": "Ruben Verborgh (https://ruben.verborgh.org/)", + "contributors": [ + "Olivier Lalonde (http://www.syskall.com)", + "James Talmage " + ], + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "peerDependenciesMeta": { + "debug": { + "optional": true + } + }, + "devDependencies": { + "concat-stream": "^2.0.0", + "eslint": "^5.16.0", + "express": "^4.16.4", + "lolex": "^3.1.0", + "mocha": "^6.0.2", + "nyc": "^14.1.1" + } +} diff --git a/node_modules/form-data/License b/node_modules/form-data/License new file mode 100644 index 000000000..c7ff12a2f --- /dev/null +++ b/node_modules/form-data/License @@ -0,0 +1,19 @@ +Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and 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/node_modules/form-data/Readme.md b/node_modules/form-data/Readme.md new file mode 100644 index 000000000..b09df6a42 --- /dev/null +++ b/node_modules/form-data/Readme.md @@ -0,0 +1,358 @@ +# Form-Data [![NPM Module](https://img.shields.io/npm/v/form-data.svg)](https://www.npmjs.com/package/form-data) [![Join the chat at https://gitter.im/form-data/form-data](http://form-data.github.io/images/gitterbadge.svg)](https://gitter.im/form-data/form-data) + +A library to create readable ```"multipart/form-data"``` streams. Can be used to submit forms and file uploads to other web applications. + +The API of this library is inspired by the [XMLHttpRequest-2 FormData Interface][xhr2-fd]. + +[xhr2-fd]: http://dev.w3.org/2006/webapi/XMLHttpRequest-2/Overview.html#the-formdata-interface + +[![Linux Build](https://img.shields.io/travis/form-data/form-data/master.svg?label=linux:6.x-12.x)](https://travis-ci.org/form-data/form-data) +[![MacOS Build](https://img.shields.io/travis/form-data/form-data/master.svg?label=macos:6.x-12.x)](https://travis-ci.org/form-data/form-data) +[![Windows Build](https://img.shields.io/travis/form-data/form-data/master.svg?label=windows:6.x-12.x)](https://travis-ci.org/form-data/form-data) + +[![Coverage Status](https://img.shields.io/coveralls/form-data/form-data/master.svg?label=code+coverage)](https://coveralls.io/github/form-data/form-data?branch=master) +[![Dependency Status](https://img.shields.io/david/form-data/form-data.svg)](https://david-dm.org/form-data/form-data) + +## Install + +``` +npm install --save form-data +``` + +## Usage + +In this example we are constructing a form with 3 fields that contain a string, +a buffer and a file stream. + +``` javascript +var FormData = require('form-data'); +var fs = require('fs'); + +var form = new FormData(); +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); +``` + +Also you can use http-response stream: + +``` javascript +var FormData = require('form-data'); +var http = require('http'); + +var form = new FormData(); + +http.request('http://nodejs.org/images/logo.png', function(response) { + form.append('my_field', 'my value'); + form.append('my_buffer', new Buffer(10)); + form.append('my_logo', response); +}); +``` + +Or @mikeal's [request](https://github.com/request/request) stream: + +``` javascript +var FormData = require('form-data'); +var request = require('request'); + +var form = new FormData(); + +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_logo', request('http://nodejs.org/images/logo.png')); +``` + +In order to submit this form to a web application, call ```submit(url, [callback])``` method: + +``` javascript +form.submit('http://example.org/', function(err, res) { + // res – response object (http.IncomingMessage) // + res.resume(); +}); + +``` + +For more advanced request manipulations ```submit()``` method returns ```http.ClientRequest``` object, or you can choose from one of the alternative submission methods. + +### Custom options + +You can provide custom options, such as `maxDataSize`: + +``` javascript +var FormData = require('form-data'); + +var form = new FormData({ maxDataSize: 20971520 }); +form.append('my_field', 'my value'); +form.append('my_buffer', /* something big */); +``` + +List of available options could be found in [combined-stream](https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15) + +### Alternative submission methods + +You can use node's http client interface: + +``` javascript +var http = require('http'); + +var request = http.request({ + method: 'post', + host: 'example.org', + path: '/upload', + headers: form.getHeaders() +}); + +form.pipe(request); + +request.on('response', function(res) { + console.log(res.statusCode); +}); +``` + +Or if you would prefer the `'Content-Length'` header to be set for you: + +``` javascript +form.submit('example.org/upload', function(err, res) { + console.log(res.statusCode); +}); +``` + +To use custom headers and pre-known length in parts: + +``` javascript +var CRLF = '\r\n'; +var form = new FormData(); + +var options = { + header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF, + knownLength: 1 +}; + +form.append('my_buffer', buffer, options); + +form.submit('http://example.com/', function(err, res) { + if (err) throw err; + console.log('Done'); +}); +``` + +Form-Data can recognize and fetch all the required information from common types of streams (```fs.readStream```, ```http.response``` and ```mikeal's request```), for some other types of streams you'd need to provide "file"-related information manually: + +``` javascript +someModule.stream(function(err, stdout, stderr) { + if (err) throw err; + + var form = new FormData(); + + form.append('file', stdout, { + filename: 'unicycle.jpg', // ... or: + filepath: 'photos/toys/unicycle.jpg', + contentType: 'image/jpeg', + knownLength: 19806 + }); + + form.submit('http://example.com/', function(err, res) { + if (err) throw err; + console.log('Done'); + }); +}); +``` + +The `filepath` property overrides `filename` and may contain a relative path. This is typically used when uploading [multiple files from a directory](https://wicg.github.io/entries-api/#dom-htmlinputelement-webkitdirectory). + +For edge cases, like POST request to URL with query string or to pass HTTP auth credentials, object can be passed to `form.submit()` as first parameter: + +``` javascript +form.submit({ + host: 'example.com', + path: '/probably.php?extra=params', + auth: 'username:password' +}, function(err, res) { + console.log(res.statusCode); +}); +``` + +In case you need to also send custom HTTP headers with the POST request, you can use the `headers` key in first parameter of `form.submit()`: + +``` javascript +form.submit({ + host: 'example.com', + path: '/surelynot.php', + headers: {'x-test-header': 'test-header-value'} +}, function(err, res) { + console.log(res.statusCode); +}); +``` + +### Methods + +- [_Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] )](https://github.com/form-data/form-data#void-append-string-field-mixed-value--mixed-options-). +- [_Headers_ getHeaders( [**Headers** _userHeaders_] )](https://github.com/form-data/form-data#array-getheaders-array-userheaders-) +- [_String_ getBoundary()](https://github.com/form-data/form-data#string-getboundary) +- [_Void_ setBoundary()](https://github.com/form-data/form-data#void-setboundary) +- [_Buffer_ getBuffer()](https://github.com/form-data/form-data#buffer-getbuffer) +- [_Integer_ getLengthSync()](https://github.com/form-data/form-data#integer-getlengthsync) +- [_Integer_ getLength( **function** _callback_ )](https://github.com/form-data/form-data#integer-getlength-function-callback-) +- [_Boolean_ hasKnownLength()](https://github.com/form-data/form-data#boolean-hasknownlength) +- [_Request_ submit( _params_, **function** _callback_ )](https://github.com/form-data/form-data#request-submit-params-function-callback-) +- [_String_ toString()](https://github.com/form-data/form-data#string-tostring) + +#### _Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] ) +Append data to the form. You can submit about any format (string, integer, boolean, buffer, etc.). However, Arrays are not supported and need to be turned into strings by the user. +```javascript +var form = new FormData(); +form.append( 'my_string', 'my value' ); +form.append( 'my_integer', 1 ); +form.append( 'my_boolean', true ); +form.append( 'my_buffer', new Buffer(10) ); +form.append( 'my_array_as_json', JSON.stringify( ['bird','cute'] ) ) +``` + +You may provide a string for options, or an object. +```javascript +// Set filename by providing a string for options +form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), 'bar.jpg' ); + +// provide an object. +form.append( 'my_file', fs.createReadStream('/foo/bar.jpg'), {filename: 'bar.jpg', contentType: 'image/jpeg', knownLength: 19806} ); +``` + +#### _Headers_ getHeaders( [**Headers** _userHeaders_] ) +This method adds the correct `content-type` header to the provided array of `userHeaders`. + +#### _String_ getBoundary() +Return the boundary of the formData. By default, the boundary consists of 26 `-` followed by 24 numbers +for example: +```javascript +--------------------------515890814546601021194782 +``` + +#### _Void_ setBoundary(String _boundary_) +Set the boundary string, overriding the default behavior described above. + +_Note: The boundary must be unique and may not appear in the data._ + +#### _Buffer_ getBuffer() +Return the full formdata request package, as a Buffer. You can insert this Buffer in e.g. Axios to send multipart data. +```javascript +var form = new FormData(); +form.append( 'my_buffer', Buffer.from([0x4a,0x42,0x20,0x52,0x6f,0x63,0x6b,0x73]) ); +form.append( 'my_file', fs.readFileSync('/foo/bar.jpg') ); + +axios.post( 'https://example.com/path/to/api', + form.getBuffer(), + form.getHeaders() + ) +``` +**Note:** Because the output is of type Buffer, you can only append types that are accepted by Buffer: *string, Buffer, ArrayBuffer, Array, or Array-like Object*. A ReadStream for example will result in an error. + +#### _Integer_ getLengthSync() +Same as `getLength` but synchronous. + +_Note: getLengthSync __doesn't__ calculate streams length._ + +#### _Integer_ getLength( **function** _callback_ ) +Returns the `Content-Length` async. The callback is used to handle errors and continue once the length has been calculated +```javascript +this.getLength(function(err, length) { + if (err) { + this._error(err); + return; + } + + // add content length + request.setHeader('Content-Length', length); + + ... +}.bind(this)); +``` + +#### _Boolean_ hasKnownLength() +Checks if the length of added values is known. + +#### _Request_ submit( _params_, **function** _callback_ ) +Submit the form to a web application. +```javascript +var form = new FormData(); +form.append( 'my_string', 'Hello World' ); + +form.submit( 'http://example.com/', function(err, res) { + // res – response object (http.IncomingMessage) // + res.resume(); +} ); +``` + +#### _String_ toString() +Returns the form data as a string. Don't use this if you are sending files or buffers, use `getBuffer()` instead. + +### Integration with other libraries + +#### Request + +Form submission using [request](https://github.com/request/request): + +```javascript +var formData = { + my_field: 'my_value', + my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), +}; + +request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) { + if (err) { + return console.error('upload failed:', err); + } + console.log('Upload successful! Server responded with:', body); +}); +``` + +For more details see [request readme](https://github.com/request/request#multipartform-data-multipart-form-uploads). + +#### node-fetch + +You can also submit a form using [node-fetch](https://github.com/bitinn/node-fetch): + +```javascript +var form = new FormData(); + +form.append('a', 1); + +fetch('http://example.com', { method: 'POST', body: form }) + .then(function(res) { + return res.json(); + }).then(function(json) { + console.log(json); + }); +``` + +#### axios + +In Node.js you can post a file using [axios](https://github.com/axios/axios): +```javascript +const form = new FormData(); +const stream = fs.createReadStream(PATH_TO_FILE); + +form.append('image', stream); + +// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders` +const formHeaders = form.getHeaders(); + +axios.post('http://example.com', form, { + headers: { + ...formHeaders, + }, +}) +.then(response => response) +.catch(error => error) +``` + +## Notes + +- ```getLengthSync()``` method DOESN'T calculate length for streams, use ```knownLength``` options as workaround. +- ```getLength(cb)``` will send an error as first parameter of callback if stream length cannot be calculated (e.g. send in custom streams w/o using ```knownLength```). +- ```submit``` will not add `content-length` if form length is unknown or not calculable. +- Starting version `2.x` FormData has dropped support for `node@0.10.x`. +- Starting version `3.x` FormData has dropped support for `node@4.x`. + +## License + +Form-Data is released under the [MIT](License) license. diff --git a/node_modules/form-data/index.d.ts b/node_modules/form-data/index.d.ts new file mode 100644 index 000000000..295e9e9bc --- /dev/null +++ b/node_modules/form-data/index.d.ts @@ -0,0 +1,62 @@ +// Definitions by: Carlos Ballesteros Velasco +// Leon Yu +// BendingBender +// Maple Miao + +/// +import * as stream from 'stream'; +import * as http from 'http'; + +export = FormData; + +// Extracted because @types/node doesn't export interfaces. +interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?(this: stream.Readable, size: number): void; + destroy?(this: stream.Readable, error: Error | null, callback: (error: Error | null) => void): void; + autoDestroy?: boolean; +} + +interface Options extends ReadableOptions { + writable?: boolean; + readable?: boolean; + dataSize?: number; + maxDataSize?: number; + pauseStreams?: boolean; +} + +declare class FormData extends stream.Readable { + constructor(options?: Options); + append(key: string, value: any, options?: FormData.AppendOptions | string): void; + getHeaders(userHeaders?: FormData.Headers): FormData.Headers; + submit( + params: string | FormData.SubmitOptions, + callback?: (error: Error | null, response: http.IncomingMessage) => void + ): http.ClientRequest; + getBuffer(): Buffer; + setBoundary(boundary: string): void; + getBoundary(): string; + getLength(callback: (err: Error | null, length: number) => void): void; + getLengthSync(): number; + hasKnownLength(): boolean; +} + +declare namespace FormData { + interface Headers { + [key: string]: any; + } + + interface AppendOptions { + header?: string | Headers; + knownLength?: number; + filename?: string; + filepath?: string; + contentType?: string; + } + + interface SubmitOptions extends http.RequestOptions { + protocol?: 'https:' | 'http:'; + } +} diff --git a/node_modules/form-data/lib/browser.js b/node_modules/form-data/lib/browser.js new file mode 100644 index 000000000..09e7c70e6 --- /dev/null +++ b/node_modules/form-data/lib/browser.js @@ -0,0 +1,2 @@ +/* eslint-env browser */ +module.exports = typeof self == 'object' ? self.FormData : window.FormData; diff --git a/node_modules/form-data/lib/form_data.js b/node_modules/form-data/lib/form_data.js new file mode 100644 index 000000000..e05c8f1ae --- /dev/null +++ b/node_modules/form-data/lib/form_data.js @@ -0,0 +1,501 @@ +var CombinedStream = require('combined-stream'); +var util = require('util'); +var path = require('path'); +var http = require('http'); +var https = require('https'); +var parseUrl = require('url').parse; +var fs = require('fs'); +var Stream = require('stream').Stream; +var mime = require('mime-types'); +var asynckit = require('asynckit'); +var populate = require('./populate.js'); + +// Public API +module.exports = FormData; + +// make it a Stream +util.inherits(FormData, CombinedStream); + +/** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. + * + * @constructor + * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + */ +function FormData(options) { + if (!(this instanceof FormData)) { + return new FormData(options); + } + + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + + CombinedStream.call(this); + + options = options || {}; + for (var option in options) { + this[option] = options[option]; + } +} + +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; + +FormData.prototype.append = function(field, value, options) { + + options = options || {}; + + // allow filename as single option + if (typeof options == 'string') { + options = {filename: options}; + } + + var append = CombinedStream.prototype.append.bind(this); + + // all that streamy business can't handle numbers + if (typeof value == 'number') { + value = '' + value; + } + + // https://github.com/felixge/node-form-data/issues/38 + if (Array.isArray(value)) { + // Please convert your array into string + // the way web server expects it + this._error(new Error('Arrays are not supported.')); + return; + } + + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); + + append(header); + append(value); + append(footer); + + // pass along options.knownLength + this._trackLength(header, value, options); +}; + +FormData.prototype._trackLength = function(header, value, options) { + var valueLength = 0; + + // used w/ getLengthSync(), when length is known. + // e.g. for streaming directly from a remote server, + // w/ a known file a size, and not wanting to wait for + // incoming file to finish to get its size. + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); + } + + this._valueLength += valueLength; + + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + FormData.LINE_BREAK.length; + + // empty or either doesn't have path or not an http response or not a stream + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { + return; + } + + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } +}; + +FormData.prototype._lengthRetriever = function(value, callback) { + + if (value.hasOwnProperty('fd')) { + + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { + + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); + + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { + + var fileSize; + + if (err) { + callback(err); + return; + } + + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } + + // or http response + } else if (value.hasOwnProperty('httpVersion')) { + callback(null, +value.headers['content-length']); + + // or request stream http://github.com/mikeal/request + } else if (value.hasOwnProperty('httpModule')) { + // wait till response come back + value.on('response', function(response) { + value.pause(); + callback(null, +response.headers['content-length']); + }); + value.resume(); + + // something else + } else { + callback('Unknown stream'); + } +}; + +FormData.prototype._multiPartHeader = function(field, value, options) { + // custom header specified (as string)? + // it becomes responsible for boundary + // (e.g. to handle extra CRLFs on .NET servers) + if (typeof options.header == 'string') { + return options.header; + } + + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); + + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) + }; + + // allow custom headers. + if (typeof options.header == 'object') { + populate(headers, options.header); + } + + var header; + for (var prop in headers) { + if (!headers.hasOwnProperty(prop)) continue; + header = headers[prop]; + + // skip nullish headers. + if (header == null) { + continue; + } + + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; + } + + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; + } + } + + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; + +FormData.prototype._getContentDisposition = function(value, options) { + + var filename + , contentDisposition + ; + + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || value.name || value.path) { + // custom filename take precedence + // formidable and the browser add a name property + // fs- and request- streams have path property + filename = path.basename(options.filename || value.name || value.path); + } else if (value.readable && value.hasOwnProperty('httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path || ''); + } + + if (filename) { + contentDisposition = 'filename="' + filename + '"'; + } + + return contentDisposition; +}; + +FormData.prototype._getContentType = function(value, options) { + + // use custom content-type above all + var contentType = options.contentType; + + // or try `name` from formidable, browser + if (!contentType && value.name) { + contentType = mime.lookup(value.name); + } + + // or try `path` from fs-, request- streams + if (!contentType && value.path) { + contentType = mime.lookup(value.path); + } + + // or if it's http-reponse + if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { + contentType = value.headers['content-type']; + } + + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } + + // fallback to the default content type if `value` is not simple value + if (!contentType && typeof value == 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; + } + + return contentType; +}; + +FormData.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData.LINE_BREAK; + + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); + } + + next(footer); + }.bind(this); +}; + +FormData.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; + +FormData.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; + + for (header in userHeaders) { + if (userHeaders.hasOwnProperty(header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } + } + + return formHeaders; +}; + +FormData.prototype.setBoundary = function(boundary) { + this._boundary = boundary; +}; + +FormData.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); + } + + return this._boundary; +}; + +FormData.prototype.getBuffer = function() { + var dataBuffer = new Buffer.alloc( 0 ); + var boundary = this.getBoundary(); + + // Create the form content. Add Line breaks to the end of data. + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== 'function') { + + // Add content to the buffer. + if(Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); + }else { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); + } + + // Add break after content. + if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); + } + } + } + + // Add the footer and return the Buffer object. + return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); +}; + +FormData.prototype._generateBoundary = function() { + // This generates a 50 character boundary similar to those used by Firefox. + // They are optimized for boyer-moore parsing. + var boundary = '--------------------------'; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); + } + + this._boundary = boundary; +}; + +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually +// and add it as knownLength option +FormData.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; + + // Don't get confused, there are 3 "internal" streams for each keyval pair + // so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + // Some async length retrievers are present + // therefore synchronous length calculation is false. + // Please use getLength(callback) to get proper length + this._error(new Error('Cannot calculate proper length in synchronous way.')); + } + + return knownLength; +}; + +// Public API to check if length of added values is known +// https://github.com/form-data/form-data/issues/196 +// https://github.com/form-data/form-data/issues/262 +FormData.prototype.hasKnownLength = function() { + var hasKnownLength = true; + + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } + + return hasKnownLength; +}; + +FormData.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; + + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } + + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; + } + + values.forEach(function(length) { + knownLength += length; + }); + + cb(null, knownLength); + }); +}; + +FormData.prototype.submit = function(params, cb) { + var request + , options + , defaults = {method: 'post'} + ; + + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { + + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); + + // use custom params + } else { + + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; + } + } + + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); + + // https if specified, fallback to http in any other case + if (options.protocol == 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } + + // get content length and fire away + this.getLength(function(err, length) { + if (err && err !== 'Unknown stream') { + this._error(err); + return; + } + + // add content length + if (length) { + request.setHeader('Content-Length', length); + } + + this.pipe(request); + if (cb) { + var onResponse; + + var callback = function (error, responce) { + request.removeListener('error', callback); + request.removeListener('response', onResponse); + + return cb.call(this, error, responce); + }; + + onResponse = callback.bind(this, null); + + request.on('error', callback); + request.on('response', onResponse); + } + }.bind(this)); + + return request; +}; + +FormData.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); + } +}; + +FormData.prototype.toString = function () { + return '[object FormData]'; +}; diff --git a/node_modules/form-data/lib/populate.js b/node_modules/form-data/lib/populate.js new file mode 100644 index 000000000..4d35738dd --- /dev/null +++ b/node_modules/form-data/lib/populate.js @@ -0,0 +1,10 @@ +// populates missing values +module.exports = function(dst, src) { + + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); + + return dst; +}; diff --git a/node_modules/form-data/package.json b/node_modules/form-data/package.json new file mode 100644 index 000000000..9bd12c951 --- /dev/null +++ b/node_modules/form-data/package.json @@ -0,0 +1,71 @@ +{ + "author": "Felix Geisendörfer (http://debuggable.com/)", + "name": "form-data", + "description": "A library to create readable \"multipart/form-data\" streams. Can be used to submit forms and file uploads to other web applications.", + "version": "4.0.1", + "repository": { + "type": "git", + "url": "git://github.com/form-data/form-data.git" + }, + "main": "./lib/form_data", + "browser": "./lib/browser", + "typings": "./index.d.ts", + "scripts": { + "pretest": "npm run lint", + "pretests-only": "rimraf coverage test/tmp", + "tests-only": "istanbul cover test/run.js", + "posttests-only": "istanbul report lcov text", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "lint": "eslint --ext=js,mjs .", + "report": "istanbul report lcov text", + "ci-lint": "is-node-modern 8 && npm run lint || is-node-not-modern 8", + "ci-test": "npm run tests-only && npm run browser && npm run report", + "predebug": "rimraf coverage test/tmp", + "debug": "verbose=1 ./test/run.js", + "browser": "browserify -t browserify-istanbul test/run-browser.js | obake --coverage", + "check": "istanbul check-coverage coverage/coverage*.json", + "files": "pkgfiles --sort=name", + "get-version": "node -e \"console.log(require('./package.json').version)\"", + "update-readme": "sed -i.bak 's/\\/master\\.svg/\\/v'$(npm --silent run get-version)'.svg/g' README.md", + "restore-readme": "mv README.md.bak README.md", + "prepublish": "in-publish && npm run update-readme || not-in-publish", + "postpublish": "npm run restore-readme" + }, + "pre-commit": [ + "lint", + "ci-test", + "check" + ], + "engines": { + "node": ">= 6" + }, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "devDependencies": { + "@types/node": "^12.0.10", + "browserify": "^13.1.1", + "browserify-istanbul": "^2.0.0", + "coveralls": "^3.0.4", + "cross-spawn": "^6.0.5", + "eslint": "^6.0.1", + "fake": "^0.2.2", + "far": "^0.0.7", + "formidable": "^1.0.17", + "in-publish": "^2.0.0", + "is-node-modern": "^1.0.0", + "istanbul": "^0.4.5", + "obake": "^0.1.2", + "puppeteer": "^1.19.0", + "pkgfiles": "^2.3.0", + "pre-commit": "^1.1.3", + "request": "^2.88.0", + "rimraf": "^2.7.1", + "tape": "^4.6.2", + "typescript": "^3.5.2" + }, + "license": "MIT" +} diff --git a/node_modules/ieee754/LICENSE b/node_modules/ieee754/LICENSE new file mode 100644 index 000000000..5aac82c78 --- /dev/null +++ b/node_modules/ieee754/LICENSE @@ -0,0 +1,11 @@ +Copyright 2008 Fair Oaks Labs, Inc. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. 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. + +3. Neither the name of the copyright holder 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 HOLDER 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/node_modules/ieee754/README.md b/node_modules/ieee754/README.md new file mode 100644 index 000000000..cb7527b3c --- /dev/null +++ b/node_modules/ieee754/README.md @@ -0,0 +1,51 @@ +# ieee754 [![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/ieee754/master.svg +[travis-url]: https://travis-ci.org/feross/ieee754 +[npm-image]: https://img.shields.io/npm/v/ieee754.svg +[npm-url]: https://npmjs.org/package/ieee754 +[downloads-image]: https://img.shields.io/npm/dm/ieee754.svg +[downloads-url]: https://npmjs.org/package/ieee754 +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[saucelabs-image]: https://saucelabs.com/browser-matrix/ieee754.svg +[saucelabs-url]: https://saucelabs.com/u/ieee754 + +### Read/write IEEE754 floating point numbers from/to a Buffer or array-like object. + +## install + +``` +npm install ieee754 +``` + +## methods + +`var ieee754 = require('ieee754')` + +The `ieee754` object has the following functions: + +``` +ieee754.read = function (buffer, offset, isLE, mLen, nBytes) +ieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) +``` + +The arguments mean the following: + +- buffer = the buffer +- offset = offset into the buffer +- value = value to set (only for `write`) +- isLe = is little endian? +- mLen = mantissa length +- nBytes = number of bytes + +## what is ieee754? + +The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation. [Read more](http://en.wikipedia.org/wiki/IEEE_floating_point). + +## license + +BSD 3 Clause. Copyright (c) 2008, Fair Oaks Labs, Inc. diff --git a/node_modules/ieee754/index.d.ts b/node_modules/ieee754/index.d.ts new file mode 100644 index 000000000..f1e435487 --- /dev/null +++ b/node_modules/ieee754/index.d.ts @@ -0,0 +1,10 @@ +declare namespace ieee754 { + export function read( + buffer: Uint8Array, offset: number, isLE: boolean, mLen: number, + nBytes: number): number; + export function write( + buffer: Uint8Array, value: number, offset: number, isLE: boolean, + mLen: number, nBytes: number): void; + } + + export = ieee754; \ No newline at end of file diff --git a/node_modules/ieee754/index.js b/node_modules/ieee754/index.js new file mode 100644 index 000000000..81d26c343 --- /dev/null +++ b/node_modules/ieee754/index.js @@ -0,0 +1,85 @@ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} diff --git a/node_modules/ieee754/package.json b/node_modules/ieee754/package.json new file mode 100644 index 000000000..7b2385138 --- /dev/null +++ b/node_modules/ieee754/package.json @@ -0,0 +1,52 @@ +{ + "name": "ieee754", + "description": "Read/write IEEE754 floating point numbers from/to a Buffer or array-like object", + "version": "1.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "contributors": [ + "Romain Beauxis " + ], + "devDependencies": { + "airtap": "^3.0.0", + "standard": "*", + "tape": "^5.0.1" + }, + "keywords": [ + "IEEE 754", + "buffer", + "convert", + "floating point", + "ieee754" + ], + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/ieee754.git" + }, + "scripts": { + "test": "standard && npm run test-node && npm run test-browser", + "test-browser": "airtap -- test/*.js", + "test-browser-local": "airtap --local -- test/*.js", + "test-node": "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/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE new file mode 100644 index 000000000..dea3013d6 --- /dev/null +++ b/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/node_modules/inherits/README.md b/node_modules/inherits/README.md new file mode 100644 index 000000000..b1c566585 --- /dev/null +++ b/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/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js new file mode 100644 index 000000000..f71f2d932 --- /dev/null +++ b/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/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js new file mode 100644 index 000000000..86bbb3dc2 --- /dev/null +++ b/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/node_modules/inherits/package.json b/node_modules/inherits/package.json new file mode 100644 index 000000000..37b4366b8 --- /dev/null +++ b/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/node_modules/is-retry-allowed/index.d.ts b/node_modules/is-retry-allowed/index.d.ts new file mode 100644 index 000000000..15ed40ccd --- /dev/null +++ b/node_modules/is-retry-allowed/index.d.ts @@ -0,0 +1,20 @@ +/** +Check whether a request can be retried based on the `error.code`. + +@param error - The `.code` property, if it exists, will be used to determine whether retry is allowed. + +@example +``` +import isRetryAllowed from 'is-retry-allowed'; + +isRetryAllowed({code: 'ETIMEDOUT'}); +//=> true + +isRetryAllowed({code: 'ENOTFOUND'}); +//=> false + +isRetryAllowed({}); +//=> true +``` +*/ +export default function isRetryAllowed(error?: Error | Record): boolean; diff --git a/node_modules/is-retry-allowed/index.js b/node_modules/is-retry-allowed/index.js new file mode 100644 index 000000000..ab6f02f47 --- /dev/null +++ b/node_modules/is-retry-allowed/index.js @@ -0,0 +1,39 @@ +const denyList = new Set([ + 'ENOTFOUND', + 'ENETUNREACH', + + // SSL errors from https://github.com/nodejs/node/blob/fc8e3e2cdc521978351de257030db0076d79e0ab/src/crypto/crypto_common.cc#L301-L328 + 'UNABLE_TO_GET_ISSUER_CERT', + 'UNABLE_TO_GET_CRL', + 'UNABLE_TO_DECRYPT_CERT_SIGNATURE', + 'UNABLE_TO_DECRYPT_CRL_SIGNATURE', + 'UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY', + 'CERT_SIGNATURE_FAILURE', + 'CRL_SIGNATURE_FAILURE', + 'CERT_NOT_YET_VALID', + 'CERT_HAS_EXPIRED', + 'CRL_NOT_YET_VALID', + 'CRL_HAS_EXPIRED', + 'ERROR_IN_CERT_NOT_BEFORE_FIELD', + 'ERROR_IN_CERT_NOT_AFTER_FIELD', + 'ERROR_IN_CRL_LAST_UPDATE_FIELD', + 'ERROR_IN_CRL_NEXT_UPDATE_FIELD', + 'OUT_OF_MEM', + 'DEPTH_ZERO_SELF_SIGNED_CERT', + 'SELF_SIGNED_CERT_IN_CHAIN', + 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY', + 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', + 'CERT_CHAIN_TOO_LONG', + 'CERT_REVOKED', + 'INVALID_CA', + 'PATH_LENGTH_EXCEEDED', + 'INVALID_PURPOSE', + 'CERT_UNTRUSTED', + 'CERT_REJECTED', + 'HOSTNAME_MISMATCH' +]); + +// TODO: Use `error?.code` when targeting Node.js 14 +export default function isRetryAllowed(error) { + return !denyList.has(error && error.code); +} diff --git a/node_modules/is-retry-allowed/license b/node_modules/is-retry-allowed/license new file mode 100644 index 000000000..a69bb5924 --- /dev/null +++ b/node_modules/is-retry-allowed/license @@ -0,0 +1,10 @@ +MIT License + +Copyright (c) Vsevolod Strukchinsky (github.com/floatdrop) +Copyright (c) Sindre Sorhus (https://sindresorhus.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. diff --git a/node_modules/is-retry-allowed/package.json b/node_modules/is-retry-allowed/package.json new file mode 100644 index 000000000..bc8a9d6d8 --- /dev/null +++ b/node_modules/is-retry-allowed/package.json @@ -0,0 +1,40 @@ +{ + "name": "is-retry-allowed", + "version": "3.0.0", + "description": "Check whether a request can be retried based on the `error.code`", + "license": "MIT", + "repository": "sindresorhus/is-retry-allowed", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": "./index.js", + "engines": { + "node": ">=12" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "retry", + "retries", + "allowed", + "check", + "http", + "https", + "request", + "fetch" + ], + "devDependencies": { + "ava": "^3.15.0", + "tsd": "^0.14.0", + "xo": "^0.38.2" + } +} diff --git a/node_modules/is-retry-allowed/readme.md b/node_modules/is-retry-allowed/readme.md new file mode 100644 index 000000000..1f94c5ee5 --- /dev/null +++ b/node_modules/is-retry-allowed/readme.md @@ -0,0 +1,46 @@ +# is-retry-allowed + +> Check whether a request can be retried based on the `error.code` + +## Install + +``` +$ npm install is-retry-allowed +``` + +## Usage + +```js +import isRetryAllowed from 'is-retry-allowed'; + +isRetryAllowed({code: 'ETIMEDOUT'}); +//=> true + +isRetryAllowed({code: 'ENOTFOUND'}); +//=> false + +isRetryAllowed({}); +//=> true +``` + +## API + +### isRetryAllowed(error) + +#### error + +Type: `Error | object` + +The `.code` property, if it exists, will be used to determine whether retry is allowed. + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/loupe/LICENSE b/node_modules/loupe/LICENSE new file mode 100644 index 000000000..b0c8a5aaa --- /dev/null +++ b/node_modules/loupe/LICENSE @@ -0,0 +1,9 @@ +(The MIT License) + +Copyright (c) 2011-2013 Jake Luer jake@alogicalparadox.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. diff --git a/node_modules/loupe/README.md b/node_modules/loupe/README.md new file mode 100644 index 000000000..44f61d38d --- /dev/null +++ b/node_modules/loupe/README.md @@ -0,0 +1,63 @@ +![npm](https://img.shields.io/npm/v/loupe?logo=npm) +![Build](https://github.com/chaijs/loupe/workflows/Build/badge.svg?branch=master) +![Codecov branch](https://img.shields.io/codecov/c/github/chaijs/loupe/master?logo=codecov) + +# What is loupe? + +Loupe turns the object you give it into a string. It's similar to Node.js' `util.inspect()` function, but it works cross platform, in most modern browsers as well as Node. + +## Installation + +### Node.js + +`loupe` is available on [npm](http://npmjs.org). To install it, type: + + $ npm install loupe + +### Browsers + +You can also use it within the browser; install via npm and use the `loupe.js` file found within the download. For example: + +```html + +``` + +## Usage + +``` js +const { inspect } = require('loupe'); +``` + +```js +inspect({ foo: 'bar' }); // => "{ foo: 'bar' }" +inspect(1); // => '1' +inspect('foo'); // => "'foo'" +inspect([ 1, 2, 3 ]); // => '[ 1, 2, 3 ]' +inspect(/Test/g); // => '/Test/g' + +// ... +``` + +## Tests + +```bash +$ npm test +``` + +Coverage: + +```bash +$ npm run upload-coverage +``` + +## License + +(The MIT License) + +Copyright (c) 2011-2013 Jake Luer jake@alogicalparadox.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. diff --git a/node_modules/loupe/lib/arguments.d.ts b/node_modules/loupe/lib/arguments.d.ts new file mode 100644 index 000000000..fb0b814b7 --- /dev/null +++ b/node_modules/loupe/lib/arguments.d.ts @@ -0,0 +1,3 @@ +import type { Options } from './types.js'; +export default function inspectArguments(args: IArguments, options: Options): string; +//# sourceMappingURL=arguments.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/arguments.d.ts.map b/node_modules/loupe/lib/arguments.d.ts.map new file mode 100644 index 000000000..15c46687a --- /dev/null +++ b/node_modules/loupe/lib/arguments.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"arguments.d.ts","sourceRoot":"","sources":["../src/arguments.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAEzC,MAAM,CAAC,OAAO,UAAU,gBAAgB,CAAC,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,CAInF"} \ No newline at end of file diff --git a/node_modules/loupe/lib/arguments.js b/node_modules/loupe/lib/arguments.js new file mode 100644 index 000000000..b5df404d1 --- /dev/null +++ b/node_modules/loupe/lib/arguments.js @@ -0,0 +1,7 @@ +import { inspectList } from './helpers.js'; +export default function inspectArguments(args, options) { + if (args.length === 0) + return 'Arguments[]'; + options.truncate -= 13; + return `Arguments[ ${inspectList(args, options)} ]`; +} diff --git a/node_modules/loupe/lib/array.d.ts b/node_modules/loupe/lib/array.d.ts new file mode 100644 index 000000000..7b4043ed4 --- /dev/null +++ b/node_modules/loupe/lib/array.d.ts @@ -0,0 +1,3 @@ +import type { Options } from './types.js'; +export default function inspectArray(array: ArrayLike, options: Options): string; +//# sourceMappingURL=array.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/array.d.ts.map b/node_modules/loupe/lib/array.d.ts.map new file mode 100644 index 000000000..dfd4d499a --- /dev/null +++ b/node_modules/loupe/lib/array.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"array.d.ts","sourceRoot":"","sources":["../src/array.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAW,OAAO,EAAE,MAAM,YAAY,CAAA;AAElD,MAAM,CAAC,OAAO,UAAU,YAAY,CAAC,KAAK,EAAE,SAAS,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,UAiB/E"} \ No newline at end of file diff --git a/node_modules/loupe/lib/array.js b/node_modules/loupe/lib/array.js new file mode 100644 index 000000000..78f6c9631 --- /dev/null +++ b/node_modules/loupe/lib/array.js @@ -0,0 +1,16 @@ +import { inspectList, inspectProperty } from './helpers.js'; +export default function inspectArray(array, options) { + // Object.keys will always output the Array indices first, so we can slice by + // `array.length` to get non-index properties + const nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) + return '[]'; + options.truncate -= 4; + const listContents = inspectList(array, options); + options.truncate -= listContents.length; + let propertyContents = ''; + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map(key => [key, array[key]]), options, inspectProperty); + } + return `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ''} ]`; +} diff --git a/node_modules/loupe/lib/bigint.d.ts b/node_modules/loupe/lib/bigint.d.ts new file mode 100644 index 000000000..ad1d63037 --- /dev/null +++ b/node_modules/loupe/lib/bigint.d.ts @@ -0,0 +1,3 @@ +import type { Options } from './types.js'; +export default function inspectBigInt(number: bigint, options: Options): string; +//# sourceMappingURL=bigint.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/bigint.d.ts.map b/node_modules/loupe/lib/bigint.d.ts.map new file mode 100644 index 000000000..2af38e7db --- /dev/null +++ b/node_modules/loupe/lib/bigint.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bigint.d.ts","sourceRoot":"","sources":["../src/bigint.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAEzC,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,UAIrE"} \ No newline at end of file diff --git a/node_modules/loupe/lib/bigint.js b/node_modules/loupe/lib/bigint.js new file mode 100644 index 000000000..808ab0ff0 --- /dev/null +++ b/node_modules/loupe/lib/bigint.js @@ -0,0 +1,7 @@ +import { truncate, truncator } from './helpers.js'; +export default function inspectBigInt(number, options) { + let nums = truncate(number.toString(), options.truncate - 1); + if (nums !== truncator) + nums += 'n'; + return options.stylize(nums, 'bigint'); +} diff --git a/node_modules/loupe/lib/class.d.ts b/node_modules/loupe/lib/class.d.ts new file mode 100644 index 000000000..affd64247 --- /dev/null +++ b/node_modules/loupe/lib/class.d.ts @@ -0,0 +1,5 @@ +import type { Options } from './types.js'; +export default function inspectClass(value: { + new (...args: any[]): unknown; +}, options: Options): string; +//# sourceMappingURL=class.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/class.d.ts.map b/node_modules/loupe/lib/class.d.ts.map new file mode 100644 index 000000000..a1324cc33 --- /dev/null +++ b/node_modules/loupe/lib/class.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"class.d.ts","sourceRoot":"","sources":["../src/class.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAIzC,MAAM,CAAC,OAAO,UAAU,YAAY,CAAC,KAAK,EAAE;IAAE,KAAK,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,OAAO,CAAA;CAAE,EAAE,OAAO,EAAE,OAAO,UAY9F"} \ No newline at end of file diff --git a/node_modules/loupe/lib/class.js b/node_modules/loupe/lib/class.js new file mode 100644 index 000000000..a5f9332b4 --- /dev/null +++ b/node_modules/loupe/lib/class.js @@ -0,0 +1,15 @@ +import inspectObject from './object.js'; +const toStringTag = typeof Symbol !== 'undefined' && Symbol.toStringTag ? Symbol.toStringTag : false; +export default function inspectClass(value, options) { + let name = ''; + if (toStringTag && toStringTag in value) { + name = value[toStringTag]; + } + name = name || value.constructor.name; + // Babel transforms anonymous classes to the name `_class` + if (!name || name === '_class') { + name = ''; + } + options.truncate -= name.length; + return `${name}${inspectObject(value, options)}`; +} diff --git a/node_modules/loupe/lib/date.d.ts b/node_modules/loupe/lib/date.d.ts new file mode 100644 index 000000000..cdc51b7a1 --- /dev/null +++ b/node_modules/loupe/lib/date.d.ts @@ -0,0 +1,3 @@ +import type { Options } from './types.js'; +export default function inspectDate(dateObject: Date, options: Options): string; +//# sourceMappingURL=date.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/date.d.ts.map b/node_modules/loupe/lib/date.d.ts.map new file mode 100644 index 000000000..a551da7fc --- /dev/null +++ b/node_modules/loupe/lib/date.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"date.d.ts","sourceRoot":"","sources":["../src/date.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAEzC,MAAM,CAAC,OAAO,UAAU,WAAW,CAAC,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,UAWrE"} \ No newline at end of file diff --git a/node_modules/loupe/lib/date.js b/node_modules/loupe/lib/date.js new file mode 100644 index 000000000..09a645aae --- /dev/null +++ b/node_modules/loupe/lib/date.js @@ -0,0 +1,11 @@ +import { truncate } from './helpers.js'; +export default function inspectDate(dateObject, options) { + const stringRepresentation = dateObject.toJSON(); + if (stringRepresentation === null) { + return 'Invalid Date'; + } + const split = stringRepresentation.split('T'); + const date = split[0]; + // If we need to - truncate the time portion, but never the date + return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, 'date'); +} diff --git a/node_modules/loupe/lib/error.d.ts b/node_modules/loupe/lib/error.d.ts new file mode 100644 index 000000000..adb2a0d10 --- /dev/null +++ b/node_modules/loupe/lib/error.d.ts @@ -0,0 +1,3 @@ +import type { Options } from './types.js'; +export default function inspectObject(error: Error, options: Options): string; +//# sourceMappingURL=error.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/error.d.ts.map b/node_modules/loupe/lib/error.d.ts.map new file mode 100644 index 000000000..90a35db1c --- /dev/null +++ b/node_modules/loupe/lib/error.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAW,OAAO,EAAE,MAAM,YAAY,CAAA;AAgBlD,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,UAuBnE"} \ No newline at end of file diff --git a/node_modules/loupe/lib/error.js b/node_modules/loupe/lib/error.js new file mode 100644 index 000000000..ab8f996b5 --- /dev/null +++ b/node_modules/loupe/lib/error.js @@ -0,0 +1,35 @@ +import { inspectList, inspectProperty, truncate } from './helpers.js'; +const errorKeys = [ + 'stack', + 'line', + 'column', + 'name', + 'message', + 'fileName', + 'lineNumber', + 'columnNumber', + 'number', + 'description', + 'cause', +]; +export default function inspectObject(error, options) { + const properties = Object.getOwnPropertyNames(error).filter(key => errorKeys.indexOf(key) === -1); + const name = error.name; + options.truncate -= name.length; + let message = ''; + if (typeof error.message === 'string') { + message = truncate(error.message, options.truncate); + } + else { + properties.unshift('message'); + } + message = message ? `: ${message}` : ''; + options.truncate -= message.length + 5; + options.seen = options.seen || []; + if (options.seen.includes(error)) { + return '[Circular]'; + } + options.seen.push(error); + const propertyContents = inspectList(properties.map(key => [key, error[key]]), options, inspectProperty); + return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ''}`; +} diff --git a/node_modules/loupe/lib/function.d.ts b/node_modules/loupe/lib/function.d.ts new file mode 100644 index 000000000..98458696c --- /dev/null +++ b/node_modules/loupe/lib/function.d.ts @@ -0,0 +1,7 @@ +import type { Options } from './types.js'; +type ToStringable = Function & { + [Symbol.toStringTag]: string; +}; +export default function inspectFunction(func: ToStringable, options: Options): string; +export {}; +//# sourceMappingURL=function.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/function.d.ts.map b/node_modules/loupe/lib/function.d.ts.map new file mode 100644 index 000000000..ccc44e2ad --- /dev/null +++ b/node_modules/loupe/lib/function.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"function.d.ts","sourceRoot":"","sources":["../src/function.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAEzC,KAAK,YAAY,GAAG,QAAQ,GAAG;IAAC,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAC,CAAC;AAE9D,MAAM,CAAC,OAAO,UAAU,eAAe,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,UAQ3E"} \ No newline at end of file diff --git a/node_modules/loupe/lib/function.js b/node_modules/loupe/lib/function.js new file mode 100644 index 000000000..4459d5b10 --- /dev/null +++ b/node_modules/loupe/lib/function.js @@ -0,0 +1,9 @@ +import { truncate } from './helpers.js'; +export default function inspectFunction(func, options) { + const functionType = func[Symbol.toStringTag] || 'Function'; + const name = func.name; + if (!name) { + return options.stylize(`[${functionType}]`, 'special'); + } + return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, 'special'); +} diff --git a/node_modules/loupe/lib/helpers.d.ts b/node_modules/loupe/lib/helpers.d.ts new file mode 100644 index 000000000..ae1b8dd3b --- /dev/null +++ b/node_modules/loupe/lib/helpers.d.ts @@ -0,0 +1,7 @@ +import type { Inspect, Options } from './types.js'; +export declare const truncator = "\u2026"; +export declare function normaliseOptions({ showHidden, depth, colors, customInspect, showProxy, maxArrayLength, breakLength, seen, truncate, stylize, }: Partial | undefined, inspect: Inspect): Options; +export declare function truncate(string: string | number, length: number, tail?: typeof truncator): string; +export declare function inspectList(list: ArrayLike, options: Options, inspectItem?: Inspect, separator?: string): string; +export declare function inspectProperty([key, value]: [unknown, unknown], options: Options): string; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/helpers.d.ts.map b/node_modules/loupe/lib/helpers.d.ts.map new file mode 100644 index 000000000..63c51574a --- /dev/null +++ b/node_modules/loupe/lib/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AA+ClD,eAAO,MAAM,SAAS,WAAM,CAAA;AAa5B,wBAAgB,gBAAgB,CAC9B,EACE,UAAkB,EAClB,KAAS,EACT,MAAc,EACd,aAAoB,EACpB,SAAiB,EACjB,cAAyB,EACzB,WAAsB,EACtB,IAAS,EAET,QAAmB,EACnB,OAAgB,GACjB,8BAAuB,EACxB,OAAO,EAAE,OAAO,GACf,OAAO,CAkBT;AAMD,wBAAgB,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,GAAE,OAAO,SAAqB,UAenG;AAGD,wBAAgB,WAAW,CACzB,IAAI,EAAE,SAAS,CAAC,OAAO,CAAC,EACxB,OAAO,EAAE,OAAO,EAChB,WAAW,CAAC,EAAE,OAAO,EACrB,SAAS,SAAO,GACf,MAAM,CAsDR;AAYD,wBAAgB,eAAe,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,CAU1F"} \ No newline at end of file diff --git a/node_modules/loupe/lib/helpers.js b/node_modules/loupe/lib/helpers.js new file mode 100644 index 000000000..0ca92ba87 --- /dev/null +++ b/node_modules/loupe/lib/helpers.js @@ -0,0 +1,159 @@ +const ansiColors = { + bold: ['1', '22'], + dim: ['2', '22'], + italic: ['3', '23'], + underline: ['4', '24'], + // 5 & 6 are blinking + inverse: ['7', '27'], + hidden: ['8', '28'], + strike: ['9', '29'], + // 10-20 are fonts + // 21-29 are resets for 1-9 + black: ['30', '39'], + red: ['31', '39'], + green: ['32', '39'], + yellow: ['33', '39'], + blue: ['34', '39'], + magenta: ['35', '39'], + cyan: ['36', '39'], + white: ['37', '39'], + brightblack: ['30;1', '39'], + brightred: ['31;1', '39'], + brightgreen: ['32;1', '39'], + brightyellow: ['33;1', '39'], + brightblue: ['34;1', '39'], + brightmagenta: ['35;1', '39'], + brightcyan: ['36;1', '39'], + brightwhite: ['37;1', '39'], + grey: ['90', '39'], +}; +const styles = { + special: 'cyan', + number: 'yellow', + bigint: 'yellow', + boolean: 'yellow', + undefined: 'grey', + null: 'bold', + string: 'green', + symbol: 'green', + date: 'magenta', + regexp: 'red', +}; +export const truncator = '…'; +function colorise(value, styleType) { + const color = ansiColors[styles[styleType]] || ansiColors[styleType] || ''; + if (!color) { + return String(value); + } + return `\u001b[${color[0]}m${String(value)}\u001b[${color[1]}m`; +} +export function normaliseOptions({ showHidden = false, depth = 2, colors = false, customInspect = true, showProxy = false, maxArrayLength = Infinity, breakLength = Infinity, seen = [], +// eslint-disable-next-line no-shadow +truncate = Infinity, stylize = String, } = {}, inspect) { + const options = { + showHidden: Boolean(showHidden), + depth: Number(depth), + colors: Boolean(colors), + customInspect: Boolean(customInspect), + showProxy: Boolean(showProxy), + maxArrayLength: Number(maxArrayLength), + breakLength: Number(breakLength), + truncate: Number(truncate), + seen, + inspect, + stylize, + }; + if (options.colors) { + options.stylize = colorise; + } + return options; +} +function isHighSurrogate(char) { + return char >= '\ud800' && char <= '\udbff'; +} +export function truncate(string, length, tail = truncator) { + string = String(string); + const tailLength = tail.length; + const stringLength = string.length; + if (tailLength > length && stringLength > tailLength) { + return tail; + } + if (stringLength > length && stringLength > tailLength) { + let end = length - tailLength; + if (end > 0 && isHighSurrogate(string[end - 1])) { + end = end - 1; + } + return `${string.slice(0, end)}${tail}`; + } + return string; +} +// eslint-disable-next-line complexity +export function inspectList(list, options, inspectItem, separator = ', ') { + inspectItem = inspectItem || options.inspect; + const size = list.length; + if (size === 0) + return ''; + const originalLength = options.truncate; + let output = ''; + let peek = ''; + let truncated = ''; + for (let i = 0; i < size; i += 1) { + const last = i + 1 === list.length; + const secondToLast = i + 2 === list.length; + truncated = `${truncator}(${list.length - i})`; + const value = list[i]; + // If there is more than one remaining we need to account for a separator of `, ` + options.truncate = originalLength - output.length - (last ? 0 : separator.length); + const string = peek || inspectItem(value, options) + (last ? '' : separator); + const nextLength = output.length + string.length; + const truncatedLength = nextLength + truncated.length; + // If this is the last element, and adding it would + // take us over length, but adding the truncator wouldn't - then break now + if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) { + break; + } + // If this isn't the last or second to last element to scan, + // but the string is already over length then break here + if (!last && !secondToLast && truncatedLength > originalLength) { + break; + } + // Peek at the next string to determine if we should + // break early before adding this item to the output + peek = last ? '' : inspectItem(list[i + 1], options) + (secondToLast ? '' : separator); + // If we have one element left, but this element and + // the next takes over length, the break early + if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) { + break; + } + output += string; + // If the next element takes us to length - + // but there are more after that, then we should truncate now + if (!last && !secondToLast && nextLength + peek.length >= originalLength) { + truncated = `${truncator}(${list.length - i - 1})`; + break; + } + truncated = ''; + } + return `${output}${truncated}`; +} +function quoteComplexKey(key) { + if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) { + return key; + } + return JSON.stringify(key) + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); +} +export function inspectProperty([key, value], options) { + options.truncate -= 2; + if (typeof key === 'string') { + key = quoteComplexKey(key); + } + else if (typeof key !== 'number') { + key = `[${options.inspect(key, options)}]`; + } + options.truncate -= key.length; + value = options.inspect(value, options); + return `${key}: ${value}`; +} diff --git a/node_modules/loupe/lib/html.d.ts b/node_modules/loupe/lib/html.d.ts new file mode 100644 index 000000000..b5b5e4a98 --- /dev/null +++ b/node_modules/loupe/lib/html.d.ts @@ -0,0 +1,5 @@ +import type { Options } from './types.js'; +export declare function inspectAttribute([key, value]: [unknown, unknown], options: Options): string; +export declare function inspectHTMLCollection(collection: ArrayLike, options: Options): string; +export default function inspectHTML(element: Element, options: Options): string; +//# sourceMappingURL=html.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/html.d.ts.map b/node_modules/loupe/lib/html.d.ts.map new file mode 100644 index 000000000..a81fc64b0 --- /dev/null +++ b/node_modules/loupe/lib/html.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"html.d.ts","sourceRoot":"","sources":["../src/html.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAW,OAAO,EAAE,MAAM,YAAY,CAAA;AAElD,wBAAgB,gBAAgB,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,UAMlF;AAGD,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,SAAS,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,CAG9F;AAGD,MAAM,CAAC,OAAO,UAAU,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,CAwB9E"} \ No newline at end of file diff --git a/node_modules/loupe/lib/html.js b/node_modules/loupe/lib/html.js new file mode 100644 index 000000000..20b53b8f3 --- /dev/null +++ b/node_modules/loupe/lib/html.js @@ -0,0 +1,34 @@ +import { inspectList, truncator } from './helpers.js'; +export function inspectAttribute([key, value], options) { + options.truncate -= 3; + if (!value) { + return `${options.stylize(String(key), 'yellow')}`; + } + return `${options.stylize(String(key), 'yellow')}=${options.stylize(`"${value}"`, 'string')}`; +} +// @ts-ignore (Deno doesn't have Element) +export function inspectHTMLCollection(collection, options) { + // eslint-disable-next-line no-use-before-define + return inspectList(collection, options, inspectHTML, '\n'); +} +// @ts-ignore (Deno doesn't have Element) +export default function inspectHTML(element, options) { + const properties = element.getAttributeNames(); + const name = element.tagName.toLowerCase(); + const head = options.stylize(`<${name}`, 'special'); + const headClose = options.stylize(`>`, 'special'); + const tail = options.stylize(``, 'special'); + options.truncate -= name.length * 2 + 5; + let propertyContents = ''; + if (properties.length > 0) { + propertyContents += ' '; + propertyContents += inspectList(properties.map((key) => [key, element.getAttribute(key)]), options, inspectAttribute, ' '); + } + options.truncate -= propertyContents.length; + const truncate = options.truncate; + let children = inspectHTMLCollection(element.children, options); + if (children && children.length > truncate) { + children = `${truncator}(${element.children.length})`; + } + return `${head}${propertyContents}${headClose}${children}${tail}`; +} diff --git a/node_modules/loupe/lib/index.d.ts b/node_modules/loupe/lib/index.d.ts new file mode 100644 index 000000000..bdf2f16c4 --- /dev/null +++ b/node_modules/loupe/lib/index.d.ts @@ -0,0 +1,7 @@ +import type { Inspect, Options } from './types.js'; +export declare function inspect(value: unknown, opts?: Partial): string; +export declare function registerConstructor(constructor: Function, inspector: Inspect): boolean; +export declare function registerStringTag(stringTag: string, inspector: Inspect): boolean; +export declare const custom: string | symbol; +export default inspect; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/index.d.ts.map b/node_modules/loupe/lib/index.d.ts.map new file mode 100644 index 000000000..cdb7900a8 --- /dev/null +++ b/node_modules/loupe/lib/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAyBA,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAmGlD,wBAAgB,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,GAAE,OAAO,CAAC,OAAO,CAAM,GAAG,MAAM,CAmD3E;AAED,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,WAM5E;AAED,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,WAMtE;AAED,eAAO,MAAM,MAAM,iBAAc,CAAA;AAEjC,eAAe,OAAO,CAAA"} \ No newline at end of file diff --git a/node_modules/loupe/lib/index.js b/node_modules/loupe/lib/index.js new file mode 100644 index 000000000..6e619e449 --- /dev/null +++ b/node_modules/loupe/lib/index.js @@ -0,0 +1,161 @@ +/* ! + * loupe + * Copyright(c) 2013 Jake Luer + * MIT Licensed + */ +import inspectArray from './array.js'; +import inspectTypedArray from './typedarray.js'; +import inspectDate from './date.js'; +import inspectFunction from './function.js'; +import inspectMap from './map.js'; +import inspectNumber from './number.js'; +import inspectBigInt from './bigint.js'; +import inspectRegExp from './regexp.js'; +import inspectSet from './set.js'; +import inspectString from './string.js'; +import inspectSymbol from './symbol.js'; +import inspectPromise from './promise.js'; +import inspectClass from './class.js'; +import inspectObject from './object.js'; +import inspectArguments from './arguments.js'; +import inspectError from './error.js'; +import inspectHTMLElement, { inspectHTMLCollection } from './html.js'; +import { normaliseOptions } from './helpers.js'; +const symbolsSupported = typeof Symbol === 'function' && typeof Symbol.for === 'function'; +const chaiInspect = symbolsSupported ? Symbol.for('chai/inspect') : '@@chai/inspect'; +let nodeInspect = false; +try { + // eslint-disable-next-line global-require + // @ts-ignore + const nodeUtil = require('util'); + nodeInspect = nodeUtil.inspect ? nodeUtil.inspect.custom : false; +} +catch (noNodeInspect) { + nodeInspect = false; +} +const constructorMap = new WeakMap(); +const stringTagMap = {}; +const baseTypesMap = { + undefined: (value, options) => options.stylize('undefined', 'undefined'), + null: (value, options) => options.stylize('null', 'null'), + boolean: (value, options) => options.stylize(String(value), 'boolean'), + Boolean: (value, options) => options.stylize(String(value), 'boolean'), + number: inspectNumber, + Number: inspectNumber, + bigint: inspectBigInt, + BigInt: inspectBigInt, + string: inspectString, + String: inspectString, + function: inspectFunction, + Function: inspectFunction, + symbol: inspectSymbol, + // A Symbol polyfill will return `Symbol` not `symbol` from typedetect + Symbol: inspectSymbol, + Array: inspectArray, + Date: inspectDate, + Map: inspectMap, + Set: inspectSet, + RegExp: inspectRegExp, + Promise: inspectPromise, + // WeakSet, WeakMap are totally opaque to us + WeakSet: (value, options) => options.stylize('WeakSet{…}', 'special'), + WeakMap: (value, options) => options.stylize('WeakMap{…}', 'special'), + Arguments: inspectArguments, + Int8Array: inspectTypedArray, + Uint8Array: inspectTypedArray, + Uint8ClampedArray: inspectTypedArray, + Int16Array: inspectTypedArray, + Uint16Array: inspectTypedArray, + Int32Array: inspectTypedArray, + Uint32Array: inspectTypedArray, + Float32Array: inspectTypedArray, + Float64Array: inspectTypedArray, + Generator: () => '', + DataView: () => '', + ArrayBuffer: () => '', + Error: inspectError, + HTMLCollection: inspectHTMLCollection, + NodeList: inspectHTMLCollection, +}; +// eslint-disable-next-line complexity +const inspectCustom = (value, options, type) => { + if (chaiInspect in value && typeof value[chaiInspect] === 'function') { + return value[chaiInspect](options); + } + if (nodeInspect && nodeInspect in value && typeof value[nodeInspect] === 'function') { + return value[nodeInspect](options.depth, options); + } + if ('inspect' in value && typeof value.inspect === 'function') { + return value.inspect(options.depth, options); + } + if ('constructor' in value && constructorMap.has(value.constructor)) { + return constructorMap.get(value.constructor)(value, options); + } + if (stringTagMap[type]) { + return stringTagMap[type](value, options); + } + return ''; +}; +const toString = Object.prototype.toString; +// eslint-disable-next-line complexity +export function inspect(value, opts = {}) { + const options = normaliseOptions(opts, inspect); + const { customInspect } = options; + let type = value === null ? 'null' : typeof value; + if (type === 'object') { + type = toString.call(value).slice(8, -1); + } + // If it is a base value that we already support, then use Loupe's inspector + if (type in baseTypesMap) { + return baseTypesMap[type](value, options); + } + // If `options.customInspect` is set to true then try to use the custom inspector + if (customInspect && value) { + const output = inspectCustom(value, options, type); + if (output) { + if (typeof output === 'string') + return output; + return inspect(output, options); + } + } + const proto = value ? Object.getPrototypeOf(value) : false; + // If it's a plain Object then use Loupe's inspector + if (proto === Object.prototype || proto === null) { + return inspectObject(value, options); + } + // Specifically account for HTMLElements + // @ts-ignore + if (value && typeof HTMLElement === 'function' && value instanceof HTMLElement) { + return inspectHTMLElement(value, options); + } + if ('constructor' in value) { + // If it is a class, inspect it like an object but add the constructor name + if (value.constructor !== Object) { + return inspectClass(value, options); + } + // If it is an object with an anonymous prototype, display it as an object. + return inspectObject(value, options); + } + // last chance to check if it's an object + if (value === Object(value)) { + return inspectObject(value, options); + } + // We have run out of options! Just stringify the value + return options.stylize(String(value), type); +} +export function registerConstructor(constructor, inspector) { + if (constructorMap.has(constructor)) { + return false; + } + constructorMap.set(constructor, inspector); + return true; +} +export function registerStringTag(stringTag, inspector) { + if (stringTag in stringTagMap) { + return false; + } + stringTagMap[stringTag] = inspector; + return true; +} +export const custom = chaiInspect; +export default inspect; diff --git a/node_modules/loupe/lib/map.d.ts b/node_modules/loupe/lib/map.d.ts new file mode 100644 index 000000000..6ed57064c --- /dev/null +++ b/node_modules/loupe/lib/map.d.ts @@ -0,0 +1,3 @@ +import type { Options } from './types.js'; +export default function inspectMap(map: Map, options: Options): string; +//# sourceMappingURL=map.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/map.d.ts.map b/node_modules/loupe/lib/map.d.ts.map new file mode 100644 index 000000000..a554ddd4d --- /dev/null +++ b/node_modules/loupe/lib/map.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"map.d.ts","sourceRoot":"","sources":["../src/map.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAW,OAAO,EAAE,MAAM,YAAY,CAAA;AAmBlD,MAAM,CAAC,OAAO,UAAU,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,CAOvF"} \ No newline at end of file diff --git a/node_modules/loupe/lib/map.js b/node_modules/loupe/lib/map.js new file mode 100644 index 000000000..d1705b979 --- /dev/null +++ b/node_modules/loupe/lib/map.js @@ -0,0 +1,24 @@ +import { inspectList } from './helpers.js'; +function inspectMapEntry([key, value], options) { + options.truncate -= 4; + key = options.inspect(key, options); + options.truncate -= key.length; + value = options.inspect(value, options); + return `${key} => ${value}`; +} +// IE11 doesn't support `map.entries()` +function mapToEntries(map) { + const entries = []; + map.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +} +export default function inspectMap(map, options) { + const size = map.size - 1; + if (size <= 0) { + return 'Map{}'; + } + options.truncate -= 7; + return `Map{ ${inspectList(mapToEntries(map), options, inspectMapEntry)} }`; +} diff --git a/node_modules/loupe/lib/number.d.ts b/node_modules/loupe/lib/number.d.ts new file mode 100644 index 000000000..231ccceb7 --- /dev/null +++ b/node_modules/loupe/lib/number.d.ts @@ -0,0 +1,3 @@ +import type { Options } from './types.js'; +export default function inspectNumber(number: number, options: Options): string; +//# sourceMappingURL=number.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/number.d.ts.map b/node_modules/loupe/lib/number.d.ts.map new file mode 100644 index 000000000..31131ddc5 --- /dev/null +++ b/node_modules/loupe/lib/number.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"number.d.ts","sourceRoot":"","sources":["../src/number.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAGzC,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,CAc9E"} \ No newline at end of file diff --git a/node_modules/loupe/lib/number.js b/node_modules/loupe/lib/number.js new file mode 100644 index 000000000..85442f04e --- /dev/null +++ b/node_modules/loupe/lib/number.js @@ -0,0 +1,17 @@ +import { truncate } from './helpers.js'; +const isNaN = Number.isNaN || (i => i !== i); // eslint-disable-line no-self-compare +export default function inspectNumber(number, options) { + if (isNaN(number)) { + return options.stylize('NaN', 'number'); + } + if (number === Infinity) { + return options.stylize('Infinity', 'number'); + } + if (number === -Infinity) { + return options.stylize('-Infinity', 'number'); + } + if (number === 0) { + return options.stylize(1 / number === Infinity ? '+0' : '-0', 'number'); + } + return options.stylize(truncate(String(number), options.truncate), 'number'); +} diff --git a/node_modules/loupe/lib/object.d.ts b/node_modules/loupe/lib/object.d.ts new file mode 100644 index 000000000..11ac7edcd --- /dev/null +++ b/node_modules/loupe/lib/object.d.ts @@ -0,0 +1,3 @@ +import type { Options } from './types.js'; +export default function inspectObject(object: object, options: Options): string; +//# sourceMappingURL=object.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/object.d.ts.map b/node_modules/loupe/lib/object.d.ts.map new file mode 100644 index 000000000..a3cf52f08 --- /dev/null +++ b/node_modules/loupe/lib/object.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"object.d.ts","sourceRoot":"","sources":["../src/object.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAW,OAAO,EAAE,MAAM,YAAY,CAAA;AAElD,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,CA4B9E"} \ No newline at end of file diff --git a/node_modules/loupe/lib/object.js b/node_modules/loupe/lib/object.js new file mode 100644 index 000000000..e39eb45d1 --- /dev/null +++ b/node_modules/loupe/lib/object.js @@ -0,0 +1,22 @@ +import { inspectList, inspectProperty } from './helpers.js'; +export default function inspectObject(object, options) { + const properties = Object.getOwnPropertyNames(object); + const symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : []; + if (properties.length === 0 && symbols.length === 0) { + return '{}'; + } + options.truncate -= 4; + options.seen = options.seen || []; + if (options.seen.includes(object)) { + return '[Circular]'; + } + options.seen.push(object); + const propertyContents = inspectList(properties.map(key => [key, object[key]]), options, inspectProperty); + const symbolContents = inspectList(symbols.map(key => [key, object[key]]), options, inspectProperty); + options.seen.pop(); + let sep = ''; + if (propertyContents && symbolContents) { + sep = ', '; + } + return `{ ${propertyContents}${sep}${symbolContents} }`; +} diff --git a/node_modules/loupe/lib/promise.d.ts b/node_modules/loupe/lib/promise.d.ts new file mode 100644 index 000000000..1dda98b53 --- /dev/null +++ b/node_modules/loupe/lib/promise.d.ts @@ -0,0 +1,5 @@ +import type { Options } from './types.js'; +type GetPromiseValue = (value: Promise, options: Options) => string; +declare let getPromiseValue: GetPromiseValue; +export default getPromiseValue; +//# sourceMappingURL=promise.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/promise.d.ts.map b/node_modules/loupe/lib/promise.d.ts.map new file mode 100644 index 000000000..3c3292b12 --- /dev/null +++ b/node_modules/loupe/lib/promise.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"promise.d.ts","sourceRoot":"","sources":["../src/promise.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AACzC,KAAK,eAAe,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,KAAK,MAAM,CAAA;AAC5E,QAAA,IAAI,eAAe,EAAE,eAAoC,CAAA;AAgBzD,eAAe,eAAe,CAAA"} \ No newline at end of file diff --git a/node_modules/loupe/lib/promise.js b/node_modules/loupe/lib/promise.js new file mode 100644 index 000000000..f9d5db32c --- /dev/null +++ b/node_modules/loupe/lib/promise.js @@ -0,0 +1,18 @@ +let getPromiseValue = () => 'Promise{…}'; +try { + // @ts-ignore + const { getPromiseDetails, kPending, kRejected } = process.binding('util'); + if (Array.isArray(getPromiseDetails(Promise.resolve()))) { + getPromiseValue = (value, options) => { + const [state, innerValue] = getPromiseDetails(value); + if (state === kPending) { + return 'Promise{}'; + } + return `Promise${state === kRejected ? '!' : ''}{${options.inspect(innerValue, options)}}`; + }; + } +} +catch (notNode) { + /* ignore */ +} +export default getPromiseValue; diff --git a/node_modules/loupe/lib/regexp.d.ts b/node_modules/loupe/lib/regexp.d.ts new file mode 100644 index 000000000..ec77ec933 --- /dev/null +++ b/node_modules/loupe/lib/regexp.d.ts @@ -0,0 +1,3 @@ +import type { Options } from './types.js'; +export default function inspectRegExp(value: RegExp, options: Options): string; +//# sourceMappingURL=regexp.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/regexp.d.ts.map b/node_modules/loupe/lib/regexp.d.ts.map new file mode 100644 index 000000000..7d8295eed --- /dev/null +++ b/node_modules/loupe/lib/regexp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"regexp.d.ts","sourceRoot":"","sources":["../src/regexp.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAEzC,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,CAK7E"} \ No newline at end of file diff --git a/node_modules/loupe/lib/regexp.js b/node_modules/loupe/lib/regexp.js new file mode 100644 index 000000000..0a35f49f9 --- /dev/null +++ b/node_modules/loupe/lib/regexp.js @@ -0,0 +1,7 @@ +import { truncate } from './helpers.js'; +export default function inspectRegExp(value, options) { + const flags = value.toString().split('/')[2]; + const sourceLength = options.truncate - (2 + flags.length); + const source = value.source; + return options.stylize(`/${truncate(source, sourceLength)}/${flags}`, 'regexp'); +} diff --git a/node_modules/loupe/lib/set.d.ts b/node_modules/loupe/lib/set.d.ts new file mode 100644 index 000000000..280de62ea --- /dev/null +++ b/node_modules/loupe/lib/set.d.ts @@ -0,0 +1,3 @@ +import type { Options } from './types.js'; +export default function inspectSet(set: Set, options: Options): string; +//# sourceMappingURL=set.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/set.d.ts.map b/node_modules/loupe/lib/set.d.ts.map new file mode 100644 index 000000000..1436d03d7 --- /dev/null +++ b/node_modules/loupe/lib/set.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"set.d.ts","sourceRoot":"","sources":["../src/set.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAWzC,MAAM,CAAC,OAAO,UAAU,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,CAI9E"} \ No newline at end of file diff --git a/node_modules/loupe/lib/set.js b/node_modules/loupe/lib/set.js new file mode 100644 index 000000000..51b81adda --- /dev/null +++ b/node_modules/loupe/lib/set.js @@ -0,0 +1,15 @@ +import { inspectList } from './helpers.js'; +// IE11 doesn't support `Array.from(set)` +function arrayFromSet(set) { + const values = []; + set.forEach(value => { + values.push(value); + }); + return values; +} +export default function inspectSet(set, options) { + if (set.size === 0) + return 'Set{}'; + options.truncate -= 7; + return `Set{ ${inspectList(arrayFromSet(set), options)} }`; +} diff --git a/node_modules/loupe/lib/string.d.ts b/node_modules/loupe/lib/string.d.ts new file mode 100644 index 000000000..7e178fb0a --- /dev/null +++ b/node_modules/loupe/lib/string.d.ts @@ -0,0 +1,3 @@ +import type { Options } from './types.js'; +export default function inspectString(string: string, options: Options): string; +//# sourceMappingURL=string.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/string.d.ts.map b/node_modules/loupe/lib/string.d.ts.map new file mode 100644 index 000000000..0471e49d1 --- /dev/null +++ b/node_modules/loupe/lib/string.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"string.d.ts","sourceRoot":"","sources":["../src/string.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AA2BzC,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,CAK9E"} \ No newline at end of file diff --git a/node_modules/loupe/lib/string.js b/node_modules/loupe/lib/string.js new file mode 100644 index 000000000..49c966580 --- /dev/null +++ b/node_modules/loupe/lib/string.js @@ -0,0 +1,24 @@ +import { truncate } from './helpers.js'; +const stringEscapeChars = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5" + + '\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]', 'g'); +const escapeCharacters = { + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + "'": "\\'", + '\\': '\\\\', +}; +const hex = 16; +const unicodeLength = 4; +function escape(char) { + return (escapeCharacters[char] || + `\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-unicodeLength)}`); +} +export default function inspectString(string, options) { + if (stringEscapeChars.test(string)) { + string = string.replace(stringEscapeChars, escape); + } + return options.stylize(`'${truncate(string, options.truncate - 2)}'`, 'string'); +} diff --git a/node_modules/loupe/lib/symbol.d.ts b/node_modules/loupe/lib/symbol.d.ts new file mode 100644 index 000000000..81015e73a --- /dev/null +++ b/node_modules/loupe/lib/symbol.d.ts @@ -0,0 +1,2 @@ +export default function inspectSymbol(value: Symbol): string; +//# sourceMappingURL=symbol.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/symbol.d.ts.map b/node_modules/loupe/lib/symbol.d.ts.map new file mode 100644 index 000000000..45786f134 --- /dev/null +++ b/node_modules/loupe/lib/symbol.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"symbol.d.ts","sourceRoot":"","sources":["../src/symbol.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAK3D"} \ No newline at end of file diff --git a/node_modules/loupe/lib/symbol.js b/node_modules/loupe/lib/symbol.js new file mode 100644 index 000000000..ca8dd68ed --- /dev/null +++ b/node_modules/loupe/lib/symbol.js @@ -0,0 +1,6 @@ +export default function inspectSymbol(value) { + if ('description' in Symbol.prototype) { + return value.description ? `Symbol(${value.description})` : 'Symbol()'; + } + return value.toString(); +} diff --git a/node_modules/loupe/lib/typedarray.d.ts b/node_modules/loupe/lib/typedarray.d.ts new file mode 100644 index 000000000..0bdc4ecf4 --- /dev/null +++ b/node_modules/loupe/lib/typedarray.d.ts @@ -0,0 +1,5 @@ +import type { Options } from './types.js'; +type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; +export default function inspectTypedArray(array: TypedArray, options: Options): string; +export {}; +//# sourceMappingURL=typedarray.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/typedarray.d.ts.map b/node_modules/loupe/lib/typedarray.d.ts.map new file mode 100644 index 000000000..6d11f7398 --- /dev/null +++ b/node_modules/loupe/lib/typedarray.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"typedarray.d.ts","sourceRoot":"","sources":["../src/typedarray.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAW,OAAO,EAAE,MAAM,YAAY,CAAA;AAElD,KAAK,UAAU,GACX,SAAS,GACT,UAAU,GACV,iBAAiB,GACjB,UAAU,GACV,WAAW,GACX,UAAU,GACV,WAAW,GACX,YAAY,GACZ,YAAY,CAAA;AAchB,MAAM,CAAC,OAAO,UAAU,iBAAiB,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,CA8BrF"} \ No newline at end of file diff --git a/node_modules/loupe/lib/typedarray.js b/node_modules/loupe/lib/typedarray.js new file mode 100644 index 000000000..e8257f692 --- /dev/null +++ b/node_modules/loupe/lib/typedarray.js @@ -0,0 +1,38 @@ +import { inspectList, inspectProperty, truncate, truncator } from './helpers.js'; +const getArrayName = (array) => { + // We need to special case Node.js' Buffers, which report to be Uint8Array + // @ts-ignore + if (typeof Buffer === 'function' && array instanceof Buffer) { + return 'Buffer'; + } + if (array[Symbol.toStringTag]) { + return array[Symbol.toStringTag]; + } + return array.constructor.name; +}; +export default function inspectTypedArray(array, options) { + const name = getArrayName(array); + options.truncate -= name.length + 4; + // Object.keys will always output the Array indices first, so we can slice by + // `array.length` to get non-index properties + const nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) + return `${name}[]`; + // As we know TypedArrays only contain Unsigned Integers, we can skip inspecting each one and simply + // stylise the toString() value of them + let output = ''; + for (let i = 0; i < array.length; i++) { + const string = `${options.stylize(truncate(array[i], options.truncate), 'number')}${i === array.length - 1 ? '' : ', '}`; + options.truncate -= string.length; + if (array[i] !== array.length && options.truncate <= 3) { + output += `${truncator}(${array.length - array[i] + 1})`; + break; + } + output += string; + } + let propertyContents = ''; + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map(key => [key, array[key]]), options, inspectProperty); + } + return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ''} ]`; +} diff --git a/node_modules/loupe/lib/types.d.ts b/node_modules/loupe/lib/types.d.ts new file mode 100644 index 000000000..1abae2373 --- /dev/null +++ b/node_modules/loupe/lib/types.d.ts @@ -0,0 +1,15 @@ +export type Inspect = (value: unknown, options: Options) => string; +export interface Options { + showHidden: boolean; + depth: number; + colors: boolean; + customInspect: boolean; + showProxy: boolean; + maxArrayLength: number; + breakLength: number; + truncate: number; + seen: unknown[]; + inspect: Inspect; + stylize: (value: string, styleType: string) => string; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/loupe/lib/types.d.ts.map b/node_modules/loupe/lib/types.d.ts.map new file mode 100644 index 000000000..e0ab591ff --- /dev/null +++ b/node_modules/loupe/lib/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,OAAO,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,KAAK,MAAM,CAAA;AAElE,MAAM,WAAW,OAAO;IACtB,UAAU,EAAE,OAAO,CAAA;IACnB,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,OAAO,CAAA;IACf,aAAa,EAAE,OAAO,CAAA;IACtB,SAAS,EAAE,OAAO,CAAA;IAClB,cAAc,EAAE,MAAM,CAAA;IACtB,WAAW,EAAE,MAAM,CAAA;IACnB,QAAQ,EAAE,MAAM,CAAA;IAChB,IAAI,EAAE,OAAO,EAAE,CAAA;IACf,OAAO,EAAE,OAAO,CAAA;IAChB,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,KAAK,MAAM,CAAA;CACtD"} \ No newline at end of file diff --git a/node_modules/loupe/lib/types.js b/node_modules/loupe/lib/types.js new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/node_modules/loupe/lib/types.js @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/loupe/loupe.js b/node_modules/loupe/loupe.js new file mode 100644 index 000000000..02378c7b7 --- /dev/null +++ b/node_modules/loupe/loupe.js @@ -0,0 +1,650 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +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); + +// (disabled):util +var require_util = __commonJS({ + "(disabled):util"() { + } +}); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + custom: () => custom, + default: () => src_default, + inspect: () => inspect, + registerConstructor: () => registerConstructor, + registerStringTag: () => registerStringTag +}); +module.exports = __toCommonJS(src_exports); + +// src/helpers.ts +var ansiColors = { + bold: ["1", "22"], + dim: ["2", "22"], + italic: ["3", "23"], + underline: ["4", "24"], + // 5 & 6 are blinking + inverse: ["7", "27"], + hidden: ["8", "28"], + strike: ["9", "29"], + // 10-20 are fonts + // 21-29 are resets for 1-9 + black: ["30", "39"], + red: ["31", "39"], + green: ["32", "39"], + yellow: ["33", "39"], + blue: ["34", "39"], + magenta: ["35", "39"], + cyan: ["36", "39"], + white: ["37", "39"], + brightblack: ["30;1", "39"], + brightred: ["31;1", "39"], + brightgreen: ["32;1", "39"], + brightyellow: ["33;1", "39"], + brightblue: ["34;1", "39"], + brightmagenta: ["35;1", "39"], + brightcyan: ["36;1", "39"], + brightwhite: ["37;1", "39"], + grey: ["90", "39"] +}; +var styles = { + special: "cyan", + number: "yellow", + bigint: "yellow", + boolean: "yellow", + undefined: "grey", + null: "bold", + string: "green", + symbol: "green", + date: "magenta", + regexp: "red" +}; +var truncator = "\u2026"; +function colorise(value, styleType) { + const color = ansiColors[styles[styleType]] || ansiColors[styleType] || ""; + if (!color) { + return String(value); + } + return `\x1B[${color[0]}m${String(value)}\x1B[${color[1]}m`; +} +function normaliseOptions({ + showHidden = false, + depth = 2, + colors = false, + customInspect = true, + showProxy = false, + maxArrayLength = Infinity, + breakLength = Infinity, + seen = [], + // eslint-disable-next-line no-shadow + truncate: truncate2 = Infinity, + stylize = String +} = {}, inspect2) { + const options = { + showHidden: Boolean(showHidden), + depth: Number(depth), + colors: Boolean(colors), + customInspect: Boolean(customInspect), + showProxy: Boolean(showProxy), + maxArrayLength: Number(maxArrayLength), + breakLength: Number(breakLength), + truncate: Number(truncate2), + seen, + inspect: inspect2, + stylize + }; + if (options.colors) { + options.stylize = colorise; + } + return options; +} +function isHighSurrogate(char) { + return char >= "\uD800" && char <= "\uDBFF"; +} +function truncate(string, length, tail = truncator) { + string = String(string); + const tailLength = tail.length; + const stringLength = string.length; + if (tailLength > length && stringLength > tailLength) { + return tail; + } + if (stringLength > length && stringLength > tailLength) { + let end = length - tailLength; + if (end > 0 && isHighSurrogate(string[end - 1])) { + end = end - 1; + } + return `${string.slice(0, end)}${tail}`; + } + return string; +} +function inspectList(list, options, inspectItem, separator = ", ") { + inspectItem = inspectItem || options.inspect; + const size = list.length; + if (size === 0) + return ""; + const originalLength = options.truncate; + let output = ""; + let peek = ""; + let truncated = ""; + for (let i = 0; i < size; i += 1) { + const last = i + 1 === list.length; + const secondToLast = i + 2 === list.length; + truncated = `${truncator}(${list.length - i})`; + const value = list[i]; + options.truncate = originalLength - output.length - (last ? 0 : separator.length); + const string = peek || inspectItem(value, options) + (last ? "" : separator); + const nextLength = output.length + string.length; + const truncatedLength = nextLength + truncated.length; + if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) { + break; + } + if (!last && !secondToLast && truncatedLength > originalLength) { + break; + } + peek = last ? "" : inspectItem(list[i + 1], options) + (secondToLast ? "" : separator); + if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) { + break; + } + output += string; + if (!last && !secondToLast && nextLength + peek.length >= originalLength) { + truncated = `${truncator}(${list.length - i - 1})`; + break; + } + truncated = ""; + } + return `${output}${truncated}`; +} +function quoteComplexKey(key) { + if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) { + return key; + } + return JSON.stringify(key).replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); +} +function inspectProperty([key, value], options) { + options.truncate -= 2; + if (typeof key === "string") { + key = quoteComplexKey(key); + } else if (typeof key !== "number") { + key = `[${options.inspect(key, options)}]`; + } + options.truncate -= key.length; + value = options.inspect(value, options); + return `${key}: ${value}`; +} + +// src/array.ts +function inspectArray(array, options) { + const nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) + return "[]"; + options.truncate -= 4; + const listContents = inspectList(array, options); + options.truncate -= listContents.length; + let propertyContents = ""; + if (nonIndexProperties.length) { + propertyContents = inspectList( + nonIndexProperties.map((key) => [key, array[key]]), + options, + inspectProperty + ); + } + return `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ""} ]`; +} + +// src/typedarray.ts +var getArrayName = (array) => { + if (typeof Buffer === "function" && array instanceof Buffer) { + return "Buffer"; + } + if (array[Symbol.toStringTag]) { + return array[Symbol.toStringTag]; + } + return array.constructor.name; +}; +function inspectTypedArray(array, options) { + const name = getArrayName(array); + options.truncate -= name.length + 4; + const nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) + return `${name}[]`; + let output = ""; + for (let i = 0; i < array.length; i++) { + const string = `${options.stylize(truncate(array[i], options.truncate), "number")}${i === array.length - 1 ? "" : ", "}`; + options.truncate -= string.length; + if (array[i] !== array.length && options.truncate <= 3) { + output += `${truncator}(${array.length - array[i] + 1})`; + break; + } + output += string; + } + let propertyContents = ""; + if (nonIndexProperties.length) { + propertyContents = inspectList( + nonIndexProperties.map((key) => [key, array[key]]), + options, + inspectProperty + ); + } + return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ""} ]`; +} + +// src/date.ts +function inspectDate(dateObject, options) { + const stringRepresentation = dateObject.toJSON(); + if (stringRepresentation === null) { + return "Invalid Date"; + } + const split = stringRepresentation.split("T"); + const date = split[0]; + return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, "date"); +} + +// src/function.ts +function inspectFunction(func, options) { + const functionType = func[Symbol.toStringTag] || "Function"; + const name = func.name; + if (!name) { + return options.stylize(`[${functionType}]`, "special"); + } + return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, "special"); +} + +// src/map.ts +function inspectMapEntry([key, value], options) { + options.truncate -= 4; + key = options.inspect(key, options); + options.truncate -= key.length; + value = options.inspect(value, options); + return `${key} => ${value}`; +} +function mapToEntries(map) { + const entries = []; + map.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +} +function inspectMap(map, options) { + const size = map.size - 1; + if (size <= 0) { + return "Map{}"; + } + options.truncate -= 7; + return `Map{ ${inspectList(mapToEntries(map), options, inspectMapEntry)} }`; +} + +// src/number.ts +var isNaN = Number.isNaN || ((i) => i !== i); +function inspectNumber(number, options) { + if (isNaN(number)) { + return options.stylize("NaN", "number"); + } + if (number === Infinity) { + return options.stylize("Infinity", "number"); + } + if (number === -Infinity) { + return options.stylize("-Infinity", "number"); + } + if (number === 0) { + return options.stylize(1 / number === Infinity ? "+0" : "-0", "number"); + } + return options.stylize(truncate(String(number), options.truncate), "number"); +} + +// src/bigint.ts +function inspectBigInt(number, options) { + let nums = truncate(number.toString(), options.truncate - 1); + if (nums !== truncator) + nums += "n"; + return options.stylize(nums, "bigint"); +} + +// src/regexp.ts +function inspectRegExp(value, options) { + const flags = value.toString().split("/")[2]; + const sourceLength = options.truncate - (2 + flags.length); + const source = value.source; + return options.stylize(`/${truncate(source, sourceLength)}/${flags}`, "regexp"); +} + +// src/set.ts +function arrayFromSet(set) { + const values = []; + set.forEach((value) => { + values.push(value); + }); + return values; +} +function inspectSet(set, options) { + if (set.size === 0) + return "Set{}"; + options.truncate -= 7; + return `Set{ ${inspectList(arrayFromSet(set), options)} }`; +} + +// src/string.ts +var stringEscapeChars = new RegExp( + "['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]", + "g" +); +var escapeCharacters = { + "\b": "\\b", + " ": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + "'": "\\'", + "\\": "\\\\" +}; +var hex = 16; +var unicodeLength = 4; +function escape(char) { + return escapeCharacters[char] || `\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-unicodeLength)}`; +} +function inspectString(string, options) { + if (stringEscapeChars.test(string)) { + string = string.replace(stringEscapeChars, escape); + } + return options.stylize(`'${truncate(string, options.truncate - 2)}'`, "string"); +} + +// src/symbol.ts +function inspectSymbol(value) { + if ("description" in Symbol.prototype) { + return value.description ? `Symbol(${value.description})` : "Symbol()"; + } + return value.toString(); +} + +// src/promise.ts +var getPromiseValue = () => "Promise{\u2026}"; +try { + const { getPromiseDetails, kPending, kRejected } = process.binding("util"); + if (Array.isArray(getPromiseDetails(Promise.resolve()))) { + getPromiseValue = (value, options) => { + const [state, innerValue] = getPromiseDetails(value); + if (state === kPending) { + return "Promise{}"; + } + return `Promise${state === kRejected ? "!" : ""}{${options.inspect(innerValue, options)}}`; + }; + } +} catch (notNode) { +} +var promise_default = getPromiseValue; + +// src/object.ts +function inspectObject(object, options) { + const properties = Object.getOwnPropertyNames(object); + const symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : []; + if (properties.length === 0 && symbols.length === 0) { + return "{}"; + } + options.truncate -= 4; + options.seen = options.seen || []; + if (options.seen.includes(object)) { + return "[Circular]"; + } + options.seen.push(object); + const propertyContents = inspectList( + properties.map((key) => [key, object[key]]), + options, + inspectProperty + ); + const symbolContents = inspectList( + symbols.map((key) => [key, object[key]]), + options, + inspectProperty + ); + options.seen.pop(); + let sep = ""; + if (propertyContents && symbolContents) { + sep = ", "; + } + return `{ ${propertyContents}${sep}${symbolContents} }`; +} + +// src/class.ts +var toStringTag = typeof Symbol !== "undefined" && Symbol.toStringTag ? Symbol.toStringTag : false; +function inspectClass(value, options) { + let name = ""; + if (toStringTag && toStringTag in value) { + name = value[toStringTag]; + } + name = name || value.constructor.name; + if (!name || name === "_class") { + name = ""; + } + options.truncate -= name.length; + return `${name}${inspectObject(value, options)}`; +} + +// src/arguments.ts +function inspectArguments(args, options) { + if (args.length === 0) + return "Arguments[]"; + options.truncate -= 13; + return `Arguments[ ${inspectList(args, options)} ]`; +} + +// src/error.ts +var errorKeys = [ + "stack", + "line", + "column", + "name", + "message", + "fileName", + "lineNumber", + "columnNumber", + "number", + "description", + "cause" +]; +function inspectObject2(error, options) { + const properties = Object.getOwnPropertyNames(error).filter((key) => errorKeys.indexOf(key) === -1); + const name = error.name; + options.truncate -= name.length; + let message = ""; + if (typeof error.message === "string") { + message = truncate(error.message, options.truncate); + } else { + properties.unshift("message"); + } + message = message ? `: ${message}` : ""; + options.truncate -= message.length + 5; + options.seen = options.seen || []; + if (options.seen.includes(error)) { + return "[Circular]"; + } + options.seen.push(error); + const propertyContents = inspectList( + properties.map((key) => [key, error[key]]), + options, + inspectProperty + ); + return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ""}`; +} + +// src/html.ts +function inspectAttribute([key, value], options) { + options.truncate -= 3; + if (!value) { + return `${options.stylize(String(key), "yellow")}`; + } + return `${options.stylize(String(key), "yellow")}=${options.stylize(`"${value}"`, "string")}`; +} +function inspectHTMLCollection(collection, options) { + return inspectList(collection, options, inspectHTML, "\n"); +} +function inspectHTML(element, options) { + const properties = element.getAttributeNames(); + const name = element.tagName.toLowerCase(); + const head = options.stylize(`<${name}`, "special"); + const headClose = options.stylize(`>`, "special"); + const tail = options.stylize(``, "special"); + options.truncate -= name.length * 2 + 5; + let propertyContents = ""; + if (properties.length > 0) { + propertyContents += " "; + propertyContents += inspectList( + properties.map((key) => [key, element.getAttribute(key)]), + options, + inspectAttribute, + " " + ); + } + options.truncate -= propertyContents.length; + const truncate2 = options.truncate; + let children = inspectHTMLCollection(element.children, options); + if (children && children.length > truncate2) { + children = `${truncator}(${element.children.length})`; + } + return `${head}${propertyContents}${headClose}${children}${tail}`; +} + +// src/index.ts +var symbolsSupported = typeof Symbol === "function" && typeof Symbol.for === "function"; +var chaiInspect = symbolsSupported ? Symbol.for("chai/inspect") : "@@chai/inspect"; +var nodeInspect = false; +try { + const nodeUtil = require_util(); + nodeInspect = nodeUtil.inspect ? nodeUtil.inspect.custom : false; +} catch (noNodeInspect) { + nodeInspect = false; +} +var constructorMap = /* @__PURE__ */ new WeakMap(); +var stringTagMap = {}; +var baseTypesMap = { + undefined: (value, options) => options.stylize("undefined", "undefined"), + null: (value, options) => options.stylize("null", "null"), + boolean: (value, options) => options.stylize(String(value), "boolean"), + Boolean: (value, options) => options.stylize(String(value), "boolean"), + number: inspectNumber, + Number: inspectNumber, + bigint: inspectBigInt, + BigInt: inspectBigInt, + string: inspectString, + String: inspectString, + function: inspectFunction, + Function: inspectFunction, + symbol: inspectSymbol, + // A Symbol polyfill will return `Symbol` not `symbol` from typedetect + Symbol: inspectSymbol, + Array: inspectArray, + Date: inspectDate, + Map: inspectMap, + Set: inspectSet, + RegExp: inspectRegExp, + Promise: promise_default, + // WeakSet, WeakMap are totally opaque to us + WeakSet: (value, options) => options.stylize("WeakSet{\u2026}", "special"), + WeakMap: (value, options) => options.stylize("WeakMap{\u2026}", "special"), + Arguments: inspectArguments, + Int8Array: inspectTypedArray, + Uint8Array: inspectTypedArray, + Uint8ClampedArray: inspectTypedArray, + Int16Array: inspectTypedArray, + Uint16Array: inspectTypedArray, + Int32Array: inspectTypedArray, + Uint32Array: inspectTypedArray, + Float32Array: inspectTypedArray, + Float64Array: inspectTypedArray, + Generator: () => "", + DataView: () => "", + ArrayBuffer: () => "", + Error: inspectObject2, + HTMLCollection: inspectHTMLCollection, + NodeList: inspectHTMLCollection +}; +var inspectCustom = (value, options, type) => { + if (chaiInspect in value && typeof value[chaiInspect] === "function") { + return value[chaiInspect](options); + } + if (nodeInspect && nodeInspect in value && typeof value[nodeInspect] === "function") { + return value[nodeInspect](options.depth, options); + } + if ("inspect" in value && typeof value.inspect === "function") { + return value.inspect(options.depth, options); + } + if ("constructor" in value && constructorMap.has(value.constructor)) { + return constructorMap.get(value.constructor)(value, options); + } + if (stringTagMap[type]) { + return stringTagMap[type](value, options); + } + return ""; +}; +var toString = Object.prototype.toString; +function inspect(value, opts = {}) { + const options = normaliseOptions(opts, inspect); + const { customInspect } = options; + let type = value === null ? "null" : typeof value; + if (type === "object") { + type = toString.call(value).slice(8, -1); + } + if (type in baseTypesMap) { + return baseTypesMap[type](value, options); + } + if (customInspect && value) { + const output = inspectCustom(value, options, type); + if (output) { + if (typeof output === "string") + return output; + return inspect(output, options); + } + } + const proto = value ? Object.getPrototypeOf(value) : false; + if (proto === Object.prototype || proto === null) { + return inspectObject(value, options); + } + if (value && typeof HTMLElement === "function" && value instanceof HTMLElement) { + return inspectHTML(value, options); + } + if ("constructor" in value) { + if (value.constructor !== Object) { + return inspectClass(value, options); + } + return inspectObject(value, options); + } + if (value === Object(value)) { + return inspectObject(value, options); + } + return options.stylize(String(value), type); +} +function registerConstructor(constructor, inspector) { + if (constructorMap.has(constructor)) { + return false; + } + constructorMap.set(constructor, inspector); + return true; +} +function registerStringTag(stringTag, inspector) { + if (stringTag in stringTagMap) { + return false; + } + stringTagMap[stringTag] = inspector; + return true; +} +var custom = chaiInspect; +var src_default = inspect; diff --git a/node_modules/loupe/package.json b/node_modules/loupe/package.json new file mode 100644 index 000000000..3f93091be --- /dev/null +++ b/node_modules/loupe/package.json @@ -0,0 +1,123 @@ +{ + "name": "loupe", + "version": "3.1.2", + "description": "Inspect utility for Node.js and browsers", + "homepage": "https://github.com/chaijs/loupe", + "license": "MIT", + "author": "Veselin Todorov ", + "contributors": [ + "Keith Cirkel (https://github.com/keithamus)" + ], + "type": "module", + "main": "./lib/index.js", + "module": "./lib/index.js", + "browser": { + "./index.js": "./loupe.js", + "util": false + }, + "repository": { + "type": "git", + "url": "https://github.com/chaijs/loupe" + }, + "files": [ + "loupe.js", + "lib/*" + ], + "scripts": { + "bench": "node bench", + "lint": "eslint --ignore-path .gitignore .", + "semantic-release": "semantic-release pre && npm publish && semantic-release post", + "test": "npm run test:node && npm run test:browser", + "pretest:browser": "npx playwright install && npm run build", + "test:browser": "wtr", + "pretest:node": "npm run build", + "test:node": "mocha", + "build": "npm run build:lib && npm run build:esm-bundle && npm run build:cjs-bundle", + "build:lib": "tsc", + "build:esm-bundle": "esbuild --bundle src/index.ts --outfile=loupe.js --format=esm", + "build:cjs-bundle": "esbuild --bundle src/index.ts --outfile=loupe.js --format=cjs", + "upload-coverage": "codecov" + }, + "eslintConfig": { + "root": true, + "parserOptions": { + "ecmaVersion": 2020 + }, + "env": { + "es6": true + }, + "plugins": [ + "filenames", + "prettier" + ], + "extends": [ + "strict/es6" + ], + "rules": { + "comma-dangle": "off", + "func-style": "off", + "no-magic-numbers": "off", + "class-methods-use-this": "off", + "array-bracket-spacing": "off", + "array-element-newline": "off", + "space-before-function-paren": "off", + "arrow-parens": "off", + "template-curly-spacing": "off", + "quotes": "off", + "generator-star-spacing": "off", + "prefer-destructuring": "off", + "no-mixed-operators": "off", + "id-blacklist": "off", + "curly": "off", + "semi": [ + "error", + "never" + ], + "prettier/prettier": [ + "error", + { + "printWidth": 120, + "tabWidth": 2, + "useTabs": false, + "semi": false, + "singleQuote": true, + "trailingComma": "es5", + "arrowParens": "avoid", + "bracketSpacing": true + } + ] + } + }, + "prettier": { + "printWidth": 120, + "tabWidth": 2, + "useTabs": false, + "semi": false, + "singleQuote": true, + "trailingComma": "es5", + "arrowParens": "avoid", + "bracketSpacing": true + }, + "devDependencies": { + "@web/dev-server-esbuild": "^0.4.2", + "@web/test-runner": "^0.17.2", + "@web/test-runner-playwright": "^0.10.1", + "benchmark": "^2.1.4", + "chai": "^5.0.0-alpha.0", + "codecov": "^3.8.1", + "core-js": "^3.8.3", + "cross-env": "^7.0.3", + "esbuild": "^0.19.5", + "eslint": "^7.18.0", + "eslint-config-strict": "^14.0.1", + "eslint-plugin-filenames": "^1.3.2", + "eslint-plugin-prettier": "^3.3.1", + "husky": "^4.3.8", + "mocha": "^10.2.0", + "nyc": "^15.1.0", + "prettier": "^2.2.1", + "semantic-release": "^17.3.6", + "simple-assert": "^1.0.0", + "typescript": "^5.0.0-beta" + } +} diff --git a/node_modules/mime-db/HISTORY.md b/node_modules/mime-db/HISTORY.md new file mode 100644 index 000000000..7436f6414 --- /dev/null +++ b/node_modules/mime-db/HISTORY.md @@ -0,0 +1,507 @@ +1.52.0 / 2022-02-21 +=================== + + * Add extensions from IANA for more `image/*` types + * Add extension `.asc` to `application/pgp-keys` + * Add extensions to various XML types + * Add new upstream MIME types + +1.51.0 / 2021-11-08 +=================== + + * Add new upstream MIME types + * Mark `image/vnd.microsoft.icon` as compressible + * Mark `image/vnd.ms-dds` as compressible + +1.50.0 / 2021-09-15 +=================== + + * Add deprecated iWorks mime types and extensions + * Add new upstream MIME types + +1.49.0 / 2021-07-26 +=================== + + * Add extension `.trig` to `application/trig` + * Add new upstream MIME types + +1.48.0 / 2021-05-30 +=================== + + * Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + * Add new upstream MIME types + * Mark `text/yaml` as compressible + +1.47.0 / 2021-04-01 +=================== + + * Add new upstream MIME types + * Remove ambigious extensions from IANA for `application/*+xml` types + * Update primary extension to `.es` for `application/ecmascript` + +1.46.0 / 2021-02-13 +=================== + + * Add extension `.amr` to `audio/amr` + * Add extension `.m4s` to `video/iso.segment` + * Add extension `.opus` to `audio/ogg` + * Add new upstream MIME types + +1.45.0 / 2020-09-22 +=================== + + * Add `application/ubjson` with extension `.ubj` + * Add `image/avif` with extension `.avif` + * Add `image/ktx2` with extension `.ktx2` + * Add extension `.dbf` to `application/vnd.dbf` + * Add extension `.rar` to `application/vnd.rar` + * Add extension `.td` to `application/urc-targetdesc+xml` + * Add new upstream MIME types + * Fix extension of `application/vnd.apple.keynote` to be `.key` + +1.44.0 / 2020-04-22 +=================== + + * Add charsets from IANA + * Add extension `.cjs` to `application/node` + * Add new upstream MIME types + +1.43.0 / 2020-01-05 +=================== + + * Add `application/x-keepass2` with extension `.kdbx` + * Add extension `.mxmf` to `audio/mobile-xmf` + * Add extensions from IANA for `application/*+xml` types + * Add new upstream MIME types + +1.42.0 / 2019-09-25 +=================== + + * Add `image/vnd.ms-dds` with extension `.dds` + * Add new upstream MIME types + * Remove compressible from `multipart/mixed` + +1.41.0 / 2019-08-30 +=================== + + * Add new upstream MIME types + * Add `application/toml` with extension `.toml` + * Mark `font/ttf` as compressible + +1.40.0 / 2019-04-20 +=================== + + * Add extensions from IANA for `model/*` types + * Add `text/mdx` with extension `.mdx` + +1.39.0 / 2019-04-04 +=================== + + * Add extensions `.siv` and `.sieve` to `application/sieve` + * Add new upstream MIME types + +1.38.0 / 2019-02-04 +=================== + + * Add extension `.nq` to `application/n-quads` + * Add extension `.nt` to `application/n-triples` + * Add new upstream MIME types + * Mark `text/less` as compressible + +1.37.0 / 2018-10-19 +=================== + + * Add extensions to HEIC image types + * Add new upstream MIME types + +1.36.0 / 2018-08-20 +=================== + + * Add Apple file extensions from IANA + * Add extensions from IANA for `image/*` types + * Add new upstream MIME types + +1.35.0 / 2018-07-15 +=================== + + * Add extension `.owl` to `application/rdf+xml` + * Add new upstream MIME types + - Removes extension `.woff` from `application/font-woff` + +1.34.0 / 2018-06-03 +=================== + + * Add extension `.csl` to `application/vnd.citationstyles.style+xml` + * Add extension `.es` to `application/ecmascript` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/turtle` + * Mark all XML-derived types as compressible + +1.33.0 / 2018-02-15 +=================== + + * Add extensions from IANA for `message/*` types + * Add new upstream MIME types + * Fix some incorrect OOXML types + * Remove `application/font-woff2` + +1.32.0 / 2017-11-29 +=================== + + * Add new upstream MIME types + * Update `text/hjson` to registered `application/hjson` + * Add `text/shex` with extension `.shex` + +1.31.0 / 2017-10-25 +=================== + + * Add `application/raml+yaml` with extension `.raml` + * Add `application/wasm` with extension `.wasm` + * Add new `font` type from IANA + * Add new upstream font extensions + * Add new upstream MIME types + * Add extensions for JPEG-2000 images + +1.30.0 / 2017-08-27 +=================== + + * Add `application/vnd.ms-outlook` + * Add `application/x-arj` + * Add extension `.mjs` to `application/javascript` + * Add glTF types and extensions + * Add new upstream MIME types + * Add `text/x-org` + * Add VirtualBox MIME types + * Fix `source` records for `video/*` types that are IANA + * Update `font/opentype` to registered `font/otf` + +1.29.0 / 2017-07-10 +=================== + + * Add `application/fido.trusted-apps+json` + * Add extension `.wadl` to `application/vnd.sun.wadl+xml` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/css` + +1.28.0 / 2017-05-14 +=================== + + * Add new upstream MIME types + * Add extension `.gz` to `application/gzip` + * Update extensions `.md` and `.markdown` to be `text/markdown` + +1.27.0 / 2017-03-16 +=================== + + * Add new upstream MIME types + * Add `image/apng` with extension `.apng` + +1.26.0 / 2017-01-14 +=================== + + * Add new upstream MIME types + * Add extension `.geojson` to `application/geo+json` + +1.25.0 / 2016-11-11 +=================== + + * Add new upstream MIME types + +1.24.0 / 2016-09-18 +=================== + + * Add `audio/mp3` + * Add new upstream MIME types + +1.23.0 / 2016-05-01 +=================== + + * Add new upstream MIME types + * Add extension `.3gpp` to `audio/3gpp` + +1.22.0 / 2016-02-15 +=================== + + * Add `text/slim` + * Add extension `.rng` to `application/xml` + * Add new upstream MIME types + * Fix extension of `application/dash+xml` to be `.mpd` + * Update primary extension to `.m4a` for `audio/mp4` + +1.21.0 / 2016-01-06 +=================== + + * Add Google document types + * Add new upstream MIME types + +1.20.0 / 2015-11-10 +=================== + + * Add `text/x-suse-ymp` + * Add new upstream MIME types + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.apple.pkpass` + * Add new upstream MIME types + +1.18.0 / 2015-09-03 +=================== + + * Add new upstream MIME types + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +1.13.0 / 2015-06-07 +=================== + + * Add nginx as a source + * Add `application/x-cocoa` + * Add `application/x-java-archive-diff` + * Add `application/x-makeself` + * Add `application/x-perl` + * Add `application/x-pilot` + * Add `application/x-redhat-package-manager` + * Add `application/x-sea` + * Add `audio/x-m4a` + * Add `audio/x-realaudio` + * Add `image/x-jng` + * Add `text/mathml` + +1.12.0 / 2015-06-05 +=================== + + * Add `application/bdoc` + * Add `application/vnd.hyperdrive+json` + * Add `application/x-bdoc` + * Add extension `.rtf` to `text/rtf` + +1.11.0 / 2015-05-31 +=================== + + * Add `audio/wav` + * Add `audio/wave` + * Add extension `.litcoffee` to `text/coffeescript` + * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` + * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` + +1.10.0 / 2015-05-19 +=================== + + * Add `application/vnd.balsamiq.bmpr` + * Add `application/vnd.microsoft.portable-executable` + * Add `application/x-ns-proxy-autoconfig` + +1.9.1 / 2015-04-19 +================== + + * Remove `.json` extension from `application/manifest+json` + - This is causing bugs downstream + +1.9.0 / 2015-04-19 +================== + + * Add `application/manifest+json` + * Add `application/vnd.micro+json` + * Add `image/vnd.zbrush.pcx` + * Add `image/x-ms-bmp` + +1.8.0 / 2015-03-13 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/node_modules/mime-db/LICENSE b/node_modules/mime-db/LICENSE new file mode 100644 index 000000000..0751cb10e --- /dev/null +++ b/node_modules/mime-db/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015-2022 Douglas Christopher Wilson + +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/node_modules/mime-db/README.md b/node_modules/mime-db/README.md new file mode 100644 index 000000000..5a8fcfe4d --- /dev/null +++ b/node_modules/mime-db/README.md @@ -0,0 +1,100 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a large database of mime types and information about them. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +It aggregates data from the following sources: + +- http://www.iana.org/assignments/media-types/media-types.xhtml +- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +- http://hg.nginx.org/nginx/raw-file/default/conf/mime.types + +## Installation + +```bash +npm install mime-db +``` + +### Database Download + +If you're crazy enough to use this in the browser, you can just grab the +JSON file using [jsDelivr](https://www.jsdelivr.com/). It is recommended to +replace `master` with [a release tag](https://github.com/jshttp/mime-db/tags) +as the JSON format may change in the future. + +``` +https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json +``` + +## Usage + +```js +var db = require('mime-db') + +// grab data on .js files +var data = db['application/javascript'] +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + If not set, it's probably a custom media type. + - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) + - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) + - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) +- `.extensions[]` - known extensions associated with this mime type. +- `.compressible` - whether a file of this type can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom-types.json` or +`src/custom-suffix.json`. + +The `src/custom-types.json` file is a JSON object with the MIME type as the +keys and the values being an object with the following keys: + +- `compressible` - leave out if you don't know, otherwise `true`/`false` to + indicate whether the data represented by the type is typically compressible. +- `extensions` - include an array of file extensions that are associated with + the type. +- `notes` - human-readable notes about the type, typically what the type is. +- `sources` - include an array of URLs of where the MIME type and the associated + extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); + links to type aggregating sites and Wikipedia are _not acceptable_. + +To update the build, run `npm run build`. + +### Adding Custom Media Types + +The best way to get new media types included in this library is to register +them with the IANA. The community registration procedure is outlined in +[RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types +registered with the IANA are automatically pulled into this library. + +If that is not possible / feasible, they can be added directly here as a +"custom" type. To do this, it is required to have a primary source that +definitively lists the media type. If an extension is going to be listed as +associateed with this media type, the source must definitively link the +media type and extension as well. + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-db/master?label=ci +[ci-url]: https://github.com/jshttp/mime-db/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master +[node-image]: https://badgen.net/npm/node/mime-db +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-db +[npm-url]: https://npmjs.org/package/mime-db +[npm-version-image]: https://badgen.net/npm/v/mime-db diff --git a/node_modules/mime-db/db.json b/node_modules/mime-db/db.json new file mode 100644 index 000000000..eb9c42c45 --- /dev/null +++ b/node_modules/mime-db/db.json @@ -0,0 +1,8519 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/3gpp-ims+xml": { + "source": "iana", + "compressible": true + }, + "application/3gpphal+json": { + "source": "iana", + "compressible": true + }, + "application/3gpphalforms+json": { + "source": "iana", + "compressible": true + }, + "application/a2l": { + "source": "iana" + }, + "application/ace+cbor": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/activity+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamcontrol+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamparams+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/at+jwt": { + "source": "iana" + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomdeleted"] + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomsvc"] + }, + "application/atsc-dwd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dwd"] + }, + "application/atsc-dynamic-event-message": { + "source": "iana" + }, + "application/atsc-held+xml": { + "source": "iana", + "compressible": true, + "extensions": ["held"] + }, + "application/atsc-rdt+json": { + "source": "iana", + "compressible": true + }, + "application/atsc-rsat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsat"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana", + "compressible": true + }, + "application/bacnet-xdd+zip": { + "source": "iana", + "compressible": false + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xcs"] + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/captive+json": { + "source": "iana", + "compressible": true + }, + "application/cbor": { + "source": "iana" + }, + "application/cbor-seq": { + "source": "iana" + }, + "application/cccex": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana", + "compressible": true + }, + "application/ccxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdfx"] + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana", + "compressible": true + }, + "application/cellml+xml": { + "source": "iana", + "compressible": true + }, + "application/cfw": { + "source": "iana" + }, + "application/city+json": { + "source": "iana", + "compressible": true + }, + "application/clr": { + "source": "iana" + }, + "application/clue+xml": { + "source": "iana", + "compressible": true + }, + "application/clue_info+xml": { + "source": "iana", + "compressible": true + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana", + "compressible": true + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/coap-payload": { + "source": "iana" + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/cose": { + "source": "iana" + }, + "application/cose-key": { + "source": "iana" + }, + "application/cose-key-set": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cpl"] + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana", + "compressible": true + }, + "application/cstadata+xml": { + "source": "iana", + "compressible": true + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cwt": { + "source": "iana" + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpd"] + }, + "application/dash-patch+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "compressible": true, + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana", + "compressible": true + }, + "application/dicom": { + "source": "iana" + }, + "application/dicom+json": { + "source": "iana", + "compressible": true + }, + "application/dicom+xml": { + "source": "iana", + "compressible": true + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/dns+json": { + "source": "iana", + "compressible": true + }, + "application/dns-message": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dbk"] + }, + "application/dots+cbor": { + "source": "iana" + }, + "application/dskpp+xml": { + "source": "iana", + "compressible": true + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["es","ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/efi": { + "source": "iana" + }, + "application/elm+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/elm+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.cap+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/emergencycalldata.comment+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.control+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.ecall.msd": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.veds+xml": { + "source": "iana", + "compressible": true + }, + "application/emma+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emotionml"] + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana", + "compressible": true + }, + "application/epub+zip": { + "source": "iana", + "compressible": false, + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/expect-ct-report+json": { + "source": "iana", + "compressible": true + }, + "application/express": { + "source": "iana", + "extensions": ["exp"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fdt"] + }, + "application/fhir+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fhir+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fido.trusted-apps+json": { + "compressible": true + }, + "application/fits": { + "source": "iana" + }, + "application/flexfec": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false + }, + "application/framework-attributes+xml": { + "source": "iana", + "compressible": true + }, + "application/geo+json": { + "source": "iana", + "compressible": true, + "extensions": ["geojson"] + }, + "application/geo+json-seq": { + "source": "iana" + }, + "application/geopackage+sqlite3": { + "source": "iana" + }, + "application/geoxacml+xml": { + "source": "iana", + "compressible": true + }, + "application/gltf-buffer": { + "source": "iana" + }, + "application/gml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false, + "extensions": ["gz"] + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana", + "compressible": true + }, + "application/hjson": { + "extensions": ["hjson"] + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pkg-reply+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana", + "compressible": true, + "extensions": ["its"] + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js","mjs"] + }, + "application/jf2feed+json": { + "source": "iana", + "compressible": true + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/jscalendar+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana", + "compressible": true + }, + "application/kpml-response+xml": { + "source": "iana", + "compressible": true + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/lgr+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lgr"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana", + "compressible": true + }, + "application/lost+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana", + "compressible": true + }, + "application/lpf+zip": { + "source": "iana", + "compressible": false + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mads"] + }, + "application/manifest+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana", + "compressible": true + }, + "application/mathml-presentation+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-deregister+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-envelope+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-protection-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-reception-report+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-user-service-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpf"] + }, + "application/media_control+xml": { + "source": "iana", + "compressible": true + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "compressible": true, + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "compressible": true, + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mipc": { + "source": "iana" + }, + "application/missing-blocks+cbor-seq": { + "source": "iana" + }, + "application/mmt-aei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["maei"] + }, + "application/mmt-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musd"] + }, + "application/mods+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana", + "compressible": true + }, + "application/mrb-publish+xml": { + "source": "iana", + "compressible": true + }, + "application/msc-ivr+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msc-mixer+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mud+json": { + "source": "iana", + "compressible": true + }, + "application/multipart-core": { + "source": "iana" + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/n-quads": { + "source": "iana", + "extensions": ["nq"] + }, + "application/n-triples": { + "source": "iana", + "extensions": ["nt"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-groupinfo": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana", + "compressible": true + }, + "application/node": { + "source": "iana", + "extensions": ["cjs"] + }, + "application/nss": { + "source": "iana" + }, + "application/oauth-authz-req+jwt": { + "source": "iana" + }, + "application/oblivious-dns-message": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] + }, + "application/oda": { + "source": "iana", + "extensions": ["oda"] + }, + "application/odm+xml": { + "source": "iana", + "compressible": true + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/opc-nodeset+xml": { + "source": "iana", + "compressible": true + }, + "application/oscore": { + "source": "iana" + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p21": { + "source": "iana" + }, + "application/p21+zip": { + "source": "iana", + "compressible": false + }, + "application/p2p-overlay+xml": { + "source": "iana", + "compressible": true, + "extensions": ["relo"] + }, + "application/parityfec": { + "source": "iana" + }, + "application/passport": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pem-certificate-chain": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana", + "extensions": ["asc"] + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pidf-diff+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkcs8-encrypted": { + "source": "iana" + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/ppsp-tracker+json": { + "source": "iana", + "compressible": true + }, + "application/problem+json": { + "source": "iana", + "compressible": true + }, + "application/problem+xml": { + "source": "iana", + "compressible": true + }, + "application/provenance+xml": { + "source": "iana", + "compressible": true, + "extensions": ["provx"] + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.cyn": { + "source": "iana", + "charset": "7-BIT" + }, + "application/prs.hpub+zip": { + "source": "iana", + "compressible": false + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana", + "compressible": true + }, + "application/pskc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pskcxml"] + }, + "application/pvd+json": { + "source": "iana", + "compressible": true + }, + "application/qsig": { + "source": "iana" + }, + "application/raml+yaml": { + "compressible": true, + "extensions": ["raml"] + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf","owl"] + }, + "application/reginfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana", + "compressible": true + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana", + "compressible": true + }, + "application/rls-services+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rs"] + }, + "application/route-apd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rapd"] + }, + "application/route-s-tsid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sls"] + }, + "application/route-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rusd"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-publication": { + "source": "iana" + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana", + "compressible": true + }, + "application/samlmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/sarif+json": { + "source": "iana", + "compressible": true + }, + "application/sarif-external-properties+json": { + "source": "iana", + "compressible": true + }, + "application/sbe": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana", + "compressible": true + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/secevent+jwt": { + "source": "iana" + }, + "application/senml+cbor": { + "source": "iana" + }, + "application/senml+json": { + "source": "iana", + "compressible": true + }, + "application/senml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["senmlx"] + }, + "application/senml-etch+cbor": { + "source": "iana" + }, + "application/senml-etch+json": { + "source": "iana", + "compressible": true + }, + "application/senml-exi": { + "source": "iana" + }, + "application/sensml+cbor": { + "source": "iana" + }, + "application/sensml+json": { + "source": "iana", + "compressible": true + }, + "application/sensml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sensmlx"] + }, + "application/sensml-exi": { + "source": "iana" + }, + "application/sep+xml": { + "source": "iana", + "compressible": true + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana", + "extensions": ["siv","sieve"] + }, + "application/simple-filter+xml": { + "source": "iana", + "compressible": true + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/sipc": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "compressible": true, + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "compressible": true, + "extensions": ["srx"] + }, + "application/spdx+json": { + "source": "iana", + "compressible": true + }, + "application/spirits-event+xml": { + "source": "iana", + "compressible": true + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ssml"] + }, + "application/stix+json": { + "source": "iana", + "compressible": true + }, + "application/swid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["swidtag"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/taxii+json": { + "source": "iana", + "compressible": true + }, + "application/td+json": { + "source": "iana", + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tei","teicorpus"] + }, + "application/tetra_isi": { + "source": "iana" + }, + "application/thraud+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/tlsrpt+gzip": { + "source": "iana" + }, + "application/tlsrpt+json": { + "source": "iana", + "compressible": true + }, + "application/tnauthlist": { + "source": "iana" + }, + "application/token-introspection+jwt": { + "source": "iana" + }, + "application/toml": { + "compressible": true, + "extensions": ["toml"] + }, + "application/trickle-ice-sdpfrag": { + "source": "iana" + }, + "application/trig": { + "source": "iana", + "extensions": ["trig"] + }, + "application/ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ttml"] + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/tzif": { + "source": "iana" + }, + "application/tzif-leap": { + "source": "iana" + }, + "application/ubjson": { + "compressible": false, + "extensions": ["ubj"] + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-ressheet+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsheet"] + }, + "application/urc-targetdesc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["td"] + }, + "application/urc-uisocketdesc+xml": { + "source": "iana", + "compressible": true + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana", + "compressible": true + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + "source": "iana", + "compressible": true, + "extensions": ["1km"] + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-v2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.5gnas": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gmop+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gtpc": { + "source": "iana" + }, + "application/vnd.3gpp.interworking-data": { + "source": "iana" + }, + "application/vnd.3gpp.lpp": { + "source": "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-payload": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-signalling": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ngap": { + "source": "iana" + }, + "application/vnd.3gpp.pfcp": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.s1ap": { + "source": "iana" + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.sms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + "source": "iana" + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "compressible": false, + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + "source": "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + "source": "iana" + }, + "application/vnd.afpc.foca-charset": { + "source": "iana" + }, + "application/vnd.afpc.foca-codedfont": { + "source": "iana" + }, + "application/vnd.afpc.foca-codepage": { + "source": "iana" + }, + "application/vnd.afpc.modca": { + "source": "iana" + }, + "application/vnd.afpc.modca-cmtable": { + "source": "iana" + }, + "application/vnd.afpc.modca-formdef": { + "source": "iana" + }, + "application/vnd.afpc.modca-mediummap": { + "source": "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + "source": "iana" + }, + "application/vnd.afpc.modca-overlay": { + "source": "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + "source": "iana" + }, + "application/vnd.age": { + "source": "iana", + "extensions": ["age"] + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amadeus+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + "source": "iana" + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.android.ota": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.arrow.file": { + "source": "iana" + }, + "application/vnd.apache.arrow.stream": { + "source": "iana" + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.aplextor.warrp+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apothekende.reservation+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpkg"] + }, + "application/vnd.apple.keynote": { + "source": "iana", + "extensions": ["key"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.numbers": { + "source": "iana", + "extensions": ["numbers"] + }, + "application/vnd.apple.pages": { + "source": "iana", + "extensions": ["pages"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artisan+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avalon+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.avistar+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["bmml"] + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.banana-accounting": { + "source": "iana" + }, + "application/vnd.bbf.usp.error": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bint.med-content": { + "source": "iana" + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.blink-idb-value-wrapper": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.bpf": { + "source": "iana" + }, + "application/vnd.bpf3": { + "source": "iana" + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.byu.uapi+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.capasystems-pg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdxml"] + }, + "application/vnd.chess-pgn": { + "source": "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.ciedi": { + "source": "iana" + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana", + "compressible": true, + "extensions": ["csl"] + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.comicbook+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.comicbook-rar": { + "source": "iana" + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wbs"] + }, + "application/vnd.cryptii.pipe+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.crypto-shade-file": { + "source": "iana" + }, + "application/vnd.cryptomator.encrypted": { + "source": "iana" + }, + "application/vnd.cryptomator.vault": { + "source": "iana" + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.cyclonedx+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cyclonedx+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.d3m-dataset": { + "source": "iana" + }, + "application/vnd.d3m-problem": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.datapackage+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dataresource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dbf": { + "source": "iana", + "extensions": ["dbf"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume.movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbisl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecip.rlp": { + "source": "iana" + }, + "application/vnd.eclipse.ditto+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.efi.img": { + "source": "iana" + }, + "application/vnd.efi.iso": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.espass-espass+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "compressible": true, + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.cug+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.sci+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eu.kasparian.car+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.evolv.ecig.profile": { + "source": "iana" + }, + "application/vnd.evolv.ecig.settings": { + "source": "iana" + }, + "application/vnd.evolv.ecig.theme": { + "source": "iana" + }, + "application/vnd.exstream-empower+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.exstream-package": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.familysearch.gedcom+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.ficlab.flb+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujifilm.fb.docuworks": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.futoin+cbor": { + "source": "iana" + }, + "application/vnd.futoin+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.gentics.grd+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.slides": { + "source": "iana" + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "compressible": true, + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.hdt": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hl7cda+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.hl7v2+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyper-item+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.imagemeter.image+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.iso11783-10+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las": { + "source": "iana" + }, + "application/vnd.las.las+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.las.las+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lasxml"] + }, + "application/vnd.laszip": { + "source": "iana" + }, + "application/vnd.leap+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.liberty-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lbe"] + }, + "application/vnd.logipipe.circuit+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.loom": { + "source": "iana" + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana", + "extensions": ["mvt"] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxar.archive.3tz+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-outlook": { + "compressible": false, + "extensions": ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-printschematicket+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.nacamar.ybrid+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nearst.inv+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nebumind.line": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nimn": { + "source": "iana" + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ac"] + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.ocf+cbor": { + "source": "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+cbor": { + "source": "iana" + }, + "application/vnd.oma.lwm2m+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+tlv": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-email+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-file+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-folder+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.onepager": { + "source": "iana" + }, + "application/vnd.onepagertamp": { + "source": "iana" + }, + "application/vnd.onepagertamx": { + "source": "iana" + }, + "application/vnd.onepagertat": { + "source": "iana" + }, + "application/vnd.onepagertatp": { + "source": "iana" + }, + "application/vnd.onepagertatx": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana", + "compressible": true, + "extensions": ["obgx"] + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osm"] + }, + "application/vnd.opentimestamps.ots": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "iana", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "iana", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "iana", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "iana" + }, + "application/vnd.patentdive": { + "source": "iana" + }, + "application/vnd.patientecommsdoc": { + "source": "iana" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.psfs": { + "source": "iana" + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quarantainenet": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.rar": { + "source": "iana", + "extensions": ["rar"] + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.resilient.logic": { + "source": "iana" + }, + "application/vnd.restful+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "compressible": true, + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sar": { + "source": "iana" + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.seis+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shade-save-file": { + "source": "iana" + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.shootproof+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shopkick+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shp": { + "source": "iana" + }, + "application/vnd.shx": { + "source": "iana" + }, + "application/vnd.sigrok.session": { + "source": "iana" + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.snesdev-page-table": { + "source": "iana" + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fo"] + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sqlite3": { + "source": "iana" + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wadl"] + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.sycle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.syft+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["ddf"] + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tableschema+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.tri.onesource": { + "source": "iana" + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.vel+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.veritone.aion+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.veryant.thin": { + "source": "iana" + }, + "application/vnd.ves.encrypted": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.dpp": { + "source": "iana" + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.wv.ssp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.youtube.yt": { + "source": "iana" + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["vxml"] + }, + "application/voucher-cms+json": { + "source": "iana", + "compressible": true + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/wasm": { + "source": "iana", + "compressible": true, + "extensions": ["wasm"] + }, + "application/watcherinfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wif"] + }, + "application/webpush-options+json": { + "source": "iana", + "compressible": true + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-arj": { + "compressible": false, + "extensions": ["arj"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "compressible": true, + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-iwork-keynote-sffkey": { + "extensions": ["key"] + }, + "application/x-iwork-numbers-sffnumbers": { + "extensions": ["numbers"] + }, + "application/x-iwork-pages-sffpages": { + "extensions": ["pages"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-keepass2": { + "extensions": ["kdbx"] + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "source": "apache", + "extensions": ["nc","cdf"] + }, + "application/x-ns-proxy-autoconfig": { + "compressible": true, + "extensions": ["pac"] + }, + "application/x-nzb": { + "source": "apache", + "extensions": ["nzb"] + }, + "application/x-perl": { + "source": "nginx", + "extensions": ["pl","pm"] + }, + "application/x-pilot": { + "source": "nginx", + "extensions": ["prc","pdb"] + }, + "application/x-pkcs12": { + "source": "apache", + "compressible": false, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-pki-message": { + "source": "iana" + }, + "application/x-rar-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["rar"] + }, + "application/x-redhat-package-manager": { + "source": "nginx", + "extensions": ["rpm"] + }, + "application/x-research-info-systems": { + "source": "apache", + "extensions": ["ris"] + }, + "application/x-sea": { + "source": "nginx", + "extensions": ["sea"] + }, + "application/x-sh": { + "source": "apache", + "compressible": true, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-virtualbox-hdd": { + "compressible": true, + "extensions": ["hdd"] + }, + "application/x-virtualbox-ova": { + "compressible": true, + "extensions": ["ova"] + }, + "application/x-virtualbox-ovf": { + "compressible": true, + "extensions": ["ovf"] + }, + "application/x-virtualbox-vbox": { + "compressible": true, + "extensions": ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + "compressible": false, + "extensions": ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + "compressible": true, + "extensions": ["vdi"] + }, + "application/x-virtualbox-vhd": { + "compressible": true, + "extensions": ["vhd"] + }, + "application/x-virtualbox-vmdk": { + "compressible": true, + "extensions": ["vmdk"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "iana", + "extensions": ["der","crt","pem"] + }, + "application/x-x509-ca-ra-cert": { + "source": "iana" + }, + "application/x-x509-next-ca-cert": { + "source": "iana" + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana", + "compressible": true + }, + "application/xaml+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xav"] + }, + "application/xcap-caps+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xca"] + }, + "application/xcap-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xel"] + }, + "application/xcap-error+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-ns+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xns"] + }, + "application/xcon-conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana", + "compressible": true + }, + "application/xenc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache", + "compressible": true + }, + "application/xliff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xlf"] + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd","rng"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/xmpp+xml": { + "source": "iana", + "compressible": true + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsl","xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yang-data+json": { + "source": "iana", + "compressible": true + }, + "application/yang-data+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+json": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/yin+xml": { + "source": "iana", + "compressible": true, + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "application/zstd": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana", + "compressible": false, + "extensions": ["3gpp"] + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/aac": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana", + "extensions": ["amr"] + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/flexfec": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/melp": { + "source": "iana" + }, + "audio/melp1200": { + "source": "iana" + }, + "audio/melp2400": { + "source": "iana" + }, + "audio/melp600": { + "source": "iana" + }, + "audio/mhas": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana", + "extensions": ["mxmf"] + }, + "audio/mp3": { + "compressible": false, + "extensions": ["mp3"] + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["m4a","mp4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx","opus"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/scip": { + "source": "iana" + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sofa": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tetra_acelp": { + "source": "iana" + }, + "audio/tetra_acelp_bb": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/tsvcis": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/usac": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dts.uhd": { + "source": "iana" + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.presonus.multitrack": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/collection": { + "source": "iana", + "extensions": ["ttc"] + }, + "font/otf": { + "source": "iana", + "compressible": true, + "extensions": ["otf"] + }, + "font/sfnt": { + "source": "iana" + }, + "font/ttf": { + "source": "iana", + "compressible": true, + "extensions": ["ttf"] + }, + "font/woff": { + "source": "iana", + "extensions": ["woff"] + }, + "font/woff2": { + "source": "iana", + "extensions": ["woff2"] + }, + "image/aces": { + "source": "iana", + "extensions": ["exr"] + }, + "image/apng": { + "compressible": false, + "extensions": ["apng"] + }, + "image/avci": { + "source": "iana", + "extensions": ["avci"] + }, + "image/avcs": { + "source": "iana", + "extensions": ["avcs"] + }, + "image/avif": { + "source": "iana", + "compressible": false, + "extensions": ["avif"] + }, + "image/bmp": { + "source": "iana", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/dicom-rle": { + "source": "iana", + "extensions": ["drle"] + }, + "image/emf": { + "source": "iana", + "extensions": ["emf"] + }, + "image/fits": { + "source": "iana", + "extensions": ["fits"] + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/heic": { + "source": "iana", + "extensions": ["heic"] + }, + "image/heic-sequence": { + "source": "iana", + "extensions": ["heics"] + }, + "image/heif": { + "source": "iana", + "extensions": ["heif"] + }, + "image/heif-sequence": { + "source": "iana", + "extensions": ["heifs"] + }, + "image/hej2k": { + "source": "iana", + "extensions": ["hej2"] + }, + "image/hsj2": { + "source": "iana", + "extensions": ["hsj2"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jls": { + "source": "iana", + "extensions": ["jls"] + }, + "image/jp2": { + "source": "iana", + "compressible": false, + "extensions": ["jp2","jpg2"] + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jph": { + "source": "iana", + "extensions": ["jph"] + }, + "image/jphc": { + "source": "iana", + "extensions": ["jhc"] + }, + "image/jpm": { + "source": "iana", + "compressible": false, + "extensions": ["jpm"] + }, + "image/jpx": { + "source": "iana", + "compressible": false, + "extensions": ["jpx","jpf"] + }, + "image/jxr": { + "source": "iana", + "extensions": ["jxr"] + }, + "image/jxra": { + "source": "iana", + "extensions": ["jxra"] + }, + "image/jxrs": { + "source": "iana", + "extensions": ["jxrs"] + }, + "image/jxs": { + "source": "iana", + "extensions": ["jxs"] + }, + "image/jxsc": { + "source": "iana", + "extensions": ["jxsc"] + }, + "image/jxsi": { + "source": "iana", + "extensions": ["jxsi"] + }, + "image/jxss": { + "source": "iana", + "extensions": ["jxss"] + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/ktx2": { + "source": "iana", + "extensions": ["ktx2"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana", + "extensions": ["pti"] + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana", + "extensions": ["t38"] + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tif","tiff"] + }, + "image/tiff-fx": { + "source": "iana", + "extensions": ["tfx"] + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana", + "extensions": ["azv"] + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana", + "compressible": true, + "extensions": ["ico"] + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-dds": { + "compressible": true, + "extensions": ["dds"] + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.pco.b16": { + "source": "iana", + "extensions": ["b16"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana", + "extensions": ["tap"] + }, + "image/vnd.valve.source.texture": { + "source": "iana", + "extensions": ["vtf"] + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana", + "extensions": ["pcx"] + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/wmf": { + "source": "iana", + "extensions": ["wmf"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "compressible": true, + "extensions": ["ico"] + }, + "image/x-jng": { + "source": "nginx", + "extensions": ["jng"] + }, + "image/x-mrsid-image": { + "source": "apache", + "extensions": ["sid"] + }, + "image/x-ms-bmp": { + "source": "nginx", + "compressible": true, + "extensions": ["bmp"] + }, + "image/x-pcx": { + "source": "apache", + "extensions": ["pcx"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana", + "extensions": [ + "disposition-notification" + ] + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana", + "extensions": ["u8msg"] + }, + "message/global-delivery-status": { + "source": "iana", + "extensions": ["u8dsn"] + }, + "message/global-disposition-notification": { + "source": "iana", + "extensions": ["u8mdn"] + }, + "message/global-headers": { + "source": "iana", + "extensions": ["u8hdr"] + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana", + "extensions": ["wsc"] + }, + "model/3mf": { + "source": "iana", + "extensions": ["3mf"] + }, + "model/e57": { + "source": "iana" + }, + "model/gltf+json": { + "source": "iana", + "compressible": true, + "extensions": ["gltf"] + }, + "model/gltf-binary": { + "source": "iana", + "compressible": true, + "extensions": ["glb"] + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/mtl": { + "source": "iana", + "extensions": ["mtl"] + }, + "model/obj": { + "source": "iana", + "extensions": ["obj"] + }, + "model/step": { + "source": "iana" + }, + "model/step+xml": { + "source": "iana", + "compressible": true, + "extensions": ["stpx"] + }, + "model/step+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpz"] + }, + "model/step-xml+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpxz"] + }, + "model/stl": { + "source": "iana", + "extensions": ["stl"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana", + "compressible": true + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana", + "extensions": ["ogex"] + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana", + "extensions": ["x_b"] + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana", + "extensions": ["x_t"] + }, + "model/vnd.pytha.pyox": { + "source": "iana" + }, + "model/vnd.rosette.annotated-data-model": { + "source": "iana" + }, + "model/vnd.sap.vds": { + "source": "iana", + "extensions": ["vds"] + }, + "model/vnd.usdz+zip": { + "source": "iana", + "compressible": false, + "extensions": ["usdz"] + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana", + "extensions": ["bsp"] + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana", + "extensions": ["x3db"] + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana", + "extensions": ["x3dv"] + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana" + }, + "multipart/multilingual": { + "source": "iana" + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/vnd.bint.med-plus": { + "source": "iana" + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/cql": { + "source": "iana" + }, + "text/cql-expression": { + "source": "iana" + }, + "text/cql-identifier": { + "source": "iana" + }, + "text/css": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fhirpath": { + "source": "iana" + }, + "text/flexfec": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/gff3": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "compressible": true, + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana", + "compressible": true, + "extensions": ["markdown","md"] + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mdx": { + "compressible": true, + "extensions": ["mdx"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana", + "charset": "UTF-8" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana", + "charset": "UTF-8" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/prs.prop.logic": { + "source": "iana" + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/shaclc": { + "source": "iana" + }, + "text/shex": { + "source": "iana", + "extensions": ["shex"] + }, + "text/slim": { + "extensions": ["slim","slm"] + }, + "text/spdx": { + "source": "iana", + "extensions": ["spdx"] + }, + "text/strings": { + "source": "iana" + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.ascii-art": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.familysearch.gedcom": { + "source": "iana", + "extensions": ["ged"] + }, + "text/vnd.ficlab.flt": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.gml": { + "source": "iana" + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.hans": { + "source": "iana" + }, + "text/vnd.hgl": { + "source": "iana" + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.senx.warpscript": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sosi": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-org": { + "compressible": true, + "extensions": ["org"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "compressible": true, + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "iana" + }, + "video/3gpp": { + "source": "iana", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "iana" + }, + "video/3gpp2": { + "source": "iana", + "extensions": ["3g2"] + }, + "video/av1": { + "source": "iana" + }, + "video/bmpeg": { + "source": "iana" + }, + "video/bt656": { + "source": "iana" + }, + "video/celb": { + "source": "iana" + }, + "video/dv": { + "source": "iana" + }, + "video/encaprtp": { + "source": "iana" + }, + "video/ffv1": { + "source": "iana" + }, + "video/flexfec": { + "source": "iana" + }, + "video/h261": { + "source": "iana", + "extensions": ["h261"] + }, + "video/h263": { + "source": "iana", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "iana" + }, + "video/h263-2000": { + "source": "iana" + }, + "video/h264": { + "source": "iana", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "iana" + }, + "video/h264-svc": { + "source": "iana" + }, + "video/h265": { + "source": "iana" + }, + "video/iso.segment": { + "source": "iana", + "extensions": ["m4s"] + }, + "video/jpeg": { + "source": "iana", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "iana" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/jxsv": { + "source": "iana" + }, + "video/mj2": { + "source": "iana", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "iana" + }, + "video/mp2p": { + "source": "iana" + }, + "video/mp2t": { + "source": "iana", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "iana" + }, + "video/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "iana" + }, + "video/mpv": { + "source": "iana" + }, + "video/nv": { + "source": "iana" + }, + "video/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "iana" + }, + "video/pointer": { + "source": "iana" + }, + "video/quicktime": { + "source": "iana", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raptorfec": { + "source": "iana" + }, + "video/raw": { + "source": "iana" + }, + "video/rtp-enc-aescm128": { + "source": "iana" + }, + "video/rtploopback": { + "source": "iana" + }, + "video/rtx": { + "source": "iana" + }, + "video/scip": { + "source": "iana" + }, + "video/smpte291": { + "source": "iana" + }, + "video/smpte292m": { + "source": "iana" + }, + "video/ulpfec": { + "source": "iana" + }, + "video/vc1": { + "source": "iana" + }, + "video/vc2": { + "source": "iana" + }, + "video/vnd.cctv": { + "source": "iana" + }, + "video/vnd.dece.hd": { + "source": "iana", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "iana", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "iana" + }, + "video/vnd.dece.pd": { + "source": "iana", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "iana", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "iana", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "iana" + }, + "video/vnd.directv.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dvb.file": { + "source": "iana", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "iana", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "iana" + }, + "video/vnd.motorola.video": { + "source": "iana" + }, + "video/vnd.motorola.videop": { + "source": "iana" + }, + "video/vnd.mpegurl": { + "source": "iana", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "iana", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "iana" + }, + "video/vnd.nokia.mp4vr": { + "source": "iana" + }, + "video/vnd.nokia.videovoip": { + "source": "iana" + }, + "video/vnd.objectvideo": { + "source": "iana" + }, + "video/vnd.radgamettools.bink": { + "source": "iana" + }, + "video/vnd.radgamettools.smacker": { + "source": "iana" + }, + "video/vnd.sealed.mpeg1": { + "source": "iana" + }, + "video/vnd.sealed.mpeg4": { + "source": "iana" + }, + "video/vnd.sealed.swf": { + "source": "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "iana" + }, + "video/vnd.uvvu.mp4": { + "source": "iana", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "iana", + "extensions": ["viv"] + }, + "video/vnd.youtube.yt": { + "source": "iana" + }, + "video/vp8": { + "source": "iana" + }, + "video/vp9": { + "source": "iana" + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/node_modules/mime-db/index.js b/node_modules/mime-db/index.js new file mode 100644 index 000000000..ec2be30de --- /dev/null +++ b/node_modules/mime-db/index.js @@ -0,0 +1,12 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/node_modules/mime-db/package.json b/node_modules/mime-db/package.json new file mode 100644 index 000000000..32c14b846 --- /dev/null +++ b/node_modules/mime-db/package.json @@ -0,0 +1,60 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.52.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)", + "Robert Kieffer (http://github.com/broofa)" + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": "jshttp/mime-db", + "devDependencies": { + "bluebird": "3.7.2", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "4.16.3", + "eslint": "7.32.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.1.1", + "eslint-plugin-standard": "4.1.0", + "gnode": "0.1.2", + "media-typer": "1.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0", + "raw-body": "2.5.0", + "stream-to-array": "2.3.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "fetch": "node scripts/fetch-apache && gnode scripts/fetch-iana && node scripts/fetch-nginx", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/mime-types/HISTORY.md b/node_modules/mime-types/HISTORY.md new file mode 100644 index 000000000..c5043b75b --- /dev/null +++ b/node_modules/mime-types/HISTORY.md @@ -0,0 +1,397 @@ +2.1.35 / 2022-03-12 +=================== + + * deps: mime-db@1.52.0 + - Add extensions from IANA for more `image/*` types + - Add extension `.asc` to `application/pgp-keys` + - Add extensions to various XML types + - Add new upstream MIME types + +2.1.34 / 2021-11-08 +=================== + + * deps: mime-db@1.51.0 + - Add new upstream MIME types + +2.1.33 / 2021-10-01 +=================== + + * deps: mime-db@1.50.0 + - Add deprecated iWorks mime types and extensions + - Add new upstream MIME types + +2.1.32 / 2021-07-27 +=================== + + * deps: mime-db@1.49.0 + - Add extension `.trig` to `application/trig` + - Add new upstream MIME types + +2.1.31 / 2021-06-01 +=================== + + * deps: mime-db@1.48.0 + - Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + - Add new upstream MIME types + +2.1.30 / 2021-04-02 +=================== + + * deps: mime-db@1.47.0 + - Add extension `.amr` to `audio/amr` + - Remove ambigious extensions from IANA for `application/*+xml` types + - Update primary extension to `.es` for `application/ecmascript` + +2.1.29 / 2021-02-17 +=================== + + * deps: mime-db@1.46.0 + - Add extension `.amr` to `audio/amr` + - Add extension `.m4s` to `video/iso.segment` + - Add extension `.opus` to `audio/ogg` + - Add new upstream MIME types + +2.1.28 / 2021-01-01 +=================== + + * deps: mime-db@1.45.0 + - Add `application/ubjson` with extension `.ubj` + - Add `image/avif` with extension `.avif` + - Add `image/ktx2` with extension `.ktx2` + - Add extension `.dbf` to `application/vnd.dbf` + - Add extension `.rar` to `application/vnd.rar` + - Add extension `.td` to `application/urc-targetdesc+xml` + - Add new upstream MIME types + - Fix extension of `application/vnd.apple.keynote` to be `.key` + +2.1.27 / 2020-04-23 +=================== + + * deps: mime-db@1.44.0 + - Add charsets from IANA + - Add extension `.cjs` to `application/node` + - Add new upstream MIME types + +2.1.26 / 2020-01-05 +=================== + + * deps: mime-db@1.43.0 + - Add `application/x-keepass2` with extension `.kdbx` + - Add extension `.mxmf` to `audio/mobile-xmf` + - Add extensions from IANA for `application/*+xml` types + - Add new upstream MIME types + +2.1.25 / 2019-11-12 +=================== + + * deps: mime-db@1.42.0 + - Add new upstream MIME types + - Add `application/toml` with extension `.toml` + - Add `image/vnd.ms-dds` with extension `.dds` + +2.1.24 / 2019-04-20 +=================== + + * deps: mime-db@1.40.0 + - Add extensions from IANA for `model/*` types + - Add `text/mdx` with extension `.mdx` + +2.1.23 / 2019-04-17 +=================== + + * deps: mime-db@~1.39.0 + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add new upstream MIME types + +2.1.22 / 2019-02-14 +=================== + + * deps: mime-db@~1.38.0 + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add new upstream MIME types + +2.1.21 / 2018-10-19 +=================== + + * deps: mime-db@~1.37.0 + - Add extensions to HEIC image types + - Add new upstream MIME types + +2.1.20 / 2018-08-26 +=================== + + * deps: mime-db@~1.36.0 + - Add Apple file extensions from IANA + - Add extensions from IANA for `image/*` types + - Add new upstream MIME types + +2.1.19 / 2018-07-17 +=================== + + * deps: mime-db@~1.35.0 + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.owl` to `application/rdf+xml` + - Add new upstream MIME types + - Add UTF-8 as default charset for `text/turtle` + +2.1.18 / 2018-02-16 +=================== + + * deps: mime-db@~1.33.0 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add new upstream MIME types + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +2.1.17 / 2017-09-01 +=================== + + * deps: mime-db@~1.30.0 + - Add `application/vnd.ms-outlook` + - Add `application/x-arj` + - Add extension `.mjs` to `application/javascript` + - Add glTF types and extensions + - Add new upstream MIME types + - Add `text/x-org` + - Add VirtualBox MIME types + - Fix `source` records for `video/*` types that are IANA + - Update `font/opentype` to registered `font/otf` + +2.1.16 / 2017-07-24 +=================== + + * deps: mime-db@~1.29.0 + - Add `application/fido.trusted-apps+json` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add new upstream MIME types + - Update extensions `.md` and `.markdown` to be `text/markdown` + +2.1.15 / 2017-03-23 +=================== + + * deps: mime-db@~1.27.0 + - Add new mime types + - Add `image/apng` + +2.1.14 / 2017-01-14 +=================== + + * deps: mime-db@~1.26.0 + - Add new mime types + +2.1.13 / 2016-11-18 +=================== + + * deps: mime-db@~1.25.0 + - Add new mime types + +2.1.12 / 2016-09-18 +=================== + + * deps: mime-db@~1.24.0 + - Add new mime types + - Add `audio/mp3` + +2.1.11 / 2016-05-01 +=================== + + * deps: mime-db@~1.23.0 + - Add new mime types + +2.1.10 / 2016-02-15 +=================== + + * deps: mime-db@~1.22.0 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +2.1.1 / 2015-06-08 +================== + + * perf: fix deopt during mapping + +2.1.0 / 2015-06-07 +================== + + * Fix incorrectly treating extension-less file name as extension + - i.e. `'path/to/json'` will no longer return `application/json` + * Fix `.charset(type)` to accept parameters + * Fix `.charset(type)` to match case-insensitive + * Improve generation of extension to MIME mapping + * Refactor internals for readability and no argument reassignment + * Prefer `application/*` MIME types from the same source + * Prefer any type over `application/octet-stream` + * deps: mime-db@~1.13.0 + - Add nginx as a source + - Add new mime types + +2.0.14 / 2015-06-06 +=================== + + * deps: mime-db@~1.12.0 + - Add new mime types + +2.0.13 / 2015-05-31 +=================== + + * deps: mime-db@~1.11.0 + - Add new mime types + +2.0.12 / 2015-05-19 +=================== + + * deps: mime-db@~1.10.0 + - Add new mime types + +2.0.11 / 2015-05-05 +=================== + + * deps: mime-db@~1.9.1 + - Add new mime types + +2.0.10 / 2015-03-13 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/node_modules/mime-types/LICENSE b/node_modules/mime-types/LICENSE new file mode 100644 index 000000000..06166077b --- /dev/null +++ b/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +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/node_modules/mime-types/README.md b/node_modules/mime-types/README.md new file mode 100644 index 000000000..48d2fb477 --- /dev/null +++ b/node_modules/mime-types/README.md @@ -0,0 +1,113 @@ +# mime-types + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +The ultimate javascript content-type utility. + +Similar to [the `mime@1.x` module](https://www.npmjs.com/package/mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, + `mime-types` simply returns `false`, so do + `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- No `.define()` functionality +- Bug fixes for `.lookup(path)` + +Otherwise, the API is compatible with `mime` 1.x. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. +When given an extension, `mime.lookup` is used to get the matching +content-type, otherwise the given content-type is used. Then if the +content-type does not already have a `charset` parameter, `mime.charset` +is used to get the default charset and add to the returned content-type. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' +mime.contentType('text/html') // 'text/html; charset=utf-8' +mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-types/master?label=ci +[ci-url]: https://github.com/jshttp/mime-types/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master +[node-version-image]: https://badgen.net/npm/node/mime-types +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-types +[npm-url]: https://npmjs.org/package/mime-types +[npm-version-image]: https://badgen.net/npm/v/mime-types diff --git a/node_modules/mime-types/index.js b/node_modules/mime-types/index.js new file mode 100644 index 000000000..b9f34d599 --- /dev/null +++ b/node_modules/mime-types/index.js @@ -0,0 +1,188 @@ +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var db = require('mime-db') +var extname = require('path').extname + +/** + * Module variables. + * @private + */ + +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] + + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/node_modules/mime-types/package.json b/node_modules/mime-types/package.json new file mode 100644 index 000000000..bbef69645 --- /dev/null +++ b/node_modules/mime-types/package.json @@ -0,0 +1,44 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.35", + "contributors": [ + "Douglas Christopher Wilson ", + "Jeremiah Senkpiel (https://searchbeam.jit.su)", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": "jshttp/mime-types", + "dependencies": { + "mime-db": "1.52.0" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.2", + "nyc": "15.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec test/test.js", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/node-gyp-build/LICENSE b/node_modules/node-gyp-build/LICENSE new file mode 100644 index 000000000..56fce0895 --- /dev/null +++ b/node_modules/node-gyp-build/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Mathias Buus + +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/node_modules/node-gyp-build/README.md b/node_modules/node-gyp-build/README.md new file mode 100644 index 000000000..f712ca686 --- /dev/null +++ b/node_modules/node-gyp-build/README.md @@ -0,0 +1,58 @@ +# node-gyp-build + +> Build tool and bindings loader for [`node-gyp`][node-gyp] that supports prebuilds. + +``` +npm install node-gyp-build +``` + +[![Test](https://github.com/prebuild/node-gyp-build/actions/workflows/test.yml/badge.svg)](https://github.com/prebuild/node-gyp-build/actions/workflows/test.yml) + +Use together with [`prebuildify`][prebuildify] to easily support prebuilds for your native modules. + +## Usage + +> **Note.** Prebuild names have changed in [`prebuildify@3`][prebuildify] and `node-gyp-build@4`. Please see the documentation below. + +`node-gyp-build` works similar to [`node-gyp build`][node-gyp] except that it will check if a build or prebuild is present before rebuilding your project. + +It's main intended use is as an npm install script and bindings loader for native modules that bundle prebuilds using [`prebuildify`][prebuildify]. + +First add `node-gyp-build` as an install script to your native project + +``` js +{ + ... + "scripts": { + "install": "node-gyp-build" + } +} +``` + +Then in your `index.js`, instead of using the [`bindings`](https://www.npmjs.com/package/bindings) module use `node-gyp-build` to load your binding. + +``` js +var binding = require('node-gyp-build')(__dirname) +``` + +If you do these two things and bundle prebuilds with [`prebuildify`][prebuildify] your native module will work for most platforms +without having to compile on install time AND will work in both node and electron without the need to recompile between usage. + +Users can override `node-gyp-build` and force compiling by doing `npm install --build-from-source`. + +Prebuilds will be attempted loaded from `MODULE_PATH/prebuilds/...` and then next `EXEC_PATH/prebuilds/...` (the latter allowing use with `zeit/pkg`) + +## Supported prebuild names + +If so desired you can bundle more specific flavors, for example `musl` builds to support Alpine, or targeting a numbered ARM architecture version. + +These prebuilds can be bundled in addition to generic prebuilds; `node-gyp-build` will try to find the most specific flavor first. Prebuild filenames are composed of _tags_. The runtime tag takes precedence, as does an `abi` tag over `napi`. For more details on tags, please see [`prebuildify`][prebuildify]. + +Values for the `libc` and `armv` tags are auto-detected but can be overridden through the `LIBC` and `ARM_VERSION` environment variables, respectively. + +## License + +MIT + +[prebuildify]: https://github.com/prebuild/prebuildify +[node-gyp]: https://www.npmjs.com/package/node-gyp diff --git a/node_modules/node-gyp-build/SECURITY.md b/node_modules/node-gyp-build/SECURITY.md new file mode 100644 index 000000000..da9c516dd --- /dev/null +++ b/node_modules/node-gyp-build/SECURITY.md @@ -0,0 +1,5 @@ +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff --git a/node_modules/node-gyp-build/bin.js b/node_modules/node-gyp-build/bin.js new file mode 100755 index 000000000..c778e0ab9 --- /dev/null +++ b/node_modules/node-gyp-build/bin.js @@ -0,0 +1,84 @@ +#!/usr/bin/env node + +var proc = require('child_process') +var os = require('os') +var path = require('path') + +if (!buildFromSource()) { + proc.exec('node-gyp-build-test', function (err, stdout, stderr) { + if (err) { + if (verbose()) console.error(stderr) + preinstall() + } + }) +} else { + preinstall() +} + +function build () { + var win32 = os.platform() === 'win32' + var shell = win32 + var args = [win32 ? 'node-gyp.cmd' : 'node-gyp', 'rebuild'] + + try { + var pkg = require('node-gyp/package.json') + args = [ + process.execPath, + path.join(require.resolve('node-gyp/package.json'), '..', typeof pkg.bin === 'string' ? pkg.bin : pkg.bin['node-gyp']), + 'rebuild' + ] + shell = false + } catch (_) {} + + proc.spawn(args[0], args.slice(1), { stdio: 'inherit', shell, windowsHide: true }).on('exit', function (code) { + if (code || !process.argv[3]) process.exit(code) + exec(process.argv[3]).on('exit', function (code) { + process.exit(code) + }) + }) +} + +function preinstall () { + if (!process.argv[2]) return build() + exec(process.argv[2]).on('exit', function (code) { + if (code) process.exit(code) + build() + }) +} + +function exec (cmd) { + if (process.platform !== 'win32') { + var shell = os.platform() === 'android' ? 'sh' : true + return proc.spawn(cmd, [], { + shell, + stdio: 'inherit' + }) + } + + return proc.spawn(cmd, [], { + windowsVerbatimArguments: true, + stdio: 'inherit', + shell: true, + windowsHide: true + }) +} + +function buildFromSource () { + return hasFlag('--build-from-source') || process.env.npm_config_build_from_source === 'true' +} + +function verbose () { + return hasFlag('--verbose') || process.env.npm_config_loglevel === 'verbose' +} + +// TODO (next major): remove in favor of env.npm_config_* which works since npm +// 0.1.8 while npm_config_argv will stop working in npm 7. See npm/rfcs#90 +function hasFlag (flag) { + if (!process.env.npm_config_argv) return false + + try { + return JSON.parse(process.env.npm_config_argv).original.indexOf(flag) !== -1 + } catch (_) { + return false + } +} diff --git a/node_modules/node-gyp-build/build-test.js b/node_modules/node-gyp-build/build-test.js new file mode 100755 index 000000000..b6622a5c2 --- /dev/null +++ b/node_modules/node-gyp-build/build-test.js @@ -0,0 +1,19 @@ +#!/usr/bin/env node + +process.env.NODE_ENV = 'test' + +var path = require('path') +var test = null + +try { + var pkg = require(path.join(process.cwd(), 'package.json')) + if (pkg.name && process.env[pkg.name.toUpperCase().replace(/-/g, '_')]) { + process.exit(0) + } + test = pkg.prebuild.test +} catch (err) { + // do nothing +} + +if (test) require(path.join(process.cwd(), test)) +else require('./')() diff --git a/node_modules/node-gyp-build/index.js b/node_modules/node-gyp-build/index.js new file mode 100644 index 000000000..07eb14ffd --- /dev/null +++ b/node_modules/node-gyp-build/index.js @@ -0,0 +1,6 @@ +const runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line +if (typeof runtimeRequire.addon === 'function') { // if the platform supports native resolving prefer that + module.exports = runtimeRequire.addon.bind(runtimeRequire) +} else { // else use the runtime version here + module.exports = require('./node-gyp-build.js') +} diff --git a/node_modules/node-gyp-build/node-gyp-build.js b/node_modules/node-gyp-build/node-gyp-build.js new file mode 100644 index 000000000..76b96e107 --- /dev/null +++ b/node_modules/node-gyp-build/node-gyp-build.js @@ -0,0 +1,207 @@ +var fs = require('fs') +var path = require('path') +var os = require('os') + +// Workaround to fix webpack's build warnings: 'the request of a dependency is an expression' +var runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line + +var vars = (process.config && process.config.variables) || {} +var prebuildsOnly = !!process.env.PREBUILDS_ONLY +var abi = process.versions.modules // TODO: support old node where this is undef +var runtime = isElectron() ? 'electron' : (isNwjs() ? 'node-webkit' : 'node') + +var arch = process.env.npm_config_arch || os.arch() +var platform = process.env.npm_config_platform || os.platform() +var libc = process.env.LIBC || (isAlpine(platform) ? 'musl' : 'glibc') +var armv = process.env.ARM_VERSION || (arch === 'arm64' ? '8' : vars.arm_version) || '' +var uv = (process.versions.uv || '').split('.')[0] + +module.exports = load + +function load (dir) { + return runtimeRequire(load.resolve(dir)) +} + +load.resolve = load.path = function (dir) { + dir = path.resolve(dir || '.') + + try { + var name = runtimeRequire(path.join(dir, 'package.json')).name.toUpperCase().replace(/-/g, '_') + if (process.env[name + '_PREBUILD']) dir = process.env[name + '_PREBUILD'] + } catch (err) {} + + if (!prebuildsOnly) { + var release = getFirst(path.join(dir, 'build/Release'), matchBuild) + if (release) return release + + var debug = getFirst(path.join(dir, 'build/Debug'), matchBuild) + if (debug) return debug + } + + var prebuild = resolve(dir) + if (prebuild) return prebuild + + var nearby = resolve(path.dirname(process.execPath)) + if (nearby) return nearby + + var target = [ + 'platform=' + platform, + 'arch=' + arch, + 'runtime=' + runtime, + 'abi=' + abi, + 'uv=' + uv, + armv ? 'armv=' + armv : '', + 'libc=' + libc, + 'node=' + process.versions.node, + process.versions.electron ? 'electron=' + process.versions.electron : '', + typeof __webpack_require__ === 'function' ? 'webpack=true' : '' // eslint-disable-line + ].filter(Boolean).join(' ') + + throw new Error('No native build was found for ' + target + '\n loaded from: ' + dir + '\n') + + function resolve (dir) { + // Find matching "prebuilds/-" directory + var tuples = readdirSync(path.join(dir, 'prebuilds')).map(parseTuple) + var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0] + if (!tuple) return + + // Find most specific flavor first + var prebuilds = path.join(dir, 'prebuilds', tuple.name) + var parsed = readdirSync(prebuilds).map(parseTags) + var candidates = parsed.filter(matchTags(runtime, abi)) + var winner = candidates.sort(compareTags(runtime))[0] + if (winner) return path.join(prebuilds, winner.file) + } +} + +function readdirSync (dir) { + try { + return fs.readdirSync(dir) + } catch (err) { + return [] + } +} + +function getFirst (dir, filter) { + var files = readdirSync(dir).filter(filter) + return files[0] && path.join(dir, files[0]) +} + +function matchBuild (name) { + return /\.node$/.test(name) +} + +function parseTuple (name) { + // Example: darwin-x64+arm64 + var arr = name.split('-') + if (arr.length !== 2) return + + var platform = arr[0] + var architectures = arr[1].split('+') + + if (!platform) return + if (!architectures.length) return + if (!architectures.every(Boolean)) return + + return { name, platform, architectures } +} + +function matchTuple (platform, arch) { + return function (tuple) { + if (tuple == null) return false + if (tuple.platform !== platform) return false + return tuple.architectures.includes(arch) + } +} + +function compareTuples (a, b) { + // Prefer single-arch prebuilds over multi-arch + return a.architectures.length - b.architectures.length +} + +function parseTags (file) { + var arr = file.split('.') + var extension = arr.pop() + var tags = { file: file, specificity: 0 } + + if (extension !== 'node') return + + for (var i = 0; i < arr.length; i++) { + var tag = arr[i] + + if (tag === 'node' || tag === 'electron' || tag === 'node-webkit') { + tags.runtime = tag + } else if (tag === 'napi') { + tags.napi = true + } else if (tag.slice(0, 3) === 'abi') { + tags.abi = tag.slice(3) + } else if (tag.slice(0, 2) === 'uv') { + tags.uv = tag.slice(2) + } else if (tag.slice(0, 4) === 'armv') { + tags.armv = tag.slice(4) + } else if (tag === 'glibc' || tag === 'musl') { + tags.libc = tag + } else { + continue + } + + tags.specificity++ + } + + return tags +} + +function matchTags (runtime, abi) { + return function (tags) { + if (tags == null) return false + if (tags.runtime && tags.runtime !== runtime && !runtimeAgnostic(tags)) return false + if (tags.abi && tags.abi !== abi && !tags.napi) return false + if (tags.uv && tags.uv !== uv) return false + if (tags.armv && tags.armv !== armv) return false + if (tags.libc && tags.libc !== libc) return false + + return true + } +} + +function runtimeAgnostic (tags) { + return tags.runtime === 'node' && tags.napi +} + +function compareTags (runtime) { + // Precedence: non-agnostic runtime, abi over napi, then by specificity. + return function (a, b) { + if (a.runtime !== b.runtime) { + return a.runtime === runtime ? -1 : 1 + } else if (a.abi !== b.abi) { + return a.abi ? -1 : 1 + } else if (a.specificity !== b.specificity) { + return a.specificity > b.specificity ? -1 : 1 + } else { + return 0 + } + } +} + +function isNwjs () { + return !!(process.versions && process.versions.nw) +} + +function isElectron () { + if (process.versions && process.versions.electron) return true + if (process.env.ELECTRON_RUN_AS_NODE) return true + return typeof window !== 'undefined' && window.process && window.process.type === 'renderer' +} + +function isAlpine (platform) { + return platform === 'linux' && fs.existsSync('/etc/alpine-release') +} + +// Exposed for unit tests +// TODO: move to lib +load.parseTags = parseTags +load.matchTags = matchTags +load.compareTags = compareTags +load.parseTuple = parseTuple +load.matchTuple = matchTuple +load.compareTuples = compareTuples diff --git a/node_modules/node-gyp-build/optional.js b/node_modules/node-gyp-build/optional.js new file mode 100755 index 000000000..8daa04a6f --- /dev/null +++ b/node_modules/node-gyp-build/optional.js @@ -0,0 +1,7 @@ +#!/usr/bin/env node + +/* +I am only useful as an install script to make node-gyp not compile for purely optional native deps +*/ + +process.exit(0) diff --git a/node_modules/node-gyp-build/package.json b/node_modules/node-gyp-build/package.json new file mode 100644 index 000000000..6f6f28b50 --- /dev/null +++ b/node_modules/node-gyp-build/package.json @@ -0,0 +1,43 @@ +{ + "name": "node-gyp-build", + "version": "4.8.4", + "description": "Build tool and bindings loader for node-gyp that supports prebuilds", + "main": "index.js", + "imports": { + "fs": { + "bare": "builtin:fs", + "default": "fs" + }, + "path": { + "bare": "builtin:path", + "default": "path" + }, + "os": { + "bare": "builtin:os", + "default": "os" + } + }, + "devDependencies": { + "array-shuffle": "^1.0.1", + "standard": "^14.0.0", + "tape": "^5.0.0" + }, + "scripts": { + "test": "standard && node test" + }, + "bin": { + "node-gyp-build": "./bin.js", + "node-gyp-build-optional": "./optional.js", + "node-gyp-build-test": "./build-test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/prebuild/node-gyp-build.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/prebuild/node-gyp-build/issues" + }, + "homepage": "https://github.com/prebuild/node-gyp-build" +} diff --git a/node_modules/pathval/LICENSE b/node_modules/pathval/LICENSE new file mode 100644 index 000000000..90d22da6a --- /dev/null +++ b/node_modules/pathval/LICENSE @@ -0,0 +1,16 @@ +MIT License + +Copyright (c) 2011-2013 Jake Luer jake@alogicalparadox.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. diff --git a/node_modules/pathval/README.md b/node_modules/pathval/README.md new file mode 100644 index 000000000..22a841eb9 --- /dev/null +++ b/node_modules/pathval/README.md @@ -0,0 +1,147 @@ +

+ + ChaiJS + +
+ pathval +

+ +

+ Tool for Object value retrieval given a string path for node and the browser. +

+ +

+ + license:mit + + + tag:? + + + build:? + + + coverage:? + + + npm:? + + + dependencies:? + + + devDependencies:? + +
+ + Selenium Test Status + +
+ + Join the Slack chat + + + Join the Gitter chat + +

+ +## What is pathval? + +Pathval is a module which you can use to retrieve or set an Object's property for a given `String` path. + +## Installation + +### Node.js + +`pathval` is available on [npm](http://npmjs.org). To install it, type: + + $ npm install pathval + +### Browsers + +You can also use it within the browser; install via npm and use the `pathval.js` file found within the download. For example: + +```html + +``` + +## Usage + +The primary export of `pathval` is an object which has the following methods: + +* `hasProperty(object, name)` - Checks whether an `object` has `name`d property or numeric array index. +* `getPathInfo(object, path)` - Returns an object with info indicating the value of the `parent` of that path, the `name ` of the property we're retrieving and its `value`. +* `getPathValue(object, path)` - Retrieves the value of a property at a given `path` inside an `object`'. +* `setPathValue(object, path, value)` - Sets the `value` of a property at a given `path` inside an `object` and returns the object in which the property has been set. + +```js +var pathval = require('pathval'); +``` + +#### .hasProperty(object, name) + +```js +var pathval = require('pathval'); + +var obj = { prop: 'a value' }; +pathval.hasProperty(obj, 'prop'); // true +``` + +#### .getPathInfo(object, path) + +```js +var pathval = require('pathval'); + +var obj = { earth: { country: 'Brazil' } }; +pathval.getPathInfo(obj, 'earth.country'); // { parent: { country: 'Brazil' }, name: 'country', value: 'Brazil', exists: true } +``` + +#### .getPathValue(object, path) + +```js +var pathval = require('pathval'); + +var obj = { earth: { country: 'Brazil' } }; +pathval.getPathValue(obj, 'earth.country'); // 'Brazil' +``` + +#### .setPathValue(object, path, value) + +```js +var pathval = require('pathval'); + +var obj = { earth: { country: 'Brazil' } }; +pathval.setPathValue(obj, 'earth.country', 'USA'); + +obj.earth.country; // 'USA' +``` diff --git a/node_modules/pathval/index.js b/node_modules/pathval/index.js new file mode 100644 index 000000000..4db57fabc --- /dev/null +++ b/node_modules/pathval/index.js @@ -0,0 +1,292 @@ +/* ! + * Chai - pathval utility + * Copyright(c) 2012-2014 Jake Luer + * @see https://github.com/logicalparadox/filtr + * MIT Licensed + */ + +/** + * ### .hasProperty(object, name) + * + * This allows checking whether an object has own + * or inherited from prototype chain named property. + * + * Basically does the same thing as the `in` + * operator but works properly with null/undefined values + * and other primitives. + * + * var obj = { + * arr: ['a', 'b', 'c'] + * , str: 'Hello' + * } + * + * The following would be the results. + * + * hasProperty(obj, 'str'); // true + * hasProperty(obj, 'constructor'); // true + * hasProperty(obj, 'bar'); // false + * + * hasProperty(obj.str, 'length'); // true + * hasProperty(obj.str, 1); // true + * hasProperty(obj.str, 5); // false + * + * hasProperty(obj.arr, 'length'); // true + * hasProperty(obj.arr, 2); // true + * hasProperty(obj.arr, 3); // false + * + * @param {Object} object + * @param {String|Symbol} name + * @returns {Boolean} whether it exists + * @namespace Utils + * @name hasProperty + * @api public + */ + +export function hasProperty(obj, name) { + if (typeof obj === 'undefined' || obj === null) { + return false; + } + + // The `in` operator does not work with primitives. + return name in Object(obj); +} + +/* ! + * ## parsePath(path) + * + * Helper function used to parse string object + * paths. Use in conjunction with `internalGetPathValue`. + * + * var parsed = parsePath('myobject.property.subprop'); + * + * ### Paths: + * + * * Can be infinitely deep and nested. + * * Arrays are also valid using the formal `myobject.document[3].property`. + * * Literal dots and brackets (not delimiter) must be backslash-escaped. + * + * @param {String} path + * @returns {Object} parsed + * @api private + */ + +function parsePath(path) { + const str = path.replace(/([^\\])\[/g, '$1.['); + const parts = str.match(/(\\\.|[^.]+?)+/g); + return parts.map((value) => { + if ( + value === 'constructor' || + value === '__proto__' || + value === 'prototype' + ) { + return {}; + } + const regexp = /^\[(\d+)\]$/; + const mArr = regexp.exec(value); + let parsed = null; + if (mArr) { + parsed = { i: parseFloat(mArr[1]) }; + } else { + parsed = { p: value.replace(/\\([.[\]])/g, '$1') }; + } + + return parsed; + }); +} + +/* ! + * ## internalGetPathValue(obj, parsed[, pathDepth]) + * + * Helper companion function for `.parsePath` that returns + * the value located at the parsed address. + * + * var value = getPathValue(obj, parsed); + * + * @param {Object} object to search against + * @param {Object} parsed definition from `parsePath`. + * @param {Number} depth (nesting level) of the property we want to retrieve + * @returns {Object|Undefined} value + * @api private + */ + +function internalGetPathValue(obj, parsed, pathDepth) { + let temporaryValue = obj; + let res = null; + pathDepth = typeof pathDepth === 'undefined' ? parsed.length : pathDepth; + + for (let i = 0; i < pathDepth; i++) { + const part = parsed[i]; + if (temporaryValue) { + if (typeof part.p === 'undefined') { + temporaryValue = temporaryValue[part.i]; + } else { + temporaryValue = temporaryValue[part.p]; + } + + if (i === pathDepth - 1) { + res = temporaryValue; + } + } + } + + return res; +} + +/* ! + * ## internalSetPathValue(obj, value, parsed) + * + * Companion function for `parsePath` that sets + * the value located at a parsed address. + * + * internalSetPathValue(obj, 'value', parsed); + * + * @param {Object} object to search and define on + * @param {*} value to use upon set + * @param {Object} parsed definition from `parsePath` + * @api private + */ + +function internalSetPathValue(obj, val, parsed) { + let tempObj = obj; + const pathDepth = parsed.length; + let part = null; + // Here we iterate through every part of the path + for (let i = 0; i < pathDepth; i++) { + let propName = null; + let propVal = null; + part = parsed[i]; + + // If it's the last part of the path, we set the 'propName' value with the property name + if (i === pathDepth - 1) { + propName = typeof part.p === 'undefined' ? part.i : part.p; + // Now we set the property with the name held by 'propName' on object with the desired val + tempObj[propName] = val; + } else if (typeof part.p !== 'undefined' && tempObj[part.p]) { + tempObj = tempObj[part.p]; + } else if (typeof part.i !== 'undefined' && tempObj[part.i]) { + tempObj = tempObj[part.i]; + } else { + // If the obj doesn't have the property we create one with that name to define it + const next = parsed[i + 1]; + // Here we set the name of the property which will be defined + propName = typeof part.p === 'undefined' ? part.i : part.p; + // Here we decide if this property will be an array or a new object + propVal = typeof next.p === 'undefined' ? [] : {}; + tempObj[propName] = propVal; + tempObj = tempObj[propName]; + } + } +} + +/** + * ### .getPathInfo(object, path) + * + * This allows the retrieval of property info in an + * object given a string path. + * + * The path info consists of an object with the + * following properties: + * + * * parent - The parent object of the property referenced by `path` + * * name - The name of the final property, a number if it was an array indexer + * * value - The value of the property, if it exists, otherwise `undefined` + * * exists - Whether the property exists or not + * + * @param {Object} object + * @param {String} path + * @returns {Object} info + * @namespace Utils + * @name getPathInfo + * @api public + */ + +export function getPathInfo(obj, path) { + const parsed = parsePath(path); + const last = parsed[parsed.length - 1]; + const info = { + parent: + parsed.length > 1 ? + internalGetPathValue(obj, parsed, parsed.length - 1) : + obj, + name: last.p || last.i, + value: internalGetPathValue(obj, parsed), + }; + info.exists = hasProperty(info.parent, info.name); + + return info; +} + +/** + * ### .getPathValue(object, path) + * + * This allows the retrieval of values in an + * object given a string path. + * + * var obj = { + * prop1: { + * arr: ['a', 'b', 'c'] + * , str: 'Hello' + * } + * , prop2: { + * arr: [ { nested: 'Universe' } ] + * , str: 'Hello again!' + * } + * } + * + * The following would be the results. + * + * getPathValue(obj, 'prop1.str'); // Hello + * getPathValue(obj, 'prop1.att[2]'); // b + * getPathValue(obj, 'prop2.arr[0].nested'); // Universe + * + * @param {Object} object + * @param {String} path + * @returns {Object} value or `undefined` + * @namespace Utils + * @name getPathValue + * @api public + */ + +export function getPathValue(obj, path) { + const info = getPathInfo(obj, path); + return info.value; +} + +/** + * ### .setPathValue(object, path, value) + * + * Define the value in an object at a given string path. + * + * ```js + * var obj = { + * prop1: { + * arr: ['a', 'b', 'c'] + * , str: 'Hello' + * } + * , prop2: { + * arr: [ { nested: 'Universe' } ] + * , str: 'Hello again!' + * } + * }; + * ``` + * + * The following would be acceptable. + * + * ```js + * var properties = require('tea-properties'); + * properties.set(obj, 'prop1.str', 'Hello Universe!'); + * properties.set(obj, 'prop1.arr[2]', 'B'); + * properties.set(obj, 'prop2.arr[0].nested.value', { hello: 'universe' }); + * ``` + * + * @param {Object} object + * @param {String} path + * @param {Mixed} value + * @api private + */ + +export function setPathValue(obj, path, val) { + const parsed = parsePath(path); + internalSetPathValue(obj, val, parsed); + return obj; +} diff --git a/node_modules/pathval/package.json b/node_modules/pathval/package.json new file mode 100644 index 000000000..f47552a97 --- /dev/null +++ b/node_modules/pathval/package.json @@ -0,0 +1,73 @@ +{ + "name": "pathval", + "description": "Object value retrieval given a string path", + "homepage": "https://github.com/chaijs/pathval", + "version": "2.0.0", + "keywords": [ + "pathval", + "value retrieval", + "chai util" + ], + "license": "MIT", + "author": "Veselin Todorov ", + "files": [ + "index.js", + "pathval.js" + ], + "main": "./index.js", + "type": "module", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/chaijs/pathval.git" + }, + "scripts": { + "build": "browserify --standalone pathval -o pathval.js", + "lint": "eslint --ignore-path .gitignore .", + "lint:fix": "npm run lint -- --fix", + "prepublish": "npm run build", + "semantic-release": "semantic-release pre && npm publish && semantic-release post", + "pretest": "npm run lint", + "test": "npm run test:node && npm run test:browser", + "test:browser": "web-test-runner test/index.js --node-resolve", + "test:node": "mocha" + }, + "config": { + "ghooks": { + "commit-msg": "validate-commit-msg" + } + }, + "eslintConfig": { + "extends": [ + "strict/es6" + ], + "parserOptions": { + "sourceType": "module" + }, + "env": { + "es6": true + }, + "globals": { + "HTMLElement": false + }, + "rules": { + "complexity": 0, + "max-statements": 0 + } + }, + "devDependencies": { + "@web/test-runner": "^0.17.0", + "browserify": "^17.0.0", + "browserify-istanbul": "^3.0.1", + "eslint": "^7.13.0", + "eslint-config-strict": "^14.0.1", + "eslint-plugin-filenames": "^1.3.2", + "ghooks": "^2.0.4", + "mocha": "^8.2.1", + "semantic-release": "^17.2.2", + "simple-assert": "^2.0.0", + "validate-commit-msg": "^2.14.0" + }, + "engines": { + "node": ">= 14.16" + } +} diff --git a/node_modules/pathval/pathval.js b/node_modules/pathval/pathval.js new file mode 100644 index 000000000..0070ed458 --- /dev/null +++ b/node_modules/pathval/pathval.js @@ -0,0 +1 @@ +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i + +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/node_modules/proxy-from-env/README.md b/node_modules/proxy-from-env/README.md new file mode 100644 index 000000000..e82520c16 --- /dev/null +++ b/node_modules/proxy-from-env/README.md @@ -0,0 +1,131 @@ +# proxy-from-env + +[![Build Status](https://travis-ci.org/Rob--W/proxy-from-env.svg?branch=master)](https://travis-ci.org/Rob--W/proxy-from-env) +[![Coverage Status](https://coveralls.io/repos/github/Rob--W/proxy-from-env/badge.svg?branch=master)](https://coveralls.io/github/Rob--W/proxy-from-env?branch=master) + +`proxy-from-env` is a Node.js package that exports a function (`getProxyForUrl`) +that takes an input URL (a string or +[`url.parse`](https://nodejs.org/docs/latest/api/url.html#url_url_parsing)'s +return value) and returns the desired proxy URL (also a string) based on +standard proxy environment variables. If no proxy is set, an empty string is +returned. + +It is your responsibility to actually proxy the request using the given URL. + +Installation: + +```sh +npm install proxy-from-env +``` + +## Example +This example shows how the data for a URL can be fetched via the +[`http` module](https://nodejs.org/api/http.html), in a proxy-aware way. + +```javascript +var http = require('http'); +var parseUrl = require('url').parse; +var getProxyForUrl = require('proxy-from-env').getProxyForUrl; + +var some_url = 'http://example.com/something'; + +// // Example, if there is a proxy server at 10.0.0.1:1234, then setting the +// // http_proxy environment variable causes the request to go through a proxy. +// process.env.http_proxy = 'http://10.0.0.1:1234'; +// +// // But if the host to be proxied is listed in NO_PROXY, then the request is +// // not proxied (but a direct request is made). +// process.env.no_proxy = 'example.com'; + +var proxy_url = getProxyForUrl(some_url); // <-- Our magic. +if (proxy_url) { + // Should be proxied through proxy_url. + var parsed_some_url = parseUrl(some_url); + var parsed_proxy_url = parseUrl(proxy_url); + // A HTTP proxy is quite simple. It is similar to a normal request, except the + // path is an absolute URL, and the proxied URL's host is put in the header + // instead of the server's actual host. + httpOptions = { + protocol: parsed_proxy_url.protocol, + hostname: parsed_proxy_url.hostname, + port: parsed_proxy_url.port, + path: parsed_some_url.href, + headers: { + Host: parsed_some_url.host, // = host name + optional port. + }, + }; +} else { + // Direct request. + httpOptions = some_url; +} +http.get(httpOptions, function(res) { + var responses = []; + res.on('data', function(chunk) { responses.push(chunk); }); + res.on('end', function() { console.log(responses.join('')); }); +}); + +``` + +## Environment variables +The environment variables can be specified in lowercase or uppercase, with the +lowercase name having precedence over the uppercase variant. A variable that is +not set has the same meaning as a variable that is set but has no value. + +### NO\_PROXY + +`NO_PROXY` is a list of host names (optionally with a port). If the input URL +matches any of the entries in `NO_PROXY`, then the input URL should be fetched +by a direct request (i.e. without a proxy). + +Matching follows the following rules: + +- `NO_PROXY=*` disables all proxies. +- Space and commas may be used to separate the entries in the `NO_PROXY` list. +- If `NO_PROXY` does not contain any entries, then proxies are never disabled. +- If a port is added after the host name, then the ports must match. If the URL + does not have an explicit port name, the protocol's default port is used. +- Generally, the proxy is only disabled if the host name is an exact match for + an entry in the `NO_PROXY` list. The only exceptions are entries that start + with a dot or with a wildcard; then the proxy is disabled if the host name + ends with the entry. + +See `test.js` for examples of what should match and what does not. + +### \*\_PROXY + +The environment variable used for the proxy depends on the protocol of the URL. +For example, `https://example.com` uses the "https" protocol, and therefore the +proxy to be used is `HTTPS_PROXY` (_NOT_ `HTTP_PROXY`, which is _only_ used for +http:-URLs). + +The library is not limited to http(s), other schemes such as +`FTP_PROXY` (ftp:), +`WSS_PROXY` (wss:), +`WS_PROXY` (ws:) +are also supported. + +If present, `ALL_PROXY` is used as fallback if there is no other match. + + +## External resources +The exact way of parsing the environment variables is not codified in any +standard. This library is designed to be compatible with formats as expected by +existing software. +The following resources were used to determine the desired behavior: + +- cURL: + https://curl.haxx.se/docs/manpage.html#ENVIRONMENT + https://github.com/curl/curl/blob/4af40b3646d3b09f68e419f7ca866ff395d1f897/lib/url.c#L4446-L4514 + https://github.com/curl/curl/blob/4af40b3646d3b09f68e419f7ca866ff395d1f897/lib/url.c#L4608-L4638 + +- wget: + https://www.gnu.org/software/wget/manual/wget.html#Proxies + http://git.savannah.gnu.org/cgit/wget.git/tree/src/init.c?id=636a5f9a1c508aa39e35a3a8e9e54520a284d93d#n383 + http://git.savannah.gnu.org/cgit/wget.git/tree/src/retr.c?id=93c1517c4071c4288ba5a4b038e7634e4c6b5482#n1278 + +- W3: + https://www.w3.org/Daemon/User/Proxies/ProxyClients.html + +- Python's urllib: + https://github.com/python/cpython/blob/936135bb97fe04223aa30ca6e98eac8f3ed6b349/Lib/urllib/request.py#L755-L782 + https://github.com/python/cpython/blob/936135bb97fe04223aa30ca6e98eac8f3ed6b349/Lib/urllib/request.py#L2444-L2479 diff --git a/node_modules/proxy-from-env/index.js b/node_modules/proxy-from-env/index.js new file mode 100644 index 000000000..df75004ae --- /dev/null +++ b/node_modules/proxy-from-env/index.js @@ -0,0 +1,108 @@ +'use strict'; + +var parseUrl = require('url').parse; + +var DEFAULT_PORTS = { + ftp: 21, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443, +}; + +var stringEndsWith = String.prototype.endsWith || function(s) { + return s.length <= this.length && + this.indexOf(s, this.length - s.length) !== -1; +}; + +/** + * @param {string|object} url - The URL, or the result from url.parse. + * @return {string} The URL of the proxy that should handle the request to the + * given URL. If no proxy is set, this will be an empty string. + */ +function getProxyForUrl(url) { + var parsedUrl = typeof url === 'string' ? parseUrl(url) : url || {}; + var proto = parsedUrl.protocol; + var hostname = parsedUrl.host; + var port = parsedUrl.port; + if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') { + return ''; // Don't proxy URLs without a valid scheme or host. + } + + proto = proto.split(':', 1)[0]; + // Stripping ports in this way instead of using parsedUrl.hostname to make + // sure that the brackets around IPv6 addresses are kept. + hostname = hostname.replace(/:\d*$/, ''); + port = parseInt(port) || DEFAULT_PORTS[proto] || 0; + if (!shouldProxy(hostname, port)) { + return ''; // Don't proxy URLs that match NO_PROXY. + } + + var proxy = + getEnv('npm_config_' + proto + '_proxy') || + getEnv(proto + '_proxy') || + getEnv('npm_config_proxy') || + getEnv('all_proxy'); + if (proxy && proxy.indexOf('://') === -1) { + // Missing scheme in proxy, default to the requested URL's scheme. + proxy = proto + '://' + proxy; + } + return proxy; +} + +/** + * Determines whether a given URL should be proxied. + * + * @param {string} hostname - The host name of the URL. + * @param {number} port - The effective port of the URL. + * @returns {boolean} Whether the given URL should be proxied. + * @private + */ +function shouldProxy(hostname, port) { + var NO_PROXY = + (getEnv('npm_config_no_proxy') || getEnv('no_proxy')).toLowerCase(); + if (!NO_PROXY) { + return true; // Always proxy if NO_PROXY is not set. + } + if (NO_PROXY === '*') { + return false; // Never proxy if wildcard is set. + } + + return NO_PROXY.split(/[,\s]/).every(function(proxy) { + if (!proxy) { + return true; // Skip zero-length hosts. + } + var parsedProxy = proxy.match(/^(.+):(\d+)$/); + var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; + var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; + if (parsedProxyPort && parsedProxyPort !== port) { + return true; // Skip if ports don't match. + } + + if (!/^[.*]/.test(parsedProxyHostname)) { + // No wildcards, so stop proxying if there is an exact match. + return hostname !== parsedProxyHostname; + } + + if (parsedProxyHostname.charAt(0) === '*') { + // Remove leading wildcard. + parsedProxyHostname = parsedProxyHostname.slice(1); + } + // Stop proxying if the hostname ends with the no_proxy host. + return !stringEndsWith.call(hostname, parsedProxyHostname); + }); +} + +/** + * Get the value for an environment variable. + * + * @param {string} key - The name of the environment variable. + * @return {string} The value of the environment variable. + * @private + */ +function getEnv(key) { + return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || ''; +} + +exports.getProxyForUrl = getProxyForUrl; diff --git a/node_modules/proxy-from-env/package.json b/node_modules/proxy-from-env/package.json new file mode 100644 index 000000000..be2b845b2 --- /dev/null +++ b/node_modules/proxy-from-env/package.json @@ -0,0 +1,34 @@ +{ + "name": "proxy-from-env", + "version": "1.1.0", + "description": "Offers getProxyForUrl to get the proxy URL for a URL, respecting the *_PROXY (e.g. HTTP_PROXY) and NO_PROXY environment variables.", + "main": "index.js", + "scripts": { + "lint": "eslint *.js", + "test": "mocha ./test.js --reporter spec", + "test-coverage": "istanbul cover ./node_modules/.bin/_mocha -- --reporter spec" + }, + "repository": { + "type": "git", + "url": "https://github.com/Rob--W/proxy-from-env.git" + }, + "keywords": [ + "proxy", + "http_proxy", + "https_proxy", + "no_proxy", + "environment" + ], + "author": "Rob Wu (https://robwu.nl/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/Rob--W/proxy-from-env/issues" + }, + "homepage": "https://github.com/Rob--W/proxy-from-env#readme", + "devDependencies": { + "coveralls": "^3.0.9", + "eslint": "^6.8.0", + "istanbul": "^0.4.5", + "mocha": "^7.1.0" + } +} diff --git a/node_modules/proxy-from-env/test.js b/node_modules/proxy-from-env/test.js new file mode 100644 index 000000000..abf65423d --- /dev/null +++ b/node_modules/proxy-from-env/test.js @@ -0,0 +1,483 @@ +/* eslint max-statements:0 */ +'use strict'; + +var assert = require('assert'); +var parseUrl = require('url').parse; + +var getProxyForUrl = require('./').getProxyForUrl; + +// Runs the callback with process.env temporarily set to env. +function runWithEnv(env, callback) { + var originalEnv = process.env; + process.env = env; + try { + callback(); + } finally { + process.env = originalEnv; + } +} + +// Defines a test case that checks whether getProxyForUrl(input) === expected. +function testProxyUrl(env, expected, input) { + assert(typeof env === 'object' && env !== null); + // Copy object to make sure that the in param does not get modified between + // the call of this function and the use of it below. + env = JSON.parse(JSON.stringify(env)); + + var title = 'getProxyForUrl(' + JSON.stringify(input) + ')' + + ' === ' + JSON.stringify(expected); + + // Save call stack for later use. + var stack = {}; + Error.captureStackTrace(stack, testProxyUrl); + // Only use the last stack frame because that shows where this function is + // called, and that is sufficient for our purpose. No need to flood the logs + // with an uninteresting stack trace. + stack = stack.stack.split('\n', 2)[1]; + + it(title, function() { + var actual; + runWithEnv(env, function() { + actual = getProxyForUrl(input); + }); + if (expected === actual) { + return; // Good! + } + try { + assert.strictEqual(expected, actual); // Create a formatted error message. + // Should not happen because previously we determined expected !== actual. + throw new Error('assert.strictEqual passed. This is impossible!'); + } catch (e) { + // Use the original stack trace, so we can see a helpful line number. + e.stack = e.message + stack; + throw e; + } + }); +} + +describe('getProxyForUrl', function() { + describe('No proxy variables', function() { + var env = {}; + testProxyUrl(env, '', 'http://example.com'); + testProxyUrl(env, '', 'https://example.com'); + testProxyUrl(env, '', 'ftp://example.com'); + }); + + describe('Invalid URLs', function() { + var env = {}; + env.ALL_PROXY = 'http://unexpected.proxy'; + testProxyUrl(env, '', 'bogus'); + testProxyUrl(env, '', '//example.com'); + testProxyUrl(env, '', '://example.com'); + testProxyUrl(env, '', '://'); + testProxyUrl(env, '', '/path'); + testProxyUrl(env, '', ''); + testProxyUrl(env, '', 'http:'); + testProxyUrl(env, '', 'http:/'); + testProxyUrl(env, '', 'http://'); + testProxyUrl(env, '', 'prototype://'); + testProxyUrl(env, '', 'hasOwnProperty://'); + testProxyUrl(env, '', '__proto__://'); + testProxyUrl(env, '', undefined); + testProxyUrl(env, '', null); + testProxyUrl(env, '', {}); + testProxyUrl(env, '', {host: 'x', protocol: 1}); + testProxyUrl(env, '', {host: 1, protocol: 'x'}); + }); + + describe('http_proxy and HTTP_PROXY', function() { + var env = {}; + env.HTTP_PROXY = 'http://http-proxy'; + + testProxyUrl(env, '', 'https://example'); + testProxyUrl(env, 'http://http-proxy', 'http://example'); + testProxyUrl(env, 'http://http-proxy', parseUrl('http://example')); + + // eslint-disable-next-line camelcase + env.http_proxy = 'http://priority'; + testProxyUrl(env, 'http://priority', 'http://example'); + }); + + describe('http_proxy with non-sensical value', function() { + var env = {}; + // Crazy values should be passed as-is. It is the responsibility of the + // one who launches the application that the value makes sense. + // TODO: Should we be stricter and perform validation? + env.HTTP_PROXY = 'Crazy \n!() { ::// }'; + testProxyUrl(env, 'Crazy \n!() { ::// }', 'http://wow'); + + // The implementation assumes that the HTTP_PROXY environment variable is + // somewhat reasonable, and if the scheme is missing, it is added. + // Garbage in, garbage out some would say... + env.HTTP_PROXY = 'crazy without colon slash slash'; + testProxyUrl(env, 'http://crazy without colon slash slash', 'http://wow'); + }); + + describe('https_proxy and HTTPS_PROXY', function() { + var env = {}; + // Assert that there is no fall back to http_proxy + env.HTTP_PROXY = 'http://unexpected.proxy'; + testProxyUrl(env, '', 'https://example'); + + env.HTTPS_PROXY = 'http://https-proxy'; + testProxyUrl(env, 'http://https-proxy', 'https://example'); + + // eslint-disable-next-line camelcase + env.https_proxy = 'http://priority'; + testProxyUrl(env, 'http://priority', 'https://example'); + }); + + describe('ftp_proxy', function() { + var env = {}; + // Something else than http_proxy / https, as a sanity check. + env.FTP_PROXY = 'http://ftp-proxy'; + + testProxyUrl(env, 'http://ftp-proxy', 'ftp://example'); + testProxyUrl(env, '', 'ftps://example'); + }); + + describe('all_proxy', function() { + var env = {}; + env.ALL_PROXY = 'http://catch-all'; + testProxyUrl(env, 'http://catch-all', 'https://example'); + + // eslint-disable-next-line camelcase + env.all_proxy = 'http://priority'; + testProxyUrl(env, 'http://priority', 'https://example'); + }); + + describe('all_proxy without scheme', function() { + var env = {}; + env.ALL_PROXY = 'noscheme'; + testProxyUrl(env, 'http://noscheme', 'http://example'); + testProxyUrl(env, 'https://noscheme', 'https://example'); + + // The module does not impose restrictions on the scheme. + testProxyUrl(env, 'bogus-scheme://noscheme', 'bogus-scheme://example'); + + // But the URL should still be valid. + testProxyUrl(env, '', 'bogus'); + }); + + describe('no_proxy empty', function() { + var env = {}; + env.HTTPS_PROXY = 'http://proxy'; + + // NO_PROXY set but empty. + env.NO_PROXY = ''; + testProxyUrl(env, 'http://proxy', 'https://example'); + + // No entries in NO_PROXY (comma). + env.NO_PROXY = ','; + testProxyUrl(env, 'http://proxy', 'https://example'); + + // No entries in NO_PROXY (whitespace). + env.NO_PROXY = ' '; + testProxyUrl(env, 'http://proxy', 'https://example'); + + // No entries in NO_PROXY (multiple whitespace / commas). + env.NO_PROXY = ',\t,,,\n, ,\r'; + testProxyUrl(env, 'http://proxy', 'https://example'); + }); + + describe('no_proxy=example (single host)', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = 'example'; + testProxyUrl(env, '', 'http://example'); + testProxyUrl(env, '', 'http://example:80'); + testProxyUrl(env, '', 'http://example:0'); + testProxyUrl(env, '', 'http://example:1337'); + testProxyUrl(env, 'http://proxy', 'http://sub.example'); + testProxyUrl(env, 'http://proxy', 'http://prefexample'); + testProxyUrl(env, 'http://proxy', 'http://example.no'); + testProxyUrl(env, 'http://proxy', 'http://a.b.example'); + testProxyUrl(env, 'http://proxy', 'http://host/example'); + }); + + describe('no_proxy=sub.example (subdomain)', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = 'sub.example'; + testProxyUrl(env, 'http://proxy', 'http://example'); + testProxyUrl(env, 'http://proxy', 'http://example:80'); + testProxyUrl(env, 'http://proxy', 'http://example:0'); + testProxyUrl(env, 'http://proxy', 'http://example:1337'); + testProxyUrl(env, '', 'http://sub.example'); + testProxyUrl(env, 'http://proxy', 'http://no.sub.example'); + testProxyUrl(env, 'http://proxy', 'http://sub-example'); + testProxyUrl(env, 'http://proxy', 'http://example.sub'); + }); + + describe('no_proxy=example:80 (host + port)', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = 'example:80'; + testProxyUrl(env, '', 'http://example'); + testProxyUrl(env, '', 'http://example:80'); + testProxyUrl(env, '', 'http://example:0'); + testProxyUrl(env, 'http://proxy', 'http://example:1337'); + testProxyUrl(env, 'http://proxy', 'http://sub.example'); + testProxyUrl(env, 'http://proxy', 'http://prefexample'); + testProxyUrl(env, 'http://proxy', 'http://example.no'); + testProxyUrl(env, 'http://proxy', 'http://a.b.example'); + }); + + describe('no_proxy=.example (host suffix)', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = '.example'; + testProxyUrl(env, 'http://proxy', 'http://example'); + testProxyUrl(env, 'http://proxy', 'http://example:80'); + testProxyUrl(env, 'http://proxy', 'http://example:1337'); + testProxyUrl(env, '', 'http://sub.example'); + testProxyUrl(env, '', 'http://sub.example:80'); + testProxyUrl(env, '', 'http://sub.example:1337'); + testProxyUrl(env, 'http://proxy', 'http://prefexample'); + testProxyUrl(env, 'http://proxy', 'http://example.no'); + testProxyUrl(env, '', 'http://a.b.example'); + }); + + describe('no_proxy=*', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + env.NO_PROXY = '*'; + testProxyUrl(env, '', 'http://example.com'); + }); + + describe('no_proxy=*.example (host suffix with *.)', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = '*.example'; + testProxyUrl(env, 'http://proxy', 'http://example'); + testProxyUrl(env, 'http://proxy', 'http://example:80'); + testProxyUrl(env, 'http://proxy', 'http://example:1337'); + testProxyUrl(env, '', 'http://sub.example'); + testProxyUrl(env, '', 'http://sub.example:80'); + testProxyUrl(env, '', 'http://sub.example:1337'); + testProxyUrl(env, 'http://proxy', 'http://prefexample'); + testProxyUrl(env, 'http://proxy', 'http://example.no'); + testProxyUrl(env, '', 'http://a.b.example'); + }); + + describe('no_proxy=*example (substring suffix)', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = '*example'; + testProxyUrl(env, '', 'http://example'); + testProxyUrl(env, '', 'http://example:80'); + testProxyUrl(env, '', 'http://example:1337'); + testProxyUrl(env, '', 'http://sub.example'); + testProxyUrl(env, '', 'http://sub.example:80'); + testProxyUrl(env, '', 'http://sub.example:1337'); + testProxyUrl(env, '', 'http://prefexample'); + testProxyUrl(env, '', 'http://a.b.example'); + testProxyUrl(env, 'http://proxy', 'http://example.no'); + testProxyUrl(env, 'http://proxy', 'http://host/example'); + }); + + describe('no_proxy=.*example (arbitrary wildcards are NOT supported)', + function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = '.*example'; + testProxyUrl(env, 'http://proxy', 'http://example'); + testProxyUrl(env, 'http://proxy', 'http://sub.example'); + testProxyUrl(env, 'http://proxy', 'http://sub.example'); + testProxyUrl(env, 'http://proxy', 'http://prefexample'); + testProxyUrl(env, 'http://proxy', 'http://x.prefexample'); + testProxyUrl(env, 'http://proxy', 'http://a.b.example'); + }); + + describe('no_proxy=[::1],[::2]:80,10.0.0.1,10.0.0.2:80 (IP addresses)', + function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = '[::1],[::2]:80,10.0.0.1,10.0.0.2:80'; + testProxyUrl(env, '', 'http://[::1]/'); + testProxyUrl(env, '', 'http://[::1]:80/'); + testProxyUrl(env, '', 'http://[::1]:1337/'); + + testProxyUrl(env, '', 'http://[::2]/'); + testProxyUrl(env, '', 'http://[::2]:80/'); + testProxyUrl(env, 'http://proxy', 'http://[::2]:1337/'); + + testProxyUrl(env, '', 'http://10.0.0.1/'); + testProxyUrl(env, '', 'http://10.0.0.1:80/'); + testProxyUrl(env, '', 'http://10.0.0.1:1337/'); + + testProxyUrl(env, '', 'http://10.0.0.2/'); + testProxyUrl(env, '', 'http://10.0.0.2:80/'); + testProxyUrl(env, 'http://proxy', 'http://10.0.0.2:1337/'); + }); + + describe('no_proxy=127.0.0.1/32 (CIDR is NOT supported)', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = '127.0.0.1/32'; + testProxyUrl(env, 'http://proxy', 'http://127.0.0.1'); + testProxyUrl(env, 'http://proxy', 'http://127.0.0.1/32'); + }); + + describe('no_proxy=127.0.0.1 does NOT match localhost', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + + env.NO_PROXY = '127.0.0.1'; + testProxyUrl(env, '', 'http://127.0.0.1'); + // We're not performing DNS queries, so this shouldn't match. + testProxyUrl(env, 'http://proxy', 'http://localhost'); + }); + + describe('no_proxy with protocols that have a default port', function() { + var env = {}; + env.WS_PROXY = 'http://ws'; + env.WSS_PROXY = 'http://wss'; + env.HTTP_PROXY = 'http://http'; + env.HTTPS_PROXY = 'http://https'; + env.GOPHER_PROXY = 'http://gopher'; + env.FTP_PROXY = 'http://ftp'; + env.ALL_PROXY = 'http://all'; + + env.NO_PROXY = 'xxx:21,xxx:70,xxx:80,xxx:443'; + + testProxyUrl(env, '', 'http://xxx'); + testProxyUrl(env, '', 'http://xxx:80'); + testProxyUrl(env, 'http://http', 'http://xxx:1337'); + + testProxyUrl(env, '', 'ws://xxx'); + testProxyUrl(env, '', 'ws://xxx:80'); + testProxyUrl(env, 'http://ws', 'ws://xxx:1337'); + + testProxyUrl(env, '', 'https://xxx'); + testProxyUrl(env, '', 'https://xxx:443'); + testProxyUrl(env, 'http://https', 'https://xxx:1337'); + + testProxyUrl(env, '', 'wss://xxx'); + testProxyUrl(env, '', 'wss://xxx:443'); + testProxyUrl(env, 'http://wss', 'wss://xxx:1337'); + + testProxyUrl(env, '', 'gopher://xxx'); + testProxyUrl(env, '', 'gopher://xxx:70'); + testProxyUrl(env, 'http://gopher', 'gopher://xxx:1337'); + + testProxyUrl(env, '', 'ftp://xxx'); + testProxyUrl(env, '', 'ftp://xxx:21'); + testProxyUrl(env, 'http://ftp', 'ftp://xxx:1337'); + }); + + describe('no_proxy should not be case-sensitive', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + env.NO_PROXY = 'XXX,YYY,ZzZ'; + + testProxyUrl(env, '', 'http://xxx'); + testProxyUrl(env, '', 'http://XXX'); + testProxyUrl(env, '', 'http://yyy'); + testProxyUrl(env, '', 'http://YYY'); + testProxyUrl(env, '', 'http://ZzZ'); + testProxyUrl(env, '', 'http://zZz'); + }); + + describe('NPM proxy configuration', function() { + describe('npm_config_http_proxy should work', function() { + var env = {}; + // eslint-disable-next-line camelcase + env.npm_config_http_proxy = 'http://http-proxy'; + + testProxyUrl(env, '', 'https://example'); + testProxyUrl(env, 'http://http-proxy', 'http://example'); + + // eslint-disable-next-line camelcase + env.npm_config_http_proxy = 'http://priority'; + testProxyUrl(env, 'http://priority', 'http://example'); + }); + // eslint-disable-next-line max-len + describe('npm_config_http_proxy should take precedence over HTTP_PROXY and npm_config_proxy', function() { + var env = {}; + // eslint-disable-next-line camelcase + env.npm_config_http_proxy = 'http://http-proxy'; + // eslint-disable-next-line camelcase + env.npm_config_proxy = 'http://unexpected-proxy'; + env.HTTP_PROXY = 'http://unexpected-proxy'; + + testProxyUrl(env, 'http://http-proxy', 'http://example'); + }); + describe('npm_config_https_proxy should work', function() { + var env = {}; + // eslint-disable-next-line camelcase + env.npm_config_http_proxy = 'http://unexpected.proxy'; + testProxyUrl(env, '', 'https://example'); + + // eslint-disable-next-line camelcase + env.npm_config_https_proxy = 'http://https-proxy'; + testProxyUrl(env, 'http://https-proxy', 'https://example'); + + // eslint-disable-next-line camelcase + env.npm_config_https_proxy = 'http://priority'; + testProxyUrl(env, 'http://priority', 'https://example'); + }); + // eslint-disable-next-line max-len + describe('npm_config_https_proxy should take precedence over HTTPS_PROXY and npm_config_proxy', function() { + var env = {}; + // eslint-disable-next-line camelcase + env.npm_config_https_proxy = 'http://https-proxy'; + // eslint-disable-next-line camelcase + env.npm_config_proxy = 'http://unexpected-proxy'; + env.HTTPS_PROXY = 'http://unexpected-proxy'; + + testProxyUrl(env, 'http://https-proxy', 'https://example'); + }); + describe('npm_config_proxy should work', function() { + var env = {}; + // eslint-disable-next-line camelcase + env.npm_config_proxy = 'http://http-proxy'; + testProxyUrl(env, 'http://http-proxy', 'http://example'); + testProxyUrl(env, 'http://http-proxy', 'https://example'); + + // eslint-disable-next-line camelcase + env.npm_config_proxy = 'http://priority'; + testProxyUrl(env, 'http://priority', 'http://example'); + testProxyUrl(env, 'http://priority', 'https://example'); + }); + // eslint-disable-next-line max-len + describe('HTTP_PROXY and HTTPS_PROXY should take precedence over npm_config_proxy', function() { + var env = {}; + env.HTTP_PROXY = 'http://http-proxy'; + env.HTTPS_PROXY = 'http://https-proxy'; + // eslint-disable-next-line camelcase + env.npm_config_proxy = 'http://unexpected-proxy'; + testProxyUrl(env, 'http://http-proxy', 'http://example'); + testProxyUrl(env, 'http://https-proxy', 'https://example'); + }); + describe('npm_config_no_proxy should work', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + // eslint-disable-next-line camelcase + env.npm_config_no_proxy = 'example'; + + testProxyUrl(env, '', 'http://example'); + testProxyUrl(env, 'http://proxy', 'http://otherwebsite'); + }); + // eslint-disable-next-line max-len + describe('npm_config_no_proxy should take precedence over NO_PROXY', function() { + var env = {}; + env.HTTP_PROXY = 'http://proxy'; + env.NO_PROXY = 'otherwebsite'; + // eslint-disable-next-line camelcase + env.npm_config_no_proxy = 'example'; + + testProxyUrl(env, '', 'http://example'); + testProxyUrl(env, 'http://proxy', 'http://otherwebsite'); + }); + }); +}); diff --git a/node_modules/randombytes/.travis.yml b/node_modules/randombytes/.travis.yml new file mode 100644 index 000000000..69fdf7130 --- /dev/null +++ b/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/node_modules/randombytes/.zuul.yml b/node_modules/randombytes/.zuul.yml new file mode 100644 index 000000000..96d9cfbd3 --- /dev/null +++ b/node_modules/randombytes/.zuul.yml @@ -0,0 +1 @@ +ui: tape diff --git a/node_modules/randombytes/LICENSE b/node_modules/randombytes/LICENSE new file mode 100644 index 000000000..fea9d48a4 --- /dev/null +++ b/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/node_modules/randombytes/README.md b/node_modules/randombytes/README.md new file mode 100644 index 000000000..3bacba4d1 --- /dev/null +++ b/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/node_modules/randombytes/browser.js b/node_modules/randombytes/browser.js new file mode 100644 index 000000000..0fb0b7153 --- /dev/null +++ b/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/node_modules/randombytes/index.js b/node_modules/randombytes/index.js new file mode 100644 index 000000000..a2d9e3911 --- /dev/null +++ b/node_modules/randombytes/index.js @@ -0,0 +1 @@ +module.exports = require('crypto').randomBytes diff --git a/node_modules/randombytes/package.json b/node_modules/randombytes/package.json new file mode 100644 index 000000000..36236526b --- /dev/null +++ b/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/node_modules/randombytes/test.js b/node_modules/randombytes/test.js new file mode 100644 index 000000000..f26697697 --- /dev/null +++ b/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/node_modules/safe-buffer/LICENSE b/node_modules/safe-buffer/LICENSE new file mode 100644 index 000000000..0c068ceec --- /dev/null +++ b/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/node_modules/safe-buffer/README.md b/node_modules/safe-buffer/README.md new file mode 100644 index 000000000..e9a81afd0 --- /dev/null +++ b/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/node_modules/safe-buffer/index.d.ts b/node_modules/safe-buffer/index.d.ts new file mode 100644 index 000000000..e9fed809a --- /dev/null +++ b/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/node_modules/safe-buffer/index.js b/node_modules/safe-buffer/index.js new file mode 100644 index 000000000..f8d3ec988 --- /dev/null +++ b/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/node_modules/safe-buffer/package.json b/node_modules/safe-buffer/package.json new file mode 100644 index 000000000..f2869e256 --- /dev/null +++ b/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/node_modules/setup/.npmignore b/node_modules/setup/.npmignore new file mode 100644 index 000000000..496ee2ca6 --- /dev/null +++ b/node_modules/setup/.npmignore @@ -0,0 +1 @@ +.DS_Store \ No newline at end of file diff --git a/node_modules/setup/README.md b/node_modules/setup/README.md new file mode 100644 index 000000000..2e8155494 --- /dev/null +++ b/node_modules/setup/README.md @@ -0,0 +1,93 @@ +setup +===== +A server config utility for nodejs +Change: hostname, network interfaces, hosts and date/time + +# Features + +- Set your network configuration. supports wireless adapters +- Change your hostname +- Set your hosts file (local dns) +- Modify server date/time and BIOS update +- Only works in linux :) + +You need to install wpasupplicant for wireless options + + +# Install +```bash +npm install setup +``` + +# API + +### Networking +- setup.network.config(config) // Creates/returns a new network config file +- setup.network.save(config, outFile) // Saves the configuration +- setup.network.restart() // Restart network interfaces + + +### Hostname +- setup.hosts.save(hostname, outFile) + + +### Hosts (dns) +- setup.hosts.config(hosts) +- setup.hosts.save(config, outFile) + + +### Date/Time +- setup.clock.set(time) // Set date/time and sync BIOS clock + + +# Examples + +### Set network interfaces + +This will set your wlan0 card to connect at boot, use dhcp for ip settings, e connect to the SSID 'myWirelessName'. +Your ethernet card will have a static ip. + +```js +var setup = require('setup')(); + +var config = setup.network.config({ + + wlan0: { + auto: true, // start at Boot + dhcp: true, // Use DHCP + wireless: { + ssid: 'myWirelessName', // Wireless SSID + psk: 'mySuperPassword', // Password + } + }, + eth0: { + auto: true, + ipv4: { + address: '192.168.1.20', + netmask: '255.255.255.0', + gateway: '192.168.1.1', + dns: '8.8.8.8' + } + } +}); + +setup.network.save(config); +``` + + +### Change Hostname +```js +setup.hostname.save('nodejs.example.com'); +``` + +### Change hosts +```js +var hosts = setup.hosts.config({ + '10.0.0.1':'server1.example.com', + '10.0.0.2':'server2.example.com' +}); + +setup.hosts.save(hosts); +``` + + diff --git a/node_modules/setup/example.js b/node_modules/setup/example.js new file mode 100644 index 000000000..3f50d65c1 --- /dev/null +++ b/node_modules/setup/example.js @@ -0,0 +1,37 @@ +var setup = require('./setup.js')(); + +var config = setup.network.config({ + + wlan0: { + auto: true, // start at Boot + dhcp: true, // Use DHCP + wireless: { + ssid: 'myWirelessName', // Wireless SSID + psk: 'mySuperPassword', // Password + } + }, + eth0: { + auto: true, + ipv4: { + address: '192.168.1.20', + netmask: '255.255.255.0', + gateway: '192.168.1.1', + dns: '8.8.8.8' + } + } +}); + +setup.network.save(config, './network.txt'); + + + +setup.hostname.save('hello.com', './hostname.txt'); + + +var hosts = setup.hosts.config({ + '10.0.0.1':'server1.example.com', + '10.0.0.2':'server2.example.com' +}); + +setup.hosts.save(hosts, './hosts.txt'); + diff --git a/node_modules/setup/package.json b/node_modules/setup/package.json new file mode 100644 index 000000000..f8b712ba7 --- /dev/null +++ b/node_modules/setup/package.json @@ -0,0 +1,14 @@ +{ + "name": "setup", + "description": "A server config utility for nodejs", + "version": "0.0.3", + "author": "Hugo Rodrigues ", + "homepage": "https://github.com/hugorodrigues/setup", + "repository": { + "type": "git", + "url": "https://hugorodrigues@github.com/hugorodrigues/setup.git" + }, + "keywords": ["sysadmin", "devops", "network", "setup", "hostname", "wireless", "dns", "hostname"], + "main": "./setup.js", + "dependencies": {} +} \ No newline at end of file diff --git a/node_modules/setup/setup.js b/node_modules/setup/setup.js new file mode 100644 index 000000000..5ce9b1f34 --- /dev/null +++ b/node_modules/setup/setup.js @@ -0,0 +1,107 @@ +module.exports = function(){ + + var obj = { + network: {}, + hostname: {}, + hosts: {}, + crontab: {}, + clock: {}, + }; + + // Hostname + obj.hostname.save = function(hostname,outFile){ + require('fs').writeFileSync(outFile || '/etc/hostname', hostname); + } + + // Hosts + obj.hosts.save = function(config,outFile){ + require('fs').writeFileSync(outFile || '/etc/hosts', config); + } + + obj.hosts.config = function(hosts) { + + var output =[]; + var hostName = require('fs').readFileSync('/etc/hostname','UTF-8').trim(); + + output.push('127.0.0.1 localhost'); + output.push('127.0.0.1 '+hostName); + output.push(''); + + for (ip in hosts) + output.push(ip+' '+hosts[ip]); + + return output.join("\n"); + } + + + + + + // Date/Time + obj.clock.set = function(time) { + require('child_process').exec('date -s "'+time+'" ; hwclock --systohc;', cb); + } + + + + + // Networking + obj.network.restart = function(cb){ + require('child_process').exec('/etc/init.d/networking restart', cb); + } + obj.network.save = function(config,outFile){ + require('fs').writeFileSync(outFile || '/etc/network/interfaces', config); + } + obj.network.config = function(config){ + + var output= []; + + output.push('auto lo') + output.push('iface lo inet loopback') + + + for (device in config) + { + output.push('') + + if (config[device].auto) + output.push('auto '+device) + + if (config[device].dhcp == true) + output.push('iface '+device+' inet dhcp') + else + output.push('iface '+device+' inet static') + + if (config[device].wireless) + { + if (config[device].wireless.ssid) + output.push(' wpa-ssid '+config[device].wireless.ssid) + + if (config[device].wireless.psk) + output.push(' wpa-psk '+config[device].wireless.psk) + } + + if (config[device].ipv4) + { + if (config[device].ipv4.address) + output.push('address '+config[device].ipv4.address) + + if (config[device].ipv4.netmask) + output.push('netmask '+config[device].ipv4.netmask) + + if (config[device].ipv4.gateway) + output.push('gateway '+config[device].ipv4.gateway) + + if (config[device].ipv4.dns) + output.push('dns-nameservers '+config[device].ipv4.dns) + } + + } + + return output.join("\n"); + } + + + + return obj; +} \ No newline at end of file diff --git a/node_modules/sha.js/.travis.yml b/node_modules/sha.js/.travis.yml new file mode 100644 index 000000000..0b606eb57 --- /dev/null +++ b/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/node_modules/sha.js/LICENSE b/node_modules/sha.js/LICENSE new file mode 100644 index 000000000..11888c135 --- /dev/null +++ b/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/node_modules/sha.js/README.md b/node_modules/sha.js/README.md new file mode 100644 index 000000000..1cc3db558 --- /dev/null +++ b/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/node_modules/sha.js/bin.js b/node_modules/sha.js/bin.js new file mode 100755 index 000000000..5a7ac83a2 --- /dev/null +++ b/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/node_modules/sha.js/hash.js b/node_modules/sha.js/hash.js new file mode 100644 index 000000000..013537a97 --- /dev/null +++ b/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/node_modules/sha.js/index.js b/node_modules/sha.js/index.js new file mode 100644 index 000000000..87cdf4939 --- /dev/null +++ b/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/node_modules/sha.js/package.json b/node_modules/sha.js/package.json new file mode 100644 index 000000000..bfe633b2a --- /dev/null +++ b/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/node_modules/sha.js/sha.js b/node_modules/sha.js/sha.js new file mode 100644 index 000000000..50c4fa801 --- /dev/null +++ b/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/node_modules/sha.js/sha1.js b/node_modules/sha.js/sha1.js new file mode 100644 index 000000000..cabd747ce --- /dev/null +++ b/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/node_modules/sha.js/sha224.js b/node_modules/sha.js/sha224.js new file mode 100644 index 000000000..35541e575 --- /dev/null +++ b/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/node_modules/sha.js/sha256.js b/node_modules/sha.js/sha256.js new file mode 100644 index 000000000..342e48aee --- /dev/null +++ b/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/node_modules/sha.js/sha384.js b/node_modules/sha.js/sha384.js new file mode 100644 index 000000000..afc85e51f --- /dev/null +++ b/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/node_modules/sha.js/sha512.js b/node_modules/sha.js/sha512.js new file mode 100644 index 000000000..fb28f2f6b --- /dev/null +++ b/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/node_modules/sha.js/test/hash.js b/node_modules/sha.js/test/hash.js new file mode 100644 index 000000000..5fa000d5a --- /dev/null +++ b/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/node_modules/sha.js/test/test.js b/node_modules/sha.js/test/test.js new file mode 100644 index 000000000..dac8580ba --- /dev/null +++ b/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/node_modules/sha.js/test/vectors.js b/node_modules/sha.js/test/vectors.js new file mode 100644 index 000000000..48a646ef6 --- /dev/null +++ b/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/node_modules/sodium-native/CMakeLists.txt b/node_modules/sodium-native/CMakeLists.txt new file mode 100644 index 000000000..0c70d869a --- /dev/null +++ b/node_modules/sodium-native/CMakeLists.txt @@ -0,0 +1,241 @@ +cmake_minimum_required(VERSION 3.25) + +find_package(cmake-bare REQUIRED PATHS node_modules/cmake-bare) +find_package(cmake-fetch REQUIRED PATHS node_modules/cmake-fetch) +find_package(cmake-napi REQUIRED PATHS node_modules/cmake-napi) + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +project(sodium_native C ASM) + +fetch_package("github:jedisct1/libsodium#stable" SOURCE_DIR sodium) + +include(TestBigEndian) + +bare_target(target) + +file(COPY_FILE "${sodium}/builds/msvc/version.h" "${sodium}/src/libsodium/include/sodium/version.h") + +file(GLOB_RECURSE sodium_headers CONFIGURE_DEPENDS "${sodium}/src/libsodium/**/*.h") +file(GLOB_RECURSE sodium_sources CONFIGURE_DEPENDS "${sodium}/src/libsodium/**/*.c") +file(GLOB_RECURSE sodium_asm_sources CONFIGURE_DEPENDS "${sodium}/src/libsodium/**/*.S") + +add_library(sodium OBJECT) + +target_sources( + sodium + INTERFACE + ${sodium_headers} + PRIVATE + ${sodium_sources} +) + +target_include_directories( + sodium + INTERFACE + "${sodium}/src/libsodium/include" + PRIVATE + "${sodium}/src/libsodium/include/sodium" +) + +if(NOT target MATCHES "win32") + target_compile_options( + sodium + PRIVATE + -fvisibility=hidden + -fno-strict-aliasing + -fwrapv + -flax-vector-conversions + ) +endif() + +target_compile_definitions( + sodium + PUBLIC + SODIUM_STATIC=1 + PRIVATE + _GNU_SOURCE=1 + CONFIGURED=1 + DEV_MODE=1 + HAVE_ATOMIC_OPS=1 + HAVE_C11_MEMORY_FENCES=1 + HAVE_CET_H=1 + HAVE_GCC_MEMORY_FENCES=1 + HAVE_INLINE_ASM=1 + HAVE_INTTYPES_H=1 + HAVE_STDINT_H=1 + HAVE_TI_MODE=1 +) + +if(target MATCHES "darwin|ios") + target_compile_definitions( + sodium + PRIVATE + ASM_HIDE_SYMBOL=.private_extern + TLS=_Thread_local + HAVE_ARC4RANDOM=1 + HAVE_ARC4RANDOM_BUF=1 + HAVE_CATCHABLE_ABRT=1 + HAVE_CATCHABLE_SEGV=1 + HAVE_CLOCK_GETTIME=1 + HAVE_GETPID=1 + HAVE_MADVISE=1 + HAVE_MEMSET_S=1 + HAVE_MLOCK=1 + HAVE_MMAP=1 + HAVE_MPROTECT=1 + HAVE_NANOSLEEP=1 + HAVE_POSIX_MEMALIGN=1 + HAVE_PTHREAD=1 + HAVE_PTHREAD_PRIO_INHERIT=1 + HAVE_RAISE=1 + HAVE_SYSCONF=1 + HAVE_SYS_MMAN_H=1 + HAVE_SYS_PARAM_H=1 + HAVE_WEAK_SYMBOLS=1 + ) + + if(NOT target MATCHES "ios") + target_compile_definitions( + sodium + PRIVATE + HAVE_GETENTROPY=1 + HAVE_SYS_RANDOM_H=1 + ) + endif() +endif() + +if(target MATCHES "linux") + target_compile_definitions( + sodium + PRIVATE + ASM_HIDE_SYMBOL=.hidden + TLS=_Thread_local + HAVE_CATCHABLE_ABRT=1 + HAVE_CATCHABLE_SEGV=1 + HAVE_CLOCK_GETTIME=1 + HAVE_GETPID=1 + HAVE_MADVISE=1 + HAVE_MLOCK=1 + HAVE_MMAP=1 + HAVE_MPROTECT=1 + HAVE_NANOSLEEP=1 + HAVE_POSIX_MEMALIGN=1 + HAVE_PTHREAD_PRIO_INHERIT=1 + HAVE_PTHREAD=1 + HAVE_RAISE=1 + HAVE_SYSCONF=1 + HAVE_SYS_AUXV_H=1 + HAVE_SYS_MMAN_H=1 + HAVE_SYS_PARAM_H=1 + HAVE_SYS_RANDOM_H=1 + HAVE_WEAK_SYMBOLS=1 + ) +endif() + +if(target MATCHES "win32") + target_compile_definitions( + sodium + PRIVATE + _CRT_SECURE_NO_WARNINGS=1 + HAVE_RAISE=1 + ) +endif() + +if(target MATCHES "x64") + target_compile_definitions( + sodium + PRIVATE + HAVE_CPUID=1 + HAVE_RDRAND=1 + HAVE_EMMINTRIN_H=1 # SSE2 + HAVE_PMMINTRIN_H=1 # SSE3 + HAVE_TMMINTRIN_H=1 # SSSE3 + HAVE_SMMINTRIN_H=1 # SSE4.1 + HAVE_WMMINTRIN_H=1 # AES + HAVE_AVXINTRIN_H=1 # AVX + HAVE_AVX2INTRIN_H=1 # AVX2 + HAVE_AVX512FINTRIN_H # AVX512F + ) + + if(NOT target MATCHES "win32") + target_compile_definitions( + sodium + PRIVATE + HAVE_AMD64_ASM=1 + HAVE_AVX_ASM=1 + ) + + target_sources( + sodium + PRIVATE + ${sodium_asm_sources} + ) + endif() +endif() + +if(target MATCHES "arm64") + target_compile_definitions( + sodium + PRIVATE + HAVE_ARMCRYPTO=1 + ) +endif() + +test_big_endian(is_big_endian) + +if(is_big_endian) + target_compile_definitions( + sodium + PRIVATE + NATIVE_BIG_ENDIAN=1 + ) +else() + target_compile_definitions( + sodium + PRIVATE + NATIVE_LITTLE_ENDIAN=1 + ) +endif() + +add_bare_module(sodium_native_bare) + +target_sources( + ${sodium_native_bare} + PRIVATE + binding.c + macros.h + extensions/tweak/tweak.c + extensions/tweak/tweak.h + extensions/pbkdf2/pbkdf2.c + extensions/pbkdf2/pbkdf2.h +) + +target_link_libraries( + ${sodium_native_bare} + PRIVATE + $ + PUBLIC + sodium +) + +add_napi_module(sodium_native_node) + +target_sources( + ${sodium_native_node} + PRIVATE + binding.c + macros.h + extensions/tweak/tweak.c + extensions/tweak/tweak.h + extensions/pbkdf2/pbkdf2.c + extensions/pbkdf2/pbkdf2.h +) + +target_link_libraries( + ${sodium_native_node} + PRIVATE + $ + PUBLIC + sodium +) diff --git a/node_modules/sodium-native/LICENSE b/node_modules/sodium-native/LICENSE new file mode 100644 index 000000000..aebbe8df5 --- /dev/null +++ b/node_modules/sodium-native/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Mathias Buus and Emil Bay + +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/node_modules/sodium-native/README.md b/node_modules/sodium-native/README.md new file mode 100644 index 000000000..29ce6700f --- /dev/null +++ b/node_modules/sodium-native/README.md @@ -0,0 +1,51 @@ +# sodium-native + +Low level bindings for [libsodium](https://github.com/jedisct1/libsodium). + +``` +npm install sodium-native +``` + +The goal of this project is to be thin, stable, unopionated wrapper around libsodium. + +All methods exposed are more or less a direct translation of the libsodium c-api. +This means that most data types are buffers and you have to manage allocating return values and passing them in as arguments intead of receiving them as return values. + +This makes this API harder to use than other libsodium wrappers out there, but also means that you'll be able to get a lot of perf / memory improvements as you can do stuff like inline encryption / decryption, re-use buffers etc. + +This also makes this library useful as a foundation for more high level crypto abstractions that you want to make. + +## Usage + +``` js +var sodium = require('sodium-native') + +var nonce = Buffer.alloc(sodium.crypto_secretbox_NONCEBYTES) +var key = sodium.sodium_malloc(sodium.crypto_secretbox_KEYBYTES) // secure buffer +var message = Buffer.from('Hello, World!') +var ciphertext = Buffer.alloc(message.length + sodium.crypto_secretbox_MACBYTES) + +sodium.randombytes_buf(nonce) // insert random data into nonce +sodium.randombytes_buf(key) // insert random data into key + +// encrypted message is stored in ciphertext. +sodium.crypto_secretbox_easy(ciphertext, message, nonce, key) + +console.log('Encrypted message:', ciphertext) + +var plainText = Buffer.alloc(ciphertext.length - sodium.crypto_secretbox_MACBYTES) + +if (!sodium.crypto_secretbox_open_easy(plainText, ciphertext, nonce, key)) { + console.log('Decryption failed!') +} else { + console.log('Decrypted message:', plainText, '(' + plainText.toString() + ')') +} +``` + +## Documentation + +Complete documentation may be found on the [sodium-friends website](https://sodium-friends.github.io/docs/docs/getstarted) + +## License + +MIT diff --git a/node_modules/sodium-native/binding.c b/node_modules/sodium-native/binding.c new file mode 100644 index 000000000..a7b2e7696 --- /dev/null +++ b/node_modules/sodium-native/binding.c @@ -0,0 +1,3470 @@ +#include +#include +#include +#include +#include "macros.h" +#include "extensions/tweak/tweak.h" +#include "extensions/pbkdf2/pbkdf2.h" + +static uint8_t typedarray_width (napi_typedarray_type type) { + switch (type) { + case napi_int8_array: return 1; + case napi_uint8_array: return 1; + case napi_uint8_clamped_array: return 1; + case napi_int16_array: return 2; + case napi_uint16_array: return 2; + case napi_int32_array: return 4; + case napi_uint32_array: return 4; + case napi_float32_array: return 4; + case napi_float64_array: return 8; + case napi_bigint64_array: return 8; + case napi_biguint64_array: return 8; + default: return 0; + } +} + +static void sn_sodium_free_finalise (napi_env env, void *finalise_data, void *finalise_hint) { + napi_adjust_external_memory(env, -4 * 4096, NULL); + sodium_free(finalise_data); +} + +napi_value sn_sodium_memzero (napi_env env, napi_callback_info info) { + SN_ARGV(1, sodium_memzero) + + SN_ARGV_TYPEDARRAY(buf, 0) + + sodium_memzero(buf_data, buf_size); + + return NULL; +} + +napi_value sn_sodium_mlock (napi_env env, napi_callback_info info) { + SN_ARGV(1, sodium_mlock) + + SN_ARGV_TYPEDARRAY(buf, 0) + + SN_RETURN(sodium_mlock(buf_data, buf_size), "memory lock failed") +} + +napi_value sn_sodium_munlock (napi_env env, napi_callback_info info) { + SN_ARGV(1, sodium_munlock) + + SN_ARGV_TYPEDARRAY(buf, 0) + + SN_RETURN(sodium_munlock(buf_data, buf_size), "memory unlock failed") +} + +napi_value sn_sodium_free (napi_env env, napi_callback_info info) { + SN_ARGV(1, sodium_free) + + SN_ARGV_TYPEDARRAY_PTR(buf, 0) + + if (buf_data == NULL) return NULL; + + napi_value array_buf; + + SN_STATUS_THROWS(napi_get_named_property(env, argv[0], "buffer", &array_buf), "failed to get arraybuffer"); + SN_STATUS_THROWS(napi_remove_wrap(env, array_buf, NULL), "failed to remove wrap"); // remove the finalizer + SN_STATUS_THROWS(napi_detach_arraybuffer(env, array_buf), "failed to detach array buffer"); + napi_adjust_external_memory(env, -4 * 4096, NULL); + sodium_free(buf_data); + + return NULL; +} + +napi_value sn_sodium_malloc (napi_env env, napi_callback_info info) { + SN_ARGV(1, sodium_malloc); + + SN_ARGV_UINT32(size, 0) + + void *ptr = sodium_malloc(size); + + SN_THROWS(ptr == NULL, "ENOMEM") + napi_adjust_external_memory(env, 4 * 4096, NULL); + + SN_THROWS(ptr == NULL, "sodium_malloc failed"); + + napi_value buf, value, array_buf; + + SN_STATUS_THROWS(napi_create_external_buffer(env, size, ptr, NULL, NULL, &buf), "failed to create a n-api buffer") + SN_STATUS_THROWS(napi_get_boolean(env, true, &value), "failed to create boolean") + + SN_STATUS_THROWS(napi_get_named_property(env, buf, "buffer", &array_buf), "failed to get arraybuffer") + SN_STATUS_THROWS(napi_set_named_property(env, buf, "secure", value), "failed to set secure property") + + SN_STATUS_THROWS(napi_wrap(env, array_buf, ptr, sn_sodium_free_finalise, NULL, NULL), "failed to wrap") + + return buf; +} + +napi_value sn_sodium_mprotect_noaccess (napi_env env, napi_callback_info info) { + SN_ARGV(1, sodium_mprotect_noaccess); + + SN_ARGV_TYPEDARRAY_PTR(buf, 0) + + SN_RETURN(sodium_mprotect_noaccess(buf_data), "failed to lock buffer") +} + + +napi_value sn_sodium_mprotect_readonly (napi_env env, napi_callback_info info) { + SN_ARGV(1, sodium_readonly); + + SN_ARGV_TYPEDARRAY_PTR(buf, 0) + + SN_RETURN(sodium_mprotect_readonly(buf_data), "failed to unlock buffer") +} + + +napi_value sn_sodium_mprotect_readwrite (napi_env env, napi_callback_info info) { + SN_ARGV(1, sodium_readwrite); + + SN_ARGV_TYPEDARRAY_PTR(buf, 0) + + SN_RETURN(sodium_mprotect_readwrite(buf_data), "failed to unlock buffer") +} + +napi_value sn_randombytes_random (napi_env env, napi_callback_info info) { + napi_value result; + + napi_create_uint32(env, randombytes_random(), &result); + return result; +} + +napi_value sn_randombytes_uniform (napi_env env, napi_callback_info info) { + SN_ARGV(1, randombytes_uniform); + + SN_ARGV_UINT32(upper_bound, 0) + + napi_value result; + napi_create_uint32(env, randombytes_uniform(upper_bound), &result); + return result; +} + +napi_value sn_randombytes_buf (napi_env env, napi_callback_info info) { + SN_ARGV(1, randombytes_buf) + + SN_ARGV_TYPEDARRAY(buf, 0) + + randombytes_buf(buf_data, buf_size); + + return NULL; +} + +napi_value sn_randombytes_buf_deterministic (napi_env env, napi_callback_info info) { + SN_ARGV(2, randombytes_buf) + + SN_ARGV_TYPEDARRAY(buf, 0) + SN_ARGV_TYPEDARRAY(seed, 1) + + SN_ASSERT_LENGTH(seed_size, randombytes_SEEDBYTES, "seed") + + randombytes_buf_deterministic(buf_data, buf_size, seed_data); + + return NULL; +} + +napi_value sn_sodium_memcmp(napi_env env, napi_callback_info info) { + SN_ARGV(2, sodium_memcmp); + + SN_ARGV_TYPEDARRAY(b1, 0) + SN_ARGV_TYPEDARRAY(b2, 1) + + SN_THROWS(b1_size != b2_size, "buffers must be of same length") + + SN_RETURN_BOOLEAN(sodium_memcmp(b1_data, b2_data, b1_size)) +} + +napi_value sn_sodium_increment(napi_env env, napi_callback_info info) { + SN_ARGV(1, sodium_increment); + SN_ARGV_TYPEDARRAY(n, 0) + + sodium_increment(n_data, n_size); + + return NULL; +} + +napi_value sn_sodium_add(napi_env env, napi_callback_info info) { + SN_ARGV(2, sodium_add); + + SN_ARGV_TYPEDARRAY(a, 0) + SN_ARGV_TYPEDARRAY(b, 1) + + SN_THROWS(a_size != b_size, "buffers must be of same length") + sodium_add(a_data, b_data, a_size); + + return NULL; +} + +napi_value sn_sodium_sub(napi_env env, napi_callback_info info) { + SN_ARGV(2, sodium_sub); + + SN_ARGV_TYPEDARRAY(a, 0) + SN_ARGV_TYPEDARRAY(b, 1) + + SN_THROWS(a_size != b_size, "buffers must be of same length") + sodium_sub(a_data, b_data, a_size); + + return NULL; +} + +napi_value sn_sodium_compare(napi_env env, napi_callback_info info) { + SN_ARGV(2, sodium_compare); + + SN_ARGV_TYPEDARRAY(a, 0) + SN_ARGV_TYPEDARRAY(b, 1) + + SN_THROWS(a_size != b_size, "buffers must be of same length") + int cmp = sodium_compare(a_data, b_data, a_size); + + napi_value result; + napi_create_int32(env, cmp, &result); + + return result; +} + +napi_value sn_sodium_is_zero(napi_env env, napi_callback_info info) { + SN_ARGV_OPTS(1, 2, sodium_is_zero); + + SN_ARGV_TYPEDARRAY(a, 0) + + size_t a_full = a_size; + + if (argc == 2) { + SN_OPT_ARGV_UINT32(a_size, 1) + SN_THROWS(a_size > a_full, "len must be shorter than 'buf.byteLength'") + } + + SN_RETURN_BOOLEAN_FROM_1(sodium_is_zero(a_data, a_size)) +} + +napi_value sn_sodium_pad(napi_env env, napi_callback_info info) { + SN_ARGV(3, sodium_pad); + + SN_ARGV_TYPEDARRAY(buf, 0) + SN_ARGV_UINT32(unpadded_buflen, 1) + SN_ARGV_UINT32(blocksize, 2) + + SN_THROWS(unpadded_buflen > buf_size, "unpadded length cannot exceed buffer length") + SN_THROWS(blocksize > buf_size, "block size cannot exceed buffer length") + SN_THROWS(blocksize < 1, "block sizemust be at least 1 byte") + SN_THROWS(buf_size < unpadded_buflen + (blocksize - (unpadded_buflen % blocksize)), "buf not long enough") + + napi_value result; + size_t padded_buflen; + sodium_pad(&padded_buflen, buf_data, unpadded_buflen, blocksize, buf_size); + napi_create_uint32(env, padded_buflen, &result); + return result; +} + +napi_value sn_sodium_unpad(napi_env env, napi_callback_info info) { + SN_ARGV(3, sodium_unpad); + + SN_ARGV_TYPEDARRAY(buf, 0) + SN_ARGV_UINT32(padded_buflen, 1) + SN_ARGV_UINT32(blocksize, 2) + + SN_THROWS(padded_buflen > buf_size, "unpadded length cannot exceed buffer length") + SN_THROWS(blocksize > buf_size, "block size cannot exceed buffer length") + SN_THROWS(blocksize < 1, "block size must be at least 1 byte") + + napi_value result; + size_t unpadded_buflen; + sodium_unpad(&unpadded_buflen, buf_data, padded_buflen, blocksize); + napi_create_uint32(env, unpadded_buflen, &result); + return result; +} + +napi_value sn_crypto_sign_keypair(napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_sign_keypair) + + SN_ARGV_TYPEDARRAY(pk, 0) + SN_ARGV_TYPEDARRAY(sk, 1) + + SN_ASSERT_LENGTH(pk_size, crypto_sign_PUBLICKEYBYTES, "pk") + SN_ASSERT_LENGTH(sk_size, crypto_sign_SECRETKEYBYTES, "sk") + + SN_RETURN(crypto_sign_keypair(pk_data, sk_data), "keypair generation failed") +} + +napi_value sn_crypto_sign_seed_keypair(napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_sign_seed_keypair) + + SN_ARGV_TYPEDARRAY(pk, 0) + SN_ARGV_TYPEDARRAY(sk, 1) + SN_ARGV_TYPEDARRAY(seed, 2) + + SN_ASSERT_LENGTH(pk_size, crypto_sign_PUBLICKEYBYTES, "pk") + SN_ASSERT_LENGTH(sk_size, crypto_sign_SECRETKEYBYTES, "sk") + SN_ASSERT_LENGTH(seed_size, crypto_sign_SEEDBYTES, "seed") + + SN_RETURN(crypto_sign_seed_keypair(pk_data, sk_data, seed_data), "keypair generation failed") +} + +napi_value sn_crypto_sign(napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_sign) + + SN_ARGV_TYPEDARRAY(sm, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(sk, 2) + + SN_THROWS(sm_size != crypto_sign_BYTES + m_size, "sm must be 'm.byteLength + crypto_sign_BYTES' bytes") + SN_ASSERT_LENGTH(sk_size, crypto_sign_SECRETKEYBYTES, "sk") + + SN_RETURN(crypto_sign(sm_data, NULL, m_data, m_size, sk_data), "signature failed") +} + +napi_value sn_crypto_sign_open(napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_sign_open) + + SN_ARGV_TYPEDARRAY(m, 0) + SN_ARGV_TYPEDARRAY(sm, 1) + SN_ARGV_TYPEDARRAY(pk, 2) + + SN_THROWS(m_size != sm_size - crypto_sign_BYTES, "m must be 'sm.byteLength - crypto_sign_BYTES' bytes") + SN_ASSERT_MIN_LENGTH(sm_size, crypto_sign_BYTES, "sm") + SN_ASSERT_LENGTH(pk_size, crypto_sign_PUBLICKEYBYTES, "pk") + + SN_RETURN_BOOLEAN(crypto_sign_open(m_data, NULL, sm_data, sm_size, pk_data)) +} + +napi_value sn_crypto_sign_detached(napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_sign_detached) + + SN_ARGV_TYPEDARRAY(sig, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(sk, 2) + + SN_ASSERT_LENGTH(sig_size, crypto_sign_BYTES, "sm") + SN_ASSERT_LENGTH(sk_size, crypto_sign_SECRETKEYBYTES, "sk") + + SN_RETURN(crypto_sign_detached(sig_data, NULL, m_data, m_size, sk_data), "signature failed") +} + +napi_value sn_crypto_sign_verify_detached(napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_sign_verify_detached) + + SN_ARGV_TYPEDARRAY(sig, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(pk, 2) + + SN_ASSERT_MIN_LENGTH(sig_size, crypto_sign_BYTES, "sig") + SN_ASSERT_LENGTH(pk_size, crypto_sign_PUBLICKEYBYTES, "pk") + + SN_RETURN_BOOLEAN(crypto_sign_verify_detached(sig_data, m_data, m_size, pk_data)) +} + +napi_value sn_crypto_sign_ed25519_sk_to_pk(napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_sign_ed25519_sk_to_pk) + + SN_ARGV_TYPEDARRAY(pk, 0) + SN_ARGV_TYPEDARRAY(sk, 1) + + SN_ASSERT_LENGTH(pk_size, crypto_sign_PUBLICKEYBYTES, "pk") + SN_ASSERT_LENGTH(sk_size, crypto_sign_SECRETKEYBYTES, "sk") + + SN_RETURN(crypto_sign_ed25519_sk_to_pk(pk_data, sk_data), "public key generation failed") +} + +napi_value sn_crypto_sign_ed25519_pk_to_curve25519(napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_sign_ed25519_sk_to_pk) + + SN_ARGV_TYPEDARRAY(x25519_pk, 0) + SN_ARGV_TYPEDARRAY(ed25519_pk, 1) + + SN_ASSERT_LENGTH(x25519_pk_size, crypto_box_PUBLICKEYBYTES, "x25519_pk") + SN_ASSERT_LENGTH(ed25519_pk_size, crypto_sign_PUBLICKEYBYTES, "ed25519_pk") + + SN_RETURN(crypto_sign_ed25519_pk_to_curve25519(x25519_pk_data, ed25519_pk_data), "public key conversion failed") +} + +napi_value sn_crypto_sign_ed25519_sk_to_curve25519(napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_sign_ed25519_sk_to_pk) + + SN_ARGV_TYPEDARRAY(x25519_sk, 0) + SN_ARGV_TYPEDARRAY(ed25519_sk, 1) + + SN_ASSERT_LENGTH(x25519_sk_size, crypto_box_SECRETKEYBYTES, "x25519_sk") + SN_THROWS(ed25519_sk_size != crypto_sign_SECRETKEYBYTES && ed25519_sk_size != crypto_box_SECRETKEYBYTES, "ed25519_sk should either be 'crypto_sign_SECRETKEYBYTES' bytes or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes") + + SN_RETURN(crypto_sign_ed25519_sk_to_curve25519(x25519_sk_data, ed25519_sk_data), "secret key conversion failed") +} + +napi_value sn_crypto_generichash(napi_env env, napi_callback_info info) { + SN_ARGV_OPTS(2, 3, crypto_generichash) + + SN_ARGV_TYPEDARRAY(out, 0) + SN_ARGV_TYPEDARRAY(in, 1) + + SN_ASSERT_MIN_LENGTH(out_size, crypto_generichash_BYTES_MIN, "out") + SN_ASSERT_MAX_LENGTH(out_size, crypto_generichash_BYTES_MAX, "out") + + void *key_data = NULL; + size_t key_size = 0; + + if (argc == 3) { + SN_OPT_ARGV_TYPEDARRAY(key, 2) + SN_THROWS(key_size < crypto_generichash_KEYBYTES_MIN, "key") + SN_ASSERT_MIN_LENGTH(key_size, crypto_generichash_KEYBYTES_MIN, "key") + SN_ASSERT_MAX_LENGTH(key_size, crypto_generichash_KEYBYTES_MAX, "key") + } + + SN_RETURN(crypto_generichash(out_data, out_size, in_data, in_size, key_data, key_size), "hash failed") +} + +napi_value sn_crypto_generichash_batch(napi_env env, napi_callback_info info) { + SN_ARGV_OPTS(2, 3, crypto_generichash) + + SN_ARGV_TYPEDARRAY(out, 0) + + uint32_t batch_length; + napi_get_array_length(env, argv[1], &batch_length); + + SN_ASSERT_MIN_LENGTH(out_size, crypto_generichash_BYTES_MIN, "out") + SN_ASSERT_MAX_LENGTH(out_size, crypto_generichash_BYTES_MAX, "out") + + void *key_data = NULL; + size_t key_size = 0; + + if (argc == 3) { + SN_OPT_ARGV_TYPEDARRAY(key, 2) + SN_ASSERT_MIN_LENGTH(key_size, crypto_generichash_KEYBYTES_MIN, "key") + SN_ASSERT_MAX_LENGTH(key_size, crypto_generichash_KEYBYTES_MAX, "key") + } + + crypto_generichash_state state; + crypto_generichash_init(&state, key_data, key_size, out_size); + for (uint32_t i = 0; i < batch_length; i++) { + napi_value element; + napi_get_element(env, argv[1], i, &element); + SN_TYPEDARRAY_ASSERT(buf, element, "batch element should be passed as a TypedArray") + SN_TYPEDARRAY(buf, element) + crypto_generichash_update(&state, buf_data, buf_size); + } + + SN_RETURN(crypto_generichash_final(&state, out_data, out_size), "batch failed") +} + +napi_value sn_crypto_generichash_keygen(napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_generichash_keygen) + + SN_ARGV_TYPEDARRAY(key, 0) + + SN_ASSERT_LENGTH(key_size, crypto_generichash_KEYBYTES, "key") + + crypto_generichash_keygen(key_data); + + return NULL; +} + +napi_value sn_crypto_generichash_init(napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_generichash_init) + + SN_ARGV_BUFFER_CAST(crypto_generichash_state *, state, 0) + SN_ARGV_OPTS_TYPEDARRAY(key, 1) + SN_ARGV_UINT32(outlen, 2) + + SN_THROWS(state_size != sizeof(crypto_generichash_state), "state must be 'crypto_generichash_STATEBYTES' bytes") + + if (key_data != NULL) { + SN_ASSERT_MIN_LENGTH(key_size, crypto_generichash_KEYBYTES_MIN, "key") + SN_ASSERT_MAX_LENGTH(key_size, crypto_generichash_KEYBYTES_MAX, "key") + } + + SN_RETURN(crypto_generichash_init(state, key_data, key_size, outlen), "hash failed to initialise") +} + +napi_value sn_crypto_generichash_update(napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_generichash_update) + + SN_ARGV_BUFFER_CAST(crypto_generichash_state *, state, 0) + SN_ARGV_TYPEDARRAY(in, 1) + + SN_THROWS(state_size != sizeof(crypto_generichash_state), "state must be 'crypto_generichash_STATEBYTES' bytes") + + SN_RETURN(crypto_generichash_update(state, in_data, in_size), "update failed") +} + +napi_value sn_crypto_generichash_final(napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_generichash_final) + + SN_ARGV_BUFFER_CAST(crypto_generichash_state *, state, 0) + SN_ARGV_TYPEDARRAY(out, 1) + + SN_THROWS(state_size != sizeof(crypto_generichash_state), "state must be 'crypto_generichash_STATEBYTES' bytes") + + SN_RETURN(crypto_generichash_final(state, out_data, out_size), "digest failed") +} + +napi_value sn_crypto_box_keypair(napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_box_keypair) + + SN_ARGV_TYPEDARRAY(pk, 0) + SN_ARGV_TYPEDARRAY(sk, 1) + + SN_ASSERT_LENGTH(pk_size, crypto_box_PUBLICKEYBYTES, "pk") + SN_ASSERT_LENGTH(sk_size, crypto_box_SECRETKEYBYTES, "sk") + + SN_RETURN(crypto_box_keypair(pk_data, sk_data), "keypair generation failed") +} + +napi_value sn_crypto_box_seed_keypair(napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_box_seed_keypair) + + SN_ARGV_TYPEDARRAY(pk, 0) + SN_ARGV_TYPEDARRAY(sk, 1) + SN_ARGV_TYPEDARRAY(seed, 2) + + SN_ASSERT_LENGTH(pk_size, crypto_box_PUBLICKEYBYTES, "pk") + SN_ASSERT_LENGTH(sk_size, crypto_box_SECRETKEYBYTES, "sk") + SN_ASSERT_LENGTH(seed_size, crypto_box_SEEDBYTES, "seed") + + SN_RETURN(crypto_box_seed_keypair(pk_data, sk_data, seed_data), "keypair generation failed") +} + +napi_value sn_crypto_box_easy(napi_env env, napi_callback_info info) { + SN_ARGV(5, crypto_box_easy) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(n, 2) + SN_ARGV_TYPEDARRAY(pk, 3) + SN_ARGV_TYPEDARRAY(sk, 4) + + SN_THROWS(c_size != m_size + crypto_box_MACBYTES, "c must be 'm.byteLength + crypto_box_MACBYTES' bytes") + SN_ASSERT_LENGTH(n_size, crypto_box_NONCEBYTES, "n") + SN_ASSERT_LENGTH(sk_size, crypto_box_SECRETKEYBYTES, "sk") + SN_ASSERT_LENGTH(pk_size, crypto_box_PUBLICKEYBYTES, "pk") + + SN_RETURN(crypto_box_easy(c_data, m_data, m_size, n_data, pk_data, sk_data), "crypto box failed") +} + +napi_value sn_crypto_box_open_easy(napi_env env, napi_callback_info info) { + SN_ARGV(5, crypto_box_open_easy) + + SN_ARGV_TYPEDARRAY(m, 0) + SN_ARGV_TYPEDARRAY(c, 1) + SN_ARGV_TYPEDARRAY(n, 2) + SN_ARGV_TYPEDARRAY(pk, 3) + SN_ARGV_TYPEDARRAY(sk, 4) + + SN_THROWS(m_size != c_size - crypto_box_MACBYTES, "m must be 'c.byteLength - crypto_box_MACBYTES' bytes") + SN_ASSERT_MIN_LENGTH(c_size, crypto_box_MACBYTES, "c") + SN_ASSERT_LENGTH(n_size, crypto_box_NONCEBYTES, "n") + SN_ASSERT_LENGTH(sk_size, crypto_box_SECRETKEYBYTES, "sk") + SN_ASSERT_LENGTH(pk_size, crypto_box_PUBLICKEYBYTES, "pk") + + SN_RETURN_BOOLEAN(crypto_box_open_easy(m_data, c_data, c_size, n_data, pk_data, sk_data)) +} + +napi_value sn_crypto_box_detached(napi_env env, napi_callback_info info) { + SN_ARGV(6, crypto_box_detached) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(mac, 1) + SN_ARGV_TYPEDARRAY(m, 2) + SN_ARGV_TYPEDARRAY(n, 3) + SN_ARGV_TYPEDARRAY(pk, 4) + SN_ARGV_TYPEDARRAY(sk, 5) + + SN_THROWS(c_size != m_size, "c must be 'm.byteLength' bytes") + SN_ASSERT_LENGTH(mac_size, crypto_box_MACBYTES, "mac") + SN_ASSERT_LENGTH(n_size, crypto_box_NONCEBYTES, "n") + SN_ASSERT_LENGTH(sk_size, crypto_box_SECRETKEYBYTES, "sk") + SN_ASSERT_LENGTH(pk_size, crypto_box_PUBLICKEYBYTES, "pk") + + SN_RETURN(crypto_box_detached(c_data, mac_data, m_data, m_size, n_data, pk_data, sk_data), "signature failed") +} + +napi_value sn_crypto_box_open_detached(napi_env env, napi_callback_info info) { + SN_ARGV(6, crypto_box_open_detached) + + SN_ARGV_TYPEDARRAY(m, 0) + SN_ARGV_TYPEDARRAY(c, 1) + SN_ARGV_TYPEDARRAY(mac, 2) + SN_ARGV_TYPEDARRAY(n, 3) + SN_ARGV_TYPEDARRAY(pk, 4) + SN_ARGV_TYPEDARRAY(sk, 5) + + SN_THROWS(m_size != c_size, "m must be 'c.byteLength' bytes") + SN_ASSERT_LENGTH(mac_size, crypto_box_MACBYTES, "mac") + SN_ASSERT_LENGTH(n_size, crypto_box_NONCEBYTES, "n") + SN_ASSERT_LENGTH(sk_size, crypto_box_SECRETKEYBYTES, "sk") + SN_ASSERT_LENGTH(pk_size, crypto_box_PUBLICKEYBYTES, "pk") + + SN_RETURN_BOOLEAN(crypto_box_open_detached(m_data, c_data, mac_data, c_size, n_data, pk_data, sk_data)) +} + +napi_value sn_crypto_box_seal(napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_box_seal) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(pk, 2) + + SN_THROWS(c_size != m_size + crypto_box_SEALBYTES, "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes") + SN_ASSERT_LENGTH(pk_size, crypto_box_PUBLICKEYBYTES, "pk") + + SN_RETURN(crypto_box_seal(c_data, m_data, m_size, pk_data), "failed to create seal") +} + +napi_value sn_crypto_box_seal_open(napi_env env, napi_callback_info info) { + SN_ARGV(4, crypto_box_seal_open) + + SN_ARGV_TYPEDARRAY(m, 0) + SN_ARGV_TYPEDARRAY(c, 1) + SN_ARGV_TYPEDARRAY(pk, 2) + SN_ARGV_TYPEDARRAY(sk, 3) + + SN_THROWS(m_size != c_size - crypto_box_SEALBYTES, "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes") + SN_ASSERT_MIN_LENGTH(c_size, crypto_box_SEALBYTES, "c") + SN_ASSERT_LENGTH(sk_size, crypto_box_SECRETKEYBYTES, "sk") + SN_ASSERT_LENGTH(pk_size, crypto_box_PUBLICKEYBYTES, "pk") + + SN_RETURN_BOOLEAN(crypto_box_seal_open(m_data, c_data, c_size, pk_data, sk_data)) +} + +napi_value sn_crypto_secretbox_easy(napi_env env, napi_callback_info info) { + SN_ARGV(4, crypto_secretbox_easy) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(n, 2) + SN_ARGV_TYPEDARRAY(k, 3) + + SN_THROWS(c_size != m_size + crypto_secretbox_MACBYTES, "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes") + SN_ASSERT_LENGTH(n_size, crypto_secretbox_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_secretbox_KEYBYTES, "k") + + SN_RETURN(crypto_secretbox_easy(c_data, m_data, m_size, n_data, k_data), "crypto secretbox failed") +} + +napi_value sn_crypto_secretbox_open_easy(napi_env env, napi_callback_info info) { + SN_ARGV(4, crypto_secretbox_open_easy) + + SN_ARGV_TYPEDARRAY(m, 0) + SN_ARGV_TYPEDARRAY(c, 1) + SN_ARGV_TYPEDARRAY(n, 2) + SN_ARGV_TYPEDARRAY(k, 3) + + SN_THROWS(m_size != c_size - crypto_secretbox_MACBYTES, "m must be 'c - crypto_secretbox_MACBYTES' bytes") + SN_ASSERT_MIN_LENGTH(c_size, crypto_secretbox_MACBYTES, "c") + SN_ASSERT_LENGTH(n_size, crypto_secretbox_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_secretbox_KEYBYTES, "k") + + SN_RETURN_BOOLEAN(crypto_secretbox_open_easy(m_data, c_data, c_size, n_data, k_data)) +} + +napi_value sn_crypto_secretbox_detached(napi_env env, napi_callback_info info) { + SN_ARGV(5, crypto_secretbox_detached) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(mac, 1) + SN_ARGV_TYPEDARRAY(m, 2) + SN_ARGV_TYPEDARRAY(n, 3) + SN_ARGV_TYPEDARRAY(k, 4) + + SN_THROWS(c_size != m_size, "c must 'm.byteLength' bytes") + SN_ASSERT_LENGTH(mac_size, crypto_secretbox_MACBYTES, "mac") + SN_ASSERT_LENGTH(n_size, crypto_secretbox_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_secretbox_KEYBYTES, "k") + + SN_RETURN(crypto_secretbox_detached(c_data, mac_data, m_data, m_size, n_data, k_data), "failed to open box") +} + +napi_value sn_crypto_secretbox_open_detached(napi_env env, napi_callback_info info) { + SN_ARGV(5, crypto_secretbox_open_detached) + + SN_ARGV_TYPEDARRAY(m, 0) + SN_ARGV_TYPEDARRAY(c, 1) + SN_ARGV_TYPEDARRAY(mac, 2) + SN_ARGV_TYPEDARRAY(n, 3) + SN_ARGV_TYPEDARRAY(k, 4) + + SN_THROWS(m_size != c_size, "m must be 'c.byteLength' bytes") + SN_ASSERT_LENGTH(mac_size, crypto_secretbox_MACBYTES, "mac") + SN_ASSERT_LENGTH(n_size, crypto_secretbox_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_secretbox_KEYBYTES, "k") + + SN_RETURN_BOOLEAN(crypto_secretbox_open_detached(m_data, c_data, mac_data, c_size, n_data, k_data)) +} + +napi_value sn_crypto_stream(napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(n, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_ASSERT_LENGTH(n_size, crypto_stream_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_KEYBYTES, "k") + + SN_RETURN(crypto_stream(c_data, c_size, n_data, k_data), "stream encryption failed") +} + +napi_value sn_crypto_stream_xor(napi_env env, napi_callback_info info) { + SN_ARGV(4, crypto_stream_xor) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(n, 2) + SN_ARGV_TYPEDARRAY(k, 3) + + SN_THROWS(c_size != m_size, "m must be 'c.byteLength' bytes") + SN_ASSERT_LENGTH(n_size, crypto_stream_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_KEYBYTES, "k") + + SN_RETURN(crypto_stream_xor(c_data, m_data, m_size, n_data, k_data), "stream encryption failed") +} + +napi_value sn_crypto_stream_chacha20(napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream_chacha20) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(n, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_ASSERT_LENGTH(n_size, crypto_stream_chacha20_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_chacha20_KEYBYTES, "k") + + SN_RETURN(crypto_stream_chacha20(c_data, c_size, n_data, k_data), "stream encryption failed") +} + +napi_value sn_crypto_stream_chacha20_xor (napi_env env, napi_callback_info info) { + SN_ARGV(4, crypto_stream_chacha20_xor) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(n, 2) + SN_ARGV_TYPEDARRAY(k, 3) + + SN_THROWS(c_size != m_size, "m must be 'c.byteLength' bytes") + SN_ASSERT_LENGTH(n_size, crypto_stream_chacha20_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_chacha20_KEYBYTES, "k") + + SN_RETURN(crypto_stream_chacha20_xor(c_data, m_data, m_size, n_data, k_data), "stream encryption failed") +} + +napi_value sn_crypto_stream_chacha20_xor_ic(napi_env env, napi_callback_info info) { + SN_ARGV(5, crypto_stream_chacha20_xor_ic) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(n, 2) + SN_ARGV_UINT32(ic, 3) + SN_ARGV_TYPEDARRAY(k, 4) + + SN_THROWS(c_size != m_size, "m must be 'c.byteLength' bytes") + SN_ASSERT_LENGTH(n_size, crypto_stream_chacha20_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_chacha20_KEYBYTES, "k") + + SN_RETURN(crypto_stream_chacha20_xor_ic(c_data, m_data, m_size, n_data, ic, k_data), "stream encryption failed") +} + +napi_value sn_crypto_stream_chacha20_ietf(napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream_chacha20_ietf) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(n, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_ASSERT_LENGTH(n_size, crypto_stream_chacha20_ietf_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_chacha20_ietf_KEYBYTES, "k") + + SN_RETURN(crypto_stream_chacha20_ietf(c_data, c_size, n_data, k_data), "stream encryption failed") +} + +napi_value sn_crypto_stream_chacha20_ietf_xor(napi_env env, napi_callback_info info) { + SN_ARGV(4, crypto_stream_chacha20_ietf_xor) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(n, 2) + SN_ARGV_TYPEDARRAY(k, 3) + + SN_THROWS(c_size != m_size, "m must be 'c.byteLength' bytes") + SN_ASSERT_LENGTH(n_size, crypto_stream_chacha20_ietf_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_chacha20_ietf_KEYBYTES, "k") + + SN_RETURN(crypto_stream_chacha20_ietf_xor(c_data, m_data, m_size, n_data, k_data), "stream encryption failed") +} + +napi_value sn_crypto_stream_chacha20_ietf_xor_ic(napi_env env, napi_callback_info info) { + SN_ARGV(5, crypto_stream_chacha20_ietf_xor_ic) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(n, 2) + SN_ARGV_UINT32(ic, 3) + SN_ARGV_TYPEDARRAY(k, 4) + + SN_THROWS(c_size != m_size, "m must be 'c.byteLength' bytes") + SN_ASSERT_LENGTH(n_size, crypto_stream_chacha20_ietf_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_chacha20_ietf_KEYBYTES, "k") + + SN_RETURN(crypto_stream_chacha20_ietf_xor_ic(c_data, m_data, m_size, n_data, ic, k_data), "stream encryption failed") +} + +napi_value sn_crypto_stream_xchacha20(napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream_xchacha20) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(n, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_ASSERT_LENGTH(n_size, crypto_stream_xchacha20_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_xchacha20_KEYBYTES, "k") + + SN_RETURN(crypto_stream_xchacha20(c_data, c_size, n_data, k_data), "stream encryption failed") +} + +napi_value sn_crypto_stream_xchacha20_xor (napi_env env, napi_callback_info info) { + SN_ARGV(4, crypto_stream_xchacha20_xor) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(n, 2) + SN_ARGV_TYPEDARRAY(k, 3) + + SN_THROWS(c_size != m_size, "m must be 'c.byteLength' bytes") + SN_ASSERT_LENGTH(n_size, crypto_stream_xchacha20_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_xchacha20_KEYBYTES, "k") + + SN_RETURN(crypto_stream_xchacha20_xor(c_data, m_data, m_size, n_data, k_data), "stream encryption failed") +} + +napi_value sn_crypto_stream_xchacha20_xor_ic(napi_env env, napi_callback_info info) { + SN_ARGV(5, crypto_stream_xchacha20_xor_ic) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(n, 2) + SN_ARGV_UINT32(ic, 3) + SN_ARGV_TYPEDARRAY(k, 4) + + SN_THROWS(c_size != m_size, "m must be 'c.byteLength' bytes") + SN_ASSERT_LENGTH(n_size, crypto_stream_xchacha20_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_xchacha20_KEYBYTES, "k") + + SN_RETURN(crypto_stream_xchacha20_xor_ic(c_data, m_data, m_size, n_data, ic, k_data), "stream encryption failed") +} + +napi_value sn_crypto_stream_salsa20(napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream_salsa20) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(n, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_ASSERT_LENGTH(n_size, crypto_stream_salsa20_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_salsa20_KEYBYTES, "k") + + SN_RETURN(crypto_stream_salsa20(c_data, c_size, n_data, k_data), "stream encryption failed") +} + +napi_value sn_crypto_stream_salsa20_xor (napi_env env, napi_callback_info info) { + SN_ARGV(4, crypto_stream_salsa20_xor) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(n, 2) + SN_ARGV_TYPEDARRAY(k, 3) + + SN_THROWS(c_size != m_size, "m must be 'c.byteLength' bytes") + SN_ASSERT_LENGTH(n_size, crypto_stream_salsa20_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_salsa20_KEYBYTES, "k") + + SN_RETURN(crypto_stream_salsa20_xor(c_data, m_data, m_size, n_data, k_data), "stream encryption failed") +} + +napi_value sn_crypto_stream_salsa20_xor_ic(napi_env env, napi_callback_info info) { + SN_ARGV(5, crypto_stream_salsa20_xor_ic) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(n, 2) + SN_ARGV_UINT32(ic, 3) + SN_ARGV_TYPEDARRAY(k, 4) + + SN_THROWS(c_size != m_size, "m must be 'c.byteLength' bytes") + SN_ASSERT_LENGTH(n_size, crypto_stream_salsa20_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_salsa20_KEYBYTES, "k") + + SN_RETURN(crypto_stream_salsa20_xor_ic(c_data, m_data, m_size, n_data, ic, k_data), "stream encryption failed") +} + +napi_value sn_crypto_auth (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_auth) + + SN_ARGV_TYPEDARRAY(out, 0) + SN_ARGV_TYPEDARRAY(in, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_ASSERT_LENGTH(out_size, crypto_auth_BYTES, "out") + SN_ASSERT_LENGTH(k_size, crypto_auth_KEYBYTES, "k") + + SN_RETURN(crypto_auth(out_data, in_data, in_size, k_data), "failed to generate authentication tag") +} + +napi_value sn_crypto_auth_verify (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_auth_verify) + + SN_ARGV_TYPEDARRAY(h, 0) + SN_ARGV_TYPEDARRAY(in, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_ASSERT_LENGTH(h_size, crypto_auth_BYTES, "h") + SN_ASSERT_LENGTH(k_size, crypto_auth_KEYBYTES, "k") + + SN_RETURN_BOOLEAN(crypto_auth_verify(h_data, in_data, in_size, k_data)) +} + +napi_value sn_crypto_onetimeauth (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_onetimeauth) + + SN_ARGV_TYPEDARRAY(out, 0) + SN_ARGV_TYPEDARRAY(in, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_ASSERT_LENGTH(out_size, crypto_onetimeauth_BYTES, "out") + SN_ASSERT_LENGTH(k_size, crypto_onetimeauth_KEYBYTES, "k") + + SN_RETURN(crypto_onetimeauth(out_data, in_data, in_size, k_data), "failed to generate onetime authentication tag") +} + +napi_value sn_crypto_onetimeauth_init (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_onetimeauth_init) + + SN_ARGV_BUFFER_CAST(crypto_onetimeauth_state *, state, 0) + SN_ARGV_TYPEDARRAY(k, 1) + + SN_THROWS(state_size != sizeof(crypto_onetimeauth_state), "state must be 'crypto_onetimeauth_STATEBYTES' bytes") + SN_ASSERT_LENGTH(k_size, crypto_onetimeauth_KEYBYTES, "k") + + SN_RETURN(crypto_onetimeauth_init(state, k_data), "failed to initialise onetime authentication") +} + +napi_value sn_crypto_onetimeauth_update(napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_onetimeauth_update) + + SN_ARGV_BUFFER_CAST(crypto_onetimeauth_state *, state, 0) + SN_ARGV_TYPEDARRAY(in, 1) + + SN_THROWS(state_size != sizeof(crypto_onetimeauth_state), "state must be 'crypto_onetimeauth_STATEBYTES' bytes") + + SN_RETURN(crypto_onetimeauth_update(state, in_data, in_size), "update failed") +} + +napi_value sn_crypto_onetimeauth_final(napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_onetimeauth_final) + + SN_ARGV_BUFFER_CAST(crypto_onetimeauth_state *, state, 0) + SN_ARGV_TYPEDARRAY(out, 1) + + SN_THROWS(state_size != sizeof(crypto_onetimeauth_state), "state must be 'crypto_onetimeauth_STATEBYTES' bytes") + SN_ASSERT_LENGTH(out_size, crypto_onetimeauth_BYTES, "out") + + SN_RETURN(crypto_onetimeauth_final(state, out_data), "failed to generate authentication tag") +} + +napi_value sn_crypto_onetimeauth_verify (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_onetimeauth_verify) + + SN_ARGV_TYPEDARRAY(h, 0) + SN_ARGV_TYPEDARRAY(in, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_ASSERT_LENGTH(h_size, crypto_onetimeauth_BYTES, "h") + SN_ASSERT_LENGTH(k_size, crypto_onetimeauth_KEYBYTES, "k") + + SN_RETURN_BOOLEAN(crypto_onetimeauth_verify(h_data, in_data, in_size, k_data)) +} + +// CHECK: memlimit can be >32bit +napi_value sn_crypto_pwhash (napi_env env, napi_callback_info info) { + SN_ARGV(6, crypto_pwhash) + + SN_ARGV_TYPEDARRAY(out, 0) + SN_ARGV_TYPEDARRAY(passwd, 1) + SN_ARGV_TYPEDARRAY(salt, 2) + SN_ARGV_UINT64(opslimit, 3) + SN_ARGV_UINT64(memlimit, 4) + SN_ARGV_UINT8(alg, 5) + + SN_ASSERT_MIN_LENGTH(out_size, crypto_pwhash_BYTES_MIN, "out") + SN_ASSERT_MAX_LENGTH(out_size, crypto_pwhash_BYTES_MAX, "out") + SN_ASSERT_LENGTH(salt_size, crypto_pwhash_SALTBYTES, "salt") + SN_ASSERT_MIN_LENGTH(opslimit, crypto_pwhash_OPSLIMIT_MIN, "opslimit") + SN_ASSERT_MAX_LENGTH(opslimit, crypto_pwhash_OPSLIMIT_MAX, "opslimit") + SN_ASSERT_MIN_LENGTH(memlimit, crypto_pwhash_MEMLIMIT_MIN, "memlimit") + SN_ASSERT_MAX_LENGTH(memlimit, (int64_t) crypto_pwhash_MEMLIMIT_MAX, "memlimit") + SN_THROWS(alg < 1 || alg > 2, "alg must be either Argon2i 1.3 or Argon2id 1.3") + + SN_RETURN(crypto_pwhash(out_data, out_size, passwd_data, passwd_size, salt_data, opslimit, memlimit, alg), "password hashing failed, check memory requirements.") +} + +napi_value sn_crypto_pwhash_str (napi_env env, napi_callback_info info) { + SN_ARGV(4, crypto_pwhash_str) + + SN_ARGV_TYPEDARRAY(out, 0) + SN_ARGV_TYPEDARRAY(passwd, 1) + SN_ARGV_UINT64(opslimit, 2) + SN_ARGV_UINT64(memlimit, 3) + + SN_ASSERT_LENGTH(out_size, crypto_pwhash_STRBYTES, "out") + SN_ASSERT_MIN_LENGTH(opslimit, crypto_pwhash_OPSLIMIT_MIN, "opslimit") + SN_ASSERT_MAX_LENGTH(opslimit, crypto_pwhash_OPSLIMIT_MAX, "opslimit") + SN_ASSERT_MIN_LENGTH(memlimit, crypto_pwhash_MEMLIMIT_MIN, "memlimit") + SN_ASSERT_MAX_LENGTH(memlimit, (int64_t) crypto_pwhash_MEMLIMIT_MAX, "memlimit") + + SN_RETURN(crypto_pwhash_str(out_data, passwd_data, passwd_size, opslimit, memlimit), "password hashing failed, check memory requirements.") +} + +napi_value sn_crypto_pwhash_str_verify (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_pwhash_str_verify) + + SN_ARGV_TYPEDARRAY(str, 0) + SN_ARGV_TYPEDARRAY(passwd, 1) + + SN_ASSERT_LENGTH(str_size, crypto_pwhash_STRBYTES, "str") + + SN_RETURN_BOOLEAN(crypto_pwhash_str_verify(str_data, passwd_data, passwd_size)) +} + +// CHECK: returns 1, 0, -1 +napi_value sn_crypto_pwhash_str_needs_rehash (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_pwhash_str_needs_rehash) + + SN_ARGV_TYPEDARRAY(str, 0) + SN_ARGV_UINT64(opslimit, 1) + SN_ARGV_UINT64(memlimit, 2) + + SN_ASSERT_LENGTH(str_size, crypto_pwhash_STRBYTES, "str") + SN_ASSERT_MIN_LENGTH(opslimit, crypto_pwhash_OPSLIMIT_MIN, "opslimit") + SN_ASSERT_MAX_LENGTH(opslimit, crypto_pwhash_OPSLIMIT_MAX, "opslimit") + SN_ASSERT_MIN_LENGTH(memlimit, crypto_pwhash_MEMLIMIT_MIN, "memlimit") + SN_ASSERT_MAX_LENGTH(memlimit, (int64_t) crypto_pwhash_MEMLIMIT_MAX, "memlimit") + + SN_RETURN_BOOLEAN_FROM_1(crypto_pwhash_str_needs_rehash(str_data, opslimit, memlimit)) +} + +// CHECK: memlimit can be >32bit +napi_value sn_crypto_pwhash_scryptsalsa208sha256 (napi_env env, napi_callback_info info) { + SN_ARGV(5, crypto_pwhash_scryptsalsa208sha256) + + SN_ARGV_TYPEDARRAY(out, 0) + SN_ARGV_TYPEDARRAY(passwd, 1) + SN_ARGV_TYPEDARRAY(salt, 2) + SN_ARGV_UINT64(opslimit, 3) + SN_ARGV_UINT64(memlimit, 4) + + SN_ASSERT_MIN_LENGTH(out_size, crypto_pwhash_scryptsalsa208sha256_BYTES_MIN, "out") + SN_ASSERT_MAX_LENGTH(out_size, crypto_pwhash_scryptsalsa208sha256_BYTES_MAX, "out") + SN_ASSERT_LENGTH(salt_size, crypto_pwhash_scryptsalsa208sha256_SALTBYTES, "salt") + SN_ASSERT_MIN_LENGTH(opslimit, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN, "opslimit") + SN_ASSERT_MAX_LENGTH(opslimit, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX, "opslimit") + SN_ASSERT_MIN_LENGTH(memlimit, crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN, "memlimit") + SN_ASSERT_MAX_LENGTH(memlimit, (int64_t) crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX, "memlimit") + + SN_RETURN(crypto_pwhash_scryptsalsa208sha256(out_data, out_size, passwd_data, passwd_size, salt_data, opslimit, memlimit), "password hashing failed, check memory requirements.") +} + +napi_value sn_crypto_pwhash_scryptsalsa208sha256_str (napi_env env, napi_callback_info info) { + SN_ARGV(4, crypto_pwhash_scryptsalsa208sha256_str) + + SN_ARGV_TYPEDARRAY(out, 0) + SN_ARGV_TYPEDARRAY(passwd, 1) + SN_ARGV_UINT64(opslimit, 2) + SN_ARGV_UINT64(memlimit, 3) + + SN_ASSERT_LENGTH(out_size, crypto_pwhash_scryptsalsa208sha256_STRBYTES, "out") + SN_ASSERT_MIN_LENGTH(opslimit, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN, "opslimit") + SN_ASSERT_MAX_LENGTH(opslimit, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX, "opslimit") + SN_ASSERT_MIN_LENGTH(memlimit, crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN, "memlimit") + SN_ASSERT_MAX_LENGTH(memlimit, (int64_t) crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX, "memlimit") + + SN_RETURN(crypto_pwhash_scryptsalsa208sha256_str(out_data, passwd_data, passwd_size, opslimit, memlimit), "password hashing failed, check memory requirements.") +} + +napi_value sn_crypto_pwhash_scryptsalsa208sha256_str_verify (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_pwhash_scryptsalsa208sha256_str_verify) + + SN_ARGV_TYPEDARRAY(str, 0) + SN_ARGV_TYPEDARRAY(passwd, 1) + + SN_ASSERT_LENGTH(str_size, crypto_pwhash_scryptsalsa208sha256_STRBYTES, "str") + + SN_RETURN_BOOLEAN(crypto_pwhash_scryptsalsa208sha256_str_verify(str_data, passwd_data, passwd_size)) +} + +napi_value sn_crypto_pwhash_scryptsalsa208sha256_str_needs_rehash (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_pwhash_scryptsalsa208sha256_str_needs_rehash) + + SN_ARGV_TYPEDARRAY(str, 0) + SN_ARGV_UINT64(opslimit, 1) + SN_ARGV_UINT64(memlimit, 2) + + SN_ASSERT_LENGTH(str_size, crypto_pwhash_scryptsalsa208sha256_STRBYTES, "str") + SN_ASSERT_MIN_LENGTH(opslimit, crypto_pwhash_OPSLIMIT_MIN, "opslimit") + SN_ASSERT_MAX_LENGTH(opslimit, crypto_pwhash_OPSLIMIT_MAX, "opslimit") + SN_ASSERT_MIN_LENGTH(memlimit, crypto_pwhash_MEMLIMIT_MIN, "memlimit") + SN_ASSERT_MAX_LENGTH(memlimit, (int64_t) crypto_pwhash_MEMLIMIT_MAX, "memlimit") + + SN_RETURN_BOOLEAN_FROM_1(crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str_data, opslimit, memlimit)) +} + +napi_value sn_crypto_kx_keypair (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_kx_keypair) + + SN_ARGV_TYPEDARRAY(pk, 0) + SN_ARGV_TYPEDARRAY(sk, 1) + + SN_ASSERT_LENGTH(pk_size, crypto_kx_PUBLICKEYBYTES, "pk") + SN_ASSERT_LENGTH(sk_size, crypto_kx_SECRETKEYBYTES, "sk") + + SN_RETURN(crypto_kx_keypair(pk_data, sk_data), "failed to generate keypair") +} + +napi_value sn_crypto_kx_seed_keypair (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_kx_seed_keypair) + + SN_ARGV_TYPEDARRAY(pk, 0) + SN_ARGV_TYPEDARRAY(sk, 1) + SN_ARGV_TYPEDARRAY(seed, 2) + + SN_ASSERT_LENGTH(pk_size, crypto_kx_PUBLICKEYBYTES, "pk") + SN_ASSERT_LENGTH(sk_size, crypto_kx_SECRETKEYBYTES, "sk") + SN_ASSERT_LENGTH(seed_size, crypto_kx_SEEDBYTES, "seed") + + SN_RETURN(crypto_kx_seed_keypair(pk_data, sk_data, seed_data), "failed to derive keypair from seed") +} + +napi_value sn_crypto_kx_client_session_keys (napi_env env, napi_callback_info info) { + SN_ARGV(5, crypto_kx_client_session_keys) + + SN_ARGV_OPTS_TYPEDARRAY(rx, 0) + SN_ARGV_OPTS_TYPEDARRAY(tx, 1) + + SN_THROWS(rx_data == NULL && tx_data == NULL, "at least one session key must be specified") + + SN_ARGV_TYPEDARRAY(client_pk, 2) + SN_ARGV_TYPEDARRAY(client_sk, 3) + SN_ARGV_TYPEDARRAY(server_pk, 4) + + SN_ASSERT_LENGTH(client_pk_size, crypto_kx_PUBLICKEYBYTES, "client_pk") + SN_ASSERT_LENGTH(client_sk_size, crypto_kx_SECRETKEYBYTES, "client_sk") + SN_ASSERT_LENGTH(server_pk_size, crypto_kx_PUBLICKEYBYTES, "server_pk") + + SN_THROWS(tx_size != crypto_kx_SESSIONKEYBYTES && tx_data != NULL, "transmitting key buffer must be 'crypto_kx_SESSIONKEYBYTES' bytes or null") + SN_THROWS(rx_size != crypto_kx_SESSIONKEYBYTES && rx_data != NULL, "receiving key buffer must be 'crypto_kx_SESSIONKEYBYTES' bytes or null") + + SN_RETURN(crypto_kx_client_session_keys(rx_data, tx_data, client_pk_data, client_sk_data, server_pk_data), "failed to derive session keys") +} + +napi_value sn_crypto_kx_server_session_keys (napi_env env, napi_callback_info info) { + SN_ARGV(5, crypto_kx_server_session_keys) + + SN_ARGV_OPTS_TYPEDARRAY(rx, 0) + SN_ARGV_OPTS_TYPEDARRAY(tx, 1) + + SN_THROWS(rx_data == NULL && tx_data == NULL, "at least one session key must be specified") + + SN_ARGV_TYPEDARRAY(server_pk, 2) + SN_ARGV_TYPEDARRAY(server_sk, 3) + SN_ARGV_TYPEDARRAY(client_pk, 4) + + SN_ASSERT_LENGTH(server_pk_size, crypto_kx_PUBLICKEYBYTES, "server_pk") + SN_ASSERT_LENGTH(server_sk_size, crypto_kx_SECRETKEYBYTES, "server_sk") + SN_ASSERT_LENGTH(client_pk_size, crypto_kx_PUBLICKEYBYTES, "client_pk") + + SN_THROWS(tx_size != crypto_kx_SESSIONKEYBYTES && tx_data != NULL, "transmitting key buffer must be 'crypto_kx_SESSIONKEYBYTES' bytes or null") + SN_THROWS(rx_size != crypto_kx_SESSIONKEYBYTES && rx_data != NULL, "receiving key buffer must be 'crypto_kx_SESSIONKEYBYTES' bytes or null") + + SN_RETURN(crypto_kx_server_session_keys(rx_data, tx_data, server_pk_data, server_sk_data, client_pk_data), "failed to derive session keys") +} + +napi_value sn_crypto_scalarmult_base (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_scalarmult_base) + + SN_ARGV_TYPEDARRAY(q, 0) + SN_ARGV_TYPEDARRAY(n, 1) + + SN_ASSERT_LENGTH(q_size, crypto_scalarmult_BYTES, "q") + SN_ASSERT_LENGTH(n_size, crypto_scalarmult_SCALARBYTES, "n") + + SN_RETURN(crypto_scalarmult_base(q_data, n_data), "failed to derive public key") +} + +napi_value sn_crypto_scalarmult (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_scalarmult) + + SN_ARGV_TYPEDARRAY(q, 0) + SN_ARGV_TYPEDARRAY(n, 1) + SN_ARGV_TYPEDARRAY(p, 2) + + SN_ASSERT_LENGTH(q_size, crypto_scalarmult_BYTES, "q") + SN_ASSERT_LENGTH(n_size, crypto_scalarmult_SCALARBYTES, "n") + SN_ASSERT_LENGTH(p_size, crypto_scalarmult_BYTES, "p") + + SN_RETURN(crypto_scalarmult(q_data, n_data, p_data), "failed to derive shared secret") +} + +napi_value sn_crypto_scalarmult_ed25519_base (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_scalarmult_ed25519_base) + + SN_ARGV_TYPEDARRAY(q, 0) + SN_ARGV_TYPEDARRAY(n, 1) + + SN_ASSERT_LENGTH(q_size, crypto_scalarmult_ed25519_BYTES, "q") + SN_ASSERT_LENGTH(n_size, crypto_scalarmult_ed25519_SCALARBYTES, "n") + + SN_RETURN(crypto_scalarmult_ed25519_base(q_data, n_data), "failed to derive public key") +} + +napi_value sn_crypto_scalarmult_ed25519 (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_scalarmult_ed25519) + + SN_ARGV_TYPEDARRAY(q, 0) + SN_ARGV_TYPEDARRAY(n, 1) + SN_ARGV_TYPEDARRAY(p, 2) + + SN_ASSERT_LENGTH(q_size, crypto_scalarmult_ed25519_BYTES, "q") + SN_ASSERT_LENGTH(n_size, crypto_scalarmult_ed25519_SCALARBYTES, "n") + SN_ASSERT_LENGTH(p_size, crypto_scalarmult_ed25519_BYTES, "p") + + SN_RETURN(crypto_scalarmult_ed25519(q_data, n_data, p_data), "failed to derive shared secret") +} + +napi_value sn_crypto_core_ed25519_is_valid_point (napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_core_ed25519_is_valid_point) + + SN_ARGV_TYPEDARRAY(p, 0) + + SN_ASSERT_LENGTH(p_size, crypto_core_ed25519_BYTES, "p") + + SN_RETURN_BOOLEAN_FROM_1(crypto_core_ed25519_is_valid_point(p_data)) +} + +napi_value sn_crypto_core_ed25519_from_uniform (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_core_ed25519_from_uniform) + + SN_ARGV_TYPEDARRAY(p, 0) + SN_ARGV_TYPEDARRAY(r, 1) + + SN_ASSERT_LENGTH(p_size, crypto_core_ed25519_BYTES, "p") + SN_ASSERT_LENGTH(r_size, crypto_core_ed25519_UNIFORMBYTES, "r") + + SN_RETURN(crypto_core_ed25519_from_uniform(p_data, r_data), "could not generate curve point from input") +} + +napi_value sn_crypto_scalarmult_ed25519_base_noclamp (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_scalarmult_ed25519_base_noclamp) + + SN_ARGV_TYPEDARRAY(q, 0) + SN_ARGV_TYPEDARRAY(n, 1) + + SN_ASSERT_LENGTH(q_size, crypto_scalarmult_ed25519_BYTES, "q") + SN_ASSERT_LENGTH(n_size, crypto_scalarmult_ed25519_SCALARBYTES, "n") + + SN_RETURN(crypto_scalarmult_ed25519_base_noclamp(q_data, n_data), "failed to derive public key") +} + +napi_value sn_crypto_scalarmult_ed25519_noclamp (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_scalarmult_ed25519_noclamp) + + SN_ARGV_TYPEDARRAY(q, 0) + SN_ARGV_TYPEDARRAY(n, 1) + SN_ARGV_TYPEDARRAY(p, 2) + + SN_ASSERT_LENGTH(q_size, crypto_scalarmult_ed25519_BYTES, "q") + SN_ASSERT_LENGTH(n_size, crypto_scalarmult_ed25519_SCALARBYTES, "n") + SN_ASSERT_LENGTH(p_size, crypto_scalarmult_ed25519_BYTES, "p") + + SN_RETURN(crypto_scalarmult_ed25519_noclamp(q_data, n_data, p_data), "failed to derive shared secret") +} + +napi_value sn_crypto_core_ed25519_add (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_core_ed25519_add) + + SN_ARGV_TYPEDARRAY(r, 0) + SN_ARGV_TYPEDARRAY(p, 1) + SN_ARGV_TYPEDARRAY(q, 2) + + SN_ASSERT_LENGTH(r_size, crypto_core_ed25519_BYTES, "r") + SN_ASSERT_LENGTH(p_size, crypto_core_ed25519_BYTES, "p") + SN_ASSERT_LENGTH(q_size, crypto_core_ed25519_BYTES, "q") + + SN_RETURN(crypto_core_ed25519_add(r_data, p_data, q_data), "could not add curve points") +} + +napi_value sn_crypto_core_ed25519_sub (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_core_ed25519_sub) + + SN_ARGV_TYPEDARRAY(r, 0) + SN_ARGV_TYPEDARRAY(p, 1) + SN_ARGV_TYPEDARRAY(q, 2) + + SN_ASSERT_LENGTH(r_size, crypto_core_ed25519_BYTES, "r") + SN_ASSERT_LENGTH(p_size, crypto_core_ed25519_BYTES, "p") + SN_ASSERT_LENGTH(q_size, crypto_core_ed25519_BYTES, "q") + + SN_RETURN(crypto_core_ed25519_sub(r_data, p_data, q_data), "could not add curve points") +} + +napi_value sn_crypto_core_ed25519_scalar_random (napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_core_ed25519_scalar_random) + + SN_ARGV_TYPEDARRAY(r, 0) + + SN_ASSERT_LENGTH(r_size, crypto_core_ed25519_SCALARBYTES, "r") + + crypto_core_ed25519_scalar_random(r_data); + + return NULL; +} + +napi_value sn_crypto_core_ed25519_scalar_reduce (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_core_ed25519_scalar_reduce) + + SN_ARGV_TYPEDARRAY(r, 0) + SN_ARGV_TYPEDARRAY(s, 1) + + SN_ASSERT_LENGTH(r_size, crypto_core_ed25519_SCALARBYTES, "r") + SN_ASSERT_LENGTH(s_size, crypto_core_ed25519_NONREDUCEDSCALARBYTES, "s") + + crypto_core_ed25519_scalar_reduce(r_data, s_data); + + return NULL; +} + +napi_value sn_crypto_core_ed25519_scalar_invert (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_core_ed25519_scalar_invert) + + SN_ARGV_TYPEDARRAY(recip, 0) + SN_ARGV_TYPEDARRAY(s, 1) + + SN_ASSERT_LENGTH(recip_size, crypto_core_ed25519_SCALARBYTES, "recip") + SN_ASSERT_LENGTH(s_size, crypto_core_ed25519_SCALARBYTES, "s") + + crypto_core_ed25519_scalar_invert(recip_data, s_data); + + return NULL; +} + +napi_value sn_crypto_core_ed25519_scalar_negate (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_core_ed25519_scalar_negate) + + SN_ARGV_TYPEDARRAY(neg, 0) + SN_ARGV_TYPEDARRAY(s, 1) + + SN_ASSERT_LENGTH(neg_size, crypto_core_ed25519_SCALARBYTES, "neg") + SN_ASSERT_LENGTH(s_size, crypto_core_ed25519_SCALARBYTES, "s") + + crypto_core_ed25519_scalar_negate(neg_data, s_data); + + return NULL; +} + +napi_value sn_crypto_core_ed25519_scalar_complement (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_core_ed25519_scalar_complement) + + SN_ARGV_TYPEDARRAY(comp, 0) + SN_ARGV_TYPEDARRAY(s, 1) + + SN_ASSERT_LENGTH(comp_size, crypto_core_ed25519_SCALARBYTES, "comp") + SN_ASSERT_LENGTH(s_size, crypto_core_ed25519_SCALARBYTES, "s") + + crypto_core_ed25519_scalar_complement(comp_data, s_data); + + return NULL; +} + +napi_value sn_crypto_core_ed25519_scalar_add (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_core_ed25519_scalar_add) + + SN_ARGV_TYPEDARRAY(z, 0) + SN_ARGV_TYPEDARRAY(x, 1) + SN_ARGV_TYPEDARRAY(y, 2) + + SN_ASSERT_LENGTH(z_size, crypto_core_ed25519_SCALARBYTES, "z") + SN_ASSERT_LENGTH(x_size, crypto_core_ed25519_SCALARBYTES, "x") + SN_ASSERT_LENGTH(y_size, crypto_core_ed25519_SCALARBYTES, "y") + + crypto_core_ed25519_scalar_add(z_data, x_data, y_data); + + return NULL; +} + +napi_value sn_crypto_core_ed25519_scalar_sub (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_core_ed25519_scalar_sub) + + SN_ARGV_TYPEDARRAY(z, 0) + SN_ARGV_TYPEDARRAY(x, 1) + SN_ARGV_TYPEDARRAY(y, 2) + + SN_ASSERT_LENGTH(z_size, crypto_core_ed25519_SCALARBYTES, "z") + SN_ASSERT_LENGTH(x_size, crypto_core_ed25519_SCALARBYTES, "x") + SN_ASSERT_LENGTH(y_size, crypto_core_ed25519_SCALARBYTES, "y") + + crypto_core_ed25519_scalar_sub(z_data, x_data, y_data); + + return NULL; +} + +napi_value sn_crypto_shorthash (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_shorthash) + + SN_ARGV_TYPEDARRAY(out, 0) + SN_ARGV_TYPEDARRAY(in, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_ASSERT_LENGTH(out_size, crypto_shorthash_BYTES, "out") + SN_ASSERT_LENGTH(k_size, crypto_shorthash_KEYBYTES, "k") + + SN_RETURN(crypto_shorthash(out_data, in_data, in_size, k_data), "could not compute hash") +} + +napi_value sn_crypto_kdf_keygen (napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_kdf_keygen) + + SN_ARGV_TYPEDARRAY(key, 0) + + SN_ASSERT_LENGTH(key_size, crypto_kdf_KEYBYTES, "key") + + crypto_kdf_keygen(key_data); + + return NULL; +} + +napi_value sn_crypto_kdf_derive_from_key (napi_env env, napi_callback_info info) { + SN_ARGV(4, crypto_kdf_derive_from_key) + + SN_ARGV_TYPEDARRAY(subkey, 0) + SN_ARGV_UINT64(subkey_id, 1) + SN_ARGV_TYPEDARRAY(ctx, 2) + SN_ARGV_TYPEDARRAY(key, 3) + + SN_ASSERT_MIN_LENGTH(subkey_size, crypto_kdf_BYTES_MIN, "subkey") + SN_ASSERT_MAX_LENGTH(subkey_size, crypto_kdf_BYTES_MAX, "subkey") + SN_ASSERT_LENGTH(ctx_size, crypto_kdf_CONTEXTBYTES, "ctx") + SN_ASSERT_LENGTH(key_size, crypto_kdf_KEYBYTES, "key") + + SN_RETURN(crypto_kdf_derive_from_key(subkey_data, subkey_size, subkey_id, ctx_data, key_data), "could not generate key") +} + +napi_value sn_crypto_hash (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_hash_sha256) + + SN_ARGV_TYPEDARRAY(out, 0) + SN_ARGV_TYPEDARRAY(in, 1) + + SN_ASSERT_LENGTH(out_size, crypto_hash_BYTES, "out") + + SN_RETURN(crypto_hash(out_data, in_data, in_size), "could not compute hash") +} + +napi_value sn_crypto_hash_sha256 (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_hash_sha256) + + SN_ARGV_TYPEDARRAY(out, 0) + SN_ARGV_TYPEDARRAY(in, 1) + + SN_ASSERT_LENGTH(out_size, crypto_hash_sha256_BYTES, "out") + + SN_RETURN(crypto_hash_sha256(out_data, in_data, in_size), "could not compute hash") +} + +napi_value sn_crypto_hash_sha256_init (napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_hash_sha256_init) + + SN_ARGV_BUFFER_CAST(crypto_hash_sha256_state *, state, 0) + + SN_THROWS(state_size != sizeof(crypto_hash_sha256_state), "state must be 'crypto_hash_sha256_STATEBYTES' bytes") + + SN_RETURN(crypto_hash_sha256_init(state), "failed to initialise sha256") +} + +napi_value sn_crypto_hash_sha256_update(napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_hash_sha256_update) + + SN_ARGV_BUFFER_CAST(crypto_hash_sha256_state *, state, 0) + SN_ARGV_TYPEDARRAY(in, 1) + + SN_THROWS(state_size != sizeof(crypto_hash_sha256_state), "state must be 'crypto_hash_sha256_STATEBYTES' bytes") + + SN_RETURN(crypto_hash_sha256_update(state, in_data, in_size), "update failed") +} + +napi_value sn_crypto_hash_sha256_final(napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_hash_sha256_final) + + SN_ARGV_BUFFER_CAST(crypto_hash_sha256_state *, state, 0) + SN_ARGV_TYPEDARRAY(out, 1) + + SN_THROWS(state_size != sizeof(crypto_hash_sha256_state), "state must be 'crypto_hash_sha256_STATEBYTES' bytes") + SN_ASSERT_LENGTH(out_size, crypto_hash_sha256_BYTES, "state") + + SN_RETURN(crypto_hash_sha256_final(state, out_data), "failed to finalise") +} + +napi_value sn_crypto_hash_sha512 (napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_hash_sha512) + + SN_ARGV_TYPEDARRAY(out, 0) + SN_ARGV_TYPEDARRAY(in, 1) + + SN_ASSERT_LENGTH(out_size, crypto_hash_sha512_BYTES, "out") + + SN_RETURN(crypto_hash_sha512(out_data, in_data, in_size), "could not compute hash") +} + +napi_value sn_crypto_hash_sha512_init (napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_hash_sha512_init) + + SN_ARGV_BUFFER_CAST(crypto_hash_sha512_state *, state, 0) + + SN_THROWS(state_size != sizeof(crypto_hash_sha512_state), "state must be 'crypto_hash_sha256_STATEBYTES' bytes") + + SN_RETURN(crypto_hash_sha512_init(state), "failed to initialise sha512") +} + +napi_value sn_crypto_hash_sha512_update(napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_hash_sha512_update) + + SN_ARGV_BUFFER_CAST(crypto_hash_sha512_state *, state, 0) + SN_ARGV_TYPEDARRAY(in, 1) + + SN_THROWS(state_size != sizeof(crypto_hash_sha512_state), "state must be 'crypto_hash_sha256_STATEBYTES' bytes") + + SN_RETURN(crypto_hash_sha512_update(state, in_data, in_size), "update failed") +} + +napi_value sn_crypto_hash_sha512_final(napi_env env, napi_callback_info info) { + SN_ARGV(2, crypto_hash_sha512_final) + + SN_ARGV_BUFFER_CAST(crypto_hash_sha512_state *, state, 0) + SN_ARGV_TYPEDARRAY(out, 1) + + SN_THROWS(state_size != sizeof(crypto_hash_sha512_state), "state must be 'crypto_hash_sha256_STATEBYTES' bytes") + SN_ASSERT_LENGTH(out_size, crypto_hash_sha512_BYTES, "out") + + SN_RETURN(crypto_hash_sha512_final(state, out_data), "failed to finalise hash") +} + +napi_value sn_crypto_aead_xchacha20poly1305_ietf_keygen (napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_aead_xchacha20poly1305_ietf_keygen) + + SN_ARGV_TYPEDARRAY(k, 0) + + SN_ASSERT_LENGTH(k_size, crypto_aead_xchacha20poly1305_ietf_KEYBYTES, "k") + + crypto_aead_xchacha20poly1305_ietf_keygen(k_data); + return NULL; +} + +napi_value sn_crypto_aead_xchacha20poly1305_ietf_encrypt (napi_env env, napi_callback_info info) { + SN_ARGV(6, crypto_aead_xchacha20poly1305_ietf_encrypt) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_OPTS_TYPEDARRAY(ad, 2) + SN_ARGV_CHECK_NULL(nsec, 3) + SN_ARGV_TYPEDARRAY(npub, 4) + SN_ARGV_TYPEDARRAY(k, 5) + + SN_THROWS(!nsec_is_null, "nsec must always be set to null") + + SN_THROWS(c_size != m_size + crypto_aead_xchacha20poly1305_ietf_ABYTES, "c must 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes") + SN_THROWS(c_size > 0xffffffff, "c.byteLength must be a 32bit integer") + SN_ASSERT_LENGTH(npub_size, crypto_aead_xchacha20poly1305_ietf_NPUBBYTES, "npub") + SN_ASSERT_LENGTH(k_size, crypto_aead_xchacha20poly1305_ietf_KEYBYTES, "k") + + unsigned long long clen; + SN_CALL(crypto_aead_xchacha20poly1305_ietf_encrypt(c_data, &clen, m_data, m_size, ad_data, ad_size, NULL, npub_data, k_data), "could not encrypt data") + + napi_value result; + SN_STATUS_THROWS(napi_create_uint32(env, (uint32_t) clen, &result), "") + return result; +} + +napi_value sn_crypto_aead_xchacha20poly1305_ietf_decrypt (napi_env env, napi_callback_info info) { + SN_ARGV(6, crypto_aead_xchacha20poly1305_ietf_decrypt) + + SN_ARGV_TYPEDARRAY(m, 0) + SN_ARGV_CHECK_NULL(nsec, 1) + SN_ARGV_TYPEDARRAY(c, 2) + SN_ARGV_OPTS_TYPEDARRAY(ad, 3) + SN_ARGV_TYPEDARRAY(npub, 4) + SN_ARGV_TYPEDARRAY(k, 5) + + SN_THROWS(!nsec_is_null, "nsec must always be set to null") + + SN_THROWS(m_size != c_size - crypto_aead_xchacha20poly1305_ietf_ABYTES, "m must 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes") + SN_ASSERT_LENGTH(npub_size, crypto_aead_xchacha20poly1305_ietf_NPUBBYTES, "npub") + SN_ASSERT_LENGTH(k_size, crypto_aead_xchacha20poly1305_ietf_KEYBYTES, "k") + SN_THROWS(m_size > 0xffffffff, "m.byteLength must be a 32bit integer") + + unsigned long long mlen; + SN_CALL(crypto_aead_xchacha20poly1305_ietf_decrypt(m_data, &mlen, NULL, c_data, c_size, ad_data, ad_size, npub_data, k_data), "could not verify data") + + napi_value result; + SN_STATUS_THROWS(napi_create_uint32(env, (uint32_t) mlen, &result), "") + return result; +} + +napi_value sn_crypto_aead_xchacha20poly1305_ietf_encrypt_detached (napi_env env, napi_callback_info info) { + SN_ARGV(7, crypto_aead_xchacha20poly1305_ietf_encrypt_detached) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(mac, 1) + SN_ARGV_TYPEDARRAY(m, 2) + SN_ARGV_OPTS_TYPEDARRAY(ad, 3) + SN_ARGV_CHECK_NULL(nsec, 4) + SN_ARGV_TYPEDARRAY(npub, 5) + SN_ARGV_TYPEDARRAY(k, 6) + + SN_THROWS(!nsec_is_null, "nsec must always be set to null") + + SN_THROWS(c_size != m_size, "c must be 'm.byteLength' bytes") + SN_ASSERT_LENGTH(mac_size, crypto_aead_xchacha20poly1305_ietf_ABYTES, "mac") + SN_ASSERT_LENGTH(npub_size, crypto_aead_xchacha20poly1305_ietf_NPUBBYTES, "npub") + SN_ASSERT_LENGTH(k_size, crypto_aead_xchacha20poly1305_ietf_KEYBYTES, "k") + + unsigned long long maclen; + SN_CALL(crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c_data, mac_data, &maclen, m_data, m_size, ad_data, ad_size, NULL, npub_data, k_data), "could not encrypt data") + + napi_value result; + SN_STATUS_THROWS(napi_create_uint32(env, (uint32_t) maclen, &result), "") + return result; +} + +napi_value sn_crypto_aead_xchacha20poly1305_ietf_decrypt_detached (napi_env env, napi_callback_info info) { + SN_ARGV(7, crypto_aead_xchacha20poly1305_ietf_decrypt_detached) + + SN_ARGV_TYPEDARRAY(m, 0) + SN_ARGV_CHECK_NULL(nsec, 1) + SN_ARGV_TYPEDARRAY(c, 2) + SN_ARGV_TYPEDARRAY(mac, 3) + SN_ARGV_OPTS_TYPEDARRAY(ad, 4) + SN_ARGV_TYPEDARRAY(npub, 5) + SN_ARGV_TYPEDARRAY(k, 6) + + SN_THROWS(!nsec_is_null, "nsec must always be set to null") + + SN_THROWS(m_size != c_size, "m must be 'c.byteLength' bytes") + SN_ASSERT_LENGTH(mac_size, crypto_aead_xchacha20poly1305_ietf_ABYTES, "mac") + SN_ASSERT_LENGTH(npub_size, crypto_aead_xchacha20poly1305_ietf_NPUBBYTES, "npub") + SN_ASSERT_LENGTH(k_size, crypto_aead_xchacha20poly1305_ietf_KEYBYTES, "k") + + SN_RETURN(crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m_data, NULL, c_data, c_size, mac_data, ad_data, ad_size, npub_data, k_data), "could not verify data") +} + +napi_value sn_crypto_aead_chacha20poly1305_ietf_keygen (napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_aead_chacha20poly1305_ietf_keygen) + + SN_ARGV_TYPEDARRAY(k, 0) + + SN_ASSERT_LENGTH(k_size, crypto_aead_chacha20poly1305_ietf_KEYBYTES, "k") + + crypto_aead_chacha20poly1305_ietf_keygen(k_data); + return NULL; +} + +napi_value sn_crypto_aead_chacha20poly1305_ietf_encrypt (napi_env env, napi_callback_info info) { + SN_ARGV(6, crypto_aead_chacha20poly1305_ietf_encrypt) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_OPTS_TYPEDARRAY(ad, 2) + SN_ARGV_CHECK_NULL(nsec, 3) + SN_ARGV_TYPEDARRAY(npub, 4) + SN_ARGV_TYPEDARRAY(k, 5) + + SN_THROWS(!nsec_is_null, "nsec must always be set to null") + + SN_THROWS(c_size != m_size + crypto_aead_chacha20poly1305_ietf_ABYTES, "c must 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes") + SN_THROWS(c_size > 0xffffffff, "c.byteLength must be a 32bit integer") + SN_ASSERT_LENGTH(npub_size, crypto_aead_chacha20poly1305_ietf_NPUBBYTES, "npub") + SN_ASSERT_LENGTH(k_size, crypto_aead_chacha20poly1305_ietf_KEYBYTES, "k") + + unsigned long long clen; + SN_CALL(crypto_aead_chacha20poly1305_ietf_encrypt(c_data, &clen, m_data, m_size, ad_data, ad_size, NULL, npub_data, k_data), "could not encrypt data") + + napi_value result; + SN_STATUS_THROWS(napi_create_uint32(env, (uint32_t) clen, &result), "") + return result; +} + +napi_value sn_crypto_aead_chacha20poly1305_ietf_decrypt (napi_env env, napi_callback_info info) { + SN_ARGV(6, crypto_aead_chacha20poly1305_ietf_decrypt) + + SN_ARGV_TYPEDARRAY(m, 0) + SN_ARGV_CHECK_NULL(nsec, 1) + SN_ARGV_TYPEDARRAY(c, 2) + SN_ARGV_OPTS_TYPEDARRAY(ad, 3) + SN_ARGV_TYPEDARRAY(npub, 4) + SN_ARGV_TYPEDARRAY(k, 5) + + SN_THROWS(!nsec_is_null, "nsec must always be set to null") + + SN_THROWS(m_size != c_size - crypto_aead_chacha20poly1305_ietf_ABYTES, "m must 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes") + SN_ASSERT_LENGTH(npub_size, crypto_aead_chacha20poly1305_ietf_NPUBBYTES, "npub") + SN_ASSERT_LENGTH(k_size, crypto_aead_chacha20poly1305_ietf_KEYBYTES, "k") + SN_THROWS(m_size > 0xffffffff, "m.byteLength must be a 32bit integer") + + unsigned long long mlen; + SN_CALL(crypto_aead_chacha20poly1305_ietf_decrypt(m_data, &mlen, NULL, c_data, c_size, ad_data, ad_size, npub_data, k_data), "could not verify data") + + napi_value result; + SN_STATUS_THROWS(napi_create_uint32(env, (uint32_t) mlen, &result), "") + return result; +} + +napi_value sn_crypto_aead_chacha20poly1305_ietf_encrypt_detached (napi_env env, napi_callback_info info) { + SN_ARGV(7, crypto_aead_chacha20poly1305_ietf_encrypt_detached) + + SN_ARGV_TYPEDARRAY(c, 0) + SN_ARGV_TYPEDARRAY(mac, 1) + SN_ARGV_TYPEDARRAY(m, 2) + SN_ARGV_OPTS_TYPEDARRAY(ad, 3) + SN_ARGV_CHECK_NULL(nsec, 4) + SN_ARGV_TYPEDARRAY(npub, 5) + SN_ARGV_TYPEDARRAY(k, 6) + + SN_THROWS(!nsec_is_null, "nsec must always be set to null") + + SN_THROWS(c_size != m_size, "c must be 'm.byteLength' bytes") + SN_ASSERT_LENGTH(mac_size, crypto_aead_chacha20poly1305_ietf_ABYTES, "mac") + SN_ASSERT_LENGTH(npub_size, crypto_aead_chacha20poly1305_ietf_NPUBBYTES, "npub") + SN_ASSERT_LENGTH(k_size, crypto_aead_chacha20poly1305_ietf_KEYBYTES, "k") + + unsigned long long maclen; + SN_CALL(crypto_aead_chacha20poly1305_ietf_encrypt_detached(c_data, mac_data, &maclen, m_data, m_size, ad_data, ad_size, NULL, npub_data, k_data), "could not encrypt data") + + napi_value result; + SN_STATUS_THROWS(napi_create_uint32(env, (uint32_t) maclen, &result), "") + return result; +} + +napi_value sn_crypto_aead_chacha20poly1305_ietf_decrypt_detached (napi_env env, napi_callback_info info) { + SN_ARGV(7, crypto_aead_chacha20poly1305_ietf_decrypt_detached) + + SN_ARGV_TYPEDARRAY(m, 0) + SN_ARGV_CHECK_NULL(nsec, 1) + SN_ARGV_TYPEDARRAY(c, 2) + SN_ARGV_TYPEDARRAY(mac, 3) + SN_ARGV_OPTS_TYPEDARRAY(ad, 4) + SN_ARGV_TYPEDARRAY(npub, 5) + SN_ARGV_TYPEDARRAY(k, 6) + + SN_THROWS(!nsec_is_null, "nsec must always be set to null") + + SN_THROWS(m_size != c_size, "m must be 'c.byteLength' bytes") + SN_ASSERT_LENGTH(mac_size, crypto_aead_chacha20poly1305_ietf_ABYTES, "mac") + SN_ASSERT_LENGTH(npub_size, crypto_aead_chacha20poly1305_ietf_NPUBBYTES, "npub") + SN_ASSERT_LENGTH(k_size, crypto_aead_chacha20poly1305_ietf_KEYBYTES, "k") + + SN_RETURN(crypto_aead_chacha20poly1305_ietf_decrypt_detached(m_data, NULL, c_data, c_size, mac_data, ad_data, ad_size, npub_data, k_data), "could not verify data") +} + +napi_value sn_crypto_secretstream_xchacha20poly1305_keygen (napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_secretstream_xchacha20poly1305_keygen) + + SN_ARGV_TYPEDARRAY(k, 0) + + SN_ASSERT_LENGTH(k_size, crypto_secretstream_xchacha20poly1305_KEYBYTES, "k") + + crypto_secretstream_xchacha20poly1305_keygen(k_data); + + return NULL; +} + +napi_value sn_crypto_secretstream_xchacha20poly1305_init_push (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_secretstream_xchacha20poly1305_init_push) + + SN_ARGV_BUFFER_CAST(crypto_secretstream_xchacha20poly1305_state *, state, 0) + SN_ARGV_TYPEDARRAY(header, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_THROWS(state_size != sizeof(crypto_secretstream_xchacha20poly1305_state), "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes") + SN_ASSERT_LENGTH(header_size, crypto_secretstream_xchacha20poly1305_HEADERBYTES, "header") + SN_ASSERT_LENGTH(k_size, crypto_secretstream_xchacha20poly1305_KEYBYTES, "k") + + SN_RETURN(crypto_secretstream_xchacha20poly1305_init_push(state, header_data, k_data), "initial push failed") +} + +napi_value sn_crypto_secretstream_xchacha20poly1305_push (napi_env env, napi_callback_info info) { + SN_ARGV(5, crypto_secretstream_xchacha20poly1305_push) + + SN_ARGV_BUFFER_CAST(crypto_secretstream_xchacha20poly1305_state *, state, 0) + SN_ARGV_TYPEDARRAY(c, 1) + SN_ARGV_TYPEDARRAY(m, 2) + SN_ARGV_OPTS_TYPEDARRAY(ad, 3) + SN_ARGV_UINT8(tag, 4) + + SN_THROWS(state_size != sizeof(crypto_secretstream_xchacha20poly1305_state), "state must be state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes") + SN_ASSERT_MAX_LENGTH(m_size, crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX, "m") + SN_THROWS(c_size != m_size + crypto_secretstream_xchacha20poly1305_ABYTES, "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes") + SN_THROWS(c_size > 0xffffffff, "c.byteLength must be a 32bit integer") + + unsigned long long clen; + SN_CALL(crypto_secretstream_xchacha20poly1305_push(state, c_data, &clen, m_data, m_size, ad_data, ad_size, tag), "push failed") + + napi_value result; + SN_STATUS_THROWS(napi_create_uint32(env, (uint32_t) clen, &result), "") + return result; +} + +napi_value sn_crypto_secretstream_xchacha20poly1305_init_pull (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_secretstream_xchacha20poly1305_init_pull) + + SN_ARGV_BUFFER_CAST(crypto_secretstream_xchacha20poly1305_state *, state, 0) + SN_ARGV_TYPEDARRAY(header, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_THROWS(state_size != sizeof(crypto_secretstream_xchacha20poly1305_state), "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes") + SN_ASSERT_LENGTH(header_size, crypto_secretstream_xchacha20poly1305_HEADERBYTES, "header") + SN_ASSERT_LENGTH(k_size, crypto_secretstream_xchacha20poly1305_KEYBYTES, "k") + + SN_RETURN(crypto_secretstream_xchacha20poly1305_init_pull(state, header_data, k_data), "initial pull failed") +} + +napi_value sn_crypto_secretstream_xchacha20poly1305_pull (napi_env env, napi_callback_info info) { + SN_ARGV(5, crypto_secretstream_xchacha20poly1305_pull) + + SN_ARGV_BUFFER_CAST(crypto_secretstream_xchacha20poly1305_state *, state, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(tag, 2) + SN_ARGV_TYPEDARRAY(c, 3) + SN_ARGV_OPTS_TYPEDARRAY(ad, 4) + + SN_THROWS(state_size != sizeof(crypto_secretstream_xchacha20poly1305_state), "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes") + SN_ASSERT_MIN_LENGTH(c_size, crypto_secretstream_xchacha20poly1305_ABYTES, "c") + SN_ASSERT_LENGTH(tag_size, 1, "tag") + SN_THROWS(m_size != c_size - crypto_secretstream_xchacha20poly1305_ABYTES, "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES") + SN_THROWS(m_size > 0xffffffff, "m.byteLength must be a 32bit integer") + + unsigned long long mlen; + SN_CALL(crypto_secretstream_xchacha20poly1305_pull(state, m_data, &mlen, tag_data, c_data, c_size, ad_data, ad_size), "pull failed") + + napi_value result; + SN_STATUS_THROWS(napi_create_uint32(env, (uint32_t) mlen, &result), "") + return result; +} + +napi_value sn_crypto_secretstream_xchacha20poly1305_rekey (napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_secretstream_xchacha20poly1305_rekey) + + SN_ARGV_BUFFER_CAST(crypto_secretstream_xchacha20poly1305_state *, state, 0) + + SN_THROWS(state_size != sizeof(crypto_secretstream_xchacha20poly1305_state), "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes") + + crypto_secretstream_xchacha20poly1305_rekey(state); + + return NULL; +} + +typedef struct sn_async_task_t { + uv_work_t task; + + enum { + sn_async_task_promise, + sn_async_task_callback + } type; + + void *req; + int code; + + napi_deferred deferred; + napi_ref cb; +} sn_async_task_t; + +typedef struct sn_async_pwhash_request { + napi_env env; + napi_ref out_ref; + unsigned char *out_data; + size_t out_size; + napi_ref pwd_ref; + const char *pwd_data; + size_t pwd_size; + napi_ref salt_ref; + unsigned char *salt; + uint32_t opslimit; + uint32_t memlimit; + uint32_t alg; +} sn_async_pwhash_request; + +static void async_pwhash_execute (uv_work_t *uv_req) { + sn_async_task_t *task = (sn_async_task_t *) uv_req; + sn_async_pwhash_request *req = (sn_async_pwhash_request *) task->req; + task->code = crypto_pwhash(req->out_data, + req->out_size, + req->pwd_data, + req->pwd_size, + req->salt, + req->opslimit, + req->memlimit, + req->alg); +} + +static void async_pwhash_complete (uv_work_t *uv_req, int status) { + sn_async_task_t *task = (sn_async_task_t *) uv_req; + sn_async_pwhash_request *req = (sn_async_pwhash_request *) task->req; + + napi_handle_scope scope; + napi_open_handle_scope(req->env, &scope); + + napi_value global; + napi_get_global(req->env, &global); + + SN_ASYNC_COMPLETE("failed to compute password hash") + + napi_close_handle_scope(req->env, scope); + + napi_delete_reference(req->env, req->out_ref); + napi_delete_reference(req->env, req->pwd_ref); + napi_delete_reference(req->env, req->salt_ref); + + free(req); + free(task); +} + +napi_value sn_crypto_pwhash_async (napi_env env, napi_callback_info info) { + SN_ARGV_OPTS(6, 7, crypto_pwhash_async) + + SN_ARGV_BUFFER_CAST(unsigned char *, out, 0) + SN_ARGV_BUFFER_CAST(char *, pwd, 1) + SN_ARGV_BUFFER_CAST(unsigned char *, salt, 2) + SN_ARGV_UINT64(opslimit, 3) + SN_ARGV_UINT64(memlimit, 4) + SN_ARGV_UINT8(alg, 5) + + SN_ASSERT_MIN_LENGTH(out_size, crypto_pwhash_BYTES_MIN, "out") + SN_ASSERT_MAX_LENGTH(out_size, crypto_pwhash_BYTES_MAX, "out") + SN_ASSERT_LENGTH(salt_size, crypto_pwhash_SALTBYTES, "salt") + SN_ASSERT_MIN_LENGTH(opslimit, crypto_pwhash_OPSLIMIT_MIN, "opslimit") + SN_ASSERT_MAX_LENGTH(opslimit, crypto_pwhash_OPSLIMIT_MAX, "opslimit") + SN_ASSERT_MIN_LENGTH(memlimit, crypto_pwhash_MEMLIMIT_MIN, "memlimit") + SN_ASSERT_MAX_LENGTH(memlimit, (int64_t) crypto_pwhash_MEMLIMIT_MAX, "memlimit") + SN_THROWS(alg < 1 || alg > 2, "alg must be either Argon2i 1.3 or Argon2id 1.3") + + sn_async_pwhash_request *req = (sn_async_pwhash_request *) malloc(sizeof(sn_async_pwhash_request)); + + req->env = env; + req->out_data = out; + req->out_size = out_size; + req->pwd_data = pwd; + req->pwd_size = pwd_size; + req->salt = salt; + req->opslimit = opslimit; + req->memlimit = memlimit; + req->alg = alg; + + sn_async_task_t *task = (sn_async_task_t *) malloc(sizeof(sn_async_task_t)); + SN_ASYNC_TASK(6) + + SN_STATUS_THROWS(napi_create_reference(env, out_argv, 1, &req->out_ref), "") + SN_STATUS_THROWS(napi_create_reference(env, pwd_argv, 1, &req->pwd_ref), "") + SN_STATUS_THROWS(napi_create_reference(env, salt_argv, 1, &req->salt_ref), "") + + SN_QUEUE_TASK(task, async_pwhash_execute, async_pwhash_complete) + + return promise; +} + +typedef struct sn_async_pwhash_str_request { + uv_work_t task; + napi_env env; + napi_ref out_ref; + char *out_data; + napi_ref pwd_ref; + const char *pwd_data; + size_t pwd_size; + uint32_t opslimit; + uint32_t memlimit; +} sn_async_pwhash_str_request; + +static void async_pwhash_str_execute (uv_work_t *uv_req) { + sn_async_task_t *task = (sn_async_task_t *) uv_req; + sn_async_pwhash_str_request *req = (sn_async_pwhash_str_request *) task->req; + task->code = crypto_pwhash_str(req->out_data, + req->pwd_data, + req->pwd_size, + req->opslimit, + req->memlimit); +} + +static void async_pwhash_str_complete (uv_work_t *uv_req, int status) { + sn_async_task_t *task = (sn_async_task_t *) uv_req; + sn_async_pwhash_str_request *req = (sn_async_pwhash_str_request *) task->req; + + napi_handle_scope scope; + napi_open_handle_scope(req->env, &scope); + + napi_value global; + napi_get_global(req->env, &global); + + SN_ASYNC_COMPLETE("failed to compute password hash") + + napi_close_handle_scope(req->env, scope); + + napi_delete_reference(req->env, req->out_ref); + napi_delete_reference(req->env, req->pwd_ref); + + free(req); + free(task); +} + +napi_value sn_crypto_pwhash_str_async (napi_env env, napi_callback_info info) { + SN_ARGV_OPTS(4, 5, crypto_pwhash_str_async) + + SN_ARGV_BUFFER_CAST(char *, out, 0) + SN_ARGV_BUFFER_CAST(char *, pwd, 1) + SN_ARGV_UINT64(opslimit, 2) + SN_ARGV_UINT64(memlimit, 3) + + SN_ASSERT_LENGTH(out_size, crypto_pwhash_STRBYTES, "out") + SN_ASSERT_MIN_LENGTH(opslimit, crypto_pwhash_OPSLIMIT_MIN, "opslimit") + SN_ASSERT_MAX_LENGTH(opslimit, crypto_pwhash_OPSLIMIT_MAX, "opslimit") + SN_ASSERT_MIN_LENGTH(memlimit, crypto_pwhash_MEMLIMIT_MIN, "memlimit") + SN_ASSERT_MAX_LENGTH(memlimit, (int64_t) crypto_pwhash_MEMLIMIT_MAX, "memlimit") + + sn_async_pwhash_str_request *req = (sn_async_pwhash_str_request *) malloc(sizeof(sn_async_pwhash_str_request)); + req->env = env; + req->out_data = out; + req->pwd_data = pwd; + req->pwd_size = pwd_size; + req->opslimit = opslimit; + req->memlimit = memlimit; + + sn_async_task_t *task = (sn_async_task_t *) malloc(sizeof(sn_async_task_t)); + SN_ASYNC_TASK(4) + + SN_STATUS_THROWS(napi_create_reference(env, out_argv, 1, &req->out_ref), "") + SN_STATUS_THROWS(napi_create_reference(env, pwd_argv, 1, &req->pwd_ref), "") + + SN_QUEUE_TASK(task, async_pwhash_str_execute, async_pwhash_str_complete) + + return promise; +} + +typedef struct sn_async_pwhash_str_verify_request { + uv_work_t task; + napi_env env; + napi_ref str_ref; + char *str_data; + napi_ref pwd_ref; + const char *pwd_data; + size_t pwd_size; +} sn_async_pwhash_str_verify_request; + +static void async_pwhash_str_verify_execute (uv_work_t *uv_req) { + sn_async_task_t *task = (sn_async_task_t *) uv_req; + sn_async_pwhash_str_verify_request *req = (sn_async_pwhash_str_verify_request *) task->req; + task->code = crypto_pwhash_str_verify(req->str_data, req->pwd_data, req->pwd_size); +} + +static void async_pwhash_str_verify_complete (uv_work_t *uv_req, int status) { + sn_async_task_t *task = (sn_async_task_t *) uv_req; + sn_async_pwhash_str_verify_request *req = (sn_async_pwhash_str_verify_request *) task->req; + + napi_handle_scope scope; + napi_open_handle_scope(req->env, &scope); + + napi_value global; + napi_get_global(req->env, &global); + + napi_value argv[2]; + + // Due to the way that crypto_pwhash_str_verify signals error different + // from a verification mismatch, we will count all errors as mismatch. + // The other possible error is wrong argument sizes, which is protected + // by macros above + napi_get_null(req->env, &argv[0]); + napi_get_boolean(req->env, task->code == 0, &argv[1]); + + switch (task->type) { + case sn_async_task_promise: { + napi_resolve_deferred(req->env, task->deferred, argv[1]); + task->deferred = NULL; + break; + } + + case sn_async_task_callback: { + napi_value callback; + napi_get_reference_value(req->env, task->cb, &callback); + + napi_value return_val; + SN_CALL_FUNCTION(req->env, global, callback, 2, argv, &return_val) + break; + } + } + + napi_close_handle_scope(req->env, scope); + + napi_delete_reference(req->env, req->str_ref); + napi_delete_reference(req->env, req->pwd_ref); + + free(req); + free(task); +} + +napi_value sn_crypto_pwhash_str_verify_async (napi_env env, napi_callback_info info) { + SN_ARGV_OPTS(2, 3, crypto_pwhash_str_async) + + SN_ARGV_BUFFER_CAST(char *, str, 0) + SN_ARGV_BUFFER_CAST(char *, pwd, 1) + + SN_ASSERT_LENGTH(str_size, crypto_pwhash_STRBYTES, "str") + + sn_async_pwhash_str_verify_request *req = (sn_async_pwhash_str_verify_request *) malloc(sizeof(sn_async_pwhash_str_verify_request)); + req->env = env; + req->str_data = str; + req->pwd_data = pwd; + req->pwd_size = pwd_size; + + sn_async_task_t *task = (sn_async_task_t *) malloc(sizeof(sn_async_task_t)); + SN_ASYNC_TASK(2) + + SN_STATUS_THROWS(napi_create_reference(env, str_argv, 1, &req->str_ref), "") + SN_STATUS_THROWS(napi_create_reference(env, pwd_argv, 1, &req->pwd_ref), "") + + SN_QUEUE_TASK(task, async_pwhash_str_verify_execute, async_pwhash_str_verify_complete) + + return promise; +} + +typedef struct sn_async_pwhash_scryptsalsa208sha256_request { + uv_work_t task; + napi_env env; + napi_ref out_ref; + unsigned char *out_data; + size_t out_size; + napi_ref pwd_ref; + const char *pwd_data; + size_t pwd_size; + napi_ref salt_ref; + unsigned char *salt; + uint32_t opslimit; + uint32_t memlimit; +} sn_async_pwhash_scryptsalsa208sha256_request; + +static void async_pwhash_scryptsalsa208sha256_execute (uv_work_t *uv_req) { + sn_async_task_t *task = (sn_async_task_t *) uv_req; + sn_async_pwhash_scryptsalsa208sha256_request *req = (sn_async_pwhash_scryptsalsa208sha256_request *) task->req; + task->code = crypto_pwhash_scryptsalsa208sha256(req->out_data, + req->out_size, + req-> pwd_data, + req->pwd_size, + req->salt, + req->opslimit, + req->memlimit); +} + +static void async_pwhash_scryptsalsa208sha256_complete (uv_work_t *uv_req, int status) { + sn_async_task_t *task = (sn_async_task_t *) uv_req; + sn_async_pwhash_scryptsalsa208sha256_request *req = (sn_async_pwhash_scryptsalsa208sha256_request *) task->req; + + napi_handle_scope scope; + napi_open_handle_scope(req->env, &scope); + + napi_value global; + napi_get_global(req->env, &global); + + SN_ASYNC_COMPLETE("failed to compute password hash") + + napi_close_handle_scope(req->env, scope); + + napi_delete_reference(req->env, req->out_ref); + napi_delete_reference(req->env, req->pwd_ref); + napi_delete_reference(req->env, req->salt_ref); + + free(req); + free(task); +} + +napi_value sn_crypto_pwhash_scryptsalsa208sha256_async (napi_env env, napi_callback_info info) { + SN_ARGV_OPTS(5, 6, crypto_pwhash_scryptsalsa208sha256_async) + + SN_ARGV_BUFFER_CAST(unsigned char *, out, 0) + SN_ARGV_BUFFER_CAST(char *, pwd, 1) + SN_ARGV_BUFFER_CAST(unsigned char *, salt, 2) + SN_ARGV_UINT64(opslimit, 3) + SN_ARGV_UINT64(memlimit, 4) + + SN_ASSERT_MIN_LENGTH(out_size, crypto_pwhash_scryptsalsa208sha256_BYTES_MIN, "out") + SN_ASSERT_MAX_LENGTH(out_size, crypto_pwhash_scryptsalsa208sha256_BYTES_MAX, "out") + SN_ASSERT_LENGTH(salt_size, crypto_pwhash_scryptsalsa208sha256_SALTBYTES, "salt") + SN_ASSERT_MIN_LENGTH(opslimit, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN, "opslimit") + SN_ASSERT_MAX_LENGTH(opslimit, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX, "opslimit") + SN_ASSERT_MIN_LENGTH(memlimit, crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN, "memlimit") + SN_ASSERT_MAX_LENGTH(memlimit, (int64_t) crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX, "memlimit") + + sn_async_pwhash_scryptsalsa208sha256_request *req = (sn_async_pwhash_scryptsalsa208sha256_request *) malloc(sizeof(sn_async_pwhash_scryptsalsa208sha256_request)); + req->env = env; + req->out_data = out; + req->out_size = out_size; + req->pwd_data = pwd; + req->pwd_size = pwd_size; + req-> salt = salt; + req->opslimit = opslimit; + req->memlimit = memlimit; + + sn_async_task_t *task = (sn_async_task_t *) malloc(sizeof(sn_async_task_t)); + SN_ASYNC_TASK(5) + + SN_STATUS_THROWS(napi_create_reference(env, out_argv, 1, &req->out_ref), "") + SN_STATUS_THROWS(napi_create_reference(env, pwd_argv, 1, &req->pwd_ref), "") + SN_STATUS_THROWS(napi_create_reference(env, salt_argv, 1, &req->salt_ref), "") + + SN_QUEUE_TASK(task, async_pwhash_scryptsalsa208sha256_execute, async_pwhash_scryptsalsa208sha256_complete) + + return promise; +} + +typedef struct sn_async_pwhash_scryptsalsa208sha256_str_request { + uv_work_t task; + napi_env env; + napi_ref out_ref; + char *out_data; + napi_ref pwd_ref; + const char *pwd_data; + size_t pwd_size; + uint32_t opslimit; + uint32_t memlimit; +} sn_async_pwhash_scryptsalsa208sha256_str_request; + +static void async_pwhash_scryptsalsa208sha256_str_execute (uv_work_t *uv_req) { + sn_async_task_t *task = (sn_async_task_t *) uv_req; + sn_async_pwhash_scryptsalsa208sha256_str_request *req = (sn_async_pwhash_scryptsalsa208sha256_str_request *) task->req; + task->code = crypto_pwhash_scryptsalsa208sha256_str(req->out_data, + req->pwd_data, + req->pwd_size, + req->opslimit, + req->memlimit); +} + +static void async_pwhash_scryptsalsa208sha256_str_complete (uv_work_t *uv_req, int status) { + sn_async_task_t *task = (sn_async_task_t *) uv_req; + sn_async_pwhash_scryptsalsa208sha256_str_request *req = (sn_async_pwhash_scryptsalsa208sha256_str_request *) task->req; + + napi_handle_scope scope; + napi_open_handle_scope(req->env, &scope); + + napi_value global; + napi_get_global(req->env, &global); + + SN_ASYNC_COMPLETE("failed to compute password hash") + + napi_close_handle_scope(req->env, scope); + + napi_delete_reference(req->env, req->out_ref); + napi_delete_reference(req->env, req->pwd_ref); + + free(req); + free(task); +} + +napi_value sn_crypto_pwhash_scryptsalsa208sha256_str_async (napi_env env, napi_callback_info info) { + SN_ARGV_OPTS(4, 5, crypto_pwhash_scryptsalsa208sha256_str_async) + + SN_ARGV_BUFFER_CAST(char *, out, 0) + SN_ARGV_BUFFER_CAST(char *, pwd, 1) + SN_ARGV_UINT64(opslimit, 2) + SN_ARGV_UINT64(memlimit, 3) + + SN_ASSERT_LENGTH(out_size, crypto_pwhash_scryptsalsa208sha256_STRBYTES, "out") + SN_ASSERT_MIN_LENGTH(opslimit, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN, "opslimit") + SN_ASSERT_MAX_LENGTH(opslimit, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX, "opslimit") + SN_ASSERT_MIN_LENGTH(memlimit, crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN, "memlimit") + SN_ASSERT_MAX_LENGTH(memlimit, (int64_t) crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX, "memlimit") + + sn_async_pwhash_scryptsalsa208sha256_str_request *req = (sn_async_pwhash_scryptsalsa208sha256_str_request *) malloc(sizeof(sn_async_pwhash_scryptsalsa208sha256_str_request)); + req->env = env; + req->out_data = out; + req->pwd_data = pwd; + req->pwd_size = pwd_size; + req->opslimit = opslimit; + req->memlimit = memlimit; + + sn_async_task_t *task = (sn_async_task_t *) malloc(sizeof(sn_async_task_t)); + SN_ASYNC_TASK(4) + + SN_STATUS_THROWS(napi_create_reference(env, out_argv, 1, &req->out_ref), "") + SN_STATUS_THROWS(napi_create_reference(env, pwd_argv, 1, &req->pwd_ref), "") + + SN_QUEUE_TASK(task, async_pwhash_scryptsalsa208sha256_str_execute, async_pwhash_scryptsalsa208sha256_str_complete) + + return promise; +} + +typedef struct sn_async_pwhash_scryptsalsa208sha256_str_verify_request { + uv_work_t task; + napi_env env; + napi_ref str_ref; + char *str_data; + napi_ref pwd_ref; + const char *pwd_data; + size_t pwd_size; +} sn_async_pwhash_scryptsalsa208sha256_str_verify_request; + +static void async_pwhash_scryptsalsa208sha256_str_verify_execute (uv_work_t *uv_req) { + sn_async_task_t *task = (sn_async_task_t *) uv_req; + sn_async_pwhash_scryptsalsa208sha256_str_verify_request *req = (sn_async_pwhash_scryptsalsa208sha256_str_verify_request *) task->req; + task->code = crypto_pwhash_scryptsalsa208sha256_str_verify(req->str_data, req->pwd_data, req->pwd_size); +} + +static void async_pwhash_scryptsalsa208sha256_str_verify_complete (uv_work_t *uv_req, int status) { + sn_async_task_t *task = (sn_async_task_t *) uv_req; + sn_async_pwhash_scryptsalsa208sha256_str_verify_request *req = (sn_async_pwhash_scryptsalsa208sha256_str_verify_request *) task->req; + + napi_handle_scope scope; + napi_open_handle_scope(req->env, &scope); + + napi_value global; + napi_get_global(req->env, &global); + + napi_value argv[2]; + + // Due to the way that crypto_pwhash_scryptsalsa208sha256_str_verify + // signal serror different from a verification mismatch, we will count + // all errors as mismatch. The other possible error is wrong argument + // sizes, which is protected by macros above + napi_get_null(req->env, &argv[0]); + napi_get_boolean(req->env, task->code == 0, &argv[1]); + + switch (task->type) { + case sn_async_task_promise: { + napi_resolve_deferred(req->env, task->deferred, argv[1]); + task->deferred = NULL; + break; + } + + case sn_async_task_callback: { + napi_value callback; + napi_get_reference_value(req->env, task->cb, &callback); + + napi_value return_val; + SN_CALL_FUNCTION(req->env, global, callback, 2, argv, &return_val) + break; + } + } + + napi_close_handle_scope(req->env, scope); + + napi_delete_reference(req->env, req->str_ref); + napi_delete_reference(req->env, req->pwd_ref); + + free(req); + free(task); +} + +napi_value sn_crypto_pwhash_scryptsalsa208sha256_str_verify_async (napi_env env, napi_callback_info info) { + SN_ARGV_OPTS(2, 3, crypto_pwhash_scryptsalsa208sha256_str_async) + + SN_ARGV_BUFFER_CAST(char *, str, 0) + SN_ARGV_BUFFER_CAST(char *, pwd, 1) + + SN_ASSERT_LENGTH(str_size, crypto_pwhash_scryptsalsa208sha256_STRBYTES, "str") + + sn_async_pwhash_scryptsalsa208sha256_str_verify_request *req = (sn_async_pwhash_scryptsalsa208sha256_str_verify_request *) malloc(sizeof(sn_async_pwhash_scryptsalsa208sha256_str_verify_request)); + req->env = env; + req->str_data = str; + req->pwd_data = pwd; + req->pwd_size = pwd_size; + + sn_async_task_t *task = (sn_async_task_t *) malloc(sizeof(sn_async_task_t)); + SN_ASYNC_TASK(2) + + SN_STATUS_THROWS(napi_create_reference(env, str_argv, 1, &req->str_ref), "") + SN_STATUS_THROWS(napi_create_reference(env, pwd_argv, 1, &req->pwd_ref), "") + + SN_QUEUE_TASK(task, async_pwhash_scryptsalsa208sha256_str_verify_execute, async_pwhash_scryptsalsa208sha256_str_verify_complete) + + return promise; +} + +typedef struct sn_crypto_stream_xor_state { + unsigned char n[crypto_stream_NONCEBYTES]; + unsigned char k[crypto_stream_KEYBYTES]; + unsigned char next_block[64]; + int remainder; + uint64_t block_counter; +} sn_crypto_stream_xor_state; + +napi_value sn_crypto_stream_xor_wrap_init (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream_xor_instance_init) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_xor_state *, state, 0) + SN_ARGV_TYPEDARRAY(n, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_xor_state), "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes") + SN_ASSERT_LENGTH(n_size, crypto_stream_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_KEYBYTES, "k") + + state->remainder = 0; + state->block_counter = 0; + memcpy(state->n, n_data, crypto_stream_NONCEBYTES); + memcpy(state->k, k_data, crypto_stream_KEYBYTES); + + return NULL; +} + +napi_value sn_crypto_stream_xor_wrap_update (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream_xor_instance_init) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_xor_state *, state, 0) + SN_ARGV_BUFFER_CAST(unsigned char *, c, 1) + SN_ARGV_BUFFER_CAST(unsigned char *, m, 2) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_xor_state), "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes") + SN_THROWS(c_size != m_size, "c must be 'm.byteLength' bytes") + + unsigned char *next_block = state->next_block; + + if (state->remainder) { + uint64_t offset = 0; + int rem = state->remainder; + + while (rem < 64 && offset < m_size) { + c[offset] = next_block[rem] ^ m[offset]; + offset++; + rem++; + } + + c += offset; + m += offset; + m_size -= offset; + state->remainder = rem == 64 ? 0 : rem; + + if (!m_size) return NULL; + } + + state->remainder = m_size & 63; + m_size -= state->remainder; + crypto_stream_xsalsa20_xor_ic(c, m, m_size, state->n, state->block_counter, state->k); + state->block_counter += m_size / 64; + + if (state->remainder) { + sodium_memzero(next_block + state->remainder, 64 - state->remainder); + memcpy(next_block, m + m_size, state->remainder); + + crypto_stream_xsalsa20_xor_ic(next_block, next_block, 64, state->n, state->block_counter, state->k); + memcpy(c + m_size, next_block, state->remainder); + + state->block_counter++; + } + + return NULL; +} + +napi_value sn_crypto_stream_xor_wrap_final (napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_stream_xor_instance_init) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_xor_state *, state, 0) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_xor_state), "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes") + + sodium_memzero(state->n, sizeof(state->n)); + sodium_memzero(state->k, sizeof(state->k)); + sodium_memzero(state->next_block, sizeof(state->next_block)); + state->remainder = 0; + + return NULL; +} + +typedef struct sn_crypto_stream_chacha20_xor_state { + unsigned char n[crypto_stream_chacha20_NONCEBYTES]; + unsigned char k[crypto_stream_chacha20_KEYBYTES]; + unsigned char next_block[64]; + int remainder; + uint64_t block_counter; +} sn_crypto_stream_chacha20_xor_state; + +napi_value sn_crypto_stream_chacha20_xor_wrap_init (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream_chacha20_xor_instance_init) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_chacha20_xor_state *, state, 0) + SN_ARGV_TYPEDARRAY(n, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_chacha20_xor_state), "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes") + SN_ASSERT_LENGTH(n_size, crypto_stream_chacha20_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_chacha20_KEYBYTES, "k") + + state->remainder = 0; + state->block_counter = 0; + memcpy(state->n, n_data, crypto_stream_chacha20_NONCEBYTES); + memcpy(state->k, k_data, crypto_stream_chacha20_KEYBYTES); + + return NULL; +} + +napi_value sn_crypto_stream_chacha20_xor_wrap_update (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream_chacha20_xor_instance_init) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_chacha20_xor_state *, state, 0) + SN_ARGV_BUFFER_CAST(unsigned char *, c, 1) + SN_ARGV_BUFFER_CAST(unsigned char *, m, 2) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_chacha20_xor_state), "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes") + SN_THROWS(c_size != m_size, "c must be 'm.byteLength' bytes") + + unsigned char *next_block = state->next_block; + + if (state->remainder) { + uint64_t offset = 0; + int rem = state->remainder; + + while (rem < 64 && offset < m_size) { + c[offset] = next_block[rem] ^ m[offset]; + offset++; + rem++; + } + + c += offset; + m += offset; + m_size -= offset; + state->remainder = rem == 64 ? 0 : rem; + + if (!m_size) return NULL; + } + + state->remainder = m_size & 63; + m_size -= state->remainder; + crypto_stream_chacha20_xor_ic(c, m, m_size, state->n, state->block_counter, state->k); + state->block_counter += m_size / 64; + + if (state->remainder) { + sodium_memzero(next_block + state->remainder, 64 - state->remainder); + memcpy(next_block, m + m_size, state->remainder); + + crypto_stream_chacha20_xor_ic(next_block, next_block, 64, state->n, state->block_counter, state->k); + memcpy(c + m_size, next_block, state->remainder); + + state->block_counter++; + } + + return NULL; +} + +napi_value sn_crypto_stream_chacha20_xor_wrap_final (napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_stream_chacha20_xor_instance_init) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_chacha20_xor_state *, state, 0) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_chacha20_xor_state), "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes") + + sodium_memzero(state->n, sizeof(state->n)); + sodium_memzero(state->k, sizeof(state->k)); + sodium_memzero(state->next_block, sizeof(state->next_block)); + state->remainder = 0; + + return NULL; +} + +typedef struct sn_crypto_stream_chacha20_ietf_xor_state { + unsigned char n[crypto_stream_chacha20_ietf_NONCEBYTES]; + unsigned char k[crypto_stream_chacha20_ietf_KEYBYTES]; + unsigned char next_block[64]; + int remainder; + uint64_t block_counter; +} sn_crypto_stream_chacha20_ietf_xor_state; + +napi_value sn_crypto_stream_chacha20_ietf_xor_wrap_init (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream_chacha20_ietf_xor_wrap_init) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_chacha20_ietf_xor_state *, state, 0) + SN_ARGV_TYPEDARRAY(n, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_chacha20_ietf_xor_state), "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes") + SN_ASSERT_LENGTH(n_size, crypto_stream_chacha20_ietf_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_chacha20_ietf_KEYBYTES, "k") + + state->remainder = 0; + state->block_counter = 0; + memcpy(state->n, n_data, crypto_stream_chacha20_ietf_NONCEBYTES); + memcpy(state->k, k_data, crypto_stream_chacha20_ietf_KEYBYTES); + + return NULL; +} + +napi_value sn_crypto_stream_chacha20_ietf_xor_wrap_update (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream_chacha20_ietf_xor_wrap_update) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_chacha20_ietf_xor_state *, state, 0) + SN_ARGV_BUFFER_CAST(unsigned char *, c, 1) + SN_ARGV_BUFFER_CAST(unsigned char *, m, 2) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_chacha20_ietf_xor_state), "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes") + SN_THROWS(c_size != m_size, "c must be 'm.byteLength' bytes") + + unsigned char *next_block = state->next_block; + + if (state->remainder) { + uint64_t offset = 0; + int rem = state->remainder; + + while (rem < 64 && offset < m_size) { + c[offset] = next_block[rem] ^ m[offset]; + offset++; + rem++; + } + + c += offset; + m += offset; + m_size -= offset; + state->remainder = rem == 64 ? 0 : rem; + + if (!m_size) return NULL; + } + + state->remainder = m_size & 63; + m_size -= state->remainder; + crypto_stream_chacha20_ietf_xor_ic(c, m, m_size, state->n, state->block_counter, state->k); + state->block_counter += m_size / 64; + + if (state->remainder) { + sodium_memzero(next_block + state->remainder, 64 - state->remainder); + memcpy(next_block, m + m_size, state->remainder); + + crypto_stream_chacha20_ietf_xor_ic(next_block, next_block, 64, state->n, state->block_counter, state->k); + memcpy(c + m_size, next_block, state->remainder); + + state->block_counter++; + } + + return NULL; +} + +napi_value sn_crypto_stream_chacha20_ietf_xor_wrap_final (napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_stream_chacha20_ietf_xor_wrap_final) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_chacha20_ietf_xor_state *, state, 0) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_chacha20_ietf_xor_state), "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes") + + sodium_memzero(state->n, sizeof(state->n)); + sodium_memzero(state->k, sizeof(state->k)); + sodium_memzero(state->next_block, sizeof(state->next_block)); + state->remainder = 0; + + return NULL; +} + +typedef struct sn_crypto_stream_xchacha20_xor_state { + unsigned char n[crypto_stream_xchacha20_NONCEBYTES]; + unsigned char k[crypto_stream_xchacha20_KEYBYTES]; + unsigned char next_block[64]; + int remainder; + uint64_t block_counter; +} sn_crypto_stream_xchacha20_xor_state; + +napi_value sn_crypto_stream_xchacha20_xor_wrap_init (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream_xchacha20_xor_wrap_init) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_xchacha20_xor_state *, state, 0) + SN_ARGV_TYPEDARRAY(n, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_xchacha20_xor_state), "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes") + SN_ASSERT_LENGTH(n_size, crypto_stream_xchacha20_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_xchacha20_KEYBYTES, "k") + + state->remainder = 0; + state->block_counter = 0; + memcpy(state->n, n_data, crypto_stream_xchacha20_NONCEBYTES); + memcpy(state->k, k_data, crypto_stream_xchacha20_KEYBYTES); + + return NULL; +} + +napi_value sn_crypto_stream_xchacha20_xor_wrap_update (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream_xchacha20_xor_wrap_update) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_xchacha20_xor_state *, state, 0) + SN_ARGV_BUFFER_CAST(unsigned char *, c, 1) + SN_ARGV_BUFFER_CAST(unsigned char *, m, 2) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_xchacha20_xor_state), "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes") + SN_THROWS(c_size != m_size, "c must be 'm.byteLength' bytes") + + unsigned char *next_block = state->next_block; + + if (state->remainder) { + uint64_t offset = 0; + int rem = state->remainder; + + while (rem < 64 && offset < m_size) { + c[offset] = next_block[rem] ^ m[offset]; + offset++; + rem++; + } + + c += offset; + m += offset; + m_size -= offset; + state->remainder = rem == 64 ? 0 : rem; + + if (!m_size) return NULL; + } + + state->remainder = m_size & 63; + m_size -= state->remainder; + crypto_stream_xchacha20_xor_ic(c, m, m_size, state->n, state->block_counter, state->k); + state->block_counter += m_size / 64; + + if (state->remainder) { + sodium_memzero(next_block + state->remainder, 64 - state->remainder); + memcpy(next_block, m + m_size, state->remainder); + + crypto_stream_xchacha20_xor_ic(next_block, next_block, 64, state->n, state->block_counter, state->k); + memcpy(c + m_size, next_block, state->remainder); + + state->block_counter++; + } + + return NULL; +} + +napi_value sn_crypto_stream_xchacha20_xor_wrap_final (napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_stream_xchacha20_xor_wrap_final) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_xchacha20_xor_state *, state, 0) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_xchacha20_xor_state), "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes") + + sodium_memzero(state->n, sizeof(state->n)); + sodium_memzero(state->k, sizeof(state->k)); + sodium_memzero(state->next_block, sizeof(state->next_block)); + state->remainder = 0; + + return NULL; +} + +typedef struct sn_crypto_stream_salsa20_xor_state { + unsigned char n[crypto_stream_salsa20_NONCEBYTES]; + unsigned char k[crypto_stream_salsa20_KEYBYTES]; + unsigned char next_block[64]; + int remainder; + uint64_t block_counter; +} sn_crypto_stream_salsa20_xor_state; + +napi_value sn_crypto_stream_salsa20_xor_wrap_init (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream_salsa20_xor_wrap_init) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_salsa20_xor_state *, state, 0) + SN_ARGV_TYPEDARRAY(n, 1) + SN_ARGV_TYPEDARRAY(k, 2) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_salsa20_xor_state), "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes") + SN_ASSERT_LENGTH(n_size, crypto_stream_salsa20_NONCEBYTES, "n") + SN_ASSERT_LENGTH(k_size, crypto_stream_salsa20_KEYBYTES, "k") + + state->remainder = 0; + state->block_counter = 0; + memcpy(state->n, n_data, crypto_stream_salsa20_NONCEBYTES); + memcpy(state->k, k_data, crypto_stream_salsa20_KEYBYTES); + + return NULL; +} + +napi_value sn_crypto_stream_salsa20_xor_wrap_update (napi_env env, napi_callback_info info) { + SN_ARGV(3, crypto_stream_salsa20_xor_wrap_update) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_salsa20_xor_state *, state, 0) + SN_ARGV_BUFFER_CAST(unsigned char *, c, 1) + SN_ARGV_BUFFER_CAST(unsigned char *, m, 2) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_salsa20_xor_state), "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes") + SN_THROWS(c_size != m_size, "c must be 'm.byteLength' bytes") + + unsigned char *next_block = state->next_block; + + if (state->remainder) { + uint64_t offset = 0; + int rem = state->remainder; + + while (rem < 64 && offset < m_size) { + c[offset] = next_block[rem] ^ m[offset]; + offset++; + rem++; + } + + c += offset; + m += offset; + m_size -= offset; + state->remainder = rem == 64 ? 0 : rem; + + if (!m_size) return NULL; + } + + state->remainder = m_size & 63; + m_size -= state->remainder; + crypto_stream_salsa20_xor_ic(c, m, m_size, state->n, state->block_counter, state->k); + state->block_counter += m_size / 64; + + if (state->remainder) { + sodium_memzero(next_block + state->remainder, 64 - state->remainder); + memcpy(next_block, m + m_size, state->remainder); + + crypto_stream_salsa20_xor_ic(next_block, next_block, 64, state->n, state->block_counter, state->k); + memcpy(c + m_size, next_block, state->remainder); + + state->block_counter++; + } + + return NULL; +} + +napi_value sn_crypto_stream_salsa20_xor_wrap_final (napi_env env, napi_callback_info info) { + SN_ARGV(1, crypto_stream_salsa20_xor_wrap_final) + + SN_ARGV_BUFFER_CAST(sn_crypto_stream_salsa20_xor_state *, state, 0) + + SN_THROWS(state_size != sizeof(sn_crypto_stream_salsa20_xor_state), "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes") + + sodium_memzero(state->n, sizeof(state->n)); + sodium_memzero(state->k, sizeof(state->k)); + sodium_memzero(state->next_block, sizeof(state->next_block)); + state->remainder = 0; + + return NULL; +} + +// Experimental API + +napi_value sn_extension_tweak_ed25519_base (napi_env env, napi_callback_info info) { + SN_ARGV(3, extension_tweak_ed25519_base) + + SN_ARGV_TYPEDARRAY(n, 0) + SN_ARGV_TYPEDARRAY(p, 1) + SN_ARGV_TYPEDARRAY(ns, 2) + + SN_ASSERT_LENGTH(n_size, sn__extension_tweak_ed25519_SCALARBYTES, "n") + SN_ASSERT_LENGTH(p_size, sn__extension_tweak_ed25519_BYTES, "p") + + sn__extension_tweak_ed25519_base(p_data, n_data, ns_data, ns_size); + + return NULL; +} + +napi_value sn_extension_tweak_ed25519_sign_detached (napi_env env, napi_callback_info info) { + SN_ARGV_OPTS(3, 4, extension_tweak_ed25519_sign_detached) + + SN_ARGV_TYPEDARRAY(sig, 0) + SN_ARGV_TYPEDARRAY(m, 1) + SN_ARGV_TYPEDARRAY(scalar, 2) + SN_ARGV_OPTS_TYPEDARRAY(pk, 3) + + SN_ASSERT_LENGTH(sig_size, crypto_sign_BYTES, "sig") + SN_ASSERT_LENGTH(scalar_size, sn__extension_tweak_ed25519_SCALARBYTES, "scalar") + + if (pk_data != NULL) { + SN_ASSERT_LENGTH(pk_size, crypto_sign_PUBLICKEYBYTES, "pk") + } + + SN_RETURN(sn__extension_tweak_ed25519_sign_detached(sig_data, NULL, m_data, m_size, scalar_data, pk_data), "failed to compute signature") +} + +napi_value sn_extension_tweak_ed25519_sk_to_scalar (napi_env env, napi_callback_info info) { + SN_ARGV(2, extension_tweak_ed25519_sk_to_scalar) + + SN_ARGV_TYPEDARRAY(n, 0) + SN_ARGV_TYPEDARRAY(sk, 1) + + SN_ASSERT_LENGTH(n_size, sn__extension_tweak_ed25519_SCALARBYTES, "n") + SN_ASSERT_LENGTH(sk_size, crypto_sign_SECRETKEYBYTES, "sk") + + sn__extension_tweak_ed25519_sk_to_scalar(n_data, sk_data); + + return NULL; +} + +napi_value sn_extension_tweak_ed25519_scalar (napi_env env, napi_callback_info info) { + SN_ARGV(3, extension_tweak_ed25519_scalar) + + SN_ARGV_TYPEDARRAY(scalar_out, 0) + SN_ARGV_TYPEDARRAY(scalar, 1) + SN_ARGV_TYPEDARRAY(ns, 2) + + SN_ASSERT_LENGTH(scalar_out_size, sn__extension_tweak_ed25519_SCALARBYTES, "scalar_out") + SN_ASSERT_LENGTH(scalar_size, sn__extension_tweak_ed25519_SCALARBYTES, "scalar") + + sn__extension_tweak_ed25519_scalar(scalar_out_data, scalar_data, ns_data, ns_size); + + return NULL; +} + +napi_value sn_extension_tweak_ed25519_pk (napi_env env, napi_callback_info info) { + SN_ARGV(3, extension_tweak_ed25519_pk) + + SN_ARGV_TYPEDARRAY(tpk, 0) + SN_ARGV_TYPEDARRAY(pk, 1) + SN_ARGV_TYPEDARRAY(ns, 2) + + SN_ASSERT_LENGTH(tpk_size, crypto_sign_PUBLICKEYBYTES, "tpk") + SN_ASSERT_LENGTH(pk_size, crypto_sign_PUBLICKEYBYTES, "pk") + + SN_RETURN(sn__extension_tweak_ed25519_pk(tpk_data, pk_data, ns_data, ns_size), "failed to tweak public key") +} + +napi_value sn_extension_tweak_ed25519_keypair (napi_env env, napi_callback_info info) { + SN_ARGV(4, extension_tweak_ed25519_keypair) + + SN_ARGV_TYPEDARRAY(pk, 0) + SN_ARGV_TYPEDARRAY(scalar_out, 1) + SN_ARGV_TYPEDARRAY(scalar_in, 2) + SN_ARGV_TYPEDARRAY(ns, 3) + + SN_ASSERT_LENGTH(pk_size, sn__extension_tweak_ed25519_BYTES, "pk") + SN_ASSERT_LENGTH(scalar_out_size, sn__extension_tweak_ed25519_SCALARBYTES, "scalar_out") + SN_ASSERT_LENGTH(scalar_in_size, sn__extension_tweak_ed25519_SCALARBYTES, "scalar_in") + + sn__extension_tweak_ed25519_keypair(pk_data, scalar_out_data, scalar_in_data, ns_data, ns_size); + + return NULL; +} + +napi_value sn_extension_tweak_ed25519_scalar_add (napi_env env, napi_callback_info info) { + SN_ARGV(3, extension_tweak_ed25519_scalar_add) + + SN_ARGV_TYPEDARRAY(scalar_out, 0) + SN_ARGV_TYPEDARRAY(scalar, 1) + SN_ARGV_TYPEDARRAY(n, 2) + + SN_ASSERT_LENGTH(scalar_out_size, sn__extension_tweak_ed25519_SCALARBYTES, "scalar_out") + SN_ASSERT_LENGTH(scalar_size, sn__extension_tweak_ed25519_SCALARBYTES, "scalar") + SN_ASSERT_LENGTH(n_size, sn__extension_tweak_ed25519_SCALARBYTES, "n") + + sn__extension_tweak_ed25519_scalar_add(scalar_out_data, scalar_data, n_data); + + return NULL; +} + +napi_value sn_extension_tweak_ed25519_pk_add (napi_env env, napi_callback_info info) { + SN_ARGV(3, extension_tweak_ed25519_pk) + + SN_ARGV_TYPEDARRAY(tpk, 0) + SN_ARGV_TYPEDARRAY(pk, 1) + SN_ARGV_TYPEDARRAY(p, 2) + + SN_ASSERT_LENGTH(tpk_size, crypto_sign_PUBLICKEYBYTES, "tpk") + SN_ASSERT_LENGTH(pk_size, crypto_sign_PUBLICKEYBYTES, "pk") + SN_ASSERT_LENGTH(p_size, crypto_sign_PUBLICKEYBYTES, "p") + + SN_RETURN(sn__extension_tweak_ed25519_pk_add(tpk_data, pk_data, p_data), "failed to add tweak to public key") +} + +napi_value sn_extension_tweak_ed25519_keypair_add (napi_env env, napi_callback_info info) { + SN_ARGV(4, extension_tweak_ed25519_keypair_add) + + SN_ARGV_TYPEDARRAY(pk, 0) + SN_ARGV_TYPEDARRAY(scalar_out, 1) + SN_ARGV_TYPEDARRAY(scalar_in, 2) + SN_ARGV_TYPEDARRAY(tweak, 3) + + SN_ASSERT_LENGTH(pk_size, sn__extension_tweak_ed25519_BYTES, "pk") + SN_ASSERT_LENGTH(scalar_out_size, sn__extension_tweak_ed25519_SCALARBYTES, "scalar_out") + SN_ASSERT_LENGTH(scalar_in_size, sn__extension_tweak_ed25519_SCALARBYTES, "scalar_in") + SN_ASSERT_LENGTH(tweak_size, sn__extension_tweak_ed25519_SCALARBYTES, "tweak") + + SN_RETURN(sn__extension_tweak_ed25519_keypair_add(pk_data, scalar_out_data, scalar_in_data, tweak_data), "failed to add tweak to keypair") +} + +napi_value sn_extension_pbkdf2_sha512 (napi_env env, napi_callback_info info) { + SN_ARGV(5, extension_pbkdf2_sha512) + + SN_ARGV_BUFFER_CAST(unsigned char *, out, 0) + SN_ARGV_BUFFER_CAST(unsigned char *, passwd, 1) + SN_ARGV_BUFFER_CAST(unsigned char *, salt, 2) + SN_ARGV_UINT64(iter, 3) + SN_ARGV_UINT64(outlen, 4) + + SN_ASSERT_MIN_LENGTH(iter, sn__extension_pbkdf2_sha512_ITERATIONS_MIN, "iterations") + SN_ASSERT_MAX_LENGTH(outlen, sn__extension_pbkdf2_sha512_BYTES_MAX, "outlen") + + SN_ASSERT_MIN_LENGTH(out_size, outlen, "out") + + SN_RETURN(sn__extension_pbkdf2_sha512(passwd, passwd_size, salt, salt_size, iter, out, outlen), "failed to add tweak to public key") +} + +typedef struct sn_async_pbkdf2_sha512_request { + napi_env env; + unsigned char *out_data; + size_t out_size; + napi_ref out_ref; + size_t outlen; + napi_ref pwd_ref; + const unsigned char *pwd_data; + size_t pwd_size; + napi_ref salt_ref; + unsigned char *salt_data; + size_t salt_size; + uint64_t iter; +} sn_async_pbkdf2_sha512_request; + +static void async_pbkdf2_sha512_execute (uv_work_t *uv_req) { + sn_async_task_t *task = (sn_async_task_t *) uv_req; + sn_async_pbkdf2_sha512_request *req = (sn_async_pbkdf2_sha512_request *) task->req; + task->code = sn__extension_pbkdf2_sha512(req->pwd_data, + req->pwd_size, + req->salt_data, + req->salt_size, + req->iter, + req->out_data, + req->outlen); +} + +static void async_pbkdf2_sha512_complete (uv_work_t *uv_req, int status) { + sn_async_task_t *task = (sn_async_task_t *) uv_req; + sn_async_pbkdf2_sha512_request *req = (sn_async_pbkdf2_sha512_request *) task->req; + + napi_handle_scope scope; + napi_open_handle_scope(req->env, &scope); + + napi_value global; + napi_get_global(req->env, &global); + + SN_ASYNC_COMPLETE("failed to compute kdf") + + napi_close_handle_scope(req->env, scope); + + napi_delete_reference(req->env, req->out_ref); + napi_delete_reference(req->env, req->pwd_ref); + napi_delete_reference(req->env, req->salt_ref); + + free(req); + free(task); +} + +napi_value sn_extension_pbkdf2_sha512_async (napi_env env, napi_callback_info info) { + SN_ARGV_OPTS(5, 6, extension_pbkdf2_sha512_async) + + SN_ARGV_BUFFER_CAST(unsigned char *, out, 0) + SN_ARGV_BUFFER_CAST(unsigned char *, pwd, 1) + SN_ARGV_BUFFER_CAST(unsigned char *, salt, 2) + SN_ARGV_UINT64(iter, 3) + SN_ARGV_UINT64(outlen, 4) + + SN_ASSERT_MIN_LENGTH(iter, sn__extension_pbkdf2_sha512_ITERATIONS_MIN, "iterations") + SN_ASSERT_MAX_LENGTH(outlen, sn__extension_pbkdf2_sha512_BYTES_MAX, "outlen") + SN_ASSERT_MIN_LENGTH(out_size, outlen, "output") + + sn_async_pbkdf2_sha512_request *req = (sn_async_pbkdf2_sha512_request *) malloc(sizeof(sn_async_pbkdf2_sha512_request)); + + req->env = env; + req->out_data = out; + req->out_size = out_size; + req->pwd_data = pwd; + req->pwd_size = pwd_size; + req->salt_data = salt; + req->salt_size = salt_size; + req->iter = iter; + req->outlen = outlen; + + sn_async_task_t *task = (sn_async_task_t *) malloc(sizeof(sn_async_task_t)); + SN_ASYNC_TASK(5); + + SN_STATUS_THROWS(napi_create_reference(env, out_argv, 1, &req->out_ref), "") + SN_STATUS_THROWS(napi_create_reference(env, pwd_argv, 1, &req->pwd_ref), "") + SN_STATUS_THROWS(napi_create_reference(env, salt_argv, 1, &req->salt_ref), "") + + SN_QUEUE_TASK(task, async_pbkdf2_sha512_execute, async_pbkdf2_sha512_complete) + + return promise; +} + +static napi_value create_sodium_native (napi_env env) { + SN_THROWS(sodium_init() == -1, "sodium_init() failed") + + napi_value exports; + napi_create_object(env, &exports); + + // memory + + SN_EXPORT_FUNCTION(sodium_memzero, sn_sodium_memzero) + SN_EXPORT_FUNCTION(sodium_mlock, sn_sodium_mlock) + SN_EXPORT_FUNCTION(sodium_munlock, sn_sodium_munlock) + SN_EXPORT_FUNCTION(sodium_malloc, sn_sodium_malloc) + SN_EXPORT_FUNCTION(sodium_free, sn_sodium_free) + SN_EXPORT_FUNCTION(sodium_mprotect_noaccess, sn_sodium_mprotect_noaccess) + SN_EXPORT_FUNCTION(sodium_mprotect_readonly, sn_sodium_mprotect_readonly) + SN_EXPORT_FUNCTION(sodium_mprotect_readwrite, sn_sodium_mprotect_readwrite) + + // randombytes + + SN_EXPORT_FUNCTION(randombytes_buf, sn_randombytes_buf) + SN_EXPORT_FUNCTION(randombytes_buf_deterministic, sn_randombytes_buf_deterministic) + SN_EXPORT_FUNCTION(randombytes_uniform, sn_randombytes_uniform) + SN_EXPORT_FUNCTION(randombytes_random, sn_randombytes_random) + SN_EXPORT_UINT32(randombytes_SEEDBYTES, randombytes_SEEDBYTES) + + // sodium helpers + + SN_EXPORT_FUNCTION(sodium_memcmp, sn_sodium_memcmp) + SN_EXPORT_FUNCTION(sodium_increment, sn_sodium_increment) + SN_EXPORT_FUNCTION(sodium_add, sn_sodium_add) + SN_EXPORT_FUNCTION(sodium_sub, sn_sodium_sub) + SN_EXPORT_FUNCTION(sodium_compare, sn_sodium_compare) + SN_EXPORT_FUNCTION(sodium_is_zero, sn_sodium_is_zero) + SN_EXPORT_FUNCTION(sodium_pad, sn_sodium_pad) + SN_EXPORT_FUNCTION(sodium_unpad, sn_sodium_unpad) + + // crypto_aead + + SN_EXPORT_FUNCTION(crypto_aead_xchacha20poly1305_ietf_keygen, sn_crypto_aead_xchacha20poly1305_ietf_keygen) + SN_EXPORT_FUNCTION(crypto_aead_xchacha20poly1305_ietf_encrypt, sn_crypto_aead_xchacha20poly1305_ietf_encrypt) + SN_EXPORT_FUNCTION(crypto_aead_xchacha20poly1305_ietf_decrypt, sn_crypto_aead_xchacha20poly1305_ietf_decrypt) + SN_EXPORT_FUNCTION(crypto_aead_xchacha20poly1305_ietf_encrypt_detached, sn_crypto_aead_xchacha20poly1305_ietf_encrypt_detached) + SN_EXPORT_FUNCTION(crypto_aead_xchacha20poly1305_ietf_decrypt_detached, sn_crypto_aead_xchacha20poly1305_ietf_decrypt_detached) + SN_EXPORT_UINT32(crypto_aead_xchacha20poly1305_ietf_ABYTES, crypto_aead_xchacha20poly1305_ietf_ABYTES) + SN_EXPORT_UINT32(crypto_aead_xchacha20poly1305_ietf_KEYBYTES, crypto_aead_xchacha20poly1305_ietf_KEYBYTES) + SN_EXPORT_UINT32(crypto_aead_xchacha20poly1305_ietf_NPUBBYTES, crypto_aead_xchacha20poly1305_ietf_NPUBBYTES) + SN_EXPORT_UINT32(crypto_aead_xchacha20poly1305_ietf_NSECBYTES, crypto_aead_xchacha20poly1305_ietf_NSECBYTES) + SN_EXPORT_UINT64(crypto_aead_xchacha20poly1305_ietf_MESSAGEBYTES_MAX, crypto_aead_xchacha20poly1305_ietf_MESSAGEBYTES_MAX) + + SN_EXPORT_FUNCTION(crypto_aead_chacha20poly1305_ietf_keygen, sn_crypto_aead_chacha20poly1305_ietf_keygen) + SN_EXPORT_FUNCTION(crypto_aead_chacha20poly1305_ietf_encrypt, sn_crypto_aead_chacha20poly1305_ietf_encrypt) + SN_EXPORT_FUNCTION(crypto_aead_chacha20poly1305_ietf_decrypt, sn_crypto_aead_chacha20poly1305_ietf_decrypt) + SN_EXPORT_FUNCTION(crypto_aead_chacha20poly1305_ietf_encrypt_detached, sn_crypto_aead_chacha20poly1305_ietf_encrypt_detached) + SN_EXPORT_FUNCTION(crypto_aead_chacha20poly1305_ietf_decrypt_detached, sn_crypto_aead_chacha20poly1305_ietf_decrypt_detached) + SN_EXPORT_UINT32(crypto_aead_chacha20poly1305_ietf_ABYTES, crypto_aead_chacha20poly1305_ietf_ABYTES) + SN_EXPORT_UINT32(crypto_aead_chacha20poly1305_ietf_KEYBYTES, crypto_aead_chacha20poly1305_ietf_KEYBYTES) + SN_EXPORT_UINT32(crypto_aead_chacha20poly1305_ietf_NPUBBYTES, crypto_aead_chacha20poly1305_ietf_NPUBBYTES) + SN_EXPORT_UINT32(crypto_aead_chacha20poly1305_ietf_NSECBYTES, crypto_aead_chacha20poly1305_ietf_NSECBYTES) + SN_EXPORT_UINT64(crypto_aead_chacha20poly1305_ietf_MESSAGEBYTES_MAX, crypto_aead_chacha20poly1305_ietf_MESSAGEBYTES_MAX) + + // crypto_auth + + SN_EXPORT_FUNCTION(crypto_auth, sn_crypto_auth) + SN_EXPORT_FUNCTION(crypto_auth_verify, sn_crypto_auth_verify) + SN_EXPORT_UINT32(crypto_auth_BYTES, crypto_auth_BYTES) + SN_EXPORT_UINT32(crypto_auth_KEYBYTES, crypto_auth_KEYBYTES) + SN_EXPORT_STRING(crypto_auth_PRIMITIVE, crypto_auth_PRIMITIVE) + + // crypto_box + + SN_EXPORT_FUNCTION(crypto_box_keypair, sn_crypto_box_keypair) + SN_EXPORT_FUNCTION(crypto_box_seed_keypair, sn_crypto_box_seed_keypair) + SN_EXPORT_FUNCTION(crypto_box_easy, sn_crypto_box_easy) + SN_EXPORT_FUNCTION(crypto_box_open_easy, sn_crypto_box_open_easy) + SN_EXPORT_FUNCTION(crypto_box_detached, sn_crypto_box_detached) + SN_EXPORT_FUNCTION(crypto_box_open_detached, sn_crypto_box_open_detached) + SN_EXPORT_FUNCTION(crypto_box_seal, sn_crypto_box_seal) + SN_EXPORT_FUNCTION(crypto_box_seal_open, sn_crypto_box_seal_open) + SN_EXPORT_UINT32(crypto_box_SEEDBYTES, crypto_box_SEEDBYTES) + SN_EXPORT_UINT32(crypto_box_PUBLICKEYBYTES, crypto_box_PUBLICKEYBYTES) + SN_EXPORT_UINT32(crypto_box_SECRETKEYBYTES, crypto_box_SECRETKEYBYTES) + SN_EXPORT_UINT32(crypto_box_NONCEBYTES, crypto_box_NONCEBYTES) + SN_EXPORT_UINT32(crypto_box_MACBYTES, crypto_box_MACBYTES) + SN_EXPORT_UINT32(crypto_box_SEALBYTES, crypto_box_SEALBYTES) + SN_EXPORT_STRING(crypto_box_PRIMITIVE, crypto_box_PRIMITIVE) + + // crypto_core + + SN_EXPORT_FUNCTION(crypto_core_ed25519_is_valid_point, sn_crypto_core_ed25519_is_valid_point) + SN_EXPORT_FUNCTION(crypto_core_ed25519_from_uniform, sn_crypto_core_ed25519_from_uniform) + SN_EXPORT_FUNCTION(crypto_core_ed25519_add, sn_crypto_core_ed25519_add) + SN_EXPORT_FUNCTION(crypto_core_ed25519_sub, sn_crypto_core_ed25519_sub) + SN_EXPORT_FUNCTION(crypto_core_ed25519_scalar_random, sn_crypto_core_ed25519_scalar_random) + SN_EXPORT_FUNCTION(crypto_core_ed25519_scalar_reduce, sn_crypto_core_ed25519_scalar_reduce) + SN_EXPORT_FUNCTION(crypto_core_ed25519_scalar_invert, sn_crypto_core_ed25519_scalar_invert) + SN_EXPORT_FUNCTION(crypto_core_ed25519_scalar_negate, sn_crypto_core_ed25519_scalar_negate) + SN_EXPORT_FUNCTION(crypto_core_ed25519_scalar_complement, sn_crypto_core_ed25519_scalar_complement) + SN_EXPORT_FUNCTION(crypto_core_ed25519_scalar_add, sn_crypto_core_ed25519_scalar_add) + SN_EXPORT_FUNCTION(crypto_core_ed25519_scalar_sub, sn_crypto_core_ed25519_scalar_sub) + SN_EXPORT_UINT32(crypto_core_ed25519_BYTES, crypto_core_ed25519_BYTES) + SN_EXPORT_UINT32(crypto_core_ed25519_UNIFORMBYTES, crypto_core_ed25519_UNIFORMBYTES) + SN_EXPORT_UINT32(crypto_core_ed25519_SCALARBYTES, crypto_core_ed25519_SCALARBYTES) + SN_EXPORT_UINT32(crypto_core_ed25519_NONREDUCEDSCALARBYTES, crypto_core_ed25519_NONREDUCEDSCALARBYTES) + + // crypto_kdf + + SN_EXPORT_FUNCTION(crypto_kdf_keygen, sn_crypto_kdf_keygen) + SN_EXPORT_FUNCTION(crypto_kdf_derive_from_key, sn_crypto_kdf_derive_from_key) + SN_EXPORT_UINT32(crypto_kdf_BYTES_MIN, crypto_kdf_BYTES_MIN) + SN_EXPORT_UINT32(crypto_kdf_BYTES_MAX, crypto_kdf_BYTES_MAX) + SN_EXPORT_UINT32(crypto_kdf_CONTEXTBYTES, crypto_kdf_CONTEXTBYTES) + SN_EXPORT_UINT32(crypto_kdf_KEYBYTES, crypto_kdf_KEYBYTES) + SN_EXPORT_STRING(crypto_kdf_PRIMITIVE, crypto_kdf_PRIMITIVE) + + // crypto_kx + + SN_EXPORT_FUNCTION(crypto_kx_keypair, sn_crypto_kx_keypair) + SN_EXPORT_FUNCTION(crypto_kx_seed_keypair, sn_crypto_kx_seed_keypair) + SN_EXPORT_FUNCTION(crypto_kx_client_session_keys, sn_crypto_kx_client_session_keys) + SN_EXPORT_FUNCTION(crypto_kx_server_session_keys, sn_crypto_kx_server_session_keys) + SN_EXPORT_UINT32(crypto_kx_PUBLICKEYBYTES, crypto_kx_PUBLICKEYBYTES) + SN_EXPORT_UINT32(crypto_kx_SECRETKEYBYTES, crypto_kx_SECRETKEYBYTES) + SN_EXPORT_UINT32(crypto_kx_SEEDBYTES, crypto_kx_SEEDBYTES) + SN_EXPORT_UINT32(crypto_kx_SESSIONKEYBYTES, crypto_kx_SESSIONKEYBYTES) + SN_EXPORT_STRING(crypto_kx_PRIMITIVE, crypto_kx_PRIMITIVE) + + // crypto_generichash + + SN_EXPORT_FUNCTION(crypto_generichash, sn_crypto_generichash) + SN_EXPORT_FUNCTION(crypto_generichash_batch, sn_crypto_generichash_batch) + SN_EXPORT_FUNCTION(crypto_generichash_keygen, sn_crypto_generichash_keygen) + SN_EXPORT_FUNCTION(crypto_generichash_init, sn_crypto_generichash_init) + SN_EXPORT_FUNCTION(crypto_generichash_update, sn_crypto_generichash_update) + SN_EXPORT_FUNCTION(crypto_generichash_final, sn_crypto_generichash_final) + SN_EXPORT_UINT32(crypto_generichash_STATEBYTES, sizeof(crypto_generichash_state)) + SN_EXPORT_STRING(crypto_generichash_PRIMITIVE, crypto_generichash_PRIMITIVE) + SN_EXPORT_UINT32(crypto_generichash_BYTES_MIN, crypto_generichash_BYTES_MIN) + SN_EXPORT_UINT32(crypto_generichash_BYTES_MAX, crypto_generichash_BYTES_MAX) + SN_EXPORT_UINT32(crypto_generichash_BYTES, crypto_generichash_BYTES) + SN_EXPORT_UINT32(crypto_generichash_KEYBYTES_MIN, crypto_generichash_KEYBYTES_MIN) + SN_EXPORT_UINT32(crypto_generichash_KEYBYTES_MAX, crypto_generichash_KEYBYTES_MAX) + SN_EXPORT_UINT32(crypto_generichash_KEYBYTES, crypto_generichash_KEYBYTES) + + // crypto_hash + + SN_EXPORT_FUNCTION(crypto_hash, sn_crypto_hash) + SN_EXPORT_UINT32(crypto_hash_BYTES, crypto_hash_BYTES) + SN_EXPORT_STRING(crypto_hash_PRIMITIVE, crypto_hash_PRIMITIVE) + + SN_EXPORT_FUNCTION(crypto_hash_sha256, sn_crypto_hash_sha256) + SN_EXPORT_FUNCTION(crypto_hash_sha256_init, sn_crypto_hash_sha256_init) + SN_EXPORT_FUNCTION(crypto_hash_sha256_update, sn_crypto_hash_sha256_update) + SN_EXPORT_FUNCTION(crypto_hash_sha256_final, sn_crypto_hash_sha256_final) + SN_EXPORT_UINT32(crypto_hash_sha256_STATEBYTES, sizeof(crypto_hash_sha256_state)) + SN_EXPORT_UINT32(crypto_hash_sha256_BYTES, crypto_hash_sha256_BYTES) + + SN_EXPORT_FUNCTION(crypto_hash_sha512, sn_crypto_hash_sha512) + SN_EXPORT_FUNCTION(crypto_hash_sha512_init, sn_crypto_hash_sha512_init) + SN_EXPORT_FUNCTION(crypto_hash_sha512_update, sn_crypto_hash_sha512_update) + SN_EXPORT_FUNCTION(crypto_hash_sha512_final, sn_crypto_hash_sha512_final) + SN_EXPORT_UINT32(crypto_hash_sha512_STATEBYTES, sizeof(crypto_hash_sha512_state)) + SN_EXPORT_UINT32(crypto_hash_sha512_BYTES, crypto_hash_sha512_BYTES) + + // crypto_onetimeauth + + SN_EXPORT_FUNCTION(crypto_onetimeauth, sn_crypto_onetimeauth) + SN_EXPORT_FUNCTION(crypto_onetimeauth_verify, sn_crypto_onetimeauth_verify) + SN_EXPORT_FUNCTION(crypto_onetimeauth_init, sn_crypto_onetimeauth_init) + SN_EXPORT_FUNCTION(crypto_onetimeauth_update, sn_crypto_onetimeauth_update) + SN_EXPORT_FUNCTION(crypto_onetimeauth_final, sn_crypto_onetimeauth_final) + SN_EXPORT_UINT32(crypto_onetimeauth_STATEBYTES, sizeof(crypto_onetimeauth_state)) + SN_EXPORT_UINT32(crypto_onetimeauth_BYTES, crypto_onetimeauth_BYTES) + SN_EXPORT_UINT32(crypto_onetimeauth_KEYBYTES, crypto_onetimeauth_KEYBYTES) + SN_EXPORT_STRING(crypto_onetimeauth_PRIMITIVE, crypto_onetimeauth_PRIMITIVE) + + // crypto_pwhash + + SN_EXPORT_FUNCTION(crypto_pwhash, sn_crypto_pwhash) + SN_EXPORT_FUNCTION(crypto_pwhash_str, sn_crypto_pwhash_str) + SN_EXPORT_FUNCTION(crypto_pwhash_str_verify, sn_crypto_pwhash_str_verify) + SN_EXPORT_FUNCTION(crypto_pwhash_str_needs_rehash, sn_crypto_pwhash_str_needs_rehash) + SN_EXPORT_FUNCTION(crypto_pwhash_async, sn_crypto_pwhash_async) + SN_EXPORT_FUNCTION(crypto_pwhash_str_async, sn_crypto_pwhash_str_async) + SN_EXPORT_FUNCTION(crypto_pwhash_str_verify_async, sn_crypto_pwhash_str_verify_async) + SN_EXPORT_UINT32(crypto_pwhash_ALG_ARGON2I13, crypto_pwhash_ALG_ARGON2I13) + SN_EXPORT_UINT32(crypto_pwhash_ALG_ARGON2ID13, crypto_pwhash_ALG_ARGON2ID13) + SN_EXPORT_UINT32(crypto_pwhash_ALG_DEFAULT, crypto_pwhash_ALG_DEFAULT) + SN_EXPORT_UINT32(crypto_pwhash_BYTES_MIN, crypto_pwhash_BYTES_MIN) + SN_EXPORT_UINT32(crypto_pwhash_BYTES_MAX, crypto_pwhash_BYTES_MAX) + SN_EXPORT_UINT32(crypto_pwhash_PASSWD_MIN, crypto_pwhash_PASSWD_MIN) + SN_EXPORT_UINT32(crypto_pwhash_PASSWD_MAX, crypto_pwhash_PASSWD_MAX) + SN_EXPORT_UINT32(crypto_pwhash_SALTBYTES, crypto_pwhash_SALTBYTES) + SN_EXPORT_UINT32(crypto_pwhash_STRBYTES, crypto_pwhash_STRBYTES) + SN_EXPORT_STRING(crypto_pwhash_STRPREFIX, crypto_pwhash_STRPREFIX) + SN_EXPORT_UINT32(crypto_pwhash_OPSLIMIT_MIN, crypto_pwhash_OPSLIMIT_MIN) + SN_EXPORT_UINT32(crypto_pwhash_OPSLIMIT_MAX, crypto_pwhash_OPSLIMIT_MAX) + SN_EXPORT_UINT32(crypto_pwhash_MEMLIMIT_MIN, crypto_pwhash_MEMLIMIT_MIN) + SN_EXPORT_UINT32(crypto_pwhash_MEMLIMIT_MAX, crypto_pwhash_MEMLIMIT_MAX) + SN_EXPORT_UINT32(crypto_pwhash_OPSLIMIT_INTERACTIVE, crypto_pwhash_OPSLIMIT_INTERACTIVE) + SN_EXPORT_UINT32(crypto_pwhash_MEMLIMIT_INTERACTIVE, crypto_pwhash_MEMLIMIT_INTERACTIVE) + SN_EXPORT_UINT32(crypto_pwhash_OPSLIMIT_MODERATE, crypto_pwhash_OPSLIMIT_MODERATE) + SN_EXPORT_UINT32(crypto_pwhash_MEMLIMIT_MODERATE, crypto_pwhash_MEMLIMIT_MODERATE) + SN_EXPORT_UINT32(crypto_pwhash_OPSLIMIT_SENSITIVE, crypto_pwhash_OPSLIMIT_SENSITIVE) + SN_EXPORT_UINT32(crypto_pwhash_MEMLIMIT_SENSITIVE, crypto_pwhash_MEMLIMIT_SENSITIVE) + SN_EXPORT_STRING(crypto_pwhash_PRIMITIVE, crypto_pwhash_PRIMITIVE) + + SN_EXPORT_FUNCTION(crypto_pwhash_scryptsalsa208sha256, sn_crypto_pwhash_scryptsalsa208sha256) + SN_EXPORT_FUNCTION(crypto_pwhash_scryptsalsa208sha256_str, sn_crypto_pwhash_scryptsalsa208sha256_str) + SN_EXPORT_FUNCTION(crypto_pwhash_scryptsalsa208sha256_str_verify, sn_crypto_pwhash_scryptsalsa208sha256_str_verify) + SN_EXPORT_FUNCTION(crypto_pwhash_scryptsalsa208sha256_str_needs_rehash, sn_crypto_pwhash_scryptsalsa208sha256_str_needs_rehash) + SN_EXPORT_FUNCTION(crypto_pwhash_scryptsalsa208sha256_async, sn_crypto_pwhash_scryptsalsa208sha256_async) + SN_EXPORT_FUNCTION(crypto_pwhash_scryptsalsa208sha256_str_async, sn_crypto_pwhash_scryptsalsa208sha256_str_async) + SN_EXPORT_FUNCTION(crypto_pwhash_scryptsalsa208sha256_str_verify_async, sn_crypto_pwhash_scryptsalsa208sha256_str_verify_async) + SN_EXPORT_UINT32(crypto_pwhash_scryptsalsa208sha256_BYTES_MIN, crypto_pwhash_scryptsalsa208sha256_BYTES_MIN) + SN_EXPORT_UINT32(crypto_pwhash_scryptsalsa208sha256_BYTES_MAX, crypto_pwhash_scryptsalsa208sha256_BYTES_MAX) + SN_EXPORT_UINT32(crypto_pwhash_scryptsalsa208sha256_PASSWD_MIN, crypto_pwhash_scryptsalsa208sha256_PASSWD_MIN) + SN_EXPORT_UINT32(crypto_pwhash_scryptsalsa208sha256_PASSWD_MAX, crypto_pwhash_scryptsalsa208sha256_PASSWD_MAX) + SN_EXPORT_UINT32(crypto_pwhash_scryptsalsa208sha256_SALTBYTES, crypto_pwhash_scryptsalsa208sha256_SALTBYTES) + SN_EXPORT_UINT32(crypto_pwhash_scryptsalsa208sha256_STRBYTES, crypto_pwhash_scryptsalsa208sha256_STRBYTES) + SN_EXPORT_STRING(crypto_pwhash_scryptsalsa208sha256_STRPREFIX, crypto_pwhash_scryptsalsa208sha256_STRPREFIX) + SN_EXPORT_UINT32(crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN) + SN_EXPORT_UINT32(crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX) + SN_EXPORT_UINT32(crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN, crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN) + SN_EXPORT_UINT32(crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX, crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX) + SN_EXPORT_UINT32(crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_INTERACTIVE, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_INTERACTIVE) + SN_EXPORT_UINT32(crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_INTERACTIVE, crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_INTERACTIVE) + SN_EXPORT_UINT32(crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_SENSITIVE, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_SENSITIVE) + SN_EXPORT_UINT32(crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_SENSITIVE, crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_SENSITIVE) + + // crypto_scalarmult + + SN_EXPORT_FUNCTION(crypto_scalarmult_base, sn_crypto_scalarmult_base) + SN_EXPORT_FUNCTION(crypto_scalarmult, sn_crypto_scalarmult) + SN_EXPORT_STRING(crypto_scalarmult_PRIMITIVE, crypto_scalarmult_PRIMITIVE) + SN_EXPORT_UINT32(crypto_scalarmult_BYTES, crypto_scalarmult_BYTES) + SN_EXPORT_UINT32(crypto_scalarmult_SCALARBYTES, crypto_scalarmult_SCALARBYTES) + + SN_EXPORT_FUNCTION(crypto_scalarmult_ed25519_base, sn_crypto_scalarmult_ed25519_base) + SN_EXPORT_FUNCTION(crypto_scalarmult_ed25519, sn_crypto_scalarmult_ed25519) + SN_EXPORT_FUNCTION(crypto_scalarmult_ed25519_base_noclamp, sn_crypto_scalarmult_ed25519_base_noclamp) + SN_EXPORT_FUNCTION(crypto_scalarmult_ed25519_noclamp, sn_crypto_scalarmult_ed25519_noclamp) + SN_EXPORT_UINT32(crypto_scalarmult_ed25519_BYTES, crypto_scalarmult_ed25519_BYTES) + SN_EXPORT_UINT32(crypto_scalarmult_ed25519_SCALARBYTES, crypto_scalarmult_ed25519_SCALARBYTES) + + // crypto_secretbox + + SN_EXPORT_FUNCTION(crypto_secretbox_easy, sn_crypto_secretbox_easy) + SN_EXPORT_FUNCTION(crypto_secretbox_open_easy, sn_crypto_secretbox_open_easy) + SN_EXPORT_FUNCTION(crypto_secretbox_detached, sn_crypto_secretbox_detached) + SN_EXPORT_FUNCTION(crypto_secretbox_open_detached, sn_crypto_secretbox_open_detached) + SN_EXPORT_UINT32(crypto_secretbox_KEYBYTES, crypto_secretbox_KEYBYTES) + SN_EXPORT_UINT32(crypto_secretbox_NONCEBYTES, crypto_secretbox_NONCEBYTES) + SN_EXPORT_UINT32(crypto_secretbox_MACBYTES, crypto_secretbox_MACBYTES) + SN_EXPORT_STRING(crypto_secretbox_PRIMITIVE, crypto_secretbox_PRIMITIVE) + + // crypto_secretstream + + SN_EXPORT_FUNCTION(crypto_secretstream_xchacha20poly1305_keygen, sn_crypto_secretstream_xchacha20poly1305_keygen) + SN_EXPORT_FUNCTION(crypto_secretstream_xchacha20poly1305_init_push, sn_crypto_secretstream_xchacha20poly1305_init_push) + SN_EXPORT_FUNCTION(crypto_secretstream_xchacha20poly1305_init_pull, sn_crypto_secretstream_xchacha20poly1305_init_pull) + SN_EXPORT_FUNCTION(crypto_secretstream_xchacha20poly1305_push, sn_crypto_secretstream_xchacha20poly1305_push) + SN_EXPORT_FUNCTION(crypto_secretstream_xchacha20poly1305_pull, sn_crypto_secretstream_xchacha20poly1305_pull) + SN_EXPORT_FUNCTION(crypto_secretstream_xchacha20poly1305_rekey, sn_crypto_secretstream_xchacha20poly1305_rekey) + SN_EXPORT_UINT32(crypto_secretstream_xchacha20poly1305_STATEBYTES, sizeof(crypto_secretstream_xchacha20poly1305_state)) + SN_EXPORT_UINT32(crypto_secretstream_xchacha20poly1305_ABYTES, crypto_secretstream_xchacha20poly1305_ABYTES) + SN_EXPORT_UINT32(crypto_secretstream_xchacha20poly1305_HEADERBYTES, crypto_secretstream_xchacha20poly1305_HEADERBYTES) + SN_EXPORT_UINT32(crypto_secretstream_xchacha20poly1305_KEYBYTES, crypto_secretstream_xchacha20poly1305_KEYBYTES) + SN_EXPORT_UINT32(crypto_secretstream_xchacha20poly1305_TAGBYTES, 1) + SN_EXPORT_UINT64(crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX, crypto_secretstream_xchacha20poly1305_MESSAGEBYTES_MAX) + SN_EXPORT_UINT32(crypto_secretstream_xchacha20poly1305_TAG_MESSAGE, crypto_secretstream_xchacha20poly1305_TAG_MESSAGE) + SN_EXPORT_UINT32(crypto_secretstream_xchacha20poly1305_TAG_PUSH, crypto_secretstream_xchacha20poly1305_TAG_PUSH) + SN_EXPORT_UINT32(crypto_secretstream_xchacha20poly1305_TAG_REKEY, crypto_secretstream_xchacha20poly1305_TAG_REKEY) + SN_EXPORT_UINT32(crypto_secretstream_xchacha20poly1305_TAG_FINAL, crypto_secretstream_xchacha20poly1305_TAG_FINAL) + + // crypto_shorthash + + SN_EXPORT_FUNCTION(crypto_shorthash, sn_crypto_shorthash) + SN_EXPORT_UINT32(crypto_shorthash_BYTES, crypto_shorthash_BYTES) + SN_EXPORT_UINT32(crypto_shorthash_KEYBYTES, crypto_shorthash_KEYBYTES) + SN_EXPORT_STRING(crypto_shorthash_PRIMITIVE, crypto_shorthash_PRIMITIVE) + + // crypto_sign + + SN_EXPORT_FUNCTION(crypto_sign_keypair, sn_crypto_sign_keypair) + SN_EXPORT_FUNCTION(crypto_sign_seed_keypair, sn_crypto_sign_seed_keypair) + SN_EXPORT_FUNCTION(crypto_sign, sn_crypto_sign) + SN_EXPORT_FUNCTION(crypto_sign_open, sn_crypto_sign_open) + SN_EXPORT_FUNCTION(crypto_sign_detached, sn_crypto_sign_detached) + SN_EXPORT_FUNCTION(crypto_sign_verify_detached, sn_crypto_sign_verify_detached) + SN_EXPORT_FUNCTION(crypto_sign_ed25519_sk_to_pk, sn_crypto_sign_ed25519_sk_to_pk) + SN_EXPORT_FUNCTION(crypto_sign_ed25519_pk_to_curve25519, sn_crypto_sign_ed25519_pk_to_curve25519) + SN_EXPORT_FUNCTION(crypto_sign_ed25519_sk_to_curve25519, sn_crypto_sign_ed25519_sk_to_curve25519) + SN_EXPORT_UINT32(crypto_sign_SEEDBYTES, crypto_sign_SEEDBYTES) + SN_EXPORT_UINT32(crypto_sign_PUBLICKEYBYTES, crypto_sign_PUBLICKEYBYTES) + SN_EXPORT_UINT32(crypto_sign_SECRETKEYBYTES, crypto_sign_SECRETKEYBYTES) + SN_EXPORT_UINT32(crypto_sign_BYTES, crypto_sign_BYTES) + + // crypto_stream + + SN_EXPORT_FUNCTION(crypto_stream, sn_crypto_stream) + SN_EXPORT_UINT32(crypto_stream_KEYBYTES, crypto_stream_KEYBYTES) + SN_EXPORT_UINT32(crypto_stream_NONCEBYTES, crypto_stream_NONCEBYTES) + SN_EXPORT_STRING(crypto_stream_PRIMITIVE, crypto_stream_PRIMITIVE) + + SN_EXPORT_FUNCTION(crypto_stream_xor, sn_crypto_stream_xor) + SN_EXPORT_FUNCTION(crypto_stream_xor_init, sn_crypto_stream_xor_wrap_init) + SN_EXPORT_FUNCTION(crypto_stream_xor_update, sn_crypto_stream_xor_wrap_update) + SN_EXPORT_FUNCTION(crypto_stream_xor_final, sn_crypto_stream_xor_wrap_final) + SN_EXPORT_UINT32(crypto_stream_xor_STATEBYTES, sizeof(sn_crypto_stream_xor_state)) + + SN_EXPORT_FUNCTION(crypto_stream_chacha20, sn_crypto_stream_chacha20) + SN_EXPORT_UINT32(crypto_stream_chacha20_KEYBYTES, crypto_stream_chacha20_KEYBYTES) + SN_EXPORT_UINT32(crypto_stream_chacha20_NONCEBYTES, crypto_stream_chacha20_NONCEBYTES) + SN_EXPORT_UINT64(crypto_stream_chacha20_MESSAGEBYTES_MAX, crypto_stream_chacha20_MESSAGEBYTES_MAX) + + SN_EXPORT_FUNCTION(crypto_stream_chacha20_xor, sn_crypto_stream_chacha20_xor) + SN_EXPORT_FUNCTION(crypto_stream_chacha20_xor_ic, sn_crypto_stream_chacha20_xor_ic) + SN_EXPORT_FUNCTION(crypto_stream_chacha20_xor_init, sn_crypto_stream_chacha20_xor_wrap_init) + SN_EXPORT_FUNCTION(crypto_stream_chacha20_xor_update, sn_crypto_stream_chacha20_xor_wrap_update) + SN_EXPORT_FUNCTION(crypto_stream_chacha20_xor_final, sn_crypto_stream_chacha20_xor_wrap_final) + SN_EXPORT_UINT32(crypto_stream_chacha20_xor_STATEBYTES, sizeof(sn_crypto_stream_chacha20_xor_state)) + + SN_EXPORT_FUNCTION(crypto_stream_chacha20_ietf, sn_crypto_stream_chacha20_ietf) + SN_EXPORT_UINT32(crypto_stream_chacha20_ietf_KEYBYTES, crypto_stream_chacha20_ietf_KEYBYTES) + SN_EXPORT_UINT32(crypto_stream_chacha20_ietf_NONCEBYTES, crypto_stream_chacha20_ietf_NONCEBYTES) + SN_EXPORT_UINT64(crypto_stream_chacha20_ietf_MESSAGEBYTES_MAX, crypto_stream_chacha20_ietf_MESSAGEBYTES_MAX) + SN_EXPORT_UINT32(crypto_stream_chacha20_ietf_xor_STATEBYTES, sizeof(sn_crypto_stream_chacha20_ietf_xor_state)) + + SN_EXPORT_FUNCTION(crypto_stream_chacha20_ietf_xor, sn_crypto_stream_chacha20_ietf_xor) + SN_EXPORT_FUNCTION(crypto_stream_chacha20_ietf_xor_ic, sn_crypto_stream_chacha20_ietf_xor_ic) + SN_EXPORT_FUNCTION(crypto_stream_chacha20_ietf_xor_init, sn_crypto_stream_chacha20_ietf_xor_wrap_init) + SN_EXPORT_FUNCTION(crypto_stream_chacha20_ietf_xor_update, sn_crypto_stream_chacha20_ietf_xor_wrap_update) + SN_EXPORT_FUNCTION(crypto_stream_chacha20_ietf_xor_final, sn_crypto_stream_chacha20_ietf_xor_wrap_final) + + SN_EXPORT_FUNCTION(crypto_stream_xchacha20, sn_crypto_stream_xchacha20) + SN_EXPORT_UINT32(crypto_stream_xchacha20_KEYBYTES, crypto_stream_xchacha20_KEYBYTES) + SN_EXPORT_UINT32(crypto_stream_xchacha20_NONCEBYTES, crypto_stream_xchacha20_NONCEBYTES) + SN_EXPORT_UINT64(crypto_stream_xchacha20_MESSAGEBYTES_MAX, crypto_stream_xchacha20_MESSAGEBYTES_MAX) + + SN_EXPORT_FUNCTION(crypto_stream_xchacha20_xor, sn_crypto_stream_xchacha20_xor) + SN_EXPORT_FUNCTION(crypto_stream_xchacha20_xor_ic, sn_crypto_stream_xchacha20_xor_ic) + SN_EXPORT_FUNCTION(crypto_stream_xchacha20_xor_init, sn_crypto_stream_xchacha20_xor_wrap_init) + SN_EXPORT_FUNCTION(crypto_stream_xchacha20_xor_update, sn_crypto_stream_xchacha20_xor_wrap_update) + SN_EXPORT_FUNCTION(crypto_stream_xchacha20_xor_final, sn_crypto_stream_xchacha20_xor_wrap_final) + SN_EXPORT_FUNCTION(crypto_stream_xchacha20, sn_crypto_stream_xchacha20) + SN_EXPORT_UINT32(crypto_stream_xchacha20_xor_STATEBYTES, sizeof(sn_crypto_stream_xchacha20_xor_state)) + + SN_EXPORT_FUNCTION(crypto_stream_salsa20, sn_crypto_stream_salsa20) + SN_EXPORT_UINT32(crypto_stream_salsa20_KEYBYTES, crypto_stream_salsa20_KEYBYTES) + SN_EXPORT_UINT32(crypto_stream_salsa20_NONCEBYTES, crypto_stream_salsa20_NONCEBYTES) + SN_EXPORT_UINT64(crypto_stream_salsa20_MESSAGEBYTES_MAX, crypto_stream_salsa20_MESSAGEBYTES_MAX) + + SN_EXPORT_FUNCTION(crypto_stream_salsa20_xor, sn_crypto_stream_salsa20_xor) + SN_EXPORT_FUNCTION(crypto_stream_salsa20_xor_ic, sn_crypto_stream_salsa20_xor_ic) + SN_EXPORT_FUNCTION(crypto_stream_salsa20_xor_init, sn_crypto_stream_salsa20_xor_wrap_init) + SN_EXPORT_FUNCTION(crypto_stream_salsa20_xor_update, sn_crypto_stream_salsa20_xor_wrap_update) + SN_EXPORT_FUNCTION(crypto_stream_salsa20_xor_final, sn_crypto_stream_salsa20_xor_wrap_final) + SN_EXPORT_UINT32(crypto_stream_salsa20_xor_STATEBYTES, sizeof(sn_crypto_stream_salsa20_xor_state)) + + // extensions + + // tweak + + SN_EXPORT_FUNCTION(extension_tweak_ed25519_base, sn_extension_tweak_ed25519_base) + SN_EXPORT_FUNCTION(extension_tweak_ed25519_sign_detached, sn_extension_tweak_ed25519_sign_detached) + SN_EXPORT_FUNCTION(extension_tweak_ed25519_sk_to_scalar, sn_extension_tweak_ed25519_sk_to_scalar) + SN_EXPORT_FUNCTION(extension_tweak_ed25519_scalar, sn_extension_tweak_ed25519_scalar) + SN_EXPORT_FUNCTION(extension_tweak_ed25519_pk, sn_extension_tweak_ed25519_pk) + SN_EXPORT_FUNCTION(extension_tweak_ed25519_keypair, sn_extension_tweak_ed25519_keypair) + SN_EXPORT_FUNCTION(extension_tweak_ed25519_scalar_add, sn_extension_tweak_ed25519_scalar_add) + SN_EXPORT_FUNCTION(extension_tweak_ed25519_pk_add, sn_extension_tweak_ed25519_pk_add) + SN_EXPORT_FUNCTION(extension_tweak_ed25519_keypair_add, sn_extension_tweak_ed25519_keypair_add) + SN_EXPORT_UINT32(extension_tweak_ed25519_BYTES, sn__extension_tweak_ed25519_BYTES) + SN_EXPORT_UINT32(extension_tweak_ed25519_SCALARBYTES, sn__extension_tweak_ed25519_SCALARBYTES) + + // pbkdf2 + + SN_EXPORT_FUNCTION(extension_pbkdf2_sha512, sn_extension_pbkdf2_sha512) + SN_EXPORT_FUNCTION(extension_pbkdf2_sha512_async, sn_extension_pbkdf2_sha512_async) + SN_EXPORT_UINT32(extension_pbkdf2_sha512_SALTBYTES, sn__extension_pbkdf2_sha512_SALTBYTES) + SN_EXPORT_UINT32(extension_pbkdf2_sha512_HASHBYTES, sn__extension_pbkdf2_sha512_HASHBYTES) + SN_EXPORT_UINT32(extension_pbkdf2_sha512_ITERATIONS_MIN, sn__extension_pbkdf2_sha512_ITERATIONS_MIN) + SN_EXPORT_UINT64(extension_pbkdf2_sha512_BYTES_MAX, sn__extension_pbkdf2_sha512_BYTES_MAX) + + return exports; +} + +static napi_value Init(napi_env env, napi_value exports) { + return create_sodium_native(env); +} + +NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/node_modules/sodium-native/extensions/pbkdf2/pbkdf2.c b/node_modules/sodium-native/extensions/pbkdf2/pbkdf2.c new file mode 100644 index 000000000..6968b18af --- /dev/null +++ b/node_modules/sodium-native/extensions/pbkdf2/pbkdf2.c @@ -0,0 +1,90 @@ +/*- + * Copyright 2005,2007,2009 Colin Percival + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. + */ + +/* + * Adapated from libsodium/crypto_pwhash/scryptsalsa208sha256/pbkdf-sha256.c + */ + +#include +#include + +#include "pbkdf2.h" + +/** + * pbkdf2_sha512(passwd, passwdlen, salt, saltlen, c, buf, dkLen): + * Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and + * write the output to buf. The value dkLen must be at most 32 * (2^32 - 1). + */ +int +sn__extension_pbkdf2_sha512(const unsigned char *passwd, size_t passwdlen, + const unsigned char *salt, size_t saltlen, uint64_t c, + unsigned char *buf, size_t dkLen) +{ + crypto_auth_hmacsha512_state PShctx, hctx; + size_t i; + unsigned char ivec[4]; + unsigned char U[64]; + unsigned char T[64]; + uint64_t j; + unsigned int k; + size_t clen; + + if (dkLen > sn__extension_pbkdf2_sha512_BYTES_MAX) { + return -1; + } + + crypto_auth_hmacsha512_init(&PShctx, passwd, passwdlen); + crypto_auth_hmacsha512_update(&PShctx, salt, saltlen); + + for (i = 0; i * crypto_auth_hmacsha512_BYTES < dkLen; i++) { + SN_PBKDF2_STORE32_BE(ivec, (uint32_t)(i + 1)); + memcpy(&hctx, &PShctx, sizeof(crypto_auth_hmacsha512_state)); + crypto_auth_hmacsha512_update(&hctx, ivec, 4); + crypto_auth_hmacsha512_final(&hctx, U); + + memcpy(T, U, crypto_auth_hmacsha512_BYTES); + /* LCOV_EXCL_START */ + for (j = 2; j <= c; j++) { + crypto_auth_hmacsha512_init(&hctx, passwd, passwdlen); + crypto_auth_hmacsha512_update(&hctx, U, crypto_auth_hmacsha512_BYTES); + crypto_auth_hmacsha512_final(&hctx, U); + + for (k = 0; k < crypto_auth_hmacsha512_BYTES; k++) { + T[k] ^= U[k]; + } + } + /* LCOV_EXCL_STOP */ + + clen = dkLen - i * crypto_auth_hmacsha512_BYTES; + if (clen > crypto_auth_hmacsha512_BYTES) { + clen = crypto_auth_hmacsha512_BYTES; + } + memcpy(&buf[i * crypto_auth_hmacsha512_BYTES], T, clen); + } + sodium_memzero((void *) &PShctx, sizeof PShctx); + + return 0; +} diff --git a/node_modules/sodium-native/extensions/pbkdf2/pbkdf2.h b/node_modules/sodium-native/extensions/pbkdf2/pbkdf2.h new file mode 100644 index 000000000..6db372586 --- /dev/null +++ b/node_modules/sodium-native/extensions/pbkdf2/pbkdf2.h @@ -0,0 +1,54 @@ +/*- + * Copyright 2005,2007,2009 Colin Percival + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. + * + */ + +/* + * Adapated from libsodium/crypto_pwhash/scryptsalsa208sha256/pbkdf-sha256.c + */ + +#include + +#define SN_PBKDF2_STORE32_BE(buf, n32) \ + buf[0] = n32 >> 24 & 0xff; \ + buf[1] = n32 >> 16 & 0xff; \ + buf[2] = n32 >> 8 & 0xff; \ + buf[3] = n32 >> 0 & 0xff; + +#define sn__extension_pbkdf2_sha512_SALTBYTES 16U + +#define sn__extension_pbkdf2_sha512_HASHBYTES crypto_hash_sha512_BYTES + +#define sn__extension_pbkdf2_sha512_ITERATIONS_MIN 1U + +#define sn__extension_pbkdf2_sha512_BYTES_MAX 0x3fffffffc0ULL + +/** + * extension_pbkdf2_sha512(passwd, passwdlen, salt, saltlen, c, buf, dkLen): + * Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and + * write the output to buf. The value dkLen must be at most 32 * (2^32 - 1). + */ +int sn__extension_pbkdf2_sha512(const unsigned char *, size_t, const unsigned char *, size_t, + uint64_t, unsigned char *, size_t); diff --git a/node_modules/sodium-native/extensions/tweak/tweak.c b/node_modules/sodium-native/extensions/tweak/tweak.c new file mode 100644 index 000000000..a4813a065 --- /dev/null +++ b/node_modules/sodium-native/extensions/tweak/tweak.c @@ -0,0 +1,206 @@ +#include "tweak.h" + +/* + *EXPERIMENTAL API* + + This module is an experimental implementation of a key tweaking protocol + over ed25519 keys. The signature algorithm has been reimplemented from + libsodium, but the nonce generation algorithm is *non-standard*. + + Use at your own risk +*/ + +static void _extension_tweak_nonce (unsigned char *nonce, const unsigned char *n, + const unsigned char *m, unsigned long long mlen) +{ + // dom2(x, y) with x = 0 (not prehashed) and y = "crypto_tweak_ed25519" + static const unsigned char TWEAK_PREFIX[32 + 2 + 20] = { + 'S', 'i', 'g', 'E', 'd', '2', '5', '5', '1', '9', ' ', + 'n', 'o', ' ', 'E', 'd', '2', '5', '5', '1', '9', ' ', + 'c', 'o', 'l', 'l', 'i', 's', 'i', 'o', 'n', 's', 0, + 20, 'c', 'r', 'y', 'p', 't', 'o', '_', 't', 'w', 'e', + 'a', 'k', '_', 'e', 'd', '2', '5', '5', '1', '9' + }; + + crypto_hash_sha512_state hs; + + crypto_hash_sha512_init(&hs); + crypto_hash_sha512_update(&hs, TWEAK_PREFIX, sizeof TWEAK_PREFIX); + crypto_hash_sha512_update(&hs, n, 32); + crypto_hash_sha512_update(&hs, m, mlen); + crypto_hash_sha512_final(&hs, nonce); +} + +static inline void +_crypto_sign_ed25519_clamp(unsigned char k[32]) +{ + k[0] &= 248; + k[31] &= 127; + k[31] |= 64; +} + +static void _extension_tweak_ed25519(unsigned char *q, unsigned char *n, + const unsigned char *ns, unsigned long long nslen) +{ + sodium_memzero(q, sizeof q); + + crypto_hash(n, ns, nslen); + n[31] &= 127; // clear highest bit + + crypto_scalarmult_ed25519_base_noclamp(q, n); + + // hash tweak until we get a valid tweaked q + while (crypto_core_ed25519_is_valid_point(q) != 1) { + crypto_hash(n, n, 32); + n[31] &= 127; // clear highest bit + + crypto_scalarmult_ed25519_base_noclamp(q, n); + } +} + +void sn__extension_tweak_ed25519_base(unsigned char *pk, unsigned char *scalar, + const unsigned char *ns, unsigned long long nslen) +{ + unsigned char n64[64]; + + _extension_tweak_ed25519(pk, n64, ns, nslen); + + SN_TWEAK_COPY_32(scalar, n64) +} + +int sn__extension_tweak_ed25519_sign_detached(unsigned char *sig, unsigned long long *siglen_p, + const unsigned char *m, unsigned long long mlen, + const unsigned char *n, unsigned char *pk) +{ + crypto_hash_sha512_state hs; + + unsigned char nonce[64]; + unsigned char R[32]; + unsigned char hram[64]; + unsigned char _pk[32]; + + // check if pk was passed + if (pk == NULL) { + pk = _pk; + + // derive pk from scalar + if (crypto_scalarmult_ed25519_base_noclamp(pk, n) != 0) { + return -1; + } + } + + _extension_tweak_nonce(nonce, n, m, mlen); + crypto_core_ed25519_scalar_reduce(nonce, nonce); + + // R = G ^ nonce : curve point from nonce + if (crypto_scalarmult_ed25519_base_noclamp(R, nonce) != 0) { + return -1; + } + + // generate challenge as h(ram) = hash(R, pk, message) + crypto_hash_sha512_init(&hs); + crypto_hash_sha512_update(&hs, R, 32); + crypto_hash_sha512_update(&hs, pk, 32); + crypto_hash_sha512_update(&hs, m, mlen); + + crypto_hash_sha512_final(&hs, hram); + + crypto_core_ed25519_scalar_reduce(hram, hram); + + // sig = nonce + n * h(ram) + crypto_core_ed25519_scalar_mul(sig, hram, n); + crypto_core_ed25519_scalar_add(sig + 32, nonce, sig); + + SN_TWEAK_COPY_32(sig, R) + + if (siglen_p != NULL) { + *siglen_p = 64U; + } + + return 0; +} + +// tweak a secret key +void sn__extension_tweak_ed25519_sk_to_scalar(unsigned char *n, const unsigned char *sk) +{ + unsigned char n64[64]; + + // get sk scalar from seed, cf. crypto_sign_keypair_seed + crypto_hash(n64, sk, 32); + _crypto_sign_ed25519_clamp(n64); + + SN_TWEAK_COPY_32(n, n64) +} + +// tweak a secret key +void sn__extension_tweak_ed25519_scalar(unsigned char *scalar_out, + const unsigned char *scalar, + const unsigned char *ns, + unsigned long long nslen) +{ + unsigned char n[64]; + unsigned char q[32]; + + _extension_tweak_ed25519(q, n, ns, nslen); + crypto_core_ed25519_scalar_add(scalar_out, scalar, n); +} + +// tweak a public key +int sn__extension_tweak_ed25519_pk(unsigned char *tpk, + const unsigned char *pk, + const unsigned char *ns, + unsigned long long nslen) +{ + unsigned char n[64]; + unsigned char q[32]; + + _extension_tweak_ed25519(q, n, ns, nslen); + return crypto_core_ed25519_add(tpk, q, pk); +} + + +void sn__extension_tweak_ed25519_keypair(unsigned char *pk, unsigned char *scalar_out, + unsigned char *scalar, const unsigned char *ns, + unsigned long long nslen) +{ + unsigned char n64[64]; + + crypto_hash(n64, ns, nslen); + n64[31] &= 127; // clear highest bit + + sn__extension_tweak_ed25519_scalar_add(scalar_out, scalar, n64); + crypto_scalarmult_ed25519_base_noclamp(pk, scalar_out); + + // hash tweak until we get a valid tweaked point + while (crypto_core_ed25519_is_valid_point(pk) != 1) { + crypto_hash(n64, n64, 32); + n64[31] &= 127; // clear highest bit + + sn__extension_tweak_ed25519_scalar_add(scalar_out, scalar, n64); + crypto_scalarmult_ed25519_base_noclamp(pk, scalar_out); + } +} + +// add tweak to scalar +void sn__extension_tweak_ed25519_scalar_add(unsigned char *scalar_out, + const unsigned char *scalar, + const unsigned char *n) +{ + crypto_core_ed25519_scalar_add(scalar_out, scalar, n); +} + +// add tweak point to public key +int sn__extension_tweak_ed25519_pk_add(unsigned char *tpk, + const unsigned char *pk, + const unsigned char *q) +{ + return crypto_core_ed25519_add(tpk, pk, q); +} + + +int sn__extension_tweak_ed25519_keypair_add(unsigned char *pk, unsigned char *scalar_out, + unsigned char *scalar, const unsigned char *tweak) +{ + sn__extension_tweak_ed25519_scalar_add(scalar_out, scalar, tweak); + return crypto_scalarmult_ed25519_base_noclamp(pk, scalar_out); +} \ No newline at end of file diff --git a/node_modules/sodium-native/extensions/tweak/tweak.h b/node_modules/sodium-native/extensions/tweak/tweak.h new file mode 100644 index 000000000..2fdb6caf6 --- /dev/null +++ b/node_modules/sodium-native/extensions/tweak/tweak.h @@ -0,0 +1,54 @@ +#include + +// copy 32 bytes using int64_t pointers +#define SN_TWEAK_COPY_32(a, b) \ + { \ + long long *dst = (long long *) a; \ + long long *src = (long long *) b; \ + dst[0] = src[0]; \ + dst[1] = src[1]; \ + dst[2] = src[2]; \ + dst[3] = src[3]; \ + } + +#define sn__extension_tweak_ed25519_BYTES crypto_sign_ed25519_PUBLICKEYBYTES + +#define sn__extension_tweak_ed25519_SCALARBYTES crypto_scalarmult_ed25519_SCALARBYTES + +int sn__extension_tweak_ed25519_sign_detached(unsigned char *sig, unsigned long long *siglen_p, + const unsigned char *m, unsigned long long mlen, + const unsigned char *n, unsigned char *pk); + +void sn__extension_tweak_ed25519_base(unsigned char *pk, unsigned char *scalar, + const unsigned char *ns, unsigned long long nslen); + +void sn__extension_tweak_ed25519_sk_to_scalar(unsigned char *scalar, const unsigned char *sk); + +// tweak a secret key +void sn__extension_tweak_ed25519_scalar(unsigned char *scalar_out, + const unsigned char *scalar, + const unsigned char *ns, + unsigned long long nslen); + +// tweak a public key +int sn__extension_tweak_ed25519_pk(unsigned char *tpk, + const unsigned char *pk, + const unsigned char *ns, + unsigned long long nslen); + +void sn__extension_tweak_ed25519_keypair(unsigned char *pk, unsigned char *scalar_out, + unsigned char *scalar, const unsigned char *ns, + unsigned long long nslen); + +// add tweak scalar to private key +void sn__extension_tweak_ed25519_scalar_add(unsigned char *scalar_out, + const unsigned char *scalar, + const unsigned char *n); + +// add tweak point to public key +int sn__extension_tweak_ed25519_pk_add(unsigned char *tpk, + const unsigned char *pk, + const unsigned char *q); + +int sn__extension_tweak_ed25519_keypair_add(unsigned char *pk, unsigned char *scalar_out, + unsigned char *scalar, const unsigned char *tweak); diff --git a/node_modules/sodium-native/index.js b/node_modules/sodium-native/index.js new file mode 100644 index 000000000..ffd938652 --- /dev/null +++ b/node_modules/sodium-native/index.js @@ -0,0 +1 @@ +module.exports = require('node-gyp-build')(__dirname) diff --git a/node_modules/sodium-native/macros.h b/node_modules/sodium-native/macros.h new file mode 100644 index 000000000..4d5003b17 --- /dev/null +++ b/node_modules/sodium-native/macros.h @@ -0,0 +1,319 @@ +#define SN_STATUS_THROWS(call, message) \ + if ((call) != napi_ok) { \ + napi_throw_error(env, NULL, message); \ + return NULL; \ + } + +#define SN_STATUS_THROWS_VOID(call, message) \ + if ((call) != napi_ok) { \ + napi_throw_error(env, NULL, message); \ + return; \ + } + +#define SN_THROWS(condition, message) \ + if ((condition)) { \ + napi_throw_error(env, NULL, message); \ + return NULL; \ + } + +#define SN_BUFFER_CAST(type, name, val) \ + type name; \ + size_t name##_size; \ + SN_STATUS_THROWS(napi_get_buffer_info(env, val, (void **) &name, &name##_size), "") + +#define SN_TYPE_ASSERT(name, var, type, message) \ + napi_valuetype name##_valuetype; \ + SN_STATUS_THROWS(napi_typeof(env, var, &name##_valuetype), ""); \ + if (name##_valuetype != type) { \ + napi_throw_type_error(env, NULL, message); \ + return NULL; \ + } + +#define SN_TYPEDARRAY_ASSERT(name, var, message) \ + bool name##_is_typedarray; \ + SN_STATUS_THROWS(napi_is_typedarray(env, var, &name##_is_typedarray), ""); \ + if (name##_is_typedarray != true) { \ + napi_throw_type_error(env, NULL, message); \ + return NULL; \ + } + +#define SN_ASSERT_MIN_LENGTH(length, constant, name) \ + SN_THROWS(length < constant, #name " must be at least " #constant " bytes long") + + +#define SN_ASSERT_MAX_LENGTH(length, constant, name) \ + SN_THROWS(length > constant, #name " must be at most " #constant " bytes long") + + +#define SN_ASSERT_LENGTH(length, constant, name) \ + SN_THROWS(length != constant, #name " must be " #constant " bytes long") + +#define SN_RANGE_THROWS(condition, message) \ + if (condition) { \ + napi_throw_range_error(env, NULL, message); \ + return NULL; \ + } + +#define SN_ARGV(n, method_name) \ + napi_value argv[n]; \ + size_t argc = n; \ + SN_STATUS_THROWS(napi_get_cb_info(env, info, &argc, argv, NULL, NULL), ""); \ + if (argc != n) { \ + napi_throw_type_error(env, NULL, #method_name " requires " #n " argument(s)"); \ + return NULL; \ + } + +#define SN_ARGV_OPTS(required, total, method_name) \ + napi_value argv[total]; \ + size_t argc = total; \ + SN_STATUS_THROWS(napi_get_cb_info(env, info, &argc, argv, NULL, NULL), ""); \ + if (argc < required) { \ + napi_throw_type_error(env, NULL, #method_name " requires at least " #required " argument(s)"); \ + return NULL; \ + } + +#define SN_EXPORT_FUNCTION(name, cb) \ + { \ + napi_value name##_fn; \ + SN_STATUS_THROWS(napi_create_function(env, #name, NAPI_AUTO_LENGTH, cb, NULL, &name##_fn), "") \ + SN_STATUS_THROWS(napi_set_named_property(env, exports, #name, name##_fn), "") \ + } + +#define SN_EXPORT_UINT32(name, num) \ + { \ + napi_value name##_num; \ + SN_STATUS_THROWS(napi_create_uint32(env, (uint32_t) num, &name##_num), "") \ + SN_STATUS_THROWS(napi_set_named_property(env, exports, #name, name##_num), "") \ + } + +#define SN_EXPORT_UINT64(name, num) \ + { \ + napi_value name##_num; \ + uint64_t max = 0x1fffffffffffffULL; \ + SN_STATUS_THROWS(napi_create_int64(env, (uint64_t) (max < num ? max : num), &name##_num), "") \ + SN_STATUS_THROWS(napi_set_named_property(env, exports, #name, name##_num), "") \ + } + +#define SN_EXPORT_STRING(name, string) \ + { \ + napi_value name##_string; \ + SN_STATUS_THROWS(napi_create_string_utf8(env, string, NAPI_AUTO_LENGTH, &name##_string), "") \ + SN_STATUS_THROWS(napi_set_named_property(env, exports, #name, name##_string), "") \ + } + +#define SN_ARGV_CHECK_NULL(name, index) \ + napi_valuetype name##_valuetype; \ + SN_STATUS_THROWS(napi_typeof(env, argv[index], &name##_valuetype), "") \ + bool name##_is_null = name##_valuetype == napi_null; + +#define SN_ARGV_OPTS_TYPEDARRAY(name, index) \ + napi_valuetype name##_valuetype; \ + void *name##_data = NULL; \ + size_t name##_size = 0; \ + SN_STATUS_THROWS(napi_typeof(env, argv[index], &name##_valuetype), "") \ + if (name##_valuetype != napi_null && name##_valuetype != napi_undefined) { \ + napi_value name##_argv = argv[index]; \ + SN_TYPEDARRAY_ASSERT(name, name##_argv, #name " must be an instance of TypedArray") \ + SN_OPT_TYPEDARRAY(name, name##_argv) \ + } + +#define SN_TYPEDARRAY(name, var) \ + napi_typedarray_type name##_type; \ + size_t name##_length; \ + void *name##_data; \ + napi_get_typedarray_info(env, (var), &name##_type, &name##_length, &name##_data, NULL, NULL); \ + uint8_t name##_width = typedarray_width(name##_type); \ + SN_THROWS(name##_width == 0, "Unexpected TypedArray type") \ + size_t name##_size = name##_length * name##_width; + +#define SN_TYPEDARRAY_PTR(name, var) \ + napi_typedarray_type name##_type; \ + size_t name##_length; \ + void *name##_data; \ + napi_get_typedarray_info(env, (var), &name##_type, &name##_length, &name##_data, NULL, NULL); \ + uint8_t name##_width = typedarray_width(name##_type); \ + SN_THROWS(name##_width == 0, "Unexpected TypedArray type") \ + +#define SN_OPT_TYPEDARRAY(name, var) \ + napi_typedarray_type name##_type; \ + size_t name##_length; \ + napi_get_typedarray_info(env, (var), &name##_type, &name##_length, &name##_data, NULL, NULL); \ + uint8_t name##_width = typedarray_width(name##_type); \ + SN_THROWS(name##_width == 0, "Unexpected TypedArray type") \ + name##_size = name##_length * name##_width; + +#define SN_UINT8(name, val) \ + uint32_t name##_int32; \ + if (napi_get_value_uint32(env, val, &name##_int32) != napi_ok) { \ + napi_throw_error(env, "EINVAL", "Expected number"); \ + return NULL; \ + } \ + SN_THROWS(name##_int32 > 255, "expect uint8") \ + unsigned char name = 0xff & name##_int32; + +#define SN_UINT32(name, val) \ + uint32_t name; \ + if (napi_get_value_uint32(env, val, &name) != napi_ok) { \ + napi_throw_error(env, "EINVAL", "Expected number"); \ + return NULL; \ + } + +#define SN_OPT_UINT32(name, val) \ + if (napi_get_value_uint32(env, val, (uint32_t *) &name) != napi_ok) { \ + napi_throw_error(env, "EINVAL", "Expected number"); \ + return NULL; \ + } + +#define SN_UINT64(name, val) \ + int64_t name##_i64; \ + if (napi_get_value_int64(env, val, &name##_i64) != napi_ok) { \ + napi_throw_error(env, "EINVAL", "Expected number"); \ + return NULL; \ + } \ + if (name##_i64 < 0) { \ + napi_throw_error(env, "EINVAL", "Expected positive number"); \ + return NULL; \ + } \ + uint64_t name = (uint64_t) name##_i64; + +#define SN_ARGV_TYPEDARRAY(name, index) \ + napi_value name##_argv = argv[index]; \ + SN_TYPEDARRAY_ASSERT(name, name##_argv, #name " must be an instance of TypedArray") \ + SN_TYPEDARRAY(name, name##_argv) + +#define SN_ARGV_TYPEDARRAY_PTR(name, index) \ + napi_value name##_argv = argv[index]; \ + SN_TYPEDARRAY_ASSERT(name, name##_argv, #name " must be an instance of TypedArray") \ + SN_TYPEDARRAY_PTR(name, name##_argv) + +#define SN_ARGV_BUFFER_CAST(type, name, index) \ + napi_value name##_argv = argv[index]; \ + SN_BUFFER_CAST(type, name, name##_argv) + +#define SN_OPT_ARGV_TYPEDARRAY(name, index) \ + napi_value name##_argv = argv[index]; \ + SN_TYPEDARRAY_ASSERT(name, name##_argv, #name " must be an instance of TypedArray") \ + SN_OPT_TYPEDARRAY(name, name##_argv) + +#define SN_ARGV_UINT8(name, index) \ + napi_value name##_argv = argv[index]; \ + SN_TYPE_ASSERT(name, name##_argv, napi_number, #name " must be an instance of Number") \ + SN_UINT8(name, name##_argv) + +#define SN_ARGV_UINT32(name, index) \ + napi_value name##_argv = argv[index]; \ + SN_TYPE_ASSERT(name, name##_argv, napi_number, #name " must be an instance of Number") \ + SN_UINT32(name, name##_argv) + +#define SN_ARGV_UINT64(name, index) \ + napi_value name##_argv = argv[index]; \ + SN_TYPE_ASSERT(name, name##_argv, napi_number, #name " must be an instance of Number") \ + SN_UINT64(name, name##_argv) + +#define SN_OPT_ARGV_UINT32(name, index) \ + napi_value name##_argv = argv[index]; \ + SN_TYPE_ASSERT(name, name##_argv, napi_number, #name " must be an instance of Number") \ + SN_OPT_UINT32(name, name##_argv) + +#define SN_CALL(call, message) \ + int success = call; \ + SN_THROWS(success != 0, message) + +#define SN_CALL_FUNCTION(env, ctx, cb, n, argv, res) \ + if (napi_make_callback(env, NULL, ctx, cb, n, argv, res) == napi_pending_exception) { \ + napi_value fatal_exception; \ + napi_get_and_clear_last_exception(env, &fatal_exception); \ + napi_fatal_exception(env, fatal_exception); \ + } + +#define SN_RETURN(call, message) \ + int success = call; \ + SN_THROWS(success != 0, message) \ + return NULL; + +#define SN_RETURN_BOOLEAN(call) \ + int success = call; \ + napi_value result; \ + SN_THROWS(napi_get_boolean(env, success == 0, &result) != napi_ok, "result not boolean") \ + return result; + +#define SN_RETURN_BOOLEAN_FROM_1(call) \ + int success = call; \ + napi_value result; \ + SN_THROWS(napi_get_boolean(env, success != 0, &result) != napi_ok, "result not boolean") \ + return result; + +#define SN_ASYNC_CHECK_FOR_ERROR(message) \ + if (req->n == 0) { \ + napi_get_null(req->env, &argv[0]); \ + } else { \ + napi_value err_msg; \ + napi_create_string_utf8(req->env, #message, NAPI_AUTO_LENGTH, &err_msg); \ + napi_create_error(req->env, NULL, err_msg, &argv[0]); \ + } + +#define SN_CALLBACK_CHECK_FOR_ERROR(message) \ + if (task->code == 0) { \ + napi_get_null(req->env, &argv[0]); \ + } else { \ + napi_value err_msg; \ + napi_create_string_utf8(req->env, #message, NAPI_AUTO_LENGTH, &err_msg); \ + napi_create_error(req->env, NULL, err_msg, &argv[0]); \ + } + +#define SN_QUEUE_WORK(req, execute, complete) \ + uv_loop_t *loop; \ + napi_get_uv_event_loop(env, &loop); \ + uv_queue_work(loop, (uv_work_t *) req, execute, complete); + +#define SN_QUEUE_TASK(task, execute, complete) \ + uv_loop_t *loop; \ + napi_get_uv_event_loop(env, &loop); \ + uv_queue_work(loop, (uv_work_t *) task, execute, complete); + +#define SN_ASYNC_TASK(cb_pos) \ + task->req = (void *) req; \ + napi_value promise; \ + if (argc > cb_pos) { \ + task->type = sn_async_task_callback; \ + promise = NULL; \ + napi_value cb = argv[cb_pos]; \ + napi_valuetype type; \ + SN_STATUS_THROWS(napi_typeof(env, cb, &type), "") \ + if (type != napi_function) { \ + napi_throw_error(env, "EINVAL", "Callback must be a function"); \ + return NULL; \ + } \ + SN_STATUS_THROWS(napi_create_reference(env, cb, 1, &task->cb), "") \ + } else { \ + task->type = sn_async_task_promise; \ + napi_create_promise(env, &task->deferred, &promise); \ + } + +#define SN_ASYNC_COMPLETE(message) \ + napi_value argv[1]; \ + switch (task->type) { \ + case sn_async_task_promise: { \ + if (task->code == 0) { \ + napi_get_null(req->env, &argv[0]); \ + napi_resolve_deferred(req->env, task->deferred, argv[0]); \ + } else { \ + napi_value err_msg; \ + napi_create_string_utf8(req->env, #message, NAPI_AUTO_LENGTH, &err_msg); \ + napi_create_error(req->env, NULL, err_msg, &argv[0]); \ + napi_reject_deferred(req->env, task->deferred, argv[0]); \ + } \ + task->deferred = NULL; \ + break; \ + } \ + case sn_async_task_callback: { \ + SN_CALLBACK_CHECK_FOR_ERROR(#message) \ + napi_value callback; \ + napi_get_reference_value(req->env, task->cb, &callback); \ + napi_value return_val; \ + SN_CALL_FUNCTION(req->env, global, callback, 1, argv, &return_val) \ + napi_close_handle_scope(req->env, scope); \ + napi_delete_reference(req->env, task->cb); \ + break; \ + } \ + } diff --git a/node_modules/sodium-native/package.json b/node_modules/sodium-native/package.json new file mode 100644 index 000000000..9a29ed4e9 --- /dev/null +++ b/node_modules/sodium-native/package.json @@ -0,0 +1,47 @@ +{ + "name": "sodium-native", + "version": "4.3.1", + "description": "Low level bindings for libsodium", + "main": "index.js", + "files": [ + "index.js", + "binding.c", + "macros.h", + "extensions", + "prebuilds", + "CMakeLists.txt" + ], + "addon": true, + "dependencies": { + "node-gyp-build": "^4.8.0" + }, + "devDependencies": { + "brittle": "^3.5.0", + "cmake-bare": "^1.1.10", + "cmake-fetch": "^1.0.1", + "cmake-napi": "^1.0.5", + "standard": "^17.1.0" + }, + "scripts": { + "test": "standard && brittle test/*.js" + }, + "standard": { + "ignore": [ + "/test/fixtures/*.js" + ] + }, + "repository": { + "type": "git", + "url": "https://github.com/holepunchto/sodium-native.git" + }, + "contributors": [ + "Emil Bay (http://bayes.dk)", + "Mathias Buus (https://mafinto.sh)", + "Christophe Diederichs " + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/holepunchto/sodium-native/issues" + }, + "homepage": "https://github.com/holepunchto/sodium-native" +} diff --git a/node_modules/sodium-native/prebuilds/android-arm/sodium-native.bare b/node_modules/sodium-native/prebuilds/android-arm/sodium-native.bare new file mode 100644 index 000000000..1f67e68b9 Binary files /dev/null and b/node_modules/sodium-native/prebuilds/android-arm/sodium-native.bare differ diff --git a/node_modules/sodium-native/prebuilds/android-arm64/sodium-native.bare b/node_modules/sodium-native/prebuilds/android-arm64/sodium-native.bare new file mode 100644 index 000000000..358b303cf Binary files /dev/null and b/node_modules/sodium-native/prebuilds/android-arm64/sodium-native.bare differ diff --git a/node_modules/sodium-native/prebuilds/android-ia32/sodium-native.bare b/node_modules/sodium-native/prebuilds/android-ia32/sodium-native.bare new file mode 100644 index 000000000..6cacdbd12 Binary files /dev/null and b/node_modules/sodium-native/prebuilds/android-ia32/sodium-native.bare differ diff --git a/node_modules/sodium-native/prebuilds/android-x64/sodium-native.bare b/node_modules/sodium-native/prebuilds/android-x64/sodium-native.bare new file mode 100644 index 000000000..4d9a90fe9 Binary files /dev/null and b/node_modules/sodium-native/prebuilds/android-x64/sodium-native.bare differ diff --git a/node_modules/sodium-native/prebuilds/darwin-arm64/sodium-native.bare b/node_modules/sodium-native/prebuilds/darwin-arm64/sodium-native.bare new file mode 100644 index 000000000..85c3ac351 Binary files /dev/null and b/node_modules/sodium-native/prebuilds/darwin-arm64/sodium-native.bare differ diff --git a/node_modules/sodium-native/prebuilds/darwin-arm64/sodium-native.node b/node_modules/sodium-native/prebuilds/darwin-arm64/sodium-native.node new file mode 100644 index 000000000..779397664 Binary files /dev/null and b/node_modules/sodium-native/prebuilds/darwin-arm64/sodium-native.node differ diff --git a/node_modules/sodium-native/prebuilds/darwin-x64/sodium-native.bare b/node_modules/sodium-native/prebuilds/darwin-x64/sodium-native.bare new file mode 100644 index 000000000..04ac656ef Binary files /dev/null and b/node_modules/sodium-native/prebuilds/darwin-x64/sodium-native.bare differ diff --git a/node_modules/sodium-native/prebuilds/darwin-x64/sodium-native.node b/node_modules/sodium-native/prebuilds/darwin-x64/sodium-native.node new file mode 100644 index 000000000..0aecdddda Binary files /dev/null and b/node_modules/sodium-native/prebuilds/darwin-x64/sodium-native.node differ diff --git a/node_modules/sodium-native/prebuilds/ios-arm64-simulator/sodium-native.bare b/node_modules/sodium-native/prebuilds/ios-arm64-simulator/sodium-native.bare new file mode 100644 index 000000000..9ea47ce87 Binary files /dev/null and b/node_modules/sodium-native/prebuilds/ios-arm64-simulator/sodium-native.bare differ diff --git a/node_modules/sodium-native/prebuilds/ios-arm64/sodium-native.bare b/node_modules/sodium-native/prebuilds/ios-arm64/sodium-native.bare new file mode 100644 index 000000000..01140f9cc Binary files /dev/null and b/node_modules/sodium-native/prebuilds/ios-arm64/sodium-native.bare differ diff --git a/node_modules/sodium-native/prebuilds/ios-x64-simulator/sodium-native.bare b/node_modules/sodium-native/prebuilds/ios-x64-simulator/sodium-native.bare new file mode 100644 index 000000000..5d1b3c5bf Binary files /dev/null and b/node_modules/sodium-native/prebuilds/ios-x64-simulator/sodium-native.bare differ diff --git a/node_modules/sodium-native/prebuilds/linux-arm64/sodium-native.bare b/node_modules/sodium-native/prebuilds/linux-arm64/sodium-native.bare new file mode 100644 index 000000000..a828ec486 Binary files /dev/null and b/node_modules/sodium-native/prebuilds/linux-arm64/sodium-native.bare differ diff --git a/node_modules/sodium-native/prebuilds/linux-arm64/sodium-native.node b/node_modules/sodium-native/prebuilds/linux-arm64/sodium-native.node new file mode 100644 index 000000000..f9d37fe2c Binary files /dev/null and b/node_modules/sodium-native/prebuilds/linux-arm64/sodium-native.node differ diff --git a/node_modules/sodium-native/prebuilds/linux-x64/sodium-native.bare b/node_modules/sodium-native/prebuilds/linux-x64/sodium-native.bare new file mode 100644 index 000000000..3c4ec61eb Binary files /dev/null and b/node_modules/sodium-native/prebuilds/linux-x64/sodium-native.bare differ diff --git a/node_modules/sodium-native/prebuilds/linux-x64/sodium-native.node b/node_modules/sodium-native/prebuilds/linux-x64/sodium-native.node new file mode 100644 index 000000000..5f7bda849 Binary files /dev/null and b/node_modules/sodium-native/prebuilds/linux-x64/sodium-native.node differ diff --git a/node_modules/sodium-native/prebuilds/win32-arm64/sodium-native.bare b/node_modules/sodium-native/prebuilds/win32-arm64/sodium-native.bare new file mode 100644 index 000000000..eff4e5a9f Binary files /dev/null and b/node_modules/sodium-native/prebuilds/win32-arm64/sodium-native.bare differ diff --git a/node_modules/sodium-native/prebuilds/win32-arm64/sodium-native.node b/node_modules/sodium-native/prebuilds/win32-arm64/sodium-native.node new file mode 100644 index 000000000..67b739858 Binary files /dev/null and b/node_modules/sodium-native/prebuilds/win32-arm64/sodium-native.node differ diff --git a/node_modules/sodium-native/prebuilds/win32-x64/sodium-native.bare b/node_modules/sodium-native/prebuilds/win32-x64/sodium-native.bare new file mode 100644 index 000000000..341870d7c Binary files /dev/null and b/node_modules/sodium-native/prebuilds/win32-x64/sodium-native.bare differ diff --git a/node_modules/sodium-native/prebuilds/win32-x64/sodium-native.node b/node_modules/sodium-native/prebuilds/win32-x64/sodium-native.node new file mode 100644 index 000000000..982585442 Binary files /dev/null and b/node_modules/sodium-native/prebuilds/win32-x64/sodium-native.node differ diff --git a/node_modules/toml/.jshintrc b/node_modules/toml/.jshintrc new file mode 100644 index 000000000..96747b1a6 --- /dev/null +++ b/node_modules/toml/.jshintrc @@ -0,0 +1,18 @@ +{ + "node": true, + "browser": true, + "browserify": true, + "curly": true, + "eqeqeq": true, + "eqnull": false, + "latedef": "nofunc", + "newcap": true, + "noarg": true, + "undef": true, + "strict": true, + "trailing": true, + "smarttabs": true, + "indent": 2, + "quotmark": true, + "laxbreak": true +} diff --git a/node_modules/toml/.travis.yml b/node_modules/toml/.travis.yml new file mode 100644 index 000000000..f46aeb8ce --- /dev/null +++ b/node_modules/toml/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +sudo: false +node_js: + - "4.1" + - "4.0" + - "0.12" + - "0.10" diff --git a/node_modules/toml/CHANGELOG.md b/node_modules/toml/CHANGELOG.md new file mode 100644 index 000000000..65b4db69a --- /dev/null +++ b/node_modules/toml/CHANGELOG.md @@ -0,0 +1,116 @@ +2.3.0 - July 13 2015 +==================== + +* Correctly handle quoted keys ([#21](https://github.com/BinaryMuse/toml-node/issues/21)) + +2.2.3 - June 8 2015 +=================== + +* Support empty inline tables ([#24](https://github.com/BinaryMuse/toml-node/issues/24)) +* Do not allow implicit table definitions to replace value ([#23](https://github.com/BinaryMuse/toml-node/issues/23)) +* Don't allow tables to replace inline tables ([#25](https://github.com/BinaryMuse/toml-node/issues/25)) + +2.2.2 - April 3 2015 +==================== + +* Correctly handle newlines at beginning of string ([#22](https://github.com/BinaryMuse/toml-node/issues/22)) + +2.2.1 - March 17 2015 +===================== + +* Parse dates generated by Date#toISOString() ([#20](https://github.com/BinaryMuse/toml-node/issues/20)) + +2.2.0 - Feb 26 2015 +=================== + +* Support TOML spec v0.4.0 + +2.1.0 - Jan 7 2015 +================== + +* Support TOML spec v0.3.1 + +2.0.6 - May 23 2014 +=================== + +### Bug Fixes + +* Fix support for empty arrays with newlines ([#13](https://github.com/BinaryMuse/toml-node/issues/13)) + +2.0.5 - May 5 2014 +================== + +### Bug Fixes + +* Fix loop iteration leak, by [sebmck](https://github.com/sebmck) ([#12](https://github.com/BinaryMuse/toml-node/pull/12)) + +### Development + +* Tests now run JSHint on `lib/compiler.js` + +2.0.4 - Mar 9 2014 +================== + +### Bug Fixes + +* Fix failure on duplicate table name inside table array ([#11](https://github.com/BinaryMuse/toml-node/issues/11)) + +2.0.2 - Feb 23 2014 +=================== + +### Bug Fixes + +* Fix absence of errors when table path starts or ends with period + +2.0.1 - Feb 23 2014 +=================== + +### Bug Fixes + +* Fix incorrect messaging in array type errors +* Fix missing error when overwriting key with table array + +2.0.0 - Feb 23 2014 +=================== + +### Features + +* Add support for [version 0.2 of the TOML spec](https://github.com/mojombo/toml/blob/master/versions/toml-v0.2.0.md) ([#9](https://github.com/BinaryMuse/toml-node/issues/9)) + +### Internals + +* Upgrade to PEG.js v0.8 and rewrite compiler; parser is now considerably faster (from ~7000ms to ~1000ms to parse `example.toml` 1000 times on Node.js v0.10) + +1.0.4 - Aug 17 2013 +=================== + +### Bug Fixes + +* Fix support for empty arrays + +1.0.3 - Aug 17 2013 +=================== + +### Bug Fixes + +* Fix typo in array type error message +* Fix single-element arrays with no trailing commas + +1.0.2 - Aug 17 2013 +=================== + +### Bug Fixes + +* Fix errors on lines that contain only whitespace ([#7](https://github.com/BinaryMuse/toml-node/issues/7)) + +1.0.1 - Aug 17 2013 +=================== + +### Internals + +* Remove old code remaining from the remove streaming API + +1.0.0 - Aug 17 2013 +=================== + +Initial stable release diff --git a/node_modules/toml/LICENSE b/node_modules/toml/LICENSE new file mode 100644 index 000000000..44ae2bfc4 --- /dev/null +++ b/node_modules/toml/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2012 Michelle Tilley + +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/node_modules/toml/README.md b/node_modules/toml/README.md new file mode 100644 index 000000000..ff4dc5877 --- /dev/null +++ b/node_modules/toml/README.md @@ -0,0 +1,93 @@ +TOML Parser for Node.js +======================= + +[![Build Status](https://travis-ci.org/BinaryMuse/toml-node.png?branch=master)](https://travis-ci.org/BinaryMuse/toml-node) + +[![NPM](https://nodei.co/npm/toml.png?downloads=true)](https://nodei.co/npm/toml/) + +If you haven't heard of TOML, well you're just missing out. [Go check it out now.](https://github.com/mojombo/toml) Back? Good. + +TOML Spec Support +----------------- + +toml-node supports version 0.4.0 the TOML spec as specified by [mojombo/toml@v0.4.0](https://github.com/mojombo/toml/blob/master/versions/en/toml-v0.4.0.md) + +Installation +------------ + +toml-node is available via npm. + + npm install toml + +toml-node also works with browser module bundlers like Browserify and webpack. + +Usage +----- + +### Standalone + +Say you have some awesome TOML in a variable called `someTomlString`. Maybe it came from the web; maybe it came from a file; wherever it came from, it came asynchronously! Let's turn that sucker into a JavaScript object. + +```javascript +var toml = require('toml'); +var data = toml.parse(someTomlString); +console.dir(data); +``` + +`toml.parse` throws an exception in the case of a parsing error; such exceptions have a `line` and `column` property on them to help identify the offending text. + +```javascript +try { + toml.parse(someCrazyKnuckleHeadedTrblToml); +} catch (e) { + console.error("Parsing error on line " + e.line + ", column " + e.column + + ": " + e.message); +} +``` + +### Streaming + +As of toml-node version 1.0, the streaming interface has been removed. Instead, use a module like [concat-stream](https://npmjs.org/package/concat-stream): + +```javascript +var toml = require('toml'); +var concat = require('concat-stream'); +var fs = require('fs'); + +fs.createReadStream('tomlFile.toml', 'utf8').pipe(concat(function(data) { + var parsed = toml.parse(data); +})); +``` + +Thanks [@ForbesLindesay](https://github.com/ForbesLindesay) for the suggestion. + +### Requiring with Node.js + +You can use the [toml-require package](https://github.com/BinaryMuse/toml-require) to `require()` your `.toml` files with Node.js + +Live Demo +--------- + +You can experiment with TOML online at http://binarymuse.github.io/toml-node/, which uses the latest version of this library. + +Building & Testing +------------------ + +toml-node uses [the PEG.js parser generator](http://pegjs.majda.cz/). + + npm install + npm run build + npm test + +Any changes to `src/toml.peg` requires a regeneration of the parser with `npm run build`. + +toml-node is tested on Travis CI and is tested against: + + * Node 0.10 + * Node 0.12 + * Latest stable io.js + +License +------- + +toml-node is licensed under the MIT license agreement. See the LICENSE file for more information. diff --git a/node_modules/toml/benchmark.js b/node_modules/toml/benchmark.js new file mode 100644 index 000000000..99fba1d3d --- /dev/null +++ b/node_modules/toml/benchmark.js @@ -0,0 +1,12 @@ +var toml = require('./index'); +var fs = require('fs'); +var data = fs.readFileSync('./test/example.toml', 'utf8'); + +var iterations = 1000; + +var start = new Date(); +for(var i = 0; i < iterations; i++) { + toml.parse(data); +} +var end = new Date(); +console.log("%s iterations in %sms", iterations, end - start); diff --git a/node_modules/toml/index.d.ts b/node_modules/toml/index.d.ts new file mode 100644 index 000000000..7e9052b4e --- /dev/null +++ b/node_modules/toml/index.d.ts @@ -0,0 +1,3 @@ +declare module 'toml' { + export function parse(input: string): any; +} diff --git a/node_modules/toml/index.js b/node_modules/toml/index.js new file mode 100644 index 000000000..6caf44a08 --- /dev/null +++ b/node_modules/toml/index.js @@ -0,0 +1,9 @@ +var parser = require('./lib/parser'); +var compiler = require('./lib/compiler'); + +module.exports = { + parse: function(input) { + var nodes = parser.parse(input.toString()); + return compiler.compile(nodes); + } +}; diff --git a/node_modules/toml/lib/compiler.js b/node_modules/toml/lib/compiler.js new file mode 100644 index 000000000..ba5312ed0 --- /dev/null +++ b/node_modules/toml/lib/compiler.js @@ -0,0 +1,195 @@ +"use strict"; +function compile(nodes) { + var assignedPaths = []; + var valueAssignments = []; + var currentPath = ""; + var data = Object.create(null); + var context = data; + var arrayMode = false; + + return reduce(nodes); + + function reduce(nodes) { + var node; + for (var i = 0; i < nodes.length; i++) { + node = nodes[i]; + switch (node.type) { + case "Assign": + assign(node); + break; + case "ObjectPath": + setPath(node); + break; + case "ArrayPath": + addTableArray(node); + break; + } + } + + return data; + } + + function genError(err, line, col) { + var ex = new Error(err); + ex.line = line; + ex.column = col; + throw ex; + } + + function assign(node) { + var key = node.key; + var value = node.value; + var line = node.line; + var column = node.column; + + var fullPath; + if (currentPath) { + fullPath = currentPath + "." + key; + } else { + fullPath = key; + } + if (typeof context[key] !== "undefined") { + genError("Cannot redefine existing key '" + fullPath + "'.", line, column); + } + + context[key] = reduceValueNode(value); + + if (!pathAssigned(fullPath)) { + assignedPaths.push(fullPath); + valueAssignments.push(fullPath); + } + } + + + function pathAssigned(path) { + return assignedPaths.indexOf(path) !== -1; + } + + function reduceValueNode(node) { + if (node.type === "Array") { + return reduceArrayWithTypeChecking(node.value); + } else if (node.type === "InlineTable") { + return reduceInlineTableNode(node.value); + } else { + return node.value; + } + } + + function reduceInlineTableNode(values) { + var obj = Object.create(null); + for (var i = 0; i < values.length; i++) { + var val = values[i]; + if (val.value.type === "InlineTable") { + obj[val.key] = reduceInlineTableNode(val.value.value); + } else if (val.type === "InlineTableValue") { + obj[val.key] = reduceValueNode(val.value); + } + } + + return obj; + } + + function setPath(node) { + var path = node.value; + var quotedPath = path.map(quoteDottedString).join("."); + var line = node.line; + var column = node.column; + + if (pathAssigned(quotedPath)) { + genError("Cannot redefine existing key '" + path + "'.", line, column); + } + assignedPaths.push(quotedPath); + context = deepRef(data, path, Object.create(null), line, column); + currentPath = path; + } + + function addTableArray(node) { + var path = node.value; + var quotedPath = path.map(quoteDottedString).join("."); + var line = node.line; + var column = node.column; + + if (!pathAssigned(quotedPath)) { + assignedPaths.push(quotedPath); + } + assignedPaths = assignedPaths.filter(function(p) { + return p.indexOf(quotedPath) !== 0; + }); + assignedPaths.push(quotedPath); + context = deepRef(data, path, [], line, column); + currentPath = quotedPath; + + if (context instanceof Array) { + var newObj = Object.create(null); + context.push(newObj); + context = newObj; + } else { + genError("Cannot redefine existing key '" + path + "'.", line, column); + } + } + + // Given a path 'a.b.c', create (as necessary) `start.a`, + // `start.a.b`, and `start.a.b.c`, assigning `value` to `start.a.b.c`. + // If `a` or `b` are arrays and have items in them, the last item in the + // array is used as the context for the next sub-path. + function deepRef(start, keys, value, line, column) { + var traversed = []; + var traversedPath = ""; + var path = keys.join("."); + var ctx = start; + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + traversed.push(key); + traversedPath = traversed.join("."); + if (typeof ctx[key] === "undefined") { + if (i === keys.length - 1) { + ctx[key] = value; + } else { + ctx[key] = Object.create(null); + } + } else if (i !== keys.length - 1 && valueAssignments.indexOf(traversedPath) > -1) { + // already a non-object value at key, can't be used as part of a new path + genError("Cannot redefine existing key '" + traversedPath + "'.", line, column); + } + + ctx = ctx[key]; + if (ctx instanceof Array && ctx.length && i < keys.length - 1) { + ctx = ctx[ctx.length - 1]; + } + } + + return ctx; + } + + function reduceArrayWithTypeChecking(array) { + // Ensure that all items in the array are of the same type + var firstType = null; + for (var i = 0; i < array.length; i++) { + var node = array[i]; + if (firstType === null) { + firstType = node.type; + } else { + if (node.type !== firstType) { + genError("Cannot add value of type " + node.type + " to array of type " + + firstType + ".", node.line, node.column); + } + } + } + + // Recursively reduce array of nodes into array of the nodes' values + return array.map(reduceValueNode); + } + + function quoteDottedString(str) { + if (str.indexOf(".") > -1) { + return "\"" + str + "\""; + } else { + return str; + } + } +} + +module.exports = { + compile: compile +}; diff --git a/node_modules/toml/lib/parser.js b/node_modules/toml/lib/parser.js new file mode 100644 index 000000000..69cbd6fd6 --- /dev/null +++ b/node_modules/toml/lib/parser.js @@ -0,0 +1,3841 @@ +module.exports = (function() { + /* + * Generated by PEG.js 0.8.0. + * + * http://pegjs.majda.cz/ + */ + + function peg$subclass(child, parent) { + function ctor() { this.constructor = child; } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + + function SyntaxError(message, expected, found, offset, line, column) { + this.message = message; + this.expected = expected; + this.found = found; + this.offset = offset; + this.line = line; + this.column = column; + + this.name = "SyntaxError"; + } + + peg$subclass(SyntaxError, Error); + + function parse(input) { + var options = arguments.length > 1 ? arguments[1] : {}, + + peg$FAILED = {}, + + peg$startRuleFunctions = { start: peg$parsestart }, + peg$startRuleFunction = peg$parsestart, + + peg$c0 = [], + peg$c1 = function() { return nodes }, + peg$c2 = peg$FAILED, + peg$c3 = "#", + peg$c4 = { type: "literal", value: "#", description: "\"#\"" }, + peg$c5 = void 0, + peg$c6 = { type: "any", description: "any character" }, + peg$c7 = "[", + peg$c8 = { type: "literal", value: "[", description: "\"[\"" }, + peg$c9 = "]", + peg$c10 = { type: "literal", value: "]", description: "\"]\"" }, + peg$c11 = function(name) { addNode(node('ObjectPath', name, line, column)) }, + peg$c12 = function(name) { addNode(node('ArrayPath', name, line, column)) }, + peg$c13 = function(parts, name) { return parts.concat(name) }, + peg$c14 = function(name) { return [name] }, + peg$c15 = function(name) { return name }, + peg$c16 = ".", + peg$c17 = { type: "literal", value: ".", description: "\".\"" }, + peg$c18 = "=", + peg$c19 = { type: "literal", value: "=", description: "\"=\"" }, + peg$c20 = function(key, value) { addNode(node('Assign', value, line, column, key)) }, + peg$c21 = function(chars) { return chars.join('') }, + peg$c22 = function(node) { return node.value }, + peg$c23 = "\"\"\"", + peg$c24 = { type: "literal", value: "\"\"\"", description: "\"\\\"\\\"\\\"\"" }, + peg$c25 = null, + peg$c26 = function(chars) { return node('String', chars.join(''), line, column) }, + peg$c27 = "\"", + peg$c28 = { type: "literal", value: "\"", description: "\"\\\"\"" }, + peg$c29 = "'''", + peg$c30 = { type: "literal", value: "'''", description: "\"'''\"" }, + peg$c31 = "'", + peg$c32 = { type: "literal", value: "'", description: "\"'\"" }, + peg$c33 = function(char) { return char }, + peg$c34 = function(char) { return char}, + peg$c35 = "\\", + peg$c36 = { type: "literal", value: "\\", description: "\"\\\\\"" }, + peg$c37 = function() { return '' }, + peg$c38 = "e", + peg$c39 = { type: "literal", value: "e", description: "\"e\"" }, + peg$c40 = "E", + peg$c41 = { type: "literal", value: "E", description: "\"E\"" }, + peg$c42 = function(left, right) { return node('Float', parseFloat(left + 'e' + right), line, column) }, + peg$c43 = function(text) { return node('Float', parseFloat(text), line, column) }, + peg$c44 = "+", + peg$c45 = { type: "literal", value: "+", description: "\"+\"" }, + peg$c46 = function(digits) { return digits.join('') }, + peg$c47 = "-", + peg$c48 = { type: "literal", value: "-", description: "\"-\"" }, + peg$c49 = function(digits) { return '-' + digits.join('') }, + peg$c50 = function(text) { return node('Integer', parseInt(text, 10), line, column) }, + peg$c51 = "true", + peg$c52 = { type: "literal", value: "true", description: "\"true\"" }, + peg$c53 = function() { return node('Boolean', true, line, column) }, + peg$c54 = "false", + peg$c55 = { type: "literal", value: "false", description: "\"false\"" }, + peg$c56 = function() { return node('Boolean', false, line, column) }, + peg$c57 = function() { return node('Array', [], line, column) }, + peg$c58 = function(value) { return node('Array', value ? [value] : [], line, column) }, + peg$c59 = function(values) { return node('Array', values, line, column) }, + peg$c60 = function(values, value) { return node('Array', values.concat(value), line, column) }, + peg$c61 = function(value) { return value }, + peg$c62 = ",", + peg$c63 = { type: "literal", value: ",", description: "\",\"" }, + peg$c64 = "{", + peg$c65 = { type: "literal", value: "{", description: "\"{\"" }, + peg$c66 = "}", + peg$c67 = { type: "literal", value: "}", description: "\"}\"" }, + peg$c68 = function(values) { return node('InlineTable', values, line, column) }, + peg$c69 = function(key, value) { return node('InlineTableValue', value, line, column, key) }, + peg$c70 = function(digits) { return "." + digits }, + peg$c71 = function(date) { return date.join('') }, + peg$c72 = ":", + peg$c73 = { type: "literal", value: ":", description: "\":\"" }, + peg$c74 = function(time) { return time.join('') }, + peg$c75 = "T", + peg$c76 = { type: "literal", value: "T", description: "\"T\"" }, + peg$c77 = "Z", + peg$c78 = { type: "literal", value: "Z", description: "\"Z\"" }, + peg$c79 = function(date, time) { return node('Date', new Date(date + "T" + time + "Z"), line, column) }, + peg$c80 = function(date, time) { return node('Date', new Date(date + "T" + time), line, column) }, + peg$c81 = /^[ \t]/, + peg$c82 = { type: "class", value: "[ \\t]", description: "[ \\t]" }, + peg$c83 = "\n", + peg$c84 = { type: "literal", value: "\n", description: "\"\\n\"" }, + peg$c85 = "\r", + peg$c86 = { type: "literal", value: "\r", description: "\"\\r\"" }, + peg$c87 = /^[0-9a-f]/i, + peg$c88 = { type: "class", value: "[0-9a-f]i", description: "[0-9a-f]i" }, + peg$c89 = /^[0-9]/, + peg$c90 = { type: "class", value: "[0-9]", description: "[0-9]" }, + peg$c91 = "_", + peg$c92 = { type: "literal", value: "_", description: "\"_\"" }, + peg$c93 = function() { return "" }, + peg$c94 = /^[A-Za-z0-9_\-]/, + peg$c95 = { type: "class", value: "[A-Za-z0-9_\\-]", description: "[A-Za-z0-9_\\-]" }, + peg$c96 = function(d) { return d.join('') }, + peg$c97 = "\\\"", + peg$c98 = { type: "literal", value: "\\\"", description: "\"\\\\\\\"\"" }, + peg$c99 = function() { return '"' }, + peg$c100 = "\\\\", + peg$c101 = { type: "literal", value: "\\\\", description: "\"\\\\\\\\\"" }, + peg$c102 = function() { return '\\' }, + peg$c103 = "\\b", + peg$c104 = { type: "literal", value: "\\b", description: "\"\\\\b\"" }, + peg$c105 = function() { return '\b' }, + peg$c106 = "\\t", + peg$c107 = { type: "literal", value: "\\t", description: "\"\\\\t\"" }, + peg$c108 = function() { return '\t' }, + peg$c109 = "\\n", + peg$c110 = { type: "literal", value: "\\n", description: "\"\\\\n\"" }, + peg$c111 = function() { return '\n' }, + peg$c112 = "\\f", + peg$c113 = { type: "literal", value: "\\f", description: "\"\\\\f\"" }, + peg$c114 = function() { return '\f' }, + peg$c115 = "\\r", + peg$c116 = { type: "literal", value: "\\r", description: "\"\\\\r\"" }, + peg$c117 = function() { return '\r' }, + peg$c118 = "\\U", + peg$c119 = { type: "literal", value: "\\U", description: "\"\\\\U\"" }, + peg$c120 = function(digits) { return convertCodePoint(digits.join('')) }, + peg$c121 = "\\u", + peg$c122 = { type: "literal", value: "\\u", description: "\"\\\\u\"" }, + + peg$currPos = 0, + peg$reportedPos = 0, + peg$cachedPos = 0, + peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }, + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$silentFails = 0, + + peg$cache = {}, + peg$result; + + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + + function text() { + return input.substring(peg$reportedPos, peg$currPos); + } + + function offset() { + return peg$reportedPos; + } + + function line() { + return peg$computePosDetails(peg$reportedPos).line; + } + + function column() { + return peg$computePosDetails(peg$reportedPos).column; + } + + function expected(description) { + throw peg$buildException( + null, + [{ type: "other", description: description }], + peg$reportedPos + ); + } + + function error(message) { + throw peg$buildException(message, null, peg$reportedPos); + } + + function peg$computePosDetails(pos) { + function advance(details, startPos, endPos) { + var p, ch; + + for (p = startPos; p < endPos; p++) { + ch = input.charAt(p); + if (ch === "\n") { + if (!details.seenCR) { details.line++; } + details.column = 1; + details.seenCR = false; + } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { + details.line++; + details.column = 1; + details.seenCR = true; + } else { + details.column++; + details.seenCR = false; + } + } + } + + if (peg$cachedPos !== pos) { + if (peg$cachedPos > pos) { + peg$cachedPos = 0; + peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }; + } + advance(peg$cachedPosDetails, peg$cachedPos, pos); + peg$cachedPos = pos; + } + + return peg$cachedPosDetails; + } + + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { return; } + + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + + peg$maxFailExpected.push(expected); + } + + function peg$buildException(message, expected, pos) { + function cleanupExpected(expected) { + var i = 1; + + expected.sort(function(a, b) { + if (a.description < b.description) { + return -1; + } else if (a.description > b.description) { + return 1; + } else { + return 0; + } + }); + + while (i < expected.length) { + if (expected[i - 1] === expected[i]) { + expected.splice(i, 1); + } else { + i++; + } + } + } + + function buildMessage(expected, found) { + function stringEscape(s) { + function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } + + return s + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\x08/g, '\\b') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\f/g, '\\f') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); }) + .replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); }) + .replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); }); + } + + var expectedDescs = new Array(expected.length), + expectedDesc, foundDesc, i; + + for (i = 0; i < expected.length; i++) { + expectedDescs[i] = expected[i].description; + } + + expectedDesc = expected.length > 1 + ? expectedDescs.slice(0, -1).join(", ") + + " or " + + expectedDescs[expected.length - 1] + : expectedDescs[0]; + + foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input"; + + return "Expected " + expectedDesc + " but " + foundDesc + " found."; + } + + var posDetails = peg$computePosDetails(pos), + found = pos < input.length ? input.charAt(pos) : null; + + if (expected !== null) { + cleanupExpected(expected); + } + + return new SyntaxError( + message !== null ? message : buildMessage(expected, found), + expected, + found, + pos, + posDetails.line, + posDetails.column + ); + } + + function peg$parsestart() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 0, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseline(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseline(); + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c1(); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseline() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 1, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parseexpression(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parsecomment(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parsecomment(); + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseNL(); + if (s6 !== peg$FAILED) { + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseNL(); + } + } else { + s5 = peg$c2; + } + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + if (s5 !== peg$FAILED) { + s1 = [s1, s2, s3, s4, s5]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseNL(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseNL(); + } + } else { + s2 = peg$c2; + } + if (s2 === peg$FAILED) { + s2 = peg$parseEOF(); + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$parseNL(); + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseexpression() { + var s0; + + var key = peg$currPos * 49 + 2, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsecomment(); + if (s0 === peg$FAILED) { + s0 = peg$parsepath(); + if (s0 === peg$FAILED) { + s0 = peg$parsetablearray(); + if (s0 === peg$FAILED) { + s0 = peg$parseassignment(); + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsecomment() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 3, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c3; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c4); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNL(); + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = peg$c5; + } else { + peg$currPos = s4; + s4 = peg$c2; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } else { + peg$currPos = s3; + s3 = peg$c2; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$currPos; + peg$silentFails++; + s5 = peg$parseNL(); + if (s5 === peg$FAILED) { + s5 = peg$parseEOF(); + } + peg$silentFails--; + if (s5 === peg$FAILED) { + s4 = peg$c5; + } else { + peg$currPos = s4; + s4 = peg$c2; + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } else { + peg$currPos = s3; + s3 = peg$c2; + } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsepath() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 4, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetable_key(); + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s5 = peg$c9; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c11(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetablearray() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + var key = peg$currPos * 49 + 5, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 91) { + s2 = peg$c7; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + s4 = peg$parsetable_key(); + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s6 = peg$c9; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s7 = peg$c9; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s7 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c12(s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetable_key() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 6, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsedot_ended_table_key_part(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsedot_ended_table_key_part(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + s2 = peg$parsetable_key_part(); + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c13(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsetable_key_part(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c14(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetable_key_part() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 7, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsequoted_key(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedot_ended_table_key_part() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 8, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsequoted_key(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c15(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseassignment() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 9, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsekey(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c18; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parsevalue(); + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c20(s1, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsequoted_key(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s3 = peg$c18; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + s5 = peg$parsevalue(); + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c20(s1, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsekey() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 10, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseASCII_BASIC(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseASCII_BASIC(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c21(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsequoted_key() { + var s0, s1; + + var key = peg$currPos * 49 + 11, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsedouble_quoted_single_line_string(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c22(s1); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsesingle_quoted_single_line_string(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c22(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsevalue() { + var s0; + + var key = peg$currPos * 49 + 12, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsestring(); + if (s0 === peg$FAILED) { + s0 = peg$parsedatetime(); + if (s0 === peg$FAILED) { + s0 = peg$parsefloat(); + if (s0 === peg$FAILED) { + s0 = peg$parseinteger(); + if (s0 === peg$FAILED) { + s0 = peg$parseboolean(); + if (s0 === peg$FAILED) { + s0 = peg$parsearray(); + if (s0 === peg$FAILED) { + s0 = peg$parseinline_table(); + } + } + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsestring() { + var s0; + + var key = peg$currPos * 49 + 13, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parsedouble_quoted_multiline_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsedouble_quoted_single_line_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsesingle_quoted_multiline_string(); + if (s0 === peg$FAILED) { + s0 = peg$parsesingle_quoted_single_line_string(); + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedouble_quoted_multiline_string() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 14, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c23) { + s1 = peg$c23; + peg$currPos += 3; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsemultiline_string_char(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsemultiline_string_char(); + } + if (s3 !== peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c23) { + s4 = peg$c23; + peg$currPos += 3; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedouble_quoted_single_line_string() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 15, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c27; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsestring_char(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsestring_char(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c27; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesingle_quoted_multiline_string() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 16, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 3) === peg$c29) { + s1 = peg$c29; + peg$currPos += 3; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsemultiline_literal_char(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsemultiline_literal_char(); + } + if (s3 !== peg$FAILED) { + if (input.substr(peg$currPos, 3) === peg$c29) { + s4 = peg$c29; + peg$currPos += 3; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesingle_quoted_single_line_string() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 17, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseliteral_char(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseliteral_char(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c31; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c26(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsestring_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 18, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseESCAPED(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 34) { + s2 = peg$c27; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c28); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseliteral_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 19, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 39) { + s2 = peg$c31; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_string_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 20, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseESCAPED(); + if (s0 === peg$FAILED) { + s0 = peg$parsemultiline_string_delim(); + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c23) { + s2 = peg$c23; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c24); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c34(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_string_delim() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 21, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c35; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c36); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseNL(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseNLS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseNLS(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c37(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsemultiline_literal_char() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 22, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + peg$silentFails++; + if (input.substr(peg$currPos, 3) === peg$c29) { + s2 = peg$c29; + peg$currPos += 3; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c30); } + } + peg$silentFails--; + if (s2 === peg$FAILED) { + s1 = peg$c5; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c33(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefloat() { + var s0, s1, s2, s3; + + var key = peg$currPos * 49 + 23, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsefloat_text(); + if (s1 === peg$FAILED) { + s1 = peg$parseinteger_text(); + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 101) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 69) { + s2 = peg$c40; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c41); } + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parseinteger_text(); + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c42(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsefloat_text(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c43(s1); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefloat_text() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 24, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c44; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + if (s1 === peg$FAILED) { + s1 = peg$c25; + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseDIGITS(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGITS(); + if (s5 !== peg$FAILED) { + s3 = [s3, s4, s5]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c46(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 45) { + s1 = peg$c47; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseDIGITS(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGITS(); + if (s5 !== peg$FAILED) { + s3 = [s3, s4, s5]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c49(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinteger() { + var s0, s1; + + var key = peg$currPos * 49 + 25, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseinteger_text(); + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c50(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinteger_text() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 26, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 43) { + s1 = peg$c44; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + if (s1 === peg$FAILED) { + s1 = peg$c25; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + peg$silentFails--; + if (s4 === peg$FAILED) { + s3 = peg$c5; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c46(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 45) { + s1 = peg$c47; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$currPos; + peg$silentFails++; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c16; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + peg$silentFails--; + if (s4 === peg$FAILED) { + s3 = peg$c5; + } else { + peg$currPos = s3; + s3 = peg$c2; + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c49(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseboolean() { + var s0, s1; + + var key = peg$currPos * 49 + 27, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c51) { + s1 = peg$c51; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c52); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c53(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c54) { + s1 = peg$c54; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c55); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c56(); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 28, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_sep(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_sep(); + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c57(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parsearray_value(); + if (s2 === peg$FAILED) { + s2 = peg$c25; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c58(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_value_list(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_value_list(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c9; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c59(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c7; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsearray_value_list(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsearray_value_list(); + } + } else { + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + s3 = peg$parsearray_value(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s4 = peg$c9; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c10); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c60(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_value() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 29, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsearray_sep(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsearray_sep(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsevalue(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsearray_sep(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsearray_sep(); + } + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c61(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_value_list() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 49 + 30, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parsearray_sep(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parsearray_sep(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsevalue(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parsearray_sep(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parsearray_sep(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s4 = peg$c62; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c63); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parsearray_sep(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parsearray_sep(); + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c61(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsearray_sep() { + var s0; + + var key = peg$currPos * 49 + 31, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseS(); + if (s0 === peg$FAILED) { + s0 = peg$parseNL(); + if (s0 === peg$FAILED) { + s0 = peg$parsecomment(); + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinline_table() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 49 + 32, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 123) { + s1 = peg$c64; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c65); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseS(); + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseS(); + } + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseinline_table_assignment(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseinline_table_assignment(); + } + if (s3 !== peg$FAILED) { + s4 = []; + s5 = peg$parseS(); + while (s5 !== peg$FAILED) { + s4.push(s5); + s5 = peg$parseS(); + } + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 125) { + s5 = peg$c66; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c67); } + } + if (s5 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c68(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseinline_table_assignment() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 33, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s4 = peg$c18; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parsevalue(); + if (s6 !== peg$FAILED) { + s7 = []; + s8 = peg$parseS(); + while (s8 !== peg$FAILED) { + s7.push(s8); + s8 = peg$parseS(); + } + if (s7 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s8 = peg$c62; + peg$currPos++; + } else { + s8 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c63); } + } + if (s8 !== peg$FAILED) { + s9 = []; + s10 = peg$parseS(); + while (s10 !== peg$FAILED) { + s9.push(s10); + s10 = peg$parseS(); + } + if (s9 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c69(s2, s6); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = []; + s2 = peg$parseS(); + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseS(); + } + if (s1 !== peg$FAILED) { + s2 = peg$parsekey(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$parseS(); + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$parseS(); + } + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s4 = peg$c18; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c19); } + } + if (s4 !== peg$FAILED) { + s5 = []; + s6 = peg$parseS(); + while (s6 !== peg$FAILED) { + s5.push(s6); + s6 = peg$parseS(); + } + if (s5 !== peg$FAILED) { + s6 = peg$parsevalue(); + if (s6 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c69(s2, s6); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesecfragment() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 34, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c16; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c17); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseDIGITS(); + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c70(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedate() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11; + + var key = peg$currPos * 49 + 35, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + s4 = peg$parseDIGIT_OR_UNDER(); + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s6 = peg$c47; + peg$currPos++; + } else { + s6 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s6 !== peg$FAILED) { + s7 = peg$parseDIGIT_OR_UNDER(); + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s9 = peg$c47; + peg$currPos++; + } else { + s9 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s9 !== peg$FAILED) { + s10 = peg$parseDIGIT_OR_UNDER(); + if (s10 !== peg$FAILED) { + s11 = peg$parseDIGIT_OR_UNDER(); + if (s11 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c71(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetime() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 36, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c72; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT_OR_UNDER(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c72; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + s9 = peg$parseDIGIT_OR_UNDER(); + if (s9 !== peg$FAILED) { + s10 = peg$parsesecfragment(); + if (s10 === peg$FAILED) { + s10 = peg$c25; + } + if (s10 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c74(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetime_with_offset() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16; + + var key = peg$currPos * 49 + 37, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + s3 = peg$parseDIGIT_OR_UNDER(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s4 = peg$c72; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseDIGIT_OR_UNDER(); + if (s5 !== peg$FAILED) { + s6 = peg$parseDIGIT_OR_UNDER(); + if (s6 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s7 = peg$c72; + peg$currPos++; + } else { + s7 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s7 !== peg$FAILED) { + s8 = peg$parseDIGIT_OR_UNDER(); + if (s8 !== peg$FAILED) { + s9 = peg$parseDIGIT_OR_UNDER(); + if (s9 !== peg$FAILED) { + s10 = peg$parsesecfragment(); + if (s10 === peg$FAILED) { + s10 = peg$c25; + } + if (s10 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 45) { + s11 = peg$c47; + peg$currPos++; + } else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c48); } + } + if (s11 === peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s11 = peg$c44; + peg$currPos++; + } else { + s11 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c45); } + } + } + if (s11 !== peg$FAILED) { + s12 = peg$parseDIGIT_OR_UNDER(); + if (s12 !== peg$FAILED) { + s13 = peg$parseDIGIT_OR_UNDER(); + if (s13 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 58) { + s14 = peg$c72; + peg$currPos++; + } else { + s14 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s14 !== peg$FAILED) { + s15 = peg$parseDIGIT_OR_UNDER(); + if (s15 !== peg$FAILED) { + s16 = peg$parseDIGIT_OR_UNDER(); + if (s16 !== peg$FAILED) { + s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + } else { + peg$currPos = s1; + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c74(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsedatetime() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 49 + 38, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsedate(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 84) { + s2 = peg$c75; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c76); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetime(); + if (s3 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 90) { + s4 = peg$c77; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c78); } + } + if (s4 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c79(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parsedate(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 84) { + s2 = peg$c75; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c76); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parsetime_with_offset(); + if (s3 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c80(s1, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseS() { + var s0; + + var key = peg$currPos * 49 + 39, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c81.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c82); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseNL() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 40, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (input.charCodeAt(peg$currPos) === 10) { + s0 = peg$c83; + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c84); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 13) { + s1 = peg$c85; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c86); } + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 10) { + s2 = peg$c83; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c84); } + } + if (s2 !== peg$FAILED) { + s1 = [s1, s2]; + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseNLS() { + var s0; + + var key = peg$currPos * 49 + 41, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$parseNL(); + if (s0 === peg$FAILED) { + s0 = peg$parseS(); + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseEOF() { + var s0, s1; + + var key = peg$currPos * 49 + 42, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + peg$silentFails++; + if (input.length > peg$currPos) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c6); } + } + peg$silentFails--; + if (s1 === peg$FAILED) { + s0 = peg$c5; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseHEX() { + var s0; + + var key = peg$currPos * 49 + 43, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c87.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c88); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseDIGIT_OR_UNDER() { + var s0, s1; + + var key = peg$currPos * 49 + 44, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c89.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c90); } + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 95) { + s1 = peg$c91; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c92); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c93(); + } + s0 = s1; + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseASCII_BASIC() { + var s0; + + var key = peg$currPos * 49 + 45, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + if (peg$c94.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c95); } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseDIGITS() { + var s0, s1, s2; + + var key = peg$currPos * 49 + 46, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + s2 = peg$parseDIGIT_OR_UNDER(); + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + s2 = peg$parseDIGIT_OR_UNDER(); + } + } else { + s1 = peg$c2; + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c96(s1); + } + s0 = s1; + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseESCAPED() { + var s0, s1; + + var key = peg$currPos * 49 + 47, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c97) { + s1 = peg$c97; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c98); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c99(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c100) { + s1 = peg$c100; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c101); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c102(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c103) { + s1 = peg$c103; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c104); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c105(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c106) { + s1 = peg$c106; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c107); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c108(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c109) { + s1 = peg$c109; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c110); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c111(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c112) { + s1 = peg$c112; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c113); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c114(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c115) { + s1 = peg$c115; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c116); } + } + if (s1 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c117(); + } + s0 = s1; + if (s0 === peg$FAILED) { + s0 = peg$parseESCAPED_UNICODE(); + } + } + } + } + } + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseESCAPED_UNICODE() { + var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; + + var key = peg$currPos * 49 + 48, + cached = peg$cache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c118) { + s1 = peg$c118; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c119); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseHEX(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEX(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHEX(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHEX(); + if (s6 !== peg$FAILED) { + s7 = peg$parseHEX(); + if (s7 !== peg$FAILED) { + s8 = peg$parseHEX(); + if (s8 !== peg$FAILED) { + s9 = peg$parseHEX(); + if (s9 !== peg$FAILED) { + s10 = peg$parseHEX(); + if (s10 !== peg$FAILED) { + s3 = [s3, s4, s5, s6, s7, s8, s9, s10]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c120(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.substr(peg$currPos, 2) === peg$c121) { + s1 = peg$c121; + peg$currPos += 2; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c122); } + } + if (s1 !== peg$FAILED) { + s2 = peg$currPos; + s3 = peg$parseHEX(); + if (s3 !== peg$FAILED) { + s4 = peg$parseHEX(); + if (s4 !== peg$FAILED) { + s5 = peg$parseHEX(); + if (s5 !== peg$FAILED) { + s6 = peg$parseHEX(); + if (s6 !== peg$FAILED) { + s3 = [s3, s4, s5, s6]; + s2 = s3; + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + } else { + peg$currPos = s2; + s2 = peg$c2; + } + if (s2 !== peg$FAILED) { + peg$reportedPos = s0; + s1 = peg$c120(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } else { + peg$currPos = s0; + s0 = peg$c2; + } + } + + peg$cache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + + var nodes = []; + + function genError(err, line, col) { + var ex = new Error(err); + ex.line = line; + ex.column = col; + throw ex; + } + + function addNode(node) { + nodes.push(node); + } + + function node(type, value, line, column, key) { + var obj = { type: type, value: value, line: line(), column: column() }; + if (key) obj.key = key; + return obj; + } + + function convertCodePoint(str, line, col) { + var num = parseInt("0x" + str); + + if ( + !isFinite(num) || + Math.floor(num) != num || + num < 0 || + num > 0x10FFFF || + (num > 0xD7FF && num < 0xE000) + ) { + genError("Invalid Unicode escape code: " + str, line, col); + } else { + return fromCodePoint(num); + } + } + + function fromCodePoint() { + var MAX_SIZE = 0x4000; + var codeUnits = []; + var highSurrogate; + var lowSurrogate; + var index = -1; + var length = arguments.length; + if (!length) { + return ''; + } + var result = ''; + while (++index < length) { + var codePoint = Number(arguments[index]); + if (codePoint <= 0xFFFF) { // BMP code point + codeUnits.push(codePoint); + } else { // Astral code point; split in surrogate halves + // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + codePoint -= 0x10000; + highSurrogate = (codePoint >> 10) + 0xD800; + lowSurrogate = (codePoint % 0x400) + 0xDC00; + codeUnits.push(highSurrogate, lowSurrogate); + } + if (index + 1 == length || codeUnits.length > MAX_SIZE) { + result += String.fromCharCode.apply(null, codeUnits); + codeUnits.length = 0; + } + } + return result; + } + + + peg$result = peg$startRuleFunction(); + + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail({ type: "end", description: "end of input" }); + } + + throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos); + } + } + + return { + SyntaxError: SyntaxError, + parse: parse + }; +})(); diff --git a/node_modules/toml/package.json b/node_modules/toml/package.json new file mode 100644 index 000000000..186ad008f --- /dev/null +++ b/node_modules/toml/package.json @@ -0,0 +1,24 @@ +{ + "name": "toml", + "version": "3.0.0", + "description": "TOML parser for Node.js (parses TOML spec v0.4.0)", + "main": "index.js", + "types": "index.d.ts", + "scripts": { + "build": "pegjs --cache src/toml.pegjs lib/parser.js", + "test": "jshint lib/compiler.js && nodeunit test/test_*.js", + "prepublish": "npm run build" + }, + "repository": "git://github.com/BinaryMuse/toml-node.git", + "keywords": [ + "toml", + "parser" + ], + "author": "Michelle Tilley ", + "license": "MIT", + "devDependencies": { + "jshint": "*", + "nodeunit": "~0.9.0", + "pegjs": "~0.8.0" + } +} diff --git a/node_modules/toml/src/toml.pegjs b/node_modules/toml/src/toml.pegjs new file mode 100644 index 000000000..705170782 --- /dev/null +++ b/node_modules/toml/src/toml.pegjs @@ -0,0 +1,231 @@ +{ + var nodes = []; + + function genError(err, line, col) { + var ex = new Error(err); + ex.line = line; + ex.column = col; + throw ex; + } + + function addNode(node) { + nodes.push(node); + } + + function node(type, value, line, column, key) { + var obj = { type: type, value: value, line: line(), column: column() }; + if (key) obj.key = key; + return obj; + } + + function convertCodePoint(str, line, col) { + var num = parseInt("0x" + str); + + if ( + !isFinite(num) || + Math.floor(num) != num || + num < 0 || + num > 0x10FFFF || + (num > 0xD7FF && num < 0xE000) + ) { + genError("Invalid Unicode escape code: " + str, line, col); + } else { + return fromCodePoint(num); + } + } + + function fromCodePoint() { + var MAX_SIZE = 0x4000; + var codeUnits = []; + var highSurrogate; + var lowSurrogate; + var index = -1; + var length = arguments.length; + if (!length) { + return ''; + } + var result = ''; + while (++index < length) { + var codePoint = Number(arguments[index]); + if (codePoint <= 0xFFFF) { // BMP code point + codeUnits.push(codePoint); + } else { // Astral code point; split in surrogate halves + // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + codePoint -= 0x10000; + highSurrogate = (codePoint >> 10) + 0xD800; + lowSurrogate = (codePoint % 0x400) + 0xDC00; + codeUnits.push(highSurrogate, lowSurrogate); + } + if (index + 1 == length || codeUnits.length > MAX_SIZE) { + result += String.fromCharCode.apply(null, codeUnits); + codeUnits.length = 0; + } + } + return result; + } +} + +start + = line* { return nodes } + +line + = S* expr:expression S* comment* (NL+ / EOF) + / S+ (NL+ / EOF) + / NL + +expression + = comment / path / tablearray / assignment + +comment + = '#' (!(NL / EOF) .)* + +path + = '[' S* name:table_key S* ']' { addNode(node('ObjectPath', name, line, column)) } + +tablearray + = '[' '[' S* name:table_key S* ']' ']' { addNode(node('ArrayPath', name, line, column)) } + +table_key + = parts:dot_ended_table_key_part+ name:table_key_part { return parts.concat(name) } + / name:table_key_part { return [name] } + +table_key_part + = S* name:key S* { return name } + / S* name:quoted_key S* { return name } + +dot_ended_table_key_part + = S* name:key S* '.' S* { return name } + / S* name:quoted_key S* '.' S* { return name } + +assignment + = key:key S* '=' S* value:value { addNode(node('Assign', value, line, column, key)) } + / key:quoted_key S* '=' S* value:value { addNode(node('Assign', value, line, column, key)) } + +key + = chars:ASCII_BASIC+ { return chars.join('') } + +quoted_key + = node:double_quoted_single_line_string { return node.value } + / node:single_quoted_single_line_string { return node.value } + +value + = string / datetime / float / integer / boolean / array / inline_table + +string + = double_quoted_multiline_string + / double_quoted_single_line_string + / single_quoted_multiline_string + / single_quoted_single_line_string + +double_quoted_multiline_string + = '"""' NL? chars:multiline_string_char* '"""' { return node('String', chars.join(''), line, column) } +double_quoted_single_line_string + = '"' chars:string_char* '"' { return node('String', chars.join(''), line, column) } +single_quoted_multiline_string + = "'''" NL? chars:multiline_literal_char* "'''" { return node('String', chars.join(''), line, column) } +single_quoted_single_line_string + = "'" chars:literal_char* "'" { return node('String', chars.join(''), line, column) } + +string_char + = ESCAPED / (!'"' char:. { return char }) + +literal_char + = (!"'" char:. { return char }) + +multiline_string_char + = ESCAPED / multiline_string_delim / (!'"""' char:. { return char}) + +multiline_string_delim + = '\\' NL NLS* { return '' } + +multiline_literal_char + = (!"'''" char:. { return char }) + +float + = left:(float_text / integer_text) ('e' / 'E') right:integer_text { return node('Float', parseFloat(left + 'e' + right), line, column) } + / text:float_text { return node('Float', parseFloat(text), line, column) } + +float_text + = '+'? digits:(DIGITS '.' DIGITS) { return digits.join('') } + / '-' digits:(DIGITS '.' DIGITS) { return '-' + digits.join('') } + +integer + = text:integer_text { return node('Integer', parseInt(text, 10), line, column) } + +integer_text + = '+'? digits:DIGIT+ !'.' { return digits.join('') } + / '-' digits:DIGIT+ !'.' { return '-' + digits.join('') } + +boolean + = 'true' { return node('Boolean', true, line, column) } + / 'false' { return node('Boolean', false, line, column) } + +array + = '[' array_sep* ']' { return node('Array', [], line, column) } + / '[' value:array_value? ']' { return node('Array', value ? [value] : [], line, column) } + / '[' values:array_value_list+ ']' { return node('Array', values, line, column) } + / '[' values:array_value_list+ value:array_value ']' { return node('Array', values.concat(value), line, column) } + +array_value + = array_sep* value:value array_sep* { return value } + +array_value_list + = array_sep* value:value array_sep* ',' array_sep* { return value } + +array_sep + = S / NL / comment + +inline_table + = '{' S* values:inline_table_assignment* S* '}' { return node('InlineTable', values, line, column) } + +inline_table_assignment + = S* key:key S* '=' S* value:value S* ',' S* { return node('InlineTableValue', value, line, column, key) } + / S* key:key S* '=' S* value:value { return node('InlineTableValue', value, line, column, key) } + +secfragment + = '.' digits:DIGITS { return "." + digits } + +date + = date:( + DIGIT DIGIT DIGIT DIGIT + '-' + DIGIT DIGIT + '-' + DIGIT DIGIT + ) { return date.join('') } + +time + = time:(DIGIT DIGIT ':' DIGIT DIGIT ':' DIGIT DIGIT secfragment?) { return time.join('') } + +time_with_offset + = time:( + DIGIT DIGIT ':' DIGIT DIGIT ':' DIGIT DIGIT secfragment? + ('-' / '+') + DIGIT DIGIT ':' DIGIT DIGIT + ) { return time.join('') } + +datetime + = date:date 'T' time:time 'Z' { return node('Date', new Date(date + "T" + time + "Z"), line, column) } + / date:date 'T' time:time_with_offset { return node('Date', new Date(date + "T" + time), line, column) } + + +S = [ \t] +NL = "\n" / "\r" "\n" +NLS = NL / S +EOF = !. +HEX = [0-9a-f]i +DIGIT = DIGIT_OR_UNDER +DIGIT_OR_UNDER = [0-9] + / '_' { return "" } +ASCII_BASIC = [A-Za-z0-9_\-] +DIGITS = d:DIGIT_OR_UNDER+ { return d.join('') } +ESCAPED = '\\"' { return '"' } + / '\\\\' { return '\\' } + / '\\b' { return '\b' } + / '\\t' { return '\t' } + / '\\n' { return '\n' } + / '\\f' { return '\f' } + / '\\r' { return '\r' } + / ESCAPED_UNICODE +ESCAPED_UNICODE = "\\U" digits:(HEX HEX HEX HEX HEX HEX HEX HEX) { return convertCodePoint(digits.join('')) } + / "\\u" digits:(HEX HEX HEX HEX) { return convertCodePoint(digits.join('')) } diff --git a/node_modules/toml/test/bad.toml b/node_modules/toml/test/bad.toml new file mode 100644 index 000000000..d51c3f310 --- /dev/null +++ b/node_modules/toml/test/bad.toml @@ -0,0 +1,5 @@ +[something] +awesome = "this is" + +[something.awesome] +this = "isn't" diff --git a/node_modules/toml/test/example.toml b/node_modules/toml/test/example.toml new file mode 100644 index 000000000..ea9dc35d3 --- /dev/null +++ b/node_modules/toml/test/example.toml @@ -0,0 +1,32 @@ +# This is a TOML document. Boom. + +title = "TOML Example" + +[owner] +name = "Tom Preston-Werner" +organization = "GitHub" +bio = "GitHub Cofounder & CEO\n\tLikes \"tater tots\" and beer and backslashes: \\" +dob = 1979-05-27T07:32:00Z # First class dates? Why not? + +[database] +server = "192.168.1.1" +ports = [ 8001, 8001, 8003 ] +connection_max = 5000 +connection_min = -2 # Don't ask me how +max_temp = 87.1 # It's a float +min_temp = -17.76 +enabled = true + +[servers] + + # You can indent as you please. Tabs or spaces. TOML don't care. + [servers.alpha] + ip = "10.0.0.1" + dc = "eqdc10" + + [servers.beta] + ip = "10.0.0.2" + dc = "eqdc10" + +[clients] +data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it diff --git a/node_modules/toml/test/hard_example.toml b/node_modules/toml/test/hard_example.toml new file mode 100644 index 000000000..38856c873 --- /dev/null +++ b/node_modules/toml/test/hard_example.toml @@ -0,0 +1,33 @@ +# Test file for TOML +# Only this one tries to emulate a TOML file written by a user of the kind of parser writers probably hate +# This part you'll really hate + +[the] +test_string = "You'll hate me after this - #" # " Annoying, isn't it? + + [the.hard] + test_array = [ "] ", " # "] # ] There you go, parse this! + test_array2 = [ "Test #11 ]proved that", "Experiment #9 was a success" ] + # You didn't think it'd as easy as chucking out the last #, did you? + another_test_string = " Same thing, but with a string #" + harder_test_string = " And when \"'s are in the string, along with # \"" # "and comments are there too" + # Things will get harder + + [the.hard."bit#"] + "what?" = "You don't think some user won't do that?" + multi_line_array = [ + "]", + # ] Oh yes I did + ] + +# Each of the following keygroups/key value pairs should produce an error. Uncomment to them to test + +#[error] if you didn't catch this, your parser is broken +#string = "Anything other than tabs, spaces and newline after a keygroup or key value pair has ended should produce an error unless it is a comment" like this +#array = [ +# "This might most likely happen in multiline arrays", +# Like here, +# "or here, +# and here" +# ] End of array comment, forgot the # +#number = 3.14 pi <--again forgot the # diff --git a/node_modules/toml/test/inline_tables.toml b/node_modules/toml/test/inline_tables.toml new file mode 100644 index 000000000..c91088eec --- /dev/null +++ b/node_modules/toml/test/inline_tables.toml @@ -0,0 +1,10 @@ +name = { first = "Tom", last = "Preston-Werner" } +point = { x = 1, y = 2 } +nested = { x = { a = { b = 3 } } } + +points = [ { x = 1, y = 2, z = 3 }, + { x = 7, y = 8, z = 9 }, + { x = 2, y = 4, z = 8 } ] + +arrays = [ { x = [1, 2, 3], y = [4, 5, 6] }, + { x = [7, 8, 9], y = [0, 1, 2] } ] diff --git a/node_modules/toml/test/literal_strings.toml b/node_modules/toml/test/literal_strings.toml new file mode 100644 index 000000000..36772bb6e --- /dev/null +++ b/node_modules/toml/test/literal_strings.toml @@ -0,0 +1,5 @@ +# What you see is what you get. +winpath = 'C:\Users\nodejs\templates' +winpath2 = '\\ServerX\admin$\system32\' +quoted = 'Tom "Dubs" Preston-Werner' +regex = '<\i\c*\s*>' diff --git a/node_modules/toml/test/multiline_eat_whitespace.toml b/node_modules/toml/test/multiline_eat_whitespace.toml new file mode 100644 index 000000000..904c17076 --- /dev/null +++ b/node_modules/toml/test/multiline_eat_whitespace.toml @@ -0,0 +1,15 @@ +# The following strings are byte-for-byte equivalent: +key1 = "The quick brown fox jumps over the lazy dog." + +key2 = """ +The quick brown \ + + + fox jumps over \ + the lazy dog.""" + +key3 = """\ + The quick brown \ + fox jumps over \ + the lazy dog.\ + """ diff --git a/node_modules/toml/test/multiline_literal_strings.toml b/node_modules/toml/test/multiline_literal_strings.toml new file mode 100644 index 000000000..bc88494c4 --- /dev/null +++ b/node_modules/toml/test/multiline_literal_strings.toml @@ -0,0 +1,7 @@ +regex2 = '''I [dw]on't need \d{2} apples''' +lines = ''' +The first newline is +trimmed in raw strings. + All other whitespace + is preserved. +''' diff --git a/node_modules/toml/test/multiline_strings.toml b/node_modules/toml/test/multiline_strings.toml new file mode 100644 index 000000000..6eb8c45af --- /dev/null +++ b/node_modules/toml/test/multiline_strings.toml @@ -0,0 +1,6 @@ +# The following strings are byte-for-byte equivalent: +key1 = "One\nTwo" +key2 = """One\nTwo""" +key3 = """ +One +Two""" diff --git a/node_modules/toml/test/smoke.js b/node_modules/toml/test/smoke.js new file mode 100644 index 000000000..7769f9c4f --- /dev/null +++ b/node_modules/toml/test/smoke.js @@ -0,0 +1,22 @@ +var fs = require('fs'); +var parser = require('../index'); + +var codes = [ + "# test\n my.key=\"value\"\nother = 101\nthird = -37", + "first = 1.2\nsecond = -56.02\nth = true\nfth = false", + "time = 1979-05-27T07:32:00Z", + "test = [\"one\", ]", + "test = [[1, 2,], [true, false,],]", + "[my.sub.path]\nkey = true\nother = -15.3\n[my.sub]\nkey=false", + "arry = [\"one\", \"two\",\"thr\nee\", \"\\u03EA\"]", + fs.readFileSync(__dirname + '/example.toml', 'utf8'), + fs.readFileSync(__dirname + '/hard_example.toml', 'utf8') +] + +console.log("============================================="); +for(i in codes) { + var code = codes[i]; + console.log(code + "\n"); + console.log(JSON.stringify(parser.parse(code))); + console.log("============================================="); +} diff --git a/node_modules/toml/test/table_arrays_easy.toml b/node_modules/toml/test/table_arrays_easy.toml new file mode 100644 index 000000000..ac3883bbc --- /dev/null +++ b/node_modules/toml/test/table_arrays_easy.toml @@ -0,0 +1,10 @@ +[[products]] +name = "Hammer" +sku = 738594937 + +[[products]] + +[[products]] +name = "Nail" +sku = 284758393 +color = "gray" diff --git a/node_modules/toml/test/table_arrays_hard.toml b/node_modules/toml/test/table_arrays_hard.toml new file mode 100644 index 000000000..2ade5409a --- /dev/null +++ b/node_modules/toml/test/table_arrays_hard.toml @@ -0,0 +1,31 @@ +[[fruit]] +name = "durian" +variety = [] + +[[fruit]] +name = "apple" + + [fruit.physical] + color = "red" + shape = "round" + + [[fruit.variety]] + name = "red delicious" + + [[fruit.variety]] + name = "granny smith" + +[[fruit]] + +[[fruit]] +name = "banana" + + [[fruit.variety]] + name = "plantain" + +[[fruit]] +name = "orange" + +[fruit.physical] +color = "orange" +shape = "round" diff --git a/node_modules/toml/test/test_toml.js b/node_modules/toml/test/test_toml.js new file mode 100644 index 000000000..1f654b396 --- /dev/null +++ b/node_modules/toml/test/test_toml.js @@ -0,0 +1,596 @@ +var toml = require('../'); +var fs = require('fs'); + +var assert = require("nodeunit").assert; + +assert.parsesToml = function(tomlStr, expected) { + try { + var actual = toml.parse(tomlStr); + } catch (e) { + var errInfo = "line: " + e.line + ", column: " + e.column; + return assert.fail("TOML parse error: " + e.message, errInfo, null, "at", assert.parsesToml); + } + return assert.deepEqual(actual, expected); +}; + +var exampleExpected = { + title: "TOML Example", + owner: { + name: "Tom Preston-Werner", + organization: "GitHub", + bio: "GitHub Cofounder & CEO\n\tLikes \"tater tots\" and beer and backslashes: \\", + dob: new Date("1979-05-27T07:32:00Z") + }, + database: { + server: "192.168.1.1", + ports: [8001, 8001, 8003], + connection_max: 5000, + connection_min: -2, + max_temp: 87.1, + min_temp: -17.76, + enabled: true + }, + servers: { + alpha: { + ip: "10.0.0.1", + dc: "eqdc10" + }, + beta: { + ip: "10.0.0.2", + dc: "eqdc10" + } + }, + clients: { + data: [ ["gamma", "delta"], [1, 2] ] + } +}; + +var hardExampleExpected = { + the: { + hard: { + another_test_string: ' Same thing, but with a string #', + 'bit#': { + multi_line_array: [']'], + 'what?': "You don't think some user won't do that?" + }, + harder_test_string: " And when \"'s are in the string, along with # \"", + test_array: ['] ', ' # '], + test_array2: ['Test #11 ]proved that', 'Experiment #9 was a success'] + }, + test_string: "You'll hate me after this - #" + } +}; + +var easyTableArrayExpected = { + "products": [ + { "name": "Hammer", "sku": 738594937 }, + { }, + { "name": "Nail", "sku": 284758393, "color": "gray" } + ] +}; + +var hardTableArrayExpected = { + "fruit": [ + { + "name": "durian", + "variety": [] + }, + { + "name": "apple", + "physical": { + "color": "red", + "shape": "round" + }, + "variety": [ + { "name": "red delicious" }, + { "name": "granny smith" } + ] + }, + {}, + { + "name": "banana", + "variety": [ + { "name": "plantain" } + ] + }, + { + "name": "orange", + "physical": { + "color": "orange", + "shape": "round" + } + } + ] +} + +var badInputs = [ + '[error] if you didn\'t catch this, your parser is broken', + 'string = "Anything other than tabs, spaces and newline after a table or key value pair has ended should produce an error unless it is a comment" like this', + 'array = [\n \"This might most likely happen in multiline arrays\",\n Like here,\n \"or here,\n and here\"\n ] End of array comment, forgot the #', + 'number = 3.14 pi <--again forgot the #' +]; + +exports.testParsesExample = function(test) { + var str = fs.readFileSync(__dirname + "/example.toml", 'utf-8') + test.parsesToml(str, exampleExpected); + test.done(); +}; + +exports.testParsesHardExample = function(test) { + var str = fs.readFileSync(__dirname + "/hard_example.toml", 'utf-8') + test.parsesToml(str, hardExampleExpected); + test.done(); +}; + +exports.testEasyTableArrays = function(test) { + var str = fs.readFileSync(__dirname + "/table_arrays_easy.toml", 'utf8') + test.parsesToml(str, easyTableArrayExpected); + test.done(); +}; + +exports.testHarderTableArrays = function(test) { + var str = fs.readFileSync(__dirname + "/table_arrays_hard.toml", 'utf8') + test.parsesToml(str, hardTableArrayExpected); + test.done(); +}; + +exports.testSupportsTrailingCommasInArrays = function(test) { + var str = 'arr = [1, 2, 3,]'; + var expected = { arr: [1, 2, 3] }; + test.parsesToml(str, expected); + test.done(); +}; + +exports.testSingleElementArrayWithNoTrailingComma = function(test) { + var str = "a = [1]"; + test.parsesToml(str, { + a: [1] + }); + test.done(); +}; + +exports.testEmptyArray = function(test) { + var str = "a = []"; + test.parsesToml(str, { + a: [] + }); + test.done(); +}; + +exports.testArrayWithWhitespace = function(test) { + var str = "[versions]\nfiles = [\n 3, \n 5 \n\n ]"; + test.parsesToml(str, { + versions: { + files: [3, 5] + } + }); + test.done(); +}; + +exports.testEmptyArrayWithWhitespace = function(test) { + var str = "[versions]\nfiles = [\n \n ]"; + test.parsesToml(str, { + versions: { + files: [] + } + }); + test.done(); +}; + +exports.testDefineOnSuperkey = function(test) { + var str = "[a.b]\nc = 1\n\n[a]\nd = 2"; + var expected = { + a: { + b: { + c: 1 + }, + d: 2 + } + }; + test.parsesToml(str, expected); + test.done(); +}; + +exports.testWhitespace = function(test) { + var str = "a = 1\n \n b = 2 "; + test.parsesToml(str, { + a: 1, b: 2 + }); + test.done(); +}; + +exports.testUnicode = function(test) { + var str = "str = \"My name is Jos\\u00E9\""; + test.parsesToml(str, { + str: "My name is Jos\u00E9" + }); + + var str = "str = \"My name is Jos\\U000000E9\""; + test.parsesToml(str, { + str: "My name is Jos\u00E9" + }); + test.done(); +}; + +exports.testMultilineStrings = function(test) { + var str = fs.readFileSync(__dirname + "/multiline_strings.toml", 'utf8'); + test.parsesToml(str, { + key1: "One\nTwo", + key2: "One\nTwo", + key3: "One\nTwo" + }); + test.done(); +}; + +exports.testMultilineEatWhitespace = function(test) { + var str = fs.readFileSync(__dirname + "/multiline_eat_whitespace.toml", 'utf8'); + test.parsesToml(str, { + key1: "The quick brown fox jumps over the lazy dog.", + key2: "The quick brown fox jumps over the lazy dog.", + key3: "The quick brown fox jumps over the lazy dog." + }); + test.done(); +}; + +exports.testLiteralStrings = function(test) { + var str = fs.readFileSync(__dirname + "/literal_strings.toml", 'utf8'); + test.parsesToml(str, { + winpath: "C:\\Users\\nodejs\\templates", + winpath2: "\\\\ServerX\\admin$\\system32\\", + quoted: "Tom \"Dubs\" Preston-Werner", + regex: "<\\i\\c*\\s*>" + }); + test.done(); +}; + +exports.testMultilineLiteralStrings = function(test) { + var str = fs.readFileSync(__dirname + "/multiline_literal_strings.toml", 'utf8'); + test.parsesToml(str, { + regex2: "I [dw]on't need \\d{2} apples", + lines: "The first newline is\ntrimmed in raw strings.\n All other whitespace\n is preserved.\n" + }); + test.done(); +}; + +exports.testIntegerFormats = function(test) { + var str = "a = +99\nb = 42\nc = 0\nd = -17\ne = 1_000_001\nf = 1_2_3_4_5 # why u do dis"; + test.parsesToml(str, { + a: 99, + b: 42, + c: 0, + d: -17, + e: 1000001, + f: 12345 + }); + test.done(); +}; + +exports.testFloatFormats = function(test) { + var str = "a = +1.0\nb = 3.1415\nc = -0.01\n" + + "d = 5e+22\ne = 1e6\nf = -2E-2\n" + + "g = 6.626e-34\n" + + "h = 9_224_617.445_991_228_313\n" + + "i = 1e1_000"; + test.parsesToml(str, { + a: 1.0, + b: 3.1415, + c: -0.01, + d: 5e22, + e: 1e6, + f: -2e-2, + g: 6.626e-34, + h: 9224617.445991228313, + i: 1e1000 + }); + test.done(); +}; + +exports.testDate = function(test) { + var date = new Date("1979-05-27T07:32:00Z"); + test.parsesToml("a = 1979-05-27T07:32:00Z", { + a: date + }); + test.done(); +}; + +exports.testDateWithOffset = function(test) { + var date1 = new Date("1979-05-27T07:32:00-07:00"), + date2 = new Date("1979-05-27T07:32:00+02:00"); + test.parsesToml("a = 1979-05-27T07:32:00-07:00\nb = 1979-05-27T07:32:00+02:00", { + a: date1, + b: date2 + }); + test.done(); +}; + +exports.testDateWithSecondFraction = function(test) { + var date = new Date("1979-05-27T00:32:00.999999-07:00"); + test.parsesToml("a = 1979-05-27T00:32:00.999999-07:00", { + a: date + }); + test.done(); +}; + +exports.testDateFromIsoString = function(test) { + // https://github.com/BinaryMuse/toml-node/issues/20 + var date = new Date(), + dateStr = date.toISOString(), + tomlStr = "a = " + dateStr; + + test.parsesToml(tomlStr, { + a: date + }); + test.done(); +}; + +exports.testLeadingNewlines = function(test) { + // https://github.com/BinaryMuse/toml-node/issues/22 + var str = "\ntest = \"ing\""; + test.parsesToml(str, { + test: "ing" + }); + test.done(); +}; + +exports.testInlineTables = function(test) { + var str = fs.readFileSync(__dirname + "/inline_tables.toml", 'utf8'); + test.parsesToml(str, { + name: { + first: "Tom", + last: "Preston-Werner" + }, + point: { + x: 1, + y: 2 + }, + nested: { + x: { + a: { + b: 3 + } + } + }, + points: [ + { x: 1, y: 2, z: 3 }, + { x: 7, y: 8, z: 9 }, + { x: 2, y: 4, z: 8 } + ], + arrays: [ + { x: [1, 2, 3], y: [4, 5, 6] }, + { x: [7, 8, 9], y: [0, 1, 2] } + ] + }); + test.done(); +}; + +exports.testEmptyInlineTables = function(test) { + // https://github.com/BinaryMuse/toml-node/issues/24 + var str = "a = { }"; + test.parsesToml(str, { + a: {} + }); + test.done(); +}; + +exports.testKeyNamesWithWhitespaceAroundStartAndFinish = function(test) { + var str = "[ a ]\nb = 1"; + test.parsesToml(str, { + a: { + b: 1 + } + }); + test.done(); +}; + +exports.testKeyNamesWithWhitespaceAroundDots = function(test) { + var str = "[ a . b . c]\nd = 1"; + test.parsesToml(str, { + a: { + b: { + c: { + d: 1 + } + } + } + }); + test.done(); +}; + +exports.testSimpleQuotedKeyNames = function(test) { + var str = "[\"ʞ\"]\na = 1"; + test.parsesToml(str, { + "ʞ": { + a: 1 + } + }); + test.done(); +}; + +exports.testComplexQuotedKeyNames = function(test) { + var str = "[ a . \"ʞ\" . c ]\nd = 1"; + test.parsesToml(str, { + a: { + "ʞ": { + c: { + d: 1 + } + } + } + }); + test.done(); +}; + +exports.testEscapedQuotesInQuotedKeyNames = function(test) { + test.parsesToml("[\"the \\\"thing\\\"\"]\na = true", { + 'the "thing"': { + a: true + } + }); + test.done(); +}; + +exports.testMoreComplexQuotedKeyNames = function(test) { + // https://github.com/BinaryMuse/toml-node/issues/21 + test.parsesToml('["the\\ key"]\n\none = "one"\ntwo = 2\nthree = false', { + "the\\ key": { + one: "one", + two: 2, + three: false + } + }); + test.parsesToml('[a."the\\ key"]\n\none = "one"\ntwo = 2\nthree = false', { + a: { + "the\\ key": { + one: "one", + two: 2, + three: false + } + } + }); + test.parsesToml('[a."the-key"]\n\none = "one"\ntwo = 2\nthree = false', { + a: { + "the-key": { + one: "one", + two: 2, + three: false + } + } + }); + test.parsesToml('[a."the.key"]\n\none = "one"\ntwo = 2\nthree = false', { + a: { + "the.key": { + one: "one", + two: 2, + three: false + } + } + }); + // https://github.com/BinaryMuse/toml-node/issues/34 + test.parsesToml('[table]\n\'a "quoted value"\' = "value"', { + table: { + 'a "quoted value"': "value" + } + }); + // https://github.com/BinaryMuse/toml-node/issues/33 + test.parsesToml('[module]\n"foo=bar" = "zzz"', { + module: { + "foo=bar": "zzz" + } + }); + + test.done(); +}; + +exports.testErrorOnBadUnicode = function(test) { + var str = "str = \"My name is Jos\\uD800\""; + test.throws(function() { + toml.parse(str); + }); + test.done(); +}; + +exports.testErrorOnDotAtStartOfKey = function(test) { + test.throws(function() { + var str = "[.a]\nb = 1"; + toml.parse(str); + }); + test.done() +}; + +exports.testErrorOnDotAtEndOfKey = function(test) { + test.throws(function() { + var str = "[.a]\nb = 1"; + toml.parse(str); + }); + test.done() +}; + +exports.testErrorOnTableOverride = function(test) { + test.throws(function() { + var str = "[a]\nb = 1\n\n[a]\nc = 2"; + toml.parse(str); + }); + test.done() +}; + +exports.testErrorOnKeyOverride = function(test) { + test.throws(function() { + var str = "[a]\nb = 1\n[a.b]\nc = 2"; + toml.parse(str); + }); + test.done() +}; + +exports.testErrorOnKeyOverrideWithNested = function(test) { + // https://github.com/BinaryMuse/toml-node/issues/23 + test.throws(function() { + var str = "[a]\nb = \"a\"\n[a.b.c]"; + toml.parse(str); + }, "existing key 'a.b'"); + test.done(); +}; + +exports.testErrorOnKeyOverrideWithArrayTable = function(test) { + test.throws(function() { + var str = "[a]\nb = 1\n[[a]]\nc = 2"; + toml.parse(str); + }); + test.done() +}; + +exports.testErrorOnKeyReplace = function(test) { + test.throws(function() { + var str = "[a]\nb = 1\nb = 2"; + toml.parse(str); + }); + test.done() +}; + +exports.testErrorOnInlineTableReplace = function(test) { + // https://github.com/BinaryMuse/toml-node/issues/25 + test.throws(function() { + var str = "a = { b = 1 }\n[a]\nc = 2"; + toml.parse(str); + }, "existing key 'a'"); + test.done(); +}; + +exports.testErrorOnArrayMismatch = function(test) { + test.throws(function() { + var str = 'data = [1, 2, "test"]' + toml.parse(str); + }); + test.done(); +}; + +exports.testErrorOnBadInputs = function(test) { + var count = 0; + for (i in badInputs) { + (function(num) { + test.throws(function() { + toml.parse(badInputs[num]); + }); + })(i); + } + test.done(); +}; + +exports.testErrorsHaveCorrectLineAndColumn = function(test) { + var str = "[a]\nb = 1\n [a.b]\nc = 2"; + try { toml.parse(str); } + catch (e) { + test.equal(e.line, 3); + test.equal(e.column, 2); + test.done(); + } +}; + +exports.testUsingConstructorAsKey = function(test) { + test.parsesToml("[empty]\n[emptier]\n[constructor]\nconstructor = 1\n[emptiest]", { + "empty": {}, + "emptier": {}, + "constructor": { "constructor": 1 }, + "emptiest": {} + }); + test.done(); +}; diff --git a/node_modules/tweetnacl/AUTHORS.md b/node_modules/tweetnacl/AUTHORS.md new file mode 100644 index 000000000..598bc2df7 --- /dev/null +++ b/node_modules/tweetnacl/AUTHORS.md @@ -0,0 +1,27 @@ +List of TweetNaCl.js authors +============================ + + Format: Name (GitHub username or URL) + +* Dmitry Chestnykh (@dchest) +* Devi Mandiri (@devi) +* AndSDev (@AndSDev) + +List of authors of third-party public domain code from which TweetNaCl.js code was derived +========================================================================================== + +[TweetNaCl](http://tweetnacl.cr.yp.to/) +-------------------------------------- + +* Bernard van Gastel +* Daniel J. Bernstein +* Peter Schwabe +* Sjaak Smetsers +* Tanja Lange +* Wesley Janssen + + +[Poly1305-donna](https://github.com/floodyberry/poly1305-donna) +-------------------------------------------------------------- + +* Andrew Moon (@floodyberry) diff --git a/node_modules/tweetnacl/CHANGELOG.md b/node_modules/tweetnacl/CHANGELOG.md new file mode 100644 index 000000000..d1eba8c57 --- /dev/null +++ b/node_modules/tweetnacl/CHANGELOG.md @@ -0,0 +1,283 @@ +TweetNaCl.js Changelog +====================== + +v1.0.3 +------ + +***IMPORTANT BUG FIX***. Due to a bug in calculating carry in +modulo reduction that used bit operations on integers larger than +32 bits, `nacl.sign` or `nacl.sign.detached` could have created +incorrect signatures. + +This only affects signing, not verification. + +Thanks to @valerini on GitHub for finding and reporting the bug. + + +v1.0.2 +------ + +Exported more internal undocumented functions for +third-party projects that rely on low-level interface, +(something users of TweetNaCl shouldn't care about). + + +v1.0.1 +------ + +Updated documentation and typings. + + +v1.0.0 +------ + +No code changes from v1.0.0-rc.1. + + +v1.0.0-rc.1 +----------- + +* **IMPORTANT!** In previous versions, `nacl.secretbox.open`, `nacl.box.open`, + and `nacl.box.after` returned `false` when opening failed (for example, when + using incorrect key, nonce, or when input was maliciously or accidentally + modified after encryption). This version instead returns `null`. + + The usual way to check for this condition: + + `if (!result) { ... }` + + is correct and will continue to work. + + However, direct comparison with `false`: + + `if (result == false) { ... }` + + it will no longer work and **will not detect failure**. Please check + your code for this condition. + + (`nacl.sign.open` always returned `null`, so it is not affected.) + + +* Arguments type check now uses `instanceof Uint8Array` instead of `Object.prototype.toString`. +* Removed deprecation checks for `nacl.util` (moved to a + [separate package](https://github.com/dchest/tweetnacl-util-js) in v0.14.0). +* Removed deprecation checks for the old signature API (changed in v0.10.0). +* Improved benchmarking. + +v0.14.5 +------- + +* Fixed incomplete return types in TypeScript typings. +* Replaced COPYING.txt with LICENSE file, which now has public domain dedication + text from The Unlicense. License fields in package.json and bower.json have + been set to "Unlicense". The project was and will be in the public domain -- + this change just makes it easier for automated tools to know about this fact by + using the widely recognized and SPDX-compatible template for public domain + dedication. + + +v0.14.4 +------- + +* Added TypeScript type definitions (contributed by @AndSDev). +* Improved benchmarking code. + + +v0.14.3 +------- + +Fixed a bug in the fast version of Poly1305 and brought it back. + +Thanks to @floodyberry for promptly responding and fixing the original C code: + +> "The issue was not properly detecting if st->h was >= 2^130 - 5, coupled with +> [testing mistake] not catching the failure. The chance of the bug affecting +> anything in the real world is essentially zero luckily, but it's good to have +> it fixed." + +https://github.com/floodyberry/poly1305-donna/issues/2#issuecomment-202698577 + + +v0.14.2 +------- + +Switched Poly1305 fast version back to original (slow) version due to a bug. + + +v0.14.1 +------- + +No code changes, just tweaked packaging and added COPYING.txt. + + +v0.14.0 +------- + +* **Breaking change!** All functions from `nacl.util` have been removed. These + functions are no longer available: + + nacl.util.decodeUTF8 + nacl.util.encodeUTF8 + nacl.util.decodeBase64 + nacl.util.encodeBase64 + + If want to continue using them, you can include + package: + + + + + or + + var nacl = require('tweetnacl'); + nacl.util = require('tweetnacl-util'); + + However it is recommended to use better packages that have wider + compatibility and better performance. Functions from `nacl.util` were never + intended to be robust solution for string conversion and were included for + convenience: cryptography library is not the right place for them. + + Currently calling these functions will throw error pointing to + `tweetnacl-util-js` (in the next version this error message will be removed). + +* Improved detection of available random number generators, making it possible + to use `nacl.randomBytes` and related functions in Web Workers without + changes. + +* Changes to testing (see README). + + +v0.13.3 +------- + +No code changes. + +* Reverted license field in package.json to "Public domain". + +* Fixed typo in README. + + +v0.13.2 +------- + +* Fixed undefined variable bug in fast version of Poly1305. No worries, this + bug was *never* triggered. + +* Specified CC0 public domain dedication. + +* Updated development dependencies. + + +v0.13.1 +------- + +* Exclude `crypto` and `buffer` modules from browserify builds. + + +v0.13.0 +------- + +* Made `nacl-fast` the default version in NPM package. Now + `require("tweetnacl")` will use fast version; to get the original version, + use `require("tweetnacl/nacl.js")`. + +* Cleanup temporary array after generating random bytes. + + +v0.12.2 +------- + +* Improved performance of curve operations, making `nacl.scalarMult`, `nacl.box`, + `nacl.sign` and related functions up to 3x faster in `nacl-fast` version. + + +v0.12.1 +------- + +* Significantly improved performance of Salsa20 (~1.5x faster) and + Poly1305 (~3.5x faster) in `nacl-fast` version. + + +v0.12.0 +------- + +* Instead of using the given secret key directly, TweetNaCl.js now copies it to + a new array in `nacl.box.keyPair.fromSecretKey` and + `nacl.sign.keyPair.fromSecretKey`. + + +v0.11.2 +------- + +* Added new constant: `nacl.sign.seedLength`. + + +v0.11.1 +------- + +* Even faster hash for both short and long inputs (in `nacl-fast`). + + +v0.11.0 +------- + +* Implement `nacl.sign.keyPair.fromSeed` to enable creation of sign key pairs + deterministically from a 32-byte seed. (It behaves like + [libsodium's](http://doc.libsodium.org/public-key_cryptography/public-key_signatures.html) + `crypto_sign_seed_keypair`: the seed becomes a secret part of the secret key.) + +* Fast version now has an improved hash implementation that is 2x-5x faster. + +* Fixed benchmarks, which may have produced incorrect measurements. + + +v0.10.1 +------- + +* Exported undocumented `nacl.lowlevel.crypto_core_hsalsa20`. + + +v0.10.0 +------- + +* **Signature API breaking change!** `nacl.sign` and `nacl.sign.open` now deal + with signed messages, and new `nacl.sign.detached` and + `nacl.sign.detached.verify` are available. + + Previously, `nacl.sign` returned a signature, and `nacl.sign.open` accepted a + message and "detached" signature. This was unlike NaCl's API, which dealt with + signed messages (concatenation of signature and message). + + The new API is: + + nacl.sign(message, secretKey) -> signedMessage + nacl.sign.open(signedMessage, publicKey) -> message | null + + Since detached signatures are common, two new API functions were introduced: + + nacl.sign.detached(message, secretKey) -> signature + nacl.sign.detached.verify(message, signature, publicKey) -> true | false + + (Note that it's `verify`, not `open`, and it returns a boolean value, unlike + `open`, which returns an "unsigned" message.) + +* NPM package now comes without `test` directory to keep it small. + + +v0.9.2 +------ + +* Improved documentation. +* Fast version: increased theoretical message size limit from 2^32-1 to 2^52 + bytes in Poly1305 (and thus, secretbox and box). However this has no impact + in practice since JavaScript arrays or ArrayBuffers are limited to 32-bit + indexes, and most implementations won't allocate more than a gigabyte or so. + (Obviously, there are no tests for the correctness of implementation.) Also, + it's not recommended to use messages that large without splitting them into + smaller packets anyway. + + +v0.9.1 +------ + +* Initial release diff --git a/node_modules/tweetnacl/LICENSE b/node_modules/tweetnacl/LICENSE new file mode 100644 index 000000000..cf1ab25da --- /dev/null +++ b/node_modules/tweetnacl/LICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +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 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. + +For more information, please refer to diff --git a/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md b/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..a8eb4a9a9 --- /dev/null +++ b/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,20 @@ +# Important! + +If your contribution is not trivial (not a typo fix, etc.), we can only accept +it if you dedicate your copyright for the contribution to the public domain. +Make sure you understand what it means (see http://unlicense.org/)! If you +agree, please add yourself to AUTHORS.md file, and include the following text +to your pull request description or a comment in it: + +------------------------------------------------------------------------------ + + I dedicate any and all copyright interest in this software to the + public domain. I make this dedication for the benefit of the public at + large and to the detriment of my heirs and successors. I intend this + dedication to be an overt act of relinquishment in perpetuity of all + present and future rights to this software under copyright law. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. diff --git a/node_modules/tweetnacl/README.md b/node_modules/tweetnacl/README.md new file mode 100644 index 000000000..022bf6bf8 --- /dev/null +++ b/node_modules/tweetnacl/README.md @@ -0,0 +1,494 @@ +TweetNaCl.js +============ + +Port of [TweetNaCl](http://tweetnacl.cr.yp.to) / [NaCl](http://nacl.cr.yp.to/) +to JavaScript for modern browsers and Node.js. Public domain. + +[![Build Status](https://travis-ci.org/dchest/tweetnacl-js.svg?branch=master) +](https://travis-ci.org/dchest/tweetnacl-js) + +Demo: + +Documentation +============= + +* [Overview](#overview) +* [Audits](#audits) +* [Installation](#installation) +* [Examples](#examples) +* [Usage](#usage) + * [Public-key authenticated encryption (box)](#public-key-authenticated-encryption-box) + * [Secret-key authenticated encryption (secretbox)](#secret-key-authenticated-encryption-secretbox) + * [Scalar multiplication](#scalar-multiplication) + * [Signatures](#signatures) + * [Hashing](#hashing) + * [Random bytes generation](#random-bytes-generation) + * [Constant-time comparison](#constant-time-comparison) +* [System requirements](#system-requirements) +* [Development and testing](#development-and-testing) +* [Benchmarks](#benchmarks) +* [Contributors](#contributors) +* [Who uses it](#who-uses-it) + + +Overview +-------- + +The primary goal of this project is to produce a translation of TweetNaCl to +JavaScript which is as close as possible to the original C implementation, plus +a thin layer of idiomatic high-level API on top of it. + +There are two versions, you can use either of them: + +* `nacl.js` is the port of TweetNaCl with minimum differences from the + original + high-level API. + +* `nacl-fast.js` is like `nacl.js`, but with some functions replaced with + faster versions. (Used by default when importing NPM package.) + + +Audits +------ + +TweetNaCl.js has been audited by [Cure53](https://cure53.de/) in January-February +2017 (audit was sponsored by [Deletype](https://deletype.com)): + +> The overall outcome of this audit signals a particularly positive assessment +> for TweetNaCl-js, as the testing team was unable to find any security +> problems in the library. It has to be noted that this is an exceptionally +> rare result of a source code audit for any project and must be seen as a true +> testament to a development proceeding with security at its core. +> +> To reiterate, the TweetNaCl-js project, the source code was found to be +> bug-free at this point. +> +> [...] +> +> In sum, the testing team is happy to recommend the TweetNaCl-js project as +> likely one of the safer and more secure cryptographic tools among its +> competition. + +[Read full audit report](https://cure53.de/tweetnacl.pdf) + + +Installation +------------ + +You can install TweetNaCl.js via a package manager: + +[Yarn](https://yarnpkg.com/): + + $ yarn add tweetnacl + +[NPM](https://www.npmjs.org/): + + $ npm install tweetnacl + +or [download source code](https://github.com/dchest/tweetnacl-js/releases). + + +Examples +-------- +You can find usage examples in our [wiki](https://github.com/dchest/tweetnacl-js/wiki/Examples). + + +Usage +----- + +All API functions accept and return bytes as `Uint8Array`s. If you need to +encode or decode strings, use functions from + or one of the more robust codec +packages. + +In Node.js v4 and later `Buffer` objects are backed by `Uint8Array`s, so you +can freely pass them to TweetNaCl.js functions as arguments. The returned +objects are still `Uint8Array`s, so if you need `Buffer`s, you'll have to +convert them manually; make sure to convert using copying: `Buffer.from(array)` +(or `new Buffer(array)` in Node.js v4 or earlier), instead of sharing: +`Buffer.from(array.buffer)` (or `new Buffer(array.buffer)` Node 4 or earlier), +because some functions return subarrays of their buffers. + + +### Public-key authenticated encryption (box) + +Implements *x25519-xsalsa20-poly1305*. + +#### nacl.box.keyPair() + +Generates a new random key pair for box and returns it as an object with +`publicKey` and `secretKey` members: + + { + publicKey: ..., // Uint8Array with 32-byte public key + secretKey: ... // Uint8Array with 32-byte secret key + } + + +#### nacl.box.keyPair.fromSecretKey(secretKey) + +Returns a key pair for box with public key corresponding to the given secret +key. + +#### nacl.box(message, nonce, theirPublicKey, mySecretKey) + +Encrypts and authenticates message using peer's public key, our secret key, and +the given nonce, which must be unique for each distinct message for a key pair. + +Returns an encrypted and authenticated message, which is +`nacl.box.overheadLength` longer than the original message. + +#### nacl.box.open(box, nonce, theirPublicKey, mySecretKey) + +Authenticates and decrypts the given box with peer's public key, our secret +key, and the given nonce. + +Returns the original message, or `null` if authentication fails. + +#### nacl.box.before(theirPublicKey, mySecretKey) + +Returns a precomputed shared key which can be used in `nacl.box.after` and +`nacl.box.open.after`. + +#### nacl.box.after(message, nonce, sharedKey) + +Same as `nacl.box`, but uses a shared key precomputed with `nacl.box.before`. + +#### nacl.box.open.after(box, nonce, sharedKey) + +Same as `nacl.box.open`, but uses a shared key precomputed with `nacl.box.before`. + +#### Constants + +##### nacl.box.publicKeyLength = 32 + +Length of public key in bytes. + +##### nacl.box.secretKeyLength = 32 + +Length of secret key in bytes. + +##### nacl.box.sharedKeyLength = 32 + +Length of precomputed shared key in bytes. + +##### nacl.box.nonceLength = 24 + +Length of nonce in bytes. + +##### nacl.box.overheadLength = 16 + +Length of overhead added to box compared to original message. + + +### Secret-key authenticated encryption (secretbox) + +Implements *xsalsa20-poly1305*. + +#### nacl.secretbox(message, nonce, key) + +Encrypts and authenticates message using the key and the nonce. The nonce must +be unique for each distinct message for this key. + +Returns an encrypted and authenticated message, which is +`nacl.secretbox.overheadLength` longer than the original message. + +#### nacl.secretbox.open(box, nonce, key) + +Authenticates and decrypts the given secret box using the key and the nonce. + +Returns the original message, or `null` if authentication fails. + +#### Constants + +##### nacl.secretbox.keyLength = 32 + +Length of key in bytes. + +##### nacl.secretbox.nonceLength = 24 + +Length of nonce in bytes. + +##### nacl.secretbox.overheadLength = 16 + +Length of overhead added to secret box compared to original message. + + +### Scalar multiplication + +Implements *x25519*. + +#### nacl.scalarMult(n, p) + +Multiplies an integer `n` by a group element `p` and returns the resulting +group element. + +#### nacl.scalarMult.base(n) + +Multiplies an integer `n` by a standard group element and returns the resulting +group element. + +#### Constants + +##### nacl.scalarMult.scalarLength = 32 + +Length of scalar in bytes. + +##### nacl.scalarMult.groupElementLength = 32 + +Length of group element in bytes. + + +### Signatures + +Implements [ed25519](http://ed25519.cr.yp.to). + +#### nacl.sign.keyPair() + +Generates new random key pair for signing and returns it as an object with +`publicKey` and `secretKey` members: + + { + publicKey: ..., // Uint8Array with 32-byte public key + secretKey: ... // Uint8Array with 64-byte secret key + } + +#### nacl.sign.keyPair.fromSecretKey(secretKey) + +Returns a signing key pair with public key corresponding to the given +64-byte secret key. The secret key must have been generated by +`nacl.sign.keyPair` or `nacl.sign.keyPair.fromSeed`. + +#### nacl.sign.keyPair.fromSeed(seed) + +Returns a new signing key pair generated deterministically from a 32-byte seed. +The seed must contain enough entropy to be secure. This method is not +recommended for general use: instead, use `nacl.sign.keyPair` to generate a new +key pair from a random seed. + +#### nacl.sign(message, secretKey) + +Signs the message using the secret key and returns a signed message. + +#### nacl.sign.open(signedMessage, publicKey) + +Verifies the signed message and returns the message without signature. + +Returns `null` if verification failed. + +#### nacl.sign.detached(message, secretKey) + +Signs the message using the secret key and returns a signature. + +#### nacl.sign.detached.verify(message, signature, publicKey) + +Verifies the signature for the message and returns `true` if verification +succeeded or `false` if it failed. + +#### Constants + +##### nacl.sign.publicKeyLength = 32 + +Length of signing public key in bytes. + +##### nacl.sign.secretKeyLength = 64 + +Length of signing secret key in bytes. + +##### nacl.sign.seedLength = 32 + +Length of seed for `nacl.sign.keyPair.fromSeed` in bytes. + +##### nacl.sign.signatureLength = 64 + +Length of signature in bytes. + + +### Hashing + +Implements *SHA-512*. + +#### nacl.hash(message) + +Returns SHA-512 hash of the message. + +#### Constants + +##### nacl.hash.hashLength = 64 + +Length of hash in bytes. + + +### Random bytes generation + +#### nacl.randomBytes(length) + +Returns a `Uint8Array` of the given length containing random bytes of +cryptographic quality. + +**Implementation note** + +TweetNaCl.js uses the following methods to generate random bytes, +depending on the platform it runs on: + +* `window.crypto.getRandomValues` (WebCrypto standard) +* `window.msCrypto.getRandomValues` (Internet Explorer 11) +* `crypto.randomBytes` (Node.js) + +If the platform doesn't provide a suitable PRNG, the following functions, +which require random numbers, will throw exception: + +* `nacl.randomBytes` +* `nacl.box.keyPair` +* `nacl.sign.keyPair` + +Other functions are deterministic and will continue working. + +If a platform you are targeting doesn't implement secure random number +generator, but you somehow have a cryptographically-strong source of entropy +(not `Math.random`!), and you know what you are doing, you can plug it into +TweetNaCl.js like this: + + nacl.setPRNG(function(x, n) { + // ... copy n random bytes into x ... + }); + +Note that `nacl.setPRNG` *completely replaces* internal random byte generator +with the one provided. + + +### Constant-time comparison + +#### nacl.verify(x, y) + +Compares `x` and `y` in constant time and returns `true` if their lengths are +non-zero and equal, and their contents are equal. + +Returns `false` if either of the arguments has zero length, or arguments have +different lengths, or their contents differ. + + +System requirements +------------------- + +TweetNaCl.js supports modern browsers that have a cryptographically secure +pseudorandom number generator and typed arrays, including the latest versions +of: + +* Chrome +* Firefox +* Safari (Mac, iOS) +* Internet Explorer 11 + +Other systems: + +* Node.js + + +Development and testing +------------------------ + +Install NPM modules needed for development: + + $ npm install + +To build minified versions: + + $ npm run build + +Tests use minified version, so make sure to rebuild it every time you change +`nacl.js` or `nacl-fast.js`. + +### Testing + +To run tests in Node.js: + + $ npm run test-node + +By default all tests described here work on `nacl.min.js`. To test other +versions, set environment variable `NACL_SRC` to the file name you want to test. +For example, the following command will test fast minified version: + + $ NACL_SRC=nacl-fast.min.js npm run test-node + +To run full suite of tests in Node.js, including comparing outputs of +JavaScript port to outputs of the original C version: + + $ npm run test-node-all + +To prepare tests for browsers: + + $ npm run build-test-browser + +and then open `test/browser/test.html` (or `test/browser/test-fast.html`) to +run them. + +To run tests in both Node and Electron: + + $ npm test + +### Benchmarking + +To run benchmarks in Node.js: + + $ npm run bench + $ NACL_SRC=nacl-fast.min.js npm run bench + +To run benchmarks in a browser, open `test/benchmark/bench.html` (or +`test/benchmark/bench-fast.html`). + + +Benchmarks +---------- + +For reference, here are benchmarks from MacBook Pro (Retina, 13-inch, Mid 2014) +laptop with 2.6 GHz Intel Core i5 CPU (Intel) in Chrome 53/OS X and Xiaomi Redmi +Note 3 smartphone with 1.8 GHz Qualcomm Snapdragon 650 64-bit CPU (ARM) in +Chrome 52/Android: + +| | nacl.js Intel | nacl-fast.js Intel | nacl.js ARM | nacl-fast.js ARM | +| ------------- |:-------------:|:-------------------:|:-------------:|:-----------------:| +| salsa20 | 1.3 MB/s | 128 MB/s | 0.4 MB/s | 43 MB/s | +| poly1305 | 13 MB/s | 171 MB/s | 4 MB/s | 52 MB/s | +| hash | 4 MB/s | 34 MB/s | 0.9 MB/s | 12 MB/s | +| secretbox 1K | 1113 op/s | 57583 op/s | 334 op/s | 14227 op/s | +| box 1K | 145 op/s | 718 op/s | 37 op/s | 368 op/s | +| scalarMult | 171 op/s | 733 op/s | 56 op/s | 380 op/s | +| sign | 77 op/s | 200 op/s | 20 op/s | 61 op/s | +| sign.open | 39 op/s | 102 op/s | 11 op/s | 31 op/s | + +(You can run benchmarks on your devices by clicking on the links at the bottom +of the [home page](https://tweetnacl.js.org)). + +In short, with *nacl-fast.js* and 1024-byte messages you can expect to encrypt and +authenticate more than 57000 messages per second on a typical laptop or more than +14000 messages per second on a $170 smartphone, sign about 200 and verify 100 +messages per second on a laptop or 60 and 30 messages per second on a smartphone, +per CPU core (with Web Workers you can do these operations in parallel), +which is good enough for most applications. + + +Contributors +------------ + +See AUTHORS.md file. + + +Third-party libraries based on TweetNaCl.js +------------------------------------------- + +* [forward-secrecy](https://github.com/alax/forward-secrecy) — Axolotl ratchet implementation +* [nacl-stream](https://github.com/dchest/nacl-stream-js) - streaming encryption +* [tweetnacl-auth-js](https://github.com/dchest/tweetnacl-auth-js) — implementation of [`crypto_auth`](http://nacl.cr.yp.to/auth.html) +* [tweetnacl-sealed-box](https://github.com/whs/tweetnacl-sealed-box) — implementation of [`sealed boxes`](https://download.libsodium.org/doc/public-key_cryptography/sealed_boxes.html) +* [chloride](https://github.com/dominictarr/chloride) - unified API for various NaCl modules + + +Who uses it +----------- + +Some notable users of TweetNaCl.js: + +* [GitHub](https://github.com) +* [MEGA](https://github.com/meganz/webclient) +* [Stellar](https://www.stellar.org/) +* [miniLock](https://github.com/kaepora/miniLock) diff --git a/node_modules/tweetnacl/nacl-fast.js b/node_modules/tweetnacl/nacl-fast.js new file mode 100644 index 000000000..7ea5fb588 --- /dev/null +++ b/node_modules/tweetnacl/nacl-fast.js @@ -0,0 +1,2391 @@ +(function(nacl) { +'use strict'; + +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ + +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; + +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; + +var _0 = new Uint8Array(16); +var _9 = new Uint8Array(32); _9[0] = 9; + +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + +function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; +} + +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; +} + +function crypto_verify_16(x, xi, y, yi) { + return vn(x,xi,y,yi,16); +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); +} + +function core_salsa20(o, p, k, c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; + + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + + o[ 4] = x1 >>> 0 & 0xff; + o[ 5] = x1 >>> 8 & 0xff; + o[ 6] = x1 >>> 16 & 0xff; + o[ 7] = x1 >>> 24 & 0xff; + + o[ 8] = x2 >>> 0 & 0xff; + o[ 9] = x2 >>> 8 & 0xff; + o[10] = x2 >>> 16 & 0xff; + o[11] = x2 >>> 24 & 0xff; + + o[12] = x3 >>> 0 & 0xff; + o[13] = x3 >>> 8 & 0xff; + o[14] = x3 >>> 16 & 0xff; + o[15] = x3 >>> 24 & 0xff; + + o[16] = x4 >>> 0 & 0xff; + o[17] = x4 >>> 8 & 0xff; + o[18] = x4 >>> 16 & 0xff; + o[19] = x4 >>> 24 & 0xff; + + o[20] = x5 >>> 0 & 0xff; + o[21] = x5 >>> 8 & 0xff; + o[22] = x5 >>> 16 & 0xff; + o[23] = x5 >>> 24 & 0xff; + + o[24] = x6 >>> 0 & 0xff; + o[25] = x6 >>> 8 & 0xff; + o[26] = x6 >>> 16 & 0xff; + o[27] = x6 >>> 24 & 0xff; + + o[28] = x7 >>> 0 & 0xff; + o[29] = x7 >>> 8 & 0xff; + o[30] = x7 >>> 16 & 0xff; + o[31] = x7 >>> 24 & 0xff; + + o[32] = x8 >>> 0 & 0xff; + o[33] = x8 >>> 8 & 0xff; + o[34] = x8 >>> 16 & 0xff; + o[35] = x8 >>> 24 & 0xff; + + o[36] = x9 >>> 0 & 0xff; + o[37] = x9 >>> 8 & 0xff; + o[38] = x9 >>> 16 & 0xff; + o[39] = x9 >>> 24 & 0xff; + + o[40] = x10 >>> 0 & 0xff; + o[41] = x10 >>> 8 & 0xff; + o[42] = x10 >>> 16 & 0xff; + o[43] = x10 >>> 24 & 0xff; + + o[44] = x11 >>> 0 & 0xff; + o[45] = x11 >>> 8 & 0xff; + o[46] = x11 >>> 16 & 0xff; + o[47] = x11 >>> 24 & 0xff; + + o[48] = x12 >>> 0 & 0xff; + o[49] = x12 >>> 8 & 0xff; + o[50] = x12 >>> 16 & 0xff; + o[51] = x12 >>> 24 & 0xff; + + o[52] = x13 >>> 0 & 0xff; + o[53] = x13 >>> 8 & 0xff; + o[54] = x13 >>> 16 & 0xff; + o[55] = x13 >>> 24 & 0xff; + + o[56] = x14 >>> 0 & 0xff; + o[57] = x14 >>> 8 & 0xff; + o[58] = x14 >>> 16 & 0xff; + o[59] = x14 >>> 24 & 0xff; + + o[60] = x15 >>> 0 & 0xff; + o[61] = x15 >>> 8 & 0xff; + o[62] = x15 >>> 16 & 0xff; + o[63] = x15 >>> 24 & 0xff; +} + +function core_hsalsa20(o,p,k,c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + + o[ 4] = x5 >>> 0 & 0xff; + o[ 5] = x5 >>> 8 & 0xff; + o[ 6] = x5 >>> 16 & 0xff; + o[ 7] = x5 >>> 24 & 0xff; + + o[ 8] = x10 >>> 0 & 0xff; + o[ 9] = x10 >>> 8 & 0xff; + o[10] = x10 >>> 16 & 0xff; + o[11] = x10 >>> 24 & 0xff; + + o[12] = x15 >>> 0 & 0xff; + o[13] = x15 >>> 8 & 0xff; + o[14] = x15 >>> 16 & 0xff; + o[15] = x15 >>> 24 & 0xff; + + o[16] = x6 >>> 0 & 0xff; + o[17] = x6 >>> 8 & 0xff; + o[18] = x6 >>> 16 & 0xff; + o[19] = x6 >>> 24 & 0xff; + + o[20] = x7 >>> 0 & 0xff; + o[21] = x7 >>> 8 & 0xff; + o[22] = x7 >>> 16 & 0xff; + o[23] = x7 >>> 24 & 0xff; + + o[24] = x8 >>> 0 & 0xff; + o[25] = x8 >>> 8 & 0xff; + o[26] = x8 >>> 16 & 0xff; + o[27] = x8 >>> 24 & 0xff; + + o[28] = x9 >>> 0 & 0xff; + o[29] = x9 >>> 8 & 0xff; + o[30] = x9 >>> 16 & 0xff; + o[31] = x9 >>> 24 & 0xff; +} + +function crypto_core_salsa20(out,inp,k,c) { + core_salsa20(out,inp,k,c); +} + +function crypto_core_hsalsa20(out,inp,k,c) { + core_hsalsa20(out,inp,k,c); +} + +var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); + // "expand 32-byte k" + +function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + mpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + } + return 0; +} + +function crypto_stream_salsa20(c,cpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = x[i]; + } + return 0; +} + +function crypto_stream(c,cpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20(c,cpos,d,sn,s); +} + +function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); +} + +/* +* Port of Andrew Moon's Poly1305-donna-16. Public domain. +* https://github.com/floodyberry/poly1305-donna +*/ + +var poly1305 = function(key) { + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.leftover = 0; + this.fin = 0; + + var t0, t1, t2, t3, t4, t5, t6, t7; + + t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; + t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = ((t4 >>> 1)) & 0x1ffe; + t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = ((t7 >>> 5)) & 0x007f; + + this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; + this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; + this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; + this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; + this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; + this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; + this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; + this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; +}; + +poly1305.prototype.blocks = function(m, mpos, bytes) { + var hibit = this.fin ? 0 : (1 << 11); + var t0, t1, t2, t3, t4, t5, t6, t7, c; + var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; + + var h0 = this.h[0], + h1 = this.h[1], + h2 = this.h[2], + h3 = this.h[3], + h4 = this.h[4], + h5 = this.h[5], + h6 = this.h[6], + h7 = this.h[7], + h8 = this.h[8], + h9 = this.h[9]; + + var r0 = this.r[0], + r1 = this.r[1], + r2 = this.r[2], + r3 = this.r[3], + r4 = this.r[4], + r5 = this.r[5], + r6 = this.r[6], + r7 = this.r[7], + r8 = this.r[8], + r9 = this.r[9]; + + while (bytes >= 16) { + t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; + t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; + t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; + h5 += ((t4 >>> 1)) & 0x1fff; + t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; + t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + h9 += ((t7 >>> 5)) | hibit; + + c = 0; + + d0 = c; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h2 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c = (d0 >>> 13); d0 &= 0x1fff; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c += (d0 >>> 13); d0 &= 0x1fff; + + d1 = c; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h2 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c = (d1 >>> 13); d1 &= 0x1fff; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c += (d1 >>> 13); d1 &= 0x1fff; + + d2 = c; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h2 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c = (d2 >>> 13); d2 &= 0x1fff; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c += (d2 >>> 13); d2 &= 0x1fff; + + d3 = c; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h2 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c = (d3 >>> 13); d3 &= 0x1fff; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c += (d3 >>> 13); d3 &= 0x1fff; + + d4 = c; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h2 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c = (d4 >>> 13); d4 &= 0x1fff; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c += (d4 >>> 13); d4 &= 0x1fff; + + d5 = c; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h2 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c = (d5 >>> 13); d5 &= 0x1fff; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c += (d5 >>> 13); d5 &= 0x1fff; + + d6 = c; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h2 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c = (d6 >>> 13); d6 &= 0x1fff; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c += (d6 >>> 13); d6 &= 0x1fff; + + d7 = c; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h2 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c = (d7 >>> 13); d7 &= 0x1fff; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c += (d7 >>> 13); d7 &= 0x1fff; + + d8 = c; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h2 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c = (d8 >>> 13); d8 &= 0x1fff; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c += (d8 >>> 13); d8 &= 0x1fff; + + d9 = c; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h2 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c = (d9 >>> 13); d9 &= 0x1fff; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c += (d9 >>> 13); d9 &= 0x1fff; + + c = (((c << 2) + c)) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = (c >>> 13); + d1 += c; + + h0 = d0; + h1 = d1; + h2 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; + + mpos += 16; + bytes -= 16; + } + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h2; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; +}; + +poly1305.prototype.finish = function(mac, macpos) { + var g = new Uint16Array(10); + var c, mask, f, i; + + if (this.leftover) { + i = this.leftover; + this.buffer[i++] = 1; + for (; i < 16; i++) this.buffer[i] = 0; + this.fin = 1; + this.blocks(this.buffer, 0, 16); + } + + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + for (i = 2; i < 10; i++) { + this.h[i] += c; + c = this.h[i] >>> 13; + this.h[i] &= 0x1fff; + } + this.h[0] += (c * 5); + c = this.h[0] >>> 13; + this.h[0] &= 0x1fff; + this.h[1] += c; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + this.h[2] += c; + + g[0] = this.h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (i = 1; i < 10; i++) { + g[i] = this.h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= (1 << 13); + + mask = (c ^ 1) - 1; + for (i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; + + this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; + this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; + this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; + this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; + this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; + this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; + this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; + this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; + + f = this.h[0] + this.pad[0]; + this.h[0] = f & 0xffff; + for (i = 1; i < 8; i++) { + f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; + this.h[i] = f & 0xffff; + } + + mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; + mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; + mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; + mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; + mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; + mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; + mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; + mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; + mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; + mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; + mac[macpos+10] = (this.h[5] >>> 0) & 0xff; + mac[macpos+11] = (this.h[5] >>> 8) & 0xff; + mac[macpos+12] = (this.h[6] >>> 0) & 0xff; + mac[macpos+13] = (this.h[6] >>> 8) & 0xff; + mac[macpos+14] = (this.h[7] >>> 0) & 0xff; + mac[macpos+15] = (this.h[7] >>> 8) & 0xff; +}; + +poly1305.prototype.update = function(m, mpos, bytes) { + var i, want; + + if (this.leftover) { + want = (16 - this.leftover); + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) + return; + this.blocks(this.buffer, 0, 16); + this.leftover = 0; + } + + if (bytes >= 16) { + want = bytes - (bytes % 16); + this.blocks(m, mpos, want); + mpos += want; + bytes -= want; + } + + if (bytes) { + for (i = 0; i < bytes; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + this.leftover += bytes; + } +}; + +function crypto_onetimeauth(out, outpos, m, mpos, n, k) { + var s = new poly1305(k); + s.update(m, mpos, n); + s.finish(out, outpos); + return 0; +} + +function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { + var x = new Uint8Array(16); + crypto_onetimeauth(x,0,m,mpos,n,k); + return crypto_verify_16(h,hpos,x,0); +} + +function crypto_secretbox(c,m,d,n,k) { + var i; + if (d < 32) return -1; + crypto_stream_xor(c,0,m,0,d,n,k); + crypto_onetimeauth(c, 16, c, 32, d - 32, c); + for (i = 0; i < 16; i++) c[i] = 0; + return 0; +} + +function crypto_secretbox_open(m,c,d,n,k) { + var i; + var x = new Uint8Array(32); + if (d < 32) return -1; + crypto_stream(x,0,32,n,k); + if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; + crypto_stream_xor(m,0,c,0,d,n,k); + for (i = 0; i < 32; i++) m[i] = 0; + return 0; +} + +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} + +function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c-1 + 37 * (c-1); +} + +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; + } +} + +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} + +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; +} + +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} + +function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +} + +function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +} + +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is + + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} + +function S(o, a) { + M(o, a, a); +} + +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; + } + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); + } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; + } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; +} + +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); +} + +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); +} + +function crypto_box_beforenm(k, y, x) { + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y); + return crypto_core_hsalsa20(k, _0, s, sigma); +} + +var crypto_box_afternm = crypto_secretbox; +var crypto_box_open_afternm = crypto_secretbox_open; + +function crypto_box(c, m, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_afternm(c, m, d, n, k); +} + +function crypto_box_open(m, c, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_open_afternm(m, c, d, n, k); +} + +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 +]; + +function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; + + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; + } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; + + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; + + // add + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // K + h = K[i*2]; + l = K[i*2+1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // w + h = wh[i%16]; + l = wl[i%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; + + // add + h = th; + l = tl; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); + + // add + h = bh3; + l = bl3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = th; + l = tl; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); + + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); + } + } + } + + // add + h = ah0; + l = al0; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[0]; + l = hl[0]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); + + h = ah1; + l = al1; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[1]; + l = hl[1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); + + h = ah2; + l = al2; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[2]; + l = hl[2]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); + + h = ah3; + l = al3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[3]; + l = hl[3]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); + + h = ah4; + l = al4; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[4]; + l = hl[4]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); + + h = ah5; + l = al5; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[5]; + l = hl[5]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); + + h = ah6; + l = al6; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[6]; + l = hl[6]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); + + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[7]; + l = hl[7]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); + + pos += 128; + n -= 128; + } + + return n; +} + +function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; + + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; + + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; + + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; + + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; + + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); + + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); + + return 0; +} + +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } +} + +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} + +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } +} + +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} + +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; + + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + scalarbase(p, d); + pack(pk, p); + + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} + +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); + +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = Math.floor((x[j] + 128) / 256); + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} + +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} + +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; + + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); + + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; + } + } + + modL(sm.subarray(32), x); + return smlen; +} + +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + return 0; +} + +function crypto_sign_open(m, sm, n, pk) { + var i; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; + + if (n < 64) return -1; + + if (unpackneg(q, pk)) return -1; + + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); + + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; + } + + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + return n; +} + +var crypto_secretbox_KEYBYTES = 32, + crypto_secretbox_NONCEBYTES = 24, + crypto_secretbox_ZEROBYTES = 32, + crypto_secretbox_BOXZEROBYTES = 16, + crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_box_BEFORENMBYTES = 32, + crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, + crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, + crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32, + crypto_hash_BYTES = 64; + +nacl.lowlevel = { + crypto_core_hsalsa20: crypto_core_hsalsa20, + crypto_stream_xor: crypto_stream_xor, + crypto_stream: crypto_stream, + crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, + crypto_stream_salsa20: crypto_stream_salsa20, + crypto_onetimeauth: crypto_onetimeauth, + crypto_onetimeauth_verify: crypto_onetimeauth_verify, + crypto_verify_16: crypto_verify_16, + crypto_verify_32: crypto_verify_32, + crypto_secretbox: crypto_secretbox, + crypto_secretbox_open: crypto_secretbox_open, + crypto_scalarmult: crypto_scalarmult, + crypto_scalarmult_base: crypto_scalarmult_base, + crypto_box_beforenm: crypto_box_beforenm, + crypto_box_afternm: crypto_box_afternm, + crypto_box: crypto_box, + crypto_box_open: crypto_box_open, + crypto_box_keypair: crypto_box_keypair, + crypto_hash: crypto_hash, + crypto_sign: crypto_sign, + crypto_sign_keypair: crypto_sign_keypair, + crypto_sign_open: crypto_sign_open, + + crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, + crypto_sign_BYTES: crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, + crypto_hash_BYTES: crypto_hash_BYTES, + + gf: gf, + D: D, + L: L, + pack25519: pack25519, + unpack25519: unpack25519, + M: M, + A: A, + S: S, + Z: Z, + pow2523: pow2523, + add: add, + set25519: set25519, + modL: modL, + scalarmult: scalarmult, + scalarbase: scalarbase, +}; + +/* High-level API */ + +function checkLengths(k, n) { + if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); +} + +function checkBoxLengths(pk, sk) { + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); +} + +function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError('unexpected type, use Uint8Array'); + } +} + +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} + +nacl.randomBytes = function(n) { + var b = new Uint8Array(n); + randombytes(b, n); + return b; +}; + +nacl.secretbox = function(msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c = new Uint8Array(m.length); + for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; + crypto_secretbox(c, m, m.length, nonce, key); + return c.subarray(crypto_secretbox_BOXZEROBYTES); +}; + +nacl.secretbox.open = function(box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m = new Uint8Array(c.length); + for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; + if (c.length < 32) return null; + if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null; + return m.subarray(crypto_secretbox_ZEROBYTES); +}; + +nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; +nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; +nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; + +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; + +nacl.scalarMult.base = function(n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; +}; + +nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; +nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; + +nacl.box = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k); +}; + +nacl.box.before = function(publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k, publicKey, secretKey); + return k; +}; + +nacl.box.after = nacl.secretbox; + +nacl.box.open = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k); +}; + +nacl.box.open.after = nacl.secretbox.open; + +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; +nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; +nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; +nacl.box.nonceLength = crypto_box_NONCEBYTES; +nacl.box.overheadLength = nacl.secretbox.overheadLength; + +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; + +nacl.sign.open = function(signedMsg, publicKey) { + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m = new Uint8Array(mlen); + for (var i = 0; i < m.length; i++) m[i] = tmp[i]; + return m; +}; + +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; + +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; + +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; +nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; +nacl.sign.seedLength = crypto_sign_SEEDBYTES; +nacl.sign.signatureLength = crypto_sign_BYTES; + +nacl.hash = function(msg) { + checkArrayTypes(msg); + var h = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h, msg, msg.length); + return h; +}; + +nacl.hash.hashLength = crypto_hash_BYTES; + +nacl.verify = function(x, y) { + checkArrayTypes(x, y); + // Zero length arguments are considered not equal. + if (x.length === 0 || y.length === 0) return false; + if (x.length !== y.length) return false; + return (vn(x, 0, y, 0, x.length) === 0) ? true : false; +}; + +nacl.setPRNG = function(fn) { + randombytes = fn; +}; + +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; + if (crypto && crypto.getRandomValues) { + // Browsers. + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } else if (typeof require !== 'undefined') { + // Node.js. + crypto = require('crypto'); + if (crypto && crypto.randomBytes) { + nacl.setPRNG(function(x, n) { + var i, v = crypto.randomBytes(n); + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } + } +})(); + +})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {})); diff --git a/node_modules/tweetnacl/nacl-fast.min.js b/node_modules/tweetnacl/nacl-fast.min.js new file mode 100644 index 000000000..348ec2e23 --- /dev/null +++ b/node_modules/tweetnacl/nacl-fast.min.js @@ -0,0 +1 @@ +!function(i){"use strict";var v=function(r){var t,n=new Float64Array(16);if(r)for(t=0;t>24&255,r[t+1]=n>>16&255,r[t+2]=n>>8&255,r[t+3]=255&n,r[t+4]=e>>24&255,r[t+5]=e>>16&255,r[t+6]=e>>8&255,r[t+7]=255&e}function w(r,t,n,e,o){var i,h=0;for(i=0;i>>8)-1}function b(r,t,n,e){return w(r,t,n,e,16)}function g(r,t,n,e){return w(r,t,n,e,32)}function A(r,t,n,e){!function(r,t,n,e){for(var o,i=255&e[0]|(255&e[1])<<8|(255&e[2])<<16|(255&e[3])<<24,h=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,s=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,u=255&e[4]|(255&e[5])<<8|(255&e[6])<<16|(255&e[7])<<24,c=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,y=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,l=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,w=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,v=255&e[8]|(255&e[9])<<8|(255&e[10])<<16|(255&e[11])<<24,p=255&n[16]|(255&n[17])<<8|(255&n[18])<<16|(255&n[19])<<24,b=255&n[20]|(255&n[21])<<8|(255&n[22])<<16|(255&n[23])<<24,g=255&n[24]|(255&n[25])<<8|(255&n[26])<<16|(255&n[27])<<24,A=255&n[28]|(255&n[29])<<8|(255&n[30])<<16|(255&n[31])<<24,_=255&e[12]|(255&e[13])<<8|(255&e[14])<<16|(255&e[15])<<24,U=i,d=h,E=a,x=f,M=s,m=u,B=c,S=y,k=l,K=w,Y=v,L=p,T=b,z=g,R=A,P=_,N=0;N<20;N+=2)U^=(o=(T^=(o=(k^=(o=(M^=(o=U+T|0)<<7|o>>>25)+U|0)<<9|o>>>23)+M|0)<<13|o>>>19)+k|0)<<18|o>>>14,m^=(o=(d^=(o=(z^=(o=(K^=(o=m+d|0)<<7|o>>>25)+m|0)<<9|o>>>23)+K|0)<<13|o>>>19)+z|0)<<18|o>>>14,Y^=(o=(B^=(o=(E^=(o=(R^=(o=Y+B|0)<<7|o>>>25)+Y|0)<<9|o>>>23)+R|0)<<13|o>>>19)+E|0)<<18|o>>>14,P^=(o=(L^=(o=(S^=(o=(x^=(o=P+L|0)<<7|o>>>25)+P|0)<<9|o>>>23)+x|0)<<13|o>>>19)+S|0)<<18|o>>>14,U^=(o=(x^=(o=(E^=(o=(d^=(o=U+x|0)<<7|o>>>25)+U|0)<<9|o>>>23)+d|0)<<13|o>>>19)+E|0)<<18|o>>>14,m^=(o=(M^=(o=(S^=(o=(B^=(o=m+M|0)<<7|o>>>25)+m|0)<<9|o>>>23)+B|0)<<13|o>>>19)+S|0)<<18|o>>>14,Y^=(o=(K^=(o=(k^=(o=(L^=(o=Y+K|0)<<7|o>>>25)+Y|0)<<9|o>>>23)+L|0)<<13|o>>>19)+k|0)<<18|o>>>14,P^=(o=(R^=(o=(z^=(o=(T^=(o=P+R|0)<<7|o>>>25)+P|0)<<9|o>>>23)+T|0)<<13|o>>>19)+z|0)<<18|o>>>14;U=U+i|0,d=d+h|0,E=E+a|0,x=x+f|0,M=M+s|0,m=m+u|0,B=B+c|0,S=S+y|0,k=k+l|0,K=K+w|0,Y=Y+v|0,L=L+p|0,T=T+b|0,z=z+g|0,R=R+A|0,P=P+_|0,r[0]=U>>>0&255,r[1]=U>>>8&255,r[2]=U>>>16&255,r[3]=U>>>24&255,r[4]=d>>>0&255,r[5]=d>>>8&255,r[6]=d>>>16&255,r[7]=d>>>24&255,r[8]=E>>>0&255,r[9]=E>>>8&255,r[10]=E>>>16&255,r[11]=E>>>24&255,r[12]=x>>>0&255,r[13]=x>>>8&255,r[14]=x>>>16&255,r[15]=x>>>24&255,r[16]=M>>>0&255,r[17]=M>>>8&255,r[18]=M>>>16&255,r[19]=M>>>24&255,r[20]=m>>>0&255,r[21]=m>>>8&255,r[22]=m>>>16&255,r[23]=m>>>24&255,r[24]=B>>>0&255,r[25]=B>>>8&255,r[26]=B>>>16&255,r[27]=B>>>24&255,r[28]=S>>>0&255,r[29]=S>>>8&255,r[30]=S>>>16&255,r[31]=S>>>24&255,r[32]=k>>>0&255,r[33]=k>>>8&255,r[34]=k>>>16&255,r[35]=k>>>24&255,r[36]=K>>>0&255,r[37]=K>>>8&255,r[38]=K>>>16&255,r[39]=K>>>24&255,r[40]=Y>>>0&255,r[41]=Y>>>8&255,r[42]=Y>>>16&255,r[43]=Y>>>24&255,r[44]=L>>>0&255,r[45]=L>>>8&255,r[46]=L>>>16&255,r[47]=L>>>24&255,r[48]=T>>>0&255,r[49]=T>>>8&255,r[50]=T>>>16&255,r[51]=T>>>24&255,r[52]=z>>>0&255,r[53]=z>>>8&255,r[54]=z>>>16&255,r[55]=z>>>24&255,r[56]=R>>>0&255,r[57]=R>>>8&255,r[58]=R>>>16&255,r[59]=R>>>24&255,r[60]=P>>>0&255,r[61]=P>>>8&255,r[62]=P>>>16&255,r[63]=P>>>24&255}(r,t,n,e)}function _(r,t,n,e){!function(r,t,n,e){for(var o,i=255&e[0]|(255&e[1])<<8|(255&e[2])<<16|(255&e[3])<<24,h=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,s=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,u=255&e[4]|(255&e[5])<<8|(255&e[6])<<16|(255&e[7])<<24,c=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,y=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,l=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,w=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,v=255&e[8]|(255&e[9])<<8|(255&e[10])<<16|(255&e[11])<<24,p=255&n[16]|(255&n[17])<<8|(255&n[18])<<16|(255&n[19])<<24,b=255&n[20]|(255&n[21])<<8|(255&n[22])<<16|(255&n[23])<<24,g=255&n[24]|(255&n[25])<<8|(255&n[26])<<16|(255&n[27])<<24,A=255&n[28]|(255&n[29])<<8|(255&n[30])<<16|(255&n[31])<<24,_=255&e[12]|(255&e[13])<<8|(255&e[14])<<16|(255&e[15])<<24,U=0;U<20;U+=2)i^=(o=(b^=(o=(l^=(o=(s^=(o=i+b|0)<<7|o>>>25)+i|0)<<9|o>>>23)+s|0)<<13|o>>>19)+l|0)<<18|o>>>14,u^=(o=(h^=(o=(g^=(o=(w^=(o=u+h|0)<<7|o>>>25)+u|0)<<9|o>>>23)+w|0)<<13|o>>>19)+g|0)<<18|o>>>14,v^=(o=(c^=(o=(a^=(o=(A^=(o=v+c|0)<<7|o>>>25)+v|0)<<9|o>>>23)+A|0)<<13|o>>>19)+a|0)<<18|o>>>14,_^=(o=(p^=(o=(y^=(o=(f^=(o=_+p|0)<<7|o>>>25)+_|0)<<9|o>>>23)+f|0)<<13|o>>>19)+y|0)<<18|o>>>14,i^=(o=(f^=(o=(a^=(o=(h^=(o=i+f|0)<<7|o>>>25)+i|0)<<9|o>>>23)+h|0)<<13|o>>>19)+a|0)<<18|o>>>14,u^=(o=(s^=(o=(y^=(o=(c^=(o=u+s|0)<<7|o>>>25)+u|0)<<9|o>>>23)+c|0)<<13|o>>>19)+y|0)<<18|o>>>14,v^=(o=(w^=(o=(l^=(o=(p^=(o=v+w|0)<<7|o>>>25)+v|0)<<9|o>>>23)+p|0)<<13|o>>>19)+l|0)<<18|o>>>14,_^=(o=(A^=(o=(g^=(o=(b^=(o=_+A|0)<<7|o>>>25)+_|0)<<9|o>>>23)+b|0)<<13|o>>>19)+g|0)<<18|o>>>14;r[0]=i>>>0&255,r[1]=i>>>8&255,r[2]=i>>>16&255,r[3]=i>>>24&255,r[4]=u>>>0&255,r[5]=u>>>8&255,r[6]=u>>>16&255,r[7]=u>>>24&255,r[8]=v>>>0&255,r[9]=v>>>8&255,r[10]=v>>>16&255,r[11]=v>>>24&255,r[12]=_>>>0&255,r[13]=_>>>8&255,r[14]=_>>>16&255,r[15]=_>>>24&255,r[16]=c>>>0&255,r[17]=c>>>8&255,r[18]=c>>>16&255,r[19]=c>>>24&255,r[20]=y>>>0&255,r[21]=y>>>8&255,r[22]=y>>>16&255,r[23]=y>>>24&255,r[24]=l>>>0&255,r[25]=l>>>8&255,r[26]=l>>>16&255,r[27]=l>>>24&255,r[28]=w>>>0&255,r[29]=w>>>8&255,r[30]=w>>>16&255,r[31]=w>>>24&255}(r,t,n,e)}var U=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function d(r,t,n,e,o,i,h){var a,f,s=new Uint8Array(16),u=new Uint8Array(64);for(f=0;f<16;f++)s[f]=0;for(f=0;f<8;f++)s[f]=i[f];for(;64<=o;){for(A(u,s,h,U),f=0;f<64;f++)r[t+f]=n[e+f]^u[f];for(a=1,f=8;f<16;f++)a=a+(255&s[f])|0,s[f]=255&a,a>>>=8;o-=64,t+=64,e+=64}if(0>>=8;n-=64,t+=64}if(0>>13|n<<3),e=255&r[4]|(255&r[5])<<8,this.r[2]=7939&(n>>>10|e<<6),o=255&r[6]|(255&r[7])<<8,this.r[3]=8191&(e>>>7|o<<9),i=255&r[8]|(255&r[9])<<8,this.r[4]=255&(o>>>4|i<<12),this.r[5]=i>>>1&8190,h=255&r[10]|(255&r[11])<<8,this.r[6]=8191&(i>>>14|h<<2),a=255&r[12]|(255&r[13])<<8,this.r[7]=8065&(h>>>11|a<<5),f=255&r[14]|(255&r[15])<<8,this.r[8]=8191&(a>>>8|f<<8),this.r[9]=f>>>5&127,this.pad[0]=255&r[16]|(255&r[17])<<8,this.pad[1]=255&r[18]|(255&r[19])<<8,this.pad[2]=255&r[20]|(255&r[21])<<8,this.pad[3]=255&r[22]|(255&r[23])<<8,this.pad[4]=255&r[24]|(255&r[25])<<8,this.pad[5]=255&r[26]|(255&r[27])<<8,this.pad[6]=255&r[28]|(255&r[29])<<8,this.pad[7]=255&r[30]|(255&r[31])<<8};function B(r,t,n,e,o,i){var h=new m(i);return h.update(n,e,o),h.finish(r,t),0}function S(r,t,n,e,o,i){var h=new Uint8Array(16);return B(h,0,n,e,o,i),b(r,t,h,0)}function k(r,t,n,e,o){var i;if(n<32)return-1;for(M(r,0,t,0,n,e,o),B(r,16,r,32,n-32,r),i=0;i<16;i++)r[i]=0;return 0}function K(r,t,n,e,o){var i,h=new Uint8Array(32);if(n<32)return-1;if(x(h,0,32,e,o),0!==S(t,16,t,32,n-32,h))return-1;for(M(r,0,t,0,n,e,o),i=0;i<32;i++)r[i]=0;return 0}function Y(r,t){var n;for(n=0;n<16;n++)r[n]=0|t[n]}function L(r){var t,n,e=1;for(t=0;t<16;t++)n=r[t]+e+65535,e=Math.floor(n/65536),r[t]=n-65536*e;r[0]+=e-1+37*(e-1)}function T(r,t,n){for(var e,o=~(n-1),i=0;i<16;i++)e=o&(r[i]^t[i]),r[i]^=e,t[i]^=e}function z(r,t){var n,e,o,i=v(),h=v();for(n=0;n<16;n++)h[n]=t[n];for(L(h),L(h),L(h),e=0;e<2;e++){for(i[0]=h[0]-65517,n=1;n<15;n++)i[n]=h[n]-65535-(i[n-1]>>16&1),i[n-1]&=65535;i[15]=h[15]-32767-(i[14]>>16&1),o=i[15]>>16&1,i[14]&=65535,T(h,i,1-o)}for(n=0;n<16;n++)r[2*n]=255&h[n],r[2*n+1]=h[n]>>8}function R(r,t){var n=new Uint8Array(32),e=new Uint8Array(32);return z(n,r),z(e,t),g(n,0,e,0)}function P(r){var t=new Uint8Array(32);return z(t,r),1&t[0]}function N(r,t){var n;for(n=0;n<16;n++)r[n]=t[2*n]+(t[2*n+1]<<8);r[15]&=32767}function O(r,t,n){for(var e=0;e<16;e++)r[e]=t[e]+n[e]}function C(r,t,n){for(var e=0;e<16;e++)r[e]=t[e]-n[e]}function F(r,t,n){var e,o,i=0,h=0,a=0,f=0,s=0,u=0,c=0,y=0,l=0,w=0,v=0,p=0,b=0,g=0,A=0,_=0,U=0,d=0,E=0,x=0,M=0,m=0,B=0,S=0,k=0,K=0,Y=0,L=0,T=0,z=0,R=0,P=n[0],N=n[1],O=n[2],C=n[3],F=n[4],I=n[5],Z=n[6],G=n[7],q=n[8],D=n[9],V=n[10],X=n[11],j=n[12],H=n[13],J=n[14],Q=n[15];i+=(e=t[0])*P,h+=e*N,a+=e*O,f+=e*C,s+=e*F,u+=e*I,c+=e*Z,y+=e*G,l+=e*q,w+=e*D,v+=e*V,p+=e*X,b+=e*j,g+=e*H,A+=e*J,_+=e*Q,h+=(e=t[1])*P,a+=e*N,f+=e*O,s+=e*C,u+=e*F,c+=e*I,y+=e*Z,l+=e*G,w+=e*q,v+=e*D,p+=e*V,b+=e*X,g+=e*j,A+=e*H,_+=e*J,U+=e*Q,a+=(e=t[2])*P,f+=e*N,s+=e*O,u+=e*C,c+=e*F,y+=e*I,l+=e*Z,w+=e*G,v+=e*q,p+=e*D,b+=e*V,g+=e*X,A+=e*j,_+=e*H,U+=e*J,d+=e*Q,f+=(e=t[3])*P,s+=e*N,u+=e*O,c+=e*C,y+=e*F,l+=e*I,w+=e*Z,v+=e*G,p+=e*q,b+=e*D,g+=e*V,A+=e*X,_+=e*j,U+=e*H,d+=e*J,E+=e*Q,s+=(e=t[4])*P,u+=e*N,c+=e*O,y+=e*C,l+=e*F,w+=e*I,v+=e*Z,p+=e*G,b+=e*q,g+=e*D,A+=e*V,_+=e*X,U+=e*j,d+=e*H,E+=e*J,x+=e*Q,u+=(e=t[5])*P,c+=e*N,y+=e*O,l+=e*C,w+=e*F,v+=e*I,p+=e*Z,b+=e*G,g+=e*q,A+=e*D,_+=e*V,U+=e*X,d+=e*j,E+=e*H,x+=e*J,M+=e*Q,c+=(e=t[6])*P,y+=e*N,l+=e*O,w+=e*C,v+=e*F,p+=e*I,b+=e*Z,g+=e*G,A+=e*q,_+=e*D,U+=e*V,d+=e*X,E+=e*j,x+=e*H,M+=e*J,m+=e*Q,y+=(e=t[7])*P,l+=e*N,w+=e*O,v+=e*C,p+=e*F,b+=e*I,g+=e*Z,A+=e*G,_+=e*q,U+=e*D,d+=e*V,E+=e*X,x+=e*j,M+=e*H,m+=e*J,B+=e*Q,l+=(e=t[8])*P,w+=e*N,v+=e*O,p+=e*C,b+=e*F,g+=e*I,A+=e*Z,_+=e*G,U+=e*q,d+=e*D,E+=e*V,x+=e*X,M+=e*j,m+=e*H,B+=e*J,S+=e*Q,w+=(e=t[9])*P,v+=e*N,p+=e*O,b+=e*C,g+=e*F,A+=e*I,_+=e*Z,U+=e*G,d+=e*q,E+=e*D,x+=e*V,M+=e*X,m+=e*j,B+=e*H,S+=e*J,k+=e*Q,v+=(e=t[10])*P,p+=e*N,b+=e*O,g+=e*C,A+=e*F,_+=e*I,U+=e*Z,d+=e*G,E+=e*q,x+=e*D,M+=e*V,m+=e*X,B+=e*j,S+=e*H,k+=e*J,K+=e*Q,p+=(e=t[11])*P,b+=e*N,g+=e*O,A+=e*C,_+=e*F,U+=e*I,d+=e*Z,E+=e*G,x+=e*q,M+=e*D,m+=e*V,B+=e*X,S+=e*j,k+=e*H,K+=e*J,Y+=e*Q,b+=(e=t[12])*P,g+=e*N,A+=e*O,_+=e*C,U+=e*F,d+=e*I,E+=e*Z,x+=e*G,M+=e*q,m+=e*D,B+=e*V,S+=e*X,k+=e*j,K+=e*H,Y+=e*J,L+=e*Q,g+=(e=t[13])*P,A+=e*N,_+=e*O,U+=e*C,d+=e*F,E+=e*I,x+=e*Z,M+=e*G,m+=e*q,B+=e*D,S+=e*V,k+=e*X,K+=e*j,Y+=e*H,L+=e*J,T+=e*Q,A+=(e=t[14])*P,_+=e*N,U+=e*O,d+=e*C,E+=e*F,x+=e*I,M+=e*Z,m+=e*G,B+=e*q,S+=e*D,k+=e*V,K+=e*X,Y+=e*j,L+=e*H,T+=e*J,z+=e*Q,_+=(e=t[15])*P,h+=38*(d+=e*O),a+=38*(E+=e*C),f+=38*(x+=e*F),s+=38*(M+=e*I),u+=38*(m+=e*Z),c+=38*(B+=e*G),y+=38*(S+=e*q),l+=38*(k+=e*D),w+=38*(K+=e*V),v+=38*(Y+=e*X),p+=38*(L+=e*j),b+=38*(T+=e*H),g+=38*(z+=e*J),A+=38*(R+=e*Q),i=(e=(i+=38*(U+=e*N))+(o=1)+65535)-65536*(o=Math.floor(e/65536)),h=(e=h+o+65535)-65536*(o=Math.floor(e/65536)),a=(e=a+o+65535)-65536*(o=Math.floor(e/65536)),f=(e=f+o+65535)-65536*(o=Math.floor(e/65536)),s=(e=s+o+65535)-65536*(o=Math.floor(e/65536)),u=(e=u+o+65535)-65536*(o=Math.floor(e/65536)),c=(e=c+o+65535)-65536*(o=Math.floor(e/65536)),y=(e=y+o+65535)-65536*(o=Math.floor(e/65536)),l=(e=l+o+65535)-65536*(o=Math.floor(e/65536)),w=(e=w+o+65535)-65536*(o=Math.floor(e/65536)),v=(e=v+o+65535)-65536*(o=Math.floor(e/65536)),p=(e=p+o+65535)-65536*(o=Math.floor(e/65536)),b=(e=b+o+65535)-65536*(o=Math.floor(e/65536)),g=(e=g+o+65535)-65536*(o=Math.floor(e/65536)),A=(e=A+o+65535)-65536*(o=Math.floor(e/65536)),_=(e=_+o+65535)-65536*(o=Math.floor(e/65536)),i=(e=(i+=o-1+37*(o-1))+(o=1)+65535)-65536*(o=Math.floor(e/65536)),h=(e=h+o+65535)-65536*(o=Math.floor(e/65536)),a=(e=a+o+65535)-65536*(o=Math.floor(e/65536)),f=(e=f+o+65535)-65536*(o=Math.floor(e/65536)),s=(e=s+o+65535)-65536*(o=Math.floor(e/65536)),u=(e=u+o+65535)-65536*(o=Math.floor(e/65536)),c=(e=c+o+65535)-65536*(o=Math.floor(e/65536)),y=(e=y+o+65535)-65536*(o=Math.floor(e/65536)),l=(e=l+o+65535)-65536*(o=Math.floor(e/65536)),w=(e=w+o+65535)-65536*(o=Math.floor(e/65536)),v=(e=v+o+65535)-65536*(o=Math.floor(e/65536)),p=(e=p+o+65535)-65536*(o=Math.floor(e/65536)),b=(e=b+o+65535)-65536*(o=Math.floor(e/65536)),g=(e=g+o+65535)-65536*(o=Math.floor(e/65536)),A=(e=A+o+65535)-65536*(o=Math.floor(e/65536)),_=(e=_+o+65535)-65536*(o=Math.floor(e/65536)),i+=o-1+37*(o-1),r[0]=i,r[1]=h,r[2]=a,r[3]=f,r[4]=s,r[5]=u,r[6]=c,r[7]=y,r[8]=l,r[9]=w,r[10]=v,r[11]=p,r[12]=b,r[13]=g,r[14]=A,r[15]=_}function I(r,t){F(r,t,t)}function Z(r,t){var n,e=v();for(n=0;n<16;n++)e[n]=t[n];for(n=253;0<=n;n--)I(e,e),2!==n&&4!==n&&F(e,e,t);for(n=0;n<16;n++)r[n]=e[n]}function G(r,t){var n,e=v();for(n=0;n<16;n++)e[n]=t[n];for(n=250;0<=n;n--)I(e,e),1!==n&&F(e,e,t);for(n=0;n<16;n++)r[n]=e[n]}function q(r,t,n){var e,o,i=new Uint8Array(32),h=new Float64Array(80),a=v(),f=v(),s=v(),u=v(),c=v(),y=v();for(o=0;o<31;o++)i[o]=t[o];for(i[31]=127&t[31]|64,i[0]&=248,N(h,n),o=0;o<16;o++)f[o]=h[o],u[o]=a[o]=s[o]=0;for(a[0]=u[0]=1,o=254;0<=o;--o)T(a,f,e=i[o>>>3]>>>(7&o)&1),T(s,u,e),O(c,a,s),C(a,a,s),O(s,f,u),C(f,f,u),I(u,c),I(y,a),F(a,s,a),F(s,f,c),O(c,a,s),C(a,a,s),I(f,a),C(s,u,y),F(a,s,p),O(a,a,u),F(s,s,a),F(a,u,y),F(u,f,h),I(f,c),T(a,f,e),T(s,u,e);for(o=0;o<16;o++)h[o+16]=a[o],h[o+32]=s[o],h[o+48]=f[o],h[o+64]=u[o];var l=h.subarray(32),w=h.subarray(16);return Z(l,l),F(w,w,l),z(r,w),0}function D(r,t){return q(r,t,n)}function V(r,t){return h(t,32),D(r,t)}function X(r,t,n){var e=new Uint8Array(32);return q(e,n,t),_(r,o,e,U)}m.prototype.blocks=function(r,t,n){for(var e,o,i,h,a,f,s,u,c,y,l,w,v,p,b,g,A,_,U,d=this.fin?0:2048,E=this.h[0],x=this.h[1],M=this.h[2],m=this.h[3],B=this.h[4],S=this.h[5],k=this.h[6],K=this.h[7],Y=this.h[8],L=this.h[9],T=this.r[0],z=this.r[1],R=this.r[2],P=this.r[3],N=this.r[4],O=this.r[5],C=this.r[6],F=this.r[7],I=this.r[8],Z=this.r[9];16<=n;)y=c=0,y+=(E+=8191&(e=255&r[t+0]|(255&r[t+1])<<8))*T,y+=(x+=8191&(e>>>13|(o=255&r[t+2]|(255&r[t+3])<<8)<<3))*(5*Z),y+=(M+=8191&(o>>>10|(i=255&r[t+4]|(255&r[t+5])<<8)<<6))*(5*I),y+=(m+=8191&(i>>>7|(h=255&r[t+6]|(255&r[t+7])<<8)<<9))*(5*F),c=(y+=(B+=8191&(h>>>4|(a=255&r[t+8]|(255&r[t+9])<<8)<<12))*(5*C))>>>13,y&=8191,y+=(S+=a>>>1&8191)*(5*O),y+=(k+=8191&(a>>>14|(f=255&r[t+10]|(255&r[t+11])<<8)<<2))*(5*N),y+=(K+=8191&(f>>>11|(s=255&r[t+12]|(255&r[t+13])<<8)<<5))*(5*P),y+=(Y+=8191&(s>>>8|(u=255&r[t+14]|(255&r[t+15])<<8)<<8))*(5*R),l=c+=(y+=(L+=u>>>5|d)*(5*z))>>>13,l+=E*z,l+=x*T,l+=M*(5*Z),l+=m*(5*I),c=(l+=B*(5*F))>>>13,l&=8191,l+=S*(5*C),l+=k*(5*O),l+=K*(5*N),l+=Y*(5*P),c+=(l+=L*(5*R))>>>13,l&=8191,w=c,w+=E*R,w+=x*z,w+=M*T,w+=m*(5*Z),c=(w+=B*(5*I))>>>13,w&=8191,w+=S*(5*F),w+=k*(5*C),w+=K*(5*O),w+=Y*(5*N),v=c+=(w+=L*(5*P))>>>13,v+=E*P,v+=x*R,v+=M*z,v+=m*T,c=(v+=B*(5*Z))>>>13,v&=8191,v+=S*(5*I),v+=k*(5*F),v+=K*(5*C),v+=Y*(5*O),p=c+=(v+=L*(5*N))>>>13,p+=E*N,p+=x*P,p+=M*R,p+=m*z,c=(p+=B*T)>>>13,p&=8191,p+=S*(5*Z),p+=k*(5*I),p+=K*(5*F),p+=Y*(5*C),b=c+=(p+=L*(5*O))>>>13,b+=E*O,b+=x*N,b+=M*P,b+=m*R,c=(b+=B*z)>>>13,b&=8191,b+=S*T,b+=k*(5*Z),b+=K*(5*I),b+=Y*(5*F),g=c+=(b+=L*(5*C))>>>13,g+=E*C,g+=x*O,g+=M*N,g+=m*P,c=(g+=B*R)>>>13,g&=8191,g+=S*z,g+=k*T,g+=K*(5*Z),g+=Y*(5*I),A=c+=(g+=L*(5*F))>>>13,A+=E*F,A+=x*C,A+=M*O,A+=m*N,c=(A+=B*P)>>>13,A&=8191,A+=S*R,A+=k*z,A+=K*T,A+=Y*(5*Z),_=c+=(A+=L*(5*I))>>>13,_+=E*I,_+=x*F,_+=M*C,_+=m*O,c=(_+=B*N)>>>13,_&=8191,_+=S*P,_+=k*R,_+=K*z,_+=Y*T,U=c+=(_+=L*(5*Z))>>>13,U+=E*Z,U+=x*I,U+=M*F,U+=m*C,c=(U+=B*O)>>>13,U&=8191,U+=S*N,U+=k*P,U+=K*R,U+=Y*z,E=y=8191&(c=(c=((c+=(U+=L*T)>>>13)<<2)+c|0)+(y&=8191)|0),x=l+=c>>>=13,M=w&=8191,m=v&=8191,B=p&=8191,S=b&=8191,k=g&=8191,K=A&=8191,Y=_&=8191,L=U&=8191,t+=16,n-=16;this.h[0]=E,this.h[1]=x,this.h[2]=M,this.h[3]=m,this.h[4]=B,this.h[5]=S,this.h[6]=k,this.h[7]=K,this.h[8]=Y,this.h[9]=L},m.prototype.finish=function(r,t){var n,e,o,i,h=new Uint16Array(10);if(this.leftover){for(i=this.leftover,this.buffer[i++]=1;i<16;i++)this.buffer[i]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(n=this.h[1]>>>13,this.h[1]&=8191,i=2;i<10;i++)this.h[i]+=n,n=this.h[i]>>>13,this.h[i]&=8191;for(this.h[0]+=5*n,n=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=n,n=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=n,h[0]=this.h[0]+5,n=h[0]>>>13,h[0]&=8191,i=1;i<10;i++)h[i]=this.h[i]+n,n=h[i]>>>13,h[i]&=8191;for(h[9]-=8192,e=(1^n)-1,i=0;i<10;i++)h[i]&=e;for(e=~e,i=0;i<10;i++)this.h[i]=this.h[i]&e|h[i];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),o=this.h[0]+this.pad[0],this.h[0]=65535&o,i=1;i<8;i++)o=(this.h[i]+this.pad[i]|0)+(o>>>16)|0,this.h[i]=65535&o;r[t+0]=this.h[0]>>>0&255,r[t+1]=this.h[0]>>>8&255,r[t+2]=this.h[1]>>>0&255,r[t+3]=this.h[1]>>>8&255,r[t+4]=this.h[2]>>>0&255,r[t+5]=this.h[2]>>>8&255,r[t+6]=this.h[3]>>>0&255,r[t+7]=this.h[3]>>>8&255,r[t+8]=this.h[4]>>>0&255,r[t+9]=this.h[4]>>>8&255,r[t+10]=this.h[5]>>>0&255,r[t+11]=this.h[5]>>>8&255,r[t+12]=this.h[6]>>>0&255,r[t+13]=this.h[6]>>>8&255,r[t+14]=this.h[7]>>>0&255,r[t+15]=this.h[7]>>>8&255},m.prototype.update=function(r,t,n){var e,o;if(this.leftover){for(n<(o=16-this.leftover)&&(o=n),e=0;e>>16,m=65535&(d=N),B=d>>>16,x+=65535&(E=((w=Z)>>>14|(a=z)<<18)^(Z>>>18|z<<14)^(z>>>9|Z<<23)),M+=E>>>16,m+=65535&(d=(z>>>14|Z<<18)^(z>>>18|Z<<14)^(Z>>>9|z<<23)),B+=d>>>16,x+=65535&(E=Z&(v=G)^~Z&(p=q)),M+=E>>>16,m+=65535&(d=z&(f=R)^~z&(s=P)),B+=d>>>16,d=J[2*_],x+=65535&(E=J[2*_+1]),M+=E>>>16,m+=65535&d,B+=d>>>16,d=S[_%16],M+=(E=k[_%16])>>>16,m+=65535&d,B+=d>>>16,m+=(M+=(x+=65535&E)>>>16)>>>16,x=65535&(E=A=65535&x|M<<16),M=E>>>16,m=65535&(d=g=65535&m|(B+=m>>>16)<<16),B=d>>>16,x+=65535&(E=(O>>>28|K<<4)^(K>>>2|O<<30)^(K>>>7|O<<25)),M+=E>>>16,m+=65535&(d=(K>>>28|O<<4)^(O>>>2|K<<30)^(O>>>7|K<<25)),B+=d>>>16,M+=(E=O&C^O&F^C&F)>>>16,m+=65535&(d=K&Y^K&L^Y&L),B+=d>>>16,u=65535&(m+=(M+=(x+=65535&E)>>>16)>>>16)|(B+=m>>>16)<<16,b=65535&x|M<<16,x=65535&(E=l),M=E>>>16,m=65535&(d=h),B=d>>>16,M+=(E=A)>>>16,m+=65535&(d=g),B+=d>>>16,Y=K,L=o,T=i,z=h=65535&(m+=(M+=(x+=65535&E)>>>16)>>>16)|(B+=m>>>16)<<16,R=a,P=f,N=s,K=u,C=O,F=c,I=y,Z=l=65535&x|M<<16,G=w,q=v,D=p,O=b,_%16==15)for(U=0;U<16;U++)d=S[U],x=65535&(E=k[U]),M=E>>>16,m=65535&d,B=d>>>16,d=S[(U+9)%16],x+=65535&(E=k[(U+9)%16]),M+=E>>>16,m+=65535&d,B+=d>>>16,g=S[(U+1)%16],x+=65535&(E=((A=k[(U+1)%16])>>>1|g<<31)^(A>>>8|g<<24)^(A>>>7|g<<25)),M+=E>>>16,m+=65535&(d=(g>>>1|A<<31)^(g>>>8|A<<24)^g>>>7),B+=d>>>16,g=S[(U+14)%16],M+=(E=((A=k[(U+14)%16])>>>19|g<<13)^(g>>>29|A<<3)^(A>>>6|g<<26))>>>16,m+=65535&(d=(g>>>19|A<<13)^(A>>>29|g<<3)^g>>>6),B+=d>>>16,B+=(m+=(M+=(x+=65535&E)>>>16)>>>16)>>>16,S[U]=65535&m|B<<16,k[U]=65535&x|M<<16;x=65535&(E=O),M=E>>>16,m=65535&(d=K),B=d>>>16,d=r[0],M+=(E=t[0])>>>16,m+=65535&d,B+=d>>>16,B+=(m+=(M+=(x+=65535&E)>>>16)>>>16)>>>16,r[0]=K=65535&m|B<<16,t[0]=O=65535&x|M<<16,x=65535&(E=C),M=E>>>16,m=65535&(d=Y),B=d>>>16,d=r[1],M+=(E=t[1])>>>16,m+=65535&d,B+=d>>>16,B+=(m+=(M+=(x+=65535&E)>>>16)>>>16)>>>16,r[1]=Y=65535&m|B<<16,t[1]=C=65535&x|M<<16,x=65535&(E=F),M=E>>>16,m=65535&(d=L),B=d>>>16,d=r[2],M+=(E=t[2])>>>16,m+=65535&d,B+=d>>>16,B+=(m+=(M+=(x+=65535&E)>>>16)>>>16)>>>16,r[2]=L=65535&m|B<<16,t[2]=F=65535&x|M<<16,x=65535&(E=I),M=E>>>16,m=65535&(d=T),B=d>>>16,d=r[3],M+=(E=t[3])>>>16,m+=65535&d,B+=d>>>16,B+=(m+=(M+=(x+=65535&E)>>>16)>>>16)>>>16,r[3]=T=65535&m|B<<16,t[3]=I=65535&x|M<<16,x=65535&(E=Z),M=E>>>16,m=65535&(d=z),B=d>>>16,d=r[4],M+=(E=t[4])>>>16,m+=65535&d,B+=d>>>16,B+=(m+=(M+=(x+=65535&E)>>>16)>>>16)>>>16,r[4]=z=65535&m|B<<16,t[4]=Z=65535&x|M<<16,x=65535&(E=G),M=E>>>16,m=65535&(d=R),B=d>>>16,d=r[5],M+=(E=t[5])>>>16,m+=65535&d,B+=d>>>16,B+=(m+=(M+=(x+=65535&E)>>>16)>>>16)>>>16,r[5]=R=65535&m|B<<16,t[5]=G=65535&x|M<<16,x=65535&(E=q),M=E>>>16,m=65535&(d=P),B=d>>>16,d=r[6],M+=(E=t[6])>>>16,m+=65535&d,B+=d>>>16,B+=(m+=(M+=(x+=65535&E)>>>16)>>>16)>>>16,r[6]=P=65535&m|B<<16,t[6]=q=65535&x|M<<16,x=65535&(E=D),M=E>>>16,m=65535&(d=N),B=d>>>16,d=r[7],M+=(E=t[7])>>>16,m+=65535&d,B+=d>>>16,B+=(m+=(M+=(x+=65535&E)>>>16)>>>16)>>>16,r[7]=N=65535&m|B<<16,t[7]=D=65535&x|M<<16,V+=128,e-=128}return e}function W(r,t,n){var e,o=new Int32Array(8),i=new Int32Array(8),h=new Uint8Array(256),a=n;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,i[0]=4089235720,i[1]=2227873595,i[2]=4271175723,i[3]=1595750129,i[4]=2917565137,i[5]=725511199,i[6]=4215389547,i[7]=327033209,Q(o,i,t,n),n%=128,e=0;e>(7&o)&1),$(t,r),$(r,r),rr(r,t,e)}function er(r,t){var n=[v(),v(),v(),v()];Y(n[0],e),Y(n[1],a),Y(n[2],u),F(n[3],e,a),nr(r,n,t)}function or(r,t,n){var e,o=new Uint8Array(64),i=[v(),v(),v(),v()];for(n||h(t,32),W(o,t,32),o[0]&=248,o[31]&=127,o[31]|=64,er(i,o),tr(r,i),e=0;e<32;e++)t[e+32]=r[e];return 0}var ir=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function hr(r,t){var n,e,o,i;for(e=63;32<=e;--e){for(n=0,o=e-32,i=e-12;o>4)*ir[o],n=t[o]>>8,t[o]&=255;for(o=0;o<32;o++)t[o]-=n*ir[o];for(e=0;e<32;e++)t[e+1]+=t[e]>>8,r[e]=255&t[e]}function ar(r){var t,n=new Float64Array(64);for(t=0;t<64;t++)n[t]=r[t];for(t=0;t<64;t++)r[t]=0;hr(r,n)}function fr(r,t,n,e){var o,i,h=new Uint8Array(64),a=new Uint8Array(64),f=new Uint8Array(64),s=new Float64Array(64),u=[v(),v(),v(),v()];W(h,e,32),h[0]&=248,h[31]&=127,h[31]|=64;var c=n+64;for(o=0;o>7&&C(r[0],s,r[0]),F(r[3],r[0],r[1])}(f,e))return-1;for(o=0;o void): void; +} diff --git a/node_modules/tweetnacl/nacl.js b/node_modules/tweetnacl/nacl.js new file mode 100644 index 000000000..fd8e6786e --- /dev/null +++ b/node_modules/tweetnacl/nacl.js @@ -0,0 +1,1178 @@ +(function(nacl) { +'use strict'; + +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ + +var u64 = function(h, l) { this.hi = h|0 >>> 0; this.lo = l|0 >>> 0; }; +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; + +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; + +var _0 = new Uint8Array(16); +var _9 = new Uint8Array(32); _9[0] = 9; + +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + +function L32(x, c) { return (x << c) | (x >>> (32 - c)); } + +function ld32(x, i) { + var u = x[i+3] & 0xff; + u = (u<<8)|(x[i+2] & 0xff); + u = (u<<8)|(x[i+1] & 0xff); + return (u<<8)|(x[i+0] & 0xff); +} + +function dl64(x, i) { + var h = (x[i] << 24) | (x[i+1] << 16) | (x[i+2] << 8) | x[i+3]; + var l = (x[i+4] << 24) | (x[i+5] << 16) | (x[i+6] << 8) | x[i+7]; + return new u64(h, l); +} + +function st32(x, j, u) { + var i; + for (i = 0; i < 4; i++) { x[j+i] = u & 255; u >>>= 8; } +} + +function ts64(x, i, u) { + x[i] = (u.hi >> 24) & 0xff; + x[i+1] = (u.hi >> 16) & 0xff; + x[i+2] = (u.hi >> 8) & 0xff; + x[i+3] = u.hi & 0xff; + x[i+4] = (u.lo >> 24) & 0xff; + x[i+5] = (u.lo >> 16) & 0xff; + x[i+6] = (u.lo >> 8) & 0xff; + x[i+7] = u.lo & 0xff; +} + +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; +} + +function crypto_verify_16(x, xi, y, yi) { + return vn(x,xi,y,yi,16); +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); +} + +function core(out,inp,k,c,h) { + var w = new Uint32Array(16), x = new Uint32Array(16), + y = new Uint32Array(16), t = new Uint32Array(4); + var i, j, m; + + for (i = 0; i < 4; i++) { + x[5*i] = ld32(c, 4*i); + x[1+i] = ld32(k, 4*i); + x[6+i] = ld32(inp, 4*i); + x[11+i] = ld32(k, 16+4*i); + } + + for (i = 0; i < 16; i++) y[i] = x[i]; + + for (i = 0; i < 20; i++) { + for (j = 0; j < 4; j++) { + for (m = 0; m < 4; m++) t[m] = x[(5*j+4*m)%16]; + t[1] ^= L32((t[0]+t[3])|0, 7); + t[2] ^= L32((t[1]+t[0])|0, 9); + t[3] ^= L32((t[2]+t[1])|0,13); + t[0] ^= L32((t[3]+t[2])|0,18); + for (m = 0; m < 4; m++) w[4*j+(j+m)%4] = t[m]; + } + for (m = 0; m < 16; m++) x[m] = w[m]; + } + + if (h) { + for (i = 0; i < 16; i++) x[i] = (x[i] + y[i]) | 0; + for (i = 0; i < 4; i++) { + x[5*i] = (x[5*i] - ld32(c, 4*i)) | 0; + x[6+i] = (x[6+i] - ld32(inp, 4*i)) | 0; + } + for (i = 0; i < 4; i++) { + st32(out,4*i,x[5*i]); + st32(out,16+4*i,x[6+i]); + } + } else { + for (i = 0; i < 16; i++) st32(out, 4 * i, (x[i] + y[i]) | 0); + } +} + +function crypto_core_salsa20(out,inp,k,c) { + core(out,inp,k,c,false); + return 0; +} + +function crypto_core_hsalsa20(out,inp,k,c) { + core(out,inp,k,c,true); + return 0; +} + +var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); + // "expand 32-byte k" + +function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + if (!b) return 0; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = (m?m[mpos+i]:0) ^ x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + if (m) mpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = (m?m[mpos+i]:0) ^ x[i]; + } + return 0; +} + +function crypto_stream_salsa20(c,cpos,d,n,k) { + return crypto_stream_salsa20_xor(c,cpos,null,0,d,n,k); +} + +function crypto_stream(c,cpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + return crypto_stream_salsa20(c,cpos,d,n.subarray(16),s); +} + +function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,n.subarray(16),s); +} + +function add1305(h, c) { + var j, u = 0; + for (j = 0; j < 17; j++) { + u = (u + ((h[j] + c[j]) | 0)) | 0; + h[j] = u & 255; + u >>>= 8; + } +} + +var minusp = new Uint32Array([ + 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 252 +]); + +function crypto_onetimeauth(out, outpos, m, mpos, n, k) { + var s, i, j, u; + var x = new Uint32Array(17), r = new Uint32Array(17), + h = new Uint32Array(17), c = new Uint32Array(17), + g = new Uint32Array(17); + for (j = 0; j < 17; j++) r[j]=h[j]=0; + for (j = 0; j < 16; j++) r[j]=k[j]; + r[3]&=15; + r[4]&=252; + r[7]&=15; + r[8]&=252; + r[11]&=15; + r[12]&=252; + r[15]&=15; + + while (n > 0) { + for (j = 0; j < 17; j++) c[j] = 0; + for (j = 0; (j < 16) && (j < n); ++j) c[j] = m[mpos+j]; + c[j] = 1; + mpos += j; n -= j; + add1305(h,c); + for (i = 0; i < 17; i++) { + x[i] = 0; + for (j = 0; j < 17; j++) x[i] = (x[i] + (h[j] * ((j <= i) ? r[i - j] : ((320 * r[i + 17 - j])|0))) | 0) | 0; + } + for (i = 0; i < 17; i++) h[i] = x[i]; + u = 0; + for (j = 0; j < 16; j++) { + u = (u + h[j]) | 0; + h[j] = u & 255; + u >>>= 8; + } + u = (u + h[16]) | 0; h[16] = u & 3; + u = (5 * (u >>> 2)) | 0; + for (j = 0; j < 16; j++) { + u = (u + h[j]) | 0; + h[j] = u & 255; + u >>>= 8; + } + u = (u + h[16]) | 0; h[16] = u; + } + + for (j = 0; j < 17; j++) g[j] = h[j]; + add1305(h,minusp); + s = (-(h[16] >>> 7) | 0); + for (j = 0; j < 17; j++) h[j] ^= s & (g[j] ^ h[j]); + + for (j = 0; j < 16; j++) c[j] = k[j + 16]; + c[16] = 0; + add1305(h,c); + for (j = 0; j < 16; j++) out[outpos+j] = h[j]; + return 0; +} + +function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { + var x = new Uint8Array(16); + crypto_onetimeauth(x,0,m,mpos,n,k); + return crypto_verify_16(h,hpos,x,0); +} + +function crypto_secretbox(c,m,d,n,k) { + var i; + if (d < 32) return -1; + crypto_stream_xor(c,0,m,0,d,n,k); + crypto_onetimeauth(c, 16, c, 32, d - 32, c); + for (i = 0; i < 16; i++) c[i] = 0; + return 0; +} + +function crypto_secretbox_open(m,c,d,n,k) { + var i; + var x = new Uint8Array(32); + if (d < 32) return -1; + crypto_stream(x,0,32,n,k); + if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; + crypto_stream_xor(m,0,c,0,d,n,k); + for (i = 0; i < 32; i++) m[i] = 0; + return 0; +} + +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} + +function car25519(o) { + var c; + var i; + for (i = 0; i < 16; i++) { + o[i] += 65536; + c = Math.floor(o[i] / 65536); + o[(i+1)*(i<15?1:0)] += c - 1 + 37 * (c-1) * (i===15?1:0); + o[i] -= (c * 65536); + } +} + +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; + } +} + +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} + +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; +} + +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} + +function A(o, a, b) { + var i; + for (i = 0; i < 16; i++) o[i] = (a[i] + b[i])|0; +} + +function Z(o, a, b) { + var i; + for (i = 0; i < 16; i++) o[i] = (a[i] - b[i])|0; +} + +function M(o, a, b) { + var i, j, t = new Float64Array(31); + for (i = 0; i < 31; i++) t[i] = 0; + for (i = 0; i < 16; i++) { + for (j = 0; j < 16; j++) { + t[i+j] += a[i] * b[j]; + } + } + for (i = 0; i < 15; i++) { + t[i] += 38 * t[i+16]; + } + for (i = 0; i < 16; i++) o[i] = t[i]; + car25519(o); + car25519(o); +} + +function S(o, a) { + M(o, a, a); +} + +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} + +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; + } + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); + } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; + } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; +} + +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); +} + +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); +} + +function crypto_box_beforenm(k, y, x) { + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y); + return crypto_core_hsalsa20(k, _0, s, sigma); +} + +var crypto_box_afternm = crypto_secretbox; +var crypto_box_open_afternm = crypto_secretbox_open; + +function crypto_box(c, m, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_afternm(c, m, d, n, k); +} + +function crypto_box_open(m, c, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_open_afternm(m, c, d, n, k); +} + +function add64() { + var a = 0, b = 0, c = 0, d = 0, m16 = 65535, l, h, i; + for (i = 0; i < arguments.length; i++) { + l = arguments[i].lo; + h = arguments[i].hi; + a += (l & m16); b += (l >>> 16); + c += (h & m16); d += (h >>> 16); + } + + b += (a >>> 16); + c += (b >>> 16); + d += (c >>> 16); + + return new u64((c & m16) | (d << 16), (a & m16) | (b << 16)); +} + +function shr64(x, c) { + return new u64((x.hi >>> c), (x.lo >>> c) | (x.hi << (32 - c))); +} + +function xor64() { + var l = 0, h = 0, i; + for (i = 0; i < arguments.length; i++) { + l ^= arguments[i].lo; + h ^= arguments[i].hi; + } + return new u64(h, l); +} + +function R(x, c) { + var h, l, c1 = 32 - c; + if (c < 32) { + h = (x.hi >>> c) | (x.lo << c1); + l = (x.lo >>> c) | (x.hi << c1); + } else if (c < 64) { + h = (x.lo >>> c) | (x.hi << c1); + l = (x.hi >>> c) | (x.lo << c1); + } + return new u64(h, l); +} + +function Ch(x, y, z) { + var h = (x.hi & y.hi) ^ (~x.hi & z.hi), + l = (x.lo & y.lo) ^ (~x.lo & z.lo); + return new u64(h, l); +} + +function Maj(x, y, z) { + var h = (x.hi & y.hi) ^ (x.hi & z.hi) ^ (y.hi & z.hi), + l = (x.lo & y.lo) ^ (x.lo & z.lo) ^ (y.lo & z.lo); + return new u64(h, l); +} + +function Sigma0(x) { return xor64(R(x,28), R(x,34), R(x,39)); } +function Sigma1(x) { return xor64(R(x,14), R(x,18), R(x,41)); } +function sigma0(x) { return xor64(R(x, 1), R(x, 8), shr64(x,7)); } +function sigma1(x) { return xor64(R(x,19), R(x,61), shr64(x,6)); } + +var K = [ + new u64(0x428a2f98, 0xd728ae22), new u64(0x71374491, 0x23ef65cd), + new u64(0xb5c0fbcf, 0xec4d3b2f), new u64(0xe9b5dba5, 0x8189dbbc), + new u64(0x3956c25b, 0xf348b538), new u64(0x59f111f1, 0xb605d019), + new u64(0x923f82a4, 0xaf194f9b), new u64(0xab1c5ed5, 0xda6d8118), + new u64(0xd807aa98, 0xa3030242), new u64(0x12835b01, 0x45706fbe), + new u64(0x243185be, 0x4ee4b28c), new u64(0x550c7dc3, 0xd5ffb4e2), + new u64(0x72be5d74, 0xf27b896f), new u64(0x80deb1fe, 0x3b1696b1), + new u64(0x9bdc06a7, 0x25c71235), new u64(0xc19bf174, 0xcf692694), + new u64(0xe49b69c1, 0x9ef14ad2), new u64(0xefbe4786, 0x384f25e3), + new u64(0x0fc19dc6, 0x8b8cd5b5), new u64(0x240ca1cc, 0x77ac9c65), + new u64(0x2de92c6f, 0x592b0275), new u64(0x4a7484aa, 0x6ea6e483), + new u64(0x5cb0a9dc, 0xbd41fbd4), new u64(0x76f988da, 0x831153b5), + new u64(0x983e5152, 0xee66dfab), new u64(0xa831c66d, 0x2db43210), + new u64(0xb00327c8, 0x98fb213f), new u64(0xbf597fc7, 0xbeef0ee4), + new u64(0xc6e00bf3, 0x3da88fc2), new u64(0xd5a79147, 0x930aa725), + new u64(0x06ca6351, 0xe003826f), new u64(0x14292967, 0x0a0e6e70), + new u64(0x27b70a85, 0x46d22ffc), new u64(0x2e1b2138, 0x5c26c926), + new u64(0x4d2c6dfc, 0x5ac42aed), new u64(0x53380d13, 0x9d95b3df), + new u64(0x650a7354, 0x8baf63de), new u64(0x766a0abb, 0x3c77b2a8), + new u64(0x81c2c92e, 0x47edaee6), new u64(0x92722c85, 0x1482353b), + new u64(0xa2bfe8a1, 0x4cf10364), new u64(0xa81a664b, 0xbc423001), + new u64(0xc24b8b70, 0xd0f89791), new u64(0xc76c51a3, 0x0654be30), + new u64(0xd192e819, 0xd6ef5218), new u64(0xd6990624, 0x5565a910), + new u64(0xf40e3585, 0x5771202a), new u64(0x106aa070, 0x32bbd1b8), + new u64(0x19a4c116, 0xb8d2d0c8), new u64(0x1e376c08, 0x5141ab53), + new u64(0x2748774c, 0xdf8eeb99), new u64(0x34b0bcb5, 0xe19b48a8), + new u64(0x391c0cb3, 0xc5c95a63), new u64(0x4ed8aa4a, 0xe3418acb), + new u64(0x5b9cca4f, 0x7763e373), new u64(0x682e6ff3, 0xd6b2b8a3), + new u64(0x748f82ee, 0x5defb2fc), new u64(0x78a5636f, 0x43172f60), + new u64(0x84c87814, 0xa1f0ab72), new u64(0x8cc70208, 0x1a6439ec), + new u64(0x90befffa, 0x23631e28), new u64(0xa4506ceb, 0xde82bde9), + new u64(0xbef9a3f7, 0xb2c67915), new u64(0xc67178f2, 0xe372532b), + new u64(0xca273ece, 0xea26619c), new u64(0xd186b8c7, 0x21c0c207), + new u64(0xeada7dd6, 0xcde0eb1e), new u64(0xf57d4f7f, 0xee6ed178), + new u64(0x06f067aa, 0x72176fba), new u64(0x0a637dc5, 0xa2c898a6), + new u64(0x113f9804, 0xbef90dae), new u64(0x1b710b35, 0x131c471b), + new u64(0x28db77f5, 0x23047d84), new u64(0x32caab7b, 0x40c72493), + new u64(0x3c9ebe0a, 0x15c9bebc), new u64(0x431d67c4, 0x9c100d4c), + new u64(0x4cc5d4be, 0xcb3e42b6), new u64(0x597f299c, 0xfc657e2a), + new u64(0x5fcb6fab, 0x3ad6faec), new u64(0x6c44198c, 0x4a475817) +]; + +function crypto_hashblocks(x, m, n) { + var z = [], b = [], a = [], w = [], t, i, j; + + for (i = 0; i < 8; i++) z[i] = a[i] = dl64(x, 8*i); + + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) w[i] = dl64(m, 8*i+pos); + for (i = 0; i < 80; i++) { + for (j = 0; j < 8; j++) b[j] = a[j]; + t = add64(a[7], Sigma1(a[4]), Ch(a[4], a[5], a[6]), K[i], w[i%16]); + b[7] = add64(t, Sigma0(a[0]), Maj(a[0], a[1], a[2])); + b[3] = add64(b[3], t); + for (j = 0; j < 8; j++) a[(j+1)%8] = b[j]; + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + w[j] = add64(w[j], w[(j+9)%16], sigma0(w[(j+1)%16]), sigma1(w[(j+14)%16])); + } + } + } + + for (i = 0; i < 8; i++) { + a[i] = add64(a[i], z[i]); + z[i] = a[i]; + } + + pos += 128; + n -= 128; + } + + for (i = 0; i < 8; i++) ts64(x, 8*i, z[i]); + return n; +} + +var iv = new Uint8Array([ + 0x6a,0x09,0xe6,0x67,0xf3,0xbc,0xc9,0x08, + 0xbb,0x67,0xae,0x85,0x84,0xca,0xa7,0x3b, + 0x3c,0x6e,0xf3,0x72,0xfe,0x94,0xf8,0x2b, + 0xa5,0x4f,0xf5,0x3a,0x5f,0x1d,0x36,0xf1, + 0x51,0x0e,0x52,0x7f,0xad,0xe6,0x82,0xd1, + 0x9b,0x05,0x68,0x8c,0x2b,0x3e,0x6c,0x1f, + 0x1f,0x83,0xd9,0xab,0xfb,0x41,0xbd,0x6b, + 0x5b,0xe0,0xcd,0x19,0x13,0x7e,0x21,0x79 +]); + +function crypto_hash(out, m, n) { + var h = new Uint8Array(64), x = new Uint8Array(256); + var i, b = n; + + for (i = 0; i < 64; i++) h[i] = iv[i]; + + crypto_hashblocks(h, m, n); + n %= 128; + + for (i = 0; i < 256; i++) x[i] = 0; + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; + + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, new u64((b / 0x20000000) | 0, b << 3)); + crypto_hashblocks(h, x, n); + + for (i = 0; i < 64; i++) out[i] = h[i]; + + return 0; +} + +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } +} + +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} + +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } +} + +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} + +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; + + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + scalarbase(p, d); + pack(pk, p); + + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} + +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); + +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = Math.floor((x[j] + 128) / 256); + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} + +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} + +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; + + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); + + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; + } + } + + modL(sm.subarray(32), x); + return smlen; +} + +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + return 0; +} + +function crypto_sign_open(m, sm, n, pk) { + var i; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; + + if (n < 64) return -1; + + if (unpackneg(q, pk)) return -1; + + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); + + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; + } + + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + return n; +} + +var crypto_secretbox_KEYBYTES = 32, + crypto_secretbox_NONCEBYTES = 24, + crypto_secretbox_ZEROBYTES = 32, + crypto_secretbox_BOXZEROBYTES = 16, + crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_box_BEFORENMBYTES = 32, + crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, + crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, + crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32, + crypto_hash_BYTES = 64; + +nacl.lowlevel = { + crypto_core_hsalsa20: crypto_core_hsalsa20, + crypto_stream_xor: crypto_stream_xor, + crypto_stream: crypto_stream, + crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, + crypto_stream_salsa20: crypto_stream_salsa20, + crypto_onetimeauth: crypto_onetimeauth, + crypto_onetimeauth_verify: crypto_onetimeauth_verify, + crypto_verify_16: crypto_verify_16, + crypto_verify_32: crypto_verify_32, + crypto_secretbox: crypto_secretbox, + crypto_secretbox_open: crypto_secretbox_open, + crypto_scalarmult: crypto_scalarmult, + crypto_scalarmult_base: crypto_scalarmult_base, + crypto_box_beforenm: crypto_box_beforenm, + crypto_box_afternm: crypto_box_afternm, + crypto_box: crypto_box, + crypto_box_open: crypto_box_open, + crypto_box_keypair: crypto_box_keypair, + crypto_hash: crypto_hash, + crypto_sign: crypto_sign, + crypto_sign_keypair: crypto_sign_keypair, + crypto_sign_open: crypto_sign_open, + + crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, + crypto_sign_BYTES: crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, + crypto_hash_BYTES: crypto_hash_BYTES, + + gf: gf, + D: D, + L: L, + pack25519: pack25519, + unpack25519: unpack25519, + M: M, + A: A, + S: S, + Z: Z, + pow2523: pow2523, + add: add, + set25519: set25519, + modL: modL, + scalarmult: scalarmult, + scalarbase: scalarbase, +}; + +/* High-level API */ + +function checkLengths(k, n) { + if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); +} + +function checkBoxLengths(pk, sk) { + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); +} + +function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError('unexpected type, use Uint8Array'); + } +} + +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} + +nacl.randomBytes = function(n) { + var b = new Uint8Array(n); + randombytes(b, n); + return b; +}; + +nacl.secretbox = function(msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c = new Uint8Array(m.length); + for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; + crypto_secretbox(c, m, m.length, nonce, key); + return c.subarray(crypto_secretbox_BOXZEROBYTES); +}; + +nacl.secretbox.open = function(box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m = new Uint8Array(c.length); + for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; + if (c.length < 32) return null; + if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null; + return m.subarray(crypto_secretbox_ZEROBYTES); +}; + +nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; +nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; +nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; + +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; + +nacl.scalarMult.base = function(n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; +}; + +nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; +nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; + +nacl.box = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k); +}; + +nacl.box.before = function(publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k, publicKey, secretKey); + return k; +}; + +nacl.box.after = nacl.secretbox; + +nacl.box.open = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k); +}; + +nacl.box.open.after = nacl.secretbox.open; + +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; +nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; +nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; +nacl.box.nonceLength = crypto_box_NONCEBYTES; +nacl.box.overheadLength = nacl.secretbox.overheadLength; + +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; + +nacl.sign.open = function(signedMsg, publicKey) { + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m = new Uint8Array(mlen); + for (var i = 0; i < m.length; i++) m[i] = tmp[i]; + return m; +}; + +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; + +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; + +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; + +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; + +nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; +nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; +nacl.sign.seedLength = crypto_sign_SEEDBYTES; +nacl.sign.signatureLength = crypto_sign_BYTES; + +nacl.hash = function(msg) { + checkArrayTypes(msg); + var h = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h, msg, msg.length); + return h; +}; + +nacl.hash.hashLength = crypto_hash_BYTES; + +nacl.verify = function(x, y) { + checkArrayTypes(x, y); + // Zero length arguments are considered not equal. + if (x.length === 0 || y.length === 0) return false; + if (x.length !== y.length) return false; + return (vn(x, 0, y, 0, x.length) === 0) ? true : false; +}; + +nacl.setPRNG = function(fn) { + randombytes = fn; +}; + +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; + if (crypto && crypto.getRandomValues) { + // Browsers. + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } else if (typeof require !== 'undefined') { + // Node.js. + crypto = require('crypto'); + if (crypto && crypto.randomBytes) { + nacl.setPRNG(function(x, n) { + var i, v = crypto.randomBytes(n); + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } + } +})(); + +})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {})); diff --git a/node_modules/tweetnacl/nacl.min.js b/node_modules/tweetnacl/nacl.min.js new file mode 100644 index 000000000..65340cca9 --- /dev/null +++ b/node_modules/tweetnacl/nacl.min.js @@ -0,0 +1 @@ +!function(i){"use strict";var m=function(r,n){this.hi=0|r,this.lo=0|n},v=function(r){var n,e=new Float64Array(16);if(r)for(n=0;n>>32-n}function b(r,n){var e=255&r[n+3];return(e=(e=e<<8|255&r[n+2])<<8|255&r[n+1])<<8|255&r[n+0]}function B(r,n){var e=r[n]<<24|r[n+1]<<16|r[n+2]<<8|r[n+3],t=r[n+4]<<24|r[n+5]<<16|r[n+6]<<8|r[n+7];return new m(e,t)}function p(r,n,e){var t;for(t=0;t<4;t++)r[n+t]=255&e,e>>>=8}function S(r,n,e){r[n]=e.hi>>24&255,r[n+1]=e.hi>>16&255,r[n+2]=e.hi>>8&255,r[n+3]=255&e.hi,r[n+4]=e.lo>>24&255,r[n+5]=e.lo>>16&255,r[n+6]=e.lo>>8&255,r[n+7]=255&e.lo}function u(r,n,e,t,o){var i,a=0;for(i=0;i>>8)-1}function A(r,n,e,t){return u(r,n,e,t,16)}function _(r,n,e,t){return u(r,n,e,t,32)}function U(r,n,e,t,o){var i,a,f,u=new Uint32Array(16),c=new Uint32Array(16),w=new Uint32Array(16),y=new Uint32Array(4);for(i=0;i<4;i++)c[5*i]=b(t,4*i),c[1+i]=b(e,4*i),c[6+i]=b(n,4*i),c[11+i]=b(e,16+4*i);for(i=0;i<16;i++)w[i]=c[i];for(i=0;i<20;i++){for(a=0;a<4;a++){for(f=0;f<4;f++)y[f]=c[(5*a+4*f)%16];for(y[1]^=h(y[0]+y[3]|0,7),y[2]^=h(y[1]+y[0]|0,9),y[3]^=h(y[2]+y[1]|0,13),y[0]^=h(y[3]+y[2]|0,18),f=0;f<4;f++)u[4*a+(a+f)%4]=y[f]}for(f=0;f<16;f++)c[f]=u[f]}if(o){for(i=0;i<16;i++)c[i]=c[i]+w[i]|0;for(i=0;i<4;i++)c[5*i]=c[5*i]-b(t,4*i)|0,c[6+i]=c[6+i]-b(n,4*i)|0;for(i=0;i<4;i++)p(r,4*i,c[5*i]),p(r,16+4*i,c[6+i])}else for(i=0;i<16;i++)p(r,4*i,c[i]+w[i]|0)}function E(r,n,e,t){U(r,n,e,t,!1)}function x(r,n,e,t){return U(r,n,e,t,!0),0}var d=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function K(r,n,e,t,o,i,a){var f,u,c=new Uint8Array(16),w=new Uint8Array(64);if(!o)return 0;for(u=0;u<16;u++)c[u]=0;for(u=0;u<8;u++)c[u]=i[u];for(;64<=o;){for(E(w,c,a,d),u=0;u<64;u++)r[n+u]=(e?e[t+u]:0)^w[u];for(f=1,u=8;u<16;u++)f=f+(255&c[u])|0,c[u]=255&f,f>>>=8;o-=64,n+=64,e&&(t+=64)}if(0>>=8}var z=new Uint32Array([5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252]);function R(r,n,e,t,o,i){var a,f,u,c,w=new Uint32Array(17),y=new Uint32Array(17),l=new Uint32Array(17),s=new Uint32Array(17),h=new Uint32Array(17);for(u=0;u<17;u++)y[u]=l[u]=0;for(u=0;u<16;u++)y[u]=i[u];for(y[3]&=15,y[4]&=252,y[7]&=15,y[8]&=252,y[11]&=15,y[12]&=252,y[15]&=15;0>>=8;for(c=c+l[16]|0,l[16]=3&c,c=5*(c>>>2)|0,u=0;u<16;u++)c=c+l[u]|0,l[u]=255&c,c>>>=8;c=c+l[16]|0,l[16]=c}for(u=0;u<17;u++)h[u]=l[u];for(k(l,z),a=0|-(l[16]>>>7),u=0;u<17;u++)l[u]^=a&(h[u]^l[u]);for(u=0;u<16;u++)s[u]=i[u+16];for(s[16]=0,k(l,s),u=0;u<16;u++)r[n+u]=l[u];return 0}function P(r,n,e,t,o,i){var a=new Uint8Array(16);return R(a,0,e,t,o,i),A(r,n,a,0)}function M(r,n,e,t,o){var i;if(e<32)return-1;for(T(r,0,n,0,e,t,o),R(r,16,r,32,e-32,r),i=0;i<16;i++)r[i]=0;return 0}function N(r,n,e,t,o){var i,a=new Uint8Array(32);if(e<32)return-1;if(L(a,0,32,t,o),0!==P(n,16,n,32,e-32,a))return-1;for(T(r,0,n,0,e,t,o),i=0;i<32;i++)r[i]=0;return 0}function O(r,n){var e;for(e=0;e<16;e++)r[e]=0|n[e]}function C(r){var n,e;for(e=0;e<16;e++)r[e]+=65536,n=Math.floor(r[e]/65536),r[(e+1)*(e<15?1:0)]+=n-1+37*(n-1)*(15===e?1:0),r[e]-=65536*n}function F(r,n,e){for(var t,o=~(e-1),i=0;i<16;i++)t=o&(r[i]^n[i]),r[i]^=t,n[i]^=t}function Z(r,n){var e,t,o,i=v(),a=v();for(e=0;e<16;e++)a[e]=n[e];for(C(a),C(a),C(a),t=0;t<2;t++){for(i[0]=a[0]-65517,e=1;e<15;e++)i[e]=a[e]-65535-(i[e-1]>>16&1),i[e-1]&=65535;i[15]=a[15]-32767-(i[14]>>16&1),o=i[15]>>16&1,i[14]&=65535,F(a,i,1-o)}for(e=0;e<16;e++)r[2*e]=255&a[e],r[2*e+1]=a[e]>>8}function G(r,n){var e=new Uint8Array(32),t=new Uint8Array(32);return Z(e,r),Z(t,n),_(e,0,t,0)}function q(r){var n=new Uint8Array(32);return Z(n,r),1&n[0]}function D(r,n){var e;for(e=0;e<16;e++)r[e]=n[2*e]+(n[2*e+1]<<8);r[15]&=32767}function I(r,n,e){var t;for(t=0;t<16;t++)r[t]=n[t]+e[t]|0}function V(r,n,e){var t;for(t=0;t<16;t++)r[t]=n[t]-e[t]|0}function X(r,n,e){var t,o,i=new Float64Array(31);for(t=0;t<31;t++)i[t]=0;for(t=0;t<16;t++)for(o=0;o<16;o++)i[t+o]+=n[t]*e[o];for(t=0;t<15;t++)i[t]+=38*i[t+16];for(t=0;t<16;t++)r[t]=i[t];C(r),C(r)}function j(r,n){X(r,n,n)}function H(r,n){var e,t=v();for(e=0;e<16;e++)t[e]=n[e];for(e=253;0<=e;e--)j(t,t),2!==e&&4!==e&&X(t,t,n);for(e=0;e<16;e++)r[e]=t[e]}function J(r,n){var e,t=v();for(e=0;e<16;e++)t[e]=n[e];for(e=250;0<=e;e--)j(t,t),1!==e&&X(t,t,n);for(e=0;e<16;e++)r[e]=t[e]}function Q(r,n,e){var t,o,i=new Uint8Array(32),a=new Float64Array(80),f=v(),u=v(),c=v(),w=v(),y=v(),l=v();for(o=0;o<31;o++)i[o]=n[o];for(i[31]=127&n[31]|64,i[0]&=248,D(a,e),o=0;o<16;o++)u[o]=a[o],w[o]=f[o]=c[o]=0;for(f[0]=w[0]=1,o=254;0<=o;--o)F(f,u,t=i[o>>>3]>>>(7&o)&1),F(c,w,t),I(y,f,c),V(f,f,c),I(c,u,w),V(u,u,w),j(w,y),j(l,f),X(f,c,f),X(c,u,y),I(y,f,c),V(f,f,c),j(u,f),V(c,w,l),X(f,c,g),I(f,f,w),X(c,c,f),X(f,w,l),X(w,u,a),j(u,y),F(f,u,t),F(c,w,t);for(o=0;o<16;o++)a[o+16]=f[o],a[o+32]=c[o],a[o+48]=u[o],a[o+64]=w[o];var s=a.subarray(32),h=a.subarray(16);return H(s,s),X(h,h,s),Z(r,h),0}function W(r,n){return Q(r,n,e)}function $(r,n){return a(n,32),W(r,n)}function rr(r,n,e){var t=new Uint8Array(32);return Q(t,e,n),x(r,o,t,d)}var nr=M,er=N;function tr(){var r,n,e,t=0,o=0,i=0,a=0,f=65535;for(e=0;e>>16,i+=(n=arguments[e].hi)&f,a+=n>>>16;return new m((i+=(o+=t>>>16)>>>16)&f|(a+=i>>>16)<<16,t&f|o<<16)}function or(r,n){return new m(r.hi>>>n,r.lo>>>n|r.hi<<32-n)}function ir(){var r,n=0,e=0;for(r=0;r>>n|r.lo<>>n|r.hi<>>n|r.hi<>>n|r.lo<>(7&o)&1),yr(n,r),yr(r,r),lr(r,n,t)}function vr(r,n){var e=[v(),v(),v(),v()];O(e[0],t),O(e[1],f),O(e[2],w),X(e[3],t,f),hr(r,e,n)}function gr(r,n,e){var t,o=new Uint8Array(64),i=[v(),v(),v(),v()];for(e||a(n,32),wr(o,n,32),o[0]&=248,o[31]&=127,o[31]|=64,vr(i,o),sr(r,i),t=0;t<32;t++)n[t+32]=r[t];return 0}var br=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function pr(r,n){var e,t,o,i;for(t=63;32<=t;--t){for(e=0,o=t-32,i=t-12;o>4)*br[o],e=n[o]>>8,n[o]&=255;for(o=0;o<32;o++)n[o]-=e*br[o];for(t=0;t<32;t++)n[t+1]+=n[t]>>8,r[t]=255&n[t]}function Ar(r){var n,e=new Float64Array(64);for(n=0;n<64;n++)e[n]=r[n];for(n=0;n<64;n++)r[n]=0;pr(r,e)}function _r(r,n,e,t){var o,i,a=new Uint8Array(64),f=new Uint8Array(64),u=new Uint8Array(64),c=new Float64Array(64),w=[v(),v(),v(),v()];wr(a,t,32),a[0]&=248,a[31]&=127,a[31]|=64;var y=e+64;for(o=0;o>7&&V(r[0],c,r[0]),X(r[3],r[0],r[1])}(u,t))return-1;for(o=0;o/dev/null && browserify test/browser/init.js test/*.quick.js | uglifyjs -c -m -o test/browser/_bundle-quick.js 2>/dev/null", + "test": "npm run test-node-all", + "bench": "node test/benchmark/bench.js", + "lint": "eslint nacl.js nacl-fast.js test/*.js test/benchmark/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/dchest/tweetnacl-js.git" + }, + "keywords": [ + "crypto", + "cryptography", + "curve25519", + "ed25519", + "encrypt", + "hash", + "key", + "nacl", + "poly1305", + "public", + "salsa20", + "signatures" + ], + "author": "TweetNaCl-js contributors", + "license": "Unlicense", + "bugs": { + "url": "https://github.com/dchest/tweetnacl-js/issues" + }, + "homepage": "https://tweetnacl.js.org", + "devDependencies": { + "browserify": "^16.2.3", + "eslint": "^6.8.0", + "faucet": "^0.0.1", + "tap-browser-color": "^0.1.2", + "tape": "^4.13.0", + "tweetnacl-util": "^0.15.0", + "uglify-js": "^3.7.5" + }, + "browser": { + "buffer": false, + "crypto": false + } +} diff --git a/node_modules/urijs/LICENSE.txt b/node_modules/urijs/LICENSE.txt new file mode 100644 index 000000000..c13824f47 --- /dev/null +++ b/node_modules/urijs/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2011 Rodney Rehm + +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/node_modules/urijs/README.md b/node_modules/urijs/README.md new file mode 100644 index 000000000..ecee39bef --- /dev/null +++ b/node_modules/urijs/README.md @@ -0,0 +1,249 @@ +# URI.js # + +[![CDNJS](https://img.shields.io/cdnjs/v/URI.js.svg)](https://cdnjs.com/libraries/URI.js) +* [About](http://medialize.github.io/URI.js/) +* [Understanding URIs](http://medialize.github.io/URI.js/about-uris.html) +* [Documentation](http://medialize.github.io/URI.js/docs.html) +* [jQuery URI Plugin](http://medialize.github.io/URI.js/jquery-uri-plugin.html) +* [Author](http://rodneyrehm.de/en/) +* [Changelog](./CHANGELOG.md) + +--- + +> **IMPORTANT:** You **may not need URI.js** anymore! Modern browsers provide the [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) and [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) interfaces. + +--- + +> **NOTE:** The npm package name changed to `urijs` + +--- + +I always want to shoot myself in the head when looking at code like the following: + +```javascript +var url = "http://example.org/foo?bar=baz"; +var separator = url.indexOf('?') > -1 ? '&' : '?'; + +url += separator + encodeURIComponent("foo") + "=" + encodeURIComponent("bar"); +``` + +Things are looking up with [URL](https://developer.mozilla.org/en/docs/Web/API/URL) and the [URL spec](http://url.spec.whatwg.org/) but until we can safely rely on that API, have a look at URI.js for a clean and simple API for mutating URIs: + +```javascript +var url = new URI("http://example.org/foo?bar=baz"); +url.addQuery("foo", "bar"); +``` + +URI.js is here to help with that. + + +## API Example ## + +```javascript +// mutating URLs +URI("http://example.org/foo.html?hello=world") + .username("rodneyrehm") + // -> http://rodneyrehm@example.org/foo.html?hello=world + .username("") + // -> http://example.org/foo.html?hello=world + .directory("bar") + // -> http://example.org/bar/foo.html?hello=world + .suffix("xml") + // -> http://example.org/bar/foo.xml?hello=world + .query("") + // -> http://example.org/bar/foo.xml + .tld("com") + // -> http://example.com/bar/foo.xml + .query({ foo: "bar", hello: ["world", "mars"] }); + // -> http://example.com/bar/foo.xml?foo=bar&hello=world&hello=mars + +// cleaning things up +URI("?&foo=bar&&foo=bar&foo=baz&") + .normalizeQuery(); + // -> ?foo=bar&foo=baz + +// working with relative paths +URI("/foo/bar/baz.html") + .relativeTo("/foo/bar/world.html"); + // -> ./baz.html + +URI("/foo/bar/baz.html") + .relativeTo("/foo/bar/sub/world.html") + // -> ../baz.html + .absoluteTo("/foo/bar/sub/world.html"); + // -> /foo/bar/baz.html + +// URI Templates +URI.expand("/foo/{dir}/{file}", { + dir: "bar", + file: "world.html" +}); +// -> /foo/bar/world.html +``` + +See the [About Page](http://medialize.github.io/URI.js/) and [API Docs](http://medialize.github.io/URI.js/docs.html) for more stuff. + +## Using URI.js ## + +URI.js (without plugins) has a gzipped weight of about 7KB - if you include all extensions you end up at about 13KB. So unless you *need* second level domain support and use URI templates, we suggest you don't include them in your build. If you don't need a full featured URI mangler, it may be worth looking into the much smaller parser-only alternatives [listed below](#alternatives). + +URI.js is available through [npm](https://www.npmjs.com/package/urijs), [bower](http://bower.io/search/?q=urijs), [bowercdn](http://bowercdn.net/package/urijs), [cdnjs](https://cdnjs.com/libraries/URI.js) and manually from the [build page](http://medialize.github.io/URI.js/build.html): + +```bash +# using bower +bower install uri.js + +# using npm +npm install urijs +``` + +### Browser ### + +I guess you'll manage to use the [build tool](http://medialize.github.io/URI.js/build.html) or follow the [instructions below](#minify) to combine and minify the various files into URI.min.js - and I'm fairly certain you know how to `` that sucker, too. + +### Node.js and NPM ### + +Install with `npm install urijs` or add `"urijs"` to the dependencies in your `package.json`. + +```javascript +// load URI.js +var URI = require('urijs'); +// load an optional module (e.g. URITemplate) +var URITemplate = require('urijs/src/URITemplate'); + +URI("/foo/bar/baz.html") + .relativeTo("/foo/bar/sub/world.html") + // -> ../baz.html +``` + +### RequireJS ### + +Clone the URI.js repository or use a package manager to get URI.js into your project. + +```javascript +require.config({ + paths: { + urijs: 'where-you-put-uri.js/src' + } +}); + +require(['urijs/URI'], function(URI) { + console.log("URI.js and dependencies: ", URI("//amazon.co.uk").is('sld') ? 'loaded' : 'failed'); +}); +require(['urijs/URITemplate'], function(URITemplate) { + console.log("URITemplate.js and dependencies: ", URITemplate._cache ? 'loaded' : 'failed'); +}); +``` + +## Minify ## + +See the [build tool](http://medialize.github.io/URI.js/build.html) or use [Google Closure Compiler](http://closure-compiler.appspot.com/home): + +``` +// ==ClosureCompiler== +// @compilation_level SIMPLE_OPTIMIZATIONS +// @output_file_name URI.min.js +// @code_url http://medialize.github.io/URI.js/src/IPv6.js +// @code_url http://medialize.github.io/URI.js/src/punycode.js +// @code_url http://medialize.github.io/URI.js/src/SecondLevelDomains.js +// @code_url http://medialize.github.io/URI.js/src/URI.js +// @code_url http://medialize.github.io/URI.js/src/URITemplate.js +// ==/ClosureCompiler== +``` + + +## Resources ## + +Documents specifying how URLs work: + +* [URL - Living Standard](http://url.spec.whatwg.org/) +* [RFC 3986 - Uniform Resource Identifier (URI): Generic Syntax](http://tools.ietf.org/html/rfc3986) +* [RFC 3987 - Internationalized Resource Identifiers (IRI)](http://tools.ietf.org/html/rfc3987) +* [RFC 2732 - Format for Literal IPv6 Addresses in URL's](http://tools.ietf.org/html/rfc2732) +* [RFC 2368 - The `mailto:` URL Scheme](https://www.ietf.org/rfc/rfc2368.txt) +* [RFC 2141 - URN Syntax](https://www.ietf.org/rfc/rfc2141.txt) +* [IANA URN Namespace Registry](http://www.iana.org/assignments/urn-namespaces/urn-namespaces.xhtml) +* [Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA)](http://tools.ietf.org/html/rfc3492) +* [application/x-www-form-urlencoded](http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type) (Query String Parameters) and [application/x-www-form-urlencoded encoding algorithm](http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#application/x-www-form-urlencoded-encoding-algorithm) +* [What every web developer must know about URL encoding](http://blog.lunatech.com/2009/02/03/what-every-web-developer-must-know-about-url-encoding) + +Informal stuff + +* [Parsing URLs for Fun and Profit](http://tools.ietf.org/html/draft-abarth-url-01) +* [Naming URL components](http://tantek.com/2011/238/b1/many-ways-slice-url-name-pieces) + +How other environments do things + +* [Java URI Class](http://docs.oracle.com/javase/7/docs/api/java/net/URI.html) +* [Java Inet6Address Class](http://docs.oracle.com/javase/1.5.0/docs/api/java/net/Inet6Address.html) +* [Node.js URL API](http://nodejs.org/docs/latest/api/url.html) + +[Discussion on Hacker News](https://news.ycombinator.com/item?id=3398837) + +### Forks / Code-borrow ### + +* [node-dom-urls](https://github.com/passy/node-dom-urls) passy's partial implementation of the W3C URL Spec Draft for Node +* [urlutils](https://github.com/cofounders/urlutils) cofounders' `window.URL` constructor for Node + +### Alternatives ### + +If you don't like URI.js, you may like one of the following libraries. (If yours is not listed, drop me a line…) + +#### Polyfill #### + +* [DOM-URL-Polyfill](https://github.com/arv/DOM-URL-Polyfill/) arv's polyfill of the [DOM URL spec](https://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#interface-urlutils) for browsers +* [inexorabletash](https://github.com/inexorabletash/polyfill/#whatwg-url-api) inexorabletash's [WHATWG URL API](http://url.spec.whatwg.org/) + +#### URL Manipulation #### + +* [The simple URL Mutation "Hack"](http://jsfiddle.net/rodneyrehm/KkGUJ/) ([jsPerf comparison](http://jsperf.com/idl-attributes-vs-uri-js)) +* [URL.js](https://github.com/ericf/urljs) +* [furl (Python)](https://github.com/gruns/furl) +* [mediawiki Uri](https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/resources/mediawiki/mediawiki.Uri.js?view=markup) (needs mw and jQuery) +* [jurlp](https://github.com/tombonner/jurlp) +* [jsUri](https://github.com/derek-watson/jsUri) + +#### URL Parsers #### + +* [The simple URL Mutation "Hack"](http://jsfiddle.net/rodneyrehm/KkGUJ/) ([jsPerf comparison](http://jsperf.com/idl-attributes-vs-uri-js)) +* [URI Parser](http://blog.stevenlevithan.com/archives/parseuri) +* [jQuery-URL-Parser](https://github.com/allmarkedup/jQuery-URL-Parser) +* [Google Closure Uri](https://google.github.io/closure-library/api/class_goog_Uri.html) +* [URI.js by Gary Court](https://github.com/garycourt/uri-js) + +#### URI Template #### + +* [uri-template](https://github.com/rezigned/uri-template.js) (supporting extraction as well) by Rezigne +* [uri-templates](https://github.com/geraintluff/uri-templates) (supporting extraction as well) by Geraint Luff +* [uri-templates](https://github.com/marc-portier/uri-templates) by Marc Portier +* [uri-templates](https://github.com/geraintluff/uri-templates) by Geraint Luff (including reverse operation) +* [URI Template JS](https://github.com/fxa/uritemplate-js) by Franz Antesberger +* [Temple](https://github.com/brettstimmerman/temple) by Brett Stimmerman +* ([jsperf comparison](http://jsperf.com/uri-templates/2)) + +#### Various #### + +* [TLD.js](https://github.com/oncletom/tld.js) - second level domain names +* [Public Suffix](http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1) - second level domain names +* [uri-collection](https://github.com/scivey/uri-collection) - underscore based utility for working with many URIs + +## Authors ## + +* [Rodney Rehm](https://github.com/rodneyrehm) +* [Various Contributors](https://github.com/medialize/URI.js/graphs/contributors) + + +## Contains Code From ## + +* [punycode.js](http://mths.be/punycode) - Mathias Bynens +* [IPv6.js](http://intermapper.com/support/tools/IPV6-Validator.aspx) - Rich Brown - (rewrite of the original) + + +## License ## + +URI.js is published under the [MIT license](http://www.opensource.org/licenses/mit-license). Until version 1.13.2 URI.js was also published under the [GPL v3](http://opensource.org/licenses/GPL-3.0) license - but as this dual-licensing causes more questions than helps anyone, it was dropped with version 1.14.0. + + +## Changelog ## + +moved to [Changelog](./CHANGELOG.md) diff --git a/node_modules/urijs/package.json b/node_modules/urijs/package.json new file mode 100644 index 000000000..ec9b1638a --- /dev/null +++ b/node_modules/urijs/package.json @@ -0,0 +1,73 @@ +{ + "name": "urijs", + "version": "1.19.11", + "title": "URI.js - Mutating URLs", + "author": { + "name": "Rodney Rehm", + "url": "http://rodneyrehm.de" + }, + "repository": { + "type": "git", + "url": "https://github.com/medialize/URI.js.git" + }, + "license": "MIT", + "description": "URI.js is a Javascript library for working with URLs.", + "keywords": [ + "uri", + "url", + "urn", + "uri mutation", + "url mutation", + "uri manipulation", + "url manipulation", + "uri template", + "url template", + "unified resource locator", + "unified resource identifier", + "query string", + "RFC 3986", + "RFC3986", + "RFC 6570", + "RFC6570", + "jquery-plugin", + "ecosystem:jquery" + ], + "categories": [ + "Parsers & Compilers", + "Utilities" + ], + "main": "./src/URI", + "homepage": "http://medialize.github.io/URI.js/", + "contributors": [ + "Francois-Guillaume Ribreau (http://fgribreau.com)", + "Justin Chase (http://justinmchase.com)" + ], + "files": [ + "src/URI.js", + "src/IPv6.js", + "src/SecondLevelDomains.js", + "src/punycode.js", + "src/URITemplate.js", + "src/jquery.URI.js", + "src/URI.min.js", + "src/jquery.URI.min.js", + "src/URI.fragmentQuery.js", + "src/URI.fragmentURI.js", + "LICENSE.txt" + ], + "npmName": "urijs", + "npmFileMap": [ + { + "basePath": "/src/", + "files": [ + "*.js" + ] + }, + { + "basePath": "/", + "files": [ + "LICENSE.txt" + ] + } + ] +} diff --git a/node_modules/urijs/src/IPv6.js b/node_modules/urijs/src/IPv6.js new file mode 100644 index 000000000..af4fc0796 --- /dev/null +++ b/node_modules/urijs/src/IPv6.js @@ -0,0 +1,185 @@ +/*! + * URI.js - Mutating URLs + * IPv6 Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if (typeof module === 'object' && module.exports) { + // Node + module.exports = factory(); + } else if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory); + } else { + // Browser globals (root is window) + root.IPv6 = factory(root); + } +}(this, function (root) { + 'use strict'; + + /* + var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156"; + var _out = IPv6.best(_in); + var _expected = "fe80::204:61ff:fe9d:f156"; + + console.log(_in, _out, _expected, _out === _expected); + */ + + // save current IPv6 variable, if any + var _IPv6 = root && root.IPv6; + + function bestPresentation(address) { + // based on: + // Javascript to test an IPv6 address for proper format, and to + // present the "best text representation" according to IETF Draft RFC at + // http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04 + // 8 Feb 2010 Rich Brown, Dartware, LLC + // Please feel free to use this code as long as you provide a link to + // http://www.intermapper.com + // http://intermapper.com/support/tools/IPV6-Validator.aspx + // http://download.dartware.com/thirdparty/ipv6validator.js + + var _address = address.toLowerCase(); + var segments = _address.split(':'); + var length = segments.length; + var total = 8; + + // trim colons (:: or ::a:b:c… or …a:b:c::) + if (segments[0] === '' && segments[1] === '' && segments[2] === '') { + // must have been :: + // remove first two items + segments.shift(); + segments.shift(); + } else if (segments[0] === '' && segments[1] === '') { + // must have been ::xxxx + // remove the first item + segments.shift(); + } else if (segments[length - 1] === '' && segments[length - 2] === '') { + // must have been xxxx:: + segments.pop(); + } + + length = segments.length; + + // adjust total segments for IPv4 trailer + if (segments[length - 1].indexOf('.') !== -1) { + // found a "." which means IPv4 + total = 7; + } + + // fill empty segments them with "0000" + var pos; + for (pos = 0; pos < length; pos++) { + if (segments[pos] === '') { + break; + } + } + + if (pos < total) { + segments.splice(pos, 1, '0000'); + while (segments.length < total) { + segments.splice(pos, 0, '0000'); + } + } + + // strip leading zeros + var _segments; + for (var i = 0; i < total; i++) { + _segments = segments[i].split(''); + for (var j = 0; j < 3 ; j++) { + if (_segments[0] === '0' && _segments.length > 1) { + _segments.splice(0,1); + } else { + break; + } + } + + segments[i] = _segments.join(''); + } + + // find longest sequence of zeroes and coalesce them into one segment + var best = -1; + var _best = 0; + var _current = 0; + var current = -1; + var inzeroes = false; + // i; already declared + + for (i = 0; i < total; i++) { + if (inzeroes) { + if (segments[i] === '0') { + _current += 1; + } else { + inzeroes = false; + if (_current > _best) { + best = current; + _best = _current; + } + } + } else { + if (segments[i] === '0') { + inzeroes = true; + current = i; + _current = 1; + } + } + } + + if (_current > _best) { + best = current; + _best = _current; + } + + if (_best > 1) { + segments.splice(best, _best, ''); + } + + length = segments.length; + + // assemble remaining segments + var result = ''; + if (segments[0] === '') { + result = ':'; + } + + for (i = 0; i < length; i++) { + result += segments[i]; + if (i === length - 1) { + break; + } + + result += ':'; + } + + if (segments[length - 1] === '') { + result += ':'; + } + + return result; + } + + function noConflict() { + /*jshint validthis: true */ + if (root.IPv6 === this) { + root.IPv6 = _IPv6; + } + + return this; + } + + return { + best: bestPresentation, + noConflict: noConflict + }; +})); diff --git a/node_modules/urijs/src/SecondLevelDomains.js b/node_modules/urijs/src/SecondLevelDomains.js new file mode 100644 index 000000000..6cac8b8ff --- /dev/null +++ b/node_modules/urijs/src/SecondLevelDomains.js @@ -0,0 +1,245 @@ +/*! + * URI.js - Mutating URLs + * Second Level Domain (SLD) Support + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ + +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if (typeof module === 'object' && module.exports) { + // Node + module.exports = factory(); + } else if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory); + } else { + // Browser globals (root is window) + root.SecondLevelDomains = factory(root); + } +}(this, function (root) { + 'use strict'; + + // save current SecondLevelDomains variable, if any + var _SecondLevelDomains = root && root.SecondLevelDomains; + + var SLD = { + // list of known Second Level Domains + // converted list of SLDs from https://github.com/gavingmiller/second-level-domains + // ---- + // publicsuffix.org is more current and actually used by a couple of browsers internally. + // downside is it also contains domains like "dyndns.org" - which is fine for the security + // issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js + // ---- + list: { + 'ac':' com gov mil net org ', + 'ae':' ac co gov mil name net org pro sch ', + 'af':' com edu gov net org ', + 'al':' com edu gov mil net org ', + 'ao':' co ed gv it og pb ', + 'ar':' com edu gob gov int mil net org tur ', + 'at':' ac co gv or ', + 'au':' asn com csiro edu gov id net org ', + 'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ', + 'bb':' biz co com edu gov info net org store tv ', + 'bh':' biz cc com edu gov info net org ', + 'bn':' com edu gov net org ', + 'bo':' com edu gob gov int mil net org tv ', + 'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ', + 'bs':' com edu gov net org ', + 'bz':' du et om ov rg ', + 'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ', + 'ck':' biz co edu gen gov info net org ', + 'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ', + 'co':' com edu gov mil net nom org ', + 'cr':' ac c co ed fi go or sa ', + 'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ', + 'do':' art com edu gob gov mil net org sld web ', + 'dz':' art asso com edu gov net org pol ', + 'ec':' com edu fin gov info med mil net org pro ', + 'eg':' com edu eun gov mil name net org sci ', + 'er':' com edu gov ind mil net org rochest w ', + 'es':' com edu gob nom org ', + 'et':' biz com edu gov info name net org ', + 'fj':' ac biz com info mil name net org pro ', + 'fk':' ac co gov net nom org ', + 'fr':' asso com f gouv nom prd presse tm ', + 'gg':' co net org ', + 'gh':' com edu gov mil org ', + 'gn':' ac com gov net org ', + 'gr':' com edu gov mil net org ', + 'gt':' com edu gob ind mil net org ', + 'gu':' com edu gov net org ', + 'hk':' com edu gov idv net org ', + 'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ', + 'id':' ac co go mil net or sch web ', + 'il':' ac co gov idf k12 muni net org ', + 'in':' ac co edu ernet firm gen gov i ind mil net nic org res ', + 'iq':' com edu gov i mil net org ', + 'ir':' ac co dnssec gov i id net org sch ', + 'it':' edu gov ', + 'je':' co net org ', + 'jo':' com edu gov mil name net org sch ', + 'jp':' ac ad co ed go gr lg ne or ', + 'ke':' ac co go info me mobi ne or sc ', + 'kh':' com edu gov mil net org per ', + 'ki':' biz com de edu gov info mob net org tel ', + 'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ', + 'kn':' edu gov net org ', + 'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ', + 'kw':' com edu gov net org ', + 'ky':' com edu gov net org ', + 'kz':' com edu gov mil net org ', + 'lb':' com edu gov net org ', + 'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ', + 'lr':' com edu gov net org ', + 'lv':' asn com conf edu gov id mil net org ', + 'ly':' com edu gov id med net org plc sch ', + 'ma':' ac co gov m net org press ', + 'mc':' asso tm ', + 'me':' ac co edu gov its net org priv ', + 'mg':' com edu gov mil nom org prd tm ', + 'mk':' com edu gov inf name net org pro ', + 'ml':' com edu gov net org presse ', + 'mn':' edu gov org ', + 'mo':' com edu gov net org ', + 'mt':' com edu gov net org ', + 'mv':' aero biz com coop edu gov info int mil museum name net org pro ', + 'mw':' ac co com coop edu gov int museum net org ', + 'mx':' com edu gob net org ', + 'my':' com edu gov mil name net org sch ', + 'nf':' arts com firm info net other per rec store web ', + 'ng':' biz com edu gov mil mobi name net org sch ', + 'ni':' ac co com edu gob mil net nom org ', + 'np':' com edu gov mil net org ', + 'nr':' biz com edu gov info net org ', + 'om':' ac biz co com edu gov med mil museum net org pro sch ', + 'pe':' com edu gob mil net nom org sld ', + 'ph':' com edu gov i mil net ngo org ', + 'pk':' biz com edu fam gob gok gon gop gos gov net org web ', + 'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ', + 'pr':' ac biz com edu est gov info isla name net org pro prof ', + 'ps':' com edu gov net org plo sec ', + 'pw':' belau co ed go ne or ', + 'ro':' arts com firm info nom nt org rec store tm www ', + 'rs':' ac co edu gov in org ', + 'sb':' com edu gov net org ', + 'sc':' com edu gov net org ', + 'sh':' co com edu gov net nom org ', + 'sl':' com edu gov net org ', + 'st':' co com consulado edu embaixada gov mil net org principe saotome store ', + 'sv':' com edu gob org red ', + 'sz':' ac co org ', + 'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ', + 'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ', + 'tw':' club com ebiz edu game gov idv mil net org ', + 'mu':' ac co com gov net or org ', + 'mz':' ac co edu gov org ', + 'na':' co com ', + 'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ', + 'pa':' abo ac com edu gob ing med net nom org sld ', + 'pt':' com edu gov int net nome org publ ', + 'py':' com edu gov mil net org ', + 'qa':' com edu gov mil net org ', + 're':' asso com nom ', + 'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ', + 'rw':' ac co com edu gouv gov int mil net ', + 'sa':' com edu gov med net org pub sch ', + 'sd':' com edu gov info med net org tv ', + 'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ', + 'sg':' com edu gov idn net org per ', + 'sn':' art com edu gouv org perso univ ', + 'sy':' com edu gov mil net news org ', + 'th':' ac co go in mi net or ', + 'tj':' ac biz co com edu go gov info int mil name net nic org test web ', + 'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ', + 'tz':' ac co go ne or ', + 'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ', + 'ug':' ac co go ne or org sc ', + 'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ', + 'us':' dni fed isa kids nsn ', + 'uy':' com edu gub mil net org ', + 've':' co com edu gob info mil net org web ', + 'vi':' co com k12 net org ', + 'vn':' ac biz com edu gov health info int name net org pro ', + 'ye':' co com gov ltd me net org plc ', + 'yu':' ac co edu gov org ', + 'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ', + 'zm':' ac co com edu gov net org sch ', + // https://en.wikipedia.org/wiki/CentralNic#Second-level_domains + 'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ', + 'net': 'gb jp se uk ', + 'org': 'ae', + 'de': 'com ' + }, + // gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost + // in both performance and memory footprint. No initialization required. + // http://jsperf.com/uri-js-sld-regex-vs-binary-search/4 + // Following methods use lastIndexOf() rather than array.split() in order + // to avoid any memory allocations. + has: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return false; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) { + return false; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return false; + } + return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0; + }, + is: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return false; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset >= 0) { + return false; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return false; + } + return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0; + }, + get: function(domain) { + var tldOffset = domain.lastIndexOf('.'); + if (tldOffset <= 0 || tldOffset >= (domain.length-1)) { + return null; + } + var sldOffset = domain.lastIndexOf('.', tldOffset-1); + if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) { + return null; + } + var sldList = SLD.list[domain.slice(tldOffset+1)]; + if (!sldList) { + return null; + } + if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) { + return null; + } + return domain.slice(sldOffset+1); + }, + noConflict: function(){ + if (root.SecondLevelDomains === this) { + root.SecondLevelDomains = _SecondLevelDomains; + } + return this; + } + }; + + return SLD; +})); diff --git a/node_modules/urijs/src/URI.fragmentQuery.js b/node_modules/urijs/src/URI.fragmentQuery.js new file mode 100644 index 000000000..1b8391c88 --- /dev/null +++ b/node_modules/urijs/src/URI.fragmentQuery.js @@ -0,0 +1,121 @@ +/* + * Extending URI.js for fragment abuse + */ + +// -------------------------------------------------------------------------------- +// EXAMPLE: storing application/x-www-form-urlencoded data in the fragment +// possibly helpful for Google's hashbangs +// see http://code.google.com/web/ajaxcrawling/ +// -------------------------------------------------------------------------------- + +// Note: make sure this is the last file loaded! + +// USAGE: +// var uri = URI("http://example.org/#?foo=bar"); +// uri.fragment(true) === {foo: "bar"}; +// uri.fragment({bar: "foo"}); +// uri.toString() === "http://example.org/#?bar=foo"; +// uri.addFragment("name", "value"); +// uri.toString() === "http://example.org/#?bar=foo&name=value"; +// uri.removeFragment("name"); +// uri.toString() === "http://example.org/#?bar=foo"; +// uri.setFragment("name", "value1"); +// uri.toString() === "http://example.org/#?bar=foo&name=value1"; +// uri.setFragment("name", "value2"); +// uri.toString() === "http://example.org/#?bar=foo&name=value2"; + +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if (typeof module === 'object' && module.exports) { + // Node + module.exports = factory(require('./URI')); + } else if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['./URI'], factory); + } else { + // Browser globals (root is window) + factory(root.URI); + } +}(this, function (URI) { + 'use strict'; + + var p = URI.prototype; + // old fragment handler we need to wrap + var f = p.fragment; + + // make fragmentPrefix configurable + URI.fragmentPrefix = '?'; + var _parts = URI._parts; + URI._parts = function() { + var parts = _parts(); + parts.fragmentPrefix = URI.fragmentPrefix; + return parts; + }; + p.fragmentPrefix = function(v) { + this._parts.fragmentPrefix = v; + return this; + }; + + // add fragment(true) and fragment({key: value}) signatures + p.fragment = function(v, build) { + var prefix = this._parts.fragmentPrefix; + var fragment = this._parts.fragment || ''; + + if (v === true) { + if (fragment.substring(0, prefix.length) !== prefix) { + return {}; + } + + return URI.parseQuery(fragment.substring(prefix.length)); + } else if (v !== undefined && typeof v !== 'string') { + this._parts.fragment = prefix + URI.buildQuery(v); + this.build(!build); + return this; + } else { + return f.call(this, v, build); + } + }; + p.addFragment = function(name, value, build) { + var prefix = this._parts.fragmentPrefix; + var data = URI.parseQuery((this._parts.fragment || '').substring(prefix.length)); + URI.addQuery(data, name, value); + this._parts.fragment = prefix + URI.buildQuery(data); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.removeFragment = function(name, value, build) { + var prefix = this._parts.fragmentPrefix; + var data = URI.parseQuery((this._parts.fragment || '').substring(prefix.length)); + URI.removeQuery(data, name, value); + this._parts.fragment = prefix + URI.buildQuery(data); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.setFragment = function(name, value, build) { + var prefix = this._parts.fragmentPrefix; + var data = URI.parseQuery((this._parts.fragment || '').substring(prefix.length)); + URI.setQuery(data, name, value); + this._parts.fragment = prefix + URI.buildQuery(data); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.addHash = p.addFragment; + p.removeHash = p.removeFragment; + p.setHash = p.setFragment; + + // extending existing object rather than defining something new + return URI; +})); diff --git a/node_modules/urijs/src/URI.fragmentURI.js b/node_modules/urijs/src/URI.fragmentURI.js new file mode 100644 index 000000000..86d990218 --- /dev/null +++ b/node_modules/urijs/src/URI.fragmentURI.js @@ -0,0 +1,97 @@ +/* + * Extending URI.js for fragment abuse + */ + +// -------------------------------------------------------------------------------- +// EXAMPLE: storing a relative URL in the fragment ("FragmentURI") +// possibly helpful when working with backbone.js or sammy.js +// inspired by https://github.com/medialize/URI.js/pull/2 +// -------------------------------------------------------------------------------- + +// Note: make sure this is the last file loaded! + +// USAGE: +// var uri = URI("http://example.org/#!/foo/bar/baz.html"); +// var furi = uri.fragment(true); +// furi.pathname() === '/foo/bar/baz.html'; +// furi.pathname('/hello.html'); +// uri.toString() === "http://example.org/#!/hello.html" + +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if (typeof module === 'object' && module.exports) { + // Node + module.exports = factory(require('./URI')); + } else if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['./URI'], factory); + } else { + // Browser globals (root is window) + factory(root.URI); + } +}(this, function (URI) { + 'use strict'; + + var p = URI.prototype; + // old handlers we need to wrap + var f = p.fragment; + var b = p.build; + + // make fragmentPrefix configurable + URI.fragmentPrefix = '!'; + var _parts = URI._parts; + URI._parts = function() { + var parts = _parts(); + parts.fragmentPrefix = URI.fragmentPrefix; + return parts; + }; + p.fragmentPrefix = function(v) { + this._parts.fragmentPrefix = v; + return this; + }; + + // add fragment(true) and fragment(URI) signatures + p.fragment = function(v, build) { + var prefix = this._parts.fragmentPrefix; + var fragment = this._parts.fragment || ''; + var furi; + + if (v === true) { + if (fragment.substring(0, prefix.length) !== prefix) { + furi = URI(''); + } else { + furi = new URI(fragment.substring(prefix.length)); + } + + this._fragmentURI = furi; + furi._parentURI = this; + return furi; + } else if (v !== undefined && typeof v !== 'string') { + this._fragmentURI = v; + v._parentURI = v; + this._parts.fragment = prefix + v.toString(); + this.build(!build); + return this; + } else if (typeof v === 'string') { + this._fragmentURI = undefined; + } + + return f.call(this, v, build); + }; + + // make .build() of the actual URI aware of the FragmentURI + p.build = function(deferBuild) { + var t = b.call(this, deferBuild); + + if (deferBuild !== false && this._parentURI) { + // update the parent + this._parentURI.fragment(this); + } + + return t; + }; + + // extending existing object rather than defining something new + return URI; +})); \ No newline at end of file diff --git a/node_modules/urijs/src/URI.js b/node_modules/urijs/src/URI.js new file mode 100644 index 000000000..795b853a0 --- /dev/null +++ b/node_modules/urijs/src/URI.js @@ -0,0 +1,2364 @@ +/*! + * URI.js - Mutating URLs + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/ + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if (typeof module === 'object' && module.exports) { + // Node + module.exports = factory(require('./punycode'), require('./IPv6'), require('./SecondLevelDomains')); + } else if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['./punycode', './IPv6', './SecondLevelDomains'], factory); + } else { + // Browser globals (root is window) + root.URI = factory(root.punycode, root.IPv6, root.SecondLevelDomains, root); + } +}(this, function (punycode, IPv6, SLD, root) { + 'use strict'; + /*global location, escape, unescape */ + // FIXME: v2.0.0 renamce non-camelCase properties to uppercase + /*jshint camelcase: false */ + + // save current URI variable, if any + var _URI = root && root.URI; + + function URI(url, base) { + var _urlSupplied = arguments.length >= 1; + var _baseSupplied = arguments.length >= 2; + + // Allow instantiation without the 'new' keyword + if (!(this instanceof URI)) { + if (_urlSupplied) { + if (_baseSupplied) { + return new URI(url, base); + } + + return new URI(url); + } + + return new URI(); + } + + if (url === undefined) { + if (_urlSupplied) { + throw new TypeError('undefined is not a valid argument for URI'); + } + + if (typeof location !== 'undefined') { + url = location.href + ''; + } else { + url = ''; + } + } + + if (url === null) { + if (_urlSupplied) { + throw new TypeError('null is not a valid argument for URI'); + } + } + + this.href(url); + + // resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor + if (base !== undefined) { + return this.absoluteTo(base); + } + + return this; + } + + function isInteger(value) { + return /^[0-9]+$/.test(value); + } + + URI.version = '1.19.11'; + + var p = URI.prototype; + var hasOwn = Object.prototype.hasOwnProperty; + + function escapeRegEx(string) { + // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963 + return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); + } + + function getType(value) { + // IE8 doesn't return [Object Undefined] but [Object Object] for undefined value + if (value === undefined) { + return 'Undefined'; + } + + return String(Object.prototype.toString.call(value)).slice(8, -1); + } + + function isArray(obj) { + return getType(obj) === 'Array'; + } + + function filterArrayValues(data, value) { + var lookup = {}; + var i, length; + + if (getType(value) === 'RegExp') { + lookup = null; + } else if (isArray(value)) { + for (i = 0, length = value.length; i < length; i++) { + lookup[value[i]] = true; + } + } else { + lookup[value] = true; + } + + for (i = 0, length = data.length; i < length; i++) { + /*jshint laxbreak: true */ + var _match = lookup && lookup[data[i]] !== undefined + || !lookup && value.test(data[i]); + /*jshint laxbreak: false */ + if (_match) { + data.splice(i, 1); + length--; + i--; + } + } + + return data; + } + + function arrayContains(list, value) { + var i, length; + + // value may be string, number, array, regexp + if (isArray(value)) { + // Note: this can be optimized to O(n) (instead of current O(m * n)) + for (i = 0, length = value.length; i < length; i++) { + if (!arrayContains(list, value[i])) { + return false; + } + } + + return true; + } + + var _type = getType(value); + for (i = 0, length = list.length; i < length; i++) { + if (_type === 'RegExp') { + if (typeof list[i] === 'string' && list[i].match(value)) { + return true; + } + } else if (list[i] === value) { + return true; + } + } + + return false; + } + + function arraysEqual(one, two) { + if (!isArray(one) || !isArray(two)) { + return false; + } + + // arrays can't be equal if they have different amount of content + if (one.length !== two.length) { + return false; + } + + one.sort(); + two.sort(); + + for (var i = 0, l = one.length; i < l; i++) { + if (one[i] !== two[i]) { + return false; + } + } + + return true; + } + + function trimSlashes(text) { + var trim_expression = /^\/+|\/+$/g; + return text.replace(trim_expression, ''); + } + + URI._parts = function() { + return { + protocol: null, + username: null, + password: null, + hostname: null, + urn: null, + port: null, + path: null, + query: null, + fragment: null, + // state + preventInvalidHostname: URI.preventInvalidHostname, + duplicateQueryParameters: URI.duplicateQueryParameters, + escapeQuerySpace: URI.escapeQuerySpace + }; + }; + // state: throw on invalid hostname + // see https://github.com/medialize/URI.js/pull/345 + // and https://github.com/medialize/URI.js/issues/354 + URI.preventInvalidHostname = false; + // state: allow duplicate query parameters (a=1&a=1) + URI.duplicateQueryParameters = false; + // state: replaces + with %20 (space in query strings) + URI.escapeQuerySpace = true; + // static properties + URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i; + URI.idn_expression = /[^a-z0-9\._-]/i; + URI.punycode_expression = /(xn--)/i; + // well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care? + URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; + // credits to Rich Brown + // source: http://forums.intermapper.com/viewtopic.php?p=1096#1096 + // specification: http://www.ietf.org/rfc/rfc4291.txt + URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/; + // expression used is "gruber revised" (@gruber v2) determined to be the + // best solution in a regex-golf we did a couple of ages ago at + // * http://mathiasbynens.be/demo/url-regex + // * http://rodneyrehm.de/t/url-regex.html + URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig; + URI.findUri = { + // valid "scheme://" or "www." + start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi, + // everything up to the next whitespace + end: /[\s\r\n]|$/, + // trim trailing punctuation captured by end RegExp + trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/, + // balanced parens inclusion (), [], {}, <> + parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g, + }; + URI.leading_whitespace_expression = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/ + // https://infra.spec.whatwg.org/#ascii-tab-or-newline + URI.ascii_tab_whitespace = /[\u0009\u000A\u000D]+/g + // http://www.iana.org/assignments/uri-schemes.html + // http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports + URI.defaultPorts = { + http: '80', + https: '443', + ftp: '21', + gopher: '70', + ws: '80', + wss: '443' + }; + // list of protocols which always require a hostname + URI.hostProtocols = [ + 'http', + 'https' + ]; + + // allowed hostname characters according to RFC 3986 + // ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded + // I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _ + URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/; + // map DOM Elements to their URI attribute + URI.domAttributes = { + 'a': 'href', + 'blockquote': 'cite', + 'link': 'href', + 'base': 'href', + 'script': 'src', + 'form': 'action', + 'img': 'src', + 'area': 'href', + 'iframe': 'src', + 'embed': 'src', + 'source': 'src', + 'track': 'src', + 'input': 'src', // but only if type="image" + 'audio': 'src', + 'video': 'src' + }; + URI.getDomAttribute = function(node) { + if (!node || !node.nodeName) { + return undefined; + } + + var nodeName = node.nodeName.toLowerCase(); + // should only expose src for type="image" + if (nodeName === 'input' && node.type !== 'image') { + return undefined; + } + + return URI.domAttributes[nodeName]; + }; + + function escapeForDumbFirefox36(value) { + // https://github.com/medialize/URI.js/issues/91 + return escape(value); + } + + // encoding / decoding according to RFC3986 + function strictEncodeURIComponent(string) { + // see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent + return encodeURIComponent(string) + .replace(/[!'()*]/g, escapeForDumbFirefox36) + .replace(/\*/g, '%2A'); + } + URI.encode = strictEncodeURIComponent; + URI.decode = decodeURIComponent; + URI.iso8859 = function() { + URI.encode = escape; + URI.decode = unescape; + }; + URI.unicode = function() { + URI.encode = strictEncodeURIComponent; + URI.decode = decodeURIComponent; + }; + URI.characters = { + pathname: { + encode: { + // RFC3986 2.1: For consistency, URI producers and normalizers should + // use uppercase hexadecimal digits for all percent-encodings. + expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig, + map: { + // -._~!'()* + '%24': '$', + '%26': '&', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=', + '%3A': ':', + '%40': '@' + } + }, + decode: { + expression: /[\/\?#]/g, + map: { + '/': '%2F', + '?': '%3F', + '#': '%23' + } + } + }, + reserved: { + encode: { + // RFC3986 2.1: For consistency, URI producers and normalizers should + // use uppercase hexadecimal digits for all percent-encodings. + expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig, + map: { + // gen-delims + '%3A': ':', + '%2F': '/', + '%3F': '?', + '%23': '#', + '%5B': '[', + '%5D': ']', + '%40': '@', + // sub-delims + '%21': '!', + '%24': '$', + '%26': '&', + '%27': '\'', + '%28': '(', + '%29': ')', + '%2A': '*', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=' + } + } + }, + urnpath: { + // The characters under `encode` are the characters called out by RFC 2141 as being acceptable + // for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but + // these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also + // note that the colon character is not featured in the encoding map; this is because URI.js + // gives the colons in URNs semantic meaning as the delimiters of path segements, and so it + // should not appear unencoded in a segment itself. + // See also the note above about RFC3986 and capitalalized hex digits. + encode: { + expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig, + map: { + '%21': '!', + '%24': '$', + '%27': '\'', + '%28': '(', + '%29': ')', + '%2A': '*', + '%2B': '+', + '%2C': ',', + '%3B': ';', + '%3D': '=', + '%40': '@' + } + }, + // These characters are the characters called out by RFC2141 as "reserved" characters that + // should never appear in a URN, plus the colon character (see note above). + decode: { + expression: /[\/\?#:]/g, + map: { + '/': '%2F', + '?': '%3F', + '#': '%23', + ':': '%3A' + } + } + } + }; + URI.encodeQuery = function(string, escapeQuerySpace) { + var escaped = URI.encode(string + ''); + if (escapeQuerySpace === undefined) { + escapeQuerySpace = URI.escapeQuerySpace; + } + + return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped; + }; + URI.decodeQuery = function(string, escapeQuerySpace) { + string += ''; + if (escapeQuerySpace === undefined) { + escapeQuerySpace = URI.escapeQuerySpace; + } + + try { + return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string); + } catch(e) { + // we're not going to mess with weird encodings, + // give up and return the undecoded original string + // see https://github.com/medialize/URI.js/issues/87 + // see https://github.com/medialize/URI.js/issues/92 + return string; + } + }; + // generate encode/decode path functions + var _parts = {'encode':'encode', 'decode':'decode'}; + var _part; + var generateAccessor = function(_group, _part) { + return function(string) { + try { + return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) { + return URI.characters[_group][_part].map[c]; + }); + } catch (e) { + // we're not going to mess with weird encodings, + // give up and return the undecoded original string + // see https://github.com/medialize/URI.js/issues/87 + // see https://github.com/medialize/URI.js/issues/92 + return string; + } + }; + }; + + for (_part in _parts) { + URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]); + URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]); + } + + var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) { + return function(string) { + // Why pass in names of functions, rather than the function objects themselves? The + // definitions of some functions (but in particular, URI.decode) will occasionally change due + // to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure + // that the functions we use here are "fresh". + var actualCodingFunc; + if (!_innerCodingFuncName) { + actualCodingFunc = URI[_codingFuncName]; + } else { + actualCodingFunc = function(string) { + return URI[_codingFuncName](URI[_innerCodingFuncName](string)); + }; + } + + var segments = (string + '').split(_sep); + + for (var i = 0, length = segments.length; i < length; i++) { + segments[i] = actualCodingFunc(segments[i]); + } + + return segments.join(_sep); + }; + }; + + // This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions. + URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment'); + URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment'); + URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode'); + URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode'); + + URI.encodeReserved = generateAccessor('reserved', 'encode'); + + URI.parse = function(string, parts) { + var pos; + if (!parts) { + parts = { + preventInvalidHostname: URI.preventInvalidHostname + }; + } + + string = string.replace(URI.leading_whitespace_expression, '') + // https://infra.spec.whatwg.org/#ascii-tab-or-newline + string = string.replace(URI.ascii_tab_whitespace, '') + + // [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment] + + // extract fragment + pos = string.indexOf('#'); + if (pos > -1) { + // escaping? + parts.fragment = string.substring(pos + 1) || null; + string = string.substring(0, pos); + } + + // extract query + pos = string.indexOf('?'); + if (pos > -1) { + // escaping? + parts.query = string.substring(pos + 1) || null; + string = string.substring(0, pos); + } + + // slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws) + string = string.replace(/^(https?|ftp|wss?)?:+[/\\]*/i, '$1://'); + // slashes and backslashes have lost all meaning for scheme relative URLs + string = string.replace(/^[/\\]{2,}/i, '//'); + + // extract protocol + if (string.substring(0, 2) === '//') { + // relative-scheme + parts.protocol = null; + string = string.substring(2); + // extract "user:pass@host:port" + string = URI.parseAuthority(string, parts); + } else { + pos = string.indexOf(':'); + if (pos > -1) { + parts.protocol = string.substring(0, pos) || null; + if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) { + // : may be within the path + parts.protocol = undefined; + } else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') { + string = string.substring(pos + 3); + + // extract "user:pass@host:port" + string = URI.parseAuthority(string, parts); + } else { + string = string.substring(pos + 1); + parts.urn = true; + } + } + } + + // what's left must be the path + parts.path = string; + + // and we're done + return parts; + }; + URI.parseHost = function(string, parts) { + if (!string) { + string = ''; + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124 + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + // https://github.com/medialize/URI.js/pull/233 + string = string.replace(/\\/g, '/'); + + // extract host:port + var pos = string.indexOf('/'); + var bracketPos; + var t; + + if (pos === -1) { + pos = string.length; + } + + if (string.charAt(0) === '[') { + // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6 + // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts + // IPv6+port in the format [2001:db8::1]:80 (for the time being) + bracketPos = string.indexOf(']'); + parts.hostname = string.substring(1, bracketPos) || null; + parts.port = string.substring(bracketPos + 2, pos) || null; + if (parts.port === '/') { + parts.port = null; + } + } else { + var firstColon = string.indexOf(':'); + var firstSlash = string.indexOf('/'); + var nextColon = string.indexOf(':', firstColon + 1); + if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) { + // IPv6 host contains multiple colons - but no port + // this notation is actually not allowed by RFC 3986, but we're a liberal parser + parts.hostname = string.substring(0, pos) || null; + parts.port = null; + } else { + t = string.substring(0, pos).split(':'); + parts.hostname = t[0] || null; + parts.port = t[1] || null; + } + } + + if (parts.hostname && string.substring(pos).charAt(0) !== '/') { + pos++; + string = '/' + string; + } + + if (parts.preventInvalidHostname) { + URI.ensureValidHostname(parts.hostname, parts.protocol); + } + + if (parts.port) { + URI.ensureValidPort(parts.port); + } + + return string.substring(pos) || '/'; + }; + URI.parseAuthority = function(string, parts) { + string = URI.parseUserinfo(string, parts); + return URI.parseHost(string, parts); + }; + URI.parseUserinfo = function(string, parts) { + // extract username:password + var _string = string + var firstBackSlash = string.indexOf('\\'); + if (firstBackSlash !== -1) { + string = string.replace(/\\/g, '/') + } + var firstSlash = string.indexOf('/'); + var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1); + var t; + + // authority@ must come before /path or \path + if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) { + t = string.substring(0, pos).split(':'); + parts.username = t[0] ? URI.decode(t[0]) : null; + t.shift(); + parts.password = t[0] ? URI.decode(t.join(':')) : null; + string = _string.substring(pos + 1); + } else { + parts.username = null; + parts.password = null; + } + + return string; + }; + URI.parseQuery = function(string, escapeQuerySpace) { + if (!string) { + return {}; + } + + // throw out the funky business - "?"[name"="value"&"]+ + string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, ''); + + if (!string) { + return {}; + } + + var items = {}; + var splits = string.split('&'); + var length = splits.length; + var v, name, value; + + for (var i = 0; i < length; i++) { + v = splits[i].split('='); + name = URI.decodeQuery(v.shift(), escapeQuerySpace); + // no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters + value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null; + + if (name === '__proto__') { + // ignore attempt at exploiting JavaScript internals + continue; + } else if (hasOwn.call(items, name)) { + if (typeof items[name] === 'string' || items[name] === null) { + items[name] = [items[name]]; + } + + items[name].push(value); + } else { + items[name] = value; + } + } + + return items; + }; + + URI.build = function(parts) { + var t = ''; + var requireAbsolutePath = false + + if (parts.protocol) { + t += parts.protocol + ':'; + } + + if (!parts.urn && (t || parts.hostname)) { + t += '//'; + requireAbsolutePath = true + } + + t += (URI.buildAuthority(parts) || ''); + + if (typeof parts.path === 'string') { + if (parts.path.charAt(0) !== '/' && requireAbsolutePath) { + t += '/'; + } + + t += parts.path; + } + + if (typeof parts.query === 'string' && parts.query) { + t += '?' + parts.query; + } + + if (typeof parts.fragment === 'string' && parts.fragment) { + t += '#' + parts.fragment; + } + return t; + }; + URI.buildHost = function(parts) { + var t = ''; + + if (!parts.hostname) { + return ''; + } else if (URI.ip6_expression.test(parts.hostname)) { + t += '[' + parts.hostname + ']'; + } else { + t += parts.hostname; + } + + if (parts.port) { + t += ':' + parts.port; + } + + return t; + }; + URI.buildAuthority = function(parts) { + return URI.buildUserinfo(parts) + URI.buildHost(parts); + }; + URI.buildUserinfo = function(parts) { + var t = ''; + + if (parts.username) { + t += URI.encode(parts.username); + } + + if (parts.password) { + t += ':' + URI.encode(parts.password); + } + + if (t) { + t += '@'; + } + + return t; + }; + URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) { + // according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html + // being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed + // the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax! + // URI.js treats the query string as being application/x-www-form-urlencoded + // see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type + + var t = ''; + var unique, key, i, length; + for (key in data) { + if (key === '__proto__') { + // ignore attempt at exploiting JavaScript internals + continue; + } else if (hasOwn.call(data, key)) { + if (isArray(data[key])) { + unique = {}; + for (i = 0, length = data[key].length; i < length; i++) { + if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) { + t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace); + if (duplicateQueryParameters !== true) { + unique[data[key][i] + ''] = true; + } + } + } + } else if (data[key] !== undefined) { + t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace); + } + } + } + + return t.substring(1); + }; + URI.buildQueryParameter = function(name, value, escapeQuerySpace) { + // http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded + // don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization + return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : ''); + }; + + URI.addQuery = function(data, name, value) { + if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + URI.addQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + if (data[name] === undefined) { + data[name] = value; + return; + } else if (typeof data[name] === 'string') { + data[name] = [data[name]]; + } + + if (!isArray(value)) { + value = [value]; + } + + data[name] = (data[name] || []).concat(value); + } else { + throw new TypeError('URI.addQuery() accepts an object, string as the name parameter'); + } + }; + + URI.setQuery = function(data, name, value) { + if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + URI.setQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + data[name] = value === undefined ? null : value; + } else { + throw new TypeError('URI.setQuery() accepts an object, string as the name parameter'); + } + }; + + URI.removeQuery = function(data, name, value) { + var i, length, key; + + if (isArray(name)) { + for (i = 0, length = name.length; i < length; i++) { + data[name[i]] = undefined; + } + } else if (getType(name) === 'RegExp') { + for (key in data) { + if (name.test(key)) { + data[key] = undefined; + } + } + } else if (typeof name === 'object') { + for (key in name) { + if (hasOwn.call(name, key)) { + URI.removeQuery(data, key, name[key]); + } + } + } else if (typeof name === 'string') { + if (value !== undefined) { + if (getType(value) === 'RegExp') { + if (!isArray(data[name]) && value.test(data[name])) { + data[name] = undefined; + } else { + data[name] = filterArrayValues(data[name], value); + } + } else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) { + data[name] = undefined; + } else if (isArray(data[name])) { + data[name] = filterArrayValues(data[name], value); + } + } else { + data[name] = undefined; + } + } else { + throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter'); + } + }; + URI.hasQuery = function(data, name, value, withinArray) { + switch (getType(name)) { + case 'String': + // Nothing to do here + break; + + case 'RegExp': + for (var key in data) { + if (hasOwn.call(data, key)) { + if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) { + return true; + } + } + } + + return false; + + case 'Object': + for (var _key in name) { + if (hasOwn.call(name, _key)) { + if (!URI.hasQuery(data, _key, name[_key])) { + return false; + } + } + } + + return true; + + default: + throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter'); + } + + switch (getType(value)) { + case 'Undefined': + // true if exists (but may be empty) + return name in data; // data[name] !== undefined; + + case 'Boolean': + // true if exists and non-empty + var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]); + return value === _booly; + + case 'Function': + // allow complex comparison + return !!value(data[name], name, data); + + case 'Array': + if (!isArray(data[name])) { + return false; + } + + var op = withinArray ? arrayContains : arraysEqual; + return op(data[name], value); + + case 'RegExp': + if (!isArray(data[name])) { + return Boolean(data[name] && data[name].match(value)); + } + + if (!withinArray) { + return false; + } + + return arrayContains(data[name], value); + + case 'Number': + value = String(value); + /* falls through */ + case 'String': + if (!isArray(data[name])) { + return data[name] === value; + } + + if (!withinArray) { + return false; + } + + return arrayContains(data[name], value); + + default: + throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter'); + } + }; + + + URI.joinPaths = function() { + var input = []; + var segments = []; + var nonEmptySegments = 0; + + for (var i = 0; i < arguments.length; i++) { + var url = new URI(arguments[i]); + input.push(url); + var _segments = url.segment(); + for (var s = 0; s < _segments.length; s++) { + if (typeof _segments[s] === 'string') { + segments.push(_segments[s]); + } + + if (_segments[s]) { + nonEmptySegments++; + } + } + } + + if (!segments.length || !nonEmptySegments) { + return new URI(''); + } + + var uri = new URI('').segment(segments); + + if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') { + uri.path('/' + uri.path()); + } + + return uri.normalize(); + }; + + URI.commonPath = function(one, two) { + var length = Math.min(one.length, two.length); + var pos; + + // find first non-matching character + for (pos = 0; pos < length; pos++) { + if (one.charAt(pos) !== two.charAt(pos)) { + pos--; + break; + } + } + + if (pos < 1) { + return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : ''; + } + + // revert to last / + if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') { + pos = one.substring(0, pos).lastIndexOf('/'); + } + + return one.substring(0, pos + 1); + }; + + URI.withinString = function(string, callback, options) { + options || (options = {}); + var _start = options.start || URI.findUri.start; + var _end = options.end || URI.findUri.end; + var _trim = options.trim || URI.findUri.trim; + var _parens = options.parens || URI.findUri.parens; + var _attributeOpen = /[a-z0-9-]=["']?$/i; + + _start.lastIndex = 0; + while (true) { + var match = _start.exec(string); + if (!match) { + break; + } + + var start = match.index; + if (options.ignoreHtml) { + // attribut(e=["']?$) + var attributeOpen = string.slice(Math.max(start - 3, 0), start); + if (attributeOpen && _attributeOpen.test(attributeOpen)) { + continue; + } + } + + var end = start + string.slice(start).search(_end); + var slice = string.slice(start, end); + // make sure we include well balanced parens + var parensEnd = -1; + while (true) { + var parensMatch = _parens.exec(slice); + if (!parensMatch) { + break; + } + + var parensMatchEnd = parensMatch.index + parensMatch[0].length; + parensEnd = Math.max(parensEnd, parensMatchEnd); + } + + if (parensEnd > -1) { + slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, ''); + } else { + slice = slice.replace(_trim, ''); + } + + if (slice.length <= match[0].length) { + // the extract only contains the starting marker of a URI, + // e.g. "www" or "http://" + continue; + } + + if (options.ignore && options.ignore.test(slice)) { + continue; + } + + end = start + slice.length; + var result = callback(slice, start, end, string); + if (result === undefined) { + _start.lastIndex = end; + continue; + } + + result = String(result); + string = string.slice(0, start) + result + string.slice(end); + _start.lastIndex = start + result.length; + } + + _start.lastIndex = 0; + return string; + }; + + URI.ensureValidHostname = function(v, protocol) { + // Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986) + // they are not part of DNS and therefore ignored by URI.js + + var hasHostname = !!v; // not null and not an empty string + var hasProtocol = !!protocol; + var rejectEmptyHostname = false; + + if (hasProtocol) { + rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol); + } + + if (rejectEmptyHostname && !hasHostname) { + throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol); + } else if (v && v.match(URI.invalid_hostname_characters)) { + // test punycode + if (!punycode) { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available'); + } + if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]'); + } + } + }; + + URI.ensureValidPort = function (v) { + if (!v) { + return; + } + + var port = Number(v); + if (isInteger(port) && (port > 0) && (port < 65536)) { + return; + } + + throw new TypeError('Port "' + v + '" is not a valid port'); + }; + + // noConflict + URI.noConflict = function(removeAll) { + if (removeAll) { + var unconflicted = { + URI: this.noConflict() + }; + + if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') { + unconflicted.URITemplate = root.URITemplate.noConflict(); + } + + if (root.IPv6 && typeof root.IPv6.noConflict === 'function') { + unconflicted.IPv6 = root.IPv6.noConflict(); + } + + if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') { + unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict(); + } + + return unconflicted; + } else if (root.URI === this) { + root.URI = _URI; + } + + return this; + }; + + p.build = function(deferBuild) { + if (deferBuild === true) { + this._deferred_build = true; + } else if (deferBuild === undefined || this._deferred_build) { + this._string = URI.build(this._parts); + this._deferred_build = false; + } + + return this; + }; + + p.clone = function() { + return new URI(this); + }; + + p.valueOf = p.toString = function() { + return this.build(false)._string; + }; + + + function generateSimpleAccessor(_part){ + return function(v, build) { + if (v === undefined) { + return this._parts[_part] || ''; + } else { + this._parts[_part] = v || null; + this.build(!build); + return this; + } + }; + } + + function generatePrefixAccessor(_part, _key){ + return function(v, build) { + if (v === undefined) { + return this._parts[_part] || ''; + } else { + if (v !== null) { + v = v + ''; + if (v.charAt(0) === _key) { + v = v.substring(1); + } + } + + this._parts[_part] = v; + this.build(!build); + return this; + } + }; + } + + p.protocol = generateSimpleAccessor('protocol'); + p.username = generateSimpleAccessor('username'); + p.password = generateSimpleAccessor('password'); + p.hostname = generateSimpleAccessor('hostname'); + p.port = generateSimpleAccessor('port'); + p.query = generatePrefixAccessor('query', '?'); + p.fragment = generatePrefixAccessor('fragment', '#'); + + p.search = function(v, build) { + var t = this.query(v, build); + return typeof t === 'string' && t.length ? ('?' + t) : t; + }; + p.hash = function(v, build) { + var t = this.fragment(v, build); + return typeof t === 'string' && t.length ? ('#' + t) : t; + }; + + p.pathname = function(v, build) { + if (v === undefined || v === true) { + var res = this._parts.path || (this._parts.hostname ? '/' : ''); + return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res; + } else { + if (this._parts.urn) { + this._parts.path = v ? URI.recodeUrnPath(v) : ''; + } else { + this._parts.path = v ? URI.recodePath(v) : '/'; + } + this.build(!build); + return this; + } + }; + p.path = p.pathname; + p.href = function(href, build) { + var key; + + if (href === undefined) { + return this.toString(); + } + + this._string = ''; + this._parts = URI._parts(); + + var _URI = href instanceof URI; + var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname); + if (href.nodeName) { + var attribute = URI.getDomAttribute(href); + href = href[attribute] || ''; + _object = false; + } + + // window.location is reported to be an object, but it's not the sort + // of object we're looking for: + // * location.protocol ends with a colon + // * location.query != object.search + // * location.hash != object.fragment + // simply serializing the unknown object should do the trick + // (for location, not for everything...) + if (!_URI && _object && href.pathname !== undefined) { + href = href.toString(); + } + + if (typeof href === 'string' || href instanceof String) { + this._parts = URI.parse(String(href), this._parts); + } else if (_URI || _object) { + var src = _URI ? href._parts : href; + for (key in src) { + if (key === 'query') { continue; } + if (hasOwn.call(this._parts, key)) { + this._parts[key] = src[key]; + } + } + if (src.query) { + this.query(src.query, false); + } + } else { + throw new TypeError('invalid input'); + } + + this.build(!build); + return this; + }; + + // identification accessors + p.is = function(what) { + var ip = false; + var ip4 = false; + var ip6 = false; + var name = false; + var sld = false; + var idn = false; + var punycode = false; + var relative = !this._parts.urn; + + if (this._parts.hostname) { + relative = false; + ip4 = URI.ip4_expression.test(this._parts.hostname); + ip6 = URI.ip6_expression.test(this._parts.hostname); + ip = ip4 || ip6; + name = !ip; + sld = name && SLD && SLD.has(this._parts.hostname); + idn = name && URI.idn_expression.test(this._parts.hostname); + punycode = name && URI.punycode_expression.test(this._parts.hostname); + } + + switch (what.toLowerCase()) { + case 'relative': + return relative; + + case 'absolute': + return !relative; + + // hostname identification + case 'domain': + case 'name': + return name; + + case 'sld': + return sld; + + case 'ip': + return ip; + + case 'ip4': + case 'ipv4': + case 'inet4': + return ip4; + + case 'ip6': + case 'ipv6': + case 'inet6': + return ip6; + + case 'idn': + return idn; + + case 'url': + return !this._parts.urn; + + case 'urn': + return !!this._parts.urn; + + case 'punycode': + return punycode; + } + + return null; + }; + + // component specific input validation + var _protocol = p.protocol; + var _port = p.port; + var _hostname = p.hostname; + + p.protocol = function(v, build) { + if (v) { + // accept trailing :// + v = v.replace(/:(\/\/)?$/, ''); + + if (!v.match(URI.protocol_expression)) { + throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]'); + } + } + + return _protocol.call(this, v, build); + }; + p.scheme = p.protocol; + p.port = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v !== undefined) { + if (v === 0) { + v = null; + } + + if (v) { + v += ''; + if (v.charAt(0) === ':') { + v = v.substring(1); + } + + URI.ensureValidPort(v); + } + } + return _port.call(this, v, build); + }; + p.hostname = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v !== undefined) { + var x = { preventInvalidHostname: this._parts.preventInvalidHostname }; + var res = URI.parseHost(v, x); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + v = x.hostname; + if (this._parts.preventInvalidHostname) { + URI.ensureValidHostname(v, this._parts.protocol); + } + } + + return _hostname.call(this, v, build); + }; + + // compound accessors + p.origin = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + var protocol = this.protocol(); + var authority = this.authority(); + if (!authority) { + return ''; + } + + return (protocol ? protocol + '://' : '') + this.authority(); + } else { + var origin = URI(v); + this + .protocol(origin.protocol()) + .authority(origin.authority()) + .build(!build); + return this; + } + }; + p.host = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + return this._parts.hostname ? URI.buildHost(this._parts) : ''; + } else { + var res = URI.parseHost(v, this._parts); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + this.build(!build); + return this; + } + }; + p.authority = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + return this._parts.hostname ? URI.buildAuthority(this._parts) : ''; + } else { + var res = URI.parseAuthority(v, this._parts); + if (res !== '/') { + throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]'); + } + + this.build(!build); + return this; + } + }; + p.userinfo = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined) { + var t = URI.buildUserinfo(this._parts); + return t ? t.substring(0, t.length -1) : t; + } else { + if (v[v.length-1] !== '@') { + v += '@'; + } + + URI.parseUserinfo(v, this._parts); + this.build(!build); + return this; + } + }; + p.resource = function(v, build) { + var parts; + + if (v === undefined) { + return this.path() + this.search() + this.hash(); + } + + parts = URI.parse(v); + this._parts.path = parts.path; + this._parts.query = parts.query; + this._parts.fragment = parts.fragment; + this.build(!build); + return this; + }; + + // fraction accessors + p.subdomain = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + // convenience, return "www" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + // grab domain and add another segment + var end = this._parts.hostname.length - this.domain().length - 1; + return this._parts.hostname.substring(0, end) || ''; + } else { + var e = this._parts.hostname.length - this.domain().length; + var sub = this._parts.hostname.substring(0, e); + var replace = new RegExp('^' + escapeRegEx(sub)); + + if (v && v.charAt(v.length - 1) !== '.') { + v += '.'; + } + + if (v.indexOf(':') !== -1) { + throw new TypeError('Domains cannot contain colons'); + } + + if (v) { + URI.ensureValidHostname(v, this._parts.protocol); + } + + this._parts.hostname = this._parts.hostname.replace(replace, v); + this.build(!build); + return this; + } + }; + p.domain = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v === 'boolean') { + build = v; + v = undefined; + } + + // convenience, return "example.org" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + // if hostname consists of 1 or 2 segments, it must be the domain + var t = this._parts.hostname.match(/\./g); + if (t && t.length < 2) { + return this._parts.hostname; + } + + // grab tld and add another segment + var end = this._parts.hostname.length - this.tld(build).length - 1; + end = this._parts.hostname.lastIndexOf('.', end -1) + 1; + return this._parts.hostname.substring(end) || ''; + } else { + if (!v) { + throw new TypeError('cannot set domain empty'); + } + + if (v.indexOf(':') !== -1) { + throw new TypeError('Domains cannot contain colons'); + } + + URI.ensureValidHostname(v, this._parts.protocol); + + if (!this._parts.hostname || this.is('IP')) { + this._parts.hostname = v; + } else { + var replace = new RegExp(escapeRegEx(this.domain()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.tld = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v === 'boolean') { + build = v; + v = undefined; + } + + // return "org" from "www.example.org" + if (v === undefined) { + if (!this._parts.hostname || this.is('IP')) { + return ''; + } + + var pos = this._parts.hostname.lastIndexOf('.'); + var tld = this._parts.hostname.substring(pos + 1); + + if (build !== true && SLD && SLD.list[tld.toLowerCase()]) { + return SLD.get(this._parts.hostname) || tld; + } + + return tld; + } else { + var replace; + + if (!v) { + throw new TypeError('cannot set TLD empty'); + } else if (v.match(/[^a-zA-Z0-9-]/)) { + if (SLD && SLD.is(v)) { + replace = new RegExp(escapeRegEx(this.tld()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } else { + throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]'); + } + } else if (!this._parts.hostname || this.is('IP')) { + throw new ReferenceError('cannot set TLD on non-domain host'); + } else { + replace = new RegExp(escapeRegEx(this.tld()) + '$'); + this._parts.hostname = this._parts.hostname.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.directory = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined || v === true) { + if (!this._parts.path && !this._parts.hostname) { + return ''; + } + + if (this._parts.path === '/') { + return '/'; + } + + var end = this._parts.path.length - this.filename().length - 1; + var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : ''); + + return v ? URI.decodePath(res) : res; + + } else { + var e = this._parts.path.length - this.filename().length; + var directory = this._parts.path.substring(0, e); + var replace = new RegExp('^' + escapeRegEx(directory)); + + // fully qualifier directories begin with a slash + if (!this.is('relative')) { + if (!v) { + v = '/'; + } + + if (v.charAt(0) !== '/') { + v = '/' + v; + } + } + + // directories always end with a slash + if (v && v.charAt(v.length - 1) !== '/') { + v += '/'; + } + + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + this.build(!build); + return this; + } + }; + p.filename = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (typeof v !== 'string') { + if (!this._parts.path || this._parts.path === '/') { + return ''; + } + + var pos = this._parts.path.lastIndexOf('/'); + var res = this._parts.path.substring(pos+1); + + return v ? URI.decodePathSegment(res) : res; + } else { + var mutatedDirectory = false; + + if (v.charAt(0) === '/') { + v = v.substring(1); + } + + if (v.match(/\.?\//)) { + mutatedDirectory = true; + } + + var replace = new RegExp(escapeRegEx(this.filename()) + '$'); + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + + if (mutatedDirectory) { + this.normalizePath(build); + } else { + this.build(!build); + } + + return this; + } + }; + p.suffix = function(v, build) { + if (this._parts.urn) { + return v === undefined ? '' : this; + } + + if (v === undefined || v === true) { + if (!this._parts.path || this._parts.path === '/') { + return ''; + } + + var filename = this.filename(); + var pos = filename.lastIndexOf('.'); + var s, res; + + if (pos === -1) { + return ''; + } + + // suffix may only contain alnum characters (yup, I made this up.) + s = filename.substring(pos+1); + res = (/^[a-z0-9%]+$/i).test(s) ? s : ''; + return v ? URI.decodePathSegment(res) : res; + } else { + if (v.charAt(0) === '.') { + v = v.substring(1); + } + + var suffix = this.suffix(); + var replace; + + if (!suffix) { + if (!v) { + return this; + } + + this._parts.path += '.' + URI.recodePath(v); + } else if (!v) { + replace = new RegExp(escapeRegEx('.' + suffix) + '$'); + } else { + replace = new RegExp(escapeRegEx(suffix) + '$'); + } + + if (replace) { + v = URI.recodePath(v); + this._parts.path = this._parts.path.replace(replace, v); + } + + this.build(!build); + return this; + } + }; + p.segment = function(segment, v, build) { + var separator = this._parts.urn ? ':' : '/'; + var path = this.path(); + var absolute = path.substring(0, 1) === '/'; + var segments = path.split(separator); + + if (segment !== undefined && typeof segment !== 'number') { + build = v; + v = segment; + segment = undefined; + } + + if (segment !== undefined && typeof segment !== 'number') { + throw new Error('Bad segment "' + segment + '", must be 0-based integer'); + } + + if (absolute) { + segments.shift(); + } + + if (segment < 0) { + // allow negative indexes to address from the end + segment = Math.max(segments.length + segment, 0); + } + + if (v === undefined) { + /*jshint laxbreak: true */ + return segment === undefined + ? segments + : segments[segment]; + /*jshint laxbreak: false */ + } else if (segment === null || segments[segment] === undefined) { + if (isArray(v)) { + segments = []; + // collapse empty elements within array + for (var i=0, l=v.length; i < l; i++) { + if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) { + continue; + } + + if (segments.length && !segments[segments.length -1].length) { + segments.pop(); + } + + segments.push(trimSlashes(v[i])); + } + } else if (v || typeof v === 'string') { + v = trimSlashes(v); + if (segments[segments.length -1] === '') { + // empty trailing elements have to be overwritten + // to prevent results such as /foo//bar + segments[segments.length -1] = v; + } else { + segments.push(v); + } + } + } else { + if (v) { + segments[segment] = trimSlashes(v); + } else { + segments.splice(segment, 1); + } + } + + if (absolute) { + segments.unshift(''); + } + + return this.path(segments.join(separator), build); + }; + p.segmentCoded = function(segment, v, build) { + var segments, i, l; + + if (typeof segment !== 'number') { + build = v; + v = segment; + segment = undefined; + } + + if (v === undefined) { + segments = this.segment(segment, v, build); + if (!isArray(segments)) { + segments = segments !== undefined ? URI.decode(segments) : undefined; + } else { + for (i = 0, l = segments.length; i < l; i++) { + segments[i] = URI.decode(segments[i]); + } + } + + return segments; + } + + if (!isArray(v)) { + v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v; + } else { + for (i = 0, l = v.length; i < l; i++) { + v[i] = URI.encode(v[i]); + } + } + + return this.segment(segment, v, build); + }; + + // mutating query string + var q = p.query; + p.query = function(v, build) { + if (v === true) { + return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + } else if (typeof v === 'function') { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + var result = v.call(this, data); + this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + this.build(!build); + return this; + } else if (v !== undefined && typeof v !== 'string') { + this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + this.build(!build); + return this; + } else { + return q.call(this, v, build); + } + }; + p.setQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + + if (typeof name === 'string' || name instanceof String) { + data[name] = value !== undefined ? value : null; + } else if (typeof name === 'object') { + for (var key in name) { + if (hasOwn.call(name, key)) { + data[key] = name[key]; + } + } + } else { + throw new TypeError('URI.addQuery() accepts an object, string as the name parameter'); + } + + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.addQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + URI.addQuery(data, name, value === undefined ? null : value); + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.removeQuery = function(name, value, build) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + URI.removeQuery(data, name, value); + this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace); + if (typeof name !== 'string') { + build = value; + } + + this.build(!build); + return this; + }; + p.hasQuery = function(name, value, withinArray) { + var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace); + return URI.hasQuery(data, name, value, withinArray); + }; + p.setSearch = p.setQuery; + p.addSearch = p.addQuery; + p.removeSearch = p.removeQuery; + p.hasSearch = p.hasQuery; + + // sanitizing URLs + p.normalize = function() { + if (this._parts.urn) { + return this + .normalizeProtocol(false) + .normalizePath(false) + .normalizeQuery(false) + .normalizeFragment(false) + .build(); + } + + return this + .normalizeProtocol(false) + .normalizeHostname(false) + .normalizePort(false) + .normalizePath(false) + .normalizeQuery(false) + .normalizeFragment(false) + .build(); + }; + p.normalizeProtocol = function(build) { + if (typeof this._parts.protocol === 'string') { + this._parts.protocol = this._parts.protocol.toLowerCase(); + this.build(!build); + } + + return this; + }; + p.normalizeHostname = function(build) { + if (this._parts.hostname) { + if (this.is('IDN') && punycode) { + this._parts.hostname = punycode.toASCII(this._parts.hostname); + } else if (this.is('IPv6') && IPv6) { + this._parts.hostname = IPv6.best(this._parts.hostname); + } + + this._parts.hostname = this._parts.hostname.toLowerCase(); + this.build(!build); + } + + return this; + }; + p.normalizePort = function(build) { + // remove port of it's the protocol's default + if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) { + this._parts.port = null; + this.build(!build); + } + + return this; + }; + p.normalizePath = function(build) { + var _path = this._parts.path; + if (!_path) { + return this; + } + + if (this._parts.urn) { + this._parts.path = URI.recodeUrnPath(this._parts.path); + this.build(!build); + return this; + } + + if (this._parts.path === '/') { + return this; + } + + _path = URI.recodePath(_path); + + var _was_relative; + var _leadingParents = ''; + var _parent, _pos; + + // handle relative paths + if (_path.charAt(0) !== '/') { + _was_relative = true; + _path = '/' + _path; + } + + // handle relative files (as opposed to directories) + if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') { + _path += '/'; + } + + // resolve simples + _path = _path + .replace(/(\/(\.\/)+)|(\/\.$)/g, '/') + .replace(/\/{2,}/g, '/'); + + // remember leading parents + if (_was_relative) { + _leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || ''; + if (_leadingParents) { + _leadingParents = _leadingParents[0]; + } + } + + // resolve parents + while (true) { + _parent = _path.search(/\/\.\.(\/|$)/); + if (_parent === -1) { + // no more ../ to resolve + break; + } else if (_parent === 0) { + // top level cannot be relative, skip it + _path = _path.substring(3); + continue; + } + + _pos = _path.substring(0, _parent).lastIndexOf('/'); + if (_pos === -1) { + _pos = _parent; + } + _path = _path.substring(0, _pos) + _path.substring(_parent + 3); + } + + // revert to relative + if (_was_relative && this.is('relative')) { + _path = _leadingParents + _path.substring(1); + } + + this._parts.path = _path; + this.build(!build); + return this; + }; + p.normalizePathname = p.normalizePath; + p.normalizeQuery = function(build) { + if (typeof this._parts.query === 'string') { + if (!this._parts.query.length) { + this._parts.query = null; + } else { + this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace)); + } + + this.build(!build); + } + + return this; + }; + p.normalizeFragment = function(build) { + if (!this._parts.fragment) { + this._parts.fragment = null; + this.build(!build); + } + + return this; + }; + p.normalizeSearch = p.normalizeQuery; + p.normalizeHash = p.normalizeFragment; + + p.iso8859 = function() { + // expect unicode input, iso8859 output + var e = URI.encode; + var d = URI.decode; + + URI.encode = escape; + URI.decode = decodeURIComponent; + try { + this.normalize(); + } finally { + URI.encode = e; + URI.decode = d; + } + return this; + }; + + p.unicode = function() { + // expect iso8859 input, unicode output + var e = URI.encode; + var d = URI.decode; + + URI.encode = strictEncodeURIComponent; + URI.decode = unescape; + try { + this.normalize(); + } finally { + URI.encode = e; + URI.decode = d; + } + return this; + }; + + p.readable = function() { + var uri = this.clone(); + // removing username, password, because they shouldn't be displayed according to RFC 3986 + uri.username('').password('').normalize(); + var t = ''; + if (uri._parts.protocol) { + t += uri._parts.protocol + '://'; + } + + if (uri._parts.hostname) { + if (uri.is('punycode') && punycode) { + t += punycode.toUnicode(uri._parts.hostname); + if (uri._parts.port) { + t += ':' + uri._parts.port; + } + } else { + t += uri.host(); + } + } + + if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') { + t += '/'; + } + + t += uri.path(true); + if (uri._parts.query) { + var q = ''; + for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) { + var kv = (qp[i] || '').split('='); + q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace) + .replace(/&/g, '%26'); + + if (kv[1] !== undefined) { + q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace) + .replace(/&/g, '%26'); + } + } + t += '?' + q.substring(1); + } + + t += URI.decodeQuery(uri.hash(), true); + return t; + }; + + // resolving relative and absolute URLs + p.absoluteTo = function(base) { + var resolved = this.clone(); + var properties = ['protocol', 'username', 'password', 'hostname', 'port']; + var basedir, i, p; + + if (this._parts.urn) { + throw new Error('URNs do not have any generally defined hierarchical components'); + } + + if (!(base instanceof URI)) { + base = new URI(base); + } + + if (resolved._parts.protocol) { + // Directly returns even if this._parts.hostname is empty. + return resolved; + } else { + resolved._parts.protocol = base._parts.protocol; + } + + if (this._parts.hostname) { + return resolved; + } + + for (i = 0; (p = properties[i]); i++) { + resolved._parts[p] = base._parts[p]; + } + + if (!resolved._parts.path) { + resolved._parts.path = base._parts.path; + if (!resolved._parts.query) { + resolved._parts.query = base._parts.query; + } + } else { + if (resolved._parts.path.substring(-2) === '..') { + resolved._parts.path += '/'; + } + + if (resolved.path().charAt(0) !== '/') { + basedir = base.directory(); + basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : ''; + resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path; + resolved.normalizePath(); + } + } + + resolved.build(); + return resolved; + }; + p.relativeTo = function(base) { + var relative = this.clone().normalize(); + var relativeParts, baseParts, common, relativePath, basePath; + + if (relative._parts.urn) { + throw new Error('URNs do not have any generally defined hierarchical components'); + } + + base = new URI(base).normalize(); + relativeParts = relative._parts; + baseParts = base._parts; + relativePath = relative.path(); + basePath = base.path(); + + if (relativePath.charAt(0) !== '/') { + throw new Error('URI is already relative'); + } + + if (basePath.charAt(0) !== '/') { + throw new Error('Cannot calculate a URI relative to another relative URI'); + } + + if (relativeParts.protocol === baseParts.protocol) { + relativeParts.protocol = null; + } + + if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) { + return relative.build(); + } + + if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) { + return relative.build(); + } + + if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) { + relativeParts.hostname = null; + relativeParts.port = null; + } else { + return relative.build(); + } + + if (relativePath === basePath) { + relativeParts.path = ''; + return relative.build(); + } + + // determine common sub path + common = URI.commonPath(relativePath, basePath); + + // If the paths have nothing in common, return a relative URL with the absolute path. + if (!common) { + return relative.build(); + } + + var parents = baseParts.path + .substring(common.length) + .replace(/[^\/]*$/, '') + .replace(/.*?\//g, '../'); + + relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './'; + + return relative.build(); + }; + + // comparing URIs + p.equals = function(uri) { + var one = this.clone(); + var two = new URI(uri); + var one_map = {}; + var two_map = {}; + var checked = {}; + var one_query, two_query, key; + + one.normalize(); + two.normalize(); + + // exact match + if (one.toString() === two.toString()) { + return true; + } + + // extract query string + one_query = one.query(); + two_query = two.query(); + one.query(''); + two.query(''); + + // definitely not equal if not even non-query parts match + if (one.toString() !== two.toString()) { + return false; + } + + // query parameters have the same length, even if they're permuted + if (one_query.length !== two_query.length) { + return false; + } + + one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace); + two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace); + + for (key in one_map) { + if (hasOwn.call(one_map, key)) { + if (!isArray(one_map[key])) { + if (one_map[key] !== two_map[key]) { + return false; + } + } else if (!arraysEqual(one_map[key], two_map[key])) { + return false; + } + + checked[key] = true; + } + } + + for (key in two_map) { + if (hasOwn.call(two_map, key)) { + if (!checked[key]) { + // two contains a parameter not present in one + return false; + } + } + } + + return true; + }; + + // state + p.preventInvalidHostname = function(v) { + this._parts.preventInvalidHostname = !!v; + return this; + }; + + p.duplicateQueryParameters = function(v) { + this._parts.duplicateQueryParameters = !!v; + return this; + }; + + p.escapeQuerySpace = function(v) { + this._parts.escapeQuerySpace = !!v; + return this; + }; + + return URI; +})); diff --git a/node_modules/urijs/src/URI.min.js b/node_modules/urijs/src/URI.min.js new file mode 100644 index 000000000..bb3c39bff --- /dev/null +++ b/node_modules/urijs/src/URI.min.js @@ -0,0 +1,94 @@ +/*! URI.js v1.19.11 http://medialize.github.io/URI.js/ */ +/* build contains: IPv6.js, punycode.js, SecondLevelDomains.js, URI.js, URITemplate.js */ +(function(r,x){"object"===typeof module&&module.exports?module.exports=x():"function"===typeof define&&define.amd?define(x):r.IPv6=x(r)})(this,function(r){var x=r&&r.IPv6;return{best:function(k){k=k.toLowerCase().split(":");var m=k.length,d=8;""===k[0]&&""===k[1]&&""===k[2]?(k.shift(),k.shift()):""===k[0]&&""===k[1]?k.shift():""===k[m-1]&&""===k[m-2]&&k.pop();m=k.length;-1!==k[m-1].indexOf(".")&&(d=7);var q;for(q=0;qE;E++)if("0"===m[0]&&1E&&(m=h,E=A)):"0"===k[q]&&(p=!0,h=q,A=1);A>E&&(m=h,E=A);1=J&&C>>10&1023|55296),t=56320|t&1023);return C+=g(t)}).join("")}function E(l,t,C){var y=0;l=C?v(l/700):l>>1;for(l+=v(l/t);455c&&(c=0);for(a=0;a=C&&x("invalid-input");var f=l.charCodeAt(c++);f=10>f-48?f-22:26>f-65?f-65:26>f-97?f-97:36; +(36<=f||f>v((2147483647-y)/e))&&x("overflow");y+=f*e;var n=b<=M?1:b>=M+26?26:b-M;if(fv(2147483647/f)&&x("overflow");e*=f}e=t.length+1;M=E(y-a,e,0==a);v(y/e)>2147483647-J&&x("overflow");J+=v(y/e);y%=e;t.splice(y++,0,J)}return q(t)}function h(l){var t,C,y,J=[];l=d(l);var M=l.length;var a=128;var b=0;var c=72;for(y=0;ye&&J.push(g(e))}for((t=C=J.length)&&J.push("-");t=a&&ev((2147483647-b)/n)&& +x("overflow");b+=(f-a)*n;a=f;for(y=0;y=c+26?26:f-c;if(ze)-0));z=v(I/z)}J.push(g(z+22+75*(26>z)-0));c=E(b,n,t==C);b=0;++t}++b;++a}return J.join("")}var p="object"==typeof exports&&exports&&!exports.nodeType&&exports,D="object"==typeof module&&module&&!module.nodeType&&module,u="object"==typeof global&&global;if(u.global===u||u.window===u|| +u.self===u)r=u;var K=/^xn--/,F=/[^\x20-\x7E]/,w=/[\x2E\u3002\uFF0E\uFF61]/g,H={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},v=Math.floor,g=String.fromCharCode,B;var G={version:"1.3.2",ucs2:{decode:d,encode:q},decode:A,encode:h,toASCII:function(l){return m(l,function(t){return F.test(t)?"xn--"+h(t):t})},toUnicode:function(l){return m(l,function(t){return K.test(t)?A(t.slice(4).toLowerCase()): +t})}};if("function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return G});else if(p&&D)if(module.exports==p)D.exports=G;else for(B in G)G.hasOwnProperty(B)&&(p[B]=G[B]);else r.punycode=G})(this); +(function(r,x){"object"===typeof module&&module.exports?module.exports=x():"function"===typeof define&&define.amd?define(x):r.SecondLevelDomains=x(r)})(this,function(r){var x=r&&r.SecondLevelDomains,k={list:{ac:" com gov mil net org ",ae:" ac co gov mil name net org pro sch ",af:" com edu gov net org ",al:" com edu gov mil net org ",ao:" co ed gv it og pb ",ar:" com edu gob gov int mil net org tur ",at:" ac co gv or ",au:" asn com csiro edu gov id net org ",ba:" co com edu gov mil net org rs unbi unmo unsa untz unze ", +bb:" biz co com edu gov info net org store tv ",bh:" biz cc com edu gov info net org ",bn:" com edu gov net org ",bo:" com edu gob gov int mil net org tv ",br:" adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ",bs:" com edu gov net org ",bz:" du et om ov rg ",ca:" ab bc mb nb nf nl ns nt nu on pe qc sk yk ", +ck:" biz co edu gen gov info net org ",cn:" ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ",co:" com edu gov mil net nom org ",cr:" ac c co ed fi go or sa ",cy:" ac biz com ekloges gov ltd name net org parliament press pro tm ","do":" art com edu gob gov mil net org sld web ",dz:" art asso com edu gov net org pol ",ec:" com edu fin gov info med mil net org pro ",eg:" com edu eun gov mil name net org sci ",er:" com edu gov ind mil net org rochest w ", +es:" com edu gob nom org ",et:" biz com edu gov info name net org ",fj:" ac biz com info mil name net org pro ",fk:" ac co gov net nom org ",fr:" asso com f gouv nom prd presse tm ",gg:" co net org ",gh:" com edu gov mil org ",gn:" ac com gov net org ",gr:" com edu gov mil net org ",gt:" com edu gob ind mil net org ",gu:" com edu gov net org ",hk:" com edu gov idv net org ",hu:" 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ", +id:" ac co go mil net or sch web ",il:" ac co gov idf k12 muni net org ","in":" ac co edu ernet firm gen gov i ind mil net nic org res ",iq:" com edu gov i mil net org ",ir:" ac co dnssec gov i id net org sch ",it:" edu gov ",je:" co net org ",jo:" com edu gov mil name net org sch ",jp:" ac ad co ed go gr lg ne or ",ke:" ac co go info me mobi ne or sc ",kh:" com edu gov mil net org per ",ki:" biz com de edu gov info mob net org tel ",km:" asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ", +kn:" edu gov net org ",kr:" ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ",kw:" com edu gov net org ",ky:" com edu gov net org ",kz:" com edu gov mil net org ",lb:" com edu gov net org ",lk:" assn com edu gov grp hotel int ltd net ngo org sch soc web ",lr:" com edu gov net org ",lv:" asn com conf edu gov id mil net org ",ly:" com edu gov id med net org plc sch ",ma:" ac co gov m net org press ", +mc:" asso tm ",me:" ac co edu gov its net org priv ",mg:" com edu gov mil nom org prd tm ",mk:" com edu gov inf name net org pro ",ml:" com edu gov net org presse ",mn:" edu gov org ",mo:" com edu gov net org ",mt:" com edu gov net org ",mv:" aero biz com coop edu gov info int mil museum name net org pro ",mw:" ac co com coop edu gov int museum net org ",mx:" com edu gob net org ",my:" com edu gov mil name net org sch ",nf:" arts com firm info net other per rec store web ",ng:" biz com edu gov mil mobi name net org sch ", +ni:" ac co com edu gob mil net nom org ",np:" com edu gov mil net org ",nr:" biz com edu gov info net org ",om:" ac biz co com edu gov med mil museum net org pro sch ",pe:" com edu gob mil net nom org sld ",ph:" com edu gov i mil net ngo org ",pk:" biz com edu fam gob gok gon gop gos gov net org web ",pl:" art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ",pr:" ac biz com edu est gov info isla name net org pro prof ", +ps:" com edu gov net org plo sec ",pw:" belau co ed go ne or ",ro:" arts com firm info nom nt org rec store tm www ",rs:" ac co edu gov in org ",sb:" com edu gov net org ",sc:" com edu gov net org ",sh:" co com edu gov net nom org ",sl:" com edu gov net org ",st:" co com consulado edu embaixada gov mil net org principe saotome store ",sv:" com edu gob org red ",sz:" ac co org ",tr:" av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ",tt:" aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ", +tw:" club com ebiz edu game gov idv mil net org ",mu:" ac co com gov net or org ",mz:" ac co edu gov org ",na:" co com ",nz:" ac co cri geek gen govt health iwi maori mil net org parliament school ",pa:" abo ac com edu gob ing med net nom org sld ",pt:" com edu gov int net nome org publ ",py:" com edu gov mil net org ",qa:" com edu gov mil net org ",re:" asso com nom ",ru:" ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ", +rw:" ac co com edu gouv gov int mil net ",sa:" com edu gov med net org pub sch ",sd:" com edu gov info med net org tv ",se:" a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ",sg:" com edu gov idn net org per ",sn:" art com edu gouv org perso univ ",sy:" com edu gov mil net news org ",th:" ac co go in mi net or ",tj:" ac biz co com edu go gov info int mil name net nic org test web ",tn:" agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ", +tz:" ac co go ne or ",ua:" biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ",ug:" ac co go ne or org sc ",uk:" ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ", +us:" dni fed isa kids nsn ",uy:" com edu gub mil net org ",ve:" co com edu gob info mil net org web ",vi:" co com k12 net org ",vn:" ac biz com edu gov health info int name net org pro ",ye:" co com gov ltd me net org plc ",yu:" ac co edu gov org ",za:" ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ",zm:" ac co com edu gov net org sch ",com:"ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ",net:"gb jp se uk ", +org:"ae",de:"com "},has:function(m){var d=m.lastIndexOf(".");if(0>=d||d>=m.length-1)return!1;var q=m.lastIndexOf(".",d-1);if(0>=q||q>=d-1)return!1;var E=k.list[m.slice(d+1)];return E?0<=E.indexOf(" "+m.slice(q+1,d)+" "):!1},is:function(m){var d=m.lastIndexOf(".");if(0>=d||d>=m.length-1||0<=m.lastIndexOf(".",d-1))return!1;var q=k.list[m.slice(d+1)];return q?0<=q.indexOf(" "+m.slice(0,d)+" "):!1},get:function(m){var d=m.lastIndexOf(".");if(0>=d||d>=m.length-1)return null;var q=m.lastIndexOf(".",d-1); +if(0>=q||q>=d-1)return null;var E=k.list[m.slice(d+1)];return!E||0>E.indexOf(" "+m.slice(q+1,d)+" ")?null:m.slice(q+1)},noConflict:function(){r.SecondLevelDomains===this&&(r.SecondLevelDomains=x);return this}};return k}); +(function(r,x){"object"===typeof module&&module.exports?module.exports=x(require("./punycode"),require("./IPv6"),require("./SecondLevelDomains")):"function"===typeof define&&define.amd?define(["./punycode","./IPv6","./SecondLevelDomains"],x):r.URI=x(r.punycode,r.IPv6,r.SecondLevelDomains,r)})(this,function(r,x,k,m){function d(a,b){var c=1<=arguments.length,e=2<=arguments.length;if(!(this instanceof d))return c?e?new d(a,b):new d(a):new d;if(void 0===a){if(c)throw new TypeError("undefined is not a valid argument for URI"); +a="undefined"!==typeof location?location.href+"":""}if(null===a&&c)throw new TypeError("null is not a valid argument for URI");this.href(a);return void 0!==b?this.absoluteTo(b):this}function q(a){return a.replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")}function E(a){return void 0===a?"Undefined":String(Object.prototype.toString.call(a)).slice(8,-1)}function A(a){return"Array"===E(a)}function h(a,b){var c={},e;if("RegExp"===E(b))c=null;else if(A(b)){var f=0;for(e=b.length;f]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?\u00ab\u00bb\u201c\u201d\u2018\u2019]))/ig;d.findUri={start:/\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,end:/[\s\r\n]|$/,trim:/[`!()\[\]{};:'".,<>?\u00ab\u00bb\u201c\u201d\u201e\u2018\u2019]+$/,parens:/(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g};d.leading_whitespace_expression=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/; +d.ascii_tab_whitespace=/[\u0009\u000A\u000D]+/g;d.defaultPorts={http:"80",https:"443",ftp:"21",gopher:"70",ws:"80",wss:"443"};d.hostProtocols=["http","https"];d.invalid_hostname_characters=/[^a-zA-Z0-9\.\-:_]/;d.domAttributes={a:"href",blockquote:"cite",link:"href",base:"href",script:"src",form:"action",img:"src",area:"href",iframe:"src",embed:"src",source:"src",track:"src",input:"src",audio:"src",video:"src"};d.getDomAttribute=function(a){if(a&&a.nodeName){var b=a.nodeName.toLowerCase();if("input"!== +b||"image"===a.type)return d.domAttributes[b]}};d.encode=F;d.decode=decodeURIComponent;d.iso8859=function(){d.encode=escape;d.decode=unescape};d.unicode=function(){d.encode=F;d.decode=decodeURIComponent};d.characters={pathname:{encode:{expression:/%(24|26|2B|2C|3B|3D|3A|40)/ig,map:{"%24":"$","%26":"&","%2B":"+","%2C":",","%3B":";","%3D":"=","%3A":":","%40":"@"}},decode:{expression:/[\/\?#]/g,map:{"/":"%2F","?":"%3F","#":"%23"}}},reserved:{encode:{expression:/%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig, +map:{"%3A":":","%2F":"/","%3F":"?","%23":"#","%5B":"[","%5D":"]","%40":"@","%21":"!","%24":"$","%26":"&","%27":"'","%28":"(","%29":")","%2A":"*","%2B":"+","%2C":",","%3B":";","%3D":"="}}},urnpath:{encode:{expression:/%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,map:{"%21":"!","%24":"$","%27":"'","%28":"(","%29":")","%2A":"*","%2B":"+","%2C":",","%3B":";","%3D":"=","%40":"@"}},decode:{expression:/[\/\?#:]/g,map:{"/":"%2F","?":"%3F","#":"%23",":":"%3A"}}}};d.encodeQuery=function(a,b){var c=d.encode(a+""); +void 0===b&&(b=d.escapeQuerySpace);return b?c.replace(/%20/g,"+"):c};d.decodeQuery=function(a,b){a+="";void 0===b&&(b=d.escapeQuerySpace);try{return d.decode(b?a.replace(/\+/g,"%20"):a)}catch(c){return a}};var G={encode:"encode",decode:"decode"},l,t=function(a,b){return function(c){try{return d[b](c+"").replace(d.characters[a][b].expression,function(e){return d.characters[a][b].map[e]})}catch(e){return c}}};for(l in G)d[l+"PathSegment"]=t("pathname",G[l]),d[l+"UrnPathSegment"]=t("urnpath",G[l]);G= +function(a,b,c){return function(e){var f=c?function(I){return d[b](d[c](I))}:d[b];e=(e+"").split(a);for(var n=0,z=e.length;ne)return a.charAt(0)===b.charAt(0)&& +"/"===a.charAt(0)?"/":"";if("/"!==a.charAt(e)||"/"!==b.charAt(e))e=a.substring(0,e).lastIndexOf("/");return a.substring(0,e+1)};d.withinString=function(a,b,c){c||(c={});var e=c.start||d.findUri.start,f=c.end||d.findUri.end,n=c.trim||d.findUri.trim,z=c.parens||d.findUri.parens,I=/[a-z0-9-]=["']?$/i;for(e.lastIndex=0;;){var L=e.exec(a);if(!L)break;var P=L.index;if(c.ignoreHtml){var N=a.slice(Math.max(P-3,0),P);if(N&&I.test(N))continue}var O=P+a.slice(P).search(f);N=a.slice(P,O);for(O=-1;;){var Q=z.exec(N); +if(!Q)break;O=Math.max(O,Q.index+Q[0].length)}N=-1b))throw new TypeError('Port "'+a+'" is not a valid port');}};d.noConflict=function(a){if(a)return a={URI:this.noConflict()},m.URITemplate&&"function"===typeof m.URITemplate.noConflict&&(a.URITemplate= +m.URITemplate.noConflict()),m.IPv6&&"function"===typeof m.IPv6.noConflict&&(a.IPv6=m.IPv6.noConflict()),m.SecondLevelDomains&&"function"===typeof m.SecondLevelDomains.noConflict&&(a.SecondLevelDomains=m.SecondLevelDomains.noConflict()),a;m.URI===this&&(m.URI=v);return this};g.build=function(a){if(!0===a)this._deferred_build=!0;else if(void 0===a||this._deferred_build)this._string=d.build(this._parts),this._deferred_build=!1;return this};g.clone=function(){return new d(this)};g.valueOf=g.toString= +function(){return this.build(!1)._string};g.protocol=w("protocol");g.username=w("username");g.password=w("password");g.hostname=w("hostname");g.port=w("port");g.query=H("query","?");g.fragment=H("fragment","#");g.search=function(a,b){var c=this.query(a,b);return"string"===typeof c&&c.length?"?"+c:c};g.hash=function(a,b){var c=this.fragment(a,b);return"string"===typeof c&&c.length?"#"+c:c};g.pathname=function(a,b){if(void 0===a||!0===a){var c=this._parts.path||(this._parts.hostname?"/":"");return a? +(this._parts.urn?d.decodeUrnPath:d.decodePath)(c):c}this._parts.path=this._parts.urn?a?d.recodeUrnPath(a):"":a?d.recodePath(a):"/";this.build(!b);return this};g.path=g.pathname;g.href=function(a,b){var c;if(void 0===a)return this.toString();this._string="";this._parts=d._parts();var e=a instanceof d,f="object"===typeof a&&(a.hostname||a.path||a.pathname);a.nodeName&&(f=d.getDomAttribute(a),a=a[f]||"",f=!1);!e&&f&&void 0!==a.pathname&&(a=a.toString());if("string"===typeof a||a instanceof String)this._parts= +d.parse(String(a),this._parts);else if(e||f){e=e?a._parts:a;for(c in e)"query"!==c&&B.call(this._parts,c)&&(this._parts[c]=e[c]);e.query&&this.query(e.query,!1)}else throw new TypeError("invalid input");this.build(!b);return this};g.is=function(a){var b=!1,c=!1,e=!1,f=!1,n=!1,z=!1,I=!1,L=!this._parts.urn;this._parts.hostname&&(L=!1,c=d.ip4_expression.test(this._parts.hostname),e=d.ip6_expression.test(this._parts.hostname),b=c||e,n=(f=!b)&&k&&k.has(this._parts.hostname),z=f&&d.idn_expression.test(this._parts.hostname), +I=f&&d.punycode_expression.test(this._parts.hostname));switch(a.toLowerCase()){case "relative":return L;case "absolute":return!L;case "domain":case "name":return f;case "sld":return n;case "ip":return b;case "ip4":case "ipv4":case "inet4":return c;case "ip6":case "ipv6":case "inet6":return e;case "idn":return z;case "url":return!this._parts.urn;case "urn":return!!this._parts.urn;case "punycode":return I}return null};var C=g.protocol,y=g.port,J=g.hostname;g.protocol=function(a,b){if(a&&(a=a.replace(/:(\/\/)?$/, +""),!a.match(d.protocol_expression)))throw new TypeError('Protocol "'+a+"\" contains characters other than [A-Z0-9.+-] or doesn't start with [A-Z]");return C.call(this,a,b)};g.scheme=g.protocol;g.port=function(a,b){if(this._parts.urn)return void 0===a?"":this;void 0!==a&&(0===a&&(a=null),a&&(a+="",":"===a.charAt(0)&&(a=a.substring(1)),d.ensureValidPort(a)));return y.call(this,a,b)};g.hostname=function(a,b){if(this._parts.urn)return void 0===a?"":this;if(void 0!==a){var c={preventInvalidHostname:this._parts.preventInvalidHostname}; +if("/"!==d.parseHost(a,c))throw new TypeError('Hostname "'+a+'" contains characters other than [A-Z0-9.-]');a=c.hostname;this._parts.preventInvalidHostname&&d.ensureValidHostname(a,this._parts.protocol)}return J.call(this,a,b)};g.origin=function(a,b){if(this._parts.urn)return void 0===a?"":this;if(void 0===a){var c=this.protocol();return this.authority()?(c?c+"://":"")+this.authority():""}c=d(a);this.protocol(c.protocol()).authority(c.authority()).build(!b);return this};g.host=function(a,b){if(this._parts.urn)return void 0=== +a?"":this;if(void 0===a)return this._parts.hostname?d.buildHost(this._parts):"";if("/"!==d.parseHost(a,this._parts))throw new TypeError('Hostname "'+a+'" contains characters other than [A-Z0-9.-]');this.build(!b);return this};g.authority=function(a,b){if(this._parts.urn)return void 0===a?"":this;if(void 0===a)return this._parts.hostname?d.buildAuthority(this._parts):"";if("/"!==d.parseAuthority(a,this._parts))throw new TypeError('Hostname "'+a+'" contains characters other than [A-Z0-9.-]');this.build(!b); +return this};g.userinfo=function(a,b){if(this._parts.urn)return void 0===a?"":this;if(void 0===a){var c=d.buildUserinfo(this._parts);return c?c.substring(0,c.length-1):c}"@"!==a[a.length-1]&&(a+="@");d.parseUserinfo(a,this._parts);this.build(!b);return this};g.resource=function(a,b){if(void 0===a)return this.path()+this.search()+this.hash();var c=d.parse(a);this._parts.path=c.path;this._parts.query=c.query;this._parts.fragment=c.fragment;this.build(!b);return this};g.subdomain=function(a,b){if(this._parts.urn)return void 0=== +a?"":this;if(void 0===a){if(!this._parts.hostname||this.is("IP"))return"";var c=this._parts.hostname.length-this.domain().length-1;return this._parts.hostname.substring(0,c)||""}c=this._parts.hostname.length-this.domain().length;c=this._parts.hostname.substring(0,c);c=new RegExp("^"+q(c));a&&"."!==a.charAt(a.length-1)&&(a+=".");if(-1!==a.indexOf(":"))throw new TypeError("Domains cannot contain colons");a&&d.ensureValidHostname(a,this._parts.protocol);this._parts.hostname=this._parts.hostname.replace(c, +a);this.build(!b);return this};g.domain=function(a,b){if(this._parts.urn)return void 0===a?"":this;"boolean"===typeof a&&(b=a,a=void 0);if(void 0===a){if(!this._parts.hostname||this.is("IP"))return"";var c=this._parts.hostname.match(/\./g);if(c&&2>c.length)return this._parts.hostname;c=this._parts.hostname.length-this.tld(b).length-1;c=this._parts.hostname.lastIndexOf(".",c-1)+1;return this._parts.hostname.substring(c)||""}if(!a)throw new TypeError("cannot set domain empty");if(-1!==a.indexOf(":"))throw new TypeError("Domains cannot contain colons"); +d.ensureValidHostname(a,this._parts.protocol);!this._parts.hostname||this.is("IP")?this._parts.hostname=a:(c=new RegExp(q(this.domain())+"$"),this._parts.hostname=this._parts.hostname.replace(c,a));this.build(!b);return this};g.tld=function(a,b){if(this._parts.urn)return void 0===a?"":this;"boolean"===typeof a&&(b=a,a=void 0);if(void 0===a){if(!this._parts.hostname||this.is("IP"))return"";var c=this._parts.hostname.lastIndexOf(".");c=this._parts.hostname.substring(c+1);return!0!==b&&k&&k.list[c.toLowerCase()]? +k.get(this._parts.hostname)||c:c}if(a)if(a.match(/[^a-zA-Z0-9-]/))if(k&&k.is(a))c=new RegExp(q(this.tld())+"$"),this._parts.hostname=this._parts.hostname.replace(c,a);else throw new TypeError('TLD "'+a+'" contains characters other than [A-Z0-9]');else{if(!this._parts.hostname||this.is("IP"))throw new ReferenceError("cannot set TLD on non-domain host");c=new RegExp(q(this.tld())+"$");this._parts.hostname=this._parts.hostname.replace(c,a)}else throw new TypeError("cannot set TLD empty");this.build(!b); +return this};g.directory=function(a,b){if(this._parts.urn)return void 0===a?"":this;if(void 0===a||!0===a){if(!this._parts.path&&!this._parts.hostname)return"";if("/"===this._parts.path)return"/";var c=this._parts.path.length-this.filename().length-1;c=this._parts.path.substring(0,c)||(this._parts.hostname?"/":"");return a?d.decodePath(c):c}c=this._parts.path.length-this.filename().length;c=this._parts.path.substring(0,c);c=new RegExp("^"+q(c));this.is("relative")||(a||(a="/"),"/"!==a.charAt(0)&& +(a="/"+a));a&&"/"!==a.charAt(a.length-1)&&(a+="/");a=d.recodePath(a);this._parts.path=this._parts.path.replace(c,a);this.build(!b);return this};g.filename=function(a,b){if(this._parts.urn)return void 0===a?"":this;if("string"!==typeof a){if(!this._parts.path||"/"===this._parts.path)return"";var c=this._parts.path.lastIndexOf("/");c=this._parts.path.substring(c+1);return a?d.decodePathSegment(c):c}c=!1;"/"===a.charAt(0)&&(a=a.substring(1));a.match(/\.?\//)&&(c=!0);var e=new RegExp(q(this.filename())+ +"$");a=d.recodePath(a);this._parts.path=this._parts.path.replace(e,a);c?this.normalizePath(b):this.build(!b);return this};g.suffix=function(a,b){if(this._parts.urn)return void 0===a?"":this;if(void 0===a||!0===a){if(!this._parts.path||"/"===this._parts.path)return"";var c=this.filename(),e=c.lastIndexOf(".");if(-1===e)return"";c=c.substring(e+1);c=/^[a-z0-9%]+$/i.test(c)?c:"";return a?d.decodePathSegment(c):c}"."===a.charAt(0)&&(a=a.substring(1));if(c=this.suffix())e=a?new RegExp(q(c)+"$"):new RegExp(q("."+ +c)+"$");else{if(!a)return this;this._parts.path+="."+d.recodePath(a)}e&&(a=d.recodePath(a),this._parts.path=this._parts.path.replace(e,a));this.build(!b);return this};g.segment=function(a,b,c){var e=this._parts.urn?":":"/",f=this.path(),n="/"===f.substring(0,1);f=f.split(e);void 0!==a&&"number"!==typeof a&&(c=b,b=a,a=void 0);if(void 0!==a&&"number"!==typeof a)throw Error('Bad segment "'+a+'", must be 0-based integer');n&&f.shift();0>a&&(a=Math.max(f.length+a,0));if(void 0===b)return void 0===a?f: +f[a];if(null===a||void 0===f[a])if(A(b)){f=[];a=0;for(var z=b.length;a{}"`^| \\]/;k.expand=function(h,p,D){var u=A[h.operator],K=u.named?"Named":"Unnamed";h=h.variables;var F=[],w,H;for(H=0;w=h[H];H++){var v=p.get(w.name);if(0===v.type&&D&&D.strict)throw Error('Missing expansion value for variable "'+ +w.name+'"');if(v.val.length){if(1{}"`^| \\]/; + + // expand parsed expression (expression, not template!) + URITemplate.expand = function(expression, data, opts) { + // container for defined options for the given operator + var options = operators[expression.operator]; + // expansion type (include keys or not) + var type = options.named ? 'Named' : 'Unnamed'; + // list of variables within the expression + var variables = expression.variables; + // result buffer for evaluating the expression + var buffer = []; + var d, variable, i; + + for (i = 0; (variable = variables[i]); i++) { + // fetch simplified data source + d = data.get(variable.name); + if (d.type === 0 && opts && opts.strict) { + throw new Error('Missing expansion value for variable "' + variable.name + '"'); + } + if (!d.val.length) { + if (d.type) { + // empty variables (empty string) + // still lead to a separator being appended! + buffer.push(''); + } + // no data, no action + continue; + } + + if (d.type > 1 && variable.maxlength) { + // composite variable cannot specify maxlength + throw new Error('Invalid expression: Prefix modifier not applicable to variable "' + variable.name + '"'); + } + + // expand the given variable + buffer.push(URITemplate['expand' + type]( + d, + options, + variable.explode, + variable.explode && options.separator || ',', + variable.maxlength, + variable.name + )); + } + + if (buffer.length) { + return options.prefix + buffer.join(options.separator); + } else { + // prefix is not prepended for empty expressions + return ''; + } + }; + // expand a named variable + URITemplate.expandNamed = function(d, options, explode, separator, length, name) { + // variable result buffer + var result = ''; + // peformance crap + var encode = options.encode; + var empty_name_separator = options.empty_name_separator; + // flag noting if values are already encoded + var _encode = !d[encode].length; + // key for named expansion + var _name = d.type === 2 ? '': URI[encode](name); + var _value, i, l; + + // for each found value + for (i = 0, l = d.val.length; i < l; i++) { + if (length) { + // maxlength must be determined before encoding can happen + _value = URI[encode](d.val[i][1].substring(0, length)); + if (d.type === 2) { + // apply maxlength to keys of objects as well + _name = URI[encode](d.val[i][0].substring(0, length)); + } + } else if (_encode) { + // encode value + _value = URI[encode](d.val[i][1]); + if (d.type === 2) { + // encode name and cache encoded value + _name = URI[encode](d.val[i][0]); + d[encode].push([_name, _value]); + } else { + // cache encoded value + d[encode].push([undefined, _value]); + } + } else { + // values are already encoded and can be pulled from cache + _value = d[encode][i][1]; + if (d.type === 2) { + _name = d[encode][i][0]; + } + } + + if (result) { + // unless we're the first value, prepend the separator + result += separator; + } + + if (!explode) { + if (!i) { + // first element, so prepend variable name + result += URI[encode](name) + (empty_name_separator || _value ? '=' : ''); + } + + if (d.type === 2) { + // without explode-modifier, keys of objects are returned comma-separated + result += _name + ','; + } + + result += _value; + } else { + // only add the = if it is either default (?&) or there actually is a value (;) + result += _name + (empty_name_separator || _value ? '=' : '') + _value; + } + } + + return result; + }; + // expand an unnamed variable + URITemplate.expandUnnamed = function(d, options, explode, separator, length) { + // variable result buffer + var result = ''; + // performance crap + var encode = options.encode; + var empty_name_separator = options.empty_name_separator; + // flag noting if values are already encoded + var _encode = !d[encode].length; + var _name, _value, i, l; + + // for each found value + for (i = 0, l = d.val.length; i < l; i++) { + if (length) { + // maxlength must be determined before encoding can happen + _value = URI[encode](d.val[i][1].substring(0, length)); + } else if (_encode) { + // encode and cache value + _value = URI[encode](d.val[i][1]); + d[encode].push([ + d.type === 2 ? URI[encode](d.val[i][0]) : undefined, + _value + ]); + } else { + // value already encoded, pull from cache + _value = d[encode][i][1]; + } + + if (result) { + // unless we're the first value, prepend the separator + result += separator; + } + + if (d.type === 2) { + if (length) { + // maxlength also applies to keys of objects + _name = URI[encode](d.val[i][0].substring(0, length)); + } else { + // at this point the name must already be encoded + _name = d[encode][i][0]; + } + + result += _name; + if (explode) { + // explode-modifier separates name and value by "=" + result += (empty_name_separator || _value ? '=' : ''); + } else { + // no explode-modifier separates name and value by "," + result += ','; + } + } + + result += _value; + } + + return result; + }; + + URITemplate.noConflict = function() { + if (root.URITemplate === URITemplate) { + root.URITemplate = _URITemplate; + } + + return URITemplate; + }; + + // expand template through given data map + p.expand = function(data, opts) { + var result = ''; + + if (!this.parts || !this.parts.length) { + // lazilyy parse the template + this.parse(); + } + + if (!(data instanceof Data)) { + // make given data available through the + // optimized data handling thingie + data = new Data(data); + } + + for (var i = 0, l = this.parts.length; i < l; i++) { + /*jshint laxbreak: true */ + result += typeof this.parts[i] === 'string' + // literal string + ? this.parts[i] + // expression + : URITemplate.expand(this.parts[i], data, opts); + /*jshint laxbreak: false */ + } + + return result; + }; + // parse template into action tokens + p.parse = function() { + // performance crap + var expression = this.expression; + var ePattern = URITemplate.EXPRESSION_PATTERN; + var vPattern = URITemplate.VARIABLE_PATTERN; + var nPattern = URITemplate.VARIABLE_NAME_PATTERN; + var lPattern = URITemplate.LITERAL_PATTERN; + // token result buffer + var parts = []; + // position within source template + var pos = 0; + var variables, eMatch, vMatch; + + var checkLiteral = function(literal) { + if (literal.match(lPattern)) { + throw new Error('Invalid Literal "' + literal + '"'); + } + return literal; + }; + + // RegExp is shared accross all templates, + // which requires a manual reset + ePattern.lastIndex = 0; + // I don't like while(foo = bar()) loops, + // to make things simpler I go while(true) and break when required + while (true) { + eMatch = ePattern.exec(expression); + if (eMatch === null) { + // push trailing literal + parts.push(checkLiteral(expression.substring(pos))); + break; + } else { + // push leading literal + parts.push(checkLiteral(expression.substring(pos, eMatch.index))); + pos = eMatch.index + eMatch[0].length; + } + + if (!operators[eMatch[1]]) { + throw new Error('Unknown Operator "' + eMatch[1] + '" in "' + eMatch[0] + '"'); + } else if (!eMatch[3]) { + throw new Error('Unclosed Expression "' + eMatch[0] + '"'); + } + + // parse variable-list + variables = eMatch[2].split(','); + for (var i = 0, l = variables.length; i < l; i++) { + vMatch = variables[i].match(vPattern); + if (vMatch === null) { + throw new Error('Invalid Variable "' + variables[i] + '" in "' + eMatch[0] + '"'); + } else if (vMatch[1].match(nPattern)) { + throw new Error('Invalid Variable Name "' + vMatch[1] + '" in "' + eMatch[0] + '"'); + } + + variables[i] = { + name: vMatch[1], + explode: !!vMatch[3], + maxlength: vMatch[4] && parseInt(vMatch[4], 10) + }; + } + + if (!variables.length) { + throw new Error('Expression Missing Variable(s) "' + eMatch[0] + '"'); + } + + parts.push({ + expression: eMatch[0], + operator: eMatch[1], + variables: variables + }); + } + + if (!parts.length) { + // template doesn't contain any expressions + // so it is a simple literal string + // this probably should fire a warning or something? + parts.push(checkLiteral(expression)); + } + + this.parts = parts; + return this; + }; + + // simplify data structures + Data.prototype.get = function(key) { + // performance crap + var data = this.data; + // cache for processed data-point + var d = { + // type of data 0: undefined/null, 1: string, 2: object, 3: array + type: 0, + // original values (except undefined/null) + val: [], + // cache for encoded values (only for non-maxlength expansion) + encode: [], + encodeReserved: [] + }; + var i, l, value; + + if (this.cache[key] !== undefined) { + // we've already processed this key + return this.cache[key]; + } + + this.cache[key] = d; + + if (String(Object.prototype.toString.call(data)) === '[object Function]') { + // data itself is a callback (global callback) + value = data(key); + } else if (String(Object.prototype.toString.call(data[key])) === '[object Function]') { + // data is a map of callbacks (local callback) + value = data[key](key); + } else { + // data is a map of data + value = data[key]; + } + + // generalize input into [ [name1, value1], [name2, value2], … ] + // so expansion has to deal with a single data structure only + if (value === undefined || value === null) { + // undefined and null values are to be ignored completely + return d; + } else if (String(Object.prototype.toString.call(value)) === '[object Array]') { + for (i = 0, l = value.length; i < l; i++) { + if (value[i] !== undefined && value[i] !== null) { + // arrays don't have names + d.val.push([undefined, String(value[i])]); + } + } + + if (d.val.length) { + // only treat non-empty arrays as arrays + d.type = 3; // array + } + } else if (String(Object.prototype.toString.call(value)) === '[object Object]') { + for (i in value) { + if (hasOwn.call(value, i) && value[i] !== undefined && value[i] !== null) { + // objects have keys, remember them for named expansion + d.val.push([i, String(value[i])]); + } + } + + if (d.val.length) { + // only treat non-empty objects as objects + d.type = 2; // object + } + } else { + d.type = 1; // primitive string (could've been string, number, boolean and objects with a toString()) + // arrays don't have names + d.val.push([undefined, String(value)]); + } + + return d; + }; + + // hook into URI for fluid access + URI.expand = function(expression, data) { + var template = new URITemplate(expression); + var expansion = template.expand(data); + + return new URI(expansion); + }; + + return URITemplate; +})); diff --git a/node_modules/urijs/src/jquery.URI.js b/node_modules/urijs/src/jquery.URI.js new file mode 100644 index 000000000..162ae55f7 --- /dev/null +++ b/node_modules/urijs/src/jquery.URI.js @@ -0,0 +1,234 @@ +/*! + * URI.js - Mutating URLs + * jQuery Plugin + * + * Version: 1.19.11 + * + * Author: Rodney Rehm + * Web: http://medialize.github.io/URI.js/jquery-uri-plugin.html + * + * Licensed under + * MIT License http://www.opensource.org/licenses/mit-license + * + */ +(function (root, factory) { + 'use strict'; + // https://github.com/umdjs/umd/blob/master/returnExports.js + if (typeof module === 'object' && module.exports) { + // Node + module.exports = factory(require('jquery'), require('./URI')); + } else if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['jquery', './URI'], factory); + } else { + // Browser globals (root is window) + factory(root.jQuery, root.URI); + } +}(this, function ($, URI) { + 'use strict'; + // FIXME: v2.0.0 renamce non-camelCase properties to uppercase + /*jshint camelcase: false */ + + var comparable = {}; + var compare = { + // equals + '=': function(value, target) { + return value === target; + }, + // ~= translates to value.match((?:^|\s)target(?:\s|$)) which is useless for URIs + // |= translates to value.match((?:\b)target(?:-|\s|$)) which is useless for URIs + // begins with + '^=': function(value, target) { + return !!(value + '').match(new RegExp('^' + escapeRegEx(target), 'i')); + }, + // ends with + '$=': function(value, target) { + return !!(value + '').match(new RegExp(escapeRegEx(target) + '$', 'i')); + }, + // contains + '*=': function(value, target, property) { + if (property === 'directory') { + // add trailing slash so /dir/ will match the deep-end as well + value += '/'; + } + + return !!(value + '').match(new RegExp(escapeRegEx(target), 'i')); + }, + 'equals:': function(uri, target) { + return uri.equals(target); + }, + 'is:': function(uri, target) { + return uri.is(target); + } + }; + + function escapeRegEx(string) { + // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963 + return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); + } + + function getUriProperty(elem) { + var nodeName = elem.nodeName.toLowerCase(); + var property = URI.domAttributes[nodeName]; + if (nodeName === 'input' && elem.type !== 'image') { + // compensate ambiguous that is not an image + return undefined; + } + + // NOTE: as we use a static mapping from element to attribute, + // the HTML5 attribute issue should not come up again + // https://github.com/medialize/URI.js/issues/69 + return property; + } + + function generateAccessor(property) { + return { + get: function(elem) { + return $(elem).uri()[property](); + }, + set: function(elem, value) { + $(elem).uri()[property](value); + return value; + } + }; + } + + // populate lookup table and register $.attr('uri:accessor') handlers + $.each('origin authority directory domain filename fragment hash host hostname href password path pathname port protocol query resource scheme search subdomain suffix tld username'.split(' '), function(k, v) { + comparable[v] = true; + $.attrHooks['uri:' + v] = generateAccessor(v); + }); + + // pipe $.attr('src') and $.attr('href') through URI.js + var _attrHooks = { + get: function(elem) { + return $(elem).uri(); + }, + set: function(elem, value) { + return $(elem).uri().href(value).toString(); + } + }; + $.each(['src', 'href', 'action', 'uri', 'cite'], function(k, v) { + $.attrHooks[v] = { + set: _attrHooks.set + }; + }); + $.attrHooks.uri.get = _attrHooks.get; + + // general URI accessor + $.fn.uri = function(uri) { + var $this = this.first(); + var elem = $this.get(0); + var property = getUriProperty(elem); + + if (!property) { + throw new Error('Element "' + elem.nodeName + '" does not have either property: href, src, action, cite'); + } + + if (uri !== undefined) { + var old = $this.data('uri'); + if (old) { + return old.href(uri); + } + + if (!(uri instanceof URI)) { + uri = URI(uri || ''); + } + } else { + uri = $this.data('uri'); + if (uri) { + return uri; + } else { + uri = URI($this.attr(property) || ''); + } + } + + uri._dom_element = elem; + uri._dom_attribute = property; + uri.normalize(); + $this.data('uri', uri); + return uri; + }; + + // overwrite URI.build() to update associated DOM element if necessary + URI.prototype.build = function(deferBuild) { + if (this._dom_element) { + // cannot defer building when hooked into a DOM element + this._string = URI.build(this._parts); + this._deferred_build = false; + this._dom_element.setAttribute(this._dom_attribute, this._string); + this._dom_element[this._dom_attribute] = this._string; + } else if (deferBuild === true) { + this._deferred_build = true; + } else if (deferBuild === undefined || this._deferred_build) { + this._string = URI.build(this._parts); + this._deferred_build = false; + } + + return this; + }; + + // add :uri() pseudo class selector to sizzle + var uriSizzle; + var pseudoArgs = /^([a-zA-Z]+)\s*([\^\$*]?=|:)\s*(['"]?)(.+)\3|^\s*([a-zA-Z0-9]+)\s*$/; + function uriPseudo (elem, text) { + var match, property, uri; + + // skip anything without src|href|action and bad :uri() syntax + if (!getUriProperty(elem) || !text) { + return false; + } + + match = text.match(pseudoArgs); + + if (!match || (!match[5] && match[2] !== ':' && !compare[match[2]])) { + // abort because the given selector cannot be executed + // filers seem to fail silently + return false; + } + + uri = $(elem).uri(); + + if (match[5]) { + return uri.is(match[5]); + } else if (match[2] === ':') { + property = match[1].toLowerCase() + ':'; + if (!compare[property]) { + // filers seem to fail silently + return false; + } + + return compare[property](uri, match[4]); + } else { + property = match[1].toLowerCase(); + if (!comparable[property]) { + // filers seem to fail silently + return false; + } + + return compare[match[2]](uri[property](), match[4], property); + } + + return false; + } + + if ($.expr.createPseudo) { + // jQuery >= 1.8 + uriSizzle = $.expr.createPseudo(function (text) { + return function (elem) { + return uriPseudo(elem, text); + }; + }); + } else { + // jQuery < 1.8 + uriSizzle = function (elem, i, match) { + return uriPseudo(elem, match[3]); + }; + } + + $.expr[':'].uri = uriSizzle; + + // extending existing object rather than defining something new, + // return jQuery anyway + return $; +})); diff --git a/node_modules/urijs/src/jquery.URI.min.js b/node_modules/urijs/src/jquery.URI.min.js new file mode 100644 index 000000000..f2c785066 --- /dev/null +++ b/node_modules/urijs/src/jquery.URI.min.js @@ -0,0 +1,7 @@ +/*! URI.js v1.19.11 http://medialize.github.io/URI.js/ */ +/* build contains: jquery.URI.js */ +(function(d,e){"object"===typeof module&&module.exports?module.exports=e(require("jquery"),require("./URI")):"function"===typeof define&&define.amd?define(["jquery","./URI"],e):e(d.jQuery,d.URI)})(this,function(d,e){function k(a){return a.replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")}function l(a){var b=a.nodeName.toLowerCase();if("input"!==b||"image"===a.type)return e.domAttributes[b]}function p(a){return{get:function(b){return d(b).uri()[a]()},set:function(b,c){d(b).uri()[a](c);return c}}}function m(a, + b){if(!l(a)||!b)return!1;var c=b.match(q);if(!c||!c[5]&&":"!==c[2]&&!h[c[2]])return!1;var g=d(a).uri();if(c[5])return g.is(c[5]);if(":"===c[2]){var f=c[1].toLowerCase()+":";return h[f]?h[f](g,c[4]):!1}f=c[1].toLowerCase();return n[f]?h[c[2]](g[f](),c[4],f):!1}var n={},h={"=":function(a,b){return a===b},"^=":function(a,b){return!!(a+"").match(new RegExp("^"+k(b),"i"))},"$=":function(a,b){return!!(a+"").match(new RegExp(k(b)+"$","i"))},"*=":function(a,b,c){"directory"===c&&(a+="/");return!!(a+"").match(new RegExp(k(b), + "i"))},"equals:":function(a,b){return a.equals(b)},"is:":function(a,b){return a.is(b)}};d.each("origin authority directory domain filename fragment hash host hostname href password path pathname port protocol query resource scheme search subdomain suffix tld username".split(" "),function(a,b){n[b]=!0;d.attrHooks["uri:"+b]=p(b)});var r=function(a,b){return d(a).uri().href(b).toString()};d.each(["src","href","action","uri","cite"],function(a,b){d.attrHooks[b]={set:r}});d.attrHooks.uri.get=function(a){return d(a).uri()}; + d.fn.uri=function(a){var b=this.first(),c=b.get(0),g=l(c);if(!g)throw Error('Element "'+c.nodeName+'" does not have either property: href, src, action, cite');if(void 0!==a){var f=b.data("uri");if(f)return f.href(a);a instanceof e||(a=e(a||""))}else{if(a=b.data("uri"))return a;a=e(b.attr(g)||"")}a._dom_element=c;a._dom_attribute=g;a.normalize();b.data("uri",a);return a};e.prototype.build=function(a){if(this._dom_element)this._string=e.build(this._parts),this._deferred_build=!1,this._dom_element.setAttribute(this._dom_attribute, + this._string),this._dom_element[this._dom_attribute]=this._string;else if(!0===a)this._deferred_build=!0;else if(void 0===a||this._deferred_build)this._string=e.build(this._parts),this._deferred_build=!1;return this};var q=/^([a-zA-Z]+)\s*([\^\$*]?=|:)\s*(['"]?)(.+)\3|^\s*([a-zA-Z0-9]+)\s*$/;var t=d.expr.createPseudo?d.expr.createPseudo(function(a){return function(b){return m(b,a)}}):function(a,b,c){return m(a,c[3])};d.expr[":"].uri=t;return d}); diff --git a/node_modules/urijs/src/punycode.js b/node_modules/urijs/src/punycode.js new file mode 100644 index 000000000..0b4f5da35 --- /dev/null +++ b/node_modules/urijs/src/punycode.js @@ -0,0 +1,533 @@ +/*! https://mths.be/punycode v1.4.0 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 000000000..3c14b88c7 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,380 @@ +{ + "name": "solang", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "@stellar/stellar-sdk": "^13.1.0", + "chai": "^5.1.2", + "setup": "^0.0.3" + } + }, + "node_modules/@stellar/js-xdr": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@stellar/js-xdr/-/js-xdr-3.1.2.tgz", + "integrity": "sha512-VVolPL5goVEIsvuGqDc5uiKxV03lzfWdvYg1KikvwheDmTBO68CKDji3bAZ/kppZrx5iTA8z3Ld5yuytcvhvOQ==" + }, + "node_modules/@stellar/stellar-base": { + "version": "13.0.1", + "resolved": "https://registry.npmjs.org/@stellar/stellar-base/-/stellar-base-13.0.1.tgz", + "integrity": "sha512-Xbd12mc9Oj/130Tv0URmm3wXG77XMshZtZ2yNCjqX5ZbMD5IYpbBs3DVCteLU/4SLj/Fnmhh1dzhrQXnk4r+pQ==", + "dependencies": { + "@stellar/js-xdr": "^3.1.2", + "base32.js": "^0.1.0", + "bignumber.js": "^9.1.2", + "buffer": "^6.0.3", + "sha.js": "^2.3.6", + "tweetnacl": "^1.0.3" + }, + "optionalDependencies": { + "sodium-native": "^4.3.0" + } + }, + "node_modules/@stellar/stellar-sdk": { + "version": "13.1.0", + "resolved": "https://registry.npmjs.org/@stellar/stellar-sdk/-/stellar-sdk-13.1.0.tgz", + "integrity": "sha512-ARQkUdyGefXdTgwSF0eONkzv/geAqUfyfheJ9Nthz6GAr5b41fNwWW9UtE8JpXC4IpvE3t5elIUN5hKJzASN9w==", + "dependencies": { + "@stellar/stellar-base": "^13.0.1", + "axios": "^1.7.9", + "bignumber.js": "^9.1.2", + "eventsource": "^2.0.2", + "feaxios": "^0.0.23", + "randombytes": "^2.1.0", + "toml": "^3.0.0", + "urijs": "^1.19.1" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "engines": { + "node": ">=12" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/axios": { + "version": "1.7.9", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz", + "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/base32.js": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/base32.js/-/base32.js-0.1.0.tgz", + "integrity": "sha512-n3TkB02ixgBOhTvANakDb4xaMXnYUVkNoRFJjQflcqMQhyEKxEHdj3E6N8t8sUQ0mjH/3/JxzlXuz3ul/J90pQ==", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/bignumber.js": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.1.2.tgz", + "integrity": "sha512-2/mKyZH9K85bzOEfhXDBFZTGd1CTs+5IHpeFQo9luiBG7hghdC851Pj2WAhb6E3R6b9tZj/XKhbg4fum+Kepug==", + "engines": { + "node": "*" + } + }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/chai": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.1.2.tgz", + "integrity": "sha512-aGtmf24DW6MLHHG5gCx4zaI3uBq3KRtxeVs0DjFH6Z0rDNbsvTxFASFvdj79pxjxZ8/5u3PIiN3IwEIQkiiuPw==", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/check-error": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.1.tgz", + "integrity": "sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==", + "engines": { + "node": ">= 16" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "engines": { + "node": ">=6" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/eventsource": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-2.0.2.tgz", + "integrity": "sha512-IzUmBGPR3+oUG9dUeXynyNmf91/3zUSJg1lCktzKw47OXuhco54U3r9B7O4XX+Rb1Itm9OZ2b0RkTs10bICOxA==", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/feaxios": { + "version": "0.0.23", + "resolved": "https://registry.npmjs.org/feaxios/-/feaxios-0.0.23.tgz", + "integrity": "sha512-eghR0A21fvbkcQBgZuMfQhrXxJzC0GNUGC9fXhBge33D+mFDTwl0aJ35zoQQn575BhyjQitRc5N4f+L4cP708g==", + "dependencies": { + "is-retry-allowed": "^3.0.0" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz", + "integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/is-retry-allowed": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-3.0.0.tgz", + "integrity": "sha512-9xH0xvoggby+u0uGF7cZXdrutWiBiaFG8ZT4YFPXL8NzkyAwX3AKGLeFQLvzDpM430+nDFBZ1LHkie/8ocL06A==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/loupe": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.1.2.tgz", + "integrity": "sha512-23I4pFZHmAemUnz8WZXbYRSKYj801VDaNv9ETuMh7IrMc7VuVVSo+Z9iLE3ni30+U48iDWfi30d3twAXBYmnCg==" + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-gyp-build": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", + "optional": true, + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/pathval": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.0.tgz", + "integrity": "sha512-vE7JKRyES09KiunauX7nd2Q9/L7lhok4smP9RZTDeD4MVs72Dp2qNFVz39Nz5a0FVEW0BJR6C0DYrq6unoziZA==", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "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" + } + ] + }, + "node_modules/setup": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/setup/-/setup-0.0.3.tgz", + "integrity": "sha512-NcuGT1k9V3jdwcNdZzpnO6h2WtLMieaIVRMWeQvlSVRMB6b51T3jeUBSeBzP5Mmqy50viW5y7LRaMaTm/MZ4CA==" + }, + "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==", + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + }, + "bin": { + "sha.js": "bin.js" + } + }, + "node_modules/sodium-native": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/sodium-native/-/sodium-native-4.3.1.tgz", + "integrity": "sha512-YdP64gAdpIKHfL4ttuX4aIfjeunh9f+hNeQJpE9C8UMndB3zkgZ7YmmGT4J2+v6Ibyp6Wem8D1TcSrtdW0bqtg==", + "optional": true, + "dependencies": { + "node-gyp-build": "^4.8.0" + } + }, + "node_modules/toml": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/toml/-/toml-3.0.0.tgz", + "integrity": "sha512-y/mWCZinnvxjTKYhJ+pYxwD0mRLVvOtdS2Awbgxln6iEnt4rk0yBxeSBHkGJcPucRiG0e55mwWp+g/05rsrd6w==" + }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==" + }, + "node_modules/urijs": { + "version": "1.19.11", + "resolved": "https://registry.npmjs.org/urijs/-/urijs-1.19.11.tgz", + "integrity": "sha512-HXgFDgDommxn5/bIv0cnQZsPhHDA90NPHD6+c/v21U5+Sx5hoP8+dP9IZXBU1gIfvdRfhG8cel9QNPeionfcCQ==" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 000000000..a5e578783 --- /dev/null +++ b/package.json @@ -0,0 +1,7 @@ +{ + "dependencies": { + "@stellar/stellar-sdk": "^13.1.0", + "chai": "^5.1.2", + "setup": "^0.0.3" + } +} diff --git a/src/codegen/.DS_Store b/src/codegen/.DS_Store new file mode 100644 index 000000000..5eedb93c3 Binary files /dev/null and b/src/codegen/.DS_Store differ diff --git a/src/codegen/dispatch/soroban.rs b/src/codegen/dispatch/soroban.rs index 58520b9b3..9e4f37936 100644 --- a/src/codegen/dispatch/soroban.rs +++ b/src/codegen/dispatch/soroban.rs @@ -1,9 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 +use anchor_syn::Ty; use num_bigint::BigInt; use solang_parser::pt::{self}; -use crate::sema::ast; +use crate::sema::ast::{self, Function}; use crate::{ codegen::{ cfg::{ASTFunction, ControlFlowGraph, Instr, InternalCallTy}, @@ -54,6 +55,7 @@ pub fn function_dispatch( wrapper_cfg.returns = vec![return_type].into(); wrapper_cfg.public = true; + wrapper_cfg.function_no = cfg.function_no.clone(); let mut vartab = Vartable::from_symbol_table(&function.symtable, ns.next_id); @@ -80,41 +82,88 @@ pub fn function_dispatch( res: call_returns, call: InternalCallTy::Static { cfg_no }, return_tys, - args: function - .params - .iter() - .enumerate() - .map(|(i, p)| Expression::ShiftRight { - loc: pt::Loc::Codegen, - ty: Type::Uint(64), - left: Expression::FunctionArg { - loc: p.loc, - ty: p.ty.clone(), - arg_no: i, - } - .into(), - right: Expression::NumberLiteral { - loc: pt::Loc::Codegen, - ty: Type::Uint(64), - value: BigInt::from(8_u64), - } - .into(), - - signed: false, - }) - .collect(), + args: decode_args(function, ns), }; wrapper_cfg.add(&mut vartab, placeholder); // TODO: support multiple returns if value.len() == 1 { - // set the msb 8 bits of the return value to 6, the return value is 64 bits. - // FIXME: this assumes that the solidity function always returns one value. + let added = encode_return(function, value[0].clone()); + wrapper_cfg.add(&mut vartab, Instr::Return { value: vec![added] }); + } else { + // Return 2 as numberliteral. 2 is the soroban Void type encoded. + let two = Expression::NumberLiteral { + loc: pt::Loc::Codegen, + ty: Type::Uint(64), + value: BigInt::from(2_u64), + }; + + wrapper_cfg.add(&mut vartab, Instr::Return { value: vec![two] }); + } + + vartab.finalize(ns, &mut wrapper_cfg); + cfg.public = false; + wrapper_cfgs.push(wrapper_cfg); + } + + wrapper_cfgs +} + +fn decode_args(function: &Function, ns: &Namespace) -> Vec { + let mut args = Vec::new(); + + for (i, arg) in function.params.iter().enumerate() { + println!("ARGUMENTS {:?}", arg); + + let arg = match arg.ty { + Type::Uint(64) | Type::Uint(32) => Expression::ShiftRight { + loc: arg.loc, + ty: Type::Uint(64), + left: Box::new(Expression::FunctionArg { + loc: arg.loc, + ty: arg.ty.clone(), + arg_no: i, + }), + right: Box::new(Expression::NumberLiteral { + loc: arg.loc, + ty: Type::Uint(64), + value: BigInt::from(8_u64), + }), + signed: false, + }, + Type::Address(_) => Expression::FunctionArg { + loc: arg.loc, + ty: arg.ty.clone(), + arg_no: i, + } + .cast(&Type::Address(false), ns), + + // FIXME: Should properly decode the value instead of just passing it + Type::Uint(128) | Type::Int(128) => Expression::FunctionArg { + loc: arg.loc, + ty: arg.ty.clone(), + arg_no: i, + }, + + _ => unimplemented!(), + }; + + args.push(arg); + } + + args +} + +// TODO: Implement for UINT32 +fn encode_return(function: &Function, value: Expression) -> Expression { + let returned = function.returns[0].clone(); + match returned.ty { + Type::Uint(64) => { let shifted = Expression::ShiftLeft { loc: pt::Loc::Codegen, ty: Type::Uint(64), - left: value[0].clone().into(), + left: value.clone().into(), right: Expression::NumberLiteral { loc: pt::Loc::Codegen, ty: Type::Uint(64), @@ -137,22 +186,39 @@ pub fn function_dispatch( right: tag.into(), }; - wrapper_cfg.add(&mut vartab, Instr::Return { value: vec![added] }); - } else { - // Return 2 as numberliteral. 2 is the soroban Void type encoded. - let two = Expression::NumberLiteral { + added + } + + // TODO: support UINT32 here + Type::Uint(32) => { + let shifted = Expression::ShiftLeft { loc: pt::Loc::Codegen, ty: Type::Uint(64), - value: BigInt::from(2_u64), + left: value.clone().into(), + right: Expression::NumberLiteral { + loc: pt::Loc::Codegen, + ty: Type::Uint(64), + value: BigInt::from(8_u64), + } + .into(), }; - wrapper_cfg.add(&mut vartab, Instr::Return { value: vec![two] }); - } + let tag = Expression::NumberLiteral { + loc: pt::Loc::Codegen, + ty: Type::Uint(64), + value: BigInt::from(4_u64), + }; - vartab.finalize(ns, &mut wrapper_cfg); - cfg.public = false; - wrapper_cfgs.push(wrapper_cfg); - } + let added = Expression::Add { + loc: pt::Loc::Codegen, + ty: Type::Uint(64), + overflowing: true, + left: shifted.into(), + right: tag.into(), + }; - wrapper_cfgs + added + } + _ => unimplemented!(), + } } diff --git a/src/emit/binary.rs b/src/emit/binary.rs index 1e7dd9cdf..e419e0632 100644 --- a/src/emit/binary.rs +++ b/src/emit/binary.rs @@ -8,6 +8,7 @@ use std::cell::RefCell; use std::path::Path; use std::str; +use libc::uint32_t; use num_bigint::BigInt; use num_traits::ToPrimitive; use std::collections::HashMap; @@ -930,8 +931,14 @@ impl<'a> Binary<'a> { match ty { Type::Bool => BasicTypeEnum::IntType(self.context.bool_type()), Type::Int(n) | Type::Uint(n) => { - BasicTypeEnum::IntType(self.context.custom_width_int_type(*n as u32)) + if ns.target == Target::Soroban { + //ahmads edit testing if this work.... + BasicTypeEnum::IntType(self.context.i64_type()) + } else { + BasicTypeEnum::IntType(self.context.custom_width_int_type(*n as u32)) + } } + Type::Value => BasicTypeEnum::IntType( self.context .custom_width_int_type(ns.value_length as u32 * 8), diff --git a/src/emit/soroban/mod.rs b/src/emit/soroban/mod.rs index 71a24a933..323f05459 100644 --- a/src/emit/soroban/mod.rs +++ b/src/emit/soroban/mod.rs @@ -174,8 +174,12 @@ impl SorobanTarget { .unwrap_or_else(|| i.to_string()) .try_into() .expect("function input name exceeds limit"), - type_: ScSpecTypeDef::U64, // TODO: Map type. - doc: StringM::default(), // TODO: Add doc. + type_: match p.ty { + ast::Type::Uint(64) => ScSpecTypeDef::U64, + ast::Type::Uint(32) => ScSpecTypeDef::U32, + _ => panic!("unsupported input type"), + }, // TODO: Map type. + doc: StringM::default(), // TODO: Add doc. }) .collect::>() .try_into() diff --git a/test_snapshots/soroban_testcases/storage/counter.1.json b/test_snapshots/soroban_testcases/storage/counter.1.json deleted file mode 100644 index 6f7a5073e..000000000 --- a/test_snapshots/soroban_testcases/storage/counter.1.json +++ /dev/null @@ -1,163 +0,0 @@ -{ - "generators": { - "address": 1, - "nonce": 0 - }, - "auth": [ - [], - [], - [], - [], - [] - ], - "ledger": { - "protocol_version": 22, - "sequence_number": 0, - "timestamp": 0, - "network_id": "0000000000000000000000000000000000000000000000000000000000000000", - "base_reserve": 0, - "min_persistent_entry_ttl": 4096, - "min_temp_entry_ttl": 16, - "max_entry_ttl": 6312000, - "ledger_entries": [ - [ - { - "contract_data": { - "contract": "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM", - "key": { - "ledger_key_nonce": { - "nonce": 801925984706572462 - } - }, - "durability": "temporary" - } - }, - [ - { - "last_modified_ledger_seq": 0, - "data": { - "contract_data": { - "ext": "v0", - "contract": "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM", - "key": { - "ledger_key_nonce": { - "nonce": 801925984706572462 - } - }, - "durability": "temporary", - "val": "void" - } - }, - "ext": "v0" - }, - 6311999 - ] - ], - [ - { - "contract_data": { - "contract": "CBKMUZNFQIAL775XBB2W2GP5CNHBM5YGH6C3XB7AY6SUVO2IBU3VYK2V", - "key": { - "bool": false - }, - "durability": "persistent" - } - }, - [ - { - "last_modified_ledger_seq": 0, - "data": { - "contract_data": { - "ext": "v0", - "contract": "CBKMUZNFQIAL775XBB2W2GP5CNHBM5YGH6C3XB7AY6SUVO2IBU3VYK2V", - "key": { - "bool": false - }, - "durability": "persistent", - "val": { - "u128": { - "hi": 0, - "lo": 0 - } - } - } - }, - "ext": "v0" - }, - 4095 - ] - ], - [ - { - "contract_data": { - "contract": "CBKMUZNFQIAL775XBB2W2GP5CNHBM5YGH6C3XB7AY6SUVO2IBU3VYK2V", - "key": "ledger_key_contract_instance", - "durability": "persistent" - } - }, - [ - { - "last_modified_ledger_seq": 0, - "data": { - "contract_data": { - "ext": "v0", - "contract": "CBKMUZNFQIAL775XBB2W2GP5CNHBM5YGH6C3XB7AY6SUVO2IBU3VYK2V", - "key": "ledger_key_contract_instance", - "durability": "persistent", - "val": { - "contract_instance": { - "executable": { - "wasm": "491b95249a0a04c1f39cdef85507db307713a9db2e9c422a33dac1c44e6ac17c" - }, - "storage": null - } - } - } - }, - "ext": "v0" - }, - 4095 - ] - ], - [ - { - "contract_code": { - "hash": "491b95249a0a04c1f39cdef85507db307713a9db2e9c422a33dac1c44e6ac17c" - } - }, - [ - { - "last_modified_ledger_seq": 0, - "data": { - "contract_code": { - "ext": { - "v1": { - "ext": "v0", - "cost_inputs": { - "ext": "v0", - "n_instructions": 91, - "n_functions": 5, - "n_globals": 1, - "n_table_entries": 0, - "n_types": 5, - "n_data_segments": 1, - "n_elem_segments": 0, - "n_imports": 3, - "n_exports": 6, - "n_data_segment_bytes": 115 - } - } - }, - "hash": "491b95249a0a04c1f39cdef85507db307713a9db2e9c422a33dac1c44e6ac17c", - "code": "0061736d01000000011d0560027e7e017e60047e7e7e7e017e60037e7e7e017e6000006000017e021303016c013100000178015f0001016c015f0002030605030404040405030100020609017f01418080c0000b076406066d656d6f7279020027636f756e7465723a3a636f756e7465723a3a636f6e7374727563746f723a3a3836313733316435000305636f756e74000409696e6372656d656e7400050964656372656d656e7400060d5f5f636f6e7374727563746f7200070ae1010502000b1200420042011080808080004208864206840b5a01017e02404200420110808080800042017c22004200520d00418088808000ad42208642048422004284808080a006200042041081808080001a000b4200200042011082808080001a420042011080808080004208864206840b5c01027e0240420042011080808080002200427f7c22012000580d0041c088808000ad42208642048422004284808080b006200042041081808080001a000b4200200142011082808080001a420042011080808080004208864206840b11004200420a42011082808080001a42020b0b7a01004180080b7372756e74696d655f6572726f723a206d617468206f766572666c6f7720696e20746573742e736f6c3a353a31372d32372c0a000000000000000000000000000072756e74696d655f6572726f723a206d617468206f766572666c6f7720696e20746573742e736f6c3a31303a31372d32372c0a001e11636f6e7472616374656e766d657461763000000000000000160000000000bf010e636f6e747261637473706563763000000000000000000000000b636f6e7374727563746f72000000000000000000000000000000000000000005636f756e74000000000000000000000100000006000000000000000000000009696e6372656d656e7400000000000000000000010000000600000000000000000000000964656372656d656e7400000000000000000000010000000600000000000000000000000d5f5f636f6e7374727563746f72000000000000000000000100000002008c01046e616d6501650800036c2e310103782e5f02036c2e5f0327636f756e7465723a3a636f756e7465723a3a636f6e7374727563746f723a3a38363137333164350405636f756e740509696e6372656d656e74060964656372656d656e74070d5f5f636f6e7374727563746f72071201000f5f5f737461636b5f706f696e746572090a0100072e726f64617461008e010970726f64756365727302086c616e6775616765010143000c70726f6365737365642d62790105636c616e676131362e302e35202868747470733a2f2f6769746875622e636f6d2f736f6c616e612d6c6162732f6c6c766d2d70726f6a6563742e676974203033386434373262636430623832666637363862353135636337376466623165336133393663613829002c0f7461726765745f6665617475726573022b0f6d757461626c652d676c6f62616c732b087369676e2d657874" - } - }, - "ext": "v0" - }, - 4095 - ] - ] - ] - }, - "events": [] -} \ No newline at end of file diff --git a/test_snapshots/soroban_testcases/storage/different_storage_types.1.json b/test_snapshots/soroban_testcases/storage/different_storage_types.1.json deleted file mode 100644 index 6262cbf63..000000000 --- a/test_snapshots/soroban_testcases/storage/different_storage_types.1.json +++ /dev/null @@ -1,236 +0,0 @@ -{ - "generators": { - "address": 1, - "nonce": 0 - }, - "auth": [ - [], - [], - [], - [], - [], - [], - [], - [], - [], - [], - [], - [], - [], - [] - ], - "ledger": { - "protocol_version": 22, - "sequence_number": 0, - "timestamp": 0, - "network_id": "0000000000000000000000000000000000000000000000000000000000000000", - "base_reserve": 0, - "min_persistent_entry_ttl": 4096, - "min_temp_entry_ttl": 16, - "max_entry_ttl": 6312000, - "ledger_entries": [ - [ - { - "contract_data": { - "contract": "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM", - "key": { - "ledger_key_nonce": { - "nonce": 801925984706572462 - } - }, - "durability": "temporary" - } - }, - [ - { - "last_modified_ledger_seq": 0, - "data": { - "contract_data": { - "ext": "v0", - "contract": "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM", - "key": { - "ledger_key_nonce": { - "nonce": 801925984706572462 - } - }, - "durability": "temporary", - "val": "void" - } - }, - "ext": "v0" - }, - 6311999 - ] - ], - [ - { - "contract_data": { - "contract": "CBKMUZNFQIAL775XBB2W2GP5CNHBM5YGH6C3XB7AY6SUVO2IBU3VYK2V", - "key": { - "bool": false - }, - "durability": "temporary" - } - }, - [ - { - "last_modified_ledger_seq": 0, - "data": { - "contract_data": { - "ext": "v0", - "contract": "CBKMUZNFQIAL775XBB2W2GP5CNHBM5YGH6C3XB7AY6SUVO2IBU3VYK2V", - "key": { - "bool": false - }, - "durability": "temporary", - "val": { - "bool": true - } - } - }, - "ext": "v0" - }, - 15 - ] - ], - [ - { - "contract_data": { - "contract": "CBKMUZNFQIAL775XBB2W2GP5CNHBM5YGH6C3XB7AY6SUVO2IBU3VYK2V", - "key": "void", - "durability": "persistent" - } - }, - [ - { - "last_modified_ledger_seq": 0, - "data": { - "contract_data": { - "ext": "v0", - "contract": "CBKMUZNFQIAL775XBB2W2GP5CNHBM5YGH6C3XB7AY6SUVO2IBU3VYK2V", - "key": "void", - "durability": "persistent", - "val": "void" - } - }, - "ext": "v0" - }, - 4095 - ] - ], - [ - { - "contract_data": { - "contract": "CBKMUZNFQIAL775XBB2W2GP5CNHBM5YGH6C3XB7AY6SUVO2IBU3VYK2V", - "key": { - "error": { - "contract": 0 - } - }, - "durability": "persistent" - } - }, - [ - { - "last_modified_ledger_seq": 0, - "data": { - "contract_data": { - "ext": "v0", - "contract": "CBKMUZNFQIAL775XBB2W2GP5CNHBM5YGH6C3XB7AY6SUVO2IBU3VYK2V", - "key": { - "error": { - "contract": 0 - } - }, - "durability": "persistent", - "val": "void" - } - }, - "ext": "v0" - }, - 4095 - ] - ], - [ - { - "contract_data": { - "contract": "CBKMUZNFQIAL775XBB2W2GP5CNHBM5YGH6C3XB7AY6SUVO2IBU3VYK2V", - "key": "ledger_key_contract_instance", - "durability": "persistent" - } - }, - [ - { - "last_modified_ledger_seq": 0, - "data": { - "contract_data": { - "ext": "v0", - "contract": "CBKMUZNFQIAL775XBB2W2GP5CNHBM5YGH6C3XB7AY6SUVO2IBU3VYK2V", - "key": "ledger_key_contract_instance", - "durability": "persistent", - "val": { - "contract_instance": { - "executable": { - "wasm": "2cbf08be172731c4b4fa9318600f13b7fc00c2082ab6601bf4c736406fc5c528" - }, - "storage": [ - { - "key": { - "bool": true - }, - "val": { - "bool": true - } - } - ] - } - } - } - }, - "ext": "v0" - }, - 4095 - ] - ], - [ - { - "contract_code": { - "hash": "2cbf08be172731c4b4fa9318600f13b7fc00c2082ab6601bf4c736406fc5c528" - } - }, - [ - { - "last_modified_ledger_seq": 0, - "data": { - "contract_code": { - "ext": { - "v1": { - "ext": "v0", - "cost_inputs": { - "ext": "v0", - "n_instructions": 293, - "n_functions": 8, - "n_globals": 1, - "n_table_entries": 0, - "n_types": 5, - "n_data_segments": 1, - "n_elem_segments": 0, - "n_imports": 3, - "n_exports": 9, - "n_data_segment_bytes": 498 - } - } - }, - "hash": "2cbf08be172731c4b4fa9318600f13b7fc00c2082ab6601bf4c736406fc5c528", - "code": "0061736d01000000011d0560027e7e017e60037e7e7e017e60047e7e7e7e017e6000006000017e021303016c01310000016c015f00010178015f0002030908030404040404040405030100020609017f01418080c0000b076909066d656d6f7279020021736573613a3a736573613a3a636f6e7374727563746f723a3a383631373331643500030473657361000405736573613100050573657361320006057365736133000703696e6300080364656300090d5f5f636f6e7374727563746f72000a0acb050802000b1200420042001080808080004208864206840b1200420142021080808080004208864206840b1200420242011080808080004208864206840b1200420342011080808080004208864206840b970201017e02400240024002404200420010808080800042017c2200500d004200200042001081808080001a4201420210808080800042017c2200500d014201200042021081808080001a4202420110808080800042017c2200500d024202200042011081808080001a4203420110808080800042017c2200500d034203200042011081808080001a42020f0b418088808000ad422086420484220042848080809006200042041082808080001a000b41c088808000ad42208642048422004284808080a006200042041082808080001a000b418089808000ad42208642048422004284808080a006200042041082808080001a000b41c089808000ad42208642048422004284808080a006200042041082808080001a000ba70201027e0240024002400240420042001080808080002200427f7c22012000560d004200200142001081808080001a420142021080808080002200427f7c22012000560d014201200142021081808080001a420242011080808080002200427f7c22012000560d024202200142011081808080001a420342011080808080002200427f7c22012000560d034203200142011081808080001a42020f0b41808a808000ad42208642048422004284808080a006200042041082808080001a000b41c08a808000ad42208642048422004284808080a006200042041082808080001a000b41808b808000ad42208642048422004284808080a006200042041082808080001a000b41c08b808000ad42208642048422004284808080a006200042041082808080001a000b38004200420142001081808080001a4201420142021081808080001a4202420242011081808080001a4203420242011081808080001a42020b0bfa0301004180080bf20372756e74696d655f6572726f723a206d617468206f766572666c6f7720696e20746573742e736f6c3a393a392d31352c0a00000000000000000000000000000072756e74696d655f6572726f723a206d617468206f766572666c6f7720696e20746573742e736f6c3a31303a392d31362c0a000000000000000000000000000072756e74696d655f6572726f723a206d617468206f766572666c6f7720696e20746573742e736f6c3a31313a392d31362c0a000000000000000000000000000072756e74696d655f6572726f723a206d617468206f766572666c6f7720696e20746573742e736f6c3a31323a392d31362c0a000000000000000000000000000072756e74696d655f6572726f723a206d617468206f766572666c6f7720696e20746573742e736f6c3a31363a392d31352c0a000000000000000000000000000072756e74696d655f6572726f723a206d617468206f766572666c6f7720696e20746573742e736f6c3a31373a392d31362c0a000000000000000000000000000072756e74696d655f6572726f723a206d617468206f766572666c6f7720696e20746573742e736f6c3a31383a392d31362c0a000000000000000000000000000072756e74696d655f6572726f723a206d617468206f766572666c6f7720696e20746573742e736f6c3a31393a392d31362c0a001e11636f6e7472616374656e766d6574617630000000000000001600000000008b020e636f6e747261637473706563763000000000000000000000000b636f6e7374727563746f7200000000000000000000000000000000000000000473657361000000000000000100000006000000000000000000000005736573613100000000000000000000010000000600000000000000000000000573657361320000000000000000000001000000060000000000000000000000057365736133000000000000000000000100000006000000000000000000000003696e63000000000000000001000000020000000000000000000000036465630000000000000000010000000200000000000000000000000d5f5f636f6e7374727563746f72000000000000000000000100000002008e01046e616d6501670b00036c2e3101036c2e5f0203782e5f0321736573613a3a736573613a3a636f6e7374727563746f723a3a38363137333164350404736573610505736573613106057365736132070573657361330803696e6309036465630a0d5f5f636f6e7374727563746f72071201000f5f5f737461636b5f706f696e746572090a0100072e726f64617461008e010970726f64756365727302086c616e6775616765010143000c70726f6365737365642d62790105636c616e676131362e302e35202868747470733a2f2f6769746875622e636f6d2f736f6c616e612d6c6162732f6c6c766d2d70726f6a6563742e676974203033386434373262636430623832666637363862353135636337376466623165336133393663613829002c0f7461726765745f6665617475726573022b0f6d757461626c652d676c6f62616c732b087369676e2d657874" - } - }, - "ext": "v0" - }, - 4095 - ] - ] - ] - }, - "events": [] -} \ No newline at end of file diff --git a/tests/soroban_testcases/math.rs b/tests/soroban_testcases/math.rs index 00220937b..4425244e9 100644 --- a/tests/soroban_testcases/math.rs +++ b/tests/soroban_testcases/math.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 -use crate::build_solidity; +use crate::{build_solidity, soroban_testcases::print}; use soroban_sdk::{IntoVal, Val}; #[test] @@ -25,6 +25,8 @@ fn math() { let expected: Val = 5_u64.into_val(&runtime.env); assert!(expected.shallow_eq(&res)); + + println!("inside math in soroban_test_cases"); } #[test] @@ -38,7 +40,6 @@ fn math_same_name() { return b; } } - function max(uint64 a, uint64 b, uint64 c) public returns (uint64) { if (a > b) { if (a > c) { @@ -73,3 +74,43 @@ fn math_same_name() { let expected: Val = 6_u64.into_val(&src.env); assert!(expected.shallow_eq(&res)); } + +#[test] +fn math_uint32() { + let src = build_solidity( + r#"contract math { + function max(uint32 a, uint32 b) public returns (uint32) { + if (a > b) { + return a; + } else { + return b; + } + } + }"#, + ); + + let arg1 = 10u32.into_val(&src.env); + let arg2 = 15u32.into_val(&src.env); + let res = src.invoke_contract(src.contracts.last().unwrap(), "max", vec![arg1, arg2]); + let expected: Val = 15u32.into_val(&src.env); + assert!(expected.shallow_eq(&res)); + println!("inside math in soroban_test_cases_uint32"); +} + +#[test] +fn adder_uint32() { + let src = build_solidity( + r#"contract adder { + function add(uint32 a, uint32 b) public returns (uint32) { + return a + b; + } + }"#, + ); + + let arg1 = 10u32.into_val(&src.env); + let arg2 = 15u32.into_val(&src.env); + let res = src.invoke_contract(src.contracts.last().unwrap(), "add", vec![arg1, arg2]); + let expected: Val = 25u32.into_val(&src.env); + assert!(expected.shallow_eq(&res)); + println!("inside adder uint32"); +}